moi-computer 0.13.1-next.5 → 0.14.0

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 (30) hide show
  1. package/dist/{chunk-cb2a4cjk.js → chunk-828s864r.js} +21 -21
  2. package/dist/{chunk-4arsawe0.js → chunk-gh11h6dc.js} +2 -2
  3. package/dist/chunk-hhgsmxsq.js +1 -0
  4. package/dist/{chunk-6aq60rm2.js → chunk-ht9zmff2.js} +4 -4
  5. package/dist/{chunk-ghyzbqgb.js → chunk-jqa4c92z.js} +2 -2
  6. package/dist/{chunk-v0w55vnq.js → chunk-kkhswjz8.js} +2 -2
  7. package/dist/{chunk-0xy5nenk.js → chunk-nqh3kx2x.js} +1 -1
  8. package/dist/chunk-rb2vsqvb.js +1 -0
  9. package/dist/{chunk-9vy2z8hd.js → chunk-t22yw8s6.js} +1 -1
  10. package/dist/chunk-yv6n9e3z.js +72 -0
  11. package/dist/index.html +1 -1
  12. package/package.json +1 -1
  13. package/runtime/{chunk-9dr0dhxj.js → chunk-00rk365r.js} +2 -2
  14. package/runtime/{chunk-q2t18c1t.js → chunk-5egvk1rz.js} +1 -1
  15. package/runtime/{chunk-mjwz158z.js → chunk-8fvgvm56.js} +1 -1
  16. package/runtime/{chunk-f56xzjzw.js → chunk-gbkjshyt.js} +1 -1
  17. package/runtime/{chunk-g9saang0.js → chunk-h2bwhk81.js} +1 -1
  18. package/runtime/chunk-hjzfk1cr.js +3 -0
  19. package/runtime/{chunk-pt32r350.js → chunk-jb63ns1z.js} +1 -1
  20. package/runtime/{chunk-8jg7v8y7.js → chunk-r5s8rm8n.js} +1 -1
  21. package/runtime/chunk-w6ksnv8y.js +2 -0
  22. package/runtime/{chunk-67h4jd69.js → chunk-wvarpvem.js} +2 -2
  23. package/runtime/cli.js +5 -5
  24. package/runtime/gateway-client.js +1 -1
  25. package/dist/chunk-5eb7n6xw.js +0 -1
  26. package/dist/chunk-j3djs7ta.js +0 -72
  27. package/dist/chunk-yff16m73.js +0 -1
  28. package/runtime/chunk-30dzwptp.js +0 -2
  29. package/runtime/chunk-hrtaxw37.js +0 -3
  30. /package/runtime/{chunk-fdbkvdht.js → chunk-c3qyet60.js} +0 -0
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Lt}from"./chunk-hrtaxw37.js";import{r,m,u,s,T,o,sn}from"./chunk-ggphq7nk.js";import{g,e}from"./chunk-7c0zbz74.js";var Pt=e(function(bt,ge){(function(t){let i={fourOctet:new RegExp("^(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)$","i"),threeOctet:new RegExp("^(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)$","i"),twoOctet:new RegExp("^(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)$","i"),longValue:new RegExp("^(0?\\d+|0x[a-f0-9]+)$","i")},a=new RegExp("^0[0-7]+$","i"),l=new RegExp("^0x[a-f0-9]+$","i"),p="%[0-9a-z]{1,}",f="(?:[0-9a-f]+::?)+",y={zoneIndex:new RegExp("%[0-9a-z]{1,}","i"),native:new RegExp("^(::)?((?:[0-9a-f]+::?)+)?([0-9a-f]+)?(::)?(%[0-9a-z]{1,})?$","i"),deprecatedTransitional:new RegExp("^(?:::)((0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)(%[0-9a-z]{1,})?)$","i"),transitional:new RegExp("^((?:(?:[0-9a-f]+::?)+)|(?:::)(?:(?:[0-9a-f]+::?)+)?)(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)(%[0-9a-z]{1,})?$","i")};function S(c,d){if(c.indexOf("::")!==c.lastIndexOf("::"))return null;let E=0,h=-1,A=(c.match(y.zoneIndex)||[])[0],I,M;if(A)A=A.substring(1),c=c.replace(/%.+$/,"");while((h=c.indexOf(":",h+1))>=0)E++;if(c.substr(0,2)==="::")E--;if(c.substr(-2,2)==="::")E--;if(E>=d)return null;M=d-E,I=":";while(M--)I+="0:";if(c=c.replace("::",I),c[0]===":")c=c.slice(1);if(c[c.length-1]===":")c=c.slice(0,-1);return d=function(){let O=c.split(":"),b=[];for(let N=0;N<O.length;N++)b.push(O[N].length>4?NaN:parseInt(O[N],16));return b}(),{parts:d,zoneId:A}}function v(c,d,E,h){if(c.length!==d.length)throw Error("ipaddr: cannot match CIDR for objects with different lengths");let A=0,I;while(h>0){if(I=E-h,I<0)I=0;if(c[A]>>I!==d[A]>>I)return!1;h-=E,A+=1}return!0}function w(c){if(l.test(c))return parseInt(c,16);if(c[0]==="0"&&!isNaN(parseInt(c[1],10))){if(a.test(c))return parseInt(c,8);throw Error(`ipaddr: cannot parse ${c} as octal`)}return parseInt(c,10)}function R(c,d){while(c.length<d)c=`0${c}`;return c}let _={};if(_.IPv4=function(){function c(d){if(d.length!==4)throw Error("ipaddr: ipv4 octet count should be 4");let E,h;for(E=0;E<d.length;E++)if(h=d[E],!(0<=h&&h<=255))throw Error("ipaddr: ipv4 octet should fit in 8 bits");this.octets=d}return c.prototype.SpecialRanges={unspecified:[[new c([0,0,0,0]),8]],broadcast:[[new c([255,255,255,255]),32]],multicast:[[new c([224,0,0,0]),4]],linkLocal:[[new c([169,254,0,0]),16]],loopback:[[new c([127,0,0,0]),8]],carrierGradeNat:[[new c([100,64,0,0]),10]],private:[[new c([10,0,0,0]),8],[new c([172,16,0,0]),12],[new c([192,168,0,0]),16]],reserved:[[new c([192,0,0,0]),24],[new c([192,0,2,0]),24],[new c([192,88,99,0]),24],[new c([198,18,0,0]),15],[new c([198,51,100,0]),24],[new c([203,0,113,0]),24],[new c([240,0,0,0]),4]],as112:[[new c([192,175,48,0]),24],[new c([192,31,196,0]),24]],amt:[[new c([192,52,193,0]),24]]},c.prototype.kind=function(){return"ipv4"},c.prototype.match=function(d,E){let h;if(E===void 0)h=d,d=h[0],E=h[1];if(d.kind()!=="ipv4")throw Error("ipaddr: cannot match ipv4 address with non-ipv4 one");return v(this.octets,d.octets,8,E)},c.prototype.prefixLengthFromSubnetMask=function(){let d=0,E=!1,h={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},A,I,M;for(A=3;A>=0;A-=1)if(I=this.octets[A],I in h){if(M=h[I],E&&M!==0)return null;if(M!==8)E=!0;d+=M}else return null;return 32-d},c.prototype.range=function(){return _.subnetMatch(this,this.SpecialRanges)},c.prototype.toByteArray=function(){return this.octets.slice(0)},c.prototype.toIPv4MappedAddress=function(){return _.IPv6.parse(`::ffff:${this.toString()}`)},c.prototype.toNormalizedString=function(){return this.toString()},c.prototype.toString=function(){return this.octets.join(".")},c}(),_.IPv4.broadcastAddressFromCIDR=function(c){try{let d=this.parseCIDR(c),E=d[0].toByteArray(),h=this.subnetMaskFromPrefixLength(d[1]).toByteArray(),A=[],I=0;while(I<4)A.push(parseInt(E[I],10)|parseInt(h[I],10)^255),I++;return new this(A)}catch(d){throw Error("ipaddr: the address does not have IPv4 CIDR format",{cause:d})}},_.IPv4.isIPv4=function(c){return this.parser(c)!==null},_.IPv4.isValid=function(c){try{return new this(this.parser(c)),!0}catch{return!1}},_.IPv4.isValidCIDR=function(c){try{return this.parseCIDR(c),!0}catch{return!1}},_.IPv4.isValidFourPartDecimal=function(c){if(_.IPv4.isValid(c)&&c.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))return!0;else return!1},_.IPv4.isValidCIDRFourPartDecimal=function(c){let d=c.match(/^(.+)\/(\d+)$/);if(!_.IPv4.isValidCIDR(c)||!d)return!1;return _.IPv4.isValidFourPartDecimal(d[1])},_.IPv4.networkAddressFromCIDR=function(c){let d,E,h,A,I;try{d=this.parseCIDR(c),h=d[0].toByteArray(),I=this.subnetMaskFromPrefixLength(d[1]).toByteArray(),A=[],E=0;while(E<4)A.push(parseInt(h[E],10)&parseInt(I[E],10)),E++;return new this(A)}catch(M){throw Error("ipaddr: the address does not have IPv4 CIDR format",{cause:M})}},_.IPv4.parse=function(c){let d=this.parser(c);if(d===null)throw Error("ipaddr: string is not formatted like an IPv4 Address");return new this(d)},_.IPv4.parseCIDR=function(c){let d;if(d=c.match(/^(.+)\/(\d+)$/)){let E=parseInt(d[2]);if(E>=0&&E<=32){let h=[this.parse(d[1]),E];return Object.defineProperty(h,"toString",{value:function(){return this.join("/")}}),h}}throw Error("ipaddr: string is not formatted like an IPv4 CIDR range")},_.IPv4.parser=function(c){let d,E,h;if(d=c.match(i.fourOctet))return function(){let A=d.slice(1,6),I=[];for(let M=0;M<A.length;M++)E=A[M],I.push(w(E));return I}();else if(d=c.match(i.longValue)){if(h=w(d[1]),h>4294967295||h<0)throw Error("ipaddr: address outside defined range");return function(){let A=[],I;for(I=0;I<=24;I+=8)A.push(h>>I&255);return A}().reverse()}else if(d=c.match(i.twoOctet))return function(){let A=d.slice(1,4),I=[];if(h=w(A[1]),h>16777215||h<0)throw Error("ipaddr: address outside defined range");return I.push(w(A[0])),I.push(h>>16&255),I.push(h>>8&255),I.push(h&255),I}();else if(d=c.match(i.threeOctet))return function(){let A=d.slice(1,5),I=[];if(h=w(A[2]),h>65535||h<0)throw Error("ipaddr: address outside defined range");return I.push(w(A[0])),I.push(w(A[1])),I.push(h>>8&255),I.push(h&255),I}();else return null},_.IPv4.subnetMaskFromPrefixLength=function(c){if(c=parseInt(c),Number.isNaN(c)||c<0||c>32)throw Error("ipaddr: invalid IPv4 prefix length");let d=[0,0,0,0],E=0,h=Math.floor(c/8);while(E<h)d[E]=255,E++;if(h<4)d[h]=Math.pow(2,c%8)-1<<8-c%8;return new this(d)},_.IPv6=function(){function c(d,E){let h,A;if(d.length===16){this.parts=[];for(h=0;h<=14;h+=2)this.parts.push(d[h]<<8|d[h+1])}else if(d.length===8)this.parts=d;else throw Error("ipaddr: ipv6 part count should be 8 or 16");for(h=0;h<this.parts.length;h++)if(A=this.parts[h],!(0<=A&&A<=65535))throw Error("ipaddr: ipv6 part should fit in 16 bits");if(E)this.zoneId=E}return c.prototype.SpecialRanges={unspecified:[new c([0,0,0,0,0,0,0,0]),128],linkLocal:[new c([65152,0,0,0,0,0,0,0]),10],multicast:[new c([65280,0,0,0,0,0,0,0]),8],loopback:[new c([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new c([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new c([0,0,0,0,0,65535,0,0]),96],deprecatedSiteLocal:[new c([65216,0,0,0,0,0,0,0]),10],discard:[new c([256,0,0,0,0,0,0,0]),64],rfc6145:[new c([0,0,0,0,65535,0,0,0]),96],rfc6052:[[new c([100,65435,0,0,0,0,0,0]),96],[new c([100,65435,1,0,0,0,0,0]),48]],"6to4":[new c([8194,0,0,0,0,0,0,0]),16],teredo:[new c([8193,0,0,0,0,0,0,0]),32],benchmarking:[new c([8193,2,0,0,0,0,0,0]),48],amt:[new c([8193,3,0,0,0,0,0,0]),32],as112v6:[[new c([8193,4,274,0,0,0,0,0]),48],[new c([9760,79,32768,0,0,0,0,0]),48]],deprecatedOrchid:[new c([8193,16,0,0,0,0,0,0]),28],orchid2:[new c([8193,32,0,0,0,0,0,0]),28],droneRemoteIdProtocolEntityTags:[new c([8193,48,0,0,0,0,0,0]),28],segmentRouting:[new c([24320,0,0,0,0,0,0,0]),16],reserved:[[new c([8193,0,0,0,0,0,0,0]),23],[new c([8193,3512,0,0,0,0,0,0]),32],[new c([16383,0,0,0,0,0,0,0]),20]]},c.prototype.isIPv4MappedAddress=function(){return this.range()==="ipv4Mapped"},c.prototype.kind=function(){return"ipv6"},c.prototype.match=function(d,E){let h;if(E===void 0)h=d,d=h[0],E=h[1];if(d.kind()!=="ipv6")throw Error("ipaddr: cannot match ipv6 address with non-ipv6 one");return v(this.parts,d.parts,16,E)},c.prototype.prefixLengthFromSubnetMask=function(){let d=0,E=!1,h={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},A,I;for(let M=7;M>=0;M-=1)if(A=this.parts[M],A in h){if(I=h[A],E&&I!==0)return null;if(I!==16)E=!0;d+=I}else return null;return 128-d},c.prototype.range=function(){return _.subnetMatch(this,this.SpecialRanges)},c.prototype.toByteArray=function(){let d,E=[],h=this.parts;for(let A=0;A<h.length;A++)d=h[A],E.push(d>>8),E.push(d&255);return E},c.prototype.toFixedLengthString=function(){let d=function(){let h=[];for(let A=0;A<this.parts.length;A++)h.push(R(this.parts[A].toString(16),4));return h}.call(this).join(":"),E="";if(this.zoneId)E=`%${this.zoneId}`;return d+E},c.prototype.toIPv4Address=function(){if(!this.isIPv4MappedAddress())throw Error("ipaddr: trying to convert a generic ipv6 address to ipv4");let d=this.parts.slice(-2),E=d[0],h=d[1];return new _.IPv4([E>>8,E&255,h>>8,h&255])},c.prototype.toNormalizedString=function(){let d=function(){let h=[];for(let A=0;A<this.parts.length;A++)h.push(this.parts[A].toString(16));return h}.call(this).join(":"),E="";if(this.zoneId)E=`%${this.zoneId}`;return d+E},c.prototype.toRFC5952String=function(){let d=/((^|:)(0(:|$)){2,})/g,E="";if(this.zoneId)E=`%${this.zoneId}`;let h=this.toNormalizedString(),A=h.slice(0,h.length-E.length),I=0,M=-1,O=-1,b;while(b=d.exec(A)){let N=(b[0].match(/0/g)||[]).length;if(N>O)O=N,I=b.index,M=b[0].length}if(M<0)return A+E;return`${A.substring(0,I)}::${A.substring(I+M)}${E}`},c.prototype.toString=function(){return this.toRFC5952String()},c}(),_.IPv6.broadcastAddressFromCIDR=function(c){try{let d=this.parseCIDR(c),E=d[0].toByteArray(),h=this.subnetMaskFromPrefixLength(d[1]).toByteArray(),A=[],I=0;while(I<16)A.push(parseInt(E[I],10)|parseInt(h[I],10)^255),I++;return new this(A)}catch(d){throw Error("ipaddr: the address does not have IPv6 CIDR format",{cause:d})}},_.IPv6.isIPv6=function(c){return this.parser(c)!==null},_.IPv6.isValid=function(c){if(typeof c==="string"&&c.indexOf(":")===-1)return!1;try{let d=this.parser(c);return new this(d.parts,d.zoneId),!0}catch{return!1}},_.IPv6.isValidCIDR=function(c){if(typeof c==="string"&&c.indexOf(":")===-1)return!1;try{return this.parseCIDR(c),!0}catch{return!1}},_.IPv6.networkAddressFromCIDR=function(c){let d,E,h,A,I;try{d=this.parseCIDR(c),h=d[0].toByteArray(),I=this.subnetMaskFromPrefixLength(d[1]).toByteArray(),A=[],E=0;while(E<16)A.push(parseInt(h[E],10)&parseInt(I[E],10)),E++;return new this(A)}catch(M){throw Error("ipaddr: the address does not have IPv6 CIDR format",{cause:M})}},_.IPv6.parse=function(c){let d=this.parser(c);if(d===null)throw Error("ipaddr: string is not formatted like an IPv6 Address");return new this(d.parts,d.zoneId)},_.IPv6.parseCIDR=function(c){let d,E,h;if(E=c.match(/^(.+)\/(\d+)$/)){if(d=parseInt(E[2]),d>=0&&d<=128)return h=[this.parse(E[1]),d],Object.defineProperty(h,"toString",{value:function(){return this.join("/")}}),h}throw Error("ipaddr: string is not formatted like an IPv6 CIDR range")},_.IPv6.parser=function(c){let d,E,h,A,I,M;if(h=c.match(y.deprecatedTransitional))return this.parser(`::ffff:${h[1]}`);if(y.native.test(c))return S(c,8);if(h=c.match(y.transitional)){if(M=h[6]||"",d=h[1],!h[1].endsWith("::"))d=d.slice(0,-1);if(d=S(d+M,6),d&&d.parts){I=[parseInt(h[2]),parseInt(h[3]),parseInt(h[4]),parseInt(h[5])];for(E=0;E<I.length;E++)if(A=I[E],!(0<=A&&A<=255))return null;return d.parts.push(I[0]<<8|I[1]),d.parts.push(I[2]<<8|I[3]),{parts:d.parts,zoneId:d.zoneId}}}return null},_.IPv6.subnetMaskFromPrefixLength=function(c){if(c=parseInt(c),Number.isNaN(c)||c<0||c>128)throw Error("ipaddr: invalid IPv6 prefix length");let d=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],E=0,h=Math.floor(c/8);while(E<h)d[E]=255,E++;if(h<16)d[h]=Math.pow(2,c%8)-1<<8-c%8;return new this(d)},_.fromByteArray=function(c){let d=c.length;if(d===4)return new _.IPv4(c);else if(d===16)return new _.IPv6(c);else throw Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},_.isValid=function(c){return _.IPv6.isValid(c)||_.IPv4.isValid(c)},_.isValidCIDR=function(c){return _.IPv6.isValidCIDR(c)||_.IPv4.isValidCIDR(c)},_.parse=function(c){if(_.IPv6.isValid(c))return _.IPv6.parse(c);else if(_.IPv4.isValid(c))return _.IPv4.parse(c);else throw Error("ipaddr: the address has neither IPv6 nor IPv4 format")},_.parseCIDR=function(c){try{return _.IPv6.parseCIDR(c)}catch{try{return _.IPv4.parseCIDR(c)}catch(d){throw Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format",{cause:d})}}},_.process=function(c){let d=this.parse(c);if(d.kind()==="ipv6"&&d.isIPv4MappedAddress())return d.toIPv4Address();else return d},_.subnetMatch=function(c,d,E){let h,A,I,M;if(E===void 0||E===null)E="unicast";for(A in d)if(Object.prototype.hasOwnProperty.call(d,A)){if(I=d[A],I[0]&&!(I[0]instanceof Array))I=[I];for(h=0;h<I.length;h++)if(M=I[h],c.kind()===M[0].kind()&&c.match.apply(c,M))return A}return E},typeof ge<"u"&&ge.exports)ge.exports=_;else t.ipaddr=_})(bt)});function et(t){if(typeof t!=="string")return null;let n=t.trim();return n?n:null}function k(t){return et(t)??void 0}function dn(t){return k(t)?.toLowerCase()}function j(t){return dn(t)??""}function pn(t){if(typeof t==="number")return Number.isSafeInteger(t)?t:void 0;let n=k(t);if(!n||!/^[+-]?\d+$/.test(n))return;let i=Number(n);return Number.isSafeInteger(i)?i:void 0}function tt(t){let n=pn(t);return n!==void 0&&n>0?n:void 0}function nt(t){return t.VITEST==="true"||t.VITEST==="1"||t.VITEST_POOL_ID!==void 0||t.VITEST_WORKER_ID!==void 0||t.NODE_ENV==="test"||t!==process.env&&nt(process.env)}var Re=2147483647,Z=30000;function ve(t){let n=setTimeout(t,Z);return n.unref?.(),n}function we(t){if(t!==null)clearTimeout(t);return null}var Ce=30000;var rt=Z;function D(t,n){let i=n?.minMs??1,a=Math.min(Re,Math.max(0,Number.isFinite(i)?Math.floor(i):1));return Math.min(Re,Math.max(a,Number.isFinite(t)?Math.floor(t):a))}function Me(t,n,i){return D(typeof t==="number"&&Number.isFinite(t)?t:n,i)}function fe(t,n=rt){return Math.max(250,Math.min(Math.max(250,n),t))}function st(t=process.env){let n=t.OPENCLAW_CONNECT_CHALLENGE_TIMEOUT_MS;if(n){let i=tt(n);if(i!==void 0)return D(i)}}function ot(t,n){let i=Oe({env:n?.env,configuredTimeoutMs:n?.configuredTimeoutMs}),a=Math.max(Z,i);if(typeof t==="number"&&Number.isFinite(t))return fe(t,a);let l=st(n?.env);if(l!==void 0)return fe(l,Math.max(a,l));return fe(i,a)}function Oe(t){let n=t?.env??process.env,i=n.OPENCLAW_HANDSHAKE_TIMEOUT_MS||(nt(n)?n.OPENCLAW_TEST_HANDSHAKE_TIMEOUT_MS:void 0);if(i){let l=tt(i);if(l!==void 0)return D(l)}let a=t?.configuredTimeoutMs;if(typeof a==="number"&&Number.isFinite(a)&&a>0)return D(a);return Z}function fn(t){if(typeof t!=="string")return null;let n=t.trim();return n?n:null}function U(t){return fn(t)??void 0}function ee(t){return typeof t==="number"&&Number.isInteger(t)&&t>0?t:void 0}function Ne(t){return typeof t==="number"&&Number.isInteger(t)&&t>=0?t:void 0}function V(t){return t!==null&&typeof t==="object"&&!Array.isArray(t)}function hn(t){if(!Array.isArray(t))return[];return t.flatMap((n)=>{let i=U(n);return i?[i]:[]})}function be(t){let n=hn(t);return n.length>0?n:void 0}var C={AUTH_REQUIRED:"AUTH_REQUIRED",AUTH_UNAUTHORIZED:"AUTH_UNAUTHORIZED",AUTH_TOKEN_MISSING:"AUTH_TOKEN_MISSING",AUTH_TOKEN_MISMATCH:"AUTH_TOKEN_MISMATCH",AUTH_TOKEN_NOT_CONFIGURED:"AUTH_TOKEN_NOT_CONFIGURED",AUTH_PASSWORD_MISSING:"AUTH_PASSWORD_MISSING",AUTH_PASSWORD_MISMATCH:"AUTH_PASSWORD_MISMATCH",AUTH_PASSWORD_NOT_CONFIGURED:"AUTH_PASSWORD_NOT_CONFIGURED",AUTH_BOOTSTRAP_TOKEN_INVALID:"AUTH_BOOTSTRAP_TOKEN_INVALID",AUTH_DEVICE_TOKEN_MISMATCH:"AUTH_DEVICE_TOKEN_MISMATCH",AUTH_SCOPE_MISMATCH:"AUTH_SCOPE_MISMATCH",AUTH_RATE_LIMITED:"AUTH_RATE_LIMITED",AUTH_TAILSCALE_IDENTITY_MISSING:"AUTH_TAILSCALE_IDENTITY_MISSING",AUTH_TAILSCALE_PROXY_MISSING:"AUTH_TAILSCALE_PROXY_MISSING",AUTH_TAILSCALE_WHOIS_FAILED:"AUTH_TAILSCALE_WHOIS_FAILED",AUTH_TAILSCALE_IDENTITY_MISMATCH:"AUTH_TAILSCALE_IDENTITY_MISMATCH",AUTH_IDENTITY_HEADER_REQUIRED:"AUTH_IDENTITY_HEADER_REQUIRED",AUTH_VERIFIED_USER_REQUIRED:"AUTH_VERIFIED_USER_REQUIRED",AUTHENTICATED_PROFILE_UNAVAILABLE:"AUTHENTICATED_PROFILE_UNAVAILABLE",OPERATOR_ACCESS_DENIED:"OPERATOR_ACCESS_DENIED",CONTROL_UI_BUILD_MISMATCH:"CONTROL_UI_BUILD_MISMATCH",CONTROL_UI_ORIGIN_NOT_ALLOWED:"CONTROL_UI_ORIGIN_NOT_ALLOWED",PROTOCOL_MISMATCH:"PROTOCOL_MISMATCH",CONTROL_UI_DEVICE_IDENTITY_REQUIRED:"CONTROL_UI_DEVICE_IDENTITY_REQUIRED",DEVICE_IDENTITY_REQUIRED:"DEVICE_IDENTITY_REQUIRED",DEVICE_AUTH_INVALID:"DEVICE_AUTH_INVALID",DEVICE_AUTH_DEVICE_ID_MISMATCH:"DEVICE_AUTH_DEVICE_ID_MISMATCH",DEVICE_AUTH_SIGNATURE_EXPIRED:"DEVICE_AUTH_SIGNATURE_EXPIRED",DEVICE_AUTH_NONCE_REQUIRED:"DEVICE_AUTH_NONCE_REQUIRED",DEVICE_AUTH_NONCE_MISMATCH:"DEVICE_AUTH_NONCE_MISMATCH",DEVICE_AUTH_SIGNATURE_INVALID:"DEVICE_AUTH_SIGNATURE_INVALID",DEVICE_AUTH_PUBLIC_KEY_INVALID:"DEVICE_AUTH_PUBLIC_KEY_INVALID",PAIRING_REQUIRED:"PAIRING_REQUIRED",PAIRING_REJECTED:"PAIRING_REJECTED",PAIRING_EXPIRED:"PAIRING_EXPIRED",CLIENT_VERSION_MISMATCH:"CLIENT_VERSION_MISMATCH"},En=["retry_with_device_token","update_auth_configuration","update_auth_credentials","wait_then_retry","review_auth_configuration"],yn=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,Pe={"not-paired":{message:"device pairing required",requirement:"device is not approved yet",remediationHint:"Approve this device from the pending pairing requests.",recoveryTitle:"Gateway pairing approval required."},"role-upgrade":{message:"role upgrade pending approval",requirement:"device is asking for a higher role than currently approved",remediationHint:"Review the requested role upgrade, then approve the pending request.",recoveryTitle:"Gateway role upgrade approval required."},"scope-upgrade":{message:"scope upgrade pending approval",requirement:"device is asking for more scopes than currently approved",remediationHint:"Review the requested scopes, then approve the pending upgrade.",recoveryTitle:"Gateway scope upgrade approval required."},"metadata-upgrade":{message:"device metadata change pending approval",requirement:"device identity changed and must be re-approved",remediationHint:"Review the refreshed device details, then approve the pending request.",recoveryTitle:"Gateway device refresh approval required."}},es=new Map([["token_missing",C.AUTH_TOKEN_MISSING],["token_mismatch",C.AUTH_TOKEN_MISMATCH],["token_missing_config",C.AUTH_TOKEN_NOT_CONFIGURED],["password_missing",C.AUTH_PASSWORD_MISSING],["password_mismatch",C.AUTH_PASSWORD_MISMATCH],["password_missing_config",C.AUTH_PASSWORD_NOT_CONFIGURED],["bootstrap_token_invalid",C.AUTH_BOOTSTRAP_TOKEN_INVALID],["tailscale_user_missing",C.AUTH_TAILSCALE_IDENTITY_MISSING],["tailscale_proxy_missing",C.AUTH_TAILSCALE_PROXY_MISSING],["tailscale_whois_failed",C.AUTH_TAILSCALE_WHOIS_FAILED],["tailscale_user_mismatch",C.AUTH_TAILSCALE_IDENTITY_MISMATCH],["rate_limited",C.AUTH_RATE_LIMITED],["device_token_mismatch",C.AUTH_DEVICE_TOKEN_MISMATCH],["scope_mismatch",C.AUTH_SCOPE_MISMATCH],[void 0,C.AUTH_REQUIRED]]),ts=new Map([["device-id-mismatch",C.DEVICE_AUTH_DEVICE_ID_MISMATCH],["device-signature-stale",C.DEVICE_AUTH_SIGNATURE_EXPIRED],["device-nonce-missing",C.DEVICE_AUTH_NONCE_REQUIRED],["device-nonce-mismatch",C.DEVICE_AUTH_NONCE_MISMATCH],["device-signature",C.DEVICE_AUTH_SIGNATURE_INVALID],["device-public-key",C.DEVICE_AUTH_PUBLIC_KEY_INVALID]]);function q(t){if(!V(t))return null;return U(t.code)??null}function it(t){if(!V(t))return{};return{canRetryWithDeviceToken:typeof t.canRetryWithDeviceToken==="boolean"?t.canRetryWithDeviceToken:void 0,recommendedNextStep:at(t.recommendedNextStep)}}function at(t){let n=U(t)??"";return En.find((i)=>i===n)}function mn(t){let n=U(t)??"";return Object.hasOwn(Pe,n)?n:void 0}function In(t){let n=U(t);return n&&yn.test(n)?n:void 0}function gn(t){return{code:C.PAIRING_REQUIRED,...t.reason?{reason:t.reason}:{},...t.requestId?{requestId:t.requestId}:{},...t.remediationHint?{remediationHint:t.remediationHint}:{},...t.recommendedNextStep?{recommendedNextStep:t.recommendedNextStep}:{},...t.retryable!==void 0?{retryable:t.retryable}:{},...t.pauseReconnect!==void 0?{pauseReconnect:t.pauseReconnect}:{},...t.waitForResolution!==void 0?{waitForResolution:t.waitForResolution}:{},...t.deviceId?{deviceId:t.deviceId}:{},...t.requestedRole?{requestedRole:t.requestedRole}:{},...t.requestedScopes?{requestedScopes:t.requestedScopes}:{},...t.approvedRoles?{approvedRoles:t.approvedRoles}:{},...t.approvedScopes?{approvedScopes:t.approvedScopes}:{}}}function Tn(t,n){return{requestId:In(t.requestId),remediationHint:U(t.remediationHint)??(n?Pe[n].remediationHint:"Approve the pending device request before retrying."),deviceId:U(t.deviceId),requestedRole:U(t.requestedRole),requestedScopes:be(t.requestedScopes),approvedRoles:be(t.approvedRoles),approvedScopes:be(t.approvedScopes)}}function ke(t){if(q(t)!==C.PAIRING_REQUIRED)return null;if(!V(t))return null;let n=mn(t.reason);return gn({...Tn(t,n),reason:n,recommendedNextStep:at(t.recommendedNextStep),retryable:typeof t.retryable==="boolean"?t.retryable:void 0,pauseReconnect:typeof t.pauseReconnect==="boolean"?t.pauseReconnect:void 0,waitForResolution:typeof t.waitForResolution==="boolean"?t.waitForResolution:void 0})}function _n(t){let n=ke(t),i=Pe[n?.reason??"not-paired"].message;return n?.requestId?`${i} (requestId: ${n.requestId})`:i}function ct(t){let n=q(t.details);if(n===C.PAIRING_REQUIRED)return _n(t.details);if(n===C.PROTOCOL_MISMATCH)return An(t.message,t.details);return U(t.message)??"gateway request failed"}function An(t,n){let i=n,a=ee(i.clientMinProtocol),l=ee(i.clientMaxProtocol),p=ee(i.expectedProtocol),f=ee(i.minimumProbeProtocol),y=[];if(a!==void 0&&l!==void 0)y.push(a===l?`Control UI v${a}`:`Control UI v${a}-v${l}`);if(p!==void 0)y.push(`Gateway v${p}`);if(f!==void 0)y.push(`connection check min v${f}`);let S=U(t)??"protocol mismatch";return y.length>0?`${S}: ${y.join(", ")}`:S}function te(t){return typeof t==="string"&&t.length>0}function Sn(t){if(!V(t))return!1;if(!te(t.code)||!te(t.message))return!1;if(t.retryable!==void 0&&typeof t.retryable!=="boolean")return!1;return t.retryAfterMs===void 0||Ne(t.retryAfterMs)!==void 0}function lt(t){if(!V(t)||t.type!=="event"||!te(t.event))return!1;return t.seq===void 0||Ne(t.seq)!==void 0}function ut(t){if(!V(t)||t.type!=="res"||!te(t.id)||typeof t.ok!=="boolean")return!1;return t.error===void 0||Sn(t.error)}var ne=60000;function De(t){return pt(t,"gateway-restarting")}function dt(t){return pt(t,"gateway-suspending")}function pt(t,n){if(!t||typeof t!=="object"||!("details"in t))return!1;let i=t.details;return typeof i==="object"&&i!==null&&"reason"in i&&i.reason===n}function Rn(t){return typeof t==="object"&&t!==null&&t.reason==="startup-sidecars"}function Ue(t){if(!t||typeof t!=="object")return!1;let n=t;return(n.gatewayCode??n.code)==="UNAVAILABLE"&&n.retryable===!0&&Rn(n.details)}function ft(t){if(!Ue(t))return null;let n=t.retryAfterMs;return Math.min(Math.max(Math.floor(typeof n==="number"&&Number.isFinite(n)?n:500),100),2000)}function xe(t){if(typeof t!=="string")return"";return t.trim().replace(/[A-Z]/g,(n)=>String.fromCharCode(n.charCodeAt(0)+32))}function ht(t){let n=t.scopes.join(","),i=t.token??"",a=xe(t.platform),l=xe(t.deviceFamily);return["v3",t.deviceId,t.clientId,t.clientMode,t.role,n,String(t.signedAtMs),i,t.nonce,a,l].join("|")}function qe(t){return t!==null&&typeof t==="object"&&!Array.isArray(t)}function Ee(t){return vn(t)??{}}function Et(t){return qe(t)?t:void 0}function vn(t){return t&&typeof t==="object"?t:void 0}function yt(t){let n=k(t.token),i=k(t.bootstrapToken),a=k(t.deviceToken),l=k(t.password),p=k(t.storedToken),f={storedToken:p,storedScopes:t.storedScopes};if(t.preferBootstrapToken&&i)return{authBootstrapToken:i,signatureToken:i,...f};let y=t.pendingDeviceTokenRetry===!0&&!a&&Boolean(n&&p&&t.trustedDeviceTokenRetry),S=a??(y||!(n||l)&&(!i||p)?p:void 0),v=Boolean(S&&!a&&p)&&S===p,w=n??S,R=!n&&!S&&!l?i:void 0;return{authToken:n,authBootstrapToken:R,authDeviceToken:y?p:void 0,authPassword:l,authApprovalRuntimeToken:k(t.approvalRuntimeToken),authAgentRuntimeIdentityToken:k(t.agentRuntimeIdentityToken),signatureToken:w??R,resolvedDeviceToken:S,usingStoredDeviceToken:v,...f}}function mt(t){let n={token:t.authToken,bootstrapToken:t.authBootstrapToken,deviceToken:t.authDeviceToken??t.resolvedDeviceToken,password:t.authPassword,approvalRuntimeToken:t.authApprovalRuntimeToken,agentRuntimeIdentityToken:t.authAgentRuntimeIdentityToken};return Object.values(n).some(Boolean)?n:void 0}function It(t){return t.requestedScopes??(t.usingStoredDeviceToken&&t.storedScopes?.length?t.storedScopes:[...t.defaultScopes])}function gt(t){if(t.retryBudgetUsed||t.currentDeviceToken||!t.explicitToken||!t.storedToken||!t.trustedEndpoint)return!1;let n=it(t.errorDetails);return t.canRetryWithDeviceTokenHint===!0||n.canRetryWithDeviceToken===!0||n.recommendedNextStep==="retry_with_device_token"||q(t.errorDetails)===C.AUTH_TOKEN_MISMATCH}var Le="model-catalog-snapshot";function Tt(t){let n=t.serverCapabilities.includes(Le)?t.modelCatalog:void 0,i=t.caps?.filter((a)=>a!==Le);if(n===void 0)return{caps:i};return{modelCatalog:n,caps:[...i??[],Le]}}var He=[[[183,183],[12288,12703],[19968,40869],[44032,55215],[65281,65376]],[[4352,4607],[11904,12287],[12704,19967],[40870,40959],[40960,42239],[42752,42759],[43360,43391],[55216,55295],[63744,64255]],[[711,711],[713,715],[729,729],[746,747],[773,773],[803,803],[65040,65103],[65377,65500],[65504,65510]],[[119648,119665]],[[94176,94207],[110576,110591],[110592,110959],[127488,127743],[131072,195103],[196608,210047]]];new RegExp(`[${He.flatMap((t)=>t.map(([n,i])=>`\\u{${n.toString(16)}}-\\u{${i.toString(16)}}`)).join("")}]`,"u");(()=>{let t=Math.max(...He.flatMap((i)=>i.map(([,a])=>a))),n=new Uint8Array(t+1);for(let[i,a]of He.entries())for(let[l,p]of a)n.fill(i+1,l,p+1);return n})();function K(t){return t instanceof Error?t:Error(String(t))}function wn(t){return Array.isArray(t)?t.filter((n)=>typeof n==="string"):[]}var me=2147000000;function Ie(t,n){let i=Error(t,n);return i.name="AbortError",i}async function _t(t,n,i,a={}){let l,p;try{let f=new Promise((S,v)=>{let w=(_)=>{try{S(_())}catch(c){v(c)}};if(l=setTimeout(()=>w(i),n),a.ref===!1)l.unref?.();let R=a.signal;if(R){if(p=()=>w(()=>{if(a.onAbort)return a.onAbort(R);throw Ie("Operation aborted",{cause:R.reason})}),R.addEventListener("abort",p,{once:!0}),R.aborted)p()}}),y;try{y=typeof t==="function"?t():t}catch(S){throw f.catch(()=>{}),S}return await Promise.race([y,f])}finally{if(clearTimeout(l),p)a.signal?.removeEventListener("abort",p)}}function Cn(t,n){let i=Math.min(t.maxMs,t.initialMs*t.factor**Math.max(n-1,0)),a=i*t.jitter*Math.random();return Math.min(t.maxMs,Math.round(i+a))}function At(t){return Number.isFinite(t)&&t>0?Math.min(Math.max(Math.floor(t),1),me):0}async function Mn(t,n,i={}){let a=At(t);if(a===0)return;await new Promise((l,p)=>{let f=()=>n?.removeEventListener("abort",S),y=setTimeout(()=>{f(),l()},a),S=()=>{clearTimeout(y),f(),p(Ie("aborted",{cause:n?.reason??Error("aborted")}))};if(n?.addEventListener("abort",S,{once:!0}),n?.aborted){S();return}if(i.ref===!1)y.unref?.()})}var On=class{constructor(t,n=Number.POSITIVE_INFINITY){this.policy=t,this.maxAttempts=n,this.attempts=0,this.initialMs=t.initialMs}reset(t=this.policy.initialMs){this.cancel(),this.attempts=0,this.initialMs=t,this.nextDelayOverrideMs=void 0}cancel(t=Error("retry cancelled")){this.pendingAbort?.abort(t),this.pendingAbort=void 0}next(t){let n=this.nextDelayOverrideMs;if(this.nextDelayOverrideMs=void 0,n===void 0&&++this.attempts>Math.ceil(this.maxAttempts))return;let i=Math.max(this.attempts,1),a=n??Cn({...this.policy,initialMs:this.initialMs},i);this.cancel();let l=new AbortController;return this.pendingAbort=l,{attempt:i,delayMs:a,signal:t?AbortSignal.any([l.signal,t]):l.signal}}},St={attempts:3,minDelayMs:300,maxDelayMs:30000,jitter:0},Nn=async(t)=>{let n=t;do{let i=Math.min(n,me);await new Promise((a)=>{setTimeout(a,i)}),n-=i}while(n>0)};function ye(t,n,i,a){if(typeof t!=="number"||!Number.isFinite(t))return n;return Math.min(Math.max(t,i??Number.NEGATIVE_INFINITY),a??Number.POSITIVE_INFINITY)}function re(t){return Math.min(Math.max(Math.round(t===Number.POSITIVE_INFINITY?me:Number.isFinite(t)?t:0),0),me)}function bn(t=St,n){let i=Math.max(1,Math.round(ye(n?.attempts,t.attempts))),a=re(ye(n?.minDelayMs,t.minDelayMs,0)),l=Math.max(a,re(ye(n?.maxDelayMs,t.maxDelayMs,0))),p=n?.jitter,f=t.jitter;return{attempts:i,minDelayMs:a,maxDelayMs:l,jitter:p==="full"?p:typeof p==="number"&&Number.isFinite(p)?Math.min(Math.max(p,0),1):f}}function Pn(t,n,i,a){if(n==="full"){if(i==="symmetric")return Math.max(0,Math.round(t*(0.5+a()*0.5)));return Math.max(0,Math.ceil(t*(1+a())))}if(n<=0)return i==="positive"?Math.ceil(t):t;let l=a(),p=t*(1+(i==="positive"?l*n:(l*2-1)*n));return Math.max(0,i==="positive"?Math.ceil(p):Math.round(p))}function kn(t,n="Non-Error thrown"){if(t instanceof Error)return t;if(typeof t==="string")return Error(t);let i=Error(n,{cause:t});if(typeof t==="object"&&t!==null||typeof t==="function")Object.assign(i,t);return i}function Dn(t={}){let n=t.sleep??Nn,i=t.random??Math.random,a=t.createFailure??((l)=>kn(l.at(-1)??Error("Retry failed")));return async function(p,f=3,y=300){let S=[],v=typeof f==="number",w=typeof f==="number"?{attempts:f}:f,R=bn(St,w),{attempts:_,minDelayMs:c}=R,d=R.maxDelayMs>0?R.maxDelayMs:Number.POSITIVE_INFINITY,E=w.retryAfterMaxDelayMs===void 0?d:Math.max(c,re(ye(w.retryAfterMaxDelayMs,d,0))),h=w.random??i,A=w.sleep??n,I=w.shouldRetry??(()=>!0);for(let M=1;M<=_;M+=1)try{return await p()}catch(O){if(S.push(O),M>=_||t.shouldRetry?.(O)===!1||!I(O,M))break;if(v){await n(re(y*2**(M-1)));continue}let b={attempt:M,maxAttempts:_,err:O,label:w.label},N=w.retryAfterMs?.(O),x=typeof N==="number"&&Number.isFinite(N),J=typeof w.delayMs==="function"?w.delayMs(b):w.delayMs,le=J===void 0?void 0:re(J),ue=x?Math.max(N,c):le===void 0?c*2**(M-1):Math.max(le,c),H=x?E:d,F=Math.min(ue,H),de=x&&(N??0)<=H,pe=R.jitter==="full"?!x||de:de;if(F=Pn(F,R.jitter,pe?"positive":"symmetric",h),F=Math.min(Math.max(F,c),H),await w.onRetry?.({...b,delayMs:F}),F>0)await A(F)}throw a(S)}}Dn();var Un=class{constructor(){this.listeners=new Map}add(t){let n=this.listeners.get(t)??{};return this.listeners.set(t,n),()=>{if(this.listeners.get(t)===n)this.listeners.delete(t)}}snapshot(){return[...this.listeners]}isCurrent(t,n){return this.listeners.get(t)===n}},Ln=new WeakSet;var z=class extends Error{constructor(t){super(t.message??"request failed");this.name="GatewayProtocolRequestError",this.code=t.code??"UNAVAILABLE",this.gatewayCode=this.code,this.details=t.details,this.retryable=t.retryable===!0,this.retryAfterMs=t.retryAfterMs}};function xn(t,n){Ln.add(t),Object.defineProperty(t,"responsePayload",{value:n,enumerable:!1,configurable:!0})}var Fe=class extends Error{constructor(t,n=`gateway request timed out after ${t.timeoutMs}ms: ${t.method}`){super(n);this.code="CLIENT_TIMEOUT",this.name="GatewayProtocolRequestTimeoutError",this.method=t.method,this.timeoutMs=t.timeoutMs,this.requestSent=t.requestSent}},Hn=class{constructor(t){this.opts=t,this.pending=new Map,this.requestSequence=0}setSuspensionPhase(t){if(t==="accepting")this.resumeBootstrapRequests();else if(t==="preparing"||t==="draining"||t==="prepared")this.pauseBootstrapRequests(void 0,!0)}pauseBootstrapRequests(t=ne,n=!1){let i=this.opts.nowMs(),a=D(Number.isFinite(t)&&t>0?t:ne),l=this.bootstrapPause??={retryAtMs:i,revision:0,announced:n};if(l.announced||=n,l.revision+=1,l.retryAtMs=Math.max(l.retryAtMs,i+a),clearTimeout(l.timer),l.timer=void 0,l.announced)return;l.timer=setTimeout(()=>{l.timer=void 0,this.drainBootstrapRequests()},D(l.retryAtMs-i)),l.timer.unref?.()}resumeBootstrapRequests(){clearTimeout(this.bootstrapPause?.timer),this.bootstrapPause=void 0,this.drainBootstrapRequests()}drainBootstrapRequests(){for(let t of this.pending.values())if(t.waitingForResume)t.resend?.()}get hasPending(){return this.pending.size>0}get hasUnboundedPending(){for(let t of this.pending.values())if(t.unbounded)return!0;return!1}releaseHeldRequests(t){for(let n of this.pending.values()){if(!t())return;let i=n.afterHello;n.afterHello=void 0,i?.()}}request(t,n,i,a,l=!1){let p;try{this.requestSequence+=1,p=`${this.requestSequence}:${this.opts.createRequestId()}`}catch(S){return Promise.reject(K(S))}let f=a?.timeoutMs===null?void 0:a?.timeoutMs??this.opts.requestTimeoutMs,y=typeof f==="number"&&Number.isFinite(f)?D(f,{minMs:0}):void 0;return new Promise((S,v)=>{let w,R,_=!1,c=!1,d={resolve:(I)=>S(I),reject:v,expectFinal:a?.expectFinal===!0,acceptedNotified:!1,onAccepted:a?.onAccepted,unbounded:y===void 0,method:n,startedAtMs:this.opts.nowMs(),prepareRetry:()=>{if(c=!1,_=!1,a?.signal?.aborted)return A(),!1;return!0}},E=()=>{if(clearTimeout(R),w!==void 0)clearTimeout(w);if(a?.signal?.removeEventListener("abort",A),this.bootstrapPause?.probe?.pending===d)this.bootstrapPause.probe=void 0,this.drainBootstrapRequests()},h=(I)=>{if(this.pending.get(p)!==d)return!1;return this.pending.delete(p),E(),this.finishTiming(p,d,!1,I),!0},A=()=>{if(a?.retainSentResultOnAbort&&c)return;if(!h("CLIENT_ABORTED"))return;v(this.opts.createRequestAbortError?.(n)??Error(`gateway request aborted for ${n}`))};if(a?.signal?.aborted){v(this.opts.createRequestAbortError?.(n)??Error(`gateway request aborted for ${n}`));return}if(d.cleanup=E,y!==void 0)w=setTimeout(()=>{if(!h("CLIENT_TIMEOUT"))return;v(this.opts.createRequestTimeoutError?.(n,y,_)??new Fe({method:n,timeoutMs:y,requestSent:_}))},y),w.unref?.();a?.signal?.addEventListener("abort",A,{once:!0}),this.pending.set(p,d);try{let I=JSON.stringify({type:"req",id:p,method:n,params:i}),M=()=>{if(this.pending.get(p)!==d||a?.signal?.aborted||y!==void 0&&this.opts.nowMs()-d.startedAtMs>=y)return;let O=d.resend?this.bootstrapPause:void 0;if(O&&!O.announced&&!O.timer&&!O.probe)O.probe={pending:d,revision:O.revision};if(d.waitingForResume=Boolean(O&&(O.announced||O.probe?.pending!==d)),d.waitingForResume)return;try{if(c=!0,t.send(I),this.pending.get(p)!==d)return;_=c,this.invoke("sent",()=>a?.onSent?.(p))}catch(b){if(h("CLIENT_SEND_ERROR"))v(K(b))}};if(d.retryStartup=(O)=>{d.resend=M,clearTimeout(R),R=setTimeout(M,Me(O,ne)),R.unref?.()},n==="agent.identity.get"||n==="sessions.subscribe"||n==="sessions.groups.list"||n==="question.list"||n==="sessions.list")d.resend=M;if(l)d.afterHello=M;else M()}catch(I){if(h("CLIENT_SEND_ERROR"))v(K(I))}})}handleResponse(t){let n=this.pending.get(t.id);if(!n)return;let i=t.payload?.status;if(t.ok&&n.expectFinal&&i==="accepted"){if(!n.acceptedNotified)n.acceptedNotified=!0,this.invoke("accepted",()=>n.onAccepted?.(t.payload));return}let a=t.error?.details;if(!t.ok&&Ue(t.error)&&a!==null&&typeof a==="object"&&"method"in a&&a.method===n.method&&!n.acceptedNotified){if(n.prepareRetry()){if(n.retryStartup?.(t.error?.retryAfterMs),this.bootstrapPause?.probe?.pending===n&&this.bootstrapPause.probe.revision===this.bootstrapPause.revision)this.resumeBootstrapRequests()}return}if(!t.ok&&n.resend&&!n.acceptedNotified&&t.error?.code==="UNAVAILABLE"&&t.error.retryable===!0&&(dt(t.error)||De(t.error))){if(!n.prepareRetry())return;if(this.bootstrapPause?.probe?.pending===n)this.bootstrapPause.probe=void 0;this.pauseBootstrapRequests(De(t.error)?Math.ceil(Math.max(ne,t.error.retryAfterMs??0)*(1+Math.random()*0.2)):t.error.retryAfterMs),n.waitingForResume=!0;return}if(this.pending.delete(t.id),t.ok&&this.bootstrapPause?.probe?.pending===n&&this.bootstrapPause.probe.revision===this.bootstrapPause.revision)this.resumeBootstrapRequests();if(n.cleanup?.(),t.ok){this.finishTiming(t.id,n,!0),n.resolve(t.payload);return}this.finishTiming(t.id,n,!1,t.error?.code);let l=this.opts.createRequestError?.(t.error??{})??new z(t.error??{});xn(l,t.payload),n.reject(l)}flush(t){clearTimeout(this.bootstrapPause?.timer),this.bootstrapPause=void 0;let n=this.pending;this.pending=new Map,this.requestSequence=0;for(let[i,a]of n)a.cleanup?.(),this.finishTiming(i,a,!1,"CLIENT_CLOSED"),a.reject(t)}finishTiming(t,n,i,a){let l=this.opts.nowMs();this.invoke("request timing",()=>this.opts.onTiming?.({id:t,method:n.method,ok:i,durationMs:Math.max(0,l-n.startedAtMs),startedAtMs:n.startedAtMs,endedAtMs:l,errorCode:a}))}invoke(t,n){try{n()}catch(i){this.opts.onCallbackError?.(t,i)}}},he=Object.freeze({closeCode:1008,closeReason:"connect failed"}),Rt=class{constructor(t){this.opts=t,this.socket=null,this.listeners=new Un,this.stopped=!0,this.generation=0,this.connectionAbort=null,this.lastSeq=null,this.connectNonce=null,this.serverCapabilities=[],this.connectSent=!1,this.connectRequestSent=!1,this.handshakeTimer=null,this.reconnectSignal=null,this.socketOpened=!1,this.helloReceived=!1,this.readyForRequests=!1,this.connectTiming=null,this.reconnectSupervisor=new On({initialMs:t.reconnect.initialMs,maxMs:t.reconnect.maxMs,factor:t.reconnect.multiplier,jitter:0}),this.requests=new Hn({createRequestId:t.createRequestId,createRequestError:t.createRequestError,createRequestTimeoutError:t.createRequestTimeoutError,createRequestAbortError:t.createRequestAbortError,requestTimeoutMs:t.requestTimeoutMs,nowMs:()=>this.nowMs(),onTiming:t.onRequestTiming,onCallbackError:t.onCallbackError})}get connected(){return this.socket?.isOpen()??!1}get hasPendingRequests(){return this.requests.hasPending}get connecting(){return this.connectSent&&!this.helloReceived}get opening(){return this.socket!==null&&!this.socketOpened}get hasUnboundedPendingRequests(){return this.requests.hasUnboundedPending}start(){if(this.socket||this.reconnectSignal)return;this.stopped=!1,this.reconnectSupervisor.cancel(),this.connect()}stop(){this.stopped=!0,this.connectionAbort?.abort(),this.clearHandshakeTimer(),this.reconnectSignal=null,this.reconnectSupervisor.reset();let t=this.socket;if(t&&this.opts.notifyStoppedClose)this.stoppedSocket={socket:t,context:this.closeContext()};this.socket=null,this.connectFailure=void 0,this.connectTiming=null,this.requests.flush(Error("gateway client stopped")),t?.close()}request(t,n,i){let a=this.socket;if(!a||this.socketOpened&&!a.isOpen())return Promise.reject(Error("gateway not connected"));if(typeof t!=="string"||t.length===0)return Promise.reject(Error("invalid request frame: method must be a non-empty string"));return this.requests.request(a,t,n,i,!this.readyForRequests)}addEventListener(t){return this.listeners.add(t)}closeSocket(t,n){this.connectionAbort?.abort(),this.socket?.close(t,n)}resetReconnectBackoff(t){this.reconnectSignal=null,this.reconnectSupervisor.reset(t)}recordTiming(t,n,i,a){let l=this.nowMs(),p=this.connectTiming;if(!p||p.generation!==n)return;if(p.hasChallenge||=t==="challenge",p.usedFallback||=t==="fallback",this.invoke("connect timing",()=>this.opts.onTiming?.({phase:t,generation:n,durationMs:Math.max(0,l-p.startedAtMs),phaseDurationMs:Math.max(0,l-p.lastAtMs),hasChallenge:p.hasChallenge,usedFallback:p.usedFallback,plan:i,detail:a})),p.lastAtMs=l,t==="hello"||t==="failed")this.connectTiming=null}connect(){if(this.stopped)return;let t=this.generation+1;this.lastSeq=null,this.connectNonce=null,this.connectChallengeTs=void 0,this.serverCapabilities=[],this.connectSent=this.connectRequestSent=!1,this.socketOpened=!1,this.helloReceived=!1,this.readyForRequests=!1,this.connectFailure=void 0;let n;try{n=this.opts.createSocket({open:()=>{if(!this.isActive(n,t))return;if(this.socketOpened=!0,this.recordTiming("socket-open",t),this.connectNonce){this.sendConnect(n,t);return}this.clearHandshakeTimer();let a=Date.now();this.handshakeTimer=setTimeout(()=>{if(this.handshakeTimer=null,!this.isActive(n,t)||this.connectSent||!n.isOpen())return;if(this.opts.handshake.mode==="fallback"){this.recordTiming("fallback",t),this.sendConnect(n,t);return}let l=Date.now()-a,p=Error(this.opts.handshake.timeoutMessage?.(l)??`gateway connect challenge timeout after ${l}ms`);this.opts.onConnectError?.(p),n.close(1008,"connect challenge timeout")},this.opts.handshake.timeoutMs),this.handshakeTimer.unref?.()},message:(a)=>this.handleMessage(n,t,a),close:(a,l)=>{if(this.socket!==n){if(this.stoppedSocket?.socket===n){let y={...this.stoppedSocket.context,code:a,reason:l};this.stoppedSocket=void 0,this.invoke("close",()=>this.opts.onClose?.(y,{retry:!1,notify:!0}))}return}this.socket=null,this.connectionAbort?.abort(),this.clearHandshakeTimer();let p={...this.closeContext(),code:a,reason:l,generation:t};this.connectFailure=void 0;let f=this.opts.resolveClose(p);if(this.requests.flush(f.pendingError??p.connectFailure?.error??Error(`gateway closed (${a}): ${l}`)),this.invoke("close",()=>this.opts.onClose?.(p,f)),f.retry&&!this.stopped&&!this.socket&&!this.reconnectSignal){let y=p.connectFailure?.error,S=y instanceof z&&y.retryable&&y.retryAfterMs!==void 0&&Number.isFinite(y.retryAfterMs)&&y.retryAfterMs>0?y.retryAfterMs:void 0;this.scheduleReconnect(f.reconnectDelayMs??p.connectFailure?.reconnectDelayMs,S)}},error:(a)=>{if(!this.isActive(n,t)||this.connectSent)return;this.connectFailure={error:a},this.opts.onConnectError?.(a)}})}catch(a){let l=K(a);if(this.opts.onSocketFactoryError?.(l),this.opts.onConnectError?.(l),this.opts.rethrowSocketFactoryError?.(l)){if(this.generation>0&&!this.stopped&&!this.socket&&!this.reconnectSignal)this.opts.onReconnectStopped?.(l);throw l}if(this.opts.shouldRetrySocketFactoryError?.(l)&&!this.stopped&&!this.socket&&!this.reconnectSignal)this.scheduleReconnect();else if(this.generation>0&&!this.stopped&&!this.socket&&!this.reconnectSignal)this.opts.onReconnectStopped?.(l);return}this.generation=t,this.connectionAbort=new AbortController,this.socket=n;let i=this.nowMs();this.connectTiming={generation:t,startedAtMs:i,lastAtMs:i,hasChallenge:!1,usedFallback:!1}}sendConnect(t,n){if(!this.isActive(t,n)||!t.isOpen()||this.connectSent)return;this.connectSent=!0,this.clearHandshakeTimer(),this.handshakeTimer=ve(()=>{if(this.isActive(t,n)&&!this.helloReceived)t.close(4000,"connect timeout")});let i;try{i=this.opts.buildConnectPlan({nonce:this.connectNonce,challengeTs:this.connectChallengeTs,serverCapabilities:this.serverCapabilities,generation:n,...this.connectAuthority(t,n)})}catch(a){this.handleConnectPlanError(t,n,a);return}if(i instanceof Promise){i.then((a)=>this.sendConnectPlan(t,n,a)).catch((a)=>this.handleConnectPlanError(t,n,a));return}this.sendConnectPlan(t,n,i)}handleConnectPlanError(t,n,i){if(!this.isConnectCurrent(t,n))return;let a=K(i),l=this.opts.onConnectPlanError?.(a)??he;if(this.opts.onConnectError?.(l.error??a),l.stop)this.stopped=!0;t.close(l.closeCode,l.closeReason)}sendConnectPlan(t,n,i){if(!this.isConnectCurrent(t,n))return;let a={...this.connectAuthority(t,n),generation:n,nonce:this.connectNonce,challengeTs:this.connectChallengeTs,plan:i};this.recordTiming("connect-plan-ready",n,i),this.requests.request(t,"connect",this.opts.buildConnectParams(i),{onSent:()=>{this.connectRequestSent=!0,this.recordTiming("request-sent",n,i)}}).then((l)=>{if(!this.isConnectCurrent(t,n))return;this.helloReceived=!0,this.requests.setSuspensionPhase(l.snapshot?.suspension?.phase),this.clearHandshakeTimer(),this.connectFailure=void 0,this.reconnectSupervisor.reset(),this.recordTiming("hello",n,i);let p=()=>{if(!this.isConnectCurrent(t,n))return;if(this.invoke("hello",()=>this.opts.onHello?.(l)),!this.isConnectCurrent(t,n))return;if(this.requests.releaseHeldRequests(()=>this.isConnectCurrent(t,n)),this.isConnectCurrent(t,n))this.readyForRequests=!0},f=this.opts.onConnectHello?.(l,a);if(f instanceof Promise)return f.then(p);return p()}).catch((l)=>{if(!this.isActive(t,n))return;let p=l instanceof z?l:new z({message:String(l)});this.connectFailure={error:p};let f=this.opts.onConnectFailure?.(p,a)??he,y=(S)=>{if(!this.isActive(t,n))return;if(this.connectFailure={error:p,reconnectDelayMs:S.reconnectDelayMs},S.keepOpen){this.clearHandshakeTimer();return}if(S.stop)this.stopped=!0;this.connectionAbort?.abort(),t.close(S.closeCode,S.closeReason)};if(f instanceof Promise)return f.then(y);return y(f)}).catch((l)=>{if(!this.isConnectCurrent(t,n))return;this.opts.onConnectError?.(K(l)),this.closeSocket(he.closeCode,he.closeReason)})}handleMessage(t,n,i){if(!this.isActive(t,n)||this.connectionAbort?.signal.aborted)return;let a;try{a=JSON.parse(i)}catch(l){this.opts.onParseError?.(l);return}if(lt(a)){if(this.opts.onActivity?.(),a.event==="connect.challenge"){let p=a.payload,f=typeof p?.nonce==="string"?p.nonce.trim():"";if(!f){if(this.opts.handshake.mode==="require-challenge"){let S=Error("gateway connect challenge missing nonce");this.opts.onConnectError?.(S),t.close(1008,"connect challenge missing nonce")}return}this.connectNonce=f,this.serverCapabilities=wn(p?.capabilities);let y=p?.ts;this.connectChallengeTs=typeof y==="number"&&Number.isSafeInteger(y)&&y>=0?y:null,this.recordTiming("challenge",n),this.sendConnect(t,n);return}let l=a.seq;if(l!==void 0){if(this.lastSeq!==null&&l>this.lastSeq+1){let p=this.lastSeq+1,f=Ee(a.payload).state;if(a.event==="chat"&&(f==="final"||f==="error"||f==="aborted"))this.dispatchEvent(t,n,a);if(!this.isActive(t,n)||this.connectionAbort?.signal.aborted)return;if(this.invoke("gap",()=>this.opts.onGap?.({expected:p,received:l})),this.isActive(t,n)&&!this.connectionAbort?.signal.aborted)this.closeSocket(4000,"event sequence gap");return}this.lastSeq=l}this.dispatchEvent(t,n,a);return}if(!ut(a))return;this.opts.onActivity?.(),this.requests.handleResponse(a)}dispatchEvent(t,n,i){let a=this.listeners.snapshot();if(i.event==="gateway.suspension")this.requests.setSuspensionPhase(Ee(i.payload).phase);else if(i.event==="shutdown"&&typeof Ee(i.payload).restartExpectedMs==="number")this.requests.setSuspensionPhase("draining");this.invoke("event",()=>this.opts.onEvent?.(i));for(let[l,p]of a){if(!this.isActive(t,n)||this.connectionAbort?.signal.aborted)return;if(this.listeners.isCurrent(l,p))this.invoke("event listener",()=>l(i))}}scheduleReconnect(t,n=0){if(t!==void 0)this.reconnectSupervisor.nextDelayOverrideMs=t;let i=this.reconnectSupervisor.next();if(!i)return;this.reconnectSignal=i.signal;let a=t;if(a===void 0){let l=Math.max(i.delayMs,n),p=Math.max(this.opts.reconnect.maxMs,Math.min(Number.MAX_VALUE,n*1.2)),f=Math.max(n,Math.min(l,p/1.2)),y=Math.min(l*1.2,p);a=Math.ceil(f+Math.random()*(y-f))}a=At(a),Mn(a,i.signal).then(()=>{if(this.reconnectSignal!==i.signal)return;this.reconnectSignal=null,this.invoke("reconnect",()=>this.connect())},()=>{if(this.reconnectSignal===i.signal)this.reconnectSignal=null}),this.invoke("reconnect scheduled",()=>this.opts.onReconnectScheduled?.(a,i.signal))}closeContext(){return{generation:this.generation,socketOpened:this.socketOpened,helloReceived:this.helloReceived,connectRequestSent:this.connectRequestSent,connectFailure:this.connectFailure}}isConnectCurrent(t,n){return this.isActive(t,n)&&t.isOpen()&&!this.connectionAbort?.signal.aborted}connectAuthority(t,n){let i=this.connectionAbort?.signal;if(!i)throw Error("gateway connection authority is unavailable");return{signal:i,assertCurrent:()=>{if(i.throwIfAborted(),!this.isConnectCurrent(t,n))throw Error("gateway connection retired")}}}isActive(t,n){return!this.stopped&&this.socket===t&&this.generation===n}nowMs(){return this.opts.nowMs?.()??Date.now()}clearHandshakeTimer(){this.handshakeTimer=we(this.handshakeTimer)}invoke(t,n){try{n()}catch(i){this.opts.onCallbackError?.(t,i)}}},qn=new Set([C.AUTH_TOKEN_MISSING,C.AUTH_BOOTSTRAP_TOKEN_INVALID,C.AUTH_PASSWORD_MISSING,C.AUTH_PASSWORD_MISMATCH,C.AUTH_RATE_LIMITED,C.AUTH_DEVICE_TOKEN_MISMATCH,C.AUTH_SCOPE_MISMATCH,C.AUTH_IDENTITY_HEADER_REQUIRED,C.AUTH_VERIFIED_USER_REQUIRED,C.CONTROL_UI_BUILD_MISMATCH,C.PAIRING_REQUIRED,C.PAIRING_REJECTED,C.PAIRING_EXPIRED,C.CONTROL_UI_DEVICE_IDENTITY_REQUIRED,C.DEVICE_IDENTITY_REQUIRED]);function vt(t){let n=q(t.details);if(!n)return!1;let i=ke(t.details);if(n===C.PAIRING_REQUIRED&&(i?.pauseReconnect===!1||i?.recommendedNextStep==="wait_then_retry"))return!1;if(n===C.AUTH_TOKEN_MISMATCH)return t.tokenMismatchIsTerminal===!0&&!t.deviceTokenRetryPending;if(n===C.AUTH_IDENTITY_HEADER_REQUIRED)return!t.deviceTokenRetryPending;return qn.has(n)||t.protocolMismatchIsTerminal===!0&&n===C.PROTOCOL_MISMATCH||t.clientVersionMismatchIsTerminal===!0&&n===C.CLIENT_VERSION_MISMATCH}import{Buffer as wt}from"buffer";function Ct(t,n="utf8"){if(Array.isArray(t))return wt.concat(t).toString(n);return t instanceof ArrayBuffer?wt.from(t).toString(n):t.toString(n)}import{createRequire as Fn}from"module";var Mt={WEBCHAT_UI:"webchat-ui",CONTROL_UI:"openclaw-control-ui",BROWSER_COPILOT:"openclaw-browser-copilot",TUI:"openclaw-tui",WEBCHAT:"webchat",CLI:"cli",GATEWAY_CLIENT:"gateway-client",MACOS_APP:"openclaw-macos",LINUX_APP:"openclaw-linux",IOS_APP:"openclaw-ios",WATCHOS_APP:"openclaw-watchos",ANDROID_APP:"openclaw-android",NODE_HOST:"node-host",WORKER:"openclaw-worker",TEST:"test",FINGERPRINT:"fingerprint",PROBE:"openclaw-probe"},se=Mt,G={WEBCHAT:"webchat",CLI:"cli",UI:"ui",BACKEND:"backend",NODE:"node",WORKER:"worker",PROBE:"probe",TEST:"test"};var vs=new Map(Object.values(Mt).map((t)=>[t,t])),ws=new Map(Object.values(G).map((t)=>[t,t]));var W=4,Ot=4,P=3,Nt=3;var oe=g(Pt(),1);import{randomUUID as Gn}from"crypto";import{isIP as Wn}from"net";import{TLSSocket as $n,checkServerIdentity as Bn}from"tls";import _e from"path";function Vn(t){try{return JSON.parse(t)}catch{return}}function Kn(t){return/^[\t\n\r ]*\{/.test(t)?Et(Vn(t)):void 0}var jn=new Set(["token","key","api_key","apikey","secret","access_token","auth_token","password","pass","passwd","auth","jwt","session","id_token","code","client_secret","app_secret","hook_token","refresh_token","signature","x_amz_signature","x_amz_security_token","private_key","credential","authorization","sig","x_api_key","x_access_token","x_auth_token"]),kt=/[\p{C}\p{Z}\u115F\u1160\u3164\uFFA0+]/gu,zn=/(?:^|_)token(?:_[a-f0-9]{16,})?$/u,Yn=/\/bot\d{6,}(?::|%3[aA])[A-Za-z0-9_-]{20,}(?=\/|$)/giu,X=8,Qn=/(?:^|[^a-z\d+.-])[a-z][a-z\d+.-]{0,31}:/iu,Xn=/\b(?:https?|wss?|ftp):[\\/]{0,2}[^\\/?#\s]*/giu,Jn=/\b(?:https?|wss?|ftp):[\\/]{0,2}[^\s]*@[^\\/?#\s]*/giu,Zn=/[\\/]{2,}[^\\/?#\s]*/gu;function Ft(t){return t.replace(Yn,"/bot***")}function er(t){let n=t.replace(kt,"");for(let i=0;i<=X;i+=1){let a;try{a=decodeURIComponent(n).replace(kt,"")}catch{break}if(a===n)return{value:j(n).replaceAll("-","_"),unresolvedEncoding:!1};n=a}return{value:j(n).replaceAll("-","_"),unresolvedEncoding:n.includes("%")}}function Q(t){if(Qn.test(t))return!0;let n=t.search(/\/\/|\\\\/u);if(n>=0&&t.includes("@",n+2))return!0;let i=t.search(/[?&]/u);if(i>=0&&t.includes("=",i+1))return!0;let a=t.indexOf("#");if(a>=0&&t.includes("=",a+1))return!0;return/%[\da-f]{2}/iu.test(t)}function Ve(t){let n=er(t);return n.unresolvedEncoding||jn.has(n.value)||zn.test(n.value)}function tr(t){try{let n=new URL(t),i=!1,a=Ft(n.pathname);if(a!==n.pathname)n.pathname=a,i=!0;if(n.username||n.password)n.username=n.username?"***":"",n.password=n.password?"***":"",i=!0;for(let l of Array.from(n.searchParams.keys()))if(Ve(l))n.searchParams.set(l,"***"),i=!0;return i?n.toString():t}catch{return t}}function $e(t,n){let i=new URLSearchParams(t),a=[],l=new Set,p=!1;for(let[f,y]of i){if(Ve(f)){if(p=!0,!l.has(f))l.add(f),a.push([f,"***"]);continue}let S=Be(f,n+1),v=Be(y,n+1);if(S!==f||v!==y)p=!0;a.push([S,v])}if(!p)return t;return new URLSearchParams(a).toString()}function Te(t){return Ft(Gt(t).replace(/([?&])([^=&]+)=([^&]*)/g,(n,i,a)=>Ve(a)?`${i}${a}=***`:n))}function Dt(t,n){let i=t.slice(n),a=i.lastIndexOf("@");if(a<0)return t;return`${t.slice(0,n)}***:***@${i.slice(a+1)}`}function Ge(t,n){let i=n;while(t[i]==="/"||t[i]==="\\")i+=1;return i}function Gt(t){return t.replace(Xn,(n)=>Dt(n,Ge(n,n.indexOf(":")+1))).replace(Jn,(n)=>{let i=Ge(n,n.indexOf(":")+1),a=n.lastIndexOf("@"),l=n.slice(i).search(/[\\/?#]/u);if(a<0||l<0)return n;let p=i+l;if(p>=a)return n;let f=n.indexOf(":",i);if(f<0||f>p)return n;let y=n.slice(i,p),S=n.slice(f+1,p);if(/^\d+$/u.test(S)||/^\[[^\]]+\](?::\d+)?$/u.test(y))return n;return`${n.slice(0,i)}***:***@${n.slice(a+1)}`}).replace(Zn,(n)=>Dt(n,Ge(n,0)))}function Ke(t){for(let n of t.matchAll(/(?:\b(?:https?|wss?|ftp):[\\/]{0,2}|[\\/]{2,})/giu)){let i=t.slice((n.index??0)+n[0].length),a=i.search(/(?<!\*\*\*:\*\*\*)@/u),l=i.search(/[\\/?#]/u),p=i.slice(l+1,a);if(a>=0&&(l<0||a<=l||i[l]==="/"&&(p.includes(":")||/^[^/?#\s]+\.[^/?#\s]+(?:[/?#]|$)/u.test(i.slice(a+1)))))return!0}return!1}function nr(t,n){let i=t.indexOf("#");if(i<0)return t;let a=t.slice(i+1),l=je(a,n+1);return l===a?t:`${t.slice(0,i+1)}${l}`}function je(t,n){if(!t)return t;if(n>X&&Q(t))return"***";let i=$t(t,n);if(i.parsedWholeUrl)return Te(i.value);let a=t.search(/[?&]/u),l=t.indexOf("=");if(l>=0&&(a<0||l<a))return $e(t,n);let p=t.indexOf("?");if(p>=0){let v=$e(t.slice(p+1),n);return`${Bt(Te(t.slice(0,p+1)),n+1)}${v}`}let f=Te(t);if(!Q(f))return f;let y;try{y=decodeURIComponent(f)}catch{return"***"}if(y===f)return f;let S=je(y,n+1);return S===y?f:encodeURIComponent(S)}function Wt(t,n){if(!Q(t))return t;if(n>X)return"***";let i;try{i=decodeURIComponent(t)}catch{return"***"}if(i===t)return t;let a=Ae(i,n);if(a.value!==i||Ke(i))return a.value!==i?a.value:"***";if(a.parsedWholeUrl)return t;let l=Wt(i,n+1);return l===i?t:l}function $t(t,n){try{let i=tr(t),a=new URL(i);if(n>X)return{value:"***",parsedWholeUrl:!0};let l=i!==t,p=Gt(Wt(a.pathname,n+1));if(p!==a.pathname){let v=a.pathname;if(a.pathname=p,a.pathname===v)return{value:i,parsedWholeUrl:!1};l=!0}let f=$e(a.search.slice(1),n);if(f!==a.search.slice(1))a.search=f,l=!0;let y=a.hash.slice(1),S=je(y,n+1);if(S!==y)a.hash=S,l=!0;return{value:l?a.toString():t,parsedWholeUrl:!0}}catch{return{value:t,parsedWholeUrl:!1}}}function Ae(t,n){let i=$t(t,n);if(i.parsedWholeUrl)return i;return{value:Bt(nr(Te(i.value),n),n+1),parsedWholeUrl:!1}}function Bt(t,n){if(!Q(t))return t;if(n>X)return"***";let i;try{i=decodeURIComponent(t)}catch{return"***"}if(i===t)return t;let a=Ae(i,n+1);if(a.value!==i||a.parsedWholeUrl)return a.value===i?t:a.value;return Ke(i)?"***":t}function Be(t,n){if(!Q(t))return t;if(n>X)return"***";let i=Ae(t,n);if(i.value!==t)return i.value;if(Ke(t))return"***";if(i.parsedWholeUrl)return t;let a;try{a=decodeURIComponent(t)}catch{return"***"}if(a===t||!Q(a))return t;let l=Be(a,n+1);return l===a?t:encodeURIComponent(l)}function rr(t){return Ae(t,0).value}oe.default.IPv4.parse("198.18.0.0");function Vt(t){return t.kind()==="ipv6"}function Kt(t){return Vt(t)&&t.isIPv4MappedAddress()?t.toIPv4Address():t}function sr(t){let n=k(t);if(!n)return;return n.startsWith("[")&&n.endsWith("]")?n.slice(1,-1):n}function ze(t){let n=sr(t);if(!n)return;return oe.default.IPv4.isValidFourPartDecimal(n)||oe.default.IPv6.isValid(n)?oe.default.parse(n):void 0}function or(t){return ir(t)?.toString()}function ir(t){let n=ze(t);if(!n)return;let i=Kt(n);if(Vt(i)&&i.zoneId)i.zoneId=i.zoneId.toLowerCase();return i}function ar(t){let n=ze(t);if(!n)return!1;return Kt(n).range()==="loopback"}function Ut(t){let n=t instanceof Error?t.message:String(t);return n==="gateway client stopped"||n==="Error: gateway client stopped"}function L(t){return String(t).replace(/\/\/([^@/?#\s]+)@/g,"//***:***@").replace(/(Authorization:\s*Bearer\s+)[^\s]+/giu,"$1***").replace(/([?&])([^=&\s]+)=([^&#\s"'<>)]*)/g,(n,i,a)=>/(?:token|password|secret|key|auth|credential)/iu.test(a)?`${i}${a}=***`:n)}var cr=/^[a-fA-F0-9]{64}$/u,lr=/^(?:[a-fA-F0-9]{2}:){31}[a-fA-F0-9]{2}$/u;function ie(t){let n=(t??"").trim().replace(/^sha256:/iu,"");if(cr.test(n))return n.toLowerCase();return lr.test(n)?n.replaceAll(":","").toLowerCase():""}function jt(t){if(!t)return null;let n=t.toLowerCase().trim(),i=n.replace(/\.+$/,"");if(i==="localhost")return{isLocalhost:!0,unbracketedHost:i};return{isLocalhost:!1,unbracketedHost:n.startsWith("[")&&n.endsWith("]")?n.slice(1,-1):n}}function zt(t){let n=or(t);return n?ze(n):void 0}var ur=class{constructor(t){this.storage=t,this.operations=new Set}load(t){let n=()=>(t.signal?.throwIfAborted(),t.assertCurrent?.(),this.track(this.storage.loadDeviceAuthToken(t)));return this.operations.size>0?this.settle().then(n):n()}store(t,n,i){let a=(p)=>{let f=K(p),y=!1;try{y=i(f)}catch{}if(!y)this.unreportedPersistenceFailure??=f;throw f};t.signal?.throwIfAborted(),t.assertCurrent?.();let l=this.storage.storeDeviceAuthToken(t);return l instanceof Promise?this.track(l.then(n).catch(a)):n()}clear(t,n,i){let a=()=>{if(!i())return;let l=[n.token,n.receiptToken].filter((S)=>typeof S==="string"),p=[...new Set(l)];if(n.token===void 0&&p.length===0)p.push(void 0);let f=(S)=>{t.signal?.throwIfAborted(),t.assertCurrent?.();let v=this.storage.clearDeviceAuthToken({...t,...S===void 0?{}:{expectedToken:S}});return v instanceof Promise?v.then(()=>{}):void 0},y;for(let S of p)y=y?y.then(()=>f(S)):f(S);return y};return this.track(n.persistence?n.persistence.then(a,a):a())}async settle(){await Promise.allSettled(this.operations)}async drain(){await this.settle();let t=this.unreportedPersistenceFailure;if(this.unreportedPersistenceFailure=void 0,t)throw t}track(t){if(!(t instanceof Promise))return t;return this.operations.add(t),t.then(()=>this.operations.delete(t),()=>this.operations.delete(t)),t}},dr=2048,pr=1000;async function fr(t){return await new Promise((n)=>{let i=[],a=0,l=!1,p=()=>{if(l)return;l=!0,clearTimeout(S),t.off("data",y),t.off("end",p),t.off("error",p),t.off("aborted",p),n(Buffer.concat(i,a).toString("utf8").replace(/\s+/gu," ").trim())},f=()=>{p(),t.destroy()},y=(v)=>{let w=Buffer.isBuffer(v)?v:Buffer.from(v),R=dr-a;if(R>0){let _=w.subarray(0,R);i.push(_),a+=_.byteLength}if(w.byteLength>=R)f()},S=setTimeout(f,pr);S.unref?.(),t.on("data",y),t.once("end",p),t.once("error",p),t.once("aborted",p)})}function hr(t,n,i){let a=t.platform??n;if(!i)return{platform:a,deviceFamily:t.deviceFamily,modelIdentifier:t.modelIdentifier};return{platform:a==="macos"?"darwin":a==="windows"?"win32":a}}function We(t){if(t.role!=="node"||t.mode!==G.NODE||t.clientName!==se.NODE_HOST)return!1;return(t.minProtocol??P)===P&&(t.maxProtocol??W)===W}var B=class extends z{constructor(t){super({...t,message:ct({message:t.message,details:t.details})});this.name="GatewayClientRequestError"}},Er=class extends Fe{constructor(t){super(t,`gateway request timeout for ${t.method}`);this.name="GatewayClientRequestTimeoutError"}},yr=Symbol("gateway.connectAssemblyError");function mr(t){return Object.defineProperty(t,yr,{configurable:!0,value:!0}),t}function Ir(t){return t instanceof URL?t:URL.parse(t)}function gr(t){return Ir(t)?.protocol==="wss:"}var Tr=new Set(["loopback","private","linkLocal","carrierGradeNat"]),_r=new Set(["loopback","linkLocal","uniqueLocal","deprecatedSiteLocal"]);function Ar(t){return(t.kind()==="ipv4"?Tr:_r).has(t.range())}function Sr(t){let n=jt(t);return Boolean(n&&(n.isLocalhost||ar(n.unbracketedHost)))}function Rr(t){let n=jt(t);if(!n)return!1;if(n.isLocalhost)return!0;let i=zt(n.unbracketedHost);return Boolean(i&&Ar(i))}function vr(t){if(Rr(t))return!0;let n=t.toLowerCase().trim().replace(/\.+$/,"");return n.endsWith(".local")||n.endsWith(".ts.net")}function wr(t,n){let i=URL.parse(t);if(!i)return!1;let a=i.protocol==="https:"?"wss:":i.protocol==="http:"?"ws:":i.protocol;if(a==="wss:")return!0;if(a!=="ws:")return!1;if(vr(i.hostname))return!0;if(n?.allowPrivateWs===!0)return zt(i.hostname.startsWith("[")&&i.hostname.endsWith("]")?i.hostname.slice(1,-1):i.hostname)===void 0;return!1}var Y=class extends Error{},xt=class extends Error{};function Cr(t){let n=gr(t.url);if(t.tlsFingerprint&&!n)throw new Y("gateway tls fingerprint requires wss:// gateway url");let i=(t.env??process.env).OPENCLAW_ALLOW_INSECURE_PRIVATE_WS==="1";if(!wr(t.url,{allowPrivateWs:i}))throw new Y(`SECURITY ERROR: Cannot connect to "${URL.parse(t.url)?.hostname||t.url}" over plaintext ws://. Both credentials and chat data would be exposed to network interception. Use wss:// for remote URLs. Safe defaults: keep gateway.bind=loopback and connect via SSH tunnel (ssh -N -L 18789:127.0.0.1:18789 user@gateway-host), or use Tailscale Serve/Funnel. `+(i?"":"Break-glass (trusted private networks only): set OPENCLAW_ALLOW_INSECURE_PRIVATE_WS=1. ")+"Run `openclaw doctor --fix` for guidance.");let a=t.normalizeTlsFingerprint??ie,l=t.tlsFingerprint?ie(t.tlsFingerprint):void 0;if(t.tlsFingerprint&&!l)throw new Y("gateway tls fingerprint must be a SHA-256 fingerprint");let p={...t.options};if(n&&t.tlsServerName){let f=t.tlsServerName;p.servername=Wn(f)?"":f,p.checkServerIdentity=(y,S)=>Bn(f,S)}if(n&&l)Mr(p,l,a);return{options:p}}function Mr(t,n,i=ie){t.rejectUnauthorized=!1;let a={...t.headers},l=Object.entries(a).filter(([p])=>p.toLowerCase()==="expect");for(let[p]of l)delete a[p];t.headers=a,t.finishRequest=(p)=>{p.once("socket",(f)=>{if(!(f instanceof $n)){p.destroy(new xt("gateway tls fingerprint unavailable"));return}let y=()=>{if(p.destroyed)return;let S=ie(f.getPeerCertificate()?.fingerprint256),v=S?i(S):"";if(!v||v!==i(n)){p.destroy(new xt(v?"gateway tls fingerprint mismatch":"gateway tls fingerprint unavailable"));return}for(let[w,R]of l)if(R!==void 0)p.setHeader(w,R);p.end()};if(f.secureConnecting)f.once("secureConnect",y),p.once("close",()=>f.off("secureConnect",y));else y()})}}var Se=Fn(import.meta.url),Ye=_e.dirname(Se.resolve("ws/package.json")),Ht=Se(_e.join(Ye,"lib/websocket.js"));Se(_e.join(Ye,"lib/websocket-server.js"));Se(_e.join(Ye,"lib/stream.js"));var Or={loadOrCreateDeviceIdentity:()=>{return},signDevicePayload:()=>{throw Error("GatewayClient device signature dependency is not configured")},publicKeyRawBase64UrlFromPem:()=>{throw Error("GatewayClient public key dependency is not configured")},loadDeviceAuthToken:()=>null,storeDeviceAuthToken:()=>{},clearDeviceAuthToken:()=>{},beforeConnect:()=>{},registerGatewayLoopbackBypass:()=>{return},logDebug:()=>{},logError:()=>{},redactForLog:(t)=>t,normalizeTlsFingerprint:ie};function Nr(t){return Object.fromEntries(Object.entries(Or).map(([n,i])=>[n,t?.[n]??i]))}var br="ws://127.0.0.1:18789",Pr="0.0.0",qt=class extends Y{},kr=250,Dr=1000,Ur=1,Yt=class{constructor(t){this.ws=null,this.stopped=!1,this.useLegacyNodeProtocolEnvelope=!1,this.nodeProtocolTransitionPending=!1,this.pendingDeviceTokenRetry=!1,this.deviceTokenRetryBudgetUsed=!1,this.approvalRuntimeTokenCompatibilityDisabled=!1,this.approvalRuntimeTokenRetryBudgetUsed=!1,this.lastTick=null,this.tickIntervalMs=30000,this.tickTimer=null,this.pendingStop=null,this.transportValidated=!1,this.suppressedTransientPreHelloCleanCloses=0,this.deps=Nr(t.hostDeps),this.deviceAuth=new ur(this.deps),this.opts={...t,deviceIdentity:t.deviceIdentity===null?void 0:t.deviceIdentity??this.deps.loadOrCreateDeviceIdentity()},this.requestTimeoutMs=typeof t.requestTimeoutMs==="number"&&Number.isFinite(t.requestTimeoutMs)?t.requestTimeoutMs:Ce;let n=ot(this.opts.connectChallengeTimeoutMs,{env:this.opts.env,configuredTimeoutMs:this.opts.preauthHandshakeTimeoutMs});this.protocol=new Rt({createSocket:(i)=>this.createSocket(i),createRequestId:Gn,createRequestError:(i)=>new B(i),createRequestTimeoutError:(i,a,l)=>new Er({method:i,timeoutMs:a,requestSent:l}),createRequestAbortError:(i)=>Ie(`gateway request aborted for ${i}`),buildConnectPlan:({nonce:i,challengeTs:a,serverCapabilities:l,generation:p,...f})=>{if(!i)throw Error("gateway connect challenge missing nonce");if(this.opts.deviceIdentity&&a==null)throw Error("gateway connect challenge timestamp invalid");let y=this.opts.role??"operator",S=(w)=>{f.assertCurrent();let R=a??Date.now(),_=yt({token:this.opts.token,bootstrapToken:this.opts.bootstrapToken,preferBootstrapToken:this.opts.preferBootstrapToken,deviceToken:this.opts.deviceToken,password:this.opts.password,approvalRuntimeToken:this.approvalRuntimeTokenCompatibilityDisabled?void 0:this.opts.approvalRuntimeToken,agentRuntimeIdentityToken:this.opts.agentRuntimeIdentityToken,storedToken:w?.token,storedScopes:w?.scopes,pendingDeviceTokenRetry:this.pendingDeviceTokenRetry,trustedDeviceTokenRetry:this.isTrustedDeviceRetryEndpoint()}),{authDeviceToken:c,authApprovalRuntimeToken:d,authAgentRuntimeIdentityToken:E,signatureToken:h,resolvedDeviceToken:A,storedToken:I,storedScopes:M,usingStoredDeviceToken:O}=_;if(this.pendingDeviceTokenRetry&&c)this.pendingDeviceTokenRetry=!1;let b=mt(_),N=It({requestedScopes:this.opts.scopes,usingStoredDeviceToken:O,storedScopes:M,defaultScopes:["operator.admin"]}),x=this.opts.mode??G.BACKEND,J=this.opts.clientName??se.GATEWAY_CLIENT,le=y==="node"&&x===G.NODE&&J===se.NODE_HOST,ue=We(this.opts),H=le&&(this.useLegacyNodeProtocolEnvelope||this.opts.maxProtocol===P&&(this.opts.minProtocol??P)<=P),F=H?P:ue?W:this.opts.minProtocol??(x===G.PROBE?Nt:y==="node"&&x===G.NODE?P:Ot),de=H?P:ue?W:this.opts.maxProtocol??W,{platform:pe,deviceFamily:Xe,modelIdentifier:cn}=hr(this.opts,process.platform,H),Je={minProtocol:F,maxProtocol:de,client:{id:J,displayName:this.opts.clientDisplayName,version:this.opts.clientVersion??Pr,buildId:this.opts.clientBuildId,platform:pe,deviceFamily:Xe,modelIdentifier:cn,mode:x,instanceId:this.opts.instanceId},...Tt({caps:Array.isArray(this.opts.caps)?this.opts.caps:[],modelCatalog:H?void 0:this.opts.modelCatalog,serverCapabilities:l}),commands:Array.isArray(this.opts.commands)?this.opts.commands:void 0,computerUse:H?void 0:this.opts.computerUse,workerRuns:H?void 0:this.opts.workerRuns,permissions:this.opts.permissions&&typeof this.opts.permissions==="object"?this.opts.permissions:void 0,pathEnv:this.opts.pathEnv,auth:b,role:y,scopes:N,device:void 0};if(this.opts.deviceIdentity){let ln=ht({deviceId:this.opts.deviceIdentity.deviceId,clientId:this.opts.clientName??se.GATEWAY_CLIENT,clientMode:x,role:y,scopes:N,signedAtMs:R,token:h??null,nonce:i,platform:pe,deviceFamily:Xe}),un=this.deps.signDevicePayload(this.opts.deviceIdentity.privateKeyPem,ln);Je.device={id:this.opts.deviceIdentity.deviceId,publicKey:this.deps.publicKeyRawBase64UrlFromPem(this.opts.deviceIdentity.publicKeyPem),signature:un,signedAt:R,nonce:i}}let Ze={params:Je,authApprovalRuntimeToken:d,authAgentRuntimeIdentityToken:E,resolvedDeviceToken:A,storedScopes:M,storedToken:I,usingStoredDeviceToken:O};return this.connectionStoredToken={generation:p,token:Ze.storedToken??null},Ze},v=this.opts.deviceIdentity?this.deviceAuth.load({deviceId:this.opts.deviceIdentity.deviceId,role:y,env:this.opts.env,...f}):null;return v instanceof Promise?v.then(S):S(v)},buildConnectParams:(i)=>i.params,onConnectPlanError:(i)=>{this.stopped=!0;let a=mr(i),l=`gateway connect failed: ${L(i)}`;if(this.opts.mode===G.PROBE||Ut(i))this.logDebug(l);else this.logError(l);return{closeCode:1008,closeReason:"connect failed",stop:!0,error:a}},onConnectHello:(i,a)=>{let l=a.plan;a.assertCurrent();let p=this.opts.role??"operator",f=i.auth,y=this.connectionStoredToken,S=()=>{if(f?.deviceToken&&(f.role??p)===p&&y)y.token=f.deviceToken;if(this.opts.preferBootstrapToken)this.opts.token=void 0,this.opts.bootstrapToken=void 0,this.opts.password=void 0,this.opts.preferBootstrapToken=!1},v=void 0;if(f?.deviceToken&&this.opts.deviceIdentity){let R=f.role??p,_=R===p&&f.deviceToken===l.storedToken?l.storedScopes??f.scopes??[]:f.scopes??[];if(R===p&&y)y.receiptToken=f.deviceToken;if(v=this.deviceAuth.store({deviceId:this.opts.deviceIdentity.deviceId,role:R,token:f.deviceToken,scopes:_,env:this.opts.env,...R===p?{expectedToken:l.storedToken??null}:{}},S,(c)=>{l.persistenceFailed=!0;let d=this.notifyConnectError(c);return this.logError(`gateway device token persistence failed: ${L(c)}`),d}),y&&v instanceof Promise)y.persistence=v}else S();let w=()=>{if(a.signal.aborted||!this.protocol.connected)return;a.assertCurrent();let R=this.useLegacyNodeProtocolEnvelope&&We(this.opts)&&i.protocol>P;if(R)this.useLegacyNodeProtocolEnvelope=!1;if(this.nodeProtocolTransitionPending=!1,this.pendingDeviceTokenRetry=!1,this.deviceTokenRetryBudgetUsed=!1,this.suppressedTransientPreHelloCleanCloses=0,this.tickIntervalMs=typeof i.policy?.tickIntervalMs==="number"?i.policy.tickIntervalMs:30000,R){this.protocol.resetReconnectBackoff(250),this.protocol.closeSocket(1012,"gateway protocol upgraded");return}this.lastTick=Date.now(),this.startTickWatch()};return v instanceof Promise?v.then(w):w()},onHello:(i)=>{this.opts.onHelloOk?.(i)},onConnectFailure:(i,a)=>{let l=a.plan;if(l.persistenceFailed)return{closeCode:1008,closeReason:"connect failed"};let p=i instanceof B?q(i.details):null,f=this.opts.deviceIdentity&&l.usingStoredDeviceToken&&p===C.AUTH_DEVICE_TOKEN_MISMATCH?this.clearDeviceToken(this.opts.deviceIdentity.deviceId,{token:l.storedToken}):void 0,y=this.resolveConnectRequestFailure(i,l);return f instanceof Promise?f.then(()=>y):y},resolveClose:(i)=>this.resolveClose(i),onClose:(i,a)=>{if(clearInterval(this.tickTimer??void 0),this.tickTimer=null,a.notify)this.opts.onClose?.(i.code,i.reason,this.closeInfo(i))},notifyStoppedClose:!0,onConnectError:(i)=>this.notifyConnectError(i),onReconnectStopped:(i)=>this.notifyReconnectPaused({code:1008,reason:i.message,detailCode:null}),onParseError:(i)=>this.logDebug(`gateway client parse error: ${L(i)}`),onEvent:(i)=>this.opts.onEvent?.(i),onGap:(i)=>this.opts.onGap?.(i),onRequestTiming:(i)=>this.opts.onRequestTiming?.(i),onActivity:()=>{this.lastTick=Date.now()},onCallbackError:(i,a)=>this.logDebug(`gateway client ${i==="hello"?"hello-ok":i==="gap"?"event":i} handler error: ${L(a)}`),handshake:{mode:"require-challenge",timeoutMs:n,timeoutMessage:(i)=>`gateway connect challenge timeout (waited ${i}ms, limit ${n}ms)`},reconnect:{initialMs:1000,multiplier:2,maxMs:30000},requestTimeoutMs:this.requestTimeoutMs,shouldRetrySocketFactoryError:(i)=>!(i instanceof Y)&&!(i instanceof SyntaxError)&&!(i instanceof TypeError)&&!(i instanceof RangeError),rethrowSocketFactoryError:(i)=>i instanceof qt})}get connected(){return!this.stopped&&this.protocol.connected}getConnectionMetadata(){return{clientName:this.opts.clientName,hasDeviceIdentity:Boolean(this.opts.deviceIdentity),mode:this.opts.mode,preauthHandshakeTimeoutMs:this.opts.preauthHandshakeTimeoutMs}}updateNodeManifest(t){if(this.opts={...this.opts,caps:[...t.caps],commands:[...t.commands],computerUse:t.computerUse===void 0?void 0:structuredClone(t.computerUse),workerRuns:t.workerRuns?structuredClone(t.workerRuns):void 0},!this.stopped)this.protocol.closeSocket(1012,"node manifest changed")}start(){if(this.stopped)return;this.protocol.start()}createSocket(t){let n=this.opts.url??br,i=this.opts.edgeAuthHeaders,a=i&&Object.keys(i).length>0?i:void 0;if(a&&new URL(n).protocol!=="wss:")throw new Y("edge auth headers require a wss:// Gateway URL");let l=Oe({env:this.opts.env,configuredTimeoutMs:this.opts.preauthHandshakeTimeoutMs}),p=Cr({url:n,tlsFingerprint:this.opts.tlsFingerprint,tlsServerName:this.opts.tlsServerName,env:this.opts.env,normalizeTlsFingerprint:this.deps.normalizeTlsFingerprint,options:{maxPayload:26214400,handshakeTimeout:l,...this.opts.origin?{origin:this.opts.origin}:{},...a?{followRedirects:!1,headers:a}:{}}});this.deps.beforeConnect();let f,y;try{try{y=this.deps.registerGatewayLoopbackBypass(n),this.opts.assertConnectionCurrent?.()}catch(v){throw new qt(v instanceof Error?v.message:String(v))}f=new Ht(n,p.options),f.binaryType="nodebuffer"}finally{y?.()}this.ws=f,this.transportValidated=!1;let S;return f.on("open",()=>{this.transportValidated=!0,t.open()}),f.on("message",(v)=>t.message(Ct(v))),f.on("close",(v,w)=>{let R=w.toString();if(this.ws===f)this.ws=null;this.resolvePendingStop(f),t.close(v,R)}),f.on("unexpected-response",(v,w)=>{fr(w).then((R)=>{let _=w.statusCode,c=Kn(R)?.error,d=qe(c)?c:void 0,E=w.headers.location,h=E?rr(Array.isArray(E)?E[0]??"":E):void 0;S=new B({code:"UNAVAILABLE",message:`gateway rejected websocket upgrade (HTTP ${_??"unknown"})${R?`: ${R}`:""}`,retryable:!0,details:{reason:"websocket-upgrade-rejected",..._===void 0?{}:{httpStatus:_},...h?{location:h}:{},...typeof d?.type==="string"?{gatewayErrorType:d.type,...typeof d.message==="string"?{gatewayErrorMessage:d.message}:{}}:{}}}),t.error(S),v.destroy(),f.close()})}),f.on("error",(v)=>{if(S)return;if(v.message==="Opening handshake has timed out")Object.assign(v,{code:"ETIMEDOUT"});this.logDebug(`gateway client error: ${L(v)}`),t.error(v instanceof Error?v:Error(String(v)))}),{isOpen:()=>f.readyState===Ht.OPEN,send:(v)=>{this.opts.assertConnectionCurrent?.(),f.send(v)},close:(v,w)=>f.close(v,w)}}stop(){this.beginStop()}async stopAndWait(t){let n=this.beginStop(),i=t?.timeoutMs===void 0?Dr:D(t.timeoutMs);try{await _t(Promise.resolve(n),i,()=>{throw Error(`gateway client stop timed out after ${i}ms`)},{ref:!1})}finally{await this.deviceAuth.drain()}}beginStop(){if(this.stopped=!0,this.pendingDeviceTokenRetry=!1,this.deviceTokenRetryBudgetUsed=!1,clearInterval(this.tickTimer??void 0),this.tickTimer=null,this.pendingStop)return this.pendingStop.promise;let t=this.ws;if(this.ws=null,t){let n=()=>{},i={ws:t,promise:new Promise((l)=>{n=l}),resolve:n};this.pendingStop=i;let a=setTimeout(()=>{try{t.terminate()}finally{this.resolvePendingStop(t)}},kr);if(a.unref?.(),i.terminateTimer=a,this.protocol.connecting){let l=Error("gateway client stopped");this.notifyConnectError(l),this.logDebug(`gateway connect failed: ${L(l)}`)}return this.protocol.stop(),i.promise}return this.protocol.stop(),null}resolvePendingStop(t){if(this.pendingStop?.ws!==t)return;let{resolve:n,terminateTimer:i}=this.pendingStop;if(i)clearTimeout(i);this.pendingStop=null,n()}logDebug(t){this.deps.logDebug(this.deps.redactForLog(t))}logError(t){this.deps.logError(this.deps.redactForLog(t))}shouldRetryWithAlternateNodeProtocol(t){if(!We(this.opts)||!(t instanceof B))return!1;let n=q(t.details);return t.details?.expectedProtocol===(this.useLegacyNodeProtocolEnvelope?W:P)&&(n===C.PROTOCOL_MISMATCH||j(t.message).includes("protocol mismatch"))}resolveConnectRequestFailure(t,n){if(this.shouldRetryWithAlternateNodeProtocol(t)){let p=!this.nodeProtocolTransitionPending;if(this.useLegacyNodeProtocolEnvelope=!this.useLegacyNodeProtocolEnvelope,this.nodeProtocolTransitionPending=!0,p)this.protocol.resetReconnectBackoff(250);return this.logDebug(this.useLegacyNodeProtocolEnvelope?`gateway rejected protocol v${W}; retrying node host with protocol v${P}`:`gateway rejected protocol v${P}; retrying node host with protocol v${W}`),{closeCode:1008,closeReason:"connect retry"}}this.nodeProtocolTransitionPending=!1;let i=t instanceof B?q(t.details):null;if(gt({retryBudgetUsed:this.deviceTokenRetryBudgetUsed,currentDeviceToken:n.resolvedDeviceToken,explicitToken:this.opts.token?.trim()||void 0,storedToken:n.storedToken,trustedEndpoint:this.isTrustedDeviceRetryEndpoint(),errorDetails:t instanceof B?t.details:void 0}))this.pendingDeviceTokenRetry=!0,this.deviceTokenRetryBudgetUsed=!0,this.protocol.resetReconnectBackoff(250);let a=ft(t);if(a!==null)return this.logDebug(`gateway connect failed: ${L(t)}`),{closeCode:1013,closeReason:"gateway starting",reconnectDelayMs:a};if(n.authAgentRuntimeIdentityToken&&this.isUnsupportedConnectAuthField(t,"agentruntimeidentitytoken")){let p=Error("gateway rejected required agent runtime identity auth field; refusing to retry without it");return this.stopped=!0,this.notifyConnectError(p),this.logError(`gateway connect failed: ${p.message}`),{closeCode:1008,closeReason:"connect failed",stop:!0}}if(!this.approvalRuntimeTokenRetryBudgetUsed&&n.authApprovalRuntimeToken&&this.isUnsupportedConnectAuthField(t,"approvalruntimetoken"))return this.approvalRuntimeTokenCompatibilityDisabled=!0,this.approvalRuntimeTokenRetryBudgetUsed=!0,this.protocol.resetReconnectBackoff(250),this.logDebug("gateway rejected approval runtime auth field; retrying without it"),{closeCode:1008,closeReason:"connect retry"};this.notifyConnectError(t);let l=`gateway connect failed: ${L(t)}`;if(this.opts.mode===G.PROBE||Ut(t)||i===C.AUTH_RATE_LIMITED)this.logDebug(l);else this.logError(l);return{closeCode:1008,closeReason:"connect failed"}}resolveClose(t){let n=this.closeInfo(t),i=t.connectFailure?.error instanceof B?q(t.connectFailure.error.details):null,a=t.connectFailure?.error instanceof B?t.connectFailure.error.details:void 0;if(t.code===1013&&t.connectFailure?.reconnectDelayMs!==void 0)return{retry:!0,notify:this.opts.notifyOnStartupRetry===!0,reconnectDelayMs:t.connectFailure.reconnectDelayMs};if(n.transientPreHelloCleanClose&&this.suppressedTransientPreHelloCleanCloses<Ur)return this.suppressedTransientPreHelloCleanCloses+=1,{retry:!0,notify:!0,pendingError:Error("gateway transient pre-hello clean close")};if(n.transientPreHelloCleanClose||t.connectRequestSent&&!t.helloReceived&&!t.connectFailure){let l=Error(`gateway closed (${t.code}): ${t.reason}`);this.notifyConnectError(l),this.logError(`gateway connect failed: ${L(l)}`)}if(this.clearStaleDeviceTokenForClose(t),vt({details:a,deviceTokenRetryPending:this.pendingDeviceTokenRetry,tokenMismatchIsTerminal:!0,protocolMismatchIsTerminal:!this.nodeProtocolTransitionPending,clientVersionMismatchIsTerminal:!0}))return this.notifyReconnectPaused({code:t.code,reason:t.reason,detailCode:i}),{retry:!1,notify:!0};return{retry:!0,notify:!0,reconnectDelayMs:t.connectFailure?.reconnectDelayMs}}closeInfo(t){return{phase:t.helloReceived?"post-hello":"pre-hello",socketOpened:t.socketOpened,transportValidated:this.transportValidated,connectRequestSent:t.connectRequestSent,transientPreHelloCleanClose:!t.helloReceived&&t.code===1000&&t.reason==="",...t.connectFailure?.error?{connectError:t.connectFailure.error}:{}}}clearStaleDeviceTokenForClose(t){let{code:n,reason:i,generation:a}=t;if(n!==1008||!j(i).includes("device token mismatch")||!this.opts.deviceIdentity)return;let l=this.connectionStoredToken?.generation===a?this.connectionStoredToken:{token:void 0};this.clearDeviceToken(this.opts.deviceIdentity.deviceId,l,()=>!this.opts.token&&!this.opts.password)}clearDeviceToken(t,n,i=()=>!0){let a=(p)=>{this.logDebug(`failed clearing stale device-auth token for device ${t}: ${String(p)}`)},l=()=>this.logDebug(`cleared stale device-auth token for device ${t}`);try{let p=this.deviceAuth.clear({deviceId:t,role:this.opts.role??"operator",env:this.opts.env,assertCurrent:()=>{if(this.stopped)throw Error("gateway client stopped")}},n,i);return p instanceof Promise?p.then(l,a):l()}catch(p){a(p)}}notifyConnectError(t){if(!this.opts.onConnectError)return!1;try{return this.opts.onConnectError(t),!0}catch(n){return this.logDebug(`gateway client connect error handler error: ${L(n)}`),!1}}notifyReconnectPaused(t){try{this.opts.onReconnectPaused?.(t)}catch(n){this.logDebug(`gateway client reconnect paused handler error: ${L(n)}`)}}isUnsupportedConnectAuthField(t,n){if(!(t instanceof B)||t.gatewayCode!=="INVALID_REQUEST")return!1;let i=j(t.message);return i.includes("invalid connect params")&&i.includes(n)}isTrustedDeviceRetryEndpoint(){let t=this.opts.url??"ws://127.0.0.1:18789";try{let n=new URL(t),i=n.protocol==="https:"?"wss:":n.protocol==="http:"?"ws:":n.protocol;if(Sr(n.hostname))return!0;return i==="wss:"&&Boolean(this.opts.tlsFingerprint?.trim())}catch{return!1}}startTickWatch(){clearInterval(this.tickTimer??void 0);let t=this.opts.tickWatchMinIntervalMs,n=typeof t==="number"&&Number.isFinite(t)?Math.max(1,Math.min(30000,t)):1000,i=D(Math.max(this.tickIntervalMs,n));this.tickTimer=setInterval(()=>{if(this.stopped)return;if(!this.lastTick)return;if(this.protocol.hasPendingRequests&&!this.protocol.hasUnboundedPendingRequests)return;let a=Date.now()-this.lastTick,l=this.opts.tickWatchTimeoutMs;if(a>(typeof l==="number"&&Number.isFinite(l)?Math.max(1,l):this.tickIntervalMs*2))this.protocol.closeSocket(4000,"tick timeout")},i)}async request(t,n,i){let a=i?.expectFinal===!0,l=i?.timeoutMs===null?null:typeof i?.timeoutMs==="number"&&Number.isFinite(i.timeoutMs)?i.timeoutMs:a?null:this.requestTimeoutMs;return this.protocol.request(t,n,{...i,expectFinal:a,timeoutMs:l})}};var on=g(sn(),1);import{createHash as Xt,createPrivateKey as Lr,createPublicKey as Jt,generateKeyPairSync as xr,sign as Zt,verify as Hr}from"crypto";import{existsSync as ae,linkSync as qr,mkdirSync as en,readFileSync as tn,renameSync as Fr,unlinkSync as nn,writeFileSync as rn}from"fs";import{homedir as Gr}from"os";import{join as ce,resolve as Wr}from"path";var $r=s({version:o(1),deviceId:r(),publicKeyPem:r(),privateKeyPem:r()}),Br=s({version:o(1),deviceId:r(),tokens:T(r(),s({token:r(),role:r(),scopes:u(r()),updatedAtMs:m()}))});function Qe(t){let n=Jt(t);if(n.asymmetricKeyType!=="ed25519")throw Error("Expected an Ed25519 device key");return Buffer.from(n.export({format:"jwk"}).x,"base64url")}function Qt(t){let n=JSON.parse(tn(t,"utf8")),i=s({deviceId:r(),publicKey:r(),privateKey:r()}).safeParse(n),a=i.success?{deviceId:i.data.deviceId,publicKeyPem:Jt({key:{kty:"OKP",crv:"Ed25519",x:i.data.publicKey},format:"jwk"}).export({type:"spki",format:"pem"}).toString(),privateKeyPem:Lr({key:{kty:"OKP",crv:"Ed25519",x:i.data.publicKey,d:i.data.privateKey},format:"jwk"}).export({type:"pkcs8",format:"pem"}).toString()}:$r.parse(n),l=Buffer.from("openclaw-device-identity-self-check");if(!Hr(null,l,a.publicKeyPem,Zt(null,l,a.privateKeyPem)))throw Error("OpenClaw device keys do not match");return{...a,deviceId:Xt("sha256").update(Qe(a.publicKeyPem)).digest("hex")}}function Vr(t){let n=ce(t,"device.json");if(ae(n))return Qt(n);en(t,{recursive:!0,mode:448});let{publicKey:i,privateKey:a}=xr("ed25519"),l=i.export({type:"spki",format:"pem"}).toString(),p={version:1,deviceId:Xt("sha256").update(Qe(l)).digest("hex"),publicKeyPem:l,privateKeyPem:a.export({type:"pkcs8",format:"pem"}).toString(),createdAtMs:Date.now()},f=`${n}.${crypto.randomUUID()}.tmp`;rn(f,JSON.stringify(p),{mode:384,flag:"wx"});try{qr(f,n)}catch(y){if(y.code!=="EEXIST")throw y}finally{nn(f)}return Qt(n)}function an(t=process.env){let n=t.HOME?.trim()||t.USERPROFILE?.trim()||Gr(),i=(R,_)=>Wr(R.replace(/^~(?=$|[\\/])/,_)),a=i(t.OPENCLAW_HOME?.trim()||n,n),l=t.OPENCLAW_STATE_DIR?.trim(),p=ce(a,".openclaw"),f=ce(a,".clawdbot"),y=ce(l?i(l,a):!ae(p)&&ae(f)?f:p,"identity"),S=ce(y,"device-auth.json");function v(R){if(!ae(S))return{version:1,deviceId:R,tokens:{}};let _=Br.parse(JSON.parse(tn(S,"utf8")));return _.deviceId===R?_:{version:1,deviceId:R,tokens:{}}}async function w(R,_){let c=()=>{R.signal?.throwIfAborted(),R.assertCurrent?.()};c(),en(y,{recursive:!0,mode:448});let d,E=await on.lock(S,{realpath:!1,retries:{retries:20,minTimeout:10,maxTimeout:100},onCompromised:(h)=>{d=h}});try{if(c(),d)throw d;let h=v(R.deviceId),A=h.tokens[R.role]?.token;if(R.expectedToken!==void 0&&(A??null)!==R.expectedToken)return;_(h.tokens);let I=`${S}.${crypto.randomUUID()}.tmp`;try{rn(I,JSON.stringify(h),{mode:384,flag:"wx"}),c(),Fr(I,S)}finally{if(ae(I))nn(I)}}finally{if(!d)await E()}}return{loadOrCreateDeviceIdentity:()=>Vr(y),signDevicePayload:(R,_)=>Zt(null,Buffer.from(_),R).toString("base64url"),publicKeyRawBase64UrlFromPem:(R)=>Qe(R).toString("base64url"),loadDeviceAuthToken:(R)=>(R.signal?.throwIfAborted(),R.assertCurrent?.(),v(R.deviceId).tokens[R.role]??null),storeDeviceAuthToken:(R)=>w(R,(_)=>{_[R.role]={token:R.token,role:R.role,scopes:R.scopes,updatedAtMs:Date.now()}}),clearDeviceAuthToken:(R)=>w(R,(_)=>{delete _[R.role]})}}class Kr extends Yt{constructor(t){super({clientVersion:Lt.devDependencies["@openclaw/gateway-client"],...t,hostDeps:{...an(t.env),...t.hostDeps}})}}export{Kr as GatewayClient};
2
+ import{Lt}from"./chunk-hjzfk1cr.js";import{r,m,u,s,T,o,sn}from"./chunk-ggphq7nk.js";import{g,e}from"./chunk-7c0zbz74.js";var Pt=e(function(bt,ge){(function(t){let i={fourOctet:new RegExp("^(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)$","i"),threeOctet:new RegExp("^(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)$","i"),twoOctet:new RegExp("^(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)$","i"),longValue:new RegExp("^(0?\\d+|0x[a-f0-9]+)$","i")},a=new RegExp("^0[0-7]+$","i"),l=new RegExp("^0x[a-f0-9]+$","i"),p="%[0-9a-z]{1,}",f="(?:[0-9a-f]+::?)+",y={zoneIndex:new RegExp("%[0-9a-z]{1,}","i"),native:new RegExp("^(::)?((?:[0-9a-f]+::?)+)?([0-9a-f]+)?(::)?(%[0-9a-z]{1,})?$","i"),deprecatedTransitional:new RegExp("^(?:::)((0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)(%[0-9a-z]{1,})?)$","i"),transitional:new RegExp("^((?:(?:[0-9a-f]+::?)+)|(?:::)(?:(?:[0-9a-f]+::?)+)?)(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)(%[0-9a-z]{1,})?$","i")};function S(c,d){if(c.indexOf("::")!==c.lastIndexOf("::"))return null;let E=0,h=-1,A=(c.match(y.zoneIndex)||[])[0],I,M;if(A)A=A.substring(1),c=c.replace(/%.+$/,"");while((h=c.indexOf(":",h+1))>=0)E++;if(c.substr(0,2)==="::")E--;if(c.substr(-2,2)==="::")E--;if(E>=d)return null;M=d-E,I=":";while(M--)I+="0:";if(c=c.replace("::",I),c[0]===":")c=c.slice(1);if(c[c.length-1]===":")c=c.slice(0,-1);return d=function(){let O=c.split(":"),b=[];for(let N=0;N<O.length;N++)b.push(O[N].length>4?NaN:parseInt(O[N],16));return b}(),{parts:d,zoneId:A}}function v(c,d,E,h){if(c.length!==d.length)throw Error("ipaddr: cannot match CIDR for objects with different lengths");let A=0,I;while(h>0){if(I=E-h,I<0)I=0;if(c[A]>>I!==d[A]>>I)return!1;h-=E,A+=1}return!0}function w(c){if(l.test(c))return parseInt(c,16);if(c[0]==="0"&&!isNaN(parseInt(c[1],10))){if(a.test(c))return parseInt(c,8);throw Error(`ipaddr: cannot parse ${c} as octal`)}return parseInt(c,10)}function R(c,d){while(c.length<d)c=`0${c}`;return c}let _={};if(_.IPv4=function(){function c(d){if(d.length!==4)throw Error("ipaddr: ipv4 octet count should be 4");let E,h;for(E=0;E<d.length;E++)if(h=d[E],!(0<=h&&h<=255))throw Error("ipaddr: ipv4 octet should fit in 8 bits");this.octets=d}return c.prototype.SpecialRanges={unspecified:[[new c([0,0,0,0]),8]],broadcast:[[new c([255,255,255,255]),32]],multicast:[[new c([224,0,0,0]),4]],linkLocal:[[new c([169,254,0,0]),16]],loopback:[[new c([127,0,0,0]),8]],carrierGradeNat:[[new c([100,64,0,0]),10]],private:[[new c([10,0,0,0]),8],[new c([172,16,0,0]),12],[new c([192,168,0,0]),16]],reserved:[[new c([192,0,0,0]),24],[new c([192,0,2,0]),24],[new c([192,88,99,0]),24],[new c([198,18,0,0]),15],[new c([198,51,100,0]),24],[new c([203,0,113,0]),24],[new c([240,0,0,0]),4]],as112:[[new c([192,175,48,0]),24],[new c([192,31,196,0]),24]],amt:[[new c([192,52,193,0]),24]]},c.prototype.kind=function(){return"ipv4"},c.prototype.match=function(d,E){let h;if(E===void 0)h=d,d=h[0],E=h[1];if(d.kind()!=="ipv4")throw Error("ipaddr: cannot match ipv4 address with non-ipv4 one");return v(this.octets,d.octets,8,E)},c.prototype.prefixLengthFromSubnetMask=function(){let d=0,E=!1,h={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},A,I,M;for(A=3;A>=0;A-=1)if(I=this.octets[A],I in h){if(M=h[I],E&&M!==0)return null;if(M!==8)E=!0;d+=M}else return null;return 32-d},c.prototype.range=function(){return _.subnetMatch(this,this.SpecialRanges)},c.prototype.toByteArray=function(){return this.octets.slice(0)},c.prototype.toIPv4MappedAddress=function(){return _.IPv6.parse(`::ffff:${this.toString()}`)},c.prototype.toNormalizedString=function(){return this.toString()},c.prototype.toString=function(){return this.octets.join(".")},c}(),_.IPv4.broadcastAddressFromCIDR=function(c){try{let d=this.parseCIDR(c),E=d[0].toByteArray(),h=this.subnetMaskFromPrefixLength(d[1]).toByteArray(),A=[],I=0;while(I<4)A.push(parseInt(E[I],10)|parseInt(h[I],10)^255),I++;return new this(A)}catch(d){throw Error("ipaddr: the address does not have IPv4 CIDR format",{cause:d})}},_.IPv4.isIPv4=function(c){return this.parser(c)!==null},_.IPv4.isValid=function(c){try{return new this(this.parser(c)),!0}catch{return!1}},_.IPv4.isValidCIDR=function(c){try{return this.parseCIDR(c),!0}catch{return!1}},_.IPv4.isValidFourPartDecimal=function(c){if(_.IPv4.isValid(c)&&c.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))return!0;else return!1},_.IPv4.isValidCIDRFourPartDecimal=function(c){let d=c.match(/^(.+)\/(\d+)$/);if(!_.IPv4.isValidCIDR(c)||!d)return!1;return _.IPv4.isValidFourPartDecimal(d[1])},_.IPv4.networkAddressFromCIDR=function(c){let d,E,h,A,I;try{d=this.parseCIDR(c),h=d[0].toByteArray(),I=this.subnetMaskFromPrefixLength(d[1]).toByteArray(),A=[],E=0;while(E<4)A.push(parseInt(h[E],10)&parseInt(I[E],10)),E++;return new this(A)}catch(M){throw Error("ipaddr: the address does not have IPv4 CIDR format",{cause:M})}},_.IPv4.parse=function(c){let d=this.parser(c);if(d===null)throw Error("ipaddr: string is not formatted like an IPv4 Address");return new this(d)},_.IPv4.parseCIDR=function(c){let d;if(d=c.match(/^(.+)\/(\d+)$/)){let E=parseInt(d[2]);if(E>=0&&E<=32){let h=[this.parse(d[1]),E];return Object.defineProperty(h,"toString",{value:function(){return this.join("/")}}),h}}throw Error("ipaddr: string is not formatted like an IPv4 CIDR range")},_.IPv4.parser=function(c){let d,E,h;if(d=c.match(i.fourOctet))return function(){let A=d.slice(1,6),I=[];for(let M=0;M<A.length;M++)E=A[M],I.push(w(E));return I}();else if(d=c.match(i.longValue)){if(h=w(d[1]),h>4294967295||h<0)throw Error("ipaddr: address outside defined range");return function(){let A=[],I;for(I=0;I<=24;I+=8)A.push(h>>I&255);return A}().reverse()}else if(d=c.match(i.twoOctet))return function(){let A=d.slice(1,4),I=[];if(h=w(A[1]),h>16777215||h<0)throw Error("ipaddr: address outside defined range");return I.push(w(A[0])),I.push(h>>16&255),I.push(h>>8&255),I.push(h&255),I}();else if(d=c.match(i.threeOctet))return function(){let A=d.slice(1,5),I=[];if(h=w(A[2]),h>65535||h<0)throw Error("ipaddr: address outside defined range");return I.push(w(A[0])),I.push(w(A[1])),I.push(h>>8&255),I.push(h&255),I}();else return null},_.IPv4.subnetMaskFromPrefixLength=function(c){if(c=parseInt(c),Number.isNaN(c)||c<0||c>32)throw Error("ipaddr: invalid IPv4 prefix length");let d=[0,0,0,0],E=0,h=Math.floor(c/8);while(E<h)d[E]=255,E++;if(h<4)d[h]=Math.pow(2,c%8)-1<<8-c%8;return new this(d)},_.IPv6=function(){function c(d,E){let h,A;if(d.length===16){this.parts=[];for(h=0;h<=14;h+=2)this.parts.push(d[h]<<8|d[h+1])}else if(d.length===8)this.parts=d;else throw Error("ipaddr: ipv6 part count should be 8 or 16");for(h=0;h<this.parts.length;h++)if(A=this.parts[h],!(0<=A&&A<=65535))throw Error("ipaddr: ipv6 part should fit in 16 bits");if(E)this.zoneId=E}return c.prototype.SpecialRanges={unspecified:[new c([0,0,0,0,0,0,0,0]),128],linkLocal:[new c([65152,0,0,0,0,0,0,0]),10],multicast:[new c([65280,0,0,0,0,0,0,0]),8],loopback:[new c([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new c([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new c([0,0,0,0,0,65535,0,0]),96],deprecatedSiteLocal:[new c([65216,0,0,0,0,0,0,0]),10],discard:[new c([256,0,0,0,0,0,0,0]),64],rfc6145:[new c([0,0,0,0,65535,0,0,0]),96],rfc6052:[[new c([100,65435,0,0,0,0,0,0]),96],[new c([100,65435,1,0,0,0,0,0]),48]],"6to4":[new c([8194,0,0,0,0,0,0,0]),16],teredo:[new c([8193,0,0,0,0,0,0,0]),32],benchmarking:[new c([8193,2,0,0,0,0,0,0]),48],amt:[new c([8193,3,0,0,0,0,0,0]),32],as112v6:[[new c([8193,4,274,0,0,0,0,0]),48],[new c([9760,79,32768,0,0,0,0,0]),48]],deprecatedOrchid:[new c([8193,16,0,0,0,0,0,0]),28],orchid2:[new c([8193,32,0,0,0,0,0,0]),28],droneRemoteIdProtocolEntityTags:[new c([8193,48,0,0,0,0,0,0]),28],segmentRouting:[new c([24320,0,0,0,0,0,0,0]),16],reserved:[[new c([8193,0,0,0,0,0,0,0]),23],[new c([8193,3512,0,0,0,0,0,0]),32],[new c([16383,0,0,0,0,0,0,0]),20]]},c.prototype.isIPv4MappedAddress=function(){return this.range()==="ipv4Mapped"},c.prototype.kind=function(){return"ipv6"},c.prototype.match=function(d,E){let h;if(E===void 0)h=d,d=h[0],E=h[1];if(d.kind()!=="ipv6")throw Error("ipaddr: cannot match ipv6 address with non-ipv6 one");return v(this.parts,d.parts,16,E)},c.prototype.prefixLengthFromSubnetMask=function(){let d=0,E=!1,h={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},A,I;for(let M=7;M>=0;M-=1)if(A=this.parts[M],A in h){if(I=h[A],E&&I!==0)return null;if(I!==16)E=!0;d+=I}else return null;return 128-d},c.prototype.range=function(){return _.subnetMatch(this,this.SpecialRanges)},c.prototype.toByteArray=function(){let d,E=[],h=this.parts;for(let A=0;A<h.length;A++)d=h[A],E.push(d>>8),E.push(d&255);return E},c.prototype.toFixedLengthString=function(){let d=function(){let h=[];for(let A=0;A<this.parts.length;A++)h.push(R(this.parts[A].toString(16),4));return h}.call(this).join(":"),E="";if(this.zoneId)E=`%${this.zoneId}`;return d+E},c.prototype.toIPv4Address=function(){if(!this.isIPv4MappedAddress())throw Error("ipaddr: trying to convert a generic ipv6 address to ipv4");let d=this.parts.slice(-2),E=d[0],h=d[1];return new _.IPv4([E>>8,E&255,h>>8,h&255])},c.prototype.toNormalizedString=function(){let d=function(){let h=[];for(let A=0;A<this.parts.length;A++)h.push(this.parts[A].toString(16));return h}.call(this).join(":"),E="";if(this.zoneId)E=`%${this.zoneId}`;return d+E},c.prototype.toRFC5952String=function(){let d=/((^|:)(0(:|$)){2,})/g,E="";if(this.zoneId)E=`%${this.zoneId}`;let h=this.toNormalizedString(),A=h.slice(0,h.length-E.length),I=0,M=-1,O=-1,b;while(b=d.exec(A)){let N=(b[0].match(/0/g)||[]).length;if(N>O)O=N,I=b.index,M=b[0].length}if(M<0)return A+E;return`${A.substring(0,I)}::${A.substring(I+M)}${E}`},c.prototype.toString=function(){return this.toRFC5952String()},c}(),_.IPv6.broadcastAddressFromCIDR=function(c){try{let d=this.parseCIDR(c),E=d[0].toByteArray(),h=this.subnetMaskFromPrefixLength(d[1]).toByteArray(),A=[],I=0;while(I<16)A.push(parseInt(E[I],10)|parseInt(h[I],10)^255),I++;return new this(A)}catch(d){throw Error("ipaddr: the address does not have IPv6 CIDR format",{cause:d})}},_.IPv6.isIPv6=function(c){return this.parser(c)!==null},_.IPv6.isValid=function(c){if(typeof c==="string"&&c.indexOf(":")===-1)return!1;try{let d=this.parser(c);return new this(d.parts,d.zoneId),!0}catch{return!1}},_.IPv6.isValidCIDR=function(c){if(typeof c==="string"&&c.indexOf(":")===-1)return!1;try{return this.parseCIDR(c),!0}catch{return!1}},_.IPv6.networkAddressFromCIDR=function(c){let d,E,h,A,I;try{d=this.parseCIDR(c),h=d[0].toByteArray(),I=this.subnetMaskFromPrefixLength(d[1]).toByteArray(),A=[],E=0;while(E<16)A.push(parseInt(h[E],10)&parseInt(I[E],10)),E++;return new this(A)}catch(M){throw Error("ipaddr: the address does not have IPv6 CIDR format",{cause:M})}},_.IPv6.parse=function(c){let d=this.parser(c);if(d===null)throw Error("ipaddr: string is not formatted like an IPv6 Address");return new this(d.parts,d.zoneId)},_.IPv6.parseCIDR=function(c){let d,E,h;if(E=c.match(/^(.+)\/(\d+)$/)){if(d=parseInt(E[2]),d>=0&&d<=128)return h=[this.parse(E[1]),d],Object.defineProperty(h,"toString",{value:function(){return this.join("/")}}),h}throw Error("ipaddr: string is not formatted like an IPv6 CIDR range")},_.IPv6.parser=function(c){let d,E,h,A,I,M;if(h=c.match(y.deprecatedTransitional))return this.parser(`::ffff:${h[1]}`);if(y.native.test(c))return S(c,8);if(h=c.match(y.transitional)){if(M=h[6]||"",d=h[1],!h[1].endsWith("::"))d=d.slice(0,-1);if(d=S(d+M,6),d&&d.parts){I=[parseInt(h[2]),parseInt(h[3]),parseInt(h[4]),parseInt(h[5])];for(E=0;E<I.length;E++)if(A=I[E],!(0<=A&&A<=255))return null;return d.parts.push(I[0]<<8|I[1]),d.parts.push(I[2]<<8|I[3]),{parts:d.parts,zoneId:d.zoneId}}}return null},_.IPv6.subnetMaskFromPrefixLength=function(c){if(c=parseInt(c),Number.isNaN(c)||c<0||c>128)throw Error("ipaddr: invalid IPv6 prefix length");let d=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],E=0,h=Math.floor(c/8);while(E<h)d[E]=255,E++;if(h<16)d[h]=Math.pow(2,c%8)-1<<8-c%8;return new this(d)},_.fromByteArray=function(c){let d=c.length;if(d===4)return new _.IPv4(c);else if(d===16)return new _.IPv6(c);else throw Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},_.isValid=function(c){return _.IPv6.isValid(c)||_.IPv4.isValid(c)},_.isValidCIDR=function(c){return _.IPv6.isValidCIDR(c)||_.IPv4.isValidCIDR(c)},_.parse=function(c){if(_.IPv6.isValid(c))return _.IPv6.parse(c);else if(_.IPv4.isValid(c))return _.IPv4.parse(c);else throw Error("ipaddr: the address has neither IPv6 nor IPv4 format")},_.parseCIDR=function(c){try{return _.IPv6.parseCIDR(c)}catch{try{return _.IPv4.parseCIDR(c)}catch(d){throw Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format",{cause:d})}}},_.process=function(c){let d=this.parse(c);if(d.kind()==="ipv6"&&d.isIPv4MappedAddress())return d.toIPv4Address();else return d},_.subnetMatch=function(c,d,E){let h,A,I,M;if(E===void 0||E===null)E="unicast";for(A in d)if(Object.prototype.hasOwnProperty.call(d,A)){if(I=d[A],I[0]&&!(I[0]instanceof Array))I=[I];for(h=0;h<I.length;h++)if(M=I[h],c.kind()===M[0].kind()&&c.match.apply(c,M))return A}return E},typeof ge<"u"&&ge.exports)ge.exports=_;else t.ipaddr=_})(bt)});function et(t){if(typeof t!=="string")return null;let n=t.trim();return n?n:null}function k(t){return et(t)??void 0}function dn(t){return k(t)?.toLowerCase()}function j(t){return dn(t)??""}function pn(t){if(typeof t==="number")return Number.isSafeInteger(t)?t:void 0;let n=k(t);if(!n||!/^[+-]?\d+$/.test(n))return;let i=Number(n);return Number.isSafeInteger(i)?i:void 0}function tt(t){let n=pn(t);return n!==void 0&&n>0?n:void 0}function nt(t){return t.VITEST==="true"||t.VITEST==="1"||t.VITEST_POOL_ID!==void 0||t.VITEST_WORKER_ID!==void 0||t.NODE_ENV==="test"||t!==process.env&&nt(process.env)}var Re=2147483647,Z=30000;function ve(t){let n=setTimeout(t,Z);return n.unref?.(),n}function we(t){if(t!==null)clearTimeout(t);return null}var Ce=30000;var rt=Z;function D(t,n){let i=n?.minMs??1,a=Math.min(Re,Math.max(0,Number.isFinite(i)?Math.floor(i):1));return Math.min(Re,Math.max(a,Number.isFinite(t)?Math.floor(t):a))}function Me(t,n,i){return D(typeof t==="number"&&Number.isFinite(t)?t:n,i)}function fe(t,n=rt){return Math.max(250,Math.min(Math.max(250,n),t))}function st(t=process.env){let n=t.OPENCLAW_CONNECT_CHALLENGE_TIMEOUT_MS;if(n){let i=tt(n);if(i!==void 0)return D(i)}}function ot(t,n){let i=Oe({env:n?.env,configuredTimeoutMs:n?.configuredTimeoutMs}),a=Math.max(Z,i);if(typeof t==="number"&&Number.isFinite(t))return fe(t,a);let l=st(n?.env);if(l!==void 0)return fe(l,Math.max(a,l));return fe(i,a)}function Oe(t){let n=t?.env??process.env,i=n.OPENCLAW_HANDSHAKE_TIMEOUT_MS||(nt(n)?n.OPENCLAW_TEST_HANDSHAKE_TIMEOUT_MS:void 0);if(i){let l=tt(i);if(l!==void 0)return D(l)}let a=t?.configuredTimeoutMs;if(typeof a==="number"&&Number.isFinite(a)&&a>0)return D(a);return Z}function fn(t){if(typeof t!=="string")return null;let n=t.trim();return n?n:null}function U(t){return fn(t)??void 0}function ee(t){return typeof t==="number"&&Number.isInteger(t)&&t>0?t:void 0}function Ne(t){return typeof t==="number"&&Number.isInteger(t)&&t>=0?t:void 0}function V(t){return t!==null&&typeof t==="object"&&!Array.isArray(t)}function hn(t){if(!Array.isArray(t))return[];return t.flatMap((n)=>{let i=U(n);return i?[i]:[]})}function be(t){let n=hn(t);return n.length>0?n:void 0}var C={AUTH_REQUIRED:"AUTH_REQUIRED",AUTH_UNAUTHORIZED:"AUTH_UNAUTHORIZED",AUTH_TOKEN_MISSING:"AUTH_TOKEN_MISSING",AUTH_TOKEN_MISMATCH:"AUTH_TOKEN_MISMATCH",AUTH_TOKEN_NOT_CONFIGURED:"AUTH_TOKEN_NOT_CONFIGURED",AUTH_PASSWORD_MISSING:"AUTH_PASSWORD_MISSING",AUTH_PASSWORD_MISMATCH:"AUTH_PASSWORD_MISMATCH",AUTH_PASSWORD_NOT_CONFIGURED:"AUTH_PASSWORD_NOT_CONFIGURED",AUTH_BOOTSTRAP_TOKEN_INVALID:"AUTH_BOOTSTRAP_TOKEN_INVALID",AUTH_DEVICE_TOKEN_MISMATCH:"AUTH_DEVICE_TOKEN_MISMATCH",AUTH_SCOPE_MISMATCH:"AUTH_SCOPE_MISMATCH",AUTH_RATE_LIMITED:"AUTH_RATE_LIMITED",AUTH_TAILSCALE_IDENTITY_MISSING:"AUTH_TAILSCALE_IDENTITY_MISSING",AUTH_TAILSCALE_PROXY_MISSING:"AUTH_TAILSCALE_PROXY_MISSING",AUTH_TAILSCALE_WHOIS_FAILED:"AUTH_TAILSCALE_WHOIS_FAILED",AUTH_TAILSCALE_IDENTITY_MISMATCH:"AUTH_TAILSCALE_IDENTITY_MISMATCH",AUTH_IDENTITY_HEADER_REQUIRED:"AUTH_IDENTITY_HEADER_REQUIRED",AUTH_VERIFIED_USER_REQUIRED:"AUTH_VERIFIED_USER_REQUIRED",AUTHENTICATED_PROFILE_UNAVAILABLE:"AUTHENTICATED_PROFILE_UNAVAILABLE",OPERATOR_ACCESS_DENIED:"OPERATOR_ACCESS_DENIED",CONTROL_UI_BUILD_MISMATCH:"CONTROL_UI_BUILD_MISMATCH",CONTROL_UI_ORIGIN_NOT_ALLOWED:"CONTROL_UI_ORIGIN_NOT_ALLOWED",PROTOCOL_MISMATCH:"PROTOCOL_MISMATCH",CONTROL_UI_DEVICE_IDENTITY_REQUIRED:"CONTROL_UI_DEVICE_IDENTITY_REQUIRED",DEVICE_IDENTITY_REQUIRED:"DEVICE_IDENTITY_REQUIRED",DEVICE_AUTH_INVALID:"DEVICE_AUTH_INVALID",DEVICE_AUTH_DEVICE_ID_MISMATCH:"DEVICE_AUTH_DEVICE_ID_MISMATCH",DEVICE_AUTH_SIGNATURE_EXPIRED:"DEVICE_AUTH_SIGNATURE_EXPIRED",DEVICE_AUTH_NONCE_REQUIRED:"DEVICE_AUTH_NONCE_REQUIRED",DEVICE_AUTH_NONCE_MISMATCH:"DEVICE_AUTH_NONCE_MISMATCH",DEVICE_AUTH_SIGNATURE_INVALID:"DEVICE_AUTH_SIGNATURE_INVALID",DEVICE_AUTH_PUBLIC_KEY_INVALID:"DEVICE_AUTH_PUBLIC_KEY_INVALID",PAIRING_REQUIRED:"PAIRING_REQUIRED",PAIRING_REJECTED:"PAIRING_REJECTED",PAIRING_EXPIRED:"PAIRING_EXPIRED",CLIENT_VERSION_MISMATCH:"CLIENT_VERSION_MISMATCH"},En=["retry_with_device_token","update_auth_configuration","update_auth_credentials","wait_then_retry","review_auth_configuration"],yn=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,Pe={"not-paired":{message:"device pairing required",requirement:"device is not approved yet",remediationHint:"Approve this device from the pending pairing requests.",recoveryTitle:"Gateway pairing approval required."},"role-upgrade":{message:"role upgrade pending approval",requirement:"device is asking for a higher role than currently approved",remediationHint:"Review the requested role upgrade, then approve the pending request.",recoveryTitle:"Gateway role upgrade approval required."},"scope-upgrade":{message:"scope upgrade pending approval",requirement:"device is asking for more scopes than currently approved",remediationHint:"Review the requested scopes, then approve the pending upgrade.",recoveryTitle:"Gateway scope upgrade approval required."},"metadata-upgrade":{message:"device metadata change pending approval",requirement:"device identity changed and must be re-approved",remediationHint:"Review the refreshed device details, then approve the pending request.",recoveryTitle:"Gateway device refresh approval required."}},es=new Map([["token_missing",C.AUTH_TOKEN_MISSING],["token_mismatch",C.AUTH_TOKEN_MISMATCH],["token_missing_config",C.AUTH_TOKEN_NOT_CONFIGURED],["password_missing",C.AUTH_PASSWORD_MISSING],["password_mismatch",C.AUTH_PASSWORD_MISMATCH],["password_missing_config",C.AUTH_PASSWORD_NOT_CONFIGURED],["bootstrap_token_invalid",C.AUTH_BOOTSTRAP_TOKEN_INVALID],["tailscale_user_missing",C.AUTH_TAILSCALE_IDENTITY_MISSING],["tailscale_proxy_missing",C.AUTH_TAILSCALE_PROXY_MISSING],["tailscale_whois_failed",C.AUTH_TAILSCALE_WHOIS_FAILED],["tailscale_user_mismatch",C.AUTH_TAILSCALE_IDENTITY_MISMATCH],["rate_limited",C.AUTH_RATE_LIMITED],["device_token_mismatch",C.AUTH_DEVICE_TOKEN_MISMATCH],["scope_mismatch",C.AUTH_SCOPE_MISMATCH],[void 0,C.AUTH_REQUIRED]]),ts=new Map([["device-id-mismatch",C.DEVICE_AUTH_DEVICE_ID_MISMATCH],["device-signature-stale",C.DEVICE_AUTH_SIGNATURE_EXPIRED],["device-nonce-missing",C.DEVICE_AUTH_NONCE_REQUIRED],["device-nonce-mismatch",C.DEVICE_AUTH_NONCE_MISMATCH],["device-signature",C.DEVICE_AUTH_SIGNATURE_INVALID],["device-public-key",C.DEVICE_AUTH_PUBLIC_KEY_INVALID]]);function q(t){if(!V(t))return null;return U(t.code)??null}function it(t){if(!V(t))return{};return{canRetryWithDeviceToken:typeof t.canRetryWithDeviceToken==="boolean"?t.canRetryWithDeviceToken:void 0,recommendedNextStep:at(t.recommendedNextStep)}}function at(t){let n=U(t)??"";return En.find((i)=>i===n)}function mn(t){let n=U(t)??"";return Object.hasOwn(Pe,n)?n:void 0}function In(t){let n=U(t);return n&&yn.test(n)?n:void 0}function gn(t){return{code:C.PAIRING_REQUIRED,...t.reason?{reason:t.reason}:{},...t.requestId?{requestId:t.requestId}:{},...t.remediationHint?{remediationHint:t.remediationHint}:{},...t.recommendedNextStep?{recommendedNextStep:t.recommendedNextStep}:{},...t.retryable!==void 0?{retryable:t.retryable}:{},...t.pauseReconnect!==void 0?{pauseReconnect:t.pauseReconnect}:{},...t.waitForResolution!==void 0?{waitForResolution:t.waitForResolution}:{},...t.deviceId?{deviceId:t.deviceId}:{},...t.requestedRole?{requestedRole:t.requestedRole}:{},...t.requestedScopes?{requestedScopes:t.requestedScopes}:{},...t.approvedRoles?{approvedRoles:t.approvedRoles}:{},...t.approvedScopes?{approvedScopes:t.approvedScopes}:{}}}function Tn(t,n){return{requestId:In(t.requestId),remediationHint:U(t.remediationHint)??(n?Pe[n].remediationHint:"Approve the pending device request before retrying."),deviceId:U(t.deviceId),requestedRole:U(t.requestedRole),requestedScopes:be(t.requestedScopes),approvedRoles:be(t.approvedRoles),approvedScopes:be(t.approvedScopes)}}function ke(t){if(q(t)!==C.PAIRING_REQUIRED)return null;if(!V(t))return null;let n=mn(t.reason);return gn({...Tn(t,n),reason:n,recommendedNextStep:at(t.recommendedNextStep),retryable:typeof t.retryable==="boolean"?t.retryable:void 0,pauseReconnect:typeof t.pauseReconnect==="boolean"?t.pauseReconnect:void 0,waitForResolution:typeof t.waitForResolution==="boolean"?t.waitForResolution:void 0})}function _n(t){let n=ke(t),i=Pe[n?.reason??"not-paired"].message;return n?.requestId?`${i} (requestId: ${n.requestId})`:i}function ct(t){let n=q(t.details);if(n===C.PAIRING_REQUIRED)return _n(t.details);if(n===C.PROTOCOL_MISMATCH)return An(t.message,t.details);return U(t.message)??"gateway request failed"}function An(t,n){let i=n,a=ee(i.clientMinProtocol),l=ee(i.clientMaxProtocol),p=ee(i.expectedProtocol),f=ee(i.minimumProbeProtocol),y=[];if(a!==void 0&&l!==void 0)y.push(a===l?`Control UI v${a}`:`Control UI v${a}-v${l}`);if(p!==void 0)y.push(`Gateway v${p}`);if(f!==void 0)y.push(`connection check min v${f}`);let S=U(t)??"protocol mismatch";return y.length>0?`${S}: ${y.join(", ")}`:S}function te(t){return typeof t==="string"&&t.length>0}function Sn(t){if(!V(t))return!1;if(!te(t.code)||!te(t.message))return!1;if(t.retryable!==void 0&&typeof t.retryable!=="boolean")return!1;return t.retryAfterMs===void 0||Ne(t.retryAfterMs)!==void 0}function lt(t){if(!V(t)||t.type!=="event"||!te(t.event))return!1;return t.seq===void 0||Ne(t.seq)!==void 0}function ut(t){if(!V(t)||t.type!=="res"||!te(t.id)||typeof t.ok!=="boolean")return!1;return t.error===void 0||Sn(t.error)}var ne=60000;function De(t){return pt(t,"gateway-restarting")}function dt(t){return pt(t,"gateway-suspending")}function pt(t,n){if(!t||typeof t!=="object"||!("details"in t))return!1;let i=t.details;return typeof i==="object"&&i!==null&&"reason"in i&&i.reason===n}function Rn(t){return typeof t==="object"&&t!==null&&t.reason==="startup-sidecars"}function Ue(t){if(!t||typeof t!=="object")return!1;let n=t;return(n.gatewayCode??n.code)==="UNAVAILABLE"&&n.retryable===!0&&Rn(n.details)}function ft(t){if(!Ue(t))return null;let n=t.retryAfterMs;return Math.min(Math.max(Math.floor(typeof n==="number"&&Number.isFinite(n)?n:500),100),2000)}function xe(t){if(typeof t!=="string")return"";return t.trim().replace(/[A-Z]/g,(n)=>String.fromCharCode(n.charCodeAt(0)+32))}function ht(t){let n=t.scopes.join(","),i=t.token??"",a=xe(t.platform),l=xe(t.deviceFamily);return["v3",t.deviceId,t.clientId,t.clientMode,t.role,n,String(t.signedAtMs),i,t.nonce,a,l].join("|")}function qe(t){return t!==null&&typeof t==="object"&&!Array.isArray(t)}function Ee(t){return vn(t)??{}}function Et(t){return qe(t)?t:void 0}function vn(t){return t&&typeof t==="object"?t:void 0}function yt(t){let n=k(t.token),i=k(t.bootstrapToken),a=k(t.deviceToken),l=k(t.password),p=k(t.storedToken),f={storedToken:p,storedScopes:t.storedScopes};if(t.preferBootstrapToken&&i)return{authBootstrapToken:i,signatureToken:i,...f};let y=t.pendingDeviceTokenRetry===!0&&!a&&Boolean(n&&p&&t.trustedDeviceTokenRetry),S=a??(y||!(n||l)&&(!i||p)?p:void 0),v=Boolean(S&&!a&&p)&&S===p,w=n??S,R=!n&&!S&&!l?i:void 0;return{authToken:n,authBootstrapToken:R,authDeviceToken:y?p:void 0,authPassword:l,authApprovalRuntimeToken:k(t.approvalRuntimeToken),authAgentRuntimeIdentityToken:k(t.agentRuntimeIdentityToken),signatureToken:w??R,resolvedDeviceToken:S,usingStoredDeviceToken:v,...f}}function mt(t){let n={token:t.authToken,bootstrapToken:t.authBootstrapToken,deviceToken:t.authDeviceToken??t.resolvedDeviceToken,password:t.authPassword,approvalRuntimeToken:t.authApprovalRuntimeToken,agentRuntimeIdentityToken:t.authAgentRuntimeIdentityToken};return Object.values(n).some(Boolean)?n:void 0}function It(t){return t.requestedScopes??(t.usingStoredDeviceToken&&t.storedScopes?.length?t.storedScopes:[...t.defaultScopes])}function gt(t){if(t.retryBudgetUsed||t.currentDeviceToken||!t.explicitToken||!t.storedToken||!t.trustedEndpoint)return!1;let n=it(t.errorDetails);return t.canRetryWithDeviceTokenHint===!0||n.canRetryWithDeviceToken===!0||n.recommendedNextStep==="retry_with_device_token"||q(t.errorDetails)===C.AUTH_TOKEN_MISMATCH}var Le="model-catalog-snapshot";function Tt(t){let n=t.serverCapabilities.includes(Le)?t.modelCatalog:void 0,i=t.caps?.filter((a)=>a!==Le);if(n===void 0)return{caps:i};return{modelCatalog:n,caps:[...i??[],Le]}}var He=[[[183,183],[12288,12703],[19968,40869],[44032,55215],[65281,65376]],[[4352,4607],[11904,12287],[12704,19967],[40870,40959],[40960,42239],[42752,42759],[43360,43391],[55216,55295],[63744,64255]],[[711,711],[713,715],[729,729],[746,747],[773,773],[803,803],[65040,65103],[65377,65500],[65504,65510]],[[119648,119665]],[[94176,94207],[110576,110591],[110592,110959],[127488,127743],[131072,195103],[196608,210047]]];new RegExp(`[${He.flatMap((t)=>t.map(([n,i])=>`\\u{${n.toString(16)}}-\\u{${i.toString(16)}}`)).join("")}]`,"u");(()=>{let t=Math.max(...He.flatMap((i)=>i.map(([,a])=>a))),n=new Uint8Array(t+1);for(let[i,a]of He.entries())for(let[l,p]of a)n.fill(i+1,l,p+1);return n})();function K(t){return t instanceof Error?t:Error(String(t))}function wn(t){return Array.isArray(t)?t.filter((n)=>typeof n==="string"):[]}var me=2147000000;function Ie(t,n){let i=Error(t,n);return i.name="AbortError",i}async function _t(t,n,i,a={}){let l,p;try{let f=new Promise((S,v)=>{let w=(_)=>{try{S(_())}catch(c){v(c)}};if(l=setTimeout(()=>w(i),n),a.ref===!1)l.unref?.();let R=a.signal;if(R){if(p=()=>w(()=>{if(a.onAbort)return a.onAbort(R);throw Ie("Operation aborted",{cause:R.reason})}),R.addEventListener("abort",p,{once:!0}),R.aborted)p()}}),y;try{y=typeof t==="function"?t():t}catch(S){throw f.catch(()=>{}),S}return await Promise.race([y,f])}finally{if(clearTimeout(l),p)a.signal?.removeEventListener("abort",p)}}function Cn(t,n){let i=Math.min(t.maxMs,t.initialMs*t.factor**Math.max(n-1,0)),a=i*t.jitter*Math.random();return Math.min(t.maxMs,Math.round(i+a))}function At(t){return Number.isFinite(t)&&t>0?Math.min(Math.max(Math.floor(t),1),me):0}async function Mn(t,n,i={}){let a=At(t);if(a===0)return;await new Promise((l,p)=>{let f=()=>n?.removeEventListener("abort",S),y=setTimeout(()=>{f(),l()},a),S=()=>{clearTimeout(y),f(),p(Ie("aborted",{cause:n?.reason??Error("aborted")}))};if(n?.addEventListener("abort",S,{once:!0}),n?.aborted){S();return}if(i.ref===!1)y.unref?.()})}var On=class{constructor(t,n=Number.POSITIVE_INFINITY){this.policy=t,this.maxAttempts=n,this.attempts=0,this.initialMs=t.initialMs}reset(t=this.policy.initialMs){this.cancel(),this.attempts=0,this.initialMs=t,this.nextDelayOverrideMs=void 0}cancel(t=Error("retry cancelled")){this.pendingAbort?.abort(t),this.pendingAbort=void 0}next(t){let n=this.nextDelayOverrideMs;if(this.nextDelayOverrideMs=void 0,n===void 0&&++this.attempts>Math.ceil(this.maxAttempts))return;let i=Math.max(this.attempts,1),a=n??Cn({...this.policy,initialMs:this.initialMs},i);this.cancel();let l=new AbortController;return this.pendingAbort=l,{attempt:i,delayMs:a,signal:t?AbortSignal.any([l.signal,t]):l.signal}}},St={attempts:3,minDelayMs:300,maxDelayMs:30000,jitter:0},Nn=async(t)=>{let n=t;do{let i=Math.min(n,me);await new Promise((a)=>{setTimeout(a,i)}),n-=i}while(n>0)};function ye(t,n,i,a){if(typeof t!=="number"||!Number.isFinite(t))return n;return Math.min(Math.max(t,i??Number.NEGATIVE_INFINITY),a??Number.POSITIVE_INFINITY)}function re(t){return Math.min(Math.max(Math.round(t===Number.POSITIVE_INFINITY?me:Number.isFinite(t)?t:0),0),me)}function bn(t=St,n){let i=Math.max(1,Math.round(ye(n?.attempts,t.attempts))),a=re(ye(n?.minDelayMs,t.minDelayMs,0)),l=Math.max(a,re(ye(n?.maxDelayMs,t.maxDelayMs,0))),p=n?.jitter,f=t.jitter;return{attempts:i,minDelayMs:a,maxDelayMs:l,jitter:p==="full"?p:typeof p==="number"&&Number.isFinite(p)?Math.min(Math.max(p,0),1):f}}function Pn(t,n,i,a){if(n==="full"){if(i==="symmetric")return Math.max(0,Math.round(t*(0.5+a()*0.5)));return Math.max(0,Math.ceil(t*(1+a())))}if(n<=0)return i==="positive"?Math.ceil(t):t;let l=a(),p=t*(1+(i==="positive"?l*n:(l*2-1)*n));return Math.max(0,i==="positive"?Math.ceil(p):Math.round(p))}function kn(t,n="Non-Error thrown"){if(t instanceof Error)return t;if(typeof t==="string")return Error(t);let i=Error(n,{cause:t});if(typeof t==="object"&&t!==null||typeof t==="function")Object.assign(i,t);return i}function Dn(t={}){let n=t.sleep??Nn,i=t.random??Math.random,a=t.createFailure??((l)=>kn(l.at(-1)??Error("Retry failed")));return async function(p,f=3,y=300){let S=[],v=typeof f==="number",w=typeof f==="number"?{attempts:f}:f,R=bn(St,w),{attempts:_,minDelayMs:c}=R,d=R.maxDelayMs>0?R.maxDelayMs:Number.POSITIVE_INFINITY,E=w.retryAfterMaxDelayMs===void 0?d:Math.max(c,re(ye(w.retryAfterMaxDelayMs,d,0))),h=w.random??i,A=w.sleep??n,I=w.shouldRetry??(()=>!0);for(let M=1;M<=_;M+=1)try{return await p()}catch(O){if(S.push(O),M>=_||t.shouldRetry?.(O)===!1||!I(O,M))break;if(v){await n(re(y*2**(M-1)));continue}let b={attempt:M,maxAttempts:_,err:O,label:w.label},N=w.retryAfterMs?.(O),x=typeof N==="number"&&Number.isFinite(N),J=typeof w.delayMs==="function"?w.delayMs(b):w.delayMs,le=J===void 0?void 0:re(J),ue=x?Math.max(N,c):le===void 0?c*2**(M-1):Math.max(le,c),H=x?E:d,F=Math.min(ue,H),de=x&&(N??0)<=H,pe=R.jitter==="full"?!x||de:de;if(F=Pn(F,R.jitter,pe?"positive":"symmetric",h),F=Math.min(Math.max(F,c),H),await w.onRetry?.({...b,delayMs:F}),F>0)await A(F)}throw a(S)}}Dn();var Un=class{constructor(){this.listeners=new Map}add(t){let n=this.listeners.get(t)??{};return this.listeners.set(t,n),()=>{if(this.listeners.get(t)===n)this.listeners.delete(t)}}snapshot(){return[...this.listeners]}isCurrent(t,n){return this.listeners.get(t)===n}},Ln=new WeakSet;var z=class extends Error{constructor(t){super(t.message??"request failed");this.name="GatewayProtocolRequestError",this.code=t.code??"UNAVAILABLE",this.gatewayCode=this.code,this.details=t.details,this.retryable=t.retryable===!0,this.retryAfterMs=t.retryAfterMs}};function xn(t,n){Ln.add(t),Object.defineProperty(t,"responsePayload",{value:n,enumerable:!1,configurable:!0})}var Fe=class extends Error{constructor(t,n=`gateway request timed out after ${t.timeoutMs}ms: ${t.method}`){super(n);this.code="CLIENT_TIMEOUT",this.name="GatewayProtocolRequestTimeoutError",this.method=t.method,this.timeoutMs=t.timeoutMs,this.requestSent=t.requestSent}},Hn=class{constructor(t){this.opts=t,this.pending=new Map,this.requestSequence=0}setSuspensionPhase(t){if(t==="accepting")this.resumeBootstrapRequests();else if(t==="preparing"||t==="draining"||t==="prepared")this.pauseBootstrapRequests(void 0,!0)}pauseBootstrapRequests(t=ne,n=!1){let i=this.opts.nowMs(),a=D(Number.isFinite(t)&&t>0?t:ne),l=this.bootstrapPause??={retryAtMs:i,revision:0,announced:n};if(l.announced||=n,l.revision+=1,l.retryAtMs=Math.max(l.retryAtMs,i+a),clearTimeout(l.timer),l.timer=void 0,l.announced)return;l.timer=setTimeout(()=>{l.timer=void 0,this.drainBootstrapRequests()},D(l.retryAtMs-i)),l.timer.unref?.()}resumeBootstrapRequests(){clearTimeout(this.bootstrapPause?.timer),this.bootstrapPause=void 0,this.drainBootstrapRequests()}drainBootstrapRequests(){for(let t of this.pending.values())if(t.waitingForResume)t.resend?.()}get hasPending(){return this.pending.size>0}get hasUnboundedPending(){for(let t of this.pending.values())if(t.unbounded)return!0;return!1}releaseHeldRequests(t){for(let n of this.pending.values()){if(!t())return;let i=n.afterHello;n.afterHello=void 0,i?.()}}request(t,n,i,a,l=!1){let p;try{this.requestSequence+=1,p=`${this.requestSequence}:${this.opts.createRequestId()}`}catch(S){return Promise.reject(K(S))}let f=a?.timeoutMs===null?void 0:a?.timeoutMs??this.opts.requestTimeoutMs,y=typeof f==="number"&&Number.isFinite(f)?D(f,{minMs:0}):void 0;return new Promise((S,v)=>{let w,R,_=!1,c=!1,d={resolve:(I)=>S(I),reject:v,expectFinal:a?.expectFinal===!0,acceptedNotified:!1,onAccepted:a?.onAccepted,unbounded:y===void 0,method:n,startedAtMs:this.opts.nowMs(),prepareRetry:()=>{if(c=!1,_=!1,a?.signal?.aborted)return A(),!1;return!0}},E=()=>{if(clearTimeout(R),w!==void 0)clearTimeout(w);if(a?.signal?.removeEventListener("abort",A),this.bootstrapPause?.probe?.pending===d)this.bootstrapPause.probe=void 0,this.drainBootstrapRequests()},h=(I)=>{if(this.pending.get(p)!==d)return!1;return this.pending.delete(p),E(),this.finishTiming(p,d,!1,I),!0},A=()=>{if(a?.retainSentResultOnAbort&&c)return;if(!h("CLIENT_ABORTED"))return;v(this.opts.createRequestAbortError?.(n)??Error(`gateway request aborted for ${n}`))};if(a?.signal?.aborted){v(this.opts.createRequestAbortError?.(n)??Error(`gateway request aborted for ${n}`));return}if(d.cleanup=E,y!==void 0)w=setTimeout(()=>{if(!h("CLIENT_TIMEOUT"))return;v(this.opts.createRequestTimeoutError?.(n,y,_)??new Fe({method:n,timeoutMs:y,requestSent:_}))},y),w.unref?.();a?.signal?.addEventListener("abort",A,{once:!0}),this.pending.set(p,d);try{let I=JSON.stringify({type:"req",id:p,method:n,params:i}),M=()=>{if(this.pending.get(p)!==d||a?.signal?.aborted||y!==void 0&&this.opts.nowMs()-d.startedAtMs>=y)return;let O=d.resend?this.bootstrapPause:void 0;if(O&&!O.announced&&!O.timer&&!O.probe)O.probe={pending:d,revision:O.revision};if(d.waitingForResume=Boolean(O&&(O.announced||O.probe?.pending!==d)),d.waitingForResume)return;try{if(c=!0,t.send(I),this.pending.get(p)!==d)return;_=c,this.invoke("sent",()=>a?.onSent?.(p))}catch(b){if(h("CLIENT_SEND_ERROR"))v(K(b))}};if(d.retryStartup=(O)=>{d.resend=M,clearTimeout(R),R=setTimeout(M,Me(O,ne)),R.unref?.()},n==="agent.identity.get"||n==="sessions.subscribe"||n==="sessions.groups.list"||n==="question.list"||n==="sessions.list")d.resend=M;if(l)d.afterHello=M;else M()}catch(I){if(h("CLIENT_SEND_ERROR"))v(K(I))}})}handleResponse(t){let n=this.pending.get(t.id);if(!n)return;let i=t.payload?.status;if(t.ok&&n.expectFinal&&i==="accepted"){if(!n.acceptedNotified)n.acceptedNotified=!0,this.invoke("accepted",()=>n.onAccepted?.(t.payload));return}let a=t.error?.details;if(!t.ok&&Ue(t.error)&&a!==null&&typeof a==="object"&&"method"in a&&a.method===n.method&&!n.acceptedNotified){if(n.prepareRetry()){if(n.retryStartup?.(t.error?.retryAfterMs),this.bootstrapPause?.probe?.pending===n&&this.bootstrapPause.probe.revision===this.bootstrapPause.revision)this.resumeBootstrapRequests()}return}if(!t.ok&&n.resend&&!n.acceptedNotified&&t.error?.code==="UNAVAILABLE"&&t.error.retryable===!0&&(dt(t.error)||De(t.error))){if(!n.prepareRetry())return;if(this.bootstrapPause?.probe?.pending===n)this.bootstrapPause.probe=void 0;this.pauseBootstrapRequests(De(t.error)?Math.ceil(Math.max(ne,t.error.retryAfterMs??0)*(1+Math.random()*0.2)):t.error.retryAfterMs),n.waitingForResume=!0;return}if(this.pending.delete(t.id),t.ok&&this.bootstrapPause?.probe?.pending===n&&this.bootstrapPause.probe.revision===this.bootstrapPause.revision)this.resumeBootstrapRequests();if(n.cleanup?.(),t.ok){this.finishTiming(t.id,n,!0),n.resolve(t.payload);return}this.finishTiming(t.id,n,!1,t.error?.code);let l=this.opts.createRequestError?.(t.error??{})??new z(t.error??{});xn(l,t.payload),n.reject(l)}flush(t){clearTimeout(this.bootstrapPause?.timer),this.bootstrapPause=void 0;let n=this.pending;this.pending=new Map,this.requestSequence=0;for(let[i,a]of n)a.cleanup?.(),this.finishTiming(i,a,!1,"CLIENT_CLOSED"),a.reject(t)}finishTiming(t,n,i,a){let l=this.opts.nowMs();this.invoke("request timing",()=>this.opts.onTiming?.({id:t,method:n.method,ok:i,durationMs:Math.max(0,l-n.startedAtMs),startedAtMs:n.startedAtMs,endedAtMs:l,errorCode:a}))}invoke(t,n){try{n()}catch(i){this.opts.onCallbackError?.(t,i)}}},he=Object.freeze({closeCode:1008,closeReason:"connect failed"}),Rt=class{constructor(t){this.opts=t,this.socket=null,this.listeners=new Un,this.stopped=!0,this.generation=0,this.connectionAbort=null,this.lastSeq=null,this.connectNonce=null,this.serverCapabilities=[],this.connectSent=!1,this.connectRequestSent=!1,this.handshakeTimer=null,this.reconnectSignal=null,this.socketOpened=!1,this.helloReceived=!1,this.readyForRequests=!1,this.connectTiming=null,this.reconnectSupervisor=new On({initialMs:t.reconnect.initialMs,maxMs:t.reconnect.maxMs,factor:t.reconnect.multiplier,jitter:0}),this.requests=new Hn({createRequestId:t.createRequestId,createRequestError:t.createRequestError,createRequestTimeoutError:t.createRequestTimeoutError,createRequestAbortError:t.createRequestAbortError,requestTimeoutMs:t.requestTimeoutMs,nowMs:()=>this.nowMs(),onTiming:t.onRequestTiming,onCallbackError:t.onCallbackError})}get connected(){return this.socket?.isOpen()??!1}get hasPendingRequests(){return this.requests.hasPending}get connecting(){return this.connectSent&&!this.helloReceived}get opening(){return this.socket!==null&&!this.socketOpened}get hasUnboundedPendingRequests(){return this.requests.hasUnboundedPending}start(){if(this.socket||this.reconnectSignal)return;this.stopped=!1,this.reconnectSupervisor.cancel(),this.connect()}stop(){this.stopped=!0,this.connectionAbort?.abort(),this.clearHandshakeTimer(),this.reconnectSignal=null,this.reconnectSupervisor.reset();let t=this.socket;if(t&&this.opts.notifyStoppedClose)this.stoppedSocket={socket:t,context:this.closeContext()};this.socket=null,this.connectFailure=void 0,this.connectTiming=null,this.requests.flush(Error("gateway client stopped")),t?.close()}request(t,n,i){let a=this.socket;if(!a||this.socketOpened&&!a.isOpen())return Promise.reject(Error("gateway not connected"));if(typeof t!=="string"||t.length===0)return Promise.reject(Error("invalid request frame: method must be a non-empty string"));return this.requests.request(a,t,n,i,!this.readyForRequests)}addEventListener(t){return this.listeners.add(t)}closeSocket(t,n){this.connectionAbort?.abort(),this.socket?.close(t,n)}resetReconnectBackoff(t){this.reconnectSignal=null,this.reconnectSupervisor.reset(t)}recordTiming(t,n,i,a){let l=this.nowMs(),p=this.connectTiming;if(!p||p.generation!==n)return;if(p.hasChallenge||=t==="challenge",p.usedFallback||=t==="fallback",this.invoke("connect timing",()=>this.opts.onTiming?.({phase:t,generation:n,durationMs:Math.max(0,l-p.startedAtMs),phaseDurationMs:Math.max(0,l-p.lastAtMs),hasChallenge:p.hasChallenge,usedFallback:p.usedFallback,plan:i,detail:a})),p.lastAtMs=l,t==="hello"||t==="failed")this.connectTiming=null}connect(){if(this.stopped)return;let t=this.generation+1;this.lastSeq=null,this.connectNonce=null,this.connectChallengeTs=void 0,this.serverCapabilities=[],this.connectSent=this.connectRequestSent=!1,this.socketOpened=!1,this.helloReceived=!1,this.readyForRequests=!1,this.connectFailure=void 0;let n;try{n=this.opts.createSocket({open:()=>{if(!this.isActive(n,t))return;if(this.socketOpened=!0,this.recordTiming("socket-open",t),this.connectNonce){this.sendConnect(n,t);return}this.clearHandshakeTimer();let a=Date.now();this.handshakeTimer=setTimeout(()=>{if(this.handshakeTimer=null,!this.isActive(n,t)||this.connectSent||!n.isOpen())return;if(this.opts.handshake.mode==="fallback"){this.recordTiming("fallback",t),this.sendConnect(n,t);return}let l=Date.now()-a,p=Error(this.opts.handshake.timeoutMessage?.(l)??`gateway connect challenge timeout after ${l}ms`);this.opts.onConnectError?.(p),n.close(1008,"connect challenge timeout")},this.opts.handshake.timeoutMs),this.handshakeTimer.unref?.()},message:(a)=>this.handleMessage(n,t,a),close:(a,l)=>{if(this.socket!==n){if(this.stoppedSocket?.socket===n){let y={...this.stoppedSocket.context,code:a,reason:l};this.stoppedSocket=void 0,this.invoke("close",()=>this.opts.onClose?.(y,{retry:!1,notify:!0}))}return}this.socket=null,this.connectionAbort?.abort(),this.clearHandshakeTimer();let p={...this.closeContext(),code:a,reason:l,generation:t};this.connectFailure=void 0;let f=this.opts.resolveClose(p);if(this.requests.flush(f.pendingError??p.connectFailure?.error??Error(`gateway closed (${a}): ${l}`)),this.invoke("close",()=>this.opts.onClose?.(p,f)),f.retry&&!this.stopped&&!this.socket&&!this.reconnectSignal){let y=p.connectFailure?.error,S=y instanceof z&&y.retryable&&y.retryAfterMs!==void 0&&Number.isFinite(y.retryAfterMs)&&y.retryAfterMs>0?y.retryAfterMs:void 0;this.scheduleReconnect(f.reconnectDelayMs??p.connectFailure?.reconnectDelayMs,S)}},error:(a)=>{if(!this.isActive(n,t)||this.connectSent)return;this.connectFailure={error:a},this.opts.onConnectError?.(a)}})}catch(a){let l=K(a);if(this.opts.onSocketFactoryError?.(l),this.opts.onConnectError?.(l),this.opts.rethrowSocketFactoryError?.(l)){if(this.generation>0&&!this.stopped&&!this.socket&&!this.reconnectSignal)this.opts.onReconnectStopped?.(l);throw l}if(this.opts.shouldRetrySocketFactoryError?.(l)&&!this.stopped&&!this.socket&&!this.reconnectSignal)this.scheduleReconnect();else if(this.generation>0&&!this.stopped&&!this.socket&&!this.reconnectSignal)this.opts.onReconnectStopped?.(l);return}this.generation=t,this.connectionAbort=new AbortController,this.socket=n;let i=this.nowMs();this.connectTiming={generation:t,startedAtMs:i,lastAtMs:i,hasChallenge:!1,usedFallback:!1}}sendConnect(t,n){if(!this.isActive(t,n)||!t.isOpen()||this.connectSent)return;this.connectSent=!0,this.clearHandshakeTimer(),this.handshakeTimer=ve(()=>{if(this.isActive(t,n)&&!this.helloReceived)t.close(4000,"connect timeout")});let i;try{i=this.opts.buildConnectPlan({nonce:this.connectNonce,challengeTs:this.connectChallengeTs,serverCapabilities:this.serverCapabilities,generation:n,...this.connectAuthority(t,n)})}catch(a){this.handleConnectPlanError(t,n,a);return}if(i instanceof Promise){i.then((a)=>this.sendConnectPlan(t,n,a)).catch((a)=>this.handleConnectPlanError(t,n,a));return}this.sendConnectPlan(t,n,i)}handleConnectPlanError(t,n,i){if(!this.isConnectCurrent(t,n))return;let a=K(i),l=this.opts.onConnectPlanError?.(a)??he;if(this.opts.onConnectError?.(l.error??a),l.stop)this.stopped=!0;t.close(l.closeCode,l.closeReason)}sendConnectPlan(t,n,i){if(!this.isConnectCurrent(t,n))return;let a={...this.connectAuthority(t,n),generation:n,nonce:this.connectNonce,challengeTs:this.connectChallengeTs,plan:i};this.recordTiming("connect-plan-ready",n,i),this.requests.request(t,"connect",this.opts.buildConnectParams(i),{onSent:()=>{this.connectRequestSent=!0,this.recordTiming("request-sent",n,i)}}).then((l)=>{if(!this.isConnectCurrent(t,n))return;this.helloReceived=!0,this.requests.setSuspensionPhase(l.snapshot?.suspension?.phase),this.clearHandshakeTimer(),this.connectFailure=void 0,this.reconnectSupervisor.reset(),this.recordTiming("hello",n,i);let p=()=>{if(!this.isConnectCurrent(t,n))return;if(this.invoke("hello",()=>this.opts.onHello?.(l)),!this.isConnectCurrent(t,n))return;if(this.requests.releaseHeldRequests(()=>this.isConnectCurrent(t,n)),this.isConnectCurrent(t,n))this.readyForRequests=!0},f=this.opts.onConnectHello?.(l,a);if(f instanceof Promise)return f.then(p);return p()}).catch((l)=>{if(!this.isActive(t,n))return;let p=l instanceof z?l:new z({message:String(l)});this.connectFailure={error:p};let f=this.opts.onConnectFailure?.(p,a)??he,y=(S)=>{if(!this.isActive(t,n))return;if(this.connectFailure={error:p,reconnectDelayMs:S.reconnectDelayMs},S.keepOpen){this.clearHandshakeTimer();return}if(S.stop)this.stopped=!0;this.connectionAbort?.abort(),t.close(S.closeCode,S.closeReason)};if(f instanceof Promise)return f.then(y);return y(f)}).catch((l)=>{if(!this.isConnectCurrent(t,n))return;this.opts.onConnectError?.(K(l)),this.closeSocket(he.closeCode,he.closeReason)})}handleMessage(t,n,i){if(!this.isActive(t,n)||this.connectionAbort?.signal.aborted)return;let a;try{a=JSON.parse(i)}catch(l){this.opts.onParseError?.(l);return}if(lt(a)){if(this.opts.onActivity?.(),a.event==="connect.challenge"){let p=a.payload,f=typeof p?.nonce==="string"?p.nonce.trim():"";if(!f){if(this.opts.handshake.mode==="require-challenge"){let S=Error("gateway connect challenge missing nonce");this.opts.onConnectError?.(S),t.close(1008,"connect challenge missing nonce")}return}this.connectNonce=f,this.serverCapabilities=wn(p?.capabilities);let y=p?.ts;this.connectChallengeTs=typeof y==="number"&&Number.isSafeInteger(y)&&y>=0?y:null,this.recordTiming("challenge",n),this.sendConnect(t,n);return}let l=a.seq;if(l!==void 0){if(this.lastSeq!==null&&l>this.lastSeq+1){let p=this.lastSeq+1,f=Ee(a.payload).state;if(a.event==="chat"&&(f==="final"||f==="error"||f==="aborted"))this.dispatchEvent(t,n,a);if(!this.isActive(t,n)||this.connectionAbort?.signal.aborted)return;if(this.invoke("gap",()=>this.opts.onGap?.({expected:p,received:l})),this.isActive(t,n)&&!this.connectionAbort?.signal.aborted)this.closeSocket(4000,"event sequence gap");return}this.lastSeq=l}this.dispatchEvent(t,n,a);return}if(!ut(a))return;this.opts.onActivity?.(),this.requests.handleResponse(a)}dispatchEvent(t,n,i){let a=this.listeners.snapshot();if(i.event==="gateway.suspension")this.requests.setSuspensionPhase(Ee(i.payload).phase);else if(i.event==="shutdown"&&typeof Ee(i.payload).restartExpectedMs==="number")this.requests.setSuspensionPhase("draining");this.invoke("event",()=>this.opts.onEvent?.(i));for(let[l,p]of a){if(!this.isActive(t,n)||this.connectionAbort?.signal.aborted)return;if(this.listeners.isCurrent(l,p))this.invoke("event listener",()=>l(i))}}scheduleReconnect(t,n=0){if(t!==void 0)this.reconnectSupervisor.nextDelayOverrideMs=t;let i=this.reconnectSupervisor.next();if(!i)return;this.reconnectSignal=i.signal;let a=t;if(a===void 0){let l=Math.max(i.delayMs,n),p=Math.max(this.opts.reconnect.maxMs,Math.min(Number.MAX_VALUE,n*1.2)),f=Math.max(n,Math.min(l,p/1.2)),y=Math.min(l*1.2,p);a=Math.ceil(f+Math.random()*(y-f))}a=At(a),Mn(a,i.signal).then(()=>{if(this.reconnectSignal!==i.signal)return;this.reconnectSignal=null,this.invoke("reconnect",()=>this.connect())},()=>{if(this.reconnectSignal===i.signal)this.reconnectSignal=null}),this.invoke("reconnect scheduled",()=>this.opts.onReconnectScheduled?.(a,i.signal))}closeContext(){return{generation:this.generation,socketOpened:this.socketOpened,helloReceived:this.helloReceived,connectRequestSent:this.connectRequestSent,connectFailure:this.connectFailure}}isConnectCurrent(t,n){return this.isActive(t,n)&&t.isOpen()&&!this.connectionAbort?.signal.aborted}connectAuthority(t,n){let i=this.connectionAbort?.signal;if(!i)throw Error("gateway connection authority is unavailable");return{signal:i,assertCurrent:()=>{if(i.throwIfAborted(),!this.isConnectCurrent(t,n))throw Error("gateway connection retired")}}}isActive(t,n){return!this.stopped&&this.socket===t&&this.generation===n}nowMs(){return this.opts.nowMs?.()??Date.now()}clearHandshakeTimer(){this.handshakeTimer=we(this.handshakeTimer)}invoke(t,n){try{n()}catch(i){this.opts.onCallbackError?.(t,i)}}},qn=new Set([C.AUTH_TOKEN_MISSING,C.AUTH_BOOTSTRAP_TOKEN_INVALID,C.AUTH_PASSWORD_MISSING,C.AUTH_PASSWORD_MISMATCH,C.AUTH_RATE_LIMITED,C.AUTH_DEVICE_TOKEN_MISMATCH,C.AUTH_SCOPE_MISMATCH,C.AUTH_IDENTITY_HEADER_REQUIRED,C.AUTH_VERIFIED_USER_REQUIRED,C.CONTROL_UI_BUILD_MISMATCH,C.PAIRING_REQUIRED,C.PAIRING_REJECTED,C.PAIRING_EXPIRED,C.CONTROL_UI_DEVICE_IDENTITY_REQUIRED,C.DEVICE_IDENTITY_REQUIRED]);function vt(t){let n=q(t.details);if(!n)return!1;let i=ke(t.details);if(n===C.PAIRING_REQUIRED&&(i?.pauseReconnect===!1||i?.recommendedNextStep==="wait_then_retry"))return!1;if(n===C.AUTH_TOKEN_MISMATCH)return t.tokenMismatchIsTerminal===!0&&!t.deviceTokenRetryPending;if(n===C.AUTH_IDENTITY_HEADER_REQUIRED)return!t.deviceTokenRetryPending;return qn.has(n)||t.protocolMismatchIsTerminal===!0&&n===C.PROTOCOL_MISMATCH||t.clientVersionMismatchIsTerminal===!0&&n===C.CLIENT_VERSION_MISMATCH}import{Buffer as wt}from"buffer";function Ct(t,n="utf8"){if(Array.isArray(t))return wt.concat(t).toString(n);return t instanceof ArrayBuffer?wt.from(t).toString(n):t.toString(n)}import{createRequire as Fn}from"module";var Mt={WEBCHAT_UI:"webchat-ui",CONTROL_UI:"openclaw-control-ui",BROWSER_COPILOT:"openclaw-browser-copilot",TUI:"openclaw-tui",WEBCHAT:"webchat",CLI:"cli",GATEWAY_CLIENT:"gateway-client",MACOS_APP:"openclaw-macos",LINUX_APP:"openclaw-linux",IOS_APP:"openclaw-ios",WATCHOS_APP:"openclaw-watchos",ANDROID_APP:"openclaw-android",NODE_HOST:"node-host",WORKER:"openclaw-worker",TEST:"test",FINGERPRINT:"fingerprint",PROBE:"openclaw-probe"},se=Mt,G={WEBCHAT:"webchat",CLI:"cli",UI:"ui",BACKEND:"backend",NODE:"node",WORKER:"worker",PROBE:"probe",TEST:"test"};var vs=new Map(Object.values(Mt).map((t)=>[t,t])),ws=new Map(Object.values(G).map((t)=>[t,t]));var W=4,Ot=4,P=3,Nt=3;var oe=g(Pt(),1);import{randomUUID as Gn}from"crypto";import{isIP as Wn}from"net";import{TLSSocket as $n,checkServerIdentity as Bn}from"tls";import _e from"path";function Vn(t){try{return JSON.parse(t)}catch{return}}function Kn(t){return/^[\t\n\r ]*\{/.test(t)?Et(Vn(t)):void 0}var jn=new Set(["token","key","api_key","apikey","secret","access_token","auth_token","password","pass","passwd","auth","jwt","session","id_token","code","client_secret","app_secret","hook_token","refresh_token","signature","x_amz_signature","x_amz_security_token","private_key","credential","authorization","sig","x_api_key","x_access_token","x_auth_token"]),kt=/[\p{C}\p{Z}\u115F\u1160\u3164\uFFA0+]/gu,zn=/(?:^|_)token(?:_[a-f0-9]{16,})?$/u,Yn=/\/bot\d{6,}(?::|%3[aA])[A-Za-z0-9_-]{20,}(?=\/|$)/giu,X=8,Qn=/(?:^|[^a-z\d+.-])[a-z][a-z\d+.-]{0,31}:/iu,Xn=/\b(?:https?|wss?|ftp):[\\/]{0,2}[^\\/?#\s]*/giu,Jn=/\b(?:https?|wss?|ftp):[\\/]{0,2}[^\s]*@[^\\/?#\s]*/giu,Zn=/[\\/]{2,}[^\\/?#\s]*/gu;function Ft(t){return t.replace(Yn,"/bot***")}function er(t){let n=t.replace(kt,"");for(let i=0;i<=X;i+=1){let a;try{a=decodeURIComponent(n).replace(kt,"")}catch{break}if(a===n)return{value:j(n).replaceAll("-","_"),unresolvedEncoding:!1};n=a}return{value:j(n).replaceAll("-","_"),unresolvedEncoding:n.includes("%")}}function Q(t){if(Qn.test(t))return!0;let n=t.search(/\/\/|\\\\/u);if(n>=0&&t.includes("@",n+2))return!0;let i=t.search(/[?&]/u);if(i>=0&&t.includes("=",i+1))return!0;let a=t.indexOf("#");if(a>=0&&t.includes("=",a+1))return!0;return/%[\da-f]{2}/iu.test(t)}function Ve(t){let n=er(t);return n.unresolvedEncoding||jn.has(n.value)||zn.test(n.value)}function tr(t){try{let n=new URL(t),i=!1,a=Ft(n.pathname);if(a!==n.pathname)n.pathname=a,i=!0;if(n.username||n.password)n.username=n.username?"***":"",n.password=n.password?"***":"",i=!0;for(let l of Array.from(n.searchParams.keys()))if(Ve(l))n.searchParams.set(l,"***"),i=!0;return i?n.toString():t}catch{return t}}function $e(t,n){let i=new URLSearchParams(t),a=[],l=new Set,p=!1;for(let[f,y]of i){if(Ve(f)){if(p=!0,!l.has(f))l.add(f),a.push([f,"***"]);continue}let S=Be(f,n+1),v=Be(y,n+1);if(S!==f||v!==y)p=!0;a.push([S,v])}if(!p)return t;return new URLSearchParams(a).toString()}function Te(t){return Ft(Gt(t).replace(/([?&])([^=&]+)=([^&]*)/g,(n,i,a)=>Ve(a)?`${i}${a}=***`:n))}function Dt(t,n){let i=t.slice(n),a=i.lastIndexOf("@");if(a<0)return t;return`${t.slice(0,n)}***:***@${i.slice(a+1)}`}function Ge(t,n){let i=n;while(t[i]==="/"||t[i]==="\\")i+=1;return i}function Gt(t){return t.replace(Xn,(n)=>Dt(n,Ge(n,n.indexOf(":")+1))).replace(Jn,(n)=>{let i=Ge(n,n.indexOf(":")+1),a=n.lastIndexOf("@"),l=n.slice(i).search(/[\\/?#]/u);if(a<0||l<0)return n;let p=i+l;if(p>=a)return n;let f=n.indexOf(":",i);if(f<0||f>p)return n;let y=n.slice(i,p),S=n.slice(f+1,p);if(/^\d+$/u.test(S)||/^\[[^\]]+\](?::\d+)?$/u.test(y))return n;return`${n.slice(0,i)}***:***@${n.slice(a+1)}`}).replace(Zn,(n)=>Dt(n,Ge(n,0)))}function Ke(t){for(let n of t.matchAll(/(?:\b(?:https?|wss?|ftp):[\\/]{0,2}|[\\/]{2,})/giu)){let i=t.slice((n.index??0)+n[0].length),a=i.search(/(?<!\*\*\*:\*\*\*)@/u),l=i.search(/[\\/?#]/u),p=i.slice(l+1,a);if(a>=0&&(l<0||a<=l||i[l]==="/"&&(p.includes(":")||/^[^/?#\s]+\.[^/?#\s]+(?:[/?#]|$)/u.test(i.slice(a+1)))))return!0}return!1}function nr(t,n){let i=t.indexOf("#");if(i<0)return t;let a=t.slice(i+1),l=je(a,n+1);return l===a?t:`${t.slice(0,i+1)}${l}`}function je(t,n){if(!t)return t;if(n>X&&Q(t))return"***";let i=$t(t,n);if(i.parsedWholeUrl)return Te(i.value);let a=t.search(/[?&]/u),l=t.indexOf("=");if(l>=0&&(a<0||l<a))return $e(t,n);let p=t.indexOf("?");if(p>=0){let v=$e(t.slice(p+1),n);return`${Bt(Te(t.slice(0,p+1)),n+1)}${v}`}let f=Te(t);if(!Q(f))return f;let y;try{y=decodeURIComponent(f)}catch{return"***"}if(y===f)return f;let S=je(y,n+1);return S===y?f:encodeURIComponent(S)}function Wt(t,n){if(!Q(t))return t;if(n>X)return"***";let i;try{i=decodeURIComponent(t)}catch{return"***"}if(i===t)return t;let a=Ae(i,n);if(a.value!==i||Ke(i))return a.value!==i?a.value:"***";if(a.parsedWholeUrl)return t;let l=Wt(i,n+1);return l===i?t:l}function $t(t,n){try{let i=tr(t),a=new URL(i);if(n>X)return{value:"***",parsedWholeUrl:!0};let l=i!==t,p=Gt(Wt(a.pathname,n+1));if(p!==a.pathname){let v=a.pathname;if(a.pathname=p,a.pathname===v)return{value:i,parsedWholeUrl:!1};l=!0}let f=$e(a.search.slice(1),n);if(f!==a.search.slice(1))a.search=f,l=!0;let y=a.hash.slice(1),S=je(y,n+1);if(S!==y)a.hash=S,l=!0;return{value:l?a.toString():t,parsedWholeUrl:!0}}catch{return{value:t,parsedWholeUrl:!1}}}function Ae(t,n){let i=$t(t,n);if(i.parsedWholeUrl)return i;return{value:Bt(nr(Te(i.value),n),n+1),parsedWholeUrl:!1}}function Bt(t,n){if(!Q(t))return t;if(n>X)return"***";let i;try{i=decodeURIComponent(t)}catch{return"***"}if(i===t)return t;let a=Ae(i,n+1);if(a.value!==i||a.parsedWholeUrl)return a.value===i?t:a.value;return Ke(i)?"***":t}function Be(t,n){if(!Q(t))return t;if(n>X)return"***";let i=Ae(t,n);if(i.value!==t)return i.value;if(Ke(t))return"***";if(i.parsedWholeUrl)return t;let a;try{a=decodeURIComponent(t)}catch{return"***"}if(a===t||!Q(a))return t;let l=Be(a,n+1);return l===a?t:encodeURIComponent(l)}function rr(t){return Ae(t,0).value}oe.default.IPv4.parse("198.18.0.0");function Vt(t){return t.kind()==="ipv6"}function Kt(t){return Vt(t)&&t.isIPv4MappedAddress()?t.toIPv4Address():t}function sr(t){let n=k(t);if(!n)return;return n.startsWith("[")&&n.endsWith("]")?n.slice(1,-1):n}function ze(t){let n=sr(t);if(!n)return;return oe.default.IPv4.isValidFourPartDecimal(n)||oe.default.IPv6.isValid(n)?oe.default.parse(n):void 0}function or(t){return ir(t)?.toString()}function ir(t){let n=ze(t);if(!n)return;let i=Kt(n);if(Vt(i)&&i.zoneId)i.zoneId=i.zoneId.toLowerCase();return i}function ar(t){let n=ze(t);if(!n)return!1;return Kt(n).range()==="loopback"}function Ut(t){let n=t instanceof Error?t.message:String(t);return n==="gateway client stopped"||n==="Error: gateway client stopped"}function L(t){return String(t).replace(/\/\/([^@/?#\s]+)@/g,"//***:***@").replace(/(Authorization:\s*Bearer\s+)[^\s]+/giu,"$1***").replace(/([?&])([^=&\s]+)=([^&#\s"'<>)]*)/g,(n,i,a)=>/(?:token|password|secret|key|auth|credential)/iu.test(a)?`${i}${a}=***`:n)}var cr=/^[a-fA-F0-9]{64}$/u,lr=/^(?:[a-fA-F0-9]{2}:){31}[a-fA-F0-9]{2}$/u;function ie(t){let n=(t??"").trim().replace(/^sha256:/iu,"");if(cr.test(n))return n.toLowerCase();return lr.test(n)?n.replaceAll(":","").toLowerCase():""}function jt(t){if(!t)return null;let n=t.toLowerCase().trim(),i=n.replace(/\.+$/,"");if(i==="localhost")return{isLocalhost:!0,unbracketedHost:i};return{isLocalhost:!1,unbracketedHost:n.startsWith("[")&&n.endsWith("]")?n.slice(1,-1):n}}function zt(t){let n=or(t);return n?ze(n):void 0}var ur=class{constructor(t){this.storage=t,this.operations=new Set}load(t){let n=()=>(t.signal?.throwIfAborted(),t.assertCurrent?.(),this.track(this.storage.loadDeviceAuthToken(t)));return this.operations.size>0?this.settle().then(n):n()}store(t,n,i){let a=(p)=>{let f=K(p),y=!1;try{y=i(f)}catch{}if(!y)this.unreportedPersistenceFailure??=f;throw f};t.signal?.throwIfAborted(),t.assertCurrent?.();let l=this.storage.storeDeviceAuthToken(t);return l instanceof Promise?this.track(l.then(n).catch(a)):n()}clear(t,n,i){let a=()=>{if(!i())return;let l=[n.token,n.receiptToken].filter((S)=>typeof S==="string"),p=[...new Set(l)];if(n.token===void 0&&p.length===0)p.push(void 0);let f=(S)=>{t.signal?.throwIfAborted(),t.assertCurrent?.();let v=this.storage.clearDeviceAuthToken({...t,...S===void 0?{}:{expectedToken:S}});return v instanceof Promise?v.then(()=>{}):void 0},y;for(let S of p)y=y?y.then(()=>f(S)):f(S);return y};return this.track(n.persistence?n.persistence.then(a,a):a())}async settle(){await Promise.allSettled(this.operations)}async drain(){await this.settle();let t=this.unreportedPersistenceFailure;if(this.unreportedPersistenceFailure=void 0,t)throw t}track(t){if(!(t instanceof Promise))return t;return this.operations.add(t),t.then(()=>this.operations.delete(t),()=>this.operations.delete(t)),t}},dr=2048,pr=1000;async function fr(t){return await new Promise((n)=>{let i=[],a=0,l=!1,p=()=>{if(l)return;l=!0,clearTimeout(S),t.off("data",y),t.off("end",p),t.off("error",p),t.off("aborted",p),n(Buffer.concat(i,a).toString("utf8").replace(/\s+/gu," ").trim())},f=()=>{p(),t.destroy()},y=(v)=>{let w=Buffer.isBuffer(v)?v:Buffer.from(v),R=dr-a;if(R>0){let _=w.subarray(0,R);i.push(_),a+=_.byteLength}if(w.byteLength>=R)f()},S=setTimeout(f,pr);S.unref?.(),t.on("data",y),t.once("end",p),t.once("error",p),t.once("aborted",p)})}function hr(t,n,i){let a=t.platform??n;if(!i)return{platform:a,deviceFamily:t.deviceFamily,modelIdentifier:t.modelIdentifier};return{platform:a==="macos"?"darwin":a==="windows"?"win32":a}}function We(t){if(t.role!=="node"||t.mode!==G.NODE||t.clientName!==se.NODE_HOST)return!1;return(t.minProtocol??P)===P&&(t.maxProtocol??W)===W}var B=class extends z{constructor(t){super({...t,message:ct({message:t.message,details:t.details})});this.name="GatewayClientRequestError"}},Er=class extends Fe{constructor(t){super(t,`gateway request timeout for ${t.method}`);this.name="GatewayClientRequestTimeoutError"}},yr=Symbol("gateway.connectAssemblyError");function mr(t){return Object.defineProperty(t,yr,{configurable:!0,value:!0}),t}function Ir(t){return t instanceof URL?t:URL.parse(t)}function gr(t){return Ir(t)?.protocol==="wss:"}var Tr=new Set(["loopback","private","linkLocal","carrierGradeNat"]),_r=new Set(["loopback","linkLocal","uniqueLocal","deprecatedSiteLocal"]);function Ar(t){return(t.kind()==="ipv4"?Tr:_r).has(t.range())}function Sr(t){let n=jt(t);return Boolean(n&&(n.isLocalhost||ar(n.unbracketedHost)))}function Rr(t){let n=jt(t);if(!n)return!1;if(n.isLocalhost)return!0;let i=zt(n.unbracketedHost);return Boolean(i&&Ar(i))}function vr(t){if(Rr(t))return!0;let n=t.toLowerCase().trim().replace(/\.+$/,"");return n.endsWith(".local")||n.endsWith(".ts.net")}function wr(t,n){let i=URL.parse(t);if(!i)return!1;let a=i.protocol==="https:"?"wss:":i.protocol==="http:"?"ws:":i.protocol;if(a==="wss:")return!0;if(a!=="ws:")return!1;if(vr(i.hostname))return!0;if(n?.allowPrivateWs===!0)return zt(i.hostname.startsWith("[")&&i.hostname.endsWith("]")?i.hostname.slice(1,-1):i.hostname)===void 0;return!1}var Y=class extends Error{},xt=class extends Error{};function Cr(t){let n=gr(t.url);if(t.tlsFingerprint&&!n)throw new Y("gateway tls fingerprint requires wss:// gateway url");let i=(t.env??process.env).OPENCLAW_ALLOW_INSECURE_PRIVATE_WS==="1";if(!wr(t.url,{allowPrivateWs:i}))throw new Y(`SECURITY ERROR: Cannot connect to "${URL.parse(t.url)?.hostname||t.url}" over plaintext ws://. Both credentials and chat data would be exposed to network interception. Use wss:// for remote URLs. Safe defaults: keep gateway.bind=loopback and connect via SSH tunnel (ssh -N -L 18789:127.0.0.1:18789 user@gateway-host), or use Tailscale Serve/Funnel. `+(i?"":"Break-glass (trusted private networks only): set OPENCLAW_ALLOW_INSECURE_PRIVATE_WS=1. ")+"Run `openclaw doctor --fix` for guidance.");let a=t.normalizeTlsFingerprint??ie,l=t.tlsFingerprint?ie(t.tlsFingerprint):void 0;if(t.tlsFingerprint&&!l)throw new Y("gateway tls fingerprint must be a SHA-256 fingerprint");let p={...t.options};if(n&&t.tlsServerName){let f=t.tlsServerName;p.servername=Wn(f)?"":f,p.checkServerIdentity=(y,S)=>Bn(f,S)}if(n&&l)Mr(p,l,a);return{options:p}}function Mr(t,n,i=ie){t.rejectUnauthorized=!1;let a={...t.headers},l=Object.entries(a).filter(([p])=>p.toLowerCase()==="expect");for(let[p]of l)delete a[p];t.headers=a,t.finishRequest=(p)=>{p.once("socket",(f)=>{if(!(f instanceof $n)){p.destroy(new xt("gateway tls fingerprint unavailable"));return}let y=()=>{if(p.destroyed)return;let S=ie(f.getPeerCertificate()?.fingerprint256),v=S?i(S):"";if(!v||v!==i(n)){p.destroy(new xt(v?"gateway tls fingerprint mismatch":"gateway tls fingerprint unavailable"));return}for(let[w,R]of l)if(R!==void 0)p.setHeader(w,R);p.end()};if(f.secureConnecting)f.once("secureConnect",y),p.once("close",()=>f.off("secureConnect",y));else y()})}}var Se=Fn(import.meta.url),Ye=_e.dirname(Se.resolve("ws/package.json")),Ht=Se(_e.join(Ye,"lib/websocket.js"));Se(_e.join(Ye,"lib/websocket-server.js"));Se(_e.join(Ye,"lib/stream.js"));var Or={loadOrCreateDeviceIdentity:()=>{return},signDevicePayload:()=>{throw Error("GatewayClient device signature dependency is not configured")},publicKeyRawBase64UrlFromPem:()=>{throw Error("GatewayClient public key dependency is not configured")},loadDeviceAuthToken:()=>null,storeDeviceAuthToken:()=>{},clearDeviceAuthToken:()=>{},beforeConnect:()=>{},registerGatewayLoopbackBypass:()=>{return},logDebug:()=>{},logError:()=>{},redactForLog:(t)=>t,normalizeTlsFingerprint:ie};function Nr(t){return Object.fromEntries(Object.entries(Or).map(([n,i])=>[n,t?.[n]??i]))}var br="ws://127.0.0.1:18789",Pr="0.0.0",qt=class extends Y{},kr=250,Dr=1000,Ur=1,Yt=class{constructor(t){this.ws=null,this.stopped=!1,this.useLegacyNodeProtocolEnvelope=!1,this.nodeProtocolTransitionPending=!1,this.pendingDeviceTokenRetry=!1,this.deviceTokenRetryBudgetUsed=!1,this.approvalRuntimeTokenCompatibilityDisabled=!1,this.approvalRuntimeTokenRetryBudgetUsed=!1,this.lastTick=null,this.tickIntervalMs=30000,this.tickTimer=null,this.pendingStop=null,this.transportValidated=!1,this.suppressedTransientPreHelloCleanCloses=0,this.deps=Nr(t.hostDeps),this.deviceAuth=new ur(this.deps),this.opts={...t,deviceIdentity:t.deviceIdentity===null?void 0:t.deviceIdentity??this.deps.loadOrCreateDeviceIdentity()},this.requestTimeoutMs=typeof t.requestTimeoutMs==="number"&&Number.isFinite(t.requestTimeoutMs)?t.requestTimeoutMs:Ce;let n=ot(this.opts.connectChallengeTimeoutMs,{env:this.opts.env,configuredTimeoutMs:this.opts.preauthHandshakeTimeoutMs});this.protocol=new Rt({createSocket:(i)=>this.createSocket(i),createRequestId:Gn,createRequestError:(i)=>new B(i),createRequestTimeoutError:(i,a,l)=>new Er({method:i,timeoutMs:a,requestSent:l}),createRequestAbortError:(i)=>Ie(`gateway request aborted for ${i}`),buildConnectPlan:({nonce:i,challengeTs:a,serverCapabilities:l,generation:p,...f})=>{if(!i)throw Error("gateway connect challenge missing nonce");if(this.opts.deviceIdentity&&a==null)throw Error("gateway connect challenge timestamp invalid");let y=this.opts.role??"operator",S=(w)=>{f.assertCurrent();let R=a??Date.now(),_=yt({token:this.opts.token,bootstrapToken:this.opts.bootstrapToken,preferBootstrapToken:this.opts.preferBootstrapToken,deviceToken:this.opts.deviceToken,password:this.opts.password,approvalRuntimeToken:this.approvalRuntimeTokenCompatibilityDisabled?void 0:this.opts.approvalRuntimeToken,agentRuntimeIdentityToken:this.opts.agentRuntimeIdentityToken,storedToken:w?.token,storedScopes:w?.scopes,pendingDeviceTokenRetry:this.pendingDeviceTokenRetry,trustedDeviceTokenRetry:this.isTrustedDeviceRetryEndpoint()}),{authDeviceToken:c,authApprovalRuntimeToken:d,authAgentRuntimeIdentityToken:E,signatureToken:h,resolvedDeviceToken:A,storedToken:I,storedScopes:M,usingStoredDeviceToken:O}=_;if(this.pendingDeviceTokenRetry&&c)this.pendingDeviceTokenRetry=!1;let b=mt(_),N=It({requestedScopes:this.opts.scopes,usingStoredDeviceToken:O,storedScopes:M,defaultScopes:["operator.admin"]}),x=this.opts.mode??G.BACKEND,J=this.opts.clientName??se.GATEWAY_CLIENT,le=y==="node"&&x===G.NODE&&J===se.NODE_HOST,ue=We(this.opts),H=le&&(this.useLegacyNodeProtocolEnvelope||this.opts.maxProtocol===P&&(this.opts.minProtocol??P)<=P),F=H?P:ue?W:this.opts.minProtocol??(x===G.PROBE?Nt:y==="node"&&x===G.NODE?P:Ot),de=H?P:ue?W:this.opts.maxProtocol??W,{platform:pe,deviceFamily:Xe,modelIdentifier:cn}=hr(this.opts,process.platform,H),Je={minProtocol:F,maxProtocol:de,client:{id:J,displayName:this.opts.clientDisplayName,version:this.opts.clientVersion??Pr,buildId:this.opts.clientBuildId,platform:pe,deviceFamily:Xe,modelIdentifier:cn,mode:x,instanceId:this.opts.instanceId},...Tt({caps:Array.isArray(this.opts.caps)?this.opts.caps:[],modelCatalog:H?void 0:this.opts.modelCatalog,serverCapabilities:l}),commands:Array.isArray(this.opts.commands)?this.opts.commands:void 0,computerUse:H?void 0:this.opts.computerUse,workerRuns:H?void 0:this.opts.workerRuns,permissions:this.opts.permissions&&typeof this.opts.permissions==="object"?this.opts.permissions:void 0,pathEnv:this.opts.pathEnv,auth:b,role:y,scopes:N,device:void 0};if(this.opts.deviceIdentity){let ln=ht({deviceId:this.opts.deviceIdentity.deviceId,clientId:this.opts.clientName??se.GATEWAY_CLIENT,clientMode:x,role:y,scopes:N,signedAtMs:R,token:h??null,nonce:i,platform:pe,deviceFamily:Xe}),un=this.deps.signDevicePayload(this.opts.deviceIdentity.privateKeyPem,ln);Je.device={id:this.opts.deviceIdentity.deviceId,publicKey:this.deps.publicKeyRawBase64UrlFromPem(this.opts.deviceIdentity.publicKeyPem),signature:un,signedAt:R,nonce:i}}let Ze={params:Je,authApprovalRuntimeToken:d,authAgentRuntimeIdentityToken:E,resolvedDeviceToken:A,storedScopes:M,storedToken:I,usingStoredDeviceToken:O};return this.connectionStoredToken={generation:p,token:Ze.storedToken??null},Ze},v=this.opts.deviceIdentity?this.deviceAuth.load({deviceId:this.opts.deviceIdentity.deviceId,role:y,env:this.opts.env,...f}):null;return v instanceof Promise?v.then(S):S(v)},buildConnectParams:(i)=>i.params,onConnectPlanError:(i)=>{this.stopped=!0;let a=mr(i),l=`gateway connect failed: ${L(i)}`;if(this.opts.mode===G.PROBE||Ut(i))this.logDebug(l);else this.logError(l);return{closeCode:1008,closeReason:"connect failed",stop:!0,error:a}},onConnectHello:(i,a)=>{let l=a.plan;a.assertCurrent();let p=this.opts.role??"operator",f=i.auth,y=this.connectionStoredToken,S=()=>{if(f?.deviceToken&&(f.role??p)===p&&y)y.token=f.deviceToken;if(this.opts.preferBootstrapToken)this.opts.token=void 0,this.opts.bootstrapToken=void 0,this.opts.password=void 0,this.opts.preferBootstrapToken=!1},v=void 0;if(f?.deviceToken&&this.opts.deviceIdentity){let R=f.role??p,_=R===p&&f.deviceToken===l.storedToken?l.storedScopes??f.scopes??[]:f.scopes??[];if(R===p&&y)y.receiptToken=f.deviceToken;if(v=this.deviceAuth.store({deviceId:this.opts.deviceIdentity.deviceId,role:R,token:f.deviceToken,scopes:_,env:this.opts.env,...R===p?{expectedToken:l.storedToken??null}:{}},S,(c)=>{l.persistenceFailed=!0;let d=this.notifyConnectError(c);return this.logError(`gateway device token persistence failed: ${L(c)}`),d}),y&&v instanceof Promise)y.persistence=v}else S();let w=()=>{if(a.signal.aborted||!this.protocol.connected)return;a.assertCurrent();let R=this.useLegacyNodeProtocolEnvelope&&We(this.opts)&&i.protocol>P;if(R)this.useLegacyNodeProtocolEnvelope=!1;if(this.nodeProtocolTransitionPending=!1,this.pendingDeviceTokenRetry=!1,this.deviceTokenRetryBudgetUsed=!1,this.suppressedTransientPreHelloCleanCloses=0,this.tickIntervalMs=typeof i.policy?.tickIntervalMs==="number"?i.policy.tickIntervalMs:30000,R){this.protocol.resetReconnectBackoff(250),this.protocol.closeSocket(1012,"gateway protocol upgraded");return}this.lastTick=Date.now(),this.startTickWatch()};return v instanceof Promise?v.then(w):w()},onHello:(i)=>{this.opts.onHelloOk?.(i)},onConnectFailure:(i,a)=>{let l=a.plan;if(l.persistenceFailed)return{closeCode:1008,closeReason:"connect failed"};let p=i instanceof B?q(i.details):null,f=this.opts.deviceIdentity&&l.usingStoredDeviceToken&&p===C.AUTH_DEVICE_TOKEN_MISMATCH?this.clearDeviceToken(this.opts.deviceIdentity.deviceId,{token:l.storedToken}):void 0,y=this.resolveConnectRequestFailure(i,l);return f instanceof Promise?f.then(()=>y):y},resolveClose:(i)=>this.resolveClose(i),onClose:(i,a)=>{if(clearInterval(this.tickTimer??void 0),this.tickTimer=null,a.notify)this.opts.onClose?.(i.code,i.reason,this.closeInfo(i))},notifyStoppedClose:!0,onConnectError:(i)=>this.notifyConnectError(i),onReconnectStopped:(i)=>this.notifyReconnectPaused({code:1008,reason:i.message,detailCode:null}),onParseError:(i)=>this.logDebug(`gateway client parse error: ${L(i)}`),onEvent:(i)=>this.opts.onEvent?.(i),onGap:(i)=>this.opts.onGap?.(i),onRequestTiming:(i)=>this.opts.onRequestTiming?.(i),onActivity:()=>{this.lastTick=Date.now()},onCallbackError:(i,a)=>this.logDebug(`gateway client ${i==="hello"?"hello-ok":i==="gap"?"event":i} handler error: ${L(a)}`),handshake:{mode:"require-challenge",timeoutMs:n,timeoutMessage:(i)=>`gateway connect challenge timeout (waited ${i}ms, limit ${n}ms)`},reconnect:{initialMs:1000,multiplier:2,maxMs:30000},requestTimeoutMs:this.requestTimeoutMs,shouldRetrySocketFactoryError:(i)=>!(i instanceof Y)&&!(i instanceof SyntaxError)&&!(i instanceof TypeError)&&!(i instanceof RangeError),rethrowSocketFactoryError:(i)=>i instanceof qt})}get connected(){return!this.stopped&&this.protocol.connected}getConnectionMetadata(){return{clientName:this.opts.clientName,hasDeviceIdentity:Boolean(this.opts.deviceIdentity),mode:this.opts.mode,preauthHandshakeTimeoutMs:this.opts.preauthHandshakeTimeoutMs}}updateNodeManifest(t){if(this.opts={...this.opts,caps:[...t.caps],commands:[...t.commands],computerUse:t.computerUse===void 0?void 0:structuredClone(t.computerUse),workerRuns:t.workerRuns?structuredClone(t.workerRuns):void 0},!this.stopped)this.protocol.closeSocket(1012,"node manifest changed")}start(){if(this.stopped)return;this.protocol.start()}createSocket(t){let n=this.opts.url??br,i=this.opts.edgeAuthHeaders,a=i&&Object.keys(i).length>0?i:void 0;if(a&&new URL(n).protocol!=="wss:")throw new Y("edge auth headers require a wss:// Gateway URL");let l=Oe({env:this.opts.env,configuredTimeoutMs:this.opts.preauthHandshakeTimeoutMs}),p=Cr({url:n,tlsFingerprint:this.opts.tlsFingerprint,tlsServerName:this.opts.tlsServerName,env:this.opts.env,normalizeTlsFingerprint:this.deps.normalizeTlsFingerprint,options:{maxPayload:26214400,handshakeTimeout:l,...this.opts.origin?{origin:this.opts.origin}:{},...a?{followRedirects:!1,headers:a}:{}}});this.deps.beforeConnect();let f,y;try{try{y=this.deps.registerGatewayLoopbackBypass(n),this.opts.assertConnectionCurrent?.()}catch(v){throw new qt(v instanceof Error?v.message:String(v))}f=new Ht(n,p.options),f.binaryType="nodebuffer"}finally{y?.()}this.ws=f,this.transportValidated=!1;let S;return f.on("open",()=>{this.transportValidated=!0,t.open()}),f.on("message",(v)=>t.message(Ct(v))),f.on("close",(v,w)=>{let R=w.toString();if(this.ws===f)this.ws=null;this.resolvePendingStop(f),t.close(v,R)}),f.on("unexpected-response",(v,w)=>{fr(w).then((R)=>{let _=w.statusCode,c=Kn(R)?.error,d=qe(c)?c:void 0,E=w.headers.location,h=E?rr(Array.isArray(E)?E[0]??"":E):void 0;S=new B({code:"UNAVAILABLE",message:`gateway rejected websocket upgrade (HTTP ${_??"unknown"})${R?`: ${R}`:""}`,retryable:!0,details:{reason:"websocket-upgrade-rejected",..._===void 0?{}:{httpStatus:_},...h?{location:h}:{},...typeof d?.type==="string"?{gatewayErrorType:d.type,...typeof d.message==="string"?{gatewayErrorMessage:d.message}:{}}:{}}}),t.error(S),v.destroy(),f.close()})}),f.on("error",(v)=>{if(S)return;if(v.message==="Opening handshake has timed out")Object.assign(v,{code:"ETIMEDOUT"});this.logDebug(`gateway client error: ${L(v)}`),t.error(v instanceof Error?v:Error(String(v)))}),{isOpen:()=>f.readyState===Ht.OPEN,send:(v)=>{this.opts.assertConnectionCurrent?.(),f.send(v)},close:(v,w)=>f.close(v,w)}}stop(){this.beginStop()}async stopAndWait(t){let n=this.beginStop(),i=t?.timeoutMs===void 0?Dr:D(t.timeoutMs);try{await _t(Promise.resolve(n),i,()=>{throw Error(`gateway client stop timed out after ${i}ms`)},{ref:!1})}finally{await this.deviceAuth.drain()}}beginStop(){if(this.stopped=!0,this.pendingDeviceTokenRetry=!1,this.deviceTokenRetryBudgetUsed=!1,clearInterval(this.tickTimer??void 0),this.tickTimer=null,this.pendingStop)return this.pendingStop.promise;let t=this.ws;if(this.ws=null,t){let n=()=>{},i={ws:t,promise:new Promise((l)=>{n=l}),resolve:n};this.pendingStop=i;let a=setTimeout(()=>{try{t.terminate()}finally{this.resolvePendingStop(t)}},kr);if(a.unref?.(),i.terminateTimer=a,this.protocol.connecting){let l=Error("gateway client stopped");this.notifyConnectError(l),this.logDebug(`gateway connect failed: ${L(l)}`)}return this.protocol.stop(),i.promise}return this.protocol.stop(),null}resolvePendingStop(t){if(this.pendingStop?.ws!==t)return;let{resolve:n,terminateTimer:i}=this.pendingStop;if(i)clearTimeout(i);this.pendingStop=null,n()}logDebug(t){this.deps.logDebug(this.deps.redactForLog(t))}logError(t){this.deps.logError(this.deps.redactForLog(t))}shouldRetryWithAlternateNodeProtocol(t){if(!We(this.opts)||!(t instanceof B))return!1;let n=q(t.details);return t.details?.expectedProtocol===(this.useLegacyNodeProtocolEnvelope?W:P)&&(n===C.PROTOCOL_MISMATCH||j(t.message).includes("protocol mismatch"))}resolveConnectRequestFailure(t,n){if(this.shouldRetryWithAlternateNodeProtocol(t)){let p=!this.nodeProtocolTransitionPending;if(this.useLegacyNodeProtocolEnvelope=!this.useLegacyNodeProtocolEnvelope,this.nodeProtocolTransitionPending=!0,p)this.protocol.resetReconnectBackoff(250);return this.logDebug(this.useLegacyNodeProtocolEnvelope?`gateway rejected protocol v${W}; retrying node host with protocol v${P}`:`gateway rejected protocol v${P}; retrying node host with protocol v${W}`),{closeCode:1008,closeReason:"connect retry"}}this.nodeProtocolTransitionPending=!1;let i=t instanceof B?q(t.details):null;if(gt({retryBudgetUsed:this.deviceTokenRetryBudgetUsed,currentDeviceToken:n.resolvedDeviceToken,explicitToken:this.opts.token?.trim()||void 0,storedToken:n.storedToken,trustedEndpoint:this.isTrustedDeviceRetryEndpoint(),errorDetails:t instanceof B?t.details:void 0}))this.pendingDeviceTokenRetry=!0,this.deviceTokenRetryBudgetUsed=!0,this.protocol.resetReconnectBackoff(250);let a=ft(t);if(a!==null)return this.logDebug(`gateway connect failed: ${L(t)}`),{closeCode:1013,closeReason:"gateway starting",reconnectDelayMs:a};if(n.authAgentRuntimeIdentityToken&&this.isUnsupportedConnectAuthField(t,"agentruntimeidentitytoken")){let p=Error("gateway rejected required agent runtime identity auth field; refusing to retry without it");return this.stopped=!0,this.notifyConnectError(p),this.logError(`gateway connect failed: ${p.message}`),{closeCode:1008,closeReason:"connect failed",stop:!0}}if(!this.approvalRuntimeTokenRetryBudgetUsed&&n.authApprovalRuntimeToken&&this.isUnsupportedConnectAuthField(t,"approvalruntimetoken"))return this.approvalRuntimeTokenCompatibilityDisabled=!0,this.approvalRuntimeTokenRetryBudgetUsed=!0,this.protocol.resetReconnectBackoff(250),this.logDebug("gateway rejected approval runtime auth field; retrying without it"),{closeCode:1008,closeReason:"connect retry"};this.notifyConnectError(t);let l=`gateway connect failed: ${L(t)}`;if(this.opts.mode===G.PROBE||Ut(t)||i===C.AUTH_RATE_LIMITED)this.logDebug(l);else this.logError(l);return{closeCode:1008,closeReason:"connect failed"}}resolveClose(t){let n=this.closeInfo(t),i=t.connectFailure?.error instanceof B?q(t.connectFailure.error.details):null,a=t.connectFailure?.error instanceof B?t.connectFailure.error.details:void 0;if(t.code===1013&&t.connectFailure?.reconnectDelayMs!==void 0)return{retry:!0,notify:this.opts.notifyOnStartupRetry===!0,reconnectDelayMs:t.connectFailure.reconnectDelayMs};if(n.transientPreHelloCleanClose&&this.suppressedTransientPreHelloCleanCloses<Ur)return this.suppressedTransientPreHelloCleanCloses+=1,{retry:!0,notify:!0,pendingError:Error("gateway transient pre-hello clean close")};if(n.transientPreHelloCleanClose||t.connectRequestSent&&!t.helloReceived&&!t.connectFailure){let l=Error(`gateway closed (${t.code}): ${t.reason}`);this.notifyConnectError(l),this.logError(`gateway connect failed: ${L(l)}`)}if(this.clearStaleDeviceTokenForClose(t),vt({details:a,deviceTokenRetryPending:this.pendingDeviceTokenRetry,tokenMismatchIsTerminal:!0,protocolMismatchIsTerminal:!this.nodeProtocolTransitionPending,clientVersionMismatchIsTerminal:!0}))return this.notifyReconnectPaused({code:t.code,reason:t.reason,detailCode:i}),{retry:!1,notify:!0};return{retry:!0,notify:!0,reconnectDelayMs:t.connectFailure?.reconnectDelayMs}}closeInfo(t){return{phase:t.helloReceived?"post-hello":"pre-hello",socketOpened:t.socketOpened,transportValidated:this.transportValidated,connectRequestSent:t.connectRequestSent,transientPreHelloCleanClose:!t.helloReceived&&t.code===1000&&t.reason==="",...t.connectFailure?.error?{connectError:t.connectFailure.error}:{}}}clearStaleDeviceTokenForClose(t){let{code:n,reason:i,generation:a}=t;if(n!==1008||!j(i).includes("device token mismatch")||!this.opts.deviceIdentity)return;let l=this.connectionStoredToken?.generation===a?this.connectionStoredToken:{token:void 0};this.clearDeviceToken(this.opts.deviceIdentity.deviceId,l,()=>!this.opts.token&&!this.opts.password)}clearDeviceToken(t,n,i=()=>!0){let a=(p)=>{this.logDebug(`failed clearing stale device-auth token for device ${t}: ${String(p)}`)},l=()=>this.logDebug(`cleared stale device-auth token for device ${t}`);try{let p=this.deviceAuth.clear({deviceId:t,role:this.opts.role??"operator",env:this.opts.env,assertCurrent:()=>{if(this.stopped)throw Error("gateway client stopped")}},n,i);return p instanceof Promise?p.then(l,a):l()}catch(p){a(p)}}notifyConnectError(t){if(!this.opts.onConnectError)return!1;try{return this.opts.onConnectError(t),!0}catch(n){return this.logDebug(`gateway client connect error handler error: ${L(n)}`),!1}}notifyReconnectPaused(t){try{this.opts.onReconnectPaused?.(t)}catch(n){this.logDebug(`gateway client reconnect paused handler error: ${L(n)}`)}}isUnsupportedConnectAuthField(t,n){if(!(t instanceof B)||t.gatewayCode!=="INVALID_REQUEST")return!1;let i=j(t.message);return i.includes("invalid connect params")&&i.includes(n)}isTrustedDeviceRetryEndpoint(){let t=this.opts.url??"ws://127.0.0.1:18789";try{let n=new URL(t),i=n.protocol==="https:"?"wss:":n.protocol==="http:"?"ws:":n.protocol;if(Sr(n.hostname))return!0;return i==="wss:"&&Boolean(this.opts.tlsFingerprint?.trim())}catch{return!1}}startTickWatch(){clearInterval(this.tickTimer??void 0);let t=this.opts.tickWatchMinIntervalMs,n=typeof t==="number"&&Number.isFinite(t)?Math.max(1,Math.min(30000,t)):1000,i=D(Math.max(this.tickIntervalMs,n));this.tickTimer=setInterval(()=>{if(this.stopped)return;if(!this.lastTick)return;if(this.protocol.hasPendingRequests&&!this.protocol.hasUnboundedPendingRequests)return;let a=Date.now()-this.lastTick,l=this.opts.tickWatchTimeoutMs;if(a>(typeof l==="number"&&Number.isFinite(l)?Math.max(1,l):this.tickIntervalMs*2))this.protocol.closeSocket(4000,"tick timeout")},i)}async request(t,n,i){let a=i?.expectFinal===!0,l=i?.timeoutMs===null?null:typeof i?.timeoutMs==="number"&&Number.isFinite(i.timeoutMs)?i.timeoutMs:a?null:this.requestTimeoutMs;return this.protocol.request(t,n,{...i,expectFinal:a,timeoutMs:l})}};var on=g(sn(),1);import{createHash as Xt,createPrivateKey as Lr,createPublicKey as Jt,generateKeyPairSync as xr,sign as Zt,verify as Hr}from"crypto";import{existsSync as ae,linkSync as qr,mkdirSync as en,readFileSync as tn,renameSync as Fr,unlinkSync as nn,writeFileSync as rn}from"fs";import{homedir as Gr}from"os";import{join as ce,resolve as Wr}from"path";var $r=s({version:o(1),deviceId:r(),publicKeyPem:r(),privateKeyPem:r()}),Br=s({version:o(1),deviceId:r(),tokens:T(r(),s({token:r(),role:r(),scopes:u(r()),updatedAtMs:m()}))});function Qe(t){let n=Jt(t);if(n.asymmetricKeyType!=="ed25519")throw Error("Expected an Ed25519 device key");return Buffer.from(n.export({format:"jwk"}).x,"base64url")}function Qt(t){let n=JSON.parse(tn(t,"utf8")),i=s({deviceId:r(),publicKey:r(),privateKey:r()}).safeParse(n),a=i.success?{deviceId:i.data.deviceId,publicKeyPem:Jt({key:{kty:"OKP",crv:"Ed25519",x:i.data.publicKey},format:"jwk"}).export({type:"spki",format:"pem"}).toString(),privateKeyPem:Lr({key:{kty:"OKP",crv:"Ed25519",x:i.data.publicKey,d:i.data.privateKey},format:"jwk"}).export({type:"pkcs8",format:"pem"}).toString()}:$r.parse(n),l=Buffer.from("openclaw-device-identity-self-check");if(!Hr(null,l,a.publicKeyPem,Zt(null,l,a.privateKeyPem)))throw Error("OpenClaw device keys do not match");return{...a,deviceId:Xt("sha256").update(Qe(a.publicKeyPem)).digest("hex")}}function Vr(t){let n=ce(t,"device.json");if(ae(n))return Qt(n);en(t,{recursive:!0,mode:448});let{publicKey:i,privateKey:a}=xr("ed25519"),l=i.export({type:"spki",format:"pem"}).toString(),p={version:1,deviceId:Xt("sha256").update(Qe(l)).digest("hex"),publicKeyPem:l,privateKeyPem:a.export({type:"pkcs8",format:"pem"}).toString(),createdAtMs:Date.now()},f=`${n}.${crypto.randomUUID()}.tmp`;rn(f,JSON.stringify(p),{mode:384,flag:"wx"});try{qr(f,n)}catch(y){if(y.code!=="EEXIST")throw y}finally{nn(f)}return Qt(n)}function an(t=process.env){let n=t.HOME?.trim()||t.USERPROFILE?.trim()||Gr(),i=(R,_)=>Wr(R.replace(/^~(?=$|[\\/])/,_)),a=i(t.OPENCLAW_HOME?.trim()||n,n),l=t.OPENCLAW_STATE_DIR?.trim(),p=ce(a,".openclaw"),f=ce(a,".clawdbot"),y=ce(l?i(l,a):!ae(p)&&ae(f)?f:p,"identity"),S=ce(y,"device-auth.json");function v(R){if(!ae(S))return{version:1,deviceId:R,tokens:{}};let _=Br.parse(JSON.parse(tn(S,"utf8")));return _.deviceId===R?_:{version:1,deviceId:R,tokens:{}}}async function w(R,_){let c=()=>{R.signal?.throwIfAborted(),R.assertCurrent?.()};c(),en(y,{recursive:!0,mode:448});let d,E=await on.lock(S,{realpath:!1,retries:{retries:20,minTimeout:10,maxTimeout:100},onCompromised:(h)=>{d=h}});try{if(c(),d)throw d;let h=v(R.deviceId),A=h.tokens[R.role]?.token;if(R.expectedToken!==void 0&&(A??null)!==R.expectedToken)return;_(h.tokens);let I=`${S}.${crypto.randomUUID()}.tmp`;try{rn(I,JSON.stringify(h),{mode:384,flag:"wx"}),c(),Fr(I,S)}finally{if(ae(I))nn(I)}}finally{if(!d)await E()}}return{loadOrCreateDeviceIdentity:()=>Vr(y),signDevicePayload:(R,_)=>Zt(null,Buffer.from(_),R).toString("base64url"),publicKeyRawBase64UrlFromPem:(R)=>Qe(R).toString("base64url"),loadDeviceAuthToken:(R)=>(R.signal?.throwIfAborted(),R.assertCurrent?.(),v(R.deviceId).tokens[R.role]??null),storeDeviceAuthToken:(R)=>w(R,(_)=>{_[R.role]={token:R.token,role:R.role,scopes:R.scopes,updatedAtMs:Date.now()}}),clearDeviceAuthToken:(R)=>w(R,(_)=>{delete _[R.role]})}}class Kr extends Yt{constructor(t){super({clientVersion:Lt.devDependencies["@openclaw/gateway-client"],...t,hostDeps:{...an(t.env),...t.hostDeps}})}}export{Kr as GatewayClient};
@@ -1 +0,0 @@
1
- import{li}from"/chunk-9vy2z8hd.js";export{li as sanitizeSvg};