@sourcegraph/amp 0.0.1775909092-g9fb21e → 0.0.1775969639-g317d38

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 +13 -11
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -2257,7 +2257,7 @@ AGENTS.md instructions are delivered dynamically in the conversation context, yo
2257
2257
 
2258
2258
  The file you create will be given to agentic coding tools (such as yourself) that operate in this repository. Make it about 20 lines long.
2259
2259
 
2260
- If there are Cursor rules (in .cursor/rules/ or .cursorrules), Claude rules (CLAUDE.md), Windsurf rules (.windsurfrules), Cline rules (.clinerules), Goose rules (.goosehints), or Copilot rules (in .github/copilot-instructions.md), make sure to include them. Also, first check if there is an existing ${R3} or ${tS0} file, and if so, update it instead of overwriting it.`;VR5=`Use \`${XU}\` only for files the user should review in the Artifacts tab, such as screenshots, videos, or data exports. Keep build artifacts, transient inspection screenshots, and other temporary scratch/debug files out of that folder. When you mention an artifact saved there, link to it; for image artifacts, prefer Markdown image format. \`.amp/out\` is not indexed by that tab.`});function AR5(J,Z,Q){let Y=Q.getExecutionProfile(J.name),X=Q.getExecutionProfile(Z.name);if(!Y||!X)return!0;if(Y.serial||X.serial)return!0;let K=Y.resourceKeys(J.input??{}),V=X.resourceKeys(Z.input??{});for(let G of K)for(let F of V)if(G.key===F.key){if(G.mode==="write"||F.mode==="write")return!0}return!1}function jR5(J,Z,Q){for(let Y of Z)if(AR5(J,Y,Q))return!0;return!1}function AV4(J,Z){if(J.length===0)return[];let Q=[],Y=[];for(let X of J){if(jR5(X,Y,Z)){if(Y.length>0)Q.push(Y),Y=[]}Y.push(X)}if(Y.length>0)Q.push(Y);return Q}class $m0{threadID;toolService;callbacks;processingMutex=new fY;runningTools=new Map;cancelledToolUses=new Set;toolMessages=new Map;toolCompletionResolvers=new Map;pendingApprovalsSubscription;writtenBlockedToolUseIds=new Set;disposed=!1;constructor(J,Z,Q){this.threadID=J;this.toolService=Z;this.callbacks=Q;this.pendingApprovalsSubscription=this.toolService.pendingApprovals$.subscribe((Y)=>{this.syncPendingApprovalsToThreadState(Y)})}syncPendingApprovalsToThreadState(J){let Z=J.filter((Y)=>Y.threadId===this.threadID);for(let Y of Z)if(!this.writtenBlockedToolUseIds.has(Y.toolUseId))this.writtenBlockedToolUseIds.add(Y.toolUseId),_.debug("Writing blocked-on-user to thread state",{name:"syncPendingApprovalsToThreadState",threadID:this.threadID,toolUseId:Y.toolUseId,toolName:Y.toolName}),this.callbacks.updateThread({type:"tool:data",toolUse:Y.toolUseId,data:{status:"blocked-on-user",reason:Y.reason,toAllow:Y.toAllow}});let Q=new Set(Z.map((Y)=>Y.toolUseId));for(let Y of this.writtenBlockedToolUseIds)if(!Q.has(Y))this.writtenBlockedToolUseIds.delete(Y)}async onResume(){await this.processingMutex.acquire();try{let J=this.callbacks.getThread(),Z=I7(J,"user");if(!Z)return;for(let Q of Z.content){if(Q.type!=="tool_result")continue;if(Q.run.status==="blocked-on-user"){let K=this.findToolUseById(Q.toolUseID);if(!K)continue;_.debug(`restoring blocked-on-user tool ${K.name} to approval queue`,{name:"onResume",threadID:this.threadID,toolUseID:Q.toolUseID}),this.toolService.restoreApproval({threadId:this.threadID,toolUseId:Q.toolUseID,toolName:K.name,args:K.input??{},reason:Q.run.reason,toAllow:Q.run.toAllow,context:J.mainThreadID?"subagent":"thread"});continue}if(!(!m8(Q.run.status)&&!this.runningTools.has(Q.toolUseID)))continue;let X=this.findToolUseById(Q.toolUseID);if(!X)continue;if(this.isDangerousToResume(X.name)){_.debug(`cancelling dangerous tool ${X.name} on resume`,{name:"onResume",threadID:this.threadID,toolUseID:Q.toolUseID});let K=lC(Q.run);this.callbacks.updateThread({type:"tool:data",toolUse:Q.toolUseID,data:{status:"cancelled",reason:"system:safety",progress:K}});continue}_.debug(`re-invoking tool ${X.name} with ID ${Q.toolUseID}`,{name:"onResume",threadID:this.threadID}),await this.invokeTool(X,Q.userInput)}}finally{this.processingMutex.release()}await this.callbacks.updateFileChanges()}async onAssistantMessageComplete(J){let Z;await this.processingMutex.acquire();try{this.cancelledToolUses.clear(),Z=this.findToolUsesNeedingInvocation(J),_.debug(`saw ${Z.length} tool uses (${Z.map((Q)=>Q.name).join(", ")})`,{name:"onAssistantMessageComplete",threadID:this.threadID})}finally{this.processingMutex.release()}if(Z.length>0)await this.executeToolsWithPlan(Z)}async userProvideInput(J,Z){await this.processingMutex.acquire();try{let Q=this.findToolUseById(J);if(Q&&I8(Q))await this.invokeTool(Q,Z)}finally{this.processingMutex.release()}}async userCancel(J){await this.cancelTool(J,"user:cancelled")}async onNewUserMessage(){this.markAllActiveToolsCancelled(),this.toolService.clearApprovalsForThread(this.threadID),await this.cancelAll("user:interrupted")}async cancelAll(J){await this.processingMutex.acquire();try{this.markAllActiveToolsCancelled(),this.toolService.clearApprovalsForThread(this.threadID),this.cancelUnstartedTools(J),await this.cancelInProgressTools(J)}finally{this.processingMutex.release()}}async findAndCancelToolRun(J,Z){let Q=this.callbacks.getThread();if(!iJ(Q,J))return;await this.cancelTool(J,"user:cancelled",Z)}async cancelToolOnly(J,Z){let Q=this.callbacks.getThread();if(!iJ(Q,J))return;let X=this.getCancelDataForToolRun(J,"user:cancelled"),K=this.toolMessages.get(J);if(K){try{K.next({type:"stop-command"})}catch(V){_.warn("Failed to send stop-command",{toolUseID:J,error:V})}K.complete(),this.toolMessages.delete(J)}_.debug(`cancelToolOnly(${J})`),await this.callbacks.handle({type:"tool:data",toolUse:J,data:X},Z)}getRunningToolIds(){return Array.from(this.runningTools.keys())}hasRunningTools(){return this.runningTools.size>0}isCancelled(J){return this.cancelledToolUses.has(J)}markCancelled(J){this.cancelledToolUses.add(J)}clearCancelled(J){this.cancelledToolUses.delete(J)}sendToolMessage(J,Z){let Q=this.toolMessages.get(J);if(Q)return Q.next(Z),!0;return!1}resolveToolCompletion(J,Z,Q){let Y=this.toolCompletionResolvers.get(J);if(Y){if(Z)Y.resolve();else Y.reject(Q??Error(`Tool failed: ${J}`));this.toolCompletionResolvers.delete(J)}}dispose(){if(this.disposed)return;this.disposed=!0,this.pendingApprovalsSubscription.unsubscribe(),this.toolService.clearApprovalsForThread(this.threadID),this.writtenBlockedToolUseIds.clear();for(let[J,Z]of this.toolCompletionResolvers)try{Z.reject(Error("Orchestrator disposed"))}finally{this.toolCompletionResolvers.delete(J)}for(let[J,Z]of this.toolMessages)try{Z.next({type:"stop-command"}),Z.complete()}catch(Q){_.warn("Failed to cleanup tool messages during disposal",{id:J,error:Q})}this.toolMessages.clear();for(let J of this.runningTools.values())J.abort.abort();this.runningTools.clear(),this.cancelledToolUses.clear()}findToolUsesNeedingInvocation(J){if(J.content.some((G)=>G.type==="tool_use"&&!I8(G)))return[];if(!(J.state?.type==="complete"||J.state?.type==="cancelled"))return[];let Y=this.callbacks.getThread(),X=I7(Y,"user"),K=I7(Y,"assistant"),V=new Set;if(X?.messageId!==void 0&&K?.messageId!==void 0&&X.messageId>K.messageId){for(let G of X.content)if(G.type==="tool_result")V.add(G.toolUseID)}return J.content.filter((G)=>G.type==="tool_use").filter((G)=>!V.has(G.id)&&!this.cancelledToolUses.has(G.id))}async executeToolsWithPlan(J){if(J.length===0)return;let Z=AV4(J,this.toolService);_.debug(`executing ${J.length} tools in ${Z.length} batch(es)`,{name:"executeToolsWithPlan",threadID:this.threadID,batches:Z.map((Q)=>Q.map((Y)=>Y.name))}),await this.executeToolBatchesSequentially(Z)}async executeToolBatchesSequentially(J){for(let Z of J){let Y=(await Promise.allSettled(Z.map((X)=>this.invokeToolAndWait(X,void 0)))).filter((X)=>X.status==="rejected");if(Y.length>0)_.warn(`${Y.length} tool(s) failed in batch`,{name:"executeToolBatchesSequentially",threadID:this.threadID,errors:Y.map((X)=>X.reason)})}}async invokeToolAndWait(J,Z){let Q=new Promise((Y,X)=>{this.toolCompletionResolvers.set(J.id,{resolve:Y,reject:X})});this.invokeTool(J,Z).catch((Y)=>{let X=this.toolCompletionResolvers.get(J.id);if(X)_.debug(`Tool invocation setup failed for ${J.id}`,{name:"invokeToolAndWait",threadID:this.threadID,error:String(Y)}),X.reject(Y),this.toolCompletionResolvers.delete(J.id)}),await Q}async invokeTool(J,Z){if(this.runningTools.has(J.id))throw Error(`(bug) tool invocation already in progress: ${J.id}`);if(!I8(J))throw Error(`(bug) tool use is incomplete: ${J.id}`);let Q=await this.callbacks.getConfig(),Y=yK4(Q.settings?.hooks,{threadID:this.threadID,toolUse:J}),{abortOp:X}=await this.callbacks.applyHookResult(Y);if(X){let F=this.toolCompletionResolvers.get(J.id);if(F)F.resolve(),this.toolCompletionResolvers.delete(J.id);return}let K=J.input;if(this.callbacks.requestPluginToolCall){let F={thread:{id:this.threadID},toolUseID:J.id,tool:J.name,input:J.input??{}},z=await this.callbacks.requestPluginToolCall(F);if(z.action==="error"){_.warn("Plugin returned error action",{tool:J.name,message:z.message,toolUseID:J.id});let q=this.toolCompletionResolvers.get(J.id);if(await this.callbacks.handle({type:"tool:data",toolUse:J.id,data:{status:"error",error:{message:`Plugin error: ${z.message}`,displayMessage:z.message}}}),q)q.resolve(),this.toolCompletionResolvers.delete(J.id);return}if(z.action==="reject-and-continue"){let q=this.toolCompletionResolvers.get(J.id);if(await this.callbacks.handle({type:"tool:data",toolUse:J.id,data:{status:"done",result:`Tool rejected by plugin: ${z.message}`,isFinal:!1}}),q)q.resolve(),this.toolCompletionResolvers.delete(J.id);return}if(z.action==="synthesize"){let q=this.toolCompletionResolvers.get(J.id);if(await this.callbacks.handle({type:"tool:data",toolUse:J.id,data:{status:"done",result:z.result.output,isFinal:!1}}),q)q.resolve(),this.toolCompletionResolvers.delete(J.id);return}if(z.action==="modify")K=z.input,await this.callbacks.handle({type:"tool:processed",toolUse:J.id,newArgs:z.input})}let V=new AbortController,G={abort:V};this.runningTools.set(J.id,G),this.callbacks.updateThread({type:"tool:data",toolUse:J.id,data:{status:"in-progress"}});try{let F=await this.callbacks.getToolRunEnvironment(J.id,V.signal),z=new k0((O)=>{this.toolMessages.set(J.id,O)}),q={...F,toolMessages:z},W=this.toolService.preprocessArgs?.(J.name,K,q);if(W)await this.callbacks.handle({type:"tool:processed",toolUse:J.id,newArgs:W});let H=W??K,U=this.toolService.normalizeToolName(J.name),D=typeof H==="object"&&H!==null?this.toolService.normalizeToolArgs(J.name,H):H,B=typeof D==="object"&&D!==null&&"__isFinal"in D&&typeof D.__isFinal==="boolean"?D.__isFinal:void 0,N=B!==void 0?Object.fromEntries(Object.entries(D).filter(([O])=>O!=="__isFinal")):D,w=this.toolService.invokeTool(U,{args:N,userInput:Z},q).pipe(bW(this.callbacks.getDisposed$()),tD(()=>{this.runningTools.delete(J.id),this.toolMessages.get(J.id)?.complete(),this.toolMessages.delete(J.id)})).subscribe({next:async(O)=>{if(this.cancelledToolUses.has(J.id))return;if(_.debug(`${J.id}, ${O.status}`,{name:"invokeTool",threadID:this.threadID}),m8(O.status)){this.runningTools.delete(J.id),w.unsubscribe();let M=this.toolCompletionResolvers.get(J.id);if(M){if(O.status==="done")M.resolve();else M.reject(Error(`Tool ${O.status}: ${J.id}`));this.toolCompletionResolvers.delete(J.id)}if(O.status==="done"&&O.trackFiles?.length)this.callbacks.trackFiles(O.trackFiles);if(O.status==="done"&&J.name.toLowerCase()===w$.toLowerCase())this.callbacks.onSkillToolComplete(J);if(Q.settings?.hooks){let A=xK4(Q.settings.hooks,{threadID:this.threadID,toolUse:J});await this.callbacks.applyPostHookResult(A,{toolUseID:J.id})}if(this.callbacks.requestPluginToolResult){let A={toolUseID:J.id,tool:J.name,input:J.input??{},status:O.status,error:O.status==="error"?O.error?.message:void 0,output:O.status==="done"&&typeof O.result==="string"?O.result:void 0};try{let j=await this.callbacks.requestPluginToolResult(A);if(j)O={...O,status:j.status,error:j.status==="error"?{message:j.error??"Plugin error"}:void 0,result:j.output}}catch(j){_.debug("Failed to request plugin tool result",{error:j})}}}await this.callbacks.updateFileChanges();let E=B!==void 0&&O.status==="done"&&O.isFinal===void 0?{...O,isFinal:B}:O;await this.callbacks.handle({type:"tool:data",toolUse:J.id,data:E},V.signal)},error:async(O)=>{let E=this.toolCompletionResolvers.get(J.id);if(E)E.reject(O),this.toolCompletionResolvers.delete(J.id);await this.callbacks.handle({type:"tool:data",toolUse:J.id,data:{status:"error",error:{message:"message"in O?O.message:String(O),displayMessage:"displayMessage"in O?O.displayMessage:void 0}}},V.signal)},complete:()=>{let O=this.toolCompletionResolvers.get(J.id);if(!O)return;let E=this.callbacks.getThread(),M=ZY(E).get(J.id)?.run;if(M&&m8(M.status))return;let A;if(this.callbacks.isDisposed())A="Worker disposed";else if(V.signal.aborted)A="Tool aborted";else if(this.cancelledToolUses.has(J.id))A="Tool cancelled";else A="Tool observable completed without terminal state";O.reject(Error(A)),this.toolCompletionResolvers.delete(J.id)}}),L=this.runningTools.get(J.id);if(L)L.subscription=w;NB(V.signal,()=>w.unsubscribe())}catch(F){this.runningTools.delete(J.id);let z=this.toolCompletionResolvers.get(J.id);if(z)z.reject(F),this.toolCompletionResolvers.delete(J.id);throw F}}async cancelTool(J,Z,Q){let Y=this.getCancelDataForToolRun(J,Z),X=this.toolMessages.get(J);if(X){try{X.next({type:"stop-command"})}catch(K){_.warn("Failed to send stop-command",{toolUseID:J,error:K})}X.complete(),this.toolMessages.delete(J)}_.debug(`cancelTool(${J}, ${Z})`),await this.callbacks.handle({type:"tool:data",toolUse:J,data:Y},Q)}getCancelDataForToolRun(J,Z){let Q=this.callbacks.getThread(),Y=ZY(Q).get(J)?.run;return{status:"cancelled",progress:Y?lC(Y):void 0,reason:Z}}markAllActiveToolsCancelled(){let J=this.callbacks.getThread(),Z=I7(J,"assistant");if(Z){let Q=I7(J,"user"),Y=new Map;if(Q){for(let X of Q.content)if(X.type==="tool_result")Y.set(X.toolUseID,X.run)}for(let X of Z.content)if(X.type==="tool_use"&&I8(X)){let K=Y.get(X.id);if(!(K?m8(K.status):!1))this.cancelledToolUses.add(X.id)}}}cancelUnstartedTools(J){let Z=this.callbacks.getThread(),Q=ZY(Z),Y=Z.messages.findLastIndex((K)=>u10(K)),X=Y===-1?Z.messages:Z.messages.slice(Y+1);for(let K of X){if(K.role!=="assistant")continue;for(let V of K.content)if(V.type==="tool_use"&&I8(V)){let G=Q.get(V.id);if(G?.run.status==="blocked-on-user"&&J==="system:disposed")continue;if(!G||G.run.status==="blocked-on-user")this.callbacks.updateThread({type:"tool:data",toolUse:V.id,data:{status:"cancelled",reason:J}})}}}async cancelInProgressTools(J){for(let[Z,Q]of this.runningTools)Q.abort.abort(),Q.subscription?.unsubscribe(),await this.cancelTool(Z,J);this.runningTools.clear()}findToolUseById(J){let Z=this.callbacks.getThread(),Q=I7(Z,"assistant");if(!Q)return;for(let Y of Q.content)if(Y.type==="tool_use"&&Y.id===J)return Y;return}isDangerousToResume(J){return J===p6||J===Bb||J===$Y||J===N9||J===zC}abortToolOp(J){let Z=this.runningTools.get(J);if(Z)Z.abort.abort(),this.runningTools.delete(J)}abortAllTools(){for(let[J,Z]of this.runningTools){let Q=this.toolMessages.get(J);if(Q){try{Q.next({type:"stop-command"}),Q.complete()}catch(Y){_.warn("Failed to send stop-command during disposal",{toolId:J,error:Y})}this.toolMessages.delete(J)}Z.abort.abort()}this.runningTools.clear()}}var jV4=Z0(()=>{E1();bV();a0();T4();EB();og0();m4()});function n$0(J){let Z=[],Q=/@((?:[^\s@\\,;]|\\.)+)/g,Y;while((Y=Q.exec(J))!==null){let X=Y[1],K=RR5(X).replace(/[.,;:!?)}\]]+$/,"");Z.push(K)}return{paths:Z}}function RR5(J){if(J.match(/^[A-Za-z]:[\\]/))return J.replace(/\\(.)/g,(Z,Q)=>{if(Q===" "||Q==="("||Q===")"||Q==="["||Q==="]"||Q==="?"||Q==="*")return Q;return Z});return J.replace(/\\(.)/g,"$1")}async function a$0(){if(!await $J.isConnected())return;let Z=await P1($J.status),Q=Z.selections?.[0],Y=o10(Q),X=Y&&Q?{line:Q.range.startLine+1,column:Q.range.startCharacter}:void 0;return{currentlyVisibleFiles:Z.visibleFiles??[],activeEditor:Z.openFile,cursorLocation:X,cursorLocationLine:void 0,selectionRange:!Y&&Q?{start:{line:Q?.range.startLine+1,column:Q?.range.startCharacter},end:{line:Q?.range.endLine+1,column:Q?.range.endCharacter}}:void 0}}var Jm0=Z0(()=>{E1();TE();AE()});async function RV4(J,{configService:Z,filesystem:Q}){let Y={sentAt:Date.now()},X=e8(J.content),{paths:K}=n$0(X),V=await P1(Z.workspaceRoot);if(!V)return{message:{role:"user",messageId:0,content:J.content,source:J.source,fileMentions:void 0,userState:void 0,agentMode:J.agentMode,meta:Y}};let G=await Z90({fileSystem:Q},K,{searchPaths:[V],shouldIncludeImages:!J.agentMode||Mb(J.agentMode)}),F;if(G?.files&&G.files.length>0){let W=new Set,H=[];for(let U of G.files){let D=T6(U.uri),B=await FQ(Q,D,V,null,W,void 0);for(let N of B){if(!H.some((w)=>w.uri===N.uri))H.push(N);W.add(N.uri)}}if(H.length>0)F=H}let z=await a$0();return{message:{role:"user",messageId:0,content:G?.imageBlocks?.length?[...J.content,...G.imageBlocks]:J.content,source:J.source,fileMentions:G,userState:{...z??pm},agentMode:J.agentMode,discoveredGuidanceFiles:F,meta:Y}}}var IV4=Z0(()=>{U4();E1();L3();x3();jH();m4();PH();Jm0()});var Xm0={};D9(Xm0,{restoreSnapshot:()=>vR5,createSnapshots:()=>yR5});import{execFile as IR5}from"node:child_process";import*as Zm0 from"node:fs";import*as Qm0 from"node:os";import*as Ym0 from"node:path";import{promisify as PR5}from"node:util";function TR5(J,Z){return Promise.race([J,new Promise((Q,Y)=>setTimeout(()=>Y(Error("Snapshot git operation timed out")),Z))])}async function tz(J,Z){let{stdout:Q}=await CR5("git",J,{cwd:Z.cwd,encoding:"utf8",env:{...process.env,...Z.env},maxBuffer:16777216});return Q.trim()}async function SR5(J,Z,Q){let Y=Ym0.join(Qm0.tmpdir(),`amp-snapshot-${Z}-${Q}-${Date.now()}`);try{let X={GIT_INDEX_FILE:Y,GIT_WORK_TREE:J};try{await tz(["read-tree","HEAD"],{cwd:J,env:X})}catch{await tz(["read-tree","--empty"],{cwd:J,env:X})}await tz(["add","-A"],{cwd:J,env:X});let K=await tz(["write-tree"],{cwd:J,env:X}),V=`refs/amp/snapshots/${Z}/${Q}`;return await tz(["update-ref","-m",`amp snapshot ${Z} ${Q}`,V,K],{cwd:J}),{treeOID:K,repoRoot:J}}finally{try{Zm0.unlinkSync(Y)}catch{}}}async function kR5(J){try{return await tz(["rev-parse","--git-dir"],{cwd:J}),!0}catch{return!1}}async function vR5(J){let Z=Ym0.join(Qm0.tmpdir(),`amp-restore-${Date.now()}`);try{let Q={GIT_INDEX_FILE:Z,GIT_WORK_TREE:J.repoRoot};try{await tz(["read-tree","HEAD"],{cwd:J.repoRoot,env:Q})}catch{await tz(["read-tree","--empty"],{cwd:J.repoRoot,env:Q})}await tz(["add","-A"],{cwd:J.repoRoot,env:Q}),await tz(["checkout","--no-overlay",J.treeOID,"--","."],{cwd:J.repoRoot,env:Q})}finally{try{Zm0.unlinkSync(Z)}catch{}}}async function yR5(J,Z,Q){let Y=[];for(let X of J){if(!pF(X))continue;let K=X.fsPath;if(!await kR5(K))continue;try{let V=await TR5(SR5(K,Z,Q),_R5);if(V)Y.push(V)}catch(V){_.debug("Auto-snapshot failed",{workspacePath:K,threadId:Z,messageId:Q,error:V})}}return Y}var CR5,_R5=1e4;var Km0=Z0(()=>{U4();a0();CR5=PR5(IR5)});function xR5(J,Z){let Q=I7(J,"assistant");if(!Q)return{updatedThread:J,uninvoked:[]};let Y=Q.content.filter((V)=>V.type==="tool_use"),X=Z.items.filter((V)=>!Z.wasInvoked(Y,V));if(X.length===0)return{updatedThread:J,uninvoked:[]};return{updatedThread:k9(J,(V)=>{let G=V.messages.findLast((F)=>F.role==="assistant");if(G&&G.role==="assistant"){for(let F of X){let z=tF();G.content.push({type:"tool_use",complete:!0,id:z,name:Z.toolName,input:Z.toToolInput(F)})}if(G.state.type==="complete"&&G.state.stopReason==="end_turn")G.state={...G.state,stopReason:"tool_use"}}V.v++}),uninvoked:X}}class rS{deps;threadID;trackFilesFromHistory(){_.debug("Tracking files from thread history",{name:"trackFilesFromHistory",threadID:this.threadID});for(let J of this.thread.messages){if(J.role==="user"&&J.fileMentions?.files)this.trackFiles(J.fileMentions.files.map((Z)=>Z.uri).filter((Z)=>Z!==void 0));if(J.role==="user"){for(let Z of J.content)if(Z.type==="tool_result"&&Z.run?.status==="done")this.trackFiles(Z.run.trackFiles??[])}}}async getConfig(J){return P1(this.deps.configService.config,J)}async isAutoSnapshotEnabled(){return(await this.getConfig()).settings["experimental.autoSnapshot"]??!1}async restoreToSnapshot(J){}setupSettingsChangeHandlers(){this.setupPermissionsChangeHandler()}setupEphemeralErrorLogging(){this.ephemeralError.pipe(bW(this.disposed$)).subscribe((J)=>{if(J)_.error("ephemeral error",{error:J})})}setupPermissionsChangeHandler(){this.deps.configService.config.pipe(w1((J)=>({permissions:YC(J.settings?.permissions),dangerouslyAllowAll:J.settings?.dangerouslyAllowAll??!1})),g4((J,Z)=>J.dangerouslyAllowAll===Z.dangerouslyAllowAll&&J.permissions===Z.permissions),dx1(1),bW(this.disposed$)).subscribe(()=>{this.reevaluateBlockedTools()})}reevaluateBlockedTools(){if(this.isDisposed)return;for(let J=this.thread.messages.length-1;J>=0;J--){let Z=this.thread.messages[J];if(!Z||Z.role!=="user")continue;let Q=!1;for(let Y of Z.content)if(Y.type==="tool_result"&&Y.run?.status==="blocked-on-user"&&Y.toolUseID)Q=!0,this.checkAndApproveBlockedTool(Y.toolUseID);if(!Q)break}}async checkAndApproveBlockedTool(J){try{let Z=iJ(this.thread,J);if(!Z){_.warn("Tool use block not found for blocked tool",{toolUseID:J});return}let Q=await a40(Z.name,Z.input??{},{configService:this.deps.configService},this.thread.mainThreadID?"subagent":"thread",this.threadID,J);if(Q.permitted)_.info("Auto-approving previously blocked tool due to permission change",{toolName:Z.name,toolUseID:J,threadID:this.threadID}),this.handle({type:"user:tool-input",toolUse:J,value:{accepted:!0}});else _.debug("Tool remains blocked after permission change",{toolName:Z.name,toolUseID:J,reason:Q.reason})}catch(Z){_.warn("Failed to re-evaluate blocked tool",{error:Z,toolUseID:J})}}ops={tools:{},toolMessages:{},inference:null,titleGeneration:null};_state=new V4("initial");state=this._state.pipe(g4(),m6({shouldCountRefs:!0}));handleMutex=new fY;ephemeralError=new V4(void 0);ephemeralErrorRetryAttempt=0;retryCountdownSeconds=new V4(void 0);retryTimer=null;retrySession=0;_inferenceState=new V4("idle");_turnStartTime=new V4(void 0);_turnElapsedMs=new V4(void 0);fileChanges=new V4({files:[]});get inferenceState(){return this._inferenceState.getValue()}toolCallUpdates=new D4;trackedFiles=new QJ;discoveredGuidanceFileURIs=new Set;fs;cachedFileChanges=[];disposed$=new D4;isDisposed=!1;shouldContinueAfterRejection=!1;_pendingSkills=new V4([]);handoffState=new V4(void 0);pendingSkills=this._pendingSkills.pipe(g4(),m6({shouldCountRefs:!0}));_awaitingSkillInvocation=new V4([]);toolOrchestrator;currentAgentSpan=null;currentSpan=null;traceStore;constructor(J,Z){this.deps=J;this.threadID=Z;this.fs=nS({fileChangeTrackerStorage:this.deps.fileChangeTrackerStorage},this.deps.osFileSystem,Z),this.traceStore={startTrace:(Q)=>{this.updateThread({type:"trace:start",span:Q})},recordTraceEvent:(Q,Y)=>{this.updateThread({type:"trace:event",span:Q,event:Y})},recordTraceAttributes:(Q,Y)=>{this.updateThread({type:"trace:attributes",span:Q,attributes:Y})},endTrace:(Q)=>{this.updateThread({type:"trace:end",span:Q})}},this.toolOrchestrator=new $m0(Z,J.toolService,this.createOrchestratorCallbacks())}createTracer(J){return ET0(this.traceStore,J)}getPluginTracer(){let J=this.currentSpan?.id??this.currentAgentSpan?.span;if(!J)return;return this.createTracer(J)}createOrchestratorCallbacks(){return{getThread:()=>this.thread,updateThread:(J)=>this.updateThread(J),handle:(J,Z)=>this.handle(J,Z),getToolRunEnvironment:(J,Z)=>this.getToolRunEnvironment(J,Z),getHooks:async()=>(await this.getConfig()).settings?.hooks,getConfig:()=>this.getConfig(),updateFileChanges:()=>this.updateFileChanges(),trackFiles:(J)=>this.trackFiles(J),isDisposed:()=>this.isDisposed,getDisposed$:()=>this.disposed$,onSkillToolComplete:(J)=>this.onSkillToolComplete(J),applyHookResult:(J)=>Promise.resolve(aS(this,J)),applyPostHookResult:(J,Z)=>Promise.resolve(aS(this,J,Z)),requestPluginToolCall:this.deps.pluginService?(J)=>this.deps.pluginService.event.toolCall(J,this.getPluginTracer()):void 0,requestPluginToolResult:this.deps.pluginService?(J)=>this.deps.pluginService.event.toolResult(J,this.getPluginTracer()):void 0}}async getToolRunEnvironment(J,Z){let Q=await this.getWorkspaceRoot(Z),Y=DC(this.thread),X=iJ(this.thread,J);return{...this.deps,dir:Q,tool:X?.name??"",thread:this.thread,config:await this.getConfig(Z),trackedFiles:new QJ(this.trackedFiles),filesystem:this.fs.trackedFileSystem(J),fileChangeTracker:this.fs.tracker,getAllTrackedChanges:this.getAllTrackedChanges.bind(this),toolUseID:J,todos:Y,toolMessages:new k0(()=>{}),threadEnvironment:this.thread.env?.initial??await this.deps.getThreadEnvironment(),handleThreadDelta:this.handle.bind(this),agentMode:await this.getSelectedAgentMode(),discoveredGuidanceFileURIs:this.discoveredGuidanceFileURIs,dtwHandoffService:void 0}}onSkillToolComplete(J){let Z=J.input;this.thread=k9(this.thread,(Q)=>{if(!Q.activatedSkills)Q.activatedSkills=[];if(!Q.activatedSkills.some((Y)=>Y.name===Z.name))Q.activatedSkills.push({name:Z.name,arguments:Z.arguments})})}status=this.state.pipe(_4((J)=>J==="active"?F5(this._inferenceState.pipe(g4()),this.fileChanges.pipe(g4()),this.ephemeralError,this.handoffState.pipe(g4()),this.retryCountdownSeconds.pipe(g4()),this._turnStartTime.pipe(g4()),this._turnElapsedMs.pipe(g4()),this.toolCallUpdates.pipe(z5(void 0))).pipe(w1(([Z,Q,Y,X,K,V,G])=>({state:J,inferenceState:Z,fileChanges:Q,ephemeralError:Y?{message:Y.message,stack:"stack"in Y?Y.stack:void 0,error:"error"in Y&&Y.error&&typeof Y.error==="object"&&"error"in Y.error?Y.error.error:void 0,retryCountdownSeconds:K}:void 0,handoff:X,turnStartTime:V,turnElapsedMs:G})),bW(this.disposed$)):k0.of({state:J})),m6({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(J){if(!this.threadReadWriter)throw Error(`thread read-writer not initialized for ThreadWorker: ${this.threadID}`);this.threadReadWriter.write(J),this.__testing__setThread(J)}updateThread(J){if(!this.threadReadWriter)throw Error(`thread read-writer not initialized for ThreadWorker: ${this.threadID}`);this.threadReadWriter.update(v04(J,new Date)),this.__testing__setThread(this.threadReadWriter.read())}async acquireThread(){if(!this.threadReadWriter)this.threadReadWriter=await this.deps.threadService.exclusiveSyncReadWriter(this.threadID),this._state.next("active")}__testing__setThread(J){}__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");if(await this.acquireThread(),!await this.isAutoSnapshotEnabled())await this.restoreFileChangesFromBackups();let J=this.thread.messages.at(-1);if(J?.role==="assistant"&&J.state.type==="streaming")this.updateThread({type:"thread:truncate",fromIndex:this.thread.messages.length-1});if(this.trackFilesFromHistory(),this.triggerTitleGeneration(),!this.shouldResumeFromLastMessage(J))return;await this.toolOrchestrator.onResume(),this.setupSettingsChangeHandlers(),this.setupEphemeralErrorLogging(),this.replayLastCompleteMessage()}resumed=!1;shouldResumeFromLastMessage(J){if(of1(J)||sf1(J)&&!this.shouldContinueAfterRejection||u10(J))return this._inferenceState.next("cancelled"),!1;return!0}replayLastCompleteMessage(){let J=this.thread.messages.findLastIndex((Q)=>Q.role==="user"?tf1(Q):Q.role==="assistant"&&Q.state.type==="complete");if(J===-1){if(this.thread.messages.length!==0)throw Error(`(bug) invalid thread: ${this.threadID}`);return}let Z=this.thread.messages[J];switch(Z.role){case"user":if(!Z.interrupted)this.onThreadDelta({type:"user:message",message:Z});break;case"assistant":this.onThreadDelta({type:"assistant:message",message:Z});break}}async handle(J,Z){let Q=J.type==="user:message"&&J.index!==void 0?J.index:void 0;await this.handleMutex.acquire();try{await this.innerHandle(J,Z)}finally{this.handleMutex.release()}if(Q!==void 0)await this.performMessageEditCleanup(Q)}async innerHandle(J,Z){if(this.isDisposed){_.debug(`Skipping ${J.type} - worker disposed.`,{name:"handle queue",threadID:this.threadID});return}if(Z?.aborted){_.debug(`Skipping ${J.type} - signal aborted.`,{name:"handle queue",threadID:this.threadID});return}if(await this.resume(),this.handleCalled=!0,await this.acquireThread(),J.type==="pending-skills"){let X=this._pendingSkills.getValue();this._pendingSkills.next([...X,...J.skills]),_.info("Pending skills set for injection",{threadID:this.threadID,skillNames:J.skills.map((K)=>K.name)});return}let Q=J,Y=[];if(J.type==="user:message"){let X=await RV4(J.message,{configService:this.deps.configService,filesystem:this.fs.fileSystem}),V=(await this.getConfig(Z)).settings["experimental.autoSnapshot"]??!1,G=[];if(V){let F=this.thread.nextMessageId??0,z=await this.getWorkspaceRoot(Z??new AbortController().signal),{createSnapshots:q}=await Promise.resolve().then(() => (Km0(),Xm0));G=await q(z?[z]:[],this.threadID,F)}if(Y=this._pendingSkills.getValue(),Y.length>0)_.info("Pending skills will be injected as info message",{threadID:this.threadID,skillNames:Y.map((F)=>F.name)}),this._pendingSkills.next([]);Q=k9(J,(F)=>{if(F.message=Z5(X.message),G.length>0){if(!F.message.userState)F.message.userState=Z5({currentlyVisibleFiles:[]});F.message.userState.snapshotOIDs=Z5(G)}Z?.throwIfAborted()})}if(Q.type==="assistant:message"||Q.type==="assistant:message-update")Q=this.addNormalizedInputToToolUses(Q);try{if(this.ephemeralError.getValue()!==void 0)this.ephemeralError.next(void 0);let X=this.thread;if(this.updateThread(Q),this.onThreadDelta(Q,X),Y.length>0)await this.injectPendingSkills(Y,Z)}catch(X){if(!V7(X))_.error("Ephemeral error during handle processing",X,{name:"ThreadWorker",threadID:this.threadID}),this.ephemeralError.next(X instanceof Error?X:Error(String(X)));else _.debug(`AbortError caught during handle processing for ${Q.type}.`,{name:"handle queue",threadID:this.threadID})}}handleCalled=!1;addNormalizedInputToToolUses(J){let Z=this.thread.agentMode;if(!J.message.content.some((Y)=>Y.type==="tool_use"))return J;return k9(J,(Y)=>{for(let X of Y.message.content)if(X.type==="tool_use"){if(!X.name){_.warn("Skipping tool_use normalization due to missing name",{threadID:this.threadID});continue}let K=this.deps.toolService.normalizeToolName(X.name);if(K!==X.name)X.normalizedName=K;if(X.input&&typeof X.input==="object"){let G=this.deps.toolService.normalizeToolArgs(X.name,X.input,Z);if(JSON.stringify(G)!==JSON.stringify(X.input))X.normalizedInput=G}if((K!==X.name?K:X.name)===zC&&!X.metadata?.handoffThreadID)X.metadata={...X.metadata,handoffThreadID:g8()}}})}onThreadDelta(J,Z){switch(J.type){case"user:message":{if(this.resetRetryAttempts(),this._turnStartTime.next(Date.now()),this._turnElapsedMs.next(void 0),J.index!==void 0&&Z){let X=Z.messages[J.index];if(X?.role==="user"&&X.userState?.snapshotOIDs&&X.userState.snapshotOIDs.length>0)this.restoreToSnapshot([...X.userState.snapshotOIDs]).catch((K)=>{_.error("Failed to restore edit snapshots",K,{name:"ThreadWorker",threadID:this.threadID})})}if(J.index!==void 0)this.trackedFiles.clear(),this.thread.messages.forEach((X)=>{if(X.role==="user"){for(let K of X.content)if(K.type==="tool_result"&&K.run?.status==="done"&&K.run.trackFiles)this.trackFiles(K.run.trackFiles);if(X.fileMentions?.files)this.trackFiles(X.fileMentions.files.map((K)=>K.uri).filter((K)=>K!==void 0))}});else this.trackFiles(J.message.fileMentions?.files?.map((X)=>X.uri).filter((X)=>X!==void 0)??[]);let Q=this.thread.messages.at(-1)?.messageId??0,Y=e8(J.message.content);this.startAgentSpan(Q),this.runInferenceAndUpdateThread({agentStart:{messageId:Q,messageText:Y}});break}case"user:message-queue:dequeue":{let Q=this.thread.messages.at(-1);if(!Q)break;if(Q.role!=="user")break;this._turnStartTime.next(Date.now()),this._turnElapsedMs.next(void 0),this.trackFiles(Q.fileMentions?.files?.map((K)=>K.uri).filter((K)=>K!==void 0)??[]);let Y=Q.messageId??0,X=e8(Q.content);this.startAgentSpan(Y),this.runInferenceAndUpdateThread({agentStart:{messageId:Y,messageText:X}});break}case"user:tool-input":{this.toolOrchestrator.userProvideInput(J.toolUse,J.value).catch((Q)=>{_.error("userProvideInput failed",{name:"ThreadWorker.handleDelta",threadID:this.threadID,toolUse:J.toolUse,error:Q instanceof Error?Q.message:String(Q)})});break}case"tool:data":{if(this.toolOrchestrator.isCancelled(J.toolUse)){let Y=ZY(this.thread).get(J.toolUse)?.run,X=Y?lC(Y):void 0;this.updateThread({type:"tool:data",toolUse:J.toolUse,data:{status:"cancelled",reason:"user:interrupted",progress:X}});return}let Q=iJ(this.thread,J.toolUse);if(J.data.status==="done"&&Q?.name===eQ){let Y=J.data.result;if("task"in Y&&Y.nextTask){let X=Y7(this.thread),K=this.deps.internalHooks?.onTaskCompleted?.({thread:this.thread,completedTask:Y.task,nextTask:Y.nextTask,usage:X?{totalInputTokens:X.totalInputTokens,maxInputTokens:X.maxInputTokens}:void 0});if(K)aS(this,K)}}if(m8(J.data.status))this.toolOrchestrator.clearCancelled(J.toolUse),this.toolOrchestrator.resolveToolCompletion(J.toolUse,J.data.status==="done",Error(`Tool ${J.data.status}: ${J.toolUse}`));if(Q){let Y=fR5(this.thread,J.toolUse,this.shouldContinueAfterRejection);_.debug(`updated tool_result${Y?" and running inference because all tools completed":""}`,{name:`handleThreadDelta(${J.type}, ${J.toolUse}, ${J.data.status})`,threadID:this.threadID});let X=this.shouldContinueAfterRejection||this._inferenceState.getValue()!=="cancelled";if(Y&&X)this.runInferenceAndUpdateThread()}this.toolCallUpdates.next();break}case"assistant:message":{if(J.message.state.type==="complete"&&J.message.state.stopReason==="tool_use"){let Y=this.thread.messages.at(-1);(this.currentAgentSpan?this.createTracer(this.currentAgentSpan.span):Hz).startActiveSpan("tools",{context:{messageId:Y?.messageId}},async()=>{await this.toolOrchestrator.onAssistantMessageComplete(J.message)}).catch((K)=>{_.error("onAssistantMessageComplete failed",{name:"ThreadWorker.handleDelta",threadID:this.threadID,messageState:J.message.state.type,error:K instanceof Error?K.message:String(K)})})}break}case"assistant:message-update":break;case"user:message-queue:enqueue":{let Q=this._inferenceState.getValue();if(Ob0(this.thread,Q)!=="tool-running"){if(Q==="cancelled"){this.handle({type:"user:message-queue:dequeue"});break}else if(Q==="idle"){let X=this.thread.messages.at(-1);if(X?.role==="assistant"){if(X.state.type==="cancelled"||X.state.type==="error"){this.handle({type:"user:message-queue:dequeue"});break}if(X.state.type==="complete"&&X.state.stopReason!=="tool_use"){this.handle({type:"user:message-queue:dequeue"});break}}else if(X?.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 Q=this.currentAgentSpan.messageId,Y=this.createTracer(this.currentAgentSpan.span);this.stopAgentSpan(this.currentAgentSpan.span),this.deps.pluginService.event.agentEnd({message:this.getMessageText(Q),id:Q,status:"interrupted",messages:q30(this.getMessagesSince(Q))},Y).then((X)=>this.handleAgentEndResult(X)).catch((X)=>_.debug("Failed to emit agent.end",{error:X}))}break}case"thread:truncate":{if(this.toolOrchestrator.cancelAll("system:edited").catch((Q)=>{_.error("Failed to cancel tools on truncate",Q,{name:"ThreadWorker",threadID:this.threadID})}),Z){let Q=Z.messages[J.fromIndex];if(Q?.role==="user"&&Q.userState?.snapshotOIDs&&Q.userState.snapshotOIDs.length>0)for(let Y of Q.userState.snapshotOIDs)Promise.resolve().then(() => (Km0(),Xm0)).then(({restoreSnapshot:X})=>X(Y)).catch((X)=>{_.error("Failed to restore edit snapshots on truncate",X,{name:"ThreadWorker",threadID:this.threadID})});else this.cleanupFileChanges(J.fromIndex).catch((Y)=>{_.error("Failed to cleanup file changes on truncate",Y,{name:"ThreadWorker",threadID:this.threadID})})}break}case"inference:completed":{this.resetRetryAttempts();let Q=J.model?.includes("gpt-5")||J.model?.includes("codex"),Y=!J.usage||J.usage.totalInputTokens===0||J.usage.outputTokens===0;if(Q&&Y)_.warn("[thread-worker] Missing token counts in deep mode inference",{threadID:this.threadID,model:J.model,hasUsage:!!J.usage,inputTokens:J.usage?.inputTokens,outputTokens:J.usage?.outputTokens,totalInputTokens:J.usage?.totalInputTokens,cacheReadInputTokens:J.usage?.cacheReadInputTokens,cacheCreationInputTokens:J.usage?.cacheCreationInputTokens});let X=I7(this.thread,"assistant");if(X&&X.state.type==="complete"&&X.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 K=I7(this.thread,"assistant"),V=K?.state.type==="complete"&&K.state.stopReason==="tool_use";if(K&&V){let F=this.currentAgentSpan?this.createTracer(this.currentAgentSpan.span):Hz,z=K.messageId;F.startActiveSpan("tools",{context:{messageId:z}},async()=>{await this.toolOrchestrator.onAssistantMessageComplete(K)}).catch((q)=>{_.error("onAssistantMessageComplete failed after inference",{name:"ThreadWorker.handleDelta",threadID:this.threadID,messageState:K.state.type,error:q instanceof Error?q.message:String(q)})})}if(K&&K.state.type==="complete"&&K.state.stopReason==="end_turn"){let F=this._turnStartTime.getValue();if(F!==void 0){let z=Date.now()-F;this._turnElapsedMs.next(z),this.thread=k9(this.thread,(q)=>{let W=q.messages.findLast((H)=>H.role==="assistant");if(W&&W.role==="assistant")W.turnElapsedMs=z;q.v++})}if(this._turnStartTime.next(void 0),this.thread.queuedMessages&&this.thread.queuedMessages.length>0)this.handle({type:"user:message-queue:dequeue"});else{aS(this,fK4(this.deps.internalHooks?.onAssistantTurnEnd,{thread:this.thread}));let z=Y7(this.thread);if(z&&this.deps.internalHooks?.onInferenceCompleted){let q=this.deps.internalHooks.onInferenceCompleted({thread:this.thread,usage:{totalInputTokens:z.totalInputTokens,maxInputTokens:z.maxInputTokens},isIdle:!0});aS(this,q)}if(this.currentAgentSpan&&this.currentAgentSpan.messageId!==void 0){let q=this.currentAgentSpan.messageId,W=this.createTracer(this.currentAgentSpan.span);this.stopAgentSpan(this.currentAgentSpan.span),this.deps.pluginService.event.agentEnd({message:this.getMessageText(q),id:q,status:"done",messages:q30(this.getMessagesSince(q))},W).then((H)=>this.handleAgentEndResult(H)).catch((H)=>_.debug("Failed to emit agent.end",{error:H}))}}}break}}}getMessageText(J){let Z=this.thread.messages.find((Q)=>Q.messageId===J);if(Z)return e8(Z.content);return""}getMessagesSince(J){let Z=this.thread.messages.findIndex((Q)=>Q.messageId===J);if(Z===-1)return[];return this.thread.messages.slice(Z)}startAgentSpan(J){let Z=OT0();this.currentAgentSpan={span:Z,messageId:J},this.updateThread({type:"trace:start",span:{name:"agent",id:Z,startTime:new Date().toISOString(),context:{messageId:J}}})}stopAgentSpan(J){if(this.updateThread({type:"trace:end",span:{name:"agent",id:J,endTime:new Date().toISOString()}}),this.currentAgentSpan?.span===J)this.currentAgentSpan=null}handleAgentEndResult(J){if(J.action!=="continue"||!J.userMessage)return;this.handle({type:"user:message",message:{content:[{type:"text",text:J.userMessage}]}}).catch((Z)=>{_.debug("Failed to handle plugin agent.end continue",{error:Z})})}triggerTitleGeneration(){if(this.thread.mainThreadID!==void 0||this.thread.title)return;this.ops.titleGeneration?.abort(),this.ops.titleGeneration=new AbortController;let J=this.ops.titleGeneration.signal;this.getConfig(J).then((Z)=>{if(J.aborted)return;let Q=Z.settings?.["agent.skipTitleGenerationIfMessageContains"],Y=Array.isArray(Q)?Q.filter((K)=>typeof K==="string"):[],X=this.thread.messages.find((K)=>{if(K.role!=="user")return!1;let V=e8(K.content);if(!V)return!1;if(Y.length===0)return!0;return!Y.some((G)=>V.includes(G))});if(_.debug("Checking for message to generate title for",{skipPatterns:Y,rawSkipPatterns:Q,hasFirstEligibleMessage:X!==void 0,firstEligibleMessageId:X?.messageId}),X)this.deps.generateThreadTitle(X,this.thread.id,this.deps.configService,J).then(({title:K,usage:V})=>{if(J.aborted||this.isDisposed)return;if(K!==void 0&&this.thread.title!==K)this.updateThread({type:"title",value:K,usage:V})}).catch((K)=>{if(!V7(K))_.error("generateThreadTitle error",K,{name:"ThreadWorker",threadID:this.threadID});else _.info("Title generation aborted",{firstEligibleMessageId:X?.messageId,threadID:this.threadID})})}).catch((Z)=>{if(!V7(Z))_.error("ThreadWorker title generation config error",Z);else _.info("Title generation aborted in outer catch",{threadID:this.threadID})})}async getWorkspaceRoot(J){let Z=await P1(this.deps.configService.workspaceRoot,J);if(Z)return Z;let Q=this.thread.env?.initial?.trees?.find((Y)=>Y.uri!==void 0)?.uri;return Q?r8(Q):null}async runInferenceAndUpdateThread(J){if(J?.agentStart){let{messageId:Z,messageText:Q}=J.agentStart;try{let Y=await this.deps.pluginService.event.agentStart({message:Q,id:Z},this.currentAgentSpan?this.createTracer(this.currentAgentSpan.span):void 0,{threadID:this.threadID});if(Y.message)this.updateThread({type:"user:message:append-content",messageId:Z,content:[{type:"text",text:Y.message.content}]})}catch(Y){_.debug("Failed to emit agent.start",{error:Y})}}return this.doRunInferenceSetup()}async doRunInferenceSetup(){if(_.debug("runInferenceAndUpdateThread: begin",{threadID:this.threadID,inferenceState:this._inferenceState.getValue(),messageCount:this.thread.messages.length}),this.ops.inference?.abort(),this.ops.inference=null,this._inferenceState.getValue()==="cancelled")this._inferenceState.next("idle");let J=new AbortController;this.ops.inference=J;let Z=this.currentAgentSpan?.span;await this.toolOrchestrator.onNewUserMessage(),await(this.currentAgentSpan?this.createTracer(this.currentAgentSpan.span):Hz).startActiveSpan("inference",{context:{messageId:this.currentAgentSpan?.messageId}},()=>this.doRunInferenceAndUpdateThread(J,Z))}async doRunInferenceAndUpdateThread(J,Z){try{await this.doRunInferenceAndUpdateThreadInner(J,Z)}catch(Q){if(V7(Q)||sI0(Q))return;throw Q}}async doRunInferenceAndUpdateThreadInner(J,Z){let Q=Y7(this.thread);if(Q&&Q.totalInputTokens>=Q.maxInputTokens){let B=Error("Context limit reached");this.ephemeralError.next(B);return}let Y=this.thread.messages.at(-1);if(this.thread.mainThreadID===void 0&&Y?.role==="user"&&this.thread.messages.filter((B)=>B.role==="user").length===1){if(this.deps.getThreadEnvironment)this.deps.getThreadEnvironment().then(async(B)=>{this.updateThread({type:"environment",env:{initial:{...this.thread.env?.initial,...B}}})}).catch((B)=>{_.error("Failed to initialize thread environment",B,{threadID:this.threadID})})}this.triggerTitleGeneration();let K=await this.getConfig(),{model:V,agentMode:G}=FJ(K.settings,this.thread),F=this.thread.messages.at(-1)?.messageId;_.debug("runInferenceAndUpdateThread: starting inference",{threadID:this.threadID,lastUserMessageId:F,selectedModel:V,agentMode:G});let z=this.deps.getServerStatus?await P1(this.deps.getServerStatus().pipe(h5((B)=>B!=="pending")),J.signal):void 0,q=z&&_6(z)?z.user.email:void 0;if(!EE(G,q))throw Error(`Agent mode '${G}' is only available for internal users`);let W={toolService:this.deps.toolService,configService:this.deps.configService,skillService:this.deps.skillService,getThreadEnvironment:this.deps.getThreadEnvironment,filesystem:this.fs.fileSystem,threadService:this.deps.threadService,serverStatus:z},H,U=0,D=Date.now();try{let[B,N,w]=V.match(/(.*?)\/(.*)/)??[],L=OK4(N??"",w??""),{systemPrompt:O,tools:E}=await sz(W,this.thread,{enableTaskList:!1,enableTask:!0,enableOracle:!0,enableChart:!1},{model:w??"",provider:N??"",agentMode:G??"smart"},J.signal),M=LK4(V,K.settings,G),A=L.stream({model:w??"",thread:this.thread,systemPrompt:O,tools:E,configService:this.deps.configService,serverStatus:z,signal:J.signal,reasoningEffort:M});this._inferenceState.next("running"),D=Date.now(),_.debug("ThreadWorker inference stream started",{threadID:this.threadID,lastUserMessageId:F,selectedModel:V,agentMode:G});for await(let j of A)U++,H=j,await this.handle({type:"assistant:message-update",message:j});if(_.debug("ThreadWorker inference stream finished",{threadID:this.threadID,streamEventCount:U,durationMs:Date.now()-D,lastMessageState:H?.state.type,lastMessageId:H?.messageId}),H){let j=H.state.type==="streaming",I=H.content.some((T)=>T.type==="tool_use"&&T.complete&&Object.keys(T.input??{}).length===0);if(j||I)_.warn("Stream ended with incomplete message",{name:"ThreadWorker.runInference",threadID:this.threadID,streamEventCount:U,durationMs:Date.now()-D,messageState:H.state.type,stopReason:H.state.type==="complete"?H.state.stopReason:void 0,contentBlocks:H.content.map((T)=>({type:T.type,...T.type==="tool_use"?{name:T.name,complete:T.complete,inputKeys:Object.keys(T.input??{})}:{},...T.type==="text"?{textLength:T.text.length}:{}}))})}await this.handle({type:"inference:completed",model:H?.usage?.model??V,usage:H?.usage})}catch(B){if(_.debug("ThreadWorker inference stream error",{threadID:this.threadID,error:B instanceof Error?B.message:String(B),errorName:B instanceof Error?B.name:void 0,streamEventCount:U,durationMs:Date.now()-D,lastMessageState:H?.state.type,lastMessageId:H?.messageId}),!(V7(B)||sI0(B))){let N=B instanceof Error?B:Error(String(B));if(pz({message:N.message})){this.ephemeralError.next(N);return}let w="status"in N&&typeof N.status==="number"?N.status:void 0;if(B20({message:N.message,status:w})){let L=this.getRetryDelaySeconds();if(L!==void 0)this.startRetryCountdown(L)}this.ephemeralError.next(N)}if(H&&H.messageId){let N=await this.deps.pluginService.event.agentEnd({message:e8(H.content),id:H.messageId,status:"error",messages:q30(this.getMessagesSince(H.messageId))},Z?this.createTracer(Z):void 0);if(Z)this.stopAgentSpan(Z);this.handleAgentEndResult(N)}else if(Z)this.stopAgentSpan(Z);return}finally{if(this.ops.inference===J)this.ops.inference=null,this._inferenceState.next("idle")}}async findAndCancelToolRun(J,Z){this.cancelInference(),await this.toolOrchestrator.findAndCancelToolRun(J,Z)}async cancelToolOnly(J,Z){await this.toolOrchestrator.cancelToolOnly(J,Z)}invokeBashTool(J,Z,Q){return new k0((Y)=>{let X,K,V,F=((q)=>{return NB(q,()=>{if(_.warn("Manual bash abort -> unsubscribe",{threadID:this.threadID}),V?.unsubscribe(),K?.unsubscribe(),Y?.complete(),X)this.handleManualBashInvocation(J,{status:"cancelled",progress:lC(X)},Q)})})(Z);return(async()=>{try{if(Z.aborted){Y.error(Error("Operation was aborted"));return}let q=await this.getWorkspaceRoot(Z),W=await this.getConfig(Z);if(this.isDisposed){Y.complete();return}let H={...this.deps,dir:q,tool:p6,thread:this.thread,config:W,trackedFiles:new QJ(this.trackedFiles),filesystem:Xp1(this.fs.fileSystem),fileChangeTracker:this.fs.tracker,getAllTrackedChanges:this.getAllTrackedChanges.bind(this),toolUseID:tF(),todos:[],threadEnvironment:this.thread.env?.initial??await this.deps.getThreadEnvironment(),handleThreadDelta:this.handle.bind(this),discoveredGuidanceFileURIs:this.discoveredGuidanceFileURIs,userInitiated:!0};K=this.deps.toolService.invokeTool(p6,{args:J,userInput:{accepted:!0}},H).subscribe({next:(U)=>{X=U,Y.next(U)},error:(U)=>{Y.error(U)},complete:()=>{if(X)this.handleManualBashInvocation(J,X,Q);Y.complete()}}),V=this.disposed$.subscribe(()=>{F(),K?.unsubscribe(),Y?.complete()})}catch(q){Y.error(q)}})(),()=>{F(),K?.unsubscribe(),V?.unsubscribe()}})}async handleManualBashInvocation(J,Z,Q){await this.handle({type:"info:manual-bash-invocation",args:J,toolRun:Z,hidden:Q})}async cleanupThreadBackups(J){try{await this.fs.tracker.cleanupBackups(),_.debug(`Cleaned up backup files for thread ${J}`,{threadID:J})}catch(Z){_.error("Error cleaning up thread backups",Z,{threadID:J})}}async cancel(){_.debug("cancel: aborting inference operation and tools"),this.cancelInference(),await this.toolOrchestrator.cancelAll("user:cancelled"),await this.handle({type:"cancelled"},void 0)}cancelInference(){if(this.ops.inference)this.ops.inference.abort(Error(rI0.USER_CANCELLED)),this.ops.inference=null;this._inferenceState.next("cancelled"),this._turnStartTime.next(void 0),this._turnElapsedMs.next(void 0)}static BASE_RETRY_SECONDS=5;static MAX_RETRY_SECONDS=60;static MAX_AUTO_RETRIES=5;getRetryDelaySeconds(){if(this.ephemeralErrorRetryAttempt>=rS.MAX_AUTO_RETRIES)return;let J=rS.BASE_RETRY_SECONDS*2**this.ephemeralErrorRetryAttempt;return Math.min(J,rS.MAX_RETRY_SECONDS)}async retry(){if(_.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 J=this.thread.messages.at(-1);if(J?.role==="assistant"&&(J.state.type!=="complete"||J.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(J){this.clearRetryCountdown();let Z=this.retrySession,Q=Date.now()+J*1000;this.retryCountdownSeconds.next(J),this.retryTimer=setInterval(()=>{if(Z!==this.retrySession)return;let Y=Math.max(0,Math.ceil((Q-Date.now())/1000));if(Y<=0)this.clearRetryCountdown(),this.retry().catch((X)=>{_.error("Auto-retry failed",{error:X})});else this.retryCountdownSeconds.next(Y)},1000)}addPendingSkill(J){_.debug("addPendingSkill",{threadID:this.threadID,skillName:J.name});let Z=this._pendingSkills.getValue();if(!Z.some((Q)=>Q.name===J.name))this._pendingSkills.next([...Z,J])}removePendingSkill(J){_.debug("removePendingSkill",{threadID:this.threadID,skillName:J});let Z=this._pendingSkills.getValue();this._pendingSkills.next(Z.filter((Q)=>Q.name!==J))}clearPendingSkills(){_.debug("clearPendingSkills",{threadID:this.threadID}),this._pendingSkills.next([])}getPendingSkills(){return this._pendingSkills.getValue()}setTestEphemeralError(J){this.ephemeralError.next(J)}trackFiles(J){for(let Z of J)this.trackedFiles.add(Z)}async restoreFileChangesFromBackups(){try{let J=await this.fs.tracker.restoreFromBackups();_.debug(`Restored ${J.totalBackups} backup files from disk`),await this.updateFileChanges()}catch(J){_.error("Error restoring file changes",J,{threadID:this.threadID})}}async revertFileChanges(J){await this.fs.tracker.revertAll(J),await this.updateFileChanges()}async getAllTrackedChanges(){return this.fs.tracker.getAllRecords()}async cleanupForkThreads(J=this.thread.messages.length){await this.acquireThread(),this.updateThread({type:"thread:truncate",fromIndex:J})}async getToolUsesToRevert(J=this.thread.messages.length){let Z=new Set;this.thread.messages.slice(0,J).forEach((X)=>{if(X.role==="user"){for(let K of X.content)if(K.type==="tool_result")Z.add(K.toolUseID)}else for(let K of X.content)if(K.type==="tool_use")Z.add(K.id)});let Q=new Set,Y=await this.fs.tracker.getAllRecords();for(let[X]of Y.entries())if(!Z.has(X))Q.add(X);return Q}async getFilesAffectedByTruncation(J){let Z=await this.getToolUsesToRevert(J);return Z.size>0?this.fs.tracker.getFilesForToolUses(Z):[]}async cleanupFileChanges(J=this.thread.messages.length){let Z=await this.getToolUsesToRevert(J);if(Z.size===0)return;await this.fs.tracker.revertChanges(Z),await this.updateFileChanges()}async performMessageEditCleanup(J){if(await this.toolOrchestrator.cancelAll("system:edited"),!await this.isAutoSnapshotEnabled())await this.cleanupFileChanges();await this.cleanupForkThreads()}async updateFileChanges(){if(await this.isAutoSnapshotEnabled())return;this.cachedFileChanges=await W80(this.fs.tracker),this.fileChanges.next({files:this.cachedFileChanges})}async injectPendingSkills(J,Z){let Q=J.map((Y)=>Y.name);_.info("Adding info message to prompt skill invocation",{threadID:this.threadID,skillNames:Q}),this._awaitingSkillInvocation.next(J),this.thread=k9(this.thread,(Y)=>{let X=Y.nextMessageId??0;Y.nextMessageId=X+1,Y.messages.push({role:"info",messageId:X,content:[{type:"text",text:`You MUST call the ${w$} tool to load: ${Q.join(", ")}. Do this immediately before responding.`}]}),Y.v++})}checkAndAppendAwaitedSkills(){let J=this._awaitingSkillInvocation.getValue();if(J.length===0)return;this._awaitingSkillInvocation.next([]);let{updatedThread:Z,uninvoked:Q}=xR5(this.thread,{toolName:w$,items:J,wasInvoked:(Y,X)=>Y.some((K)=>K.name===w$&&K.input.name===X.name),toToolInput:(Y)=>({name:Y.name,arguments:Y.arguments})});if(Q.length>0)_.info("Skills not invoked by model, appending tool_use blocks",{threadID:this.threadID,uninvokedSkills:Q.map((Y)=>Y.name)}),this.thread=Z}async executeHandoff(J){_.info("Executing handoff",{threadID:this.threadID,goal:J}),this.handoffState.next({goal:J});try{let{threadWorkerService:Z}=await Promise.resolve().then(() => (KU(),CV4)),Q={toolService:this.deps.toolService,configService:this.deps.configService,skillService:this.deps.skillService,getThreadEnvironment:this.deps.getThreadEnvironment,filesystem:this.fs.fileSystem,threadService:this.deps.threadService},{threadID:Y}=await Z.handoff(this.deps,{threadID:this.threadID,goal:J,images:[],mode:"initial",agentMode:this.thread.agentMode,queuedMessages:this.thread.queuedMessages,clearQueuedMessages:!0,blockIndex:0,buildSystemPromptDeps:Q});_.info("Handoff thread created and running in background",{fromThreadID:this.threadID,newThreadID:Y,goal:J}),this.handoffState.next({goal:J,result:{newThreadID:Y}})}catch(Z){_.error("Handoff failed",Z,{threadID:this.threadID,goal:J}),this.handoffState.next({goal:J,result:{error:Z instanceof Error?Z.message:String(Z)}})}}continueInferenceAfterRejection(J=!0){this.shouldContinueAfterRejection=J}getTurnStartTime(){return this._turnStartTime.getValue()}setTurnStartTime(J){this._turnStartTime.next(J)}async asyncDispose(){if(this.isDisposed)return;if(_.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 J=await this.getConfig(),{agentMode:Z}=FJ(J.settings,this.thread);return Z}}function fR5(J,Z,Q=!1){let Y=I7(J,"assistant");if(!Y||Y.state.type!=="complete"||Y.state.stopReason!=="tool_use")return!1;let X=Y.content.filter((F)=>F.type==="tool_use").map((F)=>F.id);if(Z&&!X.includes(Z))return _.debug(`tool:data for orphaned tool_use ${Z} - ignoring for inference`,{name:"shouldRunInferenceWithToolData",threadID:J.id}),!1;if(X.length===0)return!1;let K=ZY(J);if(!X.every((F)=>{let z=K.get(F);if(!z?.run||!m8(z.run.status))return!1;let q=z.run.status;if(q==="cancelled"){let W=z.run.reason;return W?!W.startsWith("user:"):!1}if(q==="rejected-by-user")return Q;return!0}))return!1;if(X.every((F)=>{let z=K.get(F);if(!z||z.run.status!=="done")return!1;return z.run.isFinal===!0}))return!1;return!0}var PV4=Z0(()=>{U4();E1();VJ();bV();a0();EK4();nH();x3();lX();o40();DE();YJ();Ac();GY();T4();EB();H80();og0();JN();xA();m4();GT();jV4();MT0();IV4()});var CV4={};D9(CV4,{threadWorkerService:()=>u9});class TV4{threadWorkers=new Ej0;async getOrCreateForThread(J,Z){let Q=this.threadWorkers.get(Z);if(!Q){if(Q=new rS(J,Z),this.threadWorkers.set(Z,Q),this.threadWorkers.size>25)_.info("Many active thread workers detected",{name:"ThreadWorkerService.memoryCheck",threadID:Z,totalWorkerCount:this.threadWorkers.size})}return Vm0.record(this.threadWorkers.size),Q}async createThreadWorker(J,Z){let Q=await this.getOrCreateForThread(J,Z);return await Q.resume(),Q}async seedThreadMessages(J,Z,Q,Y){let X=await J.threadService.exclusiveSyncReadWriter(Z),K=Y?Q.map((F)=>F.role==="user"?{...F,agentMode:Y}:F):[...Q],V=K.length>0?Math.max(...K.map((F)=>F.messageId))+1:0,G=X.read();X.write({...G,agentMode:Y??G.agentMode,messages:K,nextMessageId:V,v:G.v+1}),await X.asyncDispose()}async applyParentRelationship(J,Z,Q,Y){let X=Date.now(),{threadID:K,type:V,messageIndex:G,blockIndex:F,comment:z}=Y;await Z.handle({type:"relationship",relationship:{threadID:K,type:V,role:"child",messageIndex:G,blockIndex:F,createdAt:X,comment:z}});let q={threadID:Q,type:V,role:"parent",messageIndex:G,blockIndex:F,createdAt:X,comment:z},W=this.threadWorkers.get(K);if(W)await W.handle({type:"relationship",relationship:q});else{let H=await J.threadService.exclusiveSyncReadWriter(K);H.update((U)=>{if(!U.relationships)U.relationships=[];if(!U.relationships.some((B)=>B.threadID===q.threadID&&B.type===q.type&&B.role===q.role))U.relationships.push(q)}),await H.asyncDispose()}}async inheritVisibilityIfNeeded(J,Z,Q){if(Z.type==="handoff")await UJ4(J.threadService,Z.threadID,Q)}async sendInitialUserMessage(J,Z){let Q=typeof Z==="string"?[{type:"text",text:Z}]:[...Z];await J.handle({type:"user:message",message:{content:Q}})}async setDraftContent(J,Z){let Q=typeof Z==="string"?Z:[...Z];await J.handle({type:"draft",content:Q})}async setPendingNavigation(J,Z){let Q=this.threadWorkers.get(J);if(Q)await Q.handle({type:"setPendingNavigation",threadID:Z})}async transferQueuedMessages(J,Z){for(let Q of Z)await J.handle({type:"user:message-queue:enqueue",message:Q.queuedMessage})}async createThread(J,Z){let Q=Z?.newThreadID??g8(),Y=Z?.agentMode,X=!1;if(Z?.seededMessages)await this.seedThreadMessages(J,Q,Z.seededMessages,Y),X=!0;let K=await this.createThreadWorker(J,Q);if(K.thread.messages.length>0&&!X)return _.info("createThread called for existing thread, returning existing worker",{threadID:Q,messageCount:K.thread.messages.length}),{threadID:Q,worker:K};if(Y&&!X)await K.handle({type:"agent-mode",mode:Y});if(Z?.parent)await this.applyParentRelationship(J,K,Q,Z.parent),await this.inheritVisibilityIfNeeded(J,Z.parent,Q);if(Z?.initialUserMessage){if(X)throw Error("initialUserMessage cannot be set when seededMessages is provided");await this.sendInitialUserMessage(K,Z.initialUserMessage)}if(Z?.draftContent){if(X)throw Error("draftContent cannot be set when seededMessages is provided");await this.setDraftContent(K,Z.draftContent)}if(Z?.navigate&&Z?.parent)await this.setPendingNavigation(Z.parent.threadID,Q);if(Z?.queuedMessages)await this.transferQueuedMessages(K,Z.queuedMessages);return{threadID:Q,worker:K}}async handoff(J,Z){let Q=await this.createThreadWorker(J,Z.threadID),Y=Q.thread,X=Z.images??[],K=Z.signal??new AbortController().signal,{content:V}=await H20({thread:Y,goal:Z.goal,images:X,deps:{configService:J.configService,buildSystemPromptDeps:Z.buildSystemPromptDeps,signal:K,filesystem:Z.filesystem,deadline:Z.deadline}}),G=typeof V==="string"?V:V.filter((q)=>q.type==="text"||q.type==="image"),F={threadID:Z.threadID,type:"handoff",messageIndex:Z.messageIndex??(Y.messages.length?Y.messages.length-1:void 0),blockIndex:Z.blockIndex,comment:Z.comment??Z.goal},z=await this.createThread(J,{newThreadID:Z.newThreadID,agentMode:Z.agentMode??Y.agentMode,parent:F,navigate:Z.navigate,queuedMessages:Z.queuedMessages??Y.queuedMessages,initialUserMessage:Z.mode==="initial"?G:void 0,draftContent:Z.mode==="draft"?G:void 0});if(Z.clearQueuedMessages&&Y.queuedMessages?.length)await Q.handle({type:"user:message-queue:discard"});return z}get workers(){return this.threadWorkers.observable}get statuses(){return this.threadWorkers.observable.pipe(_4((J)=>J.size===0?k0.of({}):F5(...Array.from(J.values()).map((Z)=>Z.status.pipe(w1((Q)=>[Z.threadID,Z.threadReadWriter?ES(Z.thread,Q):void 0])))).pipe(w1((Z)=>Object.fromEntries(Z)))),kV(25),m6())}get(J){return this.threadWorkers.get(J)}prettyPrintToolRun(J,Z){let Q=this.threadWorkers.get(J);if(!Q)throw Error(`No worker found for thread ${J}`);for(let Y of Q.thread.messages)for(let X of Y.content)if(X.type==="tool_result"&&X.toolUseID===Z)return o04(X.run);throw Error(`Tool run not found for thread ${J} and tool use ${Z}`)}async cancelToolOnly(J,Z){await this.threadWorkers.get(J)?.cancelToolOnly(Z)}async cancel(J){await this.threadWorkers.get(J)?.cancel()}async dispose(J){let Z=this.threadWorkers.get(J);if(Z)await Z.cancel(),await Z.asyncDispose(),this.threadWorkers.delete(J),Vm0.record(this.threadWorkers.size)}async retry(J){let Z=this.threadWorkers.get(J);if(!Z)throw Error(`No active worker for thread ${J}`);await Z.retry()}async revertFileChanges(J,Z){let Q=this.threadWorkers.get(J);if(!Q)throw Error(`No active worker for thread ${J}`);await Q.revertFileChanges(Z)}async getFilesAffectedByTruncation(J,Z){let Q=this.threadWorkers.get(J);if(!Q)throw Error(`No active worker for thread ${J}`);return Q.getFilesAffectedByTruncation(Z)}async cleanupThreadBackups(J,Z){let Q=this.threadWorkers.get(Z);if(Q)await Q.fs.tracker.cleanupBackups();else try{await new sV(J.osFileSystem).cleanup(Z),_.debug(`Cleaned up backup files for thread ${Z}`,{threadID:Z})}catch(Y){_.error("Error cleaning up thread backups",Y,{threadID:Z})}}async disposeAll(){await Promise.all(Array.from(this.threadWorkers.values()).map(async(J)=>await J.asyncDispose())),this.threadWorkers.clear(),Vm0.record(0)}}var _V4,uR5,Vm0,u9;var KU=Z0(()=>{E1();a0();r04();HJ4();l_();m4();DJ4();PV4();_V4=H4(w4(),1),uR5=_V4.metrics.getMeter("thread-worker-service"),Vm0=uR5.createGauge("thread_worker_count",{description:"Number of active thread workers"});u9=new TV4});var Fm0=u((vV4)=>{Object.defineProperty(vV4,"__esModule",{value:!0});vV4.dynamicAnchor=void 0;var Gm0=d6(),bR5=rX(),SV4=dh(),hR5=t60(),gR5={keyword:"$dynamicAnchor",schemaType:"string",code:(J)=>kV4(J,J.schema)};function kV4(J,Z){let{gen:Q,it:Y}=J;Y.schemaEnv.root.dynamicAnchors[Z]=!0;let X=Gm0._`${bR5.default.dynamicAnchors}${(0,Gm0.getProperty)(Z)}`,K=Y.errSchemaPath==="#"?Y.validateName:mR5(J);Q.if(Gm0._`!${X}`,()=>Q.assign(X,K))}vV4.dynamicAnchor=kV4;function mR5(J){let{schemaEnv:Z,schema:Q,self:Y}=J.it,{root:X,baseId:K,localRefs:V,meta:G}=Z.root,{schemaId:F}=Y.opts,z=new SV4.SchemaEnv({schema:Q,schemaId:F,root:X,baseId:K,localRefs:V,meta:G});return SV4.compileSchema.call(Y,z),(0,hR5.getValidate)(J,z)}vV4.default=gR5});var zm0=u((bV4)=>{Object.defineProperty(bV4,"__esModule",{value:!0});bV4.dynamicRef=void 0;var xV4=d6(),dR5=rX(),fV4=t60(),cR5={keyword:"$dynamicRef",schemaType:"string",code:(J)=>uV4(J,J.schema)};function uV4(J,Z){let{gen:Q,keyword:Y,it:X}=J;if(Z[0]!=="#")throw Error(`"${Y}" only supports hash fragment reference`);let K=Z.slice(1);if(X.allErrors)V();else{let F=Q.let("valid",!1);V(F),J.ok(F)}function V(F){if(X.schemaEnv.root.dynamicAnchors[K]){let z=Q.let("_v",xV4._`${dR5.default.dynamicAnchors}${(0,xV4.getProperty)(K)}`);Q.if(z,G(z,F),G(X.validateName,F))}else G(X.validateName,F)()}function G(F,z){return z?()=>Q.block(()=>{(0,fV4.callRef)(J,F),Q.let(z,!0)}):()=>(0,fV4.callRef)(J,F)}}bV4.dynamicRef=uV4;bV4.default=cR5});var mV4=u((gV4)=>{Object.defineProperty(gV4,"__esModule",{value:!0});var iR5=Fm0(),nR5=I5(),aR5={keyword:"$recursiveAnchor",schemaType:"boolean",code(J){if(J.schema)(0,iR5.dynamicAnchor)(J,"");else(0,nR5.checkStrictMode)(J.it,"$recursiveAnchor: false is ignored")}};gV4.default=aR5});var dV4=u((pV4)=>{Object.defineProperty(pV4,"__esModule",{value:!0});var rR5=zm0(),sR5={keyword:"$recursiveRef",schemaType:"string",code:(J)=>(0,rR5.dynamicRef)(J,J.schema)};pV4.default=sR5});var lV4=u((cV4)=>{Object.defineProperty(cV4,"__esModule",{value:!0});var eR5=Fm0(),$I5=zm0(),JI5=mV4(),ZI5=dV4(),QI5=[eR5.default,$I5.default,JI5.default,ZI5.default];cV4.default=QI5});var aV4=u((nV4)=>{Object.defineProperty(nV4,"__esModule",{value:!0});var iV4=X50(),XI5={keyword:"dependentRequired",type:"object",schemaType:"object",error:iV4.error,code:(J)=>(0,iV4.validatePropertyDeps)(J)};nV4.default=XI5});var rV4=u((oV4)=>{Object.defineProperty(oV4,"__esModule",{value:!0});var VI5=X50(),GI5={keyword:"dependentSchemas",type:"object",schemaType:"object",code:(J)=>(0,VI5.validateSchemaDeps)(J)};oV4.default=GI5});var tV4=u((sV4)=>{Object.defineProperty(sV4,"__esModule",{value:!0});var zI5=I5(),qI5={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:J,parentSchema:Z,it:Q}){if(Z.contains===void 0)(0,zI5.checkStrictMode)(Q,`"${J}" without "contains" is ignored`)}};sV4.default=qI5});var $G4=u((eV4)=>{Object.defineProperty(eV4,"__esModule",{value:!0});var HI5=aV4(),UI5=rV4(),DI5=tV4(),BI5=[HI5.default,UI5.default,DI5.default];eV4.default=BI5});var QG4=u((ZG4)=>{Object.defineProperty(ZG4,"__esModule",{value:!0});var rN=d6(),JG4=I5(),wI5=rX(),LI5={message:"must NOT have unevaluated properties",params:({params:J})=>rN._`{unevaluatedProperty: ${J.unevaluatedProperty}}`},OI5={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:LI5,code(J){let{gen:Z,schema:Q,data:Y,errsCount:X,it:K}=J;if(!X)throw Error("ajv implementation error");let{allErrors:V,props:G}=K;if(G instanceof rN.Name)Z.if(rN._`${G} !== true`,()=>Z.forIn("key",Y,(W)=>Z.if(z(G,W),()=>F(W))));else if(G!==!0)Z.forIn("key",Y,(W)=>G===void 0?F(W):Z.if(q(G,W),()=>F(W)));K.props=!0,J.ok(rN._`${X} === ${wI5.default.errors}`);function F(W){if(Q===!1){if(J.setParams({unevaluatedProperty:W}),J.error(),!V)Z.break();return}if(!(0,JG4.alwaysValidSchema)(K,Q)){let H=Z.name("valid");if(J.subschema({keyword:"unevaluatedProperties",dataProp:W,dataPropType:JG4.Type.Str},H),!V)Z.if((0,rN.not)(H),()=>Z.break())}}function z(W,H){return rN._`!${W} || !${W}[${H}]`}function q(W,H){let U=[];for(let D in W)if(W[D]===!0)U.push(rN._`${H} !== ${D}`);return(0,rN.and)(...U)}}};ZG4.default=OI5});var KG4=u((XG4)=>{Object.defineProperty(XG4,"__esModule",{value:!0});var fA=d6(),YG4=I5(),MI5={message:({params:{len:J}})=>fA.str`must NOT have more than ${J} items`,params:({params:{len:J}})=>fA._`{limit: ${J}}`},AI5={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:MI5,code(J){let{gen:Z,schema:Q,data:Y,it:X}=J,K=X.items||0;if(K===!0)return;let V=Z.const("len",fA._`${Y}.length`);if(Q===!1)J.setParams({len:K}),J.fail(fA._`${V} > ${K}`);else if(typeof Q=="object"&&!(0,YG4.alwaysValidSchema)(X,Q)){let F=Z.var("valid",fA._`${V} <= ${K}`);Z.if((0,fA.not)(F),()=>G(F,K)),J.ok(F)}X.items=!0;function G(F,z){Z.forRange("i",z,V,(q)=>{if(J.subschema({keyword:"unevaluatedItems",dataProp:q,dataPropType:YG4.Type.Num},F),!X.allErrors)Z.if((0,fA.not)(F),()=>Z.break())})}}};XG4.default=AI5});var GG4=u((VG4)=>{Object.defineProperty(VG4,"__esModule",{value:!0});var RI5=QG4(),II5=KG4(),PI5=[RI5.default,II5.default];VG4.default=PI5});var qG4=u((zG4)=>{Object.defineProperty(zG4,"__esModule",{value:!0});var _I5=nC0(),TI5=rC0(),SI5=Q_0(),kI5=lV4(),vI5=$G4(),yI5=GG4(),xI5=Y_0(),FG4=X_0(),fI5=[kI5.default,_I5.default,TI5.default,(0,SI5.default)(!0),xI5.default,FG4.metadataVocabulary,FG4.contentVocabulary,vI5.default,yI5.default];zG4.default=fI5});var WG4=u((Tb8,bI5)=>{bI5.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 HG4=u((Sb8,hI5)=>{hI5.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 UG4=u((kb8,gI5)=>{gI5.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 DG4=u((vb8,mI5)=>{mI5.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 BG4=u((yb8,pI5)=>{pI5.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 NG4=u((xb8,dI5)=>{dI5.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 wG4=u((fb8,cI5)=>{cI5.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 LG4=u((ub8,lI5)=>{lI5.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 EG4=u((OG4)=>{Object.defineProperty(OG4,"__esModule",{value:!0});var iI5=WG4(),nI5=HG4(),aI5=UG4(),oI5=DG4(),rI5=BG4(),sI5=NG4(),tI5=wG4(),eI5=LG4(),$P5=["/properties"];function JP5(J){return[iI5,nI5,aI5,oI5,rI5,Z(this,sI5),tI5,Z(this,eI5)].forEach((Q)=>this.addMetaSchema(Q,void 0,!1)),this;function Z(Q,Y){return J?Q.$dataMetaSchema(Y,$P5):Y}}OG4.default=JP5});var MG4=u((NQ,Wm0)=>{Object.defineProperty(NQ,"__esModule",{value:!0});NQ.MissingRefError=NQ.ValidationError=NQ.CodeGen=NQ.Name=NQ.nil=NQ.stringify=NQ.str=NQ._=NQ.KeywordCxt=NQ.Ajv2020=void 0;var QP5=iC0(),YP5=qG4(),XP5=V_0(),KP5=EG4(),qm0="https://json-schema.org/draft/2020-12/schema";class Ic extends QP5.default{constructor(J={}){super({...J,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){if(super._addVocabularies(),YP5.default.forEach((J)=>this.addVocabulary(J)),this.opts.discriminator)this.addKeyword(XP5.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:J,meta:Z}=this.opts;if(!Z)return;KP5.default.call(this,J),this.refs["http://json-schema.org/schema"]=qm0}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(qm0)?qm0:void 0)}}NQ.Ajv2020=Ic;Wm0.exports=NQ=Ic;Wm0.exports.Ajv2020=Ic;Object.defineProperty(NQ,"__esModule",{value:!0});NQ.default=Ic;var VP5=Q_();Object.defineProperty(NQ,"KeywordCxt",{enumerable:!0,get:function(){return VP5.KeywordCxt}});var sS=d6();Object.defineProperty(NQ,"_",{enumerable:!0,get:function(){return sS._}});Object.defineProperty(NQ,"str",{enumerable:!0,get:function(){return sS.str}});Object.defineProperty(NQ,"stringify",{enumerable:!0,get:function(){return sS.stringify}});Object.defineProperty(NQ,"nil",{enumerable:!0,get:function(){return sS.nil}});Object.defineProperty(NQ,"Name",{enumerable:!0,get:function(){return sS.Name}});Object.defineProperty(NQ,"CodeGen",{enumerable:!0,get:function(){return sS.CodeGen}});var GP5=mh();Object.defineProperty(NQ,"ValidationError",{enumerable:!0,get:function(){return GP5.default}});var FP5=Y_();Object.defineProperty(NQ,"MissingRefError",{enumerable:!0,get:function(){return FP5.default}})});var jG4=u((AG4)=>{(()=>{var J={349:(V,G,F)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.CircularList=void 0;let z=F(460),q=F(844);class W extends q.Disposable{constructor(H){super(),this._maxLength=H,this.onDeleteEmitter=this.register(new z.EventEmitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this.register(new z.EventEmitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this.register(new z.EventEmitter),this.onTrim=this.onTrimEmitter.event,this._array=Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(H){if(this._maxLength===H)return;let U=Array(H);for(let D=0;D<Math.min(H,this.length);D++)U[D]=this._array[this._getCyclicIndex(D)];this._array=U,this._maxLength=H,this._startIndex=0}get length(){return this._length}set length(H){if(H>this._length)for(let U=this._length;U<H;U++)this._array[U]=void 0;this._length=H}get(H){return this._array[this._getCyclicIndex(H)]}set(H,U){this._array[this._getCyclicIndex(H)]=U}push(H){this._array[this._getCyclicIndex(this._length)]=H,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(H,U,...D){if(U){for(let B=H;B<this._length-U;B++)this._array[this._getCyclicIndex(B)]=this._array[this._getCyclicIndex(B+U)];this._length-=U,this.onDeleteEmitter.fire({index:H,amount:U})}for(let B=this._length-1;B>=H;B--)this._array[this._getCyclicIndex(B+D.length)]=this._array[this._getCyclicIndex(B)];for(let B=0;B<D.length;B++)this._array[this._getCyclicIndex(H+B)]=D[B];if(D.length&&this.onInsertEmitter.fire({index:H,amount:D.length}),this._length+D.length>this._maxLength){let B=this._length+D.length-this._maxLength;this._startIndex+=B,this._length=this._maxLength,this.onTrimEmitter.fire(B)}else this._length+=D.length}trimStart(H){H>this._length&&(H=this._length),this._startIndex+=H,this._length-=H,this.onTrimEmitter.fire(H)}shiftElements(H,U,D){if(!(U<=0)){if(H<0||H>=this._length)throw Error("start argument out of range");if(H+D<0)throw Error("Cannot shift elements in list beyond index 0");if(D>0){for(let N=U-1;N>=0;N--)this.set(H+N+D,this.get(H+N));let B=H+U+D-this._length;if(B>0)for(this._length+=B;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let B=0;B<U;B++)this.set(H+B+D,this.get(H+B))}}_getCyclicIndex(H){return(this._startIndex+H)%this._maxLength}}G.CircularList=W},439:(V,G)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.clone=void 0,G.clone=function F(z,q=5){if(typeof z!="object")return z;let W=Array.isArray(z)?[]:{};for(let H in z)W[H]=q<=1?z[H]:z[H]&&F(z[H],q-1);return W}},969:(V,G,F)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.CoreTerminal=void 0;let z=F(844),q=F(585),W=F(348),H=F(866),U=F(744),D=F(302),B=F(83),N=F(460),w=F(753),L=F(480),O=F(994),E=F(282),M=F(435),A=F(981),j=F(660),I=!1;class T extends z.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this.register(new N.EventEmitter),this._onScroll.event((P)=>{this._onScrollApi?.fire(P.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(P){for(let h in P)this.optionsService.options[h]=P[h]}constructor(P){super(),this._windowsWrappingHeuristics=this.register(new z.MutableDisposable),this._onBinary=this.register(new N.EventEmitter),this.onBinary=this._onBinary.event,this._onData=this.register(new N.EventEmitter),this.onData=this._onData.event,this._onLineFeed=this.register(new N.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this.register(new N.EventEmitter),this.onResize=this._onResize.event,this._onWriteParsed=this.register(new N.EventEmitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this.register(new N.EventEmitter),this._instantiationService=new W.InstantiationService,this.optionsService=this.register(new D.OptionsService(P)),this._instantiationService.setService(q.IOptionsService,this.optionsService),this._bufferService=this.register(this._instantiationService.createInstance(U.BufferService)),this._instantiationService.setService(q.IBufferService,this._bufferService),this._logService=this.register(this._instantiationService.createInstance(H.LogService)),this._instantiationService.setService(q.ILogService,this._logService),this.coreService=this.register(this._instantiationService.createInstance(B.CoreService)),this._instantiationService.setService(q.ICoreService,this.coreService),this.coreMouseService=this.register(this._instantiationService.createInstance(w.CoreMouseService)),this._instantiationService.setService(q.ICoreMouseService,this.coreMouseService),this.unicodeService=this.register(this._instantiationService.createInstance(L.UnicodeService)),this._instantiationService.setService(q.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(O.CharsetService),this._instantiationService.setService(q.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(j.OscLinkService),this._instantiationService.setService(q.IOscLinkService,this._oscLinkService),this._inputHandler=this.register(new M.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this.register((0,N.forwardEvent)(this._inputHandler.onLineFeed,this._onLineFeed)),this.register(this._inputHandler),this.register((0,N.forwardEvent)(this._bufferService.onResize,this._onResize)),this.register((0,N.forwardEvent)(this.coreService.onData,this._onData)),this.register((0,N.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((h)=>{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((h)=>{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 A.WriteBuffer((h,p)=>this._inputHandler.parse(h,p))),this.register((0,N.forwardEvent)(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(P,h){this._writeBuffer.write(P,h)}writeSync(P,h){this._logService.logLevel<=q.LogLevelEnum.WARN&&!I&&(this._logService.warn("writeSync is unreliable and will be removed soon."),I=!0),this._writeBuffer.writeSync(P,h)}input(P,h=!0){this.coreService.triggerDataEvent(P,h)}resize(P,h){isNaN(P)||isNaN(h)||(P=Math.max(P,U.MINIMUM_COLS),h=Math.max(h,U.MINIMUM_ROWS),this._bufferService.resize(P,h))}scroll(P,h=!1){this._bufferService.scroll(P,h)}scrollLines(P,h,p){this._bufferService.scrollLines(P,h,p)}scrollPages(P){this.scrollLines(P*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(P){let h=P-this._bufferService.buffer.ydisp;h!==0&&this.scrollLines(h)}registerEscHandler(P,h){return this._inputHandler.registerEscHandler(P,h)}registerDcsHandler(P,h){return this._inputHandler.registerDcsHandler(P,h)}registerCsiHandler(P,h){return this._inputHandler.registerCsiHandler(P,h)}registerOscHandler(P,h){return this._inputHandler.registerOscHandler(P,h)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let P=!1,h=this.optionsService.rawOptions.windowsPty;h&&h.buildNumber!==void 0&&h.buildNumber!==void 0?P=h.backend==="conpty"&&h.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(P=!0),P?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let P=[];P.push(this.onLineFeed(E.updateWindowsModeWrappedState.bind(null,this._bufferService))),P.push(this.registerCsiHandler({final:"H"},()=>((0,E.updateWindowsModeWrappedState)(this._bufferService),!1))),this._windowsWrappingHeuristics.value=(0,z.toDisposable)(()=>{for(let h of P)h.dispose()})}}}G.CoreTerminal=T},460:(V,G)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.runAndSubscribe=G.forwardEvent=G.EventEmitter=void 0,G.EventEmitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||(this._event=(F)=>{return this._listeners.push(F),{dispose:()=>{if(!this._disposed){for(let q=0;q<this._listeners.length;q++)if(this._listeners[q]===F)return void this._listeners.splice(q,1)}}}}),this._event}fire(F,z){let q=[];for(let W=0;W<this._listeners.length;W++)q.push(this._listeners[W]);for(let W=0;W<q.length;W++)q[W].call(void 0,F,z)}dispose(){this.clearListeners(),this._disposed=!0}clearListeners(){this._listeners&&(this._listeners.length=0)}},G.forwardEvent=function(F,z){return F((q)=>z.fire(q))},G.runAndSubscribe=function(F,z){return z(void 0),F((q)=>z(q))}},435:function(V,G,F){var z=this&&this.__decorate||function(b,n,c,s){var W0,r=arguments.length,F0=r<3?n:s===null?s=Object.getOwnPropertyDescriptor(n,c):s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")F0=Reflect.decorate(b,n,c,s);else for(var w0=b.length-1;w0>=0;w0--)(W0=b[w0])&&(F0=(r<3?W0(F0):r>3?W0(n,c,F0):W0(n,c))||F0);return r>3&&F0&&Object.defineProperty(n,c,F0),F0},q=this&&this.__param||function(b,n){return function(c,s){n(c,s,b)}};Object.defineProperty(G,"__esModule",{value:!0}),G.InputHandler=G.WindowsOptionsReportType=void 0;let W=F(584),H=F(116),U=F(15),D=F(844),B=F(482),N=F(437),w=F(460),L=F(643),O=F(511),E=F(734),M=F(585),A=F(480),j=F(242),I=F(351),T=F(941),P={"(":0,")":1,"*":2,"+":3,"-":1,".":2},h=131072;function p(b,n){if(b>24)return n.setWinLines||!1;switch(b){case 1:return!!n.restoreWin;case 2:return!!n.minimizeWin;case 3:return!!n.setWinPosition;case 4:return!!n.setWinSizePixels;case 5:return!!n.raiseWin;case 6:return!!n.lowerWin;case 7:return!!n.refreshWin;case 8:return!!n.setWinSizeChars;case 9:return!!n.maximizeWin;case 10:return!!n.fullscreenWin;case 11:return!!n.getWinState;case 13:return!!n.getWinPosition;case 14:return!!n.getWinSizePixels;case 15:return!!n.getScreenSizePixels;case 16:return!!n.getCellSizePixels;case 18:return!!n.getWinSizeChars;case 19:return!!n.getScreenSizeChars;case 20:return!!n.getIconTitle;case 21:return!!n.getWinTitle;case 22:return!!n.pushTitle;case 23:return!!n.popTitle;case 24:return!!n.setWinLines}return!1}var x;(function(b){b[b.GET_WIN_SIZE_PIXELS=0]="GET_WIN_SIZE_PIXELS",b[b.GET_CELL_SIZE_PIXELS=1]="GET_CELL_SIZE_PIXELS"})(x||(G.WindowsOptionsReportType=x={}));let k=0;class f extends D.Disposable{getAttrData(){return this._curAttrData}constructor(b,n,c,s,W0,r,F0,w0,L0=new U.EscapeSequenceParser){super(),this._bufferService=b,this._charsetService=n,this._coreService=c,this._logService=s,this._optionsService=W0,this._oscLinkService=r,this._coreMouseService=F0,this._unicodeService=w0,this._parser=L0,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new B.StringToUtf32,this._utf8Decoder=new B.Utf8ToUtf32,this._workCell=new O.CellData,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=N.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=N.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this.register(new w.EventEmitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this.register(new w.EventEmitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this.register(new w.EventEmitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this.register(new w.EventEmitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this.register(new w.EventEmitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this.register(new w.EventEmitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this.register(new w.EventEmitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this.register(new w.EventEmitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this.register(new w.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this.register(new w.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this.register(new w.EventEmitter),this.onScroll=this._onScroll.event,this._onTitleChange=this.register(new w.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this.register(new w.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((e)=>this._activeBuffer=e.activeBuffer)),this._parser.setCsiHandlerFallback((e,K0)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(e),params:K0.toArray()})}),this._parser.setEscHandlerFallback((e)=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(e)})}),this._parser.setExecuteHandlerFallback((e)=>{this._logService.debug("Unknown EXECUTE code: ",{code:e})}),this._parser.setOscHandlerFallback((e,K0,i)=>{this._logService.debug("Unknown OSC code: ",{identifier:e,action:K0,data:i})}),this._parser.setDcsHandlerFallback((e,K0,i)=>{K0==="HOOK"&&(i=i.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(e),action:K0,payload:i})}),this._parser.setPrintHandler((e,K0,i)=>this.print(e,K0,i)),this._parser.registerCsiHandler({final:"@"},(e)=>this.insertChars(e)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},(e)=>this.scrollLeft(e)),this._parser.registerCsiHandler({final:"A"},(e)=>this.cursorUp(e)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},(e)=>this.scrollRight(e)),this._parser.registerCsiHandler({final:"B"},(e)=>this.cursorDown(e)),this._parser.registerCsiHandler({final:"C"},(e)=>this.cursorForward(e)),this._parser.registerCsiHandler({final:"D"},(e)=>this.cursorBackward(e)),this._parser.registerCsiHandler({final:"E"},(e)=>this.cursorNextLine(e)),this._parser.registerCsiHandler({final:"F"},(e)=>this.cursorPrecedingLine(e)),this._parser.registerCsiHandler({final:"G"},(e)=>this.cursorCharAbsolute(e)),this._parser.registerCsiHandler({final:"H"},(e)=>this.cursorPosition(e)),this._parser.registerCsiHandler({final:"I"},(e)=>this.cursorForwardTab(e)),this._parser.registerCsiHandler({final:"J"},(e)=>this.eraseInDisplay(e,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},(e)=>this.eraseInDisplay(e,!0)),this._parser.registerCsiHandler({final:"K"},(e)=>this.eraseInLine(e,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},(e)=>this.eraseInLine(e,!0)),this._parser.registerCsiHandler({final:"L"},(e)=>this.insertLines(e)),this._parser.registerCsiHandler({final:"M"},(e)=>this.deleteLines(e)),this._parser.registerCsiHandler({final:"P"},(e)=>this.deleteChars(e)),this._parser.registerCsiHandler({final:"S"},(e)=>this.scrollUp(e)),this._parser.registerCsiHandler({final:"T"},(e)=>this.scrollDown(e)),this._parser.registerCsiHandler({final:"X"},(e)=>this.eraseChars(e)),this._parser.registerCsiHandler({final:"Z"},(e)=>this.cursorBackwardTab(e)),this._parser.registerCsiHandler({final:"`"},(e)=>this.charPosAbsolute(e)),this._parser.registerCsiHandler({final:"a"},(e)=>this.hPositionRelative(e)),this._parser.registerCsiHandler({final:"b"},(e)=>this.repeatPrecedingCharacter(e)),this._parser.registerCsiHandler({final:"c"},(e)=>this.sendDeviceAttributesPrimary(e)),this._parser.registerCsiHandler({prefix:">",final:"c"},(e)=>this.sendDeviceAttributesSecondary(e)),this._parser.registerCsiHandler({final:"d"},(e)=>this.linePosAbsolute(e)),this._parser.registerCsiHandler({final:"e"},(e)=>this.vPositionRelative(e)),this._parser.registerCsiHandler({final:"f"},(e)=>this.hVPosition(e)),this._parser.registerCsiHandler({final:"g"},(e)=>this.tabClear(e)),this._parser.registerCsiHandler({final:"h"},(e)=>this.setMode(e)),this._parser.registerCsiHandler({prefix:"?",final:"h"},(e)=>this.setModePrivate(e)),this._parser.registerCsiHandler({final:"l"},(e)=>this.resetMode(e)),this._parser.registerCsiHandler({prefix:"?",final:"l"},(e)=>this.resetModePrivate(e)),this._parser.registerCsiHandler({final:"m"},(e)=>this.charAttributes(e)),this._parser.registerCsiHandler({final:"n"},(e)=>this.deviceStatus(e)),this._parser.registerCsiHandler({prefix:"?",final:"n"},(e)=>this.deviceStatusPrivate(e)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},(e)=>this.softReset(e)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},(e)=>this.setCursorStyle(e)),this._parser.registerCsiHandler({final:"r"},(e)=>this.setScrollRegion(e)),this._parser.registerCsiHandler({final:"s"},(e)=>this.saveCursor(e)),this._parser.registerCsiHandler({final:"t"},(e)=>this.windowOptions(e)),this._parser.registerCsiHandler({final:"u"},(e)=>this.restoreCursor(e)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},(e)=>this.insertColumns(e)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},(e)=>this.deleteColumns(e)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},(e)=>this.selectProtected(e)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},(e)=>this.requestMode(e,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},(e)=>this.requestMode(e,!1)),this._parser.setExecuteHandler(W.C0.BEL,()=>this.bell()),this._parser.setExecuteHandler(W.C0.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(W.C0.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(W.C0.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(W.C0.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(W.C0.BS,()=>this.backspace()),this._parser.setExecuteHandler(W.C0.HT,()=>this.tab()),this._parser.setExecuteHandler(W.C0.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(W.C0.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(W.C1.IND,()=>this.index()),this._parser.setExecuteHandler(W.C1.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(W.C1.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new j.OscHandler((e)=>(this.setTitle(e),this.setIconName(e),!0))),this._parser.registerOscHandler(1,new j.OscHandler((e)=>this.setIconName(e))),this._parser.registerOscHandler(2,new j.OscHandler((e)=>this.setTitle(e))),this._parser.registerOscHandler(4,new j.OscHandler((e)=>this.setOrReportIndexedColor(e))),this._parser.registerOscHandler(8,new j.OscHandler((e)=>this.setHyperlink(e))),this._parser.registerOscHandler(10,new j.OscHandler((e)=>this.setOrReportFgColor(e))),this._parser.registerOscHandler(11,new j.OscHandler((e)=>this.setOrReportBgColor(e))),this._parser.registerOscHandler(12,new j.OscHandler((e)=>this.setOrReportCursorColor(e))),this._parser.registerOscHandler(104,new j.OscHandler((e)=>this.restoreIndexedColor(e))),this._parser.registerOscHandler(110,new j.OscHandler((e)=>this.restoreFgColor(e))),this._parser.registerOscHandler(111,new j.OscHandler((e)=>this.restoreBgColor(e))),this._parser.registerOscHandler(112,new j.OscHandler((e)=>this.restoreCursorColor(e))),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 e in H.CHARSETS)this._parser.registerEscHandler({intermediates:"(",final:e},()=>this.selectCharset("("+e)),this._parser.registerEscHandler({intermediates:")",final:e},()=>this.selectCharset(")"+e)),this._parser.registerEscHandler({intermediates:"*",final:e},()=>this.selectCharset("*"+e)),this._parser.registerEscHandler({intermediates:"+",final:e},()=>this.selectCharset("+"+e)),this._parser.registerEscHandler({intermediates:"-",final:e},()=>this.selectCharset("-"+e)),this._parser.registerEscHandler({intermediates:".",final:e},()=>this.selectCharset("."+e)),this._parser.registerEscHandler({intermediates:"/",final:e},()=>this.selectCharset("/"+e));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler((e)=>(this._logService.error("Parsing error: ",e),e)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new I.DcsHandler((e,K0)=>this.requestStatusString(e,K0)))}_preserveStack(b,n,c,s){this._parseStack.paused=!0,this._parseStack.cursorStartX=b,this._parseStack.cursorStartY=n,this._parseStack.decodedLength=c,this._parseStack.position=s}_logSlowResolvingAsync(b){this._logService.logLevel<=M.LogLevelEnum.WARN&&Promise.race([b,new Promise((n,c)=>setTimeout(()=>c("#SLOW_TIMEOUT"),5000))]).catch((n)=>{if(n!=="#SLOW_TIMEOUT")throw n;console.warn("async parser handler taking longer than 5000 ms")})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(b,n){let c,s=this._activeBuffer.x,W0=this._activeBuffer.y,r=0,F0=this._parseStack.paused;if(F0){if(c=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,n))return this._logSlowResolvingAsync(c),c;s=this._parseStack.cursorStartX,W0=this._parseStack.cursorStartY,this._parseStack.paused=!1,b.length>h&&(r=this._parseStack.position+h)}if(this._logService.logLevel<=M.LogLevelEnum.DEBUG&&this._logService.debug("parsing data"+(typeof b=="string"?` "${b}"`:` "${Array.prototype.map.call(b,(e)=>String.fromCharCode(e)).join("")}"`),typeof b=="string"?b.split("").map((e)=>e.charCodeAt(0)):b),this._parseBuffer.length<b.length&&this._parseBuffer.length<h&&(this._parseBuffer=new Uint32Array(Math.min(b.length,h))),F0||this._dirtyRowTracker.clearRange(),b.length>h)for(let e=r;e<b.length;e+=h){let K0=e+h<b.length?e+h:b.length,i=typeof b=="string"?this._stringDecoder.decode(b.substring(e,K0),this._parseBuffer):this._utf8Decoder.decode(b.subarray(e,K0),this._parseBuffer);if(c=this._parser.parse(this._parseBuffer,i))return this._preserveStack(s,W0,i,e),this._logSlowResolvingAsync(c),c}else if(!F0){let e=typeof b=="string"?this._stringDecoder.decode(b,this._parseBuffer):this._utf8Decoder.decode(b,this._parseBuffer);if(c=this._parser.parse(this._parseBuffer,e))return this._preserveStack(s,W0,e,0),this._logSlowResolvingAsync(c),c}this._activeBuffer.x===s&&this._activeBuffer.y===W0||this._onCursorMove.fire();let w0=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),L0=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);L0<this._bufferService.rows&&this._onRequestRefreshRows.fire(Math.min(L0,this._bufferService.rows-1),Math.min(w0,this._bufferService.rows-1))}print(b,n,c){let s,W0,r=this._charsetService.charset,F0=this._optionsService.rawOptions.screenReaderMode,w0=this._bufferService.cols,L0=this._coreService.decPrivateModes.wraparound,e=this._coreService.modes.insertMode,K0=this._curAttrData,i=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&c-n>0&&i.getWidth(this._activeBuffer.x-1)===2&&i.setCellFromCodepoint(this._activeBuffer.x-1,0,1,K0);let a=this._parser.precedingJoinState;for(let t=n;t<c;++t){if(s=b[t],s<127&&r){let B0=r[String.fromCharCode(s)];B0&&(s=B0.charCodeAt(0))}let $0=this._unicodeService.charProperties(s,a);W0=A.UnicodeService.extractWidth($0);let G0=A.UnicodeService.extractShouldJoin($0),Y0=G0?A.UnicodeService.extractWidth(a):0;if(a=$0,F0&&this._onA11yChar.fire((0,B.stringFromCodePoint)(s)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+W0-Y0>w0){if(L0){let B0=i,U0=this._activeBuffer.x-Y0;for(this._activeBuffer.x=Y0,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),i=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),Y0>0&&i instanceof N.BufferLine&&i.copyCellsFrom(B0,U0,0,Y0,!1);U0<w0;)B0.setCellFromCodepoint(U0++,0,1,K0)}else if(this._activeBuffer.x=w0-1,W0===2)continue}if(G0&&this._activeBuffer.x){let B0=i.getWidth(this._activeBuffer.x-1)?1:2;i.addCodepointToCell(this._activeBuffer.x-B0,s,W0);for(let U0=W0-Y0;--U0>=0;)i.setCellFromCodepoint(this._activeBuffer.x++,0,0,K0)}else if(e&&(i.insertCells(this._activeBuffer.x,W0-Y0,this._activeBuffer.getNullCell(K0)),i.getWidth(w0-1)===2&&i.setCellFromCodepoint(w0-1,L.NULL_CELL_CODE,L.NULL_CELL_WIDTH,K0)),i.setCellFromCodepoint(this._activeBuffer.x++,s,W0,K0),W0>0)for(;--W0;)i.setCellFromCodepoint(this._activeBuffer.x++,0,0,K0)}this._parser.precedingJoinState=a,this._activeBuffer.x<w0&&c-n>0&&i.getWidth(this._activeBuffer.x)===0&&!i.hasContent(this._activeBuffer.x)&&i.setCellFromCodepoint(this._activeBuffer.x,0,1,K0),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(b,n){return b.final!=="t"||b.prefix||b.intermediates?this._parser.registerCsiHandler(b,n):this._parser.registerCsiHandler(b,(c)=>!p(c.params[0],this._optionsService.rawOptions.windowOptions)||n(c))}registerDcsHandler(b,n){return this._parser.registerDcsHandler(b,new I.DcsHandler(n))}registerEscHandler(b,n){return this._parser.registerEscHandler(b,n)}registerOscHandler(b,n){return this._parser.registerOscHandler(b,new j.OscHandler(n))}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 b=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);b.hasWidth(this._activeBuffer.x)&&!b.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let b=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-b),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(b=this._bufferService.cols-1){this._activeBuffer.x=Math.min(b,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(b,n){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=b,this._activeBuffer.y=this._activeBuffer.scrollTop+n):(this._activeBuffer.x=b,this._activeBuffer.y=n),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(b,n){this._restrictCursor(),this._setCursor(this._activeBuffer.x+b,this._activeBuffer.y+n)}cursorUp(b){let n=this._activeBuffer.y-this._activeBuffer.scrollTop;return n>=0?this._moveCursor(0,-Math.min(n,b.params[0]||1)):this._moveCursor(0,-(b.params[0]||1)),!0}cursorDown(b){let n=this._activeBuffer.scrollBottom-this._activeBuffer.y;return n>=0?this._moveCursor(0,Math.min(n,b.params[0]||1)):this._moveCursor(0,b.params[0]||1),!0}cursorForward(b){return this._moveCursor(b.params[0]||1,0),!0}cursorBackward(b){return this._moveCursor(-(b.params[0]||1),0),!0}cursorNextLine(b){return this.cursorDown(b),this._activeBuffer.x=0,!0}cursorPrecedingLine(b){return this.cursorUp(b),this._activeBuffer.x=0,!0}cursorCharAbsolute(b){return this._setCursor((b.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(b){return this._setCursor(b.length>=2?(b.params[1]||1)-1:0,(b.params[0]||1)-1),!0}charPosAbsolute(b){return this._setCursor((b.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(b){return this._moveCursor(b.params[0]||1,0),!0}linePosAbsolute(b){return this._setCursor(this._activeBuffer.x,(b.params[0]||1)-1),!0}vPositionRelative(b){return this._moveCursor(0,b.params[0]||1),!0}hVPosition(b){return this.cursorPosition(b),!0}tabClear(b){let n=b.params[0];return n===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:n===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(b){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let n=b.params[0]||1;for(;n--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(b){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let n=b.params[0]||1;for(;n--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(b){let n=b.params[0];return n===1&&(this._curAttrData.bg|=536870912),n!==2&&n!==0||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(b,n,c,s=!1,W0=!1){let r=this._activeBuffer.lines.get(this._activeBuffer.ybase+b);r.replaceCells(n,c,this._activeBuffer.getNullCell(this._eraseAttrData()),W0),s&&(r.isWrapped=!1)}_resetBufferLine(b,n=!1){let c=this._activeBuffer.lines.get(this._activeBuffer.ybase+b);c&&(c.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),n),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+b),c.isWrapped=!1)}eraseInDisplay(b,n=!1){let c;switch(this._restrictCursor(this._bufferService.cols),b.params[0]){case 0:for(c=this._activeBuffer.y,this._dirtyRowTracker.markDirty(c),this._eraseInBufferLine(c++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,n);c<this._bufferService.rows;c++)this._resetBufferLine(c,n);this._dirtyRowTracker.markDirty(c);break;case 1:for(c=this._activeBuffer.y,this._dirtyRowTracker.markDirty(c),this._eraseInBufferLine(c,0,this._activeBuffer.x+1,!0,n),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(c+1).isWrapped=!1);c--;)this._resetBufferLine(c,n);this._dirtyRowTracker.markDirty(0);break;case 2:for(c=this._bufferService.rows,this._dirtyRowTracker.markDirty(c-1);c--;)this._resetBufferLine(c,n);this._dirtyRowTracker.markDirty(0);break;case 3:let s=this._activeBuffer.lines.length-this._bufferService.rows;s>0&&(this._activeBuffer.lines.trimStart(s),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-s,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-s,0),this._onScroll.fire(0))}return!0}eraseInLine(b,n=!1){switch(this._restrictCursor(this._bufferService.cols),b.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,n);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,n);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,n)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(b){this._restrictCursor();let n=b.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let c=this._activeBuffer.ybase+this._activeBuffer.y,s=this._bufferService.rows-1-this._activeBuffer.scrollBottom,W0=this._bufferService.rows-1+this._activeBuffer.ybase-s+1;for(;n--;)this._activeBuffer.lines.splice(W0-1,1),this._activeBuffer.lines.splice(c,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(b){this._restrictCursor();let n=b.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let c=this._activeBuffer.ybase+this._activeBuffer.y,s;for(s=this._bufferService.rows-1-this._activeBuffer.scrollBottom,s=this._bufferService.rows-1+this._activeBuffer.ybase-s;n--;)this._activeBuffer.lines.splice(c,1),this._activeBuffer.lines.splice(s,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(b){this._restrictCursor();let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return n&&(n.insertCells(this._activeBuffer.x,b.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(b){this._restrictCursor();let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return n&&(n.deleteCells(this._activeBuffer.x,b.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(b){let n=b.params[0]||1;for(;n--;)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(b){let n=b.params[0]||1;for(;n--;)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(N.DEFAULT_ATTR_DATA));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(b){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=b.params[0]||1;for(let c=this._activeBuffer.scrollTop;c<=this._activeBuffer.scrollBottom;++c){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+c);s.deleteCells(0,n,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(b){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=b.params[0]||1;for(let c=this._activeBuffer.scrollTop;c<=this._activeBuffer.scrollBottom;++c){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+c);s.insertCells(0,n,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(b){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=b.params[0]||1;for(let c=this._activeBuffer.scrollTop;c<=this._activeBuffer.scrollBottom;++c){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+c);s.insertCells(this._activeBuffer.x,n,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(b){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=b.params[0]||1;for(let c=this._activeBuffer.scrollTop;c<=this._activeBuffer.scrollBottom;++c){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+c);s.deleteCells(this._activeBuffer.x,n,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(b){this._restrictCursor();let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return n&&(n.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(b.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(b){let n=this._parser.precedingJoinState;if(!n)return!0;let c=b.params[0]||1,s=A.UnicodeService.extractWidth(n),W0=this._activeBuffer.x-s,r=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(W0),F0=new Uint32Array(r.length*c),w0=0;for(let e=0;e<r.length;){let K0=r.codePointAt(e)||0;F0[w0++]=K0,e+=K0>65535?2:1}let L0=w0;for(let e=1;e<c;++e)F0.copyWithin(L0,0,w0),L0+=w0;return this.print(F0,0,L0),!0}sendDeviceAttributesPrimary(b){return b.params[0]>0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(W.C0.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(W.C0.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(b){return b.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(W.C0.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(W.C0.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(b.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(W.C0.ESC+"[>83;40003;0c")),!0}_is(b){return(this._optionsService.rawOptions.termName+"").indexOf(b)===0}setMode(b){for(let n=0;n<b.length;n++)switch(b.params[n]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(b){for(let n=0;n<b.length;n++)switch(b.params[n]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,H.DEFAULT_CHARSET),this._charsetService.setgCharset(1,H.DEFAULT_CHARSET),this._charsetService.setgCharset(2,H.DEFAULT_CHARSET),this._charsetService.setgCharset(3,H.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(b){for(let n=0;n<b.length;n++)switch(b.params[n]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(b){for(let n=0;n<b.length;n++)switch(b.params[n]){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(),b.params[n]===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(b,n){let c=this._coreService.decPrivateModes,{activeProtocol:s,activeEncoding:W0}=this._coreMouseService,r=this._coreService,{buffers:F0,cols:w0}=this._bufferService,{active:L0,alt:e}=F0,K0=this._optionsService.rawOptions,i=(G0)=>G0?1:2,a=b.params[0];return t=a,$0=n?a===2?4:a===4?i(r.modes.insertMode):a===12?3:a===20?i(K0.convertEol):0:a===1?i(c.applicationCursorKeys):a===3?K0.windowOptions.setWinLines?w0===80?2:w0===132?1:0:0:a===6?i(c.origin):a===7?i(c.wraparound):a===8?3:a===9?i(s==="X10"):a===12?i(K0.cursorBlink):a===25?i(!r.isCursorHidden):a===45?i(c.reverseWraparound):a===66?i(c.applicationKeypad):a===67?4:a===1000?i(s==="VT200"):a===1002?i(s==="DRAG"):a===1003?i(s==="ANY"):a===1004?i(c.sendFocus):a===1005?4:a===1006?i(W0==="SGR"):a===1015?4:a===1016?i(W0==="SGR_PIXELS"):a===1048?1:a===47||a===1047||a===1049?i(L0===e):a===2004?i(c.bracketedPasteMode):0,r.triggerDataEvent(`${W.C0.ESC}[${n?"":"?"}${t};${$0}$y`),!0;var t,$0}_updateAttrColor(b,n,c,s,W0){return n===2?(b|=50331648,b&=-16777216,b|=E.AttributeData.fromColorRGB([c,s,W0])):n===5&&(b&=-50331904,b|=33554432|255&c),b}_extractColor(b,n,c){let s=[0,0,-1,0,0,0],W0=0,r=0;do{if(s[r+W0]=b.params[n+r],b.hasSubParams(n+r)){let F0=b.getSubParams(n+r),w0=0;do s[1]===5&&(W0=1),s[r+w0+1+W0]=F0[w0];while(++w0<F0.length&&w0+r+1+W0<s.length);break}if(s[1]===5&&r+W0>=2||s[1]===2&&r+W0>=5)break;s[1]&&(W0=1)}while(++r+n<b.length&&r+W0<s.length);for(let F0=2;F0<s.length;++F0)s[F0]===-1&&(s[F0]=0);switch(s[0]){case 38:c.fg=this._updateAttrColor(c.fg,s[1],s[3],s[4],s[5]);break;case 48:c.bg=this._updateAttrColor(c.bg,s[1],s[3],s[4],s[5]);break;case 58:c.extended=c.extended.clone(),c.extended.underlineColor=this._updateAttrColor(c.extended.underlineColor,s[1],s[3],s[4],s[5])}return r}_processUnderline(b,n){n.extended=n.extended.clone(),(!~b||b>5)&&(b=1),n.extended.underlineStyle=b,n.fg|=268435456,b===0&&(n.fg&=-268435457),n.updateExtended()}_processSGR0(b){b.fg=N.DEFAULT_ATTR_DATA.fg,b.bg=N.DEFAULT_ATTR_DATA.bg,b.extended=b.extended.clone(),b.extended.underlineStyle=0,b.extended.underlineColor&=-67108864,b.updateExtended()}charAttributes(b){if(b.length===1&&b.params[0]===0)return this._processSGR0(this._curAttrData),!0;let n=b.length,c,s=this._curAttrData;for(let W0=0;W0<n;W0++)c=b.params[W0],c>=30&&c<=37?(s.fg&=-50331904,s.fg|=16777216|c-30):c>=40&&c<=47?(s.bg&=-50331904,s.bg|=16777216|c-40):c>=90&&c<=97?(s.fg&=-50331904,s.fg|=16777224|c-90):c>=100&&c<=107?(s.bg&=-50331904,s.bg|=16777224|c-100):c===0?this._processSGR0(s):c===1?s.fg|=134217728:c===3?s.bg|=67108864:c===4?(s.fg|=268435456,this._processUnderline(b.hasSubParams(W0)?b.getSubParams(W0)[0]:1,s)):c===5?s.fg|=536870912:c===7?s.fg|=67108864:c===8?s.fg|=1073741824:c===9?s.fg|=2147483648:c===2?s.bg|=134217728:c===21?this._processUnderline(2,s):c===22?(s.fg&=-134217729,s.bg&=-134217729):c===23?s.bg&=-67108865:c===24?(s.fg&=-268435457,this._processUnderline(0,s)):c===25?s.fg&=-536870913:c===27?s.fg&=-67108865:c===28?s.fg&=-1073741825:c===29?s.fg&=2147483647:c===39?(s.fg&=-67108864,s.fg|=16777215&N.DEFAULT_ATTR_DATA.fg):c===49?(s.bg&=-67108864,s.bg|=16777215&N.DEFAULT_ATTR_DATA.bg):c===38||c===48||c===58?W0+=this._extractColor(b,W0,s):c===53?s.bg|=1073741824:c===55?s.bg&=-1073741825:c===59?(s.extended=s.extended.clone(),s.extended.underlineColor=-1,s.updateExtended()):c===100?(s.fg&=-67108864,s.fg|=16777215&N.DEFAULT_ATTR_DATA.fg,s.bg&=-67108864,s.bg|=16777215&N.DEFAULT_ATTR_DATA.bg):this._logService.debug("Unknown SGR attribute: %d.",c);return!0}deviceStatus(b){switch(b.params[0]){case 5:this._coreService.triggerDataEvent(`${W.C0.ESC}[0n`);break;case 6:let n=this._activeBuffer.y+1,c=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${W.C0.ESC}[${n};${c}R`)}return!0}deviceStatusPrivate(b){if(b.params[0]===6){let n=this._activeBuffer.y+1,c=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${W.C0.ESC}[?${n};${c}R`)}return!0}softReset(b){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=N.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(b){let n=b.params[0]||1;switch(n){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 c=n%2==1;return this._optionsService.options.cursorBlink=c,!0}setScrollRegion(b){let n=b.params[0]||1,c;return(b.length<2||(c=b.params[1])>this._bufferService.rows||c===0)&&(c=this._bufferService.rows),c>n&&(this._activeBuffer.scrollTop=n-1,this._activeBuffer.scrollBottom=c-1,this._setCursor(0,0)),!0}windowOptions(b){if(!p(b.params[0],this._optionsService.rawOptions.windowOptions))return!0;let n=b.length>1?b.params[1]:0;switch(b.params[0]){case 14:n!==2&&this._onRequestWindowsOptionsReport.fire(x.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(x.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${W.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:n!==0&&n!==2||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),n!==0&&n!==1||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:n!==0&&n!==2||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),n!==0&&n!==1||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(b){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(b){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(b){return this._windowTitle=b,this._onTitleChange.fire(b),!0}setIconName(b){return this._iconName=b,!0}setOrReportIndexedColor(b){let n=[],c=b.split(";");for(;c.length>1;){let s=c.shift(),W0=c.shift();if(/^\d+$/.exec(s)){let r=parseInt(s);if(m(r))if(W0==="?")n.push({type:0,index:r});else{let F0=(0,T.parseColor)(W0);F0&&n.push({type:1,index:r,color:F0})}}}return n.length&&this._onColor.fire(n),!0}setHyperlink(b){let n=b.split(";");return!(n.length<2)&&(n[1]?this._createHyperlink(n[0],n[1]):!n[0]&&this._finishHyperlink())}_createHyperlink(b,n){this._getCurrentLinkId()&&this._finishHyperlink();let c=b.split(":"),s,W0=c.findIndex((r)=>r.startsWith("id="));return W0!==-1&&(s=c[W0].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:s,uri:n}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(b,n){let c=b.split(";");for(let s=0;s<c.length&&!(n>=this._specialColors.length);++s,++n)if(c[s]==="?")this._onColor.fire([{type:0,index:this._specialColors[n]}]);else{let W0=(0,T.parseColor)(c[s]);W0&&this._onColor.fire([{type:1,index:this._specialColors[n],color:W0}])}return!0}setOrReportFgColor(b){return this._setOrReportSpecialColor(b,0)}setOrReportBgColor(b){return this._setOrReportSpecialColor(b,1)}setOrReportCursorColor(b){return this._setOrReportSpecialColor(b,2)}restoreIndexedColor(b){if(!b)return this._onColor.fire([{type:2}]),!0;let n=[],c=b.split(";");for(let s=0;s<c.length;++s)if(/^\d+$/.exec(c[s])){let W0=parseInt(c[s]);m(W0)&&n.push({type:2,index:W0})}return n.length&&this._onColor.fire(n),!0}restoreFgColor(b){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(b){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(b){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,H.DEFAULT_CHARSET),!0}selectCharset(b){return b.length!==2?(this.selectDefaultCharset(),!0):(b[0]==="/"||this._charsetService.setgCharset(P[b[0]],H.CHARSETS[b[1]]||H.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 b=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,b,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=N.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=N.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(b){return this._charsetService.setgLevel(b),!0}screenAlignmentPattern(){let b=new O.CellData;b.content=4194373,b.fg=this._curAttrData.fg,b.bg=this._curAttrData.bg,this._setCursor(0,0);for(let n=0;n<this._bufferService.rows;++n){let c=this._activeBuffer.ybase+this._activeBuffer.y+n,s=this._activeBuffer.lines.get(c);s&&(s.fill(b),s.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(b,n){let c=this._bufferService.buffer,s=this._optionsService.rawOptions;return((W0)=>(this._coreService.triggerDataEvent(`${W.C0.ESC}${W0}${W.C0.ESC}\\`),!0))(b==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:b==='"p'?'P1$r61;1"p':b==="r"?`P1$r${c.scrollTop+1};${c.scrollBottom+1}r`:b==="m"?"P1$r0m":b===" q"?`P1$r${{block:2,underline:4,bar:6}[s.cursorStyle]-(s.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(b,n){this._dirtyRowTracker.markRangeDirty(b,n)}}G.InputHandler=f;let d=class{constructor(b){this._bufferService=b,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(b){b<this.start?this.start=b:b>this.end&&(this.end=b)}markRangeDirty(b,n){b>n&&(k=b,b=n,n=k),b<this.start&&(this.start=b),n>this.end&&(this.end=n)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function m(b){return 0<=b&&b<256}d=z([q(0,M.IBufferService)],d)},844:(V,G)=>{function F(z){for(let q of z)q.dispose();z.length=0}Object.defineProperty(G,"__esModule",{value:!0}),G.getDisposeArrayDisposable=G.disposeArray=G.toDisposable=G.MutableDisposable=G.Disposable=void 0,G.Disposable=class{constructor(){this._disposables=[],this._isDisposed=!1}dispose(){this._isDisposed=!0;for(let z of this._disposables)z.dispose();this._disposables.length=0}register(z){return this._disposables.push(z),z}unregister(z){let q=this._disposables.indexOf(z);q!==-1&&this._disposables.splice(q,1)}},G.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(z){this._isDisposed||z===this._value||(this._value?.dispose(),this._value=z)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}},G.toDisposable=function(z){return{dispose:z}},G.disposeArray=F,G.getDisposeArrayDisposable=function(z){return{dispose:()=>F(z)}}},114:(V,G)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.isChromeOS=G.isLinux=G.isWindows=G.isIphone=G.isIpad=G.isMac=G.getSafariVersion=G.isSafari=G.isLegacyEdge=G.isFirefox=G.isNode=void 0,G.isNode=typeof process<"u"&&"title"in process;let F=G.isNode?"node":navigator.userAgent,z=G.isNode?"node":navigator.platform;G.isFirefox=F.includes("Firefox"),G.isLegacyEdge=F.includes("Edge"),G.isSafari=/^((?!chrome|android).)*safari/i.test(F),G.getSafariVersion=function(){if(!G.isSafari)return 0;let q=F.match(/Version\/(\d+)/);return q===null||q.length<2?0:parseInt(q[1])},G.isMac=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(z),G.isIpad=z==="iPad",G.isIphone=z==="iPhone",G.isWindows=["Windows","Win16","Win32","WinCE"].includes(z),G.isLinux=z.indexOf("Linux")>=0,G.isChromeOS=/\bCrOS\b/.test(F)},226:(V,G,F)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.DebouncedIdleTask=G.IdleTaskQueue=G.PriorityTaskQueue=void 0;let z=F(114);class q{constructor(){this._tasks=[],this._i=0}enqueue(H){this._tasks.push(H),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(H){this._idleCallback=void 0;let U=0,D=0,B=H.timeRemaining(),N=0;for(;this._i<this._tasks.length;){if(U=Date.now(),this._tasks[this._i]()||this._i++,U=Math.max(1,Date.now()-U),D=Math.max(U,D),N=H.timeRemaining(),1.5*D>N)return B-U<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(B-U))}ms`),void this._start();B=N}this.clear()}}class W extends q{_requestCallback(H){return setTimeout(()=>H(this._createDeadline(16)))}_cancelCallback(H){clearTimeout(H)}_createDeadline(H){let U=Date.now()+H;return{timeRemaining:()=>Math.max(0,U-Date.now())}}}G.PriorityTaskQueue=W,G.IdleTaskQueue=!z.isNode&&"requestIdleCallback"in window?class extends q{_requestCallback(H){return requestIdleCallback(H)}_cancelCallback(H){cancelIdleCallback(H)}}:W,G.DebouncedIdleTask=class{constructor(){this._queue=new G.IdleTaskQueue}set(H){this._queue.clear(),this._queue.enqueue(H)}flush(){this._queue.flush()}}},282:(V,G,F)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.updateWindowsModeWrappedState=void 0;let z=F(643);G.updateWindowsModeWrappedState=function(q){let W=q.buffer.lines.get(q.buffer.ybase+q.buffer.y-1),H=W?.get(q.cols-1),U=q.buffer.lines.get(q.buffer.ybase+q.buffer.y);U&&H&&(U.isWrapped=H[z.CHAR_DATA_CODE_INDEX]!==z.NULL_CELL_CODE&&H[z.CHAR_DATA_CODE_INDEX]!==z.WHITESPACE_CELL_CODE)}},734:(V,G)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.ExtendedAttrs=G.AttributeData=void 0;class F{constructor(){this.fg=0,this.bg=0,this.extended=new z}static toColorRGB(q){return[q>>>16&255,q>>>8&255,255&q]}static fromColorRGB(q){return(255&q[0])<<16|(255&q[1])<<8|255&q[2]}clone(){let q=new F;return q.fg=this.fg,q.bg=this.bg,q.extended=this.extended.clone(),q}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}}G.AttributeData=F;class z{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(q){this._ext=q}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(q){this._ext&=-469762049,this._ext|=q<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(q){this._ext&=-67108864,this._ext|=67108863&q}get urlId(){return this._urlId}set urlId(q){this._urlId=q}get underlineVariantOffset(){let q=(3758096384&this._ext)>>29;return q<0?4294967288^q:q}set underlineVariantOffset(q){this._ext&=536870911,this._ext|=q<<29&3758096384}constructor(q=0,W=0){this._ext=0,this._urlId=0,this._ext=q,this._urlId=W}clone(){return new z(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}}G.ExtendedAttrs=z},92:(V,G,F)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.Buffer=G.MAX_BUFFER_SIZE=void 0;let z=F(349),q=F(226),W=F(734),H=F(437),U=F(634),D=F(511),B=F(643),N=F(863),w=F(116);G.MAX_BUFFER_SIZE=4294967295,G.Buffer=class{constructor(L,O,E){this._hasScrollback=L,this._optionsService=O,this._bufferService=E,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=H.DEFAULT_ATTR_DATA.clone(),this.savedCharset=w.DEFAULT_CHARSET,this.markers=[],this._nullCell=D.CellData.fromCharData([0,B.NULL_CELL_CHAR,B.NULL_CELL_WIDTH,B.NULL_CELL_CODE]),this._whitespaceCell=D.CellData.fromCharData([0,B.WHITESPACE_CELL_CHAR,B.WHITESPACE_CELL_WIDTH,B.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new q.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new z.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(L){return L?(this._nullCell.fg=L.fg,this._nullCell.bg=L.bg,this._nullCell.extended=L.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new W.ExtendedAttrs),this._nullCell}getWhitespaceCell(L){return L?(this._whitespaceCell.fg=L.fg,this._whitespaceCell.bg=L.bg,this._whitespaceCell.extended=L.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new W.ExtendedAttrs),this._whitespaceCell}getBlankLine(L,O){return new H.BufferLine(this._bufferService.cols,this.getNullCell(L),O)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let L=this.ybase+this.y-this.ydisp;return L>=0&&L<this._rows}_getCorrectBufferLength(L){if(!this._hasScrollback)return L;let O=L+this._optionsService.rawOptions.scrollback;return O>G.MAX_BUFFER_SIZE?G.MAX_BUFFER_SIZE:O}fillViewportRows(L){if(this.lines.length===0){L===void 0&&(L=H.DEFAULT_ATTR_DATA);let O=this._rows;for(;O--;)this.lines.push(this.getBlankLine(L))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new z.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(L,O){let E=this.getNullCell(H.DEFAULT_ATTR_DATA),M=0,A=this._getCorrectBufferLength(O);if(A>this.lines.maxLength&&(this.lines.maxLength=A),this.lines.length>0){if(this._cols<L)for(let I=0;I<this.lines.length;I++)M+=+this.lines.get(I).resize(L,E);let j=0;if(this._rows<O)for(let I=this._rows;I<O;I++)this.lines.length<O+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new H.BufferLine(L,E)):this.ybase>0&&this.lines.length<=this.ybase+this.y+j+1?(this.ybase--,j++,this.ydisp>0&&this.ydisp--):this.lines.push(new H.BufferLine(L,E)));else for(let I=this._rows;I>O;I--)this.lines.length>O+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(A<this.lines.maxLength){let I=this.lines.length-A;I>0&&(this.lines.trimStart(I),this.ybase=Math.max(this.ybase-I,0),this.ydisp=Math.max(this.ydisp-I,0),this.savedY=Math.max(this.savedY-I,0)),this.lines.maxLength=A}this.x=Math.min(this.x,L-1),this.y=Math.min(this.y,O-1),j&&(this.y+=j),this.savedX=Math.min(this.savedX,L-1),this.scrollTop=0}if(this.scrollBottom=O-1,this._isReflowEnabled&&(this._reflow(L,O),this._cols>L))for(let j=0;j<this.lines.length;j++)M+=+this.lines.get(j).resize(L,E);this._cols=L,this._rows=O,this._memoryCleanupQueue.clear(),M>0.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let L=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,L=!1);let O=0;for(;this._memoryCleanupPosition<this.lines.length;)if(O+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),O>100)return!0;return L}get _isReflowEnabled(){let L=this._optionsService.rawOptions.windowsPty;return L&&L.buildNumber?this._hasScrollback&&L.backend==="conpty"&&L.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(L,O){this._cols!==L&&(L>this._cols?this._reflowLarger(L,O):this._reflowSmaller(L,O))}_reflowLarger(L,O){let E=(0,U.reflowLargerGetLinesToRemove)(this.lines,this._cols,L,this.ybase+this.y,this.getNullCell(H.DEFAULT_ATTR_DATA));if(E.length>0){let M=(0,U.reflowLargerCreateNewLayout)(this.lines,E);(0,U.reflowLargerApplyNewLayout)(this.lines,M.layout),this._reflowLargerAdjustViewport(L,O,M.countRemoved)}}_reflowLargerAdjustViewport(L,O,E){let M=this.getNullCell(H.DEFAULT_ATTR_DATA),A=E;for(;A-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<O&&this.lines.push(new H.BufferLine(L,M))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-E,0)}_reflowSmaller(L,O){let E=this.getNullCell(H.DEFAULT_ATTR_DATA),M=[],A=0;for(let j=this.lines.length-1;j>=0;j--){let I=this.lines.get(j);if(!I||!I.isWrapped&&I.getTrimmedLength()<=L)continue;let T=[I];for(;I.isWrapped&&j>0;)I=this.lines.get(--j),T.unshift(I);let P=this.ybase+this.y;if(P>=j&&P<j+T.length)continue;let h=T[T.length-1].getTrimmedLength(),p=(0,U.reflowSmallerGetNewLineLengths)(T,this._cols,L),x=p.length-T.length,k;k=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+x):Math.max(0,this.lines.length-this.lines.maxLength+x);let f=[];for(let s=0;s<x;s++){let W0=this.getBlankLine(H.DEFAULT_ATTR_DATA,!0);f.push(W0)}f.length>0&&(M.push({start:j+T.length+A,newLines:f}),A+=f.length),T.push(...f);let d=p.length-1,m=p[d];m===0&&(d--,m=p[d]);let b=T.length-x-1,n=h;for(;b>=0;){let s=Math.min(n,m);if(T[d]===void 0)break;if(T[d].copyCellsFrom(T[b],n-s,m-s,s,!0),m-=s,m===0&&(d--,m=p[d]),n-=s,n===0){b--;let W0=Math.max(b,0);n=(0,U.getWrappedLineTrimmedLength)(T,W0,this._cols)}}for(let s=0;s<T.length;s++)p[s]<L&&T[s].setCell(p[s],E);let c=x-k;for(;c-- >0;)this.ybase===0?this.y<O-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+A)-O&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+x,this.ybase+O-1)}if(M.length>0){let j=[],I=[];for(let d=0;d<this.lines.length;d++)I.push(this.lines.get(d));let T=this.lines.length,P=T-1,h=0,p=M[h];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+A);let x=0;for(let d=Math.min(this.lines.maxLength-1,T+A-1);d>=0;d--)if(p&&p.start>P+x){for(let m=p.newLines.length-1;m>=0;m--)this.lines.set(d--,p.newLines[m]);d++,j.push({index:P+1,amount:p.newLines.length}),x+=p.newLines.length,p=M[++h]}else this.lines.set(d,I[P--]);let k=0;for(let d=j.length-1;d>=0;d--)j[d].index+=k,this.lines.onInsertEmitter.fire(j[d]),k+=j[d].amount;let f=Math.max(0,T+A-this.lines.maxLength);f>0&&this.lines.onTrimEmitter.fire(f)}}translateBufferLineToString(L,O,E=0,M){let A=this.lines.get(L);return A?A.translateToString(O,E,M):""}getWrappedRangeForLine(L){let O=L,E=L;for(;O>0&&this.lines.get(O).isWrapped;)O--;for(;E+1<this.lines.length&&this.lines.get(E+1).isWrapped;)E++;return{first:O,last:E}}setupTabStops(L){for(L!=null?this.tabs[L]||(L=this.prevStop(L)):(this.tabs={},L=0);L<this._cols;L+=this._optionsService.rawOptions.tabStopWidth)this.tabs[L]=!0}prevStop(L){for(L==null&&(L=this.x);!this.tabs[--L]&&L>0;);return L>=this._cols?this._cols-1:L<0?0:L}nextStop(L){for(L==null&&(L=this.x);!this.tabs[++L]&&L<this._cols;);return L>=this._cols?this._cols-1:L<0?0:L}clearMarkers(L){this._isClearing=!0;for(let O=0;O<this.markers.length;O++)this.markers[O].line===L&&(this.markers[O].dispose(),this.markers.splice(O--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let L=0;L<this.markers.length;L++)this.markers[L].dispose(),this.markers.splice(L--,1);this._isClearing=!1}addMarker(L){let O=new N.Marker(L);return this.markers.push(O),O.register(this.lines.onTrim((E)=>{O.line-=E,O.line<0&&O.dispose()})),O.register(this.lines.onInsert((E)=>{O.line>=E.index&&(O.line+=E.amount)})),O.register(this.lines.onDelete((E)=>{O.line>=E.index&&O.line<E.index+E.amount&&O.dispose(),O.line>E.index&&(O.line-=E.amount)})),O.register(O.onDispose(()=>this._removeMarker(O))),O}_removeMarker(L){this._isClearing||this.markers.splice(this.markers.indexOf(L),1)}}},437:(V,G,F)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.BufferLine=G.DEFAULT_ATTR_DATA=void 0;let z=F(734),q=F(511),W=F(643),H=F(482);G.DEFAULT_ATTR_DATA=Object.freeze(new z.AttributeData);let U=0;class D{constructor(B,N,w=!1){this.isWrapped=w,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*B);let L=N||q.CellData.fromCharData([0,W.NULL_CELL_CHAR,W.NULL_CELL_WIDTH,W.NULL_CELL_CODE]);for(let O=0;O<B;++O)this.setCell(O,L);this.length=B}get(B){let N=this._data[3*B+0],w=2097151&N;return[this._data[3*B+1],2097152&N?this._combined[B]:w?(0,H.stringFromCodePoint)(w):"",N>>22,2097152&N?this._combined[B].charCodeAt(this._combined[B].length-1):w]}set(B,N){this._data[3*B+1]=N[W.CHAR_DATA_ATTR_INDEX],N[W.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[B]=N[1],this._data[3*B+0]=2097152|B|N[W.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*B+0]=N[W.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|N[W.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(B){return this._data[3*B+0]>>22}hasWidth(B){return 12582912&this._data[3*B+0]}getFg(B){return this._data[3*B+1]}getBg(B){return this._data[3*B+2]}hasContent(B){return 4194303&this._data[3*B+0]}getCodePoint(B){let N=this._data[3*B+0];return 2097152&N?this._combined[B].charCodeAt(this._combined[B].length-1):2097151&N}isCombined(B){return 2097152&this._data[3*B+0]}getString(B){let N=this._data[3*B+0];return 2097152&N?this._combined[B]:2097151&N?(0,H.stringFromCodePoint)(2097151&N):""}isProtected(B){return 536870912&this._data[3*B+2]}loadCell(B,N){return U=3*B,N.content=this._data[U+0],N.fg=this._data[U+1],N.bg=this._data[U+2],2097152&N.content&&(N.combinedData=this._combined[B]),268435456&N.bg&&(N.extended=this._extendedAttrs[B]),N}setCell(B,N){2097152&N.content&&(this._combined[B]=N.combinedData),268435456&N.bg&&(this._extendedAttrs[B]=N.extended),this._data[3*B+0]=N.content,this._data[3*B+1]=N.fg,this._data[3*B+2]=N.bg}setCellFromCodepoint(B,N,w,L){268435456&L.bg&&(this._extendedAttrs[B]=L.extended),this._data[3*B+0]=N|w<<22,this._data[3*B+1]=L.fg,this._data[3*B+2]=L.bg}addCodepointToCell(B,N,w){let L=this._data[3*B+0];2097152&L?this._combined[B]+=(0,H.stringFromCodePoint)(N):2097151&L?(this._combined[B]=(0,H.stringFromCodePoint)(2097151&L)+(0,H.stringFromCodePoint)(N),L&=-2097152,L|=2097152):L=N|4194304,w&&(L&=-12582913,L|=w<<22),this._data[3*B+0]=L}insertCells(B,N,w){if((B%=this.length)&&this.getWidth(B-1)===2&&this.setCellFromCodepoint(B-1,0,1,w),N<this.length-B){let L=new q.CellData;for(let O=this.length-B-N-1;O>=0;--O)this.setCell(B+N+O,this.loadCell(B+O,L));for(let O=0;O<N;++O)this.setCell(B+O,w)}else for(let L=B;L<this.length;++L)this.setCell(L,w);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,w)}deleteCells(B,N,w){if(B%=this.length,N<this.length-B){let L=new q.CellData;for(let O=0;O<this.length-B-N;++O)this.setCell(B+O,this.loadCell(B+N+O,L));for(let O=this.length-N;O<this.length;++O)this.setCell(O,w)}else for(let L=B;L<this.length;++L)this.setCell(L,w);B&&this.getWidth(B-1)===2&&this.setCellFromCodepoint(B-1,0,1,w),this.getWidth(B)!==0||this.hasContent(B)||this.setCellFromCodepoint(B,0,1,w)}replaceCells(B,N,w,L=!1){if(L)for(B&&this.getWidth(B-1)===2&&!this.isProtected(B-1)&&this.setCellFromCodepoint(B-1,0,1,w),N<this.length&&this.getWidth(N-1)===2&&!this.isProtected(N)&&this.setCellFromCodepoint(N,0,1,w);B<N&&B<this.length;)this.isProtected(B)||this.setCell(B,w),B++;else for(B&&this.getWidth(B-1)===2&&this.setCellFromCodepoint(B-1,0,1,w),N<this.length&&this.getWidth(N-1)===2&&this.setCellFromCodepoint(N,0,1,w);B<N&&B<this.length;)this.setCell(B++,w)}resize(B,N){if(B===this.length)return 4*this._data.length*2<this._data.buffer.byteLength;let w=3*B;if(B>this.length){if(this._data.buffer.byteLength>=4*w)this._data=new Uint32Array(this._data.buffer,0,w);else{let L=new Uint32Array(w);L.set(this._data),this._data=L}for(let L=this.length;L<B;++L)this.setCell(L,N)}else{this._data=this._data.subarray(0,w);let L=Object.keys(this._combined);for(let E=0;E<L.length;E++){let M=parseInt(L[E],10);M>=B&&delete this._combined[M]}let O=Object.keys(this._extendedAttrs);for(let E=0;E<O.length;E++){let M=parseInt(O[E],10);M>=B&&delete this._extendedAttrs[M]}}return this.length=B,4*w*2<this._data.buffer.byteLength}cleanupMemory(){if(4*this._data.length*2<this._data.buffer.byteLength){let B=new Uint32Array(this._data.length);return B.set(this._data),this._data=B,1}return 0}fill(B,N=!1){if(N)for(let w=0;w<this.length;++w)this.isProtected(w)||this.setCell(w,B);else{this._combined={},this._extendedAttrs={};for(let w=0;w<this.length;++w)this.setCell(w,B)}}copyFrom(B){this.length!==B.length?this._data=new Uint32Array(B._data):this._data.set(B._data),this.length=B.length,this._combined={};for(let N in B._combined)this._combined[N]=B._combined[N];this._extendedAttrs={};for(let N in B._extendedAttrs)this._extendedAttrs[N]=B._extendedAttrs[N];this.isWrapped=B.isWrapped}clone(){let B=new D(0);B._data=new Uint32Array(this._data),B.length=this.length;for(let N in this._combined)B._combined[N]=this._combined[N];for(let N in this._extendedAttrs)B._extendedAttrs[N]=this._extendedAttrs[N];return B.isWrapped=this.isWrapped,B}getTrimmedLength(){for(let B=this.length-1;B>=0;--B)if(4194303&this._data[3*B+0])return B+(this._data[3*B+0]>>22);return 0}getNoBgTrimmedLength(){for(let B=this.length-1;B>=0;--B)if(4194303&this._data[3*B+0]||50331648&this._data[3*B+2])return B+(this._data[3*B+0]>>22);return 0}copyCellsFrom(B,N,w,L,O){let E=B._data;if(O)for(let A=L-1;A>=0;A--){for(let j=0;j<3;j++)this._data[3*(w+A)+j]=E[3*(N+A)+j];268435456&E[3*(N+A)+2]&&(this._extendedAttrs[w+A]=B._extendedAttrs[N+A])}else for(let A=0;A<L;A++){for(let j=0;j<3;j++)this._data[3*(w+A)+j]=E[3*(N+A)+j];268435456&E[3*(N+A)+2]&&(this._extendedAttrs[w+A]=B._extendedAttrs[N+A])}let M=Object.keys(B._combined);for(let A=0;A<M.length;A++){let j=parseInt(M[A],10);j>=N&&(this._combined[j-N+w]=B._combined[j])}}translateToString(B,N,w,L){N=N??0,w=w??this.length,B&&(w=Math.min(w,this.getTrimmedLength())),L&&(L.length=0);let O="";for(;N<w;){let E=this._data[3*N+0],M=2097151&E,A=2097152&E?this._combined[N]:M?(0,H.stringFromCodePoint)(M):W.WHITESPACE_CELL_CHAR;if(O+=A,L)for(let j=0;j<A.length;++j)L.push(N);N+=E>>22||1}return L&&L.push(N),O}}G.BufferLine=D},634:(V,G)=>{function F(z,q,W){if(q===z.length-1)return z[q].getTrimmedLength();let H=!z[q].hasContent(W-1)&&z[q].getWidth(W-1)===1,U=z[q+1].getWidth(0)===2;return H&&U?W-1:W}Object.defineProperty(G,"__esModule",{value:!0}),G.getWrappedLineTrimmedLength=G.reflowSmallerGetNewLineLengths=G.reflowLargerApplyNewLayout=G.reflowLargerCreateNewLayout=G.reflowLargerGetLinesToRemove=void 0,G.reflowLargerGetLinesToRemove=function(z,q,W,H,U){let D=[];for(let B=0;B<z.length-1;B++){let N=B,w=z.get(++N);if(!w.isWrapped)continue;let L=[z.get(B)];for(;N<z.length&&w.isWrapped;)L.push(w),w=z.get(++N);if(H>=B&&H<N){B+=L.length-1;continue}let O=0,E=F(L,O,q),M=1,A=0;for(;M<L.length;){let I=F(L,M,q),T=I-A,P=W-E,h=Math.min(T,P);L[O].copyCellsFrom(L[M],A,E,h,!1),E+=h,E===W&&(O++,E=0),A+=h,A===I&&(M++,A=0),E===0&&O!==0&&L[O-1].getWidth(W-1)===2&&(L[O].copyCellsFrom(L[O-1],W-1,E++,1,!1),L[O-1].setCell(W-1,U))}L[O].replaceCells(E,W,U);let j=0;for(let I=L.length-1;I>0&&(I>O||L[I].getTrimmedLength()===0);I--)j++;j>0&&(D.push(B+L.length-j),D.push(j)),B+=L.length-1}return D},G.reflowLargerCreateNewLayout=function(z,q){let W=[],H=0,U=q[H],D=0;for(let B=0;B<z.length;B++)if(U===B){let N=q[++H];z.onDeleteEmitter.fire({index:B-D,amount:N}),B+=N-1,D+=N,U=q[++H]}else W.push(B);return{layout:W,countRemoved:D}},G.reflowLargerApplyNewLayout=function(z,q){let W=[];for(let H=0;H<q.length;H++)W.push(z.get(q[H]));for(let H=0;H<W.length;H++)z.set(H,W[H]);z.length=q.length},G.reflowSmallerGetNewLineLengths=function(z,q,W){let H=[],U=z.map((w,L)=>F(z,L,q)).reduce((w,L)=>w+L),D=0,B=0,N=0;for(;N<U;){if(U-N<W){H.push(U-N);break}D+=W;let w=F(z,B,q);D>w&&(D-=w,B++);let L=z[B].getWidth(D-1)===2;L&&D--;let O=L?W-1:W;H.push(O),N+=O}return H},G.getWrappedLineTrimmedLength=F},295:(V,G,F)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.BufferSet=void 0;let z=F(460),q=F(844),W=F(92);class H extends q.Disposable{constructor(U,D){super(),this._optionsService=U,this._bufferService=D,this._onBufferActivate=this.register(new z.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 W.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new W.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(U){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(U),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(U,D){this._normal.resize(U,D),this._alt.resize(U,D),this.setupTabStops(U)}setupTabStops(U){this._normal.setupTabStops(U),this._alt.setupTabStops(U)}}G.BufferSet=H},511:(V,G,F)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.CellData=void 0;let z=F(482),q=F(643),W=F(734);class H extends W.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new W.ExtendedAttrs,this.combinedData=""}static fromCharData(U){let D=new H;return D.setFromCharData(U),D}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,z.stringFromCodePoint)(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(U){this.fg=U[q.CHAR_DATA_ATTR_INDEX],this.bg=0;let D=!1;if(U[q.CHAR_DATA_CHAR_INDEX].length>2)D=!0;else if(U[q.CHAR_DATA_CHAR_INDEX].length===2){let B=U[q.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=B&&B<=56319){let N=U[q.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=N&&N<=57343?this.content=1024*(B-55296)+N-56320+65536|U[q.CHAR_DATA_WIDTH_INDEX]<<22:D=!0}else D=!0}else this.content=U[q.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|U[q.CHAR_DATA_WIDTH_INDEX]<<22;D&&(this.combinedData=U[q.CHAR_DATA_CHAR_INDEX],this.content=2097152|U[q.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}G.CellData=H},643:(V,G)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.WHITESPACE_CELL_CODE=G.WHITESPACE_CELL_WIDTH=G.WHITESPACE_CELL_CHAR=G.NULL_CELL_CODE=G.NULL_CELL_WIDTH=G.NULL_CELL_CHAR=G.CHAR_DATA_CODE_INDEX=G.CHAR_DATA_WIDTH_INDEX=G.CHAR_DATA_CHAR_INDEX=G.CHAR_DATA_ATTR_INDEX=G.DEFAULT_EXT=G.DEFAULT_ATTR=G.DEFAULT_COLOR=void 0,G.DEFAULT_COLOR=0,G.DEFAULT_ATTR=256|G.DEFAULT_COLOR<<9,G.DEFAULT_EXT=0,G.CHAR_DATA_ATTR_INDEX=0,G.CHAR_DATA_CHAR_INDEX=1,G.CHAR_DATA_WIDTH_INDEX=2,G.CHAR_DATA_CODE_INDEX=3,G.NULL_CELL_CHAR="",G.NULL_CELL_WIDTH=1,G.NULL_CELL_CODE=0,G.WHITESPACE_CELL_CHAR=" ",G.WHITESPACE_CELL_WIDTH=1,G.WHITESPACE_CELL_CODE=32},863:(V,G,F)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.Marker=void 0;let z=F(460),q=F(844);class W{get id(){return this._id}constructor(H){this.line=H,this.isDisposed=!1,this._disposables=[],this._id=W._nextId++,this._onDispose=this.register(new z.EventEmitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,q.disposeArray)(this._disposables),this._disposables.length=0)}register(H){return this._disposables.push(H),H}}G.Marker=W,W._nextId=1},116:(V,G)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.DEFAULT_CHARSET=G.CHARSETS=void 0,G.CHARSETS={},G.DEFAULT_CHARSET=G.CHARSETS.B,G.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:"≥","{":"π","|":"≠","}":"£","~":"·"},G.CHARSETS.A={"#":"£"},G.CHARSETS.B=void 0,G.CHARSETS[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"},G.CHARSETS.C=G.CHARSETS[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},G.CHARSETS.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"},G.CHARSETS.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"},G.CHARSETS.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"},G.CHARSETS.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"},G.CHARSETS.E=G.CHARSETS[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"},G.CHARSETS.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"},G.CHARSETS.H=G.CHARSETS[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},G.CHARSETS["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"}},584:(V,G)=>{var F,z,q;Object.defineProperty(G,"__esModule",{value:!0}),G.C1_ESCAPED=G.C1=G.C0=void 0,function(W){W.NUL="\x00",W.SOH="\x01",W.STX="\x02",W.ETX="\x03",W.EOT="\x04",W.ENQ="\x05",W.ACK="\x06",W.BEL="\x07",W.BS="\b",W.HT="\t",W.LF=`
2260
+ If there are Cursor rules (in .cursor/rules/ or .cursorrules), Claude rules (CLAUDE.md), Windsurf rules (.windsurfrules), Cline rules (.clinerules), Goose rules (.goosehints), or Copilot rules (in .github/copilot-instructions.md), make sure to include them. Also, first check if there is an existing ${R3} or ${tS0} file, and if so, update it instead of overwriting it.`;VR5=`Use \`${XU}\` only for files the user should review in the Artifacts tab, such as screenshots, videos, or data exports. Keep build artifacts, transient inspection screenshots, and other temporary scratch/debug files out of that folder. When you mention an artifact saved there, link to it; for image artifacts, prefer Markdown image format using a workspace file URI, for example \`![screenshot](file:///workspace/.amp/in/artifacts/example.png)\`. \`.amp/out\` is not indexed by that tab.`});function AR5(J,Z,Q){let Y=Q.getExecutionProfile(J.name),X=Q.getExecutionProfile(Z.name);if(!Y||!X)return!0;if(Y.serial||X.serial)return!0;let K=Y.resourceKeys(J.input??{}),V=X.resourceKeys(Z.input??{});for(let G of K)for(let F of V)if(G.key===F.key){if(G.mode==="write"||F.mode==="write")return!0}return!1}function jR5(J,Z,Q){for(let Y of Z)if(AR5(J,Y,Q))return!0;return!1}function AV4(J,Z){if(J.length===0)return[];let Q=[],Y=[];for(let X of J){if(jR5(X,Y,Z)){if(Y.length>0)Q.push(Y),Y=[]}Y.push(X)}if(Y.length>0)Q.push(Y);return Q}class $m0{threadID;toolService;callbacks;processingMutex=new fY;runningTools=new Map;cancelledToolUses=new Set;toolMessages=new Map;toolCompletionResolvers=new Map;pendingApprovalsSubscription;writtenBlockedToolUseIds=new Set;disposed=!1;constructor(J,Z,Q){this.threadID=J;this.toolService=Z;this.callbacks=Q;this.pendingApprovalsSubscription=this.toolService.pendingApprovals$.subscribe((Y)=>{this.syncPendingApprovalsToThreadState(Y)})}syncPendingApprovalsToThreadState(J){let Z=J.filter((Y)=>Y.threadId===this.threadID);for(let Y of Z)if(!this.writtenBlockedToolUseIds.has(Y.toolUseId))this.writtenBlockedToolUseIds.add(Y.toolUseId),_.debug("Writing blocked-on-user to thread state",{name:"syncPendingApprovalsToThreadState",threadID:this.threadID,toolUseId:Y.toolUseId,toolName:Y.toolName}),this.callbacks.updateThread({type:"tool:data",toolUse:Y.toolUseId,data:{status:"blocked-on-user",reason:Y.reason,toAllow:Y.toAllow}});let Q=new Set(Z.map((Y)=>Y.toolUseId));for(let Y of this.writtenBlockedToolUseIds)if(!Q.has(Y))this.writtenBlockedToolUseIds.delete(Y)}async onResume(){await this.processingMutex.acquire();try{let J=this.callbacks.getThread(),Z=I7(J,"user");if(!Z)return;for(let Q of Z.content){if(Q.type!=="tool_result")continue;if(Q.run.status==="blocked-on-user"){let K=this.findToolUseById(Q.toolUseID);if(!K)continue;_.debug(`restoring blocked-on-user tool ${K.name} to approval queue`,{name:"onResume",threadID:this.threadID,toolUseID:Q.toolUseID}),this.toolService.restoreApproval({threadId:this.threadID,toolUseId:Q.toolUseID,toolName:K.name,args:K.input??{},reason:Q.run.reason,toAllow:Q.run.toAllow,context:J.mainThreadID?"subagent":"thread"});continue}if(!(!m8(Q.run.status)&&!this.runningTools.has(Q.toolUseID)))continue;let X=this.findToolUseById(Q.toolUseID);if(!X)continue;if(this.isDangerousToResume(X.name)){_.debug(`cancelling dangerous tool ${X.name} on resume`,{name:"onResume",threadID:this.threadID,toolUseID:Q.toolUseID});let K=lC(Q.run);this.callbacks.updateThread({type:"tool:data",toolUse:Q.toolUseID,data:{status:"cancelled",reason:"system:safety",progress:K}});continue}_.debug(`re-invoking tool ${X.name} with ID ${Q.toolUseID}`,{name:"onResume",threadID:this.threadID}),await this.invokeTool(X,Q.userInput)}}finally{this.processingMutex.release()}await this.callbacks.updateFileChanges()}async onAssistantMessageComplete(J){let Z;await this.processingMutex.acquire();try{this.cancelledToolUses.clear(),Z=this.findToolUsesNeedingInvocation(J),_.debug(`saw ${Z.length} tool uses (${Z.map((Q)=>Q.name).join(", ")})`,{name:"onAssistantMessageComplete",threadID:this.threadID})}finally{this.processingMutex.release()}if(Z.length>0)await this.executeToolsWithPlan(Z)}async userProvideInput(J,Z){await this.processingMutex.acquire();try{let Q=this.findToolUseById(J);if(Q&&I8(Q))await this.invokeTool(Q,Z)}finally{this.processingMutex.release()}}async userCancel(J){await this.cancelTool(J,"user:cancelled")}async onNewUserMessage(){this.markAllActiveToolsCancelled(),this.toolService.clearApprovalsForThread(this.threadID),await this.cancelAll("user:interrupted")}async cancelAll(J){await this.processingMutex.acquire();try{this.markAllActiveToolsCancelled(),this.toolService.clearApprovalsForThread(this.threadID),this.cancelUnstartedTools(J),await this.cancelInProgressTools(J)}finally{this.processingMutex.release()}}async findAndCancelToolRun(J,Z){let Q=this.callbacks.getThread();if(!iJ(Q,J))return;await this.cancelTool(J,"user:cancelled",Z)}async cancelToolOnly(J,Z){let Q=this.callbacks.getThread();if(!iJ(Q,J))return;let X=this.getCancelDataForToolRun(J,"user:cancelled"),K=this.toolMessages.get(J);if(K){try{K.next({type:"stop-command"})}catch(V){_.warn("Failed to send stop-command",{toolUseID:J,error:V})}K.complete(),this.toolMessages.delete(J)}_.debug(`cancelToolOnly(${J})`),await this.callbacks.handle({type:"tool:data",toolUse:J,data:X},Z)}getRunningToolIds(){return Array.from(this.runningTools.keys())}hasRunningTools(){return this.runningTools.size>0}isCancelled(J){return this.cancelledToolUses.has(J)}markCancelled(J){this.cancelledToolUses.add(J)}clearCancelled(J){this.cancelledToolUses.delete(J)}sendToolMessage(J,Z){let Q=this.toolMessages.get(J);if(Q)return Q.next(Z),!0;return!1}resolveToolCompletion(J,Z,Q){let Y=this.toolCompletionResolvers.get(J);if(Y){if(Z)Y.resolve();else Y.reject(Q??Error(`Tool failed: ${J}`));this.toolCompletionResolvers.delete(J)}}dispose(){if(this.disposed)return;this.disposed=!0,this.pendingApprovalsSubscription.unsubscribe(),this.toolService.clearApprovalsForThread(this.threadID),this.writtenBlockedToolUseIds.clear();for(let[J,Z]of this.toolCompletionResolvers)try{Z.reject(Error("Orchestrator disposed"))}finally{this.toolCompletionResolvers.delete(J)}for(let[J,Z]of this.toolMessages)try{Z.next({type:"stop-command"}),Z.complete()}catch(Q){_.warn("Failed to cleanup tool messages during disposal",{id:J,error:Q})}this.toolMessages.clear();for(let J of this.runningTools.values())J.abort.abort();this.runningTools.clear(),this.cancelledToolUses.clear()}findToolUsesNeedingInvocation(J){if(J.content.some((G)=>G.type==="tool_use"&&!I8(G)))return[];if(!(J.state?.type==="complete"||J.state?.type==="cancelled"))return[];let Y=this.callbacks.getThread(),X=I7(Y,"user"),K=I7(Y,"assistant"),V=new Set;if(X?.messageId!==void 0&&K?.messageId!==void 0&&X.messageId>K.messageId){for(let G of X.content)if(G.type==="tool_result")V.add(G.toolUseID)}return J.content.filter((G)=>G.type==="tool_use").filter((G)=>!V.has(G.id)&&!this.cancelledToolUses.has(G.id))}async executeToolsWithPlan(J){if(J.length===0)return;let Z=AV4(J,this.toolService);_.debug(`executing ${J.length} tools in ${Z.length} batch(es)`,{name:"executeToolsWithPlan",threadID:this.threadID,batches:Z.map((Q)=>Q.map((Y)=>Y.name))}),await this.executeToolBatchesSequentially(Z)}async executeToolBatchesSequentially(J){for(let Z of J){let Y=(await Promise.allSettled(Z.map((X)=>this.invokeToolAndWait(X,void 0)))).filter((X)=>X.status==="rejected");if(Y.length>0)_.warn(`${Y.length} tool(s) failed in batch`,{name:"executeToolBatchesSequentially",threadID:this.threadID,errors:Y.map((X)=>X.reason)})}}async invokeToolAndWait(J,Z){let Q=new Promise((Y,X)=>{this.toolCompletionResolvers.set(J.id,{resolve:Y,reject:X})});this.invokeTool(J,Z).catch((Y)=>{let X=this.toolCompletionResolvers.get(J.id);if(X)_.debug(`Tool invocation setup failed for ${J.id}`,{name:"invokeToolAndWait",threadID:this.threadID,error:String(Y)}),X.reject(Y),this.toolCompletionResolvers.delete(J.id)}),await Q}async invokeTool(J,Z){if(this.runningTools.has(J.id))throw Error(`(bug) tool invocation already in progress: ${J.id}`);if(!I8(J))throw Error(`(bug) tool use is incomplete: ${J.id}`);let Q=await this.callbacks.getConfig(),Y=yK4(Q.settings?.hooks,{threadID:this.threadID,toolUse:J}),{abortOp:X}=await this.callbacks.applyHookResult(Y);if(X){let F=this.toolCompletionResolvers.get(J.id);if(F)F.resolve(),this.toolCompletionResolvers.delete(J.id);return}let K=J.input;if(this.callbacks.requestPluginToolCall){let F={thread:{id:this.threadID},toolUseID:J.id,tool:J.name,input:J.input??{}},z=await this.callbacks.requestPluginToolCall(F);if(z.action==="error"){_.warn("Plugin returned error action",{tool:J.name,message:z.message,toolUseID:J.id});let q=this.toolCompletionResolvers.get(J.id);if(await this.callbacks.handle({type:"tool:data",toolUse:J.id,data:{status:"error",error:{message:`Plugin error: ${z.message}`,displayMessage:z.message}}}),q)q.resolve(),this.toolCompletionResolvers.delete(J.id);return}if(z.action==="reject-and-continue"){let q=this.toolCompletionResolvers.get(J.id);if(await this.callbacks.handle({type:"tool:data",toolUse:J.id,data:{status:"done",result:`Tool rejected by plugin: ${z.message}`,isFinal:!1}}),q)q.resolve(),this.toolCompletionResolvers.delete(J.id);return}if(z.action==="synthesize"){let q=this.toolCompletionResolvers.get(J.id);if(await this.callbacks.handle({type:"tool:data",toolUse:J.id,data:{status:"done",result:z.result.output,isFinal:!1}}),q)q.resolve(),this.toolCompletionResolvers.delete(J.id);return}if(z.action==="modify")K=z.input,await this.callbacks.handle({type:"tool:processed",toolUse:J.id,newArgs:z.input})}let V=new AbortController,G={abort:V};this.runningTools.set(J.id,G),this.callbacks.updateThread({type:"tool:data",toolUse:J.id,data:{status:"in-progress"}});try{let F=await this.callbacks.getToolRunEnvironment(J.id,V.signal),z=new k0((O)=>{this.toolMessages.set(J.id,O)}),q={...F,toolMessages:z},W=this.toolService.preprocessArgs?.(J.name,K,q);if(W)await this.callbacks.handle({type:"tool:processed",toolUse:J.id,newArgs:W});let H=W??K,U=this.toolService.normalizeToolName(J.name),D=typeof H==="object"&&H!==null?this.toolService.normalizeToolArgs(J.name,H):H,B=typeof D==="object"&&D!==null&&"__isFinal"in D&&typeof D.__isFinal==="boolean"?D.__isFinal:void 0,N=B!==void 0?Object.fromEntries(Object.entries(D).filter(([O])=>O!=="__isFinal")):D,w=this.toolService.invokeTool(U,{args:N,userInput:Z},q).pipe(bW(this.callbacks.getDisposed$()),tD(()=>{this.runningTools.delete(J.id),this.toolMessages.get(J.id)?.complete(),this.toolMessages.delete(J.id)})).subscribe({next:async(O)=>{if(this.cancelledToolUses.has(J.id))return;if(_.debug(`${J.id}, ${O.status}`,{name:"invokeTool",threadID:this.threadID}),m8(O.status)){this.runningTools.delete(J.id),w.unsubscribe();let M=this.toolCompletionResolvers.get(J.id);if(M){if(O.status==="done")M.resolve();else M.reject(Error(`Tool ${O.status}: ${J.id}`));this.toolCompletionResolvers.delete(J.id)}if(O.status==="done"&&O.trackFiles?.length)this.callbacks.trackFiles(O.trackFiles);if(O.status==="done"&&J.name.toLowerCase()===w$.toLowerCase())this.callbacks.onSkillToolComplete(J);if(Q.settings?.hooks){let A=xK4(Q.settings.hooks,{threadID:this.threadID,toolUse:J});await this.callbacks.applyPostHookResult(A,{toolUseID:J.id})}if(this.callbacks.requestPluginToolResult){let A={toolUseID:J.id,tool:J.name,input:J.input??{},status:O.status,error:O.status==="error"?O.error?.message:void 0,output:O.status==="done"&&typeof O.result==="string"?O.result:void 0};try{let j=await this.callbacks.requestPluginToolResult(A);if(j)O={...O,status:j.status,error:j.status==="error"?{message:j.error??"Plugin error"}:void 0,result:j.output}}catch(j){_.debug("Failed to request plugin tool result",{error:j})}}}await this.callbacks.updateFileChanges();let E=B!==void 0&&O.status==="done"&&O.isFinal===void 0?{...O,isFinal:B}:O;await this.callbacks.handle({type:"tool:data",toolUse:J.id,data:E},V.signal)},error:async(O)=>{let E=this.toolCompletionResolvers.get(J.id);if(E)E.reject(O),this.toolCompletionResolvers.delete(J.id);await this.callbacks.handle({type:"tool:data",toolUse:J.id,data:{status:"error",error:{message:"message"in O?O.message:String(O),displayMessage:"displayMessage"in O?O.displayMessage:void 0}}},V.signal)},complete:()=>{let O=this.toolCompletionResolvers.get(J.id);if(!O)return;let E=this.callbacks.getThread(),M=ZY(E).get(J.id)?.run;if(M&&m8(M.status))return;let A;if(this.callbacks.isDisposed())A="Worker disposed";else if(V.signal.aborted)A="Tool aborted";else if(this.cancelledToolUses.has(J.id))A="Tool cancelled";else A="Tool observable completed without terminal state";O.reject(Error(A)),this.toolCompletionResolvers.delete(J.id)}}),L=this.runningTools.get(J.id);if(L)L.subscription=w;NB(V.signal,()=>w.unsubscribe())}catch(F){this.runningTools.delete(J.id);let z=this.toolCompletionResolvers.get(J.id);if(z)z.reject(F),this.toolCompletionResolvers.delete(J.id);throw F}}async cancelTool(J,Z,Q){let Y=this.getCancelDataForToolRun(J,Z),X=this.toolMessages.get(J);if(X){try{X.next({type:"stop-command"})}catch(K){_.warn("Failed to send stop-command",{toolUseID:J,error:K})}X.complete(),this.toolMessages.delete(J)}_.debug(`cancelTool(${J}, ${Z})`),await this.callbacks.handle({type:"tool:data",toolUse:J,data:Y},Q)}getCancelDataForToolRun(J,Z){let Q=this.callbacks.getThread(),Y=ZY(Q).get(J)?.run;return{status:"cancelled",progress:Y?lC(Y):void 0,reason:Z}}markAllActiveToolsCancelled(){let J=this.callbacks.getThread(),Z=I7(J,"assistant");if(Z){let Q=I7(J,"user"),Y=new Map;if(Q){for(let X of Q.content)if(X.type==="tool_result")Y.set(X.toolUseID,X.run)}for(let X of Z.content)if(X.type==="tool_use"&&I8(X)){let K=Y.get(X.id);if(!(K?m8(K.status):!1))this.cancelledToolUses.add(X.id)}}}cancelUnstartedTools(J){let Z=this.callbacks.getThread(),Q=ZY(Z),Y=Z.messages.findLastIndex((K)=>u10(K)),X=Y===-1?Z.messages:Z.messages.slice(Y+1);for(let K of X){if(K.role!=="assistant")continue;for(let V of K.content)if(V.type==="tool_use"&&I8(V)){let G=Q.get(V.id);if(G?.run.status==="blocked-on-user"&&J==="system:disposed")continue;if(!G||G.run.status==="blocked-on-user")this.callbacks.updateThread({type:"tool:data",toolUse:V.id,data:{status:"cancelled",reason:J}})}}}async cancelInProgressTools(J){for(let[Z,Q]of this.runningTools)Q.abort.abort(),Q.subscription?.unsubscribe(),await this.cancelTool(Z,J);this.runningTools.clear()}findToolUseById(J){let Z=this.callbacks.getThread(),Q=I7(Z,"assistant");if(!Q)return;for(let Y of Q.content)if(Y.type==="tool_use"&&Y.id===J)return Y;return}isDangerousToResume(J){return J===p6||J===Bb||J===$Y||J===N9||J===zC}abortToolOp(J){let Z=this.runningTools.get(J);if(Z)Z.abort.abort(),this.runningTools.delete(J)}abortAllTools(){for(let[J,Z]of this.runningTools){let Q=this.toolMessages.get(J);if(Q){try{Q.next({type:"stop-command"}),Q.complete()}catch(Y){_.warn("Failed to send stop-command during disposal",{toolId:J,error:Y})}this.toolMessages.delete(J)}Z.abort.abort()}this.runningTools.clear()}}var jV4=Z0(()=>{E1();bV();a0();T4();EB();og0();m4()});function n$0(J){let Z=[],Q=/@((?:[^\s@\\,;]|\\.)+)/g,Y;while((Y=Q.exec(J))!==null){let X=Y[1],K=RR5(X).replace(/[.,;:!?)}\]]+$/,"");Z.push(K)}return{paths:Z}}function RR5(J){if(J.match(/^[A-Za-z]:[\\]/))return J.replace(/\\(.)/g,(Z,Q)=>{if(Q===" "||Q==="("||Q===")"||Q==="["||Q==="]"||Q==="?"||Q==="*")return Q;return Z});return J.replace(/\\(.)/g,"$1")}async function a$0(){if(!await $J.isConnected())return;let Z=await P1($J.status),Q=Z.selections?.[0],Y=o10(Q),X=Y&&Q?{line:Q.range.startLine+1,column:Q.range.startCharacter}:void 0;return{currentlyVisibleFiles:Z.visibleFiles??[],activeEditor:Z.openFile,cursorLocation:X,cursorLocationLine:void 0,selectionRange:!Y&&Q?{start:{line:Q?.range.startLine+1,column:Q?.range.startCharacter},end:{line:Q?.range.endLine+1,column:Q?.range.endCharacter}}:void 0}}var Jm0=Z0(()=>{E1();TE();AE()});async function RV4(J,{configService:Z,filesystem:Q}){let Y={sentAt:Date.now()},X=e8(J.content),{paths:K}=n$0(X),V=await P1(Z.workspaceRoot);if(!V)return{message:{role:"user",messageId:0,content:J.content,source:J.source,fileMentions:void 0,userState:void 0,agentMode:J.agentMode,meta:Y}};let G=await Z90({fileSystem:Q},K,{searchPaths:[V],shouldIncludeImages:!J.agentMode||Mb(J.agentMode)}),F;if(G?.files&&G.files.length>0){let W=new Set,H=[];for(let U of G.files){let D=T6(U.uri),B=await FQ(Q,D,V,null,W,void 0);for(let N of B){if(!H.some((w)=>w.uri===N.uri))H.push(N);W.add(N.uri)}}if(H.length>0)F=H}let z=await a$0();return{message:{role:"user",messageId:0,content:G?.imageBlocks?.length?[...J.content,...G.imageBlocks]:J.content,source:J.source,fileMentions:G,userState:{...z??pm},agentMode:J.agentMode,discoveredGuidanceFiles:F,meta:Y}}}var IV4=Z0(()=>{U4();E1();L3();x3();jH();m4();PH();Jm0()});var Xm0={};D9(Xm0,{restoreSnapshot:()=>vR5,createSnapshots:()=>yR5});import{execFile as IR5}from"node:child_process";import*as Zm0 from"node:fs";import*as Qm0 from"node:os";import*as Ym0 from"node:path";import{promisify as PR5}from"node:util";function TR5(J,Z){return Promise.race([J,new Promise((Q,Y)=>setTimeout(()=>Y(Error("Snapshot git operation timed out")),Z))])}async function tz(J,Z){let{stdout:Q}=await CR5("git",J,{cwd:Z.cwd,encoding:"utf8",env:{...process.env,...Z.env},maxBuffer:16777216});return Q.trim()}async function SR5(J,Z,Q){let Y=Ym0.join(Qm0.tmpdir(),`amp-snapshot-${Z}-${Q}-${Date.now()}`);try{let X={GIT_INDEX_FILE:Y,GIT_WORK_TREE:J};try{await tz(["read-tree","HEAD"],{cwd:J,env:X})}catch{await tz(["read-tree","--empty"],{cwd:J,env:X})}await tz(["add","-A"],{cwd:J,env:X});let K=await tz(["write-tree"],{cwd:J,env:X}),V=`refs/amp/snapshots/${Z}/${Q}`;return await tz(["update-ref","-m",`amp snapshot ${Z} ${Q}`,V,K],{cwd:J}),{treeOID:K,repoRoot:J}}finally{try{Zm0.unlinkSync(Y)}catch{}}}async function kR5(J){try{return await tz(["rev-parse","--git-dir"],{cwd:J}),!0}catch{return!1}}async function vR5(J){let Z=Ym0.join(Qm0.tmpdir(),`amp-restore-${Date.now()}`);try{let Q={GIT_INDEX_FILE:Z,GIT_WORK_TREE:J.repoRoot};try{await tz(["read-tree","HEAD"],{cwd:J.repoRoot,env:Q})}catch{await tz(["read-tree","--empty"],{cwd:J.repoRoot,env:Q})}await tz(["add","-A"],{cwd:J.repoRoot,env:Q}),await tz(["checkout","--no-overlay",J.treeOID,"--","."],{cwd:J.repoRoot,env:Q})}finally{try{Zm0.unlinkSync(Z)}catch{}}}async function yR5(J,Z,Q){let Y=[];for(let X of J){if(!pF(X))continue;let K=X.fsPath;if(!await kR5(K))continue;try{let V=await TR5(SR5(K,Z,Q),_R5);if(V)Y.push(V)}catch(V){_.debug("Auto-snapshot failed",{workspacePath:K,threadId:Z,messageId:Q,error:V})}}return Y}var CR5,_R5=1e4;var Km0=Z0(()=>{U4();a0();CR5=PR5(IR5)});function xR5(J,Z){let Q=I7(J,"assistant");if(!Q)return{updatedThread:J,uninvoked:[]};let Y=Q.content.filter((V)=>V.type==="tool_use"),X=Z.items.filter((V)=>!Z.wasInvoked(Y,V));if(X.length===0)return{updatedThread:J,uninvoked:[]};return{updatedThread:k9(J,(V)=>{let G=V.messages.findLast((F)=>F.role==="assistant");if(G&&G.role==="assistant"){for(let F of X){let z=tF();G.content.push({type:"tool_use",complete:!0,id:z,name:Z.toolName,input:Z.toToolInput(F)})}if(G.state.type==="complete"&&G.state.stopReason==="end_turn")G.state={...G.state,stopReason:"tool_use"}}V.v++}),uninvoked:X}}class rS{deps;threadID;trackFilesFromHistory(){_.debug("Tracking files from thread history",{name:"trackFilesFromHistory",threadID:this.threadID});for(let J of this.thread.messages){if(J.role==="user"&&J.fileMentions?.files)this.trackFiles(J.fileMentions.files.map((Z)=>Z.uri).filter((Z)=>Z!==void 0));if(J.role==="user"){for(let Z of J.content)if(Z.type==="tool_result"&&Z.run?.status==="done")this.trackFiles(Z.run.trackFiles??[])}}}async getConfig(J){return P1(this.deps.configService.config,J)}async isAutoSnapshotEnabled(){return(await this.getConfig()).settings["experimental.autoSnapshot"]??!1}async restoreToSnapshot(J){}setupSettingsChangeHandlers(){this.setupPermissionsChangeHandler()}setupEphemeralErrorLogging(){this.ephemeralError.pipe(bW(this.disposed$)).subscribe((J)=>{if(J)_.error("ephemeral error",{error:J})})}setupPermissionsChangeHandler(){this.deps.configService.config.pipe(w1((J)=>({permissions:YC(J.settings?.permissions),dangerouslyAllowAll:J.settings?.dangerouslyAllowAll??!1})),g4((J,Z)=>J.dangerouslyAllowAll===Z.dangerouslyAllowAll&&J.permissions===Z.permissions),dx1(1),bW(this.disposed$)).subscribe(()=>{this.reevaluateBlockedTools()})}reevaluateBlockedTools(){if(this.isDisposed)return;for(let J=this.thread.messages.length-1;J>=0;J--){let Z=this.thread.messages[J];if(!Z||Z.role!=="user")continue;let Q=!1;for(let Y of Z.content)if(Y.type==="tool_result"&&Y.run?.status==="blocked-on-user"&&Y.toolUseID)Q=!0,this.checkAndApproveBlockedTool(Y.toolUseID);if(!Q)break}}async checkAndApproveBlockedTool(J){try{let Z=iJ(this.thread,J);if(!Z){_.warn("Tool use block not found for blocked tool",{toolUseID:J});return}let Q=await a40(Z.name,Z.input??{},{configService:this.deps.configService},this.thread.mainThreadID?"subagent":"thread",this.threadID,J);if(Q.permitted)_.info("Auto-approving previously blocked tool due to permission change",{toolName:Z.name,toolUseID:J,threadID:this.threadID}),this.handle({type:"user:tool-input",toolUse:J,value:{accepted:!0}});else _.debug("Tool remains blocked after permission change",{toolName:Z.name,toolUseID:J,reason:Q.reason})}catch(Z){_.warn("Failed to re-evaluate blocked tool",{error:Z,toolUseID:J})}}ops={tools:{},toolMessages:{},inference:null,titleGeneration:null};_state=new V4("initial");state=this._state.pipe(g4(),m6({shouldCountRefs:!0}));handleMutex=new fY;ephemeralError=new V4(void 0);ephemeralErrorRetryAttempt=0;retryCountdownSeconds=new V4(void 0);retryTimer=null;retrySession=0;_inferenceState=new V4("idle");_turnStartTime=new V4(void 0);_turnElapsedMs=new V4(void 0);fileChanges=new V4({files:[]});get inferenceState(){return this._inferenceState.getValue()}toolCallUpdates=new D4;trackedFiles=new QJ;discoveredGuidanceFileURIs=new Set;fs;cachedFileChanges=[];disposed$=new D4;isDisposed=!1;shouldContinueAfterRejection=!1;_pendingSkills=new V4([]);handoffState=new V4(void 0);pendingSkills=this._pendingSkills.pipe(g4(),m6({shouldCountRefs:!0}));_awaitingSkillInvocation=new V4([]);toolOrchestrator;currentAgentSpan=null;currentSpan=null;traceStore;constructor(J,Z){this.deps=J;this.threadID=Z;this.fs=nS({fileChangeTrackerStorage:this.deps.fileChangeTrackerStorage},this.deps.osFileSystem,Z),this.traceStore={startTrace:(Q)=>{this.updateThread({type:"trace:start",span:Q})},recordTraceEvent:(Q,Y)=>{this.updateThread({type:"trace:event",span:Q,event:Y})},recordTraceAttributes:(Q,Y)=>{this.updateThread({type:"trace:attributes",span:Q,attributes:Y})},endTrace:(Q)=>{this.updateThread({type:"trace:end",span:Q})}},this.toolOrchestrator=new $m0(Z,J.toolService,this.createOrchestratorCallbacks())}createTracer(J){return ET0(this.traceStore,J)}getPluginTracer(){let J=this.currentSpan?.id??this.currentAgentSpan?.span;if(!J)return;return this.createTracer(J)}createOrchestratorCallbacks(){return{getThread:()=>this.thread,updateThread:(J)=>this.updateThread(J),handle:(J,Z)=>this.handle(J,Z),getToolRunEnvironment:(J,Z)=>this.getToolRunEnvironment(J,Z),getHooks:async()=>(await this.getConfig()).settings?.hooks,getConfig:()=>this.getConfig(),updateFileChanges:()=>this.updateFileChanges(),trackFiles:(J)=>this.trackFiles(J),isDisposed:()=>this.isDisposed,getDisposed$:()=>this.disposed$,onSkillToolComplete:(J)=>this.onSkillToolComplete(J),applyHookResult:(J)=>Promise.resolve(aS(this,J)),applyPostHookResult:(J,Z)=>Promise.resolve(aS(this,J,Z)),requestPluginToolCall:this.deps.pluginService?(J)=>this.deps.pluginService.event.toolCall(J,this.getPluginTracer()):void 0,requestPluginToolResult:this.deps.pluginService?(J)=>this.deps.pluginService.event.toolResult(J,this.getPluginTracer()):void 0}}async getToolRunEnvironment(J,Z){let Q=await this.getWorkspaceRoot(Z),Y=DC(this.thread),X=iJ(this.thread,J);return{...this.deps,dir:Q,tool:X?.name??"",thread:this.thread,config:await this.getConfig(Z),trackedFiles:new QJ(this.trackedFiles),filesystem:this.fs.trackedFileSystem(J),fileChangeTracker:this.fs.tracker,getAllTrackedChanges:this.getAllTrackedChanges.bind(this),toolUseID:J,todos:Y,toolMessages:new k0(()=>{}),threadEnvironment:this.thread.env?.initial??await this.deps.getThreadEnvironment(),handleThreadDelta:this.handle.bind(this),agentMode:await this.getSelectedAgentMode(),discoveredGuidanceFileURIs:this.discoveredGuidanceFileURIs,dtwHandoffService:void 0}}onSkillToolComplete(J){let Z=J.input;this.thread=k9(this.thread,(Q)=>{if(!Q.activatedSkills)Q.activatedSkills=[];if(!Q.activatedSkills.some((Y)=>Y.name===Z.name))Q.activatedSkills.push({name:Z.name,arguments:Z.arguments})})}status=this.state.pipe(_4((J)=>J==="active"?F5(this._inferenceState.pipe(g4()),this.fileChanges.pipe(g4()),this.ephemeralError,this.handoffState.pipe(g4()),this.retryCountdownSeconds.pipe(g4()),this._turnStartTime.pipe(g4()),this._turnElapsedMs.pipe(g4()),this.toolCallUpdates.pipe(z5(void 0))).pipe(w1(([Z,Q,Y,X,K,V,G])=>({state:J,inferenceState:Z,fileChanges:Q,ephemeralError:Y?{message:Y.message,stack:"stack"in Y?Y.stack:void 0,error:"error"in Y&&Y.error&&typeof Y.error==="object"&&"error"in Y.error?Y.error.error:void 0,retryCountdownSeconds:K}:void 0,handoff:X,turnStartTime:V,turnElapsedMs:G})),bW(this.disposed$)):k0.of({state:J})),m6({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(J){if(!this.threadReadWriter)throw Error(`thread read-writer not initialized for ThreadWorker: ${this.threadID}`);this.threadReadWriter.write(J),this.__testing__setThread(J)}updateThread(J){if(!this.threadReadWriter)throw Error(`thread read-writer not initialized for ThreadWorker: ${this.threadID}`);this.threadReadWriter.update(v04(J,new Date)),this.__testing__setThread(this.threadReadWriter.read())}async acquireThread(){if(!this.threadReadWriter)this.threadReadWriter=await this.deps.threadService.exclusiveSyncReadWriter(this.threadID),this._state.next("active")}__testing__setThread(J){}__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");if(await this.acquireThread(),!await this.isAutoSnapshotEnabled())await this.restoreFileChangesFromBackups();let J=this.thread.messages.at(-1);if(J?.role==="assistant"&&J.state.type==="streaming")this.updateThread({type:"thread:truncate",fromIndex:this.thread.messages.length-1});if(this.trackFilesFromHistory(),this.triggerTitleGeneration(),!this.shouldResumeFromLastMessage(J))return;await this.toolOrchestrator.onResume(),this.setupSettingsChangeHandlers(),this.setupEphemeralErrorLogging(),this.replayLastCompleteMessage()}resumed=!1;shouldResumeFromLastMessage(J){if(of1(J)||sf1(J)&&!this.shouldContinueAfterRejection||u10(J))return this._inferenceState.next("cancelled"),!1;return!0}replayLastCompleteMessage(){let J=this.thread.messages.findLastIndex((Q)=>Q.role==="user"?tf1(Q):Q.role==="assistant"&&Q.state.type==="complete");if(J===-1){if(this.thread.messages.length!==0)throw Error(`(bug) invalid thread: ${this.threadID}`);return}let Z=this.thread.messages[J];switch(Z.role){case"user":if(!Z.interrupted)this.onThreadDelta({type:"user:message",message:Z});break;case"assistant":this.onThreadDelta({type:"assistant:message",message:Z});break}}async handle(J,Z){let Q=J.type==="user:message"&&J.index!==void 0?J.index:void 0;await this.handleMutex.acquire();try{await this.innerHandle(J,Z)}finally{this.handleMutex.release()}if(Q!==void 0)await this.performMessageEditCleanup(Q)}async innerHandle(J,Z){if(this.isDisposed){_.debug(`Skipping ${J.type} - worker disposed.`,{name:"handle queue",threadID:this.threadID});return}if(Z?.aborted){_.debug(`Skipping ${J.type} - signal aborted.`,{name:"handle queue",threadID:this.threadID});return}if(await this.resume(),this.handleCalled=!0,await this.acquireThread(),J.type==="pending-skills"){let X=this._pendingSkills.getValue();this._pendingSkills.next([...X,...J.skills]),_.info("Pending skills set for injection",{threadID:this.threadID,skillNames:J.skills.map((K)=>K.name)});return}let Q=J,Y=[];if(J.type==="user:message"){let X=await RV4(J.message,{configService:this.deps.configService,filesystem:this.fs.fileSystem}),V=(await this.getConfig(Z)).settings["experimental.autoSnapshot"]??!1,G=[];if(V){let F=this.thread.nextMessageId??0,z=await this.getWorkspaceRoot(Z??new AbortController().signal),{createSnapshots:q}=await Promise.resolve().then(() => (Km0(),Xm0));G=await q(z?[z]:[],this.threadID,F)}if(Y=this._pendingSkills.getValue(),Y.length>0)_.info("Pending skills will be injected as info message",{threadID:this.threadID,skillNames:Y.map((F)=>F.name)}),this._pendingSkills.next([]);Q=k9(J,(F)=>{if(F.message=Z5(X.message),G.length>0){if(!F.message.userState)F.message.userState=Z5({currentlyVisibleFiles:[]});F.message.userState.snapshotOIDs=Z5(G)}Z?.throwIfAborted()})}if(Q.type==="assistant:message"||Q.type==="assistant:message-update")Q=this.addNormalizedInputToToolUses(Q);try{if(this.ephemeralError.getValue()!==void 0)this.ephemeralError.next(void 0);let X=this.thread;if(this.updateThread(Q),this.onThreadDelta(Q,X),Y.length>0)await this.injectPendingSkills(Y,Z)}catch(X){if(!V7(X))_.error("Ephemeral error during handle processing",X,{name:"ThreadWorker",threadID:this.threadID}),this.ephemeralError.next(X instanceof Error?X:Error(String(X)));else _.debug(`AbortError caught during handle processing for ${Q.type}.`,{name:"handle queue",threadID:this.threadID})}}handleCalled=!1;addNormalizedInputToToolUses(J){let Z=this.thread.agentMode;if(!J.message.content.some((Y)=>Y.type==="tool_use"))return J;return k9(J,(Y)=>{for(let X of Y.message.content)if(X.type==="tool_use"){if(!X.name){_.warn("Skipping tool_use normalization due to missing name",{threadID:this.threadID});continue}let K=this.deps.toolService.normalizeToolName(X.name);if(K!==X.name)X.normalizedName=K;if(X.input&&typeof X.input==="object"){let G=this.deps.toolService.normalizeToolArgs(X.name,X.input,Z);if(JSON.stringify(G)!==JSON.stringify(X.input))X.normalizedInput=G}if((K!==X.name?K:X.name)===zC&&!X.metadata?.handoffThreadID)X.metadata={...X.metadata,handoffThreadID:g8()}}})}onThreadDelta(J,Z){switch(J.type){case"user:message":{if(this.resetRetryAttempts(),this._turnStartTime.next(Date.now()),this._turnElapsedMs.next(void 0),J.index!==void 0&&Z){let X=Z.messages[J.index];if(X?.role==="user"&&X.userState?.snapshotOIDs&&X.userState.snapshotOIDs.length>0)this.restoreToSnapshot([...X.userState.snapshotOIDs]).catch((K)=>{_.error("Failed to restore edit snapshots",K,{name:"ThreadWorker",threadID:this.threadID})})}if(J.index!==void 0)this.trackedFiles.clear(),this.thread.messages.forEach((X)=>{if(X.role==="user"){for(let K of X.content)if(K.type==="tool_result"&&K.run?.status==="done"&&K.run.trackFiles)this.trackFiles(K.run.trackFiles);if(X.fileMentions?.files)this.trackFiles(X.fileMentions.files.map((K)=>K.uri).filter((K)=>K!==void 0))}});else this.trackFiles(J.message.fileMentions?.files?.map((X)=>X.uri).filter((X)=>X!==void 0)??[]);let Q=this.thread.messages.at(-1)?.messageId??0,Y=e8(J.message.content);this.startAgentSpan(Q),this.runInferenceAndUpdateThread({agentStart:{messageId:Q,messageText:Y}});break}case"user:message-queue:dequeue":{let Q=this.thread.messages.at(-1);if(!Q)break;if(Q.role!=="user")break;this._turnStartTime.next(Date.now()),this._turnElapsedMs.next(void 0),this.trackFiles(Q.fileMentions?.files?.map((K)=>K.uri).filter((K)=>K!==void 0)??[]);let Y=Q.messageId??0,X=e8(Q.content);this.startAgentSpan(Y),this.runInferenceAndUpdateThread({agentStart:{messageId:Y,messageText:X}});break}case"user:tool-input":{this.toolOrchestrator.userProvideInput(J.toolUse,J.value).catch((Q)=>{_.error("userProvideInput failed",{name:"ThreadWorker.handleDelta",threadID:this.threadID,toolUse:J.toolUse,error:Q instanceof Error?Q.message:String(Q)})});break}case"tool:data":{if(this.toolOrchestrator.isCancelled(J.toolUse)){let Y=ZY(this.thread).get(J.toolUse)?.run,X=Y?lC(Y):void 0;this.updateThread({type:"tool:data",toolUse:J.toolUse,data:{status:"cancelled",reason:"user:interrupted",progress:X}});return}let Q=iJ(this.thread,J.toolUse);if(J.data.status==="done"&&Q?.name===eQ){let Y=J.data.result;if("task"in Y&&Y.nextTask){let X=Y7(this.thread),K=this.deps.internalHooks?.onTaskCompleted?.({thread:this.thread,completedTask:Y.task,nextTask:Y.nextTask,usage:X?{totalInputTokens:X.totalInputTokens,maxInputTokens:X.maxInputTokens}:void 0});if(K)aS(this,K)}}if(m8(J.data.status))this.toolOrchestrator.clearCancelled(J.toolUse),this.toolOrchestrator.resolveToolCompletion(J.toolUse,J.data.status==="done",Error(`Tool ${J.data.status}: ${J.toolUse}`));if(Q){let Y=fR5(this.thread,J.toolUse,this.shouldContinueAfterRejection);_.debug(`updated tool_result${Y?" and running inference because all tools completed":""}`,{name:`handleThreadDelta(${J.type}, ${J.toolUse}, ${J.data.status})`,threadID:this.threadID});let X=this.shouldContinueAfterRejection||this._inferenceState.getValue()!=="cancelled";if(Y&&X)this.runInferenceAndUpdateThread()}this.toolCallUpdates.next();break}case"assistant:message":{if(J.message.state.type==="complete"&&J.message.state.stopReason==="tool_use"){let Y=this.thread.messages.at(-1);(this.currentAgentSpan?this.createTracer(this.currentAgentSpan.span):Hz).startActiveSpan("tools",{context:{messageId:Y?.messageId}},async()=>{await this.toolOrchestrator.onAssistantMessageComplete(J.message)}).catch((K)=>{_.error("onAssistantMessageComplete failed",{name:"ThreadWorker.handleDelta",threadID:this.threadID,messageState:J.message.state.type,error:K instanceof Error?K.message:String(K)})})}break}case"assistant:message-update":break;case"user:message-queue:enqueue":{let Q=this._inferenceState.getValue();if(Ob0(this.thread,Q)!=="tool-running"){if(Q==="cancelled"){this.handle({type:"user:message-queue:dequeue"});break}else if(Q==="idle"){let X=this.thread.messages.at(-1);if(X?.role==="assistant"){if(X.state.type==="cancelled"||X.state.type==="error"){this.handle({type:"user:message-queue:dequeue"});break}if(X.state.type==="complete"&&X.state.stopReason!=="tool_use"){this.handle({type:"user:message-queue:dequeue"});break}}else if(X?.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 Q=this.currentAgentSpan.messageId,Y=this.createTracer(this.currentAgentSpan.span);this.stopAgentSpan(this.currentAgentSpan.span),this.deps.pluginService.event.agentEnd({message:this.getMessageText(Q),id:Q,status:"interrupted",messages:q30(this.getMessagesSince(Q))},Y).then((X)=>this.handleAgentEndResult(X)).catch((X)=>_.debug("Failed to emit agent.end",{error:X}))}break}case"thread:truncate":{if(this.toolOrchestrator.cancelAll("system:edited").catch((Q)=>{_.error("Failed to cancel tools on truncate",Q,{name:"ThreadWorker",threadID:this.threadID})}),Z){let Q=Z.messages[J.fromIndex];if(Q?.role==="user"&&Q.userState?.snapshotOIDs&&Q.userState.snapshotOIDs.length>0)for(let Y of Q.userState.snapshotOIDs)Promise.resolve().then(() => (Km0(),Xm0)).then(({restoreSnapshot:X})=>X(Y)).catch((X)=>{_.error("Failed to restore edit snapshots on truncate",X,{name:"ThreadWorker",threadID:this.threadID})});else this.cleanupFileChanges(J.fromIndex).catch((Y)=>{_.error("Failed to cleanup file changes on truncate",Y,{name:"ThreadWorker",threadID:this.threadID})})}break}case"inference:completed":{this.resetRetryAttempts();let Q=J.model?.includes("gpt-5")||J.model?.includes("codex"),Y=!J.usage||J.usage.totalInputTokens===0||J.usage.outputTokens===0;if(Q&&Y)_.warn("[thread-worker] Missing token counts in deep mode inference",{threadID:this.threadID,model:J.model,hasUsage:!!J.usage,inputTokens:J.usage?.inputTokens,outputTokens:J.usage?.outputTokens,totalInputTokens:J.usage?.totalInputTokens,cacheReadInputTokens:J.usage?.cacheReadInputTokens,cacheCreationInputTokens:J.usage?.cacheCreationInputTokens});let X=I7(this.thread,"assistant");if(X&&X.state.type==="complete"&&X.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 K=I7(this.thread,"assistant"),V=K?.state.type==="complete"&&K.state.stopReason==="tool_use";if(K&&V){let F=this.currentAgentSpan?this.createTracer(this.currentAgentSpan.span):Hz,z=K.messageId;F.startActiveSpan("tools",{context:{messageId:z}},async()=>{await this.toolOrchestrator.onAssistantMessageComplete(K)}).catch((q)=>{_.error("onAssistantMessageComplete failed after inference",{name:"ThreadWorker.handleDelta",threadID:this.threadID,messageState:K.state.type,error:q instanceof Error?q.message:String(q)})})}if(K&&K.state.type==="complete"&&K.state.stopReason==="end_turn"){let F=this._turnStartTime.getValue();if(F!==void 0){let z=Date.now()-F;this._turnElapsedMs.next(z),this.thread=k9(this.thread,(q)=>{let W=q.messages.findLast((H)=>H.role==="assistant");if(W&&W.role==="assistant")W.turnElapsedMs=z;q.v++})}if(this._turnStartTime.next(void 0),this.thread.queuedMessages&&this.thread.queuedMessages.length>0)this.handle({type:"user:message-queue:dequeue"});else{aS(this,fK4(this.deps.internalHooks?.onAssistantTurnEnd,{thread:this.thread}));let z=Y7(this.thread);if(z&&this.deps.internalHooks?.onInferenceCompleted){let q=this.deps.internalHooks.onInferenceCompleted({thread:this.thread,usage:{totalInputTokens:z.totalInputTokens,maxInputTokens:z.maxInputTokens},isIdle:!0});aS(this,q)}if(this.currentAgentSpan&&this.currentAgentSpan.messageId!==void 0){let q=this.currentAgentSpan.messageId,W=this.createTracer(this.currentAgentSpan.span);this.stopAgentSpan(this.currentAgentSpan.span),this.deps.pluginService.event.agentEnd({message:this.getMessageText(q),id:q,status:"done",messages:q30(this.getMessagesSince(q))},W).then((H)=>this.handleAgentEndResult(H)).catch((H)=>_.debug("Failed to emit agent.end",{error:H}))}}}break}}}getMessageText(J){let Z=this.thread.messages.find((Q)=>Q.messageId===J);if(Z)return e8(Z.content);return""}getMessagesSince(J){let Z=this.thread.messages.findIndex((Q)=>Q.messageId===J);if(Z===-1)return[];return this.thread.messages.slice(Z)}startAgentSpan(J){let Z=OT0();this.currentAgentSpan={span:Z,messageId:J},this.updateThread({type:"trace:start",span:{name:"agent",id:Z,startTime:new Date().toISOString(),context:{messageId:J}}})}stopAgentSpan(J){if(this.updateThread({type:"trace:end",span:{name:"agent",id:J,endTime:new Date().toISOString()}}),this.currentAgentSpan?.span===J)this.currentAgentSpan=null}handleAgentEndResult(J){if(J.action!=="continue"||!J.userMessage)return;this.handle({type:"user:message",message:{content:[{type:"text",text:J.userMessage}]}}).catch((Z)=>{_.debug("Failed to handle plugin agent.end continue",{error:Z})})}triggerTitleGeneration(){if(this.thread.mainThreadID!==void 0||this.thread.title)return;this.ops.titleGeneration?.abort(),this.ops.titleGeneration=new AbortController;let J=this.ops.titleGeneration.signal;this.getConfig(J).then((Z)=>{if(J.aborted)return;let Q=Z.settings?.["agent.skipTitleGenerationIfMessageContains"],Y=Array.isArray(Q)?Q.filter((K)=>typeof K==="string"):[],X=this.thread.messages.find((K)=>{if(K.role!=="user")return!1;let V=e8(K.content);if(!V)return!1;if(Y.length===0)return!0;return!Y.some((G)=>V.includes(G))});if(_.debug("Checking for message to generate title for",{skipPatterns:Y,rawSkipPatterns:Q,hasFirstEligibleMessage:X!==void 0,firstEligibleMessageId:X?.messageId}),X)this.deps.generateThreadTitle(X,this.thread.id,this.deps.configService,J).then(({title:K,usage:V})=>{if(J.aborted||this.isDisposed)return;if(K!==void 0&&this.thread.title!==K)this.updateThread({type:"title",value:K,usage:V})}).catch((K)=>{if(!V7(K))_.error("generateThreadTitle error",K,{name:"ThreadWorker",threadID:this.threadID});else _.info("Title generation aborted",{firstEligibleMessageId:X?.messageId,threadID:this.threadID})})}).catch((Z)=>{if(!V7(Z))_.error("ThreadWorker title generation config error",Z);else _.info("Title generation aborted in outer catch",{threadID:this.threadID})})}async getWorkspaceRoot(J){let Z=await P1(this.deps.configService.workspaceRoot,J);if(Z)return Z;let Q=this.thread.env?.initial?.trees?.find((Y)=>Y.uri!==void 0)?.uri;return Q?r8(Q):null}async runInferenceAndUpdateThread(J){if(J?.agentStart){let{messageId:Z,messageText:Q}=J.agentStart;try{let Y=await this.deps.pluginService.event.agentStart({message:Q,id:Z},this.currentAgentSpan?this.createTracer(this.currentAgentSpan.span):void 0,{threadID:this.threadID});if(Y.message)this.updateThread({type:"user:message:append-content",messageId:Z,content:[{type:"text",text:Y.message.content}]})}catch(Y){_.debug("Failed to emit agent.start",{error:Y})}}return this.doRunInferenceSetup()}async doRunInferenceSetup(){if(_.debug("runInferenceAndUpdateThread: begin",{threadID:this.threadID,inferenceState:this._inferenceState.getValue(),messageCount:this.thread.messages.length}),this.ops.inference?.abort(),this.ops.inference=null,this._inferenceState.getValue()==="cancelled")this._inferenceState.next("idle");let J=new AbortController;this.ops.inference=J;let Z=this.currentAgentSpan?.span;await this.toolOrchestrator.onNewUserMessage(),await(this.currentAgentSpan?this.createTracer(this.currentAgentSpan.span):Hz).startActiveSpan("inference",{context:{messageId:this.currentAgentSpan?.messageId}},()=>this.doRunInferenceAndUpdateThread(J,Z))}async doRunInferenceAndUpdateThread(J,Z){try{await this.doRunInferenceAndUpdateThreadInner(J,Z)}catch(Q){if(V7(Q)||sI0(Q))return;throw Q}}async doRunInferenceAndUpdateThreadInner(J,Z){let Q=Y7(this.thread);if(Q&&Q.totalInputTokens>=Q.maxInputTokens){let B=Error("Context limit reached");this.ephemeralError.next(B);return}let Y=this.thread.messages.at(-1);if(this.thread.mainThreadID===void 0&&Y?.role==="user"&&this.thread.messages.filter((B)=>B.role==="user").length===1){if(this.deps.getThreadEnvironment)this.deps.getThreadEnvironment().then(async(B)=>{this.updateThread({type:"environment",env:{initial:{...this.thread.env?.initial,...B}}})}).catch((B)=>{_.error("Failed to initialize thread environment",B,{threadID:this.threadID})})}this.triggerTitleGeneration();let K=await this.getConfig(),{model:V,agentMode:G}=FJ(K.settings,this.thread),F=this.thread.messages.at(-1)?.messageId;_.debug("runInferenceAndUpdateThread: starting inference",{threadID:this.threadID,lastUserMessageId:F,selectedModel:V,agentMode:G});let z=this.deps.getServerStatus?await P1(this.deps.getServerStatus().pipe(h5((B)=>B!=="pending")),J.signal):void 0,q=z&&_6(z)?z.user.email:void 0;if(!EE(G,q))throw Error(`Agent mode '${G}' is only available for internal users`);let W={toolService:this.deps.toolService,configService:this.deps.configService,skillService:this.deps.skillService,getThreadEnvironment:this.deps.getThreadEnvironment,filesystem:this.fs.fileSystem,threadService:this.deps.threadService,serverStatus:z},H,U=0,D=Date.now();try{let[B,N,w]=V.match(/(.*?)\/(.*)/)??[],L=OK4(N??"",w??""),{systemPrompt:O,tools:E}=await sz(W,this.thread,{enableTaskList:!1,enableTask:!0,enableOracle:!0,enableChart:!1},{model:w??"",provider:N??"",agentMode:G??"smart"},J.signal),M=LK4(V,K.settings,G),A=L.stream({model:w??"",thread:this.thread,systemPrompt:O,tools:E,configService:this.deps.configService,serverStatus:z,signal:J.signal,reasoningEffort:M});this._inferenceState.next("running"),D=Date.now(),_.debug("ThreadWorker inference stream started",{threadID:this.threadID,lastUserMessageId:F,selectedModel:V,agentMode:G});for await(let j of A)U++,H=j,await this.handle({type:"assistant:message-update",message:j});if(_.debug("ThreadWorker inference stream finished",{threadID:this.threadID,streamEventCount:U,durationMs:Date.now()-D,lastMessageState:H?.state.type,lastMessageId:H?.messageId}),H){let j=H.state.type==="streaming",I=H.content.some((T)=>T.type==="tool_use"&&T.complete&&Object.keys(T.input??{}).length===0);if(j||I)_.warn("Stream ended with incomplete message",{name:"ThreadWorker.runInference",threadID:this.threadID,streamEventCount:U,durationMs:Date.now()-D,messageState:H.state.type,stopReason:H.state.type==="complete"?H.state.stopReason:void 0,contentBlocks:H.content.map((T)=>({type:T.type,...T.type==="tool_use"?{name:T.name,complete:T.complete,inputKeys:Object.keys(T.input??{})}:{},...T.type==="text"?{textLength:T.text.length}:{}}))})}await this.handle({type:"inference:completed",model:H?.usage?.model??V,usage:H?.usage})}catch(B){if(_.debug("ThreadWorker inference stream error",{threadID:this.threadID,error:B instanceof Error?B.message:String(B),errorName:B instanceof Error?B.name:void 0,streamEventCount:U,durationMs:Date.now()-D,lastMessageState:H?.state.type,lastMessageId:H?.messageId}),!(V7(B)||sI0(B))){let N=B instanceof Error?B:Error(String(B));if(pz({message:N.message})){this.ephemeralError.next(N);return}let w="status"in N&&typeof N.status==="number"?N.status:void 0;if(B20({message:N.message,status:w})){let L=this.getRetryDelaySeconds();if(L!==void 0)this.startRetryCountdown(L)}this.ephemeralError.next(N)}if(H&&H.messageId){let N=await this.deps.pluginService.event.agentEnd({message:e8(H.content),id:H.messageId,status:"error",messages:q30(this.getMessagesSince(H.messageId))},Z?this.createTracer(Z):void 0);if(Z)this.stopAgentSpan(Z);this.handleAgentEndResult(N)}else if(Z)this.stopAgentSpan(Z);return}finally{if(this.ops.inference===J)this.ops.inference=null,this._inferenceState.next("idle")}}async findAndCancelToolRun(J,Z){this.cancelInference(),await this.toolOrchestrator.findAndCancelToolRun(J,Z)}async cancelToolOnly(J,Z){await this.toolOrchestrator.cancelToolOnly(J,Z)}invokeBashTool(J,Z,Q){return new k0((Y)=>{let X,K,V,F=((q)=>{return NB(q,()=>{if(_.warn("Manual bash abort -> unsubscribe",{threadID:this.threadID}),V?.unsubscribe(),K?.unsubscribe(),Y?.complete(),X)this.handleManualBashInvocation(J,{status:"cancelled",progress:lC(X)},Q)})})(Z);return(async()=>{try{if(Z.aborted){Y.error(Error("Operation was aborted"));return}let q=await this.getWorkspaceRoot(Z),W=await this.getConfig(Z);if(this.isDisposed){Y.complete();return}let H={...this.deps,dir:q,tool:p6,thread:this.thread,config:W,trackedFiles:new QJ(this.trackedFiles),filesystem:Xp1(this.fs.fileSystem),fileChangeTracker:this.fs.tracker,getAllTrackedChanges:this.getAllTrackedChanges.bind(this),toolUseID:tF(),todos:[],threadEnvironment:this.thread.env?.initial??await this.deps.getThreadEnvironment(),handleThreadDelta:this.handle.bind(this),discoveredGuidanceFileURIs:this.discoveredGuidanceFileURIs,userInitiated:!0};K=this.deps.toolService.invokeTool(p6,{args:J,userInput:{accepted:!0}},H).subscribe({next:(U)=>{X=U,Y.next(U)},error:(U)=>{Y.error(U)},complete:()=>{if(X)this.handleManualBashInvocation(J,X,Q);Y.complete()}}),V=this.disposed$.subscribe(()=>{F(),K?.unsubscribe(),Y?.complete()})}catch(q){Y.error(q)}})(),()=>{F(),K?.unsubscribe(),V?.unsubscribe()}})}async handleManualBashInvocation(J,Z,Q){await this.handle({type:"info:manual-bash-invocation",args:J,toolRun:Z,hidden:Q})}async cleanupThreadBackups(J){try{await this.fs.tracker.cleanupBackups(),_.debug(`Cleaned up backup files for thread ${J}`,{threadID:J})}catch(Z){_.error("Error cleaning up thread backups",Z,{threadID:J})}}async cancel(){_.debug("cancel: aborting inference operation and tools"),this.cancelInference(),await this.toolOrchestrator.cancelAll("user:cancelled"),await this.handle({type:"cancelled"},void 0)}cancelInference(){if(this.ops.inference)this.ops.inference.abort(Error(rI0.USER_CANCELLED)),this.ops.inference=null;this._inferenceState.next("cancelled"),this._turnStartTime.next(void 0),this._turnElapsedMs.next(void 0)}static BASE_RETRY_SECONDS=5;static MAX_RETRY_SECONDS=60;static MAX_AUTO_RETRIES=5;getRetryDelaySeconds(){if(this.ephemeralErrorRetryAttempt>=rS.MAX_AUTO_RETRIES)return;let J=rS.BASE_RETRY_SECONDS*2**this.ephemeralErrorRetryAttempt;return Math.min(J,rS.MAX_RETRY_SECONDS)}async retry(){if(_.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 J=this.thread.messages.at(-1);if(J?.role==="assistant"&&(J.state.type!=="complete"||J.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(J){this.clearRetryCountdown();let Z=this.retrySession,Q=Date.now()+J*1000;this.retryCountdownSeconds.next(J),this.retryTimer=setInterval(()=>{if(Z!==this.retrySession)return;let Y=Math.max(0,Math.ceil((Q-Date.now())/1000));if(Y<=0)this.clearRetryCountdown(),this.retry().catch((X)=>{_.error("Auto-retry failed",{error:X})});else this.retryCountdownSeconds.next(Y)},1000)}addPendingSkill(J){_.debug("addPendingSkill",{threadID:this.threadID,skillName:J.name});let Z=this._pendingSkills.getValue();if(!Z.some((Q)=>Q.name===J.name))this._pendingSkills.next([...Z,J])}removePendingSkill(J){_.debug("removePendingSkill",{threadID:this.threadID,skillName:J});let Z=this._pendingSkills.getValue();this._pendingSkills.next(Z.filter((Q)=>Q.name!==J))}clearPendingSkills(){_.debug("clearPendingSkills",{threadID:this.threadID}),this._pendingSkills.next([])}getPendingSkills(){return this._pendingSkills.getValue()}setTestEphemeralError(J){this.ephemeralError.next(J)}trackFiles(J){for(let Z of J)this.trackedFiles.add(Z)}async restoreFileChangesFromBackups(){try{let J=await this.fs.tracker.restoreFromBackups();_.debug(`Restored ${J.totalBackups} backup files from disk`),await this.updateFileChanges()}catch(J){_.error("Error restoring file changes",J,{threadID:this.threadID})}}async revertFileChanges(J){await this.fs.tracker.revertAll(J),await this.updateFileChanges()}async getAllTrackedChanges(){return this.fs.tracker.getAllRecords()}async cleanupForkThreads(J=this.thread.messages.length){await this.acquireThread(),this.updateThread({type:"thread:truncate",fromIndex:J})}async getToolUsesToRevert(J=this.thread.messages.length){let Z=new Set;this.thread.messages.slice(0,J).forEach((X)=>{if(X.role==="user"){for(let K of X.content)if(K.type==="tool_result")Z.add(K.toolUseID)}else for(let K of X.content)if(K.type==="tool_use")Z.add(K.id)});let Q=new Set,Y=await this.fs.tracker.getAllRecords();for(let[X]of Y.entries())if(!Z.has(X))Q.add(X);return Q}async getFilesAffectedByTruncation(J){let Z=await this.getToolUsesToRevert(J);return Z.size>0?this.fs.tracker.getFilesForToolUses(Z):[]}async cleanupFileChanges(J=this.thread.messages.length){let Z=await this.getToolUsesToRevert(J);if(Z.size===0)return;await this.fs.tracker.revertChanges(Z),await this.updateFileChanges()}async performMessageEditCleanup(J){if(await this.toolOrchestrator.cancelAll("system:edited"),!await this.isAutoSnapshotEnabled())await this.cleanupFileChanges();await this.cleanupForkThreads()}async updateFileChanges(){if(await this.isAutoSnapshotEnabled())return;this.cachedFileChanges=await W80(this.fs.tracker),this.fileChanges.next({files:this.cachedFileChanges})}async injectPendingSkills(J,Z){let Q=J.map((Y)=>Y.name);_.info("Adding info message to prompt skill invocation",{threadID:this.threadID,skillNames:Q}),this._awaitingSkillInvocation.next(J),this.thread=k9(this.thread,(Y)=>{let X=Y.nextMessageId??0;Y.nextMessageId=X+1,Y.messages.push({role:"info",messageId:X,content:[{type:"text",text:`You MUST call the ${w$} tool to load: ${Q.join(", ")}. Do this immediately before responding.`}]}),Y.v++})}checkAndAppendAwaitedSkills(){let J=this._awaitingSkillInvocation.getValue();if(J.length===0)return;this._awaitingSkillInvocation.next([]);let{updatedThread:Z,uninvoked:Q}=xR5(this.thread,{toolName:w$,items:J,wasInvoked:(Y,X)=>Y.some((K)=>K.name===w$&&K.input.name===X.name),toToolInput:(Y)=>({name:Y.name,arguments:Y.arguments})});if(Q.length>0)_.info("Skills not invoked by model, appending tool_use blocks",{threadID:this.threadID,uninvokedSkills:Q.map((Y)=>Y.name)}),this.thread=Z}async executeHandoff(J){_.info("Executing handoff",{threadID:this.threadID,goal:J}),this.handoffState.next({goal:J});try{let{threadWorkerService:Z}=await Promise.resolve().then(() => (KU(),CV4)),Q={toolService:this.deps.toolService,configService:this.deps.configService,skillService:this.deps.skillService,getThreadEnvironment:this.deps.getThreadEnvironment,filesystem:this.fs.fileSystem,threadService:this.deps.threadService},{threadID:Y}=await Z.handoff(this.deps,{threadID:this.threadID,goal:J,images:[],mode:"initial",agentMode:this.thread.agentMode,queuedMessages:this.thread.queuedMessages,clearQueuedMessages:!0,blockIndex:0,buildSystemPromptDeps:Q});_.info("Handoff thread created and running in background",{fromThreadID:this.threadID,newThreadID:Y,goal:J}),this.handoffState.next({goal:J,result:{newThreadID:Y}})}catch(Z){_.error("Handoff failed",Z,{threadID:this.threadID,goal:J}),this.handoffState.next({goal:J,result:{error:Z instanceof Error?Z.message:String(Z)}})}}continueInferenceAfterRejection(J=!0){this.shouldContinueAfterRejection=J}getTurnStartTime(){return this._turnStartTime.getValue()}setTurnStartTime(J){this._turnStartTime.next(J)}async asyncDispose(){if(this.isDisposed)return;if(_.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 J=await this.getConfig(),{agentMode:Z}=FJ(J.settings,this.thread);return Z}}function fR5(J,Z,Q=!1){let Y=I7(J,"assistant");if(!Y||Y.state.type!=="complete"||Y.state.stopReason!=="tool_use")return!1;let X=Y.content.filter((F)=>F.type==="tool_use").map((F)=>F.id);if(Z&&!X.includes(Z))return _.debug(`tool:data for orphaned tool_use ${Z} - ignoring for inference`,{name:"shouldRunInferenceWithToolData",threadID:J.id}),!1;if(X.length===0)return!1;let K=ZY(J);if(!X.every((F)=>{let z=K.get(F);if(!z?.run||!m8(z.run.status))return!1;let q=z.run.status;if(q==="cancelled"){let W=z.run.reason;return W?!W.startsWith("user:"):!1}if(q==="rejected-by-user")return Q;return!0}))return!1;if(X.every((F)=>{let z=K.get(F);if(!z||z.run.status!=="done")return!1;return z.run.isFinal===!0}))return!1;return!0}var PV4=Z0(()=>{U4();E1();VJ();bV();a0();EK4();nH();x3();lX();o40();DE();YJ();Ac();GY();T4();EB();H80();og0();JN();xA();m4();GT();jV4();MT0();IV4()});var CV4={};D9(CV4,{threadWorkerService:()=>u9});class TV4{threadWorkers=new Ej0;async getOrCreateForThread(J,Z){let Q=this.threadWorkers.get(Z);if(!Q){if(Q=new rS(J,Z),this.threadWorkers.set(Z,Q),this.threadWorkers.size>25)_.info("Many active thread workers detected",{name:"ThreadWorkerService.memoryCheck",threadID:Z,totalWorkerCount:this.threadWorkers.size})}return Vm0.record(this.threadWorkers.size),Q}async createThreadWorker(J,Z){let Q=await this.getOrCreateForThread(J,Z);return await Q.resume(),Q}async seedThreadMessages(J,Z,Q,Y){let X=await J.threadService.exclusiveSyncReadWriter(Z),K=Y?Q.map((F)=>F.role==="user"?{...F,agentMode:Y}:F):[...Q],V=K.length>0?Math.max(...K.map((F)=>F.messageId))+1:0,G=X.read();X.write({...G,agentMode:Y??G.agentMode,messages:K,nextMessageId:V,v:G.v+1}),await X.asyncDispose()}async applyParentRelationship(J,Z,Q,Y){let X=Date.now(),{threadID:K,type:V,messageIndex:G,blockIndex:F,comment:z}=Y;await Z.handle({type:"relationship",relationship:{threadID:K,type:V,role:"child",messageIndex:G,blockIndex:F,createdAt:X,comment:z}});let q={threadID:Q,type:V,role:"parent",messageIndex:G,blockIndex:F,createdAt:X,comment:z},W=this.threadWorkers.get(K);if(W)await W.handle({type:"relationship",relationship:q});else{let H=await J.threadService.exclusiveSyncReadWriter(K);H.update((U)=>{if(!U.relationships)U.relationships=[];if(!U.relationships.some((B)=>B.threadID===q.threadID&&B.type===q.type&&B.role===q.role))U.relationships.push(q)}),await H.asyncDispose()}}async inheritVisibilityIfNeeded(J,Z,Q){if(Z.type==="handoff")await UJ4(J.threadService,Z.threadID,Q)}async sendInitialUserMessage(J,Z){let Q=typeof Z==="string"?[{type:"text",text:Z}]:[...Z];await J.handle({type:"user:message",message:{content:Q}})}async setDraftContent(J,Z){let Q=typeof Z==="string"?Z:[...Z];await J.handle({type:"draft",content:Q})}async setPendingNavigation(J,Z){let Q=this.threadWorkers.get(J);if(Q)await Q.handle({type:"setPendingNavigation",threadID:Z})}async transferQueuedMessages(J,Z){for(let Q of Z)await J.handle({type:"user:message-queue:enqueue",message:Q.queuedMessage})}async createThread(J,Z){let Q=Z?.newThreadID??g8(),Y=Z?.agentMode,X=!1;if(Z?.seededMessages)await this.seedThreadMessages(J,Q,Z.seededMessages,Y),X=!0;let K=await this.createThreadWorker(J,Q);if(K.thread.messages.length>0&&!X)return _.info("createThread called for existing thread, returning existing worker",{threadID:Q,messageCount:K.thread.messages.length}),{threadID:Q,worker:K};if(Y&&!X)await K.handle({type:"agent-mode",mode:Y});if(Z?.parent)await this.applyParentRelationship(J,K,Q,Z.parent),await this.inheritVisibilityIfNeeded(J,Z.parent,Q);if(Z?.initialUserMessage){if(X)throw Error("initialUserMessage cannot be set when seededMessages is provided");await this.sendInitialUserMessage(K,Z.initialUserMessage)}if(Z?.draftContent){if(X)throw Error("draftContent cannot be set when seededMessages is provided");await this.setDraftContent(K,Z.draftContent)}if(Z?.navigate&&Z?.parent)await this.setPendingNavigation(Z.parent.threadID,Q);if(Z?.queuedMessages)await this.transferQueuedMessages(K,Z.queuedMessages);return{threadID:Q,worker:K}}async handoff(J,Z){let Q=await this.createThreadWorker(J,Z.threadID),Y=Q.thread,X=Z.images??[],K=Z.signal??new AbortController().signal,{content:V}=await H20({thread:Y,goal:Z.goal,images:X,deps:{configService:J.configService,buildSystemPromptDeps:Z.buildSystemPromptDeps,signal:K,filesystem:Z.filesystem,deadline:Z.deadline}}),G=typeof V==="string"?V:V.filter((q)=>q.type==="text"||q.type==="image"),F={threadID:Z.threadID,type:"handoff",messageIndex:Z.messageIndex??(Y.messages.length?Y.messages.length-1:void 0),blockIndex:Z.blockIndex,comment:Z.comment??Z.goal},z=await this.createThread(J,{newThreadID:Z.newThreadID,agentMode:Z.agentMode??Y.agentMode,parent:F,navigate:Z.navigate,queuedMessages:Z.queuedMessages??Y.queuedMessages,initialUserMessage:Z.mode==="initial"?G:void 0,draftContent:Z.mode==="draft"?G:void 0});if(Z.clearQueuedMessages&&Y.queuedMessages?.length)await Q.handle({type:"user:message-queue:discard"});return z}get workers(){return this.threadWorkers.observable}get statuses(){return this.threadWorkers.observable.pipe(_4((J)=>J.size===0?k0.of({}):F5(...Array.from(J.values()).map((Z)=>Z.status.pipe(w1((Q)=>[Z.threadID,Z.threadReadWriter?ES(Z.thread,Q):void 0])))).pipe(w1((Z)=>Object.fromEntries(Z)))),kV(25),m6())}get(J){return this.threadWorkers.get(J)}prettyPrintToolRun(J,Z){let Q=this.threadWorkers.get(J);if(!Q)throw Error(`No worker found for thread ${J}`);for(let Y of Q.thread.messages)for(let X of Y.content)if(X.type==="tool_result"&&X.toolUseID===Z)return o04(X.run);throw Error(`Tool run not found for thread ${J} and tool use ${Z}`)}async cancelToolOnly(J,Z){await this.threadWorkers.get(J)?.cancelToolOnly(Z)}async cancel(J){await this.threadWorkers.get(J)?.cancel()}async dispose(J){let Z=this.threadWorkers.get(J);if(Z)await Z.cancel(),await Z.asyncDispose(),this.threadWorkers.delete(J),Vm0.record(this.threadWorkers.size)}async retry(J){let Z=this.threadWorkers.get(J);if(!Z)throw Error(`No active worker for thread ${J}`);await Z.retry()}async revertFileChanges(J,Z){let Q=this.threadWorkers.get(J);if(!Q)throw Error(`No active worker for thread ${J}`);await Q.revertFileChanges(Z)}async getFilesAffectedByTruncation(J,Z){let Q=this.threadWorkers.get(J);if(!Q)throw Error(`No active worker for thread ${J}`);return Q.getFilesAffectedByTruncation(Z)}async cleanupThreadBackups(J,Z){let Q=this.threadWorkers.get(Z);if(Q)await Q.fs.tracker.cleanupBackups();else try{await new sV(J.osFileSystem).cleanup(Z),_.debug(`Cleaned up backup files for thread ${Z}`,{threadID:Z})}catch(Y){_.error("Error cleaning up thread backups",Y,{threadID:Z})}}async disposeAll(){await Promise.all(Array.from(this.threadWorkers.values()).map(async(J)=>await J.asyncDispose())),this.threadWorkers.clear(),Vm0.record(0)}}var _V4,uR5,Vm0,u9;var KU=Z0(()=>{E1();a0();r04();HJ4();l_();m4();DJ4();PV4();_V4=H4(w4(),1),uR5=_V4.metrics.getMeter("thread-worker-service"),Vm0=uR5.createGauge("thread_worker_count",{description:"Number of active thread workers"});u9=new TV4});var Fm0=u((vV4)=>{Object.defineProperty(vV4,"__esModule",{value:!0});vV4.dynamicAnchor=void 0;var Gm0=d6(),bR5=rX(),SV4=dh(),hR5=t60(),gR5={keyword:"$dynamicAnchor",schemaType:"string",code:(J)=>kV4(J,J.schema)};function kV4(J,Z){let{gen:Q,it:Y}=J;Y.schemaEnv.root.dynamicAnchors[Z]=!0;let X=Gm0._`${bR5.default.dynamicAnchors}${(0,Gm0.getProperty)(Z)}`,K=Y.errSchemaPath==="#"?Y.validateName:mR5(J);Q.if(Gm0._`!${X}`,()=>Q.assign(X,K))}vV4.dynamicAnchor=kV4;function mR5(J){let{schemaEnv:Z,schema:Q,self:Y}=J.it,{root:X,baseId:K,localRefs:V,meta:G}=Z.root,{schemaId:F}=Y.opts,z=new SV4.SchemaEnv({schema:Q,schemaId:F,root:X,baseId:K,localRefs:V,meta:G});return SV4.compileSchema.call(Y,z),(0,hR5.getValidate)(J,z)}vV4.default=gR5});var zm0=u((bV4)=>{Object.defineProperty(bV4,"__esModule",{value:!0});bV4.dynamicRef=void 0;var xV4=d6(),dR5=rX(),fV4=t60(),cR5={keyword:"$dynamicRef",schemaType:"string",code:(J)=>uV4(J,J.schema)};function uV4(J,Z){let{gen:Q,keyword:Y,it:X}=J;if(Z[0]!=="#")throw Error(`"${Y}" only supports hash fragment reference`);let K=Z.slice(1);if(X.allErrors)V();else{let F=Q.let("valid",!1);V(F),J.ok(F)}function V(F){if(X.schemaEnv.root.dynamicAnchors[K]){let z=Q.let("_v",xV4._`${dR5.default.dynamicAnchors}${(0,xV4.getProperty)(K)}`);Q.if(z,G(z,F),G(X.validateName,F))}else G(X.validateName,F)()}function G(F,z){return z?()=>Q.block(()=>{(0,fV4.callRef)(J,F),Q.let(z,!0)}):()=>(0,fV4.callRef)(J,F)}}bV4.dynamicRef=uV4;bV4.default=cR5});var mV4=u((gV4)=>{Object.defineProperty(gV4,"__esModule",{value:!0});var iR5=Fm0(),nR5=I5(),aR5={keyword:"$recursiveAnchor",schemaType:"boolean",code(J){if(J.schema)(0,iR5.dynamicAnchor)(J,"");else(0,nR5.checkStrictMode)(J.it,"$recursiveAnchor: false is ignored")}};gV4.default=aR5});var dV4=u((pV4)=>{Object.defineProperty(pV4,"__esModule",{value:!0});var rR5=zm0(),sR5={keyword:"$recursiveRef",schemaType:"string",code:(J)=>(0,rR5.dynamicRef)(J,J.schema)};pV4.default=sR5});var lV4=u((cV4)=>{Object.defineProperty(cV4,"__esModule",{value:!0});var eR5=Fm0(),$I5=zm0(),JI5=mV4(),ZI5=dV4(),QI5=[eR5.default,$I5.default,JI5.default,ZI5.default];cV4.default=QI5});var aV4=u((nV4)=>{Object.defineProperty(nV4,"__esModule",{value:!0});var iV4=X50(),XI5={keyword:"dependentRequired",type:"object",schemaType:"object",error:iV4.error,code:(J)=>(0,iV4.validatePropertyDeps)(J)};nV4.default=XI5});var rV4=u((oV4)=>{Object.defineProperty(oV4,"__esModule",{value:!0});var VI5=X50(),GI5={keyword:"dependentSchemas",type:"object",schemaType:"object",code:(J)=>(0,VI5.validateSchemaDeps)(J)};oV4.default=GI5});var tV4=u((sV4)=>{Object.defineProperty(sV4,"__esModule",{value:!0});var zI5=I5(),qI5={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:J,parentSchema:Z,it:Q}){if(Z.contains===void 0)(0,zI5.checkStrictMode)(Q,`"${J}" without "contains" is ignored`)}};sV4.default=qI5});var $G4=u((eV4)=>{Object.defineProperty(eV4,"__esModule",{value:!0});var HI5=aV4(),UI5=rV4(),DI5=tV4(),BI5=[HI5.default,UI5.default,DI5.default];eV4.default=BI5});var QG4=u((ZG4)=>{Object.defineProperty(ZG4,"__esModule",{value:!0});var rN=d6(),JG4=I5(),wI5=rX(),LI5={message:"must NOT have unevaluated properties",params:({params:J})=>rN._`{unevaluatedProperty: ${J.unevaluatedProperty}}`},OI5={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:LI5,code(J){let{gen:Z,schema:Q,data:Y,errsCount:X,it:K}=J;if(!X)throw Error("ajv implementation error");let{allErrors:V,props:G}=K;if(G instanceof rN.Name)Z.if(rN._`${G} !== true`,()=>Z.forIn("key",Y,(W)=>Z.if(z(G,W),()=>F(W))));else if(G!==!0)Z.forIn("key",Y,(W)=>G===void 0?F(W):Z.if(q(G,W),()=>F(W)));K.props=!0,J.ok(rN._`${X} === ${wI5.default.errors}`);function F(W){if(Q===!1){if(J.setParams({unevaluatedProperty:W}),J.error(),!V)Z.break();return}if(!(0,JG4.alwaysValidSchema)(K,Q)){let H=Z.name("valid");if(J.subschema({keyword:"unevaluatedProperties",dataProp:W,dataPropType:JG4.Type.Str},H),!V)Z.if((0,rN.not)(H),()=>Z.break())}}function z(W,H){return rN._`!${W} || !${W}[${H}]`}function q(W,H){let U=[];for(let D in W)if(W[D]===!0)U.push(rN._`${H} !== ${D}`);return(0,rN.and)(...U)}}};ZG4.default=OI5});var KG4=u((XG4)=>{Object.defineProperty(XG4,"__esModule",{value:!0});var fA=d6(),YG4=I5(),MI5={message:({params:{len:J}})=>fA.str`must NOT have more than ${J} items`,params:({params:{len:J}})=>fA._`{limit: ${J}}`},AI5={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:MI5,code(J){let{gen:Z,schema:Q,data:Y,it:X}=J,K=X.items||0;if(K===!0)return;let V=Z.const("len",fA._`${Y}.length`);if(Q===!1)J.setParams({len:K}),J.fail(fA._`${V} > ${K}`);else if(typeof Q=="object"&&!(0,YG4.alwaysValidSchema)(X,Q)){let F=Z.var("valid",fA._`${V} <= ${K}`);Z.if((0,fA.not)(F),()=>G(F,K)),J.ok(F)}X.items=!0;function G(F,z){Z.forRange("i",z,V,(q)=>{if(J.subschema({keyword:"unevaluatedItems",dataProp:q,dataPropType:YG4.Type.Num},F),!X.allErrors)Z.if((0,fA.not)(F),()=>Z.break())})}}};XG4.default=AI5});var GG4=u((VG4)=>{Object.defineProperty(VG4,"__esModule",{value:!0});var RI5=QG4(),II5=KG4(),PI5=[RI5.default,II5.default];VG4.default=PI5});var qG4=u((zG4)=>{Object.defineProperty(zG4,"__esModule",{value:!0});var _I5=nC0(),TI5=rC0(),SI5=Q_0(),kI5=lV4(),vI5=$G4(),yI5=GG4(),xI5=Y_0(),FG4=X_0(),fI5=[kI5.default,_I5.default,TI5.default,(0,SI5.default)(!0),xI5.default,FG4.metadataVocabulary,FG4.contentVocabulary,vI5.default,yI5.default];zG4.default=fI5});var WG4=u((Tb8,bI5)=>{bI5.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 HG4=u((Sb8,hI5)=>{hI5.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 UG4=u((kb8,gI5)=>{gI5.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 DG4=u((vb8,mI5)=>{mI5.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 BG4=u((yb8,pI5)=>{pI5.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 NG4=u((xb8,dI5)=>{dI5.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 wG4=u((fb8,cI5)=>{cI5.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 LG4=u((ub8,lI5)=>{lI5.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 EG4=u((OG4)=>{Object.defineProperty(OG4,"__esModule",{value:!0});var iI5=WG4(),nI5=HG4(),aI5=UG4(),oI5=DG4(),rI5=BG4(),sI5=NG4(),tI5=wG4(),eI5=LG4(),$P5=["/properties"];function JP5(J){return[iI5,nI5,aI5,oI5,rI5,Z(this,sI5),tI5,Z(this,eI5)].forEach((Q)=>this.addMetaSchema(Q,void 0,!1)),this;function Z(Q,Y){return J?Q.$dataMetaSchema(Y,$P5):Y}}OG4.default=JP5});var MG4=u((NQ,Wm0)=>{Object.defineProperty(NQ,"__esModule",{value:!0});NQ.MissingRefError=NQ.ValidationError=NQ.CodeGen=NQ.Name=NQ.nil=NQ.stringify=NQ.str=NQ._=NQ.KeywordCxt=NQ.Ajv2020=void 0;var QP5=iC0(),YP5=qG4(),XP5=V_0(),KP5=EG4(),qm0="https://json-schema.org/draft/2020-12/schema";class Ic extends QP5.default{constructor(J={}){super({...J,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){if(super._addVocabularies(),YP5.default.forEach((J)=>this.addVocabulary(J)),this.opts.discriminator)this.addKeyword(XP5.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:J,meta:Z}=this.opts;if(!Z)return;KP5.default.call(this,J),this.refs["http://json-schema.org/schema"]=qm0}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(qm0)?qm0:void 0)}}NQ.Ajv2020=Ic;Wm0.exports=NQ=Ic;Wm0.exports.Ajv2020=Ic;Object.defineProperty(NQ,"__esModule",{value:!0});NQ.default=Ic;var VP5=Q_();Object.defineProperty(NQ,"KeywordCxt",{enumerable:!0,get:function(){return VP5.KeywordCxt}});var sS=d6();Object.defineProperty(NQ,"_",{enumerable:!0,get:function(){return sS._}});Object.defineProperty(NQ,"str",{enumerable:!0,get:function(){return sS.str}});Object.defineProperty(NQ,"stringify",{enumerable:!0,get:function(){return sS.stringify}});Object.defineProperty(NQ,"nil",{enumerable:!0,get:function(){return sS.nil}});Object.defineProperty(NQ,"Name",{enumerable:!0,get:function(){return sS.Name}});Object.defineProperty(NQ,"CodeGen",{enumerable:!0,get:function(){return sS.CodeGen}});var GP5=mh();Object.defineProperty(NQ,"ValidationError",{enumerable:!0,get:function(){return GP5.default}});var FP5=Y_();Object.defineProperty(NQ,"MissingRefError",{enumerable:!0,get:function(){return FP5.default}})});var jG4=u((AG4)=>{(()=>{var J={349:(V,G,F)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.CircularList=void 0;let z=F(460),q=F(844);class W extends q.Disposable{constructor(H){super(),this._maxLength=H,this.onDeleteEmitter=this.register(new z.EventEmitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this.register(new z.EventEmitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this.register(new z.EventEmitter),this.onTrim=this.onTrimEmitter.event,this._array=Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(H){if(this._maxLength===H)return;let U=Array(H);for(let D=0;D<Math.min(H,this.length);D++)U[D]=this._array[this._getCyclicIndex(D)];this._array=U,this._maxLength=H,this._startIndex=0}get length(){return this._length}set length(H){if(H>this._length)for(let U=this._length;U<H;U++)this._array[U]=void 0;this._length=H}get(H){return this._array[this._getCyclicIndex(H)]}set(H,U){this._array[this._getCyclicIndex(H)]=U}push(H){this._array[this._getCyclicIndex(this._length)]=H,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(H,U,...D){if(U){for(let B=H;B<this._length-U;B++)this._array[this._getCyclicIndex(B)]=this._array[this._getCyclicIndex(B+U)];this._length-=U,this.onDeleteEmitter.fire({index:H,amount:U})}for(let B=this._length-1;B>=H;B--)this._array[this._getCyclicIndex(B+D.length)]=this._array[this._getCyclicIndex(B)];for(let B=0;B<D.length;B++)this._array[this._getCyclicIndex(H+B)]=D[B];if(D.length&&this.onInsertEmitter.fire({index:H,amount:D.length}),this._length+D.length>this._maxLength){let B=this._length+D.length-this._maxLength;this._startIndex+=B,this._length=this._maxLength,this.onTrimEmitter.fire(B)}else this._length+=D.length}trimStart(H){H>this._length&&(H=this._length),this._startIndex+=H,this._length-=H,this.onTrimEmitter.fire(H)}shiftElements(H,U,D){if(!(U<=0)){if(H<0||H>=this._length)throw Error("start argument out of range");if(H+D<0)throw Error("Cannot shift elements in list beyond index 0");if(D>0){for(let N=U-1;N>=0;N--)this.set(H+N+D,this.get(H+N));let B=H+U+D-this._length;if(B>0)for(this._length+=B;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let B=0;B<U;B++)this.set(H+B+D,this.get(H+B))}}_getCyclicIndex(H){return(this._startIndex+H)%this._maxLength}}G.CircularList=W},439:(V,G)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.clone=void 0,G.clone=function F(z,q=5){if(typeof z!="object")return z;let W=Array.isArray(z)?[]:{};for(let H in z)W[H]=q<=1?z[H]:z[H]&&F(z[H],q-1);return W}},969:(V,G,F)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.CoreTerminal=void 0;let z=F(844),q=F(585),W=F(348),H=F(866),U=F(744),D=F(302),B=F(83),N=F(460),w=F(753),L=F(480),O=F(994),E=F(282),M=F(435),A=F(981),j=F(660),I=!1;class T extends z.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this.register(new N.EventEmitter),this._onScroll.event((P)=>{this._onScrollApi?.fire(P.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(P){for(let h in P)this.optionsService.options[h]=P[h]}constructor(P){super(),this._windowsWrappingHeuristics=this.register(new z.MutableDisposable),this._onBinary=this.register(new N.EventEmitter),this.onBinary=this._onBinary.event,this._onData=this.register(new N.EventEmitter),this.onData=this._onData.event,this._onLineFeed=this.register(new N.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this.register(new N.EventEmitter),this.onResize=this._onResize.event,this._onWriteParsed=this.register(new N.EventEmitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this.register(new N.EventEmitter),this._instantiationService=new W.InstantiationService,this.optionsService=this.register(new D.OptionsService(P)),this._instantiationService.setService(q.IOptionsService,this.optionsService),this._bufferService=this.register(this._instantiationService.createInstance(U.BufferService)),this._instantiationService.setService(q.IBufferService,this._bufferService),this._logService=this.register(this._instantiationService.createInstance(H.LogService)),this._instantiationService.setService(q.ILogService,this._logService),this.coreService=this.register(this._instantiationService.createInstance(B.CoreService)),this._instantiationService.setService(q.ICoreService,this.coreService),this.coreMouseService=this.register(this._instantiationService.createInstance(w.CoreMouseService)),this._instantiationService.setService(q.ICoreMouseService,this.coreMouseService),this.unicodeService=this.register(this._instantiationService.createInstance(L.UnicodeService)),this._instantiationService.setService(q.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(O.CharsetService),this._instantiationService.setService(q.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(j.OscLinkService),this._instantiationService.setService(q.IOscLinkService,this._oscLinkService),this._inputHandler=this.register(new M.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this.register((0,N.forwardEvent)(this._inputHandler.onLineFeed,this._onLineFeed)),this.register(this._inputHandler),this.register((0,N.forwardEvent)(this._bufferService.onResize,this._onResize)),this.register((0,N.forwardEvent)(this.coreService.onData,this._onData)),this.register((0,N.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((h)=>{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((h)=>{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 A.WriteBuffer((h,p)=>this._inputHandler.parse(h,p))),this.register((0,N.forwardEvent)(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(P,h){this._writeBuffer.write(P,h)}writeSync(P,h){this._logService.logLevel<=q.LogLevelEnum.WARN&&!I&&(this._logService.warn("writeSync is unreliable and will be removed soon."),I=!0),this._writeBuffer.writeSync(P,h)}input(P,h=!0){this.coreService.triggerDataEvent(P,h)}resize(P,h){isNaN(P)||isNaN(h)||(P=Math.max(P,U.MINIMUM_COLS),h=Math.max(h,U.MINIMUM_ROWS),this._bufferService.resize(P,h))}scroll(P,h=!1){this._bufferService.scroll(P,h)}scrollLines(P,h,p){this._bufferService.scrollLines(P,h,p)}scrollPages(P){this.scrollLines(P*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(P){let h=P-this._bufferService.buffer.ydisp;h!==0&&this.scrollLines(h)}registerEscHandler(P,h){return this._inputHandler.registerEscHandler(P,h)}registerDcsHandler(P,h){return this._inputHandler.registerDcsHandler(P,h)}registerCsiHandler(P,h){return this._inputHandler.registerCsiHandler(P,h)}registerOscHandler(P,h){return this._inputHandler.registerOscHandler(P,h)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let P=!1,h=this.optionsService.rawOptions.windowsPty;h&&h.buildNumber!==void 0&&h.buildNumber!==void 0?P=h.backend==="conpty"&&h.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(P=!0),P?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let P=[];P.push(this.onLineFeed(E.updateWindowsModeWrappedState.bind(null,this._bufferService))),P.push(this.registerCsiHandler({final:"H"},()=>((0,E.updateWindowsModeWrappedState)(this._bufferService),!1))),this._windowsWrappingHeuristics.value=(0,z.toDisposable)(()=>{for(let h of P)h.dispose()})}}}G.CoreTerminal=T},460:(V,G)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.runAndSubscribe=G.forwardEvent=G.EventEmitter=void 0,G.EventEmitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||(this._event=(F)=>{return this._listeners.push(F),{dispose:()=>{if(!this._disposed){for(let q=0;q<this._listeners.length;q++)if(this._listeners[q]===F)return void this._listeners.splice(q,1)}}}}),this._event}fire(F,z){let q=[];for(let W=0;W<this._listeners.length;W++)q.push(this._listeners[W]);for(let W=0;W<q.length;W++)q[W].call(void 0,F,z)}dispose(){this.clearListeners(),this._disposed=!0}clearListeners(){this._listeners&&(this._listeners.length=0)}},G.forwardEvent=function(F,z){return F((q)=>z.fire(q))},G.runAndSubscribe=function(F,z){return z(void 0),F((q)=>z(q))}},435:function(V,G,F){var z=this&&this.__decorate||function(b,n,c,s){var W0,r=arguments.length,F0=r<3?n:s===null?s=Object.getOwnPropertyDescriptor(n,c):s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")F0=Reflect.decorate(b,n,c,s);else for(var w0=b.length-1;w0>=0;w0--)(W0=b[w0])&&(F0=(r<3?W0(F0):r>3?W0(n,c,F0):W0(n,c))||F0);return r>3&&F0&&Object.defineProperty(n,c,F0),F0},q=this&&this.__param||function(b,n){return function(c,s){n(c,s,b)}};Object.defineProperty(G,"__esModule",{value:!0}),G.InputHandler=G.WindowsOptionsReportType=void 0;let W=F(584),H=F(116),U=F(15),D=F(844),B=F(482),N=F(437),w=F(460),L=F(643),O=F(511),E=F(734),M=F(585),A=F(480),j=F(242),I=F(351),T=F(941),P={"(":0,")":1,"*":2,"+":3,"-":1,".":2},h=131072;function p(b,n){if(b>24)return n.setWinLines||!1;switch(b){case 1:return!!n.restoreWin;case 2:return!!n.minimizeWin;case 3:return!!n.setWinPosition;case 4:return!!n.setWinSizePixels;case 5:return!!n.raiseWin;case 6:return!!n.lowerWin;case 7:return!!n.refreshWin;case 8:return!!n.setWinSizeChars;case 9:return!!n.maximizeWin;case 10:return!!n.fullscreenWin;case 11:return!!n.getWinState;case 13:return!!n.getWinPosition;case 14:return!!n.getWinSizePixels;case 15:return!!n.getScreenSizePixels;case 16:return!!n.getCellSizePixels;case 18:return!!n.getWinSizeChars;case 19:return!!n.getScreenSizeChars;case 20:return!!n.getIconTitle;case 21:return!!n.getWinTitle;case 22:return!!n.pushTitle;case 23:return!!n.popTitle;case 24:return!!n.setWinLines}return!1}var x;(function(b){b[b.GET_WIN_SIZE_PIXELS=0]="GET_WIN_SIZE_PIXELS",b[b.GET_CELL_SIZE_PIXELS=1]="GET_CELL_SIZE_PIXELS"})(x||(G.WindowsOptionsReportType=x={}));let k=0;class f extends D.Disposable{getAttrData(){return this._curAttrData}constructor(b,n,c,s,W0,r,F0,w0,L0=new U.EscapeSequenceParser){super(),this._bufferService=b,this._charsetService=n,this._coreService=c,this._logService=s,this._optionsService=W0,this._oscLinkService=r,this._coreMouseService=F0,this._unicodeService=w0,this._parser=L0,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new B.StringToUtf32,this._utf8Decoder=new B.Utf8ToUtf32,this._workCell=new O.CellData,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=N.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=N.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this.register(new w.EventEmitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this.register(new w.EventEmitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this.register(new w.EventEmitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this.register(new w.EventEmitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this.register(new w.EventEmitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this.register(new w.EventEmitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this.register(new w.EventEmitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this.register(new w.EventEmitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this.register(new w.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this.register(new w.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this.register(new w.EventEmitter),this.onScroll=this._onScroll.event,this._onTitleChange=this.register(new w.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this.register(new w.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((e)=>this._activeBuffer=e.activeBuffer)),this._parser.setCsiHandlerFallback((e,K0)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(e),params:K0.toArray()})}),this._parser.setEscHandlerFallback((e)=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(e)})}),this._parser.setExecuteHandlerFallback((e)=>{this._logService.debug("Unknown EXECUTE code: ",{code:e})}),this._parser.setOscHandlerFallback((e,K0,i)=>{this._logService.debug("Unknown OSC code: ",{identifier:e,action:K0,data:i})}),this._parser.setDcsHandlerFallback((e,K0,i)=>{K0==="HOOK"&&(i=i.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(e),action:K0,payload:i})}),this._parser.setPrintHandler((e,K0,i)=>this.print(e,K0,i)),this._parser.registerCsiHandler({final:"@"},(e)=>this.insertChars(e)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},(e)=>this.scrollLeft(e)),this._parser.registerCsiHandler({final:"A"},(e)=>this.cursorUp(e)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},(e)=>this.scrollRight(e)),this._parser.registerCsiHandler({final:"B"},(e)=>this.cursorDown(e)),this._parser.registerCsiHandler({final:"C"},(e)=>this.cursorForward(e)),this._parser.registerCsiHandler({final:"D"},(e)=>this.cursorBackward(e)),this._parser.registerCsiHandler({final:"E"},(e)=>this.cursorNextLine(e)),this._parser.registerCsiHandler({final:"F"},(e)=>this.cursorPrecedingLine(e)),this._parser.registerCsiHandler({final:"G"},(e)=>this.cursorCharAbsolute(e)),this._parser.registerCsiHandler({final:"H"},(e)=>this.cursorPosition(e)),this._parser.registerCsiHandler({final:"I"},(e)=>this.cursorForwardTab(e)),this._parser.registerCsiHandler({final:"J"},(e)=>this.eraseInDisplay(e,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},(e)=>this.eraseInDisplay(e,!0)),this._parser.registerCsiHandler({final:"K"},(e)=>this.eraseInLine(e,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},(e)=>this.eraseInLine(e,!0)),this._parser.registerCsiHandler({final:"L"},(e)=>this.insertLines(e)),this._parser.registerCsiHandler({final:"M"},(e)=>this.deleteLines(e)),this._parser.registerCsiHandler({final:"P"},(e)=>this.deleteChars(e)),this._parser.registerCsiHandler({final:"S"},(e)=>this.scrollUp(e)),this._parser.registerCsiHandler({final:"T"},(e)=>this.scrollDown(e)),this._parser.registerCsiHandler({final:"X"},(e)=>this.eraseChars(e)),this._parser.registerCsiHandler({final:"Z"},(e)=>this.cursorBackwardTab(e)),this._parser.registerCsiHandler({final:"`"},(e)=>this.charPosAbsolute(e)),this._parser.registerCsiHandler({final:"a"},(e)=>this.hPositionRelative(e)),this._parser.registerCsiHandler({final:"b"},(e)=>this.repeatPrecedingCharacter(e)),this._parser.registerCsiHandler({final:"c"},(e)=>this.sendDeviceAttributesPrimary(e)),this._parser.registerCsiHandler({prefix:">",final:"c"},(e)=>this.sendDeviceAttributesSecondary(e)),this._parser.registerCsiHandler({final:"d"},(e)=>this.linePosAbsolute(e)),this._parser.registerCsiHandler({final:"e"},(e)=>this.vPositionRelative(e)),this._parser.registerCsiHandler({final:"f"},(e)=>this.hVPosition(e)),this._parser.registerCsiHandler({final:"g"},(e)=>this.tabClear(e)),this._parser.registerCsiHandler({final:"h"},(e)=>this.setMode(e)),this._parser.registerCsiHandler({prefix:"?",final:"h"},(e)=>this.setModePrivate(e)),this._parser.registerCsiHandler({final:"l"},(e)=>this.resetMode(e)),this._parser.registerCsiHandler({prefix:"?",final:"l"},(e)=>this.resetModePrivate(e)),this._parser.registerCsiHandler({final:"m"},(e)=>this.charAttributes(e)),this._parser.registerCsiHandler({final:"n"},(e)=>this.deviceStatus(e)),this._parser.registerCsiHandler({prefix:"?",final:"n"},(e)=>this.deviceStatusPrivate(e)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},(e)=>this.softReset(e)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},(e)=>this.setCursorStyle(e)),this._parser.registerCsiHandler({final:"r"},(e)=>this.setScrollRegion(e)),this._parser.registerCsiHandler({final:"s"},(e)=>this.saveCursor(e)),this._parser.registerCsiHandler({final:"t"},(e)=>this.windowOptions(e)),this._parser.registerCsiHandler({final:"u"},(e)=>this.restoreCursor(e)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},(e)=>this.insertColumns(e)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},(e)=>this.deleteColumns(e)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},(e)=>this.selectProtected(e)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},(e)=>this.requestMode(e,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},(e)=>this.requestMode(e,!1)),this._parser.setExecuteHandler(W.C0.BEL,()=>this.bell()),this._parser.setExecuteHandler(W.C0.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(W.C0.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(W.C0.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(W.C0.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(W.C0.BS,()=>this.backspace()),this._parser.setExecuteHandler(W.C0.HT,()=>this.tab()),this._parser.setExecuteHandler(W.C0.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(W.C0.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(W.C1.IND,()=>this.index()),this._parser.setExecuteHandler(W.C1.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(W.C1.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new j.OscHandler((e)=>(this.setTitle(e),this.setIconName(e),!0))),this._parser.registerOscHandler(1,new j.OscHandler((e)=>this.setIconName(e))),this._parser.registerOscHandler(2,new j.OscHandler((e)=>this.setTitle(e))),this._parser.registerOscHandler(4,new j.OscHandler((e)=>this.setOrReportIndexedColor(e))),this._parser.registerOscHandler(8,new j.OscHandler((e)=>this.setHyperlink(e))),this._parser.registerOscHandler(10,new j.OscHandler((e)=>this.setOrReportFgColor(e))),this._parser.registerOscHandler(11,new j.OscHandler((e)=>this.setOrReportBgColor(e))),this._parser.registerOscHandler(12,new j.OscHandler((e)=>this.setOrReportCursorColor(e))),this._parser.registerOscHandler(104,new j.OscHandler((e)=>this.restoreIndexedColor(e))),this._parser.registerOscHandler(110,new j.OscHandler((e)=>this.restoreFgColor(e))),this._parser.registerOscHandler(111,new j.OscHandler((e)=>this.restoreBgColor(e))),this._parser.registerOscHandler(112,new j.OscHandler((e)=>this.restoreCursorColor(e))),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 e in H.CHARSETS)this._parser.registerEscHandler({intermediates:"(",final:e},()=>this.selectCharset("("+e)),this._parser.registerEscHandler({intermediates:")",final:e},()=>this.selectCharset(")"+e)),this._parser.registerEscHandler({intermediates:"*",final:e},()=>this.selectCharset("*"+e)),this._parser.registerEscHandler({intermediates:"+",final:e},()=>this.selectCharset("+"+e)),this._parser.registerEscHandler({intermediates:"-",final:e},()=>this.selectCharset("-"+e)),this._parser.registerEscHandler({intermediates:".",final:e},()=>this.selectCharset("."+e)),this._parser.registerEscHandler({intermediates:"/",final:e},()=>this.selectCharset("/"+e));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler((e)=>(this._logService.error("Parsing error: ",e),e)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new I.DcsHandler((e,K0)=>this.requestStatusString(e,K0)))}_preserveStack(b,n,c,s){this._parseStack.paused=!0,this._parseStack.cursorStartX=b,this._parseStack.cursorStartY=n,this._parseStack.decodedLength=c,this._parseStack.position=s}_logSlowResolvingAsync(b){this._logService.logLevel<=M.LogLevelEnum.WARN&&Promise.race([b,new Promise((n,c)=>setTimeout(()=>c("#SLOW_TIMEOUT"),5000))]).catch((n)=>{if(n!=="#SLOW_TIMEOUT")throw n;console.warn("async parser handler taking longer than 5000 ms")})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(b,n){let c,s=this._activeBuffer.x,W0=this._activeBuffer.y,r=0,F0=this._parseStack.paused;if(F0){if(c=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,n))return this._logSlowResolvingAsync(c),c;s=this._parseStack.cursorStartX,W0=this._parseStack.cursorStartY,this._parseStack.paused=!1,b.length>h&&(r=this._parseStack.position+h)}if(this._logService.logLevel<=M.LogLevelEnum.DEBUG&&this._logService.debug("parsing data"+(typeof b=="string"?` "${b}"`:` "${Array.prototype.map.call(b,(e)=>String.fromCharCode(e)).join("")}"`),typeof b=="string"?b.split("").map((e)=>e.charCodeAt(0)):b),this._parseBuffer.length<b.length&&this._parseBuffer.length<h&&(this._parseBuffer=new Uint32Array(Math.min(b.length,h))),F0||this._dirtyRowTracker.clearRange(),b.length>h)for(let e=r;e<b.length;e+=h){let K0=e+h<b.length?e+h:b.length,i=typeof b=="string"?this._stringDecoder.decode(b.substring(e,K0),this._parseBuffer):this._utf8Decoder.decode(b.subarray(e,K0),this._parseBuffer);if(c=this._parser.parse(this._parseBuffer,i))return this._preserveStack(s,W0,i,e),this._logSlowResolvingAsync(c),c}else if(!F0){let e=typeof b=="string"?this._stringDecoder.decode(b,this._parseBuffer):this._utf8Decoder.decode(b,this._parseBuffer);if(c=this._parser.parse(this._parseBuffer,e))return this._preserveStack(s,W0,e,0),this._logSlowResolvingAsync(c),c}this._activeBuffer.x===s&&this._activeBuffer.y===W0||this._onCursorMove.fire();let w0=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),L0=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);L0<this._bufferService.rows&&this._onRequestRefreshRows.fire(Math.min(L0,this._bufferService.rows-1),Math.min(w0,this._bufferService.rows-1))}print(b,n,c){let s,W0,r=this._charsetService.charset,F0=this._optionsService.rawOptions.screenReaderMode,w0=this._bufferService.cols,L0=this._coreService.decPrivateModes.wraparound,e=this._coreService.modes.insertMode,K0=this._curAttrData,i=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&c-n>0&&i.getWidth(this._activeBuffer.x-1)===2&&i.setCellFromCodepoint(this._activeBuffer.x-1,0,1,K0);let a=this._parser.precedingJoinState;for(let t=n;t<c;++t){if(s=b[t],s<127&&r){let B0=r[String.fromCharCode(s)];B0&&(s=B0.charCodeAt(0))}let $0=this._unicodeService.charProperties(s,a);W0=A.UnicodeService.extractWidth($0);let G0=A.UnicodeService.extractShouldJoin($0),Y0=G0?A.UnicodeService.extractWidth(a):0;if(a=$0,F0&&this._onA11yChar.fire((0,B.stringFromCodePoint)(s)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+W0-Y0>w0){if(L0){let B0=i,U0=this._activeBuffer.x-Y0;for(this._activeBuffer.x=Y0,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),i=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),Y0>0&&i instanceof N.BufferLine&&i.copyCellsFrom(B0,U0,0,Y0,!1);U0<w0;)B0.setCellFromCodepoint(U0++,0,1,K0)}else if(this._activeBuffer.x=w0-1,W0===2)continue}if(G0&&this._activeBuffer.x){let B0=i.getWidth(this._activeBuffer.x-1)?1:2;i.addCodepointToCell(this._activeBuffer.x-B0,s,W0);for(let U0=W0-Y0;--U0>=0;)i.setCellFromCodepoint(this._activeBuffer.x++,0,0,K0)}else if(e&&(i.insertCells(this._activeBuffer.x,W0-Y0,this._activeBuffer.getNullCell(K0)),i.getWidth(w0-1)===2&&i.setCellFromCodepoint(w0-1,L.NULL_CELL_CODE,L.NULL_CELL_WIDTH,K0)),i.setCellFromCodepoint(this._activeBuffer.x++,s,W0,K0),W0>0)for(;--W0;)i.setCellFromCodepoint(this._activeBuffer.x++,0,0,K0)}this._parser.precedingJoinState=a,this._activeBuffer.x<w0&&c-n>0&&i.getWidth(this._activeBuffer.x)===0&&!i.hasContent(this._activeBuffer.x)&&i.setCellFromCodepoint(this._activeBuffer.x,0,1,K0),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(b,n){return b.final!=="t"||b.prefix||b.intermediates?this._parser.registerCsiHandler(b,n):this._parser.registerCsiHandler(b,(c)=>!p(c.params[0],this._optionsService.rawOptions.windowOptions)||n(c))}registerDcsHandler(b,n){return this._parser.registerDcsHandler(b,new I.DcsHandler(n))}registerEscHandler(b,n){return this._parser.registerEscHandler(b,n)}registerOscHandler(b,n){return this._parser.registerOscHandler(b,new j.OscHandler(n))}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 b=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);b.hasWidth(this._activeBuffer.x)&&!b.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let b=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-b),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(b=this._bufferService.cols-1){this._activeBuffer.x=Math.min(b,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(b,n){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=b,this._activeBuffer.y=this._activeBuffer.scrollTop+n):(this._activeBuffer.x=b,this._activeBuffer.y=n),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(b,n){this._restrictCursor(),this._setCursor(this._activeBuffer.x+b,this._activeBuffer.y+n)}cursorUp(b){let n=this._activeBuffer.y-this._activeBuffer.scrollTop;return n>=0?this._moveCursor(0,-Math.min(n,b.params[0]||1)):this._moveCursor(0,-(b.params[0]||1)),!0}cursorDown(b){let n=this._activeBuffer.scrollBottom-this._activeBuffer.y;return n>=0?this._moveCursor(0,Math.min(n,b.params[0]||1)):this._moveCursor(0,b.params[0]||1),!0}cursorForward(b){return this._moveCursor(b.params[0]||1,0),!0}cursorBackward(b){return this._moveCursor(-(b.params[0]||1),0),!0}cursorNextLine(b){return this.cursorDown(b),this._activeBuffer.x=0,!0}cursorPrecedingLine(b){return this.cursorUp(b),this._activeBuffer.x=0,!0}cursorCharAbsolute(b){return this._setCursor((b.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(b){return this._setCursor(b.length>=2?(b.params[1]||1)-1:0,(b.params[0]||1)-1),!0}charPosAbsolute(b){return this._setCursor((b.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(b){return this._moveCursor(b.params[0]||1,0),!0}linePosAbsolute(b){return this._setCursor(this._activeBuffer.x,(b.params[0]||1)-1),!0}vPositionRelative(b){return this._moveCursor(0,b.params[0]||1),!0}hVPosition(b){return this.cursorPosition(b),!0}tabClear(b){let n=b.params[0];return n===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:n===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(b){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let n=b.params[0]||1;for(;n--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(b){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let n=b.params[0]||1;for(;n--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(b){let n=b.params[0];return n===1&&(this._curAttrData.bg|=536870912),n!==2&&n!==0||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(b,n,c,s=!1,W0=!1){let r=this._activeBuffer.lines.get(this._activeBuffer.ybase+b);r.replaceCells(n,c,this._activeBuffer.getNullCell(this._eraseAttrData()),W0),s&&(r.isWrapped=!1)}_resetBufferLine(b,n=!1){let c=this._activeBuffer.lines.get(this._activeBuffer.ybase+b);c&&(c.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),n),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+b),c.isWrapped=!1)}eraseInDisplay(b,n=!1){let c;switch(this._restrictCursor(this._bufferService.cols),b.params[0]){case 0:for(c=this._activeBuffer.y,this._dirtyRowTracker.markDirty(c),this._eraseInBufferLine(c++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,n);c<this._bufferService.rows;c++)this._resetBufferLine(c,n);this._dirtyRowTracker.markDirty(c);break;case 1:for(c=this._activeBuffer.y,this._dirtyRowTracker.markDirty(c),this._eraseInBufferLine(c,0,this._activeBuffer.x+1,!0,n),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(c+1).isWrapped=!1);c--;)this._resetBufferLine(c,n);this._dirtyRowTracker.markDirty(0);break;case 2:for(c=this._bufferService.rows,this._dirtyRowTracker.markDirty(c-1);c--;)this._resetBufferLine(c,n);this._dirtyRowTracker.markDirty(0);break;case 3:let s=this._activeBuffer.lines.length-this._bufferService.rows;s>0&&(this._activeBuffer.lines.trimStart(s),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-s,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-s,0),this._onScroll.fire(0))}return!0}eraseInLine(b,n=!1){switch(this._restrictCursor(this._bufferService.cols),b.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,n);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,n);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,n)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(b){this._restrictCursor();let n=b.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let c=this._activeBuffer.ybase+this._activeBuffer.y,s=this._bufferService.rows-1-this._activeBuffer.scrollBottom,W0=this._bufferService.rows-1+this._activeBuffer.ybase-s+1;for(;n--;)this._activeBuffer.lines.splice(W0-1,1),this._activeBuffer.lines.splice(c,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(b){this._restrictCursor();let n=b.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let c=this._activeBuffer.ybase+this._activeBuffer.y,s;for(s=this._bufferService.rows-1-this._activeBuffer.scrollBottom,s=this._bufferService.rows-1+this._activeBuffer.ybase-s;n--;)this._activeBuffer.lines.splice(c,1),this._activeBuffer.lines.splice(s,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(b){this._restrictCursor();let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return n&&(n.insertCells(this._activeBuffer.x,b.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(b){this._restrictCursor();let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return n&&(n.deleteCells(this._activeBuffer.x,b.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(b){let n=b.params[0]||1;for(;n--;)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(b){let n=b.params[0]||1;for(;n--;)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(N.DEFAULT_ATTR_DATA));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(b){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=b.params[0]||1;for(let c=this._activeBuffer.scrollTop;c<=this._activeBuffer.scrollBottom;++c){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+c);s.deleteCells(0,n,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(b){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=b.params[0]||1;for(let c=this._activeBuffer.scrollTop;c<=this._activeBuffer.scrollBottom;++c){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+c);s.insertCells(0,n,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(b){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=b.params[0]||1;for(let c=this._activeBuffer.scrollTop;c<=this._activeBuffer.scrollBottom;++c){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+c);s.insertCells(this._activeBuffer.x,n,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(b){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=b.params[0]||1;for(let c=this._activeBuffer.scrollTop;c<=this._activeBuffer.scrollBottom;++c){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+c);s.deleteCells(this._activeBuffer.x,n,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(b){this._restrictCursor();let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return n&&(n.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(b.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(b){let n=this._parser.precedingJoinState;if(!n)return!0;let c=b.params[0]||1,s=A.UnicodeService.extractWidth(n),W0=this._activeBuffer.x-s,r=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(W0),F0=new Uint32Array(r.length*c),w0=0;for(let e=0;e<r.length;){let K0=r.codePointAt(e)||0;F0[w0++]=K0,e+=K0>65535?2:1}let L0=w0;for(let e=1;e<c;++e)F0.copyWithin(L0,0,w0),L0+=w0;return this.print(F0,0,L0),!0}sendDeviceAttributesPrimary(b){return b.params[0]>0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(W.C0.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(W.C0.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(b){return b.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(W.C0.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(W.C0.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(b.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(W.C0.ESC+"[>83;40003;0c")),!0}_is(b){return(this._optionsService.rawOptions.termName+"").indexOf(b)===0}setMode(b){for(let n=0;n<b.length;n++)switch(b.params[n]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(b){for(let n=0;n<b.length;n++)switch(b.params[n]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,H.DEFAULT_CHARSET),this._charsetService.setgCharset(1,H.DEFAULT_CHARSET),this._charsetService.setgCharset(2,H.DEFAULT_CHARSET),this._charsetService.setgCharset(3,H.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(b){for(let n=0;n<b.length;n++)switch(b.params[n]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(b){for(let n=0;n<b.length;n++)switch(b.params[n]){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(),b.params[n]===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(b,n){let c=this._coreService.decPrivateModes,{activeProtocol:s,activeEncoding:W0}=this._coreMouseService,r=this._coreService,{buffers:F0,cols:w0}=this._bufferService,{active:L0,alt:e}=F0,K0=this._optionsService.rawOptions,i=(G0)=>G0?1:2,a=b.params[0];return t=a,$0=n?a===2?4:a===4?i(r.modes.insertMode):a===12?3:a===20?i(K0.convertEol):0:a===1?i(c.applicationCursorKeys):a===3?K0.windowOptions.setWinLines?w0===80?2:w0===132?1:0:0:a===6?i(c.origin):a===7?i(c.wraparound):a===8?3:a===9?i(s==="X10"):a===12?i(K0.cursorBlink):a===25?i(!r.isCursorHidden):a===45?i(c.reverseWraparound):a===66?i(c.applicationKeypad):a===67?4:a===1000?i(s==="VT200"):a===1002?i(s==="DRAG"):a===1003?i(s==="ANY"):a===1004?i(c.sendFocus):a===1005?4:a===1006?i(W0==="SGR"):a===1015?4:a===1016?i(W0==="SGR_PIXELS"):a===1048?1:a===47||a===1047||a===1049?i(L0===e):a===2004?i(c.bracketedPasteMode):0,r.triggerDataEvent(`${W.C0.ESC}[${n?"":"?"}${t};${$0}$y`),!0;var t,$0}_updateAttrColor(b,n,c,s,W0){return n===2?(b|=50331648,b&=-16777216,b|=E.AttributeData.fromColorRGB([c,s,W0])):n===5&&(b&=-50331904,b|=33554432|255&c),b}_extractColor(b,n,c){let s=[0,0,-1,0,0,0],W0=0,r=0;do{if(s[r+W0]=b.params[n+r],b.hasSubParams(n+r)){let F0=b.getSubParams(n+r),w0=0;do s[1]===5&&(W0=1),s[r+w0+1+W0]=F0[w0];while(++w0<F0.length&&w0+r+1+W0<s.length);break}if(s[1]===5&&r+W0>=2||s[1]===2&&r+W0>=5)break;s[1]&&(W0=1)}while(++r+n<b.length&&r+W0<s.length);for(let F0=2;F0<s.length;++F0)s[F0]===-1&&(s[F0]=0);switch(s[0]){case 38:c.fg=this._updateAttrColor(c.fg,s[1],s[3],s[4],s[5]);break;case 48:c.bg=this._updateAttrColor(c.bg,s[1],s[3],s[4],s[5]);break;case 58:c.extended=c.extended.clone(),c.extended.underlineColor=this._updateAttrColor(c.extended.underlineColor,s[1],s[3],s[4],s[5])}return r}_processUnderline(b,n){n.extended=n.extended.clone(),(!~b||b>5)&&(b=1),n.extended.underlineStyle=b,n.fg|=268435456,b===0&&(n.fg&=-268435457),n.updateExtended()}_processSGR0(b){b.fg=N.DEFAULT_ATTR_DATA.fg,b.bg=N.DEFAULT_ATTR_DATA.bg,b.extended=b.extended.clone(),b.extended.underlineStyle=0,b.extended.underlineColor&=-67108864,b.updateExtended()}charAttributes(b){if(b.length===1&&b.params[0]===0)return this._processSGR0(this._curAttrData),!0;let n=b.length,c,s=this._curAttrData;for(let W0=0;W0<n;W0++)c=b.params[W0],c>=30&&c<=37?(s.fg&=-50331904,s.fg|=16777216|c-30):c>=40&&c<=47?(s.bg&=-50331904,s.bg|=16777216|c-40):c>=90&&c<=97?(s.fg&=-50331904,s.fg|=16777224|c-90):c>=100&&c<=107?(s.bg&=-50331904,s.bg|=16777224|c-100):c===0?this._processSGR0(s):c===1?s.fg|=134217728:c===3?s.bg|=67108864:c===4?(s.fg|=268435456,this._processUnderline(b.hasSubParams(W0)?b.getSubParams(W0)[0]:1,s)):c===5?s.fg|=536870912:c===7?s.fg|=67108864:c===8?s.fg|=1073741824:c===9?s.fg|=2147483648:c===2?s.bg|=134217728:c===21?this._processUnderline(2,s):c===22?(s.fg&=-134217729,s.bg&=-134217729):c===23?s.bg&=-67108865:c===24?(s.fg&=-268435457,this._processUnderline(0,s)):c===25?s.fg&=-536870913:c===27?s.fg&=-67108865:c===28?s.fg&=-1073741825:c===29?s.fg&=2147483647:c===39?(s.fg&=-67108864,s.fg|=16777215&N.DEFAULT_ATTR_DATA.fg):c===49?(s.bg&=-67108864,s.bg|=16777215&N.DEFAULT_ATTR_DATA.bg):c===38||c===48||c===58?W0+=this._extractColor(b,W0,s):c===53?s.bg|=1073741824:c===55?s.bg&=-1073741825:c===59?(s.extended=s.extended.clone(),s.extended.underlineColor=-1,s.updateExtended()):c===100?(s.fg&=-67108864,s.fg|=16777215&N.DEFAULT_ATTR_DATA.fg,s.bg&=-67108864,s.bg|=16777215&N.DEFAULT_ATTR_DATA.bg):this._logService.debug("Unknown SGR attribute: %d.",c);return!0}deviceStatus(b){switch(b.params[0]){case 5:this._coreService.triggerDataEvent(`${W.C0.ESC}[0n`);break;case 6:let n=this._activeBuffer.y+1,c=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${W.C0.ESC}[${n};${c}R`)}return!0}deviceStatusPrivate(b){if(b.params[0]===6){let n=this._activeBuffer.y+1,c=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${W.C0.ESC}[?${n};${c}R`)}return!0}softReset(b){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=N.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(b){let n=b.params[0]||1;switch(n){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 c=n%2==1;return this._optionsService.options.cursorBlink=c,!0}setScrollRegion(b){let n=b.params[0]||1,c;return(b.length<2||(c=b.params[1])>this._bufferService.rows||c===0)&&(c=this._bufferService.rows),c>n&&(this._activeBuffer.scrollTop=n-1,this._activeBuffer.scrollBottom=c-1,this._setCursor(0,0)),!0}windowOptions(b){if(!p(b.params[0],this._optionsService.rawOptions.windowOptions))return!0;let n=b.length>1?b.params[1]:0;switch(b.params[0]){case 14:n!==2&&this._onRequestWindowsOptionsReport.fire(x.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(x.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${W.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:n!==0&&n!==2||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),n!==0&&n!==1||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:n!==0&&n!==2||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),n!==0&&n!==1||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(b){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(b){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(b){return this._windowTitle=b,this._onTitleChange.fire(b),!0}setIconName(b){return this._iconName=b,!0}setOrReportIndexedColor(b){let n=[],c=b.split(";");for(;c.length>1;){let s=c.shift(),W0=c.shift();if(/^\d+$/.exec(s)){let r=parseInt(s);if(m(r))if(W0==="?")n.push({type:0,index:r});else{let F0=(0,T.parseColor)(W0);F0&&n.push({type:1,index:r,color:F0})}}}return n.length&&this._onColor.fire(n),!0}setHyperlink(b){let n=b.split(";");return!(n.length<2)&&(n[1]?this._createHyperlink(n[0],n[1]):!n[0]&&this._finishHyperlink())}_createHyperlink(b,n){this._getCurrentLinkId()&&this._finishHyperlink();let c=b.split(":"),s,W0=c.findIndex((r)=>r.startsWith("id="));return W0!==-1&&(s=c[W0].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:s,uri:n}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(b,n){let c=b.split(";");for(let s=0;s<c.length&&!(n>=this._specialColors.length);++s,++n)if(c[s]==="?")this._onColor.fire([{type:0,index:this._specialColors[n]}]);else{let W0=(0,T.parseColor)(c[s]);W0&&this._onColor.fire([{type:1,index:this._specialColors[n],color:W0}])}return!0}setOrReportFgColor(b){return this._setOrReportSpecialColor(b,0)}setOrReportBgColor(b){return this._setOrReportSpecialColor(b,1)}setOrReportCursorColor(b){return this._setOrReportSpecialColor(b,2)}restoreIndexedColor(b){if(!b)return this._onColor.fire([{type:2}]),!0;let n=[],c=b.split(";");for(let s=0;s<c.length;++s)if(/^\d+$/.exec(c[s])){let W0=parseInt(c[s]);m(W0)&&n.push({type:2,index:W0})}return n.length&&this._onColor.fire(n),!0}restoreFgColor(b){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(b){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(b){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,H.DEFAULT_CHARSET),!0}selectCharset(b){return b.length!==2?(this.selectDefaultCharset(),!0):(b[0]==="/"||this._charsetService.setgCharset(P[b[0]],H.CHARSETS[b[1]]||H.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 b=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,b,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=N.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=N.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(b){return this._charsetService.setgLevel(b),!0}screenAlignmentPattern(){let b=new O.CellData;b.content=4194373,b.fg=this._curAttrData.fg,b.bg=this._curAttrData.bg,this._setCursor(0,0);for(let n=0;n<this._bufferService.rows;++n){let c=this._activeBuffer.ybase+this._activeBuffer.y+n,s=this._activeBuffer.lines.get(c);s&&(s.fill(b),s.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(b,n){let c=this._bufferService.buffer,s=this._optionsService.rawOptions;return((W0)=>(this._coreService.triggerDataEvent(`${W.C0.ESC}${W0}${W.C0.ESC}\\`),!0))(b==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:b==='"p'?'P1$r61;1"p':b==="r"?`P1$r${c.scrollTop+1};${c.scrollBottom+1}r`:b==="m"?"P1$r0m":b===" q"?`P1$r${{block:2,underline:4,bar:6}[s.cursorStyle]-(s.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(b,n){this._dirtyRowTracker.markRangeDirty(b,n)}}G.InputHandler=f;let d=class{constructor(b){this._bufferService=b,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(b){b<this.start?this.start=b:b>this.end&&(this.end=b)}markRangeDirty(b,n){b>n&&(k=b,b=n,n=k),b<this.start&&(this.start=b),n>this.end&&(this.end=n)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function m(b){return 0<=b&&b<256}d=z([q(0,M.IBufferService)],d)},844:(V,G)=>{function F(z){for(let q of z)q.dispose();z.length=0}Object.defineProperty(G,"__esModule",{value:!0}),G.getDisposeArrayDisposable=G.disposeArray=G.toDisposable=G.MutableDisposable=G.Disposable=void 0,G.Disposable=class{constructor(){this._disposables=[],this._isDisposed=!1}dispose(){this._isDisposed=!0;for(let z of this._disposables)z.dispose();this._disposables.length=0}register(z){return this._disposables.push(z),z}unregister(z){let q=this._disposables.indexOf(z);q!==-1&&this._disposables.splice(q,1)}},G.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(z){this._isDisposed||z===this._value||(this._value?.dispose(),this._value=z)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}},G.toDisposable=function(z){return{dispose:z}},G.disposeArray=F,G.getDisposeArrayDisposable=function(z){return{dispose:()=>F(z)}}},114:(V,G)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.isChromeOS=G.isLinux=G.isWindows=G.isIphone=G.isIpad=G.isMac=G.getSafariVersion=G.isSafari=G.isLegacyEdge=G.isFirefox=G.isNode=void 0,G.isNode=typeof process<"u"&&"title"in process;let F=G.isNode?"node":navigator.userAgent,z=G.isNode?"node":navigator.platform;G.isFirefox=F.includes("Firefox"),G.isLegacyEdge=F.includes("Edge"),G.isSafari=/^((?!chrome|android).)*safari/i.test(F),G.getSafariVersion=function(){if(!G.isSafari)return 0;let q=F.match(/Version\/(\d+)/);return q===null||q.length<2?0:parseInt(q[1])},G.isMac=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(z),G.isIpad=z==="iPad",G.isIphone=z==="iPhone",G.isWindows=["Windows","Win16","Win32","WinCE"].includes(z),G.isLinux=z.indexOf("Linux")>=0,G.isChromeOS=/\bCrOS\b/.test(F)},226:(V,G,F)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.DebouncedIdleTask=G.IdleTaskQueue=G.PriorityTaskQueue=void 0;let z=F(114);class q{constructor(){this._tasks=[],this._i=0}enqueue(H){this._tasks.push(H),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(H){this._idleCallback=void 0;let U=0,D=0,B=H.timeRemaining(),N=0;for(;this._i<this._tasks.length;){if(U=Date.now(),this._tasks[this._i]()||this._i++,U=Math.max(1,Date.now()-U),D=Math.max(U,D),N=H.timeRemaining(),1.5*D>N)return B-U<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(B-U))}ms`),void this._start();B=N}this.clear()}}class W extends q{_requestCallback(H){return setTimeout(()=>H(this._createDeadline(16)))}_cancelCallback(H){clearTimeout(H)}_createDeadline(H){let U=Date.now()+H;return{timeRemaining:()=>Math.max(0,U-Date.now())}}}G.PriorityTaskQueue=W,G.IdleTaskQueue=!z.isNode&&"requestIdleCallback"in window?class extends q{_requestCallback(H){return requestIdleCallback(H)}_cancelCallback(H){cancelIdleCallback(H)}}:W,G.DebouncedIdleTask=class{constructor(){this._queue=new G.IdleTaskQueue}set(H){this._queue.clear(),this._queue.enqueue(H)}flush(){this._queue.flush()}}},282:(V,G,F)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.updateWindowsModeWrappedState=void 0;let z=F(643);G.updateWindowsModeWrappedState=function(q){let W=q.buffer.lines.get(q.buffer.ybase+q.buffer.y-1),H=W?.get(q.cols-1),U=q.buffer.lines.get(q.buffer.ybase+q.buffer.y);U&&H&&(U.isWrapped=H[z.CHAR_DATA_CODE_INDEX]!==z.NULL_CELL_CODE&&H[z.CHAR_DATA_CODE_INDEX]!==z.WHITESPACE_CELL_CODE)}},734:(V,G)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.ExtendedAttrs=G.AttributeData=void 0;class F{constructor(){this.fg=0,this.bg=0,this.extended=new z}static toColorRGB(q){return[q>>>16&255,q>>>8&255,255&q]}static fromColorRGB(q){return(255&q[0])<<16|(255&q[1])<<8|255&q[2]}clone(){let q=new F;return q.fg=this.fg,q.bg=this.bg,q.extended=this.extended.clone(),q}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}}G.AttributeData=F;class z{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(q){this._ext=q}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(q){this._ext&=-469762049,this._ext|=q<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(q){this._ext&=-67108864,this._ext|=67108863&q}get urlId(){return this._urlId}set urlId(q){this._urlId=q}get underlineVariantOffset(){let q=(3758096384&this._ext)>>29;return q<0?4294967288^q:q}set underlineVariantOffset(q){this._ext&=536870911,this._ext|=q<<29&3758096384}constructor(q=0,W=0){this._ext=0,this._urlId=0,this._ext=q,this._urlId=W}clone(){return new z(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}}G.ExtendedAttrs=z},92:(V,G,F)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.Buffer=G.MAX_BUFFER_SIZE=void 0;let z=F(349),q=F(226),W=F(734),H=F(437),U=F(634),D=F(511),B=F(643),N=F(863),w=F(116);G.MAX_BUFFER_SIZE=4294967295,G.Buffer=class{constructor(L,O,E){this._hasScrollback=L,this._optionsService=O,this._bufferService=E,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=H.DEFAULT_ATTR_DATA.clone(),this.savedCharset=w.DEFAULT_CHARSET,this.markers=[],this._nullCell=D.CellData.fromCharData([0,B.NULL_CELL_CHAR,B.NULL_CELL_WIDTH,B.NULL_CELL_CODE]),this._whitespaceCell=D.CellData.fromCharData([0,B.WHITESPACE_CELL_CHAR,B.WHITESPACE_CELL_WIDTH,B.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new q.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new z.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(L){return L?(this._nullCell.fg=L.fg,this._nullCell.bg=L.bg,this._nullCell.extended=L.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new W.ExtendedAttrs),this._nullCell}getWhitespaceCell(L){return L?(this._whitespaceCell.fg=L.fg,this._whitespaceCell.bg=L.bg,this._whitespaceCell.extended=L.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new W.ExtendedAttrs),this._whitespaceCell}getBlankLine(L,O){return new H.BufferLine(this._bufferService.cols,this.getNullCell(L),O)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let L=this.ybase+this.y-this.ydisp;return L>=0&&L<this._rows}_getCorrectBufferLength(L){if(!this._hasScrollback)return L;let O=L+this._optionsService.rawOptions.scrollback;return O>G.MAX_BUFFER_SIZE?G.MAX_BUFFER_SIZE:O}fillViewportRows(L){if(this.lines.length===0){L===void 0&&(L=H.DEFAULT_ATTR_DATA);let O=this._rows;for(;O--;)this.lines.push(this.getBlankLine(L))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new z.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(L,O){let E=this.getNullCell(H.DEFAULT_ATTR_DATA),M=0,A=this._getCorrectBufferLength(O);if(A>this.lines.maxLength&&(this.lines.maxLength=A),this.lines.length>0){if(this._cols<L)for(let I=0;I<this.lines.length;I++)M+=+this.lines.get(I).resize(L,E);let j=0;if(this._rows<O)for(let I=this._rows;I<O;I++)this.lines.length<O+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new H.BufferLine(L,E)):this.ybase>0&&this.lines.length<=this.ybase+this.y+j+1?(this.ybase--,j++,this.ydisp>0&&this.ydisp--):this.lines.push(new H.BufferLine(L,E)));else for(let I=this._rows;I>O;I--)this.lines.length>O+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(A<this.lines.maxLength){let I=this.lines.length-A;I>0&&(this.lines.trimStart(I),this.ybase=Math.max(this.ybase-I,0),this.ydisp=Math.max(this.ydisp-I,0),this.savedY=Math.max(this.savedY-I,0)),this.lines.maxLength=A}this.x=Math.min(this.x,L-1),this.y=Math.min(this.y,O-1),j&&(this.y+=j),this.savedX=Math.min(this.savedX,L-1),this.scrollTop=0}if(this.scrollBottom=O-1,this._isReflowEnabled&&(this._reflow(L,O),this._cols>L))for(let j=0;j<this.lines.length;j++)M+=+this.lines.get(j).resize(L,E);this._cols=L,this._rows=O,this._memoryCleanupQueue.clear(),M>0.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let L=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,L=!1);let O=0;for(;this._memoryCleanupPosition<this.lines.length;)if(O+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),O>100)return!0;return L}get _isReflowEnabled(){let L=this._optionsService.rawOptions.windowsPty;return L&&L.buildNumber?this._hasScrollback&&L.backend==="conpty"&&L.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(L,O){this._cols!==L&&(L>this._cols?this._reflowLarger(L,O):this._reflowSmaller(L,O))}_reflowLarger(L,O){let E=(0,U.reflowLargerGetLinesToRemove)(this.lines,this._cols,L,this.ybase+this.y,this.getNullCell(H.DEFAULT_ATTR_DATA));if(E.length>0){let M=(0,U.reflowLargerCreateNewLayout)(this.lines,E);(0,U.reflowLargerApplyNewLayout)(this.lines,M.layout),this._reflowLargerAdjustViewport(L,O,M.countRemoved)}}_reflowLargerAdjustViewport(L,O,E){let M=this.getNullCell(H.DEFAULT_ATTR_DATA),A=E;for(;A-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<O&&this.lines.push(new H.BufferLine(L,M))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-E,0)}_reflowSmaller(L,O){let E=this.getNullCell(H.DEFAULT_ATTR_DATA),M=[],A=0;for(let j=this.lines.length-1;j>=0;j--){let I=this.lines.get(j);if(!I||!I.isWrapped&&I.getTrimmedLength()<=L)continue;let T=[I];for(;I.isWrapped&&j>0;)I=this.lines.get(--j),T.unshift(I);let P=this.ybase+this.y;if(P>=j&&P<j+T.length)continue;let h=T[T.length-1].getTrimmedLength(),p=(0,U.reflowSmallerGetNewLineLengths)(T,this._cols,L),x=p.length-T.length,k;k=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+x):Math.max(0,this.lines.length-this.lines.maxLength+x);let f=[];for(let s=0;s<x;s++){let W0=this.getBlankLine(H.DEFAULT_ATTR_DATA,!0);f.push(W0)}f.length>0&&(M.push({start:j+T.length+A,newLines:f}),A+=f.length),T.push(...f);let d=p.length-1,m=p[d];m===0&&(d--,m=p[d]);let b=T.length-x-1,n=h;for(;b>=0;){let s=Math.min(n,m);if(T[d]===void 0)break;if(T[d].copyCellsFrom(T[b],n-s,m-s,s,!0),m-=s,m===0&&(d--,m=p[d]),n-=s,n===0){b--;let W0=Math.max(b,0);n=(0,U.getWrappedLineTrimmedLength)(T,W0,this._cols)}}for(let s=0;s<T.length;s++)p[s]<L&&T[s].setCell(p[s],E);let c=x-k;for(;c-- >0;)this.ybase===0?this.y<O-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+A)-O&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+x,this.ybase+O-1)}if(M.length>0){let j=[],I=[];for(let d=0;d<this.lines.length;d++)I.push(this.lines.get(d));let T=this.lines.length,P=T-1,h=0,p=M[h];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+A);let x=0;for(let d=Math.min(this.lines.maxLength-1,T+A-1);d>=0;d--)if(p&&p.start>P+x){for(let m=p.newLines.length-1;m>=0;m--)this.lines.set(d--,p.newLines[m]);d++,j.push({index:P+1,amount:p.newLines.length}),x+=p.newLines.length,p=M[++h]}else this.lines.set(d,I[P--]);let k=0;for(let d=j.length-1;d>=0;d--)j[d].index+=k,this.lines.onInsertEmitter.fire(j[d]),k+=j[d].amount;let f=Math.max(0,T+A-this.lines.maxLength);f>0&&this.lines.onTrimEmitter.fire(f)}}translateBufferLineToString(L,O,E=0,M){let A=this.lines.get(L);return A?A.translateToString(O,E,M):""}getWrappedRangeForLine(L){let O=L,E=L;for(;O>0&&this.lines.get(O).isWrapped;)O--;for(;E+1<this.lines.length&&this.lines.get(E+1).isWrapped;)E++;return{first:O,last:E}}setupTabStops(L){for(L!=null?this.tabs[L]||(L=this.prevStop(L)):(this.tabs={},L=0);L<this._cols;L+=this._optionsService.rawOptions.tabStopWidth)this.tabs[L]=!0}prevStop(L){for(L==null&&(L=this.x);!this.tabs[--L]&&L>0;);return L>=this._cols?this._cols-1:L<0?0:L}nextStop(L){for(L==null&&(L=this.x);!this.tabs[++L]&&L<this._cols;);return L>=this._cols?this._cols-1:L<0?0:L}clearMarkers(L){this._isClearing=!0;for(let O=0;O<this.markers.length;O++)this.markers[O].line===L&&(this.markers[O].dispose(),this.markers.splice(O--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let L=0;L<this.markers.length;L++)this.markers[L].dispose(),this.markers.splice(L--,1);this._isClearing=!1}addMarker(L){let O=new N.Marker(L);return this.markers.push(O),O.register(this.lines.onTrim((E)=>{O.line-=E,O.line<0&&O.dispose()})),O.register(this.lines.onInsert((E)=>{O.line>=E.index&&(O.line+=E.amount)})),O.register(this.lines.onDelete((E)=>{O.line>=E.index&&O.line<E.index+E.amount&&O.dispose(),O.line>E.index&&(O.line-=E.amount)})),O.register(O.onDispose(()=>this._removeMarker(O))),O}_removeMarker(L){this._isClearing||this.markers.splice(this.markers.indexOf(L),1)}}},437:(V,G,F)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.BufferLine=G.DEFAULT_ATTR_DATA=void 0;let z=F(734),q=F(511),W=F(643),H=F(482);G.DEFAULT_ATTR_DATA=Object.freeze(new z.AttributeData);let U=0;class D{constructor(B,N,w=!1){this.isWrapped=w,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*B);let L=N||q.CellData.fromCharData([0,W.NULL_CELL_CHAR,W.NULL_CELL_WIDTH,W.NULL_CELL_CODE]);for(let O=0;O<B;++O)this.setCell(O,L);this.length=B}get(B){let N=this._data[3*B+0],w=2097151&N;return[this._data[3*B+1],2097152&N?this._combined[B]:w?(0,H.stringFromCodePoint)(w):"",N>>22,2097152&N?this._combined[B].charCodeAt(this._combined[B].length-1):w]}set(B,N){this._data[3*B+1]=N[W.CHAR_DATA_ATTR_INDEX],N[W.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[B]=N[1],this._data[3*B+0]=2097152|B|N[W.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*B+0]=N[W.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|N[W.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(B){return this._data[3*B+0]>>22}hasWidth(B){return 12582912&this._data[3*B+0]}getFg(B){return this._data[3*B+1]}getBg(B){return this._data[3*B+2]}hasContent(B){return 4194303&this._data[3*B+0]}getCodePoint(B){let N=this._data[3*B+0];return 2097152&N?this._combined[B].charCodeAt(this._combined[B].length-1):2097151&N}isCombined(B){return 2097152&this._data[3*B+0]}getString(B){let N=this._data[3*B+0];return 2097152&N?this._combined[B]:2097151&N?(0,H.stringFromCodePoint)(2097151&N):""}isProtected(B){return 536870912&this._data[3*B+2]}loadCell(B,N){return U=3*B,N.content=this._data[U+0],N.fg=this._data[U+1],N.bg=this._data[U+2],2097152&N.content&&(N.combinedData=this._combined[B]),268435456&N.bg&&(N.extended=this._extendedAttrs[B]),N}setCell(B,N){2097152&N.content&&(this._combined[B]=N.combinedData),268435456&N.bg&&(this._extendedAttrs[B]=N.extended),this._data[3*B+0]=N.content,this._data[3*B+1]=N.fg,this._data[3*B+2]=N.bg}setCellFromCodepoint(B,N,w,L){268435456&L.bg&&(this._extendedAttrs[B]=L.extended),this._data[3*B+0]=N|w<<22,this._data[3*B+1]=L.fg,this._data[3*B+2]=L.bg}addCodepointToCell(B,N,w){let L=this._data[3*B+0];2097152&L?this._combined[B]+=(0,H.stringFromCodePoint)(N):2097151&L?(this._combined[B]=(0,H.stringFromCodePoint)(2097151&L)+(0,H.stringFromCodePoint)(N),L&=-2097152,L|=2097152):L=N|4194304,w&&(L&=-12582913,L|=w<<22),this._data[3*B+0]=L}insertCells(B,N,w){if((B%=this.length)&&this.getWidth(B-1)===2&&this.setCellFromCodepoint(B-1,0,1,w),N<this.length-B){let L=new q.CellData;for(let O=this.length-B-N-1;O>=0;--O)this.setCell(B+N+O,this.loadCell(B+O,L));for(let O=0;O<N;++O)this.setCell(B+O,w)}else for(let L=B;L<this.length;++L)this.setCell(L,w);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,w)}deleteCells(B,N,w){if(B%=this.length,N<this.length-B){let L=new q.CellData;for(let O=0;O<this.length-B-N;++O)this.setCell(B+O,this.loadCell(B+N+O,L));for(let O=this.length-N;O<this.length;++O)this.setCell(O,w)}else for(let L=B;L<this.length;++L)this.setCell(L,w);B&&this.getWidth(B-1)===2&&this.setCellFromCodepoint(B-1,0,1,w),this.getWidth(B)!==0||this.hasContent(B)||this.setCellFromCodepoint(B,0,1,w)}replaceCells(B,N,w,L=!1){if(L)for(B&&this.getWidth(B-1)===2&&!this.isProtected(B-1)&&this.setCellFromCodepoint(B-1,0,1,w),N<this.length&&this.getWidth(N-1)===2&&!this.isProtected(N)&&this.setCellFromCodepoint(N,0,1,w);B<N&&B<this.length;)this.isProtected(B)||this.setCell(B,w),B++;else for(B&&this.getWidth(B-1)===2&&this.setCellFromCodepoint(B-1,0,1,w),N<this.length&&this.getWidth(N-1)===2&&this.setCellFromCodepoint(N,0,1,w);B<N&&B<this.length;)this.setCell(B++,w)}resize(B,N){if(B===this.length)return 4*this._data.length*2<this._data.buffer.byteLength;let w=3*B;if(B>this.length){if(this._data.buffer.byteLength>=4*w)this._data=new Uint32Array(this._data.buffer,0,w);else{let L=new Uint32Array(w);L.set(this._data),this._data=L}for(let L=this.length;L<B;++L)this.setCell(L,N)}else{this._data=this._data.subarray(0,w);let L=Object.keys(this._combined);for(let E=0;E<L.length;E++){let M=parseInt(L[E],10);M>=B&&delete this._combined[M]}let O=Object.keys(this._extendedAttrs);for(let E=0;E<O.length;E++){let M=parseInt(O[E],10);M>=B&&delete this._extendedAttrs[M]}}return this.length=B,4*w*2<this._data.buffer.byteLength}cleanupMemory(){if(4*this._data.length*2<this._data.buffer.byteLength){let B=new Uint32Array(this._data.length);return B.set(this._data),this._data=B,1}return 0}fill(B,N=!1){if(N)for(let w=0;w<this.length;++w)this.isProtected(w)||this.setCell(w,B);else{this._combined={},this._extendedAttrs={};for(let w=0;w<this.length;++w)this.setCell(w,B)}}copyFrom(B){this.length!==B.length?this._data=new Uint32Array(B._data):this._data.set(B._data),this.length=B.length,this._combined={};for(let N in B._combined)this._combined[N]=B._combined[N];this._extendedAttrs={};for(let N in B._extendedAttrs)this._extendedAttrs[N]=B._extendedAttrs[N];this.isWrapped=B.isWrapped}clone(){let B=new D(0);B._data=new Uint32Array(this._data),B.length=this.length;for(let N in this._combined)B._combined[N]=this._combined[N];for(let N in this._extendedAttrs)B._extendedAttrs[N]=this._extendedAttrs[N];return B.isWrapped=this.isWrapped,B}getTrimmedLength(){for(let B=this.length-1;B>=0;--B)if(4194303&this._data[3*B+0])return B+(this._data[3*B+0]>>22);return 0}getNoBgTrimmedLength(){for(let B=this.length-1;B>=0;--B)if(4194303&this._data[3*B+0]||50331648&this._data[3*B+2])return B+(this._data[3*B+0]>>22);return 0}copyCellsFrom(B,N,w,L,O){let E=B._data;if(O)for(let A=L-1;A>=0;A--){for(let j=0;j<3;j++)this._data[3*(w+A)+j]=E[3*(N+A)+j];268435456&E[3*(N+A)+2]&&(this._extendedAttrs[w+A]=B._extendedAttrs[N+A])}else for(let A=0;A<L;A++){for(let j=0;j<3;j++)this._data[3*(w+A)+j]=E[3*(N+A)+j];268435456&E[3*(N+A)+2]&&(this._extendedAttrs[w+A]=B._extendedAttrs[N+A])}let M=Object.keys(B._combined);for(let A=0;A<M.length;A++){let j=parseInt(M[A],10);j>=N&&(this._combined[j-N+w]=B._combined[j])}}translateToString(B,N,w,L){N=N??0,w=w??this.length,B&&(w=Math.min(w,this.getTrimmedLength())),L&&(L.length=0);let O="";for(;N<w;){let E=this._data[3*N+0],M=2097151&E,A=2097152&E?this._combined[N]:M?(0,H.stringFromCodePoint)(M):W.WHITESPACE_CELL_CHAR;if(O+=A,L)for(let j=0;j<A.length;++j)L.push(N);N+=E>>22||1}return L&&L.push(N),O}}G.BufferLine=D},634:(V,G)=>{function F(z,q,W){if(q===z.length-1)return z[q].getTrimmedLength();let H=!z[q].hasContent(W-1)&&z[q].getWidth(W-1)===1,U=z[q+1].getWidth(0)===2;return H&&U?W-1:W}Object.defineProperty(G,"__esModule",{value:!0}),G.getWrappedLineTrimmedLength=G.reflowSmallerGetNewLineLengths=G.reflowLargerApplyNewLayout=G.reflowLargerCreateNewLayout=G.reflowLargerGetLinesToRemove=void 0,G.reflowLargerGetLinesToRemove=function(z,q,W,H,U){let D=[];for(let B=0;B<z.length-1;B++){let N=B,w=z.get(++N);if(!w.isWrapped)continue;let L=[z.get(B)];for(;N<z.length&&w.isWrapped;)L.push(w),w=z.get(++N);if(H>=B&&H<N){B+=L.length-1;continue}let O=0,E=F(L,O,q),M=1,A=0;for(;M<L.length;){let I=F(L,M,q),T=I-A,P=W-E,h=Math.min(T,P);L[O].copyCellsFrom(L[M],A,E,h,!1),E+=h,E===W&&(O++,E=0),A+=h,A===I&&(M++,A=0),E===0&&O!==0&&L[O-1].getWidth(W-1)===2&&(L[O].copyCellsFrom(L[O-1],W-1,E++,1,!1),L[O-1].setCell(W-1,U))}L[O].replaceCells(E,W,U);let j=0;for(let I=L.length-1;I>0&&(I>O||L[I].getTrimmedLength()===0);I--)j++;j>0&&(D.push(B+L.length-j),D.push(j)),B+=L.length-1}return D},G.reflowLargerCreateNewLayout=function(z,q){let W=[],H=0,U=q[H],D=0;for(let B=0;B<z.length;B++)if(U===B){let N=q[++H];z.onDeleteEmitter.fire({index:B-D,amount:N}),B+=N-1,D+=N,U=q[++H]}else W.push(B);return{layout:W,countRemoved:D}},G.reflowLargerApplyNewLayout=function(z,q){let W=[];for(let H=0;H<q.length;H++)W.push(z.get(q[H]));for(let H=0;H<W.length;H++)z.set(H,W[H]);z.length=q.length},G.reflowSmallerGetNewLineLengths=function(z,q,W){let H=[],U=z.map((w,L)=>F(z,L,q)).reduce((w,L)=>w+L),D=0,B=0,N=0;for(;N<U;){if(U-N<W){H.push(U-N);break}D+=W;let w=F(z,B,q);D>w&&(D-=w,B++);let L=z[B].getWidth(D-1)===2;L&&D--;let O=L?W-1:W;H.push(O),N+=O}return H},G.getWrappedLineTrimmedLength=F},295:(V,G,F)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.BufferSet=void 0;let z=F(460),q=F(844),W=F(92);class H extends q.Disposable{constructor(U,D){super(),this._optionsService=U,this._bufferService=D,this._onBufferActivate=this.register(new z.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 W.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new W.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(U){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(U),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(U,D){this._normal.resize(U,D),this._alt.resize(U,D),this.setupTabStops(U)}setupTabStops(U){this._normal.setupTabStops(U),this._alt.setupTabStops(U)}}G.BufferSet=H},511:(V,G,F)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.CellData=void 0;let z=F(482),q=F(643),W=F(734);class H extends W.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new W.ExtendedAttrs,this.combinedData=""}static fromCharData(U){let D=new H;return D.setFromCharData(U),D}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,z.stringFromCodePoint)(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(U){this.fg=U[q.CHAR_DATA_ATTR_INDEX],this.bg=0;let D=!1;if(U[q.CHAR_DATA_CHAR_INDEX].length>2)D=!0;else if(U[q.CHAR_DATA_CHAR_INDEX].length===2){let B=U[q.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=B&&B<=56319){let N=U[q.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=N&&N<=57343?this.content=1024*(B-55296)+N-56320+65536|U[q.CHAR_DATA_WIDTH_INDEX]<<22:D=!0}else D=!0}else this.content=U[q.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|U[q.CHAR_DATA_WIDTH_INDEX]<<22;D&&(this.combinedData=U[q.CHAR_DATA_CHAR_INDEX],this.content=2097152|U[q.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}G.CellData=H},643:(V,G)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.WHITESPACE_CELL_CODE=G.WHITESPACE_CELL_WIDTH=G.WHITESPACE_CELL_CHAR=G.NULL_CELL_CODE=G.NULL_CELL_WIDTH=G.NULL_CELL_CHAR=G.CHAR_DATA_CODE_INDEX=G.CHAR_DATA_WIDTH_INDEX=G.CHAR_DATA_CHAR_INDEX=G.CHAR_DATA_ATTR_INDEX=G.DEFAULT_EXT=G.DEFAULT_ATTR=G.DEFAULT_COLOR=void 0,G.DEFAULT_COLOR=0,G.DEFAULT_ATTR=256|G.DEFAULT_COLOR<<9,G.DEFAULT_EXT=0,G.CHAR_DATA_ATTR_INDEX=0,G.CHAR_DATA_CHAR_INDEX=1,G.CHAR_DATA_WIDTH_INDEX=2,G.CHAR_DATA_CODE_INDEX=3,G.NULL_CELL_CHAR="",G.NULL_CELL_WIDTH=1,G.NULL_CELL_CODE=0,G.WHITESPACE_CELL_CHAR=" ",G.WHITESPACE_CELL_WIDTH=1,G.WHITESPACE_CELL_CODE=32},863:(V,G,F)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.Marker=void 0;let z=F(460),q=F(844);class W{get id(){return this._id}constructor(H){this.line=H,this.isDisposed=!1,this._disposables=[],this._id=W._nextId++,this._onDispose=this.register(new z.EventEmitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,q.disposeArray)(this._disposables),this._disposables.length=0)}register(H){return this._disposables.push(H),H}}G.Marker=W,W._nextId=1},116:(V,G)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.DEFAULT_CHARSET=G.CHARSETS=void 0,G.CHARSETS={},G.DEFAULT_CHARSET=G.CHARSETS.B,G.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:"≥","{":"π","|":"≠","}":"£","~":"·"},G.CHARSETS.A={"#":"£"},G.CHARSETS.B=void 0,G.CHARSETS[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"},G.CHARSETS.C=G.CHARSETS[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},G.CHARSETS.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"},G.CHARSETS.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"},G.CHARSETS.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"},G.CHARSETS.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"},G.CHARSETS.E=G.CHARSETS[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"},G.CHARSETS.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"},G.CHARSETS.H=G.CHARSETS[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},G.CHARSETS["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"}},584:(V,G)=>{var F,z,q;Object.defineProperty(G,"__esModule",{value:!0}),G.C1_ESCAPED=G.C1=G.C0=void 0,function(W){W.NUL="\x00",W.SOH="\x01",W.STX="\x02",W.ETX="\x03",W.EOT="\x04",W.ENQ="\x05",W.ACK="\x06",W.BEL="\x07",W.BS="\b",W.HT="\t",W.LF=`
2261
2261
  `,W.VT="\v",W.FF="\f",W.CR="\r",W.SO="\x0E",W.SI="\x0F",W.DLE="\x10",W.DC1="\x11",W.DC2="\x12",W.DC3="\x13",W.DC4="\x14",W.NAK="\x15",W.SYN="\x16",W.ETB="\x17",W.CAN="\x18",W.EM="\x19",W.SUB="\x1A",W.ESC="\x1B",W.FS="\x1C",W.GS="\x1D",W.RS="\x1E",W.US="\x1F",W.SP=" ",W.DEL=""}(F||(G.C0=F={})),function(W){W.PAD="€",W.HOP="",W.BPH="‚",W.NBH="ƒ",W.IND="„",W.NEL="…",W.SSA="†",W.ESA="‡",W.HTS="ˆ",W.HTJ="‰",W.VTS="Š",W.PLD="‹",W.PLU="Œ",W.RI="",W.SS2="Ž",W.SS3="",W.DCS="",W.PU1="‘",W.PU2="’",W.STS="“",W.CCH="”",W.MW="•",W.SPA="–",W.EPA="—",W.SOS="˜",W.SGCI="™",W.SCI="š",W.CSI="›",W.ST="œ",W.OSC="",W.PM="ž",W.APC="Ÿ"}(z||(G.C1=z={})),function(W){W.ST=`${F.ESC}\\`}(q||(G.C1_ESCAPED=q={}))},482:(V,G)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.Utf8ToUtf32=G.StringToUtf32=G.utf32ToString=G.stringFromCodePoint=void 0,G.stringFromCodePoint=function(F){return F>65535?(F-=65536,String.fromCharCode(55296+(F>>10))+String.fromCharCode(F%1024+56320)):String.fromCharCode(F)},G.utf32ToString=function(F,z=0,q=F.length){let W="";for(let H=z;H<q;++H){let U=F[H];U>65535?(U-=65536,W+=String.fromCharCode(55296+(U>>10))+String.fromCharCode(U%1024+56320)):W+=String.fromCharCode(U)}return W},G.StringToUtf32=class{constructor(){this._interim=0}clear(){this._interim=0}decode(F,z){let q=F.length;if(!q)return 0;let W=0,H=0;if(this._interim){let U=F.charCodeAt(H++);56320<=U&&U<=57343?z[W++]=1024*(this._interim-55296)+U-56320+65536:(z[W++]=this._interim,z[W++]=U),this._interim=0}for(let U=H;U<q;++U){let D=F.charCodeAt(U);if(55296<=D&&D<=56319){if(++U>=q)return this._interim=D,W;let B=F.charCodeAt(U);56320<=B&&B<=57343?z[W++]=1024*(D-55296)+B-56320+65536:(z[W++]=D,z[W++]=B)}else D!==65279&&(z[W++]=D)}return W}},G.Utf8ToUtf32=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(F,z){let q=F.length;if(!q)return 0;let W,H,U,D,B=0,N=0,w=0;if(this.interim[0]){let E=!1,M=this.interim[0];M&=(224&M)==192?31:(240&M)==224?15:7;let A,j=0;for(;(A=63&this.interim[++j])&&j<4;)M<<=6,M|=A;let I=(224&this.interim[0])==192?2:(240&this.interim[0])==224?3:4,T=I-j;for(;w<T;){if(w>=q)return 0;if(A=F[w++],(192&A)!=128){w--,E=!0;break}this.interim[j++]=A,M<<=6,M|=63&A}E||(I===2?M<128?w--:z[B++]=M:I===3?M<2048||M>=55296&&M<=57343||M===65279||(z[B++]=M):M<65536||M>1114111||(z[B++]=M)),this.interim.fill(0)}let L=q-4,O=w;for(;O<q;){for(;!(!(O<L)||128&(W=F[O])||128&(H=F[O+1])||128&(U=F[O+2])||128&(D=F[O+3]));)z[B++]=W,z[B++]=H,z[B++]=U,z[B++]=D,O+=4;if(W=F[O++],W<128)z[B++]=W;else if((224&W)==192){if(O>=q)return this.interim[0]=W,B;if(H=F[O++],(192&H)!=128){O--;continue}if(N=(31&W)<<6|63&H,N<128){O--;continue}z[B++]=N}else if((240&W)==224){if(O>=q)return this.interim[0]=W,B;if(H=F[O++],(192&H)!=128){O--;continue}if(O>=q)return this.interim[0]=W,this.interim[1]=H,B;if(U=F[O++],(192&U)!=128){O--;continue}if(N=(15&W)<<12|(63&H)<<6|63&U,N<2048||N>=55296&&N<=57343||N===65279)continue;z[B++]=N}else if((248&W)==240){if(O>=q)return this.interim[0]=W,B;if(H=F[O++],(192&H)!=128){O--;continue}if(O>=q)return this.interim[0]=W,this.interim[1]=H,B;if(U=F[O++],(192&U)!=128){O--;continue}if(O>=q)return this.interim[0]=W,this.interim[1]=H,this.interim[2]=U,B;if(D=F[O++],(192&D)!=128){O--;continue}if(N=(7&W)<<18|(63&H)<<12|(63&U)<<6|63&D,N<65536||N>1114111)continue;z[B++]=N}}return B}}},225:(V,G,F)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.UnicodeV6=void 0;let z=F(480),q=[[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]],W=[[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]],H;G.UnicodeV6=class{constructor(){if(this.version="6",!H){H=new Uint8Array(65536),H.fill(1),H[0]=0,H.fill(0,1,32),H.fill(0,127,160),H.fill(2,4352,4448),H[9001]=2,H[9002]=2,H.fill(2,11904,42192),H[12351]=1,H.fill(2,44032,55204),H.fill(2,63744,64256),H.fill(2,65040,65050),H.fill(2,65072,65136),H.fill(2,65280,65377),H.fill(2,65504,65511);for(let U=0;U<q.length;++U)H.fill(0,q[U][0],q[U][1]+1)}}wcwidth(U){return U<32?0:U<127?1:U<65536?H[U]:function(D,B){let N,w=0,L=B.length-1;if(D<B[0][0]||D>B[L][1])return!1;for(;L>=w;)if(N=w+L>>1,D>B[N][1])w=N+1;else{if(!(D<B[N][0]))return!0;L=N-1}return!1}(U,W)?0:U>=131072&&U<=196605||U>=196608&&U<=262141?2:1}charProperties(U,D){let B=this.wcwidth(U),N=B===0&&D!==0;if(N){let w=z.UnicodeService.extractWidth(D);w===0?N=!1:w>B&&(B=w)}return z.UnicodeService.createPropertyValue(0,B,N)}}},981:(V,G,F)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.WriteBuffer=void 0;let z=F(460),q=F(844);class W extends q.Disposable{constructor(H){super(),this._action=H,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this.register(new z.EventEmitter),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(H,U){if(U!==void 0&&this._syncCalls>U)return void(this._syncCalls=0);if(this._pendingData+=H.length,this._writeBuffer.push(H),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;let D;for(this._isSyncWriting=!0;D=this._writeBuffer.shift();){this._action(D);let B=this._callbacks.shift();B&&B()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(H,U){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+=H.length,this._writeBuffer.push(H),this._callbacks.push(U),void this._innerWrite();setTimeout(()=>this._innerWrite())}this._pendingData+=H.length,this._writeBuffer.push(H),this._callbacks.push(U)}_innerWrite(H=0,U=!0){let D=H||Date.now();for(;this._writeBuffer.length>this._bufferOffset;){let B=this._writeBuffer[this._bufferOffset],N=this._action(B,U);if(N){let L=(O)=>Date.now()-D>=12?setTimeout(()=>this._innerWrite(0,O)):this._innerWrite(D,O);return void N.catch((O)=>(queueMicrotask(()=>{throw O}),Promise.resolve(!1))).then(L)}let w=this._callbacks[this._bufferOffset];if(w&&w(),this._bufferOffset++,this._pendingData-=B.length,Date.now()-D>=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()}}G.WriteBuffer=W},941:(V,G)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.toRgbString=G.parseColor=void 0;let F=/^([\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})$/,z=/^[\da-f]+$/;function q(W,H){let U=W.toString(16),D=U.length<2?"0"+U:U;switch(H){case 4:return U[0];case 8:return D;case 12:return(D+D).slice(0,3);default:return D+D}}G.parseColor=function(W){if(!W)return;let H=W.toLowerCase();if(H.indexOf("rgb:")===0){H=H.slice(4);let U=F.exec(H);if(U){let D=U[1]?15:U[4]?255:U[7]?4095:65535;return[Math.round(parseInt(U[1]||U[4]||U[7]||U[10],16)/D*255),Math.round(parseInt(U[2]||U[5]||U[8]||U[11],16)/D*255),Math.round(parseInt(U[3]||U[6]||U[9]||U[12],16)/D*255)]}}else if(H.indexOf("#")===0&&(H=H.slice(1),z.exec(H)&&[3,6,9,12].includes(H.length))){let U=H.length/3,D=[0,0,0];for(let B=0;B<3;++B){let N=parseInt(H.slice(U*B,U*B+U),16);D[B]=U===1?N<<4:U===2?N:U===3?N>>4:N>>8}return D}},G.toRgbString=function(W,H=16){let[U,D,B]=W;return`rgb:${q(U,H)}/${q(D,H)}/${q(B,H)}`}},770:(V,G)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.PAYLOAD_LIMIT=void 0,G.PAYLOAD_LIMIT=1e7},351:(V,G,F)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.DcsHandler=G.DcsParser=void 0;let z=F(482),q=F(742),W=F(770),H=[];G.DcsParser=class{constructor(){this._handlers=Object.create(null),this._active=H,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=H}registerHandler(D,B){this._handlers[D]===void 0&&(this._handlers[D]=[]);let N=this._handlers[D];return N.push(B),{dispose:()=>{let w=N.indexOf(B);w!==-1&&N.splice(w,1)}}}clearHandler(D){this._handlers[D]&&delete this._handlers[D]}setHandlerFallback(D){this._handlerFb=D}reset(){if(this._active.length)for(let D=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;D>=0;--D)this._active[D].unhook(!1);this._stack.paused=!1,this._active=H,this._ident=0}hook(D,B){if(this.reset(),this._ident=D,this._active=this._handlers[D]||H,this._active.length)for(let N=this._active.length-1;N>=0;N--)this._active[N].hook(B);else this._handlerFb(this._ident,"HOOK",B)}put(D,B,N){if(this._active.length)for(let w=this._active.length-1;w>=0;w--)this._active[w].put(D,B,N);else this._handlerFb(this._ident,"PUT",(0,z.utf32ToString)(D,B,N))}unhook(D,B=!0){if(this._active.length){let N=!1,w=this._active.length-1,L=!1;if(this._stack.paused&&(w=this._stack.loopPosition-1,N=B,L=this._stack.fallThrough,this._stack.paused=!1),!L&&N===!1){for(;w>=0&&(N=this._active[w].unhook(D),N!==!0);w--)if(N instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=w,this._stack.fallThrough=!1,N;w--}for(;w>=0;w--)if(N=this._active[w].unhook(!1),N instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=w,this._stack.fallThrough=!0,N}else this._handlerFb(this._ident,"UNHOOK",D);this._active=H,this._ident=0}};let U=new q.Params;U.addParam(0),G.DcsHandler=class{constructor(D){this._handler=D,this._data="",this._params=U,this._hitLimit=!1}hook(D){this._params=D.length>1||D.params[0]?D.clone():U,this._data="",this._hitLimit=!1}put(D,B,N){this._hitLimit||(this._data+=(0,z.utf32ToString)(D,B,N),this._data.length>W.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}unhook(D){let B=!1;if(this._hitLimit)B=!1;else if(D&&(B=this._handler(this._data,this._params),B instanceof Promise))return B.then((N)=>(this._params=U,this._data="",this._hitLimit=!1,N));return this._params=U,this._data="",this._hitLimit=!1,B}}},15:(V,G,F)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.EscapeSequenceParser=G.VT500_TRANSITION_TABLE=G.TransitionTable=void 0;let z=F(844),q=F(742),W=F(242),H=F(351);class U{constructor(N){this.table=new Uint8Array(N)}setDefault(N,w){this.table.fill(N<<4|w)}add(N,w,L,O){this.table[w<<8|N]=L<<4|O}addMany(N,w,L,O){for(let E=0;E<N.length;E++)this.table[w<<8|N[E]]=L<<4|O}}G.TransitionTable=U;let D=160;G.VT500_TRANSITION_TABLE=function(){let N=new U(4095),w=Array.apply(null,Array(256)).map((j,I)=>I),L=(j,I)=>w.slice(j,I),O=L(32,127),E=L(0,24);E.push(25),E.push.apply(E,L(28,32));let M=L(0,14),A;for(A in N.setDefault(1,0),N.addMany(O,0,2,0),M)N.addMany([24,26,153,154],A,3,0),N.addMany(L(128,144),A,3,0),N.addMany(L(144,152),A,3,0),N.add(156,A,0,0),N.add(27,A,11,1),N.add(157,A,4,8),N.addMany([152,158,159],A,0,7),N.add(155,A,11,3),N.add(144,A,11,9);return N.addMany(E,0,3,0),N.addMany(E,1,3,1),N.add(127,1,0,1),N.addMany(E,8,0,8),N.addMany(E,3,3,3),N.add(127,3,0,3),N.addMany(E,4,3,4),N.add(127,4,0,4),N.addMany(E,6,3,6),N.addMany(E,5,3,5),N.add(127,5,0,5),N.addMany(E,2,3,2),N.add(127,2,0,2),N.add(93,1,4,8),N.addMany(O,8,5,8),N.add(127,8,5,8),N.addMany([156,27,24,26,7],8,6,0),N.addMany(L(28,32),8,0,8),N.addMany([88,94,95],1,0,7),N.addMany(O,7,0,7),N.addMany(E,7,0,7),N.add(156,7,0,0),N.add(127,7,0,7),N.add(91,1,11,3),N.addMany(L(64,127),3,7,0),N.addMany(L(48,60),3,8,4),N.addMany([60,61,62,63],3,9,4),N.addMany(L(48,60),4,8,4),N.addMany(L(64,127),4,7,0),N.addMany([60,61,62,63],4,0,6),N.addMany(L(32,64),6,0,6),N.add(127,6,0,6),N.addMany(L(64,127),6,0,0),N.addMany(L(32,48),3,9,5),N.addMany(L(32,48),5,9,5),N.addMany(L(48,64),5,0,6),N.addMany(L(64,127),5,7,0),N.addMany(L(32,48),4,9,5),N.addMany(L(32,48),1,9,2),N.addMany(L(32,48),2,9,2),N.addMany(L(48,127),2,10,0),N.addMany(L(48,80),1,10,0),N.addMany(L(81,88),1,10,0),N.addMany([89,90,92],1,10,0),N.addMany(L(96,127),1,10,0),N.add(80,1,11,9),N.addMany(E,9,0,9),N.add(127,9,0,9),N.addMany(L(28,32),9,0,9),N.addMany(L(32,48),9,9,12),N.addMany(L(48,60),9,8,10),N.addMany([60,61,62,63],9,9,10),N.addMany(E,11,0,11),N.addMany(L(32,128),11,0,11),N.addMany(L(28,32),11,0,11),N.addMany(E,10,0,10),N.add(127,10,0,10),N.addMany(L(28,32),10,0,10),N.addMany(L(48,60),10,8,10),N.addMany([60,61,62,63],10,0,11),N.addMany(L(32,48),10,9,12),N.addMany(E,12,0,12),N.add(127,12,0,12),N.addMany(L(28,32),12,0,12),N.addMany(L(32,48),12,9,12),N.addMany(L(48,64),12,0,11),N.addMany(L(64,127),12,12,13),N.addMany(L(64,127),10,12,13),N.addMany(L(64,127),9,12,13),N.addMany(E,13,13,13),N.addMany(O,13,13,13),N.add(127,13,0,13),N.addMany([27,156,24,26],13,14,0),N.add(D,0,2,0),N.add(D,8,5,8),N.add(D,6,0,6),N.add(D,11,0,11),N.add(D,13,13,13),N}();class B extends z.Disposable{constructor(N=G.VT500_TRANSITION_TABLE){super(),this._transitions=N,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new q.Params,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(w,L,O)=>{},this._executeHandlerFb=(w)=>{},this._csiHandlerFb=(w,L)=>{},this._escHandlerFb=(w)=>{},this._errorHandlerFb=(w)=>w,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this.register((0,z.toDisposable)(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this.register(new W.OscParser),this._dcsParser=this.register(new H.DcsParser),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(N,w=[64,126]){let L=0;if(N.prefix){if(N.prefix.length>1)throw Error("only one byte as prefix supported");if(L=N.prefix.charCodeAt(0),L&&60>L||L>63)throw Error("prefix must be in range 0x3c .. 0x3f")}if(N.intermediates){if(N.intermediates.length>2)throw Error("only two bytes as intermediates are supported");for(let E=0;E<N.intermediates.length;++E){let M=N.intermediates.charCodeAt(E);if(32>M||M>47)throw Error("intermediate must be in range 0x20 .. 0x2f");L<<=8,L|=M}}if(N.final.length!==1)throw Error("final must be a single byte");let O=N.final.charCodeAt(0);if(w[0]>O||O>w[1])throw Error(`final must be in range ${w[0]} .. ${w[1]}`);return L<<=8,L|=O,L}identToString(N){let w=[];for(;N;)w.push(String.fromCharCode(255&N)),N>>=8;return w.reverse().join("")}setPrintHandler(N){this._printHandler=N}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(N,w){let L=this._identifier(N,[48,126]);this._escHandlers[L]===void 0&&(this._escHandlers[L]=[]);let O=this._escHandlers[L];return O.push(w),{dispose:()=>{let E=O.indexOf(w);E!==-1&&O.splice(E,1)}}}clearEscHandler(N){this._escHandlers[this._identifier(N,[48,126])]&&delete this._escHandlers[this._identifier(N,[48,126])]}setEscHandlerFallback(N){this._escHandlerFb=N}setExecuteHandler(N,w){this._executeHandlers[N.charCodeAt(0)]=w}clearExecuteHandler(N){this._executeHandlers[N.charCodeAt(0)]&&delete this._executeHandlers[N.charCodeAt(0)]}setExecuteHandlerFallback(N){this._executeHandlerFb=N}registerCsiHandler(N,w){let L=this._identifier(N);this._csiHandlers[L]===void 0&&(this._csiHandlers[L]=[]);let O=this._csiHandlers[L];return O.push(w),{dispose:()=>{let E=O.indexOf(w);E!==-1&&O.splice(E,1)}}}clearCsiHandler(N){this._csiHandlers[this._identifier(N)]&&delete this._csiHandlers[this._identifier(N)]}setCsiHandlerFallback(N){this._csiHandlerFb=N}registerDcsHandler(N,w){return this._dcsParser.registerHandler(this._identifier(N),w)}clearDcsHandler(N){this._dcsParser.clearHandler(this._identifier(N))}setDcsHandlerFallback(N){this._dcsParser.setHandlerFallback(N)}registerOscHandler(N,w){return this._oscParser.registerHandler(N,w)}clearOscHandler(N){this._oscParser.clearHandler(N)}setOscHandlerFallback(N){this._oscParser.setHandlerFallback(N)}setErrorHandler(N){this._errorHandler=N}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(N,w,L,O,E){this._parseStack.state=N,this._parseStack.handlers=w,this._parseStack.handlerPos=L,this._parseStack.transition=O,this._parseStack.chunkPos=E}parse(N,w,L){let O,E=0,M=0,A=0;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,A=this._parseStack.chunkPos+1;else{if(L===void 0||this._parseStack.state===1)throw this._parseStack.state=1,Error("improper continuation due to previous async handler, giving up parsing");let j=this._parseStack.handlers,I=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(L===!1&&I>-1){for(;I>=0&&(O=j[I](this._params),O!==!0);I--)if(O instanceof Promise)return this._parseStack.handlerPos=I,O}this._parseStack.handlers=[];break;case 4:if(L===!1&&I>-1){for(;I>=0&&(O=j[I](),O!==!0);I--)if(O instanceof Promise)return this._parseStack.handlerPos=I,O}this._parseStack.handlers=[];break;case 6:if(E=N[this._parseStack.chunkPos],O=this._dcsParser.unhook(E!==24&&E!==26,L),O)return O;E===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(E=N[this._parseStack.chunkPos],O=this._oscParser.end(E!==24&&E!==26,L),O)return O;E===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,A=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=15&this._parseStack.transition}for(let j=A;j<w;++j){switch(E=N[j],M=this._transitions.table[this.currentState<<8|(E<160?E:D)],M>>4){case 2:for(let p=j+1;;++p){if(p>=w||(E=N[p])<32||E>126&&E<D){this._printHandler(N,j,p),j=p-1;break}if(++p>=w||(E=N[p])<32||E>126&&E<D){this._printHandler(N,j,p),j=p-1;break}if(++p>=w||(E=N[p])<32||E>126&&E<D){this._printHandler(N,j,p),j=p-1;break}if(++p>=w||(E=N[p])<32||E>126&&E<D){this._printHandler(N,j,p),j=p-1;break}}break;case 3:this._executeHandlers[E]?this._executeHandlers[E]():this._executeHandlerFb(E),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:j,code:E,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let I=this._csiHandlers[this._collect<<8|E],T=I?I.length-1:-1;for(;T>=0&&(O=I[T](this._params),O!==!0);T--)if(O instanceof Promise)return this._preserveStack(3,I,T,M,j),O;T<0&&this._csiHandlerFb(this._collect<<8|E,this._params),this.precedingJoinState=0;break;case 8:do switch(E){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(E-48)}while(++j<w&&(E=N[j])>47&&E<60);j--;break;case 9:this._collect<<=8,this._collect|=E;break;case 10:let P=this._escHandlers[this._collect<<8|E],h=P?P.length-1:-1;for(;h>=0&&(O=P[h](),O!==!0);h--)if(O instanceof Promise)return this._preserveStack(4,P,h,M,j),O;h<0&&this._escHandlerFb(this._collect<<8|E),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|E,this._params);break;case 13:for(let p=j+1;;++p)if(p>=w||(E=N[p])===24||E===26||E===27||E>127&&E<D){this._dcsParser.put(N,j,p),j=p-1;break}break;case 14:if(O=this._dcsParser.unhook(E!==24&&E!==26),O)return this._preserveStack(6,[],0,M,j),O;E===27&&(M|=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 p=j+1;;p++)if(p>=w||(E=N[p])<32||E>127&&E<D){this._oscParser.put(N,j,p),j=p-1;break}break;case 6:if(O=this._oscParser.end(E!==24&&E!==26),O)return this._preserveStack(5,[],0,M,j),O;E===27&&(M|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=15&M}}}G.EscapeSequenceParser=B},242:(V,G,F)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.OscHandler=G.OscParser=void 0;let z=F(770),q=F(482),W=[];G.OscParser=class{constructor(){this._state=0,this._active=W,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(H,U){this._handlers[H]===void 0&&(this._handlers[H]=[]);let D=this._handlers[H];return D.push(U),{dispose:()=>{let B=D.indexOf(U);B!==-1&&D.splice(B,1)}}}clearHandler(H){this._handlers[H]&&delete this._handlers[H]}setHandlerFallback(H){this._handlerFb=H}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=W}reset(){if(this._state===2)for(let H=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;H>=0;--H)this._active[H].end(!1);this._stack.paused=!1,this._active=W,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||W,this._active.length)for(let H=this._active.length-1;H>=0;H--)this._active[H].start();else this._handlerFb(this._id,"START")}_put(H,U,D){if(this._active.length)for(let B=this._active.length-1;B>=0;B--)this._active[B].put(H,U,D);else this._handlerFb(this._id,"PUT",(0,q.utf32ToString)(H,U,D))}start(){this.reset(),this._state=1}put(H,U,D){if(this._state!==3){if(this._state===1)for(;U<D;){let B=H[U++];if(B===59){this._state=2,this._start();break}if(B<48||57<B)return void(this._state=3);this._id===-1&&(this._id=0),this._id=10*this._id+B-48}this._state===2&&D-U>0&&this._put(H,U,D)}}end(H,U=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),this._active.length){let D=!1,B=this._active.length-1,N=!1;if(this._stack.paused&&(B=this._stack.loopPosition-1,D=U,N=this._stack.fallThrough,this._stack.paused=!1),!N&&D===!1){for(;B>=0&&(D=this._active[B].end(H),D!==!0);B--)if(D instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=B,this._stack.fallThrough=!1,D;B--}for(;B>=0;B--)if(D=this._active[B].end(!1),D instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=B,this._stack.fallThrough=!0,D}else this._handlerFb(this._id,"END",H);this._active=W,this._id=-1,this._state=0}}},G.OscHandler=class{constructor(H){this._handler=H,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(H,U,D){this._hitLimit||(this._data+=(0,q.utf32ToString)(H,U,D),this._data.length>z.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}end(H){let U=!1;if(this._hitLimit)U=!1;else if(H&&(U=this._handler(this._data),U instanceof Promise))return U.then((D)=>(this._data="",this._hitLimit=!1,D));return this._data="",this._hitLimit=!1,U}}},742:(V,G)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.Params=void 0;let F=2147483647;class z{static fromArray(q){let W=new z;if(!q.length)return W;for(let H=Array.isArray(q[0])?1:0;H<q.length;++H){let U=q[H];if(Array.isArray(U))for(let D=0;D<U.length;++D)W.addSubParam(U[D]);else W.addParam(U)}return W}constructor(q=32,W=32){if(this.maxLength=q,this.maxSubParamsLength=W,W>256)throw Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(q),this.length=0,this._subParams=new Int32Array(W),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(q),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}clone(){let q=new z(this.maxLength,this.maxSubParamsLength);return q.params.set(this.params),q.length=this.length,q._subParams.set(this._subParams),q._subParamsLength=this._subParamsLength,q._subParamsIdx.set(this._subParamsIdx),q._rejectDigits=this._rejectDigits,q._rejectSubDigits=this._rejectSubDigits,q._digitIsSub=this._digitIsSub,q}toArray(){let q=[];for(let W=0;W<this.length;++W){q.push(this.params[W]);let H=this._subParamsIdx[W]>>8,U=255&this._subParamsIdx[W];U-H>0&&q.push(Array.prototype.slice.call(this._subParams,H,U))}return q}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(q){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(q<-1)throw Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=q>F?F:q}}addSubParam(q){if(this._digitIsSub=!0,this.length)if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)this._rejectSubDigits=!0;else{if(q<-1)throw Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=q>F?F:q,this._subParamsIdx[this.length-1]++}}hasSubParams(q){return(255&this._subParamsIdx[q])-(this._subParamsIdx[q]>>8)>0}getSubParams(q){let W=this._subParamsIdx[q]>>8,H=255&this._subParamsIdx[q];return H-W>0?this._subParams.subarray(W,H):null}getSubParamsAll(){let q={};for(let W=0;W<this.length;++W){let H=this._subParamsIdx[W]>>8,U=255&this._subParamsIdx[W];U-H>0&&(q[W]=this._subParams.slice(H,U))}return q}addDigit(q){let W;if(this._rejectDigits||!(W=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let H=this._digitIsSub?this._subParams:this.params,U=H[W-1];H[W-1]=~U?Math.min(10*U+q,F):q}}G.Params=z},741:(V,G)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.AddonManager=void 0,G.AddonManager=class{constructor(){this._addons=[]}dispose(){for(let F=this._addons.length-1;F>=0;F--)this._addons[F].instance.dispose()}loadAddon(F,z){let q={instance:z,dispose:z.dispose,isDisposed:!1};this._addons.push(q),z.dispose=()=>this._wrappedAddonDispose(q),z.activate(F)}_wrappedAddonDispose(F){if(F.isDisposed)return;let z=-1;for(let q=0;q<this._addons.length;q++)if(this._addons[q]===F){z=q;break}if(z===-1)throw Error("Could not dispose an addon that has not been loaded");F.isDisposed=!0,F.dispose.apply(F.instance),this._addons.splice(z,1)}}},771:(V,G,F)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.BufferApiView=void 0;let z=F(785),q=F(511);G.BufferApiView=class{constructor(W,H){this._buffer=W,this.type=H}init(W){return this._buffer=W,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(W){let H=this._buffer.lines.get(W);if(H)return new z.BufferLineApiView(H)}getNullCell(){return new q.CellData}}},785:(V,G,F)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.BufferLineApiView=void 0;let z=F(511);G.BufferLineApiView=class{constructor(q){this._line=q}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(q,W){if(!(q<0||q>=this._line.length))return W?(this._line.loadCell(q,W),W):this._line.loadCell(q,new z.CellData)}translateToString(q,W,H){return this._line.translateToString(q,W,H)}}},285:(V,G,F)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.BufferNamespaceApi=void 0;let z=F(771),q=F(460),W=F(844);class H extends W.Disposable{constructor(U){super(),this._core=U,this._onBufferChange=this.register(new q.EventEmitter),this.onBufferChange=this._onBufferChange.event,this._normal=new z.BufferApiView(this._core.buffers.normal,"normal"),this._alternate=new z.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)}}G.BufferNamespaceApi=H},975:(V,G)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.ParserApi=void 0,G.ParserApi=class{constructor(F){this._core=F}registerCsiHandler(F,z){return this._core.registerCsiHandler(F,(q)=>z(q.toArray()))}addCsiHandler(F,z){return this.registerCsiHandler(F,z)}registerDcsHandler(F,z){return this._core.registerDcsHandler(F,(q,W)=>z(q,W.toArray()))}addDcsHandler(F,z){return this.registerDcsHandler(F,z)}registerEscHandler(F,z){return this._core.registerEscHandler(F,z)}addEscHandler(F,z){return this.registerEscHandler(F,z)}registerOscHandler(F,z){return this._core.registerOscHandler(F,z)}addOscHandler(F,z){return this.registerOscHandler(F,z)}}},90:(V,G)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.UnicodeApi=void 0,G.UnicodeApi=class{constructor(F){this._core=F}register(F){this._core.unicodeService.register(F)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(F){this._core.unicodeService.activeVersion=F}}},744:function(V,G,F){var z=this&&this.__decorate||function(N,w,L,O){var E,M=arguments.length,A=M<3?w:O===null?O=Object.getOwnPropertyDescriptor(w,L):O;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")A=Reflect.decorate(N,w,L,O);else for(var j=N.length-1;j>=0;j--)(E=N[j])&&(A=(M<3?E(A):M>3?E(w,L,A):E(w,L))||A);return M>3&&A&&Object.defineProperty(w,L,A),A},q=this&&this.__param||function(N,w){return function(L,O){w(L,O,N)}};Object.defineProperty(G,"__esModule",{value:!0}),G.BufferService=G.MINIMUM_ROWS=G.MINIMUM_COLS=void 0;let W=F(460),H=F(844),U=F(295),D=F(585);G.MINIMUM_COLS=2,G.MINIMUM_ROWS=1;let B=G.BufferService=class extends H.Disposable{get buffer(){return this.buffers.active}constructor(N){super(),this.isUserScrolling=!1,this._onResize=this.register(new W.EventEmitter),this.onResize=this._onResize.event,this._onScroll=this.register(new W.EventEmitter),this.onScroll=this._onScroll.event,this.cols=Math.max(N.rawOptions.cols||0,G.MINIMUM_COLS),this.rows=Math.max(N.rawOptions.rows||0,G.MINIMUM_ROWS),this.buffers=this.register(new U.BufferSet(N,this))}resize(N,w){this.cols=N,this.rows=w,this.buffers.resize(N,w),this._onResize.fire({cols:N,rows:w})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(N,w=!1){let L=this.buffer,O;O=this._cachedBlankLine,O&&O.length===this.cols&&O.getFg(0)===N.fg&&O.getBg(0)===N.bg||(O=L.getBlankLine(N,w),this._cachedBlankLine=O),O.isWrapped=w;let E=L.ybase+L.scrollTop,M=L.ybase+L.scrollBottom;if(L.scrollTop===0){let A=L.lines.isFull;M===L.lines.length-1?A?L.lines.recycle().copyFrom(O):L.lines.push(O.clone()):L.lines.splice(M+1,0,O.clone()),A?this.isUserScrolling&&(L.ydisp=Math.max(L.ydisp-1,0)):(L.ybase++,this.isUserScrolling||L.ydisp++)}else{let A=M-E+1;L.lines.shiftElements(E+1,A-1,-1),L.lines.set(M,O.clone())}this.isUserScrolling||(L.ydisp=L.ybase),this._onScroll.fire(L.ydisp)}scrollLines(N,w,L){let O=this.buffer;if(N<0){if(O.ydisp===0)return;this.isUserScrolling=!0}else N+O.ydisp>=O.ybase&&(this.isUserScrolling=!1);let E=O.ydisp;O.ydisp=Math.max(Math.min(O.ydisp+N,O.ybase),0),E!==O.ydisp&&(w||this._onScroll.fire(O.ydisp))}};G.BufferService=B=z([q(0,D.IOptionsService)],B)},994:(V,G)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.CharsetService=void 0,G.CharsetService=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(F){this.glevel=F,this.charset=this._charsets[F]}setgCharset(F,z){this._charsets[F]=z,this.glevel===F&&(this.charset=z)}}},753:function(V,G,F){var z=this&&this.__decorate||function(O,E,M,A){var j,I=arguments.length,T=I<3?E:A===null?A=Object.getOwnPropertyDescriptor(E,M):A;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")T=Reflect.decorate(O,E,M,A);else for(var P=O.length-1;P>=0;P--)(j=O[P])&&(T=(I<3?j(T):I>3?j(E,M,T):j(E,M))||T);return I>3&&T&&Object.defineProperty(E,M,T),T},q=this&&this.__param||function(O,E){return function(M,A){E(M,A,O)}};Object.defineProperty(G,"__esModule",{value:!0}),G.CoreMouseService=void 0;let W=F(585),H=F(460),U=F(844),D={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:(O)=>O.button!==4&&O.action===1&&(O.ctrl=!1,O.alt=!1,O.shift=!1,!0)},VT200:{events:19,restrict:(O)=>O.action!==32},DRAG:{events:23,restrict:(O)=>O.action!==32||O.button!==3},ANY:{events:31,restrict:(O)=>!0}};function B(O,E){let M=(O.ctrl?16:0)|(O.shift?4:0)|(O.alt?8:0);return O.button===4?(M|=64,M|=O.action):(M|=3&O.button,4&O.button&&(M|=64),8&O.button&&(M|=128),O.action===32?M|=32:O.action!==0||E||(M|=3)),M}let N=String.fromCharCode,w={DEFAULT:(O)=>{let E=[B(O,!1)+32,O.col+32,O.row+32];return E[0]>255||E[1]>255||E[2]>255?"":`\x1B[M${N(E[0])}${N(E[1])}${N(E[2])}`},SGR:(O)=>{let E=O.action===0&&O.button!==4?"m":"M";return`\x1B[<${B(O,!0)};${O.col};${O.row}${E}`},SGR_PIXELS:(O)=>{let E=O.action===0&&O.button!==4?"m":"M";return`\x1B[<${B(O,!0)};${O.x};${O.y}${E}`}},L=G.CoreMouseService=class extends U.Disposable{constructor(O,E){super(),this._bufferService=O,this._coreService=E,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._onProtocolChange=this.register(new H.EventEmitter),this.onProtocolChange=this._onProtocolChange.event;for(let M of Object.keys(D))this.addProtocol(M,D[M]);for(let M of Object.keys(w))this.addEncoding(M,w[M]);this.reset()}addProtocol(O,E){this._protocols[O]=E}addEncoding(O,E){this._encodings[O]=E}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(O){if(!this._protocols[O])throw Error(`unknown protocol "${O}"`);this._activeProtocol=O,this._onProtocolChange.fire(this._protocols[O].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(O){if(!this._encodings[O])throw Error(`unknown encoding "${O}"`);this._activeEncoding=O}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null}triggerMouseEvent(O){if(O.col<0||O.col>=this._bufferService.cols||O.row<0||O.row>=this._bufferService.rows)return!1;if(O.button===4&&O.action===32)return!1;if(O.button===3&&O.action!==32)return!1;if(O.button!==4&&(O.action===2||O.action===3))return!1;if(O.col++,O.row++,O.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,O,this._activeEncoding==="SGR_PIXELS"))return!1;if(!this._protocols[this._activeProtocol].restrict(O))return!1;let E=this._encodings[this._activeEncoding](O);return E&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(E):this._coreService.triggerDataEvent(E,!0)),this._lastEvent=O,!0}explainEvents(O){return{down:!!(1&O),up:!!(2&O),drag:!!(4&O),move:!!(8&O),wheel:!!(16&O)}}_equalEvents(O,E,M){if(M){if(O.x!==E.x)return!1;if(O.y!==E.y)return!1}else{if(O.col!==E.col)return!1;if(O.row!==E.row)return!1}return O.button===E.button&&O.action===E.action&&O.ctrl===E.ctrl&&O.alt===E.alt&&O.shift===E.shift}};G.CoreMouseService=L=z([q(0,W.IBufferService),q(1,W.ICoreService)],L)},83:function(V,G,F){var z=this&&this.__decorate||function(L,O,E,M){var A,j=arguments.length,I=j<3?O:M===null?M=Object.getOwnPropertyDescriptor(O,E):M;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")I=Reflect.decorate(L,O,E,M);else for(var T=L.length-1;T>=0;T--)(A=L[T])&&(I=(j<3?A(I):j>3?A(O,E,I):A(O,E))||I);return j>3&&I&&Object.defineProperty(O,E,I),I},q=this&&this.__param||function(L,O){return function(E,M){O(E,M,L)}};Object.defineProperty(G,"__esModule",{value:!0}),G.CoreService=void 0;let W=F(439),H=F(460),U=F(844),D=F(585),B=Object.freeze({insertMode:!1}),N=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,origin:!1,reverseWraparound:!1,sendFocus:!1,wraparound:!0}),w=G.CoreService=class extends U.Disposable{constructor(L,O,E){super(),this._bufferService=L,this._logService=O,this._optionsService=E,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this.register(new H.EventEmitter),this.onData=this._onData.event,this._onUserInput=this.register(new H.EventEmitter),this.onUserInput=this._onUserInput.event,this._onBinary=this.register(new H.EventEmitter),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this.register(new H.EventEmitter),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=(0,W.clone)(B),this.decPrivateModes=(0,W.clone)(N)}reset(){this.modes=(0,W.clone)(B),this.decPrivateModes=(0,W.clone)(N)}triggerDataEvent(L,O=!1){if(this._optionsService.rawOptions.disableStdin)return;let E=this._bufferService.buffer;O&&this._optionsService.rawOptions.scrollOnUserInput&&E.ybase!==E.ydisp&&this._onRequestScrollToBottom.fire(),O&&this._onUserInput.fire(),this._logService.debug(`sending data "${L}"`,()=>L.split("").map((M)=>M.charCodeAt(0))),this._onData.fire(L)}triggerBinaryEvent(L){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${L}"`,()=>L.split("").map((O)=>O.charCodeAt(0))),this._onBinary.fire(L))}};G.CoreService=w=z([q(0,D.IBufferService),q(1,D.ILogService),q(2,D.IOptionsService)],w)},348:(V,G,F)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.InstantiationService=G.ServiceCollection=void 0;let z=F(585),q=F(343);class W{constructor(...H){this._entries=new Map;for(let[U,D]of H)this.set(U,D)}set(H,U){let D=this._entries.get(H);return this._entries.set(H,U),D}forEach(H){for(let[U,D]of this._entries.entries())H(U,D)}has(H){return this._entries.has(H)}get(H){return this._entries.get(H)}}G.ServiceCollection=W,G.InstantiationService=class{constructor(){this._services=new W,this._services.set(z.IInstantiationService,this)}setService(H,U){this._services.set(H,U)}getService(H){return this._services.get(H)}createInstance(H,...U){let D=(0,q.getServiceDependencies)(H).sort((w,L)=>w.index-L.index),B=[];for(let w of D){let L=this._services.get(w.id);if(!L)throw Error(`[createInstance] ${H.name} depends on UNKNOWN service ${w.id}.`);B.push(L)}let N=D.length>0?D[0].index:U.length;if(U.length!==N)throw Error(`[createInstance] First service dependency of ${H.name} at position ${N+1} conflicts with ${U.length} static arguments`);return new H(...[...U,...B])}}},866:function(V,G,F){var z=this&&this.__decorate||function(N,w,L,O){var E,M=arguments.length,A=M<3?w:O===null?O=Object.getOwnPropertyDescriptor(w,L):O;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")A=Reflect.decorate(N,w,L,O);else for(var j=N.length-1;j>=0;j--)(E=N[j])&&(A=(M<3?E(A):M>3?E(w,L,A):E(w,L))||A);return M>3&&A&&Object.defineProperty(w,L,A),A},q=this&&this.__param||function(N,w){return function(L,O){w(L,O,N)}};Object.defineProperty(G,"__esModule",{value:!0}),G.traceCall=G.setTraceLogger=G.LogService=void 0;let W=F(844),H=F(585),U={trace:H.LogLevelEnum.TRACE,debug:H.LogLevelEnum.DEBUG,info:H.LogLevelEnum.INFO,warn:H.LogLevelEnum.WARN,error:H.LogLevelEnum.ERROR,off:H.LogLevelEnum.OFF},D,B=G.LogService=class extends W.Disposable{get logLevel(){return this._logLevel}constructor(N){super(),this._optionsService=N,this._logLevel=H.LogLevelEnum.OFF,this._updateLogLevel(),this.register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel())),D=this}_updateLogLevel(){this._logLevel=U[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(N){for(let w=0;w<N.length;w++)typeof N[w]=="function"&&(N[w]=N[w]())}_log(N,w,L){this._evalLazyOptionalParams(L),N.call(console,(this._optionsService.options.logger?"":"xterm.js: ")+w,...L)}trace(N,...w){this._logLevel<=H.LogLevelEnum.TRACE&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,N,w)}debug(N,...w){this._logLevel<=H.LogLevelEnum.DEBUG&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,N,w)}info(N,...w){this._logLevel<=H.LogLevelEnum.INFO&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,N,w)}warn(N,...w){this._logLevel<=H.LogLevelEnum.WARN&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,N,w)}error(N,...w){this._logLevel<=H.LogLevelEnum.ERROR&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,N,w)}};G.LogService=B=z([q(0,H.IOptionsService)],B),G.setTraceLogger=function(N){D=N},G.traceCall=function(N,w,L){if(typeof L.value!="function")throw Error("not supported");let O=L.value;L.value=function(...E){if(D.logLevel!==H.LogLevelEnum.TRACE)return O.apply(this,E);D.trace(`GlyphRenderer#${O.name}(${E.map((A)=>JSON.stringify(A)).join(", ")})`);let M=O.apply(this,E);return D.trace(`GlyphRenderer#${O.name} return`,M),M}}},302:(V,G,F)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.OptionsService=G.DEFAULT_OPTIONS=void 0;let z=F(460),q=F(844),W=F(114);G.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:W.isMac,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRulerWidth:0};let H=["normal","bold","100","200","300","400","500","600","700","800","900"];class U extends q.Disposable{constructor(D){super(),this._onOptionChange=this.register(new z.EventEmitter),this.onOptionChange=this._onOptionChange.event;let B={...G.DEFAULT_OPTIONS};for(let N in D)if(N in B)try{let w=D[N];B[N]=this._sanitizeAndValidateOption(N,w)}catch(w){console.error(w)}this.rawOptions=B,this.options={...B},this._setupOptions(),this.register((0,q.toDisposable)(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(D,B){return this.onOptionChange((N)=>{N===D&&B(this.rawOptions[D])})}onMultipleOptionChange(D,B){return this.onOptionChange((N)=>{D.indexOf(N)!==-1&&B()})}_setupOptions(){let D=(N)=>{if(!(N in G.DEFAULT_OPTIONS))throw Error(`No option with key "${N}"`);return this.rawOptions[N]},B=(N,w)=>{if(!(N in G.DEFAULT_OPTIONS))throw Error(`No option with key "${N}"`);w=this._sanitizeAndValidateOption(N,w),this.rawOptions[N]!==w&&(this.rawOptions[N]=w,this._onOptionChange.fire(N))};for(let N in this.rawOptions){let w={get:D.bind(this,N),set:B.bind(this,N)};Object.defineProperty(this.options,N,w)}}_sanitizeAndValidateOption(D,B){switch(D){case"cursorStyle":if(B||(B=G.DEFAULT_OPTIONS[D]),!function(N){return N==="block"||N==="underline"||N==="bar"}(B))throw Error(`"${B}" is not a valid value for ${D}`);break;case"wordSeparator":B||(B=G.DEFAULT_OPTIONS[D]);break;case"fontWeight":case"fontWeightBold":if(typeof B=="number"&&1<=B&&B<=1000)break;B=H.includes(B)?B:G.DEFAULT_OPTIONS[D];break;case"cursorWidth":B=Math.floor(B);case"lineHeight":case"tabStopWidth":if(B<1)throw Error(`${D} cannot be less than 1, value: ${B}`);break;case"minimumContrastRatio":B=Math.max(1,Math.min(21,Math.round(10*B)/10));break;case"scrollback":if((B=Math.min(B,4294967295))<0)throw Error(`${D} cannot be less than 0, value: ${B}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(B<=0)throw Error(`${D} cannot be less than or equal to 0, value: ${B}`);break;case"rows":case"cols":if(!B&&B!==0)throw Error(`${D} must be numeric, value: ${B}`);break;case"windowsPty":B=B??{}}return B}}G.OptionsService=U},660:function(V,G,F){var z=this&&this.__decorate||function(U,D,B,N){var w,L=arguments.length,O=L<3?D:N===null?N=Object.getOwnPropertyDescriptor(D,B):N;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")O=Reflect.decorate(U,D,B,N);else for(var E=U.length-1;E>=0;E--)(w=U[E])&&(O=(L<3?w(O):L>3?w(D,B,O):w(D,B))||O);return L>3&&O&&Object.defineProperty(D,B,O),O},q=this&&this.__param||function(U,D){return function(B,N){D(B,N,U)}};Object.defineProperty(G,"__esModule",{value:!0}),G.OscLinkService=void 0;let W=F(585),H=G.OscLinkService=class{constructor(U){this._bufferService=U,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(U){let D=this._bufferService.buffer;if(U.id===void 0){let E=D.addMarker(D.ybase+D.y),M={data:U,id:this._nextId++,lines:[E]};return E.onDispose(()=>this._removeMarkerFromLink(M,E)),this._dataByLinkId.set(M.id,M),M.id}let B=U,N=this._getEntryIdKey(B),w=this._entriesWithId.get(N);if(w)return this.addLineToLink(w.id,D.ybase+D.y),w.id;let L=D.addMarker(D.ybase+D.y),O={id:this._nextId++,key:this._getEntryIdKey(B),data:B,lines:[L]};return L.onDispose(()=>this._removeMarkerFromLink(O,L)),this._entriesWithId.set(O.key,O),this._dataByLinkId.set(O.id,O),O.id}addLineToLink(U,D){let B=this._dataByLinkId.get(U);if(B&&B.lines.every((N)=>N.line!==D)){let N=this._bufferService.buffer.addMarker(D);B.lines.push(N),N.onDispose(()=>this._removeMarkerFromLink(B,N))}}getLinkData(U){return this._dataByLinkId.get(U)?.data}_getEntryIdKey(U){return`${U.id};;${U.uri}`}_removeMarkerFromLink(U,D){let B=U.lines.indexOf(D);B!==-1&&(U.lines.splice(B,1),U.lines.length===0&&(U.data.id!==void 0&&this._entriesWithId.delete(U.key),this._dataByLinkId.delete(U.id)))}};G.OscLinkService=H=z([q(0,W.IBufferService)],H)},343:(V,G)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.createDecorator=G.getServiceDependencies=G.serviceRegistry=void 0;let F="di$target",z="di$dependencies";G.serviceRegistry=new Map,G.getServiceDependencies=function(q){return q[z]||[]},G.createDecorator=function(q){if(G.serviceRegistry.has(q))return G.serviceRegistry.get(q);let W=function(H,U,D){if(arguments.length!==3)throw Error("@IServiceName-decorator can only be used to decorate a parameter");(function(B,N,w){N[F]===N?N[z].push({id:B,index:w}):(N[z]=[{id:B,index:w}],N[F]=N)})(W,H,D)};return W.toString=()=>q,G.serviceRegistry.set(q,W),W}},585:(V,G,F)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.IDecorationService=G.IUnicodeService=G.IOscLinkService=G.IOptionsService=G.ILogService=G.LogLevelEnum=G.IInstantiationService=G.ICharsetService=G.ICoreService=G.ICoreMouseService=G.IBufferService=void 0;let z=F(343);var q;G.IBufferService=(0,z.createDecorator)("BufferService"),G.ICoreMouseService=(0,z.createDecorator)("CoreMouseService"),G.ICoreService=(0,z.createDecorator)("CoreService"),G.ICharsetService=(0,z.createDecorator)("CharsetService"),G.IInstantiationService=(0,z.createDecorator)("InstantiationService"),function(W){W[W.TRACE=0]="TRACE",W[W.DEBUG=1]="DEBUG",W[W.INFO=2]="INFO",W[W.WARN=3]="WARN",W[W.ERROR=4]="ERROR",W[W.OFF=5]="OFF"}(q||(G.LogLevelEnum=q={})),G.ILogService=(0,z.createDecorator)("LogService"),G.IOptionsService=(0,z.createDecorator)("OptionsService"),G.IOscLinkService=(0,z.createDecorator)("OscLinkService"),G.IUnicodeService=(0,z.createDecorator)("UnicodeService"),G.IDecorationService=(0,z.createDecorator)("DecorationService")},480:(V,G,F)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.UnicodeService=void 0;let z=F(460),q=F(225);class W{static extractShouldJoin(H){return(1&H)!=0}static extractWidth(H){return H>>1&3}static extractCharKind(H){return H>>3}static createPropertyValue(H,U,D=!1){return(16777215&H)<<3|(3&U)<<1|(D?1:0)}constructor(){this._providers=Object.create(null),this._active="",this._onChange=new z.EventEmitter,this.onChange=this._onChange.event;let H=new q.UnicodeV6;this.register(H),this._active=H.version,this._activeProvider=H}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(H){if(!this._providers[H])throw Error(`unknown Unicode version "${H}"`);this._active=H,this._activeProvider=this._providers[H],this._onChange.fire(H)}register(H){this._providers[H.version]=H}wcwidth(H){return this._activeProvider.wcwidth(H)}getStringCellWidth(H){let U=0,D=0,B=H.length;for(let N=0;N<B;++N){let w=H.charCodeAt(N);if(55296<=w&&w<=56319){if(++N>=B)return U+this.wcwidth(w);let E=H.charCodeAt(N);56320<=E&&E<=57343?w=1024*(w-55296)+E-56320+65536:U+=this.wcwidth(E)}let L=this.charProperties(w,D),O=W.extractWidth(L);W.extractShouldJoin(L)&&(O-=W.extractWidth(D)),U+=O,D=L}return U}charProperties(H,U){return this._activeProvider.charProperties(H,U)}}G.UnicodeService=W},781:(V,G,F)=>{Object.defineProperty(G,"__esModule",{value:!0}),G.Terminal=void 0;let z=F(437),q=F(969),W=F(460);class H extends q.CoreTerminal{constructor(U={}){super(U),this._onBell=this.register(new W.EventEmitter),this.onBell=this._onBell.event,this._onCursorMove=this.register(new W.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onTitleChange=this.register(new W.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onA11yCharEmitter=this.register(new W.EventEmitter),this.onA11yChar=this._onA11yCharEmitter.event,this._onA11yTabEmitter=this.register(new W.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,W.forwardEvent)(this._inputHandler.onCursorMove,this._onCursorMove)),this.register((0,W.forwardEvent)(this._inputHandler.onTitleChange,this._onTitleChange)),this.register((0,W.forwardEvent)(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this.register((0,W.forwardEvent)(this._inputHandler.onA11yTab,this._onA11yTabEmitter))}get buffer(){return this.buffers.active}get markers(){return this.buffer.markers}addMarker(U){if(this.buffer===this.buffers.normal)return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+U)}bell(){this._onBell.fire()}input(U,D=!0){this.coreService.triggerDataEvent(U,D)}resize(U,D){U===this.cols&&D===this.rows||super.resize(U,D)}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 U=1;U<this.rows;U++)this.buffer.lines.push(this.buffer.getBlankLine(z.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()}}G.Terminal=H}},Z={};function Q(V){var G=Z[V];if(G!==void 0)return G.exports;var F=Z[V]={exports:{}};return J[V].call(F.exports,F,F.exports,Q),F.exports}var Y={};(()=>{var V=Y;Object.defineProperty(V,"__esModule",{value:!0}),V.Terminal=void 0;let G=Q(285),F=Q(975),z=Q(90),q=Q(781),W=Q(741),H=Q(844),U=["cols","rows"];class D extends H.Disposable{constructor(B){super(),this._core=this.register(new q.Terminal(B)),this._addonManager=this.register(new W.AddonManager),this._publicOptions={...this._core.options};let N=(L)=>this._core.options[L],w=(L,O)=>{this._checkReadonlyOptions(L),this._core.options[L]=O};for(let L in this._core.options){Object.defineProperty(this._publicOptions,L,{get:()=>this._core.options[L],set:(E)=>{this._checkReadonlyOptions(L),this._core.options[L]=E}});let O={get:N.bind(this,L),set:w.bind(this,L)};Object.defineProperty(this._publicOptions,L,O)}}_checkReadonlyOptions(B){if(U.includes(B))throw Error(`Option "${B}" 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 F.ParserApi(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new z.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 G.BufferNamespaceApi(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let B=this._core.coreService.decPrivateModes,N="none";switch(this._core.coreMouseService.activeProtocol){case"X10":N="x10";break;case"VT200":N="vt200";break;case"DRAG":N="drag";break;case"ANY":N="any"}return{applicationCursorKeysMode:B.applicationCursorKeys,applicationKeypadMode:B.applicationKeypad,bracketedPasteMode:B.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:N,originMode:B.origin,reverseWraparoundMode:B.reverseWraparound,sendFocusMode:B.sendFocus,wraparoundMode:B.wraparound}}get options(){return this._publicOptions}set options(B){for(let N in B)this._publicOptions[N]=B[N]}input(B,N=!0){this._core.input(B,N)}resize(B,N){this._verifyIntegers(B,N),this._core.resize(B,N)}registerMarker(B=0){return this._checkProposedApi(),this._verifyIntegers(B),this._core.addMarker(B)}addMarker(B){return this.registerMarker(B)}dispose(){super.dispose()}scrollLines(B){this._verifyIntegers(B),this._core.scrollLines(B)}scrollPages(B){this._verifyIntegers(B),this._core.scrollPages(B)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(B){this._verifyIntegers(B),this._core.scrollToLine(B)}clear(){this._core.clear()}write(B,N){this._core.write(B,N)}writeln(B,N){this._core.write(B),this._core.write(`\r
2262
2262
  `,N)}reset(){this._core.reset()}loadAddon(B){this._addonManager.loadAddon(this,B)}_verifyIntegers(...B){for(let N of B)if(N===1/0||isNaN(N)||N%1!=0)throw Error("This API only accepts integers")}}V.Terminal=D})();var X=AG4;for(var K in Y)X[K]=Y[K];Y.__esModule&&Object.defineProperty(X,"__esModule",{value:!0})})()});function lP5(J){return`${J.description}
2263
2263
  \`\`\`json
@@ -3301,11 +3301,12 @@ This tool searches **Amp threads** (conversations with the agent), NOT git commi
3301
3301
  - **Keywords**: Bare words or quoted phrases for text search: \`auth\` or \`"race condition"\`
3302
3302
  - **File filter**: \`file:path\` to find threads that touched a file: \`file:src/auth/login.ts\`
3303
3303
  - **Repo filter**: \`repo:url\` to scope to a repository: \`repo:github.com/owner/repo\` or \`repo:owner/repo\`
3304
+ - **Ref filter**: \`ref:name\` to scope to a git ref: \`ref:main\`
3304
3305
  - **Author filter**: \`author:name\` to find threads by a user: \`author:alice\` or \`author:me\` for your own threads
3305
3306
  - **Date filters**: \`after:date\` and \`before:date\` to filter by date: \`after:2024-01-15\`, \`after:7d\`, \`before:2w\`
3306
3307
  - **Task filter**: \`task:id\` to find threads that worked on a task: \`task:142\`. Use \`task:142+\` to include threads that worked on the task's dependencies, \`task:142^\` to include dependents (tasks that depend on this task), or \`task:142+^\` for both.
3307
3308
  - **Cluster filter**: \`cluster_of:id\` to find threads in the same cluster as a thread: \`cluster_of:T-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\`
3308
- - **Combine filters**: Use implicit AND: \`auth file:src/foo.ts repo:amp after:7d\`
3309
+ - **Combine filters**: Use implicit AND: \`auth file:src/foo.ts repo:amp ref:main after:7d\`
3309
3310
 
3310
3311
  All matching is case-insensitive. File paths use partial matching. Date formats: ISO dates (\`2024-01-15\`), relative days (\`7d\`), or weeks (\`2w\`).
3311
3312
 
@@ -4710,12 +4711,12 @@ ${D}`))}},error:(U)=>{if(!H)H=!0,F(Error(`Failed to spawn brew: ${U.message}`))}
4710
4711
  ${D}`;if(K==="pnpm"&&D.includes("Unable to find the global bin directory"))B+=`
4711
4712
 
4712
4713
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
4713
- npm install -g @sourcegraph/amp`;F(Error(B))}},error:(U)=>{if(!W)W=!0,F(Error(`Failed to spawn ${K}: ${U.message}`))},complete:()=>{if(!W)W=!0,G()}})})}a0();a0();TN();async function HX0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let G=await fetch(X,{signal:K.signal});if(!G.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let F=await G.json(),z=F.version??F["dist-tags"]?.latest;if(!z)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=HC4(J,z),W=q<0,H,U;if(F.time){let D=F.time[J],B=F.time[z],N=Date.now();if(D)H=Math.floor((N-new Date(D).getTime())/3600000);if(B)U=Math.floor((N-new Date(B).getTime())/3600000)}return _.info("NPM version comparison",{currentVersion:J,latestVersion:z,compareResult:q,hasUpdate:W,currentVersionAge:H,latestVersionAge:U}),{hasUpdate:W,latestVersion:z,currentVersion:J,currentVersionAge:H,latestVersionAge:U,source:"npm"}}catch(G){return _.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var QX3="https://static.ampcode.com/cli/cli-version.txt";async function UX0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${QX3}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let X=(await Y.text()).trim();if(!X||!/^\d+\.\d+\.\d+/.test(X))return{hasUpdate:!1,currentVersion:J,source:"bin"};let K=HC4(J,X),V=K<0;return _.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return _.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var YX3=604800000;function WC4(J){if(!J)return null;let Z=typeof J==="number"?J:new Date(J).getTime();if(isNaN(Z))return null;let Q=Date.now()-Z;if(Q>YX3)return{ageMs:Q};return null}function HC4(J,Z){let Q=(V)=>{let[G,F]=V.split("-");return{parts:G?.split(".").map(Number)||[],label:F}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let G=Y.parts[V]||0,F=X.parts[V]||0;if(G<F)return-1;if(G>F)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function _o0(J){try{let Z=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Z)return null;let Q=parseInt(Z[1],10)*1000,Y=Z[2],X=Q!==0?mz(Q):void 0;return{sha:Y,age:X}}catch{return null}}E1();function To0(J,Z,Q={}){let Y=new D4,X=Y.pipe(m6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new cF().scoped("update"),V=Q.startDelayMs??0;if(V>0)await gz(V);let G=X.subscribe({next:(F)=>{K.debug("emit new state",F)}});try{let F=process.env.AMP_TEST_UPDATE_STATUS;if(F){K.debug("using fake update status for testing",{status:F}),await gz(500),Y.next(F);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let z=await Z.get("updates.mode");if(z==="disabled"){K.debug("checking disabled");return}let q=await WX0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:z,packageManager:q,isBinaryDistribution:W});let H=W?await UX0(J):await HX0(J,mj());if(!(H.latestVersion&&H.hasUpdate)){K.debug("no update available");return}let U=()=>{if(H.currentVersionAge!==void 0&&H.latestVersionAge!==void 0){let D=H.currentVersionAge-H.latestVersionAge,B=0.5;if(Math.abs(D)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:H.currentVersionAge,latestVersionAge:H.latestVersionAge,ageDifferenceHours:D}),!0}return!1};if(!z)z=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:z});if(q==="brew"){if(!U())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==Ao0()){if(K.debug("non-standard binary path, showing warning"),!U())Y.next("update-available-unrecognized-path");return}if(z==="warn"){if(!U())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!U())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!U())Y.next("update-available");return}try{await ri(H.latestVersion,q);let D=await yw(H.latestVersion),B={from:H.currentVersion,to:H.latestVersion,...D};if(D.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(D){Y.next("update-error")}}catch(F){K.debug("check failed",{error:F})}finally{await gz(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:X}}TN();import{stderr as lG}from"node:process";function UC4(J){let Z=new tN().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(Y)=>{await Bo0(Y.force||!1,Y.verbose||!1,"0.0.1775909092-g9fb21e"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new tN("update").alias("up").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(Y)=>{await KX3(Y.targetVersion)});J.addCommand(Q)}function XX3(J){let Z=Boolean(J.isTTY),Q=0,Y=!1;function X(){if(!Z||!Y)return;J.write(`
4714
+ npm install -g @sourcegraph/amp`;F(Error(B))}},error:(U)=>{if(!W)W=!0,F(Error(`Failed to spawn ${K}: ${U.message}`))},complete:()=>{if(!W)W=!0,G()}})})}a0();a0();TN();async function HX0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let G=await fetch(X,{signal:K.signal});if(!G.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let F=await G.json(),z=F.version??F["dist-tags"]?.latest;if(!z)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=HC4(J,z),W=q<0,H,U;if(F.time){let D=F.time[J],B=F.time[z],N=Date.now();if(D)H=Math.floor((N-new Date(D).getTime())/3600000);if(B)U=Math.floor((N-new Date(B).getTime())/3600000)}return _.info("NPM version comparison",{currentVersion:J,latestVersion:z,compareResult:q,hasUpdate:W,currentVersionAge:H,latestVersionAge:U}),{hasUpdate:W,latestVersion:z,currentVersion:J,currentVersionAge:H,latestVersionAge:U,source:"npm"}}catch(G){return _.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var QX3="https://static.ampcode.com/cli/cli-version.txt";async function UX0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${QX3}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let X=(await Y.text()).trim();if(!X||!/^\d+\.\d+\.\d+/.test(X))return{hasUpdate:!1,currentVersion:J,source:"bin"};let K=HC4(J,X),V=K<0;return _.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return _.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var YX3=604800000;function WC4(J){if(!J)return null;let Z=typeof J==="number"?J:new Date(J).getTime();if(isNaN(Z))return null;let Q=Date.now()-Z;if(Q>YX3)return{ageMs:Q};return null}function HC4(J,Z){let Q=(V)=>{let[G,F]=V.split("-");return{parts:G?.split(".").map(Number)||[],label:F}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let G=Y.parts[V]||0,F=X.parts[V]||0;if(G<F)return-1;if(G>F)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function _o0(J){try{let Z=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Z)return null;let Q=parseInt(Z[1],10)*1000,Y=Z[2],X=Q!==0?mz(Q):void 0;return{sha:Y,age:X}}catch{return null}}E1();function To0(J,Z,Q={}){let Y=new D4,X=Y.pipe(m6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new cF().scoped("update"),V=Q.startDelayMs??0;if(V>0)await gz(V);let G=X.subscribe({next:(F)=>{K.debug("emit new state",F)}});try{let F=process.env.AMP_TEST_UPDATE_STATUS;if(F){K.debug("using fake update status for testing",{status:F}),await gz(500),Y.next(F);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let z=await Z.get("updates.mode");if(z==="disabled"){K.debug("checking disabled");return}let q=await WX0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:z,packageManager:q,isBinaryDistribution:W});let H=W?await UX0(J):await HX0(J,mj());if(!(H.latestVersion&&H.hasUpdate)){K.debug("no update available");return}let U=()=>{if(H.currentVersionAge!==void 0&&H.latestVersionAge!==void 0){let D=H.currentVersionAge-H.latestVersionAge,B=0.5;if(Math.abs(D)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:H.currentVersionAge,latestVersionAge:H.latestVersionAge,ageDifferenceHours:D}),!0}return!1};if(!z)z=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:z});if(q==="brew"){if(!U())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==Ao0()){if(K.debug("non-standard binary path, showing warning"),!U())Y.next("update-available-unrecognized-path");return}if(z==="warn"){if(!U())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!U())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!U())Y.next("update-available");return}try{await ri(H.latestVersion,q);let D=await yw(H.latestVersion),B={from:H.currentVersion,to:H.latestVersion,...D};if(D.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(D){Y.next("update-error")}}catch(F){K.debug("check failed",{error:F})}finally{await gz(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:X}}TN();import{stderr as lG}from"node:process";function UC4(J){let Z=new tN().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(Y)=>{await Bo0(Y.force||!1,Y.verbose||!1,"0.0.1775969639-g317d38"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new tN("update").alias("up").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(Y)=>{await KX3(Y.targetVersion)});J.addCommand(Q)}function XX3(J){let Z=Boolean(J.isTTY),Q=0,Y=!1;function X(){if(!Z||!Y)return;J.write(`
4714
4715
  `),Y=!1,Q=0}function K(V){if(!Z)return;let G=V.padEnd(Q," ");J.write(`\r${G}`),Y=!0,Q=G.length}return{flushProgressLine:X,renderProgress:K}}async function KX3(J){let Q=process.platform==="win32"&&gj()?{currentExecutablePath:process.execPath}:void 0,{flushProgressLine:Y,renderProgress:X}=XX3(lG);if(process.env.AMP_SKIP_UPDATE_CHECK==="1")lG.write(i0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
4715
4716
 
4716
4717
  `));try{if(!J){lG.write(i0.blue(`Checking for updates...
4717
- `));let{hasUpdate:G,latestVersion:F}=gj()?await UX0("0.0.1775909092-g9fb21e"):await HX0("0.0.1775909092-g9fb21e",mj());if(!G){let z=_o0("0.0.1775909092-g9fb21e"),q=z?.age?`released ${z.age} ago`:`built ${mz(new Date("2026-04-11T12:08:43.560Z"))} ago`;lG.write(i0.green(`✓ Amp is already up to date on version ${"0.0.1775909092-g9fb21e"} (${q})
4718
- `));let W=await yw("0.0.1775909092-g9fb21e",Q);if(W.warning)lG.write(`
4718
+ `));let{hasUpdate:G,latestVersion:F}=gj()?await UX0("0.0.1775969639-g317d38"):await HX0("0.0.1775969639-g317d38",mj());if(!G){let z=_o0("0.0.1775969639-g317d38"),q=z?.age?`released ${z.age} ago`:`built ${mz(new Date("2026-04-12T04:57:51.445Z"))} ago`;lG.write(i0.green(`✓ Amp is already up to date on version ${"0.0.1775969639-g317d38"} (${q})
4719
+ `));let W=await yw("0.0.1775969639-g317d38",Q);if(W.warning)lG.write(`
4719
4720
  `+i0.yellow(W.warning)+`
4720
4721
  `);process.exit(0)}if(!F)lG.write(i0.yellow("[WARN] could not find latest version")),process.exit(0);J=F}lG.write(i0.blue(`Updating to version ${J}...
4721
4722
  `)),await ri(J,void 0,(G)=>{Y(),lG.write(i0.dim(`Running: ${G}
@@ -5921,7 +5922,7 @@ ${X}`,Z);this.line=Q,this.column=Y,this.codeblock=X}}/*!
5921
5922
  `),K=[];for(let V=0;V<X.length;V++){let z=X[V].replace(/\b(SELECT|FROM|WHERE|GROUP BY|ORDER BY|HAVING|LIMIT|JOIN|LEFT JOIN|RIGHT JOIN|INNER JOIN|ON|AND|OR|AS|IN|NOT|NULL|IS|BETWEEN|LIKE|EXISTS|UNION|DISTINCT|COUNT|SUM|AVG|MIN|MAX|DATE|TIMESTAMP_TRUNC|TIMESTAMP_SUB|CURRENT_TIMESTAMP|INTERVAL|CASE|WHEN|THEN|ELSE|END|WITH|INSERT|UPDATE|DELETE|SET|VALUES|INTO|CREATE|ALTER|DROP|TRUE|FALSE|ASC|DESC)\b/gi,"\x00$1\x01").split(/(\x00[^\x01]+\x01)/);for(let q of z)if(q.startsWith("\x00")&&q.endsWith("\x01"))K.push(new C(q.slice(1,-1),new g({color:Y.app.keybind,bold:!0})));else K.push(new C(q,new g({color:Q.colorScheme.foreground})));if(V<X.length-1)K.push(new C(`
5922
5923
  `))}return new c0({decoration:{color:Q.colorScheme.background,border:Y4.all(new Z4(Y.app.keybind,1,"rounded"))},child:new l0({padding:C0.symmetric(0,1),child:new J0({text:new C(void 0,void 0,K)})})})}}class P11 extends N2{chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=NF0}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new R11({chartData:this.chartData,highlightIndex:this.highlightIndex,showAxes:this.showAxes,colors:this.colors})}updateRenderObject(J){let Z=J;Z.chartData=this.chartData,Z.highlightIndex=this.highlightIndex,Z.showAxes=this.showAxes,Z.colors=this.colors,Z.markNeedsLayout()}}function Im4(J,Z,Q,Y,X,K,V){if(K<=0)return null;switch(J){case"horizontal-bar":{let G=Q;return G>=0&&G<K?G:null}case"bar":case"stacked-bar":{let G=V?P9:0,F=Y-G;if(F<=0)return null;let z=Z-G;if(z<0||z>=F)return null;let q=Math.max(1,Math.floor(F/K)),W=Math.floor(z/q);return W>=0&&W<K?W:null}case"line":case"sparkline":case"stacked-area":{let G=V?P9:0,F=Y-G;if(F<=0)return null;let z=Math.max(0,Math.min(F-1,Z-G));if(K===1)return 0;let q=F/(K-1),W=Math.round(z/q);return Math.max(0,Math.min(K-1,W))}default:return null}}function j_3(J,Z,Q,Y,X,K,V,G){if(X<=0||Z<0||Z>=X)return null;let F=2;switch(J){case"horizontal-bar":return{x:Math.floor(Q/2),y:Z};case"bar":case"stacked-bar":{let z=K?P9:0,q=Q-z,W=Y-(K?F:0);if(q<=0||W<=0)return null;let H=Math.max(1,Math.floor(q/X)),U=z+Z*H+Math.floor(H/2),D=G>0?V/G:0,B=Math.round((1-D)*(W-1));return{x:U,y:B}}case"line":case"sparkline":case"stacked-area":{let z=K?P9:0,q=Q-z,W=Y-(K?F:0);if(q<=0||W<=0)return null;let H=X>1?z+Math.round(Z/(X-1)*(q-1)):z+Math.floor(q/2),U=G>0?V/G:0,D=Math.round((1-U)*(W-1));return{x:H,y:D}}default:return null}}function R_3(J){let Z=0;for(let Q of J)for(let Y of Q.points)if(Y.value>Z)Z=Y.value;return Z||1}function I_3(J,Z,Q,Y,X){if(Q.length<=1){let G=Y(J.value),F=J.meta?` (${J.meta})`:"";return J.label.length+2+G.length+F.length}let K=J.label.length,V=0;for(let G of Q){let F=G.points[Z];if(!F)continue;V+=F.value;let z=2+G.name.length+2+Y(F.value).length;K=Math.max(K,z)}if(X){let G=9+Y(V).length;K=Math.max(K,G)}return K}function P_3(J,Z,Q,Y,X,K,V){let G;try{let D=b1.of(J),B=f0.of(J);G={foreground:D.colorScheme.foreground,background:D.colorScheme.background,border:B.app.keybind}}catch{G={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let F=new g({color:G.foreground,bold:!0}),z=new g({color:G.foreground}),q=new g({color:G.foreground,dim:!0}),W=[],H=new g({color:G.foreground,underline:!0}),U=(D,B)=>new C(B,H,void 0,OX0(D),()=>{i3(J,D)});if(Y.length<=1){if(W.push(new C(`${Z.label}: `,F)),Z.link)W.push(U(Z.link,K(Z.value)));else W.push(new C(K(Z.value),z));if(Z.meta)W.push(new C(` (${Z.meta})`,q))}else{let D=V==="stacked-bar"||V==="stacked-area";W.push(new C(`${Z.label}
5923
5924
  `,F));let B=0;for(let N=0;N<Y.length;N++){let w=Y[N],L=w.points[Q];if(!L)continue;B+=L.value;let O=w.color??X[N%X.length]??G.foreground;if(W.push(new C("● ",new g({color:O}))),W.push(new C(`${w.name}: `,q)),L.link)W.push(U(L.link,K(L.value)));else W.push(new C(K(L.value),z));if(N<Y.length-1||D)W.push(new C(`
5924
- `))}if(D)W.push(new C(" ",q)),W.push(new C("Total: ",q)),W.push(new C(K(B),z))}return new c0({decoration:{color:G.background,border:Y4.all(new Z4(G.border,1,"rounded"))},child:new J0({text:new C(void 0,void 0,W)})})}rD();a0();B9();ME();t7();x3();y2();kd();fX();sZ();VY();JQ();xA();m4();rg();lP();E1();a0();sZ();class C11{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Z){this.enabled=J;this.configService=Z;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Z,Q])=>({feature:"cli.command",action:Z,source:{client:"cli",clientVersion:"0.0.1775909092-g9fb21e"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await p40(Z,this.configService)}catch(Z){_.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class IL extends p0{props;constructor(J){super();this.props=J}createState(){return new Pm4}}class Pm4 extends m0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Z=(Q)=>{this.setState(()=>{this._state=Q(this._state)})};return this.widget.props.builder(J,Z,this._state)}}class Cm4 extends m0{controller=new i7;focusNode=new O6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,G=Y4.all(new Z4(Q.foreground,1,"solid")),F=new ZX({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(U)=>{let D=U.trim();if(X&&D.length===0)return;this.widget.props.onSubmit(D)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),z=new D1({children:[new c0({decoration:{color:Q.background},child:new J0({text:new C(">",new g({color:Q.foreground}))})}),new i1({child:F})]}),q=new c0({padding:C0.symmetric(1,0),child:new J0({text:new C("",void 0,[new C("Command: ",new g({color:Q.foreground})),new C(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=[];if(V)W.push(new C("Enter",new g({color:Y.keybind}))),W.push(new C(" to submit, ",new g({color:Q.foreground,dim:!0})));W.push(new C("Esc",new g({color:Y.keybind}))),W.push(new C(" to cancel",new g({color:Q.foreground,dim:!0})));let H=new c0({padding:C0.symmetric(1,0),child:new J0({text:new C("",void 0,W)})});return new c0({decoration:{border:G,color:Q.background},padding:C0.all(1),child:new g0({children:[q,new I0({height:1}),z,new k5,H]})})}}class sa extends p0{props;constructor(J){super();this.props=J}createState(){return new Cm4}}JQ();class _m4 extends m0{controller=new i7;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new O6({debugLabel:"CommandMultilinePrompt",onKey:(J)=>{if(J.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(J)=>{if(this.imageAttachments.length>=hV)return!1;let Z=await VL(J);if(typeof Z==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Z],this.imagePaths=[...this.imagePaths,J]}),!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(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,K=O4.of(J).size.height,V=Math.max(Math.floor(K*0.5),10),G=new mU({controller:this.controller,triggers:[new rK],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(U)=>{this.widget.props.onSubmit(U.trim(),this.imageAttachments)},theme:Q,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:X6.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),F=new Y6({focusNode:this.focusNode,child:G}),z=new c0({constraints:new M1({maxHeight:V}),padding:C0.symmetric(1,0),child:F}),q=new c0({padding:C0.symmetric(1,0),child:new J0({text:new C("",void 0,[new C("Command: ",new g({color:Q.foreground})),new C(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=new c0({padding:C0.symmetric(1,0),child:new J0({text:this.isConfirmingClearInput?new C("",void 0,[new C("Esc",new g({color:Y.keybind})),new C(" again to clear input",new g({color:Q.foreground,dim:!0}))]):new C("",void 0,[new C("Press ",new g({color:Q.foreground,dim:!0})),new C("Enter",new g({color:Y.keybind})),new C(" to submit, ",new g({color:Q.foreground,dim:!0})),new C("Esc",new g({color:Y.keybind})),new C(" to clear",new g({color:Q.foreground,dim:!0}))])})}),H=[q,new I0({height:1}),new i1({child:z}),new I0({height:1}),W];return new c0({decoration:{border:Y4.all(new Z4(Q.foreground,1,"solid")),color:Q.background},padding:C0.all(1),child:new g0({children:H})})}}class _11 extends p0{props;constructor(J){super();this.props=J}createState(){return new _m4}}function Tm4(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/60000),X=Math.floor(Q/3600000),K=Math.floor(Q/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(K<7)return`${K}d ago`;return J.toLocaleDateString()}class T11 extends m1{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((X,K)=>K.pubDate.getTime()-X.pubDate.getTime()),Q=Math.max(0,...Z.map((X)=>Tm4(X.pubDate).length));return new W9({items:Z,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,K,V,G)=>{let F=f0.of(G),{colors:z}=F,q=F.app,W=K?q.selectionBackground:void 0,H=K?q.selectionForeground:z.foreground,U=z.mutedForeground,D=(B,N)=>new I0({width:N,child:D1.end([new J0({text:new C(B,new g({color:U}))})])});return new c0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new D1({children:[new i1({child:new J0({text:new C(X.title,new g({color:H})),overflow:"ellipsis",maxLines:1})}),new I0({width:2}),D(Tm4(X.pubDate),Q)]})})}})}}QB();class S11 extends p0{createState(){return new Sm4}}class Sm4 extends m0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=f0.of(J).colors;return new J0({text:new C("●",new g({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function C_3(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let V of J)Z.set(V.id,V);for(let V of J){let G=V.relationships.find((F)=>F.role==="child"&&Z.has(F.threadID)&&(F.type==="fork"||F.type==="handoff"));if(G){Y.set(V.id,G.type);let F=G.threadID,z=Q.get(F)||[];z.push(V),Q.set(F,z)}else X.push(V)}return KG0.flatten(X,(V)=>Q.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Y.get(V.item.id)}))}function k11(J,Z,Q){return new J0({text:new C(`${J}${Z}`,new g({color:Q})),maxLines:1})}function __3(J,Z,Q,Y){return[k11("+",J,Y.success),k5.horizontal(1),k11("~",Z,Y.warning),k5.horizontal(1),k11("-",Q,Y.destructive)]}function T_3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class LF0 extends p0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new km4}}class km4 extends m0{spinner=new M5;spinnerInterval=null;isSwitchingThread=!1;get isBusy(){return this.isSwitchingThread||this.widget.props.isLoading===!0}updateSpinnerAnimation(){if(this.isBusy){if(!this.spinnerInterval)this.spinnerInterval=setInterval(()=>{this.spinner.step(),this.setState(()=>{})},100);return}if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null}setSwitchingThread(J){if(this.isSwitchingThread===J)return;this.setState(()=>{this.isSwitchingThread=J}),this.updateSpinnerAnimation()}initState(){super.initState(),this.updateSpinnerAnimation()}didUpdateWidget(J){this.updateSpinnerAnimation()}dispose(){if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null;super.dispose()}build(J){let{props:Z}=this.widget,Q=this.isBusy,Y=this.isSwitchingThread?"Switching thread...":"Loading threads...",X=`${this.spinner.toBraille()} ${Y}`,K=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((L)=>!L.workspaceURI||L.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)K=K.filter((L)=>L.id!==Z.currentThreadID);let V=Z.recentThreadIDs||[],G=new Set(V),F=Z.currentThreadID,z=[...K].sort((L,O)=>{if(F){if(L.id===F)return-1;if(O.id===F)return 1}let E=V.indexOf(L.id),M=V.indexOf(O.id);if(E!==-1&&M!==-1)return E-M;if(E!==-1)return-1;if(M!==-1)return 1;return 0}),q=C_3(z),W=Math.max(0,...q.map((L)=>L.description.timeAgo.length)),H=f0.of(J),U=new l0({padding:C0.symmetric(0,1),child:new X4({child:new J0({text:new C("",new g({color:H.colors.foreground,dim:!0}),[new C("Alt+W/Ctrl+T",new g({color:H.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new g({color:H.colors.foreground,dim:!0}))])})})}),D="",B=null,N=(L)=>{if(L!==D)D=L,B=S9(L);return B};return new W9({items:q,getLabel:(L)=>`${L.title} ${L.id}`,filterItem:(L,O)=>{let E=N(O);if(E)return L.id.toLowerCase()===E.toLowerCase();return!0},normalizeQuery:(L)=>N(L)?"":L,onAccept:async(L,O)=>{if(!Z.onSelect||this.isSwitchingThread)return;let E=Z.onSelect(L.id,O);if(!T_3(E))return;this.setSwitchingThread(!0);try{await E}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(L)=>{if(Z.previewController){if(L)Z.previewController.select(L.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:Z.hasError?"Failed to load threads":"No threads match your filter",maxRenderItems:200,footer:Q||Z.hasError?void 0:U,renderItem:(L,O,E,M)=>{let A=f0.of(M),{app:j,colors:I}=A,T=O?j.selectionBackground:void 0,P=O?j.selectionForeground:I.foreground,h=I.mutedForeground,p=(s,W0)=>new I0({width:W0,child:D1.end([new J0({text:new C(s,new g({color:h}))})])}),x=Z.threadViewStates[L.id],k=[],f=L.relationshipType==="handoff",d=new ua({connectorColor:I.mutedForeground});if(L.depth>0){let s=[],W0=L.ancestorsAreLast.slice(1);for(let w0 of W0)s.push(new C(d.getAncestorPrefix(w0),new g({color:d.connectorColor,dim:d.connectorDim})));let r=L.isLast?d.elbow:d.tee,F0=d.getConnectorText(r);s.push(new C(F0,new g({color:d.connectorColor,dim:d.connectorDim}))),k.push(new J0({text:new C("",void 0,s)}))}let m=[],b=F===L.id?new C("(current) ",new g({color:I.success})):G.has(L.id)?new C("(visited) ",new g({color:I.foreground,dim:!0})):null;if(b)m.push(new J0({text:b}));if(ZA(x))m.push(new S11),m.push(new I0({width:1}));let n=L.title;if(L.relationshipType==="fork"){let s=n.match(/^Forked\((\d+)\): /);if(s)n=n.slice(s[0].length);else while(n.startsWith("Forked: "))n=n.slice(8);m.push(new J0({text:new C("[fork] ",new g({color:I.primary}))}))}else if(f)m.push(new J0({text:new C("[handoff] ",new g({color:I.accent}))}));if(m.push(new i1({child:new J0({text:new C(n,new g({color:P})),overflow:"ellipsis",maxLines:1})})),m.push(new I0({width:2})),L.diffStats&&(L.diffStats.added>0||L.diffStats.changed>0||L.diffStats.deleted>0)){let s=O?{success:h,warning:h,destructive:h}:I;m.push(...__3(L.diffStats.added,L.diffStats.changed,L.diffStats.deleted,s)),m.push(new I0({width:2}))}return m.push(p(L.description.timeAgo,W)),new c0({decoration:T?{color:T}:void 0,padding:C0.symmetric(2,0),child:new D1({children:[...k,...m]})})}})}}a0();class eK{message;constructor(J){this.message=J}}class O7{widget;title;type;footerStyle;dimensions;constructor(J,Z="Info",Q="info",Y="default",X){this.widget=J;this.title=Z;this.type=Q;this.footerStyle=Y;this.dimensions=X}}function OF0(J){if(J instanceof eK)return{title:"Info",description:J.message,type:"info"};return _.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}a0();xX();TN();fX();sZ();m4();U4();lP();var y11=H4(DH(),1);import{execSync as yR}from"node:child_process";import{writeFile as by}from"node:fs/promises";import S_3 from"node:os";import tq from"node:path";var vm4="c446b2e9b16cdc06df2ec285894d6421",k_3="5ea19563777f4ade8707fc56f7e7a388",v_3="amp-thread-worker",ym4=[{id:"cli-open",label:"cli: open in pager"},{id:"cloudflare-logs",label:"cloudflare: open logs"},{id:"cloudflare-data-studio",label:"cloudflare: open data studio"}];function y_3(J){return!!J&&typeof J==="object"&&"usesDtw"in J}function CL(J){if(!J||!y_3(J.meta))return!1;return J.meta.usesDtw===!0}function x11(J){let Z=new URL(`https://dash.cloudflare.com/${vm4}/workers/durable-objects/view/${k_3}/studio`);return Z.searchParams.set("name",J),Z.searchParams.set("jurisdiction","none"),Z.toString()}function f11(J){let Z=new URL(`https://dash.cloudflare.com/${vm4}/workers/services/view/${v_3}/production/observability/events`);return Z.searchParams.set("filterCombination",'"and"'),Z.searchParams.set("calculations",'[{"operator":"count"}]'),Z.searchParams.set("orderBy",'{"value":"count","limit":10,"order":"desc"}'),Z.searchParams.set("timeframe","24h"),Z.searchParams.set("conditions","{}"),Z.searchParams.set("conditionCombination",'"and"'),Z.searchParams.set("alertTiming",'{"interval":300,"window":900,"timeBeforeFiring":600,"timeBeforeResolved":600}'),Z.searchParams.set("filters",JSON.stringify([{key:"threadId",operation:"eq",value:J,type:"string"}])),Z.toString()}function x_3(J,Z){if(hW(J))return`amp dtw-curl ${Z}`;return`AMP_URL=${JSON.stringify(J)} pnpm -C cli cli -- dtw-curl ${Z}`}function u11(J,Z){let Q=x_3(Z,J);return[{label:"dtw: get full transcript",command:`${Q} get-transcript`},{label:"dtw: send message via curl",command:`${Q} add-message "<your message here>"`},{label:"dtw: dump full sqlite DB to disk",command:`${Q} dump`},{label:"dtw: fetch Cloudflare logs",command:`./scripts/fetch-cloudflare-logs.ts ${J}`}]}function ta(J,Z,Q){let Y=`select(.pid == ${Z})`,X=ea(Q);return`${J==="snapshot"?`tail -n 10000 ${X}`:`tail -f ${X}`} | jq -C '${Y}'`}function ea(J){return J.path??A8(J.uri)}function xm4(J,Z,Q){let Y=ta("snapshot",J,Z);return Q?`${Y} | ${Q}`:Y}function fm4(J,Z){return u11(J,Z).map(({label:Q,command:Y})=>`# ${Q}
5925
+ `))}if(D)W.push(new C(" ",q)),W.push(new C("Total: ",q)),W.push(new C(K(B),z))}return new c0({decoration:{color:G.background,border:Y4.all(new Z4(G.border,1,"rounded"))},child:new J0({text:new C(void 0,void 0,W)})})}rD();a0();B9();ME();t7();x3();y2();kd();fX();sZ();VY();JQ();xA();m4();rg();lP();E1();a0();sZ();class C11{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Z){this.enabled=J;this.configService=Z;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Z,Q])=>({feature:"cli.command",action:Z,source:{client:"cli",clientVersion:"0.0.1775969639-g317d38"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await p40(Z,this.configService)}catch(Z){_.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class IL extends p0{props;constructor(J){super();this.props=J}createState(){return new Pm4}}class Pm4 extends m0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Z=(Q)=>{this.setState(()=>{this._state=Q(this._state)})};return this.widget.props.builder(J,Z,this._state)}}class Cm4 extends m0{controller=new i7;focusNode=new O6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,G=Y4.all(new Z4(Q.foreground,1,"solid")),F=new ZX({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(U)=>{let D=U.trim();if(X&&D.length===0)return;this.widget.props.onSubmit(D)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),z=new D1({children:[new c0({decoration:{color:Q.background},child:new J0({text:new C(">",new g({color:Q.foreground}))})}),new i1({child:F})]}),q=new c0({padding:C0.symmetric(1,0),child:new J0({text:new C("",void 0,[new C("Command: ",new g({color:Q.foreground})),new C(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=[];if(V)W.push(new C("Enter",new g({color:Y.keybind}))),W.push(new C(" to submit, ",new g({color:Q.foreground,dim:!0})));W.push(new C("Esc",new g({color:Y.keybind}))),W.push(new C(" to cancel",new g({color:Q.foreground,dim:!0})));let H=new c0({padding:C0.symmetric(1,0),child:new J0({text:new C("",void 0,W)})});return new c0({decoration:{border:G,color:Q.background},padding:C0.all(1),child:new g0({children:[q,new I0({height:1}),z,new k5,H]})})}}class sa extends p0{props;constructor(J){super();this.props=J}createState(){return new Cm4}}JQ();class _m4 extends m0{controller=new i7;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new O6({debugLabel:"CommandMultilinePrompt",onKey:(J)=>{if(J.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(J)=>{if(this.imageAttachments.length>=hV)return!1;let Z=await VL(J);if(typeof Z==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Z],this.imagePaths=[...this.imagePaths,J]}),!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(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,K=O4.of(J).size.height,V=Math.max(Math.floor(K*0.5),10),G=new mU({controller:this.controller,triggers:[new rK],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(U)=>{this.widget.props.onSubmit(U.trim(),this.imageAttachments)},theme:Q,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:X6.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),F=new Y6({focusNode:this.focusNode,child:G}),z=new c0({constraints:new M1({maxHeight:V}),padding:C0.symmetric(1,0),child:F}),q=new c0({padding:C0.symmetric(1,0),child:new J0({text:new C("",void 0,[new C("Command: ",new g({color:Q.foreground})),new C(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=new c0({padding:C0.symmetric(1,0),child:new J0({text:this.isConfirmingClearInput?new C("",void 0,[new C("Esc",new g({color:Y.keybind})),new C(" again to clear input",new g({color:Q.foreground,dim:!0}))]):new C("",void 0,[new C("Press ",new g({color:Q.foreground,dim:!0})),new C("Enter",new g({color:Y.keybind})),new C(" to submit, ",new g({color:Q.foreground,dim:!0})),new C("Esc",new g({color:Y.keybind})),new C(" to clear",new g({color:Q.foreground,dim:!0}))])})}),H=[q,new I0({height:1}),new i1({child:z}),new I0({height:1}),W];return new c0({decoration:{border:Y4.all(new Z4(Q.foreground,1,"solid")),color:Q.background},padding:C0.all(1),child:new g0({children:H})})}}class _11 extends p0{props;constructor(J){super();this.props=J}createState(){return new _m4}}function Tm4(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/60000),X=Math.floor(Q/3600000),K=Math.floor(Q/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(K<7)return`${K}d ago`;return J.toLocaleDateString()}class T11 extends m1{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((X,K)=>K.pubDate.getTime()-X.pubDate.getTime()),Q=Math.max(0,...Z.map((X)=>Tm4(X.pubDate).length));return new W9({items:Z,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,K,V,G)=>{let F=f0.of(G),{colors:z}=F,q=F.app,W=K?q.selectionBackground:void 0,H=K?q.selectionForeground:z.foreground,U=z.mutedForeground,D=(B,N)=>new I0({width:N,child:D1.end([new J0({text:new C(B,new g({color:U}))})])});return new c0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new D1({children:[new i1({child:new J0({text:new C(X.title,new g({color:H})),overflow:"ellipsis",maxLines:1})}),new I0({width:2}),D(Tm4(X.pubDate),Q)]})})}})}}QB();class S11 extends p0{createState(){return new Sm4}}class Sm4 extends m0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=f0.of(J).colors;return new J0({text:new C("●",new g({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function C_3(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let V of J)Z.set(V.id,V);for(let V of J){let G=V.relationships.find((F)=>F.role==="child"&&Z.has(F.threadID)&&(F.type==="fork"||F.type==="handoff"));if(G){Y.set(V.id,G.type);let F=G.threadID,z=Q.get(F)||[];z.push(V),Q.set(F,z)}else X.push(V)}return KG0.flatten(X,(V)=>Q.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Y.get(V.item.id)}))}function k11(J,Z,Q){return new J0({text:new C(`${J}${Z}`,new g({color:Q})),maxLines:1})}function __3(J,Z,Q,Y){return[k11("+",J,Y.success),k5.horizontal(1),k11("~",Z,Y.warning),k5.horizontal(1),k11("-",Q,Y.destructive)]}function T_3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class LF0 extends p0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new km4}}class km4 extends m0{spinner=new M5;spinnerInterval=null;isSwitchingThread=!1;get isBusy(){return this.isSwitchingThread||this.widget.props.isLoading===!0}updateSpinnerAnimation(){if(this.isBusy){if(!this.spinnerInterval)this.spinnerInterval=setInterval(()=>{this.spinner.step(),this.setState(()=>{})},100);return}if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null}setSwitchingThread(J){if(this.isSwitchingThread===J)return;this.setState(()=>{this.isSwitchingThread=J}),this.updateSpinnerAnimation()}initState(){super.initState(),this.updateSpinnerAnimation()}didUpdateWidget(J){this.updateSpinnerAnimation()}dispose(){if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null;super.dispose()}build(J){let{props:Z}=this.widget,Q=this.isBusy,Y=this.isSwitchingThread?"Switching thread...":"Loading threads...",X=`${this.spinner.toBraille()} ${Y}`,K=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((L)=>!L.workspaceURI||L.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)K=K.filter((L)=>L.id!==Z.currentThreadID);let V=Z.recentThreadIDs||[],G=new Set(V),F=Z.currentThreadID,z=[...K].sort((L,O)=>{if(F){if(L.id===F)return-1;if(O.id===F)return 1}let E=V.indexOf(L.id),M=V.indexOf(O.id);if(E!==-1&&M!==-1)return E-M;if(E!==-1)return-1;if(M!==-1)return 1;return 0}),q=C_3(z),W=Math.max(0,...q.map((L)=>L.description.timeAgo.length)),H=f0.of(J),U=new l0({padding:C0.symmetric(0,1),child:new X4({child:new J0({text:new C("",new g({color:H.colors.foreground,dim:!0}),[new C("Alt+W/Ctrl+T",new g({color:H.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new g({color:H.colors.foreground,dim:!0}))])})})}),D="",B=null,N=(L)=>{if(L!==D)D=L,B=S9(L);return B};return new W9({items:q,getLabel:(L)=>`${L.title} ${L.id}`,filterItem:(L,O)=>{let E=N(O);if(E)return L.id.toLowerCase()===E.toLowerCase();return!0},normalizeQuery:(L)=>N(L)?"":L,onAccept:async(L,O)=>{if(!Z.onSelect||this.isSwitchingThread)return;let E=Z.onSelect(L.id,O);if(!T_3(E))return;this.setSwitchingThread(!0);try{await E}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(L)=>{if(Z.previewController){if(L)Z.previewController.select(L.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:Z.hasError?"Failed to load threads":"No threads match your filter",maxRenderItems:200,footer:Q||Z.hasError?void 0:U,renderItem:(L,O,E,M)=>{let A=f0.of(M),{app:j,colors:I}=A,T=O?j.selectionBackground:void 0,P=O?j.selectionForeground:I.foreground,h=I.mutedForeground,p=(s,W0)=>new I0({width:W0,child:D1.end([new J0({text:new C(s,new g({color:h}))})])}),x=Z.threadViewStates[L.id],k=[],f=L.relationshipType==="handoff",d=new ua({connectorColor:I.mutedForeground});if(L.depth>0){let s=[],W0=L.ancestorsAreLast.slice(1);for(let w0 of W0)s.push(new C(d.getAncestorPrefix(w0),new g({color:d.connectorColor,dim:d.connectorDim})));let r=L.isLast?d.elbow:d.tee,F0=d.getConnectorText(r);s.push(new C(F0,new g({color:d.connectorColor,dim:d.connectorDim}))),k.push(new J0({text:new C("",void 0,s)}))}let m=[],b=F===L.id?new C("(current) ",new g({color:I.success})):G.has(L.id)?new C("(visited) ",new g({color:I.foreground,dim:!0})):null;if(b)m.push(new J0({text:b}));if(ZA(x))m.push(new S11),m.push(new I0({width:1}));let n=L.title;if(L.relationshipType==="fork"){let s=n.match(/^Forked\((\d+)\): /);if(s)n=n.slice(s[0].length);else while(n.startsWith("Forked: "))n=n.slice(8);m.push(new J0({text:new C("[fork] ",new g({color:I.primary}))}))}else if(f)m.push(new J0({text:new C("[handoff] ",new g({color:I.accent}))}));if(m.push(new i1({child:new J0({text:new C(n,new g({color:P})),overflow:"ellipsis",maxLines:1})})),m.push(new I0({width:2})),L.diffStats&&(L.diffStats.added>0||L.diffStats.changed>0||L.diffStats.deleted>0)){let s=O?{success:h,warning:h,destructive:h}:I;m.push(...__3(L.diffStats.added,L.diffStats.changed,L.diffStats.deleted,s)),m.push(new I0({width:2}))}return m.push(p(L.description.timeAgo,W)),new c0({decoration:T?{color:T}:void 0,padding:C0.symmetric(2,0),child:new D1({children:[...k,...m]})})}})}}a0();class eK{message;constructor(J){this.message=J}}class O7{widget;title;type;footerStyle;dimensions;constructor(J,Z="Info",Q="info",Y="default",X){this.widget=J;this.title=Z;this.type=Q;this.footerStyle=Y;this.dimensions=X}}function OF0(J){if(J instanceof eK)return{title:"Info",description:J.message,type:"info"};return _.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}a0();xX();TN();fX();sZ();m4();U4();lP();var y11=H4(DH(),1);import{execSync as yR}from"node:child_process";import{writeFile as by}from"node:fs/promises";import S_3 from"node:os";import tq from"node:path";var vm4="c446b2e9b16cdc06df2ec285894d6421",k_3="5ea19563777f4ade8707fc56f7e7a388",v_3="amp-thread-worker",ym4=[{id:"cli-open",label:"cli: open in pager"},{id:"cloudflare-logs",label:"cloudflare: open logs"},{id:"cloudflare-data-studio",label:"cloudflare: open data studio"}];function y_3(J){return!!J&&typeof J==="object"&&"usesDtw"in J}function CL(J){if(!J||!y_3(J.meta))return!1;return J.meta.usesDtw===!0}function x11(J){let Z=new URL(`https://dash.cloudflare.com/${vm4}/workers/durable-objects/view/${k_3}/studio`);return Z.searchParams.set("name",J),Z.searchParams.set("jurisdiction","none"),Z.toString()}function f11(J){let Z=new URL(`https://dash.cloudflare.com/${vm4}/workers/services/view/${v_3}/production/observability/events`);return Z.searchParams.set("filterCombination",'"and"'),Z.searchParams.set("calculations",'[{"operator":"count"}]'),Z.searchParams.set("orderBy",'{"value":"count","limit":10,"order":"desc"}'),Z.searchParams.set("timeframe","24h"),Z.searchParams.set("conditions","{}"),Z.searchParams.set("conditionCombination",'"and"'),Z.searchParams.set("alertTiming",'{"interval":300,"window":900,"timeBeforeFiring":600,"timeBeforeResolved":600}'),Z.searchParams.set("filters",JSON.stringify([{key:"threadId",operation:"eq",value:J,type:"string"}])),Z.toString()}function x_3(J,Z){if(hW(J))return`amp dtw-curl ${Z}`;return`AMP_URL=${JSON.stringify(J)} pnpm -C cli cli -- dtw-curl ${Z}`}function u11(J,Z){let Q=x_3(Z,J);return[{label:"dtw: get full transcript",command:`${Q} get-transcript`},{label:"dtw: send message via curl",command:`${Q} add-message "<your message here>"`},{label:"dtw: dump full sqlite DB to disk",command:`${Q} dump`},{label:"dtw: fetch Cloudflare logs",command:`./scripts/fetch-cloudflare-logs.ts ${J}`}]}function ta(J,Z,Q){let Y=`select(.pid == ${Z})`,X=ea(Q);return`${J==="snapshot"?`tail -n 10000 ${X}`:`tail -f ${X}`} | jq -C '${Y}'`}function ea(J){return J.path??A8(J.uri)}function xm4(J,Z,Q){let Y=ta("snapshot",J,Z);return Q?`${Y} | ${Q}`:Y}function fm4(J,Z){return u11(J,Z).map(({label:Q,command:Y})=>`# ${Q}
5925
5926
  ${Y}`).join(`
5926
5927
 
5927
5928
  `)}function v11(J){if(J===void 0||!Number.isFinite(J)||J<=0)return"n/a";return`${mz(J)} ago (\`${new Date(J).toISOString()}\`)`}function f_3(J){if(!J)return"n/a";let Z=Date.parse(J);if(!Number.isFinite(Z))return`\`${J}\``;return v11(Z)}function PL(J){if(J===void 0||J===null)return"n/a";return`\`${String(J)}\``}function EF0(J,Z="#"){let{thread:Q,threadViewState:Y}=J,X=(V)=>`${Z} ${V}`,K=[X("Thread"),`- ID: \`${Q.id}\``,`- Title: ${f10(Q)}`,`- URL: \`${JH(new URL(J.ampURL),Q.id).toString()}\``,`- Created: ${v11(Q.created)}`,`- Agent mode: ${PL(Q.agentMode)}`,`- Effective mode: \`${J.effectiveAgentMode}\``,`- DTW backed: ${CL(Q)?"yes":"no"}`,`- Executor type: ${PL(Q.meta?.executorType)}`,`- Messages: \`${Q.messages.length}\` total / \`${q8(Q)}\` human / \`${Q.queuedMessages?.length??0}\` queued`];if(Q.meta?.status!==void 0)K.push(`- Merge status: ${PL(Q.meta.status??"null")}`);if(Q.meta?.lastKnownAgentState)K.push(`- Last known agent state: \`${Q.meta.lastKnownAgentState.state}\` at ${f_3(Q.meta.lastKnownAgentState.updatedAt)}`);if(J.initialTreePath)K.push(`- Initial tree: \`${J.initialTreePath}\``);if(J.currentWorkspacePath)K.push(`- Current workspace: \`${J.currentWorkspacePath}\``);if(K.push("",X("Runtime"),`- Amp URL: \`${hW(J.ampURL)?Z7:J.ampURL}\``,`- Thread pool mode: \`${J.threadPoolIsDTW?"dtw":"worker"}\``,`- Connection state: ${PL(J.transportState)}`,`- Connection role: ${PL(J.transportRole)}`,`- Processing: ${J.isProcessing?"yes":"no"}`,`- PID: ${PL(J.pid)}`,`- Client ID: ${PL(J.clientId)}`),J.logFile)K.push(`- Log file: \`${ea(J.logFile)}\``);if(!Y)return K.push("",X("View State"),"- No live thread view state available."),K.join(`
@@ -6148,7 +6149,7 @@ ${t.content||""}`:t.content||"",R0=[],y0=t.baseDir.startsWith("file://")?Zz0(t.b
6148
6149
  `),process.exit(1)}process.stdout.write(await wy3(F.result.displayText)+`
6149
6150
  `),process.exit(0)})}TN();import{stdout as Ly3}from"node:process";function Oy3({version:J,buildTimestamp:Z,buildType:Q}){let Y=Q==="dev"?"dev":"released",X=Z?new Date(Z):null,K=X&&!Number.isNaN(X.getTime())?`, ${mz(X)} ago`:"";return`${J} (${Y}${Z?` ${Z}`:""}${K})`}function ql4(J){Ly3.write(`${Oy3(J)}
6150
6151
  `)}function Wl4(J,Z){J.option("-V, --version","Print the version number and exit",()=>{ql4(Z),process.exit(0)}),J.command("version").description("Print the version number and exit").action(()=>{ql4(Z),process.exit(0)})}var gb3=nL.join(vX,"logs","headless.log"),Q31=nL.join(Av,"device-id.json"),ya4=`cli-tui-${da4(16).toString("hex")}`;async function mb3(){for(let J of jE)try{if((await J.listConfigs()).length>0)return J}catch(Z){_.debug("Failed to detect query-based IDE integration",{ideName:J.ideName,error:Z})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => H4(Wx(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){i$.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
6151
- `)}function pb3(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",G=!1;J.warn(K,{name:V,code:Y})}}function M7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")lJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")lJ("experimental.agentMode",Z.mode)}function na4(J,Z){if(J.getOptionValueSourceWithGlobals("sp")==="cli"&&Z.sp)return Z.sp;if(J.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Z.systemPrompt)return Z.systemPrompt;return}async function db3(J){try{return await la4(J,"utf-8")}catch{return J}}async function Y31(J,Z,Q){let Y=na4(J,Z);if(!Y)return;let X=_6(Q)?Q.features:[],K=_6(Q)?Q.user.email:void 0;if(!po(X,_7.HARNESS_SYSTEM_PROMPT)&&!aa4(K))throw new T1("You are not allowed to do this.",1);lJ("systemPrompt",await db3(Y))}function aa4(J){return!!(J&&J10(J))}function po(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function X31(J){return(J.userEmail?B$(J.userEmail):!1)||po(J.features,_7.DTW_TUI)}function xa4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new T1("This TUI mode is not enabled for your user;",1)}function K31(J,Z){if(typeof J==="boolean")return J;if(!_6(Z))return!1;return X31({userEmail:Z.user.email,features:Z.features})}function cb3(J){return J!=="pending"}function Hx(J){if(!_6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function lb3(J){let Z=Hx(J);if(Z)return Z.id;if(Fz(J))throw Error(J.error.message);throw Error("unreachable")}function ib3(J){try{let Z=new URL(J);return Z.hostname==="localhost"||Z.hostname==="127.0.0.1"}catch{return J.includes("localhost")||J.includes("127.0.0.1")}}function lz0(J){let Y=ib3(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new T1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function fa4(J){if(!a6.write(J))await fb3(a6,"drain")}var ua4=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??pK,description:`Custom settings file path (overrides the default location ${pK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(_).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Va0})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:l7(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"mode",long:"mode",short:"m",type:"option",default:Jz.SMART.key,description:`Set the agent mode (${uX({},!1).map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:uX().map((J)=>J.mode).concat("large","deep","internal")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable v2 thread mode and use the legacy worker runtime",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless DTW harness (no TUI). Optionally provide a thread ID to connect as executor.",hidden:!0},{name:"threadActors",long:"thread-actors",type:"switch",description:"Connect to the thread-actors counter service. Optionally provide a thread ID.",hidden:!0},{name:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0}],ba4=(J)=>("deprecated"in J)&&J.deprecated===!0,nb3=(J)=>("hidden"in J)&&J.hidden===!0,ab3=(J)=>("default"in J),ob3=(J)=>("default"in J)?J.default:void 0,oa4=[{name:"toggle-skills-count",entryPoint:q01}];function rb3(J,Z){let Q=Z.args[0],Y=Z.commands.map((K)=>K.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let K=Y.filter((G)=>Q.includes(G)||G.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new T1(M3.unknownCommand(Q),1,V)}}async function G31(J){return{...J,getThreadEnvironment:qZ,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new sV(J.fileSystem),generateThreadTitle:W90,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>JJ(J.configService),pluginService:J.pluginService}}function ra4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:qZ,filesystem:J.fileSystem,threadService:J.threadService}}var iz0=F1.file(ia4.homedir()),V31=process.env.XDG_CONFIG_HOME?F1.file(process.env.XDG_CONFIG_HOME):G1.joinPath(iz0,".config");function sb3(J){return sq4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){if(process.platform==="darwin"&&Z==="idle"&&J.isTUIVoiceNotifEnabled())rq4();else Gp0(Z);let Q=$K0(),Y=Or0();if((!Q||Y||hC4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(TU("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(TU("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve($K0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}async function T9(J,Z,Q){let Y=Q?.deferAuth??!1;Gu1("0.0.1775909092-g9fb21e");let X=a10({storage:J.settings,secretStorage:J.secrets,workspaceRoot:k0.of(F1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:iz0,userConfigDir:V31});Ub4(X);let K=await X.getLatest();_.debug("Global configuration initialized",{settingsKeys:Object.keys(K.settings)});let V=!1;{let m=await J.secrets.get("apiKey",J.ampURL);if(V=Boolean(m),_.info("API key lookup before login",{found:Boolean(m),ampURL:J.ampURL,deferAuth:Y}),!m)if(Y)_.info("No API key found, continuing startup with deferred auth");else{a6.write(`No API key found. Starting login flow...
6152
+ `)}function pb3(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",G=!1;J.warn(K,{name:V,code:Y})}}function M7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")lJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")lJ("experimental.agentMode",Z.mode)}function na4(J,Z){if(J.getOptionValueSourceWithGlobals("sp")==="cli"&&Z.sp)return Z.sp;if(J.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Z.systemPrompt)return Z.systemPrompt;return}async function db3(J){try{return await la4(J,"utf-8")}catch{return J}}async function Y31(J,Z,Q){let Y=na4(J,Z);if(!Y)return;let X=_6(Q)?Q.features:[],K=_6(Q)?Q.user.email:void 0;if(!po(X,_7.HARNESS_SYSTEM_PROMPT)&&!aa4(K))throw new T1("You are not allowed to do this.",1);lJ("systemPrompt",await db3(Y))}function aa4(J){return!!(J&&J10(J))}function po(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function X31(J){return(J.userEmail?B$(J.userEmail):!1)||po(J.features,_7.DTW_TUI)}function xa4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new T1("This TUI mode is not enabled for your user;",1)}function K31(J,Z){if(typeof J==="boolean")return J;if(!_6(Z))return!1;return X31({userEmail:Z.user.email,features:Z.features})}function cb3(J){return J!=="pending"}function Hx(J){if(!_6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function lb3(J){let Z=Hx(J);if(Z)return Z.id;if(Fz(J))throw Error(J.error.message);throw Error("unreachable")}function ib3(J){try{let Z=new URL(J);return Z.hostname==="localhost"||Z.hostname==="127.0.0.1"}catch{return J.includes("localhost")||J.includes("127.0.0.1")}}function lz0(J){let Y=ib3(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new T1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function fa4(J){if(!a6.write(J))await fb3(a6,"drain")}var ua4=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??pK,description:`Custom settings file path (overrides the default location ${pK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(_).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Va0})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:l7(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"mode",long:"mode",short:"m",type:"option",default:Jz.SMART.key,description:`Set the agent mode (${uX({},!1).map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:uX().map((J)=>J.mode).concat("large","deep","internal")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable v2 thread mode and use the legacy worker runtime",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless DTW harness (no TUI). Optionally provide a thread ID to connect as executor.",hidden:!0},{name:"threadActors",long:"thread-actors",type:"switch",description:"Connect to the thread-actors counter service. Optionally provide a thread ID.",hidden:!0},{name:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0}],ba4=(J)=>("deprecated"in J)&&J.deprecated===!0,nb3=(J)=>("hidden"in J)&&J.hidden===!0,ab3=(J)=>("default"in J),ob3=(J)=>("default"in J)?J.default:void 0,oa4=[{name:"toggle-skills-count",entryPoint:q01}];function rb3(J,Z){let Q=Z.args[0],Y=Z.commands.map((K)=>K.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let K=Y.filter((G)=>Q.includes(G)||G.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new T1(M3.unknownCommand(Q),1,V)}}async function G31(J){return{...J,getThreadEnvironment:qZ,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new sV(J.fileSystem),generateThreadTitle:W90,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>JJ(J.configService),pluginService:J.pluginService}}function ra4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:qZ,filesystem:J.fileSystem,threadService:J.threadService}}var iz0=F1.file(ia4.homedir()),V31=process.env.XDG_CONFIG_HOME?F1.file(process.env.XDG_CONFIG_HOME):G1.joinPath(iz0,".config");function sb3(J){return sq4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){if(process.platform==="darwin"&&Z==="idle"&&J.isTUIVoiceNotifEnabled())rq4();else Gp0(Z);let Q=$K0(),Y=Or0();if((!Q||Y||hC4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(TU("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(TU("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve($K0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}async function T9(J,Z,Q){let Y=Q?.deferAuth??!1;Gu1("0.0.1775969639-g317d38");let X=a10({storage:J.settings,secretStorage:J.secrets,workspaceRoot:k0.of(F1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:iz0,userConfigDir:V31});Ub4(X);let K=await X.getLatest();_.debug("Global configuration initialized",{settingsKeys:Object.keys(K.settings)});let V=!1;{let m=await J.secrets.get("apiKey",J.ampURL);if(V=Boolean(m),_.info("API key lookup before login",{found:Boolean(m),ampURL:J.ampURL,deferAuth:Y}),!m)if(Y)_.info("No API key found, continuing startup with deferred auth");else{a6.write(`No API key found. Starting login flow...
6152
6153
  `);let b=await tb3(J),n=await J.secrets.get("apiKey",J.ampURL);if(_.info("Login flow completed",{success:b,storedKeyPresent:Boolean(n),ampURL:J.ampURL}),!b)await RU(),process.exit(1);V=!0}}{let m=await X.getLatest(),b=m.settings.url,n=m.secrets.isSet?.[b];_.info("Config secrets state after login",{configURL:b,apiKeySet:n?.apiKey??!1})}let G=P1(JJ(X).pipe(h5(cb3))),F=Y?"pending":await G;if(!Y)_.info("Server status resolved",{status:"ready",isAuthenticated:_6(F),isError:Fz(F),errorMessage:Fz(F)?F.error.message:void 0});let z=G.then((m)=>lb3(m)),{toolService:q,dispose:W}=xJ0({configService:X}),H=new Map,U=()=>H.clear(),D=new BT0(X,J.settings.getWorkspaceRootPath()),B=ze1({configService:X,filesystem:C8}),N=Yo1({configService:X,trustStore:D,skillMCPServers:B.skillMCPServers,createOAuthProvider:async(m,b,n)=>{let c=`${m}:${b}`,s=H.get(c);if(s)return _.debug("Reusing existing OAuth provider for server",{serverName:m,serverUrl:b}),s;_.debug("Creating OAuth provider for server",{serverName:m,serverUrl:b});let W0=(async()=>{let r=new kE(J.secrets),F0=await r.getClientInfo(m,b),w0=n?.scopes??F0?.scopes,L0=JP4();_.info("OAuth headless mode check",{useHeadless:L0,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:a6.isTTY});let e;if(L0)e=J.executeMode?$P4():eI4(m);let K0=new oR0({storage:r,serverName:m,serverUrl:b,clientId:n?.clientId??F0?.clientId,clientSecret:n?.clientSecret??F0?.clientSecret,authUrl:n?.authUrl??F0?.authUrl,tokenUrl:n?.tokenUrl??F0?.tokenUrl,scopes:w0,headlessAuthHandler:e});return _.debug("OAuth provider created",{serverName:m,serverUrl:b,hasManualClientId:!!(n?.clientId??F0?.clientId),willUseDCR:!(n?.clientId??F0?.clientId),scopes:w0,headlessMode:L0,executeMode:J.executeMode}),K0})();return H.set(c,W0),W0}}),w=Dm0({configService:X,filesystem:C8,spawn:t$0}),L;if(J.executeMode){let m=await tG4({toolService:q,providers:[N,w],initialTimeout:15000});L=m.registrations;for(let[b,n]of m.initErrors)_.warn(`${b} provider initialization slow or failed:`,n)}else L=Bm0({toolService:q,providers:[N,w]});if(Z.jetbrains)LE("JetBrains");else if(Z.ide&&bP4())LE("VS Code");else if(Z.ide&&hP4())LE("Neovim");else if(Z.ide){let m=await mb3();if(m){let b=Y40(m.ideName);if(b)LE(b)}}if(J.executeMode)Fu1(!0);let O,E=$J.status.pipe(w1((m)=>Boolean(m.connected&&m.authenticated&&m.ideName&&ou1(m.ideName))),g4()).subscribe((m)=>{if(m){if(!O)O=q.registerTool(sG4)}else O?.dispose(),O=void 0}),M;if(!J.executeMode){let m=await J.settings.get("fuzzy.alwaysIncludePaths")??[];M=new Uv(process.cwd(),{alwaysIncludePaths:m},!0)}else M=new class extends Uv{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let A=new wk0(I80(X),{maxThreads:200});_.info("Starting Amp background services");let j=Z.takeMeBack?!1:void 0,I=K31(j,F),T=new N01,P=process.env.PLUGINS??"off",h=Z.headless?tu4():void 0,p=h??new nV0({configService:X}),x=p instanceof nV0?p:void 0;if(x)x.pluginExecutorKind=I?"local":"unknown";let k=kT0({configService:X,fileSystem:C8,platform:p,internalPlugins:oa4,pluginFilter:P}),f=eo1({pluginService:k,toolService:q}),d={configService:X,toolService:q,mcpService:N,skillService:B,toolboxService:w,trustStore:D,threadService:A,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:M,fileSystem:C8,terminal:T,pluginService:k,pluginPlatform:x,headlessPluginPlatform:h,serverStatus:F,serverStatusPromise:G,viewerUserIDPromise:z,hasAPIKeyAtStartup:V};return{...d,async asyncDispose(){if(d.mcpService.hasAuthenticatingClients())_.info("Waiting for OAuth authentication to complete before exit..."),await d.mcpService.waitForAuthentication();for(let m of L.values())m.dispose();await d.mcpService.dispose(),U(),await d.threadService.asyncDispose(),d.configService.unsubscribe(),W(),d.fuzzyServer.dispose(),d.settingsStorage[Symbol.dispose](),E.unsubscribe(),O?.dispose(),f.dispose(),await d.pluginService.dispose()}}}async function tb3(J){if(!J.executeMode){if(!await dX0("Would you like to log in to Amp? [(y)es, (n)o]: "))return a6.write(`Login cancelled. Run the command again to retry.
6153
6154
  `),!1}return await sa4(J)}async function sa4(J){let Z=da4(32).toString("hex"),Q=await kv(J.ampURL,Z),Y=new AbortController;try{await TV(Q,Y.signal)}catch(K){_.error("Error opening browser",{error:K})}let X=await kv(J.ampURL,Z,!1);a6.write(`If your browser does not open automatically, visit:
6154
6155
 
@@ -6156,7 +6157,7 @@ ${i0.blue.bold(X)}
6156
6157
 
6157
6158
  `);try{return await r_4(J.ampURL,Z,J.secrets,Y),a6.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(K){return _.error("Login failed",{error:K}),i$.write(`
6158
6159
  Login failed: ${K instanceof Error?K.message:String(K)}
6159
- `),!1}}function ha4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function eb3(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new T1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!Q7(Y.threadId))throw new T1("Create response did not include a valid thread ID",1);return Y.threadId}function $h3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function Jh3(J){let Z=await fetch(new URL(`/threads/${J.threadID}/durable-object-id`,J.workerURL),{method:"GET",headers:{Authorization:`Bearer ${J.apiKey}`}});if(!Z.ok){let Y=await Z.text();throw new T1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!$h3(Q))throw new T1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function Zh3(J){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(J)}async function Qh3(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new T1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function Yh3(J){let Z=new tN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Z.exitOverride((B)=>{if(B.code==="commander.help"||B.code==="commander.version"||B.exitCode===0)vj(),process.exit(0);let N=B.originalError??B;uR4(N)}),Wl4(Z,{version:"0.0.1775909092-g9fb21e",buildTimestamp:"2026-04-11T12:08:43.560Z",buildType:"'release'"}),Z.addHelpText("after",xP4()),Z.configureHelp({formatHelp:fP4}),Z.command("logout").description("Log out by removing stored API key").action(async(B,N)=>{let w=N.optsWithGlobals(),L=await _3(w);await Wh3(L)}),Z.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(B,N)=>{let w=N.optsWithGlobals(),L=await _3(w);await qh3(L,await gi(w,L.settings))}),Z.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(B,N,w)=>{let L=w.optsWithGlobals(),O=await _3(L);await UI4(B??"get",O.ampURL,O.secrets),process.exit(process.exitCode??0)}),Z.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(B,N)=>{let w=N.optsWithGlobals(),L=await _3(w);await DI4(L.ampURL,L.secrets),process.exit(process.exitCode??0)}),Z.command("dtw-curl [threadId] [action] [message...]",{hidden:!0}).summary("DTW helper").description("Internal: helper for DTW one-shot commands.").addHelpText("after",`
6160
+ `),!1}}function ha4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function eb3(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new T1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!Q7(Y.threadId))throw new T1("Create response did not include a valid thread ID",1);return Y.threadId}function $h3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function Jh3(J){let Z=await fetch(new URL(`/threads/${J.threadID}/durable-object-id`,J.workerURL),{method:"GET",headers:{Authorization:`Bearer ${J.apiKey}`}});if(!Z.ok){let Y=await Z.text();throw new T1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!$h3(Q))throw new T1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function Zh3(J){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(J)}async function Qh3(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new T1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function Yh3(J){let Z=new tN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Z.exitOverride((B)=>{if(B.code==="commander.help"||B.code==="commander.version"||B.exitCode===0)vj(),process.exit(0);let N=B.originalError??B;uR4(N)}),Wl4(Z,{version:"0.0.1775969639-g317d38",buildTimestamp:"2026-04-12T04:57:51.445Z",buildType:"'release'"}),Z.addHelpText("after",xP4()),Z.configureHelp({formatHelp:fP4}),Z.command("logout").description("Log out by removing stored API key").action(async(B,N)=>{let w=N.optsWithGlobals(),L=await _3(w);await Wh3(L)}),Z.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(B,N)=>{let w=N.optsWithGlobals(),L=await _3(w);await qh3(L,await gi(w,L.settings))}),Z.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(B,N,w)=>{let L=w.optsWithGlobals(),O=await _3(L);await UI4(B??"get",O.ampURL,O.secrets),process.exit(process.exitCode??0)}),Z.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(B,N)=>{let w=N.optsWithGlobals(),L=await _3(w);await DI4(L.ampURL,L.secrets),process.exit(process.exitCode??0)}),Z.command("dtw-curl [threadId] [action] [message...]",{hidden:!0}).summary("DTW helper").description("Internal: helper for DTW one-shot commands.").addHelpText("after",`
6160
6161
  Actions:
6161
6162
  create Create a new DTW thread and print its ID
6162
6163
  add-message <message> Send a user message and wait for message_added
@@ -6201,7 +6202,8 @@ See: https://ampcode.com/news/stick-a-fork-in-it
6201
6202
  - Keywords: Bare words or quoted phrases for text search: auth or "race condition"
6202
6203
  - File filter: file:path to find threads that touched a file: file:src/auth/login.ts
6203
6204
  - Repo filter: repo:url to scope to a repository: repo:github.com/owner/repo
6204
- - Combine filters: Use implicit AND: auth file:src/foo.ts repo:amp
6205
+ - Ref filter: ref:name to scope to a git ref: ref:main
6206
+ - Combine filters: Use implicit AND: auth file:src/foo.ts repo:amp ref:main
6205
6207
 
6206
6208
  All matching is case-insensitive. File paths use partial matching.`).option("-n, --limit <number>","Maximum number of threads to return","20").option("--offset <number>","Number of results to skip (for pagination)","0").option("--json","Output as JSON").action(async(B,N,w)=>{let L=w.optsWithGlobals(),O=await _3(L);await Ih3(L,O,B,N.limit?parseInt(N.limit,10):20,N.offset?parseInt(N.offset,10):0,N.json??!1)}),Y.command("label <threadIDOrURL> <labels...>").summary("Add labels to a thread").description("Add one or more labels to an existing thread without removing the labels it already has.").action(async(B,N,w,L)=>{let O=S9(B)??lY(B),E=L.optsWithGlobals(),M=await _3(E);await Lh3(E,M,O,N,L)}),Y.command("share <threadIDOrURL>").summary("Share a thread").description("Change thread visibility (private, public, unlisted, workspace, group) or share with Amp support for debugging. Use --visibility to change who can access the thread, or --support to share with the Amp team for troubleshooting.").alias("s").option("--visibility <visibility>","Set thread visibility (private, public, unlisted, workspace, group)").option("--support [message]","Share thread with Amp support for debugging").action(async(B,N,w)=>{let L=S9(B)??lY(B),O=w.optsWithGlobals(),E=await _3(O);await wh3(O,E,L,w,N.support)}),Y.command("rename <threadIDOrURL> <newName>").alias("r").summary("Rename a thread").description('Change the title of a thread. Quote names with spaces: amp threads rename T-123 "New thread name"').action(async(B,N,w,L)=>{let O=S9(B)??lY(B),E=L.optsWithGlobals(),M=await _3(E);await Hh3(E,M,O,N,L)}),Y.command("archive <threadIDOrURL>").summary("Archive a thread").description("Archive a thread to hide it from the thread switcher and navigation. Use --unarchive to restore.").option("--unarchive","Unarchive the thread instead of archiving").action(async(B,N,w)=>{let L=S9(B)??lY(B),O=w.optsWithGlobals(),E=await _3(O);await Uh3(O,E,L,!N.unarchive)}),Y.command("delete <threadIDOrURL>").summary("Delete a thread").description("Permanently delete a thread from both the local client and the server.").action(async(B,N,w)=>{let L=S9(B)??lY(B),O=w.optsWithGlobals(),E=await _3(O);await Dh3(O,E,L)}),Y.command("handoff [threadIDOrURL]").alias("h").summary("Create a handoff thread from an existing thread").description(`Create a new thread by handing off from an existing thread with a goal/prompt.
6207
6209
 
@@ -6220,8 +6222,8 @@ ${M}
6220
6222
 
6221
6223
  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 Xh3(J){_.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new ba({threadService:J.threadService,configService:J.configService,mcpService:J.mcpService,clientID:J.clientID,initialToolDiscovery:Promise.all([J.mcpService.initialized,J.toolboxService.initialized]).then(()=>{return}),toolService:J.toolService,skillService:J.skillService,getThreadEnvironment:qZ,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new sV(J.fileSystem),ampURL:J.ampURL,useThreadActors:J.useThreadActors});if(J.threadId)await Z.switchThread(J.threadId);else await Z.createThread();return Z}catch(Z){throw _.error("[createDTWThreadPool] Failed to create DTW thread pool",{threadId:J.threadId,error:Z}),Z}}async function Kh3(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await Dy()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await Dy()).trimEnd(),stdinInput:null}}function Vh3(J,Z,Q){if(J.remote&&!Z)throw new T1("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(J.streamJson&&!Z)throw new T1("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new T1("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new T1("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new T1("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new T1("The --archive flag requires --execute mode",1,'Use: amp --execute "your message" --archive');if(J.streamJsonInput&&typeof J.execute==="string"&&J.execute.trim()!=="")throw new T1("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"..."}}]}}' | amp --execute --stream-json --stream-json-input`);if(Z&&Q===""&&!J.streamJsonInput&&!J.headless)throw new T1("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"
6222
6224
  Or pipe via stdin: echo "your message" | amp --execute`)}async function nz0(J,Z,Q,Y){let X=process.hrtime.bigint(),K=(e,K0)=>{let i=Number(process.hrtime.bigint()-K0)/1e6,a=cO4();_.info("Startup phase",{phase:e,phaseMs:Math.round(i),sinceMainMs:a===null?void 0:Math.round(a)})},{userInput:V,stdinInput:G}=await Kh3(Z),F=!!Z.streamJson||!!Z.streamJsonThinking;Vh3({...Z,streamJson:F},J.executeMode,V),M7(Q,Z);let z=process.hrtime.bigint(),q=Boolean(await J.secrets.get("apiKey",J.ampURL)),W=!J.executeMode&&!Z.headless&&!Z.threadActors&&q;_.info("Interactive auth startup mode",{deferInteractiveAuth:W,hasAPIKeyAtStartup:q,executeMode:J.executeMode,headless:Boolean(Z.headless)});let H=await T9(J,Z,{deferAuth:W});K("runMainThread:createThreadDependencies",z),z=process.hrtime.bigint();let U=await G31(H);K("runMainThread:createWorkerDeps",z);let{serverStatus:D}=H;if(!W&&Fz(D)){let e=qv(Error(D.error.message));if(e.message===M3.networkOffline||e.message===M3.networkTimeout)throw lz0(J.ampURL);throw new T1(M3.invalidAPIKey,1)}let B=_6(D)?D:null,N=B?.user.email,w=aa4(N),L=X31({userEmail:N,features:B?.features}),O=Z.takeMeBack?!1:void 0,E=B!==null&&K31(O,B);if(!W)await Y31(Q,Z,D);let M=Hx(D),A=M?.features??[],j=M?.team??null,I=iV0(Z,M);if(I instanceof Error)T3(I.message);if((J.executeMode||F)&&p8(Z.mode)&&!w)throw new T1(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(B&&!EE(Z.mode,N))throw new T1(`Agent mode '${Z.mode}' is only available for Amp employees`,1);if(J.executeMode&&Z.remote)await Jb4(V,G,H.configService),await H.asyncDispose(),process.exit(0);if(Z.headless){if(process.env.AMP_EXECUTOR!=="1"&&(!N||!B$(N)))throw new T1("Headless DTW mode is only available for Amp employees",1);let K0=await H.secretStorage.get("apiKey",J.ampURL);if(!K0)throw new T1("API key required for headless mode. Please run `amp login` first.",1);let i=typeof Z.headless==="string"&&Z.headless!=="true"?Z.headless:void 0;if(i&&!Q7(i))throw new T1(`Invalid thread ID: ${i}`,1);let a=i?void 0:await Eh3({dependencies:H,visibility:I??void 0,usesThreadActors:Z.threadActors?!0:void 0}),t=i??a?.threadId;if(!t)throw new T1("Failed to resolve headless thread ID",1);let $0=await XP4(t);if($0.status==="already-running")await H.asyncDispose(),await RU(),process.exit(0);try{await sI4({ampURL:J.ampURL,apiKey:K0,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:t,ownerUserId:a?.ownerUserId,threadVersion:a?.threadVersion,agentMode:a?.agentMode,initialToolDiscovery:Promise.all([H.mcpService.initialized,H.toolboxService.initialized]).then(()=>{return}),configService:H.configService,mcpService:H.mcpService,toolService:H.toolService,skillService:H.skillService,fileSystem:H.fileSystem,pluginService:H.pluginService,pluginPlatform:H.headlessPluginPlatform,useThreadActors:Z.threadActors?!0:void 0})}finally{await $0.release(),await H.asyncDispose()}await RU(),process.exit(0)}let T=J.executeMode?void 0:async(e)=>co(e,"interactive"),P={threadService:H.threadService,workerDeps:U,createThread:async()=>{let e=W?await H.serverStatusPromise:D,K0=await RY0(J.settings,process.cwd(),Hx(e),I);if(K0 instanceof Error)T3(K0.message);return S01(U,{threadMeta:K0?JF(K0):void 0,agentMode:Z.mode,onFirstAssistantMessage:T})},validateThreadOwnership:async(e,K0)=>{if(K0?.nonBlockingOwnershipCheck){ga4(e,H.configService,H.viewerUserIDPromise).catch((i)=>{if(i instanceof T1){if(K0.onOwnershipError){K0.onOwnershipError(i,e);return}IU(i,e);return}_.warn("Failed to validate thread ownership in CLI, allowing to open",{error:i})});return}try{await ga4(e,H.configService,H.viewerUserIDPromise)}catch(i){if(i instanceof T1)throw i;_.warn("Failed to validate thread ownership in CLI, allowing to open",{error:i})}},switchThreadVisibility:I,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:T,handleError:IU},h=async(e)=>{try{if(e==="dtw")return Xh3({ampURL:J.ampURL,configService:H.configService,threadService:H.threadService,mcpService:H.mcpService,clientID:ya4,toolboxService:H.toolboxService,toolService:H.toolService,skillService:H.skillService,fileSystem:H.fileSystem,threadId:Z.threadId,useThreadActors:Z.threadActors?!0:void 0});return Jh4(P,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch(K0){if(K0 instanceof T1)throw K0;throw await IU(K0,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")i$.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
6223
- `),await RU(),process.exit(1);let p=(async()=>{if(W){_.info("Skipping initial free tier status fetch until auth is complete");return}try{let e=await H.configService.getLatest(),K0=Gb(e),i=await i5.getUserFreeTierStatus({},{config:H.configService,signal:AbortSignal.timeout(K0)});if(i.ok)return _.info("User free tier status:",i),i.result;return}catch(e){_.error("Failed to fetch free tier status:",e);return}})(),k=!J.executeMode?new P01:null,f,d=null;if(k)f=k,d=(async()=>{let e=W?await H.serverStatusPromise:H.serverStatus;await Y31(Q,Z,e);let K0=process.hrtime.bigint(),i=K31(O,e),a=_6(e)?X31({userEmail:e.user.email,features:e.features}):!1;xa4({dtwEnabled:i,hasV2TUIAccess:a});let t=await h(i?"dtw":"worker");if(K("runMainThread:createThreadPool",K0),k.attach(t),V){let $0=await P1(t.threadHandles$);if(!$0)throw new T1("No active thread is available yet.",1);await $0.sendMessage({content:[{type:"text",text:V}]})}})(),d.catch(async(e)=>{let K0=e instanceof Error?e:Error(String(e));k.setInitError(K0),await IU(e,Z.threadId)});else z=process.hrtime.bigint(),xa4({dtwEnabled:E,hasV2TUIAccess:L}),f=await h(E?"dtw":"worker"),K("runMainThread:createThreadPool",z);let m=Z.notifications!==void 0?Z.notifications:!J.executeMode,b=B!==null&&po(B.features,_7.TUI_VOICE_NOTIF);if(W)H.serverStatusPromise.then((e)=>{b=_6(e)&&po(e.features,_7.TUI_VOICE_NOTIF)}).catch((e)=>{_.debug("Failed to resolve TUI voice notification feature flag",{error:e})});z=process.hrtime.bigint();let n=await H.configService.getLatest();if(K("runMainThread:configService.getLatest",z),z=process.hrtime.bigint(),sb3({configService:H.configService,threadService:H.threadService,config:n,useNotificationsForService:m,isTUIVoiceNotifEnabled:()=>b,threadViewStates$:()=>f.threadHandles$.pipe(_4((e)=>{if(!e)return k0.of({});return F5(e.thread$,e.threadViewState$).pipe(w1(([K0,i])=>({[K0.id]:i})))}))}),K("runMainThread:createCliNotificationService",z),J.executeMode){iu4(H.mcpService,J.settings);let e={userInput:V,stdinInput:G,dependencies:H,streamJson:F,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label},K0=await sR4({threadPool:f,...e});if(await co(K0,"execute"),Z.archive)await H.threadService.archive(K0,!0),await lo(H.threadService,K0);await H.asyncDispose(),process.exit(0)}let c=!1,s=!1;if(Z.jetbrains||Z.ide){await Jb1();let e=await RE({jetbrainsOnly:Z.jetbrains});if(e.length===0){if(Z.jetbrains)c=!await H.configService.get("jetbrains.skipInstall")}else if(e.length===1){let K0=e[0];if(K0)$J.selectConfig(K0)}else s=!0}z=process.hrtime.bigint();let W0=To0("0.0.1775909092-g9fb21e",H.settingsStorage,{startDelayMs:3000});K("runMainThread:createUpdateService",z),z=process.hrtime.bigint();let r=new z01(H.mcpService,J.settings.getWorkspaceRootPath());if(K("runMainThread:createMcpTrustHandler",z),V&&J.executeMode){let e=await P1(f.threadHandles$);if(!e)throw new T1("No active thread is available yet.",1);await e.sendMessage({content:[{type:"text",text:V}]})}z=process.hrtime.bigint();let F0=await aV0();K("runMainThread:loadSessionState",z),_.info("Loaded session state:",F0);let w0={...F0,launchCount:F0.launchCount+1};Hy((e)=>({...e,launchCount:e.launchCount+1}));let L0=Z.threadId&&Q7(Z.threadId)?Z.threadId:void 0;try{if(z=process.hrtime.bigint(),await uh4({history:new pa0,fuzzyServer:H.fuzzyServer,settingsStorage:H.settingsStorage,threadService:H.threadService,skillService:H.skillService,configService:H.configService,secretStorage:H.secretStorage,internalAPIClient:i5,threadPool:f,createSystemPromptDeps:async()=>ra4(H),ideClient:$J,mcpService:H.mcpService,toolboxService:H.toolboxService,mcpTrustHandler:r,updateService:W0,pluginPlatform:H.pluginPlatform,pluginService:H.pluginService},{initialServerStatus:H.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:H.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:L0,showJetBrainsInstaller:c,showIdePickerHint:s,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:ya4,logFile:{path:Y},sessionState:w0,freeTierStatusPromise:p,workspace:j??null,features:A,isDogfooding:w,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-04-11T12:08:43.560Z"},(e)=>new m01({...e,threadPool:e.threadPool},(K0)=>new C61({...K0,threadState:K0.threadState}))),K("runMainThread:mountApp-returned",z),d)await d}finally{await f.dispose().catch((e)=>{_.error("Failed to dispose thread pool during shutdown",e)})}await H.asyncDispose(),K("runMainThread:dependencies.asyncDispose",X),process.exit(0)}async function _3(J){if(_.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),J.interactive)i$.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
6224
- `);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;_.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await Fo1({get:async(G)=>{if(G!==Fg)return;try{let F=await la4(Q31,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(G,F)=>{if(G!==Fg)return;await ca4(nL.dirname(Q31),{recursive:!0}),await ub3(Q31,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:eF()});zu1(Y);let X=await GX0({...J,workspaceTrust:{current:!0,changes:Aj0},getHook:process.env.AMP_URL?(G,F)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return F()}:void 0});if(J.mcpConfig){let G=await cu4(J.mcpConfig);X=lu4(X,G)}let K=nL.dirname(X.getSettingsFilePath());oq4(Av,K);let V=await X.get("url","global");if(!V)V=Z7;if(_.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!hW(V))_.info("Targeting custom Amp server",{ampURL:V});return X=Qf1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:cX0(await gi(J,X))}}function Gh3(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let K=Y.slice(2).replace(/-([a-z])/g,(G,F)=>F.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}function Fh3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=nL.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?gb3:Va0));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function zh3(){dO4();let J=Gh3(process.argv),Z=Fh3(process.argv,J),Q=ej4(Z),Y=process.argv.includes("--no-color"),X=process.argv.includes("--color"),K=process.stdout.isTTY&&process.stderr.isTTY;if(Y||!X&&!K)i0.level=0;if(pb3(_),_.info("Starting Amp CLI.",{version:"0.0.1775909092-g9fb21e",buildTimestamp:"2026-04-11T12:08:43.560Z"}),process.platform==="win32"&&gj())QC4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new T1(M3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");if(process.argv.includes("--neo")){await uu4();return}await Yh3(Q).parseAsync(process.argv)}nq4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await zh3().catch(IU)});async function qh3(J,Z){let Q=J.ampURL.includes("localhost")||J.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!Q)await J.settings.set("url",process.env.AMP_URL,"global"),a6.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
6225
+ `),await RU(),process.exit(1);let p=(async()=>{if(W){_.info("Skipping initial free tier status fetch until auth is complete");return}try{let e=await H.configService.getLatest(),K0=Gb(e),i=await i5.getUserFreeTierStatus({},{config:H.configService,signal:AbortSignal.timeout(K0)});if(i.ok)return _.info("User free tier status:",i),i.result;return}catch(e){_.error("Failed to fetch free tier status:",e);return}})(),k=!J.executeMode?new P01:null,f,d=null;if(k)f=k,d=(async()=>{let e=W?await H.serverStatusPromise:H.serverStatus;await Y31(Q,Z,e);let K0=process.hrtime.bigint(),i=K31(O,e),a=_6(e)?X31({userEmail:e.user.email,features:e.features}):!1;xa4({dtwEnabled:i,hasV2TUIAccess:a});let t=await h(i?"dtw":"worker");if(K("runMainThread:createThreadPool",K0),k.attach(t),V){let $0=await P1(t.threadHandles$);if(!$0)throw new T1("No active thread is available yet.",1);await $0.sendMessage({content:[{type:"text",text:V}]})}})(),d.catch(async(e)=>{let K0=e instanceof Error?e:Error(String(e));k.setInitError(K0),await IU(e,Z.threadId)});else z=process.hrtime.bigint(),xa4({dtwEnabled:E,hasV2TUIAccess:L}),f=await h(E?"dtw":"worker"),K("runMainThread:createThreadPool",z);let m=Z.notifications!==void 0?Z.notifications:!J.executeMode,b=B!==null&&po(B.features,_7.TUI_VOICE_NOTIF);if(W)H.serverStatusPromise.then((e)=>{b=_6(e)&&po(e.features,_7.TUI_VOICE_NOTIF)}).catch((e)=>{_.debug("Failed to resolve TUI voice notification feature flag",{error:e})});z=process.hrtime.bigint();let n=await H.configService.getLatest();if(K("runMainThread:configService.getLatest",z),z=process.hrtime.bigint(),sb3({configService:H.configService,threadService:H.threadService,config:n,useNotificationsForService:m,isTUIVoiceNotifEnabled:()=>b,threadViewStates$:()=>f.threadHandles$.pipe(_4((e)=>{if(!e)return k0.of({});return F5(e.thread$,e.threadViewState$).pipe(w1(([K0,i])=>({[K0.id]:i})))}))}),K("runMainThread:createCliNotificationService",z),J.executeMode){iu4(H.mcpService,J.settings);let e={userInput:V,stdinInput:G,dependencies:H,streamJson:F,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label},K0=await sR4({threadPool:f,...e});if(await co(K0,"execute"),Z.archive)await H.threadService.archive(K0,!0),await lo(H.threadService,K0);await H.asyncDispose(),process.exit(0)}let c=!1,s=!1;if(Z.jetbrains||Z.ide){await Jb1();let e=await RE({jetbrainsOnly:Z.jetbrains});if(e.length===0){if(Z.jetbrains)c=!await H.configService.get("jetbrains.skipInstall")}else if(e.length===1){let K0=e[0];if(K0)$J.selectConfig(K0)}else s=!0}z=process.hrtime.bigint();let W0=To0("0.0.1775969639-g317d38",H.settingsStorage,{startDelayMs:3000});K("runMainThread:createUpdateService",z),z=process.hrtime.bigint();let r=new z01(H.mcpService,J.settings.getWorkspaceRootPath());if(K("runMainThread:createMcpTrustHandler",z),V&&J.executeMode){let e=await P1(f.threadHandles$);if(!e)throw new T1("No active thread is available yet.",1);await e.sendMessage({content:[{type:"text",text:V}]})}z=process.hrtime.bigint();let F0=await aV0();K("runMainThread:loadSessionState",z),_.info("Loaded session state:",F0);let w0={...F0,launchCount:F0.launchCount+1};Hy((e)=>({...e,launchCount:e.launchCount+1}));let L0=Z.threadId&&Q7(Z.threadId)?Z.threadId:void 0;try{if(z=process.hrtime.bigint(),await uh4({history:new pa0,fuzzyServer:H.fuzzyServer,settingsStorage:H.settingsStorage,threadService:H.threadService,skillService:H.skillService,configService:H.configService,secretStorage:H.secretStorage,internalAPIClient:i5,threadPool:f,createSystemPromptDeps:async()=>ra4(H),ideClient:$J,mcpService:H.mcpService,toolboxService:H.toolboxService,mcpTrustHandler:r,updateService:W0,pluginPlatform:H.pluginPlatform,pluginService:H.pluginService},{initialServerStatus:H.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:H.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:L0,showJetBrainsInstaller:c,showIdePickerHint:s,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:ya4,logFile:{path:Y},sessionState:w0,freeTierStatusPromise:p,workspace:j??null,features:A,isDogfooding:w,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-04-12T04:57:51.445Z"},(e)=>new m01({...e,threadPool:e.threadPool},(K0)=>new C61({...K0,threadState:K0.threadState}))),K("runMainThread:mountApp-returned",z),d)await d}finally{await f.dispose().catch((e)=>{_.error("Failed to dispose thread pool during shutdown",e)})}await H.asyncDispose(),K("runMainThread:dependencies.asyncDispose",X),process.exit(0)}async function _3(J){if(_.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),J.interactive)i$.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
6226
+ `);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;_.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await Fo1({get:async(G)=>{if(G!==Fg)return;try{let F=await la4(Q31,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(G,F)=>{if(G!==Fg)return;await ca4(nL.dirname(Q31),{recursive:!0}),await ub3(Q31,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:eF()});zu1(Y);let X=await GX0({...J,workspaceTrust:{current:!0,changes:Aj0},getHook:process.env.AMP_URL?(G,F)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return F()}:void 0});if(J.mcpConfig){let G=await cu4(J.mcpConfig);X=lu4(X,G)}let K=nL.dirname(X.getSettingsFilePath());oq4(Av,K);let V=await X.get("url","global");if(!V)V=Z7;if(_.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!hW(V))_.info("Targeting custom Amp server",{ampURL:V});return X=Qf1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:cX0(await gi(J,X))}}function Gh3(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let K=Y.slice(2).replace(/-([a-z])/g,(G,F)=>F.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}function Fh3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=nL.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?gb3:Va0));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function zh3(){dO4();let J=Gh3(process.argv),Z=Fh3(process.argv,J),Q=ej4(Z),Y=process.argv.includes("--no-color"),X=process.argv.includes("--color"),K=process.stdout.isTTY&&process.stderr.isTTY;if(Y||!X&&!K)i0.level=0;if(pb3(_),_.info("Starting Amp CLI.",{version:"0.0.1775969639-g317d38",buildTimestamp:"2026-04-12T04:57:51.445Z"}),process.platform==="win32"&&gj())QC4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new T1(M3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");if(process.argv.includes("--neo")){await uu4();return}await Yh3(Q).parseAsync(process.argv)}nq4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await zh3().catch(IU)});async function qh3(J,Z){let Q=J.ampURL.includes("localhost")||J.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!Q)await J.settings.set("url",process.env.AMP_URL,"global"),a6.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
6225
6227
  `);else if(!hW(J.ampURL))a6.write(`Logging in to ${new URL(J.ampURL).hostname}
6226
6228
  `);let Y=process.env.AMP_API_KEY;if(Y)a6.write(`API key found in environment variable, storing...
6227
6229
  `),await Z.set("apiKey",Y,J.ampURL),a6.write(`API key successfully stored.