@sourcegraph/amp 0.0.1773462612-g20fbe1 → 0.0.1773489712-g258ad5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.js +13 -13
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -2548,7 +2548,7 @@ ${Q.error.stderr}`;return V}case"connected":{let V=J.tools;if(V instanceof Error
2548
2548
  `,Q};LA4.decode=function(J){var Z=[],Q=/\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g,Y=/([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/,X=/\r?\n/,V;while(!0){if(V=Q.exec(J),!V)break;var K=V[1];if(K==="NEW CERTIFICATE REQUEST")K="CERTIFICATE REQUEST";var z={type:K,procType:null,contentDomain:null,dekInfo:null,headers:[],body:fJ0.util.decode64(V[3])};if(Z.push(z),!V[2])continue;var G=V[2].split(X),F=0;while(V&&F<G.length){var U=G[F].replace(/\s+$/,"");for(var q=F+1;q<G.length;++q){var D=G[q];if(!/\s/.test(D[0]))break;U+=D,F=q}if(V=U.match(Y),V){var W={name:V[1],values:[]},H=V[2].split(",");for(var B=0;B<H.length;++B)W.values.push(ms5(H[B]));if(!z.procType){if(W.name!=="Proc-Type")throw Error('Invalid PEM formatted message. The first encapsulated header must be "Proc-Type".');else if(W.values.length!==2)throw Error('Invalid PEM formatted message. The "Proc-Type" header must have two subfields.');z.procType={version:H[0],type:H[1]}}else if(!z.contentDomain&&W.name==="Content-Domain")z.contentDomain=H[0]||"";else if(!z.dekInfo&&W.name==="DEK-Info"){if(W.values.length===0)throw Error('Invalid PEM formatted message. The "DEK-Info" header must have at least one subfield.');z.dekInfo={algorithm:H[0],parameters:H[1]||null}}else z.headers.push(W)}++F}if(z.procType==="ENCRYPTED"&&!z.dekInfo)throw Error('Invalid PEM formatted message. The "DEK-Info" header must be present if "Proc-Type" is "ENCRYPTED".')}if(Z.length===0)throw Error("Invalid PEM formatted message.");return Z};function xJ0(J){var Z=J.name+": ",Q=[],Y=function(G,F){return" "+F};for(var X=0;X<J.values.length;++X)Q.push(J.values[X].replace(/^(\S+\r\n)/,Y));Z+=Q.join(",")+`\r
2549
2549
  `;var V=0,K=-1;for(var X=0;X<Z.length;++X,++V)if(V>65&&K!==-1){var z=Z[K];if(z===",")++K,Z=Z.substr(0,K)+`\r
2550
2550
  `+Z.substr(K);else Z=Z.substr(0,K)+`\r
2551
- `+z+Z.substr(K+1);V=X-K-1,K=-1,++X}else if(Z[X]===" "||Z[X]==="\t"||Z[X]===",")K=X;return Z}function ms5(J){return J.replace(/^\s+/,"")}});var wd=u((lO9,IA4)=>{var x8=J5();CJ0();Fc0();c5();IA4.exports=x8.des=x8.des||{};x8.des.startEncrypting=function(J,Z,Q,Y){var X=bJ0({key:J,output:Q,decrypt:!1,mode:Y||(Z===null?"ECB":"CBC")});return X.start(Z),X};x8.des.createEncryptionCipher=function(J,Z){return bJ0({key:J,output:null,decrypt:!1,mode:Z})};x8.des.startDecrypting=function(J,Z,Q,Y){var X=bJ0({key:J,output:Q,decrypt:!0,mode:Y||(Z===null?"ECB":"CBC")});return X.start(Z),X};x8.des.createDecryptionCipher=function(J,Z){return bJ0({key:J,output:null,decrypt:!0,mode:Z})};x8.des.Algorithm=function(J,Z){var Q=this;Q.name=J,Q.mode=new Z({blockSize:8,cipher:{encrypt:function(Y,X){return AA4(Q._keys,Y,X,!1)},decrypt:function(Y,X){return AA4(Q._keys,Y,X,!0)}}}),Q._init=!1};x8.des.Algorithm.prototype.initialize=function(J){if(this._init)return;var Z=x8.util.createBuffer(J.key);if(this.name.indexOf("3DES")===0){if(Z.length()!==24)throw Error("Invalid Triple-DES key size: "+Z.length()*8)}this._keys=os5(Z),this._init=!0};EG("DES-ECB",x8.cipher.modes.ecb);EG("DES-CBC",x8.cipher.modes.cbc);EG("DES-CFB",x8.cipher.modes.cfb);EG("DES-OFB",x8.cipher.modes.ofb);EG("DES-CTR",x8.cipher.modes.ctr);EG("3DES-ECB",x8.cipher.modes.ecb);EG("3DES-CBC",x8.cipher.modes.cbc);EG("3DES-CFB",x8.cipher.modes.cfb);EG("3DES-OFB",x8.cipher.modes.ofb);EG("3DES-CTR",x8.cipher.modes.ctr);function EG(J,Z){var Q=function(){return new x8.des.Algorithm(J,Z)};x8.cipher.registerAlgorithm(J,Q)}var gs5=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],ps5=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],ds5=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],cs5=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],ls5=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],is5=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],ns5=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],as5=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];function os5(J){var Z=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],Q=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],Y=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],X=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],V=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],K=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],z=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],G=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],F=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],U=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],q=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],D=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],W=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],H=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],B=J.length()>8?3:1,w=[],N=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],O=0,E;for(var L=0;L<B;L++){var M=J.getInt32(),A=J.getInt32();E=(M>>>4^A)&252645135,A^=E,M^=E<<4,E=(A>>>-16^M)&65535,M^=E,A^=E<<-16,E=(M>>>2^A)&858993459,A^=E,M^=E<<2,E=(A>>>-16^M)&65535,M^=E,A^=E<<-16,E=(M>>>1^A)&1431655765,A^=E,M^=E<<1,E=(A>>>8^M)&16711935,M^=E,A^=E<<8,E=(M>>>1^A)&1431655765,A^=E,M^=E<<1,E=M<<8|A>>>20&240,M=A<<24|A<<8&16711680|A>>>8&65280|A>>>24&240,A=E;for(var I=0;I<N.length;++I){if(N[I])M=M<<2|M>>>26,A=A<<2|A>>>26;else M=M<<1|M>>>27,A=A<<1|A>>>27;M&=-15,A&=-15;var P=Z[M>>>28]|Q[M>>>24&15]|Y[M>>>20&15]|X[M>>>16&15]|V[M>>>12&15]|K[M>>>8&15]|z[M>>>4&15],_=G[A>>>28]|F[A>>>24&15]|U[A>>>20&15]|q[A>>>16&15]|D[A>>>12&15]|W[A>>>8&15]|H[A>>>4&15];E=(_>>>16^P)&65535,w[O++]=P^E,w[O++]=_^E<<16}}return w}function AA4(J,Z,Q,Y){var X=J.length===32?3:9,V;if(X===3)V=Y?[30,-2,-2]:[0,32,2];else V=Y?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var K,z=Z[0],G=Z[1];K=(z>>>4^G)&252645135,G^=K,z^=K<<4,K=(z>>>16^G)&65535,G^=K,z^=K<<16,K=(G>>>2^z)&858993459,z^=K,G^=K<<2,K=(G>>>8^z)&16711935,z^=K,G^=K<<8,K=(z>>>1^G)&1431655765,G^=K,z^=K<<1,z=z<<1|z>>>31,G=G<<1|G>>>31;for(var F=0;F<X;F+=3){var U=V[F+1],q=V[F+2];for(var D=V[F];D!=U;D+=q){var W=G^J[D],H=(G>>>4|G<<28)^J[D+1];K=z,z=G,G=K^(ps5[W>>>24&63]|cs5[W>>>16&63]|is5[W>>>8&63]|as5[W&63]|gs5[H>>>24&63]|ds5[H>>>16&63]|ls5[H>>>8&63]|ns5[H&63])}K=z,z=G,G=K}z=z>>>1|z<<31,G=G>>>1|G<<31,K=(z>>>1^G)&1431655765,G^=K,z^=K<<1,K=(G>>>8^z)&16711935,z^=K,G^=K<<8,K=(G>>>2^z)&858993459,z^=K,G^=K<<2,K=(z>>>16^G)&65535,G^=K,z^=K<<16,K=(z>>>4^G)&252645135,G^=K,z^=K<<4,Q[0]=z,Q[1]=G}function bJ0(J){J=J||{};var Z=(J.mode||"CBC").toUpperCase(),Q="DES-"+Z,Y;if(J.decrypt)Y=x8.cipher.createDecipher(Q,J.key);else Y=x8.cipher.createCipher(Q,J.key);var X=Y.start;return Y.start=function(V,K){var z=null;if(K instanceof x8.util.ByteBuffer)z=K,K={};K=K||{},K.output=z,K.iv=V,X.call(Y,K)},Y}});var hJ0=u((iO9,jA4)=>{var WJ=J5();Y_();NG();c5();var rs5=WJ.pkcs5=WJ.pkcs5||{},eU;if(WJ.util.isNodejs&&!WJ.options.usePureJavaScript)eU=j0("crypto");jA4.exports=WJ.pbkdf2=rs5.pbkdf2=function(J,Z,Q,Y,X,V){if(typeof X==="function")V=X,X=null;if(WJ.util.isNodejs&&!WJ.options.usePureJavaScript&&eU.pbkdf2&&(X===null||typeof X!=="object")&&(eU.pbkdf2Sync.length>4||(!X||X==="sha1"))){if(typeof X!=="string")X="sha1";if(J=Buffer.from(J,"binary"),Z=Buffer.from(Z,"binary"),!V){if(eU.pbkdf2Sync.length===4)return eU.pbkdf2Sync(J,Z,Q,Y).toString("binary");return eU.pbkdf2Sync(J,Z,Q,Y,X).toString("binary")}if(eU.pbkdf2Sync.length===4)return eU.pbkdf2(J,Z,Q,Y,function(E,L){if(E)return V(E);V(null,L.toString("binary"))});return eU.pbkdf2(J,Z,Q,Y,X,function(E,L){if(E)return V(E);V(null,L.toString("binary"))})}if(typeof X>"u"||X===null)X="sha1";if(typeof X==="string"){if(!(X in WJ.md.algorithms))throw Error("Unknown hash algorithm: "+X);X=WJ.md[X].create()}var K=X.digestLength;if(Y>4294967295*K){var z=Error("Derived key is too long.");if(V)return V(z);throw z}var G=Math.ceil(Y/K),F=Y-(G-1)*K,U=WJ.hmac.create();U.start(X,J);var q="",D,W,H;if(!V){for(var B=1;B<=G;++B){U.start(null,null),U.update(Z),U.update(WJ.util.int32ToBytes(B)),D=H=U.digest().getBytes();for(var w=2;w<=Q;++w)U.start(null,null),U.update(H),W=U.digest().getBytes(),D=WJ.util.xorBytes(D,W,K),H=W;q+=B<G?D:D.substr(0,F)}return q}var B=1,w;function N(){if(B>G)return V(null,q);U.start(null,null),U.update(Z),U.update(WJ.util.int32ToBytes(B)),D=H=U.digest().getBytes(),w=2,O()}function O(){if(w<=Q)return U.start(null,null),U.update(H),W=U.digest().getBytes(),D=WJ.util.xorBytes(D,W,K),H=W,++w,WJ.util.setImmediate(O);q+=B<G?D:D.substr(0,F),++B,N()}N()}});var wc0=u((nO9,_A4)=>{var LG=J5();NG();c5();var PA4=_A4.exports=LG.sha256=LG.sha256||{};LG.md.sha256=LG.md.algorithms.sha256=PA4;PA4.create=function(){if(!CA4)ss5();var J=null,Z=LG.util.createBuffer(),Q=Array(64),Y={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8};return Y.start=function(){Y.messageLength=0,Y.fullMessageLength=Y.messageLength64=[];var X=Y.messageLengthSize/4;for(var V=0;V<X;++V)Y.fullMessageLength.push(0);return Z=LG.util.createBuffer(),J={h0:1779033703,h1:3144134277,h2:1013904242,h3:2773480762,h4:1359893119,h5:2600822924,h6:528734635,h7:1541459225},Y},Y.start(),Y.update=function(X,V){if(V==="utf8")X=LG.util.encodeUtf8(X);var K=X.length;Y.messageLength+=K,K=[K/4294967296>>>0,K>>>0];for(var z=Y.fullMessageLength.length-1;z>=0;--z)Y.fullMessageLength[z]+=K[1],K[1]=K[0]+(Y.fullMessageLength[z]/4294967296>>>0),Y.fullMessageLength[z]=Y.fullMessageLength[z]>>>0,K[0]=K[1]/4294967296>>>0;if(Z.putBytes(X),RA4(J,Q,Z),Z.read>2048||Z.length()===0)Z.compact();return Y},Y.digest=function(){var X=LG.util.createBuffer();X.putBytes(Z.bytes());var V=Y.fullMessageLength[Y.fullMessageLength.length-1]+Y.messageLengthSize,K=V&Y.blockLength-1;X.putBytes(Bc0.substr(0,Y.blockLength-K));var z,G,F=Y.fullMessageLength[0]*8;for(var U=0;U<Y.fullMessageLength.length-1;++U)z=Y.fullMessageLength[U+1]*8,G=z/4294967296>>>0,F+=G,X.putInt32(F>>>0),F=z>>>0;X.putInt32(F);var q={h0:J.h0,h1:J.h1,h2:J.h2,h3:J.h3,h4:J.h4,h5:J.h5,h6:J.h6,h7:J.h7};RA4(q,Q,X);var D=LG.util.createBuffer();return D.putInt32(q.h0),D.putInt32(q.h1),D.putInt32(q.h2),D.putInt32(q.h3),D.putInt32(q.h4),D.putInt32(q.h5),D.putInt32(q.h6),D.putInt32(q.h7),D},Y};var Bc0=null,CA4=!1,TA4=null;function ss5(){Bc0=String.fromCharCode(128),Bc0+=LG.util.fillString(String.fromCharCode(0),64),TA4=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],CA4=!0}function RA4(J,Z,Q){var Y,X,V,K,z,G,F,U,q,D,W,H,B,w,N,O=Q.length();while(O>=64){for(F=0;F<16;++F)Z[F]=Q.getInt32();for(;F<64;++F)Y=Z[F-2],Y=(Y>>>17|Y<<15)^(Y>>>19|Y<<13)^Y>>>10,X=Z[F-15],X=(X>>>7|X<<25)^(X>>>18|X<<14)^X>>>3,Z[F]=Y+Z[F-7]+X+Z[F-16]|0;U=J.h0,q=J.h1,D=J.h2,W=J.h3,H=J.h4,B=J.h5,w=J.h6,N=J.h7;for(F=0;F<64;++F)K=(H>>>6|H<<26)^(H>>>11|H<<21)^(H>>>25|H<<7),z=w^H&(B^w),V=(U>>>2|U<<30)^(U>>>13|U<<19)^(U>>>22|U<<10),G=U&q|D&(U^q),Y=N+K+z+TA4[F]+Z[F],X=V+G,N=w,w=B,B=H,H=W+Y>>>0,W=D,D=q,q=U,U=Y+X>>>0;J.h0=J.h0+U|0,J.h1=J.h1+q|0,J.h2=J.h2+D|0,J.h3=J.h3+W|0,J.h4=J.h4+H|0,J.h5=J.h5+B|0,J.h6=J.h6+w|0,J.h7=J.h7+N|0,O-=64}}});var Nc0=u((aO9,SA4)=>{var MG=J5();c5();var mJ0=null;if(MG.util.isNodejs&&!MG.options.usePureJavaScript&&!process.versions["node-webkit"])mJ0=j0("crypto");var ts5=SA4.exports=MG.prng=MG.prng||{};ts5.create=function(J){var Z={plugin:J,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},Q=J.md,Y=Array(32);for(var X=0;X<32;++X)Y[X]=Q.create();Z.pools=Y,Z.pool=0,Z.generate=function(F,U){if(!U)return Z.generateSync(F);var q=Z.plugin.cipher,D=Z.plugin.increment,W=Z.plugin.formatKey,H=Z.plugin.formatSeed,B=MG.util.createBuffer();Z.key=null,w();function w(N){if(N)return U(N);if(B.length()>=F)return U(null,B.getBytes(F));if(Z.generated>1048575)Z.key=null;if(Z.key===null)return MG.util.nextTick(function(){V(w)});var O=q(Z.key,Z.seed);Z.generated+=O.length,B.putBytes(O),Z.key=W(q(Z.key,D(Z.seed))),Z.seed=H(q(Z.key,Z.seed)),MG.util.setImmediate(w)}},Z.generateSync=function(F){var U=Z.plugin.cipher,q=Z.plugin.increment,D=Z.plugin.formatKey,W=Z.plugin.formatSeed;Z.key=null;var H=MG.util.createBuffer();while(H.length()<F){if(Z.generated>1048575)Z.key=null;if(Z.key===null)K();var B=U(Z.key,Z.seed);Z.generated+=B.length,H.putBytes(B),Z.key=D(U(Z.key,q(Z.seed))),Z.seed=W(U(Z.key,Z.seed))}return H.getBytes(F)};function V(F){if(Z.pools[0].messageLength>=32)return z(),F();var U=32-Z.pools[0].messageLength<<5;Z.seedFile(U,function(q,D){if(q)return F(q);Z.collect(D),z(),F()})}function K(){if(Z.pools[0].messageLength>=32)return z();var F=32-Z.pools[0].messageLength<<5;Z.collect(Z.seedFileSync(F)),z()}function z(){Z.reseeds=Z.reseeds===4294967295?0:Z.reseeds+1;var F=Z.plugin.md.create();F.update(Z.keyBytes);var U=1;for(var q=0;q<32;++q){if(Z.reseeds%U===0)F.update(Z.pools[q].digest().getBytes()),Z.pools[q].start();U=U<<1}Z.keyBytes=F.digest().getBytes(),F.start(),F.update(Z.keyBytes);var D=F.digest().getBytes();Z.key=Z.plugin.formatKey(Z.keyBytes),Z.seed=Z.plugin.formatSeed(D),Z.generated=0}function G(F){var U=null,q=MG.util.globalScope,D=q.crypto||q.msCrypto;if(D&&D.getRandomValues)U=function(M){return D.getRandomValues(M)};var W=MG.util.createBuffer();if(U)while(W.length()<F){var H=Math.max(1,Math.min(F-W.length(),65536)/4),B=new Uint32Array(Math.floor(H));try{U(B);for(var w=0;w<B.length;++w)W.putInt32(B[w])}catch(M){if(!(typeof QuotaExceededError<"u"&&M instanceof QuotaExceededError))throw M}}if(W.length()<F){var N,O,E,L=Math.floor(Math.random()*65536);while(W.length()<F){O=16807*(L&65535),N=16807*(L>>16),O+=(N&32767)<<16,O+=N>>15,O=(O&2147483647)+(O>>31),L=O&4294967295;for(var w=0;w<3;++w)E=L>>>(w<<3),E^=Math.floor(Math.random()*256),W.putByte(E&255)}}return W.getBytes(F)}if(mJ0)Z.seedFile=function(F,U){mJ0.randomBytes(F,function(q,D){if(q)return U(q);U(null,D.toString())})},Z.seedFileSync=function(F){return mJ0.randomBytes(F).toString()};else Z.seedFile=function(F,U){try{U(null,G(F))}catch(q){U(q)}},Z.seedFileSync=G;return Z.collect=function(F){var U=F.length;for(var q=0;q<U;++q)Z.pools[Z.pool].update(F.substr(q,1)),Z.pool=Z.pool===31?0:Z.pool+1},Z.collectInt=function(F,U){var q="";for(var D=0;D<U;D+=8)q+=String.fromCharCode(F>>D&255);Z.collect(q)},Z.registerWorker=function(F){if(F===self)Z.seedFile=function(q,D){function W(H){var B=H.data;if(B.forge&&B.forge.prng)self.removeEventListener("message",W),D(B.forge.prng.err,B.forge.prng.bytes)}self.addEventListener("message",W),self.postMessage({forge:{prng:{needed:q}}})};else{var U=function(q){var D=q.data;if(D.forge&&D.forge.prng)Z.seedFile(D.forge.prng.needed,function(W,H){F.postMessage({forge:{prng:{err:W,bytes:H}}})})};F.addEventListener("message",U)}},Z}});var JX=u((oO9,Oc0)=>{var r7=J5();KB();wc0();Nc0();c5();(function(){if(r7.random&&r7.random.getBytes){Oc0.exports=r7.random;return}(function(J){var Z={},Q=[,,,,],Y=r7.util.createBuffer();Z.formatKey=function(q){var D=r7.util.createBuffer(q);return q=[,,,,],q[0]=D.getInt32(),q[1]=D.getInt32(),q[2]=D.getInt32(),q[3]=D.getInt32(),r7.aes._expandKey(q,!1)},Z.formatSeed=function(q){var D=r7.util.createBuffer(q);return q=[,,,,],q[0]=D.getInt32(),q[1]=D.getInt32(),q[2]=D.getInt32(),q[3]=D.getInt32(),q},Z.cipher=function(q,D){return r7.aes._updateBlock(q,D,Q,!1),Y.putInt32(Q[0]),Y.putInt32(Q[1]),Y.putInt32(Q[2]),Y.putInt32(Q[3]),Y.getBytes()},Z.increment=function(q){return++q[3],q},Z.md=r7.md.sha256;function X(){var q=r7.prng.create(Z);return q.getBytes=function(D,W){return q.generate(D,W)},q.getBytesSync=function(D){return q.generate(D)},q}var V=X(),K=null,z=r7.util.globalScope,G=z.crypto||z.msCrypto;if(G&&G.getRandomValues)K=function(q){return G.getRandomValues(q)};if(r7.options.usePureJavaScript||!r7.util.isNodejs&&!K){if(typeof window>"u"||window.document===void 0);if(V.collectInt(+new Date,32),typeof navigator<"u"){var F="";for(var U in navigator)try{if(typeof navigator[U]=="string")F+=navigator[U]}catch(q){}V.collect(F),F=null}if(J)J().mousemove(function(q){V.collectInt(q.clientX,16),V.collectInt(q.clientY,16)}),J().keypress(function(q){V.collectInt(q.charCode,8)})}if(!r7.random)r7.random=V;else for(var U in V)r7.random[U]=V[U];r7.random.createInstance=X,Oc0.exports=r7.random})(typeof jQuery<"u"?jQuery:null)})()});var Lc0=u((rO9,yA4)=>{var BZ=J5();c5();var Ec0=[217,120,249,196,25,221,181,237,40,233,253,121,74,160,216,157,198,126,55,131,43,118,83,142,98,76,100,136,68,139,251,162,23,154,89,245,135,179,79,19,97,69,109,141,9,129,125,50,189,143,64,235,134,183,123,11,240,149,33,34,92,107,78,130,84,214,101,147,206,96,178,28,115,86,192,20,167,140,241,220,18,117,202,31,59,190,228,209,66,61,212,48,163,60,182,38,111,191,14,218,70,105,7,87,39,242,29,155,188,148,67,3,248,17,199,246,144,239,62,231,6,195,213,47,200,102,30,215,8,232,234,222,128,82,238,247,132,170,114,172,53,77,106,42,150,26,210,113,90,21,73,116,75,159,208,94,4,24,164,236,194,224,65,110,15,81,203,204,36,145,175,80,161,244,112,57,153,124,58,133,35,184,180,122,252,2,54,91,37,85,151,49,45,93,250,152,227,138,146,174,5,223,41,16,103,108,186,201,211,0,230,207,225,158,168,44,99,22,1,63,88,226,137,169,13,56,52,27,171,51,255,176,187,72,12,95,185,177,205,46,197,243,219,71,229,165,156,119,10,166,32,104,254,127,193,173],vA4=[1,2,3,5],es5=function(J,Z){return J<<Z&65535|(J&65535)>>16-Z},$t5=function(J,Z){return(J&65535)>>Z|J<<16-Z&65535};yA4.exports=BZ.rc2=BZ.rc2||{};BZ.rc2.expandKey=function(J,Z){if(typeof J==="string")J=BZ.util.createBuffer(J);Z=Z||128;var Q=J,Y=J.length(),X=Z,V=Math.ceil(X/8),K=255>>(X&7),z;for(z=Y;z<128;z++)Q.putByte(Ec0[Q.at(z-1)+Q.at(z-Y)&255]);Q.setAt(128-V,Ec0[Q.at(128-V)&K]);for(z=127-V;z>=0;z--)Q.setAt(z,Ec0[Q.at(z+1)^Q.at(z+V)]);return Q};var kA4=function(J,Z,Q){var Y=!1,X=null,V=null,K=null,z,G,F,U,q=[];J=BZ.rc2.expandKey(J,Z);for(F=0;F<64;F++)q.push(J.getInt16Le());if(Q)z=function(H){for(F=0;F<4;F++)H[F]+=q[U]+(H[(F+3)%4]&H[(F+2)%4])+(~H[(F+3)%4]&H[(F+1)%4]),H[F]=es5(H[F],vA4[F]),U++},G=function(H){for(F=0;F<4;F++)H[F]+=q[H[(F+3)%4]&63]};else z=function(H){for(F=3;F>=0;F--)H[F]=$t5(H[F],vA4[F]),H[F]-=q[U]+(H[(F+3)%4]&H[(F+2)%4])+(~H[(F+3)%4]&H[(F+1)%4]),U--},G=function(H){for(F=3;F>=0;F--)H[F]-=q[H[(F+3)%4]&63]};var D=function(H){var B=[];for(F=0;F<4;F++){var w=X.getInt16Le();if(K!==null)if(Q)w^=K.getInt16Le();else K.putInt16Le(w);B.push(w&65535)}U=Q?0:63;for(var N=0;N<H.length;N++)for(var O=0;O<H[N][0];O++)H[N][1](B);for(F=0;F<4;F++){if(K!==null)if(Q)K.putInt16Le(B[F]);else B[F]^=K.getInt16Le();V.putInt16Le(B[F])}},W=null;return W={start:function(H,B){if(H){if(typeof H==="string")H=BZ.util.createBuffer(H)}Y=!1,X=BZ.util.createBuffer(),V=B||new BZ.util.createBuffer,K=H,W.output=V},update:function(H){if(!Y)X.putBuffer(H);while(X.length()>=8)D([[5,z],[1,G],[6,z],[1,G],[5,z]])},finish:function(H){var B=!0;if(Q)if(H)B=H(8,X,!Q);else{var w=X.length()===8?8:8-X.length();X.fillWithByte(w,w)}if(B)Y=!0,W.update();if(!Q){if(B=X.length()===0,B)if(H)B=H(8,V,!Q);else{var N=V.length(),O=V.at(N-1);if(O>N)B=!1;else V.truncate(O)}}return B}},W};BZ.rc2.startEncrypting=function(J,Z,Q){var Y=BZ.rc2.createEncryptionCipher(J,128);return Y.start(Z,Q),Y};BZ.rc2.createEncryptionCipher=function(J,Z){return kA4(J,Z,!0)};BZ.rc2.startDecrypting=function(J,Z,Q){var Y=BZ.rc2.createDecryptionCipher(J,128);return Y.start(Z,Q),Y};BZ.rc2.createDecryptionCipher=function(J,Z){return kA4(J,Z,!1)}});var Od=u((sO9,pA4)=>{var Mc0=J5();pA4.exports=Mc0.jsbn=Mc0.jsbn||{};var $q,Jt5=244837814094590,uA4=(Jt5&16777215)==15715070;function _1(J,Z,Q){if(this.data=[],J!=null)if(typeof J=="number")this.fromNumber(J,Z,Q);else if(Z==null&&typeof J!="string")this.fromString(J,256);else this.fromString(J,Z)}Mc0.jsbn.BigInteger=_1;function l5(){return new _1(null)}function Zt5(J,Z,Q,Y,X,V){while(--V>=0){var K=Z*this.data[J++]+Q.data[Y]+X;X=Math.floor(K/67108864),Q.data[Y++]=K&67108863}return X}function Qt5(J,Z,Q,Y,X,V){var K=Z&32767,z=Z>>15;while(--V>=0){var G=this.data[J]&32767,F=this.data[J++]>>15,U=z*G+F*K;G=K*G+((U&32767)<<15)+Q.data[Y]+(X&1073741823),X=(G>>>30)+(U>>>15)+z*F+(X>>>30),Q.data[Y++]=G&1073741823}return X}function xA4(J,Z,Q,Y,X,V){var K=Z&16383,z=Z>>14;while(--V>=0){var G=this.data[J]&16383,F=this.data[J++]>>14,U=z*G+F*K;G=K*G+((U&16383)<<14)+Q.data[Y]+X,X=(G>>28)+(U>>14)+z*F,Q.data[Y++]=G&268435455}return X}if(typeof navigator>"u")_1.prototype.am=xA4,$q=28;else if(uA4&&navigator.appName=="Microsoft Internet Explorer")_1.prototype.am=Qt5,$q=30;else if(uA4&&navigator.appName!="Netscape")_1.prototype.am=Zt5,$q=26;else _1.prototype.am=xA4,$q=28;_1.prototype.DB=$q;_1.prototype.DM=(1<<$q)-1;_1.prototype.DV=1<<$q;var Ac0=52;_1.prototype.FV=Math.pow(2,Ac0);_1.prototype.F1=Ac0-$q;_1.prototype.F2=2*$q-Ac0;var Yt5="0123456789abcdefghijklmnopqrstuvwxyz",gJ0=[],V_,ZX;V_=48;for(ZX=0;ZX<=9;++ZX)gJ0[V_++]=ZX;V_=97;for(ZX=10;ZX<36;++ZX)gJ0[V_++]=ZX;V_=65;for(ZX=10;ZX<36;++ZX)gJ0[V_++]=ZX;function fA4(J){return Yt5.charAt(J)}function bA4(J,Z){var Q=gJ0[J.charCodeAt(Z)];return Q==null?-1:Q}function Xt5(J){for(var Z=this.t-1;Z>=0;--Z)J.data[Z]=this.data[Z];J.t=this.t,J.s=this.s}function Vt5(J){if(this.t=1,this.s=J<0?-1:0,J>0)this.data[0]=J;else if(J<-1)this.data[0]=J+this.DV;else this.t=0}function GB(J){var Z=l5();return Z.fromInt(J),Z}function Kt5(J,Z){var Q;if(Z==16)Q=4;else if(Z==8)Q=3;else if(Z==256)Q=8;else if(Z==2)Q=1;else if(Z==32)Q=5;else if(Z==4)Q=2;else{this.fromRadix(J,Z);return}this.t=0,this.s=0;var Y=J.length,X=!1,V=0;while(--Y>=0){var K=Q==8?J[Y]&255:bA4(J,Y);if(K<0){if(J.charAt(Y)=="-")X=!0;continue}if(X=!1,V==0)this.data[this.t++]=K;else if(V+Q>this.DB)this.data[this.t-1]|=(K&(1<<this.DB-V)-1)<<V,this.data[this.t++]=K>>this.DB-V;else this.data[this.t-1]|=K<<V;if(V+=Q,V>=this.DB)V-=this.DB}if(Q==8&&(J[0]&128)!=0){if(this.s=-1,V>0)this.data[this.t-1]|=(1<<this.DB-V)-1<<V}if(this.clamp(),X)_1.ZERO.subTo(this,this)}function zt5(){var J=this.s&this.DM;while(this.t>0&&this.data[this.t-1]==J)--this.t}function Gt5(J){if(this.s<0)return"-"+this.negate().toString(J);var Z;if(J==16)Z=4;else if(J==8)Z=3;else if(J==2)Z=1;else if(J==32)Z=5;else if(J==4)Z=2;else return this.toRadix(J);var Q=(1<<Z)-1,Y,X=!1,V="",K=this.t,z=this.DB-K*this.DB%Z;if(K-- >0){if(z<this.DB&&(Y=this.data[K]>>z)>0)X=!0,V=fA4(Y);while(K>=0){if(z<Z)Y=(this.data[K]&(1<<z)-1)<<Z-z,Y|=this.data[--K]>>(z+=this.DB-Z);else if(Y=this.data[K]>>(z-=Z)&Q,z<=0)z+=this.DB,--K;if(Y>0)X=!0;if(X)V+=fA4(Y)}}return X?V:"0"}function Ft5(){var J=l5();return _1.ZERO.subTo(this,J),J}function Ut5(){return this.s<0?this.negate():this}function qt5(J){var Z=this.s-J.s;if(Z!=0)return Z;var Q=this.t;if(Z=Q-J.t,Z!=0)return this.s<0?-Z:Z;while(--Q>=0)if((Z=this.data[Q]-J.data[Q])!=0)return Z;return 0}function pJ0(J){var Z=1,Q;if((Q=J>>>16)!=0)J=Q,Z+=16;if((Q=J>>8)!=0)J=Q,Z+=8;if((Q=J>>4)!=0)J=Q,Z+=4;if((Q=J>>2)!=0)J=Q,Z+=2;if((Q=J>>1)!=0)J=Q,Z+=1;return Z}function Dt5(){if(this.t<=0)return 0;return this.DB*(this.t-1)+pJ0(this.data[this.t-1]^this.s&this.DM)}function Wt5(J,Z){var Q;for(Q=this.t-1;Q>=0;--Q)Z.data[Q+J]=this.data[Q];for(Q=J-1;Q>=0;--Q)Z.data[Q]=0;Z.t=this.t+J,Z.s=this.s}function Ht5(J,Z){for(var Q=J;Q<this.t;++Q)Z.data[Q-J]=this.data[Q];Z.t=Math.max(this.t-J,0),Z.s=this.s}function Bt5(J,Z){var Q=J%this.DB,Y=this.DB-Q,X=(1<<Y)-1,V=Math.floor(J/this.DB),K=this.s<<Q&this.DM,z;for(z=this.t-1;z>=0;--z)Z.data[z+V+1]=this.data[z]>>Y|K,K=(this.data[z]&X)<<Q;for(z=V-1;z>=0;--z)Z.data[z]=0;Z.data[V]=K,Z.t=this.t+V+1,Z.s=this.s,Z.clamp()}function wt5(J,Z){Z.s=this.s;var Q=Math.floor(J/this.DB);if(Q>=this.t){Z.t=0;return}var Y=J%this.DB,X=this.DB-Y,V=(1<<Y)-1;Z.data[0]=this.data[Q]>>Y;for(var K=Q+1;K<this.t;++K)Z.data[K-Q-1]|=(this.data[K]&V)<<X,Z.data[K-Q]=this.data[K]>>Y;if(Y>0)Z.data[this.t-Q-1]|=(this.s&V)<<X;Z.t=this.t-Q,Z.clamp()}function Nt5(J,Z){var Q=0,Y=0,X=Math.min(J.t,this.t);while(Q<X)Y+=this.data[Q]-J.data[Q],Z.data[Q++]=Y&this.DM,Y>>=this.DB;if(J.t<this.t){Y-=J.s;while(Q<this.t)Y+=this.data[Q],Z.data[Q++]=Y&this.DM,Y>>=this.DB;Y+=this.s}else{Y+=this.s;while(Q<J.t)Y-=J.data[Q],Z.data[Q++]=Y&this.DM,Y>>=this.DB;Y-=J.s}if(Z.s=Y<0?-1:0,Y<-1)Z.data[Q++]=this.DV+Y;else if(Y>0)Z.data[Q++]=Y;Z.t=Q,Z.clamp()}function Ot5(J,Z){var Q=this.abs(),Y=J.abs(),X=Q.t;Z.t=X+Y.t;while(--X>=0)Z.data[X]=0;for(X=0;X<Y.t;++X)Z.data[X+Q.t]=Q.am(0,Y.data[X],Z,X,0,Q.t);if(Z.s=0,Z.clamp(),this.s!=J.s)_1.ZERO.subTo(Z,Z)}function Et5(J){var Z=this.abs(),Q=J.t=2*Z.t;while(--Q>=0)J.data[Q]=0;for(Q=0;Q<Z.t-1;++Q){var Y=Z.am(Q,Z.data[Q],J,2*Q,0,1);if((J.data[Q+Z.t]+=Z.am(Q+1,2*Z.data[Q],J,2*Q+1,Y,Z.t-Q-1))>=Z.DV)J.data[Q+Z.t]-=Z.DV,J.data[Q+Z.t+1]=1}if(J.t>0)J.data[J.t-1]+=Z.am(Q,Z.data[Q],J,2*Q,0,1);J.s=0,J.clamp()}function Lt5(J,Z,Q){var Y=J.abs();if(Y.t<=0)return;var X=this.abs();if(X.t<Y.t){if(Z!=null)Z.fromInt(0);if(Q!=null)this.copyTo(Q);return}if(Q==null)Q=l5();var V=l5(),K=this.s,z=J.s,G=this.DB-pJ0(Y.data[Y.t-1]);if(G>0)Y.lShiftTo(G,V),X.lShiftTo(G,Q);else Y.copyTo(V),X.copyTo(Q);var F=V.t,U=V.data[F-1];if(U==0)return;var q=U*(1<<this.F1)+(F>1?V.data[F-2]>>this.F2:0),D=this.FV/q,W=(1<<this.F1)/q,H=1<<this.F2,B=Q.t,w=B-F,N=Z==null?l5():Z;if(V.dlShiftTo(w,N),Q.compareTo(N)>=0)Q.data[Q.t++]=1,Q.subTo(N,Q);_1.ONE.dlShiftTo(F,N),N.subTo(V,V);while(V.t<F)V.data[V.t++]=0;while(--w>=0){var O=Q.data[--B]==U?this.DM:Math.floor(Q.data[B]*D+(Q.data[B-1]+H)*W);if((Q.data[B]+=V.am(0,O,Q,w,0,F))<O){V.dlShiftTo(w,N),Q.subTo(N,Q);while(Q.data[B]<--O)Q.subTo(N,Q)}}if(Z!=null){if(Q.drShiftTo(F,Z),K!=z)_1.ZERO.subTo(Z,Z)}if(Q.t=F,Q.clamp(),G>0)Q.rShiftTo(G,Q);if(K<0)_1.ZERO.subTo(Q,Q)}function Mt5(J){var Z=l5();if(this.abs().divRemTo(J,null,Z),this.s<0&&Z.compareTo(_1.ZERO)>0)J.subTo(Z,Z);return Z}function iL(J){this.m=J}function At5(J){if(J.s<0||J.compareTo(this.m)>=0)return J.mod(this.m);else return J}function It5(J){return J}function jt5(J){J.divRemTo(this.m,null,J)}function Rt5(J,Z,Q){J.multiplyTo(Z,Q),this.reduce(Q)}function Pt5(J,Z){J.squareTo(Z),this.reduce(Z)}iL.prototype.convert=At5;iL.prototype.revert=It5;iL.prototype.reduce=jt5;iL.prototype.mulTo=Rt5;iL.prototype.sqrTo=Pt5;function Ct5(){if(this.t<1)return 0;var J=this.data[0];if((J&1)==0)return 0;var Z=J&3;return Z=Z*(2-(J&15)*Z)&15,Z=Z*(2-(J&255)*Z)&255,Z=Z*(2-((J&65535)*Z&65535))&65535,Z=Z*(2-J*Z%this.DV)%this.DV,Z>0?this.DV-Z:-Z}function nL(J){this.m=J,this.mp=J.invDigit(),this.mpl=this.mp&32767,this.mph=this.mp>>15,this.um=(1<<J.DB-15)-1,this.mt2=2*J.t}function Tt5(J){var Z=l5();if(J.abs().dlShiftTo(this.m.t,Z),Z.divRemTo(this.m,null,Z),J.s<0&&Z.compareTo(_1.ZERO)>0)this.m.subTo(Z,Z);return Z}function _t5(J){var Z=l5();return J.copyTo(Z),this.reduce(Z),Z}function St5(J){while(J.t<=this.mt2)J.data[J.t++]=0;for(var Z=0;Z<this.m.t;++Z){var Q=J.data[Z]&32767,Y=Q*this.mpl+((Q*this.mph+(J.data[Z]>>15)*this.mpl&this.um)<<15)&J.DM;Q=Z+this.m.t,J.data[Q]+=this.m.am(0,Y,J,Z,0,this.m.t);while(J.data[Q]>=J.DV)J.data[Q]-=J.DV,J.data[++Q]++}if(J.clamp(),J.drShiftTo(this.m.t,J),J.compareTo(this.m)>=0)J.subTo(this.m,J)}function vt5(J,Z){J.squareTo(Z),this.reduce(Z)}function kt5(J,Z,Q){J.multiplyTo(Z,Q),this.reduce(Q)}nL.prototype.convert=Tt5;nL.prototype.revert=_t5;nL.prototype.reduce=St5;nL.prototype.mulTo=kt5;nL.prototype.sqrTo=vt5;function yt5(){return(this.t>0?this.data[0]&1:this.s)==0}function ut5(J,Z){if(J>4294967295||J<1)return _1.ONE;var Q=l5(),Y=l5(),X=Z.convert(this),V=pJ0(J)-1;X.copyTo(Q);while(--V>=0)if(Z.sqrTo(Q,Y),(J&1<<V)>0)Z.mulTo(Y,X,Q);else{var K=Q;Q=Y,Y=K}return Z.revert(Q)}function xt5(J,Z){var Q;if(J<256||Z.isEven())Q=new iL(Z);else Q=new nL(Z);return this.exp(J,Q)}_1.prototype.copyTo=Xt5;_1.prototype.fromInt=Vt5;_1.prototype.fromString=Kt5;_1.prototype.clamp=zt5;_1.prototype.dlShiftTo=Wt5;_1.prototype.drShiftTo=Ht5;_1.prototype.lShiftTo=Bt5;_1.prototype.rShiftTo=wt5;_1.prototype.subTo=Nt5;_1.prototype.multiplyTo=Ot5;_1.prototype.squareTo=Et5;_1.prototype.divRemTo=Lt5;_1.prototype.invDigit=Ct5;_1.prototype.isEven=yt5;_1.prototype.exp=ut5;_1.prototype.toString=Gt5;_1.prototype.negate=Ft5;_1.prototype.abs=Ut5;_1.prototype.compareTo=qt5;_1.prototype.bitLength=Dt5;_1.prototype.mod=Mt5;_1.prototype.modPowInt=xt5;_1.ZERO=GB(0);_1.ONE=GB(1);function ft5(){var J=l5();return this.copyTo(J),J}function bt5(){if(this.s<0){if(this.t==1)return this.data[0]-this.DV;else if(this.t==0)return-1}else if(this.t==1)return this.data[0];else if(this.t==0)return 0;return(this.data[1]&(1<<32-this.DB)-1)<<this.DB|this.data[0]}function ht5(){return this.t==0?this.s:this.data[0]<<24>>24}function mt5(){return this.t==0?this.s:this.data[0]<<16>>16}function gt5(J){return Math.floor(Math.LN2*this.DB/Math.log(J))}function pt5(){if(this.s<0)return-1;else if(this.t<=0||this.t==1&&this.data[0]<=0)return 0;else return 1}function dt5(J){if(J==null)J=10;if(this.signum()==0||J<2||J>36)return"0";var Z=this.chunkSize(J),Q=Math.pow(J,Z),Y=GB(Q),X=l5(),V=l5(),K="";this.divRemTo(Y,X,V);while(X.signum()>0)K=(Q+V.intValue()).toString(J).substr(1)+K,X.divRemTo(Y,X,V);return V.intValue().toString(J)+K}function ct5(J,Z){if(this.fromInt(0),Z==null)Z=10;var Q=this.chunkSize(Z),Y=Math.pow(Z,Q),X=!1,V=0,K=0;for(var z=0;z<J.length;++z){var G=bA4(J,z);if(G<0){if(J.charAt(z)=="-"&&this.signum()==0)X=!0;continue}if(K=Z*K+G,++V>=Q)this.dMultiply(Y),this.dAddOffset(K,0),V=0,K=0}if(V>0)this.dMultiply(Math.pow(Z,V)),this.dAddOffset(K,0);if(X)_1.ZERO.subTo(this,this)}function lt5(J,Z,Q){if(typeof Z=="number")if(J<2)this.fromInt(1);else{if(this.fromNumber(J,Q),!this.testBit(J-1))this.bitwiseTo(_1.ONE.shiftLeft(J-1),Ic0,this);if(this.isEven())this.dAddOffset(1,0);while(!this.isProbablePrime(Z))if(this.dAddOffset(2,0),this.bitLength()>J)this.subTo(_1.ONE.shiftLeft(J-1),this)}else{var Y=[],X=J&7;if(Y.length=(J>>3)+1,Z.nextBytes(Y),X>0)Y[0]&=(1<<X)-1;else Y[0]=0;this.fromString(Y,256)}}function it5(){var J=this.t,Z=[];Z[0]=this.s;var Q=this.DB-J*this.DB%8,Y,X=0;if(J-- >0){if(Q<this.DB&&(Y=this.data[J]>>Q)!=(this.s&this.DM)>>Q)Z[X++]=Y|this.s<<this.DB-Q;while(J>=0){if(Q<8)Y=(this.data[J]&(1<<Q)-1)<<8-Q,Y|=this.data[--J]>>(Q+=this.DB-8);else if(Y=this.data[J]>>(Q-=8)&255,Q<=0)Q+=this.DB,--J;if((Y&128)!=0)Y|=-256;if(X==0&&(this.s&128)!=(Y&128))++X;if(X>0||Y!=this.s)Z[X++]=Y}}return Z}function nt5(J){return this.compareTo(J)==0}function at5(J){return this.compareTo(J)<0?this:J}function ot5(J){return this.compareTo(J)>0?this:J}function rt5(J,Z,Q){var Y,X,V=Math.min(J.t,this.t);for(Y=0;Y<V;++Y)Q.data[Y]=Z(this.data[Y],J.data[Y]);if(J.t<this.t){X=J.s&this.DM;for(Y=V;Y<this.t;++Y)Q.data[Y]=Z(this.data[Y],X);Q.t=this.t}else{X=this.s&this.DM;for(Y=V;Y<J.t;++Y)Q.data[Y]=Z(X,J.data[Y]);Q.t=J.t}Q.s=Z(this.s,J.s),Q.clamp()}function st5(J,Z){return J&Z}function tt5(J){var Z=l5();return this.bitwiseTo(J,st5,Z),Z}function Ic0(J,Z){return J|Z}function et5(J){var Z=l5();return this.bitwiseTo(J,Ic0,Z),Z}function hA4(J,Z){return J^Z}function $e5(J){var Z=l5();return this.bitwiseTo(J,hA4,Z),Z}function mA4(J,Z){return J&~Z}function Je5(J){var Z=l5();return this.bitwiseTo(J,mA4,Z),Z}function Ze5(){var J=l5();for(var Z=0;Z<this.t;++Z)J.data[Z]=this.DM&~this.data[Z];return J.t=this.t,J.s=~this.s,J}function Qe5(J){var Z=l5();if(J<0)this.rShiftTo(-J,Z);else this.lShiftTo(J,Z);return Z}function Ye5(J){var Z=l5();if(J<0)this.lShiftTo(-J,Z);else this.rShiftTo(J,Z);return Z}function Xe5(J){if(J==0)return-1;var Z=0;if((J&65535)==0)J>>=16,Z+=16;if((J&255)==0)J>>=8,Z+=8;if((J&15)==0)J>>=4,Z+=4;if((J&3)==0)J>>=2,Z+=2;if((J&1)==0)++Z;return Z}function Ve5(){for(var J=0;J<this.t;++J)if(this.data[J]!=0)return J*this.DB+Xe5(this.data[J]);if(this.s<0)return this.t*this.DB;return-1}function Ke5(J){var Z=0;while(J!=0)J&=J-1,++Z;return Z}function ze5(){var J=0,Z=this.s&this.DM;for(var Q=0;Q<this.t;++Q)J+=Ke5(this.data[Q]^Z);return J}function Ge5(J){var Z=Math.floor(J/this.DB);if(Z>=this.t)return this.s!=0;return(this.data[Z]&1<<J%this.DB)!=0}function Fe5(J,Z){var Q=_1.ONE.shiftLeft(J);return this.bitwiseTo(Q,Z,Q),Q}function Ue5(J){return this.changeBit(J,Ic0)}function qe5(J){return this.changeBit(J,mA4)}function De5(J){return this.changeBit(J,hA4)}function We5(J,Z){var Q=0,Y=0,X=Math.min(J.t,this.t);while(Q<X)Y+=this.data[Q]+J.data[Q],Z.data[Q++]=Y&this.DM,Y>>=this.DB;if(J.t<this.t){Y+=J.s;while(Q<this.t)Y+=this.data[Q],Z.data[Q++]=Y&this.DM,Y>>=this.DB;Y+=this.s}else{Y+=this.s;while(Q<J.t)Y+=J.data[Q],Z.data[Q++]=Y&this.DM,Y>>=this.DB;Y+=J.s}if(Z.s=Y<0?-1:0,Y>0)Z.data[Q++]=Y;else if(Y<-1)Z.data[Q++]=this.DV+Y;Z.t=Q,Z.clamp()}function He5(J){var Z=l5();return this.addTo(J,Z),Z}function Be5(J){var Z=l5();return this.subTo(J,Z),Z}function we5(J){var Z=l5();return this.multiplyTo(J,Z),Z}function Ne5(J){var Z=l5();return this.divRemTo(J,Z,null),Z}function Oe5(J){var Z=l5();return this.divRemTo(J,null,Z),Z}function Ee5(J){var Z=l5(),Q=l5();return this.divRemTo(J,Z,Q),[Z,Q]}function Le5(J){this.data[this.t]=this.am(0,J-1,this,0,0,this.t),++this.t,this.clamp()}function Me5(J,Z){if(J==0)return;while(this.t<=Z)this.data[this.t++]=0;this.data[Z]+=J;while(this.data[Z]>=this.DV){if(this.data[Z]-=this.DV,++Z>=this.t)this.data[this.t++]=0;++this.data[Z]}}function Nd(){}function gA4(J){return J}function Ae5(J,Z,Q){J.multiplyTo(Z,Q)}function Ie5(J,Z){J.squareTo(Z)}Nd.prototype.convert=gA4;Nd.prototype.revert=gA4;Nd.prototype.mulTo=Ae5;Nd.prototype.sqrTo=Ie5;function je5(J){return this.exp(J,new Nd)}function Re5(J,Z,Q){var Y=Math.min(this.t+J.t,Z);Q.s=0,Q.t=Y;while(Y>0)Q.data[--Y]=0;var X;for(X=Q.t-this.t;Y<X;++Y)Q.data[Y+this.t]=this.am(0,J.data[Y],Q,Y,0,this.t);for(X=Math.min(J.t,Z);Y<X;++Y)this.am(0,J.data[Y],Q,Y,0,Z-Y);Q.clamp()}function Pe5(J,Z,Q){--Z;var Y=Q.t=this.t+J.t-Z;Q.s=0;while(--Y>=0)Q.data[Y]=0;for(Y=Math.max(Z-this.t,0);Y<J.t;++Y)Q.data[this.t+Y-Z]=this.am(Z-Y,J.data[Y],Q,0,0,this.t+Y-Z);Q.clamp(),Q.drShiftTo(1,Q)}function K_(J){this.r2=l5(),this.q3=l5(),_1.ONE.dlShiftTo(2*J.t,this.r2),this.mu=this.r2.divide(J),this.m=J}function Ce5(J){if(J.s<0||J.t>2*this.m.t)return J.mod(this.m);else if(J.compareTo(this.m)<0)return J;else{var Z=l5();return J.copyTo(Z),this.reduce(Z),Z}}function Te5(J){return J}function _e5(J){if(J.drShiftTo(this.m.t-1,this.r2),J.t>this.m.t+1)J.t=this.m.t+1,J.clamp();this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);while(J.compareTo(this.r2)<0)J.dAddOffset(1,this.m.t+1);J.subTo(this.r2,J);while(J.compareTo(this.m)>=0)J.subTo(this.m,J)}function Se5(J,Z){J.squareTo(Z),this.reduce(Z)}function ve5(J,Z,Q){J.multiplyTo(Z,Q),this.reduce(Q)}K_.prototype.convert=Ce5;K_.prototype.revert=Te5;K_.prototype.reduce=_e5;K_.prototype.mulTo=ve5;K_.prototype.sqrTo=Se5;function ke5(J,Z){var Q=J.bitLength(),Y,X=GB(1),V;if(Q<=0)return X;else if(Q<18)Y=1;else if(Q<48)Y=3;else if(Q<144)Y=4;else if(Q<768)Y=5;else Y=6;if(Q<8)V=new iL(Z);else if(Z.isEven())V=new K_(Z);else V=new nL(Z);var K=[],z=3,G=Y-1,F=(1<<Y)-1;if(K[1]=V.convert(this),Y>1){var U=l5();V.sqrTo(K[1],U);while(z<=F)K[z]=l5(),V.mulTo(U,K[z-2],K[z]),z+=2}var q=J.t-1,D,W=!0,H=l5(),B;Q=pJ0(J.data[q])-1;while(q>=0){if(Q>=G)D=J.data[q]>>Q-G&F;else if(D=(J.data[q]&(1<<Q+1)-1)<<G-Q,q>0)D|=J.data[q-1]>>this.DB+Q-G;z=Y;while((D&1)==0)D>>=1,--z;if((Q-=z)<0)Q+=this.DB,--q;if(W)K[D].copyTo(X),W=!1;else{while(z>1)V.sqrTo(X,H),V.sqrTo(H,X),z-=2;if(z>0)V.sqrTo(X,H);else B=X,X=H,H=B;V.mulTo(H,K[D],X)}while(q>=0&&(J.data[q]&1<<Q)==0)if(V.sqrTo(X,H),B=X,X=H,H=B,--Q<0)Q=this.DB-1,--q}return V.revert(X)}function ye5(J){var Z=this.s<0?this.negate():this.clone(),Q=J.s<0?J.negate():J.clone();if(Z.compareTo(Q)<0){var Y=Z;Z=Q,Q=Y}var X=Z.getLowestSetBit(),V=Q.getLowestSetBit();if(V<0)return Z;if(X<V)V=X;if(V>0)Z.rShiftTo(V,Z),Q.rShiftTo(V,Q);while(Z.signum()>0){if((X=Z.getLowestSetBit())>0)Z.rShiftTo(X,Z);if((X=Q.getLowestSetBit())>0)Q.rShiftTo(X,Q);if(Z.compareTo(Q)>=0)Z.subTo(Q,Z),Z.rShiftTo(1,Z);else Q.subTo(Z,Q),Q.rShiftTo(1,Q)}if(V>0)Q.lShiftTo(V,Q);return Q}function ue5(J){if(J<=0)return 0;var Z=this.DV%J,Q=this.s<0?J-1:0;if(this.t>0)if(Z==0)Q=this.data[0]%J;else for(var Y=this.t-1;Y>=0;--Y)Q=(Z*Q+this.data[Y])%J;return Q}function xe5(J){var Z=J.isEven();if(this.isEven()&&Z||J.signum()==0)return _1.ZERO;var Q=J.clone(),Y=this.clone(),X=GB(1),V=GB(0),K=GB(0),z=GB(1);while(Q.signum()!=0){while(Q.isEven()){if(Q.rShiftTo(1,Q),Z){if(!X.isEven()||!V.isEven())X.addTo(this,X),V.subTo(J,V);X.rShiftTo(1,X)}else if(!V.isEven())V.subTo(J,V);V.rShiftTo(1,V)}while(Y.isEven()){if(Y.rShiftTo(1,Y),Z){if(!K.isEven()||!z.isEven())K.addTo(this,K),z.subTo(J,z);K.rShiftTo(1,K)}else if(!z.isEven())z.subTo(J,z);z.rShiftTo(1,z)}if(Q.compareTo(Y)>=0){if(Q.subTo(Y,Q),Z)X.subTo(K,X);V.subTo(z,V)}else{if(Y.subTo(Q,Y),Z)K.subTo(X,K);z.subTo(V,z)}}if(Y.compareTo(_1.ONE)!=0)return _1.ZERO;if(z.compareTo(J)>=0)return z.subtract(J);if(z.signum()<0)z.addTo(J,z);else return z;if(z.signum()<0)return z.add(J);else return z}var rV=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509],fe5=67108864/rV[rV.length-1];function be5(J){var Z,Q=this.abs();if(Q.t==1&&Q.data[0]<=rV[rV.length-1]){for(Z=0;Z<rV.length;++Z)if(Q.data[0]==rV[Z])return!0;return!1}if(Q.isEven())return!1;Z=1;while(Z<rV.length){var Y=rV[Z],X=Z+1;while(X<rV.length&&Y<fe5)Y*=rV[X++];Y=Q.modInt(Y);while(Z<X)if(Y%rV[Z++]==0)return!1}return Q.millerRabin(J)}function he5(J){var Z=this.subtract(_1.ONE),Q=Z.getLowestSetBit();if(Q<=0)return!1;var Y=Z.shiftRight(Q),X=me5(),V;for(var K=0;K<J;++K){do V=new _1(this.bitLength(),X);while(V.compareTo(_1.ONE)<=0||V.compareTo(Z)>=0);var z=V.modPow(Y,this);if(z.compareTo(_1.ONE)!=0&&z.compareTo(Z)!=0){var G=1;while(G++<Q&&z.compareTo(Z)!=0)if(z=z.modPowInt(2,this),z.compareTo(_1.ONE)==0)return!1;if(z.compareTo(Z)!=0)return!1}}return!0}function me5(){return{nextBytes:function(J){for(var Z=0;Z<J.length;++Z)J[Z]=Math.floor(Math.random()*256)}}}_1.prototype.chunkSize=gt5;_1.prototype.toRadix=dt5;_1.prototype.fromRadix=ct5;_1.prototype.fromNumber=lt5;_1.prototype.bitwiseTo=rt5;_1.prototype.changeBit=Fe5;_1.prototype.addTo=We5;_1.prototype.dMultiply=Le5;_1.prototype.dAddOffset=Me5;_1.prototype.multiplyLowerTo=Re5;_1.prototype.multiplyUpperTo=Pe5;_1.prototype.modInt=ue5;_1.prototype.millerRabin=he5;_1.prototype.clone=ft5;_1.prototype.intValue=bt5;_1.prototype.byteValue=ht5;_1.prototype.shortValue=mt5;_1.prototype.signum=pt5;_1.prototype.toByteArray=it5;_1.prototype.equals=nt5;_1.prototype.min=at5;_1.prototype.max=ot5;_1.prototype.and=tt5;_1.prototype.or=et5;_1.prototype.xor=$e5;_1.prototype.andNot=Je5;_1.prototype.not=Ze5;_1.prototype.shiftLeft=Qe5;_1.prototype.shiftRight=Ye5;_1.prototype.getLowestSetBit=Ve5;_1.prototype.bitCount=ze5;_1.prototype.testBit=Ge5;_1.prototype.setBit=Ue5;_1.prototype.clearBit=qe5;_1.prototype.flipBit=De5;_1.prototype.add=He5;_1.prototype.subtract=Be5;_1.prototype.multiply=we5;_1.prototype.divide=Ne5;_1.prototype.remainder=Oe5;_1.prototype.divideAndRemainder=Ee5;_1.prototype.modPow=ke5;_1.prototype.modInverse=xe5;_1.prototype.pow=je5;_1.prototype.gcd=ye5;_1.prototype.isProbablePrime=be5});var z_=u((tO9,iA4)=>{var AG=J5();NG();c5();var cA4=iA4.exports=AG.sha1=AG.sha1||{};AG.md.sha1=AG.md.algorithms.sha1=cA4;cA4.create=function(){if(!lA4)ge5();var J=null,Z=AG.util.createBuffer(),Q=Array(80),Y={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8};return Y.start=function(){Y.messageLength=0,Y.fullMessageLength=Y.messageLength64=[];var X=Y.messageLengthSize/4;for(var V=0;V<X;++V)Y.fullMessageLength.push(0);return Z=AG.util.createBuffer(),J={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878,h4:3285377520},Y},Y.start(),Y.update=function(X,V){if(V==="utf8")X=AG.util.encodeUtf8(X);var K=X.length;Y.messageLength+=K,K=[K/4294967296>>>0,K>>>0];for(var z=Y.fullMessageLength.length-1;z>=0;--z)Y.fullMessageLength[z]+=K[1],K[1]=K[0]+(Y.fullMessageLength[z]/4294967296>>>0),Y.fullMessageLength[z]=Y.fullMessageLength[z]>>>0,K[0]=K[1]/4294967296>>>0;if(Z.putBytes(X),dA4(J,Q,Z),Z.read>2048||Z.length()===0)Z.compact();return Y},Y.digest=function(){var X=AG.util.createBuffer();X.putBytes(Z.bytes());var V=Y.fullMessageLength[Y.fullMessageLength.length-1]+Y.messageLengthSize,K=V&Y.blockLength-1;X.putBytes(jc0.substr(0,Y.blockLength-K));var z,G,F=Y.fullMessageLength[0]*8;for(var U=0;U<Y.fullMessageLength.length-1;++U)z=Y.fullMessageLength[U+1]*8,G=z/4294967296>>>0,F+=G,X.putInt32(F>>>0),F=z>>>0;X.putInt32(F);var q={h0:J.h0,h1:J.h1,h2:J.h2,h3:J.h3,h4:J.h4};dA4(q,Q,X);var D=AG.util.createBuffer();return D.putInt32(q.h0),D.putInt32(q.h1),D.putInt32(q.h2),D.putInt32(q.h3),D.putInt32(q.h4),D},Y};var jc0=null,lA4=!1;function ge5(){jc0=String.fromCharCode(128),jc0+=AG.util.fillString(String.fromCharCode(0),64),lA4=!0}function dA4(J,Z,Q){var Y,X,V,K,z,G,F,U,q=Q.length();while(q>=64){X=J.h0,V=J.h1,K=J.h2,z=J.h3,G=J.h4;for(U=0;U<16;++U)Y=Q.getInt32(),Z[U]=Y,F=z^V&(K^z),Y=(X<<5|X>>>27)+F+G+1518500249+Y,G=z,z=K,K=(V<<30|V>>>2)>>>0,V=X,X=Y;for(;U<20;++U)Y=Z[U-3]^Z[U-8]^Z[U-14]^Z[U-16],Y=Y<<1|Y>>>31,Z[U]=Y,F=z^V&(K^z),Y=(X<<5|X>>>27)+F+G+1518500249+Y,G=z,z=K,K=(V<<30|V>>>2)>>>0,V=X,X=Y;for(;U<32;++U)Y=Z[U-3]^Z[U-8]^Z[U-14]^Z[U-16],Y=Y<<1|Y>>>31,Z[U]=Y,F=V^K^z,Y=(X<<5|X>>>27)+F+G+1859775393+Y,G=z,z=K,K=(V<<30|V>>>2)>>>0,V=X,X=Y;for(;U<40;++U)Y=Z[U-6]^Z[U-16]^Z[U-28]^Z[U-32],Y=Y<<2|Y>>>30,Z[U]=Y,F=V^K^z,Y=(X<<5|X>>>27)+F+G+1859775393+Y,G=z,z=K,K=(V<<30|V>>>2)>>>0,V=X,X=Y;for(;U<60;++U)Y=Z[U-6]^Z[U-16]^Z[U-28]^Z[U-32],Y=Y<<2|Y>>>30,Z[U]=Y,F=V&K|z&(V^K),Y=(X<<5|X>>>27)+F+G+2400959708+Y,G=z,z=K,K=(V<<30|V>>>2)>>>0,V=X,X=Y;for(;U<80;++U)Y=Z[U-6]^Z[U-16]^Z[U-28]^Z[U-32],Y=Y<<2|Y>>>30,Z[U]=Y,F=V^K^z,Y=(X<<5|X>>>27)+F+G+3395469782+Y,G=z,z=K,K=(V<<30|V>>>2)>>>0,V=X,X=Y;J.h0=J.h0+X|0,J.h1=J.h1+V|0,J.h2=J.h2+K|0,J.h3=J.h3+z|0,J.h4=J.h4+G|0,q-=64}}});var Rc0=u((eO9,aA4)=>{var IG=J5();c5();JX();z_();var nA4=aA4.exports=IG.pkcs1=IG.pkcs1||{};nA4.encode_rsa_oaep=function(J,Z,Q){var Y,X,V,K;if(typeof Q==="string")Y=Q,X=arguments[3]||void 0,V=arguments[4]||void 0;else if(Q){if(Y=Q.label||void 0,X=Q.seed||void 0,V=Q.md||void 0,Q.mgf1&&Q.mgf1.md)K=Q.mgf1.md}if(!V)V=IG.md.sha1.create();else V.start();if(!K)K=V;var z=Math.ceil(J.n.bitLength()/8),G=z-2*V.digestLength-2;if(Z.length>G){var F=Error("RSAES-OAEP input message length is too long.");throw F.length=Z.length,F.maxLength=G,F}if(!Y)Y="";V.update(Y,"raw");var U=V.digest(),q="",D=G-Z.length;for(var W=0;W<D;W++)q+="\x00";var H=U.getBytes()+q+"\x01"+Z;if(!X)X=IG.random.getBytes(V.digestLength);else if(X.length!==V.digestLength){var F=Error("Invalid RSAES-OAEP seed. The seed length must match the digest length.");throw F.seedLength=X.length,F.digestLength=V.digestLength,F}var B=dJ0(X,z-V.digestLength-1,K),w=IG.util.xorBytes(H,B,H.length),N=dJ0(w,V.digestLength,K),O=IG.util.xorBytes(X,N,X.length);return"\x00"+O+w};nA4.decode_rsa_oaep=function(J,Z,Q){var Y,X,V;if(typeof Q==="string")Y=Q,X=arguments[3]||void 0;else if(Q){if(Y=Q.label||void 0,X=Q.md||void 0,Q.mgf1&&Q.mgf1.md)V=Q.mgf1.md}var K=Math.ceil(J.n.bitLength()/8);if(Z.length!==K){var w=Error("RSAES-OAEP encoded message length is invalid.");throw w.length=Z.length,w.expectedLength=K,w}if(X===void 0)X=IG.md.sha1.create();else X.start();if(!V)V=X;if(K<2*X.digestLength+2)throw Error("RSAES-OAEP key is too short for the hash function.");if(!Y)Y="";X.update(Y,"raw");var z=X.digest().getBytes(),G=Z.charAt(0),F=Z.substring(1,X.digestLength+1),U=Z.substring(1+X.digestLength),q=dJ0(U,X.digestLength,V),D=IG.util.xorBytes(F,q,F.length),W=dJ0(D,K-X.digestLength-1,V),H=IG.util.xorBytes(U,W,U.length),B=H.substring(0,X.digestLength),w=G!=="\x00";for(var N=0;N<X.digestLength;++N)w|=z.charAt(N)!==B.charAt(N);var O=1,E=X.digestLength;for(var L=X.digestLength;L<H.length;L++){var M=H.charCodeAt(L),A=M&1^1,I=O?65534:0;w|=M&I,O=O&A,E+=O}if(w||H.charCodeAt(E)!==1)throw Error("Invalid RSAES-OAEP padding.");return H.substring(E+1)};function dJ0(J,Z,Q){if(!Q)Q=IG.md.sha1.create();var Y="",X=Math.ceil(Z/Q.digestLength);for(var V=0;V<X;++V){var K=String.fromCharCode(V>>24&255,V>>16&255,V>>8&255,V&255);Q.start(),Q.update(J+K),Y+=Q.digest().getBytes()}return Y.substring(0,Z)}});var Cc0=u(($E9,Pc0)=>{var FB=J5();c5();Od();JX();(function(){if(FB.prime){Pc0.exports=FB.prime;return}var J=Pc0.exports=FB.prime=FB.prime||{},Z=FB.jsbn.BigInteger,Q=[6,4,2,4,2,4,6,2],Y=new Z(null);Y.fromInt(30);var X=function(q,D){return q|D};J.generateProbablePrime=function(q,D,W){if(typeof D==="function")W=D,D={};D=D||{};var H=D.algorithm||"PRIMEINC";if(typeof H==="string")H={name:H};H.options=H.options||{};var B=D.prng||FB.random,w={nextBytes:function(N){var O=B.getBytesSync(N.length);for(var E=0;E<N.length;++E)N[E]=O.charCodeAt(E)}};if(H.name==="PRIMEINC")return V(q,w,H.options,W);throw Error("Invalid prime generation algorithm: "+H.name)};function V(q,D,W,H){if("workers"in W)return G(q,D,W,H);return K(q,D,W,H)}function K(q,D,W,H){var B=F(q,D),w=0,N=U(B.bitLength());if("millerRabinTests"in W)N=W.millerRabinTests;var O=10;if("maxBlockTime"in W)O=W.maxBlockTime;z(B,q,D,w,N,O,H)}function z(q,D,W,H,B,w,N){var O=+new Date;do{if(q.bitLength()>D)q=F(D,W);if(q.isProbablePrime(B))return N(null,q);q.dAddOffset(Q[H++%8],0)}while(w<0||+new Date-O<w);FB.util.setImmediate(function(){z(q,D,W,H,B,w,N)})}function G(q,D,W,H){if(typeof Worker>"u")return K(q,D,W,H);var B=F(q,D),w=W.workers,N=W.workLoad||100,O=N*30/8,E=W.workerScript||"forge/prime.worker.js";if(w===-1)return FB.util.estimateCores(function(M,A){if(M)A=2;w=A-1,L()});L();function L(){w=Math.max(1,w);var M=[];for(var A=0;A<w;++A)M[A]=new Worker(E);var I=w;for(var A=0;A<w;++A)M[A].addEventListener("message",_);var P=!1;function _(S){if(P)return;--I;var y=S.data;if(y.found){for(var m=0;m<M.length;++m)M[m].terminate();return P=!0,H(null,new Z(y.prime,16))}if(B.bitLength()>q)B=F(q,D);var b=B.toString(16);S.target.postMessage({hex:b,workLoad:N}),B.dAddOffset(O,0)}}}function F(q,D){var W=new Z(q,D),H=q-1;if(!W.testBit(H))W.bitwiseTo(Z.ONE.shiftLeft(H),X,W);return W.dAddOffset(31-W.mod(Y).byteValue(),0),W}function U(q){if(q<=100)return 27;if(q<=150)return 18;if(q<=200)return 15;if(q<=250)return 12;if(q<=300)return 9;if(q<=350)return 8;if(q<=400)return 7;if(q<=500)return 6;if(q<=600)return 5;if(q<=800)return 4;if(q<=1250)return 3;return 2}})()});var Ed=u((JE9,JI4)=>{var Z6=J5();oV();Od();zB();Rc0();Cc0();JX();c5();if(typeof _5>"u")_5=Z6.jsbn.BigInteger;var _5,Tc0=Z6.util.isNodejs?j0("crypto"):null,Q1=Z6.asn1,QX=Z6.util;Z6.pki=Z6.pki||{};JI4.exports=Z6.pki.rsa=Z6.rsa=Z6.rsa||{};var g6=Z6.pki,pe5=[6,4,2,4,2,4,6,2],de5={name:"PrivateKeyInfo",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},ce5={name:"RSAPrivateKey",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},le5={name:"RSAPublicKey",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},ie5=Z6.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},ne5={name:"DigestInfo",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},ae5=function(J){var Z;if(J.algorithm in g6.oids)Z=g6.oids[J.algorithm];else{var Q=Error("Unknown message digest algorithm.");throw Q.algorithm=J.algorithm,Q}var Y=Q1.oidToDer(Z).getBytes(),X=Q1.create(Q1.Class.UNIVERSAL,Q1.Type.SEQUENCE,!0,[]),V=Q1.create(Q1.Class.UNIVERSAL,Q1.Type.SEQUENCE,!0,[]);V.value.push(Q1.create(Q1.Class.UNIVERSAL,Q1.Type.OID,!1,Y)),V.value.push(Q1.create(Q1.Class.UNIVERSAL,Q1.Type.NULL,!1,""));var K=Q1.create(Q1.Class.UNIVERSAL,Q1.Type.OCTETSTRING,!1,J.digest().getBytes());return X.value.push(V),X.value.push(K),Q1.toDer(X).getBytes()},eA4=function(J,Z,Q){if(Q)return J.modPow(Z.e,Z.n);if(!Z.p||!Z.q)return J.modPow(Z.d,Z.n);if(!Z.dP)Z.dP=Z.d.mod(Z.p.subtract(_5.ONE));if(!Z.dQ)Z.dQ=Z.d.mod(Z.q.subtract(_5.ONE));if(!Z.qInv)Z.qInv=Z.q.modInverse(Z.p);var Y;do Y=new _5(Z6.util.bytesToHex(Z6.random.getBytes(Z.n.bitLength()/8)),16);while(Y.compareTo(Z.n)>=0||!Y.gcd(Z.n).equals(_5.ONE));J=J.multiply(Y.modPow(Z.e,Z.n)).mod(Z.n);var X=J.mod(Z.p).modPow(Z.dP,Z.p),V=J.mod(Z.q).modPow(Z.dQ,Z.q);while(X.compareTo(V)<0)X=X.add(Z.p);var K=X.subtract(V).multiply(Z.qInv).mod(Z.p).multiply(Z.q).add(V);return K=K.multiply(Y.modInverse(Z.n)).mod(Z.n),K};g6.rsa.encrypt=function(J,Z,Q){var Y=Q,X,V=Math.ceil(Z.n.bitLength()/8);if(Q!==!1&&Q!==!0)Y=Q===2,X=$I4(J,Z,Q);else X=Z6.util.createBuffer(),X.putBytes(J);var K=new _5(X.toHex(),16),z=eA4(K,Z,Y),G=z.toString(16),F=Z6.util.createBuffer(),U=V-Math.ceil(G.length/2);while(U>0)F.putByte(0),--U;return F.putBytes(Z6.util.hexToBytes(G)),F.getBytes()};g6.rsa.decrypt=function(J,Z,Q,Y){var X=Math.ceil(Z.n.bitLength()/8);if(J.length!==X){var V=Error("Encrypted message length is invalid.");throw V.length=J.length,V.expected=X,V}var K=new _5(Z6.util.createBuffer(J).toHex(),16);if(K.compareTo(Z.n)>=0)throw Error("Encrypted message is invalid.");var z=eA4(K,Z,Q),G=z.toString(16),F=Z6.util.createBuffer(),U=X-Math.ceil(G.length/2);while(U>0)F.putByte(0),--U;if(F.putBytes(Z6.util.hexToBytes(G)),Y!==!1)return cJ0(F.getBytes(),Z,Q);return F.getBytes()};g6.rsa.createKeyPairGenerationState=function(J,Z,Q){if(typeof J==="string")J=parseInt(J,10);J=J||2048,Q=Q||{};var Y=Q.prng||Z6.random,X={nextBytes:function(z){var G=Y.getBytesSync(z.length);for(var F=0;F<z.length;++F)z[F]=G.charCodeAt(F)}},V=Q.algorithm||"PRIMEINC",K;if(V==="PRIMEINC")K={algorithm:V,state:0,bits:J,rng:X,eInt:Z||65537,e:new _5(null),p:null,q:null,qBits:J>>1,pBits:J-(J>>1),pqState:0,num:null,keys:null},K.e.fromInt(K.eInt);else throw Error("Invalid key generation algorithm: "+V);return K};g6.rsa.stepKeyPairGenerationState=function(J,Z){if(!("algorithm"in J))J.algorithm="PRIMEINC";var Q=new _5(null);Q.fromInt(30);var Y=0,X=function(q,D){return q|D},V=+new Date,K,z=0;while(J.keys===null&&(Z<=0||z<Z)){if(J.state===0){var G=J.p===null?J.pBits:J.qBits,F=G-1;if(J.pqState===0){if(J.num=new _5(G,J.rng),!J.num.testBit(F))J.num.bitwiseTo(_5.ONE.shiftLeft(F),X,J.num);J.num.dAddOffset(31-J.num.mod(Q).byteValue(),0),Y=0,++J.pqState}else if(J.pqState===1)if(J.num.bitLength()>G)J.pqState=0;else if(J.num.isProbablePrime(re5(J.num.bitLength())))++J.pqState;else J.num.dAddOffset(pe5[Y++%8],0);else if(J.pqState===2)J.pqState=J.num.subtract(_5.ONE).gcd(J.e).compareTo(_5.ONE)===0?3:0;else if(J.pqState===3){if(J.pqState=0,J.p===null)J.p=J.num;else J.q=J.num;if(J.p!==null&&J.q!==null)++J.state;J.num=null}}else if(J.state===1){if(J.p.compareTo(J.q)<0)J.num=J.p,J.p=J.q,J.q=J.num;++J.state}else if(J.state===2)J.p1=J.p.subtract(_5.ONE),J.q1=J.q.subtract(_5.ONE),J.phi=J.p1.multiply(J.q1),++J.state;else if(J.state===3)if(J.phi.gcd(J.e).compareTo(_5.ONE)===0)++J.state;else J.p=null,J.q=null,J.state=0;else if(J.state===4)if(J.n=J.p.multiply(J.q),J.n.bitLength()===J.bits)++J.state;else J.q=null,J.state=0;else if(J.state===5){var U=J.e.modInverse(J.phi);J.keys={privateKey:g6.rsa.setPrivateKey(J.n,J.e,U,J.p,J.q,U.mod(J.p1),U.mod(J.q1),J.q.modInverse(J.p)),publicKey:g6.rsa.setPublicKey(J.n,J.e)}}K=+new Date,z+=K-V,V=K}return J.keys!==null};g6.rsa.generateKeyPair=function(J,Z,Q,Y){if(arguments.length===1){if(typeof J==="object")Q=J,J=void 0;else if(typeof J==="function")Y=J,J=void 0}else if(arguments.length===2)if(typeof J==="number"){if(typeof Z==="function")Y=Z,Z=void 0;else if(typeof Z!=="number")Q=Z,Z=void 0}else Q=J,Y=Z,J=void 0,Z=void 0;else if(arguments.length===3)if(typeof Z==="number"){if(typeof Q==="function")Y=Q,Q=void 0}else Y=Q,Q=Z,Z=void 0;if(Q=Q||{},J===void 0)J=Q.bits||2048;if(Z===void 0)Z=Q.e||65537;if(!Z6.options.usePureJavaScript&&!Q.prng&&J>=256&&J<=16384&&(Z===65537||Z===3)){if(Y){if(oA4("generateKeyPair"))return Tc0.generateKeyPair("rsa",{modulusLength:J,publicExponent:Z,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},function(z,G,F){if(z)return Y(z);Y(null,{privateKey:g6.privateKeyFromPem(F),publicKey:g6.publicKeyFromPem(G)})});if(rA4("generateKey")&&rA4("exportKey"))return QX.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:J,publicExponent:tA4(Z),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(z){return QX.globalScope.crypto.subtle.exportKey("pkcs8",z.privateKey)}).then(void 0,function(z){Y(z)}).then(function(z){if(z){var G=g6.privateKeyFromAsn1(Q1.fromDer(Z6.util.createBuffer(z)));Y(null,{privateKey:G,publicKey:g6.setRsaPublicKey(G.n,G.e)})}});if(sA4("generateKey")&&sA4("exportKey")){var X=QX.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:J,publicExponent:tA4(Z),hash:{name:"SHA-256"}},!0,["sign","verify"]);X.oncomplete=function(z){var G=z.target.result,F=QX.globalScope.msCrypto.subtle.exportKey("pkcs8",G.privateKey);F.oncomplete=function(U){var q=U.target.result,D=g6.privateKeyFromAsn1(Q1.fromDer(Z6.util.createBuffer(q)));Y(null,{privateKey:D,publicKey:g6.setRsaPublicKey(D.n,D.e)})},F.onerror=function(U){Y(U)}},X.onerror=function(z){Y(z)};return}}else if(oA4("generateKeyPairSync")){var V=Tc0.generateKeyPairSync("rsa",{modulusLength:J,publicExponent:Z,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:g6.privateKeyFromPem(V.privateKey),publicKey:g6.publicKeyFromPem(V.publicKey)}}}var K=g6.rsa.createKeyPairGenerationState(J,Z,Q);if(!Y)return g6.rsa.stepKeyPairGenerationState(K,0),K.keys;oe5(K,Q,Y)};g6.setRsaPublicKey=g6.rsa.setPublicKey=function(J,Z){var Q={n:J,e:Z};return Q.encrypt=function(Y,X,V){if(typeof X==="string")X=X.toUpperCase();else if(X===void 0)X="RSAES-PKCS1-V1_5";if(X==="RSAES-PKCS1-V1_5")X={encode:function(z,G,F){return $I4(z,G,2).getBytes()}};else if(X==="RSA-OAEP"||X==="RSAES-OAEP")X={encode:function(z,G){return Z6.pkcs1.encode_rsa_oaep(G,z,V)}};else if(["RAW","NONE","NULL",null].indexOf(X)!==-1)X={encode:function(z){return z}};else if(typeof X==="string")throw Error('Unsupported encryption scheme: "'+X+'".');var K=X.encode(Y,Q,!0);return g6.rsa.encrypt(K,Q,!0)},Q.verify=function(Y,X,V,K){if(typeof V==="string")V=V.toUpperCase();else if(V===void 0)V="RSASSA-PKCS1-V1_5";if(K===void 0)K={_parseAllDigestBytes:!0};if(!("_parseAllDigestBytes"in K))K._parseAllDigestBytes=!0;if(V==="RSASSA-PKCS1-V1_5")V={verify:function(G,F){F=cJ0(F,Q,!0);var U=Q1.fromDer(F,{parseAllBytes:K._parseAllDigestBytes}),q={},D=[];if(!Q1.validate(U,ne5,q,D)){var W=Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.");throw W.errors=D,W}var H=Q1.derToOid(q.algorithmIdentifier);if(!(H===Z6.oids.md2||H===Z6.oids.md5||H===Z6.oids.sha1||H===Z6.oids.sha224||H===Z6.oids.sha256||H===Z6.oids.sha384||H===Z6.oids.sha512||H===Z6.oids["sha512-224"]||H===Z6.oids["sha512-256"])){var W=Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.");throw W.oid=H,W}if(H===Z6.oids.md2||H===Z6.oids.md5){if(!("parameters"in q))throw Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifier NULL parameters.")}return G===q.digest}};else if(V==="NONE"||V==="NULL"||V===null)V={verify:function(G,F){return F=cJ0(F,Q,!0),G===F}};var z=g6.rsa.decrypt(X,Q,!0,!1);return V.verify(Y,z,Q.n.bitLength())},Q};g6.setRsaPrivateKey=g6.rsa.setPrivateKey=function(J,Z,Q,Y,X,V,K,z){var G={n:J,e:Z,d:Q,p:Y,q:X,dP:V,dQ:K,qInv:z};return G.decrypt=function(F,U,q){if(typeof U==="string")U=U.toUpperCase();else if(U===void 0)U="RSAES-PKCS1-V1_5";var D=g6.rsa.decrypt(F,G,!1,!1);if(U==="RSAES-PKCS1-V1_5")U={decode:cJ0};else if(U==="RSA-OAEP"||U==="RSAES-OAEP")U={decode:function(W,H){return Z6.pkcs1.decode_rsa_oaep(H,W,q)}};else if(["RAW","NONE","NULL",null].indexOf(U)!==-1)U={decode:function(W){return W}};else throw Error('Unsupported encryption scheme: "'+U+'".');return U.decode(D,G,!1)},G.sign=function(F,U){var q=!1;if(typeof U==="string")U=U.toUpperCase();if(U===void 0||U==="RSASSA-PKCS1-V1_5")U={encode:ae5},q=1;else if(U==="NONE"||U==="NULL"||U===null)U={encode:function(){return F}},q=1;var D=U.encode(F,G.n.bitLength());return g6.rsa.encrypt(D,G,q)},G};g6.wrapRsaPrivateKey=function(J){return Q1.create(Q1.Class.UNIVERSAL,Q1.Type.SEQUENCE,!0,[Q1.create(Q1.Class.UNIVERSAL,Q1.Type.INTEGER,!1,Q1.integerToDer(0).getBytes()),Q1.create(Q1.Class.UNIVERSAL,Q1.Type.SEQUENCE,!0,[Q1.create(Q1.Class.UNIVERSAL,Q1.Type.OID,!1,Q1.oidToDer(g6.oids.rsaEncryption).getBytes()),Q1.create(Q1.Class.UNIVERSAL,Q1.Type.NULL,!1,"")]),Q1.create(Q1.Class.UNIVERSAL,Q1.Type.OCTETSTRING,!1,Q1.toDer(J).getBytes())])};g6.privateKeyFromAsn1=function(J){var Z={},Q=[];if(Q1.validate(J,de5,Z,Q))J=Q1.fromDer(Z6.util.createBuffer(Z.privateKey));if(Z={},Q=[],!Q1.validate(J,ce5,Z,Q)){var Y=Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw Y.errors=Q,Y}var X,V,K,z,G,F,U,q;return X=Z6.util.createBuffer(Z.privateKeyModulus).toHex(),V=Z6.util.createBuffer(Z.privateKeyPublicExponent).toHex(),K=Z6.util.createBuffer(Z.privateKeyPrivateExponent).toHex(),z=Z6.util.createBuffer(Z.privateKeyPrime1).toHex(),G=Z6.util.createBuffer(Z.privateKeyPrime2).toHex(),F=Z6.util.createBuffer(Z.privateKeyExponent1).toHex(),U=Z6.util.createBuffer(Z.privateKeyExponent2).toHex(),q=Z6.util.createBuffer(Z.privateKeyCoefficient).toHex(),g6.setRsaPrivateKey(new _5(X,16),new _5(V,16),new _5(K,16),new _5(z,16),new _5(G,16),new _5(F,16),new _5(U,16),new _5(q,16))};g6.privateKeyToAsn1=g6.privateKeyToRSAPrivateKey=function(J){return Q1.create(Q1.Class.UNIVERSAL,Q1.Type.SEQUENCE,!0,[Q1.create(Q1.Class.UNIVERSAL,Q1.Type.INTEGER,!1,Q1.integerToDer(0).getBytes()),Q1.create(Q1.Class.UNIVERSAL,Q1.Type.INTEGER,!1,jG(J.n)),Q1.create(Q1.Class.UNIVERSAL,Q1.Type.INTEGER,!1,jG(J.e)),Q1.create(Q1.Class.UNIVERSAL,Q1.Type.INTEGER,!1,jG(J.d)),Q1.create(Q1.Class.UNIVERSAL,Q1.Type.INTEGER,!1,jG(J.p)),Q1.create(Q1.Class.UNIVERSAL,Q1.Type.INTEGER,!1,jG(J.q)),Q1.create(Q1.Class.UNIVERSAL,Q1.Type.INTEGER,!1,jG(J.dP)),Q1.create(Q1.Class.UNIVERSAL,Q1.Type.INTEGER,!1,jG(J.dQ)),Q1.create(Q1.Class.UNIVERSAL,Q1.Type.INTEGER,!1,jG(J.qInv))])};g6.publicKeyFromAsn1=function(J){var Z={},Q=[];if(Q1.validate(J,ie5,Z,Q)){var Y=Q1.derToOid(Z.publicKeyOid);if(Y!==g6.oids.rsaEncryption){var X=Error("Cannot read public key. Unknown OID.");throw X.oid=Y,X}J=Z.rsaPublicKey}if(Q=[],!Q1.validate(J,le5,Z,Q)){var X=Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.");throw X.errors=Q,X}var V=Z6.util.createBuffer(Z.publicKeyModulus).toHex(),K=Z6.util.createBuffer(Z.publicKeyExponent).toHex();return g6.setRsaPublicKey(new _5(V,16),new _5(K,16))};g6.publicKeyToAsn1=g6.publicKeyToSubjectPublicKeyInfo=function(J){return Q1.create(Q1.Class.UNIVERSAL,Q1.Type.SEQUENCE,!0,[Q1.create(Q1.Class.UNIVERSAL,Q1.Type.SEQUENCE,!0,[Q1.create(Q1.Class.UNIVERSAL,Q1.Type.OID,!1,Q1.oidToDer(g6.oids.rsaEncryption).getBytes()),Q1.create(Q1.Class.UNIVERSAL,Q1.Type.NULL,!1,"")]),Q1.create(Q1.Class.UNIVERSAL,Q1.Type.BITSTRING,!1,[g6.publicKeyToRSAPublicKey(J)])])};g6.publicKeyToRSAPublicKey=function(J){return Q1.create(Q1.Class.UNIVERSAL,Q1.Type.SEQUENCE,!0,[Q1.create(Q1.Class.UNIVERSAL,Q1.Type.INTEGER,!1,jG(J.n)),Q1.create(Q1.Class.UNIVERSAL,Q1.Type.INTEGER,!1,jG(J.e))])};function $I4(J,Z,Q){var Y=Z6.util.createBuffer(),X=Math.ceil(Z.n.bitLength()/8);if(J.length>X-11){var V=Error("Message is too long for PKCS#1 v1.5 padding.");throw V.length=J.length,V.max=X-11,V}Y.putByte(0),Y.putByte(Q);var K=X-3-J.length,z;if(Q===0||Q===1){z=Q===0?0:255;for(var G=0;G<K;++G)Y.putByte(z)}else while(K>0){var F=0,U=Z6.random.getBytes(K);for(var G=0;G<K;++G)if(z=U.charCodeAt(G),z===0)++F;else Y.putByte(z);K=F}return Y.putByte(0),Y.putBytes(J),Y}function cJ0(J,Z,Q,Y){var X=Math.ceil(Z.n.bitLength()/8),V=Z6.util.createBuffer(J),K=V.getByte(),z=V.getByte();if(K!==0||Q&&z!==0&&z!==1||!Q&&z!=2||Q&&z===0&&typeof Y>"u")throw Error("Encryption block is invalid.");var G=0;if(z===0){G=X-3-Y;for(var F=0;F<G;++F)if(V.getByte()!==0)throw Error("Encryption block is invalid.")}else if(z===1){G=0;while(V.length()>1){if(V.getByte()!==255){--V.read;break}++G}}else if(z===2){G=0;while(V.length()>1){if(V.getByte()===0){--V.read;break}++G}}var U=V.getByte();if(U!==0||G!==X-3-V.length())throw Error("Encryption block is invalid.");return V.getBytes()}function oe5(J,Z,Q){if(typeof Z==="function")Q=Z,Z={};Z=Z||{};var Y={algorithm:{name:Z.algorithm||"PRIMEINC",options:{workers:Z.workers||2,workLoad:Z.workLoad||100,workerScript:Z.workerScript}}};if("prng"in Z)Y.prng=Z.prng;X();function X(){V(J.pBits,function(z,G){if(z)return Q(z);if(J.p=G,J.q!==null)return K(z,J.q);V(J.qBits,K)})}function V(z,G){Z6.prime.generateProbablePrime(z,Y,G)}function K(z,G){if(z)return Q(z);if(J.q=G,J.p.compareTo(J.q)<0){var F=J.p;J.p=J.q,J.q=F}if(J.p.subtract(_5.ONE).gcd(J.e).compareTo(_5.ONE)!==0){J.p=null,X();return}if(J.q.subtract(_5.ONE).gcd(J.e).compareTo(_5.ONE)!==0){J.q=null,V(J.qBits,K);return}if(J.p1=J.p.subtract(_5.ONE),J.q1=J.q.subtract(_5.ONE),J.phi=J.p1.multiply(J.q1),J.phi.gcd(J.e).compareTo(_5.ONE)!==0){J.p=J.q=null,X();return}if(J.n=J.p.multiply(J.q),J.n.bitLength()!==J.bits){J.q=null,V(J.qBits,K);return}var U=J.e.modInverse(J.phi);J.keys={privateKey:g6.rsa.setPrivateKey(J.n,J.e,U,J.p,J.q,U.mod(J.p1),U.mod(J.q1),J.q.modInverse(J.p)),publicKey:g6.rsa.setPublicKey(J.n,J.e)},Q(null,J.keys)}}function jG(J){var Z=J.toString(16);if(Z[0]>="8")Z="00"+Z;var Q=Z6.util.hexToBytes(Z);if(Q.length>1&&(Q.charCodeAt(0)===0&&(Q.charCodeAt(1)&128)===0||Q.charCodeAt(0)===255&&(Q.charCodeAt(1)&128)===128))return Q.substr(1);return Q}function re5(J){if(J<=100)return 27;if(J<=150)return 18;if(J<=200)return 15;if(J<=250)return 12;if(J<=300)return 9;if(J<=350)return 8;if(J<=400)return 7;if(J<=500)return 6;if(J<=600)return 5;if(J<=800)return 4;if(J<=1250)return 3;return 2}function oA4(J){return Z6.util.isNodejs&&typeof Tc0[J]==="function"}function rA4(J){return typeof QX.globalScope<"u"&&typeof QX.globalScope.crypto==="object"&&typeof QX.globalScope.crypto.subtle==="object"&&typeof QX.globalScope.crypto.subtle[J]==="function"}function sA4(J){return typeof QX.globalScope<"u"&&typeof QX.globalScope.msCrypto==="object"&&typeof QX.globalScope.msCrypto.subtle==="object"&&typeof QX.globalScope.msCrypto.subtle[J]==="function"}function tA4(J){var Z=Z6.util.hexToBytes(J.toString(16)),Q=new Uint8Array(Z.length);for(var Y=0;Y<Z.length;++Y)Q[Y]=Z.charCodeAt(Y);return Q}});var Sc0=u((ZE9,XI4)=>{var j4=J5();KB();oV();wd();NG();zB();hJ0();lL();JX();Lc0();Ed();c5();if(typeof _c0>"u")_c0=j4.jsbn.BigInteger;var _c0,O1=j4.asn1,n6=j4.pki=j4.pki||{};XI4.exports=n6.pbe=j4.pbe=j4.pbe||{};var aL=n6.oids,se5={name:"EncryptedPrivateKeyInfo",tagClass:O1.Class.UNIVERSAL,type:O1.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:O1.Class.UNIVERSAL,type:O1.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:O1.Class.UNIVERSAL,type:O1.Type.OID,constructed:!1,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:O1.Class.UNIVERSAL,type:O1.Type.SEQUENCE,constructed:!0,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:O1.Class.UNIVERSAL,type:O1.Type.OCTETSTRING,constructed:!1,capture:"encryptedData"}]},te5={name:"PBES2Algorithms",tagClass:O1.Class.UNIVERSAL,type:O1.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:O1.Class.UNIVERSAL,type:O1.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:O1.Class.UNIVERSAL,type:O1.Type.OID,constructed:!1,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:O1.Class.UNIVERSAL,type:O1.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.params.salt",tagClass:O1.Class.UNIVERSAL,type:O1.Type.OCTETSTRING,constructed:!1,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:O1.Class.UNIVERSAL,type:O1.Type.INTEGER,constructed:!1,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:O1.Class.UNIVERSAL,type:O1.Type.INTEGER,constructed:!1,optional:!0,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:O1.Class.UNIVERSAL,type:O1.Type.SEQUENCE,constructed:!0,optional:!0,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:O1.Class.UNIVERSAL,type:O1.Type.OID,constructed:!1,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:O1.Class.UNIVERSAL,type:O1.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:O1.Class.UNIVERSAL,type:O1.Type.OID,constructed:!1,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:O1.Class.UNIVERSAL,type:O1.Type.OCTETSTRING,constructed:!1,capture:"encIv"}]}]},ee5={name:"pkcs-12PbeParams",tagClass:O1.Class.UNIVERSAL,type:O1.Type.SEQUENCE,constructed:!0,value:[{name:"pkcs-12PbeParams.salt",tagClass:O1.Class.UNIVERSAL,type:O1.Type.OCTETSTRING,constructed:!1,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:O1.Class.UNIVERSAL,type:O1.Type.INTEGER,constructed:!1,capture:"iterations"}]};n6.encryptPrivateKeyInfo=function(J,Z,Q){Q=Q||{},Q.saltSize=Q.saltSize||8,Q.count=Q.count||2048,Q.algorithm=Q.algorithm||"aes128",Q.prfAlgorithm=Q.prfAlgorithm||"sha1";var Y=j4.random.getBytesSync(Q.saltSize),X=Q.count,V=O1.integerToDer(X),K,z,G;if(Q.algorithm.indexOf("aes")===0||Q.algorithm==="des"){var F,U,q;switch(Q.algorithm){case"aes128":K=16,F=16,U=aL["aes128-CBC"],q=j4.aes.createEncryptionCipher;break;case"aes192":K=24,F=16,U=aL["aes192-CBC"],q=j4.aes.createEncryptionCipher;break;case"aes256":K=32,F=16,U=aL["aes256-CBC"],q=j4.aes.createEncryptionCipher;break;case"des":K=8,F=8,U=aL.desCBC,q=j4.des.createEncryptionCipher;break;default:var D=Error("Cannot encrypt private key. Unknown encryption algorithm.");throw D.algorithm=Q.algorithm,D}var W="hmacWith"+Q.prfAlgorithm.toUpperCase(),H=YI4(W),B=j4.pkcs5.pbkdf2(Z,Y,X,K,H),w=j4.random.getBytesSync(F),N=q(B);N.start(w),N.update(O1.toDer(J)),N.finish(),G=N.output.getBytes();var O=$03(Y,V,K,W);z=O1.create(O1.Class.UNIVERSAL,O1.Type.SEQUENCE,!0,[O1.create(O1.Class.UNIVERSAL,O1.Type.OID,!1,O1.oidToDer(aL.pkcs5PBES2).getBytes()),O1.create(O1.Class.UNIVERSAL,O1.Type.SEQUENCE,!0,[O1.create(O1.Class.UNIVERSAL,O1.Type.SEQUENCE,!0,[O1.create(O1.Class.UNIVERSAL,O1.Type.OID,!1,O1.oidToDer(aL.pkcs5PBKDF2).getBytes()),O]),O1.create(O1.Class.UNIVERSAL,O1.Type.SEQUENCE,!0,[O1.create(O1.Class.UNIVERSAL,O1.Type.OID,!1,O1.oidToDer(U).getBytes()),O1.create(O1.Class.UNIVERSAL,O1.Type.OCTETSTRING,!1,w)])])])}else if(Q.algorithm==="3des"){K=24;var E=new j4.util.ByteBuffer(Y),B=n6.pbe.generatePkcs12Key(Z,E,1,X,K),w=n6.pbe.generatePkcs12Key(Z,E,2,X,K),N=j4.des.createEncryptionCipher(B);N.start(w),N.update(O1.toDer(J)),N.finish(),G=N.output.getBytes(),z=O1.create(O1.Class.UNIVERSAL,O1.Type.SEQUENCE,!0,[O1.create(O1.Class.UNIVERSAL,O1.Type.OID,!1,O1.oidToDer(aL["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),O1.create(O1.Class.UNIVERSAL,O1.Type.SEQUENCE,!0,[O1.create(O1.Class.UNIVERSAL,O1.Type.OCTETSTRING,!1,Y),O1.create(O1.Class.UNIVERSAL,O1.Type.INTEGER,!1,V.getBytes())])])}else{var D=Error("Cannot encrypt private key. Unknown encryption algorithm.");throw D.algorithm=Q.algorithm,D}var L=O1.create(O1.Class.UNIVERSAL,O1.Type.SEQUENCE,!0,[z,O1.create(O1.Class.UNIVERSAL,O1.Type.OCTETSTRING,!1,G)]);return L};n6.decryptPrivateKeyInfo=function(J,Z){var Q=null,Y={},X=[];if(!O1.validate(J,se5,Y,X)){var V=Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw V.errors=X,V}var K=O1.derToOid(Y.encryptionOid),z=n6.pbe.getCipher(K,Y.encryptionParams,Z),G=j4.util.createBuffer(Y.encryptedData);if(z.update(G),z.finish())Q=O1.fromDer(z.output);return Q};n6.encryptedPrivateKeyToPem=function(J,Z){var Q={type:"ENCRYPTED PRIVATE KEY",body:O1.toDer(J).getBytes()};return j4.pem.encode(Q,{maxline:Z})};n6.encryptedPrivateKeyFromPem=function(J){var Z=j4.pem.decode(J)[0];if(Z.type!=="ENCRYPTED PRIVATE KEY"){var Q=Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".');throw Q.headerType=Z.type,Q}if(Z.procType&&Z.procType.type==="ENCRYPTED")throw Error("Could not convert encrypted private key from PEM; PEM is encrypted.");return O1.fromDer(Z.body)};n6.encryptRsaPrivateKey=function(J,Z,Q){if(Q=Q||{},!Q.legacy){var Y=n6.wrapRsaPrivateKey(n6.privateKeyToAsn1(J));return Y=n6.encryptPrivateKeyInfo(Y,Z,Q),n6.encryptedPrivateKeyToPem(Y)}var X,V,K,z;switch(Q.algorithm){case"aes128":X="AES-128-CBC",K=16,V=j4.random.getBytesSync(16),z=j4.aes.createEncryptionCipher;break;case"aes192":X="AES-192-CBC",K=24,V=j4.random.getBytesSync(16),z=j4.aes.createEncryptionCipher;break;case"aes256":X="AES-256-CBC",K=32,V=j4.random.getBytesSync(16),z=j4.aes.createEncryptionCipher;break;case"3des":X="DES-EDE3-CBC",K=24,V=j4.random.getBytesSync(8),z=j4.des.createEncryptionCipher;break;case"des":X="DES-CBC",K=8,V=j4.random.getBytesSync(8),z=j4.des.createEncryptionCipher;break;default:var G=Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+Q.algorithm+'".');throw G.algorithm=Q.algorithm,G}var F=j4.pbe.opensslDeriveBytes(Z,V.substr(0,8),K),U=z(F);U.start(V),U.update(O1.toDer(n6.privateKeyToAsn1(J))),U.finish();var q={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:X,parameters:j4.util.bytesToHex(V).toUpperCase()},body:U.output.getBytes()};return j4.pem.encode(q)};n6.decryptRsaPrivateKey=function(J,Z){var Q=null,Y=j4.pem.decode(J)[0];if(Y.type!=="ENCRYPTED PRIVATE KEY"&&Y.type!=="PRIVATE KEY"&&Y.type!=="RSA PRIVATE KEY"){var X=Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".');throw X.headerType=X,X}if(Y.procType&&Y.procType.type==="ENCRYPTED"){var V,K;switch(Y.dekInfo.algorithm){case"DES-CBC":V=8,K=j4.des.createDecryptionCipher;break;case"DES-EDE3-CBC":V=24,K=j4.des.createDecryptionCipher;break;case"AES-128-CBC":V=16,K=j4.aes.createDecryptionCipher;break;case"AES-192-CBC":V=24,K=j4.aes.createDecryptionCipher;break;case"AES-256-CBC":V=32,K=j4.aes.createDecryptionCipher;break;case"RC2-40-CBC":V=5,K=function(q){return j4.rc2.createDecryptionCipher(q,40)};break;case"RC2-64-CBC":V=8,K=function(q){return j4.rc2.createDecryptionCipher(q,64)};break;case"RC2-128-CBC":V=16,K=function(q){return j4.rc2.createDecryptionCipher(q,128)};break;default:var X=Error('Could not decrypt private key; unsupported encryption algorithm "'+Y.dekInfo.algorithm+'".');throw X.algorithm=Y.dekInfo.algorithm,X}var z=j4.util.hexToBytes(Y.dekInfo.parameters),G=j4.pbe.opensslDeriveBytes(Z,z.substr(0,8),V),F=K(G);if(F.start(z),F.update(j4.util.createBuffer(Y.body)),F.finish())Q=F.output.getBytes();else return Q}else Q=Y.body;if(Y.type==="ENCRYPTED PRIVATE KEY")Q=n6.decryptPrivateKeyInfo(O1.fromDer(Q),Z);else Q=O1.fromDer(Q);if(Q!==null)Q=n6.privateKeyFromAsn1(Q);return Q};n6.pbe.generatePkcs12Key=function(J,Z,Q,Y,X,V){var K,z;if(typeof V>"u"||V===null){if(!("sha1"in j4.md))throw Error('"sha1" hash algorithm unavailable.');V=j4.md.sha1.create()}var{digestLength:G,blockLength:F}=V,U=new j4.util.ByteBuffer,q=new j4.util.ByteBuffer;if(J!==null&&J!==void 0){for(z=0;z<J.length;z++)q.putInt16(J.charCodeAt(z));q.putInt16(0)}var D=q.length(),W=Z.length(),H=new j4.util.ByteBuffer;H.fillWithByte(Q,F);var B=F*Math.ceil(W/F),w=new j4.util.ByteBuffer;for(z=0;z<B;z++)w.putByte(Z.at(z%W));var N=F*Math.ceil(D/F),O=new j4.util.ByteBuffer;for(z=0;z<N;z++)O.putByte(q.at(z%D));var E=w;E.putBuffer(O);var L=Math.ceil(X/G);for(var M=1;M<=L;M++){var A=new j4.util.ByteBuffer;A.putBytes(H.bytes()),A.putBytes(E.bytes());for(var I=0;I<Y;I++)V.start(),V.update(A.getBytes()),A=V.digest();var P=new j4.util.ByteBuffer;for(z=0;z<F;z++)P.putByte(A.at(z%G));var _=Math.ceil(W/F)+Math.ceil(D/F),S=new j4.util.ByteBuffer;for(K=0;K<_;K++){var y=new j4.util.ByteBuffer(E.getBytes(F)),m=511;for(z=P.length()-1;z>=0;z--)m=m>>8,m+=P.at(z)+y.at(z),y.setAt(z,m&255);S.putBuffer(y)}E=S,U.putBuffer(A)}return U.truncate(U.length()-X),U};n6.pbe.getCipher=function(J,Z,Q){switch(J){case n6.oids.pkcs5PBES2:return n6.pbe.getCipherForPBES2(J,Z,Q);case n6.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case n6.oids["pbewithSHAAnd40BitRC2-CBC"]:return n6.pbe.getCipherForPKCS12PBE(J,Z,Q);default:var Y=Error("Cannot read encrypted PBE data block. Unsupported OID.");throw Y.oid=J,Y.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],Y}};n6.pbe.getCipherForPBES2=function(J,Z,Q){var Y={},X=[];if(!O1.validate(Z,te5,Y,X)){var V=Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw V.errors=X,V}if(J=O1.derToOid(Y.kdfOid),J!==n6.oids.pkcs5PBKDF2){var V=Error("Cannot read encrypted private key. Unsupported key derivation function OID.");throw V.oid=J,V.supportedOids=["pkcs5PBKDF2"],V}if(J=O1.derToOid(Y.encOid),J!==n6.oids["aes128-CBC"]&&J!==n6.oids["aes192-CBC"]&&J!==n6.oids["aes256-CBC"]&&J!==n6.oids["des-EDE3-CBC"]&&J!==n6.oids.desCBC){var V=Error("Cannot read encrypted private key. Unsupported encryption scheme OID.");throw V.oid=J,V.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],V}var K=Y.kdfSalt,z=j4.util.createBuffer(Y.kdfIterationCount);z=z.getInt(z.length()<<3);var G,F;switch(n6.oids[J]){case"aes128-CBC":G=16,F=j4.aes.createDecryptionCipher;break;case"aes192-CBC":G=24,F=j4.aes.createDecryptionCipher;break;case"aes256-CBC":G=32,F=j4.aes.createDecryptionCipher;break;case"des-EDE3-CBC":G=24,F=j4.des.createDecryptionCipher;break;case"desCBC":G=8,F=j4.des.createDecryptionCipher;break}var U=QI4(Y.prfOid),q=j4.pkcs5.pbkdf2(Q,K,z,G,U),D=Y.encIv,W=F(q);return W.start(D),W};n6.pbe.getCipherForPKCS12PBE=function(J,Z,Q){var Y={},X=[];if(!O1.validate(Z,ee5,Y,X)){var V=Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw V.errors=X,V}var K=j4.util.createBuffer(Y.salt),z=j4.util.createBuffer(Y.iterations);z=z.getInt(z.length()<<3);var G,F,U;switch(J){case n6.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:G=24,F=8,U=j4.des.startDecrypting;break;case n6.oids["pbewithSHAAnd40BitRC2-CBC"]:G=5,F=8,U=function(B,w){var N=j4.rc2.createDecryptionCipher(B,40);return N.start(w,null),N};break;default:var V=Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");throw V.oid=J,V}var q=QI4(Y.prfOid),D=n6.pbe.generatePkcs12Key(Q,K,1,z,G,q);q.start();var W=n6.pbe.generatePkcs12Key(Q,K,2,z,F,q);return U(D,W)};n6.pbe.opensslDeriveBytes=function(J,Z,Q,Y){if(typeof Y>"u"||Y===null){if(!("md5"in j4.md))throw Error('"md5" hash algorithm unavailable.');Y=j4.md.md5.create()}if(Z===null)Z="";var X=[ZI4(Y,J+Z)];for(var V=16,K=1;V<Q;++K,V+=16)X.push(ZI4(Y,X[K-1]+J+Z));return X.join("").substr(0,Q)};function ZI4(J,Z){return J.start().update(Z).digest().getBytes()}function QI4(J){var Z;if(!J)Z="hmacWithSHA1";else if(Z=n6.oids[O1.derToOid(J)],!Z){var Q=Error("Unsupported PRF OID.");throw Q.oid=J,Q.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],Q}return YI4(Z)}function YI4(J){var Z=j4.md;switch(J){case"hmacWithSHA224":Z=j4.md.sha512;case"hmacWithSHA1":case"hmacWithSHA256":case"hmacWithSHA384":case"hmacWithSHA512":J=J.substr(8).toLowerCase();break;default:var Q=Error("Unsupported PRF algorithm.");throw Q.algorithm=J,Q.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],Q}if(!Z||!(J in Z))throw Error("Unknown hash algorithm: "+J);return Z[J].create()}function $03(J,Z,Q,Y){var X=O1.create(O1.Class.UNIVERSAL,O1.Type.SEQUENCE,!0,[O1.create(O1.Class.UNIVERSAL,O1.Type.OCTETSTRING,!1,J),O1.create(O1.Class.UNIVERSAL,O1.Type.INTEGER,!1,Z.getBytes())]);if(Y!=="hmacWithSHA1")X.value.push(O1.create(O1.Class.UNIVERSAL,O1.Type.INTEGER,!1,j4.util.hexToBytes(Q.toString(16))),O1.create(O1.Class.UNIVERSAL,O1.Type.SEQUENCE,!0,[O1.create(O1.Class.UNIVERSAL,O1.Type.OID,!1,O1.oidToDer(n6.oids[Y]).getBytes()),O1.create(O1.Class.UNIVERSAL,O1.Type.NULL,!1,"")]));return X}});var vc0=u((QE9,zI4)=>{var G_=J5();oV();c5();var E4=G_.asn1,F_=zI4.exports=G_.pkcs7asn1=G_.pkcs7asn1||{};G_.pkcs7=G_.pkcs7||{};G_.pkcs7.asn1=F_;var VI4={name:"ContentInfo",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.ContentType",tagClass:E4.Class.UNIVERSAL,type:E4.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:E4.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,captureAsn1:"content"}]};F_.contentInfoValidator=VI4;var KI4={name:"EncryptedContentInfo",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentType",tagClass:E4.Class.UNIVERSAL,type:E4.Type.OID,constructed:!1,capture:"contentType"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentEncryptionAlgorithm.algorithm",tagClass:E4.Class.UNIVERSAL,type:E4.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm.parameter",tagClass:E4.Class.UNIVERSAL,captureAsn1:"encParameter"}]},{name:"EncryptedContentInfo.encryptedContent",tagClass:E4.Class.CONTEXT_SPECIFIC,type:0,capture:"encryptedContent",captureAsn1:"encryptedContentAsn1"}]};F_.envelopedDataValidator={name:"EnvelopedData",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SEQUENCE,constructed:!0,value:[{name:"EnvelopedData.Version",tagClass:E4.Class.UNIVERSAL,type:E4.Type.INTEGER,constructed:!1,capture:"version"},{name:"EnvelopedData.RecipientInfos",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SET,constructed:!0,captureAsn1:"recipientInfos"}].concat(KI4)};F_.encryptedDataValidator={name:"EncryptedData",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedData.Version",tagClass:E4.Class.UNIVERSAL,type:E4.Type.INTEGER,constructed:!1,capture:"version"}].concat(KI4)};var J03={name:"SignerInfo",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.version",tagClass:E4.Class.UNIVERSAL,type:E4.Type.INTEGER,constructed:!1},{name:"SignerInfo.issuerAndSerialNumber",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.issuerAndSerialNumber.issuer",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"SignerInfo.issuerAndSerialNumber.serialNumber",tagClass:E4.Class.UNIVERSAL,type:E4.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"SignerInfo.digestAlgorithm",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.digestAlgorithm.algorithm",tagClass:E4.Class.UNIVERSAL,type:E4.Type.OID,constructed:!1,capture:"digestAlgorithm"},{name:"SignerInfo.digestAlgorithm.parameter",tagClass:E4.Class.UNIVERSAL,constructed:!1,captureAsn1:"digestParameter",optional:!0}]},{name:"SignerInfo.authenticatedAttributes",tagClass:E4.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"authenticatedAttributes"},{name:"SignerInfo.digestEncryptionAlgorithm",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SEQUENCE,constructed:!0,capture:"signatureAlgorithm"},{name:"SignerInfo.encryptedDigest",tagClass:E4.Class.UNIVERSAL,type:E4.Type.OCTETSTRING,constructed:!1,capture:"signature"},{name:"SignerInfo.unauthenticatedAttributes",tagClass:E4.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,capture:"unauthenticatedAttributes"}]};F_.signedDataValidator={name:"SignedData",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SEQUENCE,constructed:!0,value:[{name:"SignedData.Version",tagClass:E4.Class.UNIVERSAL,type:E4.Type.INTEGER,constructed:!1,capture:"version"},{name:"SignedData.DigestAlgorithms",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SET,constructed:!0,captureAsn1:"digestAlgorithms"},VI4,{name:"SignedData.Certificates",tagClass:E4.Class.CONTEXT_SPECIFIC,type:0,optional:!0,captureAsn1:"certificates"},{name:"SignedData.CertificateRevocationLists",tagClass:E4.Class.CONTEXT_SPECIFIC,type:1,optional:!0,captureAsn1:"crls"},{name:"SignedData.SignerInfos",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SET,capture:"signerInfos",optional:!0,value:[J03]}]};F_.recipientInfoValidator={name:"RecipientInfo",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.version",tagClass:E4.Class.UNIVERSAL,type:E4.Type.INTEGER,constructed:!1,capture:"version"},{name:"RecipientInfo.issuerAndSerial",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.issuerAndSerial.issuer",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"RecipientInfo.issuerAndSerial.serialNumber",tagClass:E4.Class.UNIVERSAL,type:E4.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"RecipientInfo.keyEncryptionAlgorithm",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.keyEncryptionAlgorithm.algorithm",tagClass:E4.Class.UNIVERSAL,type:E4.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"RecipientInfo.keyEncryptionAlgorithm.parameter",tagClass:E4.Class.UNIVERSAL,constructed:!1,captureAsn1:"encParameter",optional:!0}]},{name:"RecipientInfo.encryptedKey",tagClass:E4.Class.UNIVERSAL,type:E4.Type.OCTETSTRING,constructed:!1,capture:"encKey"}]}});var kc0=u((YE9,GI4)=>{var oL=J5();c5();oL.mgf=oL.mgf||{};var Z03=GI4.exports=oL.mgf.mgf1=oL.mgf1=oL.mgf1||{};Z03.create=function(J){var Z={generate:function(Q,Y){var X=new oL.util.ByteBuffer,V=Math.ceil(Y/J.digestLength);for(var K=0;K<V;K++){var z=new oL.util.ByteBuffer;z.putInt32(K),J.start(),J.update(Q+z.getBytes()),X.putBuffer(J.digest())}return X.truncate(X.length()-Y),X.getBytes()}};return Z}});var UI4=u((XE9,FI4)=>{var lJ0=J5();kc0();FI4.exports=lJ0.mgf=lJ0.mgf||{};lJ0.mgf.mgf1=lJ0.mgf1});var iJ0=u((VE9,qI4)=>{var rL=J5();JX();c5();var Q03=qI4.exports=rL.pss=rL.pss||{};Q03.create=function(J){if(arguments.length===3)J={md:arguments[0],mgf:arguments[1],saltLength:arguments[2]};var{md:Z,mgf:Q}=J,Y=Z.digestLength,X=J.salt||null;if(typeof X==="string")X=rL.util.createBuffer(X);var V;if("saltLength"in J)V=J.saltLength;else if(X!==null)V=X.length();else throw Error("Salt length not specified or specific salt not given.");if(X!==null&&X.length()!==V)throw Error("Given salt length does not match length of given salt.");var K=J.prng||rL.random,z={};return z.encode=function(G,F){var U,q=F-1,D=Math.ceil(q/8),W=G.digest().getBytes();if(D<Y+V+2)throw Error("Message is too long to encrypt.");var H;if(X===null)H=K.getBytesSync(V);else H=X.bytes();var B=new rL.util.ByteBuffer;B.fillWithByte(0,8),B.putBytes(W),B.putBytes(H),Z.start(),Z.update(B.getBytes());var w=Z.digest().getBytes(),N=new rL.util.ByteBuffer;N.fillWithByte(0,D-V-Y-2),N.putByte(1),N.putBytes(H);var O=N.getBytes(),E=D-Y-1,L=Q.generate(w,E),M="";for(U=0;U<E;U++)M+=String.fromCharCode(O.charCodeAt(U)^L.charCodeAt(U));var A=65280>>8*D-q&255;return M=String.fromCharCode(M.charCodeAt(0)&~A)+M.substr(1),M+w+String.fromCharCode(188)},z.verify=function(G,F,U){var q,D=U-1,W=Math.ceil(D/8);if(F=F.substr(-W),W<Y+V+2)throw Error("Inconsistent parameters to PSS signature verification.");if(F.charCodeAt(W-1)!==188)throw Error("Encoded message does not end in 0xBC.");var H=W-Y-1,B=F.substr(0,H),w=F.substr(H,Y),N=65280>>8*W-D&255;if((B.charCodeAt(0)&N)!==0)throw Error("Bits beyond keysize not zero as expected.");var O=Q.generate(w,H),E="";for(q=0;q<H;q++)E+=String.fromCharCode(B.charCodeAt(q)^O.charCodeAt(q));E=String.fromCharCode(E.charCodeAt(0)&~N)+E.substr(1);var L=W-Y-V-2;for(q=0;q<L;q++)if(E.charCodeAt(q)!==0)throw Error("Leftmost octets not zero as expected");if(E.charCodeAt(L)!==1)throw Error("Inconsistent PSS signature, 0x01 marker not found");var M=E.substr(-V),A=new rL.util.ByteBuffer;A.fillWithByte(0,8),A.putBytes(G),A.putBytes(M),Z.start(),Z.update(A.getBytes());var I=Z.digest().getBytes();return w===I},z}});var oJ0=u((KE9,wI4)=>{var Q6=J5();KB();oV();wd();NG();UI4();zB();lL();iJ0();Ed();c5();var E0=Q6.asn1,e1=wI4.exports=Q6.pki=Q6.pki||{},f5=e1.oids,z9={};z9.CN=f5.commonName;z9.commonName="CN";z9.C=f5.countryName;z9.countryName="C";z9.L=f5.localityName;z9.localityName="L";z9.ST=f5.stateOrProvinceName;z9.stateOrProvinceName="ST";z9.O=f5.organizationName;z9.organizationName="O";z9.OU=f5.organizationalUnitName;z9.organizationalUnitName="OU";z9.E=f5.emailAddress;z9.emailAddress="E";var WI4=Q6.pki.rsa.publicKeyValidator,Y03={name:"Certificate",tagClass:E0.Class.UNIVERSAL,type:E0.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate",tagClass:E0.Class.UNIVERSAL,type:E0.Type.SEQUENCE,constructed:!0,captureAsn1:"tbsCertificate",value:[{name:"Certificate.TBSCertificate.version",tagClass:E0.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.version.integer",tagClass:E0.Class.UNIVERSAL,type:E0.Type.INTEGER,constructed:!1,capture:"certVersion"}]},{name:"Certificate.TBSCertificate.serialNumber",tagClass:E0.Class.UNIVERSAL,type:E0.Type.INTEGER,constructed:!1,capture:"certSerialNumber"},{name:"Certificate.TBSCertificate.signature",tagClass:E0.Class.UNIVERSAL,type:E0.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.signature.algorithm",tagClass:E0.Class.UNIVERSAL,type:E0.Type.OID,constructed:!1,capture:"certinfoSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:E0.Class.UNIVERSAL,optional:!0,captureAsn1:"certinfoSignatureParams"}]},{name:"Certificate.TBSCertificate.issuer",tagClass:E0.Class.UNIVERSAL,type:E0.Type.SEQUENCE,constructed:!0,captureAsn1:"certIssuer"},{name:"Certificate.TBSCertificate.validity",tagClass:E0.Class.UNIVERSAL,type:E0.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.validity.notBefore (utc)",tagClass:E0.Class.UNIVERSAL,type:E0.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity1UTCTime"},{name:"Certificate.TBSCertificate.validity.notBefore (generalized)",tagClass:E0.Class.UNIVERSAL,type:E0.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity2GeneralizedTime"},{name:"Certificate.TBSCertificate.validity.notAfter (utc)",tagClass:E0.Class.UNIVERSAL,type:E0.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity3UTCTime"},{name:"Certificate.TBSCertificate.validity.notAfter (generalized)",tagClass:E0.Class.UNIVERSAL,type:E0.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity4GeneralizedTime"}]},{name:"Certificate.TBSCertificate.subject",tagClass:E0.Class.UNIVERSAL,type:E0.Type.SEQUENCE,constructed:!0,captureAsn1:"certSubject"},WI4,{name:"Certificate.TBSCertificate.issuerUniqueID",tagClass:E0.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.issuerUniqueID.id",tagClass:E0.Class.UNIVERSAL,type:E0.Type.BITSTRING,constructed:!1,captureBitStringValue:"certIssuerUniqueId"}]},{name:"Certificate.TBSCertificate.subjectUniqueID",tagClass:E0.Class.CONTEXT_SPECIFIC,type:2,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.subjectUniqueID.id",tagClass:E0.Class.UNIVERSAL,type:E0.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSubjectUniqueId"}]},{name:"Certificate.TBSCertificate.extensions",tagClass:E0.Class.CONTEXT_SPECIFIC,type:3,constructed:!0,captureAsn1:"certExtensions",optional:!0}]},{name:"Certificate.signatureAlgorithm",tagClass:E0.Class.UNIVERSAL,type:E0.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.signatureAlgorithm.algorithm",tagClass:E0.Class.UNIVERSAL,type:E0.Type.OID,constructed:!1,capture:"certSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:E0.Class.UNIVERSAL,optional:!0,captureAsn1:"certSignatureParams"}]},{name:"Certificate.signatureValue",tagClass:E0.Class.UNIVERSAL,type:E0.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSignature"}]},X03={name:"rsapss",tagClass:E0.Class.UNIVERSAL,type:E0.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.hashAlgorithm",tagClass:E0.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier",tagClass:E0.Class.UNIVERSAL,type:E0.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm",tagClass:E0.Class.UNIVERSAL,type:E0.Type.OID,constructed:!1,capture:"hashOid"}]}]},{name:"rsapss.maskGenAlgorithm",tagClass:E0.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier",tagClass:E0.Class.UNIVERSAL,type:E0.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm",tagClass:E0.Class.UNIVERSAL,type:E0.Type.OID,constructed:!1,capture:"maskGenOid"},{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params",tagClass:E0.Class.UNIVERSAL,type:E0.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm",tagClass:E0.Class.UNIVERSAL,type:E0.Type.OID,constructed:!1,capture:"maskGenHashOid"}]}]}]},{name:"rsapss.saltLength",tagClass:E0.Class.CONTEXT_SPECIFIC,type:2,optional:!0,value:[{name:"rsapss.saltLength.saltLength",tagClass:E0.Class.UNIVERSAL,type:E0.Class.INTEGER,constructed:!1,capture:"saltLength"}]},{name:"rsapss.trailerField",tagClass:E0.Class.CONTEXT_SPECIFIC,type:3,optional:!0,value:[{name:"rsapss.trailer.trailer",tagClass:E0.Class.UNIVERSAL,type:E0.Class.INTEGER,constructed:!1,capture:"trailer"}]}]},V03={name:"CertificationRequestInfo",tagClass:E0.Class.UNIVERSAL,type:E0.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfo",value:[{name:"CertificationRequestInfo.integer",tagClass:E0.Class.UNIVERSAL,type:E0.Type.INTEGER,constructed:!1,capture:"certificationRequestInfoVersion"},{name:"CertificationRequestInfo.subject",tagClass:E0.Class.UNIVERSAL,type:E0.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfoSubject"},WI4,{name:"CertificationRequestInfo.attributes",tagClass:E0.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"certificationRequestInfoAttributes",value:[{name:"CertificationRequestInfo.attributes",tagClass:E0.Class.UNIVERSAL,type:E0.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequestInfo.attributes.type",tagClass:E0.Class.UNIVERSAL,type:E0.Type.OID,constructed:!1},{name:"CertificationRequestInfo.attributes.value",tagClass:E0.Class.UNIVERSAL,type:E0.Type.SET,constructed:!0}]}]}]},K03={name:"CertificationRequest",tagClass:E0.Class.UNIVERSAL,type:E0.Type.SEQUENCE,constructed:!0,captureAsn1:"csr",value:[V03,{name:"CertificationRequest.signatureAlgorithm",tagClass:E0.Class.UNIVERSAL,type:E0.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequest.signatureAlgorithm.algorithm",tagClass:E0.Class.UNIVERSAL,type:E0.Type.OID,constructed:!1,capture:"csrSignatureOid"},{name:"CertificationRequest.signatureAlgorithm.parameters",tagClass:E0.Class.UNIVERSAL,optional:!0,captureAsn1:"csrSignatureParams"}]},{name:"CertificationRequest.signature",tagClass:E0.Class.UNIVERSAL,type:E0.Type.BITSTRING,constructed:!1,captureBitStringValue:"csrSignature"}]};e1.RDNAttributesAsArray=function(J,Z){var Q=[],Y,X,V;for(var K=0;K<J.value.length;++K){Y=J.value[K];for(var z=0;z<Y.value.length;++z){if(V={},X=Y.value[z],V.type=E0.derToOid(X.value[0].value),V.value=X.value[1].value,V.valueTagClass=X.value[1].type,V.type in f5){if(V.name=f5[V.type],V.name in z9)V.shortName=z9[V.name]}if(Z)Z.update(V.type),Z.update(V.value);Q.push(V)}}return Q};e1.CRIAttributesAsArray=function(J){var Z=[];for(var Q=0;Q<J.length;++Q){var Y=J[Q],X=E0.derToOid(Y.value[0].value),V=Y.value[1].value;for(var K=0;K<V.length;++K){var z={};if(z.type=X,z.value=V[K].value,z.valueTagClass=V[K].type,z.type in f5){if(z.name=f5[z.type],z.name in z9)z.shortName=z9[z.name]}if(z.type===f5.extensionRequest){z.extensions=[];for(var G=0;G<z.value.length;++G)z.extensions.push(e1.certificateExtensionFromAsn1(z.value[G]))}Z.push(z)}}return Z};function UB(J,Z){if(typeof Z==="string")Z={shortName:Z};var Q=null,Y;for(var X=0;Q===null&&X<J.attributes.length;++X)if(Y=J.attributes[X],Z.type&&Z.type===Y.type)Q=Y;else if(Z.name&&Z.name===Y.name)Q=Y;else if(Z.shortName&&Z.shortName===Y.shortName)Q=Y;return Q}var nJ0=function(J,Z,Q){var Y={};if(J!==f5["RSASSA-PSS"])return Y;if(Q)Y={hash:{algorithmOid:f5.sha1},mgf:{algorithmOid:f5.mgf1,hash:{algorithmOid:f5.sha1}},saltLength:20};var X={},V=[];if(!E0.validate(Z,X03,X,V)){var K=Error("Cannot read RSASSA-PSS parameter block.");throw K.errors=V,K}if(X.hashOid!==void 0)Y.hash=Y.hash||{},Y.hash.algorithmOid=E0.derToOid(X.hashOid);if(X.maskGenOid!==void 0)Y.mgf=Y.mgf||{},Y.mgf.algorithmOid=E0.derToOid(X.maskGenOid),Y.mgf.hash=Y.mgf.hash||{},Y.mgf.hash.algorithmOid=E0.derToOid(X.maskGenHashOid);if(X.saltLength!==void 0)Y.saltLength=X.saltLength.charCodeAt(0);return Y},aJ0=function(J){switch(f5[J.signatureOid]){case"sha1WithRSAEncryption":case"sha1WithRSASignature":return Q6.md.sha1.create();case"md5WithRSAEncryption":return Q6.md.md5.create();case"sha256WithRSAEncryption":return Q6.md.sha256.create();case"sha384WithRSAEncryption":return Q6.md.sha384.create();case"sha512WithRSAEncryption":return Q6.md.sha512.create();case"RSASSA-PSS":return Q6.md.sha256.create();default:var Z=Error("Could not compute "+J.type+" digest. Unknown signature OID.");throw Z.signatureOid=J.signatureOid,Z}},HI4=function(J){var Z=J.certificate,Q;switch(Z.signatureOid){case f5.sha1WithRSAEncryption:case f5.sha1WithRSASignature:break;case f5["RSASSA-PSS"]:var Y,X;if(Y=f5[Z.signatureParameters.mgf.hash.algorithmOid],Y===void 0||Q6.md[Y]===void 0){var V=Error("Unsupported MGF hash function.");throw V.oid=Z.signatureParameters.mgf.hash.algorithmOid,V.name=Y,V}if(X=f5[Z.signatureParameters.mgf.algorithmOid],X===void 0||Q6.mgf[X]===void 0){var V=Error("Unsupported MGF function.");throw V.oid=Z.signatureParameters.mgf.algorithmOid,V.name=X,V}if(X=Q6.mgf[X].create(Q6.md[Y].create()),Y=f5[Z.signatureParameters.hash.algorithmOid],Y===void 0||Q6.md[Y]===void 0){var V=Error("Unsupported RSASSA-PSS hash function.");throw V.oid=Z.signatureParameters.hash.algorithmOid,V.name=Y,V}Q=Q6.pss.create(Q6.md[Y].create(),X,Z.signatureParameters.saltLength);break}return Z.publicKey.verify(J.md.digest().getBytes(),J.signature,Q)};e1.certificateFromPem=function(J,Z,Q){var Y=Q6.pem.decode(J)[0];if(Y.type!=="CERTIFICATE"&&Y.type!=="X509 CERTIFICATE"&&Y.type!=="TRUSTED CERTIFICATE"){var X=Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');throw X.headerType=Y.type,X}if(Y.procType&&Y.procType.type==="ENCRYPTED")throw Error("Could not convert certificate from PEM; PEM is encrypted.");var V=E0.fromDer(Y.body,Q);return e1.certificateFromAsn1(V,Z)};e1.certificateToPem=function(J,Z){var Q={type:"CERTIFICATE",body:E0.toDer(e1.certificateToAsn1(J)).getBytes()};return Q6.pem.encode(Q,{maxline:Z})};e1.publicKeyFromPem=function(J){var Z=Q6.pem.decode(J)[0];if(Z.type!=="PUBLIC KEY"&&Z.type!=="RSA PUBLIC KEY"){var Q=Error('Could not convert public key from PEM; PEM header type is not "PUBLIC KEY" or "RSA PUBLIC KEY".');throw Q.headerType=Z.type,Q}if(Z.procType&&Z.procType.type==="ENCRYPTED")throw Error("Could not convert public key from PEM; PEM is encrypted.");var Y=E0.fromDer(Z.body);return e1.publicKeyFromAsn1(Y)};e1.publicKeyToPem=function(J,Z){var Q={type:"PUBLIC KEY",body:E0.toDer(e1.publicKeyToAsn1(J)).getBytes()};return Q6.pem.encode(Q,{maxline:Z})};e1.publicKeyToRSAPublicKeyPem=function(J,Z){var Q={type:"RSA PUBLIC KEY",body:E0.toDer(e1.publicKeyToRSAPublicKey(J)).getBytes()};return Q6.pem.encode(Q,{maxline:Z})};e1.getPublicKeyFingerprint=function(J,Z){Z=Z||{};var Q=Z.md||Q6.md.sha1.create(),Y=Z.type||"RSAPublicKey",X;switch(Y){case"RSAPublicKey":X=E0.toDer(e1.publicKeyToRSAPublicKey(J)).getBytes();break;case"SubjectPublicKeyInfo":X=E0.toDer(e1.publicKeyToAsn1(J)).getBytes();break;default:throw Error('Unknown fingerprint type "'+Z.type+'".')}Q.start(),Q.update(X);var V=Q.digest();if(Z.encoding==="hex"){var K=V.toHex();if(Z.delimiter)return K.match(/.{2}/g).join(Z.delimiter);return K}else if(Z.encoding==="binary")return V.getBytes();else if(Z.encoding)throw Error('Unknown encoding "'+Z.encoding+'".');return V};e1.certificationRequestFromPem=function(J,Z,Q){var Y=Q6.pem.decode(J)[0];if(Y.type!=="CERTIFICATE REQUEST"){var X=Error('Could not convert certification request from PEM; PEM header type is not "CERTIFICATE REQUEST".');throw X.headerType=Y.type,X}if(Y.procType&&Y.procType.type==="ENCRYPTED")throw Error("Could not convert certification request from PEM; PEM is encrypted.");var V=E0.fromDer(Y.body,Q);return e1.certificationRequestFromAsn1(V,Z)};e1.certificationRequestToPem=function(J,Z){var Q={type:"CERTIFICATE REQUEST",body:E0.toDer(e1.certificationRequestToAsn1(J)).getBytes()};return Q6.pem.encode(Q,{maxline:Z})};e1.createCertificate=function(){var J={};return J.version=2,J.serialNumber="00",J.signatureOid=null,J.signature=null,J.siginfo={},J.siginfo.algorithmOid=null,J.validity={},J.validity.notBefore=new Date,J.validity.notAfter=new Date,J.issuer={},J.issuer.getField=function(Z){return UB(J.issuer,Z)},J.issuer.addField=function(Z){YX([Z]),J.issuer.attributes.push(Z)},J.issuer.attributes=[],J.issuer.hash=null,J.subject={},J.subject.getField=function(Z){return UB(J.subject,Z)},J.subject.addField=function(Z){YX([Z]),J.subject.attributes.push(Z)},J.subject.attributes=[],J.subject.hash=null,J.extensions=[],J.publicKey=null,J.md=null,J.setSubject=function(Z,Q){if(YX(Z),J.subject.attributes=Z,delete J.subject.uniqueId,Q)J.subject.uniqueId=Q;J.subject.hash=null},J.setIssuer=function(Z,Q){if(YX(Z),J.issuer.attributes=Z,delete J.issuer.uniqueId,Q)J.issuer.uniqueId=Q;J.issuer.hash=null},J.setExtensions=function(Z){for(var Q=0;Q<Z.length;++Q)BI4(Z[Q],{cert:J});J.extensions=Z},J.getExtension=function(Z){if(typeof Z==="string")Z={name:Z};var Q=null,Y;for(var X=0;Q===null&&X<J.extensions.length;++X)if(Y=J.extensions[X],Z.id&&Y.id===Z.id)Q=Y;else if(Z.name&&Y.name===Z.name)Q=Y;return Q},J.sign=function(Z,Q){J.md=Q||Q6.md.sha1.create();var Y=f5[J.md.algorithm+"WithRSAEncryption"];if(!Y){var X=Error("Could not compute certificate digest. Unknown message digest algorithm OID.");throw X.algorithm=J.md.algorithm,X}J.signatureOid=J.siginfo.algorithmOid=Y,J.tbsCertificate=e1.getTBSCertificate(J);var V=E0.toDer(J.tbsCertificate);J.md.update(V.getBytes()),J.signature=Z.sign(J.md)},J.verify=function(Z){var Q=!1;if(!J.issued(Z)){var Y=Z.issuer,X=J.subject,V=Error("The parent certificate did not issue the given child certificate; the child certificate's issuer does not match the parent's subject.");throw V.expectedIssuer=X.attributes,V.actualIssuer=Y.attributes,V}var K=Z.md;if(K===null){K=aJ0({signatureOid:Z.signatureOid,type:"certificate"});var z=Z.tbsCertificate||e1.getTBSCertificate(Z),G=E0.toDer(z);K.update(G.getBytes())}if(K!==null)Q=HI4({certificate:J,md:K,signature:Z.signature});return Q},J.isIssuer=function(Z){var Q=!1,Y=J.issuer,X=Z.subject;if(Y.hash&&X.hash)Q=Y.hash===X.hash;else if(Y.attributes.length===X.attributes.length){Q=!0;var V,K;for(var z=0;Q&&z<Y.attributes.length;++z)if(V=Y.attributes[z],K=X.attributes[z],V.type!==K.type||V.value!==K.value)Q=!1}return Q},J.issued=function(Z){return Z.isIssuer(J)},J.generateSubjectKeyIdentifier=function(){return e1.getPublicKeyFingerprint(J.publicKey,{type:"RSAPublicKey"})},J.verifySubjectKeyIdentifier=function(){var Z=f5.subjectKeyIdentifier;for(var Q=0;Q<J.extensions.length;++Q){var Y=J.extensions[Q];if(Y.id===Z){var X=J.generateSubjectKeyIdentifier().getBytes();return Q6.util.hexToBytes(Y.subjectKeyIdentifier)===X}}return!1},J};e1.certificateFromAsn1=function(J,Z){var Q={},Y=[];if(!E0.validate(J,Y03,Q,Y)){var X=Error("Cannot read X.509 certificate. ASN.1 object is not an X509v3 Certificate.");throw X.errors=Y,X}var V=E0.derToOid(Q.publicKeyOid);if(V!==e1.oids.rsaEncryption)throw Error("Cannot read public key. OID is not RSA.");var K=e1.createCertificate();K.version=Q.certVersion?Q.certVersion.charCodeAt(0):0;var z=Q6.util.createBuffer(Q.certSerialNumber);K.serialNumber=z.toHex(),K.signatureOid=Q6.asn1.derToOid(Q.certSignatureOid),K.signatureParameters=nJ0(K.signatureOid,Q.certSignatureParams,!0),K.siginfo.algorithmOid=Q6.asn1.derToOid(Q.certinfoSignatureOid),K.siginfo.parameters=nJ0(K.siginfo.algorithmOid,Q.certinfoSignatureParams,!1),K.signature=Q.certSignature;var G=[];if(Q.certValidity1UTCTime!==void 0)G.push(E0.utcTimeToDate(Q.certValidity1UTCTime));if(Q.certValidity2GeneralizedTime!==void 0)G.push(E0.generalizedTimeToDate(Q.certValidity2GeneralizedTime));if(Q.certValidity3UTCTime!==void 0)G.push(E0.utcTimeToDate(Q.certValidity3UTCTime));if(Q.certValidity4GeneralizedTime!==void 0)G.push(E0.generalizedTimeToDate(Q.certValidity4GeneralizedTime));if(G.length>2)throw Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate.");if(G.length<2)throw Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime.");if(K.validity.notBefore=G[0],K.validity.notAfter=G[1],K.tbsCertificate=Q.tbsCertificate,Z){K.md=aJ0({signatureOid:K.signatureOid,type:"certificate"});var F=E0.toDer(K.tbsCertificate);K.md.update(F.getBytes())}var U=Q6.md.sha1.create(),q=E0.toDer(Q.certIssuer);if(U.update(q.getBytes()),K.issuer.getField=function(H){return UB(K.issuer,H)},K.issuer.addField=function(H){YX([H]),K.issuer.attributes.push(H)},K.issuer.attributes=e1.RDNAttributesAsArray(Q.certIssuer),Q.certIssuerUniqueId)K.issuer.uniqueId=Q.certIssuerUniqueId;K.issuer.hash=U.digest().toHex();var D=Q6.md.sha1.create(),W=E0.toDer(Q.certSubject);if(D.update(W.getBytes()),K.subject.getField=function(H){return UB(K.subject,H)},K.subject.addField=function(H){YX([H]),K.subject.attributes.push(H)},K.subject.attributes=e1.RDNAttributesAsArray(Q.certSubject),Q.certSubjectUniqueId)K.subject.uniqueId=Q.certSubjectUniqueId;if(K.subject.hash=D.digest().toHex(),Q.certExtensions)K.extensions=e1.certificateExtensionsFromAsn1(Q.certExtensions);else K.extensions=[];return K.publicKey=e1.publicKeyFromAsn1(Q.subjectPublicKeyInfo),K};e1.certificateExtensionsFromAsn1=function(J){var Z=[];for(var Q=0;Q<J.value.length;++Q){var Y=J.value[Q];for(var X=0;X<Y.value.length;++X)Z.push(e1.certificateExtensionFromAsn1(Y.value[X]))}return Z};e1.certificateExtensionFromAsn1=function(J){var Z={};if(Z.id=E0.derToOid(J.value[0].value),Z.critical=!1,J.value[1].type===E0.Type.BOOLEAN)Z.critical=J.value[1].value.charCodeAt(0)!==0,Z.value=J.value[2].value;else Z.value=J.value[1].value;if(Z.id in f5){if(Z.name=f5[Z.id],Z.name==="keyUsage"){var Q=E0.fromDer(Z.value),Y=0,X=0;if(Q.value.length>1)Y=Q.value.charCodeAt(1),X=Q.value.length>2?Q.value.charCodeAt(2):0;Z.digitalSignature=(Y&128)===128,Z.nonRepudiation=(Y&64)===64,Z.keyEncipherment=(Y&32)===32,Z.dataEncipherment=(Y&16)===16,Z.keyAgreement=(Y&8)===8,Z.keyCertSign=(Y&4)===4,Z.cRLSign=(Y&2)===2,Z.encipherOnly=(Y&1)===1,Z.decipherOnly=(X&128)===128}else if(Z.name==="basicConstraints"){var Q=E0.fromDer(Z.value);if(Q.value.length>0&&Q.value[0].type===E0.Type.BOOLEAN)Z.cA=Q.value[0].value.charCodeAt(0)!==0;else Z.cA=!1;var V=null;if(Q.value.length>0&&Q.value[0].type===E0.Type.INTEGER)V=Q.value[0].value;else if(Q.value.length>1)V=Q.value[1].value;if(V!==null)Z.pathLenConstraint=E0.derToInteger(V)}else if(Z.name==="extKeyUsage"){var Q=E0.fromDer(Z.value);for(var K=0;K<Q.value.length;++K){var z=E0.derToOid(Q.value[K].value);if(z in f5)Z[f5[z]]=!0;else Z[z]=!0}}else if(Z.name==="nsCertType"){var Q=E0.fromDer(Z.value),Y=0;if(Q.value.length>1)Y=Q.value.charCodeAt(1);Z.client=(Y&128)===128,Z.server=(Y&64)===64,Z.email=(Y&32)===32,Z.objsign=(Y&16)===16,Z.reserved=(Y&8)===8,Z.sslCA=(Y&4)===4,Z.emailCA=(Y&2)===2,Z.objCA=(Y&1)===1}else if(Z.name==="subjectAltName"||Z.name==="issuerAltName"){Z.altNames=[];var G,Q=E0.fromDer(Z.value);for(var F=0;F<Q.value.length;++F){G=Q.value[F];var U={type:G.type,value:G.value};switch(Z.altNames.push(U),G.type){case 1:case 2:case 6:break;case 7:U.ip=Q6.util.bytesToIP(G.value);break;case 8:U.oid=E0.derToOid(G.value);break;default:}}}else if(Z.name==="subjectKeyIdentifier"){var Q=E0.fromDer(Z.value);Z.subjectKeyIdentifier=Q6.util.bytesToHex(Q.value)}}return Z};e1.certificationRequestFromAsn1=function(J,Z){var Q={},Y=[];if(!E0.validate(J,K03,Q,Y)){var X=Error("Cannot read PKCS#10 certificate request. ASN.1 object is not a PKCS#10 CertificationRequest.");throw X.errors=Y,X}var V=E0.derToOid(Q.publicKeyOid);if(V!==e1.oids.rsaEncryption)throw Error("Cannot read public key. OID is not RSA.");var K=e1.createCertificationRequest();if(K.version=Q.csrVersion?Q.csrVersion.charCodeAt(0):0,K.signatureOid=Q6.asn1.derToOid(Q.csrSignatureOid),K.signatureParameters=nJ0(K.signatureOid,Q.csrSignatureParams,!0),K.siginfo.algorithmOid=Q6.asn1.derToOid(Q.csrSignatureOid),K.siginfo.parameters=nJ0(K.siginfo.algorithmOid,Q.csrSignatureParams,!1),K.signature=Q.csrSignature,K.certificationRequestInfo=Q.certificationRequestInfo,Z){K.md=aJ0({signatureOid:K.signatureOid,type:"certification request"});var z=E0.toDer(K.certificationRequestInfo);K.md.update(z.getBytes())}var G=Q6.md.sha1.create();return K.subject.getField=function(F){return UB(K.subject,F)},K.subject.addField=function(F){YX([F]),K.subject.attributes.push(F)},K.subject.attributes=e1.RDNAttributesAsArray(Q.certificationRequestInfoSubject,G),K.subject.hash=G.digest().toHex(),K.publicKey=e1.publicKeyFromAsn1(Q.subjectPublicKeyInfo),K.getAttribute=function(F){return UB(K,F)},K.addAttribute=function(F){YX([F]),K.attributes.push(F)},K.attributes=e1.CRIAttributesAsArray(Q.certificationRequestInfoAttributes||[]),K};e1.createCertificationRequest=function(){var J={};return J.version=0,J.signatureOid=null,J.signature=null,J.siginfo={},J.siginfo.algorithmOid=null,J.subject={},J.subject.getField=function(Z){return UB(J.subject,Z)},J.subject.addField=function(Z){YX([Z]),J.subject.attributes.push(Z)},J.subject.attributes=[],J.subject.hash=null,J.publicKey=null,J.attributes=[],J.getAttribute=function(Z){return UB(J,Z)},J.addAttribute=function(Z){YX([Z]),J.attributes.push(Z)},J.md=null,J.setSubject=function(Z){YX(Z),J.subject.attributes=Z,J.subject.hash=null},J.setAttributes=function(Z){YX(Z),J.attributes=Z},J.sign=function(Z,Q){J.md=Q||Q6.md.sha1.create();var Y=f5[J.md.algorithm+"WithRSAEncryption"];if(!Y){var X=Error("Could not compute certification request digest. Unknown message digest algorithm OID.");throw X.algorithm=J.md.algorithm,X}J.signatureOid=J.siginfo.algorithmOid=Y,J.certificationRequestInfo=e1.getCertificationRequestInfo(J);var V=E0.toDer(J.certificationRequestInfo);J.md.update(V.getBytes()),J.signature=Z.sign(J.md)},J.verify=function(){var Z=!1,Q=J.md;if(Q===null){Q=aJ0({signatureOid:J.signatureOid,type:"certification request"});var Y=J.certificationRequestInfo||e1.getCertificationRequestInfo(J),X=E0.toDer(Y);Q.update(X.getBytes())}if(Q!==null)Z=HI4({certificate:J,md:Q,signature:J.signature});return Z},J};function U_(J){var Z=E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[]),Q,Y,X=J.attributes;for(var V=0;V<X.length;++V){Q=X[V];var K=Q.value,z=E0.Type.PRINTABLESTRING;if("valueTagClass"in Q){if(z=Q.valueTagClass,z===E0.Type.UTF8)K=Q6.util.encodeUtf8(K)}Y=E0.create(E0.Class.UNIVERSAL,E0.Type.SET,!0,[E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[E0.create(E0.Class.UNIVERSAL,E0.Type.OID,!1,E0.oidToDer(Q.type).getBytes()),E0.create(E0.Class.UNIVERSAL,z,!1,K)])]),Z.value.push(Y)}return Z}function YX(J){var Z;for(var Q=0;Q<J.length;++Q){if(Z=J[Q],typeof Z.name>"u"){if(Z.type&&Z.type in e1.oids)Z.name=e1.oids[Z.type];else if(Z.shortName&&Z.shortName in z9)Z.name=e1.oids[z9[Z.shortName]]}if(typeof Z.type>"u")if(Z.name&&Z.name in e1.oids)Z.type=e1.oids[Z.name];else{var Y=Error("Attribute type not specified.");throw Y.attribute=Z,Y}if(typeof Z.shortName>"u"){if(Z.name&&Z.name in z9)Z.shortName=z9[Z.name]}if(Z.type===f5.extensionRequest){if(Z.valueConstructed=!0,Z.valueTagClass=E0.Type.SEQUENCE,!Z.value&&Z.extensions){Z.value=[];for(var X=0;X<Z.extensions.length;++X)Z.value.push(e1.certificateExtensionToAsn1(BI4(Z.extensions[X])))}}if(typeof Z.value>"u"){var Y=Error("Attribute value not specified.");throw Y.attribute=Z,Y}}}function BI4(J,Z){if(Z=Z||{},typeof J.name>"u"){if(J.id&&J.id in e1.oids)J.name=e1.oids[J.id]}if(typeof J.id>"u")if(J.name&&J.name in e1.oids)J.id=e1.oids[J.name];else{var Q=Error("Extension ID not specified.");throw Q.extension=J,Q}if(typeof J.value<"u")return J;if(J.name==="keyUsage"){var Y=0,X=0,V=0;if(J.digitalSignature)X|=128,Y=7;if(J.nonRepudiation)X|=64,Y=6;if(J.keyEncipherment)X|=32,Y=5;if(J.dataEncipherment)X|=16,Y=4;if(J.keyAgreement)X|=8,Y=3;if(J.keyCertSign)X|=4,Y=2;if(J.cRLSign)X|=2,Y=1;if(J.encipherOnly)X|=1,Y=0;if(J.decipherOnly)V|=128,Y=7;var K=String.fromCharCode(Y);if(V!==0)K+=String.fromCharCode(X)+String.fromCharCode(V);else if(X!==0)K+=String.fromCharCode(X);J.value=E0.create(E0.Class.UNIVERSAL,E0.Type.BITSTRING,!1,K)}else if(J.name==="basicConstraints"){if(J.value=E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[]),J.cA)J.value.value.push(E0.create(E0.Class.UNIVERSAL,E0.Type.BOOLEAN,!1,String.fromCharCode(255)));if("pathLenConstraint"in J)J.value.value.push(E0.create(E0.Class.UNIVERSAL,E0.Type.INTEGER,!1,E0.integerToDer(J.pathLenConstraint).getBytes()))}else if(J.name==="extKeyUsage"){J.value=E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[]);var z=J.value.value;for(var G in J){if(J[G]!==!0)continue;if(G in f5)z.push(E0.create(E0.Class.UNIVERSAL,E0.Type.OID,!1,E0.oidToDer(f5[G]).getBytes()));else if(G.indexOf(".")!==-1)z.push(E0.create(E0.Class.UNIVERSAL,E0.Type.OID,!1,E0.oidToDer(G).getBytes()))}}else if(J.name==="nsCertType"){var Y=0,X=0;if(J.client)X|=128,Y=7;if(J.server)X|=64,Y=6;if(J.email)X|=32,Y=5;if(J.objsign)X|=16,Y=4;if(J.reserved)X|=8,Y=3;if(J.sslCA)X|=4,Y=2;if(J.emailCA)X|=2,Y=1;if(J.objCA)X|=1,Y=0;var K=String.fromCharCode(Y);if(X!==0)K+=String.fromCharCode(X);J.value=E0.create(E0.Class.UNIVERSAL,E0.Type.BITSTRING,!1,K)}else if(J.name==="subjectAltName"||J.name==="issuerAltName"){J.value=E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[]);var F;for(var U=0;U<J.altNames.length;++U){F=J.altNames[U];var K=F.value;if(F.type===7&&F.ip){if(K=Q6.util.bytesFromIP(F.ip),K===null){var Q=Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');throw Q.extension=J,Q}}else if(F.type===8)if(F.oid)K=E0.oidToDer(E0.oidToDer(F.oid));else K=E0.oidToDer(K);J.value.value.push(E0.create(E0.Class.CONTEXT_SPECIFIC,F.type,!1,K))}}else if(J.name==="nsComment"&&Z.cert){if(!/^[\x00-\x7F]*$/.test(J.comment)||J.comment.length<1||J.comment.length>128)throw Error('Invalid "nsComment" content.');J.value=E0.create(E0.Class.UNIVERSAL,E0.Type.IA5STRING,!1,J.comment)}else if(J.name==="subjectKeyIdentifier"&&Z.cert){var q=Z.cert.generateSubjectKeyIdentifier();J.subjectKeyIdentifier=q.toHex(),J.value=E0.create(E0.Class.UNIVERSAL,E0.Type.OCTETSTRING,!1,q.getBytes())}else if(J.name==="authorityKeyIdentifier"&&Z.cert){J.value=E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[]);var z=J.value.value;if(J.keyIdentifier){var D=J.keyIdentifier===!0?Z.cert.generateSubjectKeyIdentifier().getBytes():J.keyIdentifier;z.push(E0.create(E0.Class.CONTEXT_SPECIFIC,0,!1,D))}if(J.authorityCertIssuer){var W=[E0.create(E0.Class.CONTEXT_SPECIFIC,4,!0,[U_(J.authorityCertIssuer===!0?Z.cert.issuer:J.authorityCertIssuer)])];z.push(E0.create(E0.Class.CONTEXT_SPECIFIC,1,!0,W))}if(J.serialNumber){var H=Q6.util.hexToBytes(J.serialNumber===!0?Z.cert.serialNumber:J.serialNumber);z.push(E0.create(E0.Class.CONTEXT_SPECIFIC,2,!1,H))}}else if(J.name==="cRLDistributionPoints"){J.value=E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[]);var z=J.value.value,B=E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[]),w=E0.create(E0.Class.CONTEXT_SPECIFIC,0,!0,[]),F;for(var U=0;U<J.altNames.length;++U){F=J.altNames[U];var K=F.value;if(F.type===7&&F.ip){if(K=Q6.util.bytesFromIP(F.ip),K===null){var Q=Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');throw Q.extension=J,Q}}else if(F.type===8)if(F.oid)K=E0.oidToDer(E0.oidToDer(F.oid));else K=E0.oidToDer(K);w.value.push(E0.create(E0.Class.CONTEXT_SPECIFIC,F.type,!1,K))}B.value.push(E0.create(E0.Class.CONTEXT_SPECIFIC,0,!0,[w])),z.push(B)}if(typeof J.value>"u"){var Q=Error("Extension value not specified.");throw Q.extension=J,Q}return J}function yc0(J,Z){switch(J){case f5["RSASSA-PSS"]:var Q=[];if(Z.hash.algorithmOid!==void 0)Q.push(E0.create(E0.Class.CONTEXT_SPECIFIC,0,!0,[E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[E0.create(E0.Class.UNIVERSAL,E0.Type.OID,!1,E0.oidToDer(Z.hash.algorithmOid).getBytes()),E0.create(E0.Class.UNIVERSAL,E0.Type.NULL,!1,"")])]));if(Z.mgf.algorithmOid!==void 0)Q.push(E0.create(E0.Class.CONTEXT_SPECIFIC,1,!0,[E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[E0.create(E0.Class.UNIVERSAL,E0.Type.OID,!1,E0.oidToDer(Z.mgf.algorithmOid).getBytes()),E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[E0.create(E0.Class.UNIVERSAL,E0.Type.OID,!1,E0.oidToDer(Z.mgf.hash.algorithmOid).getBytes()),E0.create(E0.Class.UNIVERSAL,E0.Type.NULL,!1,"")])])]));if(Z.saltLength!==void 0)Q.push(E0.create(E0.Class.CONTEXT_SPECIFIC,2,!0,[E0.create(E0.Class.UNIVERSAL,E0.Type.INTEGER,!1,E0.integerToDer(Z.saltLength).getBytes())]));return E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,Q);default:return E0.create(E0.Class.UNIVERSAL,E0.Type.NULL,!1,"")}}function z03(J){var Z=E0.create(E0.Class.CONTEXT_SPECIFIC,0,!0,[]);if(J.attributes.length===0)return Z;var Q=J.attributes;for(var Y=0;Y<Q.length;++Y){var X=Q[Y],V=X.value,K=E0.Type.UTF8;if("valueTagClass"in X)K=X.valueTagClass;if(K===E0.Type.UTF8)V=Q6.util.encodeUtf8(V);var z=!1;if("valueConstructed"in X)z=X.valueConstructed;var G=E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[E0.create(E0.Class.UNIVERSAL,E0.Type.OID,!1,E0.oidToDer(X.type).getBytes()),E0.create(E0.Class.UNIVERSAL,E0.Type.SET,!0,[E0.create(E0.Class.UNIVERSAL,K,z,V)])]);Z.value.push(G)}return Z}var G03=new Date("1950-01-01T00:00:00Z"),F03=new Date("2050-01-01T00:00:00Z");function DI4(J){if(J>=G03&&J<F03)return E0.create(E0.Class.UNIVERSAL,E0.Type.UTCTIME,!1,E0.dateToUtcTime(J));else return E0.create(E0.Class.UNIVERSAL,E0.Type.GENERALIZEDTIME,!1,E0.dateToGeneralizedTime(J))}e1.getTBSCertificate=function(J){var Z=DI4(J.validity.notBefore),Q=DI4(J.validity.notAfter),Y=E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[E0.create(E0.Class.CONTEXT_SPECIFIC,0,!0,[E0.create(E0.Class.UNIVERSAL,E0.Type.INTEGER,!1,E0.integerToDer(J.version).getBytes())]),E0.create(E0.Class.UNIVERSAL,E0.Type.INTEGER,!1,Q6.util.hexToBytes(J.serialNumber)),E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[E0.create(E0.Class.UNIVERSAL,E0.Type.OID,!1,E0.oidToDer(J.siginfo.algorithmOid).getBytes()),yc0(J.siginfo.algorithmOid,J.siginfo.parameters)]),U_(J.issuer),E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[Z,Q]),U_(J.subject),e1.publicKeyToAsn1(J.publicKey)]);if(J.issuer.uniqueId)Y.value.push(E0.create(E0.Class.CONTEXT_SPECIFIC,1,!0,[E0.create(E0.Class.UNIVERSAL,E0.Type.BITSTRING,!1,String.fromCharCode(0)+J.issuer.uniqueId)]));if(J.subject.uniqueId)Y.value.push(E0.create(E0.Class.CONTEXT_SPECIFIC,2,!0,[E0.create(E0.Class.UNIVERSAL,E0.Type.BITSTRING,!1,String.fromCharCode(0)+J.subject.uniqueId)]));if(J.extensions.length>0)Y.value.push(e1.certificateExtensionsToAsn1(J.extensions));return Y};e1.getCertificationRequestInfo=function(J){var Z=E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[E0.create(E0.Class.UNIVERSAL,E0.Type.INTEGER,!1,E0.integerToDer(J.version).getBytes()),U_(J.subject),e1.publicKeyToAsn1(J.publicKey),z03(J)]);return Z};e1.distinguishedNameToAsn1=function(J){return U_(J)};e1.certificateToAsn1=function(J){var Z=J.tbsCertificate||e1.getTBSCertificate(J);return E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[Z,E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[E0.create(E0.Class.UNIVERSAL,E0.Type.OID,!1,E0.oidToDer(J.signatureOid).getBytes()),yc0(J.signatureOid,J.signatureParameters)]),E0.create(E0.Class.UNIVERSAL,E0.Type.BITSTRING,!1,String.fromCharCode(0)+J.signature)])};e1.certificateExtensionsToAsn1=function(J){var Z=E0.create(E0.Class.CONTEXT_SPECIFIC,3,!0,[]),Q=E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[]);Z.value.push(Q);for(var Y=0;Y<J.length;++Y)Q.value.push(e1.certificateExtensionToAsn1(J[Y]));return Z};e1.certificateExtensionToAsn1=function(J){var Z=E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[]);if(Z.value.push(E0.create(E0.Class.UNIVERSAL,E0.Type.OID,!1,E0.oidToDer(J.id).getBytes())),J.critical)Z.value.push(E0.create(E0.Class.UNIVERSAL,E0.Type.BOOLEAN,!1,String.fromCharCode(255)));var Q=J.value;if(typeof J.value!=="string")Q=E0.toDer(Q).getBytes();return Z.value.push(E0.create(E0.Class.UNIVERSAL,E0.Type.OCTETSTRING,!1,Q)),Z};e1.certificationRequestToAsn1=function(J){var Z=J.certificationRequestInfo||e1.getCertificationRequestInfo(J);return E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[Z,E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[E0.create(E0.Class.UNIVERSAL,E0.Type.OID,!1,E0.oidToDer(J.signatureOid).getBytes()),yc0(J.signatureOid,J.signatureParameters)]),E0.create(E0.Class.UNIVERSAL,E0.Type.BITSTRING,!1,String.fromCharCode(0)+J.signature)])};e1.createCaStore=function(J){var Z={certs:{}};Z.getIssuer=function(K){var z=Q(K.issuer);return z},Z.addCertificate=function(K){if(typeof K==="string")K=Q6.pki.certificateFromPem(K);if(Y(K.subject),!Z.hasCertificate(K))if(K.subject.hash in Z.certs){var z=Z.certs[K.subject.hash];if(!Q6.util.isArray(z))z=[z];z.push(K),Z.certs[K.subject.hash]=z}else Z.certs[K.subject.hash]=K},Z.hasCertificate=function(K){if(typeof K==="string")K=Q6.pki.certificateFromPem(K);var z=Q(K.subject);if(!z)return!1;if(!Q6.util.isArray(z))z=[z];var G=E0.toDer(e1.certificateToAsn1(K)).getBytes();for(var F=0;F<z.length;++F){var U=E0.toDer(e1.certificateToAsn1(z[F])).getBytes();if(G===U)return!0}return!1},Z.listAllCertificates=function(){var K=[];for(var z in Z.certs)if(Z.certs.hasOwnProperty(z)){var G=Z.certs[z];if(!Q6.util.isArray(G))K.push(G);else for(var F=0;F<G.length;++F)K.push(G[F])}return K},Z.removeCertificate=function(K){var z;if(typeof K==="string")K=Q6.pki.certificateFromPem(K);if(Y(K.subject),!Z.hasCertificate(K))return null;var G=Q(K.subject);if(!Q6.util.isArray(G))return z=Z.certs[K.subject.hash],delete Z.certs[K.subject.hash],z;var F=E0.toDer(e1.certificateToAsn1(K)).getBytes();for(var U=0;U<G.length;++U){var q=E0.toDer(e1.certificateToAsn1(G[U])).getBytes();if(F===q)z=G[U],G.splice(U,1)}if(G.length===0)delete Z.certs[K.subject.hash];return z};function Q(K){return Y(K),Z.certs[K.hash]||null}function Y(K){if(!K.hash){var z=Q6.md.sha1.create();K.attributes=e1.RDNAttributesAsArray(U_(K),z),K.hash=z.digest().toHex()}}if(J)for(var X=0;X<J.length;++X){var V=J[X];Z.addCertificate(V)}return Z};e1.certificateError={bad_certificate:"forge.pki.BadCertificate",unsupported_certificate:"forge.pki.UnsupportedCertificate",certificate_revoked:"forge.pki.CertificateRevoked",certificate_expired:"forge.pki.CertificateExpired",certificate_unknown:"forge.pki.CertificateUnknown",unknown_ca:"forge.pki.UnknownCertificateAuthority"};e1.verifyCertificateChain=function(J,Z,Q){if(typeof Q==="function")Q={verify:Q};Q=Q||{},Z=Z.slice(0);var Y=Z.slice(0),X=Q.validityCheckDate;if(typeof X>"u")X=new Date;var V=!0,K=null,z=0;do{var G=Z.shift(),F=null,U=!1;if(X){if(X<G.validity.notBefore||X>G.validity.notAfter)K={message:"Certificate is not valid yet or has expired.",error:e1.certificateError.certificate_expired,notBefore:G.validity.notBefore,notAfter:G.validity.notAfter,now:X}}if(K===null){if(F=Z[0]||J.getIssuer(G),F===null){if(G.isIssuer(G))U=!0,F=G}if(F){var q=F;if(!Q6.util.isArray(q))q=[q];var D=!1;while(!D&&q.length>0){F=q.shift();try{D=F.verify(G)}catch(M){}}if(!D)K={message:"Certificate signature is invalid.",error:e1.certificateError.bad_certificate}}if(K===null&&(!F||U)&&!J.hasCertificate(G))K={message:"Certificate is not trusted.",error:e1.certificateError.unknown_ca}}if(K===null&&F&&!G.isIssuer(F))K={message:"Certificate issuer is invalid.",error:e1.certificateError.bad_certificate};if(K===null){var W={keyUsage:!0,basicConstraints:!0};for(var H=0;K===null&&H<G.extensions.length;++H){var B=G.extensions[H];if(B.critical&&!(B.name in W))K={message:"Certificate has an unsupported critical extension.",error:e1.certificateError.unsupported_certificate}}}if(K===null&&(!V||Z.length===0&&(!F||U))){var w=G.getExtension("basicConstraints"),N=G.getExtension("keyUsage");if(N!==null){if(!N.keyCertSign||w===null)K={message:"Certificate keyUsage or basicConstraints conflict or indicate that the certificate is not a CA. If the certificate is the only one in the chain or isn't the first then the certificate must be a valid CA.",error:e1.certificateError.bad_certificate}}if(K===null&&w!==null&&!w.cA)K={message:"Certificate basicConstraints indicates the certificate is not a CA.",error:e1.certificateError.bad_certificate};if(K===null&&N!==null&&"pathLenConstraint"in w){var O=z-1;if(O>w.pathLenConstraint)K={message:"Certificate basicConstraints pathLenConstraint violated.",error:e1.certificateError.bad_certificate}}}var E=K===null?!0:K.error,L=Q.verify?Q.verify(E,z,Y):E;if(L===!0)K=null;else{if(E===!0)K={message:"The application rejected the certificate.",error:e1.certificateError.bad_certificate};if(L||L===0){if(typeof L==="object"&&!Q6.util.isArray(L)){if(L.message)K.message=L.message;if(L.error)K.error=L.error}else if(typeof L==="string")K.error=L}throw K}V=!1,++z}while(Z.length>0);return!0}});var xc0=u((zE9,OI4)=>{var U8=J5();oV();Y_();zB();vc0();Sc0();JX();Ed();z_();c5();oJ0();var{asn1:y0,pki:B5}=U8,Md=OI4.exports=U8.pkcs12=U8.pkcs12||{},NI4={name:"ContentInfo",tagClass:y0.Class.UNIVERSAL,type:y0.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.contentType",tagClass:y0.Class.UNIVERSAL,type:y0.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:y0.Class.CONTEXT_SPECIFIC,constructed:!0,captureAsn1:"content"}]},U03={name:"PFX",tagClass:y0.Class.UNIVERSAL,type:y0.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.version",tagClass:y0.Class.UNIVERSAL,type:y0.Type.INTEGER,constructed:!1,capture:"version"},NI4,{name:"PFX.macData",tagClass:y0.Class.UNIVERSAL,type:y0.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"mac",value:[{name:"PFX.macData.mac",tagClass:y0.Class.UNIVERSAL,type:y0.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.macData.mac.digestAlgorithm",tagClass:y0.Class.UNIVERSAL,type:y0.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.macData.mac.digestAlgorithm.algorithm",tagClass:y0.Class.UNIVERSAL,type:y0.Type.OID,constructed:!1,capture:"macAlgorithm"},{name:"PFX.macData.mac.digestAlgorithm.parameters",optional:!0,tagClass:y0.Class.UNIVERSAL,captureAsn1:"macAlgorithmParameters"}]},{name:"PFX.macData.mac.digest",tagClass:y0.Class.UNIVERSAL,type:y0.Type.OCTETSTRING,constructed:!1,capture:"macDigest"}]},{name:"PFX.macData.macSalt",tagClass:y0.Class.UNIVERSAL,type:y0.Type.OCTETSTRING,constructed:!1,capture:"macSalt"},{name:"PFX.macData.iterations",tagClass:y0.Class.UNIVERSAL,type:y0.Type.INTEGER,constructed:!1,optional:!0,capture:"macIterations"}]}]},q03={name:"SafeBag",tagClass:y0.Class.UNIVERSAL,type:y0.Type.SEQUENCE,constructed:!0,value:[{name:"SafeBag.bagId",tagClass:y0.Class.UNIVERSAL,type:y0.Type.OID,constructed:!1,capture:"bagId"},{name:"SafeBag.bagValue",tagClass:y0.Class.CONTEXT_SPECIFIC,constructed:!0,captureAsn1:"bagValue"},{name:"SafeBag.bagAttributes",tagClass:y0.Class.UNIVERSAL,type:y0.Type.SET,constructed:!0,optional:!0,capture:"bagAttributes"}]},D03={name:"Attribute",tagClass:y0.Class.UNIVERSAL,type:y0.Type.SEQUENCE,constructed:!0,value:[{name:"Attribute.attrId",tagClass:y0.Class.UNIVERSAL,type:y0.Type.OID,constructed:!1,capture:"oid"},{name:"Attribute.attrValues",tagClass:y0.Class.UNIVERSAL,type:y0.Type.SET,constructed:!0,capture:"values"}]},W03={name:"CertBag",tagClass:y0.Class.UNIVERSAL,type:y0.Type.SEQUENCE,constructed:!0,value:[{name:"CertBag.certId",tagClass:y0.Class.UNIVERSAL,type:y0.Type.OID,constructed:!1,capture:"certId"},{name:"CertBag.certValue",tagClass:y0.Class.CONTEXT_SPECIFIC,constructed:!0,value:[{name:"CertBag.certValue[0]",tagClass:y0.Class.UNIVERSAL,type:y0.Class.OCTETSTRING,constructed:!1,capture:"cert"}]}]};function Ld(J,Z,Q,Y){var X=[];for(var V=0;V<J.length;V++)for(var K=0;K<J[V].safeBags.length;K++){var z=J[V].safeBags[K];if(Y!==void 0&&z.type!==Y)continue;if(Z===null){X.push(z);continue}if(z.attributes[Z]!==void 0&&z.attributes[Z].indexOf(Q)>=0)X.push(z)}return X}Md.pkcs12FromAsn1=function(J,Z,Q){if(typeof Z==="string")Q=Z,Z=!0;else if(Z===void 0)Z=!0;var Y={},X=[];if(!y0.validate(J,U03,Y,X)){var V=Error("Cannot read PKCS#12 PFX. ASN.1 object is not an PKCS#12 PFX.");throw V.errors=V,V}var K={version:Y.version.charCodeAt(0),safeContents:[],getBags:function(w){var N={},O;if("localKeyId"in w)O=w.localKeyId;else if("localKeyIdHex"in w)O=U8.util.hexToBytes(w.localKeyIdHex);if(O===void 0&&!("friendlyName"in w)&&"bagType"in w)N[w.bagType]=Ld(K.safeContents,null,null,w.bagType);if(O!==void 0)N.localKeyId=Ld(K.safeContents,"localKeyId",O,w.bagType);if("friendlyName"in w)N.friendlyName=Ld(K.safeContents,"friendlyName",w.friendlyName,w.bagType);return N},getBagsByFriendlyName:function(w,N){return Ld(K.safeContents,"friendlyName",w,N)},getBagsByLocalKeyId:function(w,N){return Ld(K.safeContents,"localKeyId",w,N)}};if(Y.version.charCodeAt(0)!==3){var V=Error("PKCS#12 PFX of version other than 3 not supported.");throw V.version=Y.version.charCodeAt(0),V}if(y0.derToOid(Y.contentType)!==B5.oids.data){var V=Error("Only PKCS#12 PFX in password integrity mode supported.");throw V.oid=y0.derToOid(Y.contentType),V}var z=Y.content.value[0];if(z.tagClass!==y0.Class.UNIVERSAL||z.type!==y0.Type.OCTETSTRING)throw Error("PKCS#12 authSafe content data is not an OCTET STRING.");if(z=uc0(z),Y.mac){var G=null,F=0,U=y0.derToOid(Y.macAlgorithm);switch(U){case B5.oids.sha1:G=U8.md.sha1.create(),F=20;break;case B5.oids.sha256:G=U8.md.sha256.create(),F=32;break;case B5.oids.sha384:G=U8.md.sha384.create(),F=48;break;case B5.oids.sha512:G=U8.md.sha512.create(),F=64;break;case B5.oids.md5:G=U8.md.md5.create(),F=16;break}if(G===null)throw Error("PKCS#12 uses unsupported MAC algorithm: "+U);var q=new U8.util.ByteBuffer(Y.macSalt),D="macIterations"in Y?parseInt(U8.util.bytesToHex(Y.macIterations),16):1,W=Md.generateKey(Q,q,3,D,F,G),H=U8.hmac.create();H.start(G,W),H.update(z.value);var B=H.getMac();if(B.getBytes()!==Y.macDigest)throw Error("PKCS#12 MAC could not be verified. Invalid password?")}else if(Array.isArray(J.value)&&J.value.length>2)throw Error("Invalid PKCS#12. macData field present but MAC was not validated.");return H03(K,z.value,Z,Q),K};function uc0(J){if(J.composed||J.constructed){var Z=U8.util.createBuffer();for(var Q=0;Q<J.value.length;++Q)Z.putBytes(J.value[Q].value);J.composed=J.constructed=!1,J.value=Z.getBytes()}return J}function H03(J,Z,Q,Y){if(Z=y0.fromDer(Z,Q),Z.tagClass!==y0.Class.UNIVERSAL||Z.type!==y0.Type.SEQUENCE||Z.constructed!==!0)throw Error("PKCS#12 AuthenticatedSafe expected to be a SEQUENCE OF ContentInfo");for(var X=0;X<Z.value.length;X++){var V=Z.value[X],K={},z=[];if(!y0.validate(V,NI4,K,z)){var G=Error("Cannot read ContentInfo.");throw G.errors=z,G}var F={encrypted:!1},U=null,q=K.content.value[0];switch(y0.derToOid(K.contentType)){case B5.oids.data:if(q.tagClass!==y0.Class.UNIVERSAL||q.type!==y0.Type.OCTETSTRING)throw Error("PKCS#12 SafeContents Data is not an OCTET STRING.");U=uc0(q).value;break;case B5.oids.encryptedData:U=B03(q,Y),F.encrypted=!0;break;default:var G=Error("Unsupported PKCS#12 contentType.");throw G.contentType=y0.derToOid(K.contentType),G}F.safeBags=w03(U,Q,Y),J.safeContents.push(F)}}function B03(J,Z){var Q={},Y=[];if(!y0.validate(J,U8.pkcs7.asn1.encryptedDataValidator,Q,Y)){var X=Error("Cannot read EncryptedContentInfo.");throw X.errors=Y,X}var V=y0.derToOid(Q.contentType);if(V!==B5.oids.data){var X=Error("PKCS#12 EncryptedContentInfo ContentType is not Data.");throw X.oid=V,X}V=y0.derToOid(Q.encAlgorithm);var K=B5.pbe.getCipher(V,Q.encParameter,Z),z=uc0(Q.encryptedContentAsn1),G=U8.util.createBuffer(z.value);if(K.update(G),!K.finish())throw Error("Failed to decrypt PKCS#12 SafeContents.");return K.output.getBytes()}function w03(J,Z,Q){if(!Z&&J.length===0)return[];if(J=y0.fromDer(J,Z),J.tagClass!==y0.Class.UNIVERSAL||J.type!==y0.Type.SEQUENCE||J.constructed!==!0)throw Error("PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag.");var Y=[];for(var X=0;X<J.value.length;X++){var V=J.value[X],K={},z=[];if(!y0.validate(V,q03,K,z)){var G=Error("Cannot read SafeBag.");throw G.errors=z,G}var F={type:y0.derToOid(K.bagId),attributes:N03(K.bagAttributes)};Y.push(F);var U,q,D=K.bagValue.value[0];switch(F.type){case B5.oids.pkcs8ShroudedKeyBag:if(D=B5.decryptPrivateKeyInfo(D,Q),D===null)throw Error("Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?");case B5.oids.keyBag:try{F.key=B5.privateKeyFromAsn1(D)}catch(H){F.key=null,F.asn1=D}continue;case B5.oids.certBag:U=W03,q=function(){if(y0.derToOid(K.certId)!==B5.oids.x509Certificate){var H=Error("Unsupported certificate type, only X.509 supported.");throw H.oid=y0.derToOid(K.certId),H}var B=y0.fromDer(K.cert,Z);try{F.cert=B5.certificateFromAsn1(B,!0)}catch(w){F.cert=null,F.asn1=B}};break;default:var G=Error("Unsupported PKCS#12 SafeBag type.");throw G.oid=F.type,G}if(U!==void 0&&!y0.validate(D,U,K,z)){var G=Error("Cannot read PKCS#12 "+U.name);throw G.errors=z,G}q()}return Y}function N03(J){var Z={};if(J!==void 0)for(var Q=0;Q<J.length;++Q){var Y={},X=[];if(!y0.validate(J[Q],D03,Y,X)){var V=Error("Cannot read PKCS#12 BagAttribute.");throw V.errors=X,V}var K=y0.derToOid(Y.oid);if(B5.oids[K]===void 0)continue;Z[B5.oids[K]]=[];for(var z=0;z<Y.values.length;++z)Z[B5.oids[K]].push(Y.values[z].value)}return Z}Md.toPkcs12Asn1=function(J,Z,Q,Y){if(Y=Y||{},Y.saltSize=Y.saltSize||8,Y.count=Y.count||2048,Y.algorithm=Y.algorithm||Y.encAlgorithm||"aes128",!("useMac"in Y))Y.useMac=!0;if(!("localKeyId"in Y))Y.localKeyId=null;if(!("generateLocalKeyId"in Y))Y.generateLocalKeyId=!0;var X=Y.localKeyId,V;if(X!==null)X=U8.util.hexToBytes(X);else if(Y.generateLocalKeyId)if(Z){var K=U8.util.isArray(Z)?Z[0]:Z;if(typeof K==="string")K=B5.certificateFromPem(K);var z=U8.md.sha1.create();z.update(y0.toDer(B5.certificateToAsn1(K)).getBytes()),X=z.digest().getBytes()}else X=U8.random.getBytes(20);var G=[];if(X!==null)G.push(y0.create(y0.Class.UNIVERSAL,y0.Type.SEQUENCE,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.OID,!1,y0.oidToDer(B5.oids.localKeyId).getBytes()),y0.create(y0.Class.UNIVERSAL,y0.Type.SET,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.OCTETSTRING,!1,X)])]));if("friendlyName"in Y)G.push(y0.create(y0.Class.UNIVERSAL,y0.Type.SEQUENCE,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.OID,!1,y0.oidToDer(B5.oids.friendlyName).getBytes()),y0.create(y0.Class.UNIVERSAL,y0.Type.SET,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.BMPSTRING,!1,Y.friendlyName)])]));if(G.length>0)V=y0.create(y0.Class.UNIVERSAL,y0.Type.SET,!0,G);var F=[],U=[];if(Z!==null)if(U8.util.isArray(Z))U=Z;else U=[Z];var q=[];for(var D=0;D<U.length;++D){if(Z=U[D],typeof Z==="string")Z=B5.certificateFromPem(Z);var W=D===0?V:void 0,H=B5.certificateToAsn1(Z),B=y0.create(y0.Class.UNIVERSAL,y0.Type.SEQUENCE,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.OID,!1,y0.oidToDer(B5.oids.certBag).getBytes()),y0.create(y0.Class.CONTEXT_SPECIFIC,0,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.SEQUENCE,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.OID,!1,y0.oidToDer(B5.oids.x509Certificate).getBytes()),y0.create(y0.Class.CONTEXT_SPECIFIC,0,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.OCTETSTRING,!1,y0.toDer(H).getBytes())])])]),W]);q.push(B)}if(q.length>0){var w=y0.create(y0.Class.UNIVERSAL,y0.Type.SEQUENCE,!0,q),N=y0.create(y0.Class.UNIVERSAL,y0.Type.SEQUENCE,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.OID,!1,y0.oidToDer(B5.oids.data).getBytes()),y0.create(y0.Class.CONTEXT_SPECIFIC,0,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.OCTETSTRING,!1,y0.toDer(w).getBytes())])]);F.push(N)}var O=null;if(J!==null){var E=B5.wrapRsaPrivateKey(B5.privateKeyToAsn1(J));if(Q===null)O=y0.create(y0.Class.UNIVERSAL,y0.Type.SEQUENCE,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.OID,!1,y0.oidToDer(B5.oids.keyBag).getBytes()),y0.create(y0.Class.CONTEXT_SPECIFIC,0,!0,[E]),V]);else O=y0.create(y0.Class.UNIVERSAL,y0.Type.SEQUENCE,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.OID,!1,y0.oidToDer(B5.oids.pkcs8ShroudedKeyBag).getBytes()),y0.create(y0.Class.CONTEXT_SPECIFIC,0,!0,[B5.encryptPrivateKeyInfo(E,Q,Y)]),V]);var L=y0.create(y0.Class.UNIVERSAL,y0.Type.SEQUENCE,!0,[O]),M=y0.create(y0.Class.UNIVERSAL,y0.Type.SEQUENCE,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.OID,!1,y0.oidToDer(B5.oids.data).getBytes()),y0.create(y0.Class.CONTEXT_SPECIFIC,0,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.OCTETSTRING,!1,y0.toDer(L).getBytes())])]);F.push(M)}var A=y0.create(y0.Class.UNIVERSAL,y0.Type.SEQUENCE,!0,F),I;if(Y.useMac){var z=U8.md.sha1.create(),P=new U8.util.ByteBuffer(U8.random.getBytes(Y.saltSize)),_=Y.count,J=Md.generateKey(Q,P,3,_,20),S=U8.hmac.create();S.start(z,J),S.update(y0.toDer(A).getBytes());var y=S.getMac();I=y0.create(y0.Class.UNIVERSAL,y0.Type.SEQUENCE,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.SEQUENCE,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.SEQUENCE,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.OID,!1,y0.oidToDer(B5.oids.sha1).getBytes()),y0.create(y0.Class.UNIVERSAL,y0.Type.NULL,!1,"")]),y0.create(y0.Class.UNIVERSAL,y0.Type.OCTETSTRING,!1,y.getBytes())]),y0.create(y0.Class.UNIVERSAL,y0.Type.OCTETSTRING,!1,P.getBytes()),y0.create(y0.Class.UNIVERSAL,y0.Type.INTEGER,!1,y0.integerToDer(_).getBytes())])}return y0.create(y0.Class.UNIVERSAL,y0.Type.SEQUENCE,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.INTEGER,!1,y0.integerToDer(3).getBytes()),y0.create(y0.Class.UNIVERSAL,y0.Type.SEQUENCE,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.OID,!1,y0.oidToDer(B5.oids.data).getBytes()),y0.create(y0.Class.CONTEXT_SPECIFIC,0,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.OCTETSTRING,!1,y0.toDer(A).getBytes())])]),I])};Md.generateKey=U8.pbe.generatePkcs12Key});var bc0=u((GE9,EI4)=>{var qB=J5();oV();zB();Sc0();lL();hJ0();xc0();iJ0();Ed();c5();oJ0();var fc0=qB.asn1,q_=EI4.exports=qB.pki=qB.pki||{};q_.pemToDer=function(J){var Z=qB.pem.decode(J)[0];if(Z.procType&&Z.procType.type==="ENCRYPTED")throw Error("Could not convert PEM to DER; PEM is encrypted.");return qB.util.createBuffer(Z.body)};q_.privateKeyFromPem=function(J){var Z=qB.pem.decode(J)[0];if(Z.type!=="PRIVATE KEY"&&Z.type!=="RSA PRIVATE KEY"){var Q=Error('Could not convert private key from PEM; PEM header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".');throw Q.headerType=Z.type,Q}if(Z.procType&&Z.procType.type==="ENCRYPTED")throw Error("Could not convert private key from PEM; PEM is encrypted.");var Y=fc0.fromDer(Z.body);return q_.privateKeyFromAsn1(Y)};q_.privateKeyToPem=function(J,Z){var Q={type:"RSA PRIVATE KEY",body:fc0.toDer(q_.privateKeyToAsn1(J)).getBytes()};return qB.pem.encode(Q,{maxline:Z})};q_.privateKeyInfoToPem=function(J,Z){var Q={type:"PRIVATE KEY",body:fc0.toDer(J).getBytes()};return qB.pem.encode(Q,{maxline:Z})}});var cc0=u((FE9,CI4)=>{var S1=J5();oV();Y_();uJ0();lL();bc0();JX();z_();c5();var tJ0=function(J,Z,Q,Y){var X=S1.util.createBuffer(),V=J.length>>1,K=V+(J.length&1),z=J.substr(0,K),G=J.substr(V,K),F=S1.util.createBuffer(),U=S1.hmac.create();Q=Z+Q;var q=Math.ceil(Y/16),D=Math.ceil(Y/20);U.start("MD5",z);var W=S1.util.createBuffer();F.putBytes(Q);for(var H=0;H<q;++H)U.start(null,null),U.update(F.getBytes()),F.putBuffer(U.digest()),U.start(null,null),U.update(F.bytes()+Q),W.putBuffer(U.digest());U.start("SHA1",G);var B=S1.util.createBuffer();F.clear(),F.putBytes(Q);for(var H=0;H<D;++H)U.start(null,null),U.update(F.getBytes()),F.putBuffer(U.digest()),U.start(null,null),U.update(F.bytes()+Q),B.putBuffer(U.digest());return X.putBytes(S1.util.xorBytes(W.getBytes(),B.getBytes(),Y)),X},O03=function(J,Z,Q){var Y=S1.hmac.create();Y.start("SHA1",J);var X=S1.util.createBuffer();return X.putInt32(Z[0]),X.putInt32(Z[1]),X.putByte(Q.type),X.putByte(Q.version.major),X.putByte(Q.version.minor),X.putInt16(Q.length),X.putBytes(Q.fragment.bytes()),Y.update(X.getBytes()),Y.digest().getBytes()},E03=function(J,Z,Q){var Y=!1;try{var X=J.deflate(Z.fragment.getBytes());Z.fragment=S1.util.createBuffer(X),Z.length=X.length,Y=!0}catch(V){}return Y},L03=function(J,Z,Q){var Y=!1;try{var X=J.inflate(Z.fragment.getBytes());Z.fragment=S1.util.createBuffer(X),Z.length=X.length,Y=!0}catch(V){}return Y},TQ=function(J,Z){var Q=0;switch(Z){case 1:Q=J.getByte();break;case 2:Q=J.getInt16();break;case 3:Q=J.getInt24();break;case 4:Q=J.getInt32();break}return S1.util.createBuffer(J.getBytes(Q))},XX=function(J,Z,Q){J.putInt(Q.length(),Z<<3),J.putBuffer(Q)},A0={};A0.Versions={TLS_1_0:{major:3,minor:1},TLS_1_1:{major:3,minor:2},TLS_1_2:{major:3,minor:3}};A0.SupportedVersions=[A0.Versions.TLS_1_1,A0.Versions.TLS_1_0];A0.Version=A0.SupportedVersions[0];A0.MaxFragment=15360;A0.ConnectionEnd={server:0,client:1};A0.PRFAlgorithm={tls_prf_sha256:0};A0.BulkCipherAlgorithm={none:null,rc4:0,des3:1,aes:2};A0.CipherType={stream:0,block:1,aead:2};A0.MACAlgorithm={none:null,hmac_md5:0,hmac_sha1:1,hmac_sha256:2,hmac_sha384:3,hmac_sha512:4};A0.CompressionMethod={none:0,deflate:1};A0.ContentType={change_cipher_spec:20,alert:21,handshake:22,application_data:23,heartbeat:24};A0.HandshakeType={hello_request:0,client_hello:1,server_hello:2,certificate:11,server_key_exchange:12,certificate_request:13,server_hello_done:14,certificate_verify:15,client_key_exchange:16,finished:20};A0.Alert={};A0.Alert.Level={warning:1,fatal:2};A0.Alert.Description={close_notify:0,unexpected_message:10,bad_record_mac:20,decryption_failed:21,record_overflow:22,decompression_failure:30,handshake_failure:40,bad_certificate:42,unsupported_certificate:43,certificate_revoked:44,certificate_expired:45,certificate_unknown:46,illegal_parameter:47,unknown_ca:48,access_denied:49,decode_error:50,decrypt_error:51,export_restriction:60,protocol_version:70,insufficient_security:71,internal_error:80,user_canceled:90,no_renegotiation:100};A0.HeartbeatMessageType={heartbeat_request:1,heartbeat_response:2};A0.CipherSuites={};A0.getCipherSuite=function(J){var Z=null;for(var Q in A0.CipherSuites){var Y=A0.CipherSuites[Q];if(Y.id[0]===J.charCodeAt(0)&&Y.id[1]===J.charCodeAt(1)){Z=Y;break}}return Z};A0.handleUnexpected=function(J,Z){var Q=!J.open&&J.entity===A0.ConnectionEnd.client;if(!Q)J.error(J,{message:"Unexpected message. Received TLS record out of order.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.unexpected_message}})};A0.handleHelloRequest=function(J,Z,Q){if(!J.handshaking&&J.handshakes>0)A0.queue(J,A0.createAlert(J,{level:A0.Alert.Level.warning,description:A0.Alert.Description.no_renegotiation})),A0.flush(J);J.process()};A0.parseHelloMessage=function(J,Z,Q){var Y=null,X=J.entity===A0.ConnectionEnd.client;if(Q<38)J.error(J,{message:X?"Invalid ServerHello message. Message too short.":"Invalid ClientHello message. Message too short.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.illegal_parameter}});else{var V=Z.fragment,K=V.length();if(Y={version:{major:V.getByte(),minor:V.getByte()},random:S1.util.createBuffer(V.getBytes(32)),session_id:TQ(V,1),extensions:[]},X)Y.cipher_suite=V.getBytes(2),Y.compression_method=V.getByte();else Y.cipher_suites=TQ(V,2),Y.compression_methods=TQ(V,1);if(K=Q-(K-V.length()),K>0){var z=TQ(V,2);while(z.length()>0)Y.extensions.push({type:[z.getByte(),z.getByte()],data:TQ(z,2)});if(!X)for(var G=0;G<Y.extensions.length;++G){var F=Y.extensions[G];if(F.type[0]===0&&F.type[1]===0){var U=TQ(F.data,2);while(U.length()>0){var q=U.getByte();if(q!==0)break;J.session.extensions.server_name.serverNameList.push(TQ(U,2).getBytes())}}}}if(J.session.version){if(Y.version.major!==J.session.version.major||Y.version.minor!==J.session.version.minor)return J.error(J,{message:"TLS version change is disallowed during renegotiation.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.protocol_version}})}if(X)J.session.cipherSuite=A0.getCipherSuite(Y.cipher_suite);else{var D=S1.util.createBuffer(Y.cipher_suites.bytes());while(D.length()>0)if(J.session.cipherSuite=A0.getCipherSuite(D.getBytes(2)),J.session.cipherSuite!==null)break}if(J.session.cipherSuite===null)return J.error(J,{message:"No cipher suites in common.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.handshake_failure},cipherSuite:S1.util.bytesToHex(Y.cipher_suite)});if(X)J.session.compressionMethod=Y.compression_method;else J.session.compressionMethod=A0.CompressionMethod.none}return Y};A0.createSecurityParameters=function(J,Z){var Q=J.entity===A0.ConnectionEnd.client,Y=Z.random.bytes(),X=Q?J.session.sp.client_random:Y,V=Q?Y:A0.createRandom().getBytes();J.session.sp={entity:J.entity,prf_algorithm:A0.PRFAlgorithm.tls_prf_sha256,bulk_cipher_algorithm:null,cipher_type:null,enc_key_length:null,block_length:null,fixed_iv_length:null,record_iv_length:null,mac_algorithm:null,mac_length:null,mac_key_length:null,compression_algorithm:J.session.compressionMethod,pre_master_secret:null,master_secret:null,client_random:X,server_random:V}};A0.handleServerHello=function(J,Z,Q){var Y=A0.parseHelloMessage(J,Z,Q);if(J.fail)return;if(Y.version.minor<=J.version.minor)J.version.minor=Y.version.minor;else return J.error(J,{message:"Incompatible TLS version.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.protocol_version}});J.session.version=J.version;var X=Y.session_id.bytes();if(X.length>0&&X===J.session.id)J.expect=AI4,J.session.resuming=!0,J.session.sp.server_random=Y.random.bytes();else J.expect=A03,J.session.resuming=!1,A0.createSecurityParameters(J,Y);J.session.id=X,J.process()};A0.handleClientHello=function(J,Z,Q){var Y=A0.parseHelloMessage(J,Z,Q);if(J.fail)return;var X=Y.session_id.bytes(),V=null;if(J.sessionCache){if(V=J.sessionCache.getSession(X),V===null)X="";else if(V.version.major!==Y.version.major||V.version.minor>Y.version.minor)V=null,X=""}if(X.length===0)X=S1.random.getBytes(32);if(J.session.id=X,J.session.clientHelloVersion=Y.version,J.session.sp={},V)J.version=J.session.version=V.version,J.session.sp=V.sp;else{var K;for(var z=1;z<A0.SupportedVersions.length;++z)if(K=A0.SupportedVersions[z],K.minor<=Y.version.minor)break;J.version={major:K.major,minor:K.minor},J.session.version=J.version}if(V!==null)J.expect=pc0,J.session.resuming=!0,J.session.sp.client_random=Y.random.bytes();else J.expect=J.verifyClient!==!1?_03:gc0,J.session.resuming=!1,A0.createSecurityParameters(J,Y);if(J.open=!0,A0.queue(J,A0.createRecord(J,{type:A0.ContentType.handshake,data:A0.createServerHello(J)})),J.session.resuming)A0.queue(J,A0.createRecord(J,{type:A0.ContentType.change_cipher_spec,data:A0.createChangeCipherSpec()})),J.state.pending=A0.createConnectionState(J),J.state.current.write=J.state.pending.write,A0.queue(J,A0.createRecord(J,{type:A0.ContentType.handshake,data:A0.createFinished(J)}));else if(A0.queue(J,A0.createRecord(J,{type:A0.ContentType.handshake,data:A0.createCertificate(J)})),!J.fail){if(A0.queue(J,A0.createRecord(J,{type:A0.ContentType.handshake,data:A0.createServerKeyExchange(J)})),J.verifyClient!==!1)A0.queue(J,A0.createRecord(J,{type:A0.ContentType.handshake,data:A0.createCertificateRequest(J)}));A0.queue(J,A0.createRecord(J,{type:A0.ContentType.handshake,data:A0.createServerHelloDone(J)}))}A0.flush(J),J.process()};A0.handleCertificate=function(J,Z,Q){if(Q<3)return J.error(J,{message:"Invalid Certificate message. Message too short.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.illegal_parameter}});var Y=Z.fragment,X={certificate_list:TQ(Y,3)},V,K,z=[];try{while(X.certificate_list.length()>0)V=TQ(X.certificate_list,3),K=S1.asn1.fromDer(V),V=S1.pki.certificateFromAsn1(K,!0),z.push(V)}catch(F){return J.error(J,{message:"Could not parse certificate list.",cause:F,send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.bad_certificate}})}var G=J.entity===A0.ConnectionEnd.client;if((G||J.verifyClient===!0)&&z.length===0)J.error(J,{message:G?"No server certificate provided.":"No client certificate provided.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.illegal_parameter}});else if(z.length===0)J.expect=G?LI4:gc0;else{if(G)J.session.serverCertificate=z[0];else J.session.clientCertificate=z[0];if(A0.verifyCertificateChain(J,z))J.expect=G?LI4:gc0}J.process()};A0.handleServerKeyExchange=function(J,Z,Q){if(Q>0)return J.error(J,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.unsupported_certificate}});J.expect=I03,J.process()};A0.handleClientKeyExchange=function(J,Z,Q){if(Q<48)return J.error(J,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.unsupported_certificate}});var Y=Z.fragment,X={enc_pre_master_secret:TQ(Y,2).getBytes()},V=null;if(J.getPrivateKey)try{V=J.getPrivateKey(J,J.session.serverCertificate),V=S1.pki.privateKeyFromPem(V)}catch(G){J.error(J,{message:"Could not get private key.",cause:G,send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.internal_error}})}if(V===null)return J.error(J,{message:"No private key set.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.internal_error}});try{var K=J.session.sp;K.pre_master_secret=V.decrypt(X.enc_pre_master_secret);var z=J.session.clientHelloVersion;if(z.major!==K.pre_master_secret.charCodeAt(0)||z.minor!==K.pre_master_secret.charCodeAt(1))throw Error("TLS version rollback attack detected.")}catch(G){K.pre_master_secret=S1.random.getBytes(48)}if(J.expect=pc0,J.session.clientCertificate!==null)J.expect=S03;J.process()};A0.handleCertificateRequest=function(J,Z,Q){if(Q<3)return J.error(J,{message:"Invalid CertificateRequest. Message too short.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.illegal_parameter}});var Y=Z.fragment,X={certificate_types:TQ(Y,1),certificate_authorities:TQ(Y,2)};J.session.certificateRequest=X,J.expect=j03,J.process()};A0.handleCertificateVerify=function(J,Z,Q){if(Q<2)return J.error(J,{message:"Invalid CertificateVerify. Message too short.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.illegal_parameter}});var Y=Z.fragment;Y.read-=4;var X=Y.bytes();Y.read+=4;var V={signature:TQ(Y,2).getBytes()},K=S1.util.createBuffer();K.putBuffer(J.session.md5.digest()),K.putBuffer(J.session.sha1.digest()),K=K.getBytes();try{var z=J.session.clientCertificate;if(!z.publicKey.verify(K,V.signature,"NONE"))throw Error("CertificateVerify signature does not match.");J.session.md5.update(X),J.session.sha1.update(X)}catch(G){return J.error(J,{message:"Bad signature in CertificateVerify.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.handshake_failure}})}J.expect=pc0,J.process()};A0.handleServerHelloDone=function(J,Z,Q){if(Q>0)return J.error(J,{message:"Invalid ServerHelloDone message. Invalid length.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.record_overflow}});if(J.serverCertificate===null){var Y={message:"No server certificate provided. Not enough security.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.insufficient_security}},X=0,V=J.verify(J,Y.alert.description,X,[]);if(V!==!0){if(V||V===0){if(typeof V==="object"&&!S1.util.isArray(V)){if(V.message)Y.message=V.message;if(V.alert)Y.alert.description=V.alert}else if(typeof V==="number")Y.alert.description=V}return J.error(J,Y)}}if(J.session.certificateRequest!==null)Z=A0.createRecord(J,{type:A0.ContentType.handshake,data:A0.createCertificate(J)}),A0.queue(J,Z);Z=A0.createRecord(J,{type:A0.ContentType.handshake,data:A0.createClientKeyExchange(J)}),A0.queue(J,Z),J.expect=C03;var K=function(z,G){if(z.session.certificateRequest!==null&&z.session.clientCertificate!==null)A0.queue(z,A0.createRecord(z,{type:A0.ContentType.handshake,data:A0.createCertificateVerify(z,G)}));A0.queue(z,A0.createRecord(z,{type:A0.ContentType.change_cipher_spec,data:A0.createChangeCipherSpec()})),z.state.pending=A0.createConnectionState(z),z.state.current.write=z.state.pending.write,A0.queue(z,A0.createRecord(z,{type:A0.ContentType.handshake,data:A0.createFinished(z)})),z.expect=AI4,A0.flush(z),z.process()};if(J.session.certificateRequest===null||J.session.clientCertificate===null)return K(J,null);A0.getClientSignature(J,K)};A0.handleChangeCipherSpec=function(J,Z){if(Z.fragment.getByte()!==1)return J.error(J,{message:"Invalid ChangeCipherSpec message received.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.illegal_parameter}});var Q=J.entity===A0.ConnectionEnd.client;if(J.session.resuming&&Q||!J.session.resuming&&!Q)J.state.pending=A0.createConnectionState(J);if(J.state.current.read=J.state.pending.read,!J.session.resuming&&Q||J.session.resuming&&!Q)J.state.pending=null;J.expect=Q?R03:v03,J.process()};A0.handleFinished=function(J,Z,Q){var Y=Z.fragment;Y.read-=4;var X=Y.bytes();Y.read+=4;var V=Z.fragment.getBytes();Y=S1.util.createBuffer(),Y.putBuffer(J.session.md5.digest()),Y.putBuffer(J.session.sha1.digest());var K=J.entity===A0.ConnectionEnd.client,z=K?"server finished":"client finished",G=J.session.sp,F=12,U=tJ0;if(Y=U(G.master_secret,z,Y.getBytes(),F),Y.getBytes()!==V)return J.error(J,{message:"Invalid verify_data in Finished message.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.decrypt_error}});if(J.session.md5.update(X),J.session.sha1.update(X),J.session.resuming&&K||!J.session.resuming&&!K)A0.queue(J,A0.createRecord(J,{type:A0.ContentType.change_cipher_spec,data:A0.createChangeCipherSpec()})),J.state.current.write=J.state.pending.write,J.state.pending=null,A0.queue(J,A0.createRecord(J,{type:A0.ContentType.handshake,data:A0.createFinished(J)}));J.expect=K?P03:k03,J.handshaking=!1,++J.handshakes,J.peerCertificate=K?J.session.serverCertificate:J.session.clientCertificate,A0.flush(J),J.isConnected=!0,J.connected(J),J.process()};A0.handleAlert=function(J,Z){var Q=Z.fragment,Y={level:Q.getByte(),description:Q.getByte()},X;switch(Y.description){case A0.Alert.Description.close_notify:X="Connection closed.";break;case A0.Alert.Description.unexpected_message:X="Unexpected message.";break;case A0.Alert.Description.bad_record_mac:X="Bad record MAC.";break;case A0.Alert.Description.decryption_failed:X="Decryption failed.";break;case A0.Alert.Description.record_overflow:X="Record overflow.";break;case A0.Alert.Description.decompression_failure:X="Decompression failed.";break;case A0.Alert.Description.handshake_failure:X="Handshake failure.";break;case A0.Alert.Description.bad_certificate:X="Bad certificate.";break;case A0.Alert.Description.unsupported_certificate:X="Unsupported certificate.";break;case A0.Alert.Description.certificate_revoked:X="Certificate revoked.";break;case A0.Alert.Description.certificate_expired:X="Certificate expired.";break;case A0.Alert.Description.certificate_unknown:X="Certificate unknown.";break;case A0.Alert.Description.illegal_parameter:X="Illegal parameter.";break;case A0.Alert.Description.unknown_ca:X="Unknown certificate authority.";break;case A0.Alert.Description.access_denied:X="Access denied.";break;case A0.Alert.Description.decode_error:X="Decode error.";break;case A0.Alert.Description.decrypt_error:X="Decrypt error.";break;case A0.Alert.Description.export_restriction:X="Export restriction.";break;case A0.Alert.Description.protocol_version:X="Unsupported protocol version.";break;case A0.Alert.Description.insufficient_security:X="Insufficient security.";break;case A0.Alert.Description.internal_error:X="Internal error.";break;case A0.Alert.Description.user_canceled:X="User canceled.";break;case A0.Alert.Description.no_renegotiation:X="Renegotiation not supported.";break;default:X="Unknown error.";break}if(Y.description===A0.Alert.Description.close_notify)return J.close();J.error(J,{message:X,send:!1,origin:J.entity===A0.ConnectionEnd.client?"server":"client",alert:Y}),J.process()};A0.handleHandshake=function(J,Z){var Q=Z.fragment,Y=Q.getByte(),X=Q.getInt24();if(X>Q.length())return J.fragmented=Z,Z.fragment=S1.util.createBuffer(),Q.read-=4,J.process();J.fragmented=null,Q.read-=4;var V=Q.bytes(X+4);if(Q.read+=4,Y in sJ0[J.entity][J.expect]){if(J.entity===A0.ConnectionEnd.server&&!J.open&&!J.fail)J.handshaking=!0,J.session={version:null,extensions:{server_name:{serverNameList:[]}},cipherSuite:null,compressionMethod:null,serverCertificate:null,clientCertificate:null,md5:S1.md.md5.create(),sha1:S1.md.sha1.create()};if(Y!==A0.HandshakeType.hello_request&&Y!==A0.HandshakeType.certificate_verify&&Y!==A0.HandshakeType.finished)J.session.md5.update(V),J.session.sha1.update(V);sJ0[J.entity][J.expect][Y](J,Z,X)}else A0.handleUnexpected(J,Z)};A0.handleApplicationData=function(J,Z){J.data.putBuffer(Z.fragment),J.dataReady(J),J.process()};A0.handleHeartbeat=function(J,Z){var Q=Z.fragment,Y=Q.getByte(),X=Q.getInt16(),V=Q.getBytes(X);if(Y===A0.HeartbeatMessageType.heartbeat_request){if(J.handshaking||X>V.length)return J.process();A0.queue(J,A0.createRecord(J,{type:A0.ContentType.heartbeat,data:A0.createHeartbeat(A0.HeartbeatMessageType.heartbeat_response,V)})),A0.flush(J)}else if(Y===A0.HeartbeatMessageType.heartbeat_response){if(V!==J.expectedHeartbeatPayload)return J.process();if(J.heartbeatReceived)J.heartbeatReceived(J,S1.util.createBuffer(V))}J.process()};var M03=0,A03=1,LI4=2,I03=3,j03=4,AI4=5,R03=6,P03=7,C03=8,T03=0,_03=1,gc0=2,S03=3,pc0=4,v03=5,k03=6,L0=A0.handleUnexpected,II4=A0.handleChangeCipherSpec,v2=A0.handleAlert,HJ=A0.handleHandshake,jI4=A0.handleApplicationData,k2=A0.handleHeartbeat,dc0=[];dc0[A0.ConnectionEnd.client]=[[L0,v2,HJ,L0,k2],[L0,v2,HJ,L0,k2],[L0,v2,HJ,L0,k2],[L0,v2,HJ,L0,k2],[L0,v2,HJ,L0,k2],[II4,v2,L0,L0,k2],[L0,v2,HJ,L0,k2],[L0,v2,HJ,jI4,k2],[L0,v2,HJ,L0,k2]];dc0[A0.ConnectionEnd.server]=[[L0,v2,HJ,L0,k2],[L0,v2,HJ,L0,k2],[L0,v2,HJ,L0,k2],[L0,v2,HJ,L0,k2],[II4,v2,L0,L0,k2],[L0,v2,HJ,L0,k2],[L0,v2,HJ,jI4,k2],[L0,v2,HJ,L0,k2]];var{handleHelloRequest:DB,handleServerHello:y03,handleCertificate:RI4,handleServerKeyExchange:MI4,handleCertificateRequest:hc0,handleServerHelloDone:rJ0,handleFinished:PI4}=A0,sJ0=[];sJ0[A0.ConnectionEnd.client]=[[L0,L0,y03,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0],[DB,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,RI4,MI4,hc0,rJ0,L0,L0,L0,L0,L0,L0],[DB,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,MI4,hc0,rJ0,L0,L0,L0,L0,L0,L0],[DB,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,hc0,rJ0,L0,L0,L0,L0,L0,L0],[DB,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,rJ0,L0,L0,L0,L0,L0,L0],[DB,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0],[DB,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,PI4],[DB,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0],[DB,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0]];var{handleClientHello:u03,handleClientKeyExchange:x03,handleCertificateVerify:f03}=A0;sJ0[A0.ConnectionEnd.server]=[[L0,u03,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0],[L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,RI4,L0,L0,L0,L0,L0,L0,L0,L0,L0],[L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,x03,L0,L0,L0,L0],[L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,f03,L0,L0,L0,L0,L0],[L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0],[L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,PI4],[L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0],[L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0]];A0.generateKeys=function(J,Z){var Q=tJ0,Y=Z.client_random+Z.server_random;if(!J.session.resuming)Z.master_secret=Q(Z.pre_master_secret,"master secret",Y,48).bytes(),Z.pre_master_secret=null;Y=Z.server_random+Z.client_random;var X=2*Z.mac_key_length+2*Z.enc_key_length,V=J.version.major===A0.Versions.TLS_1_0.major&&J.version.minor===A0.Versions.TLS_1_0.minor;if(V)X+=2*Z.fixed_iv_length;var K=Q(Z.master_secret,"key expansion",Y,X),z={client_write_MAC_key:K.getBytes(Z.mac_key_length),server_write_MAC_key:K.getBytes(Z.mac_key_length),client_write_key:K.getBytes(Z.enc_key_length),server_write_key:K.getBytes(Z.enc_key_length)};if(V)z.client_write_IV=K.getBytes(Z.fixed_iv_length),z.server_write_IV=K.getBytes(Z.fixed_iv_length);return z};A0.createConnectionState=function(J){var Z=J.entity===A0.ConnectionEnd.client,Q=function(){var V={sequenceNumber:[0,0],macKey:null,macLength:0,macFunction:null,cipherState:null,cipherFunction:function(K){return!0},compressionState:null,compressFunction:function(K){return!0},updateSequenceNumber:function(){if(V.sequenceNumber[1]===4294967295)V.sequenceNumber[1]=0,++V.sequenceNumber[0];else++V.sequenceNumber[1]}};return V},Y={read:Q(),write:Q()};if(Y.read.update=function(V,K){if(!Y.read.cipherFunction(K,Y.read))V.error(V,{message:"Could not decrypt record or bad MAC.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.bad_record_mac}});else if(!Y.read.compressFunction(V,K,Y.read))V.error(V,{message:"Could not decompress record.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.decompression_failure}});return!V.fail},Y.write.update=function(V,K){if(!Y.write.compressFunction(V,K,Y.write))V.error(V,{message:"Could not compress record.",send:!1,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.internal_error}});else if(!Y.write.cipherFunction(K,Y.write))V.error(V,{message:"Could not encrypt record.",send:!1,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.internal_error}});return!V.fail},J.session){var X=J.session.sp;switch(J.session.cipherSuite.initSecurityParameters(X),X.keys=A0.generateKeys(J,X),Y.read.macKey=Z?X.keys.server_write_MAC_key:X.keys.client_write_MAC_key,Y.write.macKey=Z?X.keys.client_write_MAC_key:X.keys.server_write_MAC_key,J.session.cipherSuite.initConnectionState(Y,J,X),X.compression_algorithm){case A0.CompressionMethod.none:break;case A0.CompressionMethod.deflate:Y.read.compressFunction=L03,Y.write.compressFunction=E03;break;default:throw Error("Unsupported compression algorithm.")}}return Y};A0.createRandom=function(){var J=new Date,Z=+J+J.getTimezoneOffset()*60000,Q=S1.util.createBuffer();return Q.putInt32(Z),Q.putBytes(S1.random.getBytes(28)),Q};A0.createRecord=function(J,Z){if(!Z.data)return null;var Q={type:Z.type,version:{major:J.version.major,minor:J.version.minor},length:Z.data.length(),fragment:Z.data};return Q};A0.createAlert=function(J,Z){var Q=S1.util.createBuffer();return Q.putByte(Z.level),Q.putByte(Z.description),A0.createRecord(J,{type:A0.ContentType.alert,data:Q})};A0.createClientHello=function(J){J.session.clientHelloVersion={major:J.version.major,minor:J.version.minor};var Z=S1.util.createBuffer();for(var Q=0;Q<J.cipherSuites.length;++Q){var Y=J.cipherSuites[Q];Z.putByte(Y.id[0]),Z.putByte(Y.id[1])}var X=Z.length(),V=S1.util.createBuffer();V.putByte(A0.CompressionMethod.none);var K=V.length(),z=S1.util.createBuffer();if(J.virtualHost){var G=S1.util.createBuffer();G.putByte(0),G.putByte(0);var F=S1.util.createBuffer();F.putByte(0),XX(F,2,S1.util.createBuffer(J.virtualHost));var U=S1.util.createBuffer();XX(U,2,F),XX(G,2,U),z.putBuffer(G)}var q=z.length();if(q>0)q+=2;var D=J.session.id,W=D.length+1+2+4+28+2+X+1+K+q,H=S1.util.createBuffer();if(H.putByte(A0.HandshakeType.client_hello),H.putInt24(W),H.putByte(J.version.major),H.putByte(J.version.minor),H.putBytes(J.session.sp.client_random),XX(H,1,S1.util.createBuffer(D)),XX(H,2,Z),XX(H,1,V),q>0)XX(H,2,z);return H};A0.createServerHello=function(J){var Z=J.session.id,Q=Z.length+1+2+4+28+2+1,Y=S1.util.createBuffer();return Y.putByte(A0.HandshakeType.server_hello),Y.putInt24(Q),Y.putByte(J.version.major),Y.putByte(J.version.minor),Y.putBytes(J.session.sp.server_random),XX(Y,1,S1.util.createBuffer(Z)),Y.putByte(J.session.cipherSuite.id[0]),Y.putByte(J.session.cipherSuite.id[1]),Y.putByte(J.session.compressionMethod),Y};A0.createCertificate=function(J){var Z=J.entity===A0.ConnectionEnd.client,Q=null;if(J.getCertificate){var Y;if(Z)Y=J.session.certificateRequest;else Y=J.session.extensions.server_name.serverNameList;Q=J.getCertificate(J,Y)}var X=S1.util.createBuffer();if(Q!==null)try{if(!S1.util.isArray(Q))Q=[Q];var V=null;for(var K=0;K<Q.length;++K){var z=S1.pem.decode(Q[K])[0];if(z.type!=="CERTIFICATE"&&z.type!=="X509 CERTIFICATE"&&z.type!=="TRUSTED CERTIFICATE"){var G=Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');throw G.headerType=z.type,G}if(z.procType&&z.procType.type==="ENCRYPTED")throw Error("Could not convert certificate from PEM; PEM is encrypted.");var F=S1.util.createBuffer(z.body);if(V===null)V=S1.asn1.fromDer(F.bytes(),!1);var U=S1.util.createBuffer();XX(U,3,F),X.putBuffer(U)}if(Q=S1.pki.certificateFromAsn1(V),Z)J.session.clientCertificate=Q;else J.session.serverCertificate=Q}catch(W){return J.error(J,{message:"Could not send certificate list.",cause:W,send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.bad_certificate}})}var q=3+X.length(),D=S1.util.createBuffer();return D.putByte(A0.HandshakeType.certificate),D.putInt24(q),XX(D,3,X),D};A0.createClientKeyExchange=function(J){var Z=S1.util.createBuffer();Z.putByte(J.session.clientHelloVersion.major),Z.putByte(J.session.clientHelloVersion.minor),Z.putBytes(S1.random.getBytes(46));var Q=J.session.sp;Q.pre_master_secret=Z.getBytes();var Y=J.session.serverCertificate.publicKey;Z=Y.encrypt(Q.pre_master_secret);var X=Z.length+2,V=S1.util.createBuffer();return V.putByte(A0.HandshakeType.client_key_exchange),V.putInt24(X),V.putInt16(Z.length),V.putBytes(Z),V};A0.createServerKeyExchange=function(J){var Z=0,Q=S1.util.createBuffer();if(Z>0)Q.putByte(A0.HandshakeType.server_key_exchange),Q.putInt24(Z);return Q};A0.getClientSignature=function(J,Z){var Q=S1.util.createBuffer();Q.putBuffer(J.session.md5.digest()),Q.putBuffer(J.session.sha1.digest()),Q=Q.getBytes(),J.getSignature=J.getSignature||function(Y,X,V){var K=null;if(Y.getPrivateKey)try{K=Y.getPrivateKey(Y,Y.session.clientCertificate),K=S1.pki.privateKeyFromPem(K)}catch(z){Y.error(Y,{message:"Could not get private key.",cause:z,send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.internal_error}})}if(K===null)Y.error(Y,{message:"No private key set.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.internal_error}});else X=K.sign(X,null);V(Y,X)},J.getSignature(J,Q,Z)};A0.createCertificateVerify=function(J,Z){var Q=Z.length+2,Y=S1.util.createBuffer();return Y.putByte(A0.HandshakeType.certificate_verify),Y.putInt24(Q),Y.putInt16(Z.length),Y.putBytes(Z),Y};A0.createCertificateRequest=function(J){var Z=S1.util.createBuffer();Z.putByte(1);var Q=S1.util.createBuffer();for(var Y in J.caStore.certs){var X=J.caStore.certs[Y],V=S1.pki.distinguishedNameToAsn1(X.subject),K=S1.asn1.toDer(V);Q.putInt16(K.length()),Q.putBuffer(K)}var z=1+Z.length()+2+Q.length(),G=S1.util.createBuffer();return G.putByte(A0.HandshakeType.certificate_request),G.putInt24(z),XX(G,1,Z),XX(G,2,Q),G};A0.createServerHelloDone=function(J){var Z=S1.util.createBuffer();return Z.putByte(A0.HandshakeType.server_hello_done),Z.putInt24(0),Z};A0.createChangeCipherSpec=function(){var J=S1.util.createBuffer();return J.putByte(1),J};A0.createFinished=function(J){var Z=S1.util.createBuffer();Z.putBuffer(J.session.md5.digest()),Z.putBuffer(J.session.sha1.digest());var Q=J.entity===A0.ConnectionEnd.client,Y=J.session.sp,X=12,V=tJ0,K=Q?"client finished":"server finished";Z=V(Y.master_secret,K,Z.getBytes(),X);var z=S1.util.createBuffer();return z.putByte(A0.HandshakeType.finished),z.putInt24(Z.length()),z.putBuffer(Z),z};A0.createHeartbeat=function(J,Z,Q){if(typeof Q>"u")Q=Z.length;var Y=S1.util.createBuffer();Y.putByte(J),Y.putInt16(Q),Y.putBytes(Z);var X=Y.length(),V=Math.max(16,X-Q-3);return Y.putBytes(S1.random.getBytes(V)),Y};A0.queue=function(J,Z){if(!Z)return;if(Z.fragment.length()===0){if(Z.type===A0.ContentType.handshake||Z.type===A0.ContentType.alert||Z.type===A0.ContentType.change_cipher_spec)return}if(Z.type===A0.ContentType.handshake){var Q=Z.fragment.bytes();J.session.md5.update(Q),J.session.sha1.update(Q),Q=null}var Y;if(Z.fragment.length()<=A0.MaxFragment)Y=[Z];else{Y=[];var X=Z.fragment.bytes();while(X.length>A0.MaxFragment)Y.push(A0.createRecord(J,{type:Z.type,data:S1.util.createBuffer(X.slice(0,A0.MaxFragment))})),X=X.slice(A0.MaxFragment);if(X.length>0)Y.push(A0.createRecord(J,{type:Z.type,data:S1.util.createBuffer(X)}))}for(var V=0;V<Y.length&&!J.fail;++V){var K=Y[V],z=J.state.current.write;if(z.update(J,K))J.records.push(K)}};A0.flush=function(J){for(var Z=0;Z<J.records.length;++Z){var Q=J.records[Z];J.tlsData.putByte(Q.type),J.tlsData.putByte(Q.version.major),J.tlsData.putByte(Q.version.minor),J.tlsData.putInt16(Q.fragment.length()),J.tlsData.putBuffer(J.records[Z].fragment)}return J.records=[],J.tlsDataReady(J)};var mc0=function(J){switch(J){case!0:return!0;case S1.pki.certificateError.bad_certificate:return A0.Alert.Description.bad_certificate;case S1.pki.certificateError.unsupported_certificate:return A0.Alert.Description.unsupported_certificate;case S1.pki.certificateError.certificate_revoked:return A0.Alert.Description.certificate_revoked;case S1.pki.certificateError.certificate_expired:return A0.Alert.Description.certificate_expired;case S1.pki.certificateError.certificate_unknown:return A0.Alert.Description.certificate_unknown;case S1.pki.certificateError.unknown_ca:return A0.Alert.Description.unknown_ca;default:return A0.Alert.Description.bad_certificate}},b03=function(J){switch(J){case!0:return!0;case A0.Alert.Description.bad_certificate:return S1.pki.certificateError.bad_certificate;case A0.Alert.Description.unsupported_certificate:return S1.pki.certificateError.unsupported_certificate;case A0.Alert.Description.certificate_revoked:return S1.pki.certificateError.certificate_revoked;case A0.Alert.Description.certificate_expired:return S1.pki.certificateError.certificate_expired;case A0.Alert.Description.certificate_unknown:return S1.pki.certificateError.certificate_unknown;case A0.Alert.Description.unknown_ca:return S1.pki.certificateError.unknown_ca;default:return S1.pki.certificateError.bad_certificate}};A0.verifyCertificateChain=function(J,Z){try{var Q={};for(var Y in J.verifyOptions)Q[Y]=J.verifyOptions[Y];Q.verify=function(V,K,z){var G=mc0(V),F=J.verify(J,V,K,z);if(F!==!0){if(typeof F==="object"&&!S1.util.isArray(F)){var U=Error("The application rejected the certificate.");if(U.send=!0,U.alert={level:A0.Alert.Level.fatal,description:A0.Alert.Description.bad_certificate},F.message)U.message=F.message;if(F.alert)U.alert.description=F.alert;throw U}if(F!==V)F=b03(F)}return F},S1.pki.verifyCertificateChain(J.caStore,Z,Q)}catch(V){var X=V;if(typeof X!=="object"||S1.util.isArray(X))X={send:!0,alert:{level:A0.Alert.Level.fatal,description:mc0(V)}};if(!("send"in X))X.send=!0;if(!("alert"in X))X.alert={level:A0.Alert.Level.fatal,description:mc0(X.error)};J.error(J,X)}return!J.fail};A0.createSessionCache=function(J,Z){var Q=null;if(J&&J.getSession&&J.setSession&&J.order)Q=J;else{Q={},Q.cache=J||{},Q.capacity=Math.max(Z||100,1),Q.order=[];for(var Y in J)if(Q.order.length<=Z)Q.order.push(Y);else delete J[Y];Q.getSession=function(X){var V=null,K=null;if(X)K=S1.util.bytesToHex(X);else if(Q.order.length>0)K=Q.order[0];if(K!==null&&K in Q.cache){V=Q.cache[K],delete Q.cache[K];for(var z in Q.order)if(Q.order[z]===K){Q.order.splice(z,1);break}}return V},Q.setSession=function(X,V){if(Q.order.length===Q.capacity){var K=Q.order.shift();delete Q.cache[K]}var K=S1.util.bytesToHex(X);Q.order.push(K),Q.cache[K]=V}}return Q};A0.createConnection=function(J){var Z=null;if(J.caStore)if(S1.util.isArray(J.caStore))Z=S1.pki.createCaStore(J.caStore);else Z=J.caStore;else Z=S1.pki.createCaStore();var Q=J.cipherSuites||null;if(Q===null){Q=[];for(var Y in A0.CipherSuites)Q.push(A0.CipherSuites[Y])}var X=J.server?A0.ConnectionEnd.server:A0.ConnectionEnd.client,V=J.sessionCache?A0.createSessionCache(J.sessionCache):null,K={version:{major:A0.Version.major,minor:A0.Version.minor},entity:X,sessionId:J.sessionId,caStore:Z,sessionCache:V,cipherSuites:Q,connected:J.connected,virtualHost:J.virtualHost||null,verifyClient:J.verifyClient||!1,verify:J.verify||function(U,q,D,W){return q},verifyOptions:J.verifyOptions||{},getCertificate:J.getCertificate||null,getPrivateKey:J.getPrivateKey||null,getSignature:J.getSignature||null,input:S1.util.createBuffer(),tlsData:S1.util.createBuffer(),data:S1.util.createBuffer(),tlsDataReady:J.tlsDataReady,dataReady:J.dataReady,heartbeatReceived:J.heartbeatReceived,closed:J.closed,error:function(U,q){if(q.origin=q.origin||(U.entity===A0.ConnectionEnd.client?"client":"server"),q.send)A0.queue(U,A0.createAlert(U,q.alert)),A0.flush(U);var D=q.fatal!==!1;if(D)U.fail=!0;if(J.error(U,q),D)U.close(!1)},deflate:J.deflate||null,inflate:J.inflate||null};K.reset=function(U){K.version={major:A0.Version.major,minor:A0.Version.minor},K.record=null,K.session=null,K.peerCertificate=null,K.state={pending:null,current:null},K.expect=K.entity===A0.ConnectionEnd.client?M03:T03,K.fragmented=null,K.records=[],K.open=!1,K.handshakes=0,K.handshaking=!1,K.isConnected=!1,K.fail=!(U||typeof U>"u"),K.input.clear(),K.tlsData.clear(),K.data.clear(),K.state.current=A0.createConnectionState(K)},K.reset();var z=function(U,q){var D=q.type-A0.ContentType.change_cipher_spec,W=dc0[U.entity][U.expect];if(D in W)W[D](U,q);else A0.handleUnexpected(U,q)},G=function(U){var q=0,D=U.input,W=D.length();if(W<5)q=5-W;else{U.record={type:D.getByte(),version:{major:D.getByte(),minor:D.getByte()},length:D.getInt16(),fragment:S1.util.createBuffer(),ready:!1};var H=U.record.version.major===U.version.major;if(H&&U.session&&U.session.version)H=U.record.version.minor===U.version.minor;if(!H)U.error(U,{message:"Incompatible TLS version.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.protocol_version}})}return q},F=function(U){var q=0,D=U.input,W=D.length();if(W<U.record.length)q=U.record.length-W;else{U.record.fragment.putBytes(D.getBytes(U.record.length)),D.compact();var H=U.state.current.read;if(H.update(U,U.record)){if(U.fragmented!==null)if(U.fragmented.type===U.record.type)U.fragmented.fragment.putBuffer(U.record.fragment),U.record=U.fragmented;else U.error(U,{message:"Invalid fragmented record.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.unexpected_message}});U.record.ready=!0}}return q};return K.handshake=function(U){if(K.entity!==A0.ConnectionEnd.client)K.error(K,{message:"Cannot initiate handshake as a server.",fatal:!1});else if(K.handshaking)K.error(K,{message:"Handshake already in progress.",fatal:!1});else{if(K.fail&&!K.open&&K.handshakes===0)K.fail=!1;K.handshaking=!0,U=U||"";var q=null;if(U.length>0){if(K.sessionCache)q=K.sessionCache.getSession(U);if(q===null)U=""}if(U.length===0&&K.sessionCache){if(q=K.sessionCache.getSession(),q!==null)U=q.id}if(K.session={id:U,version:null,cipherSuite:null,compressionMethod:null,serverCertificate:null,certificateRequest:null,clientCertificate:null,sp:{},md5:S1.md.md5.create(),sha1:S1.md.sha1.create()},q)K.version=q.version,K.session.sp=q.sp;K.session.sp.client_random=A0.createRandom().getBytes(),K.open=!0,A0.queue(K,A0.createRecord(K,{type:A0.ContentType.handshake,data:A0.createClientHello(K)})),A0.flush(K)}},K.process=function(U){var q=0;if(U)K.input.putBytes(U);if(!K.fail){if(K.record!==null&&K.record.ready&&K.record.fragment.isEmpty())K.record=null;if(K.record===null)q=G(K);if(!K.fail&&K.record!==null&&!K.record.ready)q=F(K);if(!K.fail&&K.record!==null&&K.record.ready)z(K,K.record)}return q},K.prepare=function(U){return A0.queue(K,A0.createRecord(K,{type:A0.ContentType.application_data,data:S1.util.createBuffer(U)})),A0.flush(K)},K.prepareHeartbeatRequest=function(U,q){if(U instanceof S1.util.ByteBuffer)U=U.bytes();if(typeof q>"u")q=U.length;return K.expectedHeartbeatPayload=U,A0.queue(K,A0.createRecord(K,{type:A0.ContentType.heartbeat,data:A0.createHeartbeat(A0.HeartbeatMessageType.heartbeat_request,U,q)})),A0.flush(K)},K.close=function(U){if(!K.fail&&K.sessionCache&&K.session){var q={id:K.session.id,version:K.session.version,sp:K.session.sp};q.sp.keys=null,K.sessionCache.setSession(q.id,q)}if(K.open){if(K.open=!1,K.input.clear(),K.isConnected||K.handshaking)K.isConnected=K.handshaking=!1,A0.queue(K,A0.createAlert(K,{level:A0.Alert.Level.warning,description:A0.Alert.Description.close_notify})),A0.flush(K);K.closed(K)}K.reset(U)},K};CI4.exports=S1.tls=S1.tls||{};for(Ad in A0)if(typeof A0[Ad]!=="function")S1.tls[Ad]=A0[Ad];var Ad;S1.tls.prf_tls1=tJ0;S1.tls.hmac_sha1=O03;S1.tls.createSessionCache=A0.createSessionCache;S1.tls.createConnection=A0.createConnection});var SI4=u((UE9,_I4)=>{var WB=J5();KB();cc0();var VX=_I4.exports=WB.tls;VX.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA={id:[0,47],name:"TLS_RSA_WITH_AES_128_CBC_SHA",initSecurityParameters:function(J){J.bulk_cipher_algorithm=VX.BulkCipherAlgorithm.aes,J.cipher_type=VX.CipherType.block,J.enc_key_length=16,J.block_length=16,J.fixed_iv_length=16,J.record_iv_length=16,J.mac_algorithm=VX.MACAlgorithm.hmac_sha1,J.mac_length=20,J.mac_key_length=20},initConnectionState:TI4};VX.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA={id:[0,53],name:"TLS_RSA_WITH_AES_256_CBC_SHA",initSecurityParameters:function(J){J.bulk_cipher_algorithm=VX.BulkCipherAlgorithm.aes,J.cipher_type=VX.CipherType.block,J.enc_key_length=32,J.block_length=16,J.fixed_iv_length=16,J.record_iv_length=16,J.mac_algorithm=VX.MACAlgorithm.hmac_sha1,J.mac_length=20,J.mac_key_length=20},initConnectionState:TI4};function TI4(J,Z,Q){var Y=Z.entity===WB.tls.ConnectionEnd.client;J.read.cipherState={init:!1,cipher:WB.cipher.createDecipher("AES-CBC",Y?Q.keys.server_write_key:Q.keys.client_write_key),iv:Y?Q.keys.server_write_IV:Q.keys.client_write_IV},J.write.cipherState={init:!1,cipher:WB.cipher.createCipher("AES-CBC",Y?Q.keys.client_write_key:Q.keys.server_write_key),iv:Y?Q.keys.client_write_IV:Q.keys.server_write_IV},J.read.cipherFunction=p03,J.write.cipherFunction=h03,J.read.macLength=J.write.macLength=Q.mac_length,J.read.macFunction=J.write.macFunction=VX.hmac_sha1}function h03(J,Z){var Q=!1,Y=Z.macFunction(Z.macKey,Z.sequenceNumber,J);J.fragment.putBytes(Y),Z.updateSequenceNumber();var X;if(J.version.minor===VX.Versions.TLS_1_0.minor)X=Z.cipherState.init?null:Z.cipherState.iv;else X=WB.random.getBytesSync(16);Z.cipherState.init=!0;var V=Z.cipherState.cipher;if(V.start({iv:X}),J.version.minor>=VX.Versions.TLS_1_1.minor)V.output.putBytes(X);if(V.update(J.fragment),V.finish(m03))J.fragment=V.output,J.length=J.fragment.length(),Q=!0;return Q}function m03(J,Z,Q){if(!Q){var Y=J-Z.length()%J;Z.fillWithByte(Y-1,Y)}return!0}function g03(J,Z,Q){var Y=!0;if(Q){var X=Z.length(),V=Z.last();for(var K=X-1-V;K<X-1;++K)Y=Y&&Z.at(K)==V;if(Y)Z.truncate(V+1)}return Y}function p03(J,Z){var Q=!1,Y;if(J.version.minor===VX.Versions.TLS_1_0.minor)Y=Z.cipherState.init?null:Z.cipherState.iv;else Y=J.fragment.getBytes(16);Z.cipherState.init=!0;var X=Z.cipherState.cipher;X.start({iv:Y}),X.update(J.fragment),Q=X.finish(g03);var V=Z.macLength,K=WB.random.getBytesSync(V),z=X.output.length();if(z>=V)J.fragment=X.output.getBytes(z-V),K=X.output.getBytes(V);else J.fragment=X.output.getBytes();J.fragment=WB.util.createBuffer(J.fragment),J.length=J.fragment.length();var G=Z.macFunction(Z.macKey,Z.sequenceNumber,J);return Z.updateSequenceNumber(),Q=d03(Z.macKey,K,G)&&Q,Q}function d03(J,Z,Q){var Y=WB.hmac.create();return Y.start("SHA1",J),Y.update(Z),Z=Y.digest().getBytes(),Y.start(null,null),Y.update(Q),Q=Y.digest().getBytes(),Z===Q}});var nc0=u((qE9,uI4)=>{var O8=J5();NG();c5();var Id=uI4.exports=O8.sha512=O8.sha512||{};O8.md.sha512=O8.md.algorithms.sha512=Id;var kI4=O8.sha384=O8.sha512.sha384=O8.sha512.sha384||{};kI4.create=function(){return Id.create("SHA-384")};O8.md.sha384=O8.md.algorithms.sha384=kI4;O8.sha512.sha256=O8.sha512.sha256||{create:function(){return Id.create("SHA-512/256")}};O8.md["sha512/256"]=O8.md.algorithms["sha512/256"]=O8.sha512.sha256;O8.sha512.sha224=O8.sha512.sha224||{create:function(){return Id.create("SHA-512/224")}};O8.md["sha512/224"]=O8.md.algorithms["sha512/224"]=O8.sha512.sha224;Id.create=function(J){if(!yI4)c03();if(typeof J>"u")J="SHA-512";if(!(J in sL))throw Error("Invalid SHA-512 algorithm: "+J);var Z=sL[J],Q=null,Y=O8.util.createBuffer(),X=Array(80);for(var V=0;V<80;++V)X[V]=[,,];var K=64;switch(J){case"SHA-384":K=48;break;case"SHA-512/256":K=32;break;case"SHA-512/224":K=28;break}var z={algorithm:J.replace("-","").toLowerCase(),blockLength:128,digestLength:K,messageLength:0,fullMessageLength:null,messageLengthSize:16};return z.start=function(){z.messageLength=0,z.fullMessageLength=z.messageLength128=[];var G=z.messageLengthSize/4;for(var F=0;F<G;++F)z.fullMessageLength.push(0);Y=O8.util.createBuffer(),Q=Array(Z.length);for(var F=0;F<Z.length;++F)Q[F]=Z[F].slice(0);return z},z.start(),z.update=function(G,F){if(F==="utf8")G=O8.util.encodeUtf8(G);var U=G.length;z.messageLength+=U,U=[U/4294967296>>>0,U>>>0];for(var q=z.fullMessageLength.length-1;q>=0;--q)z.fullMessageLength[q]+=U[1],U[1]=U[0]+(z.fullMessageLength[q]/4294967296>>>0),z.fullMessageLength[q]=z.fullMessageLength[q]>>>0,U[0]=U[1]/4294967296>>>0;if(Y.putBytes(G),vI4(Q,X,Y),Y.read>2048||Y.length()===0)Y.compact();return z},z.digest=function(){var G=O8.util.createBuffer();G.putBytes(Y.bytes());var F=z.fullMessageLength[z.fullMessageLength.length-1]+z.messageLengthSize,U=F&z.blockLength-1;G.putBytes(lc0.substr(0,z.blockLength-U));var q,D,W=z.fullMessageLength[0]*8;for(var H=0;H<z.fullMessageLength.length-1;++H)q=z.fullMessageLength[H+1]*8,D=q/4294967296>>>0,W+=D,G.putInt32(W>>>0),W=q>>>0;G.putInt32(W);var B=Array(Q.length);for(var H=0;H<Q.length;++H)B[H]=Q[H].slice(0);vI4(B,X,G);var w=O8.util.createBuffer(),N;if(J==="SHA-512")N=B.length;else if(J==="SHA-384")N=B.length-2;else N=B.length-4;for(var H=0;H<N;++H)if(w.putInt32(B[H][0]),H!==N-1||J!=="SHA-512/224")w.putInt32(B[H][1]);return w},z};var lc0=null,yI4=!1,ic0=null,sL=null;function c03(){lc0=String.fromCharCode(128),lc0+=O8.util.fillString(String.fromCharCode(0),128),ic0=[[1116352408,3609767458],[1899447441,602891725],[3049323471,3964484399],[3921009573,2173295548],[961987163,4081628472],[1508970993,3053834265],[2453635748,2937671579],[2870763221,3664609560],[3624381080,2734883394],[310598401,1164996542],[607225278,1323610764],[1426881987,3590304994],[1925078388,4068182383],[2162078206,991336113],[2614888103,633803317],[3248222580,3479774868],[3835390401,2666613458],[4022224774,944711139],[264347078,2341262773],[604807628,2007800933],[770255983,1495990901],[1249150122,1856431235],[1555081692,3175218132],[1996064986,2198950837],[2554220882,3999719339],[2821834349,766784016],[2952996808,2566594879],[3210313671,3203337956],[3336571891,1034457026],[3584528711,2466948901],[113926993,3758326383],[338241895,168717936],[666307205,1188179964],[773529912,1546045734],[1294757372,1522805485],[1396182291,2643833823],[1695183700,2343527390],[1986661051,1014477480],[2177026350,1206759142],[2456956037,344077627],[2730485921,1290863460],[2820302411,3158454273],[3259730800,3505952657],[3345764771,106217008],[3516065817,3606008344],[3600352804,1432725776],[4094571909,1467031594],[275423344,851169720],[430227734,3100823752],[506948616,1363258195],[659060556,3750685593],[883997877,3785050280],[958139571,3318307427],[1322822218,3812723403],[1537002063,2003034995],[1747873779,3602036899],[1955562222,1575990012],[2024104815,1125592928],[2227730452,2716904306],[2361852424,442776044],[2428436474,593698344],[2756734187,3733110249],[3204031479,2999351573],[3329325298,3815920427],[3391569614,3928383900],[3515267271,566280711],[3940187606,3454069534],[4118630271,4000239992],[116418474,1914138554],[174292421,2731055270],[289380356,3203993006],[460393269,320620315],[685471733,587496836],[852142971,1086792851],[1017036298,365543100],[1126000580,2618297676],[1288033470,3409855158],[1501505948,4234509866],[1607167915,987167468],[1816402316,1246189591]],sL={},sL["SHA-512"]=[[1779033703,4089235720],[3144134277,2227873595],[1013904242,4271175723],[2773480762,1595750129],[1359893119,2917565137],[2600822924,725511199],[528734635,4215389547],[1541459225,327033209]],sL["SHA-384"]=[[3418070365,3238371032],[1654270250,914150663],[2438529370,812702999],[355462360,4144912697],[1731405415,4290775857],[2394180231,1750603025],[3675008525,1694076839],[1203062813,3204075428]],sL["SHA-512/256"]=[[573645204,4230739756],[2673172387,3360449730],[596883563,1867755857],[2520282905,1497426621],[2519219938,2827943907],[3193839141,1401305490],[721525244,746961066],[246885852,2177182882]],sL["SHA-512/224"]=[[2352822216,424955298],[1944164710,2312950998],[502970286,855612546],[1738396948,1479516111],[258812777,2077511080],[2011393907,79989058],[1067287976,1780299464],[286451373,2446758561]],yI4=!0}function vI4(J,Z,Q){var Y,X,V,K,z,G,F,U,q,D,W,H,B,w,N,O,E,L,M,A,I,P,_,S,y,m,b,k,f,p,l,x,r,c,s,w0=Q.length();while(w0>=128){for(f=0;f<16;++f)Z[f][0]=Q.getInt32()>>>0,Z[f][1]=Q.getInt32()>>>0;for(;f<80;++f)x=Z[f-2],p=x[0],l=x[1],Y=((p>>>19|l<<13)^(l>>>29|p<<3)^p>>>6)>>>0,X=((p<<13|l>>>19)^(l<<3|p>>>29)^(p<<26|l>>>6))>>>0,c=Z[f-15],p=c[0],l=c[1],V=((p>>>1|l<<31)^(p>>>8|l<<24)^p>>>7)>>>0,K=((p<<31|l>>>1)^(p<<24|l>>>8)^(p<<25|l>>>7))>>>0,r=Z[f-7],s=Z[f-16],l=X+r[1]+K+s[1],Z[f][0]=Y+r[0]+V+s[0]+(l/4294967296>>>0)>>>0,Z[f][1]=l>>>0;B=J[0][0],w=J[0][1],N=J[1][0],O=J[1][1],E=J[2][0],L=J[2][1],M=J[3][0],A=J[3][1],I=J[4][0],P=J[4][1],_=J[5][0],S=J[5][1],y=J[6][0],m=J[6][1],b=J[7][0],k=J[7][1];for(f=0;f<80;++f)F=((I>>>14|P<<18)^(I>>>18|P<<14)^(P>>>9|I<<23))>>>0,U=((I<<18|P>>>14)^(I<<14|P>>>18)^(P<<23|I>>>9))>>>0,q=(y^I&(_^y))>>>0,D=(m^P&(S^m))>>>0,z=((B>>>28|w<<4)^(w>>>2|B<<30)^(w>>>7|B<<25))>>>0,G=((B<<4|w>>>28)^(w<<30|B>>>2)^(w<<25|B>>>7))>>>0,W=(B&N|E&(B^N))>>>0,H=(w&O|L&(w^O))>>>0,l=k+U+D+ic0[f][1]+Z[f][1],Y=b+F+q+ic0[f][0]+Z[f][0]+(l/4294967296>>>0)>>>0,X=l>>>0,l=G+H,V=z+W+(l/4294967296>>>0)>>>0,K=l>>>0,b=y,k=m,y=_,m=S,_=I,S=P,l=A+X,I=M+Y+(l/4294967296>>>0)>>>0,P=l>>>0,M=E,A=L,E=N,L=O,N=B,O=w,l=X+K,B=Y+V+(l/4294967296>>>0)>>>0,w=l>>>0;l=J[0][1]+w,J[0][0]=J[0][0]+B+(l/4294967296>>>0)>>>0,J[0][1]=l>>>0,l=J[1][1]+O,J[1][0]=J[1][0]+N+(l/4294967296>>>0)>>>0,J[1][1]=l>>>0,l=J[2][1]+L,J[2][0]=J[2][0]+E+(l/4294967296>>>0)>>>0,J[2][1]=l>>>0,l=J[3][1]+A,J[3][0]=J[3][0]+M+(l/4294967296>>>0)>>>0,J[3][1]=l>>>0,l=J[4][1]+P,J[4][0]=J[4][0]+I+(l/4294967296>>>0)>>>0,J[4][1]=l>>>0,l=J[5][1]+S,J[5][0]=J[5][0]+_+(l/4294967296>>>0)>>>0,J[5][1]=l>>>0,l=J[6][1]+m,J[6][0]=J[6][0]+y+(l/4294967296>>>0)>>>0,J[6][1]=l>>>0,l=J[7][1]+k,J[7][0]=J[7][0]+b+(l/4294967296>>>0)>>>0,J[7][1]=l>>>0,w0-=128}}});var xI4=u((i03)=>{var l03=J5();oV();var s7=l03.asn1;i03.privateKeyValidator={name:"PrivateKeyInfo",tagClass:s7.Class.UNIVERSAL,type:s7.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:s7.Class.UNIVERSAL,type:s7.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:s7.Class.UNIVERSAL,type:s7.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:s7.Class.UNIVERSAL,type:s7.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:s7.Class.UNIVERSAL,type:s7.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]};i03.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:s7.Class.UNIVERSAL,type:s7.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:s7.Class.UNIVERSAL,type:s7.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:s7.Class.UNIVERSAL,type:s7.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{tagClass:s7.Class.UNIVERSAL,type:s7.Type.BITSTRING,constructed:!1,composed:!0,captureBitStringValue:"ed25519PublicKey"}]}});var aI4=u((WE9,nI4)=>{var y2=J5();Od();JX();nc0();c5();var gI4=xI4(),o03=gI4.publicKeyValidator,r03=gI4.privateKeyValidator;if(typeof rc0>"u")rc0=y2.jsbn.BigInteger;var rc0,sc0=y2.util.ByteBuffer,wZ=typeof Buffer>"u"?Uint8Array:Buffer;y2.pki=y2.pki||{};nI4.exports=y2.pki.ed25519=y2.ed25519=y2.ed25519||{};var w5=y2.ed25519;w5.constants={};w5.constants.PUBLIC_KEY_BYTE_LENGTH=32;w5.constants.PRIVATE_KEY_BYTE_LENGTH=64;w5.constants.SEED_BYTE_LENGTH=32;w5.constants.SIGN_BYTE_LENGTH=64;w5.constants.HASH_BYTE_LENGTH=64;w5.generateKeyPair=function(J){J=J||{};var Z=J.seed;if(Z===void 0)Z=y2.random.getBytesSync(w5.constants.SEED_BYTE_LENGTH);else if(typeof Z==="string"){if(Z.length!==w5.constants.SEED_BYTE_LENGTH)throw TypeError('"seed" must be '+w5.constants.SEED_BYTE_LENGTH+" bytes in length.")}else if(!(Z instanceof Uint8Array))throw TypeError('"seed" must be a node.js Buffer, Uint8Array, or a binary string.');Z=Jq({message:Z,encoding:"binary"});var Q=new wZ(w5.constants.PUBLIC_KEY_BYTE_LENGTH),Y=new wZ(w5.constants.PRIVATE_KEY_BYTE_LENGTH);for(var X=0;X<32;++X)Y[X]=Z[X];return $13(Q,Y),{publicKey:Q,privateKey:Y}};w5.privateKeyFromAsn1=function(J){var Z={},Q=[],Y=y2.asn1.validate(J,r03,Z,Q);if(!Y){var X=Error("Invalid Key.");throw X.errors=Q,X}var V=y2.asn1.derToOid(Z.privateKeyOid),K=y2.oids.EdDSA25519;if(V!==K)throw Error('Invalid OID "'+V+'"; OID must be "'+K+'".');var z=Z.privateKey,G=Jq({message:y2.asn1.fromDer(z).value,encoding:"binary"});return{privateKeyBytes:G}};w5.publicKeyFromAsn1=function(J){var Z={},Q=[],Y=y2.asn1.validate(J,o03,Z,Q);if(!Y){var X=Error("Invalid Key.");throw X.errors=Q,X}var V=y2.asn1.derToOid(Z.publicKeyOid),K=y2.oids.EdDSA25519;if(V!==K)throw Error('Invalid OID "'+V+'"; OID must be "'+K+'".');var z=Z.ed25519PublicKey;if(z.length!==w5.constants.PUBLIC_KEY_BYTE_LENGTH)throw Error("Key length is invalid.");return Jq({message:z,encoding:"binary"})};w5.publicKeyFromPrivateKey=function(J){J=J||{};var Z=Jq({message:J.privateKey,encoding:"binary"});if(Z.length!==w5.constants.PRIVATE_KEY_BYTE_LENGTH)throw TypeError('"options.privateKey" must have a byte length of '+w5.constants.PRIVATE_KEY_BYTE_LENGTH);var Q=new wZ(w5.constants.PUBLIC_KEY_BYTE_LENGTH);for(var Y=0;Y<Q.length;++Y)Q[Y]=Z[32+Y];return Q};w5.sign=function(J){J=J||{};var Z=Jq(J),Q=Jq({message:J.privateKey,encoding:"binary"});if(Q.length===w5.constants.SEED_BYTE_LENGTH){var Y=w5.generateKeyPair({seed:Q});Q=Y.privateKey}else if(Q.length!==w5.constants.PRIVATE_KEY_BYTE_LENGTH)throw TypeError('"options.privateKey" must have a byte length of '+w5.constants.SEED_BYTE_LENGTH+" or "+w5.constants.PRIVATE_KEY_BYTE_LENGTH);var X=new wZ(w5.constants.SIGN_BYTE_LENGTH+Z.length);J13(X,Z,Z.length,Q);var V=new wZ(w5.constants.SIGN_BYTE_LENGTH);for(var K=0;K<V.length;++K)V[K]=X[K];return V};w5.verify=function(J){J=J||{};var Z=Jq(J);if(J.signature===void 0)throw TypeError('"options.signature" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a binary string.');var Q=Jq({message:J.signature,encoding:"binary"});if(Q.length!==w5.constants.SIGN_BYTE_LENGTH)throw TypeError('"options.signature" must have a byte length of '+w5.constants.SIGN_BYTE_LENGTH);var Y=Jq({message:J.publicKey,encoding:"binary"});if(Y.length!==w5.constants.PUBLIC_KEY_BYTE_LENGTH)throw TypeError('"options.publicKey" must have a byte length of '+w5.constants.PUBLIC_KEY_BYTE_LENGTH);var X=new wZ(w5.constants.SIGN_BYTE_LENGTH+Z.length),V=new wZ(w5.constants.SIGN_BYTE_LENGTH+Z.length),K;for(K=0;K<w5.constants.SIGN_BYTE_LENGTH;++K)X[K]=Q[K];for(K=0;K<Z.length;++K)X[K+w5.constants.SIGN_BYTE_LENGTH]=Z[K];return Z13(V,X,X.length,Y)>=0};function Jq(J){var Z=J.message;if(Z instanceof Uint8Array||Z instanceof wZ)return Z;var Q=J.encoding;if(Z===void 0)if(J.md)Z=J.md.digest().getBytes(),Q="binary";else throw TypeError('"options.message" or "options.md" not specified.');if(typeof Z==="string"&&!Q)throw TypeError('"options.encoding" must be "binary" or "utf8".');if(typeof Z==="string"){if(typeof Buffer<"u")return Buffer.from(Z,Q);Z=new sc0(Z,Q)}else if(!(Z instanceof sc0))throw TypeError('"options.message" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a string with "options.encoding" specifying its encoding.');var Y=new wZ(Z.length());for(var X=0;X<Y.length;++X)Y[X]=Z.at(X);return Y}var tc0=q6(),eJ0=q6([1]),s03=q6([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),t03=q6([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),fI4=q6([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),bI4=q6([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),ac0=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]),e03=q6([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function jd(J,Z){var Q=y2.md.sha512.create(),Y=new sc0(J);Q.update(Y.getBytes(Z),"binary");var X=Q.digest().getBytes();if(typeof Buffer<"u")return Buffer.from(X,"binary");var V=new wZ(w5.constants.HASH_BYTE_LENGTH);for(var K=0;K<64;++K)V[K]=X.charCodeAt(K);return V}function $13(J,Z){var Q=[q6(),q6(),q6(),q6()],Y,X=jd(Z,32);X[0]&=248,X[31]&=127,X[31]|=64,Zl0(Q,X),Jl0(J,Q);for(Y=0;Y<32;++Y)Z[Y+32]=J[Y];return 0}function J13(J,Z,Q,Y){var X,V,K=new Float64Array(64),z=[q6(),q6(),q6(),q6()],G=jd(Y,32);G[0]&=248,G[31]&=127,G[31]|=64;var F=Q+64;for(X=0;X<Q;++X)J[64+X]=Z[X];for(X=0;X<32;++X)J[32+X]=G[32+X];var U=jd(J.subarray(32),Q+32);ec0(U),Zl0(z,U),Jl0(J,z);for(X=32;X<64;++X)J[X]=Y[X];var q=jd(J,Q+64);ec0(q);for(X=32;X<64;++X)K[X]=0;for(X=0;X<32;++X)K[X]=U[X];for(X=0;X<32;++X)for(V=0;V<32;V++)K[X+V]+=q[X]*G[V];return pI4(J.subarray(32),K),F}function Z13(J,Z,Q,Y){var X,V,K=new wZ(32),z=[q6(),q6(),q6(),q6()],G=[q6(),q6(),q6(),q6()];if(V=-1,Q<64)return-1;if(Q13(G,Y))return-1;for(X=0;X<Q;++X)J[X]=Z[X];for(X=0;X<32;++X)J[X+32]=Y[X];var F=jd(J,Q);if(ec0(F),lI4(z,G,F),Zl0(G,Z.subarray(32)),$l0(z,G),Jl0(K,z),Q-=64,dI4(Z,0,K,0)){for(X=0;X<Q;++X)J[X]=0;return-1}for(X=0;X<Q;++X)J[X]=Z[X+64];return V=Q,V}function pI4(J,Z){var Q,Y,X,V;for(Y=63;Y>=32;--Y){Q=0;for(X=Y-32,V=Y-12;X<V;++X)Z[X]+=Q-16*Z[Y]*ac0[X-(Y-32)],Q=Z[X]+128>>8,Z[X]-=Q*256;Z[X]+=Q,Z[Y]=0}Q=0;for(X=0;X<32;++X)Z[X]+=Q-(Z[31]>>4)*ac0[X],Q=Z[X]>>8,Z[X]&=255;for(X=0;X<32;++X)Z[X]-=Q*ac0[X];for(Y=0;Y<32;++Y)Z[Y+1]+=Z[Y]>>8,J[Y]=Z[Y]&255}function ec0(J){var Z=new Float64Array(64);for(var Q=0;Q<64;++Q)Z[Q]=J[Q],J[Q]=0;pI4(J,Z)}function $l0(J,Z){var Q=q6(),Y=q6(),X=q6(),V=q6(),K=q6(),z=q6(),G=q6(),F=q6(),U=q6();W_(Q,J[1],J[0]),W_(U,Z[1],Z[0]),o3(Q,Q,U),D_(Y,J[0],J[1]),D_(U,Z[0],Z[1]),o3(Y,Y,U),o3(X,J[3],Z[3]),o3(X,X,t03),o3(V,J[2],Z[2]),D_(V,V,V),W_(K,Y,Q),W_(z,V,X),D_(G,V,X),D_(F,Y,Q),o3(J[0],K,z),o3(J[1],F,G),o3(J[2],G,z),o3(J[3],K,F)}function hI4(J,Z,Q){for(var Y=0;Y<4;++Y)iI4(J[Y],Z[Y],Q)}function Jl0(J,Z){var Q=q6(),Y=q6(),X=q6();K13(X,Z[2]),o3(Q,Z[0],X),o3(Y,Z[1],X),$Z0(J,Y),J[31]^=cI4(Q)<<7}function $Z0(J,Z){var Q,Y,X,V=q6(),K=q6();for(Q=0;Q<16;++Q)K[Q]=Z[Q];oc0(K),oc0(K),oc0(K);for(Y=0;Y<2;++Y){V[0]=K[0]-65517;for(Q=1;Q<15;++Q)V[Q]=K[Q]-65535-(V[Q-1]>>16&1),V[Q-1]&=65535;V[15]=K[15]-32767-(V[14]>>16&1),X=V[15]>>16&1,V[14]&=65535,iI4(K,V,1-X)}for(Q=0;Q<16;Q++)J[2*Q]=K[Q]&255,J[2*Q+1]=K[Q]>>8}function Q13(J,Z){var Q=q6(),Y=q6(),X=q6(),V=q6(),K=q6(),z=q6(),G=q6();if(HB(J[2],eJ0),Y13(J[1],Z),tL(X,J[1]),o3(V,X,s03),W_(X,X,J[2]),D_(V,J[2],V),tL(K,V),tL(z,K),o3(G,z,K),o3(Q,G,X),o3(Q,Q,V),X13(Q,Q),o3(Q,Q,X),o3(Q,Q,V),o3(Q,Q,V),o3(J[0],Q,V),tL(Y,J[0]),o3(Y,Y,V),mI4(Y,X))o3(J[0],J[0],e03);if(tL(Y,J[0]),o3(Y,Y,V),mI4(Y,X))return-1;if(cI4(J[0])===Z[31]>>7)W_(J[0],tc0,J[0]);return o3(J[3],J[0],J[1]),0}function Y13(J,Z){var Q;for(Q=0;Q<16;++Q)J[Q]=Z[2*Q]+(Z[2*Q+1]<<8);J[15]&=32767}function X13(J,Z){var Q=q6(),Y;for(Y=0;Y<16;++Y)Q[Y]=Z[Y];for(Y=250;Y>=0;--Y)if(tL(Q,Q),Y!==1)o3(Q,Q,Z);for(Y=0;Y<16;++Y)J[Y]=Q[Y]}function mI4(J,Z){var Q=new wZ(32),Y=new wZ(32);return $Z0(Q,J),$Z0(Y,Z),dI4(Q,0,Y,0)}function dI4(J,Z,Q,Y){return V13(J,Z,Q,Y,32)}function V13(J,Z,Q,Y,X){var V,K=0;for(V=0;V<X;++V)K|=J[Z+V]^Q[Y+V];return(1&K-1>>>8)-1}function cI4(J){var Z=new wZ(32);return $Z0(Z,J),Z[0]&1}function lI4(J,Z,Q){var Y,X;HB(J[0],tc0),HB(J[1],eJ0),HB(J[2],eJ0),HB(J[3],tc0);for(X=255;X>=0;--X)Y=Q[X/8|0]>>(X&7)&1,hI4(J,Z,Y),$l0(Z,J),$l0(J,J),hI4(J,Z,Y)}function Zl0(J,Z){var Q=[q6(),q6(),q6(),q6()];HB(Q[0],fI4),HB(Q[1],bI4),HB(Q[2],eJ0),o3(Q[3],fI4,bI4),lI4(J,Q,Z)}function HB(J,Z){var Q;for(Q=0;Q<16;Q++)J[Q]=Z[Q]|0}function K13(J,Z){var Q=q6(),Y;for(Y=0;Y<16;++Y)Q[Y]=Z[Y];for(Y=253;Y>=0;--Y)if(tL(Q,Q),Y!==2&&Y!==4)o3(Q,Q,Z);for(Y=0;Y<16;++Y)J[Y]=Q[Y]}function oc0(J){var Z,Q,Y=1;for(Z=0;Z<16;++Z)Q=J[Z]+Y+65535,Y=Math.floor(Q/65536),J[Z]=Q-Y*65536;J[0]+=Y-1+37*(Y-1)}function iI4(J,Z,Q){var Y,X=~(Q-1);for(var V=0;V<16;++V)Y=X&(J[V]^Z[V]),J[V]^=Y,Z[V]^=Y}function q6(J){var Z,Q=new Float64Array(16);if(J)for(Z=0;Z<J.length;++Z)Q[Z]=J[Z];return Q}function D_(J,Z,Q){for(var Y=0;Y<16;++Y)J[Y]=Z[Y]+Q[Y]}function W_(J,Z,Q){for(var Y=0;Y<16;++Y)J[Y]=Z[Y]-Q[Y]}function tL(J,Z){o3(J,Z,Z)}function o3(J,Z,Q){var Y,X,V=0,K=0,z=0,G=0,F=0,U=0,q=0,D=0,W=0,H=0,B=0,w=0,N=0,O=0,E=0,L=0,M=0,A=0,I=0,P=0,_=0,S=0,y=0,m=0,b=0,k=0,f=0,p=0,l=0,x=0,r=0,c=Q[0],s=Q[1],w0=Q[2],a=Q[3],F0=Q[4],z0=Q[5],q0=Q[6],Q0=Q[7],H0=Q[8],i=Q[9],n=Q[10],e=Q[11],J0=Q[12],Z0=Q[13],K0=Q[14],t=Q[15];Y=Z[0],V+=Y*c,K+=Y*s,z+=Y*w0,G+=Y*a,F+=Y*F0,U+=Y*z0,q+=Y*q0,D+=Y*Q0,W+=Y*H0,H+=Y*i,B+=Y*n,w+=Y*e,N+=Y*J0,O+=Y*Z0,E+=Y*K0,L+=Y*t,Y=Z[1],K+=Y*c,z+=Y*s,G+=Y*w0,F+=Y*a,U+=Y*F0,q+=Y*z0,D+=Y*q0,W+=Y*Q0,H+=Y*H0,B+=Y*i,w+=Y*n,N+=Y*e,O+=Y*J0,E+=Y*Z0,L+=Y*K0,M+=Y*t,Y=Z[2],z+=Y*c,G+=Y*s,F+=Y*w0,U+=Y*a,q+=Y*F0,D+=Y*z0,W+=Y*q0,H+=Y*Q0,B+=Y*H0,w+=Y*i,N+=Y*n,O+=Y*e,E+=Y*J0,L+=Y*Z0,M+=Y*K0,A+=Y*t,Y=Z[3],G+=Y*c,F+=Y*s,U+=Y*w0,q+=Y*a,D+=Y*F0,W+=Y*z0,H+=Y*q0,B+=Y*Q0,w+=Y*H0,N+=Y*i,O+=Y*n,E+=Y*e,L+=Y*J0,M+=Y*Z0,A+=Y*K0,I+=Y*t,Y=Z[4],F+=Y*c,U+=Y*s,q+=Y*w0,D+=Y*a,W+=Y*F0,H+=Y*z0,B+=Y*q0,w+=Y*Q0,N+=Y*H0,O+=Y*i,E+=Y*n,L+=Y*e,M+=Y*J0,A+=Y*Z0,I+=Y*K0,P+=Y*t,Y=Z[5],U+=Y*c,q+=Y*s,D+=Y*w0,W+=Y*a,H+=Y*F0,B+=Y*z0,w+=Y*q0,N+=Y*Q0,O+=Y*H0,E+=Y*i,L+=Y*n,M+=Y*e,A+=Y*J0,I+=Y*Z0,P+=Y*K0,_+=Y*t,Y=Z[6],q+=Y*c,D+=Y*s,W+=Y*w0,H+=Y*a,B+=Y*F0,w+=Y*z0,N+=Y*q0,O+=Y*Q0,E+=Y*H0,L+=Y*i,M+=Y*n,A+=Y*e,I+=Y*J0,P+=Y*Z0,_+=Y*K0,S+=Y*t,Y=Z[7],D+=Y*c,W+=Y*s,H+=Y*w0,B+=Y*a,w+=Y*F0,N+=Y*z0,O+=Y*q0,E+=Y*Q0,L+=Y*H0,M+=Y*i,A+=Y*n,I+=Y*e,P+=Y*J0,_+=Y*Z0,S+=Y*K0,y+=Y*t,Y=Z[8],W+=Y*c,H+=Y*s,B+=Y*w0,w+=Y*a,N+=Y*F0,O+=Y*z0,E+=Y*q0,L+=Y*Q0,M+=Y*H0,A+=Y*i,I+=Y*n,P+=Y*e,_+=Y*J0,S+=Y*Z0,y+=Y*K0,m+=Y*t,Y=Z[9],H+=Y*c,B+=Y*s,w+=Y*w0,N+=Y*a,O+=Y*F0,E+=Y*z0,L+=Y*q0,M+=Y*Q0,A+=Y*H0,I+=Y*i,P+=Y*n,_+=Y*e,S+=Y*J0,y+=Y*Z0,m+=Y*K0,b+=Y*t,Y=Z[10],B+=Y*c,w+=Y*s,N+=Y*w0,O+=Y*a,E+=Y*F0,L+=Y*z0,M+=Y*q0,A+=Y*Q0,I+=Y*H0,P+=Y*i,_+=Y*n,S+=Y*e,y+=Y*J0,m+=Y*Z0,b+=Y*K0,k+=Y*t,Y=Z[11],w+=Y*c,N+=Y*s,O+=Y*w0,E+=Y*a,L+=Y*F0,M+=Y*z0,A+=Y*q0,I+=Y*Q0,P+=Y*H0,_+=Y*i,S+=Y*n,y+=Y*e,m+=Y*J0,b+=Y*Z0,k+=Y*K0,f+=Y*t,Y=Z[12],N+=Y*c,O+=Y*s,E+=Y*w0,L+=Y*a,M+=Y*F0,A+=Y*z0,I+=Y*q0,P+=Y*Q0,_+=Y*H0,S+=Y*i,y+=Y*n,m+=Y*e,b+=Y*J0,k+=Y*Z0,f+=Y*K0,p+=Y*t,Y=Z[13],O+=Y*c,E+=Y*s,L+=Y*w0,M+=Y*a,A+=Y*F0,I+=Y*z0,P+=Y*q0,_+=Y*Q0,S+=Y*H0,y+=Y*i,m+=Y*n,b+=Y*e,k+=Y*J0,f+=Y*Z0,p+=Y*K0,l+=Y*t,Y=Z[14],E+=Y*c,L+=Y*s,M+=Y*w0,A+=Y*a,I+=Y*F0,P+=Y*z0,_+=Y*q0,S+=Y*Q0,y+=Y*H0,m+=Y*i,b+=Y*n,k+=Y*e,f+=Y*J0,p+=Y*Z0,l+=Y*K0,x+=Y*t,Y=Z[15],L+=Y*c,M+=Y*s,A+=Y*w0,I+=Y*a,P+=Y*F0,_+=Y*z0,S+=Y*q0,y+=Y*Q0,m+=Y*H0,b+=Y*i,k+=Y*n,f+=Y*e,p+=Y*J0,l+=Y*Z0,x+=Y*K0,r+=Y*t,V+=38*M,K+=38*A,z+=38*I,G+=38*P,F+=38*_,U+=38*S,q+=38*y,D+=38*m,W+=38*b,H+=38*k,B+=38*f,w+=38*p,N+=38*l,O+=38*x,E+=38*r,X=1,Y=V+X+65535,X=Math.floor(Y/65536),V=Y-X*65536,Y=K+X+65535,X=Math.floor(Y/65536),K=Y-X*65536,Y=z+X+65535,X=Math.floor(Y/65536),z=Y-X*65536,Y=G+X+65535,X=Math.floor(Y/65536),G=Y-X*65536,Y=F+X+65535,X=Math.floor(Y/65536),F=Y-X*65536,Y=U+X+65535,X=Math.floor(Y/65536),U=Y-X*65536,Y=q+X+65535,X=Math.floor(Y/65536),q=Y-X*65536,Y=D+X+65535,X=Math.floor(Y/65536),D=Y-X*65536,Y=W+X+65535,X=Math.floor(Y/65536),W=Y-X*65536,Y=H+X+65535,X=Math.floor(Y/65536),H=Y-X*65536,Y=B+X+65535,X=Math.floor(Y/65536),B=Y-X*65536,Y=w+X+65535,X=Math.floor(Y/65536),w=Y-X*65536,Y=N+X+65535,X=Math.floor(Y/65536),N=Y-X*65536,Y=O+X+65535,X=Math.floor(Y/65536),O=Y-X*65536,Y=E+X+65535,X=Math.floor(Y/65536),E=Y-X*65536,Y=L+X+65535,X=Math.floor(Y/65536),L=Y-X*65536,V+=X-1+37*(X-1),X=1,Y=V+X+65535,X=Math.floor(Y/65536),V=Y-X*65536,Y=K+X+65535,X=Math.floor(Y/65536),K=Y-X*65536,Y=z+X+65535,X=Math.floor(Y/65536),z=Y-X*65536,Y=G+X+65535,X=Math.floor(Y/65536),G=Y-X*65536,Y=F+X+65535,X=Math.floor(Y/65536),F=Y-X*65536,Y=U+X+65535,X=Math.floor(Y/65536),U=Y-X*65536,Y=q+X+65535,X=Math.floor(Y/65536),q=Y-X*65536,Y=D+X+65535,X=Math.floor(Y/65536),D=Y-X*65536,Y=W+X+65535,X=Math.floor(Y/65536),W=Y-X*65536,Y=H+X+65535,X=Math.floor(Y/65536),H=Y-X*65536,Y=B+X+65535,X=Math.floor(Y/65536),B=Y-X*65536,Y=w+X+65535,X=Math.floor(Y/65536),w=Y-X*65536,Y=N+X+65535,X=Math.floor(Y/65536),N=Y-X*65536,Y=O+X+65535,X=Math.floor(Y/65536),O=Y-X*65536,Y=E+X+65535,X=Math.floor(Y/65536),E=Y-X*65536,Y=L+X+65535,X=Math.floor(Y/65536),L=Y-X*65536,V+=X-1+37*(X-1),J[0]=V,J[1]=K,J[2]=z,J[3]=G,J[4]=F,J[5]=U,J[6]=q,J[7]=D,J[8]=W,J[9]=H,J[10]=B,J[11]=w,J[12]=N,J[13]=O,J[14]=E,J[15]=L}});var tI4=u((HE9,sI4)=>{var _Q=J5();c5();JX();Od();sI4.exports=_Q.kem=_Q.kem||{};var oI4=_Q.jsbn.BigInteger;_Q.kem.rsa={};_Q.kem.rsa.create=function(J,Z){Z=Z||{};var Q=Z.prng||_Q.random,Y={};return Y.encrypt=function(X,V){var K=Math.ceil(X.n.bitLength()/8),z;do z=new oI4(_Q.util.bytesToHex(Q.getBytesSync(K)),16).mod(X.n);while(z.compareTo(oI4.ONE)<=0);z=_Q.util.hexToBytes(z.toString(16));var G=K-z.length;if(G>0)z=_Q.util.fillString(String.fromCharCode(0),G)+z;var F=X.encrypt(z,"NONE"),U=J.generate(z,V);return{encapsulation:F,key:U}},Y.decrypt=function(X,V,K){var z=X.decrypt(V,"NONE");return J.generate(z,K)},Y};_Q.kem.kdf1=function(J,Z){rI4(this,J,0,Z||J.digestLength)};_Q.kem.kdf2=function(J,Z){rI4(this,J,1,Z||J.digestLength)};function rI4(J,Z,Q,Y){J.generate=function(X,V){var K=new _Q.util.ByteBuffer,z=Math.ceil(V/Y)+Q,G=new _Q.util.ByteBuffer;for(var F=Q;F<z;++F){G.putInt32(F),Z.start(),Z.update(X+G.getBytes());var U=Z.digest();K.putBytes(U.getBytes(Y))}return K.truncate(K.length()-V),K.getBytes()}}});var $j4=u((BE9,eI4)=>{var L5=J5();c5();eI4.exports=L5.log=L5.log||{};L5.log.levels=["none","error","warning","info","debug","verbose","max"];var QZ0={},Ql0=[],Rd=null;L5.log.LEVEL_LOCKED=2;L5.log.NO_LEVEL_CHECK=4;L5.log.INTERPOLATE=8;for(KX=0;KX<L5.log.levels.length;++KX)JZ0=L5.log.levels[KX],QZ0[JZ0]={index:KX,name:JZ0.toUpperCase()};var JZ0,KX;L5.log.logMessage=function(J){var Z=QZ0[J.level].index;for(var Q=0;Q<Ql0.length;++Q){var Y=Ql0[Q];if(Y.flags&L5.log.NO_LEVEL_CHECK)Y.f(J);else{var X=QZ0[Y.level].index;if(Z<=X)Y.f(Y,J)}}};L5.log.prepareStandard=function(J){if(!("standard"in J))J.standard=QZ0[J.level].name+" ["+J.category+"] "+J.message};L5.log.prepareFull=function(J){if(!("full"in J)){var Z=[J.message];Z=Z.concat([]),J.full=L5.util.format.apply(this,Z)}};L5.log.prepareStandardFull=function(J){if(!("standardFull"in J))L5.log.prepareStandard(J),J.standardFull=J.standard};ZZ0=["error","warning","info","debug","verbose"];for(KX=0;KX<ZZ0.length;++KX)(function(Z){L5.log[Z]=function(Q,Y){var X=Array.prototype.slice.call(arguments).slice(2),V={timestamp:new Date,level:Z,category:Q,message:Y,arguments:X};L5.log.logMessage(V)}})(ZZ0[KX]);var ZZ0,KX;L5.log.makeLogger=function(J){var Z={flags:0,f:J};return L5.log.setLevel(Z,"none"),Z};L5.log.setLevel=function(J,Z){var Q=!1;if(J&&!(J.flags&L5.log.LEVEL_LOCKED))for(var Y=0;Y<L5.log.levels.length;++Y){var X=L5.log.levels[Y];if(Z==X){J.level=Z,Q=!0;break}}return Q};L5.log.lock=function(J,Z){if(typeof Z>"u"||Z)J.flags|=L5.log.LEVEL_LOCKED;else J.flags&=~L5.log.LEVEL_LOCKED};L5.log.addLogger=function(J){Ql0.push(J)};if(typeof console<"u"&&"log"in console){if(console.error&&console.warn&&console.info&&console.debug)Yl0={error:console.error,warning:console.warn,info:console.info,debug:console.debug,verbose:console.debug},B_=function(J,Z){L5.log.prepareStandard(Z);var Q=Yl0[Z.level],Y=[Z.standard];Y=Y.concat(Z.arguments.slice()),Q.apply(console,Y)},eL=L5.log.makeLogger(B_);else B_=function(Z,Q){L5.log.prepareStandardFull(Q),console.log(Q.standardFull)},eL=L5.log.makeLogger(B_);L5.log.setLevel(eL,"debug"),L5.log.addLogger(eL),Rd=eL}else console={log:function(){}};var eL,Yl0,B_;if(Rd!==null&&typeof window<"u"&&window.location){if(H_=new URL(window.location.href).searchParams,H_.has("console.level"))L5.log.setLevel(Rd,H_.get("console.level").slice(-1)[0]);if(H_.has("console.lock")){if(Xl0=H_.get("console.lock").slice(-1)[0],Xl0=="true")L5.log.lock(Rd)}}var H_,Xl0;L5.log.consoleLogger=Rd});var Zj4=u((wE9,Jj4)=>{Jj4.exports=NG();uJ0();z_();wc0();nc0()});var Xj4=u((NE9,Yj4)=>{var U4=J5();KB();oV();wd();zB();lL();vc0();JX();c5();oJ0();var b0=U4.asn1,BJ=Yj4.exports=U4.pkcs7=U4.pkcs7||{};BJ.messageFromPem=function(J){var Z=U4.pem.decode(J)[0];if(Z.type!=="PKCS7"){var Q=Error('Could not convert PKCS#7 message from PEM; PEM header type is not "PKCS#7".');throw Q.headerType=Z.type,Q}if(Z.procType&&Z.procType.type==="ENCRYPTED")throw Error("Could not convert PKCS#7 message from PEM; PEM is encrypted.");var Y=b0.fromDer(Z.body);return BJ.messageFromAsn1(Y)};BJ.messageToPem=function(J,Z){var Q={type:"PKCS7",body:b0.toDer(J.toAsn1()).getBytes()};return U4.pem.encode(Q,{maxline:Z})};BJ.messageFromAsn1=function(J){var Z={},Q=[];if(!b0.validate(J,BJ.asn1.contentInfoValidator,Z,Q)){var Y=Error("Cannot read PKCS#7 message. ASN.1 object is not an PKCS#7 ContentInfo.");throw Y.errors=Q,Y}var X=b0.derToOid(Z.contentType),V;switch(X){case U4.pki.oids.envelopedData:V=BJ.createEnvelopedData();break;case U4.pki.oids.encryptedData:V=BJ.createEncryptedData();break;case U4.pki.oids.signedData:V=BJ.createSignedData();break;default:throw Error("Cannot read PKCS#7 message. ContentType with OID "+X+" is not (yet) supported.")}return V.fromAsn1(Z.content.value[0]),V};BJ.createSignedData=function(){var J=null;return J={type:U4.pki.oids.signedData,version:1,certificates:[],crls:[],signers:[],digestAlgorithmIdentifiers:[],contentInfo:null,signerInfos:[],fromAsn1:function(Y){if(Kl0(J,Y,BJ.asn1.signedDataValidator),J.certificates=[],J.crls=[],J.digestAlgorithmIdentifiers=[],J.contentInfo=null,J.signerInfos=[],J.rawCapture.certificates){var X=J.rawCapture.certificates.value;for(var V=0;V<X.length;++V)J.certificates.push(U4.pki.certificateFromAsn1(X[V]))}},toAsn1:function(){if(!J.contentInfo)J.sign();var Y=[];for(var X=0;X<J.certificates.length;++X)Y.push(U4.pki.certificateToAsn1(J.certificates[X]));var V=[],K=b0.create(b0.Class.CONTEXT_SPECIFIC,0,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.SEQUENCE,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.INTEGER,!1,b0.integerToDer(J.version).getBytes()),b0.create(b0.Class.UNIVERSAL,b0.Type.SET,!0,J.digestAlgorithmIdentifiers),J.contentInfo])]);if(Y.length>0)K.value[0].value.push(b0.create(b0.Class.CONTEXT_SPECIFIC,0,!0,Y));if(V.length>0)K.value[0].value.push(b0.create(b0.Class.CONTEXT_SPECIFIC,1,!0,V));return K.value[0].value.push(b0.create(b0.Class.UNIVERSAL,b0.Type.SET,!0,J.signerInfos)),b0.create(b0.Class.UNIVERSAL,b0.Type.SEQUENCE,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.OID,!1,b0.oidToDer(J.type).getBytes()),K])},addSigner:function(Y){var{issuer:X,serialNumber:V}=Y;if(Y.certificate){var K=Y.certificate;if(typeof K==="string")K=U4.pki.certificateFromPem(K);X=K.issuer.attributes,V=K.serialNumber}var z=Y.key;if(!z)throw Error("Could not add PKCS#7 signer; no private key specified.");if(typeof z==="string")z=U4.pki.privateKeyFromPem(z);var G=Y.digestAlgorithm||U4.pki.oids.sha1;switch(G){case U4.pki.oids.sha1:case U4.pki.oids.sha256:case U4.pki.oids.sha384:case U4.pki.oids.sha512:case U4.pki.oids.md5:break;default:throw Error("Could not add PKCS#7 signer; unknown message digest algorithm: "+G)}var F=Y.authenticatedAttributes||[];if(F.length>0){var U=!1,q=!1;for(var D=0;D<F.length;++D){var W=F[D];if(!U&&W.type===U4.pki.oids.contentType){if(U=!0,q)break;continue}if(!q&&W.type===U4.pki.oids.messageDigest){if(q=!0,U)break;continue}}if(!U||!q)throw Error("Invalid signer.authenticatedAttributes. If signer.authenticatedAttributes is specified, then it must contain at least two attributes, PKCS #9 content-type and PKCS #9 message-digest.")}J.signers.push({key:z,version:1,issuer:X,serialNumber:V,digestAlgorithm:G,signatureAlgorithm:U4.pki.oids.rsaEncryption,signature:null,authenticatedAttributes:F,unauthenticatedAttributes:[]})},sign:function(Y){if(Y=Y||{},typeof J.content!=="object"||J.contentInfo===null){if(J.contentInfo=b0.create(b0.Class.UNIVERSAL,b0.Type.SEQUENCE,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.OID,!1,b0.oidToDer(U4.pki.oids.data).getBytes())]),"content"in J){var X;if(J.content instanceof U4.util.ByteBuffer)X=J.content.bytes();else if(typeof J.content==="string")X=U4.util.encodeUtf8(J.content);if(Y.detached)J.detachedContent=b0.create(b0.Class.UNIVERSAL,b0.Type.OCTETSTRING,!1,X);else J.contentInfo.value.push(b0.create(b0.Class.CONTEXT_SPECIFIC,0,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.OCTETSTRING,!1,X)]))}}if(J.signers.length===0)return;var V=Z();Q(V)},verify:function(){throw Error("PKCS#7 signature verification not yet implemented.")},addCertificate:function(Y){if(typeof Y==="string")Y=U4.pki.certificateFromPem(Y);J.certificates.push(Y)},addCertificateRevokationList:function(Y){throw Error("PKCS#7 CRL support not yet implemented.")}},J;function Z(){var Y={};for(var X=0;X<J.signers.length;++X){var V=J.signers[X],K=V.digestAlgorithm;if(!(K in Y))Y[K]=U4.md[U4.pki.oids[K]].create();if(V.authenticatedAttributes.length===0)V.md=Y[K];else V.md=U4.md[U4.pki.oids[K]].create()}J.digestAlgorithmIdentifiers=[];for(var K in Y)J.digestAlgorithmIdentifiers.push(b0.create(b0.Class.UNIVERSAL,b0.Type.SEQUENCE,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.OID,!1,b0.oidToDer(K).getBytes()),b0.create(b0.Class.UNIVERSAL,b0.Type.NULL,!1,"")]));return Y}function Q(Y){var X;if(J.detachedContent)X=J.detachedContent;else X=J.contentInfo.value[1],X=X.value[0];if(!X)throw Error("Could not sign PKCS#7 message; there is no content to sign.");var V=b0.derToOid(J.contentInfo.value[0].value),K=b0.toDer(X);K.getByte(),b0.getBerValueLength(K),K=K.getBytes();for(var z in Y)Y[z].start().update(K);var G=new Date;for(var F=0;F<J.signers.length;++F){var U=J.signers[F];if(U.authenticatedAttributes.length===0){if(V!==U4.pki.oids.data)throw Error("Invalid signer; authenticatedAttributes must be present when the ContentInfo content type is not PKCS#7 Data.")}else{U.authenticatedAttributesAsn1=b0.create(b0.Class.CONTEXT_SPECIFIC,0,!0,[]);var q=b0.create(b0.Class.UNIVERSAL,b0.Type.SET,!0,[]);for(var D=0;D<U.authenticatedAttributes.length;++D){var W=U.authenticatedAttributes[D];if(W.type===U4.pki.oids.messageDigest)W.value=Y[U.digestAlgorithm].digest();else if(W.type===U4.pki.oids.signingTime){if(!W.value)W.value=G}q.value.push(Vl0(W)),U.authenticatedAttributesAsn1.value.push(Vl0(W))}K=b0.toDer(q).getBytes(),U.md.start().update(K)}U.signature=U.key.sign(U.md,"RSASSA-PKCS1-V1_5")}J.signerInfos=D13(J.signers)}};BJ.createEncryptedData=function(){var J=null;return J={type:U4.pki.oids.encryptedData,version:0,encryptedContent:{algorithm:U4.pki.oids["aes256-CBC"]},fromAsn1:function(Z){Kl0(J,Z,BJ.asn1.encryptedDataValidator)},decrypt:function(Z){if(Z!==void 0)J.encryptedContent.key=Z;Qj4(J)}},J};BJ.createEnvelopedData=function(){var J=null;return J={type:U4.pki.oids.envelopedData,version:0,recipients:[],encryptedContent:{algorithm:U4.pki.oids["aes256-CBC"]},fromAsn1:function(Z){var Q=Kl0(J,Z,BJ.asn1.envelopedDataValidator);J.recipients=F13(Q.recipientInfos.value)},toAsn1:function(){return b0.create(b0.Class.UNIVERSAL,b0.Type.SEQUENCE,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.OID,!1,b0.oidToDer(J.type).getBytes()),b0.create(b0.Class.CONTEXT_SPECIFIC,0,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.SEQUENCE,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.INTEGER,!1,b0.integerToDer(J.version).getBytes()),b0.create(b0.Class.UNIVERSAL,b0.Type.SET,!0,U13(J.recipients)),b0.create(b0.Class.UNIVERSAL,b0.Type.SEQUENCE,!0,W13(J.encryptedContent))])])])},findRecipient:function(Z){var Q=Z.issuer.attributes;for(var Y=0;Y<J.recipients.length;++Y){var X=J.recipients[Y],V=X.issuer;if(X.serialNumber!==Z.serialNumber)continue;if(V.length!==Q.length)continue;var K=!0;for(var z=0;z<Q.length;++z)if(V[z].type!==Q[z].type||V[z].value!==Q[z].value){K=!1;break}if(K)return X}return null},decrypt:function(Z,Q){if(J.encryptedContent.key===void 0&&Z!==void 0&&Q!==void 0)switch(Z.encryptedContent.algorithm){case U4.pki.oids.rsaEncryption:case U4.pki.oids.desCBC:var Y=Q.decrypt(Z.encryptedContent.content);J.encryptedContent.key=U4.util.createBuffer(Y);break;default:throw Error("Unsupported asymmetric cipher, OID "+Z.encryptedContent.algorithm)}Qj4(J)},addRecipient:function(Z){J.recipients.push({version:0,issuer:Z.issuer.attributes,serialNumber:Z.serialNumber,encryptedContent:{algorithm:U4.pki.oids.rsaEncryption,key:Z.publicKey}})},encrypt:function(Z,Q){if(J.encryptedContent.content===void 0){Q=Q||J.encryptedContent.algorithm,Z=Z||J.encryptedContent.key;var Y,X,V;switch(Q){case U4.pki.oids["aes128-CBC"]:Y=16,X=16,V=U4.aes.createEncryptionCipher;break;case U4.pki.oids["aes192-CBC"]:Y=24,X=16,V=U4.aes.createEncryptionCipher;break;case U4.pki.oids["aes256-CBC"]:Y=32,X=16,V=U4.aes.createEncryptionCipher;break;case U4.pki.oids["des-EDE3-CBC"]:Y=24,X=8,V=U4.des.createEncryptionCipher;break;default:throw Error("Unsupported symmetric cipher, OID "+Q)}if(Z===void 0)Z=U4.util.createBuffer(U4.random.getBytes(Y));else if(Z.length()!=Y)throw Error("Symmetric key has wrong length; got "+Z.length()+" bytes, expected "+Y+".");J.encryptedContent.algorithm=Q,J.encryptedContent.key=Z,J.encryptedContent.parameter=U4.util.createBuffer(U4.random.getBytes(X));var K=V(Z);if(K.start(J.encryptedContent.parameter.copy()),K.update(J.content),!K.finish())throw Error("Symmetric encryption failed.");J.encryptedContent.content=K.output}for(var z=0;z<J.recipients.length;++z){var G=J.recipients[z];if(G.encryptedContent.content!==void 0)continue;switch(G.encryptedContent.algorithm){case U4.pki.oids.rsaEncryption:G.encryptedContent.content=G.encryptedContent.key.encrypt(J.encryptedContent.key.data);break;default:throw Error("Unsupported asymmetric cipher, OID "+G.encryptedContent.algorithm)}}}},J};function z13(J){var Z={},Q=[];if(!b0.validate(J,BJ.asn1.recipientInfoValidator,Z,Q)){var Y=Error("Cannot read PKCS#7 RecipientInfo. ASN.1 object is not an PKCS#7 RecipientInfo.");throw Y.errors=Q,Y}return{version:Z.version.charCodeAt(0),issuer:U4.pki.RDNAttributesAsArray(Z.issuer),serialNumber:U4.util.createBuffer(Z.serial).toHex(),encryptedContent:{algorithm:b0.derToOid(Z.encAlgorithm),parameter:Z.encParameter?Z.encParameter.value:void 0,content:Z.encKey}}}function G13(J){return b0.create(b0.Class.UNIVERSAL,b0.Type.SEQUENCE,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.INTEGER,!1,b0.integerToDer(J.version).getBytes()),b0.create(b0.Class.UNIVERSAL,b0.Type.SEQUENCE,!0,[U4.pki.distinguishedNameToAsn1({attributes:J.issuer}),b0.create(b0.Class.UNIVERSAL,b0.Type.INTEGER,!1,U4.util.hexToBytes(J.serialNumber))]),b0.create(b0.Class.UNIVERSAL,b0.Type.SEQUENCE,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.OID,!1,b0.oidToDer(J.encryptedContent.algorithm).getBytes()),b0.create(b0.Class.UNIVERSAL,b0.Type.NULL,!1,"")]),b0.create(b0.Class.UNIVERSAL,b0.Type.OCTETSTRING,!1,J.encryptedContent.content)])}function F13(J){var Z=[];for(var Q=0;Q<J.length;++Q)Z.push(z13(J[Q]));return Z}function U13(J){var Z=[];for(var Q=0;Q<J.length;++Q)Z.push(G13(J[Q]));return Z}function q13(J){var Z=b0.create(b0.Class.UNIVERSAL,b0.Type.SEQUENCE,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.INTEGER,!1,b0.integerToDer(J.version).getBytes()),b0.create(b0.Class.UNIVERSAL,b0.Type.SEQUENCE,!0,[U4.pki.distinguishedNameToAsn1({attributes:J.issuer}),b0.create(b0.Class.UNIVERSAL,b0.Type.INTEGER,!1,U4.util.hexToBytes(J.serialNumber))]),b0.create(b0.Class.UNIVERSAL,b0.Type.SEQUENCE,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.OID,!1,b0.oidToDer(J.digestAlgorithm).getBytes()),b0.create(b0.Class.UNIVERSAL,b0.Type.NULL,!1,"")])]);if(J.authenticatedAttributesAsn1)Z.value.push(J.authenticatedAttributesAsn1);if(Z.value.push(b0.create(b0.Class.UNIVERSAL,b0.Type.SEQUENCE,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.OID,!1,b0.oidToDer(J.signatureAlgorithm).getBytes()),b0.create(b0.Class.UNIVERSAL,b0.Type.NULL,!1,"")])),Z.value.push(b0.create(b0.Class.UNIVERSAL,b0.Type.OCTETSTRING,!1,J.signature)),J.unauthenticatedAttributes.length>0){var Q=b0.create(b0.Class.CONTEXT_SPECIFIC,1,!0,[]);for(var Y=0;Y<J.unauthenticatedAttributes.length;++Y){var X=J.unauthenticatedAttributes[Y];Q.values.push(Vl0(X))}Z.value.push(Q)}return Z}function D13(J){var Z=[];for(var Q=0;Q<J.length;++Q)Z.push(q13(J[Q]));return Z}function Vl0(J){var Z;if(J.type===U4.pki.oids.contentType)Z=b0.create(b0.Class.UNIVERSAL,b0.Type.OID,!1,b0.oidToDer(J.value).getBytes());else if(J.type===U4.pki.oids.messageDigest)Z=b0.create(b0.Class.UNIVERSAL,b0.Type.OCTETSTRING,!1,J.value.bytes());else if(J.type===U4.pki.oids.signingTime){var Q=new Date("1950-01-01T00:00:00Z"),Y=new Date("2050-01-01T00:00:00Z"),X=J.value;if(typeof X==="string"){var V=Date.parse(X);if(!isNaN(V))X=new Date(V);else if(X.length===13)X=b0.utcTimeToDate(X);else X=b0.generalizedTimeToDate(X)}if(X>=Q&&X<Y)Z=b0.create(b0.Class.UNIVERSAL,b0.Type.UTCTIME,!1,b0.dateToUtcTime(X));else Z=b0.create(b0.Class.UNIVERSAL,b0.Type.GENERALIZEDTIME,!1,b0.dateToGeneralizedTime(X))}return b0.create(b0.Class.UNIVERSAL,b0.Type.SEQUENCE,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.OID,!1,b0.oidToDer(J.type).getBytes()),b0.create(b0.Class.UNIVERSAL,b0.Type.SET,!0,[Z])])}function W13(J){return[b0.create(b0.Class.UNIVERSAL,b0.Type.OID,!1,b0.oidToDer(U4.pki.oids.data).getBytes()),b0.create(b0.Class.UNIVERSAL,b0.Type.SEQUENCE,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.OID,!1,b0.oidToDer(J.algorithm).getBytes()),!J.parameter?void 0:b0.create(b0.Class.UNIVERSAL,b0.Type.OCTETSTRING,!1,J.parameter.getBytes())]),b0.create(b0.Class.CONTEXT_SPECIFIC,0,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.OCTETSTRING,!1,J.content.getBytes())])]}function Kl0(J,Z,Q){var Y={},X=[];if(!b0.validate(Z,Q,Y,X)){var V=Error("Cannot read PKCS#7 message. ASN.1 object is not a supported PKCS#7 message.");throw V.errors=V,V}var K=b0.derToOid(Y.contentType);if(K!==U4.pki.oids.data)throw Error("Unsupported PKCS#7 message. Only wrapped ContentType Data supported.");if(Y.encryptedContent){var z="";if(U4.util.isArray(Y.encryptedContent))for(var G=0;G<Y.encryptedContent.length;++G){if(Y.encryptedContent[G].type!==b0.Type.OCTETSTRING)throw Error("Malformed PKCS#7 message, expecting encrypted content constructed of only OCTET STRING objects.");z+=Y.encryptedContent[G].value}else z=Y.encryptedContent;J.encryptedContent={algorithm:b0.derToOid(Y.encAlgorithm),parameter:U4.util.createBuffer(Y.encParameter.value),content:U4.util.createBuffer(z)}}if(Y.content){var z="";if(U4.util.isArray(Y.content))for(var G=0;G<Y.content.length;++G){if(Y.content[G].type!==b0.Type.OCTETSTRING)throw Error("Malformed PKCS#7 message, expecting content constructed of only OCTET STRING objects.");z+=Y.content[G].value}else z=Y.content;J.content=U4.util.createBuffer(z)}return J.version=Y.version.charCodeAt(0),J.rawCapture=Y,Y}function Qj4(J){if(J.encryptedContent.key===void 0)throw Error("Symmetric key not available.");if(J.content===void 0){var Z;switch(J.encryptedContent.algorithm){case U4.pki.oids["aes128-CBC"]:case U4.pki.oids["aes192-CBC"]:case U4.pki.oids["aes256-CBC"]:Z=U4.aes.createDecryptionCipher(J.encryptedContent.key);break;case U4.pki.oids.desCBC:case U4.pki.oids["des-EDE3-CBC"]:Z=U4.des.createDecryptionCipher(J.encryptedContent.key);break;default:throw Error("Unsupported symmetric cipher, OID "+J.encryptedContent.algorithm)}if(Z.start(J.encryptedContent.parameter),Z.update(J.encryptedContent.content),!Z.finish())throw Error("Symmetric decryption failed.");J.content=Z.output}}});var Kj4=u((OE9,Vj4)=>{var s9=J5();KB();Y_();uJ0();z_();c5();var XZ0=Vj4.exports=s9.ssh=s9.ssh||{};XZ0.privateKeyToPutty=function(J,Z,Q){Q=Q||"",Z=Z||"";var Y="ssh-rsa",X=Z===""?"none":"aes256-cbc",V="PuTTY-User-Key-File-2: "+Y+`\r
2551
+ `+z+Z.substr(K+1);V=X-K-1,K=-1,++X}else if(Z[X]===" "||Z[X]==="\t"||Z[X]===",")K=X;return Z}function ms5(J){return J.replace(/^\s+/,"")}});var wd=u((lO9,IA4)=>{var x8=J5();CJ0();Fc0();c5();IA4.exports=x8.des=x8.des||{};x8.des.startEncrypting=function(J,Z,Q,Y){var X=bJ0({key:J,output:Q,decrypt:!1,mode:Y||(Z===null?"ECB":"CBC")});return X.start(Z),X};x8.des.createEncryptionCipher=function(J,Z){return bJ0({key:J,output:null,decrypt:!1,mode:Z})};x8.des.startDecrypting=function(J,Z,Q,Y){var X=bJ0({key:J,output:Q,decrypt:!0,mode:Y||(Z===null?"ECB":"CBC")});return X.start(Z),X};x8.des.createDecryptionCipher=function(J,Z){return bJ0({key:J,output:null,decrypt:!0,mode:Z})};x8.des.Algorithm=function(J,Z){var Q=this;Q.name=J,Q.mode=new Z({blockSize:8,cipher:{encrypt:function(Y,X){return AA4(Q._keys,Y,X,!1)},decrypt:function(Y,X){return AA4(Q._keys,Y,X,!0)}}}),Q._init=!1};x8.des.Algorithm.prototype.initialize=function(J){if(this._init)return;var Z=x8.util.createBuffer(J.key);if(this.name.indexOf("3DES")===0){if(Z.length()!==24)throw Error("Invalid Triple-DES key size: "+Z.length()*8)}this._keys=os5(Z),this._init=!0};EG("DES-ECB",x8.cipher.modes.ecb);EG("DES-CBC",x8.cipher.modes.cbc);EG("DES-CFB",x8.cipher.modes.cfb);EG("DES-OFB",x8.cipher.modes.ofb);EG("DES-CTR",x8.cipher.modes.ctr);EG("3DES-ECB",x8.cipher.modes.ecb);EG("3DES-CBC",x8.cipher.modes.cbc);EG("3DES-CFB",x8.cipher.modes.cfb);EG("3DES-OFB",x8.cipher.modes.ofb);EG("3DES-CTR",x8.cipher.modes.ctr);function EG(J,Z){var Q=function(){return new x8.des.Algorithm(J,Z)};x8.cipher.registerAlgorithm(J,Q)}var gs5=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],ps5=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],ds5=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],cs5=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],ls5=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],is5=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],ns5=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],as5=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];function os5(J){var Z=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],Q=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],Y=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],X=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],V=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],K=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],z=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],G=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],F=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],U=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],q=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],D=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],W=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],H=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],B=J.length()>8?3:1,w=[],N=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],O=0,E;for(var L=0;L<B;L++){var M=J.getInt32(),A=J.getInt32();E=(M>>>4^A)&252645135,A^=E,M^=E<<4,E=(A>>>-16^M)&65535,M^=E,A^=E<<-16,E=(M>>>2^A)&858993459,A^=E,M^=E<<2,E=(A>>>-16^M)&65535,M^=E,A^=E<<-16,E=(M>>>1^A)&1431655765,A^=E,M^=E<<1,E=(A>>>8^M)&16711935,M^=E,A^=E<<8,E=(M>>>1^A)&1431655765,A^=E,M^=E<<1,E=M<<8|A>>>20&240,M=A<<24|A<<8&16711680|A>>>8&65280|A>>>24&240,A=E;for(var I=0;I<N.length;++I){if(N[I])M=M<<2|M>>>26,A=A<<2|A>>>26;else M=M<<1|M>>>27,A=A<<1|A>>>27;M&=-15,A&=-15;var P=Z[M>>>28]|Q[M>>>24&15]|Y[M>>>20&15]|X[M>>>16&15]|V[M>>>12&15]|K[M>>>8&15]|z[M>>>4&15],_=G[A>>>28]|F[A>>>24&15]|U[A>>>20&15]|q[A>>>16&15]|D[A>>>12&15]|W[A>>>8&15]|H[A>>>4&15];E=(_>>>16^P)&65535,w[O++]=P^E,w[O++]=_^E<<16}}return w}function AA4(J,Z,Q,Y){var X=J.length===32?3:9,V;if(X===3)V=Y?[30,-2,-2]:[0,32,2];else V=Y?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var K,z=Z[0],G=Z[1];K=(z>>>4^G)&252645135,G^=K,z^=K<<4,K=(z>>>16^G)&65535,G^=K,z^=K<<16,K=(G>>>2^z)&858993459,z^=K,G^=K<<2,K=(G>>>8^z)&16711935,z^=K,G^=K<<8,K=(z>>>1^G)&1431655765,G^=K,z^=K<<1,z=z<<1|z>>>31,G=G<<1|G>>>31;for(var F=0;F<X;F+=3){var U=V[F+1],q=V[F+2];for(var D=V[F];D!=U;D+=q){var W=G^J[D],H=(G>>>4|G<<28)^J[D+1];K=z,z=G,G=K^(ps5[W>>>24&63]|cs5[W>>>16&63]|is5[W>>>8&63]|as5[W&63]|gs5[H>>>24&63]|ds5[H>>>16&63]|ls5[H>>>8&63]|ns5[H&63])}K=z,z=G,G=K}z=z>>>1|z<<31,G=G>>>1|G<<31,K=(z>>>1^G)&1431655765,G^=K,z^=K<<1,K=(G>>>8^z)&16711935,z^=K,G^=K<<8,K=(G>>>2^z)&858993459,z^=K,G^=K<<2,K=(z>>>16^G)&65535,G^=K,z^=K<<16,K=(z>>>4^G)&252645135,G^=K,z^=K<<4,Q[0]=z,Q[1]=G}function bJ0(J){J=J||{};var Z=(J.mode||"CBC").toUpperCase(),Q="DES-"+Z,Y;if(J.decrypt)Y=x8.cipher.createDecipher(Q,J.key);else Y=x8.cipher.createCipher(Q,J.key);var X=Y.start;return Y.start=function(V,K){var z=null;if(K instanceof x8.util.ByteBuffer)z=K,K={};K=K||{},K.output=z,K.iv=V,X.call(Y,K)},Y}});var hJ0=u((iO9,jA4)=>{var WJ=J5();Y_();NG();c5();var rs5=WJ.pkcs5=WJ.pkcs5||{},eU;if(WJ.util.isNodejs&&!WJ.options.usePureJavaScript)eU=j0("crypto");jA4.exports=WJ.pbkdf2=rs5.pbkdf2=function(J,Z,Q,Y,X,V){if(typeof X==="function")V=X,X=null;if(WJ.util.isNodejs&&!WJ.options.usePureJavaScript&&eU.pbkdf2&&(X===null||typeof X!=="object")&&(eU.pbkdf2Sync.length>4||(!X||X==="sha1"))){if(typeof X!=="string")X="sha1";if(J=Buffer.from(J,"binary"),Z=Buffer.from(Z,"binary"),!V){if(eU.pbkdf2Sync.length===4)return eU.pbkdf2Sync(J,Z,Q,Y).toString("binary");return eU.pbkdf2Sync(J,Z,Q,Y,X).toString("binary")}if(eU.pbkdf2Sync.length===4)return eU.pbkdf2(J,Z,Q,Y,function(E,L){if(E)return V(E);V(null,L.toString("binary"))});return eU.pbkdf2(J,Z,Q,Y,X,function(E,L){if(E)return V(E);V(null,L.toString("binary"))})}if(typeof X>"u"||X===null)X="sha1";if(typeof X==="string"){if(!(X in WJ.md.algorithms))throw Error("Unknown hash algorithm: "+X);X=WJ.md[X].create()}var K=X.digestLength;if(Y>4294967295*K){var z=Error("Derived key is too long.");if(V)return V(z);throw z}var G=Math.ceil(Y/K),F=Y-(G-1)*K,U=WJ.hmac.create();U.start(X,J);var q="",D,W,H;if(!V){for(var B=1;B<=G;++B){U.start(null,null),U.update(Z),U.update(WJ.util.int32ToBytes(B)),D=H=U.digest().getBytes();for(var w=2;w<=Q;++w)U.start(null,null),U.update(H),W=U.digest().getBytes(),D=WJ.util.xorBytes(D,W,K),H=W;q+=B<G?D:D.substr(0,F)}return q}var B=1,w;function N(){if(B>G)return V(null,q);U.start(null,null),U.update(Z),U.update(WJ.util.int32ToBytes(B)),D=H=U.digest().getBytes(),w=2,O()}function O(){if(w<=Q)return U.start(null,null),U.update(H),W=U.digest().getBytes(),D=WJ.util.xorBytes(D,W,K),H=W,++w,WJ.util.setImmediate(O);q+=B<G?D:D.substr(0,F),++B,N()}N()}});var wc0=u((nO9,_A4)=>{var LG=J5();NG();c5();var PA4=_A4.exports=LG.sha256=LG.sha256||{};LG.md.sha256=LG.md.algorithms.sha256=PA4;PA4.create=function(){if(!CA4)ss5();var J=null,Z=LG.util.createBuffer(),Q=Array(64),Y={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8};return Y.start=function(){Y.messageLength=0,Y.fullMessageLength=Y.messageLength64=[];var X=Y.messageLengthSize/4;for(var V=0;V<X;++V)Y.fullMessageLength.push(0);return Z=LG.util.createBuffer(),J={h0:1779033703,h1:3144134277,h2:1013904242,h3:2773480762,h4:1359893119,h5:2600822924,h6:528734635,h7:1541459225},Y},Y.start(),Y.update=function(X,V){if(V==="utf8")X=LG.util.encodeUtf8(X);var K=X.length;Y.messageLength+=K,K=[K/4294967296>>>0,K>>>0];for(var z=Y.fullMessageLength.length-1;z>=0;--z)Y.fullMessageLength[z]+=K[1],K[1]=K[0]+(Y.fullMessageLength[z]/4294967296>>>0),Y.fullMessageLength[z]=Y.fullMessageLength[z]>>>0,K[0]=K[1]/4294967296>>>0;if(Z.putBytes(X),RA4(J,Q,Z),Z.read>2048||Z.length()===0)Z.compact();return Y},Y.digest=function(){var X=LG.util.createBuffer();X.putBytes(Z.bytes());var V=Y.fullMessageLength[Y.fullMessageLength.length-1]+Y.messageLengthSize,K=V&Y.blockLength-1;X.putBytes(Bc0.substr(0,Y.blockLength-K));var z,G,F=Y.fullMessageLength[0]*8;for(var U=0;U<Y.fullMessageLength.length-1;++U)z=Y.fullMessageLength[U+1]*8,G=z/4294967296>>>0,F+=G,X.putInt32(F>>>0),F=z>>>0;X.putInt32(F);var q={h0:J.h0,h1:J.h1,h2:J.h2,h3:J.h3,h4:J.h4,h5:J.h5,h6:J.h6,h7:J.h7};RA4(q,Q,X);var D=LG.util.createBuffer();return D.putInt32(q.h0),D.putInt32(q.h1),D.putInt32(q.h2),D.putInt32(q.h3),D.putInt32(q.h4),D.putInt32(q.h5),D.putInt32(q.h6),D.putInt32(q.h7),D},Y};var Bc0=null,CA4=!1,TA4=null;function ss5(){Bc0=String.fromCharCode(128),Bc0+=LG.util.fillString(String.fromCharCode(0),64),TA4=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],CA4=!0}function RA4(J,Z,Q){var Y,X,V,K,z,G,F,U,q,D,W,H,B,w,N,O=Q.length();while(O>=64){for(F=0;F<16;++F)Z[F]=Q.getInt32();for(;F<64;++F)Y=Z[F-2],Y=(Y>>>17|Y<<15)^(Y>>>19|Y<<13)^Y>>>10,X=Z[F-15],X=(X>>>7|X<<25)^(X>>>18|X<<14)^X>>>3,Z[F]=Y+Z[F-7]+X+Z[F-16]|0;U=J.h0,q=J.h1,D=J.h2,W=J.h3,H=J.h4,B=J.h5,w=J.h6,N=J.h7;for(F=0;F<64;++F)K=(H>>>6|H<<26)^(H>>>11|H<<21)^(H>>>25|H<<7),z=w^H&(B^w),V=(U>>>2|U<<30)^(U>>>13|U<<19)^(U>>>22|U<<10),G=U&q|D&(U^q),Y=N+K+z+TA4[F]+Z[F],X=V+G,N=w,w=B,B=H,H=W+Y>>>0,W=D,D=q,q=U,U=Y+X>>>0;J.h0=J.h0+U|0,J.h1=J.h1+q|0,J.h2=J.h2+D|0,J.h3=J.h3+W|0,J.h4=J.h4+H|0,J.h5=J.h5+B|0,J.h6=J.h6+w|0,J.h7=J.h7+N|0,O-=64}}});var Nc0=u((aO9,SA4)=>{var MG=J5();c5();var mJ0=null;if(MG.util.isNodejs&&!MG.options.usePureJavaScript&&!process.versions["node-webkit"])mJ0=j0("crypto");var ts5=SA4.exports=MG.prng=MG.prng||{};ts5.create=function(J){var Z={plugin:J,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},Q=J.md,Y=Array(32);for(var X=0;X<32;++X)Y[X]=Q.create();Z.pools=Y,Z.pool=0,Z.generate=function(F,U){if(!U)return Z.generateSync(F);var q=Z.plugin.cipher,D=Z.plugin.increment,W=Z.plugin.formatKey,H=Z.plugin.formatSeed,B=MG.util.createBuffer();Z.key=null,w();function w(N){if(N)return U(N);if(B.length()>=F)return U(null,B.getBytes(F));if(Z.generated>1048575)Z.key=null;if(Z.key===null)return MG.util.nextTick(function(){V(w)});var O=q(Z.key,Z.seed);Z.generated+=O.length,B.putBytes(O),Z.key=W(q(Z.key,D(Z.seed))),Z.seed=H(q(Z.key,Z.seed)),MG.util.setImmediate(w)}},Z.generateSync=function(F){var U=Z.plugin.cipher,q=Z.plugin.increment,D=Z.plugin.formatKey,W=Z.plugin.formatSeed;Z.key=null;var H=MG.util.createBuffer();while(H.length()<F){if(Z.generated>1048575)Z.key=null;if(Z.key===null)K();var B=U(Z.key,Z.seed);Z.generated+=B.length,H.putBytes(B),Z.key=D(U(Z.key,q(Z.seed))),Z.seed=W(U(Z.key,Z.seed))}return H.getBytes(F)};function V(F){if(Z.pools[0].messageLength>=32)return z(),F();var U=32-Z.pools[0].messageLength<<5;Z.seedFile(U,function(q,D){if(q)return F(q);Z.collect(D),z(),F()})}function K(){if(Z.pools[0].messageLength>=32)return z();var F=32-Z.pools[0].messageLength<<5;Z.collect(Z.seedFileSync(F)),z()}function z(){Z.reseeds=Z.reseeds===4294967295?0:Z.reseeds+1;var F=Z.plugin.md.create();F.update(Z.keyBytes);var U=1;for(var q=0;q<32;++q){if(Z.reseeds%U===0)F.update(Z.pools[q].digest().getBytes()),Z.pools[q].start();U=U<<1}Z.keyBytes=F.digest().getBytes(),F.start(),F.update(Z.keyBytes);var D=F.digest().getBytes();Z.key=Z.plugin.formatKey(Z.keyBytes),Z.seed=Z.plugin.formatSeed(D),Z.generated=0}function G(F){var U=null,q=MG.util.globalScope,D=q.crypto||q.msCrypto;if(D&&D.getRandomValues)U=function(M){return D.getRandomValues(M)};var W=MG.util.createBuffer();if(U)while(W.length()<F){var H=Math.max(1,Math.min(F-W.length(),65536)/4),B=new Uint32Array(Math.floor(H));try{U(B);for(var w=0;w<B.length;++w)W.putInt32(B[w])}catch(M){if(!(typeof QuotaExceededError<"u"&&M instanceof QuotaExceededError))throw M}}if(W.length()<F){var N,O,E,L=Math.floor(Math.random()*65536);while(W.length()<F){O=16807*(L&65535),N=16807*(L>>16),O+=(N&32767)<<16,O+=N>>15,O=(O&2147483647)+(O>>31),L=O&4294967295;for(var w=0;w<3;++w)E=L>>>(w<<3),E^=Math.floor(Math.random()*256),W.putByte(E&255)}}return W.getBytes(F)}if(mJ0)Z.seedFile=function(F,U){mJ0.randomBytes(F,function(q,D){if(q)return U(q);U(null,D.toString())})},Z.seedFileSync=function(F){return mJ0.randomBytes(F).toString()};else Z.seedFile=function(F,U){try{U(null,G(F))}catch(q){U(q)}},Z.seedFileSync=G;return Z.collect=function(F){var U=F.length;for(var q=0;q<U;++q)Z.pools[Z.pool].update(F.substr(q,1)),Z.pool=Z.pool===31?0:Z.pool+1},Z.collectInt=function(F,U){var q="";for(var D=0;D<U;D+=8)q+=String.fromCharCode(F>>D&255);Z.collect(q)},Z.registerWorker=function(F){if(F===self)Z.seedFile=function(q,D){function W(H){var B=H.data;if(B.forge&&B.forge.prng)self.removeEventListener("message",W),D(B.forge.prng.err,B.forge.prng.bytes)}self.addEventListener("message",W),self.postMessage({forge:{prng:{needed:q}}})};else{var U=function(q){var D=q.data;if(D.forge&&D.forge.prng)Z.seedFile(D.forge.prng.needed,function(W,H){F.postMessage({forge:{prng:{err:W,bytes:H}}})})};F.addEventListener("message",U)}},Z}});var JX=u((oO9,Oc0)=>{var r7=J5();KB();wc0();Nc0();c5();(function(){if(r7.random&&r7.random.getBytes){Oc0.exports=r7.random;return}(function(J){var Z={},Q=[,,,,],Y=r7.util.createBuffer();Z.formatKey=function(q){var D=r7.util.createBuffer(q);return q=[,,,,],q[0]=D.getInt32(),q[1]=D.getInt32(),q[2]=D.getInt32(),q[3]=D.getInt32(),r7.aes._expandKey(q,!1)},Z.formatSeed=function(q){var D=r7.util.createBuffer(q);return q=[,,,,],q[0]=D.getInt32(),q[1]=D.getInt32(),q[2]=D.getInt32(),q[3]=D.getInt32(),q},Z.cipher=function(q,D){return r7.aes._updateBlock(q,D,Q,!1),Y.putInt32(Q[0]),Y.putInt32(Q[1]),Y.putInt32(Q[2]),Y.putInt32(Q[3]),Y.getBytes()},Z.increment=function(q){return++q[3],q},Z.md=r7.md.sha256;function X(){var q=r7.prng.create(Z);return q.getBytes=function(D,W){return q.generate(D,W)},q.getBytesSync=function(D){return q.generate(D)},q}var V=X(),K=null,z=r7.util.globalScope,G=z.crypto||z.msCrypto;if(G&&G.getRandomValues)K=function(q){return G.getRandomValues(q)};if(r7.options.usePureJavaScript||!r7.util.isNodejs&&!K){if(typeof window>"u"||window.document===void 0);if(V.collectInt(+new Date,32),typeof navigator<"u"){var F="";for(var U in navigator)try{if(typeof navigator[U]=="string")F+=navigator[U]}catch(q){}V.collect(F),F=null}if(J)J().mousemove(function(q){V.collectInt(q.clientX,16),V.collectInt(q.clientY,16)}),J().keypress(function(q){V.collectInt(q.charCode,8)})}if(!r7.random)r7.random=V;else for(var U in V)r7.random[U]=V[U];r7.random.createInstance=X,Oc0.exports=r7.random})(typeof jQuery<"u"?jQuery:null)})()});var Lc0=u((rO9,yA4)=>{var BZ=J5();c5();var Ec0=[217,120,249,196,25,221,181,237,40,233,253,121,74,160,216,157,198,126,55,131,43,118,83,142,98,76,100,136,68,139,251,162,23,154,89,245,135,179,79,19,97,69,109,141,9,129,125,50,189,143,64,235,134,183,123,11,240,149,33,34,92,107,78,130,84,214,101,147,206,96,178,28,115,86,192,20,167,140,241,220,18,117,202,31,59,190,228,209,66,61,212,48,163,60,182,38,111,191,14,218,70,105,7,87,39,242,29,155,188,148,67,3,248,17,199,246,144,239,62,231,6,195,213,47,200,102,30,215,8,232,234,222,128,82,238,247,132,170,114,172,53,77,106,42,150,26,210,113,90,21,73,116,75,159,208,94,4,24,164,236,194,224,65,110,15,81,203,204,36,145,175,80,161,244,112,57,153,124,58,133,35,184,180,122,252,2,54,91,37,85,151,49,45,93,250,152,227,138,146,174,5,223,41,16,103,108,186,201,211,0,230,207,225,158,168,44,99,22,1,63,88,226,137,169,13,56,52,27,171,51,255,176,187,72,12,95,185,177,205,46,197,243,219,71,229,165,156,119,10,166,32,104,254,127,193,173],vA4=[1,2,3,5],es5=function(J,Z){return J<<Z&65535|(J&65535)>>16-Z},$t5=function(J,Z){return(J&65535)>>Z|J<<16-Z&65535};yA4.exports=BZ.rc2=BZ.rc2||{};BZ.rc2.expandKey=function(J,Z){if(typeof J==="string")J=BZ.util.createBuffer(J);Z=Z||128;var Q=J,Y=J.length(),X=Z,V=Math.ceil(X/8),K=255>>(X&7),z;for(z=Y;z<128;z++)Q.putByte(Ec0[Q.at(z-1)+Q.at(z-Y)&255]);Q.setAt(128-V,Ec0[Q.at(128-V)&K]);for(z=127-V;z>=0;z--)Q.setAt(z,Ec0[Q.at(z+1)^Q.at(z+V)]);return Q};var kA4=function(J,Z,Q){var Y=!1,X=null,V=null,K=null,z,G,F,U,q=[];J=BZ.rc2.expandKey(J,Z);for(F=0;F<64;F++)q.push(J.getInt16Le());if(Q)z=function(H){for(F=0;F<4;F++)H[F]+=q[U]+(H[(F+3)%4]&H[(F+2)%4])+(~H[(F+3)%4]&H[(F+1)%4]),H[F]=es5(H[F],vA4[F]),U++},G=function(H){for(F=0;F<4;F++)H[F]+=q[H[(F+3)%4]&63]};else z=function(H){for(F=3;F>=0;F--)H[F]=$t5(H[F],vA4[F]),H[F]-=q[U]+(H[(F+3)%4]&H[(F+2)%4])+(~H[(F+3)%4]&H[(F+1)%4]),U--},G=function(H){for(F=3;F>=0;F--)H[F]-=q[H[(F+3)%4]&63]};var D=function(H){var B=[];for(F=0;F<4;F++){var w=X.getInt16Le();if(K!==null)if(Q)w^=K.getInt16Le();else K.putInt16Le(w);B.push(w&65535)}U=Q?0:63;for(var N=0;N<H.length;N++)for(var O=0;O<H[N][0];O++)H[N][1](B);for(F=0;F<4;F++){if(K!==null)if(Q)K.putInt16Le(B[F]);else B[F]^=K.getInt16Le();V.putInt16Le(B[F])}},W=null;return W={start:function(H,B){if(H){if(typeof H==="string")H=BZ.util.createBuffer(H)}Y=!1,X=BZ.util.createBuffer(),V=B||new BZ.util.createBuffer,K=H,W.output=V},update:function(H){if(!Y)X.putBuffer(H);while(X.length()>=8)D([[5,z],[1,G],[6,z],[1,G],[5,z]])},finish:function(H){var B=!0;if(Q)if(H)B=H(8,X,!Q);else{var w=X.length()===8?8:8-X.length();X.fillWithByte(w,w)}if(B)Y=!0,W.update();if(!Q){if(B=X.length()===0,B)if(H)B=H(8,V,!Q);else{var N=V.length(),O=V.at(N-1);if(O>N)B=!1;else V.truncate(O)}}return B}},W};BZ.rc2.startEncrypting=function(J,Z,Q){var Y=BZ.rc2.createEncryptionCipher(J,128);return Y.start(Z,Q),Y};BZ.rc2.createEncryptionCipher=function(J,Z){return kA4(J,Z,!0)};BZ.rc2.startDecrypting=function(J,Z,Q){var Y=BZ.rc2.createDecryptionCipher(J,128);return Y.start(Z,Q),Y};BZ.rc2.createDecryptionCipher=function(J,Z){return kA4(J,Z,!1)}});var Od=u((sO9,pA4)=>{var Mc0=J5();pA4.exports=Mc0.jsbn=Mc0.jsbn||{};var $q,Jt5=244837814094590,uA4=(Jt5&16777215)==15715070;function _1(J,Z,Q){if(this.data=[],J!=null)if(typeof J=="number")this.fromNumber(J,Z,Q);else if(Z==null&&typeof J!="string")this.fromString(J,256);else this.fromString(J,Z)}Mc0.jsbn.BigInteger=_1;function l5(){return new _1(null)}function Zt5(J,Z,Q,Y,X,V){while(--V>=0){var K=Z*this.data[J++]+Q.data[Y]+X;X=Math.floor(K/67108864),Q.data[Y++]=K&67108863}return X}function Qt5(J,Z,Q,Y,X,V){var K=Z&32767,z=Z>>15;while(--V>=0){var G=this.data[J]&32767,F=this.data[J++]>>15,U=z*G+F*K;G=K*G+((U&32767)<<15)+Q.data[Y]+(X&1073741823),X=(G>>>30)+(U>>>15)+z*F+(X>>>30),Q.data[Y++]=G&1073741823}return X}function xA4(J,Z,Q,Y,X,V){var K=Z&16383,z=Z>>14;while(--V>=0){var G=this.data[J]&16383,F=this.data[J++]>>14,U=z*G+F*K;G=K*G+((U&16383)<<14)+Q.data[Y]+X,X=(G>>28)+(U>>14)+z*F,Q.data[Y++]=G&268435455}return X}if(typeof navigator>"u")_1.prototype.am=xA4,$q=28;else if(uA4&&navigator.appName=="Microsoft Internet Explorer")_1.prototype.am=Qt5,$q=30;else if(uA4&&navigator.appName!="Netscape")_1.prototype.am=Zt5,$q=26;else _1.prototype.am=xA4,$q=28;_1.prototype.DB=$q;_1.prototype.DM=(1<<$q)-1;_1.prototype.DV=1<<$q;var Ac0=52;_1.prototype.FV=Math.pow(2,Ac0);_1.prototype.F1=Ac0-$q;_1.prototype.F2=2*$q-Ac0;var Yt5="0123456789abcdefghijklmnopqrstuvwxyz",gJ0=[],V_,ZX;V_=48;for(ZX=0;ZX<=9;++ZX)gJ0[V_++]=ZX;V_=97;for(ZX=10;ZX<36;++ZX)gJ0[V_++]=ZX;V_=65;for(ZX=10;ZX<36;++ZX)gJ0[V_++]=ZX;function fA4(J){return Yt5.charAt(J)}function bA4(J,Z){var Q=gJ0[J.charCodeAt(Z)];return Q==null?-1:Q}function Xt5(J){for(var Z=this.t-1;Z>=0;--Z)J.data[Z]=this.data[Z];J.t=this.t,J.s=this.s}function Vt5(J){if(this.t=1,this.s=J<0?-1:0,J>0)this.data[0]=J;else if(J<-1)this.data[0]=J+this.DV;else this.t=0}function GB(J){var Z=l5();return Z.fromInt(J),Z}function Kt5(J,Z){var Q;if(Z==16)Q=4;else if(Z==8)Q=3;else if(Z==256)Q=8;else if(Z==2)Q=1;else if(Z==32)Q=5;else if(Z==4)Q=2;else{this.fromRadix(J,Z);return}this.t=0,this.s=0;var Y=J.length,X=!1,V=0;while(--Y>=0){var K=Q==8?J[Y]&255:bA4(J,Y);if(K<0){if(J.charAt(Y)=="-")X=!0;continue}if(X=!1,V==0)this.data[this.t++]=K;else if(V+Q>this.DB)this.data[this.t-1]|=(K&(1<<this.DB-V)-1)<<V,this.data[this.t++]=K>>this.DB-V;else this.data[this.t-1]|=K<<V;if(V+=Q,V>=this.DB)V-=this.DB}if(Q==8&&(J[0]&128)!=0){if(this.s=-1,V>0)this.data[this.t-1]|=(1<<this.DB-V)-1<<V}if(this.clamp(),X)_1.ZERO.subTo(this,this)}function zt5(){var J=this.s&this.DM;while(this.t>0&&this.data[this.t-1]==J)--this.t}function Gt5(J){if(this.s<0)return"-"+this.negate().toString(J);var Z;if(J==16)Z=4;else if(J==8)Z=3;else if(J==2)Z=1;else if(J==32)Z=5;else if(J==4)Z=2;else return this.toRadix(J);var Q=(1<<Z)-1,Y,X=!1,V="",K=this.t,z=this.DB-K*this.DB%Z;if(K-- >0){if(z<this.DB&&(Y=this.data[K]>>z)>0)X=!0,V=fA4(Y);while(K>=0){if(z<Z)Y=(this.data[K]&(1<<z)-1)<<Z-z,Y|=this.data[--K]>>(z+=this.DB-Z);else if(Y=this.data[K]>>(z-=Z)&Q,z<=0)z+=this.DB,--K;if(Y>0)X=!0;if(X)V+=fA4(Y)}}return X?V:"0"}function Ft5(){var J=l5();return _1.ZERO.subTo(this,J),J}function Ut5(){return this.s<0?this.negate():this}function qt5(J){var Z=this.s-J.s;if(Z!=0)return Z;var Q=this.t;if(Z=Q-J.t,Z!=0)return this.s<0?-Z:Z;while(--Q>=0)if((Z=this.data[Q]-J.data[Q])!=0)return Z;return 0}function pJ0(J){var Z=1,Q;if((Q=J>>>16)!=0)J=Q,Z+=16;if((Q=J>>8)!=0)J=Q,Z+=8;if((Q=J>>4)!=0)J=Q,Z+=4;if((Q=J>>2)!=0)J=Q,Z+=2;if((Q=J>>1)!=0)J=Q,Z+=1;return Z}function Dt5(){if(this.t<=0)return 0;return this.DB*(this.t-1)+pJ0(this.data[this.t-1]^this.s&this.DM)}function Wt5(J,Z){var Q;for(Q=this.t-1;Q>=0;--Q)Z.data[Q+J]=this.data[Q];for(Q=J-1;Q>=0;--Q)Z.data[Q]=0;Z.t=this.t+J,Z.s=this.s}function Ht5(J,Z){for(var Q=J;Q<this.t;++Q)Z.data[Q-J]=this.data[Q];Z.t=Math.max(this.t-J,0),Z.s=this.s}function Bt5(J,Z){var Q=J%this.DB,Y=this.DB-Q,X=(1<<Y)-1,V=Math.floor(J/this.DB),K=this.s<<Q&this.DM,z;for(z=this.t-1;z>=0;--z)Z.data[z+V+1]=this.data[z]>>Y|K,K=(this.data[z]&X)<<Q;for(z=V-1;z>=0;--z)Z.data[z]=0;Z.data[V]=K,Z.t=this.t+V+1,Z.s=this.s,Z.clamp()}function wt5(J,Z){Z.s=this.s;var Q=Math.floor(J/this.DB);if(Q>=this.t){Z.t=0;return}var Y=J%this.DB,X=this.DB-Y,V=(1<<Y)-1;Z.data[0]=this.data[Q]>>Y;for(var K=Q+1;K<this.t;++K)Z.data[K-Q-1]|=(this.data[K]&V)<<X,Z.data[K-Q]=this.data[K]>>Y;if(Y>0)Z.data[this.t-Q-1]|=(this.s&V)<<X;Z.t=this.t-Q,Z.clamp()}function Nt5(J,Z){var Q=0,Y=0,X=Math.min(J.t,this.t);while(Q<X)Y+=this.data[Q]-J.data[Q],Z.data[Q++]=Y&this.DM,Y>>=this.DB;if(J.t<this.t){Y-=J.s;while(Q<this.t)Y+=this.data[Q],Z.data[Q++]=Y&this.DM,Y>>=this.DB;Y+=this.s}else{Y+=this.s;while(Q<J.t)Y-=J.data[Q],Z.data[Q++]=Y&this.DM,Y>>=this.DB;Y-=J.s}if(Z.s=Y<0?-1:0,Y<-1)Z.data[Q++]=this.DV+Y;else if(Y>0)Z.data[Q++]=Y;Z.t=Q,Z.clamp()}function Ot5(J,Z){var Q=this.abs(),Y=J.abs(),X=Q.t;Z.t=X+Y.t;while(--X>=0)Z.data[X]=0;for(X=0;X<Y.t;++X)Z.data[X+Q.t]=Q.am(0,Y.data[X],Z,X,0,Q.t);if(Z.s=0,Z.clamp(),this.s!=J.s)_1.ZERO.subTo(Z,Z)}function Et5(J){var Z=this.abs(),Q=J.t=2*Z.t;while(--Q>=0)J.data[Q]=0;for(Q=0;Q<Z.t-1;++Q){var Y=Z.am(Q,Z.data[Q],J,2*Q,0,1);if((J.data[Q+Z.t]+=Z.am(Q+1,2*Z.data[Q],J,2*Q+1,Y,Z.t-Q-1))>=Z.DV)J.data[Q+Z.t]-=Z.DV,J.data[Q+Z.t+1]=1}if(J.t>0)J.data[J.t-1]+=Z.am(Q,Z.data[Q],J,2*Q,0,1);J.s=0,J.clamp()}function Lt5(J,Z,Q){var Y=J.abs();if(Y.t<=0)return;var X=this.abs();if(X.t<Y.t){if(Z!=null)Z.fromInt(0);if(Q!=null)this.copyTo(Q);return}if(Q==null)Q=l5();var V=l5(),K=this.s,z=J.s,G=this.DB-pJ0(Y.data[Y.t-1]);if(G>0)Y.lShiftTo(G,V),X.lShiftTo(G,Q);else Y.copyTo(V),X.copyTo(Q);var F=V.t,U=V.data[F-1];if(U==0)return;var q=U*(1<<this.F1)+(F>1?V.data[F-2]>>this.F2:0),D=this.FV/q,W=(1<<this.F1)/q,H=1<<this.F2,B=Q.t,w=B-F,N=Z==null?l5():Z;if(V.dlShiftTo(w,N),Q.compareTo(N)>=0)Q.data[Q.t++]=1,Q.subTo(N,Q);_1.ONE.dlShiftTo(F,N),N.subTo(V,V);while(V.t<F)V.data[V.t++]=0;while(--w>=0){var O=Q.data[--B]==U?this.DM:Math.floor(Q.data[B]*D+(Q.data[B-1]+H)*W);if((Q.data[B]+=V.am(0,O,Q,w,0,F))<O){V.dlShiftTo(w,N),Q.subTo(N,Q);while(Q.data[B]<--O)Q.subTo(N,Q)}}if(Z!=null){if(Q.drShiftTo(F,Z),K!=z)_1.ZERO.subTo(Z,Z)}if(Q.t=F,Q.clamp(),G>0)Q.rShiftTo(G,Q);if(K<0)_1.ZERO.subTo(Q,Q)}function Mt5(J){var Z=l5();if(this.abs().divRemTo(J,null,Z),this.s<0&&Z.compareTo(_1.ZERO)>0)J.subTo(Z,Z);return Z}function iL(J){this.m=J}function At5(J){if(J.s<0||J.compareTo(this.m)>=0)return J.mod(this.m);else return J}function It5(J){return J}function jt5(J){J.divRemTo(this.m,null,J)}function Rt5(J,Z,Q){J.multiplyTo(Z,Q),this.reduce(Q)}function Pt5(J,Z){J.squareTo(Z),this.reduce(Z)}iL.prototype.convert=At5;iL.prototype.revert=It5;iL.prototype.reduce=jt5;iL.prototype.mulTo=Rt5;iL.prototype.sqrTo=Pt5;function Ct5(){if(this.t<1)return 0;var J=this.data[0];if((J&1)==0)return 0;var Z=J&3;return Z=Z*(2-(J&15)*Z)&15,Z=Z*(2-(J&255)*Z)&255,Z=Z*(2-((J&65535)*Z&65535))&65535,Z=Z*(2-J*Z%this.DV)%this.DV,Z>0?this.DV-Z:-Z}function nL(J){this.m=J,this.mp=J.invDigit(),this.mpl=this.mp&32767,this.mph=this.mp>>15,this.um=(1<<J.DB-15)-1,this.mt2=2*J.t}function Tt5(J){var Z=l5();if(J.abs().dlShiftTo(this.m.t,Z),Z.divRemTo(this.m,null,Z),J.s<0&&Z.compareTo(_1.ZERO)>0)this.m.subTo(Z,Z);return Z}function _t5(J){var Z=l5();return J.copyTo(Z),this.reduce(Z),Z}function St5(J){while(J.t<=this.mt2)J.data[J.t++]=0;for(var Z=0;Z<this.m.t;++Z){var Q=J.data[Z]&32767,Y=Q*this.mpl+((Q*this.mph+(J.data[Z]>>15)*this.mpl&this.um)<<15)&J.DM;Q=Z+this.m.t,J.data[Q]+=this.m.am(0,Y,J,Z,0,this.m.t);while(J.data[Q]>=J.DV)J.data[Q]-=J.DV,J.data[++Q]++}if(J.clamp(),J.drShiftTo(this.m.t,J),J.compareTo(this.m)>=0)J.subTo(this.m,J)}function vt5(J,Z){J.squareTo(Z),this.reduce(Z)}function kt5(J,Z,Q){J.multiplyTo(Z,Q),this.reduce(Q)}nL.prototype.convert=Tt5;nL.prototype.revert=_t5;nL.prototype.reduce=St5;nL.prototype.mulTo=kt5;nL.prototype.sqrTo=vt5;function yt5(){return(this.t>0?this.data[0]&1:this.s)==0}function ut5(J,Z){if(J>4294967295||J<1)return _1.ONE;var Q=l5(),Y=l5(),X=Z.convert(this),V=pJ0(J)-1;X.copyTo(Q);while(--V>=0)if(Z.sqrTo(Q,Y),(J&1<<V)>0)Z.mulTo(Y,X,Q);else{var K=Q;Q=Y,Y=K}return Z.revert(Q)}function xt5(J,Z){var Q;if(J<256||Z.isEven())Q=new iL(Z);else Q=new nL(Z);return this.exp(J,Q)}_1.prototype.copyTo=Xt5;_1.prototype.fromInt=Vt5;_1.prototype.fromString=Kt5;_1.prototype.clamp=zt5;_1.prototype.dlShiftTo=Wt5;_1.prototype.drShiftTo=Ht5;_1.prototype.lShiftTo=Bt5;_1.prototype.rShiftTo=wt5;_1.prototype.subTo=Nt5;_1.prototype.multiplyTo=Ot5;_1.prototype.squareTo=Et5;_1.prototype.divRemTo=Lt5;_1.prototype.invDigit=Ct5;_1.prototype.isEven=yt5;_1.prototype.exp=ut5;_1.prototype.toString=Gt5;_1.prototype.negate=Ft5;_1.prototype.abs=Ut5;_1.prototype.compareTo=qt5;_1.prototype.bitLength=Dt5;_1.prototype.mod=Mt5;_1.prototype.modPowInt=xt5;_1.ZERO=GB(0);_1.ONE=GB(1);function ft5(){var J=l5();return this.copyTo(J),J}function bt5(){if(this.s<0){if(this.t==1)return this.data[0]-this.DV;else if(this.t==0)return-1}else if(this.t==1)return this.data[0];else if(this.t==0)return 0;return(this.data[1]&(1<<32-this.DB)-1)<<this.DB|this.data[0]}function ht5(){return this.t==0?this.s:this.data[0]<<24>>24}function mt5(){return this.t==0?this.s:this.data[0]<<16>>16}function gt5(J){return Math.floor(Math.LN2*this.DB/Math.log(J))}function pt5(){if(this.s<0)return-1;else if(this.t<=0||this.t==1&&this.data[0]<=0)return 0;else return 1}function dt5(J){if(J==null)J=10;if(this.signum()==0||J<2||J>36)return"0";var Z=this.chunkSize(J),Q=Math.pow(J,Z),Y=GB(Q),X=l5(),V=l5(),K="";this.divRemTo(Y,X,V);while(X.signum()>0)K=(Q+V.intValue()).toString(J).substr(1)+K,X.divRemTo(Y,X,V);return V.intValue().toString(J)+K}function ct5(J,Z){if(this.fromInt(0),Z==null)Z=10;var Q=this.chunkSize(Z),Y=Math.pow(Z,Q),X=!1,V=0,K=0;for(var z=0;z<J.length;++z){var G=bA4(J,z);if(G<0){if(J.charAt(z)=="-"&&this.signum()==0)X=!0;continue}if(K=Z*K+G,++V>=Q)this.dMultiply(Y),this.dAddOffset(K,0),V=0,K=0}if(V>0)this.dMultiply(Math.pow(Z,V)),this.dAddOffset(K,0);if(X)_1.ZERO.subTo(this,this)}function lt5(J,Z,Q){if(typeof Z=="number")if(J<2)this.fromInt(1);else{if(this.fromNumber(J,Q),!this.testBit(J-1))this.bitwiseTo(_1.ONE.shiftLeft(J-1),Ic0,this);if(this.isEven())this.dAddOffset(1,0);while(!this.isProbablePrime(Z))if(this.dAddOffset(2,0),this.bitLength()>J)this.subTo(_1.ONE.shiftLeft(J-1),this)}else{var Y=[],X=J&7;if(Y.length=(J>>3)+1,Z.nextBytes(Y),X>0)Y[0]&=(1<<X)-1;else Y[0]=0;this.fromString(Y,256)}}function it5(){var J=this.t,Z=[];Z[0]=this.s;var Q=this.DB-J*this.DB%8,Y,X=0;if(J-- >0){if(Q<this.DB&&(Y=this.data[J]>>Q)!=(this.s&this.DM)>>Q)Z[X++]=Y|this.s<<this.DB-Q;while(J>=0){if(Q<8)Y=(this.data[J]&(1<<Q)-1)<<8-Q,Y|=this.data[--J]>>(Q+=this.DB-8);else if(Y=this.data[J]>>(Q-=8)&255,Q<=0)Q+=this.DB,--J;if((Y&128)!=0)Y|=-256;if(X==0&&(this.s&128)!=(Y&128))++X;if(X>0||Y!=this.s)Z[X++]=Y}}return Z}function nt5(J){return this.compareTo(J)==0}function at5(J){return this.compareTo(J)<0?this:J}function ot5(J){return this.compareTo(J)>0?this:J}function rt5(J,Z,Q){var Y,X,V=Math.min(J.t,this.t);for(Y=0;Y<V;++Y)Q.data[Y]=Z(this.data[Y],J.data[Y]);if(J.t<this.t){X=J.s&this.DM;for(Y=V;Y<this.t;++Y)Q.data[Y]=Z(this.data[Y],X);Q.t=this.t}else{X=this.s&this.DM;for(Y=V;Y<J.t;++Y)Q.data[Y]=Z(X,J.data[Y]);Q.t=J.t}Q.s=Z(this.s,J.s),Q.clamp()}function st5(J,Z){return J&Z}function tt5(J){var Z=l5();return this.bitwiseTo(J,st5,Z),Z}function Ic0(J,Z){return J|Z}function et5(J){var Z=l5();return this.bitwiseTo(J,Ic0,Z),Z}function hA4(J,Z){return J^Z}function $e5(J){var Z=l5();return this.bitwiseTo(J,hA4,Z),Z}function mA4(J,Z){return J&~Z}function Je5(J){var Z=l5();return this.bitwiseTo(J,mA4,Z),Z}function Ze5(){var J=l5();for(var Z=0;Z<this.t;++Z)J.data[Z]=this.DM&~this.data[Z];return J.t=this.t,J.s=~this.s,J}function Qe5(J){var Z=l5();if(J<0)this.rShiftTo(-J,Z);else this.lShiftTo(J,Z);return Z}function Ye5(J){var Z=l5();if(J<0)this.lShiftTo(-J,Z);else this.rShiftTo(J,Z);return Z}function Xe5(J){if(J==0)return-1;var Z=0;if((J&65535)==0)J>>=16,Z+=16;if((J&255)==0)J>>=8,Z+=8;if((J&15)==0)J>>=4,Z+=4;if((J&3)==0)J>>=2,Z+=2;if((J&1)==0)++Z;return Z}function Ve5(){for(var J=0;J<this.t;++J)if(this.data[J]!=0)return J*this.DB+Xe5(this.data[J]);if(this.s<0)return this.t*this.DB;return-1}function Ke5(J){var Z=0;while(J!=0)J&=J-1,++Z;return Z}function ze5(){var J=0,Z=this.s&this.DM;for(var Q=0;Q<this.t;++Q)J+=Ke5(this.data[Q]^Z);return J}function Ge5(J){var Z=Math.floor(J/this.DB);if(Z>=this.t)return this.s!=0;return(this.data[Z]&1<<J%this.DB)!=0}function Fe5(J,Z){var Q=_1.ONE.shiftLeft(J);return this.bitwiseTo(Q,Z,Q),Q}function Ue5(J){return this.changeBit(J,Ic0)}function qe5(J){return this.changeBit(J,mA4)}function De5(J){return this.changeBit(J,hA4)}function We5(J,Z){var Q=0,Y=0,X=Math.min(J.t,this.t);while(Q<X)Y+=this.data[Q]+J.data[Q],Z.data[Q++]=Y&this.DM,Y>>=this.DB;if(J.t<this.t){Y+=J.s;while(Q<this.t)Y+=this.data[Q],Z.data[Q++]=Y&this.DM,Y>>=this.DB;Y+=this.s}else{Y+=this.s;while(Q<J.t)Y+=J.data[Q],Z.data[Q++]=Y&this.DM,Y>>=this.DB;Y+=J.s}if(Z.s=Y<0?-1:0,Y>0)Z.data[Q++]=Y;else if(Y<-1)Z.data[Q++]=this.DV+Y;Z.t=Q,Z.clamp()}function He5(J){var Z=l5();return this.addTo(J,Z),Z}function Be5(J){var Z=l5();return this.subTo(J,Z),Z}function we5(J){var Z=l5();return this.multiplyTo(J,Z),Z}function Ne5(J){var Z=l5();return this.divRemTo(J,Z,null),Z}function Oe5(J){var Z=l5();return this.divRemTo(J,null,Z),Z}function Ee5(J){var Z=l5(),Q=l5();return this.divRemTo(J,Z,Q),[Z,Q]}function Le5(J){this.data[this.t]=this.am(0,J-1,this,0,0,this.t),++this.t,this.clamp()}function Me5(J,Z){if(J==0)return;while(this.t<=Z)this.data[this.t++]=0;this.data[Z]+=J;while(this.data[Z]>=this.DV){if(this.data[Z]-=this.DV,++Z>=this.t)this.data[this.t++]=0;++this.data[Z]}}function Nd(){}function gA4(J){return J}function Ae5(J,Z,Q){J.multiplyTo(Z,Q)}function Ie5(J,Z){J.squareTo(Z)}Nd.prototype.convert=gA4;Nd.prototype.revert=gA4;Nd.prototype.mulTo=Ae5;Nd.prototype.sqrTo=Ie5;function je5(J){return this.exp(J,new Nd)}function Re5(J,Z,Q){var Y=Math.min(this.t+J.t,Z);Q.s=0,Q.t=Y;while(Y>0)Q.data[--Y]=0;var X;for(X=Q.t-this.t;Y<X;++Y)Q.data[Y+this.t]=this.am(0,J.data[Y],Q,Y,0,this.t);for(X=Math.min(J.t,Z);Y<X;++Y)this.am(0,J.data[Y],Q,Y,0,Z-Y);Q.clamp()}function Pe5(J,Z,Q){--Z;var Y=Q.t=this.t+J.t-Z;Q.s=0;while(--Y>=0)Q.data[Y]=0;for(Y=Math.max(Z-this.t,0);Y<J.t;++Y)Q.data[this.t+Y-Z]=this.am(Z-Y,J.data[Y],Q,0,0,this.t+Y-Z);Q.clamp(),Q.drShiftTo(1,Q)}function K_(J){this.r2=l5(),this.q3=l5(),_1.ONE.dlShiftTo(2*J.t,this.r2),this.mu=this.r2.divide(J),this.m=J}function Ce5(J){if(J.s<0||J.t>2*this.m.t)return J.mod(this.m);else if(J.compareTo(this.m)<0)return J;else{var Z=l5();return J.copyTo(Z),this.reduce(Z),Z}}function Te5(J){return J}function _e5(J){if(J.drShiftTo(this.m.t-1,this.r2),J.t>this.m.t+1)J.t=this.m.t+1,J.clamp();this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);while(J.compareTo(this.r2)<0)J.dAddOffset(1,this.m.t+1);J.subTo(this.r2,J);while(J.compareTo(this.m)>=0)J.subTo(this.m,J)}function Se5(J,Z){J.squareTo(Z),this.reduce(Z)}function ve5(J,Z,Q){J.multiplyTo(Z,Q),this.reduce(Q)}K_.prototype.convert=Ce5;K_.prototype.revert=Te5;K_.prototype.reduce=_e5;K_.prototype.mulTo=ve5;K_.prototype.sqrTo=Se5;function ke5(J,Z){var Q=J.bitLength(),Y,X=GB(1),V;if(Q<=0)return X;else if(Q<18)Y=1;else if(Q<48)Y=3;else if(Q<144)Y=4;else if(Q<768)Y=5;else Y=6;if(Q<8)V=new iL(Z);else if(Z.isEven())V=new K_(Z);else V=new nL(Z);var K=[],z=3,G=Y-1,F=(1<<Y)-1;if(K[1]=V.convert(this),Y>1){var U=l5();V.sqrTo(K[1],U);while(z<=F)K[z]=l5(),V.mulTo(U,K[z-2],K[z]),z+=2}var q=J.t-1,D,W=!0,H=l5(),B;Q=pJ0(J.data[q])-1;while(q>=0){if(Q>=G)D=J.data[q]>>Q-G&F;else if(D=(J.data[q]&(1<<Q+1)-1)<<G-Q,q>0)D|=J.data[q-1]>>this.DB+Q-G;z=Y;while((D&1)==0)D>>=1,--z;if((Q-=z)<0)Q+=this.DB,--q;if(W)K[D].copyTo(X),W=!1;else{while(z>1)V.sqrTo(X,H),V.sqrTo(H,X),z-=2;if(z>0)V.sqrTo(X,H);else B=X,X=H,H=B;V.mulTo(H,K[D],X)}while(q>=0&&(J.data[q]&1<<Q)==0)if(V.sqrTo(X,H),B=X,X=H,H=B,--Q<0)Q=this.DB-1,--q}return V.revert(X)}function ye5(J){var Z=this.s<0?this.negate():this.clone(),Q=J.s<0?J.negate():J.clone();if(Z.compareTo(Q)<0){var Y=Z;Z=Q,Q=Y}var X=Z.getLowestSetBit(),V=Q.getLowestSetBit();if(V<0)return Z;if(X<V)V=X;if(V>0)Z.rShiftTo(V,Z),Q.rShiftTo(V,Q);while(Z.signum()>0){if((X=Z.getLowestSetBit())>0)Z.rShiftTo(X,Z);if((X=Q.getLowestSetBit())>0)Q.rShiftTo(X,Q);if(Z.compareTo(Q)>=0)Z.subTo(Q,Z),Z.rShiftTo(1,Z);else Q.subTo(Z,Q),Q.rShiftTo(1,Q)}if(V>0)Q.lShiftTo(V,Q);return Q}function ue5(J){if(J<=0)return 0;var Z=this.DV%J,Q=this.s<0?J-1:0;if(this.t>0)if(Z==0)Q=this.data[0]%J;else for(var Y=this.t-1;Y>=0;--Y)Q=(Z*Q+this.data[Y])%J;return Q}function xe5(J){var Z=J.isEven();if(this.isEven()&&Z||J.signum()==0)return _1.ZERO;var Q=J.clone(),Y=this.clone(),X=GB(1),V=GB(0),K=GB(0),z=GB(1);while(Q.signum()!=0){while(Q.isEven()){if(Q.rShiftTo(1,Q),Z){if(!X.isEven()||!V.isEven())X.addTo(this,X),V.subTo(J,V);X.rShiftTo(1,X)}else if(!V.isEven())V.subTo(J,V);V.rShiftTo(1,V)}while(Y.isEven()){if(Y.rShiftTo(1,Y),Z){if(!K.isEven()||!z.isEven())K.addTo(this,K),z.subTo(J,z);K.rShiftTo(1,K)}else if(!z.isEven())z.subTo(J,z);z.rShiftTo(1,z)}if(Q.compareTo(Y)>=0){if(Q.subTo(Y,Q),Z)X.subTo(K,X);V.subTo(z,V)}else{if(Y.subTo(Q,Y),Z)K.subTo(X,K);z.subTo(V,z)}}if(Y.compareTo(_1.ONE)!=0)return _1.ZERO;if(z.compareTo(J)>=0)return z.subtract(J);if(z.signum()<0)z.addTo(J,z);else return z;if(z.signum()<0)return z.add(J);else return z}var rV=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509],fe5=67108864/rV[rV.length-1];function be5(J){var Z,Q=this.abs();if(Q.t==1&&Q.data[0]<=rV[rV.length-1]){for(Z=0;Z<rV.length;++Z)if(Q.data[0]==rV[Z])return!0;return!1}if(Q.isEven())return!1;Z=1;while(Z<rV.length){var Y=rV[Z],X=Z+1;while(X<rV.length&&Y<fe5)Y*=rV[X++];Y=Q.modInt(Y);while(Z<X)if(Y%rV[Z++]==0)return!1}return Q.millerRabin(J)}function he5(J){var Z=this.subtract(_1.ONE),Q=Z.getLowestSetBit();if(Q<=0)return!1;var Y=Z.shiftRight(Q),X=me5(),V;for(var K=0;K<J;++K){do V=new _1(this.bitLength(),X);while(V.compareTo(_1.ONE)<=0||V.compareTo(Z)>=0);var z=V.modPow(Y,this);if(z.compareTo(_1.ONE)!=0&&z.compareTo(Z)!=0){var G=1;while(G++<Q&&z.compareTo(Z)!=0)if(z=z.modPowInt(2,this),z.compareTo(_1.ONE)==0)return!1;if(z.compareTo(Z)!=0)return!1}}return!0}function me5(){return{nextBytes:function(J){for(var Z=0;Z<J.length;++Z)J[Z]=Math.floor(Math.random()*256)}}}_1.prototype.chunkSize=gt5;_1.prototype.toRadix=dt5;_1.prototype.fromRadix=ct5;_1.prototype.fromNumber=lt5;_1.prototype.bitwiseTo=rt5;_1.prototype.changeBit=Fe5;_1.prototype.addTo=We5;_1.prototype.dMultiply=Le5;_1.prototype.dAddOffset=Me5;_1.prototype.multiplyLowerTo=Re5;_1.prototype.multiplyUpperTo=Pe5;_1.prototype.modInt=ue5;_1.prototype.millerRabin=he5;_1.prototype.clone=ft5;_1.prototype.intValue=bt5;_1.prototype.byteValue=ht5;_1.prototype.shortValue=mt5;_1.prototype.signum=pt5;_1.prototype.toByteArray=it5;_1.prototype.equals=nt5;_1.prototype.min=at5;_1.prototype.max=ot5;_1.prototype.and=tt5;_1.prototype.or=et5;_1.prototype.xor=$e5;_1.prototype.andNot=Je5;_1.prototype.not=Ze5;_1.prototype.shiftLeft=Qe5;_1.prototype.shiftRight=Ye5;_1.prototype.getLowestSetBit=Ve5;_1.prototype.bitCount=ze5;_1.prototype.testBit=Ge5;_1.prototype.setBit=Ue5;_1.prototype.clearBit=qe5;_1.prototype.flipBit=De5;_1.prototype.add=He5;_1.prototype.subtract=Be5;_1.prototype.multiply=we5;_1.prototype.divide=Ne5;_1.prototype.remainder=Oe5;_1.prototype.divideAndRemainder=Ee5;_1.prototype.modPow=ke5;_1.prototype.modInverse=xe5;_1.prototype.pow=je5;_1.prototype.gcd=ye5;_1.prototype.isProbablePrime=be5});var z_=u((tO9,iA4)=>{var AG=J5();NG();c5();var cA4=iA4.exports=AG.sha1=AG.sha1||{};AG.md.sha1=AG.md.algorithms.sha1=cA4;cA4.create=function(){if(!lA4)ge5();var J=null,Z=AG.util.createBuffer(),Q=Array(80),Y={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8};return Y.start=function(){Y.messageLength=0,Y.fullMessageLength=Y.messageLength64=[];var X=Y.messageLengthSize/4;for(var V=0;V<X;++V)Y.fullMessageLength.push(0);return Z=AG.util.createBuffer(),J={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878,h4:3285377520},Y},Y.start(),Y.update=function(X,V){if(V==="utf8")X=AG.util.encodeUtf8(X);var K=X.length;Y.messageLength+=K,K=[K/4294967296>>>0,K>>>0];for(var z=Y.fullMessageLength.length-1;z>=0;--z)Y.fullMessageLength[z]+=K[1],K[1]=K[0]+(Y.fullMessageLength[z]/4294967296>>>0),Y.fullMessageLength[z]=Y.fullMessageLength[z]>>>0,K[0]=K[1]/4294967296>>>0;if(Z.putBytes(X),dA4(J,Q,Z),Z.read>2048||Z.length()===0)Z.compact();return Y},Y.digest=function(){var X=AG.util.createBuffer();X.putBytes(Z.bytes());var V=Y.fullMessageLength[Y.fullMessageLength.length-1]+Y.messageLengthSize,K=V&Y.blockLength-1;X.putBytes(jc0.substr(0,Y.blockLength-K));var z,G,F=Y.fullMessageLength[0]*8;for(var U=0;U<Y.fullMessageLength.length-1;++U)z=Y.fullMessageLength[U+1]*8,G=z/4294967296>>>0,F+=G,X.putInt32(F>>>0),F=z>>>0;X.putInt32(F);var q={h0:J.h0,h1:J.h1,h2:J.h2,h3:J.h3,h4:J.h4};dA4(q,Q,X);var D=AG.util.createBuffer();return D.putInt32(q.h0),D.putInt32(q.h1),D.putInt32(q.h2),D.putInt32(q.h3),D.putInt32(q.h4),D},Y};var jc0=null,lA4=!1;function ge5(){jc0=String.fromCharCode(128),jc0+=AG.util.fillString(String.fromCharCode(0),64),lA4=!0}function dA4(J,Z,Q){var Y,X,V,K,z,G,F,U,q=Q.length();while(q>=64){X=J.h0,V=J.h1,K=J.h2,z=J.h3,G=J.h4;for(U=0;U<16;++U)Y=Q.getInt32(),Z[U]=Y,F=z^V&(K^z),Y=(X<<5|X>>>27)+F+G+1518500249+Y,G=z,z=K,K=(V<<30|V>>>2)>>>0,V=X,X=Y;for(;U<20;++U)Y=Z[U-3]^Z[U-8]^Z[U-14]^Z[U-16],Y=Y<<1|Y>>>31,Z[U]=Y,F=z^V&(K^z),Y=(X<<5|X>>>27)+F+G+1518500249+Y,G=z,z=K,K=(V<<30|V>>>2)>>>0,V=X,X=Y;for(;U<32;++U)Y=Z[U-3]^Z[U-8]^Z[U-14]^Z[U-16],Y=Y<<1|Y>>>31,Z[U]=Y,F=V^K^z,Y=(X<<5|X>>>27)+F+G+1859775393+Y,G=z,z=K,K=(V<<30|V>>>2)>>>0,V=X,X=Y;for(;U<40;++U)Y=Z[U-6]^Z[U-16]^Z[U-28]^Z[U-32],Y=Y<<2|Y>>>30,Z[U]=Y,F=V^K^z,Y=(X<<5|X>>>27)+F+G+1859775393+Y,G=z,z=K,K=(V<<30|V>>>2)>>>0,V=X,X=Y;for(;U<60;++U)Y=Z[U-6]^Z[U-16]^Z[U-28]^Z[U-32],Y=Y<<2|Y>>>30,Z[U]=Y,F=V&K|z&(V^K),Y=(X<<5|X>>>27)+F+G+2400959708+Y,G=z,z=K,K=(V<<30|V>>>2)>>>0,V=X,X=Y;for(;U<80;++U)Y=Z[U-6]^Z[U-16]^Z[U-28]^Z[U-32],Y=Y<<2|Y>>>30,Z[U]=Y,F=V^K^z,Y=(X<<5|X>>>27)+F+G+3395469782+Y,G=z,z=K,K=(V<<30|V>>>2)>>>0,V=X,X=Y;J.h0=J.h0+X|0,J.h1=J.h1+V|0,J.h2=J.h2+K|0,J.h3=J.h3+z|0,J.h4=J.h4+G|0,q-=64}}});var Rc0=u((eO9,aA4)=>{var IG=J5();c5();JX();z_();var nA4=aA4.exports=IG.pkcs1=IG.pkcs1||{};nA4.encode_rsa_oaep=function(J,Z,Q){var Y,X,V,K;if(typeof Q==="string")Y=Q,X=arguments[3]||void 0,V=arguments[4]||void 0;else if(Q){if(Y=Q.label||void 0,X=Q.seed||void 0,V=Q.md||void 0,Q.mgf1&&Q.mgf1.md)K=Q.mgf1.md}if(!V)V=IG.md.sha1.create();else V.start();if(!K)K=V;var z=Math.ceil(J.n.bitLength()/8),G=z-2*V.digestLength-2;if(Z.length>G){var F=Error("RSAES-OAEP input message length is too long.");throw F.length=Z.length,F.maxLength=G,F}if(!Y)Y="";V.update(Y,"raw");var U=V.digest(),q="",D=G-Z.length;for(var W=0;W<D;W++)q+="\x00";var H=U.getBytes()+q+"\x01"+Z;if(!X)X=IG.random.getBytes(V.digestLength);else if(X.length!==V.digestLength){var F=Error("Invalid RSAES-OAEP seed. The seed length must match the digest length.");throw F.seedLength=X.length,F.digestLength=V.digestLength,F}var B=dJ0(X,z-V.digestLength-1,K),w=IG.util.xorBytes(H,B,H.length),N=dJ0(w,V.digestLength,K),O=IG.util.xorBytes(X,N,X.length);return"\x00"+O+w};nA4.decode_rsa_oaep=function(J,Z,Q){var Y,X,V;if(typeof Q==="string")Y=Q,X=arguments[3]||void 0;else if(Q){if(Y=Q.label||void 0,X=Q.md||void 0,Q.mgf1&&Q.mgf1.md)V=Q.mgf1.md}var K=Math.ceil(J.n.bitLength()/8);if(Z.length!==K){var w=Error("RSAES-OAEP encoded message length is invalid.");throw w.length=Z.length,w.expectedLength=K,w}if(X===void 0)X=IG.md.sha1.create();else X.start();if(!V)V=X;if(K<2*X.digestLength+2)throw Error("RSAES-OAEP key is too short for the hash function.");if(!Y)Y="";X.update(Y,"raw");var z=X.digest().getBytes(),G=Z.charAt(0),F=Z.substring(1,X.digestLength+1),U=Z.substring(1+X.digestLength),q=dJ0(U,X.digestLength,V),D=IG.util.xorBytes(F,q,F.length),W=dJ0(D,K-X.digestLength-1,V),H=IG.util.xorBytes(U,W,U.length),B=H.substring(0,X.digestLength),w=G!=="\x00";for(var N=0;N<X.digestLength;++N)w|=z.charAt(N)!==B.charAt(N);var O=1,E=X.digestLength;for(var L=X.digestLength;L<H.length;L++){var M=H.charCodeAt(L),A=M&1^1,I=O?65534:0;w|=M&I,O=O&A,E+=O}if(w||H.charCodeAt(E)!==1)throw Error("Invalid RSAES-OAEP padding.");return H.substring(E+1)};function dJ0(J,Z,Q){if(!Q)Q=IG.md.sha1.create();var Y="",X=Math.ceil(Z/Q.digestLength);for(var V=0;V<X;++V){var K=String.fromCharCode(V>>24&255,V>>16&255,V>>8&255,V&255);Q.start(),Q.update(J+K),Y+=Q.digest().getBytes()}return Y.substring(0,Z)}});var Cc0=u(($E9,Pc0)=>{var FB=J5();c5();Od();JX();(function(){if(FB.prime){Pc0.exports=FB.prime;return}var J=Pc0.exports=FB.prime=FB.prime||{},Z=FB.jsbn.BigInteger,Q=[6,4,2,4,2,4,6,2],Y=new Z(null);Y.fromInt(30);var X=function(q,D){return q|D};J.generateProbablePrime=function(q,D,W){if(typeof D==="function")W=D,D={};D=D||{};var H=D.algorithm||"PRIMEINC";if(typeof H==="string")H={name:H};H.options=H.options||{};var B=D.prng||FB.random,w={nextBytes:function(N){var O=B.getBytesSync(N.length);for(var E=0;E<N.length;++E)N[E]=O.charCodeAt(E)}};if(H.name==="PRIMEINC")return V(q,w,H.options,W);throw Error("Invalid prime generation algorithm: "+H.name)};function V(q,D,W,H){if("workers"in W)return G(q,D,W,H);return K(q,D,W,H)}function K(q,D,W,H){var B=F(q,D),w=0,N=U(B.bitLength());if("millerRabinTests"in W)N=W.millerRabinTests;var O=10;if("maxBlockTime"in W)O=W.maxBlockTime;z(B,q,D,w,N,O,H)}function z(q,D,W,H,B,w,N){var O=+new Date;do{if(q.bitLength()>D)q=F(D,W);if(q.isProbablePrime(B))return N(null,q);q.dAddOffset(Q[H++%8],0)}while(w<0||+new Date-O<w);FB.util.setImmediate(function(){z(q,D,W,H,B,w,N)})}function G(q,D,W,H){if(typeof Worker>"u")return K(q,D,W,H);var B=F(q,D),w=W.workers,N=W.workLoad||100,O=N*30/8,E=W.workerScript||"forge/prime.worker.js";if(w===-1)return FB.util.estimateCores(function(M,A){if(M)A=2;w=A-1,L()});L();function L(){w=Math.max(1,w);var M=[];for(var A=0;A<w;++A)M[A]=new Worker(E);var I=w;for(var A=0;A<w;++A)M[A].addEventListener("message",_);var P=!1;function _(S){if(P)return;--I;var y=S.data;if(y.found){for(var m=0;m<M.length;++m)M[m].terminate();return P=!0,H(null,new Z(y.prime,16))}if(B.bitLength()>q)B=F(q,D);var b=B.toString(16);S.target.postMessage({hex:b,workLoad:N}),B.dAddOffset(O,0)}}}function F(q,D){var W=new Z(q,D),H=q-1;if(!W.testBit(H))W.bitwiseTo(Z.ONE.shiftLeft(H),X,W);return W.dAddOffset(31-W.mod(Y).byteValue(),0),W}function U(q){if(q<=100)return 27;if(q<=150)return 18;if(q<=200)return 15;if(q<=250)return 12;if(q<=300)return 9;if(q<=350)return 8;if(q<=400)return 7;if(q<=500)return 6;if(q<=600)return 5;if(q<=800)return 4;if(q<=1250)return 3;return 2}})()});var Ed=u((JE9,JI4)=>{var Z6=J5();oV();Od();zB();Rc0();Cc0();JX();c5();if(typeof _5>"u")_5=Z6.jsbn.BigInteger;var _5,Tc0=Z6.util.isNodejs?j0("crypto"):null,Q1=Z6.asn1,QX=Z6.util;Z6.pki=Z6.pki||{};JI4.exports=Z6.pki.rsa=Z6.rsa=Z6.rsa||{};var g6=Z6.pki,pe5=[6,4,2,4,2,4,6,2],de5={name:"PrivateKeyInfo",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},ce5={name:"RSAPrivateKey",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},le5={name:"RSAPublicKey",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},ie5=Z6.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},ne5={name:"DigestInfo",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:Q1.Class.UNIVERSAL,type:Q1.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},ae5=function(J){var Z;if(J.algorithm in g6.oids)Z=g6.oids[J.algorithm];else{var Q=Error("Unknown message digest algorithm.");throw Q.algorithm=J.algorithm,Q}var Y=Q1.oidToDer(Z).getBytes(),X=Q1.create(Q1.Class.UNIVERSAL,Q1.Type.SEQUENCE,!0,[]),V=Q1.create(Q1.Class.UNIVERSAL,Q1.Type.SEQUENCE,!0,[]);V.value.push(Q1.create(Q1.Class.UNIVERSAL,Q1.Type.OID,!1,Y)),V.value.push(Q1.create(Q1.Class.UNIVERSAL,Q1.Type.NULL,!1,""));var K=Q1.create(Q1.Class.UNIVERSAL,Q1.Type.OCTETSTRING,!1,J.digest().getBytes());return X.value.push(V),X.value.push(K),Q1.toDer(X).getBytes()},eA4=function(J,Z,Q){if(Q)return J.modPow(Z.e,Z.n);if(!Z.p||!Z.q)return J.modPow(Z.d,Z.n);if(!Z.dP)Z.dP=Z.d.mod(Z.p.subtract(_5.ONE));if(!Z.dQ)Z.dQ=Z.d.mod(Z.q.subtract(_5.ONE));if(!Z.qInv)Z.qInv=Z.q.modInverse(Z.p);var Y;do Y=new _5(Z6.util.bytesToHex(Z6.random.getBytes(Z.n.bitLength()/8)),16);while(Y.compareTo(Z.n)>=0||!Y.gcd(Z.n).equals(_5.ONE));J=J.multiply(Y.modPow(Z.e,Z.n)).mod(Z.n);var X=J.mod(Z.p).modPow(Z.dP,Z.p),V=J.mod(Z.q).modPow(Z.dQ,Z.q);while(X.compareTo(V)<0)X=X.add(Z.p);var K=X.subtract(V).multiply(Z.qInv).mod(Z.p).multiply(Z.q).add(V);return K=K.multiply(Y.modInverse(Z.n)).mod(Z.n),K};g6.rsa.encrypt=function(J,Z,Q){var Y=Q,X,V=Math.ceil(Z.n.bitLength()/8);if(Q!==!1&&Q!==!0)Y=Q===2,X=$I4(J,Z,Q);else X=Z6.util.createBuffer(),X.putBytes(J);var K=new _5(X.toHex(),16),z=eA4(K,Z,Y),G=z.toString(16),F=Z6.util.createBuffer(),U=V-Math.ceil(G.length/2);while(U>0)F.putByte(0),--U;return F.putBytes(Z6.util.hexToBytes(G)),F.getBytes()};g6.rsa.decrypt=function(J,Z,Q,Y){var X=Math.ceil(Z.n.bitLength()/8);if(J.length!==X){var V=Error("Encrypted message length is invalid.");throw V.length=J.length,V.expected=X,V}var K=new _5(Z6.util.createBuffer(J).toHex(),16);if(K.compareTo(Z.n)>=0)throw Error("Encrypted message is invalid.");var z=eA4(K,Z,Q),G=z.toString(16),F=Z6.util.createBuffer(),U=X-Math.ceil(G.length/2);while(U>0)F.putByte(0),--U;if(F.putBytes(Z6.util.hexToBytes(G)),Y!==!1)return cJ0(F.getBytes(),Z,Q);return F.getBytes()};g6.rsa.createKeyPairGenerationState=function(J,Z,Q){if(typeof J==="string")J=parseInt(J,10);J=J||2048,Q=Q||{};var Y=Q.prng||Z6.random,X={nextBytes:function(z){var G=Y.getBytesSync(z.length);for(var F=0;F<z.length;++F)z[F]=G.charCodeAt(F)}},V=Q.algorithm||"PRIMEINC",K;if(V==="PRIMEINC")K={algorithm:V,state:0,bits:J,rng:X,eInt:Z||65537,e:new _5(null),p:null,q:null,qBits:J>>1,pBits:J-(J>>1),pqState:0,num:null,keys:null},K.e.fromInt(K.eInt);else throw Error("Invalid key generation algorithm: "+V);return K};g6.rsa.stepKeyPairGenerationState=function(J,Z){if(!("algorithm"in J))J.algorithm="PRIMEINC";var Q=new _5(null);Q.fromInt(30);var Y=0,X=function(q,D){return q|D},V=+new Date,K,z=0;while(J.keys===null&&(Z<=0||z<Z)){if(J.state===0){var G=J.p===null?J.pBits:J.qBits,F=G-1;if(J.pqState===0){if(J.num=new _5(G,J.rng),!J.num.testBit(F))J.num.bitwiseTo(_5.ONE.shiftLeft(F),X,J.num);J.num.dAddOffset(31-J.num.mod(Q).byteValue(),0),Y=0,++J.pqState}else if(J.pqState===1)if(J.num.bitLength()>G)J.pqState=0;else if(J.num.isProbablePrime(re5(J.num.bitLength())))++J.pqState;else J.num.dAddOffset(pe5[Y++%8],0);else if(J.pqState===2)J.pqState=J.num.subtract(_5.ONE).gcd(J.e).compareTo(_5.ONE)===0?3:0;else if(J.pqState===3){if(J.pqState=0,J.p===null)J.p=J.num;else J.q=J.num;if(J.p!==null&&J.q!==null)++J.state;J.num=null}}else if(J.state===1){if(J.p.compareTo(J.q)<0)J.num=J.p,J.p=J.q,J.q=J.num;++J.state}else if(J.state===2)J.p1=J.p.subtract(_5.ONE),J.q1=J.q.subtract(_5.ONE),J.phi=J.p1.multiply(J.q1),++J.state;else if(J.state===3)if(J.phi.gcd(J.e).compareTo(_5.ONE)===0)++J.state;else J.p=null,J.q=null,J.state=0;else if(J.state===4)if(J.n=J.p.multiply(J.q),J.n.bitLength()===J.bits)++J.state;else J.q=null,J.state=0;else if(J.state===5){var U=J.e.modInverse(J.phi);J.keys={privateKey:g6.rsa.setPrivateKey(J.n,J.e,U,J.p,J.q,U.mod(J.p1),U.mod(J.q1),J.q.modInverse(J.p)),publicKey:g6.rsa.setPublicKey(J.n,J.e)}}K=+new Date,z+=K-V,V=K}return J.keys!==null};g6.rsa.generateKeyPair=function(J,Z,Q,Y){if(arguments.length===1){if(typeof J==="object")Q=J,J=void 0;else if(typeof J==="function")Y=J,J=void 0}else if(arguments.length===2)if(typeof J==="number"){if(typeof Z==="function")Y=Z,Z=void 0;else if(typeof Z!=="number")Q=Z,Z=void 0}else Q=J,Y=Z,J=void 0,Z=void 0;else if(arguments.length===3)if(typeof Z==="number"){if(typeof Q==="function")Y=Q,Q=void 0}else Y=Q,Q=Z,Z=void 0;if(Q=Q||{},J===void 0)J=Q.bits||2048;if(Z===void 0)Z=Q.e||65537;if(!Z6.options.usePureJavaScript&&!Q.prng&&J>=256&&J<=16384&&(Z===65537||Z===3)){if(Y){if(oA4("generateKeyPair"))return Tc0.generateKeyPair("rsa",{modulusLength:J,publicExponent:Z,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},function(z,G,F){if(z)return Y(z);Y(null,{privateKey:g6.privateKeyFromPem(F),publicKey:g6.publicKeyFromPem(G)})});if(rA4("generateKey")&&rA4("exportKey"))return QX.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:J,publicExponent:tA4(Z),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(z){return QX.globalScope.crypto.subtle.exportKey("pkcs8",z.privateKey)}).then(void 0,function(z){Y(z)}).then(function(z){if(z){var G=g6.privateKeyFromAsn1(Q1.fromDer(Z6.util.createBuffer(z)));Y(null,{privateKey:G,publicKey:g6.setRsaPublicKey(G.n,G.e)})}});if(sA4("generateKey")&&sA4("exportKey")){var X=QX.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:J,publicExponent:tA4(Z),hash:{name:"SHA-256"}},!0,["sign","verify"]);X.oncomplete=function(z){var G=z.target.result,F=QX.globalScope.msCrypto.subtle.exportKey("pkcs8",G.privateKey);F.oncomplete=function(U){var q=U.target.result,D=g6.privateKeyFromAsn1(Q1.fromDer(Z6.util.createBuffer(q)));Y(null,{privateKey:D,publicKey:g6.setRsaPublicKey(D.n,D.e)})},F.onerror=function(U){Y(U)}},X.onerror=function(z){Y(z)};return}}else if(oA4("generateKeyPairSync")){var V=Tc0.generateKeyPairSync("rsa",{modulusLength:J,publicExponent:Z,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:g6.privateKeyFromPem(V.privateKey),publicKey:g6.publicKeyFromPem(V.publicKey)}}}var K=g6.rsa.createKeyPairGenerationState(J,Z,Q);if(!Y)return g6.rsa.stepKeyPairGenerationState(K,0),K.keys;oe5(K,Q,Y)};g6.setRsaPublicKey=g6.rsa.setPublicKey=function(J,Z){var Q={n:J,e:Z};return Q.encrypt=function(Y,X,V){if(typeof X==="string")X=X.toUpperCase();else if(X===void 0)X="RSAES-PKCS1-V1_5";if(X==="RSAES-PKCS1-V1_5")X={encode:function(z,G,F){return $I4(z,G,2).getBytes()}};else if(X==="RSA-OAEP"||X==="RSAES-OAEP")X={encode:function(z,G){return Z6.pkcs1.encode_rsa_oaep(G,z,V)}};else if(["RAW","NONE","NULL",null].indexOf(X)!==-1)X={encode:function(z){return z}};else if(typeof X==="string")throw Error('Unsupported encryption scheme: "'+X+'".');var K=X.encode(Y,Q,!0);return g6.rsa.encrypt(K,Q,!0)},Q.verify=function(Y,X,V,K){if(typeof V==="string")V=V.toUpperCase();else if(V===void 0)V="RSASSA-PKCS1-V1_5";if(K===void 0)K={_parseAllDigestBytes:!0};if(!("_parseAllDigestBytes"in K))K._parseAllDigestBytes=!0;if(V==="RSASSA-PKCS1-V1_5")V={verify:function(G,F){F=cJ0(F,Q,!0);var U=Q1.fromDer(F,{parseAllBytes:K._parseAllDigestBytes}),q={},D=[];if(!Q1.validate(U,ne5,q,D)){var W=Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.");throw W.errors=D,W}var H=Q1.derToOid(q.algorithmIdentifier);if(!(H===Z6.oids.md2||H===Z6.oids.md5||H===Z6.oids.sha1||H===Z6.oids.sha224||H===Z6.oids.sha256||H===Z6.oids.sha384||H===Z6.oids.sha512||H===Z6.oids["sha512-224"]||H===Z6.oids["sha512-256"])){var W=Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.");throw W.oid=H,W}if(H===Z6.oids.md2||H===Z6.oids.md5){if(!("parameters"in q))throw Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifier NULL parameters.")}return G===q.digest}};else if(V==="NONE"||V==="NULL"||V===null)V={verify:function(G,F){return F=cJ0(F,Q,!0),G===F}};var z=g6.rsa.decrypt(X,Q,!0,!1);return V.verify(Y,z,Q.n.bitLength())},Q};g6.setRsaPrivateKey=g6.rsa.setPrivateKey=function(J,Z,Q,Y,X,V,K,z){var G={n:J,e:Z,d:Q,p:Y,q:X,dP:V,dQ:K,qInv:z};return G.decrypt=function(F,U,q){if(typeof U==="string")U=U.toUpperCase();else if(U===void 0)U="RSAES-PKCS1-V1_5";var D=g6.rsa.decrypt(F,G,!1,!1);if(U==="RSAES-PKCS1-V1_5")U={decode:cJ0};else if(U==="RSA-OAEP"||U==="RSAES-OAEP")U={decode:function(W,H){return Z6.pkcs1.decode_rsa_oaep(H,W,q)}};else if(["RAW","NONE","NULL",null].indexOf(U)!==-1)U={decode:function(W){return W}};else throw Error('Unsupported encryption scheme: "'+U+'".');return U.decode(D,G,!1)},G.sign=function(F,U){var q=!1;if(typeof U==="string")U=U.toUpperCase();if(U===void 0||U==="RSASSA-PKCS1-V1_5")U={encode:ae5},q=1;else if(U==="NONE"||U==="NULL"||U===null)U={encode:function(){return F}},q=1;var D=U.encode(F,G.n.bitLength());return g6.rsa.encrypt(D,G,q)},G};g6.wrapRsaPrivateKey=function(J){return Q1.create(Q1.Class.UNIVERSAL,Q1.Type.SEQUENCE,!0,[Q1.create(Q1.Class.UNIVERSAL,Q1.Type.INTEGER,!1,Q1.integerToDer(0).getBytes()),Q1.create(Q1.Class.UNIVERSAL,Q1.Type.SEQUENCE,!0,[Q1.create(Q1.Class.UNIVERSAL,Q1.Type.OID,!1,Q1.oidToDer(g6.oids.rsaEncryption).getBytes()),Q1.create(Q1.Class.UNIVERSAL,Q1.Type.NULL,!1,"")]),Q1.create(Q1.Class.UNIVERSAL,Q1.Type.OCTETSTRING,!1,Q1.toDer(J).getBytes())])};g6.privateKeyFromAsn1=function(J){var Z={},Q=[];if(Q1.validate(J,de5,Z,Q))J=Q1.fromDer(Z6.util.createBuffer(Z.privateKey));if(Z={},Q=[],!Q1.validate(J,ce5,Z,Q)){var Y=Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw Y.errors=Q,Y}var X,V,K,z,G,F,U,q;return X=Z6.util.createBuffer(Z.privateKeyModulus).toHex(),V=Z6.util.createBuffer(Z.privateKeyPublicExponent).toHex(),K=Z6.util.createBuffer(Z.privateKeyPrivateExponent).toHex(),z=Z6.util.createBuffer(Z.privateKeyPrime1).toHex(),G=Z6.util.createBuffer(Z.privateKeyPrime2).toHex(),F=Z6.util.createBuffer(Z.privateKeyExponent1).toHex(),U=Z6.util.createBuffer(Z.privateKeyExponent2).toHex(),q=Z6.util.createBuffer(Z.privateKeyCoefficient).toHex(),g6.setRsaPrivateKey(new _5(X,16),new _5(V,16),new _5(K,16),new _5(z,16),new _5(G,16),new _5(F,16),new _5(U,16),new _5(q,16))};g6.privateKeyToAsn1=g6.privateKeyToRSAPrivateKey=function(J){return Q1.create(Q1.Class.UNIVERSAL,Q1.Type.SEQUENCE,!0,[Q1.create(Q1.Class.UNIVERSAL,Q1.Type.INTEGER,!1,Q1.integerToDer(0).getBytes()),Q1.create(Q1.Class.UNIVERSAL,Q1.Type.INTEGER,!1,jG(J.n)),Q1.create(Q1.Class.UNIVERSAL,Q1.Type.INTEGER,!1,jG(J.e)),Q1.create(Q1.Class.UNIVERSAL,Q1.Type.INTEGER,!1,jG(J.d)),Q1.create(Q1.Class.UNIVERSAL,Q1.Type.INTEGER,!1,jG(J.p)),Q1.create(Q1.Class.UNIVERSAL,Q1.Type.INTEGER,!1,jG(J.q)),Q1.create(Q1.Class.UNIVERSAL,Q1.Type.INTEGER,!1,jG(J.dP)),Q1.create(Q1.Class.UNIVERSAL,Q1.Type.INTEGER,!1,jG(J.dQ)),Q1.create(Q1.Class.UNIVERSAL,Q1.Type.INTEGER,!1,jG(J.qInv))])};g6.publicKeyFromAsn1=function(J){var Z={},Q=[];if(Q1.validate(J,ie5,Z,Q)){var Y=Q1.derToOid(Z.publicKeyOid);if(Y!==g6.oids.rsaEncryption){var X=Error("Cannot read public key. Unknown OID.");throw X.oid=Y,X}J=Z.rsaPublicKey}if(Q=[],!Q1.validate(J,le5,Z,Q)){var X=Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.");throw X.errors=Q,X}var V=Z6.util.createBuffer(Z.publicKeyModulus).toHex(),K=Z6.util.createBuffer(Z.publicKeyExponent).toHex();return g6.setRsaPublicKey(new _5(V,16),new _5(K,16))};g6.publicKeyToAsn1=g6.publicKeyToSubjectPublicKeyInfo=function(J){return Q1.create(Q1.Class.UNIVERSAL,Q1.Type.SEQUENCE,!0,[Q1.create(Q1.Class.UNIVERSAL,Q1.Type.SEQUENCE,!0,[Q1.create(Q1.Class.UNIVERSAL,Q1.Type.OID,!1,Q1.oidToDer(g6.oids.rsaEncryption).getBytes()),Q1.create(Q1.Class.UNIVERSAL,Q1.Type.NULL,!1,"")]),Q1.create(Q1.Class.UNIVERSAL,Q1.Type.BITSTRING,!1,[g6.publicKeyToRSAPublicKey(J)])])};g6.publicKeyToRSAPublicKey=function(J){return Q1.create(Q1.Class.UNIVERSAL,Q1.Type.SEQUENCE,!0,[Q1.create(Q1.Class.UNIVERSAL,Q1.Type.INTEGER,!1,jG(J.n)),Q1.create(Q1.Class.UNIVERSAL,Q1.Type.INTEGER,!1,jG(J.e))])};function $I4(J,Z,Q){var Y=Z6.util.createBuffer(),X=Math.ceil(Z.n.bitLength()/8);if(J.length>X-11){var V=Error("Message is too long for PKCS#1 v1.5 padding.");throw V.length=J.length,V.max=X-11,V}Y.putByte(0),Y.putByte(Q);var K=X-3-J.length,z;if(Q===0||Q===1){z=Q===0?0:255;for(var G=0;G<K;++G)Y.putByte(z)}else while(K>0){var F=0,U=Z6.random.getBytes(K);for(var G=0;G<K;++G)if(z=U.charCodeAt(G),z===0)++F;else Y.putByte(z);K=F}return Y.putByte(0),Y.putBytes(J),Y}function cJ0(J,Z,Q,Y){var X=Math.ceil(Z.n.bitLength()/8),V=Z6.util.createBuffer(J),K=V.getByte(),z=V.getByte();if(K!==0||Q&&z!==0&&z!==1||!Q&&z!=2||Q&&z===0&&typeof Y>"u")throw Error("Encryption block is invalid.");var G=0;if(z===0){G=X-3-Y;for(var F=0;F<G;++F)if(V.getByte()!==0)throw Error("Encryption block is invalid.")}else if(z===1){G=0;while(V.length()>1){if(V.getByte()!==255){--V.read;break}++G}}else if(z===2){G=0;while(V.length()>1){if(V.getByte()===0){--V.read;break}++G}}var U=V.getByte();if(U!==0||G!==X-3-V.length())throw Error("Encryption block is invalid.");return V.getBytes()}function oe5(J,Z,Q){if(typeof Z==="function")Q=Z,Z={};Z=Z||{};var Y={algorithm:{name:Z.algorithm||"PRIMEINC",options:{workers:Z.workers||2,workLoad:Z.workLoad||100,workerScript:Z.workerScript}}};if("prng"in Z)Y.prng=Z.prng;X();function X(){V(J.pBits,function(z,G){if(z)return Q(z);if(J.p=G,J.q!==null)return K(z,J.q);V(J.qBits,K)})}function V(z,G){Z6.prime.generateProbablePrime(z,Y,G)}function K(z,G){if(z)return Q(z);if(J.q=G,J.p.compareTo(J.q)<0){var F=J.p;J.p=J.q,J.q=F}if(J.p.subtract(_5.ONE).gcd(J.e).compareTo(_5.ONE)!==0){J.p=null,X();return}if(J.q.subtract(_5.ONE).gcd(J.e).compareTo(_5.ONE)!==0){J.q=null,V(J.qBits,K);return}if(J.p1=J.p.subtract(_5.ONE),J.q1=J.q.subtract(_5.ONE),J.phi=J.p1.multiply(J.q1),J.phi.gcd(J.e).compareTo(_5.ONE)!==0){J.p=J.q=null,X();return}if(J.n=J.p.multiply(J.q),J.n.bitLength()!==J.bits){J.q=null,V(J.qBits,K);return}var U=J.e.modInverse(J.phi);J.keys={privateKey:g6.rsa.setPrivateKey(J.n,J.e,U,J.p,J.q,U.mod(J.p1),U.mod(J.q1),J.q.modInverse(J.p)),publicKey:g6.rsa.setPublicKey(J.n,J.e)},Q(null,J.keys)}}function jG(J){var Z=J.toString(16);if(Z[0]>="8")Z="00"+Z;var Q=Z6.util.hexToBytes(Z);if(Q.length>1&&(Q.charCodeAt(0)===0&&(Q.charCodeAt(1)&128)===0||Q.charCodeAt(0)===255&&(Q.charCodeAt(1)&128)===128))return Q.substr(1);return Q}function re5(J){if(J<=100)return 27;if(J<=150)return 18;if(J<=200)return 15;if(J<=250)return 12;if(J<=300)return 9;if(J<=350)return 8;if(J<=400)return 7;if(J<=500)return 6;if(J<=600)return 5;if(J<=800)return 4;if(J<=1250)return 3;return 2}function oA4(J){return Z6.util.isNodejs&&typeof Tc0[J]==="function"}function rA4(J){return typeof QX.globalScope<"u"&&typeof QX.globalScope.crypto==="object"&&typeof QX.globalScope.crypto.subtle==="object"&&typeof QX.globalScope.crypto.subtle[J]==="function"}function sA4(J){return typeof QX.globalScope<"u"&&typeof QX.globalScope.msCrypto==="object"&&typeof QX.globalScope.msCrypto.subtle==="object"&&typeof QX.globalScope.msCrypto.subtle[J]==="function"}function tA4(J){var Z=Z6.util.hexToBytes(J.toString(16)),Q=new Uint8Array(Z.length);for(var Y=0;Y<Z.length;++Y)Q[Y]=Z.charCodeAt(Y);return Q}});var Sc0=u((ZE9,XI4)=>{var R4=J5();KB();oV();wd();NG();zB();hJ0();lL();JX();Lc0();Ed();c5();if(typeof _c0>"u")_c0=R4.jsbn.BigInteger;var _c0,O1=R4.asn1,n6=R4.pki=R4.pki||{};XI4.exports=n6.pbe=R4.pbe=R4.pbe||{};var aL=n6.oids,se5={name:"EncryptedPrivateKeyInfo",tagClass:O1.Class.UNIVERSAL,type:O1.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:O1.Class.UNIVERSAL,type:O1.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:O1.Class.UNIVERSAL,type:O1.Type.OID,constructed:!1,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:O1.Class.UNIVERSAL,type:O1.Type.SEQUENCE,constructed:!0,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:O1.Class.UNIVERSAL,type:O1.Type.OCTETSTRING,constructed:!1,capture:"encryptedData"}]},te5={name:"PBES2Algorithms",tagClass:O1.Class.UNIVERSAL,type:O1.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:O1.Class.UNIVERSAL,type:O1.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:O1.Class.UNIVERSAL,type:O1.Type.OID,constructed:!1,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:O1.Class.UNIVERSAL,type:O1.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.params.salt",tagClass:O1.Class.UNIVERSAL,type:O1.Type.OCTETSTRING,constructed:!1,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:O1.Class.UNIVERSAL,type:O1.Type.INTEGER,constructed:!1,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:O1.Class.UNIVERSAL,type:O1.Type.INTEGER,constructed:!1,optional:!0,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:O1.Class.UNIVERSAL,type:O1.Type.SEQUENCE,constructed:!0,optional:!0,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:O1.Class.UNIVERSAL,type:O1.Type.OID,constructed:!1,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:O1.Class.UNIVERSAL,type:O1.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:O1.Class.UNIVERSAL,type:O1.Type.OID,constructed:!1,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:O1.Class.UNIVERSAL,type:O1.Type.OCTETSTRING,constructed:!1,capture:"encIv"}]}]},ee5={name:"pkcs-12PbeParams",tagClass:O1.Class.UNIVERSAL,type:O1.Type.SEQUENCE,constructed:!0,value:[{name:"pkcs-12PbeParams.salt",tagClass:O1.Class.UNIVERSAL,type:O1.Type.OCTETSTRING,constructed:!1,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:O1.Class.UNIVERSAL,type:O1.Type.INTEGER,constructed:!1,capture:"iterations"}]};n6.encryptPrivateKeyInfo=function(J,Z,Q){Q=Q||{},Q.saltSize=Q.saltSize||8,Q.count=Q.count||2048,Q.algorithm=Q.algorithm||"aes128",Q.prfAlgorithm=Q.prfAlgorithm||"sha1";var Y=R4.random.getBytesSync(Q.saltSize),X=Q.count,V=O1.integerToDer(X),K,z,G;if(Q.algorithm.indexOf("aes")===0||Q.algorithm==="des"){var F,U,q;switch(Q.algorithm){case"aes128":K=16,F=16,U=aL["aes128-CBC"],q=R4.aes.createEncryptionCipher;break;case"aes192":K=24,F=16,U=aL["aes192-CBC"],q=R4.aes.createEncryptionCipher;break;case"aes256":K=32,F=16,U=aL["aes256-CBC"],q=R4.aes.createEncryptionCipher;break;case"des":K=8,F=8,U=aL.desCBC,q=R4.des.createEncryptionCipher;break;default:var D=Error("Cannot encrypt private key. Unknown encryption algorithm.");throw D.algorithm=Q.algorithm,D}var W="hmacWith"+Q.prfAlgorithm.toUpperCase(),H=YI4(W),B=R4.pkcs5.pbkdf2(Z,Y,X,K,H),w=R4.random.getBytesSync(F),N=q(B);N.start(w),N.update(O1.toDer(J)),N.finish(),G=N.output.getBytes();var O=$03(Y,V,K,W);z=O1.create(O1.Class.UNIVERSAL,O1.Type.SEQUENCE,!0,[O1.create(O1.Class.UNIVERSAL,O1.Type.OID,!1,O1.oidToDer(aL.pkcs5PBES2).getBytes()),O1.create(O1.Class.UNIVERSAL,O1.Type.SEQUENCE,!0,[O1.create(O1.Class.UNIVERSAL,O1.Type.SEQUENCE,!0,[O1.create(O1.Class.UNIVERSAL,O1.Type.OID,!1,O1.oidToDer(aL.pkcs5PBKDF2).getBytes()),O]),O1.create(O1.Class.UNIVERSAL,O1.Type.SEQUENCE,!0,[O1.create(O1.Class.UNIVERSAL,O1.Type.OID,!1,O1.oidToDer(U).getBytes()),O1.create(O1.Class.UNIVERSAL,O1.Type.OCTETSTRING,!1,w)])])])}else if(Q.algorithm==="3des"){K=24;var E=new R4.util.ByteBuffer(Y),B=n6.pbe.generatePkcs12Key(Z,E,1,X,K),w=n6.pbe.generatePkcs12Key(Z,E,2,X,K),N=R4.des.createEncryptionCipher(B);N.start(w),N.update(O1.toDer(J)),N.finish(),G=N.output.getBytes(),z=O1.create(O1.Class.UNIVERSAL,O1.Type.SEQUENCE,!0,[O1.create(O1.Class.UNIVERSAL,O1.Type.OID,!1,O1.oidToDer(aL["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),O1.create(O1.Class.UNIVERSAL,O1.Type.SEQUENCE,!0,[O1.create(O1.Class.UNIVERSAL,O1.Type.OCTETSTRING,!1,Y),O1.create(O1.Class.UNIVERSAL,O1.Type.INTEGER,!1,V.getBytes())])])}else{var D=Error("Cannot encrypt private key. Unknown encryption algorithm.");throw D.algorithm=Q.algorithm,D}var L=O1.create(O1.Class.UNIVERSAL,O1.Type.SEQUENCE,!0,[z,O1.create(O1.Class.UNIVERSAL,O1.Type.OCTETSTRING,!1,G)]);return L};n6.decryptPrivateKeyInfo=function(J,Z){var Q=null,Y={},X=[];if(!O1.validate(J,se5,Y,X)){var V=Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw V.errors=X,V}var K=O1.derToOid(Y.encryptionOid),z=n6.pbe.getCipher(K,Y.encryptionParams,Z),G=R4.util.createBuffer(Y.encryptedData);if(z.update(G),z.finish())Q=O1.fromDer(z.output);return Q};n6.encryptedPrivateKeyToPem=function(J,Z){var Q={type:"ENCRYPTED PRIVATE KEY",body:O1.toDer(J).getBytes()};return R4.pem.encode(Q,{maxline:Z})};n6.encryptedPrivateKeyFromPem=function(J){var Z=R4.pem.decode(J)[0];if(Z.type!=="ENCRYPTED PRIVATE KEY"){var Q=Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".');throw Q.headerType=Z.type,Q}if(Z.procType&&Z.procType.type==="ENCRYPTED")throw Error("Could not convert encrypted private key from PEM; PEM is encrypted.");return O1.fromDer(Z.body)};n6.encryptRsaPrivateKey=function(J,Z,Q){if(Q=Q||{},!Q.legacy){var Y=n6.wrapRsaPrivateKey(n6.privateKeyToAsn1(J));return Y=n6.encryptPrivateKeyInfo(Y,Z,Q),n6.encryptedPrivateKeyToPem(Y)}var X,V,K,z;switch(Q.algorithm){case"aes128":X="AES-128-CBC",K=16,V=R4.random.getBytesSync(16),z=R4.aes.createEncryptionCipher;break;case"aes192":X="AES-192-CBC",K=24,V=R4.random.getBytesSync(16),z=R4.aes.createEncryptionCipher;break;case"aes256":X="AES-256-CBC",K=32,V=R4.random.getBytesSync(16),z=R4.aes.createEncryptionCipher;break;case"3des":X="DES-EDE3-CBC",K=24,V=R4.random.getBytesSync(8),z=R4.des.createEncryptionCipher;break;case"des":X="DES-CBC",K=8,V=R4.random.getBytesSync(8),z=R4.des.createEncryptionCipher;break;default:var G=Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+Q.algorithm+'".');throw G.algorithm=Q.algorithm,G}var F=R4.pbe.opensslDeriveBytes(Z,V.substr(0,8),K),U=z(F);U.start(V),U.update(O1.toDer(n6.privateKeyToAsn1(J))),U.finish();var q={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:X,parameters:R4.util.bytesToHex(V).toUpperCase()},body:U.output.getBytes()};return R4.pem.encode(q)};n6.decryptRsaPrivateKey=function(J,Z){var Q=null,Y=R4.pem.decode(J)[0];if(Y.type!=="ENCRYPTED PRIVATE KEY"&&Y.type!=="PRIVATE KEY"&&Y.type!=="RSA PRIVATE KEY"){var X=Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".');throw X.headerType=X,X}if(Y.procType&&Y.procType.type==="ENCRYPTED"){var V,K;switch(Y.dekInfo.algorithm){case"DES-CBC":V=8,K=R4.des.createDecryptionCipher;break;case"DES-EDE3-CBC":V=24,K=R4.des.createDecryptionCipher;break;case"AES-128-CBC":V=16,K=R4.aes.createDecryptionCipher;break;case"AES-192-CBC":V=24,K=R4.aes.createDecryptionCipher;break;case"AES-256-CBC":V=32,K=R4.aes.createDecryptionCipher;break;case"RC2-40-CBC":V=5,K=function(q){return R4.rc2.createDecryptionCipher(q,40)};break;case"RC2-64-CBC":V=8,K=function(q){return R4.rc2.createDecryptionCipher(q,64)};break;case"RC2-128-CBC":V=16,K=function(q){return R4.rc2.createDecryptionCipher(q,128)};break;default:var X=Error('Could not decrypt private key; unsupported encryption algorithm "'+Y.dekInfo.algorithm+'".');throw X.algorithm=Y.dekInfo.algorithm,X}var z=R4.util.hexToBytes(Y.dekInfo.parameters),G=R4.pbe.opensslDeriveBytes(Z,z.substr(0,8),V),F=K(G);if(F.start(z),F.update(R4.util.createBuffer(Y.body)),F.finish())Q=F.output.getBytes();else return Q}else Q=Y.body;if(Y.type==="ENCRYPTED PRIVATE KEY")Q=n6.decryptPrivateKeyInfo(O1.fromDer(Q),Z);else Q=O1.fromDer(Q);if(Q!==null)Q=n6.privateKeyFromAsn1(Q);return Q};n6.pbe.generatePkcs12Key=function(J,Z,Q,Y,X,V){var K,z;if(typeof V>"u"||V===null){if(!("sha1"in R4.md))throw Error('"sha1" hash algorithm unavailable.');V=R4.md.sha1.create()}var{digestLength:G,blockLength:F}=V,U=new R4.util.ByteBuffer,q=new R4.util.ByteBuffer;if(J!==null&&J!==void 0){for(z=0;z<J.length;z++)q.putInt16(J.charCodeAt(z));q.putInt16(0)}var D=q.length(),W=Z.length(),H=new R4.util.ByteBuffer;H.fillWithByte(Q,F);var B=F*Math.ceil(W/F),w=new R4.util.ByteBuffer;for(z=0;z<B;z++)w.putByte(Z.at(z%W));var N=F*Math.ceil(D/F),O=new R4.util.ByteBuffer;for(z=0;z<N;z++)O.putByte(q.at(z%D));var E=w;E.putBuffer(O);var L=Math.ceil(X/G);for(var M=1;M<=L;M++){var A=new R4.util.ByteBuffer;A.putBytes(H.bytes()),A.putBytes(E.bytes());for(var I=0;I<Y;I++)V.start(),V.update(A.getBytes()),A=V.digest();var P=new R4.util.ByteBuffer;for(z=0;z<F;z++)P.putByte(A.at(z%G));var _=Math.ceil(W/F)+Math.ceil(D/F),S=new R4.util.ByteBuffer;for(K=0;K<_;K++){var y=new R4.util.ByteBuffer(E.getBytes(F)),m=511;for(z=P.length()-1;z>=0;z--)m=m>>8,m+=P.at(z)+y.at(z),y.setAt(z,m&255);S.putBuffer(y)}E=S,U.putBuffer(A)}return U.truncate(U.length()-X),U};n6.pbe.getCipher=function(J,Z,Q){switch(J){case n6.oids.pkcs5PBES2:return n6.pbe.getCipherForPBES2(J,Z,Q);case n6.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case n6.oids["pbewithSHAAnd40BitRC2-CBC"]:return n6.pbe.getCipherForPKCS12PBE(J,Z,Q);default:var Y=Error("Cannot read encrypted PBE data block. Unsupported OID.");throw Y.oid=J,Y.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],Y}};n6.pbe.getCipherForPBES2=function(J,Z,Q){var Y={},X=[];if(!O1.validate(Z,te5,Y,X)){var V=Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw V.errors=X,V}if(J=O1.derToOid(Y.kdfOid),J!==n6.oids.pkcs5PBKDF2){var V=Error("Cannot read encrypted private key. Unsupported key derivation function OID.");throw V.oid=J,V.supportedOids=["pkcs5PBKDF2"],V}if(J=O1.derToOid(Y.encOid),J!==n6.oids["aes128-CBC"]&&J!==n6.oids["aes192-CBC"]&&J!==n6.oids["aes256-CBC"]&&J!==n6.oids["des-EDE3-CBC"]&&J!==n6.oids.desCBC){var V=Error("Cannot read encrypted private key. Unsupported encryption scheme OID.");throw V.oid=J,V.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],V}var K=Y.kdfSalt,z=R4.util.createBuffer(Y.kdfIterationCount);z=z.getInt(z.length()<<3);var G,F;switch(n6.oids[J]){case"aes128-CBC":G=16,F=R4.aes.createDecryptionCipher;break;case"aes192-CBC":G=24,F=R4.aes.createDecryptionCipher;break;case"aes256-CBC":G=32,F=R4.aes.createDecryptionCipher;break;case"des-EDE3-CBC":G=24,F=R4.des.createDecryptionCipher;break;case"desCBC":G=8,F=R4.des.createDecryptionCipher;break}var U=QI4(Y.prfOid),q=R4.pkcs5.pbkdf2(Q,K,z,G,U),D=Y.encIv,W=F(q);return W.start(D),W};n6.pbe.getCipherForPKCS12PBE=function(J,Z,Q){var Y={},X=[];if(!O1.validate(Z,ee5,Y,X)){var V=Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw V.errors=X,V}var K=R4.util.createBuffer(Y.salt),z=R4.util.createBuffer(Y.iterations);z=z.getInt(z.length()<<3);var G,F,U;switch(J){case n6.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:G=24,F=8,U=R4.des.startDecrypting;break;case n6.oids["pbewithSHAAnd40BitRC2-CBC"]:G=5,F=8,U=function(B,w){var N=R4.rc2.createDecryptionCipher(B,40);return N.start(w,null),N};break;default:var V=Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");throw V.oid=J,V}var q=QI4(Y.prfOid),D=n6.pbe.generatePkcs12Key(Q,K,1,z,G,q);q.start();var W=n6.pbe.generatePkcs12Key(Q,K,2,z,F,q);return U(D,W)};n6.pbe.opensslDeriveBytes=function(J,Z,Q,Y){if(typeof Y>"u"||Y===null){if(!("md5"in R4.md))throw Error('"md5" hash algorithm unavailable.');Y=R4.md.md5.create()}if(Z===null)Z="";var X=[ZI4(Y,J+Z)];for(var V=16,K=1;V<Q;++K,V+=16)X.push(ZI4(Y,X[K-1]+J+Z));return X.join("").substr(0,Q)};function ZI4(J,Z){return J.start().update(Z).digest().getBytes()}function QI4(J){var Z;if(!J)Z="hmacWithSHA1";else if(Z=n6.oids[O1.derToOid(J)],!Z){var Q=Error("Unsupported PRF OID.");throw Q.oid=J,Q.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],Q}return YI4(Z)}function YI4(J){var Z=R4.md;switch(J){case"hmacWithSHA224":Z=R4.md.sha512;case"hmacWithSHA1":case"hmacWithSHA256":case"hmacWithSHA384":case"hmacWithSHA512":J=J.substr(8).toLowerCase();break;default:var Q=Error("Unsupported PRF algorithm.");throw Q.algorithm=J,Q.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],Q}if(!Z||!(J in Z))throw Error("Unknown hash algorithm: "+J);return Z[J].create()}function $03(J,Z,Q,Y){var X=O1.create(O1.Class.UNIVERSAL,O1.Type.SEQUENCE,!0,[O1.create(O1.Class.UNIVERSAL,O1.Type.OCTETSTRING,!1,J),O1.create(O1.Class.UNIVERSAL,O1.Type.INTEGER,!1,Z.getBytes())]);if(Y!=="hmacWithSHA1")X.value.push(O1.create(O1.Class.UNIVERSAL,O1.Type.INTEGER,!1,R4.util.hexToBytes(Q.toString(16))),O1.create(O1.Class.UNIVERSAL,O1.Type.SEQUENCE,!0,[O1.create(O1.Class.UNIVERSAL,O1.Type.OID,!1,O1.oidToDer(n6.oids[Y]).getBytes()),O1.create(O1.Class.UNIVERSAL,O1.Type.NULL,!1,"")]));return X}});var vc0=u((QE9,zI4)=>{var G_=J5();oV();c5();var E4=G_.asn1,F_=zI4.exports=G_.pkcs7asn1=G_.pkcs7asn1||{};G_.pkcs7=G_.pkcs7||{};G_.pkcs7.asn1=F_;var VI4={name:"ContentInfo",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.ContentType",tagClass:E4.Class.UNIVERSAL,type:E4.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:E4.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,captureAsn1:"content"}]};F_.contentInfoValidator=VI4;var KI4={name:"EncryptedContentInfo",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentType",tagClass:E4.Class.UNIVERSAL,type:E4.Type.OID,constructed:!1,capture:"contentType"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentEncryptionAlgorithm.algorithm",tagClass:E4.Class.UNIVERSAL,type:E4.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm.parameter",tagClass:E4.Class.UNIVERSAL,captureAsn1:"encParameter"}]},{name:"EncryptedContentInfo.encryptedContent",tagClass:E4.Class.CONTEXT_SPECIFIC,type:0,capture:"encryptedContent",captureAsn1:"encryptedContentAsn1"}]};F_.envelopedDataValidator={name:"EnvelopedData",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SEQUENCE,constructed:!0,value:[{name:"EnvelopedData.Version",tagClass:E4.Class.UNIVERSAL,type:E4.Type.INTEGER,constructed:!1,capture:"version"},{name:"EnvelopedData.RecipientInfos",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SET,constructed:!0,captureAsn1:"recipientInfos"}].concat(KI4)};F_.encryptedDataValidator={name:"EncryptedData",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedData.Version",tagClass:E4.Class.UNIVERSAL,type:E4.Type.INTEGER,constructed:!1,capture:"version"}].concat(KI4)};var J03={name:"SignerInfo",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.version",tagClass:E4.Class.UNIVERSAL,type:E4.Type.INTEGER,constructed:!1},{name:"SignerInfo.issuerAndSerialNumber",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.issuerAndSerialNumber.issuer",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"SignerInfo.issuerAndSerialNumber.serialNumber",tagClass:E4.Class.UNIVERSAL,type:E4.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"SignerInfo.digestAlgorithm",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.digestAlgorithm.algorithm",tagClass:E4.Class.UNIVERSAL,type:E4.Type.OID,constructed:!1,capture:"digestAlgorithm"},{name:"SignerInfo.digestAlgorithm.parameter",tagClass:E4.Class.UNIVERSAL,constructed:!1,captureAsn1:"digestParameter",optional:!0}]},{name:"SignerInfo.authenticatedAttributes",tagClass:E4.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"authenticatedAttributes"},{name:"SignerInfo.digestEncryptionAlgorithm",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SEQUENCE,constructed:!0,capture:"signatureAlgorithm"},{name:"SignerInfo.encryptedDigest",tagClass:E4.Class.UNIVERSAL,type:E4.Type.OCTETSTRING,constructed:!1,capture:"signature"},{name:"SignerInfo.unauthenticatedAttributes",tagClass:E4.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,capture:"unauthenticatedAttributes"}]};F_.signedDataValidator={name:"SignedData",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SEQUENCE,constructed:!0,value:[{name:"SignedData.Version",tagClass:E4.Class.UNIVERSAL,type:E4.Type.INTEGER,constructed:!1,capture:"version"},{name:"SignedData.DigestAlgorithms",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SET,constructed:!0,captureAsn1:"digestAlgorithms"},VI4,{name:"SignedData.Certificates",tagClass:E4.Class.CONTEXT_SPECIFIC,type:0,optional:!0,captureAsn1:"certificates"},{name:"SignedData.CertificateRevocationLists",tagClass:E4.Class.CONTEXT_SPECIFIC,type:1,optional:!0,captureAsn1:"crls"},{name:"SignedData.SignerInfos",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SET,capture:"signerInfos",optional:!0,value:[J03]}]};F_.recipientInfoValidator={name:"RecipientInfo",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.version",tagClass:E4.Class.UNIVERSAL,type:E4.Type.INTEGER,constructed:!1,capture:"version"},{name:"RecipientInfo.issuerAndSerial",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.issuerAndSerial.issuer",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"RecipientInfo.issuerAndSerial.serialNumber",tagClass:E4.Class.UNIVERSAL,type:E4.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"RecipientInfo.keyEncryptionAlgorithm",tagClass:E4.Class.UNIVERSAL,type:E4.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.keyEncryptionAlgorithm.algorithm",tagClass:E4.Class.UNIVERSAL,type:E4.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"RecipientInfo.keyEncryptionAlgorithm.parameter",tagClass:E4.Class.UNIVERSAL,constructed:!1,captureAsn1:"encParameter",optional:!0}]},{name:"RecipientInfo.encryptedKey",tagClass:E4.Class.UNIVERSAL,type:E4.Type.OCTETSTRING,constructed:!1,capture:"encKey"}]}});var kc0=u((YE9,GI4)=>{var oL=J5();c5();oL.mgf=oL.mgf||{};var Z03=GI4.exports=oL.mgf.mgf1=oL.mgf1=oL.mgf1||{};Z03.create=function(J){var Z={generate:function(Q,Y){var X=new oL.util.ByteBuffer,V=Math.ceil(Y/J.digestLength);for(var K=0;K<V;K++){var z=new oL.util.ByteBuffer;z.putInt32(K),J.start(),J.update(Q+z.getBytes()),X.putBuffer(J.digest())}return X.truncate(X.length()-Y),X.getBytes()}};return Z}});var UI4=u((XE9,FI4)=>{var lJ0=J5();kc0();FI4.exports=lJ0.mgf=lJ0.mgf||{};lJ0.mgf.mgf1=lJ0.mgf1});var iJ0=u((VE9,qI4)=>{var rL=J5();JX();c5();var Q03=qI4.exports=rL.pss=rL.pss||{};Q03.create=function(J){if(arguments.length===3)J={md:arguments[0],mgf:arguments[1],saltLength:arguments[2]};var{md:Z,mgf:Q}=J,Y=Z.digestLength,X=J.salt||null;if(typeof X==="string")X=rL.util.createBuffer(X);var V;if("saltLength"in J)V=J.saltLength;else if(X!==null)V=X.length();else throw Error("Salt length not specified or specific salt not given.");if(X!==null&&X.length()!==V)throw Error("Given salt length does not match length of given salt.");var K=J.prng||rL.random,z={};return z.encode=function(G,F){var U,q=F-1,D=Math.ceil(q/8),W=G.digest().getBytes();if(D<Y+V+2)throw Error("Message is too long to encrypt.");var H;if(X===null)H=K.getBytesSync(V);else H=X.bytes();var B=new rL.util.ByteBuffer;B.fillWithByte(0,8),B.putBytes(W),B.putBytes(H),Z.start(),Z.update(B.getBytes());var w=Z.digest().getBytes(),N=new rL.util.ByteBuffer;N.fillWithByte(0,D-V-Y-2),N.putByte(1),N.putBytes(H);var O=N.getBytes(),E=D-Y-1,L=Q.generate(w,E),M="";for(U=0;U<E;U++)M+=String.fromCharCode(O.charCodeAt(U)^L.charCodeAt(U));var A=65280>>8*D-q&255;return M=String.fromCharCode(M.charCodeAt(0)&~A)+M.substr(1),M+w+String.fromCharCode(188)},z.verify=function(G,F,U){var q,D=U-1,W=Math.ceil(D/8);if(F=F.substr(-W),W<Y+V+2)throw Error("Inconsistent parameters to PSS signature verification.");if(F.charCodeAt(W-1)!==188)throw Error("Encoded message does not end in 0xBC.");var H=W-Y-1,B=F.substr(0,H),w=F.substr(H,Y),N=65280>>8*W-D&255;if((B.charCodeAt(0)&N)!==0)throw Error("Bits beyond keysize not zero as expected.");var O=Q.generate(w,H),E="";for(q=0;q<H;q++)E+=String.fromCharCode(B.charCodeAt(q)^O.charCodeAt(q));E=String.fromCharCode(E.charCodeAt(0)&~N)+E.substr(1);var L=W-Y-V-2;for(q=0;q<L;q++)if(E.charCodeAt(q)!==0)throw Error("Leftmost octets not zero as expected");if(E.charCodeAt(L)!==1)throw Error("Inconsistent PSS signature, 0x01 marker not found");var M=E.substr(-V),A=new rL.util.ByteBuffer;A.fillWithByte(0,8),A.putBytes(G),A.putBytes(M),Z.start(),Z.update(A.getBytes());var I=Z.digest().getBytes();return w===I},z}});var oJ0=u((KE9,wI4)=>{var Q6=J5();KB();oV();wd();NG();UI4();zB();lL();iJ0();Ed();c5();var E0=Q6.asn1,e1=wI4.exports=Q6.pki=Q6.pki||{},f5=e1.oids,z9={};z9.CN=f5.commonName;z9.commonName="CN";z9.C=f5.countryName;z9.countryName="C";z9.L=f5.localityName;z9.localityName="L";z9.ST=f5.stateOrProvinceName;z9.stateOrProvinceName="ST";z9.O=f5.organizationName;z9.organizationName="O";z9.OU=f5.organizationalUnitName;z9.organizationalUnitName="OU";z9.E=f5.emailAddress;z9.emailAddress="E";var WI4=Q6.pki.rsa.publicKeyValidator,Y03={name:"Certificate",tagClass:E0.Class.UNIVERSAL,type:E0.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate",tagClass:E0.Class.UNIVERSAL,type:E0.Type.SEQUENCE,constructed:!0,captureAsn1:"tbsCertificate",value:[{name:"Certificate.TBSCertificate.version",tagClass:E0.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.version.integer",tagClass:E0.Class.UNIVERSAL,type:E0.Type.INTEGER,constructed:!1,capture:"certVersion"}]},{name:"Certificate.TBSCertificate.serialNumber",tagClass:E0.Class.UNIVERSAL,type:E0.Type.INTEGER,constructed:!1,capture:"certSerialNumber"},{name:"Certificate.TBSCertificate.signature",tagClass:E0.Class.UNIVERSAL,type:E0.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.signature.algorithm",tagClass:E0.Class.UNIVERSAL,type:E0.Type.OID,constructed:!1,capture:"certinfoSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:E0.Class.UNIVERSAL,optional:!0,captureAsn1:"certinfoSignatureParams"}]},{name:"Certificate.TBSCertificate.issuer",tagClass:E0.Class.UNIVERSAL,type:E0.Type.SEQUENCE,constructed:!0,captureAsn1:"certIssuer"},{name:"Certificate.TBSCertificate.validity",tagClass:E0.Class.UNIVERSAL,type:E0.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.validity.notBefore (utc)",tagClass:E0.Class.UNIVERSAL,type:E0.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity1UTCTime"},{name:"Certificate.TBSCertificate.validity.notBefore (generalized)",tagClass:E0.Class.UNIVERSAL,type:E0.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity2GeneralizedTime"},{name:"Certificate.TBSCertificate.validity.notAfter (utc)",tagClass:E0.Class.UNIVERSAL,type:E0.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity3UTCTime"},{name:"Certificate.TBSCertificate.validity.notAfter (generalized)",tagClass:E0.Class.UNIVERSAL,type:E0.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity4GeneralizedTime"}]},{name:"Certificate.TBSCertificate.subject",tagClass:E0.Class.UNIVERSAL,type:E0.Type.SEQUENCE,constructed:!0,captureAsn1:"certSubject"},WI4,{name:"Certificate.TBSCertificate.issuerUniqueID",tagClass:E0.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.issuerUniqueID.id",tagClass:E0.Class.UNIVERSAL,type:E0.Type.BITSTRING,constructed:!1,captureBitStringValue:"certIssuerUniqueId"}]},{name:"Certificate.TBSCertificate.subjectUniqueID",tagClass:E0.Class.CONTEXT_SPECIFIC,type:2,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.subjectUniqueID.id",tagClass:E0.Class.UNIVERSAL,type:E0.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSubjectUniqueId"}]},{name:"Certificate.TBSCertificate.extensions",tagClass:E0.Class.CONTEXT_SPECIFIC,type:3,constructed:!0,captureAsn1:"certExtensions",optional:!0}]},{name:"Certificate.signatureAlgorithm",tagClass:E0.Class.UNIVERSAL,type:E0.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.signatureAlgorithm.algorithm",tagClass:E0.Class.UNIVERSAL,type:E0.Type.OID,constructed:!1,capture:"certSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:E0.Class.UNIVERSAL,optional:!0,captureAsn1:"certSignatureParams"}]},{name:"Certificate.signatureValue",tagClass:E0.Class.UNIVERSAL,type:E0.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSignature"}]},X03={name:"rsapss",tagClass:E0.Class.UNIVERSAL,type:E0.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.hashAlgorithm",tagClass:E0.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier",tagClass:E0.Class.UNIVERSAL,type:E0.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm",tagClass:E0.Class.UNIVERSAL,type:E0.Type.OID,constructed:!1,capture:"hashOid"}]}]},{name:"rsapss.maskGenAlgorithm",tagClass:E0.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier",tagClass:E0.Class.UNIVERSAL,type:E0.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm",tagClass:E0.Class.UNIVERSAL,type:E0.Type.OID,constructed:!1,capture:"maskGenOid"},{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params",tagClass:E0.Class.UNIVERSAL,type:E0.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm",tagClass:E0.Class.UNIVERSAL,type:E0.Type.OID,constructed:!1,capture:"maskGenHashOid"}]}]}]},{name:"rsapss.saltLength",tagClass:E0.Class.CONTEXT_SPECIFIC,type:2,optional:!0,value:[{name:"rsapss.saltLength.saltLength",tagClass:E0.Class.UNIVERSAL,type:E0.Class.INTEGER,constructed:!1,capture:"saltLength"}]},{name:"rsapss.trailerField",tagClass:E0.Class.CONTEXT_SPECIFIC,type:3,optional:!0,value:[{name:"rsapss.trailer.trailer",tagClass:E0.Class.UNIVERSAL,type:E0.Class.INTEGER,constructed:!1,capture:"trailer"}]}]},V03={name:"CertificationRequestInfo",tagClass:E0.Class.UNIVERSAL,type:E0.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfo",value:[{name:"CertificationRequestInfo.integer",tagClass:E0.Class.UNIVERSAL,type:E0.Type.INTEGER,constructed:!1,capture:"certificationRequestInfoVersion"},{name:"CertificationRequestInfo.subject",tagClass:E0.Class.UNIVERSAL,type:E0.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfoSubject"},WI4,{name:"CertificationRequestInfo.attributes",tagClass:E0.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"certificationRequestInfoAttributes",value:[{name:"CertificationRequestInfo.attributes",tagClass:E0.Class.UNIVERSAL,type:E0.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequestInfo.attributes.type",tagClass:E0.Class.UNIVERSAL,type:E0.Type.OID,constructed:!1},{name:"CertificationRequestInfo.attributes.value",tagClass:E0.Class.UNIVERSAL,type:E0.Type.SET,constructed:!0}]}]}]},K03={name:"CertificationRequest",tagClass:E0.Class.UNIVERSAL,type:E0.Type.SEQUENCE,constructed:!0,captureAsn1:"csr",value:[V03,{name:"CertificationRequest.signatureAlgorithm",tagClass:E0.Class.UNIVERSAL,type:E0.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequest.signatureAlgorithm.algorithm",tagClass:E0.Class.UNIVERSAL,type:E0.Type.OID,constructed:!1,capture:"csrSignatureOid"},{name:"CertificationRequest.signatureAlgorithm.parameters",tagClass:E0.Class.UNIVERSAL,optional:!0,captureAsn1:"csrSignatureParams"}]},{name:"CertificationRequest.signature",tagClass:E0.Class.UNIVERSAL,type:E0.Type.BITSTRING,constructed:!1,captureBitStringValue:"csrSignature"}]};e1.RDNAttributesAsArray=function(J,Z){var Q=[],Y,X,V;for(var K=0;K<J.value.length;++K){Y=J.value[K];for(var z=0;z<Y.value.length;++z){if(V={},X=Y.value[z],V.type=E0.derToOid(X.value[0].value),V.value=X.value[1].value,V.valueTagClass=X.value[1].type,V.type in f5){if(V.name=f5[V.type],V.name in z9)V.shortName=z9[V.name]}if(Z)Z.update(V.type),Z.update(V.value);Q.push(V)}}return Q};e1.CRIAttributesAsArray=function(J){var Z=[];for(var Q=0;Q<J.length;++Q){var Y=J[Q],X=E0.derToOid(Y.value[0].value),V=Y.value[1].value;for(var K=0;K<V.length;++K){var z={};if(z.type=X,z.value=V[K].value,z.valueTagClass=V[K].type,z.type in f5){if(z.name=f5[z.type],z.name in z9)z.shortName=z9[z.name]}if(z.type===f5.extensionRequest){z.extensions=[];for(var G=0;G<z.value.length;++G)z.extensions.push(e1.certificateExtensionFromAsn1(z.value[G]))}Z.push(z)}}return Z};function UB(J,Z){if(typeof Z==="string")Z={shortName:Z};var Q=null,Y;for(var X=0;Q===null&&X<J.attributes.length;++X)if(Y=J.attributes[X],Z.type&&Z.type===Y.type)Q=Y;else if(Z.name&&Z.name===Y.name)Q=Y;else if(Z.shortName&&Z.shortName===Y.shortName)Q=Y;return Q}var nJ0=function(J,Z,Q){var Y={};if(J!==f5["RSASSA-PSS"])return Y;if(Q)Y={hash:{algorithmOid:f5.sha1},mgf:{algorithmOid:f5.mgf1,hash:{algorithmOid:f5.sha1}},saltLength:20};var X={},V=[];if(!E0.validate(Z,X03,X,V)){var K=Error("Cannot read RSASSA-PSS parameter block.");throw K.errors=V,K}if(X.hashOid!==void 0)Y.hash=Y.hash||{},Y.hash.algorithmOid=E0.derToOid(X.hashOid);if(X.maskGenOid!==void 0)Y.mgf=Y.mgf||{},Y.mgf.algorithmOid=E0.derToOid(X.maskGenOid),Y.mgf.hash=Y.mgf.hash||{},Y.mgf.hash.algorithmOid=E0.derToOid(X.maskGenHashOid);if(X.saltLength!==void 0)Y.saltLength=X.saltLength.charCodeAt(0);return Y},aJ0=function(J){switch(f5[J.signatureOid]){case"sha1WithRSAEncryption":case"sha1WithRSASignature":return Q6.md.sha1.create();case"md5WithRSAEncryption":return Q6.md.md5.create();case"sha256WithRSAEncryption":return Q6.md.sha256.create();case"sha384WithRSAEncryption":return Q6.md.sha384.create();case"sha512WithRSAEncryption":return Q6.md.sha512.create();case"RSASSA-PSS":return Q6.md.sha256.create();default:var Z=Error("Could not compute "+J.type+" digest. Unknown signature OID.");throw Z.signatureOid=J.signatureOid,Z}},HI4=function(J){var Z=J.certificate,Q;switch(Z.signatureOid){case f5.sha1WithRSAEncryption:case f5.sha1WithRSASignature:break;case f5["RSASSA-PSS"]:var Y,X;if(Y=f5[Z.signatureParameters.mgf.hash.algorithmOid],Y===void 0||Q6.md[Y]===void 0){var V=Error("Unsupported MGF hash function.");throw V.oid=Z.signatureParameters.mgf.hash.algorithmOid,V.name=Y,V}if(X=f5[Z.signatureParameters.mgf.algorithmOid],X===void 0||Q6.mgf[X]===void 0){var V=Error("Unsupported MGF function.");throw V.oid=Z.signatureParameters.mgf.algorithmOid,V.name=X,V}if(X=Q6.mgf[X].create(Q6.md[Y].create()),Y=f5[Z.signatureParameters.hash.algorithmOid],Y===void 0||Q6.md[Y]===void 0){var V=Error("Unsupported RSASSA-PSS hash function.");throw V.oid=Z.signatureParameters.hash.algorithmOid,V.name=Y,V}Q=Q6.pss.create(Q6.md[Y].create(),X,Z.signatureParameters.saltLength);break}return Z.publicKey.verify(J.md.digest().getBytes(),J.signature,Q)};e1.certificateFromPem=function(J,Z,Q){var Y=Q6.pem.decode(J)[0];if(Y.type!=="CERTIFICATE"&&Y.type!=="X509 CERTIFICATE"&&Y.type!=="TRUSTED CERTIFICATE"){var X=Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');throw X.headerType=Y.type,X}if(Y.procType&&Y.procType.type==="ENCRYPTED")throw Error("Could not convert certificate from PEM; PEM is encrypted.");var V=E0.fromDer(Y.body,Q);return e1.certificateFromAsn1(V,Z)};e1.certificateToPem=function(J,Z){var Q={type:"CERTIFICATE",body:E0.toDer(e1.certificateToAsn1(J)).getBytes()};return Q6.pem.encode(Q,{maxline:Z})};e1.publicKeyFromPem=function(J){var Z=Q6.pem.decode(J)[0];if(Z.type!=="PUBLIC KEY"&&Z.type!=="RSA PUBLIC KEY"){var Q=Error('Could not convert public key from PEM; PEM header type is not "PUBLIC KEY" or "RSA PUBLIC KEY".');throw Q.headerType=Z.type,Q}if(Z.procType&&Z.procType.type==="ENCRYPTED")throw Error("Could not convert public key from PEM; PEM is encrypted.");var Y=E0.fromDer(Z.body);return e1.publicKeyFromAsn1(Y)};e1.publicKeyToPem=function(J,Z){var Q={type:"PUBLIC KEY",body:E0.toDer(e1.publicKeyToAsn1(J)).getBytes()};return Q6.pem.encode(Q,{maxline:Z})};e1.publicKeyToRSAPublicKeyPem=function(J,Z){var Q={type:"RSA PUBLIC KEY",body:E0.toDer(e1.publicKeyToRSAPublicKey(J)).getBytes()};return Q6.pem.encode(Q,{maxline:Z})};e1.getPublicKeyFingerprint=function(J,Z){Z=Z||{};var Q=Z.md||Q6.md.sha1.create(),Y=Z.type||"RSAPublicKey",X;switch(Y){case"RSAPublicKey":X=E0.toDer(e1.publicKeyToRSAPublicKey(J)).getBytes();break;case"SubjectPublicKeyInfo":X=E0.toDer(e1.publicKeyToAsn1(J)).getBytes();break;default:throw Error('Unknown fingerprint type "'+Z.type+'".')}Q.start(),Q.update(X);var V=Q.digest();if(Z.encoding==="hex"){var K=V.toHex();if(Z.delimiter)return K.match(/.{2}/g).join(Z.delimiter);return K}else if(Z.encoding==="binary")return V.getBytes();else if(Z.encoding)throw Error('Unknown encoding "'+Z.encoding+'".');return V};e1.certificationRequestFromPem=function(J,Z,Q){var Y=Q6.pem.decode(J)[0];if(Y.type!=="CERTIFICATE REQUEST"){var X=Error('Could not convert certification request from PEM; PEM header type is not "CERTIFICATE REQUEST".');throw X.headerType=Y.type,X}if(Y.procType&&Y.procType.type==="ENCRYPTED")throw Error("Could not convert certification request from PEM; PEM is encrypted.");var V=E0.fromDer(Y.body,Q);return e1.certificationRequestFromAsn1(V,Z)};e1.certificationRequestToPem=function(J,Z){var Q={type:"CERTIFICATE REQUEST",body:E0.toDer(e1.certificationRequestToAsn1(J)).getBytes()};return Q6.pem.encode(Q,{maxline:Z})};e1.createCertificate=function(){var J={};return J.version=2,J.serialNumber="00",J.signatureOid=null,J.signature=null,J.siginfo={},J.siginfo.algorithmOid=null,J.validity={},J.validity.notBefore=new Date,J.validity.notAfter=new Date,J.issuer={},J.issuer.getField=function(Z){return UB(J.issuer,Z)},J.issuer.addField=function(Z){YX([Z]),J.issuer.attributes.push(Z)},J.issuer.attributes=[],J.issuer.hash=null,J.subject={},J.subject.getField=function(Z){return UB(J.subject,Z)},J.subject.addField=function(Z){YX([Z]),J.subject.attributes.push(Z)},J.subject.attributes=[],J.subject.hash=null,J.extensions=[],J.publicKey=null,J.md=null,J.setSubject=function(Z,Q){if(YX(Z),J.subject.attributes=Z,delete J.subject.uniqueId,Q)J.subject.uniqueId=Q;J.subject.hash=null},J.setIssuer=function(Z,Q){if(YX(Z),J.issuer.attributes=Z,delete J.issuer.uniqueId,Q)J.issuer.uniqueId=Q;J.issuer.hash=null},J.setExtensions=function(Z){for(var Q=0;Q<Z.length;++Q)BI4(Z[Q],{cert:J});J.extensions=Z},J.getExtension=function(Z){if(typeof Z==="string")Z={name:Z};var Q=null,Y;for(var X=0;Q===null&&X<J.extensions.length;++X)if(Y=J.extensions[X],Z.id&&Y.id===Z.id)Q=Y;else if(Z.name&&Y.name===Z.name)Q=Y;return Q},J.sign=function(Z,Q){J.md=Q||Q6.md.sha1.create();var Y=f5[J.md.algorithm+"WithRSAEncryption"];if(!Y){var X=Error("Could not compute certificate digest. Unknown message digest algorithm OID.");throw X.algorithm=J.md.algorithm,X}J.signatureOid=J.siginfo.algorithmOid=Y,J.tbsCertificate=e1.getTBSCertificate(J);var V=E0.toDer(J.tbsCertificate);J.md.update(V.getBytes()),J.signature=Z.sign(J.md)},J.verify=function(Z){var Q=!1;if(!J.issued(Z)){var Y=Z.issuer,X=J.subject,V=Error("The parent certificate did not issue the given child certificate; the child certificate's issuer does not match the parent's subject.");throw V.expectedIssuer=X.attributes,V.actualIssuer=Y.attributes,V}var K=Z.md;if(K===null){K=aJ0({signatureOid:Z.signatureOid,type:"certificate"});var z=Z.tbsCertificate||e1.getTBSCertificate(Z),G=E0.toDer(z);K.update(G.getBytes())}if(K!==null)Q=HI4({certificate:J,md:K,signature:Z.signature});return Q},J.isIssuer=function(Z){var Q=!1,Y=J.issuer,X=Z.subject;if(Y.hash&&X.hash)Q=Y.hash===X.hash;else if(Y.attributes.length===X.attributes.length){Q=!0;var V,K;for(var z=0;Q&&z<Y.attributes.length;++z)if(V=Y.attributes[z],K=X.attributes[z],V.type!==K.type||V.value!==K.value)Q=!1}return Q},J.issued=function(Z){return Z.isIssuer(J)},J.generateSubjectKeyIdentifier=function(){return e1.getPublicKeyFingerprint(J.publicKey,{type:"RSAPublicKey"})},J.verifySubjectKeyIdentifier=function(){var Z=f5.subjectKeyIdentifier;for(var Q=0;Q<J.extensions.length;++Q){var Y=J.extensions[Q];if(Y.id===Z){var X=J.generateSubjectKeyIdentifier().getBytes();return Q6.util.hexToBytes(Y.subjectKeyIdentifier)===X}}return!1},J};e1.certificateFromAsn1=function(J,Z){var Q={},Y=[];if(!E0.validate(J,Y03,Q,Y)){var X=Error("Cannot read X.509 certificate. ASN.1 object is not an X509v3 Certificate.");throw X.errors=Y,X}var V=E0.derToOid(Q.publicKeyOid);if(V!==e1.oids.rsaEncryption)throw Error("Cannot read public key. OID is not RSA.");var K=e1.createCertificate();K.version=Q.certVersion?Q.certVersion.charCodeAt(0):0;var z=Q6.util.createBuffer(Q.certSerialNumber);K.serialNumber=z.toHex(),K.signatureOid=Q6.asn1.derToOid(Q.certSignatureOid),K.signatureParameters=nJ0(K.signatureOid,Q.certSignatureParams,!0),K.siginfo.algorithmOid=Q6.asn1.derToOid(Q.certinfoSignatureOid),K.siginfo.parameters=nJ0(K.siginfo.algorithmOid,Q.certinfoSignatureParams,!1),K.signature=Q.certSignature;var G=[];if(Q.certValidity1UTCTime!==void 0)G.push(E0.utcTimeToDate(Q.certValidity1UTCTime));if(Q.certValidity2GeneralizedTime!==void 0)G.push(E0.generalizedTimeToDate(Q.certValidity2GeneralizedTime));if(Q.certValidity3UTCTime!==void 0)G.push(E0.utcTimeToDate(Q.certValidity3UTCTime));if(Q.certValidity4GeneralizedTime!==void 0)G.push(E0.generalizedTimeToDate(Q.certValidity4GeneralizedTime));if(G.length>2)throw Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate.");if(G.length<2)throw Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime.");if(K.validity.notBefore=G[0],K.validity.notAfter=G[1],K.tbsCertificate=Q.tbsCertificate,Z){K.md=aJ0({signatureOid:K.signatureOid,type:"certificate"});var F=E0.toDer(K.tbsCertificate);K.md.update(F.getBytes())}var U=Q6.md.sha1.create(),q=E0.toDer(Q.certIssuer);if(U.update(q.getBytes()),K.issuer.getField=function(H){return UB(K.issuer,H)},K.issuer.addField=function(H){YX([H]),K.issuer.attributes.push(H)},K.issuer.attributes=e1.RDNAttributesAsArray(Q.certIssuer),Q.certIssuerUniqueId)K.issuer.uniqueId=Q.certIssuerUniqueId;K.issuer.hash=U.digest().toHex();var D=Q6.md.sha1.create(),W=E0.toDer(Q.certSubject);if(D.update(W.getBytes()),K.subject.getField=function(H){return UB(K.subject,H)},K.subject.addField=function(H){YX([H]),K.subject.attributes.push(H)},K.subject.attributes=e1.RDNAttributesAsArray(Q.certSubject),Q.certSubjectUniqueId)K.subject.uniqueId=Q.certSubjectUniqueId;if(K.subject.hash=D.digest().toHex(),Q.certExtensions)K.extensions=e1.certificateExtensionsFromAsn1(Q.certExtensions);else K.extensions=[];return K.publicKey=e1.publicKeyFromAsn1(Q.subjectPublicKeyInfo),K};e1.certificateExtensionsFromAsn1=function(J){var Z=[];for(var Q=0;Q<J.value.length;++Q){var Y=J.value[Q];for(var X=0;X<Y.value.length;++X)Z.push(e1.certificateExtensionFromAsn1(Y.value[X]))}return Z};e1.certificateExtensionFromAsn1=function(J){var Z={};if(Z.id=E0.derToOid(J.value[0].value),Z.critical=!1,J.value[1].type===E0.Type.BOOLEAN)Z.critical=J.value[1].value.charCodeAt(0)!==0,Z.value=J.value[2].value;else Z.value=J.value[1].value;if(Z.id in f5){if(Z.name=f5[Z.id],Z.name==="keyUsage"){var Q=E0.fromDer(Z.value),Y=0,X=0;if(Q.value.length>1)Y=Q.value.charCodeAt(1),X=Q.value.length>2?Q.value.charCodeAt(2):0;Z.digitalSignature=(Y&128)===128,Z.nonRepudiation=(Y&64)===64,Z.keyEncipherment=(Y&32)===32,Z.dataEncipherment=(Y&16)===16,Z.keyAgreement=(Y&8)===8,Z.keyCertSign=(Y&4)===4,Z.cRLSign=(Y&2)===2,Z.encipherOnly=(Y&1)===1,Z.decipherOnly=(X&128)===128}else if(Z.name==="basicConstraints"){var Q=E0.fromDer(Z.value);if(Q.value.length>0&&Q.value[0].type===E0.Type.BOOLEAN)Z.cA=Q.value[0].value.charCodeAt(0)!==0;else Z.cA=!1;var V=null;if(Q.value.length>0&&Q.value[0].type===E0.Type.INTEGER)V=Q.value[0].value;else if(Q.value.length>1)V=Q.value[1].value;if(V!==null)Z.pathLenConstraint=E0.derToInteger(V)}else if(Z.name==="extKeyUsage"){var Q=E0.fromDer(Z.value);for(var K=0;K<Q.value.length;++K){var z=E0.derToOid(Q.value[K].value);if(z in f5)Z[f5[z]]=!0;else Z[z]=!0}}else if(Z.name==="nsCertType"){var Q=E0.fromDer(Z.value),Y=0;if(Q.value.length>1)Y=Q.value.charCodeAt(1);Z.client=(Y&128)===128,Z.server=(Y&64)===64,Z.email=(Y&32)===32,Z.objsign=(Y&16)===16,Z.reserved=(Y&8)===8,Z.sslCA=(Y&4)===4,Z.emailCA=(Y&2)===2,Z.objCA=(Y&1)===1}else if(Z.name==="subjectAltName"||Z.name==="issuerAltName"){Z.altNames=[];var G,Q=E0.fromDer(Z.value);for(var F=0;F<Q.value.length;++F){G=Q.value[F];var U={type:G.type,value:G.value};switch(Z.altNames.push(U),G.type){case 1:case 2:case 6:break;case 7:U.ip=Q6.util.bytesToIP(G.value);break;case 8:U.oid=E0.derToOid(G.value);break;default:}}}else if(Z.name==="subjectKeyIdentifier"){var Q=E0.fromDer(Z.value);Z.subjectKeyIdentifier=Q6.util.bytesToHex(Q.value)}}return Z};e1.certificationRequestFromAsn1=function(J,Z){var Q={},Y=[];if(!E0.validate(J,K03,Q,Y)){var X=Error("Cannot read PKCS#10 certificate request. ASN.1 object is not a PKCS#10 CertificationRequest.");throw X.errors=Y,X}var V=E0.derToOid(Q.publicKeyOid);if(V!==e1.oids.rsaEncryption)throw Error("Cannot read public key. OID is not RSA.");var K=e1.createCertificationRequest();if(K.version=Q.csrVersion?Q.csrVersion.charCodeAt(0):0,K.signatureOid=Q6.asn1.derToOid(Q.csrSignatureOid),K.signatureParameters=nJ0(K.signatureOid,Q.csrSignatureParams,!0),K.siginfo.algorithmOid=Q6.asn1.derToOid(Q.csrSignatureOid),K.siginfo.parameters=nJ0(K.siginfo.algorithmOid,Q.csrSignatureParams,!1),K.signature=Q.csrSignature,K.certificationRequestInfo=Q.certificationRequestInfo,Z){K.md=aJ0({signatureOid:K.signatureOid,type:"certification request"});var z=E0.toDer(K.certificationRequestInfo);K.md.update(z.getBytes())}var G=Q6.md.sha1.create();return K.subject.getField=function(F){return UB(K.subject,F)},K.subject.addField=function(F){YX([F]),K.subject.attributes.push(F)},K.subject.attributes=e1.RDNAttributesAsArray(Q.certificationRequestInfoSubject,G),K.subject.hash=G.digest().toHex(),K.publicKey=e1.publicKeyFromAsn1(Q.subjectPublicKeyInfo),K.getAttribute=function(F){return UB(K,F)},K.addAttribute=function(F){YX([F]),K.attributes.push(F)},K.attributes=e1.CRIAttributesAsArray(Q.certificationRequestInfoAttributes||[]),K};e1.createCertificationRequest=function(){var J={};return J.version=0,J.signatureOid=null,J.signature=null,J.siginfo={},J.siginfo.algorithmOid=null,J.subject={},J.subject.getField=function(Z){return UB(J.subject,Z)},J.subject.addField=function(Z){YX([Z]),J.subject.attributes.push(Z)},J.subject.attributes=[],J.subject.hash=null,J.publicKey=null,J.attributes=[],J.getAttribute=function(Z){return UB(J,Z)},J.addAttribute=function(Z){YX([Z]),J.attributes.push(Z)},J.md=null,J.setSubject=function(Z){YX(Z),J.subject.attributes=Z,J.subject.hash=null},J.setAttributes=function(Z){YX(Z),J.attributes=Z},J.sign=function(Z,Q){J.md=Q||Q6.md.sha1.create();var Y=f5[J.md.algorithm+"WithRSAEncryption"];if(!Y){var X=Error("Could not compute certification request digest. Unknown message digest algorithm OID.");throw X.algorithm=J.md.algorithm,X}J.signatureOid=J.siginfo.algorithmOid=Y,J.certificationRequestInfo=e1.getCertificationRequestInfo(J);var V=E0.toDer(J.certificationRequestInfo);J.md.update(V.getBytes()),J.signature=Z.sign(J.md)},J.verify=function(){var Z=!1,Q=J.md;if(Q===null){Q=aJ0({signatureOid:J.signatureOid,type:"certification request"});var Y=J.certificationRequestInfo||e1.getCertificationRequestInfo(J),X=E0.toDer(Y);Q.update(X.getBytes())}if(Q!==null)Z=HI4({certificate:J,md:Q,signature:J.signature});return Z},J};function U_(J){var Z=E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[]),Q,Y,X=J.attributes;for(var V=0;V<X.length;++V){Q=X[V];var K=Q.value,z=E0.Type.PRINTABLESTRING;if("valueTagClass"in Q){if(z=Q.valueTagClass,z===E0.Type.UTF8)K=Q6.util.encodeUtf8(K)}Y=E0.create(E0.Class.UNIVERSAL,E0.Type.SET,!0,[E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[E0.create(E0.Class.UNIVERSAL,E0.Type.OID,!1,E0.oidToDer(Q.type).getBytes()),E0.create(E0.Class.UNIVERSAL,z,!1,K)])]),Z.value.push(Y)}return Z}function YX(J){var Z;for(var Q=0;Q<J.length;++Q){if(Z=J[Q],typeof Z.name>"u"){if(Z.type&&Z.type in e1.oids)Z.name=e1.oids[Z.type];else if(Z.shortName&&Z.shortName in z9)Z.name=e1.oids[z9[Z.shortName]]}if(typeof Z.type>"u")if(Z.name&&Z.name in e1.oids)Z.type=e1.oids[Z.name];else{var Y=Error("Attribute type not specified.");throw Y.attribute=Z,Y}if(typeof Z.shortName>"u"){if(Z.name&&Z.name in z9)Z.shortName=z9[Z.name]}if(Z.type===f5.extensionRequest){if(Z.valueConstructed=!0,Z.valueTagClass=E0.Type.SEQUENCE,!Z.value&&Z.extensions){Z.value=[];for(var X=0;X<Z.extensions.length;++X)Z.value.push(e1.certificateExtensionToAsn1(BI4(Z.extensions[X])))}}if(typeof Z.value>"u"){var Y=Error("Attribute value not specified.");throw Y.attribute=Z,Y}}}function BI4(J,Z){if(Z=Z||{},typeof J.name>"u"){if(J.id&&J.id in e1.oids)J.name=e1.oids[J.id]}if(typeof J.id>"u")if(J.name&&J.name in e1.oids)J.id=e1.oids[J.name];else{var Q=Error("Extension ID not specified.");throw Q.extension=J,Q}if(typeof J.value<"u")return J;if(J.name==="keyUsage"){var Y=0,X=0,V=0;if(J.digitalSignature)X|=128,Y=7;if(J.nonRepudiation)X|=64,Y=6;if(J.keyEncipherment)X|=32,Y=5;if(J.dataEncipherment)X|=16,Y=4;if(J.keyAgreement)X|=8,Y=3;if(J.keyCertSign)X|=4,Y=2;if(J.cRLSign)X|=2,Y=1;if(J.encipherOnly)X|=1,Y=0;if(J.decipherOnly)V|=128,Y=7;var K=String.fromCharCode(Y);if(V!==0)K+=String.fromCharCode(X)+String.fromCharCode(V);else if(X!==0)K+=String.fromCharCode(X);J.value=E0.create(E0.Class.UNIVERSAL,E0.Type.BITSTRING,!1,K)}else if(J.name==="basicConstraints"){if(J.value=E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[]),J.cA)J.value.value.push(E0.create(E0.Class.UNIVERSAL,E0.Type.BOOLEAN,!1,String.fromCharCode(255)));if("pathLenConstraint"in J)J.value.value.push(E0.create(E0.Class.UNIVERSAL,E0.Type.INTEGER,!1,E0.integerToDer(J.pathLenConstraint).getBytes()))}else if(J.name==="extKeyUsage"){J.value=E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[]);var z=J.value.value;for(var G in J){if(J[G]!==!0)continue;if(G in f5)z.push(E0.create(E0.Class.UNIVERSAL,E0.Type.OID,!1,E0.oidToDer(f5[G]).getBytes()));else if(G.indexOf(".")!==-1)z.push(E0.create(E0.Class.UNIVERSAL,E0.Type.OID,!1,E0.oidToDer(G).getBytes()))}}else if(J.name==="nsCertType"){var Y=0,X=0;if(J.client)X|=128,Y=7;if(J.server)X|=64,Y=6;if(J.email)X|=32,Y=5;if(J.objsign)X|=16,Y=4;if(J.reserved)X|=8,Y=3;if(J.sslCA)X|=4,Y=2;if(J.emailCA)X|=2,Y=1;if(J.objCA)X|=1,Y=0;var K=String.fromCharCode(Y);if(X!==0)K+=String.fromCharCode(X);J.value=E0.create(E0.Class.UNIVERSAL,E0.Type.BITSTRING,!1,K)}else if(J.name==="subjectAltName"||J.name==="issuerAltName"){J.value=E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[]);var F;for(var U=0;U<J.altNames.length;++U){F=J.altNames[U];var K=F.value;if(F.type===7&&F.ip){if(K=Q6.util.bytesFromIP(F.ip),K===null){var Q=Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');throw Q.extension=J,Q}}else if(F.type===8)if(F.oid)K=E0.oidToDer(E0.oidToDer(F.oid));else K=E0.oidToDer(K);J.value.value.push(E0.create(E0.Class.CONTEXT_SPECIFIC,F.type,!1,K))}}else if(J.name==="nsComment"&&Z.cert){if(!/^[\x00-\x7F]*$/.test(J.comment)||J.comment.length<1||J.comment.length>128)throw Error('Invalid "nsComment" content.');J.value=E0.create(E0.Class.UNIVERSAL,E0.Type.IA5STRING,!1,J.comment)}else if(J.name==="subjectKeyIdentifier"&&Z.cert){var q=Z.cert.generateSubjectKeyIdentifier();J.subjectKeyIdentifier=q.toHex(),J.value=E0.create(E0.Class.UNIVERSAL,E0.Type.OCTETSTRING,!1,q.getBytes())}else if(J.name==="authorityKeyIdentifier"&&Z.cert){J.value=E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[]);var z=J.value.value;if(J.keyIdentifier){var D=J.keyIdentifier===!0?Z.cert.generateSubjectKeyIdentifier().getBytes():J.keyIdentifier;z.push(E0.create(E0.Class.CONTEXT_SPECIFIC,0,!1,D))}if(J.authorityCertIssuer){var W=[E0.create(E0.Class.CONTEXT_SPECIFIC,4,!0,[U_(J.authorityCertIssuer===!0?Z.cert.issuer:J.authorityCertIssuer)])];z.push(E0.create(E0.Class.CONTEXT_SPECIFIC,1,!0,W))}if(J.serialNumber){var H=Q6.util.hexToBytes(J.serialNumber===!0?Z.cert.serialNumber:J.serialNumber);z.push(E0.create(E0.Class.CONTEXT_SPECIFIC,2,!1,H))}}else if(J.name==="cRLDistributionPoints"){J.value=E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[]);var z=J.value.value,B=E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[]),w=E0.create(E0.Class.CONTEXT_SPECIFIC,0,!0,[]),F;for(var U=0;U<J.altNames.length;++U){F=J.altNames[U];var K=F.value;if(F.type===7&&F.ip){if(K=Q6.util.bytesFromIP(F.ip),K===null){var Q=Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');throw Q.extension=J,Q}}else if(F.type===8)if(F.oid)K=E0.oidToDer(E0.oidToDer(F.oid));else K=E0.oidToDer(K);w.value.push(E0.create(E0.Class.CONTEXT_SPECIFIC,F.type,!1,K))}B.value.push(E0.create(E0.Class.CONTEXT_SPECIFIC,0,!0,[w])),z.push(B)}if(typeof J.value>"u"){var Q=Error("Extension value not specified.");throw Q.extension=J,Q}return J}function yc0(J,Z){switch(J){case f5["RSASSA-PSS"]:var Q=[];if(Z.hash.algorithmOid!==void 0)Q.push(E0.create(E0.Class.CONTEXT_SPECIFIC,0,!0,[E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[E0.create(E0.Class.UNIVERSAL,E0.Type.OID,!1,E0.oidToDer(Z.hash.algorithmOid).getBytes()),E0.create(E0.Class.UNIVERSAL,E0.Type.NULL,!1,"")])]));if(Z.mgf.algorithmOid!==void 0)Q.push(E0.create(E0.Class.CONTEXT_SPECIFIC,1,!0,[E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[E0.create(E0.Class.UNIVERSAL,E0.Type.OID,!1,E0.oidToDer(Z.mgf.algorithmOid).getBytes()),E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[E0.create(E0.Class.UNIVERSAL,E0.Type.OID,!1,E0.oidToDer(Z.mgf.hash.algorithmOid).getBytes()),E0.create(E0.Class.UNIVERSAL,E0.Type.NULL,!1,"")])])]));if(Z.saltLength!==void 0)Q.push(E0.create(E0.Class.CONTEXT_SPECIFIC,2,!0,[E0.create(E0.Class.UNIVERSAL,E0.Type.INTEGER,!1,E0.integerToDer(Z.saltLength).getBytes())]));return E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,Q);default:return E0.create(E0.Class.UNIVERSAL,E0.Type.NULL,!1,"")}}function z03(J){var Z=E0.create(E0.Class.CONTEXT_SPECIFIC,0,!0,[]);if(J.attributes.length===0)return Z;var Q=J.attributes;for(var Y=0;Y<Q.length;++Y){var X=Q[Y],V=X.value,K=E0.Type.UTF8;if("valueTagClass"in X)K=X.valueTagClass;if(K===E0.Type.UTF8)V=Q6.util.encodeUtf8(V);var z=!1;if("valueConstructed"in X)z=X.valueConstructed;var G=E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[E0.create(E0.Class.UNIVERSAL,E0.Type.OID,!1,E0.oidToDer(X.type).getBytes()),E0.create(E0.Class.UNIVERSAL,E0.Type.SET,!0,[E0.create(E0.Class.UNIVERSAL,K,z,V)])]);Z.value.push(G)}return Z}var G03=new Date("1950-01-01T00:00:00Z"),F03=new Date("2050-01-01T00:00:00Z");function DI4(J){if(J>=G03&&J<F03)return E0.create(E0.Class.UNIVERSAL,E0.Type.UTCTIME,!1,E0.dateToUtcTime(J));else return E0.create(E0.Class.UNIVERSAL,E0.Type.GENERALIZEDTIME,!1,E0.dateToGeneralizedTime(J))}e1.getTBSCertificate=function(J){var Z=DI4(J.validity.notBefore),Q=DI4(J.validity.notAfter),Y=E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[E0.create(E0.Class.CONTEXT_SPECIFIC,0,!0,[E0.create(E0.Class.UNIVERSAL,E0.Type.INTEGER,!1,E0.integerToDer(J.version).getBytes())]),E0.create(E0.Class.UNIVERSAL,E0.Type.INTEGER,!1,Q6.util.hexToBytes(J.serialNumber)),E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[E0.create(E0.Class.UNIVERSAL,E0.Type.OID,!1,E0.oidToDer(J.siginfo.algorithmOid).getBytes()),yc0(J.siginfo.algorithmOid,J.siginfo.parameters)]),U_(J.issuer),E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[Z,Q]),U_(J.subject),e1.publicKeyToAsn1(J.publicKey)]);if(J.issuer.uniqueId)Y.value.push(E0.create(E0.Class.CONTEXT_SPECIFIC,1,!0,[E0.create(E0.Class.UNIVERSAL,E0.Type.BITSTRING,!1,String.fromCharCode(0)+J.issuer.uniqueId)]));if(J.subject.uniqueId)Y.value.push(E0.create(E0.Class.CONTEXT_SPECIFIC,2,!0,[E0.create(E0.Class.UNIVERSAL,E0.Type.BITSTRING,!1,String.fromCharCode(0)+J.subject.uniqueId)]));if(J.extensions.length>0)Y.value.push(e1.certificateExtensionsToAsn1(J.extensions));return Y};e1.getCertificationRequestInfo=function(J){var Z=E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[E0.create(E0.Class.UNIVERSAL,E0.Type.INTEGER,!1,E0.integerToDer(J.version).getBytes()),U_(J.subject),e1.publicKeyToAsn1(J.publicKey),z03(J)]);return Z};e1.distinguishedNameToAsn1=function(J){return U_(J)};e1.certificateToAsn1=function(J){var Z=J.tbsCertificate||e1.getTBSCertificate(J);return E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[Z,E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[E0.create(E0.Class.UNIVERSAL,E0.Type.OID,!1,E0.oidToDer(J.signatureOid).getBytes()),yc0(J.signatureOid,J.signatureParameters)]),E0.create(E0.Class.UNIVERSAL,E0.Type.BITSTRING,!1,String.fromCharCode(0)+J.signature)])};e1.certificateExtensionsToAsn1=function(J){var Z=E0.create(E0.Class.CONTEXT_SPECIFIC,3,!0,[]),Q=E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[]);Z.value.push(Q);for(var Y=0;Y<J.length;++Y)Q.value.push(e1.certificateExtensionToAsn1(J[Y]));return Z};e1.certificateExtensionToAsn1=function(J){var Z=E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[]);if(Z.value.push(E0.create(E0.Class.UNIVERSAL,E0.Type.OID,!1,E0.oidToDer(J.id).getBytes())),J.critical)Z.value.push(E0.create(E0.Class.UNIVERSAL,E0.Type.BOOLEAN,!1,String.fromCharCode(255)));var Q=J.value;if(typeof J.value!=="string")Q=E0.toDer(Q).getBytes();return Z.value.push(E0.create(E0.Class.UNIVERSAL,E0.Type.OCTETSTRING,!1,Q)),Z};e1.certificationRequestToAsn1=function(J){var Z=J.certificationRequestInfo||e1.getCertificationRequestInfo(J);return E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[Z,E0.create(E0.Class.UNIVERSAL,E0.Type.SEQUENCE,!0,[E0.create(E0.Class.UNIVERSAL,E0.Type.OID,!1,E0.oidToDer(J.signatureOid).getBytes()),yc0(J.signatureOid,J.signatureParameters)]),E0.create(E0.Class.UNIVERSAL,E0.Type.BITSTRING,!1,String.fromCharCode(0)+J.signature)])};e1.createCaStore=function(J){var Z={certs:{}};Z.getIssuer=function(K){var z=Q(K.issuer);return z},Z.addCertificate=function(K){if(typeof K==="string")K=Q6.pki.certificateFromPem(K);if(Y(K.subject),!Z.hasCertificate(K))if(K.subject.hash in Z.certs){var z=Z.certs[K.subject.hash];if(!Q6.util.isArray(z))z=[z];z.push(K),Z.certs[K.subject.hash]=z}else Z.certs[K.subject.hash]=K},Z.hasCertificate=function(K){if(typeof K==="string")K=Q6.pki.certificateFromPem(K);var z=Q(K.subject);if(!z)return!1;if(!Q6.util.isArray(z))z=[z];var G=E0.toDer(e1.certificateToAsn1(K)).getBytes();for(var F=0;F<z.length;++F){var U=E0.toDer(e1.certificateToAsn1(z[F])).getBytes();if(G===U)return!0}return!1},Z.listAllCertificates=function(){var K=[];for(var z in Z.certs)if(Z.certs.hasOwnProperty(z)){var G=Z.certs[z];if(!Q6.util.isArray(G))K.push(G);else for(var F=0;F<G.length;++F)K.push(G[F])}return K},Z.removeCertificate=function(K){var z;if(typeof K==="string")K=Q6.pki.certificateFromPem(K);if(Y(K.subject),!Z.hasCertificate(K))return null;var G=Q(K.subject);if(!Q6.util.isArray(G))return z=Z.certs[K.subject.hash],delete Z.certs[K.subject.hash],z;var F=E0.toDer(e1.certificateToAsn1(K)).getBytes();for(var U=0;U<G.length;++U){var q=E0.toDer(e1.certificateToAsn1(G[U])).getBytes();if(F===q)z=G[U],G.splice(U,1)}if(G.length===0)delete Z.certs[K.subject.hash];return z};function Q(K){return Y(K),Z.certs[K.hash]||null}function Y(K){if(!K.hash){var z=Q6.md.sha1.create();K.attributes=e1.RDNAttributesAsArray(U_(K),z),K.hash=z.digest().toHex()}}if(J)for(var X=0;X<J.length;++X){var V=J[X];Z.addCertificate(V)}return Z};e1.certificateError={bad_certificate:"forge.pki.BadCertificate",unsupported_certificate:"forge.pki.UnsupportedCertificate",certificate_revoked:"forge.pki.CertificateRevoked",certificate_expired:"forge.pki.CertificateExpired",certificate_unknown:"forge.pki.CertificateUnknown",unknown_ca:"forge.pki.UnknownCertificateAuthority"};e1.verifyCertificateChain=function(J,Z,Q){if(typeof Q==="function")Q={verify:Q};Q=Q||{},Z=Z.slice(0);var Y=Z.slice(0),X=Q.validityCheckDate;if(typeof X>"u")X=new Date;var V=!0,K=null,z=0;do{var G=Z.shift(),F=null,U=!1;if(X){if(X<G.validity.notBefore||X>G.validity.notAfter)K={message:"Certificate is not valid yet or has expired.",error:e1.certificateError.certificate_expired,notBefore:G.validity.notBefore,notAfter:G.validity.notAfter,now:X}}if(K===null){if(F=Z[0]||J.getIssuer(G),F===null){if(G.isIssuer(G))U=!0,F=G}if(F){var q=F;if(!Q6.util.isArray(q))q=[q];var D=!1;while(!D&&q.length>0){F=q.shift();try{D=F.verify(G)}catch(M){}}if(!D)K={message:"Certificate signature is invalid.",error:e1.certificateError.bad_certificate}}if(K===null&&(!F||U)&&!J.hasCertificate(G))K={message:"Certificate is not trusted.",error:e1.certificateError.unknown_ca}}if(K===null&&F&&!G.isIssuer(F))K={message:"Certificate issuer is invalid.",error:e1.certificateError.bad_certificate};if(K===null){var W={keyUsage:!0,basicConstraints:!0};for(var H=0;K===null&&H<G.extensions.length;++H){var B=G.extensions[H];if(B.critical&&!(B.name in W))K={message:"Certificate has an unsupported critical extension.",error:e1.certificateError.unsupported_certificate}}}if(K===null&&(!V||Z.length===0&&(!F||U))){var w=G.getExtension("basicConstraints"),N=G.getExtension("keyUsage");if(N!==null){if(!N.keyCertSign||w===null)K={message:"Certificate keyUsage or basicConstraints conflict or indicate that the certificate is not a CA. If the certificate is the only one in the chain or isn't the first then the certificate must be a valid CA.",error:e1.certificateError.bad_certificate}}if(K===null&&w!==null&&!w.cA)K={message:"Certificate basicConstraints indicates the certificate is not a CA.",error:e1.certificateError.bad_certificate};if(K===null&&N!==null&&"pathLenConstraint"in w){var O=z-1;if(O>w.pathLenConstraint)K={message:"Certificate basicConstraints pathLenConstraint violated.",error:e1.certificateError.bad_certificate}}}var E=K===null?!0:K.error,L=Q.verify?Q.verify(E,z,Y):E;if(L===!0)K=null;else{if(E===!0)K={message:"The application rejected the certificate.",error:e1.certificateError.bad_certificate};if(L||L===0){if(typeof L==="object"&&!Q6.util.isArray(L)){if(L.message)K.message=L.message;if(L.error)K.error=L.error}else if(typeof L==="string")K.error=L}throw K}V=!1,++z}while(Z.length>0);return!0}});var xc0=u((zE9,OI4)=>{var U8=J5();oV();Y_();zB();vc0();Sc0();JX();Ed();z_();c5();oJ0();var{asn1:y0,pki:B5}=U8,Md=OI4.exports=U8.pkcs12=U8.pkcs12||{},NI4={name:"ContentInfo",tagClass:y0.Class.UNIVERSAL,type:y0.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.contentType",tagClass:y0.Class.UNIVERSAL,type:y0.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:y0.Class.CONTEXT_SPECIFIC,constructed:!0,captureAsn1:"content"}]},U03={name:"PFX",tagClass:y0.Class.UNIVERSAL,type:y0.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.version",tagClass:y0.Class.UNIVERSAL,type:y0.Type.INTEGER,constructed:!1,capture:"version"},NI4,{name:"PFX.macData",tagClass:y0.Class.UNIVERSAL,type:y0.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"mac",value:[{name:"PFX.macData.mac",tagClass:y0.Class.UNIVERSAL,type:y0.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.macData.mac.digestAlgorithm",tagClass:y0.Class.UNIVERSAL,type:y0.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.macData.mac.digestAlgorithm.algorithm",tagClass:y0.Class.UNIVERSAL,type:y0.Type.OID,constructed:!1,capture:"macAlgorithm"},{name:"PFX.macData.mac.digestAlgorithm.parameters",optional:!0,tagClass:y0.Class.UNIVERSAL,captureAsn1:"macAlgorithmParameters"}]},{name:"PFX.macData.mac.digest",tagClass:y0.Class.UNIVERSAL,type:y0.Type.OCTETSTRING,constructed:!1,capture:"macDigest"}]},{name:"PFX.macData.macSalt",tagClass:y0.Class.UNIVERSAL,type:y0.Type.OCTETSTRING,constructed:!1,capture:"macSalt"},{name:"PFX.macData.iterations",tagClass:y0.Class.UNIVERSAL,type:y0.Type.INTEGER,constructed:!1,optional:!0,capture:"macIterations"}]}]},q03={name:"SafeBag",tagClass:y0.Class.UNIVERSAL,type:y0.Type.SEQUENCE,constructed:!0,value:[{name:"SafeBag.bagId",tagClass:y0.Class.UNIVERSAL,type:y0.Type.OID,constructed:!1,capture:"bagId"},{name:"SafeBag.bagValue",tagClass:y0.Class.CONTEXT_SPECIFIC,constructed:!0,captureAsn1:"bagValue"},{name:"SafeBag.bagAttributes",tagClass:y0.Class.UNIVERSAL,type:y0.Type.SET,constructed:!0,optional:!0,capture:"bagAttributes"}]},D03={name:"Attribute",tagClass:y0.Class.UNIVERSAL,type:y0.Type.SEQUENCE,constructed:!0,value:[{name:"Attribute.attrId",tagClass:y0.Class.UNIVERSAL,type:y0.Type.OID,constructed:!1,capture:"oid"},{name:"Attribute.attrValues",tagClass:y0.Class.UNIVERSAL,type:y0.Type.SET,constructed:!0,capture:"values"}]},W03={name:"CertBag",tagClass:y0.Class.UNIVERSAL,type:y0.Type.SEQUENCE,constructed:!0,value:[{name:"CertBag.certId",tagClass:y0.Class.UNIVERSAL,type:y0.Type.OID,constructed:!1,capture:"certId"},{name:"CertBag.certValue",tagClass:y0.Class.CONTEXT_SPECIFIC,constructed:!0,value:[{name:"CertBag.certValue[0]",tagClass:y0.Class.UNIVERSAL,type:y0.Class.OCTETSTRING,constructed:!1,capture:"cert"}]}]};function Ld(J,Z,Q,Y){var X=[];for(var V=0;V<J.length;V++)for(var K=0;K<J[V].safeBags.length;K++){var z=J[V].safeBags[K];if(Y!==void 0&&z.type!==Y)continue;if(Z===null){X.push(z);continue}if(z.attributes[Z]!==void 0&&z.attributes[Z].indexOf(Q)>=0)X.push(z)}return X}Md.pkcs12FromAsn1=function(J,Z,Q){if(typeof Z==="string")Q=Z,Z=!0;else if(Z===void 0)Z=!0;var Y={},X=[];if(!y0.validate(J,U03,Y,X)){var V=Error("Cannot read PKCS#12 PFX. ASN.1 object is not an PKCS#12 PFX.");throw V.errors=V,V}var K={version:Y.version.charCodeAt(0),safeContents:[],getBags:function(w){var N={},O;if("localKeyId"in w)O=w.localKeyId;else if("localKeyIdHex"in w)O=U8.util.hexToBytes(w.localKeyIdHex);if(O===void 0&&!("friendlyName"in w)&&"bagType"in w)N[w.bagType]=Ld(K.safeContents,null,null,w.bagType);if(O!==void 0)N.localKeyId=Ld(K.safeContents,"localKeyId",O,w.bagType);if("friendlyName"in w)N.friendlyName=Ld(K.safeContents,"friendlyName",w.friendlyName,w.bagType);return N},getBagsByFriendlyName:function(w,N){return Ld(K.safeContents,"friendlyName",w,N)},getBagsByLocalKeyId:function(w,N){return Ld(K.safeContents,"localKeyId",w,N)}};if(Y.version.charCodeAt(0)!==3){var V=Error("PKCS#12 PFX of version other than 3 not supported.");throw V.version=Y.version.charCodeAt(0),V}if(y0.derToOid(Y.contentType)!==B5.oids.data){var V=Error("Only PKCS#12 PFX in password integrity mode supported.");throw V.oid=y0.derToOid(Y.contentType),V}var z=Y.content.value[0];if(z.tagClass!==y0.Class.UNIVERSAL||z.type!==y0.Type.OCTETSTRING)throw Error("PKCS#12 authSafe content data is not an OCTET STRING.");if(z=uc0(z),Y.mac){var G=null,F=0,U=y0.derToOid(Y.macAlgorithm);switch(U){case B5.oids.sha1:G=U8.md.sha1.create(),F=20;break;case B5.oids.sha256:G=U8.md.sha256.create(),F=32;break;case B5.oids.sha384:G=U8.md.sha384.create(),F=48;break;case B5.oids.sha512:G=U8.md.sha512.create(),F=64;break;case B5.oids.md5:G=U8.md.md5.create(),F=16;break}if(G===null)throw Error("PKCS#12 uses unsupported MAC algorithm: "+U);var q=new U8.util.ByteBuffer(Y.macSalt),D="macIterations"in Y?parseInt(U8.util.bytesToHex(Y.macIterations),16):1,W=Md.generateKey(Q,q,3,D,F,G),H=U8.hmac.create();H.start(G,W),H.update(z.value);var B=H.getMac();if(B.getBytes()!==Y.macDigest)throw Error("PKCS#12 MAC could not be verified. Invalid password?")}else if(Array.isArray(J.value)&&J.value.length>2)throw Error("Invalid PKCS#12. macData field present but MAC was not validated.");return H03(K,z.value,Z,Q),K};function uc0(J){if(J.composed||J.constructed){var Z=U8.util.createBuffer();for(var Q=0;Q<J.value.length;++Q)Z.putBytes(J.value[Q].value);J.composed=J.constructed=!1,J.value=Z.getBytes()}return J}function H03(J,Z,Q,Y){if(Z=y0.fromDer(Z,Q),Z.tagClass!==y0.Class.UNIVERSAL||Z.type!==y0.Type.SEQUENCE||Z.constructed!==!0)throw Error("PKCS#12 AuthenticatedSafe expected to be a SEQUENCE OF ContentInfo");for(var X=0;X<Z.value.length;X++){var V=Z.value[X],K={},z=[];if(!y0.validate(V,NI4,K,z)){var G=Error("Cannot read ContentInfo.");throw G.errors=z,G}var F={encrypted:!1},U=null,q=K.content.value[0];switch(y0.derToOid(K.contentType)){case B5.oids.data:if(q.tagClass!==y0.Class.UNIVERSAL||q.type!==y0.Type.OCTETSTRING)throw Error("PKCS#12 SafeContents Data is not an OCTET STRING.");U=uc0(q).value;break;case B5.oids.encryptedData:U=B03(q,Y),F.encrypted=!0;break;default:var G=Error("Unsupported PKCS#12 contentType.");throw G.contentType=y0.derToOid(K.contentType),G}F.safeBags=w03(U,Q,Y),J.safeContents.push(F)}}function B03(J,Z){var Q={},Y=[];if(!y0.validate(J,U8.pkcs7.asn1.encryptedDataValidator,Q,Y)){var X=Error("Cannot read EncryptedContentInfo.");throw X.errors=Y,X}var V=y0.derToOid(Q.contentType);if(V!==B5.oids.data){var X=Error("PKCS#12 EncryptedContentInfo ContentType is not Data.");throw X.oid=V,X}V=y0.derToOid(Q.encAlgorithm);var K=B5.pbe.getCipher(V,Q.encParameter,Z),z=uc0(Q.encryptedContentAsn1),G=U8.util.createBuffer(z.value);if(K.update(G),!K.finish())throw Error("Failed to decrypt PKCS#12 SafeContents.");return K.output.getBytes()}function w03(J,Z,Q){if(!Z&&J.length===0)return[];if(J=y0.fromDer(J,Z),J.tagClass!==y0.Class.UNIVERSAL||J.type!==y0.Type.SEQUENCE||J.constructed!==!0)throw Error("PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag.");var Y=[];for(var X=0;X<J.value.length;X++){var V=J.value[X],K={},z=[];if(!y0.validate(V,q03,K,z)){var G=Error("Cannot read SafeBag.");throw G.errors=z,G}var F={type:y0.derToOid(K.bagId),attributes:N03(K.bagAttributes)};Y.push(F);var U,q,D=K.bagValue.value[0];switch(F.type){case B5.oids.pkcs8ShroudedKeyBag:if(D=B5.decryptPrivateKeyInfo(D,Q),D===null)throw Error("Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?");case B5.oids.keyBag:try{F.key=B5.privateKeyFromAsn1(D)}catch(H){F.key=null,F.asn1=D}continue;case B5.oids.certBag:U=W03,q=function(){if(y0.derToOid(K.certId)!==B5.oids.x509Certificate){var H=Error("Unsupported certificate type, only X.509 supported.");throw H.oid=y0.derToOid(K.certId),H}var B=y0.fromDer(K.cert,Z);try{F.cert=B5.certificateFromAsn1(B,!0)}catch(w){F.cert=null,F.asn1=B}};break;default:var G=Error("Unsupported PKCS#12 SafeBag type.");throw G.oid=F.type,G}if(U!==void 0&&!y0.validate(D,U,K,z)){var G=Error("Cannot read PKCS#12 "+U.name);throw G.errors=z,G}q()}return Y}function N03(J){var Z={};if(J!==void 0)for(var Q=0;Q<J.length;++Q){var Y={},X=[];if(!y0.validate(J[Q],D03,Y,X)){var V=Error("Cannot read PKCS#12 BagAttribute.");throw V.errors=X,V}var K=y0.derToOid(Y.oid);if(B5.oids[K]===void 0)continue;Z[B5.oids[K]]=[];for(var z=0;z<Y.values.length;++z)Z[B5.oids[K]].push(Y.values[z].value)}return Z}Md.toPkcs12Asn1=function(J,Z,Q,Y){if(Y=Y||{},Y.saltSize=Y.saltSize||8,Y.count=Y.count||2048,Y.algorithm=Y.algorithm||Y.encAlgorithm||"aes128",!("useMac"in Y))Y.useMac=!0;if(!("localKeyId"in Y))Y.localKeyId=null;if(!("generateLocalKeyId"in Y))Y.generateLocalKeyId=!0;var X=Y.localKeyId,V;if(X!==null)X=U8.util.hexToBytes(X);else if(Y.generateLocalKeyId)if(Z){var K=U8.util.isArray(Z)?Z[0]:Z;if(typeof K==="string")K=B5.certificateFromPem(K);var z=U8.md.sha1.create();z.update(y0.toDer(B5.certificateToAsn1(K)).getBytes()),X=z.digest().getBytes()}else X=U8.random.getBytes(20);var G=[];if(X!==null)G.push(y0.create(y0.Class.UNIVERSAL,y0.Type.SEQUENCE,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.OID,!1,y0.oidToDer(B5.oids.localKeyId).getBytes()),y0.create(y0.Class.UNIVERSAL,y0.Type.SET,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.OCTETSTRING,!1,X)])]));if("friendlyName"in Y)G.push(y0.create(y0.Class.UNIVERSAL,y0.Type.SEQUENCE,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.OID,!1,y0.oidToDer(B5.oids.friendlyName).getBytes()),y0.create(y0.Class.UNIVERSAL,y0.Type.SET,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.BMPSTRING,!1,Y.friendlyName)])]));if(G.length>0)V=y0.create(y0.Class.UNIVERSAL,y0.Type.SET,!0,G);var F=[],U=[];if(Z!==null)if(U8.util.isArray(Z))U=Z;else U=[Z];var q=[];for(var D=0;D<U.length;++D){if(Z=U[D],typeof Z==="string")Z=B5.certificateFromPem(Z);var W=D===0?V:void 0,H=B5.certificateToAsn1(Z),B=y0.create(y0.Class.UNIVERSAL,y0.Type.SEQUENCE,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.OID,!1,y0.oidToDer(B5.oids.certBag).getBytes()),y0.create(y0.Class.CONTEXT_SPECIFIC,0,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.SEQUENCE,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.OID,!1,y0.oidToDer(B5.oids.x509Certificate).getBytes()),y0.create(y0.Class.CONTEXT_SPECIFIC,0,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.OCTETSTRING,!1,y0.toDer(H).getBytes())])])]),W]);q.push(B)}if(q.length>0){var w=y0.create(y0.Class.UNIVERSAL,y0.Type.SEQUENCE,!0,q),N=y0.create(y0.Class.UNIVERSAL,y0.Type.SEQUENCE,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.OID,!1,y0.oidToDer(B5.oids.data).getBytes()),y0.create(y0.Class.CONTEXT_SPECIFIC,0,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.OCTETSTRING,!1,y0.toDer(w).getBytes())])]);F.push(N)}var O=null;if(J!==null){var E=B5.wrapRsaPrivateKey(B5.privateKeyToAsn1(J));if(Q===null)O=y0.create(y0.Class.UNIVERSAL,y0.Type.SEQUENCE,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.OID,!1,y0.oidToDer(B5.oids.keyBag).getBytes()),y0.create(y0.Class.CONTEXT_SPECIFIC,0,!0,[E]),V]);else O=y0.create(y0.Class.UNIVERSAL,y0.Type.SEQUENCE,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.OID,!1,y0.oidToDer(B5.oids.pkcs8ShroudedKeyBag).getBytes()),y0.create(y0.Class.CONTEXT_SPECIFIC,0,!0,[B5.encryptPrivateKeyInfo(E,Q,Y)]),V]);var L=y0.create(y0.Class.UNIVERSAL,y0.Type.SEQUENCE,!0,[O]),M=y0.create(y0.Class.UNIVERSAL,y0.Type.SEQUENCE,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.OID,!1,y0.oidToDer(B5.oids.data).getBytes()),y0.create(y0.Class.CONTEXT_SPECIFIC,0,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.OCTETSTRING,!1,y0.toDer(L).getBytes())])]);F.push(M)}var A=y0.create(y0.Class.UNIVERSAL,y0.Type.SEQUENCE,!0,F),I;if(Y.useMac){var z=U8.md.sha1.create(),P=new U8.util.ByteBuffer(U8.random.getBytes(Y.saltSize)),_=Y.count,J=Md.generateKey(Q,P,3,_,20),S=U8.hmac.create();S.start(z,J),S.update(y0.toDer(A).getBytes());var y=S.getMac();I=y0.create(y0.Class.UNIVERSAL,y0.Type.SEQUENCE,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.SEQUENCE,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.SEQUENCE,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.OID,!1,y0.oidToDer(B5.oids.sha1).getBytes()),y0.create(y0.Class.UNIVERSAL,y0.Type.NULL,!1,"")]),y0.create(y0.Class.UNIVERSAL,y0.Type.OCTETSTRING,!1,y.getBytes())]),y0.create(y0.Class.UNIVERSAL,y0.Type.OCTETSTRING,!1,P.getBytes()),y0.create(y0.Class.UNIVERSAL,y0.Type.INTEGER,!1,y0.integerToDer(_).getBytes())])}return y0.create(y0.Class.UNIVERSAL,y0.Type.SEQUENCE,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.INTEGER,!1,y0.integerToDer(3).getBytes()),y0.create(y0.Class.UNIVERSAL,y0.Type.SEQUENCE,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.OID,!1,y0.oidToDer(B5.oids.data).getBytes()),y0.create(y0.Class.CONTEXT_SPECIFIC,0,!0,[y0.create(y0.Class.UNIVERSAL,y0.Type.OCTETSTRING,!1,y0.toDer(A).getBytes())])]),I])};Md.generateKey=U8.pbe.generatePkcs12Key});var bc0=u((GE9,EI4)=>{var qB=J5();oV();zB();Sc0();lL();hJ0();xc0();iJ0();Ed();c5();oJ0();var fc0=qB.asn1,q_=EI4.exports=qB.pki=qB.pki||{};q_.pemToDer=function(J){var Z=qB.pem.decode(J)[0];if(Z.procType&&Z.procType.type==="ENCRYPTED")throw Error("Could not convert PEM to DER; PEM is encrypted.");return qB.util.createBuffer(Z.body)};q_.privateKeyFromPem=function(J){var Z=qB.pem.decode(J)[0];if(Z.type!=="PRIVATE KEY"&&Z.type!=="RSA PRIVATE KEY"){var Q=Error('Could not convert private key from PEM; PEM header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".');throw Q.headerType=Z.type,Q}if(Z.procType&&Z.procType.type==="ENCRYPTED")throw Error("Could not convert private key from PEM; PEM is encrypted.");var Y=fc0.fromDer(Z.body);return q_.privateKeyFromAsn1(Y)};q_.privateKeyToPem=function(J,Z){var Q={type:"RSA PRIVATE KEY",body:fc0.toDer(q_.privateKeyToAsn1(J)).getBytes()};return qB.pem.encode(Q,{maxline:Z})};q_.privateKeyInfoToPem=function(J,Z){var Q={type:"PRIVATE KEY",body:fc0.toDer(J).getBytes()};return qB.pem.encode(Q,{maxline:Z})}});var cc0=u((FE9,CI4)=>{var S1=J5();oV();Y_();uJ0();lL();bc0();JX();z_();c5();var tJ0=function(J,Z,Q,Y){var X=S1.util.createBuffer(),V=J.length>>1,K=V+(J.length&1),z=J.substr(0,K),G=J.substr(V,K),F=S1.util.createBuffer(),U=S1.hmac.create();Q=Z+Q;var q=Math.ceil(Y/16),D=Math.ceil(Y/20);U.start("MD5",z);var W=S1.util.createBuffer();F.putBytes(Q);for(var H=0;H<q;++H)U.start(null,null),U.update(F.getBytes()),F.putBuffer(U.digest()),U.start(null,null),U.update(F.bytes()+Q),W.putBuffer(U.digest());U.start("SHA1",G);var B=S1.util.createBuffer();F.clear(),F.putBytes(Q);for(var H=0;H<D;++H)U.start(null,null),U.update(F.getBytes()),F.putBuffer(U.digest()),U.start(null,null),U.update(F.bytes()+Q),B.putBuffer(U.digest());return X.putBytes(S1.util.xorBytes(W.getBytes(),B.getBytes(),Y)),X},O03=function(J,Z,Q){var Y=S1.hmac.create();Y.start("SHA1",J);var X=S1.util.createBuffer();return X.putInt32(Z[0]),X.putInt32(Z[1]),X.putByte(Q.type),X.putByte(Q.version.major),X.putByte(Q.version.minor),X.putInt16(Q.length),X.putBytes(Q.fragment.bytes()),Y.update(X.getBytes()),Y.digest().getBytes()},E03=function(J,Z,Q){var Y=!1;try{var X=J.deflate(Z.fragment.getBytes());Z.fragment=S1.util.createBuffer(X),Z.length=X.length,Y=!0}catch(V){}return Y},L03=function(J,Z,Q){var Y=!1;try{var X=J.inflate(Z.fragment.getBytes());Z.fragment=S1.util.createBuffer(X),Z.length=X.length,Y=!0}catch(V){}return Y},TQ=function(J,Z){var Q=0;switch(Z){case 1:Q=J.getByte();break;case 2:Q=J.getInt16();break;case 3:Q=J.getInt24();break;case 4:Q=J.getInt32();break}return S1.util.createBuffer(J.getBytes(Q))},XX=function(J,Z,Q){J.putInt(Q.length(),Z<<3),J.putBuffer(Q)},A0={};A0.Versions={TLS_1_0:{major:3,minor:1},TLS_1_1:{major:3,minor:2},TLS_1_2:{major:3,minor:3}};A0.SupportedVersions=[A0.Versions.TLS_1_1,A0.Versions.TLS_1_0];A0.Version=A0.SupportedVersions[0];A0.MaxFragment=15360;A0.ConnectionEnd={server:0,client:1};A0.PRFAlgorithm={tls_prf_sha256:0};A0.BulkCipherAlgorithm={none:null,rc4:0,des3:1,aes:2};A0.CipherType={stream:0,block:1,aead:2};A0.MACAlgorithm={none:null,hmac_md5:0,hmac_sha1:1,hmac_sha256:2,hmac_sha384:3,hmac_sha512:4};A0.CompressionMethod={none:0,deflate:1};A0.ContentType={change_cipher_spec:20,alert:21,handshake:22,application_data:23,heartbeat:24};A0.HandshakeType={hello_request:0,client_hello:1,server_hello:2,certificate:11,server_key_exchange:12,certificate_request:13,server_hello_done:14,certificate_verify:15,client_key_exchange:16,finished:20};A0.Alert={};A0.Alert.Level={warning:1,fatal:2};A0.Alert.Description={close_notify:0,unexpected_message:10,bad_record_mac:20,decryption_failed:21,record_overflow:22,decompression_failure:30,handshake_failure:40,bad_certificate:42,unsupported_certificate:43,certificate_revoked:44,certificate_expired:45,certificate_unknown:46,illegal_parameter:47,unknown_ca:48,access_denied:49,decode_error:50,decrypt_error:51,export_restriction:60,protocol_version:70,insufficient_security:71,internal_error:80,user_canceled:90,no_renegotiation:100};A0.HeartbeatMessageType={heartbeat_request:1,heartbeat_response:2};A0.CipherSuites={};A0.getCipherSuite=function(J){var Z=null;for(var Q in A0.CipherSuites){var Y=A0.CipherSuites[Q];if(Y.id[0]===J.charCodeAt(0)&&Y.id[1]===J.charCodeAt(1)){Z=Y;break}}return Z};A0.handleUnexpected=function(J,Z){var Q=!J.open&&J.entity===A0.ConnectionEnd.client;if(!Q)J.error(J,{message:"Unexpected message. Received TLS record out of order.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.unexpected_message}})};A0.handleHelloRequest=function(J,Z,Q){if(!J.handshaking&&J.handshakes>0)A0.queue(J,A0.createAlert(J,{level:A0.Alert.Level.warning,description:A0.Alert.Description.no_renegotiation})),A0.flush(J);J.process()};A0.parseHelloMessage=function(J,Z,Q){var Y=null,X=J.entity===A0.ConnectionEnd.client;if(Q<38)J.error(J,{message:X?"Invalid ServerHello message. Message too short.":"Invalid ClientHello message. Message too short.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.illegal_parameter}});else{var V=Z.fragment,K=V.length();if(Y={version:{major:V.getByte(),minor:V.getByte()},random:S1.util.createBuffer(V.getBytes(32)),session_id:TQ(V,1),extensions:[]},X)Y.cipher_suite=V.getBytes(2),Y.compression_method=V.getByte();else Y.cipher_suites=TQ(V,2),Y.compression_methods=TQ(V,1);if(K=Q-(K-V.length()),K>0){var z=TQ(V,2);while(z.length()>0)Y.extensions.push({type:[z.getByte(),z.getByte()],data:TQ(z,2)});if(!X)for(var G=0;G<Y.extensions.length;++G){var F=Y.extensions[G];if(F.type[0]===0&&F.type[1]===0){var U=TQ(F.data,2);while(U.length()>0){var q=U.getByte();if(q!==0)break;J.session.extensions.server_name.serverNameList.push(TQ(U,2).getBytes())}}}}if(J.session.version){if(Y.version.major!==J.session.version.major||Y.version.minor!==J.session.version.minor)return J.error(J,{message:"TLS version change is disallowed during renegotiation.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.protocol_version}})}if(X)J.session.cipherSuite=A0.getCipherSuite(Y.cipher_suite);else{var D=S1.util.createBuffer(Y.cipher_suites.bytes());while(D.length()>0)if(J.session.cipherSuite=A0.getCipherSuite(D.getBytes(2)),J.session.cipherSuite!==null)break}if(J.session.cipherSuite===null)return J.error(J,{message:"No cipher suites in common.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.handshake_failure},cipherSuite:S1.util.bytesToHex(Y.cipher_suite)});if(X)J.session.compressionMethod=Y.compression_method;else J.session.compressionMethod=A0.CompressionMethod.none}return Y};A0.createSecurityParameters=function(J,Z){var Q=J.entity===A0.ConnectionEnd.client,Y=Z.random.bytes(),X=Q?J.session.sp.client_random:Y,V=Q?Y:A0.createRandom().getBytes();J.session.sp={entity:J.entity,prf_algorithm:A0.PRFAlgorithm.tls_prf_sha256,bulk_cipher_algorithm:null,cipher_type:null,enc_key_length:null,block_length:null,fixed_iv_length:null,record_iv_length:null,mac_algorithm:null,mac_length:null,mac_key_length:null,compression_algorithm:J.session.compressionMethod,pre_master_secret:null,master_secret:null,client_random:X,server_random:V}};A0.handleServerHello=function(J,Z,Q){var Y=A0.parseHelloMessage(J,Z,Q);if(J.fail)return;if(Y.version.minor<=J.version.minor)J.version.minor=Y.version.minor;else return J.error(J,{message:"Incompatible TLS version.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.protocol_version}});J.session.version=J.version;var X=Y.session_id.bytes();if(X.length>0&&X===J.session.id)J.expect=AI4,J.session.resuming=!0,J.session.sp.server_random=Y.random.bytes();else J.expect=A03,J.session.resuming=!1,A0.createSecurityParameters(J,Y);J.session.id=X,J.process()};A0.handleClientHello=function(J,Z,Q){var Y=A0.parseHelloMessage(J,Z,Q);if(J.fail)return;var X=Y.session_id.bytes(),V=null;if(J.sessionCache){if(V=J.sessionCache.getSession(X),V===null)X="";else if(V.version.major!==Y.version.major||V.version.minor>Y.version.minor)V=null,X=""}if(X.length===0)X=S1.random.getBytes(32);if(J.session.id=X,J.session.clientHelloVersion=Y.version,J.session.sp={},V)J.version=J.session.version=V.version,J.session.sp=V.sp;else{var K;for(var z=1;z<A0.SupportedVersions.length;++z)if(K=A0.SupportedVersions[z],K.minor<=Y.version.minor)break;J.version={major:K.major,minor:K.minor},J.session.version=J.version}if(V!==null)J.expect=pc0,J.session.resuming=!0,J.session.sp.client_random=Y.random.bytes();else J.expect=J.verifyClient!==!1?_03:gc0,J.session.resuming=!1,A0.createSecurityParameters(J,Y);if(J.open=!0,A0.queue(J,A0.createRecord(J,{type:A0.ContentType.handshake,data:A0.createServerHello(J)})),J.session.resuming)A0.queue(J,A0.createRecord(J,{type:A0.ContentType.change_cipher_spec,data:A0.createChangeCipherSpec()})),J.state.pending=A0.createConnectionState(J),J.state.current.write=J.state.pending.write,A0.queue(J,A0.createRecord(J,{type:A0.ContentType.handshake,data:A0.createFinished(J)}));else if(A0.queue(J,A0.createRecord(J,{type:A0.ContentType.handshake,data:A0.createCertificate(J)})),!J.fail){if(A0.queue(J,A0.createRecord(J,{type:A0.ContentType.handshake,data:A0.createServerKeyExchange(J)})),J.verifyClient!==!1)A0.queue(J,A0.createRecord(J,{type:A0.ContentType.handshake,data:A0.createCertificateRequest(J)}));A0.queue(J,A0.createRecord(J,{type:A0.ContentType.handshake,data:A0.createServerHelloDone(J)}))}A0.flush(J),J.process()};A0.handleCertificate=function(J,Z,Q){if(Q<3)return J.error(J,{message:"Invalid Certificate message. Message too short.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.illegal_parameter}});var Y=Z.fragment,X={certificate_list:TQ(Y,3)},V,K,z=[];try{while(X.certificate_list.length()>0)V=TQ(X.certificate_list,3),K=S1.asn1.fromDer(V),V=S1.pki.certificateFromAsn1(K,!0),z.push(V)}catch(F){return J.error(J,{message:"Could not parse certificate list.",cause:F,send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.bad_certificate}})}var G=J.entity===A0.ConnectionEnd.client;if((G||J.verifyClient===!0)&&z.length===0)J.error(J,{message:G?"No server certificate provided.":"No client certificate provided.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.illegal_parameter}});else if(z.length===0)J.expect=G?LI4:gc0;else{if(G)J.session.serverCertificate=z[0];else J.session.clientCertificate=z[0];if(A0.verifyCertificateChain(J,z))J.expect=G?LI4:gc0}J.process()};A0.handleServerKeyExchange=function(J,Z,Q){if(Q>0)return J.error(J,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.unsupported_certificate}});J.expect=I03,J.process()};A0.handleClientKeyExchange=function(J,Z,Q){if(Q<48)return J.error(J,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.unsupported_certificate}});var Y=Z.fragment,X={enc_pre_master_secret:TQ(Y,2).getBytes()},V=null;if(J.getPrivateKey)try{V=J.getPrivateKey(J,J.session.serverCertificate),V=S1.pki.privateKeyFromPem(V)}catch(G){J.error(J,{message:"Could not get private key.",cause:G,send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.internal_error}})}if(V===null)return J.error(J,{message:"No private key set.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.internal_error}});try{var K=J.session.sp;K.pre_master_secret=V.decrypt(X.enc_pre_master_secret);var z=J.session.clientHelloVersion;if(z.major!==K.pre_master_secret.charCodeAt(0)||z.minor!==K.pre_master_secret.charCodeAt(1))throw Error("TLS version rollback attack detected.")}catch(G){K.pre_master_secret=S1.random.getBytes(48)}if(J.expect=pc0,J.session.clientCertificate!==null)J.expect=S03;J.process()};A0.handleCertificateRequest=function(J,Z,Q){if(Q<3)return J.error(J,{message:"Invalid CertificateRequest. Message too short.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.illegal_parameter}});var Y=Z.fragment,X={certificate_types:TQ(Y,1),certificate_authorities:TQ(Y,2)};J.session.certificateRequest=X,J.expect=j03,J.process()};A0.handleCertificateVerify=function(J,Z,Q){if(Q<2)return J.error(J,{message:"Invalid CertificateVerify. Message too short.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.illegal_parameter}});var Y=Z.fragment;Y.read-=4;var X=Y.bytes();Y.read+=4;var V={signature:TQ(Y,2).getBytes()},K=S1.util.createBuffer();K.putBuffer(J.session.md5.digest()),K.putBuffer(J.session.sha1.digest()),K=K.getBytes();try{var z=J.session.clientCertificate;if(!z.publicKey.verify(K,V.signature,"NONE"))throw Error("CertificateVerify signature does not match.");J.session.md5.update(X),J.session.sha1.update(X)}catch(G){return J.error(J,{message:"Bad signature in CertificateVerify.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.handshake_failure}})}J.expect=pc0,J.process()};A0.handleServerHelloDone=function(J,Z,Q){if(Q>0)return J.error(J,{message:"Invalid ServerHelloDone message. Invalid length.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.record_overflow}});if(J.serverCertificate===null){var Y={message:"No server certificate provided. Not enough security.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.insufficient_security}},X=0,V=J.verify(J,Y.alert.description,X,[]);if(V!==!0){if(V||V===0){if(typeof V==="object"&&!S1.util.isArray(V)){if(V.message)Y.message=V.message;if(V.alert)Y.alert.description=V.alert}else if(typeof V==="number")Y.alert.description=V}return J.error(J,Y)}}if(J.session.certificateRequest!==null)Z=A0.createRecord(J,{type:A0.ContentType.handshake,data:A0.createCertificate(J)}),A0.queue(J,Z);Z=A0.createRecord(J,{type:A0.ContentType.handshake,data:A0.createClientKeyExchange(J)}),A0.queue(J,Z),J.expect=C03;var K=function(z,G){if(z.session.certificateRequest!==null&&z.session.clientCertificate!==null)A0.queue(z,A0.createRecord(z,{type:A0.ContentType.handshake,data:A0.createCertificateVerify(z,G)}));A0.queue(z,A0.createRecord(z,{type:A0.ContentType.change_cipher_spec,data:A0.createChangeCipherSpec()})),z.state.pending=A0.createConnectionState(z),z.state.current.write=z.state.pending.write,A0.queue(z,A0.createRecord(z,{type:A0.ContentType.handshake,data:A0.createFinished(z)})),z.expect=AI4,A0.flush(z),z.process()};if(J.session.certificateRequest===null||J.session.clientCertificate===null)return K(J,null);A0.getClientSignature(J,K)};A0.handleChangeCipherSpec=function(J,Z){if(Z.fragment.getByte()!==1)return J.error(J,{message:"Invalid ChangeCipherSpec message received.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.illegal_parameter}});var Q=J.entity===A0.ConnectionEnd.client;if(J.session.resuming&&Q||!J.session.resuming&&!Q)J.state.pending=A0.createConnectionState(J);if(J.state.current.read=J.state.pending.read,!J.session.resuming&&Q||J.session.resuming&&!Q)J.state.pending=null;J.expect=Q?R03:v03,J.process()};A0.handleFinished=function(J,Z,Q){var Y=Z.fragment;Y.read-=4;var X=Y.bytes();Y.read+=4;var V=Z.fragment.getBytes();Y=S1.util.createBuffer(),Y.putBuffer(J.session.md5.digest()),Y.putBuffer(J.session.sha1.digest());var K=J.entity===A0.ConnectionEnd.client,z=K?"server finished":"client finished",G=J.session.sp,F=12,U=tJ0;if(Y=U(G.master_secret,z,Y.getBytes(),F),Y.getBytes()!==V)return J.error(J,{message:"Invalid verify_data in Finished message.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.decrypt_error}});if(J.session.md5.update(X),J.session.sha1.update(X),J.session.resuming&&K||!J.session.resuming&&!K)A0.queue(J,A0.createRecord(J,{type:A0.ContentType.change_cipher_spec,data:A0.createChangeCipherSpec()})),J.state.current.write=J.state.pending.write,J.state.pending=null,A0.queue(J,A0.createRecord(J,{type:A0.ContentType.handshake,data:A0.createFinished(J)}));J.expect=K?P03:k03,J.handshaking=!1,++J.handshakes,J.peerCertificate=K?J.session.serverCertificate:J.session.clientCertificate,A0.flush(J),J.isConnected=!0,J.connected(J),J.process()};A0.handleAlert=function(J,Z){var Q=Z.fragment,Y={level:Q.getByte(),description:Q.getByte()},X;switch(Y.description){case A0.Alert.Description.close_notify:X="Connection closed.";break;case A0.Alert.Description.unexpected_message:X="Unexpected message.";break;case A0.Alert.Description.bad_record_mac:X="Bad record MAC.";break;case A0.Alert.Description.decryption_failed:X="Decryption failed.";break;case A0.Alert.Description.record_overflow:X="Record overflow.";break;case A0.Alert.Description.decompression_failure:X="Decompression failed.";break;case A0.Alert.Description.handshake_failure:X="Handshake failure.";break;case A0.Alert.Description.bad_certificate:X="Bad certificate.";break;case A0.Alert.Description.unsupported_certificate:X="Unsupported certificate.";break;case A0.Alert.Description.certificate_revoked:X="Certificate revoked.";break;case A0.Alert.Description.certificate_expired:X="Certificate expired.";break;case A0.Alert.Description.certificate_unknown:X="Certificate unknown.";break;case A0.Alert.Description.illegal_parameter:X="Illegal parameter.";break;case A0.Alert.Description.unknown_ca:X="Unknown certificate authority.";break;case A0.Alert.Description.access_denied:X="Access denied.";break;case A0.Alert.Description.decode_error:X="Decode error.";break;case A0.Alert.Description.decrypt_error:X="Decrypt error.";break;case A0.Alert.Description.export_restriction:X="Export restriction.";break;case A0.Alert.Description.protocol_version:X="Unsupported protocol version.";break;case A0.Alert.Description.insufficient_security:X="Insufficient security.";break;case A0.Alert.Description.internal_error:X="Internal error.";break;case A0.Alert.Description.user_canceled:X="User canceled.";break;case A0.Alert.Description.no_renegotiation:X="Renegotiation not supported.";break;default:X="Unknown error.";break}if(Y.description===A0.Alert.Description.close_notify)return J.close();J.error(J,{message:X,send:!1,origin:J.entity===A0.ConnectionEnd.client?"server":"client",alert:Y}),J.process()};A0.handleHandshake=function(J,Z){var Q=Z.fragment,Y=Q.getByte(),X=Q.getInt24();if(X>Q.length())return J.fragmented=Z,Z.fragment=S1.util.createBuffer(),Q.read-=4,J.process();J.fragmented=null,Q.read-=4;var V=Q.bytes(X+4);if(Q.read+=4,Y in sJ0[J.entity][J.expect]){if(J.entity===A0.ConnectionEnd.server&&!J.open&&!J.fail)J.handshaking=!0,J.session={version:null,extensions:{server_name:{serverNameList:[]}},cipherSuite:null,compressionMethod:null,serverCertificate:null,clientCertificate:null,md5:S1.md.md5.create(),sha1:S1.md.sha1.create()};if(Y!==A0.HandshakeType.hello_request&&Y!==A0.HandshakeType.certificate_verify&&Y!==A0.HandshakeType.finished)J.session.md5.update(V),J.session.sha1.update(V);sJ0[J.entity][J.expect][Y](J,Z,X)}else A0.handleUnexpected(J,Z)};A0.handleApplicationData=function(J,Z){J.data.putBuffer(Z.fragment),J.dataReady(J),J.process()};A0.handleHeartbeat=function(J,Z){var Q=Z.fragment,Y=Q.getByte(),X=Q.getInt16(),V=Q.getBytes(X);if(Y===A0.HeartbeatMessageType.heartbeat_request){if(J.handshaking||X>V.length)return J.process();A0.queue(J,A0.createRecord(J,{type:A0.ContentType.heartbeat,data:A0.createHeartbeat(A0.HeartbeatMessageType.heartbeat_response,V)})),A0.flush(J)}else if(Y===A0.HeartbeatMessageType.heartbeat_response){if(V!==J.expectedHeartbeatPayload)return J.process();if(J.heartbeatReceived)J.heartbeatReceived(J,S1.util.createBuffer(V))}J.process()};var M03=0,A03=1,LI4=2,I03=3,j03=4,AI4=5,R03=6,P03=7,C03=8,T03=0,_03=1,gc0=2,S03=3,pc0=4,v03=5,k03=6,L0=A0.handleUnexpected,II4=A0.handleChangeCipherSpec,v2=A0.handleAlert,HJ=A0.handleHandshake,jI4=A0.handleApplicationData,k2=A0.handleHeartbeat,dc0=[];dc0[A0.ConnectionEnd.client]=[[L0,v2,HJ,L0,k2],[L0,v2,HJ,L0,k2],[L0,v2,HJ,L0,k2],[L0,v2,HJ,L0,k2],[L0,v2,HJ,L0,k2],[II4,v2,L0,L0,k2],[L0,v2,HJ,L0,k2],[L0,v2,HJ,jI4,k2],[L0,v2,HJ,L0,k2]];dc0[A0.ConnectionEnd.server]=[[L0,v2,HJ,L0,k2],[L0,v2,HJ,L0,k2],[L0,v2,HJ,L0,k2],[L0,v2,HJ,L0,k2],[II4,v2,L0,L0,k2],[L0,v2,HJ,L0,k2],[L0,v2,HJ,jI4,k2],[L0,v2,HJ,L0,k2]];var{handleHelloRequest:DB,handleServerHello:y03,handleCertificate:RI4,handleServerKeyExchange:MI4,handleCertificateRequest:hc0,handleServerHelloDone:rJ0,handleFinished:PI4}=A0,sJ0=[];sJ0[A0.ConnectionEnd.client]=[[L0,L0,y03,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0],[DB,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,RI4,MI4,hc0,rJ0,L0,L0,L0,L0,L0,L0],[DB,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,MI4,hc0,rJ0,L0,L0,L0,L0,L0,L0],[DB,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,hc0,rJ0,L0,L0,L0,L0,L0,L0],[DB,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,rJ0,L0,L0,L0,L0,L0,L0],[DB,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0],[DB,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,PI4],[DB,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0],[DB,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0]];var{handleClientHello:u03,handleClientKeyExchange:x03,handleCertificateVerify:f03}=A0;sJ0[A0.ConnectionEnd.server]=[[L0,u03,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0],[L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,RI4,L0,L0,L0,L0,L0,L0,L0,L0,L0],[L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,x03,L0,L0,L0,L0],[L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,f03,L0,L0,L0,L0,L0],[L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0],[L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,PI4],[L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0],[L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0,L0]];A0.generateKeys=function(J,Z){var Q=tJ0,Y=Z.client_random+Z.server_random;if(!J.session.resuming)Z.master_secret=Q(Z.pre_master_secret,"master secret",Y,48).bytes(),Z.pre_master_secret=null;Y=Z.server_random+Z.client_random;var X=2*Z.mac_key_length+2*Z.enc_key_length,V=J.version.major===A0.Versions.TLS_1_0.major&&J.version.minor===A0.Versions.TLS_1_0.minor;if(V)X+=2*Z.fixed_iv_length;var K=Q(Z.master_secret,"key expansion",Y,X),z={client_write_MAC_key:K.getBytes(Z.mac_key_length),server_write_MAC_key:K.getBytes(Z.mac_key_length),client_write_key:K.getBytes(Z.enc_key_length),server_write_key:K.getBytes(Z.enc_key_length)};if(V)z.client_write_IV=K.getBytes(Z.fixed_iv_length),z.server_write_IV=K.getBytes(Z.fixed_iv_length);return z};A0.createConnectionState=function(J){var Z=J.entity===A0.ConnectionEnd.client,Q=function(){var V={sequenceNumber:[0,0],macKey:null,macLength:0,macFunction:null,cipherState:null,cipherFunction:function(K){return!0},compressionState:null,compressFunction:function(K){return!0},updateSequenceNumber:function(){if(V.sequenceNumber[1]===4294967295)V.sequenceNumber[1]=0,++V.sequenceNumber[0];else++V.sequenceNumber[1]}};return V},Y={read:Q(),write:Q()};if(Y.read.update=function(V,K){if(!Y.read.cipherFunction(K,Y.read))V.error(V,{message:"Could not decrypt record or bad MAC.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.bad_record_mac}});else if(!Y.read.compressFunction(V,K,Y.read))V.error(V,{message:"Could not decompress record.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.decompression_failure}});return!V.fail},Y.write.update=function(V,K){if(!Y.write.compressFunction(V,K,Y.write))V.error(V,{message:"Could not compress record.",send:!1,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.internal_error}});else if(!Y.write.cipherFunction(K,Y.write))V.error(V,{message:"Could not encrypt record.",send:!1,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.internal_error}});return!V.fail},J.session){var X=J.session.sp;switch(J.session.cipherSuite.initSecurityParameters(X),X.keys=A0.generateKeys(J,X),Y.read.macKey=Z?X.keys.server_write_MAC_key:X.keys.client_write_MAC_key,Y.write.macKey=Z?X.keys.client_write_MAC_key:X.keys.server_write_MAC_key,J.session.cipherSuite.initConnectionState(Y,J,X),X.compression_algorithm){case A0.CompressionMethod.none:break;case A0.CompressionMethod.deflate:Y.read.compressFunction=L03,Y.write.compressFunction=E03;break;default:throw Error("Unsupported compression algorithm.")}}return Y};A0.createRandom=function(){var J=new Date,Z=+J+J.getTimezoneOffset()*60000,Q=S1.util.createBuffer();return Q.putInt32(Z),Q.putBytes(S1.random.getBytes(28)),Q};A0.createRecord=function(J,Z){if(!Z.data)return null;var Q={type:Z.type,version:{major:J.version.major,minor:J.version.minor},length:Z.data.length(),fragment:Z.data};return Q};A0.createAlert=function(J,Z){var Q=S1.util.createBuffer();return Q.putByte(Z.level),Q.putByte(Z.description),A0.createRecord(J,{type:A0.ContentType.alert,data:Q})};A0.createClientHello=function(J){J.session.clientHelloVersion={major:J.version.major,minor:J.version.minor};var Z=S1.util.createBuffer();for(var Q=0;Q<J.cipherSuites.length;++Q){var Y=J.cipherSuites[Q];Z.putByte(Y.id[0]),Z.putByte(Y.id[1])}var X=Z.length(),V=S1.util.createBuffer();V.putByte(A0.CompressionMethod.none);var K=V.length(),z=S1.util.createBuffer();if(J.virtualHost){var G=S1.util.createBuffer();G.putByte(0),G.putByte(0);var F=S1.util.createBuffer();F.putByte(0),XX(F,2,S1.util.createBuffer(J.virtualHost));var U=S1.util.createBuffer();XX(U,2,F),XX(G,2,U),z.putBuffer(G)}var q=z.length();if(q>0)q+=2;var D=J.session.id,W=D.length+1+2+4+28+2+X+1+K+q,H=S1.util.createBuffer();if(H.putByte(A0.HandshakeType.client_hello),H.putInt24(W),H.putByte(J.version.major),H.putByte(J.version.minor),H.putBytes(J.session.sp.client_random),XX(H,1,S1.util.createBuffer(D)),XX(H,2,Z),XX(H,1,V),q>0)XX(H,2,z);return H};A0.createServerHello=function(J){var Z=J.session.id,Q=Z.length+1+2+4+28+2+1,Y=S1.util.createBuffer();return Y.putByte(A0.HandshakeType.server_hello),Y.putInt24(Q),Y.putByte(J.version.major),Y.putByte(J.version.minor),Y.putBytes(J.session.sp.server_random),XX(Y,1,S1.util.createBuffer(Z)),Y.putByte(J.session.cipherSuite.id[0]),Y.putByte(J.session.cipherSuite.id[1]),Y.putByte(J.session.compressionMethod),Y};A0.createCertificate=function(J){var Z=J.entity===A0.ConnectionEnd.client,Q=null;if(J.getCertificate){var Y;if(Z)Y=J.session.certificateRequest;else Y=J.session.extensions.server_name.serverNameList;Q=J.getCertificate(J,Y)}var X=S1.util.createBuffer();if(Q!==null)try{if(!S1.util.isArray(Q))Q=[Q];var V=null;for(var K=0;K<Q.length;++K){var z=S1.pem.decode(Q[K])[0];if(z.type!=="CERTIFICATE"&&z.type!=="X509 CERTIFICATE"&&z.type!=="TRUSTED CERTIFICATE"){var G=Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');throw G.headerType=z.type,G}if(z.procType&&z.procType.type==="ENCRYPTED")throw Error("Could not convert certificate from PEM; PEM is encrypted.");var F=S1.util.createBuffer(z.body);if(V===null)V=S1.asn1.fromDer(F.bytes(),!1);var U=S1.util.createBuffer();XX(U,3,F),X.putBuffer(U)}if(Q=S1.pki.certificateFromAsn1(V),Z)J.session.clientCertificate=Q;else J.session.serverCertificate=Q}catch(W){return J.error(J,{message:"Could not send certificate list.",cause:W,send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.bad_certificate}})}var q=3+X.length(),D=S1.util.createBuffer();return D.putByte(A0.HandshakeType.certificate),D.putInt24(q),XX(D,3,X),D};A0.createClientKeyExchange=function(J){var Z=S1.util.createBuffer();Z.putByte(J.session.clientHelloVersion.major),Z.putByte(J.session.clientHelloVersion.minor),Z.putBytes(S1.random.getBytes(46));var Q=J.session.sp;Q.pre_master_secret=Z.getBytes();var Y=J.session.serverCertificate.publicKey;Z=Y.encrypt(Q.pre_master_secret);var X=Z.length+2,V=S1.util.createBuffer();return V.putByte(A0.HandshakeType.client_key_exchange),V.putInt24(X),V.putInt16(Z.length),V.putBytes(Z),V};A0.createServerKeyExchange=function(J){var Z=0,Q=S1.util.createBuffer();if(Z>0)Q.putByte(A0.HandshakeType.server_key_exchange),Q.putInt24(Z);return Q};A0.getClientSignature=function(J,Z){var Q=S1.util.createBuffer();Q.putBuffer(J.session.md5.digest()),Q.putBuffer(J.session.sha1.digest()),Q=Q.getBytes(),J.getSignature=J.getSignature||function(Y,X,V){var K=null;if(Y.getPrivateKey)try{K=Y.getPrivateKey(Y,Y.session.clientCertificate),K=S1.pki.privateKeyFromPem(K)}catch(z){Y.error(Y,{message:"Could not get private key.",cause:z,send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.internal_error}})}if(K===null)Y.error(Y,{message:"No private key set.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.internal_error}});else X=K.sign(X,null);V(Y,X)},J.getSignature(J,Q,Z)};A0.createCertificateVerify=function(J,Z){var Q=Z.length+2,Y=S1.util.createBuffer();return Y.putByte(A0.HandshakeType.certificate_verify),Y.putInt24(Q),Y.putInt16(Z.length),Y.putBytes(Z),Y};A0.createCertificateRequest=function(J){var Z=S1.util.createBuffer();Z.putByte(1);var Q=S1.util.createBuffer();for(var Y in J.caStore.certs){var X=J.caStore.certs[Y],V=S1.pki.distinguishedNameToAsn1(X.subject),K=S1.asn1.toDer(V);Q.putInt16(K.length()),Q.putBuffer(K)}var z=1+Z.length()+2+Q.length(),G=S1.util.createBuffer();return G.putByte(A0.HandshakeType.certificate_request),G.putInt24(z),XX(G,1,Z),XX(G,2,Q),G};A0.createServerHelloDone=function(J){var Z=S1.util.createBuffer();return Z.putByte(A0.HandshakeType.server_hello_done),Z.putInt24(0),Z};A0.createChangeCipherSpec=function(){var J=S1.util.createBuffer();return J.putByte(1),J};A0.createFinished=function(J){var Z=S1.util.createBuffer();Z.putBuffer(J.session.md5.digest()),Z.putBuffer(J.session.sha1.digest());var Q=J.entity===A0.ConnectionEnd.client,Y=J.session.sp,X=12,V=tJ0,K=Q?"client finished":"server finished";Z=V(Y.master_secret,K,Z.getBytes(),X);var z=S1.util.createBuffer();return z.putByte(A0.HandshakeType.finished),z.putInt24(Z.length()),z.putBuffer(Z),z};A0.createHeartbeat=function(J,Z,Q){if(typeof Q>"u")Q=Z.length;var Y=S1.util.createBuffer();Y.putByte(J),Y.putInt16(Q),Y.putBytes(Z);var X=Y.length(),V=Math.max(16,X-Q-3);return Y.putBytes(S1.random.getBytes(V)),Y};A0.queue=function(J,Z){if(!Z)return;if(Z.fragment.length()===0){if(Z.type===A0.ContentType.handshake||Z.type===A0.ContentType.alert||Z.type===A0.ContentType.change_cipher_spec)return}if(Z.type===A0.ContentType.handshake){var Q=Z.fragment.bytes();J.session.md5.update(Q),J.session.sha1.update(Q),Q=null}var Y;if(Z.fragment.length()<=A0.MaxFragment)Y=[Z];else{Y=[];var X=Z.fragment.bytes();while(X.length>A0.MaxFragment)Y.push(A0.createRecord(J,{type:Z.type,data:S1.util.createBuffer(X.slice(0,A0.MaxFragment))})),X=X.slice(A0.MaxFragment);if(X.length>0)Y.push(A0.createRecord(J,{type:Z.type,data:S1.util.createBuffer(X)}))}for(var V=0;V<Y.length&&!J.fail;++V){var K=Y[V],z=J.state.current.write;if(z.update(J,K))J.records.push(K)}};A0.flush=function(J){for(var Z=0;Z<J.records.length;++Z){var Q=J.records[Z];J.tlsData.putByte(Q.type),J.tlsData.putByte(Q.version.major),J.tlsData.putByte(Q.version.minor),J.tlsData.putInt16(Q.fragment.length()),J.tlsData.putBuffer(J.records[Z].fragment)}return J.records=[],J.tlsDataReady(J)};var mc0=function(J){switch(J){case!0:return!0;case S1.pki.certificateError.bad_certificate:return A0.Alert.Description.bad_certificate;case S1.pki.certificateError.unsupported_certificate:return A0.Alert.Description.unsupported_certificate;case S1.pki.certificateError.certificate_revoked:return A0.Alert.Description.certificate_revoked;case S1.pki.certificateError.certificate_expired:return A0.Alert.Description.certificate_expired;case S1.pki.certificateError.certificate_unknown:return A0.Alert.Description.certificate_unknown;case S1.pki.certificateError.unknown_ca:return A0.Alert.Description.unknown_ca;default:return A0.Alert.Description.bad_certificate}},b03=function(J){switch(J){case!0:return!0;case A0.Alert.Description.bad_certificate:return S1.pki.certificateError.bad_certificate;case A0.Alert.Description.unsupported_certificate:return S1.pki.certificateError.unsupported_certificate;case A0.Alert.Description.certificate_revoked:return S1.pki.certificateError.certificate_revoked;case A0.Alert.Description.certificate_expired:return S1.pki.certificateError.certificate_expired;case A0.Alert.Description.certificate_unknown:return S1.pki.certificateError.certificate_unknown;case A0.Alert.Description.unknown_ca:return S1.pki.certificateError.unknown_ca;default:return S1.pki.certificateError.bad_certificate}};A0.verifyCertificateChain=function(J,Z){try{var Q={};for(var Y in J.verifyOptions)Q[Y]=J.verifyOptions[Y];Q.verify=function(V,K,z){var G=mc0(V),F=J.verify(J,V,K,z);if(F!==!0){if(typeof F==="object"&&!S1.util.isArray(F)){var U=Error("The application rejected the certificate.");if(U.send=!0,U.alert={level:A0.Alert.Level.fatal,description:A0.Alert.Description.bad_certificate},F.message)U.message=F.message;if(F.alert)U.alert.description=F.alert;throw U}if(F!==V)F=b03(F)}return F},S1.pki.verifyCertificateChain(J.caStore,Z,Q)}catch(V){var X=V;if(typeof X!=="object"||S1.util.isArray(X))X={send:!0,alert:{level:A0.Alert.Level.fatal,description:mc0(V)}};if(!("send"in X))X.send=!0;if(!("alert"in X))X.alert={level:A0.Alert.Level.fatal,description:mc0(X.error)};J.error(J,X)}return!J.fail};A0.createSessionCache=function(J,Z){var Q=null;if(J&&J.getSession&&J.setSession&&J.order)Q=J;else{Q={},Q.cache=J||{},Q.capacity=Math.max(Z||100,1),Q.order=[];for(var Y in J)if(Q.order.length<=Z)Q.order.push(Y);else delete J[Y];Q.getSession=function(X){var V=null,K=null;if(X)K=S1.util.bytesToHex(X);else if(Q.order.length>0)K=Q.order[0];if(K!==null&&K in Q.cache){V=Q.cache[K],delete Q.cache[K];for(var z in Q.order)if(Q.order[z]===K){Q.order.splice(z,1);break}}return V},Q.setSession=function(X,V){if(Q.order.length===Q.capacity){var K=Q.order.shift();delete Q.cache[K]}var K=S1.util.bytesToHex(X);Q.order.push(K),Q.cache[K]=V}}return Q};A0.createConnection=function(J){var Z=null;if(J.caStore)if(S1.util.isArray(J.caStore))Z=S1.pki.createCaStore(J.caStore);else Z=J.caStore;else Z=S1.pki.createCaStore();var Q=J.cipherSuites||null;if(Q===null){Q=[];for(var Y in A0.CipherSuites)Q.push(A0.CipherSuites[Y])}var X=J.server?A0.ConnectionEnd.server:A0.ConnectionEnd.client,V=J.sessionCache?A0.createSessionCache(J.sessionCache):null,K={version:{major:A0.Version.major,minor:A0.Version.minor},entity:X,sessionId:J.sessionId,caStore:Z,sessionCache:V,cipherSuites:Q,connected:J.connected,virtualHost:J.virtualHost||null,verifyClient:J.verifyClient||!1,verify:J.verify||function(U,q,D,W){return q},verifyOptions:J.verifyOptions||{},getCertificate:J.getCertificate||null,getPrivateKey:J.getPrivateKey||null,getSignature:J.getSignature||null,input:S1.util.createBuffer(),tlsData:S1.util.createBuffer(),data:S1.util.createBuffer(),tlsDataReady:J.tlsDataReady,dataReady:J.dataReady,heartbeatReceived:J.heartbeatReceived,closed:J.closed,error:function(U,q){if(q.origin=q.origin||(U.entity===A0.ConnectionEnd.client?"client":"server"),q.send)A0.queue(U,A0.createAlert(U,q.alert)),A0.flush(U);var D=q.fatal!==!1;if(D)U.fail=!0;if(J.error(U,q),D)U.close(!1)},deflate:J.deflate||null,inflate:J.inflate||null};K.reset=function(U){K.version={major:A0.Version.major,minor:A0.Version.minor},K.record=null,K.session=null,K.peerCertificate=null,K.state={pending:null,current:null},K.expect=K.entity===A0.ConnectionEnd.client?M03:T03,K.fragmented=null,K.records=[],K.open=!1,K.handshakes=0,K.handshaking=!1,K.isConnected=!1,K.fail=!(U||typeof U>"u"),K.input.clear(),K.tlsData.clear(),K.data.clear(),K.state.current=A0.createConnectionState(K)},K.reset();var z=function(U,q){var D=q.type-A0.ContentType.change_cipher_spec,W=dc0[U.entity][U.expect];if(D in W)W[D](U,q);else A0.handleUnexpected(U,q)},G=function(U){var q=0,D=U.input,W=D.length();if(W<5)q=5-W;else{U.record={type:D.getByte(),version:{major:D.getByte(),minor:D.getByte()},length:D.getInt16(),fragment:S1.util.createBuffer(),ready:!1};var H=U.record.version.major===U.version.major;if(H&&U.session&&U.session.version)H=U.record.version.minor===U.version.minor;if(!H)U.error(U,{message:"Incompatible TLS version.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.protocol_version}})}return q},F=function(U){var q=0,D=U.input,W=D.length();if(W<U.record.length)q=U.record.length-W;else{U.record.fragment.putBytes(D.getBytes(U.record.length)),D.compact();var H=U.state.current.read;if(H.update(U,U.record)){if(U.fragmented!==null)if(U.fragmented.type===U.record.type)U.fragmented.fragment.putBuffer(U.record.fragment),U.record=U.fragmented;else U.error(U,{message:"Invalid fragmented record.",send:!0,alert:{level:A0.Alert.Level.fatal,description:A0.Alert.Description.unexpected_message}});U.record.ready=!0}}return q};return K.handshake=function(U){if(K.entity!==A0.ConnectionEnd.client)K.error(K,{message:"Cannot initiate handshake as a server.",fatal:!1});else if(K.handshaking)K.error(K,{message:"Handshake already in progress.",fatal:!1});else{if(K.fail&&!K.open&&K.handshakes===0)K.fail=!1;K.handshaking=!0,U=U||"";var q=null;if(U.length>0){if(K.sessionCache)q=K.sessionCache.getSession(U);if(q===null)U=""}if(U.length===0&&K.sessionCache){if(q=K.sessionCache.getSession(),q!==null)U=q.id}if(K.session={id:U,version:null,cipherSuite:null,compressionMethod:null,serverCertificate:null,certificateRequest:null,clientCertificate:null,sp:{},md5:S1.md.md5.create(),sha1:S1.md.sha1.create()},q)K.version=q.version,K.session.sp=q.sp;K.session.sp.client_random=A0.createRandom().getBytes(),K.open=!0,A0.queue(K,A0.createRecord(K,{type:A0.ContentType.handshake,data:A0.createClientHello(K)})),A0.flush(K)}},K.process=function(U){var q=0;if(U)K.input.putBytes(U);if(!K.fail){if(K.record!==null&&K.record.ready&&K.record.fragment.isEmpty())K.record=null;if(K.record===null)q=G(K);if(!K.fail&&K.record!==null&&!K.record.ready)q=F(K);if(!K.fail&&K.record!==null&&K.record.ready)z(K,K.record)}return q},K.prepare=function(U){return A0.queue(K,A0.createRecord(K,{type:A0.ContentType.application_data,data:S1.util.createBuffer(U)})),A0.flush(K)},K.prepareHeartbeatRequest=function(U,q){if(U instanceof S1.util.ByteBuffer)U=U.bytes();if(typeof q>"u")q=U.length;return K.expectedHeartbeatPayload=U,A0.queue(K,A0.createRecord(K,{type:A0.ContentType.heartbeat,data:A0.createHeartbeat(A0.HeartbeatMessageType.heartbeat_request,U,q)})),A0.flush(K)},K.close=function(U){if(!K.fail&&K.sessionCache&&K.session){var q={id:K.session.id,version:K.session.version,sp:K.session.sp};q.sp.keys=null,K.sessionCache.setSession(q.id,q)}if(K.open){if(K.open=!1,K.input.clear(),K.isConnected||K.handshaking)K.isConnected=K.handshaking=!1,A0.queue(K,A0.createAlert(K,{level:A0.Alert.Level.warning,description:A0.Alert.Description.close_notify})),A0.flush(K);K.closed(K)}K.reset(U)},K};CI4.exports=S1.tls=S1.tls||{};for(Ad in A0)if(typeof A0[Ad]!=="function")S1.tls[Ad]=A0[Ad];var Ad;S1.tls.prf_tls1=tJ0;S1.tls.hmac_sha1=O03;S1.tls.createSessionCache=A0.createSessionCache;S1.tls.createConnection=A0.createConnection});var SI4=u((UE9,_I4)=>{var WB=J5();KB();cc0();var VX=_I4.exports=WB.tls;VX.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA={id:[0,47],name:"TLS_RSA_WITH_AES_128_CBC_SHA",initSecurityParameters:function(J){J.bulk_cipher_algorithm=VX.BulkCipherAlgorithm.aes,J.cipher_type=VX.CipherType.block,J.enc_key_length=16,J.block_length=16,J.fixed_iv_length=16,J.record_iv_length=16,J.mac_algorithm=VX.MACAlgorithm.hmac_sha1,J.mac_length=20,J.mac_key_length=20},initConnectionState:TI4};VX.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA={id:[0,53],name:"TLS_RSA_WITH_AES_256_CBC_SHA",initSecurityParameters:function(J){J.bulk_cipher_algorithm=VX.BulkCipherAlgorithm.aes,J.cipher_type=VX.CipherType.block,J.enc_key_length=32,J.block_length=16,J.fixed_iv_length=16,J.record_iv_length=16,J.mac_algorithm=VX.MACAlgorithm.hmac_sha1,J.mac_length=20,J.mac_key_length=20},initConnectionState:TI4};function TI4(J,Z,Q){var Y=Z.entity===WB.tls.ConnectionEnd.client;J.read.cipherState={init:!1,cipher:WB.cipher.createDecipher("AES-CBC",Y?Q.keys.server_write_key:Q.keys.client_write_key),iv:Y?Q.keys.server_write_IV:Q.keys.client_write_IV},J.write.cipherState={init:!1,cipher:WB.cipher.createCipher("AES-CBC",Y?Q.keys.client_write_key:Q.keys.server_write_key),iv:Y?Q.keys.client_write_IV:Q.keys.server_write_IV},J.read.cipherFunction=p03,J.write.cipherFunction=h03,J.read.macLength=J.write.macLength=Q.mac_length,J.read.macFunction=J.write.macFunction=VX.hmac_sha1}function h03(J,Z){var Q=!1,Y=Z.macFunction(Z.macKey,Z.sequenceNumber,J);J.fragment.putBytes(Y),Z.updateSequenceNumber();var X;if(J.version.minor===VX.Versions.TLS_1_0.minor)X=Z.cipherState.init?null:Z.cipherState.iv;else X=WB.random.getBytesSync(16);Z.cipherState.init=!0;var V=Z.cipherState.cipher;if(V.start({iv:X}),J.version.minor>=VX.Versions.TLS_1_1.minor)V.output.putBytes(X);if(V.update(J.fragment),V.finish(m03))J.fragment=V.output,J.length=J.fragment.length(),Q=!0;return Q}function m03(J,Z,Q){if(!Q){var Y=J-Z.length()%J;Z.fillWithByte(Y-1,Y)}return!0}function g03(J,Z,Q){var Y=!0;if(Q){var X=Z.length(),V=Z.last();for(var K=X-1-V;K<X-1;++K)Y=Y&&Z.at(K)==V;if(Y)Z.truncate(V+1)}return Y}function p03(J,Z){var Q=!1,Y;if(J.version.minor===VX.Versions.TLS_1_0.minor)Y=Z.cipherState.init?null:Z.cipherState.iv;else Y=J.fragment.getBytes(16);Z.cipherState.init=!0;var X=Z.cipherState.cipher;X.start({iv:Y}),X.update(J.fragment),Q=X.finish(g03);var V=Z.macLength,K=WB.random.getBytesSync(V),z=X.output.length();if(z>=V)J.fragment=X.output.getBytes(z-V),K=X.output.getBytes(V);else J.fragment=X.output.getBytes();J.fragment=WB.util.createBuffer(J.fragment),J.length=J.fragment.length();var G=Z.macFunction(Z.macKey,Z.sequenceNumber,J);return Z.updateSequenceNumber(),Q=d03(Z.macKey,K,G)&&Q,Q}function d03(J,Z,Q){var Y=WB.hmac.create();return Y.start("SHA1",J),Y.update(Z),Z=Y.digest().getBytes(),Y.start(null,null),Y.update(Q),Q=Y.digest().getBytes(),Z===Q}});var nc0=u((qE9,uI4)=>{var O8=J5();NG();c5();var Id=uI4.exports=O8.sha512=O8.sha512||{};O8.md.sha512=O8.md.algorithms.sha512=Id;var kI4=O8.sha384=O8.sha512.sha384=O8.sha512.sha384||{};kI4.create=function(){return Id.create("SHA-384")};O8.md.sha384=O8.md.algorithms.sha384=kI4;O8.sha512.sha256=O8.sha512.sha256||{create:function(){return Id.create("SHA-512/256")}};O8.md["sha512/256"]=O8.md.algorithms["sha512/256"]=O8.sha512.sha256;O8.sha512.sha224=O8.sha512.sha224||{create:function(){return Id.create("SHA-512/224")}};O8.md["sha512/224"]=O8.md.algorithms["sha512/224"]=O8.sha512.sha224;Id.create=function(J){if(!yI4)c03();if(typeof J>"u")J="SHA-512";if(!(J in sL))throw Error("Invalid SHA-512 algorithm: "+J);var Z=sL[J],Q=null,Y=O8.util.createBuffer(),X=Array(80);for(var V=0;V<80;++V)X[V]=[,,];var K=64;switch(J){case"SHA-384":K=48;break;case"SHA-512/256":K=32;break;case"SHA-512/224":K=28;break}var z={algorithm:J.replace("-","").toLowerCase(),blockLength:128,digestLength:K,messageLength:0,fullMessageLength:null,messageLengthSize:16};return z.start=function(){z.messageLength=0,z.fullMessageLength=z.messageLength128=[];var G=z.messageLengthSize/4;for(var F=0;F<G;++F)z.fullMessageLength.push(0);Y=O8.util.createBuffer(),Q=Array(Z.length);for(var F=0;F<Z.length;++F)Q[F]=Z[F].slice(0);return z},z.start(),z.update=function(G,F){if(F==="utf8")G=O8.util.encodeUtf8(G);var U=G.length;z.messageLength+=U,U=[U/4294967296>>>0,U>>>0];for(var q=z.fullMessageLength.length-1;q>=0;--q)z.fullMessageLength[q]+=U[1],U[1]=U[0]+(z.fullMessageLength[q]/4294967296>>>0),z.fullMessageLength[q]=z.fullMessageLength[q]>>>0,U[0]=U[1]/4294967296>>>0;if(Y.putBytes(G),vI4(Q,X,Y),Y.read>2048||Y.length()===0)Y.compact();return z},z.digest=function(){var G=O8.util.createBuffer();G.putBytes(Y.bytes());var F=z.fullMessageLength[z.fullMessageLength.length-1]+z.messageLengthSize,U=F&z.blockLength-1;G.putBytes(lc0.substr(0,z.blockLength-U));var q,D,W=z.fullMessageLength[0]*8;for(var H=0;H<z.fullMessageLength.length-1;++H)q=z.fullMessageLength[H+1]*8,D=q/4294967296>>>0,W+=D,G.putInt32(W>>>0),W=q>>>0;G.putInt32(W);var B=Array(Q.length);for(var H=0;H<Q.length;++H)B[H]=Q[H].slice(0);vI4(B,X,G);var w=O8.util.createBuffer(),N;if(J==="SHA-512")N=B.length;else if(J==="SHA-384")N=B.length-2;else N=B.length-4;for(var H=0;H<N;++H)if(w.putInt32(B[H][0]),H!==N-1||J!=="SHA-512/224")w.putInt32(B[H][1]);return w},z};var lc0=null,yI4=!1,ic0=null,sL=null;function c03(){lc0=String.fromCharCode(128),lc0+=O8.util.fillString(String.fromCharCode(0),128),ic0=[[1116352408,3609767458],[1899447441,602891725],[3049323471,3964484399],[3921009573,2173295548],[961987163,4081628472],[1508970993,3053834265],[2453635748,2937671579],[2870763221,3664609560],[3624381080,2734883394],[310598401,1164996542],[607225278,1323610764],[1426881987,3590304994],[1925078388,4068182383],[2162078206,991336113],[2614888103,633803317],[3248222580,3479774868],[3835390401,2666613458],[4022224774,944711139],[264347078,2341262773],[604807628,2007800933],[770255983,1495990901],[1249150122,1856431235],[1555081692,3175218132],[1996064986,2198950837],[2554220882,3999719339],[2821834349,766784016],[2952996808,2566594879],[3210313671,3203337956],[3336571891,1034457026],[3584528711,2466948901],[113926993,3758326383],[338241895,168717936],[666307205,1188179964],[773529912,1546045734],[1294757372,1522805485],[1396182291,2643833823],[1695183700,2343527390],[1986661051,1014477480],[2177026350,1206759142],[2456956037,344077627],[2730485921,1290863460],[2820302411,3158454273],[3259730800,3505952657],[3345764771,106217008],[3516065817,3606008344],[3600352804,1432725776],[4094571909,1467031594],[275423344,851169720],[430227734,3100823752],[506948616,1363258195],[659060556,3750685593],[883997877,3785050280],[958139571,3318307427],[1322822218,3812723403],[1537002063,2003034995],[1747873779,3602036899],[1955562222,1575990012],[2024104815,1125592928],[2227730452,2716904306],[2361852424,442776044],[2428436474,593698344],[2756734187,3733110249],[3204031479,2999351573],[3329325298,3815920427],[3391569614,3928383900],[3515267271,566280711],[3940187606,3454069534],[4118630271,4000239992],[116418474,1914138554],[174292421,2731055270],[289380356,3203993006],[460393269,320620315],[685471733,587496836],[852142971,1086792851],[1017036298,365543100],[1126000580,2618297676],[1288033470,3409855158],[1501505948,4234509866],[1607167915,987167468],[1816402316,1246189591]],sL={},sL["SHA-512"]=[[1779033703,4089235720],[3144134277,2227873595],[1013904242,4271175723],[2773480762,1595750129],[1359893119,2917565137],[2600822924,725511199],[528734635,4215389547],[1541459225,327033209]],sL["SHA-384"]=[[3418070365,3238371032],[1654270250,914150663],[2438529370,812702999],[355462360,4144912697],[1731405415,4290775857],[2394180231,1750603025],[3675008525,1694076839],[1203062813,3204075428]],sL["SHA-512/256"]=[[573645204,4230739756],[2673172387,3360449730],[596883563,1867755857],[2520282905,1497426621],[2519219938,2827943907],[3193839141,1401305490],[721525244,746961066],[246885852,2177182882]],sL["SHA-512/224"]=[[2352822216,424955298],[1944164710,2312950998],[502970286,855612546],[1738396948,1479516111],[258812777,2077511080],[2011393907,79989058],[1067287976,1780299464],[286451373,2446758561]],yI4=!0}function vI4(J,Z,Q){var Y,X,V,K,z,G,F,U,q,D,W,H,B,w,N,O,E,L,M,A,I,P,_,S,y,m,b,k,f,p,l,x,r,c,s,w0=Q.length();while(w0>=128){for(f=0;f<16;++f)Z[f][0]=Q.getInt32()>>>0,Z[f][1]=Q.getInt32()>>>0;for(;f<80;++f)x=Z[f-2],p=x[0],l=x[1],Y=((p>>>19|l<<13)^(l>>>29|p<<3)^p>>>6)>>>0,X=((p<<13|l>>>19)^(l<<3|p>>>29)^(p<<26|l>>>6))>>>0,c=Z[f-15],p=c[0],l=c[1],V=((p>>>1|l<<31)^(p>>>8|l<<24)^p>>>7)>>>0,K=((p<<31|l>>>1)^(p<<24|l>>>8)^(p<<25|l>>>7))>>>0,r=Z[f-7],s=Z[f-16],l=X+r[1]+K+s[1],Z[f][0]=Y+r[0]+V+s[0]+(l/4294967296>>>0)>>>0,Z[f][1]=l>>>0;B=J[0][0],w=J[0][1],N=J[1][0],O=J[1][1],E=J[2][0],L=J[2][1],M=J[3][0],A=J[3][1],I=J[4][0],P=J[4][1],_=J[5][0],S=J[5][1],y=J[6][0],m=J[6][1],b=J[7][0],k=J[7][1];for(f=0;f<80;++f)F=((I>>>14|P<<18)^(I>>>18|P<<14)^(P>>>9|I<<23))>>>0,U=((I<<18|P>>>14)^(I<<14|P>>>18)^(P<<23|I>>>9))>>>0,q=(y^I&(_^y))>>>0,D=(m^P&(S^m))>>>0,z=((B>>>28|w<<4)^(w>>>2|B<<30)^(w>>>7|B<<25))>>>0,G=((B<<4|w>>>28)^(w<<30|B>>>2)^(w<<25|B>>>7))>>>0,W=(B&N|E&(B^N))>>>0,H=(w&O|L&(w^O))>>>0,l=k+U+D+ic0[f][1]+Z[f][1],Y=b+F+q+ic0[f][0]+Z[f][0]+(l/4294967296>>>0)>>>0,X=l>>>0,l=G+H,V=z+W+(l/4294967296>>>0)>>>0,K=l>>>0,b=y,k=m,y=_,m=S,_=I,S=P,l=A+X,I=M+Y+(l/4294967296>>>0)>>>0,P=l>>>0,M=E,A=L,E=N,L=O,N=B,O=w,l=X+K,B=Y+V+(l/4294967296>>>0)>>>0,w=l>>>0;l=J[0][1]+w,J[0][0]=J[0][0]+B+(l/4294967296>>>0)>>>0,J[0][1]=l>>>0,l=J[1][1]+O,J[1][0]=J[1][0]+N+(l/4294967296>>>0)>>>0,J[1][1]=l>>>0,l=J[2][1]+L,J[2][0]=J[2][0]+E+(l/4294967296>>>0)>>>0,J[2][1]=l>>>0,l=J[3][1]+A,J[3][0]=J[3][0]+M+(l/4294967296>>>0)>>>0,J[3][1]=l>>>0,l=J[4][1]+P,J[4][0]=J[4][0]+I+(l/4294967296>>>0)>>>0,J[4][1]=l>>>0,l=J[5][1]+S,J[5][0]=J[5][0]+_+(l/4294967296>>>0)>>>0,J[5][1]=l>>>0,l=J[6][1]+m,J[6][0]=J[6][0]+y+(l/4294967296>>>0)>>>0,J[6][1]=l>>>0,l=J[7][1]+k,J[7][0]=J[7][0]+b+(l/4294967296>>>0)>>>0,J[7][1]=l>>>0,w0-=128}}});var xI4=u((i03)=>{var l03=J5();oV();var s7=l03.asn1;i03.privateKeyValidator={name:"PrivateKeyInfo",tagClass:s7.Class.UNIVERSAL,type:s7.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:s7.Class.UNIVERSAL,type:s7.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:s7.Class.UNIVERSAL,type:s7.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:s7.Class.UNIVERSAL,type:s7.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:s7.Class.UNIVERSAL,type:s7.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]};i03.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:s7.Class.UNIVERSAL,type:s7.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:s7.Class.UNIVERSAL,type:s7.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:s7.Class.UNIVERSAL,type:s7.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{tagClass:s7.Class.UNIVERSAL,type:s7.Type.BITSTRING,constructed:!1,composed:!0,captureBitStringValue:"ed25519PublicKey"}]}});var aI4=u((WE9,nI4)=>{var y2=J5();Od();JX();nc0();c5();var gI4=xI4(),o03=gI4.publicKeyValidator,r03=gI4.privateKeyValidator;if(typeof rc0>"u")rc0=y2.jsbn.BigInteger;var rc0,sc0=y2.util.ByteBuffer,wZ=typeof Buffer>"u"?Uint8Array:Buffer;y2.pki=y2.pki||{};nI4.exports=y2.pki.ed25519=y2.ed25519=y2.ed25519||{};var w5=y2.ed25519;w5.constants={};w5.constants.PUBLIC_KEY_BYTE_LENGTH=32;w5.constants.PRIVATE_KEY_BYTE_LENGTH=64;w5.constants.SEED_BYTE_LENGTH=32;w5.constants.SIGN_BYTE_LENGTH=64;w5.constants.HASH_BYTE_LENGTH=64;w5.generateKeyPair=function(J){J=J||{};var Z=J.seed;if(Z===void 0)Z=y2.random.getBytesSync(w5.constants.SEED_BYTE_LENGTH);else if(typeof Z==="string"){if(Z.length!==w5.constants.SEED_BYTE_LENGTH)throw TypeError('"seed" must be '+w5.constants.SEED_BYTE_LENGTH+" bytes in length.")}else if(!(Z instanceof Uint8Array))throw TypeError('"seed" must be a node.js Buffer, Uint8Array, or a binary string.');Z=Jq({message:Z,encoding:"binary"});var Q=new wZ(w5.constants.PUBLIC_KEY_BYTE_LENGTH),Y=new wZ(w5.constants.PRIVATE_KEY_BYTE_LENGTH);for(var X=0;X<32;++X)Y[X]=Z[X];return $13(Q,Y),{publicKey:Q,privateKey:Y}};w5.privateKeyFromAsn1=function(J){var Z={},Q=[],Y=y2.asn1.validate(J,r03,Z,Q);if(!Y){var X=Error("Invalid Key.");throw X.errors=Q,X}var V=y2.asn1.derToOid(Z.privateKeyOid),K=y2.oids.EdDSA25519;if(V!==K)throw Error('Invalid OID "'+V+'"; OID must be "'+K+'".');var z=Z.privateKey,G=Jq({message:y2.asn1.fromDer(z).value,encoding:"binary"});return{privateKeyBytes:G}};w5.publicKeyFromAsn1=function(J){var Z={},Q=[],Y=y2.asn1.validate(J,o03,Z,Q);if(!Y){var X=Error("Invalid Key.");throw X.errors=Q,X}var V=y2.asn1.derToOid(Z.publicKeyOid),K=y2.oids.EdDSA25519;if(V!==K)throw Error('Invalid OID "'+V+'"; OID must be "'+K+'".');var z=Z.ed25519PublicKey;if(z.length!==w5.constants.PUBLIC_KEY_BYTE_LENGTH)throw Error("Key length is invalid.");return Jq({message:z,encoding:"binary"})};w5.publicKeyFromPrivateKey=function(J){J=J||{};var Z=Jq({message:J.privateKey,encoding:"binary"});if(Z.length!==w5.constants.PRIVATE_KEY_BYTE_LENGTH)throw TypeError('"options.privateKey" must have a byte length of '+w5.constants.PRIVATE_KEY_BYTE_LENGTH);var Q=new wZ(w5.constants.PUBLIC_KEY_BYTE_LENGTH);for(var Y=0;Y<Q.length;++Y)Q[Y]=Z[32+Y];return Q};w5.sign=function(J){J=J||{};var Z=Jq(J),Q=Jq({message:J.privateKey,encoding:"binary"});if(Q.length===w5.constants.SEED_BYTE_LENGTH){var Y=w5.generateKeyPair({seed:Q});Q=Y.privateKey}else if(Q.length!==w5.constants.PRIVATE_KEY_BYTE_LENGTH)throw TypeError('"options.privateKey" must have a byte length of '+w5.constants.SEED_BYTE_LENGTH+" or "+w5.constants.PRIVATE_KEY_BYTE_LENGTH);var X=new wZ(w5.constants.SIGN_BYTE_LENGTH+Z.length);J13(X,Z,Z.length,Q);var V=new wZ(w5.constants.SIGN_BYTE_LENGTH);for(var K=0;K<V.length;++K)V[K]=X[K];return V};w5.verify=function(J){J=J||{};var Z=Jq(J);if(J.signature===void 0)throw TypeError('"options.signature" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a binary string.');var Q=Jq({message:J.signature,encoding:"binary"});if(Q.length!==w5.constants.SIGN_BYTE_LENGTH)throw TypeError('"options.signature" must have a byte length of '+w5.constants.SIGN_BYTE_LENGTH);var Y=Jq({message:J.publicKey,encoding:"binary"});if(Y.length!==w5.constants.PUBLIC_KEY_BYTE_LENGTH)throw TypeError('"options.publicKey" must have a byte length of '+w5.constants.PUBLIC_KEY_BYTE_LENGTH);var X=new wZ(w5.constants.SIGN_BYTE_LENGTH+Z.length),V=new wZ(w5.constants.SIGN_BYTE_LENGTH+Z.length),K;for(K=0;K<w5.constants.SIGN_BYTE_LENGTH;++K)X[K]=Q[K];for(K=0;K<Z.length;++K)X[K+w5.constants.SIGN_BYTE_LENGTH]=Z[K];return Z13(V,X,X.length,Y)>=0};function Jq(J){var Z=J.message;if(Z instanceof Uint8Array||Z instanceof wZ)return Z;var Q=J.encoding;if(Z===void 0)if(J.md)Z=J.md.digest().getBytes(),Q="binary";else throw TypeError('"options.message" or "options.md" not specified.');if(typeof Z==="string"&&!Q)throw TypeError('"options.encoding" must be "binary" or "utf8".');if(typeof Z==="string"){if(typeof Buffer<"u")return Buffer.from(Z,Q);Z=new sc0(Z,Q)}else if(!(Z instanceof sc0))throw TypeError('"options.message" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a string with "options.encoding" specifying its encoding.');var Y=new wZ(Z.length());for(var X=0;X<Y.length;++X)Y[X]=Z.at(X);return Y}var tc0=q6(),eJ0=q6([1]),s03=q6([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),t03=q6([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),fI4=q6([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),bI4=q6([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),ac0=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]),e03=q6([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function jd(J,Z){var Q=y2.md.sha512.create(),Y=new sc0(J);Q.update(Y.getBytes(Z),"binary");var X=Q.digest().getBytes();if(typeof Buffer<"u")return Buffer.from(X,"binary");var V=new wZ(w5.constants.HASH_BYTE_LENGTH);for(var K=0;K<64;++K)V[K]=X.charCodeAt(K);return V}function $13(J,Z){var Q=[q6(),q6(),q6(),q6()],Y,X=jd(Z,32);X[0]&=248,X[31]&=127,X[31]|=64,Zl0(Q,X),Jl0(J,Q);for(Y=0;Y<32;++Y)Z[Y+32]=J[Y];return 0}function J13(J,Z,Q,Y){var X,V,K=new Float64Array(64),z=[q6(),q6(),q6(),q6()],G=jd(Y,32);G[0]&=248,G[31]&=127,G[31]|=64;var F=Q+64;for(X=0;X<Q;++X)J[64+X]=Z[X];for(X=0;X<32;++X)J[32+X]=G[32+X];var U=jd(J.subarray(32),Q+32);ec0(U),Zl0(z,U),Jl0(J,z);for(X=32;X<64;++X)J[X]=Y[X];var q=jd(J,Q+64);ec0(q);for(X=32;X<64;++X)K[X]=0;for(X=0;X<32;++X)K[X]=U[X];for(X=0;X<32;++X)for(V=0;V<32;V++)K[X+V]+=q[X]*G[V];return pI4(J.subarray(32),K),F}function Z13(J,Z,Q,Y){var X,V,K=new wZ(32),z=[q6(),q6(),q6(),q6()],G=[q6(),q6(),q6(),q6()];if(V=-1,Q<64)return-1;if(Q13(G,Y))return-1;for(X=0;X<Q;++X)J[X]=Z[X];for(X=0;X<32;++X)J[X+32]=Y[X];var F=jd(J,Q);if(ec0(F),lI4(z,G,F),Zl0(G,Z.subarray(32)),$l0(z,G),Jl0(K,z),Q-=64,dI4(Z,0,K,0)){for(X=0;X<Q;++X)J[X]=0;return-1}for(X=0;X<Q;++X)J[X]=Z[X+64];return V=Q,V}function pI4(J,Z){var Q,Y,X,V;for(Y=63;Y>=32;--Y){Q=0;for(X=Y-32,V=Y-12;X<V;++X)Z[X]+=Q-16*Z[Y]*ac0[X-(Y-32)],Q=Z[X]+128>>8,Z[X]-=Q*256;Z[X]+=Q,Z[Y]=0}Q=0;for(X=0;X<32;++X)Z[X]+=Q-(Z[31]>>4)*ac0[X],Q=Z[X]>>8,Z[X]&=255;for(X=0;X<32;++X)Z[X]-=Q*ac0[X];for(Y=0;Y<32;++Y)Z[Y+1]+=Z[Y]>>8,J[Y]=Z[Y]&255}function ec0(J){var Z=new Float64Array(64);for(var Q=0;Q<64;++Q)Z[Q]=J[Q],J[Q]=0;pI4(J,Z)}function $l0(J,Z){var Q=q6(),Y=q6(),X=q6(),V=q6(),K=q6(),z=q6(),G=q6(),F=q6(),U=q6();W_(Q,J[1],J[0]),W_(U,Z[1],Z[0]),o3(Q,Q,U),D_(Y,J[0],J[1]),D_(U,Z[0],Z[1]),o3(Y,Y,U),o3(X,J[3],Z[3]),o3(X,X,t03),o3(V,J[2],Z[2]),D_(V,V,V),W_(K,Y,Q),W_(z,V,X),D_(G,V,X),D_(F,Y,Q),o3(J[0],K,z),o3(J[1],F,G),o3(J[2],G,z),o3(J[3],K,F)}function hI4(J,Z,Q){for(var Y=0;Y<4;++Y)iI4(J[Y],Z[Y],Q)}function Jl0(J,Z){var Q=q6(),Y=q6(),X=q6();K13(X,Z[2]),o3(Q,Z[0],X),o3(Y,Z[1],X),$Z0(J,Y),J[31]^=cI4(Q)<<7}function $Z0(J,Z){var Q,Y,X,V=q6(),K=q6();for(Q=0;Q<16;++Q)K[Q]=Z[Q];oc0(K),oc0(K),oc0(K);for(Y=0;Y<2;++Y){V[0]=K[0]-65517;for(Q=1;Q<15;++Q)V[Q]=K[Q]-65535-(V[Q-1]>>16&1),V[Q-1]&=65535;V[15]=K[15]-32767-(V[14]>>16&1),X=V[15]>>16&1,V[14]&=65535,iI4(K,V,1-X)}for(Q=0;Q<16;Q++)J[2*Q]=K[Q]&255,J[2*Q+1]=K[Q]>>8}function Q13(J,Z){var Q=q6(),Y=q6(),X=q6(),V=q6(),K=q6(),z=q6(),G=q6();if(HB(J[2],eJ0),Y13(J[1],Z),tL(X,J[1]),o3(V,X,s03),W_(X,X,J[2]),D_(V,J[2],V),tL(K,V),tL(z,K),o3(G,z,K),o3(Q,G,X),o3(Q,Q,V),X13(Q,Q),o3(Q,Q,X),o3(Q,Q,V),o3(Q,Q,V),o3(J[0],Q,V),tL(Y,J[0]),o3(Y,Y,V),mI4(Y,X))o3(J[0],J[0],e03);if(tL(Y,J[0]),o3(Y,Y,V),mI4(Y,X))return-1;if(cI4(J[0])===Z[31]>>7)W_(J[0],tc0,J[0]);return o3(J[3],J[0],J[1]),0}function Y13(J,Z){var Q;for(Q=0;Q<16;++Q)J[Q]=Z[2*Q]+(Z[2*Q+1]<<8);J[15]&=32767}function X13(J,Z){var Q=q6(),Y;for(Y=0;Y<16;++Y)Q[Y]=Z[Y];for(Y=250;Y>=0;--Y)if(tL(Q,Q),Y!==1)o3(Q,Q,Z);for(Y=0;Y<16;++Y)J[Y]=Q[Y]}function mI4(J,Z){var Q=new wZ(32),Y=new wZ(32);return $Z0(Q,J),$Z0(Y,Z),dI4(Q,0,Y,0)}function dI4(J,Z,Q,Y){return V13(J,Z,Q,Y,32)}function V13(J,Z,Q,Y,X){var V,K=0;for(V=0;V<X;++V)K|=J[Z+V]^Q[Y+V];return(1&K-1>>>8)-1}function cI4(J){var Z=new wZ(32);return $Z0(Z,J),Z[0]&1}function lI4(J,Z,Q){var Y,X;HB(J[0],tc0),HB(J[1],eJ0),HB(J[2],eJ0),HB(J[3],tc0);for(X=255;X>=0;--X)Y=Q[X/8|0]>>(X&7)&1,hI4(J,Z,Y),$l0(Z,J),$l0(J,J),hI4(J,Z,Y)}function Zl0(J,Z){var Q=[q6(),q6(),q6(),q6()];HB(Q[0],fI4),HB(Q[1],bI4),HB(Q[2],eJ0),o3(Q[3],fI4,bI4),lI4(J,Q,Z)}function HB(J,Z){var Q;for(Q=0;Q<16;Q++)J[Q]=Z[Q]|0}function K13(J,Z){var Q=q6(),Y;for(Y=0;Y<16;++Y)Q[Y]=Z[Y];for(Y=253;Y>=0;--Y)if(tL(Q,Q),Y!==2&&Y!==4)o3(Q,Q,Z);for(Y=0;Y<16;++Y)J[Y]=Q[Y]}function oc0(J){var Z,Q,Y=1;for(Z=0;Z<16;++Z)Q=J[Z]+Y+65535,Y=Math.floor(Q/65536),J[Z]=Q-Y*65536;J[0]+=Y-1+37*(Y-1)}function iI4(J,Z,Q){var Y,X=~(Q-1);for(var V=0;V<16;++V)Y=X&(J[V]^Z[V]),J[V]^=Y,Z[V]^=Y}function q6(J){var Z,Q=new Float64Array(16);if(J)for(Z=0;Z<J.length;++Z)Q[Z]=J[Z];return Q}function D_(J,Z,Q){for(var Y=0;Y<16;++Y)J[Y]=Z[Y]+Q[Y]}function W_(J,Z,Q){for(var Y=0;Y<16;++Y)J[Y]=Z[Y]-Q[Y]}function tL(J,Z){o3(J,Z,Z)}function o3(J,Z,Q){var Y,X,V=0,K=0,z=0,G=0,F=0,U=0,q=0,D=0,W=0,H=0,B=0,w=0,N=0,O=0,E=0,L=0,M=0,A=0,I=0,P=0,_=0,S=0,y=0,m=0,b=0,k=0,f=0,p=0,l=0,x=0,r=0,c=Q[0],s=Q[1],w0=Q[2],a=Q[3],F0=Q[4],z0=Q[5],q0=Q[6],Q0=Q[7],H0=Q[8],i=Q[9],n=Q[10],e=Q[11],J0=Q[12],Z0=Q[13],K0=Q[14],t=Q[15];Y=Z[0],V+=Y*c,K+=Y*s,z+=Y*w0,G+=Y*a,F+=Y*F0,U+=Y*z0,q+=Y*q0,D+=Y*Q0,W+=Y*H0,H+=Y*i,B+=Y*n,w+=Y*e,N+=Y*J0,O+=Y*Z0,E+=Y*K0,L+=Y*t,Y=Z[1],K+=Y*c,z+=Y*s,G+=Y*w0,F+=Y*a,U+=Y*F0,q+=Y*z0,D+=Y*q0,W+=Y*Q0,H+=Y*H0,B+=Y*i,w+=Y*n,N+=Y*e,O+=Y*J0,E+=Y*Z0,L+=Y*K0,M+=Y*t,Y=Z[2],z+=Y*c,G+=Y*s,F+=Y*w0,U+=Y*a,q+=Y*F0,D+=Y*z0,W+=Y*q0,H+=Y*Q0,B+=Y*H0,w+=Y*i,N+=Y*n,O+=Y*e,E+=Y*J0,L+=Y*Z0,M+=Y*K0,A+=Y*t,Y=Z[3],G+=Y*c,F+=Y*s,U+=Y*w0,q+=Y*a,D+=Y*F0,W+=Y*z0,H+=Y*q0,B+=Y*Q0,w+=Y*H0,N+=Y*i,O+=Y*n,E+=Y*e,L+=Y*J0,M+=Y*Z0,A+=Y*K0,I+=Y*t,Y=Z[4],F+=Y*c,U+=Y*s,q+=Y*w0,D+=Y*a,W+=Y*F0,H+=Y*z0,B+=Y*q0,w+=Y*Q0,N+=Y*H0,O+=Y*i,E+=Y*n,L+=Y*e,M+=Y*J0,A+=Y*Z0,I+=Y*K0,P+=Y*t,Y=Z[5],U+=Y*c,q+=Y*s,D+=Y*w0,W+=Y*a,H+=Y*F0,B+=Y*z0,w+=Y*q0,N+=Y*Q0,O+=Y*H0,E+=Y*i,L+=Y*n,M+=Y*e,A+=Y*J0,I+=Y*Z0,P+=Y*K0,_+=Y*t,Y=Z[6],q+=Y*c,D+=Y*s,W+=Y*w0,H+=Y*a,B+=Y*F0,w+=Y*z0,N+=Y*q0,O+=Y*Q0,E+=Y*H0,L+=Y*i,M+=Y*n,A+=Y*e,I+=Y*J0,P+=Y*Z0,_+=Y*K0,S+=Y*t,Y=Z[7],D+=Y*c,W+=Y*s,H+=Y*w0,B+=Y*a,w+=Y*F0,N+=Y*z0,O+=Y*q0,E+=Y*Q0,L+=Y*H0,M+=Y*i,A+=Y*n,I+=Y*e,P+=Y*J0,_+=Y*Z0,S+=Y*K0,y+=Y*t,Y=Z[8],W+=Y*c,H+=Y*s,B+=Y*w0,w+=Y*a,N+=Y*F0,O+=Y*z0,E+=Y*q0,L+=Y*Q0,M+=Y*H0,A+=Y*i,I+=Y*n,P+=Y*e,_+=Y*J0,S+=Y*Z0,y+=Y*K0,m+=Y*t,Y=Z[9],H+=Y*c,B+=Y*s,w+=Y*w0,N+=Y*a,O+=Y*F0,E+=Y*z0,L+=Y*q0,M+=Y*Q0,A+=Y*H0,I+=Y*i,P+=Y*n,_+=Y*e,S+=Y*J0,y+=Y*Z0,m+=Y*K0,b+=Y*t,Y=Z[10],B+=Y*c,w+=Y*s,N+=Y*w0,O+=Y*a,E+=Y*F0,L+=Y*z0,M+=Y*q0,A+=Y*Q0,I+=Y*H0,P+=Y*i,_+=Y*n,S+=Y*e,y+=Y*J0,m+=Y*Z0,b+=Y*K0,k+=Y*t,Y=Z[11],w+=Y*c,N+=Y*s,O+=Y*w0,E+=Y*a,L+=Y*F0,M+=Y*z0,A+=Y*q0,I+=Y*Q0,P+=Y*H0,_+=Y*i,S+=Y*n,y+=Y*e,m+=Y*J0,b+=Y*Z0,k+=Y*K0,f+=Y*t,Y=Z[12],N+=Y*c,O+=Y*s,E+=Y*w0,L+=Y*a,M+=Y*F0,A+=Y*z0,I+=Y*q0,P+=Y*Q0,_+=Y*H0,S+=Y*i,y+=Y*n,m+=Y*e,b+=Y*J0,k+=Y*Z0,f+=Y*K0,p+=Y*t,Y=Z[13],O+=Y*c,E+=Y*s,L+=Y*w0,M+=Y*a,A+=Y*F0,I+=Y*z0,P+=Y*q0,_+=Y*Q0,S+=Y*H0,y+=Y*i,m+=Y*n,b+=Y*e,k+=Y*J0,f+=Y*Z0,p+=Y*K0,l+=Y*t,Y=Z[14],E+=Y*c,L+=Y*s,M+=Y*w0,A+=Y*a,I+=Y*F0,P+=Y*z0,_+=Y*q0,S+=Y*Q0,y+=Y*H0,m+=Y*i,b+=Y*n,k+=Y*e,f+=Y*J0,p+=Y*Z0,l+=Y*K0,x+=Y*t,Y=Z[15],L+=Y*c,M+=Y*s,A+=Y*w0,I+=Y*a,P+=Y*F0,_+=Y*z0,S+=Y*q0,y+=Y*Q0,m+=Y*H0,b+=Y*i,k+=Y*n,f+=Y*e,p+=Y*J0,l+=Y*Z0,x+=Y*K0,r+=Y*t,V+=38*M,K+=38*A,z+=38*I,G+=38*P,F+=38*_,U+=38*S,q+=38*y,D+=38*m,W+=38*b,H+=38*k,B+=38*f,w+=38*p,N+=38*l,O+=38*x,E+=38*r,X=1,Y=V+X+65535,X=Math.floor(Y/65536),V=Y-X*65536,Y=K+X+65535,X=Math.floor(Y/65536),K=Y-X*65536,Y=z+X+65535,X=Math.floor(Y/65536),z=Y-X*65536,Y=G+X+65535,X=Math.floor(Y/65536),G=Y-X*65536,Y=F+X+65535,X=Math.floor(Y/65536),F=Y-X*65536,Y=U+X+65535,X=Math.floor(Y/65536),U=Y-X*65536,Y=q+X+65535,X=Math.floor(Y/65536),q=Y-X*65536,Y=D+X+65535,X=Math.floor(Y/65536),D=Y-X*65536,Y=W+X+65535,X=Math.floor(Y/65536),W=Y-X*65536,Y=H+X+65535,X=Math.floor(Y/65536),H=Y-X*65536,Y=B+X+65535,X=Math.floor(Y/65536),B=Y-X*65536,Y=w+X+65535,X=Math.floor(Y/65536),w=Y-X*65536,Y=N+X+65535,X=Math.floor(Y/65536),N=Y-X*65536,Y=O+X+65535,X=Math.floor(Y/65536),O=Y-X*65536,Y=E+X+65535,X=Math.floor(Y/65536),E=Y-X*65536,Y=L+X+65535,X=Math.floor(Y/65536),L=Y-X*65536,V+=X-1+37*(X-1),X=1,Y=V+X+65535,X=Math.floor(Y/65536),V=Y-X*65536,Y=K+X+65535,X=Math.floor(Y/65536),K=Y-X*65536,Y=z+X+65535,X=Math.floor(Y/65536),z=Y-X*65536,Y=G+X+65535,X=Math.floor(Y/65536),G=Y-X*65536,Y=F+X+65535,X=Math.floor(Y/65536),F=Y-X*65536,Y=U+X+65535,X=Math.floor(Y/65536),U=Y-X*65536,Y=q+X+65535,X=Math.floor(Y/65536),q=Y-X*65536,Y=D+X+65535,X=Math.floor(Y/65536),D=Y-X*65536,Y=W+X+65535,X=Math.floor(Y/65536),W=Y-X*65536,Y=H+X+65535,X=Math.floor(Y/65536),H=Y-X*65536,Y=B+X+65535,X=Math.floor(Y/65536),B=Y-X*65536,Y=w+X+65535,X=Math.floor(Y/65536),w=Y-X*65536,Y=N+X+65535,X=Math.floor(Y/65536),N=Y-X*65536,Y=O+X+65535,X=Math.floor(Y/65536),O=Y-X*65536,Y=E+X+65535,X=Math.floor(Y/65536),E=Y-X*65536,Y=L+X+65535,X=Math.floor(Y/65536),L=Y-X*65536,V+=X-1+37*(X-1),J[0]=V,J[1]=K,J[2]=z,J[3]=G,J[4]=F,J[5]=U,J[6]=q,J[7]=D,J[8]=W,J[9]=H,J[10]=B,J[11]=w,J[12]=N,J[13]=O,J[14]=E,J[15]=L}});var tI4=u((HE9,sI4)=>{var _Q=J5();c5();JX();Od();sI4.exports=_Q.kem=_Q.kem||{};var oI4=_Q.jsbn.BigInteger;_Q.kem.rsa={};_Q.kem.rsa.create=function(J,Z){Z=Z||{};var Q=Z.prng||_Q.random,Y={};return Y.encrypt=function(X,V){var K=Math.ceil(X.n.bitLength()/8),z;do z=new oI4(_Q.util.bytesToHex(Q.getBytesSync(K)),16).mod(X.n);while(z.compareTo(oI4.ONE)<=0);z=_Q.util.hexToBytes(z.toString(16));var G=K-z.length;if(G>0)z=_Q.util.fillString(String.fromCharCode(0),G)+z;var F=X.encrypt(z,"NONE"),U=J.generate(z,V);return{encapsulation:F,key:U}},Y.decrypt=function(X,V,K){var z=X.decrypt(V,"NONE");return J.generate(z,K)},Y};_Q.kem.kdf1=function(J,Z){rI4(this,J,0,Z||J.digestLength)};_Q.kem.kdf2=function(J,Z){rI4(this,J,1,Z||J.digestLength)};function rI4(J,Z,Q,Y){J.generate=function(X,V){var K=new _Q.util.ByteBuffer,z=Math.ceil(V/Y)+Q,G=new _Q.util.ByteBuffer;for(var F=Q;F<z;++F){G.putInt32(F),Z.start(),Z.update(X+G.getBytes());var U=Z.digest();K.putBytes(U.getBytes(Y))}return K.truncate(K.length()-V),K.getBytes()}}});var $j4=u((BE9,eI4)=>{var L5=J5();c5();eI4.exports=L5.log=L5.log||{};L5.log.levels=["none","error","warning","info","debug","verbose","max"];var QZ0={},Ql0=[],Rd=null;L5.log.LEVEL_LOCKED=2;L5.log.NO_LEVEL_CHECK=4;L5.log.INTERPOLATE=8;for(KX=0;KX<L5.log.levels.length;++KX)JZ0=L5.log.levels[KX],QZ0[JZ0]={index:KX,name:JZ0.toUpperCase()};var JZ0,KX;L5.log.logMessage=function(J){var Z=QZ0[J.level].index;for(var Q=0;Q<Ql0.length;++Q){var Y=Ql0[Q];if(Y.flags&L5.log.NO_LEVEL_CHECK)Y.f(J);else{var X=QZ0[Y.level].index;if(Z<=X)Y.f(Y,J)}}};L5.log.prepareStandard=function(J){if(!("standard"in J))J.standard=QZ0[J.level].name+" ["+J.category+"] "+J.message};L5.log.prepareFull=function(J){if(!("full"in J)){var Z=[J.message];Z=Z.concat([]),J.full=L5.util.format.apply(this,Z)}};L5.log.prepareStandardFull=function(J){if(!("standardFull"in J))L5.log.prepareStandard(J),J.standardFull=J.standard};ZZ0=["error","warning","info","debug","verbose"];for(KX=0;KX<ZZ0.length;++KX)(function(Z){L5.log[Z]=function(Q,Y){var X=Array.prototype.slice.call(arguments).slice(2),V={timestamp:new Date,level:Z,category:Q,message:Y,arguments:X};L5.log.logMessage(V)}})(ZZ0[KX]);var ZZ0,KX;L5.log.makeLogger=function(J){var Z={flags:0,f:J};return L5.log.setLevel(Z,"none"),Z};L5.log.setLevel=function(J,Z){var Q=!1;if(J&&!(J.flags&L5.log.LEVEL_LOCKED))for(var Y=0;Y<L5.log.levels.length;++Y){var X=L5.log.levels[Y];if(Z==X){J.level=Z,Q=!0;break}}return Q};L5.log.lock=function(J,Z){if(typeof Z>"u"||Z)J.flags|=L5.log.LEVEL_LOCKED;else J.flags&=~L5.log.LEVEL_LOCKED};L5.log.addLogger=function(J){Ql0.push(J)};if(typeof console<"u"&&"log"in console){if(console.error&&console.warn&&console.info&&console.debug)Yl0={error:console.error,warning:console.warn,info:console.info,debug:console.debug,verbose:console.debug},B_=function(J,Z){L5.log.prepareStandard(Z);var Q=Yl0[Z.level],Y=[Z.standard];Y=Y.concat(Z.arguments.slice()),Q.apply(console,Y)},eL=L5.log.makeLogger(B_);else B_=function(Z,Q){L5.log.prepareStandardFull(Q),console.log(Q.standardFull)},eL=L5.log.makeLogger(B_);L5.log.setLevel(eL,"debug"),L5.log.addLogger(eL),Rd=eL}else console={log:function(){}};var eL,Yl0,B_;if(Rd!==null&&typeof window<"u"&&window.location){if(H_=new URL(window.location.href).searchParams,H_.has("console.level"))L5.log.setLevel(Rd,H_.get("console.level").slice(-1)[0]);if(H_.has("console.lock")){if(Xl0=H_.get("console.lock").slice(-1)[0],Xl0=="true")L5.log.lock(Rd)}}var H_,Xl0;L5.log.consoleLogger=Rd});var Zj4=u((wE9,Jj4)=>{Jj4.exports=NG();uJ0();z_();wc0();nc0()});var Xj4=u((NE9,Yj4)=>{var U4=J5();KB();oV();wd();zB();lL();vc0();JX();c5();oJ0();var b0=U4.asn1,BJ=Yj4.exports=U4.pkcs7=U4.pkcs7||{};BJ.messageFromPem=function(J){var Z=U4.pem.decode(J)[0];if(Z.type!=="PKCS7"){var Q=Error('Could not convert PKCS#7 message from PEM; PEM header type is not "PKCS#7".');throw Q.headerType=Z.type,Q}if(Z.procType&&Z.procType.type==="ENCRYPTED")throw Error("Could not convert PKCS#7 message from PEM; PEM is encrypted.");var Y=b0.fromDer(Z.body);return BJ.messageFromAsn1(Y)};BJ.messageToPem=function(J,Z){var Q={type:"PKCS7",body:b0.toDer(J.toAsn1()).getBytes()};return U4.pem.encode(Q,{maxline:Z})};BJ.messageFromAsn1=function(J){var Z={},Q=[];if(!b0.validate(J,BJ.asn1.contentInfoValidator,Z,Q)){var Y=Error("Cannot read PKCS#7 message. ASN.1 object is not an PKCS#7 ContentInfo.");throw Y.errors=Q,Y}var X=b0.derToOid(Z.contentType),V;switch(X){case U4.pki.oids.envelopedData:V=BJ.createEnvelopedData();break;case U4.pki.oids.encryptedData:V=BJ.createEncryptedData();break;case U4.pki.oids.signedData:V=BJ.createSignedData();break;default:throw Error("Cannot read PKCS#7 message. ContentType with OID "+X+" is not (yet) supported.")}return V.fromAsn1(Z.content.value[0]),V};BJ.createSignedData=function(){var J=null;return J={type:U4.pki.oids.signedData,version:1,certificates:[],crls:[],signers:[],digestAlgorithmIdentifiers:[],contentInfo:null,signerInfos:[],fromAsn1:function(Y){if(Kl0(J,Y,BJ.asn1.signedDataValidator),J.certificates=[],J.crls=[],J.digestAlgorithmIdentifiers=[],J.contentInfo=null,J.signerInfos=[],J.rawCapture.certificates){var X=J.rawCapture.certificates.value;for(var V=0;V<X.length;++V)J.certificates.push(U4.pki.certificateFromAsn1(X[V]))}},toAsn1:function(){if(!J.contentInfo)J.sign();var Y=[];for(var X=0;X<J.certificates.length;++X)Y.push(U4.pki.certificateToAsn1(J.certificates[X]));var V=[],K=b0.create(b0.Class.CONTEXT_SPECIFIC,0,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.SEQUENCE,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.INTEGER,!1,b0.integerToDer(J.version).getBytes()),b0.create(b0.Class.UNIVERSAL,b0.Type.SET,!0,J.digestAlgorithmIdentifiers),J.contentInfo])]);if(Y.length>0)K.value[0].value.push(b0.create(b0.Class.CONTEXT_SPECIFIC,0,!0,Y));if(V.length>0)K.value[0].value.push(b0.create(b0.Class.CONTEXT_SPECIFIC,1,!0,V));return K.value[0].value.push(b0.create(b0.Class.UNIVERSAL,b0.Type.SET,!0,J.signerInfos)),b0.create(b0.Class.UNIVERSAL,b0.Type.SEQUENCE,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.OID,!1,b0.oidToDer(J.type).getBytes()),K])},addSigner:function(Y){var{issuer:X,serialNumber:V}=Y;if(Y.certificate){var K=Y.certificate;if(typeof K==="string")K=U4.pki.certificateFromPem(K);X=K.issuer.attributes,V=K.serialNumber}var z=Y.key;if(!z)throw Error("Could not add PKCS#7 signer; no private key specified.");if(typeof z==="string")z=U4.pki.privateKeyFromPem(z);var G=Y.digestAlgorithm||U4.pki.oids.sha1;switch(G){case U4.pki.oids.sha1:case U4.pki.oids.sha256:case U4.pki.oids.sha384:case U4.pki.oids.sha512:case U4.pki.oids.md5:break;default:throw Error("Could not add PKCS#7 signer; unknown message digest algorithm: "+G)}var F=Y.authenticatedAttributes||[];if(F.length>0){var U=!1,q=!1;for(var D=0;D<F.length;++D){var W=F[D];if(!U&&W.type===U4.pki.oids.contentType){if(U=!0,q)break;continue}if(!q&&W.type===U4.pki.oids.messageDigest){if(q=!0,U)break;continue}}if(!U||!q)throw Error("Invalid signer.authenticatedAttributes. If signer.authenticatedAttributes is specified, then it must contain at least two attributes, PKCS #9 content-type and PKCS #9 message-digest.")}J.signers.push({key:z,version:1,issuer:X,serialNumber:V,digestAlgorithm:G,signatureAlgorithm:U4.pki.oids.rsaEncryption,signature:null,authenticatedAttributes:F,unauthenticatedAttributes:[]})},sign:function(Y){if(Y=Y||{},typeof J.content!=="object"||J.contentInfo===null){if(J.contentInfo=b0.create(b0.Class.UNIVERSAL,b0.Type.SEQUENCE,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.OID,!1,b0.oidToDer(U4.pki.oids.data).getBytes())]),"content"in J){var X;if(J.content instanceof U4.util.ByteBuffer)X=J.content.bytes();else if(typeof J.content==="string")X=U4.util.encodeUtf8(J.content);if(Y.detached)J.detachedContent=b0.create(b0.Class.UNIVERSAL,b0.Type.OCTETSTRING,!1,X);else J.contentInfo.value.push(b0.create(b0.Class.CONTEXT_SPECIFIC,0,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.OCTETSTRING,!1,X)]))}}if(J.signers.length===0)return;var V=Z();Q(V)},verify:function(){throw Error("PKCS#7 signature verification not yet implemented.")},addCertificate:function(Y){if(typeof Y==="string")Y=U4.pki.certificateFromPem(Y);J.certificates.push(Y)},addCertificateRevokationList:function(Y){throw Error("PKCS#7 CRL support not yet implemented.")}},J;function Z(){var Y={};for(var X=0;X<J.signers.length;++X){var V=J.signers[X],K=V.digestAlgorithm;if(!(K in Y))Y[K]=U4.md[U4.pki.oids[K]].create();if(V.authenticatedAttributes.length===0)V.md=Y[K];else V.md=U4.md[U4.pki.oids[K]].create()}J.digestAlgorithmIdentifiers=[];for(var K in Y)J.digestAlgorithmIdentifiers.push(b0.create(b0.Class.UNIVERSAL,b0.Type.SEQUENCE,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.OID,!1,b0.oidToDer(K).getBytes()),b0.create(b0.Class.UNIVERSAL,b0.Type.NULL,!1,"")]));return Y}function Q(Y){var X;if(J.detachedContent)X=J.detachedContent;else X=J.contentInfo.value[1],X=X.value[0];if(!X)throw Error("Could not sign PKCS#7 message; there is no content to sign.");var V=b0.derToOid(J.contentInfo.value[0].value),K=b0.toDer(X);K.getByte(),b0.getBerValueLength(K),K=K.getBytes();for(var z in Y)Y[z].start().update(K);var G=new Date;for(var F=0;F<J.signers.length;++F){var U=J.signers[F];if(U.authenticatedAttributes.length===0){if(V!==U4.pki.oids.data)throw Error("Invalid signer; authenticatedAttributes must be present when the ContentInfo content type is not PKCS#7 Data.")}else{U.authenticatedAttributesAsn1=b0.create(b0.Class.CONTEXT_SPECIFIC,0,!0,[]);var q=b0.create(b0.Class.UNIVERSAL,b0.Type.SET,!0,[]);for(var D=0;D<U.authenticatedAttributes.length;++D){var W=U.authenticatedAttributes[D];if(W.type===U4.pki.oids.messageDigest)W.value=Y[U.digestAlgorithm].digest();else if(W.type===U4.pki.oids.signingTime){if(!W.value)W.value=G}q.value.push(Vl0(W)),U.authenticatedAttributesAsn1.value.push(Vl0(W))}K=b0.toDer(q).getBytes(),U.md.start().update(K)}U.signature=U.key.sign(U.md,"RSASSA-PKCS1-V1_5")}J.signerInfos=D13(J.signers)}};BJ.createEncryptedData=function(){var J=null;return J={type:U4.pki.oids.encryptedData,version:0,encryptedContent:{algorithm:U4.pki.oids["aes256-CBC"]},fromAsn1:function(Z){Kl0(J,Z,BJ.asn1.encryptedDataValidator)},decrypt:function(Z){if(Z!==void 0)J.encryptedContent.key=Z;Qj4(J)}},J};BJ.createEnvelopedData=function(){var J=null;return J={type:U4.pki.oids.envelopedData,version:0,recipients:[],encryptedContent:{algorithm:U4.pki.oids["aes256-CBC"]},fromAsn1:function(Z){var Q=Kl0(J,Z,BJ.asn1.envelopedDataValidator);J.recipients=F13(Q.recipientInfos.value)},toAsn1:function(){return b0.create(b0.Class.UNIVERSAL,b0.Type.SEQUENCE,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.OID,!1,b0.oidToDer(J.type).getBytes()),b0.create(b0.Class.CONTEXT_SPECIFIC,0,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.SEQUENCE,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.INTEGER,!1,b0.integerToDer(J.version).getBytes()),b0.create(b0.Class.UNIVERSAL,b0.Type.SET,!0,U13(J.recipients)),b0.create(b0.Class.UNIVERSAL,b0.Type.SEQUENCE,!0,W13(J.encryptedContent))])])])},findRecipient:function(Z){var Q=Z.issuer.attributes;for(var Y=0;Y<J.recipients.length;++Y){var X=J.recipients[Y],V=X.issuer;if(X.serialNumber!==Z.serialNumber)continue;if(V.length!==Q.length)continue;var K=!0;for(var z=0;z<Q.length;++z)if(V[z].type!==Q[z].type||V[z].value!==Q[z].value){K=!1;break}if(K)return X}return null},decrypt:function(Z,Q){if(J.encryptedContent.key===void 0&&Z!==void 0&&Q!==void 0)switch(Z.encryptedContent.algorithm){case U4.pki.oids.rsaEncryption:case U4.pki.oids.desCBC:var Y=Q.decrypt(Z.encryptedContent.content);J.encryptedContent.key=U4.util.createBuffer(Y);break;default:throw Error("Unsupported asymmetric cipher, OID "+Z.encryptedContent.algorithm)}Qj4(J)},addRecipient:function(Z){J.recipients.push({version:0,issuer:Z.issuer.attributes,serialNumber:Z.serialNumber,encryptedContent:{algorithm:U4.pki.oids.rsaEncryption,key:Z.publicKey}})},encrypt:function(Z,Q){if(J.encryptedContent.content===void 0){Q=Q||J.encryptedContent.algorithm,Z=Z||J.encryptedContent.key;var Y,X,V;switch(Q){case U4.pki.oids["aes128-CBC"]:Y=16,X=16,V=U4.aes.createEncryptionCipher;break;case U4.pki.oids["aes192-CBC"]:Y=24,X=16,V=U4.aes.createEncryptionCipher;break;case U4.pki.oids["aes256-CBC"]:Y=32,X=16,V=U4.aes.createEncryptionCipher;break;case U4.pki.oids["des-EDE3-CBC"]:Y=24,X=8,V=U4.des.createEncryptionCipher;break;default:throw Error("Unsupported symmetric cipher, OID "+Q)}if(Z===void 0)Z=U4.util.createBuffer(U4.random.getBytes(Y));else if(Z.length()!=Y)throw Error("Symmetric key has wrong length; got "+Z.length()+" bytes, expected "+Y+".");J.encryptedContent.algorithm=Q,J.encryptedContent.key=Z,J.encryptedContent.parameter=U4.util.createBuffer(U4.random.getBytes(X));var K=V(Z);if(K.start(J.encryptedContent.parameter.copy()),K.update(J.content),!K.finish())throw Error("Symmetric encryption failed.");J.encryptedContent.content=K.output}for(var z=0;z<J.recipients.length;++z){var G=J.recipients[z];if(G.encryptedContent.content!==void 0)continue;switch(G.encryptedContent.algorithm){case U4.pki.oids.rsaEncryption:G.encryptedContent.content=G.encryptedContent.key.encrypt(J.encryptedContent.key.data);break;default:throw Error("Unsupported asymmetric cipher, OID "+G.encryptedContent.algorithm)}}}},J};function z13(J){var Z={},Q=[];if(!b0.validate(J,BJ.asn1.recipientInfoValidator,Z,Q)){var Y=Error("Cannot read PKCS#7 RecipientInfo. ASN.1 object is not an PKCS#7 RecipientInfo.");throw Y.errors=Q,Y}return{version:Z.version.charCodeAt(0),issuer:U4.pki.RDNAttributesAsArray(Z.issuer),serialNumber:U4.util.createBuffer(Z.serial).toHex(),encryptedContent:{algorithm:b0.derToOid(Z.encAlgorithm),parameter:Z.encParameter?Z.encParameter.value:void 0,content:Z.encKey}}}function G13(J){return b0.create(b0.Class.UNIVERSAL,b0.Type.SEQUENCE,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.INTEGER,!1,b0.integerToDer(J.version).getBytes()),b0.create(b0.Class.UNIVERSAL,b0.Type.SEQUENCE,!0,[U4.pki.distinguishedNameToAsn1({attributes:J.issuer}),b0.create(b0.Class.UNIVERSAL,b0.Type.INTEGER,!1,U4.util.hexToBytes(J.serialNumber))]),b0.create(b0.Class.UNIVERSAL,b0.Type.SEQUENCE,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.OID,!1,b0.oidToDer(J.encryptedContent.algorithm).getBytes()),b0.create(b0.Class.UNIVERSAL,b0.Type.NULL,!1,"")]),b0.create(b0.Class.UNIVERSAL,b0.Type.OCTETSTRING,!1,J.encryptedContent.content)])}function F13(J){var Z=[];for(var Q=0;Q<J.length;++Q)Z.push(z13(J[Q]));return Z}function U13(J){var Z=[];for(var Q=0;Q<J.length;++Q)Z.push(G13(J[Q]));return Z}function q13(J){var Z=b0.create(b0.Class.UNIVERSAL,b0.Type.SEQUENCE,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.INTEGER,!1,b0.integerToDer(J.version).getBytes()),b0.create(b0.Class.UNIVERSAL,b0.Type.SEQUENCE,!0,[U4.pki.distinguishedNameToAsn1({attributes:J.issuer}),b0.create(b0.Class.UNIVERSAL,b0.Type.INTEGER,!1,U4.util.hexToBytes(J.serialNumber))]),b0.create(b0.Class.UNIVERSAL,b0.Type.SEQUENCE,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.OID,!1,b0.oidToDer(J.digestAlgorithm).getBytes()),b0.create(b0.Class.UNIVERSAL,b0.Type.NULL,!1,"")])]);if(J.authenticatedAttributesAsn1)Z.value.push(J.authenticatedAttributesAsn1);if(Z.value.push(b0.create(b0.Class.UNIVERSAL,b0.Type.SEQUENCE,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.OID,!1,b0.oidToDer(J.signatureAlgorithm).getBytes()),b0.create(b0.Class.UNIVERSAL,b0.Type.NULL,!1,"")])),Z.value.push(b0.create(b0.Class.UNIVERSAL,b0.Type.OCTETSTRING,!1,J.signature)),J.unauthenticatedAttributes.length>0){var Q=b0.create(b0.Class.CONTEXT_SPECIFIC,1,!0,[]);for(var Y=0;Y<J.unauthenticatedAttributes.length;++Y){var X=J.unauthenticatedAttributes[Y];Q.values.push(Vl0(X))}Z.value.push(Q)}return Z}function D13(J){var Z=[];for(var Q=0;Q<J.length;++Q)Z.push(q13(J[Q]));return Z}function Vl0(J){var Z;if(J.type===U4.pki.oids.contentType)Z=b0.create(b0.Class.UNIVERSAL,b0.Type.OID,!1,b0.oidToDer(J.value).getBytes());else if(J.type===U4.pki.oids.messageDigest)Z=b0.create(b0.Class.UNIVERSAL,b0.Type.OCTETSTRING,!1,J.value.bytes());else if(J.type===U4.pki.oids.signingTime){var Q=new Date("1950-01-01T00:00:00Z"),Y=new Date("2050-01-01T00:00:00Z"),X=J.value;if(typeof X==="string"){var V=Date.parse(X);if(!isNaN(V))X=new Date(V);else if(X.length===13)X=b0.utcTimeToDate(X);else X=b0.generalizedTimeToDate(X)}if(X>=Q&&X<Y)Z=b0.create(b0.Class.UNIVERSAL,b0.Type.UTCTIME,!1,b0.dateToUtcTime(X));else Z=b0.create(b0.Class.UNIVERSAL,b0.Type.GENERALIZEDTIME,!1,b0.dateToGeneralizedTime(X))}return b0.create(b0.Class.UNIVERSAL,b0.Type.SEQUENCE,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.OID,!1,b0.oidToDer(J.type).getBytes()),b0.create(b0.Class.UNIVERSAL,b0.Type.SET,!0,[Z])])}function W13(J){return[b0.create(b0.Class.UNIVERSAL,b0.Type.OID,!1,b0.oidToDer(U4.pki.oids.data).getBytes()),b0.create(b0.Class.UNIVERSAL,b0.Type.SEQUENCE,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.OID,!1,b0.oidToDer(J.algorithm).getBytes()),!J.parameter?void 0:b0.create(b0.Class.UNIVERSAL,b0.Type.OCTETSTRING,!1,J.parameter.getBytes())]),b0.create(b0.Class.CONTEXT_SPECIFIC,0,!0,[b0.create(b0.Class.UNIVERSAL,b0.Type.OCTETSTRING,!1,J.content.getBytes())])]}function Kl0(J,Z,Q){var Y={},X=[];if(!b0.validate(Z,Q,Y,X)){var V=Error("Cannot read PKCS#7 message. ASN.1 object is not a supported PKCS#7 message.");throw V.errors=V,V}var K=b0.derToOid(Y.contentType);if(K!==U4.pki.oids.data)throw Error("Unsupported PKCS#7 message. Only wrapped ContentType Data supported.");if(Y.encryptedContent){var z="";if(U4.util.isArray(Y.encryptedContent))for(var G=0;G<Y.encryptedContent.length;++G){if(Y.encryptedContent[G].type!==b0.Type.OCTETSTRING)throw Error("Malformed PKCS#7 message, expecting encrypted content constructed of only OCTET STRING objects.");z+=Y.encryptedContent[G].value}else z=Y.encryptedContent;J.encryptedContent={algorithm:b0.derToOid(Y.encAlgorithm),parameter:U4.util.createBuffer(Y.encParameter.value),content:U4.util.createBuffer(z)}}if(Y.content){var z="";if(U4.util.isArray(Y.content))for(var G=0;G<Y.content.length;++G){if(Y.content[G].type!==b0.Type.OCTETSTRING)throw Error("Malformed PKCS#7 message, expecting content constructed of only OCTET STRING objects.");z+=Y.content[G].value}else z=Y.content;J.content=U4.util.createBuffer(z)}return J.version=Y.version.charCodeAt(0),J.rawCapture=Y,Y}function Qj4(J){if(J.encryptedContent.key===void 0)throw Error("Symmetric key not available.");if(J.content===void 0){var Z;switch(J.encryptedContent.algorithm){case U4.pki.oids["aes128-CBC"]:case U4.pki.oids["aes192-CBC"]:case U4.pki.oids["aes256-CBC"]:Z=U4.aes.createDecryptionCipher(J.encryptedContent.key);break;case U4.pki.oids.desCBC:case U4.pki.oids["des-EDE3-CBC"]:Z=U4.des.createDecryptionCipher(J.encryptedContent.key);break;default:throw Error("Unsupported symmetric cipher, OID "+J.encryptedContent.algorithm)}if(Z.start(J.encryptedContent.parameter),Z.update(J.encryptedContent.content),!Z.finish())throw Error("Symmetric decryption failed.");J.content=Z.output}}});var Kj4=u((OE9,Vj4)=>{var s9=J5();KB();Y_();uJ0();z_();c5();var XZ0=Vj4.exports=s9.ssh=s9.ssh||{};XZ0.privateKeyToPutty=function(J,Z,Q){Q=Q||"",Z=Z||"";var Y="ssh-rsa",X=Z===""?"none":"aes256-cbc",V="PuTTY-User-Key-File-2: "+Y+`\r
2552
2552
  `;V+="Encryption: "+X+`\r
2553
2553
  `,V+="Comment: "+Q+`\r
2554
2554
  `;var K=s9.util.createBuffer();w_(K,Y),RG(K,J.e),RG(K,J.n);var z=s9.util.encode64(K.bytes(),64),G=Math.floor(z.length/66)+1;V+="Public-Lines: "+G+`\r
@@ -6119,11 +6119,11 @@ ${W}`))}},error:(D)=>{if(!q)q=!0,z(Error(`Failed to spawn brew: ${D.message}`))}
6119
6119
  ${W}`;if(X==="pnpm"&&W.includes("Unable to find the global bin directory"))H+=`
6120
6120
 
6121
6121
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
6122
- npm install -g @sourcegraph/amp`;z(Error(H))}},error:(D)=>{if(!U)U=!0,z(Error(`Failed to spawn ${X}: ${D.message}`))},complete:()=>{if(!U)U=!0,K()}})})}h0();h0();Rj();async function e80(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,V=new AbortController,K=setTimeout(()=>V.abort(),5000);try{let z=await fetch(X,{signal:V.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 U=SK4(J,F),q=U<0,D,W;if(G.time){let H=G.time[J],B=G.time[F],w=Date.now();if(H)D=Math.floor((w-new Date(H).getTime())/3600000);if(B)W=Math.floor((w-new Date(B).getTime())/3600000)}return j.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:U,hasUpdate:q,currentVersionAge:D,latestVersionAge:W}),{hasUpdate:q,latestVersion:F,currentVersion:J,currentVersionAge:D,latestVersionAge:W,source:"npm"}}catch(z){return j.debug("Error checking npm version",{error:z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(K)}}var ZR5="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function $90(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${ZR5}?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 V=SK4(J,X),K=V<0;return j.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:V,hasUpdate:K}),{hasUpdate:K,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return j.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var QR5=604800000;function _K4(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>QR5)return{ageMs:Q};return null}function SK4(J,Z){let Q=(K)=>{let[z,G]=K.split("-");return{parts:z?.split(".").map(Number)||[],label:G}},Y=Q(J),X=Q(Z),V=Math.max(Y.parts.length,X.parts.length);for(let K=0;K<V;K++){let z=Y.parts[K]||0,G=X.parts[K]||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 lx0(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?PD(Q):void 0;return{sha:Y,age:X}}catch{return null}}H1();function ix0(J,Z,Q={}){let Y=new s1,X=Y.pipe(R6({shouldCountRefs:!1}));return setImmediate(async()=>{let V=new TK().scoped("update"),K=Q.startDelayMs??0;if(K>0)await Yz(K);let z=X.subscribe({next:(G)=>{V.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){V.debug("using fake update status for testing",{status:G}),await Yz(500),Y.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){V.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let F=await Z.get("updates.mode");if(F==="disabled"){V.debug("checking disabled");return}let U=await t80(),q=U==="binary"||U==="brew";V.debug("checking",{currentVersion:J,mode:F,packageManager:U,isBinaryDistribution:q});let D=q?await $90(J):await e80(J,aE());if(!(D.latestVersion&&D.hasUpdate)){V.debug("no update available");return}let W=()=>{if(D.currentVersionAge!==void 0&&D.latestVersionAge!==void 0){let H=D.currentVersionAge-D.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return V.debug("versions too close together, suppressing update warning",{currentVersionAge:D.currentVersionAge,latestVersionAge:D.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!F)F=U==="pnpm"?"warn":"auto",V.debug("no configured update mode; selected default based on package manager",{packageManager:U,mode:F});if(U==="brew"){if(!W())Y.next("update-available-brew");return}if(U==="binary"&&process.execPath!==hx0()){if(V.debug("non-standard binary path, showing warning"),!W())Y.next("update-available-unrecognized-path");return}if(F==="warn"){if(!W())Y.next("update-available");return}if(!U){if(V.debug("auto-update not supported, falling back to warn mode"),!W())Y.next("update-available");return}if(U==="binary"&&process.platform==="win32"){if(V.debug("binary auto-update not supported on Windows, falling back to warn mode"),!W())Y.next("update-available");return}try{await Qg(D.latestVersion,U);let H=await FH(D.latestVersion),B={from:D.currentVersion,to:D.latestVersion,...H};if(H.status==="same")V.info("success",B),Y.next("updated");else V.warn("success with warning",B),Y.next("updated-with-warning")}catch(H){Y.next("update-error")}}catch(G){V.debug("check failed",{error:G})}finally{await Yz(5000),Y.next("hidden"),z.unsubscribe(),Y.complete()}}),{state:X}}Rj();import{stderr as az}from"node:process";function vK4(J){let Z=new sW().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 ux0(Y.force||!1,Y.verbose||!1,"0.0.1773462612-g20fbe1"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new sW("update").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(Y)=>{await YR5(Y.targetVersion)});J.addCommand(Q)}async function YR5(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")az.write(Z1.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6122
+ npm install -g @sourcegraph/amp`;z(Error(H))}},error:(D)=>{if(!U)U=!0,z(Error(`Failed to spawn ${X}: ${D.message}`))},complete:()=>{if(!U)U=!0,K()}})})}h0();h0();Rj();async function e80(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,V=new AbortController,K=setTimeout(()=>V.abort(),5000);try{let z=await fetch(X,{signal:V.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 U=SK4(J,F),q=U<0,D,W;if(G.time){let H=G.time[J],B=G.time[F],w=Date.now();if(H)D=Math.floor((w-new Date(H).getTime())/3600000);if(B)W=Math.floor((w-new Date(B).getTime())/3600000)}return j.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:U,hasUpdate:q,currentVersionAge:D,latestVersionAge:W}),{hasUpdate:q,latestVersion:F,currentVersion:J,currentVersionAge:D,latestVersionAge:W,source:"npm"}}catch(z){return j.debug("Error checking npm version",{error:z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(K)}}var ZR5="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function $90(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${ZR5}?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 V=SK4(J,X),K=V<0;return j.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:V,hasUpdate:K}),{hasUpdate:K,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return j.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var QR5=604800000;function _K4(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>QR5)return{ageMs:Q};return null}function SK4(J,Z){let Q=(K)=>{let[z,G]=K.split("-");return{parts:z?.split(".").map(Number)||[],label:G}},Y=Q(J),X=Q(Z),V=Math.max(Y.parts.length,X.parts.length);for(let K=0;K<V;K++){let z=Y.parts[K]||0,G=X.parts[K]||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 lx0(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?PD(Q):void 0;return{sha:Y,age:X}}catch{return null}}H1();function ix0(J,Z,Q={}){let Y=new s1,X=Y.pipe(R6({shouldCountRefs:!1}));return setImmediate(async()=>{let V=new TK().scoped("update"),K=Q.startDelayMs??0;if(K>0)await Yz(K);let z=X.subscribe({next:(G)=>{V.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){V.debug("using fake update status for testing",{status:G}),await Yz(500),Y.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){V.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let F=await Z.get("updates.mode");if(F==="disabled"){V.debug("checking disabled");return}let U=await t80(),q=U==="binary"||U==="brew";V.debug("checking",{currentVersion:J,mode:F,packageManager:U,isBinaryDistribution:q});let D=q?await $90(J):await e80(J,aE());if(!(D.latestVersion&&D.hasUpdate)){V.debug("no update available");return}let W=()=>{if(D.currentVersionAge!==void 0&&D.latestVersionAge!==void 0){let H=D.currentVersionAge-D.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return V.debug("versions too close together, suppressing update warning",{currentVersionAge:D.currentVersionAge,latestVersionAge:D.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!F)F=U==="pnpm"?"warn":"auto",V.debug("no configured update mode; selected default based on package manager",{packageManager:U,mode:F});if(U==="brew"){if(!W())Y.next("update-available-brew");return}if(U==="binary"&&process.execPath!==hx0()){if(V.debug("non-standard binary path, showing warning"),!W())Y.next("update-available-unrecognized-path");return}if(F==="warn"){if(!W())Y.next("update-available");return}if(!U){if(V.debug("auto-update not supported, falling back to warn mode"),!W())Y.next("update-available");return}if(U==="binary"&&process.platform==="win32"){if(V.debug("binary auto-update not supported on Windows, falling back to warn mode"),!W())Y.next("update-available");return}try{await Qg(D.latestVersion,U);let H=await FH(D.latestVersion),B={from:D.currentVersion,to:D.latestVersion,...H};if(H.status==="same")V.info("success",B),Y.next("updated");else V.warn("success with warning",B),Y.next("updated-with-warning")}catch(H){Y.next("update-error")}}catch(G){V.debug("check failed",{error:G})}finally{await Yz(5000),Y.next("hidden"),z.unsubscribe(),Y.complete()}}),{state:X}}Rj();import{stderr as az}from"node:process";function vK4(J){let Z=new sW().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 ux0(Y.force||!1,Y.verbose||!1,"0.0.1773489712-g258ad5"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new sW("update").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(Y)=>{await YR5(Y.targetVersion)});J.addCommand(Q)}async function YR5(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")az.write(Z1.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6123
6123
 
6124
6124
  `));try{if(!J){az.write(Z1.blue(`Checking for updates...
6125
- `));let{hasUpdate:Y,latestVersion:X}=xx0()?await $90("0.0.1773462612-g20fbe1"):await e80("0.0.1773462612-g20fbe1",aE());if(!Y){let V=lx0("0.0.1773462612-g20fbe1"),K=V?.age?`released ${V.age} ago`:`built ${PD(new Date("2026-03-14T04:35:49.775Z"))} ago`;az.write(Z1.green(`✓ Amp is already up to date on version ${"0.0.1773462612-g20fbe1"} (${K})
6126
- `));let z=await FH("0.0.1773462612-g20fbe1");if(z.warning)az.write(`
6125
+ `));let{hasUpdate:Y,latestVersion:X}=xx0()?await $90("0.0.1773489712-g258ad5"):await e80("0.0.1773489712-g258ad5",aE());if(!Y){let V=lx0("0.0.1773489712-g258ad5"),K=V?.age?`released ${V.age} ago`:`built ${PD(new Date("2026-03-14T12:07:36.317Z"))} ago`;az.write(Z1.green(`✓ Amp is already up to date on version ${"0.0.1773489712-g258ad5"} (${K})
6126
+ `));let z=await FH("0.0.1773489712-g258ad5");if(z.warning)az.write(`
6127
6127
  `+Z1.yellow(z.warning)+`
6128
6128
  `);process.exit(0)}if(!X)az.write(Z1.yellow("[WARN] could not find latest version")),process.exit(0);J=X}az.write(Z1.blue(`Updating to version ${J}...
6129
6129
  `)),await Qg(J,void 0,(Y)=>{az.write(Z1.dim(`Running: ${Y}
@@ -6885,7 +6885,7 @@ See https://ampcode.com/manual#toolboxes`);return Z[0]||MI}function bG4(J,Z){let
6885
6885
  `),await V.asyncDispose(),V.cleanupTerminal(),process.exit(1);let U=await N_5(K,"utf-8").catch(()=>K);u$("systemPrompt",U)}let z=0;await CG4({json:X.json,inspect:X.inspect,isTTY:V.context.isTTY,mode:X.mode,toolService:V.toolService,configService:V.configService,mcpService:V.mcpService,skillService:V.skillService,threadService:V.threadService,fileSystem:V.fileSystem,getThreadEnvironment:V.getThreadEnvironment,serverStatus:V.serverStatus,toolboxService:V.toolboxService,stderr:process.stderr,stdout:process.stdout,exit:(G)=>{z=G}}),await V.asyncDispose(),V.cleanupTerminal(),process.exit(z)})}function L_5(J,Z){J.command("show").argument("<tool>","The tool for which to show details").description("Show details about an active tool").option("--json","output as a single JSON object").option("--mode <mode>","filter tools by agent mode (default: smart)","smart").action(async(Q,Y,X)=>{let V=X.optsWithGlobals(),K=await Z(X,V),z=0,G=K.toolService;await vG4({toolName:Q,json:V.json,isTTY:K.context.isTTY,mode:V.mode,toolService:G,mcpService:K.mcpService,stdout:process.stdout,exit:(F)=>{z=F}}),await K.asyncDispose(),K.cleanupTerminal(),process.exit(z)})}function M_5(J,Z){J.command("make").argument("<tool-name>","A descriptive name like run-tests or build-project").description("Sets up a skeleton tool in your toolbox").option("--force","Overwrite an existing tool if it already exists").option("--bun","Create a Bun/TypeScript tool (default)").option("--zsh","Create a Zsh shell script tool").option("--bash","Create a Bash shell script tool").action(async(Q,Y,X)=>{let V="bun";if(Y.zsh)V="zsh";else if(Y.bash)V="bash";else if(Y.bun)V="bun";try{let K=O_5();await SG4({fs:_G4,toolName:Q,toolboxDir:K,force:Y.force,language:V,stdout:process.stdout,exit:process.exit})}catch(K){process.stdout.write(`${K instanceof Error?K.message:String(K)}
6886
6886
  `),process.exit(1)}})}function A_5(J,Z){let Q=[Z1.bold("Examples:"),""," # invoke the Read tool for README.md and the first ten lines"," amp tools use Read --path $PWD/README.md --read_range 0 --read_range 10",""," # invoke web_search with JSON input",` amp tools use web_search <<<'{"query":"Svelte 5"}'`,""," # invoke a toolbox tool"," amp tools use tb__run_test --workspace server","",`Use ${Z1.green("amp tools list")} to get a list of all tools available in this environment.`,"",`Use ${Z1.green("amp tools show <tool-name>")} to see the schema of a tool.`].join(`
6887
6887
  `);J.command("use").argument("<tool-name>","The tool to invoke").summary("Invoke a tool with arguments or JSON input from stdin").description(Q).option("--only <field>","Extract only the specified field from the result").option("--stream","Stream updates as they arrive instead of waiting for completion").allowUnknownOption(!0).allowExcessArguments(!0).action(async(Y,X,V)=>{let K=V.optsWithGlobals(),z=await Z(V,K),G=0,F=V.args.slice(1),U;if(xG4()){let q=[];for await(let D of process.stdin)q.push(D);U=Buffer.concat(q).toString("utf-8").trim()}await yG4({toolName:Y,rawArgs:F,stdinInput:U,only:X.only,stream:X.stream,threadDeps:z,stdout:process.stdout,stderr:process.stderr,exit:(q)=>{G=q}}),await z.asyncDispose(),z.cleanupTerminal(),process.exit(G)})}_4();H1();H1();function mG4(J){let Z=new Ug,Q=[],Y=new h,X,V="",K=()=>{if(V.length>0)Q.push({text:V,style:Y,hyperlink:X}),V=""};if(Z.onEvent((G)=>{switch(G.type){case"print":V+=G.grapheme;break;case"execute":if(G.code===10)V+=`
6888
- `;else if(G.code===9)V+="\t";break;case"csi":if(G.final==="m")K(),Y=I_5(Y,G);break;case"osc":{let F=R_5(G.data);if(F!==null)K(),X=F;break}case"escape":case"dcs":break}}),Z.parse(J),Z.flush(),K(),Q.length===0)return new C("");if(Q.length===1){let G=Q[0];return new C(G.text,G.style,void 0,G.hyperlink)}let z=Q.map((G)=>new C(G.text,G.style,void 0,G.hyperlink));return new C(void 0,void 0,z)}function I_5(J,Z){let Q=j_5(Z.params);if(Q.length===0)Q.push(0);let Y=J;for(let X=0;X<Q.length;X++){let V=Q[X];switch(V){case 0:Y=new h;break;case 1:Y=Y.copyWith({bold:!0});break;case 2:Y=Y.copyWith({dim:!0});break;case 3:Y=Y.copyWith({italic:!0});break;case 4:Y=Y.copyWith({underline:!0});break;case 9:Y=Y.copyWith({strikethrough:!0});break;case 22:Y=Y.copyWith({bold:!1,dim:!1});break;case 23:Y=Y.copyWith({italic:!1});break;case 24:Y=Y.copyWith({underline:!1});break;case 29:Y=Y.copyWith({strikethrough:!1});break;case 30:case 31:case 32:case 33:case 34:case 35:case 36:case 37:Y=Y.copyWith({color:M0.index(V-30)});break;case 38:{let K=hG4(Q,X);if(K.color)Y=Y.copyWith({color:K.color});X=K.nextIndex;break}case 39:Y=Y.copyWith({color:M0.default()});break;case 40:case 41:case 42:case 43:case 44:case 45:case 46:case 47:Y=Y.copyWith({backgroundColor:M0.index(V-40)});break;case 48:{let K=hG4(Q,X);if(K.color)Y=Y.copyWith({backgroundColor:K.color});X=K.nextIndex;break}case 49:Y=Y.copyWith({backgroundColor:M0.default()});break;case 90:case 91:case 92:case 93:case 94:case 95:case 96:case 97:Y=Y.copyWith({color:M0.index(V-90+8)});break;case 100:case 101:case 102:case 103:case 104:case 105:case 106:case 107:Y=Y.copyWith({backgroundColor:M0.index(V-100+8)});break}}return Y}function j_5(J){let Z=[];for(let Q of J)if(Z.push(Q.value),Q.subparams)Z.push(...Q.subparams);return Z}function hG4(J,Z){if(Z+1>=J.length)return{color:null,nextIndex:Z};let Q=J[Z+1];if(Q===2){let Y=Z+2,X=J.length-Y;if(X>=4){let V=J[Y+1]??0,K=J[Y+2]??0,z=J[Y+3]??0;return{color:M0.rgb(V,K,z),nextIndex:Z+5}}else if(X>=3){let V=J[Y]??0,K=J[Y+1]??0,z=J[Y+2]??0;return{color:M0.rgb(V,K,z),nextIndex:Z+4}}return{color:null,nextIndex:Z+1}}else if(Q===5){let Y=Z+2,X=J.length-Y;if(X>=2){let V=J[Y+1]??0;return{color:M0.index(V),nextIndex:Z+4}}else if(X>=1){let V=J[Y]??0;return{color:M0.index(V),nextIndex:Z+2}}return{color:null,nextIndex:Z+1}}return{color:null,nextIndex:Z+1}}function R_5(J){let Z=J.split(";");if(Z.length<2||Z[0]!=="8")return null;let Q=Z[1]??"",Y=Z.slice(2).join(";");if(!Y)return;let X="";if(Q){let V=Q.match(/id=([^:;]+)/);if(V)X=V[1]??""}return{uri:Y,id:X}}function P_5(J){let Z=J.replace(/\r/g,"");if(!Z.includes("\x1B"))return Z;return mG4(Z).toPlainText()}function v90(J){let Z;for(let[Q,Y]of J.entries()){let X=P_5(Y);if(X===Y)continue;if(!Z)Z=new Map(J);Z.set(Q,X)}return Z??J}function k90(J){let Z=J.toolProgressByToolUseID$.pipe(D1(v90));return{get thread$(){return J.thread$},get threadViewState$(){return J.threadViewState$},get inferenceErrors$(){return J.inferenceErrors$},get toolProgressByToolUseID$(){return Z},get pendingApprovals$(){return J.pendingApprovals$},get pendingSkills$(){return J.pendingSkills$},get getResolvedTokenUsage(){return J.getResolvedTokenUsage},sendMessage:J.sendMessage,restoreTo:J.restoreTo,queueMessage:J.queueMessage,discardQueuedMessages:J.discardQueuedMessages,interruptQueuedMessage:J.interruptQueuedMessage,setTitle:J.setTitle,setVisibility:J.setVisibility,cancelTurn:J.cancelTurn,cancelStreaming:J.cancelStreaming,retryTurn:J.retryTurn,dismissEphemeralError:J.dismissEphemeralError,preExecuteMode:J.preExecuteMode,postExecuteMode:J.postExecuteMode,setTestEphemeralError:J.setTestEphemeralError,resolveApproval:J.resolveApproval,addPendingSkill:J.addPendingSkill,removePendingSkill:J.removePendingSkill,clearPendingSkills:J.clearPendingSkills,getFilesAffectedByTruncation:J.getFilesAffectedByTruncation,clearPendingNavigation:J.clearPendingNavigation,getGuidanceFiles:J.getGuidanceFiles,invokeBashTool:J.invokeBashTool}}var gG4="Loading thread...";function C_5(J){return{id:J,created:Date.now(),v:0,messages:[]}}class _f0{placeholderThreadID;recentThreadIDsSubject=new Z4([]);threadTitlesSubject=new Z4({});draftsSubject=new Z4(new Map);threadHandlesSubject;allConnectedThreadActivityStatusesSubject=new Z4({});initializationStatusSubject=new Z4({pending:!0,message:gG4});pendingApprovalsSubject=new Z4([]);pendingSkillsSubject=new Z4([]);attachedPool=null;attachedPoolSubscriptions=[];attached=!1;readyPromise;readyResolve=null;readyReject=null;constructor(J=D3()){this.placeholderThreadID=J;let Z=new Z4(C_5(this.placeholderThreadID)),Q=new Z4(new Map),Y=new Z4(RP(Z.getValue(),{state:"active",inferenceState:"idle",fileChanges:{files:[]}}));this.threadHandlesSubject=new Z4(k90({thread$:Z,threadViewState$:Y,toolProgressByToolUseID$:Q,pendingApprovals$:this.pendingApprovalsSubject,pendingSkills$:this.pendingSkillsSubject,sendMessage:async(X)=>(await this.waitForActiveHandle()).sendMessage(X),restoreTo:async(X)=>(await this.waitForActiveHandle()).restoreTo(X),queueMessage:async(X)=>(await this.waitForActiveHandle()).queueMessage(X),discardQueuedMessages:async()=>(await this.waitForActiveHandle()).discardQueuedMessages(),setVisibility:async(X)=>(await this.waitForActiveHandle()).setVisibility(X),cancelTurn:async()=>(await this.waitForActiveHandle()).cancelTurn(),cancelStreaming:async()=>(await this.waitForActiveHandle()).cancelStreaming(),retryTurn:async()=>(await this.waitForActiveHandle()).retryTurn(),dismissEphemeralError:()=>{},preExecuteMode:async()=>(await this.waitForActiveHandle()).preExecuteMode?.(),postExecuteMode:async()=>(await this.waitForActiveHandle()).postExecuteMode?.(),resolveApproval:async(X,V,K)=>(await this.waitForActiveHandle()).resolveApproval(X,V,K),addPendingSkill:()=>{},removePendingSkill:()=>{},clearPendingSkills:()=>{},getFilesAffectedByTruncation:async(X)=>(await this.waitForActiveHandle()).getFilesAffectedByTruncation(X),clearPendingNavigation:async()=>(await this.waitForActiveHandle()).clearPendingNavigation(),getGuidanceFiles:async(X)=>(await this.waitForActiveHandle()).getGuidanceFiles(X)})),this.readyPromise=new Promise((X,V)=>{this.readyResolve=X,this.readyReject=V}),this.readyPromise.catch(()=>{return})}get recentThreadIDs$(){return this.recentThreadIDsSubject}get threadTitles$(){return this.threadTitlesSubject}get drafts$(){return this.draftsSubject}get threadHandles$(){return this.threadHandlesSubject}get allConnectedThreadActivityStatuses$(){return this.allConnectedThreadActivityStatusesSubject}get initializationStatus$(){return this.initializationStatusSubject}get queueOnSubmitByDefault(){return this.attachedPool?.queueOnSubmitByDefault??!1}hasPendingInitialization(){return this.attachedPool===null}isDTWMode(){return this.attachedPool?.isDTWMode?.()===!0}getTransportConnectionState(){if(!this.attachedPool?.getTransportConnectionState)return;return this.attachedPool.getTransportConnectionState()}getCompactionStatus(){if(!this.attachedPool?.getCompactionStatus)return;return this.attachedPool.getCompactionStatus()}attach(J){if(this.attached)throw Error("DeferredThreadPool is already attached");this.attached=!0,this.attachedPool=J;let Z=null,Q=null;this.attachedPoolSubscriptions=[J.recentThreadIDs$.subscribe((Y)=>this.recentThreadIDsSubject.next(Y)),J.threadTitles$.subscribe((Y)=>this.threadTitlesSubject.next(Y)),J.drafts$.subscribe((Y)=>this.draftsSubject.next(Y)),J.allConnectedThreadActivityStatuses$.subscribe((Y)=>this.allConnectedThreadActivityStatusesSubject.next(Y)),...J.initializationStatus$?[J.initializationStatus$.subscribe((Y)=>this.initializationStatusSubject.next(Y))]:[(()=>{return this.initializationStatusSubject.next({pending:!1,message:gG4}),{unsubscribe:()=>{}}})()],J.threadHandles$.subscribe((Y)=>{if(Y)Z?.unsubscribe(),Z=Y.pendingApprovals$.subscribe((X)=>this.pendingApprovalsSubject.next(X)),Q?.unsubscribe(),Q=Y.pendingSkills$.subscribe((X)=>this.pendingSkillsSubject.next(X)),this.threadHandlesSubject.next(Y)}),{unsubscribe:()=>{Z?.unsubscribe(),Q?.unsubscribe()}}],this.readyResolve?.(J),this.readyResolve=null,this.readyReject=null}setInitError(J){if(this.attached)return;this.readyReject?.(J),this.readyResolve=null,this.readyReject=null}async createThread(){return(await this.waitForAttach()).createThread()}async switchThread(J){return(await this.waitForAttach()).switchThread(J)}async createHandoff(J,Z){return(await this.waitForAttach()).createHandoff(J,Z)}async deleteThread(J){let Z=await this.waitForAttach();if(Z.deleteThread)await Z.deleteThread(J)}async dispose(){for(let J of this.attachedPoolSubscriptions)J.unsubscribe();if(this.attachedPoolSubscriptions=[],this.attachedPool)await this.attachedPool.dispose();this.recentThreadIDsSubject.complete(),this.threadTitlesSubject.complete(),this.draftsSubject.complete(),this.threadHandlesSubject.complete(),this.allConnectedThreadActivityStatusesSubject.complete(),this.initializationStatusSubject.complete(),this.pendingApprovalsSubject.complete(),this.pendingSkillsSubject.complete()}waitForAttach(){if(this.attachedPool)return Promise.resolve(this.attachedPool);return this.readyPromise}async waitForActiveHandle(){let J=await this.waitForAttach();return E1(J.threadHandles$.pipe(F5((Z)=>Z!==null)))}}h0();o50();_4();H1();h0();a2();H1();function T_5(J){let Z=[],Q=0;for(let X of J.messages){if(X.role==="user"){Z.push({role:"user",content:[...X.content],meta:X.meta,userState:X.userState,readAt:X.readAt,parentToolUseId:X.parentToolUseId});continue}if(X.role==="assistant"){Z.push({role:"assistant",content:[...X.content],meta:X.meta,readAt:X.readAt,cancelled:X.state.type==="cancelled",parentToolUseId:X.parentToolUseId});continue}let V=X.content.filter((K)=>K.type==="manual_bash_invocation");if(V.length>0)Z.push({role:"info",content:V,parentToolUseId:X.parentToolUseId});for(let K of X.content){if(K.type!=="summary"||K.summary.type!=="message")continue;Q+=1,Z.push({role:"assistant",content:[{type:"text",text:K.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}}async function u90(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}:{}},V=await p3("/api/durable-thread-workers",Sf0({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(X),signal:Y.signal},Q),Z);if(!V.ok)throw Error(`Failed to create DTW thread: ${V.status} ${await V.text()}`);let K=await V.json();if(!K.threadId||!K.wsToken)throw Error("DTW thread creation response missing threadId or wsToken");return{threadId:K.threadId,wsToken:K.wsToken,usesDtw:K.usesDtw??!0,executorType:K.executorType??null}}async function __5(J,Z,Q,Y){let X=await Z.getLatest(),V=Q??await X.secrets.getToken("apiKey",X.settings.url);if(!V)throw Error("API key required. Please run `amp login` first.");let K=Y.workerURL??Q$(Y.ampURL),z=await fetch(`${K}/threads/${J.id}/import`,{method:"POST",headers:{Authorization:`Bearer ${V}`,"Content-Type":"application/json"},body:JSON.stringify({thread:T_5(J)})});if(z.status===409)return;if(!z.ok)throw Error(`Failed to import thread into DTW: ${z.status} ${await z.text()}`);if((await z.json()).ok!==!0)throw Error("Failed to import thread into DTW: import endpoint returned an invalid response")}async function S_5(J,Z,Q){let Y=await p3(`/api/durable-thread-workers/${J}`,Sf0({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 pG4(J,Z,Q){let Y=await p3(`/api/threads/${J}`,Sf0(void 0,Q),Z);if(!Y.ok)throw Error(`Failed to fetch thread snapshot: ${Y.status} ${await Y.text()}`);return await Y.json()}function Sf0(J,Z){if(!Z)return J;return{...J,headers:{...J?.headers,Authorization:`Bearer ${Z}`}}}function y90(J){let Z=M2.safeParse(J.dtwMessageID);if(Z.success)return Z.data;let Q=M2.safeParse(`${J.messageId}`);return Q.success?Q.data:null}function v_5(J){let Z=[],Q=new Set;for(let[Y,X]of J.messages.entries()){let V=y90(X);if(V)Q.add(V);Z.push({...X,messageId:Y})}return{messages:Z,processedIds:Q}}function k_5(J){let Z=new Set;for(let Q of J){let Y=y90(Q);if(Y)Z.add(Y)}return Z}function Og(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((V)=>V.type==="tool_use"&&V.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 y_5(J,Z,Q,Y){if(!J||Z.length===0)return null;return{role:"assistant",content:Z,state:{type:"streaming"},messageId:Q,parentToolUseId:Y}}function cG4(J){if(typeof J==="string")return J;if(!J||typeof J!=="object")return;if("output"in J&&typeof J.output==="string")return J.output;if("value"in J)return cG4(J.value);return}function u_5(J){return J.type==="text"}function x_5(J){if(J===void 0)return;let Z;try{Z=A80(J,"snapshot")}catch{return}if(Z.type==="snapshot")return cG4(Z.value);let Q=(Z.blocks??[]).filter(u_5).map((Y)=>Y.text).join("");return Q.length>0?Q:void 0}function f_5(J,Z){let Q=J.parentToolCallId,{completedMessages:Y}=Z;if(J.state==="complete"||J.state==="error"){if(Z.streamingMessageId!==null&&J.messageId!==Z.streamingMessageId){if(Z.streamingBlocks.length>0)Y.push({messageId:Z.streamingMessageId,role:"assistant",blocks:Z.streamingBlocks,parentToolCallId:Z.streamingParentToolCallId});Z.streamingMessageId=null,Z.streamingBlocks=[],Z.streamingParentToolCallId=void 0;let V=J.blocks??[];if(V.length>0)if(J.role==="user")Y.push({messageId:J.messageId,role:"user",blocks:V,parentToolCallId:Q});else Y.push({messageId:J.messageId,role:"assistant",blocks:V,parentToolCallId:Q});return}if(Z.streamingMessageId===null&&J.blocks&&J.blocks.length>0){let V=J.blocks;if(J.role==="user")Y.push({messageId:J.messageId,role:"user",blocks:V,parentToolCallId:Q});else Y.push({messageId:J.messageId,role:"assistant",blocks:V,parentToolCallId:Q});return}let X=Z.streamingBlocks;if(J.messageId===Z.streamingMessageId&&J.blocks&&J.role==="assistant")X=Og(Z.streamingBlocks,J.blocks);if(Z.streamingMessageId&&X.length>0)Y.push({messageId:Z.streamingMessageId,role:"assistant",blocks:X,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=Og([],J.blocks??[]),Z.streamingParentToolCallId=Q;else if(J.blocks)Z.streamingBlocks=Og(Z.streamingBlocks,J.blocks);if(Z.streamingBlocks.length>0)Y.push({messageId:Z.streamingMessageId??J.messageId,role:"assistant",blocks:Z.streamingBlocks,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=Og([],J.blocks??[]),Z.streamingParentToolCallId=Q;else if(J.blocks)Z.streamingBlocks=Og(Z.streamingBlocks,J.blocks)}}function b_5(J,Z,Q){if(Z.length===0)return J;let Y=[],X=J.length;for(let V of Z){if(Q.has(V.messageId))continue;Q.add(V.messageId);let K=X++;if(V.role==="assistant")Y.push({role:"assistant",content:V.blocks,state:{type:"complete",stopReason:"end_turn"},messageId:K,dtwMessageID:V.messageId,parentToolUseId:V.parentToolCallId});else Y.push({role:"user",content:V.blocks,messageId:K,dtwMessageID:V.messageId,parentToolUseId:V.parentToolCallId})}if(Y.length===0)return J;return[...J,...Y]}function h_5(J,Z,Q){let Y=J.message.messageId;if(Q.has(Y))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"},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,userState:J.message.userState,messageId:X,dtwMessageID:Y,parentToolUseId:J.parentToolUseId}]}function m_5(J,Z){let Q=Z.findIndex((z)=>y90(z)===J.messageId),Y=Z.findIndex((z)=>y90(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 V={role:"user",content:J.content,messageId:X.messageId,dtwMessageID:J.messageId},K=Z.slice(0,Y+1);return K[Q]=V,K}function Eg(J){if(!J||J.length===0)return;return J.map((Z)=>({...Z,queuedMessage:{...Z.queuedMessage,content:Z.queuedMessage.content.map((Q)=>({...Q}))}}))}function dG4(J){let Z=J.queuedMessage,Q=Z.content.map((Y)=>({...Y}));return{id:J.id,interrupt:J.interrupt,queuedMessage:{role:"user",content:Q,userState:Z.userState,meta:Z.createdAt?{sentAt:Date.parse(Z.createdAt)}:void 0,messageId:-1,dtwMessageID:J.id}}}function g_5(J){if(J.type==="queued_messages")return{type:"queued_messages",messages:J.messages.map((Z)=>dG4(Z))};if(J.type==="queued_message_added")return{type:"queued_message_added",message:dG4(J.message)};return{type:"queued_message_removed",queuedMessageId:J.queuedMessageId}}function p_5(J,Z){let Q=g_5(Z);return Vx0(Eg(J)??[],Q,{dedupeAdded:!0})}function d_5(J,Z){return{baseURL:J.workerUrl??Q$(J.ampURL),threadId:Z.threadId,wsToken:Z.wsToken,wsTokenProvider:async()=>u90(Z.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL}),WebSocketClass:WebSocket,maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000}}class x90{threadSubject;agentLoopStateSubject=new Z4("idle");editErrorSubject=new s1;deltaState={streamingMessageId:null,streamingBlocks:[],completedMessages:[]};toolProgressByToolUseIDSubject=new Z4(new Map);toolProgressSubject=new s1;subscriptions=[];threadVersion;messages;queuedMessages;relationships;threadTitle;processedIds;agentLoopState="idle";toolProgressByToolUseID=new Map;contextWindowRatio=null;compactionStateSubject=new Z4("idle");compactionState="idle";lastConnectionState="disconnected";lastConnectionInfo=null;transport;threadId;constructor(J,Z,Q,Y){this.threadId=J.id,this.threadTitle=J.title,this.messages=[...J.messages],this.queuedMessages=Eg(J.queuedMessages)??[],this.relationships=J.relationships??[],this.processedIds=Q,this.transport=Z,this.threadVersion=Y,this.threadSubject=new Z4(J)}static async create(J){let Z=await u90(J.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL,executorType:J.executorType}),Q=await pG4(Z.threadId,J.configService,J.apiKey),Y=Q;if(!Z.usesDtw){J.onLegacyImportStateChange?.("importing");try{await __5(Q,J.configService,J.apiKey,{ampURL:J.ampURL,workerURL:J.workerUrl}),await S_5(Z.threadId,J.configService,J.apiKey),Y=await pG4(Z.threadId,J.configService,J.apiKey)}finally{J.onLegacyImportStateChange?.("idle")}}let{messages:X,processedIds:V}=v_5(Y),K={...Y,id:Z.threadId,messages:X,queuedMessages:Eg(Y.queuedMessages),relationships:Y.relationships?[...Y.relationships]:void 0},z=new XH(d_5(J,Z)),G=new x90(K,z,V,Y.v);try{return await G.connect(),G}catch(F){throw G.dispose(),F}}threadChanges(){return this.threadSubject}agentLoopStateChanges(){return this.agentLoopStateSubject}toolProgressByToolUseIDChanges(){return this.toolProgressByToolUseIDSubject}toolProgressChanges(){return this.toolProgressSubject}editErrors(){return this.editErrorSubject}getThread(){return this.threadSubject.getValue()}getAgentLoopState(){return this.agentLoopState}getConnectionInfo(){return this.lastConnectionInfo?{...this.lastConnectionInfo}:null}getContextWindowRatio(){return this.contextWindowRatio}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)}emitThread(){let J=this.threadSubject.getValue(),Z=y_5(this.deltaState.streamingMessageId,this.deltaState.streamingBlocks,this.messages.length,this.deltaState.streamingParentToolCallId),Y=Z?[...this.messages,Z]:[...this.messages],X=Y.reduce((K,z)=>Math.max(K,z.messageId),-1)+1,V={...J,id:this.threadId,v:this.threadVersion,title:this.threadTitle,messages:Y,queuedMessages:this.queuedMessages.length>0?Eg(this.queuedMessages):void 0,relationships:this.relationships.length>0?[...this.relationships]:void 0,nextMessageId:Math.max(X,0)};this.threadSubject.next(V)}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)}runTransportHandler(J,Z){try{Z()}catch(Q){let Y=Q instanceof Error?Q.message:String(Q);j.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.lastConnectionInfo,Q=J.state!==this.lastConnectionState,Y=Z!==null&&(J.role!==Z.role||J.clientId!==Z.clientId);if(!Q&&!Y)return;if(Q)this.logConnectionStateTransition(this.lastConnectionState,J);else if(Y&&Z)this.logConnectionRoleTransition(Z,J);let X=J.state;if(X==="connected"&&this.lastConnectionState!=="connected")this.transport.resumeFromVersion(this.threadVersion);this.lastConnectionState=X,this.lastConnectionInfo={...J}})}}),this.transport.errors().subscribe({next:(J)=>{this.runTransportHandler("errors",()=>{let Z=J.code==="PARSE_ERROR"?$x0(J.message):null;if(j.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(J.usage?.contextWindowRatio!==void 0){let Z=J.usage.contextWindowRatio;this.contextWindowRatio=Number.isFinite(Z)&&Z>=0&&Z<=1?Z:null}if(f_5(J,this.deltaState),J.role==="user"&&(J.state==="complete"||J.state==="error")&&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=b_5(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=x_5(J.progress);if(Q===void 0){if(this.toolProgressByToolUseID.delete(Z))this.emitToolProgress();return}if(this.toolProgressByToolUseID.get(Z)===Q)return;this.toolProgressByToolUseID.set(Z,Q),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",()=>{if(this.messages=h_5(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.threadVersion=Math.max(this.threadVersion,J.seq),this.emitThread()})}}),this.transport.messageEdited().subscribe({next:(J)=>{this.runTransportHandler("messageEdited",()=>{this.messages=m_5(J,this.messages),this.processedIds=k_5(this.messages),this.threadVersion=Math.max(this.threadVersion,J.seq),this.emitThread()})}}),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.threadVersion=Math.max(this.threadVersion,J.seq),this.emitThread()})}}),this.transport.queuedMessages().subscribe({next:(J)=>{this.runTransportHandler("queuedMessages",()=>{this.queuedMessages=p_5(this.queuedMessages,J),this.emitThread()})}}))}logConnectionStateTransition(J,Z){let Q={threadId:this.threadId,from:J,to:Z.state,role:Z.role,clientId:Z.clientId,transportThreadId:Z.threadId,threadVersion:this.threadVersion};if(Z.state==="connected"){if(J==="reconnecting"){j.info("[dtw] Transport reconnected",Q);return}j.info("[dtw] Transport connected",Q);return}if(Z.state==="reconnecting"){j.warn("[dtw] Transport reconnecting",Q);return}if(Z.state==="disconnected"){j.warn("[dtw] Transport disconnected",Q);return}j.info("[dtw] Transport state changed",Q)}logConnectionRoleTransition(J,Z){j.info("[dtw] Transport role changed",{threadId:this.threadId,state:Z.state,fromRole:J.role,toRole:Z.role,fromClientId:J.clientId,toClientId:Z.clientId,transportThreadId:Z.threadId,threadVersion:this.threadVersion})}async connect(){this.subscribeToTransport(),await this.transport.connect(),this.emitThread()}sendUserMessage(J,Z,Q){return this.setAgentMode(Z),this.transport.sendUserMessage(J,Z,{userState:Q})}interruptQueuedMessage(J){this.transport.interruptQueuedMessage(J)}discardQueuedMessages(){let J=Eg(this.queuedMessages);if(this.queuedMessages.length===0)return;let Z=this.queuedMessages.map((Q)=>Q.id);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.compactionStateSubject.complete(),this.agentLoopStateSubject.complete(),this.toolProgressByToolUseIDSubject.complete(),this.toolProgressSubject.complete(),this.transport.dispose()}}h0();i5();d9();h$();K00();_4();bF();bv0();N4();H1();v$();function c_5(J){let Z=-1;for(let V=J.messages.length-1;V>=0;V--)if(J.messages[V]?.role==="assistant"){Z=V;break}if(Z<0)return{running:0,blocked:0};let Q=J.messages[Z];if(!Q)return{running:0,blocked:0};let Y=new Map;for(let V of J.messages.slice(Z+1)){if(V.role!=="user")continue;for(let K of V.content)if(K.type==="tool_result")Y.set(K.toolUseID,K.run)}let X=0;for(let V of Q.content){if(V.type!=="tool_use")continue;let K=Y.get(V.id);if(!K||!M8(K))X++}return{running:X,blocked:0}}function l_5(J){let Z=J.messages.at(-1);if(!Z)return"user-message-initial";if(Z.role==="assistant")return Z.state.type==="complete"&&Z.state.stopReason==="end_turn"?"user-message-reply":!1;return!1}function i_5(J){let Z=l_5(J);if(Z)return Z;return!1}function vf0(J,Z,Q={files:[]},Y=void 0){let X=c_5(J),V=Z==="awaiting_approval"?1:0;if(Z==="working"||Z==="streaming")return{state:"active",inferenceState:"running",fileChanges:Q,ephemeralError:Y,interactionState:!1,toolState:{running:0,blocked:0}};if(Z==="tool_use"||Z==="running_tools"){let K=X.running;return{state:"active",inferenceState:"idle",fileChanges:Q,ephemeralError:Y,interactionState:K>0?"tool-running":!1,toolState:{running:K,blocked:V}}}if(Z==="awaiting_approval")return{state:"active",inferenceState:"idle",fileChanges:Q,ephemeralError:Y,interactionState:"user-tool-approval",toolState:{running:X.running,blocked:V}};return{state:"active",inferenceState:"idle",fileChanges:Q,ephemeralError:Y,interactionState:i_5(J),toolState:{running:X.running,blocked:V}}}_4();class kf0{authoritativeThread;currentAgentLoopState;pendingMessageSubmits=[];pendingQueuedSubmits=[];pendingQueuedInterruptMessageIDs=new Set;pendingEdit;constructor(J,Z){this.authoritativeThread=J,this.currentAgentLoopState=Z}setAgentLoopState(J){this.currentAgentLoopState=J}optimisticUpdate(J){switch(J.type){case"submit":return this.optimisticSubmit(J);case"discard-queued":return this.pendingQueuedSubmits=[],this.pendingQueuedInterruptMessageIDs.clear(),this.buildProjection();case"interrupt-queued":return this.optimisticInterruptQueued(J);case"edit":return this.optimisticEdit(J)}}optimisticInterruptQueued(J){let Z=this.buildProjection(),Q=(Z.queuedMessages??[]).find((Y)=>Y.id===J.queuedMessageID);if(!Q||yf0(Q))return Z;if(this.pendingQueuedInterruptMessageIDs.has(J.queuedMessageID))return this.buildProjection();return this.pendingQueuedInterruptMessageIDs.add(J.queuedMessageID),this.buildProjection()}optimisticSubmit(J){if(YS5(this.pendingMessageSubmits,this.pendingQueuedSubmits,this.authoritativeThread,J.clientMessageID))return this.buildProjection();let Z={clientMessageID:J.clientMessageID,content:J.content,userState:J.userState,sentAt:J.sentAt??Date.now()};if(DS5(this.currentAgentLoopState))this.pendingQueuedSubmits.push(Z);else this.pendingMessageSubmits.push(Z);return this.buildProjection()}optimisticEdit(J){let Z=this.buildProjection(),Q=Gw0(Z,J.targetMessageID);if(Q<0)return Z;return this.pendingMessageSubmits=[],this.pendingQueuedSubmits=[],this.pendingEdit={targetMessageID:J.targetMessageID,content:J.content,truncatedMessageIDs:JS5(Z,Q)},this.buildProjection()}resolve(J){if(!this.hasPendingOverlay())return this.authoritativeThread=J,J;let Z=this.authoritativeThread;return this.authoritativeThread=J,this.reconcilePending(Z),this.buildProjection()}hasPendingOverlay(){return a_5(this.pendingMessageSubmits,this.pendingQueuedSubmits,this.pendingQueuedInterruptMessageIDs,this.pendingEdit)}reconcilePending(J){let Z=$S5(this.authoritativeThread);this.pendingMessageSubmits=XS5(J,this.authoritativeThread,Z,this.pendingMessageSubmits),this.pendingQueuedSubmits=GS5(this.authoritativeThread,Z,this.pendingQueuedSubmits),this.pendingQueuedInterruptMessageIDs=FS5(this.authoritativeThread,this.pendingQueuedSubmits,this.pendingQueuedInterruptMessageIDs),this.pendingEdit=US5(Z,this.pendingEdit)}buildProjection(){if(!this.hasPendingOverlay())return this.authoritativeThread;let J=this.pendingEdit;return n_5(this.authoritativeThread,(Z)=>o_5(Z,J),(Z)=>r_5(Z,this.pendingMessageSubmits),(Z)=>s_5(Z,this.pendingQueuedSubmits),(Z)=>t_5(Z,this.pendingQueuedInterruptMessageIDs))}}function n_5(J,...Z){return Z.reduce((Q,Y)=>Y?Y(Q):Q,J)}function a_5(J,Z,Q,Y){return J.length>0||Z.length>0||Q.size>0||Y!==void 0}function o_5(J,Z){if(!Z)return J;let Q=_I1(J,Z.targetMessageID);if(!Q)return J;let{index:Y,message:X}=Q,V=J.messages.slice(0,Y+1);return V[Y]={...X,content:Z.content},{...J,messages:V,nextMessageId:zw0({messages:V,nextMessageId:J.nextMessageId})}}function r_5(J,Z){if(Z.length===0)return J;let Q=zw0(J),Y=Z.map((X,V)=>iG4(X,Q+V));return{...J,messages:[...J.messages,...Y],nextMessageId:Math.max(J.nextMessageId??0,Q+Y.length)}}function s_5(J,Z){if(Z.length===0)return J;let Q=Z.map(e_5);return{...J,queuedMessages:[...J.queuedMessages??[],...Q]}}function t_5(J,Z){if(Z.size===0||!J.queuedMessages?.length)return J;let Q=!1,Y=J.queuedMessages.map((X)=>{if(!Z.has(X.id)||yf0(X))return X;return Q=!0,{...X,interrupt:!0}});if(!Q)return J;return{...J,queuedMessages:Y}}function iG4(J,Z){return{role:"user",content:J.content,userState:J.userState,meta:{sentAt:J.sentAt},messageId:Z,dtwMessageID:J.clientMessageID}}function e_5(J){return{id:J.clientMessageID,queuedMessage:iG4(J,-1)}}function $S5(J){let Z=new Set,Q=new Set,Y=new Map,X=new Set;for(let V of J.messages)if(typeof V.dtwMessageID==="string"){if(X.add(V.dtwMessageID),V.role==="user")Z.add(V.dtwMessageID),Y.set(V.dtwMessageID,V)}for(let V of J.queuedMessages??[])Q.add(V.id);return{userMessageIDs:Z,queuedMessageIDs:Q,userMessagesByID:Y,messageIDsInTimeline:X}}function JS5(J,Z){return J.messages.slice(Z+1).map((Q)=>Q.dtwMessageID).filter((Q)=>typeof Q==="string")}function ZS5(J,Z){return J.messages.some((Q)=>Q.role==="user"&&Q.dtwMessageID===Z)}function QS5(J,Z){return(J.queuedMessages??[]).some((Q)=>Q.id===Z)}function yf0(J){return"interrupt"in J&&J.interrupt===!0}function YS5(J,Z,Q,Y){return J.some((X)=>X.clientMessageID===Y)||Z.some((X)=>X.clientMessageID===Y)||ZS5(Q,Y)||QS5(Q,Y)}function XS5(J,Z,Q,Y){if(Y.length===0)return[];let{unmatchedPendingSubmits:X,acknowledgedByID:V}=VS5(Y,Q.userMessageIDs);if(X.length===0)return[];let K=KS5(J,Z);if(!K)return X;let z=zS5(K,V,X.length);return X.slice(z)}function VS5(J,Z){let Q=new Set,Y=[];for(let X of J){if(Z.has(X.clientMessageID)){Q.add(X.clientMessageID);continue}Y.push(X)}return{unmatchedPendingSubmits:Y,acknowledgedByID:Q}}function KS5(J,Z){let Q=lG4(J),Y=lG4(Z);if(!(Q.length<=Y.length&&Q.every((V,K)=>V.dtwMessageID===Y[K]?.dtwMessageID)))return;return Y.slice(Q.length)}function zS5(J,Z,Q){let Y=0;for(let X of J){if(typeof X.dtwMessageID==="string"&&Z.has(X.dtwMessageID))continue;if(Y++,Y===Q)return Y}return Y}function lG4(J){return J.messages.filter((Z)=>Z.role==="user")}function GS5(J,Z,Q){if(Q.length===0)return[];let Y=[...J.queuedMessages??[]];return Q.filter((X)=>{if(Z.queuedMessageIDs.has(X.clientMessageID)||Z.userMessageIDs.has(X.clientMessageID))return!1;let V=Y.findIndex((K)=>Fw0(X.content,K.queuedMessage.content));if(V>=0)return Y.splice(V,1),!1;return!0})}function FS5(J,Z,Q){if(Q.size===0)return new Set;let Y=new Map((J.queuedMessages??[]).map((K)=>[K.id,K])),X=new Set(Z.map((K)=>K.clientMessageID)),V=new Set;for(let K of Q){let z=Y.get(K);if(!z){if(X.has(K))V.add(K);continue}if(yf0(z))continue;V.add(K)}return V}function US5(J,Z){if(!Z)return;return qS5(J,Z)?void 0:Z}function qS5(J,Z){let Q=J.userMessagesByID.get(Z.targetMessageID);if(!Q)return!1;if(!Fw0(Q.content,Z.content))return!1;return Z.truncatedMessageIDs.every((X)=>!J.messageIDsInTimeline.has(X))}function DS5(J){return WS5.has(J)}var WS5=new Set(["working","streaming","tool_use","running_tools","awaiting_approval"]);class uf0{threadWriter;deps;thread$;threadViewState$;inferenceErrors$;toolProgressByToolUseID$;pendingApprovals$;provider;threadSubject;threadViewStateSubject;transportSubscriptions=[];clientID=`cli-tui-${crypto.randomUUID()}`;toolRunner;handshakeManager;optimisticThreadProjection;settingsSyncSubscription=null;lastSentSettingsJSON="";pendingApprovalsSubject=new Z4([]);pendingSkillsSubject=new Z4([]);inferenceErrorsSubject=new s1;pendingSkills$=this.pendingSkillsSubject;fileChanges={files:[]};activeError=null;retryCountdownTimer=null;advertisedExecutorTools=[];handoffService;providerSubscriptions=null;constructor(J,Z,Q){this.threadWriter=Z;this.deps=Q;this.provider=J;let Y=uH0("info"),X=uH0("error");this.toolRunner=new im({clientID:this.clientID,transport:this.provider.transport,executeBuiltinTool:()=>null,invokeTool:(G)=>this.invokeToolForLease(G),batchGuidanceFiles:f80,renderToolRunError:Zf,log:{info:(G,F)=>Y(G,F),error:(G,F)=>X(G,{error:F}),wsMessage:(G,F,U)=>{j.debug("DTW executor tool runner message",{direction:G,clientID:F,...typeof U==="object"&&U!==null?U:{message:U}})}}}),this.handshakeManager=this.createHandshakeManager();let V=J.getThread();this.optimisticThreadProjection=new kf0(V,J.getAgentLoopState());let K=this.optimisticThreadProjection.resolve(V),z=vf0(K,J.getAgentLoopState(),this.fileChanges,this.currentEphemeralError());this.threadSubject=new Z4(K),this.thread$=this.threadSubject,this.threadViewStateSubject=new Z4(z),this.threadViewState$=this.threadViewStateSubject,this.inferenceErrors$=this.inferenceErrorsSubject,this.toolProgressByToolUseID$=this.provider.toolProgressByToolUseIDChanges().pipe(D1(v90)),this.pendingApprovals$=this.pendingApprovalsSubject,this.refreshProviderFileChanges(),this.attachTransportHandlers(),this.handshakeManager.ensureHandshake("connect"),this.handoffService=Q.handoffService}startProviderSubscription(J){this.providerSubscriptions?.unsubscribe();let Z=this.provider.threadChanges().subscribe({next:(Y)=>{J(Y),this.refreshProviderFileChanges(),this.updateThreadViewStateFromProvider()}}),Q=this.provider.agentLoopStateChanges().subscribe({next:(Y)=>{if(this.optimisticThreadProjection.setAgentLoopState(Y),Y==="error")this.inferenceErrorsSubject.next(Error("Agent failed to complete the request."));this.updateThreadViewStateFromProvider()}});this.providerSubscriptions={unsubscribe:()=>{Z.unsubscribe(),Q.unsubscribe()}}}writeThread(J){this.threadWriter.write(J),this.threadSubject.next(J)}providerThread(){return this.provider.getThread()}resolveAuthoritativeThread(J){return this.optimisticThreadProjection.resolve(J)}getThreadViewState(){return this.threadViewStateSubject.getValue()}getResolvedTokenUsage(){let J=K2(this.thread$.getValue());if(J)return J;let Z=this.provider.getContextWindowRatio();if(Z===null)return;return{maxInputTokens:1,inputTokens:Z,outputTokens:0,cacheCreationInputTokens:0,cacheReadInputTokens:0,totalInputTokens:Z}}async dispose(){this.providerSubscriptions?.unsubscribe(),this.providerSubscriptions=null;for(let J of this.transportSubscriptions)J.unsubscribe();this.transportSubscriptions.length=0,this.clearRetryCountdownTimer(),this.settingsSyncSubscription?.unsubscribe(),this.settingsSyncSubscription=null,this.handshakeManager.dispose(),this.toolRunner.dispose(),this.provider.dispose(),await this.threadWriter.asyncDispose(),this.threadSubject.complete(),this.threadViewStateSubject.complete(),this.inferenceErrorsSubject.complete(),this.pendingApprovalsSubject.complete(),this.pendingSkillsSubject.complete()}async sendMessage(J){await this.handshakeManager.ensureReady();let Z=this.thread$.getValue();if(J.editIndex!==void 0){let K=Z.messages[J.editIndex];if(!K||K.role!=="user"||!K.dtwMessageID)throw Error("Unable to edit message: missing DTW message ID");let z=Z.messages.findIndex((U)=>U.role==="user");if(J.editIndex===z&&J.agentMode&&Z.agentMode!==J.agentMode)this.provider.setAgentMode(J.agentMode,{overwrite:!0}),this.updateThread((U)=>{U.agentMode=J.agentMode});this.provider.transport.editUserMessage(K.dtwMessageID,J.content,cu0(),J.agentMode);let F=this.optimisticThreadProjection.optimisticUpdate({type:"edit",targetMessageID:K.dtwMessageID,content:J.content});this.writeThread(F);return}if(!Z.messages.some((K)=>K.role==="user")&&!Z.agentMode&&J.agentMode)this.updateThread((K)=>{K.agentMode=J.agentMode});let Y=await this.collectUserState(),X=this.provider.sendUserMessage(J.content,J.agentMode,Y),V=this.optimisticThreadProjection.optimisticUpdate({type:"submit",clientMessageID:X,content:J.content,userState:Y});this.writeThread(V)}async restoreTo(J){await this.handshakeManager.ensureReady();let Y=[...this.thread$.getValue().messages.slice(0,J+1)].reverse().find((K)=>K.role==="user");if(!Y?.dtwMessageID)throw Error("Unable to edit message: missing DTW message ID");let X=Y.content.filter((K)=>K.type==="text"||K.type==="image").map((K)=>{if(K.type==="image")return{...K,source:{...K.source}};return{...K}});if(X.length===0)throw Error("Unable to edit message: no editable content found");this.provider.transport.editUserMessage(Y.dtwMessageID,X,cu0());let V=this.optimisticThreadProjection.optimisticUpdate({type:"edit",targetMessageID:Y.dtwMessageID,content:X});this.writeThread(V)}async queueMessage(J){await this.handshakeManager.ensureReady();let Z=await this.collectUserState(),Q=this.provider.sendUserMessage(J,void 0,Z),Y=this.optimisticThreadProjection.optimisticUpdate({type:"submit",clientMessageID:Q,content:J,userState:Z});this.writeThread(Y)}async discardQueuedMessages(){let J=this.optimisticThreadProjection.optimisticUpdate({type:"discard-queued"});this.writeThread(J),this.provider.discardQueuedMessages()}async interruptQueuedMessage(J){await this.handshakeManager.ensureReady(),this.provider.interruptQueuedMessage(J);let Z=this.optimisticThreadProjection.optimisticUpdate({type:"interrupt-queued",queuedMessageID:J});this.writeThread(Z)}async setVisibility(J){let Z=await A6.setThreadMeta({thread:this.provider.threadId,meta:yV(J)},{config:this.deps.configService});if(!Z.ok)throw Error(Z.error.code)}updateThread(J){let Z=this.threadWriter.update(J),Q=this.optimisticThreadProjection.resolve(Z);if(Q!==Z)this.threadWriter.write(Q);this.threadSubject.next(Q)}async cancelTurn(){this.provider.transport.cancelAgentLoop()}async cancelStreaming(){this.provider.transport.cancelAgentLoop()}async retryTurn(){this.provider.transport.retryAgentLoop()}invokeBashTool(J,Z){let Q=lY4();return new v0((Y)=>{let X=!1,V=null,K=(U)=>{this.provider.transport.appendManualBashInvocation({args:J,run:U,hidden:Z.hidden})},z=(U,q={emitRun:!0})=>{if(X)return;if(X=!0,K(U),q.emitRun)Y.next(U);Y.complete()},G=(U)=>U instanceof Error?U.message:String(U),F=()=>{V?.unsubscribe(),z({status:"cancelled",reason:"User canceled"})};return Z.abortController.signal.addEventListener("abort",F),(async()=>{try{let U=await LU({toolName:C6,threadSnapshot:this.provider.getThread(),dtwArtifactSyncService:this.createDTWArtifactSyncService(),configService:this.deps.configService,toolService:this.deps.toolService,mcpService:this.deps.mcpService,skillService:this.deps.skillService,fsTracker:this.deps.fs,toolUseID:Q,discoveredGuidanceFileURIs:this.toolRunner.discoveredGuidanceFileURIs});if(X)return;Y.next({status:"in-progress"}),V=this.deps.toolService.invokeTool(C6,{args:J},U).subscribe({next:(q)=>{if(X)return;if(Y.next(q),q.status!=="in-progress")z(q,{emitRun:!1})},error:(q)=>{z({status:"error",error:{message:G(q)}})}})}catch(U){z({status:"error",error:{message:G(U)}})}})(),()=>{V?.unsubscribe(),Z.abortController.signal.removeEventListener("abort",F)}})}dismissEphemeralError(){this.activeError=null,this.clearRetryCountdownTimer(),this.updateThreadViewStateFromProvider()}async resolveApproval(J,Z,Q){let Y=z8.safeParse(J);if(!Y.success)return;this.provider.transport.resolveToolApproval(Y.data,Z)}addPendingSkill(J){this.pendingSkillsSubject.next([...this.pendingSkillsSubject.getValue(),J])}removePendingSkill(J){this.pendingSkillsSubject.next(this.pendingSkillsSubject.getValue().filter((Z)=>Z.name!==J))}clearPendingSkills(){this.pendingSkillsSubject.next([])}async clearPendingNavigation(){}async getGuidanceFiles(J){let Z=this.thread$.getValue();return(await Zz({filesystem:this.deps.filesystem,configService:this.deps.configService,threadService:this.deps.threadService},Z,J)).map((Y)=>({uri:Y.uri,type:Y.type}))}async getFilesAffectedByTruncation(J){let Z=this.thread$.getValue(),Q=await this.getToolUsesToRevert(Z,J);return Q.size>0?this.deps.fs.tracker.getFilesForToolUses(Q):[]}async getToolUsesToRevert(J,Z){let Q=new Set;J.messages.slice(0,Z).forEach((V)=>{if(V.role==="user"){for(let K of V.content)if(K.type==="tool_result")Q.add(K.toolUseID)}else for(let K of V.content)if(K.type==="tool_use")Q.add(K.id)});let Y=new Set,X=await this.deps.fs.tracker.getAllRecords();for(let[V]of X.entries())if(!Q.has(V))Y.add(V);return Y}async collectUserState(){try{return await r50()??$f}catch(J){return j.warn("Failed to collect IDE user state for DTW message",{error:J}),$f}}createHandshakeManager(){return new lm({handshake:(J)=>this.sendExecutorHandshake(J),onError:({error:J,attempt:Z,delayMs:Q})=>{j.warn("DTW executor handshake failed",{error:J,attempt:Z,delayMs:Q})},onExhausted:(J)=>{this.handleHandshakeExhausted(J)}})}handleHandshakeExhausted(J){j.error("DTW executor handshake exhausted",J)}syncApprovalRequests(J){let Z=this.provider.threadId;if(!Z){this.pendingApprovalsSubject.next([]);return}let Q=J.filter((X)=>X.threadId===Z||X.mainThreadId===Z);this.pendingApprovalsSubject.next(Q);let Y=new Set(Q.map(dE));for(let X of[...this.toolRunner.sentApprovalRequests])if(!Y.has(X))this.toolRunner.sentApprovalRequests.delete(X);for(let X of Q){let V=dE(X);if(this.toolRunner.sentApprovalRequests.has(V))continue;let K=y80(X);this.provider.transport.sendExecutorToolApprovalRequest(K),this.toolRunner.sentApprovalRequests.add(V)}}handleExecutorToolApprovalResponse(J){this.deps.toolService.resolveApproval(J.toolCallId,J.accepted)}syncExecutorTools(J){let Z=this.provider.transport.getConnectionInfo();if(Z.state!=="connected"||Z.role!=="executor")return;this.advertisedExecutorTools=dm({transport:this.provider.transport,nextTools:J,previouslyAdvertisedTools:this.advertisedExecutorTools})}attachTransportHandlers(){this.transportSubscriptions.push(this.provider.transport.connectionChanges().subscribe({next:(J)=>{this.handshakeManager.handleConnectionChange(J)}}),this.provider.compactionStateChanges().subscribe({next:()=>{this.updateThreadViewStateFromProvider()}}),this.provider.transport.errorEvents().subscribe({next:(J)=>{if(this.activeError=J.type==="error_set"?J.error:null,J.type==="error_set")this.inferenceErrorsSubject.next(J.error);this.syncRetryCountdownTimer(),this.updateThreadViewStateFromProvider()}}),this.provider.transport.errors().subscribe({next:(J)=>{this.inferenceErrorsSubject.next(Error(J.message))}}),this.provider.transport.cancelledEvents().subscribe({next:()=>{this.activeError=null,this.clearRetryCountdownTimer(),this.updateThreadViewStateFromProvider()}}),this.provider.transport.toolLeases().subscribe({next:(J)=>{this.toolRunner.handleToolLease(J)}}),this.provider.transport.toolLeaseRevoked().subscribe({next:(J)=>{this.toolRunner.handleToolRevocation(J)}}),this.provider.transport.executorRollbackRequests().subscribe({next:(J)=>{this.handleRollbackRequest(J).catch(()=>{return})}}),this.provider.transport.fileSystemReadDirectoryRequests().subscribe({next:(J)=>{this.handleFileSystemReadDirectoryRequest(J).catch(()=>{return})}}),this.provider.transport.fileSystemReadFileRequests().subscribe({next:(J)=>{this.handleFileSystemReadFileRequest(J).catch(()=>{return})}}),this.provider.transport.executorToolApprovalResponses().subscribe({next:(J)=>{this.handleExecutorToolApprovalResponse(J)}}),this.deps.toolService.tools.subscribe({next:(J)=>{this.syncExecutorTools(_C(J))}}),this.deps.toolService.pendingApprovals$.subscribe((J)=>{this.syncApprovalRequests(J)}))}async sendExecutorHandshake(J){j.debug("DTW executor handshake",{trigger:J,threadID:this.provider.threadId}),this.settingsSyncSubscription?.unsubscribe(),this.settingsSyncSubscription=null;let{advertisedTools:Z}=await b80({transport:this.provider.transport,executorClientID:this.clientID,workspaceRoot:process.cwd(),threadId:this.provider.threadId,resumeFromVersion:this.provider.getThread().v,configService:this.deps.configService,toolService:this.deps.toolService,skillService:this.deps.skillService,sendGitSnapshot:!1,executorType:"local-client",previouslyAdvertisedTools:this.advertisedExecutorTools,initialToolDiscovery:this.deps.initialToolDiscovery});this.advertisedExecutorTools=Z,this.applyLocalEnvironment(),this.settingsSyncSubscription=this.deps.configService.config.subscribe({next:(Q)=>{this.lastSentSettingsJSON=h80(this.provider.transport,Q,this.lastSentSettingsJSON)}})}async applyLocalEnvironment(){try{let J=await $J();this.provider.setEnvironment({initial:J})}catch(J){j.debug("Failed to apply local environment",{error:J})}}createDTWArtifactSyncService(){return{upsertArtifact:(J,Z)=>{let Q=z8.safeParse(Z);this.provider.transport.sendExecutorArtifactUpsert(J,Q.success?Q.data:void 0)},deleteArtifact:(J)=>{this.provider.transport.sendExecutorArtifactDelete(J)}}}async invokeToolForLease(J){let Z=typeof J.args==="object"&&J.args!==null?J.args:{},Q=await LU({toolName:J.toolName,threadSnapshot:this.provider.getThread(),dtwHandoffService:this.handoffService,dtwArtifactSyncService:this.createDTWArtifactSyncService(),configService:this.deps.configService,toolService:this.deps.toolService,mcpService:this.deps.mcpService,skillService:this.deps.skillService,fsTracker:this.deps.fs,toolUseID:J.toolCallId,discoveredGuidanceFileURIs:this.toolRunner.discoveredGuidanceFileURIs});return this.deps.toolService.invokeTool(J.toolName,{args:Z},Q)}async handleRollbackRequest(J){await this.toolRunner.handleRollbackRequest(J.editId,J.toolUseIdsToRevert,(Z)=>this.deps.fs.tracker.revertChanges(Z)),await this.refreshProviderFileChanges(),this.updateThreadViewStateFromProvider()}async handleFileSystemReadDirectoryRequest(J){let Z=await g80({fileSystem:this.deps.filesystem,workspaceRoot:process.cwd()},J.uri);this.provider.transport.sendExecutorFileSystemReadDirectoryResult(J.requestId,Z)}async handleFileSystemReadFileRequest(J){let Z=await p80({fileSystem:this.deps.filesystem,workspaceRoot:process.cwd()},J.uri);this.provider.transport.sendExecutorFileSystemReadFileResult(J.requestId,Z)}async refreshProviderFileChanges(){this.fileChanges={files:await V00(this.deps.fs.tracker)},this.updateThreadViewStateFromProvider()}updateThreadViewStateFromProvider(){this.threadViewStateSubject.next(vf0(this.threadSubject.getValue(),this.provider.getAgentLoopState(),this.fileChanges,this.currentEphemeralError())),this.deps.onThreadViewStateChange()}syncRetryCountdownTimer(){let J=this.activeError?.retryAt;if(J===void 0||J<=Date.now()){this.clearRetryCountdownTimer();return}if(this.retryCountdownTimer!==null)return;this.retryCountdownTimer=setInterval(()=>{let Z=this.activeError?.retryAt;if(Z===void 0){this.clearRetryCountdownTimer();return}if(this.updateThreadViewStateFromProvider(),Z<=Date.now())this.clearRetryCountdownTimer()},1000)}clearRetryCountdownTimer(){if(this.retryCountdownTimer===null)return;clearInterval(this.retryCountdownTimer),this.retryCountdownTimer=null}currentEphemeralError(){if(!this.activeError)return;let J=this.activeError.retryAt!==void 0?Math.max(0,Math.ceil((this.activeError.retryAt-Date.now())/1000)):void 0,Z=this.activeError.code!==void 0||this.activeError.attempt!==void 0?{code:this.activeError.code,attempt:this.activeError.attempt}:void 0;return{message:this.activeError.message,stack:this.activeError.stack,error:Z,retryCountdownSeconds:J}}}var f90="Loading thread...",HS5="Importing thread";class Lg{deps;recentThreadIDsSubject=new Z4([]);threadTitlesSubject=new Z4({});activeThreadHandleSubject=new Z4(null);allConnectedThreadActivityStatusesSubject=new Z4({});initializationStatusSubject=new Z4({pending:!1,message:f90});threadHandleMap=new Map;draftsByThreadIDSubject=new Z4(new Map);pendingRelationships=new Map;isThreadActivationInProgress=!1;activeThreadContextID;handoffService;queueOnSubmitByDefault=!0;constructor(J){this.deps=J;this.handoffService=nm({configService:this.deps.configService,onFollow:this.followHandoffIfSourceActive})}get recentThreadIDs$(){return this.recentThreadIDsSubject}get threadTitles$(){return this.threadTitlesSubject}get drafts$(){return this.draftsByThreadIDSubject}get threadHandles$(){return this.activeThreadHandleSubject}get allConnectedThreadActivityStatuses$(){return this.allConnectedThreadActivityStatusesSubject}get initializationStatus$(){return this.initializationStatusSubject}get activeThreadHandle(){let J=this.threadHandleMap.get(this.activeThreadContextID);if(!J)throw Error(`No thread handle for ${this.activeThreadContextID}`);return J}get activeProvider(){return this.threadHandleMap.get(this.activeThreadContextID)?.provider}hasPendingInitialization(){return this.initializationStatusSubject.getValue().pending}isDTWMode(){return!0}getTransportConnectionState(){return this.activeProvider?.getConnectionInfo()?.state??"disconnected"}getCompactionStatus(){let J=this.activeProvider;if(!J)return;return{compactionState:J.getCompactionState()}}async createThread(J){await this.activateThread(J)}async switchThread(J){await this.activateThread(J)}followHandoffIfSourceActive=async(J)=>{if(this.activeThreadContextID!==J.sourceThreadID)return;await this.switchThread(J.targetThreadID)};async createHandoff(J,Z){let Y=this.threadHandleMap.get(J)?.provider.getThread()??this.activeProvider?.getThread();if(!Y||Y.id!==J)throw Error("No thread available for handoff");let X=Y.env?.initial?.trees?.[0]?.repository?.url??(await this.deps.getThreadEnvironment()).trees?.[0]?.repository?.url,K=await nm({configService:this.deps.configService}).createHandoffDraft({parentThread:Y,goal:Z.goal,images:Z.images,signal:Z.signal});Z.signal?.throwIfAborted();let z=Z.agentMode??K.sourceAgentMode??Y.agentMode,G={threadID:K.parentThreadID,type:"handoff",...K.parentMessageIndex!==void 0?{messageIndex:K.parentMessageIndex}:{},comment:Z.goal},{threadId:F}=await u90(void 0,this.deps.configService,void 0,{repositoryURL:X,agentMode:z??void 0,relationship:G,executorType:"local-client",signal:Z.signal}),U=BS5(K.content);if(U)this.setDraft(F,U);return this.pendingRelationships.set(F,[{threadID:J,type:"handoff",role:"child",...K.parentMessageIndex!==void 0?{messageIndex:K.parentMessageIndex}:{},createdAt:Date.now(),comment:Z.goal}]),F}async dispose(){for(let J of this.threadHandleMap.values())await J.dispose();this.threadHandleMap.clear(),this.draftsByThreadIDSubject.complete(),this.activeThreadHandleSubject.complete(),this.allConnectedThreadActivityStatusesSubject.complete(),this.initializationStatusSubject.complete(),this.threadTitlesSubject.complete(),this.recentThreadIDsSubject.complete()}async activateThread(J){j.info("[dtw-thread-pool] activateThread:start",{requestedThreadID:J,hasExistingHandle:Boolean(J&&this.threadHandleMap.get(J))});let Z=J?this.threadHandleMap.get(J):void 0;if(Z){let Q=Z.thread$.getValue().id;this.activeThreadContextID=Q,this.activeThreadHandleSubject.next(Z),this.addToRecentThreads(Q),this.syncAllConnectedThreadActivityStatuses(),j.info("[dtw-thread-pool] activateThread:reused",{activeThreadID:Q,handleCount:this.threadHandleMap.size});return}this.isThreadActivationInProgress=!0,this.setInitializationStatus({pending:!0,message:f90});try{let Q=await this.createProvider(J),Y=this.pendingRelationships.get(Q.threadId);if(Y)Q.setRelationships(Y),this.pendingRelationships.delete(Q.threadId);let X=await this.deps.threadService.exclusiveSyncReadWriter(Q.threadId),V=tP({fileChangeTrackerStorage:this.deps.fileChangeTrackerStorage},this.deps.osFileSystem,Q.threadId),K=new uf0(Q,X,{configService:this.deps.configService,toolService:this.deps.toolService,skillService:this.deps.skillService,mcpService:this.deps.mcpService,initialToolDiscovery:this.deps.initialToolDiscovery,fs:V,filesystem:this.deps.osFileSystem,threadService:this.deps.threadService,onThreadViewStateChange:()=>{this.syncAllConnectedThreadActivityStatuses()},handoffService:this.handoffService});this.threadHandleMap.set(Q.threadId,K),K.startProviderSubscription((z)=>{this.applyProviderState(Q.threadId,z)}),await this.applyProviderState(Q.threadId,Q.getThread()),this.activeThreadContextID=Q.threadId,this.activeThreadHandleSubject.next(K),this.addToRecentThreads(Q.threadId),j.info("[dtw-thread-pool] activateThread:created",{activeThreadID:Q.threadId,handleCount:this.threadHandleMap.size})}finally{this.isThreadActivationInProgress=!1,this.setInitializationStatus({pending:!1,message:f90})}}async applyProviderState(J,Z){let Q=this.threadHandleMap.get(J);if(!Q)return;let Y=Q.resolveAuthoritativeThread(Z);if(Q.writeThread(Y),await this.deps.threadService.flushVersion(J,Y.v).catch(()=>{return}),this.threadTitlesSubject.next({...this.threadTitlesSubject.getValue(),[J]:Y.title}),W3(Y)>0)this.clearDraftPrompt(J);this.syncAllConnectedThreadActivityStatuses()}setDraft(J,Z){let Q=new Map(this.draftsByThreadIDSubject.getValue());Q.set(J,Z),this.draftsByThreadIDSubject.next(Q)}clearDraftPrompt(J){let Z=new Map(this.draftsByThreadIDSubject.getValue());if(!Z.delete(J))return;this.draftsByThreadIDSubject.next(Z)}syncAllConnectedThreadActivityStatuses(){let J={};for(let[Z,Q]of this.threadHandleMap.entries())J[Z]=Q.getThreadViewState();this.allConnectedThreadActivityStatusesSubject.next(J)}addToRecentThreads(J){let Z=[...this.recentThreadIDsSubject.getValue()],Q=Z.indexOf(J);if(Q!==-1)Z.splice(Q,1);if(Z.unshift(J),Z.length>50)Z.pop();this.recentThreadIDsSubject.next(Z)}async createProvider(J){let Z=J?void 0:(await this.deps.getThreadEnvironment()).trees?.[0]?.repository?.url,Q=J?void 0:"local-client";return x90.create({ampURL:this.deps.ampURL,configService:this.deps.configService,executorType:Q,onLegacyImportStateChange:(Y)=>{if(Y==="importing"){this.setInitializationStatus({pending:!0,message:HS5});return}if(this.isThreadActivationInProgress)this.setInitializationStatus({pending:!0,message:f90})},repositoryURL:Z,threadId:J,workerUrl:process.env.AMP_WORKER_URL})}setInitializationStatus(J){let Z=this.initializationStatusSubject.getValue();if(Z.pending===J.pending&&Z.message===J.message)return;this.initializationStatusSubject.next(J)}}function BS5(J){let Z=J.filter((Y)=>Y.type==="text").map((Y)=>Y.text).join(`
6888
+ `;else if(G.code===9)V+="\t";break;case"csi":if(G.final==="m")K(),Y=I_5(Y,G);break;case"osc":{let F=R_5(G.data);if(F!==null)K(),X=F;break}case"escape":case"dcs":break}}),Z.parse(J),Z.flush(),K(),Q.length===0)return new C("");if(Q.length===1){let G=Q[0];return new C(G.text,G.style,void 0,G.hyperlink)}let z=Q.map((G)=>new C(G.text,G.style,void 0,G.hyperlink));return new C(void 0,void 0,z)}function I_5(J,Z){let Q=j_5(Z.params);if(Q.length===0)Q.push(0);let Y=J;for(let X=0;X<Q.length;X++){let V=Q[X];switch(V){case 0:Y=new h;break;case 1:Y=Y.copyWith({bold:!0});break;case 2:Y=Y.copyWith({dim:!0});break;case 3:Y=Y.copyWith({italic:!0});break;case 4:Y=Y.copyWith({underline:!0});break;case 9:Y=Y.copyWith({strikethrough:!0});break;case 22:Y=Y.copyWith({bold:!1,dim:!1});break;case 23:Y=Y.copyWith({italic:!1});break;case 24:Y=Y.copyWith({underline:!1});break;case 29:Y=Y.copyWith({strikethrough:!1});break;case 30:case 31:case 32:case 33:case 34:case 35:case 36:case 37:Y=Y.copyWith({color:M0.index(V-30)});break;case 38:{let K=hG4(Q,X);if(K.color)Y=Y.copyWith({color:K.color});X=K.nextIndex;break}case 39:Y=Y.copyWith({color:M0.default()});break;case 40:case 41:case 42:case 43:case 44:case 45:case 46:case 47:Y=Y.copyWith({backgroundColor:M0.index(V-40)});break;case 48:{let K=hG4(Q,X);if(K.color)Y=Y.copyWith({backgroundColor:K.color});X=K.nextIndex;break}case 49:Y=Y.copyWith({backgroundColor:M0.default()});break;case 90:case 91:case 92:case 93:case 94:case 95:case 96:case 97:Y=Y.copyWith({color:M0.index(V-90+8)});break;case 100:case 101:case 102:case 103:case 104:case 105:case 106:case 107:Y=Y.copyWith({backgroundColor:M0.index(V-100+8)});break}}return Y}function j_5(J){let Z=[];for(let Q of J)if(Z.push(Q.value),Q.subparams)Z.push(...Q.subparams);return Z}function hG4(J,Z){if(Z+1>=J.length)return{color:null,nextIndex:Z};let Q=J[Z+1];if(Q===2){let Y=Z+2,X=J.length-Y;if(X>=4){let V=J[Y+1]??0,K=J[Y+2]??0,z=J[Y+3]??0;return{color:M0.rgb(V,K,z),nextIndex:Z+5}}else if(X>=3){let V=J[Y]??0,K=J[Y+1]??0,z=J[Y+2]??0;return{color:M0.rgb(V,K,z),nextIndex:Z+4}}return{color:null,nextIndex:Z+1}}else if(Q===5){let Y=Z+2,X=J.length-Y;if(X>=2){let V=J[Y+1]??0;return{color:M0.index(V),nextIndex:Z+4}}else if(X>=1){let V=J[Y]??0;return{color:M0.index(V),nextIndex:Z+2}}return{color:null,nextIndex:Z+1}}return{color:null,nextIndex:Z+1}}function R_5(J){let Z=J.split(";");if(Z.length<2||Z[0]!=="8")return null;let Q=Z[1]??"",Y=Z.slice(2).join(";");if(!Y)return;let X="";if(Q){let V=Q.match(/id=([^:;]+)/);if(V)X=V[1]??""}return{uri:Y,id:X}}function P_5(J){let Z=J.replace(/\r/g,"");if(!Z.includes("\x1B"))return Z;return mG4(Z).toPlainText()}function v90(J){let Z;for(let[Q,Y]of J.entries()){let X=P_5(Y);if(X===Y)continue;if(!Z)Z=new Map(J);Z.set(Q,X)}return Z??J}function k90(J){let Z=J.toolProgressByToolUseID$.pipe(D1(v90));return{get thread$(){return J.thread$},get threadViewState$(){return J.threadViewState$},get inferenceErrors$(){return J.inferenceErrors$},get toolProgressByToolUseID$(){return Z},get pendingApprovals$(){return J.pendingApprovals$},get pendingSkills$(){return J.pendingSkills$},get getResolvedTokenUsage(){return J.getResolvedTokenUsage},sendMessage:J.sendMessage,restoreTo:J.restoreTo,queueMessage:J.queueMessage,discardQueuedMessages:J.discardQueuedMessages,interruptQueuedMessage:J.interruptQueuedMessage,setTitle:J.setTitle,setVisibility:J.setVisibility,cancelTurn:J.cancelTurn,cancelStreaming:J.cancelStreaming,retryTurn:J.retryTurn,dismissEphemeralError:J.dismissEphemeralError,preExecuteMode:J.preExecuteMode,postExecuteMode:J.postExecuteMode,setTestEphemeralError:J.setTestEphemeralError,resolveApproval:J.resolveApproval,addPendingSkill:J.addPendingSkill,removePendingSkill:J.removePendingSkill,clearPendingSkills:J.clearPendingSkills,getFilesAffectedByTruncation:J.getFilesAffectedByTruncation,clearPendingNavigation:J.clearPendingNavigation,getGuidanceFiles:J.getGuidanceFiles,invokeBashTool:J.invokeBashTool}}var gG4="Loading thread...";function C_5(J){return{id:J,created:Date.now(),v:0,messages:[]}}class _f0{placeholderThreadID;recentThreadIDsSubject=new Z4([]);threadTitlesSubject=new Z4({});draftsSubject=new Z4(new Map);threadHandlesSubject;allConnectedThreadActivityStatusesSubject=new Z4({});initializationStatusSubject=new Z4({pending:!0,message:gG4});pendingApprovalsSubject=new Z4([]);pendingSkillsSubject=new Z4([]);attachedPool=null;attachedPoolSubscriptions=[];attached=!1;readyPromise;readyResolve=null;readyReject=null;constructor(J=D3()){this.placeholderThreadID=J;let Z=new Z4(C_5(this.placeholderThreadID)),Q=new Z4(new Map),Y=new Z4(RP(Z.getValue(),{state:"active",inferenceState:"idle",fileChanges:{files:[]}}));this.threadHandlesSubject=new Z4(k90({thread$:Z,threadViewState$:Y,toolProgressByToolUseID$:Q,pendingApprovals$:this.pendingApprovalsSubject,pendingSkills$:this.pendingSkillsSubject,sendMessage:async(X)=>(await this.waitForActiveHandle()).sendMessage(X),restoreTo:async(X)=>(await this.waitForActiveHandle()).restoreTo(X),queueMessage:async(X)=>(await this.waitForActiveHandle()).queueMessage(X),discardQueuedMessages:async()=>(await this.waitForActiveHandle()).discardQueuedMessages(),setVisibility:async(X)=>(await this.waitForActiveHandle()).setVisibility(X),cancelTurn:async()=>(await this.waitForActiveHandle()).cancelTurn(),cancelStreaming:async()=>(await this.waitForActiveHandle()).cancelStreaming(),retryTurn:async()=>(await this.waitForActiveHandle()).retryTurn(),dismissEphemeralError:()=>{},preExecuteMode:async()=>(await this.waitForActiveHandle()).preExecuteMode?.(),postExecuteMode:async()=>(await this.waitForActiveHandle()).postExecuteMode?.(),resolveApproval:async(X,V,K)=>(await this.waitForActiveHandle()).resolveApproval(X,V,K),addPendingSkill:()=>{},removePendingSkill:()=>{},clearPendingSkills:()=>{},getFilesAffectedByTruncation:async(X)=>(await this.waitForActiveHandle()).getFilesAffectedByTruncation(X),clearPendingNavigation:async()=>(await this.waitForActiveHandle()).clearPendingNavigation(),getGuidanceFiles:async(X)=>(await this.waitForActiveHandle()).getGuidanceFiles(X)})),this.readyPromise=new Promise((X,V)=>{this.readyResolve=X,this.readyReject=V}),this.readyPromise.catch(()=>{return})}get recentThreadIDs$(){return this.recentThreadIDsSubject}get threadTitles$(){return this.threadTitlesSubject}get drafts$(){return this.draftsSubject}get threadHandles$(){return this.threadHandlesSubject}get allConnectedThreadActivityStatuses$(){return this.allConnectedThreadActivityStatusesSubject}get initializationStatus$(){return this.initializationStatusSubject}get queueOnSubmitByDefault(){return this.attachedPool?.queueOnSubmitByDefault??!1}hasPendingInitialization(){return this.attachedPool===null}isDTWMode(){return this.attachedPool?.isDTWMode?.()===!0}getTransportConnectionState(){if(!this.attachedPool?.getTransportConnectionState)return;return this.attachedPool.getTransportConnectionState()}getCompactionStatus(){if(!this.attachedPool?.getCompactionStatus)return;return this.attachedPool.getCompactionStatus()}attach(J){if(this.attached)throw Error("DeferredThreadPool is already attached");this.attached=!0,this.attachedPool=J;let Z=null,Q=null;this.attachedPoolSubscriptions=[J.recentThreadIDs$.subscribe((Y)=>this.recentThreadIDsSubject.next(Y)),J.threadTitles$.subscribe((Y)=>this.threadTitlesSubject.next(Y)),J.drafts$.subscribe((Y)=>this.draftsSubject.next(Y)),J.allConnectedThreadActivityStatuses$.subscribe((Y)=>this.allConnectedThreadActivityStatusesSubject.next(Y)),...J.initializationStatus$?[J.initializationStatus$.subscribe((Y)=>this.initializationStatusSubject.next(Y))]:[(()=>{return this.initializationStatusSubject.next({pending:!1,message:gG4}),{unsubscribe:()=>{}}})()],J.threadHandles$.subscribe((Y)=>{if(Y)Z?.unsubscribe(),Z=Y.pendingApprovals$.subscribe((X)=>this.pendingApprovalsSubject.next(X)),Q?.unsubscribe(),Q=Y.pendingSkills$.subscribe((X)=>this.pendingSkillsSubject.next(X)),this.threadHandlesSubject.next(Y)}),{unsubscribe:()=>{Z?.unsubscribe(),Q?.unsubscribe()}}],this.readyResolve?.(J),this.readyResolve=null,this.readyReject=null}setInitError(J){if(this.attached)return;this.readyReject?.(J),this.readyResolve=null,this.readyReject=null}async createThread(){return(await this.waitForAttach()).createThread()}async switchThread(J){return(await this.waitForAttach()).switchThread(J)}canNavigateBack(){return this.attachedPool?.canNavigateBack()??!1}canNavigateForward(){return this.attachedPool?.canNavigateForward()??!1}async navigateBack(){return(await this.waitForAttach()).navigateBack()}async navigateForward(){return(await this.waitForAttach()).navigateForward()}async createHandoff(J,Z){return(await this.waitForAttach()).createHandoff(J,Z)}async deleteThread(J){let Z=await this.waitForAttach();if(Z.deleteThread)await Z.deleteThread(J)}async dispose(){for(let J of this.attachedPoolSubscriptions)J.unsubscribe();if(this.attachedPoolSubscriptions=[],this.attachedPool)await this.attachedPool.dispose();this.recentThreadIDsSubject.complete(),this.threadTitlesSubject.complete(),this.draftsSubject.complete(),this.threadHandlesSubject.complete(),this.allConnectedThreadActivityStatusesSubject.complete(),this.initializationStatusSubject.complete(),this.pendingApprovalsSubject.complete(),this.pendingSkillsSubject.complete()}waitForAttach(){if(this.attachedPool)return Promise.resolve(this.attachedPool);return this.readyPromise}async waitForActiveHandle(){let J=await this.waitForAttach();return E1(J.threadHandles$.pipe(F5((Z)=>Z!==null)))}}h0();o50();_4();H1();h0();a2();H1();function T_5(J){let Z=[],Q=0;for(let X of J.messages){if(X.role==="user"){Z.push({role:"user",content:[...X.content],meta:X.meta,userState:X.userState,readAt:X.readAt,parentToolUseId:X.parentToolUseId});continue}if(X.role==="assistant"){Z.push({role:"assistant",content:[...X.content],meta:X.meta,readAt:X.readAt,cancelled:X.state.type==="cancelled",parentToolUseId:X.parentToolUseId});continue}let V=X.content.filter((K)=>K.type==="manual_bash_invocation");if(V.length>0)Z.push({role:"info",content:V,parentToolUseId:X.parentToolUseId});for(let K of X.content){if(K.type!=="summary"||K.summary.type!=="message")continue;Q+=1,Z.push({role:"assistant",content:[{type:"text",text:K.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}}async function u90(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}:{}},V=await p3("/api/durable-thread-workers",Sf0({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(X),signal:Y.signal},Q),Z);if(!V.ok)throw Error(`Failed to create DTW thread: ${V.status} ${await V.text()}`);let K=await V.json();if(!K.threadId||!K.wsToken)throw Error("DTW thread creation response missing threadId or wsToken");return{threadId:K.threadId,wsToken:K.wsToken,usesDtw:K.usesDtw??!0,executorType:K.executorType??null}}async function __5(J,Z,Q,Y){let X=await Z.getLatest(),V=Q??await X.secrets.getToken("apiKey",X.settings.url);if(!V)throw Error("API key required. Please run `amp login` first.");let K=Y.workerURL??Q$(Y.ampURL),z=await fetch(`${K}/threads/${J.id}/import`,{method:"POST",headers:{Authorization:`Bearer ${V}`,"Content-Type":"application/json"},body:JSON.stringify({thread:T_5(J)})});if(z.status===409)return;if(!z.ok)throw Error(`Failed to import thread into DTW: ${z.status} ${await z.text()}`);if((await z.json()).ok!==!0)throw Error("Failed to import thread into DTW: import endpoint returned an invalid response")}async function S_5(J,Z,Q){let Y=await p3(`/api/durable-thread-workers/${J}`,Sf0({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 pG4(J,Z,Q){let Y=await p3(`/api/threads/${J}`,Sf0(void 0,Q),Z);if(!Y.ok)throw Error(`Failed to fetch thread snapshot: ${Y.status} ${await Y.text()}`);return await Y.json()}function Sf0(J,Z){if(!Z)return J;return{...J,headers:{...J?.headers,Authorization:`Bearer ${Z}`}}}function y90(J){let Z=M2.safeParse(J.dtwMessageID);if(Z.success)return Z.data;let Q=M2.safeParse(`${J.messageId}`);return Q.success?Q.data:null}function v_5(J){let Z=[],Q=new Set;for(let[Y,X]of J.messages.entries()){let V=y90(X);if(V)Q.add(V);Z.push({...X,messageId:Y})}return{messages:Z,processedIds:Q}}function k_5(J){let Z=new Set;for(let Q of J){let Y=y90(Q);if(Y)Z.add(Y)}return Z}function Og(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((V)=>V.type==="tool_use"&&V.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 y_5(J,Z,Q,Y){if(!J||Z.length===0)return null;return{role:"assistant",content:Z,state:{type:"streaming"},messageId:Q,parentToolUseId:Y}}function cG4(J){if(typeof J==="string")return J;if(!J||typeof J!=="object")return;if("output"in J&&typeof J.output==="string")return J.output;if("value"in J)return cG4(J.value);return}function u_5(J){return J.type==="text"}function x_5(J){if(J===void 0)return;let Z;try{Z=A80(J,"snapshot")}catch{return}if(Z.type==="snapshot")return cG4(Z.value);let Q=(Z.blocks??[]).filter(u_5).map((Y)=>Y.text).join("");return Q.length>0?Q:void 0}function f_5(J,Z){let Q=J.parentToolCallId,{completedMessages:Y}=Z;if(J.state==="complete"||J.state==="error"){if(Z.streamingMessageId!==null&&J.messageId!==Z.streamingMessageId){if(Z.streamingBlocks.length>0)Y.push({messageId:Z.streamingMessageId,role:"assistant",blocks:Z.streamingBlocks,parentToolCallId:Z.streamingParentToolCallId});Z.streamingMessageId=null,Z.streamingBlocks=[],Z.streamingParentToolCallId=void 0;let V=J.blocks??[];if(V.length>0)if(J.role==="user")Y.push({messageId:J.messageId,role:"user",blocks:V,parentToolCallId:Q});else Y.push({messageId:J.messageId,role:"assistant",blocks:V,parentToolCallId:Q});return}if(Z.streamingMessageId===null&&J.blocks&&J.blocks.length>0){let V=J.blocks;if(J.role==="user")Y.push({messageId:J.messageId,role:"user",blocks:V,parentToolCallId:Q});else Y.push({messageId:J.messageId,role:"assistant",blocks:V,parentToolCallId:Q});return}let X=Z.streamingBlocks;if(J.messageId===Z.streamingMessageId&&J.blocks&&J.role==="assistant")X=Og(Z.streamingBlocks,J.blocks);if(Z.streamingMessageId&&X.length>0)Y.push({messageId:Z.streamingMessageId,role:"assistant",blocks:X,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=Og([],J.blocks??[]),Z.streamingParentToolCallId=Q;else if(J.blocks)Z.streamingBlocks=Og(Z.streamingBlocks,J.blocks);if(Z.streamingBlocks.length>0)Y.push({messageId:Z.streamingMessageId??J.messageId,role:"assistant",blocks:Z.streamingBlocks,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=Og([],J.blocks??[]),Z.streamingParentToolCallId=Q;else if(J.blocks)Z.streamingBlocks=Og(Z.streamingBlocks,J.blocks)}}function b_5(J,Z,Q){if(Z.length===0)return J;let Y=[],X=J.length;for(let V of Z){if(Q.has(V.messageId))continue;Q.add(V.messageId);let K=X++;if(V.role==="assistant")Y.push({role:"assistant",content:V.blocks,state:{type:"complete",stopReason:"end_turn"},messageId:K,dtwMessageID:V.messageId,parentToolUseId:V.parentToolCallId});else Y.push({role:"user",content:V.blocks,messageId:K,dtwMessageID:V.messageId,parentToolUseId:V.parentToolCallId})}if(Y.length===0)return J;return[...J,...Y]}function h_5(J,Z,Q){let Y=J.message.messageId;if(Q.has(Y))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"},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,userState:J.message.userState,messageId:X,dtwMessageID:Y,parentToolUseId:J.parentToolUseId}]}function m_5(J,Z){let Q=Z.findIndex((z)=>y90(z)===J.messageId),Y=Z.findIndex((z)=>y90(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 V={role:"user",content:J.content,messageId:X.messageId,dtwMessageID:J.messageId},K=Z.slice(0,Y+1);return K[Q]=V,K}function Eg(J){if(!J||J.length===0)return;return J.map((Z)=>({...Z,queuedMessage:{...Z.queuedMessage,content:Z.queuedMessage.content.map((Q)=>({...Q}))}}))}function dG4(J){let Z=J.queuedMessage,Q=Z.content.map((Y)=>({...Y}));return{id:J.id,interrupt:J.interrupt,queuedMessage:{role:"user",content:Q,userState:Z.userState,meta:Z.createdAt?{sentAt:Date.parse(Z.createdAt)}:void 0,messageId:-1,dtwMessageID:J.id}}}function g_5(J){if(J.type==="queued_messages")return{type:"queued_messages",messages:J.messages.map((Z)=>dG4(Z))};if(J.type==="queued_message_added")return{type:"queued_message_added",message:dG4(J.message)};return{type:"queued_message_removed",queuedMessageId:J.queuedMessageId}}function p_5(J,Z){let Q=g_5(Z);return Vx0(Eg(J)??[],Q,{dedupeAdded:!0})}function d_5(J,Z){return{baseURL:J.workerUrl??Q$(J.ampURL),threadId:Z.threadId,wsToken:Z.wsToken,wsTokenProvider:async()=>u90(Z.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL}),WebSocketClass:WebSocket,maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000}}class x90{threadSubject;agentLoopStateSubject=new Z4("idle");editErrorSubject=new s1;deltaState={streamingMessageId:null,streamingBlocks:[],completedMessages:[]};toolProgressByToolUseIDSubject=new Z4(new Map);toolProgressSubject=new s1;subscriptions=[];threadVersion;messages;queuedMessages;relationships;threadTitle;processedIds;agentLoopState="idle";toolProgressByToolUseID=new Map;contextWindowRatio=null;compactionStateSubject=new Z4("idle");compactionState="idle";lastConnectionState="disconnected";lastConnectionInfo=null;transport;threadId;constructor(J,Z,Q,Y){this.threadId=J.id,this.threadTitle=J.title,this.messages=[...J.messages],this.queuedMessages=Eg(J.queuedMessages)??[],this.relationships=J.relationships??[],this.processedIds=Q,this.transport=Z,this.threadVersion=Y,this.threadSubject=new Z4(J)}static async create(J){let Z=await u90(J.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL,executorType:J.executorType}),Q=await pG4(Z.threadId,J.configService,J.apiKey),Y=Q;if(!Z.usesDtw){J.onLegacyImportStateChange?.("importing");try{await __5(Q,J.configService,J.apiKey,{ampURL:J.ampURL,workerURL:J.workerUrl}),await S_5(Z.threadId,J.configService,J.apiKey),Y=await pG4(Z.threadId,J.configService,J.apiKey)}finally{J.onLegacyImportStateChange?.("idle")}}let{messages:X,processedIds:V}=v_5(Y),K={...Y,id:Z.threadId,messages:X,queuedMessages:Eg(Y.queuedMessages),relationships:Y.relationships?[...Y.relationships]:void 0},z=new XH(d_5(J,Z)),G=new x90(K,z,V,Y.v);try{return await G.connect(),G}catch(F){throw G.dispose(),F}}threadChanges(){return this.threadSubject}agentLoopStateChanges(){return this.agentLoopStateSubject}toolProgressByToolUseIDChanges(){return this.toolProgressByToolUseIDSubject}toolProgressChanges(){return this.toolProgressSubject}editErrors(){return this.editErrorSubject}getThread(){return this.threadSubject.getValue()}getAgentLoopState(){return this.agentLoopState}getConnectionInfo(){return this.lastConnectionInfo?{...this.lastConnectionInfo}:null}getContextWindowRatio(){return this.contextWindowRatio}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)}emitThread(){let J=this.threadSubject.getValue(),Z=y_5(this.deltaState.streamingMessageId,this.deltaState.streamingBlocks,this.messages.length,this.deltaState.streamingParentToolCallId),Y=Z?[...this.messages,Z]:[...this.messages],X=Y.reduce((K,z)=>Math.max(K,z.messageId),-1)+1,V={...J,id:this.threadId,v:this.threadVersion,title:this.threadTitle,messages:Y,queuedMessages:this.queuedMessages.length>0?Eg(this.queuedMessages):void 0,relationships:this.relationships.length>0?[...this.relationships]:void 0,nextMessageId:Math.max(X,0)};this.threadSubject.next(V)}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)}runTransportHandler(J,Z){try{Z()}catch(Q){let Y=Q instanceof Error?Q.message:String(Q);j.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.lastConnectionInfo,Q=J.state!==this.lastConnectionState,Y=Z!==null&&(J.role!==Z.role||J.clientId!==Z.clientId);if(!Q&&!Y)return;if(Q)this.logConnectionStateTransition(this.lastConnectionState,J);else if(Y&&Z)this.logConnectionRoleTransition(Z,J);let X=J.state;if(X==="connected"&&this.lastConnectionState!=="connected")this.transport.resumeFromVersion(this.threadVersion);this.lastConnectionState=X,this.lastConnectionInfo={...J}})}}),this.transport.errors().subscribe({next:(J)=>{this.runTransportHandler("errors",()=>{let Z=J.code==="PARSE_ERROR"?$x0(J.message):null;if(j.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(J.usage?.contextWindowRatio!==void 0){let Z=J.usage.contextWindowRatio;this.contextWindowRatio=Number.isFinite(Z)&&Z>=0&&Z<=1?Z:null}if(f_5(J,this.deltaState),J.role==="user"&&(J.state==="complete"||J.state==="error")&&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=b_5(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=x_5(J.progress);if(Q===void 0){if(this.toolProgressByToolUseID.delete(Z))this.emitToolProgress();return}if(this.toolProgressByToolUseID.get(Z)===Q)return;this.toolProgressByToolUseID.set(Z,Q),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",()=>{if(this.messages=h_5(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.threadVersion=Math.max(this.threadVersion,J.seq),this.emitThread()})}}),this.transport.messageEdited().subscribe({next:(J)=>{this.runTransportHandler("messageEdited",()=>{this.messages=m_5(J,this.messages),this.processedIds=k_5(this.messages),this.threadVersion=Math.max(this.threadVersion,J.seq),this.emitThread()})}}),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.threadVersion=Math.max(this.threadVersion,J.seq),this.emitThread()})}}),this.transport.queuedMessages().subscribe({next:(J)=>{this.runTransportHandler("queuedMessages",()=>{this.queuedMessages=p_5(this.queuedMessages,J),this.emitThread()})}}))}logConnectionStateTransition(J,Z){let Q={threadId:this.threadId,from:J,to:Z.state,role:Z.role,clientId:Z.clientId,transportThreadId:Z.threadId,threadVersion:this.threadVersion};if(Z.state==="connected"){if(J==="reconnecting"){j.info("[dtw] Transport reconnected",Q);return}j.info("[dtw] Transport connected",Q);return}if(Z.state==="reconnecting"){j.warn("[dtw] Transport reconnecting",Q);return}if(Z.state==="disconnected"){j.warn("[dtw] Transport disconnected",Q);return}j.info("[dtw] Transport state changed",Q)}logConnectionRoleTransition(J,Z){j.info("[dtw] Transport role changed",{threadId:this.threadId,state:Z.state,fromRole:J.role,toRole:Z.role,fromClientId:J.clientId,toClientId:Z.clientId,transportThreadId:Z.threadId,threadVersion:this.threadVersion})}async connect(){this.subscribeToTransport(),await this.transport.connect(),this.emitThread()}sendUserMessage(J,Z,Q){return this.setAgentMode(Z),this.transport.sendUserMessage(J,Z,{userState:Q})}interruptQueuedMessage(J){this.transport.interruptQueuedMessage(J)}discardQueuedMessages(){let J=Eg(this.queuedMessages);if(this.queuedMessages.length===0)return;let Z=this.queuedMessages.map((Q)=>Q.id);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.compactionStateSubject.complete(),this.agentLoopStateSubject.complete(),this.toolProgressByToolUseIDSubject.complete(),this.toolProgressSubject.complete(),this.transport.dispose()}}h0();i5();d9();h$();K00();_4();bF();bv0();N4();H1();v$();function c_5(J){let Z=-1;for(let V=J.messages.length-1;V>=0;V--)if(J.messages[V]?.role==="assistant"){Z=V;break}if(Z<0)return{running:0,blocked:0};let Q=J.messages[Z];if(!Q)return{running:0,blocked:0};let Y=new Map;for(let V of J.messages.slice(Z+1)){if(V.role!=="user")continue;for(let K of V.content)if(K.type==="tool_result")Y.set(K.toolUseID,K.run)}let X=0;for(let V of Q.content){if(V.type!=="tool_use")continue;let K=Y.get(V.id);if(!K||!M8(K))X++}return{running:X,blocked:0}}function l_5(J){let Z=J.messages.at(-1);if(!Z)return"user-message-initial";if(Z.role==="assistant")return Z.state.type==="complete"&&Z.state.stopReason==="end_turn"?"user-message-reply":!1;return!1}function i_5(J){let Z=l_5(J);if(Z)return Z;return!1}function vf0(J,Z,Q={files:[]},Y=void 0){let X=c_5(J),V=Z==="awaiting_approval"?1:0;if(Z==="working"||Z==="streaming")return{state:"active",inferenceState:"running",fileChanges:Q,ephemeralError:Y,interactionState:!1,toolState:{running:0,blocked:0}};if(Z==="tool_use"||Z==="running_tools"){let K=X.running;return{state:"active",inferenceState:"idle",fileChanges:Q,ephemeralError:Y,interactionState:K>0?"tool-running":!1,toolState:{running:K,blocked:V}}}if(Z==="awaiting_approval")return{state:"active",inferenceState:"idle",fileChanges:Q,ephemeralError:Y,interactionState:"user-tool-approval",toolState:{running:X.running,blocked:V}};return{state:"active",inferenceState:"idle",fileChanges:Q,ephemeralError:Y,interactionState:i_5(J),toolState:{running:X.running,blocked:V}}}_4();class kf0{authoritativeThread;currentAgentLoopState;pendingMessageSubmits=[];pendingQueuedSubmits=[];pendingQueuedInterruptMessageIDs=new Set;pendingEdit;constructor(J,Z){this.authoritativeThread=J,this.currentAgentLoopState=Z}setAgentLoopState(J){this.currentAgentLoopState=J}optimisticUpdate(J){switch(J.type){case"submit":return this.optimisticSubmit(J);case"discard-queued":return this.pendingQueuedSubmits=[],this.pendingQueuedInterruptMessageIDs.clear(),this.buildProjection();case"interrupt-queued":return this.optimisticInterruptQueued(J);case"edit":return this.optimisticEdit(J)}}optimisticInterruptQueued(J){let Z=this.buildProjection(),Q=(Z.queuedMessages??[]).find((Y)=>Y.id===J.queuedMessageID);if(!Q||yf0(Q))return Z;if(this.pendingQueuedInterruptMessageIDs.has(J.queuedMessageID))return this.buildProjection();return this.pendingQueuedInterruptMessageIDs.add(J.queuedMessageID),this.buildProjection()}optimisticSubmit(J){if(YS5(this.pendingMessageSubmits,this.pendingQueuedSubmits,this.authoritativeThread,J.clientMessageID))return this.buildProjection();let Z={clientMessageID:J.clientMessageID,content:J.content,userState:J.userState,sentAt:J.sentAt??Date.now()};if(DS5(this.currentAgentLoopState))this.pendingQueuedSubmits.push(Z);else this.pendingMessageSubmits.push(Z);return this.buildProjection()}optimisticEdit(J){let Z=this.buildProjection(),Q=Gw0(Z,J.targetMessageID);if(Q<0)return Z;return this.pendingMessageSubmits=[],this.pendingQueuedSubmits=[],this.pendingEdit={targetMessageID:J.targetMessageID,content:J.content,truncatedMessageIDs:JS5(Z,Q)},this.buildProjection()}resolve(J){if(!this.hasPendingOverlay())return this.authoritativeThread=J,J;let Z=this.authoritativeThread;return this.authoritativeThread=J,this.reconcilePending(Z),this.buildProjection()}hasPendingOverlay(){return a_5(this.pendingMessageSubmits,this.pendingQueuedSubmits,this.pendingQueuedInterruptMessageIDs,this.pendingEdit)}reconcilePending(J){let Z=$S5(this.authoritativeThread);this.pendingMessageSubmits=XS5(J,this.authoritativeThread,Z,this.pendingMessageSubmits),this.pendingQueuedSubmits=GS5(this.authoritativeThread,Z,this.pendingQueuedSubmits),this.pendingQueuedInterruptMessageIDs=FS5(this.authoritativeThread,this.pendingQueuedSubmits,this.pendingQueuedInterruptMessageIDs),this.pendingEdit=US5(Z,this.pendingEdit)}buildProjection(){if(!this.hasPendingOverlay())return this.authoritativeThread;let J=this.pendingEdit;return n_5(this.authoritativeThread,(Z)=>o_5(Z,J),(Z)=>r_5(Z,this.pendingMessageSubmits),(Z)=>s_5(Z,this.pendingQueuedSubmits),(Z)=>t_5(Z,this.pendingQueuedInterruptMessageIDs))}}function n_5(J,...Z){return Z.reduce((Q,Y)=>Y?Y(Q):Q,J)}function a_5(J,Z,Q,Y){return J.length>0||Z.length>0||Q.size>0||Y!==void 0}function o_5(J,Z){if(!Z)return J;let Q=_I1(J,Z.targetMessageID);if(!Q)return J;let{index:Y,message:X}=Q,V=J.messages.slice(0,Y+1);return V[Y]={...X,content:Z.content},{...J,messages:V,nextMessageId:zw0({messages:V,nextMessageId:J.nextMessageId})}}function r_5(J,Z){if(Z.length===0)return J;let Q=zw0(J),Y=Z.map((X,V)=>iG4(X,Q+V));return{...J,messages:[...J.messages,...Y],nextMessageId:Math.max(J.nextMessageId??0,Q+Y.length)}}function s_5(J,Z){if(Z.length===0)return J;let Q=Z.map(e_5);return{...J,queuedMessages:[...J.queuedMessages??[],...Q]}}function t_5(J,Z){if(Z.size===0||!J.queuedMessages?.length)return J;let Q=!1,Y=J.queuedMessages.map((X)=>{if(!Z.has(X.id)||yf0(X))return X;return Q=!0,{...X,interrupt:!0}});if(!Q)return J;return{...J,queuedMessages:Y}}function iG4(J,Z){return{role:"user",content:J.content,userState:J.userState,meta:{sentAt:J.sentAt},messageId:Z,dtwMessageID:J.clientMessageID}}function e_5(J){return{id:J.clientMessageID,queuedMessage:iG4(J,-1)}}function $S5(J){let Z=new Set,Q=new Set,Y=new Map,X=new Set;for(let V of J.messages)if(typeof V.dtwMessageID==="string"){if(X.add(V.dtwMessageID),V.role==="user")Z.add(V.dtwMessageID),Y.set(V.dtwMessageID,V)}for(let V of J.queuedMessages??[])Q.add(V.id);return{userMessageIDs:Z,queuedMessageIDs:Q,userMessagesByID:Y,messageIDsInTimeline:X}}function JS5(J,Z){return J.messages.slice(Z+1).map((Q)=>Q.dtwMessageID).filter((Q)=>typeof Q==="string")}function ZS5(J,Z){return J.messages.some((Q)=>Q.role==="user"&&Q.dtwMessageID===Z)}function QS5(J,Z){return(J.queuedMessages??[]).some((Q)=>Q.id===Z)}function yf0(J){return"interrupt"in J&&J.interrupt===!0}function YS5(J,Z,Q,Y){return J.some((X)=>X.clientMessageID===Y)||Z.some((X)=>X.clientMessageID===Y)||ZS5(Q,Y)||QS5(Q,Y)}function XS5(J,Z,Q,Y){if(Y.length===0)return[];let{unmatchedPendingSubmits:X,acknowledgedByID:V}=VS5(Y,Q.userMessageIDs);if(X.length===0)return[];let K=KS5(J,Z);if(!K)return X;let z=zS5(K,V,X.length);return X.slice(z)}function VS5(J,Z){let Q=new Set,Y=[];for(let X of J){if(Z.has(X.clientMessageID)){Q.add(X.clientMessageID);continue}Y.push(X)}return{unmatchedPendingSubmits:Y,acknowledgedByID:Q}}function KS5(J,Z){let Q=lG4(J),Y=lG4(Z);if(!(Q.length<=Y.length&&Q.every((V,K)=>V.dtwMessageID===Y[K]?.dtwMessageID)))return;return Y.slice(Q.length)}function zS5(J,Z,Q){let Y=0;for(let X of J){if(typeof X.dtwMessageID==="string"&&Z.has(X.dtwMessageID))continue;if(Y++,Y===Q)return Y}return Y}function lG4(J){return J.messages.filter((Z)=>Z.role==="user")}function GS5(J,Z,Q){if(Q.length===0)return[];let Y=[...J.queuedMessages??[]];return Q.filter((X)=>{if(Z.queuedMessageIDs.has(X.clientMessageID)||Z.userMessageIDs.has(X.clientMessageID))return!1;let V=Y.findIndex((K)=>Fw0(X.content,K.queuedMessage.content));if(V>=0)return Y.splice(V,1),!1;return!0})}function FS5(J,Z,Q){if(Q.size===0)return new Set;let Y=new Map((J.queuedMessages??[]).map((K)=>[K.id,K])),X=new Set(Z.map((K)=>K.clientMessageID)),V=new Set;for(let K of Q){let z=Y.get(K);if(!z){if(X.has(K))V.add(K);continue}if(yf0(z))continue;V.add(K)}return V}function US5(J,Z){if(!Z)return;return qS5(J,Z)?void 0:Z}function qS5(J,Z){let Q=J.userMessagesByID.get(Z.targetMessageID);if(!Q)return!1;if(!Fw0(Q.content,Z.content))return!1;return Z.truncatedMessageIDs.every((X)=>!J.messageIDsInTimeline.has(X))}function DS5(J){return WS5.has(J)}var WS5=new Set(["working","streaming","tool_use","running_tools","awaiting_approval"]);class uf0{threadWriter;deps;thread$;threadViewState$;inferenceErrors$;toolProgressByToolUseID$;pendingApprovals$;provider;threadSubject;threadViewStateSubject;transportSubscriptions=[];clientID=`cli-tui-${crypto.randomUUID()}`;toolRunner;handshakeManager;optimisticThreadProjection;settingsSyncSubscription=null;lastSentSettingsJSON="";pendingApprovalsSubject=new Z4([]);pendingSkillsSubject=new Z4([]);inferenceErrorsSubject=new s1;pendingSkills$=this.pendingSkillsSubject;fileChanges={files:[]};activeError=null;retryCountdownTimer=null;advertisedExecutorTools=[];handoffService;providerSubscriptions=null;constructor(J,Z,Q){this.threadWriter=Z;this.deps=Q;this.provider=J;let Y=uH0("info"),X=uH0("error");this.toolRunner=new im({clientID:this.clientID,transport:this.provider.transport,executeBuiltinTool:()=>null,invokeTool:(G)=>this.invokeToolForLease(G),batchGuidanceFiles:f80,renderToolRunError:Zf,log:{info:(G,F)=>Y(G,F),error:(G,F)=>X(G,{error:F}),wsMessage:(G,F,U)=>{j.debug("DTW executor tool runner message",{direction:G,clientID:F,...typeof U==="object"&&U!==null?U:{message:U}})}}}),this.handshakeManager=this.createHandshakeManager();let V=J.getThread();this.optimisticThreadProjection=new kf0(V,J.getAgentLoopState());let K=this.optimisticThreadProjection.resolve(V),z=vf0(K,J.getAgentLoopState(),this.fileChanges,this.currentEphemeralError());this.threadSubject=new Z4(K),this.thread$=this.threadSubject,this.threadViewStateSubject=new Z4(z),this.threadViewState$=this.threadViewStateSubject,this.inferenceErrors$=this.inferenceErrorsSubject,this.toolProgressByToolUseID$=this.provider.toolProgressByToolUseIDChanges().pipe(D1(v90)),this.pendingApprovals$=this.pendingApprovalsSubject,this.refreshProviderFileChanges(),this.attachTransportHandlers(),this.handshakeManager.ensureHandshake("connect"),this.handoffService=Q.handoffService}startProviderSubscription(J){this.providerSubscriptions?.unsubscribe();let Z=this.provider.threadChanges().subscribe({next:(Y)=>{J(Y),this.refreshProviderFileChanges(),this.updateThreadViewStateFromProvider()}}),Q=this.provider.agentLoopStateChanges().subscribe({next:(Y)=>{if(this.optimisticThreadProjection.setAgentLoopState(Y),Y==="error")this.inferenceErrorsSubject.next(Error("Agent failed to complete the request."));this.updateThreadViewStateFromProvider()}});this.providerSubscriptions={unsubscribe:()=>{Z.unsubscribe(),Q.unsubscribe()}}}writeThread(J){this.threadWriter.write(J),this.threadSubject.next(J)}providerThread(){return this.provider.getThread()}resolveAuthoritativeThread(J){return this.optimisticThreadProjection.resolve(J)}getThreadViewState(){return this.threadViewStateSubject.getValue()}getResolvedTokenUsage(){let J=K2(this.thread$.getValue());if(J)return J;let Z=this.provider.getContextWindowRatio();if(Z===null)return;return{maxInputTokens:1,inputTokens:Z,outputTokens:0,cacheCreationInputTokens:0,cacheReadInputTokens:0,totalInputTokens:Z}}async dispose(){this.providerSubscriptions?.unsubscribe(),this.providerSubscriptions=null;for(let J of this.transportSubscriptions)J.unsubscribe();this.transportSubscriptions.length=0,this.clearRetryCountdownTimer(),this.settingsSyncSubscription?.unsubscribe(),this.settingsSyncSubscription=null,this.handshakeManager.dispose(),this.toolRunner.dispose(),this.provider.dispose(),await this.threadWriter.asyncDispose(),this.threadSubject.complete(),this.threadViewStateSubject.complete(),this.inferenceErrorsSubject.complete(),this.pendingApprovalsSubject.complete(),this.pendingSkillsSubject.complete()}async sendMessage(J){await this.handshakeManager.ensureReady();let Z=this.thread$.getValue();if(J.editIndex!==void 0){let K=Z.messages[J.editIndex];if(!K||K.role!=="user"||!K.dtwMessageID)throw Error("Unable to edit message: missing DTW message ID");let z=Z.messages.findIndex((U)=>U.role==="user");if(J.editIndex===z&&J.agentMode&&Z.agentMode!==J.agentMode)this.provider.setAgentMode(J.agentMode,{overwrite:!0}),this.updateThread((U)=>{U.agentMode=J.agentMode});this.provider.transport.editUserMessage(K.dtwMessageID,J.content,cu0(),J.agentMode);let F=this.optimisticThreadProjection.optimisticUpdate({type:"edit",targetMessageID:K.dtwMessageID,content:J.content});this.writeThread(F);return}if(!Z.messages.some((K)=>K.role==="user")&&!Z.agentMode&&J.agentMode)this.updateThread((K)=>{K.agentMode=J.agentMode});let Y=await this.collectUserState(),X=this.provider.sendUserMessage(J.content,J.agentMode,Y),V=this.optimisticThreadProjection.optimisticUpdate({type:"submit",clientMessageID:X,content:J.content,userState:Y});this.writeThread(V)}async restoreTo(J){await this.handshakeManager.ensureReady();let Y=[...this.thread$.getValue().messages.slice(0,J+1)].reverse().find((K)=>K.role==="user");if(!Y?.dtwMessageID)throw Error("Unable to edit message: missing DTW message ID");let X=Y.content.filter((K)=>K.type==="text"||K.type==="image").map((K)=>{if(K.type==="image")return{...K,source:{...K.source}};return{...K}});if(X.length===0)throw Error("Unable to edit message: no editable content found");this.provider.transport.editUserMessage(Y.dtwMessageID,X,cu0());let V=this.optimisticThreadProjection.optimisticUpdate({type:"edit",targetMessageID:Y.dtwMessageID,content:X});this.writeThread(V)}async queueMessage(J){await this.handshakeManager.ensureReady();let Z=await this.collectUserState(),Q=this.provider.sendUserMessage(J,void 0,Z),Y=this.optimisticThreadProjection.optimisticUpdate({type:"submit",clientMessageID:Q,content:J,userState:Z});this.writeThread(Y)}async discardQueuedMessages(){let J=this.optimisticThreadProjection.optimisticUpdate({type:"discard-queued"});this.writeThread(J),this.provider.discardQueuedMessages()}async interruptQueuedMessage(J){await this.handshakeManager.ensureReady(),this.provider.interruptQueuedMessage(J);let Z=this.optimisticThreadProjection.optimisticUpdate({type:"interrupt-queued",queuedMessageID:J});this.writeThread(Z)}async setVisibility(J){let Z=await A6.setThreadMeta({thread:this.provider.threadId,meta:yV(J)},{config:this.deps.configService});if(!Z.ok)throw Error(Z.error.code)}updateThread(J){let Z=this.threadWriter.update(J),Q=this.optimisticThreadProjection.resolve(Z);if(Q!==Z)this.threadWriter.write(Q);this.threadSubject.next(Q)}async cancelTurn(){this.provider.transport.cancelAgentLoop()}async cancelStreaming(){this.provider.transport.cancelAgentLoop()}async retryTurn(){this.provider.transport.retryAgentLoop()}invokeBashTool(J,Z){let Q=lY4();return new v0((Y)=>{let X=!1,V=null,K=(U)=>{this.provider.transport.appendManualBashInvocation({args:J,run:U,hidden:Z.hidden})},z=(U,q={emitRun:!0})=>{if(X)return;if(X=!0,K(U),q.emitRun)Y.next(U);Y.complete()},G=(U)=>U instanceof Error?U.message:String(U),F=()=>{V?.unsubscribe(),z({status:"cancelled",reason:"User canceled"})};return Z.abortController.signal.addEventListener("abort",F),(async()=>{try{let U=await LU({toolName:C6,threadSnapshot:this.provider.getThread(),dtwArtifactSyncService:this.createDTWArtifactSyncService(),configService:this.deps.configService,toolService:this.deps.toolService,mcpService:this.deps.mcpService,skillService:this.deps.skillService,fsTracker:this.deps.fs,toolUseID:Q,discoveredGuidanceFileURIs:this.toolRunner.discoveredGuidanceFileURIs});if(X)return;Y.next({status:"in-progress"}),V=this.deps.toolService.invokeTool(C6,{args:J},U).subscribe({next:(q)=>{if(X)return;if(Y.next(q),q.status!=="in-progress")z(q,{emitRun:!1})},error:(q)=>{z({status:"error",error:{message:G(q)}})}})}catch(U){z({status:"error",error:{message:G(U)}})}})(),()=>{V?.unsubscribe(),Z.abortController.signal.removeEventListener("abort",F)}})}dismissEphemeralError(){this.activeError=null,this.clearRetryCountdownTimer(),this.updateThreadViewStateFromProvider()}async resolveApproval(J,Z,Q){let Y=z8.safeParse(J);if(!Y.success)return;this.provider.transport.resolveToolApproval(Y.data,Z)}addPendingSkill(J){this.pendingSkillsSubject.next([...this.pendingSkillsSubject.getValue(),J])}removePendingSkill(J){this.pendingSkillsSubject.next(this.pendingSkillsSubject.getValue().filter((Z)=>Z.name!==J))}clearPendingSkills(){this.pendingSkillsSubject.next([])}async clearPendingNavigation(){}async getGuidanceFiles(J){let Z=this.thread$.getValue();return(await Zz({filesystem:this.deps.filesystem,configService:this.deps.configService,threadService:this.deps.threadService},Z,J)).map((Y)=>({uri:Y.uri,type:Y.type}))}async getFilesAffectedByTruncation(J){let Z=this.thread$.getValue(),Q=await this.getToolUsesToRevert(Z,J);return Q.size>0?this.deps.fs.tracker.getFilesForToolUses(Q):[]}async getToolUsesToRevert(J,Z){let Q=new Set;J.messages.slice(0,Z).forEach((V)=>{if(V.role==="user"){for(let K of V.content)if(K.type==="tool_result")Q.add(K.toolUseID)}else for(let K of V.content)if(K.type==="tool_use")Q.add(K.id)});let Y=new Set,X=await this.deps.fs.tracker.getAllRecords();for(let[V]of X.entries())if(!Q.has(V))Y.add(V);return Y}async collectUserState(){try{return await r50()??$f}catch(J){return j.warn("Failed to collect IDE user state for DTW message",{error:J}),$f}}createHandshakeManager(){return new lm({handshake:(J)=>this.sendExecutorHandshake(J),onError:({error:J,attempt:Z,delayMs:Q})=>{j.warn("DTW executor handshake failed",{error:J,attempt:Z,delayMs:Q})},onExhausted:(J)=>{this.handleHandshakeExhausted(J)}})}handleHandshakeExhausted(J){j.error("DTW executor handshake exhausted",J)}syncApprovalRequests(J){let Z=this.provider.threadId;if(!Z){this.pendingApprovalsSubject.next([]);return}let Q=J.filter((X)=>X.threadId===Z||X.mainThreadId===Z);this.pendingApprovalsSubject.next(Q);let Y=new Set(Q.map(dE));for(let X of[...this.toolRunner.sentApprovalRequests])if(!Y.has(X))this.toolRunner.sentApprovalRequests.delete(X);for(let X of Q){let V=dE(X);if(this.toolRunner.sentApprovalRequests.has(V))continue;let K=y80(X);this.provider.transport.sendExecutorToolApprovalRequest(K),this.toolRunner.sentApprovalRequests.add(V)}}handleExecutorToolApprovalResponse(J){this.deps.toolService.resolveApproval(J.toolCallId,J.accepted)}syncExecutorTools(J){let Z=this.provider.transport.getConnectionInfo();if(Z.state!=="connected"||Z.role!=="executor")return;this.advertisedExecutorTools=dm({transport:this.provider.transport,nextTools:J,previouslyAdvertisedTools:this.advertisedExecutorTools})}attachTransportHandlers(){this.transportSubscriptions.push(this.provider.transport.connectionChanges().subscribe({next:(J)=>{this.handshakeManager.handleConnectionChange(J)}}),this.provider.compactionStateChanges().subscribe({next:()=>{this.updateThreadViewStateFromProvider()}}),this.provider.transport.errorEvents().subscribe({next:(J)=>{if(this.activeError=J.type==="error_set"?J.error:null,J.type==="error_set")this.inferenceErrorsSubject.next(J.error);this.syncRetryCountdownTimer(),this.updateThreadViewStateFromProvider()}}),this.provider.transport.errors().subscribe({next:(J)=>{this.inferenceErrorsSubject.next(Error(J.message))}}),this.provider.transport.cancelledEvents().subscribe({next:()=>{this.activeError=null,this.clearRetryCountdownTimer(),this.updateThreadViewStateFromProvider()}}),this.provider.transport.toolLeases().subscribe({next:(J)=>{this.toolRunner.handleToolLease(J)}}),this.provider.transport.toolLeaseRevoked().subscribe({next:(J)=>{this.toolRunner.handleToolRevocation(J)}}),this.provider.transport.executorRollbackRequests().subscribe({next:(J)=>{this.handleRollbackRequest(J).catch(()=>{return})}}),this.provider.transport.fileSystemReadDirectoryRequests().subscribe({next:(J)=>{this.handleFileSystemReadDirectoryRequest(J).catch(()=>{return})}}),this.provider.transport.fileSystemReadFileRequests().subscribe({next:(J)=>{this.handleFileSystemReadFileRequest(J).catch(()=>{return})}}),this.provider.transport.executorToolApprovalResponses().subscribe({next:(J)=>{this.handleExecutorToolApprovalResponse(J)}}),this.deps.toolService.tools.subscribe({next:(J)=>{this.syncExecutorTools(_C(J))}}),this.deps.toolService.pendingApprovals$.subscribe((J)=>{this.syncApprovalRequests(J)}))}async sendExecutorHandshake(J){j.debug("DTW executor handshake",{trigger:J,threadID:this.provider.threadId}),this.settingsSyncSubscription?.unsubscribe(),this.settingsSyncSubscription=null;let{advertisedTools:Z}=await b80({transport:this.provider.transport,executorClientID:this.clientID,workspaceRoot:process.cwd(),threadId:this.provider.threadId,resumeFromVersion:this.provider.getThread().v,configService:this.deps.configService,toolService:this.deps.toolService,skillService:this.deps.skillService,sendGitSnapshot:!1,executorType:"local-client",previouslyAdvertisedTools:this.advertisedExecutorTools,initialToolDiscovery:this.deps.initialToolDiscovery});this.advertisedExecutorTools=Z,this.applyLocalEnvironment(),this.settingsSyncSubscription=this.deps.configService.config.subscribe({next:(Q)=>{this.lastSentSettingsJSON=h80(this.provider.transport,Q,this.lastSentSettingsJSON)}})}async applyLocalEnvironment(){try{let J=await $J();this.provider.setEnvironment({initial:J})}catch(J){j.debug("Failed to apply local environment",{error:J})}}createDTWArtifactSyncService(){return{upsertArtifact:(J,Z)=>{let Q=z8.safeParse(Z);this.provider.transport.sendExecutorArtifactUpsert(J,Q.success?Q.data:void 0)},deleteArtifact:(J)=>{this.provider.transport.sendExecutorArtifactDelete(J)}}}async invokeToolForLease(J){let Z=typeof J.args==="object"&&J.args!==null?J.args:{},Q=await LU({toolName:J.toolName,threadSnapshot:this.provider.getThread(),dtwHandoffService:this.handoffService,dtwArtifactSyncService:this.createDTWArtifactSyncService(),configService:this.deps.configService,toolService:this.deps.toolService,mcpService:this.deps.mcpService,skillService:this.deps.skillService,fsTracker:this.deps.fs,toolUseID:J.toolCallId,discoveredGuidanceFileURIs:this.toolRunner.discoveredGuidanceFileURIs});return this.deps.toolService.invokeTool(J.toolName,{args:Z},Q)}async handleRollbackRequest(J){await this.toolRunner.handleRollbackRequest(J.editId,J.toolUseIdsToRevert,(Z)=>this.deps.fs.tracker.revertChanges(Z)),await this.refreshProviderFileChanges(),this.updateThreadViewStateFromProvider()}async handleFileSystemReadDirectoryRequest(J){let Z=await g80({fileSystem:this.deps.filesystem,workspaceRoot:process.cwd()},J.uri);this.provider.transport.sendExecutorFileSystemReadDirectoryResult(J.requestId,Z)}async handleFileSystemReadFileRequest(J){let Z=await p80({fileSystem:this.deps.filesystem,workspaceRoot:process.cwd()},J.uri);this.provider.transport.sendExecutorFileSystemReadFileResult(J.requestId,Z)}async refreshProviderFileChanges(){this.fileChanges={files:await V00(this.deps.fs.tracker)},this.updateThreadViewStateFromProvider()}updateThreadViewStateFromProvider(){this.threadViewStateSubject.next(vf0(this.threadSubject.getValue(),this.provider.getAgentLoopState(),this.fileChanges,this.currentEphemeralError())),this.deps.onThreadViewStateChange()}syncRetryCountdownTimer(){let J=this.activeError?.retryAt;if(J===void 0||J<=Date.now()){this.clearRetryCountdownTimer();return}if(this.retryCountdownTimer!==null)return;this.retryCountdownTimer=setInterval(()=>{let Z=this.activeError?.retryAt;if(Z===void 0){this.clearRetryCountdownTimer();return}if(this.updateThreadViewStateFromProvider(),Z<=Date.now())this.clearRetryCountdownTimer()},1000)}clearRetryCountdownTimer(){if(this.retryCountdownTimer===null)return;clearInterval(this.retryCountdownTimer),this.retryCountdownTimer=null}currentEphemeralError(){if(!this.activeError)return;let J=this.activeError.retryAt!==void 0?Math.max(0,Math.ceil((this.activeError.retryAt-Date.now())/1000)):void 0,Z=this.activeError.code!==void 0||this.activeError.attempt!==void 0?{code:this.activeError.code,attempt:this.activeError.attempt}:void 0;return{message:this.activeError.message,stack:this.activeError.stack,error:Z,retryCountdownSeconds:J}}}var f90="Loading thread...",HS5="Importing thread";class Lg{deps;recentThreadIDsSubject=new Z4([]);threadTitlesSubject=new Z4({});activeThreadHandleSubject=new Z4(null);allConnectedThreadActivityStatusesSubject=new Z4({});initializationStatusSubject=new Z4({pending:!1,message:f90});threadHandleMap=new Map;draftsByThreadIDSubject=new Z4(new Map);pendingRelationships=new Map;threadBackStack=[];threadForwardStack=[];isThreadActivationInProgress=!1;activeThreadContextID=null;handoffService;queueOnSubmitByDefault=!0;constructor(J){this.deps=J;this.handoffService=nm({configService:this.deps.configService,onFollow:this.followHandoffIfSourceActive})}get recentThreadIDs$(){return this.recentThreadIDsSubject}get threadTitles$(){return this.threadTitlesSubject}get drafts$(){return this.draftsByThreadIDSubject}get threadHandles$(){return this.activeThreadHandleSubject}get allConnectedThreadActivityStatuses$(){return this.allConnectedThreadActivityStatusesSubject}get initializationStatus$(){return this.initializationStatusSubject}get activeThreadHandle(){if(!this.activeThreadContextID)throw Error("No active thread context");let J=this.threadHandleMap.get(this.activeThreadContextID);if(!J)throw Error(`No thread handle for ${this.activeThreadContextID}`);return J}get activeProvider(){if(!this.activeThreadContextID)return;return this.threadHandleMap.get(this.activeThreadContextID)?.provider}hasPendingInitialization(){return this.initializationStatusSubject.getValue().pending}isDTWMode(){return!0}getTransportConnectionState(){return this.activeProvider?.getConnectionInfo()?.state??"disconnected"}getCompactionStatus(){let J=this.activeProvider;if(!J)return;return{compactionState:J.getCompactionState()}}async createThread(J){await this.activateThreadWithNavigation(J,{recordNavigation:!0})}async switchThread(J){await this.activateThreadWithNavigation(J,{recordNavigation:!0})}canNavigateBack(){return this.threadBackStack.length>0}canNavigateForward(){return this.threadForwardStack.length>0}async navigateBack(){if(!this.canNavigateBack())return;let J=this.activeThreadContextID;if(!J)return;let Z=this.threadBackStack.pop();if(!Z)return;this.threadForwardStack.push(J);try{await this.activateThreadWithNavigation(Z,{recordNavigation:!1})}catch(Q){throw this.threadForwardStack.pop(),this.threadBackStack.push(Z),Q}}async navigateForward(){if(!this.canNavigateForward())return;let J=this.activeThreadContextID;if(!J)return;let Z=this.threadForwardStack.pop();if(!Z)return;this.threadBackStack.push(J);try{await this.activateThreadWithNavigation(Z,{recordNavigation:!1})}catch(Q){throw this.threadBackStack.pop(),this.threadForwardStack.push(Z),Q}}followHandoffIfSourceActive=async(J)=>{if(this.activeThreadContextID!==J.sourceThreadID)return;await this.switchThread(J.targetThreadID)};async createHandoff(J,Z){let Y=this.threadHandleMap.get(J)?.provider.getThread()??this.activeProvider?.getThread();if(!Y||Y.id!==J)throw Error("No thread available for handoff");let X=Y.env?.initial?.trees?.[0]?.repository?.url??(await this.deps.getThreadEnvironment()).trees?.[0]?.repository?.url,K=await nm({configService:this.deps.configService}).createHandoffDraft({parentThread:Y,goal:Z.goal,images:Z.images,signal:Z.signal});Z.signal?.throwIfAborted();let z=Z.agentMode??K.sourceAgentMode??Y.agentMode,G={threadID:K.parentThreadID,type:"handoff",...K.parentMessageIndex!==void 0?{messageIndex:K.parentMessageIndex}:{},comment:Z.goal},{threadId:F}=await u90(void 0,this.deps.configService,void 0,{repositoryURL:X,agentMode:z??void 0,relationship:G,executorType:"local-client",signal:Z.signal}),U=BS5(K.content);if(U)this.setDraft(F,U);return this.pendingRelationships.set(F,[{threadID:J,type:"handoff",role:"child",...K.parentMessageIndex!==void 0?{messageIndex:K.parentMessageIndex}:{},createdAt:Date.now(),comment:Z.goal}]),F}async dispose(){for(let J of this.threadHandleMap.values())await J.dispose();this.threadHandleMap.clear(),this.draftsByThreadIDSubject.complete(),this.activeThreadHandleSubject.complete(),this.allConnectedThreadActivityStatusesSubject.complete(),this.initializationStatusSubject.complete(),this.threadTitlesSubject.complete(),this.recentThreadIDsSubject.complete()}async activateThread(J){j.info("[dtw-thread-pool] activateThread:start",{requestedThreadID:J,hasExistingHandle:Boolean(J&&this.threadHandleMap.get(J))});let Z=J?this.threadHandleMap.get(J):void 0;if(Z){let Q=Z.thread$.getValue().id;this.activeThreadContextID=Q,this.activeThreadHandleSubject.next(Z),this.addToRecentThreads(Q),this.syncAllConnectedThreadActivityStatuses(),j.info("[dtw-thread-pool] activateThread:reused",{activeThreadID:Q,handleCount:this.threadHandleMap.size});return}this.isThreadActivationInProgress=!0,this.setInitializationStatus({pending:!0,message:f90});try{let Q=await this.createProvider(J),Y=this.pendingRelationships.get(Q.threadId);if(Y)Q.setRelationships(Y),this.pendingRelationships.delete(Q.threadId);let X=await this.deps.threadService.exclusiveSyncReadWriter(Q.threadId),V=tP({fileChangeTrackerStorage:this.deps.fileChangeTrackerStorage},this.deps.osFileSystem,Q.threadId),K=new uf0(Q,X,{configService:this.deps.configService,toolService:this.deps.toolService,skillService:this.deps.skillService,mcpService:this.deps.mcpService,initialToolDiscovery:this.deps.initialToolDiscovery,fs:V,filesystem:this.deps.osFileSystem,threadService:this.deps.threadService,onThreadViewStateChange:()=>{this.syncAllConnectedThreadActivityStatuses()},handoffService:this.handoffService});this.threadHandleMap.set(Q.threadId,K),K.startProviderSubscription((z)=>{this.applyProviderState(Q.threadId,z)}),await this.applyProviderState(Q.threadId,Q.getThread()),this.activeThreadContextID=Q.threadId,this.activeThreadHandleSubject.next(K),this.addToRecentThreads(Q.threadId),j.info("[dtw-thread-pool] activateThread:created",{activeThreadID:Q.threadId,handleCount:this.threadHandleMap.size})}finally{this.isThreadActivationInProgress=!1,this.setInitializationStatus({pending:!1,message:f90})}}async activateThreadWithNavigation(J,Z){let Q=this.activeThreadContextID;await this.activateThread(J);let Y=this.activeThreadContextID;if(Z.recordNavigation&&Q!==null&&Y!==null&&Q!==Y)this.recordNavigation(Q)}async applyProviderState(J,Z){let Q=this.threadHandleMap.get(J);if(!Q)return;let Y=Q.resolveAuthoritativeThread(Z);if(Q.writeThread(Y),await this.deps.threadService.flushVersion(J,Y.v).catch(()=>{return}),this.threadTitlesSubject.next({...this.threadTitlesSubject.getValue(),[J]:Y.title}),W3(Y)>0)this.clearDraftPrompt(J);this.syncAllConnectedThreadActivityStatuses()}setDraft(J,Z){let Q=new Map(this.draftsByThreadIDSubject.getValue());Q.set(J,Z),this.draftsByThreadIDSubject.next(Q)}clearDraftPrompt(J){let Z=new Map(this.draftsByThreadIDSubject.getValue());if(!Z.delete(J))return;this.draftsByThreadIDSubject.next(Z)}syncAllConnectedThreadActivityStatuses(){let J={};for(let[Z,Q]of this.threadHandleMap.entries())J[Z]=Q.getThreadViewState();this.allConnectedThreadActivityStatusesSubject.next(J)}addToRecentThreads(J){let Z=[...this.recentThreadIDsSubject.getValue()],Q=Z.indexOf(J);if(Q!==-1)Z.splice(Q,1);if(Z.unshift(J),Z.length>50)Z.pop();this.recentThreadIDsSubject.next(Z)}recordNavigation(J){this.threadBackStack.push(J),this.threadForwardStack=[]}async createProvider(J){let Z=J?void 0:(await this.deps.getThreadEnvironment()).trees?.[0]?.repository?.url,Q=J?void 0:"local-client";return x90.create({ampURL:this.deps.ampURL,configService:this.deps.configService,executorType:Q,onLegacyImportStateChange:(Y)=>{if(Y==="importing"){this.setInitializationStatus({pending:!0,message:HS5});return}if(this.isThreadActivationInProgress)this.setInitializationStatus({pending:!0,message:f90})},repositoryURL:Z,threadId:J,workerUrl:process.env.AMP_WORKER_URL})}setInitializationStatus(J){let Z=this.initializationStatusSubject.getValue();if(Z.pending===J.pending&&Z.message===J.message)return;this.initializationStatusSubject.next(J)}}function BS5(J){let Z=J.filter((Y)=>Y.type==="text").map((Y)=>Y.text).join(`
6889
6889
  `),Q=J.filter((Y)=>Y.type==="image");if(!Z&&Q.length===0)return null;return{text:Z,images:Q}}Nf0();import{readFile as Qg5}from"node:fs/promises";import Yg5 from"node:readline";import{setTimeout as Xg5}from"node:timers/promises";H3();a2();aj();_4();wU();H1();import{mkdir as wS5,writeFile as NS5}from"node:fs/promises";import OS5 from"node:path";function ES5(J){let Z=J?.trim();return Z&&Z.length>0?Z:void 0}function LS5(J){let Z=J.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48);return Z.length>0?Z:"trace"}function MS5(J,Z){let Q=new Date(J).toISOString().replace(/[:.]/g,"-");return`${Z?`dtw-trace-${LS5(Z)}`:"dtw-trace"}-${Q}-${crypto.randomUUID().slice(0,8)}`}function xf0(J){let Z=JSON.stringify(J);if(Z===void 0)return null;return JSON.parse(Z)}class ff0{options;traceFilePath;session;constructor(J){this.options=J;let Z=Date.now(),Q=ES5(J.traceName),Y=MS5(Z,Q);this.traceFilePath=OS5.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:xf0(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:xf0(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:xf0(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 wS5(this.options.traceDir,{recursive:!0});let J=JSON.stringify(this.session,null,2);return await NS5(this.traceFilePath,J,"utf-8"),this.traceFilePath}}function nG4(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.gitStatuses().subscribe({next:(Y)=>Z("git_statuses",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()}}}_4();N4();v$();function aC(J,Z){let Q=(G)=>G===R7||G===P3||G===T$||G===H9,Y=new Map;for(let G of J)if(G.type==="toolResult"&&Q(G.toolUse.name))Y.set(G.toolUse.id,{toolUseId:G.toolUse.id,toolName:G.toolUse.name,toolRun:G.toolResult.run});let X=(G,F)=>{let U=Y.get(G)?.toolRun;if(!U||U.status!=="cancelled"||M8(F))return F;return{status:"cancelled",reason:"Parent subagent was cancelled"}},V=Array.from(Y.values()),K={},z={};for(let{toolUseId:G,toolRun:F}of V){let U=[],q;if(F.status==="in-progress"||F.status==="done"||F.status==="error"||F.status==="cancelled")q=F.progress;if(Array.isArray(q)){let D=0;for(let W of q)if(W.tool_uses)for(let H of W.tool_uses){let B=`${G}:progress:${D++}`,w=H.status==="done"&&H.result!==void 0?{status:"done",result:H.result}:{status:H.status},N=H.normalized_name??H.tool_name;U.push({toolUse:NI(N,H.input,B),toolRun:X(G,w)})}}K[G]=U}if(Z){let G=new Map;for(let F of Z.messages){let U=F.parentToolUseId;if(!U)continue;let q=G.get(U)??[];q.push(F),G.set(U,q)}for(let[F,U]of G){let{items:q}=TU({id:Z.id,messages:U},{includeSubagentMessages:!0});z[F]=q.filter((D)=>D.type==="toolResult").map((D)=>({toolUse:D.toolUse,toolRun:X(F,D.toolResult.run)}))}}for(let[G,F]of Object.entries(z))if(F.length>0)K[G]=F;return K}function TU(J,Z){let Q=[],Y=new Set;if(Z?.includeSubagentMessages)for(let[K]of J.messages.entries())Y.add(K);else for(let[K,z]of J.messages.entries())if(!z.parentToolUseId)Y.add(K);let X=new Map,V=new Set;for(let[K,z]of J.messages.entries()){if(!Y.has(K))continue;let G=`${z.role}-${K}`;switch(z.role){case"assistant":{let F=z.state.type==="streaming";for(let q of z.content)if(q.type==="tool_use"){if(X.set(q.id,q),F)V.add(q.id)}if(z.content.some((q)=>q.type==="text"&&q.text.trim()||q.type==="thinking"))Q.push({type:"message",id:G,message:z});for(let q of z.content)if(q.type==="tool_use"){let D=!1;for(let W=K+1;W<J.messages.length;W++){if(!Y.has(W))continue;let H=J.messages[W];if(H){for(let B of H.content)if(B.type==="tool_result"&&B.toolUseID===q.id){D=!0;break}}if(D)break}if(!D)Q.push({type:"toolResult",id:q.id,toolUse:q,toolResult:{type:"tool_result",toolUseID:q.id,run:{status:"in-progress"}}})}break}case"info":{if(z.content.some((U)=>U.type==="manual_bash_invocation"||U.type==="summary"&&U.summary.type==="message"))Q.push({type:"message",id:G,message:z});break}case"user":{let F=z.content.some((U)=>U.type==="text"&&U.text.trim()||U.type==="image");for(let U of z.content)if(U.type==="tool_result"){let q=X.get(U.toolUseID)??k$(J,U.toolUseID);if(!q)throw Error(`(bug) tool use ${U.toolUseID} not found`);Q.push({type:"toolResult",id:U.toolUseID,toolUse:q,toolResult:U})}if(F)Q.push({type:"message",id:G,message:z});break}}}return{items:Q}}i5();a2();_4();wU();H1();class S3{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((V,K)=>{let z=this.neighborMap[K].filter((G)=>this.state[G]).length;if(V)return z===2||z===3;return z===3||z===6}),Z=J.every((V,K)=>V===this.state[K]),Q=this.previousState.length>0&&J.every((V,K)=>V===this.previousState[K]);this.previousState=[...this.state],this.state=J,this.generation++;let Y=J.every((V)=>!V),X=J.filter((V)=>V).length;if(Z||Q||this.generation>=this.maxGenerations||Y||X<2){let V;do V=Array.from({length:8},()=>Math.random()>0.6);while(V.filter((K)=>K).length<3);this.state=V,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)}}class d1 extends X${createElement(){return new bf0(this)}}class bf0 extends EQ{_child;_context;constructor(J){super(J)}get statelessWidget(){return this.widget}get child(){return this._child}get renderObject(){return this._child?.renderObject}mount(){this._context=new fV(this,this.widget),this.rebuild(),this.markMounted()}unmount(){if(this._child)this._child.unmount(),this.removeChild(this._child),this._child=void 0;this._context=void 0,super.unmount()}update(J){if(this.widget===J)return;if(super.update(J),this._context)this._context.widget=J;this.rebuild()}performRebuild(){this.rebuild()}rebuild(){if(!this._context)throw Error("Cannot rebuild unmounted element");let J=this.statelessWidget.build(this._context);if(this._child){if(this._child.widget===J)return;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()}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}}class v4{color;border;constructor(J,Z){this.color=J;this.border=Z}}class u1{top;right;bottom;left;constructor(J,Z,Q,Y){this.top=J;this.right=Z;this.bottom=Q;this.left=Y}static all(J){return new u1(J,J,J,J)}static symmetric(J,Z){return new u1(Z,J,Z,J)}}class v1{color;width;style;constructor(J=M0.black,Z=1,Q="rounded"){this.color=J;this.width=Z;this.style=Q}}class c0 extends N3{width;height;padding;margin;decoration;constraints;constructor({key:J,child:Z,width:Q,height:Y,padding:X,margin:V,decoration:K,constraints:z}={}){super({...J?{key:J}:{},...Z?{child:Z}:{}});this.width=Q,this.height=Y,this.padding=X,this.margin=V,this.decoration=K,this.constraints=z}createElement(){return new aG4(this)}createRenderObject(){return new b90(this.width,this.height,this.padding,this.margin,this.decoration,this.constraints)}updateRenderObject(J){if(!(J instanceof b90))throw Error("renderObject must be an instance of ContainerRenderObject");J.updateProperties(this.width,this.height,this.padding,this.margin,this.decoration,this.constraints)}}class aG4 extends ez{constructor(J){super(J)}mount(){super.mount(),this._updateForceDim()}performRebuild(){super.performRebuild(),this._updateForceDim()}_updateForceDim(){if(!this.renderObject)return;let J=new fV(this,this.widget),Z=LQ.shouldForceDim(J);if(this.renderObject instanceof b90)this.renderObject.setForceDim(Z)}}class b90 extends A4{_width;_height;_padding;_margin;_decoration;_constraints;_forceDim=!1;constructor(J,Z,Q,Y,X,V){super();this._width=J;this._height=Z;this._padding=Q;this._margin=Y;this._decoration=X;this._constraints=V}setForceDim(J){if(this._forceDim!==J)this._forceDim=J,this.markNeedsPaint()}updateProperties(J,Z,Q,Y,X,V){this._width=J,this._height=Z,this._padding=Q,this._margin=Y,this._decoration=X,this._constraints=V,this.markNeedsLayout(),this.markNeedsPaint()}performLayout(){super.performLayout();let J=this._lastConstraints;f4(!!J,"performLayout called without constraints");let Z=this._margin?.horizontal??0,Q=this._margin?.vertical??0,Y=this._padding?.horizontal??0,X=this._padding?.vertical??0,V=this._decoration?.border,K=(V?.left?1:0)+(V?.right?1:0),z=(V?.top?1:0)+(V?.bottom?1:0);this.sendDebugData({margin:this._margin,padding:this._padding,decoration:this._decoration,width:this._width,height:this._height,constraints:this._constraints});let G=this._width!==void 0||this._height!==void 0?this._constraints?.tighten({width:this._width,height:this._height})??M1.tightFor({width:this._width,height:this._height}):this._constraints,F=G?J.enforce(G):J,U=F.maxWidth-Z-Y-K,q=F.maxHeight-Q-X-z,D=new M1(Math.max(0,F.minWidth-Z-Y-K),Math.max(0,U),Math.max(0,F.minHeight-Q-X-z),Math.max(0,q)),W,H;if(this.children.length>0){let N=this.children[0];if(!(N instanceof A4))throw Error("Child must be a RenderBox");N.layout(D),W=N.size.width,H=N.size.height;let O=V?.left?1:0,E=V?.top?1:0,L=(this._margin?.left??0)+O+(this._padding?.left??0),M=(this._margin?.top??0)+E+(this._padding?.top??0);N.setOffset(L,M)}else if(D.maxWidth!==1/0&&D.maxHeight!==1/0)W=D.maxWidth,H=D.maxHeight;else W=D.minWidth,H=D.minHeight;let B,w;if(F.minWidth===F.maxWidth&&isFinite(F.maxWidth))B=F.maxWidth;else B=W+Y+K+Z;if(F.minHeight===F.maxHeight&&isFinite(F.maxHeight))w=F.maxHeight;else w=H+X+z+Q;this.setSize(F.constrain(B,w).width,F.constrain(B,w).height)}getMinIntrinsicWidth(J){if(this._width!==void 0)return this._width;if(this._constraints&&this._constraints.minWidth!==0)return this._constraints.minWidth;let Z=this._margin?.horizontal??0,Q=this._padding?.horizontal??0,Y=this._decoration?.border,X=(Y?.left?1:0)+(Y?.right?1:0),V=0;if(this.children.length>0){let K=this.children[0],z=Math.max(0,J-(this._margin?.vertical??0)-(this._padding?.vertical??0)-((Y?.top?1:0)+(Y?.bottom?1:0)));V=K.getMinIntrinsicWidth(z)}return V+Z+Q+X}getMaxIntrinsicWidth(J){if(this._width!==void 0)return this._width;if(this._constraints&&this._constraints.maxWidth!==1/0)return this._constraints.maxWidth;let Z=this._margin?.horizontal??0,Q=this._padding?.horizontal??0,Y=this._decoration?.border,X=(Y?.left?1:0)+(Y?.right?1:0),V=0;if(this.children.length>0){let K=this.children[0],z=Math.max(0,J-(this._margin?.vertical??0)-(this._padding?.vertical??0)-((Y?.top?1:0)+(Y?.bottom?1:0)));V=K.getMaxIntrinsicWidth(z)}if(V===1/0)return 1/0;return V+Z+Q+X}getMinIntrinsicHeight(J){if(this._height!==void 0)return this._height;if(this._constraints&&this._constraints.minHeight!==0)return this._constraints.minHeight;let Z=this._margin?.vertical??0,Q=this._padding?.vertical??0,Y=this._decoration?.border,X=(Y?.top?1:0)+(Y?.bottom?1:0),V=0;if(this.children.length>0){let z=this.children[0],G=Math.max(0,J-(this._margin?.horizontal??0)-(this._padding?.horizontal??0)-((Y?.left?1:0)+(Y?.right?1:0)));V=z.getMinIntrinsicHeight(G)}let K=V+Z+Q+X;if(this._constraints&&this._constraints.maxHeight!==1/0)return Math.min(K,this._constraints.maxHeight);return K}getMaxIntrinsicHeight(J){if(this._height!==void 0)return this._height;if(this._constraints&&this._constraints.maxHeight!==1/0)return this._constraints.maxHeight;let Z=this._margin?.vertical??0,Q=this._padding?.vertical??0,Y=this._decoration?.border,X=(Y?.top?1:0)+(Y?.bottom?1:0),V=0;if(this.children.length>0){let K=this.children[0],z=Math.max(0,J-(this._margin?.horizontal??0)-(this._padding?.horizontal??0)-((Y?.left?1:0)+(Y?.right?1:0)));V=K.getMaxIntrinsicHeight(z)}if(V===1/0)return 1/0;return V+Z+Q+X}paint(J,Z=0,Q=0){let Y=Math.floor(Z+this.offset.x),X=Math.floor(Q+this.offset.y);if(this._decoration?.color){let V={bg:this._decoration.color};J.fill(Y,X,this.size.width,this.size.height," ",V)}if(this._decoration?.border)this._paintBorder(J,Y,X);super.paint(J,Z,Q)}_paintBorder(J,Z,Q){let Y=this._decoration.border,X=this.size.width,V=this.size.height,K=(W)=>{let H={fg:W};if(this._decoration?.color)H.bg=this._decoration.color;if(this._forceDim)H.dim=!0;return H},z=(W)=>{switch(W){case 1:return"─";case 2:return"━";case 3:return"━";default:return"━"}},G=(W)=>{switch(W){case 1:return"│";case 2:return"┃";case 3:return"┃";default:return"┃"}},F=(W,H)=>{if(W===1)return H?{tl:"╭",tr:"╮",bl:"╰",br:"╯"}:{tl:"┌",tr:"┐",bl:"└",br:"┘"};else return H?{tl:"╭",tr:"╮",bl:"╰",br:"╯"}:{tl:"┏",tr:"┓",bl:"┗",br:"┛"}};if(Y.top){let W=K(Y.top.color),H=z(Y.top.width);for(let B=0;B<X;B++)J.setChar(Z+B,Q,H,W,1)}if(Y.bottom){let W=K(Y.bottom.color),H=z(Y.bottom.width);for(let B=0;B<X;B++)J.setChar(Z+B,Q+V-1,H,W,1)}if(Y.left){let W=K(Y.left.color),H=G(Y.left.width);for(let B=0;B<V;B++)J.setChar(Z,Q+B,H,W,1)}if(Y.right){let W=K(Y.right.color),H=G(Y.right.width);for(let B=0;B<V;B++)J.setChar(Z+X-1,Q+B,H,W,1)}let U=Y.top?.style==="rounded",q=Math.max(Y.top?.width??1,Y.right?.width??1,Y.bottom?.width??1,Y.left?.width??1),D=F(q,U);if(Y.top&&Y.left){let W=K(Y.top.color);J.setChar(Z,Q,D.tl,W,1)}if(Y.top&&Y.right){let W=K(Y.top.color);J.setChar(Z+X-1,Q,D.tr,W,1)}if(Y.bottom&&Y.left){let W=K(Y.bottom.color);J.setChar(Z,Q+V-1,D.bl,W,1)}if(Y.bottom&&Y.right){let W=K(Y.bottom.color);J.setChar(Z+X-1,Q+V-1,D.br,W,1)}}hitTest(J,Z,Q=0,Y=0){return super.hitTest(J,Z,Q,Y)}dispose(){this._decoration=void 0,this._constraints=void 0,this._padding=void 0,this._margin=void 0,super.dispose()}}function Mg(J,Z,Q){return Math.min(Math.max(J,Z),Q)}class Ag{detach(){}toString(){return`${this.constructor.name}#${this.hashCode()}`}hashCode(){return Math.random().toString(36).substr(2,9)}}class ZL extends Ag{flex;fit;constructor(J=0,Z="tight"){super();this.flex=J,this.fit=Z}toString(){return`FlexParentData(flex: ${this.flex}, fit: ${this.fit})`}}class Ig extends YJ{direction;mainAxisAlignment;crossAxisAlignment;mainAxisSize;constructor({key:J,direction:Z,children:Q=[],mainAxisAlignment:Y="start",crossAxisAlignment:X="center",mainAxisSize:V="min"}){super({...J?{key:J}:{},children:Q});this.direction=Z,this.mainAxisAlignment=Y,this.crossAxisAlignment=X,this.mainAxisSize=V}createRenderObject(){return new rG4(this.direction,this.mainAxisAlignment,this.crossAxisAlignment,this.mainAxisSize)}updateRenderObject(J){J.updateProperties(this.direction,this.mainAxisAlignment,this.crossAxisAlignment,this.mainAxisSize)}createElement(){return new oG4(this)}}class oG4 extends O90{constructor(J){super(J)}get flexWidget(){return this.widget}mount(){super.mount(),this._setupChildParentData()}update(J){super.update(J),this._setupChildParentData()}performRebuild(){super.performRebuild(),this._setupChildParentData()}_setupChildParentData(){for(let J of this.children){let Z=J.renderObject;if(Z&&!Z.parentData)Z.parentData=new ZL(0,"tight")}}}class rG4 extends A4{_direction;_mainAxisAlignment;_crossAxisAlignment;_mainAxisSize;constructor(J,Z,Q,Y){super();this._direction=J;this._mainAxisAlignment=Z;this._crossAxisAlignment=Q;this._mainAxisSize=Y}updateProperties(J,Z,Q,Y){this._direction=J,this._mainAxisAlignment=Z,this._crossAxisAlignment=Q,this._mainAxisSize=Y,this.markNeedsLayout()}performLayout(){super.performLayout();let J=this._lastConstraints;f4(!!J,"performLayout called without constraints");let Z=this._direction==="horizontal",Q=[],Y=[];for(let N of this.children){let O=N.parentData;if(O&&O.flex>0)Q.push({child:N,flex:O.flex,fit:O.fit});else Y.push(N)}let X=0,V=0,K,z=Z?J.maxHeight:J.maxWidth;if(isFinite(z))K=z;else{let N=0;for(let O of Y){let E=Z?O.getMaxIntrinsicHeight(1/0):O.getMaxIntrinsicWidth(1/0);N=Math.max(N,E)}K=N}for(let N of Y){let O=this._crossAxisAlignment==="stretch"?K:0,E=Z?new M1(0,1/0,O,K):new M1(O,K,0,1/0);if(N.layout(E),Z)X+=N.size.width,V=Math.max(V,N.size.height);else X+=N.size.height,V=Math.max(V,N.size.width)}let G=Z?J.maxWidth:J.maxHeight,F=Number.isFinite(G)?Math.max(0,G-X):0,U=Q.reduce((N,O)=>N+O.flex,0),q=G<1/0;if(!q&&U>0){for(let{flex:N,fit:O}of Q)if(N>0&&(this._mainAxisSize==="max"||O==="tight")){let E=Z?"row":"column",L=Z?"horizontal":"vertical",M=Z?"width":"height";f4(!1,`RenderFlex children have non-zero flex but incoming ${M} constraints are unbounded.
6890
6890
 
6891
6891
  When a ${E} is in a parent that does not provide a finite ${M} constraint, for example if it is in a ${L} scrollable, it will try to shrink-wrap its children along the ${L} axis. Setting a flex on a child (e.g. using Expanded) indicates that the child is to expand to fill the remaining space in the ${L} direction.
@@ -6942,12 +6942,12 @@ ${Q}`}async function dm5(J,Z){let Q=K1.parse(J).fsPath;if(!Z?.forceExternal&&Z?.
6942
6942
  `).trim()});return Q}function fU(J){return J.replace(rm5,"").replace(sm5,"").replace(om5,"").trim()}function V20(J){let Z=J.split(`
6943
6943
  `);for(let Q=0;Q<Z.length;Q++){let Y=Z[Q]?.trim();if(!Y)continue;let X=Y.match(BH4);if(X?.[1]){let K=X[1].trim();if(K)return{header:K,lineIndex:Q}}let V=Y.match(wH4);if(V?.[1]){let K=V[1].trim();if(K)return{header:K,lineIndex:Q}}break}return{}}function NH4(J,Z){if(Z===void 0)return J;let Q=J.split(`
6944
6944
  `);return Q.splice(Z,1),Q.join(`
6945
- `).trim()}function OH4(J){let Z=fU(J),Q=V20(Z);return NH4(Z,Q.lineIndex)}class CL extends d0{thinkingBlock;expanded;onToggle;isStreaming;isCancelled;constructor({key:J,thinkingBlock:Z,expanded:Q,onToggle:Y,isStreaming:X=!1,isCancelled:V=!1}){super(J?{key:J}:{});this.thinkingBlock=Z,this.expanded=Q,this.onToggle=Y,this.isStreaming=X,this.isCancelled=V}createState(){return new EH4}}class EH4 extends p0{_animationTimer;_spinner=new S3;_localExpanded=!1;get isComplete(){return!this.widget.isStreaming}get expanded(){return this._localExpanded}initState(){if(super.initState(),this._localExpanded=this.widget.expanded??!1,!this.isComplete)this._startAnimation()}didUpdateWidget(J){if(super.didUpdateWidget(J),J.isStreaming&&!this.widget.isStreaming)this._stopAnimation();else if(!J.isStreaming&&this.widget.isStreaming)this._startAnimation();if(J.thinkingBlock.thinking!==this.widget.thinkingBlock.thinking)this.setState(()=>{});if(this.widget.expanded!==void 0&&this.widget.expanded!==J.expanded)this._localExpanded=this.widget.expanded}dispose(){this._stopAnimation(),super.dispose()}_startAnimation(){this._animationTimer=setInterval(()=>{this.setState(()=>{this._spinner.step()})},200)}_stopAnimation(){if(this._animationTimer)clearInterval(this._animationTimer),this._animationTimer=void 0}build(J){let Q=I1.of(J).colorScheme,Y=this.widget.isCancelled,X,V;if(Y)X=Q.warning,V="";else if(this.isComplete)X=Q.success,V="✓ ";else X=Q.accent,V=`${this._spinner.toBraille()} `;let K=fU(this.widget.thinkingBlock.thinking),z=V20(K),G=NH4(K,z.lineIndex),F=G.trim().length>0,U=F?new $0({text:new C(this.expanded?"▼":"▶",new h({color:Q.foreground,dim:!0}))}):null,q=Y?Q.warning:Q.foreground,D=new h({color:Y?X:Q.foreground,dim:!Y}),W=[new C(V,D),new C(z.header??"Thinking",new h({color:q,dim:!Y}))];if(Y)W.push(new C(" (interrupted)",new h({color:Q.warning,italic:!0})));let H=[new $0({text:new C("",void 0,W)})];if(U)H.push(new R0({width:1}),U);let B=new U1({mainAxisSize:"min",children:H}),w={...WT(J),text:new h({color:Q.foreground,dim:!0,italic:!0}),inlineCode:new h({color:Q.foreground,dim:!0,italic:!0,bold:!0}),codeBlock:new h({color:Q.foreground,dim:!0,italic:!0}),link:new h({color:Q.foreground,dim:!0,italic:!0,underline:!0})},N=()=>{if(this.isComplete&&!this.expanded)return;let P=E.map((_)=>{let S=[];if(S.push(new $0({text:new C(_.header,new h({color:Q.foreground,dim:!0,bold:!0}))})),this.expanded)S.push(new i0({padding:C0.vertical(1),child:new a3({markdown:_.content,styleScheme:w})}));return new u0({crossAxisAlignment:"start",children:S})});return new i0({padding:C0.only({left:2}),child:new cV({children:P})})},O=()=>{if(!this.expanded)return;return new i0({padding:C0.only({left:2}),child:new a3({markdown:G,styleScheme:w})})},E=tm5(G),M=E.length>0&&!!E[0]?.header?N():O(),I=[F?new n1({onClick:this._handleHeaderClick.bind(this),cursor:"pointer",child:new u0({crossAxisAlignment:"start",children:[B]})}):new u0({crossAxisAlignment:"start",children:[B]})];if(M)I.push(M);return new u0({mainAxisSize:"min",crossAxisAlignment:"start",children:I})}_handleHeaderClick(J){let Z=!this.expanded;this.setState(()=>{this._localExpanded=Z}),this.widget.onToggle?.(Z)}}var em5=1e4;class MH4{stateSubject;constructor(J){this.stateSubject=new Z4(J)}get state$(){return this.stateSubject}get state(){return this.stateSubject.getValue()}update(J){this.stateSubject.next(J)}}function LH4(J){let Z=new Map;for(let Q of J.messages){if(Q.role!=="user")continue;for(let Y of Q.content){if(Y.type!=="tool_result")continue;if(!("progress"in Y.run))continue;let X=Y.run.progress;if(typeof X==="string"){Z.set(Y.toolUseID,X);continue}if(X&&typeof X==="object"&&"output"in X&&typeof X.output==="string")Z.set(Y.toolUseID,X.output)}}return Z}function $g5(J){if(!J.draft)return null;let Z=TI1(J.draft);if(!Z.text&&Z.images.length===0)return null;return Z}function Jg5(J){if(!J?.meta||typeof J.meta!=="object")return!1;return J.meta.usesDtw===!0}async function Zg5(J,Z){try{let Q=await p3(`/api/durable-thread-workers/${Z}`,{method:"GET"},J);if(!Q.ok)return!1;return(await Q.json()).usesDtw===!0}catch{return!1}}async function um0(J,Z){let{thread:Q,threadMeta:Y}=Z,X=Q?.id??Z.threadID??D3(),V=e8.get(X),K=V?.thread??await J.threadService.get(X);if(Q&&!K){let G=await J.threadService.exclusiveSyncReadWriter(X);G.write(Q),await G.asyncDispose(),K=Q}let z=V??await e8.getOrCreateForThread(J,X);if(Z.agentMode&&!K?.agentMode&&(!K||W3(K)===0))await z.handle({type:"agent-mode",mode:Z.agentMode});if(Y&&Q)await J.threadSyncService?.updateThreadMeta(X,Y);if(Y&&!Q){let G=J.threadService.observe(X).subscribe((F)=>{if(F.messages.length===0)return;G.unsubscribe(),J.threadSyncService?.uploadThread(X).then(()=>J.threadSyncService?.updateThreadMeta(X,Y)).catch(()=>{return})})}if(Z.onFirstAssistantMessage){let G=J.threadService.observe(X).subscribe(async(F)=>{if(h8(F,"assistant"))await Z.onFirstAssistantMessage?.(X),G.unsubscribe()})}return await z.resume(),z}async function AH4(J,Z,Q){await J.validateThreadOwnership?.(Z,Q);let Y=await J.threadService.get(Z)??void 0;if(Jg5(Y)||await Zg5(J.workerDeps.configService,Z))throw new c1(`Thread ${Z} was migrated to the DTW runtime and can't be opened in legacy mode. Update Amp to the latest version, then run with --dtw to continue this thread.`);return um0(J.workerDeps,{threadID:Z,threadMeta:J.switchThreadVisibility?yV(J.switchThreadVisibility):void 0,agentMode:Y?void 0:J.switchThreadAgentMode,thread:Y,onFirstAssistantMessage:J.onFirstAssistantMessage})}async function IH4(J,Z,Q){let Y=Z?await AH4(J,Z,{nonBlockingOwnershipCheck:Q?.nonBlockingOwnershipCheck??!1}):await J.createThread();return new K20(J,Y)}class K20{deps;queueOnSubmitByDefault=!1;restoreTo=this.truncateThread.bind(this);stateTracker;activeThreadHandleSubject;workersByThreadID=new Map;currentWorker;activeThreadHandleValue;activeThreadHandleThreadID;latestStatus={state:"initial"};threadSubscription=null;statusSubscription=null;pendingSkillsSubscription=null;recentThreadIDsSubject=new Z4([]);pendingApprovalsSubject=new Z4([]);pendingSkillsSubject=new Z4([]);threadViewStatesSubject=new Z4({});threadTitlesSubject=new Z4({});draftsByThreadIDSubject=new Z4(new Map);subscriptions=[];workerSubscription=null;disposing=!1;constructor(J,Z){this.deps=J;this.currentWorker=Z,this.stateTracker=new MH4(this.buildPoolState(Z.thread,this.recentThreadIDsSubject.getValue())),this.workersByThreadID.set(Z.thread.id,Z),this.activeThreadHandleValue=this.createHandle(Z.thread.id,Z),this.activeThreadHandleThreadID=Z.thread.id,this.activeThreadHandleSubject=new Z4(this.activeThreadHandleValue),this.refreshDerivedState(Z.thread),this.addToRecentThreads(Z.thread.id),this.subscribeToWorker(Z),this.subscribeToPendingApprovals(),this.subscribeToGlobalWorkerStates(),this.subscribeToWorkerTitles()}get threadHandles$(){return this.activeThreadHandleSubject}get threadState$(){return this.stateTracker.state$.pipe(D1((J)=>J.threadState))}get currentThreadState(){return this.stateTracker.state.threadState}get currentThread(){return this.stateTracker.state.currentThread}get currentThreadID(){return this.stateTracker.state.currentThreadID}get recentThreadIDs$(){return this.recentThreadIDsSubject}get recentThreadIDs(){return this.stateTracker.state.recentThreadIDs}get threadTitles$(){return this.threadTitlesSubject}get drafts$(){return this.draftsByThreadIDSubject}get allConnectedThreadActivityStatuses$(){return this.threadViewStatesSubject}get pendingApprovals$(){return this.pendingApprovalsSubject}get pendingSkills$(){return this.pendingSkillsSubject}getWorkerForExecuteMode(){return this.currentWorker}async createThread(){let J=await this.deps.createThread();this.workersByThreadID.set(J.thread.id,J),this.setCurrentWorker(J)}async switchThread(J){let Z=this.workersByThreadID.get(J)??await AH4(this.deps,J);this.workersByThreadID.set(Z.thread.id,Z),this.setCurrentWorker(Z)}async sendMessage(J){await this.currentWorker.handle({type:"user:message",index:J.editIndex,message:{content:J.content,agentMode:J.agentMode}}),this.maybeMarkLastUserMessageInterrupted(this.currentWorker)}async truncateThread(J){await this.currentWorker.handle({type:"thread:truncate",fromIndex:J})}createHandle(J,Z){let Q=(X)=>{if(this.currentThreadID!==J)throw Error(`ThreadHandle.${X} called for inactive thread ${J}. Current thread is ${this.currentThreadID}.`)},Y=async(X)=>{await Z.handle({type:"thread:truncate",fromIndex:X})};return k90({thread$:this.deps.threadService.observe(J),threadViewState$:this.threadViewStatesSubject.pipe(D1((X)=>X[J]??{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}})),inferenceErrors$:Z.status.pipe(D1((X)=>X.state==="active"?X.ephemeralError:void 0),F5((X)=>X!==void 0)),toolProgressByToolUseID$:this.deps.threadService.observe(J).pipe(D1((X)=>LH4(X))),pendingApprovals$:this.pendingApprovals$,pendingSkills$:this.pendingSkills$,sendMessage:async(X)=>{Q("sendMessage"),await Z.handle({type:"user:message",index:X.editIndex,message:{content:X.content,agentMode:X.agentMode}}),this.maybeMarkLastUserMessageInterrupted(Z)},restoreTo:async(X)=>{Q("restoreTo"),await Y(X)},queueMessage:async(X)=>{Q("queueMessage"),await Z.handle({type:"user:message-queue:enqueue",message:{content:X}})},discardQueuedMessages:async()=>{Q("discardQueuedMessages"),await Z.handle({type:"user:message-queue:discard"})},setTitle:async(X)=>{Q("setTitle"),await Z.handle({type:"title",value:X}),await this.deps.workerDeps.threadSyncService?.sync()},setVisibility:async(X)=>{Q("setVisibility"),await this.deps.workerDeps.threadSyncService?.updateThreadMeta(J,yV(X))},cancelTurn:async()=>{Q("cancelTurn"),await this.maybeCancelActiveTurn(Z)},cancelStreaming:async()=>{Q("cancelStreaming"),await this.maybeCancelActiveTurn(Z)},retryTurn:async()=>{Q("retryTurn"),await Z.retry()},dismissEphemeralError:()=>{Q("dismissEphemeralError"),Z.dismissEphemeralError()},preExecuteMode:async()=>{Q("preExecuteMode"),Z.continueInferenceAfterRejection(!0)},postExecuteMode:async()=>{Q("postExecuteMode");let X=Z.thread.v,V=this.deps.workerDeps.threadSyncService;if(!V)return;await this.deps.threadService.flushVersion(J,X);let K=V.uploadThread(J),z=new Promise((G,F)=>{setTimeout(()=>F(Error("Thread sync timeout")),em5)});await Promise.race([K,z])},setTestEphemeralError:(X)=>{Q("setTestEphemeralError"),Z.setTestEphemeralError(X)},resolveApproval:async(X,V,K)=>{Q("resolveApproval"),this.deps.workerDeps.toolService.resolveApproval(X,V,K)},addPendingSkill:(X)=>{Q("addPendingSkill"),Z.addPendingSkill(X)},removePendingSkill:(X)=>{Q("removePendingSkill"),Z.removePendingSkill(X)},clearPendingSkills:()=>{Q("clearPendingSkills"),Z.clearPendingSkills()},getFilesAffectedByTruncation:async(X)=>{return Q("getFilesAffectedByTruncation"),Z.getFilesAffectedByTruncation(X)},clearPendingNavigation:async()=>{Q("clearPendingNavigation"),await Z.handle({type:"clearPendingNavigation"})},getGuidanceFiles:async(X)=>{let V=this.stateTracker.state.currentThread;if(!V)return[];return(await Zz({filesystem:this.getFilesystemReader(),configService:this.deps.workerDeps.configService,threadService:this.deps.threadService},V,X)).map((z)=>({uri:z.uri,type:z.type}))},invokeBashTool:(X,V)=>{Q("invokeBashTool");let K=Z.invokeBashTool(X,V.abortController.signal,V.hidden);return new v0((z)=>{let G=!1,F=K.subscribe({next:(U)=>z.next(U),error:(U)=>{G=!0,z.error(U)},complete:()=>{G=!0,z.complete()}});return()=>{if(!G)V.abortController.abort();F.unsubscribe()}})}})}maybeMarkLastUserMessageInterrupted(J){let Z=this.stateTracker.state.currentThread;if(!Z)return;if(this.latestStatus.state!=="active")return;let Q=Z.messages.findLast((V)=>V?.role==="assistant"),Y=Q?.state.type==="streaming";if(!(this.latestStatus.inferenceState==="running"||Y))return;if(Y){if(Q.content.some((K)=>K.type==="thinking"&&fU(K.thinking).length>0))return}for(let V=Z.messages.length-1;V>=0;V--){let K=Z.messages[V];if(K?.role==="user"&&!K.interrupted){J.handle({type:"user:message:interrupt",messageIndex:V});let z=[...Z.messages];z[V]={...K,interrupted:!0};let G={...Z,messages:z};this.refreshDerivedState(G),this.updateInterruptedMessage(G,V);break}}}updateInterruptedMessage(J,Z){let Q=J.messages[Z];if(!Q||Q.role!=="user"||Q.interrupted)return;let Y=J.messages.map((X,V)=>{if(V!==Z)return X;return{...X,interrupted:!0}});this.refreshDerivedState({...J,messages:Y})}async queueMessage(J){await this.currentWorker.handle({type:"user:message-queue:enqueue",message:{content:J}})}async discardQueuedMessages(){await this.currentWorker.handle({type:"user:message-queue:discard"})}setTitle=async(J)=>{await this.currentWorker.handle({type:"title",value:J}),await this.deps.workerDeps.threadSyncService?.sync()};setVisibility=async(J)=>{await this.deps.workerDeps.threadSyncService?.updateThreadMeta(this.currentThreadID,yV(J))};async cancelTurn(){await this.maybeCancelActiveTurn(this.currentWorker)}async cancelStreaming(){await this.maybeCancelActiveTurn(this.currentWorker)}async maybeCancelActiveTurn(J){let Z=this.stateTracker.state.currentThread;if(!Z)return;if(this.latestStatus.state!=="active")return;let Y=Z.messages.findLast((K)=>K?.role==="assistant")?.state.type==="streaming",X=this.hasActiveTools(Z);if(!(this.latestStatus.inferenceState==="running"||this.latestStatus.inferenceState==="retrying"||Boolean(Y)||X))return;this.maybeMarkLastUserMessageInterrupted(J),await J.cancel()}hasActiveTools(J){for(let Z of J.messages){if(Z?.role!=="user")continue;for(let Q of Z.content){if(Q.type!=="tool_result")continue;if(Q.run.status==="in-progress"||Q.run.status==="queued")return!0}}return!1}async retryTurn(){await this.currentWorker.retry()}dismissEphemeralError(){this.currentWorker.dismissEphemeralError()}async resolveApproval(J,Z,Q){this.deps.workerDeps.toolService.resolveApproval(J,Z,Q)}addPendingSkill(J){this.currentWorker.addPendingSkill(J)}removePendingSkill(J){this.currentWorker.removePendingSkill(J)}clearPendingSkills(){this.currentWorker.clearPendingSkills()}async getFilesAffectedByTruncation(J){return this.currentWorker.getFilesAffectedByTruncation(J)}invokeBashTool(J,Z){let Q=this.currentWorker.invokeBashTool(J,Z.abortController.signal,Z.hidden);return new v0((Y)=>{let X=!1,V=Q.subscribe({next:(K)=>Y.next(K),error:(K)=>{X=!0,Y.error(K)},complete:()=>{X=!0,Y.complete()}});return()=>{if(!X)Z.abortController.abort();V.unsubscribe()}})}async createHandoff(J,Z){let Q={toolService:this.deps.workerDeps.toolService,configService:this.deps.workerDeps.configService,skillService:this.deps.workerDeps.skillService,getThreadEnvironment:this.deps.workerDeps.getThreadEnvironment,filesystem:this.getFilesystemReader(),threadService:this.deps.workerDeps.threadService};return(await e8.handoff(this.deps.workerDeps,{threadID:J,goal:Z.goal,images:Z.images,mode:"draft",navigate:!1,agentMode:Z.agentMode??void 0,queuedMessages:Z.queuedMessages,clearQueuedMessages:!0,blockIndex:0,buildSystemPromptDeps:Q,signal:Z.signal,filesystem:this.getFilesystemReader()})).threadID}async clearPendingNavigation(){await this.currentWorker.handle({type:"clearPendingNavigation"})}getFilesystemReader(){return this.deps.workerDeps.osFileSystem}setTestEphemeralError(J){this.currentWorker.setTestEphemeralError(J)}setTestRetryCountdown(J){let Z=Math.max(0,Math.ceil((J.retryAt-Date.now())/1000));this.currentWorker.setTestEphemeralError(Object.assign(Error(J.message),{retryCountdownSeconds:Z}))}async getThreadEnvironment(){return await this.deps.workerDeps.getThreadEnvironment()}async dispose(){if(this.disposing)return;this.disposing=!0,this.cleanupSubscriptions(),await Promise.all(Array.from(this.workersByThreadID.values()).map((J)=>J.asyncDispose())),this.workersByThreadID.clear(),this.pendingApprovalsSubject.complete(),this.pendingSkillsSubject.complete(),this.threadViewStatesSubject.complete(),this.threadTitlesSubject.complete(),this.draftsByThreadIDSubject.complete(),this.recentThreadIDsSubject.complete(),this.activeThreadHandleSubject.complete(),this.disposing=!1}async deleteThread(J){if(this.currentWorker.thread.id===J)return;this.workersByThreadID.delete(J),this.clearDraftForThread(J),await e8.dispose(J),await this.deps.threadService.delete(J)}subscribeToWorker(J){this.threadSubscription?.unsubscribe(),this.statusSubscription?.unsubscribe(),this.pendingSkillsSubscription?.unsubscribe(),this.threadSubscription=this.deps.threadService.observePatches(J.thread.id).pipe(Qr()).subscribe((Z)=>{this.refreshDerivedState(Z)}),this.statusSubscription=J.status.subscribe((Z)=>{this.latestStatus=Z,this.updateThreadState(this.stateTracker.state.currentThread)}),this.pendingSkillsSubscription=J.pendingSkills.subscribe((Z)=>{this.pendingSkillsSubject.next(Z)})}subscribeToPendingApprovals(){let J=this.deps.workerDeps.toolService.pendingApprovals$.subscribe((Z)=>{let Q=this.stateTracker.state.currentThreadID,Y=Z.filter((X)=>X.threadId===Q||X.mainThreadId===Q);this.pendingApprovalsSubject.next(Y)});this.subscriptions.push(J)}subscribeToGlobalWorkerStates(){let J=e8.statuses.subscribe((Z)=>{this.threadViewStatesSubject.next(Z)});this.subscriptions.push(J)}subscribeToWorkerTitles(){let J=async(Z)=>{let Q={};await Promise.all(Array.from(Z.keys()).map(async(Y)=>{Q[Y]=await this.deps.threadService.getPrimitiveProperty(Y,"title")??void 0})),this.threadTitlesSubject.next(Q)};this.workerSubscription=e8.workers.subscribe((Z)=>{J(Z)})}setCurrentWorker(J){if(this.workersByThreadID.set(J.thread.id,J),J.thread.id!==this.currentWorker.thread.id)this.addToRecentThreads(J.thread.id);this.currentWorker=J,this.latestStatus={state:"initial"},this.refreshDerivedState(J.thread),this.subscribeToWorker(J)}refreshDerivedState(J){let Z=this.buildPoolState(J,this.recentThreadIDsSubject.getValue());this.threadTitlesSubject.next({...this.threadTitlesSubject.getValue(),[J.id]:J.title??void 0}),this.stateTracker.update(Z),this.updateDraftForThread(J),this.emitActiveThreadHandleIfNeeded()}updateDraftForThread(J){let Z=new Map(this.draftsByThreadIDSubject.getValue()),Q=$g5(J);if(Q&&W3(J)===0)Z.set(J.id,Q);else Z.delete(J.id);this.draftsByThreadIDSubject.next(Z)}clearDraftForThread(J){let Z=new Map(this.draftsByThreadIDSubject.getValue());if(!Z.delete(J))return;this.draftsByThreadIDSubject.next(Z)}buildPoolState(J,Z){let Q=RP(J,this.latestStatus),{items:Y}=TU(J),X=hK({messages:J.messages}),V=Array.isArray(X)?X:[];return{threadState:{viewState:Q,items:Y,todosList:V,mainThread:J,subagentToolsByParentID:aC(Y,J),toolProgressByToolUseID:LH4(J),resolvedTokenUsage:K2(J)},currentThread:J,currentThreadID:J.id,recentThreadIDs:Z}}updateThreadState(J){this.refreshDerivedState(J)}addToRecentThreads(J){let Z=[...this.recentThreadIDsSubject.getValue()],Q=Z.indexOf(J);if(Q!==-1)Z.splice(Q,1);if(Z.unshift(J),Z.length>50)Z.pop();this.recentThreadIDsSubject.next(Z),this.stateTracker.update({...this.stateTracker.state,recentThreadIDs:Z})}cleanupSubscriptions(){this.threadSubscription?.unsubscribe(),this.statusSubscription?.unsubscribe(),this.pendingSkillsSubscription?.unsubscribe(),this.workerSubscription?.unsubscribe(),this.threadSubscription=null,this.statusSubscription=null,this.pendingSkillsSubscription=null,this.workerSubscription=null;for(let J of this.subscriptions)J.unsubscribe();this.subscriptions=[]}emitActiveThreadHandleIfNeeded(){if(this.activeThreadHandleThreadID!==this.currentThreadID)this.activeThreadHandleValue=this.createHandle(this.currentThreadID,this.currentWorker),this.activeThreadHandleThreadID=this.currentThreadID;this.activeThreadHandleSubject.next(this.activeThreadHandleValue)}}function R4(J,Z){let Q=Z?` ${JSON.stringify(Z)}`:"";process.stderr.write(`[thread-pool] ${J}${Q}
6945
+ `).trim()}function OH4(J){let Z=fU(J),Q=V20(Z);return NH4(Z,Q.lineIndex)}class CL extends d0{thinkingBlock;expanded;onToggle;isStreaming;isCancelled;constructor({key:J,thinkingBlock:Z,expanded:Q,onToggle:Y,isStreaming:X=!1,isCancelled:V=!1}){super(J?{key:J}:{});this.thinkingBlock=Z,this.expanded=Q,this.onToggle=Y,this.isStreaming=X,this.isCancelled=V}createState(){return new EH4}}class EH4 extends p0{_animationTimer;_spinner=new S3;_localExpanded=!1;get isComplete(){return!this.widget.isStreaming}get expanded(){return this._localExpanded}initState(){if(super.initState(),this._localExpanded=this.widget.expanded??!1,!this.isComplete)this._startAnimation()}didUpdateWidget(J){if(super.didUpdateWidget(J),J.isStreaming&&!this.widget.isStreaming)this._stopAnimation();else if(!J.isStreaming&&this.widget.isStreaming)this._startAnimation();if(J.thinkingBlock.thinking!==this.widget.thinkingBlock.thinking)this.setState(()=>{});if(this.widget.expanded!==void 0&&this.widget.expanded!==J.expanded)this._localExpanded=this.widget.expanded}dispose(){this._stopAnimation(),super.dispose()}_startAnimation(){this._animationTimer=setInterval(()=>{this.setState(()=>{this._spinner.step()})},200)}_stopAnimation(){if(this._animationTimer)clearInterval(this._animationTimer),this._animationTimer=void 0}build(J){let Q=I1.of(J).colorScheme,Y=this.widget.isCancelled,X,V;if(Y)X=Q.warning,V="";else if(this.isComplete)X=Q.success,V="✓ ";else X=Q.accent,V=`${this._spinner.toBraille()} `;let K=fU(this.widget.thinkingBlock.thinking),z=V20(K),G=NH4(K,z.lineIndex),F=G.trim().length>0,U=F?new $0({text:new C(this.expanded?"▼":"▶",new h({color:Q.foreground,dim:!0}))}):null,q=Y?Q.warning:Q.foreground,D=new h({color:Y?X:Q.foreground,dim:!Y}),W=[new C(V,D),new C(z.header??"Thinking",new h({color:q,dim:!Y}))];if(Y)W.push(new C(" (interrupted)",new h({color:Q.warning,italic:!0})));let H=[new $0({text:new C("",void 0,W)})];if(U)H.push(new R0({width:1}),U);let B=new U1({mainAxisSize:"min",children:H}),w={...WT(J),text:new h({color:Q.foreground,dim:!0,italic:!0}),inlineCode:new h({color:Q.foreground,dim:!0,italic:!0,bold:!0}),codeBlock:new h({color:Q.foreground,dim:!0,italic:!0}),link:new h({color:Q.foreground,dim:!0,italic:!0,underline:!0})},N=()=>{if(this.isComplete&&!this.expanded)return;let P=E.map((_)=>{let S=[];if(S.push(new $0({text:new C(_.header,new h({color:Q.foreground,dim:!0,bold:!0}))})),this.expanded)S.push(new i0({padding:C0.vertical(1),child:new a3({markdown:_.content,styleScheme:w})}));return new u0({crossAxisAlignment:"start",children:S})});return new i0({padding:C0.only({left:2}),child:new cV({children:P})})},O=()=>{if(!this.expanded)return;return new i0({padding:C0.only({left:2}),child:new a3({markdown:G,styleScheme:w})})},E=tm5(G),M=E.length>0&&!!E[0]?.header?N():O(),I=[F?new n1({onClick:this._handleHeaderClick.bind(this),cursor:"pointer",child:new u0({crossAxisAlignment:"start",children:[B]})}):new u0({crossAxisAlignment:"start",children:[B]})];if(M)I.push(M);return new u0({mainAxisSize:"min",crossAxisAlignment:"start",children:I})}_handleHeaderClick(J){let Z=!this.expanded;this.setState(()=>{this._localExpanded=Z}),this.widget.onToggle?.(Z)}}var em5=1e4;class MH4{stateSubject;constructor(J){this.stateSubject=new Z4(J)}get state$(){return this.stateSubject}get state(){return this.stateSubject.getValue()}update(J){this.stateSubject.next(J)}}function LH4(J){let Z=new Map;for(let Q of J.messages){if(Q.role!=="user")continue;for(let Y of Q.content){if(Y.type!=="tool_result")continue;if(!("progress"in Y.run))continue;let X=Y.run.progress;if(typeof X==="string"){Z.set(Y.toolUseID,X);continue}if(X&&typeof X==="object"&&"output"in X&&typeof X.output==="string")Z.set(Y.toolUseID,X.output)}}return Z}function $g5(J){if(!J.draft)return null;let Z=TI1(J.draft);if(!Z.text&&Z.images.length===0)return null;return Z}function Jg5(J){if(!J?.meta||typeof J.meta!=="object")return!1;return J.meta.usesDtw===!0}async function Zg5(J,Z){try{let Q=await p3(`/api/durable-thread-workers/${Z}`,{method:"GET"},J);if(!Q.ok)return!1;return(await Q.json()).usesDtw===!0}catch{return!1}}async function um0(J,Z){let{thread:Q,threadMeta:Y}=Z,X=Q?.id??Z.threadID??D3(),V=e8.get(X),K=V?.thread??await J.threadService.get(X);if(Q&&!K){let G=await J.threadService.exclusiveSyncReadWriter(X);G.write(Q),await G.asyncDispose(),K=Q}let z=V??await e8.getOrCreateForThread(J,X);if(Z.agentMode&&!K?.agentMode&&(!K||W3(K)===0))await z.handle({type:"agent-mode",mode:Z.agentMode});if(Y&&Q)await J.threadSyncService?.updateThreadMeta(X,Y);if(Y&&!Q){let G=J.threadService.observe(X).subscribe((F)=>{if(F.messages.length===0)return;G.unsubscribe(),J.threadSyncService?.uploadThread(X).then(()=>J.threadSyncService?.updateThreadMeta(X,Y)).catch(()=>{return})})}if(Z.onFirstAssistantMessage){let G=J.threadService.observe(X).subscribe(async(F)=>{if(h8(F,"assistant"))await Z.onFirstAssistantMessage?.(X),G.unsubscribe()})}return await z.resume(),z}async function AH4(J,Z,Q){await J.validateThreadOwnership?.(Z,Q);let Y=await J.threadService.get(Z)??void 0;if(Jg5(Y)||await Zg5(J.workerDeps.configService,Z))throw new c1(`Thread ${Z} was migrated to the DTW runtime and can't be opened in legacy mode. Update Amp to the latest version, then run with --dtw to continue this thread.`);return um0(J.workerDeps,{threadID:Z,threadMeta:J.switchThreadVisibility?yV(J.switchThreadVisibility):void 0,agentMode:Y?void 0:J.switchThreadAgentMode,thread:Y,onFirstAssistantMessage:J.onFirstAssistantMessage})}async function IH4(J,Z,Q){let Y=Z?await AH4(J,Z,{nonBlockingOwnershipCheck:Q?.nonBlockingOwnershipCheck??!1}):await J.createThread();return new K20(J,Y)}class K20{deps;queueOnSubmitByDefault=!1;restoreTo=this.truncateThread.bind(this);stateTracker;activeThreadHandleSubject;workersByThreadID=new Map;currentWorker;activeThreadHandleValue;activeThreadHandleThreadID;latestStatus={state:"initial"};threadSubscription=null;statusSubscription=null;pendingSkillsSubscription=null;recentThreadIDsSubject=new Z4([]);pendingApprovalsSubject=new Z4([]);pendingSkillsSubject=new Z4([]);threadViewStatesSubject=new Z4({});threadTitlesSubject=new Z4({});draftsByThreadIDSubject=new Z4(new Map);threadBackStack=[];threadForwardStack=[];subscriptions=[];workerSubscription=null;disposing=!1;constructor(J,Z){this.deps=J;this.currentWorker=Z,this.stateTracker=new MH4(this.buildPoolState(Z.thread,this.recentThreadIDsSubject.getValue())),this.workersByThreadID.set(Z.thread.id,Z),this.activeThreadHandleValue=this.createHandle(Z.thread.id,Z),this.activeThreadHandleThreadID=Z.thread.id,this.activeThreadHandleSubject=new Z4(this.activeThreadHandleValue),this.refreshDerivedState(Z.thread),this.addToRecentThreads(Z.thread.id),this.subscribeToWorker(Z),this.subscribeToPendingApprovals(),this.subscribeToGlobalWorkerStates(),this.subscribeToWorkerTitles()}get threadHandles$(){return this.activeThreadHandleSubject}get threadState$(){return this.stateTracker.state$.pipe(D1((J)=>J.threadState))}get currentThreadState(){return this.stateTracker.state.threadState}get currentThread(){return this.stateTracker.state.currentThread}get currentThreadID(){return this.stateTracker.state.currentThreadID}get recentThreadIDs$(){return this.recentThreadIDsSubject}get recentThreadIDs(){return this.stateTracker.state.recentThreadIDs}get threadTitles$(){return this.threadTitlesSubject}get drafts$(){return this.draftsByThreadIDSubject}get allConnectedThreadActivityStatuses$(){return this.threadViewStatesSubject}get pendingApprovals$(){return this.pendingApprovalsSubject}get pendingSkills$(){return this.pendingSkillsSubject}getWorkerForExecuteMode(){return this.currentWorker}async createThread(){let J=await this.deps.createThread();this.switchToWorker(J,{recordNavigation:!0})}async switchThread(J){await this.switchToThreadByID(J,{recordNavigation:!0})}canNavigateBack(){return this.threadBackStack.length>0}canNavigateForward(){return this.threadForwardStack.length>0}async navigateBack(){if(!this.canNavigateBack())return;let J=this.currentWorker.thread.id,Z=this.threadBackStack.pop();if(!Z)return;this.threadForwardStack.push(J);try{await this.switchToThreadByID(Z,{recordNavigation:!1})}catch(Q){throw this.threadForwardStack.pop(),this.threadBackStack.push(Z),Q}}async navigateForward(){if(!this.canNavigateForward())return;let J=this.currentWorker.thread.id,Z=this.threadForwardStack.pop();if(!Z)return;this.threadBackStack.push(J);try{await this.switchToThreadByID(Z,{recordNavigation:!1})}catch(Q){throw this.threadBackStack.pop(),this.threadForwardStack.push(Z),Q}}async sendMessage(J){await this.currentWorker.handle({type:"user:message",index:J.editIndex,message:{content:J.content,agentMode:J.agentMode}}),this.maybeMarkLastUserMessageInterrupted(this.currentWorker)}async truncateThread(J){await this.currentWorker.handle({type:"thread:truncate",fromIndex:J})}createHandle(J,Z){let Q=(X)=>{if(this.currentThreadID!==J)throw Error(`ThreadHandle.${X} called for inactive thread ${J}. Current thread is ${this.currentThreadID}.`)},Y=async(X)=>{await Z.handle({type:"thread:truncate",fromIndex:X})};return k90({thread$:this.deps.threadService.observe(J),threadViewState$:this.threadViewStatesSubject.pipe(D1((X)=>X[J]??{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}})),inferenceErrors$:Z.status.pipe(D1((X)=>X.state==="active"?X.ephemeralError:void 0),F5((X)=>X!==void 0)),toolProgressByToolUseID$:this.deps.threadService.observe(J).pipe(D1((X)=>LH4(X))),pendingApprovals$:this.pendingApprovals$,pendingSkills$:this.pendingSkills$,sendMessage:async(X)=>{Q("sendMessage"),await Z.handle({type:"user:message",index:X.editIndex,message:{content:X.content,agentMode:X.agentMode}}),this.maybeMarkLastUserMessageInterrupted(Z)},restoreTo:async(X)=>{Q("restoreTo"),await Y(X)},queueMessage:async(X)=>{Q("queueMessage"),await Z.handle({type:"user:message-queue:enqueue",message:{content:X}})},discardQueuedMessages:async()=>{Q("discardQueuedMessages"),await Z.handle({type:"user:message-queue:discard"})},setTitle:async(X)=>{Q("setTitle"),await Z.handle({type:"title",value:X}),await this.deps.workerDeps.threadSyncService?.sync()},setVisibility:async(X)=>{Q("setVisibility"),await this.deps.workerDeps.threadSyncService?.updateThreadMeta(J,yV(X))},cancelTurn:async()=>{Q("cancelTurn"),await this.maybeCancelActiveTurn(Z)},cancelStreaming:async()=>{Q("cancelStreaming"),await this.maybeCancelActiveTurn(Z)},retryTurn:async()=>{Q("retryTurn"),await Z.retry()},dismissEphemeralError:()=>{Q("dismissEphemeralError"),Z.dismissEphemeralError()},preExecuteMode:async()=>{Q("preExecuteMode"),Z.continueInferenceAfterRejection(!0)},postExecuteMode:async()=>{Q("postExecuteMode");let X=Z.thread.v,V=this.deps.workerDeps.threadSyncService;if(!V)return;await this.deps.threadService.flushVersion(J,X);let K=V.uploadThread(J),z=new Promise((G,F)=>{setTimeout(()=>F(Error("Thread sync timeout")),em5)});await Promise.race([K,z])},setTestEphemeralError:(X)=>{Q("setTestEphemeralError"),Z.setTestEphemeralError(X)},resolveApproval:async(X,V,K)=>{Q("resolveApproval"),this.deps.workerDeps.toolService.resolveApproval(X,V,K)},addPendingSkill:(X)=>{Q("addPendingSkill"),Z.addPendingSkill(X)},removePendingSkill:(X)=>{Q("removePendingSkill"),Z.removePendingSkill(X)},clearPendingSkills:()=>{Q("clearPendingSkills"),Z.clearPendingSkills()},getFilesAffectedByTruncation:async(X)=>{return Q("getFilesAffectedByTruncation"),Z.getFilesAffectedByTruncation(X)},clearPendingNavigation:async()=>{Q("clearPendingNavigation"),await Z.handle({type:"clearPendingNavigation"})},getGuidanceFiles:async(X)=>{let V=this.stateTracker.state.currentThread;if(!V)return[];return(await Zz({filesystem:this.getFilesystemReader(),configService:this.deps.workerDeps.configService,threadService:this.deps.threadService},V,X)).map((z)=>({uri:z.uri,type:z.type}))},invokeBashTool:(X,V)=>{Q("invokeBashTool");let K=Z.invokeBashTool(X,V.abortController.signal,V.hidden);return new v0((z)=>{let G=!1,F=K.subscribe({next:(U)=>z.next(U),error:(U)=>{G=!0,z.error(U)},complete:()=>{G=!0,z.complete()}});return()=>{if(!G)V.abortController.abort();F.unsubscribe()}})}})}maybeMarkLastUserMessageInterrupted(J){let Z=this.stateTracker.state.currentThread;if(!Z)return;if(this.latestStatus.state!=="active")return;let Q=Z.messages.findLast((V)=>V?.role==="assistant"),Y=Q?.state.type==="streaming";if(!(this.latestStatus.inferenceState==="running"||Y))return;if(Y){if(Q.content.some((K)=>K.type==="thinking"&&fU(K.thinking).length>0))return}for(let V=Z.messages.length-1;V>=0;V--){let K=Z.messages[V];if(K?.role==="user"&&!K.interrupted){J.handle({type:"user:message:interrupt",messageIndex:V});let z=[...Z.messages];z[V]={...K,interrupted:!0};let G={...Z,messages:z};this.refreshDerivedState(G),this.updateInterruptedMessage(G,V);break}}}updateInterruptedMessage(J,Z){let Q=J.messages[Z];if(!Q||Q.role!=="user"||Q.interrupted)return;let Y=J.messages.map((X,V)=>{if(V!==Z)return X;return{...X,interrupted:!0}});this.refreshDerivedState({...J,messages:Y})}async queueMessage(J){await this.currentWorker.handle({type:"user:message-queue:enqueue",message:{content:J}})}async discardQueuedMessages(){await this.currentWorker.handle({type:"user:message-queue:discard"})}setTitle=async(J)=>{await this.currentWorker.handle({type:"title",value:J}),await this.deps.workerDeps.threadSyncService?.sync()};setVisibility=async(J)=>{await this.deps.workerDeps.threadSyncService?.updateThreadMeta(this.currentThreadID,yV(J))};async cancelTurn(){await this.maybeCancelActiveTurn(this.currentWorker)}async cancelStreaming(){await this.maybeCancelActiveTurn(this.currentWorker)}async maybeCancelActiveTurn(J){let Z=this.stateTracker.state.currentThread;if(!Z)return;if(this.latestStatus.state!=="active")return;let Y=Z.messages.findLast((K)=>K?.role==="assistant")?.state.type==="streaming",X=this.hasActiveTools(Z);if(!(this.latestStatus.inferenceState==="running"||this.latestStatus.inferenceState==="retrying"||Boolean(Y)||X))return;this.maybeMarkLastUserMessageInterrupted(J),await J.cancel()}hasActiveTools(J){for(let Z of J.messages){if(Z?.role!=="user")continue;for(let Q of Z.content){if(Q.type!=="tool_result")continue;if(Q.run.status==="in-progress"||Q.run.status==="queued")return!0}}return!1}async retryTurn(){await this.currentWorker.retry()}dismissEphemeralError(){this.currentWorker.dismissEphemeralError()}async resolveApproval(J,Z,Q){this.deps.workerDeps.toolService.resolveApproval(J,Z,Q)}addPendingSkill(J){this.currentWorker.addPendingSkill(J)}removePendingSkill(J){this.currentWorker.removePendingSkill(J)}clearPendingSkills(){this.currentWorker.clearPendingSkills()}async getFilesAffectedByTruncation(J){return this.currentWorker.getFilesAffectedByTruncation(J)}invokeBashTool(J,Z){let Q=this.currentWorker.invokeBashTool(J,Z.abortController.signal,Z.hidden);return new v0((Y)=>{let X=!1,V=Q.subscribe({next:(K)=>Y.next(K),error:(K)=>{X=!0,Y.error(K)},complete:()=>{X=!0,Y.complete()}});return()=>{if(!X)Z.abortController.abort();V.unsubscribe()}})}async createHandoff(J,Z){let Q={toolService:this.deps.workerDeps.toolService,configService:this.deps.workerDeps.configService,skillService:this.deps.workerDeps.skillService,getThreadEnvironment:this.deps.workerDeps.getThreadEnvironment,filesystem:this.getFilesystemReader(),threadService:this.deps.workerDeps.threadService};return(await e8.handoff(this.deps.workerDeps,{threadID:J,goal:Z.goal,images:Z.images,mode:"draft",navigate:!1,agentMode:Z.agentMode??void 0,queuedMessages:Z.queuedMessages,clearQueuedMessages:!0,blockIndex:0,buildSystemPromptDeps:Q,signal:Z.signal,filesystem:this.getFilesystemReader()})).threadID}async clearPendingNavigation(){await this.currentWorker.handle({type:"clearPendingNavigation"})}getFilesystemReader(){return this.deps.workerDeps.osFileSystem}setTestEphemeralError(J){this.currentWorker.setTestEphemeralError(J)}setTestRetryCountdown(J){let Z=Math.max(0,Math.ceil((J.retryAt-Date.now())/1000));this.currentWorker.setTestEphemeralError(Object.assign(Error(J.message),{retryCountdownSeconds:Z}))}async getThreadEnvironment(){return await this.deps.workerDeps.getThreadEnvironment()}async dispose(){if(this.disposing)return;this.disposing=!0,this.cleanupSubscriptions(),await Promise.all(Array.from(this.workersByThreadID.values()).map((J)=>J.asyncDispose())),this.workersByThreadID.clear(),this.pendingApprovalsSubject.complete(),this.pendingSkillsSubject.complete(),this.threadViewStatesSubject.complete(),this.threadTitlesSubject.complete(),this.draftsByThreadIDSubject.complete(),this.recentThreadIDsSubject.complete(),this.activeThreadHandleSubject.complete(),this.disposing=!1}async deleteThread(J){if(this.currentWorker.thread.id===J)return;this.workersByThreadID.delete(J),this.clearDraftForThread(J),await e8.dispose(J),await this.deps.threadService.delete(J)}subscribeToWorker(J){this.threadSubscription?.unsubscribe(),this.statusSubscription?.unsubscribe(),this.pendingSkillsSubscription?.unsubscribe(),this.threadSubscription=this.deps.threadService.observePatches(J.thread.id).pipe(Qr()).subscribe((Z)=>{this.refreshDerivedState(Z)}),this.statusSubscription=J.status.subscribe((Z)=>{this.latestStatus=Z,this.updateThreadState(this.stateTracker.state.currentThread)}),this.pendingSkillsSubscription=J.pendingSkills.subscribe((Z)=>{this.pendingSkillsSubject.next(Z)})}subscribeToPendingApprovals(){let J=this.deps.workerDeps.toolService.pendingApprovals$.subscribe((Z)=>{let Q=this.stateTracker.state.currentThreadID,Y=Z.filter((X)=>X.threadId===Q||X.mainThreadId===Q);this.pendingApprovalsSubject.next(Y)});this.subscriptions.push(J)}subscribeToGlobalWorkerStates(){let J=e8.statuses.subscribe((Z)=>{this.threadViewStatesSubject.next(Z)});this.subscriptions.push(J)}subscribeToWorkerTitles(){let J=async(Z)=>{let Q={};await Promise.all(Array.from(Z.keys()).map(async(Y)=>{Q[Y]=await this.deps.threadService.getPrimitiveProperty(Y,"title")??void 0})),this.threadTitlesSubject.next(Q)};this.workerSubscription=e8.workers.subscribe((Z)=>{J(Z)})}setCurrentWorker(J){if(this.workersByThreadID.set(J.thread.id,J),J.thread.id!==this.currentWorker.thread.id)this.addToRecentThreads(J.thread.id);this.currentWorker=J,this.latestStatus={state:"initial"},this.refreshDerivedState(J.thread),this.subscribeToWorker(J)}refreshDerivedState(J){let Z=this.buildPoolState(J,this.recentThreadIDsSubject.getValue());this.threadTitlesSubject.next({...this.threadTitlesSubject.getValue(),[J.id]:J.title??void 0}),this.stateTracker.update(Z),this.updateDraftForThread(J),this.emitActiveThreadHandleIfNeeded()}updateDraftForThread(J){let Z=new Map(this.draftsByThreadIDSubject.getValue()),Q=$g5(J);if(Q&&W3(J)===0)Z.set(J.id,Q);else Z.delete(J.id);this.draftsByThreadIDSubject.next(Z)}clearDraftForThread(J){let Z=new Map(this.draftsByThreadIDSubject.getValue());if(!Z.delete(J))return;this.draftsByThreadIDSubject.next(Z)}buildPoolState(J,Z){let Q=RP(J,this.latestStatus),{items:Y}=TU(J),X=hK({messages:J.messages}),V=Array.isArray(X)?X:[];return{threadState:{viewState:Q,items:Y,todosList:V,mainThread:J,subagentToolsByParentID:aC(Y,J),toolProgressByToolUseID:LH4(J),resolvedTokenUsage:K2(J)},currentThread:J,currentThreadID:J.id,recentThreadIDs:Z}}updateThreadState(J){this.refreshDerivedState(J)}addToRecentThreads(J){let Z=[...this.recentThreadIDsSubject.getValue()],Q=Z.indexOf(J);if(Q!==-1)Z.splice(Q,1);if(Z.unshift(J),Z.length>50)Z.pop();this.recentThreadIDsSubject.next(Z),this.stateTracker.update({...this.stateTracker.state,recentThreadIDs:Z})}switchToWorker(J,Z){let Q=this.currentWorker.thread.id;if(this.workersByThreadID.set(J.thread.id,J),this.setCurrentWorker(J),Z.recordNavigation&&J.thread.id!==Q)this.recordNavigation(Q)}async switchToThreadByID(J,Z){let Q=this.workersByThreadID.get(J)??await AH4(this.deps,J);this.switchToWorker(Q,Z)}recordNavigation(J){this.threadBackStack.push(J),this.threadForwardStack=[]}cleanupSubscriptions(){this.threadSubscription?.unsubscribe(),this.statusSubscription?.unsubscribe(),this.pendingSkillsSubscription?.unsubscribe(),this.workerSubscription?.unsubscribe(),this.threadSubscription=null,this.statusSubscription=null,this.pendingSkillsSubscription=null,this.workerSubscription=null;for(let J of this.subscriptions)J.unsubscribe();this.subscriptions=[]}emitActiveThreadHandleIfNeeded(){if(this.activeThreadHandleThreadID!==this.currentThreadID)this.activeThreadHandleValue=this.createHandle(this.currentThreadID,this.currentWorker),this.activeThreadHandleThreadID=this.currentThreadID;this.activeThreadHandleSubject.next(this.activeThreadHandleValue)}}function j4(J,Z){let Q=Z?` ${JSON.stringify(Z)}`:"";process.stderr.write(`[thread-pool] ${J}${Q}
6946
6946
  `)}function RH4(J,Z){process.stdout.write(`${JSON.stringify({type:"state",reason:J,state:Z})}
6947
6947
  `)}function z20(J,Z){process.stdout.write(`${JSON.stringify({type:J,...Z})}
6948
6948
  `)}function Vg5(J){if(!J)return[];return Kg5(J).map((Z)=>Z.trim()).filter((Z)=>Z.length>0)}function Kg5(J){let Z=[],Q="";for(let Y of J){if(Y===";"||Y===`
6949
6949
  `){if(Q)Z.push(Q),Q="";continue}Q+=Y}if(Q)Z.push(Q);return Z}function Dp(J){return[{type:"text",text:J}]}function zg5(J){switch(J){case"public":case"unlisted":case"private":case"workspace":case"group":return J;default:return null}}function xm0(J){if(!J||typeof J!=="object")return"unknown";let Z=J;if(Array.isArray(Z.type))return Z.type.join(" | ");if(Z.type==="array")return`array<${xm0(Z.items)}>`;if(typeof Z.type==="string")return Z.type;if(Array.isArray(Z.enum)&&Z.enum.length>0)return`enum(${Z.enum.map(String).join(", ")})`;let Q=Z.anyOf??Z.oneOf;if(Array.isArray(Q)&&Q.length>0)return Array.from(new Set(Q.map(xm0))).join(" | ");return"unknown"}function Gg5(J){let Z=J.spec.inputSchema,Q=Z.properties??{},Y=new Set(Z.required??[]),X=Object.entries(Q).map(([V,K])=>{let z=K;return{name:V,type:xm0(K),required:Y.has(V),description:z.description}}).sort((V,K)=>V.name.localeCompare(K.name));return{name:J.spec.name,description:J.spec.description,arguments:X}}async function PH4(J){let Y=(await J.configService.getLatest()).settings["experimental.agentMode"]??xK.SMART.key,V=(await E1(J.toolService.getToolsForMode(Y))).map(Gg5).sort((K,z)=>K.name.localeCompare(z.name));process.stdout.write(`${JSON.stringify({type:"tools",agentMode:Y,count:V.length,tools:V},null,2)}
6950
- `)}async function Fg5(J){try{return await Qg5(J,"utf-8")}catch{return J}}async function Ug5(J,Z){return new Promise((Q)=>{let Y=!1,X=null,V=null,K=(G)=>{if(Y)return;if(Y=!0,X)clearTimeout(X);V?.unsubscribe(),Q(G)},z=!0;V=J.subscribe({next:()=>{if(z){z=!1;return}K(!0)}}),X=setTimeout(()=>{K(!1)},Z)})}async function qg5(J,Z){return new Promise((Q)=>{let Y=!1,X=!1,V=null,K=null,z=(G)=>{if(Y)return;if(Y=!0,V)clearTimeout(V);K?.unsubscribe(),Q(G)};K=J.subscribe({next:(G)=>{let F=G.threadState.viewState;if(F.state==="active"&&F.inferenceState==="running")X=!0;if(X&&F.interactionState==="user-message-reply")z(!0)}}),V=setTimeout(()=>{R4(`drain-until-complete timed out after ${Z}ms (sawInferenceRunning=${X})`),z(!1)},Z)})}async function Dg5(J,Z,Q){return new Promise((Y)=>{let X=!1,V=null,K=null,z=(G)=>{if(X)return;if(X=!0,V)clearTimeout(V);K?.unsubscribe(),Y(G)};K=J.subscribe({next:(G)=>{if(G.currentThreadID===Z)z(!0)}}),V=setTimeout(()=>{z(!1)},Q)})}async function jH4(J,Z){let Q=await Z.threadStorage.get(J);if(!Q){let X=await p3(`/api/threads/${J}`,void 0,Z.configService);if(!X.ok)throw new c1(`Thread ${J} does not exist.`,1);Q=await X.json(),await Z.threadStorage.set(J,Q)}let Y=Q.env?.initial?.trees?.find((X)=>X.fs&&X.fs!=="os");if(Y)throw new c1(`Thread uses a remote filesystem (${Y.fs}) that the CLI cannot access.`,1);return Q}function CH4(){return{viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},subagentToolsByParentID:{},toolProgressByToolUseID:new Map,items:[],todosList:[],mainThread:null}}function Wg5(){return{v:1,id:D3(),created:Date.now(),messages:[],nextMessageId:0}}function Hg5(J,Z){if(!J)return CH4();let{items:Q}=TU(J),Y=hK({messages:J.messages}),X=Array.isArray(Y)?Y:[];return{viewState:Z,subagentToolsByParentID:aC(Q,J),toolProgressByToolUseID:new Map,items:Q,todosList:X,mainThread:J}}function Bg5(J){let Z=Wg5(),Q=CH4(),Y=new Z4({threadState:Q,currentThread:Z,currentThreadID:Z.id,recentThreadIDs:[],threadViewStates:{},threadTitles:{},pendingApprovals:[],pendingSkills:[]}),X={thread:null,threadViewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},approvals:[],skills:[]},V=[],K={},z={},G=null,F=()=>{let H=X.thread??Y.getValue().currentThread,B=Hg5(X.thread,X.threadViewState),w=X.thread===null?K:{...K,[X.thread.id]:X.threadViewState};Y.next({threadState:B,currentThread:H,currentThreadID:H.id,recentThreadIDs:V,threadViewStates:w,threadTitles:z,pendingApprovals:X.approvals,pendingSkills:X.skills}),K=w},U=J.threadHandles$.pipe(Q4((H)=>{if(G?.unsubscribe(),G=null,!H)return X={thread:null,threadViewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},approvals:[],skills:[]},F(),v0.of(null);return G=X5(H.thread$,H.threadViewState$,H.pendingApprovals$,H.pendingSkills$).pipe(D1(([B,w,N,O])=>({thread:B,threadViewState:w,approvals:N,skills:O}))).subscribe((B)=>{X=B,F()}),v0.of(null)})).subscribe(()=>{return}),q=J.recentThreadIDs$.subscribe((H)=>{V=H,F()}),D=J.threadTitles$.subscribe((H)=>{z=H,F()});return{state$:Y,subscription:{unsubscribe:()=>{U.unsubscribe(),G?.unsubscribe(),q.unsubscribe(),D.unsubscribe()}}}}async function wg5(J){let Z={configService:J.configService,threadService:J.threadService,threadSyncService:J.threadSyncService,toolService:J.toolService,skillService:J.skillService,getThreadEnvironment:J.getThreadEnvironment,fileChangeTrackerStorage:new JV(J.fileSystem),osFileSystem:J.fileSystem,deleteThread:(V)=>J.threadService.delete(V),generateThreadTitle:r00,mcpService:J.mcpService,pluginService:J.pluginService,getServerStatus:void 0},Q=async(V)=>{let K=V??D3(),z=await e8.getOrCreateForThread(Z,K);return await z.resume(),z};if(J.threadId)await jH4(J.threadId,J);let Y=await Q(J.threadId);return{threadPool:new K20({threadService:J.threadService,workerDeps:Z,createThread:async()=>Q(),validateThreadOwnership:async(V)=>{if(!V||!D8(V))throw new c1(`Invalid thread ID: ${V}`,1);await jH4(V,J)}},Y)}}async function Ng5(J){if(!J.isInternalUser)throw new c1("DTW thread pool harness is only available for Amp employees",1);let Z=new Lg({threadService:J.threadService,configService:J.configService,mcpService:J.mcpService,initialToolDiscovery:Promise.all([J.mcpService.initialized,J.toolboxService.initialized]).then(()=>{return}),toolService:J.toolService,skillService:J.skillService,getThreadEnvironment:J.getThreadEnvironment,fileChangeTrackerStorage:new JV(J.fileSystem),osFileSystem:J.fileSystem,ampURL:J.ampURL});if(J.threadId)await Z.switchThread(J.threadId);else await Z.createThread();return{threadPool:Z,dtwProvider:Z.activeProvider}}async function TH4(J,Z,Q,Y,X){let V=async()=>{let G=await E1(J.threadHandles$);if(!G)throw new c1("No active thread handle. Run create-thread or switch first.",1);return G},K=()=>{let G=Z.getValue();X?.recordAdapterState("command",G),RH4("command",G)},z=async(G,F)=>{if(!G){R4(F?"Usage: shell-hidden <cmd>":"Usage: shell <cmd>");return}let U=await V();if(!U.invokeBashTool){R4("Manual shell invocation is not supported by this thread pool");return}let q=U.invokeBashTool.bind(U),D=new AbortController,W=Date.now(),H=null;await new Promise((B,w)=>{let N=q({cmd:G},{hidden:F,abortController:D}).subscribe({next:(O)=>{H=O},error:(O)=>{N.unsubscribe(),w(O)},complete:()=>{N.unsubscribe(),B()}})}),z20("shell-invocation",{cmd:G,hidden:F,durationMs:Date.now()-W,finalRun:H})};for(let G of Q){if(X?.recordCommand(G),G==="quit"||G==="exit"){K();return}if(G.startsWith("shell-hidden ")||G.startsWith("$$ ")){let F=G.startsWith("shell-hidden ")?G.slice(13).trim():G.slice(3).trim();await z(F,!0),K();continue}if(G.startsWith("shell ")||G.startsWith("$ ")){let F=G.startsWith("shell ")?G.slice(6).trim():G.slice(2).trim();await z(F,!1),K();continue}if(G.startsWith("send ")){let F=await V(),U=G.slice(5).trim();if(!U){R4("Missing message text for send");continue}await F.sendMessage({content:Dp(U)}),K();continue}if(G.startsWith("send-agent ")){let F=await V(),U=G.slice(11).trim(),q=U.indexOf(" "),D=q===-1?U:U.slice(0,q),W=q===-1?"":U.slice(q+1).trim();if(!D||!W){R4("Usage: send-agent <mode> <text>");continue}await F.sendMessage({content:Dp(W),agentMode:D}),K();continue}if(G.startsWith("edit-agent ")){let F=await V(),q=G.slice(11).trim().match(/^(\S+)\s+(\d+)\s+(.*)$/);if(!q){R4("Usage: edit-agent <mode> <index> <text>");continue}let D=q[1]??"",W=Number(q[2]),H=q[3]??"";if(!Number.isFinite(W)||W<0){R4(`Invalid edit index: ${q[2]}`);continue}await F.sendMessage({content:Dp(H),editIndex:W,agentMode:D}),K();continue}if(G.startsWith("edit ")){let F=await V(),q=G.slice(5).trim().match(/^(\d+)\s+(.*)$/);if(!q){R4("Usage: edit <index> <text>");continue}let D=Number(q[1]),W=q[2]??"";if(!Number.isFinite(D)||D<0){R4(`Invalid edit index: ${q[1]}`);continue}await F.sendMessage({content:Dp(W),editIndex:D}),K();continue}if(G.startsWith("truncate ")){let F=await V(),U=G.slice(9).trim(),q=Number(U);if(!Number.isFinite(q)||q<0){R4(`Invalid truncate index: ${U}`);continue}await F.restoreTo(q),K();continue}if(G.startsWith("queue ")){let F=await V(),U=G.slice(6).trim();if(!U){R4("Missing message text for queue");continue}await F.queueMessage(Dp(U)),K();continue}if(G==="discard-queue"){await(await V()).discardQueuedMessages(),K();continue}if(G.startsWith("title ")){let F=await V(),U=G.slice(6).trim();if(!U){R4("Missing title text");continue}if(!F.setTitle){R4("Title update is not supported by this thread pool");continue}await F.setTitle(U),K();continue}if(G==="cancel"){await(await V()).cancelTurn(),K();continue}if(G==="retry"){await(await V()).retryTurn(),K();continue}if(G==="cancel-streaming"){await(await V()).cancelStreaming(),K();continue}if(G==="clear-ephemeral"){(await V()).dismissEphemeralError(),K();continue}if(G.startsWith("test-ephemeral ")){let F=await V(),U=G.slice(15).trim();if(!U){R4("Usage: test-ephemeral <message>");continue}F.setTestEphemeralError?.(Error(U)),K();continue}if(G.startsWith("test-retry ")){let F=await V(),q=G.slice(11).trim().match(/^(\d+)\s+(.*)$/);if(!q){R4("Usage: test-retry <seconds> <message>");continue}let D=Number(q[1]),W=q[2]??"";if(!Number.isFinite(D)||D<0||!W){R4("Usage: test-retry <seconds> <message>");continue}let H=Date.now()+D*1000,B=Math.max(0,Math.ceil((H-Date.now())/1000));F.setTestEphemeralError?.(Object.assign(Error(W),{retryCountdownSeconds:B})),K();continue}if(G.startsWith("handoff ")){let F=G.slice(8).trim();if(!F){R4("Missing goal text for handoff");continue}let U=Z.getValue().currentThread;if(!U){R4("No current thread for handoff");continue}try{let q=await J.createHandoff(U.id,{goal:F,images:[],agentMode:U.agentMode,queuedMessages:void 0,signal:new AbortController().signal});R4("Handoff created, switching",{newThreadID:q}),await J.switchThread(q);let D=await Dg5(Z,q,5000),W=Z.getValue();R4("Switched to handoff thread",{expectedThreadID:q,didSwitch:D,currentThreadID:W.currentThreadID,draft:W.currentThread?.draft?"present":"none",messages:W.currentThread?.messages.length??0})}catch(q){R4(`Handoff failed: ${q}`)}K();continue}if(G.startsWith("switch ")){let F=G.slice(7).trim();if(!F){R4("Missing thread ID for switch");continue}if(!D8(F)){R4(`Invalid thread ID: ${F}`);continue}await J.switchThread(F),K();continue}if(G.startsWith("switch-recent ")){let F=G.slice(14).trim(),U=Number(F);if(!Number.isFinite(U)||U<0){R4(`Invalid switch-recent index: ${F}`);continue}let q=Z.getValue().recentThreadIDs[U];if(!q){R4(`No recent thread at index ${U}`);continue}await J.switchThread(q),K();continue}if(G.startsWith("restore ")){let F=await V(),U=G.slice(8).trim(),q=Number(U);if(!Number.isFinite(q)||q<0){R4(`Invalid restore index: ${U}`);continue}await F.restoreTo(q),K();continue}if(G.startsWith("visibility ")){let F=await V(),U=G.slice(11).trim(),q=zg5(U);if(!q){R4(`Invalid visibility: ${U}`);continue}await F.setVisibility(q),K();continue}if(G.startsWith("files-affected ")){let F=await V(),U=G.slice(15).trim(),q=Number(U);if(!Number.isFinite(q)||q<0){R4(`Invalid files-affected index: ${U}`);continue}let D=await F.getFilesAffectedByTruncation(q);z20("files-affected",{index:q,count:D.length,files:D}),K();continue}if(G==="guidance-files"){let F=await V(),U=new AbortController,q=await F.getGuidanceFiles(U.signal);z20("guidance-files",{count:q.length,files:q}),K();continue}if(G==="clear-pending-navigation"){await(await V()).clearPendingNavigation(),K();continue}if(G==="system-prompt-deps"){let F={toolService:Y.toolService,configService:Y.configService,skillService:Y.skillService,getThreadEnvironment:Y.getThreadEnvironment,filesystem:Y.fileSystem,threadService:Y.threadService};z20("system-prompt-deps",{hasFilesystem:Boolean(F.filesystem),hasConfigService:Boolean(F.configService),hasThreadService:Boolean(F.threadService)}),K();continue}if(G==="list-tools"){await PH4(Y);continue}if(G==="create-thread"){await J.createThread(),K();continue}if(G==="wait"||G.startsWith("wait ")){let F=G.slice(4).trim(),U=F?Number(F):1000;if(!Number.isFinite(U)||U<0){R4(`Invalid wait duration: ${F||"1000"}`);continue}await Xg5(U),K();continue}if(G==="drain"||G.startsWith("drain ")){let F=G.slice(5).trim(),U=F?Number(F):5000;if(!Number.isFinite(U)||U<0){R4(`Invalid drain timeout: ${F||"5000"}`);continue}await Ug5(Z,U),K();continue}if(G==="drain-until-complete"||G.startsWith("drain-until-complete ")){let F=G.slice(20).trim(),U=F?Number(F):120000;if(!Number.isFinite(U)||U<0){R4(`Invalid drain-until-complete timeout: ${F||"120000"}`);continue}await qg5(Z,U),K();continue}R4(`Unknown command: ${G}`)}}async function Og5(J,Z,Q,Y){let X=Yg5.createInterface({input:process.stdin,output:process.stdout,terminal:!0}),V=()=>{R4("Commands:"),R4(" shell <cmd>"),R4(" shell-hidden <cmd>"),R4(" $ <cmd> (alias for shell)"),R4(" $$ <cmd> (alias for shell-hidden)"),R4(" send <text>"),R4(" send-agent <mode> <text>"),R4(" edit <index> <text>"),R4(" truncate <index>"),R4(" queue <text>"),R4(" discard-queue"),R4(" title <text>"),R4(" cancel"),R4(" cancel-streaming"),R4(" retry"),R4(" clear-ephemeral"),R4(" test-ephemeral <message>"),R4(" test-retry <seconds> <message>"),R4(" create-thread"),R4(" handoff <goal>"),R4(" switch <threadId>"),R4(" switch-recent <index>"),R4(" restore <index>"),R4(" visibility <public|unlisted|private|workspace|group>"),R4(" files-affected <index>"),R4(" guidance-files"),R4(" clear-pending-navigation"),R4(" system-prompt-deps"),R4(" list-tools"),R4(" wait [ms]"),R4(" drain [ms]"),R4(" drain-until-complete [ms]"),R4(" quit")};V();for await(let K of X){let z=K.trim();if(!z)continue;if(z==="quit"||z==="exit"){X.close();break}if(z==="help"){V();continue}await TH4(J,Z,[z],Q,Y)}}async function _H4(J){if(J.systemPromptOverride){let q=await Fg5(J.systemPromptOverride);u$("systemPrompt",q)}if(J.listTools){await PH4(J);return}let Z=J.mode==="dtw"?await Ng5(J):await wg5(J),Q=Vg5(J.commands),Y=await E1(Z.threadPool.threadHandles$);if(!Y)throw new c1("No active thread handle available after thread pool initialization.",1);let X=await E1(Y.thread$),V=J.traceDir?new ff0({traceDir:J.traceDir,traceName:J.traceName,runtimeMode:J.mode,threadId:X.id,scriptedCommands:Q}):void 0,K=Z.dtwProvider?nG4(Z.dtwProvider.transport,(q,D)=>{V?.recordProtocolEvent(q,D)}):void 0,z=Z.dtwProvider?.threadChanges().subscribe({next:(q)=>{V?.recordProviderState("update",q)}}),{state$:G,subscription:F}=Bg5(Z.threadPool),U=G.subscribe({next:(q)=>{V?.recordAdapterState("update",q),RH4("update",q)}});try{if(Q.length>0){await TH4(Z.threadPool,G,Q,J,V);return}await Og5(Z.threadPool,G,J,V)}finally{if(U.unsubscribe(),F.unsubscribe(),z?.unsubscribe(),K?.unsubscribe(),V)try{let q=await V.flush();R4("Trace session written",{tracePath:q})}catch(q){R4("Failed to write trace session",{error:q instanceof Error?q.message:String(q)})}await Z.threadPool.dispose()}}h0();_4();H1();_4();function fm0(J,Z,Q){return J+(Z-J)*Q}function G20(J,Z,Q){let Y=Math.max(0,Math.min(1,Q));return{r:Math.round(fm0(J.r,Z.r,Y)),g:Math.round(fm0(J.g,Z.g,Y)),b:Math.round(fm0(J.b,Z.b,Y))}}C7();var lH4=D4(dH4(),1),cH4=20;function cm0(J){let Z=p2(J??"smart")??p2("smart");if(Z?.uiHints?.primaryColor&&Z.uiHints.secondaryColor)return{primary:Z.uiHints.primaryColor,secondary:Z.uiHints.secondaryColor};return{primary:kA1,secondary:yA1}}function lm0(J,Z,Q){let Y=Math.max(0,Math.min(1,J)),{primary:X,secondary:V}=Q??cm0(Z),K=G20(X,V,Y);return{type:"rgb",value:{r:K.r,g:K.g,b:K.b}}}class bH{_noise2D;_seed;constructor(J){this._seed=J??Date.now(),this._noise2D=lH4.makeNoise2D(this._seed)}get seed(){return this._seed}sample(J,Z,Q,Y=1){return(this._noise2D(J/cH4,Z/cH4+Q*Y)+1)*0.5}sampleEdge(J,Z,Q,Y,X=1){let V=J-1,K=Z/2+Q*(Z/2);return this.sample(V,K,Y,X)}getColor(J,Z,Q){return lm0(J,Z,Q)}}var im0=" .:-=+*#%@",bg5=" ",wp=64,iH4=0.5,hH=1,nm0=30,TL=3;class am0 extends d0{width;height;minWidth;minHeight;maxWidth;maxHeight;agentMode;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:V,maxHeight:K,agentMode:z,primaryColor:G,secondaryColor:F,backgroundColor:U,t:q,onFrame:D,fps:W=30,seed:H,glow:B,shockwaves:w,onShockwave:N,onClick:O}){super(J?{key:J}:{});this.width=Z,this.height=Q,this.minWidth=Y??8,this.minHeight=X??8,this.maxWidth=V??40,this.maxHeight=K??40,this.agentMode=z,this.primaryColor=G,this.secondaryColor=F,this.backgroundColor=U,this.t=q,this.onFrame=D,this.fps=W,this.seed=H,this.glow=B,this.shockwaves=w,this.onShockwave=N,this.onClick=O}createState(){return new nH4}}class nH4 extends p0{_t=0;_timer=null;_internalShockwaves=[];_glow;initState(){if(super.initState(),this._glow=this.widget.glow??new bH(this.widget.seed),this.widget.t!==void 0||this.widget.fps===0){this._t=this.widget.t??0;return}if(this.widget.fps==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<hH),this.setState(()=>{})},1000/this.widget.fps)}didUpdateWidget(J){if(super.didUpdateWidget(J),this.widget.glow!==J.glow)this._glow=this.widget.glow??new bH(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=I1.of(J),Q=this.widget.backgroundColor??Z.colorScheme.background,Y=new aH4({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,primaryColor:this.widget.primaryColor,secondaryColor:this.widget.secondaryColor,backgroundColor:Q,glow:this._glow,shockwaves:this.widget.shockwaves??this._internalShockwaves});return new n1({onClick:this.handleClick,child:Y})}}class aH4 extends A2{props;constructor(J,Z){super(Z?{key:Z}:{});this.props=J}createElement(){return new iY(this)}createRenderObject(){return new w20(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.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.primaryColor,this.props.secondaryColor,this.props.backgroundColor,this.props.glow,this.props.shockwaves)}}class w20 extends A4{_width;_height;_minWidth;_minHeight;_maxWidth;_maxHeight;_time;_agentMode;_primaryColor;_secondaryColor;_backgroundColor;_glow;_shockwaves;_palette=[];_paletteSignature="";constructor(J,Z,Q,Y,X,V,K,z,G,F,U,q,D=[]){super();this._width=J;this._height=Z;this._minWidth=Q;this._minHeight=Y;this._maxWidth=X;this._maxHeight=V;this._time=K;this._agentMode=z;this._primaryColor=G;this._secondaryColor=F;this._backgroundColor=U;this._glow=q;this._shockwaves=D;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:wp},(X,V)=>{let K=V/(wp-1);return lm0(K,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,V,K,z,G,F,U,q,D=[]){let W=!1;if(J!==this._width||Z!==this._height||Q!==this._minWidth||Y!==this._minHeight||X!==this._maxWidth||V!==this._maxHeight)this._width=J,this._height=Z,this._minWidth=Q,this._minHeight=Y,this._maxWidth=X,this._maxHeight=V,W=!0;if(this._time=K,this._agentMode=z,this._primaryColor=G,this._secondaryColor=F,this._backgroundColor=U,this._glow=q,this._shockwaves=D,this.getPaletteSignature(z,G,F)!==this._paletteSignature)this.rebuildPalette(z,G,F);if(W)this.markNeedsLayout();this.markNeedsPaint()}performLayout(){let J=this._lastConstraints;f4(!!J,"performLayout called without constraints");let Z=J.constrain(this._width,this._height);this.setSize(Z.width,Z.height),super.performLayout()}paint(J,Z=0,Q=0){let Y=Z+this.offset.x,X=Q+this.offset.y,V=Math.floor(this.size.width),K=Math.floor(this.size.height),z=J.getSize(),G=z.width,F=z.height,U=this._backgroundColor,q=this._palette,D=V/2,W=K/2,H=Math.max(1,V/2-1),B=Math.max(1,K/(2*iH4)-1),w=Math.min(H,B),N=w*w,O=1/N,E=1/iH4,L=this._agentMode==="rush"?2.5:1,M=this._shockwaves.length>0;for(let A=0;A<K;A++){let I=X+A;if(I<0||I>=F)continue;let P=(A-W)*E,_=P*P;if(_>=N)continue;let S=Math.sqrt(N-_),y=Math.max(0,Math.floor(D-S)),m=Math.min(V-1,Math.ceil(D+S));for(let b=y;b<=m;b++){let k=b-D,f=k*k+_;if(f>=N)continue;let p=1-f*O,x=this._glow.sample(b,A,this._time,L)*p;if(x<=0)continue;if(M){let F0=f*O;if(F0<0.9025)for(let z0 of this._shockwaves){let q0=this._time-z0.startTime;if(q0<0||q0>hH)continue;let Q0=b-z0.x,H0=(A-z0.y)*E,i=Q0*Q0+H0*H0,n=q0*nm0,e=Math.max(0,n-TL),J0=n+TL;if(i<e*e||i>J0*J0)continue;let Z0=Math.sqrt(i),K0=Math.abs(Z0-n);if(K0>=TL)continue;let t=1-q0/hH,V0=(1-K0/TL)*t,N0=Math.sqrt(F0),D0=1-F0*N0;x=Math.min(1,x+V0*0.8*D0)}}let r=Math.min(im0.length-1,Math.floor(x*im0.length)),c=im0[r]||bg5,s=Math.min(wp-1,Math.floor(x*wp)),w0=q[s]||q[wp-1],a=Y+b;if(a<0||a>=G)continue;J.setCell(a,I,{char:c,width:1,style:{fg:w0,bg:U}})}}}}function oH4(J,Z,Q,Y){let X=SI1(J),V=Zr(J),K="\x1B[0m",z="\x1B[32m",G="\x1B[33m",F="\x1B[31m",U="\x1B[34m",q="\x1B[90m",D="\x1B[2m",W=[];if(J.archived)W.push("\x1B[90m\x1B[2mArchived\x1B[0m");if(W.push(`${X}`),W.push(`\x1B[34m${Z}\x1B[0m`),V.added>0||V.changed>0||V.deleted>0){let m=[];if(V.added>0)m.push(`\x1B[32m+${V.added}\x1B[0m`);if(V.changed>0)m.push(`\x1B[33m~${V.changed}\x1B[0m`);if(V.deleted>0)m.push(`\x1B[31m-${V.deleted}\x1B[0m`);W.push(`${m.join(" ")}`)}W.push(`\x1B[90mamp threads continue ${J.id}\x1B[0m`);let H=14,B=7,w=new rE(H,B),N=new bH(42),O=new w20(H,B,H,B,H,B,0,J.agentMode??"smart",void 0,void 0,M0.default(),N);O.layout(M1.tight(H,B)),O.paint(w,0,0);let E=w.getBuffer().getCells(),L=0;for(let m=0;m<B;m++)if(E[m].some((b)=>b.char!==" ")){L=m;break}let M=B-1;for(let m=B-1;m>=0;m--)if(E[m].some((b)=>b.char!==" ")){M=m;break}function A(m,b){if(!m)return"";if(m.type==="rgb"){let{r:k,g:f,b:p}=m.value;if(Q.getColorDepth()>=24)return`\x1B[${b?38:48};2;${k};${f};${p}m`;let l=Vf0(k,f,p);return`\x1B[${b?38:48};5;${l}m`}return""}let I=[];if(M>=L)for(let m=L;m<=M;m++){let b="";for(let k=0;k<H;k++){let f=E[m][k],p=f.char,l=A(f.style.fg,!0);b+=l+p+"\x1B[0m"}I.push(b)}let P=I.length,_=Math.max(P,W.length),S=Math.floor((_-P)/2),y=Math.floor((_-W.length)/2);for(let m=0;m<_;m++){let b=" ".repeat(H);if(m>=S&&m<S+P)b=I[m-S];let k=" ",f="";if(m>=y&&m<y+W.length)f=W[m-y];Q.write(b+k+f+`
6950
+ `)}async function Fg5(J){try{return await Qg5(J,"utf-8")}catch{return J}}async function Ug5(J,Z){return new Promise((Q)=>{let Y=!1,X=null,V=null,K=(G)=>{if(Y)return;if(Y=!0,X)clearTimeout(X);V?.unsubscribe(),Q(G)},z=!0;V=J.subscribe({next:()=>{if(z){z=!1;return}K(!0)}}),X=setTimeout(()=>{K(!1)},Z)})}async function qg5(J,Z){return new Promise((Q)=>{let Y=!1,X=!1,V=null,K=null,z=(G)=>{if(Y)return;if(Y=!0,V)clearTimeout(V);K?.unsubscribe(),Q(G)};K=J.subscribe({next:(G)=>{let F=G.threadState.viewState;if(F.state==="active"&&F.inferenceState==="running")X=!0;if(X&&F.interactionState==="user-message-reply")z(!0)}}),V=setTimeout(()=>{j4(`drain-until-complete timed out after ${Z}ms (sawInferenceRunning=${X})`),z(!1)},Z)})}async function Dg5(J,Z,Q){return new Promise((Y)=>{let X=!1,V=null,K=null,z=(G)=>{if(X)return;if(X=!0,V)clearTimeout(V);K?.unsubscribe(),Y(G)};K=J.subscribe({next:(G)=>{if(G.currentThreadID===Z)z(!0)}}),V=setTimeout(()=>{z(!1)},Q)})}async function jH4(J,Z){let Q=await Z.threadStorage.get(J);if(!Q){let X=await p3(`/api/threads/${J}`,void 0,Z.configService);if(!X.ok)throw new c1(`Thread ${J} does not exist.`,1);Q=await X.json(),await Z.threadStorage.set(J,Q)}let Y=Q.env?.initial?.trees?.find((X)=>X.fs&&X.fs!=="os");if(Y)throw new c1(`Thread uses a remote filesystem (${Y.fs}) that the CLI cannot access.`,1);return Q}function CH4(){return{viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},subagentToolsByParentID:{},toolProgressByToolUseID:new Map,items:[],todosList:[],mainThread:null}}function Wg5(){return{v:1,id:D3(),created:Date.now(),messages:[],nextMessageId:0}}function Hg5(J,Z){if(!J)return CH4();let{items:Q}=TU(J),Y=hK({messages:J.messages}),X=Array.isArray(Y)?Y:[];return{viewState:Z,subagentToolsByParentID:aC(Q,J),toolProgressByToolUseID:new Map,items:Q,todosList:X,mainThread:J}}function Bg5(J){let Z=Wg5(),Q=CH4(),Y=new Z4({threadState:Q,currentThread:Z,currentThreadID:Z.id,recentThreadIDs:[],threadViewStates:{},threadTitles:{},pendingApprovals:[],pendingSkills:[]}),X={thread:null,threadViewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},approvals:[],skills:[]},V=[],K={},z={},G=null,F=()=>{let H=X.thread??Y.getValue().currentThread,B=Hg5(X.thread,X.threadViewState),w=X.thread===null?K:{...K,[X.thread.id]:X.threadViewState};Y.next({threadState:B,currentThread:H,currentThreadID:H.id,recentThreadIDs:V,threadViewStates:w,threadTitles:z,pendingApprovals:X.approvals,pendingSkills:X.skills}),K=w},U=J.threadHandles$.pipe(Q4((H)=>{if(G?.unsubscribe(),G=null,!H)return X={thread:null,threadViewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},approvals:[],skills:[]},F(),v0.of(null);return G=X5(H.thread$,H.threadViewState$,H.pendingApprovals$,H.pendingSkills$).pipe(D1(([B,w,N,O])=>({thread:B,threadViewState:w,approvals:N,skills:O}))).subscribe((B)=>{X=B,F()}),v0.of(null)})).subscribe(()=>{return}),q=J.recentThreadIDs$.subscribe((H)=>{V=H,F()}),D=J.threadTitles$.subscribe((H)=>{z=H,F()});return{state$:Y,subscription:{unsubscribe:()=>{U.unsubscribe(),G?.unsubscribe(),q.unsubscribe(),D.unsubscribe()}}}}async function wg5(J){let Z={configService:J.configService,threadService:J.threadService,threadSyncService:J.threadSyncService,toolService:J.toolService,skillService:J.skillService,getThreadEnvironment:J.getThreadEnvironment,fileChangeTrackerStorage:new JV(J.fileSystem),osFileSystem:J.fileSystem,deleteThread:(V)=>J.threadService.delete(V),generateThreadTitle:r00,mcpService:J.mcpService,pluginService:J.pluginService,getServerStatus:void 0},Q=async(V)=>{let K=V??D3(),z=await e8.getOrCreateForThread(Z,K);return await z.resume(),z};if(J.threadId)await jH4(J.threadId,J);let Y=await Q(J.threadId);return{threadPool:new K20({threadService:J.threadService,workerDeps:Z,createThread:async()=>Q(),validateThreadOwnership:async(V)=>{if(!V||!D8(V))throw new c1(`Invalid thread ID: ${V}`,1);await jH4(V,J)}},Y)}}async function Ng5(J){if(!J.isInternalUser)throw new c1("DTW thread pool harness is only available for Amp employees",1);let Z=new Lg({threadService:J.threadService,configService:J.configService,mcpService:J.mcpService,initialToolDiscovery:Promise.all([J.mcpService.initialized,J.toolboxService.initialized]).then(()=>{return}),toolService:J.toolService,skillService:J.skillService,getThreadEnvironment:J.getThreadEnvironment,fileChangeTrackerStorage:new JV(J.fileSystem),osFileSystem:J.fileSystem,ampURL:J.ampURL});if(J.threadId)await Z.switchThread(J.threadId);else await Z.createThread();return{threadPool:Z,dtwProvider:Z.activeProvider}}async function TH4(J,Z,Q,Y,X){let V=async()=>{let G=await E1(J.threadHandles$);if(!G)throw new c1("No active thread handle. Run create-thread or switch first.",1);return G},K=()=>{let G=Z.getValue();X?.recordAdapterState("command",G),RH4("command",G)},z=async(G,F)=>{if(!G){j4(F?"Usage: shell-hidden <cmd>":"Usage: shell <cmd>");return}let U=await V();if(!U.invokeBashTool){j4("Manual shell invocation is not supported by this thread pool");return}let q=U.invokeBashTool.bind(U),D=new AbortController,W=Date.now(),H=null;await new Promise((B,w)=>{let N=q({cmd:G},{hidden:F,abortController:D}).subscribe({next:(O)=>{H=O},error:(O)=>{N.unsubscribe(),w(O)},complete:()=>{N.unsubscribe(),B()}})}),z20("shell-invocation",{cmd:G,hidden:F,durationMs:Date.now()-W,finalRun:H})};for(let G of Q){if(X?.recordCommand(G),G==="quit"||G==="exit"){K();return}if(G.startsWith("shell-hidden ")||G.startsWith("$$ ")){let F=G.startsWith("shell-hidden ")?G.slice(13).trim():G.slice(3).trim();await z(F,!0),K();continue}if(G.startsWith("shell ")||G.startsWith("$ ")){let F=G.startsWith("shell ")?G.slice(6).trim():G.slice(2).trim();await z(F,!1),K();continue}if(G.startsWith("send ")){let F=await V(),U=G.slice(5).trim();if(!U){j4("Missing message text for send");continue}await F.sendMessage({content:Dp(U)}),K();continue}if(G.startsWith("send-agent ")){let F=await V(),U=G.slice(11).trim(),q=U.indexOf(" "),D=q===-1?U:U.slice(0,q),W=q===-1?"":U.slice(q+1).trim();if(!D||!W){j4("Usage: send-agent <mode> <text>");continue}await F.sendMessage({content:Dp(W),agentMode:D}),K();continue}if(G.startsWith("edit-agent ")){let F=await V(),q=G.slice(11).trim().match(/^(\S+)\s+(\d+)\s+(.*)$/);if(!q){j4("Usage: edit-agent <mode> <index> <text>");continue}let D=q[1]??"",W=Number(q[2]),H=q[3]??"";if(!Number.isFinite(W)||W<0){j4(`Invalid edit index: ${q[2]}`);continue}await F.sendMessage({content:Dp(H),editIndex:W,agentMode:D}),K();continue}if(G.startsWith("edit ")){let F=await V(),q=G.slice(5).trim().match(/^(\d+)\s+(.*)$/);if(!q){j4("Usage: edit <index> <text>");continue}let D=Number(q[1]),W=q[2]??"";if(!Number.isFinite(D)||D<0){j4(`Invalid edit index: ${q[1]}`);continue}await F.sendMessage({content:Dp(W),editIndex:D}),K();continue}if(G.startsWith("truncate ")){let F=await V(),U=G.slice(9).trim(),q=Number(U);if(!Number.isFinite(q)||q<0){j4(`Invalid truncate index: ${U}`);continue}await F.restoreTo(q),K();continue}if(G.startsWith("queue ")){let F=await V(),U=G.slice(6).trim();if(!U){j4("Missing message text for queue");continue}await F.queueMessage(Dp(U)),K();continue}if(G==="discard-queue"){await(await V()).discardQueuedMessages(),K();continue}if(G.startsWith("title ")){let F=await V(),U=G.slice(6).trim();if(!U){j4("Missing title text");continue}if(!F.setTitle){j4("Title update is not supported by this thread pool");continue}await F.setTitle(U),K();continue}if(G==="cancel"){await(await V()).cancelTurn(),K();continue}if(G==="retry"){await(await V()).retryTurn(),K();continue}if(G==="cancel-streaming"){await(await V()).cancelStreaming(),K();continue}if(G==="clear-ephemeral"){(await V()).dismissEphemeralError(),K();continue}if(G.startsWith("test-ephemeral ")){let F=await V(),U=G.slice(15).trim();if(!U){j4("Usage: test-ephemeral <message>");continue}F.setTestEphemeralError?.(Error(U)),K();continue}if(G.startsWith("test-retry ")){let F=await V(),q=G.slice(11).trim().match(/^(\d+)\s+(.*)$/);if(!q){j4("Usage: test-retry <seconds> <message>");continue}let D=Number(q[1]),W=q[2]??"";if(!Number.isFinite(D)||D<0||!W){j4("Usage: test-retry <seconds> <message>");continue}let H=Date.now()+D*1000,B=Math.max(0,Math.ceil((H-Date.now())/1000));F.setTestEphemeralError?.(Object.assign(Error(W),{retryCountdownSeconds:B})),K();continue}if(G.startsWith("handoff ")){let F=G.slice(8).trim();if(!F){j4("Missing goal text for handoff");continue}let U=Z.getValue().currentThread;if(!U){j4("No current thread for handoff");continue}try{let q=await J.createHandoff(U.id,{goal:F,images:[],agentMode:U.agentMode,queuedMessages:void 0,signal:new AbortController().signal});j4("Handoff created, switching",{newThreadID:q}),await J.switchThread(q);let D=await Dg5(Z,q,5000),W=Z.getValue();j4("Switched to handoff thread",{expectedThreadID:q,didSwitch:D,currentThreadID:W.currentThreadID,draft:W.currentThread?.draft?"present":"none",messages:W.currentThread?.messages.length??0})}catch(q){j4(`Handoff failed: ${q}`)}K();continue}if(G.startsWith("switch ")){let F=G.slice(7).trim();if(!F){j4("Missing thread ID for switch");continue}if(!D8(F)){j4(`Invalid thread ID: ${F}`);continue}await J.switchThread(F),K();continue}if(G.startsWith("switch-recent ")){let F=G.slice(14).trim(),U=Number(F);if(!Number.isFinite(U)||U<0){j4(`Invalid switch-recent index: ${F}`);continue}let q=Z.getValue().recentThreadIDs[U];if(!q){j4(`No recent thread at index ${U}`);continue}await J.switchThread(q),K();continue}if(G==="back"){if(!J.canNavigateBack()){j4("Cannot navigate back: no previous thread"),K();continue}await J.navigateBack(),K();continue}if(G==="forward"){if(!J.canNavigateForward()){j4("Cannot navigate forward: no next thread"),K();continue}await J.navigateForward(),K();continue}if(G.startsWith("restore ")){let F=await V(),U=G.slice(8).trim(),q=Number(U);if(!Number.isFinite(q)||q<0){j4(`Invalid restore index: ${U}`);continue}await F.restoreTo(q),K();continue}if(G.startsWith("visibility ")){let F=await V(),U=G.slice(11).trim(),q=zg5(U);if(!q){j4(`Invalid visibility: ${U}`);continue}await F.setVisibility(q),K();continue}if(G.startsWith("files-affected ")){let F=await V(),U=G.slice(15).trim(),q=Number(U);if(!Number.isFinite(q)||q<0){j4(`Invalid files-affected index: ${U}`);continue}let D=await F.getFilesAffectedByTruncation(q);z20("files-affected",{index:q,count:D.length,files:D}),K();continue}if(G==="guidance-files"){let F=await V(),U=new AbortController,q=await F.getGuidanceFiles(U.signal);z20("guidance-files",{count:q.length,files:q}),K();continue}if(G==="clear-pending-navigation"){await(await V()).clearPendingNavigation(),K();continue}if(G==="system-prompt-deps"){let F={toolService:Y.toolService,configService:Y.configService,skillService:Y.skillService,getThreadEnvironment:Y.getThreadEnvironment,filesystem:Y.fileSystem,threadService:Y.threadService};z20("system-prompt-deps",{hasFilesystem:Boolean(F.filesystem),hasConfigService:Boolean(F.configService),hasThreadService:Boolean(F.threadService)}),K();continue}if(G==="list-tools"){await PH4(Y);continue}if(G==="create-thread"){await J.createThread(),K();continue}if(G==="wait"||G.startsWith("wait ")){let F=G.slice(4).trim(),U=F?Number(F):1000;if(!Number.isFinite(U)||U<0){j4(`Invalid wait duration: ${F||"1000"}`);continue}await Xg5(U),K();continue}if(G==="drain"||G.startsWith("drain ")){let F=G.slice(5).trim(),U=F?Number(F):5000;if(!Number.isFinite(U)||U<0){j4(`Invalid drain timeout: ${F||"5000"}`);continue}await Ug5(Z,U),K();continue}if(G==="drain-until-complete"||G.startsWith("drain-until-complete ")){let F=G.slice(20).trim(),U=F?Number(F):120000;if(!Number.isFinite(U)||U<0){j4(`Invalid drain-until-complete timeout: ${F||"120000"}`);continue}await qg5(Z,U),K();continue}j4(`Unknown command: ${G}`)}}async function Og5(J,Z,Q,Y){let X=Yg5.createInterface({input:process.stdin,output:process.stdout,terminal:!0}),V=()=>{j4("Commands:"),j4(" shell <cmd>"),j4(" shell-hidden <cmd>"),j4(" $ <cmd> (alias for shell)"),j4(" $$ <cmd> (alias for shell-hidden)"),j4(" send <text>"),j4(" send-agent <mode> <text>"),j4(" edit <index> <text>"),j4(" truncate <index>"),j4(" queue <text>"),j4(" discard-queue"),j4(" title <text>"),j4(" cancel"),j4(" cancel-streaming"),j4(" retry"),j4(" clear-ephemeral"),j4(" test-ephemeral <message>"),j4(" test-retry <seconds> <message>"),j4(" create-thread"),j4(" handoff <goal>"),j4(" switch <threadId>"),j4(" switch-recent <index>"),j4(" back"),j4(" forward"),j4(" restore <index>"),j4(" visibility <public|unlisted|private|workspace|group>"),j4(" files-affected <index>"),j4(" guidance-files"),j4(" clear-pending-navigation"),j4(" system-prompt-deps"),j4(" list-tools"),j4(" wait [ms]"),j4(" drain [ms]"),j4(" drain-until-complete [ms]"),j4(" quit")};V();for await(let K of X){let z=K.trim();if(!z)continue;if(z==="quit"||z==="exit"){X.close();break}if(z==="help"){V();continue}await TH4(J,Z,[z],Q,Y)}}async function _H4(J){if(J.systemPromptOverride){let q=await Fg5(J.systemPromptOverride);u$("systemPrompt",q)}if(J.listTools){await PH4(J);return}let Z=J.mode==="dtw"?await Ng5(J):await wg5(J),Q=Vg5(J.commands),Y=await E1(Z.threadPool.threadHandles$);if(!Y)throw new c1("No active thread handle available after thread pool initialization.",1);let X=await E1(Y.thread$),V=J.traceDir?new ff0({traceDir:J.traceDir,traceName:J.traceName,runtimeMode:J.mode,threadId:X.id,scriptedCommands:Q}):void 0,K=Z.dtwProvider?nG4(Z.dtwProvider.transport,(q,D)=>{V?.recordProtocolEvent(q,D)}):void 0,z=Z.dtwProvider?.threadChanges().subscribe({next:(q)=>{V?.recordProviderState("update",q)}}),{state$:G,subscription:F}=Bg5(Z.threadPool),U=G.subscribe({next:(q)=>{V?.recordAdapterState("update",q),RH4("update",q)}});try{if(Q.length>0){await TH4(Z.threadPool,G,Q,J,V);return}await Og5(Z.threadPool,G,J,V)}finally{if(U.unsubscribe(),F.unsubscribe(),z?.unsubscribe(),K?.unsubscribe(),V)try{let q=await V.flush();j4("Trace session written",{tracePath:q})}catch(q){j4("Failed to write trace session",{error:q instanceof Error?q.message:String(q)})}await Z.threadPool.dispose()}}h0();_4();H1();_4();function fm0(J,Z,Q){return J+(Z-J)*Q}function G20(J,Z,Q){let Y=Math.max(0,Math.min(1,Q));return{r:Math.round(fm0(J.r,Z.r,Y)),g:Math.round(fm0(J.g,Z.g,Y)),b:Math.round(fm0(J.b,Z.b,Y))}}C7();var lH4=D4(dH4(),1),cH4=20;function cm0(J){let Z=p2(J??"smart")??p2("smart");if(Z?.uiHints?.primaryColor&&Z.uiHints.secondaryColor)return{primary:Z.uiHints.primaryColor,secondary:Z.uiHints.secondaryColor};return{primary:kA1,secondary:yA1}}function lm0(J,Z,Q){let Y=Math.max(0,Math.min(1,J)),{primary:X,secondary:V}=Q??cm0(Z),K=G20(X,V,Y);return{type:"rgb",value:{r:K.r,g:K.g,b:K.b}}}class bH{_noise2D;_seed;constructor(J){this._seed=J??Date.now(),this._noise2D=lH4.makeNoise2D(this._seed)}get seed(){return this._seed}sample(J,Z,Q,Y=1){return(this._noise2D(J/cH4,Z/cH4+Q*Y)+1)*0.5}sampleEdge(J,Z,Q,Y,X=1){let V=J-1,K=Z/2+Q*(Z/2);return this.sample(V,K,Y,X)}getColor(J,Z,Q){return lm0(J,Z,Q)}}var im0=" .:-=+*#%@",bg5=" ",wp=64,iH4=0.5,hH=1,nm0=30,TL=3;class am0 extends d0{width;height;minWidth;minHeight;maxWidth;maxHeight;agentMode;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:V,maxHeight:K,agentMode:z,primaryColor:G,secondaryColor:F,backgroundColor:U,t:q,onFrame:D,fps:W=30,seed:H,glow:B,shockwaves:w,onShockwave:N,onClick:O}){super(J?{key:J}:{});this.width=Z,this.height=Q,this.minWidth=Y??8,this.minHeight=X??8,this.maxWidth=V??40,this.maxHeight=K??40,this.agentMode=z,this.primaryColor=G,this.secondaryColor=F,this.backgroundColor=U,this.t=q,this.onFrame=D,this.fps=W,this.seed=H,this.glow=B,this.shockwaves=w,this.onShockwave=N,this.onClick=O}createState(){return new nH4}}class nH4 extends p0{_t=0;_timer=null;_internalShockwaves=[];_glow;initState(){if(super.initState(),this._glow=this.widget.glow??new bH(this.widget.seed),this.widget.t!==void 0||this.widget.fps===0){this._t=this.widget.t??0;return}if(this.widget.fps==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<hH),this.setState(()=>{})},1000/this.widget.fps)}didUpdateWidget(J){if(super.didUpdateWidget(J),this.widget.glow!==J.glow)this._glow=this.widget.glow??new bH(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=I1.of(J),Q=this.widget.backgroundColor??Z.colorScheme.background,Y=new aH4({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,primaryColor:this.widget.primaryColor,secondaryColor:this.widget.secondaryColor,backgroundColor:Q,glow:this._glow,shockwaves:this.widget.shockwaves??this._internalShockwaves});return new n1({onClick:this.handleClick,child:Y})}}class aH4 extends A2{props;constructor(J,Z){super(Z?{key:Z}:{});this.props=J}createElement(){return new iY(this)}createRenderObject(){return new w20(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.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.primaryColor,this.props.secondaryColor,this.props.backgroundColor,this.props.glow,this.props.shockwaves)}}class w20 extends A4{_width;_height;_minWidth;_minHeight;_maxWidth;_maxHeight;_time;_agentMode;_primaryColor;_secondaryColor;_backgroundColor;_glow;_shockwaves;_palette=[];_paletteSignature="";constructor(J,Z,Q,Y,X,V,K,z,G,F,U,q,D=[]){super();this._width=J;this._height=Z;this._minWidth=Q;this._minHeight=Y;this._maxWidth=X;this._maxHeight=V;this._time=K;this._agentMode=z;this._primaryColor=G;this._secondaryColor=F;this._backgroundColor=U;this._glow=q;this._shockwaves=D;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:wp},(X,V)=>{let K=V/(wp-1);return lm0(K,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,V,K,z,G,F,U,q,D=[]){let W=!1;if(J!==this._width||Z!==this._height||Q!==this._minWidth||Y!==this._minHeight||X!==this._maxWidth||V!==this._maxHeight)this._width=J,this._height=Z,this._minWidth=Q,this._minHeight=Y,this._maxWidth=X,this._maxHeight=V,W=!0;if(this._time=K,this._agentMode=z,this._primaryColor=G,this._secondaryColor=F,this._backgroundColor=U,this._glow=q,this._shockwaves=D,this.getPaletteSignature(z,G,F)!==this._paletteSignature)this.rebuildPalette(z,G,F);if(W)this.markNeedsLayout();this.markNeedsPaint()}performLayout(){let J=this._lastConstraints;f4(!!J,"performLayout called without constraints");let Z=J.constrain(this._width,this._height);this.setSize(Z.width,Z.height),super.performLayout()}paint(J,Z=0,Q=0){let Y=Z+this.offset.x,X=Q+this.offset.y,V=Math.floor(this.size.width),K=Math.floor(this.size.height),z=J.getSize(),G=z.width,F=z.height,U=this._backgroundColor,q=this._palette,D=V/2,W=K/2,H=Math.max(1,V/2-1),B=Math.max(1,K/(2*iH4)-1),w=Math.min(H,B),N=w*w,O=1/N,E=1/iH4,L=this._agentMode==="rush"?2.5:1,M=this._shockwaves.length>0;for(let A=0;A<K;A++){let I=X+A;if(I<0||I>=F)continue;let P=(A-W)*E,_=P*P;if(_>=N)continue;let S=Math.sqrt(N-_),y=Math.max(0,Math.floor(D-S)),m=Math.min(V-1,Math.ceil(D+S));for(let b=y;b<=m;b++){let k=b-D,f=k*k+_;if(f>=N)continue;let p=1-f*O,x=this._glow.sample(b,A,this._time,L)*p;if(x<=0)continue;if(M){let F0=f*O;if(F0<0.9025)for(let z0 of this._shockwaves){let q0=this._time-z0.startTime;if(q0<0||q0>hH)continue;let Q0=b-z0.x,H0=(A-z0.y)*E,i=Q0*Q0+H0*H0,n=q0*nm0,e=Math.max(0,n-TL),J0=n+TL;if(i<e*e||i>J0*J0)continue;let Z0=Math.sqrt(i),K0=Math.abs(Z0-n);if(K0>=TL)continue;let t=1-q0/hH,V0=(1-K0/TL)*t,N0=Math.sqrt(F0),D0=1-F0*N0;x=Math.min(1,x+V0*0.8*D0)}}let r=Math.min(im0.length-1,Math.floor(x*im0.length)),c=im0[r]||bg5,s=Math.min(wp-1,Math.floor(x*wp)),w0=q[s]||q[wp-1],a=Y+b;if(a<0||a>=G)continue;J.setCell(a,I,{char:c,width:1,style:{fg:w0,bg:U}})}}}}function oH4(J,Z,Q,Y){let X=SI1(J),V=Zr(J),K="\x1B[0m",z="\x1B[32m",G="\x1B[33m",F="\x1B[31m",U="\x1B[34m",q="\x1B[90m",D="\x1B[2m",W=[];if(J.archived)W.push("\x1B[90m\x1B[2mArchived\x1B[0m");if(W.push(`${X}`),W.push(`\x1B[34m${Z}\x1B[0m`),V.added>0||V.changed>0||V.deleted>0){let m=[];if(V.added>0)m.push(`\x1B[32m+${V.added}\x1B[0m`);if(V.changed>0)m.push(`\x1B[33m~${V.changed}\x1B[0m`);if(V.deleted>0)m.push(`\x1B[31m-${V.deleted}\x1B[0m`);W.push(`${m.join(" ")}`)}W.push(`\x1B[90mamp threads continue ${J.id}\x1B[0m`);let H=14,B=7,w=new rE(H,B),N=new bH(42),O=new w20(H,B,H,B,H,B,0,J.agentMode??"smart",void 0,void 0,M0.default(),N);O.layout(M1.tight(H,B)),O.paint(w,0,0);let E=w.getBuffer().getCells(),L=0;for(let m=0;m<B;m++)if(E[m].some((b)=>b.char!==" ")){L=m;break}let M=B-1;for(let m=B-1;m>=0;m--)if(E[m].some((b)=>b.char!==" ")){M=m;break}function A(m,b){if(!m)return"";if(m.type==="rgb"){let{r:k,g:f,b:p}=m.value;if(Q.getColorDepth()>=24)return`\x1B[${b?38:48};2;${k};${f};${p}m`;let l=Vf0(k,f,p);return`\x1B[${b?38:48};5;${l}m`}return""}let I=[];if(M>=L)for(let m=L;m<=M;m++){let b="";for(let k=0;k<H;k++){let f=E[m][k],p=f.char,l=A(f.style.fg,!0);b+=l+p+"\x1B[0m"}I.push(b)}let P=I.length,_=Math.max(P,W.length),S=Math.floor((_-P)/2),y=Math.floor((_-W.length)/2);for(let m=0;m<_;m++){let b=" ".repeat(H);if(m>=S&&m<S+P)b=I[m-S];let k=" ",f="";if(m>=y&&m<y+W.length)f=W[m-y];Q.write(b+k+f+`
6951
6951
  `)}if(Y)Q.write(`
6952
6952
  \x1B[90m${Y}\x1B[0m
6953
6953
  `)}class om0{constructor(){}isEnabled(J){return!0}consumesKey(J){return!0}toString(){return`${this.constructor.name}()`}}class s4 extends om0{onInvoke;constructor(J){super();this.onInvoke=J}invoke(J){return this.onInvoke(J)}}class rH4{invokeAction(J,Z){let Q=this.findAction(J,Z);if(Q&&Q.enabled)return Q.action.invoke(J);return null}findAction(J,Z){let Q=Z;while(Q){let Y=Q.findAncestorStateOfType(_L);if(Y){let X=Y.getActionForIntent(J);if(X)return{action:X,enabled:X.isEnabled(J)}}Q=Q.parent}return null}}class S9 extends d0{actions;child;dispatcher;constructor({actions:J,child:Z,dispatcher:Q,key:Y}){super({key:Y});this.actions=J,this.child=Z,this.dispatcher=Q}createState(){return new _L}static invoke(J,Z){return S9.of(J).invokeAction(Z,J)}static maybeInvoke(J,Z){try{return S9.invoke(J,Z)}catch{return null}}static find(J,Z){let Q=S9.maybeFind(J,Z);if(!Q){let Y=Z?.constructor.name||"unknown";throw Error(`No action found for intent type: ${Y}`)}return Q}static maybeFind(J,Z){let Q=J;while(Q){let Y=Q.findAncestorStateOfType(_L);if(Y&&Z){let X=Y.getActionForIntent(Z);if(X)return X}Q=Q.parent}return null}static of(J){let Z=J.findAncestorStateOfType(_L);if(!Z)throw Error("No Actions widget found in context");return Z.dispatcher}static handler(J,Z){let Q=S9.of(J).findAction(Z,J);if(Q&&Q.enabled)return()=>Q.action.invoke(Z);return null}}class _L extends p0{dispatcher=new rH4;getActionForIntent(J){let Z=J.constructor;return this.widget.actions.get(Z)}build(J){return this.widget.child}}class Z3{constructor(){}toString(){return`${this.constructor.name}()`}}class Np extends Z3{constructor(){super()}}class Op extends Z3{constructor(){super()}}class Ep extends Z3{constructor(){super()}}class Lp extends Z3{constructor(){super()}}class Mp extends Z3{constructor(){super()}}class Ap extends Z3{constructor(){super()}}class N20 extends Z3{constructor(){super()}}class Ip extends Z3{constructor(){super()}}class HT extends Z3{constructor(){super()}}class jp extends Z3{constructor(){super()}}class Rp extends Z3{constructor(){super()}}class BT extends Z3{direction;constructor(J){super();this.direction=J}toString(){return`NavigateToPromptHistoryIntent(direction: ${this.direction})`}}class Pp extends Z3{constructor(){super()}}class Cp extends Z3{constructor(){super()}}function hg5(J){let Z=[];if(J.ctrlKey)Z.push("ctrl");if(J.metaKey)Z.push("meta");if(J.altKey)Z.push("alt");if(J.shiftKey)Z.push("shift");let Q=J.key.toLowerCase();if(["control","meta","alt","shift"].includes(Q))return"";if(Q===" ")Q="space";return Z.push(Q),Z.join("+")}function sH4(J){let Z=J.toLowerCase().split("+"),Q=Z.pop()||"";return{modifiers:new Set(Z),key:Q}}function tH4(J,Z){let Q=sH4(J),Y=sH4(Z);if(Q.key!==Y.key)return!1;for(let X of Y.modifiers)if(!Q.modifiers.has(X))return!1;if(Y.modifiers.size===0&&Q.modifiers.size>0)return!1;return!0}class O20{sequence;timeout;matchedKeys=[];timeoutId=null;constructor(J,Z={}){this.sequence=J,this.timeout=Z.timeout??2000}getProgress(){return{matched:[...this.matchedKeys],remaining:this.sequence.slice(this.matchedKeys.length)}}isInProgress(){return this.matchedKeys.length>0}reset(){if(this.matchedKeys=[],this.timeoutId)clearTimeout(this.timeoutId),this.timeoutId=null}handleKeyEvent(J){let Z=hg5(J);if(!Z)return"none";let Q=this.matchedKeys.length,Y=this.sequence[Q];if(Y&&tH4(Z,Y)){if(this.matchedKeys.push(Y),this.timeoutId)clearTimeout(this.timeoutId),this.timeoutId=null;if(this.matchedKeys.length===this.sequence.length)return this.reset(),"matched";return this.timeoutId=setTimeout(()=>this.reset(),this.timeout),"progress"}else if(this.matchedKeys.length>0){this.reset();let X=this.sequence[0];if(X&&tH4(Z,X))return this.matchedKeys.push(X),this.timeoutId=setTimeout(()=>this.reset(),this.timeout),"progress"}return"none"}dispose(){this.reset()}toString(){return this.sequence.map((J)=>{return J.replace("ctrl+","C-").replace("meta+","M-").replace("alt+","A-")}).join(" ")}}class E20{sequences;activeSequence=null;constructor(J=new Map){this.sequences=J}handleKeyEvent(J){if(this.activeSequence){let Z=this.activeSequence.handleKeyEvent(J);if(Z==="matched"){let Q=this.sequences.get(this.activeSequence);return this.activeSequence=null,{intent:Q,consumed:!0,progress:null}}else if(Z==="progress")return{intent:null,consumed:!0,progress:this.activeSequence.getProgress()};else this.activeSequence=null}for(let[Z,Q]of this.sequences){let Y=Z.handleKeyEvent(J);if(Y==="matched")return{intent:Q,consumed:!0,progress:null};else if(Y==="progress")return this.activeSequence=Z,{intent:null,consumed:!0,progress:Z.getProgress()}}return{intent:null,consumed:!1,progress:null}}isInProgress(){return this.activeSequence!==null}getProgress(){return this.activeSequence?.getProgress()??null}reset(){this.activeSequence=null;for(let J of this.sequences.keys())J.reset()}dispose(){for(let J of this.sequences.keys())J.dispose()}}function eH4(J){let Z=J.key;if(Z.length===1&&Z>="a"&&Z<="z")return Z;if(J.code!==void 0)return J.code;return Z}class Y4{key;shift;ctrl;alt;meta;constructor(J,Z={}){this.key=J;this.shift=Z.shift??!1,this.ctrl=Z.ctrl??!1,this.alt=Z.alt??!1,this.meta=Z.meta??!1}accepts(J){return eH4(J)===this.key&&J.shiftKey===this.shift&&J.ctrlKey===this.ctrl&&J.altKey===this.alt&&J.metaKey===this.meta}static key(J){return new Y4(J)}static ctrl(J){return new Y4(J,{ctrl:!0})}static shift(J){return new Y4(J,{shift:!0})}static alt(J){return new Y4(J,{alt:!0})}static meta(J){return new Y4(J,{meta:!0})}toString(){let J=[];if(this.meta)J.push("Meta");if(this.ctrl)J.push("Ctrl");if(this.alt)J.push("Alt");if(this.shift)J.push("Shift");return J.length>0?`${J.join("+")}+${this.key}`:this.key}}class rm0{shortcuts=new Map;constructor(J=new Map){this.shortcuts=new Map(J)}handleKeyEvent(J){for(let[Z,Q]of this.shortcuts)if(Z.accepts(J))return Q;return null}addShortcut(J,Z){this.shortcuts.set(J,Z)}removeShortcut(J){return this.shortcuts.delete(J)}getAllShortcuts(){return new Map(this.shortcuts)}copyWith(J){let Z=new Map([...this.shortcuts,...J]);return new rm0(Z)}}class C2 extends d0{shortcuts;child;manager;debugLabel;focusNode;constructor({shortcuts:J,child:Z,manager:Q,debugLabel:Y,focusNode:X,key:V}){super({key:V});this.shortcuts=J,this.child=Z,this.manager=Q,this.debugLabel=Y,this.focusNode=X}createState(){return new $B4}}class $B4 extends p0{manager=null;initState(){if(super.initState(),this.createManager(),this.widget.focusNode)this.widget.focusNode.addKeyHandler(this.handleKeyEvent)}didUpdateWidget(J){if(super.didUpdateWidget(J),J.shortcuts!==this.widget.shortcuts||J.manager!==this.widget.manager)this.createManager()}createManager(){if(this.widget.manager)this.manager=this.widget.manager;else this.manager=new rm0(this.widget.shortcuts)}dispose(){if(this.widget.focusNode)this.widget.focusNode.removeKeyHandler(this.handleKeyEvent);super.dispose()}handleKeyEvent=(J)=>{if(!this.manager)return"ignored";let Z=this.manager.handleKeyEvent(J);if(Z){if(this.invokeIntent(Z)==="handled")return"handled"}return"ignored"};invokeIntent(J){let Z=this.context.findAncestorStateOfType(_L);if(Z){let Q=Z.getActionForIntent(J);if(Q&&Q.isEnabled(J)){if(Q.invoke(J)==="ignored")return null;return"handled"}}return null}build(J){if(this.widget.focusNode)return this.widget.child;else return new k4({onKey:this.handleKeyEvent,autofocus:!1,canRequestFocus:!0,skipTraversal:!1,debugLabel:this.widget.debugLabel,child:this.widget.child})}}h0();h0();class sm0{_selectables=[];_idToSelectable=new Map;_nextId=1;_selection=null;_isDragging=!1;_dragAnchor=null;_orderedCache=[];_orderDirty=!0;_listeners=new Set;_copyHighlightTimer;_clearSelectionTimer;_onCopyCallback;register(J){let Z=this._nextId++;return J.selectableId=Z,this._selectables.push(J),this._idToSelectable.set(Z,J),this._orderDirty=!0,J.onAttachToSelectionArea(this),Z}unregister(J){let Z=this._selectables.indexOf(J);if(Z===-1)return;if(this._selectables.splice(Z,1),this._idToSelectable.delete(J.selectableId),this._orderDirty=!0,this._selection&&this._involvesSelectable(this._selection,J.selectableId))this.clear();J.setSelectedRanges([]),J.onDetachFromSelectionArea(this)}getAllSelectables(){return[...this._selectables]}hitTest(J){this._ensureOrder();for(let Z=this._orderedCache.length-1;Z>=0;Z--){let Q=this._orderedCache[Z];if(Q){let Y=Q.selectable.globalBounds();if(this._pointInRect(J,Y))return Q.selectable}}return null}setSelection(J){if(this._selectionsEqual(this._selection,J))return;this._selection=J,this._propagateSelection(),this._notifyListeners()}getSelection(){return this._selection}comparePositions(J,Z){return this._compareDocumentPositions(J,Z)}clear(){this.setSelection(null),this._isDragging=!1,this._dragAnchor=null}selectAll(){if(this._selectables.length===0){this.clear();return}this._ensureOrder();let J=this._orderedCache[0],Z=this._orderedCache[this._orderedCache.length-1];if(!J||!Z){this.clear();return}this.setSelection({anchor:{selectableId:J.selectable.selectableId,offset:0},extent:{selectableId:Z.selectable.selectableId,offset:Z.selectable.textLength()}})}copySelection(){if(!this._selection)return"";let J=this._splitSelectionBySelectable(this._selection),Z=[];this._ensureOrder();for(let{selectable:Q}of this._orderedCache){let Y=J.get(Q.selectableId);if(!Y||Y.length===0)continue;let X=[];for(let V of Y){let K=Q.getText(V);if(K)X.push(K)}if(X.length>0){if(Z.length>0&&!Z[Z.length-1]?.endsWith(`
@@ -7286,7 +7286,7 @@ Ctrl-X, Y, Z to unlock`;if(D){let b=F.text.replace(/`([^`]+)`/g,"$1")+`
7286
7286
  `),V=[];for(let K=0;K<X.length;K++){let F=X[K].replace(/\b(SELECT|FROM|WHERE|GROUP BY|ORDER BY|HAVING|LIMIT|JOIN|LEFT JOIN|RIGHT JOIN|INNER JOIN|ON|AND|OR|AS|IN|NOT|NULL|IS|BETWEEN|LIKE|EXISTS|UNION|DISTINCT|COUNT|SUM|AVG|MIN|MAX|DATE|TIMESTAMP_TRUNC|TIMESTAMP_SUB|CURRENT_TIMESTAMP|INTERVAL|CASE|WHEN|THEN|ELSE|END|WITH|INSERT|UPDATE|DELETE|SET|VALUES|INTO|CREATE|ALTER|DROP|TRUE|FALSE|ASC|DESC)\b/gi,"\x00$1\x01").split(/(\x00[^\x01]+\x01)/);for(let U of F)if(U.startsWith("\x00")&&U.endsWith("\x01"))V.push(new C(U.slice(1,-1),new h({color:Y.app.keybind,bold:!0})));else V.push(new C(U,new h({color:Q.colorScheme.foreground})));if(K<X.length-1)V.push(new C(`
7287
7287
  `))}return new c0({decoration:{color:Q.colorScheme.background,border:u1.all(new v1(Y.app.keybind,1,"rounded"))},child:new i0({padding:C0.symmetric(0,1),child:new $0({text:new C(void 0,void 0,V)})})})}}class eg0 extends A2{chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=_$0}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new sg0({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 bN4(J,Z,Q,Y,X,V,K){if(V<=0)return null;switch(J){case"horizontal-bar":{let z=Q;return z>=0&&z<V?z:null}case"bar":case"stacked-bar":{let z=K?i8:0,G=Y-z;if(G<=0)return null;let F=Z-z;if(F<0||F>=G)return null;let U=Math.max(1,Math.floor(G/V)),q=Math.floor(F/U);return q>=0&&q<V?q:null}case"line":case"sparkline":case"stacked-area":{let z=K?i8:0,G=Y-z;if(G<=0)return null;let F=Math.max(0,Math.min(G-1,Z-z));if(V===1)return 0;let U=G/(V-1),q=Math.round(F/U);return Math.max(0,Math.min(V-1,q))}default:return null}}function _i5(J,Z,Q,Y,X,V,K,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=V?i8:0,U=Q-F,q=Y-(V?G:0);if(U<=0||q<=0)return null;let D=Math.max(1,Math.floor(U/X)),W=F+Z*D+Math.floor(D/2),H=z>0?K/z:0,B=Math.round((1-H)*(q-1));return{x:W,y:B}}case"line":case"sparkline":case"stacked-area":{let F=V?i8:0,U=Q-F,q=Y-(V?G:0);if(U<=0||q<=0)return null;let D=X>1?F+Math.round(Z/(X-1)*(U-1)):F+Math.floor(U/2),W=z>0?K/z:0,H=Math.round((1-W)*(q-1));return{x:D,y:H}}default:return null}}function Si5(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 vi5(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 V=J.label.length,K=0;for(let z of Q){let G=z.points[Z];if(!G)continue;K+=G.value;let F=2+z.name.length+2+Y(G.value).length;V=Math.max(V,F)}if(X){let z=9+Y(K).length;V=Math.max(V,z)}return V}function ki5(J,Z,Q,Y,X,V,K){let z;try{let H=I1.of(J),B=f0.of(J);z={foreground:H.colorScheme.foreground,background:H.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 h({color:z.foreground,bold:!0}),F=new h({color:z.foreground}),U=new h({color:z.foreground,dim:!0}),q=[],D=new h({color:z.foreground,underline:!0}),W=(H,B)=>new C(B,D,void 0,D90(H),()=>{w8(J,H)});if(Y.length<=1){if(q.push(new C(`${Z.label}: `,G)),Z.link)q.push(W(Z.link,V(Z.value)));else q.push(new C(V(Z.value),F));if(Z.meta)q.push(new C(` (${Z.meta})`,U))}else{let H=K==="stacked-bar"||K==="stacked-area";q.push(new C(`${Z.label}
7288
7288
  `,G));let B=0;for(let w=0;w<Y.length;w++){let N=Y[w],O=N.points[Q];if(!O)continue;B+=O.value;let E=N.color??X[w%X.length]??z.foreground;if(q.push(new C("● ",new h({color:E}))),q.push(new C(`${N.name}: `,U)),O.link)q.push(W(O.link,V(O.value)));else q.push(new C(V(O.value),F));if(w<Y.length-1||H)q.push(new C(`
7289
- `))}if(H)q.push(new C(" ",U)),q.push(new C("Total: ",U)),q.push(new C(V(B),F))}return new c0({decoration:{color:z.background,border:u1.all(new v1(z.border,1,"rounded"))},child:new $0({text:new C(void 0,void 0,q)})})}ow();h0();e9();import{execSync as zn5}from"node:child_process";KN();C7();H3();P7();sb();bX();a2();h$();xX();OE();_4();Gx();qk();H1();var xO4=D4(CF(),1);import{writeFile as SO4}from"fs/promises";import vO4 from"path";h0();a2();class $p0{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.1773462612-g20fbe1"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await Ct(Z,this.configService)}catch(Z){j.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 sH extends d0{props;constructor(J){super();this.props=J}createState(){return new hN4}}class hN4 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 mN4 extends p0{controller=new i7;focusNode=new r4({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,V=this.controller.text.trim().length>0,K=!X||V,z=u1.all(new v1(Q.foreground,1,"solid")),G=new FJ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(W)=>{let H=W.trim();if(X&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new U1({children:[new c0({decoration:{color:Q.background},child:new $0({text:new C(">",new h({color:Q.foreground}))})}),new T1({child:G})]}),U=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("",void 0,[new C("Command: ",new h({color:Q.foreground})),new C(this.widget.props.commandName,new h({color:Y.command,bold:!0}))])})}),q=[];if(K)q.push(new C("Enter",new h({color:Y.keybind}))),q.push(new C(" to submit, ",new h({color:Q.foreground,dim:!0})));q.push(new C("Esc",new h({color:Y.keybind}))),q.push(new C(" to cancel",new h({color:Q.foreground,dim:!0})));let D=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("",void 0,q)})});return new c0({decoration:{border:z,color:Q.background},padding:C0.all(1),child:new u0({children:[U,new R0({height:1}),F,new V3,D]})})}}class dp extends d0{props;constructor(J){super();this.props=J}createState(){return new mN4}}import{isDeepStrictEqual as Jp0}from"node:util";var yi5=/[\\/_ +.#"@[({&]/,ui5=/[\\/_ +.#"@[({&]/g,xi5=/[\s-]/,gN4=/[\s-]/g;function k$0(J,Z,Q,Y,X,V,K){if(V===Z.length){if(X===J.length)return 1;return 0.99}let z=`${X},${V}`;if(K[z]!==void 0)return K[z];let G=Y.charAt(V),F=Q.indexOf(G,X),U=0,q,D,W,H;while(F>=0){if(q=k$0(J,Z,Q,Y,F+1,V+1,K),q>U){if(F===X)q*=1;else if(xi5.test(J.charAt(F-1))){if(q*=0.9,H=J.slice(X,F-1).match(gN4),H&&X>0)q*=0.999**H.length}else if(yi5.test(J.charAt(F-1))){if(q*=0.8,W=J.slice(X,F-1).match(ui5),W&&X>0)q*=0.999**W.length}else if(q*=0.3,X>0)q*=0.999**(F-X);if(J.charAt(F)!==Z.charAt(V))q*=0.9999}if(q<0.1&&(Q.charAt(F-1)===Y.charAt(V+1)||Y.charAt(V+1)===Y.charAt(V)&&Q.charAt(F-1)!==Y.charAt(V))){if(D=k$0(J,Z,Q,Y,F+1,V+2,K),D*0.1>q)q=D*0.1}if(q>U)U=q;F=Q.indexOf(G,F+1)}return K[z]=U,U}function v$0(J){return J.toLowerCase().replace(gN4," ")}function pN4(J,Z){let Q=k$0(J,Z,v$0(J),v$0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,V=0;for(let z of Y){let G=k$0(J,z,v$0(J),v$0(z),0,0,{});if(G===0)return Q;X+=G,V+=z.length}let K=X/Y.length*0.95;return Math.max(Q,K)}return Q}class hT{}class mT{}class y$0{}class u$0{}class dN4 extends d0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new cN4}}class cN4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function fi5(J,Z){if(J==="")return{matches:!0,score:1};let Q=pN4(Z,J);return{matches:Q>0.15,score:Q}}class o9 extends d0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new lN4}}class lN4 extends p0{textController;focusNode;scrollController=new Y5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new i7(this.widget.props.controller?.query??""),this.focusNode=new r4({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),H6.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)=>Jp0(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!Jp0(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>Jp0(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 hT){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof mT){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof y$0){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 u$0)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,...fi5(Q,this.widget.props.getLabel(X))})).filter((X)=>X.matches).sort(this.widget.props.sortItems?(X,V)=>this.widget.props.sortItems(X,V,J):(X,V)=>V.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;kT(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(),H6.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=u1.all(new v1(Q.foreground,1,"solid")),V=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,K=this.widget.props.enabled??!0,z=new FJ({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:K,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),G=new C2({shortcuts:new Map([[new Y4("ArrowDown"),new hT],[new Y4("ArrowUp"),new mT],[new Y4("Tab"),new hT],[new Y4("Tab",{shift:!0}),new mT],[new Y4("n",{ctrl:!0}),new hT],[new Y4("p",{ctrl:!0}),new mT],[new Y4("Enter"),new y$0],[new Y4("Escape"),new u$0]]),focusNode:this.focusNode,child:z}),F=new S9({actions:new Map([[hT,new s4(this.invoke)],[mT,new s4(this.invoke)],[y$0,new s4(this.invoke)],[u$0,new s4(this.invoke)]]),child:G}),U=new U1({children:[new c0({decoration:{color:Q.background},child:new $0({text:new C(">",new h({color:Q.foreground}))})}),new T1({child:F})]});this.itemContexts=[];let q;if(this.widget.props.isLoading){let w=this.widget.props.loadingText??"Loading...";q=new R0({height:10,child:new l1({child:new $0({text:new C(w,new h({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)q=new T1({child:new l1({child:new $0({text:new C(this.widget.props.emptyStateText,new h({color:Q.foreground,dim:!0}))})})});else{let w=Y.map((N,O)=>{let E=O===this.selectedIndex,L=this.widget.props.isItemDisabled?.(N)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(N,E,L,J);else{let A=E?Z.app.selectionBackground:void 0,I=E?Z.app.selectionForeground:Q.foreground;M=new c0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C(this.widget.props.getLabel(N),new h({color:I,dim:L}))})})}return new dN4(new n1({onClick:(A)=>this.handleItemClick(O,A.clickCount),child:M}),(A)=>{this.itemContexts[O]=A})});q=new u0({children:w,crossAxisAlignment:"start"})}let D=new n1({onScroll:this.handleScroll,opaque:!1,child:new j6({controller:this.scrollController,autofocus:!1,child:q})}),W=[];if(this.widget.props.title){let w=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C(this.widget.props.title,new h({color:Z.app.command,bold:!0}))})});W.push(w)}if(!V)W.push(U,new R0({height:1}));if(this.textController.text!==""){let w=Y.length>0?Y[this.selectedIndex]:void 0,N=w&&this.widget.props.buildDisabledReasonWidget?.(w,J);W.push(new T1({child:new u0({mainAxisAlignment:"spaceBetween",children:[new T1({child:D}),new c0({padding:C0.only({top:1}),child:new l1({child:N??new R0({height:1})})})]})}))}else W.push(new T1({child:D}));if(this.widget.props.footer)W.push(this.widget.props.footer);return new c0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new u0({children:W})})}}function iN4(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/60000),X=Math.floor(Q/3600000),V=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(V<7)return`${V}d ago`;return J.toLocaleDateString()}class Zp0 extends d1{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((X,V)=>V.pubDate.getTime()-X.pubDate.getTime()),Q=Math.max(0,...Z.map((X)=>iN4(X.pubDate).length));return new o9({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,V,K,z)=>{let G=f0.of(z),{colors:F}=G,U=G.app,q=V?U.selectionBackground:void 0,D=V?U.selectionForeground:F.foreground,W=F.mutedForeground,H=(B,w)=>new R0({width:w,child:U1.end([new $0({text:new C(B,new h({color:W}))})])});return new c0({decoration:q?{color:q}:void 0,padding:C0.symmetric(2,0),child:new U1({children:[new T1({child:new $0({text:new C(X.title,new h({color:D})),overflow:"ellipsis",maxLines:1})}),new R0({width:2}),H(iN4(X.pubDate),Q)]})})}})}}_4();class Qp0 extends d0{createState(){return new nN4}}class nN4 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 $0({text:new C("●",new h({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}var bi5=/\/threads\/(T-[^/?#\s<>]+)/i;function hi5(J){let Z=J.trim(),Y=Z.match(bi5)?.[1];if(Y&&D8(Y))return Y;let X=Z.replace(/^[<("'`]+|[>")'`,.]+$/g,"");if(D8(X))return X;return null}function mi5(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let K of J)Z.set(K.id,K);for(let K of J){let z=K.relationships.find((G)=>G.role==="child"&&Z.has(G.threadID)&&(G.type==="fork"||G.type==="handoff"));if(z){Y.set(K.id,z.type);let G=z.threadID,F=Q.get(G)||[];F.push(K),Q.set(G,F)}else X.push(K)}return X20.flatten(X,(K)=>Q.get(K.id)).map((K)=>({...K.item,depth:K.depth,isLast:K.isLast,ancestorsAreLast:K.ancestorsAreLast,relationshipType:Y.get(K.item.id)}))}function Yp0(J,Z,Q){return new $0({text:new C(`${J}${Z}`,new h({color:Q})),maxLines:1})}function gi5(J,Z,Q,Y){return[Yp0("+",J,Y.success),V3.horizontal(1),Yp0("~",Z,Y.warning),V3.horizontal(1),Yp0("-",Q,Y.destructive)]}function pi5(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class x$0 extends d0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new aN4}}class aN4 extends p0{spinner=new S3;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}`,V=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((O)=>O.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)V=V.filter((O)=>O.id!==Z.currentThreadID);let K=Z.recentThreadIDs||[],z=new Set(K),G=Z.currentThreadID,F=[...V].sort((O,E)=>{if(G){if(O.id===G)return-1;if(E.id===G)return 1}let L=K.indexOf(O.id),M=K.indexOf(E.id);if(L!==-1&&M!==-1)return L-M;if(L!==-1)return-1;if(M!==-1)return 1;return 0}),U=mi5(F),q=Math.max(0,...U.map((O)=>O.description.timeAgo.length)),D=f0.of(J),W=new i0({padding:C0.symmetric(0,1),child:new l1({child:new $0({text:new C("",new h({color:D.colors.foreground,dim:!0}),[new C("Ctrl+T",new h({color:D.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new h({color:D.colors.foreground,dim:!0}))])})})}),H="",B=null,w=(O)=>{if(O!==H)H=O,B=hi5(O);return B};return new o9({items:U,getLabel:(O)=>`${O.title} ${O.id}`,filterItem:(O,E)=>{let L=w(E);if(L)return O.id.toLowerCase()===L.toLowerCase();return!0},normalizeQuery:(O)=>w(O)?"":O,onAccept:async(O,E)=>{if(!Z.onSelect||this.isSwitchingThread)return;let L=Z.onSelect(O.id,E);if(!pi5(L))return;this.setSwitchingThread(!0);try{await L}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(O)=>{if(Z.previewController){if(O)Z.previewController.select(O.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:W,renderItem:(O,E,L,M)=>{let A=f0.of(M),{app:I,colors:P}=A,_=E?I.selectionBackground:void 0,S=E?I.selectionForeground:P.foreground,y=P.mutedForeground,m=(s,w0)=>new R0({width:w0,child:U1.end([new $0({text:new C(s,new h({color:y}))})])}),b=Z.threadViewStates[O.id],k=[],f=O.relationshipType==="handoff",p=new qp({connectorColor:P.mutedForeground});if(O.depth>0){let s=[],w0=O.ancestorsAreLast.slice(1);for(let z0 of w0)s.push(new C(p.getAncestorPrefix(z0),new h({color:p.connectorColor,dim:p.connectorDim})));let a=O.isLast?p.elbow:p.tee,F0=p.getConnectorText(a);s.push(new C(F0,new h({color:p.connectorColor,dim:p.connectorDim}))),k.push(new $0({text:new C("",void 0,s)}))}let l=[],x=G===O.id?new C("(current) ",new h({color:P.success})):z.has(O.id)?new C("(visited) ",new h({color:P.foreground,dim:!0})):null;if(x)l.push(new $0({text:x}));if(gO(b))l.push(new Qp0),l.push(new R0({width:1}));let r=O.title;if(O.relationshipType==="fork"){let s=r.match(/^Forked\((\d+)\): /);if(s)r=r.slice(s[0].length);else while(r.startsWith("Forked: "))r=r.slice(8);l.push(new $0({text:new C("[fork] ",new h({color:P.primary}))}))}else if(f)l.push(new $0({text:new C("[handoff] ",new h({color:P.accent}))}));if(l.push(new T1({child:new $0({text:new C(r,new h({color:S})),overflow:"ellipsis",maxLines:1})})),l.push(new R0({width:2})),O.diffStats&&(O.diffStats.added>0||O.diffStats.changed>0||O.diffStats.deleted>0)){let s=E?{success:y,warning:y,destructive:y}:P;l.push(...gi5(O.diffStats.added,O.diffStats.changed,O.diffStats.deleted,s)),l.push(new R0({width:2}))}return l.push(m(O.description.timeAgo,q)),new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new U1({children:[...k,...l]})})}})}}function oN4(J){return 1-(1-J)**3}function rN4(J,Z,Q){return J+(Z-J)*Q}function cp(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),V=oN4(Y),K=oN4(X);return{x:rN4(J.startOffset.x,J.targetOffset.x,V),y:rN4(J.startOffset.y,J.targetOffset.y,K)}}var di5={nodeWidth:3,horizontalSpacing:3};class gT{options;constructor(J={}){this.options={...di5,...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 V=0,K=(z,G)=>{let F=Z.get(z.id)??[];if(this.options.comparator)F.sort(this.options.comparator);let U={...z,parentID:Q.get(z.id)};if(F.length===0){Y.push({node:U,position:{x:V,y:G}});let B=V;return V+=this.options.nodeWidth+this.options.horizontalSpacing,B}let q=[];for(let B of F)q.push(K(B,G+1));let D=Math.min(...q),W=Math.max(...q),H=Math.floor((D+W)/2);return Y.push({node:U,position:{x:H,y:G}}),H};for(let z of X)K(z,0);return Y}buildTree(J){let Z=new Set(J.map((V)=>V.id)),Q=[...J].sort((V,K)=>V.id.localeCompare(K.id)),Y=new Map;for(let V of Q){if(!V.parentID||!Z.has(V.parentID)){Y.set(V.id,void 0);continue}let K=!1,z=V.parentID;while(z){if(z===V.id){K=!0;break}z=Y.get(z)}Y.set(V.id,K?void 0:V.parentID)}let X=new Map;for(let V of J){let K=Y.get(V.id);if(!X.has(K))X.set(K,[]);X.get(K).push(V)}return{childrenMap:X,resolvedParent:Y}}}var ci5={nodeWidth:3,nodeHeight:2};class pT{options;constructor(J={}){this.options={...ci5,...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 V=this.calculateConnectorLine(X.position,Y.position);Z.push({points:V,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,V=Z.x+Q,K=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:K});let z=K+1;if(Y.push({x:X,y:z}),X!==V)Y.push({x:V,y:z});let G=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:V,y:G}),Y}}var li5={nodeWidth:3,nodeHeight:2},ii5={x:0,y:0};class b$0{options;constructor(J={}){this.options={...li5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=ii5,X,V,K,z){let G=z?f0.of(z):null,F=G?.colors,U=G?.app,q=F?.mutedForeground??F?.foreground;if(J.length===0)return new $0({text:new C("No nodes",new h({color:q}))});let D=Math.max(...J.map((I)=>I.position.y)),H=Math.max(...J.map((I)=>I.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,w=[];for(let I=D;I>=0;I--){let P=J.filter((y)=>y.position.y===I);P.sort((y,m)=>y.position.x-m.position.x);let _=[],S=0;for(let y of P){if(y.position.x>S)_.push(new R0({width:y.position.x-S}));let m=y.node.id===Q,b=K?.(y.node.data)??!1,k=V?.activeFlashOn??!1,f=y.node.id===V?.copyFlashNodeId;_.push(this.renderNode(m,b,k,f,U,F)),S=y.position.x+this.options.nodeWidth}if(w.push(new U1({crossAxisAlignment:"start",children:_})),I>0){let y=J.filter((k)=>k.position.y===I-1),m=P,b=this.renderConnectors(y,m,Z,H,F,U);w.push(...b)}}let N=new u0({crossAxisAlignment:"start",children:w}),O=Math.round(Y.x),E=Math.round(Y.y*B),L=(D+1)*B,M=[new R0({width:H,height:L}),new x6({left:O,top:E,child:N})],A=Q?J.find((I)=>I.node.id===Q):void 0;if(A&&X){let I=X(A.node.data),P=D-A.position.y,_=O+A.position.x+this.options.nodeWidth+1,S=E+P*B+1,y=30;if(V?.maxTitleWidthPercent&&V.viewportWidth)y=Math.floor(V.viewportWidth*V.maxTitleWidthPercent/100);M.push(new x6({left:_,top:S,child:this.renderInfoBox(I,y,F,U)}))}return new c0({padding:C0.horizontal(2),child:new LH(new i6({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,V){let K="┌─┐",z="└─┘",G=J?X?.threadGraphNodeSelected??V?.primary??V?.foreground:X?.threadGraphNode??V?.primary??V?.foreground,F=!1;if(Y)G=X?.threadGraphNodeSelected??V?.primary??G,K="┏━┓",z="┗━┛",F=!0;else if(Z&&Q)G=X?.toolSuccess??V?.primary??G,K="┏━┓",z="┗━┛";return new u0({crossAxisAlignment:"start",children:[new $0({text:new C(K,new h({color:G,bold:F}))}),new $0({text:new C(z,new h({color:G,bold:F}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let V of Q){if(V.length>Z)V=V.slice(0,Z-1)+"…";if(X.length===0)X=V;else if(X.length+1+V.length<=Z)X+=" "+V;else Y.push(X),X=V}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),V=Math.min(Z,Math.max(1,...X.map((D)=>D.length))),K=V+2,z="┌"+"─".repeat(K)+"┐",G="└"+"─".repeat(K)+"┘",F=Q?.border??Y?.threadGraphConnector??Q?.foreground,U=Q?.foreground,q=[new $0({text:new C(z,new h({color:F}))})];for(let D of X){let W=" ".repeat(V-D.length);q.push(new $0({text:new C("│ ",new h({color:F}),[new C(D+W,new h({color:U??F})),new C(" │",new h({color:F}))])}))}return q.push(new $0({text:new C(G,new h({color:F}))})),new u0({crossAxisAlignment:"start",children:q})}renderConnectors(J,Z,Q,Y,X,V){let K=[],z=Math.floor(this.options.nodeWidth/2),G=V?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let D of Z){let W=D.position.x+z;if(W>=0&&W<Y)F[W]="▲"}K.push(new $0({text:new C(F.join(""),new h({color:G}))}));let U=Array(Y).fill(" ");for(let D of J){let W=Z.filter((O)=>O.node.parentID===D.node.id);if(W.length===0)continue;let H=D.position.x+z,B=W.map((O)=>O.position.x+z),w=Math.min(...B),N=Math.max(...B);for(let O=w;O<=N;O++)if(O>=0&&O<Y){if(O===H)if(W.length===1&&B[0]===H)U[O]="│";else if(O===w)U[O]="└";else if(O===N)U[O]="┘";else U[O]="┬";else if(B.includes(O))if(O===w)U[O]="└";else if(O===N)U[O]="┘";else U[O]="┴";else if(U[O]===" ")U[O]="─"}}K.push(new $0({text:new C(U.join(""),new h({color:G}))}));let q=Array(Y).fill(" ");for(let D of J){if(Z.filter((B)=>B.node.parentID===D.node.id).length===0)continue;let H=D.position.x+z;if(H>=0&&H<Y)q[H]="│"}return K.push(new $0({text:new C(q.join(""),new h({color:G}))})),K}}var ni5={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},ai5={x:0,y:0};class Xp0{options;constructor(J={}){this.options={...ni5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=ai5,X,V,K,z){let G=z?f0.of(z):null,F=G?.colors,U=G?.app,q=F?.mutedForeground??F?.foreground;if(J.length===0)return new $0({text:new C("No nodes",new h({color:q}))});let D=Math.max(...J.map((I)=>I.position.y)),H=Math.max(...J.map((I)=>I.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,w=[];for(let I=D;I>=0;I--){let P=J.filter((y)=>y.position.y===I);P.sort((y,m)=>y.position.x-m.position.x);let _=[],S=0;for(let y of P){if(y.position.x>S)_.push(new R0({width:y.position.x-S}));let m=y.node.id===Q,b=K?.(y.node.data)??!1,k=V?.activeFlashOn??!1;_.push(this.renderNode(m,b,k,U,F)),S=y.position.x+this.options.nodeWidth}if(w.push(new U1({crossAxisAlignment:"start",children:_})),I>0){let y=J.filter((k)=>k.position.y===I-1),m=P,b=this.renderConnectors(y,m,Z,H,F,U);w.push(...b)}}let N=new u0({crossAxisAlignment:"start",children:w}),O=Math.round(Y.x),E=Math.round(Y.y*B),L=(D+1)*B,M=[new R0({width:H,height:L}),new x6({left:O,top:E,child:N})],A=Q?J.find((I)=>I.node.id===Q):void 0;if(A&&X){let I=X(A.node.data),P=D-A.position.y,_=O+A.position.x+this.options.nodeWidth+1,S=E+P*B,y=30;if(V?.maxTitleWidthPercent&&V.viewportWidth)y=Math.floor(V.viewportWidth*V.maxTitleWidthPercent/100);M.push(new x6({left:_,top:S,child:this.renderInfoBox(I,y,F)}))}return new c0({padding:C0.horizontal(2),child:new LH(new i6({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X){let V=J?this.options.selectedIcon:this.options.nodeIcon,K=J?Y?.threadGraphNodeSelected??X?.primary??X?.foreground:Y?.threadGraphNode??X?.primary??X?.foreground;if(Z&&Q)K=Y?.toolSuccess??X?.primary??K,V="■";return new $0({text:new C(V,new h({color:K}))})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let V of Q){if(V.length>Z)V=V.slice(0,Z-1)+"…";if(X.length===0)X=V;else if(X.length+1+V.length<=Z)X+=" "+V;else Y.push(X),X=V}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q){let Y=this.wrapText(J,Z),X=Q?.foreground,V=[];for(let K of Y)V.push(new $0({text:new C(K,new h({color:X??Q?.primary??Q?.foreground}))}));return new u0({crossAxisAlignment:"start",children:V})}renderConnectors(J,Z,Q,Y,X,V){let K=[],z=Math.floor(this.options.nodeWidth/2),G=V?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let U of J){let q=Z.filter((w)=>w.node.parentID===U.node.id);if(q.length===0)continue;let D=U.position.x+z,W=q.map((w)=>w.position.x+z),H=Math.min(...W),B=Math.max(...W);for(let w=H;w<=B;w++)if(w>=0&&w<Y){let N=w===D,O=W.includes(w);if(N&&O)if(q.length===1)F[w]="│";else if(w===H)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┼";else if(N)if(w===H)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┬";else if(O)if(w===H)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┴";else if(F[w]===" ")F[w]="─"}}return K.push(new $0({text:new C(F.join(""),new h({color:G}))})),K}}class lp extends N3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new sN4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class sN4 extends A4{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 bL extends d0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new $O4}}var tN4=400,eN4=300,oi5=16;class $O4 extends p0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new gT({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new pT;renderer=new Xp0;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,V=this.widget.props.initialSelectedThreadID;if(X!==V&&V){let F=this.widget.props.threads.find((U)=>U.id===V);if(F)this.selectedNodeId=F.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let K=J.props.threads.some((G)=>G.isActive),z=this.widget.props.threads.some((G)=>G.isActive);if(K!==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:tN4,durationY:eN4};let Z=Math.max(tN4,eN4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=cp(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},oi5)}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),V=Math.floor(this.viewportWidth/2)-J-Y,K=Q-Z,z=2,G=Math.floor(this.viewportHeight/2),U=Math.floor(G/2)-K;return{x:V,y:U}}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((V)=>V.node.parentID===Q.node.id);if(X.length>0){X.sort((K,z)=>K.position.x-z.position.x);let V=Math.floor(X.length/2);Y=X[V]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((V)=>V.position.y===Q.position.y&&V.position.x<Q.position.x);if(X.length>0)X.sort((V,K)=>K.position.x-V.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((V)=>V.position.y===Q.position.y&&V.position.x>Q.position.x);if(X.length>0)X.sort((V,K)=>V.position.x-K.position.x),Y=X[0];break}case"Enter":{if(this.widget.props.onSelect)this.widget.props.onSelect(this.toThreadNode(Q));return"handled"}default:{if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"}}if(Y)return this.selectedNodeId=Y.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(Y)),this.animateToNode(Y.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let U=(this.selectedNodeId?this.positionedNodes.find((q)=>q.node.id===this.selectedNodeId):null)??this.positionedNodes.find((q)=>!q.node.parentID);if(U){let q=Math.max(...this.positionedNodes.map((D)=>D.position.y));this.currentOffset=this.calculateCenterOffset(U.position.x,U.position.y,q)}}let X=this.widget.props.showTitle??!0,V=this.widget.props.offsetY??0,K={x:this.currentOffset.x,y:this.currentOffset.y+V},z=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,K,X?(F)=>F.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(F)=>F.isActive??!1,J),G=new lp({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 k4({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 ZO4 extends d0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new QO4}}class QO4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}var JO4=30,ri5=30;class dT{}class cT{}class h$0{}class m$0{}class Vp0 extends d0{props;constructor(J){super();this.props=J}createState(){return new YO4}}class YO4 extends p0{highlightedIndex=0;controller=new i7;focusNode;scrollController=new Y5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new r4({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),H6.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;kT(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 dT){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof cT){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof h$0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof m$0)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Z)=>{if(J>=0&&J<this.filteredClusters.length){if(Z===1)this.highlightedIndex=J,this.setState();else if(Z===2){let Q=this.filteredClusters[J];if(Q)this.widget.props.onAccept(Q)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return!1;let Z=this.highlightedIndex;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return!1;else if(this.highlightedIndex>0)this.highlightedIndex--;else return!1;return this.setState(),H6.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=t1.of(J).size.width>=ri5+JO4,G=u1.all(new v1(Y.foreground,1,"solid")),F=this.filteredClusters[this.highlightedIndex]??null,U=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("Select a cluster",new h({color:X.command,bold:!0}))})}),q=new FJ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),D=new C2({shortcuts:new Map([[new Y4("ArrowDown"),new dT],[new Y4("ArrowUp"),new cT],[new Y4("Tab"),new dT],[new Y4("Tab",{shift:!0}),new cT],[new Y4("n",{ctrl:!0}),new dT],[new Y4("p",{ctrl:!0}),new cT],[new Y4("Enter"),new h$0],[new Y4("Escape"),new m$0]]),focusNode:this.focusNode,child:q}),W=new S9({actions:new Map([[dT,new s4(this.invoke)],[cT,new s4(this.invoke)],[h$0,new s4(this.invoke)],[m$0,new s4(this.invoke)]]),child:D}),H=new U1({children:[new c0({decoration:{color:Y.background},child:new $0({text:new C(">",new h({color:Y.foreground}))})}),new T1({child:W})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let I=A===this.highlightedIndex,P=Z?M.threads.some((m)=>m.id===Z):!1,_=I?X.selectionBackground:void 0,S=I?X.selectionForeground:Y.foreground,y=[new C(M.label,new h({color:S})),new C(` (${M.threads.length})`,new h({color:S,dim:!0}))];if(P)y.push(new C(" (current)",new h({color:I?X.selectionForeground:Y.success})));return new ZO4(new n1({onClick:(m)=>this.handleItemClick(A,m.clickCount),child:new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C("",void 0,y)})})}),(m)=>{this.itemContexts[A]=m})}),w=new u0({children:B,crossAxisAlignment:"start"}),N=new T1({child:new n1({onScroll:this.handleScroll,child:new j6({controller:this.scrollController,autofocus:!1,child:w})})}),O=F?F.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],E=F?new c0({padding:C0.all(1),child:new bL({threads:O,autofocus:!1,offsetY:2})}):null,L;if(z){let M=E?new T1({child:E}):new R0({width:JO4});L=new U1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[N,M]})}else{let M=[new T1({child:new n1({onScroll:this.handleScroll,child:new j6({controller:this.scrollController,autofocus:!1,child:w})})})];if(E)M.push(new T1({child:E}));L=new u0({crossAxisAlignment:"stretch",children:M})}return new c0({decoration:{border:G,color:Y.background},padding:C0.symmetric(1,0),child:new u0({children:[U,H,new R0({height:1}),new T1({child:L})]})})}}class UJ{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!UJ._instance)UJ._instance=new UJ;return UJ._instance}get allExpanded(){return this._allExpanded}setAllExpanded(J){if(this._allExpanded===J)return;this._allExpanded=J,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(J){return this._listeners.add(J),()=>this.removeListener(J)}removeListener(J){this._listeners.delete(J)}_notifyListeners(){for(let J of this._listeners)J()}}h0();class XO4 extends p0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){j.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){j.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){let Z=J.trim().toLowerCase();if(Z.length===0)return null;if(Z.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Z))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Z)=>!J.includes(Z.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Z=J.trim().toLowerCase();if(!this.isValidLabelName(Z))return!1;let Q=this.widget.props.currentLabels||[],Y=this.labels.some((V)=>V.name===Z),X=Q.includes(Z);return!Y&&!X}build(J){let Z=f0.of(J),{app:Q,colors:Y}=Z,X=this.currentQuery.trim().toLowerCase(),V=X.length>0?this.getValidationError(X):null,K=this.getAvailableLabels(),G=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...K];return new o9({title:"Add Label",items:G,getLabel:(F)=>{if("__isCreateMarker"in F)return this.currentQuery.trim().toLowerCase();return F.name},onAccept:(F)=>{if("__isCreateMarker"in F)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(F.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:V||"Type to create a new label",renderItem:(F,U,q,D)=>{let W=U?Q.selectionBackground:void 0,H=U?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in F&&F.__isCreateMarker){let w=this.currentQuery.trim().toLowerCase();return new c0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C("",void 0,[new C("Create new label: ",new h({color:H})),new C(w,new h({color:H,bold:!0}))])})})}return new c0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C(F.name,new h({color:H}))})})},filterItem:(F,U)=>{if(this.currentQuery!==U)this.currentQuery=U,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in F&&F.__isCreateMarker)return this.shouldShowCreateMarker(U);let D=U.trim().toLowerCase();return D.length===0||F.name.includes(D)},sortItems:(F,U,q)=>{let D="__isCreateMarker"in F.item&&F.item.__isCreateMarker,W="__isCreateMarker"in U.item&&U.item.__isCreateMarker;if(D&&!W)return-1;if(!D&&W)return 1;return U.score-F.score}})}}class Kp0 extends d0{props;constructor(J){super();this.props=J}createState(){return new XO4}}class iV extends d0{props;constructor(J){super();this.props=J}createState(){return new VO4}}class VO4 extends p0{_spinner=new S3;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=u1.all(new v1(Q.foreground,1,"solid")),V=this._spinner.toBraille(),K=new $0({textAlign:"center",text:new C("",void 0,[new C(V,new h({color:Y.processing})),new C(" ",void 0),new C(this.widget.props.message,new h({color:Q.foreground}))])}),G=[new T1({child:new u0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[K]})})];if(this.widget.props.onAbort)G.push(new R0({height:2,child:new c0({padding:C0.symmetric(2,0),child:new $0({text:new C("",new h({dim:!0}),[new C("Press ",new h({color:Q.foreground})),new C("Esc",new h({color:Q.info})),new C(" to cancel",new h({color:Q.foreground}))])})})}));let F=new c0({decoration:new v4(Q.background,X),child:new R0({width:60,height:7,child:new u0({mainAxisAlignment:"start",children:G})})});if(this.widget.props.onAbort)return new k4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(U)=>{if(U.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:F});return F}}var ip={workspace:{label:"Workspace",pathHint:".amp/settings.json",description:"workspace config"},global:{label:"Global",pathHint:"~/.config/amp/settings.json",description:"global config"},flag:{label:"Flag",pathHint:"CLI flags",description:"flag config"},default:{label:"Default",pathHint:"built-in defaults",description:"default config"},external:{label:"External",pathHint:"extensions / external",description:"external source"},skill:{label:"Skills",pathHint:".agents/skills/",description:"skill source"},other:{label:"Other",pathHint:"",description:"other source"}},g$0=["workspace","global","flag","default","external","skill","other"];function si5(J){return Array.from(new Set(J))}function KO4(J){return si5([...J.skillNames??[],...J.skillName?[J.skillName]:[]])}function lT(J){if(J.isExternal)return"external";switch(J.spec._target){case"workspace":return"workspace";case"global":return"global";case"flag":return"flag";case"default":return"default"}return KO4(J).length>0?"skill":"other"}function zp0(J){return lT(J)==="skill"}function zO4(J){let Z=KO4(J);if(Z.length===0)return;let Q=Z.join(", "),Y=lT(J);if(Y==="skill")return`skills: ${Q}`;return`${Z.length===1?"skill source":"skill sources"} overridden by ${ip[Y].description}: ${Q}`}function GO4(J){return J.spec.meta?.skillNames?Array.from(J.spec.meta.skillNames):[]}class u8 extends d0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X="█",thumbChar:V="█",showTrack:K=!0,thumbColor:z,trackColor:G}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=V,this.showTrack=K,this.thumbColor=z,this.trackColor=G}createState(){return new FO4}}class FO4 extends p0{_dragStartY=null;_dragStartOffset=null;_isOverThumb=!1;_isPositionOverThumb(J){let{totalContentHeight:Z,viewportHeight:Q}=this.widget.getScrollInfo(),X=this.context.findRenderObject()?.size.height??0;if(X===0||Z<=Q)return!1;let V=this.widget.getScrollInfo(),K=Math.min(1,Q/Z),z=Math.max(1,X*K),G=Math.max(0,Math.min(1,V.scrollOffset/(Z-Q))),F=X-z,U=Math.max(0,F*G),q=U+z;return J>=U&&J<=q}_handleHover=(J)=>{let Z=this._isOverThumb;if(this._isOverThumb=this._isPositionOverThumb(J.localPosition.y),Z!==this._isOverThumb)this.setState()};_handleDrag=(J)=>{let{totalContentHeight:Z,viewportHeight:Q,scrollOffset:Y}=this.widget.getScrollInfo(),V=this.context.findRenderObject()?.size.height??0;if(V===0||Z<=Q)return;if(this._dragStartY===null)this._dragStartY=J.localPosition.y,this._dragStartOffset=Y;let K=J.localPosition.y-this._dragStartY,z=Math.min(1,Q/Z),G=Math.max(1,V*z),F=V-G;if(F<=0)return;let U=Z-Q,q=F/U,D=K/q,W=Math.max(0,Math.min(U,this._dragStartOffset+D));this.widget.controller.jumpTo(W)};_handleRelease=()=>{this._dragStartY=null,this._dragStartOffset=null};_handleClick=(J)=>{if(J.button!=="left")return;let Z=J.localPosition.y,{totalContentHeight:Q,viewportHeight:Y,scrollOffset:X}=this.widget.getScrollInfo(),K=this.context.findRenderObject()?.size.height??0;if(K===0||Q<=Y)return;let z=Math.min(1,Y/Q),G=Math.max(1,K*z),F=Q-Y,U=K-G,q=Math.max(0,Math.min(1,X/(Q-Y))),D=Math.max(0,U*q),W=D+G;if(Z>=D&&Z<=W)return;if(Z<D)this.widget.controller.animateTo(Math.max(0,X-Y));else this.widget.controller.animateTo(Math.min(F,X+Y))};build(J){return new n1({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?E5.POINTER:E5.DEFAULT,child:new UO4({controller:this.widget.controller,getScrollInfo:this.widget.getScrollInfo,thickness:this.widget.thickness,trackChar:this.widget.trackChar,thumbChar:this.widget.thumbChar,showTrack:this.widget.showTrack,thumbColor:this.widget.thumbColor,trackColor:this.widget.trackColor})})}}class UO4 extends dC{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X="█",thumbChar:V="█",showTrack:K=!0,thumbColor:z,trackColor:G}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=V,this.showTrack=K,this.thumbColor=z,this.trackColor=G}createRenderObject(){return new qO4(this)}updateRenderObject(J){J.updateWidget(this)}}class qO4 extends A4{_widget;constructor(J){super();this._widget=J}updateWidget(J){this._widget=J,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;f4(!!J,"performLayout called without constraints");let Z=Math.min(J.maxWidth,this._widget.thickness),Q=J.maxHeight;this.setSize(Z,Q),super.performLayout()}getMinIntrinsicWidth(J){return this._widget.thickness}getMaxIntrinsicWidth(J){return this._widget.thickness}getMinIntrinsicHeight(J){return 0}getMaxIntrinsicHeight(J){return 0}paint(J,Z,Q){let{thumbStartFloat:Y,thumbSizeFloat:X,showScrollbar:V}=this._calculateScrollbarMetrics();if(!V)return;let K=this._widget.trackColor,z=this._widget.thumbColor,G=["▁","▂","▃","▄","▅","▆","▇","█"],F=Y,U=Y+X;for(let q=0;q<this.size.height;q++){let D="█",W=!0;if(q===Math.floor(F)){let H=1-(F-q),B=Math.floor(H*8);D=G[B]||"█",W=!1}else if(q===Math.floor(U)){let H=1-(U-q),B=Math.floor(H*8);D=G[B]||"█"}else if(q>F&&q<U)W=!1;J.setChar(Z,Q+q,D,{fg:z,bg:K,reverse:W},1)}}_calculateScrollbarMetrics(){let{totalContentHeight:J,viewportHeight:Z,scrollOffset:Q}=this._widget.getScrollInfo(),Y=this.size.height;if(J<=Z||Y<=0)return{thumbStartFloat:0,thumbSizeFloat:0,showScrollbar:!1};let X=Math.max(0,Math.min(1,Q/(J-Z))),V=Math.min(1,Z/J),K=Math.max(1,Y*V),z=Y-K;return{thumbStartFloat:Math.max(0,z*X),thumbSizeFloat:K,showScrollbar:!0}}}class hL extends d0{props;constructor(J){super();this.props=J}createState(){return new DO4}}class DO4 extends p0{scrollController=new Y5;scrollAreaKey=new g7("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(J){return J instanceof S2}resolveFooterStyle(J){if(this.isWidgetMessage(J))return J.footerStyle;return"default"}getViewportHeight(){let Z=this.scrollAreaKey.currentElement?.renderObject;if(Z&&"size"in Z){let Q=Z.size;if(typeof Q.height==="number"&&Q.height>0)return this.viewportHeight=Q.height,Q.height}return this.viewportHeight}build(J){let Z=f0.of(J),Q=this.widget.props.message,Y=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let U=B$0(Q);return{title:U.title,type:U.type,description:U.description}})(),X=Y.type==="error"?Z.app.toolError:Z.app.command,V=u1.all(new v1(Z.colors.border,1,"solid")),K=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C(Y.title,new h({color:X,bold:!0}))})}),z=this.isWidgetMessage(Q)?Q.widget:new $0({text:new C(Y.description,new h({color:Z.colors.foreground})),selectable:!0}),G=new T1({child:new T2({child:new c0({padding:C0.symmetric(1,0),child:new U1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new T1({child:new j6({controller:this.scrollController,autofocus:!0,child:z})}),new u8({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let U=this.scrollController.maxScrollExtent,q=this.scrollController.offset,D=this.getViewportHeight(),W=U+D;return{totalContentHeight:Math.max(W,0),viewportHeight:Math.max(D,1),scrollOffset:Math.max(q,0)}}})]})})})}),F=new c0({padding:C0.symmetric(1,0),child:new $0({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new h({color:Z.colors.foreground,dim:!0})),new C("R",new h({color:Z.app.keybind})),new C(" to retry, ",new h({color:Z.colors.foreground,dim:!0})),new C("Esc",new h({color:Z.app.keybind})),new C(" to cancel",new h({color:Z.colors.foreground,dim:!0}))]);let U=this.resolveFooterStyle(this.widget.props.message);if(U==="none")return new C("",new h({color:Z.colors.foreground,dim:!0}));if(U==="help"){let q=new h({color:Z.app.keybind}),D=new h({color:Z.colors.foreground,dim:!0});return new C("",D,[new C("Press ",D),new C("Escape",q),new C(" to close • Use ",D),new C("↑↓",q),new C(" or ",D),new C("j/k",q),new C(" to scroll",D)])}return new C("Press any key to close",new h({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new k4({onKey:(U)=>{if(this.widget.props.onRetry&&U.key==="r")return this.widget.props.onRetry(),"handled";if(U.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new c0({decoration:{border:V,color:Z.colors.background},padding:C0.all(1),child:new u0({mainAxisAlignment:"center",children:[K,new R0({height:1}),G,F]})})})}}e9();class WO4 extends d0{props;constructor(J){super();this.props=J}createState(){return new HO4}}class HO4 extends p0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((J)=>{this.plugins=J,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(J){let Z=J.startsWith("file://")?J.slice(7):J,Q=this.widget.props.cwd;if(Z.startsWith(Q))return Z.slice(Q.length+1);return Z}statusIcon(J){let Z=c8.default(),{colors:Q,app:Y}=Z;switch(J){case"loading":return{icon:"◌",color:Q.warning};case"active":return{icon:"✓",color:Y.toolSuccess};case"error":return{icon:"✗",color:Y.toolError}}}build(J){let Z=f0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new $0({text:new C("No plugins found.",new h({dim:!0}))});let Y=[],X=this.plugins.length,V=this.plugins.filter((G)=>G.status==="active").length,K=this.plugins.reduce((G,F)=>G+F.registeredCommands.length,0),z=this.plugins.reduce((G,F)=>G+F.registeredTools.length,0);if(Y.push(new C(`${V}/${X} ${m4(X,"plugin")} active`,new h({bold:!0}))),K>0||z>0)Y.push(new C(` (${K} ${m4(K,"command")}, ${z} ${m4(z,"tool")})`,new h({dim:!0})));Y.push(new C(`
7289
+ `))}if(H)q.push(new C(" ",U)),q.push(new C("Total: ",U)),q.push(new C(V(B),F))}return new c0({decoration:{color:z.background,border:u1.all(new v1(z.border,1,"rounded"))},child:new $0({text:new C(void 0,void 0,q)})})}ow();h0();e9();import{execSync as zn5}from"node:child_process";KN();C7();H3();P7();sb();bX();a2();h$();xX();OE();_4();Gx();qk();H1();var xO4=D4(CF(),1);import{writeFile as SO4}from"fs/promises";import vO4 from"path";h0();a2();class $p0{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.1773489712-g258ad5"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await Ct(Z,this.configService)}catch(Z){j.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 sH extends d0{props;constructor(J){super();this.props=J}createState(){return new hN4}}class hN4 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 mN4 extends p0{controller=new i7;focusNode=new r4({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,V=this.controller.text.trim().length>0,K=!X||V,z=u1.all(new v1(Q.foreground,1,"solid")),G=new FJ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(W)=>{let H=W.trim();if(X&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new U1({children:[new c0({decoration:{color:Q.background},child:new $0({text:new C(">",new h({color:Q.foreground}))})}),new T1({child:G})]}),U=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("",void 0,[new C("Command: ",new h({color:Q.foreground})),new C(this.widget.props.commandName,new h({color:Y.command,bold:!0}))])})}),q=[];if(K)q.push(new C("Enter",new h({color:Y.keybind}))),q.push(new C(" to submit, ",new h({color:Q.foreground,dim:!0})));q.push(new C("Esc",new h({color:Y.keybind}))),q.push(new C(" to cancel",new h({color:Q.foreground,dim:!0})));let D=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("",void 0,q)})});return new c0({decoration:{border:z,color:Q.background},padding:C0.all(1),child:new u0({children:[U,new R0({height:1}),F,new V3,D]})})}}class dp extends d0{props;constructor(J){super();this.props=J}createState(){return new mN4}}import{isDeepStrictEqual as Jp0}from"node:util";var yi5=/[\\/_ +.#"@[({&]/,ui5=/[\\/_ +.#"@[({&]/g,xi5=/[\s-]/,gN4=/[\s-]/g;function k$0(J,Z,Q,Y,X,V,K){if(V===Z.length){if(X===J.length)return 1;return 0.99}let z=`${X},${V}`;if(K[z]!==void 0)return K[z];let G=Y.charAt(V),F=Q.indexOf(G,X),U=0,q,D,W,H;while(F>=0){if(q=k$0(J,Z,Q,Y,F+1,V+1,K),q>U){if(F===X)q*=1;else if(xi5.test(J.charAt(F-1))){if(q*=0.9,H=J.slice(X,F-1).match(gN4),H&&X>0)q*=0.999**H.length}else if(yi5.test(J.charAt(F-1))){if(q*=0.8,W=J.slice(X,F-1).match(ui5),W&&X>0)q*=0.999**W.length}else if(q*=0.3,X>0)q*=0.999**(F-X);if(J.charAt(F)!==Z.charAt(V))q*=0.9999}if(q<0.1&&(Q.charAt(F-1)===Y.charAt(V+1)||Y.charAt(V+1)===Y.charAt(V)&&Q.charAt(F-1)!==Y.charAt(V))){if(D=k$0(J,Z,Q,Y,F+1,V+2,K),D*0.1>q)q=D*0.1}if(q>U)U=q;F=Q.indexOf(G,F+1)}return K[z]=U,U}function v$0(J){return J.toLowerCase().replace(gN4," ")}function pN4(J,Z){let Q=k$0(J,Z,v$0(J),v$0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,V=0;for(let z of Y){let G=k$0(J,z,v$0(J),v$0(z),0,0,{});if(G===0)return Q;X+=G,V+=z.length}let K=X/Y.length*0.95;return Math.max(Q,K)}return Q}class hT{}class mT{}class y$0{}class u$0{}class dN4 extends d0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new cN4}}class cN4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function fi5(J,Z){if(J==="")return{matches:!0,score:1};let Q=pN4(Z,J);return{matches:Q>0.15,score:Q}}class o9 extends d0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new lN4}}class lN4 extends p0{textController;focusNode;scrollController=new Y5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new i7(this.widget.props.controller?.query??""),this.focusNode=new r4({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),H6.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)=>Jp0(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!Jp0(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>Jp0(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 hT){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof mT){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof y$0){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 u$0)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,...fi5(Q,this.widget.props.getLabel(X))})).filter((X)=>X.matches).sort(this.widget.props.sortItems?(X,V)=>this.widget.props.sortItems(X,V,J):(X,V)=>V.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;kT(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(),H6.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=u1.all(new v1(Q.foreground,1,"solid")),V=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,K=this.widget.props.enabled??!0,z=new FJ({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:K,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),G=new C2({shortcuts:new Map([[new Y4("ArrowDown"),new hT],[new Y4("ArrowUp"),new mT],[new Y4("Tab"),new hT],[new Y4("Tab",{shift:!0}),new mT],[new Y4("n",{ctrl:!0}),new hT],[new Y4("p",{ctrl:!0}),new mT],[new Y4("Enter"),new y$0],[new Y4("Escape"),new u$0]]),focusNode:this.focusNode,child:z}),F=new S9({actions:new Map([[hT,new s4(this.invoke)],[mT,new s4(this.invoke)],[y$0,new s4(this.invoke)],[u$0,new s4(this.invoke)]]),child:G}),U=new U1({children:[new c0({decoration:{color:Q.background},child:new $0({text:new C(">",new h({color:Q.foreground}))})}),new T1({child:F})]});this.itemContexts=[];let q;if(this.widget.props.isLoading){let w=this.widget.props.loadingText??"Loading...";q=new R0({height:10,child:new l1({child:new $0({text:new C(w,new h({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)q=new T1({child:new l1({child:new $0({text:new C(this.widget.props.emptyStateText,new h({color:Q.foreground,dim:!0}))})})});else{let w=Y.map((N,O)=>{let E=O===this.selectedIndex,L=this.widget.props.isItemDisabled?.(N)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(N,E,L,J);else{let A=E?Z.app.selectionBackground:void 0,I=E?Z.app.selectionForeground:Q.foreground;M=new c0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C(this.widget.props.getLabel(N),new h({color:I,dim:L}))})})}return new dN4(new n1({onClick:(A)=>this.handleItemClick(O,A.clickCount),child:M}),(A)=>{this.itemContexts[O]=A})});q=new u0({children:w,crossAxisAlignment:"start"})}let D=new n1({onScroll:this.handleScroll,opaque:!1,child:new j6({controller:this.scrollController,autofocus:!1,child:q})}),W=[];if(this.widget.props.title){let w=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C(this.widget.props.title,new h({color:Z.app.command,bold:!0}))})});W.push(w)}if(!V)W.push(U,new R0({height:1}));if(this.textController.text!==""){let w=Y.length>0?Y[this.selectedIndex]:void 0,N=w&&this.widget.props.buildDisabledReasonWidget?.(w,J);W.push(new T1({child:new u0({mainAxisAlignment:"spaceBetween",children:[new T1({child:D}),new c0({padding:C0.only({top:1}),child:new l1({child:N??new R0({height:1})})})]})}))}else W.push(new T1({child:D}));if(this.widget.props.footer)W.push(this.widget.props.footer);return new c0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new u0({children:W})})}}function iN4(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/60000),X=Math.floor(Q/3600000),V=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(V<7)return`${V}d ago`;return J.toLocaleDateString()}class Zp0 extends d1{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((X,V)=>V.pubDate.getTime()-X.pubDate.getTime()),Q=Math.max(0,...Z.map((X)=>iN4(X.pubDate).length));return new o9({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,V,K,z)=>{let G=f0.of(z),{colors:F}=G,U=G.app,q=V?U.selectionBackground:void 0,D=V?U.selectionForeground:F.foreground,W=F.mutedForeground,H=(B,w)=>new R0({width:w,child:U1.end([new $0({text:new C(B,new h({color:W}))})])});return new c0({decoration:q?{color:q}:void 0,padding:C0.symmetric(2,0),child:new U1({children:[new T1({child:new $0({text:new C(X.title,new h({color:D})),overflow:"ellipsis",maxLines:1})}),new R0({width:2}),H(iN4(X.pubDate),Q)]})})}})}}_4();class Qp0 extends d0{createState(){return new nN4}}class nN4 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 $0({text:new C("●",new h({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}var bi5=/\/threads\/(T-[^/?#\s<>]+)/i;function hi5(J){let Z=J.trim(),Y=Z.match(bi5)?.[1];if(Y&&D8(Y))return Y;let X=Z.replace(/^[<("'`]+|[>")'`,.]+$/g,"");if(D8(X))return X;return null}function mi5(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let K of J)Z.set(K.id,K);for(let K of J){let z=K.relationships.find((G)=>G.role==="child"&&Z.has(G.threadID)&&(G.type==="fork"||G.type==="handoff"));if(z){Y.set(K.id,z.type);let G=z.threadID,F=Q.get(G)||[];F.push(K),Q.set(G,F)}else X.push(K)}return X20.flatten(X,(K)=>Q.get(K.id)).map((K)=>({...K.item,depth:K.depth,isLast:K.isLast,ancestorsAreLast:K.ancestorsAreLast,relationshipType:Y.get(K.item.id)}))}function Yp0(J,Z,Q){return new $0({text:new C(`${J}${Z}`,new h({color:Q})),maxLines:1})}function gi5(J,Z,Q,Y){return[Yp0("+",J,Y.success),V3.horizontal(1),Yp0("~",Z,Y.warning),V3.horizontal(1),Yp0("-",Q,Y.destructive)]}function pi5(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class x$0 extends d0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new aN4}}class aN4 extends p0{spinner=new S3;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}`,V=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((O)=>O.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)V=V.filter((O)=>O.id!==Z.currentThreadID);let K=Z.recentThreadIDs||[],z=new Set(K),G=Z.currentThreadID,F=[...V].sort((O,E)=>{if(G){if(O.id===G)return-1;if(E.id===G)return 1}let L=K.indexOf(O.id),M=K.indexOf(E.id);if(L!==-1&&M!==-1)return L-M;if(L!==-1)return-1;if(M!==-1)return 1;return 0}),U=mi5(F),q=Math.max(0,...U.map((O)=>O.description.timeAgo.length)),D=f0.of(J),W=new i0({padding:C0.symmetric(0,1),child:new l1({child:new $0({text:new C("",new h({color:D.colors.foreground,dim:!0}),[new C("Ctrl+T",new h({color:D.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new h({color:D.colors.foreground,dim:!0}))])})})}),H="",B=null,w=(O)=>{if(O!==H)H=O,B=hi5(O);return B};return new o9({items:U,getLabel:(O)=>`${O.title} ${O.id}`,filterItem:(O,E)=>{let L=w(E);if(L)return O.id.toLowerCase()===L.toLowerCase();return!0},normalizeQuery:(O)=>w(O)?"":O,onAccept:async(O,E)=>{if(!Z.onSelect||this.isSwitchingThread)return;let L=Z.onSelect(O.id,E);if(!pi5(L))return;this.setSwitchingThread(!0);try{await L}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(O)=>{if(Z.previewController){if(O)Z.previewController.select(O.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:W,renderItem:(O,E,L,M)=>{let A=f0.of(M),{app:I,colors:P}=A,_=E?I.selectionBackground:void 0,S=E?I.selectionForeground:P.foreground,y=P.mutedForeground,m=(s,w0)=>new R0({width:w0,child:U1.end([new $0({text:new C(s,new h({color:y}))})])}),b=Z.threadViewStates[O.id],k=[],f=O.relationshipType==="handoff",p=new qp({connectorColor:P.mutedForeground});if(O.depth>0){let s=[],w0=O.ancestorsAreLast.slice(1);for(let z0 of w0)s.push(new C(p.getAncestorPrefix(z0),new h({color:p.connectorColor,dim:p.connectorDim})));let a=O.isLast?p.elbow:p.tee,F0=p.getConnectorText(a);s.push(new C(F0,new h({color:p.connectorColor,dim:p.connectorDim}))),k.push(new $0({text:new C("",void 0,s)}))}let l=[],x=G===O.id?new C("(current) ",new h({color:P.success})):z.has(O.id)?new C("(visited) ",new h({color:P.foreground,dim:!0})):null;if(x)l.push(new $0({text:x}));if(gO(b))l.push(new Qp0),l.push(new R0({width:1}));let r=O.title;if(O.relationshipType==="fork"){let s=r.match(/^Forked\((\d+)\): /);if(s)r=r.slice(s[0].length);else while(r.startsWith("Forked: "))r=r.slice(8);l.push(new $0({text:new C("[fork] ",new h({color:P.primary}))}))}else if(f)l.push(new $0({text:new C("[handoff] ",new h({color:P.accent}))}));if(l.push(new T1({child:new $0({text:new C(r,new h({color:S})),overflow:"ellipsis",maxLines:1})})),l.push(new R0({width:2})),O.diffStats&&(O.diffStats.added>0||O.diffStats.changed>0||O.diffStats.deleted>0)){let s=E?{success:y,warning:y,destructive:y}:P;l.push(...gi5(O.diffStats.added,O.diffStats.changed,O.diffStats.deleted,s)),l.push(new R0({width:2}))}return l.push(m(O.description.timeAgo,q)),new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new U1({children:[...k,...l]})})}})}}function oN4(J){return 1-(1-J)**3}function rN4(J,Z,Q){return J+(Z-J)*Q}function cp(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),V=oN4(Y),K=oN4(X);return{x:rN4(J.startOffset.x,J.targetOffset.x,V),y:rN4(J.startOffset.y,J.targetOffset.y,K)}}var di5={nodeWidth:3,horizontalSpacing:3};class gT{options;constructor(J={}){this.options={...di5,...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 V=0,K=(z,G)=>{let F=Z.get(z.id)??[];if(this.options.comparator)F.sort(this.options.comparator);let U={...z,parentID:Q.get(z.id)};if(F.length===0){Y.push({node:U,position:{x:V,y:G}});let B=V;return V+=this.options.nodeWidth+this.options.horizontalSpacing,B}let q=[];for(let B of F)q.push(K(B,G+1));let D=Math.min(...q),W=Math.max(...q),H=Math.floor((D+W)/2);return Y.push({node:U,position:{x:H,y:G}}),H};for(let z of X)K(z,0);return Y}buildTree(J){let Z=new Set(J.map((V)=>V.id)),Q=[...J].sort((V,K)=>V.id.localeCompare(K.id)),Y=new Map;for(let V of Q){if(!V.parentID||!Z.has(V.parentID)){Y.set(V.id,void 0);continue}let K=!1,z=V.parentID;while(z){if(z===V.id){K=!0;break}z=Y.get(z)}Y.set(V.id,K?void 0:V.parentID)}let X=new Map;for(let V of J){let K=Y.get(V.id);if(!X.has(K))X.set(K,[]);X.get(K).push(V)}return{childrenMap:X,resolvedParent:Y}}}var ci5={nodeWidth:3,nodeHeight:2};class pT{options;constructor(J={}){this.options={...ci5,...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 V=this.calculateConnectorLine(X.position,Y.position);Z.push({points:V,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,V=Z.x+Q,K=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:K});let z=K+1;if(Y.push({x:X,y:z}),X!==V)Y.push({x:V,y:z});let G=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:V,y:G}),Y}}var li5={nodeWidth:3,nodeHeight:2},ii5={x:0,y:0};class b$0{options;constructor(J={}){this.options={...li5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=ii5,X,V,K,z){let G=z?f0.of(z):null,F=G?.colors,U=G?.app,q=F?.mutedForeground??F?.foreground;if(J.length===0)return new $0({text:new C("No nodes",new h({color:q}))});let D=Math.max(...J.map((I)=>I.position.y)),H=Math.max(...J.map((I)=>I.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,w=[];for(let I=D;I>=0;I--){let P=J.filter((y)=>y.position.y===I);P.sort((y,m)=>y.position.x-m.position.x);let _=[],S=0;for(let y of P){if(y.position.x>S)_.push(new R0({width:y.position.x-S}));let m=y.node.id===Q,b=K?.(y.node.data)??!1,k=V?.activeFlashOn??!1,f=y.node.id===V?.copyFlashNodeId;_.push(this.renderNode(m,b,k,f,U,F)),S=y.position.x+this.options.nodeWidth}if(w.push(new U1({crossAxisAlignment:"start",children:_})),I>0){let y=J.filter((k)=>k.position.y===I-1),m=P,b=this.renderConnectors(y,m,Z,H,F,U);w.push(...b)}}let N=new u0({crossAxisAlignment:"start",children:w}),O=Math.round(Y.x),E=Math.round(Y.y*B),L=(D+1)*B,M=[new R0({width:H,height:L}),new x6({left:O,top:E,child:N})],A=Q?J.find((I)=>I.node.id===Q):void 0;if(A&&X){let I=X(A.node.data),P=D-A.position.y,_=O+A.position.x+this.options.nodeWidth+1,S=E+P*B+1,y=30;if(V?.maxTitleWidthPercent&&V.viewportWidth)y=Math.floor(V.viewportWidth*V.maxTitleWidthPercent/100);M.push(new x6({left:_,top:S,child:this.renderInfoBox(I,y,F,U)}))}return new c0({padding:C0.horizontal(2),child:new LH(new i6({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,V){let K="┌─┐",z="└─┘",G=J?X?.threadGraphNodeSelected??V?.primary??V?.foreground:X?.threadGraphNode??V?.primary??V?.foreground,F=!1;if(Y)G=X?.threadGraphNodeSelected??V?.primary??G,K="┏━┓",z="┗━┛",F=!0;else if(Z&&Q)G=X?.toolSuccess??V?.primary??G,K="┏━┓",z="┗━┛";return new u0({crossAxisAlignment:"start",children:[new $0({text:new C(K,new h({color:G,bold:F}))}),new $0({text:new C(z,new h({color:G,bold:F}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let V of Q){if(V.length>Z)V=V.slice(0,Z-1)+"…";if(X.length===0)X=V;else if(X.length+1+V.length<=Z)X+=" "+V;else Y.push(X),X=V}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),V=Math.min(Z,Math.max(1,...X.map((D)=>D.length))),K=V+2,z="┌"+"─".repeat(K)+"┐",G="└"+"─".repeat(K)+"┘",F=Q?.border??Y?.threadGraphConnector??Q?.foreground,U=Q?.foreground,q=[new $0({text:new C(z,new h({color:F}))})];for(let D of X){let W=" ".repeat(V-D.length);q.push(new $0({text:new C("│ ",new h({color:F}),[new C(D+W,new h({color:U??F})),new C(" │",new h({color:F}))])}))}return q.push(new $0({text:new C(G,new h({color:F}))})),new u0({crossAxisAlignment:"start",children:q})}renderConnectors(J,Z,Q,Y,X,V){let K=[],z=Math.floor(this.options.nodeWidth/2),G=V?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let D of Z){let W=D.position.x+z;if(W>=0&&W<Y)F[W]="▲"}K.push(new $0({text:new C(F.join(""),new h({color:G}))}));let U=Array(Y).fill(" ");for(let D of J){let W=Z.filter((O)=>O.node.parentID===D.node.id);if(W.length===0)continue;let H=D.position.x+z,B=W.map((O)=>O.position.x+z),w=Math.min(...B),N=Math.max(...B);for(let O=w;O<=N;O++)if(O>=0&&O<Y){if(O===H)if(W.length===1&&B[0]===H)U[O]="│";else if(O===w)U[O]="└";else if(O===N)U[O]="┘";else U[O]="┬";else if(B.includes(O))if(O===w)U[O]="└";else if(O===N)U[O]="┘";else U[O]="┴";else if(U[O]===" ")U[O]="─"}}K.push(new $0({text:new C(U.join(""),new h({color:G}))}));let q=Array(Y).fill(" ");for(let D of J){if(Z.filter((B)=>B.node.parentID===D.node.id).length===0)continue;let H=D.position.x+z;if(H>=0&&H<Y)q[H]="│"}return K.push(new $0({text:new C(q.join(""),new h({color:G}))})),K}}var ni5={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},ai5={x:0,y:0};class Xp0{options;constructor(J={}){this.options={...ni5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=ai5,X,V,K,z){let G=z?f0.of(z):null,F=G?.colors,U=G?.app,q=F?.mutedForeground??F?.foreground;if(J.length===0)return new $0({text:new C("No nodes",new h({color:q}))});let D=Math.max(...J.map((I)=>I.position.y)),H=Math.max(...J.map((I)=>I.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,w=[];for(let I=D;I>=0;I--){let P=J.filter((y)=>y.position.y===I);P.sort((y,m)=>y.position.x-m.position.x);let _=[],S=0;for(let y of P){if(y.position.x>S)_.push(new R0({width:y.position.x-S}));let m=y.node.id===Q,b=K?.(y.node.data)??!1,k=V?.activeFlashOn??!1;_.push(this.renderNode(m,b,k,U,F)),S=y.position.x+this.options.nodeWidth}if(w.push(new U1({crossAxisAlignment:"start",children:_})),I>0){let y=J.filter((k)=>k.position.y===I-1),m=P,b=this.renderConnectors(y,m,Z,H,F,U);w.push(...b)}}let N=new u0({crossAxisAlignment:"start",children:w}),O=Math.round(Y.x),E=Math.round(Y.y*B),L=(D+1)*B,M=[new R0({width:H,height:L}),new x6({left:O,top:E,child:N})],A=Q?J.find((I)=>I.node.id===Q):void 0;if(A&&X){let I=X(A.node.data),P=D-A.position.y,_=O+A.position.x+this.options.nodeWidth+1,S=E+P*B,y=30;if(V?.maxTitleWidthPercent&&V.viewportWidth)y=Math.floor(V.viewportWidth*V.maxTitleWidthPercent/100);M.push(new x6({left:_,top:S,child:this.renderInfoBox(I,y,F)}))}return new c0({padding:C0.horizontal(2),child:new LH(new i6({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X){let V=J?this.options.selectedIcon:this.options.nodeIcon,K=J?Y?.threadGraphNodeSelected??X?.primary??X?.foreground:Y?.threadGraphNode??X?.primary??X?.foreground;if(Z&&Q)K=Y?.toolSuccess??X?.primary??K,V="■";return new $0({text:new C(V,new h({color:K}))})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let V of Q){if(V.length>Z)V=V.slice(0,Z-1)+"…";if(X.length===0)X=V;else if(X.length+1+V.length<=Z)X+=" "+V;else Y.push(X),X=V}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q){let Y=this.wrapText(J,Z),X=Q?.foreground,V=[];for(let K of Y)V.push(new $0({text:new C(K,new h({color:X??Q?.primary??Q?.foreground}))}));return new u0({crossAxisAlignment:"start",children:V})}renderConnectors(J,Z,Q,Y,X,V){let K=[],z=Math.floor(this.options.nodeWidth/2),G=V?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let U of J){let q=Z.filter((w)=>w.node.parentID===U.node.id);if(q.length===0)continue;let D=U.position.x+z,W=q.map((w)=>w.position.x+z),H=Math.min(...W),B=Math.max(...W);for(let w=H;w<=B;w++)if(w>=0&&w<Y){let N=w===D,O=W.includes(w);if(N&&O)if(q.length===1)F[w]="│";else if(w===H)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┼";else if(N)if(w===H)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┬";else if(O)if(w===H)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┴";else if(F[w]===" ")F[w]="─"}}return K.push(new $0({text:new C(F.join(""),new h({color:G}))})),K}}class lp extends N3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new sN4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class sN4 extends A4{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 bL extends d0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new $O4}}var tN4=400,eN4=300,oi5=16;class $O4 extends p0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new gT({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new pT;renderer=new Xp0;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,V=this.widget.props.initialSelectedThreadID;if(X!==V&&V){let F=this.widget.props.threads.find((U)=>U.id===V);if(F)this.selectedNodeId=F.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let K=J.props.threads.some((G)=>G.isActive),z=this.widget.props.threads.some((G)=>G.isActive);if(K!==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:tN4,durationY:eN4};let Z=Math.max(tN4,eN4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=cp(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},oi5)}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),V=Math.floor(this.viewportWidth/2)-J-Y,K=Q-Z,z=2,G=Math.floor(this.viewportHeight/2),U=Math.floor(G/2)-K;return{x:V,y:U}}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((V)=>V.node.parentID===Q.node.id);if(X.length>0){X.sort((K,z)=>K.position.x-z.position.x);let V=Math.floor(X.length/2);Y=X[V]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((V)=>V.position.y===Q.position.y&&V.position.x<Q.position.x);if(X.length>0)X.sort((V,K)=>K.position.x-V.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((V)=>V.position.y===Q.position.y&&V.position.x>Q.position.x);if(X.length>0)X.sort((V,K)=>V.position.x-K.position.x),Y=X[0];break}case"Enter":{if(this.widget.props.onSelect)this.widget.props.onSelect(this.toThreadNode(Q));return"handled"}default:{if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"}}if(Y)return this.selectedNodeId=Y.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(Y)),this.animateToNode(Y.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let U=(this.selectedNodeId?this.positionedNodes.find((q)=>q.node.id===this.selectedNodeId):null)??this.positionedNodes.find((q)=>!q.node.parentID);if(U){let q=Math.max(...this.positionedNodes.map((D)=>D.position.y));this.currentOffset=this.calculateCenterOffset(U.position.x,U.position.y,q)}}let X=this.widget.props.showTitle??!0,V=this.widget.props.offsetY??0,K={x:this.currentOffset.x,y:this.currentOffset.y+V},z=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,K,X?(F)=>F.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(F)=>F.isActive??!1,J),G=new lp({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 k4({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 ZO4 extends d0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new QO4}}class QO4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}var JO4=30,ri5=30;class dT{}class cT{}class h$0{}class m$0{}class Vp0 extends d0{props;constructor(J){super();this.props=J}createState(){return new YO4}}class YO4 extends p0{highlightedIndex=0;controller=new i7;focusNode;scrollController=new Y5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new r4({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),H6.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;kT(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 dT){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof cT){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof h$0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof m$0)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Z)=>{if(J>=0&&J<this.filteredClusters.length){if(Z===1)this.highlightedIndex=J,this.setState();else if(Z===2){let Q=this.filteredClusters[J];if(Q)this.widget.props.onAccept(Q)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return!1;let Z=this.highlightedIndex;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return!1;else if(this.highlightedIndex>0)this.highlightedIndex--;else return!1;return this.setState(),H6.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=t1.of(J).size.width>=ri5+JO4,G=u1.all(new v1(Y.foreground,1,"solid")),F=this.filteredClusters[this.highlightedIndex]??null,U=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("Select a cluster",new h({color:X.command,bold:!0}))})}),q=new FJ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),D=new C2({shortcuts:new Map([[new Y4("ArrowDown"),new dT],[new Y4("ArrowUp"),new cT],[new Y4("Tab"),new dT],[new Y4("Tab",{shift:!0}),new cT],[new Y4("n",{ctrl:!0}),new dT],[new Y4("p",{ctrl:!0}),new cT],[new Y4("Enter"),new h$0],[new Y4("Escape"),new m$0]]),focusNode:this.focusNode,child:q}),W=new S9({actions:new Map([[dT,new s4(this.invoke)],[cT,new s4(this.invoke)],[h$0,new s4(this.invoke)],[m$0,new s4(this.invoke)]]),child:D}),H=new U1({children:[new c0({decoration:{color:Y.background},child:new $0({text:new C(">",new h({color:Y.foreground}))})}),new T1({child:W})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let I=A===this.highlightedIndex,P=Z?M.threads.some((m)=>m.id===Z):!1,_=I?X.selectionBackground:void 0,S=I?X.selectionForeground:Y.foreground,y=[new C(M.label,new h({color:S})),new C(` (${M.threads.length})`,new h({color:S,dim:!0}))];if(P)y.push(new C(" (current)",new h({color:I?X.selectionForeground:Y.success})));return new ZO4(new n1({onClick:(m)=>this.handleItemClick(A,m.clickCount),child:new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C("",void 0,y)})})}),(m)=>{this.itemContexts[A]=m})}),w=new u0({children:B,crossAxisAlignment:"start"}),N=new T1({child:new n1({onScroll:this.handleScroll,child:new j6({controller:this.scrollController,autofocus:!1,child:w})})}),O=F?F.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],E=F?new c0({padding:C0.all(1),child:new bL({threads:O,autofocus:!1,offsetY:2})}):null,L;if(z){let M=E?new T1({child:E}):new R0({width:JO4});L=new U1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[N,M]})}else{let M=[new T1({child:new n1({onScroll:this.handleScroll,child:new j6({controller:this.scrollController,autofocus:!1,child:w})})})];if(E)M.push(new T1({child:E}));L=new u0({crossAxisAlignment:"stretch",children:M})}return new c0({decoration:{border:G,color:Y.background},padding:C0.symmetric(1,0),child:new u0({children:[U,H,new R0({height:1}),new T1({child:L})]})})}}class UJ{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!UJ._instance)UJ._instance=new UJ;return UJ._instance}get allExpanded(){return this._allExpanded}setAllExpanded(J){if(this._allExpanded===J)return;this._allExpanded=J,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(J){return this._listeners.add(J),()=>this.removeListener(J)}removeListener(J){this._listeners.delete(J)}_notifyListeners(){for(let J of this._listeners)J()}}h0();class XO4 extends p0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){j.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){j.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){let Z=J.trim().toLowerCase();if(Z.length===0)return null;if(Z.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Z))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Z)=>!J.includes(Z.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Z=J.trim().toLowerCase();if(!this.isValidLabelName(Z))return!1;let Q=this.widget.props.currentLabels||[],Y=this.labels.some((V)=>V.name===Z),X=Q.includes(Z);return!Y&&!X}build(J){let Z=f0.of(J),{app:Q,colors:Y}=Z,X=this.currentQuery.trim().toLowerCase(),V=X.length>0?this.getValidationError(X):null,K=this.getAvailableLabels(),G=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...K];return new o9({title:"Add Label",items:G,getLabel:(F)=>{if("__isCreateMarker"in F)return this.currentQuery.trim().toLowerCase();return F.name},onAccept:(F)=>{if("__isCreateMarker"in F)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(F.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:V||"Type to create a new label",renderItem:(F,U,q,D)=>{let W=U?Q.selectionBackground:void 0,H=U?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in F&&F.__isCreateMarker){let w=this.currentQuery.trim().toLowerCase();return new c0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C("",void 0,[new C("Create new label: ",new h({color:H})),new C(w,new h({color:H,bold:!0}))])})})}return new c0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C(F.name,new h({color:H}))})})},filterItem:(F,U)=>{if(this.currentQuery!==U)this.currentQuery=U,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in F&&F.__isCreateMarker)return this.shouldShowCreateMarker(U);let D=U.trim().toLowerCase();return D.length===0||F.name.includes(D)},sortItems:(F,U,q)=>{let D="__isCreateMarker"in F.item&&F.item.__isCreateMarker,W="__isCreateMarker"in U.item&&U.item.__isCreateMarker;if(D&&!W)return-1;if(!D&&W)return 1;return U.score-F.score}})}}class Kp0 extends d0{props;constructor(J){super();this.props=J}createState(){return new XO4}}class iV extends d0{props;constructor(J){super();this.props=J}createState(){return new VO4}}class VO4 extends p0{_spinner=new S3;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=u1.all(new v1(Q.foreground,1,"solid")),V=this._spinner.toBraille(),K=new $0({textAlign:"center",text:new C("",void 0,[new C(V,new h({color:Y.processing})),new C(" ",void 0),new C(this.widget.props.message,new h({color:Q.foreground}))])}),G=[new T1({child:new u0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[K]})})];if(this.widget.props.onAbort)G.push(new R0({height:2,child:new c0({padding:C0.symmetric(2,0),child:new $0({text:new C("",new h({dim:!0}),[new C("Press ",new h({color:Q.foreground})),new C("Esc",new h({color:Q.info})),new C(" to cancel",new h({color:Q.foreground}))])})})}));let F=new c0({decoration:new v4(Q.background,X),child:new R0({width:60,height:7,child:new u0({mainAxisAlignment:"start",children:G})})});if(this.widget.props.onAbort)return new k4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(U)=>{if(U.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:F});return F}}var ip={workspace:{label:"Workspace",pathHint:".amp/settings.json",description:"workspace config"},global:{label:"Global",pathHint:"~/.config/amp/settings.json",description:"global config"},flag:{label:"Flag",pathHint:"CLI flags",description:"flag config"},default:{label:"Default",pathHint:"built-in defaults",description:"default config"},external:{label:"External",pathHint:"extensions / external",description:"external source"},skill:{label:"Skills",pathHint:".agents/skills/",description:"skill source"},other:{label:"Other",pathHint:"",description:"other source"}},g$0=["workspace","global","flag","default","external","skill","other"];function si5(J){return Array.from(new Set(J))}function KO4(J){return si5([...J.skillNames??[],...J.skillName?[J.skillName]:[]])}function lT(J){if(J.isExternal)return"external";switch(J.spec._target){case"workspace":return"workspace";case"global":return"global";case"flag":return"flag";case"default":return"default"}return KO4(J).length>0?"skill":"other"}function zp0(J){return lT(J)==="skill"}function zO4(J){let Z=KO4(J);if(Z.length===0)return;let Q=Z.join(", "),Y=lT(J);if(Y==="skill")return`skills: ${Q}`;return`${Z.length===1?"skill source":"skill sources"} overridden by ${ip[Y].description}: ${Q}`}function GO4(J){return J.spec.meta?.skillNames?Array.from(J.spec.meta.skillNames):[]}class u8 extends d0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X="█",thumbChar:V="█",showTrack:K=!0,thumbColor:z,trackColor:G}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=V,this.showTrack=K,this.thumbColor=z,this.trackColor=G}createState(){return new FO4}}class FO4 extends p0{_dragStartY=null;_dragStartOffset=null;_isOverThumb=!1;_isPositionOverThumb(J){let{totalContentHeight:Z,viewportHeight:Q}=this.widget.getScrollInfo(),X=this.context.findRenderObject()?.size.height??0;if(X===0||Z<=Q)return!1;let V=this.widget.getScrollInfo(),K=Math.min(1,Q/Z),z=Math.max(1,X*K),G=Math.max(0,Math.min(1,V.scrollOffset/(Z-Q))),F=X-z,U=Math.max(0,F*G),q=U+z;return J>=U&&J<=q}_handleHover=(J)=>{let Z=this._isOverThumb;if(this._isOverThumb=this._isPositionOverThumb(J.localPosition.y),Z!==this._isOverThumb)this.setState()};_handleDrag=(J)=>{let{totalContentHeight:Z,viewportHeight:Q,scrollOffset:Y}=this.widget.getScrollInfo(),V=this.context.findRenderObject()?.size.height??0;if(V===0||Z<=Q)return;if(this._dragStartY===null)this._dragStartY=J.localPosition.y,this._dragStartOffset=Y;let K=J.localPosition.y-this._dragStartY,z=Math.min(1,Q/Z),G=Math.max(1,V*z),F=V-G;if(F<=0)return;let U=Z-Q,q=F/U,D=K/q,W=Math.max(0,Math.min(U,this._dragStartOffset+D));this.widget.controller.jumpTo(W)};_handleRelease=()=>{this._dragStartY=null,this._dragStartOffset=null};_handleClick=(J)=>{if(J.button!=="left")return;let Z=J.localPosition.y,{totalContentHeight:Q,viewportHeight:Y,scrollOffset:X}=this.widget.getScrollInfo(),K=this.context.findRenderObject()?.size.height??0;if(K===0||Q<=Y)return;let z=Math.min(1,Y/Q),G=Math.max(1,K*z),F=Q-Y,U=K-G,q=Math.max(0,Math.min(1,X/(Q-Y))),D=Math.max(0,U*q),W=D+G;if(Z>=D&&Z<=W)return;if(Z<D)this.widget.controller.animateTo(Math.max(0,X-Y));else this.widget.controller.animateTo(Math.min(F,X+Y))};build(J){return new n1({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?E5.POINTER:E5.DEFAULT,child:new UO4({controller:this.widget.controller,getScrollInfo:this.widget.getScrollInfo,thickness:this.widget.thickness,trackChar:this.widget.trackChar,thumbChar:this.widget.thumbChar,showTrack:this.widget.showTrack,thumbColor:this.widget.thumbColor,trackColor:this.widget.trackColor})})}}class UO4 extends dC{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X="█",thumbChar:V="█",showTrack:K=!0,thumbColor:z,trackColor:G}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=V,this.showTrack=K,this.thumbColor=z,this.trackColor=G}createRenderObject(){return new qO4(this)}updateRenderObject(J){J.updateWidget(this)}}class qO4 extends A4{_widget;constructor(J){super();this._widget=J}updateWidget(J){this._widget=J,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;f4(!!J,"performLayout called without constraints");let Z=Math.min(J.maxWidth,this._widget.thickness),Q=J.maxHeight;this.setSize(Z,Q),super.performLayout()}getMinIntrinsicWidth(J){return this._widget.thickness}getMaxIntrinsicWidth(J){return this._widget.thickness}getMinIntrinsicHeight(J){return 0}getMaxIntrinsicHeight(J){return 0}paint(J,Z,Q){let{thumbStartFloat:Y,thumbSizeFloat:X,showScrollbar:V}=this._calculateScrollbarMetrics();if(!V)return;let K=this._widget.trackColor,z=this._widget.thumbColor,G=["▁","▂","▃","▄","▅","▆","▇","█"],F=Y,U=Y+X;for(let q=0;q<this.size.height;q++){let D="█",W=!0;if(q===Math.floor(F)){let H=1-(F-q),B=Math.floor(H*8);D=G[B]||"█",W=!1}else if(q===Math.floor(U)){let H=1-(U-q),B=Math.floor(H*8);D=G[B]||"█"}else if(q>F&&q<U)W=!1;J.setChar(Z,Q+q,D,{fg:z,bg:K,reverse:W},1)}}_calculateScrollbarMetrics(){let{totalContentHeight:J,viewportHeight:Z,scrollOffset:Q}=this._widget.getScrollInfo(),Y=this.size.height;if(J<=Z||Y<=0)return{thumbStartFloat:0,thumbSizeFloat:0,showScrollbar:!1};let X=Math.max(0,Math.min(1,Q/(J-Z))),V=Math.min(1,Z/J),K=Math.max(1,Y*V),z=Y-K;return{thumbStartFloat:Math.max(0,z*X),thumbSizeFloat:K,showScrollbar:!0}}}class hL extends d0{props;constructor(J){super();this.props=J}createState(){return new DO4}}class DO4 extends p0{scrollController=new Y5;scrollAreaKey=new g7("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(J){return J instanceof S2}resolveFooterStyle(J){if(this.isWidgetMessage(J))return J.footerStyle;return"default"}getViewportHeight(){let Z=this.scrollAreaKey.currentElement?.renderObject;if(Z&&"size"in Z){let Q=Z.size;if(typeof Q.height==="number"&&Q.height>0)return this.viewportHeight=Q.height,Q.height}return this.viewportHeight}build(J){let Z=f0.of(J),Q=this.widget.props.message,Y=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let U=B$0(Q);return{title:U.title,type:U.type,description:U.description}})(),X=Y.type==="error"?Z.app.toolError:Z.app.command,V=u1.all(new v1(Z.colors.border,1,"solid")),K=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C(Y.title,new h({color:X,bold:!0}))})}),z=this.isWidgetMessage(Q)?Q.widget:new $0({text:new C(Y.description,new h({color:Z.colors.foreground})),selectable:!0}),G=new T1({child:new T2({child:new c0({padding:C0.symmetric(1,0),child:new U1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new T1({child:new j6({controller:this.scrollController,autofocus:!0,child:z})}),new u8({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let U=this.scrollController.maxScrollExtent,q=this.scrollController.offset,D=this.getViewportHeight(),W=U+D;return{totalContentHeight:Math.max(W,0),viewportHeight:Math.max(D,1),scrollOffset:Math.max(q,0)}}})]})})})}),F=new c0({padding:C0.symmetric(1,0),child:new $0({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new h({color:Z.colors.foreground,dim:!0})),new C("R",new h({color:Z.app.keybind})),new C(" to retry, ",new h({color:Z.colors.foreground,dim:!0})),new C("Esc",new h({color:Z.app.keybind})),new C(" to cancel",new h({color:Z.colors.foreground,dim:!0}))]);let U=this.resolveFooterStyle(this.widget.props.message);if(U==="none")return new C("",new h({color:Z.colors.foreground,dim:!0}));if(U==="help"){let q=new h({color:Z.app.keybind}),D=new h({color:Z.colors.foreground,dim:!0});return new C("",D,[new C("Press ",D),new C("Escape",q),new C(" to close • Use ",D),new C("↑↓",q),new C(" or ",D),new C("j/k",q),new C(" to scroll",D)])}return new C("Press any key to close",new h({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new k4({onKey:(U)=>{if(this.widget.props.onRetry&&U.key==="r")return this.widget.props.onRetry(),"handled";if(U.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new c0({decoration:{border:V,color:Z.colors.background},padding:C0.all(1),child:new u0({mainAxisAlignment:"center",children:[K,new R0({height:1}),G,F]})})})}}e9();class WO4 extends d0{props;constructor(J){super();this.props=J}createState(){return new HO4}}class HO4 extends p0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((J)=>{this.plugins=J,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(J){let Z=J.startsWith("file://")?J.slice(7):J,Q=this.widget.props.cwd;if(Z.startsWith(Q))return Z.slice(Q.length+1);return Z}statusIcon(J){let Z=c8.default(),{colors:Q,app:Y}=Z;switch(J){case"loading":return{icon:"◌",color:Q.warning};case"active":return{icon:"✓",color:Y.toolSuccess};case"error":return{icon:"✗",color:Y.toolError}}}build(J){let Z=f0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new $0({text:new C("No plugins found.",new h({dim:!0}))});let Y=[],X=this.plugins.length,V=this.plugins.filter((G)=>G.status==="active").length,K=this.plugins.reduce((G,F)=>G+F.registeredCommands.length,0),z=this.plugins.reduce((G,F)=>G+F.registeredTools.length,0);if(Y.push(new C(`${V}/${X} ${m4(X,"plugin")} active`,new h({bold:!0}))),K>0||z>0)Y.push(new C(` (${K} ${m4(K,"command")}, ${z} ${m4(z,"tool")})`,new h({dim:!0})));Y.push(new C(`
7290
7290
 
7291
7291
  `));for(let G of this.plugins){let{icon:F,color:U}=this.statusIcon(G.status),q=this.getRelativePath(G.uri.toString());if(Y.push(new C(`${F} `,new h({color:U}))),Y.push(new C(q,new h({bold:!0}))),Y.push(new C(` ${G.status}`,new h({dim:!0}))),Y.push(new C(`
7292
7292
  `)),G.status==="active"&&G.registeredEvents.length>0)Y.push(new C(" Events: ",new h({dim:!0}))),Y.push(new C(G.registeredEvents.join(", "),new h({color:Q.link}))),Y.push(new C(`
@@ -7497,12 +7497,12 @@ ${O0.join(`
7497
7497
  ---
7498
7498
 
7499
7499
  ${Z0.content||""}`:Z0.content||"",a0=[],F1=Z0.baseDir.startsWith("file://")?IJ0(Z0.baseDir):Z0.baseDir,a1=(Z0.files||[]).filter((V1)=>!V1.toLowerCase().endsWith("skill.md"));if(!K0){a0.push(new R0({height:1})),a0.push(new $0({text:new C("─".repeat(P-4),q)})),a0.push(new R0({height:1})),a0.push(new $0({text:new C("Files:",q)})),a0.push(new n1({cursor:"pointer",onClick:()=>{w8(J,`${Z0.baseDir}/SKILL.md`)},child:new $0({text:new C(" SKILL.md",new h({color:Q.primary}))})}));for(let V1 of a1){let t0=kM4(F1,V1),A1=V1.startsWith("/")?`file://${V1}`:`${Z0.baseDir}/${V1}`;a0.push(new n1({cursor:"pointer",onClick:()=>{w8(J,A1)},child:new $0({text:new C(` ${t0}`,new h({color:Q.primary}))})}))}}let o1=K0?new $0({text:new C("SKILL.md",q)}):new n1({cursor:"pointer",onClick:()=>{w8(J,`${Z0.baseDir}/SKILL.md`)},child:new $0({text:new C("SKILL.md",new h({color:Q.primary}))})}),m0=new u0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[o1,new R0({height:1}),...e0?[new $0({text:new C(e0,U)})]:[],...a0]});q0=new c0({constraints:new M1({minWidth:P,maxWidth:P}),decoration:new v4(void 0,new u1(void 0,void 0,void 0,new v1(Q.border,1))),padding:C0.only({left:2}),child:new u0({crossAxisAlignment:"stretch",children:[D0,new R0({height:1}),new T1({child:new U1({crossAxisAlignment:"stretch",children:[new T1({child:new j6({controller:this.detailScrollController,child:m0})}),new u8({controller:this.detailScrollController,thumbColor:X.scrollbarThumb,trackColor:X.scrollbarTrack,getScrollInfo:()=>{let V1=this.detailScrollController.maxScrollExtent,t0=this.detailScrollController.offset;return{totalContentHeight:Math.max(V1+20,0),viewportHeight:20,scrollOffset:Math.max(t0,0)}}})]})})]})})}let Q0=new T1({child:new i0({padding:A?C0.only({right:1}):C0.all(0),child:new U1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new T1({child:new j6({controller:this.listScrollController,child:z0})}),new u8({controller:this.listScrollController,thumbColor:X.scrollbarThumb,trackColor:X.scrollbarTrack,getScrollInfo:()=>{let Z0=this.getViewportHeight(),K0=this.listScrollController.maxScrollExtent,t=this.listScrollController.offset;return{totalContentHeight:Math.max(K0+Z0,0),viewportHeight:Z0,scrollOffset:Math.max(t,0)}}})]})})}),H0=new l1({child:new $0({text:new C("",N,[new C("Escape",B),new C(" to close",N)])})}),i=new T1({child:new c0({padding:C0.symmetric(1,0),child:new U1({crossAxisAlignment:"stretch",children:[Q0]})})}),e=[new T1({child:new u0({crossAxisAlignment:"stretch",children:[s,new R0({height:1}),i,new R0({height:1}),H0]})})];if(q0)e.push(q0);let J0=new U1({crossAxisAlignment:"stretch",children:e});return new k4({autofocus:!0,focusNode:this.focusNode,onKey:this.handleKeyEvent,child:new l1({child:new c0({constraints:new M1(I,I,0,M),decoration:new v4(Q.background,u1.all(new v1(Q.primary,1,"rounded"))),child:new i0({padding:C0.all(1),child:J0})})})})}}class sd0 extends d0{props;constructor(J){super();this.props=J}createState(){return new uM4}}class uM4 extends p0{_scrollController=new Y5;_viewportHeight=0;getOptions(){return[{value:"remove",label:"Remove skill"},{value:"close",label:"Close"}]}handleSelect=(J)=>{if(!J){this.widget.props.onDismiss();return}switch(J){case"remove":this.widget.props.onRemove();break;case"close":this.widget.props.onDismiss();break}};dispose(){this._scrollController.dispose(),super.dispose()}build(J){let{pendingSkill:Z,skill:Q}=this.widget.props,Y=I1.of(J).colorScheme,X=f0.of(J),V=t1.sizeOf(J),K=V.width,z=V.height,G=Math.min(K-12,80),F=Math.min(z-4,30),U=16,q=F-16,D=[];if(Q?.description){if(D.push(new $0({text:new C(Q.description,new h({color:Y.foreground}))})),D.push(new R0({height:1})),Q.content&&q>2){D.push(new $0({text:new C("─".repeat(G-6),new h({color:Y.foreground,dim:!0}))})),D.push(new R0({height:1}));let H=Q.content.split(`
7500
- `).length,B=Math.max(Math.min(H,q),3);this._viewportHeight=B;let w=new a3({markdown:Q.content}),N=new c0({constraints:new M1({maxHeight:B}),child:new U1({crossAxisAlignment:"stretch",children:[new T1({child:new j6({controller:this._scrollController,autofocus:!1,child:w})}),new u8({controller:this._scrollController,thumbColor:X.app.scrollbarThumb,trackColor:X.app.scrollbarTrack,getScrollInfo:()=>{let O=this._scrollController.maxScrollExtent,E=this._scrollController.offset,L=this._viewportHeight,M=O+L;return{totalContentHeight:Math.max(M,0),viewportHeight:Math.max(L,1),scrollOffset:Math.max(E,0)}}})]})});D.push(N),D.push(new R0({height:1}))}}else D.push(new $0({text:new C("(Loading skill details...)",new h({color:Y.foreground,dim:!0,italic:!0}))})),D.push(new R0({height:1}));if(Z.arguments)D.push(new $0({text:new C("",void 0,[new C("Arguments: ",new h({color:Y.foreground,dim:!0})),new C(Z.arguments,new h({color:Y.foreground}))])})),D.push(new R0({height:1}));let W=new u0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new $0({text:new C("",void 0,[new C(Z.name,new h({bold:!0,color:Y.success,underline:!0}))])}),new R0({height:1}),...D,new c7({options:this.getOptions(),onSelect:this.handleSelect,autofocus:!0,showDismissalMessage:!1,enableMouseInteraction:!0})]});return new k4({onKey:(H)=>{if(H.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"},child:new l1({child:new LH(new c0({constraints:new M1(G,G,0,F),decoration:{color:Y.background,border:u1.all(new v1(Y.success,1,"rounded"))},padding:C0.symmetric(2,1),child:W}))})})}}function Ns5(J,Z){if(J===Z)return!0;let Q=Object.keys(J),Y=Object.keys(Z);if(Q.length!==Y.length)return!1;for(let X of Q){if(!(X in Z))return!1;if(!Object.is(J[X],Z[X]))return!1}return!0}class td0 extends d0{stableProps;arePropsEqual;constructor({key:J,stableProps:Z,arePropsEqual:Q}){super(J?{key:J}:{});this.stableProps=Z,this.arePropsEqual=Q??Ns5}createState(){return new jJ0}}class jJ0 extends p0{cachedChild=null;build(J){let{stableProps:Z,arePropsEqual:Q}=this.widget,Y=this.cachedChild;if(Y&&Q(Y.props,Z))return Y.widget;let X=this.widget.buildStableChild(Z);return this.cachedChild={props:Z,widget:X},X}dispose(){this.cachedChild=null}}class ed0 extends td0{constructor(J){super({stableProps:J})}createState(){return new xM4}buildStableChild(J){let{threadID:Z,...Q}=J;return new qd({...Q,key:Z?new $3(`message-view-${Z}`):void 0})}}class xM4 extends jJ0{build(J){return super.build(J)}}H1();function Os5(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/3600000),X=Math.floor(Y/24),V=Math.floor(X/7),K=Math.floor(X/30);if(Y<1)return"Just now";if(Y<24)return`${Y}h ago`;if(X<7)return`${X}d ago`;if(V<=4)return`${V}w ago`;return`${K}mo ago`}class $c0{threadHistoryService;constructor(J){this.threadHistoryService=J}async fetchThreadSummaries(J="",Z){try{let Q=await new Promise((Y)=>{let X=this.threadHistoryService.observeThreadList(Z).subscribe((V)=>{X.unsubscribe(),Y(V)})});return{ok:!0,threads:this.formatThreadSummaries(Q,J,Z)}}catch(Q){return{ok:!1,errorMsg:Q instanceof Error?Q.message:"An unexpected error occurred"}}}observeThreadSummaries(J="",Z={}){return this.threadHistoryService.observeHistory().pipe(D1((Q)=>this.formatThreadSummaries(Q,J,Z)))}formatThreadSummaries(J,Z,Q={}){return J.filter((X)=>{if(X.mainThreadID)return!1;if(!Q.includeArchived&&X.archived)return!1;if(!Z.trim())return!0;let V=X.title?.toLowerCase()||"untitled",K=X.id.toLowerCase(),z=Z.toLowerCase();return V.includes(z)||K.includes(z)}).map((X)=>{let V=new Date(X.userLastInteractedAt),K=Os5(V),z=X.id.slice(-8),G=X.env?.initial.trees?.[0]?.uri;return{id:X.id,title:X.title||"Untitled",updatedAt:new Date(X.userLastInteractedAt).toISOString(),description:{timeAgo:K,title:X.title||"Untitled",shortThreadID:z},diffStats:X.summaryStats?.diffStats,workspaceURI:G,relationships:X.relationships,agentMode:X.agentMode,details:{messageCount:X.summaryStats?.messageCount},archived:X.archived}})}}h0();_4();_4();function fM4(J){let Z=fI1(J),Q=Array.from(Z.entries()).map(([V,K])=>({path:V,diffStats:K})),X=K2(J)?.totalInputTokens??0;return{filesAffected:Q,totalTokens:X}}class Jc0{currentId=null;current=null;statsCache=new Map;subscribeTimer=null;subscription=null;listeners=[];threadService=null;scrollController=new Y5;constructor(){}setThreadService(J){this.threadService=J}async select(J){if(!this.threadService){j.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId===J)return;this.cancelTimerAndSubscription(),this.currentId=J;let Z=await this.threadService.get(J);if(Z){if(this.currentId===J)this.current=Z,this.notifyListeners()}this.subscribeTimer=setTimeout(()=>{this.subscribeLive(J)},1000)}clear(){this.cancelTimerAndSubscription(),this.currentId=null,this.current=null,this.notifyListeners()}addListener(J){this.listeners.push(J)}removeListener(J){let Z=this.listeners.indexOf(J);if(Z!==-1)this.listeners.splice(Z,1)}getCurrentThread(){return this.current}getCurrentStats(){if(!this.current)return null;let J=this.statsCache.get(this.current.id);if(J&&J.version===this.current.v)return J.stats;let Z=fM4(this.current);return this.statsCache.set(this.current.id,{stats:Z,version:this.current.v}),Z}clearStatsCache(){this.statsCache.clear()}dispose(){this.cancelTimerAndSubscription(),this.clearStatsCache(),this.scrollController.dispose(),this.listeners=[]}subscribeLive(J){if(!this.threadService){j.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId!==J)return;this.subscription=this.threadService.observePatches(J).pipe(Qr()).subscribe((Z)=>{if(this.currentId===J)this.current=Z,this.notifyListeners()})}cancelTimerAndSubscription(){if(this.subscribeTimer)clearTimeout(this.subscribeTimer),this.subscribeTimer=null;if(this.subscription)this.subscription.unsubscribe(),this.subscription=null}notifyListeners(){for(let J of this.listeners)J(this.current)}}class Zc0 extends d0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new bM4}}class bM4 extends p0{build(J){let Q=f0.of(J).colors,{todos:Y,title:X="TODOs"}=this.widget.props;if(!Array.isArray(Y)||Y.length===0)return new R0({width:0,height:0});let V=Y.map((K)=>this.buildTodoItem(K,Q));return new c0({child:new i0({padding:C0.symmetric(1,0),child:new u0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new $0({text:new C(X,new h({bold:!0,color:Q.foreground}))}),...V]})})})}buildTodoItem(J,Z){let Q=this.getStatusIcon(J.status),Y=J.status==="completed",X=new h({bold:J.status==="in-progress",color:Z.foreground,dim:Y}),V=new h({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Z.foreground,dim:Y});return new U1({crossAxisAlignment:"start",children:[new $0({text:new C(Q,X)}),new R0({width:1}),new T1({child:new $0({text:new C(J.content,V)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}function hM4(J,Z){switch(J){case"update-available":return[new C("A newer Amp is available. Run ",new h({color:Z.foreground,dim:!0})),new C("amp update",new h({color:Z.warning}))];case"update-available-unrecognized-path":return[new C("A newer Amp is available.",new h({color:Z.foreground,dim:!0}))];case"update-available-brew":return[new C("A newer Amp is available. Run ",new h({color:Z.foreground,dim:!0})),new C("brew upgrade ampcode",new h({color:Z.warning}))];case"updated":return null;case"updated-with-warning":return[new C("Update complete, run ",new h({color:Z.foreground,dim:!0})),new C("amp update",new h({color:Z.warning})),new C(" to see warnings",new h({color:Z.foreground,dim:!0}))];case"update-error":return[new C("Update failed, run ",new h({color:Z.foreground,dim:!0})),new C("amp update",new h({color:Z.warning})),new C(" to see warnings",new h({color:Z.foreground,dim:!0}))];case"hidden":return null}}async function Ps5(J){return new Promise((Z)=>{Es5("git",["branch","--show-current"],{cwd:J},(Q,Y)=>{if(Q){Z(null);return}let X=Y.trim();Z(X||null)})})}function pM4(J){return"interrupt"in J&&J.interrupt===!0}class Qc0 extends d0{dependencies;constructor(J){super();this.dependencies=J}createState(){return new RJ0}}class RJ0 extends p0{get tuiContext(){return DZ.require(this.context)}debugThreadViewState=process.env.AMP_DEBUG_THREAD_VIEW==="1";lastThreadStatusDebugSignature=null;themeColors=null;themeApp=null;ideStatus=null;randomAd=null;adSubscription=null;adsDisabledBySetting=!1;adReadinessTimeout=null;threadLoadSubscription=null;lastAdImpressionId=null;lastUserInteractionTime=Date.now();hasShownWinPasteHookRecoveryWarning=!1;winPasteHookImageUnsubscribe=null;winPasteHookStateUnsubscribe=null;isConfirmingExit=!1;isExiting=!1;isConfirmingClearInput=!1;isConfirmingCancelProcessing=!1;statusMessage=null;statusMessageTimer=null;isShowingHelp=!1;isShowingShortcutsHelp=!1;isShowingContextAnalyzeModal=!1;isShowingSkillListModal=!1;skillListData=null;shortcutsHintUsed=!1;deepReasoningEffort="high";anthropicSpeed=void 0;openAISpeed=void 0;deepReasoningEffortSubscription=null;anthropicSpeedSubscription=null;openAISpeedSubscription=null;sessionState=bC;isShowingConsoleOverlay=!1;isShowingMCPStatusModal=!1;isShowingConfirmationOverlay=!1;isShowingFileChangesOverlay=!1;isShowingContextDetailOverlay=!1;threadCostInfo=void 0;threadCostInfoThreadID=void 0;lastInferenceState=void 0;elapsedTimeTimer=null;confirmationOverlayContent="";exitConfirmTimeout=null;clearInputConfirmTimeout=null;cancelProcessingConfirmTimeout=null;historyIndex=-1;historyDraft=null;bashInvocations=[];currentTitle=void 0;currentShellModeStatus=void 0;imageAttachments=[];pendingSkills=[];pendingSkillsSubscription=null;skillListSubscription=null;skillWarningsSubscription=null;skillErrorsSubscription=null;availableSkillCount=0;availableSkillCountReady=!1;showSkillsCountInPromptBar=!0;showSkillsCountInPromptBarSubscription=null;skillWarningCount=0;skillErrorCount=0;pendingApprovals=[];pendingApprovalsSubscription=null;submitOnEnter=!0;submitOnEnterSubscription=null;displayMessage=null;executingCommand=null;isShowingJetBrainsInstaller=!1;isShowingIdePicker=!1;isShowingPalette=!1;isShowingPromptHistoryPicker=!1;paletteShowOptions=null;paletteOnThreadMentionSelected=null;threadsForPicker=[];parentThreadTitles=new Map;parentThreadTitleLoadsInFlight=new Set;clustersForPicker=[];isLoadingThreads=!1;threadPreviewController=new Jc0;previewThread=null;todoScrollController=(()=>{let J=new Y5;return J.followMode=!1,J})();contextAnalyzeDeps=null;contextAnalyzeFromDTW=null;openContextAnalyzeModal=()=>{if(this.widget.dependencies.threadPool.isDTWMode?.()){let J=this.widget.dependencies.threadState.mainThread;if(!J)return;this.contextAnalyzeDeps=null,this.contextAnalyzeFromDTW=(Z)=>g30({ampURL:this.tuiContext.ampURL,configService:this.widget.dependencies.configService,threadID:J.id,workerURL:process.env.AMP_WORKER_URL,signal:Z}),this.setState(()=>{this.isShowingContextAnalyzeModal=!0});return}this.contextAnalyzeFromDTW=null,this.widget.dependencies.createSystemPromptDeps().then((J)=>{this.contextAnalyzeDeps=J,this.setState(()=>{this.isShowingContextAnalyzeModal=!0})})};filterThreadPickerByWorkspace=!0;currentGitBranch=null;messageViewFocusNode=new r4({debugLabel:"MessageViewFocus"});autocompleteFocusNode=new r4({debugLabel:"AutocompleteFocus"});autocompleteFocusNodeListener=null;isTextfieldAndAutocompleteFocused=!1;hasReplayedEarlyInput=!1;submitDisabledHint=null;submitDisabledHintTimer=null;showImageUnsupportedHint=!1;imageUnsupportedHintTimer=null;imagePreview=null;fileImagePreviewPath=null;painterImagePreview=null;painterSaveDialog=null;messageViewController=new AJ0;previewMessageViewController=new AJ0;handleMainMessageViewCopy=(J,Z)=>{this._handleTextCopy(J,Z)};handleMainMessageViewDismissFocus=()=>{if(this.setState(()=>{this.isMessageViewInSelectionMode=!1,this.imagePreview=null}),!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()};messageViewControllerUnsubscribe=null;lastEditingMessageOrdinal=null;skillPreview=null;cachedSkillForPreview=null;adActionModal=null;adInfoModal=null;adModalStack=[];newsFeedReader=null;newsFeedEntries=[];newsFeedSubscription=null;bottomGridUserHeight=void 0;bottomGridDragStartY=null;bottomGridDragStartHeight=null;parentThreadLinkAnchor=new hp;previousThreadIdForHint=null;handoffController=null;handoffState={isInHandoffMode:!1,isGeneratingHandoff:!1,isConfirmingAbortHandoff:!1,pendingHandoffPrompt:null,spinner:null,countdownSeconds:null};isInQueueMode=!1;pendingMCPServers=[];mcpTrustSubscription=null;pendingOAuthRequest=null;pendingAuthLogin=null;authStatus="pending";authStatusSubscription=null;authModalKeyInterceptorUnsubscribe=null;isCreatingAuthLoginSession=!1;queuedPromptAfterAuth=null;pendingInputDialog=null;pendingConfirmDialog=null;mcpServers=[];mcpServersSubscription=null;pluginInfos=[];pluginInfosSubscription=null;agentModeController=null;freeTierStatus={canUseAmpFree:!1,isDailyGrantEnabled:!1};agentModePulseSeq=0;lastEffectiveAgentMode="smart";deepModeEffortHintController=new vg0({getDeepReasoningEffort:()=>this.deepReasoningEffort,getEffectiveAgentMode:()=>this.getEffectiveAgentMode(),canShowHintInCurrentThread:()=>{let J=this.widget.dependencies.threadState.mainThread;return!!J&&W3(J)===0},requestRender:()=>{if(!this.mounted)return;this.setState(()=>{})},isMounted:()=>this.mounted});updateState="hidden";updateServiceSubscription=null;toastController=new x70;isMessageViewInSelectionMode=!1;threadBackStack=[];threadForwardStack=[];isShowingForkDeprecationModal=!1;mysteriousMessage=null;isShowingMysteriousMessageModal=!1;mysteriousMessageSubscription=null;mysterySequenceManager=null;mysterySequenceProgress=null;mysteryKeyInterceptorUnsubscribe=null;static MYSTERY_SEQUENCE=["ctrl+x","y","z"];splashOrbExplosion=null;splashOrbExplosionSeq=0;freeTierStatusSubscription=null;allConnectedThreadActivityStatusesSubscription=null;threadInitializationStatusSubscription=null;allConnectedThreadActivityStatuses={};threadInitializationMessage=null;threadTitlesSubscription=null;threadTitles={};pendingNavigationSubscription=null;pendingNavigationInFlightThreadID=null;pluginCommands=[];pluginCommandsSubscription=null;async initNewsFeed(){let J=async(Q)=>{return p3(Q,void 0,this.widget.dependencies.configService)},Z=Bm1();this.newsFeedReader=new Tg0(Z,J,"/news.rss"),this.newsFeedSubscription=this.newsFeedReader.stream().subscribe({next:(Q)=>{if(Q.length>0)this.setState(()=>{this.newsFeedEntries=[...Q,...this.newsFeedEntries]})},error:(Q)=>{j.error("News feed error:",Q)}})}bringAdModalToFront(J){this.adModalStack=this.adModalStack.filter((Z)=>Z!==J),this.adModalStack.push(J)}removeAdModalFromStack(J){this.adModalStack=this.adModalStack.filter((Z)=>Z!==J)}getTopAdModal(){for(let J=this.adModalStack.length-1;J>=0;J--){let Z=this.adModalStack[J];if(Z==="adAction"&&this.adActionModal)return Z;if(Z==="adInfo"&&this.adInfoModal)return Z}return null}dismissTopAdModal(){let J=this.getTopAdModal();if(!J)return!1;return this.setState(()=>{if(J==="adAction")this.adActionModal=null;if(J==="adInfo")this.adInfoModal=null;this.removeAdModalFromStack(J)}),!0}recordNavigation(J){this.threadBackStack.push(J),this.threadForwardStack=[]}navigateBack=async()=>{if(this.threadBackStack.length===0)return;let J=this.widget.dependencies.threadState.mainThread?.id;if(!J)return;let Z=this.threadBackStack.pop();this.threadForwardStack.push(J),await this.switchToExistingThread(Z,{recordInNavigationHistory:!1})};navigateForward=async()=>{if(this.threadForwardStack.length===0)return;let J=this.widget.dependencies.threadState.mainThread?.id;if(!J)return;let Z=this.threadForwardStack.pop();this.threadBackStack.push(J),await this.switchToExistingThread(Z,{recordInNavigationHistory:!1})};onThreadSwitch(){this.handoffController?.resetUIState(),this.exitQueueMode(),this.isMessageViewInSelectionMode=!1,this.imagePreview=null}canInterruptQueuedInference(){let{activeThreadHandle:J,threadPool:Z,threadState:Q}=this.widget.dependencies,Y=Q.mainThread?.queuedMessages?.some((X)=>!pM4(X))??!1;return Z.queueOnSubmitByDefault&&Boolean(J.interruptQueuedMessage)&&Y&&gO(Q.viewState)}interruptNextQueuedMessage=async()=>{let{activeThreadHandle:J,threadState:Z}=this.widget.dependencies,Q=Z.mainThread?.queuedMessages?.find((Y)=>!pM4(Y))?.id;if(!Q||!J.interruptQueuedMessage)return;await J.interruptQueuedMessage(Q)};startAndSwitchToNewThread=async()=>{let J=this.widget.dependencies.threadState.mainThread?.id;if(J)this.recordNavigation(J);await this.widget.dependencies.threadPool.createThread(),this.setState(()=>{this.onThreadSwitch(),this.previousThreadIdForHint=J??null})};canChangeAgentModeInPromptEditor(){return(this.messageViewController.editingMessageOrdinal===0||this.handoffState.isInHandoffMode)&&!this.handoffState.isGeneratingHandoff}getEffectiveAgentMode(){if(!this.agentModeController)return"smart";return(this.canChangeAgentModeInPromptEditor()?this.agentModeController.getMode():null)??this.agentModeController.getEffectiveMode()}isProcessing(){let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return!1;if(J.viewState.state!=="active")return!1;if(J.viewState.interactionState==="handoff")return!0;if(Boolean(J.viewState.inferenceState==="running"))return!0;return J.items.filter((Y)=>Y.type==="toolResult").filter((Y)=>Y.toolResult.run.status==="in-progress"||Y.toolResult.run.status==="queued").length>0}showSubmitDisabledHint(J){if(this.submitDisabledHintTimer)clearTimeout(this.submitDisabledHintTimer);this.setState(()=>{this.submitDisabledHint=J}),this.submitDisabledHintTimer=setTimeout(()=>{this.setState(()=>{this.submitDisabledHint=null}),this.submitDisabledHintTimer=null},3000)}getUIHint(){let J=this.themeColors?.colorScheme;if(!J)return null;let Z=this.themeApp;if(!Z)return null;if(this.submitDisabledHint)return new C(this.submitDisabledHint,new h({color:J.foreground,dim:!0}));if(this.isExiting)return new C("Exiting...",new h({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new C("",void 0,[new C("Ctrl+C",new h({color:Z.keybind})),new C(" again to exit",new h({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new C("",void 0,[new C("Esc",new h({color:Z.keybind})),new C(" again to clear input",new h({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new C("",void 0,[new C("Escape",new h({color:Z.keybind})),new C(" to close help",new h({color:J.foreground,dim:!0}))]);if(this.showImageUnsupportedHint){let U=this.getEffectiveAgentMode(),q=rg(U);return new C("",void 0,[new C("Images aren't supported in ",new h({color:J.warning,dim:!1})),new C(U,new h({color:q})),new C(" mode.",new h({color:J.warning,dim:!1}))])}if(this.isProcessing()||this.bashInvocations.length>0){if(this.isConfirmingCancelProcessing)return new C("",void 0,[new C("Esc",new h({color:Z.keybind})),new C(" again to cancel",new h({color:J.foreground,dim:!0}))]);if(this.canInterruptQueuedInference())return new C("",void 0,[new C("Enter",new h({color:Z.keybind})),new C(" to interject",new h({color:J.foreground,dim:!0}))]);return new C("",void 0,[new C("Esc",new h({color:Z.keybind})),new C(" to cancel",new h({color:J.foreground,dim:!0}))])}let{threadState:Q}=this.widget.dependencies;if(this.statusMessage){if(this.debugThreadViewState)j.info("[tui-ui] footer status override",{source:"statusMessage",statusMessage:this.statusMessage,inferenceState:Q.viewState.state==="active"?Q.viewState.inferenceState:void 0});return new C(this.statusMessage,new h({color:J.foreground,dim:!0}))}let Y=hM4(this.updateState,J);if(Y){if(this.debugThreadViewState)j.info("[tui-ui] footer status override",{source:"updateState",inferenceState:Q.viewState.state==="active"?Q.viewState.inferenceState:void 0});return new C("",void 0,Y)}let X=this.getCurrentConfirmation(),V=dM4(Q),K=this.widget.dependencies.threadPool.getCompactionStatus?.(),z=new pp({threadViewState:Q.viewState,tokenUsage:V,thread:Q.mainThread??void 0,compactionState:K?.compactionState??"idle",waitingForConfirmation:!!X,showingEphemeralError:Boolean(Q.viewState.state==="active"&&Q.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null,executingCommandNoun:this.executingCommand?.noun??null,executingCommandVerb:this.executingCommand?.verb??null,executingCommandMessage:this.executingCommand?.statusMessage??null}),G=gp(z);if(this.debugThreadViewState){let U=JSON.stringify({inferenceState:Q.viewState.state==="active"?Q.viewState.inferenceState:void 0,interactionState:Q.viewState.interactionState,statusType:G.type});if(U!==this.lastThreadStatusDebugSignature)this.lastThreadStatusDebugSignature=U,j.info("[tui-ui] footer thread status",JSON.parse(U))}let F=!this.shortcutsHintUsed||this.sessionState.launchCount<10;if(G.type==="none"&&!this.isShowingShortcutsHelp&&this.textController.text===""&&F)return new C("",void 0,[new C("?",new h({color:Z.keybind})),new C(" for shortcuts",new h({color:J.foreground,dim:!0}))]);return null}getParentThreadInfo(){let J=this.previewThread??this.widget.dependencies.threadState.mainThread;if(!J)return null;let Z=ck(J).filter((K)=>K.type==="fork"||K.type==="handoff");if(Z.length===0)return null;let Q=Z[0],Y=Q.threadID,X=this.threadsForPicker.find((K)=>K.id===Y);if(!X?.title)this.ensureParentThreadTitleLoaded(Y);let V=X?.title??this.parentThreadTitles.get(Y)??Y.slice(-8);return{type:Q.type==="handoff"?"handoff":"fork",title:V,threadID:Y}}ensureParentThreadTitleLoaded(J){if(this.parentThreadTitles.has(J)||this.parentThreadTitleLoadsInFlight.has(J))return;this.parentThreadTitleLoadsInFlight.add(J),this.widget.dependencies.threadService.getPrimitiveProperty(J,"title").then((Z)=>{if(!this.mounted||!Z)return;this.setState(()=>{this.parentThreadTitles.set(J,Z)})}).catch((Z)=>{j.debug("Failed to load parent thread title",{threadID:J,error:Z})}).finally(()=>{this.parentThreadTitleLoadsInFlight.delete(J)})}getThreadClusterForMinimap=(J)=>{let Z=this.clustersForPicker.find((Q)=>Q.threads.some((Y)=>Y.id===J));if(!Z||Z.threads.length<2)return null;return Z.threads.map((Q)=>({id:Q.id,title:Q.title,parentID:Q.parentID,updatedAt:Q.updatedAt,isActive:this.isThreadActivelyWorking(Q.id)}))};getCurrentThreadClusterForMinimap=()=>{let J=this.previewThread??this.widget.dependencies.threadState.mainThread;if(!J)return null;return this.getThreadClusterForMinimap(J.id)};enrichClustersWithActiveState=(J)=>{return J.map((Z)=>({...Z,threads:Z.threads.map((Q)=>({...Q,isActive:this.isThreadActivelyWorking(Q.id)}))}))};areRecordValuesEqual(J,Z){if(J===Z)return!0;let Q=Object.entries(J),Y=Object.entries(Z);if(Q.length!==Y.length)return!1;for(let[X,V]of Q){if(!Object.hasOwn(Z,X))return!1;if(!Object.is(V,Z[X]))return!1}return!0}getThreadViewStatesSnapshot(){let J={...this.allConnectedThreadActivityStatuses},Z=this.widget.dependencies.threadState.mainThread;if(Z)J[Z.id]=this.widget.dependencies.threadState.viewState;return J}isThreadActivelyWorking(J){return gO(this.allConnectedThreadActivityStatuses[J])}isTranscriptEmpty(){let{threadState:J}=this.widget.dependencies;return J.items.length===0}isStartupThreadLoading(){if(!this.tuiContext.startupThreadID)return!1;let{threadPool:J}=this.widget.dependencies;return J.hasPendingInitialization?.()===!0}handleMessageRestoreSubmit=async(J)=>{let{threadState:Z,activeThreadHandle:Q}=this.widget.dependencies;if(!Z.mainThread?.id)return;let X=Z.mainThread?.messages.findIndex((V)=>V===J);if(X===void 0||X===-1)return;try{this.cancelBashInvocations(),await Q.cancelTurn(),await Q.restoreTo(X),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(V){j.error("Failed to edit message:",V)}};showForkDeprecationMessage=()=>{this.setState(()=>{this.isShowingForkDeprecationModal=!0})};dismissForkDeprecationModal=()=>{this.setState(()=>{this.isShowingForkDeprecationModal=!1})};handleMessageEditSubmit=async(J,Z,Q)=>{let{threadState:Y,activeThreadHandle:X}=this.widget.dependencies,V=Y.mainThread;if(!V)return;let K=V.messages.findIndex((F)=>F.messageId!==void 0&&F.messageId===J.messageId);if(K===-1)return;let z=K===0,G=z?this.agentModeController?.getMode()??V.agentMode??this.getEffectiveAgentMode():V.agentMode;if(this.shouldRequireAuthForPromptSubmit()){this.showSubmitDisabledHint("Sign in required before editing and resubmitting messages"),this.ensureAuthLoginSession();return}try{this.cancelBashInvocations(),await X.cancelTurn(),this.widget.dependencies.history.add(Z,process.cwd());let F=aH(Z);if(F&&X.invokeBashTool)await X.restoreTo(K),this.invokeBashCommand(F.cmd,{visibility:F.visibility});else{let U=[{type:"text",text:Z}];if(Q.length>0)U.push(...Q);let q=G;if(V.agentMode&&!z&&q!==V.agentMode){j.error(`Cannot edit message: This thread uses ${V.agentMode} mode. To change mode, create a new thread.`);return}await X.sendMessage({content:U,agentMode:q,editIndex:K})}this.scrollMessageViewToBottom()}catch(F){j.error("Failed to edit message:",F)}};getAffectedFiles=async(J)=>{let{activeThreadHandle:Z,threadState:Q}=this.widget.dependencies;try{let Y=Q.mainThread;if(!Y)return[];let X=Y.messages.findIndex((K)=>K===J);if(X===-1)return[];return(await Z.getFilesAffectedByTruncation(X)).map(b9)}catch(Y){return j.error("Failed to get affected files:",Y),[]}};textController=new i7;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new Y5);return this.messageScrollControllers.get(J)}scrollMessageViewToBottom(){let{threadState:J}=this.widget.dependencies,Z=J.mainThread?.id;if(!Z)return;this.getMessageScrollController(Z).scrollToBottom()}_handleSelectionChanged=(J)=>{this.setState(()=>{})};updateTerminalTitle(){let{threadState:J}=this.widget.dependencies,Z=J.mainThread?.title;if(Z!==this.currentTitle){this.currentTitle=Z;let Q=process.cwd().replace(process.env.HOME||"","~"),Y=Z?`amp - ${Z} - ${Q}`:"";process.stdout.write(B90(Y))}}_handleTextCopy(J,Z){if(J&&J.length>0){let Q=Z?"Selection copied to clipboard":"Failed to copy selection to clipboard",Y=Z?"success":"error";this.toastController.show(Q,Y,2000)}}textFieldKey=new $3("text-field");ideStatusSubscription=null;ideMessageSubscription=null;ideAppendToPromptSubscription=null;paletteCommands;paletteConfig;completionBuilder=null;textChangeListener=()=>{let J=this.textController.text;if(J==="")this.textController.resetScrollOffset();if(J!=="")this.deepModeEffortHintController.dismissForInteraction();if(this.handoffState.countdownSeconds!==null)this.handoffController?.stopCountdown();if(J==="/"&&!this.handoffState.isGeneratingHandoff){this.showCommandPalette(),this.textController.clear(),this.toastController.show("Use [[Ctrl-O]] to open the command palette","warning");return}let Z=aH(J),Q=J===""&&this.bottomGridUserHeight!==void 0,Y=this.handoffState.isInHandoffMode||!this.widget.dependencies.activeThreadHandle.invokeBashTool?void 0:Z?.visibility;this.setState(()=>{if(this.currentShellModeStatus=Y,Q)this.bottomGridUserHeight=void 0})};navigateHistoryPrevious=()=>{let J=this.widget.dependencies.history.previous();if(J!==null){if(this.historyIndex===-1)this.historyDraft=this.textController.text;this.historyIndex++,this.textController.text=J,this.textController.moveCursorToStart()}};navigateHistoryNext=()=>{let J=this.widget.dependencies.history.next();if(J!==null)this.historyIndex--,this.textController.text=J,this.textController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.textController.text=this.historyDraft||"",this.textController.moveCursorToEnd(),this.historyDraft=null};resetHistory=()=>{this.widget.dependencies.history.reset(),this.historyIndex=-1,this.historyDraft=null};openJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!0})};dismissJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!1})};openIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!0})};dismissIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!1}),H6.instance.addPostFrameCallback(()=>{this.autocompleteFocusNode.requestFocus()})};handleIdeSelection=async(J,Z)=>{let Q=this.widget.dependencies.ideClient.getSelectedConfig();if(Q&&this.isSameIdeConfig(Q,J)){this.dismissIdePicker();return}try{await this.connectToSelectedIde(J,Z)}catch(Y){let X=Y instanceof Error?Y.message:String(Y);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${X}`)})}this.widget.dependencies.ideClient.selectConfig(J),this.dismissIdePicker()};isSameIdeConfig(J,Z){if(J.connection!==Z.connection||J.ideName!==Z.ideName||J.pid!==Z.pid||J.port!==Z.port||J.authToken!==Z.authToken||J.workspaceId!==Z.workspaceId)return!1;if(J.workspaceFolders.length!==Z.workspaceFolders.length)return!1;return J.workspaceFolders.every((Q)=>Z.workspaceFolders.includes(Q))}async connectToSelectedIde(J,Z){await this.widget.dependencies.ideClient.start(J,!0,Z)}previewControllerListener=(J)=>{this.setState(()=>{this.previewThread=J})};showStandaloneThreadPicker=()=>{this.showCommandPalette({type:"standalone",commandId:"continue",onSubmit:()=>{this.threadPreviewController.clear(),this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null}),H6.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette)this.autocompleteFocusNode.requestFocus()})},onCancel:()=>{this.exitApplication()}})};toggleThreadPickerWorkspaceFilter=()=>{this.setState(()=>{this.filterThreadPickerByWorkspace=!this.filterThreadPickerByWorkspace})};handleDoubleAtTrigger=(J)=>{let{text:Z,cursorPosition:Q}=J,X=Z.slice(0,Q).lastIndexOf("@@"),V=J!==this.textController;if(j.info("[handleDoubleAtTrigger] called",{isEditingPreviousMessage:V,text:Z,cursor:Q,atAtIndex:X}),V)this.setState(()=>{this.paletteOnThreadMentionSelected=(K)=>{let z=this.messageViewController.editingController;if(!z){j.warn("[paletteOnThreadMentionSelected] no editing controller found");return}this.insertThreadMention(z,K)}});else this.setState(()=>{this.paletteOnThreadMentionSelected=null});this.showCommandPalette({type:"standalone",commandId:"mention-thread",onBeforeExecute:V?void 0:()=>{if(X!==-1){let K=J.text,z=K.slice(0,X)+K.slice(X+2);J.text=z,J.cursorPosition=X}},onSubmit:()=>{this.setState(()=>{this.paletteOnThreadMentionSelected=null}),this.dismissPalette()},onCancel:()=>{this.setState(()=>{this.paletteOnThreadMentionSelected=null}),this.dismissPalette()}})};insertThreadMention(J,Z){let{text:Q,cursorPosition:Y}=J,V=Q.slice(0,Y).lastIndexOf("@@");if(V!==-1){let K=Q.slice(Y),z=K.length===0,G=`@${Z}${z?" ":""}`,F=Q.slice(0,V)+G+K,U=V+G.length;J.text=F,J.cursorPosition=U}else J.insertText(`@${Z} `)}showCommandPalette(J){if(this.handoffState.isGeneratingHandoff)return;let Z=!this.isShowingPalette;if(this.setState(()=>{if(this.isShowingPalette=Z,this.paletteShowOptions=Z?J??null:null,!Z)this.threadsForPicker=[],this.clustersForPicker=[],this.isLoadingThreads=!1}),Z)this.loadThreadsForPicker();else this.unloadThreadsForPicker()}isShowingStandalonePalette(){return this.isShowingPalette&&this.paletteShowOptions?.type==="standalone"}getPaletteCommands(){if(!this.paletteCommands){if(!this.paletteConfig)throw Error("Config not yet available");this.paletteCommands=new Np0(this.widget.dependencies.configService,(J)=>{this.setState(()=>{this.executingCommand=J})},()=>{this.setState(()=>{this.executingCommand=null})},this.paletteConfig)}return this.paletteCommands}getCompletionBuilder(){if(!this.completionBuilder)this.completionBuilder=new Lp0(this.widget.dependencies.fuzzyServer);return this.completionBuilder}unloadThreadsForPicker(){if(this.threadLoadSubscription)this.threadLoadSubscription.unsubscribe(),this.threadLoadSubscription=null;this.threadPreviewController.clearStatsCache(),this.widget.dependencies.threadHistoryService.resetCache()}dismissPalette=()=>{if(this.isExiting)return;this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null,this.threadsForPicker=[],this.clustersForPicker=[],this.isLoadingThreads=!1}),this.unloadThreadsForPicker()};lastRootContext;getCommandPaletteContext=(J)=>{let{threadState:Z,recentThreadIDs:Q}=this.widget.dependencies;if(!Z.mainThread)return null;let Y=J??this.lastRootContext;if(!Y)return null;let X=K1.file(process.cwd()),V=g1(X);return{recentThreadIDs:Q,currentThreadID:Z.mainThread.id,contextFallback:Y,context:J,threadPool:this.widget.dependencies.threadPool,createSystemPromptDeps:this.widget.dependencies.createSystemPromptDeps,activeThreadHandle:this.widget.dependencies.activeThreadHandle,editorState:this.textController,isProcessing:this.isProcessing(),thread:Z.mainThread,ampURL:this.tuiContext.ampURL,threadService:this.widget.dependencies.threadService,configService:this.widget.dependencies.configService,skillService:this.widget.dependencies.skillService,openInEditor:this.openInEditor,takeImageAttachments:()=>{let K=this.imageAttachments;return this.setState(()=>{this.imageAttachments=[]}),K},setImageAttachments:(K)=>{this.setState(()=>{this.imageAttachments=K})},editorDispatch:(K)=>{switch(K.type){case"set-input":this.textController.clear(),this.textController.insertText(K.input);break;case"set-input-with-cursor":this.textController.clear(),this.textController.insertText(K.input),this.textController.cursorPosition=K.cursorPosition;break;case"insert-text":this.textController.insertText(K.text);break;case"clear":this.textController.clear();break}},submitMessage:(K)=>{this.onTextSubmitted(K).catch((z)=>{this.handleSubmitFlowError(z)})},exitApp:this.exitApplication,openHelp:()=>{this.setState(()=>{this.isShowingHelp=!0})},openContextAnalyze:()=>{this.openContextAnalyzeModal()},openSkillList:()=>{this.setState(()=>{this.isShowingSkillListModal=!0})},settingsStorage:this.widget.dependencies.settingsStorage,clientId:this.tuiContext.clientId,mcpService:this.widget.dependencies.mcpService,toolboxService:this.widget.dependencies.toolboxService,createThread:async()=>{await this.startAndSwitchToNewThread()},navigateBack:this.navigateBack,navigateForward:this.navigateForward,canNavigateBack:this.threadBackStack.length>0,canNavigateForward:this.threadForwardStack.length>0,canUseAmpFree:this.freeTierStatus.canUseAmpFree,isDailyGrantEnabled:this.freeTierStatus.isDailyGrantEnabled,switchToThread:async(K)=>{await this.switchToExistingThread(K),this.setState(()=>{this.isMessageViewInSelectionMode=!1,this.imagePreview=null});return},handleHandoff:async(K,z)=>{let{goal:G,images:F}=z;if(!G)return{ok:!1,error:Error("Goal is required")};try{let U=this.widget.dependencies.threadState.mainThread;if(!U)return{ok:!1,error:Error("No active thread")};let q=setTimeout(()=>K.abort(new uT("Handoff took too long and was aborted (timeout: 60s)")),60000);try{let D=await this.widget.dependencies.threadPool.createHandoff(U.id,{goal:G,images:F,agentMode:U.agentMode,queuedMessages:U.queuedMessages?[...U.queuedMessages]:void 0,signal:K.signal});return clearTimeout(q),await this.switchToExistingThread(D),{ok:!0}}catch(D){if(clearTimeout(q),D instanceof Error&&(D.name==="AbortError"||D.message.includes("aborted")))throw K.signal.reason;throw D}}catch(U){return j.error("Failed to create handoff thread",{error:U}),{ok:!1,error:U instanceof Error?U:Error(String(U))}}},getGuidanceFiles:(K)=>{return this.widget.dependencies.activeThreadHandle.getGuidanceFiles(K)},openIdePicker:()=>{this.openIdePicker()},openPromptHistoryPicker:()=>{this.setState(()=>{this.isShowingPromptHistoryPicker=!0})},getAgentMode:()=>{return this.agentModeController?.getMode()??null},setAgentMode:(K)=>{this.agentModeController?.setMode(K)},toggleAgentMode:this.toggleAgentMode,toggleDeepReasoningEffort:this.toggleDeepReasoningEffort,getEffectiveAgentMode:()=>this.getEffectiveAgentMode(),getEditorText:()=>this.textController.text,userEmail:y6(this.authStatus)?this.authStatus.user.email:void 0,workspace:this.tuiContext.workspace??null,completionBuilder:this.getCompletionBuilder(),threads:this.threadsForPicker,clusters:this.enrichClustersWithActiveState(this.clustersForPicker),previewController:this.threadPreviewController,isLoadingThreads:this.isLoadingThreads,filterByWorkspace:this.filterThreadPickerByWorkspace,currentWorkspace:V,threadViewStates:this.getThreadViewStatesSnapshot(),newsFeedEntries:this.newsFeedEntries,showMCPStatusModal:()=>{this.setState(()=>{this.isShowingMCPStatusModal=!0})},internalAPIClient:this.widget.dependencies.internalAPIClient,features:y6(this.authStatus)?this.authStatus.features:this.tuiContext.features,showStatusMessage:(K,z=2000)=>{this.showStatusMessage(K,z)},showToast:(K,z="success",G)=>{this.toastController.show(K,z,G)},getThemeName:()=>LB4(Y).themeName,isMessageViewInteractionActive:this.isMessageViewInSelectionMode||this.messageViewController.editingMessageOrdinal!==null,enterHandoffMode:this.enterHandoffMode,isInHandoffMode:this.handoffState.isInHandoffMode,enterQueueMode:this.enterQueueMode,submitQueue:this.submitQueue,isInQueueMode:this.isInQueueMode,addPendingSkill:(K)=>{this.widget.dependencies.activeThreadHandle.addPendingSkill(K)},onThreadMentionSelected:this.paletteOnThreadMentionSelected??void 0,canChangeAgentModeInPromptEditor:()=>this.canChangeAgentModeInPromptEditor(),pluginCommands:this.pluginCommands,executePluginCommand:this.widget.dependencies.pluginService?(K,z,G)=>this.widget.dependencies.pluginService.commands.execute(K,z,{threadID:G}):void 0,reloadPlugins:this.widget.dependencies.pluginService?()=>this.widget.dependencies.pluginService.reload():void 0,pluginService:this.widget.dependencies.pluginService}};loadThreadsForPicker(){if(this.threadLoadSubscription)return;this.setState(()=>{this.isLoadingThreads=!0});let J=new $c0(this.widget.dependencies.threadHistoryService);this.threadLoadSubscription=J.observeThreadSummaries("",{includeArchived:!0}).subscribe({next:(Z)=>{this.setState(()=>{this.threadsForPicker=Z,this.clustersForPicker=_O4(Z),this.isLoadingThreads=!1})},error:()=>{this.setState(()=>{this.isLoadingThreads=!1})}})}updateGitBranch=async()=>{let J=await Ps5(process.cwd());this.setState(()=>{this.currentGitBranch=J})};removeBashInvocation=(J)=>{this.setState(()=>{this.bashInvocations=this.bashInvocations.filter((Z)=>Z.id!==J)})};invokeBashCommand=(J,{visibility:Z})=>{if(!this.widget.dependencies.activeThreadHandle.invokeBashTool)return;let Q=Date.now(),Y=`bash-${Q}-${Math.random().toString(36).substring(7)}`,X={cmd:J},V=new AbortController;this.widget.dependencies.activeThreadHandle.invokeBashTool(X,{hidden:Z===nH,abortController:V}).subscribe({next:(K)=>{this.setState(()=>{if(this.bashInvocations.find((G)=>G.id===Y))this.bashInvocations=this.bashInvocations.map((G)=>G.id===Y?{...G,toolRun:K}:G);else{let G={id:Y,args:X,toolRun:K,startTime:Q,abortController:V,hidden:Z===nH};this.bashInvocations=[...this.bashInvocations,G]}})},error:()=>this.removeBashInvocation(Y),complete:()=>this.removeBashInvocation(Y)})};cancelBashInvocations=()=>{let J=this.bashInvocations.find((Z)=>Z.toolRun.status==="in-progress");if(J)J.abortController.abort()};showContextDetailOverlay=()=>{this.setState(()=>{this.isShowingContextDetailOverlay=!0}),this.fetchThreadCostInfo()};fetchThreadCostInfo=uB4(()=>{let J=this.widget.dependencies.threadState.mainThread?.id;if(!J)return;this.widget.dependencies.internalAPIClient.threadDisplayCostInfo({threadID:J},{config:this.widget.dependencies.configService}).then((Z)=>{if(Z.ok)this.setState(()=>{this.threadCostInfo=Z.result,this.threadCostInfoThreadID=J})}).catch(()=>{this.setState(()=>{this.threadCostInfo=void 0,this.threadCostInfoThreadID=J})})},150);maybeRefetchThreadCostInfo=(J)=>{let Z=this.lastInferenceState==="running",Q=J==="running",Y=J==="idle"&&Z,X=Q&&!Z;if(Y)this.fetchThreadCostInfo();if(X)this.startElapsedTimeTimer();else if(Z&&!Q)this.stopElapsedTimeTimer();this.lastInferenceState=J};startElapsedTimeTimer=()=>{if(this.elapsedTimeTimer)return;this.elapsedTimeTimer=setInterval(()=>{let J=this.widget.dependencies.threadState.viewState;if(!(J.state==="active"&&J.inferenceState==="running")){this.stopElapsedTimeTimer();return}this.setState(()=>{})},1000)};stopElapsedTimeTimer=()=>{if(this.elapsedTimeTimer)clearInterval(this.elapsedTimeTimer),this.elapsedTimeTimer=null};toggleAgentMode=()=>{if(!this.agentModeController)return;if(this.handoffState.isGeneratingHandoff)return;let J=this.canChangeAgentModeInPromptEditor();if(this.agentModeController.toggle(J))this.setState(()=>{this.showImageUnsupportedHint=!1,this.agentModePulseSeq++})};handleMessageViewControllerUpdate=()=>{let J=this.messageViewController.editingMessageOrdinal;if(J===this.lastEditingMessageOrdinal)return;if(this.lastEditingMessageOrdinal===0&&J!==0){let Y=this.agentModeController;if(!Y){this.lastEditingMessageOrdinal=J,this.setState(()=>{});return}if(Y.getMode()!==null)Y.setMode(null)}this.lastEditingMessageOrdinal=J,this.setState(()=>{})};showStatusMessage(J,Z=2000){if(this.statusMessageTimer)clearTimeout(this.statusMessageTimer);this.setState(()=>{this.statusMessage=J}),this.statusMessageTimer=setTimeout(()=>{this.setState(()=>{this.statusMessage=null}),this.statusMessageTimer=null},Z)}applyDeepReasoningEffort(J){this.deepReasoningEffort=J,u$("agent.deepReasoningEffort",J)}commitDeepReasoningEffort(J){let Z=this.deepReasoningEffort;if(this.applyDeepReasoningEffort(J),J===Z)return Promise.resolve(!0);return this.widget.dependencies.configService.updateSettings("agent.deepReasoningEffort",J,"global").then(()=>!0).catch((Q)=>{return this.applyDeepReasoningEffort(Z),j.error("Failed to persist deep reasoning setting",{error:Q}),this.showStatusMessage("Failed to save deep reasoning effort"),!1})}getNextDeepReasoningEffort(J){return J==="medium"?"high":J==="high"?"xhigh":"medium"}toggleDeepReasoningEffort=async()=>{if(this.deepModeEffortHintController.dismissForInteraction(),this.getEffectiveAgentMode()!=="deep"){this.showStatusMessage("Deep reasoning effort is only available in deep mode");return}let Z=this.widget.dependencies.threadState.mainThread;if(!Z)return;if(W3(Z)>0){this.showStatusMessage("Deep reasoning effort can only be toggled before the first message");return}let Q=this.getNextDeepReasoningEffort(this.deepReasoningEffort);if(!await this.commitDeepReasoningEffort(Q))return;this.showStatusMessage(`Deep reasoning effort: ${Q}`),this.setState(()=>{this.agentModePulseSeq++})};formatAgentModeLabel(J){if(J!=="deep")return J;if(this.deepReasoningEffort==="high")return"deep²";if(this.deepReasoningEffort==="xhigh")return"deep³";return"deep"}handleInsertImage=async(J)=>{let Z=this.getEffectiveAgentMode();if(!vk(Z)){if(this.imageUnsupportedHintTimer)clearTimeout(this.imageUnsupportedHintTimer);return this.setState(()=>{this.showImageUnsupportedHint=!0}),this.imageUnsupportedHintTimer=setTimeout(()=>{this.setState(()=>{this.showImageUnsupportedHint=!1}),this.imageUnsupportedHintTimer=null},5000),!1}if(this.imageAttachments.length>=BI)return!1;let Q=await vT(J);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q]}),!1;return this.setState(()=>{this.displayMessage=Error(`Failed to attach image: ${Q}`)}),!1};handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1)})};handleImageClick=(J)=>{let Z=this.imageAttachments[J];if(Z)this.setState(()=>{this.imagePreview={image:Z,index:J,onRemove:()=>{let Q=this.imageAttachments.indexOf(Z);if(Q!==-1)this.setState(()=>{this.imageAttachments=this.imageAttachments.filter((Y,X)=>X!==Q),this.imagePreview=null})}}})};handleImagePreviewDismiss=()=>{this.setState(()=>{this.imagePreview=null})};handleShowFileImagePreview=(J)=>{this.setState(()=>{this.fileImagePreviewPath=J})};handleFileImagePreviewDismiss=()=>{this.setState(()=>{this.fileImagePreviewPath=null})};handleShowPainterImagePreview=(J,Z)=>{this.setState(()=>{this.painterImagePreview={image:J,filePath:Z}})};handlePainterImagePreviewDismiss=()=>{this.setState(()=>{this.painterImagePreview=null})};handleShowPainterSaveDialog=(J,Z)=>{this.setState(()=>{this.painterSaveDialog={image:J,filePath:Z}})};handlePainterSaveDialogDismiss=()=>{this.setState(()=>{this.painterSaveDialog=null})};handleSkillClick=(J)=>{let Z=this.pendingSkills[J];if(Z)this.setState(()=>{this.cachedSkillForPreview=null,this.skillPreview={skillIndex:J,onRemove:()=>{this.widget.dependencies.activeThreadHandle.removePendingSkill(Z.name),this.setState(()=>{this.skillPreview=null,this.cachedSkillForPreview=null})}}}),this.widget.dependencies.skillService.getSkills().then((Q)=>{let Y=Q.find((X)=>X.name===Z.name)??null;if(this.skillPreview!==null)this.setState(()=>{this.cachedSkillForPreview=Y})})};handleSkillPreviewDismiss=()=>{this.setState(()=>{this.skillPreview=null,this.cachedSkillForPreview=null})};handleShowEditingImagePreview=(J,Z,Q)=>{this.setState(()=>{this.imagePreview={image:J,index:Z,onRemove:Q}})};handleImagePreviewRemove=()=>{if(this.imagePreview)this.imagePreview.onRemove(),this.setState(()=>{this.imagePreview=null})};handleShowMysteryModal=()=>{if(this.mysteriousMessage)this.setState(()=>{this.isShowingMysteriousMessageModal=!0})};handleSplashOrbExplode=(J)=>{this.splashOrbExplosionSeq+=1,this.setState(()=>{this.splashOrbExplosion={seq:this.splashOrbExplosionSeq,originX:J.x,originY:J.y}})};handleSplashOrbExplosionComplete=()=>{if(!this.splashOrbExplosion)return;this.setState(()=>{this.splashOrbExplosion=null})};handleDestructMysteriousMessage=()=>{if(!this.mysteriousMessage)return;let J=this.mysteriousMessage.id;this.widget.dependencies.internalAPIClient.markAsReadMysteriousMessage({messageId:J},{config:this.widget.dependencies.configService}).then((Z)=>{if(!Z.ok)j.error("Failed to destruct mysterious message",Z.error);else this.setState(()=>{this.mysteriousMessage=null,this.isShowingMysteriousMessageModal=!1})}).catch((Z)=>{j.error("Failed to destruct mysterious message",Z)})};exitMessageViewInteraction=()=>{this.messageViewController.setSelectedUserMessageOrdinal(null),this.messageViewController.setIsShowingRestoreConfirmation(!1),this.messageViewController.setIsShowingEditConfirmation(!1),this.messageViewController.setPendingEditText(null),this.messageViewController.setPendingEditImageAttachments([]),this.messageViewController.setAffectedFiles([]),this.messageViewController.stopEditing(),this.setState(()=>{this.isMessageViewInSelectionMode=!1,this.imagePreview=null}),this.scrollMessageViewToBottom(),H6.instance.addPostFrameCallback(()=>{if(!this.isShowingPalette&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})};enterHandoffMode=()=>{this.dismissPalette(),this.exitMessageViewInteraction(),this.handoffController?.enter()};exitHandoffMode=()=>{this.handoffController?.exit()};submitHandoff=async(J)=>{let Z=this.imageAttachments;if(this.resetHistory(),!this.handoffController){this.showSubmitDisabledHint("Handoff controller not initialized");return}let Q=await this.handoffController.submit(J,Z,this.agentModeController?.getMode()??null);if(!Q.ok&&Q.error.message!=="Cancelled")this.displayMessage=Q.error,this.setState(()=>{});else if(Q.ok)this.setState(()=>{this.imageAttachments=[]}),setTimeout(()=>{this.handoffController?.startCountdown(()=>{this.autoSubmitHandoffDraft().catch((Y)=>{this.handleSubmitFlowError(Y)})})},0)};autoSubmitHandoffDraft=async()=>{let J=this.textController.text;if(J.trim())this.textController.clear(),await this.sendUserMessage(J)};enterQueueMode=()=>{this.dismissPalette(),this.exitMessageViewInteraction(),this.setState(()=>{this.isInQueueMode=!0})};exitQueueMode=()=>{this.setState(()=>{this.isInQueueMode=!1})};submitQueue=(J)=>{this.exitMessageViewInteraction();let{threadState:Z}=this.widget.dependencies;if((Z.mainThread?.queuedMessages?.length??0)>=l00){this.toastController.show(`Queue is full (max ${l00} messages)`,"error",3000);return}let Y=this.imageAttachments;this.resetHistory(),this.setState(()=>{this.imageAttachments=[]}),this.textController.clear();let X=[{type:"text",text:J}];if(Y.length>0)X.push(...Y);this.widget.dependencies.activeThreadHandle.queueMessage(X),this.exitQueueMode()};isAuthRequiredStatus(J){if(!RD(J))return!1;let Z=J.error.message.toLowerCase();return Z.includes("user not found")||Z.includes("auth-required")||Z.includes("unauthorized")||Z.includes("forbidden")||Z.includes("401")||Z.includes("403")||Z.includes("api key")||Z.includes("access token")}shouldRequireAuthForPromptSubmit(){if(!this.tuiContext.hasAPIKeyAtStartup&&!y6(this.authStatus))return!0;return this.isAuthRequiredStatus(this.authStatus)&&!y6(this.authStatus)}queuePromptUntilAuthenticated(J,Z=[...this.imageAttachments],Q){if(this.queuedPromptAfterAuth={text:J,images:Z},Q?.clearInput??!0)this.textController.clear(),this.textController.resetScrollOffset(),this.resetHistory(),this.setState(()=>{this.imageAttachments=[]});this.showStatusMessage("Sign in required. Prompt queued and will send after login.",2500),this.ensureAuthLoginSession()}ensureAuthLoginSession=async()=>{if(this.pendingAuthLogin||this.isCreatingAuthLoginSession||y6(this.authStatus))return;this.isCreatingAuthLoginSession=!0;try{let J=mM4(32).toString("hex"),Z=await yC(this.tuiContext.ampURL,J),Q=await yC(this.tuiContext.ampURL,J,!1),Y=new AbortController;this.setState(()=>{this.pendingAuthLogin={authToken:J,browserURL:Z,manualURL:Q,abortController:Y,isOpeningBrowser:!1,isAuthenticating:!0,errorMessage:null}}),uK4(this.tuiContext.ampURL,J,this.widget.dependencies.secretStorage,Y).then(()=>{this.showStatusMessage("Login successful",2000),this.checkAuthStatusAfterLogin()}).catch((X)=>{if(Y.signal.aborted)return;let V=X instanceof Error?X.message:"Login failed. Please try again.";this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.errorMessage=V,this.pendingAuthLogin.isAuthenticating=!1})})}catch(J){let Z=J instanceof Error?J.message:"Unable to start login flow. Please try again.";this.setState(()=>{if(!this.pendingAuthLogin){this.displayMessage=Error(Z);return}this.pendingAuthLogin.errorMessage=Z,this.pendingAuthLogin.isAuthenticating=!1})}finally{this.isCreatingAuthLoginSession=!1}};openAuthLoginBrowser=async()=>{if(!this.pendingAuthLogin)return;let J=this.pendingAuthLogin.browserURL,Z=this.pendingAuthLogin.abortController;this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.isOpeningBrowser=!0,this.pendingAuthLogin.errorMessage=null});try{await fX(J,Z.signal)}catch(Q){let Y=Q instanceof Error?Q.message:"Unable to open browser. Copy the manual link.";this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.errorMessage=Y})}finally{this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.isOpeningBrowser=!1})}};copyAuthLoginLink=async()=>{let J=this.pendingAuthLogin?.manualURL;if(!J)return;try{await l4.instance.tuiInstance.clipboard.writeText(J),this.showStatusMessage("Login link copied to clipboard",2000)}catch(Z){j.error("Failed to copy login link",{error:Z}),this.showStatusMessage("Failed to copy login link",2000)}};checkAuthStatusAfterLogin=async()=>{try{let J=await this.widget.dependencies.configService.getLatest(),Z=_k(J),Q=await this.widget.dependencies.internalAPIClient.getUserInfo({},{config:this.widget.dependencies.configService,signal:AbortSignal.timeout(Z)});if(!Q.ok){this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.errorMessage="Still waiting for login confirmation. Finish login in your browser, then press I again."});return}this.setState(()=>{this.authStatus={user:Q.result,features:Q.result.features,workspace:Q.result.team,mysteriousMessage:Q.result.mysteriousMessage},this.pendingAuthLogin=null}),await this.maybeResumeQueuedPromptAfterAuth()}catch(J){j.error("Failed to verify login state",{error:J}),this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.errorMessage="Unable to verify login yet. Press I again in a moment."})}};cancelAuthLoginSession=()=>{if(this.pendingAuthLogin)this.pendingAuthLogin.abortController.abort(Error("Authentication cancelled"));this.setState(()=>{this.pendingAuthLogin=null})};maybeResumeQueuedPromptAfterAuth=async()=>{if(!y6(this.authStatus))return;let J=this.queuedPromptAfterAuth;if(!J)return;this.queuedPromptAfterAuth=null,await this.proceedWithUserMessage(J.text,J.images)};handleAuthModalKey=(J)=>{if(!this.pendingAuthLogin||this.pendingInputDialog)return!1;let Z=J.key.length===1?J.key.toLowerCase():J.key;if(Z==="Enter"||Z==="o")return this.openAuthLoginBrowser(),!0;if(Z==="c")return this.copyAuthLoginLink(),!0;if(Z==="i")return this.checkAuthStatusAfterLogin(),!0;if(Z==="p")return this.promptForAuthLoginCode(),!0;return!1};promptForAuthLoginCode=async()=>{if(!this.pendingAuthLogin)return;let{authToken:J,abortController:Z}=this.pendingAuthLogin,Q=await new Promise((Y)=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null,this.pendingInputDialog={options:{title:"Paste Login Code",helpText:"Paste the login code from the browser page. This is not your API key.",submitButtonText:"Verify"},resolve:Y}})});if(!Q||!this.pendingAuthLogin)return;try{let{accessToken:Y}=nx0(Q,J);await this.widget.dependencies.secretStorage.set("apiKey",Y,this.tuiContext.ampURL),Z.abort(Error("Authentication completed from pasted code")),this.showStatusMessage("Login code accepted",2000),await this.checkAuthStatusAfterLogin()}catch(Y){let X=Y instanceof Error?Y.message:"Invalid login code.";this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.errorMessage=X,this.pendingAuthLogin.isAuthenticating=!1})}};openInEditor=async(J)=>{try{let Z=await Ls5(wG.join(Rs5(),"amp-edit-")),Q=wG.join(Z,"message.amp.md");await Is5(Q,J,"utf-8"),await oY(Q);try{let Y=await Ms5(Q,"utf-8");this.textController.text=Y}catch(Y){if(Y?.code!=="ENOENT")j.error("Failed to read temporary file",Y)}try{await gM4(Q),await As5(Z)}catch(Y){j.warn("Failed to clean up temporary file",Y)}}catch(Z){j.error("Error opening editor:",Z)}};onTextSubmitted=async(J)=>{if(!J.trim()&&this.imageAttachments.length===0){if(!this.canInterruptQueuedInference())return;try{await this.interruptNextQueuedMessage();return}catch(Y){j.error("Failed to interrupt queued message from empty submit",Y)}return}let Z=J.trim();if(Z===":q"){this.widget.dependencies.setExitNotice?.("Vim reflex detected. Exiting politely."),await this.exitApplication();return}if(Z==="exit"||Z==="quit"){await this.exitApplication();return}if(this.handoffState.isInHandoffMode){await this.submitHandoff(J);return}if(this.isInQueueMode){this.submitQueue(J);return}let Q=aH(J);if(Q&&this.widget.dependencies.activeThreadHandle.invokeBashTool)if(!Q.cmd){this.showSubmitDisabledHint("No command provided");return}else if(this.isProcessing()){this.showSubmitDisabledHint("Unable to use shell mode while agent is active");return}else{this.invokeBashCommand(Q.cmd,{visibility:Q.visibility}),this.widget.dependencies.history.add(J,process.cwd()),this.textController.clear(),this.textController.resetScrollOffset(),this.resetHistory();return}if(this.shouldRequireAuthForPromptSubmit()){this.queuePromptUntilAuthenticated(J);return}this.textController.clear(),this.textController.resetScrollOffset(),this.resetHistory(),await this.updateGitBranch(),await this.sendUserMessage(J)};agentModeListener=()=>{let J=this.agentModeController?.getMode(),Z=this.canChangeAgentModeInPromptEditor(),Q=this.widget.dependencies.threadState.mainThread;if(!Q)return;let Y=!Z&&J!==null&&W3(Q)>0&&Q.agentMode!==J;if(this.handoffState.countdownSeconds!==null)this.handoffController?.stopCountdown();if(!Z&&J&&J!==this.sessionState.agentMode)this.persistAgentMode(J);if(Y)this.agentModeController?.setMode(null);let X=this.lastEffectiveAgentMode,V=this.getEffectiveAgentMode();this.lastEffectiveAgentMode=V,this.deepModeEffortHintController.onAgentModeTransition(X,V),this.setState(()=>{})};handoffListener=(J)=>{this.setState(()=>{this.handoffState=J})};handleWinPasteHookImagePaste=async(J)=>{this.lastUserInteractionTime=Date.now();let Z=this.imageAttachments.length;try{await this.handleInsertImage(J.image.tempFile)}catch(Q){j.error("Failed to process win-paste-hook image paste event",{error:Q})}if(this.imageAttachments.length<=Z)await gM4(J.image.tempFile).catch(()=>{})};handleWinPasteHookStateChange=(J)=>{if(J.current!=="disabled_session"||this.hasShownWinPasteHookRecoveryWarning)return;this.hasShownWinPasteHookRecoveryWarning=!0,this.toastController.show('Windows clipboard hook unavailable. Open the command palette (Ctrl+O) and run "paste image from clipboard".',"warning",7000)};initState(){if(OQ.getInstance().interceptConsole(),this.threadPreviewController.setThreadService(this.widget.dependencies.threadService),this.threadPreviewController.addListener(this.previewControllerListener),this.handoffController=new yg0({getActiveThreadHandle:()=>this.widget.dependencies.activeThreadHandle,getThreadPool:()=>this.widget.dependencies.threadPool,switchToThread:(X)=>{return this.textController.clear(),this.switchToExistingThread(X)}}),this.handoffController.addListener(this.handoffListener),this.tuiContext.openThreadSwitcher)this.showStandaloneThreadPicker();l4.instance.on("key",()=>{this.lastUserInteractionTime=Date.now()}),l4.instance.on("mouse",()=>{this.lastUserInteractionTime=Date.now()}),l4.instance.on("paste",()=>{this.lastUserInteractionTime=Date.now()});let J=l4.instance.tuiInstance;if(this.winPasteHookImageUnsubscribe=J.onWinPasteHookImagePaste((X)=>{this.handleWinPasteHookImagePaste(X)}),this.winPasteHookStateUnsubscribe=J.onWinPasteHookStateChange((X)=>{this.handleWinPasteHookStateChange(X)}),this.authStatus=this.tuiContext.initialServerStatus,this.authStatusSubscription=nJ(this.widget.dependencies.configService).subscribe((X)=>{if(this.setState(()=>{if(this.authStatus=X,y6(X))this.pendingAuthLogin=null}),this.agentModeController?.updateVisibilityContext({userEmail:y6(X)?X.user.email:void 0}),y6(X)){this.maybeResumeQueuedPromptAfterAuth();return}if(this.isAuthRequiredStatus(X))this.ensureAuthLoginSession()}),this.authModalKeyInterceptorUnsubscribe=l4.instance.addKeyInterceptor((X)=>this.handleAuthModalKey(X)),!this.tuiContext.hasAPIKeyAtStartup)this.ensureAuthLoginSession();this.autocompleteFocusNodeListener=(X)=>{H6.instance.addPostFrameCallback(()=>{if(!this.mounted)return;this.setState(()=>{this.isTextfieldAndAutocompleteFocused=X.hasFocus})},"TuiUIState.autocompleteFocusNodeListener")},this.autocompleteFocusNode.addListener(this.autocompleteFocusNodeListener),this.sessionState=this.tuiContext.sessionState??bC,this.shortcutsHintUsed=this.sessionState.shortcutsHintUsed,this.messageViewControllerUnsubscribe??=this.messageViewController.subscribe(this.handleMessageViewControllerUpdate),Promise.all([this.tuiContext.freeTierStatusPromise??Promise.resolve(void 0),E1(this.widget.dependencies.configService.config)]).then(([X,V])=>{if(X)this.freeTierStatus=X;this.paletteConfig=V;let K=Jy(V.settings),z=V.settings["anthropic.speed"],G=V.settings["openai.speed"];this.showSkillsCountInPromptBar=V.settings["internal.cli.showSkillsCountInPromptBar"]!==!1,this.adsDisabledBySetting=V.settings.newAdsDisplay===!0,this.applyDeepReasoningEffort(K),this.anthropicSpeed=z,this.openAISpeed=G,this.deepReasoningEffortSubscription=this.widget.dependencies.configService.config.pipe(D1((F)=>Jy(F.settings)),M4()).subscribe((F)=>{if(F!==this.deepReasoningEffort)this.applyDeepReasoningEffort(F),this.setState(()=>{this.agentModePulseSeq++})}),this.anthropicSpeedSubscription=this.widget.dependencies.configService.config.pipe(D1((F)=>({settings:F.settings})),M4((F,U)=>F.settings["anthropic.speed"]===U.settings["anthropic.speed"])).subscribe(({settings:F})=>{let U=F["anthropic.speed"];if(U!==this.anthropicSpeed)this.anthropicSpeed=U,this.setState(()=>{this.agentModePulseSeq++})}),this.openAISpeedSubscription=this.widget.dependencies.configService.config.pipe(D1((F)=>({settings:F.settings})),M4((F,U)=>F.settings["openai.speed"]===U.settings["openai.speed"])).subscribe(({settings:F})=>{let U=F["openai.speed"];if(U!==this.openAISpeed)this.openAISpeed=U,this.setState(()=>{this.agentModePulseSeq++})}),this.showSkillsCountInPromptBarSubscription=this.widget.dependencies.configService.config.pipe(D1((F)=>({settings:F.settings})),M4((F,U)=>F.settings["internal.cli.showSkillsCountInPromptBar"]===U.settings["internal.cli.showSkillsCountInPromptBar"])).subscribe(({settings:F})=>{let U=F["internal.cli.showSkillsCountInPromptBar"]!==!1;if(U!==this.showSkillsCountInPromptBar)this.setState(()=>{this.showSkillsCountInPromptBar=U})}),this.submitOnEnter=V.settings.submitOnEnter??!0,this.submitOnEnterSubscription=this.widget.dependencies.configService.config.pipe(D1((F)=>({settings:F.settings})),M4((F,U)=>F.settings.submitOnEnter===U.settings.submitOnEnter)).subscribe(({settings:F})=>{let U=F.submitOnEnter??!0;if(U!==this.submitOnEnter)this.setState(()=>{this.submitOnEnter=U})}),this.agentModeController=new _g0({initialCliMode:this.tuiContext.initialAgentMode,sessionState:this.sessionState,freeTierStatus:this.freeTierStatus,workspace:this.tuiContext.workspace??null,userEmail:y6(this.authStatus)?this.authStatus.user.email:void 0,initialSettings:V.settings,config$:this.widget.dependencies.configService.config,getThread:()=>this.widget.dependencies.threadState.mainThread}),this.agentModeController.addListener(this.agentModeListener),this.lastEffectiveAgentMode=this.getEffectiveAgentMode(),this.deepModeEffortHintController.maybeShowForInitialDeepMode(),this.scheduleAdSubscriptionWithIdeReadiness(),this.setState(()=>{})}),this.updateGitBranch(),this.allConnectedThreadActivityStatusesSubscription=this.widget.dependencies.threadPool.allConnectedThreadActivityStatuses$.subscribe((X)=>{if(this.areRecordValuesEqual(this.allConnectedThreadActivityStatuses,X))return;this.setState(()=>{this.allConnectedThreadActivityStatuses=X})}),this.threadTitlesSubscription=this.widget.dependencies.threadPool.threadTitles$.subscribe((X)=>{if(this.areRecordValuesEqual(this.threadTitles,X))return;this.setState(()=>{this.threadTitles=X})}),this.threadInitializationStatusSubscription=this.widget.dependencies.threadPool.initializationStatus$?.subscribe((X)=>{let V=X.pending?X.message:null;if(V===this.threadInitializationMessage)return;this.setState(()=>{this.threadInitializationMessage=V})})??null,this.pendingNavigationSubscription=this.widget.dependencies.threadPool.threadHandles$.pipe(M4(),Q4((X)=>X?X.thread$:v0.of(null))).subscribe((X)=>{this.checkForPendingNavigation(X);let V=X?.id;if(this.threadCostInfoThreadID!==V){if(this.threadCostInfo=void 0,this.threadCostInfoThreadID=V,V&&W3(X)>0)this.fetchThreadCostInfo()}let K=X?this.widget.dependencies.threadState.viewState:void 0;this.maybeRefetchThreadCostInfo(K?.state==="active"?K.inferenceState:void 0)}),this.freeTierStatusSubscription=Ke1(async()=>{let X=await this.widget.dependencies.configService.getLatest(),V=_k(X),K=await this.widget.dependencies.internalAPIClient.getUserFreeTierStatus({},{config:this.widget.dependencies.configService,signal:AbortSignal.timeout(V)});if(!K.ok)throw K.error;return K.result}).subscribe({next:(X)=>{if(X){let V=this.freeTierStatus.canUseAmpFree;if(this.setState(()=>{this.freeTierStatus=X}),this.agentModeController?.updateVisibilityContext({freeTierStatus:X}),X.canUseAmpFree!==V)if(X.canUseAmpFree){if(!this.adSubscription&&!this.adsDisabledBySetting)this.scheduleAdSubscriptionWithIdeReadiness()}else this.unsubscribeFromAds()}},error:(X)=>{j.debug("Failed to fetch free tier status",X)}});let{mcpTrustHandler:Z}=this.widget.dependencies;if(this.mcpTrustSubscription=Z.pendingServers$.subscribe((X)=>{this.setState(()=>{this.pendingMCPServers=X})}),Ax0((X)=>{this.setState(()=>{this.pendingOAuthRequest=X})}),this.mcpServersSubscription=this.widget.dependencies.mcpService.servers.subscribe((X)=>{this.setState(()=>{this.mcpServers=X})}),this.pendingSkillsSubscription=this.widget.dependencies.activeThreadHandle.pendingSkills$.subscribe((X)=>{this.setState(()=>{this.pendingSkills=X})}),this.widget.dependencies.pluginService){let X=this.widget.dependencies.pluginService;this.pluginCommandsSubscription=_J(X.plugins,X.commands.changed).subscribe(()=>{let V=X.commands.list();this.setState(()=>{this.pluginCommands=V})}),this.pluginInfosSubscription=X.plugins.subscribe((V)=>{this.setState(()=>{this.pluginInfos=V})})}this.skillListSubscription=this.widget.dependencies.skillService.skills.subscribe((X)=>{let V=X.filter((K)=>!K.baseDir.startsWith("builtin://")).length;this.setState(()=>{this.availableSkillCount=V,this.availableSkillCountReady=!0})}),this.skillWarningsSubscription=this.widget.dependencies.skillService.skillWarnings.subscribe((X)=>{this.setState(()=>{this.skillWarningCount=X.length})}),this.skillErrorsSubscription=this.widget.dependencies.skillService.skillErrors.subscribe((X)=>{this.setState(()=>{this.skillErrorCount=X.length})}),this.pendingApprovalsSubscription=this.widget.dependencies.activeThreadHandle.pendingApprovals$.subscribe((X)=>{this.setState(()=>{this.pendingApprovals=X})}),this.ideStatusSubscription=this.widget.dependencies.ideClient.status.subscribe((X)=>{let V=this.isIdeReadyForAdContext();if(this.setState(()=>{this.ideStatus=X}),!V&&this.isIdeReadyForAdContext()){if(this.adReadinessTimeout)clearTimeout(this.adReadinessTimeout),this.adReadinessTimeout=null;if(!this.adSubscription&&!this.adsDisabledBySetting)this.subscribeToAds()}}),this.ideMessageSubscription=this.widget.dependencies.ideClient.messages.subscribe(async(X)=>{try{if(!this.widget.dependencies.threadState.mainThread){j.warn("No active thread found to handle IDE message");return}await new Promise((K)=>setTimeout(K,50)),await this.widget.dependencies.activeThreadHandle.sendMessage({content:[{type:"text",text:X}]}),j.debug("Message sent from IDE to agent",{message:X.slice(0,100)})}catch(V){this.handleSubmitFlowError(V)}}),this.ideAppendToPromptSubscription=this.widget.dependencies.ideClient.appendToPrompt.subscribe((X)=>{this.textController.insertText(X),j.debug("Appended text to CLI prompt from IDE",{text:X.slice(0,100)})}),this.updateServiceSubscription=this.widget.dependencies.updateService.state.subscribe((X)=>{this.setState(()=>{this.updateState=X})}),this.mysteriousMessageSubscription=nJ(this.widget.dependencies.configService).pipe(F5((X)=>X!=="pending"),D1((X)=>y6(X)?X.mysteriousMessage??null:null),M4((X,V)=>X?.id===V?.id)).subscribe((X)=>{this.setState(()=>{if(X?.id!==this.mysteriousMessage?.id)this.isShowingMysteriousMessageModal=!1;if(this.mysteriousMessage=X,X&&!this.mysterySequenceManager)this.mysterySequenceManager=new E20(new Map([[new O20(RJ0.MYSTERY_SEQUENCE),new Pp]])),this.mysteryKeyInterceptorUnsubscribe=l4.instance.addKeyInterceptor((V)=>{if(!this.mysterySequenceManager)return!1;if(this.isShowingMysteriousMessageModal)return!1;let K=this.mysterySequenceManager.handleKeyEvent(V);if(K.consumed){if(K.intent)this.handleShowMysteryModal();return this.setState(()=>{this.mysterySequenceProgress=K.progress}),!0}else if(this.mysterySequenceProgress)this.setState(()=>{this.mysterySequenceProgress=null});return!1});else if(!X)this.mysteryKeyInterceptorUnsubscribe?.(),this.mysteryKeyInterceptorUnsubscribe=null,this.mysterySequenceManager?.dispose(),this.mysterySequenceManager=null,this.mysterySequenceProgress=null})}),this.textController.addListener(this.textChangeListener),l4.instance.addKeyInterceptor((X)=>{if(X.key==="?"){if(this.textController.text===""&&this.textController.cursorPosition===0&&!this.isShowingHelp&&!this.isShowingPalette&&this.isTextfieldAndAutocompleteFocused){if(this.setState(()=>{this.isShowingShortcutsHelp=!this.isShowingShortcutsHelp}),!this.shortcutsHintUsed)this.shortcutsHintUsed=!0,this.sessionState={...this.sessionState,shortcutsHintUsed:!0},rz(this.sessionState);return!0}}if(this.isShowingShortcutsHelp){if(this.setState(()=>{this.isShowingShortcutsHelp=!1}),X.key==="Escape")return!0;return!1}return!1}),this.updateTerminalTitle();let Q=this.widget.dependencies.ideClient.getSelectedConfig();if(Q)this.connectToSelectedIde(Q,"auto-startup").catch((X)=>{let V=X instanceof Error?X.message:String(X);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${V}`)})});else if(this.tuiContext.showIdePickerHint)this.toastController.show("Use /ide to connect to an IDE","success",5000);else if(this.tuiContext.showJetBrainsInstaller)this.openJetBrainsInstaller();let Y=this.widget.dependencies.threadState.mainThread;if(!Y){this.initNewsFeed();return}if(Y.autoSubmitDraft&&Y.messages.length===0)setTimeout(()=>{this.autoSubmitInitialDraft(Y.id)},100);this.initNewsFeed()}async autoSubmitInitialDraft(J){let Z=await this.getDraft(J);if(!Z)return;let Q=Z.text.trim();if(!Q&&Z.images.length===0)return;j.info("Auto-submitting initial handoff draft",{name:"handoff",threadID:J,hasDraftText:Boolean(Q),draftImageCount:Z.images.length}),this.textController.clear(),await this.proceedWithUserMessage(Q,[...Z.images])}handleSubmitFlowError(J){j.error("Failed to submit prompt message",J);let Z=J instanceof Error?J.message:String(J);this.showErrorMessage(Z)}checkForPendingNavigation(J){let Z=J??this.widget.dependencies.threadState.mainThread;if(!Z?.pendingNavigation)return;let Q=Z.pendingNavigation;if(this.pendingNavigationInFlightThreadID===Q)return;this.pendingNavigationInFlightThreadID=Q,this.widget.dependencies.activeThreadHandle.clearPendingNavigation().catch(()=>{return}),j.info("Pending navigation detected, navigating to new thread",{name:"handoff",fromThreadID:Z.id,targetThreadID:Q}),this.handleHandoffNavigation(Q).finally(()=>{if(this.pendingNavigationInFlightThreadID===Q)this.pendingNavigationInFlightThreadID=null})}handleHandoffNavigation=async(J)=>{try{await this.switchToExistingThread(J);let Z=this.widget.dependencies.threadState.mainThread;if(!Z){j.error("Failed to get new thread after handoff navigation");return}if(Z.autoSubmitDraft&&Z.messages.length===0){let Q=await this.getDraft(J);if(!Q)return;let Y=Q.text.trim();if(!Y&&Q.images.length===0)return;j.info("Auto-submitting handoff draft",{name:"handoff",threadID:J,hasDraftText:Boolean(Y),draftImageCount:Q.images.length}),this.textController.clear(),await this.proceedWithUserMessage(Y,[...Q.images])}}catch(Z){j.error("Failed to handle handoff navigation",{name:"handoff",newThreadID:J,error:Z})}};dispose(){if(this.ideStatusSubscription)this.ideStatusSubscription.unsubscribe();if(this.ideMessageSubscription)this.ideMessageSubscription.unsubscribe();if(this.ideAppendToPromptSubscription)this.ideAppendToPromptSubscription.unsubscribe();if(this.updateServiceSubscription)this.updateServiceSubscription.unsubscribe();if(this.agentModeController)this.agentModeController.removeListener(this.agentModeListener),this.agentModeController.dispose();if(this.deepModeEffortHintController.dispose(),this.messageViewControllerUnsubscribe)this.messageViewControllerUnsubscribe(),this.messageViewControllerUnsubscribe=null;if(this.handoffController)this.handoffController.removeListener(this.handoffListener),this.handoffController.dispose();if(this.adReadinessTimeout)clearTimeout(this.adReadinessTimeout),this.adReadinessTimeout=null;if(this.adSubscription)this.adSubscription.unsubscribe();if(this.freeTierStatusSubscription)this.freeTierStatusSubscription.unsubscribe();if(this.allConnectedThreadActivityStatusesSubscription)this.allConnectedThreadActivityStatusesSubscription.unsubscribe();if(this.threadInitializationStatusSubscription)this.threadInitializationStatusSubscription.unsubscribe();if(this.threadTitlesSubscription)this.threadTitlesSubscription.unsubscribe();if(this.pendingNavigationSubscription)this.pendingNavigationSubscription.unsubscribe();if(this.mcpTrustSubscription)this.mcpTrustSubscription.unsubscribe();if(this.authStatusSubscription)this.authStatusSubscription.unsubscribe(),this.authStatusSubscription=null;if(Ax0(null),this.authModalKeyInterceptorUnsubscribe?.(),this.authModalKeyInterceptorUnsubscribe=null,this.pendingAuthLogin)this.pendingAuthLogin.abortController.abort(Error("TUI disposed")),this.pendingAuthLogin=null;if(this.mcpServersSubscription)this.mcpServersSubscription.unsubscribe();if(this.pendingSkillsSubscription)this.pendingSkillsSubscription.unsubscribe();if(this.pluginCommandsSubscription)this.pluginCommandsSubscription.unsubscribe();if(this.pluginInfosSubscription)this.pluginInfosSubscription.unsubscribe();if(this.skillListSubscription)this.skillListSubscription.unsubscribe();if(this.skillWarningsSubscription)this.skillWarningsSubscription.unsubscribe();if(this.skillErrorsSubscription)this.skillErrorsSubscription.unsubscribe();if(this.pendingApprovalsSubscription)this.pendingApprovalsSubscription.unsubscribe();if(this.unloadThreadsForPicker(),this.newsFeedSubscription)this.newsFeedSubscription.unsubscribe();if(this.deepReasoningEffortSubscription)this.deepReasoningEffortSubscription.unsubscribe(),this.deepReasoningEffortSubscription=null;if(this.anthropicSpeedSubscription)this.anthropicSpeedSubscription.unsubscribe(),this.anthropicSpeedSubscription=null;if(this.openAISpeedSubscription)this.openAISpeedSubscription.unsubscribe(),this.openAISpeedSubscription=null;if(this.submitOnEnterSubscription)this.submitOnEnterSubscription.unsubscribe(),this.submitOnEnterSubscription=null;if(this.showSkillsCountInPromptBarSubscription)this.showSkillsCountInPromptBarSubscription.unsubscribe(),this.showSkillsCountInPromptBarSubscription=null;if(this.stopElapsedTimeTimer(),this.winPasteHookImageUnsubscribe?.(),this.winPasteHookImageUnsubscribe=null,this.winPasteHookStateUnsubscribe?.(),this.winPasteHookStateUnsubscribe=null,this.mysteriousMessageSubscription)this.mysteriousMessageSubscription.unsubscribe();if(this.mysteryKeyInterceptorUnsubscribe?.(),this.mysterySequenceManager?.dispose(),this.threadPreviewController.removeListener(this.previewControllerListener),this.threadPreviewController.dispose(),this.toastController.dispose(),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;if(this.autocompleteFocusNodeListener)this.autocompleteFocusNode.removeListener(this.autocompleteFocusNodeListener),this.autocompleteFocusNodeListener=null;this.textController.removeListener(this.textChangeListener);for(let J of this.messageScrollControllers.values())J.dispose();this.messageScrollControllers.clear()}getCurrentConfirmation(){if(this.pendingApprovals.length>0){let J=this.pendingApprovals[0];return{type:"tool-use",tools:[{useBlock:{type:"tool_use",id:J.toolUseId,name:J.toolName,complete:!0,input:J.args},toAllow:J.toAllow??[]}],subthreadID:void 0,reason:J.reason??`Tool requires approval: ${J.toolName}`,isSubagent:J.context==="subagent",subagentToolName:J.subagentToolName}}return null}updateProgressBar(){}static AD_READINESS_TIMEOUT_MS=1000;scheduleAdSubscriptionWithIdeReadiness(){if(this.adsDisabledBySetting)return;if(!this.freeTierStatus.canUseAmpFree)return;if(this.isIdeReadyForAdContext()){this.subscribeToAds();return}this.adReadinessTimeout=setTimeout(()=>{if(this.adReadinessTimeout=null,!this.adSubscription)this.subscribeToAds()},RJ0.AD_READINESS_TIMEOUT_MS)}isIdeReadyForAdContext(){let J=this.ideStatus;if(!J||!J.enabled)return!1;return Boolean(J.openFile||J.visibleFiles&&J.visibleFiles.length>0)}unsubscribeFromAds(){if(this.adSubscription)this.adSubscription.unsubscribe(),this.adSubscription=null;if(this.adReadinessTimeout)clearTimeout(this.adReadinessTimeout),this.adReadinessTimeout=null;this.setState(()=>{this.randomAd=null})}subscribeToAds(){if(this.adSubscription)return;if(this.adsDisabledBySetting)return;if(!this.freeTierStatus.canUseAmpFree)return;this.adSubscription=Gg0(this.widget.dependencies.internalAPIClient,this.widget.dependencies.configService,()=>zg0(this.lastUserInteractionTime),this.widget.dependencies.codebaseContextService,()=>this.widget.dependencies.threadState.mainThread??void 0).subscribe({next:(J)=>{this.setState(()=>{this.randomAd=J}),H6.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})}})}onConfirmationResponse=async(J)=>{let Z=this.getCurrentConfirmation();if(!Z||Z.type!=="tool-use"){j.error("No current tool confirmation found");return}let Q=Z.tools[0]?.useBlock;if(!Q){j.error("No tool use block found in confirmation");return}if(J?.type==="deny-with-feedback"){let{feedback:V}=J;try{if(this.pendingApprovals.find((z)=>z.toolUseId===Q.id))await this.widget.dependencies.activeThreadHandle.resolveApproval(Q.id,!1,V.trim()||void 0);else await this.widget.dependencies.activeThreadHandle.resolveApproval(Q.id,!1,V.trim()||void 0)}catch(K){j.error("Failed to send deny with feedback:",K)}return}let Y=J?.type==="simple"?J.value:null;if(Y==="allow-all-session")u$("dangerouslyAllowAll",!0);if(Y==="allow-all-persistent")try{await this.widget.dependencies.settingsStorage.set("dangerouslyAllowAll",!0,"global")}catch(V){if(V&&V instanceof Error)this.setState(()=>{this.displayMessage=V});else j.error("Failed to write dangerouslyAllowAll setting:",V);return}if(Y==="always-guarded"){let V=Z.tools[0]?.toAllow??[],K=await this.widget.dependencies.settingsStorage.get("guardedFiles.allowlist")||[],z=[...V,...K];await this.widget.dependencies.settingsStorage.set("guardedFiles.allowlist",z,"global")}if(Y==="connect-github"){let V=new URL("/settings#code-host-connections",this.tuiContext.ampURL).toString();await w8(this.context,V);return}if(Y==="disable-librarian"){let V=await this.widget.dependencies.settingsStorage.get("tools.disable")??[];if(!V.includes(T$))await this.widget.dependencies.settingsStorage.set("tools.disable",[...V,T$],"global")}let X=Y!==null&&["yes","allow-all-session","allow-all-persistent","always-guarded"].includes(Y);try{await this.widget.dependencies.activeThreadHandle.resolveApproval(Q.id,X)}catch(V){j.error("Failed to send tool confirmation:",V)}};showConfirmationOverlay=(J)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=J})};getCurrentEphemeralError(){let{threadState:J}=this.widget.dependencies,Z=J.viewState;if(Z.state!=="active"||!Z.ephemeralError)return null;return Z.ephemeralError}handleEphemeralErrorResponse=async(J)=>{let{activeThreadHandle:Z}=this.widget.dependencies;switch(J){case"retry":await Z.retryTurn();break;case"dismiss":Z.dismissEphemeralError();break;case"new-thread":Z.dismissEphemeralError(),await this.startAndSwitchToNewThread();break;case"handoff":Z.dismissEphemeralError(),this.enterHandoffMode();break;case"add-credits":{let Q=new URL("/pay",this.tuiContext.ampURL);await w8(this.context,Q),this.showStatusMessage("Payment page opened. After paying, choose Retry.");break}}this.setState(()=>{})};handleDisplayMessageDismiss=()=>{this.setState(()=>{this.displayMessage=null})};handleMCPTrustOpenSettings=async()=>{let{mcpTrustHandler:J,settingsStorage:Z}=this.widget.dependencies;await J.deny();try{await oY(Z.getSettingsFilePath())}catch(Q){let Y=Q instanceof Error?Q.message:String(Q);await this.showErrorMessage(`Failed to open settings: ${Y}`)}};cancelStreamingMessage=async()=>{await this.widget.dependencies.activeThreadHandle.cancelStreaming()};switchToExistingThread=async(J,Z={})=>{let{recordInNavigationHistory:Q=!0}=Z,Y=Date.now(),X=this.widget.dependencies.threadState.mainThread?.id,V=Q&&X!==void 0&&X!==J;try{j.info(`[switchToExistingThread] Switching to thread: ${J}`);let K=Date.now();await this.widget.dependencies.threadPool.switchThread(J),j.info(`[switchToExistingThread] switchToThread resolved in ${Date.now()-K}ms`);let z=await this.widget.dependencies.threadService.get(J)??this.widget.dependencies.threadState.mainThread;if(!z||z.id!==J)throw Error("No active thread after switch");j.info(`[switchToExistingThread] Got thread ${J}, thread.agentMode: ${z.agentMode}`),j.info("[switchToExistingThread] Clearing agent mode"),this.agentModeController?.setMode(null);let G=Date.now();if(this.onThreadSwitch(),j.info(`[switchToExistingThread] onThreadSwitch completed in ${Date.now()-G}ms`),V&&X)this.recordNavigation(X);this.persistLastThreadId(J);let F=await this.getDraft(J);if(F&&W3(z)===0){if(this.textController.clear(),F.text)this.textController.insertText(F.text);if(F.images.length>0)this.setState(()=>{this.imageAttachments=[...F.images]})}j.info(`[switchToExistingThread] Completed in ${Date.now()-Y}ms`)}catch(K){j.error("Failed to switch to thread",{threadId:J,error:K});let z=K instanceof Error?K.message:String(K);if(z.includes("can't be opened in legacy mode")){await this.showErrorMessage(z);return}throw Error(`Failed to switch to thread: ${J}. ${z}`,{cause:K})}};async getDraft(J){return(await E1(this.widget.dependencies.threadPool.drafts$).catch(()=>null))?.get(J)??null}sendUserMessage=async(J)=>{await this.proceedWithUserMessage(J)};proceedWithUserMessage=async(J,Z)=>{if(this.cancelBashInvocations(),this.shouldRequireAuthForPromptSubmit()){this.queuePromptUntilAuthenticated(J,Z??[...this.imageAttachments],{clearInput:Z===void 0});return}this.handoffController?.clearPendingPrompt(),this.widget.dependencies.history.add(J,process.cwd());let Q=this.widget.dependencies.threadState.mainThread;if(!Q)return;let Y=W3(Q)===0,X=this.getEffectiveAgentMode();if(Q.agentMode&&!Y&&X!==Q.agentMode){await this.showErrorMessage(`This thread uses ${Q.agentMode} mode. To change mode, edit the first message or create a new thread.`);return}let V=Z??this.imageAttachments,K=[{type:"text",text:J}];if(V.length>0)K.push(...V);if(await this.widget.dependencies.activeThreadHandle.sendMessage({content:K,agentMode:X}),this.persistLastThreadId(Q.id),Y)this.persistAgentMode(X);if(this.scrollMessageViewToBottom(),!Z)this.setState(()=>{this.imageAttachments=[]});H6.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})};async showErrorMessage(J){this.setState(()=>{this.displayMessage=Error(J)})}exitApplication=async()=>{this.setState(()=>{this.isExiting=!0});let J=this.widget.dependencies.threadState.mainThread;if(J&&J.messages.length===0){if(J.relationships?.find((Q)=>Q.type==="handoff"&&Q.role==="child"))await this.widget.dependencies.threadPool.deleteThread?.(J.id).catch(()=>{})}l4.instance.stop()};async persistAgentMode(J){let Q={...await oz(),agentMode:J};this.sessionState=Q,await rz(Q)}async persistLastThreadId(J){let Q={...await oz(),lastThreadId:J};this.sessionState=Q,await rz(Q)}onExitPressed=()=>{if(this.isConfirmingExit){if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;this.exitApplication()}else{if(this.setState(()=>{this.isConfirmingExit=!0}),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout);this.exitConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingExit=!1}),this.exitConfirmTimeout=null},1000)}};toHomeRelative(J){let Z=js5();if(J===Z)return"~";if(J.startsWith(Z+wG.sep))return"~"+J.slice(Z.length);return J}shorten(J){let Z=J.split(wG.sep).filter(Boolean);if(Z.length<=5)return J;return[Z.slice(0,2).join(wG.sep),"…",Z.slice(-2).join(wG.sep)].join(wG.sep)}buildDisplayText(J,Z,Q,Y){let X=Z?` (${Z})`:"",V=J+X;if(p5(V,Y)<=Q)return V;let K=J.split(wG.sep);if(K.length>2){let G=[K[0],"…",K[K.length-1]].join(wG.sep)+X;if(p5(G,Y)<=Q)return G}return sE(V,Q,Y)}build(J){this.lastRootContext=J;let Z=this.widget.dependencies.pluginPlatform;if(Z&&!Z.showToast){let z1=this.toastController;Z.showToast=(L4)=>z1.show(L4,"success")}if(Z&&!Z.showOpenedURLToast){let z1=this.toastController;Z.showOpenedURLToast=(L4)=>z1.show(`Opened URL: ${L4}`,"success",8000)}if(Z&&!Z.appendToThreadHandler){let z1=this.widget.dependencies;Z.appendToThreadHandler=async(L4)=>{for(let T4 of L4)await z1.activeThreadHandle.queueMessage([{type:"text",text:T4.content}])}}if(Z&&!Z.showInputDialog)Z.showInputDialog=(z1)=>{return new Promise((L4)=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null,this.pendingInputDialog={options:z1,resolve:L4}})})};if(Z&&!Z.showConfirmDialog)Z.showConfirmDialog=(z1)=>{return new Promise((L4)=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null,this.pendingConfirmDialog={options:z1,resolve:L4}})})};let Q=t1.of(J),Y=f0.of(J),X=Y.base;this.themeColors=X;let{colors:V,app:K}=Y;this.themeApp=K;let z=this.widget.dependencies.threadState.mainThread,G=z?.agentMode&&h3(z.agentMode),F=this.freeTierStatus.isDailyGrantEnabled,U=!this.adsDisabledBySetting&&(G||F)&&this.randomAd!==null,q=Boolean(U),{threadState:D}=this.widget.dependencies;this.updateTerminalTitle(),this.updateProgressBar();let W=this.getCurrentConfirmation(),H=D.items,B=D.mainThread||void 0,w=D.subagentToolsByParentID,N=D.toolProgressByToolUseID,O=D.todosList,E=B?.id,L=B,M=this.isTranscriptEmpty(),A=M&&this.isStartupThreadLoading(),I=this.threadInitializationMessage?.startsWith("Importing thread")??!1,P=this.widget.dependencies.threadPool.isDTWMode?.()===!0,_=(z1)=>new qd({key:new $3(`preview-message-view-${z1.id}`),items:TU(z1).items,toolProgressByToolUseID:new Map,controller:this.threadPreviewController.scrollController,autofocus:!1,thread:z1,denseView:z1.agentMode==="deep",focusNode:new r4({debugLabel:"PreviewFocus"}),onShowImagePreview:()=>{},stateController:this.previewMessageViewController,submitOnEnter:this.submitOnEnter,isDTWMode:P}),S=this.previewThread,y=S?S.messages.length>2000?new u0({mainAxisSize:"max",children:[new T1({child:new R0}),new i0({padding:C0.all(2),child:new l1({child:new $0({text:new C("Thread too long for preview",new h({color:V.mutedForeground,dim:!0}))})})})]}):_(S):M?new P$0({agentMode:this.getEffectiveAgentMode(),mysteriousMessage:this.mysteriousMessage,mysterySequenceProgress:this.mysterySequenceProgress,onShowMysteryModal:this.handleShowMysteryModal,onOrbExplode:this.handleSplashOrbExplode}):new ed0({threadID:E,items:H,subagentToolsByParentID:w,toolProgressByToolUseID:N,controller:E?this.getMessageScrollController(E):new Y5,autofocus:!1,onCopy:this.handleMainMessageViewCopy,thread:L,onMessageEditSubmit:this.handleMessageEditSubmit,...P?{}:{onMessageRestoreSubmit:this.handleMessageRestoreSubmit},onShowForkDeprecation:this.showForkDeprecationMessage,getAffectedFiles:this.getAffectedFiles,denseView:L?.agentMode==="deep",focusNode:this.messageViewFocusNode,onDismissFocus:this.handleMainMessageViewDismissFocus,isInSelectionMode:this.isMessageViewInSelectionMode,isInHandoffMode:this.handoffState.isInHandoffMode,completionBuilder:this.getCompletionBuilder(),onShowImagePreview:this.handleShowEditingImagePreview,onSelectionChanged:this._handleSelectionChanged,onDoubleAtTrigger:this.handleDoubleAtTrigger,stateController:this.messageViewController,submitOnEnter:this.submitOnEnter,threadViewState:D.viewState,isDTWMode:P}),m=Math.max(Math.floor(Q.size.height*0.4),12),b=this.getCurrentEphemeralError(),k=Q.size.width<40,f=dM4(D),p=this.widget.dependencies.threadPool.getCompactionStatus?.(),l=M20(J),x=this.buildBottomWidget(b,W,V,Y,D,O,m,q,f,Q,l),r=new L$0({threadViewState:D.viewState,threadTokenUsage:f,compactionState:p?.compactionState??"idle",threadID:E??null,thread:D.mainThread??void 0,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},onShowIdePicker:this.openIdePicker,ideStatus:this.ideStatus,mcpServers:this.mcpServers,plugins:this.pluginInfos,isNarrow:k,uiHint:this.getUIHint()??void 0,waitingForConfirmation:!!W,showingEphemeralError:Boolean(D.viewState.state==="active"&&D.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null,executingCommandNoun:this.executingCommand?.noun??null,executingCommandVerb:this.executingCommand?.verb??null,executingCommandMessage:this.executingCommand?.statusMessage??null}),c=new O$0({bashInvocations:this.bashInvocations}),s=[],w0=_K4(this.tuiContext.buildTimestamp);if(w0){let z1=sL0(w0.ageMs,{verbose:!0});s.push(new c0({decoration:new v4(V.destructive),child:new i0({padding:C0.horizontal(1),child:new $0({text:new C("",new h({color:V.foreground,bold:!0}),[new C(`Your Amp version is ${z1} old — run `),new C("amp update",new h({color:V.warning})),new C(" or see ampcode.com/manual")]),textAlign:"center"})})}))}s.push(new T1({child:y}),c);let a=new i6({children:[new u0({mainAxisSize:"min",children:[U?new lg0({ad:this.randomAd,onImpression:(z1)=>{if(!z1.advertiserId){j.warn("[ad-telemetry] Skipping impression due to missing advertiserId",{adId:z1.id});return}let L4=z1.impressionId??mM4(16).toString("hex");this.lastAdImpressionId=L4;let T4=this.widget.dependencies.threadState.mainThread;if(!T4)return;let i4=T4.messages[T4.messages.length-1],E8=Date.now();CN("viewed",{adId:z1.id,advertiserId:z1.advertiserId,threadId:T4.id,messageId:i4?.messageId,impressionId:L4,placement:"tui",matchType:z1.metadata?.matchType,matchedPatterns:z1.metadata?.matchedPatterns,candidateAdPoolCount:z1.metadata?.candidateAdPoolCount,clientRegion:z1.metadata?.clientRegion,tokenProvided:!!z1.impressionToken,campaignId:z1.metadata?.campaignId,providerId:z1.metadata?.providerId,providerType:z1.metadata?.providerType,relevance:z1.metadata?.relevance}),CN("impressionStarted",{adId:z1.id,advertiserId:z1.advertiserId,impressionId:L4,placement:"tui",providerId:z1.metadata?.providerId,providerType:z1.metadata?.providerType}),this.widget.dependencies.internalAPIClient.recordAdImpression({adId:z1.id,impressionToken:z1.impressionToken,impressionId:L4,externalImpressionUrl:z1.externalImpressionUrl},{config:this.widget.dependencies.configService}).then((L7)=>{if(!L7.ok)throw Error(`recordAdImpression failed: ${L7.error.code??"unknown"}`);let zX=Math.round(Date.now()-E8);CN("impressionRecorded",{adId:z1.id,advertiserId:z1.advertiserId,impressionId:L4,placement:"tui",durationMs:zX,providerId:z1.metadata?.providerId,providerType:z1.metadata?.providerType})}).catch((L7)=>{let zX=Math.round(Date.now()-E8);CN("impressionFailed",{adId:z1.id,advertiserId:z1.advertiserId,impressionId:L4,errorMessage:L7 instanceof Error?L7.message:String(L7),errorType:"error",placement:"tui",durationMs:zX,providerId:z1.metadata?.providerId,providerType:z1.metadata?.providerType})})},onButtonClick:async()=>{let z1=this.randomAd;if(this.lastAdImpressionId&&z1.advertiserId){let i4=this.widget.dependencies.threadState.mainThread;if(!i4)return;let E8=i4.messages[i4.messages.length-1];CN("clicked",{adId:z1.id,advertiserId:z1.advertiserId,threadId:i4.id,messageId:E8?.messageId,impressionId:this.lastAdImpressionId,placement:"tui",actionType:"link_to",matchType:z1.metadata?.matchType,matchedPatterns:z1.metadata?.matchedPatterns,candidateAdPoolCount:z1.metadata?.candidateAdPoolCount,clientRegion:z1.metadata?.clientRegion,providerId:z1.metadata?.providerId,providerType:z1.metadata?.providerType})}let T4=l4.instance.tuiInstance.clipboard.isOsc52Supported();if(d80())this.setState(()=>{this.adActionModal={showCopyOption:!1,url:z1.shortDestinationUrl,title:z1.buttonLabel},this.bringAdModalToFront("adAction")});else if(!await w8(this.context,z1.shortDestinationUrl))this.setState(()=>{this.adActionModal={showCopyOption:T4,url:z1.shortDestinationUrl},this.bringAdModalToFront("adAction")})},onAdInfoClick:()=>{this.setState(()=>{this.adInfoModal={provider:this.randomAd?.metadata?.provider},this.bringAdModalToFront("adInfo")})}}):new R0({height:0}),new c0({constraints:new M1(0,Q.size.width,0,m),child:x})]}),q?new x6({top:0,left:0,right:0,child:new iM4({userHeight:this.bottomGridUserHeight,maxHeight:m,onInitializeHeight:(z1)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(z1,m)})},onDrag:(z1)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(z1.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let L4=Math.floor(z1.localPosition.y)-this.bottomGridDragStartY,T4=Math.max(4,this.bottomGridDragStartHeight-L4),i4=Math.min(T4,m),E8=Math.floor(i4);if(this.bottomGridUserHeight!==E8)this.setState(()=>{this.bottomGridUserHeight=E8})},onRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null}})}):new R0({height:0})]}),F0=this.getParentThreadInfo();if(F0){let z1=F0.type==="handoff"?K.handoffMode:V.primary,L4=40,T4=l6(F0.title),i4=T4.length>40?T4.slice(0,39).join("")+"…":F0.title;s.push(new bp({link:this.parentThreadLinkAnchor,child:new Sp0({type:F0.type,title:i4,threadID:F0.threadID,labelColor:z1,mutedColor:V.mutedForeground,foregroundColor:V.foreground,onNavigate:(E8)=>this.switchToExistingThread(E8)})}))}s.push(a,new R0({height:1,child:new i0({padding:C0.horizontal(1),child:r})}));let z0=new u0({crossAxisAlignment:"stretch",mainAxisSize:"max",children:s}),q0=new c0({constraints:M1.tight(Q.size.width,Q.size.height),decoration:new v4(V.background),child:z0}),Q0=new s4(()=>{if(this.isShowingPalette)return this.dismissPalette(),"handled";if(this.isShowingMCPStatusModal)return this.setState(()=>{this.isShowingMCPStatusModal=!1}),"handled";if(this.pendingAuthLogin)return this.cancelAuthLoginSession(),"handled";if(this.pendingOAuthRequest){let L4=this.pendingOAuthRequest;return this.setState(()=>{this.pendingOAuthRequest=null}),L4.reject(Error("OAuth authorization cancelled")),"handled"}if(this.isShowingPromptHistoryPicker)return this.setState(()=>{this.isShowingPromptHistoryPicker=!1}),"handled";if(this.pendingMCPServers.length>0)return this.widget.dependencies.mcpTrustHandler.deny(),"handled";if(this.getCurrentEphemeralError())return this.handleEphemeralErrorResponse("dismiss"),"handled";if(this.displayMessage)return this.handleDisplayMessageDismiss(),"handled";if(this.isShowingHelp)return this.setState(()=>{this.isShowingHelp=!1}),"handled";if(this.isShowingContextAnalyzeModal)return this.setState(()=>{this.isShowingContextAnalyzeModal=!1,this.contextAnalyzeDeps=null,this.contextAnalyzeFromDTW=null}),"handled";if(this.isShowingSkillListModal)return this.setState(()=>{this.isShowingSkillListModal=!1}),"handled";if(this.isShowingFileChangesOverlay)return this.setState(()=>{this.isShowingFileChangesOverlay=!1}),"handled";if(this.isShowingContextDetailOverlay)return this.setState(()=>{this.isShowingContextDetailOverlay=!1}),"handled";if(this.isShowingIdePicker)return this.dismissIdePicker(),"handled";if(this.isShowingJetBrainsInstaller)return this.dismissJetBrainsInstaller(),"handled";if(this.isShowingConfirmationOverlay)return this.setState(()=>{this.isShowingConfirmationOverlay=!1,this.confirmationOverlayContent=""}),"handled";if(this.isShowingConsoleOverlay)return this.setState(()=>{this.isShowingConsoleOverlay=!1}),"handled";if(this.dismissTopAdModal())return"handled";if(this.handoffState.countdownSeconds!==null)return this.handoffController?.stopCountdown(),"handled";if(this.handoffState.isInHandoffMode){if(this.handoffState.isGeneratingHandoff)this.handoffController?.cancelGeneration();else this.exitHandoffMode();return"handled"}if(this.isInQueueMode)return this.exitQueueMode(),"handled";if(this.textController.hasSelection)return this.textController.clearSelection(),"handled";if(this.isConfirmingClearInput){if(this.textController.clear(),this.textController.resetScrollOffset(),this.widget.dependencies.activeThreadHandle.clearPendingSkills(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.handoffState.isConfirmingAbortHandoff&&this.handoffController){let L4=this.handoffController.getPendingPrompt(),T4=this.imageAttachments;return this.textController.clear(),this.textController.resetScrollOffset(),this.widget.dependencies.activeThreadHandle.clearPendingSkills(),this.setState(()=>{this.imageAttachments=[]}),this.handoffController.confirmAbort().then((i4)=>{if(i4&&L4)this.textController.text=L4,this.handoffController?.clearPendingPrompt();if(i4&&T4.length>0)this.setState(()=>{this.imageAttachments=T4})}),"handled"}if(this.isConfirmingCancelProcessing){if(this.bashInvocations.length>0)this.cancelBashInvocations();if(this.cancelStreamingMessage().catch((L4)=>{j.error("Failed to cancel streaming message:",L4)}),this.setState(()=>{this.isConfirmingCancelProcessing=!1}),this.cancelProcessingConfirmTimeout)clearTimeout(this.cancelProcessingConfirmTimeout),this.cancelProcessingConfirmTimeout=null;return"handled"}if(this.executingCommand)return j.info("Canceling executing command:",this.executingCommand.name),this.executingCommand.abortController.abort(),"handled";if(this.bashInvocations.length>0||this.isProcessing()){if(this.setState(()=>{this.isConfirmingCancelProcessing=!0}),this.cancelProcessingConfirmTimeout)clearTimeout(this.cancelProcessingConfirmTimeout);return this.cancelProcessingConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingCancelProcessing=!1}),this.cancelProcessingConfirmTimeout=null},1000),"handled"}if(this.handoffController?.getEmptyHandoffParentThreadID(this.widget.dependencies.threadState.mainThread))return this.handoffController.startAbortConfirmation(),"handled";if(this.textController.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"ignored"}),H0=new s4(()=>{return this.onExitPressed(),"handled"}),i=new s4(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),n=new s4(()=>{return this.setState(()=>{this.isShowingMCPStatusModal=!this.isShowingMCPStatusModal}),"handled"}),e=new s4(()=>{if(r9.instance.toggleAll(),D.mainThread?.agentMode==="deep"||D.mainThread?.agentMode==="internal")UJ.instance.toggleAll();return"handled"}),J0=new s4(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";return this.setState(()=>{this.isShowingPromptHistoryPicker=!0}),"handled"}),Z0=new s4(()=>{return l4.instance.toggleFrameStatsOverlay(),"handled"}),K0=new s4(()=>{return l4.instance.tuiInstance.getScreen().markForRefresh(),H6.instance.requestFrame(),"handled"}),t=new s4(()=>{return this.toggleAgentMode(),"handled"}),V0=new s4(()=>{return this.toggleDeepReasoningEffort(),"handled"}),N0=new s4(()=>{let L4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:T4}=this.widget.dependencies,i4=T4.mainThread?.id;return i4?this.getMessageScrollController(i4):null})();if(L4){let T4=Math.max(Math.floor(Q.size.height*0.4),10),i4=Q.size.height-T4;L4.animatePageUp(i4,100)}return"handled"}),D0=new s4(()=>{let L4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:T4}=this.widget.dependencies,i4=T4.mainThread?.id;return i4?this.getMessageScrollController(i4):null})();if(L4){let T4=Math.max(Math.floor(Q.size.height*0.4),10),i4=Q.size.height-T4;L4.animatePageDown(i4,100)}return"handled"}),O0=new s4(()=>{let L4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:T4}=this.widget.dependencies,i4=T4.mainThread?.id;return i4?this.getMessageScrollController(i4):null})();if(L4){let T4=Math.max(Math.floor(Q.size.height*0.4),10),i4=Q.size.height-T4;L4.animatePageUp(Math.floor(i4/2),100)}return"handled"}),_0=new s4(()=>{let L4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:T4}=this.widget.dependencies,i4=T4.mainThread?.id;return i4?this.getMessageScrollController(i4):null})();if(L4){let T4=Math.max(Math.floor(Q.size.height*0.4),10),i4=Q.size.height-T4;L4.animatePageDown(Math.floor(i4/2),100)}return"handled"}),e0=new s4(()=>{let L4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:T4}=this.widget.dependencies,i4=T4.mainThread?.id;return i4?this.getMessageScrollController(i4):null})();if(L4)L4.animateTo(0,100);return"handled"}),a0=new s4(()=>{let L4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:T4}=this.widget.dependencies,i4=T4.mainThread?.id;return i4?this.getMessageScrollController(i4):null})();if(L4)L4.animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),F1=new s4(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";if(this.handoffState.isInHandoffMode)return"ignored";if(this.isInQueueMode)return"ignored";let{threadState:z1}=this.widget.dependencies;if(!z1.mainThread?.messages.some((T4)=>T4.role==="user"||VF(T4)))return"ignored";return this.setState(()=>{this.isMessageViewInSelectionMode=!0}),"handled"}),a1=new s4((z1)=>{if(z1.direction==="previous")this.navigateHistoryPrevious();else this.navigateHistoryNext();return"handled"}),o1=new s4(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";return H$0().then(async(z1)=>{if(z1)await this.handleInsertImage(z1)}),"handled"}),m0=new Map([[Y4.ctrl("c"),new Ep],[Y4.ctrl("l"),new Ip],[Y4.ctrl("o"),new q$0],[Y4.ctrl("v"),new Np],[Y4.alt("s"),new HT],[Y4.ctrl("s"),new HT],[Y4.alt("p"),new Ap],[Y4.ctrl("r"),new Cp],[Y4.alt("t"),new Mp],[Y4.ctrl("t"),new Rp],[Y4.key("PageUp"),new V$0],[Y4.key("PageDown"),new K$0],[Y4.alt("k"),new z$0],[Y4.alt("j"),new G$0],[Y4.key("Home"),new F$0],[Y4.key("End"),new U$0],[Y4.key("Escape"),new Op],[Y4.ctrl("p"),new BT("previous")],[Y4.ctrl("n"),new BT("next")],[Y4.key("Tab"),new fp]]);if(m0.set(Y4.alt("d"),new jp),!a9())m0.set(Y4.key("ArrowUp"),new fp);if(!1)m0.set(Y4.alt("c"),new Lp);let t0=new s4(()=>{if(this.isShowingStandalonePalette())return"handled";return this.showCommandPalette(),"handled"}),A1=new s4(()=>{return this.toggleThreadPickerWorkspaceFilter(),"handled"}),$4=new s4(()=>{if(this.mysteriousMessage)this.handleShowMysteryModal();return"handled"}),D6=new Map([[Op,Q0],[Ip,K0],[HT,t],[jp,V0],[q$0,t0],[Np,o1],[Lp,i],[N20,n],[Mp,e],[Ap,Z0],[Rp,A1],[Cp,J0],[Ep,H0],[V$0,N0],[K$0,D0],[z$0,O0],[G$0,_0],[F$0,e0],[U$0,a0],[fp,F1],[BT,a1],[Pp,$4]]),m1=[q0];if(this.splashOrbExplosion){let z1=rg(this.getEffectiveAgentMode());m1.push(new id0({key:new $3(`splash-orb-explosion-${this.splashOrbExplosion.seq}`),originX:this.splashOrbExplosion.originX,originY:this.splashOrbExplosion.originY,sparkleColors:[z1,V.warning],onComplete:this.handleSplashOrbExplosionComplete}))}if(A||I)m1.push(new l1({child:new iV({message:this.threadInitializationMessage??"Loading thread..."})}));if(this.isShowingConsoleOverlay)m1.push(new jp0);if(this.isShowingHelp&&this.paletteConfig)m1.push(new vp0({commands:this.getPaletteCommands().getAllCommands(),submitOnEnter:this.submitOnEnter}));if(this.isShowingContextAnalyzeModal){let{configService:z1}=this.widget.dependencies,L4=this.widget.dependencies.threadState.mainThread,T4=this.contextAnalyzeDeps,i4=this.contextAnalyzeFromDTW;if(L4&&(T4||i4)){let E8=T4?{configService:z1,agentModeOverride:this.getEffectiveAgentMode(),buildSystemPromptDeps:T4}:null;m1.push(new Rp0({deps:E8,thread:L4,dtwAnalyze:i4??void 0,onDismiss:()=>{this.setState(()=>{this.isShowingContextAnalyzeModal=!1,this.contextAnalyzeDeps=null,this.contextAnalyzeFromDTW=null})}}))}else this.setState(()=>{this.isShowingContextAnalyzeModal=!1,this.contextAnalyzeDeps=null,this.contextAnalyzeFromDTW=null})}if(this.isShowingSkillListModal&&!this.isShowingPalette)Promise.all([this.widget.dependencies.skillService.getSkills(),this.widget.dependencies.skillService.getSkillErrors(),this.widget.dependencies.skillService.getSkillWarnings()]).then(([z1,L4,T4])=>{if(this.isShowingSkillListModal&&this.mounted)this.skillListData={skills:z1,errors:L4,warnings:T4},this.setState()}),m1.push(new rd0({skills:this.skillListData?.skills??[],errors:this.skillListData?.errors??[],warnings:this.skillListData?.warnings??[],cwd:process.cwd(),onDismiss:()=>{this.setState(()=>{this.isShowingSkillListModal=!1,this.skillListData=null})},onAddSkill:()=>{this.showCommandPalette({type:"standalone",commandId:"skill-add",onSubmit:()=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null,this.isShowingSkillListModal=!1,this.skillListData=null})},onCancel:()=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null})}})},onDocs:()=>{fX("https://ampcode.com/manual#agent-skills")},onInsertPrompt:(z1)=>{this.setState(()=>{this.isShowingSkillListModal=!1,this.skillListData=null,this.textController.text=z1})},onInvokeSkill:(z1)=>{this.widget.dependencies.activeThreadHandle.addPendingSkill({name:z1})}}));if(this.isShowingMCPStatusModal)m1.push(new sp0({servers:this.mcpServers,onDismiss:()=>{this.setState(()=>{this.isShowingMCPStatusModal=!1})}}));if(this.isShowingPromptHistoryPicker)m1.push(new nd0({entries:this.widget.dependencies.history.getAll(),currentCwd:process.cwd(),onAccept:(z1)=>{this.setState(()=>{this.isShowingPromptHistoryPicker=!1,this.textController.text=z1,this.textController.cursorPosition=z1.length})},onDismiss:()=>{this.setState(()=>{this.isShowingPromptHistoryPicker=!1})}}));if(this.isShowingMysteriousMessageModal&&this.mysteriousMessage)m1.push(new cd0({message:this.mysteriousMessage,onDestruct:this.handleDestructMysteriousMessage}));if(this.isShowingForkDeprecationModal)m1.push(new Tp0({onDismiss:this.dismissForkDeprecationModal}));for(let z1=0;z1<this.adModalStack.length;z1++){let L4=this.adModalStack[z1],T4=z1===this.adModalStack.length-1;if(L4==="adAction"&&this.adActionModal)m1.push(new ig0({key:new $3(`ad-action-modal-${T4?"top":"back"}`),title:this.adActionModal.title??"Failed to open browser",message:this.adActionModal.url,showCopyOption:this.adActionModal.showCopyOption,onSelect:async(i4)=>{let E8=this.adActionModal.url;if(i4==="copy")try{await l4.instance.tuiInstance.clipboard.writeText(E8),this.setState(()=>{this.displayMessage=new W$("Link copied to clipboard")})}catch(L7){j.error("Failed to copy to clipboard",{error:L7}),this.setState(()=>{this.displayMessage=Error("Failed to copy to clipboard")})}this.setState(()=>{this.adActionModal=null,this.removeAdModalFromStack("adAction")})}}));if(L4==="adInfo"&&this.adInfoModal)m1.push(new ng0({key:new $3(`ad-info-modal-${T4?"top":"back"}`),provider:this.adInfoModal.provider,onClose:()=>{this.setState(()=>{this.adInfoModal=null,this.removeAdModalFromStack("adInfo")})}}))}if(this.pendingMCPServers.length>0){let{mcpTrustHandler:z1}=this.widget.dependencies;m1.push(new tp0({servers:this.pendingMCPServers,onAlwaysTrust:z1.trustAlways.bind(z1),onTrustOnce:z1.trustOnce.bind(z1),onOpenSettings:this.handleMCPTrustOpenSettings,onDismiss:z1.deny.bind(z1)}))}if(this.pendingAuthLogin)m1.push(new ag0({manualURL:this.pendingAuthLogin.manualURL,isAuthenticating:this.pendingAuthLogin.isAuthenticating||this.pendingAuthLogin.isOpeningBrowser,errorMessage:this.pendingAuthLogin.errorMessage}));if(this.pendingOAuthRequest)m1.push(new ld0({request:this.pendingOAuthRequest,onDismiss:()=>{this.setState(()=>{this.pendingOAuthRequest=null})}}));if(this.pendingInputDialog){let z1=this.pendingInputDialog;m1.push(new xp0({options:z1.options,onSubmit:(L4)=>{this.setState(()=>{this.pendingInputDialog=null}),z1.resolve(L4)},onCancel:()=>{this.setState(()=>{this.pendingInputDialog=null}),z1.resolve(void 0)}}))}if(this.pendingConfirmDialog){let z1=this.pendingConfirmDialog;m1.push(new Mp0({options:z1.options,onConfirm:()=>{this.setState(()=>{this.pendingConfirmDialog=null}),z1.resolve(!0)},onCancel:()=>{this.setState(()=>{this.pendingConfirmDialog=null}),z1.resolve(!1)}}))}if(this.isShowingFileChangesOverlay)m1.push(new mg0({threadData:D}));if(this.isShowingContextDetailOverlay){let z1=this.threadCostInfo?.costBreakdownURL;m1.push(new Pp0({tokenUsage:f??void 0,costInfo:this.threadCostInfo,onDismiss:()=>{this.setState(()=>{this.isShowingContextDetailOverlay=!1})},onOpenCostBreakdown:z1?()=>{w8(J,z1)}:void 0}))}if(this.isShowingConfirmationOverlay)m1.push(new Ap0({details:this.confirmationOverlayContent}));if(this.imagePreview!==null)m1.push(new l1({child:new up0({image:this.imagePreview.image,imageIndex:this.imagePreview.index,onDismiss:this.handleImagePreviewDismiss,onRemove:this.handleImagePreviewRemove})}));if(this.fileImagePreviewPath!==null)m1.push(new l1({child:new Up({filePath:this.fileImagePreviewPath,onDismiss:this.handleFileImagePreviewDismiss})}));if(this.painterImagePreview!==null)m1.push(new l1({child:new Up({filePath:this.painterImagePreview.filePath,onDismiss:this.handlePainterImagePreviewDismiss})}));if(this.painterSaveDialog!==null)m1.push(new l1({child:new Up({filePath:this.painterSaveDialog.filePath,imageBlock:this.painterSaveDialog.image,onDismiss:this.handlePainterSaveDialogDismiss})}));if(this.skillPreview!==null){let z1=this.pendingSkills[this.skillPreview.skillIndex];if(z1)m1.push(new l1({child:new sd0({pendingSkill:z1,skill:this.cachedSkillForPreview,onDismiss:this.handleSkillPreviewDismiss,onRemove:this.skillPreview.onRemove})}))}let y4=this.getCommandPaletteContext(J);if(y4&&this.isShowingPalette&&this.paletteConfig)m1.push(new l1({child:new Ep0({commandContext:y4,mainThread:D.mainThread,commands:this.getPaletteCommands(),onDismiss:this.dismissPalette,showOptions:this.paletteShowOptions??void 0})}));if(this.isShowingIdePicker)m1.push(new yp0({onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection}));let b4=new i6({children:m1});if(this.isShowingJetBrainsInstaller)return new uL({child:new S9({actions:D6,child:new C2({shortcuts:m0,debugLabel:"jetbrains-installer-shortcuts",child:new op0({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});let H4=this.widget.dependencies.threadState.mainThread?.id,S5=1+(this.bottomGridUserHeight??5)+1,X6=!this.isShowingPalette&&!this.isShowingIdePicker;return new tT({switchToThread:(z1)=>this.switchToExistingThread(z1),child:new HG({threadViewStates:this.getThreadViewStatesSnapshot(),threadTitles:this.threadTitles,threadSummaries:this.threadsForPicker,child:new _p0({getThreadCluster:this.getCurrentThreadClusterForMinimap,parentThreadID:F0?.threadID,anchorLink:F0?this.parentThreadLinkAnchor:void 0,bottomOffset:S5,enabled:X6,child:new xT({onShowImagePreview:this.handleShowFileImagePreview,child:new fT({onShowImagePreview:this.handleShowPainterImagePreview,onShowSaveDialog:this.handleShowPainterSaveDialog,child:new rY({controller:this.toastController,child:new uL({child:new Ad0({getThreadCluster:this.getThreadClusterForMinimap,currentThreadID:H4,enabled:X6,child:new rH({enabled:X6,child:new f70({controller:this.toastController,child:new S9({actions:D6,child:new C2({shortcuts:m0,debugLabel:"main-app-shortcuts",child:b4})})})})})})})})})})})})}buildScrollableTodoList(J,Z,Q){return new cM4({todos:J,enabled:Z,controller:this.todoScrollController,appTheme:Q})}buildBottomWidget(J,Z,Q,Y,X,V,K,z,G,F,U){if(J)return new Cp0({error:J,options:{freeTierEnabled:this.freeTierStatus.canUseAmpFree},onResponse:this.handleEphemeralErrorResponse});if(Z){if(this.displayMessage)this.handleDisplayMessageDismiss();return new Ip0({confirmationRequest:Z,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new ep0({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let q=this.handoffState.isInHandoffMode||!this.widget.dependencies.activeThreadHandle.invokeBashTool?[]:N$0(Y),D=this.agentModeController?.isInRestrictedFreeMode()??!1,W=this.isTextfieldAndAutocompleteFocused&&!D&&!this.isShowingStandalonePalette()&&!this.handoffState.isGeneratingHandoff;if(W&&!this.hasReplayedEarlyInput){this.hasReplayedEarlyInput=!0;let t=l4.instance.tuiInstance.getEarlyInputText();if(t)this.textController.insertText(t)}let H=this.submitOnEnter?{character:"Enter"}:{character:"Enter",modifiers:{meta:!0}},B=new Ud({key:this.textFieldKey,controller:this.textController,triggers:[new YB],completionBuilder:this.getCompletionBuilder(),onSubmitted:(t)=>{this.onTextSubmitted(t).catch((V0)=>{this.handleSubmitFlowError(V0)})},submitKey:H,theme:Q,placeholder:D?"Amp Free is not enabled. Press Ctrl+S to switch modes.":void 0,enabled:W,shellPromptRules:q,focusNode:this.autocompleteFocusNode,autofocus:!this.isMessageViewInSelectionMode&&!this.isShowingStandalonePalette()&&!this.isShowingIdePicker&&!this.isShowingSkillListModal,clipboard:l4.instance.tuiInstance.clipboard,onCopy:this._handleTextCopy.bind(this),onInsertImage:this.handleInsertImage,imageAttachments:this.imageAttachments,popImage:this.handlePopImage,onImageClick:this.handleImageClick,previousThreadId:this.previousThreadIdForHint&&(X.mainThread?.messages.length??0)===0?this.previousThreadIdForHint:void 0,onPreviousThreadHintAccepted:()=>{let t=this.previousThreadIdForHint;if(t)this.setState(()=>{this.previousThreadIdForHint=null}),this.textController.text=`following: @${t} `},onDoubleAtTrigger:(t)=>{this.handleDoubleAtTrigger(t)},pendingSkills:this.pendingSkills,onClearPendingSkill:(t)=>{this.widget.dependencies.activeThreadHandle.removePendingSkill(t)},popSkill:()=>{let t=this.pendingSkills[this.pendingSkills.length-1];if(t)this.widget.dependencies.activeThreadHandle.removePendingSkill(t.name)},onSkillClick:this.handleSkillClick,topWidget:this.isShowingShortcutsHelp?new od0({submitOnEnter:this.submitOnEnter}):void 0}),w=X.mainThread?.queuedMessages??[],N=Array.isArray(V)&&V.length>0,O=Array.isArray(w)&&w.length>0,E=this.widget.dependencies.threadPool,L=E.isDTWMode?.()===!0,M=O?new ad0({queuedMessages:w,onInterruptQueuedMessage:L?(t)=>this.widget.dependencies.activeThreadHandle.interruptQueuedMessage?.(t):void 0}):void 0,A=N?this.buildScrollableTodoList(V,this.isTextfieldAndAutocompleteFocused&&!D,Y):void 0,I=[],P=null,_=0,S=F.capabilities.emojiWidth,y=L?E.getTransportConnectionState?.():void 0;if(L&&y!==void 0)I.push({child:new $0({text:new C(`(dtw: ${y})`,new h({color:Q.mutedForeground,dim:!0}))}),position:"top-left"});let m=this.currentShellModeStatus;if(m)I.push({child:new $0({text:new C(m==="hidden"?"shell mode (incognito)":"shell mode",new h({color:m==="hidden"?Y.app.shellModeHidden:Y.app.shellMode}))}),position:"top-left"});if(this.handoffState.isInHandoffMode){let t=new h({color:Y.app.handoffMode}),V0=this.handoffState.isGeneratingHandoff&&this.handoffState.spinner?new C("",void 0,[new C("handoff ",t),new C(this.handoffState.spinner.toBraille(),t)]):new C("handoff (submit a goal for the new thread)",t);if(I.push({child:new $0({text:V0}),position:"top-left"}),this.handoffState.isGeneratingHandoff){let N0=new h({color:Q.foreground,dim:!0});I.push({child:new $0({text:new C("",void 0,[new C("Esc",new h({color:Y.app.keybind})),new C(" to cancel",N0)])}),position:"bottom-left"}),_=p5("Esc to cancel",S)}}if(this.handoffState.countdownSeconds!==null){let t=new h({color:Q.foreground,dim:!0}),V0=`Auto-submitting in ${this.handoffState.countdownSeconds}s`,N0=this.handoffState.countdownSeconds<10?1:0;I.push({child:new i0({padding:C0.only({right:N0}),child:new $0({text:new C(V0,new h({color:Y.app.handoffMode}))})}),position:"bottom-left"}),I.push({child:new $0({text:new C("",void 0,[new C("type",new h({color:Y.app.keybind})),new C(" to edit",t)])}),position:"bottom-left"}),_=p5("Auto-submitting in 10s",S)+2+p5("type to edit",S)}if(this.isInQueueMode){let t=new h({color:Y.app.queueMode});I.push({child:new $0({text:new C("queue",t)}),position:"top-left"})}let b=this.handoffController?.getEmptyHandoffParentThreadID(this.widget.dependencies.threadState.mainThread)??null,k=F.capabilities.animationSupport,f=k==="disabled"?0:k==="slow"?30:60,p=this.getEffectiveAgentMode(),l=rg(p),x=null,r=null,c=!1,s=this.agentModeController?.getVisibleModes()??[];if(!m&&!this.isInQueueMode&&s.length>1){let t=this.previewThread,V0=this.agentModeController?.getMode(),N0=t?t.agentMode??this.getEffectiveAgentMode():this.handoffState.isGeneratingHandoff&&V0?V0:this.getEffectiveAgentMode(),D0=this.formatAgentModeLabel(N0),O0=N0==="smart"&&this.anthropicSpeed==="fast",_0=rb(this.openAISpeed,y6(this.authStatus)?this.authStatus.features:this.tuiContext.features),e0=uK(N0)&&_0==="fast",a0=O0?"+fast(6x$)":e0?"+fast(2x$)":void 0,F1=a0?`${D0}${a0}`:D0,a1=rg(N0),o1=t??this.widget.dependencies.threadState.mainThread,m0=o1?W3(o1)>0:!1,V1="top-right";if(t){x=p5(F1,S);let t0=a0?new C("",void 0,[new C(D0,new h({color:a1})),new C(a0,new h({color:Q.warning}))]):new C(D0,new h({color:a1}));I.push({child:new $0({text:t0}),position:"top-right"})}else{let t0=!m0&&!this.handoffState.isGeneratingHandoff,A1=this.handoffState.isGeneratingHandoff,$4=new h({color:a1,dim:A1}),D6=new $0({text:a0?new C("",void 0,[new C(D0,$4),new C(a0,new h({color:Q.warning,dim:A1}))]):new C(D0,$4)}),m1=p5(F1,S),y4=t0?new n1({child:D6,onClick:()=>this.toggleAgentMode(),cursor:"pointer"}):D6,b4=[];if(x=m1,N0==="deep"&&!m0&&!this.handoffState.isGeneratingHandoff&&this.deepModeEffortHintController.isVisibleOrFalling()){let X4=this.deepModeEffortHintController.getHintWidth(S),S5=3;c=this.deepModeEffortHintController.isVisible()&&this.deepModeEffortHintController.isShimmering();let X6=this.deepModeEffortHintController.isVisible()&&!c?new $0({text:this.deepModeEffortHintController.buildVisibleTextSpan(Q.foreground)}):new R0({width:X4});b4.push(X6,new R0({width:3})),x+=X4+3,r=Q.foreground}if(b4.push(y4),this.showSkillsCountInPromptBar){let X4=this.availableSkillCountReady?this.availableSkillCount:this.widget.dependencies.skillService.listInstalled().length,S5=this.skillWarningCount>0||this.skillErrorCount>0,z1=`${S5?"⚠ ":""}${X4} ${m4(X4,"skill")}`,L4=2,T4=p5(z1,S);x+=2+T4;let i4=new h({color:S5?Q.warning:Q.foreground,dim:!S5});b4.push(new R0({width:2}),new n1({child:new $0({text:new C(z1,i4)}),onClick:()=>{this.setState(()=>{this.isShowingSkillListModal=!0})},cursor:"pointer"}))}I.push({child:new U1({mainAxisSize:"min",children:b4}),position:"top-right"})}}let a=f>0&&this.agentModePulseSeq>0&&!m&&!this.isInQueueMode&&!b&&s.length>1,F0=[];if(a){let V0=p2(p)?.uiHints?.fasterAnimation?3:1,N0=(x??0)+1,D0=N0>0?2+N0:1,O0=new x6({top:0,left:1,right:D0,height:1,child:new rp0({color:l,backgroundColor:Q.background,trigger:this.agentModePulseSeq,fps:f,speed:V0,trail:5,leftOffset:0,direction:"right-to-left"})});F0.push(O0)}if(c&&r&&x!==null){let t=this.deepModeEffortHintController.buildShimmerOverlay(x,r);if(t)F0.push(t)}if(this.deepModeEffortHintController.isFalling()&&r&&x!==null){let t=this.deepModeEffortHintController.buildFallingOverlay(x,r);if(t)F0.push(t)}if(F0.length>0)P=new x6({top:0,left:0,right:0,bottom:0,child:new i6({children:F0})});if(b&&this.handoffState.countdownSeconds===null){let t=this.handoffState.isConfirmingAbortHandoff?" again to abort ":" to abort ";I.push({child:new $0({text:new C("",void 0,[new C("Esc",new h({color:Y.app.keybind})),new C(t,new h({color:Q.foreground,dim:!0})),new C("handoff",new h({color:Y.app.handoffMode}))])}),position:"bottom-left"}),_=p5(`Esc${t}handoff`,S)}if(!b&&this.previousThreadIdForHint&&(X.mainThread?.messages.length??0)===0&&this.textController.text.trim()==="")I.push({child:new $0({text:new C("",void 0,[new C("press ",new h({color:Q.foreground,dim:!0})),new C("enter",new h({color:Y.app.keybind})),new C(" to reference the previous thread",new h({color:Q.foreground,dim:!0}))])}),position:"bottom-left"}),_=p5("press enter to reference the previous thread",S);let q0=X.mainThread?.env?.initial.trees?.[0]?.uri,Q0;if(q0)Q0=K1.parse(q0).fsPath;else Q0=process.cwd();let H0=this.toHomeRelative(Q0),i=this.shorten(H0),n=_>0?F.size.width-_-6:F.size.width-4,e=this.buildDisplayText(i,this.currentGitBranch||void 0,n,S);I.push({child:new $0({text:new C(e,new h({color:Q.foreground,dim:!0}))}),position:"bottom-right"});let J0=this.previewThread,Z0=this.widget.dependencies.threadState.mainThread;if((Z0?W3(Z0)>0:!1)&&!m&&!this.handoffState.isInHandoffMode&&!J0){let t=[],V0=new h({color:Q.foreground,dim:!0}),N0=new C(" · ",V0);if(G){let a0=G.totalInputTokens/G.maxInputTokens,F1=Math.round(a0*100),a1=Math.max(0,Math.min(F1,100)),o1=E$0(a0,G.maxInputTokens),m0=V0;if(o1==="danger")m0=new h({color:Q.destructive});else if(o1==="warning")m0=new h({color:Q.warning});else if(o1==="recommendation")m0=new h({color:Y.app.recommendation});if(t.length>0)t.push(N0);if(G.maxInputTokens>=1000){let V1=Math.round(G.maxInputTokens/1000);t.push(new C(`${a1}% of ${V1}k`,m0))}else t.push(new C(`${a1}%`,m0))}if(U&&this.threadCostInfo){let a0=nC(this.threadCostInfo,{colors:{foreground:Q.foreground},dim:!0});if(a0.length>0){if(t.length>0)t.push(N0);t.push(...a0)}}let D0=X.viewState,O0=D0.state==="active"?D0.turnStartTime:void 0,_0=D0.state==="active"?D0.turnElapsedMs:void 0,e0=null;if(X.mainThread?.agentMode==="deep"){let a0=O0?Date.now()-O0:_0;if(a0!==void 0){let F1=ru1(a0);e0=new $0({text:new C(F1,V0)})}}if(t.length>0||e0){let a0=[];if(t.length>0){let F1=new $0({text:new C("",void 0,t)});a0.push(U?new n1({child:F1,onClick:this.showContextDetailOverlay,cursor:"pointer"}):F1)}if(e0){if(t.length>0)a0.push(new $0({text:new C(" · ",V0)}));a0.push(e0)}I.push({child:new U1({mainAxisSize:"min",children:a0}),position:"top-left"})}}return new og0({leftChild:new T1({child:B}),rightChild1:M,rightChild2:A,maxHeight:K,overlayTexts:I,overlayLayer:P,backgroundColor:Q.background,borderColor:D||!this.isTextfieldAndAutocompleteFocused||this.handoffState.isGeneratingHandoff?Q.border:void 0,hasBanner:z,userHeight:this.bottomGridUserHeight,onInitializeHeight:(t)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(t,K)})},onDrag:(t)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(t.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let V0=Math.floor(t.localPosition.y)-this.bottomGridDragStartY,N0=Math.max(4,this.bottomGridDragStartHeight-V0),D0=Math.min(N0,K),O0=Math.floor(D0);if(this.bottomGridUserHeight!==O0)this.setState(()=>{this.bottomGridUserHeight=O0})},onDragRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null},enableResize:!z})}}function dM4(J){return J.resolvedTokenUsage}class cM4 extends d0{props;constructor(J){super();this.props=J}createState(){return new lM4}}class lM4 extends p0{viewportHeight=1;scrollListenerAttached=!1;initState(){if(!this.scrollListenerAttached)this.widget.props.controller.addListener(()=>{this.updateViewportHeight()}),this.scrollListenerAttached=!0}build(J){let{todos:Z,controller:Q,appTheme:Y}=this.widget.props;return new U1({crossAxisAlignment:"stretch",children:[new T1({child:new j6({controller:Q,autofocus:!1,child:new Zc0({todos:Z})})}),new u8({controller:Q,thumbColor:Y.app.scrollbarThumb,trackColor:Y.app.scrollbarTrack,getScrollInfo:()=>{let{maxScrollExtent:X,offset:V}=Q,K=this.viewportHeight,z=X+K;return{totalContentHeight:Math.max(z,0),viewportHeight:Math.max(K,1),scrollOffset:Math.max(V,0)}}})]})}updateViewportHeight(){let J=this.getViewportHeight();if(J!==this.viewportHeight)this.viewportHeight=J}getViewportHeight(){let J=this.context.findRenderObject();if(!J)return this.viewportHeight;let Z=(Y,X=0)=>{if(Y&&"size"in Y&&"children"in Y){let V=Y.children||[];for(let K of V){if(K&&"size"in K){let G=K.size;if(typeof G?.height==="number"&&G.height>0)return G.height}let z=Z(K,X+1);if(z>0)return z}}return 0},Q=Z(J);if(Q>0)return Q;if("size"in J){let Y=J.size;if(typeof Y?.height==="number"&&Y.height>0)return Y.height}return this.viewportHeight}}class iM4 extends d1{props;constructor(J){super();this.props=J}build(J){return new n1({child:new R0({height:1}),cursor:E5.NS_RESIZE,onDrag:(Z)=>{if(this.props.userHeight===void 0){let Y=J.findRenderObject()?.size.height??0;if(Y>0){this.props.onInitializeHeight(Y);return}}this.props.onDrag(Z)},onRelease:this.props.onRelease})}}function aM4(J){let Z=J.split(`
7500
+ `).length,B=Math.max(Math.min(H,q),3);this._viewportHeight=B;let w=new a3({markdown:Q.content}),N=new c0({constraints:new M1({maxHeight:B}),child:new U1({crossAxisAlignment:"stretch",children:[new T1({child:new j6({controller:this._scrollController,autofocus:!1,child:w})}),new u8({controller:this._scrollController,thumbColor:X.app.scrollbarThumb,trackColor:X.app.scrollbarTrack,getScrollInfo:()=>{let O=this._scrollController.maxScrollExtent,E=this._scrollController.offset,L=this._viewportHeight,M=O+L;return{totalContentHeight:Math.max(M,0),viewportHeight:Math.max(L,1),scrollOffset:Math.max(E,0)}}})]})});D.push(N),D.push(new R0({height:1}))}}else D.push(new $0({text:new C("(Loading skill details...)",new h({color:Y.foreground,dim:!0,italic:!0}))})),D.push(new R0({height:1}));if(Z.arguments)D.push(new $0({text:new C("",void 0,[new C("Arguments: ",new h({color:Y.foreground,dim:!0})),new C(Z.arguments,new h({color:Y.foreground}))])})),D.push(new R0({height:1}));let W=new u0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new $0({text:new C("",void 0,[new C(Z.name,new h({bold:!0,color:Y.success,underline:!0}))])}),new R0({height:1}),...D,new c7({options:this.getOptions(),onSelect:this.handleSelect,autofocus:!0,showDismissalMessage:!1,enableMouseInteraction:!0})]});return new k4({onKey:(H)=>{if(H.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"},child:new l1({child:new LH(new c0({constraints:new M1(G,G,0,F),decoration:{color:Y.background,border:u1.all(new v1(Y.success,1,"rounded"))},padding:C0.symmetric(2,1),child:W}))})})}}function Ns5(J,Z){if(J===Z)return!0;let Q=Object.keys(J),Y=Object.keys(Z);if(Q.length!==Y.length)return!1;for(let X of Q){if(!(X in Z))return!1;if(!Object.is(J[X],Z[X]))return!1}return!0}class td0 extends d0{stableProps;arePropsEqual;constructor({key:J,stableProps:Z,arePropsEqual:Q}){super(J?{key:J}:{});this.stableProps=Z,this.arePropsEqual=Q??Ns5}createState(){return new jJ0}}class jJ0 extends p0{cachedChild=null;build(J){let{stableProps:Z,arePropsEqual:Q}=this.widget,Y=this.cachedChild;if(Y&&Q(Y.props,Z))return Y.widget;let X=this.widget.buildStableChild(Z);return this.cachedChild={props:Z,widget:X},X}dispose(){this.cachedChild=null}}class ed0 extends td0{constructor(J){super({stableProps:J})}createState(){return new xM4}buildStableChild(J){let{threadID:Z,...Q}=J;return new qd({...Q,key:Z?new $3(`message-view-${Z}`):void 0})}}class xM4 extends jJ0{build(J){return super.build(J)}}H1();function Os5(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/3600000),X=Math.floor(Y/24),V=Math.floor(X/7),K=Math.floor(X/30);if(Y<1)return"Just now";if(Y<24)return`${Y}h ago`;if(X<7)return`${X}d ago`;if(V<=4)return`${V}w ago`;return`${K}mo ago`}class $c0{threadHistoryService;constructor(J){this.threadHistoryService=J}async fetchThreadSummaries(J="",Z){try{let Q=await new Promise((Y)=>{let X=this.threadHistoryService.observeThreadList(Z).subscribe((V)=>{X.unsubscribe(),Y(V)})});return{ok:!0,threads:this.formatThreadSummaries(Q,J,Z)}}catch(Q){return{ok:!1,errorMsg:Q instanceof Error?Q.message:"An unexpected error occurred"}}}observeThreadSummaries(J="",Z={}){return this.threadHistoryService.observeHistory().pipe(D1((Q)=>this.formatThreadSummaries(Q,J,Z)))}formatThreadSummaries(J,Z,Q={}){return J.filter((X)=>{if(X.mainThreadID)return!1;if(!Q.includeArchived&&X.archived)return!1;if(!Z.trim())return!0;let V=X.title?.toLowerCase()||"untitled",K=X.id.toLowerCase(),z=Z.toLowerCase();return V.includes(z)||K.includes(z)}).map((X)=>{let V=new Date(X.userLastInteractedAt),K=Os5(V),z=X.id.slice(-8),G=X.env?.initial.trees?.[0]?.uri;return{id:X.id,title:X.title||"Untitled",updatedAt:new Date(X.userLastInteractedAt).toISOString(),description:{timeAgo:K,title:X.title||"Untitled",shortThreadID:z},diffStats:X.summaryStats?.diffStats,workspaceURI:G,relationships:X.relationships,agentMode:X.agentMode,details:{messageCount:X.summaryStats?.messageCount},archived:X.archived}})}}h0();_4();_4();function fM4(J){let Z=fI1(J),Q=Array.from(Z.entries()).map(([V,K])=>({path:V,diffStats:K})),X=K2(J)?.totalInputTokens??0;return{filesAffected:Q,totalTokens:X}}class Jc0{currentId=null;current=null;statsCache=new Map;subscribeTimer=null;subscription=null;listeners=[];threadService=null;scrollController=new Y5;constructor(){}setThreadService(J){this.threadService=J}async select(J){if(!this.threadService){j.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId===J)return;this.cancelTimerAndSubscription(),this.currentId=J;let Z=await this.threadService.get(J);if(Z){if(this.currentId===J)this.current=Z,this.notifyListeners()}this.subscribeTimer=setTimeout(()=>{this.subscribeLive(J)},1000)}clear(){this.cancelTimerAndSubscription(),this.currentId=null,this.current=null,this.notifyListeners()}addListener(J){this.listeners.push(J)}removeListener(J){let Z=this.listeners.indexOf(J);if(Z!==-1)this.listeners.splice(Z,1)}getCurrentThread(){return this.current}getCurrentStats(){if(!this.current)return null;let J=this.statsCache.get(this.current.id);if(J&&J.version===this.current.v)return J.stats;let Z=fM4(this.current);return this.statsCache.set(this.current.id,{stats:Z,version:this.current.v}),Z}clearStatsCache(){this.statsCache.clear()}dispose(){this.cancelTimerAndSubscription(),this.clearStatsCache(),this.scrollController.dispose(),this.listeners=[]}subscribeLive(J){if(!this.threadService){j.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId!==J)return;this.subscription=this.threadService.observePatches(J).pipe(Qr()).subscribe((Z)=>{if(this.currentId===J)this.current=Z,this.notifyListeners()})}cancelTimerAndSubscription(){if(this.subscribeTimer)clearTimeout(this.subscribeTimer),this.subscribeTimer=null;if(this.subscription)this.subscription.unsubscribe(),this.subscription=null}notifyListeners(){for(let J of this.listeners)J(this.current)}}class Zc0 extends d0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new bM4}}class bM4 extends p0{build(J){let Q=f0.of(J).colors,{todos:Y,title:X="TODOs"}=this.widget.props;if(!Array.isArray(Y)||Y.length===0)return new R0({width:0,height:0});let V=Y.map((K)=>this.buildTodoItem(K,Q));return new c0({child:new i0({padding:C0.symmetric(1,0),child:new u0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new $0({text:new C(X,new h({bold:!0,color:Q.foreground}))}),...V]})})})}buildTodoItem(J,Z){let Q=this.getStatusIcon(J.status),Y=J.status==="completed",X=new h({bold:J.status==="in-progress",color:Z.foreground,dim:Y}),V=new h({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Z.foreground,dim:Y});return new U1({crossAxisAlignment:"start",children:[new $0({text:new C(Q,X)}),new R0({width:1}),new T1({child:new $0({text:new C(J.content,V)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}function hM4(J,Z){switch(J){case"update-available":return[new C("A newer Amp is available. Run ",new h({color:Z.foreground,dim:!0})),new C("amp update",new h({color:Z.warning}))];case"update-available-unrecognized-path":return[new C("A newer Amp is available.",new h({color:Z.foreground,dim:!0}))];case"update-available-brew":return[new C("A newer Amp is available. Run ",new h({color:Z.foreground,dim:!0})),new C("brew upgrade ampcode",new h({color:Z.warning}))];case"updated":return null;case"updated-with-warning":return[new C("Update complete, run ",new h({color:Z.foreground,dim:!0})),new C("amp update",new h({color:Z.warning})),new C(" to see warnings",new h({color:Z.foreground,dim:!0}))];case"update-error":return[new C("Update failed, run ",new h({color:Z.foreground,dim:!0})),new C("amp update",new h({color:Z.warning})),new C(" to see warnings",new h({color:Z.foreground,dim:!0}))];case"hidden":return null}}async function Ps5(J){return new Promise((Z)=>{Es5("git",["branch","--show-current"],{cwd:J},(Q,Y)=>{if(Q){Z(null);return}let X=Y.trim();Z(X||null)})})}function pM4(J){return"interrupt"in J&&J.interrupt===!0}class Qc0 extends d0{dependencies;constructor(J){super();this.dependencies=J}createState(){return new RJ0}}class RJ0 extends p0{get tuiContext(){return DZ.require(this.context)}debugThreadViewState=process.env.AMP_DEBUG_THREAD_VIEW==="1";lastThreadStatusDebugSignature=null;themeColors=null;themeApp=null;ideStatus=null;randomAd=null;adSubscription=null;adsDisabledBySetting=!1;adReadinessTimeout=null;threadLoadSubscription=null;lastAdImpressionId=null;lastUserInteractionTime=Date.now();hasShownWinPasteHookRecoveryWarning=!1;winPasteHookImageUnsubscribe=null;winPasteHookStateUnsubscribe=null;isConfirmingExit=!1;isExiting=!1;isConfirmingClearInput=!1;isConfirmingCancelProcessing=!1;statusMessage=null;statusMessageTimer=null;isShowingHelp=!1;isShowingShortcutsHelp=!1;isShowingContextAnalyzeModal=!1;isShowingSkillListModal=!1;skillListData=null;shortcutsHintUsed=!1;deepReasoningEffort="high";anthropicSpeed=void 0;openAISpeed=void 0;deepReasoningEffortSubscription=null;anthropicSpeedSubscription=null;openAISpeedSubscription=null;sessionState=bC;isShowingConsoleOverlay=!1;isShowingMCPStatusModal=!1;isShowingConfirmationOverlay=!1;isShowingFileChangesOverlay=!1;isShowingContextDetailOverlay=!1;threadCostInfo=void 0;threadCostInfoThreadID=void 0;lastInferenceState=void 0;elapsedTimeTimer=null;confirmationOverlayContent="";exitConfirmTimeout=null;clearInputConfirmTimeout=null;cancelProcessingConfirmTimeout=null;historyIndex=-1;historyDraft=null;bashInvocations=[];currentTitle=void 0;currentShellModeStatus=void 0;imageAttachments=[];pendingSkills=[];pendingSkillsSubscription=null;skillListSubscription=null;skillWarningsSubscription=null;skillErrorsSubscription=null;availableSkillCount=0;availableSkillCountReady=!1;showSkillsCountInPromptBar=!0;showSkillsCountInPromptBarSubscription=null;skillWarningCount=0;skillErrorCount=0;pendingApprovals=[];pendingApprovalsSubscription=null;submitOnEnter=!0;submitOnEnterSubscription=null;displayMessage=null;executingCommand=null;isShowingJetBrainsInstaller=!1;isShowingIdePicker=!1;isShowingPalette=!1;isShowingPromptHistoryPicker=!1;paletteShowOptions=null;paletteOnThreadMentionSelected=null;threadsForPicker=[];parentThreadTitles=new Map;parentThreadTitleLoadsInFlight=new Set;clustersForPicker=[];isLoadingThreads=!1;threadPreviewController=new Jc0;previewThread=null;todoScrollController=(()=>{let J=new Y5;return J.followMode=!1,J})();contextAnalyzeDeps=null;contextAnalyzeFromDTW=null;openContextAnalyzeModal=()=>{if(this.widget.dependencies.threadPool.isDTWMode?.()){let J=this.widget.dependencies.threadState.mainThread;if(!J)return;this.contextAnalyzeDeps=null,this.contextAnalyzeFromDTW=(Z)=>g30({ampURL:this.tuiContext.ampURL,configService:this.widget.dependencies.configService,threadID:J.id,workerURL:process.env.AMP_WORKER_URL,signal:Z}),this.setState(()=>{this.isShowingContextAnalyzeModal=!0});return}this.contextAnalyzeFromDTW=null,this.widget.dependencies.createSystemPromptDeps().then((J)=>{this.contextAnalyzeDeps=J,this.setState(()=>{this.isShowingContextAnalyzeModal=!0})})};filterThreadPickerByWorkspace=!0;currentGitBranch=null;messageViewFocusNode=new r4({debugLabel:"MessageViewFocus"});autocompleteFocusNode=new r4({debugLabel:"AutocompleteFocus"});autocompleteFocusNodeListener=null;isTextfieldAndAutocompleteFocused=!1;hasReplayedEarlyInput=!1;submitDisabledHint=null;submitDisabledHintTimer=null;showImageUnsupportedHint=!1;imageUnsupportedHintTimer=null;imagePreview=null;fileImagePreviewPath=null;painterImagePreview=null;painterSaveDialog=null;messageViewController=new AJ0;previewMessageViewController=new AJ0;handleMainMessageViewCopy=(J,Z)=>{this._handleTextCopy(J,Z)};handleMainMessageViewDismissFocus=()=>{if(this.setState(()=>{this.isMessageViewInSelectionMode=!1,this.imagePreview=null}),!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()};messageViewControllerUnsubscribe=null;lastEditingMessageOrdinal=null;skillPreview=null;cachedSkillForPreview=null;adActionModal=null;adInfoModal=null;adModalStack=[];newsFeedReader=null;newsFeedEntries=[];newsFeedSubscription=null;bottomGridUserHeight=void 0;bottomGridDragStartY=null;bottomGridDragStartHeight=null;parentThreadLinkAnchor=new hp;previousThreadIdForHint=null;handoffController=null;handoffState={isInHandoffMode:!1,isGeneratingHandoff:!1,isConfirmingAbortHandoff:!1,pendingHandoffPrompt:null,spinner:null,countdownSeconds:null};isInQueueMode=!1;pendingMCPServers=[];mcpTrustSubscription=null;pendingOAuthRequest=null;pendingAuthLogin=null;authStatus="pending";authStatusSubscription=null;authModalKeyInterceptorUnsubscribe=null;isCreatingAuthLoginSession=!1;queuedPromptAfterAuth=null;pendingInputDialog=null;pendingConfirmDialog=null;mcpServers=[];mcpServersSubscription=null;pluginInfos=[];pluginInfosSubscription=null;agentModeController=null;freeTierStatus={canUseAmpFree:!1,isDailyGrantEnabled:!1};agentModePulseSeq=0;lastEffectiveAgentMode="smart";deepModeEffortHintController=new vg0({getDeepReasoningEffort:()=>this.deepReasoningEffort,getEffectiveAgentMode:()=>this.getEffectiveAgentMode(),canShowHintInCurrentThread:()=>{let J=this.widget.dependencies.threadState.mainThread;return!!J&&W3(J)===0},requestRender:()=>{if(!this.mounted)return;this.setState(()=>{})},isMounted:()=>this.mounted});updateState="hidden";updateServiceSubscription=null;toastController=new x70;isMessageViewInSelectionMode=!1;isShowingForkDeprecationModal=!1;mysteriousMessage=null;isShowingMysteriousMessageModal=!1;mysteriousMessageSubscription=null;mysterySequenceManager=null;mysterySequenceProgress=null;mysteryKeyInterceptorUnsubscribe=null;static MYSTERY_SEQUENCE=["ctrl+x","y","z"];splashOrbExplosion=null;splashOrbExplosionSeq=0;freeTierStatusSubscription=null;allConnectedThreadActivityStatusesSubscription=null;threadInitializationStatusSubscription=null;allConnectedThreadActivityStatuses={};threadInitializationMessage=null;threadTitlesSubscription=null;threadTitles={};pendingNavigationSubscription=null;pendingNavigationInFlightThreadID=null;pluginCommands=[];pluginCommandsSubscription=null;async initNewsFeed(){let J=async(Q)=>{return p3(Q,void 0,this.widget.dependencies.configService)},Z=Bm1();this.newsFeedReader=new Tg0(Z,J,"/news.rss"),this.newsFeedSubscription=this.newsFeedReader.stream().subscribe({next:(Q)=>{if(Q.length>0)this.setState(()=>{this.newsFeedEntries=[...Q,...this.newsFeedEntries]})},error:(Q)=>{j.error("News feed error:",Q)}})}bringAdModalToFront(J){this.adModalStack=this.adModalStack.filter((Z)=>Z!==J),this.adModalStack.push(J)}removeAdModalFromStack(J){this.adModalStack=this.adModalStack.filter((Z)=>Z!==J)}getTopAdModal(){for(let J=this.adModalStack.length-1;J>=0;J--){let Z=this.adModalStack[J];if(Z==="adAction"&&this.adActionModal)return Z;if(Z==="adInfo"&&this.adInfoModal)return Z}return null}dismissTopAdModal(){let J=this.getTopAdModal();if(!J)return!1;return this.setState(()=>{if(J==="adAction")this.adActionModal=null;if(J==="adInfo")this.adInfoModal=null;this.removeAdModalFromStack(J)}),!0}navigateBack=async()=>{await this.widget.dependencies.threadPool.navigateBack(),this.agentModeController?.setMode(null),this.onThreadSwitch();let J=this.widget.dependencies.threadState.mainThread?.id;if(J)this.persistLastThreadId(J)};navigateForward=async()=>{await this.widget.dependencies.threadPool.navigateForward(),this.agentModeController?.setMode(null),this.onThreadSwitch();let J=this.widget.dependencies.threadState.mainThread?.id;if(J)this.persistLastThreadId(J)};onThreadSwitch(){this.handoffController?.resetUIState(),this.exitQueueMode(),this.isMessageViewInSelectionMode=!1,this.imagePreview=null}canInterruptQueuedInference(){let{activeThreadHandle:J,threadPool:Z,threadState:Q}=this.widget.dependencies,Y=Q.mainThread?.queuedMessages?.some((X)=>!pM4(X))??!1;return Z.queueOnSubmitByDefault&&Boolean(J.interruptQueuedMessage)&&Y&&gO(Q.viewState)}interruptNextQueuedMessage=async()=>{let{activeThreadHandle:J,threadState:Z}=this.widget.dependencies,Q=Z.mainThread?.queuedMessages?.find((Y)=>!pM4(Y))?.id;if(!Q||!J.interruptQueuedMessage)return;await J.interruptQueuedMessage(Q)};startAndSwitchToNewThread=async()=>{let J=this.widget.dependencies.threadState.mainThread?.id;await this.widget.dependencies.threadPool.createThread(),this.setState(()=>{this.onThreadSwitch(),this.previousThreadIdForHint=J??null})};canChangeAgentModeInPromptEditor(){return(this.messageViewController.editingMessageOrdinal===0||this.handoffState.isInHandoffMode)&&!this.handoffState.isGeneratingHandoff}getEffectiveAgentMode(){if(!this.agentModeController)return"smart";return(this.canChangeAgentModeInPromptEditor()?this.agentModeController.getMode():null)??this.agentModeController.getEffectiveMode()}isProcessing(){let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return!1;if(J.viewState.state!=="active")return!1;if(J.viewState.interactionState==="handoff")return!0;if(Boolean(J.viewState.inferenceState==="running"))return!0;return J.items.filter((Y)=>Y.type==="toolResult").filter((Y)=>Y.toolResult.run.status==="in-progress"||Y.toolResult.run.status==="queued").length>0}showSubmitDisabledHint(J){if(this.submitDisabledHintTimer)clearTimeout(this.submitDisabledHintTimer);this.setState(()=>{this.submitDisabledHint=J}),this.submitDisabledHintTimer=setTimeout(()=>{this.setState(()=>{this.submitDisabledHint=null}),this.submitDisabledHintTimer=null},3000)}getUIHint(){let J=this.themeColors?.colorScheme;if(!J)return null;let Z=this.themeApp;if(!Z)return null;if(this.submitDisabledHint)return new C(this.submitDisabledHint,new h({color:J.foreground,dim:!0}));if(this.isExiting)return new C("Exiting...",new h({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new C("",void 0,[new C("Ctrl+C",new h({color:Z.keybind})),new C(" again to exit",new h({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new C("",void 0,[new C("Esc",new h({color:Z.keybind})),new C(" again to clear input",new h({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new C("",void 0,[new C("Escape",new h({color:Z.keybind})),new C(" to close help",new h({color:J.foreground,dim:!0}))]);if(this.showImageUnsupportedHint){let U=this.getEffectiveAgentMode(),q=rg(U);return new C("",void 0,[new C("Images aren't supported in ",new h({color:J.warning,dim:!1})),new C(U,new h({color:q})),new C(" mode.",new h({color:J.warning,dim:!1}))])}if(this.isProcessing()||this.bashInvocations.length>0){if(this.isConfirmingCancelProcessing)return new C("",void 0,[new C("Esc",new h({color:Z.keybind})),new C(" again to cancel",new h({color:J.foreground,dim:!0}))]);if(this.canInterruptQueuedInference())return new C("",void 0,[new C("Enter",new h({color:Z.keybind})),new C(" to interject",new h({color:J.foreground,dim:!0}))]);return new C("",void 0,[new C("Esc",new h({color:Z.keybind})),new C(" to cancel",new h({color:J.foreground,dim:!0}))])}let{threadState:Q}=this.widget.dependencies;if(this.statusMessage){if(this.debugThreadViewState)j.info("[tui-ui] footer status override",{source:"statusMessage",statusMessage:this.statusMessage,inferenceState:Q.viewState.state==="active"?Q.viewState.inferenceState:void 0});return new C(this.statusMessage,new h({color:J.foreground,dim:!0}))}let Y=hM4(this.updateState,J);if(Y){if(this.debugThreadViewState)j.info("[tui-ui] footer status override",{source:"updateState",inferenceState:Q.viewState.state==="active"?Q.viewState.inferenceState:void 0});return new C("",void 0,Y)}let X=this.getCurrentConfirmation(),V=dM4(Q),K=this.widget.dependencies.threadPool.getCompactionStatus?.(),z=new pp({threadViewState:Q.viewState,tokenUsage:V,thread:Q.mainThread??void 0,compactionState:K?.compactionState??"idle",waitingForConfirmation:!!X,showingEphemeralError:Boolean(Q.viewState.state==="active"&&Q.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null,executingCommandNoun:this.executingCommand?.noun??null,executingCommandVerb:this.executingCommand?.verb??null,executingCommandMessage:this.executingCommand?.statusMessage??null}),G=gp(z);if(this.debugThreadViewState){let U=JSON.stringify({inferenceState:Q.viewState.state==="active"?Q.viewState.inferenceState:void 0,interactionState:Q.viewState.interactionState,statusType:G.type});if(U!==this.lastThreadStatusDebugSignature)this.lastThreadStatusDebugSignature=U,j.info("[tui-ui] footer thread status",JSON.parse(U))}let F=!this.shortcutsHintUsed||this.sessionState.launchCount<10;if(G.type==="none"&&!this.isShowingShortcutsHelp&&this.textController.text===""&&F)return new C("",void 0,[new C("?",new h({color:Z.keybind})),new C(" for shortcuts",new h({color:J.foreground,dim:!0}))]);return null}getParentThreadInfo(){let J=this.previewThread??this.widget.dependencies.threadState.mainThread;if(!J)return null;let Z=ck(J).filter((K)=>K.type==="fork"||K.type==="handoff");if(Z.length===0)return null;let Q=Z[0],Y=Q.threadID,X=this.threadsForPicker.find((K)=>K.id===Y);if(!X?.title)this.ensureParentThreadTitleLoaded(Y);let V=X?.title??this.parentThreadTitles.get(Y)??Y.slice(-8);return{type:Q.type==="handoff"?"handoff":"fork",title:V,threadID:Y}}ensureParentThreadTitleLoaded(J){if(this.parentThreadTitles.has(J)||this.parentThreadTitleLoadsInFlight.has(J))return;this.parentThreadTitleLoadsInFlight.add(J),this.widget.dependencies.threadService.getPrimitiveProperty(J,"title").then((Z)=>{if(!this.mounted||!Z)return;this.setState(()=>{this.parentThreadTitles.set(J,Z)})}).catch((Z)=>{j.debug("Failed to load parent thread title",{threadID:J,error:Z})}).finally(()=>{this.parentThreadTitleLoadsInFlight.delete(J)})}getThreadClusterForMinimap=(J)=>{let Z=this.clustersForPicker.find((Q)=>Q.threads.some((Y)=>Y.id===J));if(!Z||Z.threads.length<2)return null;return Z.threads.map((Q)=>({id:Q.id,title:Q.title,parentID:Q.parentID,updatedAt:Q.updatedAt,isActive:this.isThreadActivelyWorking(Q.id)}))};getCurrentThreadClusterForMinimap=()=>{let J=this.previewThread??this.widget.dependencies.threadState.mainThread;if(!J)return null;return this.getThreadClusterForMinimap(J.id)};enrichClustersWithActiveState=(J)=>{return J.map((Z)=>({...Z,threads:Z.threads.map((Q)=>({...Q,isActive:this.isThreadActivelyWorking(Q.id)}))}))};areRecordValuesEqual(J,Z){if(J===Z)return!0;let Q=Object.entries(J),Y=Object.entries(Z);if(Q.length!==Y.length)return!1;for(let[X,V]of Q){if(!Object.hasOwn(Z,X))return!1;if(!Object.is(V,Z[X]))return!1}return!0}getThreadViewStatesSnapshot(){let J={...this.allConnectedThreadActivityStatuses},Z=this.widget.dependencies.threadState.mainThread;if(Z)J[Z.id]=this.widget.dependencies.threadState.viewState;return J}isThreadActivelyWorking(J){return gO(this.allConnectedThreadActivityStatuses[J])}isTranscriptEmpty(){let{threadState:J}=this.widget.dependencies;return J.items.length===0}isStartupThreadLoading(){if(!this.tuiContext.startupThreadID)return!1;let{threadPool:J}=this.widget.dependencies;return J.hasPendingInitialization?.()===!0}handleMessageRestoreSubmit=async(J)=>{let{threadState:Z,activeThreadHandle:Q}=this.widget.dependencies;if(!Z.mainThread?.id)return;let X=Z.mainThread?.messages.findIndex((V)=>V===J);if(X===void 0||X===-1)return;try{this.cancelBashInvocations(),await Q.cancelTurn(),await Q.restoreTo(X),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(V){j.error("Failed to edit message:",V)}};showForkDeprecationMessage=()=>{this.setState(()=>{this.isShowingForkDeprecationModal=!0})};dismissForkDeprecationModal=()=>{this.setState(()=>{this.isShowingForkDeprecationModal=!1})};handleMessageEditSubmit=async(J,Z,Q)=>{let{threadState:Y,activeThreadHandle:X}=this.widget.dependencies,V=Y.mainThread;if(!V)return;let K=V.messages.findIndex((F)=>F.messageId!==void 0&&F.messageId===J.messageId);if(K===-1)return;let z=K===0,G=z?this.agentModeController?.getMode()??V.agentMode??this.getEffectiveAgentMode():V.agentMode;if(this.shouldRequireAuthForPromptSubmit()){this.showSubmitDisabledHint("Sign in required before editing and resubmitting messages"),this.ensureAuthLoginSession();return}try{this.cancelBashInvocations(),await X.cancelTurn(),this.widget.dependencies.history.add(Z,process.cwd());let F=aH(Z);if(F&&X.invokeBashTool)await X.restoreTo(K),this.invokeBashCommand(F.cmd,{visibility:F.visibility});else{let U=[{type:"text",text:Z}];if(Q.length>0)U.push(...Q);let q=G;if(V.agentMode&&!z&&q!==V.agentMode){j.error(`Cannot edit message: This thread uses ${V.agentMode} mode. To change mode, create a new thread.`);return}await X.sendMessage({content:U,agentMode:q,editIndex:K})}this.scrollMessageViewToBottom()}catch(F){j.error("Failed to edit message:",F)}};getAffectedFiles=async(J)=>{let{activeThreadHandle:Z,threadState:Q}=this.widget.dependencies;try{let Y=Q.mainThread;if(!Y)return[];let X=Y.messages.findIndex((K)=>K===J);if(X===-1)return[];return(await Z.getFilesAffectedByTruncation(X)).map(b9)}catch(Y){return j.error("Failed to get affected files:",Y),[]}};textController=new i7;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new Y5);return this.messageScrollControllers.get(J)}scrollMessageViewToBottom(){let{threadState:J}=this.widget.dependencies,Z=J.mainThread?.id;if(!Z)return;this.getMessageScrollController(Z).scrollToBottom()}_handleSelectionChanged=(J)=>{this.setState(()=>{})};updateTerminalTitle(){let{threadState:J}=this.widget.dependencies,Z=J.mainThread?.title;if(Z!==this.currentTitle){this.currentTitle=Z;let Q=process.cwd().replace(process.env.HOME||"","~"),Y=Z?`amp - ${Z} - ${Q}`:"";process.stdout.write(B90(Y))}}_handleTextCopy(J,Z){if(J&&J.length>0){let Q=Z?"Selection copied to clipboard":"Failed to copy selection to clipboard",Y=Z?"success":"error";this.toastController.show(Q,Y,2000)}}textFieldKey=new $3("text-field");ideStatusSubscription=null;ideMessageSubscription=null;ideAppendToPromptSubscription=null;paletteCommands;paletteConfig;completionBuilder=null;textChangeListener=()=>{let J=this.textController.text;if(J==="")this.textController.resetScrollOffset();if(J!=="")this.deepModeEffortHintController.dismissForInteraction();if(this.handoffState.countdownSeconds!==null)this.handoffController?.stopCountdown();if(J==="/"&&!this.handoffState.isGeneratingHandoff){this.showCommandPalette(),this.textController.clear(),this.toastController.show("Use [[Ctrl-O]] to open the command palette","warning");return}let Z=aH(J),Q=J===""&&this.bottomGridUserHeight!==void 0,Y=this.handoffState.isInHandoffMode||!this.widget.dependencies.activeThreadHandle.invokeBashTool?void 0:Z?.visibility;this.setState(()=>{if(this.currentShellModeStatus=Y,Q)this.bottomGridUserHeight=void 0})};navigateHistoryPrevious=()=>{let J=this.widget.dependencies.history.previous();if(J!==null){if(this.historyIndex===-1)this.historyDraft=this.textController.text;this.historyIndex++,this.textController.text=J,this.textController.moveCursorToStart()}};navigateHistoryNext=()=>{let J=this.widget.dependencies.history.next();if(J!==null)this.historyIndex--,this.textController.text=J,this.textController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.textController.text=this.historyDraft||"",this.textController.moveCursorToEnd(),this.historyDraft=null};resetHistory=()=>{this.widget.dependencies.history.reset(),this.historyIndex=-1,this.historyDraft=null};openJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!0})};dismissJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!1})};openIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!0})};dismissIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!1}),H6.instance.addPostFrameCallback(()=>{this.autocompleteFocusNode.requestFocus()})};handleIdeSelection=async(J,Z)=>{let Q=this.widget.dependencies.ideClient.getSelectedConfig();if(Q&&this.isSameIdeConfig(Q,J)){this.dismissIdePicker();return}try{await this.connectToSelectedIde(J,Z)}catch(Y){let X=Y instanceof Error?Y.message:String(Y);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${X}`)})}this.widget.dependencies.ideClient.selectConfig(J),this.dismissIdePicker()};isSameIdeConfig(J,Z){if(J.connection!==Z.connection||J.ideName!==Z.ideName||J.pid!==Z.pid||J.port!==Z.port||J.authToken!==Z.authToken||J.workspaceId!==Z.workspaceId)return!1;if(J.workspaceFolders.length!==Z.workspaceFolders.length)return!1;return J.workspaceFolders.every((Q)=>Z.workspaceFolders.includes(Q))}async connectToSelectedIde(J,Z){await this.widget.dependencies.ideClient.start(J,!0,Z)}previewControllerListener=(J)=>{this.setState(()=>{this.previewThread=J})};showStandaloneThreadPicker=()=>{this.showCommandPalette({type:"standalone",commandId:"continue",onSubmit:()=>{this.threadPreviewController.clear(),this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null}),H6.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette)this.autocompleteFocusNode.requestFocus()})},onCancel:()=>{this.exitApplication()}})};toggleThreadPickerWorkspaceFilter=()=>{this.setState(()=>{this.filterThreadPickerByWorkspace=!this.filterThreadPickerByWorkspace})};handleDoubleAtTrigger=(J)=>{let{text:Z,cursorPosition:Q}=J,X=Z.slice(0,Q).lastIndexOf("@@"),V=J!==this.textController;if(j.info("[handleDoubleAtTrigger] called",{isEditingPreviousMessage:V,text:Z,cursor:Q,atAtIndex:X}),V)this.setState(()=>{this.paletteOnThreadMentionSelected=(K)=>{let z=this.messageViewController.editingController;if(!z){j.warn("[paletteOnThreadMentionSelected] no editing controller found");return}this.insertThreadMention(z,K)}});else this.setState(()=>{this.paletteOnThreadMentionSelected=null});this.showCommandPalette({type:"standalone",commandId:"mention-thread",onBeforeExecute:V?void 0:()=>{if(X!==-1){let K=J.text,z=K.slice(0,X)+K.slice(X+2);J.text=z,J.cursorPosition=X}},onSubmit:()=>{this.setState(()=>{this.paletteOnThreadMentionSelected=null}),this.dismissPalette()},onCancel:()=>{this.setState(()=>{this.paletteOnThreadMentionSelected=null}),this.dismissPalette()}})};insertThreadMention(J,Z){let{text:Q,cursorPosition:Y}=J,V=Q.slice(0,Y).lastIndexOf("@@");if(V!==-1){let K=Q.slice(Y),z=K.length===0,G=`@${Z}${z?" ":""}`,F=Q.slice(0,V)+G+K,U=V+G.length;J.text=F,J.cursorPosition=U}else J.insertText(`@${Z} `)}showCommandPalette(J){if(this.handoffState.isGeneratingHandoff)return;let Z=!this.isShowingPalette;if(this.setState(()=>{if(this.isShowingPalette=Z,this.paletteShowOptions=Z?J??null:null,!Z)this.threadsForPicker=[],this.clustersForPicker=[],this.isLoadingThreads=!1}),Z)this.loadThreadsForPicker();else this.unloadThreadsForPicker()}isShowingStandalonePalette(){return this.isShowingPalette&&this.paletteShowOptions?.type==="standalone"}getPaletteCommands(){if(!this.paletteCommands){if(!this.paletteConfig)throw Error("Config not yet available");this.paletteCommands=new Np0(this.widget.dependencies.configService,(J)=>{this.setState(()=>{this.executingCommand=J})},()=>{this.setState(()=>{this.executingCommand=null})},this.paletteConfig)}return this.paletteCommands}getCompletionBuilder(){if(!this.completionBuilder)this.completionBuilder=new Lp0(this.widget.dependencies.fuzzyServer);return this.completionBuilder}unloadThreadsForPicker(){if(this.threadLoadSubscription)this.threadLoadSubscription.unsubscribe(),this.threadLoadSubscription=null;this.threadPreviewController.clearStatsCache(),this.widget.dependencies.threadHistoryService.resetCache()}dismissPalette=()=>{if(this.isExiting)return;this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null,this.threadsForPicker=[],this.clustersForPicker=[],this.isLoadingThreads=!1}),this.unloadThreadsForPicker()};lastRootContext;getCommandPaletteContext=(J)=>{let{threadState:Z,recentThreadIDs:Q}=this.widget.dependencies;if(!Z.mainThread)return null;let Y=J??this.lastRootContext;if(!Y)return null;let X=K1.file(process.cwd()),V=g1(X);return{recentThreadIDs:Q,currentThreadID:Z.mainThread.id,contextFallback:Y,context:J,threadPool:this.widget.dependencies.threadPool,createSystemPromptDeps:this.widget.dependencies.createSystemPromptDeps,activeThreadHandle:this.widget.dependencies.activeThreadHandle,editorState:this.textController,isProcessing:this.isProcessing(),thread:Z.mainThread,ampURL:this.tuiContext.ampURL,threadService:this.widget.dependencies.threadService,configService:this.widget.dependencies.configService,skillService:this.widget.dependencies.skillService,openInEditor:this.openInEditor,takeImageAttachments:()=>{let K=this.imageAttachments;return this.setState(()=>{this.imageAttachments=[]}),K},setImageAttachments:(K)=>{this.setState(()=>{this.imageAttachments=K})},editorDispatch:(K)=>{switch(K.type){case"set-input":this.textController.clear(),this.textController.insertText(K.input);break;case"set-input-with-cursor":this.textController.clear(),this.textController.insertText(K.input),this.textController.cursorPosition=K.cursorPosition;break;case"insert-text":this.textController.insertText(K.text);break;case"clear":this.textController.clear();break}},submitMessage:(K)=>{this.onTextSubmitted(K).catch((z)=>{this.handleSubmitFlowError(z)})},exitApp:this.exitApplication,openHelp:()=>{this.setState(()=>{this.isShowingHelp=!0})},openContextAnalyze:()=>{this.openContextAnalyzeModal()},openSkillList:()=>{this.setState(()=>{this.isShowingSkillListModal=!0})},settingsStorage:this.widget.dependencies.settingsStorage,clientId:this.tuiContext.clientId,mcpService:this.widget.dependencies.mcpService,toolboxService:this.widget.dependencies.toolboxService,createThread:async()=>{await this.startAndSwitchToNewThread()},navigateBack:this.navigateBack,navigateForward:this.navigateForward,canNavigateBack:this.widget.dependencies.threadPool.canNavigateBack(),canNavigateForward:this.widget.dependencies.threadPool.canNavigateForward(),canUseAmpFree:this.freeTierStatus.canUseAmpFree,isDailyGrantEnabled:this.freeTierStatus.isDailyGrantEnabled,switchToThread:async(K)=>{await this.switchToExistingThread(K),this.setState(()=>{this.isMessageViewInSelectionMode=!1,this.imagePreview=null});return},handleHandoff:async(K,z)=>{let{goal:G,images:F}=z;if(!G)return{ok:!1,error:Error("Goal is required")};try{let U=this.widget.dependencies.threadState.mainThread;if(!U)return{ok:!1,error:Error("No active thread")};let q=setTimeout(()=>K.abort(new uT("Handoff took too long and was aborted (timeout: 60s)")),60000);try{let D=await this.widget.dependencies.threadPool.createHandoff(U.id,{goal:G,images:F,agentMode:U.agentMode,queuedMessages:U.queuedMessages?[...U.queuedMessages]:void 0,signal:K.signal});return clearTimeout(q),await this.switchToExistingThread(D),{ok:!0}}catch(D){if(clearTimeout(q),D instanceof Error&&(D.name==="AbortError"||D.message.includes("aborted")))throw K.signal.reason;throw D}}catch(U){return j.error("Failed to create handoff thread",{error:U}),{ok:!1,error:U instanceof Error?U:Error(String(U))}}},getGuidanceFiles:(K)=>{return this.widget.dependencies.activeThreadHandle.getGuidanceFiles(K)},openIdePicker:()=>{this.openIdePicker()},openPromptHistoryPicker:()=>{this.setState(()=>{this.isShowingPromptHistoryPicker=!0})},getAgentMode:()=>{return this.agentModeController?.getMode()??null},setAgentMode:(K)=>{this.agentModeController?.setMode(K)},toggleAgentMode:this.toggleAgentMode,toggleDeepReasoningEffort:this.toggleDeepReasoningEffort,getEffectiveAgentMode:()=>this.getEffectiveAgentMode(),getEditorText:()=>this.textController.text,userEmail:y6(this.authStatus)?this.authStatus.user.email:void 0,workspace:this.tuiContext.workspace??null,completionBuilder:this.getCompletionBuilder(),threads:this.threadsForPicker,clusters:this.enrichClustersWithActiveState(this.clustersForPicker),previewController:this.threadPreviewController,isLoadingThreads:this.isLoadingThreads,filterByWorkspace:this.filterThreadPickerByWorkspace,currentWorkspace:V,threadViewStates:this.getThreadViewStatesSnapshot(),newsFeedEntries:this.newsFeedEntries,showMCPStatusModal:()=>{this.setState(()=>{this.isShowingMCPStatusModal=!0})},internalAPIClient:this.widget.dependencies.internalAPIClient,features:y6(this.authStatus)?this.authStatus.features:this.tuiContext.features,showStatusMessage:(K,z=2000)=>{this.showStatusMessage(K,z)},showToast:(K,z="success",G)=>{this.toastController.show(K,z,G)},getThemeName:()=>LB4(Y).themeName,isMessageViewInteractionActive:this.isMessageViewInSelectionMode||this.messageViewController.editingMessageOrdinal!==null,enterHandoffMode:this.enterHandoffMode,isInHandoffMode:this.handoffState.isInHandoffMode,enterQueueMode:this.enterQueueMode,submitQueue:this.submitQueue,isInQueueMode:this.isInQueueMode,addPendingSkill:(K)=>{this.widget.dependencies.activeThreadHandle.addPendingSkill(K)},onThreadMentionSelected:this.paletteOnThreadMentionSelected??void 0,canChangeAgentModeInPromptEditor:()=>this.canChangeAgentModeInPromptEditor(),pluginCommands:this.pluginCommands,executePluginCommand:this.widget.dependencies.pluginService?(K,z,G)=>this.widget.dependencies.pluginService.commands.execute(K,z,{threadID:G}):void 0,reloadPlugins:this.widget.dependencies.pluginService?()=>this.widget.dependencies.pluginService.reload():void 0,pluginService:this.widget.dependencies.pluginService}};loadThreadsForPicker(){if(this.threadLoadSubscription)return;this.setState(()=>{this.isLoadingThreads=!0});let J=new $c0(this.widget.dependencies.threadHistoryService);this.threadLoadSubscription=J.observeThreadSummaries("",{includeArchived:!0}).subscribe({next:(Z)=>{this.setState(()=>{this.threadsForPicker=Z,this.clustersForPicker=_O4(Z),this.isLoadingThreads=!1})},error:()=>{this.setState(()=>{this.isLoadingThreads=!1})}})}updateGitBranch=async()=>{let J=await Ps5(process.cwd());this.setState(()=>{this.currentGitBranch=J})};removeBashInvocation=(J)=>{this.setState(()=>{this.bashInvocations=this.bashInvocations.filter((Z)=>Z.id!==J)})};invokeBashCommand=(J,{visibility:Z})=>{if(!this.widget.dependencies.activeThreadHandle.invokeBashTool)return;let Q=Date.now(),Y=`bash-${Q}-${Math.random().toString(36).substring(7)}`,X={cmd:J},V=new AbortController;this.widget.dependencies.activeThreadHandle.invokeBashTool(X,{hidden:Z===nH,abortController:V}).subscribe({next:(K)=>{this.setState(()=>{if(this.bashInvocations.find((G)=>G.id===Y))this.bashInvocations=this.bashInvocations.map((G)=>G.id===Y?{...G,toolRun:K}:G);else{let G={id:Y,args:X,toolRun:K,startTime:Q,abortController:V,hidden:Z===nH};this.bashInvocations=[...this.bashInvocations,G]}})},error:()=>this.removeBashInvocation(Y),complete:()=>this.removeBashInvocation(Y)})};cancelBashInvocations=()=>{let J=this.bashInvocations.find((Z)=>Z.toolRun.status==="in-progress");if(J)J.abortController.abort()};showContextDetailOverlay=()=>{this.setState(()=>{this.isShowingContextDetailOverlay=!0}),this.fetchThreadCostInfo()};fetchThreadCostInfo=uB4(()=>{let J=this.widget.dependencies.threadState.mainThread?.id;if(!J)return;this.widget.dependencies.internalAPIClient.threadDisplayCostInfo({threadID:J},{config:this.widget.dependencies.configService}).then((Z)=>{if(Z.ok)this.setState(()=>{this.threadCostInfo=Z.result,this.threadCostInfoThreadID=J})}).catch(()=>{this.setState(()=>{this.threadCostInfo=void 0,this.threadCostInfoThreadID=J})})},150);maybeRefetchThreadCostInfo=(J)=>{let Z=this.lastInferenceState==="running",Q=J==="running",Y=J==="idle"&&Z,X=Q&&!Z;if(Y)this.fetchThreadCostInfo();if(X)this.startElapsedTimeTimer();else if(Z&&!Q)this.stopElapsedTimeTimer();this.lastInferenceState=J};startElapsedTimeTimer=()=>{if(this.elapsedTimeTimer)return;this.elapsedTimeTimer=setInterval(()=>{let J=this.widget.dependencies.threadState.viewState;if(!(J.state==="active"&&J.inferenceState==="running")){this.stopElapsedTimeTimer();return}this.setState(()=>{})},1000)};stopElapsedTimeTimer=()=>{if(this.elapsedTimeTimer)clearInterval(this.elapsedTimeTimer),this.elapsedTimeTimer=null};toggleAgentMode=()=>{if(!this.agentModeController)return;if(this.handoffState.isGeneratingHandoff)return;let J=this.canChangeAgentModeInPromptEditor();if(this.agentModeController.toggle(J))this.setState(()=>{this.showImageUnsupportedHint=!1,this.agentModePulseSeq++})};handleMessageViewControllerUpdate=()=>{let J=this.messageViewController.editingMessageOrdinal;if(J===this.lastEditingMessageOrdinal)return;if(this.lastEditingMessageOrdinal===0&&J!==0){let Y=this.agentModeController;if(!Y){this.lastEditingMessageOrdinal=J,this.setState(()=>{});return}if(Y.getMode()!==null)Y.setMode(null)}this.lastEditingMessageOrdinal=J,this.setState(()=>{})};showStatusMessage(J,Z=2000){if(this.statusMessageTimer)clearTimeout(this.statusMessageTimer);this.setState(()=>{this.statusMessage=J}),this.statusMessageTimer=setTimeout(()=>{this.setState(()=>{this.statusMessage=null}),this.statusMessageTimer=null},Z)}applyDeepReasoningEffort(J){this.deepReasoningEffort=J,u$("agent.deepReasoningEffort",J)}commitDeepReasoningEffort(J){let Z=this.deepReasoningEffort;if(this.applyDeepReasoningEffort(J),J===Z)return Promise.resolve(!0);return this.widget.dependencies.configService.updateSettings("agent.deepReasoningEffort",J,"global").then(()=>!0).catch((Q)=>{return this.applyDeepReasoningEffort(Z),j.error("Failed to persist deep reasoning setting",{error:Q}),this.showStatusMessage("Failed to save deep reasoning effort"),!1})}getNextDeepReasoningEffort(J){return J==="medium"?"high":J==="high"?"xhigh":"medium"}toggleDeepReasoningEffort=async()=>{if(this.deepModeEffortHintController.dismissForInteraction(),this.getEffectiveAgentMode()!=="deep"){this.showStatusMessage("Deep reasoning effort is only available in deep mode");return}let Z=this.widget.dependencies.threadState.mainThread;if(!Z)return;if(W3(Z)>0){this.showStatusMessage("Deep reasoning effort can only be toggled before the first message");return}let Q=this.getNextDeepReasoningEffort(this.deepReasoningEffort);if(!await this.commitDeepReasoningEffort(Q))return;this.showStatusMessage(`Deep reasoning effort: ${Q}`),this.setState(()=>{this.agentModePulseSeq++})};formatAgentModeLabel(J){if(J!=="deep")return J;if(this.deepReasoningEffort==="high")return"deep²";if(this.deepReasoningEffort==="xhigh")return"deep³";return"deep"}handleInsertImage=async(J)=>{let Z=this.getEffectiveAgentMode();if(!vk(Z)){if(this.imageUnsupportedHintTimer)clearTimeout(this.imageUnsupportedHintTimer);return this.setState(()=>{this.showImageUnsupportedHint=!0}),this.imageUnsupportedHintTimer=setTimeout(()=>{this.setState(()=>{this.showImageUnsupportedHint=!1}),this.imageUnsupportedHintTimer=null},5000),!1}if(this.imageAttachments.length>=BI)return!1;let Q=await vT(J);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q]}),!1;return this.setState(()=>{this.displayMessage=Error(`Failed to attach image: ${Q}`)}),!1};handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1)})};handleImageClick=(J)=>{let Z=this.imageAttachments[J];if(Z)this.setState(()=>{this.imagePreview={image:Z,index:J,onRemove:()=>{let Q=this.imageAttachments.indexOf(Z);if(Q!==-1)this.setState(()=>{this.imageAttachments=this.imageAttachments.filter((Y,X)=>X!==Q),this.imagePreview=null})}}})};handleImagePreviewDismiss=()=>{this.setState(()=>{this.imagePreview=null})};handleShowFileImagePreview=(J)=>{this.setState(()=>{this.fileImagePreviewPath=J})};handleFileImagePreviewDismiss=()=>{this.setState(()=>{this.fileImagePreviewPath=null})};handleShowPainterImagePreview=(J,Z)=>{this.setState(()=>{this.painterImagePreview={image:J,filePath:Z}})};handlePainterImagePreviewDismiss=()=>{this.setState(()=>{this.painterImagePreview=null})};handleShowPainterSaveDialog=(J,Z)=>{this.setState(()=>{this.painterSaveDialog={image:J,filePath:Z}})};handlePainterSaveDialogDismiss=()=>{this.setState(()=>{this.painterSaveDialog=null})};handleSkillClick=(J)=>{let Z=this.pendingSkills[J];if(Z)this.setState(()=>{this.cachedSkillForPreview=null,this.skillPreview={skillIndex:J,onRemove:()=>{this.widget.dependencies.activeThreadHandle.removePendingSkill(Z.name),this.setState(()=>{this.skillPreview=null,this.cachedSkillForPreview=null})}}}),this.widget.dependencies.skillService.getSkills().then((Q)=>{let Y=Q.find((X)=>X.name===Z.name)??null;if(this.skillPreview!==null)this.setState(()=>{this.cachedSkillForPreview=Y})})};handleSkillPreviewDismiss=()=>{this.setState(()=>{this.skillPreview=null,this.cachedSkillForPreview=null})};handleShowEditingImagePreview=(J,Z,Q)=>{this.setState(()=>{this.imagePreview={image:J,index:Z,onRemove:Q}})};handleImagePreviewRemove=()=>{if(this.imagePreview)this.imagePreview.onRemove(),this.setState(()=>{this.imagePreview=null})};handleShowMysteryModal=()=>{if(this.mysteriousMessage)this.setState(()=>{this.isShowingMysteriousMessageModal=!0})};handleSplashOrbExplode=(J)=>{this.splashOrbExplosionSeq+=1,this.setState(()=>{this.splashOrbExplosion={seq:this.splashOrbExplosionSeq,originX:J.x,originY:J.y}})};handleSplashOrbExplosionComplete=()=>{if(!this.splashOrbExplosion)return;this.setState(()=>{this.splashOrbExplosion=null})};handleDestructMysteriousMessage=()=>{if(!this.mysteriousMessage)return;let J=this.mysteriousMessage.id;this.widget.dependencies.internalAPIClient.markAsReadMysteriousMessage({messageId:J},{config:this.widget.dependencies.configService}).then((Z)=>{if(!Z.ok)j.error("Failed to destruct mysterious message",Z.error);else this.setState(()=>{this.mysteriousMessage=null,this.isShowingMysteriousMessageModal=!1})}).catch((Z)=>{j.error("Failed to destruct mysterious message",Z)})};exitMessageViewInteraction=()=>{this.messageViewController.setSelectedUserMessageOrdinal(null),this.messageViewController.setIsShowingRestoreConfirmation(!1),this.messageViewController.setIsShowingEditConfirmation(!1),this.messageViewController.setPendingEditText(null),this.messageViewController.setPendingEditImageAttachments([]),this.messageViewController.setAffectedFiles([]),this.messageViewController.stopEditing(),this.setState(()=>{this.isMessageViewInSelectionMode=!1,this.imagePreview=null}),this.scrollMessageViewToBottom(),H6.instance.addPostFrameCallback(()=>{if(!this.isShowingPalette&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})};enterHandoffMode=()=>{this.dismissPalette(),this.exitMessageViewInteraction(),this.handoffController?.enter()};exitHandoffMode=()=>{this.handoffController?.exit()};submitHandoff=async(J)=>{let Z=this.imageAttachments;if(this.resetHistory(),!this.handoffController){this.showSubmitDisabledHint("Handoff controller not initialized");return}let Q=await this.handoffController.submit(J,Z,this.agentModeController?.getMode()??null);if(!Q.ok&&Q.error.message!=="Cancelled")this.displayMessage=Q.error,this.setState(()=>{});else if(Q.ok)this.setState(()=>{this.imageAttachments=[]}),setTimeout(()=>{this.handoffController?.startCountdown(()=>{this.autoSubmitHandoffDraft().catch((Y)=>{this.handleSubmitFlowError(Y)})})},0)};autoSubmitHandoffDraft=async()=>{let J=this.textController.text;if(J.trim())this.textController.clear(),await this.sendUserMessage(J)};enterQueueMode=()=>{this.dismissPalette(),this.exitMessageViewInteraction(),this.setState(()=>{this.isInQueueMode=!0})};exitQueueMode=()=>{this.setState(()=>{this.isInQueueMode=!1})};submitQueue=(J)=>{this.exitMessageViewInteraction();let{threadState:Z}=this.widget.dependencies;if((Z.mainThread?.queuedMessages?.length??0)>=l00){this.toastController.show(`Queue is full (max ${l00} messages)`,"error",3000);return}let Y=this.imageAttachments;this.resetHistory(),this.setState(()=>{this.imageAttachments=[]}),this.textController.clear();let X=[{type:"text",text:J}];if(Y.length>0)X.push(...Y);this.widget.dependencies.activeThreadHandle.queueMessage(X),this.exitQueueMode()};isAuthRequiredStatus(J){if(!RD(J))return!1;let Z=J.error.message.toLowerCase();return Z.includes("user not found")||Z.includes("auth-required")||Z.includes("unauthorized")||Z.includes("forbidden")||Z.includes("401")||Z.includes("403")||Z.includes("api key")||Z.includes("access token")}shouldRequireAuthForPromptSubmit(){if(!this.tuiContext.hasAPIKeyAtStartup&&!y6(this.authStatus))return!0;return this.isAuthRequiredStatus(this.authStatus)&&!y6(this.authStatus)}queuePromptUntilAuthenticated(J,Z=[...this.imageAttachments],Q){if(this.queuedPromptAfterAuth={text:J,images:Z},Q?.clearInput??!0)this.textController.clear(),this.textController.resetScrollOffset(),this.resetHistory(),this.setState(()=>{this.imageAttachments=[]});this.showStatusMessage("Sign in required. Prompt queued and will send after login.",2500),this.ensureAuthLoginSession()}ensureAuthLoginSession=async()=>{if(this.pendingAuthLogin||this.isCreatingAuthLoginSession||y6(this.authStatus))return;this.isCreatingAuthLoginSession=!0;try{let J=mM4(32).toString("hex"),Z=await yC(this.tuiContext.ampURL,J),Q=await yC(this.tuiContext.ampURL,J,!1),Y=new AbortController;this.setState(()=>{this.pendingAuthLogin={authToken:J,browserURL:Z,manualURL:Q,abortController:Y,isOpeningBrowser:!1,isAuthenticating:!0,errorMessage:null}}),uK4(this.tuiContext.ampURL,J,this.widget.dependencies.secretStorage,Y).then(()=>{this.showStatusMessage("Login successful",2000),this.checkAuthStatusAfterLogin()}).catch((X)=>{if(Y.signal.aborted)return;let V=X instanceof Error?X.message:"Login failed. Please try again.";this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.errorMessage=V,this.pendingAuthLogin.isAuthenticating=!1})})}catch(J){let Z=J instanceof Error?J.message:"Unable to start login flow. Please try again.";this.setState(()=>{if(!this.pendingAuthLogin){this.displayMessage=Error(Z);return}this.pendingAuthLogin.errorMessage=Z,this.pendingAuthLogin.isAuthenticating=!1})}finally{this.isCreatingAuthLoginSession=!1}};openAuthLoginBrowser=async()=>{if(!this.pendingAuthLogin)return;let J=this.pendingAuthLogin.browserURL,Z=this.pendingAuthLogin.abortController;this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.isOpeningBrowser=!0,this.pendingAuthLogin.errorMessage=null});try{await fX(J,Z.signal)}catch(Q){let Y=Q instanceof Error?Q.message:"Unable to open browser. Copy the manual link.";this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.errorMessage=Y})}finally{this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.isOpeningBrowser=!1})}};copyAuthLoginLink=async()=>{let J=this.pendingAuthLogin?.manualURL;if(!J)return;try{await l4.instance.tuiInstance.clipboard.writeText(J),this.showStatusMessage("Login link copied to clipboard",2000)}catch(Z){j.error("Failed to copy login link",{error:Z}),this.showStatusMessage("Failed to copy login link",2000)}};checkAuthStatusAfterLogin=async()=>{try{let J=await this.widget.dependencies.configService.getLatest(),Z=_k(J),Q=await this.widget.dependencies.internalAPIClient.getUserInfo({},{config:this.widget.dependencies.configService,signal:AbortSignal.timeout(Z)});if(!Q.ok){this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.errorMessage="Still waiting for login confirmation. Finish login in your browser, then press I again."});return}this.setState(()=>{this.authStatus={user:Q.result,features:Q.result.features,workspace:Q.result.team,mysteriousMessage:Q.result.mysteriousMessage},this.pendingAuthLogin=null}),await this.maybeResumeQueuedPromptAfterAuth()}catch(J){j.error("Failed to verify login state",{error:J}),this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.errorMessage="Unable to verify login yet. Press I again in a moment."})}};cancelAuthLoginSession=()=>{if(this.pendingAuthLogin)this.pendingAuthLogin.abortController.abort(Error("Authentication cancelled"));this.setState(()=>{this.pendingAuthLogin=null})};maybeResumeQueuedPromptAfterAuth=async()=>{if(!y6(this.authStatus))return;let J=this.queuedPromptAfterAuth;if(!J)return;this.queuedPromptAfterAuth=null,await this.proceedWithUserMessage(J.text,J.images)};handleAuthModalKey=(J)=>{if(!this.pendingAuthLogin||this.pendingInputDialog)return!1;let Z=J.key.length===1?J.key.toLowerCase():J.key;if(Z==="Enter"||Z==="o")return this.openAuthLoginBrowser(),!0;if(Z==="c")return this.copyAuthLoginLink(),!0;if(Z==="i")return this.checkAuthStatusAfterLogin(),!0;if(Z==="p")return this.promptForAuthLoginCode(),!0;return!1};promptForAuthLoginCode=async()=>{if(!this.pendingAuthLogin)return;let{authToken:J,abortController:Z}=this.pendingAuthLogin,Q=await new Promise((Y)=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null,this.pendingInputDialog={options:{title:"Paste Login Code",helpText:"Paste the login code from the browser page. This is not your API key.",submitButtonText:"Verify"},resolve:Y}})});if(!Q||!this.pendingAuthLogin)return;try{let{accessToken:Y}=nx0(Q,J);await this.widget.dependencies.secretStorage.set("apiKey",Y,this.tuiContext.ampURL),Z.abort(Error("Authentication completed from pasted code")),this.showStatusMessage("Login code accepted",2000),await this.checkAuthStatusAfterLogin()}catch(Y){let X=Y instanceof Error?Y.message:"Invalid login code.";this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.errorMessage=X,this.pendingAuthLogin.isAuthenticating=!1})}};openInEditor=async(J)=>{try{let Z=await Ls5(wG.join(Rs5(),"amp-edit-")),Q=wG.join(Z,"message.amp.md");await Is5(Q,J,"utf-8"),await oY(Q);try{let Y=await Ms5(Q,"utf-8");this.textController.text=Y}catch(Y){if(Y?.code!=="ENOENT")j.error("Failed to read temporary file",Y)}try{await gM4(Q),await As5(Z)}catch(Y){j.warn("Failed to clean up temporary file",Y)}}catch(Z){j.error("Error opening editor:",Z)}};onTextSubmitted=async(J)=>{if(!J.trim()&&this.imageAttachments.length===0){if(!this.canInterruptQueuedInference())return;try{await this.interruptNextQueuedMessage();return}catch(Y){j.error("Failed to interrupt queued message from empty submit",Y)}return}let Z=J.trim();if(Z===":q"){this.widget.dependencies.setExitNotice?.("Vim reflex detected. Exiting politely."),await this.exitApplication();return}if(Z==="exit"||Z==="quit"){await this.exitApplication();return}if(this.handoffState.isInHandoffMode){await this.submitHandoff(J);return}if(this.isInQueueMode){this.submitQueue(J);return}let Q=aH(J);if(Q&&this.widget.dependencies.activeThreadHandle.invokeBashTool)if(!Q.cmd){this.showSubmitDisabledHint("No command provided");return}else if(this.isProcessing()){this.showSubmitDisabledHint("Unable to use shell mode while agent is active");return}else{this.invokeBashCommand(Q.cmd,{visibility:Q.visibility}),this.widget.dependencies.history.add(J,process.cwd()),this.textController.clear(),this.textController.resetScrollOffset(),this.resetHistory();return}if(this.shouldRequireAuthForPromptSubmit()){this.queuePromptUntilAuthenticated(J);return}this.textController.clear(),this.textController.resetScrollOffset(),this.resetHistory(),await this.updateGitBranch(),await this.sendUserMessage(J)};agentModeListener=()=>{let J=this.agentModeController?.getMode(),Z=this.canChangeAgentModeInPromptEditor(),Q=this.widget.dependencies.threadState.mainThread;if(!Q)return;let Y=!Z&&J!==null&&W3(Q)>0&&Q.agentMode!==J;if(this.handoffState.countdownSeconds!==null)this.handoffController?.stopCountdown();if(!Z&&J&&J!==this.sessionState.agentMode)this.persistAgentMode(J);if(Y)this.agentModeController?.setMode(null);let X=this.lastEffectiveAgentMode,V=this.getEffectiveAgentMode();this.lastEffectiveAgentMode=V,this.deepModeEffortHintController.onAgentModeTransition(X,V),this.setState(()=>{})};handoffListener=(J)=>{this.setState(()=>{this.handoffState=J})};handleWinPasteHookImagePaste=async(J)=>{this.lastUserInteractionTime=Date.now();let Z=this.imageAttachments.length;try{await this.handleInsertImage(J.image.tempFile)}catch(Q){j.error("Failed to process win-paste-hook image paste event",{error:Q})}if(this.imageAttachments.length<=Z)await gM4(J.image.tempFile).catch(()=>{})};handleWinPasteHookStateChange=(J)=>{if(J.current!=="disabled_session"||this.hasShownWinPasteHookRecoveryWarning)return;this.hasShownWinPasteHookRecoveryWarning=!0,this.toastController.show('Windows clipboard hook unavailable. Open the command palette (Ctrl+O) and run "paste image from clipboard".',"warning",7000)};initState(){if(OQ.getInstance().interceptConsole(),this.threadPreviewController.setThreadService(this.widget.dependencies.threadService),this.threadPreviewController.addListener(this.previewControllerListener),this.handoffController=new yg0({getActiveThreadHandle:()=>this.widget.dependencies.activeThreadHandle,getThreadPool:()=>this.widget.dependencies.threadPool,switchToThread:(X)=>{return this.textController.clear(),this.switchToExistingThread(X)}}),this.handoffController.addListener(this.handoffListener),this.tuiContext.openThreadSwitcher)this.showStandaloneThreadPicker();l4.instance.on("key",()=>{this.lastUserInteractionTime=Date.now()}),l4.instance.on("mouse",()=>{this.lastUserInteractionTime=Date.now()}),l4.instance.on("paste",()=>{this.lastUserInteractionTime=Date.now()});let J=l4.instance.tuiInstance;if(this.winPasteHookImageUnsubscribe=J.onWinPasteHookImagePaste((X)=>{this.handleWinPasteHookImagePaste(X)}),this.winPasteHookStateUnsubscribe=J.onWinPasteHookStateChange((X)=>{this.handleWinPasteHookStateChange(X)}),this.authStatus=this.tuiContext.initialServerStatus,this.authStatusSubscription=nJ(this.widget.dependencies.configService).subscribe((X)=>{if(this.setState(()=>{if(this.authStatus=X,y6(X))this.pendingAuthLogin=null}),this.agentModeController?.updateVisibilityContext({userEmail:y6(X)?X.user.email:void 0}),y6(X)){this.maybeResumeQueuedPromptAfterAuth();return}if(this.isAuthRequiredStatus(X))this.ensureAuthLoginSession()}),this.authModalKeyInterceptorUnsubscribe=l4.instance.addKeyInterceptor((X)=>this.handleAuthModalKey(X)),!this.tuiContext.hasAPIKeyAtStartup)this.ensureAuthLoginSession();this.autocompleteFocusNodeListener=(X)=>{H6.instance.addPostFrameCallback(()=>{if(!this.mounted)return;this.setState(()=>{this.isTextfieldAndAutocompleteFocused=X.hasFocus})},"TuiUIState.autocompleteFocusNodeListener")},this.autocompleteFocusNode.addListener(this.autocompleteFocusNodeListener),this.sessionState=this.tuiContext.sessionState??bC,this.shortcutsHintUsed=this.sessionState.shortcutsHintUsed,this.messageViewControllerUnsubscribe??=this.messageViewController.subscribe(this.handleMessageViewControllerUpdate),Promise.all([this.tuiContext.freeTierStatusPromise??Promise.resolve(void 0),E1(this.widget.dependencies.configService.config)]).then(([X,V])=>{if(X)this.freeTierStatus=X;this.paletteConfig=V;let K=Jy(V.settings),z=V.settings["anthropic.speed"],G=V.settings["openai.speed"];this.showSkillsCountInPromptBar=V.settings["internal.cli.showSkillsCountInPromptBar"]!==!1,this.adsDisabledBySetting=V.settings.newAdsDisplay===!0,this.applyDeepReasoningEffort(K),this.anthropicSpeed=z,this.openAISpeed=G,this.deepReasoningEffortSubscription=this.widget.dependencies.configService.config.pipe(D1((F)=>Jy(F.settings)),M4()).subscribe((F)=>{if(F!==this.deepReasoningEffort)this.applyDeepReasoningEffort(F),this.setState(()=>{this.agentModePulseSeq++})}),this.anthropicSpeedSubscription=this.widget.dependencies.configService.config.pipe(D1((F)=>({settings:F.settings})),M4((F,U)=>F.settings["anthropic.speed"]===U.settings["anthropic.speed"])).subscribe(({settings:F})=>{let U=F["anthropic.speed"];if(U!==this.anthropicSpeed)this.anthropicSpeed=U,this.setState(()=>{this.agentModePulseSeq++})}),this.openAISpeedSubscription=this.widget.dependencies.configService.config.pipe(D1((F)=>({settings:F.settings})),M4((F,U)=>F.settings["openai.speed"]===U.settings["openai.speed"])).subscribe(({settings:F})=>{let U=F["openai.speed"];if(U!==this.openAISpeed)this.openAISpeed=U,this.setState(()=>{this.agentModePulseSeq++})}),this.showSkillsCountInPromptBarSubscription=this.widget.dependencies.configService.config.pipe(D1((F)=>({settings:F.settings})),M4((F,U)=>F.settings["internal.cli.showSkillsCountInPromptBar"]===U.settings["internal.cli.showSkillsCountInPromptBar"])).subscribe(({settings:F})=>{let U=F["internal.cli.showSkillsCountInPromptBar"]!==!1;if(U!==this.showSkillsCountInPromptBar)this.setState(()=>{this.showSkillsCountInPromptBar=U})}),this.submitOnEnter=V.settings.submitOnEnter??!0,this.submitOnEnterSubscription=this.widget.dependencies.configService.config.pipe(D1((F)=>({settings:F.settings})),M4((F,U)=>F.settings.submitOnEnter===U.settings.submitOnEnter)).subscribe(({settings:F})=>{let U=F.submitOnEnter??!0;if(U!==this.submitOnEnter)this.setState(()=>{this.submitOnEnter=U})}),this.agentModeController=new _g0({initialCliMode:this.tuiContext.initialAgentMode,sessionState:this.sessionState,freeTierStatus:this.freeTierStatus,workspace:this.tuiContext.workspace??null,userEmail:y6(this.authStatus)?this.authStatus.user.email:void 0,initialSettings:V.settings,config$:this.widget.dependencies.configService.config,getThread:()=>this.widget.dependencies.threadState.mainThread}),this.agentModeController.addListener(this.agentModeListener),this.lastEffectiveAgentMode=this.getEffectiveAgentMode(),this.deepModeEffortHintController.maybeShowForInitialDeepMode(),this.scheduleAdSubscriptionWithIdeReadiness(),this.setState(()=>{})}),this.updateGitBranch(),this.allConnectedThreadActivityStatusesSubscription=this.widget.dependencies.threadPool.allConnectedThreadActivityStatuses$.subscribe((X)=>{if(this.areRecordValuesEqual(this.allConnectedThreadActivityStatuses,X))return;this.setState(()=>{this.allConnectedThreadActivityStatuses=X})}),this.threadTitlesSubscription=this.widget.dependencies.threadPool.threadTitles$.subscribe((X)=>{if(this.areRecordValuesEqual(this.threadTitles,X))return;this.setState(()=>{this.threadTitles=X})}),this.threadInitializationStatusSubscription=this.widget.dependencies.threadPool.initializationStatus$?.subscribe((X)=>{let V=X.pending?X.message:null;if(V===this.threadInitializationMessage)return;this.setState(()=>{this.threadInitializationMessage=V})})??null,this.pendingNavigationSubscription=this.widget.dependencies.threadPool.threadHandles$.pipe(M4(),Q4((X)=>X?X.thread$:v0.of(null))).subscribe((X)=>{this.checkForPendingNavigation(X);let V=X?.id;if(this.threadCostInfoThreadID!==V){if(this.threadCostInfo=void 0,this.threadCostInfoThreadID=V,V&&W3(X)>0)this.fetchThreadCostInfo()}let K=X?this.widget.dependencies.threadState.viewState:void 0;this.maybeRefetchThreadCostInfo(K?.state==="active"?K.inferenceState:void 0)}),this.freeTierStatusSubscription=Ke1(async()=>{let X=await this.widget.dependencies.configService.getLatest(),V=_k(X),K=await this.widget.dependencies.internalAPIClient.getUserFreeTierStatus({},{config:this.widget.dependencies.configService,signal:AbortSignal.timeout(V)});if(!K.ok)throw K.error;return K.result}).subscribe({next:(X)=>{if(X){let V=this.freeTierStatus.canUseAmpFree;if(this.setState(()=>{this.freeTierStatus=X}),this.agentModeController?.updateVisibilityContext({freeTierStatus:X}),X.canUseAmpFree!==V)if(X.canUseAmpFree){if(!this.adSubscription&&!this.adsDisabledBySetting)this.scheduleAdSubscriptionWithIdeReadiness()}else this.unsubscribeFromAds()}},error:(X)=>{j.debug("Failed to fetch free tier status",X)}});let{mcpTrustHandler:Z}=this.widget.dependencies;if(this.mcpTrustSubscription=Z.pendingServers$.subscribe((X)=>{this.setState(()=>{this.pendingMCPServers=X})}),Ax0((X)=>{this.setState(()=>{this.pendingOAuthRequest=X})}),this.mcpServersSubscription=this.widget.dependencies.mcpService.servers.subscribe((X)=>{this.setState(()=>{this.mcpServers=X})}),this.pendingSkillsSubscription=this.widget.dependencies.activeThreadHandle.pendingSkills$.subscribe((X)=>{this.setState(()=>{this.pendingSkills=X})}),this.widget.dependencies.pluginService){let X=this.widget.dependencies.pluginService;this.pluginCommandsSubscription=_J(X.plugins,X.commands.changed).subscribe(()=>{let V=X.commands.list();this.setState(()=>{this.pluginCommands=V})}),this.pluginInfosSubscription=X.plugins.subscribe((V)=>{this.setState(()=>{this.pluginInfos=V})})}this.skillListSubscription=this.widget.dependencies.skillService.skills.subscribe((X)=>{let V=X.filter((K)=>!K.baseDir.startsWith("builtin://")).length;this.setState(()=>{this.availableSkillCount=V,this.availableSkillCountReady=!0})}),this.skillWarningsSubscription=this.widget.dependencies.skillService.skillWarnings.subscribe((X)=>{this.setState(()=>{this.skillWarningCount=X.length})}),this.skillErrorsSubscription=this.widget.dependencies.skillService.skillErrors.subscribe((X)=>{this.setState(()=>{this.skillErrorCount=X.length})}),this.pendingApprovalsSubscription=this.widget.dependencies.activeThreadHandle.pendingApprovals$.subscribe((X)=>{this.setState(()=>{this.pendingApprovals=X})}),this.ideStatusSubscription=this.widget.dependencies.ideClient.status.subscribe((X)=>{let V=this.isIdeReadyForAdContext();if(this.setState(()=>{this.ideStatus=X}),!V&&this.isIdeReadyForAdContext()){if(this.adReadinessTimeout)clearTimeout(this.adReadinessTimeout),this.adReadinessTimeout=null;if(!this.adSubscription&&!this.adsDisabledBySetting)this.subscribeToAds()}}),this.ideMessageSubscription=this.widget.dependencies.ideClient.messages.subscribe(async(X)=>{try{if(!this.widget.dependencies.threadState.mainThread){j.warn("No active thread found to handle IDE message");return}await new Promise((K)=>setTimeout(K,50)),await this.widget.dependencies.activeThreadHandle.sendMessage({content:[{type:"text",text:X}]}),j.debug("Message sent from IDE to agent",{message:X.slice(0,100)})}catch(V){this.handleSubmitFlowError(V)}}),this.ideAppendToPromptSubscription=this.widget.dependencies.ideClient.appendToPrompt.subscribe((X)=>{this.textController.insertText(X),j.debug("Appended text to CLI prompt from IDE",{text:X.slice(0,100)})}),this.updateServiceSubscription=this.widget.dependencies.updateService.state.subscribe((X)=>{this.setState(()=>{this.updateState=X})}),this.mysteriousMessageSubscription=nJ(this.widget.dependencies.configService).pipe(F5((X)=>X!=="pending"),D1((X)=>y6(X)?X.mysteriousMessage??null:null),M4((X,V)=>X?.id===V?.id)).subscribe((X)=>{this.setState(()=>{if(X?.id!==this.mysteriousMessage?.id)this.isShowingMysteriousMessageModal=!1;if(this.mysteriousMessage=X,X&&!this.mysterySequenceManager)this.mysterySequenceManager=new E20(new Map([[new O20(RJ0.MYSTERY_SEQUENCE),new Pp]])),this.mysteryKeyInterceptorUnsubscribe=l4.instance.addKeyInterceptor((V)=>{if(!this.mysterySequenceManager)return!1;if(this.isShowingMysteriousMessageModal)return!1;let K=this.mysterySequenceManager.handleKeyEvent(V);if(K.consumed){if(K.intent)this.handleShowMysteryModal();return this.setState(()=>{this.mysterySequenceProgress=K.progress}),!0}else if(this.mysterySequenceProgress)this.setState(()=>{this.mysterySequenceProgress=null});return!1});else if(!X)this.mysteryKeyInterceptorUnsubscribe?.(),this.mysteryKeyInterceptorUnsubscribe=null,this.mysterySequenceManager?.dispose(),this.mysterySequenceManager=null,this.mysterySequenceProgress=null})}),this.textController.addListener(this.textChangeListener),l4.instance.addKeyInterceptor((X)=>{if(X.key==="?"){if(this.textController.text===""&&this.textController.cursorPosition===0&&!this.isShowingHelp&&!this.isShowingPalette&&this.isTextfieldAndAutocompleteFocused){if(this.setState(()=>{this.isShowingShortcutsHelp=!this.isShowingShortcutsHelp}),!this.shortcutsHintUsed)this.shortcutsHintUsed=!0,this.sessionState={...this.sessionState,shortcutsHintUsed:!0},rz(this.sessionState);return!0}}if(this.isShowingShortcutsHelp){if(this.setState(()=>{this.isShowingShortcutsHelp=!1}),X.key==="Escape")return!0;return!1}return!1}),this.updateTerminalTitle();let Q=this.widget.dependencies.ideClient.getSelectedConfig();if(Q)this.connectToSelectedIde(Q,"auto-startup").catch((X)=>{let V=X instanceof Error?X.message:String(X);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${V}`)})});else if(this.tuiContext.showIdePickerHint)this.toastController.show("Use /ide to connect to an IDE","success",5000);else if(this.tuiContext.showJetBrainsInstaller)this.openJetBrainsInstaller();let Y=this.widget.dependencies.threadState.mainThread;if(!Y){this.initNewsFeed();return}if(Y.autoSubmitDraft&&Y.messages.length===0)setTimeout(()=>{this.autoSubmitInitialDraft(Y.id)},100);this.initNewsFeed()}async autoSubmitInitialDraft(J){let Z=await this.getDraft(J);if(!Z)return;let Q=Z.text.trim();if(!Q&&Z.images.length===0)return;j.info("Auto-submitting initial handoff draft",{name:"handoff",threadID:J,hasDraftText:Boolean(Q),draftImageCount:Z.images.length}),this.textController.clear(),await this.proceedWithUserMessage(Q,[...Z.images])}handleSubmitFlowError(J){j.error("Failed to submit prompt message",J);let Z=J instanceof Error?J.message:String(J);this.showErrorMessage(Z)}checkForPendingNavigation(J){let Z=J??this.widget.dependencies.threadState.mainThread;if(!Z?.pendingNavigation)return;let Q=Z.pendingNavigation;if(this.pendingNavigationInFlightThreadID===Q)return;this.pendingNavigationInFlightThreadID=Q,this.widget.dependencies.activeThreadHandle.clearPendingNavigation().catch(()=>{return}),j.info("Pending navigation detected, navigating to new thread",{name:"handoff",fromThreadID:Z.id,targetThreadID:Q}),this.handleHandoffNavigation(Q).finally(()=>{if(this.pendingNavigationInFlightThreadID===Q)this.pendingNavigationInFlightThreadID=null})}handleHandoffNavigation=async(J)=>{try{await this.switchToExistingThread(J);let Z=this.widget.dependencies.threadState.mainThread;if(!Z){j.error("Failed to get new thread after handoff navigation");return}if(Z.autoSubmitDraft&&Z.messages.length===0){let Q=await this.getDraft(J);if(!Q)return;let Y=Q.text.trim();if(!Y&&Q.images.length===0)return;j.info("Auto-submitting handoff draft",{name:"handoff",threadID:J,hasDraftText:Boolean(Y),draftImageCount:Q.images.length}),this.textController.clear(),await this.proceedWithUserMessage(Y,[...Q.images])}}catch(Z){j.error("Failed to handle handoff navigation",{name:"handoff",newThreadID:J,error:Z})}};dispose(){if(this.ideStatusSubscription)this.ideStatusSubscription.unsubscribe();if(this.ideMessageSubscription)this.ideMessageSubscription.unsubscribe();if(this.ideAppendToPromptSubscription)this.ideAppendToPromptSubscription.unsubscribe();if(this.updateServiceSubscription)this.updateServiceSubscription.unsubscribe();if(this.agentModeController)this.agentModeController.removeListener(this.agentModeListener),this.agentModeController.dispose();if(this.deepModeEffortHintController.dispose(),this.messageViewControllerUnsubscribe)this.messageViewControllerUnsubscribe(),this.messageViewControllerUnsubscribe=null;if(this.handoffController)this.handoffController.removeListener(this.handoffListener),this.handoffController.dispose();if(this.adReadinessTimeout)clearTimeout(this.adReadinessTimeout),this.adReadinessTimeout=null;if(this.adSubscription)this.adSubscription.unsubscribe();if(this.freeTierStatusSubscription)this.freeTierStatusSubscription.unsubscribe();if(this.allConnectedThreadActivityStatusesSubscription)this.allConnectedThreadActivityStatusesSubscription.unsubscribe();if(this.threadInitializationStatusSubscription)this.threadInitializationStatusSubscription.unsubscribe();if(this.threadTitlesSubscription)this.threadTitlesSubscription.unsubscribe();if(this.pendingNavigationSubscription)this.pendingNavigationSubscription.unsubscribe();if(this.mcpTrustSubscription)this.mcpTrustSubscription.unsubscribe();if(this.authStatusSubscription)this.authStatusSubscription.unsubscribe(),this.authStatusSubscription=null;if(Ax0(null),this.authModalKeyInterceptorUnsubscribe?.(),this.authModalKeyInterceptorUnsubscribe=null,this.pendingAuthLogin)this.pendingAuthLogin.abortController.abort(Error("TUI disposed")),this.pendingAuthLogin=null;if(this.mcpServersSubscription)this.mcpServersSubscription.unsubscribe();if(this.pendingSkillsSubscription)this.pendingSkillsSubscription.unsubscribe();if(this.pluginCommandsSubscription)this.pluginCommandsSubscription.unsubscribe();if(this.pluginInfosSubscription)this.pluginInfosSubscription.unsubscribe();if(this.skillListSubscription)this.skillListSubscription.unsubscribe();if(this.skillWarningsSubscription)this.skillWarningsSubscription.unsubscribe();if(this.skillErrorsSubscription)this.skillErrorsSubscription.unsubscribe();if(this.pendingApprovalsSubscription)this.pendingApprovalsSubscription.unsubscribe();if(this.unloadThreadsForPicker(),this.newsFeedSubscription)this.newsFeedSubscription.unsubscribe();if(this.deepReasoningEffortSubscription)this.deepReasoningEffortSubscription.unsubscribe(),this.deepReasoningEffortSubscription=null;if(this.anthropicSpeedSubscription)this.anthropicSpeedSubscription.unsubscribe(),this.anthropicSpeedSubscription=null;if(this.openAISpeedSubscription)this.openAISpeedSubscription.unsubscribe(),this.openAISpeedSubscription=null;if(this.submitOnEnterSubscription)this.submitOnEnterSubscription.unsubscribe(),this.submitOnEnterSubscription=null;if(this.showSkillsCountInPromptBarSubscription)this.showSkillsCountInPromptBarSubscription.unsubscribe(),this.showSkillsCountInPromptBarSubscription=null;if(this.stopElapsedTimeTimer(),this.winPasteHookImageUnsubscribe?.(),this.winPasteHookImageUnsubscribe=null,this.winPasteHookStateUnsubscribe?.(),this.winPasteHookStateUnsubscribe=null,this.mysteriousMessageSubscription)this.mysteriousMessageSubscription.unsubscribe();if(this.mysteryKeyInterceptorUnsubscribe?.(),this.mysterySequenceManager?.dispose(),this.threadPreviewController.removeListener(this.previewControllerListener),this.threadPreviewController.dispose(),this.toastController.dispose(),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;if(this.autocompleteFocusNodeListener)this.autocompleteFocusNode.removeListener(this.autocompleteFocusNodeListener),this.autocompleteFocusNodeListener=null;this.textController.removeListener(this.textChangeListener);for(let J of this.messageScrollControllers.values())J.dispose();this.messageScrollControllers.clear()}getCurrentConfirmation(){if(this.pendingApprovals.length>0){let J=this.pendingApprovals[0];return{type:"tool-use",tools:[{useBlock:{type:"tool_use",id:J.toolUseId,name:J.toolName,complete:!0,input:J.args},toAllow:J.toAllow??[]}],subthreadID:void 0,reason:J.reason??`Tool requires approval: ${J.toolName}`,isSubagent:J.context==="subagent",subagentToolName:J.subagentToolName}}return null}updateProgressBar(){}static AD_READINESS_TIMEOUT_MS=1000;scheduleAdSubscriptionWithIdeReadiness(){if(this.adsDisabledBySetting)return;if(!this.freeTierStatus.canUseAmpFree)return;if(this.isIdeReadyForAdContext()){this.subscribeToAds();return}this.adReadinessTimeout=setTimeout(()=>{if(this.adReadinessTimeout=null,!this.adSubscription)this.subscribeToAds()},RJ0.AD_READINESS_TIMEOUT_MS)}isIdeReadyForAdContext(){let J=this.ideStatus;if(!J||!J.enabled)return!1;return Boolean(J.openFile||J.visibleFiles&&J.visibleFiles.length>0)}unsubscribeFromAds(){if(this.adSubscription)this.adSubscription.unsubscribe(),this.adSubscription=null;if(this.adReadinessTimeout)clearTimeout(this.adReadinessTimeout),this.adReadinessTimeout=null;this.setState(()=>{this.randomAd=null})}subscribeToAds(){if(this.adSubscription)return;if(this.adsDisabledBySetting)return;if(!this.freeTierStatus.canUseAmpFree)return;this.adSubscription=Gg0(this.widget.dependencies.internalAPIClient,this.widget.dependencies.configService,()=>zg0(this.lastUserInteractionTime),this.widget.dependencies.codebaseContextService,()=>this.widget.dependencies.threadState.mainThread??void 0).subscribe({next:(J)=>{this.setState(()=>{this.randomAd=J}),H6.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})}})}onConfirmationResponse=async(J)=>{let Z=this.getCurrentConfirmation();if(!Z||Z.type!=="tool-use"){j.error("No current tool confirmation found");return}let Q=Z.tools[0]?.useBlock;if(!Q){j.error("No tool use block found in confirmation");return}if(J?.type==="deny-with-feedback"){let{feedback:V}=J;try{if(this.pendingApprovals.find((z)=>z.toolUseId===Q.id))await this.widget.dependencies.activeThreadHandle.resolveApproval(Q.id,!1,V.trim()||void 0);else await this.widget.dependencies.activeThreadHandle.resolveApproval(Q.id,!1,V.trim()||void 0)}catch(K){j.error("Failed to send deny with feedback:",K)}return}let Y=J?.type==="simple"?J.value:null;if(Y==="allow-all-session")u$("dangerouslyAllowAll",!0);if(Y==="allow-all-persistent")try{await this.widget.dependencies.settingsStorage.set("dangerouslyAllowAll",!0,"global")}catch(V){if(V&&V instanceof Error)this.setState(()=>{this.displayMessage=V});else j.error("Failed to write dangerouslyAllowAll setting:",V);return}if(Y==="always-guarded"){let V=Z.tools[0]?.toAllow??[],K=await this.widget.dependencies.settingsStorage.get("guardedFiles.allowlist")||[],z=[...V,...K];await this.widget.dependencies.settingsStorage.set("guardedFiles.allowlist",z,"global")}if(Y==="connect-github"){let V=new URL("/settings#code-host-connections",this.tuiContext.ampURL).toString();await w8(this.context,V);return}if(Y==="disable-librarian"){let V=await this.widget.dependencies.settingsStorage.get("tools.disable")??[];if(!V.includes(T$))await this.widget.dependencies.settingsStorage.set("tools.disable",[...V,T$],"global")}let X=Y!==null&&["yes","allow-all-session","allow-all-persistent","always-guarded"].includes(Y);try{await this.widget.dependencies.activeThreadHandle.resolveApproval(Q.id,X)}catch(V){j.error("Failed to send tool confirmation:",V)}};showConfirmationOverlay=(J)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=J})};getCurrentEphemeralError(){let{threadState:J}=this.widget.dependencies,Z=J.viewState;if(Z.state!=="active"||!Z.ephemeralError)return null;return Z.ephemeralError}handleEphemeralErrorResponse=async(J)=>{let{activeThreadHandle:Z}=this.widget.dependencies;switch(J){case"retry":await Z.retryTurn();break;case"dismiss":Z.dismissEphemeralError();break;case"new-thread":Z.dismissEphemeralError(),await this.startAndSwitchToNewThread();break;case"handoff":Z.dismissEphemeralError(),this.enterHandoffMode();break;case"add-credits":{let Q=new URL("/pay",this.tuiContext.ampURL);await w8(this.context,Q),this.showStatusMessage("Payment page opened. After paying, choose Retry.");break}}this.setState(()=>{})};handleDisplayMessageDismiss=()=>{this.setState(()=>{this.displayMessage=null})};handleMCPTrustOpenSettings=async()=>{let{mcpTrustHandler:J,settingsStorage:Z}=this.widget.dependencies;await J.deny();try{await oY(Z.getSettingsFilePath())}catch(Q){let Y=Q instanceof Error?Q.message:String(Q);await this.showErrorMessage(`Failed to open settings: ${Y}`)}};cancelStreamingMessage=async()=>{await this.widget.dependencies.activeThreadHandle.cancelStreaming()};switchToExistingThread=async(J)=>{let Z=Date.now();try{j.info(`[switchToExistingThread] Switching to thread: ${J}`);let Q=Date.now();await this.widget.dependencies.threadPool.switchThread(J),j.info(`[switchToExistingThread] switchToThread resolved in ${Date.now()-Q}ms`);let Y=await this.widget.dependencies.threadService.get(J)??this.widget.dependencies.threadState.mainThread;if(!Y||Y.id!==J)throw Error("No active thread after switch");j.info(`[switchToExistingThread] Got thread ${J}, thread.agentMode: ${Y.agentMode}`),j.info("[switchToExistingThread] Clearing agent mode"),this.agentModeController?.setMode(null);let X=Date.now();this.onThreadSwitch(),j.info(`[switchToExistingThread] onThreadSwitch completed in ${Date.now()-X}ms`),this.persistLastThreadId(J);let V=await this.getDraft(J);if(V&&W3(Y)===0){if(this.textController.clear(),V.text)this.textController.insertText(V.text);if(V.images.length>0)this.setState(()=>{this.imageAttachments=[...V.images]})}j.info(`[switchToExistingThread] Completed in ${Date.now()-Z}ms`)}catch(Q){j.error("Failed to switch to thread",{threadId:J,error:Q});let Y=Q instanceof Error?Q.message:String(Q);if(Y.includes("can't be opened in legacy mode")){await this.showErrorMessage(Y);return}throw Error(`Failed to switch to thread: ${J}. ${Y}`,{cause:Q})}};async getDraft(J){return(await E1(this.widget.dependencies.threadPool.drafts$).catch(()=>null))?.get(J)??null}sendUserMessage=async(J)=>{await this.proceedWithUserMessage(J)};proceedWithUserMessage=async(J,Z)=>{if(this.cancelBashInvocations(),this.shouldRequireAuthForPromptSubmit()){this.queuePromptUntilAuthenticated(J,Z??[...this.imageAttachments],{clearInput:Z===void 0});return}this.handoffController?.clearPendingPrompt(),this.widget.dependencies.history.add(J,process.cwd());let Q=this.widget.dependencies.threadState.mainThread;if(!Q)return;let Y=W3(Q)===0,X=this.getEffectiveAgentMode();if(Q.agentMode&&!Y&&X!==Q.agentMode){await this.showErrorMessage(`This thread uses ${Q.agentMode} mode. To change mode, edit the first message or create a new thread.`);return}let V=Z??this.imageAttachments,K=[{type:"text",text:J}];if(V.length>0)K.push(...V);if(await this.widget.dependencies.activeThreadHandle.sendMessage({content:K,agentMode:X}),this.persistLastThreadId(Q.id),Y)this.persistAgentMode(X);if(this.scrollMessageViewToBottom(),!Z)this.setState(()=>{this.imageAttachments=[]});H6.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})};async showErrorMessage(J){this.setState(()=>{this.displayMessage=Error(J)})}exitApplication=async()=>{this.setState(()=>{this.isExiting=!0});let J=this.widget.dependencies.threadState.mainThread;if(J&&J.messages.length===0){if(J.relationships?.find((Q)=>Q.type==="handoff"&&Q.role==="child"))await this.widget.dependencies.threadPool.deleteThread?.(J.id).catch(()=>{})}l4.instance.stop()};async persistAgentMode(J){let Q={...await oz(),agentMode:J};this.sessionState=Q,await rz(Q)}async persistLastThreadId(J){let Q={...await oz(),lastThreadId:J};this.sessionState=Q,await rz(Q)}onExitPressed=()=>{if(this.isConfirmingExit){if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;this.exitApplication()}else{if(this.setState(()=>{this.isConfirmingExit=!0}),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout);this.exitConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingExit=!1}),this.exitConfirmTimeout=null},1000)}};toHomeRelative(J){let Z=js5();if(J===Z)return"~";if(J.startsWith(Z+wG.sep))return"~"+J.slice(Z.length);return J}shorten(J){let Z=J.split(wG.sep).filter(Boolean);if(Z.length<=5)return J;return[Z.slice(0,2).join(wG.sep),"…",Z.slice(-2).join(wG.sep)].join(wG.sep)}buildDisplayText(J,Z,Q,Y){let X=Z?` (${Z})`:"",V=J+X;if(p5(V,Y)<=Q)return V;let K=J.split(wG.sep);if(K.length>2){let G=[K[0],"…",K[K.length-1]].join(wG.sep)+X;if(p5(G,Y)<=Q)return G}return sE(V,Q,Y)}build(J){this.lastRootContext=J;let Z=this.widget.dependencies.pluginPlatform;if(Z&&!Z.showToast){let z1=this.toastController;Z.showToast=(L4)=>z1.show(L4,"success")}if(Z&&!Z.showOpenedURLToast){let z1=this.toastController;Z.showOpenedURLToast=(L4)=>z1.show(`Opened URL: ${L4}`,"success",8000)}if(Z&&!Z.appendToThreadHandler){let z1=this.widget.dependencies;Z.appendToThreadHandler=async(L4)=>{for(let T4 of L4)await z1.activeThreadHandle.queueMessage([{type:"text",text:T4.content}])}}if(Z&&!Z.showInputDialog)Z.showInputDialog=(z1)=>{return new Promise((L4)=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null,this.pendingInputDialog={options:z1,resolve:L4}})})};if(Z&&!Z.showConfirmDialog)Z.showConfirmDialog=(z1)=>{return new Promise((L4)=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null,this.pendingConfirmDialog={options:z1,resolve:L4}})})};let Q=t1.of(J),Y=f0.of(J),X=Y.base;this.themeColors=X;let{colors:V,app:K}=Y;this.themeApp=K;let z=this.widget.dependencies.threadState.mainThread,G=z?.agentMode&&h3(z.agentMode),F=this.freeTierStatus.isDailyGrantEnabled,U=!this.adsDisabledBySetting&&(G||F)&&this.randomAd!==null,q=Boolean(U),{threadState:D}=this.widget.dependencies;this.updateTerminalTitle(),this.updateProgressBar();let W=this.getCurrentConfirmation(),H=D.items,B=D.mainThread||void 0,w=D.subagentToolsByParentID,N=D.toolProgressByToolUseID,O=D.todosList,E=B?.id,L=B,M=this.isTranscriptEmpty(),A=M&&this.isStartupThreadLoading(),I=this.threadInitializationMessage?.startsWith("Importing thread")??!1,P=this.widget.dependencies.threadPool.isDTWMode?.()===!0,_=(z1)=>new qd({key:new $3(`preview-message-view-${z1.id}`),items:TU(z1).items,toolProgressByToolUseID:new Map,controller:this.threadPreviewController.scrollController,autofocus:!1,thread:z1,denseView:z1.agentMode==="deep",focusNode:new r4({debugLabel:"PreviewFocus"}),onShowImagePreview:()=>{},stateController:this.previewMessageViewController,submitOnEnter:this.submitOnEnter,isDTWMode:P}),S=this.previewThread,y=S?S.messages.length>2000?new u0({mainAxisSize:"max",children:[new T1({child:new R0}),new i0({padding:C0.all(2),child:new l1({child:new $0({text:new C("Thread too long for preview",new h({color:V.mutedForeground,dim:!0}))})})})]}):_(S):M?new P$0({agentMode:this.getEffectiveAgentMode(),mysteriousMessage:this.mysteriousMessage,mysterySequenceProgress:this.mysterySequenceProgress,onShowMysteryModal:this.handleShowMysteryModal,onOrbExplode:this.handleSplashOrbExplode}):new ed0({threadID:E,items:H,subagentToolsByParentID:w,toolProgressByToolUseID:N,controller:E?this.getMessageScrollController(E):new Y5,autofocus:!1,onCopy:this.handleMainMessageViewCopy,thread:L,onMessageEditSubmit:this.handleMessageEditSubmit,...P?{}:{onMessageRestoreSubmit:this.handleMessageRestoreSubmit},onShowForkDeprecation:this.showForkDeprecationMessage,getAffectedFiles:this.getAffectedFiles,denseView:L?.agentMode==="deep",focusNode:this.messageViewFocusNode,onDismissFocus:this.handleMainMessageViewDismissFocus,isInSelectionMode:this.isMessageViewInSelectionMode,isInHandoffMode:this.handoffState.isInHandoffMode,completionBuilder:this.getCompletionBuilder(),onShowImagePreview:this.handleShowEditingImagePreview,onSelectionChanged:this._handleSelectionChanged,onDoubleAtTrigger:this.handleDoubleAtTrigger,stateController:this.messageViewController,submitOnEnter:this.submitOnEnter,threadViewState:D.viewState,isDTWMode:P}),m=Math.max(Math.floor(Q.size.height*0.4),12),b=this.getCurrentEphemeralError(),k=Q.size.width<40,f=dM4(D),p=this.widget.dependencies.threadPool.getCompactionStatus?.(),l=M20(J),x=this.buildBottomWidget(b,W,V,Y,D,O,m,q,f,Q,l),r=new L$0({threadViewState:D.viewState,threadTokenUsage:f,compactionState:p?.compactionState??"idle",threadID:E??null,thread:D.mainThread??void 0,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},onShowIdePicker:this.openIdePicker,ideStatus:this.ideStatus,mcpServers:this.mcpServers,plugins:this.pluginInfos,isNarrow:k,uiHint:this.getUIHint()??void 0,waitingForConfirmation:!!W,showingEphemeralError:Boolean(D.viewState.state==="active"&&D.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null,executingCommandNoun:this.executingCommand?.noun??null,executingCommandVerb:this.executingCommand?.verb??null,executingCommandMessage:this.executingCommand?.statusMessage??null}),c=new O$0({bashInvocations:this.bashInvocations}),s=[],w0=_K4(this.tuiContext.buildTimestamp);if(w0){let z1=sL0(w0.ageMs,{verbose:!0});s.push(new c0({decoration:new v4(V.destructive),child:new i0({padding:C0.horizontal(1),child:new $0({text:new C("",new h({color:V.foreground,bold:!0}),[new C(`Your Amp version is ${z1} old — run `),new C("amp update",new h({color:V.warning})),new C(" or see ampcode.com/manual")]),textAlign:"center"})})}))}s.push(new T1({child:y}),c);let a=new i6({children:[new u0({mainAxisSize:"min",children:[U?new lg0({ad:this.randomAd,onImpression:(z1)=>{if(!z1.advertiserId){j.warn("[ad-telemetry] Skipping impression due to missing advertiserId",{adId:z1.id});return}let L4=z1.impressionId??mM4(16).toString("hex");this.lastAdImpressionId=L4;let T4=this.widget.dependencies.threadState.mainThread;if(!T4)return;let i4=T4.messages[T4.messages.length-1],E8=Date.now();CN("viewed",{adId:z1.id,advertiserId:z1.advertiserId,threadId:T4.id,messageId:i4?.messageId,impressionId:L4,placement:"tui",matchType:z1.metadata?.matchType,matchedPatterns:z1.metadata?.matchedPatterns,candidateAdPoolCount:z1.metadata?.candidateAdPoolCount,clientRegion:z1.metadata?.clientRegion,tokenProvided:!!z1.impressionToken,campaignId:z1.metadata?.campaignId,providerId:z1.metadata?.providerId,providerType:z1.metadata?.providerType,relevance:z1.metadata?.relevance}),CN("impressionStarted",{adId:z1.id,advertiserId:z1.advertiserId,impressionId:L4,placement:"tui",providerId:z1.metadata?.providerId,providerType:z1.metadata?.providerType}),this.widget.dependencies.internalAPIClient.recordAdImpression({adId:z1.id,impressionToken:z1.impressionToken,impressionId:L4,externalImpressionUrl:z1.externalImpressionUrl},{config:this.widget.dependencies.configService}).then((L7)=>{if(!L7.ok)throw Error(`recordAdImpression failed: ${L7.error.code??"unknown"}`);let zX=Math.round(Date.now()-E8);CN("impressionRecorded",{adId:z1.id,advertiserId:z1.advertiserId,impressionId:L4,placement:"tui",durationMs:zX,providerId:z1.metadata?.providerId,providerType:z1.metadata?.providerType})}).catch((L7)=>{let zX=Math.round(Date.now()-E8);CN("impressionFailed",{adId:z1.id,advertiserId:z1.advertiserId,impressionId:L4,errorMessage:L7 instanceof Error?L7.message:String(L7),errorType:"error",placement:"tui",durationMs:zX,providerId:z1.metadata?.providerId,providerType:z1.metadata?.providerType})})},onButtonClick:async()=>{let z1=this.randomAd;if(this.lastAdImpressionId&&z1.advertiserId){let i4=this.widget.dependencies.threadState.mainThread;if(!i4)return;let E8=i4.messages[i4.messages.length-1];CN("clicked",{adId:z1.id,advertiserId:z1.advertiserId,threadId:i4.id,messageId:E8?.messageId,impressionId:this.lastAdImpressionId,placement:"tui",actionType:"link_to",matchType:z1.metadata?.matchType,matchedPatterns:z1.metadata?.matchedPatterns,candidateAdPoolCount:z1.metadata?.candidateAdPoolCount,clientRegion:z1.metadata?.clientRegion,providerId:z1.metadata?.providerId,providerType:z1.metadata?.providerType})}let T4=l4.instance.tuiInstance.clipboard.isOsc52Supported();if(d80())this.setState(()=>{this.adActionModal={showCopyOption:!1,url:z1.shortDestinationUrl,title:z1.buttonLabel},this.bringAdModalToFront("adAction")});else if(!await w8(this.context,z1.shortDestinationUrl))this.setState(()=>{this.adActionModal={showCopyOption:T4,url:z1.shortDestinationUrl},this.bringAdModalToFront("adAction")})},onAdInfoClick:()=>{this.setState(()=>{this.adInfoModal={provider:this.randomAd?.metadata?.provider},this.bringAdModalToFront("adInfo")})}}):new R0({height:0}),new c0({constraints:new M1(0,Q.size.width,0,m),child:x})]}),q?new x6({top:0,left:0,right:0,child:new iM4({userHeight:this.bottomGridUserHeight,maxHeight:m,onInitializeHeight:(z1)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(z1,m)})},onDrag:(z1)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(z1.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let L4=Math.floor(z1.localPosition.y)-this.bottomGridDragStartY,T4=Math.max(4,this.bottomGridDragStartHeight-L4),i4=Math.min(T4,m),E8=Math.floor(i4);if(this.bottomGridUserHeight!==E8)this.setState(()=>{this.bottomGridUserHeight=E8})},onRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null}})}):new R0({height:0})]}),F0=this.getParentThreadInfo();if(F0){let z1=F0.type==="handoff"?K.handoffMode:V.primary,L4=40,T4=l6(F0.title),i4=T4.length>40?T4.slice(0,39).join("")+"…":F0.title;s.push(new bp({link:this.parentThreadLinkAnchor,child:new Sp0({type:F0.type,title:i4,threadID:F0.threadID,labelColor:z1,mutedColor:V.mutedForeground,foregroundColor:V.foreground,onNavigate:(E8)=>this.switchToExistingThread(E8)})}))}s.push(a,new R0({height:1,child:new i0({padding:C0.horizontal(1),child:r})}));let z0=new u0({crossAxisAlignment:"stretch",mainAxisSize:"max",children:s}),q0=new c0({constraints:M1.tight(Q.size.width,Q.size.height),decoration:new v4(V.background),child:z0}),Q0=new s4(()=>{if(this.isShowingPalette)return this.dismissPalette(),"handled";if(this.isShowingMCPStatusModal)return this.setState(()=>{this.isShowingMCPStatusModal=!1}),"handled";if(this.pendingAuthLogin)return this.cancelAuthLoginSession(),"handled";if(this.pendingOAuthRequest){let L4=this.pendingOAuthRequest;return this.setState(()=>{this.pendingOAuthRequest=null}),L4.reject(Error("OAuth authorization cancelled")),"handled"}if(this.isShowingPromptHistoryPicker)return this.setState(()=>{this.isShowingPromptHistoryPicker=!1}),"handled";if(this.pendingMCPServers.length>0)return this.widget.dependencies.mcpTrustHandler.deny(),"handled";if(this.getCurrentEphemeralError())return this.handleEphemeralErrorResponse("dismiss"),"handled";if(this.displayMessage)return this.handleDisplayMessageDismiss(),"handled";if(this.isShowingHelp)return this.setState(()=>{this.isShowingHelp=!1}),"handled";if(this.isShowingContextAnalyzeModal)return this.setState(()=>{this.isShowingContextAnalyzeModal=!1,this.contextAnalyzeDeps=null,this.contextAnalyzeFromDTW=null}),"handled";if(this.isShowingSkillListModal)return this.setState(()=>{this.isShowingSkillListModal=!1}),"handled";if(this.isShowingFileChangesOverlay)return this.setState(()=>{this.isShowingFileChangesOverlay=!1}),"handled";if(this.isShowingContextDetailOverlay)return this.setState(()=>{this.isShowingContextDetailOverlay=!1}),"handled";if(this.isShowingIdePicker)return this.dismissIdePicker(),"handled";if(this.isShowingJetBrainsInstaller)return this.dismissJetBrainsInstaller(),"handled";if(this.isShowingConfirmationOverlay)return this.setState(()=>{this.isShowingConfirmationOverlay=!1,this.confirmationOverlayContent=""}),"handled";if(this.isShowingConsoleOverlay)return this.setState(()=>{this.isShowingConsoleOverlay=!1}),"handled";if(this.dismissTopAdModal())return"handled";if(this.handoffState.countdownSeconds!==null)return this.handoffController?.stopCountdown(),"handled";if(this.handoffState.isInHandoffMode){if(this.handoffState.isGeneratingHandoff)this.handoffController?.cancelGeneration();else this.exitHandoffMode();return"handled"}if(this.isInQueueMode)return this.exitQueueMode(),"handled";if(this.textController.hasSelection)return this.textController.clearSelection(),"handled";if(this.isConfirmingClearInput){if(this.textController.clear(),this.textController.resetScrollOffset(),this.widget.dependencies.activeThreadHandle.clearPendingSkills(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.handoffState.isConfirmingAbortHandoff&&this.handoffController){let L4=this.handoffController.getPendingPrompt(),T4=this.imageAttachments;return this.textController.clear(),this.textController.resetScrollOffset(),this.widget.dependencies.activeThreadHandle.clearPendingSkills(),this.setState(()=>{this.imageAttachments=[]}),this.handoffController.confirmAbort().then((i4)=>{if(i4&&L4)this.textController.text=L4,this.handoffController?.clearPendingPrompt();if(i4&&T4.length>0)this.setState(()=>{this.imageAttachments=T4})}),"handled"}if(this.isConfirmingCancelProcessing){if(this.bashInvocations.length>0)this.cancelBashInvocations();if(this.cancelStreamingMessage().catch((L4)=>{j.error("Failed to cancel streaming message:",L4)}),this.setState(()=>{this.isConfirmingCancelProcessing=!1}),this.cancelProcessingConfirmTimeout)clearTimeout(this.cancelProcessingConfirmTimeout),this.cancelProcessingConfirmTimeout=null;return"handled"}if(this.executingCommand)return j.info("Canceling executing command:",this.executingCommand.name),this.executingCommand.abortController.abort(),"handled";if(this.bashInvocations.length>0||this.isProcessing()){if(this.setState(()=>{this.isConfirmingCancelProcessing=!0}),this.cancelProcessingConfirmTimeout)clearTimeout(this.cancelProcessingConfirmTimeout);return this.cancelProcessingConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingCancelProcessing=!1}),this.cancelProcessingConfirmTimeout=null},1000),"handled"}if(this.handoffController?.getEmptyHandoffParentThreadID(this.widget.dependencies.threadState.mainThread))return this.handoffController.startAbortConfirmation(),"handled";if(this.textController.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"ignored"}),H0=new s4(()=>{return this.onExitPressed(),"handled"}),i=new s4(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),n=new s4(()=>{return this.setState(()=>{this.isShowingMCPStatusModal=!this.isShowingMCPStatusModal}),"handled"}),e=new s4(()=>{if(r9.instance.toggleAll(),D.mainThread?.agentMode==="deep"||D.mainThread?.agentMode==="internal")UJ.instance.toggleAll();return"handled"}),J0=new s4(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";return this.setState(()=>{this.isShowingPromptHistoryPicker=!0}),"handled"}),Z0=new s4(()=>{return l4.instance.toggleFrameStatsOverlay(),"handled"}),K0=new s4(()=>{return l4.instance.tuiInstance.getScreen().markForRefresh(),H6.instance.requestFrame(),"handled"}),t=new s4(()=>{return this.toggleAgentMode(),"handled"}),V0=new s4(()=>{return this.toggleDeepReasoningEffort(),"handled"}),N0=new s4(()=>{let L4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:T4}=this.widget.dependencies,i4=T4.mainThread?.id;return i4?this.getMessageScrollController(i4):null})();if(L4){let T4=Math.max(Math.floor(Q.size.height*0.4),10),i4=Q.size.height-T4;L4.animatePageUp(i4,100)}return"handled"}),D0=new s4(()=>{let L4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:T4}=this.widget.dependencies,i4=T4.mainThread?.id;return i4?this.getMessageScrollController(i4):null})();if(L4){let T4=Math.max(Math.floor(Q.size.height*0.4),10),i4=Q.size.height-T4;L4.animatePageDown(i4,100)}return"handled"}),O0=new s4(()=>{let L4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:T4}=this.widget.dependencies,i4=T4.mainThread?.id;return i4?this.getMessageScrollController(i4):null})();if(L4){let T4=Math.max(Math.floor(Q.size.height*0.4),10),i4=Q.size.height-T4;L4.animatePageUp(Math.floor(i4/2),100)}return"handled"}),_0=new s4(()=>{let L4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:T4}=this.widget.dependencies,i4=T4.mainThread?.id;return i4?this.getMessageScrollController(i4):null})();if(L4){let T4=Math.max(Math.floor(Q.size.height*0.4),10),i4=Q.size.height-T4;L4.animatePageDown(Math.floor(i4/2),100)}return"handled"}),e0=new s4(()=>{let L4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:T4}=this.widget.dependencies,i4=T4.mainThread?.id;return i4?this.getMessageScrollController(i4):null})();if(L4)L4.animateTo(0,100);return"handled"}),a0=new s4(()=>{let L4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:T4}=this.widget.dependencies,i4=T4.mainThread?.id;return i4?this.getMessageScrollController(i4):null})();if(L4)L4.animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),F1=new s4(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";if(this.handoffState.isInHandoffMode)return"ignored";if(this.isInQueueMode)return"ignored";let{threadState:z1}=this.widget.dependencies;if(!z1.mainThread?.messages.some((T4)=>T4.role==="user"||VF(T4)))return"ignored";return this.setState(()=>{this.isMessageViewInSelectionMode=!0}),"handled"}),a1=new s4((z1)=>{if(z1.direction==="previous")this.navigateHistoryPrevious();else this.navigateHistoryNext();return"handled"}),o1=new s4(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";return H$0().then(async(z1)=>{if(z1)await this.handleInsertImage(z1)}),"handled"}),m0=new Map([[Y4.ctrl("c"),new Ep],[Y4.ctrl("l"),new Ip],[Y4.ctrl("o"),new q$0],[Y4.ctrl("v"),new Np],[Y4.alt("s"),new HT],[Y4.ctrl("s"),new HT],[Y4.alt("p"),new Ap],[Y4.ctrl("r"),new Cp],[Y4.alt("t"),new Mp],[Y4.ctrl("t"),new Rp],[Y4.key("PageUp"),new V$0],[Y4.key("PageDown"),new K$0],[Y4.alt("k"),new z$0],[Y4.alt("j"),new G$0],[Y4.key("Home"),new F$0],[Y4.key("End"),new U$0],[Y4.key("Escape"),new Op],[Y4.ctrl("p"),new BT("previous")],[Y4.ctrl("n"),new BT("next")],[Y4.key("Tab"),new fp]]);if(m0.set(Y4.alt("d"),new jp),!a9())m0.set(Y4.key("ArrowUp"),new fp);if(!1)m0.set(Y4.alt("c"),new Lp);let t0=new s4(()=>{if(this.isShowingStandalonePalette())return"handled";return this.showCommandPalette(),"handled"}),A1=new s4(()=>{return this.toggleThreadPickerWorkspaceFilter(),"handled"}),$4=new s4(()=>{if(this.mysteriousMessage)this.handleShowMysteryModal();return"handled"}),D6=new Map([[Op,Q0],[Ip,K0],[HT,t],[jp,V0],[q$0,t0],[Np,o1],[Lp,i],[N20,n],[Mp,e],[Ap,Z0],[Rp,A1],[Cp,J0],[Ep,H0],[V$0,N0],[K$0,D0],[z$0,O0],[G$0,_0],[F$0,e0],[U$0,a0],[fp,F1],[BT,a1],[Pp,$4]]),m1=[q0];if(this.splashOrbExplosion){let z1=rg(this.getEffectiveAgentMode());m1.push(new id0({key:new $3(`splash-orb-explosion-${this.splashOrbExplosion.seq}`),originX:this.splashOrbExplosion.originX,originY:this.splashOrbExplosion.originY,sparkleColors:[z1,V.warning],onComplete:this.handleSplashOrbExplosionComplete}))}if(A||I)m1.push(new l1({child:new iV({message:this.threadInitializationMessage??"Loading thread..."})}));if(this.isShowingConsoleOverlay)m1.push(new jp0);if(this.isShowingHelp&&this.paletteConfig)m1.push(new vp0({commands:this.getPaletteCommands().getAllCommands(),submitOnEnter:this.submitOnEnter}));if(this.isShowingContextAnalyzeModal){let{configService:z1}=this.widget.dependencies,L4=this.widget.dependencies.threadState.mainThread,T4=this.contextAnalyzeDeps,i4=this.contextAnalyzeFromDTW;if(L4&&(T4||i4)){let E8=T4?{configService:z1,agentModeOverride:this.getEffectiveAgentMode(),buildSystemPromptDeps:T4}:null;m1.push(new Rp0({deps:E8,thread:L4,dtwAnalyze:i4??void 0,onDismiss:()=>{this.setState(()=>{this.isShowingContextAnalyzeModal=!1,this.contextAnalyzeDeps=null,this.contextAnalyzeFromDTW=null})}}))}else this.setState(()=>{this.isShowingContextAnalyzeModal=!1,this.contextAnalyzeDeps=null,this.contextAnalyzeFromDTW=null})}if(this.isShowingSkillListModal&&!this.isShowingPalette)Promise.all([this.widget.dependencies.skillService.getSkills(),this.widget.dependencies.skillService.getSkillErrors(),this.widget.dependencies.skillService.getSkillWarnings()]).then(([z1,L4,T4])=>{if(this.isShowingSkillListModal&&this.mounted)this.skillListData={skills:z1,errors:L4,warnings:T4},this.setState()}),m1.push(new rd0({skills:this.skillListData?.skills??[],errors:this.skillListData?.errors??[],warnings:this.skillListData?.warnings??[],cwd:process.cwd(),onDismiss:()=>{this.setState(()=>{this.isShowingSkillListModal=!1,this.skillListData=null})},onAddSkill:()=>{this.showCommandPalette({type:"standalone",commandId:"skill-add",onSubmit:()=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null,this.isShowingSkillListModal=!1,this.skillListData=null})},onCancel:()=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null})}})},onDocs:()=>{fX("https://ampcode.com/manual#agent-skills")},onInsertPrompt:(z1)=>{this.setState(()=>{this.isShowingSkillListModal=!1,this.skillListData=null,this.textController.text=z1})},onInvokeSkill:(z1)=>{this.widget.dependencies.activeThreadHandle.addPendingSkill({name:z1})}}));if(this.isShowingMCPStatusModal)m1.push(new sp0({servers:this.mcpServers,onDismiss:()=>{this.setState(()=>{this.isShowingMCPStatusModal=!1})}}));if(this.isShowingPromptHistoryPicker)m1.push(new nd0({entries:this.widget.dependencies.history.getAll(),currentCwd:process.cwd(),onAccept:(z1)=>{this.setState(()=>{this.isShowingPromptHistoryPicker=!1,this.textController.text=z1,this.textController.cursorPosition=z1.length})},onDismiss:()=>{this.setState(()=>{this.isShowingPromptHistoryPicker=!1})}}));if(this.isShowingMysteriousMessageModal&&this.mysteriousMessage)m1.push(new cd0({message:this.mysteriousMessage,onDestruct:this.handleDestructMysteriousMessage}));if(this.isShowingForkDeprecationModal)m1.push(new Tp0({onDismiss:this.dismissForkDeprecationModal}));for(let z1=0;z1<this.adModalStack.length;z1++){let L4=this.adModalStack[z1],T4=z1===this.adModalStack.length-1;if(L4==="adAction"&&this.adActionModal)m1.push(new ig0({key:new $3(`ad-action-modal-${T4?"top":"back"}`),title:this.adActionModal.title??"Failed to open browser",message:this.adActionModal.url,showCopyOption:this.adActionModal.showCopyOption,onSelect:async(i4)=>{let E8=this.adActionModal.url;if(i4==="copy")try{await l4.instance.tuiInstance.clipboard.writeText(E8),this.setState(()=>{this.displayMessage=new W$("Link copied to clipboard")})}catch(L7){j.error("Failed to copy to clipboard",{error:L7}),this.setState(()=>{this.displayMessage=Error("Failed to copy to clipboard")})}this.setState(()=>{this.adActionModal=null,this.removeAdModalFromStack("adAction")})}}));if(L4==="adInfo"&&this.adInfoModal)m1.push(new ng0({key:new $3(`ad-info-modal-${T4?"top":"back"}`),provider:this.adInfoModal.provider,onClose:()=>{this.setState(()=>{this.adInfoModal=null,this.removeAdModalFromStack("adInfo")})}}))}if(this.pendingMCPServers.length>0){let{mcpTrustHandler:z1}=this.widget.dependencies;m1.push(new tp0({servers:this.pendingMCPServers,onAlwaysTrust:z1.trustAlways.bind(z1),onTrustOnce:z1.trustOnce.bind(z1),onOpenSettings:this.handleMCPTrustOpenSettings,onDismiss:z1.deny.bind(z1)}))}if(this.pendingAuthLogin)m1.push(new ag0({manualURL:this.pendingAuthLogin.manualURL,isAuthenticating:this.pendingAuthLogin.isAuthenticating||this.pendingAuthLogin.isOpeningBrowser,errorMessage:this.pendingAuthLogin.errorMessage}));if(this.pendingOAuthRequest)m1.push(new ld0({request:this.pendingOAuthRequest,onDismiss:()=>{this.setState(()=>{this.pendingOAuthRequest=null})}}));if(this.pendingInputDialog){let z1=this.pendingInputDialog;m1.push(new xp0({options:z1.options,onSubmit:(L4)=>{this.setState(()=>{this.pendingInputDialog=null}),z1.resolve(L4)},onCancel:()=>{this.setState(()=>{this.pendingInputDialog=null}),z1.resolve(void 0)}}))}if(this.pendingConfirmDialog){let z1=this.pendingConfirmDialog;m1.push(new Mp0({options:z1.options,onConfirm:()=>{this.setState(()=>{this.pendingConfirmDialog=null}),z1.resolve(!0)},onCancel:()=>{this.setState(()=>{this.pendingConfirmDialog=null}),z1.resolve(!1)}}))}if(this.isShowingFileChangesOverlay)m1.push(new mg0({threadData:D}));if(this.isShowingContextDetailOverlay){let z1=this.threadCostInfo?.costBreakdownURL;m1.push(new Pp0({tokenUsage:f??void 0,costInfo:this.threadCostInfo,onDismiss:()=>{this.setState(()=>{this.isShowingContextDetailOverlay=!1})},onOpenCostBreakdown:z1?()=>{w8(J,z1)}:void 0}))}if(this.isShowingConfirmationOverlay)m1.push(new Ap0({details:this.confirmationOverlayContent}));if(this.imagePreview!==null)m1.push(new l1({child:new up0({image:this.imagePreview.image,imageIndex:this.imagePreview.index,onDismiss:this.handleImagePreviewDismiss,onRemove:this.handleImagePreviewRemove})}));if(this.fileImagePreviewPath!==null)m1.push(new l1({child:new Up({filePath:this.fileImagePreviewPath,onDismiss:this.handleFileImagePreviewDismiss})}));if(this.painterImagePreview!==null)m1.push(new l1({child:new Up({filePath:this.painterImagePreview.filePath,onDismiss:this.handlePainterImagePreviewDismiss})}));if(this.painterSaveDialog!==null)m1.push(new l1({child:new Up({filePath:this.painterSaveDialog.filePath,imageBlock:this.painterSaveDialog.image,onDismiss:this.handlePainterSaveDialogDismiss})}));if(this.skillPreview!==null){let z1=this.pendingSkills[this.skillPreview.skillIndex];if(z1)m1.push(new l1({child:new sd0({pendingSkill:z1,skill:this.cachedSkillForPreview,onDismiss:this.handleSkillPreviewDismiss,onRemove:this.skillPreview.onRemove})}))}let y4=this.getCommandPaletteContext(J);if(y4&&this.isShowingPalette&&this.paletteConfig)m1.push(new l1({child:new Ep0({commandContext:y4,mainThread:D.mainThread,commands:this.getPaletteCommands(),onDismiss:this.dismissPalette,showOptions:this.paletteShowOptions??void 0})}));if(this.isShowingIdePicker)m1.push(new yp0({onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection}));let b4=new i6({children:m1});if(this.isShowingJetBrainsInstaller)return new uL({child:new S9({actions:D6,child:new C2({shortcuts:m0,debugLabel:"jetbrains-installer-shortcuts",child:new op0({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});let H4=this.widget.dependencies.threadState.mainThread?.id,S5=1+(this.bottomGridUserHeight??5)+1,X6=!this.isShowingPalette&&!this.isShowingIdePicker;return new tT({switchToThread:(z1)=>this.switchToExistingThread(z1),child:new HG({threadViewStates:this.getThreadViewStatesSnapshot(),threadTitles:this.threadTitles,threadSummaries:this.threadsForPicker,child:new _p0({getThreadCluster:this.getCurrentThreadClusterForMinimap,parentThreadID:F0?.threadID,anchorLink:F0?this.parentThreadLinkAnchor:void 0,bottomOffset:S5,enabled:X6,child:new xT({onShowImagePreview:this.handleShowFileImagePreview,child:new fT({onShowImagePreview:this.handleShowPainterImagePreview,onShowSaveDialog:this.handleShowPainterSaveDialog,child:new rY({controller:this.toastController,child:new uL({child:new Ad0({getThreadCluster:this.getThreadClusterForMinimap,currentThreadID:H4,enabled:X6,child:new rH({enabled:X6,child:new f70({controller:this.toastController,child:new S9({actions:D6,child:new C2({shortcuts:m0,debugLabel:"main-app-shortcuts",child:b4})})})})})})})})})})})})}buildScrollableTodoList(J,Z,Q){return new cM4({todos:J,enabled:Z,controller:this.todoScrollController,appTheme:Q})}buildBottomWidget(J,Z,Q,Y,X,V,K,z,G,F,U){if(J)return new Cp0({error:J,options:{freeTierEnabled:this.freeTierStatus.canUseAmpFree},onResponse:this.handleEphemeralErrorResponse});if(Z){if(this.displayMessage)this.handleDisplayMessageDismiss();return new Ip0({confirmationRequest:Z,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new ep0({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let q=this.handoffState.isInHandoffMode||!this.widget.dependencies.activeThreadHandle.invokeBashTool?[]:N$0(Y),D=this.agentModeController?.isInRestrictedFreeMode()??!1,W=this.isTextfieldAndAutocompleteFocused&&!D&&!this.isShowingStandalonePalette()&&!this.handoffState.isGeneratingHandoff;if(W&&!this.hasReplayedEarlyInput){this.hasReplayedEarlyInput=!0;let t=l4.instance.tuiInstance.getEarlyInputText();if(t)this.textController.insertText(t)}let H=this.submitOnEnter?{character:"Enter"}:{character:"Enter",modifiers:{meta:!0}},B=new Ud({key:this.textFieldKey,controller:this.textController,triggers:[new YB],completionBuilder:this.getCompletionBuilder(),onSubmitted:(t)=>{this.onTextSubmitted(t).catch((V0)=>{this.handleSubmitFlowError(V0)})},submitKey:H,theme:Q,placeholder:D?"Amp Free is not enabled. Press Ctrl+S to switch modes.":void 0,enabled:W,shellPromptRules:q,focusNode:this.autocompleteFocusNode,autofocus:!this.isMessageViewInSelectionMode&&!this.isShowingStandalonePalette()&&!this.isShowingIdePicker&&!this.isShowingSkillListModal,clipboard:l4.instance.tuiInstance.clipboard,onCopy:this._handleTextCopy.bind(this),onInsertImage:this.handleInsertImage,imageAttachments:this.imageAttachments,popImage:this.handlePopImage,onImageClick:this.handleImageClick,previousThreadId:this.previousThreadIdForHint&&(X.mainThread?.messages.length??0)===0?this.previousThreadIdForHint:void 0,onPreviousThreadHintAccepted:()=>{let t=this.previousThreadIdForHint;if(t)this.setState(()=>{this.previousThreadIdForHint=null}),this.textController.text=`following: @${t} `},onDoubleAtTrigger:(t)=>{this.handleDoubleAtTrigger(t)},pendingSkills:this.pendingSkills,onClearPendingSkill:(t)=>{this.widget.dependencies.activeThreadHandle.removePendingSkill(t)},popSkill:()=>{let t=this.pendingSkills[this.pendingSkills.length-1];if(t)this.widget.dependencies.activeThreadHandle.removePendingSkill(t.name)},onSkillClick:this.handleSkillClick,topWidget:this.isShowingShortcutsHelp?new od0({submitOnEnter:this.submitOnEnter}):void 0}),w=X.mainThread?.queuedMessages??[],N=Array.isArray(V)&&V.length>0,O=Array.isArray(w)&&w.length>0,E=this.widget.dependencies.threadPool,L=E.isDTWMode?.()===!0,M=O?new ad0({queuedMessages:w,onInterruptQueuedMessage:L?(t)=>this.widget.dependencies.activeThreadHandle.interruptQueuedMessage?.(t):void 0}):void 0,A=N?this.buildScrollableTodoList(V,this.isTextfieldAndAutocompleteFocused&&!D,Y):void 0,I=[],P=null,_=0,S=F.capabilities.emojiWidth,y=L?E.getTransportConnectionState?.():void 0;if(L&&y!==void 0)I.push({child:new $0({text:new C(`(dtw: ${y})`,new h({color:Q.mutedForeground,dim:!0}))}),position:"top-left"});let m=this.currentShellModeStatus;if(m)I.push({child:new $0({text:new C(m==="hidden"?"shell mode (incognito)":"shell mode",new h({color:m==="hidden"?Y.app.shellModeHidden:Y.app.shellMode}))}),position:"top-left"});if(this.handoffState.isInHandoffMode){let t=new h({color:Y.app.handoffMode}),V0=this.handoffState.isGeneratingHandoff&&this.handoffState.spinner?new C("",void 0,[new C("handoff ",t),new C(this.handoffState.spinner.toBraille(),t)]):new C("handoff (submit a goal for the new thread)",t);if(I.push({child:new $0({text:V0}),position:"top-left"}),this.handoffState.isGeneratingHandoff){let N0=new h({color:Q.foreground,dim:!0});I.push({child:new $0({text:new C("",void 0,[new C("Esc",new h({color:Y.app.keybind})),new C(" to cancel",N0)])}),position:"bottom-left"}),_=p5("Esc to cancel",S)}}if(this.handoffState.countdownSeconds!==null){let t=new h({color:Q.foreground,dim:!0}),V0=`Auto-submitting in ${this.handoffState.countdownSeconds}s`,N0=this.handoffState.countdownSeconds<10?1:0;I.push({child:new i0({padding:C0.only({right:N0}),child:new $0({text:new C(V0,new h({color:Y.app.handoffMode}))})}),position:"bottom-left"}),I.push({child:new $0({text:new C("",void 0,[new C("type",new h({color:Y.app.keybind})),new C(" to edit",t)])}),position:"bottom-left"}),_=p5("Auto-submitting in 10s",S)+2+p5("type to edit",S)}if(this.isInQueueMode){let t=new h({color:Y.app.queueMode});I.push({child:new $0({text:new C("queue",t)}),position:"top-left"})}let b=this.handoffController?.getEmptyHandoffParentThreadID(this.widget.dependencies.threadState.mainThread)??null,k=F.capabilities.animationSupport,f=k==="disabled"?0:k==="slow"?30:60,p=this.getEffectiveAgentMode(),l=rg(p),x=null,r=null,c=!1,s=this.agentModeController?.getVisibleModes()??[];if(!m&&!this.isInQueueMode&&s.length>1){let t=this.previewThread,V0=this.agentModeController?.getMode(),N0=t?t.agentMode??this.getEffectiveAgentMode():this.handoffState.isGeneratingHandoff&&V0?V0:this.getEffectiveAgentMode(),D0=this.formatAgentModeLabel(N0),O0=N0==="smart"&&this.anthropicSpeed==="fast",_0=rb(this.openAISpeed,y6(this.authStatus)?this.authStatus.features:this.tuiContext.features),e0=uK(N0)&&_0==="fast",a0=O0?"+fast(6x$)":e0?"+fast(2x$)":void 0,F1=a0?`${D0}${a0}`:D0,a1=rg(N0),o1=t??this.widget.dependencies.threadState.mainThread,m0=o1?W3(o1)>0:!1,V1="top-right";if(t){x=p5(F1,S);let t0=a0?new C("",void 0,[new C(D0,new h({color:a1})),new C(a0,new h({color:Q.warning}))]):new C(D0,new h({color:a1}));I.push({child:new $0({text:t0}),position:"top-right"})}else{let t0=!m0&&!this.handoffState.isGeneratingHandoff,A1=this.handoffState.isGeneratingHandoff,$4=new h({color:a1,dim:A1}),D6=new $0({text:a0?new C("",void 0,[new C(D0,$4),new C(a0,new h({color:Q.warning,dim:A1}))]):new C(D0,$4)}),m1=p5(F1,S),y4=t0?new n1({child:D6,onClick:()=>this.toggleAgentMode(),cursor:"pointer"}):D6,b4=[];if(x=m1,N0==="deep"&&!m0&&!this.handoffState.isGeneratingHandoff&&this.deepModeEffortHintController.isVisibleOrFalling()){let X4=this.deepModeEffortHintController.getHintWidth(S),S5=3;c=this.deepModeEffortHintController.isVisible()&&this.deepModeEffortHintController.isShimmering();let X6=this.deepModeEffortHintController.isVisible()&&!c?new $0({text:this.deepModeEffortHintController.buildVisibleTextSpan(Q.foreground)}):new R0({width:X4});b4.push(X6,new R0({width:3})),x+=X4+3,r=Q.foreground}if(b4.push(y4),this.showSkillsCountInPromptBar){let X4=this.availableSkillCountReady?this.availableSkillCount:this.widget.dependencies.skillService.listInstalled().length,S5=this.skillWarningCount>0||this.skillErrorCount>0,z1=`${S5?"⚠ ":""}${X4} ${m4(X4,"skill")}`,L4=2,T4=p5(z1,S);x+=2+T4;let i4=new h({color:S5?Q.warning:Q.foreground,dim:!S5});b4.push(new R0({width:2}),new n1({child:new $0({text:new C(z1,i4)}),onClick:()=>{this.setState(()=>{this.isShowingSkillListModal=!0})},cursor:"pointer"}))}I.push({child:new U1({mainAxisSize:"min",children:b4}),position:"top-right"})}}let a=f>0&&this.agentModePulseSeq>0&&!m&&!this.isInQueueMode&&!b&&s.length>1,F0=[];if(a){let V0=p2(p)?.uiHints?.fasterAnimation?3:1,N0=(x??0)+1,D0=N0>0?2+N0:1,O0=new x6({top:0,left:1,right:D0,height:1,child:new rp0({color:l,backgroundColor:Q.background,trigger:this.agentModePulseSeq,fps:f,speed:V0,trail:5,leftOffset:0,direction:"right-to-left"})});F0.push(O0)}if(c&&r&&x!==null){let t=this.deepModeEffortHintController.buildShimmerOverlay(x,r);if(t)F0.push(t)}if(this.deepModeEffortHintController.isFalling()&&r&&x!==null){let t=this.deepModeEffortHintController.buildFallingOverlay(x,r);if(t)F0.push(t)}if(F0.length>0)P=new x6({top:0,left:0,right:0,bottom:0,child:new i6({children:F0})});if(b&&this.handoffState.countdownSeconds===null){let t=this.handoffState.isConfirmingAbortHandoff?" again to abort ":" to abort ";I.push({child:new $0({text:new C("",void 0,[new C("Esc",new h({color:Y.app.keybind})),new C(t,new h({color:Q.foreground,dim:!0})),new C("handoff",new h({color:Y.app.handoffMode}))])}),position:"bottom-left"}),_=p5(`Esc${t}handoff`,S)}if(!b&&this.previousThreadIdForHint&&(X.mainThread?.messages.length??0)===0&&this.textController.text.trim()==="")I.push({child:new $0({text:new C("",void 0,[new C("press ",new h({color:Q.foreground,dim:!0})),new C("enter",new h({color:Y.app.keybind})),new C(" to reference the previous thread",new h({color:Q.foreground,dim:!0}))])}),position:"bottom-left"}),_=p5("press enter to reference the previous thread",S);let q0=X.mainThread?.env?.initial.trees?.[0]?.uri,Q0;if(q0)Q0=K1.parse(q0).fsPath;else Q0=process.cwd();let H0=this.toHomeRelative(Q0),i=this.shorten(H0),n=_>0?F.size.width-_-6:F.size.width-4,e=this.buildDisplayText(i,this.currentGitBranch||void 0,n,S);I.push({child:new $0({text:new C(e,new h({color:Q.foreground,dim:!0}))}),position:"bottom-right"});let J0=this.previewThread,Z0=this.widget.dependencies.threadState.mainThread;if((Z0?W3(Z0)>0:!1)&&!m&&!this.handoffState.isInHandoffMode&&!J0){let t=[],V0=new h({color:Q.foreground,dim:!0}),N0=new C(" · ",V0);if(G){let a0=G.totalInputTokens/G.maxInputTokens,F1=Math.round(a0*100),a1=Math.max(0,Math.min(F1,100)),o1=E$0(a0,G.maxInputTokens),m0=V0;if(o1==="danger")m0=new h({color:Q.destructive});else if(o1==="warning")m0=new h({color:Q.warning});else if(o1==="recommendation")m0=new h({color:Y.app.recommendation});if(t.length>0)t.push(N0);if(G.maxInputTokens>=1000){let V1=Math.round(G.maxInputTokens/1000);t.push(new C(`${a1}% of ${V1}k`,m0))}else t.push(new C(`${a1}%`,m0))}if(U&&this.threadCostInfo){let a0=nC(this.threadCostInfo,{colors:{foreground:Q.foreground},dim:!0});if(a0.length>0){if(t.length>0)t.push(N0);t.push(...a0)}}let D0=X.viewState,O0=D0.state==="active"?D0.turnStartTime:void 0,_0=D0.state==="active"?D0.turnElapsedMs:void 0,e0=null;if(X.mainThread?.agentMode==="deep"){let a0=O0?Date.now()-O0:_0;if(a0!==void 0){let F1=ru1(a0);e0=new $0({text:new C(F1,V0)})}}if(t.length>0||e0){let a0=[];if(t.length>0){let F1=new $0({text:new C("",void 0,t)});a0.push(U?new n1({child:F1,onClick:this.showContextDetailOverlay,cursor:"pointer"}):F1)}if(e0){if(t.length>0)a0.push(new $0({text:new C(" · ",V0)}));a0.push(e0)}I.push({child:new U1({mainAxisSize:"min",children:a0}),position:"top-left"})}}return new og0({leftChild:new T1({child:B}),rightChild1:M,rightChild2:A,maxHeight:K,overlayTexts:I,overlayLayer:P,backgroundColor:Q.background,borderColor:D||!this.isTextfieldAndAutocompleteFocused||this.handoffState.isGeneratingHandoff?Q.border:void 0,hasBanner:z,userHeight:this.bottomGridUserHeight,onInitializeHeight:(t)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(t,K)})},onDrag:(t)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(t.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let V0=Math.floor(t.localPosition.y)-this.bottomGridDragStartY,N0=Math.max(4,this.bottomGridDragStartHeight-V0),D0=Math.min(N0,K),O0=Math.floor(D0);if(this.bottomGridUserHeight!==O0)this.setState(()=>{this.bottomGridUserHeight=O0})},onDragRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null},enableResize:!z})}}function dM4(J){return J.resolvedTokenUsage}class cM4 extends d0{props;constructor(J){super();this.props=J}createState(){return new lM4}}class lM4 extends p0{viewportHeight=1;scrollListenerAttached=!1;initState(){if(!this.scrollListenerAttached)this.widget.props.controller.addListener(()=>{this.updateViewportHeight()}),this.scrollListenerAttached=!0}build(J){let{todos:Z,controller:Q,appTheme:Y}=this.widget.props;return new U1({crossAxisAlignment:"stretch",children:[new T1({child:new j6({controller:Q,autofocus:!1,child:new Zc0({todos:Z})})}),new u8({controller:Q,thumbColor:Y.app.scrollbarThumb,trackColor:Y.app.scrollbarTrack,getScrollInfo:()=>{let{maxScrollExtent:X,offset:V}=Q,K=this.viewportHeight,z=X+K;return{totalContentHeight:Math.max(z,0),viewportHeight:Math.max(K,1),scrollOffset:Math.max(V,0)}}})]})}updateViewportHeight(){let J=this.getViewportHeight();if(J!==this.viewportHeight)this.viewportHeight=J}getViewportHeight(){let J=this.context.findRenderObject();if(!J)return this.viewportHeight;let Z=(Y,X=0)=>{if(Y&&"size"in Y&&"children"in Y){let V=Y.children||[];for(let K of V){if(K&&"size"in K){let G=K.size;if(typeof G?.height==="number"&&G.height>0)return G.height}let z=Z(K,X+1);if(z>0)return z}}return 0},Q=Z(J);if(Q>0)return Q;if("size"in J){let Y=J.size;if(typeof Y?.height==="number"&&Y.height>0)return Y.height}return this.viewportHeight}}class iM4 extends d1{props;constructor(J){super();this.props=J}build(J){return new n1({child:new R0({height:1}),cursor:E5.NS_RESIZE,onDrag:(Z)=>{if(this.props.userHeight===void 0){let Y=J.findRenderObject()?.size.height??0;if(Y>0){this.props.onInitializeHeight(Y);return}}this.props.onDrag(Z)},onRelease:this.props.onRelease})}}function aM4(J){let Z=J.split(`
7501
7501
  `);try{return Z.map((Q)=>{let Y=Q.indexOf(":");if(Y===-1)return{label:"",content:nM4(Q)};let X=Q.slice(0,Y+1),V=Q.slice(Y+1);return{label:X,content:nM4(V)}})}catch(Q){return Z.map((Y)=>({label:"",content:[{type:"text",text:Y}]}))}}function nM4(J){let Z=[],Q=/(\+?\$[\d,.]+(?:\/\$[\d,.]+)?(?:\/hour)?)|(\busage paid\b|\bpaid\b)|(\s-\s(?=https?:\/\/))|((https?:\/\/)[^\s]+)|([^$\s][^\s]*)/gi,Y,X=0;while((Y=Q.exec(J))!==null){if(Y.index>X){let U=J.slice(X,Y.index);if(U)Z.push({type:"text",text:U})}let[V,K,z,G,F]=Y;if(K)Z.push({type:"amount",text:K});else if(z)Z.push({type:"paid",text:z});else if(G);else if(F)Z.push({type:"url",text:F});else{let U=V.replace(/\s+\)/g,")");Z.push({type:"text",text:U})}X=Q.lastIndex}if(X<J.length){let V=J.slice(X);if(V)Z.push({type:"text",text:V})}return Z}h$();async function Cs5(J){return aM4(J).map((Z)=>{let Q=Z.content.map((Y)=>{switch(Y.type){case"amount":case"paid":return Z1.bold.green(Y.text);case"url":return Z1.dim(" - ")+Z1.blue.underline(Y.text);default:return Z1.dim(Y.text)}}).join("");if(Z.label)return Z1.bold(Z.label)+Q;return Q}).join(`
7502
7502
  `)}function oM4(J,Z){J.command("usage").description("Show your current Amp usage and credit balance").action(async(Q,Y)=>{let X=Y.optsWithGlobals(),V=await Z(X),K=await V.settings.get("proxy"),z=qj1({settings:{url:V.ampURL,proxy:K},secrets:{getToken:(F,U)=>V.secrets.get(F,U)}}),G=await A6.userDisplayBalanceInfo({},{config:z});if(!G.ok){if(G.error.code==="auth-required")process.stderr.write(Z1.red("Error: ")+"You must be logged in to view usage. Run `amp login` first.\n"),process.exit(1);process.stderr.write(Z1.red("Error: ")+G.error.message+`
7503
7503
  `),process.exit(1)}process.stdout.write(await Cs5(G.result.displayText)+`
7504
7504
  `),process.exit(0)})}var a13=wB.join(y$,"logs","headless.log"),Sl0=wB.join(vC,"device-id.json");async function o13(){for(let J of GN)try{if((await J.listConfigs()).length>0)return J}catch(Z){j.debug("Failed to detect query-based IDE integration",{ideName:J.ideName,error:Z})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => D4(N_(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){E7.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
7505
- `)}function r13(J){process.emitWarning=(Z,Q,Y,X)=>{let V=typeof Z==="string"?Z:Z.message||String(Z),K=Q||"Warning",z=!1;J.warn(V,{name:K,code:Y})}}function O7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")u$("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")u$("experimental.agentMode",Z.mode)}function PR4(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 s13(J){try{return await jR4(J,"utf-8")}catch{return J}}async function vl0(J,Z,Q){let Y=PR4(J,Z);if(!Y)return;let X=y6(Q)?Q.features:[],V=y6(Q)?Q.user.email:void 0;if(!TR4(X,z2.HARNESS_SYSTEM_PROMPT)&&!CR4(V))throw new c1("You are not allowed to do this.",1);u$("systemPrompt",await s13(Y))}function CR4(J){return!!(J&&Ao(J))}function TR4(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function kl0(J){return(J.userEmail?vZ(J.userEmail):!1)||TR4(J.features,z2.DTW_TUI)}function wR4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new c1("This TUI mode is not enabled for your user;",1)}function yl0(J,Z){if(typeof J==="boolean")return J;if(!y6(Z))return!1;return kl0({userEmail:Z.user.email,features:Z.features})}function ul0(J){if(!y6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function t13(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 xl0(J){let Y=t13(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new c1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}var NR4=[{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??cY,description:`Custom settings file path (overrides the default location ${cY})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(j).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${hE})`},{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:a9(),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:xK.SMART.key,description:`Set the agent mode (${vX().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:vX().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:"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}],OR4=(J)=>("deprecated"in J)&&J.deprecated===!0,e13=(J)=>("hidden"in J)&&J.hidden===!0,$43=(J)=>("default"in J),J43=(J)=>("default"in J)?J.default:void 0,_R4=[{name:"toggle-skills-count",entryPoint:rx0}];function Z43(J,Z){let Q=Z.args[0],Y=Z.commands.map((V)=>V.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let V=Y.filter((z)=>Q.includes(z)||z.includes(Q)),K="Run amp --help for a list of available commands.";if(V.length>0)K=`Did you mean: ${V.join(", ")}? Or run amp --help for all commands.`;throw new c1(B8.unknownCommand(Q),1,K)}}async function bl0(J){return{...J,getThreadEnvironment:$J,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new JV(J.fileSystem),generateThreadTitle:r00,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>nJ(J.configService),pluginService:J.pluginService}}function SR4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:$J,filesystem:J.fileSystem,threadService:J.threadService}}var WZ0=K1.file(RR4.homedir()),fl0=process.env.XDG_CONFIG_HOME?K1.file(process.env.XDG_CONFIG_HOME):Y1.joinPath(WZ0,".config");function Q43(J){return y24({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){k24(Z);let Q=L90(),Y=wf0();if((!Q||Y||Ez4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(jU("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(jU("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(L90()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function Y43(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>v0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function k9(J,Z,Q){let Y=Q?.deferAuth??!1;Xj1("0.0.1773462612-g20fbe1");let X=Dr({storage:J.settings,secretStorage:J.secrets,workspaceRoots:v0.of([K1.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:WZ0,userConfigDir:fl0});Hz4(X);let V=await X.getLatest();j.debug("Global configuration initialized",{settingsKeys:Object.keys(V.settings)});let{toolService:K,dispose:z}=C24({configService:X}),G=new Map,F=()=>G.clear(),U=new rL0(X,J.settings.getWorkspaceRootPath()),q=Xm1({configService:X,filesystem:r6}),D=iu1({configService:X,trustStore:U,skillMCPServers:q.skillMCPServers,createOAuthProvider:async(w0,a,F0)=>{let z0=`${w0}:${a}`,q0=G.get(z0);if(q0)return j.debug("Reusing existing OAuth provider for server",{serverName:w0,serverUrl:a}),q0;j.debug("Creating OAuth provider for server",{serverName:w0,serverUrl:a});let Q0=(async()=>{let H0=new _N(J.secrets),i=await H0.getClientInfo(w0,a),n=F0?.scopes??i?.scopes,e=wV4();j.info("OAuth headless mode check",{useHeadless:e,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:p6.isTTY});let J0;if(e)J0=J.executeMode?BV4():HV4(w0);let Z0=new WL0({storage:H0,serverName:w0,serverUrl:a,clientId:F0?.clientId??i?.clientId,clientSecret:F0?.clientSecret??i?.clientSecret,authUrl:F0?.authUrl??i?.authUrl,tokenUrl:F0?.tokenUrl??i?.tokenUrl,scopes:n,headlessAuthHandler:J0});return j.debug("OAuth provider created",{serverName:w0,serverUrl:a,hasManualClientId:!!(F0?.clientId??i?.clientId),willUseDCR:!(F0?.clientId??i?.clientId),scopes:n,headlessMode:e,executeMode:J.executeMode}),Z0})();return G.set(z0,Q0),Q0}}),W=tv0({configService:X,filesystem:r6,spawn:e50}),H;if(J.executeMode){let w0=await f84({toolService:K,providers:[D,W],initialTimeout:15000});H=w0.registrations;for(let[a,F0]of w0.initErrors)j.warn(`${a} provider initialization slow or failed:`,F0)}else H=ev0({toolService:K,providers:[D,W]});if(Z.jetbrains)XN("JetBrains");else if(Z.ide&&eV4())XN("VS Code");else if(Z.ide&&$K4())XN("Neovim");else if(Z.ide){let w0=await o13();if(w0){let a=Mr(w0.ideName);if(a)XN(a)}}if(J.executeMode)Vj1(!0);let B,w=m8.status.pipe(D1((w0)=>Boolean(w0.connected&&w0.authenticated&&w0.ideName&&bj1(w0.ideName))),M4()).subscribe((w0)=>{if(w0){if(!B)B=K.registerTool(x84)}else B?.dispose(),B=void 0}),N;if(!J.executeMode){let w0=await J.settings.get("fuzzy.alwaysIncludePaths")??[];N=new k80(process.cwd(),{alwaysIncludePaths:w0},!0)}else N=new class extends k80{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let O=!1;{let w0=await J.secrets.get("apiKey",J.ampURL);if(O=Boolean(w0),j.info("API key lookup before login",{found:Boolean(w0),ampURL:J.ampURL,deferAuth:Y}),!w0)if(Y)j.info("No API key found, continuing startup with deferred auth");else{p6.write(`No API key found. Starting login flow...
7505
+ `)}function r13(J){process.emitWarning=(Z,Q,Y,X)=>{let V=typeof Z==="string"?Z:Z.message||String(Z),K=Q||"Warning",z=!1;J.warn(V,{name:K,code:Y})}}function O7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")u$("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")u$("experimental.agentMode",Z.mode)}function PR4(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 s13(J){try{return await jR4(J,"utf-8")}catch{return J}}async function vl0(J,Z,Q){let Y=PR4(J,Z);if(!Y)return;let X=y6(Q)?Q.features:[],V=y6(Q)?Q.user.email:void 0;if(!TR4(X,z2.HARNESS_SYSTEM_PROMPT)&&!CR4(V))throw new c1("You are not allowed to do this.",1);u$("systemPrompt",await s13(Y))}function CR4(J){return!!(J&&Ao(J))}function TR4(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function kl0(J){return(J.userEmail?vZ(J.userEmail):!1)||TR4(J.features,z2.DTW_TUI)}function wR4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new c1("This TUI mode is not enabled for your user;",1)}function yl0(J,Z){if(typeof J==="boolean")return J;if(!y6(Z))return!1;return kl0({userEmail:Z.user.email,features:Z.features})}function ul0(J){if(!y6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function t13(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 xl0(J){let Y=t13(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new c1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}var NR4=[{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??cY,description:`Custom settings file path (overrides the default location ${cY})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(j).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${hE})`},{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:a9(),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:xK.SMART.key,description:`Set the agent mode (${vX().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:vX().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:"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}],OR4=(J)=>("deprecated"in J)&&J.deprecated===!0,e13=(J)=>("hidden"in J)&&J.hidden===!0,$43=(J)=>("default"in J),J43=(J)=>("default"in J)?J.default:void 0,_R4=[{name:"toggle-skills-count",entryPoint:rx0}];function Z43(J,Z){let Q=Z.args[0],Y=Z.commands.map((V)=>V.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let V=Y.filter((z)=>Q.includes(z)||z.includes(Q)),K="Run amp --help for a list of available commands.";if(V.length>0)K=`Did you mean: ${V.join(", ")}? Or run amp --help for all commands.`;throw new c1(B8.unknownCommand(Q),1,K)}}async function bl0(J){return{...J,getThreadEnvironment:$J,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new JV(J.fileSystem),generateThreadTitle:r00,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>nJ(J.configService),pluginService:J.pluginService}}function SR4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:$J,filesystem:J.fileSystem,threadService:J.threadService}}var WZ0=K1.file(RR4.homedir()),fl0=process.env.XDG_CONFIG_HOME?K1.file(process.env.XDG_CONFIG_HOME):Y1.joinPath(WZ0,".config");function Q43(J){return y24({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){k24(Z);let Q=L90(),Y=wf0();if((!Q||Y||Ez4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(jU("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(jU("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(L90()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function Y43(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>v0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function k9(J,Z,Q){let Y=Q?.deferAuth??!1;Xj1("0.0.1773489712-g258ad5");let X=Dr({storage:J.settings,secretStorage:J.secrets,workspaceRoots:v0.of([K1.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:WZ0,userConfigDir:fl0});Hz4(X);let V=await X.getLatest();j.debug("Global configuration initialized",{settingsKeys:Object.keys(V.settings)});let{toolService:K,dispose:z}=C24({configService:X}),G=new Map,F=()=>G.clear(),U=new rL0(X,J.settings.getWorkspaceRootPath()),q=Xm1({configService:X,filesystem:r6}),D=iu1({configService:X,trustStore:U,skillMCPServers:q.skillMCPServers,createOAuthProvider:async(w0,a,F0)=>{let z0=`${w0}:${a}`,q0=G.get(z0);if(q0)return j.debug("Reusing existing OAuth provider for server",{serverName:w0,serverUrl:a}),q0;j.debug("Creating OAuth provider for server",{serverName:w0,serverUrl:a});let Q0=(async()=>{let H0=new _N(J.secrets),i=await H0.getClientInfo(w0,a),n=F0?.scopes??i?.scopes,e=wV4();j.info("OAuth headless mode check",{useHeadless:e,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:p6.isTTY});let J0;if(e)J0=J.executeMode?BV4():HV4(w0);let Z0=new WL0({storage:H0,serverName:w0,serverUrl:a,clientId:F0?.clientId??i?.clientId,clientSecret:F0?.clientSecret??i?.clientSecret,authUrl:F0?.authUrl??i?.authUrl,tokenUrl:F0?.tokenUrl??i?.tokenUrl,scopes:n,headlessAuthHandler:J0});return j.debug("OAuth provider created",{serverName:w0,serverUrl:a,hasManualClientId:!!(F0?.clientId??i?.clientId),willUseDCR:!(F0?.clientId??i?.clientId),scopes:n,headlessMode:e,executeMode:J.executeMode}),Z0})();return G.set(z0,Q0),Q0}}),W=tv0({configService:X,filesystem:r6,spawn:e50}),H;if(J.executeMode){let w0=await f84({toolService:K,providers:[D,W],initialTimeout:15000});H=w0.registrations;for(let[a,F0]of w0.initErrors)j.warn(`${a} provider initialization slow or failed:`,F0)}else H=ev0({toolService:K,providers:[D,W]});if(Z.jetbrains)XN("JetBrains");else if(Z.ide&&eV4())XN("VS Code");else if(Z.ide&&$K4())XN("Neovim");else if(Z.ide){let w0=await o13();if(w0){let a=Mr(w0.ideName);if(a)XN(a)}}if(J.executeMode)Vj1(!0);let B,w=m8.status.pipe(D1((w0)=>Boolean(w0.connected&&w0.authenticated&&w0.ideName&&bj1(w0.ideName))),M4()).subscribe((w0)=>{if(w0){if(!B)B=K.registerTool(x84)}else B?.dispose(),B=void 0}),N;if(!J.executeMode){let w0=await J.settings.get("fuzzy.alwaysIncludePaths")??[];N=new k80(process.cwd(),{alwaysIncludePaths:w0},!0)}else N=new class extends k80{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let O=!1;{let w0=await J.secrets.get("apiKey",J.ampURL);if(O=Boolean(w0),j.info("API key lookup before login",{found:Boolean(w0),ampURL:J.ampURL,deferAuth:Y}),!w0)if(Y)j.info("No API key found, continuing startup with deferred auth");else{p6.write(`No API key found. Starting login flow...
7506
7506
  `);let a=await X43(J),F0=await J.secrets.get("apiKey",J.ampURL);if(j.info("Login flow completed",{success:a,storedKeyPresent:Boolean(F0),ampURL:J.ampURL}),!a)await EU(),process.exit(1);O=!0}}{let w0=await X.getLatest(),a=w0.settings.url,F0=w0.secrets.isSet?.[a];j.info("Config secrets state after login",{configURL:a,apiKeySet:F0?.apiKey??!1})}let E=E1(nJ(X).pipe(F5((w0)=>w0!=="pending"))),L=await Um1({isDevelopment:!1}),M=Y?"pending":await E;if(!Y)j.info("Server status resolved",{status:"ready",isAuthenticated:y6(M),isError:RD(M),errorMessage:RD(M)?M.error.message:void 0});let A=new sI0(L,X),I=new cA0(L,{lazy:!0,maxThreads:200});j.info("Starting Amp background services");let P=Z.takeMeBack?!1:void 0,_=yl0(P,M),S=Boolean(_||Z.headless);if(S)j.info("DTW mode enabled: thread sync service disabled");let y=S?Y43():ug1({threadService:A,threadHistoryService:I,configService:X,isExtensionDevelopment:!1}),m;m8.status.subscribe((w0)=>{m=w0});let b=new Uw0({workspaceRoots:[K1.file(process.cwd())],fileSystem:Z.jetbrains||Z.ide?xt:r6,getCurrentFile:()=>{if(!m?.openFile)return;try{return K1.parse(m.openFile)}catch(w0){j.warn("Failed to parse current file URI",{uri:m.openFile,error:w0});return}},getOpenFiles:()=>{if(!m?.visibleFiles?.length)return[];let w0=m.openFile;return m.visibleFiles.filter((a)=>a!==w0).map((a)=>{try{return K1.parse(a)}catch(F0){return j.warn("Failed to parse visible file URI",{uri:a,error:F0}),null}}).filter((a)=>a!==null)}}),k=new Ef0,f=process.env.PLUGINS??"off",p=Z.headless?Jz4():void 0,l=p??new Q90({configService:X}),x=l instanceof Q90?l:void 0;if(x)x.pluginExecutorKind=_?"local":"unknown";let r=HM0({configService:X,fileSystem:Z.jetbrains||Z.ide?xt:r6,platform:l,internalPlugins:_R4,pluginFilter:f}),c=ax1({pluginService:r,toolService:K}),s={codebaseContextService:b,configService:X,toolService:K,mcpService:D,skillService:q,toolboxService:W,trustStore:U,threadService:A,threadHistoryService:I,threadSyncService:y,threadStorage:L,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:N,fileSystem:Z.jetbrains||Z.ide?xt:r6,terminal:k,pluginService:r,pluginPlatform:x,headlessPluginPlatform:p,serverStatus:M,serverStatusPromise:E,hasAPIKeyAtStartup:O};return{...s,async asyncDispose(){if(s.mcpService.hasAuthenticatingClients())j.info("Waiting for OAuth authentication to complete before exit..."),await s.mcpService.waitForAuthentication();for(let w0 of H.values())w0.dispose();await s.mcpService.dispose(),F(),await s.threadService.asyncDispose(),s.configService.unsubscribe(),z(),s.fuzzyServer.dispose(),s.threadSyncService.dispose(),s.settingsStorage[Symbol.dispose](),w.unsubscribe(),B?.dispose(),c.dispose(),await s.pluginService.dispose()}}}async function X43(J){if(!J.executeMode){if(!await ax0("Would you like to log in to Amp? [(y)es, (n)o]: "))return p6.write(`Login cancelled. Run the command again to retry.
7507
7507
  `),!1}return await vR4(J)}async function vR4(J){let Z=c13(32).toString("hex"),Q=await yC(J.ampURL,Z),Y=new AbortController;try{await fX(Q,Y.signal)}catch(V){j.error("Error opening browser",{error:V})}let X=await yC(J.ampURL,Z,!1);p6.write(`If your browser does not open automatically, visit:
7508
7508
 
@@ -7510,7 +7510,7 @@ ${Z1.blue.bold(X)}
7510
7510
 
7511
7511
  `);try{return await yK4(J.ampURL,Z,J.secrets,Y),p6.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(V){return j.error("Login failed",{error:V}),E7.write(`
7512
7512
  Login failed: ${V instanceof Error?V.message:String(V)}
7513
- `),!1}}function ER4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function V43(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new c1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!D8(Y.threadId))throw new c1("Create response did not include a valid thread ID",1);return Y.threadId}function K43(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 z43(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new c1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function G43(){let J=new sW().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)gE(),process.exit(0);let B=H.originalError??H;MX4(B)}),J.option("-V, --version","Print the version number and exit",()=>{let B;try{B=`, ${PD(new Date("2026-03-14T04:35:49.775Z"))} ago`}catch{}p6.write(`0.0.1773462612-g20fbe1 (released 2026-03-14T04:35:49.775Z${B??""})
7513
+ `),!1}}function ER4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function V43(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new c1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!D8(Y.threadId))throw new c1("Create response did not include a valid thread ID",1);return Y.threadId}function K43(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 z43(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new c1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function G43(){let J=new sW().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)gE(),process.exit(0);let B=H.originalError??H;MX4(B)}),J.option("-V, --version","Print the version number and exit",()=>{let B;try{B=`, ${PD(new Date("2026-03-14T12:07:36.317Z"))} ago`}catch{}p6.write(`0.0.1773489712-g258ad5 (released 2026-03-14T12:07:36.317Z${B??""})
7514
7514
  `),process.exit(0)}),J.addHelpText("after",rV4()),J.configureHelp({formatHelp:sV4}),J.command("logout").description("Log out by removing stored API key").action(async(H,B)=>{let w=B.optsWithGlobals(),N=await E3(w);await B43(N)}),J.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(H,B)=>{let w=B.optsWithGlobals(),N=await E3(w);await H43(N,await Px0(w,N.settings))}),J.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(H,B,w)=>{let N=w.optsWithGlobals(),O=await E3(N);await aX4(H??"get",O.ampURL,O.secrets),process.exit(process.exitCode??0)}),J.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(H,B)=>{let w=B.optsWithGlobals(),N=await E3(w);await oX4(N.ampURL,N.secrets),process.exit(process.exitCode??0)}),J.command("dtw-curl [threadId] [action] [message...]",{hidden:!0}).summary("DTW helper").description("Internal: helper for DTW one-shot commands.").addHelpText("after",`
7515
7515
  Actions:
7516
7516
  create Create a new DTW thread and print its ID
@@ -7573,8 +7573,8 @@ ${L}
7573
7573
 
7574
7574
  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 F43(J){j.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new Lg({threadService:J.threadService,configService:J.configService,mcpService:J.mcpService,initialToolDiscovery:Promise.all([J.mcpService.initialized,J.toolboxService.initialized]).then(()=>{return}),toolService:J.toolService,skillService:J.skillService,getThreadEnvironment:$J,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new JV(J.fileSystem),ampURL:J.ampURL});if(J.threadId)await Z.switchThread(J.threadId);else await Z.createThread();return Z}catch(Z){throw j.error("[createDTWThreadPool] Failed to create DTW thread pool",{threadId:J.threadId,error:Z}),Z}}async function U43(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await mC()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await mC()).trimEnd(),stdinInput:null}}function q43(J,Z,Q){if(J.remote&&!Z)throw new c1("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(J.streamJson&&!Z)throw new c1("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new c1("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new c1("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new c1("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new c1("The --archive flag requires --execute mode",1,'Use: amp --execute "your message" --archive');if(J.streamJsonInput&&typeof J.execute==="string"&&J.execute.trim()!=="")throw new c1("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"}]}}' | amp --execute --stream-json --stream-json-input`);if(Z&&Q===""&&!J.streamJsonInput&&!J.headless)throw new c1("User message must be provided through stdin or as argument when using execute mode",1,`Either pass a message as an argument: amp --execute "your message"
7575
7575
  Or pipe via stdin: echo "your message" | amp --execute`)}async function HZ0(J,Z,Q){let Y=process.hrtime.bigint(),X=(z0,q0)=>{let Q0=Number(process.hrtime.bigint()-q0)/1e6,H0=A$4();j.info("Startup phase",{phase:z0,phaseMs:Math.round(Q0),sinceMainMs:H0===null?void 0:Math.round(H0)})},{userInput:V,stdinInput:K}=await U43(Z),z=!!Z.streamJson||!!Z.streamJsonThinking;q43({...Z,streamJson:z},J.executeMode,V),O7(Q,Z);let G=process.hrtime.bigint(),F=Boolean(await J.secrets.get("apiKey",J.ampURL)),U=!J.executeMode&&!Z.headless&&F;j.info("Interactive auth startup mode",{deferInteractiveAuth:U,hasAPIKeyAtStartup:F,executeMode:J.executeMode,headless:Boolean(Z.headless)});let q=await k9(J,Z,{deferAuth:U});X("runMainThread:createThreadDependencies",G),G=process.hrtime.bigint();let D=await bl0(q);X("runMainThread:createWorkerDeps",G);let{serverStatus:W}=q;if(!U&&RD(W)){let z0=ym(Error(W.error.message));if(z0.message===B8.networkOffline||z0.message===B8.networkTimeout)throw xl0(J.ampURL);throw new c1(B8.invalidAPIKey,1)}let H=y6(W)?W:null,B=H?.user.email,w=CR4(B),N=kl0({userEmail:B,features:H?.features}),O=Z.takeMeBack?!1:void 0,E=H!==null&&yl0(O,H);if(!U)await vl0(Q,Z,W);let L=ul0(W),M=L?.features??[],A=L?.team??null,I=J90(Z,L);if(I instanceof Error)G3(I.message);if((J.executeMode||z)&&h3(Z.mode)&&!w)throw new c1(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(H&&!iq(Z.mode,B))throw new c1(`Agent mode '${Z.mode}' is only available for Amp employees`,1);if(J.executeMode&&Z.remote)await Yz4(V,K,q.configService),await q.asyncDispose(),process.exit(0);if(Z.headless){if(!B||!vZ(B))throw new c1("Headless DTW mode is only available for Amp employees",1);let z0=await q.secretStorage.get("apiKey",J.ampURL);if(!z0)throw new c1("API key required for headless mode. Please run `amp login` first.",1);let q0=typeof Z.headless==="string"&&Z.headless!=="true"?Z.headless:void 0;if(q0&&!D8(q0))throw new c1(`Invalid thread ID: ${q0}`,1);let Q0=q0??await I43({dependencies:q,visibility:I??void 0}),H0=await LV4(Q0);if(H0.status==="already-running")await q.asyncDispose(),await EU(),process.exit(0);try{await WV4({ampURL:J.ampURL,apiKey:z0,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:Q0,initialToolDiscovery:Promise.all([q.mcpService.initialized,q.toolboxService.initialized]).then(()=>{return}),configService:q.configService,mcpService:q.mcpService,toolService:q.toolService,skillService:q.skillService,fileSystem:q.fileSystem,pluginService:q.pluginService,pluginPlatform:q.headlessPluginPlatform})}finally{await H0.release(),await q.asyncDispose()}await EU(),process.exit(0)}let P={threadService:q.threadService,workerDeps:D,createThread:async()=>{let z0=U?await q.serverStatusPromise:W,q0=await N80(J.settings,process.cwd(),ul0(z0),I);if(q0 instanceof Error)G3(q0.message);return um0(D,{threadMeta:q0?yV(q0):void 0,agentMode:Z.mode,onFirstAssistantMessage:LR4})},validateThreadOwnership:async(z0,q0)=>{if(q0?.nonBlockingOwnershipCheck){MR4(z0,q.configService).catch((Q0)=>{if(Q0 instanceof c1){if(q0.onOwnershipError){q0.onOwnershipError(Q0,z0);return}RC(Q0,z0);return}j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Q0})});return}try{await MR4(z0,q.configService)}catch(Q0){if(Q0 instanceof c1)throw Q0;j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Q0})}},switchThreadVisibility:I,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:LR4},_=async(z0)=>{try{if(z0==="dtw")return F43({ampURL:J.ampURL,configService:q.configService,threadService:q.threadService,mcpService:q.mcpService,toolboxService:q.toolboxService,toolService:q.toolService,skillService:q.skillService,fileSystem:q.fileSystem,threadId:Z.threadId});return IH4(P,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch(q0){if(q0 instanceof c1)throw q0;throw await RC(q0,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")E7.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
7576
- `),await EU(),process.exit(1);let S=(async()=>{if(U){j.info("Skipping initial free tier status fetch until auth is complete");return}try{let z0=await q.configService.getLatest(),q0=_k(z0),Q0=await A6.getUserFreeTierStatus({},{config:q.configService,signal:AbortSignal.timeout(q0)});if(Q0.ok)return j.info("User free tier status:",Q0),Q0.result;return}catch(z0){j.error("Failed to fetch free tier status:",z0);return}})(),m=!J.executeMode?new _f0:null,b,k=null;if(m)b=m,k=(async()=>{let z0=U?await q.serverStatusPromise:q.serverStatus;await vl0(Q,Z,z0);let q0=process.hrtime.bigint(),Q0=yl0(O,z0),H0=y6(z0)?kl0({userEmail:z0.user.email,features:z0.features}):!1;wR4({dtwEnabled:Q0,hasV2TUIAccess:H0});let i=await _(Q0?"dtw":"worker");if(X("runMainThread:createThreadPool",q0),m.attach(i),V){let n=await E1(i.threadHandles$);if(!n)throw new c1("No active thread is available yet.",1);await n.sendMessage({content:[{type:"text",text:V}]})}})(),k.catch(async(z0)=>{let q0=z0 instanceof Error?z0:Error(String(z0));m.setInitError(q0),await RC(z0,Z.threadId)});else G=process.hrtime.bigint(),wR4({dtwEnabled:E,hasV2TUIAccess:N}),b=await _(E?"dtw":"worker"),X("runMainThread:createThreadPool",G);let f=Z.notifications!==void 0?Z.notifications:!J.executeMode;G=process.hrtime.bigint();let p=await q.configService.getLatest();if(X("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),Q43({configService:q.configService,threadService:q.threadService,config:p,useNotificationsForService:f,threadViewStates$:()=>b.threadHandles$.pipe(Q4((z0)=>{if(!z0)return v0.of({});return X5(z0.thread$,z0.threadViewState$).pipe(D1(([q0,Q0])=>({[q0.id]:Q0})))}))}),X("runMainThread:createCliNotificationService",G),J.executeMode){iK4(q.mcpService,J.settings);let z0={userInput:V,stdinInput:K,dependencies:q,streamJson:z,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label},q0=await kX4({threadPool:b,...z0});if(Z.archive)await A6.archiveThread({thread:q0,archived:!0},{config:q.configService});await q.asyncDispose(),process.exit(0)}let l=!1,x=!1;if(Z.jetbrains||Z.ide){await cj1();let z0=await UN({jetbrainsOnly:Z.jetbrains});if(z0.length===0){if(Z.jetbrains)l=!await q.configService.get("jetbrains.skipInstall")}else if(z0.length===1){let q0=z0[0];if(q0)m8.selectConfig(q0)}else x=!0}G=process.hrtime.bigint();let r=ix0("0.0.1773462612-g20fbe1",q.settingsStorage,{startDelayMs:3000});X("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let c=new dA0(q.threadStorage);X("runMainThread:createThreadFuzzyIndexer",G),G=process.hrtime.bigint();let s=new ox0(q.mcpService,J.settings.getWorkspaceRootPath());if(X("runMainThread:createMcpTrustHandler",G),V&&J.executeMode){let z0=await E1(b.threadHandles$);if(!z0)throw new c1("No active thread is available yet.",1);await z0.sendMessage({content:[{type:"text",text:V}]})}G=process.hrtime.bigint();let w0=await oz();X("runMainThread:loadSessionState",G),j.info("Loaded session state:",w0);let a={...w0,launchCount:w0.launchCount+1};rz(a);let F0=Z.threadId&&D8(Z.threadId)?Z.threadId:void 0;try{if(G=process.hrtime.bigint(),await vB4({codebaseContextService:q.codebaseContextService,history:new Fx0,fuzzyServer:q.fuzzyServer,settingsStorage:q.settingsStorage,threadService:q.threadService,threadHistoryService:q.threadHistoryService,threadFuzzyIndexer:c,skillService:q.skillService,configService:q.configService,secretStorage:q.secretStorage,internalAPIClient:A6,threadPool:b,createSystemPromptDeps:async()=>SR4(q),ideClient:m8,mcpService:q.mcpService,toolboxService:q.toolboxService,mcpTrustHandler:s,updateService:r,pluginPlatform:q.pluginPlatform,pluginService:q.pluginService},{initialServerStatus:q.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:q.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:F0,showJetBrainsInstaller:l,showIdePickerHint:x,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Z.clientId,sessionState:a,freeTierStatusPromise:S,workspace:A??null,features:M,isDogfooding:w,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-14T04:35:49.775Z"},(z0)=>new Kg0({...z0,threadPool:z0.threadPool},(q0)=>new Qc0({...q0,threadState:q0.threadState}))),X("runMainThread:mountApp-returned",G),k)await k}finally{}await q.asyncDispose(),X("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function E3(J){if(j.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),J.interactive)E7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7577
- `);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;j.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await tu1({get:async(z)=>{if(z!==Au)return;try{let G=await jR4(Sl0,"utf-8");return JSON.parse(G).installationID}catch{return}},set:async(z,G)=>{if(z!==Au)return;await IR4(wB.dirname(Sl0),{recursive:!0}),await l13(Sl0,JSON.stringify({installationID:G},null,2),{mode:384})}},{clientType:"cli",platform:gK()});Kj1(Y);let X=await yV4({...J,workspaceTrust:{current:!0,changes:Wk},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 cK4(J.mcpConfig);X=lK4(X,z)}let V=wB.dirname(X.getSettingsFilePath());v24(vC,V);let K=await X.get("url","global");if(!K)K=J7;if(j.info("Resolved Amp URL",{ampURL:K,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!QD(K))j.info("Targeting custom Amp server",{ampURL:K});return X=sI1(X),{executeMode:Z,isTTY:Q,ampURL:K,settings:X,secrets:Gz4(await Px0(J,X))}}function D43(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let V=Y.slice(2).replace(/-([a-z])/g,(z,G)=>G.toUpperCase()),K=J[Q+1];if(K&&!K.startsWith("--"))Z[V]=K,Q++}}return Z}async function W43(){M$4();let J=D43(process.argv),Z=process.argv.includes("--headless")||process.argv.some((V)=>V.startsWith("--headless="));uY4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?a13:void 0)});let Q=process.argv.includes("--no-color"),Y=process.argv.includes("--color"),X=process.stdout.isTTY&&process.stderr.isTTY;if(Q||!Y&&!X)Z1.level=0;if(r13(j),j.info("Starting Amp CLI.",{version:"0.0.1773462612-g20fbe1",buildTimestamp:"2026-03-14T04:35:49.775Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new c1(B8.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await G43().parseAsync(process.argv)}_24().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await W43().catch(RC)});async function H43(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"),p6.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7576
+ `),await EU(),process.exit(1);let S=(async()=>{if(U){j.info("Skipping initial free tier status fetch until auth is complete");return}try{let z0=await q.configService.getLatest(),q0=_k(z0),Q0=await A6.getUserFreeTierStatus({},{config:q.configService,signal:AbortSignal.timeout(q0)});if(Q0.ok)return j.info("User free tier status:",Q0),Q0.result;return}catch(z0){j.error("Failed to fetch free tier status:",z0);return}})(),m=!J.executeMode?new _f0:null,b,k=null;if(m)b=m,k=(async()=>{let z0=U?await q.serverStatusPromise:q.serverStatus;await vl0(Q,Z,z0);let q0=process.hrtime.bigint(),Q0=yl0(O,z0),H0=y6(z0)?kl0({userEmail:z0.user.email,features:z0.features}):!1;wR4({dtwEnabled:Q0,hasV2TUIAccess:H0});let i=await _(Q0?"dtw":"worker");if(X("runMainThread:createThreadPool",q0),m.attach(i),V){let n=await E1(i.threadHandles$);if(!n)throw new c1("No active thread is available yet.",1);await n.sendMessage({content:[{type:"text",text:V}]})}})(),k.catch(async(z0)=>{let q0=z0 instanceof Error?z0:Error(String(z0));m.setInitError(q0),await RC(z0,Z.threadId)});else G=process.hrtime.bigint(),wR4({dtwEnabled:E,hasV2TUIAccess:N}),b=await _(E?"dtw":"worker"),X("runMainThread:createThreadPool",G);let f=Z.notifications!==void 0?Z.notifications:!J.executeMode;G=process.hrtime.bigint();let p=await q.configService.getLatest();if(X("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),Q43({configService:q.configService,threadService:q.threadService,config:p,useNotificationsForService:f,threadViewStates$:()=>b.threadHandles$.pipe(Q4((z0)=>{if(!z0)return v0.of({});return X5(z0.thread$,z0.threadViewState$).pipe(D1(([q0,Q0])=>({[q0.id]:Q0})))}))}),X("runMainThread:createCliNotificationService",G),J.executeMode){iK4(q.mcpService,J.settings);let z0={userInput:V,stdinInput:K,dependencies:q,streamJson:z,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label},q0=await kX4({threadPool:b,...z0});if(Z.archive)await A6.archiveThread({thread:q0,archived:!0},{config:q.configService});await q.asyncDispose(),process.exit(0)}let l=!1,x=!1;if(Z.jetbrains||Z.ide){await cj1();let z0=await UN({jetbrainsOnly:Z.jetbrains});if(z0.length===0){if(Z.jetbrains)l=!await q.configService.get("jetbrains.skipInstall")}else if(z0.length===1){let q0=z0[0];if(q0)m8.selectConfig(q0)}else x=!0}G=process.hrtime.bigint();let r=ix0("0.0.1773489712-g258ad5",q.settingsStorage,{startDelayMs:3000});X("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let c=new dA0(q.threadStorage);X("runMainThread:createThreadFuzzyIndexer",G),G=process.hrtime.bigint();let s=new ox0(q.mcpService,J.settings.getWorkspaceRootPath());if(X("runMainThread:createMcpTrustHandler",G),V&&J.executeMode){let z0=await E1(b.threadHandles$);if(!z0)throw new c1("No active thread is available yet.",1);await z0.sendMessage({content:[{type:"text",text:V}]})}G=process.hrtime.bigint();let w0=await oz();X("runMainThread:loadSessionState",G),j.info("Loaded session state:",w0);let a={...w0,launchCount:w0.launchCount+1};rz(a);let F0=Z.threadId&&D8(Z.threadId)?Z.threadId:void 0;try{if(G=process.hrtime.bigint(),await vB4({codebaseContextService:q.codebaseContextService,history:new Fx0,fuzzyServer:q.fuzzyServer,settingsStorage:q.settingsStorage,threadService:q.threadService,threadHistoryService:q.threadHistoryService,threadFuzzyIndexer:c,skillService:q.skillService,configService:q.configService,secretStorage:q.secretStorage,internalAPIClient:A6,threadPool:b,createSystemPromptDeps:async()=>SR4(q),ideClient:m8,mcpService:q.mcpService,toolboxService:q.toolboxService,mcpTrustHandler:s,updateService:r,pluginPlatform:q.pluginPlatform,pluginService:q.pluginService},{initialServerStatus:q.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:q.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:F0,showJetBrainsInstaller:l,showIdePickerHint:x,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Z.clientId,sessionState:a,freeTierStatusPromise:S,workspace:A??null,features:M,isDogfooding:w,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-14T12:07:36.317Z"},(z0)=>new Kg0({...z0,threadPool:z0.threadPool},(q0)=>new Qc0({...q0,threadState:q0.threadState}))),X("runMainThread:mountApp-returned",G),k)await k}finally{}await q.asyncDispose(),X("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function E3(J){if(j.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),J.interactive)E7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7577
+ `);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;j.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await tu1({get:async(z)=>{if(z!==Au)return;try{let G=await jR4(Sl0,"utf-8");return JSON.parse(G).installationID}catch{return}},set:async(z,G)=>{if(z!==Au)return;await IR4(wB.dirname(Sl0),{recursive:!0}),await l13(Sl0,JSON.stringify({installationID:G},null,2),{mode:384})}},{clientType:"cli",platform:gK()});Kj1(Y);let X=await yV4({...J,workspaceTrust:{current:!0,changes:Wk},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 cK4(J.mcpConfig);X=lK4(X,z)}let V=wB.dirname(X.getSettingsFilePath());v24(vC,V);let K=await X.get("url","global");if(!K)K=J7;if(j.info("Resolved Amp URL",{ampURL:K,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!QD(K))j.info("Targeting custom Amp server",{ampURL:K});return X=sI1(X),{executeMode:Z,isTTY:Q,ampURL:K,settings:X,secrets:Gz4(await Px0(J,X))}}function D43(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let V=Y.slice(2).replace(/-([a-z])/g,(z,G)=>G.toUpperCase()),K=J[Q+1];if(K&&!K.startsWith("--"))Z[V]=K,Q++}}return Z}async function W43(){M$4();let J=D43(process.argv),Z=process.argv.includes("--headless")||process.argv.some((V)=>V.startsWith("--headless="));uY4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?a13:void 0)});let Q=process.argv.includes("--no-color"),Y=process.argv.includes("--color"),X=process.stdout.isTTY&&process.stderr.isTTY;if(Q||!Y&&!X)Z1.level=0;if(r13(j),j.info("Starting Amp CLI.",{version:"0.0.1773489712-g258ad5",buildTimestamp:"2026-03-14T12:07:36.317Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new c1(B8.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await G43().parseAsync(process.argv)}_24().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await W43().catch(RC)});async function H43(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"),p6.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7578
7578
  `);else if(!QD(J.ampURL))p6.write(`Logging in to ${new URL(J.ampURL).hostname}
7579
7579
  `);let Y=process.env.AMP_API_KEY;if(Y)p6.write(`API key found in environment variable, storing...
7580
7580
  `),await Z.set("apiKey",Y,J.ampURL),p6.write(`API key successfully stored.