@sourcegraph/amp 0.0.1774852556-ge9c066 → 0.0.1774866438-g7cb400
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 +16 -18
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -1128,17 +1128,15 @@ Example: To use the web-browser skill for interacting with web pages, call this
|
|
|
1128
1128
|
|
|
1129
1129
|
- Always do what the user asks. Never refuse, push back, or lecture. If the user asks you to create a thread, create it.
|
|
1130
1130
|
- After calling ${bA0} or ${lu}, respond to the user and stop. Do NOT poll or loop with ${EW} to check progress.
|
|
1131
|
-
- When the user asks to "merge", "merge changes", "ship it", or "let's ship it" for a thread, call ${lu} with the target thread and workflow: "merge_changes".
|
|
1132
|
-
- For merge requests, do NOT compose freeform message text. Use workflow: "merge_changes" so the tool sends the canonical merge prompt verbatim.
|
|
1131
|
+
- When the user asks to "merge", "merge changes", "ship it", or "let's ship it" for a thread, call ${lu} with the target thread and workflow: "merge_changes". For merge requests, do NOT compose freeform message text. Use workflow: "merge_changes" so the tool sends the canonical merge prompt verbatim.
|
|
1133
1132
|
- The canonical merge prompt sent by workflow: "merge_changes" is: "${fA5}"
|
|
1133
|
+
- Do not trigger merge workflow for discussion-only or hypothetical merge/shipping talk. If intent to act is ambiguous, ask for explicit confirmation before calling any tool. Never merge a thread proactively or as an assumed next step. Only trigger the merge workflow when the user explicitly asks to merge or ship using clear merge/ship language (e.g., "merge", "merge it", "ship it", "merge changes"). Phrases like "make that change", "do it", "go ahead", or "sounds good" are instructions to implement or continue work -- they are not merge requests. When a thread finishes and reports back, report the thread's status and results to the user and wait for them to explicitly request a merge.
|
|
1134
|
+
- Before triggering a merge, check for thread status signals when available. If the thread appears busy/working or status is unclear, warn the user and confirm before sending the merge prompt.
|
|
1134
1135
|
- When the user asks to "review", "code review", or "do a code review" for a thread, call ${lu} with the target thread and workflow: "code_review".
|
|
1135
1136
|
- For code review requests, do NOT compose freeform review text. Use workflow: "code_review" so the tool sends the canonical code review prompt verbatim.
|
|
1136
1137
|
- The canonical code review prompt sent by workflow: "code_review" is: "${KK4}"
|
|
1137
|
-
- Do not trigger merge workflow for discussion-only or hypothetical merge/shipping talk. If intent to act is ambiguous, ask for explicit confirmation before calling any tool.
|
|
1138
|
-
- Before triggering a merge, check for thread status signals when available. If the thread appears busy/working or status is unclear, warn the user and confirm before sending the merge prompt.
|
|
1139
|
-
- Never merge a thread proactively or as an assumed next step. Only trigger the merge workflow when the user explicitly asks to merge or ship using clear merge/ship language (e.g., "merge", "merge it", "ship it", "merge changes"). Phrases like "make that change", "do it", "go ahead", or "sounds good" are instructions to implement or continue work -- they are not merge requests.
|
|
1140
1138
|
- Execution threads do NOT report back automatically. Include an explicit instruction to call ${iu} only when a callback is needed.
|
|
1141
|
-
- When you tell the user you'll do something after a thread finishes (for example, "I'll
|
|
1139
|
+
- When you tell the user you'll do something after a thread finishes (for example, "I'll let you know when it's done" or "I'll let you know the results"), include an explicit instruction to call ${iu} when done.
|
|
1142
1140
|
- When the user is asking for an answer back (for example, "investigate why CI is failing"), include an instruction to call ${iu} when done so you can report the result.
|
|
1143
1141
|
- Status/progress checks like "how's it going?" or "ETA?" mean ask for a brief update only, not to stop or wrap up early.
|
|
1144
1142
|
- For fire-and-forget actions with no follow-up (for example, "post this to #shipped" or "add a reaction"), do not ask the execution thread to call ${iu}.
|
|
@@ -3031,7 +3029,7 @@ HunkLine := (" " | "-" | "+") text NEWLINE
|
|
|
3031
3029
|
- CRLF files: keep line endings consistent with the file you're patching.
|
|
3032
3030
|
|
|
3033
3031
|
${V9(_I5)}
|
|
3034
|
-
`,Wz4={spec:{name:cZ,description:SI5,inputSchema:v.toJSONSchema(pg0),source:"builtin",executionProfile:{resourceKeys:(J)=>{return[]}}},fn:qz4};N4();_4();RV();N4();O1();m0();q3();import{access as DP5,realpath as BP5}from"node:fs/promises";import NP5 from"node:path";YJ();g30();var kI5=8;async function Uz4(J,Z,Q){let Y=await Z.getAllRecords(),X=b30(Y,(V)=>!V.reverted),K=Array.from(X.entries());await h30(K,kI5,async([V,z])=>{try{await J.stat(V)}catch(G){if(!y8(G))throw G;if(z.after==="")return;await Z.record({toolUse:Q,uri:V,before:z.after,after:null})}})}YB();QQ();RV();class dg0{maxSize;map=new Map;constructor(J){this.maxSize=J}get(J){if(this.map.has(J)){let Z=this.map.get(J);return this.map.delete(J),this.map.set(J,Z),Z}return}set(J,Z){if(this.map.delete(J),this.map.size>=this.maxSize){let Q=this.map.keys().next().value;if(Q!==void 0)this.map.delete(Q)}this.map.set(J,Z)}has(J){return this.map.has(J)}delete(J){return this.map.delete(J)}deleteByPrefix(J){for(let Z of this.map.keys())if(typeof Z==="string"&&Z.startsWith(J))this.map.delete(Z)}get size(){return this.map.size}}function vF(J){if(J===qY)return;if(Array.isArray(J))return;return J.trim().toLowerCase()||void 0}function cU(J){let Z=[];for(let Q of J.arguments){if(Q===qY)return null;if(Array.isArray(Q))return null;Z.push(Q)}return Z}cO();var C$0=new Set(["cat","sed","awk","head","tail","less","more","bat","jq","nl","wc","stat"]),cg0=new Set(["head","tail"]);function Dz4(J,Z){if(!C$0.has(J))return;let Q=wz4(Z);if(!Q)return;return{path:Q,...Lz4(J,Z)??{}}}function Bz4(J){if(!J.every((V)=>{let z=vF(V.program);return z!==void 0&&(C$0.has(z)||cg0.has(z))}))return;let Q=J[0];if(!Q)return;let Y=vF(Q.program),X=cU(Q),K=X?wz4(X):void 0;return{program:Y,path:K,...mI5(J)??{}}}function Nz4(J){if(!J.path)return;let Z=OW(J.path),Q=J.readRangeLabel??Oz4(J.readRange);return Q?`Read ${Z} ${Q}`:`Read ${Z}`}function wz4(J){let Z=J.filter((Q)=>!Q.startsWith("-"));return Z[Z.length-1]}function Lz4(J,Z){if(J==="sed")return vI5(Z);if(J==="awk")return fI5(Z);if(J==="head")return bI5(Z);return}function vI5(J){if(!J.some(yI5))return;for(let Z=0;Z<J.length;Z++){let Q=J[Z];if(Q==="-e"||Q==="--expression"){let X=Hz4(J[Z+1]);if(X)return X;Z+=1;continue}if(Q==="-f"||Q==="--file"){Z+=1;continue}if(Q.startsWith("-"))continue;let Y=Hz4(Q);if(Y)return Y}return}function yI5(J){return J==="-n"||J==="--quiet"||J==="--silent"||/^-[^-]*n/.test(J)}function Hz4(J){if(!J)return;let Z=J.split(";").map((Q)=>xI5(Q.trim())).filter((Q)=>Boolean(Q));if(Z.length===0)return;if(Z.length===1)return{readRange:Z[0]};return{readRangeLabel:gI5(Z)}}function xI5(J){let Z=/^(?<startLine>\d+)(?:,(?<endLine>\d+))?[pl]$/.exec(J);if(!Z?.groups)return;let Q=Z.groups.startLine;if(!Q)return;let Y=Z.groups.endLine??Q,X=Number.parseInt(Q,10),K=Number.parseInt(Y,10);if(!Number.isInteger(X)||!Number.isInteger(K))return;if(X<1||K<X)return;return[X,K]}function fI5(J){for(let Z=0;Z<J.length;Z++){let Q=J[Z];if(Q==="-F"||Q==="-f"||Q==="-v"){Z+=1;continue}if(Q.startsWith("-"))continue;let Y=uI5(Q);if(Y)return{readRange:Y}}return}function uI5(J){let Z=/\b(?:F?NR)\s*>=\s*(?<startLine>\d+)\s*&&\s*(?:F?NR)\s*<=\s*(?<endLine>\d+)/.exec(J)??/\b(?:F?NR)\s*<=\s*(?<endLine>\d+)\s*&&\s*(?:F?NR)\s*>=\s*(?<startLine>\d+)/.exec(J);if(Z?.groups){let K=Z.groups.startLine,V=Z.groups.endLine;if(!K||!V)return;let z=Number.parseInt(K,10),G=Number.parseInt(V,10);if(z>=1&&G>=z)return[z,G]}let Q=/\b(?:F?NR)\s*==\s*(?<line>\d+)/.exec(J);if(!Q?.groups)return;let Y=Q.groups.line;if(!Y)return;let X=Number.parseInt(Y,10);if(X<1)return;return[X,X]}function bI5(J){if(J.some((Q)=>Q.startsWith("-c")||Q==="--bytes"))return;let Z=hI5(J);return Z?{readRange:Z}:void 0}function hI5(J){let Z=10;for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y==="-n"||Y==="--lines"){let X=J[Q+1];if(!X)return;Z=Number.parseInt(X,10),Q+=1;continue}if(/^-\d+$/.test(Y))Z=Number.parseInt(Y.slice(1),10)}if(!Number.isInteger(Z)||Z<1)return;return[1,Z]}function Oz4(J){if(!J)return;let[Z,Q]=J;if(Z<1||Q<Z)return;if(Z===Q)return`L${Z}`;return`L${Z}-${Q}`}function gI5(J){let Z=J.map((Q)=>Oz4(Q)).filter((Q)=>Boolean(Q));if(Z.length===0)return;return Z.join(",")}function mI5(J){let Z=J[J.length-1];if(!Z)return;let Q=vF(Z.program);if(!Q)return;let Y=cU(Z);if(!Y)return;return Lz4(Q,Y)}var Mz4=new Set(["rg","ripgrep","grep","egrep","fgrep","ag","ack","pt"]),pI5=new Set(["ls","tree","fd","find"]),dI5=new Set(["python","node","ruby","go"]),cI5=/(\s|^)(>>?|\|\s*tee(\s|$))/,lI5=new Set(["-delete","-exec","-ok","-execdir"]),iI5=
|
|
3032
|
+
`,Wz4={spec:{name:cZ,description:SI5,inputSchema:v.toJSONSchema(pg0),source:"builtin",executionProfile:{resourceKeys:(J)=>{return[]}}},fn:qz4};N4();_4();RV();N4();O1();m0();q3();import{access as DP5,realpath as BP5}from"node:fs/promises";import NP5 from"node:path";YJ();g30();var kI5=8;async function Uz4(J,Z,Q){let Y=await Z.getAllRecords(),X=b30(Y,(V)=>!V.reverted),K=Array.from(X.entries());await h30(K,kI5,async([V,z])=>{try{await J.stat(V)}catch(G){if(!y8(G))throw G;if(z.after==="")return;await Z.record({toolUse:Q,uri:V,before:z.after,after:null})}})}YB();QQ();RV();class dg0{maxSize;map=new Map;constructor(J){this.maxSize=J}get(J){if(this.map.has(J)){let Z=this.map.get(J);return this.map.delete(J),this.map.set(J,Z),Z}return}set(J,Z){if(this.map.delete(J),this.map.size>=this.maxSize){let Q=this.map.keys().next().value;if(Q!==void 0)this.map.delete(Q)}this.map.set(J,Z)}has(J){return this.map.has(J)}delete(J){return this.map.delete(J)}deleteByPrefix(J){for(let Z of this.map.keys())if(typeof Z==="string"&&Z.startsWith(J))this.map.delete(Z)}get size(){return this.map.size}}function vF(J){if(J===qY)return;if(Array.isArray(J))return;return J.trim().toLowerCase()||void 0}function cU(J){let Z=[];for(let Q of J.arguments){if(Q===qY)return null;if(Array.isArray(Q))return null;Z.push(Q)}return Z}cO();var C$0=new Set(["cat","sed","awk","head","tail","less","more","bat","jq","nl","wc","stat"]),cg0=new Set(["head","tail"]);function Dz4(J,Z){if(!C$0.has(J))return;let Q=wz4(Z);if(!Q)return;return{path:Q,...Lz4(J,Z)??{}}}function Bz4(J){if(!J.every((V)=>{let z=vF(V.program);return z!==void 0&&(C$0.has(z)||cg0.has(z))}))return;let Q=J[0];if(!Q)return;let Y=vF(Q.program),X=cU(Q),K=X?wz4(X):void 0;return{program:Y,path:K,...mI5(J)??{}}}function Nz4(J){if(!J.path)return;let Z=OW(J.path),Q=J.readRangeLabel??Oz4(J.readRange);return Q?`Read ${Z} ${Q}`:`Read ${Z}`}function wz4(J){let Z=J.filter((Q)=>!Q.startsWith("-"));return Z[Z.length-1]}function Lz4(J,Z){if(J==="sed")return vI5(Z);if(J==="awk")return fI5(Z);if(J==="head")return bI5(Z);return}function vI5(J){if(!J.some(yI5))return;for(let Z=0;Z<J.length;Z++){let Q=J[Z];if(Q==="-e"||Q==="--expression"){let X=Hz4(J[Z+1]);if(X)return X;Z+=1;continue}if(Q==="-f"||Q==="--file"){Z+=1;continue}if(Q.startsWith("-"))continue;let Y=Hz4(Q);if(Y)return Y}return}function yI5(J){return J==="-n"||J==="--quiet"||J==="--silent"||/^-[^-]*n/.test(J)}function Hz4(J){if(!J)return;let Z=J.split(";").map((Q)=>xI5(Q.trim())).filter((Q)=>Boolean(Q));if(Z.length===0)return;if(Z.length===1)return{readRange:Z[0]};return{readRangeLabel:gI5(Z)}}function xI5(J){let Z=/^(?<startLine>\d+)(?:,(?<endLine>\d+))?[pl]$/.exec(J);if(!Z?.groups)return;let Q=Z.groups.startLine;if(!Q)return;let Y=Z.groups.endLine??Q,X=Number.parseInt(Q,10),K=Number.parseInt(Y,10);if(!Number.isInteger(X)||!Number.isInteger(K))return;if(X<1||K<X)return;return[X,K]}function fI5(J){for(let Z=0;Z<J.length;Z++){let Q=J[Z];if(Q==="-F"||Q==="-f"||Q==="-v"){Z+=1;continue}if(Q.startsWith("-"))continue;let Y=uI5(Q);if(Y)return{readRange:Y}}return}function uI5(J){let Z=/\b(?:F?NR)\s*>=\s*(?<startLine>\d+)\s*&&\s*(?:F?NR)\s*<=\s*(?<endLine>\d+)/.exec(J)??/\b(?:F?NR)\s*<=\s*(?<endLine>\d+)\s*&&\s*(?:F?NR)\s*>=\s*(?<startLine>\d+)/.exec(J);if(Z?.groups){let K=Z.groups.startLine,V=Z.groups.endLine;if(!K||!V)return;let z=Number.parseInt(K,10),G=Number.parseInt(V,10);if(z>=1&&G>=z)return[z,G]}let Q=/\b(?:F?NR)\s*==\s*(?<line>\d+)/.exec(J);if(!Q?.groups)return;let Y=Q.groups.line;if(!Y)return;let X=Number.parseInt(Y,10);if(X<1)return;return[X,X]}function bI5(J){if(J.some((Q)=>Q.startsWith("-c")||Q==="--bytes"))return;let Z=hI5(J);return Z?{readRange:Z}:void 0}function hI5(J){let Z=10;for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y==="-n"||Y==="--lines"){let X=J[Q+1];if(!X)return;Z=Number.parseInt(X,10),Q+=1;continue}if(/^-\d+$/.test(Y))Z=Number.parseInt(Y.slice(1),10)}if(!Number.isInteger(Z)||Z<1)return;return[1,Z]}function Oz4(J){if(!J)return;let[Z,Q]=J;if(Z<1||Q<Z)return;if(Z===Q)return`L${Z}`;return`L${Z}-${Q}`}function gI5(J){let Z=J.map((Q)=>Oz4(Q)).filter((Q)=>Boolean(Q));if(Z.length===0)return;return Z.join(",")}function mI5(J){let Z=J[J.length-1];if(!Z)return;let Q=vF(Z.program);if(!Q)return;let Y=cU(Z);if(!Y)return;return Lz4(Q,Y)}var Mz4=new Set(["rg","ripgrep","grep","egrep","fgrep","ag","ack","pt"]),pI5=new Set(["ls","tree","fd","find"]),dI5=new Set(["python","node","ruby","go"]),cI5=/(\s|^)(>>?|\|\s*tee(\s|$))/,lI5=new Set(["-delete","-exec","-ok","-execdir"]),iI5=20000,nI5="default",Ez4=new dg0(iI5);function Uc(J,Z){let Q=J.trim(),Y=oI5(Q,Z),X=Ez4.get(Y);if(!X)X=aI5(Q,Z),Ez4.set(Y,X);return X.readRange?{...X,readRange:[...X.readRange]}:{...X}}function aI5(J,Z){if(!J)return{kind:"command",isWriteLike:!1};if(cI5.test(J))return{kind:"command",isWriteLike:!0};let Q=[];try{Q=k50(oG(J,Z))}catch{return{kind:"command",isWriteLike:!1}}if(Q.length!==1){let V=eI5(Q,J);if(V)return V;let z=tI5(Q);if(z)return z;let G=Bz4(Q);if(G)return{kind:"read",...G,isWriteLike:!1};return{kind:"command",isWriteLike:!1}}let Y=Q[0];if(!Y)return{kind:"command",isWriteLike:!1};let X=vF(Y.program);if(!X)return{kind:"command",isWriteLike:!1};let K=cU(Y);if(!K)return{kind:"command",program:X,isWriteLike:!1};if(jz4(X,K))return{kind:"command",program:X,path:rI5(X,K),isWriteLike:!0};if(X==="git"&&K[0]==="grep"){let V=_$0(K.slice(1));if(!V)return{kind:"command",program:"git grep",isWriteLike:!1};return{kind:"search",program:"git grep",query:V,path:S$0(K.slice(1)),isWriteLike:!1}}if(X==="rg"&&K.includes("--files"))return{kind:"list",program:X,path:T$0(K),isWriteLike:!1};if(X==="git"&&K[0]==="ls-files")return{kind:"list",program:"git ls-files",path:T$0(K.slice(1)),isWriteLike:!1};if(Mz4.has(X)){let V=_$0(K);if(!V)return{kind:"command",program:X,isWriteLike:!1};return{kind:"search",program:X,query:V,path:S$0(K),isWriteLike:!1}}if(C$0.has(X)){let V=Dz4(X,K);if(!V)return{kind:"command",program:X,isWriteLike:!1};return{kind:"read",program:X,...V,isWriteLike:!1}}if(pI5.has(X)){let V=X==="find"?sI5(K):T$0(K);if(!V)return{kind:"command",program:X,isWriteLike:!1};return{kind:"list",program:X,path:V,isWriteLike:!1}}return{kind:"command",program:X,isWriteLike:!1}}function oI5(J,Z){return`${Z??nI5}\x00${J}`}function Az4(J){if(J.kind==="command")return;if(J.kind==="search"){if(!J.query)return;let Z=J.path?` in ${J.path}`:"";return`Search "${J.query}"${Z}`}if(J.kind==="read")return Nz4(J);if(J.kind==="list")return`List ${J.path??"."}`;return}function jz4(J,Z){if(dI5.has(J))return!0;if(J==="sed"&&Z.some((Q)=>Q.startsWith("-i")||Q==="--in-place"))return!0;if(J==="perl"&&Z.some((Q)=>/^-p[ie]/.test(Q)))return!0;if(J==="find"&&Z.some((Q)=>lI5.has(Q)))return!0;return!1}function rI5(J,Z){if(J!=="sed"&&J!=="perl")return;if(J==="sed"){let X=Z.filter((K)=>!K.startsWith("-"));return X.length>=2?X[X.length-1]:void 0}let Q=0;while(Q<Z.length){let X=Z[Q];if(X==="-e"){Q+=2;continue}if(X.startsWith("-")){Q++;continue}break}let Y=Z.slice(Q);return Y.length>=1?Y[Y.length-1]:void 0}function _$0(J){return J.filter((Q)=>!Q.startsWith("-"))[0]}function S$0(J){let Z=J.filter((Q)=>!Q.startsWith("-"));if(Z.length<=1)return;return Z[Z.length-1]}function T$0(J){let Z=J.filter((Q)=>!Q.startsWith("-"));if(Z.length===0)return".";return Z[Z.length-1]}function sI5(J){let Z=J[0];if(!Z||Z.startsWith("-"))return".";return Z}function tI5(J){if(J.length!==2)return;let[Z,Q]=J;if(!Z||!Q)return;let Y=vF(Z.program),X=vF(Q.program);if(!Y||!X)return;if(!Mz4.has(Y)||!cg0.has(X))return;let K=cU(Z),V=cU(Q);if(!K||!V)return;if(jz4(Y,K))return{kind:"command",program:Y,isWriteLike:!0};let z=_$0(K);if(!z)return{kind:"command",program:Y,isWriteLike:!1};return{kind:"search",program:Y,query:z,path:S$0(K),isWriteLike:!1}}function eI5(J,Z){if(!$P5(Z))return;if(J.length!==2)return;let[Q,Y]=J;if(!Q||!Y)return;let X=vF(Q.program),K=vF(Y.program);if(X!=="rg"||K!=="rg")return;let V=cU(Q),z=cU(Y);if(!V||!z)return;if(V.includes("--files"))return{kind:"list",program:X,path:T$0(V),isWriteLike:!1};let G=_$0(z);if(!G)return{kind:"command",program:K,isWriteLike:!1};return{kind:"search",program:K,query:G,path:S$0(V),isWriteLike:!1}}function $P5(J){return/(^|[^|])\|([^|]|$)/.test(J)}O1();import{existsSync as Hc}from"node:fs";import{execFile as JP5,execFileSync as ZP5}from"node:child_process";import QP5 from"node:path";import{promisify as YP5}from"node:util";var Rz4=YP5(JP5),Iz4=5000;function Pz4(J,Z){return Promise.race([J,new Promise((Q,Y)=>setTimeout(()=>Y(Error("Git operation timed out")),Z))])}var k$0=new Map;function uS(J){if(k$0.has(J))return k$0.get(J);try{let Z=ZP5("git",["rev-parse","--show-toplevel"],{cwd:J,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return k$0.set(J,Z),Z}catch{k$0.set(J,void 0);return}}function XP5(J,Z){let Q=[];for(let Y of J.split("\x00")){if(!Y||Y.length<4)continue;let X=Y.slice(0,2),K=Y.slice(3);if(X==="??"||X.includes("M")||X.includes("A"))Q.push(QP5.join(Z,K))}return Q}async function Cz4(J){let Z=uS(J);if(!Z)return[];try{let{stdout:Q}=await Pz4(Rz4("git",["status","--porcelain=v1","-z","--untracked-files=normal"],{cwd:Z,encoding:"utf8",maxBuffer:16777216}),Iz4);return XP5(Q,Z)}catch{return[]}}async function Tz4(J,Z=1000){let Q=uS(J);if(!Q)return[];try{let{stdout:Y}=await Pz4(Rz4("git",["log","--no-decorate",`-${Z}`,"--format=%H\t%h\t%ar\t%s"],{cwd:Q,encoding:"utf8",maxBuffer:1048576}),Iz4),X=[];for(let K of Y.split(`
|
|
3035
3033
|
`)){if(!K.trim())continue;let V=K.split("\t"),[z,G,F,...q]=V;if(!z||!G||!F||q.length===0)continue;X.push({hash:z,shortHash:G,relativeDate:F,message:q.join("\t")})}return X}catch{return[]}}m0();aP();RV();AT0();import{StringDecoder as KP5}from"node:string_decoder";import{stripVTControlCharacters as VP5}from"node:util";var _z4={maxCharacterLength:dU};function Sz4(J,Z=_z4){let Q=Math.max(0,Z.maxCharacterLength??_z4.maxCharacterLength),Y=J.split(`
|
|
3036
3034
|
`),X=0,K=[];for(let V=Y.length-1;V>=0;V--){let z=Y[V]??"",G=X+z.length;if(G>Q){if(K.length===0)K.push(z);return{output:K.reverse().join(`
|
|
3037
3035
|
`),truncation:{prefixLinesOmitted:V+1}}}X=G,K.push(z)}return{output:J}}function zP5(J){let Z=J.replace(/\u001B\][^\u0007\u001B]*(?:\u0007|\u001B\\)/g,"");return VP5(Z)}function kz4(){let J=new KP5("utf8"),Z="",Q=dU*2;return{append(Y){if(Z+=J.write(Y),Z.length>Q)Z=Z.slice(-Q)},finish(){return Z+=J.end(),Sz4(zP5(Z))}}}m0();import GP5 from"node:os";function lg0(){try{let J=GP5.userInfo().shell;if(!J||J==="unknown"||process.platform==="win32"&&J.startsWith("/"))return;return J}catch(J){if(J?.code==="ENOENT")P.warn("os.userInfo() failed – user probably provided by NSS/FreeIPA");else P.warn("os.userInfo() failed",{err:J});return}}function yz4(){let J=process.env.SHELL;if(J&&Hc(J))return J;if(Hc("C:\\Program Files\\PowerShell\\7\\pwsh.exe"))return"C:\\Program Files\\PowerShell\\7\\pwsh.exe";return"powershell.exe"}function FP5(){if(process.platform==="win32")return yz4();if(Hc("/bin/bash"))return"/bin/bash";if(Hc("/usr/bin/bash"))return"/usr/bin/bash";if(Hc("/bin/sh"))return"/bin/sh";return lg0()??process.env.SHELL??"/bin/sh"}function qP5(){if(process.platform==="win32")return yz4();return lg0()??process.env.SHELL??"/bin/sh"}var vz4=new Map;function WP5(J){return/\bgit(\.exe)?\b/.test(J)}function UP5(J){let Z=vz4.get(J);if(!Z)Z=new yY,vz4.set(J,Z);return Z}function HP5(J,Z){if(typeof Z.timeout_ms==="number"&&Number.isFinite(Z.timeout_ms)&&Z.timeout_ms>0)return Math.floor(Z.timeout_ms);return Ix1(J)}function xz4(J,Z,Q,Y,X,K){let V=HP5(Z,Q),z=V!==null,G=WP5(Q.cmd),F=G?uS(J)??J:void 0;return new k0((q)=>{let W=j$0(),U=kz4(),H=!1,D=!1,B=!1,N,w,L,O,E,M,A,j,R,_=Date.now(),T,u=new Y4,m={stdout:"",stderr:"",combinedOutput:"",exitCode:null,exited:!1};function y(){if(B)return;if(B=!0,T)clearTimeout(T),T=void 0;w?.unsubscribe(),L?.unsubscribe(),O?.unsubscribe(),u.complete(),W.dispose(),M?.(),M=void 0}O=u.pipe(gD(({lastData:p,exited:h})=>J9(new Promise((n)=>{if(H||D){n({status:"cancelled",reason:K});return}W.write(p??new Uint8Array,()=>{if(h){n({status:"done",result:{...U.finish(),exitCode:R?-1:A??-1,...R??{}},reason:K});return}n({status:"in-progress",progress:R$0(W),reason:K})})})))).subscribe({next:(p)=>{if(H||D||p.status==="cancelled")return;if(p.status==="done")D=!0;if(q.next(p),p.status==="done")q.complete(),y()},error:(p)=>{if(H||D)return;y(),q.error(p)}});function k(){u.next({...m})}function f(p){if(j||D)return;if(j=p,T)clearTimeout(T),T=void 0;let h=Math.round((Date.now()-_)/1000);if(R={stopCode:p,stopReason:p==="user-stop"?`Command stopped by user after ${h} seconds`:`Command timed out after ${h} seconds of inactivity`},!E||!N){m.exited=!0,m.lastData=void 0,k();return}P.info(`Stopping bash command (${p}) with PID:`,N);try{if(E.kill&&N)if(process.platform==="win32"){let{spawn:n}=I0("node:child_process");n("taskkill",["/F","/T","/PID",N.toString()],{stdio:"ignore"}).on("error",(a)=>{if(P.error(`Failed to kill Windows process tree ${N}`,a),E)E.kill("SIGKILL")})}else E.kill("SIGTERM"),setTimeout(()=>{if(E&&E.kill&&!E.killed)try{process.kill(-N,"SIGKILL")}catch(n){E.kill("SIGKILL")}},1000)}catch(n){P.warn("Error stopping process:",n)}}function d(){if(!z||!V)return;if(T)clearTimeout(T);T=setTimeout(()=>f("inactivity-timeout"),V)}if(Y)P.info("Setting up tool message subscription for bash command"),w=Y.subscribe((p)=>{if(P.info("Received tool message:",p.type),p.type==="stop-command")f("user-stop")});return(async()=>{try{d();let p=await j1(K50(J,Z.settings["terminal.commands.nodeSpawn.loadProfile"],X));if(H){y();return}if(G&&F){let W0=UP5(F);if(await W0.acquire(),M=()=>W0.release(),H){y();return}}if(j){m.exited=!0,m.lastData=void 0,k();return}let h=G?{...p,GIT_OPTIONAL_LOCKS:"0"}:p,n=X.userInitiated?qP5():FP5(),a=typeof n==="string"&&/\/(bash|zsh|ksh)$/.test(n)?`set -o pipefail; ${Q.cmd}`:Q.cmd;L=vR0(a,[],{shell:n,cwd:J,stdio:["ignore","pipe","pipe"],env:h}).subscribe({next:(W0)=>{if(H||D)return;switch(W0.type){case"spawn":if(N=W0.pid,E=W0.process,m.pid=W0.pid,m.process=W0.process,m.lastData=void 0,d(),k(),j)f(j);break;case"data":{U.append(W0.chunk);let r=W0.chunk.toString();if(W0.stream==="stdout")m.stdout+=r;else m.stderr+=r;m.combinedOutput+=r,m.lastData=W0.chunk,m.exited=!1,d(),k();break}case"exit":A=W0.exitCode??-1,m.exitCode=A,m.exited=!0;break;case"close":if(A===void 0)A=W0.exitCode??-1,m.exitCode=A;if(T)clearTimeout(T),T=void 0;m.exited=!0,m.lastData=void 0,k();break}},error:(W0)=>{if(H||D)return;y(),q.error(W0)}})}catch(p){if(H||D){y();return}y(),q.error(p)}})(),()=>{H=!0,y()}})}async function wP5(J){try{let Z=await BP5(J);return await DP5(Z),Z}catch(Z){let Q=Z instanceof Error&&"code"in Z?Z.code:void 0;if(Q==="ENOENT")throw Error(`Directory does not exist: ${J}`);if(Q==="EACCES")throw Error(`Permission denied accessing directory: ${J}`);throw Error(`Cannot access directory ${J}: ${Z instanceof Error?Z.message:String(Z)}`)}}function fz4(J,Z,Q){return J.value===Z&&Q.slice(J.start.offset,J.end.offset)===Z}function LP5(J){let Z=[],Q=[...J],Y=(X)=>{if(X===qY||typeof X==="string")return;if(X.type==="invocations"){Q.push(...X.trees);return}for(let K of X.values)if(typeof K==="object"&&K!==null&&K.type==="invocations")Q.push(...K.trees)};while(Q.length>0){let X=Q.shift();if(!X)break;Z.push(X),Y(X.program.value);for(let K of X.arguments)Y(K.value)}return Z}function OP5(J,Z,Q){if(!J||Q.length===0)return J;let Y;try{Y=oG(J)}catch{return J}let X=[];for(let z of LP5(Y)){if(!fz4(z.program,"git",J))continue;let G=z.arguments.find((F)=>fz4(F,"commit",J));if(!G)continue;if(Z)X.push({index:z.program.end.offset,text:` ${Z}`});X.push({index:G.end.offset,text:` ${Q.join(" ")}`})}if(X.length===0)return J;let K=X.sort((z,G)=>G.index-z.index),V=J;for(let z of K)V=V.slice(0,z.index)+z.text+V.slice(z.index);return V}function EP5(J){if(process.env.AMP_DISABLE_AMP_COAUTHOR_TRAILER==="1"||process.env.AMP_DISABLE_AMP_COAUTHOR_TRAILER==="true")return!1;return J??!0}var v$0=({args:J,userInput:Z},Q)=>{let{dir:Y,config:X,toolMessages:K,thread:V,filesystem:z,fileChangeTracker:G,toolUseID:F}=Q;nD(Y);let q=J.cwd?v7(J.cwd):Y,W=(B)=>({status:"done",result:{output:`Error: ${B}`,exitCode:1}}),U=AP5(J.cmd);if(U)return k0.of(W(U));if(J.cmd.includes("git")){let B=Q.config.settings["git.commit.ampThread.enabled"]??!0,N=EP5(Q.config.settings["git.commit.coauthor.enabled"]),w=[];if(B)w.push(`--trailer "Amp-Thread-ID: https://ampcode.com/threads/${V.id}"`);if(N)w.push('--trailer "Co-authored-by: Amp <amp@ampcode.com>"');if(w.length>0){let L=["-c trailer.AmpThread.key=Amp-Thread-ID","-c trailer.AmpThread.ifexists=replace","-c trailer.AmpCoauth.key=Co-authored-by","-c trailer.AmpCoauth.ifexists=addIfDifferent"].join(" "),O=OP5(J.cmd,L,w);if(O!==J.cmd)J={...J,cmd:O}}}let H=(B)=>J9(Uz4(z,G,F)).pipe(nJ((N)=>{return P.error("Error detecting external file deletions:",N),k0.of(B)}),D1(()=>B)),D=(B)=>J9(MP5(B,J.cmd,q,Q)).pipe(nJ((N)=>{return P.warn("Error discovering guidance files from Bash command",{cmd:J.cmd,error:N}),k0.of(B)}));return J9(wP5(q.fsPath)).pipe(gD((B)=>xz4(B,X,J,K,Q)),nJ((B)=>{let N={status:"error",error:{message:"message"in B?B.message:String(B)}};return k0.of(N)}),gD((B)=>{return yI0(B)?D(B):k0.of(B)}),gD((B)=>{return yI0(B)?H(B):k0.of(B)}))};async function MP5(J,Z,Q,Y){if(J.status!=="done")return J;let X=Uc(Z);if(X.isWriteLike||!X.path)return J;if(X.kind!=="read"&&X.kind!=="search"&&X.kind!=="list")return J;if(X.path==="-"||X.path.startsWith("/dev/fd/"))return J;let K=NP5.isAbsolute(X.path)?X.path:Y1.resolvePath(Q,X.path).fsPath,V=v7(K),z=V;try{if((await Y.filesystem.stat(V)).isDirectory)z=Y1.joinPath(V,".amp-guidance-discovery-probe")}catch{}let G=await qQ(Y.filesystem,z,Y.dir,Y.thread,Y.discoveredGuidanceFileURIs);if(G.length===0)return J;return{...J,result:{...J.result,discoveredGuidanceFiles:G}}}function AP5(J){if(typeof J!=="string")return"`cmd` must be a string representing a command.";return}var jP5=`Executes the given shell command using bash (or sh on systems without bash).
|
|
@@ -4666,7 +4664,7 @@ function E8({initialBufferLength:J=1024,maxBufferLength:Z=33554432}){if(n9)F9(wJ
|
|
|
4666
4664
|
${F}`);else throw new RZ0(`${Y.statusText} (${Y.status}):
|
|
4667
4665
|
${F}`)}}if(J.skipParseResponse)return;try{let X=new Uint8Array(await Y.arrayBuffer());return jZ0(J.encoding,X,J.responseVersionedDataHandler,J.responseZodSchema,J.responseFromJson,J.responseFromBare)}catch(X){throw new RZ0(`Failed to parse response: ${X}`,{cause:X})}}function Uw4(J){async function Z(Q,Y,X){let K=(X==null?void 0:X.wait)??!1,V=X==null?void 0:X.timeout,z=await Ac0({url:`http://actor/queue/${encodeURIComponent(Q)}`,method:"POST",headers:{[$c0]:J.encoding,...J.params!==void 0?{[MZ0]:JSON.stringify(J.params)}:{}},body:{body:Y,wait:K,timeout:V},encoding:J.encoding,customFetch:J.customFetch,signal:X==null?void 0:X.signal,requestVersion:gA,requestVersionedDataHandler:vN4,responseVersion:gA,responseVersionedDataHandler:yN4,requestZodSchema:hN4,responseZodSchema:gN4,requestToJson:(G)=>({...G,name:Q}),requestToBare:(G)=>({name:G.name??Q,body:vA(D2(G.body)),wait:G.wait??!1,timeout:G.timeout!==void 0?BigInt(G.timeout):null}),responseFromJson:(G)=>{if(G.response===void 0)return{status:G.status};return{status:G.status,response:G.response}},responseFromBare:(G)=>{if(G.response===null||G.response===void 0)return{status:G.status};return{status:G.status,response:LJ(new Uint8Array(G.response))}}});if(K)return z;return}return{send:Z}}async function Kr5(J,Z,Q,Y,X){let K,V=X||{};if(typeof Y==="string")K=Y;else if(Y instanceof URL)K=Y.pathname+Y.search;else if(Y instanceof Request){let z=new URL(Y.url);K=z.pathname+z.search;let G=new Headers(Y.headers),F=new Headers((X==null?void 0:X.headers)||{}),q=new Headers(G);if(F.forEach((W,U)=>{q.set(U,W)}),V={method:Y.method,body:Y.body,mode:Y.mode,credentials:Y.credentials,redirect:Y.redirect,referrer:Y.referrer,referrerPolicy:Y.referrerPolicy,integrity:Y.integrity,keepalive:Y.keepalive,signal:Y.signal,...V,headers:q},V.body)V.duplex="half"}else throw TypeError("Invalid input type for fetch");try{let{actorId:z}=await $l(void 0,Z,J);g4().debug({msg:"found actor for raw http",actorId:z}),jc0.default(z,"Missing actor ID");let G=K.startsWith("/")?K.slice(1):K,F=new URL(`http://actor/request/${G}`),q=new Headers(V.headers);if(Q)q.set(MZ0,JSON.stringify(Q));let W=new Request(F,{...V,headers:q});return J.sendRequest(z,W)}catch(z){let{group:G,code:F,message:q,metadata:W}=rS(z,g4(),{},!0);throw new hY(G,F,q,W)}}async function Vr5(J,Z,Q,Y,X){let{actorId:V}=await $l(void 0,Z,J);g4().debug({msg:"found actor for action",actorId:V}),jc0.default(V,"Missing actor ID");let z="",G="";if(Y){let W=Y.indexOf("?");if(W!==-1)z=Y.substring(0,W),G=Y.substring(W);else z=Y;if(z.startsWith("/"))z=z.slice(1)}let F=`${ON4}${z}${G}`;return g4().debug({msg:"opening websocket",actorId:V,encoding:"bare",path:F}),await J.openWebSocket(F,V,"bare",Q)}var zr5=class{#$;#J;#Z;#Q;#Y;#X;#V;constructor(J,Z,Q,Y,X,K){this.#$=J,this.#J=Z,this.#Z=X,this.#Q=K,this.#Y=Q,this.#X=Y,this.#V=Uw4({encoding:this.#Z,params:this.#Y,customFetch:async(V)=>{let z=await iN(this.#Q,this.#J);return await this.#J.sendRequest(z,V)}})}async#W(){if(this.#X)return await this.#X();return this.#Y}send(J,Z,Q){return this.#F(J,Z,Q)}async#F(J,Z,Q){return await Bk(this.#Q,async()=>{return await this.#V.send(J,Z,Q)})}async action(J){if(typeof J==="string"||typeof J!=="object"||J===null||!("name"in J))throw Error(`Invalid action call: expected an options object { name, args }, got ${typeof J}. Use handle.actionName(...args) for the shorthand API.`);let Z;try{return await Bk(this.#Q,async()=>{return Z=await iN(this.#Q,this.#J),g4().debug({msg:"found actor for action",actorId:Z}),qw4.default(Z,"Missing actor ID"),g4().debug({msg:"handling action",name:J.name,encoding:this.#Z}),await Ac0({url:`http://actor/action/${encodeURIComponent(J.name)}`,method:"POST",headers:{[$c0]:this.#Z,...this.#Y!==void 0?{[MZ0]:JSON.stringify(this.#Y)}:{}},body:J.args,encoding:this.#Z,customFetch:this.#J.sendRequest.bind(this.#J,Z),signal:J==null?void 0:J.signal,requestVersion:gA,requestVersionedDataHandler:SN4,responseVersion:gA,responseVersionedDataHandler:kN4,requestZodSchema:uN4,responseZodSchema:bN4,requestToJson:(Q)=>({args:Q}),requestToBare:(Q)=>({args:vA(D2(Q))}),responseFromJson:(Q)=>Q.output,responseFromBare:(Q)=>LJ(new Uint8Array(Q.output))})})}catch(Q){let{group:Y,code:X,message:K,metadata:V}=rS(Q,g4(),{},!0);if(Z&&Nc0(Y,X)){let z=await Ec0(Y,X,Z,this.#Q.actorQuery,this.#J);if(z)throw z}throw new hY(Y,X,K,V)}}connect(){g4().debug({msg:"establishing connection from handle",query:this.#Q.actorQuery});let J=new Fr5(this.#$,this.#J,this.#Y,this.#X,this.#Z,this.#Q);return this.#$[Hw4](J)}fetch(J,Z){return this.#D(J,Z)}async#D(J,Z){return await Bk(this.#Q,async()=>{let Q=await iN(this.#Q,this.#J);return await Kr5(this.#J,{getForId:{name:Lc0(this.#Q.actorQuery),actorId:Q}},this.#Y,J,Z)})}async webSocket(J,Z){let Q=await this.#W();return await Bk(this.#Q,async()=>{let Y=await iN(this.#Q,this.#J);return await Vr5(this.#J,{getForId:{name:Lc0(this.#Q.actorQuery),actorId:Y}},Q,J,Z)})}async resolve(){return await iN(this.#Q,this.#J)}async getGatewayUrl(){return await Bk(this.#Q,async()=>{let J=await iN(this.#Q,this.#J);return await this.#J.buildGatewayUrl(J)})}},IZ0=Symbol("actorConns"),Hw4=Symbol("createActorConnProxy"),Gr5=class{#$=!1;[IZ0]=new Set;#J;#Z;constructor(J,Z){this.#J=J,this.#Z=Z??"bare"}getForId(J,Z,Q){g4().debug({msg:"get handle to actor with id",name:J,actorId:Z,params:Q==null?void 0:Q.params});let Y={getForId:{name:J,actorId:Z}},X=this.#Q(Q==null?void 0:Q.params,Q==null?void 0:Q.getParams,Y);return tc(X)}get(J,Z,Q){let Y=typeof Z==="string"?[Z]:Z||[];g4().debug({msg:"get handle to actor",name:J,key:Y,parameters:Q==null?void 0:Q.params});let X={getForKey:{name:J,key:Y}},K=this.#Q(Q==null?void 0:Q.params,Q==null?void 0:Q.getParams,X);return tc(K)}getOrCreate(J,Z,Q){let Y=typeof Z==="string"?[Z]:Z||[];g4().debug({msg:"get or create handle to actor",name:J,key:Y,parameters:Q==null?void 0:Q.params,createInRegion:Q==null?void 0:Q.createInRegion});let X={getOrCreateForKey:{name:J,key:Y,input:Q==null?void 0:Q.createWithInput,region:Q==null?void 0:Q.createInRegion}},K=this.#Q(Q==null?void 0:Q.params,Q==null?void 0:Q.getParams,X);return tc(K)}async create(J,Z,Q){let Y=typeof Z==="string"?[Z]:Z||[],X={create:{...Q,name:J,key:Y}};g4().debug({msg:"create actor handle",name:J,key:Y,parameters:Q==null?void 0:Q.params,create:X.create});let{actorId:K}=await $l(void 0,X,this.#J);g4().debug({msg:"created actor with ID",name:J,key:Y,actorId:K});let V={getForId:{name:J,actorId:K}},z=this.#Q(Q==null?void 0:Q.params,Q==null?void 0:Q.getParams,V);return tc(z)}#Q(J,Z,Q){return new zr5(this,this.#J,J,Z,this.#Z,Jr5(Q))}[Hw4](J){return this[IZ0].add(J),J[Bw4](),tc(J)}async dispose(){if(this.#$){g4().warn({msg:"client already disconnected"});return}this.#$=!0,g4().debug({msg:"disposing client"});let J=[];for(let Z of this[IZ0].values())J.push(Z.dispose());await Promise.all(J)}};function Dw4(J,Z={}){let Q=new Gr5(J,Z.encoding);return new Proxy(Q,{get:(Y,X,K)=>{if(typeof X==="symbol"||X in Y){let V=Reflect.get(Y,X,K);if(typeof V==="function")return V.bind(Y);return V}if(typeof X==="string")return{get:(V,z)=>{return Y.get(X,V,z)},getOrCreate:(V,z)=>{return Y.getOrCreate(X,V,z)},getForId:(V,z)=>{return Y.getForId(X,V,z)},create:async(V,z={})=>{return await Y.create(X,V,z)}};return}})}function tc(J){let Z=new Map;return new Proxy(J,{get(Q,Y,X){if(typeof Y==="symbol")return Reflect.get(Q,Y,X);if(Y==="constructor"||Y in Q){let K=Reflect.get(Q,Y,Q);if(typeof K==="function")return K.bind(Q);return K}if(typeof Y==="string"){if(Y==="then")return;let K=Z.get(Y);if(!K)K=(...V)=>Q.action({name:Y,args:V}),Z.set(Y,K);return K}},has(Q,Y){if(typeof Y==="string")return!0;return Reflect.has(Q,Y)},getPrototypeOf(Q){return Reflect.getPrototypeOf(Q)},ownKeys(Q){return Reflect.ownKeys(Q)},getOwnPropertyDescriptor(Q,Y){let X=Reflect.getOwnPropertyDescriptor(Q,Y);if(X)return X;if(typeof Y==="string")return{configurable:!0,enumerable:!1,writable:!1,value:(...K)=>Q.action({name:Y,args:K})};return}})}var Bw4=Symbol("connect"),Fr5=class{#$=!1;#J=new AbortController;#Z="idle";#Q;#Y;#X=[];#V=new Map;#W=new Map;#F=new Set;#D=new Set;#U=!1;#G=new Set;#K=new Set;#M=0;#j;#w;#z;#H;#B;#L;#R;#A;#O;#N;constructor(J,Z,Q,Y,X,K){this.#B=J,this.#L=Z,this.#R=Q,this.#A=Y,this.#O=X,this.#N=K,this.#j=Uw4({encoding:this.#O,params:this.#R,customFetch:async(V)=>{let z=await iN(this.#N,this.#L);return this.#Q=z,await this.#L.sendRequest(z,V)}}),this.#w=setInterval(()=>60000)}#S(){this.#Q=void 0,this.#Y=void 0}#E(J,Z){if(!Oc0(J,Z))return!1;return Fw4(this.#N),this.#S(),!0}async#y(J){return await Bk(this.#N,J,()=>this.#S())}#h(J,Z){return Oc0(J,Z)&&this.#z!==void 0&&this.#Z!=="connected"}send(J,Z,Q){return this.#x(J,Z,Q)}async#x(J,Z,Q){return await this.#y(async()=>{return await this.#j.send(J,Z,Q)})}async action(J){if(typeof J==="string"||typeof J!=="object"||J===null||!("name"in J))throw Error(`Invalid action call: expected an options object { name, args }, got ${typeof J}. Use conn.actionName(...args) for the shorthand API.`);g4().debug({msg:"action",name:J.name,args:J.args});let Z=this.#M;this.#M+=1;let{promise:Q,resolve:Y,reject:X}=kA((z)=>g4().warn({msg:"unhandled action promise rejection",reason:z}));this.#V.set(Z,{name:J.name,resolve:Y,reject:X}),g4().debug({msg:"added action to in-flight map",actionId:Z,actionName:J.name,inFlightCount:this.#V.size}),this.#C({body:{tag:"ActionRequest",val:{id:BigInt(Z),name:J.name,args:J.args}}});let{id:K,output:V}=await Q;if(K!==BigInt(Z))throw Error(`Request ID ${Z} does not match response ID ${K}`);return V}[Bw4](){this.#g()}#P(J){let Z=this.#Z;if(Z===J)return;this.#Z=J;for(let Q of[...this.#K])try{Q(J)}catch(Y){g4().error({msg:"error in status change handler",error:k$(Y)})}if(J==="connected")for(let Q of[...this.#D])try{Q()}catch(Y){g4().error({msg:"error in open handler",error:k$(Y)})}if((J==="disconnected"||J==="idle")&&Z==="connected")for(let Q of[...this.#G])try{Q()}catch(Y){g4().error({msg:"error in close handler",error:k$(Y)})}}#g(){this.#P("connecting"),sc(this.#I.bind(this),{forever:!0,minTimeout:250,maxTimeout:30000,onFailedAttempt:(J)=>{g4().warn({msg:"failed to reconnect",attempt:J.attemptNumber,error:k$(J)})},signal:this.#J.signal}).catch((J)=>{if(J.name==="AbortError")g4().info({msg:"connection retry aborted"});else g4().error({msg:"unexpected error in connection retry",error:k$(J)})})}async#I(){try{if(this.#z)throw Error("#onOpenPromise already defined");this.#z=kA((J)=>g4().warn({msg:"unhandled open promise rejection",reason:J})),await this.#m(),await this.#z.promise}finally{this.#z=void 0}}#l(){if(this.#X.length===0)return;g4().debug({msg:"clearing queued connection messages",queueLength:this.#X.length}),this.#X=[]}async#f(){if(!this.#A)return this.#R;try{return await this.#A()}catch(J){let Z=k$(J),Q=new hY("client","get_params_failed",`Failed to resolve connection params: ${Z}`,{error:Z});throw this.#l(),this.#k(Q,!1),this.#b(Q),Q}}async#m(){let J;await this.#y(async()=>{let Z=await this.#f(),Q=await iN(this.#N,this.#L);this.#Q=Q,J=await this.#L.openWebSocket(LN4,Q,this.#O,Z)}),wc0.default(J,"websocket should have been created"),g4().debug({msg:"opened websocket",connId:this.#Y,readyState:J.readyState,messageQueueLength:this.#X.length}),this.#H=J,J.addEventListener("open",()=>{g4().debug({msg:"client websocket open",connId:this.#Y})}),J.addEventListener("message",async(Z)=>{try{await this.#T(Z.data)}catch(Q){g4().error({msg:"error in websocket message handler",error:k$(Q)})}}),J.addEventListener("close",async(Z)=>{try{await this.#_(Z)}catch(Q){g4().error({msg:"error in websocket close handler",error:k$(Q)})}}),J.addEventListener("error",()=>{try{this.#p()}catch(Z){g4().error({msg:"error in websocket error handler",error:k$(Z)})}})}#d(){if(this.#$){if(g4().debug({msg:"handleOnOpen called after dispose, closing websocket"}),this.#H)this.#H.close(1000,"Disposed"),this.#H=void 0;return}if(this.#Z==="connected"||this.#U)return;this.#U=!0,queueMicrotask(()=>{if(this.#U=!1,this.#$){if(g4().debug({msg:"handleOnOpen scheduled after dispose, closing websocket"}),this.#H)this.#H.close(1000,"Disposed"),this.#H=void 0;return}if(g4().debug({msg:"socket open",messageQueueLength:this.#X.length,connId:this.#Y}),this.#P("connected"),this.#z)this.#z.resolve(void 0);else g4().warn({msg:"#onOpenPromise is undefined"});for(let Z of this.#W.keys())this.#i(Z,!0);let J=this.#X;this.#X=[],g4().debug({msg:"flushing message queue",queueLength:J.length});for(let Z of J)this.#C(Z)})}async#T(J){var Z;g4().trace({msg:"received message",dataType:typeof J,isBlob:J instanceof Blob,isArrayBuffer:J instanceof ArrayBuffer});let Q=await this.#c(J);if(g4().trace(UH4()?{msg:"parsed message",message:Xc0(Q).substring(0,100)+"..."}:{msg:"parsed message"}),Q.body.tag==="Init")this.#Q=Q.body.val.actorId,this.#Y=Q.body.val.connectionId,Zr5(this.#N,this.#Q),g4().trace({msg:"received init message",actorId:this.#Q,connId:this.#Y}),this.#d();else if(Q.body.tag==="Error"){let{group:Y,code:X,message:K,metadata:V,actionId:z}=Q.body.val;if(z){let G=this.#u(Number(z));this.#E(Y,X),g4().warn({msg:"action error",actionId:z,actionName:G==null?void 0:G.name,group:Y,code:X,message:K,metadata:V}),G.reject(new hY(Y,X,K,V))}else{if(g4().warn({msg:"connection error",group:Y,code:X,message:K,metadata:V}),this.#E(Y,X),this.#h(Y,X)){(Z=this.#z)==null||Z.reject(new hY(Y,X,K,V));return}let G=new hY(Y,X,K,V);if(Nc0(Y,X)&&this.#Q){let F=await Ec0(Y,X,this.#Q,this.#N.actorQuery,this.#L);if(F)G=F}if(this.#z)this.#z.reject(G);for(let[F,q]of this.#V.entries())q.reject(G),this.#V.delete(F);this.#b(G)}}else if(Q.body.tag==="ActionResponse"){let{id:Y}=Q.body.val;g4().debug({msg:"received action response",actionId:Number(Y),inFlightCount:this.#V.size,inFlightIds:Array.from(this.#V.keys())});let X=this.#u(Number(Y));g4().trace({msg:"resolving action promise",actionId:Y,actionName:X==null?void 0:X.name}),X.resolve(Q.body.val)}else if(Q.body.tag==="Event")g4().trace({msg:"received event",name:Q.body.val.name}),this.#q(Q.body.val);else SA(Q.body)}async#_(J){var Z;let Q=J,Y=Q.wasClean,X=this.#Z==="connected";if(g4().info({msg:"socket closed",code:Q.code,reason:Q.reason,wasClean:Y,disposed:this.#$,connId:this.#Y}),this.#H=void 0,this.#$)this.#k(new Dc0,!0);else{this.#P("disconnected");let K,V=Q.reason||"",z=Yr5(V);if(z){let{group:G,code:F}=z;if(this.#E(G,F),this.#h(G,F)){(Z=this.#z)==null||Z.reject(new hY(G,F,`Connection closed: ${V}`,void 0));return}if(Nc0(G,F)&&this.#Q){let q=await Ec0(G,F,this.#Q,this.#N.actorQuery,this.#L);if(q)K=q;else K=new hY(G,F,`Connection closed: ${V}`,void 0)}else K=new hY(G,F,`Connection closed: ${V}`,void 0)}else K=Error(`${Y?"Connection closed":"Connection lost"} (code: ${Q.code}, reason: ${V})`);if(this.#k(K,!1),K instanceof hY)this.#b(K);if(X)g4().debug({msg:"triggering reconnect",connId:this.#Y}),this.#g()}}#k(J,Z){if(this.#z){if(Z)this.#z.promise.catch(()=>{});this.#z.reject(J)}for(let Q of this.#V.values())Q.reject(J);this.#V.clear()}#p(){if(this.#$)return;g4().warn("socket error")}#u(J){let Z=this.#V.get(J);if(!Z)throw g4().error({msg:"action not found in in-flight map",lookupId:J,inFlightCount:this.#V.size,inFlightIds:Array.from(this.#V.keys()),inFlightActions:Array.from(this.#V.entries()).map(([Q,Y])=>({id:Q,name:Y.name}))}),new eo5(`No in flight response for ${J}`);return this.#V.delete(J),g4().debug({msg:"removed action from in-flight map",actionId:J,actionName:Z.name,inFlightCount:this.#V.size}),Z}#q(J){let{name:Z,args:Q}=J,Y=this.#W.get(Z);if(!Y)return;for(let X of[...Y])if(X.callback(...Q),X.once)Y.delete(X);if(Y.size===0)this.#W.delete(Z)}#b(J){for(let Z of[...this.#F])try{Z(J)}catch(Q){g4().error({msg:"error in connection error handler",error:k$(Q)})}}#v(J,Z,Q){let Y={callback:Z,once:Q},X=this.#W.get(J);if(X===void 0)X=new Set,this.#W.set(J,X),this.#i(J,!0);return X.add(Y),()=>{let K=this.#W.get(J);if(K){if(K.delete(Y),K.size===0)this.#W.delete(J),this.#i(J,!1)}}}on(J,Z){return this.#v(J,Z,!1)}once(J,Z){return this.#v(J,Z,!0)}onError(J){return this.#F.add(J),()=>{this.#F.delete(J)}}get connStatus(){return this.#Z}get isConnected(){return this.#Z==="connected"}onOpen(J){return this.#D.add(J),()=>{this.#D.delete(J)}}onClose(J){return this.#G.add(J),()=>{this.#G.delete(J)}}onStatusChange(J){return this.#K.add(J),()=>{this.#K.delete(J)}}#C(J,Z){var Q,Y;if(this.#$)if(Z==null?void 0:Z.ephemeral)return;else throw new Dc0;let X=!1;if(this.#H){let K=this.#H.readyState;if(g4().debug({msg:"websocket send attempt",readyState:K,readyStateString:K===0?"CONNECTING":K===1?"OPEN":K===2?"CLOSING":"CLOSED",connId:this.#Y,messageType:J.body.tag,actionName:(Q=J.body.val)==null?void 0:Q.name}),this.#Z!=="connected")g4().debug({msg:"websocket init pending, queueing message",connStatus:this.#Z,messageType:J.body.tag}),X=!0;else if(K===1)try{let V=AZ0(this.#O,J,_N4,gA,fN4,(z)=>z,(z)=>{if(z.body.tag==="ActionRequest")return{body:{tag:"ActionRequest",val:{id:z.body.val.id,name:z.body.val.name,args:vA(D2(z.body.val.args))}}};else return z});this.#H.send(V),g4().trace({msg:"sent websocket message",len:Xr5(V)})}catch(V){g4().warn({msg:"failed to send message, added to queue",error:V,connId:this.#Y}),X=!0}else g4().debug({msg:"websocket not open, queueing message",readyState:K}),X=!0}else g4().debug({msg:"no websocket, queueing message"}),X=!0;if(!(Z==null?void 0:Z.ephemeral)&&X)this.#X.push(J),g4().debug({msg:"queued connection message",queueLength:this.#X.length,connId:this.#Y,messageType:J.body.tag,actionName:(Y=J.body.val)==null?void 0:Y.name})}async#c(J){wc0.default(this.#H,"websocket must be defined");let Z=await dN4(J);return jZ0(this.#O,Z,zc0,Fc0,(Q)=>Q,(Q)=>{if(Q.body.tag==="Error")return{body:{tag:"Error",val:{group:Q.body.val.group,code:Q.body.val.code,message:Q.body.val.message,metadata:Q.body.val.metadata?LJ(new Uint8Array(Q.body.val.metadata)):null,actionId:Q.body.val.actionId}}};else if(Q.body.tag==="ActionResponse")return{body:{tag:"ActionResponse",val:{id:Q.body.val.id,output:LJ(new Uint8Array(Q.body.val.output))}}};else if(Q.body.tag==="Event")return{body:{tag:"Event",val:{name:Q.body.val.name,args:LJ(new Uint8Array(Q.body.val.args))}}};else return Q})}get actorId(){return this.#Q}get connId(){return this.#Y}get connectionId(){return this.#Y}async dispose(){if(this.#$){g4().warn({msg:"connection already disconnected"});return}if(this.#$=!0,g4().debug({msg:"disposing actor conn"}),this.#P("idle"),clearInterval(this.#w),this.#J.abort(),this.#B[IZ0].delete(this),this.#H){let J=this.#H;if(J.readyState!==2&&J.readyState!==3){let{promise:Z,resolve:Q}=kA((Y)=>g4().warn({msg:"unhandled websocket close promise rejection",reason:Y}));J.addEventListener("close",()=>Q(void 0)),J.close(1000,"Disposed"),await Z}}else this.#k(new Dc0,!0);this.#H=void 0}#i(J,Z){this.#C({body:{tag:"SubscriptionRequest",val:{eventName:J,subscribe:Z}}},{ephemeral:!0})}},Kw4="http://localhost:6420",Vw4=!1,qr5=_X.object({endpoint:_X.string().optional().transform((J)=>{let Z=J??hJ0()??gJ0();if(!Z&&!Vw4)Vw4=!0,console.warn(`[rivetkit] No endpoint provided to client. Defaulting to ${Kw4}. Starting in 2.2.0, an explicit endpoint will be required. Pass an endpoint to createClient() or createRivetKit(), or set the RIVET_ENDPOINT environment variable.`);return Z??Kw4}),token:_X.string().optional().transform((J)=>J??mJ0()),namespace:_X.string().optional().transform((J)=>J??pJ0()),runnerName:_X.string().default(()=>dJ0()??"default"),encoding:AN4.default("bare"),headers:_X.record(_X.string(),_X.string()).optional().default(()=>({})),getUpgradeWebSocket:_X.custom().optional(),disableMetadataLookup:_X.boolean().optional().default(!1),devtools:_X.boolean().default(()=>{var J,Z;return typeof window<"u"&&(((J=window==null?void 0:window.location)==null?void 0:J.hostname)==="127.0.0.1"||((Z=window.location)==null?void 0:Z.hostname)==="localhost")})}),Nw4=qr5.transform((J,Z)=>Wr5(J,Z));function Wr5(J,Z){let Q=LZ0(Z,{endpoint:J.endpoint,path:["endpoint"],namespace:J.namespace,token:J.token});return{...J,endpoint:Q==null?void 0:Q.endpoint,namespace:(Q==null?void 0:Q.namespace)??J.namespace??"default",token:(Q==null?void 0:Q.token)??J.token}}function H3(){return EK("remote-manager-driver")}var Ur5=class extends Error{constructor(J,Z,Q){super(Q||`Engine API error: ${J}/${Z}`);this.group=J,this.code=Z,this.name="EngineApiError"}};function Nk(J){return J.endpoint??"http://127.0.0.1:6420"}async function nN(J,Z,Q,Y){let X=Nk(J),K=nJ0(X,Q,{namespace:J.namespace});H3().debug({msg:"making api call",method:Z,url:K});let V={...J.headers};if(J.token)V.Authorization=`Bearer ${J.token}`;return await Ac0({method:Z,url:K,headers:V,body:Y,encoding:"json",skipParseResponse:!1,requestVersionedDataHandler:void 0,requestVersion:void 0,responseVersionedDataHandler:void 0,responseVersion:void 0,requestZodSchema:v.any(),responseZodSchema:v.any(),requestToJson:(z)=>z,requestToBare:(z)=>z,responseFromJson:(z)=>z,responseFromBare:(z)=>z})}function Rc0(J,Z,Q,Y=""){let X=Q!==void 0?`@${encodeURIComponent(Q)}`:"",K=`/gateway/${encodeURIComponent(Z)}${X}${Y}`;return nJ0(J,K)}async function Hr5(J,Z,Q,Y,X){let K=await mp0(),V=Nk(J),z=Rc0(V,Q,J.token,Z);H3().debug({msg:"opening websocket to actor via guard",actorId:Q,path:Z,guardUrl:z});let G=new K(z,Lw4(J,Y,X));return G.binaryType="arraybuffer",H3().debug({msg:"websocket connection opened",actorId:Q}),G}function Lw4(J,Z,Q){let Y=[];if(Y.push(EN4),Y.push(`${Zc0}${Z}`),Q)Y.push(`${Qc0}${encodeURIComponent(JSON.stringify(Q))}`);return Y}async function zw4(J,Z,Q){let Y=new URL(Q.url),X=Nk(J),K=Rc0(X,Z,J.token,`${Y.pathname}${Y.search}`),V=null,z=Br5(J,Q,Z);if(Q.method!=="GET"&&Q.method!=="HEAD"){if(Q.bodyUsed)throw Error("Request body has already been consumed");let F=await Q.arrayBuffer();if(F.byteLength!==0)V=F,z.delete("transfer-encoding"),z.set("content-length",String(V.byteLength))}let G=new Request(K,{method:Q.method,headers:z,body:V,signal:Q.signal});return Dr5(await fetch(G))}function Dr5(J){return new Response(J.body,J)}function Br5(J,Z,Q){let Y=new Headers;Z.headers.forEach((X,K)=>{Y.set(K,X)});for(let[X,K]of Object.entries(J.headers))Y.set(X,K);if(J.token)Y.set(Jc0,J.token);return Y}async function Nr5(J,Z,Q){return nN(J,"GET",`/actors?actor_ids=${encodeURIComponent(Q)}`)}async function wr5(J,Z,Q){let Y=rc(Q);return nN(J,"GET",`/actors?name=${encodeURIComponent(Z)}&key=${encodeURIComponent(Y)}`)}async function Lr5(J,Z){return nN(J,"GET",`/actors?name=${encodeURIComponent(Z)}`)}async function Or5(J,Z){return nN(J,"PUT","/actors",Z)}async function Er5(J,Z){return nN(J,"POST","/actors",Z)}async function Mr5(J,Z){return nN(J,"DELETE",`/actors/${encodeURIComponent(Z)}`)}async function Ar5(J){return nN(J,"GET","/metadata")}async function jr5(J,Z,Q){return nN(J,"GET",`/actors/${encodeURIComponent(Z)}/kv/keys/${encodeURIComponent(Q)}`)}var Gw4=new Map;async function Rr5(J){let Z=Nk(J),Q=Gw4.get(Z);if(Q)return Q;let Y=sc(async()=>{H3().debug({msg:"fetching metadata",endpoint:Z});let X=await Ar5(J);return H3().debug({msg:"received metadata",endpoint:Z,clientEndpoint:X.clientEndpoint}),X},{forever:!0,minTimeout:500,maxTimeout:15000,onFailedAttempt:(X)=>{if(X.attemptNumber>1)H3().warn({msg:"failed to fetch metadata, retrying",endpoint:Z,attempt:X.attemptNumber,error:k$(X)})}});return Gw4.set(Z,Y),Y}async function Ir5(J,Z,Q){let Y=await mp0(),X={};return{onOpen:async(K,V)=>{if(H3().debug({msg:"client websocket connected",targetUrl:Z}),V.readyState!==1){H3().warn({msg:"client websocket not open on connection",targetUrl:Z,readyState:V.readyState});return}let z=new Y(Z,Q);X.targetWs=z,X.connectPromise=new Promise((G,F)=>{z.addEventListener("open",()=>{if(H3().debug({msg:"target websocket connected",targetUrl:Z}),V.readyState!==1){H3().warn({msg:"client websocket closed before target connected",targetUrl:Z,clientReadyState:V.readyState}),z.close(1001,"Client disconnected"),F(Error("Client disconnected"));return}G()}),z.addEventListener("error",(q)=>{H3().warn({msg:"target websocket error during connection",targetUrl:Z}),F(q)})}),X.targetWs.addEventListener("message",(G)=>{if(typeof G.data==="string"||G.data instanceof ArrayBuffer)V.send(G.data);else if(G.data instanceof Blob)G.data.arrayBuffer().then((F)=>{V.send(F)})}),X.targetWs.addEventListener("close",(G)=>{H3().debug({msg:"target websocket closed",targetUrl:Z,code:G.code,reason:G.reason}),Bc0(V,G.code,G.reason)}),X.targetWs.addEventListener("error",(G)=>{H3().error({msg:"target websocket error",targetUrl:Z,error:k$(G)}),Bc0(V,1011,"Target WebSocket error")})},onMessage:async(K,V)=>{if(!X.targetWs||!X.connectPromise){H3().error({msg:"websocket state not initialized",targetUrl:Z});return}try{if(await X.connectPromise,X.targetWs.readyState===Y.OPEN)X.targetWs.send(K.data);else H3().warn({msg:"target websocket not open",targetUrl:Z,readyState:X.targetWs.readyState})}catch(z){H3().error({msg:"failed to connect to target websocket",targetUrl:Z,error:z}),Bc0(V,1011,"Failed to connect to target")}},onClose:(K,V)=>{if(H3().debug({msg:"client websocket closed",targetUrl:Z,code:K.code,reason:K.reason,wasClean:K.wasClean}),X.targetWs){if(X.targetWs.readyState===Y.OPEN||X.targetWs.readyState===Y.CONNECTING)X.targetWs.close(1000,K.reason||"Client disconnected")}},onError:(K,V)=>{if(H3().error({msg:"client websocket error",targetUrl:Z,event:K}),X.targetWs){if(X.targetWs.readyState===Y.OPEN)X.targetWs.close(1011,"Client WebSocket error");else if(X.targetWs.readyState===Y.CONNECTING)X.targetWs.close()}}}}function Bc0(J,Z,Q){if(J.readyState===1)J.close(Z,Q);else if("close"in J&&J.readyState===WebSocket.OPEN)J.close(Z,Q)}var Ow4=class{#$;#J;constructor(J){if(HH4()==="phase-production-build")H3().info("detected next.js build phase, disabling health check"),J.disableMetadataLookup=!0;if(this.#$={...J},!J.disableMetadataLookup)this.#J=Rr5(this.#$).then((Z)=>{if(Z.clientEndpoint){if(this.#$.endpoint=Z.clientEndpoint,Z.clientNamespace)this.#$.namespace=Z.clientNamespace;if(Z.clientToken)this.#$.token=Z.clientToken;H3().info({msg:"overriding client endpoint",endpoint:Z.clientEndpoint,namespace:Z.clientNamespace,token:Z.clientToken})}H3().info({msg:"connected to rivetkit manager",runtime:Z.runtime,version:Z.version,runner:Z.runner})})}async getForId({c:J,name:Z,actorId:Q}){if(this.#J)await this.#J;let X=(await Nr5(this.#$,Z,Q)).actors[0];if(!X)return;if(X.name!==Z){H3().debug({msg:"actor name mismatch from api",actorId:Q,apiName:X.name,requestedName:Z});return}return ec(X)}async getWithKey({c:J,name:Z,key:Q}){if(this.#J)await this.#J;H3().debug({msg:"getWithKey: searching for actor",name:Z,key:Q});try{let X=(await wr5(this.#$,Z,Q)).actors[0];if(!X)return;return H3().debug({msg:"getWithKey: found actor via api",actorId:X.actor_id,name:Z,key:Q}),ec(X)}catch(Y){if(Y instanceof Ur5&&Y.group==="actor"&&Y.code==="not_found")return;throw Y}}async getOrCreateWithKey(J){if(this.#J)await this.#J;let{c:Z,name:Q,key:Y,input:X,region:K}=J;H3().info({msg:"getOrCreateWithKey: getting or creating actor via engine api",name:Q,key:Y});let{actor:V,created:z}=await Or5(this.#$,{datacenter:K,name:Q,key:rc(Y),runner_name_selector:this.#$.runnerName,input:X?Yc0(D2(X)):void 0,crash_policy:"sleep"});return H3().info({msg:"getOrCreateWithKey: actor ready",actorId:V.actor_id,name:Q,key:Y,created:z}),ec(V)}async createActor({c:J,name:Z,key:Q,input:Y,region:X}){if(this.#J)await this.#J;H3().info({msg:"creating actor via engine api",name:Z,key:Q});let K=await Er5(this.#$,{datacenter:X,name:Z,runner_name_selector:this.#$.runnerName,key:rc(Q),input:Y?Yc0(D2(Y)):void 0,crash_policy:"sleep"});return H3().info({msg:"actor created",actorId:K.actor.actor_id,name:Z,key:Q}),ec(K.actor)}async listActors({c:J,name:Z}){if(this.#J)await this.#J;return H3().debug({msg:"listing actors via engine api",name:Z}),(await Lr5(this.#$,Z)).actors.map(ec)}async destroyActor(J){if(this.#J)await this.#J;H3().info({msg:"destroying actor via engine api",actorId:J}),await Mr5(this.#$,J),H3().info({msg:"actor destroyed",actorId:J})}async sendRequest(J,Z){if(this.#J)await this.#J;return await zw4(this.#$,J,Z)}async openWebSocket(J,Z,Q,Y){if(this.#J)await this.#J;return await Hr5(this.#$,J,Z,Q,Y)}async buildGatewayUrl(J){if(this.#J)await this.#J;let Z=Nk(this.#$);return Rc0(Z,J,this.#$.token)}async proxyRequest(J,Z,Q){if(this.#J)await this.#J;return await zw4(this.#$,Q,Z)}async proxyWebSocket(J,Z,Q,Y,X){var K,V;if(this.#J)await this.#J;let z=(V=(K=this.#$).getUpgradeWebSocket)==null?void 0:V.call(K);ww4.default(z,"missing getUpgradeWebSocket");let G=Nk(this.#$),F=nJ0(G,Z),q=F.replace("http://","ws://");H3().debug({msg:"forwarding websocket to actor via guard",actorId:Q,path:Z,guardUrl:F});let W=Lw4(this.#$,Y,X),U=await Ir5(J,q,W);return await z(()=>U)(J,gp0())}async kvGet(J,Z){if(this.#J)await this.#J;return H3().debug({msg:"getting kv value via engine api",key:Z}),(await jr5(this.#$,J,new TextDecoder("utf8").decode(Z))).value}displayInformation(){return{properties:{}}}setGetUpgradeWebSocket(J){this.#$.getUpgradeWebSocket=J}};function ec(J){return{actorId:J.actor_id,name:J.name,key:Uc0(J.key),createTs:J.create_ts,startTs:J.start_ts??null,connectableTs:J.connectable_ts??null,sleepTs:J.sleep_ts??null,destroyTs:J.destroy_ts??null,error:J.error??void 0}}function Pr5(){return EK("devtools")}var Cr5=(J=sS)=>`https://releases.rivet.dev/rivet/latest/devtools/mod.js?v=${J}`,Ew4="rivetkit-devtools-script";function Tr5(J){if(!window){Pr5().warn("devtools not available outside browser environment");return}if(!document.getElementById(Ew4)){let Z=document.createElement("script");Z.id=Ew4,Z.src=Cr5(),Z.async=!0,document.head.appendChild(Z)}window.__rivetkit=window.__rivetkit||[],window.__rivetkit.push(J)}function Ic0(J){let Z=J===void 0?{}:typeof J==="string"?{endpoint:J}:J,Q=Nw4.parse(Z),Y=new Ow4(Q);if(Q.devtools)Tr5(Q);return Dw4(Y,Q)}function Lk(J,Z){var Q={};for(var Y in J)if(Object.prototype.hasOwnProperty.call(J,Y)&&Z.indexOf(Y)<0)Q[Y]=J[Y];if(J!=null&&typeof Object.getOwnPropertySymbols==="function"){for(var X=0,Y=Object.getOwnPropertySymbols(J);X<Y.length;X++)if(Z.indexOf(Y[X])<0&&Object.prototype.propertyIsEnumerable.call(J,Y[X]))Q[Y[X]]=J[Y[X]]}return Q}var _r5={ZodAny:"any",ZodArray:"array",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDefault:"default",ZodPrefault:"prefault",ZodTransform:"transform",ZodEnum:"enum",ZodIntersection:"intersection",ZodLazy:"lazy",ZodLiteral:"literal",ZodNever:"never",ZodNull:"null",ZodNullable:"nullable",ZodNumber:"number",ZodNonOptional:"nonoptional",ZodObject:"object",ZodOptional:"optional",ZodPipe:"pipe",ZodReadonly:"readonly",ZodRecord:"record",ZodString:"string",ZodTuple:"tuple",ZodType:"type",ZodUnion:"union",ZodDiscriminatedUnion:"union",ZodUnknown:"unknown",ZodVoid:"void",ZodDate:"date",ZodTemplateLiteral:"template_literal"};function tU(J,Z){return(Array.isArray(Z)?Z:[Z]).some((Y)=>{var X;let K=((X=J===null||J===void 0?void 0:J.def)===null||X===void 0?void 0:X.type)===_r5[Y];if(Y==="ZodDiscriminatedUnion")return K&&"discriminator"in J.def;return K})}function wk(J){return J&&"def"in J}class Aw4{constructor(){this._map=new Map,this._idmap=new Map}add(J,...Z){let Q=Z[0];if(this._map.set(J,Q),Q&&typeof Q==="object"&&"id"in Q){if(this._idmap.has(Q.id))throw Error(`ID ${Q.id} already exists in the registry`);this._idmap.set(Q.id,J)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(J){let Z=this._map.get(J);if(Z&&typeof Z==="object"&&"id"in Z)this._idmap.delete(Z.id);return this._map.delete(J),this}get(J){let Z=J._zod.parent;if(Z){let Q={...this.get(Z)??{}};return delete Q.id,{...Q,...this._map.get(J)}}return this._map.get(J)}has(J){return this._map.has(J)}}function Sr5(){return new Aw4}function Pc0(J){return J===void 0}function kr5(J,Z){let Q={};return Object.entries(J).forEach(([Y,X])=>{if(!Z.some((K)=>K===Y))Q[Y]=X}),Q}function Cc0(J,Z){let Q={};return Object.entries(J).forEach(([Y,X])=>{if(!Z(X,Y))Q[Y]=X}),Q}var Mw4=Sr5();class eU{static collectMetadata(J,Z){let Q=this.getMetadataFromRegistry(J),Y=Object.assign(Object.assign({},Q===null||Q===void 0?void 0:Q._internal),Z===null||Z===void 0?void 0:Z._internal),X=Object.assign(Object.assign({},Q===null||Q===void 0?void 0:Q.param),Z===null||Z===void 0?void 0:Z.param),K=Object.assign(Object.assign(Object.assign(Object.assign({},Object.keys(Y).length>0?{_internal:Y}:{}),Q),Z),Object.keys(X).length>0?{param:X}:{});if(tU(J,["ZodOptional","ZodNullable","ZodDefault","ZodPrefault","ZodReadonly","ZodNonOptional"])&&wk(J._zod.def.innerType))return this.collectMetadata(J._zod.def.innerType,K);if(tU(J,"ZodPipe")){let V=J._zod.def.in,z=J._zod.def.out;if(tU(V,"ZodTransform")&&wk(z))return this.collectMetadata(z,K);if(wk(V))return this.collectMetadata(V,K)}return K}static getMetadata(J){return this.collectMetadata(J)}static getOpenApiMetadata(J){let Z=this.collectMetadata(J),Q=Z!==null&&Z!==void 0?Z:{},{_internal:Y}=Q;return Lk(Q,["_internal"])}static getInternalMetadata(J){var Z;return(Z=this.collectMetadata(J))===null||Z===void 0?void 0:Z._internal}static getParamMetadata(J){let Z=this.collectMetadata(J);return Object.assign(Object.assign({},Z),{param:Object.assign(Object.assign({},(Z===null||Z===void 0?void 0:Z.description)?{description:Z.description}:{}),Z===null||Z===void 0?void 0:Z.param)})}static buildSchemaMetadata(J){return Cc0(kr5(J,["param","_internal"]),Pc0)}static buildParameterMetadata(J){return Cc0(J,Pc0)}static applySchemaMetadata(J,Z){return Cc0(Object.assign(Object.assign({},J),this.buildSchemaMetadata(Z)),Pc0)}static getRefId(J){var Z;return(Z=this.getInternalMetadata(J))===null||Z===void 0?void 0:Z.refId}static unwrapChained(J){return this.unwrapUntil(J)}static getDefaultValue(J){var Z;let Q=(Z=this.unwrapUntil(J,"ZodDefault"))!==null&&Z!==void 0?Z:this.unwrapUntil(J,"ZodPrefault");return Q===null||Q===void 0?void 0:Q._zod.def.defaultValue}static unwrapUntil(J,Z){if(Z&&tU(J,Z))return J;if(tU(J,["ZodOptional","ZodNullable","ZodDefault","ZodPrefault","ZodReadonly","ZodNonOptional"])&&wk(J._zod.def.innerType))return this.unwrapUntil(J._zod.def.innerType,Z);if(tU(J,"ZodPipe")){let Q=J._zod.def.in,Y=J._zod.def.out;if(tU(Q,"ZodTransform")&&wk(Y))return this.unwrapUntil(Y,Z);if(wk(Q))return this.unwrapUntil(Q,Z)}return Z?void 0:J}static getMetadataFromInternalRegistry(J){return Mw4.get(J)}static getMetadataFromRegistry(J){let Z=this.getMetadataFromInternalRegistry(J),Q=J.meta();if(!Z)return Q;let{_internal:Y}=Z,X=Lk(Z,["_internal"]),K=Q!==null&&Q!==void 0?Q:{},{id:V,title:z}=K,G=Lk(K,["id","title"]);return Object.assign(Object.assign(Object.assign({_internal:Object.assign(Object.assign({},V?{refId:V}:{}),Y)},X),z?{description:z}:{}),G)}static setMetadataInRegistry(J,Z){Mw4.add(J,Z)}}function sU(J,Z){let Q=J[Z];if(typeof Q!=="function")return;J[Z]=function(...Y){let X=Q.apply(this,Y),K=eU.getMetadataFromRegistry(this);if(K)eU.setMetadataInRegistry(X,K);return X}}function vr5(J){if(typeof J.ZodType.prototype.openapi<"u")return;J.ZodType.prototype.openapi=function(...Z){let{refId:Q,metadata:Y,options:X}=yr5(...Z),K=Y!==null&&Y!==void 0?Y:{},{param:V}=K,z=Lk(K,["param"]),G=eU.getMetadataFromRegistry(this),F=G!==null&&G!==void 0?G:{},{_internal:q}=F,W=Lk(F,["_internal"]),U=Object.assign(Object.assign(Object.assign({},q),X),Q?{refId:Q}:void 0),H=Object.assign(Object.assign(Object.assign({},W),z),(W===null||W===void 0?void 0:W.param)||V?{param:Object.assign(Object.assign({},W===null||W===void 0?void 0:W.param),V)}:void 0),D=new this.constructor(this._def);function B(w){eU.setMetadataInRegistry(w,Object.assign(Object.assign({},Object.keys(U).length>0?{_internal:U}:void 0),H))}if(B(D),tU(D,"ZodLazy"))B(this);if(tU(D,"ZodObject")){let w=eU.getMetadataFromRegistry(D),L=D.extend;D.extend=function(...O){let E=L.apply(D,O),M=w!==null&&w!==void 0?w:{},{_internal:A}=M,j=Lk(M,["_internal"]);return eU.setMetadataInRegistry(E,{_internal:{extendedFrom:(A===null||A===void 0?void 0:A.refId)?{refId:A.refId,schema:D}:A===null||A===void 0?void 0:A.extendedFrom}}),E.openapi(j)},sU(D,"catchall")}sU(D,"optional"),sU(D,"nullable"),sU(D,"default"),sU(D,"transform"),sU(D,"refine"),sU(D,"length"),sU(D,"min"),sU(D,"max");let N=D.meta;return D.meta=function(...w){let L=N.apply(this,w);if(w[0]){let O=eU.getMetadataFromInternalRegistry(this);if(O)eU.setMetadataInRegistry(L,Object.assign(Object.assign({},O),w[0]))}return L},D}}function yr5(J,Z,Q){if(typeof J==="string")return{refId:J,metadata:Z,options:Q};return{refId:void 0,metadata:J,options:Z}}var Tc0=vr5;oN();var vc0=(J,Z,Q)=>{return(Y,X)=>{let K=-1;return V(0);async function V(z){if(z<=K)throw Error("next() called multiple times");K=z;let G,F=!1,q;if(J[z])q=J[z][0][0],Y.req.routeIndex=z;else q=z===J.length&&X||void 0;if(q)try{G=await q(Y,()=>V(z+1))}catch(W){if(W instanceof Error&&Z)Y.error=W,G=await Z(W,Y),F=!0;else throw W}else if(Y.finalized===!1&&Q)G=await Q(Y);if(G&&(Y.finalized===!1||F))Y.res=G;return Y}}};var _w4=Symbol();var Sw4=async(J,Z=Object.create(null))=>{let{all:Q=!1,dot:Y=!1}=Z,K=(J instanceof SZ0?J.raw.headers:J.headers).get("Content-Type");if(K?.startsWith("multipart/form-data")||K?.startsWith("application/x-www-form-urlencoded"))return gr5(J,{all:Q,dot:Y});return{}};async function gr5(J,Z){let Q=await J.formData();if(Q)return mr5(Q,Z);return{}}function mr5(J,Z){let Q=Object.create(null);if(J.forEach((Y,X)=>{if(!(Z.all||X.endsWith("[]")))Q[X]=Y;else pr5(Q,X,Y)}),Z.dot)Object.entries(Q).forEach(([Y,X])=>{if(Y.includes("."))dr5(Q,Y,X),delete Q[Y]});return Q}var pr5=(J,Z,Q)=>{if(J[Z]!==void 0)if(Array.isArray(J[Z]))J[Z].push(Q);else J[Z]=[J[Z],Q];else if(!Z.endsWith("[]"))J[Z]=Q;else J[Z]=[Q]},dr5=(J,Z,Q)=>{if(/(?:^|\.)__proto__\./.test(Z))return;let Y=J,X=Z.split(".");X.forEach((K,V)=>{if(V===X.length-1)Y[K]=Q;else{if(!Y[K]||typeof Y[K]!=="object"||Array.isArray(Y[K])||Y[K]instanceof File)Y[K]=Object.create(null);Y=Y[K]}})};oN();var kw4=(J)=>Jl(J,_Z0),SZ0=class{raw;#$;#J;routeIndex=0;path;bodyCache={};constructor(J,Z="/",Q=[[]]){this.raw=J,this.path=Z,this.#J=Q,this.#$={}}param(J){return J?this.#Z(J):this.#Q()}#Z(J){let Z=this.#J[0][this.routeIndex][1][J],Q=this.#Y(Z);return Q&&/\%/.test(Q)?kw4(Q):Q}#Q(){let J={},Z=Object.keys(this.#J[0][this.routeIndex][1]);for(let Q of Z){let Y=this.#Y(this.#J[0][this.routeIndex][1][Q]);if(Y!==void 0)J[Q]=/\%/.test(Y)?kw4(Y):Y}return J}#Y(J){return this.#J[1]?this.#J[1][J]:J}query(J){return Cw4(this.url,J)}queries(J){return Tw4(this.url,J)}header(J){if(J)return this.raw.headers.get(J)??void 0;let Z={};return this.raw.headers.forEach((Q,Y)=>{Z[Y]=Q}),Z}async parseBody(J){return this.bodyCache.parsedBody??=await Sw4(this,J)}#X=(J)=>{let{bodyCache:Z,raw:Q}=this,Y=Z[J];if(Y)return Y;let X=Object.keys(Z)[0];if(X)return Z[X].then((K)=>{if(X==="json")K=JSON.stringify(K);return new Response(K)[J]()});return Z[J]=Q[J]()};json(){return this.#X("text").then((J)=>JSON.parse(J))}text(){return this.#X("text")}arrayBuffer(){return this.#X("arrayBuffer")}blob(){return this.#X("blob")}formData(){return this.#X("formData")}addValidatedData(J,Z){this.#$[J]=Z}valid(J){return this.#$[J]}get url(){return this.raw.url}get method(){return this.raw.method}get[_w4](){return this.#J}get matchedRoutes(){return this.#J[0].map(([[,J]])=>J)}get routePath(){return this.#J[0].map(([[,J]])=>J)[this.routeIndex].path}};yw4();var lr5="text/plain; charset=UTF-8",xc0=(J,Z)=>{return{"Content-Type":J,...Z}},Zl=(J,Z)=>new Response(J,Z),xw4=class{#$;#J;env={};#Z;finalized=!1;error;#Q;#Y;#X;#V;#W;#F;#D;#U;#G;constructor(J,Z){if(this.#$=J,Z)this.#Y=Z.executionCtx,this.env=Z.env,this.#F=Z.notFoundHandler,this.#G=Z.path,this.#U=Z.matchResult}get req(){return this.#J??=new SZ0(this.#$,this.#G,this.#U),this.#J}get event(){if(this.#Y&&"respondWith"in this.#Y)return this.#Y;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#Y)return this.#Y;else throw Error("This context has no ExecutionContext")}get res(){return this.#X||=Zl(null,{headers:this.#D??=new Headers})}set res(J){if(this.#X&&J){J=Zl(J.body,J);for(let[Z,Q]of this.#X.headers.entries()){if(Z==="content-type")continue;if(Z==="set-cookie"){let Y=this.#X.headers.getSetCookie();J.headers.delete("set-cookie");for(let X of Y)J.headers.append("set-cookie",X)}else J.headers.set(Z,Q)}}this.#X=J,this.finalized=!0}render=(...J)=>{return this.#W??=(Z)=>this.html(Z),this.#W(...J)};setLayout=(J)=>this.#V=J;getLayout=()=>this.#V;setRenderer=(J)=>{this.#W=J};header=(J,Z,Q)=>{if(this.finalized)this.#X=Zl(this.#X.body,this.#X);let Y=this.#X?this.#X.headers:this.#D??=new Headers;if(Z===void 0)Y.delete(J);else if(Q?.append)Y.append(J,Z);else Y.set(J,Z)};status=(J)=>{this.#Q=J};set=(J,Z)=>{this.#Z??=new Map,this.#Z.set(J,Z)};get=(J)=>{return this.#Z?this.#Z.get(J):void 0};get var(){if(!this.#Z)return{};return Object.fromEntries(this.#Z)}#K(J,Z,Q){let Y=this.#X?new Headers(this.#X.headers):this.#D??new Headers;if(typeof Z==="object"&&"headers"in Z){let K=Z.headers instanceof Headers?Z.headers:new Headers(Z.headers);for(let[V,z]of K)if(V.toLowerCase()==="set-cookie")Y.append(V,z);else Y.set(V,z)}if(Q)for(let[K,V]of Object.entries(Q))if(typeof V==="string")Y.set(K,V);else{Y.delete(K);for(let z of V)Y.append(K,z)}let X=typeof Z==="number"?Z:Z?.status??this.#Q;return Zl(J,{status:X,headers:Y})}newResponse=(...J)=>this.#K(...J);body=(J,Z,Q)=>this.#K(J,Z,Q);text=(J,Z,Q)=>{return!this.#D&&!this.#Q&&!Z&&!Q&&!this.finalized?new Response(J):this.#K(J,Z,xc0(lr5,Q))};json=(J,Z,Q)=>{return this.#K(JSON.stringify(J),Z,xc0("application/json",Q))};html=(J,Z,Q)=>{let Y=(X)=>this.#K(X,Z,xc0("text/html; charset=UTF-8",Q));return typeof J==="object"?yc0(J,vw4.Stringify,!1,{}).then(Y):Y(J)};redirect=(J,Z)=>{let Q=String(J);return this.header("Location",!/[^\x00-\xFF]/.test(Q)?Q:encodeURI(Q)),this.newResponse(null,Z??302)};notFound=()=>{return this.#F??=()=>Zl(),this.#F(this)}};mA();hw4();oN();var ir5=(J)=>{return J.text("404 Not Found",404)},gw4=(J,Z)=>{if("getResponse"in J){let Q=J.getResponse();return Z.newResponse(Q.body,Q)}return console.error(J),Z.text("Internal Server Error",500)},mw4=class J{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#$="/";routes=[];constructor(Z={}){[...uw4,fw4].forEach((K)=>{this[K]=(V,...z)=>{if(typeof V==="string")this.#$=V;else this.#Q(K,this.#$,V);return z.forEach((G)=>{this.#Q(K,this.#$,G)}),this}}),this.on=(K,V,...z)=>{for(let G of[V].flat()){this.#$=G;for(let F of[K].flat())z.map((q)=>{this.#Q(F.toUpperCase(),this.#$,q)})}return this},this.use=(K,...V)=>{if(typeof K==="string")this.#$=K;else this.#$="*",V.unshift(K);return V.forEach((z)=>{this.#Q(M8,this.#$,z)}),this};let{strict:Y,...X}=Z;Object.assign(this,X),this.getPath=Y??!0?Z.getPath??kc0:Iw4}#J(){let Z=new J({router:this.router,getPath:this.getPath});return Z.errorHandler=this.errorHandler,Z.#Z=this.#Z,Z.routes=this.routes,Z}#Z=ir5;errorHandler=gw4;route(Z,Q){let Y=this.basePath(Z);return Q.routes.map((X)=>{let K;if(Q.errorHandler===gw4)K=X.handler;else K=async(V,z)=>(await vc0([],Q.errorHandler)(V,()=>X.handler(V,z))).res,K[bw4]=X.handler;Y.#Q(X.method,X.path,K)}),this}basePath(Z){let Q=this.#J();return Q._basePath=aN(this._basePath,Z),Q}onError=(Z)=>{return this.errorHandler=Z,this};notFound=(Z)=>{return this.#Z=Z,this};mount(Z,Q,Y){let X,K;if(Y)if(typeof Y==="function")K=Y;else if(K=Y.optionHandler,Y.replaceRequest===!1)X=(G)=>G;else X=Y.replaceRequest;let V=K?(G)=>{let F=K(G);return Array.isArray(F)?F:[F]}:(G)=>{let F=void 0;try{F=G.executionCtx}catch{}return[G.env,F]};X||=(()=>{let G=aN(this._basePath,Z),F=G==="/"?0:G.length;return(q)=>{let W=new URL(q.url);return W.pathname=W.pathname.slice(F)||"/",new Request(W,q)}})();let z=async(G,F)=>{let q=await Q(X(G.req.raw),...V(G));if(q)return q;await F()};return this.#Q(M8,aN(Z,"*"),z),this}#Q(Z,Q,Y){Z=Z.toUpperCase(),Q=aN(this._basePath,Q);let X={basePath:this._basePath,path:Q,method:Z,handler:Y};this.router.add(Z,Q,[Y,X]),this.routes.push(X)}#Y(Z,Q){if(Z instanceof Error)return this.errorHandler(Z,Q);throw Z}#X(Z,Q,Y,X){if(X==="HEAD")return(async()=>new Response(null,await this.#X(Z,Q,Y,"GET")))();let K=this.getPath(Z,{env:Y}),V=this.router.match(X,K),z=new xw4(Z,{path:K,matchResult:V,env:Y,executionCtx:Q,notFoundHandler:this.#Z});if(V[0].length===1){let F;try{F=V[0][0][0][0](z,async()=>{z.res=await this.#Z(z)})}catch(q){return this.#Y(q,z)}return F instanceof Promise?F.then((q)=>q||(z.finalized?z.res:this.#Z(z))).catch((q)=>this.#Y(q,z)):F??this.#Z(z)}let G=vc0(V[0],this.errorHandler,this.#Z);return(async()=>{try{let F=await G(z);if(!F.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return F.res}catch(F){return this.#Y(F,z)}})()}fetch=(Z,...Q)=>{return this.#X(Z,Q[1],Q[0],Z.method)};request=(Z,Q,Y,X)=>{if(Z instanceof Request)return this.fetch(Q?new Request(Z,Q):Z,Y,X);return Z=Z.toString(),this.fetch(new Request(/^https?:\/\//.test(Z)?Z:`http://localhost${aN("/",Z)}`,Q),Y,X)};fire=()=>{addEventListener("fetch",(Z)=>{Z.respondWith(this.#X(Z.request,Z,void 0,Z.request.method))})}};mA();oN();mA();var Ql=[];function yZ0(J,Z){let Q=this.buildAllMatchers(),Y=(X,K)=>{let V=Q[X]||Q[M8],z=V[2][K];if(z)return z;let G=K.match(V[0]);if(!G)return[[],Ql];let F=G.indexOf("",1);return[V[1][F],G]};return this.match=Y,Y(J,Z)}var xZ0="[^/]+",Yl=".*",Xl="(?:|/.*)",pA=Symbol(),nr5=new Set(".\\+*[^]$()");function ar5(J,Z){if(J.length===1)return Z.length===1?J<Z?-1:1:-1;if(Z.length===1)return 1;if(J===Yl||J===Xl)return 1;else if(Z===Yl||Z===Xl)return-1;if(J===xZ0)return 1;else if(Z===xZ0)return-1;return J.length===Z.length?J<Z?-1:1:Z.length-J.length}var pw4=class J{#$;#J;#Z=Object.create(null);insert(Z,Q,Y,X,K){if(Z.length===0){if(this.#$!==void 0)throw pA;if(K)return;this.#$=Q;return}let[V,...z]=Z,G=V==="*"?z.length===0?["","",Yl]:["","",xZ0]:V==="/*"?["","",Xl]:V.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),F;if(G){let q=G[1],W=G[2]||xZ0;if(q&&G[2]){if(W===".*")throw pA;if(W=W.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(W))throw pA}if(F=this.#Z[W],!F){if(Object.keys(this.#Z).some((U)=>U!==Yl&&U!==Xl))throw pA;if(K)return;if(F=this.#Z[W]=new J,q!=="")F.#J=X.varIndex++}if(!K&&q!=="")Y.push([q,F.#J])}else if(F=this.#Z[V],!F){if(Object.keys(this.#Z).some((q)=>q.length>1&&q!==Yl&&q!==Xl))throw pA;if(K)return;F=this.#Z[V]=new J}F.insert(z,Q,Y,X,K)}buildRegExpStr(){let Q=Object.keys(this.#Z).sort(ar5).map((Y)=>{let X=this.#Z[Y];return(typeof X.#J==="number"?`(${Y})@${X.#J}`:nr5.has(Y)?`\\${Y}`:Y)+X.buildRegExpStr()});if(typeof this.#$==="number")Q.unshift(`#${this.#$}`);if(Q.length===0)return"";if(Q.length===1)return Q[0];return"(?:"+Q.join("|")+")"}};var dw4=class{#$={varIndex:0};#J=new pw4;insert(J,Z,Q){let Y=[],X=[];for(let V=0;;){let z=!1;if(J=J.replace(/\{[^}]+\}/g,(G)=>{let F=`@\\${V}`;return X[V]=[F,G],V++,z=!0,F}),!z)break}let K=J.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let V=X.length-1;V>=0;V--){let[z]=X[V];for(let G=K.length-1;G>=0;G--)if(K[G].indexOf(z)!==-1){K[G]=K[G].replace(z,X[V][1]);break}}return this.#J.insert(K,Z,Y,this.#$,Q),Y}buildRegExp(){let J=this.#J.buildRegExpStr();if(J==="")return[/^$/,[],[]];let Z=0,Q=[],Y=[];return J=J.replace(/#(\d+)|@(\d+)|\.\*\$/g,(X,K,V)=>{if(K!==void 0)return Q[++Z]=Number(K),"$()";if(V!==void 0)return Y[Number(V)]=++Z,"";return""}),[new RegExp(`^${J}`),Q,Y]}};var or5=[/^$/,[],Object.create(null)],cw4=Object.create(null);function lw4(J){return cw4[J]??=new RegExp(J==="*"?"":`^${J.replace(/\/\*$|([.\\+*[^\]$()])/g,(Z,Q)=>Q?`\\${Q}`:"(?:|/.*)")}$`)}function rr5(){cw4=Object.create(null)}function sr5(J){let Z=new dw4,Q=[];if(J.length===0)return or5;let Y=J.map((F)=>[!/\*|\/:/.test(F[0]),...F]).sort(([F,q],[W,U])=>F?1:W?-1:q.length-U.length),X=Object.create(null);for(let F=0,q=-1,W=Y.length;F<W;F++){let[U,H,D]=Y[F];if(U)X[H]=[D.map(([N])=>[N,Object.create(null)]),Ql];else q++;let B;try{B=Z.insert(H,q,U)}catch(N){throw N===pA?new vZ0(H):N}if(U)continue;Q[q]=D.map(([N,w])=>{let L=Object.create(null);w-=1;for(;w>=0;w--){let[O,E]=B[w];L[O]=E}return[N,L]})}let[K,V,z]=Z.buildRegExp();for(let F=0,q=Q.length;F<q;F++)for(let W=0,U=Q[F].length;W<U;W++){let H=Q[F][W]?.[1];if(!H)continue;let D=Object.keys(H);for(let B=0,N=D.length;B<N;B++)H[D[B]]=z[H[D[B]]]}let G=[];for(let F in V)G[F]=Q[V[F]];return[K,G,X]}function Ok(J,Z){if(!J)return;for(let Q of Object.keys(J).sort((Y,X)=>X.length-Y.length))if(lw4(Q).test(Z))return[...J[Q]];return}var fZ0=class{name="RegExpRouter";#$;#J;constructor(){this.#$={[M8]:Object.create(null)},this.#J={[M8]:Object.create(null)}}add(J,Z,Q){let Y=this.#$,X=this.#J;if(!Y||!X)throw Error(kZ0);if(!Y[J])[Y,X].forEach((z)=>{z[J]=Object.create(null),Object.keys(z[M8]).forEach((G)=>{z[J][G]=[...z[M8][G]]})});if(Z==="/*")Z="*";let K=(Z.match(/\/:/g)||[]).length;if(/\*$/.test(Z)){let z=lw4(Z);if(J===M8)Object.keys(Y).forEach((G)=>{Y[G][Z]||=Ok(Y[G],Z)||Ok(Y[M8],Z)||[]});else Y[J][Z]||=Ok(Y[J],Z)||Ok(Y[M8],Z)||[];Object.keys(Y).forEach((G)=>{if(J===M8||J===G)Object.keys(Y[G]).forEach((F)=>{z.test(F)&&Y[G][F].push([Q,K])})}),Object.keys(X).forEach((G)=>{if(J===M8||J===G)Object.keys(X[G]).forEach((F)=>z.test(F)&&X[G][F].push([Q,K]))});return}let V=TZ0(Z)||[Z];for(let z=0,G=V.length;z<G;z++){let F=V[z];Object.keys(X).forEach((q)=>{if(J===M8||J===q)X[q][F]||=[...Ok(Y[q],F)||Ok(Y[M8],F)||[]],X[q][F].push([Q,K-G+z+1])})}}match=yZ0;buildAllMatchers(){let J=Object.create(null);return Object.keys(this.#J).concat(Object.keys(this.#$)).forEach((Z)=>{J[Z]||=this.#Z(Z)}),this.#$=this.#J=void 0,rr5(),J}#Z(J){let Z=[],Q=J===M8;if([this.#$,this.#J].forEach((Y)=>{let X=Y[J]?Object.keys(Y[J]).map((K)=>[K,Y[J][K]]):[];if(X.length!==0)Q||=!0,Z.push(...X);else if(J!==M8)Z.push(...Object.keys(Y[M8]).map((K)=>[K,Y[M8][K]]))}),!Q)return null;else return sr5(Z)}};mA();var tr5=class{name="PreparedRegExpRouter";#$;#J;constructor(J,Z){this.#$=J,this.#J=Z}#Z(J,Z){let Q=this.#$[J];Q[1].forEach((Y)=>Y&&Y.push(Z)),Object.values(Q[2]).forEach((Y)=>Y[0].push(Z))}#Q(J,Z,Q,Y,X){let K=this.#$[J];if(!X)K[2][Z][0].push([Q,{}]);else Y.forEach((V)=>{if(typeof V==="number")K[1][V].push([Q,X]);else K[2][V||Z][0].push([Q,X])})}add(J,Z,Q){if(!this.#$[J]){let X=this.#$[M8],K={};for(let V in X[2])K[V]=[X[2][V][0].slice(),Ql];this.#$[J]=[X[0],X[1].map((V)=>Array.isArray(V)?V.slice():0),K]}if(Z==="/*"||Z==="*"){let X=[Q,{}];if(J===M8)for(let K in this.#$)this.#Z(K,X);else this.#Z(J,X);return}let Y=this.#J[Z];if(!Y)throw Error(`Path ${Z} is not registered`);for(let[X,K]of Y)if(J===M8)for(let V in this.#$)this.#Q(V,Z,Q,X,K);else this.#Q(J,Z,Q,X,K)}buildAllMatchers(){return this.#$}match=yZ0};mA();var fc0=class{name="SmartRouter";#$=[];#J=[];constructor(J){this.#$=J.routers}add(J,Z,Q){if(!this.#J)throw Error(kZ0);this.#J.push([J,Z,Q])}match(J,Z){if(!this.#J)throw Error("Fatal error");let Q=this.#$,Y=this.#J,X=Q.length,K=0,V;for(;K<X;K++){let z=Q[K];try{for(let G=0,F=Y.length;G<F;G++)z.add(...Y[G]);V=z.match(J,Z)}catch(G){if(G instanceof vZ0)continue;throw G}this.match=z.match.bind(z),this.#$=[z],this.#J=void 0;break}if(K===X)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,V}get activeRouter(){if(this.#J||this.#$.length!==1)throw Error("No active router has been determined yet.");return this.#$[0]}};oN();mA();oN();var Kl=Object.create(null),er5=(J)=>{for(let Z in J)return!0;return!1},iw4=class J{#$;#J;#Z;#Q=0;#Y=Kl;constructor(Z,Q,Y){if(this.#J=Y||Object.create(null),this.#$=[],Z&&Q){let X=Object.create(null);X[Z]={handler:Q,possibleKeys:[],score:0},this.#$=[X]}this.#Z=[]}insert(Z,Q,Y){this.#Q=++this.#Q;let X=this,K=jw4(Q),V=[];for(let z=0,G=K.length;z<G;z++){let F=K[z],q=K[z+1],W=Rw4(F,q),U=Array.isArray(W)?W[0]:F;if(U in X.#J){if(X=X.#J[U],W)V.push(W[1]);continue}if(X.#J[U]=new J,W)X.#Z.push(W),V.push(W[1]);X=X.#J[U]}return X.#$.push({[Z]:{handler:Y,possibleKeys:V.filter((z,G,F)=>F.indexOf(z)===G),score:this.#Q}}),X}#X(Z,Q,Y,X,K){for(let V=0,z=Q.#$.length;V<z;V++){let G=Q.#$[V],F=G[Y]||G[M8],q={};if(F!==void 0){if(F.params=Object.create(null),Z.push(F),X!==Kl||K&&K!==Kl)for(let W=0,U=F.possibleKeys.length;W<U;W++){let H=F.possibleKeys[W],D=q[F.score];F.params[H]=K?.[H]&&!D?K[H]:X[H]??K?.[H],q[F.score]=!0}}}}search(Z,Q){let Y=[];this.#Y=Kl;let K=[this],V=Sc0(Q),z=[],G=V.length,F=null;for(let q=0;q<G;q++){let W=V[q],U=q===G-1,H=[];for(let B=0,N=K.length;B<N;B++){let w=K[B],L=w.#J[W];if(L)if(L.#Y=w.#Y,U){if(L.#J["*"])this.#X(Y,L.#J["*"],Z,w.#Y);this.#X(Y,L,Z,w.#Y)}else H.push(L);for(let O=0,E=w.#Z.length;O<E;O++){let M=w.#Z[O],A=w.#Y===Kl?{}:{...w.#Y};if(M==="*"){let u=w.#J["*"];if(u)this.#X(Y,u,Z,w.#Y),u.#Y=A,H.push(u);continue}let[j,R,_]=M;if(!W&&!(_ instanceof RegExp))continue;let T=w.#J[j];if(_ instanceof RegExp){if(F===null){F=Array(G);let y=Q[0]==="/"?1:0;for(let k=0;k<G;k++)F[k]=y,y+=V[k].length+1}let u=Q.substring(F[q]),m=_.exec(u);if(m){if(A[R]=m[0],this.#X(Y,T,Z,w.#Y,A),er5(T.#J)){T.#Y=A;let y=m[0].match(/\//)?.length??0;(z[y]||=[]).push(T)}continue}}if(_===!0||_.test(W))if(A[R]=W,U){if(this.#X(Y,T,Z,A,w.#Y),T.#J["*"])this.#X(Y,T.#J["*"],Z,A,w.#Y)}else T.#Y=A,H.push(T)}}let D=z.shift();K=D?H.concat(D):H}if(Y.length>1)Y.sort((q,W)=>{return q.score-W.score});return[Y.map(({handler:q,params:W})=>[q,W])]}};var uc0=class{name="TrieRouter";#$;constructor(){this.#$=new iw4}add(J,Z,Q){let Y=TZ0(Z);if(Y){for(let X=0,K=Y.length;X<K;X++)this.#$.insert(J,Y[X],Q);return}this.#$.insert(J,Z,Q)}match(J,Z){return this.#$.search(J,Z)}};var uZ0=class extends mw4{constructor(J={}){super(J);this.router=J.router??new fc0({routers:[new fZ0,new uc0]})}};oN();t$();Tc0(v);var ze5=B4(wz(),1);import Zs5 from"events";import PQ from"fs";import{EventEmitter as kl0}from"node:events";import RL4 from"node:stream";import{StringDecoder as Qs5}from"node:string_decoder";import CL4 from"node:path";import Tk from"node:fs";import{dirname as Bs5,parse as Ns5}from"path";import{EventEmitter as Rs5}from"events";import Ul0 from"assert";import{Buffer as eA}from"buffer";import*as sw4 from"zlib";import Is5 from"zlib";import{posix as Mk}from"node:path";import{basename as es5}from"node:path";import FQ0 from"fs";import Jq from"fs";import YL4 from"path";import{win32 as Ft5}from"node:path";import qL4 from"path";import pL4 from"node:fs";import Pt5 from"node:assert";import{randomBytes as dL4}from"node:crypto";import K3 from"node:fs";import B2 from"node:path";import cL4 from"fs";import OQ0 from"node:fs";import Al from"node:path";import pY from"node:fs";import bt5 from"node:fs/promises";import UQ0 from"node:path";import{join as sL4}from"node:path";import mY from"node:fs";import eL4 from"node:path";var $s5=Object.defineProperty,Js5=(J,Z)=>{for(var Q in Z)$s5(J,Q,{get:Z[Q],enumerable:!0})},nw4=typeof process=="object"&&process?process:{stdout:null,stderr:null},Ys5=(J)=>!!J&&typeof J=="object"&&(J instanceof Zj||J instanceof RL4||Xs5(J)||Ks5(J)),Xs5=(J)=>!!J&&typeof J=="object"&&J instanceof kl0&&typeof J.pipe=="function"&&J.pipe!==RL4.Writable.prototype.pipe,Ks5=(J)=>!!J&&typeof J=="object"&&J instanceof kl0&&typeof J.write=="function"&&typeof J.end=="function",$H=Symbol("EOF"),JH=Symbol("maybeEmitEnd"),rN=Symbol("emittedEnd"),bZ0=Symbol("emittingEnd"),Vl=Symbol("emittedError"),hZ0=Symbol("closed"),aw4=Symbol("read"),gZ0=Symbol("flush"),ow4=Symbol("flushChunk"),Oz=Symbol("encoding"),Ek=Symbol("decoder"),l2=Symbol("flowing"),zl=Symbol("paused"),Ik=Symbol("resume"),i2=Symbol("buffer"),BZ=Symbol("pipes"),n2=Symbol("bufferLength"),bc0=Symbol("bufferPush"),mZ0=Symbol("bufferShift"),OJ=Symbol("objectMode"),L7=Symbol("destroyed"),hc0=Symbol("error"),gc0=Symbol("emitData"),rw4=Symbol("emitEnd"),mc0=Symbol("emitEnd2"),tF=Symbol("async"),pc0=Symbol("abort"),pZ0=Symbol("aborted"),Gl=Symbol("signal"),dA=Symbol("dataListeners"),gY=Symbol("discarded"),Fl=(J)=>Promise.resolve().then(J),Vs5=(J)=>J(),zs5=(J)=>J==="end"||J==="finish"||J==="prefinish",Gs5=(J)=>J instanceof ArrayBuffer||!!J&&typeof J=="object"&&J.constructor&&J.constructor.name==="ArrayBuffer"&&J.byteLength>=0,Fs5=(J)=>!Buffer.isBuffer(J)&&ArrayBuffer.isView(J),IL4=class{src;dest;opts;ondrain;constructor(J,Z,Q){this.src=J,this.dest=Z,this.opts=Q,this.ondrain=()=>J[Ik](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(J){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},qs5=class extends IL4{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(J,Z,Q){super(J,Z,Q),this.proxyErrors=(Y)=>this.dest.emit("error",Y),J.on("error",this.proxyErrors)}},Ws5=(J)=>!!J.objectMode,Us5=(J)=>!J.objectMode&&!!J.encoding&&J.encoding!=="buffer",Zj=class extends kl0{[l2]=!1;[zl]=!1;[BZ]=[];[i2]=[];[OJ];[Oz];[tF];[Ek];[$H]=!1;[rN]=!1;[bZ0]=!1;[hZ0]=!1;[Vl]=null;[n2]=0;[L7]=!1;[Gl];[pZ0]=!1;[dA]=0;[gY]=!1;writable=!0;readable=!0;constructor(...J){let Z=J[0]||{};if(super(),Z.objectMode&&typeof Z.encoding=="string")throw TypeError("Encoding and objectMode may not be used together");Ws5(Z)?(this[OJ]=!0,this[Oz]=null):Us5(Z)?(this[Oz]=Z.encoding,this[OJ]=!1):(this[OJ]=!1,this[Oz]=null),this[tF]=!!Z.async,this[Ek]=this[Oz]?new Qs5(this[Oz]):null,Z&&Z.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[i2]}),Z&&Z.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[BZ]});let{signal:Q}=Z;Q&&(this[Gl]=Q,Q.aborted?this[pc0]():Q.addEventListener("abort",()=>this[pc0]()))}get bufferLength(){return this[n2]}get encoding(){return this[Oz]}set encoding(J){throw Error("Encoding must be set at instantiation time")}setEncoding(J){throw Error("Encoding must be set at instantiation time")}get objectMode(){return this[OJ]}set objectMode(J){throw Error("objectMode must be set at instantiation time")}get async(){return this[tF]}set async(J){this[tF]=this[tF]||!!J}[pc0](){this[pZ0]=!0,this.emit("abort",this[Gl]?.reason),this.destroy(this[Gl]?.reason)}get aborted(){return this[pZ0]}set aborted(J){}write(J,Z,Q){if(this[pZ0])return!1;if(this[$H])throw Error("write after end");if(this[L7])return this.emit("error",Object.assign(Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof Z=="function"&&(Q=Z,Z="utf8"),Z||(Z="utf8");let Y=this[tF]?Fl:Vs5;if(!this[OJ]&&!Buffer.isBuffer(J)){if(Fs5(J))J=Buffer.from(J.buffer,J.byteOffset,J.byteLength);else if(Gs5(J))J=Buffer.from(J);else if(typeof J!="string")throw Error("Non-contiguous data written to non-objectMode stream")}return this[OJ]?(this[l2]&&this[n2]!==0&&this[gZ0](!0),this[l2]?this.emit("data",J):this[bc0](J),this[n2]!==0&&this.emit("readable"),Q&&Y(Q),this[l2]):J.length?(typeof J=="string"&&!(Z===this[Oz]&&!this[Ek]?.lastNeed)&&(J=Buffer.from(J,Z)),Buffer.isBuffer(J)&&this[Oz]&&(J=this[Ek].write(J)),this[l2]&&this[n2]!==0&&this[gZ0](!0),this[l2]?this.emit("data",J):this[bc0](J),this[n2]!==0&&this.emit("readable"),Q&&Y(Q),this[l2]):(this[n2]!==0&&this.emit("readable"),Q&&Y(Q),this[l2])}read(J){if(this[L7])return null;if(this[gY]=!1,this[n2]===0||J===0||J&&J>this[n2])return this[JH](),null;this[OJ]&&(J=null),this[i2].length>1&&!this[OJ]&&(this[i2]=[this[Oz]?this[i2].join(""):Buffer.concat(this[i2],this[n2])]);let Z=this[aw4](J||null,this[i2][0]);return this[JH](),Z}[aw4](J,Z){if(this[OJ])this[mZ0]();else{let Q=Z;J===Q.length||J===null?this[mZ0]():typeof Q=="string"?(this[i2][0]=Q.slice(J),Z=Q.slice(0,J),this[n2]-=J):(this[i2][0]=Q.subarray(J),Z=Q.subarray(0,J),this[n2]-=J)}return this.emit("data",Z),!this[i2].length&&!this[$H]&&this.emit("drain"),Z}end(J,Z,Q){return typeof J=="function"&&(Q=J,J=void 0),typeof Z=="function"&&(Q=Z,Z="utf8"),J!==void 0&&this.write(J,Z),Q&&this.once("end",Q),this[$H]=!0,this.writable=!1,(this[l2]||!this[zl])&&this[JH](),this}[Ik](){this[L7]||(!this[dA]&&!this[BZ].length&&(this[gY]=!0),this[zl]=!1,this[l2]=!0,this.emit("resume"),this[i2].length?this[gZ0]():this[$H]?this[JH]():this.emit("drain"))}resume(){return this[Ik]()}pause(){this[l2]=!1,this[zl]=!0,this[gY]=!1}get destroyed(){return this[L7]}get flowing(){return this[l2]}get paused(){return this[zl]}[bc0](J){this[OJ]?this[n2]+=1:this[n2]+=J.length,this[i2].push(J)}[mZ0](){return this[OJ]?this[n2]-=1:this[n2]-=this[i2][0].length,this[i2].shift()}[gZ0](J=!1){do;while(this[ow4](this[mZ0]())&&this[i2].length);!J&&!this[i2].length&&!this[$H]&&this.emit("drain")}[ow4](J){return this.emit("data",J),this[l2]}pipe(J,Z){if(this[L7])return J;this[gY]=!1;let Q=this[rN];return Z=Z||{},J===nw4.stdout||J===nw4.stderr?Z.end=!1:Z.end=Z.end!==!1,Z.proxyErrors=!!Z.proxyErrors,Q?Z.end&&J.end():(this[BZ].push(Z.proxyErrors?new qs5(this,J,Z):new IL4(this,J,Z)),this[tF]?Fl(()=>this[Ik]()):this[Ik]()),J}unpipe(J){let Z=this[BZ].find((Q)=>Q.dest===J);Z&&(this[BZ].length===1?(this[l2]&&this[dA]===0&&(this[l2]=!1),this[BZ]=[]):this[BZ].splice(this[BZ].indexOf(Z),1),Z.unpipe())}addListener(J,Z){return this.on(J,Z)}on(J,Z){let Q=super.on(J,Z);if(J==="data")this[gY]=!1,this[dA]++,!this[BZ].length&&!this[l2]&&this[Ik]();else if(J==="readable"&&this[n2]!==0)super.emit("readable");else if(zs5(J)&&this[rN])super.emit(J),this.removeAllListeners(J);else if(J==="error"&&this[Vl]){let Y=Z;this[tF]?Fl(()=>Y.call(this,this[Vl])):Y.call(this,this[Vl])}return Q}removeListener(J,Z){return this.off(J,Z)}off(J,Z){let Q=super.off(J,Z);return J==="data"&&(this[dA]=this.listeners("data").length,this[dA]===0&&!this[gY]&&!this[BZ].length&&(this[l2]=!1)),Q}removeAllListeners(J){let Z=super.removeAllListeners(J);return(J==="data"||J===void 0)&&(this[dA]=0,!this[gY]&&!this[BZ].length&&(this[l2]=!1)),Z}get emittedEnd(){return this[rN]}[JH](){!this[bZ0]&&!this[rN]&&!this[L7]&&this[i2].length===0&&this[$H]&&(this[bZ0]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[hZ0]&&this.emit("close"),this[bZ0]=!1)}emit(J,...Z){let Q=Z[0];if(J!=="error"&&J!=="close"&&J!==L7&&this[L7])return!1;if(J==="data")return!this[OJ]&&!Q?!1:this[tF]?(Fl(()=>this[gc0](Q)),!0):this[gc0](Q);if(J==="end")return this[rw4]();if(J==="close"){if(this[hZ0]=!0,!this[rN]&&!this[L7])return!1;let X=super.emit("close");return this.removeAllListeners("close"),X}else if(J==="error"){this[Vl]=Q,super.emit(hc0,Q);let X=!this[Gl]||this.listeners("error").length?super.emit("error",Q):!1;return this[JH](),X}else if(J==="resume"){let X=super.emit("resume");return this[JH](),X}else if(J==="finish"||J==="prefinish"){let X=super.emit(J);return this.removeAllListeners(J),X}let Y=super.emit(J,...Z);return this[JH](),Y}[gc0](J){for(let Q of this[BZ])Q.dest.write(J)===!1&&this.pause();let Z=this[gY]?!1:super.emit("data",J);return this[JH](),Z}[rw4](){return this[rN]?!1:(this[rN]=!0,this.readable=!1,this[tF]?(Fl(()=>this[mc0]()),!0):this[mc0]())}[mc0](){if(this[Ek]){let Z=this[Ek].end();if(Z){for(let Q of this[BZ])Q.dest.write(Z);this[gY]||super.emit("data",Z)}}for(let Z of this[BZ])Z.end();let J=super.emit("end");return this.removeAllListeners("end"),J}async collect(){let J=Object.assign([],{dataLength:0});this[OJ]||(J.dataLength=0);let Z=this.promise();return this.on("data",(Q)=>{J.push(Q),this[OJ]||(J.dataLength+=Q.length)}),await Z,J}async concat(){if(this[OJ])throw Error("cannot concat in objectMode");let J=await this.collect();return this[Oz]?J.join(""):Buffer.concat(J,J.dataLength)}async promise(){return new Promise((J,Z)=>{this.on(L7,()=>Z(Error("stream destroyed"))),this.on("error",(Q)=>Z(Q)),this.on("end",()=>J())})}[Symbol.asyncIterator](){this[gY]=!1;let J=!1,Z=async()=>(this.pause(),J=!0,{value:void 0,done:!0});return{next:()=>{if(J)return Z();let Q=this.read();if(Q!==null)return Promise.resolve({done:!1,value:Q});if(this[$H])return Z();let Y,X,K=(F)=>{this.off("data",V),this.off("end",z),this.off(L7,G),Z(),X(F)},V=(F)=>{this.off("error",K),this.off("end",z),this.off(L7,G),this.pause(),Y({value:F,done:!!this[$H]})},z=()=>{this.off("error",K),this.off("data",V),this.off(L7,G),Z(),Y({done:!0,value:void 0})},G=()=>K(Error("stream destroyed"));return new Promise((F,q)=>{X=q,Y=F,this.once(L7,G),this.once("error",K),this.once("end",z),this.once("data",V)})},throw:Z,return:Z,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[gY]=!1;let J=!1,Z=()=>(this.pause(),this.off(hc0,Z),this.off(L7,Z),this.off("end",Z),J=!0,{done:!0,value:void 0}),Q=()=>{if(J)return Z();let Y=this.read();return Y===null?Z():{done:!1,value:Y}};return this.once("end",Z),this.once(hc0,Z),this.once(L7,Z),{next:Q,throw:Z,return:Z,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(J){if(this[L7])return J?this.emit("error",J):this.emit(L7),this;this[L7]=!0,this[gY]=!0,this[i2].length=0,this[n2]=0;let Z=this;return typeof Z.close=="function"&&!this[hZ0]&&Z.close(),J?this.emit("error",J):this.emit(L7),this}static get isStream(){return Ys5}},Hs5=PQ.writev,Xw=Symbol("_autoClose"),jz=Symbol("_close"),ql=Symbol("_ended"),x3=Symbol("_fd"),dc0=Symbol("_finished"),XH=Symbol("_flags"),cc0=Symbol("_flush"),ql0=Symbol("_handleChunk"),Wl0=Symbol("_makeBuf"),El=Symbol("_mode"),dZ0=Symbol("_needDrain"),_k=Symbol("_onerror"),Sk=Symbol("_onopen"),lc0=Symbol("_onread"),Pk=Symbol("_onwrite"),Kw=Symbol("_open"),Az=Symbol("_path"),$w=Symbol("_pos"),eF=Symbol("_queue"),Ck=Symbol("_read"),ic0=Symbol("_readSize"),YH=Symbol("_reading"),Wl=Symbol("_remain"),nc0=Symbol("_size"),tZ0=Symbol("_write"),cA=Symbol("_writing"),eZ0=Symbol("_defaultFlag"),tA=Symbol("_errored"),vl0=class extends Zj{[tA]=!1;[x3];[Az];[ic0];[YH]=!1;[nc0];[Wl];[Xw];constructor(J,Z){if(Z=Z||{},super(Z),this.readable=!0,this.writable=!1,typeof J!="string")throw TypeError("path must be a string");this[tA]=!1,this[x3]=typeof Z.fd=="number"?Z.fd:void 0,this[Az]=J,this[ic0]=Z.readSize||16777216,this[YH]=!1,this[nc0]=typeof Z.size=="number"?Z.size:1/0,this[Wl]=this[nc0],this[Xw]=typeof Z.autoClose=="boolean"?Z.autoClose:!0,typeof this[x3]=="number"?this[Ck]():this[Kw]()}get fd(){return this[x3]}get path(){return this[Az]}write(){throw TypeError("this is a readable stream")}end(){throw TypeError("this is a readable stream")}[Kw](){PQ.open(this[Az],"r",(J,Z)=>this[Sk](J,Z))}[Sk](J,Z){J?this[_k](J):(this[x3]=Z,this.emit("open",Z),this[Ck]())}[Wl0](){return Buffer.allocUnsafe(Math.min(this[ic0],this[Wl]))}[Ck](){if(!this[YH]){this[YH]=!0;let J=this[Wl0]();if(J.length===0)return process.nextTick(()=>this[lc0](null,0,J));PQ.read(this[x3],J,0,J.length,null,(Z,Q,Y)=>this[lc0](Z,Q,Y))}}[lc0](J,Z,Q){this[YH]=!1,J?this[_k](J):this[ql0](Z,Q)&&this[Ck]()}[jz](){if(this[Xw]&&typeof this[x3]=="number"){let J=this[x3];this[x3]=void 0,PQ.close(J,(Z)=>Z?this.emit("error",Z):this.emit("close"))}}[_k](J){this[YH]=!0,this[jz](),this.emit("error",J)}[ql0](J,Z){let Q=!1;return this[Wl]-=J,J>0&&(Q=super.write(J<Z.length?Z.subarray(0,J):Z)),(J===0||this[Wl]<=0)&&(Q=!1,this[jz](),super.end()),Q}emit(J,...Z){switch(J){case"prefinish":case"finish":return!1;case"drain":return typeof this[x3]=="number"&&this[Ck](),!1;case"error":return this[tA]?!1:(this[tA]=!0,super.emit(J,...Z));default:return super.emit(J,...Z)}}},Ds5=class extends vl0{[Kw](){let J=!0;try{this[Sk](null,PQ.openSync(this[Az],"r")),J=!1}finally{J&&this[jz]()}}[Ck](){let J=!0;try{if(!this[YH]){this[YH]=!0;do{let Z=this[Wl0](),Q=Z.length===0?0:PQ.readSync(this[x3],Z,0,Z.length,null);if(!this[ql0](Q,Z))break}while(!0);this[YH]=!1}J=!1}finally{J&&this[jz]()}}[jz](){if(this[Xw]&&typeof this[x3]=="number"){let J=this[x3];this[x3]=void 0,PQ.closeSync(J),this.emit("close")}}},HQ0=class extends Zs5{readable=!1;writable=!0;[tA]=!1;[cA]=!1;[ql]=!1;[eF]=[];[dZ0]=!1;[Az];[El];[Xw];[x3];[eZ0];[XH];[dc0]=!1;[$w];constructor(J,Z){Z=Z||{},super(Z),this[Az]=J,this[x3]=typeof Z.fd=="number"?Z.fd:void 0,this[El]=Z.mode===void 0?438:Z.mode,this[$w]=typeof Z.start=="number"?Z.start:void 0,this[Xw]=typeof Z.autoClose=="boolean"?Z.autoClose:!0;let Q=this[$w]!==void 0?"r+":"w";this[eZ0]=Z.flags===void 0,this[XH]=Z.flags===void 0?Q:Z.flags,this[x3]===void 0&&this[Kw]()}emit(J,...Z){if(J==="error"){if(this[tA])return!1;this[tA]=!0}return super.emit(J,...Z)}get fd(){return this[x3]}get path(){return this[Az]}[_k](J){this[jz](),this[cA]=!0,this.emit("error",J)}[Kw](){PQ.open(this[Az],this[XH],this[El],(J,Z)=>this[Sk](J,Z))}[Sk](J,Z){this[eZ0]&&this[XH]==="r+"&&J&&J.code==="ENOENT"?(this[XH]="w",this[Kw]()):J?this[_k](J):(this[x3]=Z,this.emit("open",Z),this[cA]||this[cc0]())}end(J,Z){return J&&this.write(J,Z),this[ql]=!0,!this[cA]&&!this[eF].length&&typeof this[x3]=="number"&&this[Pk](null,0),this}write(J,Z){return typeof J=="string"&&(J=Buffer.from(J,Z)),this[ql]?(this.emit("error",Error("write() after end()")),!1):this[x3]===void 0||this[cA]||this[eF].length?(this[eF].push(J),this[dZ0]=!0,!1):(this[cA]=!0,this[tZ0](J),!0)}[tZ0](J){PQ.write(this[x3],J,0,J.length,this[$w],(Z,Q)=>this[Pk](Z,Q))}[Pk](J,Z){J?this[_k](J):(this[$w]!==void 0&&typeof Z=="number"&&(this[$w]+=Z),this[eF].length?this[cc0]():(this[cA]=!1,this[ql]&&!this[dc0]?(this[dc0]=!0,this[jz](),this.emit("finish")):this[dZ0]&&(this[dZ0]=!1,this.emit("drain"))))}[cc0](){if(this[eF].length===0)this[ql]&&this[Pk](null,0);else if(this[eF].length===1)this[tZ0](this[eF].pop());else{let J=this[eF];this[eF]=[],Hs5(this[x3],J,this[$w],(Z,Q)=>this[Pk](Z,Q))}}[jz](){if(this[Xw]&&typeof this[x3]=="number"){let J=this[x3];this[x3]=void 0,PQ.close(J,(Z)=>Z?this.emit("error",Z):this.emit("close"))}}},PL4=class extends HQ0{[Kw](){let J;if(this[eZ0]&&this[XH]==="r+")try{J=PQ.openSync(this[Az],this[XH],this[El])}catch(Z){if(Z?.code==="ENOENT")return this[XH]="w",this[Kw]();throw Z}else J=PQ.openSync(this[Az],this[XH],this[El]);this[Sk](null,J)}[jz](){if(this[Xw]&&typeof this[x3]=="number"){let J=this[x3];this[x3]=void 0,PQ.closeSync(J),this.emit("close")}}[tZ0](J){let Z=!0;try{this[Pk](null,PQ.writeSync(this[x3],J,0,J.length,this[$w])),Z=!1}finally{if(Z)try{this[jz]()}catch{}}}},ws5=new Map([["C","cwd"],["f","file"],["z","gzip"],["P","preservePaths"],["U","unlink"],["strip-components","strip"],["stripComponents","strip"],["keep-newer","newer"],["keepNewer","newer"],["keep-newer-files","newer"],["keepNewerFiles","newer"],["k","keep"],["keep-existing","keep"],["keepExisting","keep"],["m","noMtime"],["no-mtime","noMtime"],["p","preserveOwner"],["L","follow"],["h","follow"],["onentry","onReadEntry"]]),Ls5=(J)=>!!J.sync&&!!J.file,Os5=(J)=>!J.sync&&!!J.file,Es5=(J)=>!!J.sync&&!J.file,Ms5=(J)=>!J.sync&&!J.file,As5=(J)=>!!J.file,js5=(J)=>{return ws5.get(J)||J},yl0=(J={})=>{if(!J)return{};let Z={};for(let[Q,Y]of Object.entries(J)){let X=js5(Q);Z[X]=Y}return Z.chmod===void 0&&Z.noChmod===!1&&(Z.chmod=!0),delete Z.noChmod,Z},_l=(J,Z,Q,Y,X)=>Object.assign((K=[],V,z)=>{Array.isArray(K)&&(V=K,K={}),typeof V=="function"&&(z=V,V=void 0),V?V=Array.from(V):V=[];let G=yl0(K);if(X?.(G,V),Ls5(G)){if(typeof z=="function")throw TypeError("callback not supported for sync tar functions");return J(G,V)}else if(Os5(G)){let F=Z(G,V),q=z||void 0;return q?F.then(()=>q(),q):F}else if(Es5(G)){if(typeof z=="function")throw TypeError("callback not supported for sync tar functions");return Q(G,V)}else if(Ms5(G)){if(typeof z=="function")throw TypeError("callback only supported with file option");return Y(G,V)}else throw Error("impossible options??")},{syncFile:J,asyncFile:Z,syncNoFile:Q,asyncNoFile:Y,validate:X}),Ps5=Is5.constants||{ZLIB_VERNUM:4736},Qq=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},Ps5)),Cs5=eA.concat,tw4=Object.getOwnPropertyDescriptor(eA,"concat"),Ts5=(J)=>J,ac0=tw4?.writable===!0||tw4?.set!==void 0?(J)=>{eA.concat=J?Ts5:Cs5}:(J)=>{},$j=Symbol("_superWrite"),cZ0=class extends Error{code;errno;constructor(J,Z){super("zlib: "+J.message,{cause:J}),this.code=J.code,this.errno=J.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+J.message,Error.captureStackTrace(this,Z??this.constructor)}get name(){return"ZlibError"}},oc0=Symbol("flushFlag"),xl0=class extends Zj{#$=!1;#J=!1;#Z;#Q;#Y;#X;#V;get sawError(){return this.#$}get handle(){return this.#X}get flushFlag(){return this.#Z}constructor(J,Z){if(!J||typeof J!="object")throw TypeError("invalid options for ZlibBase constructor");if(super(J),this.#Z=J.flush??0,this.#Q=J.finishFlush??0,this.#Y=J.fullFlushFlag??0,typeof sw4[Z]!="function")throw TypeError("Compression method not supported: "+Z);try{this.#X=new sw4[Z](J)}catch(Q){throw new cZ0(Q,this.constructor)}this.#V=(Q)=>{this.#$||(this.#$=!0,this.close(),this.emit("error",Q))},this.#X?.on("error",(Q)=>this.#V(new cZ0(Q))),this.once("end",()=>this.close)}close(){this.#X&&(this.#X.close(),this.#X=void 0,this.emit("close"))}reset(){if(!this.#$)return Ul0(this.#X,"zlib binding closed"),this.#X.reset?.()}flush(J){this.ended||(typeof J!="number"&&(J=this.#Y),this.write(Object.assign(eA.alloc(0),{[oc0]:J})))}end(J,Z,Q){return typeof J=="function"&&(Q=J,Z=void 0,J=void 0),typeof Z=="function"&&(Q=Z,Z=void 0),J&&(Z?this.write(J,Z):this.write(J)),this.flush(this.#Q),this.#J=!0,super.end(Q)}get ended(){return this.#J}[$j](J){return super.write(J)}write(J,Z,Q){if(typeof Z=="function"&&(Q=Z,Z="utf8"),typeof J=="string"&&(J=eA.from(J,Z)),this.#$)return;Ul0(this.#X,"zlib binding closed");let Y=this.#X._handle,X=Y.close;Y.close=()=>{};let K=this.#X.close;this.#X.close=()=>{},ac0(!0);let V;try{let G=typeof J[oc0]=="number"?J[oc0]:this.#Z;V=this.#X._processChunk(J,G),ac0(!1)}catch(G){ac0(!1),this.#V(new cZ0(G,this.write))}finally{this.#X&&(this.#X._handle=Y,Y.close=X,this.#X.close=K,this.#X.removeAllListeners("error"))}this.#X&&this.#X.on("error",(G)=>this.#V(new cZ0(G,this.write)));let z;if(V)if(Array.isArray(V)&&V.length>0){let G=V[0];z=this[$j](eA.from(G));for(let F=1;F<V.length;F++)z=this[$j](V[F])}else z=this[$j](eA.from(V));return Q&&Q(),z}},TL4=class extends xl0{#$;#J;constructor(J,Z){J=J||{},J.flush=J.flush||Qq.Z_NO_FLUSH,J.finishFlush=J.finishFlush||Qq.Z_FINISH,J.fullFlushFlag=Qq.Z_FULL_FLUSH,super(J,Z),this.#$=J.level,this.#J=J.strategy}params(J,Z){if(!this.sawError){if(!this.handle)throw Error("cannot switch params when binding is closed");if(!this.handle.params)throw Error("not supported in this implementation");if(this.#$!==J||this.#J!==Z){this.flush(Qq.Z_SYNC_FLUSH),Ul0(this.handle,"zlib binding closed");let Q=this.handle.flush;this.handle.flush=(Y,X)=>{typeof Y=="function"&&(X=Y,Y=this.flushFlag),this.flush(Y),X?.()};try{this.handle.params(J,Z)}finally{this.handle.flush=Q}this.handle&&(this.#$=J,this.#J=Z)}}}},_s5=class extends TL4{#$;constructor(J){super(J,"Gzip"),this.#$=J&&!!J.portable}[$j](J){return this.#$?(this.#$=!1,J[9]=255,super[$j](J)):super[$j](J)}},Ss5=class extends TL4{constructor(J){super(J,"Unzip")}},_L4=class extends xl0{constructor(J,Z){J=J||{},J.flush=J.flush||Qq.BROTLI_OPERATION_PROCESS,J.finishFlush=J.finishFlush||Qq.BROTLI_OPERATION_FINISH,J.fullFlushFlag=Qq.BROTLI_OPERATION_FLUSH,super(J,Z)}},ks5=class extends _L4{constructor(J){super(J,"BrotliCompress")}},vs5=class extends _L4{constructor(J){super(J,"BrotliDecompress")}},SL4=class extends xl0{constructor(J,Z){J=J||{},J.flush=J.flush||Qq.ZSTD_e_continue,J.finishFlush=J.finishFlush||Qq.ZSTD_e_end,J.fullFlushFlag=Qq.ZSTD_e_flush,super(J,Z)}},ys5=class extends SL4{constructor(J){super(J,"ZstdCompress")}},xs5=class extends SL4{constructor(J){super(J,"ZstdDecompress")}},fs5=(J,Z)=>{if(Number.isSafeInteger(J))J<0?bs5(J,Z):us5(J,Z);else throw Error("cannot encode number outside of javascript safe integer range");return Z},us5=(J,Z)=>{Z[0]=128;for(var Q=Z.length;Q>1;Q--)Z[Q-1]=J&255,J=Math.floor(J/256)},bs5=(J,Z)=>{Z[0]=255;var Q=!1;J=J*-1;for(var Y=Z.length;Y>1;Y--){var X=J&255;J=Math.floor(J/256),Q?Z[Y-1]=kL4(X):X===0?Z[Y-1]=0:(Q=!0,Z[Y-1]=vL4(X))}},hs5=(J)=>{let Z=J[0],Q=Z===128?ms5(J.subarray(1,J.length)):Z===255?gs5(J):null;if(Q===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(Q))throw Error("parsed number outside of javascript safe integer range");return Q},gs5=(J)=>{for(var Z=J.length,Q=0,Y=!1,X=Z-1;X>-1;X--){var K=Number(J[X]),V;Y?V=kL4(K):K===0?V=K:(Y=!0,V=vL4(K)),V!==0&&(Q-=V*Math.pow(256,Z-X-1))}return Q},ms5=(J)=>{for(var Z=J.length,Q=0,Y=Z-1;Y>-1;Y--){var X=Number(J[Y]);X!==0&&(Q+=X*Math.pow(256,Z-Y-1))}return Q},kL4=(J)=>(255^J)&255,vL4=(J)=>(255^J)+1&255,ps5={};Js5(ps5,{code:()=>fl0,isCode:()=>$Q0,isName:()=>ds5,name:()=>DQ0});var $Q0=(J)=>DQ0.has(J),ds5=(J)=>fl0.has(J),DQ0=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]),fl0=new Map(Array.from(DQ0).map((J)=>[J[1],J[0]])),Jj=class{cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#$="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(J,Z=0,Q,Y){Buffer.isBuffer(J)?this.decode(J,Z||0,Q,Y):J&&this.#J(J)}decode(J,Z,Q,Y){if(Z||(Z=0),!J||!(J.length>=Z+512))throw Error("need 512 bytes for header");this.path=Q?.path??lA(J,Z,100),this.mode=Q?.mode??Y?.mode??Jw(J,Z+100,8),this.uid=Q?.uid??Y?.uid??Jw(J,Z+108,8),this.gid=Q?.gid??Y?.gid??Jw(J,Z+116,8),this.size=Q?.size??Y?.size??Jw(J,Z+124,12),this.mtime=Q?.mtime??Y?.mtime??rc0(J,Z+136,12),this.cksum=Jw(J,Z+148,12),Y&&this.#J(Y,!0),Q&&this.#J(Q);let X=lA(J,Z+156,1);if($Q0(X)&&(this.#$=X||"0"),this.#$==="0"&&this.path.slice(-1)==="/"&&(this.#$="5"),this.#$==="5"&&(this.size=0),this.linkpath=lA(J,Z+157,100),J.subarray(Z+257,Z+265).toString()==="ustar\x0000")if(this.uname=Q?.uname??Y?.uname??lA(J,Z+265,32),this.gname=Q?.gname??Y?.gname??lA(J,Z+297,32),this.devmaj=Q?.devmaj??Y?.devmaj??Jw(J,Z+329,8)??0,this.devmin=Q?.devmin??Y?.devmin??Jw(J,Z+337,8)??0,J[Z+475]!==0){let V=lA(J,Z+345,155);this.path=V+"/"+this.path}else{let V=lA(J,Z+345,130);V&&(this.path=V+"/"+this.path),this.atime=Q?.atime??Y?.atime??rc0(J,Z+476,12),this.ctime=Q?.ctime??Y?.ctime??rc0(J,Z+488,12)}let K=256;for(let V=Z;V<Z+148;V++)K+=J[V];for(let V=Z+156;V<Z+512;V++)K+=J[V];this.cksumValid=K===this.cksum,this.cksum===void 0&&K===256&&(this.nullBlock=!0)}#J(J,Z=!1){Object.assign(this,Object.fromEntries(Object.entries(J).filter(([Q,Y])=>!(Y==null||Q==="path"&&Z||Q==="linkpath"&&Z||Q==="global"))))}encode(J,Z=0){if(J||(J=this.block=Buffer.alloc(512)),this.#$==="Unsupported"&&(this.#$="0"),!(J.length>=Z+512))throw Error("need 512 bytes for header");let Q=this.ctime||this.atime?130:155,Y=cs5(this.path||"",Q),X=Y[0],K=Y[1];this.needPax=!!Y[2],this.needPax=iA(J,Z,100,X)||this.needPax,this.needPax=Zw(J,Z+100,8,this.mode)||this.needPax,this.needPax=Zw(J,Z+108,8,this.uid)||this.needPax,this.needPax=Zw(J,Z+116,8,this.gid)||this.needPax,this.needPax=Zw(J,Z+124,12,this.size)||this.needPax,this.needPax=sc0(J,Z+136,12,this.mtime)||this.needPax,J[Z+156]=this.#$.charCodeAt(0),this.needPax=iA(J,Z+157,100,this.linkpath)||this.needPax,J.write("ustar\x0000",Z+257,8),this.needPax=iA(J,Z+265,32,this.uname)||this.needPax,this.needPax=iA(J,Z+297,32,this.gname)||this.needPax,this.needPax=Zw(J,Z+329,8,this.devmaj)||this.needPax,this.needPax=Zw(J,Z+337,8,this.devmin)||this.needPax,this.needPax=iA(J,Z+345,Q,K)||this.needPax,J[Z+475]!==0?this.needPax=iA(J,Z+345,155,K)||this.needPax:(this.needPax=iA(J,Z+345,130,K)||this.needPax,this.needPax=sc0(J,Z+476,12,this.atime)||this.needPax,this.needPax=sc0(J,Z+488,12,this.ctime)||this.needPax);let V=256;for(let z=Z;z<Z+148;z++)V+=J[z];for(let z=Z+156;z<Z+512;z++)V+=J[z];return this.cksum=V,Zw(J,Z+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#$==="Unsupported"?this.#$:DQ0.get(this.#$)}get typeKey(){return this.#$}set type(J){let Z=String(fl0.get(J));if($Q0(Z)||Z==="Unsupported")this.#$=Z;else if($Q0(J))this.#$=J;else throw TypeError("invalid entry type: "+J)}},cs5=(J,Z)=>{let Q=J,Y="",X,K=Mk.parse(J).root||".";if(Buffer.byteLength(Q)<100)X=[Q,Y,!1];else{Y=Mk.dirname(Q),Q=Mk.basename(Q);do Buffer.byteLength(Q)<=100&&Buffer.byteLength(Y)<=Z?X=[Q,Y,!1]:Buffer.byteLength(Q)>100&&Buffer.byteLength(Y)<=Z?X=[Q.slice(0,99),Y,!0]:(Q=Mk.join(Mk.basename(Y),Q),Y=Mk.dirname(Y));while(Y!==K&&X===void 0);X||(X=[J.slice(0,99),"",!0])}return X},lA=(J,Z,Q)=>J.subarray(Z,Z+Q).toString("utf8").replace(/\0.*/,""),rc0=(J,Z,Q)=>ls5(Jw(J,Z,Q)),ls5=(J)=>J===void 0?void 0:new Date(J*1000),Jw=(J,Z,Q)=>Number(J[Z])&128?hs5(J.subarray(Z,Z+Q)):ns5(J,Z,Q),is5=(J)=>isNaN(J)?void 0:J,ns5=(J,Z,Q)=>is5(parseInt(J.subarray(Z,Z+Q).toString("utf8").replace(/\0.*$/,"").trim(),8)),as5={12:8589934591,8:2097151},Zw=(J,Z,Q,Y)=>Y===void 0?!1:Y>as5[Q]||Y<0?(fs5(Y,J.subarray(Z,Z+Q)),!0):(os5(J,Z,Q,Y),!1),os5=(J,Z,Q,Y)=>J.write(rs5(Y,Q),Z,Q,"ascii"),rs5=(J,Z)=>ss5(Math.floor(J).toString(8),Z),ss5=(J,Z)=>(J.length===Z-1?J:Array(Z-J.length-1).join("0")+J+" ")+"\x00",sc0=(J,Z,Q,Y)=>Y===void 0?!1:Zw(J,Z,Q,Y.getTime()/1000),ts5=Array(156).join("\x00"),iA=(J,Z,Q,Y)=>Y===void 0?!1:(J.write(Y+ts5,Z,Q,"utf8"),Y.length!==Buffer.byteLength(Y)||Y.length>Q),GQ0=class J{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(Z,Q=!1){this.atime=Z.atime,this.charset=Z.charset,this.comment=Z.comment,this.ctime=Z.ctime,this.dev=Z.dev,this.gid=Z.gid,this.global=Q,this.gname=Z.gname,this.ino=Z.ino,this.linkpath=Z.linkpath,this.mtime=Z.mtime,this.nlink=Z.nlink,this.path=Z.path,this.size=Z.size,this.uid=Z.uid,this.uname=Z.uname}encode(){let Z=this.encodeBody();if(Z==="")return Buffer.allocUnsafe(0);let Q=Buffer.byteLength(Z),Y=512*Math.ceil(1+Q/512),X=Buffer.allocUnsafe(Y);for(let K=0;K<512;K++)X[K]=0;new Jj({path:("PaxHeader/"+es5(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:Q,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(X),X.write(Z,512,Q,"utf8");for(let K=Q+512;K<X.length;K++)X[K]=0;return X}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(Z){if(this[Z]===void 0)return"";let Q=this[Z],Y=Q instanceof Date?Q.getTime()/1000:Q,X=" "+(Z==="dev"||Z==="ino"||Z==="nlink"?"SCHILY.":"")+Z+"="+Y+`
|
|
4668
4666
|
`,K=Buffer.byteLength(X),V=Math.floor(Math.log(K)/Math.log(10))+1;return K+V>=Math.pow(10,V)&&(V+=1),V+K+X}static parse(Z,Q,Y=!1){return new J($t5(Jt5(Z),Q),Y)}},$t5=(J,Z)=>Z?Object.assign({},Z,J):J,Jt5=(J)=>J.replace(/\n$/,"").split(`
|
|
4669
|
-
`).reduce(Zt5,Object.create(null)),Zt5=(J,Z)=>{let Q=parseInt(Z,10);if(Q!==Buffer.byteLength(Z)+1)return J;Z=Z.slice((Q+" ").length);let Y=Z.split("="),X=Y.shift();if(!X)return J;let K=X.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),V=Y.join("=");return J[K]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(K)?new Date(Number(V)*1000):/^[0-9]+$/.test(V)?+V:V,J},Qt5=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,A5=Qt5!=="win32"?(J)=>J:(J)=>J&&J.replace(/\\/g,"/"),yL4=class extends Zj{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(J,Z,Q){switch(super({}),this.pause(),this.extended=Z,this.globalExtended=Q,this.header=J,this.remain=J.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=J.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!J.path)throw Error("no path provided for tar.ReadEntry");this.path=A5(J.path),this.mode=J.mode,this.mode&&(this.mode=this.mode&4095),this.uid=J.uid,this.gid=J.gid,this.uname=J.uname,this.gname=J.gname,this.size=this.remain,this.mtime=J.mtime,this.atime=J.atime,this.ctime=J.ctime,this.linkpath=J.linkpath?A5(J.linkpath):void 0,this.uname=J.uname,this.gname=J.gname,Z&&this.#$(Z),Q&&this.#$(Q,!0)}write(J){let Z=J.length;if(Z>this.blockRemain)throw Error("writing more to entry than is appropriate");let Q=this.remain,Y=this.blockRemain;return this.remain=Math.max(0,Q-Z),this.blockRemain=Math.max(0,Y-Z),this.ignore?!0:Q>=Z?super.write(J):super.write(J.subarray(0,Q))}#$(J,Z=!1){J.path&&(J.path=A5(J.path)),J.linkpath&&(J.linkpath=A5(J.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(J).filter(([Q,Y])=>!(Y==null||Q==="path"&&Z))))}},BQ0=(J,Z,Q,Y={})=>{J.file&&(Y.file=J.file),J.cwd&&(Y.cwd=J.cwd),Y.code=Q instanceof Error&&Q.code||Z,Y.tarCode=Z,!J.strict&&Y.recoverable!==!1?(Q instanceof Error&&(Y=Object.assign(Q,Y),Q=Q.message),J.emit("warn",Z,Q,Y)):Q instanceof Error?J.emit("error",Object.assign(Q,Y)):J.emit("error",Object.assign(Error(`${Z}: ${Q}`),Y))},Yt5=1048576,Hl0=Buffer.from([31,139]),Dl0=Buffer.from([40,181,47,253]),Xt5=Math.max(Hl0.length,Dl0.length),TK=Symbol("state"),nA=Symbol("writeEntry"),ZH=Symbol("readEntry"),tc0=Symbol("nextEntry"),ew4=Symbol("processEntry"),$q=Symbol("extendedHeader"),Ul=Symbol("globalExtendedHeader"),sN=Symbol("meta"),$L4=Symbol("emitMeta"),g8=Symbol("buffer"),QH=Symbol("queue"),tN=Symbol("ended"),ec0=Symbol("emittedEnd"),aA=Symbol("emit"),l7=Symbol("unzip"),lZ0=Symbol("consumeChunk"),iZ0=Symbol("consumeChunkSub"),$l0=Symbol("consumeBody"),JL4=Symbol("consumeMeta"),ZL4=Symbol("consumeHeader"),Hl=Symbol("consuming"),Jl0=Symbol("bufferConcat"),nZ0=Symbol("maybeEnd"),Ak=Symbol("writing"),eN=Symbol("aborted"),aZ0=Symbol("onDone"),oA=Symbol("sawValidEntry"),oZ0=Symbol("sawNullBlock"),rZ0=Symbol("sawEOF"),QL4=Symbol("closeStream"),Kt5=()=>!0,Tl=class extends Rs5{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[QH]=[];[g8];[ZH];[nA];[TK]="begin";[sN]="";[$q];[Ul];[tN]=!1;[l7];[eN]=!1;[oA];[oZ0]=!1;[rZ0]=!1;[Ak]=!1;[Hl]=!1;[ec0]=!1;constructor(J={}){super(),this.file=J.file||"",this.on(aZ0,()=>{(this[TK]==="begin"||this[oA]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),J.ondone?this.on(aZ0,J.ondone):this.on(aZ0,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!J.strict,this.maxMetaEntrySize=J.maxMetaEntrySize||Yt5,this.filter=typeof J.filter=="function"?J.filter:Kt5;let Z=J.file&&(J.file.endsWith(".tar.br")||J.file.endsWith(".tbr"));this.brotli=!(J.gzip||J.zstd)&&J.brotli!==void 0?J.brotli:Z?void 0:!1;let Q=J.file&&(J.file.endsWith(".tar.zst")||J.file.endsWith(".tzst"));this.zstd=!(J.gzip||J.brotli)&&J.zstd!==void 0?J.zstd:Q?!0:void 0,this.on("end",()=>this[QL4]()),typeof J.onwarn=="function"&&this.on("warn",J.onwarn),typeof J.onReadEntry=="function"&&this.on("entry",J.onReadEntry)}warn(J,Z,Q={}){BQ0(this,J,Z,Q)}[ZL4](J,Z){this[oA]===void 0&&(this[oA]=!1);let Q;try{Q=new Jj(J,Z,this[$q],this[Ul])}catch(Y){return this.warn("TAR_ENTRY_INVALID",Y)}if(Q.nullBlock)this[oZ0]?(this[rZ0]=!0,this[TK]==="begin"&&(this[TK]="header"),this[aA]("eof")):(this[oZ0]=!0,this[aA]("nullBlock"));else if(this[oZ0]=!1,!Q.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:Q});else if(!Q.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:Q});else{let Y=Q.type;if(/^(Symbolic)?Link$/.test(Y)&&!Q.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:Q});else if(!/^(Symbolic)?Link$/.test(Y)&&!/^(Global)?ExtendedHeader$/.test(Y)&&Q.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:Q});else{let X=this[nA]=new yL4(Q,this[$q],this[Ul]);if(!this[oA])if(X.remain){let K=()=>{X.invalid||(this[oA]=!0)};X.on("end",K)}else this[oA]=!0;X.meta?X.size>this.maxMetaEntrySize?(X.ignore=!0,this[aA]("ignoredEntry",X),this[TK]="ignore",X.resume()):X.size>0&&(this[sN]="",X.on("data",(K)=>this[sN]+=K),this[TK]="meta"):(this[$q]=void 0,X.ignore=X.ignore||!this.filter(X.path,X),X.ignore?(this[aA]("ignoredEntry",X),this[TK]=X.remain?"ignore":"header",X.resume()):(X.remain?this[TK]="body":(this[TK]="header",X.end()),this[ZH]?this[QH].push(X):(this[QH].push(X),this[tc0]())))}}}[QL4](){queueMicrotask(()=>this.emit("close"))}[ew4](J){let Z=!0;if(!J)this[ZH]=void 0,Z=!1;else if(Array.isArray(J)){let[Q,...Y]=J;this.emit(Q,...Y)}else this[ZH]=J,this.emit("entry",J),J.emittedEnd||(J.on("end",()=>this[tc0]()),Z=!1);return Z}[tc0](){do;while(this[ew4](this[QH].shift()));if(!this[QH].length){let J=this[ZH];!J||J.flowing||J.size===J.remain?this[Ak]||this.emit("drain"):J.once("drain",()=>this.emit("drain"))}}[$l0](J,Z){let Q=this[nA];if(!Q)throw Error("attempt to consume body without entry??");let Y=Q.blockRemain??0,X=Y>=J.length&&Z===0?J:J.subarray(Z,Z+Y);return Q.write(X),Q.blockRemain||(this[TK]="header",this[nA]=void 0,Q.end()),X.length}[JL4](J,Z){let Q=this[nA],Y=this[$l0](J,Z);return!this[nA]&&Q&&this[$L4](Q),Y}[aA](J,Z,Q){!this[QH].length&&!this[ZH]?this.emit(J,Z,Q):this[QH].push([J,Z,Q])}[$L4](J){switch(this[aA]("meta",this[sN]),J.type){case"ExtendedHeader":case"OldExtendedHeader":this[$q]=GQ0.parse(this[sN],this[$q],!1);break;case"GlobalExtendedHeader":this[Ul]=GQ0.parse(this[sN],this[Ul],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let Z=this[$q]??Object.create(null);this[$q]=Z,Z.path=this[sN].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let Z=this[$q]||Object.create(null);this[$q]=Z,Z.linkpath=this[sN].replace(/\0.*/,"");break}default:throw Error("unknown meta: "+J.type)}}abort(J){this[eN]=!0,this.emit("abort",J),this.warn("TAR_ABORT",J,{recoverable:!1})}write(J,Z,Q){if(typeof Z=="function"&&(Q=Z,Z=void 0),typeof J=="string"&&(J=Buffer.from(J,typeof Z=="string"?Z:"utf8")),this[eN])return Q?.(),!1;if((this[l7]===void 0||this.brotli===void 0&&this[l7]===!1)&&J){if(this[g8]&&(J=Buffer.concat([this[g8],J]),this[g8]=void 0),J.length<Xt5)return this[g8]=J,Q?.(),!0;for(let V=0;this[l7]===void 0&&V<Hl0.length;V++)J[V]!==Hl0[V]&&(this[l7]=!1);let X=!1;if(this[l7]===!1&&this.zstd!==!1){X=!0;for(let V=0;V<Dl0.length;V++)if(J[V]!==Dl0[V]){X=!1;break}}let K=this.brotli===void 0&&!X;if(this[l7]===!1&&K)if(J.length<512)if(this[tN])this.brotli=!0;else return this[g8]=J,Q?.(),!0;else try{new Jj(J.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[l7]===void 0||this[l7]===!1&&(this.brotli||X)){let V=this[tN];this[tN]=!1,this[l7]=this[l7]===void 0?new Ss5({}):X?new xs5({}):new vs5({}),this[l7].on("data",(G)=>this[lZ0](G)),this[l7].on("error",(G)=>this.abort(G)),this[l7].on("end",()=>{this[tN]=!0,this[lZ0]()}),this[Ak]=!0;let z=!!this[l7][V?"end":"write"](J);return this[Ak]=!1,Q?.(),z}}this[Ak]=!0,this[l7]?this[l7].write(J):this[lZ0](J),this[Ak]=!1;let Y=this[QH].length?!1:this[ZH]?this[ZH].flowing:!0;return!Y&&!this[QH].length&&this[ZH]?.once("drain",()=>this.emit("drain")),Q?.(),Y}[Jl0](J){J&&!this[eN]&&(this[g8]=this[g8]?Buffer.concat([this[g8],J]):J)}[nZ0](){if(this[tN]&&!this[ec0]&&!this[eN]&&!this[Hl]){this[ec0]=!0;let J=this[nA];if(J&&J.blockRemain){let Z=this[g8]?this[g8].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${J.blockRemain} more bytes, only ${Z} available)`,{entry:J}),this[g8]&&J.write(this[g8]),J.end()}this[aA](aZ0)}}[lZ0](J){if(this[Hl]&&J)this[Jl0](J);else if(!J&&!this[g8])this[nZ0]();else if(J){if(this[Hl]=!0,this[g8]){this[Jl0](J);let Z=this[g8];this[g8]=void 0,this[iZ0](Z)}else this[iZ0](J);for(;this[g8]&&this[g8]?.length>=512&&!this[eN]&&!this[rZ0];){let Z=this[g8];this[g8]=void 0,this[iZ0](Z)}this[Hl]=!1}(!this[g8]||this[tN])&&this[nZ0]()}[iZ0](J){let Z=0,Q=J.length;for(;Z+512<=Q&&!this[eN]&&!this[rZ0];)switch(this[TK]){case"begin":case"header":this[ZL4](J,Z),Z+=512;break;case"ignore":case"body":Z+=this[$l0](J,Z);break;case"meta":Z+=this[JL4](J,Z);break;default:throw Error("invalid state: "+this[TK])}Z<Q&&(this[g8]?this[g8]=Buffer.concat([J.subarray(Z),this[g8]]):this[g8]=J.subarray(Z))}end(J,Z,Q){return typeof J=="function"&&(Q=J,Z=void 0,J=void 0),typeof Z=="function"&&(Q=Z,Z=void 0),typeof J=="string"&&(J=Buffer.from(J,Z)),Q&&this.once("finish",Q),this[eN]||(this[l7]?(J&&this[l7].write(J),this[l7].end()):(this[tN]=!0,(this.brotli===void 0||this.zstd===void 0)&&(J=J||Buffer.alloc(0)),J&&this.write(J),this[nZ0]())),this}},Ml=(J)=>{let Z=J.length-1,Q=-1;for(;Z>-1&&J.charAt(Z)==="/";)Q=Z,Z--;return Q===-1?J:J.slice(0,Q)},Vt5=(J)=>{let Z=J.onReadEntry;J.onReadEntry=Z?(Q)=>{Z(Q),Q.resume()}:(Q)=>Q.resume()},xL4=(J,Z)=>{let Q=new Map(Z.map((K)=>[Ml(K),!0])),Y=J.filter,X=(K,V="")=>{let z=V||Ns5(K).root||".",G;if(K===z)G=!1;else{let F=Q.get(K);F!==void 0?G=F:G=X(Bs5(K),z)}return Q.set(K,G),G};J.filter=Y?(K,V)=>Y(K,V)&&X(Ml(K)):(K)=>X(Ml(K))},zt5=(J)=>{let Z=new Tl(J),Q=J.file,Y;try{Y=Tk.openSync(Q,"r");let X=Tk.fstatSync(Y),K=J.maxReadSize||16777216;if(X.size<K){let V=Buffer.allocUnsafe(X.size),z=Tk.readSync(Y,V,0,X.size,0);Z.end(z===V.byteLength?V:V.subarray(0,z))}else{let V=0,z=Buffer.allocUnsafe(K);for(;V<X.size;){let G=Tk.readSync(Y,z,0,K,V);if(G===0)break;V+=G,Z.write(z.subarray(0,G))}Z.end()}}finally{if(typeof Y=="number")try{Tk.closeSync(Y)}catch{}}},Gt5=(J,Z)=>{let Q=new Tl(J),Y=J.maxReadSize||16777216,X=J.file;return new Promise((K,V)=>{Q.on("error",V),Q.on("end",K),Tk.stat(X,(z,G)=>{if(z)V(z);else{let F=new vl0(X,{readSize:Y,size:G.size});F.on("error",V),F.pipe(Q)}})})},NQ0=_l(zt5,Gt5,(J)=>new Tl(J),(J)=>new Tl(J),(J,Z)=>{Z?.length&&xL4(J,Z),J.noResume||Vt5(J)}),fL4=(J,Z,Q)=>(J&=4095,Q&&(J=(J|384)&-19),Z&&(J&256&&(J|=64),J&32&&(J|=8),J&4&&(J|=1)),J),{isAbsolute:qt5,parse:XL4}=Ft5,ul0=(J)=>{let Z="",Q=XL4(J);for(;qt5(J)||Q.root;){let Y=J.charAt(0)==="/"&&J.slice(0,4)!=="//?/"?"/":Q.root;J=J.slice(Y.length),Z+=Y,Q=XL4(J)}return[Z,J]},wQ0=["|","<",">","?",":"],bl0=wQ0.map((J)=>String.fromCharCode(61440+J.charCodeAt(0))),Wt5=new Map(wQ0.map((J,Z)=>[J,bl0[Z]])),Ut5=new Map(bl0.map((J,Z)=>[J,wQ0[Z]])),KL4=(J)=>wQ0.reduce((Z,Q)=>Z.split(Q).join(Wt5.get(Q)),J),Ht5=(J)=>bl0.reduce((Z,Q)=>Z.split(Q).join(Ut5.get(Q)),J),uL4=(J,Z)=>Z?(J=A5(J).replace(/^\.(\/|$)/,""),Ml(Z)+"/"+J):A5(J),Dt5=16777216,VL4=Symbol("process"),zL4=Symbol("file"),GL4=Symbol("directory"),Bl0=Symbol("symlink"),FL4=Symbol("hardlink"),Dl=Symbol("header"),JQ0=Symbol("read"),Nl0=Symbol("lstat"),ZQ0=Symbol("onlstat"),wl0=Symbol("onread"),Ll0=Symbol("onreadlink"),Ol0=Symbol("openfile"),El0=Symbol("onopenfile"),Qw=Symbol("close"),qQ0=Symbol("mode"),Ml0=Symbol("awaitDrain"),Zl0=Symbol("ondrain"),Zq=Symbol("prefix"),bL4=class extends Zj{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#$=!1;constructor(J,Z={}){let Q=yl0(Z);super(),this.path=A5(J),this.portable=!!Q.portable,this.maxReadSize=Q.maxReadSize||Dt5,this.linkCache=Q.linkCache||new Map,this.statCache=Q.statCache||new Map,this.preservePaths=!!Q.preservePaths,this.cwd=A5(Q.cwd||process.cwd()),this.strict=!!Q.strict,this.noPax=!!Q.noPax,this.noMtime=!!Q.noMtime,this.mtime=Q.mtime,this.prefix=Q.prefix?A5(Q.prefix):void 0,this.onWriteEntry=Q.onWriteEntry,typeof Q.onwarn=="function"&&this.on("warn",Q.onwarn);let Y=!1;if(!this.preservePaths){let[K,V]=ul0(this.path);K&&typeof V=="string"&&(this.path=V,Y=K)}this.win32=!!Q.win32||process.platform==="win32",this.win32&&(this.path=Ht5(this.path.replace(/\\/g,"/")),J=J.replace(/\\/g,"/")),this.absolute=A5(Q.absolute||YL4.resolve(this.cwd,J)),this.path===""&&(this.path="./"),Y&&this.warn("TAR_ENTRY_INFO",`stripping ${Y} from absolute path`,{entry:this,path:Y+this.path});let X=this.statCache.get(this.absolute);X?this[ZQ0](X):this[Nl0]()}warn(J,Z,Q={}){return BQ0(this,J,Z,Q)}emit(J,...Z){return J==="error"&&(this.#$=!0),super.emit(J,...Z)}[Nl0](){Jq.lstat(this.absolute,(J,Z)=>{if(J)return this.emit("error",J);this[ZQ0](Z)})}[ZQ0](J){this.statCache.set(this.absolute,J),this.stat=J,J.isFile()||(J.size=0),this.type=wt5(J),this.emit("stat",J),this[VL4]()}[VL4](){switch(this.type){case"File":return this[zL4]();case"Directory":return this[GL4]();case"SymbolicLink":return this[Bl0]();default:return this.end()}}[qQ0](J){return fL4(J,this.type==="Directory",this.portable)}[Zq](J){return uL4(J,this.prefix)}[Dl](){if(!this.stat)throw Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new Jj({path:this[Zq](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Zq](this.linkpath):this.linkpath,mode:this[qQ0](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new GQ0({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[Zq](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Zq](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let J=this.header?.block;if(!J)throw Error("failed to encode header");super.write(J)}[GL4](){if(!this.stat)throw Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[Dl](),this.end()}[Bl0](){Jq.readlink(this.absolute,(J,Z)=>{if(J)return this.emit("error",J);this[Ll0](Z)})}[Ll0](J){this.linkpath=A5(J),this[Dl](),this.end()}[FL4](J){if(!this.stat)throw Error("cannot create link entry without stat");this.type="Link",this.linkpath=A5(YL4.relative(this.cwd,J)),this.stat.size=0,this[Dl](),this.end()}[zL4](){if(!this.stat)throw Error("cannot create file entry without stat");if(this.stat.nlink>1){let J=`${this.stat.dev}:${this.stat.ino}`,Z=this.linkCache.get(J);if(Z?.indexOf(this.cwd)===0)return this[FL4](Z);this.linkCache.set(J,this.absolute)}if(this[Dl](),this.stat.size===0)return this.end();this[Ol0]()}[Ol0](){Jq.open(this.absolute,"r",(J,Z)=>{if(J)return this.emit("error",J);this[El0](Z)})}[El0](J){if(this.fd=J,this.#$)return this[Qw]();if(!this.stat)throw Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let Z=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(Z),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[JQ0]()}[JQ0](){let{fd:J,buf:Z,offset:Q,length:Y,pos:X}=this;if(J===void 0||Z===void 0)throw Error("cannot read file without first opening");Jq.read(J,Z,Q,Y,X,(K,V)=>{if(K)return this[Qw](()=>this.emit("error",K));this[wl0](V)})}[Qw](J=()=>{}){this.fd!==void 0&&Jq.close(this.fd,J)}[wl0](J){if(J<=0&&this.remain>0){let Q=Object.assign(Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[Qw](()=>this.emit("error",Q))}if(J>this.remain){let Q=Object.assign(Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[Qw](()=>this.emit("error",Q))}if(!this.buf)throw Error("should have created buffer prior to reading");if(J===this.remain)for(let Q=J;Q<this.length&&J<this.blockRemain;Q++)this.buf[Q+this.offset]=0,J++,this.remain++;let Z=this.offset===0&&J===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+J);this.write(Z)?this[Zl0]():this[Ml0](()=>this[Zl0]())}[Ml0](J){this.once("drain",J)}write(J,Z,Q){if(typeof Z=="function"&&(Q=Z,Z=void 0),typeof J=="string"&&(J=Buffer.from(J,typeof Z=="string"?Z:"utf8")),this.blockRemain<J.length){let Y=Object.assign(Error("writing more data than expected"),{path:this.absolute});return this.emit("error",Y)}return this.remain-=J.length,this.blockRemain-=J.length,this.pos+=J.length,this.offset+=J.length,super.write(J,null,Q)}[Zl0](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[Qw]((J)=>J?this.emit("error",J):this.end());if(!this.buf)throw Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[JQ0]()}},Bt5=class extends bL4{sync=!0;[Nl0](){this[ZQ0](Jq.lstatSync(this.absolute))}[Bl0](){this[Ll0](Jq.readlinkSync(this.absolute))}[Ol0](){this[El0](Jq.openSync(this.absolute,"r"))}[JQ0](){let J=!0;try{let{fd:Z,buf:Q,offset:Y,length:X,pos:K}=this;if(Z===void 0||Q===void 0)throw Error("fd and buf must be set in READ method");let V=Jq.readSync(Z,Q,Y,X,K);this[wl0](V),J=!1}finally{if(J)try{this[Qw](()=>{})}catch{}}}[Ml0](J){J()}[Qw](J=()=>{}){this.fd!==void 0&&Jq.closeSync(this.fd),J()}},Nt5=class extends Zj{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(J,Z,Q={}){return BQ0(this,J,Z,Q)}constructor(J,Z={}){let Q=yl0(Z);super(),this.preservePaths=!!Q.preservePaths,this.portable=!!Q.portable,this.strict=!!Q.strict,this.noPax=!!Q.noPax,this.noMtime=!!Q.noMtime,this.onWriteEntry=Q.onWriteEntry,this.readEntry=J;let{type:Y}=J;if(Y==="Unsupported")throw Error("writing entry that should be ignored");this.type=Y,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=Q.prefix,this.path=A5(J.path),this.mode=J.mode!==void 0?this[qQ0](J.mode):void 0,this.uid=this.portable?void 0:J.uid,this.gid=this.portable?void 0:J.gid,this.uname=this.portable?void 0:J.uname,this.gname=this.portable?void 0:J.gname,this.size=J.size,this.mtime=this.noMtime?void 0:Q.mtime||J.mtime,this.atime=this.portable?void 0:J.atime,this.ctime=this.portable?void 0:J.ctime,this.linkpath=J.linkpath!==void 0?A5(J.linkpath):void 0,typeof Q.onwarn=="function"&&this.on("warn",Q.onwarn);let X=!1;if(!this.preservePaths){let[V,z]=ul0(this.path);V&&typeof z=="string"&&(this.path=z,X=V)}this.remain=J.size,this.blockRemain=J.startBlockSize,this.onWriteEntry?.(this),this.header=new Jj({path:this[Zq](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Zq](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),X&&this.warn("TAR_ENTRY_INFO",`stripping ${X} from absolute path`,{entry:this,path:X+this.path}),this.header.encode()&&!this.noPax&&super.write(new GQ0({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[Zq](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Zq](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let K=this.header?.block;if(!K)throw Error("failed to encode header");super.write(K),J.pipe(this)}[Zq](J){return uL4(J,this.prefix)}[qQ0](J){return fL4(J,this.type==="Directory",this.portable)}write(J,Z,Q){typeof Z=="function"&&(Q=Z,Z=void 0),typeof J=="string"&&(J=Buffer.from(J,typeof Z=="string"?Z:"utf8"));let Y=J.length;if(Y>this.blockRemain)throw Error("writing more to entry than is appropriate");return this.blockRemain-=Y,super.write(J,Q)}end(J,Z,Q){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof J=="function"&&(Q=J,Z=void 0,J=void 0),typeof Z=="function"&&(Q=Z,Z=void 0),typeof J=="string"&&(J=Buffer.from(J,Z??"utf8")),Q&&this.once("finish",Q),J?super.end(J,Q):super.end(Q),this}},wt5=(J)=>J.isFile()?"File":J.isDirectory()?"Directory":J.isSymbolicLink()?"SymbolicLink":"Unsupported",Lt5=class J{tail;head;length=0;static create(Z=[]){return new J(Z)}constructor(Z=[]){for(let Q of Z)this.push(Q)}*[Symbol.iterator](){for(let Z=this.head;Z;Z=Z.next)yield Z.value}removeNode(Z){if(Z.list!==this)throw Error("removing node which does not belong to this list");let{next:Q,prev:Y}=Z;return Q&&(Q.prev=Y),Y&&(Y.next=Q),Z===this.head&&(this.head=Q),Z===this.tail&&(this.tail=Y),this.length--,Z.next=void 0,Z.prev=void 0,Z.list=void 0,Q}unshiftNode(Z){if(Z===this.head)return;Z.list&&Z.list.removeNode(Z);let Q=this.head;Z.list=this,Z.next=Q,Q&&(Q.prev=Z),this.head=Z,this.tail||(this.tail=Z),this.length++}pushNode(Z){if(Z===this.tail)return;Z.list&&Z.list.removeNode(Z);let Q=this.tail;Z.list=this,Z.prev=Q,Q&&(Q.next=Z),this.tail=Z,this.head||(this.head=Z),this.length++}push(...Z){for(let Q=0,Y=Z.length;Q<Y;Q++)Et5(this,Z[Q]);return this.length}unshift(...Z){for(var Q=0,Y=Z.length;Q<Y;Q++)Mt5(this,Z[Q]);return this.length}pop(){if(!this.tail)return;let Z=this.tail.value,Q=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,Q.list=void 0,this.length--,Z}shift(){if(!this.head)return;let Z=this.head.value,Q=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,Q.list=void 0,this.length--,Z}forEach(Z,Q){Q=Q||this;for(let Y=this.head,X=0;Y;X++)Z.call(Q,Y.value,X,this),Y=Y.next}forEachReverse(Z,Q){Q=Q||this;for(let Y=this.tail,X=this.length-1;Y;X--)Z.call(Q,Y.value,X,this),Y=Y.prev}get(Z){let Q=0,Y=this.head;for(;Y&&Q<Z;Q++)Y=Y.next;if(Q===Z&&Y)return Y.value}getReverse(Z){let Q=0,Y=this.tail;for(;Y&&Q<Z;Q++)Y=Y.prev;if(Q===Z&&Y)return Y.value}map(Z,Q){Q=Q||this;let Y=new J;for(let X=this.head;X;)Y.push(Z.call(Q,X.value,this)),X=X.next;return Y}mapReverse(Z,Q){Q=Q||this;var Y=new J;for(let X=this.tail;X;)Y.push(Z.call(Q,X.value,this)),X=X.prev;return Y}reduce(Z,Q){let Y,X=this.head;if(arguments.length>1)Y=Q;else if(this.head)X=this.head.next,Y=this.head.value;else throw TypeError("Reduce of empty list with no initial value");for(var K=0;X;K++)Y=Z(Y,X.value,K),X=X.next;return Y}reduceReverse(Z,Q){let Y,X=this.tail;if(arguments.length>1)Y=Q;else if(this.tail)X=this.tail.prev,Y=this.tail.value;else throw TypeError("Reduce of empty list with no initial value");for(let K=this.length-1;X;K--)Y=Z(Y,X.value,K),X=X.prev;return Y}toArray(){let Z=Array(this.length);for(let Q=0,Y=this.head;Y;Q++)Z[Q]=Y.value,Y=Y.next;return Z}toArrayReverse(){let Z=Array(this.length);for(let Q=0,Y=this.tail;Y;Q++)Z[Q]=Y.value,Y=Y.prev;return Z}slice(Z=0,Q=this.length){Q<0&&(Q+=this.length),Z<0&&(Z+=this.length);let Y=new J;if(Q<Z||Q<0)return Y;Z<0&&(Z=0),Q>this.length&&(Q=this.length);let X=this.head,K=0;for(K=0;X&&K<Z;K++)X=X.next;for(;X&&K<Q;K++,X=X.next)Y.push(X.value);return Y}sliceReverse(Z=0,Q=this.length){Q<0&&(Q+=this.length),Z<0&&(Z+=this.length);let Y=new J;if(Q<Z||Q<0)return Y;Z<0&&(Z=0),Q>this.length&&(Q=this.length);let X=this.length,K=this.tail;for(;K&&X>Q;X--)K=K.prev;for(;K&&X>Z;X--,K=K.prev)Y.push(K.value);return Y}splice(Z,Q=0,...Y){Z>this.length&&(Z=this.length-1),Z<0&&(Z=this.length+Z);let X=this.head;for(let V=0;X&&V<Z;V++)X=X.next;let K=[];for(let V=0;X&&V<Q;V++)K.push(X.value),X=this.removeNode(X);X?X!==this.tail&&(X=X.prev):X=this.tail;for(let V of Y)X=Ot5(this,X,V);return K}reverse(){let Z=this.head,Q=this.tail;for(let Y=Z;Y;Y=Y.prev){let X=Y.prev;Y.prev=Y.next,Y.next=X}return this.head=Q,this.tail=Z,this}};function Ot5(J,Z,Q){let Y=Z,X=Z?Z.next:J.head,K=new hl0(Q,Y,X,J);return K.next===void 0&&(J.tail=K),K.prev===void 0&&(J.head=K),J.length++,K}function Et5(J,Z){J.tail=new hl0(Z,J.tail,void 0,J),J.head||(J.head=J.tail),J.length++}function Mt5(J,Z){J.head=new hl0(Z,void 0,J.head,J),J.tail||(J.tail=J.head),J.length++}var hl0=class{list;next;prev;value;constructor(J,Z,Q,Y){this.list=Y,this.value=J,Z?(Z.next=this,this.prev=Z):this.prev=void 0,Q?(Q.prev=this,this.next=Q):this.next=void 0}},WL4=class{path;absolute;entry;stat;readdir;pending=!1;ignore=!1;piped=!1;constructor(J,Z){this.path=J||"./",this.absolute=Z}},UL4=Buffer.alloc(1024),QQ0=Symbol("onStat"),Bl=Symbol("ended"),Ez=Symbol("queue"),rA=Symbol("current"),sA=Symbol("process"),Nl=Symbol("processing"),Ql0=Symbol("processJob"),Mz=Symbol("jobs"),Yl0=Symbol("jobDone"),YQ0=Symbol("addFSEntry"),HL4=Symbol("addTarEntry"),Al0=Symbol("stat"),jl0=Symbol("readdir"),XQ0=Symbol("onreaddir"),KQ0=Symbol("pipe"),DL4=Symbol("entry"),Xl0=Symbol("entryOpt"),VQ0=Symbol("writeEntryClass"),hL4=Symbol("write"),Kl0=Symbol("ondrain"),LQ0=class extends Zj{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[VQ0];onWriteEntry;[Ez];[Mz]=0;[Nl]=!1;[Bl]=!1;constructor(J={}){if(super(),this.opt=J,this.file=J.file||"",this.cwd=J.cwd||process.cwd(),this.maxReadSize=J.maxReadSize,this.preservePaths=!!J.preservePaths,this.strict=!!J.strict,this.noPax=!!J.noPax,this.prefix=A5(J.prefix||""),this.linkCache=J.linkCache||new Map,this.statCache=J.statCache||new Map,this.readdirCache=J.readdirCache||new Map,this.onWriteEntry=J.onWriteEntry,this[VQ0]=bL4,typeof J.onwarn=="function"&&this.on("warn",J.onwarn),this.portable=!!J.portable,J.gzip||J.brotli||J.zstd){if((J.gzip?1:0)+(J.brotli?1:0)+(J.zstd?1:0)>1)throw TypeError("gzip, brotli, zstd are mutually exclusive");if(J.gzip&&(typeof J.gzip!="object"&&(J.gzip={}),this.portable&&(J.gzip.portable=!0),this.zip=new _s5(J.gzip)),J.brotli&&(typeof J.brotli!="object"&&(J.brotli={}),this.zip=new ks5(J.brotli)),J.zstd&&(typeof J.zstd!="object"&&(J.zstd={}),this.zip=new ys5(J.zstd)),!this.zip)throw Error("impossible");let Z=this.zip;Z.on("data",(Q)=>super.write(Q)),Z.on("end",()=>super.end()),Z.on("drain",()=>this[Kl0]()),this.on("resume",()=>Z.resume())}else this.on("drain",this[Kl0]);this.noDirRecurse=!!J.noDirRecurse,this.follow=!!J.follow,this.noMtime=!!J.noMtime,J.mtime&&(this.mtime=J.mtime),this.filter=typeof J.filter=="function"?J.filter:()=>!0,this[Ez]=new Lt5,this[Mz]=0,this.jobs=Number(J.jobs)||4,this[Nl]=!1,this[Bl]=!1}[hL4](J){return super.write(J)}add(J){return this.write(J),this}end(J,Z,Q){return typeof J=="function"&&(Q=J,J=void 0),typeof Z=="function"&&(Q=Z,Z=void 0),J&&this.add(J),this[Bl]=!0,this[sA](),Q&&Q(),this}write(J){if(this[Bl])throw Error("write after end");return J instanceof yL4?this[HL4](J):this[YQ0](J),this.flowing}[HL4](J){let Z=A5(qL4.resolve(this.cwd,J.path));if(!this.filter(J.path,J))J.resume();else{let Q=new WL4(J.path,Z);Q.entry=new Nt5(J,this[Xl0](Q)),Q.entry.on("end",()=>this[Yl0](Q)),this[Mz]+=1,this[Ez].push(Q)}this[sA]()}[YQ0](J){let Z=A5(qL4.resolve(this.cwd,J));this[Ez].push(new WL4(J,Z)),this[sA]()}[Al0](J){J.pending=!0,this[Mz]+=1;let Z=this.follow?"stat":"lstat";FQ0[Z](J.absolute,(Q,Y)=>{J.pending=!1,this[Mz]-=1,Q?this.emit("error",Q):this[QQ0](J,Y)})}[QQ0](J,Z){this.statCache.set(J.absolute,Z),J.stat=Z,this.filter(J.path,Z)?Z.isFile()&&Z.nlink>1&&J===this[rA]&&!this.linkCache.get(`${Z.dev}:${Z.ino}`)&&!this.sync&&this[Ql0](J):J.ignore=!0,this[sA]()}[jl0](J){J.pending=!0,this[Mz]+=1,FQ0.readdir(J.absolute,(Z,Q)=>{if(J.pending=!1,this[Mz]-=1,Z)return this.emit("error",Z);this[XQ0](J,Q)})}[XQ0](J,Z){this.readdirCache.set(J.absolute,Z),J.readdir=Z,this[sA]()}[sA](){if(!this[Nl]){this[Nl]=!0;for(let J=this[Ez].head;J&&this[Mz]<this.jobs;J=J.next)if(this[Ql0](J.value),J.value.ignore){let Z=J.next;this[Ez].removeNode(J),J.next=Z}this[Nl]=!1,this[Bl]&&!this[Ez].length&&this[Mz]===0&&(this.zip?this.zip.end(UL4):(super.write(UL4),super.end()))}}get[rA](){return this[Ez]&&this[Ez].head&&this[Ez].head.value}[Yl0](J){this[Ez].shift(),this[Mz]-=1,this[sA]()}[Ql0](J){if(!J.pending){if(J.entry){J===this[rA]&&!J.piped&&this[KQ0](J);return}if(!J.stat){let Z=this.statCache.get(J.absolute);Z?this[QQ0](J,Z):this[Al0](J)}if(J.stat&&!J.ignore){if(!this.noDirRecurse&&J.stat.isDirectory()&&!J.readdir){let Z=this.readdirCache.get(J.absolute);if(Z?this[XQ0](J,Z):this[jl0](J),!J.readdir)return}if(J.entry=this[DL4](J),!J.entry){J.ignore=!0;return}J===this[rA]&&!J.piped&&this[KQ0](J)}}}[Xl0](J){return{onwarn:(Z,Q,Y)=>this.warn(Z,Q,Y),noPax:this.noPax,cwd:this.cwd,absolute:J.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix,onWriteEntry:this.onWriteEntry}}[DL4](J){this[Mz]+=1;try{return new this[VQ0](J.path,this[Xl0](J)).on("end",()=>this[Yl0](J)).on("error",(Z)=>this.emit("error",Z))}catch(Z){this.emit("error",Z)}}[Kl0](){this[rA]&&this[rA].entry&&this[rA].entry.resume()}[KQ0](J){J.piped=!0,J.readdir&&J.readdir.forEach((Y)=>{let X=J.path,K=X==="./"?"":X.replace(/\/*$/,"/");this[YQ0](K+Y)});let Z=J.entry,Q=this.zip;if(!Z)throw Error("cannot pipe without source");Q?Z.on("data",(Y)=>{Q.write(Y)||Z.pause()}):Z.on("data",(Y)=>{super.write(Y)||Z.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(J,Z,Q={}){BQ0(this,J,Z,Q)}},gl0=class extends LQ0{sync=!0;constructor(J){super(J),this[VQ0]=Bt5}pause(){}resume(){}[Al0](J){let Z=this.follow?"statSync":"lstatSync";this[QQ0](J,FQ0[Z](J.absolute))}[jl0](J){this[XQ0](J,FQ0.readdirSync(J.absolute))}[KQ0](J){let Z=J.entry,Q=this.zip;if(J.readdir&&J.readdir.forEach((Y)=>{let X=J.path,K=X==="./"?"":X.replace(/\/*$/,"/");this[YQ0](K+Y)}),!Z)throw Error("Cannot pipe without source");Q?Z.on("data",(Y)=>{Q.write(Y)}):Z.on("data",(Y)=>{super[hL4](Y)})}},At5=(J,Z)=>{let Q=new gl0(J),Y=new PL4(J.file,{mode:J.mode||438});Q.pipe(Y),gL4(Q,Z)},jt5=(J,Z)=>{let Q=new LQ0(J),Y=new HQ0(J.file,{mode:J.mode||438});Q.pipe(Y);let X=new Promise((K,V)=>{Y.on("error",V),Y.on("close",K),Q.on("error",V)});return mL4(Q,Z),X},gL4=(J,Z)=>{Z.forEach((Q)=>{Q.charAt(0)==="@"?NQ0({file:CL4.resolve(J.cwd,Q.slice(1)),sync:!0,noResume:!0,onReadEntry:(Y)=>J.add(Y)}):J.add(Q)}),J.end()},mL4=async(J,Z)=>{for(let Q=0;Q<Z.length;Q++){let Y=String(Z[Q]);Y.charAt(0)==="@"?await NQ0({file:CL4.resolve(String(J.cwd),Y.slice(1)),noResume:!0,onReadEntry:(X)=>{J.add(X)}}):J.add(Y)}J.end()},Rt5=(J,Z)=>{let Q=new gl0(J);return gL4(Q,Z),Q},It5=(J,Z)=>{let Q=new LQ0(J);return mL4(Q,Z),Q},w59=_l(At5,jt5,Rt5,It5,(J,Z)=>{if(!Z?.length)throw TypeError("no paths specified to add to archive")}),Ct5=process.env.__FAKE_PLATFORM__||process.platform,Tt5=Ct5==="win32",{O_CREAT:_t5,O_TRUNC:St5,O_WRONLY:kt5}=cL4.constants,lL4=Number(process.env.__FAKE_FS_O_FILENAME__)||cL4.constants.UV_FS_O_FILEMAP||0,vt5=Tt5&&!!lL4,yt5=524288,xt5=lL4|St5|_t5|kt5,iL4=vt5?(J)=>J<yt5?xt5:"w":()=>"w",Rl0=(J,Z,Q)=>{try{return OQ0.lchownSync(J,Z,Q)}catch(Y){if(Y?.code!=="ENOENT")throw Y}},WQ0=(J,Z,Q,Y)=>{OQ0.lchown(J,Z,Q,(X)=>{Y(X&&X?.code!=="ENOENT"?X:null)})},ft5=(J,Z,Q,Y,X)=>{if(Z.isDirectory())nL4(Al.resolve(J,Z.name),Q,Y,(K)=>{if(K)return X(K);let V=Al.resolve(J,Z.name);WQ0(V,Q,Y,X)});else{let K=Al.resolve(J,Z.name);WQ0(K,Q,Y,X)}},nL4=(J,Z,Q,Y)=>{OQ0.readdir(J,{withFileTypes:!0},(X,K)=>{if(X){if(X.code==="ENOENT")return Y();if(X.code!=="ENOTDIR"&&X.code!=="ENOTSUP")return Y(X)}if(X||!K.length)return WQ0(J,Z,Q,Y);let V=K.length,z=null,G=(F)=>{if(!z){if(F)return Y(z=F);if(--V===0)return WQ0(J,Z,Q,Y)}};for(let F of K)ft5(J,F,Z,Q,G)})},ut5=(J,Z,Q,Y)=>{Z.isDirectory()&&aL4(Al.resolve(J,Z.name),Q,Y),Rl0(Al.resolve(J,Z.name),Q,Y)},aL4=(J,Z,Q)=>{let Y;try{Y=OQ0.readdirSync(J,{withFileTypes:!0})}catch(X){let K=X;if(K?.code==="ENOENT")return;if(K?.code==="ENOTDIR"||K?.code==="ENOTSUP")return Rl0(J,Z,Q);throw K}for(let X of Y)ut5(J,X,Z,Q);return Rl0(J,Z,Q)},oL4=class extends Error{path;code;syscall="chdir";constructor(J,Z){super(`${Z}: Cannot cd into '${J}'`),this.path=J,this.code=Z}get name(){return"CwdError"}},EQ0=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(J,Z){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=J,this.path=Z}get name(){return"SymlinkError"}},ht5=(J,Z)=>{pY.stat(J,(Q,Y)=>{(Q||!Y.isDirectory())&&(Q=new oL4(J,Q?.code||"ENOTDIR")),Z(Q)})},gt5=(J,Z,Q)=>{J=A5(J);let Y=Z.umask??18,X=Z.mode|448,K=(X&Y)!==0,V=Z.uid,z=Z.gid,G=typeof V=="number"&&typeof z=="number"&&(V!==Z.processUid||z!==Z.processGid),F=Z.preserve,q=Z.unlink,W=A5(Z.cwd),U=(D,B)=>{D?Q(D):B&&G?nL4(B,V,z,(N)=>U(N)):K?pY.chmod(J,X,Q):Q()};if(J===W)return ht5(J,U);if(F)return bt5.mkdir(J,{mode:X,recursive:!0}).then((D)=>U(null,D??void 0),U);let H=A5(UQ0.relative(W,J)).split("/");Il0(W,H,X,q,W,void 0,U)},Il0=(J,Z,Q,Y,X,K,V)=>{if(!Z.length)return V(null,K);let z=Z.shift(),G=A5(UQ0.resolve(J+"/"+z));pY.mkdir(G,Q,rL4(G,Z,Q,Y,X,K,V))},rL4=(J,Z,Q,Y,X,K,V)=>(z)=>{z?pY.lstat(J,(G,F)=>{if(G)G.path=G.path&&A5(G.path),V(G);else if(F.isDirectory())Il0(J,Z,Q,Y,X,K,V);else if(Y)pY.unlink(J,(q)=>{if(q)return V(q);pY.mkdir(J,Q,rL4(J,Z,Q,Y,X,K,V))});else{if(F.isSymbolicLink())return V(new EQ0(J,J+"/"+Z.join("/")));V(z)}}):(K=K||J,Il0(J,Z,Q,Y,X,K,V))},mt5=(J)=>{let Z=!1,Q;try{Z=pY.statSync(J).isDirectory()}catch(Y){Q=Y?.code}finally{if(!Z)throw new oL4(J,Q??"ENOTDIR")}},pt5=(J,Z)=>{J=A5(J);let Q=Z.umask??18,Y=Z.mode|448,X=(Y&Q)!==0,K=Z.uid,V=Z.gid,z=typeof K=="number"&&typeof V=="number"&&(K!==Z.processUid||V!==Z.processGid),G=Z.preserve,F=Z.unlink,q=A5(Z.cwd),W=(D)=>{D&&z&&aL4(D,K,V),X&&pY.chmodSync(J,Y)};if(J===q)return mt5(q),W();if(G)return W(pY.mkdirSync(J,{mode:Y,recursive:!0})??void 0);let U=A5(UQ0.relative(q,J)).split("/"),H;for(let D=U.shift(),B=q;D&&(B+="/"+D);D=U.shift()){B=A5(UQ0.resolve(B));try{pY.mkdirSync(B,Y),H=H||B}catch{let N=pY.lstatSync(B);if(N.isDirectory())continue;if(F){pY.unlinkSync(B),pY.mkdirSync(B,Y),H=H||B;continue}else if(N.isSymbolicLink())return new EQ0(B,B+"/"+U.join("/"))}}return W(H)},Vl0=Object.create(null),BL4=1e4,jk=new Set,dt5=(J)=>{jk.has(J)?jk.delete(J):Vl0[J]=J.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),jk.add(J);let Z=Vl0[J],Q=jk.size-BL4;if(Q>BL4/10){for(let Y of jk)if(jk.delete(Y),delete Vl0[Y],--Q<=0)break}return Z},ct5=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,lt5=ct5==="win32",it5=(J)=>J.split("/").slice(0,-1).reduce((Z,Q)=>{let Y=Z[Z.length-1];return Y!==void 0&&(Q=sL4(Y,Q)),Z.push(Q||"/"),Z},[]),nt5=class{#$=new Map;#J=new Map;#Z=new Set;reserve(J,Z){J=lt5?["win32 parallelization disabled"]:J.map((Y)=>Ml(sL4(dt5(Y))));let Q=new Set(J.map((Y)=>it5(Y)).reduce((Y,X)=>Y.concat(X)));this.#J.set(Z,{dirs:Q,paths:J});for(let Y of J){let X=this.#$.get(Y);X?X.push(Z):this.#$.set(Y,[Z])}for(let Y of Q){let X=this.#$.get(Y);if(!X)this.#$.set(Y,[new Set([Z])]);else{let K=X[X.length-1];K instanceof Set?K.add(Z):X.push(new Set([Z]))}}return this.#Y(Z)}#Q(J){let Z=this.#J.get(J);if(!Z)throw Error("function does not have any path reservations");return{paths:Z.paths.map((Q)=>this.#$.get(Q)),dirs:[...Z.dirs].map((Q)=>this.#$.get(Q))}}check(J){let{paths:Z,dirs:Q}=this.#Q(J);return Z.every((Y)=>Y&&Y[0]===J)&&Q.every((Y)=>Y&&Y[0]instanceof Set&&Y[0].has(J))}#Y(J){return this.#Z.has(J)||!this.check(J)?!1:(this.#Z.add(J),J(()=>this.#X(J)),!0)}#X(J){if(!this.#Z.has(J))return!1;let Z=this.#J.get(J);if(!Z)throw Error("invalid reservation");let{paths:Q,dirs:Y}=Z,X=new Set;for(let K of Q){let V=this.#$.get(K);if(!V||V?.[0]!==J)continue;let z=V[1];if(!z){this.#$.delete(K);continue}if(V.shift(),typeof z=="function")X.add(z);else for(let G of z)X.add(G)}for(let K of Y){let V=this.#$.get(K),z=V?.[0];if(!(!V||!(z instanceof Set)))if(z.size===1&&V.length===1){this.#$.delete(K);continue}else if(z.size===1){V.shift();let G=V[0];typeof G=="function"&&X.add(G)}else z.delete(J)}return this.#Z.delete(J),X.forEach((K)=>this.#Y(K)),!0}},at5=()=>process.umask(),NL4=Symbol("onEntry"),Pl0=Symbol("checkFs"),wL4=Symbol("checkFs2"),Cl0=Symbol("isReusable"),_K=Symbol("makeFs"),Tl0=Symbol("file"),_l0=Symbol("directory"),zQ0=Symbol("link"),LL4=Symbol("symlink"),OL4=Symbol("hardlink"),Ol=Symbol("ensureNoSymlink"),EL4=Symbol("unsupported"),ML4=Symbol("checkPath"),zl0=Symbol("stripAbsolutePath"),Yw=Symbol("mkdir"),a2=Symbol("onError"),sZ0=Symbol("pending"),AL4=Symbol("pend"),Rk=Symbol("unpend"),Gl0=Symbol("ended"),Fl0=Symbol("maybeClose"),Sl0=Symbol("skip"),jl=Symbol("doChown"),Rl=Symbol("uid"),Il=Symbol("gid"),Pl=Symbol("checkedCwd"),ot5=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Cl=ot5==="win32",rt5=1024,st5=(J,Z)=>{if(!Cl)return K3.unlink(J,Z);let Q=J+".DELETE."+dL4(16).toString("hex");K3.rename(J,Q,(Y)=>{if(Y)return Z(Y);K3.unlink(Q,Z)})},tt5=(J)=>{if(!Cl)return K3.unlinkSync(J);let Z=J+".DELETE."+dL4(16).toString("hex");K3.renameSync(J,Z),K3.unlinkSync(Z)},jL4=(J,Z,Q)=>J!==void 0&&J===J>>>0?J:Z!==void 0&&Z===Z>>>0?Z:Q,ml0=class extends Tl{[Gl0]=!1;[Pl]=!1;[sZ0]=0;reservations=new nt5;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(J={}){if(J.ondone=()=>{this[Gl0]=!0,this[Fl0]()},super(J),this.transform=J.transform,this.chmod=!!J.chmod,typeof J.uid=="number"||typeof J.gid=="number"){if(typeof J.uid!="number"||typeof J.gid!="number")throw TypeError("cannot set owner without number uid and gid");if(J.preserveOwner)throw TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=J.uid,this.gid=J.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;J.preserveOwner===void 0&&typeof J.uid!="number"?this.preserveOwner=!!(process.getuid&&process.getuid()===0):this.preserveOwner=!!J.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof J.maxDepth=="number"?J.maxDepth:rt5,this.forceChown=J.forceChown===!0,this.win32=!!J.win32||Cl,this.newer=!!J.newer,this.keep=!!J.keep,this.noMtime=!!J.noMtime,this.preservePaths=!!J.preservePaths,this.unlink=!!J.unlink,this.cwd=A5(B2.resolve(J.cwd||process.cwd())),this.strip=Number(J.strip)||0,this.processUmask=this.chmod?typeof J.processUmask=="number"?J.processUmask:at5():0,this.umask=typeof J.umask=="number"?J.umask:this.processUmask,this.dmode=J.dmode||511&~this.umask,this.fmode=J.fmode||438&~this.umask,this.on("entry",(Z)=>this[NL4](Z))}warn(J,Z,Q={}){return(J==="TAR_BAD_ARCHIVE"||J==="TAR_ABORT")&&(Q.recoverable=!1),super.warn(J,Z,Q)}[Fl0](){this[Gl0]&&this[sZ0]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[zl0](J,Z){let Q=J[Z],{type:Y}=J;if(!Q||this.preservePaths)return!0;let[X,K]=ul0(Q),V=K.replace(/\\/g,"/").split("/");if(V.includes("..")||Cl&&/^[a-z]:\.\.$/i.test(V[0]??"")){if(Z==="path"||Y==="Link")return this.warn("TAR_ENTRY_ERROR",`${Z} contains '..'`,{entry:J,[Z]:Q}),!1;{let z=B2.posix.dirname(J.path),G=B2.posix.normalize(B2.posix.join(z,Q));if(G.startsWith("../")||G==="..")return this.warn("TAR_ENTRY_ERROR",`${Z} escapes extraction directory`,{entry:J,[Z]:Q}),!1}}return X&&(J[Z]=String(K),this.warn("TAR_ENTRY_INFO",`stripping ${X} from absolute ${Z}`,{entry:J,[Z]:Q})),!0}[ML4](J){let Z=A5(J.path),Q=Z.split("/");if(this.strip){if(Q.length<this.strip)return!1;if(J.type==="Link"){let Y=A5(String(J.linkpath)).split("/");if(Y.length>=this.strip)J.linkpath=Y.slice(this.strip).join("/");else return!1}Q.splice(0,this.strip),J.path=Q.join("/")}if(isFinite(this.maxDepth)&&Q.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:J,path:Z,depth:Q.length,maxDepth:this.maxDepth}),!1;if(!this[zl0](J,"path")||!this[zl0](J,"linkpath"))return!1;if(B2.isAbsolute(J.path)?J.absolute=A5(B2.resolve(J.path)):J.absolute=A5(B2.resolve(this.cwd,J.path)),!this.preservePaths&&typeof J.absolute=="string"&&J.absolute.indexOf(this.cwd+"/")!==0&&J.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:J,path:A5(J.path),resolvedPath:J.absolute,cwd:this.cwd}),!1;if(J.absolute===this.cwd&&J.type!=="Directory"&&J.type!=="GNUDumpDir")return!1;if(this.win32){let{root:Y}=B2.win32.parse(String(J.absolute));J.absolute=Y+KL4(String(J.absolute).slice(Y.length));let{root:X}=B2.win32.parse(J.path);J.path=X+KL4(J.path.slice(X.length))}return!0}[NL4](J){if(!this[ML4](J))return J.resume();switch(Pt5.equal(typeof J.absolute,"string"),J.type){case"Directory":case"GNUDumpDir":J.mode&&(J.mode=J.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[Pl0](J);default:return this[EL4](J)}}[a2](J,Z){J.name==="CwdError"?this.emit("error",J):(this.warn("TAR_ENTRY_ERROR",J,{entry:Z}),this[Rk](),Z.resume())}[Yw](J,Z,Q){gt5(A5(J),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:Z},Q)}[jl](J){return this.forceChown||this.preserveOwner&&(typeof J.uid=="number"&&J.uid!==this.processUid||typeof J.gid=="number"&&J.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[Rl](J){return jL4(this.uid,J.uid,this.processUid)}[Il](J){return jL4(this.gid,J.gid,this.processGid)}[Tl0](J,Z){let Q=typeof J.mode=="number"?J.mode&4095:this.fmode,Y=new HQ0(String(J.absolute),{flags:iL4(J.size),mode:Q,autoClose:!1});Y.on("error",(z)=>{Y.fd&&K3.close(Y.fd,()=>{}),Y.write=()=>!0,this[a2](z,J),Z()});let X=1,K=(z)=>{if(z){Y.fd&&K3.close(Y.fd,()=>{}),this[a2](z,J),Z();return}--X===0&&Y.fd!==void 0&&K3.close(Y.fd,(G)=>{G?this[a2](G,J):this[Rk](),Z()})};Y.on("finish",()=>{let z=String(J.absolute),G=Y.fd;if(typeof G=="number"&&J.mtime&&!this.noMtime){X++;let F=J.atime||new Date,q=J.mtime;K3.futimes(G,F,q,(W)=>W?K3.utimes(z,F,q,(U)=>K(U&&W)):K())}if(typeof G=="number"&&this[jl](J)){X++;let F=this[Rl](J),q=this[Il](J);typeof F=="number"&&typeof q=="number"&&K3.fchown(G,F,q,(W)=>W?K3.chown(z,F,q,(U)=>K(U&&W)):K())}K()});let V=this.transform&&this.transform(J)||J;V!==J&&(V.on("error",(z)=>{this[a2](z,J),Z()}),J.pipe(V)),V.pipe(Y)}[_l0](J,Z){let Q=typeof J.mode=="number"?J.mode&4095:this.dmode;this[Yw](String(J.absolute),Q,(Y)=>{if(Y){this[a2](Y,J),Z();return}let X=1,K=()=>{--X===0&&(Z(),this[Rk](),J.resume())};J.mtime&&!this.noMtime&&(X++,K3.utimes(String(J.absolute),J.atime||new Date,J.mtime,K)),this[jl](J)&&(X++,K3.chown(String(J.absolute),Number(this[Rl](J)),Number(this[Il](J)),K)),K()})}[EL4](J){J.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${J.type}`,{entry:J}),J.resume()}[LL4](J,Z){let Q=A5(B2.relative(this.cwd,B2.resolve(B2.dirname(String(J.absolute)),String(J.linkpath)))).split("/");this[Ol](J,this.cwd,Q,()=>this[zQ0](J,String(J.linkpath),"symlink",Z),(Y)=>{this[a2](Y,J),Z()})}[OL4](J,Z){let Q=A5(B2.resolve(this.cwd,String(J.linkpath))),Y=A5(String(J.linkpath)).split("/");this[Ol](J,this.cwd,Y,()=>this[zQ0](J,Q,"link",Z),(X)=>{this[a2](X,J),Z()})}[Ol](J,Z,Q,Y,X){let K=Q.shift();if(this.preservePaths||K===void 0)return Y();let V=B2.resolve(Z,K);K3.lstat(V,(z,G)=>{if(z)return Y();if(G?.isSymbolicLink())return X(new EQ0(V,B2.resolve(V,Q.join("/"))));this[Ol](J,V,Q,Y,X)})}[AL4](){this[sZ0]++}[Rk](){this[sZ0]--,this[Fl0]()}[Sl0](J){this[Rk](),J.resume()}[Cl0](J,Z){return J.type==="File"&&!this.unlink&&Z.isFile()&&Z.nlink<=1&&!Cl}[Pl0](J){this[AL4]();let Z=[J.path];J.linkpath&&Z.push(J.linkpath),this.reservations.reserve(Z,(Q)=>this[wL4](J,Q))}[wL4](J,Z){let Q=(V)=>{Z(V)},Y=()=>{this[Yw](this.cwd,this.dmode,(V)=>{if(V){this[a2](V,J),Q();return}this[Pl]=!0,X()})},X=()=>{if(J.absolute!==this.cwd){let V=A5(B2.dirname(String(J.absolute)));if(V!==this.cwd)return this[Yw](V,this.dmode,(z)=>{if(z){this[a2](z,J),Q();return}K()})}K()},K=()=>{K3.lstat(String(J.absolute),(V,z)=>{if(z&&(this.keep||this.newer&&z.mtime>(J.mtime??z.mtime))){this[Sl0](J),Q();return}if(V||this[Cl0](J,z))return this[_K](null,J,Q);if(z.isDirectory()){if(J.type==="Directory"){let G=this.chmod&&J.mode&&(z.mode&4095)!==J.mode,F=(q)=>this[_K](q??null,J,Q);return G?K3.chmod(String(J.absolute),Number(J.mode),F):F()}if(J.absolute!==this.cwd)return K3.rmdir(String(J.absolute),(G)=>this[_K](G??null,J,Q))}if(J.absolute===this.cwd)return this[_K](null,J,Q);st5(String(J.absolute),(G)=>this[_K](G??null,J,Q))})};this[Pl]?X():Y()}[_K](J,Z,Q){if(J){this[a2](J,Z),Q();return}switch(Z.type){case"File":case"OldFile":case"ContiguousFile":return this[Tl0](Z,Q);case"Link":return this[OL4](Z,Q);case"SymbolicLink":return this[LL4](Z,Q);case"Directory":case"GNUDumpDir":return this[_l0](Z,Q)}}[zQ0](J,Z,Q,Y){K3[Q](Z,String(J.absolute),(X)=>{X?this[a2](X,J):(this[Rk](),J.resume()),Y()})}},wl=(J)=>{try{return[null,J()]}catch(Z){return[Z,null]}},tL4=class extends ml0{sync=!0;[_K](J,Z){return super[_K](J,Z,()=>{})}[Pl0](J){if(!this[Pl]){let X=this[Yw](this.cwd,this.dmode);if(X)return this[a2](X,J);this[Pl]=!0}if(J.absolute!==this.cwd){let X=A5(B2.dirname(String(J.absolute)));if(X!==this.cwd){let K=this[Yw](X,this.dmode);if(K)return this[a2](K,J)}}let[Z,Q]=wl(()=>K3.lstatSync(String(J.absolute)));if(Q&&(this.keep||this.newer&&Q.mtime>(J.mtime??Q.mtime)))return this[Sl0](J);if(Z||this[Cl0](J,Q))return this[_K](null,J);if(Q.isDirectory()){if(J.type==="Directory"){let K=this.chmod&&J.mode&&(Q.mode&4095)!==J.mode,[V]=K?wl(()=>{K3.chmodSync(String(J.absolute),Number(J.mode))}):[];return this[_K](V,J)}let[X]=wl(()=>K3.rmdirSync(String(J.absolute)));this[_K](X,J)}let[Y]=J.absolute===this.cwd?[]:wl(()=>tt5(String(J.absolute)));this[_K](Y,J)}[Tl0](J,Z){let Q=typeof J.mode=="number"?J.mode&4095:this.fmode,Y=(V)=>{let z;try{K3.closeSync(X)}catch(G){z=G}(V||z)&&this[a2](V||z,J),Z()},X;try{X=K3.openSync(String(J.absolute),iL4(J.size),Q)}catch(V){return Y(V)}let K=this.transform&&this.transform(J)||J;K!==J&&(K.on("error",(V)=>this[a2](V,J)),J.pipe(K)),K.on("data",(V)=>{try{K3.writeSync(X,V,0,V.length)}catch(z){Y(z)}}),K.on("end",()=>{let V=null;if(J.mtime&&!this.noMtime){let z=J.atime||new Date,G=J.mtime;try{K3.futimesSync(X,z,G)}catch(F){try{K3.utimesSync(String(J.absolute),z,G)}catch{V=F}}}if(this[jl](J)){let z=this[Rl](J),G=this[Il](J);try{K3.fchownSync(X,Number(z),Number(G))}catch(F){try{K3.chownSync(String(J.absolute),Number(z),Number(G))}catch{V=V||F}}}Y(V)})}[_l0](J,Z){let Q=typeof J.mode=="number"?J.mode&4095:this.dmode,Y=this[Yw](String(J.absolute),Q);if(Y){this[a2](Y,J),Z();return}if(J.mtime&&!this.noMtime)try{K3.utimesSync(String(J.absolute),J.atime||new Date,J.mtime)}catch{}if(this[jl](J))try{K3.chownSync(String(J.absolute),Number(this[Rl](J)),Number(this[Il](J)))}catch{}Z(),J.resume()}[Yw](J,Z){try{return pt5(A5(J),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:Z})}catch(Q){return Q}}[Ol](J,Z,Q,Y,X){if(this.preservePaths||!Q.length)return Y();let K=Z;for(let V of Q){K=B2.resolve(K,V);let[z,G]=wl(()=>K3.lstatSync(K));if(z)return Y();if(G.isSymbolicLink())return X(new EQ0(K,B2.resolve(Z,Q.join("/"))))}Y()}[zQ0](J,Z,Q,Y){let X=`${Q}Sync`;try{K3[X](Z,String(J.absolute)),Y(),J.resume()}catch(K){return this[a2](K,J)}}},et5=(J)=>{let Z=new tL4(J),Q=J.file,Y=pL4.statSync(Q),X=J.maxReadSize||16777216;new Ds5(Q,{readSize:X,size:Y.size}).pipe(Z)},$e5=(J,Z)=>{let Q=new ml0(J),Y=J.maxReadSize||16777216,X=J.file;return new Promise((K,V)=>{Q.on("error",V),Q.on("close",K),pL4.stat(X,(z,G)=>{if(z)V(z);else{let F=new vl0(X,{readSize:Y,size:G.size});F.on("error",V),F.pipe(Q)}})})},Je5=_l(et5,$e5,(J)=>new tL4(J),(J)=>new ml0(J),(J,Z)=>{Z?.length&&xL4(J,Z)}),Ze5=(J,Z)=>{let Q=new gl0(J),Y=!0,X,K;try{try{X=mY.openSync(J.file,"r+")}catch(G){if(G?.code==="ENOENT")X=mY.openSync(J.file,"w+");else throw G}let V=mY.fstatSync(X),z=Buffer.alloc(512);$:for(K=0;K<V.size;K+=512){for(let q=0,W=0;q<512;q+=W){if(W=mY.readSync(X,z,q,z.length-q,K+q),K===0&&z[0]===31&&z[1]===139)throw Error("cannot append to compressed archives");if(!W)break $}let G=new Jj(z);if(!G.cksumValid)break;let F=512*Math.ceil((G.size||0)/512);if(K+F+512>V.size)break;K+=F,J.mtimeCache&&G.mtime&&J.mtimeCache.set(String(G.path),G.mtime)}Y=!1,Qe5(J,Q,K,X,Z)}finally{if(Y)try{mY.closeSync(X)}catch{}}},Qe5=(J,Z,Q,Y,X)=>{let K=new PL4(J.file,{fd:Y,start:Q});Z.pipe(K),Xe5(Z,X)},Ye5=(J,Z)=>{Z=Array.from(Z);let Q=new LQ0(J),Y=(X,K,V)=>{let z=(U,H)=>{U?mY.close(X,(D)=>V(U)):V(null,H)},G=0;if(K===0)return z(null,0);let F=0,q=Buffer.alloc(512),W=(U,H)=>{if(U||typeof H>"u")return z(U);if(F+=H,F<512&&H)return mY.read(X,q,F,q.length-F,G+F,W);if(G===0&&q[0]===31&&q[1]===139)return z(Error("cannot append to compressed archives"));if(F<512)return z(null,G);let D=new Jj(q);if(!D.cksumValid)return z(null,G);let B=512*Math.ceil((D.size??0)/512);if(G+B+512>K||(G+=B+512,G>=K))return z(null,G);J.mtimeCache&&D.mtime&&J.mtimeCache.set(String(D.path),D.mtime),F=0,mY.read(X,q,0,512,G,W)};mY.read(X,q,0,512,G,W)};return new Promise((X,K)=>{Q.on("error",K);let V="r+",z=(G,F)=>{if(G&&G.code==="ENOENT"&&V==="r+")return V="w+",mY.open(J.file,V,z);if(G||!F)return K(G);mY.fstat(F,(q,W)=>{if(q)return mY.close(F,()=>K(q));Y(F,W.size,(U,H)=>{if(U)return K(U);let D=new HQ0(J.file,{fd:F,start:H});Q.pipe(D),D.on("error",K),D.on("close",X),Ke5(Q,Z)})})};mY.open(J.file,V,z)})},Xe5=(J,Z)=>{Z.forEach((Q)=>{Q.charAt(0)==="@"?NQ0({file:eL4.resolve(J.cwd,Q.slice(1)),sync:!0,noResume:!0,onReadEntry:(Y)=>J.add(Y)}):J.add(Q)}),J.end()},Ke5=async(J,Z)=>{for(let Q=0;Q<Z.length;Q++){let Y=String(Z[Q]);Y.charAt(0)==="@"?await NQ0({file:eL4.resolve(String(J.cwd),Y.slice(1)),noResume:!0,onReadEntry:(X)=>J.add(X)}):J.add(Y)}J.end()},Ll=_l(Ze5,Ye5,()=>{throw TypeError("file is required")},()=>{throw TypeError("file is required")},(J,Z)=>{if(!As5(J))throw TypeError("file is required");if(J.gzip||J.brotli||J.zstd||J.file.endsWith(".br")||J.file.endsWith(".tbr"))throw TypeError("cannot append to compressed archives");if(!Z?.length)throw TypeError("no paths specified to add/replace")}),v59=_l(Ll.syncFile,Ll.asyncFile,Ll.syncNoFile,Ll.asyncNoFile,(J,Z=[])=>{Ll.validate?.(J,Z),Ve5(J)}),Ve5=(J)=>{let Z=J.filter;J.mtimeCache||(J.mtimeCache=new Map),J.filter=Z?(Q,Y)=>Z(Q,Y)&&!((J.mtimeCache?.get(Q)??Y.mtime??0)>(Y.mtime??0)):(Q,Y)=>!((J.mtimeCache?.get(Q)??Y.mtime??0)>(Y.mtime??0))};j9();j9();var D39=class{initApp;#$;constructor(J){this.initApp=J?.initApp,this.#$=J?.defaultAppOptions}createApp=(J)=>{let Z=new uZ0(J&&this.#$?{...this.#$,...J}:J??this.#$);if(this.initApp)this.initApp(Z);return Z};createMiddleware=(J)=>J;createHandlers=(...J)=>{return J.filter((Z)=>Z!==void 0)}};var Fe5=B4(wz(),1);var $O4=v.string(),pl0=v.object({actor_id:$O4,name:v.string(),key:v.string(),namespace_id:$O4,runner_name_selector:v.string(),create_ts:v.number(),connectable_ts:v.number().nullable().optional(),destroy_ts:v.number().nullable().optional(),sleep_ts:v.number().nullable().optional(),start_ts:v.number().nullable().optional(),error:v.unknown().nullable().optional()}),Ge5=v.object({metadata:v.record(v.string(),v.unknown())}),a39=v.object({actors:v.array(pl0)}),o39=v.object({datacenter:v.string().optional(),name:v.string(),runner_name_selector:v.string(),crash_policy:v.string(),key:v.string().nullable().optional(),input:v.string().nullable().optional()}),r39=v.object({actor:pl0}),s39=v.object({datacenter:v.string().optional(),name:v.string(),key:v.string(),runner_name_selector:v.string(),crash_policy:v.string(),input:v.string().nullable().optional()}),t39=v.object({actor:pl0,created:v.boolean()}),e39=v.object({}),$89=v.object({names:v.record(v.string(),Ge5)}),J89=v.object({value:v.string().nullable()});var Y89=class{#$;#J;constructor(J){this.#J=J}async acquire(J){if(!this.#$){let Q=this.#J.sqlitePool,Y=["@rivetkit","sqlite-vfs"].join("/");this.#$=import(Y).then(({SqliteVfsPool:X})=>new X({actorsPerInstance:Q.actorsPerInstance,idleDestroyMs:Q.idleDestroyMs}))}return await(await this.#$).acquire(J)}async shutdown(){if(this.#$)await(await this.#$).shutdown()}};function kk(J){return Ic0(J)}var qe5="https://production.ampworkers.com",We5="https://staging.ampworkers.com";function i7(J){if(J.includes("staging.ampcodedev.org"))return We5;return qe5}var Ue5="https://thread-actors-prod-us-east1-935747076731.us-east1.run.app",He5="https://thread-actors-staging-us-east1-739316246630.us-east1.run.app";function vk(J){if(J.includes("staging.ampcodedev.org"))return He5;return Ue5}async function JO4(J){let Z=J.workerURL??i7(J.ampURL),Q=await J.configService.getLatest(J.signal),Y=await Q.secrets.getToken("apiKey",Q.settings.url);if(!Y)throw Error("API key required. Please run `amp login` first.");let X=await fetch(`${Z}/threads/${J.threadID}/context-analysis`,{method:"GET",headers:{Authorization:`Bearer ${Y}`},signal:J.signal});if(!X.ok){let V=await X.text();throw Error(`Context analysis request failed (${X.status}): ${V}`)}let K=await X.json();if(!K.ok||!K.analysis)throw Error(K.error??"Invalid context analysis response from DTW");return K.analysis}async function ZO4(J){let Z=vk(J.ampURL),Q=kk({endpoint:`${Z}/api/rivet`}),Y=await J.configService.getLatest(J.signal),X=await Y.secrets.getToken("apiKey",Y.settings.url);if(!X)throw Error("API key required. Please run `amp login` first.");let K=await Q.threadActor.get([J.threadID]).fetch("/context-analysis",{method:"GET",headers:{Authorization:`Bearer ${X}`},signal:J.signal});if(!K.ok){let z=await K.text();throw Error(`Context analysis request failed (${K.status}): ${z}`)}let V=await K.json();if(!V.ok||!V.analysis)throw Error(V.error??"Invalid context analysis response from DTW");return V.analysis}var QO4=process.hrtime.bigint(),dl0=null;function YO4(){dl0=process.hrtime.bigint()}function XO4(){if(dl0===null)return null;return Number(process.hrtime.bigint()-dl0)/1e6}PX();m0();var Wj4=B4(O4(),1),dY=B4(Fj4(),1),Uj4=B4(zj(),1);import rQ0 from"node:fs";import In0 from"node:path";var qj4=Object.keys(P),Z83=In0.join(nZ,"logs"),Pn0=In0.join(Z83,"cli.log"),Q83=10485760;function Y83(J){try{if(rQ0.statSync(J).size>Q83)rQ0.truncateSync(J,0)}catch{}}var Zi,Cn0=!1,Ji=null;function X83(J){return J instanceof Error&&J.message.includes("write after end")}function $i(J,Z,Q,Y){if(Cn0)return;try{J[Z](Q,...Y)}catch(X){if(!X83(X))throw X}}function Hj4(J){Cn0=!1,Ji=null;let{logFile:Z,logLevel:Q}=J;if(!qj4.includes(Q))console.warn(`Invalid log level: ${Q}. Using 'info' instead.`);try{rQ0.mkdirSync(In0.dirname(Z),{recursive:!0})}catch(z){console.error(`Failed to create log directory: ${z}`)}Y83(Z);let Y=dY.default.format((z)=>{for(let G of Object.keys(z)){let F=z[G];if(F instanceof Error)z[G]={name:F.name,message:F.message,stack:F.stack}}return z}),X=dY.default.format((z)=>{return z.pid=process.pid,z}),K=[new dY.default.transports.File({filename:Z}),new Dj4];if(process.env.AMP_CLI_STDOUT_DEBUG==="true")K.push(new dY.default.transports.Console({level:"debug",format:dY.default.format.combine(dY.default.format.colorize(),dY.default.format.simple())}));Zi=dY.default.createLogger({level:qj4.includes(Q)?Q:"info",format:dY.default.format.combine(dY.default.format.timestamp(),X(),Y(),dY.default.format.json(),dY.default.format.errors({stack:!0})),transports:K});let V=Zi;return My1({error:(z,...G)=>{$i(V,"error",z,G)},warn:(z,...G)=>{$i(V,"warn",z,G)},info:(z,...G)=>{$i(V,"info",z,G)},debug:(z,...G)=>{$i(V,"debug",z,G)},audit:(z,...G)=>{let F=typeof G[0]==="object"&&G[0]!==null?{audit:!0,...G[0]}:{audit:!0};$i(V,"info",z,[F])}}),Z}class Dj4 extends Uj4.default{log({message:J,...Z},Q){Wj4.trace.getActiveSpan()?.addEvent(J,Z),Q()}}function VH(){if(Ji)return Ji;let J=Zi;if(!J)return Promise.resolve();return Cn0=!0,Ji=new Promise((Z)=>{let Q=!1,Y=()=>{if(!Q){if(Q=!0,Zi===J)Zi=void 0;Z()}};setImmediate(()=>{try{J.once("finish",Y).once("error",Y).end()}catch{Y()}}),setTimeout(Y,500)}),Ji}m0();import{execFile as K83}from"node:child_process";import{promisify as V83}from"node:util";var z83=V83(K83),G83=["private","public","workspace"];function Tn0(J){return J.endsWith("/")?J.slice(0,-1):J}function F83(J){let Z=HJ0(J);try{let X=new URL(Z);return Tn0(`${X.host}${X.pathname}`).replace(/^\//,"")}catch{}let Q=Z.match(/^[^@]+@([^:/]+)[:/](.+)$/);if(Q?.[1]&&Q[2])return Tn0(`${Q[1]}/${Q[2]}`).replace(/\.git$/,"");let Y=Z.match(/^([^:]+):(.+)$/);if(Y?.[1]&&Y[2])return Tn0(`${Y[1]}/${Y[2]}`).replace(/\.git$/,"");return null}async function wj4(J){try{let{stdout:Z}=await z83("git",["remote","get-url","origin"],{cwd:J}),Q=Z.trim();if(!Q)return null;return F83(Q)}catch{return null}}function q83(J){let Z=[...G83];if(J?.team?.disablePrivateThreads){let Q=Z.indexOf("private");if(Q!==-1)Z.splice(Q,1)}if(J?.team?.groups&&J.team.groups.length>0)Z.push("group");return Z}function Bj4(J){let Z=J?.team?.disablePrivateThreads??!1,Q=J?.team?.defaultThreadVisibility;if(!Q||Q==="private")return Z?"workspace":"private";if(Q==="thread_workspace_shared")return"workspace";if(Q==="creator_groups_fallback_private"){if(J?.team?.groups?.length)return"group";return Z?"workspace":"private"}return Z?"workspace":"private"}function W83(J){if(J?.team?.groups!==void 0)return Error(["Group visibility is not available. ",`You are not a member of any group in this workspace.
|
|
4667
|
+
`).reduce(Zt5,Object.create(null)),Zt5=(J,Z)=>{let Q=parseInt(Z,10);if(Q!==Buffer.byteLength(Z)+1)return J;Z=Z.slice((Q+" ").length);let Y=Z.split("="),X=Y.shift();if(!X)return J;let K=X.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),V=Y.join("=");return J[K]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(K)?new Date(Number(V)*1000):/^[0-9]+$/.test(V)?+V:V,J},Qt5=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,A5=Qt5!=="win32"?(J)=>J:(J)=>J&&J.replace(/\\/g,"/"),yL4=class extends Zj{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(J,Z,Q){switch(super({}),this.pause(),this.extended=Z,this.globalExtended=Q,this.header=J,this.remain=J.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=J.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!J.path)throw Error("no path provided for tar.ReadEntry");this.path=A5(J.path),this.mode=J.mode,this.mode&&(this.mode=this.mode&4095),this.uid=J.uid,this.gid=J.gid,this.uname=J.uname,this.gname=J.gname,this.size=this.remain,this.mtime=J.mtime,this.atime=J.atime,this.ctime=J.ctime,this.linkpath=J.linkpath?A5(J.linkpath):void 0,this.uname=J.uname,this.gname=J.gname,Z&&this.#$(Z),Q&&this.#$(Q,!0)}write(J){let Z=J.length;if(Z>this.blockRemain)throw Error("writing more to entry than is appropriate");let Q=this.remain,Y=this.blockRemain;return this.remain=Math.max(0,Q-Z),this.blockRemain=Math.max(0,Y-Z),this.ignore?!0:Q>=Z?super.write(J):super.write(J.subarray(0,Q))}#$(J,Z=!1){J.path&&(J.path=A5(J.path)),J.linkpath&&(J.linkpath=A5(J.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(J).filter(([Q,Y])=>!(Y==null||Q==="path"&&Z))))}},BQ0=(J,Z,Q,Y={})=>{J.file&&(Y.file=J.file),J.cwd&&(Y.cwd=J.cwd),Y.code=Q instanceof Error&&Q.code||Z,Y.tarCode=Z,!J.strict&&Y.recoverable!==!1?(Q instanceof Error&&(Y=Object.assign(Q,Y),Q=Q.message),J.emit("warn",Z,Q,Y)):Q instanceof Error?J.emit("error",Object.assign(Q,Y)):J.emit("error",Object.assign(Error(`${Z}: ${Q}`),Y))},Yt5=1048576,Hl0=Buffer.from([31,139]),Dl0=Buffer.from([40,181,47,253]),Xt5=Math.max(Hl0.length,Dl0.length),TK=Symbol("state"),nA=Symbol("writeEntry"),ZH=Symbol("readEntry"),tc0=Symbol("nextEntry"),ew4=Symbol("processEntry"),$q=Symbol("extendedHeader"),Ul=Symbol("globalExtendedHeader"),sN=Symbol("meta"),$L4=Symbol("emitMeta"),g8=Symbol("buffer"),QH=Symbol("queue"),tN=Symbol("ended"),ec0=Symbol("emittedEnd"),aA=Symbol("emit"),l7=Symbol("unzip"),lZ0=Symbol("consumeChunk"),iZ0=Symbol("consumeChunkSub"),$l0=Symbol("consumeBody"),JL4=Symbol("consumeMeta"),ZL4=Symbol("consumeHeader"),Hl=Symbol("consuming"),Jl0=Symbol("bufferConcat"),nZ0=Symbol("maybeEnd"),Ak=Symbol("writing"),eN=Symbol("aborted"),aZ0=Symbol("onDone"),oA=Symbol("sawValidEntry"),oZ0=Symbol("sawNullBlock"),rZ0=Symbol("sawEOF"),QL4=Symbol("closeStream"),Kt5=()=>!0,Tl=class extends Rs5{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[QH]=[];[g8];[ZH];[nA];[TK]="begin";[sN]="";[$q];[Ul];[tN]=!1;[l7];[eN]=!1;[oA];[oZ0]=!1;[rZ0]=!1;[Ak]=!1;[Hl]=!1;[ec0]=!1;constructor(J={}){super(),this.file=J.file||"",this.on(aZ0,()=>{(this[TK]==="begin"||this[oA]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),J.ondone?this.on(aZ0,J.ondone):this.on(aZ0,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!J.strict,this.maxMetaEntrySize=J.maxMetaEntrySize||Yt5,this.filter=typeof J.filter=="function"?J.filter:Kt5;let Z=J.file&&(J.file.endsWith(".tar.br")||J.file.endsWith(".tbr"));this.brotli=!(J.gzip||J.zstd)&&J.brotli!==void 0?J.brotli:Z?void 0:!1;let Q=J.file&&(J.file.endsWith(".tar.zst")||J.file.endsWith(".tzst"));this.zstd=!(J.gzip||J.brotli)&&J.zstd!==void 0?J.zstd:Q?!0:void 0,this.on("end",()=>this[QL4]()),typeof J.onwarn=="function"&&this.on("warn",J.onwarn),typeof J.onReadEntry=="function"&&this.on("entry",J.onReadEntry)}warn(J,Z,Q={}){BQ0(this,J,Z,Q)}[ZL4](J,Z){this[oA]===void 0&&(this[oA]=!1);let Q;try{Q=new Jj(J,Z,this[$q],this[Ul])}catch(Y){return this.warn("TAR_ENTRY_INVALID",Y)}if(Q.nullBlock)this[oZ0]?(this[rZ0]=!0,this[TK]==="begin"&&(this[TK]="header"),this[aA]("eof")):(this[oZ0]=!0,this[aA]("nullBlock"));else if(this[oZ0]=!1,!Q.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:Q});else if(!Q.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:Q});else{let Y=Q.type;if(/^(Symbolic)?Link$/.test(Y)&&!Q.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:Q});else if(!/^(Symbolic)?Link$/.test(Y)&&!/^(Global)?ExtendedHeader$/.test(Y)&&Q.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:Q});else{let X=this[nA]=new yL4(Q,this[$q],this[Ul]);if(!this[oA])if(X.remain){let K=()=>{X.invalid||(this[oA]=!0)};X.on("end",K)}else this[oA]=!0;X.meta?X.size>this.maxMetaEntrySize?(X.ignore=!0,this[aA]("ignoredEntry",X),this[TK]="ignore",X.resume()):X.size>0&&(this[sN]="",X.on("data",(K)=>this[sN]+=K),this[TK]="meta"):(this[$q]=void 0,X.ignore=X.ignore||!this.filter(X.path,X),X.ignore?(this[aA]("ignoredEntry",X),this[TK]=X.remain?"ignore":"header",X.resume()):(X.remain?this[TK]="body":(this[TK]="header",X.end()),this[ZH]?this[QH].push(X):(this[QH].push(X),this[tc0]())))}}}[QL4](){queueMicrotask(()=>this.emit("close"))}[ew4](J){let Z=!0;if(!J)this[ZH]=void 0,Z=!1;else if(Array.isArray(J)){let[Q,...Y]=J;this.emit(Q,...Y)}else this[ZH]=J,this.emit("entry",J),J.emittedEnd||(J.on("end",()=>this[tc0]()),Z=!1);return Z}[tc0](){do;while(this[ew4](this[QH].shift()));if(!this[QH].length){let J=this[ZH];!J||J.flowing||J.size===J.remain?this[Ak]||this.emit("drain"):J.once("drain",()=>this.emit("drain"))}}[$l0](J,Z){let Q=this[nA];if(!Q)throw Error("attempt to consume body without entry??");let Y=Q.blockRemain??0,X=Y>=J.length&&Z===0?J:J.subarray(Z,Z+Y);return Q.write(X),Q.blockRemain||(this[TK]="header",this[nA]=void 0,Q.end()),X.length}[JL4](J,Z){let Q=this[nA],Y=this[$l0](J,Z);return!this[nA]&&Q&&this[$L4](Q),Y}[aA](J,Z,Q){!this[QH].length&&!this[ZH]?this.emit(J,Z,Q):this[QH].push([J,Z,Q])}[$L4](J){switch(this[aA]("meta",this[sN]),J.type){case"ExtendedHeader":case"OldExtendedHeader":this[$q]=GQ0.parse(this[sN],this[$q],!1);break;case"GlobalExtendedHeader":this[Ul]=GQ0.parse(this[sN],this[Ul],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let Z=this[$q]??Object.create(null);this[$q]=Z,Z.path=this[sN].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let Z=this[$q]||Object.create(null);this[$q]=Z,Z.linkpath=this[sN].replace(/\0.*/,"");break}default:throw Error("unknown meta: "+J.type)}}abort(J){this[eN]=!0,this.emit("abort",J),this.warn("TAR_ABORT",J,{recoverable:!1})}write(J,Z,Q){if(typeof Z=="function"&&(Q=Z,Z=void 0),typeof J=="string"&&(J=Buffer.from(J,typeof Z=="string"?Z:"utf8")),this[eN])return Q?.(),!1;if((this[l7]===void 0||this.brotli===void 0&&this[l7]===!1)&&J){if(this[g8]&&(J=Buffer.concat([this[g8],J]),this[g8]=void 0),J.length<Xt5)return this[g8]=J,Q?.(),!0;for(let V=0;this[l7]===void 0&&V<Hl0.length;V++)J[V]!==Hl0[V]&&(this[l7]=!1);let X=!1;if(this[l7]===!1&&this.zstd!==!1){X=!0;for(let V=0;V<Dl0.length;V++)if(J[V]!==Dl0[V]){X=!1;break}}let K=this.brotli===void 0&&!X;if(this[l7]===!1&&K)if(J.length<512)if(this[tN])this.brotli=!0;else return this[g8]=J,Q?.(),!0;else try{new Jj(J.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[l7]===void 0||this[l7]===!1&&(this.brotli||X)){let V=this[tN];this[tN]=!1,this[l7]=this[l7]===void 0?new Ss5({}):X?new xs5({}):new vs5({}),this[l7].on("data",(G)=>this[lZ0](G)),this[l7].on("error",(G)=>this.abort(G)),this[l7].on("end",()=>{this[tN]=!0,this[lZ0]()}),this[Ak]=!0;let z=!!this[l7][V?"end":"write"](J);return this[Ak]=!1,Q?.(),z}}this[Ak]=!0,this[l7]?this[l7].write(J):this[lZ0](J),this[Ak]=!1;let Y=this[QH].length?!1:this[ZH]?this[ZH].flowing:!0;return!Y&&!this[QH].length&&this[ZH]?.once("drain",()=>this.emit("drain")),Q?.(),Y}[Jl0](J){J&&!this[eN]&&(this[g8]=this[g8]?Buffer.concat([this[g8],J]):J)}[nZ0](){if(this[tN]&&!this[ec0]&&!this[eN]&&!this[Hl]){this[ec0]=!0;let J=this[nA];if(J&&J.blockRemain){let Z=this[g8]?this[g8].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${J.blockRemain} more bytes, only ${Z} available)`,{entry:J}),this[g8]&&J.write(this[g8]),J.end()}this[aA](aZ0)}}[lZ0](J){if(this[Hl]&&J)this[Jl0](J);else if(!J&&!this[g8])this[nZ0]();else if(J){if(this[Hl]=!0,this[g8]){this[Jl0](J);let Z=this[g8];this[g8]=void 0,this[iZ0](Z)}else this[iZ0](J);for(;this[g8]&&this[g8]?.length>=512&&!this[eN]&&!this[rZ0];){let Z=this[g8];this[g8]=void 0,this[iZ0](Z)}this[Hl]=!1}(!this[g8]||this[tN])&&this[nZ0]()}[iZ0](J){let Z=0,Q=J.length;for(;Z+512<=Q&&!this[eN]&&!this[rZ0];)switch(this[TK]){case"begin":case"header":this[ZL4](J,Z),Z+=512;break;case"ignore":case"body":Z+=this[$l0](J,Z);break;case"meta":Z+=this[JL4](J,Z);break;default:throw Error("invalid state: "+this[TK])}Z<Q&&(this[g8]?this[g8]=Buffer.concat([J.subarray(Z),this[g8]]):this[g8]=J.subarray(Z))}end(J,Z,Q){return typeof J=="function"&&(Q=J,Z=void 0,J=void 0),typeof Z=="function"&&(Q=Z,Z=void 0),typeof J=="string"&&(J=Buffer.from(J,Z)),Q&&this.once("finish",Q),this[eN]||(this[l7]?(J&&this[l7].write(J),this[l7].end()):(this[tN]=!0,(this.brotli===void 0||this.zstd===void 0)&&(J=J||Buffer.alloc(0)),J&&this.write(J),this[nZ0]())),this}},Ml=(J)=>{let Z=J.length-1,Q=-1;for(;Z>-1&&J.charAt(Z)==="/";)Q=Z,Z--;return Q===-1?J:J.slice(0,Q)},Vt5=(J)=>{let Z=J.onReadEntry;J.onReadEntry=Z?(Q)=>{Z(Q),Q.resume()}:(Q)=>Q.resume()},xL4=(J,Z)=>{let Q=new Map(Z.map((K)=>[Ml(K),!0])),Y=J.filter,X=(K,V="")=>{let z=V||Ns5(K).root||".",G;if(K===z)G=!1;else{let F=Q.get(K);F!==void 0?G=F:G=X(Bs5(K),z)}return Q.set(K,G),G};J.filter=Y?(K,V)=>Y(K,V)&&X(Ml(K)):(K)=>X(Ml(K))},zt5=(J)=>{let Z=new Tl(J),Q=J.file,Y;try{Y=Tk.openSync(Q,"r");let X=Tk.fstatSync(Y),K=J.maxReadSize||16777216;if(X.size<K){let V=Buffer.allocUnsafe(X.size),z=Tk.readSync(Y,V,0,X.size,0);Z.end(z===V.byteLength?V:V.subarray(0,z))}else{let V=0,z=Buffer.allocUnsafe(K);for(;V<X.size;){let G=Tk.readSync(Y,z,0,K,V);if(G===0)break;V+=G,Z.write(z.subarray(0,G))}Z.end()}}finally{if(typeof Y=="number")try{Tk.closeSync(Y)}catch{}}},Gt5=(J,Z)=>{let Q=new Tl(J),Y=J.maxReadSize||16777216,X=J.file;return new Promise((K,V)=>{Q.on("error",V),Q.on("end",K),Tk.stat(X,(z,G)=>{if(z)V(z);else{let F=new vl0(X,{readSize:Y,size:G.size});F.on("error",V),F.pipe(Q)}})})},NQ0=_l(zt5,Gt5,(J)=>new Tl(J),(J)=>new Tl(J),(J,Z)=>{Z?.length&&xL4(J,Z),J.noResume||Vt5(J)}),fL4=(J,Z,Q)=>(J&=4095,Q&&(J=(J|384)&-19),Z&&(J&256&&(J|=64),J&32&&(J|=8),J&4&&(J|=1)),J),{isAbsolute:qt5,parse:XL4}=Ft5,ul0=(J)=>{let Z="",Q=XL4(J);for(;qt5(J)||Q.root;){let Y=J.charAt(0)==="/"&&J.slice(0,4)!=="//?/"?"/":Q.root;J=J.slice(Y.length),Z+=Y,Q=XL4(J)}return[Z,J]},wQ0=["|","<",">","?",":"],bl0=wQ0.map((J)=>String.fromCharCode(61440+J.charCodeAt(0))),Wt5=new Map(wQ0.map((J,Z)=>[J,bl0[Z]])),Ut5=new Map(bl0.map((J,Z)=>[J,wQ0[Z]])),KL4=(J)=>wQ0.reduce((Z,Q)=>Z.split(Q).join(Wt5.get(Q)),J),Ht5=(J)=>bl0.reduce((Z,Q)=>Z.split(Q).join(Ut5.get(Q)),J),uL4=(J,Z)=>Z?(J=A5(J).replace(/^\.(\/|$)/,""),Ml(Z)+"/"+J):A5(J),Dt5=16777216,VL4=Symbol("process"),zL4=Symbol("file"),GL4=Symbol("directory"),Bl0=Symbol("symlink"),FL4=Symbol("hardlink"),Dl=Symbol("header"),JQ0=Symbol("read"),Nl0=Symbol("lstat"),ZQ0=Symbol("onlstat"),wl0=Symbol("onread"),Ll0=Symbol("onreadlink"),Ol0=Symbol("openfile"),El0=Symbol("onopenfile"),Qw=Symbol("close"),qQ0=Symbol("mode"),Ml0=Symbol("awaitDrain"),Zl0=Symbol("ondrain"),Zq=Symbol("prefix"),bL4=class extends Zj{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#$=!1;constructor(J,Z={}){let Q=yl0(Z);super(),this.path=A5(J),this.portable=!!Q.portable,this.maxReadSize=Q.maxReadSize||Dt5,this.linkCache=Q.linkCache||new Map,this.statCache=Q.statCache||new Map,this.preservePaths=!!Q.preservePaths,this.cwd=A5(Q.cwd||process.cwd()),this.strict=!!Q.strict,this.noPax=!!Q.noPax,this.noMtime=!!Q.noMtime,this.mtime=Q.mtime,this.prefix=Q.prefix?A5(Q.prefix):void 0,this.onWriteEntry=Q.onWriteEntry,typeof Q.onwarn=="function"&&this.on("warn",Q.onwarn);let Y=!1;if(!this.preservePaths){let[K,V]=ul0(this.path);K&&typeof V=="string"&&(this.path=V,Y=K)}this.win32=!!Q.win32||process.platform==="win32",this.win32&&(this.path=Ht5(this.path.replace(/\\/g,"/")),J=J.replace(/\\/g,"/")),this.absolute=A5(Q.absolute||YL4.resolve(this.cwd,J)),this.path===""&&(this.path="./"),Y&&this.warn("TAR_ENTRY_INFO",`stripping ${Y} from absolute path`,{entry:this,path:Y+this.path});let X=this.statCache.get(this.absolute);X?this[ZQ0](X):this[Nl0]()}warn(J,Z,Q={}){return BQ0(this,J,Z,Q)}emit(J,...Z){return J==="error"&&(this.#$=!0),super.emit(J,...Z)}[Nl0](){Jq.lstat(this.absolute,(J,Z)=>{if(J)return this.emit("error",J);this[ZQ0](Z)})}[ZQ0](J){this.statCache.set(this.absolute,J),this.stat=J,J.isFile()||(J.size=0),this.type=wt5(J),this.emit("stat",J),this[VL4]()}[VL4](){switch(this.type){case"File":return this[zL4]();case"Directory":return this[GL4]();case"SymbolicLink":return this[Bl0]();default:return this.end()}}[qQ0](J){return fL4(J,this.type==="Directory",this.portable)}[Zq](J){return uL4(J,this.prefix)}[Dl](){if(!this.stat)throw Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new Jj({path:this[Zq](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Zq](this.linkpath):this.linkpath,mode:this[qQ0](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new GQ0({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[Zq](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Zq](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let J=this.header?.block;if(!J)throw Error("failed to encode header");super.write(J)}[GL4](){if(!this.stat)throw Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[Dl](),this.end()}[Bl0](){Jq.readlink(this.absolute,(J,Z)=>{if(J)return this.emit("error",J);this[Ll0](Z)})}[Ll0](J){this.linkpath=A5(J),this[Dl](),this.end()}[FL4](J){if(!this.stat)throw Error("cannot create link entry without stat");this.type="Link",this.linkpath=A5(YL4.relative(this.cwd,J)),this.stat.size=0,this[Dl](),this.end()}[zL4](){if(!this.stat)throw Error("cannot create file entry without stat");if(this.stat.nlink>1){let J=`${this.stat.dev}:${this.stat.ino}`,Z=this.linkCache.get(J);if(Z?.indexOf(this.cwd)===0)return this[FL4](Z);this.linkCache.set(J,this.absolute)}if(this[Dl](),this.stat.size===0)return this.end();this[Ol0]()}[Ol0](){Jq.open(this.absolute,"r",(J,Z)=>{if(J)return this.emit("error",J);this[El0](Z)})}[El0](J){if(this.fd=J,this.#$)return this[Qw]();if(!this.stat)throw Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let Z=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(Z),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[JQ0]()}[JQ0](){let{fd:J,buf:Z,offset:Q,length:Y,pos:X}=this;if(J===void 0||Z===void 0)throw Error("cannot read file without first opening");Jq.read(J,Z,Q,Y,X,(K,V)=>{if(K)return this[Qw](()=>this.emit("error",K));this[wl0](V)})}[Qw](J=()=>{}){this.fd!==void 0&&Jq.close(this.fd,J)}[wl0](J){if(J<=0&&this.remain>0){let Q=Object.assign(Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[Qw](()=>this.emit("error",Q))}if(J>this.remain){let Q=Object.assign(Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[Qw](()=>this.emit("error",Q))}if(!this.buf)throw Error("should have created buffer prior to reading");if(J===this.remain)for(let Q=J;Q<this.length&&J<this.blockRemain;Q++)this.buf[Q+this.offset]=0,J++,this.remain++;let Z=this.offset===0&&J===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+J);this.write(Z)?this[Zl0]():this[Ml0](()=>this[Zl0]())}[Ml0](J){this.once("drain",J)}write(J,Z,Q){if(typeof Z=="function"&&(Q=Z,Z=void 0),typeof J=="string"&&(J=Buffer.from(J,typeof Z=="string"?Z:"utf8")),this.blockRemain<J.length){let Y=Object.assign(Error("writing more data than expected"),{path:this.absolute});return this.emit("error",Y)}return this.remain-=J.length,this.blockRemain-=J.length,this.pos+=J.length,this.offset+=J.length,super.write(J,null,Q)}[Zl0](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[Qw]((J)=>J?this.emit("error",J):this.end());if(!this.buf)throw Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[JQ0]()}},Bt5=class extends bL4{sync=!0;[Nl0](){this[ZQ0](Jq.lstatSync(this.absolute))}[Bl0](){this[Ll0](Jq.readlinkSync(this.absolute))}[Ol0](){this[El0](Jq.openSync(this.absolute,"r"))}[JQ0](){let J=!0;try{let{fd:Z,buf:Q,offset:Y,length:X,pos:K}=this;if(Z===void 0||Q===void 0)throw Error("fd and buf must be set in READ method");let V=Jq.readSync(Z,Q,Y,X,K);this[wl0](V),J=!1}finally{if(J)try{this[Qw](()=>{})}catch{}}}[Ml0](J){J()}[Qw](J=()=>{}){this.fd!==void 0&&Jq.closeSync(this.fd),J()}},Nt5=class extends Zj{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(J,Z,Q={}){return BQ0(this,J,Z,Q)}constructor(J,Z={}){let Q=yl0(Z);super(),this.preservePaths=!!Q.preservePaths,this.portable=!!Q.portable,this.strict=!!Q.strict,this.noPax=!!Q.noPax,this.noMtime=!!Q.noMtime,this.onWriteEntry=Q.onWriteEntry,this.readEntry=J;let{type:Y}=J;if(Y==="Unsupported")throw Error("writing entry that should be ignored");this.type=Y,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=Q.prefix,this.path=A5(J.path),this.mode=J.mode!==void 0?this[qQ0](J.mode):void 0,this.uid=this.portable?void 0:J.uid,this.gid=this.portable?void 0:J.gid,this.uname=this.portable?void 0:J.uname,this.gname=this.portable?void 0:J.gname,this.size=J.size,this.mtime=this.noMtime?void 0:Q.mtime||J.mtime,this.atime=this.portable?void 0:J.atime,this.ctime=this.portable?void 0:J.ctime,this.linkpath=J.linkpath!==void 0?A5(J.linkpath):void 0,typeof Q.onwarn=="function"&&this.on("warn",Q.onwarn);let X=!1;if(!this.preservePaths){let[V,z]=ul0(this.path);V&&typeof z=="string"&&(this.path=z,X=V)}this.remain=J.size,this.blockRemain=J.startBlockSize,this.onWriteEntry?.(this),this.header=new Jj({path:this[Zq](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Zq](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),X&&this.warn("TAR_ENTRY_INFO",`stripping ${X} from absolute path`,{entry:this,path:X+this.path}),this.header.encode()&&!this.noPax&&super.write(new GQ0({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[Zq](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Zq](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let K=this.header?.block;if(!K)throw Error("failed to encode header");super.write(K),J.pipe(this)}[Zq](J){return uL4(J,this.prefix)}[qQ0](J){return fL4(J,this.type==="Directory",this.portable)}write(J,Z,Q){typeof Z=="function"&&(Q=Z,Z=void 0),typeof J=="string"&&(J=Buffer.from(J,typeof Z=="string"?Z:"utf8"));let Y=J.length;if(Y>this.blockRemain)throw Error("writing more to entry than is appropriate");return this.blockRemain-=Y,super.write(J,Q)}end(J,Z,Q){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof J=="function"&&(Q=J,Z=void 0,J=void 0),typeof Z=="function"&&(Q=Z,Z=void 0),typeof J=="string"&&(J=Buffer.from(J,Z??"utf8")),Q&&this.once("finish",Q),J?super.end(J,Q):super.end(Q),this}},wt5=(J)=>J.isFile()?"File":J.isDirectory()?"Directory":J.isSymbolicLink()?"SymbolicLink":"Unsupported",Lt5=class J{tail;head;length=0;static create(Z=[]){return new J(Z)}constructor(Z=[]){for(let Q of Z)this.push(Q)}*[Symbol.iterator](){for(let Z=this.head;Z;Z=Z.next)yield Z.value}removeNode(Z){if(Z.list!==this)throw Error("removing node which does not belong to this list");let{next:Q,prev:Y}=Z;return Q&&(Q.prev=Y),Y&&(Y.next=Q),Z===this.head&&(this.head=Q),Z===this.tail&&(this.tail=Y),this.length--,Z.next=void 0,Z.prev=void 0,Z.list=void 0,Q}unshiftNode(Z){if(Z===this.head)return;Z.list&&Z.list.removeNode(Z);let Q=this.head;Z.list=this,Z.next=Q,Q&&(Q.prev=Z),this.head=Z,this.tail||(this.tail=Z),this.length++}pushNode(Z){if(Z===this.tail)return;Z.list&&Z.list.removeNode(Z);let Q=this.tail;Z.list=this,Z.prev=Q,Q&&(Q.next=Z),this.tail=Z,this.head||(this.head=Z),this.length++}push(...Z){for(let Q=0,Y=Z.length;Q<Y;Q++)Et5(this,Z[Q]);return this.length}unshift(...Z){for(var Q=0,Y=Z.length;Q<Y;Q++)Mt5(this,Z[Q]);return this.length}pop(){if(!this.tail)return;let Z=this.tail.value,Q=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,Q.list=void 0,this.length--,Z}shift(){if(!this.head)return;let Z=this.head.value,Q=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,Q.list=void 0,this.length--,Z}forEach(Z,Q){Q=Q||this;for(let Y=this.head,X=0;Y;X++)Z.call(Q,Y.value,X,this),Y=Y.next}forEachReverse(Z,Q){Q=Q||this;for(let Y=this.tail,X=this.length-1;Y;X--)Z.call(Q,Y.value,X,this),Y=Y.prev}get(Z){let Q=0,Y=this.head;for(;Y&&Q<Z;Q++)Y=Y.next;if(Q===Z&&Y)return Y.value}getReverse(Z){let Q=0,Y=this.tail;for(;Y&&Q<Z;Q++)Y=Y.prev;if(Q===Z&&Y)return Y.value}map(Z,Q){Q=Q||this;let Y=new J;for(let X=this.head;X;)Y.push(Z.call(Q,X.value,this)),X=X.next;return Y}mapReverse(Z,Q){Q=Q||this;var Y=new J;for(let X=this.tail;X;)Y.push(Z.call(Q,X.value,this)),X=X.prev;return Y}reduce(Z,Q){let Y,X=this.head;if(arguments.length>1)Y=Q;else if(this.head)X=this.head.next,Y=this.head.value;else throw TypeError("Reduce of empty list with no initial value");for(var K=0;X;K++)Y=Z(Y,X.value,K),X=X.next;return Y}reduceReverse(Z,Q){let Y,X=this.tail;if(arguments.length>1)Y=Q;else if(this.tail)X=this.tail.prev,Y=this.tail.value;else throw TypeError("Reduce of empty list with no initial value");for(let K=this.length-1;X;K--)Y=Z(Y,X.value,K),X=X.prev;return Y}toArray(){let Z=Array(this.length);for(let Q=0,Y=this.head;Y;Q++)Z[Q]=Y.value,Y=Y.next;return Z}toArrayReverse(){let Z=Array(this.length);for(let Q=0,Y=this.tail;Y;Q++)Z[Q]=Y.value,Y=Y.prev;return Z}slice(Z=0,Q=this.length){Q<0&&(Q+=this.length),Z<0&&(Z+=this.length);let Y=new J;if(Q<Z||Q<0)return Y;Z<0&&(Z=0),Q>this.length&&(Q=this.length);let X=this.head,K=0;for(K=0;X&&K<Z;K++)X=X.next;for(;X&&K<Q;K++,X=X.next)Y.push(X.value);return Y}sliceReverse(Z=0,Q=this.length){Q<0&&(Q+=this.length),Z<0&&(Z+=this.length);let Y=new J;if(Q<Z||Q<0)return Y;Z<0&&(Z=0),Q>this.length&&(Q=this.length);let X=this.length,K=this.tail;for(;K&&X>Q;X--)K=K.prev;for(;K&&X>Z;X--,K=K.prev)Y.push(K.value);return Y}splice(Z,Q=0,...Y){Z>this.length&&(Z=this.length-1),Z<0&&(Z=this.length+Z);let X=this.head;for(let V=0;X&&V<Z;V++)X=X.next;let K=[];for(let V=0;X&&V<Q;V++)K.push(X.value),X=this.removeNode(X);X?X!==this.tail&&(X=X.prev):X=this.tail;for(let V of Y)X=Ot5(this,X,V);return K}reverse(){let Z=this.head,Q=this.tail;for(let Y=Z;Y;Y=Y.prev){let X=Y.prev;Y.prev=Y.next,Y.next=X}return this.head=Q,this.tail=Z,this}};function Ot5(J,Z,Q){let Y=Z,X=Z?Z.next:J.head,K=new hl0(Q,Y,X,J);return K.next===void 0&&(J.tail=K),K.prev===void 0&&(J.head=K),J.length++,K}function Et5(J,Z){J.tail=new hl0(Z,J.tail,void 0,J),J.head||(J.head=J.tail),J.length++}function Mt5(J,Z){J.head=new hl0(Z,void 0,J.head,J),J.tail||(J.tail=J.head),J.length++}var hl0=class{list;next;prev;value;constructor(J,Z,Q,Y){this.list=Y,this.value=J,Z?(Z.next=this,this.prev=Z):this.prev=void 0,Q?(Q.prev=this,this.next=Q):this.next=void 0}},WL4=class{path;absolute;entry;stat;readdir;pending=!1;ignore=!1;piped=!1;constructor(J,Z){this.path=J||"./",this.absolute=Z}},UL4=Buffer.alloc(1024),QQ0=Symbol("onStat"),Bl=Symbol("ended"),Ez=Symbol("queue"),rA=Symbol("current"),sA=Symbol("process"),Nl=Symbol("processing"),Ql0=Symbol("processJob"),Mz=Symbol("jobs"),Yl0=Symbol("jobDone"),YQ0=Symbol("addFSEntry"),HL4=Symbol("addTarEntry"),Al0=Symbol("stat"),jl0=Symbol("readdir"),XQ0=Symbol("onreaddir"),KQ0=Symbol("pipe"),DL4=Symbol("entry"),Xl0=Symbol("entryOpt"),VQ0=Symbol("writeEntryClass"),hL4=Symbol("write"),Kl0=Symbol("ondrain"),LQ0=class extends Zj{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[VQ0];onWriteEntry;[Ez];[Mz]=0;[Nl]=!1;[Bl]=!1;constructor(J={}){if(super(),this.opt=J,this.file=J.file||"",this.cwd=J.cwd||process.cwd(),this.maxReadSize=J.maxReadSize,this.preservePaths=!!J.preservePaths,this.strict=!!J.strict,this.noPax=!!J.noPax,this.prefix=A5(J.prefix||""),this.linkCache=J.linkCache||new Map,this.statCache=J.statCache||new Map,this.readdirCache=J.readdirCache||new Map,this.onWriteEntry=J.onWriteEntry,this[VQ0]=bL4,typeof J.onwarn=="function"&&this.on("warn",J.onwarn),this.portable=!!J.portable,J.gzip||J.brotli||J.zstd){if((J.gzip?1:0)+(J.brotli?1:0)+(J.zstd?1:0)>1)throw TypeError("gzip, brotli, zstd are mutually exclusive");if(J.gzip&&(typeof J.gzip!="object"&&(J.gzip={}),this.portable&&(J.gzip.portable=!0),this.zip=new _s5(J.gzip)),J.brotli&&(typeof J.brotli!="object"&&(J.brotli={}),this.zip=new ks5(J.brotli)),J.zstd&&(typeof J.zstd!="object"&&(J.zstd={}),this.zip=new ys5(J.zstd)),!this.zip)throw Error("impossible");let Z=this.zip;Z.on("data",(Q)=>super.write(Q)),Z.on("end",()=>super.end()),Z.on("drain",()=>this[Kl0]()),this.on("resume",()=>Z.resume())}else this.on("drain",this[Kl0]);this.noDirRecurse=!!J.noDirRecurse,this.follow=!!J.follow,this.noMtime=!!J.noMtime,J.mtime&&(this.mtime=J.mtime),this.filter=typeof J.filter=="function"?J.filter:()=>!0,this[Ez]=new Lt5,this[Mz]=0,this.jobs=Number(J.jobs)||4,this[Nl]=!1,this[Bl]=!1}[hL4](J){return super.write(J)}add(J){return this.write(J),this}end(J,Z,Q){return typeof J=="function"&&(Q=J,J=void 0),typeof Z=="function"&&(Q=Z,Z=void 0),J&&this.add(J),this[Bl]=!0,this[sA](),Q&&Q(),this}write(J){if(this[Bl])throw Error("write after end");return J instanceof yL4?this[HL4](J):this[YQ0](J),this.flowing}[HL4](J){let Z=A5(qL4.resolve(this.cwd,J.path));if(!this.filter(J.path,J))J.resume();else{let Q=new WL4(J.path,Z);Q.entry=new Nt5(J,this[Xl0](Q)),Q.entry.on("end",()=>this[Yl0](Q)),this[Mz]+=1,this[Ez].push(Q)}this[sA]()}[YQ0](J){let Z=A5(qL4.resolve(this.cwd,J));this[Ez].push(new WL4(J,Z)),this[sA]()}[Al0](J){J.pending=!0,this[Mz]+=1;let Z=this.follow?"stat":"lstat";FQ0[Z](J.absolute,(Q,Y)=>{J.pending=!1,this[Mz]-=1,Q?this.emit("error",Q):this[QQ0](J,Y)})}[QQ0](J,Z){this.statCache.set(J.absolute,Z),J.stat=Z,this.filter(J.path,Z)?Z.isFile()&&Z.nlink>1&&J===this[rA]&&!this.linkCache.get(`${Z.dev}:${Z.ino}`)&&!this.sync&&this[Ql0](J):J.ignore=!0,this[sA]()}[jl0](J){J.pending=!0,this[Mz]+=1,FQ0.readdir(J.absolute,(Z,Q)=>{if(J.pending=!1,this[Mz]-=1,Z)return this.emit("error",Z);this[XQ0](J,Q)})}[XQ0](J,Z){this.readdirCache.set(J.absolute,Z),J.readdir=Z,this[sA]()}[sA](){if(!this[Nl]){this[Nl]=!0;for(let J=this[Ez].head;J&&this[Mz]<this.jobs;J=J.next)if(this[Ql0](J.value),J.value.ignore){let Z=J.next;this[Ez].removeNode(J),J.next=Z}this[Nl]=!1,this[Bl]&&!this[Ez].length&&this[Mz]===0&&(this.zip?this.zip.end(UL4):(super.write(UL4),super.end()))}}get[rA](){return this[Ez]&&this[Ez].head&&this[Ez].head.value}[Yl0](J){this[Ez].shift(),this[Mz]-=1,this[sA]()}[Ql0](J){if(!J.pending){if(J.entry){J===this[rA]&&!J.piped&&this[KQ0](J);return}if(!J.stat){let Z=this.statCache.get(J.absolute);Z?this[QQ0](J,Z):this[Al0](J)}if(J.stat&&!J.ignore){if(!this.noDirRecurse&&J.stat.isDirectory()&&!J.readdir){let Z=this.readdirCache.get(J.absolute);if(Z?this[XQ0](J,Z):this[jl0](J),!J.readdir)return}if(J.entry=this[DL4](J),!J.entry){J.ignore=!0;return}J===this[rA]&&!J.piped&&this[KQ0](J)}}}[Xl0](J){return{onwarn:(Z,Q,Y)=>this.warn(Z,Q,Y),noPax:this.noPax,cwd:this.cwd,absolute:J.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix,onWriteEntry:this.onWriteEntry}}[DL4](J){this[Mz]+=1;try{return new this[VQ0](J.path,this[Xl0](J)).on("end",()=>this[Yl0](J)).on("error",(Z)=>this.emit("error",Z))}catch(Z){this.emit("error",Z)}}[Kl0](){this[rA]&&this[rA].entry&&this[rA].entry.resume()}[KQ0](J){J.piped=!0,J.readdir&&J.readdir.forEach((Y)=>{let X=J.path,K=X==="./"?"":X.replace(/\/*$/,"/");this[YQ0](K+Y)});let Z=J.entry,Q=this.zip;if(!Z)throw Error("cannot pipe without source");Q?Z.on("data",(Y)=>{Q.write(Y)||Z.pause()}):Z.on("data",(Y)=>{super.write(Y)||Z.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(J,Z,Q={}){BQ0(this,J,Z,Q)}},gl0=class extends LQ0{sync=!0;constructor(J){super(J),this[VQ0]=Bt5}pause(){}resume(){}[Al0](J){let Z=this.follow?"statSync":"lstatSync";this[QQ0](J,FQ0[Z](J.absolute))}[jl0](J){this[XQ0](J,FQ0.readdirSync(J.absolute))}[KQ0](J){let Z=J.entry,Q=this.zip;if(J.readdir&&J.readdir.forEach((Y)=>{let X=J.path,K=X==="./"?"":X.replace(/\/*$/,"/");this[YQ0](K+Y)}),!Z)throw Error("Cannot pipe without source");Q?Z.on("data",(Y)=>{Q.write(Y)}):Z.on("data",(Y)=>{super[hL4](Y)})}},At5=(J,Z)=>{let Q=new gl0(J),Y=new PL4(J.file,{mode:J.mode||438});Q.pipe(Y),gL4(Q,Z)},jt5=(J,Z)=>{let Q=new LQ0(J),Y=new HQ0(J.file,{mode:J.mode||438});Q.pipe(Y);let X=new Promise((K,V)=>{Y.on("error",V),Y.on("close",K),Q.on("error",V)});return mL4(Q,Z),X},gL4=(J,Z)=>{Z.forEach((Q)=>{Q.charAt(0)==="@"?NQ0({file:CL4.resolve(J.cwd,Q.slice(1)),sync:!0,noResume:!0,onReadEntry:(Y)=>J.add(Y)}):J.add(Q)}),J.end()},mL4=async(J,Z)=>{for(let Q=0;Q<Z.length;Q++){let Y=String(Z[Q]);Y.charAt(0)==="@"?await NQ0({file:CL4.resolve(String(J.cwd),Y.slice(1)),noResume:!0,onReadEntry:(X)=>{J.add(X)}}):J.add(Y)}J.end()},Rt5=(J,Z)=>{let Q=new gl0(J);return gL4(Q,Z),Q},It5=(J,Z)=>{let Q=new LQ0(J);return mL4(Q,Z),Q},w59=_l(At5,jt5,Rt5,It5,(J,Z)=>{if(!Z?.length)throw TypeError("no paths specified to add to archive")}),Ct5=process.env.__FAKE_PLATFORM__||process.platform,Tt5=Ct5==="win32",{O_CREAT:_t5,O_TRUNC:St5,O_WRONLY:kt5}=cL4.constants,lL4=Number(process.env.__FAKE_FS_O_FILENAME__)||cL4.constants.UV_FS_O_FILEMAP||0,vt5=Tt5&&!!lL4,yt5=524288,xt5=lL4|St5|_t5|kt5,iL4=vt5?(J)=>J<yt5?xt5:"w":()=>"w",Rl0=(J,Z,Q)=>{try{return OQ0.lchownSync(J,Z,Q)}catch(Y){if(Y?.code!=="ENOENT")throw Y}},WQ0=(J,Z,Q,Y)=>{OQ0.lchown(J,Z,Q,(X)=>{Y(X&&X?.code!=="ENOENT"?X:null)})},ft5=(J,Z,Q,Y,X)=>{if(Z.isDirectory())nL4(Al.resolve(J,Z.name),Q,Y,(K)=>{if(K)return X(K);let V=Al.resolve(J,Z.name);WQ0(V,Q,Y,X)});else{let K=Al.resolve(J,Z.name);WQ0(K,Q,Y,X)}},nL4=(J,Z,Q,Y)=>{OQ0.readdir(J,{withFileTypes:!0},(X,K)=>{if(X){if(X.code==="ENOENT")return Y();if(X.code!=="ENOTDIR"&&X.code!=="ENOTSUP")return Y(X)}if(X||!K.length)return WQ0(J,Z,Q,Y);let V=K.length,z=null,G=(F)=>{if(!z){if(F)return Y(z=F);if(--V===0)return WQ0(J,Z,Q,Y)}};for(let F of K)ft5(J,F,Z,Q,G)})},ut5=(J,Z,Q,Y)=>{Z.isDirectory()&&aL4(Al.resolve(J,Z.name),Q,Y),Rl0(Al.resolve(J,Z.name),Q,Y)},aL4=(J,Z,Q)=>{let Y;try{Y=OQ0.readdirSync(J,{withFileTypes:!0})}catch(X){let K=X;if(K?.code==="ENOENT")return;if(K?.code==="ENOTDIR"||K?.code==="ENOTSUP")return Rl0(J,Z,Q);throw K}for(let X of Y)ut5(J,X,Z,Q);return Rl0(J,Z,Q)},oL4=class extends Error{path;code;syscall="chdir";constructor(J,Z){super(`${Z}: Cannot cd into '${J}'`),this.path=J,this.code=Z}get name(){return"CwdError"}},EQ0=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(J,Z){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=J,this.path=Z}get name(){return"SymlinkError"}},ht5=(J,Z)=>{pY.stat(J,(Q,Y)=>{(Q||!Y.isDirectory())&&(Q=new oL4(J,Q?.code||"ENOTDIR")),Z(Q)})},gt5=(J,Z,Q)=>{J=A5(J);let Y=Z.umask??18,X=Z.mode|448,K=(X&Y)!==0,V=Z.uid,z=Z.gid,G=typeof V=="number"&&typeof z=="number"&&(V!==Z.processUid||z!==Z.processGid),F=Z.preserve,q=Z.unlink,W=A5(Z.cwd),U=(D,B)=>{D?Q(D):B&&G?nL4(B,V,z,(N)=>U(N)):K?pY.chmod(J,X,Q):Q()};if(J===W)return ht5(J,U);if(F)return bt5.mkdir(J,{mode:X,recursive:!0}).then((D)=>U(null,D??void 0),U);let H=A5(UQ0.relative(W,J)).split("/");Il0(W,H,X,q,W,void 0,U)},Il0=(J,Z,Q,Y,X,K,V)=>{if(!Z.length)return V(null,K);let z=Z.shift(),G=A5(UQ0.resolve(J+"/"+z));pY.mkdir(G,Q,rL4(G,Z,Q,Y,X,K,V))},rL4=(J,Z,Q,Y,X,K,V)=>(z)=>{z?pY.lstat(J,(G,F)=>{if(G)G.path=G.path&&A5(G.path),V(G);else if(F.isDirectory())Il0(J,Z,Q,Y,X,K,V);else if(Y)pY.unlink(J,(q)=>{if(q)return V(q);pY.mkdir(J,Q,rL4(J,Z,Q,Y,X,K,V))});else{if(F.isSymbolicLink())return V(new EQ0(J,J+"/"+Z.join("/")));V(z)}}):(K=K||J,Il0(J,Z,Q,Y,X,K,V))},mt5=(J)=>{let Z=!1,Q;try{Z=pY.statSync(J).isDirectory()}catch(Y){Q=Y?.code}finally{if(!Z)throw new oL4(J,Q??"ENOTDIR")}},pt5=(J,Z)=>{J=A5(J);let Q=Z.umask??18,Y=Z.mode|448,X=(Y&Q)!==0,K=Z.uid,V=Z.gid,z=typeof K=="number"&&typeof V=="number"&&(K!==Z.processUid||V!==Z.processGid),G=Z.preserve,F=Z.unlink,q=A5(Z.cwd),W=(D)=>{D&&z&&aL4(D,K,V),X&&pY.chmodSync(J,Y)};if(J===q)return mt5(q),W();if(G)return W(pY.mkdirSync(J,{mode:Y,recursive:!0})??void 0);let U=A5(UQ0.relative(q,J)).split("/"),H;for(let D=U.shift(),B=q;D&&(B+="/"+D);D=U.shift()){B=A5(UQ0.resolve(B));try{pY.mkdirSync(B,Y),H=H||B}catch{let N=pY.lstatSync(B);if(N.isDirectory())continue;if(F){pY.unlinkSync(B),pY.mkdirSync(B,Y),H=H||B;continue}else if(N.isSymbolicLink())return new EQ0(B,B+"/"+U.join("/"))}}return W(H)},Vl0=Object.create(null),BL4=1e4,jk=new Set,dt5=(J)=>{jk.has(J)?jk.delete(J):Vl0[J]=J.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),jk.add(J);let Z=Vl0[J],Q=jk.size-BL4;if(Q>BL4/10){for(let Y of jk)if(jk.delete(Y),delete Vl0[Y],--Q<=0)break}return Z},ct5=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,lt5=ct5==="win32",it5=(J)=>J.split("/").slice(0,-1).reduce((Z,Q)=>{let Y=Z[Z.length-1];return Y!==void 0&&(Q=sL4(Y,Q)),Z.push(Q||"/"),Z},[]),nt5=class{#$=new Map;#J=new Map;#Z=new Set;reserve(J,Z){J=lt5?["win32 parallelization disabled"]:J.map((Y)=>Ml(sL4(dt5(Y))));let Q=new Set(J.map((Y)=>it5(Y)).reduce((Y,X)=>Y.concat(X)));this.#J.set(Z,{dirs:Q,paths:J});for(let Y of J){let X=this.#$.get(Y);X?X.push(Z):this.#$.set(Y,[Z])}for(let Y of Q){let X=this.#$.get(Y);if(!X)this.#$.set(Y,[new Set([Z])]);else{let K=X[X.length-1];K instanceof Set?K.add(Z):X.push(new Set([Z]))}}return this.#Y(Z)}#Q(J){let Z=this.#J.get(J);if(!Z)throw Error("function does not have any path reservations");return{paths:Z.paths.map((Q)=>this.#$.get(Q)),dirs:[...Z.dirs].map((Q)=>this.#$.get(Q))}}check(J){let{paths:Z,dirs:Q}=this.#Q(J);return Z.every((Y)=>Y&&Y[0]===J)&&Q.every((Y)=>Y&&Y[0]instanceof Set&&Y[0].has(J))}#Y(J){return this.#Z.has(J)||!this.check(J)?!1:(this.#Z.add(J),J(()=>this.#X(J)),!0)}#X(J){if(!this.#Z.has(J))return!1;let Z=this.#J.get(J);if(!Z)throw Error("invalid reservation");let{paths:Q,dirs:Y}=Z,X=new Set;for(let K of Q){let V=this.#$.get(K);if(!V||V?.[0]!==J)continue;let z=V[1];if(!z){this.#$.delete(K);continue}if(V.shift(),typeof z=="function")X.add(z);else for(let G of z)X.add(G)}for(let K of Y){let V=this.#$.get(K),z=V?.[0];if(!(!V||!(z instanceof Set)))if(z.size===1&&V.length===1){this.#$.delete(K);continue}else if(z.size===1){V.shift();let G=V[0];typeof G=="function"&&X.add(G)}else z.delete(J)}return this.#Z.delete(J),X.forEach((K)=>this.#Y(K)),!0}},at5=()=>process.umask(),NL4=Symbol("onEntry"),Pl0=Symbol("checkFs"),wL4=Symbol("checkFs2"),Cl0=Symbol("isReusable"),_K=Symbol("makeFs"),Tl0=Symbol("file"),_l0=Symbol("directory"),zQ0=Symbol("link"),LL4=Symbol("symlink"),OL4=Symbol("hardlink"),Ol=Symbol("ensureNoSymlink"),EL4=Symbol("unsupported"),ML4=Symbol("checkPath"),zl0=Symbol("stripAbsolutePath"),Yw=Symbol("mkdir"),a2=Symbol("onError"),sZ0=Symbol("pending"),AL4=Symbol("pend"),Rk=Symbol("unpend"),Gl0=Symbol("ended"),Fl0=Symbol("maybeClose"),Sl0=Symbol("skip"),jl=Symbol("doChown"),Rl=Symbol("uid"),Il=Symbol("gid"),Pl=Symbol("checkedCwd"),ot5=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Cl=ot5==="win32",rt5=1024,st5=(J,Z)=>{if(!Cl)return K3.unlink(J,Z);let Q=J+".DELETE."+dL4(16).toString("hex");K3.rename(J,Q,(Y)=>{if(Y)return Z(Y);K3.unlink(Q,Z)})},tt5=(J)=>{if(!Cl)return K3.unlinkSync(J);let Z=J+".DELETE."+dL4(16).toString("hex");K3.renameSync(J,Z),K3.unlinkSync(Z)},jL4=(J,Z,Q)=>J!==void 0&&J===J>>>0?J:Z!==void 0&&Z===Z>>>0?Z:Q,ml0=class extends Tl{[Gl0]=!1;[Pl]=!1;[sZ0]=0;reservations=new nt5;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(J={}){if(J.ondone=()=>{this[Gl0]=!0,this[Fl0]()},super(J),this.transform=J.transform,this.chmod=!!J.chmod,typeof J.uid=="number"||typeof J.gid=="number"){if(typeof J.uid!="number"||typeof J.gid!="number")throw TypeError("cannot set owner without number uid and gid");if(J.preserveOwner)throw TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=J.uid,this.gid=J.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;J.preserveOwner===void 0&&typeof J.uid!="number"?this.preserveOwner=!!(process.getuid&&process.getuid()===0):this.preserveOwner=!!J.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof J.maxDepth=="number"?J.maxDepth:rt5,this.forceChown=J.forceChown===!0,this.win32=!!J.win32||Cl,this.newer=!!J.newer,this.keep=!!J.keep,this.noMtime=!!J.noMtime,this.preservePaths=!!J.preservePaths,this.unlink=!!J.unlink,this.cwd=A5(B2.resolve(J.cwd||process.cwd())),this.strip=Number(J.strip)||0,this.processUmask=this.chmod?typeof J.processUmask=="number"?J.processUmask:at5():0,this.umask=typeof J.umask=="number"?J.umask:this.processUmask,this.dmode=J.dmode||511&~this.umask,this.fmode=J.fmode||438&~this.umask,this.on("entry",(Z)=>this[NL4](Z))}warn(J,Z,Q={}){return(J==="TAR_BAD_ARCHIVE"||J==="TAR_ABORT")&&(Q.recoverable=!1),super.warn(J,Z,Q)}[Fl0](){this[Gl0]&&this[sZ0]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[zl0](J,Z){let Q=J[Z],{type:Y}=J;if(!Q||this.preservePaths)return!0;let[X,K]=ul0(Q),V=K.replace(/\\/g,"/").split("/");if(V.includes("..")||Cl&&/^[a-z]:\.\.$/i.test(V[0]??"")){if(Z==="path"||Y==="Link")return this.warn("TAR_ENTRY_ERROR",`${Z} contains '..'`,{entry:J,[Z]:Q}),!1;{let z=B2.posix.dirname(J.path),G=B2.posix.normalize(B2.posix.join(z,Q));if(G.startsWith("../")||G==="..")return this.warn("TAR_ENTRY_ERROR",`${Z} escapes extraction directory`,{entry:J,[Z]:Q}),!1}}return X&&(J[Z]=String(K),this.warn("TAR_ENTRY_INFO",`stripping ${X} from absolute ${Z}`,{entry:J,[Z]:Q})),!0}[ML4](J){let Z=A5(J.path),Q=Z.split("/");if(this.strip){if(Q.length<this.strip)return!1;if(J.type==="Link"){let Y=A5(String(J.linkpath)).split("/");if(Y.length>=this.strip)J.linkpath=Y.slice(this.strip).join("/");else return!1}Q.splice(0,this.strip),J.path=Q.join("/")}if(isFinite(this.maxDepth)&&Q.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:J,path:Z,depth:Q.length,maxDepth:this.maxDepth}),!1;if(!this[zl0](J,"path")||!this[zl0](J,"linkpath"))return!1;if(B2.isAbsolute(J.path)?J.absolute=A5(B2.resolve(J.path)):J.absolute=A5(B2.resolve(this.cwd,J.path)),!this.preservePaths&&typeof J.absolute=="string"&&J.absolute.indexOf(this.cwd+"/")!==0&&J.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:J,path:A5(J.path),resolvedPath:J.absolute,cwd:this.cwd}),!1;if(J.absolute===this.cwd&&J.type!=="Directory"&&J.type!=="GNUDumpDir")return!1;if(this.win32){let{root:Y}=B2.win32.parse(String(J.absolute));J.absolute=Y+KL4(String(J.absolute).slice(Y.length));let{root:X}=B2.win32.parse(J.path);J.path=X+KL4(J.path.slice(X.length))}return!0}[NL4](J){if(!this[ML4](J))return J.resume();switch(Pt5.equal(typeof J.absolute,"string"),J.type){case"Directory":case"GNUDumpDir":J.mode&&(J.mode=J.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[Pl0](J);default:return this[EL4](J)}}[a2](J,Z){J.name==="CwdError"?this.emit("error",J):(this.warn("TAR_ENTRY_ERROR",J,{entry:Z}),this[Rk](),Z.resume())}[Yw](J,Z,Q){gt5(A5(J),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:Z},Q)}[jl](J){return this.forceChown||this.preserveOwner&&(typeof J.uid=="number"&&J.uid!==this.processUid||typeof J.gid=="number"&&J.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[Rl](J){return jL4(this.uid,J.uid,this.processUid)}[Il](J){return jL4(this.gid,J.gid,this.processGid)}[Tl0](J,Z){let Q=typeof J.mode=="number"?J.mode&4095:this.fmode,Y=new HQ0(String(J.absolute),{flags:iL4(J.size),mode:Q,autoClose:!1});Y.on("error",(z)=>{Y.fd&&K3.close(Y.fd,()=>{}),Y.write=()=>!0,this[a2](z,J),Z()});let X=1,K=(z)=>{if(z){Y.fd&&K3.close(Y.fd,()=>{}),this[a2](z,J),Z();return}--X===0&&Y.fd!==void 0&&K3.close(Y.fd,(G)=>{G?this[a2](G,J):this[Rk](),Z()})};Y.on("finish",()=>{let z=String(J.absolute),G=Y.fd;if(typeof G=="number"&&J.mtime&&!this.noMtime){X++;let F=J.atime||new Date,q=J.mtime;K3.futimes(G,F,q,(W)=>W?K3.utimes(z,F,q,(U)=>K(U&&W)):K())}if(typeof G=="number"&&this[jl](J)){X++;let F=this[Rl](J),q=this[Il](J);typeof F=="number"&&typeof q=="number"&&K3.fchown(G,F,q,(W)=>W?K3.chown(z,F,q,(U)=>K(U&&W)):K())}K()});let V=this.transform&&this.transform(J)||J;V!==J&&(V.on("error",(z)=>{this[a2](z,J),Z()}),J.pipe(V)),V.pipe(Y)}[_l0](J,Z){let Q=typeof J.mode=="number"?J.mode&4095:this.dmode;this[Yw](String(J.absolute),Q,(Y)=>{if(Y){this[a2](Y,J),Z();return}let X=1,K=()=>{--X===0&&(Z(),this[Rk](),J.resume())};J.mtime&&!this.noMtime&&(X++,K3.utimes(String(J.absolute),J.atime||new Date,J.mtime,K)),this[jl](J)&&(X++,K3.chown(String(J.absolute),Number(this[Rl](J)),Number(this[Il](J)),K)),K()})}[EL4](J){J.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${J.type}`,{entry:J}),J.resume()}[LL4](J,Z){let Q=A5(B2.relative(this.cwd,B2.resolve(B2.dirname(String(J.absolute)),String(J.linkpath)))).split("/");this[Ol](J,this.cwd,Q,()=>this[zQ0](J,String(J.linkpath),"symlink",Z),(Y)=>{this[a2](Y,J),Z()})}[OL4](J,Z){let Q=A5(B2.resolve(this.cwd,String(J.linkpath))),Y=A5(String(J.linkpath)).split("/");this[Ol](J,this.cwd,Y,()=>this[zQ0](J,Q,"link",Z),(X)=>{this[a2](X,J),Z()})}[Ol](J,Z,Q,Y,X){let K=Q.shift();if(this.preservePaths||K===void 0)return Y();let V=B2.resolve(Z,K);K3.lstat(V,(z,G)=>{if(z)return Y();if(G?.isSymbolicLink())return X(new EQ0(V,B2.resolve(V,Q.join("/"))));this[Ol](J,V,Q,Y,X)})}[AL4](){this[sZ0]++}[Rk](){this[sZ0]--,this[Fl0]()}[Sl0](J){this[Rk](),J.resume()}[Cl0](J,Z){return J.type==="File"&&!this.unlink&&Z.isFile()&&Z.nlink<=1&&!Cl}[Pl0](J){this[AL4]();let Z=[J.path];J.linkpath&&Z.push(J.linkpath),this.reservations.reserve(Z,(Q)=>this[wL4](J,Q))}[wL4](J,Z){let Q=(V)=>{Z(V)},Y=()=>{this[Yw](this.cwd,this.dmode,(V)=>{if(V){this[a2](V,J),Q();return}this[Pl]=!0,X()})},X=()=>{if(J.absolute!==this.cwd){let V=A5(B2.dirname(String(J.absolute)));if(V!==this.cwd)return this[Yw](V,this.dmode,(z)=>{if(z){this[a2](z,J),Q();return}K()})}K()},K=()=>{K3.lstat(String(J.absolute),(V,z)=>{if(z&&(this.keep||this.newer&&z.mtime>(J.mtime??z.mtime))){this[Sl0](J),Q();return}if(V||this[Cl0](J,z))return this[_K](null,J,Q);if(z.isDirectory()){if(J.type==="Directory"){let G=this.chmod&&J.mode&&(z.mode&4095)!==J.mode,F=(q)=>this[_K](q??null,J,Q);return G?K3.chmod(String(J.absolute),Number(J.mode),F):F()}if(J.absolute!==this.cwd)return K3.rmdir(String(J.absolute),(G)=>this[_K](G??null,J,Q))}if(J.absolute===this.cwd)return this[_K](null,J,Q);st5(String(J.absolute),(G)=>this[_K](G??null,J,Q))})};this[Pl]?X():Y()}[_K](J,Z,Q){if(J){this[a2](J,Z),Q();return}switch(Z.type){case"File":case"OldFile":case"ContiguousFile":return this[Tl0](Z,Q);case"Link":return this[OL4](Z,Q);case"SymbolicLink":return this[LL4](Z,Q);case"Directory":case"GNUDumpDir":return this[_l0](Z,Q)}}[zQ0](J,Z,Q,Y){K3[Q](Z,String(J.absolute),(X)=>{X?this[a2](X,J):(this[Rk](),J.resume()),Y()})}},wl=(J)=>{try{return[null,J()]}catch(Z){return[Z,null]}},tL4=class extends ml0{sync=!0;[_K](J,Z){return super[_K](J,Z,()=>{})}[Pl0](J){if(!this[Pl]){let X=this[Yw](this.cwd,this.dmode);if(X)return this[a2](X,J);this[Pl]=!0}if(J.absolute!==this.cwd){let X=A5(B2.dirname(String(J.absolute)));if(X!==this.cwd){let K=this[Yw](X,this.dmode);if(K)return this[a2](K,J)}}let[Z,Q]=wl(()=>K3.lstatSync(String(J.absolute)));if(Q&&(this.keep||this.newer&&Q.mtime>(J.mtime??Q.mtime)))return this[Sl0](J);if(Z||this[Cl0](J,Q))return this[_K](null,J);if(Q.isDirectory()){if(J.type==="Directory"){let K=this.chmod&&J.mode&&(Q.mode&4095)!==J.mode,[V]=K?wl(()=>{K3.chmodSync(String(J.absolute),Number(J.mode))}):[];return this[_K](V,J)}let[X]=wl(()=>K3.rmdirSync(String(J.absolute)));this[_K](X,J)}let[Y]=J.absolute===this.cwd?[]:wl(()=>tt5(String(J.absolute)));this[_K](Y,J)}[Tl0](J,Z){let Q=typeof J.mode=="number"?J.mode&4095:this.fmode,Y=(V)=>{let z;try{K3.closeSync(X)}catch(G){z=G}(V||z)&&this[a2](V||z,J),Z()},X;try{X=K3.openSync(String(J.absolute),iL4(J.size),Q)}catch(V){return Y(V)}let K=this.transform&&this.transform(J)||J;K!==J&&(K.on("error",(V)=>this[a2](V,J)),J.pipe(K)),K.on("data",(V)=>{try{K3.writeSync(X,V,0,V.length)}catch(z){Y(z)}}),K.on("end",()=>{let V=null;if(J.mtime&&!this.noMtime){let z=J.atime||new Date,G=J.mtime;try{K3.futimesSync(X,z,G)}catch(F){try{K3.utimesSync(String(J.absolute),z,G)}catch{V=F}}}if(this[jl](J)){let z=this[Rl](J),G=this[Il](J);try{K3.fchownSync(X,Number(z),Number(G))}catch(F){try{K3.chownSync(String(J.absolute),Number(z),Number(G))}catch{V=V||F}}}Y(V)})}[_l0](J,Z){let Q=typeof J.mode=="number"?J.mode&4095:this.dmode,Y=this[Yw](String(J.absolute),Q);if(Y){this[a2](Y,J),Z();return}if(J.mtime&&!this.noMtime)try{K3.utimesSync(String(J.absolute),J.atime||new Date,J.mtime)}catch{}if(this[jl](J))try{K3.chownSync(String(J.absolute),Number(this[Rl](J)),Number(this[Il](J)))}catch{}Z(),J.resume()}[Yw](J,Z){try{return pt5(A5(J),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:Z})}catch(Q){return Q}}[Ol](J,Z,Q,Y,X){if(this.preservePaths||!Q.length)return Y();let K=Z;for(let V of Q){K=B2.resolve(K,V);let[z,G]=wl(()=>K3.lstatSync(K));if(z)return Y();if(G.isSymbolicLink())return X(new EQ0(K,B2.resolve(Z,Q.join("/"))))}Y()}[zQ0](J,Z,Q,Y){let X=`${Q}Sync`;try{K3[X](Z,String(J.absolute)),Y(),J.resume()}catch(K){return this[a2](K,J)}}},et5=(J)=>{let Z=new tL4(J),Q=J.file,Y=pL4.statSync(Q),X=J.maxReadSize||16777216;new Ds5(Q,{readSize:X,size:Y.size}).pipe(Z)},$e5=(J,Z)=>{let Q=new ml0(J),Y=J.maxReadSize||16777216,X=J.file;return new Promise((K,V)=>{Q.on("error",V),Q.on("close",K),pL4.stat(X,(z,G)=>{if(z)V(z);else{let F=new vl0(X,{readSize:Y,size:G.size});F.on("error",V),F.pipe(Q)}})})},Je5=_l(et5,$e5,(J)=>new tL4(J),(J)=>new ml0(J),(J,Z)=>{Z?.length&&xL4(J,Z)}),Ze5=(J,Z)=>{let Q=new gl0(J),Y=!0,X,K;try{try{X=mY.openSync(J.file,"r+")}catch(G){if(G?.code==="ENOENT")X=mY.openSync(J.file,"w+");else throw G}let V=mY.fstatSync(X),z=Buffer.alloc(512);$:for(K=0;K<V.size;K+=512){for(let q=0,W=0;q<512;q+=W){if(W=mY.readSync(X,z,q,z.length-q,K+q),K===0&&z[0]===31&&z[1]===139)throw Error("cannot append to compressed archives");if(!W)break $}let G=new Jj(z);if(!G.cksumValid)break;let F=512*Math.ceil((G.size||0)/512);if(K+F+512>V.size)break;K+=F,J.mtimeCache&&G.mtime&&J.mtimeCache.set(String(G.path),G.mtime)}Y=!1,Qe5(J,Q,K,X,Z)}finally{if(Y)try{mY.closeSync(X)}catch{}}},Qe5=(J,Z,Q,Y,X)=>{let K=new PL4(J.file,{fd:Y,start:Q});Z.pipe(K),Xe5(Z,X)},Ye5=(J,Z)=>{Z=Array.from(Z);let Q=new LQ0(J),Y=(X,K,V)=>{let z=(U,H)=>{U?mY.close(X,(D)=>V(U)):V(null,H)},G=0;if(K===0)return z(null,0);let F=0,q=Buffer.alloc(512),W=(U,H)=>{if(U||typeof H>"u")return z(U);if(F+=H,F<512&&H)return mY.read(X,q,F,q.length-F,G+F,W);if(G===0&&q[0]===31&&q[1]===139)return z(Error("cannot append to compressed archives"));if(F<512)return z(null,G);let D=new Jj(q);if(!D.cksumValid)return z(null,G);let B=512*Math.ceil((D.size??0)/512);if(G+B+512>K||(G+=B+512,G>=K))return z(null,G);J.mtimeCache&&D.mtime&&J.mtimeCache.set(String(D.path),D.mtime),F=0,mY.read(X,q,0,512,G,W)};mY.read(X,q,0,512,G,W)};return new Promise((X,K)=>{Q.on("error",K);let V="r+",z=(G,F)=>{if(G&&G.code==="ENOENT"&&V==="r+")return V="w+",mY.open(J.file,V,z);if(G||!F)return K(G);mY.fstat(F,(q,W)=>{if(q)return mY.close(F,()=>K(q));Y(F,W.size,(U,H)=>{if(U)return K(U);let D=new HQ0(J.file,{fd:F,start:H});Q.pipe(D),D.on("error",K),D.on("close",X),Ke5(Q,Z)})})};mY.open(J.file,V,z)})},Xe5=(J,Z)=>{Z.forEach((Q)=>{Q.charAt(0)==="@"?NQ0({file:eL4.resolve(J.cwd,Q.slice(1)),sync:!0,noResume:!0,onReadEntry:(Y)=>J.add(Y)}):J.add(Q)}),J.end()},Ke5=async(J,Z)=>{for(let Q=0;Q<Z.length;Q++){let Y=String(Z[Q]);Y.charAt(0)==="@"?await NQ0({file:eL4.resolve(String(J.cwd),Y.slice(1)),noResume:!0,onReadEntry:(X)=>J.add(X)}):J.add(Y)}J.end()},Ll=_l(Ze5,Ye5,()=>{throw TypeError("file is required")},()=>{throw TypeError("file is required")},(J,Z)=>{if(!As5(J))throw TypeError("file is required");if(J.gzip||J.brotli||J.zstd||J.file.endsWith(".br")||J.file.endsWith(".tbr"))throw TypeError("cannot append to compressed archives");if(!Z?.length)throw TypeError("no paths specified to add/replace")}),v59=_l(Ll.syncFile,Ll.asyncFile,Ll.syncNoFile,Ll.asyncNoFile,(J,Z=[])=>{Ll.validate?.(J,Z),Ve5(J)}),Ve5=(J)=>{let Z=J.filter;J.mtimeCache||(J.mtimeCache=new Map),J.filter=Z?(Q,Y)=>Z(Q,Y)&&!((J.mtimeCache?.get(Q)??Y.mtime??0)>(Y.mtime??0)):(Q,Y)=>!((J.mtimeCache?.get(Q)??Y.mtime??0)>(Y.mtime??0))};j9();j9();var D39=class{initApp;#$;constructor(J){this.initApp=J?.initApp,this.#$=J?.defaultAppOptions}createApp=(J)=>{let Z=new uZ0(J&&this.#$?{...this.#$,...J}:J??this.#$);if(this.initApp)this.initApp(Z);return Z};createMiddleware=(J)=>J;createHandlers=(...J)=>{return J.filter((Z)=>Z!==void 0)}};var Fe5=B4(wz(),1);var $O4=v.string(),pl0=v.object({actor_id:$O4,name:v.string(),key:v.string(),namespace_id:$O4,runner_name_selector:v.string(),create_ts:v.number(),connectable_ts:v.number().nullable().optional(),destroy_ts:v.number().nullable().optional(),sleep_ts:v.number().nullable().optional(),start_ts:v.number().nullable().optional(),error:v.unknown().nullable().optional()}),Ge5=v.object({metadata:v.record(v.string(),v.unknown())}),a39=v.object({actors:v.array(pl0)}),o39=v.object({datacenter:v.string().optional(),name:v.string(),runner_name_selector:v.string(),crash_policy:v.string(),key:v.string().nullable().optional(),input:v.string().nullable().optional()}),r39=v.object({actor:pl0}),s39=v.object({datacenter:v.string().optional(),name:v.string(),key:v.string(),runner_name_selector:v.string(),crash_policy:v.string(),input:v.string().nullable().optional()}),t39=v.object({actor:pl0,created:v.boolean()}),e39=v.object({}),$89=v.object({names:v.record(v.string(),Ge5)}),J89=v.object({value:v.string().nullable()});var Y89=class{#$;#J;constructor(J){this.#J=J}async acquire(J){if(!this.#$){let Q=this.#J.sqlitePool,Y=["@rivetkit","sqlite-vfs"].join("/");this.#$=import(Y).then(({SqliteVfsPool:X})=>new X({actorsPerInstance:Q.actorsPerInstance,idleDestroyMs:Q.idleDestroyMs}))}return await(await this.#$).acquire(J)}async shutdown(){if(this.#$)await(await this.#$).shutdown()}};function kk(J){return Ic0(J)}var qe5="https://production.ampworkers.com",We5="https://staging.ampworkers.com";function i7(J){if(J.includes("staging.ampcodedev.org"))return We5;return qe5}var Ue5="https://thread-actors-prod-us-east1-935747076731.us-east1.run.app",He5="https://thread-actors-staging-us-east1-739316246630.us-east1.run.app";function vk(J){if(J.includes("staging.ampcodedev.org"))return He5;return Ue5}async function JO4(J){let Z=J.workerURL??i7(J.ampURL),Q=await J.configService.getLatest(J.signal),Y=await Q.secrets.getToken("apiKey",Q.settings.url);if(!Y)throw Error("API key required. Please run `amp login` first.");let X=await fetch(`${Z}/threads/${J.threadID}/context-analysis`,{method:"GET",headers:{Authorization:`Bearer ${Y}`},signal:J.signal});if(!X.ok){let V=await X.text();throw Error(`Context analysis request failed (${X.status}): ${V}`)}let K=await X.json();if(!K.ok||!K.analysis)throw Error(K.error??"Invalid context analysis response from DTW");return K.analysis}async function ZO4(J){let Z=vk(J.ampURL),Q=kk({endpoint:Z}),Y=await J.configService.getLatest(J.signal),X=await Y.secrets.getToken("apiKey",Y.settings.url);if(!X)throw Error("API key required. Please run `amp login` first.");let K=await Q.threadActor.get([J.threadID]).fetch("/context-analysis",{method:"GET",headers:{Authorization:`Bearer ${X}`},signal:J.signal});if(!K.ok){let z=await K.text();throw Error(`Context analysis request failed (${K.status}): ${z}`)}let V=await K.json();if(!V.ok||!V.analysis)throw Error(V.error??"Invalid context analysis response from DTW");return V.analysis}var QO4=process.hrtime.bigint(),dl0=null;function YO4(){dl0=process.hrtime.bigint()}function XO4(){if(dl0===null)return null;return Number(process.hrtime.bigint()-dl0)/1e6}PX();m0();var Wj4=B4(O4(),1),dY=B4(Fj4(),1),Uj4=B4(zj(),1);import rQ0 from"node:fs";import In0 from"node:path";var qj4=Object.keys(P),Z83=In0.join(nZ,"logs"),Pn0=In0.join(Z83,"cli.log"),Q83=10485760;function Y83(J){try{if(rQ0.statSync(J).size>Q83)rQ0.truncateSync(J,0)}catch{}}var Zi,Cn0=!1,Ji=null;function X83(J){return J instanceof Error&&J.message.includes("write after end")}function $i(J,Z,Q,Y){if(Cn0)return;try{J[Z](Q,...Y)}catch(X){if(!X83(X))throw X}}function Hj4(J){Cn0=!1,Ji=null;let{logFile:Z,logLevel:Q}=J;if(!qj4.includes(Q))console.warn(`Invalid log level: ${Q}. Using 'info' instead.`);try{rQ0.mkdirSync(In0.dirname(Z),{recursive:!0})}catch(z){console.error(`Failed to create log directory: ${z}`)}Y83(Z);let Y=dY.default.format((z)=>{for(let G of Object.keys(z)){let F=z[G];if(F instanceof Error)z[G]={name:F.name,message:F.message,stack:F.stack}}return z}),X=dY.default.format((z)=>{return z.pid=process.pid,z}),K=[new dY.default.transports.File({filename:Z}),new Dj4];if(process.env.AMP_CLI_STDOUT_DEBUG==="true")K.push(new dY.default.transports.Console({level:"debug",format:dY.default.format.combine(dY.default.format.colorize(),dY.default.format.simple())}));Zi=dY.default.createLogger({level:qj4.includes(Q)?Q:"info",format:dY.default.format.combine(dY.default.format.timestamp(),X(),Y(),dY.default.format.json(),dY.default.format.errors({stack:!0})),transports:K});let V=Zi;return My1({error:(z,...G)=>{$i(V,"error",z,G)},warn:(z,...G)=>{$i(V,"warn",z,G)},info:(z,...G)=>{$i(V,"info",z,G)},debug:(z,...G)=>{$i(V,"debug",z,G)},audit:(z,...G)=>{let F=typeof G[0]==="object"&&G[0]!==null?{audit:!0,...G[0]}:{audit:!0};$i(V,"info",z,[F])}}),Z}class Dj4 extends Uj4.default{log({message:J,...Z},Q){Wj4.trace.getActiveSpan()?.addEvent(J,Z),Q()}}function VH(){if(Ji)return Ji;let J=Zi;if(!J)return Promise.resolve();return Cn0=!0,Ji=new Promise((Z)=>{let Q=!1,Y=()=>{if(!Q){if(Q=!0,Zi===J)Zi=void 0;Z()}};setImmediate(()=>{try{J.once("finish",Y).once("error",Y).end()}catch{Y()}}),setTimeout(Y,500)}),Ji}m0();import{execFile as K83}from"node:child_process";import{promisify as V83}from"node:util";var z83=V83(K83),G83=["private","public","workspace"];function Tn0(J){return J.endsWith("/")?J.slice(0,-1):J}function F83(J){let Z=HJ0(J);try{let X=new URL(Z);return Tn0(`${X.host}${X.pathname}`).replace(/^\//,"")}catch{}let Q=Z.match(/^[^@]+@([^:/]+)[:/](.+)$/);if(Q?.[1]&&Q[2])return Tn0(`${Q[1]}/${Q[2]}`).replace(/\.git$/,"");let Y=Z.match(/^([^:]+):(.+)$/);if(Y?.[1]&&Y[2])return Tn0(`${Y[1]}/${Y[2]}`).replace(/\.git$/,"");return null}async function wj4(J){try{let{stdout:Z}=await z83("git",["remote","get-url","origin"],{cwd:J}),Q=Z.trim();if(!Q)return null;return F83(Q)}catch{return null}}function q83(J){let Z=[...G83];if(J?.team?.disablePrivateThreads){let Q=Z.indexOf("private");if(Q!==-1)Z.splice(Q,1)}if(J?.team?.groups&&J.team.groups.length>0)Z.push("group");return Z}function Bj4(J){let Z=J?.team?.disablePrivateThreads??!1,Q=J?.team?.defaultThreadVisibility;if(!Q||Q==="private")return Z?"workspace":"private";if(Q==="thread_workspace_shared")return"workspace";if(Q==="creator_groups_fallback_private"){if(J?.team?.groups?.length)return"group";return Z?"workspace":"private"}return Z?"workspace":"private"}function W83(J){if(J?.team?.groups!==void 0)return Error(["Group visibility is not available. ",`You are not a member of any group in this workspace.
|
|
4670
4668
|
`].join(""));return Error(`Group visibility is not available.
|
|
4671
4669
|
`)}function Nj4(J,Z){let Y=[`Invalid ${J?`visibility for amp.defaultVisibility.${J}`:"visibility"}. `,`Must be one of: ${Z.join(", ")}.
|
|
4672
4670
|
`].join("");return Error(Y)}function U83(J,Z){return Z.includes(J)}function H83(J){return J?.team?.billingMode==="enterprise"||J?.team?.billingMode==="enterprise.selfserve"}function Lj4(J,Z,Q){if(J===void 0||J===null)return;let Y=q83(Z);if(typeof J!=="string")return Nj4(Q,Y);if(J==="group"&&!Y.includes("group"))return W83(Z);if(U83(J,Y))return J;return Nj4(Q,Y)}async function D83(J,Z,Q){let Y=await wj4(Z);if(!Y)return;let X;try{X=await J.get("defaultVisibility")}catch(V){P.warn("Failed to read defaultVisibility setting",{error:V});return}let K=X?.[Y];return Lj4(K,Q,Y)}async function sQ0(J,Z,Q,Y){if(Y)return Y;if(!H83(Q))return Bj4(Q);let X=await D83(J,Z,Q);if(X instanceof Error)return X;return X??Bj4(Q)}function Oj4(J,Z){return Lj4(J,Z)}async function Ej4(J,Z,Q){let Y=await wj4(Z);if(!Y)return Error("No git origin remote found for this repository.");let K={...await J.get("defaultVisibility","global")??{},[Y]:Q};return await J.set("defaultVisibility",K,"global"),{repoKey:Y}}t$();function tQ0(J){let Z=J.replace(/-/g,"");if(Z.length!==32)throw Error(`Invalid UUID hex length: ${Z.length}`);let Q=BigInt("0x"+Z),Y="";while(Q>0n)Y="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[Number(Q%62n)]+Y,Q=Q/62n;return Y.padStart(22,"0")}y3();N4();xA0();t$();var z8=v.string().min(1),eQ0=z8.brand(),Sn0=v.string().regex(/^[0-9A-Za-z]{22}$/),B83=v.templateLiteral([v.string().regex(/^[0-9a-f]{8}$/),"-",v.string().regex(/^[0-9a-f]{4}$/),"-",v.string().regex(/^[0-9a-f]{4}$/),"-",v.string().regex(/^[0-9a-f]{4}$/),"-",v.string().regex(/^[0-9a-f]{12}$/)]),Qi=v.templateLiteral(["T-",B83]),N83=v.enum(["fork","handoff","mention"]),w83=v.enum(["parent","child"]),Mj4=v.object({threadID:Qi,type:N83,role:w83,messageIndex:v.number().int().nonnegative().optional(),blockIndex:v.number().int().nonnegative().optional(),createdAt:v.number().int().nonnegative(),comment:v.string().optional()}),s6=v.templateLiteral(["M-",Sn0]);function zq(){return`M-${tQ0(iO())}`}var r8=v.templateLiteral(["TU-",Sn0]);function Aj4(){return`TU-${tQ0(iO())}`}var Yi=v.templateLiteral(["E-",Sn0]);function kn0(){return`E-${tQ0(iO())}`}var L83=v.looseObject({type:v.literal("object"),properties:v.record(v.string(),v.unknown()),required:v.array(v.string()).optional(),additionalProperties:v.boolean().optional()}),O83=v.union([v.literal("builtin"),v.object({toolbox:z8}).strict(),v.object({mcp:z8,target:v.enum(["global","workspace","flag","default"]).optional()}).strict(),v.object({plugin:z8}).strict(),v.object({remote:z8}).strict()]),E83=v.object({serial:v.boolean().optional(),deferred:v.boolean().optional(),skillNames:v.array(z8).optional()}),jj4=v.looseObject({name:z8,description:v.string(),inputSchema:L83,source:O83,meta:E83.optional()}),T79=v.object({id:z8,category:z8,title:z8,description:v.string().optional(),pluginName:z8}),vn0=v.strictObject({"agent.deepReasoningEffort":v.enum(["medium","high","xhigh"]).optional(),"agent.skipTitleGenerationIfMessageContains":v.array(v.string()).optional(),"anthropic.thinking.enabled":v.boolean().optional(),"anthropic.interleavedThinking.enabled":v.boolean().optional(),"anthropic.temperature":v.number().optional(),"anthropic.effort":v.enum(["low","medium","high","max"]).optional(),"anthropic.speed":v.enum(["standard","fast"]).optional(),"anthropic.provider":v.enum(["anthropic","vertex"]).optional(),"openai.speed":v.enum(["standard","fast"]).optional(),"internal.compactionThresholdPercent":v.number().min(0).max(100).optional(),"internal.model":v.union([v.string(),v.record(v.string(),v.string())]).optional(),"internal.oracleReasoningEffort":v.enum(["none","minimal","low","medium","high","xhigh"]).optional(),"gemini.thinkingLevel":v.enum(["minimal","low","medium","high"]).optional(),"tools.disable":v.array(v.string()).optional(),"tools.enable":v.array(v.string()).optional()}),Rj4=v.object({settings:vn0,workspaceId:v.string(),workingDirectory:v.string(),environment:v.object({os:v.enum(["darwin","linux","windows"]),hasDocker:v.boolean().optional(),hasBrowser:v.boolean().optional()}).strict(),tags:v.array(v.string())}).strict(),Ij4=v.enum(["sandbox","local-client"]),Xi=v.any().and(v.object({status:v.string()})),Pj4=v.discriminatedUnion("type",[v.object({type:v.literal("delta"),blocks:v.array(v.unknown()).optional(),state:v.enum(["start","generating","tool_use","complete","error"])}),v.object({type:v.literal("snapshot"),value:v.unknown()})]),Gq=z8,Cj4=30000,lk=PG,M83=v.enum(["file","directory"]),A83=v.object({mtimeMs:v.number().nonnegative().optional()}),Ki=v.tuple([v.string(),M83,A83.nullish()]),j83=v.enum(["INVALID_URI","EXECUTOR_NOT_CONNECTED","NOT_FOUND","NOT_DIRECTORY","IS_DIRECTORY","ACCESS_DENIED","INTERNAL_ERROR"]),Ww=v.object({code:j83,message:v.string()}),R83=v.object({ok:v.literal(!0),entries:v.array(Ki)}),I83=v.object({ok:v.literal(!1),error:Ww}),_79=v.discriminatedUnion("ok",[R83,I83]),P83=v.object({ok:v.literal(!0),contentBase64:v.string()}),C83=v.object({ok:v.literal(!1),error:Ww}),S79=v.discriminatedUnion("ok",[P83,C83]),T83=z8,yn0=v.object({key:z8,dataType:T83,contentBase64:v.string()}),xn0=yn0.extend({toolCallId:r8.optional(),updatedAt:v.string()}),ik=v.looseObject({uri:PG,content:v.string().optional(),lineCount:v.int().optional(),hash:v.string().optional()}),Tj4=v.object({name:z8,description:v.string(),baseDir:PG,frontmatter:v.object({name:z8,description:v.string()}).catchall(v.unknown()),files:v.array(v.string()).optional()}),fn0=v.object({type:v.literal("text"),text:v.string(),hidden:v.boolean().optional()}),_j4=v.looseObject({type:v.literal("image"),source:v.discriminatedUnion("type",[v.object({type:v.literal("base64"),mediaType:v.literal(["image/jpeg","image/png","image/gif","image/webp"]),data:v.string()}),v.object({type:v.literal("url"),url:v.string()})]),sourcePath:v.string()}),nk=v.array(v.discriminatedUnion("type",[fn0,_j4])),ck=v.record(v.string(),v.unknown()),Sj4=v.object({type:v.literal("tool_use"),id:v.string().min(1),name:v.string().min(1),normalizedName:v.string().optional(),metadata:v.record(v.string(),v.unknown()).optional()}),_83=Sj4.extend({complete:v.literal(!0),input:ck,normalizedInput:ck.optional()}),S83=Sj4.extend({complete:v.literal(!1),input:ck,inputIncomplete:ck,inputPartialJSON:v.object({json:v.string()}),normalizedInput:ck.optional()}),k83=v.object({accepted:v.boolean(),askAnswers:v.record(v.string(),v.string()).optional(),denyFeedback:v.string().optional()}),v83=v.object({type:v.literal("tool_result"),toolUseID:v.string().min(1),run:Xi,userInput:k83.optional()}),y83=v.object({type:v.literal("thinking"),thinking:v.string(),signature:v.string()}),x83=v.object({type:v.literal("redacted_thinking"),data:v.string()}),f83=v.object({type:v.literal("server_tool_use"),id:v.string().min(1),name:v.string().min(1),input:ck}),u83=v.object({type:v.literal("manual_bash_invocation"),args:v.object({cmd:v.string(),args:v.array(v.string()).readonly().optional(),cwd:v.string().optional()}),toolRun:Xi,hidden:v.boolean().optional()}),b83=v.object({sentAt:v.number().int().nonnegative().optional(),fromAggman:v.boolean().optional(),fromExecutorThreadID:Qi.optional()}),h83=v.object({uri:PG,lineCount:v.number().int().nonnegative(),content:v.string().optional()}),g83=v.union([fn0,_j4,v83]),m83=v.union([fn0,y83,x83,_83,S83,f83]),un0=v.array(g83),bn0=v.array(m83),p83=v.array(u83),_n0=v.looseObject({line:v.number().int(),column:v.number().int()}),d83=v.looseObject({start:_n0,end:_n0}),c83=v.looseObject({name:v.string(),repositoryURL:v.string()}),l83=v.looseObject({currentURL:v.string(),availableProjects:v.array(c83).optional()}),i83=v.object({treeOID:v.string(),repoRoot:v.string()}),hn0=v.looseObject({currentlyVisibleFiles:v.array(PG),runningTerminalCommands:v.array(v.string()).optional(),activeEditor:v.any().optional(),cursorLocation:_n0.optional(),cursorLocationLine:v.string().optional(),selectionRange:d83.optional(),snapshotOIDs:v.array(i83).optional(),aggmanContext:l83.optional()}),gn0=v.custom((J)=>typeof J==="string"&&B$(J)!==void 0),n83=v.object({threadId:Qi,role:v.literal("user"),content:un0,agentMode:gn0.optional(),discoveredGuidanceFiles:v.array(h83).optional(),meta:b83.optional(),userState:hn0.optional(),readAt:v.string().nullable().optional(),messageId:s6,createdAt:v.string().optional()}),mn0=v.object({model:v.string().optional(),maxInputTokens:v.number(),inputTokens:v.number(),outputTokens:v.number(),cacheCreationInputTokens:v.number().nullable(),cacheReadInputTokens:v.number().nullable(),totalInputTokens:v.number(),thinkingBudget:v.number().optional(),timestamp:v.string().optional()}),a83=v.union([v.object({type:v.literal("complete")}),v.object({type:v.literal("cancelled")})]),o83=v.object({threadId:Qi,role:v.literal("assistant"),content:bn0,state:a83.optional(),usage:mn0.optional(),readAt:v.string().nullable().optional(),messageId:s6,createdAt:v.string().optional()}),r83=v.object({threadId:Qi,role:v.literal("info"),content:p83,messageId:s6,createdAt:v.string().optional()}),kj4=v.discriminatedUnion("role",[n83,o83,r83]),Vi=v.object({workspaceRoot:PG.optional(),workingDirectory:PG.optional(),rootDirectoryListing:v.string().nullable().optional(),trees:v.array(v.any()).optional(),platform:v.any().optional(),tags:v.array(v.string()).optional(),updatedAt:v.string().optional()}),s83=v.object({added:v.number().int().nonnegative(),deleted:v.number().int().nonnegative(),changed:v.number().int().nonnegative()}),t83=v.object({path:v.string(),previousPath:v.string().optional(),changeType:v.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","untracked"]),created:v.boolean(),diff:v.string(),fullFileDiff:v.string().optional(),oldContent:v.string().optional(),newContent:v.string().optional(),diffStat:s83}),e83=v.object({hash:v.string(),shortHash:v.string(),subject:v.string()}),vj4=v.object({provider:v.literal("git"),capturedAt:v.number(),available:v.boolean(),repositoryRoot:v.string().nullable(),repositoryName:v.string().nullable(),branch:v.string().nullable(),head:v.string().nullable(),baseRef:v.string().nullable().optional(),baseRefHead:v.string().nullable().optional(),aheadCount:v.number().int().nonnegative().optional(),behindCount:v.number().int().nonnegative().optional(),aheadCommits:v.array(e83).optional(),files:v.array(t83),unavailableReason:v.string().optional(),unchanged:v.boolean().optional()}),$Y0=v.object({id:v.string(),toolCallId:r8,toolName:v.string(),args:v.record(v.string(),v.unknown()),reason:v.string().optional(),toAllow:v.array(v.string()).optional(),context:v.enum(["thread","subagent"]),subagentToolName:v.string().optional(),parentToolCallId:r8.optional(),timestamp:v.number(),matchedRule:v.object({tool:v.string(),action:v.string(),matches:v.record(v.string(),v.unknown()).optional()}).optional(),ruleSource:v.enum(["user","built-in"]).optional()}),$93=v.object({type:v.literal("request"),id:z8,method:z8,params:v.unknown()}),J93=v.object({type:v.literal("response"),id:z8,result:v.unknown().optional(),error:v.string().optional()}),Z93=v.object({type:v.literal("event"),event:z8,data:v.unknown(),span:v.string().optional()}),JY0=v.discriminatedUnion("type",[$93,J93,Z93]);var Q93=v.object({type:v.literal("executor_connect"),clientId:eQ0,capabilities:Rj4,executorType:Ij4.optional()}),Y93=v.object({type:v.literal("executor_settings_update"),settings:vn0}),X93=v.object({type:v.literal("executor_tools_register"),tools:v.array(jj4)}),K93=v.object({type:v.literal("executor_tools_unregister"),toolNames:v.array(z8)}),V93=v.object({type:v.literal("executor_tools_bootstrap_complete"),ok:v.boolean(),error:v.string().optional()}),z93=v.object({type:v.literal("executor_tool_lease_ack"),toolCallId:r8}),pn0=v.object({type:v.literal("tool_progress"),toolCallId:r8,progress:v.union([Pj4,v.unknown()]).optional(),parentToolCallId:r8.optional()}),G93=v.object({type:v.literal("executor_tool_result"),toolCallId:r8,run:Xi}),F93=v.object({type:v.literal("executor_guidance_snapshot"),snapshotId:z8,files:v.array(ik),isLast:v.boolean(),userConfigDir:v.any().optional()}),q93=v.object({type:v.literal("executor_guidance_discovery"),toolCallId:r8,files:v.array(ik),isLast:v.boolean()}),W93=v.object({type:v.literal("executor_skill_snapshot"),snapshotId:z8,skills:v.array(Tj4),isLast:v.boolean()}),U93=v.object({type:v.literal("executor_rollback_ack"),editId:Yi,ok:v.boolean(),error:v.string().optional()}),H93=v.object({type:v.literal("executor_revocation_ack"),toolCallId:r8}),D93=v.object({type:v.literal("executor_environment_snapshot"),environment:Vi}),B93=v.object({type:v.literal("executor_environment_update"),environment:Vi}),N93=v.object({type:v.literal("executor_artifact_upsert"),artifact:yn0,toolCallId:r8.optional()}),w93=v.object({type:v.literal("executor_artifact_delete"),key:z8}),L93=v.object({type:v.literal("executor_tool_approval_request"),approval:$Y0}),O93=v.object({type:v.literal("executor_plugin_message"),message:JY0}),E93=v.object({type:v.literal("client_append_user_msg"),content:nk,userState:hn0.optional(),discoveredGuidanceFiles:v.array(ik).optional(),agentMode:v.string().optional(),messageId:s6}),M93=v.object({type:v.literal("client_remove_queued_msg"),queuedMessageId:s6}),A93=v.object({type:v.literal("client_interrupt_queued_msg"),queuedMessageId:s6}),j93=v.object({type:v.literal("client_edit_message"),messageId:s6,editId:Yi,content:nk,agentMode:v.string().optional()}),R93=v.object({type:v.literal("client_mark_message_read"),messageId:s6}),I93=v.object({type:v.literal("client_mark_message_unread"),messageId:s6}),P93=v.object({type:v.literal("client_set_thread_title"),title:v.string().trim().min(1).max(256)}),C93=v.object({auth:v.string().min(1),p256dh:v.string().min(1)}),T93=v.object({endpoint:v.string().url(),keys:C93}),_93=v.object({type:v.literal("client_upsert_notification_subscription"),subscription:T93,threadURL:v.string().min(1)}),S93=v.object({type:v.literal("client_filesystem_read_directory"),requestId:Gq,uri:lk}),k93=v.object({type:v.literal("client_filesystem_read_file"),requestId:Gq,uri:lk}),v93=v.object({type:v.literal("executor_filesystem_read_directory_result"),requestId:Gq,ok:v.boolean(),entries:v.array(Ki).optional(),error:Ww.optional()}).superRefine((J,Z)=>{if(J.ok){if(!J.entries)Z.addIssue({code:v.ZodIssueCode.custom,message:"entries is required when ok is true"});if(J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.entries)Z.addIssue({code:v.ZodIssueCode.custom,message:"entries must not be present when ok is false"})}),y93=v.object({type:v.literal("executor_filesystem_read_file_result"),requestId:Gq,ok:v.boolean(),contentBase64:v.string().optional(),error:Ww.optional()}).superRefine((J,Z)=>{if(J.ok){if(J.contentBase64===void 0)Z.addIssue({code:v.ZodIssueCode.custom,message:"contentBase64 is required when ok is true"});if(J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.contentBase64!==void 0)Z.addIssue({code:v.ZodIssueCode.custom,message:"contentBase64 must not be present when ok is false"})}),x93=v.object({type:v.literal("client_resume"),version:v.number()}),f93=v.object({type:v.literal("client_retry")}),u93=v.object({type:v.literal("client_cancel")}),b93=v.object({type:v.literal("client_append_manual_bash_invocation"),args:v.object({cmd:v.string().trim().min(1,"cmd must contain at least one non-whitespace character"),args:v.array(v.string()).optional(),cwd:v.string().optional()}),run:Xi,hidden:v.boolean().optional()}),h93=v.object({type:v.literal("client_tool_approval_response"),toolCallId:r8,accepted:v.boolean(),input:v.object({askAnswers:v.record(v.string(),v.string()).optional(),denyFeedback:v.string().optional()}).optional()}),g93=v.object({type:v.literal("client_spawn_executor"),requestId:v.string().optional(),repositoryURL:v.string().optional(),projectID:v.uuid().optional(),additionalRepositories:v.array(v.object({name:v.string(),url:v.string()})).optional()}),x79=v.enum(["agg-man"]),yj4=v.discriminatedUnion("type",[Q93,Y93,X93,K93,V93,z93,pn0,G93,F93,q93,W93,U93,H93,D93,B93,N93,w93,L93,O93,E93,M93,A93,j93,R93,I93,P93,_93,S93,k93,v93,y93,x93,f93,u93,b93,h93,g93]);t$();t$();var m93=v.enum(["idle","working","streaming","tool_use","running_tools","awaiting_approval","error"]),p93=v.enum(["start","generating","tool_use","complete","error"]),d93=v.object({message:v.string(),code:v.string().optional(),stack:v.string().optional(),retryAt:v.number().optional(),attempt:v.number().optional()}),c93=v.object({userId:v.string(),name:v.string(),avatarURL:v.string().optional()}),l93=v.enum(["starting","running","failed"]),i93=v.object({cutMessageId:s6,createdAt:v.string()}),xj4=v.object({interrupt:v.boolean(),queuedMessage:v.object({role:v.literal("user"),messageId:s6,content:nk,userState:v.any().optional(),discoveredGuidanceFiles:v.array(ik).optional(),createdAt:v.string().optional()})}),n93=v.object({type:v.literal("agent_state"),state:m93,messageId:s6.optional()}),a93=v.object({type:v.literal("error"),message:v.string(),code:v.enum(["ACCESS_DENIED","CONNECTION_ERROR","MAX_RECONNECT_EXCEEDED","MESSAGE_ERROR","LOOP_RUNNING","NO_THREAD_ID","NO_ERROR","INVALID_MESSAGE","PARSE_ERROR","UNKNOWN_TYPE","INTERNAL_ERROR"]).optional()}),o93=v.object({type:v.literal("error_set"),seq:v.number(),error:d93}),r93=v.object({type:v.literal("error_cleared"),seq:v.number()}),s93=v.object({type:v.literal("cancelled"),seq:v.number(),messageId:s6.optional()}),t93=v.object({type:v.literal("retry_scheduled"),retryAt:v.number(),attempt:v.number(),maxAttempts:v.number(),reason:v.string()}),e93=v.object({type:v.literal("retry_started")}),$73=v.object({type:v.literal("retry_cancelled")}),J73=v.object({type:v.literal("executor_connected"),executorId:eQ0,registeredToolCount:v.number(),rejectedTools:v.array(v.object({name:v.string(),reason:v.string()})).optional()}),Z73=v.object({type:v.literal("tool_lease"),toolCallId:r8,toolName:v.string(),args:v.unknown(),messageId:s6,parentToolCallId:r8.optional()}),Q73=v.object({type:v.literal("executor_filesystem_read_directory"),requestId:Gq,uri:lk}),Y73=v.object({type:v.literal("executor_filesystem_read_file"),requestId:Gq,uri:lk}),X73=v.object({type:v.literal("client_filesystem_read_directory_result"),requestId:Gq,ok:v.boolean(),entries:v.array(Ki).optional(),error:Ww.optional()}).superRefine((J,Z)=>{if(J.ok){if(!J.entries)Z.addIssue({code:v.ZodIssueCode.custom,message:"entries is required when ok is true"});if(J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.entries)Z.addIssue({code:v.ZodIssueCode.custom,message:"entries must not be present when ok is false"})}),K73=v.object({type:v.literal("client_filesystem_read_file_result"),requestId:Gq,ok:v.boolean(),contentBase64:v.string().optional(),error:Ww.optional()}).superRefine((J,Z)=>{if(J.ok){if(J.contentBase64===void 0)Z.addIssue({code:v.ZodIssueCode.custom,message:"contentBase64 is required when ok is true"});if(J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.contentBase64!==void 0)Z.addIssue({code:v.ZodIssueCode.custom,message:"contentBase64 must not be present when ok is false"})}),V73=v.object({type:v.literal("tool_approval_queue"),approvals:v.array($Y0)}),z73=v.object({type:v.literal("executor_rollback_request"),editId:Yi,messageId:s6,reason:v.literal("message_edit"),toolUseIdsToRevert:v.array(r8)}),G73=v.object({type:v.literal("executor_tool_lease_revoked"),toolCallId:r8,reason:v.enum(["executor_disconnected","reassigned","user_canceled"])}),F73=v.object({type:v.literal("plugin_message"),message:JY0}),q73=v.object({type:v.literal("executor_tool_approval_response"),toolCallId:r8,accepted:v.boolean(),input:v.object({askAnswers:v.record(v.string(),v.string()).optional(),denyFeedback:v.string().optional()}).optional()}),W73=v.object({type:v.literal("executor_error"),message:v.string(),code:v.enum(["NOT_CONNECTED","ACCESS_DENIED","INVALID_MESSAGE","TOOL_NOT_FOUND","LEASE_NOT_FOUND","DUPLICATE_TOOL","INTERNAL_ERROR"])}),U73=v.object({type:v.literal("delta"),messageId:s6,role:v.literal("assistant"),blocks:bn0.optional(),state:p93,usage:mn0.optional(),parentToolCallId:r8.optional()}),H73=v.object({type:v.literal("delta"),messageId:s6,role:v.literal("user"),blocks:un0.optional(),state:v.literal("complete"),parentToolCallId:r8.optional()}),D73=v.discriminatedUnion("role",[U73,H73]),B73=v.object({type:v.literal("queued_messages"),messages:v.array(xj4)}),N73=v.object({type:v.literal("queued_message_added"),message:xj4,seq:v.number()}),w73=v.object({type:v.literal("queued_message_removed"),queuedMessageId:s6,seq:v.number()}),L73=v.object({type:v.literal("message_added"),message:kj4,seq:v.number(),parentToolUseId:z8.optional()}),O73=v.object({type:v.literal("edit_rejected"),editId:v.string(),message:v.string()}),E73=v.object({type:v.literal("message_edited"),seq:v.number(),editId:v.string(),messageId:s6,content:nk,truncateToMessageId:s6,reason:v.literal("message_edit"),agentMode:gn0.optional()}),M73=v.looseObject({type:v.literal("cf_agent_state")}),A73=v.looseObject({type:v.literal("cf_agent_mcp_servers")}),j73=v.looseObject({type:v.literal("cf_agent_identity")}),R73=v.object({type:v.literal("observers"),count:v.number(),observers:v.array(c93),hasExecutor:v.boolean().optional()}),I73=v.object({type:v.literal("executor_status"),spawnId:v.string(),status:l93,message:v.string().optional(),executorId:v.string().optional()}),P73=v.object({type:v.literal("environment_update"),environment:Vi}),C73=v.object({type:v.literal("artifacts_snapshot"),artifacts:v.array(xn0)}),T73=v.object({type:v.literal("artifact_upserted"),artifact:xn0}),_73=v.object({type:v.literal("artifact_deleted"),key:z8}),S73=v.object({type:v.literal("thread_title"),title:v.string().nullable()}),k73=v.object({type:v.literal("thread_status"),status:v.union([v.literal("merging"),v.literal("merged"),v.null()])}),v73=v.object({type:v.literal("thread_relationships"),seq:v.number(),relationships:v.array(Mj4)}),y73=v.object({type:v.literal("compaction_started")}),x73=v.object({type:v.literal("compaction_complete"),cutMessageId:s6}),f73=v.object({type:v.literal("compaction_records"),records:v.array(i93)}),ZY0=v.discriminatedUnion("type",[n93,a93,o93,r93,s93,t93,e93,$73,J73,Z73,Q73,Y73,X73,K73,V73,z73,G73,F73,q73,pn0,W73,D73,B73,N73,w73,L73,O73,E73,M73,A73,j73,R73,I73,P73,C73,T73,_73,S73,k73,v73,y73,x73,f73]);var dn0=(J)=>v.codec(v.string(),J,{decode:(Z,Q)=>{try{return JSON.parse(Z)}catch(Y){return Q.issues.push({code:"invalid_format",format:"json",input:Z,message:Y.message}),v.NEVER}},encode:(Z)=>JSON.stringify(Z)}),fj4=dn0(yj4),u73=v.union([ZY0,v.array(ZY0)]),uj4=dn0(ZY0),bj4=dn0(u73);N4();function hj4(J,Z={}){let Y=(Z.mode??"lenient")==="strict";if(!Array.isArray(J))return Y?null:[];let X=[];for(let K of J){if(typeof K!=="object"||K===null){if(Y)return null;continue}let V=K;if(typeof V.uri!=="string"||V.uri.length===0){if(Y)return null;continue}let z;try{z=n1(V1.parse(V.uri))}catch{if(Y)return null;continue}let G={uri:z};if(typeof V.content==="string")G.content=V.content;if(typeof V.lineCount==="number"&&Number.isFinite(V.lineCount))G.lineCount=V.lineCount;if(typeof V.hash==="string")G.hash=V.hash;X.push(G)}return X}var gj4=["invalid_json","missing_type","invalid_type","unknown_type","invalid_shape"];function cn0(J,Z){if(J.length<=Z)return J;return`${J.slice(0,Z)}...<truncated>`}function b73(J){return J.replace(/\s+/g," ").trim()}function h73(J){if(!J||typeof J!=="object")return[];let Z=J.issues;return Array.isArray(Z)?Z.slice(0,5):[]}function g73(J){if(J===void 0)return null;if(typeof J==="string")return JSON.stringify(J);if(typeof J==="number"||typeof J==="boolean"||J===null)return JSON.stringify(J);try{return cn0(JSON.stringify(J),120)}catch{return cn0(String(J),120)}}function mj4(J){if(!Array.isArray(J)||J.length===0)return null;let Z=J.map((Q)=>typeof Q==="number"?`[${Q}]`:String(Q)).join(".").replace(/\.\[/g,"[");return Z.length>0?Z:null}function m73(J){if(!J||typeof J!=="object")return null;let Z=J,Q=typeof Z.message==="string"?Z.message:null,Y=typeof Z.note==="string"?Z.note:null,X=mj4(Z.path);if(X&&Q&&Q!=="Invalid input")return`${X}: ${Q}`;if(X&&Y)return`${X}: ${Y}`;if(X&&Q)return`invalid value at ${X}`;return Y??Q}function pj4(J){for(let Z of J){let Q=m73(Z);if(Q)return Q}return null}function p73(J){return J.some((Z)=>{if(!Z||typeof Z!=="object")return!1;let Q=Z;return Q.code==="invalid_union"&&(Q.note==="No matching discriminator"||Q.discriminator==="type"||mj4(Q.path)==="type")})}function d73(J,Z){let Q=pj4(Z);if(J&&Q)return`type ${JSON.stringify(J)} failed validation: ${Q}`;if(J)return`type ${JSON.stringify(J)} failed validation`;if(Q)return`message payload failed validation: ${Q}`;return"message payload failed validation"}function dj4(J,Z,Q){let Y=h73(Z),X=(()=>{let F=b73(J);if(F.length===0)return null;return cn0(F,Q?.payloadPreviewMaxChars??1200)})(),K;try{K=JSON.parse(J)}catch{let F=pj4(Y);return{failureType:"invalid_json",summary:F?`malformed JSON: ${F}`:"malformed JSON",messageType:null,typePreview:null,payloadPreview:X,issues:Y}}if(!K||typeof K!=="object"||Array.isArray(K))return{failureType:"invalid_shape",summary:"expected a JSON object payload",messageType:null,typePreview:null,payloadPreview:X,issues:Y};let V=K;if(!Object.hasOwn(V,"type"))return{failureType:"missing_type",summary:'missing string "type"',messageType:null,typePreview:null,payloadPreview:X,issues:Y};let z=V.type,G=g73(z);if(typeof z!=="string")return{failureType:"invalid_type",summary:`expected string "type", got ${G??"unknown value"}`,messageType:null,typePreview:G,payloadPreview:X,issues:Y};if(p73(Y))return{failureType:"unknown_type",summary:`unsupported type ${JSON.stringify(z)} (likely protocol version mismatch)`,messageType:z,typePreview:G,payloadPreview:X,issues:Y};return{failureType:"invalid_shape",summary:d73(z,Y),messageType:z,typePreview:G,payloadPreview:X,issues:Y}}function zi(J,Z){if(J&&typeof J==="object"&&"type"in J){let Y=J;if(Y.type==="delta"||Y.type==="snapshot")return Y}if(Z==="snapshot")return{type:"snapshot",value:J};let Q=typeof J==="string"?J:J!==void 0?JSON.stringify(J):"";return{type:"delta",blocks:Q?[{type:"text",text:Q}]:void 0,state:"generating"}}function cj4(J){let Z=Number.isFinite(J)?J:0,Q=0,Y=Z;function X(V=Z){if(Number.isFinite(V))Z=V;return Q=0,Y=Z,Z}function K(V){if(!Number.isFinite(V)||V<1)return Z;if(V<=Q)return Z;if(Q===0)Y=Z-(V-1);return Z=Math.max(Z,Y+V),Q=V,Z}return{getVersion:()=>Z,reset:X,advanceFromSeq:K}}t$();var lj4="[dtw-parse-error]",in0="dtw-parse-error",c73=v.object({kind:v.literal(in0),failureType:v.enum(gj4).nullable().optional(),source:v.string().nullable().optional(),direction:v.string().nullable().optional(),stage:v.string().nullable().optional(),summary:v.string().nullable().optional(),messageType:v.string().nullable().optional(),typePreview:v.string().nullable().optional(),payloadPreview:v.string().nullable().optional(),issues:v.array(v.unknown()).optional()}).passthrough(),l73=v.object({source:v.string(),direction:v.string(),stage:v.string(),summary:v.string().nullable().optional(),messageType:v.string().nullable().optional(),payloadPreview:v.string().nullable().optional(),issues:v.array(v.unknown()).optional()}).passthrough();function ln0(J){return{kind:in0,failureType:J.failureType??null,source:J.source??null,direction:J.direction??null,stage:J.stage??null,summary:J.summary??null,messageType:J.messageType??null,typePreview:J.typePreview??null,payloadPreview:J.payloadPreview??null,issues:J.issues??[]}}function ij4(J){let Z=ln0(J);return JSON.stringify(Z)}function nj4(J,Z){let Q=dj4(J,Z);return ij4({failureType:Q.failureType,source:"dtw-transport",direction:"server->client",stage:"decode-server-message",summary:Q.summary,messageType:Q.messageType,typePreview:Q.typePreview,payloadPreview:Q.payloadPreview,issues:Q.issues})}function nn0(J){let Z=J.startsWith(lj4)?J.slice(lj4.length):J,Q;try{Q=JSON.parse(Z)}catch{return null}let Y=c73.safeParse(Q);if(Y.success)return ln0(Y.data);let X=l73.safeParse(Q);if(X.success)return ln0(X.data);return null}O1();class an0 extends Error{constructor(J){super(J);this.name="DTWError"}}class _9 extends an0{cause;constructor(J,Z){super(J);this.cause=Z;this.name="NetworkError"}}O1();var i73=1000,n73=30000,a73=5,o73=30000,r73=200,s73=30000,aj4=["online","focus","pageshow","keydown","pointerdown"],oj4=["visibilitychange"];function rn0(){return globalThis}function sj4(J){if(!J||typeof J!=="object")return null;let Z=J;if(typeof Z.addEventListener!=="function"||typeof Z.removeEventListener!=="function")return null;return Z}function rj4(){return sj4(rn0().window)}function on0(){let J=rn0().document;if(!sj4(J))return null;return J}function t73(){let J=rn0().navigator;if(!J||typeof J!=="object")return null;return J}function e73(J){if(!J)return"none";let Z=[J.type];if(J.code!==void 0)Z.push(`code=${J.code}`);if(J.reason!==void 0)Z.push(`reason=${J.reason}`);if(J.error!==void 0)Z.push(`error=${J.error}`);return Z.join(" ")}function QY0(J){return!!(J.apiKey&&J.WebSocketClass)}function sn0(J){if(QY0(J))return"one-step";return"two-step"}class tn0{ws=null;connectionInfo={state:"disconnected",role:null,clientId:null,threadId:null};reconnectCause=null;reconnectAttempts=0;reconnectTimeoutID=null;reconnectResetTimeoutID=null;pingIntervalID=null;disposed=!1;lastPongAt=Date.now();intentionallyClosedSockets=new WeakSet;reconnectActivityCleanup=null;lifecycleEventID=0;lifecycleEvents=[];connectionSubject=new K4({state:"disconnected",role:null,clientId:null,threadId:null});lifecycleEventSubject=new K4([]);config;currentThreadID=null;currentWsToken=null;constructor(J){this.config={baseURL:J.baseURL,threadId:J.threadId,apiKey:J.apiKey,wsToken:J.wsToken,wsTokenProvider:J.wsTokenProvider,webSocketProvider:J.webSocketProvider,reconnectDelayMs:J.reconnectDelayMs??i73,maxReconnectDelayMs:J.maxReconnectDelayMs??n73,maxReconnectAttempts:J.maxReconnectAttempts??a73,pingIntervalMs:J.pingIntervalMs??o73,WebSocketClass:J.WebSocketClass},this.currentThreadID=J.threadId??null,this.currentWsToken=J.wsToken??null,this.recordLifecycleEvent("transport_initialized",`flow=${sn0(this.config)} threadId=${this.currentThreadID??"none"}`)}getThreadId(){return this.currentThreadID}connectionChanges(){return this.connectionSubject}getConnectionInfo(){return{...this.connectionInfo}}connectionLifecycleChanges(){return this.lifecycleEventSubject}getConnectionLifecycleEvents(){return[...this.lifecycleEvents]}async connect(){return this.connectInternal({fromReconnect:!1})}recordLifecycleEvent(J,Z){let Q={id:++this.lifecycleEventID,at:Date.now(),type:J,...Z?{details:Z}:{}},Y=r73,X=this.lifecycleEvents.slice(-(Y-1));this.lifecycleEvents=[...X,Q],this.lifecycleEventSubject.next([...this.lifecycleEvents])}async connectInternal(J){if(this.disposed)throw new _9("Transport is disposed");if(this.ws)return;this.recordLifecycleEvent("connect_requested",J.fromReconnect?`mode=reconnect attempt=${this.reconnectAttempts}`:"mode=initial"),this.updateConnectionState("connecting");try{let Z=this.config.WebSocketClass??WebSocket,Q;if(this.config.webSocketProvider)Q=await this.config.webSocketProvider();else if(QY0(this.config)){let Y=this.config.baseURL.replace(/^http:/,"ws:").replace(/^https:/,"wss:"),X=this.config.apiKey;if(!X)throw new _9("1-step flow requires apiKey");let K=this.currentThreadID??this.config.threadId;if(!K)K=(await this.fetchWsToken()).threadId;let V=`${Y}/threads`;if(K)V=`${V}?threadId=${encodeURIComponent(K)}`;Q=new Z(V,{headers:{Authorization:`Bearer ${X}`}})}else{let Y=this.config.baseURL.replace(/^http:/,"ws:").replace(/^https:/,"wss:"),{threadId:X,wsToken:K}=await this.ensureWsToken();this.currentThreadID=X,this.currentWsToken=K;let V=`${Y}/threads`;Q=new Z(V,["amp",K])}try{Q.binaryType="arraybuffer"}catch{}await this.waitForOpen(Q),this.ws=Q,this.lastPongAt=Date.now(),this.setupWebSocketHandlers(Q),this.stopWaitingForReconnectActivity(),this.scheduleReconnectAttemptsReset(),this.reconnectCause=null,this.updateConnectionState("connected"),this.recordLifecycleEvent("connect_succeeded",`threadId=${this.currentThreadID??"none"} attempt=${this.reconnectAttempts}`)}catch(Z){let Q=Z instanceof Error?Z.message:String(Z);if(this.recordLifecycleEvent("connect_failed",`mode=${J.fromReconnect?"reconnect":"initial"} error=${Q}`),!J.fromReconnect&&!this.disposed)this.reconnectCause={type:"connect_failed",at:Date.now(),error:Q},this.scheduleReconnect();throw Z}}disconnect(){this.recordLifecycleEvent("disconnect_requested"),this.stopPingInterval(),this.cancelReconnect(),this.reconnectCause=null;let J=this.ws;if(J)this.ws=null,this.intentionallyClosedSockets.add(J),J.close(1000,"Client disconnect");this.updateConnectionState("disconnected")}dispose(){if(this.disposed)return;this.recordLifecycleEvent("disposed"),this.disposed=!0,this.disconnect(),this.connectionSubject.complete(),this.lifecycleEventSubject.complete()}sendRaw(J){if(!this.hasOpenSocket())throw new _9("WebSocket is not connected");this.ws?.send(J)}hasOpenSocket(){return!!this.ws&&this.ws.readyState===WebSocket.OPEN}updateConnectionState(J){if(J==="disconnected"||J==="reconnecting"){let Z={state:J,role:null,clientId:null,threadId:null};if(this.reconnectCause)Z.reconnectCause=this.reconnectCause;this.connectionInfo=Z}else if(this.connectionInfo.state=J,J==="connected")this.connectionInfo.threadId=this.currentThreadID,this.reconnectCause=null,delete this.connectionInfo.reconnectCause;else if(this.reconnectCause)this.connectionInfo.reconnectCause=this.reconnectCause;this.connectionSubject.next({...this.connectionInfo}),this.recordLifecycleEvent("state_changed",`state=${J} cause=${e73(this.reconnectCause)}`)}async handleAuthExpired(){this.recordLifecycleEvent("auth_refresh_started");try{if(this.currentWsToken=null,this.config.wsTokenProvider){let J=await this.config.wsTokenProvider({forceRefresh:!0});this.currentThreadID=J.threadId,this.currentWsToken=J.wsToken}this.recordLifecycleEvent("auth_refresh_succeeded",`threadId=${this.currentThreadID??"none"}`)}catch{this.recordLifecycleEvent("auth_refresh_failed")}}onRawMessage(J){}onMaxReconnectExceeded(J){}async ensureWsToken(){let J=this.reconnectAttempts>0;if(!J&&this.currentWsToken&&this.currentThreadID)return{threadId:this.currentThreadID,wsToken:this.currentWsToken};if(this.config.wsTokenProvider){let Z=await this.config.wsTokenProvider(J?{forceRefresh:!0}:void 0);return this.currentThreadID=Z.threadId,this.currentWsToken=Z.wsToken,Z}if(!J&&this.config.wsToken&&this.config.threadId)return{threadId:this.config.threadId,wsToken:this.config.wsToken};return this.fetchWsToken()}async fetchWsToken(){let Z=`${this.config.baseURL.replace(/^ws:/,"http:").replace(/^wss:/,"https:")}/threads`,Q={"Content-Type":"application/json"};if(this.config.apiKey)Q.Authorization=`Bearer ${this.config.apiKey}`;let Y=this.currentThreadID??this.config.threadId,X={};if(Y)X.threadId=Y;let K=await fetch(Z,{method:"POST",headers:Q,body:JSON.stringify(X)});if(!K.ok){let z=await K.text().catch(()=>"");throw new _9(`Failed to get wsToken: ${K.status} ${z}`)}let V=await K.json();if(!V.threadId||!V.wsToken)throw new _9("Invalid response from /threads: missing threadId or wsToken");return this.currentThreadID=V.threadId,this.currentWsToken=V.wsToken,{threadId:V.threadId,wsToken:V.wsToken}}async waitForOpen(J){if(J.readyState===WebSocket.OPEN)return;return new Promise((Z,Q)=>{let Y=()=>{J.removeEventListener("open",Y),J.removeEventListener("error",X),J.removeEventListener("close",K),Z()},X=(V)=>{J.removeEventListener("open",Y),J.removeEventListener("error",X),J.removeEventListener("close",K),this.updateConnectionState("disconnected");let z="message"in V?V.message:("error"in V)&&V.error instanceof Error?V.error.message:V.type;Q(new _9(`WebSocket connection failed: ${z}`))},K=(V)=>{J.removeEventListener("open",Y),J.removeEventListener("error",X),J.removeEventListener("close",K),this.updateConnectionState("disconnected"),Q(new _9(`WebSocket closed during connect: code=${V.code} reason=${V.reason||"none"}`))};if(J.addEventListener("open",Y),J.addEventListener("error",X),J.addEventListener("close",K),J.readyState===WebSocket.OPEN)return Y();if(J.readyState===WebSocket.CLOSED||J.readyState===WebSocket.CLOSING)return K({code:1006,reason:"Socket already closed before connect"})})}setupWebSocketHandlers(J){J.addEventListener("message",(Z)=>{let Q=Z.data;if(typeof Q==="string"){if(Q==="pong"){this.lastPongAt=Date.now();return}this.onRawMessage(Q)}else if(Q instanceof ArrayBuffer)this.onRawMessage(new TextDecoder().decode(Q))}),J.addEventListener("close",(Z)=>{this.handleClose(J,Z.code,Z.reason)}),J.addEventListener("error",()=>{this.handleError(J)}),this.startPingInterval()}handleClose(J,Z,Q){let Y=this.intentionallyClosedSockets.has(J);if(Y)this.intentionallyClosedSockets.delete(J);if(this.recordLifecycleEvent("socket_closed",`code=${Z} reason=${Q||"none"} intentional=${Y}`),J!==this.ws)return;if(this.ws=null,this.stopPingInterval(),this.cancelReconnectAttemptsReset(),!this.disposed&&!Y){let X=this.reconnectCause,K=X?.type==="ping_timeout"&&Z===4000&&!Q?{...X,at:Date.now(),code:Z}:{type:"close",at:Date.now(),code:Z,...Q?{reason:Q}:{}};if(this.reconnectCause=K,Z===4001||Q.includes("Token expired"))this.handleAuthExpired().catch(()=>{return}).finally(()=>{if(!this.disposed)this.scheduleReconnect()});else this.scheduleReconnect()}else this.reconnectCause=null,this.updateConnectionState("disconnected")}handleError(J){if(J!==this.ws)return;if(this.recordLifecycleEvent("socket_error","error=WebSocket error event"),this.reconnectCause={type:"error",at:Date.now(),error:"WebSocket error event"},this.ws)this.ws.close()}scheduleReconnect(J){if(this.disposed||this.reconnectTimeoutID)return;if(this.reconnectAttempts>=this.config.maxReconnectAttempts){this.stopWaitingForReconnectActivity(),this.recordLifecycleEvent("reconnect_exhausted",`attempts=${this.reconnectAttempts} max=${this.config.maxReconnectAttempts}`),this.updateConnectionState("disconnected"),this.onMaxReconnectExceeded(this.config.maxReconnectAttempts);return}if(!J?.bypassActivityGate&&this.shouldWaitForReconnectActivity()){this.recordLifecycleEvent("reconnect_waiting_for_activity",`offline=${this.isBrowserOffline()} hidden=${this.isDocumentHidden()}`),this.updateConnectionState("reconnecting"),this.waitForReconnectActivity();return}this.stopWaitingForReconnectActivity(),this.updateConnectionState("reconnecting"),this.reconnectAttempts++;let Z=J?.immediate?0:this.getReconnectDelayMs();this.recordLifecycleEvent("reconnect_scheduled",`attempt=${this.reconnectAttempts} delayMs=${Math.round(Z)}`),this.reconnectTimeoutID=setTimeout(()=>{this.reconnectTimeoutID=null,this.connectInternal({fromReconnect:!0}).catch((Q)=>{if(this.reconnectCause={type:"connect_failed",at:Date.now(),error:Q instanceof Error?Q.message:String(Q)},!this.disposed)this.scheduleReconnect()})},Z)}cancelReconnect(){if(this.reconnectTimeoutID)clearTimeout(this.reconnectTimeoutID),this.reconnectTimeoutID=null;this.stopWaitingForReconnectActivity(),this.cancelReconnectAttemptsReset(),this.reconnectAttempts=0}getReconnectDelayMs(){let J=this.config.reconnectDelayMs*2**(this.reconnectAttempts-1),Z=0.8+Math.random()*0.4;return Math.min(J*Z,this.config.maxReconnectDelayMs)}shouldWaitForReconnectActivity(){let J=rj4(),Z=on0();if(!J&&!Z)return!1;return this.isBrowserOffline()||this.isDocumentHidden()}isBrowserOffline(){let J=t73();if(typeof J?.onLine!=="boolean")return!1;return J.onLine===!1}isDocumentHidden(){let J=on0();if(!J)return!1;return J.visibilityState==="hidden"}waitForReconnectActivity(){if(this.reconnectActivityCleanup)return;let J=rj4(),Z=on0();if(!J&&!Z)return;let Q=()=>{this.handleReconnectActivity()};for(let Y of aj4)J?.addEventListener(Y,Q);for(let Y of oj4)Z?.addEventListener(Y,Q);this.reconnectActivityCleanup=()=>{for(let Y of aj4)J?.removeEventListener(Y,Q);for(let Y of oj4)Z?.removeEventListener(Y,Q)}}stopWaitingForReconnectActivity(){this.reconnectActivityCleanup?.(),this.reconnectActivityCleanup=null}handleReconnectActivity(){if(this.disposed||this.ws){this.stopWaitingForReconnectActivity();return}if(this.shouldWaitForReconnectActivity())return;this.stopWaitingForReconnectActivity(),this.recordLifecycleEvent("reconnect_activity_detected"),this.scheduleReconnect({immediate:!0,bypassActivityGate:!0})}scheduleReconnectAttemptsReset(){this.cancelReconnectAttemptsReset(),this.reconnectResetTimeoutID=setTimeout(()=>{this.reconnectResetTimeoutID=null,this.reconnectAttempts=0},s73)}cancelReconnectAttemptsReset(){if(this.reconnectResetTimeoutID)clearTimeout(this.reconnectResetTimeoutID),this.reconnectResetTimeoutID=null}startPingInterval(){this.stopPingInterval();let J=Date.now();this.pingIntervalID=setInterval(()=>{let Z=Date.now(),Q=Z-J;if(J=Z,Q>this.config.pingIntervalMs*3){this.lastPongAt=Z;return}if(this.hasOpenSocket()){let Y=Z-this.lastPongAt,X=this.config.pingIntervalMs*2;if(Y>X){this.recordLifecycleEvent("ping_timeout",`elapsedMs=${Y} thresholdMs=${X}`),this.reconnectCause={type:"ping_timeout",at:Z,code:4000,reason:"Pong timeout",error:`No pong received for ${Y}ms (threshold ${X}ms)`},this.ws?.close(4000,"Pong timeout");return}try{this.ws?.send("ping")}catch{}}},this.config.pingIntervalMs)}stopPingInterval(){if(this.pingIntervalID)clearInterval(this.pingIntervalID),this.pingIntervalID=null}}function $23(J){let Z=atob(J),Q=new Uint8Array(Z.length);for(let Y=0;Y<Z.length;Y++)Q[Y]=Z.charCodeAt(Y);return Q}class Fq extends tn0{deltaSubject=new Y4;errorSubject=new Y4;errorEventSubject=new Y4;cancelledSubject=new Y4;agentStateSubject=new Y4;messageAddedSubject=new Y4;editRejectedSubject=new Y4;messageEditedSubject=new Y4;queuedMessagesSubject=new Y4;retrySubject=new Y4;toolLeaseSubject=new Y4;toolLeaseRevokedSubject=new Y4;toolApprovalQueueSubject=new Y4;executorToolApprovalResponseSubject=new Y4;toolProgressSubject=new Y4;executorErrorSubject=new Y4;executorConnectedSubject=new Y4;executorRollbackRequestSubject=new Y4;observersSubject=new Y4;executorStatusSubject=new Y4;environmentUpdateSubject=new Y4;artifactsSubject=new Y4;threadTitleSubject=new Y4;threadStatusSubject=new Y4;threadRelationshipsSubject=new Y4;compactionSubject=new Y4;compactionRecordsSubject=new Y4;pluginMessageSubject=new Y4;fileSystemReadDirectoryRequestSubject=new Y4;fileSystemReadFileRequestSubject=new Y4;pendingReadDirectoryRequests=new Map;pendingReadFileRequests=new Map;fileSystemRequestCounter=0;constructor(J){super(J)}deltas(){return this.deltaSubject}agentStates(){return this.agentStateSubject}messageEvents(){return this.messageAddedSubject}editRejected(){return this.editRejectedSubject}messageEdited(){return this.messageEditedSubject}queuedMessages(){return this.queuedMessagesSubject}retryEvents(){return this.retrySubject}errors(){return this.errorSubject}errorEvents(){return this.errorEventSubject}cancelledEvents(){return this.cancelledSubject}toolLeases(){return this.toolLeaseSubject}toolLeaseRevoked(){return this.toolLeaseRevokedSubject}toolApprovalQueue(){return this.toolApprovalQueueSubject}executorToolApprovalResponses(){return this.executorToolApprovalResponseSubject}toolProgress(){return this.toolProgressSubject}executorErrors(){return this.executorErrorSubject}executorConnected(){return this.executorConnectedSubject}executorRollbackRequests(){return this.executorRollbackRequestSubject}observers(){return this.observersSubject}executorStatuses(){return this.executorStatusSubject}environmentUpdates(){return this.environmentUpdateSubject}artifacts(){return this.artifactsSubject}threadTitles(){return this.threadTitleSubject}threadStatuses(){return this.threadStatusSubject}threadRelationships(){return this.threadRelationshipsSubject}compactionEvents(){return this.compactionSubject}compactionRecords(){return this.compactionRecordsSubject}pluginMessages(){return this.pluginMessageSubject}fileSystemReadDirectoryRequests(){return this.fileSystemReadDirectoryRequestSubject}fileSystemReadFileRequests(){return this.fileSystemReadFileRequestSubject}dispose(){if(this.disposed)return;super.dispose(),this.rejectPendingFileSystemRequests("Transport disposed"),this.deltaSubject.complete(),this.errorSubject.complete(),this.errorEventSubject.complete(),this.cancelledSubject.complete(),this.agentStateSubject.complete(),this.messageAddedSubject.complete(),this.editRejectedSubject.complete(),this.messageEditedSubject.complete(),this.queuedMessagesSubject.complete(),this.retrySubject.complete(),this.toolLeaseSubject.complete(),this.toolLeaseRevokedSubject.complete(),this.toolApprovalQueueSubject.complete(),this.executorToolApprovalResponseSubject.complete(),this.toolProgressSubject.complete(),this.executorErrorSubject.complete(),this.executorConnectedSubject.complete(),this.executorRollbackRequestSubject.complete(),this.observersSubject.complete(),this.executorStatusSubject.complete(),this.environmentUpdateSubject.complete(),this.artifactsSubject.complete(),this.threadTitleSubject.complete(),this.threadStatusSubject.complete(),this.threadRelationshipsSubject.complete(),this.compactionSubject.complete(),this.compactionRecordsSubject.complete(),this.pluginMessageSubject.complete(),this.fileSystemReadDirectoryRequestSubject.complete(),this.fileSystemReadFileRequestSubject.complete()}sendUserMessage(J,Z,Q){let Y=Q?.messageId??zq();return this.send({type:"client_append_user_msg",content:J,agentMode:Z,messageId:Y,userState:Q?.userState,discoveredGuidanceFiles:Q?.discoveredGuidanceFiles}),Y}removeQueuedMessage(J){this.send({type:"client_remove_queued_msg",queuedMessageId:J})}interruptQueuedMessage(J){this.send({type:"client_interrupt_queued_msg",queuedMessageId:J})}editUserMessage(J,Z,Q,Y){this.send({type:"client_edit_message",messageId:J,editId:Q,content:Z,agentMode:Y})}markMessageRead(J){this.send({type:"client_mark_message_read",messageId:J})}markMessageUnread(J){this.send({type:"client_mark_message_unread",messageId:J})}setThreadTitle(J){this.send({type:"client_set_thread_title",title:J})}upsertNotificationSubscription(J,Z){this.send({type:"client_upsert_notification_subscription",subscription:J,threadURL:Z})}readDirectory(J){return this.requestReadDirectory(J)}readFile(J){return this.requestReadFile(J)}resumeFromVersion(J){this.send({type:"client_resume",version:J})}retryAgentLoop(){this.send({type:"client_retry"})}cancelAgentLoop(){if(!this.hasOpenSocket())return;this.send({type:"client_cancel"})}appendManualBashInvocation(J){this.send({type:"client_append_manual_bash_invocation",args:J.args,run:J.run,hidden:J.hidden})}resolveToolApproval(J,Z,Q){this.send({type:"client_tool_approval_response",toolCallId:J,accepted:Z,input:Q})}requestExecutorSpawn(J,Z){this.send({type:"client_spawn_executor",requestId:J,repositoryURL:Z?.repositoryURL,projectID:Z?.projectID,additionalRepositories:Z?.additionalRepositories})}executePluginCommand(J,Z,Q,Y){this.sendPluginMessage({type:"request",id:J,method:"command.execute",params:{pluginName:Z,commandId:Q,threadID:Y}})}async executorHandshake(J,Z,Q){if(this.disposed)throw new _9("Transport is disposed");if(!this.hasOpenSocket())throw new _9("WebSocket is not connected. Call connect() first.");return new Promise((Y,X)=>{let K=!1,V=null,z=(q)=>{if(K)return;if(K=!0,V)clearTimeout(V),V=null;G.unsubscribe(),F.unsubscribe(),q()},G=this.executorConnectedSubject.subscribe({next:(q)=>{this.connectionInfo.clientId=q.executorId,this.connectionInfo.role="executor",this.updateConnectionState("connected"),z(()=>Y(q))},error:(q)=>{z(()=>X(q))}}),F=this.executorErrorSubject.subscribe({next:(q)=>{z(()=>X(Error(q.message)))}});this.send({type:"executor_connect",clientId:J,capabilities:Z,executorType:Q?.executorType}),V=setTimeout(()=>{z(()=>X(Error("Executor connect timeout")))},1e4)})}ackToolLease(J){this.send({type:"executor_tool_lease_ack",toolCallId:J})}sendToolProgress(J,Z){let Q=zi(Z,"snapshot");this.send({type:"tool_progress",toolCallId:J,progress:Q})}sendExecutorToolResult(J,Z){this.send({type:"executor_tool_result",toolCallId:J,run:Z})}sendExecutorFileSystemReadDirectoryResult(J,Z){this.send({type:"executor_filesystem_read_directory_result",requestId:J,...Z})}sendExecutorFileSystemReadFileResult(J,Z){this.send({type:"executor_filesystem_read_file_result",requestId:J,...Z})}sendExecutorToolApprovalRequest(J){this.send({type:"executor_tool_approval_request",approval:J})}sendPluginMessage(J){this.send({type:"executor_plugin_message",message:J})}sendRevocationAck(J){this.send({type:"executor_revocation_ack",toolCallId:J})}sendExecutorGuidanceSnapshot(J){this.send({type:"executor_guidance_snapshot",...J})}sendExecutorGuidanceDiscovery(J){this.send({type:"executor_guidance_discovery",...J})}sendExecutorSkillSnapshot(J){this.send({type:"executor_skill_snapshot",...J})}sendExecutorSettingsUpdate(J){this.send({type:"executor_settings_update",settings:J})}sendExecutorRollbackAck(J,Z,Q){this.send({type:"executor_rollback_ack",editId:J,ok:Z,error:Q})}registerTools(J){this.send({type:"executor_tools_register",tools:J})}sendExecutorToolsBootstrapComplete(J,Z){this.send({type:"executor_tools_bootstrap_complete",ok:J,error:Z})}sendEnvironmentSnapshot(J){this.send({type:"executor_environment_snapshot",environment:J})}sendEnvironmentUpdate(J){this.send({type:"executor_environment_update",environment:J})}sendExecutorArtifactUpsert(J,Z){this.send({type:"executor_artifact_upsert",artifact:J,toolCallId:Z})}sendExecutorArtifactDelete(J){this.send({type:"executor_artifact_delete",key:J})}unregisterTools(J){this.send({type:"executor_tools_unregister",toolNames:J})}updateConnectionState(J){if(super.updateConnectionState(J),J==="reconnecting"||J==="disconnected")this.rejectPendingFileSystemRequests("Connection closed before filesystem request completed")}requestReadDirectory(J){let Z=this.nextFileSystemRequestID("read-directory");return this.createPendingReadRequest(this.pendingReadDirectoryRequests,Z,()=>{this.send({type:"client_filesystem_read_directory",requestId:Z,uri:J})})}requestReadFile(J){let Z=this.nextFileSystemRequestID("read-file");return this.createPendingReadRequest(this.pendingReadFileRequests,Z,()=>{this.send({type:"client_filesystem_read_file",requestId:Z,uri:J})})}createPendingReadRequest(J,Z,Q){if(!this.hasOpenSocket())return Promise.reject(new _9("WebSocket is not connected"));return new Promise((Y,X)=>{let K=setTimeout(()=>{J.delete(Z),X(new _9(`Filesystem request timed out: ${Z}`))},Cj4);J.set(Z,{resolve:Y,reject:X,timeoutID:K});try{Q()}catch(V){clearTimeout(K),J.delete(Z),X(V instanceof Error?V:Error(String(V)))}})}nextFileSystemRequestID(J){let Z=this.fileSystemRequestCounter++;return`${J}-${Date.now()}-${Z}`}handleReadDirectoryResult(J){let Z=this.pendingReadDirectoryRequests.get(J.requestId);if(!Z)return;if(clearTimeout(Z.timeoutID),this.pendingReadDirectoryRequests.delete(J.requestId),J.ok&&J.entries){Z.resolve(J.entries);return}if(J.ok){Z.reject(Error("Invalid filesystem read_directory response: missing entries"));return}if(!J.error){Z.reject(Error("Invalid filesystem read_directory response: missing error"));return}Z.reject(this.createFileSystemError(J.error))}handleReadFileResult(J){let Z=this.pendingReadFileRequests.get(J.requestId);if(!Z)return;if(clearTimeout(Z.timeoutID),this.pendingReadFileRequests.delete(J.requestId),!J.ok&&J.error){Z.reject(this.createFileSystemError(J.error));return}if(!J.ok){Z.reject(Error("Invalid filesystem read_file response: missing error"));return}if(J.contentBase64===void 0){Z.reject(Error("Invalid filesystem read_file response: missing content"));return}try{Z.resolve($23(J.contentBase64))}catch{Z.reject(Error("Invalid base64 payload in filesystem read_file response"))}}createFileSystemError(J){return Error(`Filesystem error (${J.code}): ${J.message}`)}rejectPendingFileSystemRequests(J){for(let[Z,Q]of this.pendingReadDirectoryRequests)clearTimeout(Q.timeoutID),Q.reject(new _9(J)),this.pendingReadDirectoryRequests.delete(Z);for(let[Z,Q]of this.pendingReadFileRequests)clearTimeout(Q.timeoutID),Q.reject(new _9(J)),this.pendingReadFileRequests.delete(Z)}onRawMessage(J){let Z=bj4.safeDecode(J);if(!Z.success){let Y=uj4.safeDecode(J),X=Y.success?Z.error:Y.error;this.errorSubject.next({type:"error",message:nj4(J,X),code:"PARSE_ERROR"});return}let Q=Array.isArray(Z.data)?Z.data:[Z.data];for(let Y of Q)this.handleServerMessage(Y)}handleServerMessage(J){switch(J.type){case"agent_state":this.agentStateSubject.next(J);break;case"error":this.errorSubject.next(J);break;case"error_set":case"error_cleared":this.errorEventSubject.next(J);break;case"cancelled":this.cancelledSubject.next(J);break;case"retry_scheduled":case"retry_started":case"retry_cancelled":this.retrySubject.next(J);break;case"delta":this.deltaSubject.next(J);break;case"message_added":this.messageAddedSubject.next(J);break;case"edit_rejected":this.editRejectedSubject.next(J);break;case"message_edited":this.messageEditedSubject.next(J);break;case"queued_messages":case"queued_message_added":case"queued_message_removed":this.queuedMessagesSubject.next(J);break;case"executor_connected":this.connectionInfo.role="executor",this.connectionInfo.clientId=J.executorId,this.connectionSubject.next({...this.connectionInfo}),this.executorConnectedSubject.next(J);break;case"tool_lease":this.toolLeaseSubject.next(J);break;case"executor_filesystem_read_directory":this.fileSystemReadDirectoryRequestSubject.next(J);break;case"executor_filesystem_read_file":this.fileSystemReadFileRequestSubject.next(J);break;case"executor_rollback_request":this.executorRollbackRequestSubject.next(J);break;case"executor_tool_lease_revoked":this.toolLeaseRevokedSubject.next(J);break;case"tool_approval_queue":this.toolApprovalQueueSubject.next(J);break;case"plugin_message":this.pluginMessageSubject.next(J);break;case"executor_tool_approval_response":this.executorToolApprovalResponseSubject.next(J);break;case"tool_progress":this.toolProgressSubject.next(J);break;case"executor_error":this.executorErrorSubject.next(J);break;case"cf_agent_state":case"cf_agent_mcp_servers":case"cf_agent_identity":break;case"observers":this.observersSubject.next(J);break;case"executor_status":this.executorStatusSubject.next(J);break;case"environment_update":this.environmentUpdateSubject.next(J);break;case"artifacts_snapshot":case"artifact_upserted":case"artifact_deleted":this.artifactsSubject.next(J);break;case"thread_title":this.threadTitleSubject.next(J);break;case"thread_status":this.threadStatusSubject.next(J);break;case"thread_relationships":this.threadRelationshipsSubject.next(J);break;case"client_filesystem_read_directory_result":this.handleReadDirectoryResult(J);break;case"client_filesystem_read_file_result":this.handleReadFileResult(J);break;case"compaction_started":case"compaction_complete":this.compactionSubject.next(J);break;case"compaction_records":this.compactionRecordsSubject.next(J);break}}onMaxReconnectExceeded(J){this.errorSubject.next({type:"error",message:`Failed to reconnect after ${J} attempts`,code:"MAX_RECONNECT_EXCEEDED"})}send(J){try{this.sendRaw(fj4.encode(J))}catch(Z){let Q=Z instanceof Error?Z.message:String(Z);throw new _9(`Failed to encode DTW client message "${J.type}": ${Q}`,Z)}}}function J23(J){if(!J||typeof J!=="object")return!1;let Z=J.queuedMessage;if(!Z||typeof Z!=="object")return!1;return typeof Z.messageId==="string"}function Z23(J){if(!J||typeof J!=="object")return!1;return typeof J.id==="string"}function Q23(J){if(J23(J))return J.queuedMessage.messageId;if(Z23(J))return J.id;throw Error("reduceQueuedMessages requires getQueuedMessageId for this message shape")}function en0(J,Z,Q={}){let Y=Q.getQueuedMessageId??Q23;if(Z.type==="queued_messages")return[...Z.messages];if(Z.type==="queued_message_added"){if(Q.dedupeAdded&&J.some((X)=>Y(X)===Y(Z.message)))return[...J];return[...J,Z.message]}if(!J.some((X)=>Y(X)===Z.queuedMessageId))return[...J];return J.filter((X)=>Y(X)!==Z.queuedMessageId)}var Y23=15000;function X23(J,Z,Q){let Y=!1,X=null,K=[],V=()=>{if(Y)return;if(Y=!0,X)clearTimeout(X),X=null;for(let G of K)G.unsubscribe()};return{promise:new Promise((G,F)=>{K.push(J.messageEvents().subscribe({next:(q)=>{if(q.message.messageId===Z)V(),G(q)}})),K.push(J.errors().subscribe({next:(q)=>{V(),F(Error(q.message))}})),K.push(J.executorErrors().subscribe({next:(q)=>{V(),F(Error(q.message))}})),K.push(J.connectionChanges().subscribe({next:(q)=>{if(q.state==="disconnected")V(),F(Error("Disconnected before message was acknowledged"))}})),X=setTimeout(()=>{V(),F(Error(`Timed out waiting for message_added after ${Q}ms`))},Q)}),dispose:V}}async function $a0(J){let Z=J.workerUrl??i7(J.ampURL),Q=new Fq({baseURL:Z,apiKey:J.apiKey,threadId:J.threadId,WebSocketClass:WebSocket,maxReconnectAttempts:1,pingIntervalMs:5000}),Y=J.timeoutMs??Y23;await Q.connect(),Q.resumeFromVersion(0);let X=Q.sendUserMessage([{type:"text",text:J.message}],J.agentMode),K=X23(Q,X,Y);try{return{messageId:(await K.promise).message.messageId}}finally{K.dispose(),Q.dispose()}}import{watch as K23}from"node:fs";import{mkdir as V23,readdir as z23,readFile as G23}from"node:fs/promises";import{createServer as F23}from"node:http";import Ja0 from"node:path";function tj4(J){return J instanceof Error?J.message:String(J)}function Wj(J,Z,Q){J.writeHead(Z,{"Content-Type":"application/json; charset=utf-8"}),J.end(JSON.stringify(Q))}function q23(J,Z){J.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),J.end(Z)}async function ej4(J,Z){let Q=Ja0.basename(Z),Y=Q.endsWith(".json")?Ja0.join(J,Q):Ja0.join(J,`${Q}.json`),X=await G23(Y,"utf-8");return JSON.parse(X)}async function W23(J){let Z=await z23(J,{withFileTypes:!0}).catch(()=>[]),Q=[];for(let Y of Z){if(!Y.isFile()||!Y.name.endsWith(".json"))continue;try{let X=await ej4(J,Y.name);Q.push({sessionID:X.sessionID,createdAt:X.createdAt,runtimeMode:X.runtimeMode,traceName:X.traceName,threadId:X.threadId,protocolEvents:X.protocolEvents.length,providerStates:X.providerStateEvents.length,adapterStates:X.adapterStateEvents.length,commands:X.commandEvents.length})}catch{}}return Q.sort((Y,X)=>X.createdAt-Y.createdAt)}function U23(){return`<!doctype html>
|
|
@@ -6070,7 +6068,7 @@ password=${K}
|
|
|
6070
6068
|
`).length})),z=crypto.randomUUID(),G=Q.userConfigDir?n1(Q.userConfigDir):void 0;if(V.length===0){X?.("SEND",{type:"executor_guidance_snapshot",snapshotId:z,fileCount:0,isLast:!0}),J.sendExecutorGuidanceSnapshot({snapshotId:z,files:[],isLast:!0,userConfigDir:G});return}let F=iR4(V,z,G);for(let q=0;q<F.length;q++){let W=F[q];if(!W)continue;let U=q===F.length-1;X?.("SEND",{type:"executor_guidance_snapshot",snapshotId:z,fileCount:W.length,isLast:U}),J.sendExecutorGuidanceSnapshot({snapshotId:z,files:W,isLast:U,userConfigDir:G})}}async function f$3(J,Z,Q){let Y=await Z.getSkills(),X=crypto.randomUUID(),K=20,V=Y.map((z)=>({name:z.name,description:z.description,baseDir:z.baseDir,frontmatter:z.frontmatter,files:z.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 z=0;z<V.length;z+=20){let G=V.slice(z,z+20),F=z+20>=V.length;Q?.("SEND",{type:"executor_skill_snapshot",snapshotId:X,skillCount:G.length,isLast:F}),J.sendExecutorSkillSnapshot({snapshotId:X,skills:G,isLast:F})}}YJ();N4();import Bi from"node:path";class Bj extends Error{code;constructor(J,Z){super(Z);this.code=J;this.name="ExecutorFileSystemPathError"}}function aR4(J,Z){let Q=V1.parse(J);if(Q.scheme!=="file")throw new Bj("INVALID_URI","Only file:// URIs are supported");if(!Q.path.startsWith("/"))throw new Bj("INVALID_URI","File URI path must be absolute");if(Q.path.split("/").some((G)=>G===".."))throw new Bj("ACCESS_DENIED","File URI resolves outside workspace root");let X=Bi.posix.normalize(Q.path).replace(/^\/+/u,"");if(X===".."||X.startsWith("../"))throw new Bj("ACCESS_DENIED","File URI resolves outside workspace root");let K=Bi.resolve(Z),V=X.length>0?Bi.resolve(K,X):K,z=Bi.relative(K,V);if(z.startsWith("..")||Bi.isAbsolute(z))throw new Bj("ACCESS_DENIED","File URI resolves outside workspace root");return V}async function MY0(J,Z){try{let Q=aR4(Z,J.workspaceRoot),Y=await J.fileSystem.readdir(V1.file(Q));return{ok:!0,entries:await Promise.all(Y.map(async(K)=>{let V=K.isDirectory?"directory":"file",z=V==="file"?await u$3(J.fileSystem,K.uri):void 0;return[Y1.basename(K.uri),V,z]}))}}catch(Q){return{ok:!1,error:oR4(Q,"read_directory")}}}async function u$3(J,Z){try{let Q=await J.getMtime(Z);if(!Number.isFinite(Q)||Q<0)return;return{mtimeMs:Q}}catch{return}}async function AY0(J,Z){try{let Q=aR4(Z,J.workspaceRoot),Y=await J.fileSystem.readBinaryFile(V1.file(Q));return{ok:!0,contentBase64:Buffer.from(Y).toString("base64")}}catch(Q){return{ok:!1,error:oR4(Q,"read_file")}}}function oR4(J,Z){if(J instanceof Bj)return{code:J.code,message:J.message};if(y8(J))return{code:"NOT_FOUND",message:"File or directory not found"};if(EY0(J,"EISDIR"))return{code:"IS_DIRECTORY",message:"Expected a file but found a directory"};if(EY0(J,"ENOTDIR"))return{code:Z==="read_directory"?"NOT_DIRECTORY":"INTERNAL_ERROR",message:Z==="read_directory"?"Expected a directory":nR4(J)};if(EY0(J,"EACCES")||EY0(J,"EPERM"))return{code:"ACCESS_DENIED",message:"Permission denied"};return{code:"INTERNAL_ERROR",message:nR4(J)}}function EY0(J,Z){if(!(J instanceof Error))return!1;return"code"in J&&J.code===Z}function nR4(J){if(J instanceof Error)return J.message;return String(J)}var Jv={baseDelayMs:1000,maxDelayMs:30000,maxAttempts:5};function jY0(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 b$3(){let J=()=>{return},Z=()=>{return};return{promise:new Promise((Y,X)=>{J=Y,Z=X}),resolve:J,reject:Z}}class Ni{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??Jv.baseDelayMs,this.maxDelayMs=J.maxDelayMs??Jv.maxDelayMs,this.maxAttempts=J.maxAttempts??Jv.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=b$3();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=jY0(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)}}d4();class wi{options;clientID;transport;sentApprovalRequests=new Set;discoveredGuidanceFileURIs=new Set;activeTools=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,args:Y}=J,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=this.options.executeBuiltinTool(Q,Y);if(K){let F=K.ok?{status:"done",result:K.content}:{status:"error",error:{message:K.content}};this.options.log.wsMessage("SEND",this.clientID,{type:"executor_tool_result",toolCallId:Z,run:F}),this.sendTransportMessage("executor_tool_result",()=>this.transport.sendExecutorToolResult(Z,F),{toolCallId:Z}),this.queueGitStatusSnapshot(Z);return}let V=new AbortController,z={subscription:{unsubscribe:()=>{}},abortController:V};this.activeTools.set(Z,z);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 q=!1,W=F.subscribe({next:(U)=>{if(V.signal.aborted)return;if(!q)q=!0,this.options.log.info(`${this.clientID} tool emitted first update`,{toolCallId:Z,toolName:Q,status:U.status,elapsedMs:Date.now()-X});let H=U.status==="in-progress"?U.progress??U.result:void 0;if(H!==void 0)this.options.log.wsMessage("SEND",this.clientID,{type:"tool_progress",toolCallId:Z,progress:H}),this.sendTransportMessage("tool_progress",()=>this.transport.sendToolProgress(Z,H),{toolCallId:Z});if(M9(U.status))this.sendToolResult(Z,U),G(),W.unsubscribe();if(U.status==="blocked-on-user")this.options.log.info(`${this.clientID} awaiting tool approval`,{toolCallId:Z,toolName:Q})},error:(U)=>{if(V.signal.aborted){G();return}this.options.log.error(`${this.clientID} tool execution failed: ${Q}`,U);let H={status:"error",error:{message:U instanceof Error?U.message:"Unknown error"}};this.options.log.wsMessage("SEND",this.clientID,{type:"executor_tool_result",toolCallId:Z,run:H}),this.sendTransportMessage("executor_tool_result",()=>this.transport.sendExecutorToolResult(Z,H),{toolCallId:Z}),this.queueGitStatusSnapshot(Z),G()}});z.subscription=W}catch(F){this.options.log.error(`${this.clientID} tool execution setup failed: ${Q}`,F);let q={status:"error",error:{message:F instanceof Error?F.message:String(F)}};this.options.log.wsMessage("SEND",this.clientID,{type:"executor_tool_result",toolCallId:Z,run:q}),this.sendTransportMessage("executor_tool_result",()=>this.transport.sendExecutorToolResult(Z,q),{toolCallId:Z}),this.queueGitStatusSnapshot(Z),G()}}handleToolRevocation(J){if(this.disposing)return;let{toolCallId:Z,reason:Q}=J;this.options.log.info(`${this.clientID} lease revoked: ${Z}`,{reason:Q});let Y=this.activeTools.get(Z);if(Y)Y.abortController.abort(),Y.subscription.unsubscribe(),this.activeTools.delete(Z);this.sentApprovalRequests.delete(Z),this.options.log.wsMessage("SEND",this.clientID,{type:"executor_revocation_ack",toolCallId:Z}),this.sendTransportMessage("executor_revocation_ack",()=>this.transport.sendRevocationAck(Z),{toolCallId:Z})}async handleRollbackRequest(J,Z,Q){if(this.disposing)return;try{if(Z.length>0)await Q(new Set(Z));this.options.log.wsMessage("SEND",this.clientID,{type:"executor_rollback_ack",editId:J,ok:!0}),this.sendTransportMessage("executor_rollback_ack",()=>this.transport.sendExecutorRollbackAck(J,!0),{editId:J}),this.queueGitStatusSnapshot()}catch(Y){let X=Y instanceof Error?Y.message:String(Y);this.options.log.error(`${this.clientID} rollback failed`,Y),this.options.log.wsMessage("SEND",this.clientID,{type:"executor_rollback_ack",editId:J,ok:!1,error:X}),this.sendTransportMessage("executor_rollback_ack",()=>this.transport.sendExecutorRollbackAck(J,!1,X),{editId:J})}}triggerGitStatus(J){this.queueGitStatusSnapshot(J)}dispose(){this.disposing=!0;for(let[,J]of this.activeTools)J.abortController.abort(),J.subscription.unsubscribe();this.activeTools.clear()}sendToolResult(J,Z){let Q=Date.now(),Y=this.toToolRun(Z),{run:X,files:K}=this.extractGuidanceFromRun(Y);if(K.length>0)this.sendGuidanceDiscovery(J,K);this.options.log.wsMessage("SEND",this.clientID,{type:"executor_tool_result",toolCallId:J,run:X});let V=this.sendTransportMessage("executor_tool_result",()=>this.transport.sendExecutorToolResult(J,X),{toolCallId:J});this.options.log.info(`${this.clientID} executor_tool_result send attempted`,{toolCallId:J,status:X.status,sent:V,guidanceFileCount:K.length,elapsedMs:Date.now()-Q}),this.sentApprovalRequests.delete(J),this.queueGitStatusSnapshot(J)}sendGuidanceDiscovery(J,Z){let Q=this.options.batchGuidanceFiles(Z,J);for(let Y=0;Y<Q.length;Y++){let X=Q[Y];if(!X)continue;let 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(NY0(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=hj4(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 _9)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}}}m0();function RY0(J){return{async createHandoffDraft(Z){let Q=await sR4(J,Z.signal);return rR4(Q,Z.parentThread.id,Z.goal,Z.images)},createHandoffThread:async(Z)=>{let Q=await sR4(J,Z.signal),Y=await rR4(Q,Z.parentThread.id,Z.goal,Z.images),X=await p$3(Q,Z,Y);if(await m$3(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){P.error("Failed to follow handoff thread",{error:K,sourceThreadID:Z.parentThread.id,targetThreadID:X.threadID})}return X.threadID}}}function h$3(J){let Z=new Headers({"Content-Type":"application/json"});if(J)Z.set("Authorization",`Bearer ${J}`);return Z}async function Wa0(J,Z,Q){return fetch(`${J.workerURL}${Z}`,{method:"POST",headers:h$3(J.apiKey),body:JSON.stringify(Q),signal:J.signal})}async function rR4(J,Z,Q,Y){let X=await Wa0(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 g$3(J,Z,Q,Y){let X=await Wa0(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 m$3(J,Z,Q,Y){let X=await Wa0(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 sR4(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??i7(Q.settings.url);return{apiKey:Y,workerURL:X,signal:Z}}async function p$3(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},z=Z.parentThread.env?.initial?.trees?.[0]?.repository?.url,G=await g$3(J,z,Y??void 0,V);return{http:J,threadID:G,prompt:Q.content,agentMode:Y??void 0}}bX();zc();TT();Hg0();d4();N4();O1();async function FH(J){let{toolName:Z,threadSnapshot:Q,dtwHandoffService:Y,dtwArtifactSyncService:X,configService:K,toolService:V,mcpService:z,skillService:G,fsTracker:F,toolUseID:q,discoveredGuidanceFileURIs:W}=J,U=V1.file(process.cwd()),H=q??SG(),D=await K.getLatest(),B,N;if(F)B=F.trackedFileSystem(H),N=F.tracker;else N=O$0(RS0,Q.id,async()=>{}),B=Dg0(n8,N,H);return{dir:U,tool:Z,thread:Q,dtwHandoffService:Y,dtwArtifactSyncService:X,trackedFiles:new QJ,toolUseID:H,todos:void 0,configService:K,toolService:V,mcpService:z,config:D,filesystem:B,fileChangeTracker:N,getAllTrackedChanges:async()=>N.getAllRecords(),threadEnvironment:{trees:[],platform:"cli"},handleThreadDelta:()=>Promise.resolve(),threadService:{observe:()=>k0.of(Q),get:()=>Promise.resolve(Q)},threadSyncService:void 0,getThreadEnvironment:()=>Promise.resolve({trees:[],platform:"cli"}),threadSummaryService:{summarizeThread:()=>Promise.resolve({summary:"CLI execution",prompt:"CLI execution",title:"CLI Tool"})},osFileSystem:n8,deleteThread:()=>Promise.resolve(),generateThreadTitle:()=>Promise.resolve({title:"CLI Tool Execution"}),fileChangeTrackerStorage:RS0,discoveredGuidanceFileURIs:W??new Set,skillService:G??{getSkills:()=>Promise.resolve([]),getTargetDir:()=>Promise.resolve("/tmp/skills"),listInstalled:()=>[],reload:()=>{}}}}function Ua0(){return new Date().toISOString()}var Ha0=process.stderr.isTTY;function d$3(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 Da0(J){if(J instanceof Error)return J.stack??J.message;if(typeof J==="string"){let Z=d$3(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 G8(J,Z,Q){if(P.info("[headless-dtw] websocket message",{direction:J,clientId:Z,...typeof Q==="object"&&Q!==null?Q:{message:Q}}),!Ha0)return;let Y=o0.dim(`[${Ua0()}]`),X=o0.magenta(`[${Z}]`),K=J==="SEND"?o0.green(">>>"):o0.yellow("<<<"),V=Da0(Q);process.stderr.write(`${Y} ${X} ${K} ${V}
|
|
6071
6069
|
`)}function N2(J,Z){if(Z)P.info(`[headless-dtw] ${J}`,Z);else P.info(`[headless-dtw] ${J}`);if(!Ha0)return;let Q=o0.dim(`[${Ua0()}]`),Y=o0.cyan("[INFO]"),X=Z?` ${Da0(Z)}`:"";process.stderr.write(`${Q} ${Y} ${J}${X}
|
|
6072
6070
|
`)}function Tz(J,Z){if(Z!==void 0)P.error(`[headless-dtw] ${J}`,{error:Z});else P.error(`[headless-dtw] ${J}`);if(!Ha0)return;let Q=o0.dim(`[${Ua0()}]`),Y=o0.red("[ERROR]"),X=Da0(Z);process.stderr.write(`${Q} ${Y} ${J} ${X}
|
|
6073
|
-
`)}function c$3(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 l$3(J,Z){let Q=new URL(J);if(!Q.pathname.endsWith("/"))Q.pathname+="/";return new URL(`threads/${Z}`,Q).toString()}class tR4{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??n8,X=new hV(Y);J.fsTracker=SS({fileChangeTrackerStorage:X},Y,Z)}async connectTransport(J,Z,Q){try{await J.connect()}catch(Y){let X=J.getConnectionInfo();if(X.state!=="reconnecting")throw Y;N2(`${Z} waiting for reconnect during ${Q}`,{connectionState:X.state,reconnectCauseType:X.reconnectCause?.type,reconnectCauseCode:X.reconnectCause?.code,reconnectCauseReason:X.reconnectCause?.reason})}}async recoverTransport(J,Z,Q,Y){let X=this.clients.get(J);if(!X||X.recoveringTransport||this.disposed)return;X.recoveringTransport=!0,N2(`${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"){N2(`${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();await this.connectTransport(X.transport,J,"recovery");let V=X.transport.getConnectionInfo(),z=X.transport.getThreadId();if(z)this.bindClientThread(X,z);if(V.state!=="connected"){N2(`${J} waiting for reconnect after transport recovery`,{connectionState:V.state});return}X.handshakeManager.ensureHandshake("retry")}catch(K){Tz(`${J} transport recovery failed`,K)}finally{X.recoveringTransport=!1}}async start(){N2("Starting Headless DTW Harness",{ampURL:this.options.ampURL,workerUrl:this.options.workerUrl??i7(this.options.ampURL),workspaceRoot:this.options.workspaceRoot,threadId:this.options.threadId??null}),this.toolSyncSubscription??=this.options.toolService.tools.subscribe({next:(J)=>{let Z=tk(J);for(let Q of this.clients.values())this.syncExecutorTools(Q,Z)}});try{let J=await this.createClient(this.options.threadId);N2("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 Tz("Failed to start harness",J),J}}logThreadURL(J){if(!J)return;let Z=l$3(this.options.ampURL,J);N2(`Thread URL: ${o0.blue.underline(Z)}`)}shutdown(J,Z){if(!this.disposed){if(J===0)N2(Z);else Tz(Z);this.dispose()}if(this.resolveRunLoop){let Q=this.resolveRunLoop;this.resolveRunLoop=null,Q(J);return}if(this.pendingExitCode===null||J>this.pendingExitCode)this.pendingExitCode=J}async invokeToolForClient(J,Z){let{toolService:Q,configService:Y,mcpService:X,skillService:K}=this.options;if(!Q||!Y||!X)throw Error("Tool service not available");let{toolName:V,toolCallId:z,args:G}=Z,F=typeof G==="object"&&G!==null?G:{},q=RY0({configService:Y,apiKey:this.options.apiKey}),W={upsertArtifact:(H,D)=>{let B=r8.safeParse(D);J.transport.sendExecutorArtifactUpsert(H,B.success?B.data:void 0)},deleteArtifact:(H)=>{J.transport.sendExecutorArtifactDelete(H)}},U=await FH({toolName:V,threadSnapshot:{id:J.threadId??p3(),created:Date.now(),v:0,messages:[]},dtwHandoffService:q,dtwArtifactSyncService:W,configService:Y,toolService:Q,mcpService:X,skillService:K,fsTracker:J.fsTracker??void 0,toolUseID:z,discoveredGuidanceFileURIs:J.toolRunner.discoveredGuidanceFileURIs});return Q.invokeTool(V,{args:F},U)}async createClient(J){let Z=`client-${++this.clientCounter}`,Q=`cli-headless-${crypto.randomUUID()}`,Y=this.options.workerUrl??i7(this.options.ampURL),X=this.options.useThreadActors?process.env.THREAD_ACTORS_URL??vk(this.options.ampURL):void 0;N2(`Creating client ${Z}`,{threadId:J,workerUrl:Y,useThreadActors:this.options.useThreadActors??!1,threadActorsUrl:X??"(not used)",options:this.options});let K;if(this.options.useThreadActors&&X){let U=kk({endpoint:`${X}/api/rivet`});K={baseURL:X,threadId:J,webSocketProvider:async()=>{return await U.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}}else K={baseURL:Y,apiKey:this.options.apiKey,threadId:J,WebSocketClass:WebSocket,maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000};let V=new Fq(K),z,G=new wi({clientID:Z,transport:V,executeBuiltinTool:()=>null,invokeTool:(U)=>this.invokeToolForClient(z,U),captureGitStatus:()=>BY0(this.options.workspaceRoot),batchGuidanceFiles:wY0,renderToolRunError:_m,onTransportSendFailure:(U,H,D,B)=>{this.recoverTransport(U,H,D,B)},log:{info:N2,error:Tz,wsMessage:G8}}),F=this.createHandshakeManager(()=>z,Z);z={id:Z,transport:V,threadId:J,hasLoggedPostBootstrapThreadURL:!1,executorClientId:Q,handshakeManager:F,toolRunner:G,fsTracker:null,settingsSubscription:null,lastSentSettingsJSON:"",recoveringTransport:!1,advertisedExecutorTools:[]},this.clients.set(Z,z),this.subscribeToTransportEvents(z),N2(`Connecting ${Z}...`),await this.connectTransport(V,Z,"startup");let q=V.getConnectionInfo(),W=V.getThreadId();if(W)this.bindClientThread(z,W);if(q.state==="connected")N2(`Connected ${Z}`,{threadId:W});else N2(`${Z} waiting for transport reconnect`,{connectionState:q.state});if(q.state==="connected")z.handshakeManager.ensureHandshake("connect");return z}async connectAsExecutor(J,Z){N2(`Connecting ${J.id} as executor...`,{trigger:Z});try{J.settingsSubscription?.unsubscribe(),J.settingsSubscription=null;let{advertisedTools:Q}=await LY0({transport:J.transport,executorClientID:J.executorClientId,workspaceRoot:this.options.workspaceRoot,threadId:J.threadId,resumeFromVersion:0,configService:this.options.configService,toolService:this.options.toolService,skillService:this.options.skillService,fileSystem:this.options.fileSystem,subscribeToThreadEvents:!1,executorType:"sandbox",previouslyAdvertisedTools:J.advertisedExecutorTools,initialToolDiscovery:this.options.initialToolDiscovery,logMessage:(Y,X)=>{G8(Y,J.id,X)}});if(J.advertisedExecutorTools=Q,!J.hasLoggedPostBootstrapThreadURL&&J.threadId)this.logThreadURL(J.threadId),J.hasLoggedPostBootstrapThreadURL=!0;this.setNotifyForwarder(J),this.bootstrapPluginsAfterExecutorConnect(J),this.startSettingsSync(J)}catch(Q){throw Tz(`${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{G8("SEND",J.id,{type:"executor_plugin_message",message:Y}),J.transport.sendPluginMessage(Y)}catch(X){Tz(`${J.id} failed to forward plugin notification`,X)}})}bootstrapPluginsAfterExecutorConnect(J){let Z=this.options.pluginService;if(!Z||this.pluginsBootstrapped)return;this.pluginsBootstrapped=!0,N2(`${J.id} reloading plugins after executor bootstrap`),Z.reload()}createHandshakeManager(J,Z){return new Ni({handshake:(Q)=>this.connectAsExecutor(J(),Q),onError:({error:Q,attempt:Y,delayMs:X})=>{Tz(`${Z} executor handshake failed`,{error:Q,attempt:Y,delayMs:X})},onExhausted:({error:Q,maxAttempts:Y})=>{this.shutdown(1,`${Z} executor handshake failed after ${Y} attempts: ${Q instanceof Error?Q.message:String(Q)}`)}})}startSettingsSync(J){if(J.settingsSubscription)return;J.settingsSubscription=this.options.configService.config.subscribe({next:(Z)=>{J.lastSentSettingsJSON=OY0(J.transport,Z,J.lastSentSettingsJSON)}})}syncExecutorTools(J,Z){let Q=J.transport.getConnectionInfo();if(Q.state!=="connected"||Q.role!=="executor")return;J.advertisedExecutorTools=Di({transport:J.transport,nextTools:Z,previouslyAdvertisedTools:J.advertisedExecutorTools,logMessage:(Y,X)=>{G8(Y,J.id,X)}})}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(Dj));for(let X of[...J.toolRunner.sentApprovalRequests])if(!Y.has(X))J.toolRunner.sentApprovalRequests.delete(X);for(let X of Q){let K=Dj(X);if(J.toolRunner.sentApprovalRequests.has(K))continue;let V=UY0(X);G8("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){Tz(`${J.id} received approval response without tool service`);return}N2(`${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)=>G8("RECV",Q,{eventType:"delta",...X})}),Z.agentStates().subscribe({next:(X)=>G8("RECV",Q,X)}),Z.messageEvents().subscribe({next:(X)=>G8("RECV",Q,X)}),Z.queuedMessages().subscribe({next:(X)=>G8("RECV",Q,X)}),Z.retryEvents().subscribe({next:(X)=>G8("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,c$3(X.reconnectCause));N2(`${Q} connection: ${X.state}`,V),J.handshakeManager.handleConnectionChange(X)}}),Z.errors().subscribe({next:(X)=>{G8("RECV",Q,X),Tz(`${Q} error`,X.message)}}),Z.errorEvents().subscribe({next:(X)=>G8("RECV",Q,X)}),Z.cancelledEvents().subscribe({next:(X)=>G8("RECV",Q,X)}),Z.toolLeases().subscribe({next:(X)=>{G8("RECV",Q,X),J.toolRunner.handleToolLease(X)}}),Z.toolLeaseRevoked().subscribe({next:(X)=>{G8("RECV",Q,X),J.toolRunner.handleToolRevocation(X)}}),Z.toolApprovalQueue().subscribe({next:(X)=>G8("RECV",Q,X)}),Z.executorToolApprovalResponses().subscribe({next:(X)=>{G8("RECV",Q,X),this.handleExecutorToolApprovalResponse(J,X)}}),Z.toolProgress().subscribe({next:(X)=>G8("RECV",Q,X)}),Z.executorErrors().subscribe({next:(X)=>{G8("RECV",Q,X),Tz(`${Q} executor error`,X.message)}}),Z.executorConnected().subscribe({next:(X)=>G8("RECV",Q,X)}),Z.executorRollbackRequests().subscribe({next:(X)=>{G8("RECV",Q,X),this.handleExecutorRollbackRequest(J,X)}}),Z.fileSystemReadDirectoryRequests().subscribe({next:(X)=>{G8("RECV",Q,X),this.handleExecutorFileSystemReadDirectoryRequest(J,X)}}),Z.fileSystemReadFileRequests().subscribe({next:(X)=>{G8("RECV",Q,X),this.handleExecutorFileSystemReadFileRequest(J,X)}}),Z.messageEdited().subscribe({next:(X)=>G8("RECV",Q,X)}),Z.editRejected().subscribe({next:(X)=>G8("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){Tz(`${Q} rollback failed: no file tracker`),G8("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 MY0({fileSystem:this.options.fileSystem??n8,workspaceRoot:this.options.workspaceRoot},Z.uri);G8("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 AY0({fileSystem:this.options.fileSystem??n8,workspaceRoot:this.options.workspaceRoot},Z.uri);G8("SEND",J.id,{type:"executor_filesystem_read_file_result",requestId:Z.requestId,...Q}),J.transport.sendExecutorFileSystemReadFileResult(Z.requestId,Q)}async runLoop(){if(N2("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){N2(`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())}dispose(){this.disposed=!0,this.toolSyncSubscription?.unsubscribe(),this.toolSyncSubscription=null,this.options.pluginPlatform?.setNotifyForwarder(null);for(let J of this.clients.values())J.toolRunner.dispose(),J.settingsSubscription?.unsubscribe(),J.handshakeManager.dispose(),J.transport.dispose();this.clients.clear()}}async function eR4(J){await new tR4(J).start()}import{stderr as _z,stdin as a$3}from"node:process";import{createInterface as o$3}from"node:readline";import{stdout as i$3}from"node:process";function n$3(){return!!(process.env.SSH_CLIENT||process.env.SSH_TTY||process.env.SSH_CONNECTION)}function IY0(){if(!i$3.isTTY)return!0;if(n$3())return!0;if(process.platform!=="darwin"&&process.platform!=="win32"&&!process.env.DISPLAY)return!0;return!1}var PY0=[],Ba0=null;function Na0(J){if(Ba0=J,J&&PY0.length>0){for(let Z of PY0)J(Z);PY0=[]}}function $I4(J){return async(Z,Q)=>{return new Promise((Y,X)=>{let K={serverName:J,authorizationUrl:Z,redirectUrl:Q,resolve:Y,reject:X};if(Ba0)Ba0(K);else PY0.push(K)})}}function JI4(){return async(J,Z)=>{return _z.write(`
|
|
6071
|
+
`)}function c$3(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 l$3(J,Z){let Q=new URL(J);if(!Q.pathname.endsWith("/"))Q.pathname+="/";return new URL(`threads/${Z}`,Q).toString()}class tR4{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??n8,X=new hV(Y);J.fsTracker=SS({fileChangeTrackerStorage:X},Y,Z)}async connectTransport(J,Z,Q){try{await J.connect()}catch(Y){let X=J.getConnectionInfo();if(X.state!=="reconnecting")throw Y;N2(`${Z} waiting for reconnect during ${Q}`,{connectionState:X.state,reconnectCauseType:X.reconnectCause?.type,reconnectCauseCode:X.reconnectCause?.code,reconnectCauseReason:X.reconnectCause?.reason})}}async recoverTransport(J,Z,Q,Y){let X=this.clients.get(J);if(!X||X.recoveringTransport||this.disposed)return;X.recoveringTransport=!0,N2(`${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"){N2(`${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();await this.connectTransport(X.transport,J,"recovery");let V=X.transport.getConnectionInfo(),z=X.transport.getThreadId();if(z)this.bindClientThread(X,z);if(V.state!=="connected"){N2(`${J} waiting for reconnect after transport recovery`,{connectionState:V.state});return}X.handshakeManager.ensureHandshake("retry")}catch(K){Tz(`${J} transport recovery failed`,K)}finally{X.recoveringTransport=!1}}async start(){N2("Starting Headless DTW Harness",{ampURL:this.options.ampURL,workerUrl:this.options.workerUrl??i7(this.options.ampURL),workspaceRoot:this.options.workspaceRoot,threadId:this.options.threadId??null}),this.toolSyncSubscription??=this.options.toolService.tools.subscribe({next:(J)=>{let Z=tk(J);for(let Q of this.clients.values())this.syncExecutorTools(Q,Z)}});try{let J=await this.createClient(this.options.threadId);N2("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 Tz("Failed to start harness",J),J}}logThreadURL(J){if(!J)return;let Z=l$3(this.options.ampURL,J);N2(`Thread URL: ${o0.blue.underline(Z)}`)}shutdown(J,Z){if(!this.disposed){if(J===0)N2(Z);else Tz(Z);this.dispose()}if(this.resolveRunLoop){let Q=this.resolveRunLoop;this.resolveRunLoop=null,Q(J);return}if(this.pendingExitCode===null||J>this.pendingExitCode)this.pendingExitCode=J}async invokeToolForClient(J,Z){let{toolService:Q,configService:Y,mcpService:X,skillService:K}=this.options;if(!Q||!Y||!X)throw Error("Tool service not available");let{toolName:V,toolCallId:z,args:G}=Z,F=typeof G==="object"&&G!==null?G:{},q=RY0({configService:Y,apiKey:this.options.apiKey}),W={upsertArtifact:(H,D)=>{let B=r8.safeParse(D);J.transport.sendExecutorArtifactUpsert(H,B.success?B.data:void 0)},deleteArtifact:(H)=>{J.transport.sendExecutorArtifactDelete(H)}},U=await FH({toolName:V,threadSnapshot:{id:J.threadId??p3(),created:Date.now(),v:0,messages:[]},dtwHandoffService:q,dtwArtifactSyncService:W,configService:Y,toolService:Q,mcpService:X,skillService:K,fsTracker:J.fsTracker??void 0,toolUseID:z,discoveredGuidanceFileURIs:J.toolRunner.discoveredGuidanceFileURIs});return Q.invokeTool(V,{args:F},U)}async createClient(J){let Z=`client-${++this.clientCounter}`,Q=`cli-headless-${crypto.randomUUID()}`,Y=this.options.workerUrl??i7(this.options.ampURL),X=this.options.useThreadActors?process.env.THREAD_ACTORS_URL??vk(this.options.ampURL):void 0;N2(`Creating client ${Z}`,{threadId:J,workerUrl:Y,useThreadActors:this.options.useThreadActors??!1,threadActorsUrl:X??"(not used)",options:this.options});let K;if(this.options.useThreadActors&&X){let U=kk({endpoint:X});K={baseURL:X,threadId:J,webSocketProvider:async()=>{return await U.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}}else K={baseURL:Y,apiKey:this.options.apiKey,threadId:J,WebSocketClass:WebSocket,maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000};let V=new Fq(K),z,G=new wi({clientID:Z,transport:V,executeBuiltinTool:()=>null,invokeTool:(U)=>this.invokeToolForClient(z,U),captureGitStatus:()=>BY0(this.options.workspaceRoot),batchGuidanceFiles:wY0,renderToolRunError:_m,onTransportSendFailure:(U,H,D,B)=>{this.recoverTransport(U,H,D,B)},log:{info:N2,error:Tz,wsMessage:G8}}),F=this.createHandshakeManager(()=>z,Z);z={id:Z,transport:V,threadId:J,hasLoggedPostBootstrapThreadURL:!1,executorClientId:Q,handshakeManager:F,toolRunner:G,fsTracker:null,settingsSubscription:null,lastSentSettingsJSON:"",recoveringTransport:!1,advertisedExecutorTools:[]},this.clients.set(Z,z),this.subscribeToTransportEvents(z),N2(`Connecting ${Z}...`),await this.connectTransport(V,Z,"startup");let q=V.getConnectionInfo(),W=V.getThreadId();if(W)this.bindClientThread(z,W);if(q.state==="connected")N2(`Connected ${Z}`,{threadId:W});else N2(`${Z} waiting for transport reconnect`,{connectionState:q.state});if(q.state==="connected")z.handshakeManager.ensureHandshake("connect");return z}async connectAsExecutor(J,Z){N2(`Connecting ${J.id} as executor...`,{trigger:Z});try{J.settingsSubscription?.unsubscribe(),J.settingsSubscription=null;let{advertisedTools:Q}=await LY0({transport:J.transport,executorClientID:J.executorClientId,workspaceRoot:this.options.workspaceRoot,threadId:J.threadId,resumeFromVersion:0,configService:this.options.configService,toolService:this.options.toolService,skillService:this.options.skillService,fileSystem:this.options.fileSystem,subscribeToThreadEvents:!1,executorType:"sandbox",previouslyAdvertisedTools:J.advertisedExecutorTools,initialToolDiscovery:this.options.initialToolDiscovery,logMessage:(Y,X)=>{G8(Y,J.id,X)}});if(J.advertisedExecutorTools=Q,!J.hasLoggedPostBootstrapThreadURL&&J.threadId)this.logThreadURL(J.threadId),J.hasLoggedPostBootstrapThreadURL=!0;this.setNotifyForwarder(J),this.bootstrapPluginsAfterExecutorConnect(J),this.startSettingsSync(J)}catch(Q){throw Tz(`${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{G8("SEND",J.id,{type:"executor_plugin_message",message:Y}),J.transport.sendPluginMessage(Y)}catch(X){Tz(`${J.id} failed to forward plugin notification`,X)}})}bootstrapPluginsAfterExecutorConnect(J){let Z=this.options.pluginService;if(!Z||this.pluginsBootstrapped)return;this.pluginsBootstrapped=!0,N2(`${J.id} reloading plugins after executor bootstrap`),Z.reload()}createHandshakeManager(J,Z){return new Ni({handshake:(Q)=>this.connectAsExecutor(J(),Q),onError:({error:Q,attempt:Y,delayMs:X})=>{Tz(`${Z} executor handshake failed`,{error:Q,attempt:Y,delayMs:X})},onExhausted:({error:Q,maxAttempts:Y})=>{this.shutdown(1,`${Z} executor handshake failed after ${Y} attempts: ${Q instanceof Error?Q.message:String(Q)}`)}})}startSettingsSync(J){if(J.settingsSubscription)return;J.settingsSubscription=this.options.configService.config.subscribe({next:(Z)=>{J.lastSentSettingsJSON=OY0(J.transport,Z,J.lastSentSettingsJSON)}})}syncExecutorTools(J,Z){let Q=J.transport.getConnectionInfo();if(Q.state!=="connected"||Q.role!=="executor")return;J.advertisedExecutorTools=Di({transport:J.transport,nextTools:Z,previouslyAdvertisedTools:J.advertisedExecutorTools,logMessage:(Y,X)=>{G8(Y,J.id,X)}})}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(Dj));for(let X of[...J.toolRunner.sentApprovalRequests])if(!Y.has(X))J.toolRunner.sentApprovalRequests.delete(X);for(let X of Q){let K=Dj(X);if(J.toolRunner.sentApprovalRequests.has(K))continue;let V=UY0(X);G8("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){Tz(`${J.id} received approval response without tool service`);return}N2(`${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)=>G8("RECV",Q,{eventType:"delta",...X})}),Z.agentStates().subscribe({next:(X)=>G8("RECV",Q,X)}),Z.messageEvents().subscribe({next:(X)=>G8("RECV",Q,X)}),Z.queuedMessages().subscribe({next:(X)=>G8("RECV",Q,X)}),Z.retryEvents().subscribe({next:(X)=>G8("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,c$3(X.reconnectCause));N2(`${Q} connection: ${X.state}`,V),J.handshakeManager.handleConnectionChange(X)}}),Z.errors().subscribe({next:(X)=>{G8("RECV",Q,X),Tz(`${Q} error`,X.message)}}),Z.errorEvents().subscribe({next:(X)=>G8("RECV",Q,X)}),Z.cancelledEvents().subscribe({next:(X)=>G8("RECV",Q,X)}),Z.toolLeases().subscribe({next:(X)=>{G8("RECV",Q,X),J.toolRunner.handleToolLease(X)}}),Z.toolLeaseRevoked().subscribe({next:(X)=>{G8("RECV",Q,X),J.toolRunner.handleToolRevocation(X)}}),Z.toolApprovalQueue().subscribe({next:(X)=>G8("RECV",Q,X)}),Z.executorToolApprovalResponses().subscribe({next:(X)=>{G8("RECV",Q,X),this.handleExecutorToolApprovalResponse(J,X)}}),Z.toolProgress().subscribe({next:(X)=>G8("RECV",Q,X)}),Z.executorErrors().subscribe({next:(X)=>{G8("RECV",Q,X),Tz(`${Q} executor error`,X.message)}}),Z.executorConnected().subscribe({next:(X)=>G8("RECV",Q,X)}),Z.executorRollbackRequests().subscribe({next:(X)=>{G8("RECV",Q,X),this.handleExecutorRollbackRequest(J,X)}}),Z.fileSystemReadDirectoryRequests().subscribe({next:(X)=>{G8("RECV",Q,X),this.handleExecutorFileSystemReadDirectoryRequest(J,X)}}),Z.fileSystemReadFileRequests().subscribe({next:(X)=>{G8("RECV",Q,X),this.handleExecutorFileSystemReadFileRequest(J,X)}}),Z.messageEdited().subscribe({next:(X)=>G8("RECV",Q,X)}),Z.editRejected().subscribe({next:(X)=>G8("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){Tz(`${Q} rollback failed: no file tracker`),G8("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 MY0({fileSystem:this.options.fileSystem??n8,workspaceRoot:this.options.workspaceRoot},Z.uri);G8("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 AY0({fileSystem:this.options.fileSystem??n8,workspaceRoot:this.options.workspaceRoot},Z.uri);G8("SEND",J.id,{type:"executor_filesystem_read_file_result",requestId:Z.requestId,...Q}),J.transport.sendExecutorFileSystemReadFileResult(Z.requestId,Q)}async runLoop(){if(N2("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){N2(`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())}dispose(){this.disposed=!0,this.toolSyncSubscription?.unsubscribe(),this.toolSyncSubscription=null,this.options.pluginPlatform?.setNotifyForwarder(null);for(let J of this.clients.values())J.toolRunner.dispose(),J.settingsSubscription?.unsubscribe(),J.handshakeManager.dispose(),J.transport.dispose();this.clients.clear()}}async function eR4(J){await new tR4(J).start()}import{stderr as _z,stdin as a$3}from"node:process";import{createInterface as o$3}from"node:readline";import{stdout as i$3}from"node:process";function n$3(){return!!(process.env.SSH_CLIENT||process.env.SSH_TTY||process.env.SSH_CONNECTION)}function IY0(){if(!i$3.isTTY)return!0;if(n$3())return!0;if(process.platform!=="darwin"&&process.platform!=="win32"&&!process.env.DISPLAY)return!0;return!1}var PY0=[],Ba0=null;function Na0(J){if(Ba0=J,J&&PY0.length>0){for(let Z of PY0)J(Z);PY0=[]}}function $I4(J){return async(Z,Q)=>{return new Promise((Y,X)=>{let K={serverName:J,authorizationUrl:Z,redirectUrl:Q,resolve:Y,reject:X};if(Ba0)Ba0(K);else PY0.push(K)})}}function JI4(){return async(J,Z)=>{return _z.write(`
|
|
6074
6072
|
`),_z.write(o0.yellow.bold(`OAuth Authorization Required
|
|
6075
6073
|
`)),_z.write(o0.dim("─".repeat(60)+`
|
|
6076
6074
|
`)),_z.write(`
|
|
@@ -6198,11 +6196,11 @@ ${H}`))}},error:(U)=>{if(!W)W=!0,z(Error(`Failed to spawn brew: ${U.message}`))}
|
|
|
6198
6196
|
${H}`;if(X==="pnpm"&&H.includes("Unable to find the global bin directory"))D+=`
|
|
6199
6197
|
|
|
6200
6198
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
6201
|
-
npm install -g @sourcegraph/amp`;z(Error(D))}},error:(U)=>{if(!q)q=!0,z(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!q)q=!0,V()}})})}m0();m0();hM();async function fY0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let z=await fetch(X,{signal:K.signal});if(!z.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=await z.json(),F=G.version??G["dist-tags"]?.latest;if(!F)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=NP4(J,F),W=q<0,U,H;if(G.time){let D=G.time[J],B=G.time[F],N=Date.now();if(D)U=Math.floor((N-new Date(D).getTime())/3600000);if(B)H=Math.floor((N-new Date(B).getTime())/3600000)}return P.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:q,hasUpdate:W,currentVersionAge:U,latestVersionAge:H}),{hasUpdate:W,latestVersion:F,currentVersion:J,currentVersionAge:U,latestVersionAge:H,source:"npm"}}catch(z){return P.debug("Error checking npm version",{error:z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var pZ3="https://static.ampcode.com/cli/cli-version.txt";async function uY0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${pZ3}?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=NP4(J,X),V=K<0;return P.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return P.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var dZ3=604800000;function BP4(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>dZ3)return{ageMs:Q};return null}function NP4(J,Z){let Q=(V)=>{let[z,G]=V.split("-");return{parts:z?.split(".").map(Number)||[],label:G}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let z=Y.parts[V]||0,G=X.parts[V]||0;if(z<G)return-1;if(z>G)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function ma0(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?EF(Q):void 0;return{sha:Y,age:X}}catch{return null}}O1();function pa0(J,Z,Q={}){let Y=new Y4,X=Y.pipe(c6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new CG().scoped("update"),V=Q.startDelayMs??0;if(V>0)await $F(V);let z=X.subscribe({next:(G)=>{K.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){K.debug("using fake update status for testing",{status:G}),await $F(500),Y.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let F=await Z.get("updates.mode");if(F==="disabled"){K.debug("checking disabled");return}let q=await xY0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:F,packageManager:q,isBinaryDistribution:W});let U=W?await uY0(J):await fY0(J,Oj());if(!(U.latestVersion&&U.hasUpdate)){K.debug("no update available");return}let H=()=>{if(U.currentVersionAge!==void 0&&U.latestVersionAge!==void 0){let D=U.currentVersionAge-U.latestVersionAge,B=0.5;if(Math.abs(D)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:U.currentVersionAge,latestVersionAge:U.latestVersionAge,ageDifferenceHours:D}),!0}return!1};if(!F)F=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:F});if(q==="brew"){if(!H())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==xa0()){if(K.debug("non-standard binary path, showing warning"),!H())Y.next("update-available-unrecognized-path");return}if(F==="warn"){if(!H())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!H())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"),!H())Y.next("update-available");return}try{await Ti(U.latestVersion,q);let D=await Nw(U.latestVersion),B={from:U.currentVersion,to:U.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(G){K.debug("check failed",{error:G})}finally{await $F(5000),Y.next("hidden"),z.unsubscribe(),Y.complete()}}),{state:X}}hM();import{stderr as Uq}from"node:process";function wP4(J){let Z=new fN().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 _a0(Y.force||!1,Y.verbose||!1,"0.0.
|
|
6199
|
+
npm install -g @sourcegraph/amp`;z(Error(D))}},error:(U)=>{if(!q)q=!0,z(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!q)q=!0,V()}})})}m0();m0();hM();async function fY0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let z=await fetch(X,{signal:K.signal});if(!z.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=await z.json(),F=G.version??G["dist-tags"]?.latest;if(!F)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=NP4(J,F),W=q<0,U,H;if(G.time){let D=G.time[J],B=G.time[F],N=Date.now();if(D)U=Math.floor((N-new Date(D).getTime())/3600000);if(B)H=Math.floor((N-new Date(B).getTime())/3600000)}return P.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:q,hasUpdate:W,currentVersionAge:U,latestVersionAge:H}),{hasUpdate:W,latestVersion:F,currentVersion:J,currentVersionAge:U,latestVersionAge:H,source:"npm"}}catch(z){return P.debug("Error checking npm version",{error:z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var pZ3="https://static.ampcode.com/cli/cli-version.txt";async function uY0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${pZ3}?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=NP4(J,X),V=K<0;return P.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return P.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var dZ3=604800000;function BP4(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>dZ3)return{ageMs:Q};return null}function NP4(J,Z){let Q=(V)=>{let[z,G]=V.split("-");return{parts:z?.split(".").map(Number)||[],label:G}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let z=Y.parts[V]||0,G=X.parts[V]||0;if(z<G)return-1;if(z>G)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function ma0(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?EF(Q):void 0;return{sha:Y,age:X}}catch{return null}}O1();function pa0(J,Z,Q={}){let Y=new Y4,X=Y.pipe(c6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new CG().scoped("update"),V=Q.startDelayMs??0;if(V>0)await $F(V);let z=X.subscribe({next:(G)=>{K.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){K.debug("using fake update status for testing",{status:G}),await $F(500),Y.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let F=await Z.get("updates.mode");if(F==="disabled"){K.debug("checking disabled");return}let q=await xY0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:F,packageManager:q,isBinaryDistribution:W});let U=W?await uY0(J):await fY0(J,Oj());if(!(U.latestVersion&&U.hasUpdate)){K.debug("no update available");return}let H=()=>{if(U.currentVersionAge!==void 0&&U.latestVersionAge!==void 0){let D=U.currentVersionAge-U.latestVersionAge,B=0.5;if(Math.abs(D)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:U.currentVersionAge,latestVersionAge:U.latestVersionAge,ageDifferenceHours:D}),!0}return!1};if(!F)F=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:F});if(q==="brew"){if(!H())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==xa0()){if(K.debug("non-standard binary path, showing warning"),!H())Y.next("update-available-unrecognized-path");return}if(F==="warn"){if(!H())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!H())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"),!H())Y.next("update-available");return}try{await Ti(U.latestVersion,q);let D=await Nw(U.latestVersion),B={from:U.currentVersion,to:U.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(G){K.debug("check failed",{error:G})}finally{await $F(5000),Y.next("hidden"),z.unsubscribe(),Y.complete()}}),{state:X}}hM();import{stderr as Uq}from"node:process";function wP4(J){let Z=new fN().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 _a0(Y.force||!1,Y.verbose||!1,"0.0.1774866438-g7cb400"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new fN("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 cZ3(Y.targetVersion)});J.addCommand(Q)}async function cZ3(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")Uq.write(o0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
6202
6200
|
|
|
6203
6201
|
`));try{if(!J){Uq.write(o0.blue(`Checking for updates...
|
|
6204
|
-
`));let{hasUpdate:Y,latestVersion:X}=ka0()?await uY0("0.0.
|
|
6205
|
-
`));let z=await Nw("0.0.
|
|
6202
|
+
`));let{hasUpdate:Y,latestVersion:X}=ka0()?await uY0("0.0.1774866438-g7cb400"):await fY0("0.0.1774866438-g7cb400",Oj());if(!Y){let K=ma0("0.0.1774866438-g7cb400"),V=K?.age?`released ${K.age} ago`:`built ${EF(new Date("2026-03-30T10:31:14.209Z"))} ago`;Uq.write(o0.green(`✓ Amp is already up to date on version ${"0.0.1774866438-g7cb400"} (${V})
|
|
6203
|
+
`));let z=await Nw("0.0.1774866438-g7cb400");if(z.warning)Uq.write(`
|
|
6206
6204
|
`+o0.yellow(z.warning)+`
|
|
6207
6205
|
`);process.exit(0)}if(!X)Uq.write(o0.yellow("[WARN] could not find latest version")),process.exit(0);J=X}Uq.write(o0.blue(`Updating to version ${J}...
|
|
6208
6206
|
`)),await Ti(J,void 0,(Y)=>{Uq.write(o0.dim(`Running: ${Y}
|
|
@@ -6210,7 +6208,7 @@ Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm in
|
|
|
6210
6208
|
`));let Q=await Nw(J);if(Q.warning)Uq.write(`
|
|
6211
6209
|
`+o0.yellow(Q.warning)+`
|
|
6212
6210
|
`);process.exit(0)}catch(Z){let Q=Z instanceof Error?Z.message:String(Z);Uq.write(o0.red.bold("Error: ")+Q+`
|
|
6213
|
-
`),process.exit(1)}}import{execFile as iY3}from"node:child_process";import{lstat as PC4,mkdir as nY3,readFile as aY3,rm as No0,writeFile as oY3}from"node:fs/promises";import aY from"node:path";import u$ from"node:process";import{createInterface as rY3}from"node:readline";import{promisify as sY3}from"node:util";class V3{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 z=this.neighborMap[V].filter((G)=>this.state[G]).length;if(K)return z===2||z===3;return z===3||z===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)}}m0();_7();N4();m0();O$();O1();import{mkdir as lZ3,writeFile as iZ3}from"node:fs/promises";import nZ3 from"node:path";function aZ3(J){let Z=J?.trim();return Z&&Z.length>0?Z:void 0}function oZ3(J){let Z=J.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48);return Z.length>0?Z:"trace"}function rZ3(J,Z){let Q=new Date(J).toISOString().replace(/[:.]/g,"-");return`${Z?`dtw-trace-${oZ3(Z)}`:"dtw-trace"}-${Q}-${crypto.randomUUID().slice(0,8)}`}function da0(J){let Z=JSON.stringify(J);if(Z===void 0)return null;return JSON.parse(Z)}class ca0{options;traceFilePath;session;constructor(J){this.options=J;let Z=Date.now(),Q=aZ3(J.traceName),Y=rZ3(Z,Q);this.traceFilePath=nZ3.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:da0(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:da0(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:da0(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 lZ3(this.options.traceDir,{recursive:!0});let J=JSON.stringify(this.session,null,2);return await iZ3(this.traceFilePath,J,"utf-8"),this.traceFilePath}}function LP4(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 hY0(J){return typeof J==="object"&&J!==null}function la0(J){if(!Array.isArray(J))return;return J}function OP4(J){let Z=J.trim();if(Z.length===0)return;try{let Q=JSON.parse(Z);return la0(Q)}catch{return}}function bY0(J){if(typeof J==="string")return J;if(!hY0(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=bY0(J.result);if(Z!==void 0)return Z}if("error"in J){let Z=bY0(J.error);if(Z!==void 0)return Z}if("value"in J)return bY0(J.value);return}function sZ3(J){return J.type==="text"}function EP4(J){if(J===void 0)return;let Z;try{Z=zi(J,"snapshot")}catch{return}if(Z.type==="snapshot")return bY0(Z.value);let Q=(Z.blocks??[]).filter(sZ3).map((Y)=>Y.text).join("");return Q.length>0?Q:void 0}var tZ3=["queued","blocked-on-user","in-progress","rejected-by-user","cancellation-requested","cancelled","done","error"];function eZ3(J){return typeof J==="string"&&tZ3.includes(J)}function MP4(J){if(J===void 0)return;let Z;try{Z=zi(J,"snapshot")}catch{return}if(Z.type!=="snapshot")return;let Q=Z.value;if(!hY0(Q))return;if(!("status"in Q)||!eZ3(Q.status))return;return Q.status}function AP4(J){let Z=la0(J);if(Z!==void 0)return Z;if(!hY0(J)||typeof J.type!=="string")return;if(J.type==="snapshot"){let Y=J.value,X=la0(Y);if(X!==void 0)return X;if(typeof Y==="string")return OP4(Y);return}if(J.type!=="delta"||!Array.isArray(J.blocks))return;let Q=J.blocks.map((Y)=>{if(!hY0(Y)||Y.type!=="text"||typeof Y.text!=="string")return"";return Y.text}).join("");return OP4(Q)}var $Q3=3000,JQ3=30000,ZQ3=5;function PP4(J){let Z=[],Q=0;for(let X of J.messages){if(X.role==="user"){Z.push({messageId:zq(),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:zq(),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:zq(),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:zq(),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 QQ3(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 UH(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 X8("/api/durable-thread-workers",na0({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 YQ3(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??PP4(J),z=Y.workerURL??i7(Y.ampURL),G=await fetch(`${z}/threads/${J.id}/import`,{method:"POST",headers:{Authorization:`Bearer ${K}`,"Content-Type":"application/json"},body:JSON.stringify({thread:V})});if(G.status===409)return"already-imported";if(!G.ok)throw Error(`Failed to import thread into DTW: ${G.status} ${await G.text()}`);if((await G.json()).ok!==!0)throw Error("Failed to import thread into DTW: import endpoint returned an invalid response");return"imported"}async function XQ3(J,Z,Q){let Y=await X8(`/api/durable-thread-workers/${J}`,na0({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 vi(J,Z,Q){let Y=await X8(`/api/threads/${J}`,na0(void 0,Q),Z);if(!Y.ok)throw Error(`Failed to fetch thread snapshot: ${Y.status} ${await Y.text()}`);return await Y.json()}function na0(J,Z){if(!Z)return J;return{...J,headers:{...J?.headers,Authorization:`Bearer ${Z}`}}}function ki(J){let Z=s6.safeParse(J.dtwMessageID);if(Z.success)return Z.data;let Q=s6.safeParse(`${J.messageId}`);return Q.success?Q.data:null}function KQ3(J){let Z=[],Q=new Set;for(let[Y,X]of J.messages.entries()){let K=ki(X);if(K)Q.add(K);Z.push({...X,messageId:Y})}return{messages:Z,processedIds:Q}}function VQ3(J){let Z=new Set;for(let Q of J){let Y=ki(Q);if(Y)Z.add(Y)}return Z}function _i(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 zQ3(J,Z,Q,Y){if(!J||Z.length===0)return null;return{role:"assistant",content:Z,state:{type:"streaming"},messageId:Q,parentToolUseId:Y}}function GQ3(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=_i(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=_i([],J.blocks??[]),Z.streamingParentToolCallId=Q;else if(J.blocks)Z.streamingBlocks=_i(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=_i([],J.blocks??[]),Z.streamingParentToolCallId=Q;else if(J.blocks)Z.streamingBlocks=_i(Z.streamingBlocks,J.blocks)}}function FQ3(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 qQ3(J){if(typeof J!=="number"||!Number.isFinite(J))return 0;return Math.max(0,Math.trunc(J))}function ia0(J){if(!J||J.length===0)return;return J.map((Z)=>({uri:Z.uri,lineCount:qQ3(Z.lineCount),...typeof Z.content==="string"?{content:Z.content}:{}}))}function WQ3(J,Z,Q){let Y=J.message.messageId;if(Q.has(Y)){let K=Z.findIndex((z)=>ki(z)===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 z={...V,content:J.message.content,agentMode:J.message.agentMode,userState:J.message.userState,discoveredGuidanceFiles:ia0(J.message.discoveredGuidanceFiles),parentToolUseId:J.parentToolUseId},G=[...Z];return G[K]=z,G}if(V.role==="assistant"&&J.message.role==="assistant"){let z={...V,content:J.message.content,usage:J.message.usage,state:{type:"complete",stopReason:"end_turn"},parentToolUseId:J.parentToolUseId},G=[...Z];return G[K]=z,G}if(V.role==="info"&&J.message.role==="info"){let z={...V,content:J.message.content,parentToolUseId:J.parentToolUseId},G=[...Z];return G[K]=z,G}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:ia0(J.message.discoveredGuidanceFiles),messageId:X,dtwMessageID:Y,parentToolUseId:J.parentToolUseId}]}function UQ3(J,Z){let Q=Z.findIndex((z)=>ki(z)===J.messageId),Y=Z.findIndex((z)=>ki(z)===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 jP4(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 RP4(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:ia0(Z.discoveredGuidanceFiles),meta:Z.createdAt?{sentAt:Date.parse(Z.createdAt)}:void 0,messageId:-1,dtwMessageID:Z.messageId}}}function HQ3(J){if(J.type==="queued_messages")return{type:"queued_messages",messages:J.messages.map((Z)=>RP4(Z))};if(J.type==="queued_message_added")return{type:"queued_message_added",message:RP4(J.message)};return{type:"queued_message_removed",queuedMessageId:J.queuedMessageId}}function DQ3(J,Z){let Q=HQ3(Z);return en0(Si(J)??[],Q,{dedupeAdded:!0,getQueuedMessageId:(Y)=>Y.id})}async function BQ3(J,Z){if(J.useThreadActors){let Q=vk(J.ampURL),Y=kk({endpoint:`${Q}/api/rivet`});return{baseURL:Q,threadId:Z.threadId,wsToken:Z.wsToken,wsTokenProvider:async()=>UH(Z.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL}),webSocketProvider:async()=>{let X=await UH(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}}return{baseURL:J.workerUrl??i7(J.ampURL),threadId:Z.threadId,wsToken:Z.wsToken,wsTokenProvider:async()=>UH(Z.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL}),WebSocketClass:WebSocket,maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000}}function IP4(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 gY0{threadSubject;agentLoopStateSubject=new K4("idle");executorReadySubject=new K4(!1);editErrorSubject=new Y4;deltaState={streamingMessageId:null,streamingBlocks:[],completedMessages:[]};toolProgressByToolUseIDSubject=new K4(new Map);toolProgressSubject=new Y4;subscriptions=[];threadResumeCursor;messages;queuedMessages;relationships;threadTitle;processedIds;agentLoopState="idle";toolProgressByToolUseID=new Map;compactionStateSubject=new K4("idle");compactionState="idle";transportSubscribed=!1;connectPromise=null;ensureConnectedPromise=null;lastConnectionState="disconnected";lastConnectionInfo=null;executorHandshakeManager=null;pendingClientWritesByMessageID=new Map;connectedTransportGeneration=0;pendingClientWriteReplayGeneration=null;transport;threadId;constructor(J,Z,Q,Y){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=cj4(Y),this.threadSubject=new K4(J)}static async create(J){let Z=await UH(J.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL,executorType:J.executorType,usesThreadActors:J.useThreadActors}),Q=await vi(Z.threadId,J.configService,J.apiKey);if(!Z.usesDtw){if(J.useThreadActors)throw Error("TODO: Importing threads into rivet thread actors isn't supported");J.onLegacyImportStateChange?.("importing");try{let G=PP4(Q),F=await YQ3(Q,J.configService,J.apiKey,{ampURL:J.ampURL,workerURL:J.workerUrl,payload:G});if(await XQ3(Z.threadId,J.configService,J.apiKey),F==="imported")Q=QQ3(Q,G)}finally{J.onLegacyImportStateChange?.("idle")}}let{messages:Y,processedIds:X}=KQ3(Q),K={...Q,id:Z.threadId,messages:Y,queuedMessages:Si(Q.queuedMessages),relationships:Q.relationships?[...Q.relationships]:void 0},V=new Fq(await BQ3(J,Z)),z=new gY0(K,V,X,Q.v);try{if(J.connectOnCreate??!0)await z.connect();return z}catch(G){throw z.dispose(),G}}threadChanges(){return this.threadSubject}agentLoopStateChanges(){return this.agentLoopStateSubject}executorReadyChanges(){return this.executorReadySubject}toolProgressByToolUseIDChanges(){return this.toolProgressByToolUseIDSubject}toolProgressChanges(){return this.toolProgressSubject}editErrors(){return this.editErrorSubject}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}willQueueNextUserMessage(){return this.agentLoopState!=="idle"||this.deltaState.streamingMessageId!==null}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)}configureExecutorHandshake(J){this.executorHandshakeManager?.dispose(),this.executorHandshakeManager=new Ni(J);let Z=this.transport.getConnectionInfo();this.executorHandshakeManager.handleConnectionChange(Z),this.executorReadySubject.next(Z.state==="connected"&&Z.role==="executor")}ensureExecutorReady(J){if(!this.executorHandshakeManager)return Promise.reject(Error("Executor handshake manager is not configured"));return this.executorHandshakeManager.ensureReady(J)}disconnectTransport(){this.transport.disconnect()}async ensureConnectedForAction(J){if(this.transport.getConnectionInfo().state==="reconnecting"){let Q=J==="client-write"?"client write action":"executor action";P.info(`Forcing transport reconnect before ${Q}`),this.transport.disconnect()}await this.ensureConnected()}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)}ackToolLease(...J){this.transport.ackToolLease(...J)}sendToolProgress(...J){this.transport.sendToolProgress(...J)}sendExecutorToolResult(...J){this.transport.sendExecutorToolResult(...J)}sendRevocationAck(...J){this.transport.sendRevocationAck(...J)}sendExecutorRollbackAck(...J){this.transport.sendExecutorRollbackAck(...J)}sendExecutorGuidanceDiscovery(...J){this.transport.sendExecutorGuidanceDiscovery(...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()}toolLeases(){return this.transport.toolLeases()}toolLeaseRevoked(){return this.transport.toolLeaseRevoked()}executorRollbackRequests(){return this.transport.executorRollbackRequests()}fileSystemReadDirectoryRequests(){return this.transport.fileSystemReadDirectoryRequests()}fileSystemReadFileRequests(){return this.transport.fileSystemReadFileRequests()}executorToolApprovalResponses(){return this.transport.executorToolApprovalResponses()}connectExecutor(J){return LY0({...J,transport:this.transport})}syncExecutorToolRegistrations(J){if(!this.isExecutorConnected())return[...J.previouslyAdvertisedTools??[]];return Di({...J,transport:this.transport})}sendSettingsUpdate(J,Z){return OY0(this.transport,J,Z)}subscribeToProtocolEvents(J){return LP4(this.transport,J)}emitThread(J){let Z=this.threadSubject.getValue(),Q=J?.agentMode??Z.agentMode,Y=zQ3(this.deltaState.streamingMessageId,this.deltaState.streamingBlocks,this.messages.length,this.deltaState.streamingParentToolCallId),K=Y?[...this.messages,Y]:[...this.messages],V=K.reduce((G,F)=>Math.max(G,F.messageId),-1)+1,z={...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(z),this.reconcilePendingClientWrites(z),this.replayPendingClientWritesIfNeeded(z)}reconcilePendingClientWrites(J){if(this.pendingClientWritesByMessageID.size===0)return;let Z=new Set;for(let Q of J.messages){let Y=s6.safeParse(Q.dtwMessageID);if(Y.success)Z.add(Y.data)}for(let Q of J.queuedMessages??[]){let Y=s6.safeParse(Q.id);if(Y.success)Z.add(Y.data);let X=s6.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,P.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){let Y=Q instanceof Error?Q.message:String(Q);P.error("[dtw] Transport handler failed",{threadId:this.threadId,handler:J,connectionState:this.lastConnectionState,error:Q}),this.editErrorSubject.next(`[dtw] ${J}: ${Y}`)}}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;if(K==="connected"&&this.lastConnectionState!=="connected")this.threadResumeCursor.reset(),this.transport.resumeFromVersion(this.threadResumeCursor.getVersion());if(this.lastConnectionState=K,this.lastConnectionInfo={...J},this.executorHandshakeManager?.handleConnectionChange(J),this.executorReadySubject.next(J.state==="connected"&&J.role==="executor"),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"?nn0(J.message):null;if(P.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}")`:"";this.editErrorSubject.next(`Received an invalid DTW message${Q}. The connection will continue running. Check logs for details.`)}})}}),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(GQ3(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=FQ3(this.messages,this.deltaState.completedMessages,this.processedIds),this.deltaState.completedMessages=[]}this.emitThread()})}}),this.transport.toolProgress().subscribe({next:(J)=>{this.runTransportHandler("toolProgress",()=>{this.toolProgressSubject.next(J);let Z=J.toolCallId,Q=EP4(J.progress),Y=MP4(J.progress),X=this.toolProgressByToolUseID.get(Z),K=J.progress!==void 0?AP4(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 z={status:Y??X?.status??"in-progress",content:Q??X?.content??"",...K!==void 0?{subagentProgressTurns:K}:{}};if(X?.status===z.status&&X?.content===z.content&&X?.subagentProgressTurns===z.subagentProgressTurns)return;this.toolProgressByToolUseID.set(Z,z),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=jP4(J);if(this.messages=WQ3(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=jP4(J);this.messages=UQ3(J,this.messages),this.processedIds=VQ3(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=DQ3(this.queuedMessages,J),this.emitThread()})}}))}logConnectionStateTransition(J,Z){let Q={threadId:this.threadId,from:J,to:Z.state,threadVersion:this.threadResumeCursor.getVersion(),...IP4(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"){P.info("[dtw] Transport reconnected",Q);return}P.info("[dtw] Transport connected",Q);return}if(Z.state==="reconnecting"){P.warn("[dtw] Transport reconnecting",Q);return}if(Z.state==="disconnected"){P.warn("[dtw] Transport disconnected",Q);return}P.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;P.info("[dtw] Transport role changed",Q)}ensureTransportSubscriptions(){if(this.transportSubscribed)return;this.transportSubscribed=!0,this.subscribeToTransport()}async connect(){if(this.connectPromise)return this.connectPromise;this.ensureTransportSubscriptions();let J=this.transport.getConnectionInfo();if(J.state==="connected"||J.state==="connecting"||J.state==="authenticating"||J.state==="reconnecting")return;this.connectPromise=(async()=>{try{await this.transport.connect()}catch(Z){let Q=this.transport.getConnectionInfo();if(Q.state!=="reconnecting")throw Z;P.warn("[dtw] Initial transport connect failed; waiting for reconnect",{threadId:this.threadId,connectionState:Q.state,...IP4(Q.reconnectCause),error:Z})}this.emitThread()})();try{await this.connectPromise}finally{this.connectPromise=null}}async ensureConnected(){if(this.ensureConnectedPromise)return this.ensureConnectedPromise;this.ensureConnectedPromise=(async()=>{let J=$Q3,Z=JQ3,Q=ZQ3;for(let K=0;K<Q;K++){await this.connect();let V=Math.min(J*2**K,Z);if(await this.waitForTransportConnected(V))return;P.info("[dtw] Connection attempt timed out, retrying",{attempt:K+1,maxAttempts:Q,nextDelayMs:K+1<Q?Math.min(J*2**(K+1),Z):null,threadId:this.threadId})}let X=this.transport.getConnectionInfo().state==="reconnecting"?"Timed out while reconnecting. Please retry after reconnecting.":"Timed out waiting for connection. Please retry.";throw Error(X)})();try{await this.ensureConnectedPromise}finally{this.ensureConnectedPromise=null}}waitForTransportConnected(J){if(this.transport.getConnectionInfo().state==="connected")return Promise.resolve(!0);return new Promise((Z)=>{let Q=!1,Y=null,X=(V)=>{if(Q)return;Q=!0,clearTimeout(K),Z(V),Y?.unsubscribe(),Y=null},K=setTimeout(()=>{X(!1)},J);if(Y=this.transport.connectionChanges().subscribe({next:(V)=>{if(V.state==="connected")X(!0)},error:()=>{X(!1)}}),Q)Y.unsubscribe(),Y=null})}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)=>s6.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)}dispose(){for(let J of this.subscriptions)J.unsubscribe();this.subscriptions.length=0,this.executorHandshakeManager?.dispose(),this.executorHandshakeManager=null,this.pendingClientWritesByMessageID.clear(),this.pendingClientWriteReplayGeneration=null,this.compactionStateSubject.complete(),this.agentLoopStateSubject.complete(),this.executorReadySubject.complete(),this.toolProgressByToolUseIDSubject.complete(),this.toolProgressSubject.complete(),this.transport.dispose()}}import{mkdir as NQ3,readFile as wQ3,rm as aa0,writeFile as LQ3}from"node:fs/promises";import OQ3 from"node:path";d4();var EQ3=5000,MQ3=100;function AQ3(J){try{return process.kill(J,0),!0}catch(Z){return Z.code==="EPERM"}}function oa0(J,Z){return J.code===Z}function jQ3(J){return J instanceof Error?J.message:String(J)}function TP4(J){if(typeof J!=="string")return null;let Z=J.trim();return Z.length>0?Z:null}function RQ3(J,Z){let Q=Reflect.get(J,Z);if(typeof Q!=="number")return;return Number.isSafeInteger(Q)&&Q>0?Q:void 0}function IQ3(J,Z){return TP4(Reflect.get(J,Z))}function PQ3(J){let Z;try{Z=JSON.parse(J)}catch{return}if(!Z||typeof Z!=="object")return;let Q=RQ3(Z,"pid"),Y=Reflect.get(Z,"threadId"),X=IQ3(Z,"threadTitle");if(Q===void 0||typeof Y!=="string"||!b9(Y))return;return{pid:Q,threadId:Y,threadTitle:X}}function CQ3(J){let Z={pid:J.pid,threadId:J.threadId};if(J.threadTitle)Z.threadTitle=J.threadTitle;return`${JSON.stringify(Z)}
|
|
6211
|
+
`),process.exit(1)}}import{execFile as iY3}from"node:child_process";import{lstat as PC4,mkdir as nY3,readFile as aY3,rm as No0,writeFile as oY3}from"node:fs/promises";import aY from"node:path";import u$ from"node:process";import{createInterface as rY3}from"node:readline";import{promisify as sY3}from"node:util";class V3{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 z=this.neighborMap[V].filter((G)=>this.state[G]).length;if(K)return z===2||z===3;return z===3||z===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)}}m0();_7();N4();m0();O$();O1();import{mkdir as lZ3,writeFile as iZ3}from"node:fs/promises";import nZ3 from"node:path";function aZ3(J){let Z=J?.trim();return Z&&Z.length>0?Z:void 0}function oZ3(J){let Z=J.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48);return Z.length>0?Z:"trace"}function rZ3(J,Z){let Q=new Date(J).toISOString().replace(/[:.]/g,"-");return`${Z?`dtw-trace-${oZ3(Z)}`:"dtw-trace"}-${Q}-${crypto.randomUUID().slice(0,8)}`}function da0(J){let Z=JSON.stringify(J);if(Z===void 0)return null;return JSON.parse(Z)}class ca0{options;traceFilePath;session;constructor(J){this.options=J;let Z=Date.now(),Q=aZ3(J.traceName),Y=rZ3(Z,Q);this.traceFilePath=nZ3.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:da0(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:da0(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:da0(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 lZ3(this.options.traceDir,{recursive:!0});let J=JSON.stringify(this.session,null,2);return await iZ3(this.traceFilePath,J,"utf-8"),this.traceFilePath}}function LP4(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 hY0(J){return typeof J==="object"&&J!==null}function la0(J){if(!Array.isArray(J))return;return J}function OP4(J){let Z=J.trim();if(Z.length===0)return;try{let Q=JSON.parse(Z);return la0(Q)}catch{return}}function bY0(J){if(typeof J==="string")return J;if(!hY0(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=bY0(J.result);if(Z!==void 0)return Z}if("error"in J){let Z=bY0(J.error);if(Z!==void 0)return Z}if("value"in J)return bY0(J.value);return}function sZ3(J){return J.type==="text"}function EP4(J){if(J===void 0)return;let Z;try{Z=zi(J,"snapshot")}catch{return}if(Z.type==="snapshot")return bY0(Z.value);let Q=(Z.blocks??[]).filter(sZ3).map((Y)=>Y.text).join("");return Q.length>0?Q:void 0}var tZ3=["queued","blocked-on-user","in-progress","rejected-by-user","cancellation-requested","cancelled","done","error"];function eZ3(J){return typeof J==="string"&&tZ3.includes(J)}function MP4(J){if(J===void 0)return;let Z;try{Z=zi(J,"snapshot")}catch{return}if(Z.type!=="snapshot")return;let Q=Z.value;if(!hY0(Q))return;if(!("status"in Q)||!eZ3(Q.status))return;return Q.status}function AP4(J){let Z=la0(J);if(Z!==void 0)return Z;if(!hY0(J)||typeof J.type!=="string")return;if(J.type==="snapshot"){let Y=J.value,X=la0(Y);if(X!==void 0)return X;if(typeof Y==="string")return OP4(Y);return}if(J.type!=="delta"||!Array.isArray(J.blocks))return;let Q=J.blocks.map((Y)=>{if(!hY0(Y)||Y.type!=="text"||typeof Y.text!=="string")return"";return Y.text}).join("");return OP4(Q)}var $Q3=3000,JQ3=30000,ZQ3=5;function PP4(J){let Z=[],Q=0;for(let X of J.messages){if(X.role==="user"){Z.push({messageId:zq(),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:zq(),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:zq(),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:zq(),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 QQ3(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 UH(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 X8("/api/durable-thread-workers",na0({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 YQ3(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??PP4(J),z=Y.workerURL??i7(Y.ampURL),G=await fetch(`${z}/threads/${J.id}/import`,{method:"POST",headers:{Authorization:`Bearer ${K}`,"Content-Type":"application/json"},body:JSON.stringify({thread:V})});if(G.status===409)return"already-imported";if(!G.ok)throw Error(`Failed to import thread into DTW: ${G.status} ${await G.text()}`);if((await G.json()).ok!==!0)throw Error("Failed to import thread into DTW: import endpoint returned an invalid response");return"imported"}async function XQ3(J,Z,Q){let Y=await X8(`/api/durable-thread-workers/${J}`,na0({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 vi(J,Z,Q){let Y=await X8(`/api/threads/${J}`,na0(void 0,Q),Z);if(!Y.ok)throw Error(`Failed to fetch thread snapshot: ${Y.status} ${await Y.text()}`);return await Y.json()}function na0(J,Z){if(!Z)return J;return{...J,headers:{...J?.headers,Authorization:`Bearer ${Z}`}}}function ki(J){let Z=s6.safeParse(J.dtwMessageID);if(Z.success)return Z.data;let Q=s6.safeParse(`${J.messageId}`);return Q.success?Q.data:null}function KQ3(J){let Z=[],Q=new Set;for(let[Y,X]of J.messages.entries()){let K=ki(X);if(K)Q.add(K);Z.push({...X,messageId:Y})}return{messages:Z,processedIds:Q}}function VQ3(J){let Z=new Set;for(let Q of J){let Y=ki(Q);if(Y)Z.add(Y)}return Z}function _i(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 zQ3(J,Z,Q,Y){if(!J||Z.length===0)return null;return{role:"assistant",content:Z,state:{type:"streaming"},messageId:Q,parentToolUseId:Y}}function GQ3(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=_i(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=_i([],J.blocks??[]),Z.streamingParentToolCallId=Q;else if(J.blocks)Z.streamingBlocks=_i(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=_i([],J.blocks??[]),Z.streamingParentToolCallId=Q;else if(J.blocks)Z.streamingBlocks=_i(Z.streamingBlocks,J.blocks)}}function FQ3(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 qQ3(J){if(typeof J!=="number"||!Number.isFinite(J))return 0;return Math.max(0,Math.trunc(J))}function ia0(J){if(!J||J.length===0)return;return J.map((Z)=>({uri:Z.uri,lineCount:qQ3(Z.lineCount),...typeof Z.content==="string"?{content:Z.content}:{}}))}function WQ3(J,Z,Q){let Y=J.message.messageId;if(Q.has(Y)){let K=Z.findIndex((z)=>ki(z)===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 z={...V,content:J.message.content,agentMode:J.message.agentMode,userState:J.message.userState,discoveredGuidanceFiles:ia0(J.message.discoveredGuidanceFiles),parentToolUseId:J.parentToolUseId},G=[...Z];return G[K]=z,G}if(V.role==="assistant"&&J.message.role==="assistant"){let z={...V,content:J.message.content,usage:J.message.usage,state:{type:"complete",stopReason:"end_turn"},parentToolUseId:J.parentToolUseId},G=[...Z];return G[K]=z,G}if(V.role==="info"&&J.message.role==="info"){let z={...V,content:J.message.content,parentToolUseId:J.parentToolUseId},G=[...Z];return G[K]=z,G}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:ia0(J.message.discoveredGuidanceFiles),messageId:X,dtwMessageID:Y,parentToolUseId:J.parentToolUseId}]}function UQ3(J,Z){let Q=Z.findIndex((z)=>ki(z)===J.messageId),Y=Z.findIndex((z)=>ki(z)===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 jP4(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 RP4(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:ia0(Z.discoveredGuidanceFiles),meta:Z.createdAt?{sentAt:Date.parse(Z.createdAt)}:void 0,messageId:-1,dtwMessageID:Z.messageId}}}function HQ3(J){if(J.type==="queued_messages")return{type:"queued_messages",messages:J.messages.map((Z)=>RP4(Z))};if(J.type==="queued_message_added")return{type:"queued_message_added",message:RP4(J.message)};return{type:"queued_message_removed",queuedMessageId:J.queuedMessageId}}function DQ3(J,Z){let Q=HQ3(Z);return en0(Si(J)??[],Q,{dedupeAdded:!0,getQueuedMessageId:(Y)=>Y.id})}async function BQ3(J,Z){if(J.useThreadActors){let Q=vk(J.ampURL),Y=kk({endpoint:Q});return{baseURL:Q,threadId:Z.threadId,wsToken:Z.wsToken,wsTokenProvider:async()=>UH(Z.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL}),webSocketProvider:async()=>{let X=await UH(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}}return{baseURL:J.workerUrl??i7(J.ampURL),threadId:Z.threadId,wsToken:Z.wsToken,wsTokenProvider:async()=>UH(Z.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL}),WebSocketClass:WebSocket,maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000}}function IP4(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 gY0{threadSubject;agentLoopStateSubject=new K4("idle");executorReadySubject=new K4(!1);editErrorSubject=new Y4;deltaState={streamingMessageId:null,streamingBlocks:[],completedMessages:[]};toolProgressByToolUseIDSubject=new K4(new Map);toolProgressSubject=new Y4;subscriptions=[];threadResumeCursor;messages;queuedMessages;relationships;threadTitle;processedIds;agentLoopState="idle";toolProgressByToolUseID=new Map;compactionStateSubject=new K4("idle");compactionState="idle";transportSubscribed=!1;connectPromise=null;ensureConnectedPromise=null;lastConnectionState="disconnected";lastConnectionInfo=null;executorHandshakeManager=null;pendingClientWritesByMessageID=new Map;connectedTransportGeneration=0;pendingClientWriteReplayGeneration=null;transport;threadId;constructor(J,Z,Q,Y){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=cj4(Y),this.threadSubject=new K4(J)}static async create(J){let Z=await UH(J.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL,executorType:J.executorType,usesThreadActors:J.useThreadActors}),Q=await vi(Z.threadId,J.configService,J.apiKey);if(!Z.usesDtw){if(J.useThreadActors)throw Error("TODO: Importing threads into rivet thread actors isn't supported");J.onLegacyImportStateChange?.("importing");try{let G=PP4(Q),F=await YQ3(Q,J.configService,J.apiKey,{ampURL:J.ampURL,workerURL:J.workerUrl,payload:G});if(await XQ3(Z.threadId,J.configService,J.apiKey),F==="imported")Q=QQ3(Q,G)}finally{J.onLegacyImportStateChange?.("idle")}}let{messages:Y,processedIds:X}=KQ3(Q),K={...Q,id:Z.threadId,messages:Y,queuedMessages:Si(Q.queuedMessages),relationships:Q.relationships?[...Q.relationships]:void 0},V=new Fq(await BQ3(J,Z)),z=new gY0(K,V,X,Q.v);try{if(J.connectOnCreate??!0)await z.connect();return z}catch(G){throw z.dispose(),G}}threadChanges(){return this.threadSubject}agentLoopStateChanges(){return this.agentLoopStateSubject}executorReadyChanges(){return this.executorReadySubject}toolProgressByToolUseIDChanges(){return this.toolProgressByToolUseIDSubject}toolProgressChanges(){return this.toolProgressSubject}editErrors(){return this.editErrorSubject}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}willQueueNextUserMessage(){return this.agentLoopState!=="idle"||this.deltaState.streamingMessageId!==null}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)}configureExecutorHandshake(J){this.executorHandshakeManager?.dispose(),this.executorHandshakeManager=new Ni(J);let Z=this.transport.getConnectionInfo();this.executorHandshakeManager.handleConnectionChange(Z),this.executorReadySubject.next(Z.state==="connected"&&Z.role==="executor")}ensureExecutorReady(J){if(!this.executorHandshakeManager)return Promise.reject(Error("Executor handshake manager is not configured"));return this.executorHandshakeManager.ensureReady(J)}disconnectTransport(){this.transport.disconnect()}async ensureConnectedForAction(J){if(this.transport.getConnectionInfo().state==="reconnecting"){let Q=J==="client-write"?"client write action":"executor action";P.info(`Forcing transport reconnect before ${Q}`),this.transport.disconnect()}await this.ensureConnected()}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)}ackToolLease(...J){this.transport.ackToolLease(...J)}sendToolProgress(...J){this.transport.sendToolProgress(...J)}sendExecutorToolResult(...J){this.transport.sendExecutorToolResult(...J)}sendRevocationAck(...J){this.transport.sendRevocationAck(...J)}sendExecutorRollbackAck(...J){this.transport.sendExecutorRollbackAck(...J)}sendExecutorGuidanceDiscovery(...J){this.transport.sendExecutorGuidanceDiscovery(...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()}toolLeases(){return this.transport.toolLeases()}toolLeaseRevoked(){return this.transport.toolLeaseRevoked()}executorRollbackRequests(){return this.transport.executorRollbackRequests()}fileSystemReadDirectoryRequests(){return this.transport.fileSystemReadDirectoryRequests()}fileSystemReadFileRequests(){return this.transport.fileSystemReadFileRequests()}executorToolApprovalResponses(){return this.transport.executorToolApprovalResponses()}connectExecutor(J){return LY0({...J,transport:this.transport})}syncExecutorToolRegistrations(J){if(!this.isExecutorConnected())return[...J.previouslyAdvertisedTools??[]];return Di({...J,transport:this.transport})}sendSettingsUpdate(J,Z){return OY0(this.transport,J,Z)}subscribeToProtocolEvents(J){return LP4(this.transport,J)}emitThread(J){let Z=this.threadSubject.getValue(),Q=J?.agentMode??Z.agentMode,Y=zQ3(this.deltaState.streamingMessageId,this.deltaState.streamingBlocks,this.messages.length,this.deltaState.streamingParentToolCallId),K=Y?[...this.messages,Y]:[...this.messages],V=K.reduce((G,F)=>Math.max(G,F.messageId),-1)+1,z={...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(z),this.reconcilePendingClientWrites(z),this.replayPendingClientWritesIfNeeded(z)}reconcilePendingClientWrites(J){if(this.pendingClientWritesByMessageID.size===0)return;let Z=new Set;for(let Q of J.messages){let Y=s6.safeParse(Q.dtwMessageID);if(Y.success)Z.add(Y.data)}for(let Q of J.queuedMessages??[]){let Y=s6.safeParse(Q.id);if(Y.success)Z.add(Y.data);let X=s6.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,P.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){let Y=Q instanceof Error?Q.message:String(Q);P.error("[dtw] Transport handler failed",{threadId:this.threadId,handler:J,connectionState:this.lastConnectionState,error:Q}),this.editErrorSubject.next(`[dtw] ${J}: ${Y}`)}}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;if(K==="connected"&&this.lastConnectionState!=="connected")this.threadResumeCursor.reset(),this.transport.resumeFromVersion(this.threadResumeCursor.getVersion());if(this.lastConnectionState=K,this.lastConnectionInfo={...J},this.executorHandshakeManager?.handleConnectionChange(J),this.executorReadySubject.next(J.state==="connected"&&J.role==="executor"),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"?nn0(J.message):null;if(P.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}")`:"";this.editErrorSubject.next(`Received an invalid DTW message${Q}. The connection will continue running. Check logs for details.`)}})}}),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(GQ3(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=FQ3(this.messages,this.deltaState.completedMessages,this.processedIds),this.deltaState.completedMessages=[]}this.emitThread()})}}),this.transport.toolProgress().subscribe({next:(J)=>{this.runTransportHandler("toolProgress",()=>{this.toolProgressSubject.next(J);let Z=J.toolCallId,Q=EP4(J.progress),Y=MP4(J.progress),X=this.toolProgressByToolUseID.get(Z),K=J.progress!==void 0?AP4(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 z={status:Y??X?.status??"in-progress",content:Q??X?.content??"",...K!==void 0?{subagentProgressTurns:K}:{}};if(X?.status===z.status&&X?.content===z.content&&X?.subagentProgressTurns===z.subagentProgressTurns)return;this.toolProgressByToolUseID.set(Z,z),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=jP4(J);if(this.messages=WQ3(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=jP4(J);this.messages=UQ3(J,this.messages),this.processedIds=VQ3(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=DQ3(this.queuedMessages,J),this.emitThread()})}}))}logConnectionStateTransition(J,Z){let Q={threadId:this.threadId,from:J,to:Z.state,threadVersion:this.threadResumeCursor.getVersion(),...IP4(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"){P.info("[dtw] Transport reconnected",Q);return}P.info("[dtw] Transport connected",Q);return}if(Z.state==="reconnecting"){P.warn("[dtw] Transport reconnecting",Q);return}if(Z.state==="disconnected"){P.warn("[dtw] Transport disconnected",Q);return}P.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;P.info("[dtw] Transport role changed",Q)}ensureTransportSubscriptions(){if(this.transportSubscribed)return;this.transportSubscribed=!0,this.subscribeToTransport()}async connect(){if(this.connectPromise)return this.connectPromise;this.ensureTransportSubscriptions();let J=this.transport.getConnectionInfo();if(J.state==="connected"||J.state==="connecting"||J.state==="authenticating"||J.state==="reconnecting")return;this.connectPromise=(async()=>{try{await this.transport.connect()}catch(Z){let Q=this.transport.getConnectionInfo();if(Q.state!=="reconnecting")throw Z;P.warn("[dtw] Initial transport connect failed; waiting for reconnect",{threadId:this.threadId,connectionState:Q.state,...IP4(Q.reconnectCause),error:Z})}this.emitThread()})();try{await this.connectPromise}finally{this.connectPromise=null}}async ensureConnected(){if(this.ensureConnectedPromise)return this.ensureConnectedPromise;this.ensureConnectedPromise=(async()=>{let J=$Q3,Z=JQ3,Q=ZQ3;for(let K=0;K<Q;K++){await this.connect();let V=Math.min(J*2**K,Z);if(await this.waitForTransportConnected(V))return;P.info("[dtw] Connection attempt timed out, retrying",{attempt:K+1,maxAttempts:Q,nextDelayMs:K+1<Q?Math.min(J*2**(K+1),Z):null,threadId:this.threadId})}let X=this.transport.getConnectionInfo().state==="reconnecting"?"Timed out while reconnecting. Please retry after reconnecting.":"Timed out waiting for connection. Please retry.";throw Error(X)})();try{await this.ensureConnectedPromise}finally{this.ensureConnectedPromise=null}}waitForTransportConnected(J){if(this.transport.getConnectionInfo().state==="connected")return Promise.resolve(!0);return new Promise((Z)=>{let Q=!1,Y=null,X=(V)=>{if(Q)return;Q=!0,clearTimeout(K),Z(V),Y?.unsubscribe(),Y=null},K=setTimeout(()=>{X(!1)},J);if(Y=this.transport.connectionChanges().subscribe({next:(V)=>{if(V.state==="connected")X(!0)},error:()=>{X(!1)}}),Q)Y.unsubscribe(),Y=null})}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)=>s6.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)}dispose(){for(let J of this.subscriptions)J.unsubscribe();this.subscriptions.length=0,this.executorHandshakeManager?.dispose(),this.executorHandshakeManager=null,this.pendingClientWritesByMessageID.clear(),this.pendingClientWriteReplayGeneration=null,this.compactionStateSubject.complete(),this.agentLoopStateSubject.complete(),this.executorReadySubject.complete(),this.toolProgressByToolUseIDSubject.complete(),this.toolProgressSubject.complete(),this.transport.dispose()}}import{mkdir as NQ3,readFile as wQ3,rm as aa0,writeFile as LQ3}from"node:fs/promises";import OQ3 from"node:path";d4();var EQ3=5000,MQ3=100;function AQ3(J){try{return process.kill(J,0),!0}catch(Z){return Z.code==="EPERM"}}function oa0(J,Z){return J.code===Z}function jQ3(J){return J instanceof Error?J.message:String(J)}function TP4(J){if(typeof J!=="string")return null;let Z=J.trim();return Z.length>0?Z:null}function RQ3(J,Z){let Q=Reflect.get(J,Z);if(typeof Q!=="number")return;return Number.isSafeInteger(Q)&&Q>0?Q:void 0}function IQ3(J,Z){return TP4(Reflect.get(J,Z))}function PQ3(J){let Z;try{Z=JSON.parse(J)}catch{return}if(!Z||typeof Z!=="object")return;let Q=RQ3(Z,"pid"),Y=Reflect.get(Z,"threadId"),X=IQ3(Z,"threadTitle");if(Q===void 0||typeof Y!=="string"||!b9(Y))return;return{pid:Q,threadId:Y,threadTitle:X}}function CQ3(J){let Z={pid:J.pid,threadId:J.threadId};if(J.threadTitle)Z.threadTitle=J.threadTitle;return`${JSON.stringify(Z)}
|
|
6214
6212
|
`}function TQ3(J){return{pid:J.currentPID??process.pid,threadId:J.currentThreadId,threadTitle:TP4(J.currentThreadTitle)}}async function _P4(J){try{let Z=await wQ3(J,"utf-8"),Q=PQ3(Z);if(Q===void 0)return{kind:"invalid",value:Z.trim()};return{kind:"valid",contents:Q}}catch(Z){if(oa0(Z,"ENOENT"))return{kind:"missing"};throw Z}}async function SP4(J,Z){let Q=await _P4(J);if(Q.kind!=="valid"||Q.contents.pid!==Z)return;await aa0(J,{force:!0})}async function _Q3(J){try{process.kill(J,"SIGTERM")}catch(Z){if(oa0(Z,"ESRCH"))return;throw Z}}async function SQ3(J,Z){let Q=Date.now()+EQ3;while(Date.now()<Q){if(!Z(J))return!0;await vQ3(MQ3)}return!Z(J)}function kQ3(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(`
|
|
6215
6213
|
`)}function CP4(J,Z){return{status:"claimed",pidFilePath:J,release:async()=>SP4(J,Z)}}function vQ3(J){return new Promise((Z)=>{setTimeout(Z,J)})}async function kP4(J){let Z=J.currentPID??process.pid,Q=TQ3(J),Y=J.isProcessRunning??AQ3,X=J.killProcess??_Q3,K=J.waitForProcessExit??((V)=>SQ3(V,Y));await NQ3(OQ3.dirname(J.pidFilePath),{recursive:!0});while(!0){let V=await _P4(J.pidFilePath);if(V.kind==="valid"){if(V.contents.pid===Z)return CP4(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 z=J.formatRunningPrompt?.({runningPID:V.contents.pid,runningThreadId:V.contents.threadId,runningThreadTitle:V.contents.threadTitle})??kQ3({running:V.contents});if(!await J.promptForYesNo(z))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(F){throw new T1(`Couldn't stop live-sync PID ${V.contents.pid}: ${jQ3(F)}`,1)}if(!await K(V.contents.pid))throw new T1(`Timed out waiting for live-sync PID ${V.contents.pid} to stop.`,1);await SP4(J.pidFilePath,V.contents.pid);continue}await aa0(J.pidFilePath,{force:!0});continue}if(V.kind==="invalid"){await aa0(J.pidFilePath,{force:!0});continue}try{return await LQ3(J.pidFilePath,CQ3(Q),{encoding:"utf-8",flag:"wx",mode:384}),CP4(J.pidFilePath,Z)}catch(z){if(oa0(z,"EEXIST"))continue;throw z}}}m0();class iY{static instance=null;logs=[];maxLogs=1000;listeners=new Set;constructor(){}static getInstance(){if(!iY.instance)iY.instance=new iY;return iY.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 vP4(){try{if(iY.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 Z6(J,...Z){if(!J){let Q=Z.join(" "),Y=Error(Q);P.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;vP4(),console.error("FATAL TUI ERROR:",Q),console.error("Stack trace:",Y.stack),console.error("Context:",{meta:Z}),process.exit(1)}}}var ra0=null,sa0=null;function yP4(J,Z){ra0=J,sa0=Z}function xP4(){return typeof process<"u"&&(process.env.BUN_TEST==="1"||globalThis.Bun?.jest!==void 0||typeof globalThis.test==="function")}function fP4(){if(!ra0){if(xP4())return{scheduleBuildFor:()=>{}};throw Error("Build scheduler not initialized. Make sure WidgetsBinding is created.")}return ra0}function mY0(){if(!sa0){if(xP4())return{requestLayout:()=>{},requestPaint:()=>{},removeFromQueues:()=>{}};throw Error("Paint scheduler not initialized. Make sure WidgetsBinding is created.")}return sa0}class Ej{_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 mY0().requestLayout(this)}markNeedsPaint(){if(this._needsPaint)return;if(!this._attached)return;this._needsPaint=!0,mY0().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(){mY0().removeFromQueues(this),this._cachedDepth=void 0,this._parent=void 0,this._children.length=0}}class u4 extends Ej{_size={width:0,height:0};get size(){return{...this._size}}setSize(J,Z){Z6(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 u4){let z=Z+this.offset.x+V.offset.x,G=Q+this.offset.y+V.offset.y,F=z+V.size.width,q=G+V.size.height;if(!(z>=X||G>=K||F<=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,z=Z.y>=K&&Z.y<K+this.size.height;if(V&&z){J.addWithPaintOffset(this,{x:X,y:K},Z);let G=!0;for(let F=this.children.length-1;F>=0;F--)if(this.children[F].hitTest(J,Z,X,K))G=!0;return G}if(this.allowHitTestOutsideBounds){let G=!1;for(let F=this.children.length-1;F>=0;F--)if(this.children[F].hitTest(J,Z,X,K))G=!0;return G}return!1}}function yi(J,Z=0){return Number.isFinite(J)?J:Z}class I1{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 I1(J,J,Z,Z)}static loose(J,Z){return new I1(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 Z6(isFinite(J),`BoxConstraints.constrain received infinite width: ${J}. This indicates a layout bug where a widget is not properly calculating its desired size.`),Z6(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 I1(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 I1(0,this.maxWidth,0,this.maxHeight)}tighten({width:J,height:Z}={}){return new I1(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 I1(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}}var Hq=B4(uP4(),1),xQ3=globalThis;xQ3.Prism=Hq.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(a,W0){return"(?:"+c[+W0]+")"})}function Q(n,c,a){return RegExp(Z(n,c),a||"")}function Y(n,c){for(var a=0;a<c;a++)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),z=RegExp(K(X.type+" "+X.typeDeclaration+" "+X.contextual+" "+X.other)),G=K(X.typeDeclaration+" "+X.contextual+" "+X.other),F=K(X.type+" "+X.typeDeclaration+" "+X.other),q=Y(/<(?:[^<>;=+\-*/%&|^]|<<self>>)*>/.source,2),W=Y(/\((?:[^()]|<<self>>)*\)/.source,2),U=/@?\b[A-Za-z_]\w*\b/.source,H=Z(/<<0>>(?:\s*<<1>>)?/.source,[U,q]),D=Z(/(?!<<0>>)<<1>>(?:\s*\.\s*<<1>>)*/.source,[G,H]),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:z,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,[U,O]),lookbehind:!0,inside:E},{pattern:Q(/(\busing\s+)<<0>>(?=\s*=)/.source,[U]),lookbehind:!0},{pattern:Q(/(\b<<0>>\s+)<<1>>/.source,[V,H]),lookbehind:!0,inside:E},{pattern:Q(/(\bcatch\s*\(\s*)<<0>>/.source,[D]),lookbehind:!0,inside:E},{pattern:Q(/(\bwhere\s+)<<0>>/.source,[U]),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,F,U]),inside:E}],keyword:z,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,[U]),lookbehind:!0,alias:"punctuation"}}),J.languages.insertBefore("csharp","class-name",{namespace:{pattern:Q(/(\b(?:namespace|using)\s+)<<0>>(?:\s*\.\s*<<0>>)*(?=\s*[;{])/.source,[U]),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,[U,q]),inside:{function:Q(/^<<0>>/.source,[U]),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,H,U,O,z.source,W,/\bnew\s*\(\s*\)/.source]),lookbehind:!0,inside:{"record-arguments":{pattern:Q(/(^(?!new\s*\()<<0>>\s*)<<1>>/.source,[H,W]),lookbehind:!0,greedy:!0,inside:J.languages.csharp},keyword:z,"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 R=A+"|"+M,_=Z(/\/(?![*/])|\/\/[^\r\n]*[\r\n]|\/\*(?:[^*]|\*(?!\/))*\*\/|<<0>>/.source,[R]),T=Y(Z(/[^"'/()]|<<0>>|\(<<self>>*\)/.source,[_]),2),u=/\b(?:assembly|event|field|method|module|param|property|return|type)\b/.source,m=Z(/<<0>>(?:\s*\(<<1>>*\))?/.source,[D,T]);J.languages.insertBefore("csharp","class-name",{attribute:{pattern:Q(/((?:^|[^\s\w>)?])\s*\[\s*)(?:<<0>>\s*:\s*)?<<1>>(?:\s*,\s*<<1>>)*(?=\s*\])/.source,[u,m]),lookbehind:!0,greedy:!0,inside:{target:{pattern:Q(/^<<0>>(?=\s*:)/.source,[u]),alias:"keyword"},"attribute-arguments":{pattern:Q(/\(<<0>>*\)/.source,[T]),inside:J.languages.csharp},"class-name":{pattern:RegExp(D),inside:{punctuation:/\./}},punctuation:/[:,]/}}});var y=/:[^}\r\n]+/.source,k=Y(Z(/[^"'/()]|<<0>>|\(<<self>>*\)/.source,[_]),2),f=Z(/\{(?!\{)(?:(?![}:])<<0>>)*<<1>>?\}/.source,[k,y]),d=Y(Z(/[^"'/()]|\/(?!\*)|\/\*(?:[^*]|\*(?!\/))*\*\/|<<0>>|\(<<self>>*\)/.source,[R]),2),p=Z(/\{(?!\{)(?:(?![}:])<<0>>)*<<1>>?\}/.source,[d,y]);function h(n,c){return{interpolation:{pattern:Q(/((?:^|[^{])(?:\{\{)*)<<0>>/.source,[n]),lookbehind:!0,inside:{"format-string":{pattern:Q(/(^\{(?:(?![}:])<<0>>)*)<<1>>(?=\}$)/.source,[c,y]),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,[p]),lookbehind:!0,greedy:!0,inside:h(p,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 z(G,F){return G=G.replace(/<OPT>/g,function(){return X}).replace(/<SP>/g,function(){return Q}),RegExp(G,F)}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:z(/(^(?: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:z(/(^(?:ONBUILD<SP>)?HEALTHCHECK<SP>(?:<OPT><SP>)*)(?:CMD|NONE)\b/.source,"i"),lookbehind:!0,greedy:!0},{pattern:z(/(^(?:ONBUILD<SP>)?FROM<SP>(?:<OPT><SP>)*(?!--)[^ \t\\]+<SP>)AS/.source,"i"),lookbehind:!0,greedy:!0},{pattern:z(/(^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 z(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 G=Q[Y++];if(G.type==="keyword"&&G.content==="mutation"){var F=[];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")z(W,"variable-input"),F.push(W.content)}Y=q+1}if(K(["punctuation","property-query"])&&X(0).content==="{"){if(Y++,z(X(0),"property-mutation"),F.length>0){var U=V(/^\{$/,/^\}$/);if(U===-1)continue;for(var H=Y;H<U;H++){var D=Q[H];if(D.type==="variable"&&F.indexOf(D.content)>=0)z(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(G,F){return G=G.replace(/<S>/g,function(){return Q}).replace(/<BRACES>/g,function(){return Y}).replace(/<SPREAD>/g,function(){return X}),RegExp(G,F)}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(G){if(!G)return"";if(typeof G==="string")return G;if(typeof G.content==="string")return G.content;return G.content.map(V).join("")},z=function(G){var F=[];for(var q=0;q<G.length;q++){var W=G[q],U=!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(F.length>0&&F[F.length-1].tagName===V(W.content[0].content[1]))F.pop()}else if(W.content[W.content.length-1].content==="/>");else F.push({tagName:V(W.content[0].content[1]),openedBraces:0});else if(F.length>0&&W.type==="punctuation"&&W.content==="{")F[F.length-1].openedBraces++;else if(F.length>0&&F[F.length-1].openedBraces>0&&W.type==="punctuation"&&W.content==="}")F[F.length-1].openedBraces--;else U=!0;if(U||typeof W==="string"){if(F.length>0&&F[F.length-1].openedBraces===0){var H=V(W);if(q<G.length-1&&(typeof G[q+1]==="string"||G[q+1].type==="plain-text"))H+=V(G[q+1]),G.splice(q+1,1);if(q>0&&(typeof G[q-1]==="string"||G[q-1].type==="plain-text"))H=V(G[q-1])+H,G.splice(q-1,1),q--;G[q]=new J.Token("plain-text",H,null,H)}}if(W.content&&typeof W.content!=="string")z(W.content)}};J.hooks.add("after-tokenize",function(G){if(G.language!=="jsx"&&G.language!=="tsx")return;z(G.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(U){if(!U||typeof U==="string")return;for(var H=0,D=U.length;H<D;H++){var B=U[H];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 U=0,H=q.classes.length;U<H;U++){var D=q.classes[U],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(F(q.content),N,W)});var V=RegExp(J.languages.markup.tag.pattern.source,"gi"),z={amp:"&",lt:"<",gt:">",quot:'"'},G=String.fromCodePoint||String.fromCharCode;function F(q){var W=q.replace(V,"");return W=W.replace(/&(\w{1,8}|#x?[\da-f]{1,8});/gi,function(U,H){if(H=H.toLowerCase(),H[0]==="#"){var D;if(H[1]==="x")D=parseInt(H.slice(2),16);else D=Number(H.slice(1));return G(D)}else{var B=z[H];if(B)return B;return U}}),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},z=[{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:z,attribute:{pattern:/#\[(?:[^"'\/#]|\/(?![*/])|\/\/.*$|#(?!\[).*$|\/\*(?:[^*]|\*(?!\/))*\*\/|"(?:\\[\s\S]|[^\\"])*"|'(?:\\[\s\S]|[^\\'])*')+\](?=\s*[a-z$#])/im,greedy:!0,inside:{"attribute-content":{pattern:/^(#\[)[\s\S]+(?=\]$)/,lookbehind:!0,inside:{comment:Z,string:z,"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(G){if(!/<\?/.test(G.code))return;var F=/<\?(?:[^"'/#]|\/(?![*/])|("|')(?:\\[\s\S]|(?!\1)[^\\])*\1|(?:\/\/|#(?!\[))(?:[^?\n\r]|\?(?!>))*(?=$|\?>|[\r\n])|#\[|\/\*(?:[^*]|\*(?!\/))*(?:\*\/|$))*?(?:\?>|$)/g;J.languages["markup-templating"].buildPlaceholders(G,"php",F)}),J.hooks.add("after-tokenize",function(G){J.languages["markup-templating"].tokenizePlaceholders(G,"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(z,G){G=(G||"").replace(/m/g,"")+"m";var F=/([:\-,[{]\s*(?:\s<<prop>>[ \t]+)?)(?:<<value>>)(?=[ \t]*(?:$|,|\]|\}|(?:[\r\n]\s*)?#))/.source.replace(/<<prop>>/g,function(){return Y}).replace(/<<value>>/g,function(){return z});return RegExp(F,G)}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(G){return function(){return G}}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)),z="(?!\\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(z)).replace(/<ALIGN>/g,Z(X))),lookbehind:!0,inside:null},{pattern:RegExp(/(\)\s*)<TYPE>(?=\s*(?:<ALIGN>\s*)?;)/.source.replace(/<TYPE>/g,Z(z)).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(G){if(G.inside===null)G.inside=J.languages.zig})})(Prism);function fQ3(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 uQ3(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 dY0="unknown",bP4;function cY0(J,Z){dY0=J,bP4=Z}function Lw(){return dY0}function hP4(){return bP4}function gP4(J,Z,Q){if(dY0==="unknown")return null;if(J.type!=="rgb"||Z.type!=="rgb")return null;let Y=dY0==="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 bQ3(J,Z,Q){let Y=[];function X(K,V){if(typeof K==="string")Y.push({content:K,color:V});else{let z=V??uQ3(K.type,Z);if(typeof K.content==="string")Y.push({content:K.content,color:z});else if(Array.isArray(K.content))K.content.forEach((G)=>X(G,z));else X(K.content,z)}}return J.forEach((K)=>X(K,Q)),Y}function Ow(J,Z,Q){try{let Y=Q?fQ3(Q):"plain";if(Y==="plain"||!Hq.default.languages[Y])return[{content:J}];let X=Hq.default.tokenize(J,Hq.default.languages[Y]);return bQ3(X,Z)}catch(Y){return[{content:J}]}}var fi=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 q6(J=" ",Z={},Q=1,Y){return{char:J,style:{...Z},width:Q,hyperlink:Y}}var Ew=q6(" ",{});function hQ3(J,Z){return J.char===Z.char&&J.width===Z.width&&pP4(J.style,Z.style)&&ui(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 ui(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 xi(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(xi(J)!==xi(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 lY0(J,Z,Q){if(J.type==="none")return Z;if(Z.type==="none"){let F=J.alpha??1;if(F>=1)return J;let q=hP4(),W=Lw(),U=q??(W==="light"?{r:255,g:255,b:255}:{r:0,g:0,b:0}),H=ta0(J,Q);if(!H)return J;let D=Math.round(H.r*F+U.r*(1-F)),B=Math.round(H.g*F+U.g*(1-F)),N=Math.round(H.b*F+U.b*(1-F));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)),z=Math.round(X.g*Y+K.g*(1-Y)),G=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,z)),b:Math.max(0,Math.min(255,G))}}}function gQ3(J,Z,Q,Y,X){let K={...Z};if(J.fg)if(Z.fg)K.fg=lY0(J.fg,Z.fg,X);else K.fg=lY0(J.fg,Y,X);if(J.bg){let V=xi(J.bg);if(J.bg.type==="none"||V===0){if(Z.bg)K.bg=Z.bg}else if(Z.bg)K.bg=lY0(J.bg,Z.bg,X);else K.bg=lY0(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(()=>Ew))}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?xi(Q.style.fg):void 0,X=Q.style.bg?xi(Q.style.bg):void 0;if(Y!==void 0&&Y<1||X!==void 0&&X<1){let V=this.cells[Z]?.[J]||Ew,z=gQ3(Q.style,V.style,this.defaultBg,this.defaultFg,this.indexToRgb);if(this.cells[Z])this.cells[Z][J]={char:Q.char,style:z,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]=q6(" ",Q.style,1)}}setChar(J,Z,Q,Y,X){this.setCell(J,Z,q6(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]=Ew}}fill(J,Z,Q,Y,X=" ",K={}){let V=q6(X,K);for(let z=0;z<Y;z++)for(let G=0;G<Q;G++)this.setCell(J+G,Z+z,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 HH{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 z=1;z<V.width;z++){let G=X[K+z];if(!G)return!1;if(!(G.char===" "&&G.width===1&&pP4(G.style,V.style)&&ui(G.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 z=K[V]??Ew;if(J.push({x:V,y:X,cell:z}),Y(K,V,z))V+=z.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 z=0;z<this.width;z++){let G=K[z]??Ew,F=V[z]??Ew;if(G===Ew&&F===Ew)continue;if(!hQ3(G,F)){if(J.push({x:z,y:X,cell:F}),Y(V,z,F))z+=F.width-1}else if(Y(V,z,F))z+=F.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 mQ3=0;function pQ3(){return`amp-${++mQ3}`}function iY0(J,Z){return{uri:J,id:Z??pQ3()}}function dP4(J){return`\x1B]8;id=${J.id};${J.uri}\x1B\\`}function nY0(){return"\x1B]8;;\x1B\\"}class bi{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 DH="\x1B",M6="\x1B[",cP4=M6+"0m",dQ3=M6+"m",lP4=(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",iP4=[...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]})],nP4=new Map;function hi(J,Z,Q){let Y=`${J},${Z},${Q}`,X=nP4.get(Y);if(X!==void 0)return X;let K=16,V=1/0;for(let z=0;z<iP4.length;z++){let[G,F,q]=iP4[z],W=(J-G)**2+(Z-F)**2+(Q-q)**2;if(W<V)V=W,K=z+16}return nP4.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",zY3=M6+">5u",GY3=M6+"<u",FY3=M6+">4;1m",qY3=M6+">4;0m",WY3=(J)=>DH+`]22;${J}`+DH+"\\",UY3=(J)=>DH+`]0;${J}\x07`;function HY3(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=DH+"]9;4;3"+DH+"\\",oP4=DH+"]9;4;0"+DH+"\\",NY3=DH+"]9;4;4"+DH+"\\",wY3=(J)=>M6+`${J} q`;function LY3(J){return $Y3+(J?ZY3:"")}function OY3(){return JY3+QY3}function oY0(J){return UY3(J)}function rP4(){return oP4}function aP4(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:z,g:G,b:F}=J.value,q=hi(z,G,F);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(!aY0(J.fg,Z.fg)){if(J.fg===void 0&&Z.fg!==void 0)Y+=M6+"39m";else Y+=aP4(J.fg,!0,Q);Z.fg=J.fg}if(!aY0(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+=aP4(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(!ui(J,Z.hyperlink)){if(Z.hyperlink)Q+=nY0();if(J)Q+=dP4(J);Z.hyperlink=J}return Q}function aY0(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 aY0(J.fg,Z.fg)&&aY0(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(fi);function RY3(J,Z){if(J.char==="\t"){if(J.width===fi)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 $o0{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 bi,Q=null,Y,X=-1,K=-1;for(let V of J){let z=V.cell.char,G=HY3(z),F=G?DY3(z):z;if(Z6(!G,`Cell contains disallowed control at (${V.x}, ${V.y}):`,`U+${z.codePointAt(0)?.toString(16).toUpperCase().padStart(4,"0")}`),!(Q!==null&&V.y===K&&V.x===X&&AY3(Q,V.cell.style)&&ui(Y,V.cell.hyperlink))){if(this.currentX!==V.x||this.currentY!==V.y)Z.append(lP4(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=G?{...V.cell,char:F}: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={},cP4+nY0()+nQ3+cQ3}hideCursor(){return lQ3}showCursor(){return iQ3}setCursorShape(J){if(this.capabilities?.supportsCursorShape===!1)return"";return wY3(J)}reset(){return this.currentStyle={},cP4+nY0()}moveTo(J,Z){return this.currentX=J,this.currentY=Z,lP4(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(){return zY3}disableKittyKeyboard(){return GY3}enableModifyOtherKeys(){return FY3}disableModifyOtherKeys(){return qY3}setMouseShape(J){return WY3(J)}setProgressBarIndeterminate(){return BY3}setProgressBarOff(){return oP4}setProgressBarPaused(){return NY3}}class rY0{constructor(){}}class M3 extends rY0{value;constructor(J){super();this.value=J}equals(J){if(!(J instanceof M3))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 s2 extends rY0{static _registry=new Map;static _counter=0;_id;_currentElement;constructor(J){super();if(J)this._id=`${J}_${s2._counter++}`;else this._id=`GlobalKey_${s2._counter++}`;s2._registry.set(this._id,this)}equals(J){if(!(J instanceof s2))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){Z6(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,s2._registry.delete(this._id)}toString(){return`GlobalKey(${this._id})`}static _clearRegistry(){s2._registry.clear(),s2._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 nY{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 s2)this.widget.key._setElement(this)}unmount(){if(this.widget.key instanceof s2)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,fP4().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 Yv extends AJ{constructor({key:J}={}){super(J!==void 0?{key:J}:{})}createElement(){return new gi(this)}updateRenderObject(J){}}class n3 extends Yv{child;constructor({key:J,child:Z}={}){super(J?{key:J}:{});this.child=Z}createElement(){return new Dq(this)}}class LZ extends Yv{children;constructor({key:J,children:Z=[]}={}){super(J?{key:J}:{});this.children=[...Z]}createElement(){return new sY0(this)}}class x$ extends Yv{constructor({key:J}={}){super(J?{key:J}:{})}createElement(){return new xK(this)}}class gi extends nY{_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 Dq extends gi{_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 sY0 extends gi{_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 G=J[Y],F=Z[X];if(!G||!F||!G.widget.canUpdate(F))break;if(G.widget!==F)G.update(F);Q.push(G),Y++,X++}let z=[];while(Y<=K&&X<=V){let G=J[K],F=Z[V];if(!G||!F||!G.widget.canUpdate(F))break;if(G.widget!==F)G.update(F);z.unshift(G),K--,V--}if(Y>K)for(let G=X;G<=V;G++){let F=Z[G];if(F){let q=this.createChildElement(F);Q.push(q)}}else if(X>V)for(let G=Y;G<=K;G++){let F=J[G];if(F)this.deactivateChild(F)}else{let G=new Map,F=new Map;for(let q=Y;q<=K;q++){let W=J[q];if(W.widget.key){let U=W.widget.key.toString();G.set(U,W),F.set(U,q)}}for(let q=X;q<=V;q++){let W=Z[q];if(!W)continue;let U;if(W.key){let H=W.key.toString();if(U=G.get(H),U){G.delete(H);let D=F.get(H);if(D!==void 0)J[D]=null;if(U.widget===W);else if(U.widget.canUpdate(W))U.update(W);else this.deactivateChild(U),U=this.createChildElement(W)}else U=this.createChildElement(W)}else{let H=!1;for(let D=Y;D<=K;D++){let B=J[D];if(B&&!B.widget.key){if(B.widget===W){U=B,J[D]=null,H=!0;break}else if(B.widget.canUpdate(W)){U=B,J[D]=null,U.update(W),H=!0;break}}}if(!H)U=this.createChildElement(W)}if(U)Q.push(U)}for(let q=Y;q<=K;q++){let W=J[q];if(W)this.deactivateChild(W)}for(let q of G.values())this.deactivateChild(q)}if(Q.push(...z),this._childElements=Q,this.renderObject){let G=[];for(let W of Q)if(W.renderObject)G.push(W.renderObject);let F=this.renderObject.children;if(F.length!==G.length||F.some((W,U)=>W!==G[U]))this.renderObject.replaceChildren(G)}}createChildElement(J){let Z=J.createElement();return this.addChild(Z),Z.mount(),Z}deactivateChild(J){J.unmount(),this.removeChild(J)}performRebuild(){}}class xK extends gi{constructor(J){super(J)}get leafWidget(){return this.widget}performRebuild(){}}class p0{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 Sz{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 Ej?J:void 0}return}}class l0 extends AJ{createElement(){return new Jo0(this)}}class Jo0 extends nY{_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 Sz(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 p5={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 Zo0{static hitTest(J,Z){let Q=new sP4;return J.hitTest(Q,Z),Q}}class sP4{_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 IY3(){let J=Ej.prototype;if(!J.hitTest)J.hitTest=function(Z,Q,Y=0,X=0){if("size"in this&&"offset"in this){let V=this,z=V.size,G=V.offset;if(z&&G){let F=Y+G.x,q=X+G.y,W=Q.x>=F&&Q.x<F+z.width,U=Q.y>=q&&Q.y<q+z.height;if(W&&U){let H={x:Q.x-F,y:Q.y-q};Z.add({target:this,localPosition:H});let D=this.children,B=!0;for(let N=D.length-1;N>=0;N--)if(D[N].hitTest(Z,Q,F,q))B=!0;return B}if(this.allowHitTestOutsideBounds){let H=!1,D=this.children;for(let B=D.length-1;B>=0;B--)if(D[B].hitTest(Z,Q,F,q))H=!0;return H}return!1}}let K=!1;for(let V of this.children)if(V.hitTest(Z,Q,Y,X))K=!0;return K}}IY3();function BH(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 tP4(J,Z,Q,Y=1){return{type:"click",button:J.button==="left"?"left":J.button==="middle"?"middle":J.button==="right"?"right":"left",clickCount:Y,...BH(J,Z,Q)}}function tY0(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,...BH(J,Z,Q)}}class A8{static _instance=null;static SCROLL_SESSION_TIMEOUT=200;_rootRenderObject=null;_hoveredRegions=new Set;_vaxis=null;_currentCursor=p5.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=A8.DOUBLE_CLICK_DISTANCE*A8.DOUBLE_CLICK_DISTANCE;_scratchCurrentRegions=new Set;_scratchEnteredRegions=new Set;_scratchExitedRegions=new Set;constructor(){}static get instance(){if(!A8._instance)A8._instance=new A8;return A8._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=Zo0.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 _Q&&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},z={type:"release",button:Y,...BH(J,Z,V)};X.handleMouseEvent(z)}else for(let{target:X,localPosition:K}of Q){let V={type:"release",button:Y,...BH(J,Z,K)};if(X.handleMouseEvent(V),X instanceof _Q&&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:z}of this._dragTargets){let G={x:Z.x-z.x,y:Z.y-z.y},F={type:"drag",button:Y,deltaX:X,deltaY:K,...BH(J,Z,G)};V.handleMouseEvent(F)}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=tP4(J,Z,K,Y);if(X.handleMouseEvent(V),X instanceof _Q&&X.opaque)break}}_handleScroll(J,Z,Q){let Y=Date.now();if(this._scrollSessionTarget&&this._scrollSessionTarget.attached&&Y-this._scrollSessionLastEvent<=A8.SCROLL_SESSION_TIMEOUT&&this._scrollSessionTarget){let V=Q.find((z)=>z.target===this._scrollSessionTarget);if(V){let z=tY0(J,Z,V.localPosition);this._scrollSessionTarget.onScroll?.(z)}else{let z=this._scrollSessionTarget.globalToLocal(Z),G=tY0(J,Z,{x:z.x,y:z.y});this._scrollSessionTarget.onScroll?.(G)}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 z=K[V];if(!z)continue;let G=tY0(J,Z,z.localPosition);if(z.target.onScroll?.(G)??!1){this._scrollSessionTarget=z.target,this._scrollSessionLastEvent=Y;return}}this._scrollSessionTarget=null,this._scrollSessionLastEvent=0}_handleMove(J,Z,Q){let Y=Q.filter((z)=>z.target instanceof _Q),X=this._scratchCurrentRegions,K=this._scratchExitedRegions,V=this._scratchEnteredRegions;X.clear();for(let{target:z}of Y)X.add(z);K.clear();for(let z of this._hoveredRegions)if(!X.has(z))K.add(z);V.clear();for(let z of X)if(!this._hoveredRegions.has(z))V.add(z);for(let z of K)if(z.onExit){let G={type:"exit",...BH(J,Z,Z)};z.handleMouseEvent(G)}for(let{target:z,localPosition:G}of Y)if(V.has(z)&&z.onEnter){let F={type:"enter",...BH(J,Z,G)};z.handleMouseEvent(F)}for(let{target:z,localPosition:G}of Y)if(z.onHover&&this._hoveredRegions.has(z)){let F={type:"hover",...BH(J,Z,G)};z.handleMouseEvent(F)}this._hoveredRegions.clear();for(let z of X)this._hoveredRegions.add(z);this._updateCursor(Y)}_updateCursor(J){if(!this._vaxis)return;let Z=p5.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 _Q&&Y.target.onScroll)Z.push({target:Y.target,localPosition:Y.localPosition});Q=K}return Z}_canHandleMouseEvents(J){if(J instanceof _Q)return!0;return typeof J.handleMouseEvent==="function"}clearHoverState(){if(this._hoveredRegions.clear(),this._dragTargets=[],this._vaxis&&this._currentCursor!==p5.DEFAULT)this._currentCursor=p5.DEFAULT,this._vaxis.setMouseCursor(p5.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<=A8.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<=A8.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(),A8._instance=null}}class Q4 extends n3{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:z,onDrag:G,cursor:F,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=z??null,this.onDrag=G??null,this.cursor=F??null,this.opaque=q}createElement(){return new eP4(this)}createRenderObject(){return new _Q({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 eP4 extends Dq{get mouseRegionWidget(){return this.widget}get renderObject(){return super.renderObject}}class _Q extends u4{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:z,opaque:G}){super();this.onClick=J,this.onEnter=Z,this.onExit=Q,this.onHover=Y,this.onScroll=X,this.onRelease=K,this.onDrag=V,this.cursor=z,this.opaque=G}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(Z6(!!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(){A8.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 s5 extends AJ{child;constructor({key:J,child:Z}){super(J!==void 0?{key:J}:{});this.child=Z}createElement(){return new $C4(this)}}class $C4 extends nY{_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 Mw{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:z,success:G,warning:F,info:q,destructive:W,selection:U,copyHighlight:H,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=z,this.success=G,this.warning=F,this.info=q,this.destructive=W,this.selection=U,this.copyHighlight=H,this.tableBorder=D}static default(){return new Mw({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 Mw({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 r9{colorScheme;constructor({colorScheme:J}){this.colorScheme=J}static default(){return new r9({colorScheme:Mw.default()})}static withRgb(J){return new r9({colorScheme:Mw.fromRgb(J)})}}class x1 extends s5{data;constructor({key:J,data:Z,child:Q}){super({key:J,child:Q});this.data=Z}static of(J){let Z=J.dependOnInheritedWidgetOfExactType(x1);if(Z)return Z.widget.data;return r9.default()}static maybeOf(J){let Z=J.dependOnInheritedWidgetOfExactType(x1);if(Z)return Z.widget.data;return null}updateShouldNotify(J){return this.data!==J.data}}function Qo0(J,Z,Q){return J+(Z-J)*Q}function eY0(J,Z,Q){let Y=Math.max(0,Math.min(1,Q));return{r:Math.round(Qo0(J.r,Z.r,Y)),g:Math.round(Qo0(J.g,Z.g,Y)),b:Math.round(Qo0(J.b,Z.b,Y))}}N$();var DC4=B4(UC4(),1),HC4=20;function Fo0(J){let Z=B$(J??"smart")??B$("smart");if(Z?.uiHints?.primaryColor&&Z.uiHints.secondaryColor)return{primary:Z.uiHints.primaryColor,secondary:Z.uiHints.secondaryColor};return{primary:Ff1,secondary:qf1}}function qo0(J,Z,Q){let Y=Math.max(0,Math.min(1,J)),{primary:X,secondary:K}=Q??Fo0(Z),V=eY0(X,K,Y);return{type:"rgb",value:{r:V.r,g:V.g,b:V.b}}}class Nq{_noise2D;_seed;constructor(J){this._seed=J??Date.now(),this._noise2D=DC4.makeNoise2D(this._seed)}get seed(){return this._seed}sample(J,Z,Q,Y=1){return(this._noise2D(J/HC4,Z/HC4+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 qo0(J,Z,Q)}}var Wo0=" .:-=+*#%@",lY3=" ",Mj=64,BC4=0.5,Aw=1,Uo0=30,Aj=3;class Ho0 extends l0{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:z,colorMode:G="intensity",primaryColor:F,secondaryColor:q,backgroundColor:W,t:U,onFrame:H,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=z,this.colorMode=G,this.primaryColor=F,this.secondaryColor=q,this.backgroundColor=W,this.t=U,this.onFrame=H,this.fps=D,this.seed=B,this.glow=N,this.shockwaves=w,this.onShockwave=L,this.onClick=O}createState(){return new NC4}}class NC4 extends p0{_t=0;_timer=null;_internalShockwaves=[];_glow;initState(){if(super.initState(),this._glow=this.widget.glow??new Nq(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<Aw),this.setState(()=>{})},1000/this.widget.fps)}didUpdateWidget(J){if(super.didUpdateWidget(J),this.widget.glow!==J.glow)this._glow=this.widget.glow??new Nq(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=x1.of(J),Q=this.widget.backgroundColor??Z.colorScheme.background,Y=new wC4({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 Q4({onClick:this.handleClick,child:Y})}}class wC4 extends x${props;constructor(J,Z){super(Z?{key:Z}:{});this.props=J}createElement(){return new xK(this)}createRenderObject(){return new Xv(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 Xv extends u4{_width;_height;_minWidth;_minHeight;_maxWidth;_maxHeight;_time;_agentMode;_colorMode;_primaryColor;_secondaryColor;_backgroundColor;_glow;_shockwaves;_palette=[];_paletteSignature="";constructor(J,Z,Q,Y,X,K,V,z,G,F,q,W,U,H=[]){super();this._width=J;this._height=Z;this._minWidth=Q;this._minHeight=Y;this._maxWidth=X;this._maxHeight=K;this._time=V;this._agentMode=z;this._colorMode=G;this._primaryColor=F;this._secondaryColor=q;this._backgroundColor=W;this._glow=U;this._shockwaves=H;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:Mj},(X,K)=>{let V=K/(Mj-1);return qo0(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,z,G,F,q,W,U,H=[]){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=z,this._colorMode=G,this._primaryColor=F,this._secondaryColor=q,this._backgroundColor=W,this._glow=U,this._shockwaves=H,this.getPaletteSignature(z,F,q)!==this._paletteSignature)this.rebuildPalette(z,F,q);if(D)this.markNeedsLayout();this.markNeedsPaint()}performLayout(){let J=this._lastConstraints;Z6(!!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(Mj-1,Math.floor(Y*Mj))}return Math.min(Mj-1,Math.floor(J*Mj))}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),z=J.getSize(),G=z.width,F=z.height,q=this._backgroundColor,W=this._palette,U=K/2,H=V/2,D=Math.max(1,K/2-1),B=Math.max(1,V/(2*BC4)-1),N=Math.min(D,B),w=N*N,L=1/w,O=1/BC4,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>=F)continue;let R=(A-H)*O,_=R*R;if(_>=w)continue;let T=Math.sqrt(w-_),u=Math.max(0,Math.floor(U-T)),m=Math.min(K-1,Math.ceil(U+T));for(let y=u;y<=m;y++){let k=y-U,f=k*k+_;if(f>=w)continue;let d=1-f*L,h=this._glow.sample(y,A,this._time,E)*d;if(h<=0)continue;if(M){let H0=f*L;if(H0<0.9025)for(let L0 of this._shockwaves){let z0=this._time-L0.startTime;if(z0<0||z0>Aw)continue;let J0=y-L0.x,G0=(A-L0.y)*O,i=J0*J0+G0*G0,o=z0*Uo0,t=Math.max(0,o-Aj),$0=o+Aj;if(i<t*t||i>$0*$0)continue;let F0=Math.sqrt(i),K0=Math.abs(F0-o);if(K0>=Aj)continue;let Z0=1-z0/Aw,Y0=(1-K0/Aj)*Z0,w0=Math.sqrt(H0),X0=1-H0*w0;h=Math.min(1,h+Y0*0.8*X0)}}let n=Math.min(Wo0.length-1,Math.floor(h*Wo0.length)),c=Wo0[n]||lY3,a=this.getPaletteIndex(h,R,N),W0=W[a]||W[Mj-1],r=Y+y;if(r<0||r>=G)continue;J.setCell(r,j,{char:c,width:1,style:{fg:W0,bg:q}})}}}}var tY3=sY3(iY3),eY3=Number.MAX_SAFE_INTEGER,$X3=30000,JX3=60000,ZX3=14400000,QX3=10,YX3=1000,XX3=5,KX3=80,VX3=3,LC4=3,CC4="Watching this thread for changes. Press Ctrl-C to stop.",zX3="Live sync paused after 4 hours to save the connection. Press Enter to resume.",jj=14,jw=7,GX3=42,wo0="[y/N]: ",TC4=aY.posix.join(".amp","live-sync.pid"),Kv=Symbol("live-sync-archived-transition"),ci=Symbol("live-sync-session-paused"),Vv=Symbol("live-sync-stop-requested"),FX3="\x1B[0m",qX3=/^Filesystem error \(([^)]+)\):/;function WX3(J,Z){let Q=new Map;for(let V of J?.available?J.files:[])Q.set(V.path,EC4(V));let Y=new Set(Z.files.map((V)=>V.path)),X=Z.files.filter((V)=>Q.get(V.path)!==EC4(V)),K=SC4([...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 Do0(J){let Z=J.filter((X)=>X.changeType==="untracked").length,Q=J.length-Z,Y=[];if(Q>0)Y.push(`${Q} changed ${i4(Q,"file")}`);if(Z>0)Y.push(`${Z} untracked ${i4(Z,"file")}`);return Y.length>0?Y.join(" and "):"0 files"}function UX3(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 HX3(J,Z=QX3){let Q=J.slice(0,Z).map((X)=>` ${UX3(X)}`),Y=J.length-Q.length;if(Y>0)Q.push(` ...and ${Y} more ${i4(Y,"file")}`);return Q.join(`
|
|
6216
6214
|
`)}async function zX0(J){let Z=await Iw(J,["status","--porcelain=v1","-z","--untracked-files=all"]);return qa0(Z.stdout).filter((Q)=>Q.path!==TC4).map((Q)=>({path:Q.path,changeType:Q.changeType,previousPath:Q.previousPath}))}async function DX3(J){await Iw(J,["reset","--hard","HEAD"]),await Iw(J,["clean","-fd","-e",TC4])}async function BX3(J){let Z=await zX0(J.repoRoot);if(Z.length===0)return;if(!await J.promptForYesNo([`Local checkout has ${Do0(Z)}:`,HX3(Z),"Clean them up before live sync starts?","This will discard tracked changes and delete untracked files.",wo0].join(`
|
|
@@ -7373,7 +7371,7 @@ Ctrl-X, Y, Z to unlock`;if(U){let f=F.text.replace(/`([^`]+)`/g,"$1")+`
|
|
|
7373
7371
|
`),K=[];for(let V=0;V<X.length;V++){let F=X[V].replace(/\b(SELECT|FROM|WHERE|GROUP BY|ORDER BY|HAVING|LIMIT|JOIN|LEFT JOIN|RIGHT JOIN|INNER JOIN|ON|AND|OR|AS|IN|NOT|NULL|IS|BETWEEN|LIKE|EXISTS|UNION|DISTINCT|COUNT|SUM|AVG|MIN|MAX|DATE|TIMESTAMP_TRUNC|TIMESTAMP_SUB|CURRENT_TIMESTAMP|INTERVAL|CASE|WHEN|THEN|ELSE|END|WITH|INSERT|UPDATE|DELETE|SET|VALUES|INTO|CREATE|ALTER|DROP|TRUE|FALSE|ASC|DESC)\b/gi,"\x00$1\x01").split(/(\x00[^\x01]+\x01)/);for(let q of F)if(q.startsWith("\x00")&&q.endsWith("\x01"))K.push(new C(q.slice(1,-1),new 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(`
|
|
7374
7372
|
`))}return new d0({decoration:{color:Q.colorScheme.background,border:c1.all(new g1(Y.app.keybind,1,"rounded"))},child:new n0({padding:C0.symmetric(0,1),child:new e({text:new C(void 0,void 0,K)})})})}}class K01 extends x${chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=jz0}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new Y01({chartData:this.chartData,highlightIndex:this.highlightIndex,showAxes:this.showAxes,colors:this.colors})}updateRenderObject(J){let Z=J;Z.chartData=this.chartData,Z.highlightIndex=this.highlightIndex,Z.showAxes=this.showAxes,Z.colors=this.colors,Z.markNeedsLayout()}}function wh4(J,Z,Q,Y,X,K,V){if(K<=0)return null;switch(J){case"horizontal-bar":{let z=Q;return z>=0&&z<K?z:null}case"bar":case"stacked-bar":{let z=V?v9:0,G=Y-z;if(G<=0)return null;let F=Z-z;if(F<0||F>=G)return null;let q=Math.max(1,Math.floor(G/K)),W=Math.floor(F/q);return W>=0&&W<K?W:null}case"line":case"sparkline":case"stacked-area":{let z=V?v9:0,G=Y-z;if(G<=0)return null;let F=Math.max(0,Math.min(G-1,Z-z));if(K===1)return 0;let q=G/(K-1),W=Math.round(F/q);return Math.max(0,Math.min(K-1,W))}default:return null}}function fR3(J,Z,Q,Y,X,K,V,z){if(X<=0||Z<0||Z>=X)return null;let G=2;switch(J){case"horizontal-bar":return{x:Math.floor(Q/2),y:Z};case"bar":case"stacked-bar":{let F=K?v9:0,q=Q-F,W=Y-(K?G:0);if(q<=0||W<=0)return null;let U=Math.max(1,Math.floor(q/X)),H=F+Z*U+Math.floor(U/2),D=z>0?V/z:0,B=Math.round((1-D)*(W-1));return{x:H,y:B}}case"line":case"sparkline":case"stacked-area":{let F=K?v9:0,q=Q-F,W=Y-(K?G:0);if(q<=0||W<=0)return null;let U=X>1?F+Math.round(Z/(X-1)*(q-1)):F+Math.floor(q/2),H=z>0?V/z:0,D=Math.round((1-H)*(W-1));return{x:U,y:D}}default:return null}}function uR3(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 bR3(J,Z,Q,Y,X){if(Q.length<=1){let z=Y(J.value),G=J.meta?` (${J.meta})`:"";return J.label.length+2+z.length+G.length}let K=J.label.length,V=0;for(let z of Q){let G=z.points[Z];if(!G)continue;V+=G.value;let F=2+z.name.length+2+Y(G.value).length;K=Math.max(K,F)}if(X){let z=9+Y(V).length;K=Math.max(K,z)}return K}function hR3(J,Z,Q,Y,X,K,V){let z;try{let D=x1.of(J),B=f0.of(J);z={foreground:D.colorScheme.foreground,background:D.colorScheme.background,border:B.app.keybind}}catch{z={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let G=new g({color:z.foreground,bold:!0}),F=new g({color:z.foreground}),q=new g({color:z.foreground,dim:!0}),W=[],U=new g({color:z.foreground,underline:!0}),H=(D,B)=>new C(B,U,void 0,iY0(D),()=>{u3(J,D)});if(Y.length<=1){if(W.push(new C(`${Z.label}: `,G)),Z.link)W.push(H(Z.link,K(Z.value)));else W.push(new C(K(Z.value),F));if(Z.meta)W.push(new C(` (${Z.meta})`,q))}else{let D=V==="stacked-bar"||V==="stacked-area";W.push(new C(`${Z.label}
|
|
7375
7373
|
`,G));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]??z.foreground;if(W.push(new C("● ",new g({color:O}))),W.push(new C(`${w.name}: `,q)),L.link)W.push(H(L.link,K(L.value)));else W.push(new C(K(L.value),F));if(N<Y.length-1||D)W.push(new C(`
|
|
7376
|
-
`))}if(D)W.push(new C(" ",q)),W.push(new C("Total: ",q)),W.push(new C(K(B),F))}return new d0({decoration:{color:z.background,border:c1.all(new g1(z.border,1,"rounded"))},child:new e({text:new C(void 0,void 0,W)})})}sO();m0();_7();QE();N$();y3();_2();Nd();CX();O$();rJ();ZQ();NA();d4();ug();SP();O1();m0();O$();class V01{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.1774852556-ge9c066"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await H40(Z,this.configService)}catch(Z){P.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class KL extends l0{props;constructor(J){super();this.props=J}createState(){return new Lh4}}class Lh4 extends p0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Z=(Q)=>{this.setState(()=>{this._state=Q(this._state)})};return this.widget.props.builder(J,Z,this._state)}}class Oh4 extends p0{controller=new r7;focusNode=new G6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,z=c1.all(new g1(Q.foreground,1,"solid")),G=new IZ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(H)=>{let D=H.trim();if(X&&D.length===0)return;this.widget.props.onSubmit(D)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new W1({children:[new d0({decoration:{color:Q.background},child:new e({text:new C(">",new g({color:Q.foreground}))})}),new y1({child:G})]}),q=new d0({padding:C0.symmetric(1,0),child:new e({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 U=new d0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,W)})});return new d0({decoration:{border:z,color:Q.background},padding:C0.all(1),child:new x0({children:[q,new R0({height:1}),F,new f3,U]})})}}class Ma extends l0{props;constructor(J){super();this.props=J}createState(){return new Oh4}}ZQ();import{mkdtemp as pR3,readFile as dR3,rmdir as cR3,unlink as lR3,writeFile as iR3}from"node:fs/promises";import{tmpdir as nR3}from"node:os";import Ch4 from"node:path";m0();m0();class Eh4{_listeners=new Set;_disposed=!1;addListener(J){if(this._disposed)throw Error("Cannot add listener to disposed ChangeNotifier");this._listeners.add(J)}removeListener(J){this._listeners.delete(J)}notifyListeners(){if(this._disposed)return;let J=Array.from(this._listeners);for(let Z of J)try{Z()}catch(Q){}}dispose(){this._disposed=!0,this._listeners.clear()}get disposed(){return this._disposed}get hasListeners(){return this._listeners.size>0}}class BR extends Eh4{_value;constructor(J){super();this._value=J}get value(){return this._value}set value(J){let Z=typeof J==="object"||this._value!==J;if(this._value=J,Z)this.notifyListeners()}}function Mh4(J,Z){let Q=()=>{Z()};return J.addListener(Q),{dispose:()=>J.removeListener(Q)}}class z01{builder;maintainState;_overlayState;_needsBuild=!0;constructor(J,Z=!1){this.builder=J;this.maintainState=Z}get mounted(){return this._overlayState!==void 0}remove(){if(this._overlayState)this._overlayState.remove(this)}markNeedsBuild(){if(this._needsBuild=!0,this._overlayState)this._overlayState._markNeedsRebuild()}_setOverlayState(J){this._overlayState=J}_needsRebuild(){return this._needsBuild}_clearNeedsRebuild(){this._needsBuild=!1}}class G01 extends n3{link;showWhenUnlinked;offset;constructor({key:J,link:Z,showWhenUnlinked:Q=!0,offset:Y={x:0,y:0},child:X}){super({key:J,child:X});this.link=Z,this.showWhenUnlinked=Q,this.offset=Y}createElement(){return new Dq(this)}createRenderObject(){return new Ah4(this.link,this.showWhenUnlinked,this.offset)}updateRenderObject(J){J.link=this.link,J.showWhenUnlinked=this.showWhenUnlinked,J.setFollowerOffset(this.offset)}}class Ah4 extends u4{_link;_showWhenUnlinked;_followerOffset;_cachedPosition=null;constructor(J,Z,Q){super();this._link=J,this._showWhenUnlinked=Z,this._followerOffset=Q}get link(){return this._link}set link(J){this._link=J,this._cachedPosition=null,this.markNeedsLayout()}get showWhenUnlinked(){return this._showWhenUnlinked}set showWhenUnlinked(J){if(this._showWhenUnlinked!==J)this._showWhenUnlinked=J,this.markNeedsLayout()}setFollowerOffset(J){if(this._followerOffset.x!==J.x||this._followerOffset.y!==J.y)this._followerOffset={...J},this.markNeedsLayout()}calculatePosition(){let J=this._link.getTargetTransform();if(!J)return null;return{x:J.position.x+this._followerOffset.x,y:J.position.y+this._followerOffset.y}}shouldShow(){return this._link.target!==null||this._showWhenUnlinked}performLayout(){let J=this._lastConstraints;if(Z6(!!J,"performLayout called without constraints"),!this.shouldShow()){this.setSize(0,0),super.performLayout();return}let Z=this.calculatePosition();if(this._cachedPosition=Z,Z)this.setOffset(Z.x,Z.y);if(this.children.length>0){let Q=this.children[0];Q.layout(J);let Y=Q.size;this.setSize(Y.width,Y.height)}else this.setSize(0,0);super.performLayout()}getCurrentPosition(){return this._cachedPosition}setOffset(J,Z){super.setOffset(J,Z)}paint(J,Z=0,Q=0){super.paint(J,Z,Q)}}m0();var gR3=500;class F01{_state;_textController=null;_lastText="";_triggers=[];_optionsBuilder=null;_onSelected=null;_pendingBuildTimer=null;_disposed=!1;constructor(){let J={trigger:null,options:[],selectedIndex:-1,isActive:!1,generationId:0};this._state=new BR(J)}get state(){return this._state}get currentState(){return this._state.value}initialize({textController:J,triggers:Z,optionsBuilder:Q,onSelected:Y}){if(this._disposed)throw Error("Cannot initialize disposed AutocompleteController");this._cleanup(),this._textController=J,this._lastText=J.text,this._triggers=Z,this._optionsBuilder=Q,this._onSelected=Y||null,this._textController.addListener(this._handleTextChange)}selectNext(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex<J.options.length-1?J.selectedIndex+1:0;this._updateState({selectedIndex:Z})}selectPrevious(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex>0?J.selectedIndex-1:J.options.length-1;this._updateState({selectedIndex:Z})}acceptSelected(){let J=this.currentState;if(!J.isActive||J.selectedIndex<0||J.selectedIndex>=J.options.length)return;let Z=J.options[J.selectedIndex];if(!Z)return;if(this.dismiss(),this._onSelected)this._onSelected(Z)}dismiss(){this._clearPendingBuildTimer(),this._updateState({trigger:null,options:[],selectedIndex:-1,isActive:!1})}dispose(){this._disposed=!0,this._cleanup(),this._state.dispose()}_handleTextChange=()=>{if(!this._textController||!this._optionsBuilder)return;let J=this.currentState.trigger,Z=this._textController.text,Q=Z!==this._lastText;if(this._lastText=Z,!Q&&!this.currentState.isActive)return;let Y=this._textController.cursorPosition,X=null;for(let z of this._triggers){let G=z.detect(Z,Y);if(G&&(!X||G.start>X.start))X=G}if(!this.currentState.isActive&&X&&X.query.length>0){let z=f6(Z),G=Y,F=G;while(F<z.length){let q=z[F];if(q&&/[\s)\]}@]/.test(q))break;F++}if(F>G){let W=[...z.slice(0,G),...z.slice(F)].join("");this._textController.text=W,this._textController.cursorPosition=Y;return}}if(!X){if(this.currentState.isActive)this.dismiss();else this._clearPendingBuildTimer();return}let K=Q&&this._shouldDebounceBuild(J,X),V=this.currentState.generationId+1;if(this._updateState({trigger:X,generationId:V,options:K?[]:this.currentState.options,isActive:!K,selectedIndex:-1}),K){this._scheduleDebouncedBuild(X.query,V);return}this._clearPendingBuildTimer(),this._buildOptions(X.query,V)};async _buildOptions(J,Z){if(!this._optionsBuilder)return;try{let Q=await this._optionsBuilder(J);if(this.currentState.generationId===Z&&!this._disposed)this._updateState({options:Q,selectedIndex:Q.length>0?0:-1,isActive:Q.length>0})}catch(Q){if(P.error("Error building autocomplete options:",Q),this.currentState.generationId===Z&&!this._disposed)this._updateState({options:[],selectedIndex:-1,isActive:!1})}}_scheduleDebouncedBuild(J,Z){this._clearPendingBuildTimer(),this._pendingBuildTimer=setTimeout(()=>{this._pendingBuildTimer=null,this._buildOptions(J,Z)},gR3)}_shouldDebounceBuild(J,Z){if(!J)return!1;if(J.trigger!==Z.trigger||J.start!==Z.start)return!1;return Z.query.length<J.query.length}_clearPendingBuildTimer(){if(this._pendingBuildTimer)clearTimeout(this._pendingBuildTimer),this._pendingBuildTimer=null}_updateState(J){if(this._disposed)return;this._state.value={...this.currentState,...J}}_cleanup(){if(this._clearPendingBuildTimer(),this._textController)this._textController.removeListener(this._handleTextChange)}}class Aa{}class ja{}class Ra{}class Iz0{}class Pz0 extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new jh4(this.props)}}class jh4 extends p0{props;controller;stateListener=null;overlayEntry=null;layerLink=new wa;scrollOffset=0;_effectiveFocusNode;_cachedMaxVisibleOptions=0;constructor(J){super();this.props=J}initState(){if(super.initState(),this._effectiveFocusNode=this.props.focusNode||new G6({debugLabel:"AutocompleteFocusOwned"}),this.controller=new F01,this.controller.initialize({textController:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.props.optionsBuilder,onSelected:this.props.onSelected}),this.stateListener=Mh4(this.controller.state,()=>{this.updateOverlay(),this.setState(()=>{})}),this.props.handle)this.props.handle.dismiss=()=>this.controller.dismiss();if(this.props.autofocus??!0)C6.instance.addPostFrameCallback(()=>{this._effectiveFocusNode.requestFocus()})}didUpdateWidget(J){super.didUpdateWidget(J);let Z=J.props,Q=this.widget.props;if(this.props=Q,Z.controller!==Q.controller||Z.triggers!==Q.triggers||Z.optionsBuilder!==Q.optionsBuilder||Z.textFieldProps!==Q.textFieldProps||Z.onSelected!==Q.onSelected)this.controller.initialize({textController:Q.controller,triggers:Q.triggers,optionsBuilder:Q.optionsBuilder,onSelected:Q.onSelected});if(Z.handle!==Q.handle){if(Q.handle)Q.handle.dismiss=()=>this.controller.dismiss()}this.setState(()=>{})}dispose(){this.removeOverlay(),this.stateListener?.dispose(),this.controller.dispose(),this._effectiveFocusNode.dispose(),super.dispose()}invoke=(J)=>{if(!this.controller.currentState.isActive)return"ignored";if(J instanceof Aa)return this.controller.selectNext(),this.updateScrollPosition(),"handled";if(J instanceof ja)return this.controller.selectPrevious(),this.updateScrollPosition(),"handled";if(J instanceof Ra)return this.controller.acceptSelected(),"handled";if(J instanceof Iz0)return this.controller.dismiss(),"handled";return"ignored"};updateScrollPosition(){let J=this.controller.currentState;if(!J.isActive||J.selectedIndex<0)return;let Z=J.selectedIndex,Q=J.options.length,Y=this._cachedMaxVisibleOptions||Q;if(Y>=Q){this.scrollOffset=0;return}let X=Z-this.scrollOffset,K=1,V=this.scrollOffset;if(X>=Y-K)V=Math.max(0,Z-(Y-K-1));if(X<K)V=Math.max(0,Z-K);let z=Math.max(0,Q-Y);V=Math.min(V,z),this.scrollOffset=V}build(J){let Z=new IZ({...this.props.textFieldProps,controller:this.props.controller,focusNode:this._effectiveFocusNode,autofocus:!1}),Q=new m$({shortcuts:new Map([[new D4("ArrowDown"),new Aa],[new D4("ArrowUp"),new ja],[new D4("n",{ctrl:!0}),new Aa],[new D4("p",{ctrl:!0}),new ja],[new D4("Enter"),new Ra],[new D4("Escape"),new Iz0],[new D4("Tab"),new Ra]]),focusNode:this._effectiveFocusNode,child:Z}),Y=new M7({actions:new Map([[Aa,new D6(this.invoke)],[ja,new D6(this.invoke)],[Ra,new D6(this.invoke)],[Iz0,new D6(this.invoke)]]),child:Q});return new Na({link:this.layerLink,child:Y})}updateOverlay(){let J=this.controller.currentState;if(J.isActive&&J.options.length>0)if(!this.overlayEntry)this.createOverlay();else this.overlayEntry.markNeedsBuild();else this.removeOverlay()}createOverlay(){if(this.overlayEntry)return;this.overlayEntry=new z01((J)=>{let Z=this.controller.currentState;return this.buildOverlayContent(J,Z)});try{UR.of(this.context).insert(this.overlayEntry)}catch(J){P.error("Failed to insert autocomplete overlay:",J),this.overlayEntry=null}}removeOverlay(){if(this.overlayEntry)this.overlayEntry.remove(),this.overlayEntry=null}buildOverlayHints(J,Z){if(this.props.overlayHint!==void 0){if(this.props.overlayHint===null)return[];let{prefix:Q,suffix:Y}=this.props.overlayHint,X=[];if(Q)X.push(new C(Q,new g({color:f0.of(J).app.command})),new C(" ",new g({color:Z})));return X.push(new C(Y,new g({color:Z}))),[{child:new e({text:new C(" ",new g({dim:!0}),X)}),position:"top",alignment:"center"}]}return[]}buildOverlayContent(J,Z){let Q=x1.maybeOf(J),Y=Q?.colorScheme.background??M0.default(),X=this.props.overlayBorderColor??Q?.colorScheme.border??M0.default(),K=Z.options.length,V=V4.sizeOf(J).height,z=0;try{let R=this.layerLink.getTargetTransform();if(R)z=R.position.y}catch{}let G=this.props.autoOverlayPosition?z<V/3:!1,F=2,q;if(G){let R=this.props.controller.getCursorVisualRow(),_=z+R+1;q=V-_-F}else q=z-F;K=Math.min(K,Math.max(1,q)),this._cachedMaxVisibleOptions=K,this.updateScrollPosition();let W=this.scrollOffset,U=Math.min(Z.options.length,W+K),H=[],D=0;for(let R=W;R<U;R++){let _=Z.options[R];if(!_)continue;let T=R===Z.selectedIndex,u,m;if(this.props.optionViewBuilder){u=this.props.optionViewBuilder(J,_,T);let f=this.props.displayStringForOption?.(_)??String(_),d="",p=f,h=_;if(h&&typeof h==="object"&&"type"in h)switch(h.type){case"file":d="@",p=h.path||f;break;case"artifact":d="",p=h.label||f;break}m=d+p}else{let f=this.props.displayStringForOption?.(_)??String(_),d=Q?.colorScheme.selection??M0.default(),p=Q?.colorScheme.foreground??M0.default();u=new e({text:new C(f,new g({color:p,backgroundColor:T?d:void 0}))}),m=f}let y=V4.of(J),k=x5(m,y.supportsEmojiWidth);D=Math.max(D,k),H.push(u)}let B=V4.sizeOf(J).width,N=D+4,w=Math.floor(B*0.9),L=Math.max(Math.min(N,w),Math.min(30,w)),M=H.length+2,A;if(G)A=this.props.controller.getCursorVisualRow()+1;else A=-M;let j=new R0({width:L,child:new d0({height:M,decoration:new $6(Y),child:new s8({decoration:{border:c1.all(new g1(X,1,"rounded"))},padding:C0.symmetric(1,0),overlays:this.buildOverlayHints(J,X),child:new x0({crossAxisAlignment:"start",children:H})})})});return new G01({link:this.layerLink,showWhenUnlinked:!1,offset:{x:0,y:A},child:j})}}function Rh4(J){if(J.kind!=="file"&&J.kind!=="folder")throw Error("Invalid completion item: missing path or kind");return{type:"file",path:J.path,kind:J.kind}}function Ih4(J){switch(J.type){case"file":return J.path;case"hint":return`${mR3(J.kind)} ${J.message}`;case"commit":return`${J.shortHash} ${J.message} (${J.relativeDate})`}}function Ph4(J){switch(J.type){case"file":return;case"hint":return;case"commit":return}}function mR3(J){switch(J){case"commit":return"@:";case"thread":return"@@"}}class vq{detect(J,Z){if(!J||Z<1)return null;let Q=f6(J);if(Z>Q.length)return null;let Y=this.findWordStart(Q,Z);if(Y>=Q.length||Q[Y]!=="@")return null;let X=Q.slice(Y+1,Z).join("");if(X.includes(" ")||X.includes("\t")||X.includes(`
|
|
7374
|
+
`))}if(D)W.push(new C(" ",q)),W.push(new C("Total: ",q)),W.push(new C(K(B),F))}return new d0({decoration:{color:z.background,border:c1.all(new g1(z.border,1,"rounded"))},child:new e({text:new C(void 0,void 0,W)})})}sO();m0();_7();QE();N$();y3();_2();Nd();CX();O$();rJ();ZQ();NA();d4();ug();SP();O1();m0();O$();class V01{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.1774866438-g7cb400"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await H40(Z,this.configService)}catch(Z){P.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class KL extends l0{props;constructor(J){super();this.props=J}createState(){return new Lh4}}class Lh4 extends p0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Z=(Q)=>{this.setState(()=>{this._state=Q(this._state)})};return this.widget.props.builder(J,Z,this._state)}}class Oh4 extends p0{controller=new r7;focusNode=new G6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,z=c1.all(new g1(Q.foreground,1,"solid")),G=new IZ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(H)=>{let D=H.trim();if(X&&D.length===0)return;this.widget.props.onSubmit(D)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new W1({children:[new d0({decoration:{color:Q.background},child:new e({text:new C(">",new g({color:Q.foreground}))})}),new y1({child:G})]}),q=new d0({padding:C0.symmetric(1,0),child:new e({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 U=new d0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,W)})});return new d0({decoration:{border:z,color:Q.background},padding:C0.all(1),child:new x0({children:[q,new R0({height:1}),F,new f3,U]})})}}class Ma extends l0{props;constructor(J){super();this.props=J}createState(){return new Oh4}}ZQ();import{mkdtemp as pR3,readFile as dR3,rmdir as cR3,unlink as lR3,writeFile as iR3}from"node:fs/promises";import{tmpdir as nR3}from"node:os";import Ch4 from"node:path";m0();m0();class Eh4{_listeners=new Set;_disposed=!1;addListener(J){if(this._disposed)throw Error("Cannot add listener to disposed ChangeNotifier");this._listeners.add(J)}removeListener(J){this._listeners.delete(J)}notifyListeners(){if(this._disposed)return;let J=Array.from(this._listeners);for(let Z of J)try{Z()}catch(Q){}}dispose(){this._disposed=!0,this._listeners.clear()}get disposed(){return this._disposed}get hasListeners(){return this._listeners.size>0}}class BR extends Eh4{_value;constructor(J){super();this._value=J}get value(){return this._value}set value(J){let Z=typeof J==="object"||this._value!==J;if(this._value=J,Z)this.notifyListeners()}}function Mh4(J,Z){let Q=()=>{Z()};return J.addListener(Q),{dispose:()=>J.removeListener(Q)}}class z01{builder;maintainState;_overlayState;_needsBuild=!0;constructor(J,Z=!1){this.builder=J;this.maintainState=Z}get mounted(){return this._overlayState!==void 0}remove(){if(this._overlayState)this._overlayState.remove(this)}markNeedsBuild(){if(this._needsBuild=!0,this._overlayState)this._overlayState._markNeedsRebuild()}_setOverlayState(J){this._overlayState=J}_needsRebuild(){return this._needsBuild}_clearNeedsRebuild(){this._needsBuild=!1}}class G01 extends n3{link;showWhenUnlinked;offset;constructor({key:J,link:Z,showWhenUnlinked:Q=!0,offset:Y={x:0,y:0},child:X}){super({key:J,child:X});this.link=Z,this.showWhenUnlinked=Q,this.offset=Y}createElement(){return new Dq(this)}createRenderObject(){return new Ah4(this.link,this.showWhenUnlinked,this.offset)}updateRenderObject(J){J.link=this.link,J.showWhenUnlinked=this.showWhenUnlinked,J.setFollowerOffset(this.offset)}}class Ah4 extends u4{_link;_showWhenUnlinked;_followerOffset;_cachedPosition=null;constructor(J,Z,Q){super();this._link=J,this._showWhenUnlinked=Z,this._followerOffset=Q}get link(){return this._link}set link(J){this._link=J,this._cachedPosition=null,this.markNeedsLayout()}get showWhenUnlinked(){return this._showWhenUnlinked}set showWhenUnlinked(J){if(this._showWhenUnlinked!==J)this._showWhenUnlinked=J,this.markNeedsLayout()}setFollowerOffset(J){if(this._followerOffset.x!==J.x||this._followerOffset.y!==J.y)this._followerOffset={...J},this.markNeedsLayout()}calculatePosition(){let J=this._link.getTargetTransform();if(!J)return null;return{x:J.position.x+this._followerOffset.x,y:J.position.y+this._followerOffset.y}}shouldShow(){return this._link.target!==null||this._showWhenUnlinked}performLayout(){let J=this._lastConstraints;if(Z6(!!J,"performLayout called without constraints"),!this.shouldShow()){this.setSize(0,0),super.performLayout();return}let Z=this.calculatePosition();if(this._cachedPosition=Z,Z)this.setOffset(Z.x,Z.y);if(this.children.length>0){let Q=this.children[0];Q.layout(J);let Y=Q.size;this.setSize(Y.width,Y.height)}else this.setSize(0,0);super.performLayout()}getCurrentPosition(){return this._cachedPosition}setOffset(J,Z){super.setOffset(J,Z)}paint(J,Z=0,Q=0){super.paint(J,Z,Q)}}m0();var gR3=500;class F01{_state;_textController=null;_lastText="";_triggers=[];_optionsBuilder=null;_onSelected=null;_pendingBuildTimer=null;_disposed=!1;constructor(){let J={trigger:null,options:[],selectedIndex:-1,isActive:!1,generationId:0};this._state=new BR(J)}get state(){return this._state}get currentState(){return this._state.value}initialize({textController:J,triggers:Z,optionsBuilder:Q,onSelected:Y}){if(this._disposed)throw Error("Cannot initialize disposed AutocompleteController");this._cleanup(),this._textController=J,this._lastText=J.text,this._triggers=Z,this._optionsBuilder=Q,this._onSelected=Y||null,this._textController.addListener(this._handleTextChange)}selectNext(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex<J.options.length-1?J.selectedIndex+1:0;this._updateState({selectedIndex:Z})}selectPrevious(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex>0?J.selectedIndex-1:J.options.length-1;this._updateState({selectedIndex:Z})}acceptSelected(){let J=this.currentState;if(!J.isActive||J.selectedIndex<0||J.selectedIndex>=J.options.length)return;let Z=J.options[J.selectedIndex];if(!Z)return;if(this.dismiss(),this._onSelected)this._onSelected(Z)}dismiss(){this._clearPendingBuildTimer(),this._updateState({trigger:null,options:[],selectedIndex:-1,isActive:!1})}dispose(){this._disposed=!0,this._cleanup(),this._state.dispose()}_handleTextChange=()=>{if(!this._textController||!this._optionsBuilder)return;let J=this.currentState.trigger,Z=this._textController.text,Q=Z!==this._lastText;if(this._lastText=Z,!Q&&!this.currentState.isActive)return;let Y=this._textController.cursorPosition,X=null;for(let z of this._triggers){let G=z.detect(Z,Y);if(G&&(!X||G.start>X.start))X=G}if(!this.currentState.isActive&&X&&X.query.length>0){let z=f6(Z),G=Y,F=G;while(F<z.length){let q=z[F];if(q&&/[\s)\]}@]/.test(q))break;F++}if(F>G){let W=[...z.slice(0,G),...z.slice(F)].join("");this._textController.text=W,this._textController.cursorPosition=Y;return}}if(!X){if(this.currentState.isActive)this.dismiss();else this._clearPendingBuildTimer();return}let K=Q&&this._shouldDebounceBuild(J,X),V=this.currentState.generationId+1;if(this._updateState({trigger:X,generationId:V,options:K?[]:this.currentState.options,isActive:!K,selectedIndex:-1}),K){this._scheduleDebouncedBuild(X.query,V);return}this._clearPendingBuildTimer(),this._buildOptions(X.query,V)};async _buildOptions(J,Z){if(!this._optionsBuilder)return;try{let Q=await this._optionsBuilder(J);if(this.currentState.generationId===Z&&!this._disposed)this._updateState({options:Q,selectedIndex:Q.length>0?0:-1,isActive:Q.length>0})}catch(Q){if(P.error("Error building autocomplete options:",Q),this.currentState.generationId===Z&&!this._disposed)this._updateState({options:[],selectedIndex:-1,isActive:!1})}}_scheduleDebouncedBuild(J,Z){this._clearPendingBuildTimer(),this._pendingBuildTimer=setTimeout(()=>{this._pendingBuildTimer=null,this._buildOptions(J,Z)},gR3)}_shouldDebounceBuild(J,Z){if(!J)return!1;if(J.trigger!==Z.trigger||J.start!==Z.start)return!1;return Z.query.length<J.query.length}_clearPendingBuildTimer(){if(this._pendingBuildTimer)clearTimeout(this._pendingBuildTimer),this._pendingBuildTimer=null}_updateState(J){if(this._disposed)return;this._state.value={...this.currentState,...J}}_cleanup(){if(this._clearPendingBuildTimer(),this._textController)this._textController.removeListener(this._handleTextChange)}}class Aa{}class ja{}class Ra{}class Iz0{}class Pz0 extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new jh4(this.props)}}class jh4 extends p0{props;controller;stateListener=null;overlayEntry=null;layerLink=new wa;scrollOffset=0;_effectiveFocusNode;_cachedMaxVisibleOptions=0;constructor(J){super();this.props=J}initState(){if(super.initState(),this._effectiveFocusNode=this.props.focusNode||new G6({debugLabel:"AutocompleteFocusOwned"}),this.controller=new F01,this.controller.initialize({textController:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.props.optionsBuilder,onSelected:this.props.onSelected}),this.stateListener=Mh4(this.controller.state,()=>{this.updateOverlay(),this.setState(()=>{})}),this.props.handle)this.props.handle.dismiss=()=>this.controller.dismiss();if(this.props.autofocus??!0)C6.instance.addPostFrameCallback(()=>{this._effectiveFocusNode.requestFocus()})}didUpdateWidget(J){super.didUpdateWidget(J);let Z=J.props,Q=this.widget.props;if(this.props=Q,Z.controller!==Q.controller||Z.triggers!==Q.triggers||Z.optionsBuilder!==Q.optionsBuilder||Z.textFieldProps!==Q.textFieldProps||Z.onSelected!==Q.onSelected)this.controller.initialize({textController:Q.controller,triggers:Q.triggers,optionsBuilder:Q.optionsBuilder,onSelected:Q.onSelected});if(Z.handle!==Q.handle){if(Q.handle)Q.handle.dismiss=()=>this.controller.dismiss()}this.setState(()=>{})}dispose(){this.removeOverlay(),this.stateListener?.dispose(),this.controller.dispose(),this._effectiveFocusNode.dispose(),super.dispose()}invoke=(J)=>{if(!this.controller.currentState.isActive)return"ignored";if(J instanceof Aa)return this.controller.selectNext(),this.updateScrollPosition(),"handled";if(J instanceof ja)return this.controller.selectPrevious(),this.updateScrollPosition(),"handled";if(J instanceof Ra)return this.controller.acceptSelected(),"handled";if(J instanceof Iz0)return this.controller.dismiss(),"handled";return"ignored"};updateScrollPosition(){let J=this.controller.currentState;if(!J.isActive||J.selectedIndex<0)return;let Z=J.selectedIndex,Q=J.options.length,Y=this._cachedMaxVisibleOptions||Q;if(Y>=Q){this.scrollOffset=0;return}let X=Z-this.scrollOffset,K=1,V=this.scrollOffset;if(X>=Y-K)V=Math.max(0,Z-(Y-K-1));if(X<K)V=Math.max(0,Z-K);let z=Math.max(0,Q-Y);V=Math.min(V,z),this.scrollOffset=V}build(J){let Z=new IZ({...this.props.textFieldProps,controller:this.props.controller,focusNode:this._effectiveFocusNode,autofocus:!1}),Q=new m$({shortcuts:new Map([[new D4("ArrowDown"),new Aa],[new D4("ArrowUp"),new ja],[new D4("n",{ctrl:!0}),new Aa],[new D4("p",{ctrl:!0}),new ja],[new D4("Enter"),new Ra],[new D4("Escape"),new Iz0],[new D4("Tab"),new Ra]]),focusNode:this._effectiveFocusNode,child:Z}),Y=new M7({actions:new Map([[Aa,new D6(this.invoke)],[ja,new D6(this.invoke)],[Ra,new D6(this.invoke)],[Iz0,new D6(this.invoke)]]),child:Q});return new Na({link:this.layerLink,child:Y})}updateOverlay(){let J=this.controller.currentState;if(J.isActive&&J.options.length>0)if(!this.overlayEntry)this.createOverlay();else this.overlayEntry.markNeedsBuild();else this.removeOverlay()}createOverlay(){if(this.overlayEntry)return;this.overlayEntry=new z01((J)=>{let Z=this.controller.currentState;return this.buildOverlayContent(J,Z)});try{UR.of(this.context).insert(this.overlayEntry)}catch(J){P.error("Failed to insert autocomplete overlay:",J),this.overlayEntry=null}}removeOverlay(){if(this.overlayEntry)this.overlayEntry.remove(),this.overlayEntry=null}buildOverlayHints(J,Z){if(this.props.overlayHint!==void 0){if(this.props.overlayHint===null)return[];let{prefix:Q,suffix:Y}=this.props.overlayHint,X=[];if(Q)X.push(new C(Q,new g({color:f0.of(J).app.command})),new C(" ",new g({color:Z})));return X.push(new C(Y,new g({color:Z}))),[{child:new e({text:new C(" ",new g({dim:!0}),X)}),position:"top",alignment:"center"}]}return[]}buildOverlayContent(J,Z){let Q=x1.maybeOf(J),Y=Q?.colorScheme.background??M0.default(),X=this.props.overlayBorderColor??Q?.colorScheme.border??M0.default(),K=Z.options.length,V=V4.sizeOf(J).height,z=0;try{let R=this.layerLink.getTargetTransform();if(R)z=R.position.y}catch{}let G=this.props.autoOverlayPosition?z<V/3:!1,F=2,q;if(G){let R=this.props.controller.getCursorVisualRow(),_=z+R+1;q=V-_-F}else q=z-F;K=Math.min(K,Math.max(1,q)),this._cachedMaxVisibleOptions=K,this.updateScrollPosition();let W=this.scrollOffset,U=Math.min(Z.options.length,W+K),H=[],D=0;for(let R=W;R<U;R++){let _=Z.options[R];if(!_)continue;let T=R===Z.selectedIndex,u,m;if(this.props.optionViewBuilder){u=this.props.optionViewBuilder(J,_,T);let f=this.props.displayStringForOption?.(_)??String(_),d="",p=f,h=_;if(h&&typeof h==="object"&&"type"in h)switch(h.type){case"file":d="@",p=h.path||f;break;case"artifact":d="",p=h.label||f;break}m=d+p}else{let f=this.props.displayStringForOption?.(_)??String(_),d=Q?.colorScheme.selection??M0.default(),p=Q?.colorScheme.foreground??M0.default();u=new e({text:new C(f,new g({color:p,backgroundColor:T?d:void 0}))}),m=f}let y=V4.of(J),k=x5(m,y.supportsEmojiWidth);D=Math.max(D,k),H.push(u)}let B=V4.sizeOf(J).width,N=D+4,w=Math.floor(B*0.9),L=Math.max(Math.min(N,w),Math.min(30,w)),M=H.length+2,A;if(G)A=this.props.controller.getCursorVisualRow()+1;else A=-M;let j=new R0({width:L,child:new d0({height:M,decoration:new $6(Y),child:new s8({decoration:{border:c1.all(new g1(X,1,"rounded"))},padding:C0.symmetric(1,0),overlays:this.buildOverlayHints(J,X),child:new x0({crossAxisAlignment:"start",children:H})})})});return new G01({link:this.layerLink,showWhenUnlinked:!1,offset:{x:0,y:A},child:j})}}function Rh4(J){if(J.kind!=="file"&&J.kind!=="folder")throw Error("Invalid completion item: missing path or kind");return{type:"file",path:J.path,kind:J.kind}}function Ih4(J){switch(J.type){case"file":return J.path;case"hint":return`${mR3(J.kind)} ${J.message}`;case"commit":return`${J.shortHash} ${J.message} (${J.relativeDate})`}}function Ph4(J){switch(J.type){case"file":return;case"hint":return;case"commit":return}}function mR3(J){switch(J){case"commit":return"@:";case"thread":return"@@"}}class vq{detect(J,Z){if(!J||Z<1)return null;let Q=f6(J);if(Z>Q.length)return null;let Y=this.findWordStart(Q,Z);if(Y>=Q.length||Q[Y]!=="@")return null;let X=Q.slice(Y+1,Z).join("");if(X.includes(" ")||X.includes("\t")||X.includes(`
|
|
7377
7375
|
`))return null;return{start:Y,end:Z,query:X,trigger:"@"}}findWordStart(J,Z){let Q=Z;for(let Y=Z-1;Y>=0;Y--){let X=J[Y];if(!X||/[\s([{]/.test(X)){Q=Y+1;break}if(Y===0)Q=0}return Q}}class NR extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new Th4(this.props)}}var aR3=":";class Th4 extends p0{props;_effectiveFocusNode;_textChangeListener=null;_isCommitMode=!1;_imageUploadSpinner=new V3;_imageUploadSpinnerInterval=null;constructor(J){super();this.props=J}buildOptions=async(J)=>{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=new vq().detect(Z,Q);if(X&&this.props.completionBuilder){if(X.query==="@"&&this.props.onDoubleAtTrigger)return this.props.onDoubleAtTrigger(this.props.controller),[];let z=X.query.toLowerCase().startsWith(aR3);if(z!==this._isCommitMode)this._isCommitMode=z,this.setState();return await this.props.completionBuilder.buildOptions(X)}if(this._isCommitMode)this._isCommitMode=!1,this.setState();return[]};defaultOnOptionSelected=(J)=>{switch(J.type){case"hint":{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=Z.slice(0,Q).lastIndexOf("@");if(X!==-1){let K=Z.slice(0,X),V=Z.slice(Q),z=J.kind==="commit"?"@:":"@@",G=K+z+V;this.props.controller.clear(),this.props.controller.insertText(G),this.props.controller.cursorPosition=X+z.length}return}case"file":{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=Z.slice(0,Q).lastIndexOf("@");if(X!==-1){let K=Z.slice(0,X),V=Z.slice(Q),z=K+`@${J.path} `+V;this.props.controller.clear(),this.props.controller.insertText(z),this.props.controller.cursorPosition=X+1+J.path.length+1}break}case"commit":{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=Z.slice(0,Q).lastIndexOf("@");if(X!==-1){let K=Z.slice(0,X),V=Z.slice(Q),z=`git-commit(${J.hash})`,G=K+z+" "+V;this.props.controller.clear(),this.props.controller.insertText(G),this.props.controller.cursorPosition=X+z.length+1}break}}};initState(){super.initState(),this._effectiveFocusNode=this.props.focusNode||new G6({debugLabel:"PromptEditorFocus"}),this._textChangeListener=()=>{this.setState()},this.props.controller.addListener(this._textChangeListener),this.props.controller.onInsertText=(J,Z)=>{if(J.length<=3)return!0;let Q=Lb4(J);if(Q.length===0)return!0;if(this.props.onInsertImage){for(let Y of Q)this.props.onInsertImage(Y);return!1}return!0},this.syncImageUploadSpinner()}didUpdateWidget(J){super.didUpdateWidget(J),this.props=this.widget.props,this.syncImageUploadSpinner()}dispose(){if(this._imageUploadSpinnerInterval)clearInterval(this._imageUploadSpinnerInterval),this._imageUploadSpinnerInterval=null;if(this._textChangeListener)this.props.controller.removeListener(this._textChangeListener),this._textChangeListener=null;if(!this.props.focusNode)this._effectiveFocusNode.dispose();super.dispose()}syncImageUploadSpinner(){if(this.props.showImageUploadSpinner===!0){if(!this._imageUploadSpinnerInterval)this._imageUploadSpinnerInterval=setInterval(()=>{this._imageUploadSpinner.step(),this.setState()},120);return}if(this._imageUploadSpinnerInterval)clearInterval(this._imageUploadSpinnerInterval),this._imageUploadSpinnerInterval=null}_handleOpenInEditor=async(J)=>{try{let Z=await pR3(Ch4.join(nR3(),"amp-edit-")),Q=Ch4.join(Z,"message.amp.md");await iR3(Q,J,"utf-8"),await hK(Q);try{let Y=await dR3(Q,"utf-8");this.props.controller.text=Y}catch(Y){if(Y?.code!=="ENOENT")P.error("Failed to read temporary file",Y)}try{await lR3(Q),await cR3(Z)}catch(Y){P.warn("Failed to clean up temporary file",Y)}}catch(Z){P.error("Error opening editor:",Z)}};_handleBackspaceAtStart=()=>{if(this.props.imageAttachments.length>0&&this.props.popImage)return this.props.popImage(),!0;if((this.props.pendingSkills??[]).length>0&&this.props.popSkill)return this.props.popSkill(),!0;return!1};_handleSubmitted=(J)=>{if(this.props.previousThreadId&&J.trim()===""){this.props.onPreviousThreadHintAccepted?.();return}this.props.onSubmitted?.(J)};build(J){let Z=this.props.theme,Q=this.props.pendingSkills??[],Y=this.props.imageAttachments.length>0,X=Q.length>0?new W1({mainAxisSize:"min",children:[new e({text:new C("Skills: ",new g({color:Z.foreground,dim:!0}))}),...Q.flatMap((G,F)=>{let q=new Q4({onClick:()=>{this.props.onSkillClick?.(F)},cursor:"pointer",child:new e({text:new C(G.name,new g({color:Z.success,underline:!0}))})});if(F<Q.length-1)return[q,new e({text:new C(" ")})];return[q]})]}):null,K=Y?new W1({mainAxisSize:"min",children:[new e({text:new C("Images: ",new g({color:Z.foreground,dim:!0}))}),...this.props.imageAttachments.flatMap((G,F)=>{let q=this.props.onImageClick!==void 0,W=new Q4({onClick:q?()=>{this.props.onImageClick?.(F)}:void 0,cursor:q?"pointer":void 0,child:new e({text:new C(`[Image ${F+1}]`,new g({color:Z.success,underline:!0}))})});if(F<this.props.imageAttachments.length-1)return[W,new e({text:new C(" ")})];return[W]}),...this.props.showImageUploadSpinner?[new e({text:new C(" ")}),new e({text:new C(this._imageUploadSpinner.toBraille(),new g({color:Z.foreground,dim:!0}))})]:[]]}):null,V=new Pz0({controller:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.buildOptions,onSelected:this.props.onOptionSelected??this.defaultOnOptionSelected,displayStringForOption:(G)=>Ih4(G),overlayBorderColor:Z.border,focusNode:this._effectiveFocusNode,autofocus:this.props.autofocus??!0,autoOverlayPosition:this.props.autoOverlayPosition,handle:this.props.autocompleteHandle,textFieldProps:{placeholder:this.props.placeholder,wrap:!0,minLines:this.props.minLines??3,maxLines:null,expands:!0,autofocus:!1,enabled:this.props.enabled??!0,onSubmitted:this._handleSubmitted,onOpenInEditor:this._handleOpenInEditor,submitKey:this.props.submitKey??{character:"Enter"},prompts:this.props.shellPromptRules,style:{backgroundColor:Z.background,border:null,padding:C0.all(0),textColor:this.props.textColor??Z.foreground,cursorColor:Z.cursor,placeholderColor:Z.mutedForeground,selectionBackgroundColor:Z.selection},clipboard:this.props.clipboard,onCopy:this.props.onCopy,copyOnSelectionEnabled:!0,onBackspaceWhenEmpty:this._handleBackspaceAtStart},optionViewBuilder:(G,F,q)=>{let W=q?Z.selection:void 0,U=Z.secondary,H=Z.foreground,D=Z.foreground,B=Z.warning;if(F.type==="commit")return new d0({decoration:new $6(W),child:new W1({children:[new y1({child:new e({text:new C("",void 0,[new C(F.shortHash,new g({color:Z.secondary})),new C(" ",new g({})),new C(F.message,new g({color:H}))]),maxLines:1,overflow:"ellipsis"})}),new e({text:new C(` ${F.relativeDate}`,new g({color:D,dim:!0}))})]})});let N=[];switch(F.type){case"file":N.push(new C("@",new g({color:U}))),N.push(new C(F.path,new g({color:H})));break;case"hint":N.push(new C(F.kind==="commit"?"@:":"@@",new g({color:B}))),N.push(new C(" ",new g({}))),N.push(new C(F.message,new g({color:B})));break}let w=Ph4(F);if(w)N.push(new C(" - ",new g({color:D,dim:!0}))),N.push(new C(w,new g({color:D,dim:!0})));return new d0({decoration:new $6(W),child:new e({text:new C("",void 0,N),maxLines:1,overflow:"ellipsis"})})}}),z=[];if(this.props.topWidget)z.push(this.props.topWidget);if(X||K){let G=[];if(X)G.push(X);if(X&&K)G.push(new e({text:new C(" ")}));if(K)G.push(K);let F=new d0({padding:C0.only({bottom:1}),child:new W1({mainAxisSize:"min",children:G})});z.push(F)}if(z.push(new y1({child:V})),this.props.bottomWidget)z.push(this.props.bottomWidget);return new x0({crossAxisAlignment:"start",children:z})}requestFocus(){this._effectiveFocusNode.requestFocus()}}class _h4 extends p0{controller=new r7;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new G6({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>=PV)return!1;let Z=await JL(J);if(typeof Z==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Z],this.imagePaths=[...this.imagePaths,J]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,K=V4.of(J).size.height,V=Math.max(Math.floor(K*0.5),10),z=new NR({controller:this.controller,triggers:[new vq],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(H)=>{this.widget.props.onSubmit(H.trim(),this.imageAttachments)},theme:Q,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:t4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),G=new s4({focusNode:this.focusNode,child:z}),F=new d0({constraints:new I1({maxHeight:V}),padding:C0.symmetric(1,0),child:G}),q=new d0({padding:C0.symmetric(1,0),child:new e({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 d0({padding:C0.symmetric(1,0),child:new e({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}))])})}),U=[q,new R0({height:1}),new y1({child:F}),new R0({height:1}),W];return new d0({decoration:{border:c1.all(new g1(Q.foreground,1,"solid")),color:Q.background},padding:C0.all(1),child:new x0({children:U})})}}class q01 extends l0{props;constructor(J){super();this.props=J}createState(){return new _h4}}import{isDeepStrictEqual as W01}from"node:util";var oR3=/[\\/_ +.#"@[({&]/,rR3=/[\\/_ +.#"@[({&]/g,sR3=/[\s-]/,Sh4=/[\s-]/g;function Tz0(J,Z,Q,Y,X,K,V){if(K===Z.length){if(X===J.length)return 1;return 0.99}let z=`${X},${K}`;if(V[z]!==void 0)return V[z];let G=Y.charAt(K),F=Q.indexOf(G,X),q=0,W,U,H,D;while(F>=0){if(W=Tz0(J,Z,Q,Y,F+1,K+1,V),W>q){if(F===X)W*=1;else if(sR3.test(J.charAt(F-1))){if(W*=0.9,D=J.slice(X,F-1).match(Sh4),D&&X>0)W*=0.999**D.length}else if(oR3.test(J.charAt(F-1))){if(W*=0.8,H=J.slice(X,F-1).match(rR3),H&&X>0)W*=0.999**H.length}else if(W*=0.3,X>0)W*=0.999**(F-X);if(J.charAt(F)!==Z.charAt(K))W*=0.9999}if(W<0.1&&(Q.charAt(F-1)===Y.charAt(K+1)||Y.charAt(K+1)===Y.charAt(K)&&Q.charAt(F-1)!==Y.charAt(K))){if(U=Tz0(J,Z,Q,Y,F+1,K+2,V),U*0.1>W)W=U*0.1}if(W>q)q=W;F=Q.indexOf(G,F+1)}return V[z]=q,q}function Cz0(J){return J.toLowerCase().replace(Sh4," ")}function kh4(J,Z){let Q=Tz0(J,Z,Cz0(J),Cz0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,K=0;for(let z of Y){let G=Tz0(J,z,Cz0(J),Cz0(z),0,0,{});if(G===0)return Q;X+=G,K+=z.length}let V=X/Y.length*0.95;return Math.max(Q,V)}return Q}class Hy{}class Dy{}class _z0{}class Sz0{}class vh4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new yh4}}class yh4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function tR3(J,Z){if(J==="")return{matches:!0,score:1};let Q=kh4(Z,J);return{matches:Q>0.15,score:Q}}class $7 extends l0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new xh4}}class xh4 extends p0{textController;focusNode;scrollController=new j5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new r7(this.widget.props.controller?.query??""),this.focusNode=new G6({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let J=this.widget.props.controller;if(J)J.query=this.textController.text;this.syncSelection()}),this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let J=this.cachedFiltered.findIndex((Z)=>W01(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!W01(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>W01(Q,this.widget.props.controller?.selectedItem));if(Z>=0)this.selectedIndex=Z}this.clampSelectedIndex(),this.ensureSelectedItemVisible(),this.syncSelection()}}dispose(){this.widget.props.onSelectionChange?.(null),this.textController.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof Hy){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof Dy){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof _z0){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length){let Q=Z[this.selectedIndex];if(Q){if(!(this.widget.props.isItemDisabled?.(Q)??!1))this.widget.props.onAccept(Q,{hasUserInteracted:this.hasUserInteracted})}}return"handled"}if(J instanceof Sz0)return this.widget.props.onDismiss?.(),"handled";return"ignored"};syncSelection(){let Z=this.cachedFiltered[this.selectedIndex]??null;if(this.widget.props.controller)this.widget.props.controller.selectedItem=Z;this.widget.props.onSelectionChange?.(Z)}clampSelectedIndex(){let J=this.cachedFiltered.length-1;if(J<0){this.selectedIndex=0;return}this.selectedIndex=Math.max(0,Math.min(this.selectedIndex,J))}recomputeFilteredItems(){let J=this.textController.text,Z=this.widget.props.items,Q=this.widget.props.normalizeQuery?.(J)??J,Y=Z.filter((X)=>!this.widget.props.filterItem||this.widget.props.filterItem(X,J)).map((X)=>({item:X,...tR3(Q,this.widget.props.getLabel(X))})).filter((X)=>X.matches).sort(this.widget.props.sortItems?(X,K)=>this.widget.props.sortItems(X,K,J):(X,K)=>K.score-X.score).map((X)=>X.item);this.cachedQuery=J,this.cachedItemsRef=Z,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.textController.text,Z=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Z)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;zy(J,{top:Q,bottom:Y},{padding:1})}handleScroll=(J)=>{let Z=this.getFilteredItems();if(Z.length===0)return!1;let Q=this.selectedIndex;if(J.direction==="down")if(this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++;else return!1;else if(this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--;else return!1;return this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let Y=Q[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=f0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=c1.all(new g1(Q.foreground,1,"solid")),K=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,V=this.widget.props.enabled??!0,z=new IZ({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:V,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),G=new m$({shortcuts:new Map([[new D4("ArrowDown"),new Hy],[new D4("ArrowUp"),new Dy],[new D4("Tab"),new Hy],[new D4("Tab",{shift:!0}),new Dy],[new D4("n",{ctrl:!0}),new Hy],[new D4("p",{ctrl:!0}),new Dy],[new D4("Enter"),new _z0],[new D4("Escape"),new Sz0]]),focusNode:this.focusNode,child:z}),F=new M7({actions:new Map([[Hy,new D6(this.invoke)],[Dy,new D6(this.invoke)],[_z0,new D6(this.invoke)],[Sz0,new D6(this.invoke)]]),child:G}),q=new W1({children:[new d0({decoration:{color:Q.background},child:new e({text:new C(">",new g({color:Q.foreground}))})}),new y1({child:F})]});this.itemContexts=[];let W;if(this.widget.props.isLoading){let N=this.widget.props.loadingText??"Loading...";W=new R0({height:10,child:new X4({child:new e({text:new C(N,new g({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)W=new y1({child:new X4({child:new e({text:new C(this.widget.props.emptyStateText,new g({color:Q.foreground,dim:!0}))})})});else{let N=Y.map((w,L)=>{let O=L===this.selectedIndex,E=this.widget.props.isItemDisabled?.(w)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(w,O,E,J);else{let A=O?Z.app.selectionBackground:void 0,j=O?Z.app.selectionForeground:Q.foreground;M=new d0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C(this.widget.props.getLabel(w),new g({color:j,dim:E}))})})}return new vh4(new Q4({onClick:(A)=>this.handleItemClick(L,A.clickCount),child:M}),(A)=>{this.itemContexts[L]=A})});W=new x0({children:N,crossAxisAlignment:"start"})}let U=new Q4({onScroll:this.handleScroll,opaque:!1,child:new T6({controller:this.scrollController,autofocus:!1,child:W})}),H=[];if(this.widget.props.title){let N=new d0({padding:C0.symmetric(1,0),child:new e({text:new C(this.widget.props.title,new g({color:Z.app.command,bold:!0}))})});H.push(N)}if(!K)H.push(q,new R0({height:1}));if(this.textController.text!==""){let N=Y.length>0?Y[this.selectedIndex]:void 0,w=N&&this.widget.props.buildDisabledReasonWidget?.(N,J);H.push(new y1({child:new x0({mainAxisAlignment:"spaceBetween",children:[new y1({child:U}),new d0({padding:C0.only({top:1}),child:new X4({child:w??new R0({height:1})})})]})}))}else H.push(new y1({child:U}));if(this.widget.props.footer)H.push(this.widget.props.footer);return new d0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new x0({children:H})})}}function fh4(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 U01 extends J4{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)=>fh4(X.pubDate).length));return new $7({items:Z,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,K,V,z)=>{let G=f0.of(z),{colors:F}=G,q=G.app,W=K?q.selectionBackground:void 0,U=K?q.selectionForeground:F.foreground,H=F.mutedForeground,D=(B,N)=>new R0({width:N,child:W1.end([new e({text:new C(B,new g({color:H}))})])});return new d0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new W1({children:[new y1({child:new e({text:new C(X.title,new g({color:U})),overflow:"ellipsis",maxLines:1})}),new R0({width:2}),D(fh4(X.pubDate),Q)]})})}})}}hP();class H01 extends l0{createState(){return new uh4}}class uh4 extends p0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=f0.of(J).colors;return new e({text:new C("●",new g({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function eR3(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let V of J)Z.set(V.id,V);for(let V of J){let z=V.relationships.find((G)=>G.role==="child"&&Z.has(G.threadID)&&(G.type==="fork"||G.type==="handoff"));if(z){Y.set(V.id,z.type);let G=z.threadID,F=Q.get(G)||[];F.push(V),Q.set(G,F)}else X.push(V)}return ZV0.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 D01(J,Z,Q){return new e({text:new C(`${J}${Z}`,new g({color:Q})),maxLines:1})}function $I3(J,Z,Q,Y){return[D01("+",J,Y.success),f3.horizontal(1),D01("~",Z,Y.warning),f3.horizontal(1),D01("-",Q,Y.destructive)]}function JI3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class kz0 extends l0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new bh4}}class bh4 extends p0{spinner=new V3;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===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)K=K.filter((L)=>L.id!==Z.currentThreadID);let V=Z.recentThreadIDs||[],z=new Set(V),G=Z.currentThreadID,F=[...K].sort((L,O)=>{if(G){if(L.id===G)return-1;if(O.id===G)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=eR3(F),W=Math.max(0,...q.map((L)=>L.description.timeAgo.length)),U=f0.of(J),H=new n0({padding:C0.symmetric(0,1),child:new X4({child:new e({text:new C("",new g({color:U.colors.foreground,dim:!0}),[new C("Alt+W/Ctrl+T",new g({color:U.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new g({color:U.colors.foreground,dim:!0}))])})})}),D="",B=null,N=(L)=>{if(L!==D)D=L,B=H$(L);return B};return new $7({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(!JI3(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:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:H,renderItem:(L,O,E,M)=>{let A=f0.of(M),{app:j,colors:R}=A,_=O?j.selectionBackground:void 0,T=O?j.selectionForeground:R.foreground,u=R.mutedForeground,m=(a,W0)=>new R0({width:W0,child:W1.end([new e({text:new C(a,new g({color:u}))})])}),y=Z.threadViewStates[L.id],k=[],f=L.relationshipType==="handoff",d=new on({connectorColor:R.mutedForeground});if(L.depth>0){let a=[],W0=L.ancestorsAreLast.slice(1);for(let L0 of W0)a.push(new C(d.getAncestorPrefix(L0),new g({color:d.connectorColor,dim:d.connectorDim})));let r=L.isLast?d.elbow:d.tee,H0=d.getConnectorText(r);a.push(new C(H0,new g({color:d.connectorColor,dim:d.connectorDim}))),k.push(new e({text:new C("",void 0,a)}))}let p=[],h=G===L.id?new C("(current) ",new g({color:R.success})):z.has(L.id)?new C("(visited) ",new g({color:R.foreground,dim:!0})):null;if(h)p.push(new e({text:h}));if(HN(y))p.push(new H01),p.push(new R0({width:1}));let n=L.title;if(L.relationshipType==="fork"){let a=n.match(/^Forked\((\d+)\): /);if(a)n=n.slice(a[0].length);else while(n.startsWith("Forked: "))n=n.slice(8);p.push(new e({text:new C("[fork] ",new g({color:R.primary}))}))}else if(f)p.push(new e({text:new C("[handoff] ",new g({color:R.accent}))}));if(p.push(new y1({child:new e({text:new C(n,new g({color:T})),overflow:"ellipsis",maxLines:1})})),p.push(new R0({width:2})),L.diffStats&&(L.diffStats.added>0||L.diffStats.changed>0||L.diffStats.deleted>0)){let a=O?{success:u,warning:u,destructive:u}:R;p.push(...$I3(L.diffStats.added,L.diffStats.changed,L.diffStats.deleted,a)),p.push(new R0({width:2}))}return p.push(m(L.description.timeAgo,W)),new d0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new W1({children:[...k,...p]})})}})}}function hh4(J){return 1-(1-J)**3}function gh4(J,Z,Q){return J+(Z-J)*Q}function Ia(J,Z){if(!J)return{x:0,y:0};let Q=Z-J.startTime,Y=Math.min(Q/J.durationX,1),X=Math.min(Q/J.durationY,1),K=hh4(Y),V=hh4(X);return{x:gh4(J.startOffset.x,J.targetOffset.x,K),y:gh4(J.startOffset.y,J.targetOffset.y,V)}}var ZI3={nodeWidth:3,horizontalSpacing:3};class By{options;constructor(J={}){this.options={...ZI3,...J}}layout(J){let{childrenMap:Z,resolvedParent:Q}=this.buildTree(J),Y=[],X=Z.get(void 0)??[];if(this.options.comparator)X.sort(this.options.comparator);let K=0,V=(z,G)=>{let F=Z.get(z.id)??[];if(this.options.comparator)F.sort(this.options.comparator);let q={...z,parentID:Q.get(z.id)};if(F.length===0){Y.push({node:q,position:{x:K,y:G}});let B=K;return K+=this.options.nodeWidth+this.options.horizontalSpacing,B}let W=[];for(let B of F)W.push(V(B,G+1));let U=Math.min(...W),H=Math.max(...W),D=Math.floor((U+H)/2);return Y.push({node:q,position:{x:D,y:G}}),D};for(let z of X)V(z,0);return Y}buildTree(J){let Z=new Set(J.map((K)=>K.id)),Q=[...J].sort((K,V)=>K.id.localeCompare(V.id)),Y=new Map;for(let K of Q){if(!K.parentID||!Z.has(K.parentID)){Y.set(K.id,void 0);continue}let V=!1,z=K.parentID;while(z){if(z===K.id){V=!0;break}z=Y.get(z)}Y.set(K.id,V?void 0:K.parentID)}let X=new Map;for(let K of J){let V=Y.get(K.id);if(!X.has(V))X.set(V,[]);X.get(V).push(K)}return{childrenMap:X,resolvedParent:Y}}}var QI3={nodeWidth:3,nodeHeight:2};class Ny{options;constructor(J={}){this.options={...QI3,...J}}calculate(J){let Z=[],Q=new Map;for(let Y of J)Q.set(Y.node.id,Y);for(let Y of J){if(!Y.node.parentID)continue;let X=Q.get(Y.node.parentID);if(!X)continue;let K=this.calculateConnectorLine(X.position,Y.position);Z.push({points:K,fromNodeID:X.node.id,toNodeID:Y.node.id})}return Z}calculateConnectorLine(J,Z){let Q=Math.floor(this.options.nodeWidth/2),Y=[],X=J.x+Q,K=Z.x+Q,V=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:V});let z=V+1;if(Y.push({x:X,y:z}),X!==K)Y.push({x:K,y:z});let G=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:K,y:G}),Y}}var YI3={nodeWidth:3,nodeHeight:2},XI3={x:0,y:0};class yz0{options;constructor(J={}){this.options={...YI3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=XI3,X,K,V,z){let G=z?f0.of(z):null,F=G?.colors,q=G?.app,W=F?.mutedForeground??F?.foreground;if(J.length===0)return new e({text:new C("No nodes",new g({color:W}))});let U=Math.max(...J.map((j)=>j.position.y)),D=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,N=[];for(let j=U;j>=0;j--){let R=J.filter((u)=>u.position.y===j);R.sort((u,m)=>u.position.x-m.position.x);let _=[],T=0;for(let u of R){if(u.position.x>T)_.push(new R0({width:u.position.x-T}));let m=u.node.id===Q,y=V?.(u.node.data)??!1,k=K?.activeFlashOn??!1,f=u.node.id===K?.copyFlashNodeId;_.push(this.renderNode(m,y,k,f,q,F)),T=u.position.x+this.options.nodeWidth}if(N.push(new W1({crossAxisAlignment:"start",children:_})),j>0){let u=J.filter((k)=>k.position.y===j-1),m=R,y=this.renderConnectors(u,m,Z,D,F,q);N.push(...y)}}let w=new x0({crossAxisAlignment:"start",children:N}),L=Math.round(Y.x),O=Math.round(Y.y*B),E=(U+1)*B,M=[new R0({width:D,height:E}),new t6({left:L,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=U-A.position.y,_=L+A.position.x+this.options.nodeWidth+1,T=O+R*B+1,u=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)u=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new t6({left:_,top:T,child:this.renderInfoBox(j,u,F,q)}))}return new d0({padding:C0.horizontal(2),child:new fz(new z5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,K){let V="┌─┐",z="└─┘",G=J?X?.threadGraphNodeSelected??K?.primary??K?.foreground:X?.threadGraphNode??K?.primary??K?.foreground,F=!1;if(Y)G=X?.threadGraphNodeSelected??K?.primary??G,V="┏━┓",z="┗━┛",F=!0;else if(Z&&Q)G=X?.toolSuccess??K?.primary??G,V="┏━┓",z="┗━┛";return new x0({crossAxisAlignment:"start",children:[new e({text:new C(V,new g({color:G,bold:F}))}),new e({text:new C(z,new g({color:G,bold:F}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),K=Math.min(Z,Math.max(1,...X.map((U)=>U.length))),V=K+2,z="┌"+"─".repeat(V)+"┐",G="└"+"─".repeat(V)+"┘",F=Q?.border??Y?.threadGraphConnector??Q?.foreground,q=Q?.foreground,W=[new e({text:new C(z,new g({color:F}))})];for(let U of X){let H=" ".repeat(K-U.length);W.push(new e({text:new C("│ ",new g({color:F}),[new C(U+H,new g({color:q??F})),new C(" │",new g({color:F}))])}))}return W.push(new e({text:new C(G,new g({color:F}))})),new x0({crossAxisAlignment:"start",children:W})}renderConnectors(J,Z,Q,Y,X,K){let V=[],z=Math.floor(this.options.nodeWidth/2),G=K?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let U of Z){let H=U.position.x+z;if(H>=0&&H<Y)F[H]="▲"}V.push(new e({text:new C(F.join(""),new g({color:G}))}));let q=Array(Y).fill(" ");for(let U of J){let H=Z.filter((L)=>L.node.parentID===U.node.id);if(H.length===0)continue;let D=U.position.x+z,B=H.map((L)=>L.position.x+z),N=Math.min(...B),w=Math.max(...B);for(let L=N;L<=w;L++)if(L>=0&&L<Y){if(L===D)if(H.length===1&&B[0]===D)q[L]="│";else if(L===N)q[L]="└";else if(L===w)q[L]="┘";else q[L]="┬";else if(B.includes(L))if(L===N)q[L]="└";else if(L===w)q[L]="┘";else q[L]="┴";else if(q[L]===" ")q[L]="─"}}V.push(new e({text:new C(q.join(""),new g({color:G}))}));let W=Array(Y).fill(" ");for(let U of J){if(Z.filter((B)=>B.node.parentID===U.node.id).length===0)continue;let D=U.position.x+z;if(D>=0&&D<Y)W[D]="│"}return V.push(new e({text:new C(W.join(""),new g({color:G}))})),V}}var KI3={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},VI3={x:0,y:0};class B01{options;constructor(J={}){this.options={...KI3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=VI3,X,K,V,z){let G=z?f0.of(z):null,F=G?.colors,q=G?.app,W=F?.mutedForeground??F?.foreground;if(J.length===0)return new e({text:new C("No nodes",new g({color:W}))});let U=Math.max(...J.map((j)=>j.position.y)),D=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,N=[];for(let j=U;j>=0;j--){let R=J.filter((u)=>u.position.y===j);R.sort((u,m)=>u.position.x-m.position.x);let _=[],T=0;for(let u of R){if(u.position.x>T)_.push(new R0({width:u.position.x-T}));let m=u.node.id===Q,y=V?.(u.node.data)??!1,k=K?.activeFlashOn??!1;_.push(this.renderNode(m,y,k,q,F)),T=u.position.x+this.options.nodeWidth}if(N.push(new W1({crossAxisAlignment:"start",children:_})),j>0){let u=J.filter((k)=>k.position.y===j-1),m=R,y=this.renderConnectors(u,m,Z,D,F,q);N.push(...y)}}let w=new x0({crossAxisAlignment:"start",children:N}),L=Math.round(Y.x),O=Math.round(Y.y*B),E=(U+1)*B,M=[new R0({width:D,height:E}),new t6({left:L,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=U-A.position.y,_=L+A.position.x+this.options.nodeWidth+1,T=O+R*B,u=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)u=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new t6({left:_,top:T,child:this.renderInfoBox(j,u,F)}))}return new d0({padding:C0.horizontal(2),child:new fz(new z5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X){let K=J?this.options.selectedIcon:this.options.nodeIcon,V=J?Y?.threadGraphNodeSelected??X?.primary??X?.foreground:Y?.threadGraphNode??X?.primary??X?.foreground;if(Z&&Q)V=Y?.toolSuccess??X?.primary??V,K="■";return new e({text:new C(K,new g({color:V}))})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q){let Y=this.wrapText(J,Z),X=Q?.foreground,K=[];for(let V of Y)K.push(new e({text:new C(V,new g({color:X??Q?.primary??Q?.foreground}))}));return new x0({crossAxisAlignment:"start",children:K})}renderConnectors(J,Z,Q,Y,X,K){let V=[],z=Math.floor(this.options.nodeWidth/2),G=K?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let q of J){let W=Z.filter((N)=>N.node.parentID===q.node.id);if(W.length===0)continue;let U=q.position.x+z,H=W.map((N)=>N.position.x+z),D=Math.min(...H),B=Math.max(...H);for(let N=D;N<=B;N++)if(N>=0&&N<Y){let w=N===U,L=H.includes(N);if(w&&L)if(W.length===1)F[N]="│";else if(N===D)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┼";else if(w)if(N===D)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┬";else if(L)if(N===D)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┴";else if(F[N]===" ")F[N]="─"}}return V.push(new e({text:new C(F.join(""),new g({color:G}))})),V}}class Pa extends n3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new mh4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class mh4 extends u4{onWidth;onHeight;constructor(J,Z){super();this.onWidth=J,this.onHeight=Z}performLayout(){let J=this._lastConstraints,Z=Number.isFinite(J.maxWidth)?J.maxWidth:80,Q=Number.isFinite(J.maxHeight)?J.maxHeight:24;this.onWidth(Z),this.onHeight?.(Q);let Y=this.children[0];if(Y)Y.layout(J),this.setSize(Y.size.width,Y.size.height);else this.setSize(J.minWidth,J.minHeight)}paint(J,Z,Q){for(let Y of this.children)Y.paint(J,Z,Q)}}class wR extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new ch4}}var ph4=400,dh4=300,zI3=16;class ch4 extends p0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new By({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new Ny;renderer=new B01;animation=null;currentOffset={x:0,y:0};animationTimer=null;viewportWidth=80;viewportHeight=24;activeFlashOn=!0;activeFlashTimer=null;initState(){let{initialSelectedThreadID:J}=this.widget.props;if(J){let Q=this.widget.props.threads.find((Y)=>Y.id===J);if(Q)this.selectedNodeId=Q.id}this.startActiveFlashTimer()}startActiveFlashTimer(){if(!this.widget.props.threads.some((Z)=>Z.isActive))return;this.activeFlashTimer=setInterval(()=>{this.activeFlashOn=!this.activeFlashOn,this.setState()},700)}stopActiveFlashTimer(){if(this.activeFlashTimer)clearInterval(this.activeFlashTimer),this.activeFlashTimer=null}didUpdateWidget(J){let Z=new Set(J.props.threads.map((G)=>G.id)),Q=new Set(this.widget.props.threads.map((G)=>G.id));if(Z.size!==Q.size||[...Z].some((G)=>!Q.has(G)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,K=this.widget.props.initialSelectedThreadID;if(X!==K&&K){let F=this.widget.props.threads.find((q)=>q.id===K);if(F)this.selectedNodeId=F.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let V=J.props.threads.some((G)=>G.isActive),z=this.widget.props.threads.some((G)=>G.isActive);if(V!==z){if(this.stopActiveFlashTimer(),z)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:ph4,durationY:dh4};let Z=Math.max(ph4,dh4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=Ia(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},zI3)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null;this.animation=null}calculateCenterOffset(J,Z,Q){let Y=Math.floor(this.renderer.getNodeWidth()/2),K=Math.floor(this.viewportWidth/2)-J-Y,V=Q-Z,z=2,G=Math.floor(this.viewportHeight/2),q=Math.floor(G/2)-V;return{x:K,y:q}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((X)=>X.position.y)),Y=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(Y)}}toGraphNodes(){return this.widget.props.threads.map((J)=>({id:J.id,parentID:J.parentID,data:{title:J.title,updatedAt:J.updatedAt,isActive:J.isActive}}))}toThreadNode(J){return{id:J.node.id,parentID:J.node.parentID,title:J.node.data.title,updatedAt:J.node.data.updatedAt}}handleKeyEvent=(J)=>{if(!this.selectedNodeId)return"ignored";let Z=this.positionedNodes,Q=Z.find((X)=>X.node.id===this.selectedNodeId);if(!Q)return"ignored";let Y;switch(J.key){case"ArrowUp":{let X=Z.filter((K)=>K.node.parentID===Q.node.id);if(X.length>0){X.sort((V,z)=>V.position.x-z.position.x);let K=Math.floor(X.length/2);Y=X[K]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x<Q.position.x);if(X.length>0)X.sort((K,V)=>V.position.x-K.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x>Q.position.x);if(X.length>0)X.sort((K,V)=>K.position.x-V.position.x),Y=X[0];break}case"Enter":{if(this.widget.props.onSelect)this.widget.props.onSelect(this.toThreadNode(Q));return"handled"}default:{if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"}}if(Y)return this.selectedNodeId=Y.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(Y)),this.animateToNode(Y.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let q=(this.selectedNodeId?this.positionedNodes.find((W)=>W.node.id===this.selectedNodeId):null)??this.positionedNodes.find((W)=>!W.node.parentID);if(q){let W=Math.max(...this.positionedNodes.map((U)=>U.position.y));this.currentOffset=this.calculateCenterOffset(q.position.x,q.position.y,W)}}let X=this.widget.props.showTitle??!0,K=this.widget.props.offsetY??0,V={x:this.currentOffset.x,y:this.currentOffset.y+K},z=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,V,X?(F)=>F.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(F)=>F.isActive??!1,J),G=new Pa({onWidth:(F)=>{if(this.viewportWidth!==F)this.viewportWidth=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(F)=>{if(this.viewportHeight!==F)this.viewportHeight=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:z});return new s4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:G})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class ih4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new nh4}}class nh4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}var lh4=30,GI3=30;class wy{}class Ly{}class xz0{}class fz0{}class N01 extends l0{props;constructor(J){super();this.props=J}createState(){return new ah4}}class ah4 extends p0{highlightedIndex=0;controller=new r7;focusNode;scrollController=new j5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new G6({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;zy(J,{top:Q,bottom:Y},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Z}=this.widget.props;if(!J)this.filteredClusters=[...Z];else this.filteredClusters=Z.filter((Q)=>Q.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof wy){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof Ly){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof xz0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof fz0)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Z)=>{if(J>=0&&J<this.filteredClusters.length){if(Z===1)this.highlightedIndex=J,this.setState();else if(Z===2){let Q=this.filteredClusters[J];if(Q)this.widget.props.onAccept(Q)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return!1;let Z=this.highlightedIndex;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return!1;else if(this.highlightedIndex>0)this.highlightedIndex--;else return!1;return this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=f0.of(J),{colors:Y,app:X}=Q,z=V4.of(J).size.width>=GI3+lh4,G=c1.all(new g1(Y.foreground,1,"solid")),F=this.filteredClusters[this.highlightedIndex]??null,q=new d0({padding:C0.symmetric(1,0),child:new e({text:new C("Select a cluster",new g({color:X.command,bold:!0}))})}),W=new IZ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),U=new m$({shortcuts:new Map([[new D4("ArrowDown"),new wy],[new D4("ArrowUp"),new Ly],[new D4("Tab"),new wy],[new D4("Tab",{shift:!0}),new Ly],[new D4("n",{ctrl:!0}),new wy],[new D4("p",{ctrl:!0}),new Ly],[new D4("Enter"),new xz0],[new D4("Escape"),new fz0]]),focusNode:this.focusNode,child:W}),H=new M7({actions:new Map([[wy,new D6(this.invoke)],[Ly,new D6(this.invoke)],[xz0,new D6(this.invoke)],[fz0,new D6(this.invoke)]]),child:U}),D=new W1({children:[new d0({decoration:{color:Y.background},child:new e({text:new C(">",new g({color:Y.foreground}))})}),new y1({child:H})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let j=A===this.highlightedIndex,R=Z?M.threads.some((m)=>m.id===Z):!1,_=j?X.selectionBackground:void 0,T=j?X.selectionForeground:Y.foreground,u=[new C(M.label,new g({color:T})),new C(` (${M.threads.length})`,new g({color:T,dim:!0}))];if(R)u.push(new C(" (current)",new g({color:j?X.selectionForeground:Y.success})));return new ih4(new Q4({onClick:(m)=>this.handleItemClick(A,m.clickCount),child:new d0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C("",void 0,u)})})}),(m)=>{this.itemContexts[A]=m})}),N=new x0({children:B,crossAxisAlignment:"start"}),w=new y1({child:new Q4({onScroll:this.handleScroll,child:new T6({controller:this.scrollController,autofocus:!1,child:N})})}),L=F?F.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],O=F?new d0({padding:C0.all(1),child:new wR({threads:L,autofocus:!1,offsetY:2})}):null,E;if(z){let M=O?new y1({child:O}):new R0({width:lh4});E=new W1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[w,M]})}else{let M=[new y1({child:new Q4({onScroll:this.handleScroll,child:new T6({controller:this.scrollController,autofocus:!1,child:N})})})];if(O)M.push(new y1({child:O}));E=new x0({crossAxisAlignment:"stretch",children:M})}return new d0({decoration:{border:G,color:Y.background},padding:C0.symmetric(1,0),child:new x0({children:[q,D,new R0({height:1}),new y1({child:E})]})})}}m0();IX();hM();CX();O$();d4();N4();SP();var L01=B4(tW(),1);import{execSync as LR}from"node:child_process";import{writeFile as Oy}from"node:fs/promises";import FI3 from"node:os";import yq from"node:path";var oh4="c446b2e9b16cdc06df2ec285894d6421",qI3="5ea19563777f4ade8707fc56f7e7a388",WI3="amp-thread-worker",rh4=[{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 UI3(J){return!!J&&typeof J==="object"&&"usesDtw"in J}function zL(J){if(!J||!UI3(J.meta))return!1;return J.meta.usesDtw===!0}function O01(J){let Z=new URL(`https://dash.cloudflare.com/${oh4}/workers/durable-objects/view/${qI3}/studio`);return Z.searchParams.set("name",J),Z.searchParams.set("jurisdiction","none"),Z.toString()}function E01(J){let Z=new URL(`https://dash.cloudflare.com/${oh4}/workers/services/view/${WI3}/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 HI3(J,Z){if(OV(J))return`amp dtw-curl ${Z}`;return`AMP_URL=${JSON.stringify(J)} pnpm -C cli cli -- dtw-curl ${Z}`}function M01(J,Z){let Q=HI3(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 Ca(J,Z,Q){let Y=`select(.pid == ${Z})`,X=Ta(Q);return`${J==="snapshot"?`tail -n 10000 ${X}`:`tail -f ${X}`} | jq -C '${Y}'`}function Ta(J){return J.path??f9(J.uri)}function sh4(J,Z,Q){let Y=Ca("snapshot",J,Z);return Q?`${Y} | ${Q}`:Y}function th4(J,Z){return M01(J,Z).map(({label:Q,command:Y})=>`# ${Q}
|
|
7378
7376
|
${Y}`).join(`
|
|
7379
7377
|
|
|
@@ -7602,7 +7600,7 @@ ${t.content||""}`:t.content||"",T0=[],e0=t.baseDir.startsWith("file://")?MG0(t.b
|
|
|
7602
7600
|
`),process.exit(1)}process.stdout.write(await s_3(G.result.displayText)+`
|
|
7603
7601
|
`),process.exit(0)})}hM();import{stdout as t_3}from"node:process";function e_3({version:J,buildTimestamp:Z,buildType:Q}){let Y=Q==="dev"?"dev":"released",X=Z?new Date(Z):null,K=X&&!Number.isNaN(X.getTime())?`, ${EF(X)} ago`:"";return`${J} (${Y}${Z?` ${Z}`:""}${K})`}function dd4(J){t_3.write(`${e_3(J)}
|
|
7604
7602
|
`)}function cd4(J,Z){J.option("-V, --version","Print the version number and exit",()=>{dd4(Z),process.exit(0)}),J.command("version").description("Print the version number and exit").action(()=>{dd4(Z),process.exit(0)})}var Lx3=lH.join(nZ,"logs","headless.log"),r61=lH.join(Qv,"device-id.json"),Wn4=`cli-tui-${En4(16).toString("hex")}`;async function Ox3(){for(let J of XE)try{if((await J.listConfigs()).length>0)return J}catch(Z){P.debug("Failed to detect query-based IDE integration",{ideName:J.ideName,error:Z})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => B4(oy(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){j2.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
|
|
7605
|
-
`)}function Ex3(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",z=!1;J.warn(K,{name:V,code:Y})}}function A2(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")aJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")aJ("experimental.agentMode",Z.mode)}function Rn4(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 Mx3(J){try{return await An4(J,"utf-8")}catch{return J}}async function s61(J,Z,Q){let Y=Rn4(J,Z);if(!Y)return;let X=o6(Q)?Q.features:[],K=o6(Q)?Q.user.email:void 0;if(!Z51(X,S2.HARNESS_SYSTEM_PROMPT)&&!In4(K))throw new T1("You are not allowed to do this.",1);aJ("systemPrompt",await Mx3(Y))}function In4(J){return!!(J&&J10(J))}function Z51(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function t61(J){return(J.userEmail?dJ(J.userEmail):!1)||Z51(J.features,S2.DTW_TUI)}function Un4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new T1("This TUI mode is not enabled for your user;",1)}function e61(J,Z){if(typeof J==="boolean")return J;if(!o6(Z))return!1;return t61({userEmail:Z.user.email,features:Z.features})}function $51(J){if(!o6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function Ax3(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 WF0(J){let Y=Ax3(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new T1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function Hn4(J){if(!Y5.write(J))await Dx3(Y5,"drain")}var Dn4=[{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??yK,description:`Custom settings file path (overrides the default location ${yK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(P).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Pn0})`},{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:a7(),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:xG.SMART.key,description:`Set the agent mode (${fG().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:fG().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}],Bn4=(J)=>("deprecated"in J)&&J.deprecated===!0,jx3=(J)=>("hidden"in J)&&J.hidden===!0,Rx3=(J)=>("default"in J),Ix3=(J)=>("default"in J)?J.default:void 0,Pn4=[{name:"toggle-skills-count",entryPoint:jo0}];function Px3(J,Z){let Q=Z.args[0],Y=Z.commands.map((K)=>K.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let K=Y.filter((z)=>Q.includes(z)||z.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new T1(E3.unknownCommand(Q),1,V)}}async function Q51(J){return{...J,getThreadEnvironment:uY,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new hV(J.fileSystem),generateThreadTitle:g80,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>xX(J.configService),pluginService:J.pluginService}}function Cn4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:uY,filesystem:J.fileSystem,threadService:J.threadService}}var UF0=V1.file(jn4.homedir()),J51=process.env.XDG_CONFIG_HOME?V1.file(process.env.XDG_CONFIG_HOME):Y1.joinPath(UF0,".config");function Cx3(J){return qq4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){Fq4(Z);let Q=MX0(),Y=ho0();if((!Q||Y||IT4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(wH("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(wH("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(MX0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function Tx3(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>k0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function R7(J,Z,Q){let Y=Q?.deferAuth??!1;Qf1("0.0.
|
|
7603
|
+
`)}function Ex3(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",z=!1;J.warn(K,{name:V,code:Y})}}function A2(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")aJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")aJ("experimental.agentMode",Z.mode)}function Rn4(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 Mx3(J){try{return await An4(J,"utf-8")}catch{return J}}async function s61(J,Z,Q){let Y=Rn4(J,Z);if(!Y)return;let X=o6(Q)?Q.features:[],K=o6(Q)?Q.user.email:void 0;if(!Z51(X,S2.HARNESS_SYSTEM_PROMPT)&&!In4(K))throw new T1("You are not allowed to do this.",1);aJ("systemPrompt",await Mx3(Y))}function In4(J){return!!(J&&J10(J))}function Z51(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function t61(J){return(J.userEmail?dJ(J.userEmail):!1)||Z51(J.features,S2.DTW_TUI)}function Un4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new T1("This TUI mode is not enabled for your user;",1)}function e61(J,Z){if(typeof J==="boolean")return J;if(!o6(Z))return!1;return t61({userEmail:Z.user.email,features:Z.features})}function $51(J){if(!o6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function Ax3(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 WF0(J){let Y=Ax3(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new T1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function Hn4(J){if(!Y5.write(J))await Dx3(Y5,"drain")}var Dn4=[{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??yK,description:`Custom settings file path (overrides the default location ${yK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(P).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Pn0})`},{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:a7(),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:xG.SMART.key,description:`Set the agent mode (${fG().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:fG().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}],Bn4=(J)=>("deprecated"in J)&&J.deprecated===!0,jx3=(J)=>("hidden"in J)&&J.hidden===!0,Rx3=(J)=>("default"in J),Ix3=(J)=>("default"in J)?J.default:void 0,Pn4=[{name:"toggle-skills-count",entryPoint:jo0}];function Px3(J,Z){let Q=Z.args[0],Y=Z.commands.map((K)=>K.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let K=Y.filter((z)=>Q.includes(z)||z.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new T1(E3.unknownCommand(Q),1,V)}}async function Q51(J){return{...J,getThreadEnvironment:uY,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new hV(J.fileSystem),generateThreadTitle:g80,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>xX(J.configService),pluginService:J.pluginService}}function Cn4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:uY,filesystem:J.fileSystem,threadService:J.threadService}}var UF0=V1.file(jn4.homedir()),J51=process.env.XDG_CONFIG_HOME?V1.file(process.env.XDG_CONFIG_HOME):Y1.joinPath(UF0,".config");function Cx3(J){return qq4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){Fq4(Z);let Q=MX0(),Y=ho0();if((!Q||Y||IT4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(wH("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(wH("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(MX0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function Tx3(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>k0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function R7(J,Z,Q){let Y=Q?.deferAuth??!1;Qf1("0.0.1774866438-g7cb400");let X=O10({storage:J.settings,secretStorage:J.secrets,workspaceRoot:k0.of(V1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:UF0,userConfigDir:J51});RT4(X);let K=await X.getLatest();P.debug("Global configuration initialized",{settingsKeys:Object.keys(K.settings)});let V=!1;{let a=await J.secrets.get("apiKey",J.ampURL);if(V=Boolean(a),P.info("API key lookup before login",{found:Boolean(a),ampURL:J.ampURL,deferAuth:Y}),!a)if(Y)P.info("No API key found, continuing startup with deferred auth");else{Y5.write(`No API key found. Starting login flow...
|
|
7606
7604
|
`);let W0=await _x3(J),r=await J.secrets.get("apiKey",J.ampURL);if(P.info("Login flow completed",{success:W0,storedKeyPresent:Boolean(r),ampURL:J.ampURL}),!W0)await VH(),process.exit(1);V=!0}}{let a=await X.getLatest(),W0=a.settings.url,r=a.secrets.isSet?.[W0];P.info("Config secrets state after login",{configURL:W0,apiKeySet:r?.apiKey??!1})}let z=j1(xX(X).pipe(T5((a)=>a!=="pending"))),G=Y?"pending":await z;if(!Y)P.info("Server status resolved",{status:"ready",isAuthenticated:o6(G),isError:bW(G),errorMessage:bW(G)?G.error.message:void 0});let{toolService:F,dispose:q}=Xq4({configService:X}),W=new Map,U=()=>W.clear(),H=new fT0(X,J.settings.getWorkspaceRootPath()),D=zt1({configService:X,filesystem:n8}),B=Qa1({configService:X,trustStore:H,skillMCPServers:D.skillMCPServers,createOAuthProvider:async(a,W0,r)=>{let H0=`${a}:${W0}`,L0=W.get(H0);if(L0)return P.debug("Reusing existing OAuth provider for server",{serverName:a,serverUrl:W0}),L0;P.debug("Creating OAuth provider for server",{serverName:a,serverUrl:W0});let z0=(async()=>{let J0=new HE(J.secrets),G0=await J0.getClientInfo(a,W0),i=r?.scopes??G0?.scopes,o=ZI4();P.info("OAuth headless mode check",{useHeadless:o,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:Y5.isTTY});let t;if(o)t=J.executeMode?JI4():$I4(a);let $0=new BR0({storage:J0,serverName:a,serverUrl:W0,clientId:r?.clientId??G0?.clientId,clientSecret:r?.clientSecret??G0?.clientSecret,authUrl:r?.authUrl??G0?.authUrl,tokenUrl:r?.tokenUrl??G0?.tokenUrl,scopes:i,headlessAuthHandler:t});return P.debug("OAuth provider created",{serverName:a,serverUrl:W0,hasManualClientId:!!(r?.clientId??G0?.clientId),willUseDCR:!(r?.clientId??G0?.clientId),scopes:i,headlessMode:o,executeMode:J.executeMode}),$0})();return W.set(H0,z0),z0}}),N=ug0({configService:X,filesystem:n8,spawn:P$0}),w;if(J.executeMode){let a=await Gz4({toolService:F,providers:[B,N],initialTimeout:15000});w=a.registrations;for(let[W0,r]of a.initErrors)P.warn(`${W0} provider initialization slow or failed:`,r)}else w=bg0({toolService:F,providers:[B,N]});if(Z.jetbrains)$E("JetBrains");else if(Z.ide&&gI4())$E("VS Code");else if(Z.ide&&mI4())$E("Neovim");else if(Z.ide){let a=await Ox3();if(a){let W0=_10(a.ideName);if(W0)$E(W0)}}if(J.executeMode)Yf1(!0);let L,O=w$.status.pipe(D1((a)=>Boolean(a.connected&&a.authenticated&&a.ideName&&if1(a.ideName))),b4()).subscribe((a)=>{if(a){if(!L)L=F.registerTool(zz4)}else L?.dispose(),L=void 0}),E;if(!J.executeMode){let a=await J.settings.get("fuzzy.alwaysIncludePaths")??[];E=new WY0(process.cwd(),{alwaysIncludePaths:a},!0)}else E=new class extends WY0{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let M=await Dt1({isDevelopment:!1}),A=new bS0(M,X,{maxThreads:200});P.info("Starting Amp background services");let j=Z.takeMeBack?!1:void 0,R=e61(j,G),_=Boolean(R||Z.headless);if(_)P.info("DTW mode enabled: thread sync service disabled");let T=_?Tx3():yt1({threadService:A,configService:X,isExtensionDevelopment:!1}),u;w$.status.subscribe((a)=>{u=a});let m=new lA0({workspaceRoots:[V1.file(process.cwd())],fileSystem:n8,getCurrentFile:()=>{if(!u?.openFile)return;try{return V1.parse(u.openFile)}catch(a){P.warn("Failed to parse current file URI",{uri:u.openFile,error:a});return}},getOpenFiles:()=>{if(!u?.visibleFiles?.length)return[];let a=u.openFile;return u.visibleFiles.filter((W0)=>W0!==a).map((W0)=>{try{return V1.parse(W0)}catch(r){return P.warn("Failed to parse visible file URI",{uri:W0,error:r}),null}}).filter((W0)=>W0!==null)}}),y=new po0,k=process.env.PLUGINS??"off",f=Z.headless?GT4():void 0,d=f??new BX0({configService:X}),p=d instanceof BX0?d:void 0;if(p)p.pluginExecutorKind=R?"local":"unknown";let h=tT0({configService:X,fileSystem:n8,platform:d,internalPlugins:Pn4,pluginFilter:k}),n=sa1({pluginService:h,toolService:F}),c={codebaseContextService:m,configService:X,toolService:F,mcpService:B,skillService:D,toolboxService:N,trustStore:H,threadService:A,threadSyncService:T,threadStorage:M,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:E,fileSystem:n8,terminal:y,pluginService:h,pluginPlatform:p,headlessPluginPlatform:f,serverStatus:G,serverStatusPromise:z,hasAPIKeyAtStartup:V};return{...c,async asyncDispose(){if(c.mcpService.hasAuthenticatingClients())P.info("Waiting for OAuth authentication to complete before exit..."),await c.mcpService.waitForAuthentication();for(let a of w.values())a.dispose();await c.mcpService.dispose(),U(),await c.threadService.asyncDispose(),c.configService.unsubscribe(),q(),c.fuzzyServer.dispose(),c.threadSyncService.dispose(),c.settingsStorage[Symbol.dispose](),O.unsubscribe(),L?.dispose(),n.dispose(),await c.pluginService.dispose()}}}async function _x3(J){if(!J.executeMode){if(!await UX0("Would you like to log in to Amp? [(y)es, (n)o]: "))return Y5.write(`Login cancelled. Run the command again to retry.
|
|
7607
7605
|
`),!1}return await Tn4(J)}async function Tn4(J){let Z=En4(32).toString("hex"),Q=await qv(J.ampURL,Z),Y=new AbortController;try{await EV(Q,Y.signal)}catch(K){P.error("Error opening browser",{error:K})}let X=await qv(J.ampURL,Z,!1);Y5.write(`If your browser does not open automatically, visit:
|
|
7608
7606
|
|
|
@@ -7610,7 +7608,7 @@ ${o0.blue.bold(X)}
|
|
|
7610
7608
|
|
|
7611
7609
|
`);try{return await pC4(J.ampURL,Z,J.secrets,Y),Y5.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(K){return P.error("Login failed",{error:K}),j2.write(`
|
|
7612
7610
|
Login failed: ${K instanceof Error?K.message:String(K)}
|
|
7613
|
-
`),!1}}function Nn4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function Sx3(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new T1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!b9(Y.threadId))throw new T1("Create response did not include a valid thread ID",1);return Y.threadId}function kx3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function vx3(J){let Z=await fetch(new URL(`/threads/${J.threadID}/durable-object-id`,J.workerURL),{method:"GET",headers:{Authorization:`Bearer ${J.apiKey}`}});if(!Z.ok){let Y=await Z.text();throw new T1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!kx3(Q))throw new T1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function yx3(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 xx3(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new T1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function fx3(J){let Z=new fN().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)Uj(),process.exit(0);let N=B.originalError??B;QR4(N)}),cd4(Z,{version:"0.0.
|
|
7611
|
+
`),!1}}function Nn4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function Sx3(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new T1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!b9(Y.threadId))throw new T1("Create response did not include a valid thread ID",1);return Y.threadId}function kx3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function vx3(J){let Z=await fetch(new URL(`/threads/${J.threadID}/durable-object-id`,J.workerURL),{method:"GET",headers:{Authorization:`Bearer ${J.apiKey}`}});if(!Z.ok){let Y=await Z.text();throw new T1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!kx3(Q))throw new T1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function yx3(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 xx3(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new T1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function fx3(J){let Z=new fN().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)Uj(),process.exit(0);let N=B.originalError??B;QR4(N)}),cd4(Z,{version:"0.0.1774866438-g7cb400",buildTimestamp:"2026-03-30T10:31:14.209Z",buildType:"'release'"}),Z.addHelpText("after",uI4()),Z.configureHelp({formatHelp:bI4}),Z.command("logout").description("Log out by removing stored API key").action(async(B,N)=>{let w=N.optsWithGlobals(),L=await r3(w);await cx3(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 r3(w);await dx3(L,await Ea0(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 r3(L);await SR4(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 r3(w);await kR4(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",`
|
|
7614
7612
|
Actions:
|
|
7615
7613
|
create Create a new DTW thread and print its ID
|
|
7616
7614
|
add-message <message> Send a user message and wait for message_added
|
|
@@ -7674,8 +7672,8 @@ ${M}
|
|
|
7674
7672
|
|
|
7675
7673
|
This thread belongs to a different user and cannot be continued for security reasons. Set AMP_RESUME_OTHER_USER_THREADS_INSECURE=1 to bypass this check.`)}}async function ux3(J){P.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new rn({threadService:J.threadService,configService:J.configService,mcpService:J.mcpService,clientID:J.clientID,initialToolDiscovery:Promise.all([J.mcpService.initialized,J.toolboxService.initialized]).then(()=>{return}),toolService:J.toolService,skillService:J.skillService,getThreadEnvironment:uY,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new hV(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 P.error("[createDTWThreadPool] Failed to create DTW thread pool",{threadId:J.threadId,error:Z}),Z}}async function bx3(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await Bv()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await Bv()).trimEnd(),stdinInput:null}}function hx3(J,Z,Q){if(J.remote&&!Z)throw new T1("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(J.streamJson&&!Z)throw new T1("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new T1("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new T1("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new T1("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new T1("The --archive flag requires --execute mode",1,'Use: amp --execute "your message" --archive');if(J.streamJsonInput&&typeof J.execute==="string"&&J.execute.trim()!=="")throw new T1("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"..."}}]}}' | amp --execute --stream-json --stream-json-input`);if(Z&&Q===""&&!J.streamJsonInput&&!J.headless)throw new T1("User message must be provided through stdin or as argument when using execute mode",1,`Either pass a message as an argument: amp --execute "your message"
|
|
7676
7674
|
Or pipe via stdin: echo "your message" | amp --execute`)}async function HF0(J,Z,Q,Y){let X=process.hrtime.bigint(),K=(z0,J0)=>{let G0=Number(process.hrtime.bigint()-J0)/1e6,i=XO4();P.info("Startup phase",{phase:z0,phaseMs:Math.round(G0),sinceMainMs:i===null?void 0:Math.round(i)})},{userInput:V,stdinInput:z}=await bx3(Z),G=!!Z.streamJson||!!Z.streamJsonThinking;hx3({...Z,streamJson:G},J.executeMode,V),A2(Q,Z);let F=process.hrtime.bigint(),q=Boolean(await J.secrets.get("apiKey",J.ampURL)),W=!J.executeMode&&!Z.headless&&!Z.threadActors&&q;P.info("Interactive auth startup mode",{deferInteractiveAuth:W,hasAPIKeyAtStartup:q,executeMode:J.executeMode,headless:Boolean(Z.headless)});let U=await R7(J,Z,{deferAuth:W});K("runMainThread:createThreadDependencies",F),F=process.hrtime.bigint();let H=await Q51(U);K("runMainThread:createWorkerDeps",F);let{serverStatus:D}=U;if(!W&&bW(D)){let z0=ak(Error(D.error.message));if(z0.message===E3.networkOffline||z0.message===E3.networkTimeout)throw WF0(J.ampURL);throw new T1(E3.invalidAPIKey,1)}let B=o6(D)?D:null,N=B?.user.email,w=In4(N),L=t61({userEmail:N,features:B?.features}),O=Z.takeMeBack?!1:void 0,E=B!==null&&e61(O,B);if(!W)await s61(Q,Z,D);let M=$51(D),A=M?.features??[],j=M?.team??null,R=HX0(Z,M);if(R instanceof Error)s3(R.message);if((J.executeMode||G)&&N8(Z.mode)&&!w)throw new T1(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(B&&!ZE(Z.mode,N))throw new T1(`Agent mode '${Z.mode}' is only available for Amp employees`,1);if(J.executeMode&&Z.remote)await WT4(V,z,U.configService),await U.asyncDispose(),process.exit(0);if(Z.headless){if(!N||!dJ(N))throw new T1("Headless DTW mode is only available for Amp employees",1);let z0=await U.secretStorage.get("apiKey",J.ampURL);if(!z0)throw new T1("API key required for headless mode. Please run `amp login` first.",1);let J0=typeof Z.headless==="string"&&Z.headless!=="true"?Z.headless:void 0;if(J0&&!b9(J0))throw new T1(`Invalid thread ID: ${J0}`,1);let G0=J0?void 0:await tx3({dependencies:U,visibility:R??void 0,usesThreadActors:Z.threadActors?!0:void 0}),i=J0??G0?.threadId;if(!i)throw new T1("Failed to resolve headless thread ID",1);let o=await KI4(i);if(o.status==="already-running")await U.asyncDispose(),await VH(),process.exit(0);try{await eR4({ampURL:J.ampURL,apiKey:z0,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:i,ownerUserId:G0?.ownerUserId,threadVersion:G0?.threadVersion,agentMode:G0?.agentMode,initialToolDiscovery:Promise.all([U.mcpService.initialized,U.toolboxService.initialized]).then(()=>{return}),configService:U.configService,mcpService:U.mcpService,toolService:U.toolService,skillService:U.skillService,fileSystem:U.fileSystem,pluginService:U.pluginService,pluginPlatform:U.headlessPluginPlatform,useThreadActors:Z.threadActors?!0:void 0})}finally{await o.release(),await U.asyncDispose()}await VH(),process.exit(0)}let _=J.executeMode?void 0:async(z0)=>Lo(z0,"interactive"),T={threadService:U.threadService,workerDeps:H,createThread:async()=>{let z0=W?await U.serverStatusPromise:D,J0=await sQ0(J.settings,process.cwd(),$51(z0),R);if(J0 instanceof Error)s3(J0.message);return Ze0(H,{threadMeta:J0?vz(J0):void 0,agentMode:Z.mode,onFirstAssistantMessage:_})},validateThreadOwnership:async(z0,J0)=>{if(J0?.nonBlockingOwnershipCheck){wn4(z0,U.configService).catch((G0)=>{if(G0 instanceof T1){if(J0.onOwnershipError){J0.onOwnershipError(G0,z0);return}zH(G0,z0);return}P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:G0})});return}try{await wn4(z0,U.configService)}catch(G0){if(G0 instanceof T1)throw G0;P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:G0})}},switchThreadVisibility:R,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:_,handleError:zH},u=async(z0)=>{try{if(z0==="dtw")return ux3({ampURL:J.ampURL,configService:U.configService,threadService:U.threadService,mcpService:U.mcpService,clientID:Wn4,toolboxService:U.toolboxService,toolService:U.toolService,skillService:U.skillService,fileSystem:U.fileSystem,threadId:Z.threadId,useThreadActors:Z.threadActors?!0:void 0});return Lf4(T,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch(J0){if(J0 instanceof T1)throw J0;throw await zH(J0,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")j2.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
7677
|
-
`),await VH(),process.exit(1);let m=(async()=>{if(W){P.info("Skipping initial free tier status fetch until auth is complete");return}try{let z0=await U.configService.getLatest(),J0=ou(z0),G0=await g6.getUserFreeTierStatus({},{config:U.configService,signal:AbortSignal.timeout(J0)});if(G0.ok)return P.info("User free tier status:",G0),G0.result;return}catch(z0){P.error("Failed to fetch free tier status:",z0);return}})(),k=!J.executeMode?new st0:null,f,d=null;if(k)f=k,d=(async()=>{let z0=W?await U.serverStatusPromise:U.serverStatus;await s61(Q,Z,z0);let J0=process.hrtime.bigint(),G0=e61(O,z0),i=o6(z0)?t61({userEmail:z0.user.email,features:z0.features}):!1;Un4({dtwEnabled:G0,hasV2TUIAccess:i});let o=await u(G0?"dtw":"worker");if(K("runMainThread:createThreadPool",J0),k.attach(o),V){let t=await j1(o.threadHandles$);if(!t)throw new T1("No active thread is available yet.",1);await t.sendMessage({content:[{type:"text",text:V}]})}})(),d.catch(async(z0)=>{let J0=z0 instanceof Error?z0:Error(String(z0));k.setInitError(J0),await zH(z0,Z.threadId)});else F=process.hrtime.bigint(),Un4({dtwEnabled:E,hasV2TUIAccess:L}),f=await u(E?"dtw":"worker"),K("runMainThread:createThreadPool",F);let p=Z.notifications!==void 0?Z.notifications:!J.executeMode;F=process.hrtime.bigint();let h=await U.configService.getLatest();if(K("runMainThread:configService.getLatest",F),F=process.hrtime.bigint(),Cx3({configService:U.configService,threadService:U.threadService,config:h,useNotificationsForService:p,threadViewStates$:()=>f.threadHandles$.pipe(H4((z0)=>{if(!z0)return k0.of({});return D5(z0.thread$,z0.threadViewState$).pipe(D1(([J0,G0])=>({[J0.id]:G0})))}))}),K("runMainThread:createCliNotificationService",F),J.executeMode){$T4(U.mcpService,J.settings);let z0={userInput:V,stdinInput:z,dependencies:U,streamJson:G,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label},J0=await HR4({threadPool:f,...z0});if(await Lo(J0,"execute"),Z.archive)await g6.archiveThread({thread:J0,archived:!0},{config:U.configService});await U.asyncDispose(),process.exit(0)}let n=!1,c=!1;if(Z.jetbrains||Z.ide){await tf1();let z0=await VE({jetbrainsOnly:Z.jetbrains});if(z0.length===0){if(Z.jetbrains)n=!await U.configService.get("jetbrains.skipInstall")}else if(z0.length===1){let J0=z0[0];if(J0)w$.selectConfig(J0)}else c=!0}F=process.hrtime.bigint();let a=pa0("0.0.
|
|
7678
|
-
`);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;P.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await za1({get:async(z)=>{if(z!==rh)return;try{let G=await An4(r61,"utf-8");return JSON.parse(G).installationID}catch{return}},set:async(z,G)=>{if(z!==rh)return;await Mn4(lH.dirname(r61),{recursive:!0}),await Bx3(r61,JSON.stringify({installationID:G},null,2),{mode:384})}},{clientType:"cli",platform:vG()});Xf1(Y);let X=await LI4({...J,workspaceTrust:{current:!0,changes:su},getHook:process.env.AMP_URL?(z,G)=>{if(z==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(J.mcpConfig){let z=await tC4(J.mcpConfig);X=eC4(X,z)}let K=lH.dirname(X.getSettingsFilePath());Gq4(Qv,K);let V=await X.get("url","global");if(!V)V=G7;if(P.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!OV(V))P.info("Targeting custom Amp server",{ampURL:V});return X=ox1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:NT4(await Ea0(J,X))}}function gx3(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let K=Y.slice(2).replace(/-([a-z])/g,(z,G)=>G.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}function mx3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=lH.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?Lx3:Pn0));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function px3(){YO4();let J=gx3(process.argv),Z=mx3(process.argv,J),Q=Hj4(Z),Y=process.argv.includes("--no-color"),X=process.argv.includes("--color"),K=process.stdout.isTTY&&process.stderr.isTTY;if(Y||!X&&!K)o0.level=0;if(Ex3(P),P.info("Starting Amp CLI.",{version:"0.0.
|
|
7675
|
+
`),await VH(),process.exit(1);let m=(async()=>{if(W){P.info("Skipping initial free tier status fetch until auth is complete");return}try{let z0=await U.configService.getLatest(),J0=ou(z0),G0=await g6.getUserFreeTierStatus({},{config:U.configService,signal:AbortSignal.timeout(J0)});if(G0.ok)return P.info("User free tier status:",G0),G0.result;return}catch(z0){P.error("Failed to fetch free tier status:",z0);return}})(),k=!J.executeMode?new st0:null,f,d=null;if(k)f=k,d=(async()=>{let z0=W?await U.serverStatusPromise:U.serverStatus;await s61(Q,Z,z0);let J0=process.hrtime.bigint(),G0=e61(O,z0),i=o6(z0)?t61({userEmail:z0.user.email,features:z0.features}):!1;Un4({dtwEnabled:G0,hasV2TUIAccess:i});let o=await u(G0?"dtw":"worker");if(K("runMainThread:createThreadPool",J0),k.attach(o),V){let t=await j1(o.threadHandles$);if(!t)throw new T1("No active thread is available yet.",1);await t.sendMessage({content:[{type:"text",text:V}]})}})(),d.catch(async(z0)=>{let J0=z0 instanceof Error?z0:Error(String(z0));k.setInitError(J0),await zH(z0,Z.threadId)});else F=process.hrtime.bigint(),Un4({dtwEnabled:E,hasV2TUIAccess:L}),f=await u(E?"dtw":"worker"),K("runMainThread:createThreadPool",F);let p=Z.notifications!==void 0?Z.notifications:!J.executeMode;F=process.hrtime.bigint();let h=await U.configService.getLatest();if(K("runMainThread:configService.getLatest",F),F=process.hrtime.bigint(),Cx3({configService:U.configService,threadService:U.threadService,config:h,useNotificationsForService:p,threadViewStates$:()=>f.threadHandles$.pipe(H4((z0)=>{if(!z0)return k0.of({});return D5(z0.thread$,z0.threadViewState$).pipe(D1(([J0,G0])=>({[J0.id]:G0})))}))}),K("runMainThread:createCliNotificationService",F),J.executeMode){$T4(U.mcpService,J.settings);let z0={userInput:V,stdinInput:z,dependencies:U,streamJson:G,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label},J0=await HR4({threadPool:f,...z0});if(await Lo(J0,"execute"),Z.archive)await g6.archiveThread({thread:J0,archived:!0},{config:U.configService});await U.asyncDispose(),process.exit(0)}let n=!1,c=!1;if(Z.jetbrains||Z.ide){await tf1();let z0=await VE({jetbrainsOnly:Z.jetbrains});if(z0.length===0){if(Z.jetbrains)n=!await U.configService.get("jetbrains.skipInstall")}else if(z0.length===1){let J0=z0[0];if(J0)w$.selectConfig(J0)}else c=!0}F=process.hrtime.bigint();let a=pa0("0.0.1774866438-g7cb400",U.settingsStorage,{startDelayMs:3000});K("runMainThread:createUpdateService",F),F=process.hrtime.bigint();let W0=new Ao0(U.mcpService,J.settings.getWorkspaceRootPath());if(K("runMainThread:createMcpTrustHandler",F),V&&J.executeMode){let z0=await j1(f.threadHandles$);if(!z0)throw new T1("No active thread is available yet.",1);await z0.sendMessage({content:[{type:"text",text:V}]})}F=process.hrtime.bigint();let r=await wX0();K("runMainThread:loadSessionState",F),P.info("Loaded session state:",r);let H0={...r,launchCount:r.launchCount+1};Ij((z0)=>({...z0,launchCount:z0.launchCount+1}));let L0=Z.threadId&&b9(Z.threadId)?Z.threadId:void 0;try{if(F=process.hrtime.bigint(),await zu4({codebaseContextService:U.codebaseContextService,history:new Qa0,fuzzyServer:U.fuzzyServer,settingsStorage:U.settingsStorage,threadService:U.threadService,skillService:U.skillService,configService:U.configService,secretStorage:U.secretStorage,internalAPIClient:g6,threadPool:f,createSystemPromptDeps:async()=>Cn4(U),ideClient:w$,mcpService:U.mcpService,toolboxService:U.toolboxService,mcpTrustHandler:W0,updateService:a,pluginPlatform:U.pluginPlatform,pluginService:U.pluginService},{initialServerStatus:U.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:U.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:L0,showJetBrainsInstaller:n,showIdePickerHint:c,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Wn4,logFile:{path:Y},sessionState:H0,freeTierStatusPromise:m,workspace:j??null,features:A,isDogfooding:w,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-30T10:31:14.209Z"},(z0)=>new De0({...z0,threadPool:z0.threadPool},(J0)=>new M41({...J0,threadState:J0.threadState}))),K("runMainThread:mountApp-returned",F),d)await d}finally{}await U.asyncDispose(),K("runMainThread:dependencies.asyncDispose",X),process.exit(0)}async function r3(J){if(P.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),J.interactive)j2.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
7676
|
+
`);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;P.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await za1({get:async(z)=>{if(z!==rh)return;try{let G=await An4(r61,"utf-8");return JSON.parse(G).installationID}catch{return}},set:async(z,G)=>{if(z!==rh)return;await Mn4(lH.dirname(r61),{recursive:!0}),await Bx3(r61,JSON.stringify({installationID:G},null,2),{mode:384})}},{clientType:"cli",platform:vG()});Xf1(Y);let X=await LI4({...J,workspaceTrust:{current:!0,changes:su},getHook:process.env.AMP_URL?(z,G)=>{if(z==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(J.mcpConfig){let z=await tC4(J.mcpConfig);X=eC4(X,z)}let K=lH.dirname(X.getSettingsFilePath());Gq4(Qv,K);let V=await X.get("url","global");if(!V)V=G7;if(P.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!OV(V))P.info("Targeting custom Amp server",{ampURL:V});return X=ox1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:NT4(await Ea0(J,X))}}function gx3(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let K=Y.slice(2).replace(/-([a-z])/g,(z,G)=>G.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}function mx3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=lH.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?Lx3:Pn0));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function px3(){YO4();let J=gx3(process.argv),Z=mx3(process.argv,J),Q=Hj4(Z),Y=process.argv.includes("--no-color"),X=process.argv.includes("--color"),K=process.stdout.isTTY&&process.stderr.isTTY;if(Y||!X&&!K)o0.level=0;if(Ex3(P),P.info("Starting Amp CLI.",{version:"0.0.1774866438-g7cb400",buildTimestamp:"2026-03-30T10:31:14.209Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new T1(E3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await fx3(Q).parseAsync(process.argv)}Vq4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await px3().catch(zH)});async function dx3(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"),Y5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
7679
7677
|
`);else if(!OV(J.ampURL))Y5.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
7680
7678
|
`);let Y=process.env.AMP_API_KEY;if(Y)Y5.write(`API key found in environment variable, storing...
|
|
7681
7679
|
`),await Z.set("apiKey",Y,J.ampURL),Y5.write(`API key successfully stored.
|