@sourcegraph/amp 0.0.1775563890-g5b477c → 0.0.1775571702-gac76fb
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +12 -12
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -1066,7 +1066,7 @@ Use the create_handoff_context tool to extract relevant information and files.`;
|
|
|
1066
1066
|
`),!0}}return!1},B=D(G,F);if(!B){let N=TA(eX4(Q)),w=TA(eX4(Y));V=Z,B=D(N,w)}if(!B)throw Error("Could not find exact match for old_str")}}let z=uY(Z,V,J),q=Og0(z),W=0,H=0;if(X)W=1,H=V.split(`
|
|
1067
1067
|
`).length;else if(V.includes(F)){let U=V.indexOf(F);W=(V.substring(0,U).match(/\n/g)||[]).length+1;let D=(F.match(/\n/g)||[]).length;H=W+D}else H=V.split(`
|
|
1068
1068
|
`).length;return{modifiedContent:V,formattedDiff:q,lineRange:[W,H]}}function uY(J,Z,Q="file"){let Y=TA(J??""),X=TA(Z);return _A(Q.toString(),Q.toString(),Y,X,"original","modified",{ignoreWhitespace:!0})}function TA(J){return J.replace(/\r\n/g,`
|
|
1069
|
-
`)}function Og0(J){J=J.replace(
|
|
1069
|
+
`)}function Og0(J){J=J.replace(/^\(?:\r?\n|$)/gm,"");let Z=3;while(J.includes("`".repeat(Z)))Z++;return`${"`".repeat(Z)}diff
|
|
1070
1070
|
${J}${"`".repeat(Z)}`}var Lg0,lA5,$K4;var nN=Q0(()=>{wg0();N9();I4();sX4();Lg0=v.object({path:v.string().describe("The absolute path to the file (MUST be absolute, not relative). File must exist. ALWAYS generate this argument first."),old_str:v.string().describe("Text to search for. Must match exactly."),new_str:v.string().describe("Text to replace old_str with."),replace_all:v.boolean().default(!1).optional().describe("Set to true to replace all matches of old_str. Else, old_str must be an unique match.")}),lA5=`Make edits to a text file.
|
|
1071
1071
|
|
|
1072
1072
|
Replaces \`old_str\` with \`new_str\` in the given file.
|
|
@@ -6088,7 +6088,7 @@ password=${K}
|
|
|
6088
6088
|
`)}n0();f7();Lc();p_();function Tj(J){return J.toolUseId}function ZJ3(J){return J.parentToolUseId}function CY0(J){let Z=Tj(J);return{id:J.id||Z,toolCallId:Z,toolName:J.toolName,args:J.args,reason:J.reason,toAllow:J.toAllow,context:J.context,subagentToolName:J.subagentToolName,parentToolCallId:ZJ3(J),timestamp:J.timestamp,matchedRule:J.matchedRule,ruleSource:J.ruleSource}}rJ();U4();import Ri from"node:path";class Sj extends Error{code;constructor(J,Z){super(Z);this.code=J;this.name="ExecutorFileSystemPathError"}}function sR4(J,Z){let Q=G1.parse(J);if(Q.scheme!=="file")throw new Sj("INVALID_URI","Only file:// URIs are supported");if(!Q.path.startsWith("/"))throw new Sj("INVALID_URI","File URI path must be absolute");if(Q.path.split("/").some((F)=>F===".."))throw new Sj("ACCESS_DENIED","File URI resolves outside workspace root");let X=Ri.posix.normalize(Q.path).replace(/^\/+/u,"");if(X===".."||X.startsWith("../"))throw new Sj("ACCESS_DENIED","File URI resolves outside workspace root");let K=Ri.resolve(Z),V=X.length>0?Ri.resolve(K,X):K,G=Ri.relative(K,V);if(G.startsWith("..")||Ri.isAbsolute(G))throw new Sj("ACCESS_DENIED","File URI resolves outside workspace root");return V}async function qv(J,Z){try{let Q=sR4(Z,J.workspaceRoot),Y=await J.fileSystem.readdir(G1.file(Q));return{ok:!0,entries:await Promise.all(Y.map(async(K)=>{let V=K.isDirectory?"directory":"file",G=V==="file"?await QJ3(J.fileSystem,K.uri):void 0;return[V1.basename(K.uri),V,G]}))}}catch(Q){return{ok:!1,error:tR4(Q,"read_directory")}}}async function QJ3(J,Z){try{let Q=await J.getMtime(Z);if(!Number.isFinite(Q)||Q<0)return;return{mtimeMs:Q}}catch{return}}async function TY0(J,Z){try{let Q=sR4(Z,J.workspaceRoot),Y=await J.fileSystem.readBinaryFile(G1.file(Q));return{ok:!0,contentBase64:Buffer.from(Y).toString("base64")}}catch(Q){return{ok:!1,error:tR4(Q,"read_file")}}}function tR4(J,Z){if(J instanceof Sj)return{code:J.code,message:J.message};if(w9(J))return{code:"NOT_FOUND",message:"File or directory not found"};if(_Y0(J,"EISDIR"))return{code:"IS_DIRECTORY",message:"Expected a file but found a directory"};if(_Y0(J,"ENOTDIR"))return{code:Z==="read_directory"?"NOT_DIRECTORY":"INTERNAL_ERROR",message:Z==="read_directory"?"Expected a directory":rR4(J)};if(_Y0(J,"EACCES")||_Y0(J,"EPERM"))return{code:"ACCESS_DENIED",message:"Permission denied"};return{code:"INTERNAL_ERROR",message:rR4(J)}}function _Y0(J,Z){if(!(J instanceof Error))return!1;return"code"in J&&J.code===Z}function rR4(J){if(J instanceof Error)return J.message;return String(J)}n0();gW();F3();c4();U4();E1();kA();c4();async function eR4(J){let Z=await WZ(),Q=B9(J)?J:h8(),Y=await _g0({filesystem:I8},Z,Q);return{...Z,...Y,updatedAt:new Date().toISOString()}}function YJ3(J){return new TextEncoder().encode(JSON.stringify(J)).length}function Wv(J,Z,Q){if(J.length===0)return[];let Y=[],X=[];for(let K of J){let V=[...X,K],G=YJ3(Q(V));if(X.length>0&&G>Z){Y.push(X),X=[K];continue}X=V}if(X.length>0)Y.push(X);return Y}var JI4=1048576;function $I4(J){let Z=new Map;for(let Q of J)Z.set(Q.name,{schema:Q,serializedSchema:JSON.stringify(Q)});return Z}function XJ3(J){let Z={...J.executionProfile?.serial!==void 0?{serial:J.executionProfile.serial}:{},...J.meta?.deferred!==void 0?{deferred:J.meta.deferred}:{},...J.meta?.skillNames!==void 0?{skillNames:[...J.meta.skillNames]}:{}};return Object.keys(Z).length>0?Z:void 0}function KJ3(J){return{name:J.name,description:J.description??"",inputSchema:{type:"object",properties:J.inputSchema.properties??{},required:J.inputSchema.required,additionalProperties:J.inputSchema.additionalProperties},source:J.source,meta:XJ3(J)}}function Hv(J){return J.map((Z)=>KJ3(Z.spec))}function ZI4(J,Z){let Q=$I4(J),Y=$I4(Z);return{toolsToRegister:Z.filter((X)=>{let K=Q.get(X.name),V=Y.get(X.name);return K?.serializedSchema!==V?.serializedSchema}),toolNamesToUnregister:[...Q.keys()].filter((X)=>!Y.has(X))}}function QI4(J,Z=JI4){return Wv(J,Z,(Q)=>({type:"executor_tools_register",tools:Q}))}function YI4(J,Z=JI4){return Wv(J,Z,(Q)=>({type:"executor_tools_unregister",toolNames:Q}))}import{execFile as VJ3}from"node:child_process";import{readFile as GJ3,stat as FJ3}from"node:fs/promises";import{basename as zJ3,join as qJ3}from"node:path";import zI4 from"node:process";import{promisify as WJ3}from"node:util";async function XI4(J,Z,Q){let Y=[];for(let X=0;X<J.length;X+=Z){let K=J.slice(X,X+Z);Y.push(...await Promise.all(K.map(Q)))}return Y}var HJ3=WJ3(VJ3),Dv=20971520,UJ3=["GIT_CONFIG","GIT_CONFIG_COUNT","GIT_CONFIG_PARAMETERS"],SY0=["-c","core.quotepath=false","diff","--no-color","--no-ext-diff"],DJ3=999999,KI4="refs/remotes/origin/",BJ3=20,NJ3=10;function kY0(J){return J.replace(/\n+$/,"")}var Ea0=zI4.platform==="win32"?"NUL":"/dev/null";function wJ3(J=zI4.env,Z={}){let{isolateGitConfig:Q=!0}=Z,Y={...J};if(Q){for(let X of Object.keys(Y))if(UJ3.includes(X)||X.startsWith("GIT_CONFIG_KEY_")||X.startsWith("GIT_CONFIG_VALUE_"))delete Y[X];Y.GIT_CONFIG_NOSYSTEM="1",Y.GIT_CONFIG_SYSTEM=Ea0,Y.GIT_CONFIG_GLOBAL=Ea0}return Y}function VI4(J,Z){return{provider:"git",capturedAt:J,available:!1,repositoryRoot:null,repositoryName:null,branch:null,head:null,files:[],unavailableReason:Z}}function LJ3(J){return J instanceof Error}async function Uv(J,Z,Q={}){try{let{stdout:Y}=await HJ3("git",Z,{cwd:J,env:wJ3(),maxBuffer:Q.maxBufferBytes??Dv});return Y}catch(Y){if(Q?.allowExitCodeOne&&LJ3(Y)&&(Y.code===1||Y.code==="1")&&typeof Y.stdout==="string")return Y.stdout;throw Y}}async function AU(J,Z){try{return await Uv(J,Z)}catch{return null}}function OJ3(J){if(J==="??")return"untracked";let Z=J[0]??" ",Q=J[1]??" ";if(Z==="U"||Q==="U"||J==="AA"||J==="DD")return"unmerged";if(Z==="R"||Q==="R")return"renamed";if(Z==="C"||Q==="C")return"copied";if(Z==="A"||Q==="A")return"added";if(Z==="D"||Q==="D")return"deleted";if(Z==="T"||Q==="T")return"type_changed";return"modified"}function Ma0(J){let Z=[],Q=J.split("\x00");for(let Y=0;Y<Q.length;Y++){let X=Q[Y];if(!X||X.length<4)continue;let K=X.slice(0,2),V=X.slice(3);if(!V)continue;let G=OJ3(K);if(G==="renamed"||G==="copied"){let F=Q[Y+1];if(F){Z.push({path:V,previousPath:F,changeType:G}),Y+=1;continue}}Z.push({path:V,changeType:G})}return Z.sort((Y,X)=>Y.path.localeCompare(X.path))}function EJ3(J){let Z=0,Q=0,Y=0,X=0,K=0,V=()=>{if(X===0&&K===0)return;Y+=Math.min(X,K),X=0,K=0};for(let G of J.split(`
|
|
6089
6089
|
`)){if(G.startsWith("+")&&!G.startsWith("+++")){Z+=1,X+=1;continue}if(G.startsWith("-")&&!G.startsWith("---")){Q+=1,K+=1;continue}V()}return V(),{added:Z,deleted:Q,changed:Y}}async function GI4(J,Z,Q,Y,X=Dv){let K=Y!==void 0?[`--unified=${Y}`]:[];if(Q)return Uv(J,[...SY0,...K,"HEAD","--",Z],{maxBufferBytes:X});let[V,G]=await Promise.all([Uv(J,[...SY0,...K,"--cached","--",Z],{maxBufferBytes:X}).catch(()=>""),Uv(J,[...SY0,...K,"--",Z],{maxBufferBytes:X}).catch(()=>"")]);return[kY0(V),kY0(G)].filter(Boolean).join(`
|
|
6090
6090
|
`)}async function MJ3(J,Z,Q=Dv){return Uv(J,[...SY0,"--no-index","--",Ea0,Z],{allowExitCodeOne:!0,maxBufferBytes:Q})}async function AJ3(J,Z,Q,Y=Dv){let X=Q??"HEAD";try{return await Uv(J,["show",`${X}:${Z}`],{maxBufferBytes:Y})}catch{return}}async function jJ3(J,Z,Q=Dv){try{let Y=qJ3(J,Z);if((await FJ3(Y)).size>Q)return;return await GJ3(Y,"utf-8")}catch{return}}function FI4(J){let Z=Number.parseInt(J.trim(),10);if(!Number.isFinite(Z))return null;return Z}async function RJ3(J){let Z=(await AU(J,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]))?.trim();if(!Z?.startsWith(KI4))return null;let Q=Z.slice(KI4.length);if(!Q)return null;let Y=`origin/${Q}`,K=(await AU(J,["rev-parse","--verify","--quiet",`${Y}^{commit}`]))?.trim();if(!K)return null;return{baseRef:Q,comparisonRef:Y,baseRefHead:K}}function IJ3(J){let Z=J.split("\x00"),Q=[];for(let Y=0;Y+1<Z.length;Y+=2){let X=Z[Y],K=Z[Y+1]??"";if(!X)continue;Q.push({hash:X,shortHash:X.slice(0,12),subject:K})}return Q}async function PJ3(J,Z){let Q=await AU(J,["log","-z",`--max-count=${BJ3}`,"--format=%H%x00%s",`${Z}..HEAD`]);if(!Q)return[];return IJ3(Q)}async function CJ3(J,Z){if(!Z)return null;let Q=await RJ3(J);if(!Q)return null;let Y=await AU(J,["rev-list","--count",`${Q.comparisonRef}..HEAD`]);if(!Y)return null;let X=await AU(J,["rev-list","--count",`HEAD..${Q.comparisonRef}`]);if(!X)return null;let K=FI4(Y);if(K===null)return null;let V=FI4(X);if(V===null)return null;return{baseRef:Q.baseRef,comparisonRef:Q.comparisonRef,baseRefHead:Q.baseRefHead,aheadCount:K,behindCount:V}}async function vY0(J,Z={}){let{maxDiffBufferBytes:Q=Dv}=Z,Y=Date.now(),X=await AU(J,["rev-parse","--show-toplevel"]);if(!X)return VI4(Y,"not a git repository");let K=X.trim(),V=zJ3(K),[G,F,z]=await Promise.all([AU(K,["rev-parse","--verify","HEAD"]),AU(K,["symbolic-ref","--short","HEAD"]),AU(K,["status","--porcelain=v1","--untracked-files=all","-z"])]);if(z===null)return VI4(Y,"failed to read git status");let q=G?.trim()||null,W=F?.trim()||null,H=Ma0(z),U=await CJ3(K,q),D=U?.aheadCount&&U.aheadCount>0?await PJ3(K,U.comparisonRef):[],B=await XI4(H,NJ3,async(N)=>{let w=kY0(N.changeType==="untracked"?await MJ3(K,N.path,Q).catch(()=>""):await GI4(K,N.path,q,void 0,Q).catch(()=>"")),L=kY0(N.changeType==="modified"?await GI4(K,N.path,q,DJ3,Q).catch(()=>""):w),O=N.changeType!=="added"&&N.changeType!=="untracked"?await AJ3(K,N.previousPath??N.path,q,Q):void 0,E=N.changeType!=="deleted"?await jJ3(K,N.path,Q):void 0;return{path:N.path,previousPath:N.previousPath,changeType:N.changeType,created:N.changeType==="added"||N.changeType==="untracked",diff:w,fullFileDiff:L,oldContent:O,newContent:E,diffStat:EJ3(w)}});return{provider:"git",capturedAt:Y,available:!0,repositoryRoot:K,repositoryName:V,branch:W,head:q,baseRef:U?.baseRef??null,baseRefHead:U?.baseRefHead??null,aheadCount:U?.aheadCount??0,behindCount:U?.behindCount,aheadCommits:D,files:B}}function Aa0(J){let Z={provider:J.provider,capturedAt:J.capturedAt,available:J.available,repositoryRoot:J.repositoryRoot,repositoryName:J.repositoryName,branch:J.branch,head:J.head,baseRef:J.baseRef??null,baseRefHead:J.baseRefHead??null,aheadCount:J.aheadCount??0,behindCount:J.behindCount,...J.unavailableReason!==void 0?{unavailableReason:J.unavailableReason}:{},aheadCommits:J.aheadCommits??[],files:J.files.map((Y)=>({path:Y.path,previousPath:Y.previousPath,changeType:Y.changeType,created:Y.created,diff:Y.diff,fullFileDiff:Y.fullFileDiff,oldContent:Y.oldContent,newContent:Y.newContent,diffStat:Y.diffStat}))},Q=Buffer.from(JSON.stringify(Z),"utf8").toString("base64");return{key:k$0,dataType:"application/json",contentBase64:Q}}var qI4=1048576;function WI4(J,Z,Q,Y=qI4){return Wv(J,Y,(X)=>({type:"executor_guidance_snapshot",snapshotId:Z,files:X,isLast:!1,userConfigDir:Q}))}function yY0(J,Z,Q=qI4){return Wv(J,Q,(Y)=>({type:"executor_guidance_discovery",toolCallId:Z,files:Y,isLast:!1}))}var Bv={baseDelayMs:1000,maxDelayMs:30000,maxAttempts:5};function xY0(J,Z){if(J>=Z.maxAttempts)return null;let Q=Math.max(1,J);return Math.min(Z.baseDelayMs*2**(Q-1),Z.maxDelayMs)}function _J3(){let J=()=>{return},Z=()=>{return};return{promise:new Promise((Y,X)=>{J=Y,Z=X}),resolve:J,reject:Z}}function TJ3(J){if(J==="darwin")return"darwin";if(J==="win32")return"windows";return"linux"}async function SJ3(J){let Z=await J.getLatest();return Tj0(Z.settings)}function HI4(J){let Z=J.previouslyAdvertisedTools??[],{toolsToRegister:Q,toolNamesToUnregister:Y}=ZI4(Z,J.nextTools),X=J.forceRegisterAll?[...J.nextTools]:Q;for(let K of QI4(X))J.logMessage?.("SEND",{type:"executor_tools_register",tools:K.map((V)=>V.name)}),J.transport.registerTools(K);for(let K of YI4(Y))J.logMessage?.("SEND",{type:"executor_tools_unregister",toolNames:K}),J.transport.unregisterTools(K);return[...J.nextTools]}async function kJ3(J){let{transport:Z,threadId:Q,configService:Y,skillService:X,logMessage:K}=J,V=J.fileSystem??I8,F={settings:await SJ3(Y),workspaceId:J.workspaceRoot,workingDirectory:J.workspaceRoot,environment:{os:TJ3(process.platform)},tags:[]};K?.("SEND",{type:"executor_connect",clientId:J.executorClientID,capabilities:F,executorType:J.executorType});let z=await Z.executorHandshake(J.executorClientID,F,{executorType:J.executorType});K?.("RECV",z);try{let q=await eR4(Q);K?.("SEND",{type:"executor_environment_snapshot",environment:q}),Z.sendEnvironmentSnapshot(q);let H={trees:q.workspaceRoot?[{uri:q.workspaceRoot}]:[],platform:q.platform,tags:q.tags};await yJ3(Z,V,Y,H,K),await xJ3(Z,X,K),await J.initialToolDiscovery;let U=await I1(J.toolService.tools),D=Hv(U),B=HI4({transport:Z,nextTools:D,previouslyAdvertisedTools:J.previouslyAdvertisedTools,forceRegisterAll:!0,logMessage:K});if(J.sendGitSnapshot!==!1)try{let N=await vY0(J.workspaceRoot);K?.("SEND",{type:"executor_artifact_upsert",available:N.available,fileCount:N.files.length,branch:N.branch,head:N.head}),Z.sendExecutorArtifactUpsert(Aa0(N))}catch{}return K?.("SEND",{type:"executor_tools_bootstrap_complete",ok:!0}),Z.sendExecutorToolsBootstrapComplete(!0),{advertisedTools:B}}catch(q){let W=q instanceof Error?q.message:String(q);throw K?.("SEND",{type:"executor_tools_bootstrap_complete",ok:!1,error:W}),Z.sendExecutorToolsBootstrapComplete(!1,W),q}}function vJ3(J,Z,Q){let Y=Tj0(Z.settings),X=JSON.stringify(Y);if(X===Q)return Q;let K=J.getConnectionInfo();if(K.state!=="connected"||K.role!=="executor")return Q;try{return J.sendExecutorSettingsUpdate(Y),X}catch{return Q}}async function yJ3(J,Z,Q,Y,X){let V=(await Wz({filesystem:Z,configService:Q,threadService:{observe:()=>k0.of({id:h8(),created:Date.now(),v:0,messages:[],env:{initial:Y}})}},{messages:[],env:{initial:Y}})).map((q)=>({uri:q.uri,content:q.content,lineCount:q.content.split(`
|
|
6091
|
-
`).length})),G=crypto.randomUUID(),F=Q.userConfigDir?o1(Q.userConfigDir):void 0;if(V.length===0){X?.("SEND",{type:"executor_guidance_snapshot",snapshotId:G,fileCount:0,isLast:!0}),J.sendExecutorGuidanceSnapshot({snapshotId:G,files:[],isLast:!0,userConfigDir:F});return}let z=WI4(V,G,F);for(let q=0;q<z.length;q++){let W=z[q];if(!W)continue;let H=q===z.length-1;X?.("SEND",{type:"executor_guidance_snapshot",snapshotId:G,fileCount:W.length,isLast:H}),J.sendExecutorGuidanceSnapshot({snapshotId:G,files:W,isLast:H,userConfigDir:F})}}async function xJ3(J,Z,Q){let Y=await Z.getSkills(),X=crypto.randomUUID(),K=20,V=Y.map((G)=>({name:G.name,description:G.description,baseDir:G.baseDir,frontmatter:G.frontmatter,files:G.files}));if(V.length===0){Q?.("SEND",{type:"executor_skill_snapshot",snapshotId:X,skillCount:0,isLast:!0}),J.sendExecutorSkillSnapshot({snapshotId:X,skills:[],isLast:!0});return}for(let G=0;G<V.length;G+=20){let F=V.slice(G,G+20),z=G+20>=V.length;Q?.("SEND",{type:"executor_skill_snapshot",snapshotId:X,skillCount:F.length,isLast:z}),J.sendExecutorSkillSnapshot({snapshotId:X,skills:F,isLast:z})}}class UI4{options;inFlight=null;readyWaiter=null;retryTimer=null;attempt=0;generation=0;lastInfo=null;disposed=!1;baseDelayMs;maxDelayMs;maxAttempts;constructor(J){this.options=J;this.baseDelayMs=J.baseDelayMs??Bv.baseDelayMs,this.maxDelayMs=J.maxDelayMs??Bv.maxDelayMs,this.maxAttempts=J.maxAttempts??Bv.maxAttempts}ensureHandshake(J){return this.tryHandshake(J)}ensureReady(J){if(this.disposed)return Promise.reject(Error("Executor handshake manager is disposed"));if(this.isReady())return Promise.resolve();if(!this.readyWaiter)this.readyWaiter=_J3();this.tryHandshake("connect");let Z=this.readyWaiter.promise;if(!J?.timeoutMs)return Z;let Q=J.timeoutMessage??`Timed out waiting for handshake after ${J.timeoutMs}ms`;return this.withTimeout(Z,J.timeoutMs,Q)}handleConnectionChange(J){if(this.lastInfo=J,J.state!=="connected"){this.reset("disconnected");return}if(J.role==="executor"){this.reset("executor"),this.resolveReadyWaiter();return}this.tryHandshake("connect")}dispose(){this.disposed=!0,this.generation++,this.clearRetryTimer(),this.rejectReadyWaiter(Error("Executor handshake manager is disposed"))}isReady(){return this.lastInfo?.state==="connected"&&this.lastInfo.role==="executor"}resolveReadyWaiter(){let J=this.readyWaiter;if(!J)return;this.readyWaiter=null,J.resolve()}rejectReadyWaiter(J){let Z=this.readyWaiter;if(!Z)return;this.readyWaiter=null,Z.reject(J)}reset(J){this.generation++,this.attempt=0,this.clearRetryTimer()}clearRetryTimer(){if(!this.retryTimer)return;clearTimeout(this.retryTimer),this.retryTimer=null}async withTimeout(J,Z,Q){let Y=null;try{return await Promise.race([J,new Promise((X,K)=>{Y=setTimeout(()=>{K(Error(Q))},Z)})])}finally{if(Y)clearTimeout(Y)}}tryHandshake(J){if(this.disposed||this.inFlight)return this.inFlight;let Z=this.generation,Q=this.options.handshake(J);return this.inFlight=Q,Q.then(()=>{if(this.disposed||Z!==this.generation)return;this.attempt=0,this.clearRetryTimer(),this.resolveReadyWaiter()}).catch((Y)=>{if(this.disposed||Z!==this.generation)return;this.scheduleRetry(J,Y)}).finally(()=>{if(this.inFlight===Q)this.inFlight=null}),Q}scheduleRetry(J,Z){if(this.disposed)return;if(!this.lastInfo||this.lastInfo.state!=="connected"||this.lastInfo.role==="executor")return;this.attempt+=1;let Q=xY0(this.attempt,{baseDelayMs:this.baseDelayMs,maxDelayMs:this.maxDelayMs,maxAttempts:this.maxAttempts});if(Q===null){this.clearRetryTimer(),this.options.onExhausted?.({attempt:this.attempt,maxAttempts:this.maxAttempts,error:Z}),this.rejectReadyWaiter(Z instanceof Error?Z:Error("Executor handshake failed and exhausted retries"));return}this.clearRetryTimer(),this.options.onError?.({trigger:J,attempt:this.attempt,delayMs:Q,error:Z}),this.retryTimer=setTimeout(()=>{if(this.retryTimer=null,!this.lastInfo||this.lastInfo.state!=="connected"||this.lastInfo.role==="executor")return;this.tryHandshake("retry")},Q)}}class DI4{options;clientID;transport;sentApprovalRequests=new Set;discoveredGuidanceFileURIs=new Set;activeTools=new Map;pendingTerminalResults=new Map;gitStatusQueue={inFlight:!1,queued:!1,queuedToolCallId:void 0};disposing=!1;constructor(J){this.options=J;this.clientID=J.clientID,this.transport=J.transport}async handleToolLease(J){if(this.disposing)return;let{toolCallId:Z,toolName:Q}=J;if(this.activeTools.has(Z)){this.options.log.info(`${this.clientID} ignoring duplicate active lease`,{toolCallId:Z,toolName:Q});return}let Y=this.pendingTerminalResults.get(Z);if(Y){this.options.log.info(`${this.clientID} replaying pending terminal result for duplicate lease`,{toolCallId:Z,toolName:Q}),this.sendTerminalResult(Z,Y,"flush");return}let X=Date.now();this.options.log.info(`${this.clientID} executing tool: ${Q}`,{toolCallId:Z}),this.options.log.wsMessage("SEND",this.clientID,{type:"executor_tool_lease_ack",toolCallId:Z}),this.transport.ackToolLease(Z);let K=new AbortController,V={subscription:{unsubscribe:()=>{}},abortController:K};this.activeTools.set(Z,V);let G=()=>{this.activeTools.delete(Z)};try{let F=await this.options.invokeTool(J);this.options.log.info(`${this.clientID} tool service returned observable`,{toolCallId:Z,toolName:Q,elapsedMs:Date.now()-X});let z=F.subscribe({next:(q)=>{if(K.signal.aborted)return;let W=q.status==="in-progress"?q.progress??q.result:void 0;if(W!==void 0)this.options.log.wsMessage("SEND",this.clientID,{type:"tool_progress",toolCallId:Z,progress:W}),this.sendTransportMessage("tool_progress",()=>this.transport.sendToolProgress(Z,W),{toolCallId:Z});if(g8(q.status))this.sendToolResult(Z,q),G(),z.unsubscribe();if(q.status==="blocked-on-user")this.options.log.info(`${this.clientID} awaiting tool approval`,{toolCallId:Z,toolName:Q})},error:(q)=>{if(K.signal.aborted){G();return}this.options.log.error(`${this.clientID} tool execution failed: ${Q}`,q);let W={status:"error",error:{message:q instanceof Error?q.message:"Unknown error"}};this.sendToolResult(Z,W),G()}});V.subscription=z}catch(F){this.options.log.error(`${this.clientID} tool execution setup failed: ${Q}`,F);let z={status:"error",error:{message:F instanceof Error?F.message:String(F)}};this.sendToolResult(Z,z),G()}}flushBufferedTerminalResults(){if(this.disposing||this.pendingTerminalResults.size===0)return;for(let[J,Z]of this.pendingTerminalResults)this.sendTerminalResult(J,Z,"flush")}handleToolRevocation(J){if(this.disposing)return;let{toolCallId:Z,reason:Q}=J;this.options.log.info(`${this.clientID} lease revoked: ${Z}`,{reason:Q});let Y=this.activeTools.get(Z);if(Y)Y.abortController.abort(),Y.subscription.unsubscribe(),this.activeTools.delete(Z);this.sentApprovalRequests.delete(Z)}async handleRollbackRequest(J,Z,Q){if(this.disposing)return;try{if(Z.length>0)await Q(new Set(Z));this.options.log.wsMessage("SEND",this.clientID,{type:"executor_rollback_ack",editId:J,ok:!0}),this.sendTransportMessage("executor_rollback_ack",()=>this.transport.sendExecutorRollbackAck(J,!0),{editId:J}),this.queueGitStatusSnapshot()}catch(Y){let X=Y instanceof Error?Y.message:String(Y);this.options.log.error(`${this.clientID} rollback failed`,Y),this.options.log.wsMessage("SEND",this.clientID,{type:"executor_rollback_ack",editId:J,ok:!1,error:X}),this.sendTransportMessage("executor_rollback_ack",()=>this.transport.sendExecutorRollbackAck(J,!1,X),{editId:J})}}triggerGitStatus(J){this.queueGitStatusSnapshot(J)}dispose(){this.disposing=!0;for(let[,J]of this.activeTools)J.abortController.abort(),J.subscription.unsubscribe();this.activeTools.clear(),this.pendingTerminalResults.clear()}sendToolResult(J,Z){let Q=Date.now(),Y=this.toToolRun(Z),{run:X,files:K}=this.extractGuidanceFromRun(Y);if(K.length>0)this.sendGuidanceDiscovery(J,K);this.sendTerminalResult(J,X,"live",{guidanceFileCount:K.length,elapsedMs:Date.now()-Q}),this.sentApprovalRequests.delete(J),this.queueGitStatusSnapshot(J)}sendTerminalResult(J,Z,Q,Y){this.options.log.wsMessage("SEND",this.clientID,{type:"executor_tool_result",toolCallId:J,run:Z});let X=this.sendTransportMessage("executor_tool_result",()=>this.transport.sendExecutorToolResult(J,Z),{toolCallId:J,source:Q});if(X)this.pendingTerminalResults.delete(J);else this.pendingTerminalResults.set(J,Z);return this.options.log.info(`${this.clientID} executor_tool_result send attempted`,{toolCallId:J,status:Z.status,sent:X,source:Q,...Y}),X}sendGuidanceDiscovery(J,Z){let Q=this.options.batchGuidanceFiles(Z,J);for(let Y=0;Y<Q.length;Y++){let X=Q[Y];if(!X)continue;let K=Y===Q.length-1;if(this.options.log.wsMessage("SEND",this.clientID,{type:"executor_guidance_discovery",toolCallId:J,fileCount:X.length,isLast:K}),!this.sendTransportMessage("executor_guidance_discovery",()=>this.transport.sendExecutorGuidanceDiscovery({toolCallId:J,files:X,isLast:K}),{toolCallId:J,isLast:K,fileCount:X.length}))return}}queueGitStatusSnapshot(J){if(this.disposing||!this.options.captureGitStatus)return;if(this.gitStatusQueue.inFlight){if(this.gitStatusQueue.queued=!0,J)this.gitStatusQueue.queuedToolCallId=J;return}this.gitStatusQueue.inFlight=!0,this.sendGitStatusSnapshot(J).finally(()=>{if(this.gitStatusQueue.inFlight=!1,!this.gitStatusQueue.queued)return;let Z=this.gitStatusQueue.queuedToolCallId;this.gitStatusQueue.queued=!1,this.gitStatusQueue.queuedToolCallId=void 0,this.queueGitStatusSnapshot(Z)})}async sendGitStatusSnapshot(J){try{if(!this.options.captureGitStatus)return;let Z=await this.options.captureGitStatus();this.options.log.wsMessage("SEND",this.clientID,{type:"executor_artifact_upsert",available:Z.available,fileCount:Z.files.length,toolCallId:J,branch:Z.branch,head:Z.head}),this.transport.sendExecutorArtifactUpsert(Aa0(Z),J)}catch(Z){this.options.log.error("Failed to send git status snapshot",Z)}}toToolRun(J){switch(J.status){case"done":return{status:"done",result:J.result,progress:J.progress,trackFiles:J.trackFiles?[...J.trackFiles]:void 0};case"error":return{status:"error",error:{message:J.error?this.options.renderToolRunError(J.error):"Tool execution failed"}};case"rejected-by-user":return{status:"rejected-by-user",reason:J.reason};case"cancelled":return{status:"cancelled",reason:J.reason};default:return{status:"error",error:{message:`Unexpected status: ${J.status}`}}}}extractGuidanceFromRun(J){if(J.status!=="done")return{run:J,files:[]};if(!J.result||typeof J.result!=="object"||Array.isArray(J.result))return{run:J,files:[]};let Z=J.result;if(!("discoveredGuidanceFiles"in Z))return{run:J,files:[]};let Q=ej4(Z.discoveredGuidanceFiles),{discoveredGuidanceFiles:Y,...X}=Z;return{run:{...J,result:X},files:Q}}sendTransportMessage(J,Z,Q){try{return Z(),!0}catch(Y){if(Y instanceof v8)return this.options.log.info(`${this.clientID} dropped ${J} while reconnecting`,{messageType:J,...Q}),this.options.onTransportSendFailure?.(this.clientID,J,Y,Q),!1;return this.options.log.error(`${this.clientID} failed to send ${J}`,Y),!1}}}class kj{options;toolRunner;sentApprovalRequests;discoveredGuidanceFileURIs;handshakeManager;runtimeLog;advertisedExecutorTools=[];lastSentSettingsJSON="";settingsSubscription=null;eventSubscriptions=[];executorCallbacksAttached=!1;constructor(J){this.options=J;this.runtimeLog=this.options.log??{info:(Q,Y)=>_.info(`[executor-client] ${Q}`,Y),error:(Q,Y)=>_.error(`[executor-client] ${Q}`,{error:Y}),wsMessage:(Q,Y,X)=>{_.info("[executor-client] websocket message",{direction:Q,clientID:Y,...typeof X==="object"&&X!==null?X:{message:X}})}};let Z=async()=>{_.info("[executor-client] executor handshake requested",{clientID:this.options.clientID})};this.handshakeManager=new UI4({handshake:this.options.handshake??Z,...this.options.handshakeManagerOptions}),this.toolRunner=new DI4({clientID:this.options.clientID,transport:this.options.transport,log:this.runtimeLog,invokeTool:(Q)=>this.invokeTool(Q),captureGitStatus:this.options.captureGitStatus,batchGuidanceFiles:this.options.batchGuidanceFiles??((Q)=>[Q]),renderToolRunError:this.options.renderToolRunError??((Q)=>Q?.message??"Tool run failed"),onTransportSendFailure:this.options.onTransportSendFailure}),this.sentApprovalRequests=this.toolRunner.sentApprovalRequests,this.discoveredGuidanceFileURIs=this.toolRunner.discoveredGuidanceFileURIs}async connect(J){await this.bootstrapExecutor({executorType:J,trigger:"connect"}),this.listenToExecutorEvents(this.options.transport)}ensureHandshake(J){return this.handshakeManager.ensureHandshake(J)}ensureReady(J){return this.handshakeManager.ensureReady(J)}async bootstrapExecutor(J){await this.connectAsExecutor(J.executorType,J.workspaceRoot??this.options.workspaceRoot??"",J.threadID??this.options.threadID,J.trigger,J.suppressConnectLog)}syncExecutorToolRegistrations(J,Z){let Q=this.options.transport.getConnectionInfo();if(Q.state!=="connected"||Q.role!=="executor")return;this.advertisedExecutorTools=HI4({transport:this.options.transport,nextTools:J,previouslyAdvertisedTools:this.advertisedExecutorTools,logMessage:Z?.logMessage})}handleConnectionChange(J){this.handshakeManager.handleConnectionChange(J)}attachTransportExecutorCallbacks(J){let Z=J?.includeConnectionChanges??!1,Q={onToolLease:(Y)=>{this.handleToolLease(Y)},onToolLeaseRevoked:(Y)=>{this.handleToolLeaseRevoked(Y)}};if(Z)Q.onConnectionChange=(Y)=>{this.handshakeManager.handleConnectionChange(Y)};if(this.shouldHandleRollbackRequests())Q.onExecutorRollbackRequest=(Y)=>{this.handleExecutorRollbackRequest(Y)};if(this.shouldHandleFileSystemReadDirectoryRequests())Q.onFileSystemReadDirectoryRequest=(Y)=>{this.handleExecutorFileSystemReadDirectoryRequest(Y)};Q.onFileSystemReadFileRequest=(Y)=>{this.handleExecutorFileSystemReadFileRequest(Y)},this.options.transport.setExecutorCallbacks(Q),this.executorCallbacksAttached=!0}clearTransportExecutorCallbacks(){if(!this.executorCallbacksAttached)return;this.options.transport.setExecutorCallbacks(null),this.executorCallbacksAttached=!1}dispose(){this.clearTransportExecutorCallbacks();for(let J of this.eventSubscriptions)J.unsubscribe();this.eventSubscriptions=[],this.toolRunner.dispose(),this.handshakeManager.dispose(),this.settingsSubscription?.unsubscribe(),this.settingsSubscription=null}async invokeTool(J){if(this.options.invokeTool)return await this.options.invokeTool(J);if(!this.options.getEnvironment)throw Error("Executor runtime requires getEnvironment or invokeTool");let{toolCallId:Z,toolName:Q,args:Y}=J,X=typeof Y==="object"&&Y!==null?Y:{},K=await this.options.getEnvironment();return K.thread={...K.thread,id:this.options.threadID},K.toolUseID=Z,this.options.toolService.invokeTool(Q,{args:X},K)}async connectAsExecutor(J,Z,Q,Y,X=!1){if(this.settingsSubscription?.unsubscribe(),this.settingsSubscription=null,!X)_.info(`Connecting ${this.options.clientID} as executor...`);try{let{advertisedTools:K}=await kJ3({transport:this.options.transport,executorClientID:this.options.executorClientID??this.options.clientID,workspaceRoot:Z,threadId:Q,configService:this.options.configService,toolService:this.options.toolService,skillService:this.options.skillService,fileSystem:this.options.fileSystem,logMessage:this.options.bootstrapLogMessage,executorType:J,initialToolDiscovery:this.options.initialToolDiscovery,sendGitSnapshot:this.options.sendGitSnapshot??!1,previouslyAdvertisedTools:this.advertisedExecutorTools});if(this.advertisedExecutorTools=K,this.toolRunner.flushBufferedTerminalResults(),this.options.onBootstrapSuccess)await this.options.onBootstrapSuccess(Y);this.startSettingsSync()}catch(K){throw _.error(`executor ${this.options.clientID} bootstrap failed`,K),K}}startSettingsSync(){if(this.settingsSubscription)return;this.settingsSubscription=this.options.configService.config.subscribe({next:(J)=>{this.lastSentSettingsJSON=vJ3(this.options.transport,J,this.lastSentSettingsJSON)}})}listenToExecutorEvents(J){if(this.eventSubscriptions.length>0)return;if(this.eventSubscriptions.push(J.connectionChanges().subscribe({next:(Z)=>{this.handleConnectionChange(Z)}}),J.toolLeases().subscribe({next:(Z)=>{this.handleToolLease(Z)}}),J.toolLeaseRevoked().subscribe({next:(Z)=>{this.handleToolLeaseRevoked(Z)}})),this.options.autoResolvePendingApprovals!==!1)this.eventSubscriptions.push(this.options.toolService.pendingApprovals$.subscribe({next:(Z)=>{this.handlePendingApprovals(Z)}}));if(this.shouldHandleRollbackRequests())this.eventSubscriptions.push(J.executorRollbackRequests().subscribe({next:(Z)=>{this.handleExecutorRollbackRequest(Z)}}));if(this.shouldHandleFileSystemReadDirectoryRequests())this.eventSubscriptions.push(J.fileSystemReadDirectoryRequests().subscribe({next:(Z)=>{this.handleExecutorFileSystemReadDirectoryRequest(Z)}}));this.eventSubscriptions.push(J.fileSystemReadFileRequests().subscribe({next:(Z)=>{this.handleExecutorFileSystemReadFileRequest(Z)}}))}shouldHandleRollbackRequests(){return typeof this.options.handleExecutorRollbackRequest==="function"}shouldHandleFileSystemReadDirectoryRequests(){return typeof this.options.handleExecutorFileSystemReadDirectoryRequest==="function"||typeof this.options.readFileSystemDirectory==="function"}maybeLogInboundExecutorMessage(J){if(!this.options.logInboundExecutorMessages)return;this.runtimeLog.wsMessage("RECV",this.options.clientID,J)}handleToolLease(J){this.maybeLogInboundExecutorMessage(J),this.toolRunner.handleToolLease(J)}handleToolLeaseRevoked(J){this.maybeLogInboundExecutorMessage(J),this.toolRunner.handleToolRevocation(J)}handlePendingApprovals(J){for(let Z of J)this.options.toolService.resolveApproval(Z.toolUseId,!0)}handleExecutorRollbackRequest(J){if(this.maybeLogInboundExecutorMessage(J),!this.options.handleExecutorRollbackRequest)return;this.options.handleExecutorRollbackRequest(J)}async handleExecutorFileSystemReadDirectoryRequest(J){if(this.maybeLogInboundExecutorMessage(J),this.options.handleExecutorFileSystemReadDirectoryRequest){await this.options.handleExecutorFileSystemReadDirectoryRequest(J);return}if(!this.options.readFileSystemDirectory)throw Error("Method not implemented.");let Z=await this.options.readFileSystemDirectory(J);this.options.transport.sendExecutorFileSystemReadDirectoryResult(J.requestId,Z)}handleExecutorFileSystemReadFileRequest(J){if(this.maybeLogInboundExecutorMessage(J),this.options.handleExecutorFileSystemReadFileRequest){this.options.handleExecutorFileSystemReadFileRequest(J);return}throw Error("Method not implemented.")}}n0();function fY0(J){return{async createHandoffDraft(Z){let Q=await NI4(J,Z.signal);return BI4(Q,Z.parentThread.id,Z.goal,Z.images)},createHandoffThread:async(Z)=>{let Q=await NI4(J,Z.signal),Y=await BI4(Q,Z.parentThread.id,Z.goal,Z.images),X=await hJ3(Q,Z,Y);if(await bJ3(X.http,X.threadID,X.prompt,X.agentMode),Z.follow&&J.onFollow)try{await J.onFollow({sourceThreadID:Z.parentThread.id,targetThreadID:X.threadID})}catch(K){_.error("Failed to follow handoff thread",{error:K,sourceThreadID:Z.parentThread.id,targetThreadID:X.threadID})}return X.threadID}}}function fJ3(J){let Z=new Headers({"Content-Type":"application/json"});if(J)Z.set("Authorization",`Bearer ${J}`);return Z}async function ja0(J,Z,Q){return fetch(`${J.workerURL}${Z}`,{method:"POST",headers:fJ3(J.apiKey),body:JSON.stringify(Q),signal:J.signal})}async function BI4(J,Z,Q,Y){let X=await ja0(J,`/threads/${Z}/handoff`,{goal:Q,images:Y});if(!X.ok)throw Error(`Failed to generate handoff prompt: ${X.status} ${await X.text()}`);return await X.json()}async function uJ3(J,Z,Q,Y){let X=await ja0(J,"/threads",{...Z?{repositoryURL:Z}:{},...Q?{agentMode:Q}:{},relationship:Y});if(!X.ok)throw Error(`Failed to create handoff thread: ${X.status} ${await X.text()}`);let K=await X.json();if(!K.threadId)throw Error("Thread creation response missing threadId");return K.threadId}async function bJ3(J,Z,Q,Y){let X=await ja0(J,`/threads/${Z}/message`,{content:Q,...Y?{agentMode:Y}:{}});if(!X.ok)throw Error(`Failed to start handoff thread: ${X.status} ${await X.text()}`)}async function NI4(J,Z){let Q=await J.configService.getLatest(),Y=J.apiKey??await Q.secrets.getToken("apiKey",Q.settings.url),X=J.workerURL??process.env.AMP_WORKER_URL??l7(Q.settings.url);return{apiKey:Y,workerURL:X,signal:Z}}async function hJ3(J,Z,Q){let Y=Z.agentMode??Q.sourceAgentMode??Z.parentThread.agentMode,X=Z.relationshipMessageIndex??Q.parentMessageIndex,K=Z.relationshipComment??Z.goal,V={threadID:Q.parentThreadID,type:"handoff",...X!==void 0?{messageIndex:X}:{},...Z.relationshipBlockIndex!==void 0?{blockIndex:Z.relationshipBlockIndex}:{},comment:K},G=Z.parentThread.env?.initial?.trees?.[0]?.repository?.url,F=await uJ3(J,G,Y??void 0,V);return{http:J,threadID:F,prompt:Q.content,agentMode:Y??void 0}}cX();Lc();p_();Eg0();c4();U4();E1();async function uG(J){let{toolName:Z,dtwHandoffService:Q,dtwArtifactSyncService:Y,configService:X,toolService:K,mcpService:V,skillService:G,fsTracker:F,toolUseID:z,discoveredGuidanceFileURIs:q,threadID:W}=J,H={id:W??h8(),created:Date.now(),v:0,messages:[]},U=G1.file(process.cwd()),D=z??lF(),B=await X.getLatest(),N,w;if(F)N=F.trackedFileSystem(D),w=F.tracker;else w=S$0(kS0,H.id,async()=>{}),N=Mg0(I8,w,D);return{dir:U,tool:Z,thread:H,dtwHandoffService:Q,dtwArtifactSyncService:Y,trackedFiles:new QJ,toolUseID:D,todos:void 0,configService:X,toolService:K,mcpService:V,config:B,filesystem:N,fileChangeTracker:w,getAllTrackedChanges:async()=>w.getAllRecords(),threadEnvironment:{trees:[],platform:"cli"},handleThreadDelta:()=>Promise.resolve(),threadService:{observe:()=>k0.of(H),get:()=>Promise.resolve(H),getPrimitiveProperty:(L,O)=>Promise.resolve(H[O]),flushVersion:()=>Promise.resolve(),updateThreadMeta:()=>Promise.resolve()},getThreadEnvironment:()=>Promise.resolve({trees:[],platform:"cli"}),threadSummaryService:{summarizeThread:()=>Promise.resolve({summary:"CLI execution",prompt:"CLI execution",title:"CLI Tool"})},osFileSystem:I8,deleteThread:()=>Promise.resolve(),generateThreadTitle:()=>Promise.resolve({title:"CLI Tool Execution"}),fileChangeTrackerStorage:kS0,discoveredGuidanceFileURIs:q??new Set,skillService:G??{getSkills:()=>Promise.resolve([]),getTargetDir:()=>Promise.resolve("/tmp/skills"),listInstalled:()=>[],reload:()=>{}}}}function Ra0(){return new Date().toISOString()}var Ia0=process.stderr.isTTY,wI4=3000;function gJ3(J){let Z=J.trim();if(!(Z.startsWith("{")&&Z.endsWith("}")||Z.startsWith("[")&&Z.endsWith("]")))return null;try{return JSON.parse(Z)}catch{return null}}function Pa0(J){if(J instanceof Error)return J.stack??J.message;if(typeof J==="string"){let Z=gJ3(J);if(Z!==null)return JSON.stringify(Z,null,2);return J}if(J===void 0)return"";try{return JSON.stringify(J,null,2)}catch{return String(J)}}function A9(J,Z,Q){if(_.info("[headless-dtw] websocket message",{direction:J,clientId:Z,...typeof Q==="object"&&Q!==null?Q:{message:Q}}),!Ia0)return;let Y=g0.dim(`[${Ra0()}]`),X=g0.magenta(`[${Z}]`),K=J==="SEND"?g0.green(">>>"):g0.yellow("<<<"),V=Pa0(Q);process.stderr.write(`${Y} ${X} ${K} ${V}
|
|
6091
|
+
`).length})),G=crypto.randomUUID(),F=Q.userConfigDir?o1(Q.userConfigDir):void 0;if(V.length===0){X?.("SEND",{type:"executor_guidance_snapshot",snapshotId:G,fileCount:0,isLast:!0}),J.sendExecutorGuidanceSnapshot({snapshotId:G,files:[],isLast:!0,userConfigDir:F});return}let z=WI4(V,G,F);for(let q=0;q<z.length;q++){let W=z[q];if(!W)continue;let H=q===z.length-1;X?.("SEND",{type:"executor_guidance_snapshot",snapshotId:G,fileCount:W.length,isLast:H}),J.sendExecutorGuidanceSnapshot({snapshotId:G,files:W,isLast:H,userConfigDir:F})}}async function xJ3(J,Z,Q){let Y=await Z.getSkills(),X=crypto.randomUUID(),K=20,V=Y.map((G)=>({name:G.name,description:G.description,baseDir:G.baseDir,frontmatter:G.frontmatter,files:G.files}));if(V.length===0){Q?.("SEND",{type:"executor_skill_snapshot",snapshotId:X,skillCount:0,isLast:!0}),J.sendExecutorSkillSnapshot({snapshotId:X,skills:[],isLast:!0});return}for(let G=0;G<V.length;G+=20){let F=V.slice(G,G+20),z=G+20>=V.length;Q?.("SEND",{type:"executor_skill_snapshot",snapshotId:X,skillCount:F.length,isLast:z}),J.sendExecutorSkillSnapshot({snapshotId:X,skills:F,isLast:z})}}class UI4{options;inFlight=null;readyWaiter=null;retryTimer=null;attempt=0;generation=0;lastInfo=null;disposed=!1;baseDelayMs;maxDelayMs;maxAttempts;constructor(J){this.options=J;this.baseDelayMs=J.baseDelayMs??Bv.baseDelayMs,this.maxDelayMs=J.maxDelayMs??Bv.maxDelayMs,this.maxAttempts=J.maxAttempts??Bv.maxAttempts}ensureHandshake(J){return this.tryHandshake(J)}ensureReady(J){if(this.disposed)return Promise.reject(Error("Executor handshake manager is disposed"));if(this.isReady())return Promise.resolve();if(!this.readyWaiter)this.readyWaiter=_J3();this.tryHandshake("connect");let Z=this.readyWaiter.promise;if(!J?.timeoutMs)return Z;let Q=J.timeoutMessage??`Timed out waiting for handshake after ${J.timeoutMs}ms`;return this.withTimeout(Z,J.timeoutMs,Q)}handleConnectionChange(J){if(this.lastInfo=J,J.state!=="connected"){this.reset("disconnected");return}if(J.role==="executor"){this.reset("executor"),this.resolveReadyWaiter();return}this.tryHandshake("connect")}dispose(){this.disposed=!0,this.generation++,this.clearRetryTimer(),this.rejectReadyWaiter(Error("Executor handshake manager is disposed"))}isReady(){return this.lastInfo?.state==="connected"&&this.lastInfo.role==="executor"}resolveReadyWaiter(){let J=this.readyWaiter;if(!J)return;this.readyWaiter=null,J.resolve()}rejectReadyWaiter(J){let Z=this.readyWaiter;if(!Z)return;this.readyWaiter=null,Z.reject(J)}reset(J){this.generation++,this.attempt=0,this.clearRetryTimer()}clearRetryTimer(){if(!this.retryTimer)return;clearTimeout(this.retryTimer),this.retryTimer=null}async withTimeout(J,Z,Q){let Y=null;try{return await Promise.race([J,new Promise((X,K)=>{Y=setTimeout(()=>{K(Error(Q))},Z)})])}finally{if(Y)clearTimeout(Y)}}tryHandshake(J){if(this.disposed||this.inFlight)return this.inFlight;let Z=this.generation,Q=this.options.handshake(J);return this.inFlight=Q,Q.then(()=>{if(this.disposed||Z!==this.generation)return;this.attempt=0,this.clearRetryTimer(),this.resolveReadyWaiter()}).catch((Y)=>{if(this.disposed||Z!==this.generation)return;this.scheduleRetry(J,Y)}).finally(()=>{if(this.inFlight===Q)this.inFlight=null}),Q}scheduleRetry(J,Z){if(this.disposed)return;if(!this.lastInfo||this.lastInfo.state!=="connected"||this.lastInfo.role==="executor")return;this.attempt+=1;let Q=xY0(this.attempt,{baseDelayMs:this.baseDelayMs,maxDelayMs:this.maxDelayMs,maxAttempts:this.maxAttempts});if(Q===null){this.clearRetryTimer(),this.options.onExhausted?.({attempt:this.attempt,maxAttempts:this.maxAttempts,error:Z}),this.rejectReadyWaiter(Z instanceof Error?Z:Error("Executor handshake failed and exhausted retries"));return}this.clearRetryTimer(),this.options.onError?.({trigger:J,attempt:this.attempt,delayMs:Q,error:Z}),this.retryTimer=setTimeout(()=>{if(this.retryTimer=null,!this.lastInfo||this.lastInfo.state!=="connected"||this.lastInfo.role==="executor")return;this.tryHandshake("retry")},Q)}}class DI4{options;clientID;transport;sentApprovalRequests=new Set;discoveredGuidanceFileURIs=new Set;activeTools=new Map;pendingTerminalResults=new Map;gitStatusQueue={inFlight:!1,queued:!1,queuedToolCallId:void 0};disposing=!1;constructor(J){this.options=J;this.clientID=J.clientID,this.transport=J.transport}async handleToolLease(J){if(this.disposing)return;let{toolCallId:Z,toolName:Q}=J;if(this.activeTools.has(Z)){this.options.log.info(`${this.clientID} ignoring duplicate active lease`,{toolCallId:Z,toolName:Q});return}let Y=this.pendingTerminalResults.get(Z);if(Y){this.options.log.info(`${this.clientID} replaying pending terminal result for duplicate lease`,{toolCallId:Z,toolName:Q}),this.sendTerminalResult(Z,Y,"flush");return}let X=Date.now();this.options.log.info(`${this.clientID} executing tool: ${Q}`,{toolCallId:Z}),this.options.log.wsMessage("SEND",this.clientID,{type:"executor_tool_lease_ack",toolCallId:Z}),this.transport.ackToolLease(Z);let K=new AbortController,V={subscription:{unsubscribe:()=>{}},abortController:K};this.activeTools.set(Z,V);let G=()=>{this.activeTools.delete(Z)};try{let F=await this.options.invokeTool(J);this.options.log.info(`${this.clientID} tool service returned observable`,{toolCallId:Z,toolName:Q,elapsedMs:Date.now()-X});let z=F.subscribe({next:(q)=>{if(K.signal.aborted)return;let W=q.status==="in-progress"?q.progress??q.result:void 0;if(W!==void 0)this.options.log.wsMessage("SEND",this.clientID,{type:"tool_progress",toolCallId:Z,progress:W}),this.sendTransportMessage("tool_progress",()=>this.transport.sendToolProgress(Z,W),{toolCallId:Z});if(g8(q.status))this.sendToolResult(Z,q),G(),z.unsubscribe();if(q.status==="blocked-on-user")this.options.log.info(`${this.clientID} awaiting tool approval`,{toolCallId:Z,toolName:Q})},error:(q)=>{if(K.signal.aborted){G();return}this.options.log.error(`${this.clientID} tool execution failed: ${Q}`,q);let W={status:"error",error:{message:q instanceof Error?q.message:"Unknown error"}};this.sendToolResult(Z,W),G()}});V.subscription=z}catch(F){this.options.log.error(`${this.clientID} tool execution setup failed: ${Q}`,F);let z={status:"error",error:{message:F instanceof Error?F.message:String(F)}};this.sendToolResult(Z,z),G()}}flushBufferedTerminalResults(){if(this.disposing||this.pendingTerminalResults.size===0)return;for(let[J,Z]of this.pendingTerminalResults)this.sendTerminalResult(J,Z,"flush")}handleToolRevocation(J){if(this.disposing)return;let{toolCallId:Z,reason:Q}=J;this.options.log.info(`${this.clientID} lease revoked: ${Z}`,{reason:Q});let Y=this.activeTools.get(Z);if(Y)Y.abortController.abort(),Y.subscription.unsubscribe(),this.activeTools.delete(Z);this.sentApprovalRequests.delete(Z)}async handleRollbackRequest(J,Z,Q){if(this.disposing)return;try{if(Z.length>0)await Q(new Set(Z));this.options.log.wsMessage("SEND",this.clientID,{type:"executor_rollback_ack",editId:J,ok:!0}),this.sendTransportMessage("executor_rollback_ack",()=>this.transport.sendExecutorRollbackAck(J,!0),{editId:J}),this.queueGitStatusSnapshot()}catch(Y){let X=Y instanceof Error?Y.message:String(Y);this.options.log.error(`${this.clientID} rollback failed`,Y),this.options.log.wsMessage("SEND",this.clientID,{type:"executor_rollback_ack",editId:J,ok:!1,error:X}),this.sendTransportMessage("executor_rollback_ack",()=>this.transport.sendExecutorRollbackAck(J,!1,X),{editId:J})}}triggerGitStatus(J){this.queueGitStatusSnapshot(J)}dispose(){this.disposing=!0;for(let[,J]of this.activeTools)J.abortController.abort(),J.subscription.unsubscribe();this.activeTools.clear(),this.pendingTerminalResults.clear()}sendToolResult(J,Z){let Q=Date.now(),Y=this.toToolRun(Z),{run:X,files:K}=this.extractGuidanceFromRun(Y);if(K.length>0)this.sendGuidanceDiscovery(J,K);this.sendTerminalResult(J,X,"live",{guidanceFileCount:K.length,elapsedMs:Date.now()-Q}),this.sentApprovalRequests.delete(J),this.queueGitStatusSnapshot(J)}sendTerminalResult(J,Z,Q,Y){this.options.log.wsMessage("SEND",this.clientID,{type:"executor_tool_result",toolCallId:J,run:Z});let X=this.sendTransportMessage("executor_tool_result",()=>this.transport.sendExecutorToolResult(J,Z),{toolCallId:J,source:Q});if(X)this.pendingTerminalResults.delete(J);else this.pendingTerminalResults.set(J,Z);return this.options.log.info(`${this.clientID} executor_tool_result send attempted`,{toolCallId:J,status:Z.status,sent:X,source:Q,...Y}),X}sendGuidanceDiscovery(J,Z){let Q=this.options.batchGuidanceFiles(Z,J);for(let Y=0;Y<Q.length;Y++){let X=Q[Y];if(!X)continue;let K=Y===Q.length-1;if(this.options.log.wsMessage("SEND",this.clientID,{type:"executor_guidance_discovery",toolCallId:J,fileCount:X.length,isLast:K}),!this.sendTransportMessage("executor_guidance_discovery",()=>this.transport.sendExecutorGuidanceDiscovery({toolCallId:J,files:X,isLast:K}),{toolCallId:J,isLast:K,fileCount:X.length}))return}}queueGitStatusSnapshot(J){if(this.disposing||!this.options.captureGitStatus)return;if(this.gitStatusQueue.inFlight){if(this.gitStatusQueue.queued=!0,J)this.gitStatusQueue.queuedToolCallId=J;return}this.gitStatusQueue.inFlight=!0,this.sendGitStatusSnapshot(J).finally(()=>{if(this.gitStatusQueue.inFlight=!1,!this.gitStatusQueue.queued)return;let Z=this.gitStatusQueue.queuedToolCallId;this.gitStatusQueue.queued=!1,this.gitStatusQueue.queuedToolCallId=void 0,this.queueGitStatusSnapshot(Z)})}async sendGitStatusSnapshot(J){try{if(!this.options.captureGitStatus)return;let Z=await this.options.captureGitStatus();this.options.log.wsMessage("SEND",this.clientID,{type:"executor_artifact_upsert",available:Z.available,fileCount:Z.files.length,toolCallId:J,branch:Z.branch,head:Z.head}),this.transport.sendExecutorArtifactUpsert(Aa0(Z),J)}catch(Z){this.options.log.error("Failed to send git status snapshot",Z)}}toToolRun(J){switch(J.status){case"done":return{status:"done",result:J.result,progress:J.progress,trackFiles:J.trackFiles?[...J.trackFiles]:void 0};case"error":return{status:"error",error:{message:J.error?this.options.renderToolRunError(J.error):"Tool execution failed"}};case"rejected-by-user":return{status:"rejected-by-user",reason:J.reason};case"cancelled":return{status:"cancelled",reason:J.reason};default:return{status:"error",error:{message:`Unexpected status: ${J.status}`}}}}extractGuidanceFromRun(J){if(J.status!=="done")return{run:J,files:[]};if(!J.result||typeof J.result!=="object"||Array.isArray(J.result))return{run:J,files:[]};let Z=J.result;if(!("discoveredGuidanceFiles"in Z))return{run:J,files:[]};let Q=ej4(Z.discoveredGuidanceFiles),{discoveredGuidanceFiles:Y,...X}=Z;return{run:{...J,result:X},files:Q}}sendTransportMessage(J,Z,Q){try{return Z(),!0}catch(Y){if(Y instanceof v8)return this.options.log.info(`${this.clientID} dropped ${J} while reconnecting`,{messageType:J,...Q}),this.options.onTransportSendFailure?.(this.clientID,J,Y,Q),!1;return this.options.log.error(`${this.clientID} failed to send ${J}`,Y),!1}}}class kj{options;toolRunner;sentApprovalRequests;discoveredGuidanceFileURIs;handshakeManager;runtimeLog;advertisedExecutorTools=[];lastSentSettingsJSON="";settingsSubscription=null;eventSubscriptions=[];executorCallbacksAttached=!1;constructor(J){this.options=J;this.runtimeLog=this.options.log??{info:(Q,Y)=>_.info(`[executor-client] ${Q}`,Y),error:(Q,Y)=>_.error(`[executor-client] ${Q}`,{error:Y}),wsMessage:(Q,Y,X)=>{_.info("[executor-client] websocket message",{direction:Q,clientID:Y,...typeof X==="object"&&X!==null?X:{message:X}})}};let Z=async()=>{_.info("[executor-client] executor handshake requested",{clientID:this.options.clientID})};this.handshakeManager=new UI4({handshake:this.options.handshake??Z,...this.options.handshakeManagerOptions}),this.toolRunner=new DI4({clientID:this.options.clientID,transport:this.options.transport,log:this.runtimeLog,invokeTool:(Q)=>this.invokeTool(Q),captureGitStatus:this.options.captureGitStatus,batchGuidanceFiles:this.options.batchGuidanceFiles??((Q)=>[Q]),renderToolRunError:this.options.renderToolRunError??((Q)=>Q?.message??"Tool run failed"),onTransportSendFailure:this.options.onTransportSendFailure}),this.sentApprovalRequests=this.toolRunner.sentApprovalRequests,this.discoveredGuidanceFileURIs=this.toolRunner.discoveredGuidanceFileURIs}async connect(J){await this.bootstrapExecutor({executorType:J,trigger:"connect"}),this.listenToExecutorEvents(this.options.transport)}ensureHandshake(J){return this.handshakeManager.ensureHandshake(J)}ensureReady(J){return this.handshakeManager.ensureReady(J)}async bootstrapExecutor(J){await this.connectAsExecutor(J.executorType,J.workspaceRoot??this.options.workspaceRoot??"",J.threadID??this.options.threadID,J.trigger,J.suppressConnectLog)}syncExecutorToolRegistrations(J,Z){let Q=this.options.transport.getConnectionInfo();if(Q.state!=="connected"||Q.role!=="executor")return;this.advertisedExecutorTools=HI4({transport:this.options.transport,nextTools:J,previouslyAdvertisedTools:this.advertisedExecutorTools,logMessage:Z?.logMessage})}handleConnectionChange(J){this.handshakeManager.handleConnectionChange(J)}attachTransportExecutorCallbacks(J){let Z=J?.includeConnectionChanges??!1,Q=this.getInboundExecutorHandlers(),Y={onToolLease:Q.onToolLease,onToolLeaseRevoked:Q.onToolLeaseRevoked,onFileSystemReadFileRequest:Q.onFileSystemReadFileRequest};if(Z)Y.onConnectionChange=(X)=>{this.handleConnectionChange(X)};if(Q.onExecutorRollbackRequest)Y.onExecutorRollbackRequest=Q.onExecutorRollbackRequest;if(Q.onFileSystemReadDirectoryRequest)Y.onFileSystemReadDirectoryRequest=Q.onFileSystemReadDirectoryRequest;this.options.transport.setExecutorCallbacks(Y),this.executorCallbacksAttached=!0}clearTransportExecutorCallbacks(){if(!this.executorCallbacksAttached)return;this.options.transport.setExecutorCallbacks(null),this.executorCallbacksAttached=!1}dispose(){this.clearTransportExecutorCallbacks();for(let J of this.eventSubscriptions)J.unsubscribe();this.eventSubscriptions=[],this.toolRunner.dispose(),this.handshakeManager.dispose(),this.settingsSubscription?.unsubscribe(),this.settingsSubscription=null}async invokeTool(J){if(this.options.invokeTool)return await this.options.invokeTool(J);if(!this.options.getEnvironment)throw Error("Executor runtime requires getEnvironment or invokeTool");let{toolCallId:Z,toolName:Q,args:Y}=J,X=typeof Y==="object"&&Y!==null?Y:{},K=await this.options.getEnvironment();return K.thread={...K.thread,id:this.options.threadID},K.toolUseID=Z,this.options.toolService.invokeTool(Q,{args:X},K)}async connectAsExecutor(J,Z,Q,Y,X=!1){if(this.settingsSubscription?.unsubscribe(),this.settingsSubscription=null,!X)_.info(`Connecting ${this.options.clientID} as executor...`);try{let{advertisedTools:K}=await kJ3({transport:this.options.transport,executorClientID:this.options.executorClientID??this.options.clientID,workspaceRoot:Z,threadId:Q,configService:this.options.configService,toolService:this.options.toolService,skillService:this.options.skillService,fileSystem:this.options.fileSystem,logMessage:this.options.bootstrapLogMessage,executorType:J,initialToolDiscovery:this.options.initialToolDiscovery,sendGitSnapshot:this.options.sendGitSnapshot??!1,previouslyAdvertisedTools:this.advertisedExecutorTools});if(this.advertisedExecutorTools=K,this.toolRunner.flushBufferedTerminalResults(),this.options.onBootstrapSuccess)await this.options.onBootstrapSuccess(Y);this.startSettingsSync()}catch(K){throw _.error(`executor ${this.options.clientID} bootstrap failed`,K),K}}startSettingsSync(){if(this.settingsSubscription)return;this.settingsSubscription=this.options.configService.config.subscribe({next:(J)=>{this.lastSentSettingsJSON=vJ3(this.options.transport,J,this.lastSentSettingsJSON)}})}listenToExecutorEvents(J){if(this.eventSubscriptions.length>0)return;let Z=this.getInboundExecutorHandlers();if(this.eventSubscriptions.push(J.connectionChanges().subscribe({next:(Q)=>{this.handleConnectionChange(Q)}}),J.toolLeases().subscribe({next:Z.onToolLease}),J.toolLeaseRevoked().subscribe({next:Z.onToolLeaseRevoked})),this.options.autoResolvePendingApprovals!==!1)this.eventSubscriptions.push(this.options.toolService.pendingApprovals$.subscribe({next:(Q)=>{this.handlePendingApprovals(Q)}}));if(Z.onExecutorRollbackRequest)this.eventSubscriptions.push(J.executorRollbackRequests().subscribe({next:Z.onExecutorRollbackRequest}));if(Z.onFileSystemReadDirectoryRequest)this.eventSubscriptions.push(J.fileSystemReadDirectoryRequests().subscribe({next:Z.onFileSystemReadDirectoryRequest}));this.eventSubscriptions.push(J.fileSystemReadFileRequests().subscribe({next:Z.onFileSystemReadFileRequest}))}getInboundExecutorHandlers(){let J={onToolLease:(Z)=>{this.handleToolLease(Z)},onToolLeaseRevoked:(Z)=>{this.handleToolLeaseRevoked(Z)},onFileSystemReadFileRequest:(Z)=>{this.handleExecutorFileSystemReadFileRequest(Z)}};if(this.options.handleExecutorRollbackRequest)J.onExecutorRollbackRequest=(Z)=>{this.handleExecutorRollbackRequest(Z)};if(this.options.handleExecutorFileSystemReadDirectoryRequest||this.options.readFileSystemDirectory)J.onFileSystemReadDirectoryRequest=(Z)=>{this.handleExecutorFileSystemReadDirectoryRequest(Z)};return J}maybeLogInboundExecutorMessage(J){if(!this.options.logInboundExecutorMessages)return;this.runtimeLog.wsMessage("RECV",this.options.clientID,J)}handleToolLease(J){this.maybeLogInboundExecutorMessage(J),this.toolRunner.handleToolLease(J)}handleToolLeaseRevoked(J){this.maybeLogInboundExecutorMessage(J),this.toolRunner.handleToolRevocation(J)}handlePendingApprovals(J){for(let Z of J)this.options.toolService.resolveApproval(Z.toolUseId,!0)}handleExecutorRollbackRequest(J){if(this.maybeLogInboundExecutorMessage(J),!this.options.handleExecutorRollbackRequest)return;this.options.handleExecutorRollbackRequest(J)}async handleExecutorFileSystemReadDirectoryRequest(J){if(this.maybeLogInboundExecutorMessage(J),this.options.handleExecutorFileSystemReadDirectoryRequest){await this.options.handleExecutorFileSystemReadDirectoryRequest(J);return}if(!this.options.readFileSystemDirectory)throw Error("Method not implemented.");let Z=await this.options.readFileSystemDirectory(J);this.options.transport.sendExecutorFileSystemReadDirectoryResult(J.requestId,Z)}handleExecutorFileSystemReadFileRequest(J){if(this.maybeLogInboundExecutorMessage(J),this.options.handleExecutorFileSystemReadFileRequest){this.options.handleExecutorFileSystemReadFileRequest(J);return}throw Error("Method not implemented.")}}n0();function fY0(J){return{async createHandoffDraft(Z){let Q=await NI4(J,Z.signal);return BI4(Q,Z.parentThread.id,Z.goal,Z.images)},createHandoffThread:async(Z)=>{let Q=await NI4(J,Z.signal),Y=await BI4(Q,Z.parentThread.id,Z.goal,Z.images),X=await hJ3(Q,Z,Y);if(await bJ3(X.http,X.threadID,X.prompt,X.agentMode),Z.follow&&J.onFollow)try{await J.onFollow({sourceThreadID:Z.parentThread.id,targetThreadID:X.threadID})}catch(K){_.error("Failed to follow handoff thread",{error:K,sourceThreadID:Z.parentThread.id,targetThreadID:X.threadID})}return X.threadID}}}function fJ3(J){let Z=new Headers({"Content-Type":"application/json"});if(J)Z.set("Authorization",`Bearer ${J}`);return Z}async function ja0(J,Z,Q){return fetch(`${J.workerURL}${Z}`,{method:"POST",headers:fJ3(J.apiKey),body:JSON.stringify(Q),signal:J.signal})}async function BI4(J,Z,Q,Y){let X=await ja0(J,`/threads/${Z}/handoff`,{goal:Q,images:Y});if(!X.ok)throw Error(`Failed to generate handoff prompt: ${X.status} ${await X.text()}`);return await X.json()}async function uJ3(J,Z,Q,Y){let X=await ja0(J,"/threads",{...Z?{repositoryURL:Z}:{},...Q?{agentMode:Q}:{},relationship:Y});if(!X.ok)throw Error(`Failed to create handoff thread: ${X.status} ${await X.text()}`);let K=await X.json();if(!K.threadId)throw Error("Thread creation response missing threadId");return K.threadId}async function bJ3(J,Z,Q,Y){let X=await ja0(J,`/threads/${Z}/message`,{content:Q,...Y?{agentMode:Y}:{}});if(!X.ok)throw Error(`Failed to start handoff thread: ${X.status} ${await X.text()}`)}async function NI4(J,Z){let Q=await J.configService.getLatest(),Y=J.apiKey??await Q.secrets.getToken("apiKey",Q.settings.url),X=J.workerURL??process.env.AMP_WORKER_URL??l7(Q.settings.url);return{apiKey:Y,workerURL:X,signal:Z}}async function hJ3(J,Z,Q){let Y=Z.agentMode??Q.sourceAgentMode??Z.parentThread.agentMode,X=Z.relationshipMessageIndex??Q.parentMessageIndex,K=Z.relationshipComment??Z.goal,V={threadID:Q.parentThreadID,type:"handoff",...X!==void 0?{messageIndex:X}:{},...Z.relationshipBlockIndex!==void 0?{blockIndex:Z.relationshipBlockIndex}:{},comment:K},G=Z.parentThread.env?.initial?.trees?.[0]?.repository?.url,F=await uJ3(J,G,Y??void 0,V);return{http:J,threadID:F,prompt:Q.content,agentMode:Y??void 0}}cX();Lc();p_();Eg0();c4();U4();E1();async function uG(J){let{toolName:Z,dtwHandoffService:Q,dtwArtifactSyncService:Y,configService:X,toolService:K,mcpService:V,skillService:G,fsTracker:F,toolUseID:z,discoveredGuidanceFileURIs:q,threadID:W}=J,H={id:W??h8(),created:Date.now(),v:0,messages:[]},U=G1.file(process.cwd()),D=z??lF(),B=await X.getLatest(),N,w;if(F)N=F.trackedFileSystem(D),w=F.tracker;else w=S$0(kS0,H.id,async()=>{}),N=Mg0(I8,w,D);return{dir:U,tool:Z,thread:H,dtwHandoffService:Q,dtwArtifactSyncService:Y,trackedFiles:new QJ,toolUseID:D,todos:void 0,configService:X,toolService:K,mcpService:V,config:B,filesystem:N,fileChangeTracker:w,getAllTrackedChanges:async()=>w.getAllRecords(),threadEnvironment:{trees:[],platform:"cli"},handleThreadDelta:()=>Promise.resolve(),threadService:{observe:()=>k0.of(H),get:()=>Promise.resolve(H),getPrimitiveProperty:(L,O)=>Promise.resolve(H[O]),flushVersion:()=>Promise.resolve(),updateThreadMeta:()=>Promise.resolve()},getThreadEnvironment:()=>Promise.resolve({trees:[],platform:"cli"}),threadSummaryService:{summarizeThread:()=>Promise.resolve({summary:"CLI execution",prompt:"CLI execution",title:"CLI Tool"})},osFileSystem:I8,deleteThread:()=>Promise.resolve(),generateThreadTitle:()=>Promise.resolve({title:"CLI Tool Execution"}),fileChangeTrackerStorage:kS0,discoveredGuidanceFileURIs:q??new Set,skillService:G??{getSkills:()=>Promise.resolve([]),getTargetDir:()=>Promise.resolve("/tmp/skills"),listInstalled:()=>[],reload:()=>{}}}}function Ra0(){return new Date().toISOString()}var Ia0=process.stderr.isTTY,wI4=3000;function gJ3(J){let Z=J.trim();if(!(Z.startsWith("{")&&Z.endsWith("}")||Z.startsWith("[")&&Z.endsWith("]")))return null;try{return JSON.parse(Z)}catch{return null}}function Pa0(J){if(J instanceof Error)return J.stack??J.message;if(typeof J==="string"){let Z=gJ3(J);if(Z!==null)return JSON.stringify(Z,null,2);return J}if(J===void 0)return"";try{return JSON.stringify(J,null,2)}catch{return String(J)}}function A9(J,Z,Q){if(_.info("[headless-dtw] websocket message",{direction:J,clientId:Z,...typeof Q==="object"&&Q!==null?Q:{message:Q}}),!Ia0)return;let Y=g0.dim(`[${Ra0()}]`),X=g0.magenta(`[${Z}]`),K=J==="SEND"?g0.green(">>>"):g0.yellow("<<<"),V=Pa0(Q);process.stderr.write(`${Y} ${X} ${K} ${V}
|
|
6092
6092
|
`)}function t2(J,Z){if(Z)_.info(`[headless-dtw] ${J}`,Z);else _.info(`[headless-dtw] ${J}`);if(!Ia0)return;let Q=g0.dim(`[${Ra0()}]`),Y=g0.cyan("[INFO]"),X=Z?` ${Pa0(Z)}`:"";process.stderr.write(`${Q} ${Y} ${J}${X}
|
|
6093
6093
|
`)}function bG(J,Z){if(Z!==void 0)_.error(`[headless-dtw] ${J}`,{error:Z});else _.error(`[headless-dtw] ${J}`);if(!Ia0)return;let Q=g0.dim(`[${Ra0()}]`),Y=g0.red("[ERROR]"),X=Pa0(Z);process.stderr.write(`${Q} ${Y} ${J} ${X}
|
|
6094
6094
|
`)}function mJ3(J){let Z={reconnectCauseType:J.type,reconnectCauseAt:new Date(J.at).toISOString()};if(J.code!==void 0)Z.reconnectCode=J.code;if(J.reason)Z.reconnectReason=J.reason;if(J.error)Z.reconnectError=J.error;return Z}function pJ3(J,Z){let Q=new URL(J);if(!Q.pathname.endsWith("/"))Q.pathname+="/";return new URL(`threads/${Z}`,Q).toString()}class LI4{options;clients=new Map;clientCounter=0;disposed=!1;pluginsBootstrapped=!1;pendingExitCode=null;toolSyncSubscription=null;resolveRunLoop=null;constructor(J){this.options=J}bindClientThread(J,Z){let Q=J.threadId!==Z;if(J.threadId=Z,J.fsTracker&&!Q)return;let Y=this.options.fileSystem??I8,X=new nV(Y);J.fsTracker=cS({fileChangeTrackerStorage:X},Y,Z)}async connectTransport(J,Z,Q){let Y=await J.ensureConnected({maxAttempts:1,waitForConnectedTimeoutMs:wI4});if(!Y){let X=J.getConnectionInfo();t2(`${Z} waiting for reconnect during ${Q}`,{connectionState:X.state,reconnectCauseType:X.reconnectCause?.type,reconnectCauseCode:X.reconnectCause?.code,reconnectCauseReason:X.reconnectCause?.reason,waitedMs:wI4})}return Y}async recoverTransport(J,Z,Q,Y){let X=this.clients.get(J);if(!X||X.recoveringTransport||this.disposed)return;X.recoveringTransport=!0,t2(`${J} recovering transport after send failure`,{messageType:Z,error:Q.message,...Y});try{let K=X.transport.getConnectionInfo();if(K.state==="connecting"||K.state==="authenticating"||K.state==="reconnecting"){t2(`${J} recovery waiting for in-flight connection`,{connectionState:K.state,reconnectCauseType:K.reconnectCause?.type,reconnectCauseCode:K.reconnectCause?.code,reconnectCauseReason:K.reconnectCause?.reason});return}if(K.state==="connected")X.transport.disconnect();let V=await this.connectTransport(X.transport,J,"recovery"),G=X.transport.getThreadId();if(G)this.bindClientThread(X,G);if(!V)return;X.executorRuntime.ensureHandshake("retry")}catch(K){bG(`${J} transport recovery failed`,K)}finally{X.recoveringTransport=!1}}async start(){t2("Starting Headless DTW Harness",{ampURL:this.options.ampURL,workerUrl:this.options.workerUrl??l7(this.options.ampURL),workspaceRoot:this.options.workspaceRoot,threadId:this.options.threadId??null}),this.toolSyncSubscription??=this.options.toolService.tools.subscribe({next:(J)=>{let Z=Hv(J);for(let Q of this.clients.values())this.syncExecutorTools(Q,Z)}});try{let J=await this.createClient(this.options.threadId);t2("Initial client created",{clientId:J.id,threadId:J.threadId}),this.logThreadURL(J.threadId);let Z=await this.runLoop();if(Z!==0)throw Error(`Headless DTW harness exited with code ${Z}`)}catch(J){throw bG("Failed to start harness",J),J}}logThreadURL(J){if(!J)return;let Z=pJ3(this.options.ampURL,J);t2(`Thread URL: ${g0.blue.underline(Z)}`)}async shutdown(J,Z){if(this.pendingExitCode===null||J>this.pendingExitCode)this.pendingExitCode=J;let Q=this.resolveRunLoop;if(Q)this.resolveRunLoop=null;if(!this.disposed){if(J===0)t2(Z);else bG(Z);await this.dispose()}if(Q){let Y=this.pendingExitCode??J;this.pendingExitCode=null,Q(Y)}}async invokeToolForClient(J,Z){let{toolService:Q,configService:Y,mcpService:X,skillService:K}=this.options;if(!Q||!Y||!X)throw Error("Tool service not available");let{toolName:V,toolCallId:G,args:F}=Z,z=typeof F==="object"&&F!==null?F:{},q=fY0({configService:Y,apiKey:this.options.apiKey}),H=await uG({toolName:V,dtwHandoffService:q,dtwArtifactSyncService:{upsertArtifact:(U,D)=>{let B=K9.safeParse(D);J.transport.sendExecutorArtifactUpsert(U,B.success?B.data:void 0)},deleteArtifact:(U)=>{J.transport.sendExecutorArtifactDelete(U)}},configService:Y,toolService:Q,mcpService:X,skillService:K,fsTracker:J.fsTracker??void 0,toolUseID:G,discoveredGuidanceFileURIs:J.toolRunner.discoveredGuidanceFileURIs,threadID:J.threadId});return Q.invokeTool(V,{args:z},H)}async createClient(J){let Z=`client-${++this.clientCounter}`,Q=`cli-headless-${crypto.randomUUID()}`,Y=this.options.workerUrl??l7(this.options.ampURL),X={current:null},K=()=>{let B=X.current;if(!B)throw Error("Headless client callbacks invoked before initialization");return B},V=this.options.useThreadActors?process.env.THREAD_ACTORS_URL??ik(this.options.ampURL):void 0;t2(`Creating client ${Z}`,{threadId:J,workerUrl:Y,useThreadActors:this.options.useThreadActors??!1,threadActorsUrl:V??"(not used)",options:this.options});let G;if(this.options.useThreadActors&&V){let B=lk({endpoint:V});G={baseURL:V,threadId:J,webSocketProvider:async()=>{return await B.threadActor.getOrCreate([J],{params:{apiKey:this.options.apiKey,threadId:J,executorClientId:Q},...this.options.ownerUserId&&typeof this.options.threadVersion==="number"?{createWithInput:{threadId:J,ownerUserId:this.options.ownerUserId,threadVersion:this.options.threadVersion}}:{}}).webSocket("/")},WebSocketClass:WebSocket,maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000,useThreadActors:!0}}else G={baseURL:Y,apiKey:this.options.apiKey,threadId:J,WebSocketClass:WebSocket,maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000};let F=new lY(G),z=(B)=>({...B??{},threadId:J}),q={info:(B,N)=>{t2(B,z(N))},error:(B,N)=>{bG(B,N)},wsMessage:(B,N,w)=>{A9(B,N,z(typeof w==="object"&&w!==null?w:{message:w}))}},W=new kj({transport:F,toolService:this.options.toolService,configService:this.options.configService,clientID:Z,executorClientID:Q,threadID:J,invokeTool:(B)=>this.invokeToolForClient(K(),B),skillService:this.options.skillService,fileSystem:this.options.fileSystem,bootstrapLogMessage:(B,N)=>{A9(B,Z,N)},initialToolDiscovery:this.options.initialToolDiscovery,onBootstrapSuccess:async()=>{let B=K();if(!B.hasLoggedPostBootstrapThreadURL&&B.threadId)this.logThreadURL(B.threadId),B.hasLoggedPostBootstrapThreadURL=!0;this.setNotifyForwarder(B),this.bootstrapPluginsAfterExecutorConnect(B)},sendGitSnapshot:!0,handshake:(B)=>this.connectAsExecutor(K(),B),handshakeManagerOptions:{onError:({error:B,attempt:N,delayMs:w})=>{bG(`${Z} executor handshake failed`,{error:B,attempt:N,delayMs:w})},onExhausted:({error:B,maxAttempts:N})=>{this.shutdown(1,`${Z} executor handshake failed after ${N} attempts: ${B instanceof Error?B.message:String(B)}`)}},captureGitStatus:()=>vY0(this.options.workspaceRoot),batchGuidanceFiles:yY0,renderToolRunError:mm,onTransportSendFailure:(B,N,w,L)=>{this.recoverTransport(B,N,w,L)},log:q,autoResolvePendingApprovals:!1,handleExecutorRollbackRequest:async(B)=>{let N=K();await this.handleExecutorRollbackRequest(N,B)},handleExecutorFileSystemReadDirectoryRequest:async(B)=>{let N=K();await this.handleExecutorFileSystemReadDirectoryRequest(N,B)},handleExecutorFileSystemReadFileRequest:async(B)=>{let N=K();await this.handleExecutorFileSystemReadFileRequest(N,B)},logInboundExecutorMessages:!0}),H={id:Z,transport:F,threadId:J,hasLoggedPostBootstrapThreadURL:!1,executorRuntime:W,toolRunner:W.toolRunner,fsTracker:null,recoveringTransport:!1};X.current=H,W.attachTransportExecutorCallbacks(),this.clients.set(Z,H),this.subscribeToTransportEvents(H),t2(`Connecting ${Z}...`);let U=await this.connectTransport(F,Z,"startup"),D=F.getThreadId();if(D)this.bindClientThread(H,D);if(U)t2(`Connected ${Z}`,{threadId:D});if(U)H.executorRuntime.ensureHandshake("connect");return H}async connectAsExecutor(J,Z){t2(`Connecting ${J.id} as executor...`,{trigger:Z});try{await J.executorRuntime.bootstrapExecutor({executorType:"sandbox",trigger:Z,workspaceRoot:this.options.workspaceRoot,threadID:J.threadId,suppressConnectLog:!0})}catch(Q){throw bG(`${J.id} executor bootstrap failed`,Q),Q}}setNotifyForwarder(J){let Z=this.options.pluginPlatform;if(!Z)return;Z.setNotifyForwarder(async(Q)=>{let Y={type:"event",event:"ui.notify",data:{message:Q}};try{A9("SEND",J.id,{type:"executor_plugin_message",message:Y}),J.transport.sendPluginMessage(Y)}catch(X){bG(`${J.id} failed to forward plugin notification`,X)}})}bootstrapPluginsAfterExecutorConnect(J){let Z=this.options.pluginService;if(!Z||this.pluginsBootstrapped)return;this.pluginsBootstrapped=!0,t2(`${J.id} reloading plugins after executor bootstrap`),Z.reload()}syncExecutorTools(J,Z){J.executorRuntime.syncExecutorToolRegistrations(Z,{logMessage:(Q,Y)=>{A9(Q,J.id,Y)}})}syncApprovalRequests(J,Z){if(!J.threadId)return;let Q=Z.filter((X)=>X.threadId===J.threadId||X.mainThreadId===J.threadId),Y=new Set(Q.map(Tj));for(let X of[...J.toolRunner.sentApprovalRequests])if(!Y.has(X))J.toolRunner.sentApprovalRequests.delete(X);for(let X of Q){let K=Tj(X);if(J.toolRunner.sentApprovalRequests.has(K))continue;let V=CY0(X);A9("SEND",J.id,{type:"executor_tool_approval_request",toolCallId:V.toolCallId,toolName:V.toolName}),J.transport.sendExecutorToolApprovalRequest(V),J.toolRunner.sentApprovalRequests.add(K)}}handleExecutorToolApprovalResponse(J,Z){let{toolService:Q}=this.options;if(!Q){bG(`${J.id} received approval response without tool service`);return}t2(`${J.id} approval resolved`,{toolCallId:Z.toolCallId,accepted:Z.accepted}),Q.resolveApproval(Z.toolCallId,Z.accepted,Z.input?.denyFeedback)}subscribeToTransportEvents(J){let{transport:Z,id:Q}=J;Z.deltas().subscribe({next:(X)=>A9("RECV",Q,{eventType:"delta",...X})}),Z.agentStates().subscribe({next:(X)=>A9("RECV",Q,X)}),Z.messageEvents().subscribe({next:(X)=>A9("RECV",Q,X)}),Z.queuedMessages().subscribe({next:(X)=>A9("RECV",Q,X)}),Z.retryEvents().subscribe({next:(X)=>A9("RECV",Q,X)}),Z.connectionChanges().subscribe({next:(X)=>{if(X.state==="connected"&&X.threadId)this.bindClientThread(J,X.threadId);let V={role:X.role??"unclaimed"};if(X.state==="reconnecting"&&X.reconnectCause)Object.assign(V,mJ3(X.reconnectCause));t2(`${Q} connection: ${X.state}`,V),J.executorRuntime.handleConnectionChange(X)}}),Z.errors().subscribe({next:(X)=>{A9("RECV",Q,X),bG(`${Q} error`,X.message)}}),Z.errorEvents().subscribe({next:(X)=>A9("RECV",Q,X)}),Z.cancelledEvents().subscribe({next:(X)=>A9("RECV",Q,X)}),Z.toolApprovalQueue().subscribe({next:(X)=>A9("RECV",Q,X)}),Z.executorToolApprovalResponses().subscribe({next:(X)=>{A9("RECV",Q,X),this.handleExecutorToolApprovalResponse(J,X)}}),Z.toolProgress().subscribe({next:(X)=>A9("RECV",Q,X)}),Z.executorErrors().subscribe({next:(X)=>{A9("RECV",Q,X),bG(`${Q} executor error`,X.message)}}),Z.executorConnected().subscribe({next:(X)=>A9("RECV",Q,X)}),Z.messageEdited().subscribe({next:(X)=>A9("RECV",Q,X)}),Z.editRejected().subscribe({next:(X)=>A9("RECV",Q,X)});let{toolService:Y}=this.options;if(Y)Y.pendingApprovals$.subscribe((X)=>{this.syncApprovalRequests(J,X)})}async handleExecutorRollbackRequest(J,Z){let{id:Q,fsTracker:Y}=J,{editId:X,toolUseIdsToRevert:K}=Z;if(!Y){bG(`${Q} rollback failed: no file tracker`),A9("SEND",Q,{type:"executor_rollback_ack",editId:X,ok:!1,error:"File tracker not initialized"}),J.transport.sendExecutorRollbackAck(X,!1,"File tracker not initialized");return}await J.toolRunner.handleRollbackRequest(X,K,(V)=>Y.tracker.revertChanges(V))}async handleExecutorFileSystemReadDirectoryRequest(J,Z){let Q=await qv({fileSystem:this.options.fileSystem??I8,workspaceRoot:this.options.workspaceRoot},Z.uri);A9("SEND",J.id,{type:"executor_filesystem_read_directory_result",requestId:Z.requestId,...Q}),J.transport.sendExecutorFileSystemReadDirectoryResult(Z.requestId,Q)}async handleExecutorFileSystemReadFileRequest(J,Z){let Q=await TY0({fileSystem:this.options.fileSystem??I8,workspaceRoot:this.options.workspaceRoot},Z.uri);A9("SEND",J.id,{type:"executor_filesystem_read_file_result",requestId:Z.requestId,...Q}),J.transport.sendExecutorFileSystemReadFileResult(Z.requestId,Q)}async runLoop(){if(t2("Harness running. Press Ctrl+C to exit."),this.pendingExitCode!==null)return this.pendingExitCode;return await new Promise((J)=>{let Z=!1,Q=(K)=>{if(Z){t2(`Received ${K} while shutdown is already in progress`);return}Z=!0,this.shutdown(0,`Received ${K}, shutting down harness...`)},Y=()=>Q("SIGINT"),X=()=>Q("SIGTERM");this.resolveRunLoop=(K)=>{process.off("SIGINT",Y),process.off("SIGTERM",X),J(K)},process.on("SIGINT",Y),process.on("SIGTERM",X)})}getClients(){return Array.from(this.clients.values())}async dispose(){this.disposed=!0,this.toolSyncSubscription?.unsubscribe(),this.toolSyncSubscription=null,this.options.pluginPlatform?.setNotifyForwarder(null);for(let J of this.clients.values()){if(J.executorRuntime.dispose(),(await J.transport.disconnectAndWait()).status==="timeout")t2(`${J.id} timed out waiting for close acknowledgement before dispose`);J.transport.dispose()}this.clients.clear()}}async function OI4(J){await new LI4(J).start()}import{stderr as hG,stdin as lJ3}from"node:process";import{createInterface as iJ3}from"node:readline";import{stdout as dJ3}from"node:process";function cJ3(){return!!(process.env.SSH_CLIENT||process.env.SSH_TTY||process.env.SSH_CONNECTION)}function EI4(){if(!dJ3.isTTY)return!0;if(cJ3())return!0;if(process.platform!=="darwin"&&process.platform!=="win32"&&!process.env.DISPLAY)return!0;return!1}var uY0=[],Ca0=null;function _a0(J){if(Ca0=J,J&&uY0.length>0){for(let Z of uY0)J(Z);uY0=[]}}function MI4(J){return async(Z,Q)=>{return new Promise((Y,X)=>{let K={serverName:J,authorizationUrl:Z,redirectUrl:Q,resolve:Y,reject:X};if(Ca0)Ca0(K);else uY0.push(K)})}}function AI4(){return async(J,Z)=>{return hG.write(`
|
|
@@ -6222,11 +6222,11 @@ ${U}`))}},error:(H)=>{if(!W)W=!0,G(Error(`Failed to spawn brew: ${H.message}`))}
|
|
|
6222
6222
|
${U}`;if(X==="pnpm"&&U.includes("Unable to find the global bin directory"))D+=`
|
|
6223
6223
|
|
|
6224
6224
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
6225
|
-
npm install -g @sourcegraph/amp`;G(Error(D))}},error:(H)=>{if(!q)q=!0,G(Error(`Failed to spawn ${X}: ${H.message}`))},complete:()=>{if(!q)q=!0,V()}})})}n0();n0();$A();async function iY0(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=xP4(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 LQ3="https://static.ampcode.com/cli/cli-version.txt";async function nY0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${LQ3}?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=xP4(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 OQ3=604800000;function yP4(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>OQ3)return{ageMs:Q};return null}function xP4(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 ra0(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?yz(Q):void 0;return{sha:Y,age:X}}catch{return null}}E1();function sa0(J,Z,Q={}){let Y=new H4,X=Y.pipe(g6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new uF().scoped("update"),V=Q.startDelayMs??0;if(V>0)await vz(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 vz(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 lY0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:z,packageManager:q,isBinaryDistribution:W});let H=W?await nY0(J):await iY0(J,fj());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!==ca0()){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 hi(H.latestVersion,q);let D=await Tw(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 vz(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:X}}$A();import{stderr as Iq}from"node:process";function fP4(J){let Z=new rN().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 ba0(Y.force||!1,Y.verbose||!1,"0.0.
|
|
6225
|
+
npm install -g @sourcegraph/amp`;G(Error(D))}},error:(H)=>{if(!q)q=!0,G(Error(`Failed to spawn ${X}: ${H.message}`))},complete:()=>{if(!q)q=!0,V()}})})}n0();n0();$A();async function iY0(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=xP4(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 LQ3="https://static.ampcode.com/cli/cli-version.txt";async function nY0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${LQ3}?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=xP4(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 OQ3=604800000;function yP4(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>OQ3)return{ageMs:Q};return null}function xP4(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 ra0(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?yz(Q):void 0;return{sha:Y,age:X}}catch{return null}}E1();function sa0(J,Z,Q={}){let Y=new H4,X=Y.pipe(g6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new uF().scoped("update"),V=Q.startDelayMs??0;if(V>0)await vz(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 vz(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 lY0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:z,packageManager:q,isBinaryDistribution:W});let H=W?await nY0(J):await iY0(J,fj());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!==ca0()){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 hi(H.latestVersion,q);let D=await Tw(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 vz(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:X}}$A();import{stderr as Iq}from"node:process";function fP4(J){let Z=new rN().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 ba0(Y.force||!1,Y.verbose||!1,"0.0.1775571702-gac76fb"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new rN("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 EQ3(Y.targetVersion)});J.addCommand(Q)}async function EQ3(J){let Q=process.platform==="win32"&&xj()?{currentExecutablePath:process.execPath}:void 0;if(process.env.AMP_SKIP_UPDATE_CHECK==="1")Iq.write(g0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
6226
6226
|
|
|
6227
6227
|
`));try{if(!J){Iq.write(g0.blue(`Checking for updates...
|
|
6228
|
-
`));let{hasUpdate:K,latestVersion:V}=xj()?await nY0("0.0.
|
|
6229
|
-
`));let z=await Tw("0.0.
|
|
6228
|
+
`));let{hasUpdate:K,latestVersion:V}=xj()?await nY0("0.0.1775571702-gac76fb"):await iY0("0.0.1775571702-gac76fb",fj());if(!K){let G=ra0("0.0.1775571702-gac76fb"),F=G?.age?`released ${G.age} ago`:`built ${yz(new Date("2026-04-07T14:25:40.862Z"))} ago`;Iq.write(g0.green(`✓ Amp is already up to date on version ${"0.0.1775571702-gac76fb"} (${F})
|
|
6229
|
+
`));let z=await Tw("0.0.1775571702-gac76fb",Q);if(z.warning)Iq.write(`
|
|
6230
6230
|
`+g0.yellow(z.warning)+`
|
|
6231
6231
|
`);process.exit(0)}if(!V)Iq.write(g0.yellow("[WARN] could not find latest version")),process.exit(0);J=V}Iq.write(g0.blue(`Updating to version ${J}...
|
|
6232
6232
|
`)),await hi(J,void 0,(K)=>{Iq.write(g0.dim(`Running: ${K}
|
|
@@ -6236,7 +6236,7 @@ Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm in
|
|
|
6236
6236
|
`);process.exit(0)}catch(Y){let X=Y instanceof Error?Y.message:String(Y);Iq.write(g0.red.bold("Error: ")+X+`
|
|
6237
6237
|
`),process.exit(1)}}import{execSync as UC4}from"node:child_process";import{closeSync as zC4,openSync as lY3,writeSync as iY3}from"node:fs";import nY3 from"node:tty";n0();function MQ3(J){let Z=(J&4)!==0,Q=(J&8)!==0,Y=(J&16)!==0,X=(J&32)!==0,K=J&-61,V="unknown";switch(K){case 0:V="left";break;case 1:V="middle";break;case 2:V="right";break;case 64:V="wheel_up";break;case 65:V="wheel_down";break;case 66:V="wheel_left";break;case 67:V="wheel_right";break;default:V="unknown";break}return{button:V,modifiers:{shift:Z,ctrl:Y,alt:Q,meta:!1},motion:X}}function gi(J,Z,Q,Y){let X=MQ3(J.button),K;if(X.button==="wheel_up"||X.button==="wheel_down"||X.button==="wheel_left"||X.button==="wheel_right")K="scroll";else if(X.motion)K="move";else if(J.pressed)K="press";else K="release";let V,G;if(Z&&Q&&Y)V=(J.x-1)/Q,G=(J.y-1)/Y;else V=J.x-1,G=J.y-1;return{type:"mouse",action:K,button:X.button,x:V,y:G,modifiers:X.modifiers,drag:X.motion&&J.pressed}}var Pq=W4(uP4(),1),jQ3=globalThis;jQ3.Prism=Pq.default;(function(J){var Z="\\b(?:BASH|BASHOPTS|BASH_ALIASES|BASH_ARGC|BASH_ARGV|BASH_CMDS|BASH_COMPLETION_COMPAT_DIR|BASH_LINENO|BASH_REMATCH|BASH_SOURCE|BASH_VERSINFO|BASH_VERSION|COLORTERM|COLUMNS|COMP_WORDBREAKS|DBUS_SESSION_BUS_ADDRESS|DEFAULTS_PATH|DESKTOP_SESSION|DIRSTACK|DISPLAY|EUID|GDMSESSION|GDM_LANG|GNOME_KEYRING_CONTROL|GNOME_KEYRING_PID|GPG_AGENT_INFO|GROUPS|HISTCONTROL|HISTFILE|HISTFILESIZE|HISTSIZE|HOME|HOSTNAME|HOSTTYPE|IFS|INSTANCE|JOB|LANG|LANGUAGE|LC_ADDRESS|LC_ALL|LC_IDENTIFICATION|LC_MEASUREMENT|LC_MONETARY|LC_NAME|LC_NUMERIC|LC_PAPER|LC_TELEPHONE|LC_TIME|LESSCLOSE|LESSOPEN|LINES|LOGNAME|LS_COLORS|MACHTYPE|MAILCHECK|MANDATORY_PATH|NO_AT_BRIDGE|OLDPWD|OPTERR|OPTIND|ORBIT_SOCKETDIR|OSTYPE|PAPERSIZE|PATH|PIPESTATUS|PPID|PS1|PS2|PS3|PS4|PWD|RANDOM|REPLY|SECONDS|SELINUX_INIT|SESSION|SESSIONTYPE|SESSION_MANAGER|SHELL|SHELLOPTS|SHLVL|SSH_AUTH_SOCK|TERM|UID|UPSTART_EVENTS|UPSTART_INSTANCE|UPSTART_JOB|UPSTART_SESSION|USER|WINDOWID|XAUTHORITY|XDG_CONFIG_DIRS|XDG_CURRENT_DESKTOP|XDG_DATA_DIRS|XDG_GREETER_DATA_DIR|XDG_MENU_PREFIX|XDG_RUNTIME_DIR|XDG_SEAT|XDG_SEAT_PATH|XDG_SESSION_DESKTOP|XDG_SESSION_ID|XDG_SESSION_PATH|XDG_SESSION_TYPE|XDG_VTNR|XMODIFIERS)\\b",Q={pattern:/(^(["']?)\w+\2)[ \t]+\S.*/,lookbehind:!0,alias:"punctuation",inside:null},Y={bash:Q,environment:{pattern:RegExp("\\$"+Z),alias:"constant"},variable:[{pattern:/\$?\(\([\s\S]+?\)\)/,greedy:!0,inside:{variable:[{pattern:/(^\$\(\([\s\S]+)\)\)/,lookbehind:!0},/^\$\(\(/],number:/\b0x[\dA-Fa-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:[Ee]-?\d+)?/,operator:/--|\+\+|\*\*=?|<<=?|>>=?|&&|\|\||[=!+\-*/%<>^&|]=?|[?~:]/,punctuation:/\(\(?|\)\)?|,|;/}},{pattern:/\$\((?:\([^)]+\)|[^()])+\)|`[^`]+`/,greedy:!0,inside:{variable:/^\$\(|^`|\)$|`$/}},{pattern:/\$\{[^}]+\}/,greedy:!0,inside:{operator:/:[-=?+]?|[!\/]|##?|%%?|\^\^?|,,?/,punctuation:/[\[\]]/,environment:{pattern:RegExp("(\\{)"+Z),lookbehind:!0,alias:"constant"}}},/\$(?:\w+|[#?*!@$])/],entity:/\\(?:[abceEfnrtv\\"]|O?[0-7]{1,3}|U[0-9a-fA-F]{8}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{1,2})/};J.languages.bash={shebang:{pattern:/^#!\s*\/.*/,alias:"important"},comment:{pattern:/(^|[^"{\\$])#.*/,lookbehind:!0},"function-name":[{pattern:/(\bfunction\s+)[\w-]+(?=(?:\s*\(?:\s*\))?\s*\{)/,lookbehind:!0,alias:"function"},{pattern:/\b[\w-]+(?=\s*\(\s*\)\s*\{)/,alias:"function"}],"for-or-select":{pattern:/(\b(?:for|select)\s+)\w+(?=\s+in\s)/,alias:"variable",lookbehind:!0},"assign-left":{pattern:/(^|[\s;|&]|[<>]\()\w+(?:\.\w+)*(?=\+?=)/,inside:{environment:{pattern:RegExp("(^|[\\s;|&]|[<>]\\()"+Z),lookbehind:!0,alias:"constant"}},alias:"variable",lookbehind:!0},parameter:{pattern:/(^|\s)-{1,2}(?:\w+:[+-]?)?\w+(?:\.\w+)*(?=[=\s]|$)/,alias:"variable",lookbehind:!0},string:[{pattern:/((?:^|[^<])<<-?\s*)(\w+)\s[\s\S]*?(?:\r?\n|\r)\2/,lookbehind:!0,greedy:!0,inside:Y},{pattern:/((?:^|[^<])<<-?\s*)(["'])(\w+)\2\s[\s\S]*?(?:\r?\n|\r)\3/,lookbehind:!0,greedy:!0,inside:{bash:Q}},{pattern:/(^|[^\\](?:\\\\)*)"(?:\\[\s\S]|\$\([^)]+\)|\$(?!\()|`[^`]+`|[^"\\`$])*"/,lookbehind:!0,greedy:!0,inside:Y},{pattern:/(^|[^$\\])'[^']*'/,lookbehind:!0,greedy:!0},{pattern:/\$'(?:[^'\\]|\\[\s\S])*'/,greedy:!0,inside:{entity:Y.entity}}],environment:{pattern:RegExp("\\$?"+Z),alias:"constant"},variable:Y.variable,function:{pattern:/(^|[\s;|&]|[<>]\()(?:add|apropos|apt|apt-cache|apt-get|aptitude|aspell|automysqlbackup|awk|basename|bash|bc|bconsole|bg|bzip2|cal|cargo|cat|cfdisk|chgrp|chkconfig|chmod|chown|chroot|cksum|clear|cmp|column|comm|composer|cp|cron|crontab|csplit|curl|cut|date|dc|dd|ddrescue|debootstrap|df|diff|diff3|dig|dir|dircolors|dirname|dirs|dmesg|docker|docker-compose|du|egrep|eject|env|ethtool|expand|expect|expr|fdformat|fdisk|fg|fgrep|file|find|fmt|fold|format|free|fsck|ftp|fuser|gawk|git|gparted|grep|groupadd|groupdel|groupmod|groups|grub-mkconfig|gzip|halt|head|hg|history|host|hostname|htop|iconv|id|ifconfig|ifdown|ifup|import|install|ip|java|jobs|join|kill|killall|less|link|ln|locate|logname|logrotate|look|lpc|lpr|lprint|lprintd|lprintq|lprm|ls|lsof|lynx|make|man|mc|mdadm|mkconfig|mkdir|mke2fs|mkfifo|mkfs|mkisofs|mknod|mkswap|mmv|more|most|mount|mtools|mtr|mutt|mv|nano|nc|netstat|nice|nl|node|nohup|notify-send|npm|nslookup|op|open|parted|passwd|paste|pathchk|ping|pkill|pnpm|podman|podman-compose|popd|pr|printcap|printenv|ps|pushd|pv|quota|quotacheck|quotactl|ram|rar|rcp|reboot|remsync|rename|renice|rev|rm|rmdir|rpm|rsync|scp|screen|sdiff|sed|sendmail|seq|service|sftp|sh|shellcheck|shuf|shutdown|sleep|slocate|sort|split|ssh|stat|strace|su|sudo|sum|suspend|swapon|sync|sysctl|tac|tail|tar|tee|time|timeout|top|touch|tr|traceroute|tsort|tty|umount|uname|unexpand|uniq|units|unrar|unshar|unzip|update-grub|uptime|useradd|userdel|usermod|users|uudecode|uuencode|v|vcpkg|vdir|vi|vim|virsh|vmstat|wait|watch|wc|wget|whereis|which|who|whoami|write|xargs|xdg-open|yarn|yes|zenity|zip|zsh|zypper)(?=$|[)\s;|&])/,lookbehind:!0},keyword:{pattern:/(^|[\s;|&]|[<>]\()(?:case|do|done|elif|else|esac|fi|for|function|if|in|select|then|until|while)(?=$|[)\s;|&])/,lookbehind:!0},builtin:{pattern:/(^|[\s;|&]|[<>]\()(?:\.|:|alias|bind|break|builtin|caller|cd|command|continue|declare|echo|enable|eval|exec|exit|export|getopts|hash|help|let|local|logout|mapfile|printf|pwd|read|readarray|readonly|return|set|shift|shopt|source|test|times|trap|type|typeset|ulimit|umask|unalias|unset)(?=$|[)\s;|&])/,lookbehind:!0,alias:"class-name"},boolean:{pattern:/(^|[\s;|&]|[<>]\()(?:false|true)(?=$|[)\s;|&])/,lookbehind:!0},"file-descriptor":{pattern:/\B&\d\b/,alias:"important"},operator:{pattern:/\d?<>|>\||\+=|=[=~]?|!=?|<<[<-]?|[&\d]?>>|\d[<>]&?|[<>][&=]?|&[>&]?|\|[&|]?/,inside:{"file-descriptor":{pattern:/^\d/,alias:"important"}}},punctuation:/\$?\(\(?|\)\)?|\.\.|[{}[\];\\]/,number:{pattern:/(^|\s)(?:[1-9]\d*|0)(?:[.,]\d+)?\b/,lookbehind:!0}},Q.inside=J.languages.bash;var X=["comment","function-name","for-or-select","assign-left","parameter","string","environment","function","keyword","builtin","boolean","file-descriptor","operator","punctuation","number"],K=Y.variable[1].inside;for(var V=0;V<X.length;V++)K[X[V]]=J.languages.bash[X[V]];J.languages.sh=J.languages.bash,J.languages.shell=J.languages.bash})(Prism);Prism.languages.c=Prism.languages.extend("clike",{comment:{pattern:/\/\/(?:[^\r\n\\]|\\(?:\r\n?|\n|(?![\r\n])))*|\/\*[\s\S]*?(?:\*\/|$)/,greedy:!0},string:{pattern:/"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"/,greedy:!0},"class-name":{pattern:/(\b(?:enum|struct)\s+(?:__attribute__\s*\(\([\s\S]*?\)\)\s*)?)\w+|\b[a-z]\w*_t\b/,lookbehind:!0},keyword:/\b(?:_Alignas|_Alignof|_Atomic|_Bool|_Complex|_Generic|_Imaginary|_Noreturn|_Static_assert|_Thread_local|__attribute__|asm|auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|inline|int|long|register|return|short|signed|sizeof|static|struct|switch|typedef|typeof|union|unsigned|void|volatile|while)\b/,function:/\b[a-z_]\w*(?=\s*\()/i,number:/(?:\b0x(?:[\da-f]+(?:\.[\da-f]*)?|\.[\da-f]+)(?:p[+-]?\d+)?|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?)[ful]{0,4}/i,operator:/>>=?|<<=?|->|([-+&|:])\1|[?:~]|[-+*/%&|^!=<>]=?/});Prism.languages.insertBefore("c","string",{char:{pattern:/'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n]){0,32}'/,greedy:!0}});Prism.languages.insertBefore("c","string",{macro:{pattern:/(^[\t ]*)#\s*[a-z](?:[^\r\n\\/]|\/(?!\*)|\/\*(?:[^*]|\*(?!\/))*\*\/|\\(?:\r\n|[\s\S]))*/im,lookbehind:!0,greedy:!0,alias:"property",inside:{string:[{pattern:/^(#\s*include\s*)<[^>]+>/,lookbehind:!0},Prism.languages.c.string],char:Prism.languages.c.char,comment:Prism.languages.c.comment,"macro-name":[{pattern:/(^#\s*define\s+)\w+\b(?!\()/i,lookbehind:!0},{pattern:/(^#\s*define\s+)\w+\b(?=\()/i,lookbehind:!0,alias:"function"}],directive:{pattern:/^(#\s*)[a-z]+/,lookbehind:!0,alias:"keyword"},"directive-hash":/^#/,punctuation:/##|\\(?=[\r\n])/,expression:{pattern:/\S[\s\S]*/,inside:Prism.languages.c}}}});Prism.languages.insertBefore("c","function",{constant:/\b(?:EOF|NULL|SEEK_CUR|SEEK_END|SEEK_SET|__DATE__|__FILE__|__LINE__|__TIMESTAMP__|__TIME__|__func__|stderr|stdin|stdout)\b/});delete Prism.languages.c.boolean;Prism.languages.clike={comment:[{pattern:/(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,lookbehind:!0,greedy:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0,greedy:!0}],string:{pattern:/(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,greedy:!0},"class-name":{pattern:/(\b(?:class|extends|implements|instanceof|interface|new|trait)\s+|\bcatch\s+\()[\w.\\]+/i,lookbehind:!0,inside:{punctuation:/[.\\]/}},keyword:/\b(?:break|catch|continue|do|else|finally|for|function|if|in|instanceof|new|null|return|throw|try|while)\b/,boolean:/\b(?:false|true)\b/,function:/\b\w+(?=\()/,number:/\b0x[\da-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?/i,operator:/[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,punctuation:/[{}[\];(),.:]/};(function(J){var Z=/\b(?:alignas|alignof|asm|auto|bool|break|case|catch|char|char16_t|char32_t|char8_t|class|co_await|co_return|co_yield|compl|concept|const|const_cast|consteval|constexpr|constinit|continue|decltype|default|delete|do|double|dynamic_cast|else|enum|explicit|export|extern|final|float|for|friend|goto|if|import|inline|int|int16_t|int32_t|int64_t|int8_t|long|module|mutable|namespace|new|noexcept|nullptr|operator|override|private|protected|public|register|reinterpret_cast|requires|return|short|signed|sizeof|static|static_assert|static_cast|struct|switch|template|this|thread_local|throw|try|typedef|typeid|typename|uint16_t|uint32_t|uint64_t|uint8_t|union|unsigned|using|virtual|void|volatile|wchar_t|while)\b/,Q=/\b(?!<keyword>)\w+(?:\s*\.\s*\w+)*\b/.source.replace(/<keyword>/g,function(){return Z.source});J.languages.cpp=J.languages.extend("c",{"class-name":[{pattern:RegExp(/(\b(?:class|concept|enum|struct|typename)\s+)(?!<keyword>)\w+/.source.replace(/<keyword>/g,function(){return Z.source})),lookbehind:!0},/\b[A-Z]\w*(?=\s*::\s*\w+\s*\()/,/\b[A-Z_]\w*(?=\s*::\s*~\w+\s*\()/i,/\b\w+(?=\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>\s*::\s*\w+\s*\()/],keyword:Z,number:{pattern:/(?:\b0b[01']+|\b0x(?:[\da-f']+(?:\.[\da-f']*)?|\.[\da-f']+)(?:p[+-]?[\d']+)?|(?:\b[\d']+(?:\.[\d']*)?|\B\.[\d']+)(?:e[+-]?[\d']+)?)[ful]{0,4}/i,greedy:!0},operator:/>>=?|<<=?|->|--|\+\+|&&|\|\||[?:~]|<=>|[-+*/%&|^!=<>]=?|\b(?:and|and_eq|bitand|bitor|not|not_eq|or|or_eq|xor|xor_eq)\b/,boolean:/\b(?:false|true)\b/}),J.languages.insertBefore("cpp","string",{module:{pattern:RegExp(/(\b(?:import|module)\s+)/.source+"(?:"+/"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|<[^<>\r\n]*>/.source+"|"+/<mod-name>(?:\s*:\s*<mod-name>)?|:\s*<mod-name>/.source.replace(/<mod-name>/g,function(){return Q})+")"),lookbehind:!0,greedy:!0,inside:{string:/^[<"][\s\S]+/,operator:/:/,punctuation:/\./}},"raw-string":{pattern:/R"([^()\\ ]{0,16})\([\s\S]*?\)\1"/,alias:"string",greedy:!0}}),J.languages.insertBefore("cpp","keyword",{"generic-function":{pattern:/\b(?!operator\b)[a-z_]\w*\s*<(?:[^<>]|<[^<>]*>)*>(?=\s*\()/i,inside:{function:/^\w+/,generic:{pattern:/<[\s\S]+/,alias:"class-name",inside:J.languages.cpp}}}}),J.languages.insertBefore("cpp","operator",{"double-colon":{pattern:/::/,alias:"punctuation"}}),J.languages.insertBefore("cpp","class-name",{"base-clause":{pattern:/(\b(?:class|struct)\s+\w+\s*:\s*)[^;{}"'\s]+(?:\s+[^;{}"'\s]+)*(?=\s*[;{])/,lookbehind:!0,greedy:!0,inside:J.languages.extend("cpp",{})}}),J.languages.insertBefore("inside","double-colon",{"class-name":/\b[a-z_]\w*\b(?!\s*::)/i},J.languages.cpp["base-clause"])})(Prism);(function(J){function Z(n,c){return n.replace(/<<(\d+)>>/g,function(s,H0){return"(?:"+c[+H0]+")"})}function Q(n,c,s){return RegExp(Z(n,c),s||"")}function Y(n,c){for(var s=0;s<c;s++)n=n.replace(/<<self>>/g,function(){return"(?:"+n+")"});return n.replace(/<<self>>/g,"[^\\s\\S]")}var X={type:"bool byte char decimal double dynamic float int long object sbyte short string uint ulong ushort var void",typeDeclaration:"class enum interface record struct",contextual:"add alias and ascending async await by descending from(?=\\s*(?:\\w|$)) get global group into init(?=\\s*;) join let nameof not notnull on or orderby partial remove select set unmanaged value when where with(?=\\s*{)",other:"abstract as base break case catch checked const continue default delegate do else event explicit extern finally fixed for foreach goto if implicit in internal is lock namespace new null operator out override params private protected public readonly ref return sealed sizeof stackalloc static switch this throw try typeof unchecked unsafe using virtual volatile while yield"};function K(n){return"\\b(?:"+n.trim().replace(/ /g,"|")+")\\b"}var V=K(X.typeDeclaration),G=RegExp(K(X.type+" "+X.typeDeclaration+" "+X.contextual+" "+X.other)),F=K(X.typeDeclaration+" "+X.contextual+" "+X.other),z=K(X.type+" "+X.typeDeclaration+" "+X.other),q=Y(/<(?:[^<>;=+\-*/%&|^]|<<self>>)*>/.source,2),W=Y(/\((?:[^()]|<<self>>)*\)/.source,2),H=/@?\b[A-Za-z_]\w*\b/.source,U=Z(/<<0>>(?:\s*<<1>>)?/.source,[H,q]),D=Z(/(?!<<0>>)<<1>>(?:\s*\.\s*<<1>>)*/.source,[F,U]),B=/\[\s*(?:,\s*)*\]/.source,N=Z(/<<0>>(?:\s*(?:\?\s*)?<<1>>)*(?:\s*\?)?/.source,[D,B]),w=Z(/[^,()<>[\];=+\-*/%&|^]|<<0>>|<<1>>|<<2>>/.source,[q,W,B]),L=Z(/\(<<0>>+(?:,<<0>>+)+\)/.source,[w]),O=Z(/(?:<<0>>|<<1>>)(?:\s*(?:\?\s*)?<<2>>)*(?:\s*\?)?/.source,[L,D,B]),E={keyword:G,punctuation:/[<>()?,.:[\]]/},M=/'(?:[^\r\n'\\]|\\.|\\[Uux][\da-fA-F]{1,8})'/.source,A=/"(?:\\.|[^\\"\r\n])*"/.source,j=/@"(?:""|\\[\s\S]|[^\\"])*"(?!")/.source;J.languages.csharp=J.languages.extend("clike",{string:[{pattern:Q(/(^|[^$\\])<<0>>/.source,[j]),lookbehind:!0,greedy:!0},{pattern:Q(/(^|[^@$\\])<<0>>/.source,[A]),lookbehind:!0,greedy:!0}],"class-name":[{pattern:Q(/(\busing\s+static\s+)<<0>>(?=\s*;)/.source,[D]),lookbehind:!0,inside:E},{pattern:Q(/(\busing\s+<<0>>\s*=\s*)<<1>>(?=\s*;)/.source,[H,O]),lookbehind:!0,inside:E},{pattern:Q(/(\busing\s+)<<0>>(?=\s*=)/.source,[H]),lookbehind:!0},{pattern:Q(/(\b<<0>>\s+)<<1>>/.source,[V,U]),lookbehind:!0,inside:E},{pattern:Q(/(\bcatch\s*\(\s*)<<0>>/.source,[D]),lookbehind:!0,inside:E},{pattern:Q(/(\bwhere\s+)<<0>>/.source,[H]),lookbehind:!0},{pattern:Q(/(\b(?:is(?:\s+not)?|as)\s+)<<0>>/.source,[N]),lookbehind:!0,inside:E},{pattern:Q(/\b<<0>>(?=\s+(?!<<1>>|with\s*\{)<<2>>(?:\s*[=,;:{)\]]|\s+(?:in|when)\b))/.source,[O,z,H]),inside:E}],keyword:G,number:/(?:\b0(?:x[\da-f_]*[\da-f]|b[01_]*[01])|(?:\B\.\d+(?:_+\d+)*|\b\d+(?:_+\d+)*(?:\.\d+(?:_+\d+)*)?)(?:e[-+]?\d+(?:_+\d+)*)?)(?:[dflmu]|lu|ul)?\b/i,operator:/>>=?|<<=?|[-=]>|([-+&|])\1|~|\?\?=?|[-+*/%&|^!=<>]=?/,punctuation:/\?\.?|::|[{}[\];(),.:]/}),J.languages.insertBefore("csharp","number",{range:{pattern:/\.\./,alias:"operator"}}),J.languages.insertBefore("csharp","punctuation",{"named-parameter":{pattern:Q(/([(,]\s*)<<0>>(?=\s*:)/.source,[H]),lookbehind:!0,alias:"punctuation"}}),J.languages.insertBefore("csharp","class-name",{namespace:{pattern:Q(/(\b(?:namespace|using)\s+)<<0>>(?:\s*\.\s*<<0>>)*(?=\s*[;{])/.source,[H]),lookbehind:!0,inside:{punctuation:/\./}},"type-expression":{pattern:Q(/(\b(?:default|sizeof|typeof)\s*\(\s*(?!\s))(?:[^()\s]|\s(?!\s)|<<0>>)*(?=\s*\))/.source,[W]),lookbehind:!0,alias:"class-name",inside:E},"return-type":{pattern:Q(/<<0>>(?=\s+(?:<<1>>\s*(?:=>|[({]|\.\s*this\s*\[)|this\s*\[))/.source,[O,D]),inside:E,alias:"class-name"},"constructor-invocation":{pattern:Q(/(\bnew\s+)<<0>>(?=\s*[[({])/.source,[O]),lookbehind:!0,inside:E,alias:"class-name"},"generic-method":{pattern:Q(/<<0>>\s*<<1>>(?=\s*\()/.source,[H,q]),inside:{function:Q(/^<<0>>/.source,[H]),generic:{pattern:RegExp(q),alias:"class-name",inside:E}}},"type-list":{pattern:Q(/\b((?:<<0>>\s+<<1>>|record\s+<<1>>\s*<<5>>|where\s+<<2>>)\s*:\s*)(?:<<3>>|<<4>>|<<1>>\s*<<5>>|<<6>>)(?:\s*,\s*(?:<<3>>|<<4>>|<<6>>))*(?=\s*(?:where|[{;]|=>|$))/.source,[V,U,H,O,G.source,W,/\bnew\s*\(\s*\)/.source]),lookbehind:!0,inside:{"record-arguments":{pattern:Q(/(^(?!new\s*\()<<0>>\s*)<<1>>/.source,[U,W]),lookbehind:!0,greedy:!0,inside:J.languages.csharp},keyword:G,"class-name":{pattern:RegExp(O),greedy:!0,inside:E},punctuation:/[,()]/}},preprocessor:{pattern:/(^[\t ]*)#.*/m,lookbehind:!0,alias:"property",inside:{directive:{pattern:/(#)\b(?:define|elif|else|endif|endregion|error|if|line|nullable|pragma|region|undef|warning)\b/,lookbehind:!0,alias:"keyword"}}}});var I=A+"|"+M,S=Z(/\/(?![*/])|\/\/[^\r\n]*[\r\n]|\/\*(?:[^*]|\*(?!\/))*\*\/|<<0>>/.source,[I]),P=Y(Z(/[^"'/()]|<<0>>|\(<<self>>*\)/.source,[S]),2),b=/\b(?:assembly|event|field|method|module|param|property|return|type)\b/.source,p=Z(/<<0>>(?:\s*\(<<1>>*\))?/.source,[D,P]);J.languages.insertBefore("csharp","class-name",{attribute:{pattern:Q(/((?:^|[^\s\w>)?])\s*\[\s*)(?:<<0>>\s*:\s*)?<<1>>(?:\s*,\s*<<1>>)*(?=\s*\])/.source,[b,p]),lookbehind:!0,greedy:!0,inside:{target:{pattern:Q(/^<<0>>(?=\s*:)/.source,[b]),alias:"keyword"},"attribute-arguments":{pattern:Q(/\(<<0>>*\)/.source,[P]),inside:J.languages.csharp},"class-name":{pattern:RegExp(D),inside:{punctuation:/\./}},punctuation:/[:,]/}}});var x=/:[^}\r\n]+/.source,k=Y(Z(/[^"'/()]|<<0>>|\(<<self>>*\)/.source,[S]),2),f=Z(/\{(?!\{)(?:(?![}:])<<0>>)*<<1>>?\}/.source,[k,x]),d=Y(Z(/[^"'/()]|\/(?!\*)|\/\*(?:[^*]|\*(?!\/))*\*\/|<<0>>|\(<<self>>*\)/.source,[I]),2),m=Z(/\{(?!\{)(?:(?![}:])<<0>>)*<<1>>?\}/.source,[d,x]);function h(n,c){return{interpolation:{pattern:Q(/((?:^|[^{])(?:\{\{)*)<<0>>/.source,[n]),lookbehind:!0,inside:{"format-string":{pattern:Q(/(^\{(?:(?![}:])<<0>>)*)<<1>>(?=\}$)/.source,[c,x]),lookbehind:!0,inside:{punctuation:/^:/}},punctuation:/^\{|\}$/,expression:{pattern:/[\s\S]+/,alias:"language-csharp",inside:J.languages.csharp}}},string:/[\s\S]+/}}J.languages.insertBefore("csharp","string",{"interpolation-string":[{pattern:Q(/(^|[^\\])(?:\$@|@\$)"(?:""|\\[\s\S]|\{\{|<<0>>|[^\\{"])*"/.source,[f]),lookbehind:!0,greedy:!0,inside:h(f,k)},{pattern:Q(/(^|[^@\\])\$"(?:\\.|\{\{|<<0>>|[^\\"{])*"/.source,[m]),lookbehind:!0,greedy:!0,inside:h(m,d)}],char:{pattern:RegExp(M),greedy:!0}}),J.languages.dotnet=J.languages.cs=J.languages.csharp})(Prism);(function(J){var Z=/(?:"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n])*')/;J.languages.css={comment:/\/\*[\s\S]*?\*\//,atrule:{pattern:RegExp("@[\\w-](?:"+/[^;{\s"']|\s+(?!\s)/.source+"|"+Z.source+")*?"+/(?:;|(?=\s*\{))/.source),inside:{rule:/^@[\w-]+/,"selector-function-argument":{pattern:/(\bselector\s*\(\s*(?![\s)]))(?:[^()\s]|\s+(?![\s)])|\((?:[^()]|\([^()]*\))*\))+(?=\s*\))/,lookbehind:!0,alias:"selector"},keyword:{pattern:/(^|[^\w-])(?:and|not|only|or)(?![\w-])/,lookbehind:!0}}},url:{pattern:RegExp("\\burl\\((?:"+Z.source+"|"+/(?:[^\\\r\n()"']|\\[\s\S])*/.source+")\\)","i"),greedy:!0,inside:{function:/^url/i,punctuation:/^\(|\)$/,string:{pattern:RegExp("^"+Z.source+"$"),alias:"url"}}},selector:{pattern:RegExp(`(^|[{}\\s])[^{}\\s](?:[^{};"'\\s]|\\s+(?![\\s{])|`+Z.source+")*(?=\\s*\\{)"),lookbehind:!0},string:{pattern:Z,greedy:!0},property:{pattern:/(^|[^-\w\xA0-\uFFFF])(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*(?=\s*:)/i,lookbehind:!0},important:/!important\b/i,function:{pattern:/(^|[^-a-z0-9])[-a-z0-9]+(?=\()/i,lookbehind:!0},punctuation:/[(){};:,]/},J.languages.css.atrule.inside.rest=J.languages.css;var Q=J.languages.markup;if(Q)Q.tag.addInlined("style","css"),Q.tag.addAttribute("style","css")})(Prism);(function(J){var Z=[/\b(?:async|sync|yield)\*/,/\b(?:abstract|assert|async|await|break|case|catch|class|const|continue|covariant|default|deferred|do|dynamic|else|enum|export|extends|extension|external|factory|final|finally|for|get|hide|if|implements|import|in|interface|library|mixin|new|null|on|operator|part|rethrow|return|set|show|static|super|switch|sync|this|throw|try|typedef|var|void|while|with|yield)\b/],Q=/(^|[^\w.])(?:[a-z]\w*\s*\.\s*)*(?:[A-Z]\w*\s*\.\s*)*/.source,Y={pattern:RegExp(Q+/[A-Z](?:[\d_A-Z]*[a-z]\w*)?\b/.source),lookbehind:!0,inside:{namespace:{pattern:/^[a-z]\w*(?:\s*\.\s*[a-z]\w*)*(?:\s*\.)?/,inside:{punctuation:/\./}}}};J.languages.dart=J.languages.extend("clike",{"class-name":[Y,{pattern:RegExp(Q+/[A-Z]\w*(?=\s+\w+\s*[;,=()])/.source),lookbehind:!0,inside:Y.inside}],keyword:Z,operator:/\bis!|\b(?:as|is)\b|\+\+|--|&&|\|\||<<=?|>>=?|~(?:\/=?)?|[+\-*\/%&^|=!<>]=?|\?/}),J.languages.insertBefore("dart","string",{"string-literal":{pattern:/r?(?:("""|''')[\s\S]*?\1|(["'])(?:\\.|(?!\2)[^\\\r\n])*\2(?!\2))/,greedy:!0,inside:{interpolation:{pattern:/((?:^|[^\\])(?:\\{2})*)\$(?:\w+|\{(?:[^{}]|\{[^{}]*\})*\})/,lookbehind:!0,inside:{punctuation:/^\$\{?|\}$/,expression:{pattern:/[\s\S]+/,inside:J.languages.dart}}},string:/[\s\S]+/}},string:void 0}),J.languages.insertBefore("dart","class-name",{metadata:{pattern:/@\w+/,alias:"function"}}),J.languages.insertBefore("dart","class-name",{generics:{pattern:/<(?:[\w\s,.&?]|<(?:[\w\s,.&?]|<(?:[\w\s,.&?]|<[\w\s,.&?]*>)*>)*>)*>/,inside:{"class-name":Y,keyword:Z,punctuation:/[<>(),.:]/,operator:/[?&|]/}}})})(Prism);(function(J){var Z=/\\[\r\n](?:\s|\\[\r\n]|#.*(?!.))*(?![\s#]|\\[\r\n])/.source,Q=/(?:[ \t]+(?![ \t])(?:<SP_BS>)?|<SP_BS>)/.source.replace(/<SP_BS>/g,function(){return Z}),Y=/"(?:[^"\\\r\n]|\\(?:\r\n|[\s\S]))*"|'(?:[^'\\\r\n]|\\(?:\r\n|[\s\S]))*'/.source,X=/--[\w-]+=(?:<STR>|(?!["'])(?:[^\s\\]|\\.)+)/.source.replace(/<STR>/g,function(){return Y}),K={pattern:RegExp(Y),greedy:!0},V={pattern:/(^[ \t]*)#.*/m,lookbehind:!0,greedy:!0};function G(F,z){return F=F.replace(/<OPT>/g,function(){return X}).replace(/<SP>/g,function(){return Q}),RegExp(F,z)}J.languages.docker={instruction:{pattern:/(^[ \t]*)(?:ADD|ARG|CMD|COPY|ENTRYPOINT|ENV|EXPOSE|FROM|HEALTHCHECK|LABEL|MAINTAINER|ONBUILD|RUN|SHELL|STOPSIGNAL|USER|VOLUME|WORKDIR)(?=\s)(?:\\.|[^\r\n\\])*(?:\\$(?:\s|#.*$)*(?![\s#])(?:\\.|[^\r\n\\])*)*/im,lookbehind:!0,greedy:!0,inside:{options:{pattern:G(/(^(?:ONBUILD<SP>)?\w+<SP>)<OPT>(?:<SP><OPT>)*/.source,"i"),lookbehind:!0,greedy:!0,inside:{property:{pattern:/(^|\s)--[\w-]+/,lookbehind:!0},string:[K,{pattern:/(=)(?!["'])(?:[^\s\\]|\\.)+/,lookbehind:!0}],operator:/\\$/m,punctuation:/=/}},keyword:[{pattern:G(/(^(?:ONBUILD<SP>)?HEALTHCHECK<SP>(?:<OPT><SP>)*)(?:CMD|NONE)\b/.source,"i"),lookbehind:!0,greedy:!0},{pattern:G(/(^(?:ONBUILD<SP>)?FROM<SP>(?:<OPT><SP>)*(?!--)[^ \t\\]+<SP>)AS/.source,"i"),lookbehind:!0,greedy:!0},{pattern:G(/(^ONBUILD<SP>)\w+/.source,"i"),lookbehind:!0,greedy:!0},{pattern:/^\w+/,greedy:!0}],comment:V,string:K,variable:/\$(?:\w+|\{[^{}"'\\]*\})/,operator:/\\$/m}},comment:V},J.languages.dockerfile=J.languages.docker})(Prism);Prism.languages.go=Prism.languages.extend("clike",{string:{pattern:/(^|[^\\])"(?:\\.|[^"\\\r\n])*"|`[^`]*`/,lookbehind:!0,greedy:!0},keyword:/\b(?:break|case|chan|const|continue|default|defer|else|fallthrough|for|func|go(?:to)?|if|import|interface|map|package|range|return|select|struct|switch|type|var)\b/,boolean:/\b(?:_|false|iota|nil|true)\b/,number:[/\b0(?:b[01_]+|o[0-7_]+)i?\b/i,/\b0x(?:[a-f\d_]+(?:\.[a-f\d_]*)?|\.[a-f\d_]+)(?:p[+-]?\d+(?:_\d+)*)?i?(?!\w)/i,/(?:\b\d[\d_]*(?:\.[\d_]*)?|\B\.\d[\d_]*)(?:e[+-]?[\d_]+)?i?(?!\w)/i],operator:/[*\/%^!=]=?|\+[=+]?|-[=-]?|\|[=|]?|&(?:=|&|\^=?)?|>(?:>=?|=)?|<(?:<=?|=|-)?|:=|\.\.\./,builtin:/\b(?:append|bool|byte|cap|close|complex|complex(?:64|128)|copy|delete|error|float(?:32|64)|u?int(?:8|16|32|64)?|imag|len|make|new|panic|print(?:ln)?|real|recover|rune|string|uintptr)\b/});Prism.languages.insertBefore("go","string",{char:{pattern:/'(?:\\.|[^'\\\r\n]){0,10}'/,greedy:!0}});delete Prism.languages.go["class-name"];Prism.languages.graphql={comment:/#.*/,description:{pattern:/(?:"""(?:[^"]|(?!""")")*"""|"(?:\\.|[^\\"\r\n])*")(?=\s*[a-z_])/i,greedy:!0,alias:"string",inside:{"language-markdown":{pattern:/(^"(?:"")?)(?!\1)[\s\S]+(?=\1$)/,lookbehind:!0,inside:Prism.languages.markdown}}},string:{pattern:/"""(?:[^"]|(?!""")")*"""|"(?:\\.|[^\\"\r\n])*"/,greedy:!0},number:/(?:\B-|\b)\d+(?:\.\d+)?(?:e[+-]?\d+)?\b/i,boolean:/\b(?:false|true)\b/,variable:/\$[a-z_]\w*/i,directive:{pattern:/@[a-z_]\w*/i,alias:"function"},"attr-name":{pattern:/\b[a-z_]\w*(?=\s*(?:\((?:[^()"]|"(?:\\.|[^\\"\r\n])*")*\))?:)/i,greedy:!0},"atom-input":{pattern:/\b[A-Z]\w*Input\b/,alias:"class-name"},scalar:/\b(?:Boolean|Float|ID|Int|String)\b/,constant:/\b[A-Z][A-Z_\d]*\b/,"class-name":{pattern:/(\b(?:enum|implements|interface|on|scalar|type|union)\s+|&\s*|:\s*|\[)[A-Z_]\w*/,lookbehind:!0},fragment:{pattern:/(\bfragment\s+|\.{3}\s*(?!on\b))[a-zA-Z_]\w*/,lookbehind:!0,alias:"function"},"definition-mutation":{pattern:/(\bmutation\s+)[a-zA-Z_]\w*/,lookbehind:!0,alias:"function"},"definition-query":{pattern:/(\bquery\s+)[a-zA-Z_]\w*/,lookbehind:!0,alias:"function"},keyword:/\b(?:directive|enum|extend|fragment|implements|input|interface|mutation|on|query|repeatable|scalar|schema|subscription|type|union)\b/,operator:/[!=|&]|\.{3}/,"property-query":/\w+(?=\s*\()/,object:/\w+(?=\s*\{)/,punctuation:/[!(){}\[\]:=,]/,property:/\w+/};Prism.hooks.add("after-tokenize",function(Z){if(Z.language!=="graphql")return;var Q=Z.tokens.filter(function(B){return typeof B!=="string"&&B.type!=="comment"&&B.type!=="scalar"}),Y=0;function X(B){return Q[Y+B]}function K(B,N){N=N||0;for(var w=0;w<B.length;w++){var L=X(w+N);if(!L||L.type!==B[w])return!1}return!0}function V(B,N){var w=1;for(var L=Y;L<Q.length;L++){var O=Q[L],E=O.content;if(O.type==="punctuation"&&typeof E==="string"){if(B.test(E))w++;else if(N.test(E)){if(w--,w===0)return L}}}return-1}function G(B,N){var w=B.alias;if(!w)B.alias=w=[];else if(!Array.isArray(w))B.alias=w=[w];w.push(N)}for(;Y<Q.length;){var F=Q[Y++];if(F.type==="keyword"&&F.content==="mutation"){var z=[];if(K(["definition-mutation","punctuation"])&&X(1).content==="("){Y+=2;var q=V(/^\($/,/^\)$/);if(q===-1)continue;for(;Y<q;Y++){var W=X(0);if(W.type==="variable")G(W,"variable-input"),z.push(W.content)}Y=q+1}if(K(["punctuation","property-query"])&&X(0).content==="{"){if(Y++,G(X(0),"property-mutation"),z.length>0){var H=V(/^\{$/,/^\}$/);if(H===-1)continue;for(var U=Y;U<H;U++){var D=Q[U];if(D.type==="variable"&&z.indexOf(D.content)>=0)G(D,"variable-input")}}}}}});(function(J){var Z=/\b(?:abstract|assert|boolean|break|byte|case|catch|char|class|const|continue|default|do|double|else|enum|exports|extends|final|finally|float|for|goto|if|implements|import|instanceof|int|interface|long|module|native|new|non-sealed|null|open|opens|package|permits|private|protected|provides|public|record(?!\s*[(){}[\]<>=%~.:,;?+\-*/&|^])|requires|return|sealed|short|static|strictfp|super|switch|synchronized|this|throw|throws|to|transient|transitive|try|uses|var|void|volatile|while|with|yield)\b/,Q=/(?:[a-z]\w*\s*\.\s*)*(?:[A-Z]\w*\s*\.\s*)*/.source,Y={pattern:RegExp(/(^|[^\w.])/.source+Q+/[A-Z](?:[\d_A-Z]*[a-z]\w*)?\b/.source),lookbehind:!0,inside:{namespace:{pattern:/^[a-z]\w*(?:\s*\.\s*[a-z]\w*)*(?:\s*\.)?/,inside:{punctuation:/\./}},punctuation:/\./}};J.languages.java=J.languages.extend("clike",{string:{pattern:/(^|[^\\])"(?:\\.|[^"\\\r\n])*"/,lookbehind:!0,greedy:!0},"class-name":[Y,{pattern:RegExp(/(^|[^\w.])/.source+Q+/[A-Z]\w*(?=\s+\w+\s*[;,=()]|\s*(?:\[[\s,]*\]\s*)?::\s*new\b)/.source),lookbehind:!0,inside:Y.inside},{pattern:RegExp(/(\b(?:class|enum|extends|implements|instanceof|interface|new|record|throws)\s+)/.source+Q+/[A-Z]\w*\b/.source),lookbehind:!0,inside:Y.inside}],keyword:Z,function:[J.languages.clike.function,{pattern:/(::\s*)[a-z_]\w*/,lookbehind:!0}],number:/\b0b[01][01_]*L?\b|\b0x(?:\.[\da-f_p+-]+|[\da-f_]+(?:\.[\da-f_p+-]+)?)\b|(?:\b\d[\d_]*(?:\.[\d_]*)?|\B\.\d[\d_]*)(?:e[+-]?\d[\d_]*)?[dfl]?/i,operator:{pattern:/(^|[^.])(?:<<=?|>>>?=?|->|--|\+\+|&&|\|\||::|[?:~]|[-+*/%&|^!=<>]=?)/m,lookbehind:!0},constant:/\b[A-Z][A-Z_\d]+\b/}),J.languages.insertBefore("java","string",{"triple-quoted-string":{pattern:/"""[ \t]*[\r\n](?:(?:"|"")?(?:\\.|[^"\\]))*"""/,greedy:!0,alias:"string"},char:{pattern:/'(?:\\.|[^'\\\r\n]){1,6}'/,greedy:!0}}),J.languages.insertBefore("java","class-name",{annotation:{pattern:/(^|[^.])@\w+(?:\s*\.\s*\w+)*/,lookbehind:!0,alias:"punctuation"},generics:{pattern:/<(?:[\w\s,.?]|&(?!&)|<(?:[\w\s,.?]|&(?!&)|<(?:[\w\s,.?]|&(?!&)|<(?:[\w\s,.?]|&(?!&))*>)*>)*>)*>/,inside:{"class-name":Y,keyword:Z,punctuation:/[<>(),.:]/,operator:/[?&|]/}},import:[{pattern:RegExp(/(\bimport\s+)/.source+Q+/(?:[A-Z]\w*|\*)(?=\s*;)/.source),lookbehind:!0,inside:{namespace:Y.inside.namespace,punctuation:/\./,operator:/\*/,"class-name":/\w+/}},{pattern:RegExp(/(\bimport\s+static\s+)/.source+Q+/(?:\w+|\*)(?=\s*;)/.source),lookbehind:!0,alias:"static",inside:{namespace:Y.inside.namespace,static:/\b\w+$/,punctuation:/\./,operator:/\*/,"class-name":/\w+/}}],namespace:{pattern:RegExp(/(\b(?:exports|import(?:\s+static)?|module|open|opens|package|provides|requires|to|transitive|uses|with)\s+)(?!<keyword>)[a-z]\w*(?:\.[a-z]\w*)*\.?/.source.replace(/<keyword>/g,function(){return Z.source})),lookbehind:!0,inside:{punctuation:/\./}}})})(Prism);Prism.languages.javascript=Prism.languages.extend("clike",{"class-name":[Prism.languages.clike["class-name"],{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:constructor|prototype))/,lookbehind:!0}],keyword:[{pattern:/((?:^|\})\s*)catch\b/,lookbehind:!0},{pattern:/(^|[^.]|\.\.\.\s*)\b(?:as|assert(?=\s*\{)|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally(?=\s*(?:\{|$))|for|from(?=\s*(?:['"]|$))|function|(?:get|set)(?=\s*(?:[#\[$\w\xA0-\uFFFF]|$))|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,lookbehind:!0}],function:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,number:{pattern:RegExp(/(^|[^\w$])/.source+"(?:"+(/NaN|Infinity/.source+"|"+/0[bB][01]+(?:_[01]+)*n?/.source+"|"+/0[oO][0-7]+(?:_[0-7]+)*n?/.source+"|"+/0[xX][\dA-Fa-f]+(?:_[\dA-Fa-f]+)*n?/.source+"|"+/\d+(?:_\d+)*n/.source+"|"+/(?:\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\.\d+(?:_\d+)*)(?:[Ee][+-]?\d+(?:_\d+)*)?/.source)+")"+/(?![\w$])/.source),lookbehind:!0},operator:/--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/});Prism.languages.javascript["class-name"][0].pattern=/(\b(?:class|extends|implements|instanceof|interface|new)\s+)[\w.\\]+/;Prism.languages.insertBefore("javascript","keyword",{regex:{pattern:RegExp(/((?:^|[^$\w\xA0-\uFFFF."'\])\s]|\b(?:return|yield))\s*)/.source+/\//.source+"(?:"+/(?:\[(?:[^\]\\\r\n]|\\.)*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}/.source+"|"+/(?:\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.)*\])*\])*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}v[dgimyus]{0,7}/.source+")"+/(?=(?:\s|\/\*(?:[^*]|\*(?!\/))*\*\/)*(?:$|[\r\n,.;:})\]]|\/\/))/.source),lookbehind:!0,greedy:!0,inside:{"regex-source":{pattern:/^(\/)[\s\S]+(?=\/[a-z]*$)/,lookbehind:!0,alias:"language-regex",inside:Prism.languages.regex},"regex-delimiter":/^\/|\/$/,"regex-flags":/^[a-z]+$/}},"function-variable":{pattern:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)\s*=>))/,alias:"function"},parameter:[{pattern:/(function(?:\s+(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)?\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\))/,lookbehind:!0,inside:Prism.languages.javascript},{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,lookbehind:!0,inside:Prism.languages.javascript},{pattern:/(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,lookbehind:!0,inside:Prism.languages.javascript},{pattern:/((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*)\(\s*|\]\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*\{)/,lookbehind:!0,inside:Prism.languages.javascript}],constant:/\b[A-Z](?:[A-Z_]|\dx?)*\b/});Prism.languages.insertBefore("javascript","string",{hashbang:{pattern:/^#!.*/,greedy:!0,alias:"comment"},"template-string":{pattern:/`(?:\\[\s\S]|\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}|(?!\$\{)[^\\`])*`/,greedy:!0,inside:{"template-punctuation":{pattern:/^`|`$/,alias:"string"},interpolation:{pattern:/((?:^|[^\\])(?:\\{2})*)\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}/,lookbehind:!0,inside:{"interpolation-punctuation":{pattern:/^\$\{|\}$/,alias:"punctuation"},rest:Prism.languages.javascript}},string:/[\s\S]+/}},"string-property":{pattern:/((?:^|[,{])[ \t]*)(["'])(?:\\(?:\r\n|[\s\S])|(?!\2)[^\\\r\n])*\2(?=\s*:)/m,lookbehind:!0,greedy:!0,alias:"property"}});Prism.languages.insertBefore("javascript","operator",{"literal-property":{pattern:/((?:^|[,{])[ \t]*)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/m,lookbehind:!0,alias:"property"}});if(Prism.languages.markup)Prism.languages.markup.tag.addInlined("script","javascript"),Prism.languages.markup.tag.addAttribute(/on(?:abort|blur|change|click|composition(?:end|start|update)|dblclick|error|focus(?:in|out)?|key(?:down|up)|load|mouse(?:down|enter|leave|move|out|over|up)|reset|resize|scroll|select|slotchange|submit|unload|wheel)/.source,"javascript");Prism.languages.js=Prism.languages.javascript;Prism.languages.json={property:{pattern:/(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?=\s*:)/,lookbehind:!0,greedy:!0},string:{pattern:/(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?!\s*:)/,lookbehind:!0,greedy:!0},comment:{pattern:/\/\/.*|\/\*[\s\S]*?(?:\*\/|$)/,greedy:!0},number:/-?\b\d+(?:\.\d+)?(?:e[+-]?\d+)?\b/i,punctuation:/[{}[\],]/,operator:/:/,boolean:/\b(?:false|true)\b/,null:{pattern:/\bnull\b/,alias:"keyword"}};Prism.languages.webmanifest=Prism.languages.json;(function(J){var Z=J.util.clone(J.languages.javascript),Q=/(?:\s|\/\/.*(?!.)|\/\*(?:[^*]|\*(?!\/))\*\/)/.source,Y=/(?:\{(?:\{(?:\{[^{}]*\}|[^{}])*\}|[^{}])*\})/.source,X=/(?:\{<S>*\.{3}(?:[^{}]|<BRACES>)*\})/.source;function K(F,z){return F=F.replace(/<S>/g,function(){return Q}).replace(/<BRACES>/g,function(){return Y}).replace(/<SPREAD>/g,function(){return X}),RegExp(F,z)}X=K(X).source,J.languages.jsx=J.languages.extend("markup",Z),J.languages.jsx.tag.pattern=K(/<\/?(?:[\w.:-]+(?:<S>+(?:[\w.:$-]+(?:=(?:"(?:\\[\s\S]|[^\\"])*"|'(?:\\[\s\S]|[^\\'])*'|[^\s{'"/>=]+|<BRACES>))?|<SPREAD>))*<S>*\/?)?>/.source),J.languages.jsx.tag.inside.tag.pattern=/^<\/?[^\s>\/]*/,J.languages.jsx.tag.inside["attr-value"].pattern=/=(?!\{)(?:"(?:\\[\s\S]|[^\\"])*"|'(?:\\[\s\S]|[^\\'])*'|[^\s'">]+)/,J.languages.jsx.tag.inside.tag.inside["class-name"]=/^[A-Z]\w*(?:\.[A-Z]\w*)*$/,J.languages.jsx.tag.inside.comment=Z.comment,J.languages.insertBefore("inside","attr-name",{spread:{pattern:K(/<SPREAD>/.source),inside:J.languages.jsx}},J.languages.jsx.tag),J.languages.insertBefore("inside","special-attr",{script:{pattern:K(/=<BRACES>/.source),alias:"language-javascript",inside:{"script-punctuation":{pattern:/^=(?=\{)/,alias:"punctuation"},rest:J.languages.jsx}}},J.languages.jsx.tag);var V=function(F){if(!F)return"";if(typeof F==="string")return F;if(typeof F.content==="string")return F.content;return F.content.map(V).join("")},G=function(F){var z=[];for(var q=0;q<F.length;q++){var W=F[q],H=!1;if(typeof W!=="string")if(W.type==="tag"&&W.content[0]&&W.content[0].type==="tag")if(W.content[0].content[0].content==="</"){if(z.length>0&&z[z.length-1].tagName===V(W.content[0].content[1]))z.pop()}else if(W.content[W.content.length-1].content==="/>");else z.push({tagName:V(W.content[0].content[1]),openedBraces:0});else if(z.length>0&&W.type==="punctuation"&&W.content==="{")z[z.length-1].openedBraces++;else if(z.length>0&&z[z.length-1].openedBraces>0&&W.type==="punctuation"&&W.content==="}")z[z.length-1].openedBraces--;else H=!0;if(H||typeof W==="string"){if(z.length>0&&z[z.length-1].openedBraces===0){var U=V(W);if(q<F.length-1&&(typeof F[q+1]==="string"||F[q+1].type==="plain-text"))U+=V(F[q+1]),F.splice(q+1,1);if(q>0&&(typeof F[q-1]==="string"||F[q-1].type==="plain-text"))U=V(F[q-1])+U,F.splice(q-1,1),q--;F[q]=new J.Token("plain-text",U,null,U)}}if(W.content&&typeof W.content!=="string")G(W.content)}};J.hooks.add("after-tokenize",function(F){if(F.language!=="jsx"&&F.language!=="tsx")return;G(F.tokens)})})(Prism);(function(J){J.languages.kotlin=J.languages.extend("clike",{keyword:{pattern:/(^|[^.])\b(?:abstract|actual|annotation|as|break|by|catch|class|companion|const|constructor|continue|crossinline|data|do|dynamic|else|enum|expect|external|final|finally|for|fun|get|if|import|in|infix|init|inline|inner|interface|internal|is|lateinit|noinline|null|object|open|operator|out|override|package|private|protected|public|reified|return|sealed|set|super|suspend|tailrec|this|throw|to|try|typealias|val|var|vararg|when|where|while)\b/,lookbehind:!0},function:[{pattern:/(?:`[^\r\n`]+`|\b\w+)(?=\s*\()/,greedy:!0},{pattern:/(\.)(?:`[^\r\n`]+`|\w+)(?=\s*\{)/,lookbehind:!0,greedy:!0}],number:/\b(?:0[xX][\da-fA-F]+(?:_[\da-fA-F]+)*|0[bB][01]+(?:_[01]+)*|\d+(?:_\d+)*(?:\.\d+(?:_\d+)*)?(?:[eE][+-]?\d+(?:_\d+)*)?[fFL]?)\b/,operator:/\+[+=]?|-[-=>]?|==?=?|!(?:!|==?)?|[\/*%<>]=?|[?:]:?|\.\.|&&|\|\||\b(?:and|inv|or|shl|shr|ushr|xor)\b/}),delete J.languages.kotlin["class-name"];var Z={"interpolation-punctuation":{pattern:/^\$\{?|\}$/,alias:"punctuation"},expression:{pattern:/[\s\S]+/,inside:J.languages.kotlin}};J.languages.insertBefore("kotlin","string",{"string-literal":[{pattern:/"""(?:[^$]|\$(?:(?!\{)|\{[^{}]*\}))*?"""/,alias:"multiline",inside:{interpolation:{pattern:/\$(?:[a-z_]\w*|\{[^{}]*\})/i,inside:Z},string:/[\s\S]+/}},{pattern:/"(?:[^"\\\r\n$]|\\.|\$(?:(?!\{)|\{[^{}]*\}))*"/,alias:"singleline",inside:{interpolation:{pattern:/((?:^|[^\\])(?:\\{2})*)\$(?:[a-z_]\w*|\{[^{}]*\})/i,lookbehind:!0,inside:Z},string:/[\s\S]+/}}],char:{pattern:/'(?:[^'\\\r\n]|\\(?:.|u[a-fA-F0-9]{0,4}))'/,greedy:!0}}),delete J.languages.kotlin.string,J.languages.insertBefore("kotlin","keyword",{annotation:{pattern:/\B@(?:\w+:)?(?:[A-Z]\w*|\[[^\]]+\])/,alias:"builtin"}}),J.languages.insertBefore("kotlin","function",{label:{pattern:/\b\w+@|@\w+\b/,alias:"symbol"}}),J.languages.kt=J.languages.kotlin,J.languages.kts=J.languages.kotlin})(Prism);Prism.languages.lua={comment:/^#!.+|--(?:\[(=*)\[[\s\S]*?\]\1\]|.*)/m,string:{pattern:/(["'])(?:(?!\1)[^\\\r\n]|\\z(?:\r\n|\s)|\\(?:\r\n|[^z]))*\1|\[(=*)\[[\s\S]*?\]\2\]/,greedy:!0},number:/\b0x[a-f\d]+(?:\.[a-f\d]*)?(?:p[+-]?\d+)?\b|\b\d+(?:\.\B|(?:\.\d*)?(?:e[+-]?\d+)?\b)|\B\.\d+(?:e[+-]?\d+)?\b/i,keyword:/\b(?:and|break|do|else|elseif|end|false|for|function|goto|if|in|local|nil|not|or|repeat|return|then|true|until|while)\b/,function:/(?!\d)\w+(?=\s*(?:[({]))/,operator:[/[-+*%^&|#]|\/\/?|<[<=]?|>[>=]?|[=~]=?/,{pattern:/(^|[^.])\.\.(?!\.)/,lookbehind:!0}],punctuation:/[\[\](){},;]|\.+|:+/};(function(J){var Z=/(?:\\.|[^\\\n\r]|(?:\n|\r\n?)(?![\r\n]))/.source;function Q(q){return q=q.replace(/<inner>/g,function(){return Z}),RegExp(/((?:^|[^\\])(?:\\{2})*)/.source+"(?:"+q+")")}var Y=/(?:\\.|``(?:[^`\r\n]|`(?!`))+``|`[^`\r\n]+`|[^\\|\r\n`])+/.source,X=/\|?__(?:\|__)+\|?(?:(?:\n|\r\n?)|(?![\s\S]))/.source.replace(/__/g,function(){return Y}),K=/\|?[ \t]*:?-{3,}:?[ \t]*(?:\|[ \t]*:?-{3,}:?[ \t]*)+\|?(?:\n|\r\n?)/.source;J.languages.markdown=J.languages.extend("markup",{}),J.languages.insertBefore("markdown","prolog",{"front-matter-block":{pattern:/(^(?:\s*[\r\n])?)---(?!.)[\s\S]*?[\r\n]---(?!.)/,lookbehind:!0,greedy:!0,inside:{punctuation:/^---|---$/,"front-matter":{pattern:/\S+(?:\s+\S+)*/,alias:["yaml","language-yaml"],inside:J.languages.yaml}}},blockquote:{pattern:/^>(?:[\t ]*>)*/m,alias:"punctuation"},table:{pattern:RegExp("^"+X+K+"(?:"+X+")*","m"),inside:{"table-data-rows":{pattern:RegExp("^("+X+K+")(?:"+X+")*$"),lookbehind:!0,inside:{"table-data":{pattern:RegExp(Y),inside:J.languages.markdown},punctuation:/\|/}},"table-line":{pattern:RegExp("^("+X+")"+K+"$"),lookbehind:!0,inside:{punctuation:/\||:?-{3,}:?/}},"table-header-row":{pattern:RegExp("^"+X+"$"),inside:{"table-header":{pattern:RegExp(Y),alias:"important",inside:J.languages.markdown},punctuation:/\|/}}}},code:[{pattern:/((?:^|\n)[ \t]*\n|(?:^|\r\n?)[ \t]*\r\n?)(?: {4}|\t).+(?:(?:\n|\r\n?)(?: {4}|\t).+)*/,lookbehind:!0,alias:"keyword"},{pattern:/^```[\s\S]*?^```$/m,greedy:!0,inside:{"code-block":{pattern:/^(```.*(?:\n|\r\n?))[\s\S]+?(?=(?:\n|\r\n?)^```$)/m,lookbehind:!0},"code-language":{pattern:/^(```).+/,lookbehind:!0},punctuation:/```/}}],title:[{pattern:/\S.*(?:\n|\r\n?)(?:==+|--+)(?=[ \t]*$)/m,alias:"important",inside:{punctuation:/==+$|--+$/}},{pattern:/(^\s*)#.+/m,lookbehind:!0,alias:"important",inside:{punctuation:/^#+|#+$/}}],hr:{pattern:/(^\s*)([*-])(?:[\t ]*\2){2,}(?=\s*$)/m,lookbehind:!0,alias:"punctuation"},list:{pattern:/(^\s*)(?:[*+-]|\d+\.)(?=[\t ].)/m,lookbehind:!0,alias:"punctuation"},"url-reference":{pattern:/!?\[[^\]]+\]:[\t ]+(?:\S+|<(?:\\.|[^>\\])+>)(?:[\t ]+(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\)))?/,inside:{variable:{pattern:/^(!?\[)[^\]]+/,lookbehind:!0},string:/(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\))$/,punctuation:/^[\[\]!:]|[<>]/},alias:"url"},bold:{pattern:Q(/\b__(?:(?!_)<inner>|_(?:(?!_)<inner>)+_)+__\b|\*\*(?:(?!\*)<inner>|\*(?:(?!\*)<inner>)+\*)+\*\*/.source),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^..)[\s\S]+(?=..$)/,lookbehind:!0,inside:{}},punctuation:/\*\*|__/}},italic:{pattern:Q(/\b_(?:(?!_)<inner>|__(?:(?!_)<inner>)+__)+_\b|\*(?:(?!\*)<inner>|\*\*(?:(?!\*)<inner>)+\*\*)+\*/.source),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^.)[\s\S]+(?=.$)/,lookbehind:!0,inside:{}},punctuation:/[*_]/}},strike:{pattern:Q(/(~~?)(?:(?!~)<inner>)+\2/.source),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^~~?)[\s\S]+(?=\1$)/,lookbehind:!0,inside:{}},punctuation:/~~?/}},"code-snippet":{pattern:/(^|[^\\`])(?:``[^`\r\n]+(?:`[^`\r\n]+)*``(?!`)|`[^`\r\n]+`(?!`))/,lookbehind:!0,greedy:!0,alias:["code","keyword"]},url:{pattern:Q(/!?\[(?:(?!\])<inner>)+\](?:\([^\s)]+(?:[\t ]+"(?:\\.|[^"\\])*")?\)|[ \t]?\[(?:(?!\])<inner>)+\])/.source),lookbehind:!0,greedy:!0,inside:{operator:/^!/,content:{pattern:/(^\[)[^\]]+(?=\])/,lookbehind:!0,inside:{}},variable:{pattern:/(^\][ \t]?\[)[^\]]+(?=\]$)/,lookbehind:!0},url:{pattern:/(^\]\()[^\s)]+/,lookbehind:!0},string:{pattern:/(^[ \t]+)"(?:\\.|[^"\\])*"(?=\)$)/,lookbehind:!0}}}}),["url","bold","italic","strike"].forEach(function(q){["url","bold","italic","strike","code-snippet"].forEach(function(W){if(q!==W)J.languages.markdown[q].inside.content.inside[W]=J.languages.markdown[W]})}),J.hooks.add("after-tokenize",function(q){if(q.language!=="markdown"&&q.language!=="md")return;function W(H){if(!H||typeof H==="string")return;for(var U=0,D=H.length;U<D;U++){var B=H[U];if(B.type!=="code"){W(B.content);continue}var N=B.content[1],w=B.content[3];if(N&&w&&N.type==="code-language"&&w.type==="code-block"&&typeof N.content==="string"){var L=N.content.replace(/\b#/g,"sharp").replace(/\b\+\+/g,"pp");L=(/[a-z][\w-]*/i.exec(L)||[""])[0].toLowerCase();var O="language-"+L;if(!w.alias)w.alias=[O];else if(typeof w.alias==="string")w.alias=[w.alias,O];else w.alias.push(O)}}}W(q.tokens)}),J.hooks.add("wrap",function(q){if(q.type!=="code-block")return;var W="";for(var H=0,U=q.classes.length;H<U;H++){var D=q.classes[H],B=/language-(.+)/.exec(D);if(B){W=B[1];break}}var N=J.languages[W];if(!N){if(W&&W!=="none"&&J.plugins.autoloader){var w="md-"+new Date().valueOf()+"-"+Math.floor(Math.random()*10000000000000000);q.attributes.id=w,J.plugins.autoloader.loadLanguages(W,function(){var L=document.getElementById(w);if(L)L.innerHTML=J.highlight(L.textContent,J.languages[W],W)})}}else q.content=J.highlight(z(q.content),N,W)});var V=RegExp(J.languages.markup.tag.pattern.source,"gi"),G={amp:"&",lt:"<",gt:">",quot:'"'},F=String.fromCodePoint||String.fromCharCode;function z(q){var W=q.replace(V,"");return W=W.replace(/&(\w{1,8}|#x?[\da-f]{1,8});/gi,function(H,U){if(U=U.toLowerCase(),U[0]==="#"){var D;if(U[1]==="x")D=parseInt(U.slice(2),16);else D=Number(U.slice(1));return F(D)}else{var B=G[U];if(B)return B;return H}}),W}J.languages.md=J.languages.markdown})(Prism);Prism.languages.markup={comment:{pattern:/<!--(?:(?!<!--)[\s\S])*?-->/,greedy:!0},prolog:{pattern:/<\?[\s\S]+?\?>/,greedy:!0},doctype:{pattern:/<!DOCTYPE(?:[^>"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]|"[^"]*"|'[^']*'|<(?!!--)|<!--(?:[^-]|-(?!->))*-->)*\]\s*)?>/i,greedy:!0,inside:{"internal-subset":{pattern:/(^[^\[]*\[)[\s\S]+(?=\]>$)/,lookbehind:!0,greedy:!0,inside:null},string:{pattern:/"[^"]*"|'[^']*'/,greedy:!0},punctuation:/^<!|>$|[[\]]/,"doctype-tag":/^DOCTYPE/i,name:/[^\s<>'"]+/}},cdata:{pattern:/<!\[CDATA\[[\s\S]*?\]\]>/i,greedy:!0},tag:{pattern:/<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,greedy:!0,inside:{tag:{pattern:/^<\/?[^\s>\/]+/,inside:{punctuation:/^<\/?/,namespace:/^[^\s>\/:]+:/}},"special-attr":[],"attr-value":{pattern:/=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,inside:{punctuation:[{pattern:/^=/,alias:"attr-equals"},{pattern:/^(\s*)["']|["']$/,lookbehind:!0}]}},punctuation:/\/?>/,"attr-name":{pattern:/[^\s>\/]+/,inside:{namespace:/^[^\s>\/:]+:/}}}},entity:[{pattern:/&[\da-z]{1,8};/i,alias:"named-entity"},/&#x?[\da-f]{1,8};/i]};Prism.languages.markup.tag.inside["attr-value"].inside.entity=Prism.languages.markup.entity;Prism.languages.markup.doctype.inside["internal-subset"].inside=Prism.languages.markup;Prism.hooks.add("wrap",function(J){if(J.type==="entity")J.attributes.title=J.content.replace(/&/,"&")});Object.defineProperty(Prism.languages.markup.tag,"addInlined",{value:function(Z,Q){var Y={};Y["language-"+Q]={pattern:/(^<!\[CDATA\[)[\s\S]+?(?=\]\]>$)/i,lookbehind:!0,inside:Prism.languages[Q]},Y.cdata=/^<!\[CDATA\[|\]\]>$/i;var X={"included-cdata":{pattern:/<!\[CDATA\[[\s\S]*?\]\]>/i,inside:Y}};X["language-"+Q]={pattern:/[\s\S]+/,inside:Prism.languages[Q]};var K={};K[Z]={pattern:RegExp(/(<__[^>]*>)(?:<!\[CDATA\[(?:[^\]]|\](?!\]>))*\]\]>|(?!<!\[CDATA\[)[\s\S])*?(?=<\/__>)/.source.replace(/__/g,function(){return Z}),"i"),lookbehind:!0,greedy:!0,inside:X},Prism.languages.insertBefore("markup","cdata",K)}});Object.defineProperty(Prism.languages.markup.tag,"addAttribute",{value:function(J,Z){Prism.languages.markup.tag.inside["special-attr"].push({pattern:RegExp(/(^|["'\s])/.source+"(?:"+J+")"+/\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))/.source,"i"),lookbehind:!0,inside:{"attr-name":/^[^\s=]+/,"attr-value":{pattern:/=[\s\S]+/,inside:{value:{pattern:/(^=\s*(["']|(?!["'])))\S[\s\S]*(?=\2$)/,lookbehind:!0,alias:[Z,"language-"+Z],inside:Prism.languages[Z]},punctuation:[{pattern:/^=/,alias:"attr-equals"},/"|'/]}}}})}});Prism.languages.html=Prism.languages.markup;Prism.languages.mathml=Prism.languages.markup;Prism.languages.svg=Prism.languages.markup;Prism.languages.xml=Prism.languages.extend("markup",{});Prism.languages.ssml=Prism.languages.xml;Prism.languages.atom=Prism.languages.xml;Prism.languages.rss=Prism.languages.xml;(function(J){var Z=/\/\*[\s\S]*?\*\/|\/\/.*|#(?!\[).*/,Q=[{pattern:/\b(?:false|true)\b/i,alias:"boolean"},{pattern:/(::\s*)\b[a-z_]\w*\b(?!\s*\()/i,greedy:!0,lookbehind:!0},{pattern:/(\b(?:case|const)\s+)\b[a-z_]\w*(?=\s*[;=])/i,greedy:!0,lookbehind:!0},/\b(?:null)\b/i,/\b[A-Z_][A-Z0-9_]*\b(?!\s*\()/],Y=/\b0b[01]+(?:_[01]+)*\b|\b0o[0-7]+(?:_[0-7]+)*\b|\b0x[\da-f]+(?:_[\da-f]+)*\b|(?:\b\d+(?:_\d+)*\.?(?:\d+(?:_\d+)*)?|\B\.\d+)(?:e[+-]?\d+)?/i,X=/<?=>|\?\?=?|\.{3}|\??->|[!=]=?=?|::|\*\*=?|--|\+\+|&&|\|\||<<|>>|[?~]|[/^|%*&<>.+-]=?/,K=/[{}\[\](),:;]/;J.languages.php={delimiter:{pattern:/\?>$|^<\?(?:php(?=\s)|=)?/i,alias:"important"},comment:Z,variable:/\$+(?:\w+\b|(?=\{))/,package:{pattern:/(namespace\s+|use\s+(?:function\s+)?)(?:\\?\b[a-z_]\w*)+\b(?!\\)/i,lookbehind:!0,inside:{punctuation:/\\/}},"class-name-definition":{pattern:/(\b(?:class|enum|interface|trait)\s+)\b[a-z_]\w*(?!\\)\b/i,lookbehind:!0,alias:"class-name"},"function-definition":{pattern:/(\bfunction\s+)[a-z_]\w*(?=\s*\()/i,lookbehind:!0,alias:"function"},keyword:[{pattern:/(\(\s*)\b(?:array|bool|boolean|float|int|integer|object|string)\b(?=\s*\))/i,alias:"type-casting",greedy:!0,lookbehind:!0},{pattern:/([(,?]\s*)\b(?:array(?!\s*\()|bool|callable|(?:false|null)(?=\s*\|)|float|int|iterable|mixed|object|self|static|string)\b(?=\s*\$)/i,alias:"type-hint",greedy:!0,lookbehind:!0},{pattern:/(\)\s*:\s*(?:\?\s*)?)\b(?:array(?!\s*\()|bool|callable|(?:false|null)(?=\s*\|)|float|int|iterable|mixed|never|object|self|static|string|void)\b/i,alias:"return-type",greedy:!0,lookbehind:!0},{pattern:/\b(?:array(?!\s*\()|bool|float|int|iterable|mixed|object|string|void)\b/i,alias:"type-declaration",greedy:!0},{pattern:/(\|\s*)(?:false|null)\b|\b(?:false|null)(?=\s*\|)/i,alias:"type-declaration",greedy:!0,lookbehind:!0},{pattern:/\b(?:parent|self|static)(?=\s*::)/i,alias:"static-context",greedy:!0},{pattern:/(\byield\s+)from\b/i,lookbehind:!0},/\bclass\b/i,{pattern:/((?:^|[^\s>:]|(?:^|[^-])>|(?:^|[^:]):)\s*)\b(?:abstract|and|array|as|break|callable|case|catch|clone|const|continue|declare|default|die|do|echo|else|elseif|empty|enddeclare|endfor|endforeach|endif|endswitch|endwhile|enum|eval|exit|extends|final|finally|fn|for|foreach|function|global|goto|if|implements|include|include_once|instanceof|insteadof|interface|isset|list|match|namespace|never|new|or|parent|print|private|protected|public|readonly|require|require_once|return|self|static|switch|throw|trait|try|unset|use|var|while|xor|yield|__halt_compiler)\b/i,lookbehind:!0}],"argument-name":{pattern:/([(,]\s*)\b[a-z_]\w*(?=\s*:(?!:))/i,lookbehind:!0},"class-name":[{pattern:/(\b(?:extends|implements|instanceof|new(?!\s+self|\s+static))\s+|\bcatch\s*\()\b[a-z_]\w*(?!\\)\b/i,greedy:!0,lookbehind:!0},{pattern:/(\|\s*)\b[a-z_]\w*(?!\\)\b/i,greedy:!0,lookbehind:!0},{pattern:/\b[a-z_]\w*(?!\\)\b(?=\s*\|)/i,greedy:!0},{pattern:/(\|\s*)(?:\\?\b[a-z_]\w*)+\b/i,alias:"class-name-fully-qualified",greedy:!0,lookbehind:!0,inside:{punctuation:/\\/}},{pattern:/(?:\\?\b[a-z_]\w*)+\b(?=\s*\|)/i,alias:"class-name-fully-qualified",greedy:!0,inside:{punctuation:/\\/}},{pattern:/(\b(?:extends|implements|instanceof|new(?!\s+self\b|\s+static\b))\s+|\bcatch\s*\()(?:\\?\b[a-z_]\w*)+\b(?!\\)/i,alias:"class-name-fully-qualified",greedy:!0,lookbehind:!0,inside:{punctuation:/\\/}},{pattern:/\b[a-z_]\w*(?=\s*\$)/i,alias:"type-declaration",greedy:!0},{pattern:/(?:\\?\b[a-z_]\w*)+(?=\s*\$)/i,alias:["class-name-fully-qualified","type-declaration"],greedy:!0,inside:{punctuation:/\\/}},{pattern:/\b[a-z_]\w*(?=\s*::)/i,alias:"static-context",greedy:!0},{pattern:/(?:\\?\b[a-z_]\w*)+(?=\s*::)/i,alias:["class-name-fully-qualified","static-context"],greedy:!0,inside:{punctuation:/\\/}},{pattern:/([(,?]\s*)[a-z_]\w*(?=\s*\$)/i,alias:"type-hint",greedy:!0,lookbehind:!0},{pattern:/([(,?]\s*)(?:\\?\b[a-z_]\w*)+(?=\s*\$)/i,alias:["class-name-fully-qualified","type-hint"],greedy:!0,lookbehind:!0,inside:{punctuation:/\\/}},{pattern:/(\)\s*:\s*(?:\?\s*)?)\b[a-z_]\w*(?!\\)\b/i,alias:"return-type",greedy:!0,lookbehind:!0},{pattern:/(\)\s*:\s*(?:\?\s*)?)(?:\\?\b[a-z_]\w*)+\b(?!\\)/i,alias:["class-name-fully-qualified","return-type"],greedy:!0,lookbehind:!0,inside:{punctuation:/\\/}}],constant:Q,function:{pattern:/(^|[^\\\w])\\?[a-z_](?:[\w\\]*\w)?(?=\s*\()/i,lookbehind:!0,inside:{punctuation:/\\/}},property:{pattern:/(->\s*)\w+/,lookbehind:!0},number:Y,operator:X,punctuation:K};var V={pattern:/\{\$(?:\{(?:\{[^{}]+\}|[^{}]+)\}|[^{}])+\}|(^|[^\\{])\$+(?:\w+(?:\[[^\r\n\[\]]+\]|->\w+)?)/,lookbehind:!0,inside:J.languages.php},G=[{pattern:/<<<'([^']+)'[\r\n](?:.*[\r\n])*?\1;/,alias:"nowdoc-string",greedy:!0,inside:{delimiter:{pattern:/^<<<'[^']+'|[a-z_]\w*;$/i,alias:"symbol",inside:{punctuation:/^<<<'?|[';]$/}}}},{pattern:/<<<(?:"([^"]+)"[\r\n](?:.*[\r\n])*?\1;|([a-z_]\w*)[\r\n](?:.*[\r\n])*?\2;)/i,alias:"heredoc-string",greedy:!0,inside:{delimiter:{pattern:/^<<<(?:"[^"]+"|[a-z_]\w*)|[a-z_]\w*;$/i,alias:"symbol",inside:{punctuation:/^<<<"?|[";]$/}},interpolation:V}},{pattern:/`(?:\\[\s\S]|[^\\`])*`/,alias:"backtick-quoted-string",greedy:!0},{pattern:/'(?:\\[\s\S]|[^\\'])*'/,alias:"single-quoted-string",greedy:!0},{pattern:/"(?:\\[\s\S]|[^\\"])*"/,alias:"double-quoted-string",greedy:!0,inside:{interpolation:V}}];J.languages.insertBefore("php","variable",{string:G,attribute:{pattern:/#\[(?:[^"'\/#]|\/(?![*/])|\/\/.*$|#(?!\[).*$|\/\*(?:[^*]|\*(?!\/))*\*\/|"(?:\\[\s\S]|[^\\"])*"|'(?:\\[\s\S]|[^\\'])*')+\](?=\s*[a-z$#])/im,greedy:!0,inside:{"attribute-content":{pattern:/^(#\[)[\s\S]+(?=\]$)/,lookbehind:!0,inside:{comment:Z,string:G,"attribute-class-name":[{pattern:/([^:]|^)\b[a-z_]\w*(?!\\)\b/i,alias:"class-name",greedy:!0,lookbehind:!0},{pattern:/([^:]|^)(?:\\?\b[a-z_]\w*)+/i,alias:["class-name","class-name-fully-qualified"],greedy:!0,lookbehind:!0,inside:{punctuation:/\\/}}],constant:Q,number:Y,operator:X,punctuation:K}},delimiter:{pattern:/^#\[|\]$/,alias:"punctuation"}}}}),J.hooks.add("before-tokenize",function(F){if(!/<\?/.test(F.code))return;var z=/<\?(?:[^"'/#]|\/(?![*/])|("|')(?:\\[\s\S]|(?!\1)[^\\])*\1|(?:\/\/|#(?!\[))(?:[^?\n\r]|\?(?!>))*(?=$|\?>|[\r\n])|#\[|\/\*(?:[^*]|\*(?!\/))*(?:\*\/|$))*?(?:\?>|$)/g;J.languages["markup-templating"].buildPlaceholders(F,"php",z)}),J.hooks.add("after-tokenize",function(F){J.languages["markup-templating"].tokenizePlaceholders(F,"php")})})(Prism);(function(J){var Z=J.languages.powershell={comment:[{pattern:/(^|[^`])<#[\s\S]*?#>/,lookbehind:!0},{pattern:/(^|[^`])#.*/,lookbehind:!0}],string:[{pattern:/"(?:`[\s\S]|[^`"])*"/,greedy:!0,inside:null},{pattern:/'(?:[^']|'')*'/,greedy:!0}],namespace:/\[[a-z](?:\[(?:\[[^\]]*\]|[^\[\]])*\]|[^\[\]])*\]/i,boolean:/\$(?:false|true)\b/i,variable:/\$\w+\b/,function:[/\b(?:Add|Approve|Assert|Backup|Block|Checkpoint|Clear|Close|Compare|Complete|Compress|Confirm|Connect|Convert|ConvertFrom|ConvertTo|Copy|Debug|Deny|Disable|Disconnect|Dismount|Edit|Enable|Enter|Exit|Expand|Export|Find|ForEach|Format|Get|Grant|Group|Hide|Import|Initialize|Install|Invoke|Join|Limit|Lock|Measure|Merge|Move|New|Open|Optimize|Out|Ping|Pop|Protect|Publish|Push|Read|Receive|Redo|Register|Remove|Rename|Repair|Request|Reset|Resize|Resolve|Restart|Restore|Resume|Revoke|Save|Search|Select|Send|Set|Show|Skip|Sort|Split|Start|Step|Stop|Submit|Suspend|Switch|Sync|Tee|Test|Trace|Unblock|Undo|Uninstall|Unlock|Unprotect|Unpublish|Unregister|Update|Use|Wait|Watch|Where|Write)-[a-z]+\b/i,/\b(?:ac|cat|chdir|clc|cli|clp|clv|compare|copy|cp|cpi|cpp|cvpa|dbp|del|diff|dir|ebp|echo|epal|epcsv|epsn|erase|fc|fl|ft|fw|gal|gbp|gc|gci|gcs|gdr|gi|gl|gm|gp|gps|group|gsv|gu|gv|gwmi|iex|ii|ipal|ipcsv|ipsn|irm|iwmi|iwr|kill|lp|ls|measure|mi|mount|move|mp|mv|nal|ndr|ni|nv|ogv|popd|ps|pushd|pwd|rbp|rd|rdr|ren|ri|rm|rmdir|rni|rnp|rp|rv|rvpa|rwmi|sal|saps|sasv|sbp|sc|select|set|shcm|si|sl|sleep|sls|sort|sp|spps|spsv|start|sv|swmi|tee|trcm|type|write)\b/i],keyword:/\b(?:Begin|Break|Catch|Class|Continue|Data|Define|Do|DynamicParam|Else|ElseIf|End|Exit|Filter|Finally|For|ForEach|From|Function|If|InlineScript|Parallel|Param|Process|Return|Sequence|Switch|Throw|Trap|Try|Until|Using|Var|While|Workflow)\b/i,operator:{pattern:/(^|\W)(?:!|-(?:b?(?:and|x?or)|as|(?:Not)?(?:Contains|In|Like|Match)|eq|ge|gt|is(?:Not)?|Join|le|lt|ne|not|Replace|sh[lr])\b|-[-=]?|\+[+=]?|[*\/%]=?)/i,lookbehind:!0},punctuation:/[|{}[\];(),.]/};Z.string[0].inside={function:{pattern:/(^|[^`])\$\((?:\$\([^\r\n()]*\)|(?!\$\()[^\r\n)])*\)/,lookbehind:!0,inside:Z},boolean:Z.boolean,variable:Z.variable}})(Prism);Prism.languages.python={comment:{pattern:/(^|[^\\])#.*/,lookbehind:!0,greedy:!0},"string-interpolation":{pattern:/(?:f|fr|rf)(?:("""|''')[\s\S]*?\1|("|')(?:\\.|(?!\2)[^\\\r\n])*\2)/i,greedy:!0,inside:{interpolation:{pattern:/((?:^|[^{])(?:\{\{)*)\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}])+\})+\})+\}/,lookbehind:!0,inside:{"format-spec":{pattern:/(:)[^:(){}]+(?=\}$)/,lookbehind:!0},"conversion-option":{pattern://,alias:"punctuation"},rest:null}},string:/[\s\S]+/}},"triple-quoted-string":{pattern:/(?:[rub]|br|rb)?("""|''')[\s\S]*?\1/i,greedy:!0,alias:"string"},string:{pattern:/(?:[rub]|br|rb)?("|')(?:\\.|(?!\1)[^\\\r\n])*\1/i,greedy:!0},function:{pattern:/((?:^|\s)def[ \t]+)[a-zA-Z_]\w*(?=\s*\()/g,lookbehind:!0},"class-name":{pattern:/(\bclass\s+)\w+/i,lookbehind:!0},decorator:{pattern:/(^[\t ]*)@\w+(?:\.\w+)*/m,lookbehind:!0,alias:["annotation","punctuation"],inside:{punctuation:/\./}},keyword:/\b(?:_(?=\s*:)|and|as|assert|async|await|break|case|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|match|nonlocal|not|or|pass|print|raise|return|try|while|with|yield)\b/,builtin:/\b(?:__import__|abs|all|any|apply|ascii|basestring|bin|bool|buffer|bytearray|bytes|callable|chr|classmethod|cmp|coerce|compile|complex|delattr|dict|dir|divmod|enumerate|eval|execfile|file|filter|float|format|frozenset|getattr|globals|hasattr|hash|help|hex|id|input|int|intern|isinstance|issubclass|iter|len|list|locals|long|map|max|memoryview|min|next|object|oct|open|ord|pow|property|range|raw_input|reduce|reload|repr|reversed|round|set|setattr|slice|sorted|staticmethod|str|sum|super|tuple|type|unichr|unicode|vars|xrange|zip)\b/,boolean:/\b(?:False|None|True)\b/,number:/\b0(?:b(?:_?[01])+|o(?:_?[0-7])+|x(?:_?[a-f0-9])+)\b|(?:\b\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\B\.\d+(?:_\d+)*)(?:e[+-]?\d+(?:_\d+)*)?j?(?!\w)/i,operator:/[-+%=]=?|!=|:=|\*\*?=?|\/\/?=?|<[<=>]?|>[=>]?|[&|^~]/,punctuation:/[{}[\];(),.:]/};Prism.languages.python["string-interpolation"].inside.interpolation.inside.rest=Prism.languages.python;Prism.languages.py=Prism.languages.python;Prism.languages.r={comment:/#.*/,string:{pattern:/(['"])(?:\\.|(?!\1)[^\\\r\n])*\1/,greedy:!0},"percent-operator":{pattern:/%[^%\s]*%/,alias:"operator"},boolean:/\b(?:FALSE|TRUE)\b/,ellipsis:/\.\.(?:\.|\d+)/,number:[/\b(?:Inf|NaN)\b/,/(?:\b0x[\dA-Fa-f]+(?:\.\d*)?|\b\d+(?:\.\d*)?|\B\.\d+)(?:[EePp][+-]?\d+)?[iL]?/],keyword:/\b(?:NA|NA_character_|NA_complex_|NA_integer_|NA_real_|NULL|break|else|for|function|if|in|next|repeat|while)\b/,operator:/->?>?|<(?:=|<?-)?|[>=!]=?|::?|&&?|\|\|?|[+*\/^$@~]/,punctuation:/[(){}\[\],;]/};(function(J){J.languages.ruby=J.languages.extend("clike",{comment:{pattern:/#.*|^=begin\s[\s\S]*?^=end/m,greedy:!0},"class-name":{pattern:/(\b(?:class|module)\s+|\bcatch\s+\()[\w.\\]+|\b[A-Z_]\w*(?=\s*\.\s*new\b)/,lookbehind:!0,inside:{punctuation:/[.\\]/}},keyword:/\b(?:BEGIN|END|alias|and|begin|break|case|class|def|define_method|defined|do|each|else|elsif|end|ensure|extend|for|if|in|include|module|new|next|nil|not|or|prepend|private|protected|public|raise|redo|require|rescue|retry|return|self|super|then|throw|undef|unless|until|when|while|yield)\b/,operator:/\.{2,3}|&\.|===|<?=>|[!=]?~|(?:&&|\|\||<<|>>|\*\*|[+\-*/%<>!^&|=])=?|[?:]/,punctuation:/[(){}[\].,;]/}),J.languages.insertBefore("ruby","operator",{"double-colon":{pattern:/::/,alias:"punctuation"}});var Z={pattern:/((?:^|[^\\])(?:\\{2})*)#\{(?:[^{}]|\{[^{}]*\})*\}/,lookbehind:!0,inside:{content:{pattern:/^(#\{)[\s\S]+(?=\}$)/,lookbehind:!0,inside:J.languages.ruby},delimiter:{pattern:/^#\{|\}$/,alias:"punctuation"}}};delete J.languages.ruby.function;var Q="(?:"+[/([^a-zA-Z0-9\s{(\[<=])(?:(?!\1)[^\\]|\\[\s\S])*\1/.source,/\((?:[^()\\]|\\[\s\S]|\((?:[^()\\]|\\[\s\S])*\))*\)/.source,/\{(?:[^{}\\]|\\[\s\S]|\{(?:[^{}\\]|\\[\s\S])*\})*\}/.source,/\[(?:[^\[\]\\]|\\[\s\S]|\[(?:[^\[\]\\]|\\[\s\S])*\])*\]/.source,/<(?:[^<>\\]|\\[\s\S]|<(?:[^<>\\]|\\[\s\S])*>)*>/.source].join("|")+")",Y=/(?:"(?:\\.|[^"\\\r\n])*"|(?:\b[a-zA-Z_]\w*|[^\s\0-\x7F]+)[?!]?|\$.)/.source;J.languages.insertBefore("ruby","keyword",{"regex-literal":[{pattern:RegExp(/%r/.source+Q+/[egimnosux]{0,6}/.source),greedy:!0,inside:{interpolation:Z,regex:/[\s\S]+/}},{pattern:/(^|[^/])\/(?!\/)(?:\[[^\r\n\]]+\]|\\.|[^[/\\\r\n])+\/[egimnosux]{0,6}(?=\s*(?:$|[\r\n,.;})#]))/,lookbehind:!0,greedy:!0,inside:{interpolation:Z,regex:/[\s\S]+/}}],variable:/[@$]+[a-zA-Z_]\w*(?:[?!]|\b)/,symbol:[{pattern:RegExp(/(^|[^:]):/.source+Y),lookbehind:!0,greedy:!0},{pattern:RegExp(/([\r\n{(,][ \t]*)/.source+Y+/(?=:(?!:))/.source),lookbehind:!0,greedy:!0}],"method-definition":{pattern:/(\bdef\s+)\w+(?:\s*\.\s*\w+)?/,lookbehind:!0,inside:{function:/\b\w+$/,keyword:/^self\b/,"class-name":/^\w+/,punctuation:/\./}}}),J.languages.insertBefore("ruby","string",{"string-literal":[{pattern:RegExp(/%[qQiIwWs]?/.source+Q),greedy:!0,inside:{interpolation:Z,string:/[\s\S]+/}},{pattern:/("|')(?:#\{[^}]+\}|#(?!\{)|\\(?:\r\n|[\s\S])|(?!\1)[^\\#\r\n])*\1/,greedy:!0,inside:{interpolation:Z,string:/[\s\S]+/}},{pattern:/<<[-~]?([a-z_]\w*)[\r\n](?:.*[\r\n])*?[\t ]*\1/i,alias:"heredoc-string",greedy:!0,inside:{delimiter:{pattern:/^<<[-~]?[a-z_]\w*|\b[a-z_]\w*$/i,inside:{symbol:/\b\w+/,punctuation:/^<<[-~]?/}},interpolation:Z,string:/[\s\S]+/}},{pattern:/<<[-~]?'([a-z_]\w*)'[\r\n](?:.*[\r\n])*?[\t ]*\1/i,alias:"heredoc-string",greedy:!0,inside:{delimiter:{pattern:/^<<[-~]?'[a-z_]\w*'|\b[a-z_]\w*$/i,inside:{symbol:/\b\w+/,punctuation:/^<<[-~]?'|'$/}},string:/[\s\S]+/}}],"command-literal":[{pattern:RegExp(/%x/.source+Q),greedy:!0,inside:{interpolation:Z,command:{pattern:/[\s\S]+/,alias:"string"}}},{pattern:/`(?:#\{[^}]+\}|#(?!\{)|\\(?:\r\n|[\s\S])|[^\\`#\r\n])*`/,greedy:!0,inside:{interpolation:Z,command:{pattern:/[\s\S]+/,alias:"string"}}}]}),delete J.languages.ruby.string,J.languages.insertBefore("ruby","number",{builtin:/\b(?:Array|Bignum|Binding|Class|Continuation|Dir|Exception|FalseClass|File|Fixnum|Float|Hash|IO|Integer|MatchData|Method|Module|NilClass|Numeric|Object|Proc|Range|Regexp|Stat|String|Struct|Symbol|TMS|Thread|ThreadGroup|Time|TrueClass)\b/,constant:/\b[A-Z][A-Z0-9_]*(?:[?!]|\b)/}),J.languages.rb=J.languages.ruby})(Prism);(function(J){var Z=/\/\*(?:[^*/]|\*(?!\/)|\/(?!\*)|<self>)*\*\//.source;for(var Q=0;Q<2;Q++)Z=Z.replace(/<self>/g,function(){return Z});Z=Z.replace(/<self>/g,function(){return/[^\s\S]/.source}),J.languages.rust={comment:[{pattern:RegExp(/(^|[^\\])/.source+Z),lookbehind:!0,greedy:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0,greedy:!0}],string:{pattern:/b?"(?:\\[\s\S]|[^\\"])*"|b?r(#*)"(?:[^"]|"(?!\1))*"\1/,greedy:!0},char:{pattern:/b?'(?:\\(?:x[0-7][\da-fA-F]|u\{(?:[\da-fA-F]_*){1,6}\}|.)|[^\\\r\n\t'])'/,greedy:!0},attribute:{pattern:/#!?\[(?:[^\[\]"]|"(?:\\[\s\S]|[^\\"])*")*\]/,greedy:!0,alias:"attr-name",inside:{string:null}},"closure-params":{pattern:/([=(,:]\s*|\bmove\s*)\|[^|]*\||\|[^|]*\|(?=\s*(?:\{|->))/,lookbehind:!0,greedy:!0,inside:{"closure-punctuation":{pattern:/^\||\|$/,alias:"punctuation"},rest:null}},"lifetime-annotation":{pattern:/'\w+/,alias:"symbol"},"fragment-specifier":{pattern:/(\$\w+:)[a-z]+/,lookbehind:!0,alias:"punctuation"},variable:/\$\w+/,"function-definition":{pattern:/(\bfn\s+)\w+/,lookbehind:!0,alias:"function"},"type-definition":{pattern:/(\b(?:enum|struct|trait|type|union)\s+)\w+/,lookbehind:!0,alias:"class-name"},"module-declaration":[{pattern:/(\b(?:crate|mod)\s+)[a-z][a-z_\d]*/,lookbehind:!0,alias:"namespace"},{pattern:/(\b(?:crate|self|super)\s*)::\s*[a-z][a-z_\d]*\b(?:\s*::(?:\s*[a-z][a-z_\d]*\s*::)*)?/,lookbehind:!0,alias:"namespace",inside:{punctuation:/::/}}],keyword:[/\b(?:Self|abstract|as|async|await|become|box|break|const|continue|crate|do|dyn|else|enum|extern|final|fn|for|if|impl|in|let|loop|macro|match|mod|move|mut|override|priv|pub|ref|return|self|static|struct|super|trait|try|type|typeof|union|unsafe|unsized|use|virtual|where|while|yield)\b/,/\b(?:bool|char|f(?:32|64)|[ui](?:8|16|32|64|128|size)|str)\b/],function:/\b[a-z_]\w*(?=\s*(?:::\s*<|\())/,macro:{pattern:/\b\w+!/,alias:"property"},constant:/\b[A-Z_][A-Z_\d]+\b/,"class-name":/\b[A-Z]\w*\b/,namespace:{pattern:/(?:\b[a-z][a-z_\d]*\s*::\s*)*\b[a-z][a-z_\d]*\s*::(?!\s*<)/,inside:{punctuation:/::/}},number:/\b(?:0x[\dA-Fa-f](?:_?[\dA-Fa-f])*|0o[0-7](?:_?[0-7])*|0b[01](?:_?[01])*|(?:(?:\d(?:_?\d)*)?\.)?\d(?:_?\d)*(?:[Ee][+-]?\d+)?)(?:_?(?:f32|f64|[iu](?:8|16|32|64|size)?))?\b/,boolean:/\b(?:false|true)\b/,punctuation:/->|\.\.=|\.{1,3}|::|[{}[\];(),:]/,operator:/[-+*\/%!^]=?|=[=>]?|&[&=]?|\|[|=]?|<<?=?|>>?=?|[@?]/},J.languages.rust["closure-params"].inside.rest=J.languages.rust,J.languages.rust.attribute.inside.string=J.languages.rust.string})(Prism);Prism.languages.scss=Prism.languages.extend("css",{comment:{pattern:/(^|[^\\])(?:\/\*[\s\S]*?\*\/|\/\/.*)/,lookbehind:!0},atrule:{pattern:/@[\w-](?:\([^()]+\)|[^()\s]|\s+(?!\s))*?(?=\s+[{;])/,inside:{rule:/@[\w-]+/}},url:/(?:[-a-z]+-)?url(?=\()/i,selector:{pattern:/(?=\S)[^@;{}()]?(?:[^@;{}()\s]|\s+(?!\s)|#\{\$[-\w]+\})+(?=\s*\{(?:\}|\s|[^}][^:{}]*[:{][^}]))/,inside:{parent:{pattern:/&/,alias:"important"},placeholder:/%[-\w]+/,variable:/\$[-\w]+|#\{\$[-\w]+\}/}},property:{pattern:/(?:[-\w]|\$[-\w]|#\{\$[-\w]+\})+(?=\s*:)/,inside:{variable:/\$[-\w]+|#\{\$[-\w]+\}/}}});Prism.languages.insertBefore("scss","atrule",{keyword:[/@(?:content|debug|each|else(?: if)?|extend|for|forward|function|if|import|include|mixin|return|use|warn|while)\b/i,{pattern:/( )(?:from|through)(?= )/,lookbehind:!0}]});Prism.languages.insertBefore("scss","important",{variable:/\$[-\w]+|#\{\$[-\w]+\}/});Prism.languages.insertBefore("scss","function",{"module-modifier":{pattern:/\b(?:as|hide|show|with)\b/i,alias:"keyword"},placeholder:{pattern:/%[-\w]+/,alias:"selector"},statement:{pattern:/\B!(?:default|optional)\b/i,alias:"keyword"},boolean:/\b(?:false|true)\b/,null:{pattern:/\bnull\b/,alias:"keyword"},operator:{pattern:/(\s)(?:[-+*\/%]|[=!]=|<=?|>=?|and|not|or)(?=\s)/,lookbehind:!0}});Prism.languages.scss.atrule.inside.rest=Prism.languages.scss;(function(J){var Z=[/"(?:\\[\s\S]|\$\([^)]+\)|\$(?!\()|`[^`]+`|[^"\\`$])*"/.source,/'[^']*'/.source,/\$'(?:[^'\\]|\\[\s\S])*'/.source,/<<-?\s*(["']?)(\w+)\1\s[\s\S]*?[\r\n]\2/.source].join("|");J.languages["shell-session"]={command:{pattern:RegExp(/^/.source+"(?:"+(/[^\s@:$#%*!/\\]+@[^\r\n@:$#%*!/\\]+(?::[^\0-\x1F$#%*?"<>:;|]+)?/.source+"|"+/[/~.][^\0-\x1F$#%*?"<>@:;|]*/.source)+")?"+/[$#%](?=\s)/.source+/(?:[^\\\r\n \t'"<$]|[ \t](?:(?!#)|#.*$)|\\(?:[^\r]|\r\n?)|\$(?!')|<(?!<)|<<str>>)+/.source.replace(/<<str>>/g,function(){return Z}),"m"),greedy:!0,inside:{info:{pattern:/^[^#$%]+/,alias:"punctuation",inside:{user:/^[^\s@:$#%*!/\\]+@[^\r\n@:$#%*!/\\]+/,punctuation:/:/,path:/[\s\S]+/}},bash:{pattern:/(^[$#%]\s*)\S[\s\S]*/,lookbehind:!0,alias:"language-bash",inside:J.languages.bash},"shell-symbol":{pattern:/^[$#%]/,alias:"important"}}},output:/.(?:.*(?:[\r\n]|.$))*/},J.languages["sh-session"]=J.languages.shellsession=J.languages["shell-session"]})(Prism);Prism.languages.sql={comment:{pattern:/(^|[^\\])(?:\/\*[\s\S]*?\*\/|(?:--|\/\/|#).*)/,lookbehind:!0},variable:[{pattern:/@(["'`])(?:\\[\s\S]|(?!\1)[^\\])+\1/,greedy:!0},/@[\w.$]+/],string:{pattern:/(^|[^@\\])("|')(?:\\[\s\S]|(?!\2)[^\\]|\2\2)*\2/,greedy:!0,lookbehind:!0},identifier:{pattern:/(^|[^@\\])`(?:\\[\s\S]|[^`\\]|``)*`/,greedy:!0,lookbehind:!0,inside:{punctuation:/^`|`$/}},function:/\b(?:AVG|COUNT|FIRST|FORMAT|LAST|LCASE|LEN|MAX|MID|MIN|MOD|NOW|ROUND|SUM|UCASE)(?=\s*\()/i,keyword:/\b(?:ACTION|ADD|AFTER|ALGORITHM|ALL|ALTER|ANALYZE|ANY|APPLY|AS|ASC|AUTHORIZATION|AUTO_INCREMENT|BACKUP|BDB|BEGIN|BERKELEYDB|BIGINT|BINARY|BIT|BLOB|BOOL|BOOLEAN|BREAK|BROWSE|BTREE|BULK|BY|CALL|CASCADED?|CASE|CHAIN|CHAR(?:ACTER|SET)?|CHECK(?:POINT)?|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMNS?|COMMENT|COMMIT(?:TED)?|COMPUTE|CONNECT|CONSISTENT|CONSTRAINT|CONTAINS(?:TABLE)?|CONTINUE|CONVERT|CREATE|CROSS|CURRENT(?:_DATE|_TIME|_TIMESTAMP|_USER)?|CURSOR|CYCLE|DATA(?:BASES?)?|DATE(?:TIME)?|DAY|DBCC|DEALLOCATE|DEC|DECIMAL|DECLARE|DEFAULT|DEFINER|DELAYED|DELETE|DELIMITERS?|DENY|DESC|DESCRIBE|DETERMINISTIC|DISABLE|DISCARD|DISK|DISTINCT|DISTINCTROW|DISTRIBUTED|DO|DOUBLE|DROP|DUMMY|DUMP(?:FILE)?|DUPLICATE|ELSE(?:IF)?|ENABLE|ENCLOSED|END|ENGINE|ENUM|ERRLVL|ERRORS|ESCAPED?|EXCEPT|EXEC(?:UTE)?|EXISTS|EXIT|EXPLAIN|EXTENDED|FETCH|FIELDS|FILE|FILLFACTOR|FIRST|FIXED|FLOAT|FOLLOWING|FOR(?: EACH ROW)?|FORCE|FOREIGN|FREETEXT(?:TABLE)?|FROM|FULL|FUNCTION|GEOMETRY(?:COLLECTION)?|GLOBAL|GOTO|GRANT|GROUP|HANDLER|HASH|HAVING|HOLDLOCK|HOUR|IDENTITY(?:COL|_INSERT)?|IF|IGNORE|IMPORT|INDEX|INFILE|INNER|INNODB|INOUT|INSERT|INT|INTEGER|INTERSECT|INTERVAL|INTO|INVOKER|ISOLATION|ITERATE|JOIN|KEYS?|KILL|LANGUAGE|LAST|LEAVE|LEFT|LEVEL|LIMIT|LINENO|LINES|LINESTRING|LOAD|LOCAL|LOCK|LONG(?:BLOB|TEXT)|LOOP|MATCH(?:ED)?|MEDIUM(?:BLOB|INT|TEXT)|MERGE|MIDDLEINT|MINUTE|MODE|MODIFIES|MODIFY|MONTH|MULTI(?:LINESTRING|POINT|POLYGON)|NATIONAL|NATURAL|NCHAR|NEXT|NO|NONCLUSTERED|NULLIF|NUMERIC|OFF?|OFFSETS?|ON|OPEN(?:DATASOURCE|QUERY|ROWSET)?|OPTIMIZE|OPTION(?:ALLY)?|ORDER|OUT(?:ER|FILE)?|OVER|PARTIAL|PARTITION|PERCENT|PIVOT|PLAN|POINT|POLYGON|PRECEDING|PRECISION|PREPARE|PREV|PRIMARY|PRINT|PRIVILEGES|PROC(?:EDURE)?|PUBLIC|PURGE|QUICK|RAISERROR|READS?|REAL|RECONFIGURE|REFERENCES|RELEASE|RENAME|REPEAT(?:ABLE)?|REPLACE|REPLICATION|REQUIRE|RESIGNAL|RESTORE|RESTRICT|RETURN(?:ING|S)?|REVOKE|RIGHT|ROLLBACK|ROUTINE|ROW(?:COUNT|GUIDCOL|S)?|RTREE|RULE|SAVE(?:POINT)?|SCHEMA|SECOND|SELECT|SERIAL(?:IZABLE)?|SESSION(?:_USER)?|SET(?:USER)?|SHARE|SHOW|SHUTDOWN|SIMPLE|SMALLINT|SNAPSHOT|SOME|SONAME|SQL|START(?:ING)?|STATISTICS|STATUS|STRIPED|SYSTEM_USER|TABLES?|TABLESPACE|TEMP(?:ORARY|TABLE)?|TERMINATED|TEXT(?:SIZE)?|THEN|TIME(?:STAMP)?|TINY(?:BLOB|INT|TEXT)|TOP?|TRAN(?:SACTIONS?)?|TRIGGER|TRUNCATE|TSEQUAL|TYPES?|UNBOUNDED|UNCOMMITTED|UNDEFINED|UNION|UNIQUE|UNLOCK|UNPIVOT|UNSIGNED|UPDATE(?:TEXT)?|USAGE|USE|USER|USING|VALUES?|VAR(?:BINARY|CHAR|CHARACTER|YING)|VIEW|WAITFOR|WARNINGS|WHEN|WHERE|WHILE|WITH(?: ROLLUP|IN)?|WORK|WRITE(?:TEXT)?|YEAR)\b/i,boolean:/\b(?:FALSE|NULL|TRUE)\b/i,number:/\b0x[\da-f]+\b|\b\d+(?:\.\d*)?|\B\.\d+\b/i,operator:/[-+*\/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?|\b(?:AND|BETWEEN|DIV|ILIKE|IN|IS|LIKE|NOT|OR|REGEXP|RLIKE|SOUNDS LIKE|XOR)\b/i,punctuation:/[;[\]()`,.]/};Prism.languages.swift={comment:{pattern:/(^|[^\\:])(?:\/\/.*|\/\*(?:[^/*]|\/(?!\*)|\*(?!\/)|\/\*(?:[^*]|\*(?!\/))*\*\/)*\*\/)/,lookbehind:!0,greedy:!0},"string-literal":[{pattern:RegExp(/(^|[^"#])/.source+"(?:"+/"(?:\\(?:\((?:[^()]|\([^()]*\))*\)|\r\n|[^(])|[^\\\r\n"])*"/.source+"|"+/"""(?:\\(?:\((?:[^()]|\([^()]*\))*\)|[^(])|[^\\"]|"(?!""))*"""/.source+")"+/(?!["#])/.source),lookbehind:!0,greedy:!0,inside:{interpolation:{pattern:/(\\\()(?:[^()]|\([^()]*\))*(?=\))/,lookbehind:!0,inside:null},"interpolation-punctuation":{pattern:/^\)|\\\($/,alias:"punctuation"},punctuation:/\\(?=[\r\n])/,string:/[\s\S]+/}},{pattern:RegExp(/(^|[^"#])(#+)/.source+"(?:"+/"(?:\\(?:#+\((?:[^()]|\([^()]*\))*\)|\r\n|[^#])|[^\\\r\n])*?"/.source+"|"+/"""(?:\\(?:#+\((?:[^()]|\([^()]*\))*\)|[^#])|[^\\])*?"""/.source+")\\2"),lookbehind:!0,greedy:!0,inside:{interpolation:{pattern:/(\\#+\()(?:[^()]|\([^()]*\))*(?=\))/,lookbehind:!0,inside:null},"interpolation-punctuation":{pattern:/^\)|\\#+\($/,alias:"punctuation"},string:/[\s\S]+/}}],directive:{pattern:RegExp(/#/.source+"(?:"+(/(?:elseif|if)\b/.source+"(?:[ \t]*"+/(?:![ \t]*)?(?:\b\w+\b(?:[ \t]*\((?:[^()]|\([^()]*\))*\))?|\((?:[^()]|\([^()]*\))*\))(?:[ \t]*(?:&&|\|\|))?/.source+")+")+"|"+/(?:else|endif)\b/.source+")"),alias:"property",inside:{"directive-name":/^#\w+/,boolean:/\b(?:false|true)\b/,number:/\b\d+(?:\.\d+)*\b/,operator:/!|&&|\|\||[<>]=?/,punctuation:/[(),]/}},literal:{pattern:/#(?:colorLiteral|column|dsohandle|file(?:ID|Literal|Path)?|function|imageLiteral|line)\b/,alias:"constant"},"other-directive":{pattern:/#\w+\b/,alias:"property"},attribute:{pattern:/@\w+/,alias:"atrule"},"function-definition":{pattern:/(\bfunc\s+)\w+/,lookbehind:!0,alias:"function"},label:{pattern:/\b(break|continue)\s+\w+|\b[a-zA-Z_]\w*(?=\s*:\s*(?:for|repeat|while)\b)/,lookbehind:!0,alias:"important"},keyword:/\b(?:Any|Protocol|Self|Type|actor|as|assignment|associatedtype|associativity|async|await|break|case|catch|class|continue|convenience|default|defer|deinit|didSet|do|dynamic|else|enum|extension|fallthrough|fileprivate|final|for|func|get|guard|higherThan|if|import|in|indirect|infix|init|inout|internal|is|isolated|lazy|left|let|lowerThan|mutating|none|nonisolated|nonmutating|open|operator|optional|override|postfix|precedencegroup|prefix|private|protocol|public|repeat|required|rethrows|return|right|safe|self|set|some|static|struct|subscript|super|switch|throw|throws|try|typealias|unowned|unsafe|var|weak|where|while|willSet)\b/,boolean:/\b(?:false|true)\b/,nil:{pattern:/\bnil\b/,alias:"constant"},"short-argument":/\$\d+\b/,omit:{pattern:/\b_\b/,alias:"keyword"},number:/\b(?:[\d_]+(?:\.[\de_]+)?|0x[a-f0-9_]+(?:\.[a-f0-9p_]+)?|0b[01_]+|0o[0-7_]+)\b/i,"class-name":/\b[A-Z](?:[A-Z_\d]*[a-z]\w*)?\b/,function:/\b[a-z_]\w*(?=\s*\()/i,constant:/\b(?:[A-Z_]{2,}|k[A-Z][A-Za-z_]+)\b/,operator:/[-+*/%=!<>&|^~?]+|\.[.\-+*/%=!<>&|^~?]+/,punctuation:/[{}[\]();,.:\\]/};Prism.languages.swift["string-literal"].forEach(function(J){J.inside.interpolation.inside=Prism.languages.swift});(function(J){var Z=/(?:[\w-]+|'[^'\n\r]*'|"(?:\\.|[^\\"\r\n])*")/.source;function Q(Y){return Y.replace(/__/g,function(){return Z})}J.languages.toml={comment:{pattern:/#.*/,greedy:!0},table:{pattern:RegExp(Q(/(^[\t ]*\[\s*(?:\[\s*)?)__(?:\s*\.\s*__)*(?=\s*\])/.source),"m"),lookbehind:!0,greedy:!0,alias:"class-name"},key:{pattern:RegExp(Q(/(^[\t ]*|[{,]\s*)__(?:\s*\.\s*__)*(?=\s*=)/.source),"m"),lookbehind:!0,greedy:!0,alias:"property"},string:{pattern:/"""(?:\\[\s\S]|[^\\])*?"""|'''[\s\S]*?'''|'[^'\n\r]*'|"(?:\\.|[^\\"\r\n])*"/,greedy:!0},date:[{pattern:/\b\d{4}-\d{2}-\d{2}(?:[T\s]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})?)?\b/i,alias:"number"},{pattern:/\b\d{2}:\d{2}:\d{2}(?:\.\d+)?\b/,alias:"number"}],number:/(?:\b0(?:x[\da-zA-Z]+(?:_[\da-zA-Z]+)*|o[0-7]+(?:_[0-7]+)*|b[10]+(?:_[10]+)*))\b|[-+]?\b\d+(?:_\d+)*(?:\.\d+(?:_\d+)*)?(?:[eE][+-]?\d+(?:_\d+)*)?\b|[-+]?\b(?:inf|nan)\b/,boolean:/\b(?:false|true)\b/,punctuation:/[.,=[\]{}]/}})(Prism);(function(J){var Z=J.util.clone(J.languages.typescript);J.languages.tsx=J.languages.extend("jsx",Z),delete J.languages.tsx.parameter,delete J.languages.tsx["literal-property"];var Q=J.languages.tsx.tag;Q.pattern=RegExp(/(^|[^\w$]|(?=<\/))/.source+"(?:"+Q.pattern.source+")",Q.pattern.flags),Q.lookbehind=!0})(Prism);(function(J){J.languages.typescript=J.languages.extend("javascript",{"class-name":{pattern:/(\b(?:class|extends|implements|instanceof|interface|new|type)\s+)(?!keyof\b)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?:\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>)?/,lookbehind:!0,greedy:!0,inside:null},builtin:/\b(?:Array|Function|Promise|any|boolean|console|never|number|string|symbol|unknown)\b/}),J.languages.typescript.keyword.push(/\b(?:abstract|declare|is|keyof|readonly|require)\b/,/\b(?:asserts|infer|interface|module|namespace|type)\b(?=\s*(?:[{_$a-zA-Z\xA0-\uFFFF]|$))/,/\btype\b(?=\s*(?:[\{*]|$))/),delete J.languages.typescript.parameter,delete J.languages.typescript["literal-property"];var Z=J.languages.extend("typescript",{});delete Z["class-name"],J.languages.typescript["class-name"].inside=Z,J.languages.insertBefore("typescript","function",{decorator:{pattern:/@[$\w\xA0-\uFFFF]+/,inside:{at:{pattern:/^@/,alias:"operator"},function:/^[\s\S]+/}},"generic-function":{pattern:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>(?=\s*\()/,greedy:!0,inside:{function:/^#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*/,generic:{pattern:/<[\s\S]+/,alias:"class-name",inside:Z}}}}),J.languages.ts=J.languages.typescript})(Prism);(function(J){function Z(K,V){if(J.languages[K])J.languages.insertBefore(K,"comment",{"doc-comment":V})}var Q=J.languages.markup.tag,Y={pattern:/\/\/\/.*/,greedy:!0,alias:"comment",inside:{tag:Q}},X={pattern:/'''.*/,greedy:!0,alias:"comment",inside:{tag:Q}};Z("csharp",Y),Z("fsharp",Y),Z("vbnet",X)})(Prism);(function(J){var Z=/[*&][^\s[\]{},]+/,Q=/!(?:<[\w\-%#;/?:@&=+$,.!~*'()[\]]+>|(?:[a-zA-Z\d-]*!)?[\w\-%#;/?:@&=+$.~*'()]+)?/,Y="(?:"+Q.source+"(?:[ \t]+"+Z.source+")?|"+Z.source+"(?:[ \t]+"+Q.source+")?)",X=/(?:[^\s\x00-\x08\x0e-\x1f!"#%&'*,\-:>?@[\]`{|}\x7f-\x84\x86-\x9f\ud800-\udfff\ufffe\uffff]|[?:-]<PLAIN>)(?:[ \t]*(?:(?![#:])<PLAIN>|:<PLAIN>))*/.source.replace(/<PLAIN>/g,function(){return/[^\s\x00-\x08\x0e-\x1f,[\]{}\x7f-\x84\x86-\x9f\ud800-\udfff\ufffe\uffff]/.source}),K=/"(?:[^"\\\r\n]|\\.)*"|'(?:[^'\\\r\n]|\\.)*'/.source;function V(G,F){F=(F||"").replace(/m/g,"")+"m";var z=/([:\-,[{]\s*(?:\s<<prop>>[ \t]+)?)(?:<<value>>)(?=[ \t]*(?:$|,|\]|\}|(?:[\r\n]\s*)?#))/.source.replace(/<<prop>>/g,function(){return Y}).replace(/<<value>>/g,function(){return G});return RegExp(z,F)}J.languages.yaml={scalar:{pattern:RegExp(/([\-:]\s*(?:\s<<prop>>[ \t]+)?[|>])[ \t]*(?:((?:\r?\n|\r)[ \t]+)\S[^\r\n]*(?:\2[^\r\n]+)*)/.source.replace(/<<prop>>/g,function(){return Y})),lookbehind:!0,alias:"string"},comment:/#.*/,key:{pattern:RegExp(/((?:^|[:\-,[{\r\n?])[ \t]*(?:<<prop>>[ \t]+)?)<<key>>(?=\s*:\s)/.source.replace(/<<prop>>/g,function(){return Y}).replace(/<<key>>/g,function(){return"(?:"+X+"|"+K+")"})),lookbehind:!0,greedy:!0,alias:"atrule"},directive:{pattern:/(^[ \t]*)%.+/m,lookbehind:!0,alias:"important"},datetime:{pattern:V(/\d{4}-\d\d?-\d\d?(?:[tT]|[ \t]+)\d\d?:\d{2}:\d{2}(?:\.\d*)?(?:[ \t]*(?:Z|[-+]\d\d?(?::\d{2})?))?|\d{4}-\d{2}-\d{2}|\d\d?:\d{2}(?::\d{2}(?:\.\d*)?)?/.source),lookbehind:!0,alias:"number"},boolean:{pattern:V(/false|true/.source,"i"),lookbehind:!0,alias:"important"},null:{pattern:V(/null|~/.source,"i"),lookbehind:!0,alias:"important"},string:{pattern:V(K),lookbehind:!0,greedy:!0},number:{pattern:V(/[+-]?(?:0x[\da-f]+|0o[0-7]+|(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?|\.inf|\.nan)/.source,"i"),lookbehind:!0},tag:Q,important:Z,punctuation:/---|[:[\]{}\-,|>?]|\.\.\./},J.languages.yml=J.languages.yaml})(Prism);(function(J){function Z(F){return function(){return F}}var Q=/\b(?:align|allowzero|and|anyframe|anytype|asm|async|await|break|cancel|catch|comptime|const|continue|defer|else|enum|errdefer|error|export|extern|fn|for|if|inline|linksection|nakedcc|noalias|nosuspend|null|or|orelse|packed|promise|pub|resume|return|stdcallcc|struct|suspend|switch|test|threadlocal|try|undefined|union|unreachable|usingnamespace|var|volatile|while)\b/,Y="\\b(?!"+Q.source+")(?!\\d)\\w+\\b",X=/align\s*\((?:[^()]|\([^()]*\))*\)/.source,K=/(?:\?|\bpromise->|(?:\[[^[\]]*\]|\*(?!\*)|\*\*)(?:\s*<ALIGN>|\s*const\b|\s*volatile\b|\s*allowzero\b)*)/.source.replace(/<ALIGN>/g,Z(X)),V=/(?:\bpromise\b|(?:\berror\.)?<ID>(?:\.<ID>)*(?!\s+<ID>))/.source.replace(/<ID>/g,Z(Y)),G="(?!\\s)(?:!?\\s*(?:"+K+"\\s*)*"+V+")+";J.languages.zig={comment:[{pattern:/\/\/[/!].*/,alias:"doc-comment"},/\/{2}.*/],string:[{pattern:/(^|[^\\@])c?"(?:[^"\\\r\n]|\\.)*"/,lookbehind:!0,greedy:!0},{pattern:/([\r\n])([ \t]+c?\\{2}).*(?:(?:\r\n?|\n)\2.*)*/,lookbehind:!0,greedy:!0}],char:{pattern:/(^|[^\\])'(?:[^'\\\r\n]|[\uD800-\uDFFF]{2}|\\(?:.|x[a-fA-F\d]{2}|u\{[a-fA-F\d]{1,6}\}))'/,lookbehind:!0,greedy:!0},builtin:/\B@(?!\d)\w+(?=\s*\()/,label:{pattern:/(\b(?:break|continue)\s*:\s*)\w+\b|\b(?!\d)\w+\b(?=\s*:\s*(?:\{|while\b))/,lookbehind:!0},"class-name":[/\b(?!\d)\w+(?=\s*=\s*(?:(?:extern|packed)\s+)?(?:enum|struct|union)\s*[({])/,{pattern:RegExp(/(:\s*)<TYPE>(?=\s*(?:<ALIGN>\s*)?[=;,)])|<TYPE>(?=\s*(?:<ALIGN>\s*)?\{)/.source.replace(/<TYPE>/g,Z(G)).replace(/<ALIGN>/g,Z(X))),lookbehind:!0,inside:null},{pattern:RegExp(/(\)\s*)<TYPE>(?=\s*(?:<ALIGN>\s*)?;)/.source.replace(/<TYPE>/g,Z(G)).replace(/<ALIGN>/g,Z(X))),lookbehind:!0,inside:null}],"builtin-type":{pattern:/\b(?:anyerror|bool|c_u?(?:int|long|longlong|short)|c_longdouble|c_void|comptime_(?:float|int)|f(?:16|32|64|128)|[iu](?:8|16|32|64|128|size)|noreturn|type|void)\b/,alias:"keyword"},keyword:Q,function:/\b(?!\d)\w+(?=\s*\()/,number:/\b(?:0b[01]+|0o[0-7]+|0x[a-fA-F\d]+(?:\.[a-fA-F\d]*)?(?:[pP][+-]?[a-fA-F\d]+)?|\d+(?:\.\d*)?(?:[eE][+-]?\d+)?)\b/,boolean:/\b(?:false|true)\b/,operator:/\.[*?]|\.{2,3}|[-=]>|\*\*|\+\+|\|\||(?:<<|>>|[-+*]%|[-+*/%^&|<>!=])=?|[?~]/,punctuation:/[.:,;(){}[\]]/},J.languages.zig["class-name"].forEach(function(F){if(F.inside===null)F.inside=J.languages.zig})})(Prism);function RQ3(J){let Z=J.split(".").pop()?.toLowerCase()||"";return{js:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",javascript:"javascript",ts:"typescript",tsx:"typescript",typescript:"typescript",py:"python",pyw:"python",python:"python",java:"java",c:"c",h:"c",cc:"cpp",cpp:"cpp",cxx:"cpp","c++":"cpp",hpp:"cpp",hh:"cpp",hxx:"cpp",cs:"csharp",csharp:"csharp",go:"go",golang:"go",rs:"rust",rust:"rust",rb:"ruby",ruby:"ruby",php:"php",swift:"swift",kt:"kotlin",kts:"kotlin",kotlin:"kotlin",dart:"dart",sh:"bash",bash:"bash",zsh:"bash",shell:"bash",sql:"sql",json:"json",yaml:"yaml",yml:"yaml",md:"markdown",markdown:"markdown",zig:"zig",pas:"pascal",pascal:"pascal",html:"markup",htm:"markup",xml:"markup",svg:"markup",markup:"markup",css:"css"}[Z]||"plain"}function IQ3(J,Z){switch(J.split(" ")[0]){case"keyword":case"important":case"atrule":return Z.keyword;case"string":case"char":case"regex":case"url":case"selector":case"attr-value":case"inserted":return Z.string;case"number":case"constant":case"boolean":case"symbol":return Z.number;case"comment":case"prolog":case"doctype":case"cdata":return Z.comment;case"function":case"class":return Z.function;case"variable":case"property":case"attr-name":case"class-name":return Z.variable;case"type":case"tag":return Z.type;case"operator":case"punctuation":case"delimiter":case"entity":case"builtin":case"deleted":return Z.operator;default:return Z.operator}}var oY0="unknown",bP4;function rY0(J,Z){oY0=J,bP4=Z}function kw(){return oY0}function hP4(){return bP4}function gP4(J,Z,Q){if(oY0==="unknown")return null;if(J.type!=="rgb"||Z.type!=="rgb")return null;let Y=oY0==="light"?0.15:0.12,X=(K)=>{if(K.type==="rgb")return{...K,alpha:Y};if(K.type==="index")return{...K,alpha:Y};return{type:"default",alpha:Y}};return{added:X(J),removed:X(Z)}}function PQ3(J,Z,Q){let Y=[];function X(K,V){if(typeof K==="string")Y.push({content:K,color:V});else{let G=V??IQ3(K.type,Z);if(typeof K.content==="string")Y.push({content:K.content,color:G});else if(Array.isArray(K.content))K.content.forEach((F)=>X(F,G));else X(K.content,G)}}return J.forEach((K)=>X(K,Q)),Y}function vw(J,Z,Q){try{let Y=Q?RQ3(Q):"plain";if(Y==="plain"||!Pq.default.languages[Y])return[{content:J}];let X=Pq.default.tokenize(J,Pq.default.languages[Y]);return PQ3(X,Z)}catch(Y){return[{content:J}]}}var pi=4,M0={default(J){return J!==void 0?{type:"default",alpha:J}:{type:"default"}},index(J,Z){return Z!==void 0?{type:"index",value:J,alpha:Z}:{type:"index",value:J}},rgb(J,Z,Q,Y){return Y!==void 0?{type:"rgb",value:{r:J,g:Z,b:Q},alpha:Y}:{type:"rgb",value:{r:J,g:Z,b:Q}}},none(){return{type:"none"}},black:{type:"index",value:0},red:{type:"index",value:1},green:{type:"index",value:2},yellow:{type:"index",value:3},blue:{type:"index",value:4},magenta:{type:"index",value:5},cyan:{type:"index",value:6},white:{type:"index",value:7},brightWhite:{type:"index",value:15}};function F6(J=" ",Z={},Q=1,Y){return{char:J,style:{...Z},width:Q,hyperlink:Y}}var yw=F6(" ",{});function CQ3(J,Z){return J.char===Z.char&&J.width===Z.width&&pP4(J.style,Z.style)&&di(J.hyperlink,Z.hyperlink)}function pP4(J,Z){return mP4(J.fg,Z.fg)&&mP4(J.bg,Z.bg)&&J.bold===Z.bold&&J.italic===Z.italic&&J.underline===Z.underline&&J.strikethrough===Z.strikethrough&&J.reverse===Z.reverse&&J.dim===Z.dim}function di(J,Z){if(J===Z)return!0;if(J===void 0||Z===void 0)return!1;return J.uri===Z.uri&&J.id===Z.id}function mi(J){if(J.type==="none")return;return J.alpha}function mP4(J,Z){if(J===Z)return!0;if(J===void 0||Z===void 0)return!1;if(J.type!==Z.type)return!1;if(mi(J)!==mi(Z))return!1;switch(J.type){case"none":return!0;case"default":return!0;case"index":return Z.value===J.value;case"rgb":{let Q=Z.value;return Q.r===J.value.r&&Q.g===J.value.g&&Q.b===J.value.b}default:return!1}}function ta0(J,Z){switch(J.type){case"rgb":return J.value;case"index":return Z?.[J.value]??null;case"default":return null;default:return null}}function sY0(J,Z,Q){if(J.type==="none")return Z;if(Z.type==="none"){let z=J.alpha??1;if(z>=1)return J;let q=hP4(),W=kw(),H=q??(W==="light"?{r:255,g:255,b:255}:{r:0,g:0,b:0}),U=ta0(J,Q);if(!U)return J;let D=Math.round(U.r*z+H.r*(1-z)),B=Math.round(U.g*z+H.g*(1-z)),N=Math.round(U.b*z+H.b*(1-z));return{type:"rgb",value:{r:Math.max(0,Math.min(255,D)),g:Math.max(0,Math.min(255,B)),b:Math.max(0,Math.min(255,N))}}}let Y=J.alpha??1;if(Y>=1)return J;if(Y<=0)return Z;let X=ta0(J,Q),K=ta0(Z,Q);if(!X||!K)return Y>0.5?J:Z;let V=Math.round(X.r*Y+K.r*(1-Y)),G=Math.round(X.g*Y+K.g*(1-Y)),F=Math.round(X.b*Y+K.b*(1-Y));return{type:"rgb",value:{r:Math.max(0,Math.min(255,V)),g:Math.max(0,Math.min(255,G)),b:Math.max(0,Math.min(255,F))}}}function _Q3(J,Z,Q,Y,X){let K={...Z};if(J.fg)if(Z.fg)K.fg=sY0(J.fg,Z.fg,X);else K.fg=sY0(J.fg,Y,X);if(J.bg){let V=mi(J.bg);if(J.bg.type==="none"||V===0){if(Z.bg)K.bg=Z.bg}else if(Z.bg)K.bg=sY0(J.bg,Z.bg,X);else K.bg=sY0(J.bg,Q,X)}if(J.bold!==void 0)K.bold=J.bold;if(J.italic!==void 0)K.italic=J.italic;if(J.underline!==void 0)K.underline=J.underline;if(J.strikethrough!==void 0)K.strikethrough=J.strikethrough;if(J.reverse!==void 0)K.reverse=J.reverse;if(J.dim!==void 0)K.dim=J.dim;return K}class ea0{cells;width;height;indexToRgb=[];defaultBg=M0.default();defaultFg=M0.default();constructor(J,Z){this.width=J,this.height=Z,this.cells=[],this.resize(J,Z)}setDefaultColors(J,Z){this.defaultBg=J,this.defaultFg=Z}setIndexRgbMapping(J){this.indexToRgb=J}getSize(){return{width:this.width,height:this.height}}resize(J,Z){this.width=J,this.height=Z,this.cells=Array(Z).fill(null).map(()=>Array(J).fill(null).map(()=>yw))}getCell(J,Z){if(J<0||J>=this.width||Z<0||Z>=this.height)return null;return this.cells[Z]?.[J]||null}setCell(J,Z,Q){if(J<0||J>=this.width||Z<0||Z>=this.height)return;let Y=Q.style.fg?mi(Q.style.fg):void 0,X=Q.style.bg?mi(Q.style.bg):void 0;if(Y!==void 0&&Y<1||X!==void 0&&X<1){let V=this.cells[Z]?.[J]||yw,G=_Q3(Q.style,V.style,this.defaultBg,this.defaultFg,this.indexToRgb);if(this.cells[Z])this.cells[Z][J]={char:Q.char,style:G,width:Q.width}}else if(this.cells[Z])this.cells[Z][J]={...Q,style:{...Q.style}};if(Q.width>1){for(let V=1;V<Q.width;V++)if(J+V<this.width&&this.cells[Z])this.cells[Z][J+V]=F6(" ",Q.style,1)}}setChar(J,Z,Q,Y,X){this.setCell(J,Z,F6(Q,Y,X))}clear(){for(let J=0;J<this.height;J++)for(let Z=0;Z<this.width;Z++){let Q=this.cells[J];if(Q)Q[Z]=yw}}fill(J,Z,Q,Y,X=" ",K={}){let V=F6(X,K);for(let G=0;G<Y;G++)for(let F=0;F<Q;F++)this.setCell(J+F,Z+G,V)}copyTo(J){let{width:Z,height:Q}=J.getSize();for(let Y=0;Y<Math.min(this.height,Q);Y++)for(let X=0;X<Math.min(this.width,Z);X++){let K=this.getCell(X,Y);if(K)J.setCell(X,Y,K)}}getCells(){return this.cells.map((J)=>J.map((Z)=>({...Z,style:{...Z.style}})))}getCellRows(){return this.cells}setCursor(J,Z){}clearCursor(){}setCursorShape(J){}markForRefresh(){}}class RU{frontBuffer;backBuffer;width;height;needsFullRefresh=!1;cursorPosition=null;cursorVisible=!1;cursorShape=0;constructor(J=80,Z=24){this.width=J,this.height=Z,this.frontBuffer=new ea0(J,Z),this.backBuffer=new ea0(J,Z)}getSize(){return{width:this.width,height:this.height}}resize(J,Z){this.width=J,this.height=Z,this.frontBuffer.resize(J,Z),this.backBuffer.resize(J,Z)}getBuffer(){return this.backBuffer}setDefaultColors(J,Z){this.frontBuffer.setDefaultColors(J,Z),this.backBuffer.setDefaultColors(J,Z)}setIndexRgbMapping(J){this.frontBuffer.setIndexRgbMapping(J),this.backBuffer.setIndexRgbMapping(J)}getCell(J,Z){return this.backBuffer.getCell(J,Z)}setCell(J,Z,Q){this.backBuffer.setCell(J,Z,Q)}setChar(J,Z,Q,Y,X){this.backBuffer.setChar(J,Z,Q,Y,X)}clear(){this.backBuffer.clear()}fill(J,Z,Q,Y,X=" ",K={}){this.backBuffer.fill(J,Z,Q,Y,X,K)}present(){let J=this.frontBuffer;this.frontBuffer=this.backBuffer,this.backBuffer=J}getDiff(){let J=[],Z=this.frontBuffer.getCellRows(),Q=this.backBuffer.getCellRows(),Y=(X,K,V)=>{if(V.width<=1)return!1;for(let G=1;G<V.width;G++){let F=X[K+G];if(!F)return!1;if(!(F.char===" "&&F.width===1&&pP4(F.style,V.style)&&di(F.hyperlink,V.hyperlink)))return!1}return!0};if(this.needsFullRefresh){for(let X=0;X<this.height;X++){let K=Q[X];if(!K)continue;for(let V=0;V<this.width;V++){let G=K[V]??yw;if(J.push({x:V,y:X,cell:G}),Y(K,V,G))V+=G.width-1}}return this.needsFullRefresh=!1,J}for(let X=0;X<this.height;X++){let K=Z[X],V=Q[X];if(!K||!V)continue;for(let G=0;G<this.width;G++){let F=K[G]??yw,z=V[G]??yw;if(F===yw&&z===yw)continue;if(!CQ3(F,z)){if(J.push({x:G,y:X,cell:z}),Y(V,G,z))G+=z.width-1}else if(Y(V,G,z))G+=z.width-1}}return J}getFrontBuffer(){return this.frontBuffer}getBackBuffer(){return this.backBuffer}markForRefresh(){this.needsFullRefresh=!0}get requiresFullRefresh(){return this.needsFullRefresh}setCursor(J,Z){this.cursorPosition={x:J,y:Z},this.cursorVisible=!0}setCursorPositionHint(J,Z){this.cursorPosition={x:J,y:Z}}clearCursor(){this.cursorPosition=null,this.cursorVisible=!1}getCursor(){return this.cursorPosition}isCursorVisible(){return this.cursorVisible}setCursorShape(J){this.cursorShape=J}getCursorShape(){return this.cursorShape}}var TQ3=0;function SQ3(){return`amp-${++TQ3}`}function tY0(J,Z){return{uri:J,id:Z??SQ3()}}function dP4(J){return`\x1B]8;id=${J.id};${J.uri}\x1B\\`}function eY0(){return"\x1B]8;;\x1B\\"}var cP4=new Map;function kQ3(J){return/\p{Extended_Pictographic}/u.test(J)}function vQ3(J){let Z=String.fromCodePoint(J);return!/\p{Emoji_Presentation}/u.test(Z)}function yQ3(J){return/\p{M}/u.test(J)}function xQ3(J,Z=!0){if(!J)return 0;let Q=Array.from(J);if(Z){let Y=0;for(let X=0;X<Q.length;X++){let K=Q[X];if(!K)continue;let V=K.codePointAt(0);if(!V)continue;let G=lP4(V);if(G!==0){if(X+1<Q.length){let z=Q[X+1]?.codePointAt(0);if(z===65038)G=1;else if(z===65039)G=2}if(Y===0){Y=G;break}}}return Y}else{let Y=0;for(let X of Q){if(!X)continue;let K=X.codePointAt(0);if(!K)continue;Y+=lP4(K)}return Y}}function lP4(J){if(J===9)return pi;if(yQ3(String.fromCodePoint(J))||J>=8203&&J<=8205||J===8206||J===8207||J===8288||J===65279||J>=65024&&J<=65039||J>=917760&&J<=917999||J>=127995&&J<=127999)return 0;if(fQ3(J)){if(n7()&&(J>=9728&&J<=10175||J===8986||J===8987||J===9203||J>=9193&&J<=9196||J===9200))return 1;if(vQ3(J))return 1;return 2}if(uQ3(J))return 2;return 1}function fQ3(J){let Z=String.fromCodePoint(J);return kQ3(Z)}function uQ3(J){return J>=19968&&J<=40959||J>=13312&&J<=19903||J>=131072&&J<=173791||J>=173824&&J<=177983||J>=177984&&J<=178207||J>=178208&&J<=183983||J>=183984&&J<=191471||J>=44032&&J<=55215||J>=12352&&J<=12447||J>=12448&&J<=12543||J>=12784&&J<=12799||J>=65280&&J<=65519||J>=12288&&J<=12351||J>=65281&&J<=65376||J===9001||J===9002||J>=65040&&J<=65049||J>=65072&&J<=65103||J>=127462&&J<=127487}function Y3(J,Z=!0){let Q=cP4.get(J);if(Q!==void 0)return Q;let Y=xQ3(J,Z);return cP4.set(J,Y),Y}var $o0=null;function U6(J){try{if(!$o0)$o0=new Intl.Segmenter("en",{granularity:"grapheme"});return Array.from($o0.segment(J),(Z)=>Z.segment)}catch(Z){return Array.from(J)}}function _5(J,Z=!0){let Q=0,Y=U6(J);for(let X of Y)Q+=Y3(X,Z);return Q}function uj(J,Z,Q=!0,Y="…"){if(Z<=0)return"";let X=0,K="",V=U6(J);for(let G of V){let F=Y3(G,Q);if(X+F>Z){let z=_5(Y,Q);if(X+z<=Z)K+=Y;break}K+=G,X+=F}return K}function ci(J,Z,Q=!0,Y="left",X=" "){let K=_5(J,Q);if(K>=Z)return J;let V=Z-K,G=Y3(X,Q),F=Math.floor(V/G);switch(Y){case"center":{let z=Math.floor(F/2),q=F-z;return X.repeat(z)+J+X.repeat(q)}case"right":return X.repeat(F)+J;default:return J+X.repeat(F)}}var Lv={ground:{...Object.fromEntries(Array.from({length:32},(J,Z)=>[Z,{nextState:"ground",action:"execute"}])),...Object.fromEntries(Array.from({length:95},(J,Z)=>[Z+32,{nextState:"ground",action:"print"}])),127:{nextState:"ground",action:"execute"},...Object.fromEntries(Array.from({length:128},(J,Z)=>[Z+128,{nextState:"ground",action:"print"}])),27:{nextState:"escape",action:"clear"}},escape:{...Object.fromEntries(Array.from({length:32},(J,Z)=>[Z,{nextState:"escape",action:"execute"}])),...Object.fromEntries(Array.from({length:16},(J,Z)=>[Z+32,{nextState:"escape_intermediate",action:"collect"}])),...Object.fromEntries(Array.from({length:79},(J,Z)=>[Z+48,{nextState:"ground",action:"esc_dispatch"}])),91:{nextState:"csi_entry",action:"clear"},80:{nextState:"dcs_entry",action:"clear"},93:{nextState:"osc_string",action:"osc_start"},88:{nextState:"sos_pm_apc_string",action:"ignore"},94:{nextState:"sos_pm_apc_string",action:"ignore"},95:{nextState:"sos_pm_apc_string",action:"apc_start"},79:{nextState:"escape_intermediate",action:"collect"},127:{nextState:"ground",action:"esc_dispatch"}},escape_intermediate:{...Object.fromEntries(Array.from({length:32},(J,Z)=>[Z,{nextState:"escape_intermediate",action:"execute"}])),...Object.fromEntries(Array.from({length:16},(J,Z)=>[Z+32,{nextState:"escape_intermediate",action:"collect"}])),...Object.fromEntries(Array.from({length:79},(J,Z)=>[Z+48,{nextState:"ground",action:"esc_dispatch"}])),127:{nextState:"escape_intermediate",action:"ignore"}},csi_entry:{...Object.fromEntries(Array.from({length:32},(J,Z)=>[Z,{nextState:"csi_entry",action:"execute"}])),...Object.fromEntries(Array.from({length:16},(J,Z)=>[Z+32,{nextState:"csi_intermediate",action:"collect"}])),...Object.fromEntries(Array.from({length:16},(J,Z)=>[Z+48,{nextState:"csi_param",action:"param"}])),...Object.fromEntries(Array.from({length:4},(J,Z)=>[Z+60,{nextState:"csi_param",action:"collect"}])),...Object.fromEntries(Array.from({length:63},(J,Z)=>[Z+64,{nextState:"ground",action:"csi_dispatch"}])),127:{nextState:"csi_entry",action:"ignore"}},csi_param:{...Object.fromEntries(Array.from({length:32},(J,Z)=>[Z,{nextState:"csi_param",action:"execute"}])),...Object.fromEntries(Array.from({length:16},(J,Z)=>[Z+32,{nextState:"csi_intermediate",action:"collect"}])),...Object.fromEntries(Array.from({length:16},(J,Z)=>[Z+48,{nextState:"csi_param",action:"param"}])),58:{nextState:"csi_param",action:"param"},...Object.fromEntries(Array.from({length:4},(J,Z)=>[Z+60,{nextState:"csi_ignore",action:"ignore"}])),...Object.fromEntries(Array.from({length:63},(J,Z)=>[Z+64,{nextState:"ground",action:"csi_dispatch"}])),127:{nextState:"csi_param",action:"ignore"}},csi_intermediate:{...Object.fromEntries(Array.from({length:32},(J,Z)=>[Z,{nextState:"csi_intermediate",action:"execute"}])),...Object.fromEntries(Array.from({length:16},(J,Z)=>[Z+32,{nextState:"csi_intermediate",action:"collect"}])),...Object.fromEntries(Array.from({length:16},(J,Z)=>[Z+48,{nextState:"csi_ignore",action:"ignore"}])),...Object.fromEntries(Array.from({length:63},(J,Z)=>[Z+64,{nextState:"ground",action:"csi_dispatch"}])),127:{nextState:"csi_intermediate",action:"ignore"}},csi_ignore:{...Object.fromEntries(Array.from({length:32},(J,Z)=>[Z,{nextState:"csi_ignore",action:"execute"}])),...Object.fromEntries(Array.from({length:64},(J,Z)=>[Z+32,{nextState:"csi_ignore",action:"ignore"}])),...Object.fromEntries(Array.from({length:63},(J,Z)=>[Z+64,{nextState:"ground",action:"ignore"}])),127:{nextState:"csi_ignore",action:"ignore"}},dcs_entry:{...Object.fromEntries(Array.from({length:32},(J,Z)=>[Z,{nextState:"dcs_entry",action:"ignore"}])),...Object.fromEntries(Array.from({length:16},(J,Z)=>[Z+32,{nextState:"dcs_intermediate",action:"collect"}])),...Object.fromEntries(Array.from({length:16},(J,Z)=>[Z+48,{nextState:"dcs_param",action:"param"}])),...Object.fromEntries(Array.from({length:4},(J,Z)=>[Z+60,{nextState:"dcs_param",action:"collect"}])),...Object.fromEntries(Array.from({length:63},(J,Z)=>[Z+64,{nextState:"dcs_passthrough",action:"hook"}])),127:{nextState:"dcs_entry",action:"ignore"}},dcs_param:{...Object.fromEntries(Array.from({length:32},(J,Z)=>[Z,{nextState:"dcs_param",action:"ignore"}])),...Object.fromEntries(Array.from({length:16},(J,Z)=>[Z+32,{nextState:"dcs_intermediate",action:"collect"}])),...Object.fromEntries(Array.from({length:16},(J,Z)=>[Z+48,{nextState:"dcs_param",action:"param"}])),58:{nextState:"dcs_param",action:"param"},...Object.fromEntries(Array.from({length:4},(J,Z)=>[Z+60,{nextState:"dcs_ignore",action:"ignore"}])),...Object.fromEntries(Array.from({length:63},(J,Z)=>[Z+64,{nextState:"dcs_passthrough",action:"hook"}])),127:{nextState:"dcs_param",action:"ignore"}},dcs_intermediate:{...Object.fromEntries(Array.from({length:32},(J,Z)=>[Z,{nextState:"dcs_intermediate",action:"ignore"}])),...Object.fromEntries(Array.from({length:16},(J,Z)=>[Z+32,{nextState:"dcs_intermediate",action:"collect"}])),...Object.fromEntries(Array.from({length:16},(J,Z)=>[Z+48,{nextState:"dcs_ignore",action:"ignore"}])),...Object.fromEntries(Array.from({length:63},(J,Z)=>[Z+64,{nextState:"dcs_passthrough",action:"hook"}])),127:{nextState:"dcs_intermediate",action:"ignore"}},dcs_passthrough:{156:{nextState:"ground",action:"unhook"},27:{nextState:"ground",action:"unhook"},...Object.fromEntries(Array.from({length:256},(J,Z)=>{if(Z===156||Z===27)return[Z,void 0];return[Z,{nextState:"dcs_passthrough",action:"put"}]}).filter(([,J])=>J!==void 0))},dcs_ignore:{...Object.fromEntries(Array.from({length:256},(J,Z)=>[Z,{nextState:"dcs_ignore",action:"ignore"}])),156:{nextState:"ground",action:"ignore"},27:{nextState:"escape",action:"clear"}},osc_string:{...Object.fromEntries(Array.from({length:32},(J,Z)=>[Z,{nextState:"osc_string",action:"ignore"}])),...Object.fromEntries(Array.from({length:128},(J,Z)=>[Z+32,{nextState:"osc_string",action:"osc_put"}])),7:{nextState:"ground",action:"osc_end"},156:{nextState:"ground",action:"osc_end"},27:{nextState:"escape",action:"clear"}},sos_pm_apc_string:{...Object.fromEntries(Array.from({length:32},(J,Z)=>[Z,{nextState:"sos_pm_apc_string",action:"ignore"}])),...Object.fromEntries(Array.from({length:128},(J,Z)=>[Z+32,{nextState:"sos_pm_apc_string",action:"apc_put"}])),156:{nextState:"ground",action:"apc_end"},27:{nextState:"escape",action:"clear"}}},iP4={24:{nextState:"ground",action:"execute"},26:{nextState:"ground",action:"execute"},27:{nextState:"escape",action:"clear"}};Object.keys(Lv).forEach((J)=>{let Z=J;if(Z==="dcs_passthrough"){let{27:Q,...Y}=iP4;Object.assign(Lv[Z],Y)}else Object.assign(Lv[Z],iP4)});class li{context;eventHandlers=[];constructor(){this.context={state:"ground",private:[],intermediates:[],final:"",params:[],paramBuffer:[],subparamBuffer:[],currentSubparams:[],oscData:[],dcsData:[],apcData:[],printBuffer:[],textBuffer:"",oscEscSeen:!1,apcEscSeen:!1,dcsEscSeen:!1}}onEvent(J){this.eventHandlers.push(J)}offEvent(J){let Z=this.eventHandlers.indexOf(J);if(Z!==-1)this.eventHandlers.splice(Z,1)}parse(J){let Z=typeof J==="string"?this.stringToBytes(J):J;for(let Q of Z)this.processByte(Q)}flush(){this.flushPrintBuffer(),this.flushTextBuffer()}stringToBytes(J){return new TextEncoder().encode(J)}processByte(J){if(this.context.state==="osc_string"&&J===27){this.context.oscEscSeen=!0;return}if(this.context.oscEscSeen&&J===92){this.context.oscEscSeen=!1,this.performAction("osc_end",J),this.context.state="ground";return}if(this.context.oscEscSeen)this.context.oscEscSeen=!1;if(this.context.state==="sos_pm_apc_string"&&J===27){this.context.apcEscSeen=!0;return}if(this.context.apcEscSeen&&J===92){this.context.apcEscSeen=!1,this.performAction("apc_end",J),this.context.state="ground";return}if(this.context.apcEscSeen){this.context.apcEscSeen=!1,this.performAction("clear",27),this.context.state="escape";let Y=Lv["escape"][J];if(Y)this.performAction(Y.action,J),this.context.state=Y.nextState;return}let Z=Lv[this.context.state][J];if(!Z)return;let Q=this.context.state;if(this.performAction(Z.action,J),this.context.state==="ground"&&Z.nextState!=="ground")this.flushTextBuffer();if(this.context.state===Q)this.context.state=Z.nextState}performAction(J,Z){if(this.context.dcsEscSeen&&Z===92){this.context.dcsEscSeen=!1;return}if(this.context.dcsEscSeen)this.context.dcsEscSeen=!1;switch(J){case"ignore":break;case"print":this.addToPrintBuffer(Z);break;case"execute":this.flushTextBuffer(),this.emitEvent({type:"execute",code:Z});break;case"clear":this.flushTextBuffer(),this.context.private.length=0,this.context.intermediates.length=0,this.context.final="",this.context.params=[],this.context.oscEscSeen=!1,this.context.paramBuffer.length=0,this.context.subparamBuffer.length=0,this.context.currentSubparams=[],this.context.oscData.length=0,this.context.dcsData.length=0;break;case"collect":if(Z>=60&&Z<=63)this.context.private.push(String.fromCharCode(Z));else this.context.intermediates.push(String.fromCharCode(Z));break;case"param":if(Z>=48&&Z<=57)if(this.context.currentSubparams.length>0)this.context.subparamBuffer.push(String.fromCharCode(Z));else this.context.paramBuffer.push(String.fromCharCode(Z));else if(Z===59)this.finishParameter();else if(Z===58)this.finishSubparameter();break;case"esc_dispatch":this.emitEvent({type:"escape",intermediates:this.context.intermediates.join(""),final:String.fromCharCode(Z)});break;case"csi_dispatch":this.finishParameter(),this.emitEvent({type:"csi",private:this.context.private.join(""),intermediates:this.context.intermediates.join(""),final:String.fromCharCode(Z),params:[...this.context.params]});break;case"hook":this.finishParameter(),this.context.dcsData.length=0,this.context.final=String.fromCharCode(Z);break;case"put":this.context.dcsData.push(String.fromCharCode(Z));break;case"unhook":this.emitEvent({type:"dcs",private:this.context.private.join(""),intermediates:this.context.intermediates.join(""),final:this.context.final,params:[...this.context.params],data:this.context.dcsData.join("")}),this.context.dcsEscSeen=Z===27;break;case"osc_start":this.context.oscData.length=0,this.context.oscEscSeen=!1;break;case"osc_put":this.context.oscData.push(String.fromCharCode(Z));break;case"osc_end":this.emitEvent({type:"osc",data:this.context.oscData.join("")});break;case"apc_start":this.context.apcData.length=0;break;case"apc_put":this.context.apcData.push(String.fromCharCode(Z));break;case"apc_end":this.emitEvent({type:"apc",data:this.context.apcData.join("")});break}}finishSubparameter(){if(this.context.currentSubparams.length===0)if(this.context.paramBuffer.length>0){let J=parseInt(this.context.paramBuffer.join(""),10);this.context.currentSubparams.push(isNaN(J)?0:J),this.context.paramBuffer.length=0}else this.context.currentSubparams.push(0);else if(this.context.subparamBuffer.length>0){let J=parseInt(this.context.subparamBuffer.join(""),10);this.context.currentSubparams.push(isNaN(J)?0:J),this.context.subparamBuffer.length=0}else this.context.currentSubparams.push(0)}finishParameter(){if(this.context.currentSubparams.length>0){this.finishSubparameter();let[J,...Z]=this.context.currentSubparams,Q={value:J??0};if(Z.length>0)Q.subparams=Z;this.context.params.push(Q),this.context.currentSubparams=[]}else if(this.context.paramBuffer.length>0){let J=parseInt(this.context.paramBuffer.join(""),10);this.context.params.push({value:isNaN(J)?0:J}),this.context.paramBuffer.length=0}else this.context.params.push({value:0})}addToPrintBuffer(J){this.context.printBuffer.push(J),this.tryEmitGraphemes()}tryEmitAccumulatedGraphemes(){if(this.context.textBuffer.length>1000){this.flushTextBuffer();return}if(this.context.flushTimeout)clearTimeout(this.context.flushTimeout);this.context.flushTimeout=setTimeout(()=>{if(this.context.textBuffer.length>0)this.flushTextBuffer()},1)}tryEmitGraphemes(){if(this.context.printBuffer.length===0)return;let J=0,Z=this.context.printBuffer;for(let Q=0;Q<Z.length;Q++){let Y=Z[Q];if(Y===void 0)continue;if(Y<128)J=Q+1;else if((Y&224)===192){let X=Z[Q+1];if(Q+1<Z.length&&X!==void 0&&(X&192)===128)J=Q+2,Q++;else break}else if((Y&240)===224){let X=Z[Q+1],K=Z[Q+2];if(Q+2<Z.length&&X!==void 0&&(X&192)===128&&K!==void 0&&(K&192)===128)J=Q+3,Q+=2;else break}else if((Y&248)===240){let X=Z[Q+1],K=Z[Q+2],V=Z[Q+3];if(Q+3<Z.length&&X!==void 0&&(X&192)===128&&K!==void 0&&(K&192)===128&&V!==void 0&&(V&192)===128)J=Q+4,Q+=3;else break}else if((Y&192)===128){this.emitEvent({type:"print",grapheme:"�"}),this.context.printBuffer.splice(0,Q+1),this.tryEmitGraphemes();return}else{this.emitEvent({type:"print",grapheme:"�"}),this.context.printBuffer.splice(0,Q+1),this.tryEmitGraphemes();return}}if(J>0){let Q=new Uint8Array(Z.slice(0,J)),X=new TextDecoder("utf-8",{fatal:!1}).decode(Q);if(this.context.textBuffer+=X,this.tryEmitAccumulatedGraphemes(),this.context.printBuffer.splice(0,J),this.context.printBuffer.length>0)this.tryEmitGraphemes()}}flushPrintBuffer(){if(this.context.printBuffer.length>0){let J=new Uint8Array(this.context.printBuffer),Q=new TextDecoder("utf-8",{fatal:!1}).decode(J);if(Q.length>0)this.context.textBuffer+=Q}this.context.printBuffer=[]}flushTextBuffer(){if(this.context.flushTimeout)clearTimeout(this.context.flushTimeout),delete this.context.flushTimeout;if(this.context.textBuffer.length>0){let J=U6(this.context.textBuffer);for(let Z of J)this.emitEvent({type:"print",grapheme:Z});this.context.textBuffer=""}}emitEvent(J){for(let Z of this.eventHandlers)Z(J)}reset(){this.flushPrintBuffer(),this.flushTextBuffer(),this.context={state:"ground",private:[],intermediates:[],final:"",params:[],paramBuffer:[],subparamBuffer:[],currentSubparams:[],oscData:[],dcsData:[],apcData:[],printBuffer:[],textBuffer:"",oscEscSeen:!1,apcEscSeen:!1,dcsEscSeen:!1}}getState(){return this.context.state}}var nP4={57348:"Insert",57349:"Delete",57350:"ArrowLeft",57351:"ArrowRight",57352:"ArrowUp",57353:"ArrowDown",57354:"PageUp",57355:"PageDown",57356:"Home",57357:"End",57358:"CapsLock",57359:"ScrollLock",57360:"NumLock",57361:"PrintScreen",57362:"Pause",57363:"ContextMenu",57364:"F1",57365:"F2",57366:"F3",57367:"F4",57368:"F5",57369:"F6",57370:"F7",57371:"F8",57372:"F9",57373:"F10",57374:"F11",57375:"F12",57376:"F13",57377:"F14",57378:"F15",57379:"F16",57380:"F17",57381:"F18",57382:"F19",57383:"F20",57384:"F21",57385:"F22",57386:"F23",57387:"F24",57388:"F25",57389:"F26",57390:"F27",57391:"F28",57392:"F29",57393:"F30",57394:"F31",57395:"F32",57396:"F33",57397:"F34",57398:"F35",57399:"0",57400:"1",57401:"2",57402:"3",57403:"4",57404:"5",57405:"6",57406:"7",57407:"8",57408:"9",57409:".",57410:"/",57411:"*",57412:"-",57413:"+",57414:"Enter",57415:"=",57416:",",57417:"ArrowLeft",57418:"ArrowRight",57419:"ArrowUp",57420:"ArrowDown",57421:"PageUp",57422:"PageDown",57423:"Home",57424:"End",57425:"Insert",57426:"Delete",57427:"Clear",57428:"MediaPlay",57429:"MediaPause",57430:"MediaPlayPause",57431:"MediaReverse",57432:"MediaStop",57433:"MediaFastForward",57434:"MediaRewind",57435:"MediaTrackNext",57436:"MediaTrackPrevious",57437:"MediaRecord",57438:"AudioVolumeDown",57439:"AudioVolumeUp",57440:"AudioVolumeMute",57441:"ShiftLeft",57442:"ControlLeft",57443:"AltLeft",57444:"MetaLeft",57445:"HyperLeft",57446:"MetaLeft",57447:"ShiftRight",57448:"ControlRight",57449:"AltRight",57450:"MetaRight",57451:"HyperRight",57452:"MetaRight",57453:"AltGraph",57454:"ISOLevel5Shift"},bQ3=1,hQ3=2,gQ3=4,mQ3=8,pQ3=16;class bj{lexer;keyHandlers=[];deviceAttributesHandlers=[];decrqssHandlers=[];dcsHandlers=[];oscHandlers=[];apcHandlers=[];pasteHandlers=[];sgrMouseHandlers=[];mouseHandlers=[];focusHandlers=[];resizeHandlers=[];colorPaletteChangeHandlers=[];cursorPositionReportHandlers=[];escapeTimeout=null;ESCAPE_TIMEOUT_MS=25;pendingEscape=!1;sgrToMouseConverter=gi;inPaste=!1;pasteBuffer="";pressedWin32Keys=new Set;constructor(){this.lexer=new li,this.lexer.onEvent(this.handleLexicalEvent.bind(this))}onEvent(J){this.lexer.onEvent(J)}offEvent(J){this.lexer.offEvent(J)}onKey(J){this.keyHandlers.push(J)}offKey(J){let Z=this.keyHandlers.indexOf(J);if(Z!==-1)this.keyHandlers.splice(Z,1)}onDeviceAttributes(J){this.deviceAttributesHandlers.push(J)}onDecrqss(J){this.decrqssHandlers.push(J)}onDcs(J){this.dcsHandlers.push(J)}onOsc(J){this.oscHandlers.push(J)}onApc(J){this.apcHandlers.push(J)}onPaste(J){this.pasteHandlers.push(J)}onSgrMouse(J){this.sgrMouseHandlers.push(J)}onMouse(J){this.mouseHandlers.push(J)}onFocus(J){this.focusHandlers.push(J)}onResize(J){this.resizeHandlers.push(J)}onColorPaletteChange(J){this.colorPaletteChangeHandlers.push(J)}onCursorPositionReport(J){this.cursorPositionReportHandlers.push(J)}setSgrToMouseConverter(J){this.sgrToMouseConverter=J}parse(J){if(this.isStandaloneEscape(J)){if(this.escapeTimeout)clearTimeout(this.escapeTimeout),this.escapeTimeout=null;this.scheduleEscapeTimeout(),this.lexer.parse(J);return}if(this.escapeTimeout)clearTimeout(this.escapeTimeout),this.escapeTimeout=null,this.pendingEscape=!1;this.lexer.parse(J)}isStandaloneEscape(J){if(typeof J==="string")return J.length===1&&J.charCodeAt(0)===27;else return J.length===1&&J[0]===27}scheduleEscapeTimeout(){this.pendingEscape=!0,this.escapeTimeout=setTimeout(()=>{this.pendingEscape=!1,this.lexer.reset();let J={type:"key",key:"Escape",shiftKey:!1,ctrlKey:!1,altKey:!1,metaKey:!1};this.emitKeyEvent(J),this.escapeTimeout=null},this.ESCAPE_TIMEOUT_MS)}clearEscapeTimeout(){if(this.escapeTimeout)clearTimeout(this.escapeTimeout),this.escapeTimeout=null;this.pendingEscape=!1}flush(){this.lexer.flush()}reset(){this.clearEscapeTimeout(),this.pressedWin32Keys.clear(),this.lexer.reset()}handleLexicalEvent(J){switch(J.type){case"print":this.handlePrintEvent(J);break;case"execute":this.handleExecuteEvent(J);break;case"csi":this.handleCsiEvent(J);break;case"dcs":this.handleDcsEvent(J);break;case"osc":this.handleOscEvent(J);break;case"apc":this.handleApcEvent(J);break;case"escape":this.handleEscapeEvent(J);break}}handlePrintEvent(J){if(this.inPaste){this.pasteBuffer+=J.grapheme;return}if(this.pendingEscape){this.clearEscapeTimeout();let Q={type:"key",key:J.grapheme,shiftKey:this.isShifted(J.grapheme),ctrlKey:!1,altKey:!0,metaKey:!1};this.emitKeyEvent(Q);return}let Z={type:"key",key:J.grapheme,shiftKey:this.isShifted(J.grapheme),ctrlKey:!1,altKey:!1,metaKey:!1};this.emitKeyEvent(Z)}handleExecuteEvent(J){if(this.inPaste)switch(J.code){case 10:this.pasteBuffer+=`
|
|
6238
6238
|
`;return;case 13:this.pasteBuffer+="\r";return;case 9:this.pasteBuffer+="\t";return;default:return}if(J.code===10){let Q={type:"key",key:"Enter",shiftKey:!0,ctrlKey:!1,altKey:!1,metaKey:!1};this.emitKeyEvent(Q);return}if(J.code===13&&this.lexer.getState()==="escape"){let Q={type:"key",key:"Enter",shiftKey:!1,ctrlKey:!1,altKey:!0,metaKey:!1};this.emitKeyEvent(Q),this.lexer.reset();return}if(this.lexer.getState()==="escape"&&this.isControlCharacter(J.code)){let Q=this.controlCharacterToGrapheme(J.code);if(Q&&J.code!==27){let Y={type:"key",key:Q,shiftKey:!1,ctrlKey:this.isControlCharacter(J.code)&&J.code!==127&&J.code!==8&&J.code!==9&&J.code!==10&&J.code!==13&&J.code!==27,altKey:!0,metaKey:!1};this.emitKeyEvent(Y),this.lexer.reset();return}}let Z=this.controlCharacterToGrapheme(J.code);if(Z){let Q={type:"key",key:Z,shiftKey:!1,ctrlKey:this.isControlCharacter(J.code)&&J.code!==127&&J.code!==8&&J.code!==9&&J.code!==10&&J.code!==13&&J.code!==27,altKey:!1,metaKey:!1};this.emitKeyEvent(Q)}}controlCharacterToGrapheme(J){switch(J){case 8:return"Backspace";case 9:return"Tab";case 10:return"Enter";case 13:return"Enter";case 27:return"Escape";case 127:return"Backspace";case 0:return"@";case 1:return"a";case 2:return"b";case 3:return"c";case 4:return"d";case 5:return"e";case 6:return"f";case 7:return"g";case 11:return"k";case 12:return"l";case 14:return"n";case 15:return"o";case 16:return"p";case 17:return"q";case 18:return"r";case 19:return"s";case 20:return"t";case 21:return"u";case 22:return"v";case 23:return"w";case 24:return"x";case 25:return"y";case 26:return"z";default:return null}}isControlCharacter(J){return J>=0&&J<=26||J===27||J===127}handleEscapeEvent(J){this.clearEscapeTimeout();let Z=this.escapeToKey(J);if(Z)this.emitKeyEvent(Z)}handleDcsEvent(J){for(let Z of this.dcsHandlers)Z(J)}handleOscEvent(J){for(let Z of this.oscHandlers)Z(J)}handleApcEvent(J){for(let Z of this.apcHandlers)Z(J)}handleCsiEvent(J){if(this.clearEscapeTimeout(),this.handleBracketedPaste(J))return;let Z=this.csiToFocus(J);if(Z){this.emitFocusEvent(Z);return}let Q=this.csiToCursorPositionReport(J);if(Q){this.emitCursorPositionReportEvent(Q);return}let Y=this.csiToDeviceAttributes(J);if(Y){this.emitDeviceAttributesEvent(Y);return}let X=this.csiToDecrqss(J);if(X){this.emitDecrqssEvent(X);return}let K=this.csiToKittyKeyboardResponse(J);if(K){this.emitDecrqssEvent(K);return}let V=this.csiToInBandResize(J);if(V){this.emitResizeEvent(V);return}if(J.final==="n"&&J.private==="?"&&J.params[0]?.value===997){let q=J.params[1]?.value??0;_.info("Received color palette change notification (mode 2031)",{mode:q}),this.emitColorPaletteChangeEvent({type:"colorPaletteChange",colorIndex:-1,value:""});return}let G=this.csiToSgrMouse(J);if(G){this.emitSgrMouseEvent(G);let q=this.sgrToMouseConverter(G);this.emitMouseEvent(q);return}let F=this.csiToWin32InputModeKey(J);if(F){this.emitKeyEvent(F);return}let z=this.csiToKey(J);if(z)this.emitKeyEvent(z)}escapeToKey(J){if(J.intermediates==="O"){if(J.final==="P")return this.createKeyEvent("F1");if(J.final==="Q")return this.createKeyEvent("F2");if(J.final==="R")return this.createKeyEvent("F3");if(J.final==="S")return this.createKeyEvent("F4")}if(J.intermediates===""&&J.final.length===1){let Z=J.final.charCodeAt(0);if(Z>=32&&Z<=126)return{type:"key",key:J.final,shiftKey:this.isShifted(J.final),ctrlKey:!1,altKey:!0,metaKey:!1};else if(Z==127)return{type:"key",key:"Backspace",shiftKey:!1,ctrlKey:!1,altKey:!0,metaKey:!1}}return null}csiToKey(J){let{final:Z,params:Q}=J;if(Q.length===0||Q.length===1&&Q[0]?.value===0)Q=[{value:1}];let Y=null,X,K={shift:!1,ctrl:!1,alt:!1,meta:!1},V,G="";if(Q.length>=1){let F=Q[0]?.value??1,q=Q[0]?.subparams?.[1];if(F===1&&Z==="Z")Y="Tab",K.shift=!0;else Y=this.getSpecialKey(F,Z)??this.unicodeToKey(F);if(q!==void 0)X=this.unicodeToKey(q)??void 0}if(Q.length>=2){let F=Q[1];K=this.parseModifiers(F?.value??1),V=this.kittyEventTypeToName(F?.subparams?.[0])}if(Q.length>=3){let F=Q[2]?.value;if(Z==="~"&&Q[0]?.value===27)Y=this.unicodeToKey(F??0);else if(Z==="u"&&V===void 0)V=this.kittyEventTypeToName(F)}if(!Y)return null;if(G===""&&K.shift&&!K.ctrl&&!K.alt&&!K.meta){let F=this.keyToUnicode(Y);if(F&&F>=32&&F<=126)G=Y.toUpperCase()}return this.createKeyEventWithModifiers(Y,K,G,X,V)}csiToWin32InputModeKey(J){if(J.final!=="_"||J.private!==""||J.params.length<6)return null;let Z=J.params[0]?.value??0,Q=J.params[1]?.value??0,Y=J.params[2]?.value??0,X=J.params[3]?.value===1,K=J.params[4]?.value??0,V=J.params[5]?.value??1,G=(Y!==0?this.unicodeToKey(Y):null)??this.win32VirtualKeyToKey(Z);if(!G)return null;let F=this.win32ControlStateToModifiers(K),z=`${Z}:${Q}`,q;if(X)q=V>1||this.pressedWin32Keys.has(z)?"repeat":"press",this.pressedWin32Keys.add(z);else q="release",this.pressedWin32Keys.delete(z);return this.createKeyEventWithModifiers(G,F,void 0,void 0,q)}kittyEventTypeToName(J){switch(J){case 1:return"press";case 2:return"repeat";case 3:return"release";default:return}}win32ControlStateToModifiers(J){return{shift:(J&pQ3)!==0,ctrl:(J&(mQ3|gQ3))!==0,alt:(J&(hQ3|bQ3))!==0,meta:!1}}win32VirtualKeyToKey(J){if(J>=48&&J<=57)return String.fromCharCode(J);if(J>=65&&J<=90)return String.fromCharCode(J+32);if(J>=96&&J<=105)return String(J-96);if(J>=112&&J<=135)return`F${J-111}`;switch(J){case 8:return"Backspace";case 9:return"Tab";case 12:return"Clear";case 13:return"Enter";case 16:return"Shift";case 17:return"Control";case 18:return"Alt";case 19:return"Pause";case 20:return"CapsLock";case 27:return"Escape";case 32:return" ";case 33:return"PageUp";case 34:return"PageDown";case 35:return"End";case 36:return"Home";case 37:return"ArrowLeft";case 38:return"ArrowUp";case 39:return"ArrowRight";case 40:return"ArrowDown";case 44:return"PrintScreen";case 45:return"Insert";case 46:return"Delete";case 106:return"*";case 107:return"+";case 109:return"-";case 110:return".";case 111:return"/";case 144:return"NumLock";case 145:return"ScrollLock";case 160:return"ShiftLeft";case 161:return"ShiftRight";case 162:return"ControlLeft";case 163:return"ControlRight";case 164:return"AltLeft";case 165:return"AltRight";case 91:return"MetaLeft";case 92:return"MetaRight";case 93:return"ContextMenu";default:return null}}parseModifiers(J){if(J===0||J===1)return{shift:!1,ctrl:!1,alt:!1,meta:!1};let Z=J-1;return{shift:(Z&1)!==0,alt:(Z&2)!==0,ctrl:(Z&4)!==0,meta:(Z&8)!==0}}unicodeToKey(J){if(J===13)return"Enter";if(J===9)return"Tab";if(J===27)return"Escape";if(J===127)return"Backspace";if(J===32)return" ";if(J>=1&&J<=26)return String.fromCharCode(J+96);if(nP4[J])return nP4[J];if(J>=32&&J<=126)return String.fromCharCode(J);if(J>126)try{return String.fromCharCode(J)}catch{return null}return null}createKeyEvent(J){return{type:"key",key:J,shiftKey:!1,ctrlKey:!1,altKey:!1,metaKey:!1}}createKeyEventWithModifiers(J,Z,Q,Y,X){let K={type:"key",key:J,shiftKey:Z.shift,ctrlKey:Z.ctrl,altKey:Z.alt,metaKey:Z.meta};if(Y!==void 0)K.code=Y;if(X!==void 0)K.eventType=X;return K}static SPECIAL_KEYS=new Map([["1:A","ArrowUp"],["1:B","ArrowDown"],["1:C","ArrowRight"],["1:D","ArrowLeft"],["1:H","Home"],["1:F","End"],["1:P","F1"],["1:Q","F2"],["1:R","F3"],["1:S","F4"],["1:~","Home"],["2:~","Insert"],["3:~","Delete"],["4:~","End"],["5:~","PageUp"],["6:~","PageDown"],["7:~","Home"],["8:~","End"],["9:~","Tab"],["11:~","F1"],["12:~","F2"],["13:~","F3"],["14:~","F4"],["15:~","F5"],["17:~","F6"],["18:~","F7"],["19:~","F8"],["20:~","F9"],["21:~","F10"],["23:~","F11"],["24:~","F12"]]);getSpecialKey(J,Z){let Q=`${J}:${Z}`;return bj.SPECIAL_KEYS.get(Q)||null}keyToUnicode(J){if(J.length===1)return J.charCodeAt(0);switch(J){case"Enter":return 13;case"Tab":return 9;case"Escape":return 27;case"Backspace":return 127;case" ":return 32}return null}isShifted(J){return J!==J.toLowerCase()}emitKeyEvent(J){for(let Z of this.keyHandlers)Z(J)}csiToDeviceAttributes(J){if(J.final==="c"&&J.private==="?"){let Z=0,Q=[];if(J.params.length>0){Z=J.params[0]?.value||0;let Y=J.params.slice(1);if(Y.length>0&&Y[Y.length-1]?.value===0)Y=Y.slice(0,-1);Q=Y.map((X)=>X.value)}return{type:"device_attributes_primary",primary:Z,secondary:Q}}return null}csiToDecrqss(J){if(J.final==="y"&&J.intermediates.includes("$")){if(J.params.length>=2){let Z=`?${J.params[0]?.value||0}`,Q=String(J.params[1]?.value||0);return{type:"decrqss_response",request:Z,response:Q}}}return null}csiToKittyKeyboardResponse(J){if(J.final==="u"&&J.private==="?"){if(J.params.length>=1)return{type:"decrqss_response",request:"u",response:this.serializeCsiParams(J.params)}}return null}serializeCsiParams(J){return J.map((Z)=>[Z.value,...Z.subparams??[]].join(":")).join(";")}emitDeviceAttributesEvent(J){for(let Z of this.deviceAttributesHandlers)Z(J)}csiToSgrMouse(J){if((J.final==="M"||J.final==="m")&&J.private==="<"){if(J.params.length>=3){let Z=J.params[0]?.value||0,Q=J.params[1]?.value||1,Y=J.params[2]?.value||1,X=Z&-61,K=J.final==="M"&&X!==3;return{type:"sgr_mouse",button:Z,x:Q,y:Y,pressed:K}}}return null}emitDecrqssEvent(J){for(let Z of this.decrqssHandlers)Z(J)}emitSgrMouseEvent(J){for(let Z of this.sgrMouseHandlers)Z(J)}emitMouseEvent(J){for(let Z of this.mouseHandlers)Z(J)}csiToFocus(J){if(J.intermediates===""&&(J.final==="I"||J.final==="O"))return{type:"focus",focused:J.final==="I"};return null}csiToInBandResize(J){if(J.final==="t"&&J.params.length>=5&&J.params[0]?.value===48){let Z=J.params[1]?.value||0,Q=J.params[2]?.value||0,Y=J.params[3]?.value||0,X=J.params[4]?.value||0;return{type:"resize",width:Q,height:Z,pixelWidth:X,pixelHeight:Y}}return null}csiToCursorPositionReport(J){if(J.final==="R"&&J.params.length===2){let Z=J.params[0]?.value||0,Q=J.params[1]?.value||0;return{type:"cursor_position_report",row:Z,col:Q}}return null}emitFocusEvent(J){for(let Z of this.focusHandlers)Z(J)}emitColorPaletteChangeEvent(J){for(let Z of this.colorPaletteChangeHandlers)Z({...J,type:"colorPaletteChange"})}emitCursorPositionReportEvent(J){for(let Z of this.cursorPositionReportHandlers)Z(J)}emitResizeEvent(J){for(let Z of this.resizeHandlers)Z(J)}handleBracketedPaste(J){if(J.final==="~"&&J.params.length===1){let Z=J.params[0]?.value;if(Z===200)return this.inPaste=!0,this.pasteBuffer="",!0;else if(Z===201){if(this.inPaste)this.inPaste=!1,this.emitPasteEvent({type:"paste",text:this.pasteBuffer}),this.pasteBuffer="";return!0}}return!1}emitPasteEvent(J){for(let Z of this.pasteHandlers)Z(J)}}n0();class oY{static instance=null;logs=[];maxLogs=1000;listeners=new Set;constructor(){}static getInstance(){if(!oY.instance)oY.instance=new oY;return oY.instance}addLog(J,Z,...Q){let Y={timestamp:new Date,level:J,message:Z,args:Q};if(this.logs.push(Y),this.logs.length>this.maxLogs)this.logs.shift();this.notifyListeners()}notifyListeners(){let J=this.getLogs();for(let Z of this.listeners)try{Z(J)}catch(Q){let Y=this.originalConsole?.error;if(Y)Y("Error in log change listener:",Q)}}getLogs(){return[...this.logs]}clear(){this.logs=[],this.notifyListeners()}addListener(J){this.listeners.add(J)}removeListener(J){this.listeners.delete(J)}interceptConsole(){let J={error:console.error.bind(console),warn:console.warn.bind(console),info:console.info.bind(console),log:console.log.bind(console),debug:console.debug.bind(console)};console.error=(Z,...Q)=>{this.addLog("error",Z,...Q)},console.warn=(Z,...Q)=>{this.addLog("warn",Z,...Q)},console.info=(Z,...Q)=>{this.addLog("info",Z,...Q)},console.log=(Z,...Q)=>{this.addLog("info",Z,...Q)},console.debug=(Z,...Q)=>{this.addLog("debug",Z,...Q)},this.originalConsole=J}restoreConsole(){let J=this.originalConsole;if(J)console.error=J.error,console.warn=J.warn,console.info=J.info,console.log=J.log,console.debug=J.debug}}function aP4(){try{if(oY.getInstance().restoreConsole(),process.stdout.write("\x1B[?1002l"),process.stdout.write("\x1B[?1003l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1006l"),process.stdout.write("\x1B[?1016l"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?2031l"),process.stdout.write("\x1B[?2048l"),process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[?1049l"),process.stdout.write("\x1B[0 q"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[999;1H"),process.stdout.write("\x1B[0m"),!process.env.TERM_PROGRAM?.startsWith("iTerm"))process.stdout.write("\x1B]9;4;0\x1B\\")}catch(J){}}function r4(J,...Z){if(!J){let Q=Z.join(" "),Y=Error(Q);_.error("TUI Assert failed",{assertion:Q,stackTrace:Y.stack,meta:Z});let X=process.env.AMP_DEBUG,K=process.env.VITEST;if(X||K){if(K)throw Y;aP4(),console.error("FATAL TUI ERROR:",Q),console.error("Stack trace:",Y.stack),console.error("Context:",{meta:Z}),process.exit(1)}}}class ii{parts=[];append(...J){this.parts.push(...J)}toString(){return this.parts.join("")}reset(){this.parts.length=0}get length(){return this.parts.length}get isEmpty(){return this.parts.length===0}}var IU="\x1B",M6="\x1B[",oP4=M6+"0m",dQ3=M6+"m",rP4=(J,Z)=>M6+`${J+1};${Z+1}H`,cQ3=M6+"H",lQ3=M6+"?25l",iQ3=M6+"?25h",nQ3=M6+"2J",aQ3=M6+"?2026h",oQ3=M6+"?2026l",rQ3=M6+"?2004h",sQ3=M6+"?2004l",sP4=[...Array.from({length:216},(J,Z)=>{let Q=Math.floor(Z/36),Y=Math.floor(Z%36/6),X=Z%6,K=(V)=>V===0?0:55+V*40;return[K(Q),K(Y),K(X)]}),...Array.from({length:24},(J,Z)=>{let Q=8+Z*10;return[Q,Q,Q]})],tP4=new Map;function ni(J,Z,Q){let Y=`${J},${Z},${Q}`,X=tP4.get(Y);if(X!==void 0)return X;let K=16,V=1/0;for(let G=0;G<sP4.length;G++){let[F,z,q]=sP4[G],W=(J-F)**2+(Z-z)**2+(Q-q)**2;if(W<V)V=W,K=G+16}return tP4.set(Y,K),K}var tQ3=M6+"?1049h",eQ3=M6+"?1049l",$Y3=M6+"?1002h"+M6+"?1003h"+M6+"?1004h"+M6+"?1006h",JY3=M6+"?1002l"+M6+"?1003l"+M6+"?1004l"+M6+"?1006l",ZY3=M6+"?1016h",QY3=M6+"?1016l",YY3=M6+"?2027h",XY3=M6+"?2027l",KY3=M6+"?2048h",VY3=M6+"?2048l",GY3=M6+"<u";function FY3(J={}){let Z=5;if(J.reportEventTypes)Z|=2;if(J.reportAllKeys)Z|=8;if(J.reportAssociatedText)Z|=16;return M6+`>${Z}u`}var zY3=M6+">4;1m",qY3=M6+">4;0m",WY3=(J)=>IU+`]22;${J}`+IU+"\\",HY3=(J)=>IU+`]0;${J}\x07`;function UY3(J){if(J==="\t")return!1;let Z=J.codePointAt(0);if(Z===void 0)return!1;if(Z>=0&&Z<=8||Z>=10&&Z<=31||Z===127)return!0;if(Z>=128&&Z<=159)return!0;if(Z===8232||Z===8233)return!0;if(Z===65279)return!0;return!1}function DY3(J){let Z=J.codePointAt(0);if(Z===void 0)return"�";if(Z>=0&&Z<=31)return String.fromCodePoint(9216+Z);if(Z===127)return"␡";return"�"}var BY3=IU+"]9;4;3"+IU+"\\",$C4=IU+"]9;4;0"+IU+"\\",NY3=IU+"]9;4;4"+IU+"\\",wY3=(J)=>M6+`${J} q`;function LY3(J){return $Y3+(J?ZY3:"")}function OY3(){return JY3+QY3}function JX0(J){return HY3(J)}function JC4(){return $C4}function eP4(J,Z,Q){if(!J)return"";switch(J.type){case"none":return"";case"default":return M6+(Z?"39":"49")+"m";case"index":return M6+`${Z?"38":"48"};5;${J.value}m`;case"rgb":{if(Q&&!Q.canRgb){let{r:G,g:F,b:z}=J.value,q=ni(G,F,z);return M6+`${Z?"38":"48"};5;${q}m`}let Y=Z?"38":"48",{r:X,g:K,b:V}=J.value;return M6+`${Y};2;${X};${K};${V}m`}default:return""}}function EY3(J,Z,Q){let Y="";if(!$X0(J.fg,Z.fg)){if(J.fg===void 0&&Z.fg!==void 0)Y+=M6+"39m";else Y+=eP4(J.fg,!0,Q);Z.fg=J.fg}if(!$X0(J.bg,Z.bg)){let X=J.bg?.type==="none",K=Z.bg?.type==="none";if((J.bg===void 0||X)&&Z.bg!==void 0&&!K)Y+=M6+"49m";else if(!X)Y+=eP4(J.bg,!1,Q);Z.bg=J.bg}if(J.bold!==Z.bold){if(Y+=J.bold?M6+"1m":M6+"22m",Z.bold=J.bold,!J.bold&&J.dim)Y+=M6+"2m"}if(J.italic!==Z.italic)Y+=J.italic?M6+"3m":M6+"23m",Z.italic=J.italic;if(J.underline!==Z.underline){if(Q?.underlineSupport!=="none")Y+=J.underline?M6+"4m":M6+"24m";Z.underline=J.underline}if(J.strikethrough!==Z.strikethrough)Y+=J.strikethrough?M6+"9m":M6+"29m",Z.strikethrough=J.strikethrough;if(J.reverse!==Z.reverse)Y+=J.reverse?M6+"7m":M6+"27m",Z.reverse=J.reverse;if(J.dim!==Z.dim){if(Y+=J.dim?M6+"2m":M6+"22m",Z.dim=J.dim,!J.dim&&J.bold)Y+=M6+"1m"}return Y}function MY3(J,Z){let Q="";if(!di(J,Z.hyperlink)){if(Z.hyperlink)Q+=eY0();if(J)Q+=dP4(J);Z.hyperlink=J}return Q}function $X0(J,Z){if(J===Z)return!0;if(J===void 0||Z===void 0)return!1;if(J.type!==Z.type)return!1;switch(J.type){case"none":return!0;case"default":return!0;case"index":return Z.value===J.value;case"rgb":{let Q=Z.value;return Q.r===J.value.r&&Q.g===J.value.g&&Q.b===J.value.b}default:return!1}}function AY3(J,Z){return $X0(J.fg,Z.fg)&&$X0(J.bg,Z.bg)&&J.bold===Z.bold&&J.italic===Z.italic&&J.underline===Z.underline&&J.strikethrough===Z.strikethrough&&J.reverse===Z.reverse&&J.dim===Z.dim}var jY3=" ".repeat(pi);function RY3(J,Z){if(J.char==="\t"){if(J.width===pi)return jY3;return" ".repeat(Math.max(1,J.width))}if(Z?.kittyExplicitWidth&&J.width>1)return`\x1B]66;w=${J.width};${J.char}\x1B\\`;return J.char}class ai{capabilities;currentStyle={};currentX=0;currentY=0;constructor(J){this.capabilities=J}updateCapabilities(J){this.capabilities=J}render(J){if(J.length===0)return"";let Z=new ii,Q=null,Y,X=-1,K=-1;for(let V of J){let G=V.cell.char,F=UY3(G),z=F?DY3(G):G;if(r4(!F,`Cell contains disallowed control at (${V.x}, ${V.y}):`,`U+${G.codePointAt(0)?.toString(16).toUpperCase().padStart(4,"0")}`),!(Q!==null&&V.y===K&&V.x===X&&AY3(Q,V.cell.style)&&di(Y,V.cell.hyperlink))){if(this.currentX!==V.x||this.currentY!==V.y)Z.append(rP4(V.y,V.x)),this.currentX=V.x,this.currentY=V.y;Z.append(EY3(V.cell.style,this.currentStyle,this.capabilities)),Z.append(MY3(V.cell.hyperlink,this.currentStyle)),Q=V.cell.style,Y=V.cell.hyperlink}let W=F?{...V.cell,char:z}:V.cell;Z.append(RY3(W,this.capabilities)),this.currentX+=V.cell.width,X=V.x+V.cell.width,K=V.y}return Z.toString()}clearScreen(){return this.currentX=0,this.currentY=0,this.currentStyle={},oP4+eY0()+nQ3+cQ3}hideCursor(){return lQ3}showCursor(){return iQ3}setCursorShape(J){if(this.capabilities?.supportsCursorShape===!1)return"";return wY3(J)}reset(){return this.currentStyle={},oP4+eY0()}moveTo(J,Z){return this.currentX=J,this.currentY=Z,rP4(Z,J)}getCursorPosition(){return{x:this.currentX,y:this.currentY}}resetState(){this.currentStyle={},this.currentX=0,this.currentY=0}startSync(){return aQ3}endSync(){return oQ3}enterAltScreen(){return tQ3+this.clearScreen()}exitAltScreen(){return eQ3}resetCursor(){return dQ3}enableMouse(J=!1){return LY3(J)}disableMouse(){return OY3()}enableEmojiWidth(){return YY3}disableEmojiWidth(){return XY3}enableInBandResize(){return KY3}disableInBandResize(){return VY3}enableBracketedPaste(){return rQ3}disableBracketedPaste(){return sQ3}enableKittyKeyboard(J={}){return FY3(J)}disableKittyKeyboard(){return GY3}enableModifyOtherKeys(){return zY3}disableModifyOtherKeys(){return qY3}setMouseShape(J){return WY3(J)}setProgressBarIndeterminate(){return BY3}setProgressBarOff(){return $C4}setProgressBarPaused(){return NY3}}import{exec as IY3,execSync as PY3}from"node:child_process";function gG(){if(process.env.TMUX||process.env.TMUX_PANE)return!0;return process.env.TERM?.toLowerCase()?.includes("tmux")??!1}var Jo0=!1;if(process.env.TMUX)IY3("tmux show-options -g extended-keys 2>/dev/null",{timeout:1000},(J,Z)=>{if(!J&&Z.trim()==="extended-keys on")Jo0=!0});function ZC4(){if(!gG())return!1;try{return PY3('tmux display-message -p "#{pane_active}"',{timeout:500,encoding:"utf8"}).trim()!=="1"}catch{return!1}}function PU(J){if(!gG())return J;return`\x1BPtmux;${J.replace(/\x1b/g,"\x1B\x1B")}\x1B\\`}n0();import{openSync as pY3}from"node:fs";import VC4 from"node:tty";import{createRequire as CY3}from"node:module";var _Y3=-10,TY3=-11,SY3=0xffffffffffffffffn,kY3=4,vY3=128,yY3=2,xY3=64,fY3=512,uY3=4,bY3=CY3(import.meta.url);function XC4(){return bY3("bun:ffi")}function hY3(){let{dlopen:J,FFIType:Z}=XC4();return J("kernel32.dll",{GetConsoleMode:{args:[Z.u64,Z.ptr],returns:Z.i32},GetStdHandle:{args:[Z.i32],returns:Z.u64},SetConsoleMode:{args:[Z.u64,Z.u32],returns:Z.i32}})}var ZX0=null;function Zo0(){if(ZX0)return ZX0;return ZX0=hY3(),ZX0}function QC4(J){let Z=Zo0().symbols.GetStdHandle(J);if(Z===0n||Z===SY3)throw Error(`GetStdHandle(${J}) returned an invalid handle`);return Z}function YC4(J,Z){let Q=new Uint32Array(1);if(Zo0().symbols.GetConsoleMode(J,XC4().ptr(Q))===0)throw Error(`GetConsoleMode(${Z}) failed`);return Q[0]??0}function oi(J,Z,Q){if(Zo0().symbols.SetConsoleMode(J,Z)===0)throw Error(`SetConsoleMode(${Q}) failed`)}function gY3(J){let Z=J|fY3|vY3;return Z&=~(xY3|yY3|kY3),Z}function mY3(J){return J|uY3}function KC4(){if(process.platform!=="win32")return null;let J=QC4(_Y3),Z=QC4(TY3),Q=YC4(J,"stdin"),Y=YC4(Z,"stdout"),X=gY3(Q),K=mY3(Y);if(K!==Y)oi(Z,K,"stdout");try{if(X!==Q)oi(J,X,"stdin")}catch(G){if(K!==Y)try{oi(Z,Y,"stdout")}catch{}throw G}let V=!1;return{restore(){if(V)return;if(V=!0,X!==Q)oi(J,Q,"stdin");if(K!==Y)oi(Z,Y,"stdout")}}}function dY3(){let J=process.versions.bun;if(!J)return!1;let Z=J.split(".").map(Number),Q=Z[0]??0,Y=Z[1]??0,X=Z[2]??0;if(!Number.isFinite(Q)||!Number.isFinite(Y)||!Number.isFinite(X))return!1;if(Q!==1||Y!==2)return!1;return X<22}function FC4(J){let Z="",Q=0;while(Q<J.length){let Y=J.charCodeAt(Q);if(Y===27){if(Q++,Q>=J.length)break;let X=J.charCodeAt(Q);if(X===91){Q++;while(Q<J.length){let K=J.charCodeAt(Q);if(Q++,K>=64&&K<=126)break}continue}if(X===93){Q++;while(Q<J.length){let K=J.charCodeAt(Q);if(K===7){Q++;break}if(K===27&&Q+1<J.length&&J.charCodeAt(Q+1)===92){Q+=2;break}Q++}continue}if(X===80){Q++;while(Q<J.length){if(J.charCodeAt(Q)===27&&Q+1<J.length&&J.charCodeAt(Q+1)===92){Q+=2;break}Q++}continue}if(X===95||X===88||X===94){Q++;while(Q<J.length){if(J.charCodeAt(Q)===27&&Q+1<J.length&&J.charCodeAt(Q+1)===92){Q+=2;break}Q++}continue}if(X===78||X===79){Q+=2;continue}if(X>=64&&X<=126){Q++;continue}continue}if(Y===127||Y===8){Z=Z.slice(0,-1),Q++;continue}if(Y<32){Q++;continue}Z+=J[Q],Q++}return Z}function cY3(){let J=!1,Z={stdin:null,dataCallback:null,earlyInputBuffer:[],init(){if(this.stdin!==null)return;if(m5.stream){if(_.info("[tty] taking over early stdin stream"),this.stdin=m5.stream,this.stdin.removeAllListeners("data"),m5.takenOver=!0,m5.buffer.length>0)this.earlyInputBuffer.push(...m5.buffer),m5.buffer=[];this.stdin.on("data",(X)=>{if(!J)this.earlyInputBuffer.push(Buffer.from(X));if(this.dataCallback)this.dataCallback(X)}),m5.stream=null;return}let Q=pY3("/dev/tty","r");if(!VC4.isatty(Q))throw Error("/dev/tty is not a TTY device");let Y=new VC4.ReadStream(Q);this.stdin=Y,Y.setRawMode(!0),Y.on("data",(X)=>{if(!J)this.earlyInputBuffer.push(Buffer.from(X));if(this.dataCallback)this.dataCallback(X)})},on(Q,Y){this.dataCallback=Y},pause(){if(this.stdin)this.stdin.setRawMode(!1),this.stdin.removeAllListeners("data"),this.stdin.destroy();this.stdin=null},resume(){this.init()},dispose(){if(this.stdin)this.stdin.setRawMode(!1),this.stdin.removeAllListeners("data"),this.stdin.destroy();this.stdin=null,this.dataCallback=null,this.earlyInputBuffer=[]},getEarlyInputText(){if(J=!0,this.earlyInputBuffer.length===0)return"";let Y=Buffer.concat(this.earlyInputBuffer).toString("utf8");return this.earlyInputBuffer=[],FC4(Y)}};return Z.init(),Z}function GC4(){let J=!1,Z=null;function Q(){if(Z)return;try{Z=KC4()}catch(K){_.warn("Failed to enable Windows VT input for TUI mouse reporting",{error:K})}}function Y(){if(!Z)return;try{Z.restore()}catch(K){_.warn("Failed to restore Windows console modes after TUI mouse reporting",{error:K})}finally{Z=null}}let X={stdin:null,dataCallback:null,earlyInputBuffer:[],init(){if(this.stdin!==null)return;if(this.stdin=process.stdin,Q(),this.stdin.isTTY)this.stdin.setRawMode(!0);if(m5.buffer.length>0)this.earlyInputBuffer.push(...m5.buffer),m5.buffer=[];if(m5.stream)m5.stream.removeAllListeners("data"),m5.stream=null,m5.takenOver=!0;this.stdin.on("data",(K)=>{if(!J)this.earlyInputBuffer.push(Buffer.from(K));if(this.dataCallback)this.dataCallback(K)})},on(K,V){this.dataCallback=V},pause(){if(Y(),this.stdin&&this.stdin.isTTY)this.stdin.setRawMode(!1);this.stdin?.pause()},resume(){if(Q(),this.stdin&&this.stdin.isTTY)this.stdin.setRawMode(!0);this.stdin?.resume()},dispose(){if(Y(),this.stdin&&this.stdin.isTTY)this.stdin.setRawMode(!1);if(this.stdin)this.stdin.removeAllListeners("data");this.stdin=null,this.dataCallback=null,this.earlyInputBuffer=[]},getEarlyInputText(){if(J=!0,this.earlyInputBuffer.length===0)return"";let V=Buffer.concat(this.earlyInputBuffer).toString("utf8");return this.earlyInputBuffer=[],FC4(V)}};return X.init(),X}function QX0(){if(process.platform==="win32")return GC4();if(dY3())return _.warn("Detected Bun <1.2.22 which has known /dev/tty issues. Please upgrade to Bun 1.2.22 or later for proper TTY support. Using process.stdin instead."),GC4();return cY3()}var aY3="\x1B[c",oY3="\x1B[?1004h",rY3="\x1B[?1004l",sY3="\x1B[?u",qC4=200,tY3="\x1B[>4;2m",eY3="\x1B[?9001h",$X3="\x1B[?9001l";function WC4(){let J=null;try{if(process.stdout.isTTY){let Z=process.stdout.getWindowSize();J=[Z[0],Z[1]]}}catch{}return{isTTY:process.stdout.isTTY,columns:process.stdout.columns??null,rows:process.stdout.rows??null,windowSize:J,hasRefreshSize:typeof process.stdout._refreshSize==="function"}}function JX3(){if(process.stdout.isTTY)return{stream:process.stdout,target:"stdout",dispose:()=>{}};if(process.stderr.isTTY)return{stream:process.stderr,target:"stderr",dispose:()=>{}};if(process.platform!=="win32")try{let J=lY3("/dev/tty","w");if(nY3.isatty(J))return{stream:{write(Z){return iY3(J,Z),!0}},target:"dev-tty",dispose:()=>{zC4(J)}};zC4(J)}catch{}return{stream:process.stdout,target:"stdout",dispose:()=>{}}}function l8(J,Z){if(!process.stdout.writable||process.stdout.destroyed){Z?.();return}let Q=`${JSON.stringify(J)}
|
|
6239
|
-
`;try{if(Z){if(!process.stdout.write(Q)){process.stdout.once("drain",Z);return}Z();return}process.stdout.write(Q)}catch{Z?.()}}function Qo0(J){return Array.from(J,(Z)=>{if(Z>=32&&Z<=126&&Z!==92)return String.fromCharCode(Z);if(Z===92)return"\\\\";return`\\x${Z.toString(16).padStart(2,"0")}`}).join("")}function ZX3(J){return J.ctrlKey&&J.key.toLowerCase()==="c"&&J.eventType!=="repeat"&&J.eventType!=="release"}function HC4(J){try{let Z=UC4(`tmux show-options -gv ${J}`,{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1000}).trim();return Z===""?null:Z}catch{return null}}function QX3(){try{let J=UC4("tmux display-message -p '#{client_termfeatures}'",{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1000}).trim();return J===""?[]:J.split(",").filter(Boolean)}catch{return null}}function TQ(J,Z,Q,Y,X){if(Y.raw){let K=Buffer.from(Z);l8({type:"control",name:Q,stage:X??null,bytes:K.toString("hex"),escaped:Qo0(K)})}J.stream.write(Z)}async function DC4(J={}){let Z=QX0(),Q=new bj,Y=new ai,X=JX3(),K=gG(),V=K?{clientTermFeatures:QX3(),extendedKeysFormat:HC4("extended-keys-format"),extendedKeysMode:HC4("extended-keys")}:null,G=V?.clientTermFeatures?.includes("extkeys")??!1;if(J.raw)l8({type:"debug",controlTarget:X.target,platform:process.platform,stdoutIsTTY:process.stdout.isTTY,stderrIsTTY:process.stderr.isTTY,term:process.env.TERM??null,termProgram:process.env.TERM_PROGRAM??null,termProgramVersion:process.env.TERM_PROGRAM_VERSION??null,tmux:K,tmuxClientTermFeatures:V?.clientTermFeatures??null,tmuxExtendedKeys:K?G:null,tmuxExtendedKeysFormat:V?.extendedKeysFormat??null,tmuxExtendedKeysMode:V?.extendedKeysMode??null});let F=!1,z=null,q=null,W=!1,H=!1,U=()=>{l8({type:"signal",signal:"SIGWINCH",stdout:WC4()})},D=()=>{l8({type:"stdout_resize",stdout:WC4()})},B=new Promise((P)=>{z=P}),N=()=>{if(!q)return null;let P=q;q=null,clearTimeout(P.timeout);let b={stage:P.stage,kittyQueryResponse:P.kittyQueryResponse,deviceAttributes:P.deviceAttributes};return l8({type:"startup_probe",stage:b.stage,timeoutMs:qC4,kittyQueryResponse:b.kittyQueryResponse,deviceAttributes:b.deviceAttributes}),P.resolve(b),b},w=(P)=>{if(!q||P.request!=="u")return;if(q.kittyQueryResponse=P.response,q.deviceAttributes!==null)N()},L=(P)=>{if(!q)return;if(q.deviceAttributes={primary:P.primary,secondary:[...P.secondary]},q.kittyQueryResponse!==null)N()},O=(P)=>{if(q)N();return new Promise((b)=>{q={stage:P,kittyQueryResponse:null,deviceAttributes:null,resolve:b,timeout:setTimeout(()=>{N()},qC4)},TQ(X,sY3,"kitty-query",J,P),TQ(X,aY3,"device-attributes-query",J,P)})},E=()=>{if(F)return;if(F=!0,H)process.off("SIGWINCH",U);if(process.stdout.isTTY)process.stdout.off("resize",D);process.off("SIGINT",A),process.off("SIGTERM",j),process.off("exit",E),N();try{if(W)TQ(X,$X3,"win32-input-mode-disable",J);if(TQ(X,rY3,"focus-disable",J),TQ(X,Y.disableInBandResize(),"inband-resize-disable",J),TQ(X,Y.disableBracketedPaste(),"bracketed-paste-disable",J),K)TQ(X,Y.disableModifyOtherKeys(),"tmux-extended-keys-disable",J);TQ(X,Y.disableKittyKeyboard(),"kitty-keyboard-disable",J)}catch{}X.dispose(),Z.dispose()},M=(P)=>{if(F)return;process.exitCode=P,E(),z?.()},A=()=>{M(130)},j=()=>{M(143)};process.once("SIGINT",A),process.once("SIGTERM",j),process.once("exit",E);try{process.on("SIGWINCH",U),H=!0}catch(P){l8({type:"signal_subscription_error",signal:"SIGWINCH",error:P instanceof Error?P.message:String(P)})}if(process.stdout.isTTY)process.stdout.on("resize",D);Q.onKey((P)=>{let b={type:"key",key:P.key,code:P.code??null,modifiers:{shift:P.shiftKey,ctrl:P.ctrlKey,alt:P.altKey,meta:P.metaKey},eventType:P.eventType??null};if(ZX3(P)){l8(b,()=>M(0));return}l8(b)}),Q.onDcs((P)=>{l8(P)}),Q.onOsc((P)=>{l8(P)}),Q.onApc((P)=>{l8(P)}),Q.onPaste((P)=>{l8(P)}),Q.onSgrMouse((P)=>{l8(P)}),Q.onFocus((P)=>{l8(P)}),Q.onMouse((P)=>{l8(P)}),Q.onResize((P)=>{l8(P)}),Q.onColorPaletteChange((P)=>{l8(P)}),Q.onCursorPositionReport((P)=>{l8(P)}),Q.onDeviceAttributes((P)=>{L(P),l8(P)}),Q.onDecrqss((P)=>{if(w(P),P.request==="u"){l8({type:"kitty_query_response",response:P.response});return}l8(P)}),Z.on("data",(P)=>{if(J.raw)l8({type:"raw",bytes:Buffer.from(P).toString("hex"),escaped:Qo0(P)});Q.parse(P)});let I=[...Z.earlyInputBuffer];Z.earlyInputBuffer.length=0;for(let P of I){if(J.raw)l8({type:"raw",bytes:P.toString("hex"),escaped:Qo0(P)});Q.parse(P)}await O("before_enable"),TQ(X,oY3,"focus-enable",J),TQ(X,Y.enableInBandResize(),"inband-resize-enable",J),TQ(X,Y.enableBracketedPaste(),"bracketed-paste-enable",J),TQ(X,Y.enableKittyKeyboard({reportEventTypes:!0}),"kitty-keyboard-enable",J);let S=await O("after_enable");if(process.platform==="win32"&&S.kittyQueryResponse===null)W=!0,l8({type:"win32_input_mode",enabled:!0,reason:"kitty-unavailable",note:"Enabling ConPTY win32-input-mode fallback for key down/up events"}),TQ(X,eY3,"win32-input-mode-enable",J);if(K)l8({type:"tmux_info",extendedKeysFormat:V?.extendedKeysFormat??null,extendedKeysMode:V?.extendedKeysMode??null,hasExtkeysFeature:G,note:"tmux does not proxy kitty query/event-type support; enabling modifyOtherKeys mode 2 for press-only extended keys"}),TQ(X,tY3,"tmux-extended-keys-enable",J);await B}import{execFile as zK3}from"node:child_process";import{lstat as F_4,mkdir as qK3,readFile as WK3,rm as _o0,writeFile as HK3}from"node:fs/promises";import sY from"node:path";import f$ from"node:process";import{createInterface as UK3}from"node:readline";import{promisify as DK3}from"node:util";class O5{state=[!0,!1,!0,!1,!0,!1,!0,!1];previousState=[];generation=0;maxGenerations=15;neighborMap=[[1,3,4,5,7],[0,2,4,5,6],[1,3,5,6,7],[0,2,4,6,7],[0,1,3,5,7],[0,1,2,4,6],[1,2,3,5,7],[0,2,3,4,6]];step(){let J=this.state.map((K,V)=>{let G=this.neighborMap[V].filter((F)=>this.state[F]).length;if(K)return G===2||G===3;return G===3||G===6}),Z=J.every((K,V)=>K===this.state[V]),Q=this.previousState.length>0&&J.every((K,V)=>K===this.previousState[V]);this.previousState=[...this.state],this.state=J,this.generation++;let Y=J.every((K)=>!K),X=J.filter((K)=>K).length;if(Z||Q||this.generation>=this.maxGenerations||Y||X<2){let K;do K=Array.from({length:8},()=>Math.random()>0.6);while(K.filter((V)=>V).length<3);this.state=K,this.previousState=[],this.generation=0}}toBraille(){let J=[0,1,2,6,3,4,5,7],Z=10240;for(let Q=0;Q<8;Q++)if(this.state[Q])Z|=1<<J[Q];return String.fromCharCode(Z)}}n0();k9();U4();n0();tZ();E1();import{mkdir as YX3,writeFile as XX3}from"node:fs/promises";import KX3 from"node:path";function VX3(J){let Z=J?.trim();return Z&&Z.length>0?Z:void 0}function GX3(J){let Z=J.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48);return Z.length>0?Z:"trace"}function FX3(J,Z){let Q=new Date(J).toISOString().replace(/[:.]/g,"-");return`${Z?`dtw-trace-${GX3(Z)}`:"dtw-trace"}-${Q}-${crypto.randomUUID().slice(0,8)}`}function Yo0(J){let Z=JSON.stringify(J);if(Z===void 0)return null;return JSON.parse(Z)}class Xo0{options;traceFilePath;session;constructor(J){this.options=J;let Z=Date.now(),Q=VX3(J.traceName),Y=FX3(Z,Q);this.traceFilePath=KX3.join(J.traceDir,`${Y}.json`),this.session={schemaVersion:1,sessionID:Y,createdAt:Z,runtimeMode:J.runtimeMode,...Q?{traceName:Q}:{},threadId:J.threadId,scriptedCommands:[...J.scriptedCommands??[]],protocolEvents:[],providerStateEvents:[],adapterStateEvents:[],commandEvents:[],timeline:[]}}nextTimelineIndex(){return this.session.timeline.length}recordProtocolEvent(J,Z){let Q=this.nextTimelineIndex(),Y=Date.now(),X={timelineIndex:Q,timestamp:Y,eventName:J,payload:Yo0(Z)};this.session.protocolEvents.push(X),this.session.timeline.push({timelineIndex:Q,timestamp:Y,kind:"protocol",protocolIndex:this.session.protocolEvents.length-1})}recordProviderState(J,Z){let Q=this.nextTimelineIndex(),Y=Date.now(),X={timelineIndex:Q,timestamp:Y,reason:J,state:Yo0(Z)};this.session.providerStateEvents.push(X),this.session.timeline.push({timelineIndex:Q,timestamp:Y,kind:"provider_state",providerStateIndex:this.session.providerStateEvents.length-1})}recordAdapterState(J,Z){let Q=this.nextTimelineIndex(),Y=Date.now(),X={timelineIndex:Q,timestamp:Y,reason:J,state:Yo0(Z)};this.session.adapterStateEvents.push(X),this.session.timeline.push({timelineIndex:Q,timestamp:Y,kind:"adapter_state",adapterStateIndex:this.session.adapterStateEvents.length-1})}recordCommand(J){let Z=this.nextTimelineIndex(),Q=Date.now();this.session.commandEvents.push({timelineIndex:Z,timestamp:Q,command:J}),this.session.timeline.push({timelineIndex:Z,timestamp:Q,kind:"command",commandIndex:this.session.commandEvents.length-1})}async flush(){await YX3(this.options.traceDir,{recursive:!0});let J=JSON.stringify(this.session,null,2);return await XX3(this.traceFilePath,J,"utf-8"),this.traceFilePath}}function BC4(J,Z){let Q=[J.connectionChanges().subscribe({next:(Y)=>Z("connection_changes",Y)}),J.errors().subscribe({next:(Y)=>Z("errors",Y)}),J.errorEvents().subscribe({next:(Y)=>Z("error_events",Y)}),J.agentStates().subscribe({next:(Y)=>Z("agent_states",Y)}),J.deltas().subscribe({next:(Y)=>Z("deltas",Y)}),J.messageEvents().subscribe({next:(Y)=>Z("message_events",Y)}),J.messageEdited().subscribe({next:(Y)=>Z("message_edited",Y)}),J.editRejected().subscribe({next:(Y)=>Z("edit_rejected",Y)}),J.threadTitles().subscribe({next:(Y)=>Z("thread_titles",Y)}),J.queuedMessages().subscribe({next:(Y)=>Z("queued_messages",Y)}),J.retryEvents().subscribe({next:(Y)=>Z("retry_events",Y)}),J.cancelledEvents().subscribe({next:(Y)=>Z("cancelled_events",Y)}),J.toolLeases().subscribe({next:(Y)=>Z("tool_leases",Y)}),J.toolLeaseRevoked().subscribe({next:(Y)=>Z("tool_lease_revoked",Y)}),J.toolApprovalQueue().subscribe({next:(Y)=>Z("tool_approval_queue",Y)}),J.executorToolApprovalResponses().subscribe({next:(Y)=>Z("executor_tool_approval_responses",Y)}),J.toolProgress().subscribe({next:(Y)=>Z("tool_progress",Y)}),J.executorErrors().subscribe({next:(Y)=>Z("executor_errors",Y)}),J.executorConnected().subscribe({next:(Y)=>Z("executor_connected",Y)}),J.executorRollbackRequests().subscribe({next:(Y)=>Z("executor_rollback_requests",Y)}),J.observers().subscribe({next:(Y)=>Z("observers",Y)}),J.executorStatuses().subscribe({next:(Y)=>Z("executor_statuses",Y)}),J.environmentUpdates().subscribe({next:(Y)=>Z("environment_updates",Y)}),J.artifacts().subscribe({next:(Y)=>Z("artifacts",Y)}),J.compactionEvents().subscribe({next:(Y)=>Z("compaction_events",Y)}),J.compactionRecords().subscribe({next:(Y)=>Z("compaction_records",Y)})];return{unsubscribe:()=>{for(let Y of Q)Y.unsubscribe()}}}function XX0(J){return typeof J==="object"&&J!==null}function Ko0(J){if(!Array.isArray(J))return;return J}function NC4(J){let Z=J.trim();if(Z.length===0)return;try{let Q=JSON.parse(Z);return Ko0(Q)}catch{return}}function YX0(J){if(typeof J==="string")return J;if(!XX0(J))return;if("output"in J&&typeof J.output==="string")return J.output;if("displayMessage"in J&&typeof J.displayMessage==="string")return J.displayMessage;if("message"in J&&typeof J.message==="string")return J.message;if("reason"in J&&typeof J.reason==="string")return J.reason;if("result"in J){let Z=YX0(J.result);if(Z!==void 0)return Z}if("error"in J){let Z=YX0(J.error);if(Z!==void 0)return Z}if("value"in J)return YX0(J.value);return}function zX3(J){return J.type==="text"}function wC4(J){if(J===void 0)return;let Z;try{Z=wi(J,"snapshot")}catch{return}if(Z.type==="snapshot")return YX0(Z.value);let Q=(Z.blocks??[]).filter(zX3).map((Y)=>Y.text).join("");return Q.length>0?Q:void 0}var qX3=["queued","blocked-on-user","in-progress","rejected-by-user","cancellation-requested","cancelled","done","error"];function WX3(J){return typeof J==="string"&&qX3.includes(J)}function LC4(J){if(J===void 0)return;let Z;try{Z=wi(J,"snapshot")}catch{return}if(Z.type!=="snapshot")return;let Q=Z.value;if(!XX0(Q))return;if(!("status"in Q)||!WX3(Q.status))return;return Q.status}function OC4(J){let Z=Ko0(J);if(Z!==void 0)return Z;if(!XX0(J)||typeof J.type!=="string")return;if(J.type==="snapshot"){let Y=J.value,X=Ko0(Y);if(X!==void 0)return X;if(typeof Y==="string")return NC4(Y);return}if(J.type!=="delta"||!Array.isArray(J.blocks))return;let Q=J.blocks.map((Y)=>{if(!XX0(Y)||Y.type!=="text"||typeof Y.text!=="string")return"";return Y.text}).join("");return NC4(Q)}function jC4(J){let Z=[],Q=0;for(let X of J.messages){if(X.role==="user"){Z.push({messageId:Eq(),role:"user",content:[...X.content],meta:X.meta,userState:X.userState,readAt:X.readAt,parentToolUseId:X.parentToolUseId});continue}if(X.role==="assistant"){Z.push({messageId:Eq(),role:"assistant",content:[...X.content],meta:X.meta,usage:X.usage,readAt:X.readAt,cancelled:X.state.type==="cancelled",parentToolUseId:X.parentToolUseId});continue}let K=X.content.filter((V)=>V.type==="manual_bash_invocation");if(K.length>0)Z.push({messageId:Eq(),role:"info",content:K,parentToolUseId:X.parentToolUseId});for(let V of X.content){if(V.type!=="summary"||V.summary.type!=="message")continue;Q+=1,Z.push({messageId:Eq(),role:"assistant",content:[{type:"text",text:V.summary.summary}],parentToolUseId:X.parentToolUseId})}}let Y=J.meta?.status!==void 0||J.meta?.executorType!==void 0?{...J.meta?.status!==void 0?{status:J.meta.status}:{},...J.meta?.executorType!==void 0?{executorType:J.meta.executorType}:{}}:void 0;return{id:J.id,v:J.v,...J.title?{title:J.title}:{},...J.agentMode?{agentMode:J.agentMode}:{},...Y?{meta:Y}:{},messages:Z,convertedSummaryMessages:Q}}function HX3(J,Z){let Q=Z.messages.map((Y,X)=>{if(Y.role==="user")return{role:"user",content:[...Y.content],meta:Y.meta,userState:Y.userState,readAt:Y.readAt,messageId:X,dtwMessageID:Y.messageId,parentToolUseId:Y.parentToolUseId};if(Y.role==="assistant"){let K=Y.content.some((V)=>V.type==="tool_use");return{role:"assistant",content:[...Y.content],meta:Y.meta,usage:Y.usage,readAt:Y.readAt,state:Y.cancelled?{type:"cancelled"}:{type:"complete",stopReason:K?"tool_use":"end_turn"},messageId:X,dtwMessageID:Y.messageId,parentToolUseId:Y.parentToolUseId}}return{role:"info",content:[...Y.content],messageId:X,dtwMessageID:Y.messageId,parentToolUseId:Y.parentToolUseId}});return{...J,messages:Q}}async function CU(J,Z,Q,Y={}){let X={...J?{threadId:J}:{},...Y.repositoryURL?{repositoryURL:Y.repositoryURL}:{},...!J&&Y.executorType?{executorType:Y.executorType}:{},...Y.agentMode?{agentMode:Y.agentMode}:{},...Y.relationship?{relationship:Y.relationship}:{},...Y.usesThreadActors?{usesThreadActors:!0}:{}},K=await J2("/api/durable-thread-workers",RC4({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(X),signal:Y.signal},Q),Z);if(!K.ok)throw Error(`Failed to create DTW thread: ${K.status} ${await K.text()}`);let V=await K.json();if(!V.threadId||!V.wsToken)throw Error("DTW thread creation response missing threadId or wsToken");if(!V.ownerUserId||typeof V.threadVersion!=="number")throw Error("DTW thread creation response missing ownerUserId or threadVersion");return{threadId:V.threadId,wsToken:V.wsToken,usesDtw:V.usesDtw??!0,executorType:V.executorType??null,ownerUserId:V.ownerUserId,threadVersion:V.threadVersion,...V.agentMode?{agentMode:V.agentMode}:{}}}async function UX3(J,Z,Q,Y){let X=await Z.getLatest(),K=Q??await X.secrets.getToken("apiKey",X.settings.url);if(!K)throw Error("API key required. Please run `amp login` first.");let V=Y.payload??jC4(J),G=Y.workerURL??l7(Y.ampURL),F=await fetch(`${G}/threads/${J.id}/import`,{method:"POST",headers:{Authorization:`Bearer ${K}`,"Content-Type":"application/json"},body:JSON.stringify({thread:V})});if(F.status===409)return"already-imported";if(!F.ok)throw Error(`Failed to import thread into DTW: ${F.status} ${await F.text()}`);if((await F.json()).ok!==!0)throw Error("Failed to import thread into DTW: import endpoint returned an invalid response");return"imported"}async function DX3(J,Z,Q){let Y=await J2(`/api/durable-thread-workers/${J}`,RC4({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({executorType:"local-client"})},Q),Z);if(!Y.ok)throw Error(`Failed to mark thread as DTW-backed: ${Y.status} ${await Y.text()}`);let X=await Y.json();if(X.ok!==!0||X.usesDtw!==!0||X.executorType!=="local-client")throw Error("Failed to mark thread as DTW-backed: server returned an invalid response")}async function ei(J,Z){let Q=await Z.get(J);if(!Q)throw Error(`Failed to fetch thread snapshot: thread ${J} not found`);return Q}function RC4(J,Z){if(!Z)return J;return{...J,headers:{...J?.headers,Authorization:`Bearer ${Z}`}}}function ti(J){let Z=n6.safeParse(J.dtwMessageID);if(Z.success)return Z.data;let Q=n6.safeParse(`${J.messageId}`);return Q.success?Q.data:null}function BX3(J){let Z=[],Q=new Set;for(let[Y,X]of J.messages.entries()){let K=ti(X);if(K)Q.add(K);Z.push({...X,messageId:Y})}return{messages:Z,processedIds:Q}}function NX3(J){let Z=new Set;for(let Q of J){let Y=ti(Q);if(Y)Z.add(Y)}return Z}function ri(J,Z){let Q=[...J];for(let Y of Z)if(Y.type==="text"){let X=Q[Q.length-1];if(X?.type==="text")Q[Q.length-1]={...X,text:X.text+Y.text};else Q.push(Y)}else if(Y.type==="tool_use"){let X=Q.findIndex((K)=>K.type==="tool_use"&&K.id===Y.id);if(X>=0)Q[X]=Y;else Q.push(Y)}else if(Y.type==="thinking"){let X=Q[Q.length-1];if(X?.type==="thinking")Q[Q.length-1]={...X,thinking:X.thinking+Y.thinking};else Q.push(Y)}else Q.push(Y);return Q}function wX3(J,Z,Q,Y){if(!J||Z.length===0)return null;return{role:"assistant",content:Z,state:{type:"streaming"},messageId:Q,parentToolUseId:Y}}function LX3(J,Z){let Q=J.parentToolCallId,Y=J.role==="assistant"?J:null,{completedMessages:X}=Z;if(J.state==="complete"||J.state==="error"){if(Z.streamingMessageId!==null&&J.messageId!==Z.streamingMessageId){if(Z.streamingBlocks.length>0)X.push({messageId:Z.streamingMessageId,role:"assistant",blocks:Z.streamingBlocks,parentToolCallId:Z.streamingParentToolCallId});if(Z.streamingMessageId=null,Z.streamingBlocks=[],Z.streamingParentToolCallId=void 0,J.blocks&&J.blocks.length>0)if(J.role==="user")X.push({messageId:J.messageId,role:"user",blocks:J.blocks??[],parentToolCallId:Q});else X.push({messageId:J.messageId,role:"assistant",blocks:J.blocks??[],usage:Y?.usage,parentToolCallId:Q});return}if(Z.streamingMessageId===null&&J.blocks&&J.blocks.length>0){if(J.role==="user"){let V=J.blocks;X.push({messageId:J.messageId,role:"user",blocks:V,parentToolCallId:Q})}else{let V=J.blocks;X.push({messageId:J.messageId,role:"assistant",blocks:V,usage:Y?.usage,parentToolCallId:Q})}return}let K=Z.streamingBlocks;if(J.messageId===Z.streamingMessageId&&J.blocks&&J.role==="assistant")K=ri(Z.streamingBlocks,J.blocks);if(Z.streamingMessageId&&K.length>0)X.push({messageId:Z.streamingMessageId,role:"assistant",blocks:K,usage:Y?.usage,parentToolCallId:Z.streamingParentToolCallId});Z.streamingMessageId=null,Z.streamingBlocks=[],Z.streamingParentToolCallId=void 0;return}if(J.state==="tool_use"){if(J.role!=="assistant")return;if(Z.streamingMessageId===null||Z.streamingMessageId!==J.messageId)Z.streamingMessageId=J.messageId,Z.streamingBlocks=ri([],J.blocks??[]),Z.streamingParentToolCallId=Q;else if(J.blocks)Z.streamingBlocks=ri(Z.streamingBlocks,J.blocks);if(Z.streamingBlocks.length>0)X.push({messageId:Z.streamingMessageId??J.messageId,role:"assistant",blocks:Z.streamingBlocks,usage:Y?.usage,parentToolCallId:Z.streamingParentToolCallId});Z.streamingMessageId=null,Z.streamingBlocks=[],Z.streamingParentToolCallId=void 0;return}if(J.state==="start"||J.state==="generating"){if(J.role!=="assistant")return;if(Z.streamingMessageId===null||Z.streamingMessageId!==J.messageId)Z.streamingMessageId=J.messageId,Z.streamingBlocks=ri([],J.blocks??[]),Z.streamingParentToolCallId=Q;else if(J.blocks)Z.streamingBlocks=ri(Z.streamingBlocks,J.blocks)}}function OX3(J,Z,Q){if(Z.length===0)return J;let Y=[],X=J.length;for(let K of Z){if(Q.has(K.messageId))continue;Q.add(K.messageId);let V=X++;if(K.role==="assistant")Y.push({role:"assistant",content:K.blocks,state:{type:"complete",stopReason:"end_turn"},usage:K.usage,messageId:V,dtwMessageID:K.messageId,parentToolUseId:K.parentToolCallId});else Y.push({role:"user",content:K.blocks,messageId:V,dtwMessageID:K.messageId,parentToolUseId:K.parentToolCallId})}if(Y.length===0)return J;return[...J,...Y]}function EX3(J){if(typeof J!=="number"||!Number.isFinite(J))return 0;return Math.max(0,Math.trunc(J))}function Vo0(J){if(!J||J.length===0)return;return J.map((Z)=>({uri:Z.uri,lineCount:EX3(Z.lineCount),...typeof Z.content==="string"?{content:Z.content}:{}}))}function MX3(J,Z,Q){let Y=J.message.messageId;if(Q.has(Y)){let K=Z.findIndex((G)=>ti(G)===Y);if(K<0)return Z;let V=Z[K];if(!V)return Z;if(J.message.role!==V.role)return Z;if(V.role==="user"&&J.message.role==="user"){let G={...V,content:J.message.content,agentMode:J.message.agentMode,userState:J.message.userState,discoveredGuidanceFiles:Vo0(J.message.discoveredGuidanceFiles),parentToolUseId:J.parentToolUseId},F=[...Z];return F[K]=G,F}if(V.role==="assistant"&&J.message.role==="assistant"){let G={...V,content:J.message.content,usage:J.message.usage,state:{type:"complete",stopReason:"end_turn"},parentToolUseId:J.parentToolUseId},F=[...Z];return F[K]=G,F}if(V.role==="info"&&J.message.role==="info"){let G={...V,content:J.message.content,parentToolUseId:J.parentToolUseId},F=[...Z];return F[K]=G,F}return Z}Q.add(Y);let X=Z.length;if(J.message.role==="assistant")return[...Z,{role:"assistant",content:J.message.content,state:{type:"complete",stopReason:"end_turn"},usage:J.message.usage,messageId:X,dtwMessageID:Y,parentToolUseId:J.parentToolUseId}];if(J.message.role==="info")return[...Z,{role:"info",content:J.message.content,messageId:X,dtwMessageID:Y,parentToolUseId:J.parentToolUseId}];return[...Z,{role:"user",content:J.message.content,agentMode:J.message.agentMode,userState:J.message.userState,discoveredGuidanceFiles:Vo0(J.message.discoveredGuidanceFiles),messageId:X,dtwMessageID:Y,parentToolUseId:J.parentToolUseId}]}function AX3(J,Z){let Q=Z.findIndex((G)=>ti(G)===J.messageId),Y=Z.findIndex((G)=>ti(G)===J.truncateToMessageId);if(Q<0||Y<0)throw Error("Unable to apply edit: message mapping not found");let X=Z[Q];if(!X||X.role!=="user")throw Error("Unable to apply edit: target message is not editable");let K={role:"user",content:J.content,agentMode:J.agentMode,messageId:X.messageId,dtwMessageID:J.messageId},V=Z.slice(0,Y+1);return V[Q]=K,V}function EC4(J){if(J.type==="message_edited")return J.agentMode;if(J.message.role==="user")return J.message.agentMode;return}function si(J){if(!J||J.length===0)return;return J.map((Z)=>({...Z,queuedMessage:{...Z.queuedMessage,content:Z.queuedMessage.content.map((Q)=>({...Q})),discoveredGuidanceFiles:Z.queuedMessage.discoveredGuidanceFiles?.map((Q)=>({...Q}))}}))}function MC4(J){let Z=J.queuedMessage,Q=Z.content.map((Y)=>({...Y}));return{id:Z.messageId,interrupt:J.interrupt,queuedMessage:{role:"user",content:Q,userState:Z.userState,discoveredGuidanceFiles:Vo0(Z.discoveredGuidanceFiles),meta:Z.createdAt?{sentAt:Date.parse(Z.createdAt)}:void 0,messageId:-1,dtwMessageID:Z.messageId}}}function jX3(J){if(J.type==="queued_messages")return{type:"queued_messages",messages:J.messages.map((Z)=>MC4(Z))};if(J.type==="queued_message_added")return{type:"queued_message_added",message:MC4(J.message)};return{type:"queued_message_removed",queuedMessageId:J.queuedMessageId}}function RX3(J,Z){let Q=jX3(Z);return Fa0(si(J)??[],Q,{dedupeAdded:!0,getQueuedMessageId:(Y)=>Y.id})}async function IX3(J,Z){if(J.useThreadActors){let Q=ik(J.ampURL),Y=lk({endpoint:Q});return{baseURL:Q,threadId:Z.threadId,wsToken:Z.wsToken,wsTokenProvider:async()=>CU(Z.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL}),webSocketProvider:async()=>{let X=await CU(Z.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL});return await Y.threadActor.getOrCreate([X.threadId],{params:{wsToken:X.wsToken},createWithInput:{threadId:X.threadId,threadVersion:X.threadVersion,ownerUserId:X.ownerUserId,agentMode:X.agentMode}}).webSocket("/")},WebSocketClass:WebSocket,maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000,useThreadActors:!0}}return{baseURL:J.workerUrl??l7(J.ampURL),threadId:Z.threadId,wsToken:Z.wsToken,wsTokenProvider:async()=>CU(Z.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL}),WebSocketClass:WebSocket,maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000}}function AC4(J){if(!J)return{};let Z={reconnectCauseType:J.type,reconnectCauseAt:new Date(J.at).toISOString()};if(J.code!==void 0)Z.reconnectCauseCode=J.code;if(J.reason)Z.reconnectCauseReason=J.reason;if(J.error)Z.reconnectCauseError=J.error;return Z}class KX0{threadSubject;agentLoopStateSubject=new V4("idle");executorReadySubject=new V4(!1);deltaState={streamingMessageId:null,streamingBlocks:[],completedMessages:[]};toolProgressByToolUseIDSubject=new V4(new Map);subscriptions=[];threadResumeCursor;messages;queuedMessages;relationships;threadTitle;processedIds;agentLoopState="idle";toolProgressByToolUseID=new Map;compactionStateSubject=new V4("idle");compactionState="idle";lastConnectionState="disconnected";lastConnectionInfo=null;connectionMode;pendingClientWritesByMessageID=new Map;connectedTransportGeneration=0;pendingClientWriteReplayGeneration=null;transport;threadId;constructor(J,Z,Q,Y,X){this.threadId=J.id,this.threadTitle=J.title,this.messages=[...J.messages],this.queuedMessages=si(J.queuedMessages)??[],this.relationships=J.relationships??[],this.processedIds=Q,this.transport=Z,this.threadResumeCursor=YR4(Y),this.threadSubject=new V4(J),this.connectionMode=X?.connectionMode??"observer",this.subscribeToTransport()}static async create(J){let Z=await CU(J.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL,executorType:J.executorType,usesThreadActors:J.useThreadActors}),Q=await ei(Z.threadId,J.threadService);if(!Z.usesDtw){if(J.useThreadActors)throw Error("TODO: Importing threads into rivet thread actors isn't supported");J.onLegacyImportStateChange?.("importing");try{let F=jC4(Q),z=await UX3(Q,J.configService,J.apiKey,{ampURL:J.ampURL,workerURL:J.workerUrl,payload:F});if(await DX3(Z.threadId,J.configService,J.apiKey),z==="imported")Q=HX3(Q,F)}finally{J.onLegacyImportStateChange?.("idle")}}let{messages:Y,processedIds:X}=BX3(Q),K={...Q,id:Z.threadId,messages:Y,queuedMessages:si(Q.queuedMessages),relationships:Q.relationships?[...Q.relationships]:void 0},V=new lY(await IX3(J,Z)),G=new KX0(K,V,X,Q.v,{connectionMode:J.connectionMode});try{if(J.connectOnCreate??!0)await G.transport.ensureConnected({maxAttempts:1,waitForConnectedTimeoutMs:0,onRetryableConnectError:(F)=>{let z=G.transport.getConnectionInfo();_.warn("[dtw] Initial transport connect failed; waiting for reconnect",{threadId:G.threadId,connectionState:z.state,...AC4(z.reconnectCause),error:F})}}),G.emitThread();return G}catch(F){throw G.dispose(),F}}threadChanges(){return this.threadSubject}agentLoopStateChanges(){return this.agentLoopStateSubject}executorReadyChanges(){return this.executorReadySubject}toolProgressByToolUseIDChanges(){return this.toolProgressByToolUseIDSubject}getThread(){return this.threadSubject.getValue()}getAgentLoopState(){return this.agentLoopState}getConnectionState(){return this.lastConnectionInfo?.state??this.transport.getConnectionInfo().state}getConnectionRole(){return this.lastConnectionInfo?.role??this.transport.getConnectionInfo().role}isExecutorConnected(){let J=this.transport.getConnectionInfo();return J.state==="connected"&&J.role==="executor"}getCompactionState(){return this.compactionState}compactionStateChanges(){return this.compactionStateSubject}setEnvironment(J){let Z=this.threadSubject.getValue();if(Z.env?.initial)return;let Q={...Z,...{env:J}};this.threadSubject.next(Q)}setRelationships(J){if(this.relationships.length>0)return;this.relationships=J,this.emitThread()}setAgentMode(J,Z){if(!J)return;let Q=this.threadSubject.getValue();if(!Z?.overwrite&&Q.agentMode)return;if(Q.agentMode===J)return;let Y={...Q,agentMode:J};this.threadSubject.next(Y)}async ensureConnectedForAction(J){if(this.transport.getConnectionInfo().state==="reconnecting"){let X=J==="client-write"?"client write action":"executor action";_.info(`Forcing transport reconnect before ${X}`)}if(await this.transport.ensureConnected({forceReconnectWhenReconnecting:!0,onAttemptTimeout:({attempt:X,maxAttempts:K,nextDelayMs:V})=>{_.info("[dtw] Connection attempt timed out, retrying",{attempt:X,maxAttempts:K,nextDelayMs:V,threadId:this.threadId})}}))return;let Y=this.transport.getConnectionInfo().state;throw Error(Y==="reconnecting"?"Timed out while reconnecting. Please retry after reconnecting.":"Timed out waiting for connection. Please retry.")}editUserMessage(...J){this.transport.editUserMessage(...J)}setThreadTitle(...J){this.transport.setThreadTitle(...J)}cancelAgentLoop(...J){this.transport.cancelAgentLoop(...J)}retryAgentLoop(...J){this.transport.retryAgentLoop(...J)}appendManualBashInvocation(...J){this.transport.appendManualBashInvocation(...J)}resolveToolApproval(...J){this.transport.resolveToolApproval(...J)}sendExecutorToolApprovalRequest(...J){if(!this.isExecutorConnected())return!1;return this.transport.sendExecutorToolApprovalRequest(...J),!0}sendExecutorArtifactUpsert(...J){this.transport.sendExecutorArtifactUpsert(...J)}sendExecutorArtifactDelete(...J){this.transport.sendExecutorArtifactDelete(...J)}sendExecutorFileSystemReadDirectoryResult(...J){this.transport.sendExecutorFileSystemReadDirectoryResult(...J)}sendExecutorFileSystemReadFileResult(...J){this.transport.sendExecutorFileSystemReadFileResult(...J)}errorEvents(){return this.transport.errorEvents()}errors(){return this.transport.errors()}cancelledEvents(){return this.transport.cancelledEvents()}executorTransport(){return this.transport}executorToolApprovalResponses(){return this.transport.executorToolApprovalResponses()}subscribeToProtocolEvents(J){return BC4(this.transport,J)}emitThread(J){let Z=this.threadSubject.getValue(),Q=J?.agentMode??Z.agentMode,Y=wX3(this.deltaState.streamingMessageId,this.deltaState.streamingBlocks,this.messages.length,this.deltaState.streamingParentToolCallId),K=Y?[...this.messages,Y]:[...this.messages],V=K.reduce((F,z)=>Math.max(F,z.messageId),-1)+1,G={...Z,id:this.threadId,...Q?{agentMode:Q}:{},v:this.threadResumeCursor.getVersion(),title:this.threadTitle,messages:K,queuedMessages:this.queuedMessages.length>0?si(this.queuedMessages):void 0,relationships:this.relationships.length>0?[...this.relationships]:void 0,nextMessageId:Math.max(V,0)};this.threadSubject.next(G),this.reconcilePendingClientWrites(G),this.replayPendingClientWritesIfNeeded(G)}reconcilePendingClientWrites(J){if(this.pendingClientWritesByMessageID.size===0)return;let Z=new Set;for(let Q of J.messages){let Y=n6.safeParse(Q.dtwMessageID);if(Y.success)Z.add(Y.data)}for(let Q of J.queuedMessages??[]){let Y=n6.safeParse(Q.id);if(Y.success)Z.add(Y.data);let X=n6.safeParse(Q.queuedMessage.dtwMessageID);if(X.success)Z.add(X.data)}for(let Q of Z)this.pendingClientWritesByMessageID.delete(Q)}replayPendingClientWritesIfNeeded(J){if(this.pendingClientWritesByMessageID.size===0){this.pendingClientWriteReplayGeneration=null;return}if(this.pendingClientWriteReplayGeneration!==this.connectedTransportGeneration)return;if(this.transport.getConnectionInfo().state!=="connected")return;let Q=!1;for(let[Y,X]of this.pendingClientWritesByMessageID)try{this.sendUserMessage(X.content,X.agentMode,X.userState,Y,X.discoveredGuidanceFiles)}catch(K){Q=!0,_.warn("Failed to replay pending client write",{threadId:this.threadId,messageID:Y,error:K});break}if(!Q)this.pendingClientWriteReplayGeneration=null;this.reconcilePendingClientWrites(J)}emitToolProgress(){this.toolProgressByToolUseIDSubject.next(new Map(this.toolProgressByToolUseID))}clearToolProgress(J){if(this.toolProgressByToolUseID.delete(J))this.emitToolProgress()}clearToolProgressFromBlocks(J){for(let Z of J)if(Z.type==="tool_result")this.clearToolProgress(Z.toolUseID)}setCompactionState(J){if(this.compactionState===J)return;this.compactionState=J,this.compactionStateSubject.next(J)}advanceThreadVersionFromSeq(J){this.threadResumeCursor.advanceFromSeq(J)}runTransportHandler(J,Z){try{Z()}catch(Q){_.error("[dtw] Transport handler failed",{threadId:this.threadId,handler:J,connectionState:this.lastConnectionState,error:Q})}}subscribeToTransport(){this.subscriptions.push(this.transport.connectionChanges().subscribe({next:(J)=>{this.runTransportHandler("connectionChanges",()=>{let Z=this.lastConnectionState,Q=this.lastConnectionInfo,Y=J.state!==this.lastConnectionState,X=Q!==null&&(J.role!==Q.role||J.clientId!==Q.clientId);if(!Y&&!X)return;if(Y)this.logConnectionStateTransition(this.lastConnectionState,J);else if(X&&Q)this.logConnectionRoleTransition(Q,J);let K=J.state,V=K==="connected"&&this.lastConnectionState!=="connected";if(V)this.threadResumeCursor.reset();this.lastConnectionState=K,this.lastConnectionInfo={...J};let G=J.state==="connected"&&J.role==="executor";this.executorReadySubject.next(G);let F=G&&Q?.role!=="executor";if(V&&this.connectionMode==="observer"||F&&this.connectionMode==="executor+observer")this.transport.resumeFromVersion(this.threadResumeCursor.getVersion());if(K==="connected"&&Z!=="connected")this.connectedTransportGeneration+=1,this.pendingClientWriteReplayGeneration=this.connectedTransportGeneration,this.replayPendingClientWritesIfNeeded(this.threadSubject.getValue())})}}),this.transport.errors().subscribe({next:(J)=>{this.runTransportHandler("errors",()=>{let Z=J.code==="PARSE_ERROR"?Qa0(J.message):null;if(_.warn("[dtw] Transport error",{threadId:this.threadId,connectionState:this.lastConnectionState,code:J.code,message:Z!==null?"Received invalid DTW payload (see parse details)":J.message,parseErrorSource:Z?.source,parseErrorDirection:Z?.direction,parseErrorStage:Z?.stage,parseErrorSummary:Z?.summary,parseErrorMessageType:Z?.messageType,parseErrorIssues:Z?.issues,parseErrorPayloadPreview:Z?.payloadPreview}),J.code==="PARSE_ERROR"){let Q=Z?.messageType?` (type="${Z.messageType}")`:"";_.warn("[dtw] Invalid DTW parse payload received",{threadId:this.threadId,messageType:Z?.messageType,messageTypeSuffix:Q})}})}}),this.transport.agentStates().subscribe({next:(J)=>{this.runTransportHandler("agentStates",()=>{this.agentLoopState=J.state,this.agentLoopStateSubject.next(J.state)})}}),this.transport.deltas().subscribe({next:(J)=>{this.runTransportHandler("deltas",()=>{if(LX3(J,this.deltaState),J.role==="user"&&J.state==="complete"&&J.blocks)this.clearToolProgressFromBlocks(J.blocks);if(this.deltaState.completedMessages.length>0){for(let Z of this.deltaState.completedMessages)if(Z.role==="user")this.clearToolProgressFromBlocks(Z.blocks);this.messages=OX3(this.messages,this.deltaState.completedMessages,this.processedIds),this.deltaState.completedMessages=[]}this.emitThread()})}}),this.transport.toolProgress().subscribe({next:(J)=>{this.runTransportHandler("toolProgress",()=>{let Z=J.toolCallId,Q=wC4(J.progress),Y=LC4(J.progress),X=this.toolProgressByToolUseID.get(Z),K=J.progress!==void 0?OC4(J.progress):X?.subagentProgressTurns,V=J.progress!==void 0;if(Q===void 0&&Y===void 0&&!V){if(this.toolProgressByToolUseID.delete(Z))this.emitToolProgress();return}let G={status:Y??X?.status??"in-progress",content:Q??X?.content??"",...K!==void 0?{subagentProgressTurns:K}:{}};if(X?.status===G.status&&X?.content===G.content&&X?.subagentProgressTurns===G.subagentProgressTurns)return;this.toolProgressByToolUseID.set(Z,G),this.emitToolProgress()})}}),this.transport.compactionEvents().subscribe({next:(J)=>{this.runTransportHandler("compactionEvents",()=>{if(J.type==="compaction_started"){this.setCompactionState("compacting");return}this.setCompactionState("idle")})}}),this.transport.messageEvents().subscribe({next:(J)=>{this.runTransportHandler("messageEvents",()=>{let Z=EC4(J);if(this.messages=MX3(J,this.messages,this.processedIds),J.message.role==="user")this.clearToolProgressFromBlocks(J.message.content);if(this.deltaState.streamingMessageId===J.message.messageId)this.deltaState.streamingMessageId=null,this.deltaState.streamingBlocks=[],this.deltaState.streamingParentToolCallId=void 0;this.advanceThreadVersionFromSeq(J.seq),this.emitThread({agentMode:Z})})}}),this.transport.messageEdited().subscribe({next:(J)=>{this.runTransportHandler("messageEdited",()=>{let Z=EC4(J);this.messages=AX3(J,this.messages),this.processedIds=NX3(this.messages),this.advanceThreadVersionFromSeq(J.seq),this.emitThread({agentMode:Z})})}}),this.transport.threadTitles().subscribe({next:(J)=>{this.runTransportHandler("threadTitles",()=>{this.threadTitle=J.title??void 0,this.emitThread()})}}),this.transport.threadRelationships().subscribe({next:(J)=>{this.runTransportHandler("threadRelationships",()=>{if(J.relationships.length>0||this.relationships.length===0)this.relationships=J.relationships;this.advanceThreadVersionFromSeq(J.seq),this.emitThread()})}}),this.transport.queuedMessages().subscribe({next:(J)=>{this.runTransportHandler("queuedMessages",()=>{this.queuedMessages=RX3(this.queuedMessages,J),this.emitThread()})}}))}logConnectionStateTransition(J,Z){let Q={threadId:this.threadId,from:J,to:Z.state,threadVersion:this.threadResumeCursor.getVersion(),...AC4(Z.reconnectCause)};if(Z.role)Q.role=Z.role;if(Z.clientId)Q.clientId=Z.clientId;if(Z.threadId&&Z.threadId!==this.threadId)Q.transportThreadId=Z.threadId;if(Z.state==="connected"){if(J==="reconnecting"){_.info("[dtw] Transport reconnected",Q);return}_.info("[dtw] Transport connected",Q);return}if(Z.state==="reconnecting"){_.warn("[dtw] Transport reconnecting",Q);return}if(Z.state==="disconnected"){_.warn("[dtw] Transport disconnected",Q);return}_.info("[dtw] Transport state changed",Q)}logConnectionRoleTransition(J,Z){let Q={threadId:this.threadId,state:Z.state,fromRole:J.role,toRole:Z.role,threadVersion:this.threadResumeCursor.getVersion()};if(J.clientId||Z.clientId)Q.fromClientId=J.clientId,Q.toClientId=Z.clientId;if(Z.threadId&&Z.threadId!==this.threadId)Q.transportThreadId=Z.threadId;_.info("[dtw] Transport role changed",Q)}sendUserMessage(J,Z,Q,Y,X){this.setAgentMode(Z);let K=this.transport.sendUserMessage(J,Z,{userState:Q,messageId:Y,discoveredGuidanceFiles:X});return this.pendingClientWritesByMessageID.set(K,{content:J,agentMode:Z,userState:Q,discoveredGuidanceFiles:X}),K}interruptQueuedMessage(J){this.transport.interruptQueuedMessage(J)}discardQueuedMessages(){let J=si(this.queuedMessages);if(this.queuedMessages.length===0)return;let Z=this.queuedMessages.map((Q)=>n6.safeParse(Q.id)).filter((Q)=>Q.success).map((Q)=>Q.data);this.queuedMessages=[],this.emitThread();try{for(let Q of Z)this.transport.removeQueuedMessage(Q)}catch(Q){throw this.queuedMessages=J??[],this.emitThread(),Q}}resumeFromVersion(J){this.transport.resumeFromVersion(J)}disposeSubscriptionsAndState(){for(let J of this.subscriptions)J.unsubscribe();this.subscriptions.length=0,this.pendingClientWritesByMessageID.clear(),this.pendingClientWriteReplayGeneration=null,this.compactionStateSubject.complete(),this.agentLoopStateSubject.complete(),this.executorReadySubject.complete(),this.toolProgressByToolUseIDSubject.complete()}async disposeAndWaitForClose(){if(this.disposeSubscriptionsAndState(),(await this.transport.disconnectAndWait()).status==="timeout")_.info("[dtw] Timed out waiting for close acknowledgement before dispose",{threadId:this.threadId});this.transport.dispose()}dispose(){this.disposeSubscriptionsAndState(),this.transport.dispose()}}import{mkdir as PX3,readFile as CX3,rm as Go0,writeFile as _X3}from"node:fs/promises";import TX3 from"node:path";c4();var SX3=5000,kX3=100;function vX3(J){try{return process.kill(J,0),!0}catch(Z){return Z.code==="EPERM"}}function Fo0(J,Z){return J.code===Z}function yX3(J){return J instanceof Error?J.message:String(J)}function PC4(J){if(typeof J!=="string")return null;let Z=J.trim();return Z.length>0?Z:null}function xX3(J,Z){let Q=Reflect.get(J,Z);if(typeof Q!=="number")return;return Number.isSafeInteger(Q)&&Q>0?Q:void 0}function fX3(J,Z){return PC4(Reflect.get(J,Z))}function uX3(J){let Z;try{Z=JSON.parse(J)}catch{return}if(!Z||typeof Z!=="object")return;let Q=xX3(Z,"pid"),Y=Reflect.get(Z,"threadId"),X=fX3(Z,"threadTitle");if(Q===void 0||typeof Y!=="string"||!B9(Y))return;return{pid:Q,threadId:Y,threadTitle:X}}function bX3(J){let Z={pid:J.pid,threadId:J.threadId};if(J.threadTitle)Z.threadTitle=J.threadTitle;return`${JSON.stringify(Z)}
|
|
6239
|
+
`;try{if(Z){if(!process.stdout.write(Q)){process.stdout.once("drain",Z);return}Z();return}process.stdout.write(Q)}catch{Z?.()}}function Qo0(J){return Array.from(J,(Z)=>{if(Z>=32&&Z<=126&&Z!==92)return String.fromCharCode(Z);if(Z===92)return"\\\\";return`\\x${Z.toString(16).padStart(2,"0")}`}).join("")}function ZX3(J){return J.ctrlKey&&J.key.toLowerCase()==="c"&&J.eventType!=="repeat"&&J.eventType!=="release"}function HC4(J){try{let Z=UC4(`tmux show-options -gv ${J}`,{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1000}).trim();return Z===""?null:Z}catch{return null}}function QX3(){try{let J=UC4("tmux display-message -p '#{client_termfeatures}'",{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1000}).trim();return J===""?[]:J.split(",").filter(Boolean)}catch{return null}}function TQ(J,Z,Q,Y,X){if(Y.raw){let K=Buffer.from(Z);l8({type:"control",name:Q,stage:X??null,bytes:K.toString("hex"),escaped:Qo0(K)})}J.stream.write(Z)}async function DC4(J={}){let Z=QX0(),Q=new bj,Y=new ai,X=JX3(),K=gG(),V=K?{clientTermFeatures:QX3(),extendedKeysFormat:HC4("extended-keys-format"),extendedKeysMode:HC4("extended-keys")}:null,G=V?.clientTermFeatures?.includes("extkeys")??!1;if(J.raw)l8({type:"debug",controlTarget:X.target,platform:process.platform,stdoutIsTTY:process.stdout.isTTY,stderrIsTTY:process.stderr.isTTY,term:process.env.TERM??null,termProgram:process.env.TERM_PROGRAM??null,termProgramVersion:process.env.TERM_PROGRAM_VERSION??null,tmux:K,tmuxClientTermFeatures:V?.clientTermFeatures??null,tmuxExtendedKeys:K?G:null,tmuxExtendedKeysFormat:V?.extendedKeysFormat??null,tmuxExtendedKeysMode:V?.extendedKeysMode??null});let F=!1,z=null,q=null,W=!1,H=!1,U=()=>{l8({type:"signal",signal:"SIGWINCH",stdout:WC4()})},D=()=>{l8({type:"stdout_resize",stdout:WC4()})},B=new Promise((P)=>{z=P}),N=()=>{if(!q)return null;let P=q;q=null,clearTimeout(P.timeout);let b={stage:P.stage,kittyQueryResponse:P.kittyQueryResponse,deviceAttributes:P.deviceAttributes};return l8({type:"startup_probe",stage:b.stage,timeoutMs:qC4,kittyQueryResponse:b.kittyQueryResponse,deviceAttributes:b.deviceAttributes}),P.resolve(b),b},w=(P)=>{if(!q||P.request!=="u")return;if(q.kittyQueryResponse=P.response,q.deviceAttributes!==null)N()},L=(P)=>{if(!q)return;if(q.deviceAttributes={primary:P.primary,secondary:[...P.secondary]},q.kittyQueryResponse!==null)N()},O=(P)=>{if(q)N();return new Promise((b)=>{q={stage:P,kittyQueryResponse:null,deviceAttributes:null,resolve:b,timeout:setTimeout(()=>{N()},qC4)},TQ(X,sY3,"kitty-query",J,P),TQ(X,aY3,"device-attributes-query",J,P)})},E=()=>{if(F)return;if(F=!0,H)process.off("SIGWINCH",U);if(process.stdout.isTTY)process.stdout.off("resize",D);process.off("SIGINT",A),process.off("SIGTERM",j),process.off("exit",E),N();try{if(W)TQ(X,$X3,"win32-input-mode-disable",J);if(TQ(X,rY3,"focus-disable",J),TQ(X,Y.disableInBandResize(),"inband-resize-disable",J),TQ(X,Y.disableBracketedPaste(),"bracketed-paste-disable",J),K)TQ(X,Y.disableModifyOtherKeys(),"tmux-extended-keys-disable",J);TQ(X,Y.disableKittyKeyboard(),"kitty-keyboard-disable",J)}catch{}X.dispose(),Z.dispose()},M=(P)=>{if(F)return;process.exitCode=P,E(),z?.()},A=()=>{M(130)},j=()=>{M(143)};process.once("SIGINT",A),process.once("SIGTERM",j),process.once("exit",E);try{process.on("SIGWINCH",U),H=!0}catch(P){l8({type:"signal_subscription_error",signal:"SIGWINCH",error:P instanceof Error?P.message:String(P)})}if(process.stdout.isTTY)process.stdout.on("resize",D);Q.onKey((P)=>{let b={type:"key",key:P.key,code:P.code??null,modifiers:{shift:P.shiftKey,ctrl:P.ctrlKey,alt:P.altKey,meta:P.metaKey},eventType:P.eventType??null};if(ZX3(P)){l8(b,()=>M(0));return}l8(b)}),Q.onDcs((P)=>{l8(P)}),Q.onOsc((P)=>{l8(P)}),Q.onApc((P)=>{l8(P)}),Q.onPaste((P)=>{l8(P)}),Q.onSgrMouse((P)=>{l8(P)}),Q.onFocus((P)=>{l8(P)}),Q.onMouse((P)=>{l8(P)}),Q.onResize((P)=>{l8(P)}),Q.onColorPaletteChange((P)=>{l8(P)}),Q.onCursorPositionReport((P)=>{l8(P)}),Q.onDeviceAttributes((P)=>{L(P),l8(P)}),Q.onDecrqss((P)=>{if(w(P),P.request==="u"){l8({type:"kitty_query_response",response:P.response});return}l8(P)}),Z.on("data",(P)=>{if(J.raw)l8({type:"raw",bytes:Buffer.from(P).toString("hex"),escaped:Qo0(P)});Q.parse(P)});let I=[...Z.earlyInputBuffer];Z.earlyInputBuffer.length=0;for(let P of I){if(J.raw)l8({type:"raw",bytes:P.toString("hex"),escaped:Qo0(P)});Q.parse(P)}await O("before_enable"),TQ(X,oY3,"focus-enable",J),TQ(X,Y.enableInBandResize(),"inband-resize-enable",J),TQ(X,Y.enableBracketedPaste(),"bracketed-paste-enable",J),TQ(X,Y.enableKittyKeyboard({reportEventTypes:!0}),"kitty-keyboard-enable",J);let S=await O("after_enable");if(process.platform==="win32"&&S.kittyQueryResponse===null)W=!0,l8({type:"win32_input_mode",enabled:!0,reason:"kitty-unavailable",note:"Enabling ConPTY win32-input-mode fallback for key down/up events"}),TQ(X,eY3,"win32-input-mode-enable",J);if(K)l8({type:"tmux_info",extendedKeysFormat:V?.extendedKeysFormat??null,extendedKeysMode:V?.extendedKeysMode??null,hasExtkeysFeature:G,note:"tmux does not proxy kitty query/event-type support; enabling modifyOtherKeys mode 2 for press-only extended keys"}),TQ(X,tY3,"tmux-extended-keys-enable",J);await B}import{execFile as zK3}from"node:child_process";import{lstat as F_4,mkdir as qK3,readFile as WK3,rm as _o0,writeFile as HK3}from"node:fs/promises";import sY from"node:path";import f$ from"node:process";import{createInterface as UK3}from"node:readline";import{promisify as DK3}from"node:util";class O5{state=[!0,!1,!0,!1,!0,!1,!0,!1];previousState=[];generation=0;maxGenerations=15;neighborMap=[[1,3,4,5,7],[0,2,4,5,6],[1,3,5,6,7],[0,2,4,6,7],[0,1,3,5,7],[0,1,2,4,6],[1,2,3,5,7],[0,2,3,4,6]];step(){let J=this.state.map((K,V)=>{let G=this.neighborMap[V].filter((F)=>this.state[F]).length;if(K)return G===2||G===3;return G===3||G===6}),Z=J.every((K,V)=>K===this.state[V]),Q=this.previousState.length>0&&J.every((K,V)=>K===this.previousState[V]);this.previousState=[...this.state],this.state=J,this.generation++;let Y=J.every((K)=>!K),X=J.filter((K)=>K).length;if(Z||Q||this.generation>=this.maxGenerations||Y||X<2){let K;do K=Array.from({length:8},()=>Math.random()>0.6);while(K.filter((V)=>V).length<3);this.state=K,this.previousState=[],this.generation=0}}toBraille(){let J=[0,1,2,6,3,4,5,7],Z=10240;for(let Q=0;Q<8;Q++)if(this.state[Q])Z|=1<<J[Q];return String.fromCharCode(Z)}}n0();k9();U4();n0();tZ();E1();import{mkdir as YX3,writeFile as XX3}from"node:fs/promises";import KX3 from"node:path";function VX3(J){let Z=J?.trim();return Z&&Z.length>0?Z:void 0}function GX3(J){let Z=J.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48);return Z.length>0?Z:"trace"}function FX3(J,Z){let Q=new Date(J).toISOString().replace(/[:.]/g,"-");return`${Z?`dtw-trace-${GX3(Z)}`:"dtw-trace"}-${Q}-${crypto.randomUUID().slice(0,8)}`}function Yo0(J){let Z=JSON.stringify(J);if(Z===void 0)return null;return JSON.parse(Z)}class Xo0{options;traceFilePath;session;constructor(J){this.options=J;let Z=Date.now(),Q=VX3(J.traceName),Y=FX3(Z,Q);this.traceFilePath=KX3.join(J.traceDir,`${Y}.json`),this.session={schemaVersion:1,sessionID:Y,createdAt:Z,runtimeMode:J.runtimeMode,...Q?{traceName:Q}:{},threadId:J.threadId,scriptedCommands:[...J.scriptedCommands??[]],protocolEvents:[],providerStateEvents:[],adapterStateEvents:[],commandEvents:[],timeline:[]}}nextTimelineIndex(){return this.session.timeline.length}recordProtocolEvent(J,Z){let Q=this.nextTimelineIndex(),Y=Date.now(),X={timelineIndex:Q,timestamp:Y,eventName:J,payload:Yo0(Z)};this.session.protocolEvents.push(X),this.session.timeline.push({timelineIndex:Q,timestamp:Y,kind:"protocol",protocolIndex:this.session.protocolEvents.length-1})}recordProviderState(J,Z){let Q=this.nextTimelineIndex(),Y=Date.now(),X={timelineIndex:Q,timestamp:Y,reason:J,state:Yo0(Z)};this.session.providerStateEvents.push(X),this.session.timeline.push({timelineIndex:Q,timestamp:Y,kind:"provider_state",providerStateIndex:this.session.providerStateEvents.length-1})}recordAdapterState(J,Z){let Q=this.nextTimelineIndex(),Y=Date.now(),X={timelineIndex:Q,timestamp:Y,reason:J,state:Yo0(Z)};this.session.adapterStateEvents.push(X),this.session.timeline.push({timelineIndex:Q,timestamp:Y,kind:"adapter_state",adapterStateIndex:this.session.adapterStateEvents.length-1})}recordCommand(J){let Z=this.nextTimelineIndex(),Q=Date.now();this.session.commandEvents.push({timelineIndex:Z,timestamp:Q,command:J}),this.session.timeline.push({timelineIndex:Z,timestamp:Q,kind:"command",commandIndex:this.session.commandEvents.length-1})}async flush(){await YX3(this.options.traceDir,{recursive:!0});let J=JSON.stringify(this.session,null,2);return await XX3(this.traceFilePath,J,"utf-8"),this.traceFilePath}}function BC4(J,Z){let Q=[J.connectionChanges().subscribe({next:(Y)=>Z("connection_changes",Y)}),J.errors().subscribe({next:(Y)=>Z("errors",Y)}),J.errorEvents().subscribe({next:(Y)=>Z("error_events",Y)}),J.agentStates().subscribe({next:(Y)=>Z("agent_states",Y)}),J.deltas().subscribe({next:(Y)=>Z("deltas",Y)}),J.messageEvents().subscribe({next:(Y)=>Z("message_events",Y)}),J.messageEdited().subscribe({next:(Y)=>Z("message_edited",Y)}),J.editRejected().subscribe({next:(Y)=>Z("edit_rejected",Y)}),J.threadTitles().subscribe({next:(Y)=>Z("thread_titles",Y)}),J.queuedMessages().subscribe({next:(Y)=>Z("queued_messages",Y)}),J.retryEvents().subscribe({next:(Y)=>Z("retry_events",Y)}),J.cancelledEvents().subscribe({next:(Y)=>Z("cancelled_events",Y)}),J.toolLeases().subscribe({next:(Y)=>Z("tool_leases",Y)}),J.toolLeaseRevoked().subscribe({next:(Y)=>Z("tool_lease_revoked",Y)}),J.toolApprovalQueue().subscribe({next:(Y)=>Z("tool_approval_queue",Y)}),J.executorToolApprovalResponses().subscribe({next:(Y)=>Z("executor_tool_approval_responses",Y)}),J.toolProgress().subscribe({next:(Y)=>Z("tool_progress",Y)}),J.executorErrors().subscribe({next:(Y)=>Z("executor_errors",Y)}),J.executorConnected().subscribe({next:(Y)=>Z("executor_connected",Y)}),J.executorRollbackRequests().subscribe({next:(Y)=>Z("executor_rollback_requests",Y)}),J.observers().subscribe({next:(Y)=>Z("observers",Y)}),J.executorStatuses().subscribe({next:(Y)=>Z("executor_statuses",Y)}),J.environmentUpdates().subscribe({next:(Y)=>Z("environment_updates",Y)}),J.artifacts().subscribe({next:(Y)=>Z("artifacts",Y)}),J.compactionEvents().subscribe({next:(Y)=>Z("compaction_events",Y)}),J.compactionRecords().subscribe({next:(Y)=>Z("compaction_records",Y)})];return{unsubscribe:()=>{for(let Y of Q)Y.unsubscribe()}}}function XX0(J){return typeof J==="object"&&J!==null}function Ko0(J){if(!Array.isArray(J))return;return J}function NC4(J){let Z=J.trim();if(Z.length===0)return;try{let Q=JSON.parse(Z);return Ko0(Q)}catch{return}}function YX0(J){if(typeof J==="string")return J;if(!XX0(J))return;if("output"in J&&typeof J.output==="string")return J.output;if("displayMessage"in J&&typeof J.displayMessage==="string")return J.displayMessage;if("message"in J&&typeof J.message==="string")return J.message;if("reason"in J&&typeof J.reason==="string")return J.reason;if("result"in J){let Z=YX0(J.result);if(Z!==void 0)return Z}if("error"in J){let Z=YX0(J.error);if(Z!==void 0)return Z}if("value"in J)return YX0(J.value);return}function zX3(J){return J.type==="text"}function wC4(J){if(J===void 0)return;let Z;try{Z=wi(J,"snapshot")}catch{return}if(Z.type==="snapshot")return YX0(Z.value);let Q=(Z.blocks??[]).filter(zX3).map((Y)=>Y.text).join("");return Q.length>0?Q:void 0}var qX3=["queued","blocked-on-user","in-progress","rejected-by-user","cancellation-requested","cancelled","done","error"];function WX3(J){return typeof J==="string"&&qX3.includes(J)}function LC4(J){if(J===void 0)return;let Z;try{Z=wi(J,"snapshot")}catch{return}if(Z.type!=="snapshot")return;let Q=Z.value;if(!XX0(Q))return;if(!("status"in Q)||!WX3(Q.status))return;return Q.status}function OC4(J){let Z=Ko0(J);if(Z!==void 0)return Z;if(!XX0(J)||typeof J.type!=="string")return;if(J.type==="snapshot"){let Y=J.value,X=Ko0(Y);if(X!==void 0)return X;if(typeof Y==="string")return NC4(Y);return}if(J.type!=="delta"||!Array.isArray(J.blocks))return;let Q=J.blocks.map((Y)=>{if(!XX0(Y)||Y.type!=="text"||typeof Y.text!=="string")return"";return Y.text}).join("");return NC4(Q)}function jC4(J){let Z=[],Q=0;for(let X of J.messages){if(X.role==="user"){Z.push({messageId:Eq(),role:"user",content:[...X.content],meta:X.meta,userState:X.userState,readAt:X.readAt,parentToolUseId:X.parentToolUseId});continue}if(X.role==="assistant"){Z.push({messageId:Eq(),role:"assistant",content:[...X.content],meta:X.meta,usage:X.usage,readAt:X.readAt,cancelled:X.state.type==="cancelled",parentToolUseId:X.parentToolUseId});continue}let K=X.content.filter((V)=>V.type==="manual_bash_invocation");if(K.length>0)Z.push({messageId:Eq(),role:"info",content:K,parentToolUseId:X.parentToolUseId});for(let V of X.content){if(V.type!=="summary"||V.summary.type!=="message")continue;Q+=1,Z.push({messageId:Eq(),role:"assistant",content:[{type:"text",text:V.summary.summary}],parentToolUseId:X.parentToolUseId})}}let Y=J.meta?.status!==void 0||J.meta?.executorType!==void 0?{...J.meta?.status!==void 0?{status:J.meta.status}:{},...J.meta?.executorType!==void 0?{executorType:J.meta.executorType}:{}}:void 0;return{id:J.id,v:J.v,...J.title?{title:J.title}:{},...J.agentMode?{agentMode:J.agentMode}:{},...Y?{meta:Y}:{},messages:Z,convertedSummaryMessages:Q}}function HX3(J,Z){let Q=Z.messages.map((Y,X)=>{if(Y.role==="user")return{role:"user",content:[...Y.content],meta:Y.meta,userState:Y.userState,readAt:Y.readAt,messageId:X,dtwMessageID:Y.messageId,parentToolUseId:Y.parentToolUseId};if(Y.role==="assistant"){let K=Y.content.some((V)=>V.type==="tool_use");return{role:"assistant",content:[...Y.content],meta:Y.meta,usage:Y.usage,readAt:Y.readAt,state:Y.cancelled?{type:"cancelled"}:{type:"complete",stopReason:K?"tool_use":"end_turn"},messageId:X,dtwMessageID:Y.messageId,parentToolUseId:Y.parentToolUseId}}return{role:"info",content:[...Y.content],messageId:X,dtwMessageID:Y.messageId,parentToolUseId:Y.parentToolUseId}});return{...J,messages:Q}}async function CU(J,Z,Q,Y={}){let X={...J?{threadId:J}:{},...Y.repositoryURL?{repositoryURL:Y.repositoryURL}:{},...!J&&Y.executorType?{executorType:Y.executorType}:{},...Y.agentMode?{agentMode:Y.agentMode}:{},...Y.relationship?{relationship:Y.relationship}:{},...Y.usesThreadActors?{usesThreadActors:!0}:{}},K=await J2("/api/durable-thread-workers",RC4({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(X),signal:Y.signal},Q),Z);if(!K.ok)throw Error(`Failed to create DTW thread: ${K.status} ${await K.text()}`);let V=await K.json();if(!V.threadId||!V.wsToken)throw Error("DTW thread creation response missing threadId or wsToken");if(!V.ownerUserId||typeof V.threadVersion!=="number")throw Error("DTW thread creation response missing ownerUserId or threadVersion");return{threadId:V.threadId,wsToken:V.wsToken,usesDtw:V.usesDtw??!0,executorType:V.executorType??null,ownerUserId:V.ownerUserId,threadVersion:V.threadVersion,...V.agentMode?{agentMode:V.agentMode}:{}}}async function UX3(J,Z,Q,Y){let X=await Z.getLatest(),K=Q??await X.secrets.getToken("apiKey",X.settings.url);if(!K)throw Error("API key required. Please run `amp login` first.");let V=Y.payload??jC4(J),G=Y.workerURL??l7(Y.ampURL),F=await fetch(`${G}/threads/${J.id}/import`,{method:"POST",headers:{Authorization:`Bearer ${K}`,"Content-Type":"application/json"},body:JSON.stringify({thread:V})});if(F.status===409)return"already-imported";if(!F.ok)throw Error(`Failed to import thread into DTW: ${F.status} ${await F.text()}`);if((await F.json()).ok!==!0)throw Error("Failed to import thread into DTW: import endpoint returned an invalid response");return"imported"}async function DX3(J,Z,Q){let Y=await J2(`/api/durable-thread-workers/${J}`,RC4({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({executorType:"local-client"})},Q),Z);if(!Y.ok)throw Error(`Failed to mark thread as DTW-backed: ${Y.status} ${await Y.text()}`);let X=await Y.json();if(X.ok!==!0||X.usesDtw!==!0||X.executorType!=="local-client")throw Error("Failed to mark thread as DTW-backed: server returned an invalid response")}async function ei(J,Z){let Q=await Z.get(J);if(!Q)throw Error(`Failed to fetch thread snapshot: thread ${J} not found`);return Q}function RC4(J,Z){if(!Z)return J;return{...J,headers:{...J?.headers,Authorization:`Bearer ${Z}`}}}function ti(J){let Z=n6.safeParse(J.dtwMessageID);if(Z.success)return Z.data;let Q=n6.safeParse(`${J.messageId}`);return Q.success?Q.data:null}function BX3(J){let Z=[],Q=new Set;for(let[Y,X]of J.messages.entries()){let K=ti(X);if(K)Q.add(K);Z.push({...X,messageId:Y})}return{messages:Z,processedIds:Q}}function NX3(J){let Z=new Set;for(let Q of J){let Y=ti(Q);if(Y)Z.add(Y)}return Z}function ri(J,Z){let Q=[...J];for(let Y of Z)if(Y.type==="text"){let X=Q[Q.length-1];if(X?.type==="text")Q[Q.length-1]={...X,text:X.text+Y.text};else Q.push(Y)}else if(Y.type==="tool_use"){let X=Q.findIndex((K)=>K.type==="tool_use"&&K.id===Y.id);if(X>=0)Q[X]=Y;else Q.push(Y)}else if(Y.type==="thinking"){let X=Q[Q.length-1];if(X?.type==="thinking")Q[Q.length-1]={...X,thinking:X.thinking+Y.thinking};else Q.push(Y)}else Q.push(Y);return Q}function wX3(J,Z,Q,Y){if(!J||Z.length===0)return null;return{role:"assistant",content:Z,state:{type:"streaming"},messageId:Q,parentToolUseId:Y}}function LX3(J,Z){let Q=J.parentToolCallId,Y=J.role==="assistant"?J:null,{completedMessages:X}=Z;if(J.state==="complete"||J.state==="error"){if(Z.streamingMessageId!==null&&J.messageId!==Z.streamingMessageId){if(Z.streamingBlocks.length>0)X.push({messageId:Z.streamingMessageId,role:"assistant",blocks:Z.streamingBlocks,parentToolCallId:Z.streamingParentToolCallId});if(Z.streamingMessageId=null,Z.streamingBlocks=[],Z.streamingParentToolCallId=void 0,J.blocks&&J.blocks.length>0)if(J.role==="user")X.push({messageId:J.messageId,role:"user",blocks:J.blocks??[],parentToolCallId:Q});else X.push({messageId:J.messageId,role:"assistant",blocks:J.blocks??[],usage:Y?.usage,parentToolCallId:Q});return}if(Z.streamingMessageId===null&&J.blocks&&J.blocks.length>0){if(J.role==="user"){let V=J.blocks;X.push({messageId:J.messageId,role:"user",blocks:V,parentToolCallId:Q})}else{let V=J.blocks;X.push({messageId:J.messageId,role:"assistant",blocks:V,usage:Y?.usage,parentToolCallId:Q})}return}let K=Z.streamingBlocks;if(J.messageId===Z.streamingMessageId&&J.blocks&&J.role==="assistant")K=ri(Z.streamingBlocks,J.blocks);if(Z.streamingMessageId&&K.length>0)X.push({messageId:Z.streamingMessageId,role:"assistant",blocks:K,usage:Y?.usage,parentToolCallId:Z.streamingParentToolCallId});Z.streamingMessageId=null,Z.streamingBlocks=[],Z.streamingParentToolCallId=void 0;return}if(J.state==="tool_use"){if(J.role!=="assistant")return;if(Z.streamingMessageId===null||Z.streamingMessageId!==J.messageId)Z.streamingMessageId=J.messageId,Z.streamingBlocks=ri([],J.blocks??[]),Z.streamingParentToolCallId=Q;else if(J.blocks)Z.streamingBlocks=ri(Z.streamingBlocks,J.blocks);if(Z.streamingBlocks.length>0)X.push({messageId:Z.streamingMessageId??J.messageId,role:"assistant",blocks:Z.streamingBlocks,usage:Y?.usage,parentToolCallId:Z.streamingParentToolCallId});Z.streamingMessageId=null,Z.streamingBlocks=[],Z.streamingParentToolCallId=void 0;return}if(J.state==="start"||J.state==="generating"){if(J.role!=="assistant")return;if(Z.streamingMessageId===null||Z.streamingMessageId!==J.messageId)Z.streamingMessageId=J.messageId,Z.streamingBlocks=ri([],J.blocks??[]),Z.streamingParentToolCallId=Q;else if(J.blocks)Z.streamingBlocks=ri(Z.streamingBlocks,J.blocks)}}function OX3(J,Z,Q){if(Z.length===0)return J;let Y=[],X=J.length;for(let K of Z){if(Q.has(K.messageId))continue;Q.add(K.messageId);let V=X++;if(K.role==="assistant")Y.push({role:"assistant",content:K.blocks,state:{type:"complete",stopReason:"end_turn"},usage:K.usage,messageId:V,dtwMessageID:K.messageId,parentToolUseId:K.parentToolCallId});else Y.push({role:"user",content:K.blocks,messageId:V,dtwMessageID:K.messageId,parentToolUseId:K.parentToolCallId})}if(Y.length===0)return J;return[...J,...Y]}function EX3(J){if(typeof J!=="number"||!Number.isFinite(J))return 0;return Math.max(0,Math.trunc(J))}function Vo0(J){if(!J||J.length===0)return;return J.map((Z)=>({uri:Z.uri,lineCount:EX3(Z.lineCount),...typeof Z.content==="string"?{content:Z.content}:{}}))}function MX3(J,Z,Q){let Y=J.message.messageId;if(Q.has(Y)){let K=Z.findIndex((G)=>ti(G)===Y);if(K<0)return Z;let V=Z[K];if(!V)return Z;if(J.message.role!==V.role)return Z;if(V.role==="user"&&J.message.role==="user"){let G={...V,content:J.message.content,agentMode:J.message.agentMode,userState:J.message.userState,discoveredGuidanceFiles:Vo0(J.message.discoveredGuidanceFiles),parentToolUseId:J.parentToolUseId},F=[...Z];return F[K]=G,F}if(V.role==="assistant"&&J.message.role==="assistant"){let G={...V,content:J.message.content,usage:J.message.usage,state:{type:"complete",stopReason:"end_turn"},parentToolUseId:J.parentToolUseId},F=[...Z];return F[K]=G,F}if(V.role==="info"&&J.message.role==="info"){let G={...V,content:J.message.content,parentToolUseId:J.parentToolUseId},F=[...Z];return F[K]=G,F}return Z}Q.add(Y);let X=Z.length;if(J.message.role==="assistant")return[...Z,{role:"assistant",content:J.message.content,state:{type:"complete",stopReason:"end_turn"},usage:J.message.usage,messageId:X,dtwMessageID:Y,parentToolUseId:J.parentToolUseId}];if(J.message.role==="info")return[...Z,{role:"info",content:J.message.content,messageId:X,dtwMessageID:Y,parentToolUseId:J.parentToolUseId}];return[...Z,{role:"user",content:J.message.content,agentMode:J.message.agentMode,userState:J.message.userState,discoveredGuidanceFiles:Vo0(J.message.discoveredGuidanceFiles),messageId:X,dtwMessageID:Y,parentToolUseId:J.parentToolUseId}]}function AX3(J,Z){let Q=Z.findIndex((G)=>ti(G)===J.messageId),Y=Z.findIndex((G)=>ti(G)===J.truncateToMessageId);if(Q<0||Y<0)throw Error("Unable to apply edit: message mapping not found");let X=Z[Q];if(!X||X.role!=="user")throw Error("Unable to apply edit: target message is not editable");let K={role:"user",content:J.content,agentMode:J.agentMode,messageId:X.messageId,dtwMessageID:J.messageId},V=Z.slice(0,Y+1);return V[Q]=K,V}function EC4(J){if(J.type==="message_edited")return J.agentMode;if(J.message.role==="user")return J.message.agentMode;return}function si(J){if(!J||J.length===0)return;return J.map((Z)=>({...Z,queuedMessage:{...Z.queuedMessage,content:Z.queuedMessage.content.map((Q)=>({...Q})),discoveredGuidanceFiles:Z.queuedMessage.discoveredGuidanceFiles?.map((Q)=>({...Q}))}}))}function MC4(J){let Z=J.queuedMessage,Q=Z.content.map((Y)=>({...Y}));return{id:Z.messageId,interrupt:J.interrupt,queuedMessage:{role:"user",content:Q,userState:Z.userState,discoveredGuidanceFiles:Vo0(Z.discoveredGuidanceFiles),meta:Z.createdAt?{sentAt:Date.parse(Z.createdAt)}:void 0,messageId:-1,dtwMessageID:Z.messageId}}}function jX3(J){if(J.type==="queued_messages")return{type:"queued_messages",messages:J.messages.map((Z)=>MC4(Z))};if(J.type==="queued_message_added")return{type:"queued_message_added",message:MC4(J.message)};return{type:"queued_message_removed",queuedMessageId:J.queuedMessageId}}function RX3(J,Z){let Q=jX3(Z);return Fa0(si(J)??[],Q,{dedupeAdded:!0,getQueuedMessageId:(Y)=>Y.id})}async function IX3(J,Z){if(J.useThreadActors){let Q=ik(J.ampURL),Y=lk({endpoint:Q});return{baseURL:Q,threadId:Z.threadId,wsToken:Z.wsToken,wsTokenProvider:async()=>CU(Z.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL}),webSocketProvider:async()=>{let X=await CU(Z.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL});return await Y.threadActor.getOrCreate([X.threadId],{params:{wsToken:X.wsToken},createWithInput:{threadId:X.threadId,threadVersion:X.threadVersion,ownerUserId:X.ownerUserId,agentMode:X.agentMode}}).webSocket("/")},WebSocketClass:WebSocket,maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000,useThreadActors:!0}}return{baseURL:J.workerUrl??l7(J.ampURL),threadId:Z.threadId,wsToken:Z.wsToken,wsTokenProvider:async()=>CU(Z.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL}),WebSocketClass:WebSocket,maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000}}function AC4(J){if(!J)return{};let Z={reconnectCauseType:J.type,reconnectCauseAt:new Date(J.at).toISOString()};if(J.code!==void 0)Z.reconnectCauseCode=J.code;if(J.reason)Z.reconnectCauseReason=J.reason;if(J.error)Z.reconnectCauseError=J.error;return Z}class KX0{threadSubject;agentLoopStateSubject=new V4("idle");executorReadySubject=new V4(!1);deltaState={streamingMessageId:null,streamingBlocks:[],completedMessages:[]};toolProgressByToolUseIDSubject=new V4(new Map);subscriptions=[];threadResumeCursor;messages;queuedMessages;relationships;threadTitle;processedIds;agentLoopState="idle";toolProgressByToolUseID=new Map;compactionStateSubject=new V4("idle");compactionState="idle";lastConnectionState="disconnected";lastConnectionInfo=null;connectionMode;pendingClientWritesByMessageID=new Map;connectedTransportGeneration=0;pendingClientWriteReplayGeneration=null;transport;threadId;constructor(J,Z,Q,Y,X){this.threadId=J.id,this.threadTitle=J.title,this.messages=[...J.messages],this.queuedMessages=si(J.queuedMessages)??[],this.relationships=J.relationships??[],this.processedIds=Q,this.transport=Z,this.threadResumeCursor=YR4(Y),this.threadSubject=new V4(J),this.connectionMode=X?.connectionMode??"observer",this.subscribeToTransport()}static async create(J){let Z=await CU(J.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL,executorType:J.executorType,usesThreadActors:J.useThreadActors}),Q=await ei(Z.threadId,J.threadService);if(!Z.usesDtw){if(J.useThreadActors)throw Error("TODO: Importing threads into rivet thread actors isn't supported");J.onLegacyImportStateChange?.("importing");try{let F=jC4(Q),z=await UX3(Q,J.configService,J.apiKey,{ampURL:J.ampURL,workerURL:J.workerUrl,payload:F});if(await DX3(Z.threadId,J.configService,J.apiKey),z==="imported")Q=HX3(Q,F)}finally{J.onLegacyImportStateChange?.("idle")}}let{messages:Y,processedIds:X}=BX3(Q),K={...Q,id:Z.threadId,messages:Y,queuedMessages:si(Q.queuedMessages),relationships:Q.relationships?[...Q.relationships]:void 0},V=new lY(await IX3(J,Z)),G=new KX0(K,V,X,Q.v,{connectionMode:J.connectionMode});try{if(J.connectOnCreate??!0)await G.transport.ensureConnected({maxAttempts:1,waitForConnectedTimeoutMs:0,onRetryableConnectError:(F)=>{let z=G.transport.getConnectionInfo();_.warn("[dtw] Initial transport connect failed; waiting for reconnect",{threadId:G.threadId,connectionState:z.state,...AC4(z.reconnectCause),error:F})}}),G.emitThread();return G}catch(F){throw G.dispose(),F}}threadChanges(){return this.threadSubject}agentLoopStateChanges(){return this.agentLoopStateSubject}executorReadyChanges(){return this.executorReadySubject}toolProgressByToolUseIDChanges(){return this.toolProgressByToolUseIDSubject}getThread(){return this.threadSubject.getValue()}getAgentLoopState(){return this.agentLoopState}getConnectionState(){return this.lastConnectionInfo?.state??this.transport.getConnectionInfo().state}getConnectionRole(){return this.lastConnectionInfo?.role??this.transport.getConnectionInfo().role}getCompactionState(){return this.compactionState}compactionStateChanges(){return this.compactionStateSubject}setEnvironment(J){let Z=this.threadSubject.getValue();if(Z.env?.initial)return;let Q={...Z,...{env:J}};this.threadSubject.next(Q)}setRelationships(J){if(this.relationships.length>0)return;this.relationships=J,this.emitThread()}setAgentMode(J,Z){if(!J)return;let Q=this.threadSubject.getValue();if(!Z?.overwrite&&Q.agentMode)return;if(Q.agentMode===J)return;let Y={...Q,agentMode:J};this.threadSubject.next(Y)}async ensureConnectedForAction(J){if(this.transport.getConnectionInfo().state==="reconnecting"){let X=J==="client-write"?"client write action":"executor action";_.info(`Forcing transport reconnect before ${X}`)}if(await this.transport.ensureConnected({forceReconnectWhenReconnecting:!0,onAttemptTimeout:({attempt:X,maxAttempts:K,nextDelayMs:V})=>{_.info("[dtw] Connection attempt timed out, retrying",{attempt:X,maxAttempts:K,nextDelayMs:V,threadId:this.threadId})}}))return;let Y=this.transport.getConnectionInfo().state;throw Error(Y==="reconnecting"?"Timed out while reconnecting. Please retry after reconnecting.":"Timed out waiting for connection. Please retry.")}editUserMessage(...J){this.transport.editUserMessage(...J)}setThreadTitle(...J){this.transport.setThreadTitle(...J)}cancelAgentLoop(...J){this.transport.cancelAgentLoop(...J)}retryAgentLoop(...J){this.transport.retryAgentLoop(...J)}appendManualBashInvocation(...J){this.transport.appendManualBashInvocation(...J)}resolveToolApproval(...J){this.transport.resolveToolApproval(...J)}errorEvents(){return this.transport.errorEvents()}errors(){return this.transport.errors()}cancelledEvents(){return this.transport.cancelledEvents()}getTransport(){return this.transport}subscribeToProtocolEvents(J){return BC4(this.transport,J)}emitThread(J){let Z=this.threadSubject.getValue(),Q=J?.agentMode??Z.agentMode,Y=wX3(this.deltaState.streamingMessageId,this.deltaState.streamingBlocks,this.messages.length,this.deltaState.streamingParentToolCallId),K=Y?[...this.messages,Y]:[...this.messages],V=K.reduce((F,z)=>Math.max(F,z.messageId),-1)+1,G={...Z,id:this.threadId,...Q?{agentMode:Q}:{},v:this.threadResumeCursor.getVersion(),title:this.threadTitle,messages:K,queuedMessages:this.queuedMessages.length>0?si(this.queuedMessages):void 0,relationships:this.relationships.length>0?[...this.relationships]:void 0,nextMessageId:Math.max(V,0)};this.threadSubject.next(G),this.reconcilePendingClientWrites(G),this.replayPendingClientWritesIfNeeded(G)}reconcilePendingClientWrites(J){if(this.pendingClientWritesByMessageID.size===0)return;let Z=new Set;for(let Q of J.messages){let Y=n6.safeParse(Q.dtwMessageID);if(Y.success)Z.add(Y.data)}for(let Q of J.queuedMessages??[]){let Y=n6.safeParse(Q.id);if(Y.success)Z.add(Y.data);let X=n6.safeParse(Q.queuedMessage.dtwMessageID);if(X.success)Z.add(X.data)}for(let Q of Z)this.pendingClientWritesByMessageID.delete(Q)}replayPendingClientWritesIfNeeded(J){if(this.pendingClientWritesByMessageID.size===0){this.pendingClientWriteReplayGeneration=null;return}if(this.pendingClientWriteReplayGeneration!==this.connectedTransportGeneration)return;if(this.transport.getConnectionInfo().state!=="connected")return;let Q=!1;for(let[Y,X]of this.pendingClientWritesByMessageID)try{this.sendUserMessage(X.content,X.agentMode,X.userState,Y,X.discoveredGuidanceFiles)}catch(K){Q=!0,_.warn("Failed to replay pending client write",{threadId:this.threadId,messageID:Y,error:K});break}if(!Q)this.pendingClientWriteReplayGeneration=null;this.reconcilePendingClientWrites(J)}emitToolProgress(){this.toolProgressByToolUseIDSubject.next(new Map(this.toolProgressByToolUseID))}clearToolProgress(J){if(this.toolProgressByToolUseID.delete(J))this.emitToolProgress()}clearToolProgressFromBlocks(J){for(let Z of J)if(Z.type==="tool_result")this.clearToolProgress(Z.toolUseID)}setCompactionState(J){if(this.compactionState===J)return;this.compactionState=J,this.compactionStateSubject.next(J)}advanceThreadVersionFromSeq(J){this.threadResumeCursor.advanceFromSeq(J)}runTransportHandler(J,Z){try{Z()}catch(Q){_.error("[dtw] Transport handler failed",{threadId:this.threadId,handler:J,connectionState:this.lastConnectionState,error:Q})}}subscribeToTransport(){this.subscriptions.push(this.transport.connectionChanges().subscribe({next:(J)=>{this.runTransportHandler("connectionChanges",()=>{let Z=this.lastConnectionState,Q=this.lastConnectionInfo,Y=J.state!==this.lastConnectionState,X=Q!==null&&(J.role!==Q.role||J.clientId!==Q.clientId);if(!Y&&!X)return;if(Y)this.logConnectionStateTransition(this.lastConnectionState,J);else if(X&&Q)this.logConnectionRoleTransition(Q,J);let K=J.state,V=K==="connected"&&this.lastConnectionState!=="connected";if(V)this.threadResumeCursor.reset();this.lastConnectionState=K,this.lastConnectionInfo={...J};let G=J.state==="connected"&&J.role==="executor";this.executorReadySubject.next(G);let F=G&&Q?.role!=="executor";if(V&&this.connectionMode==="observer"||F&&this.connectionMode==="executor+observer")this.transport.resumeFromVersion(this.threadResumeCursor.getVersion());if(K==="connected"&&Z!=="connected")this.connectedTransportGeneration+=1,this.pendingClientWriteReplayGeneration=this.connectedTransportGeneration,this.replayPendingClientWritesIfNeeded(this.threadSubject.getValue())})}}),this.transport.errors().subscribe({next:(J)=>{this.runTransportHandler("errors",()=>{let Z=J.code==="PARSE_ERROR"?Qa0(J.message):null;if(_.warn("[dtw] Transport error",{threadId:this.threadId,connectionState:this.lastConnectionState,code:J.code,message:Z!==null?"Received invalid DTW payload (see parse details)":J.message,parseErrorSource:Z?.source,parseErrorDirection:Z?.direction,parseErrorStage:Z?.stage,parseErrorSummary:Z?.summary,parseErrorMessageType:Z?.messageType,parseErrorIssues:Z?.issues,parseErrorPayloadPreview:Z?.payloadPreview}),J.code==="PARSE_ERROR"){let Q=Z?.messageType?` (type="${Z.messageType}")`:"";_.warn("[dtw] Invalid DTW parse payload received",{threadId:this.threadId,messageType:Z?.messageType,messageTypeSuffix:Q})}})}}),this.transport.agentStates().subscribe({next:(J)=>{this.runTransportHandler("agentStates",()=>{this.agentLoopState=J.state,this.agentLoopStateSubject.next(J.state)})}}),this.transport.deltas().subscribe({next:(J)=>{this.runTransportHandler("deltas",()=>{if(LX3(J,this.deltaState),J.role==="user"&&J.state==="complete"&&J.blocks)this.clearToolProgressFromBlocks(J.blocks);if(this.deltaState.completedMessages.length>0){for(let Z of this.deltaState.completedMessages)if(Z.role==="user")this.clearToolProgressFromBlocks(Z.blocks);this.messages=OX3(this.messages,this.deltaState.completedMessages,this.processedIds),this.deltaState.completedMessages=[]}this.emitThread()})}}),this.transport.toolProgress().subscribe({next:(J)=>{this.runTransportHandler("toolProgress",()=>{let Z=J.toolCallId,Q=wC4(J.progress),Y=LC4(J.progress),X=this.toolProgressByToolUseID.get(Z),K=J.progress!==void 0?OC4(J.progress):X?.subagentProgressTurns,V=J.progress!==void 0;if(Q===void 0&&Y===void 0&&!V){if(this.toolProgressByToolUseID.delete(Z))this.emitToolProgress();return}let G={status:Y??X?.status??"in-progress",content:Q??X?.content??"",...K!==void 0?{subagentProgressTurns:K}:{}};if(X?.status===G.status&&X?.content===G.content&&X?.subagentProgressTurns===G.subagentProgressTurns)return;this.toolProgressByToolUseID.set(Z,G),this.emitToolProgress()})}}),this.transport.compactionEvents().subscribe({next:(J)=>{this.runTransportHandler("compactionEvents",()=>{if(J.type==="compaction_started"){this.setCompactionState("compacting");return}this.setCompactionState("idle")})}}),this.transport.messageEvents().subscribe({next:(J)=>{this.runTransportHandler("messageEvents",()=>{let Z=EC4(J);if(this.messages=MX3(J,this.messages,this.processedIds),J.message.role==="user")this.clearToolProgressFromBlocks(J.message.content);if(this.deltaState.streamingMessageId===J.message.messageId)this.deltaState.streamingMessageId=null,this.deltaState.streamingBlocks=[],this.deltaState.streamingParentToolCallId=void 0;this.advanceThreadVersionFromSeq(J.seq),this.emitThread({agentMode:Z})})}}),this.transport.messageEdited().subscribe({next:(J)=>{this.runTransportHandler("messageEdited",()=>{let Z=EC4(J);this.messages=AX3(J,this.messages),this.processedIds=NX3(this.messages),this.advanceThreadVersionFromSeq(J.seq),this.emitThread({agentMode:Z})})}}),this.transport.threadTitles().subscribe({next:(J)=>{this.runTransportHandler("threadTitles",()=>{this.threadTitle=J.title??void 0,this.emitThread()})}}),this.transport.threadRelationships().subscribe({next:(J)=>{this.runTransportHandler("threadRelationships",()=>{if(J.relationships.length>0||this.relationships.length===0)this.relationships=J.relationships;this.advanceThreadVersionFromSeq(J.seq),this.emitThread()})}}),this.transport.queuedMessages().subscribe({next:(J)=>{this.runTransportHandler("queuedMessages",()=>{this.queuedMessages=RX3(this.queuedMessages,J),this.emitThread()})}}))}logConnectionStateTransition(J,Z){let Q={threadId:this.threadId,from:J,to:Z.state,threadVersion:this.threadResumeCursor.getVersion(),...AC4(Z.reconnectCause)};if(Z.role)Q.role=Z.role;if(Z.clientId)Q.clientId=Z.clientId;if(Z.threadId&&Z.threadId!==this.threadId)Q.transportThreadId=Z.threadId;if(Z.state==="connected"){if(J==="reconnecting"){_.info("[dtw] Transport reconnected",Q);return}_.info("[dtw] Transport connected",Q);return}if(Z.state==="reconnecting"){_.warn("[dtw] Transport reconnecting",Q);return}if(Z.state==="disconnected"){_.warn("[dtw] Transport disconnected",Q);return}_.info("[dtw] Transport state changed",Q)}logConnectionRoleTransition(J,Z){let Q={threadId:this.threadId,state:Z.state,fromRole:J.role,toRole:Z.role,threadVersion:this.threadResumeCursor.getVersion()};if(J.clientId||Z.clientId)Q.fromClientId=J.clientId,Q.toClientId=Z.clientId;if(Z.threadId&&Z.threadId!==this.threadId)Q.transportThreadId=Z.threadId;_.info("[dtw] Transport role changed",Q)}sendUserMessage(J,Z,Q,Y,X){this.setAgentMode(Z);let K=this.transport.sendUserMessage(J,Z,{userState:Q,messageId:Y,discoveredGuidanceFiles:X});return this.pendingClientWritesByMessageID.set(K,{content:J,agentMode:Z,userState:Q,discoveredGuidanceFiles:X}),K}interruptQueuedMessage(J){this.transport.interruptQueuedMessage(J)}discardQueuedMessages(){let J=si(this.queuedMessages);if(this.queuedMessages.length===0)return;let Z=this.queuedMessages.map((Q)=>n6.safeParse(Q.id)).filter((Q)=>Q.success).map((Q)=>Q.data);this.queuedMessages=[],this.emitThread();try{for(let Q of Z)this.transport.removeQueuedMessage(Q)}catch(Q){throw this.queuedMessages=J??[],this.emitThread(),Q}}resumeFromVersion(J){this.transport.resumeFromVersion(J)}disposeSubscriptionsAndState(){for(let J of this.subscriptions)J.unsubscribe();this.subscriptions.length=0,this.pendingClientWritesByMessageID.clear(),this.pendingClientWriteReplayGeneration=null,this.compactionStateSubject.complete(),this.agentLoopStateSubject.complete(),this.executorReadySubject.complete(),this.toolProgressByToolUseIDSubject.complete()}async disposeAndWaitForClose(){if(this.disposeSubscriptionsAndState(),(await this.transport.disconnectAndWait()).status==="timeout")_.info("[dtw] Timed out waiting for close acknowledgement before dispose",{threadId:this.threadId});this.transport.dispose()}dispose(){this.disposeSubscriptionsAndState(),this.transport.dispose()}}import{mkdir as PX3,readFile as CX3,rm as Go0,writeFile as _X3}from"node:fs/promises";import TX3 from"node:path";c4();var SX3=5000,kX3=100;function vX3(J){try{return process.kill(J,0),!0}catch(Z){return Z.code==="EPERM"}}function Fo0(J,Z){return J.code===Z}function yX3(J){return J instanceof Error?J.message:String(J)}function PC4(J){if(typeof J!=="string")return null;let Z=J.trim();return Z.length>0?Z:null}function xX3(J,Z){let Q=Reflect.get(J,Z);if(typeof Q!=="number")return;return Number.isSafeInteger(Q)&&Q>0?Q:void 0}function fX3(J,Z){return PC4(Reflect.get(J,Z))}function uX3(J){let Z;try{Z=JSON.parse(J)}catch{return}if(!Z||typeof Z!=="object")return;let Q=xX3(Z,"pid"),Y=Reflect.get(Z,"threadId"),X=fX3(Z,"threadTitle");if(Q===void 0||typeof Y!=="string"||!B9(Y))return;return{pid:Q,threadId:Y,threadTitle:X}}function bX3(J){let Z={pid:J.pid,threadId:J.threadId};if(J.threadTitle)Z.threadTitle=J.threadTitle;return`${JSON.stringify(Z)}
|
|
6240
6240
|
`}function hX3(J){return{pid:J.currentPID??process.pid,threadId:J.currentThreadId,threadTitle:PC4(J.currentThreadTitle)}}async function CC4(J){try{let Z=await CX3(J,"utf-8"),Q=uX3(Z);if(Q===void 0)return{kind:"invalid",value:Z.trim()};return{kind:"valid",contents:Q}}catch(Z){if(Fo0(Z,"ENOENT"))return{kind:"missing"};throw Z}}async function _C4(J,Z){let Q=await CC4(J);if(Q.kind!=="valid"||Q.contents.pid!==Z)return;await Go0(J,{force:!0})}async function gX3(J){try{process.kill(J,"SIGTERM")}catch(Z){if(Fo0(Z,"ESRCH"))return;throw Z}}async function mX3(J,Z){let Q=Date.now()+SX3;while(Date.now()<Q){if(!Z(J))return!0;await dX3(kX3)}return!Z(J)}function pX3(J){return["Another amp live-sync is already running for this checkout.","",...[J.running.threadTitle,J.running.threadId,`PID ${J.running.pid}`].filter((Q)=>Boolean(Q)),"","Kill the running live-sync process and continue? [y/N]: "].join(`
|
|
6241
6241
|
`)}function IC4(J,Z){return{status:"claimed",pidFilePath:J,release:async()=>_C4(J,Z)}}function dX3(J){return new Promise((Z)=>{setTimeout(Z,J)})}async function TC4(J){let Z=J.currentPID??process.pid,Q=hX3(J),Y=J.isProcessRunning??vX3,X=J.killProcess??gX3,K=J.waitForProcessExit??((V)=>mX3(V,Y));await PX3(TX3.dirname(J.pidFilePath),{recursive:!0});while(!0){let V=await CC4(J.pidFilePath);if(V.kind==="valid"){if(V.contents.pid===Z)return IC4(J.pidFilePath,Z);if(Y(V.contents.pid)){if(!J.promptForYesNo)return{status:"already-running",pidFilePath:J.pidFilePath,runningPID:V.contents.pid,runningThreadId:V.contents.threadId,runningThreadTitle:V.contents.threadTitle};let G=J.formatRunningPrompt?.({runningPID:V.contents.pid,runningThreadId:V.contents.threadId,runningThreadTitle:V.contents.threadTitle})??pX3({running:V.contents});if(!await J.promptForYesNo(G))return{status:"already-running",pidFilePath:J.pidFilePath,runningPID:V.contents.pid,runningThreadId:V.contents.threadId,runningThreadTitle:V.contents.threadTitle};try{await X(V.contents.pid)}catch(z){throw new C1(`Couldn't stop live-sync PID ${V.contents.pid}: ${yX3(z)}`,1)}if(!await K(V.contents.pid))throw new C1(`Timed out waiting for live-sync PID ${V.contents.pid} to stop.`,1);await _C4(J.pidFilePath,V.contents.pid);continue}await Go0(J.pidFilePath,{force:!0});continue}if(V.kind==="invalid"){await Go0(J.pidFilePath,{force:!0});continue}try{return await _X3(J.pidFilePath,bX3(Q),{encoding:"utf-8",flag:"wx",mode:384}),IC4(J.pidFilePath,Z)}catch(G){if(Fo0(G,"EEXIST"))continue;throw G}}}var zo0=null,qo0=null;function SC4(J,Z){zo0=J,qo0=Z}function kC4(){return typeof process<"u"&&(process.env.BUN_TEST==="1"||globalThis.Bun?.jest!==void 0||typeof globalThis.test==="function")}function vC4(){if(!zo0){if(kC4())return{scheduleBuildFor:()=>{}};throw Error("Build scheduler not initialized. Make sure WidgetsBinding is created.")}return zo0}function VX0(){if(!qo0){if(kC4())return{requestLayout:()=>{},requestPaint:()=>{},removeFromQueues:()=>{}};throw Error("Paint scheduler not initialized. Make sure WidgetsBinding is created.")}return qo0}class hj{_parent;_children=[];_needsLayout=!1;_needsPaint=!1;_cachedDepth;_attached=!1;_debugData={};allowHitTestOutsideBounds=!1;parentData;setupParentData(J){}sendDebugData(J){this._debugData={...this._debugData,...J}}get debugData(){return this._debugData}get parent(){return this._parent}get children(){return this._children}get depth(){if(this._cachedDepth!==void 0)return this._cachedDepth;let J=0,Z=this._parent;while(Z)J++,Z=Z._parent;return this._cachedDepth=J,J}_invalidateDepth(){this._cachedDepth=void 0;for(let J of this._children)J._invalidateDepth()}get needsLayout(){return this._needsLayout}get needsPaint(){return this._needsPaint}get attached(){return this._attached}adoptChild(J){if(J._parent=this,J._invalidateDepth(),this._children.push(J),this.setupParentData(J),this._attached)J.attach();this.markNeedsLayout()}dropChild(J){let Z=this._children.indexOf(J);if(Z!==-1){if(J._attached)J.detach();this._children.splice(Z,1),J._parent=void 0,J._invalidateDepth(),this.markNeedsLayout()}}removeAllChildren(){for(let J of this._children){if(J._attached)J.detach();J._parent=void 0,J._invalidateDepth()}this._children.length=0,this.markNeedsLayout()}replaceChildren(J){for(let Z of J)Z._parent=this,Z._invalidateDepth(),this.setupParentData(Z);this._children=J,this.markNeedsLayout()}attach(){if(this._attached)return;this._attached=!0;for(let J of this._children)J.attach()}detach(){if(!this._attached)return;this._attached=!1;for(let J of this._children)J.detach()}markNeedsLayout(){if(this._needsLayout)return;if(!this._attached)return;if(this._needsLayout=!0,this.parent)this.parent.markNeedsLayout();else VX0().requestLayout(this)}markNeedsPaint(){if(this._needsPaint)return;if(!this._attached)return;this._needsPaint=!0,VX0().requestPaint(this)}performLayout(){}paint(J,Z=0,Q=0){this._needsPaint=!1;for(let Y of this.children)if("offset"in Y){let X=Y,K=Z+X.offset.x,V=Q+X.offset.y;Y.paint(J,K,V)}else Y.paint(J,Z,Q)}visitChildren(J){for(let Z of this._children)J(Z)}dispose(){VX0().removeFromQueues(this),this._cachedDepth=void 0,this._parent=void 0,this._children.length=0}}class x4 extends hj{_size={width:0,height:0};get size(){return{...this._size}}setSize(J,Z){r4(Number.isFinite(J)&&Number.isFinite(Z),`RenderBox.setSize received non-finite dimension: ${J}x${Z}`),this._size.width=J,this._size.height=Z}_offset={x:0,y:0};get offset(){return{...this._offset}}setOffset(J,Z){let Q=Number.isFinite(J)?Math.round(J):0,Y=Number.isFinite(Z)?Math.round(Z):0;this._offset.x=Q,this._offset.y=Y}localToGlobal(J){let{x:Z,y:Q}=J,Y=this;while(Y)if(Z+=Y._offset.x,Q+=Y._offset.y,Y=Y.parent,Y&&!("_offset"in Y))break;return{x:Z,y:Q}}globalToLocal(J){let Z=this.localToGlobal({x:0,y:0});return{x:J.x-Z.x,y:J.y-Z.y}}_lastConstraints;layout(J){let Z=!this._lastConstraints||!J.equals(this._lastConstraints);if(!this._needsLayout&&!Z)return;this._lastConstraints=J,this._needsLayout=!1,this.performLayout()}getMinIntrinsicWidth(J){let Z=this.children;if(Z.length===0)return 0;let Q=0;for(let Y of Z)Q=Math.max(Q,Y.getMinIntrinsicWidth(J));return Q}getMaxIntrinsicWidth(J){let Z=this.children;if(Z.length===0)return 0;let Q=0;for(let Y of Z)Q=Math.max(Q,Y.getMaxIntrinsicWidth(J));return Q}getMinIntrinsicHeight(J){let Z=this.children;if(Z.length===0)return 0;let Q=0;for(let Y of Z)Q=Math.max(Q,Y.getMinIntrinsicHeight(J));return Q}getMaxIntrinsicHeight(J){let Z=this.children;if(Z.length===0)return 0;let Q=0;for(let Y of Z)Q=Math.max(Q,Y.getMaxIntrinsicHeight(J));return Q}paint(J,Z=0,Q=0){let Y=J.getSize(),X=Y.width,K=Y.height;for(let V of this.children)if(V instanceof x4){let G=Z+this.offset.x+V.offset.x,F=Q+this.offset.y+V.offset.y,z=G+V.size.width,q=F+V.size.height;if(!(G>=X||F>=K||z<=0||q<=0))V.paint(J,Z+this.offset.x,Q+this.offset.y)}}hitTest(J,Z,Q=0,Y=0){let X=Q+this.offset.x,K=Y+this.offset.y,V=Z.x>=X&&Z.x<X+this.size.width,G=Z.y>=K&&Z.y<K+this.size.height;if(V&&G){J.addWithPaintOffset(this,{x:X,y:K},Z);let F=!0;for(let z=this.children.length-1;z>=0;z--)if(this.children[z].hitTest(J,Z,X,K))F=!0;return F}if(this.allowHitTestOutsideBounds){let F=!1;for(let z=this.children.length-1;z>=0;z--)if(this.children[z].hitTest(J,Z,X,K))F=!0;return F}return!1}}function $n(J,Z=0){return Number.isFinite(J)?J:Z}class j1{minWidth;maxWidth;minHeight;maxHeight;constructor(J,Z,Q,Y){if(typeof J==="object")this.minWidth=J.minWidth??0,this.maxWidth=J.maxWidth??1/0,this.minHeight=J.minHeight??0,this.maxHeight=J.maxHeight??1/0;else this.minWidth=J??0,this.maxWidth=Z??1/0,this.minHeight=Q??0,this.maxHeight=Y??1/0}static tight(J,Z){return new j1(J,J,Z,Z)}static loose(J,Z){return new j1(0,J,0,Z)}get hasBoundedWidth(){return this.maxWidth!==1/0}get hasBoundedHeight(){return this.maxHeight!==1/0}get hasTightWidth(){return this.minWidth>=this.maxWidth}get hasTightHeight(){return this.minHeight>=this.maxHeight}constrain(J,Z){return r4(isFinite(J),`BoxConstraints.constrain received infinite width: ${J}. This indicates a layout bug where a widget is not properly calculating its desired size.`),r4(isFinite(Z),`BoxConstraints.constrain received infinite height: ${Z}. This indicates a layout bug where a widget is not properly calculating its desired size.`),{width:Math.max(this.minWidth,Math.min(this.maxWidth,J)),height:Math.max(this.minHeight,Math.min(this.maxHeight,Z))}}enforce(J){let Z=(Q,Y,X)=>Math.max(Y,Math.min(X,Q));return new j1(Z(J.minWidth,this.minWidth,this.maxWidth),Z(J.maxWidth,this.minWidth,this.maxWidth),Z(J.minHeight,this.minHeight,this.maxHeight),Z(J.maxHeight,this.minHeight,this.maxHeight))}get biggest(){return{width:this.maxWidth,height:this.maxHeight}}get smallest(){return{width:this.minWidth,height:this.minHeight}}loosen(){return new j1(0,this.maxWidth,0,this.maxHeight)}tighten({width:J,height:Z}={}){return new j1(J===void 0?this.minWidth:Math.max(this.minWidth,Math.min(this.maxWidth,J)),J===void 0?this.maxWidth:Math.max(this.minWidth,Math.min(this.maxWidth,J)),Z===void 0?this.minHeight:Math.max(this.minHeight,Math.min(this.maxHeight,Z)),Z===void 0?this.maxHeight:Math.max(this.minHeight,Math.min(this.maxHeight,Z)))}static tightFor({width:J,height:Z}={}){return new j1(J??0,J??1/0,Z??0,Z??1/0)}equals(J){return this.minWidth===J.minWidth&&this.maxWidth===J.maxWidth&&this.minHeight===J.minHeight&&this.maxHeight===J.maxHeight}}class Jn{constructor(){}}class X3 extends Jn{value;constructor(J){super();this.value=J}equals(J){if(!(J instanceof X3))return!1;return this.value===J.value}get hashCode(){if(this.value===null||this.value===void 0)return 0;if(typeof this.value==="string")return this.stringHash(this.value);if(typeof this.value==="number")return this.value;if(typeof this.value==="boolean")return this.value?1:0;return this.stringHash(String(this.value))}stringHash(J){let Z=0;for(let Q=0;Q<J.length;Q++){let Y=J.charCodeAt(Q);Z=(Z<<5)-Z+Y,Z=Z&Z}return Z}toString(){return`ValueKey(${this.value})`}}class Ov extends Jn{static _counter=0;_id;constructor(){super();this._id=Ov._counter++}equals(J){if(!(J instanceof Ov))return!1;return this._id===J._id}get hashCode(){return this._id}toString(){return`UniqueKey(${this._id})`}}class MJ extends Jn{static _registry=new Map;static _counter=0;_id;_currentElement;constructor(J){super();if(J)this._id=`${J}_${MJ._counter++}`;else this._id=`GlobalKey_${MJ._counter++}`;MJ._registry.set(this._id,this)}equals(J){if(!(J instanceof MJ))return!1;return this._id===J._id}get hashCode(){return this.stringHash(this._id)}stringHash(J){let Z=0;for(let Q=0;Q<J.length;Q++){let Y=J.charCodeAt(Q);Z=(Z<<5)-Z+Y,Z=Z&Z}return Z}get currentElement(){return this._currentElement}get currentWidget(){return this._currentElement?.widget}_setElement(J){r4(this._currentElement===void 0,`GlobalKey ${this._id} is already associated with an element. Each GlobalKey can only be used once in the widget tree.`),this._currentElement=J}_clearElement(){this._currentElement=void 0,MJ._registry.delete(this._id)}toString(){return`GlobalKey(${this._id})`}static _clearRegistry(){MJ._registry.clear(),MJ._counter=0}}class AJ{key;_debugData={};constructor({key:J}={}){if(this.constructor===AJ)throw Error("Widget is abstract and cannot be instantiated directly");this.key=J}sendDebugData(J){this._debugData={...this._debugData,...J}}get debugData(){return this._debugData}canUpdate(J){if(this.constructor!==J.constructor)return!1;if(this.key===void 0&&J.key===void 0)return!0;if(this.key===void 0||J.key===void 0)return!1;return this.key.equals(J.key)}}class rY{widget;parent;_children=[];_inheritedDependencies=new Set;_dirty=!1;_cachedDepth;_mounted=!1;constructor(J){this.widget=J}get children(){return this._children}get depth(){if(this._cachedDepth!==void 0)return this._cachedDepth;let J=0,Z=this.parent;while(Z)J++,Z=Z.parent;return this._cachedDepth=J,J}_invalidateDepth(){this._cachedDepth=void 0;for(let J of this._children)J._invalidateDepth()}get dirty(){return this._dirty}get mounted(){return this._mounted}get renderObject(){return}update(J){this.widget=J}addChild(J){J.parent=this,J._invalidateDepth(),this._children.push(J)}removeChild(J){let Z=this._children.indexOf(J);if(Z!==-1)this._children.splice(Z,1),J.parent=void 0,J._invalidateDepth()}removeAllChildren(){for(let J of this._children)J.parent=void 0,J._invalidateDepth();this._children.length=0}markMounted(){if(this._mounted=!0,this.widget.key instanceof MJ)this.widget.key._setElement(this)}unmount(){if(this.widget.key instanceof MJ)this.widget.key._clearElement();this._mounted=!1,this._dirty=!1,this._cachedDepth=void 0;for(let J of this._inheritedDependencies)if("removeDependent"in J)J.removeDependent(this);this._inheritedDependencies.clear()}markNeedsRebuild(){if(!this._mounted)return;this._dirty=!0,vC4().scheduleBuildFor(this)}dependOnInheritedWidgetOfExactType(J){let Z=this.parent;while(Z){if(Z.widget.constructor===J){if("addDependent"in Z&&"removeDependent"in Z){let Q=Z;Q.addDependent(this),this._inheritedDependencies.add(Q)}return Z}Z=Z.parent}return null}findAncestorElementOfType(J){let Z=this.parent;while(Z){if(Z instanceof J)return Z;Z=Z.parent}return null}findAncestorWidgetOfType(J){let Z=this.parent;while(Z){if(Z.widget instanceof J)return Z.widget;Z=Z.parent}return null}}class Ev extends AJ{constructor({key:J}={}){super(J!==void 0?{key:J}:{})}createElement(){return new Zn(this)}updateRenderObject(J){}}class p3 extends Ev{child;constructor({key:J,child:Z}={}){super(J?{key:J}:{});this.child=Z}createElement(){return new Cq(this)}}class wZ extends Ev{children;constructor({key:J,children:Z=[]}={}){super(J?{key:J}:{});this.children=[...Z]}createElement(){return new GX0(this)}}class y$ extends Ev{constructor({key:J}={}){super(J?{key:J}:{})}createElement(){return new mK(this)}}class Zn extends rY{_renderObject;constructor(J){super(J)}get renderObjectWidget(){return this.widget}get renderObject(){return this._renderObject}mount(){this._renderObject=this.renderObjectWidget.createRenderObject(),this._renderObject.attach(),this.markMounted()}unmount(){if(this._renderObject)this._renderObject.detach(),this._renderObject.dispose(),this._renderObject=void 0;super.unmount()}update(J){super.update(J);let Z=this.renderObjectWidget;if(this._renderObject)Z.updateRenderObject(this._renderObject)}performRebuild(){}}class Cq extends Zn{_child;constructor(J){super(J)}get singleChildWidget(){return this.widget}get child(){return this._child}mount(){if(super.mount(),this.singleChildWidget.child){if(this._child=this.singleChildWidget.child.createElement(),this.addChild(this._child),this._child.mount(),this._child.renderObject&&this.renderObject)this.renderObject.adoptChild(this._child.renderObject)}}unmount(){if(this._child)this._child.unmount(),this.removeChild(this._child),this._child=void 0;super.unmount()}update(J){super.update(J);let Z=this.singleChildWidget;if(Z.child&&this._child){if(this._child.widget.canUpdate(Z.child))this._child.update(Z.child);else if(this._child.unmount(),this.removeChild(this._child),this._child=Z.child.createElement(),this.addChild(this._child),this._child.mount(),this.renderObject){if(this.renderObject.removeAllChildren(),this._child.renderObject)this.renderObject.adoptChild(this._child.renderObject)}}else if(Z.child&&!this._child){if(this._child=Z.child.createElement(),this.addChild(this._child),this._child.mount(),this.renderObject&&this._child.renderObject)this.renderObject.adoptChild(this._child.renderObject)}else if(!Z.child&&this._child){if(this._child.unmount(),this.removeChild(this._child),this._child=void 0,this.renderObject)this.renderObject.removeAllChildren()}}performRebuild(){}}class GX0 extends Zn{_childElements=[];constructor(J){super(J)}get multiChildWidget(){return this.widget}get children(){return this._childElements}mount(){super.mount();for(let J of this.multiChildWidget.children){let Z=J.createElement();if(this._childElements.push(Z),this.addChild(Z),Z.mount(),Z.renderObject&&this.renderObject)this.renderObject.adoptChild(Z.renderObject)}}unmount(){for(let J of this._childElements)J.unmount(),this.removeChild(J);this._childElements.length=0,super.unmount()}update(J){super.update(J);let Z=this.multiChildWidget;this.updateChildren(this._childElements,[...Z.children])}updateChildren(J,Z){let Q=[],Y=0,X=0,K=J.length-1,V=Z.length-1;while(Y<=K&&X<=V){let F=J[Y],z=Z[X];if(!F||!z||!F.widget.canUpdate(z))break;if(F.widget!==z)F.update(z);Q.push(F),Y++,X++}let G=[];while(Y<=K&&X<=V){let F=J[K],z=Z[V];if(!F||!z||!F.widget.canUpdate(z))break;if(F.widget!==z)F.update(z);G.unshift(F),K--,V--}if(Y>K)for(let F=X;F<=V;F++){let z=Z[F];if(z){let q=this.createChildElement(z);Q.push(q)}}else if(X>V)for(let F=Y;F<=K;F++){let z=J[F];if(z)this.deactivateChild(z)}else{let F=new Map,z=new Map;for(let q=Y;q<=K;q++){let W=J[q];if(W.widget.key){let H=W.widget.key.toString();F.set(H,W),z.set(H,q)}}for(let q=X;q<=V;q++){let W=Z[q];if(!W)continue;let H;if(W.key){let U=W.key.toString();if(H=F.get(U),H){F.delete(U);let D=z.get(U);if(D!==void 0)J[D]=null;if(H.widget===W);else if(H.widget.canUpdate(W))H.update(W);else this.deactivateChild(H),H=this.createChildElement(W)}else H=this.createChildElement(W)}else{let U=!1;for(let D=Y;D<=K;D++){let B=J[D];if(B&&!B.widget.key){if(B.widget===W){H=B,J[D]=null,U=!0;break}else if(B.widget.canUpdate(W)){H=B,J[D]=null,H.update(W),U=!0;break}}}if(!U)H=this.createChildElement(W)}if(H)Q.push(H)}for(let q=Y;q<=K;q++){let W=J[q];if(W)this.deactivateChild(W)}for(let q of F.values())this.deactivateChild(q)}if(Q.push(...G),this._childElements=Q,this.renderObject){let F=[];for(let W of Q)if(W.renderObject)F.push(W.renderObject);let z=this.renderObject.children;if(z.length!==F.length||z.some((W,H)=>W!==F[H]))this.renderObject.replaceChildren(F)}}createChildElement(J){let Z=J.createElement();return this.addChild(Z),Z.mount(),Z}deactivateChild(J){J.unmount(),this.removeChild(J)}performRebuild(){}}class mK extends Zn{constructor(J){super(J)}get leafWidget(){return this.widget}performRebuild(){}}class m0{widget;context;_mounted=!1;get mounted(){return this._mounted}initState(){}didUpdateWidget(J){}dispose(){}setState(J){if(!this._mounted)throw Error("setState() called after dispose()");if(J)J();this._markNeedsBuild()}_mount(J,Z){this.widget=J,this.context=Z,this._mounted=!0,this.initState()}_update(J){let Z=this.widget;this.widget=J,this.didUpdateWidget(Z)}_unmount(){this._mounted=!1,this.dispose()}_markNeedsBuild(){let J=this.context.element;if("markNeedsBuild"in J&&typeof J.markNeedsBuild==="function")J.markNeedsBuild()}}class mG{element;widget;mediaQuery;parent;constructor(J,Z,Q=void 0,Y=null){this.element=J;this.widget=Z;this.mediaQuery=Q;this.parent=Y}findAncestorElementOfType(J){let Z=this.element.parent;while(Z){if(Z instanceof J)return Z;Z=Z.parent}return null}findAncestorWidgetOfType(J){return this.element.findAncestorWidgetOfType(J)}dependOnInheritedWidgetOfExactType(J){return this.element.dependOnInheritedWidgetOfExactType(J)}findAncestorStateOfType(J){let Z=this.element.parent;while(Z){if("state"in Z&&Z.state instanceof J)return Z.state;Z=Z.parent}return null}findRenderObject(){if("renderObject"in this.element){let J=this.element.renderObject;return J instanceof hj?J:void 0}return}}class c0 extends AJ{createElement(){return new Wo0(this)}}class Wo0 extends rY{_state;_child;_context;constructor(J){super(J)}get statefulWidget(){return this.widget}get state(){return this._state}get child(){return this._child}mount(){this._context=new mG(this,this.widget),this._state=this.statefulWidget.createState(),this._state._mount(this.statefulWidget,this._context),this.rebuild(),this.markMounted()}unmount(){if(this._child)this._child.unmount(),this.removeChild(this._child),this._child=void 0;if(this._state)this._state._unmount(),this._state=void 0;this._context=void 0,super.unmount()}update(J){if(this.widget===J)return;if(super.update(J),this._state)this._state._update(this.statefulWidget);if(this._context)this._context.widget=J;this.rebuild()}performRebuild(){this.rebuild()}rebuild(){if(!this._context||!this._state)throw Error("Cannot rebuild unmounted element");let J=this._state.build(this._context);if(this._child)if(this._child.widget.canUpdate(J))this._child.update(J);else{let Z=this._child,Q=this.findNearestRenderObjectAncestor();if(Q&&Z.renderObject)Q.dropChild(Z.renderObject);else if(!Q&&Z.renderObject)Z.renderObject.detach();if(this._child.unmount(),this.removeChild(this._child),this._child=J.createElement(),this.addChild(this._child),this._child.mount(),Q&&this._child.renderObject)Q.adoptChild(this._child.renderObject),this._child.renderObject.markNeedsLayout();else if(!Q&&this._child.renderObject)this._child.renderObject.attach(),this._child.renderObject.markNeedsLayout();if(this._child.renderObject)this._child.renderObject.markNeedsLayout()}else this._child=J.createElement(),this.addChild(this._child),this._child.mount()}markNeedsBuild(){this.markNeedsRebuild()}findNearestRenderObjectAncestor(){let J=this.parent;while(J){if(J.renderObject){if(this._child?.renderObject&&J.renderObject===this._child.renderObject){J=J.parent;continue}return J.renderObject}J=J.parent}return}get renderObject(){return this._child?.renderObject}}var K3={DEFAULT:"default",POINTER:"pointer",TEXT:"text",WAIT:"wait",CROSSHAIR:"crosshair",HELP:"help",MOVE:"move",NOT_ALLOWED:"not-allowed",PROGRESS:"progress",CELL:"cell",CONTEXT_MENU:"context-menu",COPY:"copy",ALIAS:"alias",ZOOM_IN:"zoom-in",ZOOM_OUT:"zoom-out",GRAB:"grab",GRABBING:"grabbing",N_RESIZE:"n-resize",S_RESIZE:"s-resize",E_RESIZE:"e-resize",W_RESIZE:"w-resize",NE_RESIZE:"ne-resize",NW_RESIZE:"nw-resize",SE_RESIZE:"se-resize",SW_RESIZE:"sw-resize",NS_RESIZE:"ns-resize",EW_RESIZE:"ew-resize",COL_RESIZE:"col-resize",ROW_RESIZE:"row-resize"};class Ho0{static hitTest(J,Z){let Q=new yC4;return J.hitTest(Q,Z),Q}}class yC4{_hits=[];get hits(){return this._hits}add(J){this._hits.push(J)}addWithPaintOffset(J,Z,Q){let Y={x:Q.x-Z.x,y:Q.y-Z.y};this.add({target:J,localPosition:Y})}addMouseTarget(J,Z){}}function cX3(){let J=hj.prototype;if(!J.hitTest)J.hitTest=function(Z,Q,Y=0,X=0){if("size"in this&&"offset"in this){let V=this,G=V.size,F=V.offset;if(G&&F){let z=Y+F.x,q=X+F.y,W=Q.x>=z&&Q.x<z+G.width,H=Q.y>=q&&Q.y<q+G.height;if(W&&H){let U={x:Q.x-z,y:Q.y-q};Z.add({target:this,localPosition:U});let D=this.children,B=!0;for(let N=D.length-1;N>=0;N--)if(D[N].hitTest(Z,Q,z,q))B=!0;return B}if(this.allowHitTestOutsideBounds){let U=!1,D=this.children;for(let B=D.length-1;B>=0;B--)if(D[B].hitTest(Z,Q,z,q))U=!0;return U}return!1}}let K=!1;for(let V of this.children)if(V.hitTest(Z,Q,Y,X))K=!0;return K}}cX3();function _U(J,Z,Q){return{position:Z,localPosition:Q,modifiers:{shift:J.modifiers.shift,ctrl:J.modifiers.ctrl,alt:J.modifiers.alt,meta:J.modifiers.meta},timestamp:Date.now()}}function xC4(J,Z,Q,Y=1){return{type:"click",button:J.button==="left"?"left":J.button==="middle"?"middle":J.button==="right"?"right":"left",clickCount:Y,..._U(J,Z,Q)}}function FX0(J,Z,Q){let Y;switch(J.button){case"wheel_up":Y="up";break;case"wheel_down":Y="down";break;case"wheel_left":Y="left";break;case"wheel_right":Y="right";break;default:Y="down"}return{type:"scroll",direction:Y,..._U(J,Z,Q)}}class D8{static _instance=null;static SCROLL_SESSION_TIMEOUT=200;_rootRenderObject=null;_hoveredRegions=new Set;_vaxis=null;_currentCursor=K3.DEFAULT;_lastMousePosition=null;_dragTargets=[];_lastDragPosition=null;_globalReleaseCallbacks=new Set;_globalClickCallbacks=new Set;_scrollSessionTarget=null;_scrollSessionLastEvent=0;_lastClickTime=new Map;_lastClickPosition=new Map;_currentClickCount=new Map;static DOUBLE_CLICK_TIME=500;static DOUBLE_CLICK_DISTANCE=2;static DOUBLE_CLICK_DISTANCE_SQUARED=D8.DOUBLE_CLICK_DISTANCE*D8.DOUBLE_CLICK_DISTANCE;_scratchCurrentRegions=new Set;_scratchEnteredRegions=new Set;_scratchExitedRegions=new Set;constructor(){}static get instance(){if(!D8._instance)D8._instance=new D8;return D8._instance}setRootRenderObject(J){this._rootRenderObject=J}setTui(J){this._vaxis=J}handleMouseEvent(J){if(!this._rootRenderObject)return;let Z={x:J.x,y:J.y},Q=Ho0.hitTest(this._rootRenderObject,Z),Y=this._findMouseTargets(Q.hits);switch(J.action){case"press":if(J.button==="left"||J.button==="middle"||J.button==="right"){if(this._handleClick(J,Z,Y),J.button==="left"){this._dragTargets=[];for(let{target:X,localPosition:K}of Y){let V={x:Z.x-K.x,y:Z.y-K.y};if(this._dragTargets.push({target:X,localPosition:K,globalOffset:V}),X instanceof SQ&&X.opaque)break}}}break;case"release":this._handleRelease(J,Z,Y),this._dragTargets=[],this._lastDragPosition=null;break;case"scroll":if(J.button==="wheel_up"||J.button==="wheel_down"||J.button==="wheel_left"||J.button==="wheel_right")this._handleScroll(J,Z,Y);break;case"move":if(this._handleMove(J,Z,Y),J.drag)this._handleDrag(J,Z,Y);break}this._lastMousePosition=Z}addGlobalReleaseCallback(J){this._globalReleaseCallbacks.add(J)}removeGlobalReleaseCallback(J){this._globalReleaseCallbacks.delete(J)}addGlobalClickCallback(J){this._globalClickCallbacks.add(J)}removeGlobalClickCallback(J){this._globalClickCallbacks.delete(J)}requestCursorChange(J){if(this._vaxis&&J!==this._currentCursor)this._currentCursor=J,this._vaxis.setMouseCursor(J)}_handleRelease(J,Z,Q){for(let X of this._globalReleaseCallbacks)X();let Y=J.button==="left"||J.button==="middle"||J.button==="right"?J.button:"left";if(this._dragTargets.length>0)for(let{target:X,globalOffset:K}of this._dragTargets){let V={x:Z.x-K.x,y:Z.y-K.y},G={type:"release",button:Y,..._U(J,Z,V)};X.handleMouseEvent(G)}else for(let{target:X,localPosition:K}of Q){let V={type:"release",button:Y,..._U(J,Z,K)};if(X.handleMouseEvent(V),X instanceof SQ&&X.opaque)break}}_handleDrag(J,Z,Q){let Y=J.button==="left"||J.button==="middle"||J.button==="right"?J.button:"left",X=this._lastDragPosition?Z.x-this._lastDragPosition.x:0,K=this._lastDragPosition?Z.y-this._lastDragPosition.y:0;for(let{target:V,globalOffset:G}of this._dragTargets){let F={x:Z.x-G.x,y:Z.y-G.y},z={type:"drag",button:Y,deltaX:X,deltaY:K,..._U(J,Z,F)};V.handleMouseEvent(z)}this._lastDragPosition=Z}_handleClick(J,Z,Q){let Y=this._calculateClickCount(Z,J.button);for(let X of this._globalClickCallbacks)X({event:J,globalPosition:Z,mouseTargets:Q,clickCount:Y});for(let{target:X,localPosition:K}of Q){let V=xC4(J,Z,K,Y);if(X.handleMouseEvent(V),X instanceof SQ&&X.opaque)break}}_handleScroll(J,Z,Q){let Y=Date.now();if(this._scrollSessionTarget&&this._scrollSessionTarget.attached&&Y-this._scrollSessionLastEvent<=D8.SCROLL_SESSION_TIMEOUT&&this._scrollSessionTarget){let V=Q.find((G)=>G.target===this._scrollSessionTarget);if(V){let G=FX0(J,Z,V.localPosition);this._scrollSessionTarget.onScroll?.(G)}else{let G=this._scrollSessionTarget.globalToLocal(Z),F=FX0(J,Z,{x:G.x,y:G.y});this._scrollSessionTarget.onScroll?.(F)}this._scrollSessionLastEvent=Y;return}let K=this._findScrollTargets(Q);if(K.length===0){this._scrollSessionTarget=null,this._scrollSessionLastEvent=0;return}for(let V=K.length-1;V>=0;V--){let G=K[V];if(!G)continue;let F=FX0(J,Z,G.localPosition);if(G.target.onScroll?.(F)??!1){this._scrollSessionTarget=G.target,this._scrollSessionLastEvent=Y;return}}this._scrollSessionTarget=null,this._scrollSessionLastEvent=0}_handleMove(J,Z,Q){let Y=Q.filter((G)=>G.target instanceof SQ),X=this._scratchCurrentRegions,K=this._scratchExitedRegions,V=this._scratchEnteredRegions;X.clear();for(let{target:G}of Y)X.add(G);K.clear();for(let G of this._hoveredRegions)if(!X.has(G))K.add(G);V.clear();for(let G of X)if(!this._hoveredRegions.has(G))V.add(G);for(let G of K)if(G.onExit){let F={type:"exit",..._U(J,Z,Z)};G.handleMouseEvent(F)}for(let{target:G,localPosition:F}of Y)if(V.has(G)&&G.onEnter){let z={type:"enter",..._U(J,Z,F)};G.handleMouseEvent(z)}for(let{target:G,localPosition:F}of Y)if(G.onHover&&this._hoveredRegions.has(G)){let z={type:"hover",..._U(J,Z,F)};G.handleMouseEvent(z)}this._hoveredRegions.clear();for(let G of X)this._hoveredRegions.add(G);this._updateCursor(Y)}_updateCursor(J){if(!this._vaxis)return;let Z=K3.DEFAULT,Q=-1;for(let{target:Y}of J){let X=Y.depth;if(X<=Q)break;if(Y.cursor!==null)Z=Y.cursor;Q=X}if(Z!==this._currentCursor)this._currentCursor=Z,this._vaxis.setMouseCursor(Z)}_findMouseTargets(J){let Z=[];for(let Q of J)if(this._canHandleMouseEvents(Q.target))Z.push({target:Q.target,localPosition:Q.localPosition});return Z}_findScrollTargets(J){let Z=[],Q=-1;for(let Y of J){let K=Y.target.depth;if(K<=Q)break;if(Y.target instanceof SQ&&Y.target.onScroll)Z.push({target:Y.target,localPosition:Y.localPosition});Q=K}return Z}_canHandleMouseEvents(J){if(J instanceof SQ)return!0;return typeof J.handleMouseEvent==="function"}clearHoverState(){if(this._hoveredRegions.clear(),this._dragTargets=[],this._vaxis&&this._currentCursor!==K3.DEFAULT)this._currentCursor=K3.DEFAULT,this._vaxis.setMouseCursor(K3.DEFAULT)}removeRegion(J){this._hoveredRegions.delete(J)}reestablishHoverState(){if(!this._lastMousePosition||!this._rootRenderObject)return;let J={type:"mouse",action:"move",x:this._lastMousePosition.x,y:this._lastMousePosition.y,button:"unknown",drag:!1,modifiers:{shift:!1,ctrl:!1,alt:!1,meta:!1}};this.handleMouseEvent(J)}_calculateClickCount(J,Z="left"){let Q=Date.now(),Y=this._lastClickTime.get(Z)??0,X=Q-Y,K=1,V=this._lastClickPosition.get(Z);if(V&&X<=D8.DOUBLE_CLICK_TIME&&this._isWithinDoubleClickDistance(J,V))K=(this._currentClickCount.get(Z)??0)+1;else K=1;return this._lastClickTime.set(Z,Q),this._lastClickPosition.set(Z,J),this._currentClickCount.set(Z,K),K}_isWithinDoubleClickDistance(J,Z){let Q=J.x-Z.x,Y=J.y-Z.y;return Q*Q+Y*Y<=D8.DOUBLE_CLICK_DISTANCE_SQUARED}dispose(){this.clearHoverState(),this._lastMousePosition=null,this._rootRenderObject=null,this._lastClickTime.clear(),this._lastClickPosition.clear(),this._currentClickCount.clear(),this._globalReleaseCallbacks.clear(),this._globalClickCallbacks.clear(),D8._instance=null}}class Y4 extends p3{child;onClick;onEnter;onExit;onHover;onScroll;onRelease;onDrag;cursor;opaque;constructor({key:J,child:Z,onClick:Q,onEnter:Y,onExit:X,onHover:K,onScroll:V,onRelease:G,onDrag:F,cursor:z,opaque:q=!0}){super({key:J});this.child=Z,this.onClick=Q??null,this.onEnter=Y??null,this.onExit=X??null,this.onHover=K??null,this.onScroll=V??null,this.onRelease=G??null,this.onDrag=F??null,this.cursor=z??null,this.opaque=q}createElement(){return new fC4(this)}createRenderObject(){return new SQ({onClick:this.onClick,onEnter:this.onEnter,onExit:this.onExit,onHover:this.onHover,onScroll:this.onScroll,onRelease:this.onRelease,onDrag:this.onDrag,cursor:this.cursor,opaque:this.opaque})}updateRenderObject(J){J.onClick=this.onClick,J.onEnter=this.onEnter,J.onExit=this.onExit,J.onHover=this.onHover,J.onScroll=this.onScroll,J.onRelease=this.onRelease,J.onDrag=this.onDrag,J.cursor=this.cursor,J.opaque=this.opaque}}class fC4 extends Cq{get mouseRegionWidget(){return this.widget}get renderObject(){return super.renderObject}}class SQ extends x4{onClick;onEnter;onExit;onHover;onScroll;onRelease;onDrag;cursor;opaque;_isHovered=!1;constructor({onClick:J,onEnter:Z,onExit:Q,onHover:Y,onScroll:X,onRelease:K,onDrag:V,cursor:G,opaque:F}){super();this.onClick=J,this.onEnter=Z,this.onExit=Q,this.onHover=Y,this.onScroll=X,this.onRelease=K,this.onDrag=V,this.cursor=G,this.opaque=F}get hasMouseListeners(){return!!(this.onClick||this.onEnter||this.onExit||this.onHover||this.onScroll||this.onRelease||this.onDrag)}get isHovered(){return this._isHovered}handleMouseEvent(J){switch(J.type){case"click":this.onClick?.(J);break;case"enter":this._isHovered=!0,this.onEnter?.(J);break;case"exit":this._isHovered=!1,this.onExit?.(J);break;case"hover":this.onHover?.(J);break;case"scroll":this.onScroll?.(J);break;case"drag":this.onDrag?.(J);break;case"release":this.onRelease?.(J);break}}performLayout(){let J=this._lastConstraints;if(r4(!!J,"performLayout called without constraints"),this.children.length>0){let Z=this.children[0];Z.layout(J);let Q=Z.size;this.setSize(Q.width,Q.height),Z.setOffset(0,0)}else this.setSize(0,0);super.performLayout()}getMinIntrinsicHeight(J){if(this.children.length>0)return this.children[0].getMinIntrinsicHeight(J);return 0}getMaxIntrinsicHeight(J){if(this.children.length>0)return this.children[0].getMaxIntrinsicHeight(J);return 0}getMinIntrinsicWidth(J){if(this.children.length>0)return this.children[0].getMinIntrinsicWidth(J);return 0}getMaxIntrinsicWidth(J){if(this.children.length>0)return this.children[0].getMaxIntrinsicWidth(J);return 0}paint(J,Z=0,Q=0){if(this.children.length>0)this.children[0].paint(J,Z+this.offset.x,Q+this.offset.y)}hitTest(J,Z,Q=0,Y=0){let X=super.hitTest(J,Z,Q,Y);if(X&&this.hasMouseListeners)J.addMouseTarget(this,Z);return X}getDebugProperties(){return{hasMouseListeners:this.hasMouseListeners,isHovered:this.isHovered,cursor:this.cursor,opaque:this.opaque}}dispose(){D8.instance.removeRegion(this),this.onClick=null,this.onEnter=null,this.onExit=null,this.onHover=null,this.onScroll=null,this.onRelease=null,this.onDrag=null,this.cursor=null,super.dispose()}}class I3 extends AJ{child;constructor({key:J,child:Z}){super(J!==void 0?{key:J}:{});this.child=Z}createElement(){return new uC4(this)}}class uC4 extends rY{_child;_dependents=new Set;constructor(J){super(J)}get inheritedWidget(){return this.widget}get child(){return this._child}get renderObject(){return this._child?.renderObject}mount(){this._child=this.inheritedWidget.child.createElement(),this.addChild(this._child),this._child.mount(),this.markMounted()}unmount(){if(this._child)this._child.unmount(),this.removeChild(this._child),this._child=void 0;this._dependents.clear(),super.unmount()}update(J){let Z=this.inheritedWidget;super.update(J);let Q=this.inheritedWidget;if(Q.updateShouldNotify(Z))this.notifyDependents();if(this._child&&this._child.widget.canUpdate(Q.child))this._child.update(Q.child);else{if(this._child)this._child.unmount(),this.removeChild(this._child);this._child=Q.child.createElement(),this.addChild(this._child),this._child.mount()}}addDependent(J){this._dependents.add(J)}removeDependent(J){this._dependents.delete(J)}notifyDependents(){for(let J of this._dependents)J.markNeedsRebuild()}performRebuild(){}}class xw{foreground;mutedForeground;background;cursor;primary;secondary;accent;border;success;warning;info;destructive;selection;copyHighlight;tableBorder;constructor({foreground:J,mutedForeground:Z,background:Q,cursor:Y,primary:X,secondary:K,accent:V,border:G,success:F,warning:z,info:q,destructive:W,selection:H,copyHighlight:U,tableBorder:D}){this.foreground=J,this.mutedForeground=Z,this.background=Q,this.cursor=Y,this.primary=X,this.secondary=K,this.accent=V,this.border=G,this.success=F,this.warning=z,this.info=q,this.destructive=W,this.selection=H,this.copyHighlight=U,this.tableBorder=D}static default(){return new xw({foreground:M0.default(),mutedForeground:M0.default(),background:M0.none(),cursor:M0.default(),primary:M0.blue,secondary:M0.cyan,accent:M0.magenta,border:M0.default(),success:M0.green,warning:M0.yellow,info:M0.index(12),destructive:M0.red,selection:M0.index(8),copyHighlight:M0.yellow,tableBorder:M0.default()})}static fromRgb(J){return new xw({foreground:M0.rgb(J.fg.r,J.fg.g,J.fg.b),mutedForeground:M0.rgb(J.indices[7].r,J.indices[7].g,J.indices[7].b),background:M0.none(),cursor:M0.rgb(J.cursor.r,J.cursor.g,J.cursor.b),primary:M0.rgb(J.indices[4].r,J.indices[4].g,J.indices[4].b),secondary:M0.rgb(J.indices[6].r,J.indices[6].g,J.indices[6].b),accent:M0.rgb(J.indices[5].r,J.indices[5].g,J.indices[5].b),border:M0.rgb(J.fg.r,J.fg.g,J.fg.b),success:M0.rgb(J.indices[2].r,J.indices[2].g,J.indices[2].b),warning:M0.rgb(J.indices[3].r,J.indices[3].g,J.indices[3].b),info:M0.rgb(J.indices[6].r,J.indices[6].g,J.indices[6].b),destructive:M0.rgb(J.indices[1].r,J.indices[1].g,J.indices[1].b),selection:M0.index(8),copyHighlight:M0.rgb(J.indices[3].r,J.indices[3].g,J.indices[3].b),tableBorder:M0.rgb(J.fg.r,J.fg.g,J.fg.b)})}}class c9{colorScheme;constructor({colorScheme:J}){this.colorScheme=J}static default(){return new c9({colorScheme:xw.default()})}static withRgb(J){return new c9({colorScheme:xw.fromRgb(J)})}}class b1 extends I3{data;constructor({key:J,data:Z,child:Q}){super({key:J,child:Q});this.data=Z}static of(J){let Z=J.dependOnInheritedWidgetOfExactType(b1);if(Z)return Z.widget.data;return c9.default()}static maybeOf(J){let Z=J.dependOnInheritedWidgetOfExactType(b1);if(Z)return Z.widget.data;return null}updateShouldNotify(J){return this.data!==J.data}}function Uo0(J,Z,Q){return J+(Z-J)*Q}function zX0(J,Z,Q){let Y=Math.max(0,Math.min(1,Q));return{r:Math.round(Uo0(J.r,Z.r,Y)),g:Math.round(Uo0(J.g,Z.g,Y)),b:Math.round(Uo0(J.b,Z.b,Y))}}T7();var tC4=W4(rC4(),1),sC4=20;function Eo0(J){let Z=$2(J??"smart")??$2("smart");if(Z?.uiHints?.primaryColor&&Z.uiHints.secondaryColor)return{primary:Z.uiHints.primaryColor,secondary:Z.uiHints.secondaryColor};return{primary:uf1,secondary:bf1}}function Mo0(J,Z,Q){let Y=Math.max(0,Math.min(1,J)),{primary:X,secondary:K}=Q??Eo0(Z),V=zX0(X,K,Y);return{type:"rgb",value:{r:V.r,g:V.g,b:V.b}}}class Tq{_noise2D;_seed;constructor(J){this._seed=J??Date.now(),this._noise2D=tC4.makeNoise2D(this._seed)}get seed(){return this._seed}sample(J,Z,Q,Y=1){return(this._noise2D(J/sC4,Z/sC4+Q*Y)+1)*0.5}sampleEdge(J,Z,Q,Y,X=1){let K=J-1,V=Z/2+Q*(Z/2);return this.sample(K,V,Y,X)}getColor(J,Z,Q){return Mo0(J,Z,Q)}}var Ao0=" .:-=+*#%@",FK3=" ",gj=64,eC4=0.5,fw=1,jo0=30,mj=3;class Ro0 extends c0{width;height;minWidth;minHeight;maxWidth;maxHeight;agentMode;colorMode;primaryColor;secondaryColor;backgroundColor;t;onFrame;fps;seed;glow;shockwaves;onShockwave;onClick;constructor({key:J,width:Z=40,height:Q=40,minWidth:Y,minHeight:X,maxWidth:K,maxHeight:V,agentMode:G,colorMode:F="intensity",primaryColor:z,secondaryColor:q,backgroundColor:W,t:H,onFrame:U,fps:D=30,seed:B,glow:N,shockwaves:w,onShockwave:L,onClick:O}){super(J?{key:J}:{});this.width=Z,this.height=Q,this.minWidth=Y??8,this.minHeight=X??8,this.maxWidth=K??40,this.maxHeight=V??40,this.agentMode=G,this.colorMode=F,this.primaryColor=z,this.secondaryColor=q,this.backgroundColor=W,this.t=H,this.onFrame=U,this.fps=D,this.seed=B,this.glow=N,this.shockwaves=w,this.onShockwave=L,this.onClick=O}createState(){return new $_4}}class $_4 extends m0{_t=0;_timer=null;_internalShockwaves=[];_glow;initState(){if(super.initState(),this._glow=this.widget.glow??new Tq(this.widget.seed),this.widget.t!==void 0||this.widget.fps===0){this._t=this.widget.t??0;return}this._timer=setInterval(()=>{if(this._t+=1/this.widget.fps,this.widget.onFrame){let J=this._t;setImmediate(()=>this.widget.onFrame?.(J))}this._internalShockwaves=this._internalShockwaves.filter((J)=>this._t-J.startTime<fw),this.setState(()=>{})},1000/this.widget.fps)}didUpdateWidget(J){if(super.didUpdateWidget(J),this.widget.glow!==J.glow)this._glow=this.widget.glow??new Tq(this.widget.seed);if(this.widget.t!==void 0&&this.widget.t!==J.t)this._t=this.widget.t,this.setState(()=>{})}dispose(){if(this._timer)clearInterval(this._timer),this._timer=null;super.dispose()}handleClick=(J)=>{this.widget.onClick?.({x:J.position.x,y:J.position.y,localX:J.localPosition.x,localY:J.localPosition.y,time:this._t});let Z={x:J.localPosition.x,y:J.localPosition.y,startTime:this._t};if(this.widget.onShockwave)this.widget.onShockwave(Z);else this._internalShockwaves.push(Z);this.setState(()=>{})};build(J){let Z=b1.of(J),Q=this.widget.backgroundColor??Z.colorScheme.background,Y=new J_4({width:this.widget.width,height:this.widget.height,minWidth:this.widget.minWidth,minHeight:this.widget.minHeight,maxWidth:this.widget.maxWidth,maxHeight:this.widget.maxHeight,time:this._t,agentMode:this.widget.agentMode,colorMode:this.widget.colorMode,primaryColor:this.widget.primaryColor,secondaryColor:this.widget.secondaryColor,backgroundColor:Q,glow:this._glow,shockwaves:this.widget.shockwaves??this._internalShockwaves});return new Y4({onClick:this.handleClick,child:Y})}}class J_4 extends y${props;constructor(J,Z){super(Z?{key:Z}:{});this.props=J}createElement(){return new mK(this)}createRenderObject(){return new Mv(this.props.width,this.props.height,this.props.minWidth,this.props.minHeight,this.props.maxWidth,this.props.maxHeight,this.props.time,this.props.agentMode,this.props.colorMode,this.props.primaryColor,this.props.secondaryColor,this.props.backgroundColor,this.props.glow,this.props.shockwaves)}updateRenderObject(J){J.update(this.props.width,this.props.height,this.props.minWidth,this.props.minHeight,this.props.maxWidth,this.props.maxHeight,this.props.time,this.props.agentMode,this.props.colorMode,this.props.primaryColor,this.props.secondaryColor,this.props.backgroundColor,this.props.glow,this.props.shockwaves)}}class Mv extends x4{_width;_height;_minWidth;_minHeight;_maxWidth;_maxHeight;_time;_agentMode;_colorMode;_primaryColor;_secondaryColor;_backgroundColor;_glow;_shockwaves;_palette=[];_paletteSignature="";constructor(J,Z,Q,Y,X,K,V,G,F,z,q,W,H,U=[]){super();this._width=J;this._height=Z;this._minWidth=Q;this._minHeight=Y;this._maxWidth=X;this._maxHeight=K;this._time=V;this._agentMode=G;this._colorMode=F;this._primaryColor=z;this._secondaryColor=q;this._backgroundColor=W;this._glow=H;this._shockwaves=U;this.rebuildPalette(this._agentMode,this._primaryColor,this._secondaryColor)}getPaletteSignature(J,Z,Q){if(Z&&Q)return`${Z.r},${Z.g},${Z.b}|${Q.r},${Q.g},${Q.b}`;return`mode:${J??"smart"}`}rebuildPalette(J,Z,Q){let Y=Z&&Q?{primary:Z,secondary:Q}:void 0;this._palette=Array.from({length:gj},(X,K)=>{let V=K/(gj-1);return Mo0(V,J,Y)}),this._paletteSignature=this.getPaletteSignature(J,Z,Q)}getMinIntrinsicWidth(J){return this._minWidth}getMaxIntrinsicWidth(J){return this._maxWidth}getMinIntrinsicHeight(J){return this._minHeight}getMaxIntrinsicHeight(J){return this._maxHeight}update(J,Z,Q,Y,X,K,V,G,F,z,q,W,H,U=[]){let D=!1;if(J!==this._width||Z!==this._height||Q!==this._minWidth||Y!==this._minHeight||X!==this._maxWidth||K!==this._maxHeight)this._width=J,this._height=Z,this._minWidth=Q,this._minHeight=Y,this._maxWidth=X,this._maxHeight=K,D=!0;if(this._time=V,this._agentMode=G,this._colorMode=F,this._primaryColor=z,this._secondaryColor=q,this._backgroundColor=W,this._glow=H,this._shockwaves=U,this.getPaletteSignature(G,z,q)!==this._paletteSignature)this.rebuildPalette(G,z,q);if(D)this.markNeedsLayout();this.markNeedsPaint()}performLayout(){let J=this._lastConstraints;r4(!!J,"performLayout called without constraints");let Z=J.constrain(this._width,this._height);this.setSize(Z.width,Z.height),super.performLayout()}getPaletteIndex(J,Z,Q){if(this._colorMode==="vertical"){let Y=Math.max(0,Math.min(1,0.5-Z/(2*Q)));return Math.min(gj-1,Math.floor(Y*gj))}return Math.min(gj-1,Math.floor(J*gj))}paint(J,Z=0,Q=0){let Y=Z+this.offset.x,X=Q+this.offset.y,K=Math.floor(this.size.width),V=Math.floor(this.size.height),G=J.getSize(),F=G.width,z=G.height,q=this._backgroundColor,W=this._palette,H=K/2,U=V/2,D=Math.max(1,K/2-1),B=Math.max(1,V/(2*eC4)-1),N=Math.min(D,B),w=N*N,L=1/w,O=1/eC4,E=this._agentMode==="rush"?2.5:1,M=this._shockwaves.length>0;for(let A=0;A<V;A++){let j=X+A;if(j<0||j>=z)continue;let I=(A-U)*O,S=I*I;if(S>=w)continue;let P=Math.sqrt(w-S),b=Math.max(0,Math.floor(H-P)),p=Math.min(K-1,Math.ceil(H+P));for(let x=b;x<=p;x++){let k=x-H,f=k*k+S;if(f>=w)continue;let d=1-f*L,h=this._glow.sample(x,A,this._time,E)*d;if(h<=0)continue;if(M){let q0=f*L;if(q0<0.9025)for(let w0 of this._shockwaves){let L0=this._time-w0.startTime;if(L0<0||L0>fw)continue;let e=x-w0.x,V0=(A-w0.y)*O,i=e*e+V0*V0,a=L0*jo0,t=Math.max(0,a-mj),$0=a+mj;if(i<t*t||i>$0*$0)continue;let F0=Math.sqrt(i),K0=Math.abs(F0-a);if(K0>=mj)continue;let Z0=1-L0/fw,Y0=(1-K0/mj)*Z0,B0=Math.sqrt(q0),X0=1-q0*B0;h=Math.min(1,h+Y0*0.8*X0)}}let n=Math.min(Ao0.length-1,Math.floor(h*Ao0.length)),c=Ao0[n]||FK3,s=this.getPaletteIndex(h,I,N),H0=W[s]||W[gj-1],r=Y+x;if(r<0||r>=F)continue;J.setCell(r,j,{char:c,width:1,style:{fg:H0,bg:q}})}}}}var BK3=DK3(zK3),NK3=Number.MAX_SAFE_INTEGER,wK3=30000,LK3=60000,OK3=14400000,EK3=10,MK3=1000,AK3=5,jK3=3000,RK3=80,IK3=3,Z_4=3,z_4="Watching this thread for changes. Press Ctrl-C to stop.",PK3="Live sync paused after 4 hours to save the connection. Press Enter to resume.",pj=14,uw=7,CK3=42,To0="[y/N]: ",q_4=sY.posix.join(".amp","live-sync.pid"),Av=Symbol("live-sync-archived-transition"),Kn=Symbol("live-sync-session-paused"),jv=Symbol("live-sync-stop-requested"),_K3="\x1B[0m",TK3=/^Filesystem error \(([^)]+)\):/;function SK3(J,Z){let Q=new Map;for(let V of J?.available?J.files:[])Q.set(V.path,Y_4(V));let Y=new Set(Z.files.map((V)=>V.path)),X=Z.files.filter((V)=>Q.get(V.path)!==Y_4(V)),K=H_4([...J?.available?J.files.filter((V)=>!Y.has(V.path)).map((V)=>V.path):[],...Z.files.flatMap((V)=>V.changeType==="renamed"&&V.previousPath&&!Y.has(V.previousPath)?[V.previousPath]:[])]);return{syncFiles:X,restorePaths:K}}function Io0(J){let Z=J.filter((X)=>X.changeType==="untracked").length,Q=J.length-Z,Y=[];if(Q>0)Y.push(`${Q} changed ${k4(Q,"file")}`);if(Z>0)Y.push(`${Z} untracked ${k4(Z,"file")}`);return Y.length>0?Y.join(" and "):"0 files"}function kK3(J){let Z=J.changeType.replaceAll("_"," ");if((J.changeType==="renamed"||J.changeType==="copied")&&J.previousPath)return`${Z}: ${J.previousPath} -> ${J.path}`;return`${Z}: ${J.path}`}function vK3(J,Z=EK3){let Q=J.slice(0,Z).map((X)=>` ${kK3(X)}`),Y=J.length-Q.length;if(Y>0)Q.push(` ...and ${Y} more ${k4(Y,"file")}`);return Q.join(`
|
|
6242
6242
|
`)}async function OX0(J){let Z=await hw(J,["status","--porcelain=v1","-z","--untracked-files=all"]);return Ma0(Z.stdout).filter((Q)=>Q.path!==q_4).map((Q)=>({path:Q.path,changeType:Q.changeType,previousPath:Q.previousPath}))}async function yK3(J){await hw(J,["reset","--hard","HEAD"]),await hw(J,["clean","-fd","-e",q_4])}async function xK3(J){let Z=await OX0(J.repoRoot);if(Z.length===0)return;if(!await J.promptForYesNo([`Local checkout has ${Io0(Z)}:`,vK3(Z),"Clean them up before live sync starts?","This will discard tracked changes and delete untracked files.",To0].join(`
|
|
@@ -7131,7 +7131,7 @@ See https://ampcode.com/manual#toolboxes`);return Z[0]||iP}function tu4(J,Z){let
|
|
|
7131
7131
|
`).trim()});return Q}function mU(J){return J.replace(XM3,"").replace(KM3,"").replace(YM3,"").trim()}function YX(J){if(mU(J.thinking).length>0)return!0;return J.signature.trim().length>0}function mV0(J){let Z=J.split(`
|
|
7132
7132
|
`);for(let Q=0;Q<Z.length;Q++){let Y=Z[Q]?.trim();if(!Y)continue;let X=Y.match($b4);if(X?.[1]){let V=X[1].trim();if(V)return{header:V,lineIndex:Q}}let K=Y.match(Jb4);if(K?.[1]){let V=K[1].trim();if(V)return{header:V,lineIndex:Q}}break}return{}}function Zb4(J,Z){if(Z===void 0)return J;let Q=J.split(`
|
|
7133
7133
|
`);return Q.splice(Z,1),Q.join(`
|
|
7134
|
-
`).trim()}function Qb4(J){let Z=mU(J),Q=mV0(Z);return Zb4(Z,Q.lineIndex)}class pU extends c0{thinkingBlock;expanded;onToggle;isStreaming;isCancelled;constructor({key:J,thinkingBlock:Z,expanded:Q,onToggle:Y,isStreaming:X=!1,isCancelled:K=!1}){super(J?{key:J}:{});this.thinkingBlock=Z,this.expanded=Q,this.onToggle=Y,this.isStreaming=X,this.isCancelled=K}createState(){return new Yb4}}class Yb4 extends m0{_animationTimer;_spinner=new O5;_localExpanded=!1;get isComplete(){return!this.widget.isStreaming}get expanded(){return this._localExpanded}initState(){if(super.initState(),this._localExpanded=this.widget.expanded??!1,!this.isComplete)this._startAnimation()}didUpdateWidget(J){if(super.didUpdateWidget(J),J.isStreaming&&!this.widget.isStreaming)this._stopAnimation();else if(!J.isStreaming&&this.widget.isStreaming)this._startAnimation();if(J.thinkingBlock.thinking!==this.widget.thinkingBlock.thinking)this.setState(()=>{});if(this.widget.expanded!==void 0&&this.widget.expanded!==J.expanded)this._localExpanded=this.widget.expanded}dispose(){this._stopAnimation(),super.dispose()}_startAnimation(){this._animationTimer=setInterval(()=>{this.setState(()=>{this._spinner.step()})},200)}_stopAnimation(){if(this._animationTimer)clearInterval(this._animationTimer),this._animationTimer=void 0}build(J){let Q=b1.of(J).colorScheme,Y=this.widget.isCancelled,X,K;if(Y)X=Q.warning,K="";else if(this.isComplete)X=Q.success,K="✓ ";else X=Q.accent,K=`${this._spinner.toBraille()} `;let V=mU(this.widget.thinkingBlock.thinking),G=mV0(V),F=Zb4(V,G.lineIndex),z=F.trim().length>0,q=z?new J0({text:new C(this.expanded?"▼":"▶",new g({color:Q.foreground,dim:!0}))}):null,W=Y?Q.warning:Q.foreground,H=new g({color:Y?X:Q.foreground,dim:!Y}),U=[new C(K,H),new C(G.header??"Thinking",new g({color:W,dim:!Y}))];if(Y)U.push(new C(" (interrupted)",new g({color:Q.warning,italic:!0})));let D=[new J0({text:new C("",void 0,U)})];if(q)D.push(new R0({width:1}),q);let B=new D1({mainAxisSize:"min",children:D}),N={...ev(J),text:new g({color:Q.foreground,dim:!0,italic:!0}),inlineCode:new g({color:Q.foreground,dim:!0,italic:!0,bold:!0}),codeBlock:new g({color:Q.foreground,dim:!0,italic:!0}),link:new g({color:Q.foreground,dim:!0,italic:!0,underline:!0})},w=()=>{if(this.isComplete&&!this.expanded)return;let I=O.map((S)=>{let P=[];if(P.push(new J0({text:new C(S.header,new g({color:Q.foreground,dim:!0,bold:!0}))})),this.expanded)P.push(new l0({padding:C0.vertical(1),child:new h5({markdown:S.content,styleScheme:N})}));return new b0({crossAxisAlignment:"start",children:P})});return new l0({padding:C0.only({left:2}),child:new oK({children:I})})},L=()=>{if(!this.expanded)return;return new l0({padding:C0.only({left:2}),child:new h5({markdown:F,styleScheme:N})})},O=VM3(F),M=O.length>0&&!!O[0]?.header?w():L(),j=[z?new Y4({onClick:this._handleHeaderClick.bind(this),cursor:"pointer",child:new b0({crossAxisAlignment:"start",children:[B]})}):new b0({crossAxisAlignment:"start",children:[B]})];if(M)j.push(M);return new b0({mainAxisSize:"min",crossAxisAlignment:"start",children:j})}_handleHeaderClick(J){let Z=!this.expanded;this.setState(()=>{this._localExpanded=Z}),this.widget.onToggle?.(Z)}}function zL(){return{viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},subagentContentByParentID:{},items:[],todosList:[],mainThread:null}}function jR(J){let{thread:Z,viewState:Q,resolvedTokenUsage:Y}=J;if(!Z)return zL();let{items:X}=pV0(Z),K=WC({messages:Z.messages}),V=Array.isArray(K)?K:[];return{viewState:Q,subagentContentByParentID:UM3(X,Z),items:X,todosList:V,mainThread:Z,resolvedTokenUsage:Y??Y7(Z)}}function GM3(J){return J===D9||J===w3||J===R7||J===b8||J===KC}function FM3(J){return J.content.filter((Z)=>Z.type==="text")}function zM3(J){return J.type==="text"&&J.text.trim().length>0||J.type==="thinking"&&YX(J)}function qM3(J){if(J.meta?.openAIResponsePhase==="commentary")return;switch(J.state.type){case"error":return;case"cancelled":{let Z=FM3(J);if(r8(Z).trim().length===0)return;return{...J,content:Z}}case"streaming":case"complete":{let Z=J.content.filter(zM3);if(Z.length===0)return;return{...J,content:Z}}}}function WM3(J){let Z;for(let Q of J){if(Q.type!=="message"||Q.message.role!=="assistant")continue;let Y=qM3(Q.message);if(!Y)continue;Z=Y}return Z}function HM3(J){if(typeof J==="object"&&J!==null&&!Array.isArray(J))return J;return{}}function UM3(J,Z,Q){let Y=new Map;for(let G of J)if(G.type==="toolResult"&&GM3(G.toolUse.name))Y.set(G.toolUse.id,G.toolResult.run);let X=(G,F)=>{let z=Y.get(G);if(!z||z.status!=="cancelled"||g8(F.status))return F;return{status:"cancelled",reason:"Parent subagent was cancelled"}},K=Array.from(Y.entries()),V={};for(let[G,F]of K){let z=[],q;if(F.status==="in-progress"||F.status==="done"||F.status==="error"||F.status==="cancelled")q=F.progress;if(Array.isArray(q)){let W=0;for(let H of q)if(H.tool_uses)for(let U of H.tool_uses){let D=DM3(U,G,W);if(!U.id||U.id.length===0)W++;let B=BM3(U),N=U.normalized_name??U.tool_name,w=HM3(U.input),L=Q?.get(D);z.push({toolUse:ZB(N,w,D),toolRun:X(G,B),toolProgress:L})}}V[G]={tools:z}}if(Z){let G=new Map;for(let F of Z.messages){let z=F.parentToolUseId;if(!z)continue;let q=G.get(z)??[];q.push(F),G.set(z,q)}for(let[F,z]of G){let{items:q}=pV0({id:Z.id,messages:z},{includeSubagentMessages:!0}),W=q.filter((D)=>D.type==="toolResult").map((D)=>({toolUse:D.toolUse,toolRun:X(F,D.toolResult.run),toolProgress:Q?.get(D.toolUse.id)})),H=WM3(q),U=V[F]??{tools:[]};V[F]={tools:W.length>0?W:U.tools,...H?{terminalAssistantMessage:H}:{}}}}return V}function DM3(J,Z,Q){if(typeof J.id==="string"&&J.id.length>0)return J.id;return`${Z}:progress:${Q}`}function BM3(J){if(J.status==="done"&&J.result!==void 0)return{status:"done",result:J.result};if(J.status==="error")return{status:"error",error:{message:typeof J.error==="string"&&J.error.length>0?J.error:"Subagent tool failed"}};return{status:J.status}}function pV0(J,Z){let Q=[],Y=new Set;if(Z?.includeSubagentMessages)for(let[V]of J.messages.entries())Y.add(V);else for(let[V,G]of J.messages.entries())if(!G.parentToolUseId)Y.add(V);let X=new Map,K=new Set;for(let[V,G]of J.messages.entries()){if(!Y.has(V))continue;let F=`${G.role}-${V}`;switch(G.role){case"assistant":{let z=G.state.type==="streaming";for(let W of G.content)if(W.type==="tool_use"){if(X.set(W.id,W),z)K.add(W.id)}if(G.content.some((W)=>W.type==="text"&&W.text.trim()||W.type==="thinking"&&YX(W)))Q.push({type:"message",id:F,message:G});for(let W of G.content){if(W.type!=="tool_use")continue;let H=!1;for(let U=V+1;U<J.messages.length;U++){if(!Y.has(U))continue;let D=J.messages[U];if(!D)continue;for(let B of D.content)if(B.type==="tool_result"&&B.toolUseID===W.id){H=!0;break}if(H)break}if(H)continue;Q.push({type:"toolResult",id:W.id,toolUse:W,toolResult:{type:"tool_result",toolUseID:W.id,run:{status:"in-progress"}}})}break}case"info":{if(G.content.some((q)=>q.type==="manual_bash_invocation"||q.type==="summary"&&q.summary.type==="message"))Q.push({type:"message",id:F,message:G});break}case"user":{let z=G.content.some((q)=>q.type==="text"&&q.text.trim()||q.type==="image");for(let q of G.content)if(q.type==="tool_result"){let W=X.get(q.toolUseID)??iJ(J,q.toolUseID);if(!W)throw Error(`(bug) tool use ${q.toolUseID} not found`);Q.push({type:"toolResult",id:q.toolUseID,toolUse:W,toolResult:q})}if(z)Q.push({type:"message",id:F,message:G});break}}}return{items:Q}}function Hy(J){let Z=J.toolProgressByToolUseID$.pipe(w1(hV0)),Q=()=>J.getCurrentThread?.(),Y=()=>Q()?.title,X=()=>Q()?.agentMode,K=()=>Q()?.messages??[],V=()=>Q()?.queuedMessages??[],G=()=>Q()?.env?.initial.trees?.[0]?.uri,F=()=>{let U=Q();if(!U?.autoSubmitDraft)return!1;return F8({messages:U.messages})===0},z=()=>{let U=Q();if(!U)return;if(F8({messages:U.messages})>0)return;return P10(U,"handoff")?.threadID},q=()=>F8({messages:K()})===0,W=()=>{let U=K().at(-1);return U?.role==="assistant"&&U.state.type==="streaming"},H=G5(J.thread$,J.threadViewState$).pipe(w1(([U,D])=>jR({thread:U,viewState:D,resolvedTokenUsage:J.getResolvedTokenUsage?.()})));return{get thread$(){return J.thread$},get threadState$(){return H},get threadViewState$(){return J.threadViewState$},get inferenceErrors$(){return J.inferenceErrors$},get toolProgressByToolUseID$(){return Z},get pendingApprovals$(){return J.pendingApprovals$},get pendingSkills$(){return J.pendingSkills$},get getCurrentThread(){return J.getCurrentThread},get getResolvedTokenUsage(){return J.getResolvedTokenUsage},getThreadID(){return Q()?.id},getThreadTitle(){return Y()},getAgentMode(){return X()},getMessages(){return K()},getQueuedMessages(){return V()},getInitialTreeURI(){return G()},shouldAutoSubmitDraft(){return F()},getEmptyHandoffParentThreadID(){return z()},isThreadEmpty(){return q()},isStreaming(){return W()},sendMessage:J.sendMessage,restoreTo:J.restoreTo,queueMessage:J.queueMessage,discardQueuedMessages:J.discardQueuedMessages,interruptQueuedMessage:J.interruptQueuedMessage,setTitle:J.setTitle,setVisibility:J.setVisibility,cancelTurn:J.cancelTurn,cancelStreaming:J.cancelStreaming,retryTurn:J.retryTurn,dismissEphemeralError:J.dismissEphemeralError,preExecuteMode:J.preExecuteMode,postExecuteMode:J.postExecuteMode,setTestEphemeralError:J.setTestEphemeralError,resolveApproval:J.resolveApproval,addPendingSkill:J.addPendingSkill,removePendingSkill:J.removePendingSkill,clearPendingSkills:J.clearPendingSkills,getDraft:J.getDraft,setDraft:J.setDraft,getFilesAffectedByTruncation:J.getFilesAffectedByTruncation,clearPendingNavigation:J.clearPendingNavigation,getGuidanceFiles:J.getGuidanceFiles,invokeBashTool:J.invokeBashTool}}var Xb4="Loading thread...";function NM3(J){return{id:J,created:Date.now(),v:0,messages:[]}}class ie0{placeholderThreadID;recentThreadIDsSubject=new V4([]);threadTitlesSubject=new V4({});threadHandlesSubject;allConnectedThreadActivityStatusesSubject=new V4({});legacyHandoffNavigationSubject=new H4;initializationStatusSubject=new V4({pending:!0,message:Xb4});pendingApprovalsSubject=new V4([]);pendingSkillsSubject=new V4([]);attachedPool=null;attachedPoolSubscriptions=[];attached=!1;readyPromise;readyResolve=null;readyReject=null;constructor(J=h8()){this.placeholderThreadID=J;let Z=new V4(NM3(this.placeholderThreadID)),Q=new V4(new Map),Y=new V4(wS(Z.getValue(),{state:"active",inferenceState:"idle",fileChanges:{files:[]}}));this.threadHandlesSubject=new V4(Hy({thread$:Z,threadViewState$:Y,toolProgressByToolUseID$:Q,pendingApprovals$:this.pendingApprovalsSubject,pendingSkills$:this.pendingSkillsSubject,getCurrentThread:()=>Z.getValue(),sendMessage:async(X)=>(await this.waitForActiveHandle()).sendMessage(X),restoreTo:async(X)=>(await this.waitForActiveHandle()).restoreTo(X),queueMessage:async(X)=>(await this.waitForActiveHandle()).queueMessage(X),discardQueuedMessages:async()=>(await this.waitForActiveHandle()).discardQueuedMessages(),setTitle:async(X)=>(await this.waitForActiveHandle()).setTitle(X),setVisibility:async(X)=>(await this.waitForActiveHandle()).setVisibility(X),cancelTurn:async()=>(await this.waitForActiveHandle()).cancelTurn(),cancelStreaming:async()=>(await this.waitForActiveHandle()).cancelStreaming(),retryTurn:async()=>(await this.waitForActiveHandle()).retryTurn(),dismissEphemeralError:()=>{},preExecuteMode:async()=>(await this.waitForActiveHandle()).preExecuteMode?.(),postExecuteMode:async()=>(await this.waitForActiveHandle()).postExecuteMode?.(),resolveApproval:async(X,K,V)=>(await this.waitForActiveHandle()).resolveApproval(X,K,V),addPendingSkill:()=>{},removePendingSkill:()=>{},clearPendingSkills:()=>{},getDraft:async()=>(await this.waitForActiveHandle()).getDraft(),setDraft:async(X)=>(await this.waitForActiveHandle()).setDraft(X),getFilesAffectedByTruncation:async(X)=>(await this.waitForActiveHandle()).getFilesAffectedByTruncation(X),clearPendingNavigation:async()=>(await this.waitForActiveHandle()).clearPendingNavigation(),getGuidanceFiles:async(X)=>(await this.waitForActiveHandle()).getGuidanceFiles(X)})),this.readyPromise=new Promise((X,K)=>{this.readyResolve=X,this.readyReject=K}),this.readyPromise.catch(()=>{return})}get recentThreadIDs$(){return this.recentThreadIDsSubject}get threadTitles$(){return this.threadTitlesSubject}get threadHandles$(){return this.threadHandlesSubject}get legacyHandoffNavigation$(){return this.legacyHandoffNavigationSubject}get allConnectedThreadActivityStatuses$(){return this.allConnectedThreadActivityStatusesSubject}get initializationStatus$(){return this.initializationStatusSubject}get queueOnSubmitByDefault(){return this.attachedPool?.queueOnSubmitByDefault??!1}hasPendingInitialization(){return this.attachedPool===null}isDTWMode(){return this.attachedPool?.isDTWMode?.()===!0}isThreadActorsMode(){return this.attachedPool?.isThreadActorsMode?.()===!0}getTransportConnectionState(){if(!this.attachedPool?.getTransportConnectionState)return;return this.attachedPool.getTransportConnectionState()}getTransportConnectionRole(){if(!this.attachedPool?.getTransportConnectionRole)return;return this.attachedPool.getTransportConnectionRole()}getCompactionStatus(){if(!this.attachedPool?.getCompactionStatus)return;return this.attachedPool.getCompactionStatus()}attach(J){if(this.attached)throw Error("DeferredThreadPool is already attached");this.attached=!0,this.attachedPool=J;let Z=null,Q=null;this.attachedPoolSubscriptions=[J.recentThreadIDs$.subscribe((Y)=>this.recentThreadIDsSubject.next(Y)),J.threadTitles$.subscribe((Y)=>this.threadTitlesSubject.next(Y)),J.allConnectedThreadActivityStatuses$.subscribe((Y)=>this.allConnectedThreadActivityStatusesSubject.next(Y)),...J.legacyHandoffNavigation$?[J.legacyHandoffNavigation$.subscribe((Y)=>{this.legacyHandoffNavigationSubject.next(Y)})]:[],...J.initializationStatus$?[J.initializationStatus$.subscribe((Y)=>this.initializationStatusSubject.next(Y))]:[(()=>{return this.initializationStatusSubject.next({pending:!1,message:Xb4}),{unsubscribe:()=>{}}})()],J.threadHandles$.subscribe((Y)=>{if(Y)Z?.unsubscribe(),Z=Y.pendingApprovals$.subscribe((X)=>this.pendingApprovalsSubject.next(X)),Q?.unsubscribe(),Q=Y.pendingSkills$.subscribe((X)=>this.pendingSkillsSubject.next(X)),this.threadHandlesSubject.next(Y)}),{unsubscribe:()=>{Z?.unsubscribe(),Q?.unsubscribe()}}],this.readyResolve?.(J),this.readyResolve=null,this.readyReject=null}setInitError(J){if(this.attached)return;this.readyReject?.(J),this.readyResolve=null,this.readyReject=null}async createThread(){return(await this.waitForAttach()).createThread()}async switchThread(J){return(await this.waitForAttach()).switchThread(J)}canNavigateBack(){return this.attachedPool?.canNavigateBack()??!1}canNavigateForward(){return this.attachedPool?.canNavigateForward()??!1}async navigateBack(){return(await this.waitForAttach()).navigateBack()}async navigateForward(){return(await this.waitForAttach()).navigateForward()}async createHandoff(J,Z){return(await this.waitForAttach()).createHandoff(J,Z)}async deleteThread(J){let Z=await this.waitForAttach();if(Z.deleteThread)await Z.deleteThread(J)}async dispose(){for(let J of this.attachedPoolSubscriptions)J.unsubscribe();if(this.attachedPoolSubscriptions=[],this.attachedPool)await this.attachedPool.dispose();this.recentThreadIDsSubject.complete(),this.threadTitlesSubject.complete(),this.threadHandlesSubject.complete(),this.allConnectedThreadActivityStatusesSubject.complete(),this.legacyHandoffNavigationSubject.complete(),this.initializationStatusSubject.complete(),this.pendingApprovalsSubject.complete(),this.pendingSkillsSubject.complete()}waitForAttach(){if(this.attachedPool)return Promise.resolve(this.attachedPool);return this.readyPromise}async waitForActiveHandle(){let J=await this.waitForAttach();return I1(J.threadHandles$.pipe(f5((Z)=>Z!==null)))}}n0();Lc();c4();E1();n0();F3();f7();BB();t30();c4();jH();Sg0();I4();U4();E1();KJ();c4();function wM3(J){let Z=J.messages.filter((V)=>!V.parentToolUseId),Q=-1;for(let V=Z.length-1;V>=0;V--)if(Z[V]?.role==="assistant"){Q=V;break}if(Q<0)return{running:0,blocked:0};let Y=Z[Q];if(!Y)return{running:0,blocked:0};let X=new Map;for(let V of Z.slice(Q+1)){if(V.role!=="user")continue;for(let G of V.content)if(G.type==="tool_result")X.set(G.toolUseID,G.run)}let K=0;for(let V of Y.content){if(V.type!=="tool_use")continue;let G=X.get(V.id);if(!G||!g8(G.status))K++}return{running:K,blocked:0}}function LM3(J){let Z=J.messages.at(-1);if(!Z)return"user-message-initial";if(Z.role==="assistant")return Z.state.type==="complete"&&Z.state.stopReason==="end_turn"?"user-message-reply":!1;return!1}function OM3(J){let Z=LM3(J);if(Z)return Z;return!1}function Uy(J,Z,Q={files:[]},Y=void 0){let X=wM3(J),K=Z==="awaiting_approval"?1:0;if(Z==="working"||Z==="streaming")return{state:"active",inferenceState:"running",fileChanges:Q,ephemeralError:Y,interactionState:!1,toolState:{running:0,blocked:0}};if(Z==="tool_use"||Z==="running_tools"){let V=X.running;return{state:"active",inferenceState:"idle",fileChanges:Q,ephemeralError:Y,interactionState:V>0?"tool-running":!1,toolState:{running:V,blocked:K}}}if(Z==="awaiting_approval")return{state:"active",inferenceState:"idle",fileChanges:Q,ephemeralError:Y,interactionState:"user-tool-approval",toolState:{running:X.running,blocked:K}};return{state:"active",inferenceState:"idle",fileChanges:Q,ephemeralError:Y,interactionState:OM3(J),toolState:{running:X.running,blocked:K}}}c4();class ne0{authoritativeThread;currentAgentLoopState;pendingMessageSubmits=[];pendingQueuedSubmits=[];pendingQueuedInterruptMessageIDs=new Set;pendingEdit;constructor(J,Z){this.authoritativeThread=J,this.currentAgentLoopState=Z}setAgentLoopState(J){this.currentAgentLoopState=J}optimisticUpdate(J){switch(J.type){case"submit":return this.optimisticSubmit(J);case"discard-queued":return this.pendingQueuedSubmits=[],this.pendingQueuedInterruptMessageIDs.clear(),this.buildProjection();case"interrupt-queued":return this.optimisticInterruptQueued(J);case"edit":return this.optimisticEdit(J);case"drop-submit":return this.dropOptimisticSubmit(J);case"update-submit-guidance":return this.updateOptimisticSubmitGuidance(J)}}updateOptimisticSubmitGuidance(J){let Z=!1;if(this.pendingMessageSubmits=this.pendingMessageSubmits.map((Q)=>{if(Q.clientMessageID!==J.clientMessageID)return Q;return Z=!0,{...Q,discoveredGuidanceFiles:J.discoveredGuidanceFiles}}),!Z)this.pendingQueuedSubmits=this.pendingQueuedSubmits.map((Q)=>{if(Q.clientMessageID!==J.clientMessageID)return Q;return Z=!0,{...Q,discoveredGuidanceFiles:J.discoveredGuidanceFiles}});return this.buildProjection()}dropOptimisticSubmit(J){let Z=this.pendingMessageSubmits.filter((Y)=>Y.clientMessageID!==J.clientMessageID),Q=this.pendingQueuedSubmits.filter((Y)=>Y.clientMessageID!==J.clientMessageID);if(Z.length===this.pendingMessageSubmits.length&&Q.length===this.pendingQueuedSubmits.length)return this.buildProjection();return this.pendingMessageSubmits=Z,this.pendingQueuedSubmits=Q,this.buildProjection()}optimisticInterruptQueued(J){let Z=this.buildProjection(),Q=(Z.queuedMessages??[]).find((Y)=>(Y.queuedMessage.dtwMessageID??Y.id)===J.queuedMessageID);if(!Q||ae0(Q))return Z;if(this.pendingQueuedInterruptMessageIDs.has(J.queuedMessageID))return this.buildProjection();return this.pendingQueuedInterruptMessageIDs.add(J.queuedMessageID),this.buildProjection()}optimisticSubmit(J){if(kM3(this.pendingMessageSubmits,this.pendingQueuedSubmits,this.authoritativeThread,J.clientMessageID))return this.buildProjection();let Z={clientMessageID:J.clientMessageID,content:J.content,userState:J.userState,sentAt:J.sentAt??Date.now()};if(mM3(this.currentAgentLoopState))this.pendingQueuedSubmits.push(Z);else this.pendingMessageSubmits.push(Z);return this.buildProjection()}optimisticEdit(J){let Z=this.buildProjection(),Q=Oj0(Z,J.targetMessageID);if(Q<0)return Z;return this.pendingMessageSubmits=[],this.pendingQueuedSubmits=[],this.pendingEdit={targetMessageID:J.targetMessageID,content:J.content,truncatedMessageIDs:_M3(Z,Q)},this.buildProjection()}resolve(J){if(!this.hasPendingOverlay())return this.authoritativeThread=J,J;let Z=this.authoritativeThread;return this.authoritativeThread=J,this.reconcilePending(Z),this.buildProjection()}hasPendingOverlay(){return MM3(this.pendingMessageSubmits,this.pendingQueuedSubmits,this.pendingQueuedInterruptMessageIDs,this.pendingEdit)}reconcilePending(J){let Z=CM3(this.authoritativeThread);this.pendingMessageSubmits=vM3(J,this.authoritativeThread,Z,this.pendingMessageSubmits),this.pendingQueuedSubmits=uM3(this.authoritativeThread,Z,this.pendingQueuedSubmits),this.pendingQueuedInterruptMessageIDs=bM3(this.authoritativeThread,this.pendingQueuedSubmits,this.pendingQueuedInterruptMessageIDs),this.pendingEdit=hM3(Z,this.pendingEdit)}buildProjection(){if(!this.hasPendingOverlay())return this.authoritativeThread;let J=this.pendingEdit;return EM3(this.authoritativeThread,(Z)=>AM3(Z,J),(Z)=>jM3(Z,this.pendingMessageSubmits),(Z)=>RM3(Z,this.pendingQueuedSubmits),(Z)=>IM3(Z,this.pendingQueuedInterruptMessageIDs))}}function EM3(J,...Z){return Z.reduce((Q,Y)=>Y?Y(Q):Q,J)}function MM3(J,Z,Q,Y){return J.length>0||Z.length>0||Q.size>0||Y!==void 0}function AM3(J,Z){if(!Z)return J;let Q=Bf1(J,Z.targetMessageID);if(!Q)return J;let{index:Y,message:X}=Q,K=J.messages.slice(0,Y+1);return K[Y]={...X,content:Z.content},{...J,messages:K,nextMessageId:Lj0({messages:K,nextMessageId:J.nextMessageId})}}function jM3(J,Z){if(Z.length===0)return J;let Q=Lj0(J),Y=Z.map((X,K)=>Vb4(X,Q+K));return{...J,messages:[...J.messages,...Y],nextMessageId:Math.max(J.nextMessageId??0,Q+Y.length)}}function RM3(J,Z){if(Z.length===0)return J;let Q=Z.map(PM3);return{...J,queuedMessages:[...J.queuedMessages??[],...Q]}}function IM3(J,Z){if(Z.size===0||!J.queuedMessages?.length)return J;let Q=!1,Y=J.queuedMessages.map((X)=>{let K=cV0(X);if(!K||!Z.has(K)||ae0(X))return X;return Q=!0,{...X,interrupt:!0}});if(!Q)return J;return{...J,queuedMessages:Y}}function Vb4(J,Z){return{role:"user",content:J.content,userState:J.userState,discoveredGuidanceFiles:J.discoveredGuidanceFiles,meta:{sentAt:J.sentAt},messageId:Z,dtwMessageID:J.clientMessageID}}function PM3(J){return{id:J.clientMessageID,queuedMessage:Vb4(J,-1)}}function CM3(J){let Z=new Set,Q=new Set,Y=new Map,X=new Set;for(let K of J.messages){let V=dV0(K);if(V){if(X.add(V),K.role==="user")Z.add(V),Y.set(V,K)}}for(let K of J.queuedMessages??[]){let V=cV0(K);if(V)Q.add(V)}return{userMessageIDs:Z,queuedMessageIDs:Q,userMessagesByID:Y,messageIDsInTimeline:X}}function _M3(J,Z){return J.messages.slice(Z+1).map((Q)=>dV0(Q)).filter((Q)=>Q!==void 0)}function TM3(J,Z){return J.messages.some((Q)=>Q.role==="user"&&dV0(Q)===Z)}function SM3(J,Z){return(J.queuedMessages??[]).some((Q)=>cV0(Q)===Z)}function ae0(J){return"interrupt"in J&&J.interrupt===!0}function kM3(J,Z,Q,Y){return J.some((X)=>X.clientMessageID===Y)||Z.some((X)=>X.clientMessageID===Y)||TM3(Q,Y)||SM3(Q,Y)}function vM3(J,Z,Q,Y){if(Y.length===0)return[];let{unmatchedPendingSubmits:X,acknowledgedByID:K}=yM3(Y,Q.userMessageIDs);if(X.length===0)return[];let V=xM3(J,Z);if(!V)return X;let G=fM3(V,K,X.length);return X.slice(G)}function yM3(J,Z){let Q=new Set,Y=[];for(let X of J){if(Z.has(X.clientMessageID)){Q.add(X.clientMessageID);continue}Y.push(X)}return{unmatchedPendingSubmits:Y,acknowledgedByID:Q}}function xM3(J,Z){let Q=Kb4(J),Y=Kb4(Z);if(!(Q.length<=Y.length&&Q.every((K,V)=>K.dtwMessageID===Y[V]?.dtwMessageID)))return;return Y.slice(Q.length)}function fM3(J,Z,Q){let Y=0;for(let X of J){let K=dV0(X);if(K&&Z.has(K))continue;if(Y++,Y===Q)return Y}return Y}function Kb4(J){return J.messages.filter((Z)=>Z.role==="user")}function uM3(J,Z,Q){if(Q.length===0)return[];let Y=[...J.queuedMessages??[]];return Q.filter((X)=>{if(Z.queuedMessageIDs.has(X.clientMessageID)||Z.userMessageIDs.has(X.clientMessageID))return!1;let K=Y.findIndex((V)=>Ej0(X.content,V.queuedMessage.content));if(K>=0)return Y.splice(K,1),!1;return!0})}function bM3(J,Z,Q){if(Q.size===0)return new Set;let Y=new Map((J.queuedMessages??[]).map((V)=>{let G=cV0(V);if(!G)return;return[G,V]}).filter((V)=>V!==void 0)),X=new Set(Z.map((V)=>V.clientMessageID)),K=new Set;for(let V of Q){let G=Y.get(V);if(!G){if(X.has(V))K.add(V);continue}if(ae0(G))continue;K.add(V)}return K}function hM3(J,Z){if(!Z)return;return gM3(J,Z)?void 0:Z}function gM3(J,Z){let Q=n6.safeParse(Z.targetMessageID);if(!Q.success)return!1;let Y=J.userMessagesByID.get(Q.data);if(!Y)return!1;if(!Ej0(Y.content,Z.content))return!1;return Z.truncatedMessageIDs.every((K)=>{let V=n6.safeParse(K);if(!V.success)return!0;return!J.messageIDsInTimeline.has(V.data)})}function dV0(J){let Z=n6.safeParse(J.dtwMessageID);if(!Z.success)return;return Z.data}function cV0(J){let Z=n6.safeParse(J.queuedMessage.dtwMessageID);if(Z.success)return Z.data;let Q=n6.safeParse(J.id);if(Q.success)return Q.data;return}function mM3(J){return pM3.has(J)}var pM3=new Set(["working","streaming","tool_use","running_tools","awaiting_approval"]);var dM3=1e4;class oe0{deps;thread$;threadState$;threadViewState$;inferenceErrors$;toolProgressByToolUseID$;pendingApprovals$;provider;threadSubject;threadStateSubject;threadViewStateSubject;transportSubscriptions=[];clientID;executorRuntime;toolRunner;optimisticThreadProjection;pendingApprovalsSubject=new V4([]);pendingSkillsSubject=new V4([]);inferenceErrorsSubject=new H4;pendingSkills$=this.pendingSkillsSubject;latestPendingApprovals=[];fileChanges={files:[]};currentAgentLoopState;activeError=null;retryCountdownTimer=null;handoffService;providerSubscriptions=null;constructor(J,Z){this.deps=Z;this.provider=J,this.clientID=Z.clientID;let Q=iD("info"),Y=iD("error"),X=(z)=>({...z??{},threadId:this.provider.threadId}),K={info:(z,q)=>{Q(z,X(q))},error:(z,q)=>{Y(z,X({error:q}))},wsMessage:(z,q,W)=>{_.debug("DTW executor tool runner message",X({direction:z,clientID:q,...typeof W==="object"&&W!==null?W:{message:W}}))}};this.executorRuntime=new kj({transport:this.provider.executorTransport(),toolService:this.deps.toolService,configService:this.deps.configService,clientID:this.clientID,threadID:this.provider.threadId,invokeTool:(z)=>this.invokeToolForLease(z),skillService:this.deps.skillService,initialToolDiscovery:this.deps.initialToolDiscovery,onBootstrapSuccess:()=>{this.applyLocalEnvironment()},sendGitSnapshot:!1,batchGuidanceFiles:yY0,renderToolRunError:mm,log:K,autoResolvePendingApprovals:!1,handshake:(z)=>this.sendExecutorHandshake(z),handshakeManagerOptions:{onError:({error:z,attempt:q,delayMs:W})=>{_.warn("DTW executor handshake failed",{error:z,attempt:q,delayMs:W})},onExhausted:(z)=>{this.handleHandshakeExhausted(z)}},handleExecutorRollbackRequest:async(z)=>{await this.handleRollbackRequest(z).catch(()=>{return})},handleExecutorFileSystemReadDirectoryRequest:async(z)=>{await this.handleFileSystemReadDirectoryRequest(z).catch(()=>{return})},handleExecutorFileSystemReadFileRequest:async(z)=>{await this.handleFileSystemReadFileRequest(z).catch(()=>{return})}}),this.executorRuntime.attachTransportExecutorCallbacks({includeConnectionChanges:!0}),this.toolRunner=this.executorRuntime.toolRunner,this.executorRuntime.handleConnectionChange(this.provider.executorTransport().getConnectionInfo()),this.currentAgentLoopState=J.getAgentLoopState();let V=J.getThread();this.optimisticThreadProjection=new ne0(V,this.currentAgentLoopState);let G=this.optimisticThreadProjection.resolve(V),F=Uy(G,this.currentAgentLoopState,this.fileChanges,this.currentEphemeralError());this.threadSubject=new V4(G),this.thread$=this.threadSubject,this.threadStateSubject=new V4(jR({thread:G,viewState:F,resolvedTokenUsage:Y7(G)})),this.threadState$=this.threadStateSubject,this.threadViewStateSubject=new V4(F),this.threadViewState$=this.threadViewStateSubject,this.inferenceErrors$=this.inferenceErrorsSubject,this.toolProgressByToolUseID$=this.provider.toolProgressByToolUseIDChanges().pipe(w1(hV0)),this.transportSubscriptions.push(this.threadSubject.subscribe((z)=>{this.rebuildThreadState(z)}),this.threadViewStateSubject.subscribe((z)=>{let q=this.threadStateSubject.getValue();if(q.viewState===z)return;this.threadStateSubject.next({...q,viewState:z})})),this.pendingApprovals$=this.pendingApprovalsSubject,this.refreshProviderFileChanges(),this.attachTransportHandlers(),this.handoffService=Z.handoffService}startProviderSubscription(J){this.providerSubscriptions?.unsubscribe();let Z=this.provider.threadChanges().subscribe({next:(Y)=>{J(Y),this.refreshProviderFileChanges(),this.updateThreadViewStateFromProvider()}}),Q=this.provider.agentLoopStateChanges().subscribe({next:(Y)=>{if(this.currentAgentLoopState=Y,this.optimisticThreadProjection.setAgentLoopState(Y),Y==="error")this.inferenceErrorsSubject.next(Error("Agent failed to complete the request."));this.updateThreadViewStateFromProvider()}});this.providerSubscriptions={unsubscribe:()=>{Z.unsubscribe(),Q.unsubscribe()}}}writeThread(J){this.currentAgentLoopState=this.provider.getAgentLoopState(),this.threadSubject.next(J)}providerThread(){return this.provider.getThread()}resolveAuthoritativeThread(J){return this.optimisticThreadProjection.resolve(J)}getThreadViewState(){return this.threadViewStateSubject.getValue()}getCurrentThread(){return this.threadSubject.getValue()}getThreadID(){return this.getCurrentThread().id}getThreadTitle(){return this.getCurrentThread().title}getAgentMode(){return this.getCurrentThread().agentMode}getMessages(){return this.getCurrentThread().messages}getQueuedMessages(){return this.getCurrentThread().queuedMessages??[]}getInitialTreeURI(){return this.getCurrentThread().env?.initial.trees?.[0]?.uri}shouldAutoSubmitDraft(){let J=this.getCurrentThread();if(!J.autoSubmitDraft)return!1;return F8(J)===0}getEmptyHandoffParentThreadID(){let J=this.getCurrentThread();if(F8(J)>0)return;return P10(J,"handoff")?.threadID}isThreadEmpty(){return F8(this.getCurrentThread())===0}isStreaming(){let J=this.getMessages().at(-1);return J?.role==="assistant"&&J.state.type==="streaming"}getResolvedTokenUsage(){return Y7(this.thread$.getValue())}async dispose(){this.providerSubscriptions?.unsubscribe(),this.providerSubscriptions=null;for(let J of this.transportSubscriptions)J.unsubscribe();this.transportSubscriptions.length=0,this.clearRetryCountdownTimer(),this.executorRuntime.dispose(),await this.provider.disposeAndWaitForClose(),this.threadSubject.complete(),this.threadStateSubject.complete(),this.threadViewStateSubject.complete(),this.inferenceErrorsSubject.complete(),this.pendingApprovalsSubject.complete(),this.pendingSkillsSubject.complete()}async sendMessage(J){if(J.editIndex!==void 0){await this.ensureProviderReadyForExecutorActions();let K=this.thread$.getValue(),V=K.messages[J.editIndex];if(!V||V.role!=="user"||!V.dtwMessageID)throw Error("Unable to edit message: missing DTW message ID");let G=K.messages.findIndex((q)=>q.role==="user");if(J.editIndex===G&&J.agentMode&&K.agentMode!==J.agentMode)this.provider.setAgentMode(J.agentMode,{overwrite:!0}),this.updateThread((q)=>{q.agentMode=J.agentMode});this.provider.editUserMessage(V.dtwMessageID,J.content,mn0(),J.agentMode);let z=this.optimisticThreadProjection.optimisticUpdate({type:"edit",targetMessageID:V.dtwMessageID,content:J.content});this.writeThread(z);return}let Z=this.thread$.getValue();if(!Z.messages.some((K)=>K.role==="user")&&J.agentMode&&Z.agentMode!==J.agentMode)this.provider.setAgentMode(J.agentMode,{overwrite:!0}),this.updateThread((K)=>{K.agentMode=J.agentMode});let Y=Eq(),X=this.optimisticThreadProjection.optimisticUpdate({type:"submit",clientMessageID:Y,content:J.content});this.writeThread(X);try{let K=J.prepareContentForSend?await J.prepareContentForSend(J.content):J.content;await this.ensureProviderConnectedForClientWrites();let V=await this.discoverGuidanceFilesForUserMessage(K);if(V&&V.length>0){let F=V.map((q)=>({uri:q.uri,lineCount:q.lineCount??0,...typeof q.content==="string"?{content:q.content}:{}})),z=this.optimisticThreadProjection.optimisticUpdate({type:"update-submit-guidance",clientMessageID:Y,discoveredGuidanceFiles:F});this.writeThread(z)}let G=await this.collectUserState();this.provider.sendUserMessage(K,J.agentMode,G,Y,V)}catch(K){throw this.rollbackOptimisticSubmit(Y),K}}async restoreTo(J){await this.ensureProviderReadyForExecutorActions();let Y=[...this.thread$.getValue().messages.slice(0,J+1)].reverse().find((V)=>V.role==="user");if(!Y?.dtwMessageID)throw Error("Unable to edit message: missing DTW message ID");let X=Y.content.filter((V)=>V.type==="text"||V.type==="image").map((V)=>{if(V.type==="image")return{...V,source:{...V.source}};return{...V}});if(X.length===0)throw Error("Unable to edit message: no editable content found");this.provider.editUserMessage(Y.dtwMessageID,X,mn0());let K=this.optimisticThreadProjection.optimisticUpdate({type:"edit",targetMessageID:Y.dtwMessageID,content:X});this.writeThread(K)}async queueMessage(J){let Z=Eq(),Q=this.optimisticThreadProjection.optimisticUpdate({type:"submit",clientMessageID:Z,content:J});this.writeThread(Q);try{await this.ensureProviderConnectedForClientWrites();let Y=await this.discoverGuidanceFilesForUserMessage(J);if(Y&&Y.length>0){let K=Y.map((G)=>({uri:G.uri,lineCount:G.lineCount??0,...typeof G.content==="string"?{content:G.content}:{}})),V=this.optimisticThreadProjection.optimisticUpdate({type:"update-submit-guidance",clientMessageID:Z,discoveredGuidanceFiles:K});this.writeThread(V)}let X=await this.collectUserState();this.provider.sendUserMessage(J,void 0,X,Z,Y)}catch(Y){throw this.rollbackOptimisticSubmit(Z),Y}}async discardQueuedMessages(){let J=this.optimisticThreadProjection.optimisticUpdate({type:"discard-queued"});this.writeThread(J),this.provider.discardQueuedMessages()}async interruptQueuedMessage(J){await this.ensureProviderReadyForExecutorActions(),this.provider.interruptQueuedMessage(J);let Z=this.optimisticThreadProjection.optimisticUpdate({type:"interrupt-queued",queuedMessageID:J});this.writeThread(Z)}async ensureProviderConnectedForClientWrites(){await this.provider.ensureConnectedForAction("client-write")}async ensureProviderReadyForExecutorActions(J){await this.provider.ensureConnectedForAction("executor-action"),await this.executorRuntime.ensureReady({timeoutMs:dM3,timeoutMessage:"Timed out waiting for executor readiness. Please retry."})}rollbackOptimisticSubmit(J){let Z=this.optimisticThreadProjection.optimisticUpdate({type:"drop-submit",clientMessageID:J});this.writeThread(Z)}async setVisibility(J){await this.deps.threadService.updateThreadMeta(this.provider.threadId,oG(J));let Z=await this.deps.threadService.get(this.provider.threadId);if(Z)this.writeThread(Z)}async setTitle(J){let Z=J.trim();if(!Z)return;await this.ensureProviderReadyForExecutorActions(),this.provider.setThreadTitle(Z),this.updateThread((Q)=>{Q.title=Z})}updateThread(J){let Z=v9(this.threadSubject.getValue(),J),Q=this.optimisticThreadProjection.resolve(Z);this.writeThread(Q)}async cancelTurn(){this.provider.cancelAgentLoop()}async cancelStreaming(){this.provider.cancelAgentLoop()}async retryTurn(){this.provider.retryAgentLoop()}invokeBashTool(J,Z){let Q=fj4();return new k0((Y)=>{let X=!1,K=null,V=(q)=>{try{this.provider.appendManualBashInvocation({args:J,run:q,hidden:Z.hidden})}catch(W){_.warn("Failed to append manual bash invocation to DTW thread",{error:W}),this.activeError={message:`Failed to sync bash result to thread: ${W instanceof Error?W.message:String(W)}`},this.updateThreadViewStateFromProvider()}},G=(q,W={emitRun:!0})=>{if(X)return;if(X=!0,V(q),W.emitRun)Y.next(q);Y.complete()},F=(q)=>q instanceof Error?q.message:String(q),z=()=>{K?.unsubscribe(),G({status:"cancelled",reason:"User canceled"})};return Z.abortController.signal.addEventListener("abort",z),(async()=>{try{if(await this.ensureProviderReadyForExecutorActions(),X)return;let q=await uG({toolName:m6,dtwArtifactSyncService:this.createDTWArtifactSyncService(),configService:this.deps.configService,toolService:this.deps.toolService,mcpService:this.deps.mcpService,skillService:this.deps.skillService,fsTracker:this.deps.fs,toolUseID:Q,discoveredGuidanceFileURIs:this.toolRunner.discoveredGuidanceFileURIs,threadID:this.provider.threadId});if(X)return;let W={...q,userInitiated:!0};Y.next({status:"in-progress"}),K=this.deps.toolService.invokeTool(m6,{args:J,userInput:{accepted:!0}},W).subscribe({next:(H)=>{if(X)return;if(Y.next(H),H.status!=="in-progress")G(H,{emitRun:!1})},error:(H)=>{G({status:"error",error:{message:F(H)}})}})}catch(q){G({status:"error",error:{message:F(q)}})}})(),()=>{K?.unsubscribe(),Z.abortController.signal.removeEventListener("abort",z)}})}dismissEphemeralError(){this.activeError=null,this.clearRetryCountdownTimer(),this.updateThreadViewStateFromProvider()}async resolveApproval(J,Z,Q){let Y=K9.safeParse(J);if(!Y.success)return;this.provider.resolveToolApproval(Y.data,Z,{denyFeedback:Q})}addPendingSkill(J){this.pendingSkillsSubject.next([...this.pendingSkillsSubject.getValue(),J])}removePendingSkill(J){this.pendingSkillsSubject.next(this.pendingSkillsSubject.getValue().filter((Z)=>Z.name!==J))}clearPendingSkills(){this.pendingSkillsSubject.next([])}async getDraft(){let J=this.thread$.getValue().draft;if(!J)return null;let Z=zC(J);if(!Z.text&&Z.images.length===0)return null;return Z}async setDraft(J){this.updateThread((Z)=>{if(!J||!J.text&&J.images.length===0){delete Z.draft,delete Z.autoSubmitDraft;return}let Q=[];if(J.text)Q.push({type:"text",text:J.text});if(J.images.length>0)Q.push(...J.images);Z.draft=Q,Z.autoSubmitDraft=!1})}async clearPendingNavigation(){}async getGuidanceFiles(J){let Z=this.thread$.getValue();return(await Wz({filesystem:this.deps.filesystem,configService:this.deps.configService,threadService:this.deps.threadService},Z,J)).map((Y)=>({uri:Y.uri,type:Y.type}))}async getFilesAffectedByTruncation(J){let Z=this.thread$.getValue(),Q=await this.getToolUsesToRevert(Z,J);return Q.size>0?this.deps.fs.tracker.getFilesForToolUses(Q):[]}async getToolUsesToRevert(J,Z){let Q=new Set;J.messages.slice(0,Z).forEach((K)=>{if(K.role==="user"){for(let V of K.content)if(V.type==="tool_result")Q.add(V.toolUseID)}else for(let V of K.content)if(V.type==="tool_use")Q.add(V.id)});let Y=new Set,X=await this.deps.fs.tracker.getAllRecords();for(let[K]of X.entries())if(!Q.has(K))Y.add(K);return Y}async collectUserState(){try{return await y$0()??bm}catch(J){return _.warn("Failed to collect IDE user state for DTW message",{error:J}),bm}}resolveUserMessageGuidanceContext(){let J=G1.file(process.cwd()),Q=this.thread$.getValue().env?.initial,Y=Q?.trees?.[0]?.uri?T6(Q.trees[0].uri):J;return{workspaceRoot:Y.scheme==="file"?Y:J,workingDirectory:J}}resolveMentionedPathToURI(J,Z){if(J.startsWith("file://"))try{let Y=G1.parse(J);return Y.scheme==="file"?Y:null}catch{return null}if(ZJ(J))return G1.file(J);let Q=J.startsWith("./")||J.startsWith("../")?Z.workingDirectory:Z.workspaceRoot;return V1.resolvePath(Q,J)}async discoverGuidanceFilesForUserMessage(J){let Z=r8(J);if(!Z.trim())return;let{paths:Q}=v$0(Z);if(Q.length===0)return;let Y=this.resolveUserMessageGuidanceContext(),X=new Set,K=new Set,V=[];for(let G of Q){let F=this.resolveMentionedPathToURI(G,Y);if(!F||!V1.hasPrefix(F,Y.workspaceRoot))continue;let z=F.toString();if(K.has(z))continue;K.add(z);let q=await qQ({stat:(W,H)=>this.deps.filesystem.stat(W,H),readFile:(W,H)=>this.deps.filesystem.readFile(W,H)},F,Y.workspaceRoot,null,X);for(let W of q){if(V.some((H)=>H.uri===W.uri))continue;X.add(W.uri),V.push({uri:W.uri,content:W.content,lineCount:W.lineCount})}}return V.length>0?V:void 0}handleHandshakeExhausted(J){_.error("DTW executor handshake exhausted",J)}syncApprovalRequests(J){let Z=this.provider.threadId;if(!Z){this.pendingApprovalsSubject.next([]);return}let Q=J.filter((X)=>X.threadId===Z||X.mainThreadId===Z);this.pendingApprovalsSubject.next(Q);let Y=new Set(Q.map(Tj));for(let X of[...this.toolRunner.sentApprovalRequests])if(!Y.has(X))this.toolRunner.sentApprovalRequests.delete(X);for(let X of Q){let K=Tj(X);if(this.toolRunner.sentApprovalRequests.has(K))continue;let V=CY0(X);if(this.provider.sendExecutorToolApprovalRequest(V))this.toolRunner.sentApprovalRequests.add(K)}}handleExecutorToolApprovalResponse(J){this.deps.toolService.resolveApproval(J.toolCallId,J.accepted,J.input?.denyFeedback)}syncExecutorTools(J){this.executorRuntime.syncExecutorToolRegistrations(J)}attachTransportHandlers(){this.transportSubscriptions.push(this.provider.executorReadyChanges().subscribe({next:(J)=>{if(J)this.syncApprovalRequests(this.latestPendingApprovals)}}),this.provider.compactionStateChanges().subscribe({next:()=>{this.updateThreadViewStateFromProvider()}}),this.provider.errorEvents().subscribe({next:(J)=>{if(this.activeError=J.type==="error_set"?J.error:null,J.type==="error_set")this.inferenceErrorsSubject.next(J.error);this.syncRetryCountdownTimer(),this.updateThreadViewStateFromProvider()}}),this.provider.errors().subscribe({next:(J)=>{this.inferenceErrorsSubject.next(Error(J.message))}}),this.provider.cancelledEvents().subscribe({next:()=>{this.activeError=null,this.clearRetryCountdownTimer(),this.updateThreadViewStateFromProvider()}}),this.provider.executorToolApprovalResponses().subscribe({next:(J)=>{this.handleExecutorToolApprovalResponse(J)}}),this.deps.toolService.tools.subscribe({next:(J)=>{this.syncExecutorTools(Hv(J))}}),this.deps.toolService.pendingApprovals$.subscribe((J)=>{this.latestPendingApprovals=J,this.syncApprovalRequests(J)}))}async sendExecutorHandshake(J){_.debug("DTW executor handshake",{trigger:J,threadID:this.provider.threadId}),await this.executorRuntime.bootstrapExecutor({executorType:"local-client",trigger:J,workspaceRoot:process.cwd(),threadID:this.provider.threadId,suppressConnectLog:!0})}async applyLocalEnvironment(){try{let J=await WZ();this.provider.setEnvironment({initial:J})}catch(J){_.debug("Failed to apply local environment",{error:J})}}createDTWArtifactSyncService(){return{upsertArtifact:(J,Z)=>{let Q=K9.safeParse(Z);this.provider.sendExecutorArtifactUpsert(J,Q.success?Q.data:void 0)},deleteArtifact:(J)=>{this.provider.sendExecutorArtifactDelete(J)}}}async invokeToolForLease(J){let Z=typeof J.args==="object"&&J.args!==null?J.args:{},Q=Date.now(),Y=await uG({toolName:J.toolName,dtwHandoffService:this.handoffService,dtwArtifactSyncService:this.createDTWArtifactSyncService(),configService:this.deps.configService,toolService:this.deps.toolService,mcpService:this.deps.mcpService,skillService:this.deps.skillService,fsTracker:this.deps.fs,toolUseID:J.toolCallId,discoveredGuidanceFileURIs:this.toolRunner.discoveredGuidanceFileURIs,threadID:this.provider.threadId});_.info("DTW TUI tool run environment ready",{toolCallId:J.toolCallId,toolName:J.toolName,threadId:this.provider.getThread().id,elapsedMs:Date.now()-Q});let X=this.deps.toolService.invokeTool(J.toolName,{args:Z},Y);return _.info("DTW TUI tool service returned observable",{toolCallId:J.toolCallId,toolName:J.toolName,threadId:this.provider.getThread().id,elapsedMs:Date.now()-Q}),X}async handleRollbackRequest(J){await this.toolRunner.handleRollbackRequest(J.editId,J.toolUseIdsToRevert,(Z)=>this.deps.fs.tracker.revertChanges(Z)),await this.refreshProviderFileChanges(),this.updateThreadViewStateFromProvider()}async handleFileSystemReadDirectoryRequest(J){let Z=await qv({fileSystem:this.deps.filesystem,workspaceRoot:process.cwd()},J.uri);this.provider.sendExecutorFileSystemReadDirectoryResult(J.requestId,Z)}async handleFileSystemReadFileRequest(J){let Z=await TY0({fileSystem:this.deps.filesystem,workspaceRoot:process.cwd()},J.uri);this.provider.sendExecutorFileSystemReadFileResult(J.requestId,Z)}async refreshProviderFileChanges(){this.fileChanges={files:await s30(this.deps.fs.tracker)},this.updateThreadViewStateFromProvider()}updateThreadViewStateFromProvider(){this.threadViewStateSubject.next(Uy(this.threadSubject.getValue(),this.currentAgentLoopState,this.fileChanges,this.currentEphemeralError())),this.deps.onThreadViewStateChange()}rebuildThreadState(J){this.threadStateSubject.next(jR({thread:J,viewState:this.threadViewStateSubject.getValue(),resolvedTokenUsage:Y7(J)}))}syncRetryCountdownTimer(){let J=this.activeError?.retryAt;if(J===void 0||J<=Date.now()){this.clearRetryCountdownTimer();return}if(this.retryCountdownTimer!==null)return;this.retryCountdownTimer=setInterval(()=>{let Z=this.activeError?.retryAt;if(Z===void 0){this.clearRetryCountdownTimer();return}if(this.updateThreadViewStateFromProvider(),Z<=Date.now())this.clearRetryCountdownTimer()},1000)}clearRetryCountdownTimer(){if(this.retryCountdownTimer===null)return;clearInterval(this.retryCountdownTimer),this.retryCountdownTimer=null}currentEphemeralError(){if(!this.activeError)return;let J=this.activeError.retryAt!==void 0?Math.max(0,Math.ceil((this.activeError.retryAt-Date.now())/1000)):void 0,Z=this.activeError.code!==void 0||this.activeError.attempt!==void 0?{code:this.activeError.code,attempt:this.activeError.attempt}:void 0;return{message:this.activeError.message,stack:this.activeError.stack,error:Z,retryCountdownSeconds:J}}}c4();E1();function Gb4(J){let Z=new V4(J.thread),Q=new V4(Uy(J.thread,"idle")),Y=new V4(new Map),X=new V4([]),K=new V4([]),V=(z)=>{let W={...Z.getValue()};if(!z||!z.text&&z.images.length===0)delete W.draft,delete W.autoSubmitDraft;else{let H=[];if(z.text)H.push({type:"text",text:z.text});if(z.images.length>0)H.push(...z.images);W.draft=H,W.autoSubmitDraft=!1}Z.next(W),Q.next(Uy(W,"idle"))};return{handle:Hy({thread$:Z,threadViewState$:Q,toolProgressByToolUseID$:Y,pendingApprovals$:X,pendingSkills$:K,getCurrentThread:()=>Z.getValue(),sendMessage:async(z)=>(await J.materialize()).sendMessage(z),restoreTo:async(z)=>(await J.materialize()).restoreTo(z),queueMessage:async(z)=>(await J.materialize()).queueMessage(z),discardQueuedMessages:async()=>{},interruptQueuedMessage:async()=>{},setTitle:async(z)=>(await J.materialize()).setTitle(z),setVisibility:async(z)=>(await J.materialize()).setVisibility(z),cancelTurn:async()=>{},cancelStreaming:async()=>{},retryTurn:async()=>{},dismissEphemeralError:()=>{},resolveApproval:async()=>{},addPendingSkill:(z)=>{K.next([...K.getValue(),z])},removePendingSkill:(z)=>{K.next(K.getValue().filter((q)=>q.name!==z))},clearPendingSkills:()=>{K.next([])},getDraft:async()=>cM3(Z.getValue()),setDraft:async(z)=>V(z),getFilesAffectedByTruncation:async()=>[],clearPendingNavigation:async()=>{},getGuidanceFiles:async()=>[]}),getThreadViewState:()=>Q.getValue(),dispose:async()=>{Z.complete(),Q.complete(),Y.complete(),X.complete(),K.complete()}}}function cM3(J){if(!J.draft)return null;let Z=zC(J.draft);if(!Z.text&&Z.images.length===0)return null;return Z}var lV0="Loading thread...",lM3="Importing thread";class Pa{deps;recentThreadIDsSubject=new V4([]);threadTitlesSubject=new V4({});activeThreadHandleSubject=new V4(null);allConnectedThreadActivityStatusesSubject=new V4({});initializationStatusSubject=new V4({pending:!1,message:lV0});threadHandleMap=new Map;pendingHandoffThreads=new Map;threadBackStack=[];threadForwardStack=[];isThreadActivationInProgress=!1;activeThreadContextID=null;handoffService;queueOnSubmitByDefault=!0;constructor(J){this.deps=J;this.handoffService=fY0({configService:this.deps.configService,onFollow:this.followHandoffIfSourceActive})}get recentThreadIDs$(){return this.recentThreadIDsSubject}get threadTitles$(){return this.threadTitlesSubject}get threadHandles$(){return this.activeThreadHandleSubject}get allConnectedThreadActivityStatuses$(){return this.allConnectedThreadActivityStatusesSubject}get initializationStatus$(){return this.initializationStatusSubject}get activeThreadHandle(){if(!this.activeThreadContextID)throw Error("No active thread context");let J=this.threadHandleMap.get(this.activeThreadContextID)??this.pendingHandoffThreads.get(this.activeThreadContextID)?.optimisticHandle.handle;if(!J)throw Error(`No thread handle for ${this.activeThreadContextID}`);return J}get activeProvider(){if(!this.activeThreadContextID)return;return this.threadHandleMap.get(this.activeThreadContextID)?.provider}hasPendingInitialization(){return this.initializationStatusSubject.getValue().pending}isDTWMode(){return!0}isThreadActorsMode(){return this.deps.useThreadActors??!1}getTransportConnectionState(){return this.activeProvider?.getConnectionState()??"disconnected"}getTransportConnectionRole(){return this.activeProvider?.getConnectionRole()??null}getCompactionStatus(){let J=this.activeProvider;if(!J)return;return{compactionState:J.getCompactionState()}}async createThread(J){await this.activateThreadWithNavigation(J,{recordNavigation:!0})}async switchThread(J){await this.activateThreadWithNavigation(J,{recordNavigation:!0})}canNavigateBack(){return this.threadBackStack.length>0}canNavigateForward(){return this.threadForwardStack.length>0}async navigateBack(){if(!this.canNavigateBack())return;let J=this.activeThreadContextID;if(!J)return;let Z=this.threadBackStack.pop();if(!Z)return;this.threadForwardStack.push(J);try{await this.activateThreadWithNavigation(Z,{recordNavigation:!1})}catch(Q){throw this.threadForwardStack.pop(),this.threadBackStack.push(Z),Q}}async navigateForward(){if(!this.canNavigateForward())return;let J=this.activeThreadContextID;if(!J)return;let Z=this.threadForwardStack.pop();if(!Z)return;this.threadBackStack.push(J);try{await this.activateThreadWithNavigation(Z,{recordNavigation:!1})}catch(Q){throw this.threadBackStack.pop(),this.threadForwardStack.push(Z),Q}}followHandoffIfSourceActive=async(J)=>{if(this.activeThreadContextID!==J.sourceThreadID)return;await this.switchThread(J.targetThreadID)};async createHandoff(J,Z){let Y=this.threadHandleMap.get(J)?.provider.getThread()??this.activeProvider?.getThread();if(!Y||Y.id!==J)throw Error("No thread available for handoff");let X=Y.env?.initial?.trees?.[0]?.repository?.url??(await this.deps.getThreadEnvironment()).trees?.[0]?.repository?.url,K=await this.handoffService.createHandoffDraft({parentThread:Y,goal:Z.goal,images:Z.images,signal:Z.signal});Z.signal?.throwIfAborted();let V=Z.agentMode??K.sourceAgentMode??Y.agentMode,G={threadID:K.parentThreadID,type:"handoff",...K.parentMessageIndex!==void 0?{messageIndex:K.parentMessageIndex}:{},comment:Z.goal},F=h8(),z=Date.now(),q=[{threadID:J,type:"handoff",role:"child",...K.parentMessageIndex!==void 0?{messageIndex:K.parentMessageIndex}:{},createdAt:z,comment:Z.goal}],W={id:F,created:Date.now(),v:0,messages:[],relationships:q,...V?{agentMode:V}:{},...K.content.length>0?{draft:K.content,autoSubmitDraft:!1}:{}},H=Gb4({thread:W,materialize:()=>this.materializePendingHandoffThread(F)});return this.pendingHandoffThreads.set(F,{agentMode:V??void 0,relationship:G,repositoryURL:X,threadRelationships:q,optimisticHandle:H,materializingPromise:null}),F}async dispose(){for(let J of this.threadHandleMap.values())await J.dispose();for(let J of this.pendingHandoffThreads.values())await J.optimisticHandle.dispose();this.threadHandleMap.clear(),this.pendingHandoffThreads.clear(),this.activeThreadHandleSubject.complete(),this.allConnectedThreadActivityStatusesSubject.complete(),this.initializationStatusSubject.complete(),this.threadTitlesSubject.complete(),this.recentThreadIDsSubject.complete()}async activateThread(J,Z){_.info("[dtw-thread-pool] activateThread:start",{requestedThreadID:J,hasExistingHandle:Boolean(J&&this.threadHandleMap.get(J))});let Q=J?this.threadHandleMap.get(J):void 0;if(Q){let X=Q.thread$.getValue().id;this.activeThreadContextID=X,this.activeThreadHandleSubject.next(Q),this.addToRecentThreads(X),this.syncAllConnectedThreadActivityStatuses(),_.info("[dtw-thread-pool] activateThread:reused",{activeThreadID:X,handleCount:this.threadHandleMap.size});return}let Y=J?this.pendingHandoffThreads.get(J):void 0;if(J&&Y){this.activeThreadContextID=J,this.activeThreadHandleSubject.next(Y.optimisticHandle.handle),this.syncAllConnectedThreadActivityStatuses(),_.info("[dtw-thread-pool] activateThread:optimistic",{activeThreadID:J,handleCount:this.threadHandleMap.size});return}this.isThreadActivationInProgress=!0,this.setInitializationStatus({pending:!0,message:lV0});try{let X=await this.createProvider(J);if(Z?.threadRelationships&&Z.threadRelationships.length>0)X.setRelationships(Z.threadRelationships);let K=cS({fileChangeTrackerStorage:this.deps.fileChangeTrackerStorage},this.deps.osFileSystem,X.threadId),V=new oe0(X,{configService:this.deps.configService,toolService:this.deps.toolService,skillService:this.deps.skillService,mcpService:this.deps.mcpService,clientID:this.deps.clientID,initialToolDiscovery:this.deps.initialToolDiscovery,fs:K,filesystem:this.deps.osFileSystem,threadService:this.deps.threadService,onThreadViewStateChange:()=>{this.syncAllConnectedThreadActivityStatuses()},handoffService:this.handoffService});this.threadHandleMap.set(X.threadId,V),V.startProviderSubscription((G)=>{this.applyProviderState(X.threadId,G)}),this.applyProviderState(X.threadId,X.getThread()),this.activeThreadContextID=X.threadId,this.activeThreadHandleSubject.next(V),this.addToRecentThreads(X.threadId),_.info("[dtw-thread-pool] activateThread:created",{activeThreadID:X.threadId,handleCount:this.threadHandleMap.size})}finally{this.isThreadActivationInProgress=!1,this.setInitializationStatus({pending:!1,message:lV0})}}async activateThreadWithNavigation(J,Z){let Q=this.activeThreadContextID;await this.activateThread(J);let Y=this.activeThreadContextID;if(Z.recordNavigation&&Q!==null&&Y!==null&&Q!==Y)this.recordNavigation(Q)}applyProviderState(J,Z){let Q=this.threadHandleMap.get(J);if(!Q)return;let Y=Q.resolveAuthoritativeThread(Z);Q.writeThread(Y);let X=this.threadTitlesSubject.getValue();if(X[J]!==Y.title)this.threadTitlesSubject.next({...X,[J]:Y.title});this.syncAllConnectedThreadActivityStatuses()}syncAllConnectedThreadActivityStatuses(){let J={};for(let[Z,Q]of this.threadHandleMap.entries())J[Z]=Q.getThreadViewState();for(let[Z,Q]of this.pendingHandoffThreads.entries())J[Z]=Q.optimisticHandle.getThreadViewState();this.allConnectedThreadActivityStatusesSubject.next(J)}addToRecentThreads(J){let Z=[...this.recentThreadIDsSubject.getValue()],Q=Z.indexOf(J);if(Q!==-1)Z.splice(Q,1);if(Z.unshift(J),Z.length>50)Z.pop();this.recentThreadIDsSubject.next(Z)}recordNavigation(J){this.threadBackStack.push(J),this.threadForwardStack=[]}async createProvider(J){let Z=J?void 0:(await this.deps.getThreadEnvironment()).trees?.[0]?.repository?.url,Q=J?void 0:"local-client";return KX0.create({ampURL:this.deps.ampURL,configService:this.deps.configService,connectOnCreate:Boolean(J),executorType:Q,onLegacyImportStateChange:(Y)=>{if(Y==="importing"){this.setInitializationStatus({pending:!0,message:lM3});return}if(this.isThreadActivationInProgress)this.setInitializationStatus({pending:!0,message:lV0})},repositoryURL:Z,threadService:this.deps.threadService,threadId:J,workerUrl:process.env.AMP_WORKER_URL,useThreadActors:this.deps.useThreadActors,connectionMode:"executor+observer"})}async materializePendingHandoffThread(J){let Z=this.pendingHandoffThreads.get(J);if(!Z)throw Error(`No pending handoff thread for ${J}`);if(!Z.materializingPromise){let K=(async()=>{let{threadId:V}=await CU(void 0,this.deps.configService,void 0,{repositoryURL:Z.repositoryURL,agentMode:Z.agentMode,relationship:Z.relationship,executorType:"local-client"});if(this.activeThreadContextID===J)await this.activateThread(V,{threadRelationships:Z.threadRelationships});return V})();Z.materializingPromise=K,K.catch(()=>{let V=this.pendingHandoffThreads.get(J);if(V?.materializingPromise===K)V.materializingPromise=null})}let Q=await Z.materializingPromise,Y=this.threadHandleMap.get(Q);if(!Y)await this.activateThread(Q,{threadRelationships:Z.threadRelationships}),Y=this.threadHandleMap.get(Q);if(!Y)throw Error(`No DTW thread handle for ${Q}`);let X=this.pendingHandoffThreads.get(J);if(X)this.pendingHandoffThreads.delete(J),await X.optimisticHandle.dispose(),this.syncAllConnectedThreadActivityStatuses();return Y}setInitializationStatus(J){let Z=this.initializationStatusSubject.getValue();if(Z.pending===J.pending&&Z.message===J.message)return;this.initializationStatusSubject.next(J)}}io0();import{randomBytes as oM3}from"node:crypto";import{readFile as rM3}from"node:fs/promises";import sM3 from"node:readline";import{setTimeout as tM3}from"node:timers/promises";S3();p_();c4();ZU();E1();F3();c4();ZU();E1();class Fb4{stateSubject;constructor(J){this.stateSubject=new V4(J)}get state$(){return this.stateSubject}get state(){return this.stateSubject.getValue()}update(J){this.stateSubject.next(J)}}function iM3(J){let Z=new Map;for(let Q of J.messages){if(Q.role!=="user")continue;for(let Y of Q.content){if(Y.type!=="tool_result")continue;if(!("progress"in Y.run))continue;let X=Y.run.progress;if(typeof X==="string"){Z.set(Y.toolUseID,{status:Y.run.status,content:X});continue}if(X&&typeof X==="object"&&"output"in X&&typeof X.output==="string")Z.set(Y.toolUseID,{status:Y.run.status,content:X.output})}}return Z}function nM3(J){if(!J.draft)return null;let Z=zC(J.draft);if(!Z.text&&Z.images.length===0)return null;return Z}function aM3(J){if(!J||!J.text&&J.images.length===0)return"";let Z=[];if(J.text)Z.push({type:"text",text:J.text});if(J.images.length>0)Z.push(...J.images);return Z}async function re0(J,Z){let{thread:Q,threadMeta:Y}=Z,X=Q?.id??Z.threadID??h8(),K=b9.get(X),V=K?.thread??await J.threadService.get(X);if(Q&&!V){let F=await J.threadService.exclusiveSyncReadWriter(X);F.write(Q),await F.asyncDispose(),V=Q}let G=K??await b9.getOrCreateForThread(J,X);if(Z.agentMode&&!V?.agentMode&&(!V||F8(V)===0))await G.handle({type:"agent-mode",mode:Z.agentMode});if(Y&&Q)await J.threadService.updateThreadMeta(X,Y);if(Y&&!Q){let F=J.threadService.observe(X).subscribe((z)=>{if(z.messages.length===0)return;F.unsubscribe(),J.threadService.updateThreadMeta(X,Y).catch(()=>{return})})}if(Z.onFirstAssistantMessage){let F=J.threadService.observe(X).subscribe(async(z)=>{if(P7(z,"assistant"))await Z.onFirstAssistantMessage?.(X),F.unsubscribe()})}return await G.resume(),G}async function zb4(J,Z,Q){await J.validateThreadOwnership?.(Z,Q);let Y=await J.threadService.get(Z)??void 0;return re0(J.workerDeps,{threadID:Z,threadMeta:J.switchThreadVisibility?oG(J.switchThreadVisibility):void 0,agentMode:Y?void 0:J.switchThreadAgentMode,thread:Y,onFirstAssistantMessage:J.onFirstAssistantMessage})}async function qb4(J,Z,Q){let Y=Z?await zb4(J,Z,{nonBlockingOwnershipCheck:Q?.nonBlockingOwnershipCheck??!1}):await J.createThread();return new iV0(J,Y)}class iV0{deps;queueOnSubmitByDefault=!1;restoreTo=this.truncateThread.bind(this);stateTracker;activeThreadHandleSubject;workersByThreadID=new Map;currentWorker;activeThreadHandleValue;activeThreadHandleThreadID;latestStatus={state:"initial"};threadSubscription=null;statusSubscription=null;pendingSkillsSubscription=null;recentThreadIDsSubject=new V4([]);pendingApprovalsSubject=new V4([]);pendingSkillsSubject=new V4([]);threadViewStatesSubject=new V4({});threadTitlesSubject=new V4({});legacyHandoffNavigationSubject=new H4;pendingNavigationInFlightThreadID=null;threadBackStack=[];threadForwardStack=[];subscriptions=[];workerSubscription=null;disposing=!1;constructor(J,Z){this.deps=J;this.currentWorker=Z,this.stateTracker=new Fb4(this.buildPoolState(Z.thread,this.recentThreadIDsSubject.getValue())),this.workersByThreadID.set(Z.thread.id,Z),this.activeThreadHandleValue=this.createHandle(Z.thread.id,Z),this.activeThreadHandleThreadID=Z.thread.id,this.activeThreadHandleSubject=new V4(this.activeThreadHandleValue),this.refreshDerivedState(Z.thread),this.addToRecentThreads(Z.thread.id),this.subscribeToWorker(Z),this.subscribeToPendingApprovals(),this.subscribeToGlobalWorkerStates(),this.subscribeToWorkerTitles()}get threadHandles$(){return this.activeThreadHandleSubject}get threadState$(){return this.stateTracker.state$.pipe(w1((J)=>J.threadState))}get currentThreadState(){return this.stateTracker.state.threadState}get currentThread(){return this.stateTracker.state.currentThread}get currentThreadID(){return this.stateTracker.state.currentThreadID}get recentThreadIDs$(){return this.recentThreadIDsSubject}get recentThreadIDs(){return this.stateTracker.state.recentThreadIDs}get threadTitles$(){return this.threadTitlesSubject}get legacyHandoffNavigation$(){return this.legacyHandoffNavigationSubject}get allConnectedThreadActivityStatuses$(){return this.threadViewStatesSubject}get pendingApprovals$(){return this.pendingApprovalsSubject}get pendingSkills$(){return this.pendingSkillsSubject}getWorkerForExecuteMode(){return this.currentWorker}async createThread(){let J=await this.deps.createThread();this.switchToWorker(J,{recordNavigation:!0})}async switchThread(J){await this.switchToThreadByID(J,{recordNavigation:!0})}canNavigateBack(){return this.threadBackStack.length>0}canNavigateForward(){return this.threadForwardStack.length>0}async navigateBack(){if(!this.canNavigateBack())return;let J=this.currentWorker.thread.id,Z=this.threadBackStack.pop();if(!Z)return;this.threadForwardStack.push(J);try{await this.switchToThreadByID(Z,{recordNavigation:!1})}catch(Q){throw this.threadForwardStack.pop(),this.threadBackStack.push(Z),Q}}async navigateForward(){if(!this.canNavigateForward())return;let J=this.currentWorker.thread.id,Z=this.threadForwardStack.pop();if(!Z)return;this.threadBackStack.push(J);try{await this.switchToThreadByID(Z,{recordNavigation:!1})}catch(Q){throw this.threadBackStack.pop(),this.threadForwardStack.push(Z),Q}}async sendMessage(J){await this.currentWorker.handle({type:"user:message",index:J.editIndex,message:{content:J.content,agentMode:J.agentMode}}),this.maybeMarkLastUserMessageInterrupted(this.currentWorker)}async truncateThread(J){await this.currentWorker.handle({type:"thread:truncate",fromIndex:J})}createHandle(J,Z){let Q=(X)=>{if(this.currentThreadID!==J)throw Error(`ThreadHandle.${X} called for inactive thread ${J}. Current thread is ${this.currentThreadID}.`)},Y=async(X)=>{await Z.handle({type:"thread:truncate",fromIndex:X})};return Hy({thread$:this.deps.threadService.observe(J),threadViewState$:this.threadViewStatesSubject.pipe(w1((X)=>X[J]??{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}})),inferenceErrors$:Z.status.pipe(w1((X)=>X.state==="active"?X.ephemeralError:void 0),f5((X)=>X!==void 0)),toolProgressByToolUseID$:this.deps.threadService.observe(J).pipe(w1((X)=>iM3(X))),pendingApprovals$:this.pendingApprovals$,pendingSkills$:this.pendingSkills$,getCurrentThread:()=>Z.thread,getResolvedTokenUsage:()=>Y7(Z.thread),sendMessage:async(X)=>{Q("sendMessage"),await Z.handle({type:"user:message",index:X.editIndex,message:{content:X.content,agentMode:X.agentMode}}),this.maybeMarkLastUserMessageInterrupted(Z)},restoreTo:async(X)=>{Q("restoreTo"),await Y(X)},queueMessage:async(X)=>{Q("queueMessage"),await Z.handle({type:"user:message-queue:enqueue",message:{content:X}})},discardQueuedMessages:async()=>{Q("discardQueuedMessages"),await Z.handle({type:"user:message-queue:discard"})},setTitle:async(X)=>{Q("setTitle"),await Z.handle({type:"title",value:X}),await this.deps.threadService.flushVersion(J,Z.thread.v)},setVisibility:async(X)=>{Q("setVisibility"),await this.deps.workerDeps.threadService.updateThreadMeta(J,oG(X))},cancelTurn:async()=>{Q("cancelTurn"),await this.maybeCancelActiveTurn(Z)},cancelStreaming:async()=>{Q("cancelStreaming"),await this.maybeCancelActiveTurn(Z)},retryTurn:async()=>{Q("retryTurn"),await Z.retry()},dismissEphemeralError:()=>{Q("dismissEphemeralError"),Z.dismissEphemeralError()},preExecuteMode:async()=>{Q("preExecuteMode"),Z.continueInferenceAfterRejection(!0)},postExecuteMode:async()=>{Q("postExecuteMode");let X=Z.thread.v;await this.deps.threadService.flushVersion(J,X)},setTestEphemeralError:(X)=>{Q("setTestEphemeralError"),Z.setTestEphemeralError(X)},resolveApproval:async(X,K,V)=>{Q("resolveApproval"),this.deps.workerDeps.toolService.resolveApproval(X,K,V)},addPendingSkill:(X)=>{Q("addPendingSkill"),Z.addPendingSkill(X)},removePendingSkill:(X)=>{Q("removePendingSkill"),Z.removePendingSkill(X)},clearPendingSkills:()=>{Q("clearPendingSkills"),Z.clearPendingSkills()},getDraft:async()=>{return Q("getDraft"),nM3(Z.thread)},setDraft:async(X)=>{Q("setDraft"),await Z.handle({type:"draft",content:aM3(X)})},getFilesAffectedByTruncation:async(X)=>{return Q("getFilesAffectedByTruncation"),Z.getFilesAffectedByTruncation(X)},clearPendingNavigation:async()=>{Q("clearPendingNavigation"),await Z.handle({type:"clearPendingNavigation"})},getGuidanceFiles:async(X)=>{let K=this.stateTracker.state.currentThread;if(!K)return[];return(await Wz({filesystem:this.getFilesystemReader(),configService:this.deps.workerDeps.configService,threadService:this.deps.threadService},K,X)).map((G)=>({uri:G.uri,type:G.type}))},invokeBashTool:(X,K)=>{Q("invokeBashTool");let V=Z.invokeBashTool(X,K.abortController.signal,K.hidden);return new k0((G)=>{let F=!1,z=V.subscribe({next:(q)=>G.next(q),error:(q)=>{F=!0,G.error(q)},complete:()=>{F=!0,G.complete()}});return()=>{if(!F)K.abortController.abort();z.unsubscribe()}})}})}maybeMarkLastUserMessageInterrupted(J){let Z=this.stateTracker.state.currentThread;if(!Z)return;if(this.latestStatus.state!=="active")return;let Q=Z.messages.findLast((K)=>K?.role==="assistant"),Y=Q?.state.type==="streaming";if(!(this.latestStatus.inferenceState==="running"||Y))return;if(Y){if(Q.content.some((V)=>V.type==="thinking"&&YX(V)))return}for(let K=Z.messages.length-1;K>=0;K--){let V=Z.messages[K];if(V?.role==="user"&&!V.interrupted){J.handle({type:"user:message:interrupt",messageIndex:K});let G=[...Z.messages];G[K]={...V,interrupted:!0};let F={...Z,messages:G};this.refreshDerivedState(F),this.updateInterruptedMessage(F,K);break}}}updateInterruptedMessage(J,Z){let Q=J.messages[Z];if(!Q||Q.role!=="user"||Q.interrupted)return;let Y=J.messages.map((X,K)=>{if(K!==Z)return X;return{...X,interrupted:!0}});this.refreshDerivedState({...J,messages:Y})}async queueMessage(J){await this.currentWorker.handle({type:"user:message-queue:enqueue",message:{content:J}})}async discardQueuedMessages(){await this.currentWorker.handle({type:"user:message-queue:discard"})}setTitle=async(J)=>{await this.currentWorker.handle({type:"title",value:J}),await this.deps.threadService.flushVersion(this.currentThreadID,this.currentWorker.thread.v)};setVisibility=async(J)=>{await this.deps.workerDeps.threadService.updateThreadMeta(this.currentThreadID,oG(J))};async cancelTurn(){await this.maybeCancelActiveTurn(this.currentWorker)}async cancelStreaming(){await this.maybeCancelActiveTurn(this.currentWorker)}async maybeCancelActiveTurn(J){let Z=this.stateTracker.state.currentThread;if(!Z)return;if(this.latestStatus.state!=="active")return;let Y=Z.messages.findLast((V)=>V?.role==="assistant")?.state.type==="streaming",X=this.hasActiveTools(Z);if(!(this.latestStatus.inferenceState==="running"||this.latestStatus.inferenceState==="retrying"||Boolean(Y)||X))return;this.maybeMarkLastUserMessageInterrupted(J),await J.cancel()}hasActiveTools(J){for(let Z of J.messages){if(Z?.role!=="user")continue;for(let Q of Z.content){if(Q.type!=="tool_result")continue;if(Q.run.status==="in-progress"||Q.run.status==="queued")return!0}}return!1}async retryTurn(){await this.currentWorker.retry()}dismissEphemeralError(){this.currentWorker.dismissEphemeralError()}async resolveApproval(J,Z,Q){this.deps.workerDeps.toolService.resolveApproval(J,Z,Q)}addPendingSkill(J){this.currentWorker.addPendingSkill(J)}removePendingSkill(J){this.currentWorker.removePendingSkill(J)}clearPendingSkills(){this.currentWorker.clearPendingSkills()}async getFilesAffectedByTruncation(J){return this.currentWorker.getFilesAffectedByTruncation(J)}invokeBashTool(J,Z){let Q=this.currentWorker.invokeBashTool(J,Z.abortController.signal,Z.hidden);return new k0((Y)=>{let X=!1,K=Q.subscribe({next:(V)=>Y.next(V),error:(V)=>{X=!0,Y.error(V)},complete:()=>{X=!0,Y.complete()}});return()=>{if(!X)Z.abortController.abort();K.unsubscribe()}})}async createHandoff(J,Z){let Q={toolService:this.deps.workerDeps.toolService,configService:this.deps.workerDeps.configService,skillService:this.deps.workerDeps.skillService,getThreadEnvironment:this.deps.workerDeps.getThreadEnvironment,filesystem:this.getFilesystemReader(),threadService:this.deps.workerDeps.threadService};return(await b9.handoff(this.deps.workerDeps,{threadID:J,goal:Z.goal,images:Z.images,mode:"draft",navigate:!1,agentMode:Z.agentMode??void 0,queuedMessages:Z.queuedMessages,clearQueuedMessages:!0,blockIndex:0,buildSystemPromptDeps:Q,signal:Z.signal,filesystem:this.getFilesystemReader()})).threadID}async clearPendingNavigation(){await this.currentWorker.handle({type:"clearPendingNavigation"})}getFilesystemReader(){return this.deps.workerDeps.osFileSystem}setTestEphemeralError(J){this.currentWorker.setTestEphemeralError(J)}setTestRetryCountdown(J){let Z=Math.max(0,Math.ceil((J.retryAt-Date.now())/1000));this.currentWorker.setTestEphemeralError(Object.assign(Error(J.message),{retryCountdownSeconds:Z}))}async getThreadEnvironment(){return await this.deps.workerDeps.getThreadEnvironment()}async dispose(){if(this.disposing)return;this.disposing=!0,this.cleanupSubscriptions(),await Promise.all(Array.from(this.workersByThreadID.values()).map((J)=>J.asyncDispose())),this.workersByThreadID.clear(),this.pendingApprovalsSubject.complete(),this.pendingSkillsSubject.complete(),this.threadViewStatesSubject.complete(),this.threadTitlesSubject.complete(),this.legacyHandoffNavigationSubject.complete(),this.recentThreadIDsSubject.complete(),this.activeThreadHandleSubject.complete(),this.disposing=!1}async deleteThread(J){if(this.currentWorker.thread.id===J)return;this.workersByThreadID.delete(J),await b9.dispose(J),await this.deps.threadService.delete(J)}subscribeToWorker(J){this.threadSubscription?.unsubscribe(),this.statusSubscription?.unsubscribe(),this.pendingSkillsSubscription?.unsubscribe(),this.threadSubscription=this.deps.threadService.observe(J.thread.id).subscribe((Z)=>{this.refreshDerivedState(Z)}),this.statusSubscription=J.status.subscribe((Z)=>{this.latestStatus=Z,this.updateThreadState(this.stateTracker.state.currentThread)}),this.pendingSkillsSubscription=J.pendingSkills.subscribe((Z)=>{this.pendingSkillsSubject.next(Z)})}subscribeToPendingApprovals(){let J=this.deps.workerDeps.toolService.pendingApprovals$.subscribe((Z)=>{let Q=this.stateTracker.state.currentThreadID,Y=Z.filter((X)=>X.threadId===Q||X.mainThreadId===Q);this.pendingApprovalsSubject.next(Y)});this.subscriptions.push(J)}subscribeToGlobalWorkerStates(){let J=b9.statuses.subscribe((Z)=>{this.threadViewStatesSubject.next(Z)});this.subscriptions.push(J)}subscribeToWorkerTitles(){let J=async(Z)=>{let Q={};await Promise.all(Array.from(Z.keys()).map(async(Y)=>{Q[Y]=await this.deps.threadService.getPrimitiveProperty(Y,"title")??void 0})),this.threadTitlesSubject.next(Q)};this.workerSubscription=b9.workers.subscribe((Z)=>{J(Z)})}setCurrentWorker(J){if(this.workersByThreadID.set(J.thread.id,J),J.thread.id!==this.currentWorker.thread.id)this.addToRecentThreads(J.thread.id);this.currentWorker=J,this.latestStatus={state:"initial"},this.refreshDerivedState(J.thread),this.subscribeToWorker(J)}refreshDerivedState(J){let Z=this.buildPoolState(J,this.recentThreadIDsSubject.getValue());this.threadTitlesSubject.next({...this.threadTitlesSubject.getValue(),[J.id]:J.title??void 0}),this.stateTracker.update(Z),this.maybeEmitLegacyHandoffNavigation(J),this.emitActiveThreadHandleIfNeeded()}maybeEmitLegacyHandoffNavigation(J){let Z=J.pendingNavigation;if(!Z||J.id!==this.currentThreadID)return;if(this.pendingNavigationInFlightThreadID===Z)return;this.pendingNavigationInFlightThreadID=Z,this.legacyHandoffNavigationSubject.next(Z),this.currentWorker.handle({type:"clearPendingNavigation"}).catch(()=>{return}).finally(()=>{if(this.pendingNavigationInFlightThreadID===Z)this.pendingNavigationInFlightThreadID=null})}buildPoolState(J,Z){let Q=wS(J,this.latestStatus);return{threadState:jR({thread:J,viewState:Q,resolvedTokenUsage:Y7(J)}),currentThread:J,currentThreadID:J.id,recentThreadIDs:Z}}updateThreadState(J){this.refreshDerivedState(J)}addToRecentThreads(J){let Z=[...this.recentThreadIDsSubject.getValue()],Q=Z.indexOf(J);if(Q!==-1)Z.splice(Q,1);if(Z.unshift(J),Z.length>50)Z.pop();this.recentThreadIDsSubject.next(Z),this.stateTracker.update({...this.stateTracker.state,recentThreadIDs:Z})}switchToWorker(J,Z){let Q=this.currentWorker.thread.id;if(this.workersByThreadID.set(J.thread.id,J),this.setCurrentWorker(J),Z.recordNavigation&&J.thread.id!==Q)this.recordNavigation(Q)}async switchToThreadByID(J,Z){let Q=this.workersByThreadID.get(J)??await zb4(this.deps,J);this.switchToWorker(Q,Z)}recordNavigation(J){this.threadBackStack.push(J),this.threadForwardStack=[]}cleanupSubscriptions(){this.threadSubscription?.unsubscribe(),this.statusSubscription?.unsubscribe(),this.pendingSkillsSubscription?.unsubscribe(),this.workerSubscription?.unsubscribe(),this.threadSubscription=null,this.statusSubscription=null,this.pendingSkillsSubscription=null,this.workerSubscription=null;for(let J of this.subscriptions)J.unsubscribe();this.subscriptions=[]}emitActiveThreadHandleIfNeeded(){if(this.activeThreadHandleThreadID!==this.currentThreadID)this.activeThreadHandleValue=this.createHandle(this.currentThreadID,this.currentWorker),this.activeThreadHandleThreadID=this.currentThreadID;this.activeThreadHandleSubject.next(this.activeThreadHandleValue)}}function b4(J,Z){let Q=Z?` ${JSON.stringify(Z)}`:"";process.stderr.write(`[thread-pool] ${J}${Q}
|
|
7134
|
+
`).trim()}function Qb4(J){let Z=mU(J),Q=mV0(Z);return Zb4(Z,Q.lineIndex)}class pU extends c0{thinkingBlock;expanded;onToggle;isStreaming;isCancelled;constructor({key:J,thinkingBlock:Z,expanded:Q,onToggle:Y,isStreaming:X=!1,isCancelled:K=!1}){super(J?{key:J}:{});this.thinkingBlock=Z,this.expanded=Q,this.onToggle=Y,this.isStreaming=X,this.isCancelled=K}createState(){return new Yb4}}class Yb4 extends m0{_animationTimer;_spinner=new O5;_localExpanded=!1;get isComplete(){return!this.widget.isStreaming}get expanded(){return this._localExpanded}initState(){if(super.initState(),this._localExpanded=this.widget.expanded??!1,!this.isComplete)this._startAnimation()}didUpdateWidget(J){if(super.didUpdateWidget(J),J.isStreaming&&!this.widget.isStreaming)this._stopAnimation();else if(!J.isStreaming&&this.widget.isStreaming)this._startAnimation();if(J.thinkingBlock.thinking!==this.widget.thinkingBlock.thinking)this.setState(()=>{});if(this.widget.expanded!==void 0&&this.widget.expanded!==J.expanded)this._localExpanded=this.widget.expanded}dispose(){this._stopAnimation(),super.dispose()}_startAnimation(){this._animationTimer=setInterval(()=>{this.setState(()=>{this._spinner.step()})},200)}_stopAnimation(){if(this._animationTimer)clearInterval(this._animationTimer),this._animationTimer=void 0}build(J){let Q=b1.of(J).colorScheme,Y=this.widget.isCancelled,X,K;if(Y)X=Q.warning,K="";else if(this.isComplete)X=Q.success,K="✓ ";else X=Q.accent,K=`${this._spinner.toBraille()} `;let V=mU(this.widget.thinkingBlock.thinking),G=mV0(V),F=Zb4(V,G.lineIndex),z=F.trim().length>0,q=z?new J0({text:new C(this.expanded?"▼":"▶",new g({color:Q.foreground,dim:!0}))}):null,W=Y?Q.warning:Q.foreground,H=new g({color:Y?X:Q.foreground,dim:!Y}),U=[new C(K,H),new C(G.header??"Thinking",new g({color:W,dim:!Y}))];if(Y)U.push(new C(" (interrupted)",new g({color:Q.warning,italic:!0})));let D=[new J0({text:new C("",void 0,U)})];if(q)D.push(new R0({width:1}),q);let B=new D1({mainAxisSize:"min",children:D}),N={...ev(J),text:new g({color:Q.foreground,dim:!0,italic:!0}),inlineCode:new g({color:Q.foreground,dim:!0,italic:!0,bold:!0}),codeBlock:new g({color:Q.foreground,dim:!0,italic:!0}),link:new g({color:Q.foreground,dim:!0,italic:!0,underline:!0})},w=()=>{if(this.isComplete&&!this.expanded)return;let I=O.map((S)=>{let P=[];if(P.push(new J0({text:new C(S.header,new g({color:Q.foreground,dim:!0,bold:!0}))})),this.expanded)P.push(new l0({padding:C0.vertical(1),child:new h5({markdown:S.content,styleScheme:N})}));return new b0({crossAxisAlignment:"start",children:P})});return new l0({padding:C0.only({left:2}),child:new oK({children:I})})},L=()=>{if(!this.expanded)return;return new l0({padding:C0.only({left:2}),child:new h5({markdown:F,styleScheme:N})})},O=VM3(F),M=O.length>0&&!!O[0]?.header?w():L(),j=[z?new Y4({onClick:this._handleHeaderClick.bind(this),cursor:"pointer",child:new b0({crossAxisAlignment:"start",children:[B]})}):new b0({crossAxisAlignment:"start",children:[B]})];if(M)j.push(M);return new b0({mainAxisSize:"min",crossAxisAlignment:"start",children:j})}_handleHeaderClick(J){let Z=!this.expanded;this.setState(()=>{this._localExpanded=Z}),this.widget.onToggle?.(Z)}}function zL(){return{viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},subagentContentByParentID:{},items:[],todosList:[],mainThread:null}}function jR(J){let{thread:Z,viewState:Q,resolvedTokenUsage:Y}=J;if(!Z)return zL();let{items:X}=pV0(Z),K=WC({messages:Z.messages}),V=Array.isArray(K)?K:[];return{viewState:Q,subagentContentByParentID:UM3(X,Z),items:X,todosList:V,mainThread:Z,resolvedTokenUsage:Y??Y7(Z)}}function GM3(J){return J===D9||J===w3||J===R7||J===b8||J===KC}function FM3(J){return J.content.filter((Z)=>Z.type==="text")}function zM3(J){return J.type==="text"&&J.text.trim().length>0||J.type==="thinking"&&YX(J)}function qM3(J){if(J.meta?.openAIResponsePhase==="commentary")return;switch(J.state.type){case"error":return;case"cancelled":{let Z=FM3(J);if(r8(Z).trim().length===0)return;return{...J,content:Z}}case"streaming":case"complete":{let Z=J.content.filter(zM3);if(Z.length===0)return;return{...J,content:Z}}}}function WM3(J){let Z;for(let Q of J){if(Q.type!=="message"||Q.message.role!=="assistant")continue;let Y=qM3(Q.message);if(!Y)continue;Z=Y}return Z}function HM3(J){if(typeof J==="object"&&J!==null&&!Array.isArray(J))return J;return{}}function UM3(J,Z,Q){let Y=new Map;for(let G of J)if(G.type==="toolResult"&&GM3(G.toolUse.name))Y.set(G.toolUse.id,G.toolResult.run);let X=(G,F)=>{let z=Y.get(G);if(!z||z.status!=="cancelled"||g8(F.status))return F;return{status:"cancelled",reason:"Parent subagent was cancelled"}},K=Array.from(Y.entries()),V={};for(let[G,F]of K){let z=[],q;if(F.status==="in-progress"||F.status==="done"||F.status==="error"||F.status==="cancelled")q=F.progress;if(Array.isArray(q)){let W=0;for(let H of q)if(H.tool_uses)for(let U of H.tool_uses){let D=DM3(U,G,W);if(!U.id||U.id.length===0)W++;let B=BM3(U),N=U.normalized_name??U.tool_name,w=HM3(U.input),L=Q?.get(D);z.push({toolUse:ZB(N,w,D),toolRun:X(G,B),toolProgress:L})}}V[G]={tools:z}}if(Z){let G=new Map;for(let F of Z.messages){let z=F.parentToolUseId;if(!z)continue;let q=G.get(z)??[];q.push(F),G.set(z,q)}for(let[F,z]of G){let{items:q}=pV0({id:Z.id,messages:z},{includeSubagentMessages:!0}),W=q.filter((D)=>D.type==="toolResult").map((D)=>({toolUse:D.toolUse,toolRun:X(F,D.toolResult.run),toolProgress:Q?.get(D.toolUse.id)})),H=WM3(q),U=V[F]??{tools:[]};V[F]={tools:W.length>0?W:U.tools,...H?{terminalAssistantMessage:H}:{}}}}return V}function DM3(J,Z,Q){if(typeof J.id==="string"&&J.id.length>0)return J.id;return`${Z}:progress:${Q}`}function BM3(J){if(J.status==="done"&&J.result!==void 0)return{status:"done",result:J.result};if(J.status==="error")return{status:"error",error:{message:typeof J.error==="string"&&J.error.length>0?J.error:"Subagent tool failed"}};return{status:J.status}}function pV0(J,Z){let Q=[],Y=new Set;if(Z?.includeSubagentMessages)for(let[V]of J.messages.entries())Y.add(V);else for(let[V,G]of J.messages.entries())if(!G.parentToolUseId)Y.add(V);let X=new Map,K=new Set;for(let[V,G]of J.messages.entries()){if(!Y.has(V))continue;let F=`${G.role}-${V}`;switch(G.role){case"assistant":{let z=G.state.type==="streaming";for(let W of G.content)if(W.type==="tool_use"){if(X.set(W.id,W),z)K.add(W.id)}if(G.content.some((W)=>W.type==="text"&&W.text.trim()||W.type==="thinking"&&YX(W)))Q.push({type:"message",id:F,message:G});for(let W of G.content){if(W.type!=="tool_use")continue;let H=!1;for(let U=V+1;U<J.messages.length;U++){if(!Y.has(U))continue;let D=J.messages[U];if(!D)continue;for(let B of D.content)if(B.type==="tool_result"&&B.toolUseID===W.id){H=!0;break}if(H)break}if(H)continue;Q.push({type:"toolResult",id:W.id,toolUse:W,toolResult:{type:"tool_result",toolUseID:W.id,run:{status:"in-progress"}}})}break}case"info":{if(G.content.some((q)=>q.type==="manual_bash_invocation"||q.type==="summary"&&q.summary.type==="message"))Q.push({type:"message",id:F,message:G});break}case"user":{let z=G.content.some((q)=>q.type==="text"&&q.text.trim()||q.type==="image");for(let q of G.content)if(q.type==="tool_result"){let W=X.get(q.toolUseID)??iJ(J,q.toolUseID);if(!W)throw Error(`(bug) tool use ${q.toolUseID} not found`);Q.push({type:"toolResult",id:q.toolUseID,toolUse:W,toolResult:q})}if(z)Q.push({type:"message",id:F,message:G});break}}}return{items:Q}}function Hy(J){let Z=J.toolProgressByToolUseID$.pipe(w1(hV0)),Q=()=>J.getCurrentThread?.(),Y=()=>Q()?.title,X=()=>Q()?.agentMode,K=()=>Q()?.messages??[],V=()=>Q()?.queuedMessages??[],G=()=>Q()?.env?.initial.trees?.[0]?.uri,F=()=>{let U=Q();if(!U?.autoSubmitDraft)return!1;return F8({messages:U.messages})===0},z=()=>{let U=Q();if(!U)return;if(F8({messages:U.messages})>0)return;return P10(U,"handoff")?.threadID},q=()=>F8({messages:K()})===0,W=()=>{let U=K().at(-1);return U?.role==="assistant"&&U.state.type==="streaming"},H=G5(J.thread$,J.threadViewState$).pipe(w1(([U,D])=>jR({thread:U,viewState:D,resolvedTokenUsage:J.getResolvedTokenUsage?.()})));return{get thread$(){return J.thread$},get threadState$(){return H},get threadViewState$(){return J.threadViewState$},get inferenceErrors$(){return J.inferenceErrors$},get toolProgressByToolUseID$(){return Z},get pendingApprovals$(){return J.pendingApprovals$},get pendingSkills$(){return J.pendingSkills$},get getCurrentThread(){return J.getCurrentThread},get getResolvedTokenUsage(){return J.getResolvedTokenUsage},getThreadID(){return Q()?.id},getThreadTitle(){return Y()},getAgentMode(){return X()},getMessages(){return K()},getQueuedMessages(){return V()},getInitialTreeURI(){return G()},shouldAutoSubmitDraft(){return F()},getEmptyHandoffParentThreadID(){return z()},isThreadEmpty(){return q()},isStreaming(){return W()},sendMessage:J.sendMessage,restoreTo:J.restoreTo,queueMessage:J.queueMessage,discardQueuedMessages:J.discardQueuedMessages,interruptQueuedMessage:J.interruptQueuedMessage,setTitle:J.setTitle,setVisibility:J.setVisibility,cancelTurn:J.cancelTurn,cancelStreaming:J.cancelStreaming,retryTurn:J.retryTurn,dismissEphemeralError:J.dismissEphemeralError,preExecuteMode:J.preExecuteMode,postExecuteMode:J.postExecuteMode,setTestEphemeralError:J.setTestEphemeralError,resolveApproval:J.resolveApproval,addPendingSkill:J.addPendingSkill,removePendingSkill:J.removePendingSkill,clearPendingSkills:J.clearPendingSkills,getDraft:J.getDraft,setDraft:J.setDraft,getFilesAffectedByTruncation:J.getFilesAffectedByTruncation,clearPendingNavigation:J.clearPendingNavigation,getGuidanceFiles:J.getGuidanceFiles,invokeBashTool:J.invokeBashTool}}var Xb4="Loading thread...";function NM3(J){return{id:J,created:Date.now(),v:0,messages:[]}}class ie0{placeholderThreadID;recentThreadIDsSubject=new V4([]);threadTitlesSubject=new V4({});threadHandlesSubject;allConnectedThreadActivityStatusesSubject=new V4({});legacyHandoffNavigationSubject=new H4;initializationStatusSubject=new V4({pending:!0,message:Xb4});pendingApprovalsSubject=new V4([]);pendingSkillsSubject=new V4([]);attachedPool=null;attachedPoolSubscriptions=[];attached=!1;readyPromise;readyResolve=null;readyReject=null;constructor(J=h8()){this.placeholderThreadID=J;let Z=new V4(NM3(this.placeholderThreadID)),Q=new V4(new Map),Y=new V4(wS(Z.getValue(),{state:"active",inferenceState:"idle",fileChanges:{files:[]}}));this.threadHandlesSubject=new V4(Hy({thread$:Z,threadViewState$:Y,toolProgressByToolUseID$:Q,pendingApprovals$:this.pendingApprovalsSubject,pendingSkills$:this.pendingSkillsSubject,getCurrentThread:()=>Z.getValue(),sendMessage:async(X)=>(await this.waitForActiveHandle()).sendMessage(X),restoreTo:async(X)=>(await this.waitForActiveHandle()).restoreTo(X),queueMessage:async(X)=>(await this.waitForActiveHandle()).queueMessage(X),discardQueuedMessages:async()=>(await this.waitForActiveHandle()).discardQueuedMessages(),setTitle:async(X)=>(await this.waitForActiveHandle()).setTitle(X),setVisibility:async(X)=>(await this.waitForActiveHandle()).setVisibility(X),cancelTurn:async()=>(await this.waitForActiveHandle()).cancelTurn(),cancelStreaming:async()=>(await this.waitForActiveHandle()).cancelStreaming(),retryTurn:async()=>(await this.waitForActiveHandle()).retryTurn(),dismissEphemeralError:()=>{},preExecuteMode:async()=>(await this.waitForActiveHandle()).preExecuteMode?.(),postExecuteMode:async()=>(await this.waitForActiveHandle()).postExecuteMode?.(),resolveApproval:async(X,K,V)=>(await this.waitForActiveHandle()).resolveApproval(X,K,V),addPendingSkill:()=>{},removePendingSkill:()=>{},clearPendingSkills:()=>{},getDraft:async()=>(await this.waitForActiveHandle()).getDraft(),setDraft:async(X)=>(await this.waitForActiveHandle()).setDraft(X),getFilesAffectedByTruncation:async(X)=>(await this.waitForActiveHandle()).getFilesAffectedByTruncation(X),clearPendingNavigation:async()=>(await this.waitForActiveHandle()).clearPendingNavigation(),getGuidanceFiles:async(X)=>(await this.waitForActiveHandle()).getGuidanceFiles(X)})),this.readyPromise=new Promise((X,K)=>{this.readyResolve=X,this.readyReject=K}),this.readyPromise.catch(()=>{return})}get recentThreadIDs$(){return this.recentThreadIDsSubject}get threadTitles$(){return this.threadTitlesSubject}get threadHandles$(){return this.threadHandlesSubject}get legacyHandoffNavigation$(){return this.legacyHandoffNavigationSubject}get allConnectedThreadActivityStatuses$(){return this.allConnectedThreadActivityStatusesSubject}get initializationStatus$(){return this.initializationStatusSubject}get queueOnSubmitByDefault(){return this.attachedPool?.queueOnSubmitByDefault??!1}hasPendingInitialization(){return this.attachedPool===null}isDTWMode(){return this.attachedPool?.isDTWMode?.()===!0}isThreadActorsMode(){return this.attachedPool?.isThreadActorsMode?.()===!0}getTransportConnectionState(){if(!this.attachedPool?.getTransportConnectionState)return;return this.attachedPool.getTransportConnectionState()}getTransportConnectionRole(){if(!this.attachedPool?.getTransportConnectionRole)return;return this.attachedPool.getTransportConnectionRole()}getCompactionStatus(){if(!this.attachedPool?.getCompactionStatus)return;return this.attachedPool.getCompactionStatus()}attach(J){if(this.attached)throw Error("DeferredThreadPool is already attached");this.attached=!0,this.attachedPool=J;let Z=null,Q=null;this.attachedPoolSubscriptions=[J.recentThreadIDs$.subscribe((Y)=>this.recentThreadIDsSubject.next(Y)),J.threadTitles$.subscribe((Y)=>this.threadTitlesSubject.next(Y)),J.allConnectedThreadActivityStatuses$.subscribe((Y)=>this.allConnectedThreadActivityStatusesSubject.next(Y)),...J.legacyHandoffNavigation$?[J.legacyHandoffNavigation$.subscribe((Y)=>{this.legacyHandoffNavigationSubject.next(Y)})]:[],...J.initializationStatus$?[J.initializationStatus$.subscribe((Y)=>this.initializationStatusSubject.next(Y))]:[(()=>{return this.initializationStatusSubject.next({pending:!1,message:Xb4}),{unsubscribe:()=>{}}})()],J.threadHandles$.subscribe((Y)=>{if(Y)Z?.unsubscribe(),Z=Y.pendingApprovals$.subscribe((X)=>this.pendingApprovalsSubject.next(X)),Q?.unsubscribe(),Q=Y.pendingSkills$.subscribe((X)=>this.pendingSkillsSubject.next(X)),this.threadHandlesSubject.next(Y)}),{unsubscribe:()=>{Z?.unsubscribe(),Q?.unsubscribe()}}],this.readyResolve?.(J),this.readyResolve=null,this.readyReject=null}setInitError(J){if(this.attached)return;this.readyReject?.(J),this.readyResolve=null,this.readyReject=null}async createThread(){return(await this.waitForAttach()).createThread()}async switchThread(J){return(await this.waitForAttach()).switchThread(J)}canNavigateBack(){return this.attachedPool?.canNavigateBack()??!1}canNavigateForward(){return this.attachedPool?.canNavigateForward()??!1}async navigateBack(){return(await this.waitForAttach()).navigateBack()}async navigateForward(){return(await this.waitForAttach()).navigateForward()}async createHandoff(J,Z){return(await this.waitForAttach()).createHandoff(J,Z)}async deleteThread(J){let Z=await this.waitForAttach();if(Z.deleteThread)await Z.deleteThread(J)}async dispose(){for(let J of this.attachedPoolSubscriptions)J.unsubscribe();if(this.attachedPoolSubscriptions=[],this.attachedPool)await this.attachedPool.dispose();this.recentThreadIDsSubject.complete(),this.threadTitlesSubject.complete(),this.threadHandlesSubject.complete(),this.allConnectedThreadActivityStatusesSubject.complete(),this.legacyHandoffNavigationSubject.complete(),this.initializationStatusSubject.complete(),this.pendingApprovalsSubject.complete(),this.pendingSkillsSubject.complete()}waitForAttach(){if(this.attachedPool)return Promise.resolve(this.attachedPool);return this.readyPromise}async waitForActiveHandle(){let J=await this.waitForAttach();return I1(J.threadHandles$.pipe(f5((Z)=>Z!==null)))}}n0();Lc();c4();E1();n0();F3();f7();BB();t30();c4();jH();Sg0();I4();U4();E1();KJ();c4();function wM3(J){let Z=J.messages.filter((V)=>!V.parentToolUseId),Q=-1;for(let V=Z.length-1;V>=0;V--)if(Z[V]?.role==="assistant"){Q=V;break}if(Q<0)return{running:0,blocked:0};let Y=Z[Q];if(!Y)return{running:0,blocked:0};let X=new Map;for(let V of Z.slice(Q+1)){if(V.role!=="user")continue;for(let G of V.content)if(G.type==="tool_result")X.set(G.toolUseID,G.run)}let K=0;for(let V of Y.content){if(V.type!=="tool_use")continue;let G=X.get(V.id);if(!G||!g8(G.status))K++}return{running:K,blocked:0}}function LM3(J){let Z=J.messages.at(-1);if(!Z)return"user-message-initial";if(Z.role==="assistant")return Z.state.type==="complete"&&Z.state.stopReason==="end_turn"?"user-message-reply":!1;return!1}function OM3(J){let Z=LM3(J);if(Z)return Z;return!1}function Uy(J,Z,Q={files:[]},Y=void 0){let X=wM3(J),K=Z==="awaiting_approval"?1:0;if(Z==="working"||Z==="streaming")return{state:"active",inferenceState:"running",fileChanges:Q,ephemeralError:Y,interactionState:!1,toolState:{running:0,blocked:0}};if(Z==="tool_use"||Z==="running_tools"){let V=X.running;return{state:"active",inferenceState:"idle",fileChanges:Q,ephemeralError:Y,interactionState:V>0?"tool-running":!1,toolState:{running:V,blocked:K}}}if(Z==="awaiting_approval")return{state:"active",inferenceState:"idle",fileChanges:Q,ephemeralError:Y,interactionState:"user-tool-approval",toolState:{running:X.running,blocked:K}};return{state:"active",inferenceState:"idle",fileChanges:Q,ephemeralError:Y,interactionState:OM3(J),toolState:{running:X.running,blocked:K}}}c4();class ne0{authoritativeThread;currentAgentLoopState;pendingMessageSubmits=[];pendingQueuedSubmits=[];pendingQueuedInterruptMessageIDs=new Set;pendingEdit;constructor(J,Z){this.authoritativeThread=J,this.currentAgentLoopState=Z}setAgentLoopState(J){this.currentAgentLoopState=J}optimisticUpdate(J){switch(J.type){case"submit":return this.optimisticSubmit(J);case"discard-queued":return this.pendingQueuedSubmits=[],this.pendingQueuedInterruptMessageIDs.clear(),this.buildProjection();case"interrupt-queued":return this.optimisticInterruptQueued(J);case"edit":return this.optimisticEdit(J);case"drop-submit":return this.dropOptimisticSubmit(J);case"update-submit-guidance":return this.updateOptimisticSubmitGuidance(J)}}updateOptimisticSubmitGuidance(J){let Z=!1;if(this.pendingMessageSubmits=this.pendingMessageSubmits.map((Q)=>{if(Q.clientMessageID!==J.clientMessageID)return Q;return Z=!0,{...Q,discoveredGuidanceFiles:J.discoveredGuidanceFiles}}),!Z)this.pendingQueuedSubmits=this.pendingQueuedSubmits.map((Q)=>{if(Q.clientMessageID!==J.clientMessageID)return Q;return Z=!0,{...Q,discoveredGuidanceFiles:J.discoveredGuidanceFiles}});return this.buildProjection()}dropOptimisticSubmit(J){let Z=this.pendingMessageSubmits.filter((Y)=>Y.clientMessageID!==J.clientMessageID),Q=this.pendingQueuedSubmits.filter((Y)=>Y.clientMessageID!==J.clientMessageID);if(Z.length===this.pendingMessageSubmits.length&&Q.length===this.pendingQueuedSubmits.length)return this.buildProjection();return this.pendingMessageSubmits=Z,this.pendingQueuedSubmits=Q,this.buildProjection()}optimisticInterruptQueued(J){let Z=this.buildProjection(),Q=(Z.queuedMessages??[]).find((Y)=>(Y.queuedMessage.dtwMessageID??Y.id)===J.queuedMessageID);if(!Q||ae0(Q))return Z;if(this.pendingQueuedInterruptMessageIDs.has(J.queuedMessageID))return this.buildProjection();return this.pendingQueuedInterruptMessageIDs.add(J.queuedMessageID),this.buildProjection()}optimisticSubmit(J){if(kM3(this.pendingMessageSubmits,this.pendingQueuedSubmits,this.authoritativeThread,J.clientMessageID))return this.buildProjection();let Z={clientMessageID:J.clientMessageID,content:J.content,userState:J.userState,sentAt:J.sentAt??Date.now()};if(mM3(this.currentAgentLoopState))this.pendingQueuedSubmits.push(Z);else this.pendingMessageSubmits.push(Z);return this.buildProjection()}optimisticEdit(J){let Z=this.buildProjection(),Q=Oj0(Z,J.targetMessageID);if(Q<0)return Z;return this.pendingMessageSubmits=[],this.pendingQueuedSubmits=[],this.pendingEdit={targetMessageID:J.targetMessageID,content:J.content,truncatedMessageIDs:_M3(Z,Q)},this.buildProjection()}resolve(J){if(!this.hasPendingOverlay())return this.authoritativeThread=J,J;let Z=this.authoritativeThread;return this.authoritativeThread=J,this.reconcilePending(Z),this.buildProjection()}hasPendingOverlay(){return MM3(this.pendingMessageSubmits,this.pendingQueuedSubmits,this.pendingQueuedInterruptMessageIDs,this.pendingEdit)}reconcilePending(J){let Z=CM3(this.authoritativeThread);this.pendingMessageSubmits=vM3(J,this.authoritativeThread,Z,this.pendingMessageSubmits),this.pendingQueuedSubmits=uM3(this.authoritativeThread,Z,this.pendingQueuedSubmits),this.pendingQueuedInterruptMessageIDs=bM3(this.authoritativeThread,this.pendingQueuedSubmits,this.pendingQueuedInterruptMessageIDs),this.pendingEdit=hM3(Z,this.pendingEdit)}buildProjection(){if(!this.hasPendingOverlay())return this.authoritativeThread;let J=this.pendingEdit;return EM3(this.authoritativeThread,(Z)=>AM3(Z,J),(Z)=>jM3(Z,this.pendingMessageSubmits),(Z)=>RM3(Z,this.pendingQueuedSubmits),(Z)=>IM3(Z,this.pendingQueuedInterruptMessageIDs))}}function EM3(J,...Z){return Z.reduce((Q,Y)=>Y?Y(Q):Q,J)}function MM3(J,Z,Q,Y){return J.length>0||Z.length>0||Q.size>0||Y!==void 0}function AM3(J,Z){if(!Z)return J;let Q=Bf1(J,Z.targetMessageID);if(!Q)return J;let{index:Y,message:X}=Q,K=J.messages.slice(0,Y+1);return K[Y]={...X,content:Z.content},{...J,messages:K,nextMessageId:Lj0({messages:K,nextMessageId:J.nextMessageId})}}function jM3(J,Z){if(Z.length===0)return J;let Q=Lj0(J),Y=Z.map((X,K)=>Vb4(X,Q+K));return{...J,messages:[...J.messages,...Y],nextMessageId:Math.max(J.nextMessageId??0,Q+Y.length)}}function RM3(J,Z){if(Z.length===0)return J;let Q=Z.map(PM3);return{...J,queuedMessages:[...J.queuedMessages??[],...Q]}}function IM3(J,Z){if(Z.size===0||!J.queuedMessages?.length)return J;let Q=!1,Y=J.queuedMessages.map((X)=>{let K=cV0(X);if(!K||!Z.has(K)||ae0(X))return X;return Q=!0,{...X,interrupt:!0}});if(!Q)return J;return{...J,queuedMessages:Y}}function Vb4(J,Z){return{role:"user",content:J.content,userState:J.userState,discoveredGuidanceFiles:J.discoveredGuidanceFiles,meta:{sentAt:J.sentAt},messageId:Z,dtwMessageID:J.clientMessageID}}function PM3(J){return{id:J.clientMessageID,queuedMessage:Vb4(J,-1)}}function CM3(J){let Z=new Set,Q=new Set,Y=new Map,X=new Set;for(let K of J.messages){let V=dV0(K);if(V){if(X.add(V),K.role==="user")Z.add(V),Y.set(V,K)}}for(let K of J.queuedMessages??[]){let V=cV0(K);if(V)Q.add(V)}return{userMessageIDs:Z,queuedMessageIDs:Q,userMessagesByID:Y,messageIDsInTimeline:X}}function _M3(J,Z){return J.messages.slice(Z+1).map((Q)=>dV0(Q)).filter((Q)=>Q!==void 0)}function TM3(J,Z){return J.messages.some((Q)=>Q.role==="user"&&dV0(Q)===Z)}function SM3(J,Z){return(J.queuedMessages??[]).some((Q)=>cV0(Q)===Z)}function ae0(J){return"interrupt"in J&&J.interrupt===!0}function kM3(J,Z,Q,Y){return J.some((X)=>X.clientMessageID===Y)||Z.some((X)=>X.clientMessageID===Y)||TM3(Q,Y)||SM3(Q,Y)}function vM3(J,Z,Q,Y){if(Y.length===0)return[];let{unmatchedPendingSubmits:X,acknowledgedByID:K}=yM3(Y,Q.userMessageIDs);if(X.length===0)return[];let V=xM3(J,Z);if(!V)return X;let G=fM3(V,K,X.length);return X.slice(G)}function yM3(J,Z){let Q=new Set,Y=[];for(let X of J){if(Z.has(X.clientMessageID)){Q.add(X.clientMessageID);continue}Y.push(X)}return{unmatchedPendingSubmits:Y,acknowledgedByID:Q}}function xM3(J,Z){let Q=Kb4(J),Y=Kb4(Z);if(!(Q.length<=Y.length&&Q.every((K,V)=>K.dtwMessageID===Y[V]?.dtwMessageID)))return;return Y.slice(Q.length)}function fM3(J,Z,Q){let Y=0;for(let X of J){let K=dV0(X);if(K&&Z.has(K))continue;if(Y++,Y===Q)return Y}return Y}function Kb4(J){return J.messages.filter((Z)=>Z.role==="user")}function uM3(J,Z,Q){if(Q.length===0)return[];let Y=[...J.queuedMessages??[]];return Q.filter((X)=>{if(Z.queuedMessageIDs.has(X.clientMessageID)||Z.userMessageIDs.has(X.clientMessageID))return!1;let K=Y.findIndex((V)=>Ej0(X.content,V.queuedMessage.content));if(K>=0)return Y.splice(K,1),!1;return!0})}function bM3(J,Z,Q){if(Q.size===0)return new Set;let Y=new Map((J.queuedMessages??[]).map((V)=>{let G=cV0(V);if(!G)return;return[G,V]}).filter((V)=>V!==void 0)),X=new Set(Z.map((V)=>V.clientMessageID)),K=new Set;for(let V of Q){let G=Y.get(V);if(!G){if(X.has(V))K.add(V);continue}if(ae0(G))continue;K.add(V)}return K}function hM3(J,Z){if(!Z)return;return gM3(J,Z)?void 0:Z}function gM3(J,Z){let Q=n6.safeParse(Z.targetMessageID);if(!Q.success)return!1;let Y=J.userMessagesByID.get(Q.data);if(!Y)return!1;if(!Ej0(Y.content,Z.content))return!1;return Z.truncatedMessageIDs.every((K)=>{let V=n6.safeParse(K);if(!V.success)return!0;return!J.messageIDsInTimeline.has(V.data)})}function dV0(J){let Z=n6.safeParse(J.dtwMessageID);if(!Z.success)return;return Z.data}function cV0(J){let Z=n6.safeParse(J.queuedMessage.dtwMessageID);if(Z.success)return Z.data;let Q=n6.safeParse(J.id);if(Q.success)return Q.data;return}function mM3(J){return pM3.has(J)}var pM3=new Set(["working","streaming","tool_use","running_tools","awaiting_approval"]);var dM3=1e4;class oe0{deps;thread$;threadState$;threadViewState$;inferenceErrors$;toolProgressByToolUseID$;pendingApprovals$;provider;threadSubject;threadStateSubject;threadViewStateSubject;transportSubscriptions=[];clientID;transport;executorRuntime;toolRunner;optimisticThreadProjection;pendingApprovalsSubject=new V4([]);pendingSkillsSubject=new V4([]);inferenceErrorsSubject=new H4;pendingSkills$=this.pendingSkillsSubject;latestPendingApprovals=[];fileChanges={files:[]};currentAgentLoopState;activeError=null;retryCountdownTimer=null;handoffService;providerSubscriptions=null;constructor(J,Z){this.deps=Z;this.provider=J,this.clientID=Z.clientID;let Q=iD("info"),Y=iD("error"),X=(z)=>({...z??{},threadId:this.provider.threadId}),K={info:(z,q)=>{Q(z,X(q))},error:(z,q)=>{Y(z,X({error:q}))},wsMessage:(z,q,W)=>{_.debug("DTW executor tool runner message",X({direction:z,clientID:q,...typeof W==="object"&&W!==null?W:{message:W}}))}};this.transport=this.provider.getTransport(),this.executorRuntime=new kj({transport:this.transport,toolService:this.deps.toolService,configService:this.deps.configService,clientID:this.clientID,threadID:this.provider.threadId,invokeTool:(z)=>this.invokeToolForLease(z),skillService:this.deps.skillService,initialToolDiscovery:this.deps.initialToolDiscovery,onBootstrapSuccess:()=>{this.applyLocalEnvironment()},sendGitSnapshot:!1,batchGuidanceFiles:yY0,renderToolRunError:mm,log:K,autoResolvePendingApprovals:!1,handshake:(z)=>this.sendExecutorHandshake(z),handshakeManagerOptions:{onError:({error:z,attempt:q,delayMs:W})=>{_.warn("DTW executor handshake failed",{error:z,attempt:q,delayMs:W})},onExhausted:(z)=>{this.handleHandshakeExhausted(z)}},handleExecutorRollbackRequest:async(z)=>{await this.handleRollbackRequest(z).catch(()=>{return})},handleExecutorFileSystemReadDirectoryRequest:async(z)=>{await this.handleFileSystemReadDirectoryRequest(z).catch(()=>{return})},handleExecutorFileSystemReadFileRequest:async(z)=>{await this.handleFileSystemReadFileRequest(z).catch(()=>{return})}}),this.executorRuntime.attachTransportExecutorCallbacks({includeConnectionChanges:!0}),this.toolRunner=this.executorRuntime.toolRunner,this.executorRuntime.handleConnectionChange(this.transport.getConnectionInfo()),this.currentAgentLoopState=J.getAgentLoopState();let V=J.getThread();this.optimisticThreadProjection=new ne0(V,this.currentAgentLoopState);let G=this.optimisticThreadProjection.resolve(V),F=Uy(G,this.currentAgentLoopState,this.fileChanges,this.currentEphemeralError());this.threadSubject=new V4(G),this.thread$=this.threadSubject,this.threadStateSubject=new V4(jR({thread:G,viewState:F,resolvedTokenUsage:Y7(G)})),this.threadState$=this.threadStateSubject,this.threadViewStateSubject=new V4(F),this.threadViewState$=this.threadViewStateSubject,this.inferenceErrors$=this.inferenceErrorsSubject,this.toolProgressByToolUseID$=this.provider.toolProgressByToolUseIDChanges().pipe(w1(hV0)),this.transportSubscriptions.push(this.threadSubject.subscribe((z)=>{this.rebuildThreadState(z)}),this.threadViewStateSubject.subscribe((z)=>{let q=this.threadStateSubject.getValue();if(q.viewState===z)return;this.threadStateSubject.next({...q,viewState:z})})),this.pendingApprovals$=this.pendingApprovalsSubject,this.refreshProviderFileChanges(),this.attachTransportHandlers(),this.handoffService=Z.handoffService}startProviderSubscription(J){this.providerSubscriptions?.unsubscribe();let Z=this.provider.threadChanges().subscribe({next:(Y)=>{J(Y),this.refreshProviderFileChanges(),this.updateThreadViewStateFromProvider()}}),Q=this.provider.agentLoopStateChanges().subscribe({next:(Y)=>{if(this.currentAgentLoopState=Y,this.optimisticThreadProjection.setAgentLoopState(Y),Y==="error")this.inferenceErrorsSubject.next(Error("Agent failed to complete the request."));this.updateThreadViewStateFromProvider()}});this.providerSubscriptions={unsubscribe:()=>{Z.unsubscribe(),Q.unsubscribe()}}}writeThread(J){this.currentAgentLoopState=this.provider.getAgentLoopState(),this.threadSubject.next(J)}providerThread(){return this.provider.getThread()}resolveAuthoritativeThread(J){return this.optimisticThreadProjection.resolve(J)}getThreadViewState(){return this.threadViewStateSubject.getValue()}getCurrentThread(){return this.threadSubject.getValue()}getThreadID(){return this.getCurrentThread().id}getThreadTitle(){return this.getCurrentThread().title}getAgentMode(){return this.getCurrentThread().agentMode}getMessages(){return this.getCurrentThread().messages}getQueuedMessages(){return this.getCurrentThread().queuedMessages??[]}getInitialTreeURI(){return this.getCurrentThread().env?.initial.trees?.[0]?.uri}shouldAutoSubmitDraft(){let J=this.getCurrentThread();if(!J.autoSubmitDraft)return!1;return F8(J)===0}getEmptyHandoffParentThreadID(){let J=this.getCurrentThread();if(F8(J)>0)return;return P10(J,"handoff")?.threadID}isThreadEmpty(){return F8(this.getCurrentThread())===0}isStreaming(){let J=this.getMessages().at(-1);return J?.role==="assistant"&&J.state.type==="streaming"}getResolvedTokenUsage(){return Y7(this.thread$.getValue())}async dispose(){this.providerSubscriptions?.unsubscribe(),this.providerSubscriptions=null;for(let J of this.transportSubscriptions)J.unsubscribe();this.transportSubscriptions.length=0,this.clearRetryCountdownTimer(),this.executorRuntime.dispose(),await this.provider.disposeAndWaitForClose(),this.threadSubject.complete(),this.threadStateSubject.complete(),this.threadViewStateSubject.complete(),this.inferenceErrorsSubject.complete(),this.pendingApprovalsSubject.complete(),this.pendingSkillsSubject.complete()}async sendMessage(J){if(J.editIndex!==void 0){await this.ensureProviderReadyForExecutorActions();let K=this.thread$.getValue(),V=K.messages[J.editIndex];if(!V||V.role!=="user"||!V.dtwMessageID)throw Error("Unable to edit message: missing DTW message ID");let G=K.messages.findIndex((q)=>q.role==="user");if(J.editIndex===G&&J.agentMode&&K.agentMode!==J.agentMode)this.provider.setAgentMode(J.agentMode,{overwrite:!0}),this.updateThread((q)=>{q.agentMode=J.agentMode});this.provider.editUserMessage(V.dtwMessageID,J.content,mn0(),J.agentMode);let z=this.optimisticThreadProjection.optimisticUpdate({type:"edit",targetMessageID:V.dtwMessageID,content:J.content});this.writeThread(z);return}let Z=this.thread$.getValue();if(!Z.messages.some((K)=>K.role==="user")&&J.agentMode&&Z.agentMode!==J.agentMode)this.provider.setAgentMode(J.agentMode,{overwrite:!0}),this.updateThread((K)=>{K.agentMode=J.agentMode});let Y=Eq(),X=this.optimisticThreadProjection.optimisticUpdate({type:"submit",clientMessageID:Y,content:J.content});this.writeThread(X);try{let K=J.prepareContentForSend?await J.prepareContentForSend(J.content):J.content;await this.ensureProviderConnectedForClientWrites();let V=await this.discoverGuidanceFilesForUserMessage(K);if(V&&V.length>0){let F=V.map((q)=>({uri:q.uri,lineCount:q.lineCount??0,...typeof q.content==="string"?{content:q.content}:{}})),z=this.optimisticThreadProjection.optimisticUpdate({type:"update-submit-guidance",clientMessageID:Y,discoveredGuidanceFiles:F});this.writeThread(z)}let G=await this.collectUserState();this.provider.sendUserMessage(K,J.agentMode,G,Y,V)}catch(K){throw this.rollbackOptimisticSubmit(Y),K}}async restoreTo(J){await this.ensureProviderReadyForExecutorActions();let Y=[...this.thread$.getValue().messages.slice(0,J+1)].reverse().find((V)=>V.role==="user");if(!Y?.dtwMessageID)throw Error("Unable to edit message: missing DTW message ID");let X=Y.content.filter((V)=>V.type==="text"||V.type==="image").map((V)=>{if(V.type==="image")return{...V,source:{...V.source}};return{...V}});if(X.length===0)throw Error("Unable to edit message: no editable content found");this.provider.editUserMessage(Y.dtwMessageID,X,mn0());let K=this.optimisticThreadProjection.optimisticUpdate({type:"edit",targetMessageID:Y.dtwMessageID,content:X});this.writeThread(K)}async queueMessage(J){let Z=Eq(),Q=this.optimisticThreadProjection.optimisticUpdate({type:"submit",clientMessageID:Z,content:J});this.writeThread(Q);try{await this.ensureProviderConnectedForClientWrites();let Y=await this.discoverGuidanceFilesForUserMessage(J);if(Y&&Y.length>0){let K=Y.map((G)=>({uri:G.uri,lineCount:G.lineCount??0,...typeof G.content==="string"?{content:G.content}:{}})),V=this.optimisticThreadProjection.optimisticUpdate({type:"update-submit-guidance",clientMessageID:Z,discoveredGuidanceFiles:K});this.writeThread(V)}let X=await this.collectUserState();this.provider.sendUserMessage(J,void 0,X,Z,Y)}catch(Y){throw this.rollbackOptimisticSubmit(Z),Y}}async discardQueuedMessages(){let J=this.optimisticThreadProjection.optimisticUpdate({type:"discard-queued"});this.writeThread(J),this.provider.discardQueuedMessages()}async interruptQueuedMessage(J){await this.ensureProviderReadyForExecutorActions(),this.provider.interruptQueuedMessage(J);let Z=this.optimisticThreadProjection.optimisticUpdate({type:"interrupt-queued",queuedMessageID:J});this.writeThread(Z)}async ensureProviderConnectedForClientWrites(){await this.provider.ensureConnectedForAction("client-write")}async ensureProviderReadyForExecutorActions(J){await this.provider.ensureConnectedForAction("executor-action"),await this.executorRuntime.ensureReady({timeoutMs:dM3,timeoutMessage:"Timed out waiting for executor readiness. Please retry."})}rollbackOptimisticSubmit(J){let Z=this.optimisticThreadProjection.optimisticUpdate({type:"drop-submit",clientMessageID:J});this.writeThread(Z)}async setVisibility(J){await this.deps.threadService.updateThreadMeta(this.provider.threadId,oG(J));let Z=await this.deps.threadService.get(this.provider.threadId);if(Z)this.writeThread(Z)}async setTitle(J){let Z=J.trim();if(!Z)return;await this.ensureProviderReadyForExecutorActions(),this.provider.setThreadTitle(Z),this.updateThread((Q)=>{Q.title=Z})}updateThread(J){let Z=v9(this.threadSubject.getValue(),J),Q=this.optimisticThreadProjection.resolve(Z);this.writeThread(Q)}async cancelTurn(){this.provider.cancelAgentLoop()}async cancelStreaming(){this.provider.cancelAgentLoop()}async retryTurn(){this.provider.retryAgentLoop()}invokeBashTool(J,Z){let Q=fj4();return new k0((Y)=>{let X=!1,K=null,V=(q)=>{try{this.provider.appendManualBashInvocation({args:J,run:q,hidden:Z.hidden})}catch(W){_.warn("Failed to append manual bash invocation to DTW thread",{error:W}),this.activeError={message:`Failed to sync bash result to thread: ${W instanceof Error?W.message:String(W)}`},this.updateThreadViewStateFromProvider()}},G=(q,W={emitRun:!0})=>{if(X)return;if(X=!0,V(q),W.emitRun)Y.next(q);Y.complete()},F=(q)=>q instanceof Error?q.message:String(q),z=()=>{K?.unsubscribe(),G({status:"cancelled",reason:"User canceled"})};return Z.abortController.signal.addEventListener("abort",z),(async()=>{try{if(await this.ensureProviderReadyForExecutorActions(),X)return;let q=await uG({toolName:m6,dtwArtifactSyncService:this.createDTWArtifactSyncService(),configService:this.deps.configService,toolService:this.deps.toolService,mcpService:this.deps.mcpService,skillService:this.deps.skillService,fsTracker:this.deps.fs,toolUseID:Q,discoveredGuidanceFileURIs:this.toolRunner.discoveredGuidanceFileURIs,threadID:this.provider.threadId});if(X)return;let W={...q,userInitiated:!0};Y.next({status:"in-progress"}),K=this.deps.toolService.invokeTool(m6,{args:J,userInput:{accepted:!0}},W).subscribe({next:(H)=>{if(X)return;if(Y.next(H),H.status!=="in-progress")G(H,{emitRun:!1})},error:(H)=>{G({status:"error",error:{message:F(H)}})}})}catch(q){G({status:"error",error:{message:F(q)}})}})(),()=>{K?.unsubscribe(),Z.abortController.signal.removeEventListener("abort",z)}})}dismissEphemeralError(){this.activeError=null,this.clearRetryCountdownTimer(),this.updateThreadViewStateFromProvider()}async resolveApproval(J,Z,Q){let Y=K9.safeParse(J);if(!Y.success)return;this.provider.resolveToolApproval(Y.data,Z,{denyFeedback:Q})}addPendingSkill(J){this.pendingSkillsSubject.next([...this.pendingSkillsSubject.getValue(),J])}removePendingSkill(J){this.pendingSkillsSubject.next(this.pendingSkillsSubject.getValue().filter((Z)=>Z.name!==J))}clearPendingSkills(){this.pendingSkillsSubject.next([])}async getDraft(){let J=this.thread$.getValue().draft;if(!J)return null;let Z=zC(J);if(!Z.text&&Z.images.length===0)return null;return Z}async setDraft(J){this.updateThread((Z)=>{if(!J||!J.text&&J.images.length===0){delete Z.draft,delete Z.autoSubmitDraft;return}let Q=[];if(J.text)Q.push({type:"text",text:J.text});if(J.images.length>0)Q.push(...J.images);Z.draft=Q,Z.autoSubmitDraft=!1})}async clearPendingNavigation(){}async getGuidanceFiles(J){let Z=this.thread$.getValue();return(await Wz({filesystem:this.deps.filesystem,configService:this.deps.configService,threadService:this.deps.threadService},Z,J)).map((Y)=>({uri:Y.uri,type:Y.type}))}async getFilesAffectedByTruncation(J){let Z=this.thread$.getValue(),Q=await this.getToolUsesToRevert(Z,J);return Q.size>0?this.deps.fs.tracker.getFilesForToolUses(Q):[]}async getToolUsesToRevert(J,Z){let Q=new Set;J.messages.slice(0,Z).forEach((K)=>{if(K.role==="user"){for(let V of K.content)if(V.type==="tool_result")Q.add(V.toolUseID)}else for(let V of K.content)if(V.type==="tool_use")Q.add(V.id)});let Y=new Set,X=await this.deps.fs.tracker.getAllRecords();for(let[K]of X.entries())if(!Q.has(K))Y.add(K);return Y}async collectUserState(){try{return await y$0()??bm}catch(J){return _.warn("Failed to collect IDE user state for DTW message",{error:J}),bm}}resolveUserMessageGuidanceContext(){let J=G1.file(process.cwd()),Q=this.thread$.getValue().env?.initial,Y=Q?.trees?.[0]?.uri?T6(Q.trees[0].uri):J;return{workspaceRoot:Y.scheme==="file"?Y:J,workingDirectory:J}}resolveMentionedPathToURI(J,Z){if(J.startsWith("file://"))try{let Y=G1.parse(J);return Y.scheme==="file"?Y:null}catch{return null}if(ZJ(J))return G1.file(J);let Q=J.startsWith("./")||J.startsWith("../")?Z.workingDirectory:Z.workspaceRoot;return V1.resolvePath(Q,J)}async discoverGuidanceFilesForUserMessage(J){let Z=r8(J);if(!Z.trim())return;let{paths:Q}=v$0(Z);if(Q.length===0)return;let Y=this.resolveUserMessageGuidanceContext(),X=new Set,K=new Set,V=[];for(let G of Q){let F=this.resolveMentionedPathToURI(G,Y);if(!F||!V1.hasPrefix(F,Y.workspaceRoot))continue;let z=F.toString();if(K.has(z))continue;K.add(z);let q=await qQ({stat:(W,H)=>this.deps.filesystem.stat(W,H),readFile:(W,H)=>this.deps.filesystem.readFile(W,H)},F,Y.workspaceRoot,null,X);for(let W of q){if(V.some((H)=>H.uri===W.uri))continue;X.add(W.uri),V.push({uri:W.uri,content:W.content,lineCount:W.lineCount})}}return V.length>0?V:void 0}handleHandshakeExhausted(J){_.error("DTW executor handshake exhausted",J)}syncApprovalRequests(J){let Z=this.provider.threadId;if(!Z){this.pendingApprovalsSubject.next([]);return}let Q=J.filter((X)=>X.threadId===Z||X.mainThreadId===Z);this.pendingApprovalsSubject.next(Q);let Y=new Set(Q.map(Tj));for(let X of[...this.toolRunner.sentApprovalRequests])if(!Y.has(X))this.toolRunner.sentApprovalRequests.delete(X);for(let X of Q){let K=Tj(X);if(this.toolRunner.sentApprovalRequests.has(K))continue;let V=CY0(X),G=this.transport.getConnectionInfo(),F=G.state==="connected"&&G.role==="executor";if(F)this.transport.sendExecutorToolApprovalRequest(V);if(F)this.toolRunner.sentApprovalRequests.add(K)}}handleExecutorToolApprovalResponse(J){this.deps.toolService.resolveApproval(J.toolCallId,J.accepted,J.input?.denyFeedback)}syncExecutorTools(J){this.executorRuntime.syncExecutorToolRegistrations(J)}attachTransportHandlers(){this.transportSubscriptions.push(this.provider.executorReadyChanges().subscribe({next:(J)=>{if(J)this.syncApprovalRequests(this.latestPendingApprovals)}}),this.provider.compactionStateChanges().subscribe({next:()=>{this.updateThreadViewStateFromProvider()}}),this.provider.errorEvents().subscribe({next:(J)=>{if(this.activeError=J.type==="error_set"?J.error:null,J.type==="error_set")this.inferenceErrorsSubject.next(J.error);this.syncRetryCountdownTimer(),this.updateThreadViewStateFromProvider()}}),this.provider.errors().subscribe({next:(J)=>{this.inferenceErrorsSubject.next(Error(J.message))}}),this.provider.cancelledEvents().subscribe({next:()=>{this.activeError=null,this.clearRetryCountdownTimer(),this.updateThreadViewStateFromProvider()}}),this.transport.executorToolApprovalResponses().subscribe({next:(J)=>{this.handleExecutorToolApprovalResponse(J)}}),this.deps.toolService.tools.subscribe({next:(J)=>{this.syncExecutorTools(Hv(J))}}),this.deps.toolService.pendingApprovals$.subscribe((J)=>{this.latestPendingApprovals=J,this.syncApprovalRequests(J)}))}async sendExecutorHandshake(J){_.debug("DTW executor handshake",{trigger:J,threadID:this.provider.threadId}),await this.executorRuntime.bootstrapExecutor({executorType:"local-client",trigger:J,workspaceRoot:process.cwd(),threadID:this.provider.threadId,suppressConnectLog:!0})}async applyLocalEnvironment(){try{let J=await WZ();this.provider.setEnvironment({initial:J})}catch(J){_.debug("Failed to apply local environment",{error:J})}}createDTWArtifactSyncService(){return{upsertArtifact:(J,Z)=>{let Q=K9.safeParse(Z);this.transport.sendExecutorArtifactUpsert(J,Q.success?Q.data:void 0)},deleteArtifact:(J)=>{this.transport.sendExecutorArtifactDelete(J)}}}async invokeToolForLease(J){let Z=typeof J.args==="object"&&J.args!==null?J.args:{},Q=Date.now(),Y=await uG({toolName:J.toolName,dtwHandoffService:this.handoffService,dtwArtifactSyncService:this.createDTWArtifactSyncService(),configService:this.deps.configService,toolService:this.deps.toolService,mcpService:this.deps.mcpService,skillService:this.deps.skillService,fsTracker:this.deps.fs,toolUseID:J.toolCallId,discoveredGuidanceFileURIs:this.toolRunner.discoveredGuidanceFileURIs,threadID:this.provider.threadId});_.info("DTW TUI tool run environment ready",{toolCallId:J.toolCallId,toolName:J.toolName,threadId:this.provider.getThread().id,elapsedMs:Date.now()-Q});let X=this.deps.toolService.invokeTool(J.toolName,{args:Z},Y);return _.info("DTW TUI tool service returned observable",{toolCallId:J.toolCallId,toolName:J.toolName,threadId:this.provider.getThread().id,elapsedMs:Date.now()-Q}),X}async handleRollbackRequest(J){await this.toolRunner.handleRollbackRequest(J.editId,J.toolUseIdsToRevert,(Z)=>this.deps.fs.tracker.revertChanges(Z)),await this.refreshProviderFileChanges(),this.updateThreadViewStateFromProvider()}async handleFileSystemReadDirectoryRequest(J){let Z=await qv({fileSystem:this.deps.filesystem,workspaceRoot:process.cwd()},J.uri);this.transport.sendExecutorFileSystemReadDirectoryResult(J.requestId,Z)}async handleFileSystemReadFileRequest(J){let Z=await TY0({fileSystem:this.deps.filesystem,workspaceRoot:process.cwd()},J.uri);this.transport.sendExecutorFileSystemReadFileResult(J.requestId,Z)}async refreshProviderFileChanges(){this.fileChanges={files:await s30(this.deps.fs.tracker)},this.updateThreadViewStateFromProvider()}updateThreadViewStateFromProvider(){this.threadViewStateSubject.next(Uy(this.threadSubject.getValue(),this.currentAgentLoopState,this.fileChanges,this.currentEphemeralError())),this.deps.onThreadViewStateChange()}rebuildThreadState(J){this.threadStateSubject.next(jR({thread:J,viewState:this.threadViewStateSubject.getValue(),resolvedTokenUsage:Y7(J)}))}syncRetryCountdownTimer(){let J=this.activeError?.retryAt;if(J===void 0||J<=Date.now()){this.clearRetryCountdownTimer();return}if(this.retryCountdownTimer!==null)return;this.retryCountdownTimer=setInterval(()=>{let Z=this.activeError?.retryAt;if(Z===void 0){this.clearRetryCountdownTimer();return}if(this.updateThreadViewStateFromProvider(),Z<=Date.now())this.clearRetryCountdownTimer()},1000)}clearRetryCountdownTimer(){if(this.retryCountdownTimer===null)return;clearInterval(this.retryCountdownTimer),this.retryCountdownTimer=null}currentEphemeralError(){if(!this.activeError)return;let J=this.activeError.retryAt!==void 0?Math.max(0,Math.ceil((this.activeError.retryAt-Date.now())/1000)):void 0,Z=this.activeError.code!==void 0||this.activeError.attempt!==void 0?{code:this.activeError.code,attempt:this.activeError.attempt}:void 0;return{message:this.activeError.message,stack:this.activeError.stack,error:Z,retryCountdownSeconds:J}}}c4();E1();function Gb4(J){let Z=new V4(J.thread),Q=new V4(Uy(J.thread,"idle")),Y=new V4(new Map),X=new V4([]),K=new V4([]),V=(z)=>{let W={...Z.getValue()};if(!z||!z.text&&z.images.length===0)delete W.draft,delete W.autoSubmitDraft;else{let H=[];if(z.text)H.push({type:"text",text:z.text});if(z.images.length>0)H.push(...z.images);W.draft=H,W.autoSubmitDraft=!1}Z.next(W),Q.next(Uy(W,"idle"))};return{handle:Hy({thread$:Z,threadViewState$:Q,toolProgressByToolUseID$:Y,pendingApprovals$:X,pendingSkills$:K,getCurrentThread:()=>Z.getValue(),sendMessage:async(z)=>(await J.materialize()).sendMessage(z),restoreTo:async(z)=>(await J.materialize()).restoreTo(z),queueMessage:async(z)=>(await J.materialize()).queueMessage(z),discardQueuedMessages:async()=>{},interruptQueuedMessage:async()=>{},setTitle:async(z)=>(await J.materialize()).setTitle(z),setVisibility:async(z)=>(await J.materialize()).setVisibility(z),cancelTurn:async()=>{},cancelStreaming:async()=>{},retryTurn:async()=>{},dismissEphemeralError:()=>{},resolveApproval:async()=>{},addPendingSkill:(z)=>{K.next([...K.getValue(),z])},removePendingSkill:(z)=>{K.next(K.getValue().filter((q)=>q.name!==z))},clearPendingSkills:()=>{K.next([])},getDraft:async()=>cM3(Z.getValue()),setDraft:async(z)=>V(z),getFilesAffectedByTruncation:async()=>[],clearPendingNavigation:async()=>{},getGuidanceFiles:async()=>[]}),getThreadViewState:()=>Q.getValue(),dispose:async()=>{Z.complete(),Q.complete(),Y.complete(),X.complete(),K.complete()}}}function cM3(J){if(!J.draft)return null;let Z=zC(J.draft);if(!Z.text&&Z.images.length===0)return null;return Z}var lV0="Loading thread...",lM3="Importing thread";class Pa{deps;recentThreadIDsSubject=new V4([]);threadTitlesSubject=new V4({});activeThreadHandleSubject=new V4(null);allConnectedThreadActivityStatusesSubject=new V4({});initializationStatusSubject=new V4({pending:!1,message:lV0});threadHandleMap=new Map;pendingHandoffThreads=new Map;threadBackStack=[];threadForwardStack=[];isThreadActivationInProgress=!1;activeThreadContextID=null;handoffService;queueOnSubmitByDefault=!0;constructor(J){this.deps=J;this.handoffService=fY0({configService:this.deps.configService,onFollow:this.followHandoffIfSourceActive})}get recentThreadIDs$(){return this.recentThreadIDsSubject}get threadTitles$(){return this.threadTitlesSubject}get threadHandles$(){return this.activeThreadHandleSubject}get allConnectedThreadActivityStatuses$(){return this.allConnectedThreadActivityStatusesSubject}get initializationStatus$(){return this.initializationStatusSubject}get activeThreadHandle(){if(!this.activeThreadContextID)throw Error("No active thread context");let J=this.threadHandleMap.get(this.activeThreadContextID)??this.pendingHandoffThreads.get(this.activeThreadContextID)?.optimisticHandle.handle;if(!J)throw Error(`No thread handle for ${this.activeThreadContextID}`);return J}get activeProvider(){if(!this.activeThreadContextID)return;return this.threadHandleMap.get(this.activeThreadContextID)?.provider}hasPendingInitialization(){return this.initializationStatusSubject.getValue().pending}isDTWMode(){return!0}isThreadActorsMode(){return this.deps.useThreadActors??!1}getTransportConnectionState(){return this.activeProvider?.getConnectionState()??"disconnected"}getTransportConnectionRole(){return this.activeProvider?.getConnectionRole()??null}getCompactionStatus(){let J=this.activeProvider;if(!J)return;return{compactionState:J.getCompactionState()}}async createThread(J){await this.activateThreadWithNavigation(J,{recordNavigation:!0})}async switchThread(J){await this.activateThreadWithNavigation(J,{recordNavigation:!0})}canNavigateBack(){return this.threadBackStack.length>0}canNavigateForward(){return this.threadForwardStack.length>0}async navigateBack(){if(!this.canNavigateBack())return;let J=this.activeThreadContextID;if(!J)return;let Z=this.threadBackStack.pop();if(!Z)return;this.threadForwardStack.push(J);try{await this.activateThreadWithNavigation(Z,{recordNavigation:!1})}catch(Q){throw this.threadForwardStack.pop(),this.threadBackStack.push(Z),Q}}async navigateForward(){if(!this.canNavigateForward())return;let J=this.activeThreadContextID;if(!J)return;let Z=this.threadForwardStack.pop();if(!Z)return;this.threadBackStack.push(J);try{await this.activateThreadWithNavigation(Z,{recordNavigation:!1})}catch(Q){throw this.threadBackStack.pop(),this.threadForwardStack.push(Z),Q}}followHandoffIfSourceActive=async(J)=>{if(this.activeThreadContextID!==J.sourceThreadID)return;await this.switchThread(J.targetThreadID)};async createHandoff(J,Z){let Y=this.threadHandleMap.get(J)?.provider.getThread()??this.activeProvider?.getThread();if(!Y||Y.id!==J)throw Error("No thread available for handoff");let X=Y.env?.initial?.trees?.[0]?.repository?.url??(await this.deps.getThreadEnvironment()).trees?.[0]?.repository?.url,K=await this.handoffService.createHandoffDraft({parentThread:Y,goal:Z.goal,images:Z.images,signal:Z.signal});Z.signal?.throwIfAborted();let V=Z.agentMode??K.sourceAgentMode??Y.agentMode,G={threadID:K.parentThreadID,type:"handoff",...K.parentMessageIndex!==void 0?{messageIndex:K.parentMessageIndex}:{},comment:Z.goal},F=h8(),z=Date.now(),q=[{threadID:J,type:"handoff",role:"child",...K.parentMessageIndex!==void 0?{messageIndex:K.parentMessageIndex}:{},createdAt:z,comment:Z.goal}],W={id:F,created:Date.now(),v:0,messages:[],relationships:q,...V?{agentMode:V}:{},...K.content.length>0?{draft:K.content,autoSubmitDraft:!1}:{}},H=Gb4({thread:W,materialize:()=>this.materializePendingHandoffThread(F)});return this.pendingHandoffThreads.set(F,{agentMode:V??void 0,relationship:G,repositoryURL:X,threadRelationships:q,optimisticHandle:H,materializingPromise:null}),F}async dispose(){for(let J of this.threadHandleMap.values())await J.dispose();for(let J of this.pendingHandoffThreads.values())await J.optimisticHandle.dispose();this.threadHandleMap.clear(),this.pendingHandoffThreads.clear(),this.activeThreadHandleSubject.complete(),this.allConnectedThreadActivityStatusesSubject.complete(),this.initializationStatusSubject.complete(),this.threadTitlesSubject.complete(),this.recentThreadIDsSubject.complete()}async activateThread(J,Z){_.info("[dtw-thread-pool] activateThread:start",{requestedThreadID:J,hasExistingHandle:Boolean(J&&this.threadHandleMap.get(J))});let Q=J?this.threadHandleMap.get(J):void 0;if(Q){let X=Q.thread$.getValue().id;this.activeThreadContextID=X,this.activeThreadHandleSubject.next(Q),this.addToRecentThreads(X),this.syncAllConnectedThreadActivityStatuses(),_.info("[dtw-thread-pool] activateThread:reused",{activeThreadID:X,handleCount:this.threadHandleMap.size});return}let Y=J?this.pendingHandoffThreads.get(J):void 0;if(J&&Y){this.activeThreadContextID=J,this.activeThreadHandleSubject.next(Y.optimisticHandle.handle),this.syncAllConnectedThreadActivityStatuses(),_.info("[dtw-thread-pool] activateThread:optimistic",{activeThreadID:J,handleCount:this.threadHandleMap.size});return}this.isThreadActivationInProgress=!0,this.setInitializationStatus({pending:!0,message:lV0});try{let X=await this.createProvider(J);if(Z?.threadRelationships&&Z.threadRelationships.length>0)X.setRelationships(Z.threadRelationships);let K=cS({fileChangeTrackerStorage:this.deps.fileChangeTrackerStorage},this.deps.osFileSystem,X.threadId),V=new oe0(X,{configService:this.deps.configService,toolService:this.deps.toolService,skillService:this.deps.skillService,mcpService:this.deps.mcpService,clientID:this.deps.clientID,initialToolDiscovery:this.deps.initialToolDiscovery,fs:K,filesystem:this.deps.osFileSystem,threadService:this.deps.threadService,onThreadViewStateChange:()=>{this.syncAllConnectedThreadActivityStatuses()},handoffService:this.handoffService});this.threadHandleMap.set(X.threadId,V),V.startProviderSubscription((G)=>{this.applyProviderState(X.threadId,G)}),this.applyProviderState(X.threadId,X.getThread()),this.activeThreadContextID=X.threadId,this.activeThreadHandleSubject.next(V),this.addToRecentThreads(X.threadId),_.info("[dtw-thread-pool] activateThread:created",{activeThreadID:X.threadId,handleCount:this.threadHandleMap.size})}finally{this.isThreadActivationInProgress=!1,this.setInitializationStatus({pending:!1,message:lV0})}}async activateThreadWithNavigation(J,Z){let Q=this.activeThreadContextID;await this.activateThread(J);let Y=this.activeThreadContextID;if(Z.recordNavigation&&Q!==null&&Y!==null&&Q!==Y)this.recordNavigation(Q)}applyProviderState(J,Z){let Q=this.threadHandleMap.get(J);if(!Q)return;let Y=Q.resolveAuthoritativeThread(Z);Q.writeThread(Y);let X=this.threadTitlesSubject.getValue();if(X[J]!==Y.title)this.threadTitlesSubject.next({...X,[J]:Y.title});this.syncAllConnectedThreadActivityStatuses()}syncAllConnectedThreadActivityStatuses(){let J={};for(let[Z,Q]of this.threadHandleMap.entries())J[Z]=Q.getThreadViewState();for(let[Z,Q]of this.pendingHandoffThreads.entries())J[Z]=Q.optimisticHandle.getThreadViewState();this.allConnectedThreadActivityStatusesSubject.next(J)}addToRecentThreads(J){let Z=[...this.recentThreadIDsSubject.getValue()],Q=Z.indexOf(J);if(Q!==-1)Z.splice(Q,1);if(Z.unshift(J),Z.length>50)Z.pop();this.recentThreadIDsSubject.next(Z)}recordNavigation(J){this.threadBackStack.push(J),this.threadForwardStack=[]}async createProvider(J){let Z=J?void 0:(await this.deps.getThreadEnvironment()).trees?.[0]?.repository?.url,Q=J?void 0:"local-client";return KX0.create({ampURL:this.deps.ampURL,configService:this.deps.configService,connectOnCreate:Boolean(J),executorType:Q,onLegacyImportStateChange:(Y)=>{if(Y==="importing"){this.setInitializationStatus({pending:!0,message:lM3});return}if(this.isThreadActivationInProgress)this.setInitializationStatus({pending:!0,message:lV0})},repositoryURL:Z,threadService:this.deps.threadService,threadId:J,workerUrl:process.env.AMP_WORKER_URL,useThreadActors:this.deps.useThreadActors,connectionMode:"executor+observer"})}async materializePendingHandoffThread(J){let Z=this.pendingHandoffThreads.get(J);if(!Z)throw Error(`No pending handoff thread for ${J}`);if(!Z.materializingPromise){let K=(async()=>{let{threadId:V}=await CU(void 0,this.deps.configService,void 0,{repositoryURL:Z.repositoryURL,agentMode:Z.agentMode,relationship:Z.relationship,executorType:"local-client"});if(this.activeThreadContextID===J)await this.activateThread(V,{threadRelationships:Z.threadRelationships});return V})();Z.materializingPromise=K,K.catch(()=>{let V=this.pendingHandoffThreads.get(J);if(V?.materializingPromise===K)V.materializingPromise=null})}let Q=await Z.materializingPromise,Y=this.threadHandleMap.get(Q);if(!Y)await this.activateThread(Q,{threadRelationships:Z.threadRelationships}),Y=this.threadHandleMap.get(Q);if(!Y)throw Error(`No DTW thread handle for ${Q}`);let X=this.pendingHandoffThreads.get(J);if(X)this.pendingHandoffThreads.delete(J),await X.optimisticHandle.dispose(),this.syncAllConnectedThreadActivityStatuses();return Y}setInitializationStatus(J){let Z=this.initializationStatusSubject.getValue();if(Z.pending===J.pending&&Z.message===J.message)return;this.initializationStatusSubject.next(J)}}io0();import{randomBytes as oM3}from"node:crypto";import{readFile as rM3}from"node:fs/promises";import sM3 from"node:readline";import{setTimeout as tM3}from"node:timers/promises";S3();p_();c4();ZU();E1();F3();c4();ZU();E1();class Fb4{stateSubject;constructor(J){this.stateSubject=new V4(J)}get state$(){return this.stateSubject}get state(){return this.stateSubject.getValue()}update(J){this.stateSubject.next(J)}}function iM3(J){let Z=new Map;for(let Q of J.messages){if(Q.role!=="user")continue;for(let Y of Q.content){if(Y.type!=="tool_result")continue;if(!("progress"in Y.run))continue;let X=Y.run.progress;if(typeof X==="string"){Z.set(Y.toolUseID,{status:Y.run.status,content:X});continue}if(X&&typeof X==="object"&&"output"in X&&typeof X.output==="string")Z.set(Y.toolUseID,{status:Y.run.status,content:X.output})}}return Z}function nM3(J){if(!J.draft)return null;let Z=zC(J.draft);if(!Z.text&&Z.images.length===0)return null;return Z}function aM3(J){if(!J||!J.text&&J.images.length===0)return"";let Z=[];if(J.text)Z.push({type:"text",text:J.text});if(J.images.length>0)Z.push(...J.images);return Z}async function re0(J,Z){let{thread:Q,threadMeta:Y}=Z,X=Q?.id??Z.threadID??h8(),K=b9.get(X),V=K?.thread??await J.threadService.get(X);if(Q&&!V){let F=await J.threadService.exclusiveSyncReadWriter(X);F.write(Q),await F.asyncDispose(),V=Q}let G=K??await b9.getOrCreateForThread(J,X);if(Z.agentMode&&!V?.agentMode&&(!V||F8(V)===0))await G.handle({type:"agent-mode",mode:Z.agentMode});if(Y&&Q)await J.threadService.updateThreadMeta(X,Y);if(Y&&!Q){let F=J.threadService.observe(X).subscribe((z)=>{if(z.messages.length===0)return;F.unsubscribe(),J.threadService.updateThreadMeta(X,Y).catch(()=>{return})})}if(Z.onFirstAssistantMessage){let F=J.threadService.observe(X).subscribe(async(z)=>{if(P7(z,"assistant"))await Z.onFirstAssistantMessage?.(X),F.unsubscribe()})}return await G.resume(),G}async function zb4(J,Z,Q){await J.validateThreadOwnership?.(Z,Q);let Y=await J.threadService.get(Z)??void 0;return re0(J.workerDeps,{threadID:Z,threadMeta:J.switchThreadVisibility?oG(J.switchThreadVisibility):void 0,agentMode:Y?void 0:J.switchThreadAgentMode,thread:Y,onFirstAssistantMessage:J.onFirstAssistantMessage})}async function qb4(J,Z,Q){let Y=Z?await zb4(J,Z,{nonBlockingOwnershipCheck:Q?.nonBlockingOwnershipCheck??!1}):await J.createThread();return new iV0(J,Y)}class iV0{deps;queueOnSubmitByDefault=!1;restoreTo=this.truncateThread.bind(this);stateTracker;activeThreadHandleSubject;workersByThreadID=new Map;currentWorker;activeThreadHandleValue;activeThreadHandleThreadID;latestStatus={state:"initial"};threadSubscription=null;statusSubscription=null;pendingSkillsSubscription=null;recentThreadIDsSubject=new V4([]);pendingApprovalsSubject=new V4([]);pendingSkillsSubject=new V4([]);threadViewStatesSubject=new V4({});threadTitlesSubject=new V4({});legacyHandoffNavigationSubject=new H4;pendingNavigationInFlightThreadID=null;threadBackStack=[];threadForwardStack=[];subscriptions=[];workerSubscription=null;disposing=!1;constructor(J,Z){this.deps=J;this.currentWorker=Z,this.stateTracker=new Fb4(this.buildPoolState(Z.thread,this.recentThreadIDsSubject.getValue())),this.workersByThreadID.set(Z.thread.id,Z),this.activeThreadHandleValue=this.createHandle(Z.thread.id,Z),this.activeThreadHandleThreadID=Z.thread.id,this.activeThreadHandleSubject=new V4(this.activeThreadHandleValue),this.refreshDerivedState(Z.thread),this.addToRecentThreads(Z.thread.id),this.subscribeToWorker(Z),this.subscribeToPendingApprovals(),this.subscribeToGlobalWorkerStates(),this.subscribeToWorkerTitles()}get threadHandles$(){return this.activeThreadHandleSubject}get threadState$(){return this.stateTracker.state$.pipe(w1((J)=>J.threadState))}get currentThreadState(){return this.stateTracker.state.threadState}get currentThread(){return this.stateTracker.state.currentThread}get currentThreadID(){return this.stateTracker.state.currentThreadID}get recentThreadIDs$(){return this.recentThreadIDsSubject}get recentThreadIDs(){return this.stateTracker.state.recentThreadIDs}get threadTitles$(){return this.threadTitlesSubject}get legacyHandoffNavigation$(){return this.legacyHandoffNavigationSubject}get allConnectedThreadActivityStatuses$(){return this.threadViewStatesSubject}get pendingApprovals$(){return this.pendingApprovalsSubject}get pendingSkills$(){return this.pendingSkillsSubject}getWorkerForExecuteMode(){return this.currentWorker}async createThread(){let J=await this.deps.createThread();this.switchToWorker(J,{recordNavigation:!0})}async switchThread(J){await this.switchToThreadByID(J,{recordNavigation:!0})}canNavigateBack(){return this.threadBackStack.length>0}canNavigateForward(){return this.threadForwardStack.length>0}async navigateBack(){if(!this.canNavigateBack())return;let J=this.currentWorker.thread.id,Z=this.threadBackStack.pop();if(!Z)return;this.threadForwardStack.push(J);try{await this.switchToThreadByID(Z,{recordNavigation:!1})}catch(Q){throw this.threadForwardStack.pop(),this.threadBackStack.push(Z),Q}}async navigateForward(){if(!this.canNavigateForward())return;let J=this.currentWorker.thread.id,Z=this.threadForwardStack.pop();if(!Z)return;this.threadBackStack.push(J);try{await this.switchToThreadByID(Z,{recordNavigation:!1})}catch(Q){throw this.threadBackStack.pop(),this.threadForwardStack.push(Z),Q}}async sendMessage(J){await this.currentWorker.handle({type:"user:message",index:J.editIndex,message:{content:J.content,agentMode:J.agentMode}}),this.maybeMarkLastUserMessageInterrupted(this.currentWorker)}async truncateThread(J){await this.currentWorker.handle({type:"thread:truncate",fromIndex:J})}createHandle(J,Z){let Q=(X)=>{if(this.currentThreadID!==J)throw Error(`ThreadHandle.${X} called for inactive thread ${J}. Current thread is ${this.currentThreadID}.`)},Y=async(X)=>{await Z.handle({type:"thread:truncate",fromIndex:X})};return Hy({thread$:this.deps.threadService.observe(J),threadViewState$:this.threadViewStatesSubject.pipe(w1((X)=>X[J]??{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}})),inferenceErrors$:Z.status.pipe(w1((X)=>X.state==="active"?X.ephemeralError:void 0),f5((X)=>X!==void 0)),toolProgressByToolUseID$:this.deps.threadService.observe(J).pipe(w1((X)=>iM3(X))),pendingApprovals$:this.pendingApprovals$,pendingSkills$:this.pendingSkills$,getCurrentThread:()=>Z.thread,getResolvedTokenUsage:()=>Y7(Z.thread),sendMessage:async(X)=>{Q("sendMessage"),await Z.handle({type:"user:message",index:X.editIndex,message:{content:X.content,agentMode:X.agentMode}}),this.maybeMarkLastUserMessageInterrupted(Z)},restoreTo:async(X)=>{Q("restoreTo"),await Y(X)},queueMessage:async(X)=>{Q("queueMessage"),await Z.handle({type:"user:message-queue:enqueue",message:{content:X}})},discardQueuedMessages:async()=>{Q("discardQueuedMessages"),await Z.handle({type:"user:message-queue:discard"})},setTitle:async(X)=>{Q("setTitle"),await Z.handle({type:"title",value:X}),await this.deps.threadService.flushVersion(J,Z.thread.v)},setVisibility:async(X)=>{Q("setVisibility"),await this.deps.workerDeps.threadService.updateThreadMeta(J,oG(X))},cancelTurn:async()=>{Q("cancelTurn"),await this.maybeCancelActiveTurn(Z)},cancelStreaming:async()=>{Q("cancelStreaming"),await this.maybeCancelActiveTurn(Z)},retryTurn:async()=>{Q("retryTurn"),await Z.retry()},dismissEphemeralError:()=>{Q("dismissEphemeralError"),Z.dismissEphemeralError()},preExecuteMode:async()=>{Q("preExecuteMode"),Z.continueInferenceAfterRejection(!0)},postExecuteMode:async()=>{Q("postExecuteMode");let X=Z.thread.v;await this.deps.threadService.flushVersion(J,X)},setTestEphemeralError:(X)=>{Q("setTestEphemeralError"),Z.setTestEphemeralError(X)},resolveApproval:async(X,K,V)=>{Q("resolveApproval"),this.deps.workerDeps.toolService.resolveApproval(X,K,V)},addPendingSkill:(X)=>{Q("addPendingSkill"),Z.addPendingSkill(X)},removePendingSkill:(X)=>{Q("removePendingSkill"),Z.removePendingSkill(X)},clearPendingSkills:()=>{Q("clearPendingSkills"),Z.clearPendingSkills()},getDraft:async()=>{return Q("getDraft"),nM3(Z.thread)},setDraft:async(X)=>{Q("setDraft"),await Z.handle({type:"draft",content:aM3(X)})},getFilesAffectedByTruncation:async(X)=>{return Q("getFilesAffectedByTruncation"),Z.getFilesAffectedByTruncation(X)},clearPendingNavigation:async()=>{Q("clearPendingNavigation"),await Z.handle({type:"clearPendingNavigation"})},getGuidanceFiles:async(X)=>{let K=this.stateTracker.state.currentThread;if(!K)return[];return(await Wz({filesystem:this.getFilesystemReader(),configService:this.deps.workerDeps.configService,threadService:this.deps.threadService},K,X)).map((G)=>({uri:G.uri,type:G.type}))},invokeBashTool:(X,K)=>{Q("invokeBashTool");let V=Z.invokeBashTool(X,K.abortController.signal,K.hidden);return new k0((G)=>{let F=!1,z=V.subscribe({next:(q)=>G.next(q),error:(q)=>{F=!0,G.error(q)},complete:()=>{F=!0,G.complete()}});return()=>{if(!F)K.abortController.abort();z.unsubscribe()}})}})}maybeMarkLastUserMessageInterrupted(J){let Z=this.stateTracker.state.currentThread;if(!Z)return;if(this.latestStatus.state!=="active")return;let Q=Z.messages.findLast((K)=>K?.role==="assistant"),Y=Q?.state.type==="streaming";if(!(this.latestStatus.inferenceState==="running"||Y))return;if(Y){if(Q.content.some((V)=>V.type==="thinking"&&YX(V)))return}for(let K=Z.messages.length-1;K>=0;K--){let V=Z.messages[K];if(V?.role==="user"&&!V.interrupted){J.handle({type:"user:message:interrupt",messageIndex:K});let G=[...Z.messages];G[K]={...V,interrupted:!0};let F={...Z,messages:G};this.refreshDerivedState(F),this.updateInterruptedMessage(F,K);break}}}updateInterruptedMessage(J,Z){let Q=J.messages[Z];if(!Q||Q.role!=="user"||Q.interrupted)return;let Y=J.messages.map((X,K)=>{if(K!==Z)return X;return{...X,interrupted:!0}});this.refreshDerivedState({...J,messages:Y})}async queueMessage(J){await this.currentWorker.handle({type:"user:message-queue:enqueue",message:{content:J}})}async discardQueuedMessages(){await this.currentWorker.handle({type:"user:message-queue:discard"})}setTitle=async(J)=>{await this.currentWorker.handle({type:"title",value:J}),await this.deps.threadService.flushVersion(this.currentThreadID,this.currentWorker.thread.v)};setVisibility=async(J)=>{await this.deps.workerDeps.threadService.updateThreadMeta(this.currentThreadID,oG(J))};async cancelTurn(){await this.maybeCancelActiveTurn(this.currentWorker)}async cancelStreaming(){await this.maybeCancelActiveTurn(this.currentWorker)}async maybeCancelActiveTurn(J){let Z=this.stateTracker.state.currentThread;if(!Z)return;if(this.latestStatus.state!=="active")return;let Y=Z.messages.findLast((V)=>V?.role==="assistant")?.state.type==="streaming",X=this.hasActiveTools(Z);if(!(this.latestStatus.inferenceState==="running"||this.latestStatus.inferenceState==="retrying"||Boolean(Y)||X))return;this.maybeMarkLastUserMessageInterrupted(J),await J.cancel()}hasActiveTools(J){for(let Z of J.messages){if(Z?.role!=="user")continue;for(let Q of Z.content){if(Q.type!=="tool_result")continue;if(Q.run.status==="in-progress"||Q.run.status==="queued")return!0}}return!1}async retryTurn(){await this.currentWorker.retry()}dismissEphemeralError(){this.currentWorker.dismissEphemeralError()}async resolveApproval(J,Z,Q){this.deps.workerDeps.toolService.resolveApproval(J,Z,Q)}addPendingSkill(J){this.currentWorker.addPendingSkill(J)}removePendingSkill(J){this.currentWorker.removePendingSkill(J)}clearPendingSkills(){this.currentWorker.clearPendingSkills()}async getFilesAffectedByTruncation(J){return this.currentWorker.getFilesAffectedByTruncation(J)}invokeBashTool(J,Z){let Q=this.currentWorker.invokeBashTool(J,Z.abortController.signal,Z.hidden);return new k0((Y)=>{let X=!1,K=Q.subscribe({next:(V)=>Y.next(V),error:(V)=>{X=!0,Y.error(V)},complete:()=>{X=!0,Y.complete()}});return()=>{if(!X)Z.abortController.abort();K.unsubscribe()}})}async createHandoff(J,Z){let Q={toolService:this.deps.workerDeps.toolService,configService:this.deps.workerDeps.configService,skillService:this.deps.workerDeps.skillService,getThreadEnvironment:this.deps.workerDeps.getThreadEnvironment,filesystem:this.getFilesystemReader(),threadService:this.deps.workerDeps.threadService};return(await b9.handoff(this.deps.workerDeps,{threadID:J,goal:Z.goal,images:Z.images,mode:"draft",navigate:!1,agentMode:Z.agentMode??void 0,queuedMessages:Z.queuedMessages,clearQueuedMessages:!0,blockIndex:0,buildSystemPromptDeps:Q,signal:Z.signal,filesystem:this.getFilesystemReader()})).threadID}async clearPendingNavigation(){await this.currentWorker.handle({type:"clearPendingNavigation"})}getFilesystemReader(){return this.deps.workerDeps.osFileSystem}setTestEphemeralError(J){this.currentWorker.setTestEphemeralError(J)}setTestRetryCountdown(J){let Z=Math.max(0,Math.ceil((J.retryAt-Date.now())/1000));this.currentWorker.setTestEphemeralError(Object.assign(Error(J.message),{retryCountdownSeconds:Z}))}async getThreadEnvironment(){return await this.deps.workerDeps.getThreadEnvironment()}async dispose(){if(this.disposing)return;this.disposing=!0,this.cleanupSubscriptions(),await Promise.all(Array.from(this.workersByThreadID.values()).map((J)=>J.asyncDispose())),this.workersByThreadID.clear(),this.pendingApprovalsSubject.complete(),this.pendingSkillsSubject.complete(),this.threadViewStatesSubject.complete(),this.threadTitlesSubject.complete(),this.legacyHandoffNavigationSubject.complete(),this.recentThreadIDsSubject.complete(),this.activeThreadHandleSubject.complete(),this.disposing=!1}async deleteThread(J){if(this.currentWorker.thread.id===J)return;this.workersByThreadID.delete(J),await b9.dispose(J),await this.deps.threadService.delete(J)}subscribeToWorker(J){this.threadSubscription?.unsubscribe(),this.statusSubscription?.unsubscribe(),this.pendingSkillsSubscription?.unsubscribe(),this.threadSubscription=this.deps.threadService.observe(J.thread.id).subscribe((Z)=>{this.refreshDerivedState(Z)}),this.statusSubscription=J.status.subscribe((Z)=>{this.latestStatus=Z,this.updateThreadState(this.stateTracker.state.currentThread)}),this.pendingSkillsSubscription=J.pendingSkills.subscribe((Z)=>{this.pendingSkillsSubject.next(Z)})}subscribeToPendingApprovals(){let J=this.deps.workerDeps.toolService.pendingApprovals$.subscribe((Z)=>{let Q=this.stateTracker.state.currentThreadID,Y=Z.filter((X)=>X.threadId===Q||X.mainThreadId===Q);this.pendingApprovalsSubject.next(Y)});this.subscriptions.push(J)}subscribeToGlobalWorkerStates(){let J=b9.statuses.subscribe((Z)=>{this.threadViewStatesSubject.next(Z)});this.subscriptions.push(J)}subscribeToWorkerTitles(){let J=async(Z)=>{let Q={};await Promise.all(Array.from(Z.keys()).map(async(Y)=>{Q[Y]=await this.deps.threadService.getPrimitiveProperty(Y,"title")??void 0})),this.threadTitlesSubject.next(Q)};this.workerSubscription=b9.workers.subscribe((Z)=>{J(Z)})}setCurrentWorker(J){if(this.workersByThreadID.set(J.thread.id,J),J.thread.id!==this.currentWorker.thread.id)this.addToRecentThreads(J.thread.id);this.currentWorker=J,this.latestStatus={state:"initial"},this.refreshDerivedState(J.thread),this.subscribeToWorker(J)}refreshDerivedState(J){let Z=this.buildPoolState(J,this.recentThreadIDsSubject.getValue());this.threadTitlesSubject.next({...this.threadTitlesSubject.getValue(),[J.id]:J.title??void 0}),this.stateTracker.update(Z),this.maybeEmitLegacyHandoffNavigation(J),this.emitActiveThreadHandleIfNeeded()}maybeEmitLegacyHandoffNavigation(J){let Z=J.pendingNavigation;if(!Z||J.id!==this.currentThreadID)return;if(this.pendingNavigationInFlightThreadID===Z)return;this.pendingNavigationInFlightThreadID=Z,this.legacyHandoffNavigationSubject.next(Z),this.currentWorker.handle({type:"clearPendingNavigation"}).catch(()=>{return}).finally(()=>{if(this.pendingNavigationInFlightThreadID===Z)this.pendingNavigationInFlightThreadID=null})}buildPoolState(J,Z){let Q=wS(J,this.latestStatus);return{threadState:jR({thread:J,viewState:Q,resolvedTokenUsage:Y7(J)}),currentThread:J,currentThreadID:J.id,recentThreadIDs:Z}}updateThreadState(J){this.refreshDerivedState(J)}addToRecentThreads(J){let Z=[...this.recentThreadIDsSubject.getValue()],Q=Z.indexOf(J);if(Q!==-1)Z.splice(Q,1);if(Z.unshift(J),Z.length>50)Z.pop();this.recentThreadIDsSubject.next(Z),this.stateTracker.update({...this.stateTracker.state,recentThreadIDs:Z})}switchToWorker(J,Z){let Q=this.currentWorker.thread.id;if(this.workersByThreadID.set(J.thread.id,J),this.setCurrentWorker(J),Z.recordNavigation&&J.thread.id!==Q)this.recordNavigation(Q)}async switchToThreadByID(J,Z){let Q=this.workersByThreadID.get(J)??await zb4(this.deps,J);this.switchToWorker(Q,Z)}recordNavigation(J){this.threadBackStack.push(J),this.threadForwardStack=[]}cleanupSubscriptions(){this.threadSubscription?.unsubscribe(),this.statusSubscription?.unsubscribe(),this.pendingSkillsSubscription?.unsubscribe(),this.workerSubscription?.unsubscribe(),this.threadSubscription=null,this.statusSubscription=null,this.pendingSkillsSubscription=null,this.workerSubscription=null;for(let J of this.subscriptions)J.unsubscribe();this.subscriptions=[]}emitActiveThreadHandleIfNeeded(){if(this.activeThreadHandleThreadID!==this.currentThreadID)this.activeThreadHandleValue=this.createHandle(this.currentThreadID,this.currentWorker),this.activeThreadHandleThreadID=this.currentThreadID;this.activeThreadHandleSubject.next(this.activeThreadHandleValue)}}function b4(J,Z){let Q=Z?` ${JSON.stringify(Z)}`:"";process.stderr.write(`[thread-pool] ${J}${Q}
|
|
7135
7135
|
`)}function Hb4(J,Z){process.stdout.write(`${JSON.stringify({type:"state",reason:J,state:Z})}
|
|
7136
7136
|
`)}function nV0(J,Z){process.stdout.write(`${JSON.stringify({type:J,...Z})}
|
|
7137
7137
|
`)}function eM3(J){if(!J)return[];return $A3(J).map((Z)=>Z.trim()).filter((Z)=>Z.length>0)}function $A3(J){let Z=[],Q="";for(let Y of J){if(Y===";"||Y===`
|
|
@@ -7433,7 +7433,7 @@ ${X}`,Z);this.line=Q,this.column=Y,this.codeblock=X}}/*!
|
|
|
7433
7433
|
`),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(`
|
|
7434
7434
|
`))}return new p0({decoration:{color:Q.colorScheme.background,border:K4.all(new X4(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 i01 extends y${chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=cG0}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new c01({chartData:this.chartData,highlightIndex:this.highlightIndex,showAxes:this.showAxes,colors:this.colors})}updateRenderObject(J){let Z=J;Z.chartData=this.chartData,Z.highlightIndex=this.highlightIndex,Z.showAxes=this.showAxes,Z.colors=this.colors,Z.markNeedsLayout()}}function fg4(J,Z,Q,Y,X,K,V){if(K<=0)return null;switch(J){case"horizontal-bar":{let 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 pP3(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 dP3(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 cP3(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 lP3(J,Z,Q,Y,X,K,V){let G;try{let D=b1.of(J),B=x0.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,tY0(D),()=>{c3(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}
|
|
7435
7435
|
`,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(`
|
|
7436
|
-
`))}if(D)W.push(new C(" ",q)),W.push(new C("Total: ",q)),W.push(new C(K(B),z))}return new p0({decoration:{color:G.background,border:K4.all(new X4(G.border,1,"rounded"))},child:new J0({text:new C(void 0,void 0,W)})})}oD();n0();k9();LE();T7();S3();v2();Cd();xX();tZ();VY();ZQ();kA();c4();ig();pP();E1();n0();tZ();class n01{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.1775563890-g5b477c"},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 ML extends c0{props;constructor(J){super();this.props=J}createState(){return new ug4}}class ug4 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 bg4 extends m0{controller=new a7;focusNode=new L6({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=x0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,G=K4.all(new X4(Q.foreground,1,"solid")),F=new JX({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 p0({decoration:{color:Q.background},child:new J0({text:new C(">",new g({color:Q.foreground}))})}),new l1({child:F})]}),q=new p0({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 p0({padding:C0.symmetric(1,0),child:new J0({text:new C("",void 0,W)})});return new p0({decoration:{border:G,color:Q.background},padding:C0.all(1),child:new b0({children:[q,new R0({height:1}),z,new T5,H]})})}}class ha extends c0{props;constructor(J){super();this.props=J}createState(){return new bg4}}ZQ();class hg4 extends m0{controller=new a7;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new L6({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>=xV)return!1;let Z=await YL(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=x0.of(J),{colors:Q,app:Y}=Z,K=L4.of(J).size.height,V=Math.max(Math.floor(K*0.5),10),G=new hU({controller:this.controller,triggers:[new dq],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:Q6.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),F=new Z6({focusNode:this.focusNode,child:G}),z=new p0({constraints:new j1({maxHeight:V}),padding:C0.symmetric(1,0),child:F}),q=new p0({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 p0({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 R0({height:1}),new l1({child:z}),new R0({height:1}),W];return new p0({decoration:{border:K4.all(new X4(Q.foreground,1,"solid")),color:Q.background},padding:C0.all(1),child:new b0({children:H})})}}class a01 extends c0{props;constructor(J){super();this.props=J}createState(){return new hg4}}function gg4(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 o01 extends c1{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)=>gg4(X.pubDate).length));return new z9({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=x0.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 R0({width:N,child:D1.end([new J0({text:new C(B,new g({color:U}))})])});return new p0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new D1({children:[new l1({child:new J0({text:new C(X.title,new g({color:H})),overflow:"ellipsis",maxLines:1})}),new R0({width:2}),D(gg4(X.pubDate),Q)]})})}})}}UE();class r01 extends c0{createState(){return new mg4}}class mg4 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=x0.of(J).colors;return new J0({text:new C("●",new g({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function iP3(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 gV0.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 s01(J,Z,Q){return new J0({text:new C(`${J}${Z}`,new g({color:Q})),maxLines:1})}function nP3(J,Z,Q,Y){return[s01("+",J,Y.success),T5.horizontal(1),s01("~",Z,Y.warning),T5.horizontal(1),s01("-",Q,Y.destructive)]}function aP3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class iG0 extends c0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new pg4}}class pg4 extends m0{spinner=new O5;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=iP3(z),W=Math.max(0,...q.map((L)=>L.description.timeAgo.length)),H=x0.of(J),U=new l0({padding:C0.symmetric(0,1),child:new Z4({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=I7(L);return B};return new z9({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(!aP3(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=x0.of(M),{app:j,colors:I}=A,S=O?j.selectionBackground:void 0,P=O?j.selectionForeground:I.foreground,b=I.mutedForeground,p=(s,H0)=>new R0({width:H0,child:D1.end([new J0({text:new C(s,new g({color:b}))})])}),x=Z.threadViewStates[L.id],k=[],f=L.relationshipType==="handoff",d=new Ia({connectorColor:I.mutedForeground});if(L.depth>0){let s=[],H0=L.ancestorsAreLast.slice(1);for(let w0 of H0)s.push(new C(d.getAncestorPrefix(w0),new g({color:d.connectorColor,dim:d.connectorDim})));let r=L.isLast?d.elbow:d.tee,q0=d.getConnectorText(r);s.push(new C(q0,new g({color:d.connectorColor,dim:d.connectorDim}))),k.push(new J0({text:new C("",void 0,s)}))}let m=[],h=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(h)m.push(new J0({text:h}));if(eM(x))m.push(new r01),m.push(new R0({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 l1({child:new J0({text:new C(n,new g({color:P})),overflow:"ellipsis",maxLines:1})})),m.push(new R0({width:2})),L.diffStats&&(L.diffStats.added>0||L.diffStats.changed>0||L.diffStats.deleted>0)){let s=O?{success:b,warning:b,destructive:b}:I;m.push(...nP3(L.diffStats.added,L.diffStats.changed,L.diffStats.deleted,s)),m.push(new R0({width:2}))}return m.push(p(L.description.timeAgo,W)),new p0({decoration:S?{color:S}:void 0,padding:C0.symmetric(2,0),child:new D1({children:[...k,...m]})})}})}}n0();class sK{message;constructor(J){this.message=J}}class L7{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 nG0(J){if(J instanceof sK)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"}}n0();tQ();$A();xX();tZ();c4();U4();pP();var e01=W4(WH(),1);import{execSync as SR}from"node:child_process";import{writeFile as ky}from"node:fs/promises";import oP3 from"node:os";import aq from"node:path";var dg4="c446b2e9b16cdc06df2ec285894d6421",rP3="5ea19563777f4ade8707fc56f7e7a388",sP3="amp-thread-worker",cg4=[{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 tP3(J){return!!J&&typeof J==="object"&&"usesDtw"in J}function jL(J){if(!J||!tP3(J.meta))return!1;return J.meta.usesDtw===!0}function $11(J){let Z=new URL(`https://dash.cloudflare.com/${dg4}/workers/durable-objects/view/${rP3}/studio`);return Z.searchParams.set("name",J),Z.searchParams.set("jurisdiction","none"),Z.toString()}function J11(J){let Z=new URL(`https://dash.cloudflare.com/${dg4}/workers/services/view/${sP3}/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 eP3(J,Z){if(fW(J))return`amp dtw-curl ${Z}`;return`AMP_URL=${JSON.stringify(J)} pnpm -C cli cli -- dtw-curl ${Z}`}function Z11(J,Z){let Q=eP3(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 ga(J,Z,Q){let Y=`select(.pid == ${Z})`,X=ma(Q);return`${J==="snapshot"?`tail -n 10000 ${X}`:`tail -f ${X}`} | jq -C '${Y}'`}function ma(J){return J.path??S9(J.uri)}function lg4(J,Z,Q){let Y=ga("snapshot",J,Z);return Q?`${Y} | ${Q}`:Y}function ig4(J,Z){return Z11(J,Z).map(({label:Q,command:Y})=>`# ${Q}
|
|
7436
|
+
`))}if(D)W.push(new C(" ",q)),W.push(new C("Total: ",q)),W.push(new C(K(B),z))}return new p0({decoration:{color:G.background,border:K4.all(new X4(G.border,1,"rounded"))},child:new J0({text:new C(void 0,void 0,W)})})}oD();n0();k9();LE();T7();S3();v2();Cd();xX();tZ();VY();ZQ();kA();c4();ig();pP();E1();n0();tZ();class n01{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.1775571702-gac76fb"},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 ML extends c0{props;constructor(J){super();this.props=J}createState(){return new ug4}}class ug4 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 bg4 extends m0{controller=new a7;focusNode=new L6({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=x0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,G=K4.all(new X4(Q.foreground,1,"solid")),F=new JX({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 p0({decoration:{color:Q.background},child:new J0({text:new C(">",new g({color:Q.foreground}))})}),new l1({child:F})]}),q=new p0({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 p0({padding:C0.symmetric(1,0),child:new J0({text:new C("",void 0,W)})});return new p0({decoration:{border:G,color:Q.background},padding:C0.all(1),child:new b0({children:[q,new R0({height:1}),z,new T5,H]})})}}class ha extends c0{props;constructor(J){super();this.props=J}createState(){return new bg4}}ZQ();class hg4 extends m0{controller=new a7;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new L6({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>=xV)return!1;let Z=await YL(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=x0.of(J),{colors:Q,app:Y}=Z,K=L4.of(J).size.height,V=Math.max(Math.floor(K*0.5),10),G=new hU({controller:this.controller,triggers:[new dq],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:Q6.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),F=new Z6({focusNode:this.focusNode,child:G}),z=new p0({constraints:new j1({maxHeight:V}),padding:C0.symmetric(1,0),child:F}),q=new p0({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 p0({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 R0({height:1}),new l1({child:z}),new R0({height:1}),W];return new p0({decoration:{border:K4.all(new X4(Q.foreground,1,"solid")),color:Q.background},padding:C0.all(1),child:new b0({children:H})})}}class a01 extends c0{props;constructor(J){super();this.props=J}createState(){return new hg4}}function gg4(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 o01 extends c1{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)=>gg4(X.pubDate).length));return new z9({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=x0.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 R0({width:N,child:D1.end([new J0({text:new C(B,new g({color:U}))})])});return new p0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new D1({children:[new l1({child:new J0({text:new C(X.title,new g({color:H})),overflow:"ellipsis",maxLines:1})}),new R0({width:2}),D(gg4(X.pubDate),Q)]})})}})}}UE();class r01 extends c0{createState(){return new mg4}}class mg4 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=x0.of(J).colors;return new J0({text:new C("●",new g({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function iP3(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 gV0.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 s01(J,Z,Q){return new J0({text:new C(`${J}${Z}`,new g({color:Q})),maxLines:1})}function nP3(J,Z,Q,Y){return[s01("+",J,Y.success),T5.horizontal(1),s01("~",Z,Y.warning),T5.horizontal(1),s01("-",Q,Y.destructive)]}function aP3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class iG0 extends c0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new pg4}}class pg4 extends m0{spinner=new O5;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=iP3(z),W=Math.max(0,...q.map((L)=>L.description.timeAgo.length)),H=x0.of(J),U=new l0({padding:C0.symmetric(0,1),child:new Z4({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=I7(L);return B};return new z9({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(!aP3(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=x0.of(M),{app:j,colors:I}=A,S=O?j.selectionBackground:void 0,P=O?j.selectionForeground:I.foreground,b=I.mutedForeground,p=(s,H0)=>new R0({width:H0,child:D1.end([new J0({text:new C(s,new g({color:b}))})])}),x=Z.threadViewStates[L.id],k=[],f=L.relationshipType==="handoff",d=new Ia({connectorColor:I.mutedForeground});if(L.depth>0){let s=[],H0=L.ancestorsAreLast.slice(1);for(let w0 of H0)s.push(new C(d.getAncestorPrefix(w0),new g({color:d.connectorColor,dim:d.connectorDim})));let r=L.isLast?d.elbow:d.tee,q0=d.getConnectorText(r);s.push(new C(q0,new g({color:d.connectorColor,dim:d.connectorDim}))),k.push(new J0({text:new C("",void 0,s)}))}let m=[],h=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(h)m.push(new J0({text:h}));if(eM(x))m.push(new r01),m.push(new R0({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 l1({child:new J0({text:new C(n,new g({color:P})),overflow:"ellipsis",maxLines:1})})),m.push(new R0({width:2})),L.diffStats&&(L.diffStats.added>0||L.diffStats.changed>0||L.diffStats.deleted>0)){let s=O?{success:b,warning:b,destructive:b}:I;m.push(...nP3(L.diffStats.added,L.diffStats.changed,L.diffStats.deleted,s)),m.push(new R0({width:2}))}return m.push(p(L.description.timeAgo,W)),new p0({decoration:S?{color:S}:void 0,padding:C0.symmetric(2,0),child:new D1({children:[...k,...m]})})}})}}n0();class sK{message;constructor(J){this.message=J}}class L7{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 nG0(J){if(J instanceof sK)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"}}n0();tQ();$A();xX();tZ();c4();U4();pP();var e01=W4(WH(),1);import{execSync as SR}from"node:child_process";import{writeFile as ky}from"node:fs/promises";import oP3 from"node:os";import aq from"node:path";var dg4="c446b2e9b16cdc06df2ec285894d6421",rP3="5ea19563777f4ade8707fc56f7e7a388",sP3="amp-thread-worker",cg4=[{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 tP3(J){return!!J&&typeof J==="object"&&"usesDtw"in J}function jL(J){if(!J||!tP3(J.meta))return!1;return J.meta.usesDtw===!0}function $11(J){let Z=new URL(`https://dash.cloudflare.com/${dg4}/workers/durable-objects/view/${rP3}/studio`);return Z.searchParams.set("name",J),Z.searchParams.set("jurisdiction","none"),Z.toString()}function J11(J){let Z=new URL(`https://dash.cloudflare.com/${dg4}/workers/services/view/${sP3}/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 eP3(J,Z){if(fW(J))return`amp dtw-curl ${Z}`;return`AMP_URL=${JSON.stringify(J)} pnpm -C cli cli -- dtw-curl ${Z}`}function Z11(J,Z){let Q=eP3(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 ga(J,Z,Q){let Y=`select(.pid == ${Z})`,X=ma(Q);return`${J==="snapshot"?`tail -n 10000 ${X}`:`tail -f ${X}`} | jq -C '${Y}'`}function ma(J){return J.path??S9(J.uri)}function lg4(J,Z,Q){let Y=ga("snapshot",J,Z);return Q?`${Y} | ${Q}`:Y}function ig4(J,Z){return Z11(J,Z).map(({label:Q,command:Y})=>`# ${Q}
|
|
7437
7437
|
${Y}`).join(`
|
|
7438
7438
|
|
|
7439
7439
|
`)}function t01(J){if(J===void 0||!Number.isFinite(J)||J<=0)return"n/a";return`${yz(J)} ago (\`${new Date(J).toISOString()}\`)`}function $C3(J){if(!J)return"n/a";let Z=Date.parse(J);if(!Number.isFinite(Z))return`\`${J}\``;return t01(Z)}function AL(J){if(J===void 0||J===null)return"n/a";return`\`${String(J)}\``}function aG0(J,Z="#"){let{thread:Q,threadViewState:Y}=J,X=(V)=>`${Z} ${V}`,K=[X("Thread"),`- ID: \`${Q.id}\``,`- Title: ${A10(Q)}`,`- URL: \`${tW(new URL(J.ampURL),Q.id).toString()}\``,`- Created: ${t01(Q.created)}`,`- Agent mode: ${AL(Q.agentMode)}`,`- Effective mode: \`${J.effectiveAgentMode}\``,`- DTW backed: ${jL(Q)?"yes":"no"}`,`- Executor type: ${AL(Q.meta?.executorType)}`,`- Messages: \`${Q.messages.length}\` total / \`${F8(Q)}\` human / \`${Q.queuedMessages?.length??0}\` queued`];if(Q.meta?.status!==void 0)K.push(`- Merge status: ${AL(Q.meta.status??"null")}`);if(Q.meta?.lastKnownAgentState)K.push(`- Last known agent state: \`${Q.meta.lastKnownAgentState.state}\` at ${$C3(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: \`${fW(J.ampURL)?Q7:J.ampURL}\``,`- Thread pool mode: \`${J.threadPoolIsDTW?"dtw":"worker"}\``,`- Connection state: ${AL(J.transportState)}`,`- Connection role: ${AL(J.transportRole)}`,`- Processing: ${J.isProcessing?"yes":"no"}`,`- PID: ${AL(J.pid)}`,`- Client ID: ${AL(J.clientId)}`),J.logFile)K.push(`- Log file: \`${ma(J.logFile)}\``);if(!Y)return K.push("",X("View State"),"- No live thread view state available."),K.join(`
|
|
@@ -7654,7 +7654,7 @@ ${t.content||""}`:t.content||"",_0=[],r0=t.baseDir.startsWith("file://")?_F0(t.b
|
|
|
7654
7654
|
`),process.exit(1)}process.stdout.write(await gk3(F.result.displayText)+`
|
|
7655
7655
|
`),process.exit(0)})}$A();import{stdout as mk3}from"node:process";function pk3({version:J,buildTimestamp:Z,buildType:Q}){let Y=Q==="dev"?"dev":"released",X=Z?new Date(Z):null,K=X&&!Number.isNaN(X.getTime())?`, ${yz(X)} ago`:"";return`${J} (${Y}${Z?` ${Z}`:""}${K})`}function Ac4(J){mk3.write(`${pk3(J)}
|
|
7656
7656
|
`)}function jc4(J,Z){J.option("-V, --version","Print the version number and exit",()=>{Ac4(Z),process.exit(0)}),J.command("version").description("Print the version number and exit").action(()=>{Ac4(Z),process.exit(0)})}var Gu3=VD.join(vX,"logs","headless.log"),A51=VD.join(wv,"device-id.json"),in4=`cli-tui-${Ja4(16).toString("hex")}`;async function Fu3(){for(let J of EE)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(() => W4(Kx(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){l$.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
|
|
7657
|
-
`)}function zu3(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 E7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")lJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")lJ("experimental.agentMode",Z.mode)}function Xa4(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 qu3(J){try{return await Qa4(J,"utf-8")}catch{return J}}async function j51(J,Z,Q){let Y=Xa4(J,Z);if(!Y)return;let X=_6(Q)?Q.features:[],K=_6(Q)?Q.user.email:void 0;if(!To(X,S7.HARNESS_SYSTEM_PROMPT)&&!Ka4(K))throw new C1("You are not allowed to do this.",1);lJ("systemPrompt",await qu3(Y))}function Ka4(J){return!!(J&&d00(J))}function To(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function R51(J){return(J.userEmail?D$(J.userEmail):!1)||To(J.features,S7.DTW_TUI)}function nn4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new C1("This TUI mode is not enabled for your user;",1)}function I51(J,Z){if(typeof J==="boolean")return J;if(!_6(Z))return!1;return R51({userEmail:Z.user.email,features:Z.features})}function Wu3(J){return J!=="pending"}function Vx(J){if(!_6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function Hu3(J){let Z=Vx(J);if(Z)return Z.id;if(Zz(J))throw Error(J.error.message);throw Error("unreachable")}function Uu3(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 wz0(J){let Y=Uu3(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 C1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function an4(J){if(!a6.write(J))await Yu3(a6,"drain")}var on4=[{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??gK,description:`Custom settings file path (overrides the default location ${gK})`},{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 ${fn0})`},{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:n7(),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:aF.SMART.key,description:`Set the agent mode (${fX({},!1).map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:fX().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}],rn4=(J)=>("deprecated"in J)&&J.deprecated===!0,Du3=(J)=>("hidden"in J)&&J.hidden===!0,Bu3=(J)=>("default"in J),Nu3=(J)=>("default"in J)?J.default:void 0,Va4=[{name:"toggle-skills-count",entryPoint:Te0}];function wu3(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 C1(E3.unknownCommand(Q),1,V)}}async function C51(J){return{...J,getThreadEnvironment:WZ,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new nV(J.fileSystem),generateThreadTitle:s80,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>JJ(J.configService),pluginService:J.pluginService}}function Ga4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:WZ,filesystem:J.fileSystem,threadService:J.threadService}}var Lz0=G1.file(Ya4.homedir()),P51=process.env.XDG_CONFIG_HOME?G1.file(process.env.XDG_CONFIG_HOME):V1.joinPath(Lz0,".config");function Lu3(J){return Rq4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){if(process.platform==="darwin"&&Z==="idle"&&J.isTUIVoiceNotifEnabled())jq4();else um0(Z);let Q=yX0(),Y=lo0();if((!Q||Y||ZC4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(PU("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(PU("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(yX0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}async function T9(J,Z,Q){let Y=Q?.deferAuth??!1;Tf1("0.0.
|
|
7657
|
+
`)}function zu3(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 E7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")lJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")lJ("experimental.agentMode",Z.mode)}function Xa4(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 qu3(J){try{return await Qa4(J,"utf-8")}catch{return J}}async function j51(J,Z,Q){let Y=Xa4(J,Z);if(!Y)return;let X=_6(Q)?Q.features:[],K=_6(Q)?Q.user.email:void 0;if(!To(X,S7.HARNESS_SYSTEM_PROMPT)&&!Ka4(K))throw new C1("You are not allowed to do this.",1);lJ("systemPrompt",await qu3(Y))}function Ka4(J){return!!(J&&d00(J))}function To(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function R51(J){return(J.userEmail?D$(J.userEmail):!1)||To(J.features,S7.DTW_TUI)}function nn4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new C1("This TUI mode is not enabled for your user;",1)}function I51(J,Z){if(typeof J==="boolean")return J;if(!_6(Z))return!1;return R51({userEmail:Z.user.email,features:Z.features})}function Wu3(J){return J!=="pending"}function Vx(J){if(!_6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function Hu3(J){let Z=Vx(J);if(Z)return Z.id;if(Zz(J))throw Error(J.error.message);throw Error("unreachable")}function Uu3(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 wz0(J){let Y=Uu3(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 C1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function an4(J){if(!a6.write(J))await Yu3(a6,"drain")}var on4=[{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??gK,description:`Custom settings file path (overrides the default location ${gK})`},{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 ${fn0})`},{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:n7(),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:aF.SMART.key,description:`Set the agent mode (${fX({},!1).map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:fX().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}],rn4=(J)=>("deprecated"in J)&&J.deprecated===!0,Du3=(J)=>("hidden"in J)&&J.hidden===!0,Bu3=(J)=>("default"in J),Nu3=(J)=>("default"in J)?J.default:void 0,Va4=[{name:"toggle-skills-count",entryPoint:Te0}];function wu3(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 C1(E3.unknownCommand(Q),1,V)}}async function C51(J){return{...J,getThreadEnvironment:WZ,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new nV(J.fileSystem),generateThreadTitle:s80,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>JJ(J.configService),pluginService:J.pluginService}}function Ga4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:WZ,filesystem:J.fileSystem,threadService:J.threadService}}var Lz0=G1.file(Ya4.homedir()),P51=process.env.XDG_CONFIG_HOME?G1.file(process.env.XDG_CONFIG_HOME):V1.joinPath(Lz0,".config");function Lu3(J){return Rq4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){if(process.platform==="darwin"&&Z==="idle"&&J.isTUIVoiceNotifEnabled())jq4();else um0(Z);let Q=yX0(),Y=lo0();if((!Q||Y||ZC4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(PU("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(PU("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(yX0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}async function T9(J,Z,Q){let Y=Q?.deferAuth??!1;Tf1("0.0.1775571702-gac76fb");let X=v10({storage:J.settings,secretStorage:J.secrets,workspaceRoot:k0.of(G1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:Lz0,userConfigDir:P51});ju4(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...
|
|
7658
7658
|
`);let h=await Ou3(J),n=await J.secrets.get("apiKey",J.ampURL);if(_.info("Login flow completed",{success:h,storedKeyPresent:Boolean(n),ampURL:J.ampURL}),!h)await EU(),process.exit(1);V=!0}}{let m=await X.getLatest(),h=m.settings.url,n=m.secrets.isSet?.[h];_.info("Config secrets state after login",{configURL:h,apiKeySet:n?.apiKey??!1})}let G=I1(JJ(X).pipe(f5(Wu3))),F=Y?"pending":await G;if(!Y)_.info("Server status resolved",{status:"ready",isAuthenticated:_6(F),isError:Zz(F),errorMessage:Zz(F)?F.error.message:void 0});let z=G.then((m)=>Hu3(m)),{toolService:q,dispose:W}=MJ0({configService:X}),H=new Map,U=()=>H.clear(),D=new c_0(X,J.settings.getWorkspaceRootPath()),B=vt1({configService:X,filesystem:I8}),N=Pa1({configService:X,trustStore:D,skillMCPServers:B.skillMCPServers,createOAuthProvider:async(m,h,n)=>{let c=`${m}:${h}`,s=H.get(c);if(s)return _.debug("Reusing existing OAuth provider for server",{serverName:m,serverUrl:h}),s;_.debug("Creating OAuth provider for server",{serverName:m,serverUrl:h});let H0=(async()=>{let r=new _E(J.secrets),q0=await r.getClientInfo(m,h),w0=n?.scopes??q0?.scopes,L0=jI4();_.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?AI4():MI4(m);let V0=new jR0({storage:r,serverName:m,serverUrl:h,clientId:n?.clientId??q0?.clientId,clientSecret:n?.clientSecret??q0?.clientSecret,authUrl:n?.authUrl??q0?.authUrl,tokenUrl:n?.tokenUrl??q0?.tokenUrl,scopes:w0,headlessAuthHandler:e});return _.debug("OAuth provider created",{serverName:m,serverUrl:h,hasManualClientId:!!(n?.clientId??q0?.clientId),willUseDCR:!(n?.clientId??q0?.clientId),scopes:w0,headlessMode:L0,executeMode:J.executeMode}),V0})();return H.set(c,H0),H0}}),w=lg0({configService:X,filesystem:I8,spawn:b$0}),L;if(J.executeMode){let m=await RG4({toolService:q,providers:[N,w],initialTimeout:15000});L=m.registrations;for(let[h,n]of m.initErrors)_.warn(`${h} provider initialization slow or failed:`,n)}else L=ig0({toolService:q,providers:[N,w]});if(Z.jetbrains)BE("JetBrains");else if(Z.ide&&VP4())BE("VS Code");else if(Z.ide&&GP4())BE("Neovim");else if(Z.ide){let m=await Fu3();if(m){let h=d10(m.ideName);if(h)BE(h)}}if(J.executeMode)Sf1(!0);let O,E=$J.status.pipe(w1((m)=>Boolean(m.connected&&m.authenticated&&m.ideName&&wu1(m.ideName))),g4()).subscribe((m)=>{if(m){if(!O)O=q.registerTool(jG4)}else O?.dispose(),O=void 0}),M;if(!J.executeMode){let m=await J.settings.get("fuzzy.alwaysIncludePaths")??[];M=new PY0(process.cwd(),{alwaysIncludePaths:m},!0)}else M=new class extends PY0{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let A=new iS0(q80(X),{maxThreads:200});_.info("Starting Amp background services");let j=Z.takeMeBack?!1:void 0,I=I51(j,F),S=new fe0,P=process.env.PLUGINS??"off",b=Z.headless?Gu4():void 0,p=b??new PV0({configService:X}),x=p instanceof PV0?p:void 0;if(x)x.pluginExecutorKind=I?"local":"unknown";let k=KT0({configService:X,fileSystem:I8,platform:p,internalPlugins:Va4,pluginFilter:P}),f=Mo1({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:I8,terminal:S,pluginService:k,pluginPlatform:x,headlessPluginPlatform:b,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 Ou3(J){if(!J.executeMode){if(!await jX0("Would you like to log in to Amp? [(y)es, (n)o]: "))return a6.write(`Login cancelled. Run the command again to retry.
|
|
7659
7659
|
`),!1}return await Fa4(J)}async function Fa4(J){let Z=Ja4(32).toString("hex"),Q=await Cv(J.ampURL,Z),Y=new AbortController;try{await PV(Q,Y.signal)}catch(K){_.error("Error opening browser",{error:K})}let X=await Cv(J.ampURL,Z,!1);a6.write(`If your browser does not open automatically, visit:
|
|
7660
7660
|
|
|
@@ -7662,7 +7662,7 @@ ${g0.blue.bold(X)}
|
|
|
7662
7662
|
|
|
7663
7663
|
`);try{return await A_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}),l$.write(`
|
|
7664
7664
|
Login failed: ${K instanceof Error?K.message:String(K)}
|
|
7665
|
-
`),!1}}function sn4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function Eu3(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 C1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!B9(Y.threadId))throw new C1("Create response did not include a valid thread ID",1);return Y.threadId}function Mu3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function Au3(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 C1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!Mu3(Q))throw new C1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function ju3(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 Ru3(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 C1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function Iu3(J){let Z=new rN().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)Cj(),process.exit(0);let N=B.originalError??B;NR4(N)}),jc4(Z,{version:"0.0.
|
|
7665
|
+
`),!1}}function sn4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function Eu3(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 C1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!B9(Y.threadId))throw new C1("Create response did not include a valid thread ID",1);return Y.threadId}function Mu3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function Au3(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 C1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!Mu3(Q))throw new C1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function ju3(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 Ru3(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 C1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function Iu3(J){let Z=new rN().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)Cj(),process.exit(0);let N=B.originalError??B;NR4(N)}),jc4(Z,{version:"0.0.1775571702-gac76fb",buildTimestamp:"2026-04-07T14:25:40.862Z",buildType:"'release'"}),Z.addHelpText("after",YP4()),Z.configureHelp({formatHelp:XP4}),Z.command("logout").description("Log out by removing stored API key").action(async(B,N)=>{let w=N.optsWithGlobals(),L=await P3(w);await yu3(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 P3(w);await vu3(L,await _i(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 P3(L);await aR4(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 P3(w);await oR4(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",`
|
|
7666
7666
|
Actions:
|
|
7667
7667
|
create Create a new DTW thread and print its ID
|
|
7668
7668
|
add-message <message> Send a user message and wait for message_added
|
|
@@ -7726,8 +7726,8 @@ ${M}
|
|
|
7726
7726
|
|
|
7727
7727
|
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 Pu3(J){_.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new Pa({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:WZ,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new nV(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 Cu3(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await Fy()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await Fy()).trimEnd(),stdinInput:null}}function _u3(J,Z,Q){if(J.remote&&!Z)throw new C1("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(J.streamJson&&!Z)throw new C1("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new C1("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new C1("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new C1("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new C1("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 C1("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 C1("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"
|
|
7728
7728
|
Or pipe via stdin: echo "your message" | amp --execute`)}async function Oz0(J,Z,Q,Y){let X=process.hrtime.bigint(),K=(e,V0)=>{let i=Number(process.hrtime.bigint()-V0)/1e6,a=wO4();_.info("Startup phase",{phase:e,phaseMs:Math.round(i),sinceMainMs:a===null?void 0:Math.round(a)})},{userInput:V,stdinInput:G}=await Cu3(Z),F=!!Z.streamJson||!!Z.streamJsonThinking;_u3({...Z,streamJson:F},J.executeMode,V),E7(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 C51(H);K("runMainThread:createWorkerDeps",z);let{serverStatus:D}=H;if(!W&&Zz(D)){let e=Gv(Error(D.error.message));if(e.message===E3.networkOffline||e.message===E3.networkTimeout)throw wz0(J.ampURL);throw new C1(E3.invalidAPIKey,1)}let B=_6(D)?D:null,N=B?.user.email,w=Ka4(N),L=R51({userEmail:N,features:B?.features}),O=Z.takeMeBack?!1:void 0,E=B!==null&&I51(O,B);if(!W)await j51(Q,Z,D);let M=Vx(D),A=M?.features??[],j=M?.team??null,I=IV0(Z,M);if(I instanceof Error)C3(I.message);if((J.executeMode||F)&&m8(Z.mode)&&!w)throw new C1(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(B&&!wE(Z.mode,N))throw new C1(`Agent mode '${Z.mode}' is only available for Amp employees`,1);if(J.executeMode&&Z.remote)await qu4(V,G,H.configService),await H.asyncDispose(),process.exit(0);if(Z.headless){if(process.env.AMP_EXECUTOR!=="1"&&(!N||!D$(N)))throw new C1("Headless DTW mode is only available for Amp employees",1);let V0=await H.secretStorage.get("apiKey",J.ampURL);if(!V0)throw new C1("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&&!B9(i))throw new C1(`Invalid thread ID: ${i}`,1);let a=i?void 0:await du3({dependencies:H,visibility:I??void 0,usesThreadActors:Z.threadActors?!0:void 0}),t=i??a?.threadId;if(!t)throw new C1("Failed to resolve headless thread ID",1);let $0=await CI4(t);if($0.status==="already-running")await H.asyncDispose(),await EU(),process.exit(0);try{await OI4({ampURL:J.ampURL,apiKey:V0,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 EU(),process.exit(0)}let S=J.executeMode?void 0:async(e)=>So(e,"interactive"),P={threadService:H.threadService,workerDeps:U,createThread:async()=>{let e=W?await H.serverStatusPromise:D,V0=await WY0(J.settings,process.cwd(),Vx(e),I);if(V0 instanceof Error)C3(V0.message);return re0(U,{threadMeta:V0?oG(V0):void 0,agentMode:Z.mode,onFirstAssistantMessage:S})},validateThreadOwnership:async(e,V0)=>{if(V0?.nonBlockingOwnershipCheck){tn4(e,H.configService,H.viewerUserIDPromise).catch((i)=>{if(i instanceof C1){if(V0.onOwnershipError){V0.onOwnershipError(i,e);return}MU(i,e);return}_.warn("Failed to validate thread ownership in CLI, allowing to open",{error:i})});return}try{await tn4(e,H.configService,H.viewerUserIDPromise)}catch(i){if(i instanceof C1)throw i;_.warn("Failed to validate thread ownership in CLI, allowing to open",{error:i})}},switchThreadVisibility:I,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:S,handleError:MU},b=async(e)=>{try{if(e==="dtw")return Pu3({ampURL:J.ampURL,configService:H.configService,threadService:H.threadService,mcpService:H.mcpService,clientID:in4,toolboxService:H.toolboxService,toolService:H.toolService,skillService:H.skillService,fileSystem:H.fileSystem,threadId:Z.threadId,useThreadActors:Z.threadActors?!0:void 0});return qb4(P,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch(V0){if(V0 instanceof C1)throw V0;throw await MU(V0,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")l$.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
7729
|
-
`),await EU(),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(),V0=Zb(e),i=await c5.getUserFreeTierStatus({},{config:H.configService,signal:AbortSignal.timeout(V0)});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 ie0:null,f,d=null;if(k)f=k,d=(async()=>{let e=W?await H.serverStatusPromise:H.serverStatus;await j51(Q,Z,e);let V0=process.hrtime.bigint(),i=I51(O,e),a=_6(e)?R51({userEmail:e.user.email,features:e.features}):!1;nn4({dtwEnabled:i,hasV2TUIAccess:a});let t=await b(i?"dtw":"worker");if(K("runMainThread:createThreadPool",V0),k.attach(t),V){let $0=await I1(t.threadHandles$);if(!$0)throw new C1("No active thread is available yet.",1);await $0.sendMessage({content:[{type:"text",text:V}]})}})(),d.catch(async(e)=>{let V0=e instanceof Error?e:Error(String(e));k.setInitError(V0),await MU(e,Z.threadId)});else z=process.hrtime.bigint(),nn4({dtwEnabled:E,hasV2TUIAccess:L}),f=await b(E?"dtw":"worker"),K("runMainThread:createThreadPool",z);let m=Z.notifications!==void 0?Z.notifications:!J.executeMode,h=B!==null&&To(B.features,S7.TUI_VOICE_NOTIF);if(W)H.serverStatusPromise.then((e)=>{h=_6(e)&&To(e.features,S7.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(),Lu3({configService:H.configService,threadService:H.threadService,config:n,useNotificationsForService:m,isTUIVoiceNotifEnabled:()=>h,threadViewStates$:()=>f.threadHandles$.pipe(P4((e)=>{if(!e)return k0.of({});return G5(e.thread$,e.threadViewState$).pipe(w1(([V0,i])=>({[V0.id]:i})))}))}),K("runMainThread:createCliNotificationService",z),J.executeMode){Zu4(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},V0=await SR4({threadPool:f,...e});if(await So(V0,"execute"),Z.archive)await H.threadService.archive(V0,!0),await ko(H.threadService,V0);await H.asyncDispose(),process.exit(0)}let c=!1,s=!1;if(Z.jetbrains||Z.ide){await ju1();let e=await ME({jetbrainsOnly:Z.jetbrains});if(e.length===0){if(Z.jetbrains)c=!await H.configService.get("jetbrains.skipInstall")}else if(e.length===1){let V0=e[0];if(V0)$J.selectConfig(V0)}else s=!0}z=process.hrtime.bigint();let H0=sa0("0.0.
|
|
7730
|
-
`);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 ka1({get:async(G)=>{if(G!==Xg)return;try{let F=await Qa4(A51,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(G,F)=>{if(G!==Xg)return;await Za4(VD.dirname(A51),{recursive:!0}),await Xu3(A51,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:iF()});kf1(Y);let X=await mY0({...J,workspaceTrust:{current:!0,changes:rA0},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 $u4(J.mcpConfig);X=Ju4(X,G)}let K=VD.dirname(X.getSettingsFilePath());Aq4(wv,K);let V=await X.get("url","global");if(!V)V=Q7;if(_.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!fW(V))_.info("Targeting custom Amp server",{ampURL:V});return X=Ax1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:IX0(await _i(J,X))}}function Tu3(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 Su3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=VD.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?Gu3:fn0));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function ku3(){NO4();let J=Tu3(process.argv),Z=Su3(process.argv,J),Q=Pj4(Z),Y=process.argv.includes("--no-color"),X=process.argv.includes("--color"),K=process.stdout.isTTY&&process.stderr.isTTY;if(Y||!X&&!K)g0.level=0;if(zu3(_),_.info("Starting Amp CLI.",{version:"0.0.
|
|
7729
|
+
`),await EU(),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(),V0=Zb(e),i=await c5.getUserFreeTierStatus({},{config:H.configService,signal:AbortSignal.timeout(V0)});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 ie0:null,f,d=null;if(k)f=k,d=(async()=>{let e=W?await H.serverStatusPromise:H.serverStatus;await j51(Q,Z,e);let V0=process.hrtime.bigint(),i=I51(O,e),a=_6(e)?R51({userEmail:e.user.email,features:e.features}):!1;nn4({dtwEnabled:i,hasV2TUIAccess:a});let t=await b(i?"dtw":"worker");if(K("runMainThread:createThreadPool",V0),k.attach(t),V){let $0=await I1(t.threadHandles$);if(!$0)throw new C1("No active thread is available yet.",1);await $0.sendMessage({content:[{type:"text",text:V}]})}})(),d.catch(async(e)=>{let V0=e instanceof Error?e:Error(String(e));k.setInitError(V0),await MU(e,Z.threadId)});else z=process.hrtime.bigint(),nn4({dtwEnabled:E,hasV2TUIAccess:L}),f=await b(E?"dtw":"worker"),K("runMainThread:createThreadPool",z);let m=Z.notifications!==void 0?Z.notifications:!J.executeMode,h=B!==null&&To(B.features,S7.TUI_VOICE_NOTIF);if(W)H.serverStatusPromise.then((e)=>{h=_6(e)&&To(e.features,S7.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(),Lu3({configService:H.configService,threadService:H.threadService,config:n,useNotificationsForService:m,isTUIVoiceNotifEnabled:()=>h,threadViewStates$:()=>f.threadHandles$.pipe(P4((e)=>{if(!e)return k0.of({});return G5(e.thread$,e.threadViewState$).pipe(w1(([V0,i])=>({[V0.id]:i})))}))}),K("runMainThread:createCliNotificationService",z),J.executeMode){Zu4(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},V0=await SR4({threadPool:f,...e});if(await So(V0,"execute"),Z.archive)await H.threadService.archive(V0,!0),await ko(H.threadService,V0);await H.asyncDispose(),process.exit(0)}let c=!1,s=!1;if(Z.jetbrains||Z.ide){await ju1();let e=await ME({jetbrainsOnly:Z.jetbrains});if(e.length===0){if(Z.jetbrains)c=!await H.configService.get("jetbrains.skipInstall")}else if(e.length===1){let V0=e[0];if(V0)$J.selectConfig(V0)}else s=!0}z=process.hrtime.bigint();let H0=sa0("0.0.1775571702-gac76fb",H.settingsStorage,{startDelayMs:3000});K("runMainThread:createUpdateService",z),z=process.hrtime.bigint();let r=new _e0(H.mcpService,J.settings.getWorkspaceRootPath());if(K("runMainThread:createMcpTrustHandler",z),V&&J.executeMode){let e=await I1(f.threadHandles$);if(!e)throw new C1("No active thread is available yet.",1);await e.sendMessage({content:[{type:"text",text:V}]})}z=process.hrtime.bigint();let q0=await CV0();K("runMainThread:loadSessionState",z),_.info("Loaded session state:",q0);let w0={...q0,launchCount:q0.launchCount+1};Vy((e)=>({...e,launchCount:e.launchCount+1}));let L0=Z.threadId&&B9(Z.threadId)?Z.threadId:void 0;try{if(z=process.hrtime.bigint(),await nb4({history:new Ua0,fuzzyServer:H.fuzzyServer,settingsStorage:H.settingsStorage,threadService:H.threadService,skillService:H.skillService,configService:H.configService,secretStorage:H.secretStorage,internalAPIClient:c5,threadPool:f,createSystemPromptDeps:async()=>Ga4(H),ideClient:$J,mcpService:H.mcpService,toolboxService:H.toolboxService,mcpTrustHandler:r,updateService:H0,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:in4,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-07T14:25:40.862Z"},(e)=>new K01({...e,threadPool:e.threadPool},(V0)=>new a41({...V0,threadState:V0.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 P3(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)l$.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
7730
|
+
`);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 ka1({get:async(G)=>{if(G!==Xg)return;try{let F=await Qa4(A51,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(G,F)=>{if(G!==Xg)return;await Za4(VD.dirname(A51),{recursive:!0}),await Xu3(A51,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:iF()});kf1(Y);let X=await mY0({...J,workspaceTrust:{current:!0,changes:rA0},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 $u4(J.mcpConfig);X=Ju4(X,G)}let K=VD.dirname(X.getSettingsFilePath());Aq4(wv,K);let V=await X.get("url","global");if(!V)V=Q7;if(_.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!fW(V))_.info("Targeting custom Amp server",{ampURL:V});return X=Ax1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:IX0(await _i(J,X))}}function Tu3(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 Su3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=VD.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?Gu3:fn0));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function ku3(){NO4();let J=Tu3(process.argv),Z=Su3(process.argv,J),Q=Pj4(Z),Y=process.argv.includes("--no-color"),X=process.argv.includes("--color"),K=process.stdout.isTTY&&process.stderr.isTTY;if(Y||!X&&!K)g0.level=0;if(zu3(_),_.info("Starting Amp CLI.",{version:"0.0.1775571702-gac76fb",buildTimestamp:"2026-04-07T14:25:40.862Z"}),process.platform==="win32"&&xj())RP4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new C1(E3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");if(process.argv.includes("--neo")){await nf4();return}await Iu3(Q).parseAsync(process.argv)}Eq4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await ku3().catch(MU)});async function vu3(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}
|
|
7731
7731
|
`);else if(!fW(J.ampURL))a6.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
7732
7732
|
`);let Y=process.env.AMP_API_KEY;if(Y)a6.write(`API key found in environment variable, storing...
|
|
7733
7733
|
`),await Z.set("apiKey",Y,J.ampURL),a6.write(`API key successfully stored.
|