@clinebot/core 0.0.2 → 0.0.3

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.
@@ -1,693 +0,0 @@
1
- import{createRequire as UD}from"node:module";var $D=Object.create;var{getPrototypeOf:qD,defineProperty:rJ,getOwnPropertyNames:YD}=Object;var TD=Object.prototype.hasOwnProperty;function XD($){return this[$]}var JD,QD,Aq=($,q,Y)=>{var T=$!=null&&typeof $==="object";if(T){var X=q?JD??=new WeakMap:QD??=new WeakMap,J=X.get($);if(J)return J}Y=$!=null?$D(qD($)):{};let Q=q||!$||!$.__esModule?rJ(Y,"default",{value:$,enumerable:!0}):Y;for(let U of YD($))if(!TD.call(Q,U))rJ(Q,U,{get:XD.bind($,U),enumerable:!0});if(T)X.set($,Q);return Q};var B=($,q)=>()=>(q||$((q={exports:{}}).exports,q),q.exports);var e=UD(import.meta.url);var n=B((YQ)=>{Object.defineProperty(YQ,"__esModule",{value:!0});YQ.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH=YQ.DEFAULT_MAX_SEND_MESSAGE_LENGTH=YQ.Propagate=YQ.LogVerbosity=YQ.Status=void 0;var eJ;(function($){$[$.OK=0]="OK",$[$.CANCELLED=1]="CANCELLED",$[$.UNKNOWN=2]="UNKNOWN",$[$.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",$[$.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",$[$.NOT_FOUND=5]="NOT_FOUND",$[$.ALREADY_EXISTS=6]="ALREADY_EXISTS",$[$.PERMISSION_DENIED=7]="PERMISSION_DENIED",$[$.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",$[$.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",$[$.ABORTED=10]="ABORTED",$[$.OUT_OF_RANGE=11]="OUT_OF_RANGE",$[$.UNIMPLEMENTED=12]="UNIMPLEMENTED",$[$.INTERNAL=13]="INTERNAL",$[$.UNAVAILABLE=14]="UNAVAILABLE",$[$.DATA_LOSS=15]="DATA_LOSS",$[$.UNAUTHENTICATED=16]="UNAUTHENTICATED"})(eJ||(YQ.Status=eJ={}));var $Q;(function($){$[$.DEBUG=0]="DEBUG",$[$.INFO=1]="INFO",$[$.ERROR=2]="ERROR",$[$.NONE=3]="NONE"})($Q||(YQ.LogVerbosity=$Q={}));var qQ;(function($){$[$.DEADLINE=1]="DEADLINE",$[$.CENSUS_STATS_CONTEXT=2]="CENSUS_STATS_CONTEXT",$[$.CENSUS_TRACING_CONTEXT=4]="CENSUS_TRACING_CONTEXT",$[$.CANCELLATION=8]="CANCELLATION",$[$.DEFAULTS=65535]="DEFAULTS"})(qQ||(YQ.Propagate=qQ={}));YQ.DEFAULT_MAX_SEND_MESSAGE_LENGTH=-1;YQ.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH=4194304});var z9=B(($v,ND)=>{ND.exports={name:"@grpc/grpc-js",version:"1.14.3",description:"gRPC Library for Node - pure JS implementation",homepage:"https://grpc.io/",repository:"https://github.com/grpc/grpc-node/tree/master/packages/grpc-js",main:"build/src/index.js",engines:{node:">=12.10.0"},keywords:[],author:{name:"Google Inc."},types:"build/src/index.d.ts",license:"Apache-2.0",devDependencies:{"@grpc/proto-loader":"file:../proto-loader","@types/gulp":"^4.0.17","@types/gulp-mocha":"0.0.37","@types/lodash":"^4.14.202","@types/mocha":"^10.0.6","@types/ncp":"^2.0.8","@types/node":">=20.11.20","@types/pify":"^5.0.4","@types/semver":"^7.5.8","@typescript-eslint/eslint-plugin":"^7.1.0","@typescript-eslint/parser":"^7.1.0","@typescript-eslint/typescript-estree":"^7.1.0","clang-format":"^1.8.0",eslint:"^8.42.0","eslint-config-prettier":"^8.8.0","eslint-plugin-node":"^11.1.0","eslint-plugin-prettier":"^4.2.1",execa:"^2.0.3",gulp:"^4.0.2","gulp-mocha":"^6.0.0",lodash:"^4.17.21",madge:"^5.0.1","mocha-jenkins-reporter":"^0.4.1",ncp:"^2.0.0",pify:"^4.0.1",prettier:"^2.8.8",rimraf:"^3.0.2",semver:"^7.6.0","ts-node":"^10.9.2",typescript:"^5.3.3"},contributors:[{name:"Google Inc."}],scripts:{build:"npm run compile",clean:"rimraf ./build",compile:"tsc -p .",format:'clang-format -i -style="{Language: JavaScript, BasedOnStyle: Google, ColumnLimit: 80}" src/*.ts test/*.ts',lint:"eslint src/*.ts test/*.ts",prepare:"npm run copy-protos && npm run generate-types && npm run generate-test-types && npm run compile",test:"gulp test",check:"npm run lint",fix:"eslint --fix src/*.ts test/*.ts",pretest:"npm run generate-types && npm run generate-test-types && npm run compile",posttest:"npm run check && madge -c ./build/src","generate-types":"proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --includeDirs proto/ --include-dirs proto/ proto/xds/ proto/protoc-gen-validate/ -O src/generated/ --grpcLib ../index channelz.proto xds/service/orca/v3/orca.proto","generate-test-types":"proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --include-dirs test/fixtures/ -O test/generated/ --grpcLib ../../src/index test_service.proto echo_service.proto","copy-protos":"node ./copy-protos"},dependencies:{"@grpc/proto-loader":"^0.8.0","@js-sdsl/ordered-map":"^4.4.2"},files:["src/**/*.ts","build/src/**/*.{js,d.ts,js.map}","proto/**/*.proto","proto/**/LICENSE","LICENSE","deps/envoy-api/envoy/api/v2/**/*.proto","deps/envoy-api/envoy/config/**/*.proto","deps/envoy-api/envoy/service/**/*.proto","deps/envoy-api/envoy/type/**/*.proto","deps/udpa/udpa/**/*.proto","deps/googleapis/google/api/*.proto","deps/googleapis/google/rpc/*.proto","deps/protoc-gen-validate/validate/**/*.proto"]}});var Z0=B((QQ)=>{var M9,B9,R9,P9;Object.defineProperty(QQ,"__esModule",{value:!0});QQ.log=QQ.setLoggerVerbosity=QQ.setLogger=QQ.getLogger=void 0;QQ.trace=CD;QQ.isTracerEnabled=JQ;var G$=n(),HD=e("process"),zD=z9().version,MD={error:($,...q)=>{console.error("E "+$,...q)},info:($,...q)=>{console.error("I "+$,...q)},debug:($,...q)=>{console.error("D "+$,...q)}},_$=MD,Wq=G$.LogVerbosity.ERROR,BD=(B9=(M9=process.env.GRPC_NODE_VERBOSITY)!==null&&M9!==void 0?M9:process.env.GRPC_VERBOSITY)!==null&&B9!==void 0?B9:"";switch(BD.toUpperCase()){case"DEBUG":Wq=G$.LogVerbosity.DEBUG;break;case"INFO":Wq=G$.LogVerbosity.INFO;break;case"ERROR":Wq=G$.LogVerbosity.ERROR;break;case"NONE":Wq=G$.LogVerbosity.NONE;break;default:}var RD=()=>{return _$};QQ.getLogger=RD;var PD=($)=>{_$=$};QQ.setLogger=PD;var OD=($)=>{Wq=$};QQ.setLoggerVerbosity=OD;var LD=($,...q)=>{let Y;if($>=Wq){switch($){case G$.LogVerbosity.DEBUG:Y=_$.debug;break;case G$.LogVerbosity.INFO:Y=_$.info;break;case G$.LogVerbosity.ERROR:Y=_$.error;break}if(!Y)Y=_$.error;if(Y)Y.bind(_$)(...q)}};QQ.log=LD;var wD=(P9=(R9=process.env.GRPC_NODE_TRACE)!==null&&R9!==void 0?R9:process.env.GRPC_TRACE)!==null&&P9!==void 0?P9:"",O9=new Set,XQ=new Set;for(let $ of wD.split(","))if($.startsWith("-"))XQ.add($.substring(1));else O9.add($);var SD=O9.has("all");function CD($,q,Y){if(JQ(q))QQ.log($,new Date().toISOString()+" | v"+zD+" "+HD.pid+" | "+q+" | "+Y)}function JQ($){return!XQ.has($)&&(SD||O9.has($))}});var k6=B((UQ)=>{Object.defineProperty(UQ,"__esModule",{value:!0});UQ.getErrorMessage=hD;UQ.getErrorCode=_D;function hD($){if($ instanceof Error)return $.message;else return String($)}function _D($){if(typeof $==="object"&&$!==null&&"code"in $&&typeof $.code==="number")return $.code;else return null}});var P0=B((AQ)=>{Object.defineProperty(AQ,"__esModule",{value:!0});AQ.Metadata=void 0;var fD=Z0(),bD=n(),uD=k6(),dD=/^[:0-9a-z_.-]+$/,cD=/^[ -~]*$/;function pD($){return dD.test($)}function lD($){return cD.test($)}function KQ($){return $.endsWith("-bin")}function nD($){return!$.startsWith("grpc-")}function h6($){return $.toLowerCase()}function ZQ($,q){if(!pD($))throw Error('Metadata key "'+$+'" contains illegal characters');if(q!==null&&q!==void 0)if(KQ($)){if(!Buffer.isBuffer(q))throw Error("keys that end with '-bin' must have Buffer values")}else{if(Buffer.isBuffer(q))throw Error("keys that don't end with '-bin' must have String values");if(!lD(q))throw Error('Metadata string value "'+q+'" contains illegal characters')}}class _6{constructor($={}){this.internalRepr=new Map,this.opaqueData=new Map,this.options=$}set($,q){$=h6($),ZQ($,q),this.internalRepr.set($,[q])}add($,q){$=h6($),ZQ($,q);let Y=this.internalRepr.get($);if(Y===void 0)this.internalRepr.set($,[q]);else Y.push(q)}remove($){$=h6($),this.internalRepr.delete($)}get($){return $=h6($),this.internalRepr.get($)||[]}getMap(){let $={};for(let[q,Y]of this.internalRepr)if(Y.length>0){let T=Y[0];$[q]=Buffer.isBuffer(T)?Buffer.from(T):T}return $}clone(){let $=new _6(this.options),q=$.internalRepr;for(let[Y,T]of this.internalRepr){let X=T.map((J)=>{if(Buffer.isBuffer(J))return Buffer.from(J);else return J});q.set(Y,X)}return $}merge($){for(let[q,Y]of $.internalRepr){let T=(this.internalRepr.get(q)||[]).concat(Y);this.internalRepr.set(q,T)}}setOptions($){this.options=$}getOptions(){return this.options}toHttp2Headers(){let $={};for(let[q,Y]of this.internalRepr){if(q.startsWith(":"))continue;$[q]=Y.map(iD)}return $}toJSON(){let $={};for(let[q,Y]of this.internalRepr)$[q]=Y;return $}setOpaque($,q){this.opaqueData.set($,q)}getOpaque($){return this.opaqueData.get($)}static fromHttp2Headers($){let q=new _6;for(let Y of Object.keys($)){if(Y.charAt(0)===":")continue;let T=$[Y];try{if(KQ(Y)){if(Array.isArray(T))T.forEach((X)=>{q.add(Y,Buffer.from(X,"base64"))});else if(T!==void 0)if(nD(Y))T.split(",").forEach((X)=>{q.add(Y,Buffer.from(X.trim(),"base64"))});else q.add(Y,Buffer.from(T,"base64"))}else if(Array.isArray(T))T.forEach((X)=>{q.add(Y,X)});else if(T!==void 0)q.add(Y,T)}catch(X){let J=`Failed to add metadata entry ${Y}: ${T}. ${(0,uD.getErrorMessage)(X)}. For more information see https://github.com/grpc/grpc-node/issues/1173`;(0,fD.log)(bD.LogVerbosity.ERROR,J)}}return q}}AQ.Metadata=_6;var iD=($)=>{return Buffer.isBuffer($)?$.toString("base64"):$}});var m6=B((GQ)=>{Object.defineProperty(GQ,"__esModule",{value:!0});GQ.CallCredentials=void 0;var w9=P0();function rD($){return"getRequestHeaders"in $&&typeof $.getRequestHeaders==="function"}class Gq{static createFromMetadataGenerator($){return new S9($)}static createFromGoogleCredential($){return Gq.createFromMetadataGenerator((q,Y)=>{let T;if(rD($))T=$.getRequestHeaders(q.service_url);else T=new Promise((X,J)=>{$.getRequestMetadata(q.service_url,(Q,U)=>{if(Q){J(Q);return}if(!U){J(Error("Headers not set by metadata plugin"));return}X(U)})});T.then((X)=>{let J=new w9.Metadata;for(let Q of Object.keys(X))J.add(Q,X[Q]);Y(null,J)},(X)=>{Y(X)})})}static createEmpty(){return new C9}}GQ.CallCredentials=Gq;class g6 extends Gq{constructor($){super();this.creds=$}async generateMetadata($){let q=new w9.Metadata,Y=await Promise.all(this.creds.map((T)=>T.generateMetadata($)));for(let T of Y)q.merge(T);return q}compose($){return new g6(this.creds.concat([$]))}_equals($){if(this===$)return!0;if($ instanceof g6)return this.creds.every((q,Y)=>q._equals($.creds[Y]));else return!1}}class S9 extends Gq{constructor($){super();this.metadataGenerator=$}generateMetadata($){return new Promise((q,Y)=>{this.metadataGenerator($,(T,X)=>{if(X!==void 0)q(X);else Y(T)})})}compose($){return new g6([this,$])}_equals($){if(this===$)return!0;if($ instanceof S9)return this.metadataGenerator===$.metadataGenerator;else return!1}}class C9 extends Gq{generateMetadata($){return Promise.resolve(new w9.Metadata)}compose($){return $}_equals($){return $ instanceof C9}}});var j9=B((DQ)=>{Object.defineProperty(DQ,"__esModule",{value:!0});DQ.CIPHER_SUITES=void 0;DQ.getDefaultRootsData=oD;var aD=e("fs");DQ.CIPHER_SUITES=process.env.GRPC_SSL_CIPHER_SUITES;var VQ=process.env.GRPC_DEFAULT_SSL_ROOTS_FILE_PATH,y9=null;function oD(){if(VQ){if(y9===null)y9=aD.readFileSync(VQ);return y9}return null}});var p0=B((NQ)=>{Object.defineProperty(NQ,"__esModule",{value:!0});NQ.parseUri=eD;NQ.splitHostPort=$F;NQ.combineHostPort=qF;NQ.uriToString=YF;var tD=/^(?:([A-Za-z0-9+.-]+):)?(?:\/\/([^/]*)\/)?(.+)$/;function eD($){let q=tD.exec($);if(q===null)return null;return{scheme:q[1],authority:q[2],path:q[3]}}var IQ=/^\d+$/;function $F($){if($.startsWith("[")){let q=$.indexOf("]");if(q===-1)return null;let Y=$.substring(1,q);if(Y.indexOf(":")===-1)return null;if($.length>q+1)if($[q+1]===":"){let T=$.substring(q+2);if(IQ.test(T))return{host:Y,port:+T};else return null}else return null;else return{host:Y}}else{let q=$.split(":");if(q.length===2)if(IQ.test(q[1]))return{host:q[0],port:+q[1]};else return null;else return{host:$}}}function qF($){if($.port===void 0)return $.host;else if($.host.includes(":"))return`[${$.host}]:${$.port}`;else return`${$.host}:${$.port}`}function YF($){let q="";if($.scheme!==void 0)q+=$.scheme+":";if($.authority!==void 0)q+="//"+$.authority+"/";return q+=$.path,q}});var H1=B((HQ)=>{Object.defineProperty(HQ,"__esModule",{value:!0});HQ.CHANNEL_ARGS_CONFIG_SELECTOR_KEY=void 0;HQ.registerResolver=UF;HQ.registerDefaultScheme=ZF;HQ.createResolver=KF;HQ.getDefaultAuthority=AF;HQ.mapUriDefaultScheme=WF;var x9=p0();HQ.CHANNEL_ARGS_CONFIG_SELECTOR_KEY="grpc.internal.config_selector";var Eq={},v9=null;function UF($,q){Eq[$]=q}function ZF($){v9=$}function KF($,q,Y){if($.scheme!==void 0&&$.scheme in Eq)return new Eq[$.scheme]($,q,Y);else throw Error(`No resolver could be created for target ${(0,x9.uriToString)($)}`)}function AF($){if($.scheme!==void 0&&$.scheme in Eq)return Eq[$.scheme].getDefaultAuthority($);else throw Error(`Invalid target ${(0,x9.uriToString)($)}`)}function WF($){if($.scheme===void 0||!($.scheme in Eq))if(v9!==null)return{scheme:v9,authority:void 0,path:(0,x9.uriToString)($)};else return null;return $}});var Dq=B((PQ)=>{Object.defineProperty(PQ,"__esModule",{value:!0});PQ.ChannelCredentials=void 0;PQ.createCertificateProviderChannelCredentials=zF;var AY=e("tls"),u6=m6(),h9=j9(),MQ=p0(),IF=H1(),NF=Z0(),HF=n();function k9($,q){if($&&!($ instanceof Buffer))throw TypeError(`${q}, if provided, must be a Buffer.`)}class Vq{compose($){return new b6(this,$)}static createSsl($,q,Y,T){var X;if(k9($,"Root certificate"),k9(q,"Private key"),k9(Y,"Certificate chain"),q&&!Y)throw Error("Private key must be given with accompanying certificate chain");if(!q&&Y)throw Error("Certificate chain must be given with accompanying private key");let J=(0,AY.createSecureContext)({ca:(X=$!==null&&$!==void 0?$:(0,h9.getDefaultRootsData)())!==null&&X!==void 0?X:void 0,key:q!==null&&q!==void 0?q:void 0,cert:Y!==null&&Y!==void 0?Y:void 0,ciphers:h9.CIPHER_SUITES});return new f6(J,T!==null&&T!==void 0?T:{})}static createFromSecureContext($,q){return new f6($,q!==null&&q!==void 0?q:{})}static createInsecure(){return new _9}}PQ.ChannelCredentials=Vq;class _9 extends Vq{constructor(){super()}compose($){throw Error("Cannot compose insecure credentials")}_isSecure(){return!1}_equals($){return $ instanceof _9}_createSecureConnector($,q,Y){return{connect(T){return Promise.resolve({socket:T,secure:!1})},waitForReady:()=>{return Promise.resolve()},getCallCredentials:()=>{return Y!==null&&Y!==void 0?Y:u6.CallCredentials.createEmpty()},destroy(){}}}}function BQ($,q,Y,T){var X,J;let Q={secureContext:$},U=Y;if("grpc.http_connect_target"in T){let W=(0,MQ.parseUri)(T["grpc.http_connect_target"]);if(W)U=W}let Z=(0,IF.getDefaultAuthority)(U),K=(0,MQ.splitHostPort)(Z),A=(X=K===null||K===void 0?void 0:K.host)!==null&&X!==void 0?X:Z;if(Q.host=A,q.checkServerIdentity)Q.checkServerIdentity=q.checkServerIdentity;if(q.rejectUnauthorized!==void 0)Q.rejectUnauthorized=q.rejectUnauthorized;if(Q.ALPNProtocols=["h2"],T["grpc.ssl_target_name_override"]){let W=T["grpc.ssl_target_name_override"],G=(J=Q.checkServerIdentity)!==null&&J!==void 0?J:AY.checkServerIdentity;Q.checkServerIdentity=(V,F)=>{return G(W,F)},Q.servername=W}else Q.servername=A;if(T["grpc-node.tls_enable_trace"])Q.enableTrace=!0;return Q}class RQ{constructor($,q){this.connectionOptions=$,this.callCredentials=q}connect($){let q=Object.assign({socket:$},this.connectionOptions);return new Promise((Y,T)=>{let X=(0,AY.connect)(q,()=>{var J;if(((J=this.connectionOptions.rejectUnauthorized)!==null&&J!==void 0?J:!0)&&!X.authorized){T(X.authorizationError);return}Y({socket:X,secure:!0})});X.on("error",(J)=>{T(J)})})}waitForReady(){return Promise.resolve()}getCallCredentials(){return this.callCredentials}destroy(){}}class f6 extends Vq{constructor($,q){super();this.secureContext=$,this.verifyOptions=q}_isSecure(){return!0}_equals($){if(this===$)return!0;if($ instanceof f6)return this.secureContext===$.secureContext&&this.verifyOptions.checkServerIdentity===$.verifyOptions.checkServerIdentity;else return!1}_createSecureConnector($,q,Y){let T=BQ(this.secureContext,this.verifyOptions,$,q);return new RQ(T,Y!==null&&Y!==void 0?Y:u6.CallCredentials.createEmpty())}}class KY extends Vq{constructor($,q,Y){super();this.caCertificateProvider=$,this.identityCertificateProvider=q,this.verifyOptions=Y,this.refcount=0,this.latestCaUpdate=void 0,this.latestIdentityUpdate=void 0,this.caCertificateUpdateListener=this.handleCaCertificateUpdate.bind(this),this.identityCertificateUpdateListener=this.handleIdentityCertitificateUpdate.bind(this),this.secureContextWatchers=[]}_isSecure(){return!0}_equals($){var q,Y;if(this===$)return!0;if($ instanceof KY)return this.caCertificateProvider===$.caCertificateProvider&&this.identityCertificateProvider===$.identityCertificateProvider&&((q=this.verifyOptions)===null||q===void 0?void 0:q.checkServerIdentity)===((Y=$.verifyOptions)===null||Y===void 0?void 0:Y.checkServerIdentity);else return!1}ref(){var $;if(this.refcount===0)this.caCertificateProvider.addCaCertificateListener(this.caCertificateUpdateListener),($=this.identityCertificateProvider)===null||$===void 0||$.addIdentityCertificateListener(this.identityCertificateUpdateListener);this.refcount+=1}unref(){var $;if(this.refcount-=1,this.refcount===0)this.caCertificateProvider.removeCaCertificateListener(this.caCertificateUpdateListener),($=this.identityCertificateProvider)===null||$===void 0||$.removeIdentityCertificateListener(this.identityCertificateUpdateListener)}_createSecureConnector($,q,Y){return this.ref(),new KY.SecureConnectorImpl(this,$,q,Y!==null&&Y!==void 0?Y:u6.CallCredentials.createEmpty())}maybeUpdateWatchers(){if(this.hasReceivedUpdates()){for(let $ of this.secureContextWatchers)$(this.getLatestSecureContext());this.secureContextWatchers=[]}}handleCaCertificateUpdate($){this.latestCaUpdate=$,this.maybeUpdateWatchers()}handleIdentityCertitificateUpdate($){this.latestIdentityUpdate=$,this.maybeUpdateWatchers()}hasReceivedUpdates(){if(this.latestCaUpdate===void 0)return!1;if(this.identityCertificateProvider&&this.latestIdentityUpdate===void 0)return!1;return!0}getSecureContext(){if(this.hasReceivedUpdates())return Promise.resolve(this.getLatestSecureContext());else return new Promise(($)=>{this.secureContextWatchers.push($)})}getLatestSecureContext(){var $,q;if(!this.latestCaUpdate)return null;if(this.identityCertificateProvider!==null&&!this.latestIdentityUpdate)return null;try{return(0,AY.createSecureContext)({ca:this.latestCaUpdate.caCertificate,key:($=this.latestIdentityUpdate)===null||$===void 0?void 0:$.privateKey,cert:(q=this.latestIdentityUpdate)===null||q===void 0?void 0:q.certificate,ciphers:h9.CIPHER_SUITES})}catch(Y){return(0,NF.log)(HF.LogVerbosity.ERROR,"Failed to createSecureContext with error "+Y.message),null}}}KY.SecureConnectorImpl=class{constructor($,q,Y,T){this.parent=$,this.channelTarget=q,this.options=Y,this.callCredentials=T}connect($){return new Promise((q,Y)=>{let T=this.parent.getLatestSecureContext();if(!T){Y(Error("Failed to load credentials"));return}if($.closed)Y(Error("Socket closed while loading credentials"));let X=BQ(T,this.parent.verifyOptions,this.channelTarget,this.options),J=Object.assign({socket:$},X),Q=()=>{Y(Error("Socket closed"))},U=(K)=>{Y(K)},Z=(0,AY.connect)(J,()=>{var K;if(Z.removeListener("close",Q),Z.removeListener("error",U),((K=this.parent.verifyOptions.rejectUnauthorized)!==null&&K!==void 0?K:!0)&&!Z.authorized){Y(Z.authorizationError);return}q({socket:Z,secure:!0})});Z.once("close",Q),Z.once("error",U)})}async waitForReady(){await this.parent.getSecureContext()}getCallCredentials(){return this.callCredentials}destroy(){this.parent.unref()}};function zF($,q,Y){return new KY($,q,Y!==null&&Y!==void 0?Y:{})}class b6 extends Vq{constructor($,q){super();if(this.channelCredentials=$,this.callCredentials=q,!$._isSecure())throw Error("Cannot compose insecure credentials")}compose($){let q=this.callCredentials.compose($);return new b6(this.channelCredentials,q)}_isSecure(){return!0}_equals($){if(this===$)return!0;if($ instanceof b6)return this.channelCredentials._equals($.channelCredentials)&&this.callCredentials._equals($.callCredentials);else return!1}_createSecureConnector($,q,Y){let T=this.callCredentials.compose(Y!==null&&Y!==void 0?Y:u6.CallCredentials.createEmpty());return this.channelCredentials._createSecureConnector($,q,T)}}});var V$=B((wQ)=>{Object.defineProperty(wQ,"__esModule",{value:!0});wQ.createChildChannelControlHelper=PF;wQ.registerLoadBalancerType=OF;wQ.registerDefaultLoadBalancerType=LF;wQ.createLoadBalancer=wF;wQ.isLoadBalancerNameRegistered=SF;wQ.parseLoadBalancingConfig=LQ;wQ.getDefaultConfig=CF;wQ.selectLbConfigFromList=yF;var BF=Z0(),RF=n();function PF($,q){var Y,T,X,J,Q,U,Z,K,A,W;return{createSubchannel:(T=(Y=q.createSubchannel)===null||Y===void 0?void 0:Y.bind(q))!==null&&T!==void 0?T:$.createSubchannel.bind($),updateState:(J=(X=q.updateState)===null||X===void 0?void 0:X.bind(q))!==null&&J!==void 0?J:$.updateState.bind($),requestReresolution:(U=(Q=q.requestReresolution)===null||Q===void 0?void 0:Q.bind(q))!==null&&U!==void 0?U:$.requestReresolution.bind($),addChannelzChild:(K=(Z=q.addChannelzChild)===null||Z===void 0?void 0:Z.bind(q))!==null&&K!==void 0?K:$.addChannelzChild.bind($),removeChannelzChild:(W=(A=q.removeChannelzChild)===null||A===void 0?void 0:A.bind(q))!==null&&W!==void 0?W:$.removeChannelzChild.bind($)}}var E$={},WY=null;function OF($,q,Y){E$[$]={LoadBalancer:q,LoadBalancingConfig:Y}}function LF($){WY=$}function wF($,q){let Y=$.getLoadBalancerName();if(Y in E$)return new E$[Y].LoadBalancer(q);else return null}function SF($){return $ in E$}function LQ($){let q=Object.keys($);if(q.length!==1)throw Error("Provided load balancing config has multiple conflicting entries");let Y=q[0];if(Y in E$)try{return E$[Y].LoadBalancingConfig.createFromJson($[Y])}catch(T){throw Error(`${Y}: ${T.message}`)}else throw Error(`Unrecognized load balancing config name ${Y}`)}function CF(){if(!WY)throw Error("No default load balancer type registered");return new E$[WY].LoadBalancingConfig}function yF($,q=!1){for(let Y of $)try{return LQ(Y)}catch(T){(0,BF.log)(RF.LogVerbosity.DEBUG,"Config parsing failed with error",T.message);continue}if(q)if(WY)return new E$[WY].LoadBalancingConfig;else return null;else return null}});var g9=B((yQ)=>{Object.defineProperty(yQ,"__esModule",{value:!0});yQ.validateRetryThrottling=SQ;yQ.validateServiceConfig=CQ;yQ.extractAndSelectServiceConfig=rF;var fF=e("os"),d6=n(),c6=/^\d+(\.\d{1,9})?s$/,bF="node";function uF($){if("service"in $&&$.service!==""){if(typeof $.service!=="string")throw Error(`Invalid method config name: invalid service: expected type string, got ${typeof $.service}`);if("method"in $&&$.method!==""){if(typeof $.method!=="string")throw Error(`Invalid method config name: invalid method: expected type string, got ${typeof $.service}`);return{service:$.service,method:$.method}}else return{service:$.service}}else{if("method"in $&&$.method!==void 0)throw Error("Invalid method config name: method set with empty or unset service");return{}}}function dF($){if(!("maxAttempts"in $)||!Number.isInteger($.maxAttempts)||$.maxAttempts<2)throw Error("Invalid method config retry policy: maxAttempts must be an integer at least 2");if(!("initialBackoff"in $)||typeof $.initialBackoff!=="string"||!c6.test($.initialBackoff))throw Error("Invalid method config retry policy: initialBackoff must be a string consisting of a positive integer or decimal followed by s");if(!("maxBackoff"in $)||typeof $.maxBackoff!=="string"||!c6.test($.maxBackoff))throw Error("Invalid method config retry policy: maxBackoff must be a string consisting of a positive integer or decimal followed by s");if(!("backoffMultiplier"in $)||typeof $.backoffMultiplier!=="number"||$.backoffMultiplier<=0)throw Error("Invalid method config retry policy: backoffMultiplier must be a number greater than 0");if(!(("retryableStatusCodes"in $)&&Array.isArray($.retryableStatusCodes)))throw Error("Invalid method config retry policy: retryableStatusCodes is required");if($.retryableStatusCodes.length===0)throw Error("Invalid method config retry policy: retryableStatusCodes must be non-empty");for(let q of $.retryableStatusCodes)if(typeof q==="number"){if(!Object.values(d6.Status).includes(q))throw Error("Invalid method config retry policy: retryableStatusCodes value not in status code range")}else if(typeof q==="string"){if(!Object.values(d6.Status).includes(q.toUpperCase()))throw Error("Invalid method config retry policy: retryableStatusCodes value not a status code name")}else throw Error("Invalid method config retry policy: retryableStatusCodes value must be a string or number");return{maxAttempts:$.maxAttempts,initialBackoff:$.initialBackoff,maxBackoff:$.maxBackoff,backoffMultiplier:$.backoffMultiplier,retryableStatusCodes:$.retryableStatusCodes}}function cF($){if(!("maxAttempts"in $)||!Number.isInteger($.maxAttempts)||$.maxAttempts<2)throw Error("Invalid method config hedging policy: maxAttempts must be an integer at least 2");if("hedgingDelay"in $&&(typeof $.hedgingDelay!=="string"||!c6.test($.hedgingDelay)))throw Error("Invalid method config hedging policy: hedgingDelay must be a string consisting of a positive integer followed by s");if("nonFatalStatusCodes"in $&&Array.isArray($.nonFatalStatusCodes))for(let Y of $.nonFatalStatusCodes)if(typeof Y==="number"){if(!Object.values(d6.Status).includes(Y))throw Error("Invalid method config hedging policy: nonFatalStatusCodes value not in status code range")}else if(typeof Y==="string"){if(!Object.values(d6.Status).includes(Y.toUpperCase()))throw Error("Invalid method config hedging policy: nonFatalStatusCodes value not a status code name")}else throw Error("Invalid method config hedging policy: nonFatalStatusCodes value must be a string or number");let q={maxAttempts:$.maxAttempts};if($.hedgingDelay)q.hedgingDelay=$.hedgingDelay;if($.nonFatalStatusCodes)q.nonFatalStatusCodes=$.nonFatalStatusCodes;return q}function pF($){var q;let Y={name:[]};if(!("name"in $)||!Array.isArray($.name))throw Error("Invalid method config: invalid name array");for(let T of $.name)Y.name.push(uF(T));if("waitForReady"in $){if(typeof $.waitForReady!=="boolean")throw Error("Invalid method config: invalid waitForReady");Y.waitForReady=$.waitForReady}if("timeout"in $)if(typeof $.timeout==="object"){if(!("seconds"in $.timeout)||typeof $.timeout.seconds!=="number")throw Error("Invalid method config: invalid timeout.seconds");if(!("nanos"in $.timeout)||typeof $.timeout.nanos!=="number")throw Error("Invalid method config: invalid timeout.nanos");Y.timeout=$.timeout}else if(typeof $.timeout==="string"&&c6.test($.timeout)){let T=$.timeout.substring(0,$.timeout.length-1).split(".");Y.timeout={seconds:T[0]|0,nanos:((q=T[1])!==null&&q!==void 0?q:0)|0}}else throw Error("Invalid method config: invalid timeout");if("maxRequestBytes"in $){if(typeof $.maxRequestBytes!=="number")throw Error("Invalid method config: invalid maxRequestBytes");Y.maxRequestBytes=$.maxRequestBytes}if("maxResponseBytes"in $){if(typeof $.maxResponseBytes!=="number")throw Error("Invalid method config: invalid maxRequestBytes");Y.maxResponseBytes=$.maxResponseBytes}if("retryPolicy"in $)if("hedgingPolicy"in $)throw Error("Invalid method config: retryPolicy and hedgingPolicy cannot both be specified");else Y.retryPolicy=dF($.retryPolicy);else if("hedgingPolicy"in $)Y.hedgingPolicy=cF($.hedgingPolicy);return Y}function SQ($){if(!("maxTokens"in $)||typeof $.maxTokens!=="number"||$.maxTokens<=0||$.maxTokens>1000)throw Error("Invalid retryThrottling: maxTokens must be a number in (0, 1000]");if(!("tokenRatio"in $)||typeof $.tokenRatio!=="number"||$.tokenRatio<=0)throw Error("Invalid retryThrottling: tokenRatio must be a number greater than 0");return{maxTokens:+$.maxTokens.toFixed(3),tokenRatio:+$.tokenRatio.toFixed(3)}}function lF($){if(!(typeof $==="object"&&$!==null))throw Error(`Invalid loadBalancingConfig: unexpected type ${typeof $}`);let q=Object.keys($);if(q.length>1)throw Error(`Invalid loadBalancingConfig: unexpected multiple keys ${q}`);if(q.length===0)throw Error("Invalid loadBalancingConfig: load balancing policy name required");return{[q[0]]:$[q[0]]}}function CQ($){let q={loadBalancingConfig:[],methodConfig:[]};if("loadBalancingPolicy"in $)if(typeof $.loadBalancingPolicy==="string")q.loadBalancingPolicy=$.loadBalancingPolicy;else throw Error("Invalid service config: invalid loadBalancingPolicy");if("loadBalancingConfig"in $)if(Array.isArray($.loadBalancingConfig))for(let T of $.loadBalancingConfig)q.loadBalancingConfig.push(lF(T));else throw Error("Invalid service config: invalid loadBalancingConfig");if("methodConfig"in $){if(Array.isArray($.methodConfig))for(let T of $.methodConfig)q.methodConfig.push(pF(T))}if("retryThrottling"in $)q.retryThrottling=SQ($.retryThrottling);let Y=[];for(let T of q.methodConfig)for(let X of T.name){for(let J of Y)if(X.service===J.service&&X.method===J.method)throw Error(`Invalid service config: duplicate name ${X.service}/${X.method}`);Y.push(X)}return q}function nF($){if(!("serviceConfig"in $))throw Error("Invalid service config choice: missing service config");let q={serviceConfig:CQ($.serviceConfig)};if("clientLanguage"in $)if(Array.isArray($.clientLanguage)){q.clientLanguage=[];for(let T of $.clientLanguage)if(typeof T==="string")q.clientLanguage.push(T);else throw Error("Invalid service config choice: invalid clientLanguage")}else throw Error("Invalid service config choice: invalid clientLanguage");if("clientHostname"in $)if(Array.isArray($.clientHostname)){q.clientHostname=[];for(let T of $.clientHostname)if(typeof T==="string")q.clientHostname.push(T);else throw Error("Invalid service config choice: invalid clientHostname")}else throw Error("Invalid service config choice: invalid clientHostname");if("percentage"in $)if(typeof $.percentage==="number"&&0<=$.percentage&&$.percentage<=100)q.percentage=$.percentage;else throw Error("Invalid service config choice: invalid percentage");let Y=["clientLanguage","percentage","clientHostname","serviceConfig"];for(let T in $)if(!Y.includes(T))throw Error(`Invalid service config choice: unexpected field ${T}`);return q}function iF($,q){if(!Array.isArray($))throw Error("Invalid service config list");for(let Y of $){let T=nF(Y);if(typeof T.percentage==="number"&&q>T.percentage)continue;if(Array.isArray(T.clientHostname)){let X=!1;for(let J of T.clientHostname)if(J===fF.hostname())X=!0;if(!X)continue}if(Array.isArray(T.clientLanguage)){let X=!1;for(let J of T.clientLanguage)if(J===bF)X=!0;if(!X)continue}return T.serviceConfig}throw Error("No matching service config found")}function rF($,q){for(let Y of $)if(Y.length>0&&Y[0].startsWith("grpc_config=")){let T=Y.join("").substring(12),X=JSON.parse(T);return iF(X,q)}return null}});var l0=B((vQ)=>{Object.defineProperty(vQ,"__esModule",{value:!0});vQ.ConnectivityState=void 0;var jQ;(function($){$[$.IDLE=0]="IDLE",$[$.CONNECTING=1]="CONNECTING",$[$.READY=2]="READY",$[$.TRANSIENT_FAILURE=3]="TRANSIENT_FAILURE",$[$.SHUTDOWN=4]="SHUTDOWN"})(jQ||(vQ.ConnectivityState=jQ={}))});var s1=B((_Q)=>{Object.defineProperty(_Q,"__esModule",{value:!0});_Q.QueuePicker=_Q.UnavailablePicker=_Q.PickResultType=void 0;var tF=P0(),eF=n(),p6;(function($){$[$.COMPLETE=0]="COMPLETE",$[$.QUEUE=1]="QUEUE",$[$.TRANSIENT_FAILURE=2]="TRANSIENT_FAILURE",$[$.DROP=3]="DROP"})(p6||(_Q.PickResultType=p6={}));class kQ{constructor($){this.status=Object.assign({code:eF.Status.UNAVAILABLE,details:"No connection established",metadata:new tF.Metadata},$)}pick($){return{pickResultType:p6.TRANSIENT_FAILURE,subchannel:null,status:this.status,onCallStarted:null,onCallEnded:null}}}_Q.UnavailablePicker=kQ;class hQ{constructor($,q){this.loadBalancer=$,this.childPicker=q,this.calledExitIdle=!1}pick($){if(!this.calledExitIdle)process.nextTick(()=>{this.loadBalancer.exitIdle()}),this.calledExitIdle=!0;if(this.childPicker)return this.childPicker.pick($);else return{pickResultType:p6.QUEUE,subchannel:null,status:null,onCallStarted:null,onCallEnded:null}}}_Q.QueuePicker=hQ});var Fq=B((mQ)=>{Object.defineProperty(mQ,"__esModule",{value:!0});mQ.BackoffTimeout=void 0;var YI=n(),TI=Z0(),XI="backoff",JI=1000,QI=1.6,UI=120000,ZI=0.2;function KI($,q){return Math.random()*(q-$)+$}class l6{constructor($,q){if(this.callback=$,this.initialDelay=JI,this.multiplier=QI,this.maxDelay=UI,this.jitter=ZI,this.running=!1,this.hasRef=!0,this.startTime=new Date,this.endTime=new Date,this.id=l6.getNextId(),q){if(q.initialDelay)this.initialDelay=q.initialDelay;if(q.multiplier)this.multiplier=q.multiplier;if(q.jitter)this.jitter=q.jitter;if(q.maxDelay)this.maxDelay=q.maxDelay}this.trace("constructed initialDelay="+this.initialDelay+" multiplier="+this.multiplier+" jitter="+this.jitter+" maxDelay="+this.maxDelay),this.nextDelay=this.initialDelay,this.timerId=setTimeout(()=>{},0),clearTimeout(this.timerId)}static getNextId(){return this.nextId++}trace($){TI.trace(YI.LogVerbosity.DEBUG,XI,"{"+this.id+"} "+$)}runTimer($){var q,Y;if(this.trace("runTimer(delay="+$+")"),this.endTime=this.startTime,this.endTime.setMilliseconds(this.endTime.getMilliseconds()+$),clearTimeout(this.timerId),this.timerId=setTimeout(()=>{this.trace("timer fired"),this.running=!1,this.callback()},$),!this.hasRef)(Y=(q=this.timerId).unref)===null||Y===void 0||Y.call(q)}runOnce(){this.trace("runOnce()"),this.running=!0,this.startTime=new Date,this.runTimer(this.nextDelay);let $=Math.min(this.nextDelay*this.multiplier,this.maxDelay),q=$*this.jitter;this.nextDelay=$+KI(-q,q)}stop(){this.trace("stop()"),clearTimeout(this.timerId),this.running=!1}reset(){if(this.trace("reset() running="+this.running),this.nextDelay=this.initialDelay,this.running){let $=new Date,q=this.startTime;if(q.setMilliseconds(q.getMilliseconds()+this.nextDelay),clearTimeout(this.timerId),$<q)this.runTimer(q.getTime()-$.getTime());else this.running=!1}}isRunning(){return this.running}ref(){var $,q;this.hasRef=!0,(q=($=this.timerId).ref)===null||q===void 0||q.call($)}unref(){var $,q;this.hasRef=!1,(q=($=this.timerId).unref)===null||q===void 0||q.call($)}getEndTime(){return this.endTime}}mQ.BackoffTimeout=l6;l6.nextId=0});var n6=B((uQ)=>{Object.defineProperty(uQ,"__esModule",{value:!0});uQ.ChildLoadBalancerHandler=void 0;var AI=V$(),WI=l0(),GI="child_load_balancer_helper";class bQ{constructor($){this.channelControlHelper=$,this.currentChild=null,this.pendingChild=null,this.latestConfig=null,this.ChildPolicyHelper=class{constructor(q){this.parent=q,this.child=null}createSubchannel(q,Y){return this.parent.channelControlHelper.createSubchannel(q,Y)}updateState(q,Y,T){var X;if(this.calledByPendingChild()){if(q===WI.ConnectivityState.CONNECTING)return;(X=this.parent.currentChild)===null||X===void 0||X.destroy(),this.parent.currentChild=this.parent.pendingChild,this.parent.pendingChild=null}else if(!this.calledByCurrentChild())return;this.parent.channelControlHelper.updateState(q,Y,T)}requestReresolution(){var q;let Y=(q=this.parent.pendingChild)!==null&&q!==void 0?q:this.parent.currentChild;if(this.child===Y)this.parent.channelControlHelper.requestReresolution()}setChild(q){this.child=q}addChannelzChild(q){this.parent.channelControlHelper.addChannelzChild(q)}removeChannelzChild(q){this.parent.channelControlHelper.removeChannelzChild(q)}calledByPendingChild(){return this.child===this.parent.pendingChild}calledByCurrentChild(){return this.child===this.parent.currentChild}}}configUpdateRequiresNewPolicyInstance($,q){return $.getLoadBalancerName()!==q.getLoadBalancerName()}updateAddressList($,q,Y,T){let X;if(this.currentChild===null||this.latestConfig===null||this.configUpdateRequiresNewPolicyInstance(this.latestConfig,q)){let J=new this.ChildPolicyHelper(this),Q=(0,AI.createLoadBalancer)(q,J);if(J.setChild(Q),this.currentChild===null)this.currentChild=Q,X=this.currentChild;else{if(this.pendingChild)this.pendingChild.destroy();this.pendingChild=Q,X=this.pendingChild}}else if(this.pendingChild===null)X=this.currentChild;else X=this.pendingChild;return this.latestConfig=q,X.updateAddressList($,q,Y,T)}exitIdle(){if(this.currentChild){if(this.currentChild.exitIdle(),this.pendingChild)this.pendingChild.exitIdle()}}resetBackoff(){if(this.currentChild){if(this.currentChild.resetBackoff(),this.pendingChild)this.pendingChild.resetBackoff()}}destroy(){if(this.currentChild)this.currentChild.destroy(),this.currentChild=null;if(this.pendingChild)this.pendingChild.destroy(),this.pendingChild=null}getTypeName(){return GI}}uQ.ChildLoadBalancerHandler=bQ});var rQ=B((nQ)=>{Object.defineProperty(nQ,"__esModule",{value:!0});nQ.ResolvingLoadBalancer=void 0;var EI=V$(),VI=g9(),n0=l0(),cQ=H1(),GY=s1(),DI=Fq(),m9=n(),FI=P0(),II=Z0(),NI=n(),HI=p0(),zI=n6(),MI="resolving_load_balancer";function pQ($){II.trace(NI.LogVerbosity.DEBUG,MI,$)}var BI=["SERVICE_AND_METHOD","SERVICE","EMPTY"];function RI($,q,Y,T){for(let X of Y.name)switch(T){case"EMPTY":if(!X.service&&!X.method)return!0;break;case"SERVICE":if(X.service===$&&!X.method)return!0;break;case"SERVICE_AND_METHOD":if(X.service===$&&X.method===q)return!0}return!1}function PI($,q,Y,T){for(let X of Y)if(RI($,q,X,T))return X;return null}function OI($){return{invoke(q,Y){var T,X;let J=q.split("/").filter((Z)=>Z.length>0),Q=(T=J[0])!==null&&T!==void 0?T:"",U=(X=J[1])!==null&&X!==void 0?X:"";if($&&$.methodConfig)for(let Z of BI){let K=PI(Q,U,$.methodConfig,Z);if(K)return{methodConfig:K,pickInformation:{},status:m9.Status.OK,dynamicFilterFactories:[]}}return{methodConfig:{name:[]},pickInformation:{},status:m9.Status.OK,dynamicFilterFactories:[]}},unref(){}}}class lQ{constructor($,q,Y,T,X){if(this.target=$,this.channelControlHelper=q,this.channelOptions=Y,this.onSuccessfulResolution=T,this.onFailedResolution=X,this.latestChildState=n0.ConnectivityState.IDLE,this.latestChildPicker=new GY.QueuePicker(this),this.latestChildErrorMessage=null,this.currentState=n0.ConnectivityState.IDLE,this.previousServiceConfig=null,this.continueResolving=!1,Y["grpc.service_config"])this.defaultServiceConfig=(0,VI.validateServiceConfig)(JSON.parse(Y["grpc.service_config"]));else this.defaultServiceConfig={loadBalancingConfig:[],methodConfig:[]};this.updateState(n0.ConnectivityState.IDLE,new GY.QueuePicker(this),null),this.childLoadBalancer=new zI.ChildLoadBalancerHandler({createSubchannel:q.createSubchannel.bind(q),requestReresolution:()=>{if(this.backoffTimeout.isRunning())pQ("requestReresolution delayed by backoff timer until "+this.backoffTimeout.getEndTime().toISOString()),this.continueResolving=!0;else this.updateResolution()},updateState:(Q,U,Z)=>{this.latestChildState=Q,this.latestChildPicker=U,this.latestChildErrorMessage=Z,this.updateState(Q,U,Z)},addChannelzChild:q.addChannelzChild.bind(q),removeChannelzChild:q.removeChannelzChild.bind(q)}),this.innerResolver=(0,cQ.createResolver)($,this.handleResolverResult.bind(this),Y);let J={initialDelay:Y["grpc.initial_reconnect_backoff_ms"],maxDelay:Y["grpc.max_reconnect_backoff_ms"]};this.backoffTimeout=new DI.BackoffTimeout(()=>{if(this.continueResolving)this.updateResolution(),this.continueResolving=!1;else this.updateState(this.latestChildState,this.latestChildPicker,this.latestChildErrorMessage)},J),this.backoffTimeout.unref()}handleResolverResult($,q,Y,T){var X,J;this.backoffTimeout.stop(),this.backoffTimeout.reset();let Q=!0,U=null;if(Y===null)U=this.defaultServiceConfig;else if(Y.ok)U=Y.value;else if(this.previousServiceConfig!==null)U=this.previousServiceConfig;else Q=!1,this.handleResolutionFailure(Y.error);if(U!==null){let Z=(X=U===null||U===void 0?void 0:U.loadBalancingConfig)!==null&&X!==void 0?X:[],K=(0,EI.selectLbConfigFromList)(Z,!0);if(K===null)Q=!1,this.handleResolutionFailure({code:m9.Status.UNAVAILABLE,details:"All load balancer options in service config are not compatible",metadata:new FI.Metadata});else Q=this.childLoadBalancer.updateAddressList($,K,Object.assign(Object.assign({},this.channelOptions),q),T)}if(Q)this.onSuccessfulResolution(U,(J=q[cQ.CHANNEL_ARGS_CONFIG_SELECTOR_KEY])!==null&&J!==void 0?J:OI(U));return Q}updateResolution(){if(this.innerResolver.updateResolution(),this.currentState===n0.ConnectivityState.IDLE)this.updateState(n0.ConnectivityState.CONNECTING,this.latestChildPicker,this.latestChildErrorMessage);this.backoffTimeout.runOnce()}updateState($,q,Y){if(pQ((0,HI.uriToString)(this.target)+" "+n0.ConnectivityState[this.currentState]+" -> "+n0.ConnectivityState[$]),$===n0.ConnectivityState.IDLE)q=new GY.QueuePicker(this,q);this.currentState=$,this.channelControlHelper.updateState($,q,Y)}handleResolutionFailure($){if(this.latestChildState===n0.ConnectivityState.IDLE)this.updateState(n0.ConnectivityState.TRANSIENT_FAILURE,new GY.UnavailablePicker($),$.details),this.onFailedResolution($)}exitIdle(){if(this.currentState===n0.ConnectivityState.IDLE||this.currentState===n0.ConnectivityState.TRANSIENT_FAILURE)if(this.backoffTimeout.isRunning())this.continueResolving=!0;else this.updateResolution();this.childLoadBalancer.exitIdle()}updateAddressList($,q){throw Error("updateAddressList not supported on ResolvingLoadBalancer")}resetBackoff(){this.backoffTimeout.reset(),this.childLoadBalancer.resetBackoff()}destroy(){this.childLoadBalancer.destroy(),this.innerResolver.destroy(),this.backoffTimeout.reset(),this.backoffTimeout.stop(),this.latestChildState=n0.ConnectivityState.IDLE,this.latestChildPicker=new GY.QueuePicker(this),this.currentState=n0.ConnectivityState.IDLE,this.previousServiceConfig=null,this.continueResolving=!1}getTypeName(){return"resolving_load_balancer"}}nQ.ResolvingLoadBalancer=lQ});var sQ=B((aQ)=>{Object.defineProperty(aQ,"__esModule",{value:!0});aQ.recognizedOptions=void 0;aQ.channelOptionsEqual=LI;aQ.recognizedOptions={"grpc.ssl_target_name_override":!0,"grpc.primary_user_agent":!0,"grpc.secondary_user_agent":!0,"grpc.default_authority":!0,"grpc.keepalive_time_ms":!0,"grpc.keepalive_timeout_ms":!0,"grpc.keepalive_permit_without_calls":!0,"grpc.service_config":!0,"grpc.max_concurrent_streams":!0,"grpc.initial_reconnect_backoff_ms":!0,"grpc.max_reconnect_backoff_ms":!0,"grpc.use_local_subchannel_pool":!0,"grpc.max_send_message_length":!0,"grpc.max_receive_message_length":!0,"grpc.enable_http_proxy":!0,"grpc.enable_channelz":!0,"grpc.dns_min_time_between_resolutions_ms":!0,"grpc.enable_retries":!0,"grpc.per_rpc_retry_buffer_size":!0,"grpc.retry_buffer_size":!0,"grpc.max_connection_age_ms":!0,"grpc.max_connection_age_grace_ms":!0,"grpc-node.max_session_memory":!0,"grpc.service_config_disable_resolution":!0,"grpc.client_idle_timeout_ms":!0,"grpc-node.tls_enable_trace":!0,"grpc.lb.ring_hash.ring_size_cap":!0,"grpc-node.retry_max_attempts_limit":!0,"grpc-node.flow_control_window":!0,"grpc.server_call_metric_recording":!0};function LI($,q){let Y=Object.keys($).sort(),T=Object.keys(q).sort();if(Y.length!==T.length)return!1;for(let X=0;X<Y.length;X+=1){if(Y[X]!==T[X])return!1;if($[Y[X]]!==q[T[X]])return!1}return!0}});var i0=B((YU)=>{Object.defineProperty(YU,"__esModule",{value:!0});YU.EndpointMap=void 0;YU.isTcpSubchannelAddress=VY;YU.subchannelAddressEqual=i6;YU.subchannelAddressToString=eQ;YU.stringToSubchannelAddress=CI;YU.endpointEqual=yI;YU.endpointToString=jI;YU.endpointHasAddress=$U;var tQ=e("net");function VY($){return"port"in $}function i6($,q){if(!$&&!q)return!0;if(!$||!q)return!1;if(VY($))return VY(q)&&$.host===q.host&&$.port===q.port;else return!VY(q)&&$.path===q.path}function eQ($){if(VY($))if((0,tQ.isIPv6)($.host))return"["+$.host+"]:"+$.port;else return $.host+":"+$.port;else return $.path}var SI=443;function CI($,q){if((0,tQ.isIP)($))return{host:$,port:q!==null&&q!==void 0?q:SI};else return{path:$}}function yI($,q){if($.addresses.length!==q.addresses.length)return!1;for(let Y=0;Y<$.addresses.length;Y++)if(!i6($.addresses[Y],q.addresses[Y]))return!1;return!0}function jI($){return"["+$.addresses.map(eQ).join(", ")+"]"}function $U($,q){for(let Y of $.addresses)if(i6(Y,q))return!0;return!1}function EY($,q){if($.addresses.length!==q.addresses.length)return!1;for(let Y of $.addresses){let T=!1;for(let X of q.addresses)if(i6(Y,X)){T=!0;break}if(!T)return!1}return!0}class qU{constructor(){this.map=new Set}get size(){return this.map.size}getForSubchannelAddress($){for(let q of this.map)if($U(q.key,$))return q.value;return}deleteMissing($){let q=[];for(let Y of this.map){let T=!1;for(let X of $)if(EY(X,Y.key))T=!0;if(!T)q.push(Y.value),this.map.delete(Y)}return q}get($){for(let q of this.map)if(EY($,q.key))return q.value;return}set($,q){for(let Y of this.map)if(EY($,Y.key)){Y.value=q;return}this.map.add({key:$,value:q})}delete($){for(let q of this.map)if(EY($,q.key)){this.map.delete(q);return}}has($){for(let q of this.map)if(EY($,q.key))return!0;return!1}clear(){this.map.clear()}*keys(){for(let $ of this.map)yield $.key}*values(){for(let $ of this.map)yield $.value}*entries(){for(let $ of this.map)yield[$.key,$.value]}}YU.EndpointMap=qU});var GU=B((WU)=>{Object.defineProperty(WU,"t",{value:!0});class f9{constructor($,q,Y=1){this.i=void 0,this.h=void 0,this.o=void 0,this.u=$,this.l=q,this.p=Y}I(){let $=this,q=$.o.o===$;if(q&&$.p===1)$=$.h;else if($.i){$=$.i;while($.h)$=$.h}else{if(q)return $.o;let Y=$.o;while(Y.i===$)$=Y,Y=$.o;$=Y}return $}B(){let $=this;if($.h){$=$.h;while($.i)$=$.i;return $}else{let q=$.o;while(q.h===$)$=q,q=$.o;if($.h!==q)return q;else return $}}_(){let $=this.o,q=this.h,Y=q.i;if($.o===this)$.o=q;else if($.i===this)$.i=q;else $.h=q;if(q.o=$,q.i=this,this.o=q,this.h=Y,Y)Y.o=this;return q}g(){let $=this.o,q=this.i,Y=q.h;if($.o===this)$.o=q;else if($.i===this)$.i=q;else $.h=q;if(q.o=$,q.h=this,this.o=q,this.i=Y,Y)Y.o=this;return q}}class XU extends f9{constructor(){super(...arguments);this.M=1}_(){let $=super._();return this.O(),$.O(),$}g(){let $=super.g();return this.O(),$.O(),$}O(){if(this.M=1,this.i)this.M+=this.i.M;if(this.h)this.M+=this.h.M}}class JU{constructor($=0){this.iteratorType=$}equals($){return this.T===$.T}}class QU{constructor(){this.m=0}get length(){return this.m}size(){return this.m}empty(){return this.m===0}}class UU extends QU{}function g$(){throw RangeError("Iterator access denied!")}class ZU extends UU{constructor($=function(Y,T){if(Y<T)return-1;if(Y>T)return 1;return 0},q=!1){super();this.v=void 0,this.A=$,this.enableIndex=q,this.N=q?XU:f9,this.C=new this.N}R($,q){let Y=this.C;while($){let T=this.A($.u,q);if(T<0)$=$.h;else if(T>0)Y=$,$=$.i;else return $}return Y}K($,q){let Y=this.C;while($)if(this.A($.u,q)<=0)$=$.h;else Y=$,$=$.i;return Y}L($,q){let Y=this.C;while($){let T=this.A($.u,q);if(T<0)Y=$,$=$.h;else if(T>0)$=$.i;else return $}return Y}k($,q){let Y=this.C;while($)if(this.A($.u,q)<0)Y=$,$=$.h;else $=$.i;return Y}P($){while(!0){let q=$.o;if(q===this.C)return;if($.p===1){$.p=0;return}if($===q.i){let Y=q.h;if(Y.p===1)if(Y.p=0,q.p=1,q===this.v)this.v=q._();else q._();else if(Y.h&&Y.h.p===1){if(Y.p=q.p,q.p=0,Y.h.p=0,q===this.v)this.v=q._();else q._();return}else if(Y.i&&Y.i.p===1)Y.p=1,Y.i.p=0,Y.g();else Y.p=1,$=q}else{let Y=q.i;if(Y.p===1)if(Y.p=0,q.p=1,q===this.v)this.v=q.g();else q.g();else if(Y.i&&Y.i.p===1){if(Y.p=q.p,q.p=0,Y.i.p=0,q===this.v)this.v=q.g();else q.g();return}else if(Y.h&&Y.h.p===1)Y.p=1,Y.h.p=0,Y._();else Y.p=1,$=q}}}S($){if(this.m===1){this.clear();return}let q=$;while(q.i||q.h){if(q.h){q=q.h;while(q.i)q=q.i}else q=q.i;let T=$.u;$.u=q.u,q.u=T;let X=$.l;$.l=q.l,q.l=X,$=q}if(this.C.i===q)this.C.i=q.o;else if(this.C.h===q)this.C.h=q.o;this.P(q);let Y=q.o;if(q===Y.i)Y.i=void 0;else Y.h=void 0;if(this.m-=1,this.v.p=0,this.enableIndex)while(Y!==this.C)Y.M-=1,Y=Y.o}U($){let q=typeof $==="number"?$:void 0,Y=typeof $==="function"?$:void 0,T=typeof $>"u"?[]:void 0,X=0,J=this.v,Q=[];while(Q.length||J)if(J)Q.push(J),J=J.i;else{if(J=Q.pop(),X===q)return J;T&&T.push(J),Y&&Y(J,X,this),X+=1,J=J.h}return T}j($){while(!0){let q=$.o;if(q.p===0)return;let Y=q.o;if(q===Y.i){let T=Y.h;if(T&&T.p===1){if(T.p=q.p=0,Y===this.v)return;Y.p=1,$=Y;continue}else if($===q.h){if($.p=0,$.i)$.i.o=q;if($.h)$.h.o=Y;if(q.h=$.i,Y.i=$.h,$.i=q,$.h=Y,Y===this.v)this.v=$,this.C.o=$;else{let X=Y.o;if(X.i===Y)X.i=$;else X.h=$}$.o=Y.o,q.o=$,Y.o=$,Y.p=1}else{if(q.p=0,Y===this.v)this.v=Y.g();else Y.g();Y.p=1;return}}else{let T=Y.i;if(T&&T.p===1){if(T.p=q.p=0,Y===this.v)return;Y.p=1,$=Y;continue}else if($===q.i){if($.p=0,$.i)$.i.o=Y;if($.h)$.h.o=q;if(Y.h=$.i,q.i=$.h,$.i=Y,$.h=q,Y===this.v)this.v=$,this.C.o=$;else{let X=Y.o;if(X.i===Y)X.i=$;else X.h=$}$.o=Y.o,q.o=$,Y.o=$,Y.p=1}else{if(q.p=0,Y===this.v)this.v=Y._();else Y._();Y.p=1;return}}if(this.enableIndex)q.O(),Y.O(),$.O();return}}q($,q,Y){if(this.v===void 0)return this.m+=1,this.v=new this.N($,q,0),this.v.o=this.C,this.C.o=this.C.i=this.C.h=this.v,this.m;let T,X=this.C.i,J=this.A(X.u,$);if(J===0)return X.l=q,this.m;else if(J>0)X.i=new this.N($,q),X.i.o=X,T=X.i,this.C.i=T;else{let Q=this.C.h,U=this.A(Q.u,$);if(U===0)return Q.l=q,this.m;else if(U<0)Q.h=new this.N($,q),Q.h.o=Q,T=Q.h,this.C.h=T;else{if(Y!==void 0){let Z=Y.T;if(Z!==this.C){let K=this.A(Z.u,$);if(K===0)return Z.l=q,this.m;else if(K>0){let A=Z.I(),W=this.A(A.u,$);if(W===0)return A.l=q,this.m;else if(W<0)if(T=new this.N($,q),A.h===void 0)A.h=T,T.o=A;else Z.i=T,T.o=Z}}}if(T===void 0){T=this.v;while(!0){let Z=this.A(T.u,$);if(Z>0){if(T.i===void 0){T.i=new this.N($,q),T.i.o=T,T=T.i;break}T=T.i}else if(Z<0){if(T.h===void 0){T.h=new this.N($,q),T.h.o=T,T=T.h;break}T=T.h}else return T.l=q,this.m}}}}if(this.enableIndex){let Q=T.o;while(Q!==this.C)Q.M+=1,Q=Q.o}return this.j(T),this.m+=1,this.m}H($,q){while($){let Y=this.A($.u,q);if(Y<0)$=$.h;else if(Y>0)$=$.i;else return $}return $||this.C}clear(){this.m=0,this.v=void 0,this.C.o=void 0,this.C.i=this.C.h=void 0}updateKeyByIterator($,q){let Y=$.T;if(Y===this.C)g$();if(this.m===1)return Y.u=q,!0;let T=Y.B().u;if(Y===this.C.i){if(this.A(T,q)>0)return Y.u=q,!0;return!1}let X=Y.I().u;if(Y===this.C.h){if(this.A(X,q)<0)return Y.u=q,!0;return!1}if(this.A(X,q)>=0||this.A(T,q)<=0)return!1;return Y.u=q,!0}eraseElementByPos($){if($<0||$>this.m-1)throw RangeError();let q=this.U($);return this.S(q),this.m}eraseElementByKey($){if(this.m===0)return!1;let q=this.H(this.v,$);if(q===this.C)return!1;return this.S(q),!0}eraseElementByIterator($){let q=$.T;if(q===this.C)g$();let Y=q.h===void 0;if($.iteratorType===0){if(Y)$.next()}else if(!Y||q.i===void 0)$.next();return this.S(q),$}getHeight(){if(this.m===0)return 0;function $(q){if(!q)return 0;return Math.max($(q.i),$(q.h))+1}return $(this.v)}}class KU extends JU{constructor($,q,Y){super(Y);if(this.T=$,this.C=q,this.iteratorType===0)this.pre=function(){if(this.T===this.C.i)g$();return this.T=this.T.I(),this},this.next=function(){if(this.T===this.C)g$();return this.T=this.T.B(),this};else this.pre=function(){if(this.T===this.C.h)g$();return this.T=this.T.B(),this},this.next=function(){if(this.T===this.C)g$();return this.T=this.T.I(),this}}get index(){let $=this.T,q=this.C.o;if($===this.C){if(q)return q.M-1;return 0}let Y=0;if($.i)Y+=$.i.M;while($!==q){let T=$.o;if($===T.h){if(Y+=1,T.i)Y+=T.i.M}$=T}return Y}isAccessible(){return this.T!==this.C}}class z1 extends KU{constructor($,q,Y,T){super($,q,T);this.container=Y}get pointer(){if(this.T===this.C)g$();let $=this;return new Proxy([],{get(q,Y){if(Y==="0")return $.T.u;else if(Y==="1")return $.T.l;return q[0]=$.T.u,q[1]=$.T.l,q[Y]},set(q,Y,T){if(Y!=="1")throw TypeError("prop must be 1");return $.T.l=T,!0}})}copy(){return new z1(this.T,this.C,this.container,this.iteratorType)}}class AU extends ZU{constructor($=[],q,Y){super(q,Y);let T=this;$.forEach(function(X){T.setElement(X[0],X[1])})}begin(){return new z1(this.C.i||this.C,this.C,this)}end(){return new z1(this.C,this.C,this)}rBegin(){return new z1(this.C.h||this.C,this.C,this,1)}rEnd(){return new z1(this.C,this.C,this,1)}front(){if(this.m===0)return;let $=this.C.i;return[$.u,$.l]}back(){if(this.m===0)return;let $=this.C.h;return[$.u,$.l]}lowerBound($){let q=this.R(this.v,$);return new z1(q,this.C,this)}upperBound($){let q=this.K(this.v,$);return new z1(q,this.C,this)}reverseLowerBound($){let q=this.L(this.v,$);return new z1(q,this.C,this)}reverseUpperBound($){let q=this.k(this.v,$);return new z1(q,this.C,this)}forEach($){this.U(function(q,Y,T){$([q.u,q.l],Y,T)})}setElement($,q,Y){return this.q($,q,Y)}getElementByPos($){if($<0||$>this.m-1)throw RangeError();let q=this.U($);return[q.u,q.l]}find($){let q=this.H(this.v,$);return new z1(q,this.C,this)}getElementByKey($){return this.H(this.v,$).l}union($){let q=this;return $.forEach(function(Y){q.setElement(Y[0],Y[1])}),this.m}*[Symbol.iterator](){let $=this.m,q=this.U();for(let Y=0;Y<$;++Y){let T=q[Y];yield[T.u,T.l]}}}WU.OrderedMap=AU});var r6=B((VU)=>{Object.defineProperty(VU,"__esModule",{value:!0});VU.registerAdminService=bI;VU.addAdminServicesToServer=uI;var EU=[];function bI($,q){EU.push({getServiceDefinition:$,getHandlers:q})}function uI($){for(let{getServiceDefinition:q,getHandlers:Y}of EU)$.addService(q(),Y())}});var MU=B((HU)=>{Object.defineProperty(HU,"__esModule",{value:!0});HU.ClientDuplexStreamImpl=HU.ClientWritableStreamImpl=HU.ClientReadableStreamImpl=HU.ClientUnaryCallImpl=void 0;HU.callErrorFromStatus=lI;var pI=e("events"),b9=e("stream"),DY=n();function lI($,q){let Y=`${$.code} ${DY.Status[$.code]}: ${$.details}`,X=`${Error(Y).stack}
2
- for call at
3
- ${q}`;return Object.assign(Error(Y),$,{stack:X})}class DU extends pI.EventEmitter{constructor(){super()}cancel(){var $;($=this.call)===null||$===void 0||$.cancelWithStatus(DY.Status.CANCELLED,"Cancelled on client")}getPeer(){var $,q;return(q=($=this.call)===null||$===void 0?void 0:$.getPeer())!==null&&q!==void 0?q:"unknown"}getAuthContext(){var $,q;return(q=($=this.call)===null||$===void 0?void 0:$.getAuthContext())!==null&&q!==void 0?q:null}}HU.ClientUnaryCallImpl=DU;class FU extends b9.Readable{constructor($){super({objectMode:!0});this.deserialize=$}cancel(){var $;($=this.call)===null||$===void 0||$.cancelWithStatus(DY.Status.CANCELLED,"Cancelled on client")}getPeer(){var $,q;return(q=($=this.call)===null||$===void 0?void 0:$.getPeer())!==null&&q!==void 0?q:"unknown"}getAuthContext(){var $,q;return(q=($=this.call)===null||$===void 0?void 0:$.getAuthContext())!==null&&q!==void 0?q:null}_read($){var q;(q=this.call)===null||q===void 0||q.startRead()}}HU.ClientReadableStreamImpl=FU;class IU extends b9.Writable{constructor($){super({objectMode:!0});this.serialize=$}cancel(){var $;($=this.call)===null||$===void 0||$.cancelWithStatus(DY.Status.CANCELLED,"Cancelled on client")}getPeer(){var $,q;return(q=($=this.call)===null||$===void 0?void 0:$.getPeer())!==null&&q!==void 0?q:"unknown"}getAuthContext(){var $,q;return(q=($=this.call)===null||$===void 0?void 0:$.getAuthContext())!==null&&q!==void 0?q:null}_write($,q,Y){var T;let X={callback:Y},J=Number(q);if(!Number.isNaN(J))X.flags=J;(T=this.call)===null||T===void 0||T.sendMessageWithContext(X,$)}_final($){var q;(q=this.call)===null||q===void 0||q.halfClose(),$()}}HU.ClientWritableStreamImpl=IU;class NU extends b9.Duplex{constructor($,q){super({objectMode:!0});this.serialize=$,this.deserialize=q}cancel(){var $;($=this.call)===null||$===void 0||$.cancelWithStatus(DY.Status.CANCELLED,"Cancelled on client")}getPeer(){var $,q;return(q=($=this.call)===null||$===void 0?void 0:$.getPeer())!==null&&q!==void 0?q:"unknown"}getAuthContext(){var $,q;return(q=($=this.call)===null||$===void 0?void 0:$.getAuthContext())!==null&&q!==void 0?q:null}_read($){var q;(q=this.call)===null||q===void 0||q.startRead()}_write($,q,Y){var T;let X={callback:Y},J=Number(q);if(!Number.isNaN(J))X.flags=J;(T=this.call)===null||T===void 0||T.sendMessageWithContext(X,$)}_final($){var q;(q=this.call)===null||q===void 0||q.halfClose(),$()}}HU.ClientDuplexStreamImpl=NU});var m$=B((RU)=>{Object.defineProperty(RU,"__esModule",{value:!0});RU.InterceptingListenerImpl=void 0;RU.statusOrFromValue=sI;RU.statusOrFromError=tI;RU.isInterceptingListener=eI;var oI=P0();function sI($){return{ok:!0,value:$}}function tI($){var q;return{ok:!1,error:Object.assign(Object.assign({},$),{metadata:(q=$.metadata)!==null&&q!==void 0?q:new oI.Metadata})}}function eI($){return $.onReceiveMetadata!==void 0&&$.onReceiveMetadata.length===1}class BU{constructor($,q){this.listener=$,this.nextListener=q,this.processingMetadata=!1,this.hasPendingMessage=!1,this.processingMessage=!1,this.pendingStatus=null}processPendingMessage(){if(this.hasPendingMessage)this.nextListener.onReceiveMessage(this.pendingMessage),this.pendingMessage=null,this.hasPendingMessage=!1}processPendingStatus(){if(this.pendingStatus)this.nextListener.onReceiveStatus(this.pendingStatus)}onReceiveMetadata($){this.processingMetadata=!0,this.listener.onReceiveMetadata($,(q)=>{this.processingMetadata=!1,this.nextListener.onReceiveMetadata(q),this.processPendingMessage(),this.processPendingStatus()})}onReceiveMessage($){this.processingMessage=!0,this.listener.onReceiveMessage($,(q)=>{if(this.processingMessage=!1,this.processingMetadata)this.pendingMessage=q,this.hasPendingMessage=!0;else this.nextListener.onReceiveMessage(q),this.processPendingStatus()})}onReceiveStatus($){this.listener.onReceiveStatus($,(q)=>{if(this.processingMetadata||this.processingMessage)this.pendingStatus=q;else this.nextListener.onReceiveStatus(q)})}}RU.InterceptingListenerImpl=BU});var c9=B((xU)=>{Object.defineProperty(xU,"__esModule",{value:!0});xU.InterceptingCall=xU.RequesterBuilder=xU.ListenerBuilder=xU.InterceptorConfigurationError=void 0;xU.getInterceptingCall=QN;var TN=P0(),OU=m$(),LU=n(),wU=k6();class IY extends Error{constructor($){super($);this.name="InterceptorConfigurationError",Error.captureStackTrace(this,IY)}}xU.InterceptorConfigurationError=IY;class SU{constructor(){this.metadata=void 0,this.message=void 0,this.status=void 0}withOnReceiveMetadata($){return this.metadata=$,this}withOnReceiveMessage($){return this.message=$,this}withOnReceiveStatus($){return this.status=$,this}build(){return{onReceiveMetadata:this.metadata,onReceiveMessage:this.message,onReceiveStatus:this.status}}}xU.ListenerBuilder=SU;class CU{constructor(){this.start=void 0,this.message=void 0,this.halfClose=void 0,this.cancel=void 0}withStart($){return this.start=$,this}withSendMessage($){return this.message=$,this}withHalfClose($){return this.halfClose=$,this}withCancel($){return this.cancel=$,this}build(){return{start:this.start,sendMessage:this.message,halfClose:this.halfClose,cancel:this.cancel}}}xU.RequesterBuilder=CU;var u9={onReceiveMetadata:($,q)=>{q($)},onReceiveMessage:($,q)=>{q($)},onReceiveStatus:($,q)=>{q($)}},FY={start:($,q,Y)=>{Y($,q)},sendMessage:($,q)=>{q($)},halfClose:($)=>{$()},cancel:($)=>{$()}};class yU{constructor($,q){var Y,T,X,J;if(this.nextCall=$,this.processingMetadata=!1,this.pendingMessageContext=null,this.processingMessage=!1,this.pendingHalfClose=!1,q)this.requester={start:(Y=q.start)!==null&&Y!==void 0?Y:FY.start,sendMessage:(T=q.sendMessage)!==null&&T!==void 0?T:FY.sendMessage,halfClose:(X=q.halfClose)!==null&&X!==void 0?X:FY.halfClose,cancel:(J=q.cancel)!==null&&J!==void 0?J:FY.cancel};else this.requester=FY}cancelWithStatus($,q){this.requester.cancel(()=>{this.nextCall.cancelWithStatus($,q)})}getPeer(){return this.nextCall.getPeer()}processPendingMessage(){if(this.pendingMessageContext)this.nextCall.sendMessageWithContext(this.pendingMessageContext,this.pendingMessage),this.pendingMessageContext=null,this.pendingMessage=null}processPendingHalfClose(){if(this.pendingHalfClose)this.nextCall.halfClose()}start($,q){var Y,T,X,J,Q,U;let Z={onReceiveMetadata:(T=(Y=q===null||q===void 0?void 0:q.onReceiveMetadata)===null||Y===void 0?void 0:Y.bind(q))!==null&&T!==void 0?T:(K)=>{},onReceiveMessage:(J=(X=q===null||q===void 0?void 0:q.onReceiveMessage)===null||X===void 0?void 0:X.bind(q))!==null&&J!==void 0?J:(K)=>{},onReceiveStatus:(U=(Q=q===null||q===void 0?void 0:q.onReceiveStatus)===null||Q===void 0?void 0:Q.bind(q))!==null&&U!==void 0?U:(K)=>{}};this.processingMetadata=!0,this.requester.start($,Z,(K,A)=>{var W,G,V;this.processingMetadata=!1;let F;if((0,OU.isInterceptingListener)(A))F=A;else{let N={onReceiveMetadata:(W=A.onReceiveMetadata)!==null&&W!==void 0?W:u9.onReceiveMetadata,onReceiveMessage:(G=A.onReceiveMessage)!==null&&G!==void 0?G:u9.onReceiveMessage,onReceiveStatus:(V=A.onReceiveStatus)!==null&&V!==void 0?V:u9.onReceiveStatus};F=new OU.InterceptingListenerImpl(N,Z)}this.nextCall.start(K,F),this.processPendingMessage(),this.processPendingHalfClose()})}sendMessageWithContext($,q){this.processingMessage=!0,this.requester.sendMessage(q,(Y)=>{if(this.processingMessage=!1,this.processingMetadata)this.pendingMessageContext=$,this.pendingMessage=q;else this.nextCall.sendMessageWithContext($,Y),this.processPendingHalfClose()})}sendMessage($){this.sendMessageWithContext({},$)}startRead(){this.nextCall.startRead()}halfClose(){this.requester.halfClose(()=>{if(this.processingMetadata||this.processingMessage)this.pendingHalfClose=!0;else this.nextCall.halfClose()})}getAuthContext(){return this.nextCall.getAuthContext()}}xU.InterceptingCall=yU;function XN($,q,Y){var T,X;let J=(T=Y.deadline)!==null&&T!==void 0?T:1/0,Q=Y.host,U=(X=Y.parent)!==null&&X!==void 0?X:null,Z=Y.propagate_flags,K=Y.credentials,A=$.createCall(q,J,Q,U,Z);if(K)A.setCredentials(K);return A}class d9{constructor($,q){this.call=$,this.methodDefinition=q}cancelWithStatus($,q){this.call.cancelWithStatus($,q)}getPeer(){return this.call.getPeer()}sendMessageWithContext($,q){let Y;try{Y=this.methodDefinition.requestSerialize(q)}catch(T){this.call.cancelWithStatus(LU.Status.INTERNAL,`Request message serialization failure: ${(0,wU.getErrorMessage)(T)}`);return}this.call.sendMessageWithContext($,Y)}sendMessage($){this.sendMessageWithContext({},$)}start($,q){let Y=null;this.call.start($,{onReceiveMetadata:(T)=>{var X;(X=q===null||q===void 0?void 0:q.onReceiveMetadata)===null||X===void 0||X.call(q,T)},onReceiveMessage:(T)=>{var X;let J;try{J=this.methodDefinition.responseDeserialize(T)}catch(Q){Y={code:LU.Status.INTERNAL,details:`Response message parsing error: ${(0,wU.getErrorMessage)(Q)}`,metadata:new TN.Metadata},this.call.cancelWithStatus(Y.code,Y.details);return}(X=q===null||q===void 0?void 0:q.onReceiveMessage)===null||X===void 0||X.call(q,J)},onReceiveStatus:(T)=>{var X,J;if(Y)(X=q===null||q===void 0?void 0:q.onReceiveStatus)===null||X===void 0||X.call(q,Y);else(J=q===null||q===void 0?void 0:q.onReceiveStatus)===null||J===void 0||J.call(q,T)}})}startRead(){this.call.startRead()}halfClose(){this.call.halfClose()}getAuthContext(){return this.call.getAuthContext()}}class jU extends d9{constructor($,q){super($,q)}start($,q){var Y,T;let X=!1,J={onReceiveMetadata:(T=(Y=q===null||q===void 0?void 0:q.onReceiveMetadata)===null||Y===void 0?void 0:Y.bind(q))!==null&&T!==void 0?T:(Q)=>{},onReceiveMessage:(Q)=>{var U;X=!0,(U=q===null||q===void 0?void 0:q.onReceiveMessage)===null||U===void 0||U.call(q,Q)},onReceiveStatus:(Q)=>{var U,Z;if(!X)(U=q===null||q===void 0?void 0:q.onReceiveMessage)===null||U===void 0||U.call(q,null);(Z=q===null||q===void 0?void 0:q.onReceiveStatus)===null||Z===void 0||Z.call(q,Q)}};super.start($,J),this.call.startRead()}}class vU extends d9{}function JN($,q,Y){let T=XN($,Y.path,q);if(Y.responseStream)return new vU(T,Y);else return new jU(T,Y)}function QN($,q,Y,T){if($.clientInterceptors.length>0&&$.clientInterceptorProviders.length>0)throw new IY("Both interceptors and interceptor_providers were passed as options to the client constructor. Only one of these is allowed.");if($.callInterceptors.length>0&&$.callInterceptorProviders.length>0)throw new IY("Both interceptors and interceptor_providers were passed as call options. Only one of these is allowed.");let X=[];if($.callInterceptors.length>0||$.callInterceptorProviders.length>0)X=[].concat($.callInterceptors,$.callInterceptorProviders.map((U)=>U(q))).filter((U)=>U);else X=[].concat($.clientInterceptors,$.clientInterceptorProviders.map((U)=>U(q))).filter((U)=>U);let J=Object.assign({},Y,{method_definition:q});return X.reduceRight((U,Z)=>{return(K)=>Z(K,U)},(U)=>JN(T,U,q))(J)}});var l9=B((_U)=>{Object.defineProperty(_U,"__esModule",{value:!0});_U.Client=void 0;var v1=MU(),WN=n9(),GN=l0(),D$=n(),Iq=P0(),a6=c9(),M1=Symbol(),Nq=Symbol(),Hq=Symbol(),t1=Symbol();function p9($){return typeof $==="function"}function zq($){var q;return((q=$.stack)===null||q===void 0?void 0:q.split(`
4
- `).slice(1).join(`
5
- `))||"no stack trace available"}class hU{constructor($,q,Y={}){var T,X;if(Y=Object.assign({},Y),this[Nq]=(T=Y.interceptors)!==null&&T!==void 0?T:[],delete Y.interceptors,this[Hq]=(X=Y.interceptor_providers)!==null&&X!==void 0?X:[],delete Y.interceptor_providers,this[Nq].length>0&&this[Hq].length>0)throw Error("Both interceptors and interceptor_providers were passed as options to the client constructor. Only one of these is allowed.");if(this[t1]=Y.callInvocationTransformer,delete Y.callInvocationTransformer,Y.channelOverride)this[M1]=Y.channelOverride;else if(Y.channelFactoryOverride){let J=Y.channelFactoryOverride;delete Y.channelFactoryOverride,this[M1]=J($,q,Y)}else this[M1]=new WN.ChannelImplementation($,q,Y)}close(){this[M1].close()}getChannel(){return this[M1]}waitForReady($,q){let Y=(T)=>{if(T){q(Error("Failed to connect before the deadline"));return}let X;try{X=this[M1].getConnectivityState(!0)}catch(J){q(Error("The channel has been closed"));return}if(X===GN.ConnectivityState.READY)q();else try{this[M1].watchConnectivityState(X,$,Y)}catch(J){q(Error("The channel has been closed"))}};setImmediate(Y)}checkOptionalUnaryResponseArguments($,q,Y){if(p9($))return{metadata:new Iq.Metadata,options:{},callback:$};else if(p9(q))if($ instanceof Iq.Metadata)return{metadata:$,options:{},callback:q};else return{metadata:new Iq.Metadata,options:$,callback:q};else{if(!($ instanceof Iq.Metadata&&q instanceof Object&&p9(Y)))throw Error("Incorrect arguments passed");return{metadata:$,options:q,callback:Y}}}makeUnaryRequest($,q,Y,T,X,J,Q){var U,Z;let K=this.checkOptionalUnaryResponseArguments(X,J,Q),A={path:$,requestStream:!1,responseStream:!1,requestSerialize:q,responseDeserialize:Y},W={argument:T,metadata:K.metadata,call:new v1.ClientUnaryCallImpl,channel:this[M1],methodDefinition:A,callOptions:K.options,callback:K.callback};if(this[t1])W=this[t1](W);let G=W.call,V={clientInterceptors:this[Nq],clientInterceptorProviders:this[Hq],callInterceptors:(U=W.callOptions.interceptors)!==null&&U!==void 0?U:[],callInterceptorProviders:(Z=W.callOptions.interceptor_providers)!==null&&Z!==void 0?Z:[]},F=(0,a6.getInterceptingCall)(V,W.methodDefinition,W.callOptions,W.channel);G.call=F;let N=null,D=!1,z=Error();return F.start(W.metadata,{onReceiveMetadata:(S)=>{G.emit("metadata",S)},onReceiveMessage(S){if(N!==null)F.cancelWithStatus(D$.Status.UNIMPLEMENTED,"Too many responses received");N=S},onReceiveStatus(S){if(D)return;if(D=!0,S.code===D$.Status.OK)if(N===null){let v=zq(z);W.callback((0,v1.callErrorFromStatus)({code:D$.Status.UNIMPLEMENTED,details:"No message received",metadata:S.metadata},v))}else W.callback(null,N);else{let v=zq(z);W.callback((0,v1.callErrorFromStatus)(S,v))}z=null,G.emit("status",S)}}),F.sendMessage(T),F.halfClose(),G}makeClientStreamRequest($,q,Y,T,X,J){var Q,U;let Z=this.checkOptionalUnaryResponseArguments(T,X,J),K={path:$,requestStream:!0,responseStream:!1,requestSerialize:q,responseDeserialize:Y},A={metadata:Z.metadata,call:new v1.ClientWritableStreamImpl(q),channel:this[M1],methodDefinition:K,callOptions:Z.options,callback:Z.callback};if(this[t1])A=this[t1](A);let W=A.call,G={clientInterceptors:this[Nq],clientInterceptorProviders:this[Hq],callInterceptors:(Q=A.callOptions.interceptors)!==null&&Q!==void 0?Q:[],callInterceptorProviders:(U=A.callOptions.interceptor_providers)!==null&&U!==void 0?U:[]},V=(0,a6.getInterceptingCall)(G,A.methodDefinition,A.callOptions,A.channel);W.call=V;let F=null,N=!1,D=Error();return V.start(A.metadata,{onReceiveMetadata:(z)=>{W.emit("metadata",z)},onReceiveMessage(z){if(F!==null)V.cancelWithStatus(D$.Status.UNIMPLEMENTED,"Too many responses received");F=z,V.startRead()},onReceiveStatus(z){if(N)return;if(N=!0,z.code===D$.Status.OK)if(F===null){let S=zq(D);A.callback((0,v1.callErrorFromStatus)({code:D$.Status.UNIMPLEMENTED,details:"No message received",metadata:z.metadata},S))}else A.callback(null,F);else{let S=zq(D);A.callback((0,v1.callErrorFromStatus)(z,S))}D=null,W.emit("status",z)}}),W}checkMetadataAndOptions($,q){let Y,T;if($ instanceof Iq.Metadata)if(Y=$,q)T=q;else T={};else{if($)T=$;else T={};Y=new Iq.Metadata}return{metadata:Y,options:T}}makeServerStreamRequest($,q,Y,T,X,J){var Q,U;let Z=this.checkMetadataAndOptions(X,J),K={path:$,requestStream:!1,responseStream:!0,requestSerialize:q,responseDeserialize:Y},A={argument:T,metadata:Z.metadata,call:new v1.ClientReadableStreamImpl(Y),channel:this[M1],methodDefinition:K,callOptions:Z.options};if(this[t1])A=this[t1](A);let W=A.call,G={clientInterceptors:this[Nq],clientInterceptorProviders:this[Hq],callInterceptors:(Q=A.callOptions.interceptors)!==null&&Q!==void 0?Q:[],callInterceptorProviders:(U=A.callOptions.interceptor_providers)!==null&&U!==void 0?U:[]},V=(0,a6.getInterceptingCall)(G,A.methodDefinition,A.callOptions,A.channel);W.call=V;let F=!1,N=Error();return V.start(A.metadata,{onReceiveMetadata(D){W.emit("metadata",D)},onReceiveMessage(D){W.push(D)},onReceiveStatus(D){if(F)return;if(F=!0,W.push(null),D.code!==D$.Status.OK){let z=zq(N);W.emit("error",(0,v1.callErrorFromStatus)(D,z))}N=null,W.emit("status",D)}}),V.sendMessage(T),V.halfClose(),W}makeBidiStreamRequest($,q,Y,T,X){var J,Q;let U=this.checkMetadataAndOptions(T,X),Z={path:$,requestStream:!0,responseStream:!0,requestSerialize:q,responseDeserialize:Y},K={metadata:U.metadata,call:new v1.ClientDuplexStreamImpl(q,Y),channel:this[M1],methodDefinition:Z,callOptions:U.options};if(this[t1])K=this[t1](K);let A=K.call,W={clientInterceptors:this[Nq],clientInterceptorProviders:this[Hq],callInterceptors:(J=K.callOptions.interceptors)!==null&&J!==void 0?J:[],callInterceptorProviders:(Q=K.callOptions.interceptor_providers)!==null&&Q!==void 0?Q:[]},G=(0,a6.getInterceptingCall)(W,K.methodDefinition,K.callOptions,K.channel);A.call=G;let V=!1,F=Error();return G.start(K.metadata,{onReceiveMetadata(N){A.emit("metadata",N)},onReceiveMessage(N){A.push(N)},onReceiveStatus(N){if(V)return;if(V=!0,A.push(null),N.code!==D$.Status.OK){let D=zq(F);A.emit("error",(0,v1.callErrorFromStatus)(N,D))}F=null,A.emit("status",N)}}),A}}_U.Client=hU});var o6=B((fU)=>{Object.defineProperty(fU,"__esModule",{value:!0});fU.makeClientConstructor=mU;fU.loadPackageDefinition=FN;var NY=l9(),EN={unary:NY.Client.prototype.makeUnaryRequest,server_stream:NY.Client.prototype.makeServerStreamRequest,client_stream:NY.Client.prototype.makeClientStreamRequest,bidi:NY.Client.prototype.makeBidiStreamRequest};function i9($){return["__proto__","prototype","constructor"].includes($)}function mU($,q,Y){if(!Y)Y={};class T extends NY.Client{}return Object.keys($).forEach((X)=>{if(i9(X))return;let J=$[X],Q;if(typeof X==="string"&&X.charAt(0)==="$")throw Error("Method names cannot start with $");if(J.requestStream)if(J.responseStream)Q="bidi";else Q="client_stream";else if(J.responseStream)Q="server_stream";else Q="unary";let{requestSerialize:U,responseDeserialize:Z}=J,K=VN(EN[Q],J.path,U,Z);if(T.prototype[X]=K,Object.assign(T.prototype[X],J),J.originalName&&!i9(J.originalName))T.prototype[J.originalName]=T.prototype[X]}),T.service=$,T.serviceName=q,T}function VN($,q,Y,T){return function(...X){return $.call(this,q,Y,T,...X)}}function DN($){return"format"in $}function FN($){let q={};for(let Y in $)if(Object.prototype.hasOwnProperty.call($,Y)){let T=$[Y],X=Y.split(".");if(X.some((U)=>i9(U)))continue;let J=X[X.length-1],Q=q;for(let U of X.slice(0,-1)){if(!Q[U])Q[U]={};Q=Q[U]}if(DN(T))Q[J]=T;else Q[J]=mU(T,J,{})}return q}});var A7=B((wv,K7)=>{var HN=1/0,zN="[object Symbol]",MN=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,BN=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,t6="\\ud800-\\udfff",iU="\\u0300-\\u036f\\ufe20-\\ufe23",rU="\\u20d0-\\u20f0",aU="\\u2700-\\u27bf",oU="a-z\\xdf-\\xf6\\xf8-\\xff",RN="\\xac\\xb1\\xd7\\xf7",PN="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",ON="\\u2000-\\u206f",LN=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",sU="A-Z\\xc0-\\xd6\\xd8-\\xde",tU="\\ufe0e\\ufe0f",eU=RN+PN+ON+LN,a9="['’]",wN="["+t6+"]",bU="["+eU+"]",s6="["+iU+rU+"]",$7="\\d+",SN="["+aU+"]",q7="["+oU+"]",Y7="[^"+t6+eU+$7+aU+oU+sU+"]",r9="\\ud83c[\\udffb-\\udfff]",CN="(?:"+s6+"|"+r9+")",T7="[^"+t6+"]",o9="(?:\\ud83c[\\udde6-\\uddff]){2}",s9="[\\ud800-\\udbff][\\udc00-\\udfff]",Mq="["+sU+"]",X7="\\u200d",uU="(?:"+q7+"|"+Y7+")",yN="(?:"+Mq+"|"+Y7+")",dU="(?:"+a9+"(?:d|ll|m|re|s|t|ve))?",cU="(?:"+a9+"(?:D|LL|M|RE|S|T|VE))?",J7=CN+"?",Q7="["+tU+"]?",jN="(?:"+X7+"(?:"+[T7,o9,s9].join("|")+")"+Q7+J7+")*",U7=Q7+J7+jN,vN="(?:"+[SN,o9,s9].join("|")+")"+U7,xN="(?:"+[T7+s6+"?",s6,o9,s9,wN].join("|")+")",kN=RegExp(a9,"g"),hN=RegExp(s6,"g"),_N=RegExp(r9+"(?="+r9+")|"+xN+U7,"g"),gN=RegExp([Mq+"?"+q7+"+"+dU+"(?="+[bU,Mq,"$"].join("|")+")",yN+"+"+cU+"(?="+[bU,Mq+uU,"$"].join("|")+")",Mq+"?"+uU+"+"+dU,Mq+"+"+cU,$7,vN].join("|"),"g"),mN=RegExp("["+X7+t6+iU+rU+tU+"]"),fN=/[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,bN={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"ss"},uN=typeof global=="object"&&global&&global.Object===Object&&global,dN=typeof self=="object"&&self&&self.Object===Object&&self,cN=uN||dN||Function("return this")();function pN($,q,Y,T){var X=-1,J=$?$.length:0;if(T&&J)Y=$[++X];while(++X<J)Y=q(Y,$[X],X,$);return Y}function lN($){return $.split("")}function nN($){return $.match(MN)||[]}function iN($){return function(q){return $==null?void 0:$[q]}}var rN=iN(bN);function Z7($){return mN.test($)}function aN($){return fN.test($)}function oN($){return Z7($)?sN($):lN($)}function sN($){return $.match(_N)||[]}function tN($){return $.match(gN)||[]}var eN=Object.prototype,$H=eN.toString,pU=cN.Symbol,lU=pU?pU.prototype:void 0,nU=lU?lU.toString:void 0;function qH($,q,Y){var T=-1,X=$.length;if(q<0)q=-q>X?0:X+q;if(Y=Y>X?X:Y,Y<0)Y+=X;X=q>Y?0:Y-q>>>0,q>>>=0;var J=Array(X);while(++T<X)J[T]=$[T+q];return J}function YH($){if(typeof $=="string")return $;if(UH($))return nU?nU.call($):"";var q=$+"";return q=="0"&&1/$==-HN?"-0":q}function TH($,q,Y){var T=$.length;return Y=Y===void 0?T:Y,!q&&Y>=T?$:qH($,q,Y)}function XH($){return function(q){q=e6(q);var Y=Z7(q)?oN(q):void 0,T=Y?Y[0]:q.charAt(0),X=Y?TH(Y,1).join(""):q.slice(1);return T[$]()+X}}function JH($){return function(q){return pN(GH(AH(q).replace(kN,"")),$,"")}}function QH($){return!!$&&typeof $=="object"}function UH($){return typeof $=="symbol"||QH($)&&$H.call($)==zN}function e6($){return $==null?"":YH($)}var ZH=JH(function($,q,Y){return q=q.toLowerCase(),$+(Y?KH(q):q)});function KH($){return WH(e6($).toLowerCase())}function AH($){return $=e6($),$&&$.replace(BN,rN).replace(hN,"")}var WH=XH("toUpperCase");function GH($,q,Y){if($=e6($),q=Y?void 0:q,q===void 0)return aN($)?tN($):nN($);return $.match(q)||[]}K7.exports=ZH});var t9=B((Sv,W7)=>{W7.exports=EH;function EH($,q){var Y=Array(arguments.length-1),T=0,X=2,J=!0;while(X<arguments.length)Y[T++]=arguments[X++];return new Promise(function(U,Z){Y[T]=function(A){if(J)if(J=!1,A)Z(A);else{var W=Array(arguments.length-1),G=0;while(G<W.length)W[G++]=arguments[G];U.apply(null,W)}};try{$.apply(q||null,Y)}catch(K){if(J)J=!1,Z(K)}})}});var D7=B((V7)=>{var $T=V7;$T.length=function(q){var Y=q.length;if(!Y)return 0;var T=0;while(--Y%4>1&&q.charAt(Y)==="=")++T;return Math.ceil(q.length*3)/4-T};var Bq=Array(64),E7=Array(123);for(Q1=0;Q1<64;)E7[Bq[Q1]=Q1<26?Q1+65:Q1<52?Q1+71:Q1<62?Q1-4:Q1-59|43]=Q1++;var Q1;$T.encode=function(q,Y,T){var X=null,J=[],Q=0,U=0,Z;while(Y<T){var K=q[Y++];switch(U){case 0:J[Q++]=Bq[K>>2],Z=(K&3)<<4,U=1;break;case 1:J[Q++]=Bq[Z|K>>4],Z=(K&15)<<2,U=2;break;case 2:J[Q++]=Bq[Z|K>>6],J[Q++]=Bq[K&63],U=0;break}if(Q>8191)(X||(X=[])).push(String.fromCharCode.apply(String,J)),Q=0}if(U){if(J[Q++]=Bq[Z],J[Q++]=61,U===1)J[Q++]=61}if(X){if(Q)X.push(String.fromCharCode.apply(String,J.slice(0,Q)));return X.join("")}return String.fromCharCode.apply(String,J.slice(0,Q))};var G7="invalid encoding";$T.decode=function(q,Y,T){var X=T,J=0,Q;for(var U=0;U<q.length;){var Z=q.charCodeAt(U++);if(Z===61&&J>1)break;if((Z=E7[Z])===void 0)throw Error(G7);switch(J){case 0:Q=Z,J=1;break;case 1:Y[T++]=Q<<2|(Z&48)>>4,Q=Z,J=2;break;case 2:Y[T++]=(Q&15)<<4|(Z&60)>>2,Q=Z,J=3;break;case 3:Y[T++]=(Q&3)<<6|Z,J=0;break}}if(J===1)throw Error(G7);return T-X};$T.test=function(q){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(q)}});var I7=B((yv,F7)=>{F7.exports=qT;function qT(){this._listeners={}}qT.prototype.on=function(q,Y,T){return(this._listeners[q]||(this._listeners[q]=[])).push({fn:Y,ctx:T||this}),this};qT.prototype.off=function(q,Y){if(q===void 0)this._listeners={};else if(Y===void 0)this._listeners[q]=[];else{var T=this._listeners[q];for(var X=0;X<T.length;)if(T[X].fn===Y)T.splice(X,1);else++X}return this};qT.prototype.emit=function(q){var Y=this._listeners[q];if(Y){var T=[],X=1;for(;X<arguments.length;)T.push(arguments[X++]);for(X=0;X<Y.length;)Y[X].fn.apply(Y[X++].ctx,T)}return this}});var P7=B((jv,R7)=>{R7.exports=N7(N7);function N7($){if(typeof Float32Array<"u")(function(){var q=new Float32Array([-0]),Y=new Uint8Array(q.buffer),T=Y[3]===128;function X(Z,K,A){q[0]=Z,K[A]=Y[0],K[A+1]=Y[1],K[A+2]=Y[2],K[A+3]=Y[3]}function J(Z,K,A){q[0]=Z,K[A]=Y[3],K[A+1]=Y[2],K[A+2]=Y[1],K[A+3]=Y[0]}$.writeFloatLE=T?X:J,$.writeFloatBE=T?J:X;function Q(Z,K){return Y[0]=Z[K],Y[1]=Z[K+1],Y[2]=Z[K+2],Y[3]=Z[K+3],q[0]}function U(Z,K){return Y[3]=Z[K],Y[2]=Z[K+1],Y[1]=Z[K+2],Y[0]=Z[K+3],q[0]}$.readFloatLE=T?Q:U,$.readFloatBE=T?U:Q})();else(function(){function q(T,X,J,Q){var U=X<0?1:0;if(U)X=-X;if(X===0)T(1/X>0?0:2147483648,J,Q);else if(isNaN(X))T(2143289344,J,Q);else if(X>340282346638528860000000000000000000000)T((U<<31|2139095040)>>>0,J,Q);else if(X<0.000000000000000000000000000000000000011754943508222875)T((U<<31|Math.round(X/0.000000000000000000000000000000000000000000001401298464324817))>>>0,J,Q);else{var Z=Math.floor(Math.log(X)/Math.LN2),K=Math.round(X*Math.pow(2,-Z)*8388608)&8388607;T((U<<31|Z+127<<23|K)>>>0,J,Q)}}$.writeFloatLE=q.bind(null,H7),$.writeFloatBE=q.bind(null,z7);function Y(T,X,J){var Q=T(X,J),U=(Q>>31)*2+1,Z=Q>>>23&255,K=Q&8388607;return Z===255?K?NaN:U*(1/0):Z===0?U*0.000000000000000000000000000000000000000000001401298464324817*K:U*Math.pow(2,Z-150)*(K+8388608)}$.readFloatLE=Y.bind(null,M7),$.readFloatBE=Y.bind(null,B7)})();if(typeof Float64Array<"u")(function(){var q=new Float64Array([-0]),Y=new Uint8Array(q.buffer),T=Y[7]===128;function X(Z,K,A){q[0]=Z,K[A]=Y[0],K[A+1]=Y[1],K[A+2]=Y[2],K[A+3]=Y[3],K[A+4]=Y[4],K[A+5]=Y[5],K[A+6]=Y[6],K[A+7]=Y[7]}function J(Z,K,A){q[0]=Z,K[A]=Y[7],K[A+1]=Y[6],K[A+2]=Y[5],K[A+3]=Y[4],K[A+4]=Y[3],K[A+5]=Y[2],K[A+6]=Y[1],K[A+7]=Y[0]}$.writeDoubleLE=T?X:J,$.writeDoubleBE=T?J:X;function Q(Z,K){return Y[0]=Z[K],Y[1]=Z[K+1],Y[2]=Z[K+2],Y[3]=Z[K+3],Y[4]=Z[K+4],Y[5]=Z[K+5],Y[6]=Z[K+6],Y[7]=Z[K+7],q[0]}function U(Z,K){return Y[7]=Z[K],Y[6]=Z[K+1],Y[5]=Z[K+2],Y[4]=Z[K+3],Y[3]=Z[K+4],Y[2]=Z[K+5],Y[1]=Z[K+6],Y[0]=Z[K+7],q[0]}$.readDoubleLE=T?Q:U,$.readDoubleBE=T?U:Q})();else(function(){function q(T,X,J,Q,U,Z){var K=Q<0?1:0;if(K)Q=-Q;if(Q===0)T(0,U,Z+X),T(1/Q>0?0:2147483648,U,Z+J);else if(isNaN(Q))T(0,U,Z+X),T(2146959360,U,Z+J);else if(Q>179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000)T(0,U,Z+X),T((K<<31|2146435072)>>>0,U,Z+J);else{var A;if(Q<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000022250738585072014)A=Q/0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005,T(A>>>0,U,Z+X),T((K<<31|A/4294967296)>>>0,U,Z+J);else{var W=Math.floor(Math.log(Q)/Math.LN2);if(W===1024)W=1023;A=Q*Math.pow(2,-W),T(A*4503599627370496>>>0,U,Z+X),T((K<<31|W+1023<<20|A*1048576&1048575)>>>0,U,Z+J)}}}$.writeDoubleLE=q.bind(null,H7,0,4),$.writeDoubleBE=q.bind(null,z7,4,0);function Y(T,X,J,Q,U){var Z=T(Q,U+X),K=T(Q,U+J),A=(K>>31)*2+1,W=K>>>20&2047,G=4294967296*(K&1048575)+Z;return W===2047?G?NaN:A*(1/0):W===0?A*0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005*G:A*Math.pow(2,W-1075)*(G+4503599627370496)}$.readDoubleLE=Y.bind(null,M7,0,4),$.readDoubleBE=Y.bind(null,B7,4,0)})();return $}function H7($,q,Y){q[Y]=$&255,q[Y+1]=$>>>8&255,q[Y+2]=$>>>16&255,q[Y+3]=$>>>24}function z7($,q,Y){q[Y]=$>>>24,q[Y+1]=$>>>16&255,q[Y+2]=$>>>8&255,q[Y+3]=$&255}function M7($,q){return($[q]|$[q+1]<<8|$[q+2]<<16|$[q+3]<<24)>>>0}function B7($,q){return($[q]<<24|$[q+1]<<16|$[q+2]<<8|$[q+3])>>>0}});var $4=B((O7,e9)=>{e9.exports=VH;function VH(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch($){}return null}});var w7=B((L7)=>{var q4=L7;q4.length=function(q){var Y=0,T=0;for(var X=0;X<q.length;++X)if(T=q.charCodeAt(X),T<128)Y+=1;else if(T<2048)Y+=2;else if((T&64512)===55296&&(q.charCodeAt(X+1)&64512)===56320)++X,Y+=4;else Y+=3;return Y};q4.read=function(q,Y,T){var X=T-Y;if(X<1)return"";var J=null,Q=[],U=0,Z;while(Y<T){if(Z=q[Y++],Z<128)Q[U++]=Z;else if(Z>191&&Z<224)Q[U++]=(Z&31)<<6|q[Y++]&63;else if(Z>239&&Z<365)Z=((Z&7)<<18|(q[Y++]&63)<<12|(q[Y++]&63)<<6|q[Y++]&63)-65536,Q[U++]=55296+(Z>>10),Q[U++]=56320+(Z&1023);else Q[U++]=(Z&15)<<12|(q[Y++]&63)<<6|q[Y++]&63;if(U>8191)(J||(J=[])).push(String.fromCharCode.apply(String,Q)),U=0}if(J){if(U)J.push(String.fromCharCode.apply(String,Q.slice(0,U)));return J.join("")}return String.fromCharCode.apply(String,Q.slice(0,U))};q4.write=function(q,Y,T){var X=T,J,Q;for(var U=0;U<q.length;++U)if(J=q.charCodeAt(U),J<128)Y[T++]=J;else if(J<2048)Y[T++]=J>>6|192,Y[T++]=J&63|128;else if((J&64512)===55296&&((Q=q.charCodeAt(U+1))&64512)===56320)J=65536+((J&1023)<<10)+(Q&1023),++U,Y[T++]=J>>18|240,Y[T++]=J>>12&63|128,Y[T++]=J>>6&63|128,Y[T++]=J&63|128;else Y[T++]=J>>12|224,Y[T++]=J>>6&63|128,Y[T++]=J&63|128;return T-X}});var C7=B((xv,S7)=>{S7.exports=DH;function DH($,q,Y){var T=Y||8192,X=T>>>1,J=null,Q=T;return function(Z){if(Z<1||Z>X)return $(Z);if(Q+Z>T)J=$(T),Q=0;var K=q.call(J,Q,Q+=Z);if(Q&7)Q=(Q|7)+1;return K}}});var j7=B((kv,y7)=>{y7.exports=O0;var HY=x1();function O0($,q){this.lo=$>>>0,this.hi=q>>>0}var f$=O0.zero=new O0(0,0);f$.toNumber=function(){return 0};f$.zzEncode=f$.zzDecode=function(){return this};f$.length=function(){return 1};var FH=O0.zeroHash="\x00\x00\x00\x00\x00\x00\x00\x00";O0.fromNumber=function(q){if(q===0)return f$;var Y=q<0;if(Y)q=-q;var T=q>>>0,X=(q-T)/4294967296>>>0;if(Y){if(X=~X>>>0,T=~T>>>0,++T>4294967295){if(T=0,++X>4294967295)X=0}}return new O0(T,X)};O0.from=function(q){if(typeof q==="number")return O0.fromNumber(q);if(HY.isString(q))if(HY.Long)q=HY.Long.fromString(q);else return O0.fromNumber(parseInt(q,10));return q.low||q.high?new O0(q.low>>>0,q.high>>>0):f$};O0.prototype.toNumber=function(q){if(!q&&this.hi>>>31){var Y=~this.lo+1>>>0,T=~this.hi>>>0;if(!Y)T=T+1>>>0;return-(Y+T*4294967296)}return this.lo+this.hi*4294967296};O0.prototype.toLong=function(q){return HY.Long?new HY.Long(this.lo|0,this.hi|0,Boolean(q)):{low:this.lo|0,high:this.hi|0,unsigned:Boolean(q)}};var F$=String.prototype.charCodeAt;O0.fromHash=function(q){if(q===FH)return f$;return new O0((F$.call(q,0)|F$.call(q,1)<<8|F$.call(q,2)<<16|F$.call(q,3)<<24)>>>0,(F$.call(q,4)|F$.call(q,5)<<8|F$.call(q,6)<<16|F$.call(q,7)<<24)>>>0)};O0.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)};O0.prototype.zzEncode=function(){var q=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^q)>>>0,this.lo=(this.lo<<1^q)>>>0,this};O0.prototype.zzDecode=function(){var q=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^q)>>>0,this.hi=(this.hi>>>1^q)>>>0,this};O0.prototype.length=function(){var q=this.lo,Y=(this.lo>>>28|this.hi<<4)>>>0,T=this.hi>>>24;return T===0?Y===0?q<16384?q<128?1:2:q<2097152?3:4:Y<16384?Y<128?5:6:Y<2097152?7:8:T<128?9:10}});var x1=B((Y4)=>{var g=Y4;g.asPromise=t9();g.base64=D7();g.EventEmitter=I7();g.float=P7();g.inquire=$4();g.utf8=w7();g.pool=C7();g.LongBits=j7();g.isNode=Boolean(typeof global<"u"&&global&&global.process&&global.process.versions&&global.process.versions.node);g.global=g.isNode&&global||typeof window<"u"&&window||typeof self<"u"&&self||Y4;g.emptyArray=Object.freeze?Object.freeze([]):[];g.emptyObject=Object.freeze?Object.freeze({}):{};g.isInteger=Number.isInteger||function(q){return typeof q==="number"&&isFinite(q)&&Math.floor(q)===q};g.isString=function(q){return typeof q==="string"||q instanceof String};g.isObject=function(q){return q&&typeof q==="object"};g.isset=g.isSet=function(q,Y){var T=q[Y];if(T!=null&&q.hasOwnProperty(Y))return typeof T!=="object"||(Array.isArray(T)?T.length:Object.keys(T).length)>0;return!1};g.Buffer=function(){try{var $=g.inquire("buffer").Buffer;return $.prototype.utf8Write?$:null}catch(q){return null}}();g._Buffer_from=null;g._Buffer_allocUnsafe=null;g.newBuffer=function(q){return typeof q==="number"?g.Buffer?g._Buffer_allocUnsafe(q):new g.Array(q):g.Buffer?g._Buffer_from(q):typeof Uint8Array>"u"?q:new Uint8Array(q)};g.Array=typeof Uint8Array<"u"?Uint8Array:Array;g.Long=g.global.dcodeIO&&g.global.dcodeIO.Long||g.global.Long||g.inquire("long");g.key2Re=/^true|false|0|1$/;g.key32Re=/^-?(?:0|[1-9][0-9]*)$/;g.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;g.longToHash=function(q){return q?g.LongBits.from(q).toHash():g.LongBits.zeroHash};g.longFromHash=function(q,Y){var T=g.LongBits.fromHash(q);if(g.Long)return g.Long.fromBits(T.lo,T.hi,Y);return T.toNumber(Boolean(Y))};function v7($,q,Y){for(var T=Object.keys(q),X=0;X<T.length;++X)if($[T[X]]===void 0||!Y)$[T[X]]=q[T[X]];return $}g.merge=v7;g.lcFirst=function(q){return q.charAt(0).toLowerCase()+q.substring(1)};function x7($){function q(Y,T){if(!(this instanceof q))return new q(Y,T);if(Object.defineProperty(this,"message",{get:function(){return Y}}),Error.captureStackTrace)Error.captureStackTrace(this,q);else Object.defineProperty(this,"stack",{value:Error().stack||""});if(T)v7(this,T)}return q.prototype=Object.create(Error.prototype,{constructor:{value:q,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return $},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),q}g.newError=x7;g.ProtocolError=x7("ProtocolError");g.oneOfGetter=function(q){var Y={};for(var T=0;T<q.length;++T)Y[q[T]]=1;return function(){for(var X=Object.keys(this),J=X.length-1;J>-1;--J)if(Y[X[J]]===1&&this[X[J]]!==void 0&&this[X[J]]!==null)return X[J]}};g.oneOfSetter=function(q){return function(Y){for(var T=0;T<q.length;++T)if(q[T]!==Y)delete this[q[T]]}};g.toJSONOptions={longs:String,enums:String,bytes:String,json:!0};g._configure=function(){var $=g.Buffer;if(!$){g._Buffer_from=g._Buffer_allocUnsafe=null;return}g._Buffer_from=$.from!==Uint8Array.from&&$.from||function(Y,T){return new $(Y,T)},g._Buffer_allocUnsafe=$.allocUnsafe||function(Y){return new $(Y)}}});var TT=B((_v,g7)=>{g7.exports=Y0;var U1=x1(),T4,YT=U1.LongBits,k7=U1.base64,h7=U1.utf8;function zY($,q,Y){this.fn=$,this.len=q,this.next=void 0,this.val=Y}function J4(){}function IH($){this.head=$.head,this.tail=$.tail,this.len=$.len,this.next=$.states}function Y0(){this.len=0,this.head=new zY(J4,0,0),this.tail=this.head,this.states=null}var _7=function(){return U1.Buffer?function(){return(Y0.create=function(){return new T4})()}:function(){return new Y0}};Y0.create=_7();Y0.alloc=function(q){return new U1.Array(q)};if(U1.Array!==Array)Y0.alloc=U1.pool(Y0.alloc,U1.Array.prototype.subarray);Y0.prototype._push=function(q,Y,T){return this.tail=this.tail.next=new zY(q,Y,T),this.len+=Y,this};function Q4($,q,Y){q[Y]=$&255}function NH($,q,Y){while($>127)q[Y++]=$&127|128,$>>>=7;q[Y]=$}function U4($,q){this.len=$,this.next=void 0,this.val=q}U4.prototype=Object.create(zY.prototype);U4.prototype.fn=NH;Y0.prototype.uint32=function(q){return this.len+=(this.tail=this.tail.next=new U4((q=q>>>0)<128?1:q<16384?2:q<2097152?3:q<268435456?4:5,q)).len,this};Y0.prototype.int32=function(q){return q<0?this._push(Z4,10,YT.fromNumber(q)):this.uint32(q)};Y0.prototype.sint32=function(q){return this.uint32((q<<1^q>>31)>>>0)};function Z4($,q,Y){while($.hi)q[Y++]=$.lo&127|128,$.lo=($.lo>>>7|$.hi<<25)>>>0,$.hi>>>=7;while($.lo>127)q[Y++]=$.lo&127|128,$.lo=$.lo>>>7;q[Y++]=$.lo}Y0.prototype.uint64=function(q){var Y=YT.from(q);return this._push(Z4,Y.length(),Y)};Y0.prototype.int64=Y0.prototype.uint64;Y0.prototype.sint64=function(q){var Y=YT.from(q).zzEncode();return this._push(Z4,Y.length(),Y)};Y0.prototype.bool=function(q){return this._push(Q4,1,q?1:0)};function X4($,q,Y){q[Y]=$&255,q[Y+1]=$>>>8&255,q[Y+2]=$>>>16&255,q[Y+3]=$>>>24}Y0.prototype.fixed32=function(q){return this._push(X4,4,q>>>0)};Y0.prototype.sfixed32=Y0.prototype.fixed32;Y0.prototype.fixed64=function(q){var Y=YT.from(q);return this._push(X4,4,Y.lo)._push(X4,4,Y.hi)};Y0.prototype.sfixed64=Y0.prototype.fixed64;Y0.prototype.float=function(q){return this._push(U1.float.writeFloatLE,4,q)};Y0.prototype.double=function(q){return this._push(U1.float.writeDoubleLE,8,q)};var HH=U1.Array.prototype.set?function(q,Y,T){Y.set(q,T)}:function(q,Y,T){for(var X=0;X<q.length;++X)Y[T+X]=q[X]};Y0.prototype.bytes=function(q){var Y=q.length>>>0;if(!Y)return this._push(Q4,1,0);if(U1.isString(q)){var T=Y0.alloc(Y=k7.length(q));k7.decode(q,T,0),q=T}return this.uint32(Y)._push(HH,Y,q)};Y0.prototype.string=function(q){var Y=h7.length(q);return Y?this.uint32(Y)._push(h7.write,Y,q):this._push(Q4,1,0)};Y0.prototype.fork=function(){return this.states=new IH(this),this.head=this.tail=new zY(J4,0,0),this.len=0,this};Y0.prototype.reset=function(){if(this.states)this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next;else this.head=this.tail=new zY(J4,0,0),this.len=0;return this};Y0.prototype.ldelim=function(){var q=this.head,Y=this.tail,T=this.len;if(this.reset().uint32(T),T)this.tail.next=q.next,this.tail=Y,this.len+=T;return this};Y0.prototype.finish=function(){var q=this.head.next,Y=this.constructor.alloc(this.len),T=0;while(q)q.fn(q.val,Y,T),T+=q.len,q=q.next;return Y};Y0._configure=function($){T4=$,Y0.create=_7(),T4._configure()}});var b7=B((gv,f7)=>{f7.exports=k1;var m7=TT();(k1.prototype=Object.create(m7.prototype)).constructor=k1;var I$=x1();function k1(){m7.call(this)}k1._configure=function(){k1.alloc=I$._Buffer_allocUnsafe,k1.writeBytesBuffer=I$.Buffer&&I$.Buffer.prototype instanceof Uint8Array&&I$.Buffer.prototype.set.name==="set"?function(q,Y,T){Y.set(q,T)}:function(q,Y,T){if(q.copy)q.copy(Y,T,0,q.length);else for(var X=0;X<q.length;)Y[T++]=q[X++]}};k1.prototype.bytes=function(q){if(I$.isString(q))q=I$._Buffer_from(q,"base64");var Y=q.length>>>0;if(this.uint32(Y),Y)this._push(k1.writeBytesBuffer,Y,q);return this};function zH($,q,Y){if($.length<40)I$.utf8.write($,q,Y);else if(q.utf8Write)q.utf8Write($,Y);else q.write($,Y)}k1.prototype.string=function(q){var Y=I$.Buffer.byteLength(q);if(this.uint32(Y),Y)this._push(zH,Y,q);return this};k1._configure()});var JT=B((mv,l7)=>{l7.exports=F0;var B1=x1(),A4,c7=B1.LongBits,MH=B1.utf8;function R1($,q){return RangeError("index out of range: "+$.pos+" + "+(q||1)+" > "+$.len)}function F0($){this.buf=$,this.pos=0,this.len=$.length}var u7=typeof Uint8Array<"u"?function(q){if(q instanceof Uint8Array||Array.isArray(q))return new F0(q);throw Error("illegal buffer")}:function(q){if(Array.isArray(q))return new F0(q);throw Error("illegal buffer")},p7=function(){return B1.Buffer?function(Y){return(F0.create=function(X){return B1.Buffer.isBuffer(X)?new A4(X):u7(X)})(Y)}:u7};F0.create=p7();F0.prototype._slice=B1.Array.prototype.subarray||B1.Array.prototype.slice;F0.prototype.uint32=function(){var q=4294967295;return function(){if(q=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128)return q;if(q=(q|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)return q;if(q=(q|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)return q;if(q=(q|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)return q;if(q=(q|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128)return q;if((this.pos+=5)>this.len)throw this.pos=this.len,R1(this,10);return q}}();F0.prototype.int32=function(){return this.uint32()|0};F0.prototype.sint32=function(){var q=this.uint32();return q>>>1^-(q&1)|0};function K4(){var $=new c7(0,0),q=0;if(this.len-this.pos>4){for(;q<4;++q)if($.lo=($.lo|(this.buf[this.pos]&127)<<q*7)>>>0,this.buf[this.pos++]<128)return $;if($.lo=($.lo|(this.buf[this.pos]&127)<<28)>>>0,$.hi=($.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return $;q=0}else{for(;q<3;++q){if(this.pos>=this.len)throw R1(this);if($.lo=($.lo|(this.buf[this.pos]&127)<<q*7)>>>0,this.buf[this.pos++]<128)return $}return $.lo=($.lo|(this.buf[this.pos++]&127)<<q*7)>>>0,$}if(this.len-this.pos>4){for(;q<5;++q)if($.hi=($.hi|(this.buf[this.pos]&127)<<q*7+3)>>>0,this.buf[this.pos++]<128)return $}else for(;q<5;++q){if(this.pos>=this.len)throw R1(this);if($.hi=($.hi|(this.buf[this.pos]&127)<<q*7+3)>>>0,this.buf[this.pos++]<128)return $}throw Error("invalid varint encoding")}F0.prototype.bool=function(){return this.uint32()!==0};function XT($,q){return($[q-4]|$[q-3]<<8|$[q-2]<<16|$[q-1]<<24)>>>0}F0.prototype.fixed32=function(){if(this.pos+4>this.len)throw R1(this,4);return XT(this.buf,this.pos+=4)};F0.prototype.sfixed32=function(){if(this.pos+4>this.len)throw R1(this,4);return XT(this.buf,this.pos+=4)|0};function d7(){if(this.pos+8>this.len)throw R1(this,8);return new c7(XT(this.buf,this.pos+=4),XT(this.buf,this.pos+=4))}F0.prototype.float=function(){if(this.pos+4>this.len)throw R1(this,4);var q=B1.float.readFloatLE(this.buf,this.pos);return this.pos+=4,q};F0.prototype.double=function(){if(this.pos+8>this.len)throw R1(this,4);var q=B1.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,q};F0.prototype.bytes=function(){var q=this.uint32(),Y=this.pos,T=this.pos+q;if(T>this.len)throw R1(this,q);if(this.pos+=q,Array.isArray(this.buf))return this.buf.slice(Y,T);if(Y===T){var X=B1.Buffer;return X?X.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,Y,T)};F0.prototype.string=function(){var q=this.bytes();return MH.read(q,0,q.length)};F0.prototype.skip=function(q){if(typeof q==="number"){if(this.pos+q>this.len)throw R1(this,q);this.pos+=q}else do if(this.pos>=this.len)throw R1(this);while(this.buf[this.pos++]&128);return this};F0.prototype.skipType=function($){switch($){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:while(($=this.uint32()&7)!==4)this.skipType($);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+$+" at offset "+this.pos)}return this};F0._configure=function($){A4=$,F0.create=p7(),A4._configure();var q=B1.Long?"toLong":"toNumber";B1.merge(F0.prototype,{int64:function(){return K4.call(this)[q](!1)},uint64:function(){return K4.call(this)[q](!0)},sint64:function(){return K4.call(this).zzDecode()[q](!1)},fixed64:function(){return d7.call(this)[q](!0)},sfixed64:function(){return d7.call(this)[q](!1)}})}});var a7=B((fv,r7)=>{r7.exports=b$;var i7=JT();(b$.prototype=Object.create(i7.prototype)).constructor=b$;var n7=x1();function b$($){i7.call(this,$)}b$._configure=function(){if(n7.Buffer)b$.prototype._slice=n7.Buffer.prototype.slice};b$.prototype.string=function(){var q=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+q,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+q,this.len))};b$._configure()});var s7=B((bv,o7)=>{o7.exports=MY;var W4=x1();(MY.prototype=Object.create(W4.EventEmitter.prototype)).constructor=MY;function MY($,q,Y){if(typeof $!=="function")throw TypeError("rpcImpl must be a function");W4.EventEmitter.call(this),this.rpcImpl=$,this.requestDelimited=Boolean(q),this.responseDelimited=Boolean(Y)}MY.prototype.rpcCall=function $(q,Y,T,X,J){if(!X)throw TypeError("request must be specified");var Q=this;if(!J)return W4.asPromise($,Q,q,Y,T,X);if(!Q.rpcImpl){setTimeout(function(){J(Error("already ended"))},0);return}try{return Q.rpcImpl(q,Y[Q.requestDelimited?"encodeDelimited":"encode"](X).finish(),function(Z,K){if(Z)return Q.emit("error",Z,q),J(Z);if(K===null){Q.end(!0);return}if(!(K instanceof T))try{K=T[Q.responseDelimited?"decodeDelimited":"decode"](K)}catch(A){return Q.emit("error",A,q),J(A)}return Q.emit("data",K,q),J(null,K)})}catch(U){Q.emit("error",U,q),setTimeout(function(){J(U)},0);return}};MY.prototype.end=function(q){if(this.rpcImpl){if(!q)this.rpcImpl(null,null,null);this.rpcImpl=null,this.emit("end").off()}return this}});var G4=B((t7)=>{var BH=t7;BH.Service=s7()});var E4=B((dv,e7)=>{e7.exports={}});var YZ=B((qZ)=>{var r0=qZ;r0.build="minimal";r0.Writer=TT();r0.BufferWriter=b7();r0.Reader=JT();r0.BufferReader=a7();r0.util=x1();r0.rpc=G4();r0.roots=E4();r0.configure=$Z;function $Z(){r0.util._configure(),r0.Writer._configure(r0.BufferWriter),r0.Reader._configure(r0.BufferReader)}$Z()});var XZ=B((pv,TZ)=>{TZ.exports=V4;function V4($,q){if(typeof $==="string")q=$,$=void 0;var Y=[];function T(J){if(typeof J!=="string"){var Q=X();if(V4.verbose)console.log("codegen: "+Q);if(Q="return "+Q,J){var U=Object.keys(J),Z=Array(U.length+1),K=Array(U.length),A=0;while(A<U.length)Z[A]=U[A],K[A]=J[U[A++]];return Z[A]=Q,Function.apply(null,Z).apply(null,K)}return Function(Q)()}var W=Array(arguments.length-1),G=0;while(G<W.length)W[G]=arguments[++G];if(G=0,J=J.replace(/%([%dfijs])/g,function(F,N){var D=W[G++];switch(N){case"d":case"f":return String(Number(D));case"i":return String(Math.floor(D));case"j":return JSON.stringify(D);case"s":return String(D)}return"%"}),G!==W.length)throw Error("parameter count mismatch");return Y.push(J),T}function X(J){return"function "+(J||q||"")+"("+($&&$.join(",")||"")+`){
6
- `+Y.join(`
7
- `)+`
8
- }`}return T.toString=X,T}V4.verbose=!1});var QZ=B((lv,JZ)=>{JZ.exports=BY;var RH=t9(),PH=$4(),D4=PH("fs");function BY($,q,Y){if(typeof q==="function")Y=q,q={};else if(!q)q={};if(!Y)return RH(BY,this,$,q);if(!q.xhr&&D4&&D4.readFile)return D4.readFile($,function(X,J){return X&&typeof XMLHttpRequest<"u"?BY.xhr($,q,Y):X?Y(X):Y(null,q.binary?J:J.toString("utf8"))});return BY.xhr($,q,Y)}BY.xhr=function(q,Y,T){var X=new XMLHttpRequest;if(X.onreadystatechange=function(){if(X.readyState!==4)return;if(X.status!==0&&X.status!==200)return T(Error("status "+X.status));if(Y.binary){var Q=X.response;if(!Q){Q=[];for(var U=0;U<X.responseText.length;++U)Q.push(X.responseText.charCodeAt(U)&255)}return T(null,typeof Uint8Array<"u"?new Uint8Array(Q):Q)}return T(null,X.responseText)},Y.binary){if("overrideMimeType"in X)X.overrideMimeType("text/plain; charset=x-user-defined");X.responseType="arraybuffer"}X.open("GET",q),X.send()}});var KZ=B((ZZ)=>{var I4=ZZ,UZ=I4.isAbsolute=function(q){return/^(?:\/|\w+:)/.test(q)},F4=I4.normalize=function(q){q=q.replace(/\\/g,"/").replace(/\/{2,}/g,"/");var Y=q.split("/"),T=UZ(q),X="";if(T)X=Y.shift()+"/";for(var J=0;J<Y.length;)if(Y[J]==="..")if(J>0&&Y[J-1]!=="..")Y.splice(--J,2);else if(T)Y.splice(J,1);else++J;else if(Y[J]===".")Y.splice(J,1);else++J;return X+Y.join("/")};I4.resolve=function(q,Y,T){if(!T)Y=F4(Y);if(UZ(Y))return Y;if(!T)q=F4(q);return(q=q.replace(/(?:\/|^)[^/]+$/,"")).length?F4(q+"/"+Y):Y}});var Pq=B((iv,GZ)=>{GZ.exports=$0;var QT=H$();(($0.prototype=Object.create(QT.prototype)).constructor=$0).className="Namespace";var N4=N$(),UT=L0(),OH=c$(),u$,Rq,d$;$0.fromJSON=function(q,Y){return new $0(q,Y.options).addJSON(Y.nested)};function AZ($,q){if(!($&&$.length))return;var Y={};for(var T=0;T<$.length;++T)Y[$[T].name]=$[T].toJSON(q);return Y}$0.arrayToJSON=AZ;$0.isReservedId=function(q,Y){if(q){for(var T=0;T<q.length;++T)if(typeof q[T]!=="string"&&q[T][0]<=Y&&q[T][1]>Y)return!0}return!1};$0.isReservedName=function(q,Y){if(q){for(var T=0;T<q.length;++T)if(q[T]===Y)return!0}return!1};function $0($,q){QT.call(this,$,q),this.nested=void 0,this._nestedArray=null,this._lookupCache={},this._needsRecursiveFeatureResolution=!0,this._needsRecursiveResolve=!0}function WZ($){$._nestedArray=null,$._lookupCache={};var q=$;while(q=q.parent)q._lookupCache={};return $}Object.defineProperty($0.prototype,"nestedArray",{get:function(){return this._nestedArray||(this._nestedArray=UT.toArray(this.nested))}});$0.prototype.toJSON=function(q){return UT.toObject(["options",this.options,"nested",AZ(this.nestedArray,q)])};$0.prototype.addJSON=function(q){var Y=this;if(q)for(var T=Object.keys(q),X=0,J;X<T.length;++X)J=q[T[X]],Y.add((J.fields!==void 0?u$.fromJSON:J.values!==void 0?d$.fromJSON:J.methods!==void 0?Rq.fromJSON:J.id!==void 0?N4.fromJSON:$0.fromJSON)(T[X],J));return this};$0.prototype.get=function(q){return this.nested&&this.nested[q]||null};$0.prototype.getEnum=function(q){if(this.nested&&this.nested[q]instanceof d$)return this.nested[q].values;throw Error("no such enum: "+q)};$0.prototype.add=function(q){if(!(q instanceof N4&&q.extend!==void 0||q instanceof u$||q instanceof OH||q instanceof d$||q instanceof Rq||q instanceof $0))throw TypeError("object must be a valid nested object");if(!this.nested)this.nested={};else{var Y=this.get(q.name);if(Y)if(Y instanceof $0&&q instanceof $0&&!(Y instanceof u$||Y instanceof Rq)){var T=Y.nestedArray;for(var X=0;X<T.length;++X)q.add(T[X]);if(this.remove(Y),!this.nested)this.nested={};q.setOptions(Y.options,!0)}else throw Error("duplicate name '"+q.name+"' in "+this)}if(this.nested[q.name]=q,!(this instanceof u$||this instanceof Rq||this instanceof d$||this instanceof N4)){if(!q._edition)q._edition=q._defaultEdition}this._needsRecursiveFeatureResolution=!0,this._needsRecursiveResolve=!0;var J=this;while(J=J.parent)J._needsRecursiveFeatureResolution=!0,J._needsRecursiveResolve=!0;return q.onAdd(this),WZ(this)};$0.prototype.remove=function(q){if(!(q instanceof QT))throw TypeError("object must be a ReflectionObject");if(q.parent!==this)throw Error(q+" is not a member of "+this);if(delete this.nested[q.name],!Object.keys(this.nested).length)this.nested=void 0;return q.onRemove(this),WZ(this)};$0.prototype.define=function(q,Y){if(UT.isString(q))q=q.split(".");else if(!Array.isArray(q))throw TypeError("illegal path");if(q&&q.length&&q[0]==="")throw Error("path must be relative");var T=this;while(q.length>0){var X=q.shift();if(T.nested&&T.nested[X]){if(T=T.nested[X],!(T instanceof $0))throw Error("path conflicts with non-namespace objects")}else T.add(T=new $0(X))}if(Y)T.addJSON(Y);return T};$0.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;this._resolveFeaturesRecursive(this._edition);var q=this.nestedArray,Y=0;this.resolve();while(Y<q.length)if(q[Y]instanceof $0)q[Y++].resolveAll();else q[Y++].resolve();return this._needsRecursiveResolve=!1,this};$0.prototype._resolveFeaturesRecursive=function(q){if(!this._needsRecursiveFeatureResolution)return this;return this._needsRecursiveFeatureResolution=!1,q=this._edition||q,QT.prototype._resolveFeaturesRecursive.call(this,q),this.nestedArray.forEach((Y)=>{Y._resolveFeaturesRecursive(q)}),this};$0.prototype.lookup=function(q,Y,T){if(typeof Y==="boolean")T=Y,Y=void 0;else if(Y&&!Array.isArray(Y))Y=[Y];if(UT.isString(q)&&q.length){if(q===".")return this.root;q=q.split(".")}else if(!q.length)return this;var X=q.join(".");if(q[0]==="")return this.root.lookup(q.slice(1),Y);var J=this.root._fullyQualifiedObjects&&this.root._fullyQualifiedObjects["."+X];if(J&&(!Y||Y.indexOf(J.constructor)>-1))return J;if(J=this._lookupImpl(q,X),J&&(!Y||Y.indexOf(J.constructor)>-1))return J;if(T)return null;var Q=this;while(Q.parent){if(J=Q.parent._lookupImpl(q,X),J&&(!Y||Y.indexOf(J.constructor)>-1))return J;Q=Q.parent}return null};$0.prototype._lookupImpl=function(q,Y){if(Object.prototype.hasOwnProperty.call(this._lookupCache,Y))return this._lookupCache[Y];var T=this.get(q[0]),X=null;if(T){if(q.length===1)X=T;else if(T instanceof $0)q=q.slice(1),X=T._lookupImpl(q,q.join("."))}else for(var J=0;J<this.nestedArray.length;++J)if(this._nestedArray[J]instanceof $0&&(T=this._nestedArray[J]._lookupImpl(q,Y)))X=T;return this._lookupCache[Y]=X,X};$0.prototype.lookupType=function(q){var Y=this.lookup(q,[u$]);if(!Y)throw Error("no such type: "+q);return Y};$0.prototype.lookupEnum=function(q){var Y=this.lookup(q,[d$]);if(!Y)throw Error("no such Enum '"+q+"' in "+this);return Y};$0.prototype.lookupTypeOrEnum=function(q){var Y=this.lookup(q,[u$,d$]);if(!Y)throw Error("no such Type or Enum '"+q+"' in "+this);return Y};$0.prototype.lookupService=function(q){var Y=this.lookup(q,[Rq]);if(!Y)throw Error("no such Service '"+q+"' in "+this);return Y};$0._configure=function($,q,Y){u$=$,Rq=q,d$=Y}});var ZT=B((rv,EZ)=>{EZ.exports=e1;var H4=N$();((e1.prototype=Object.create(H4.prototype)).constructor=e1).className="MapField";var LH=p$(),RY=L0();function e1($,q,Y,T,X,J){if(H4.call(this,$,q,T,void 0,void 0,X,J),!RY.isString(Y))throw TypeError("keyType must be a string");this.keyType=Y,this.resolvedKeyType=null,this.map=!0}e1.fromJSON=function(q,Y){return new e1(q,Y.id,Y.keyType,Y.type,Y.options,Y.comment)};e1.prototype.toJSON=function(q){var Y=q?Boolean(q.keepComments):!1;return RY.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",Y?this.comment:void 0])};e1.prototype.resolve=function(){if(this.resolved)return this;if(LH.mapKey[this.keyType]===void 0)throw Error("invalid key type: "+this.keyType);return H4.prototype.resolve.call(this)};e1.d=function(q,Y,T){if(typeof T==="function")T=RY.decorateType(T).name;else if(T&&typeof T==="object")T=RY.decorateEnum(T).name;return function(J,Q){RY.decorateType(J.constructor).add(new e1(Q,q,Y,T))}}});var KT=B((av,VZ)=>{VZ.exports=l$;var z4=H$();((l$.prototype=Object.create(z4.prototype)).constructor=l$).className="Method";var Oq=L0();function l$($,q,Y,T,X,J,Q,U,Z){if(Oq.isObject(X))Q=X,X=J=void 0;else if(Oq.isObject(J))Q=J,J=void 0;if(!(q===void 0||Oq.isString(q)))throw TypeError("type must be a string");if(!Oq.isString(Y))throw TypeError("requestType must be a string");if(!Oq.isString(T))throw TypeError("responseType must be a string");z4.call(this,$,Q),this.type=q||"rpc",this.requestType=Y,this.requestStream=X?!0:void 0,this.responseType=T,this.responseStream=J?!0:void 0,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=U,this.parsedOptions=Z}l$.fromJSON=function(q,Y){return new l$(q,Y.type,Y.requestType,Y.responseType,Y.requestStream,Y.responseStream,Y.options,Y.comment,Y.parsedOptions)};l$.prototype.toJSON=function(q){var Y=q?Boolean(q.keepComments):!1;return Oq.toObject(["type",this.type!=="rpc"&&this.type||void 0,"requestType",this.requestType,"requestStream",this.requestStream,"responseType",this.responseType,"responseStream",this.responseStream,"options",this.options,"comment",Y?this.comment:void 0,"parsedOptions",this.parsedOptions])};l$.prototype.resolve=function(){if(this.resolved)return this;return this.resolvedRequestType=this.parent.lookupType(this.requestType),this.resolvedResponseType=this.parent.lookupType(this.responseType),z4.prototype.resolve.call(this)}});var AT=B((ov,FZ)=>{FZ.exports=t0;var $$=Pq();((t0.prototype=Object.create($$.prototype)).constructor=t0).className="Service";var M4=KT(),PY=L0(),wH=G4();function t0($,q){$$.call(this,$,q),this.methods={},this._methodsArray=null}t0.fromJSON=function(q,Y){var T=new t0(q,Y.options);if(Y.methods)for(var X=Object.keys(Y.methods),J=0;J<X.length;++J)T.add(M4.fromJSON(X[J],Y.methods[X[J]]));if(Y.nested)T.addJSON(Y.nested);if(Y.edition)T._edition=Y.edition;return T.comment=Y.comment,T._defaultEdition="proto3",T};t0.prototype.toJSON=function(q){var Y=$$.prototype.toJSON.call(this,q),T=q?Boolean(q.keepComments):!1;return PY.toObject(["edition",this._editionToJSON(),"options",Y&&Y.options||void 0,"methods",$$.arrayToJSON(this.methodsArray,q)||{},"nested",Y&&Y.nested||void 0,"comment",T?this.comment:void 0])};Object.defineProperty(t0.prototype,"methodsArray",{get:function(){return this._methodsArray||(this._methodsArray=PY.toArray(this.methods))}});function DZ($){return $._methodsArray=null,$}t0.prototype.get=function(q){return this.methods[q]||$$.prototype.get.call(this,q)};t0.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;$$.prototype.resolve.call(this);var q=this.methodsArray;for(var Y=0;Y<q.length;++Y)q[Y].resolve();return this};t0.prototype._resolveFeaturesRecursive=function(q){if(!this._needsRecursiveFeatureResolution)return this;return q=this._edition||q,$$.prototype._resolveFeaturesRecursive.call(this,q),this.methodsArray.forEach((Y)=>{Y._resolveFeaturesRecursive(q)}),this};t0.prototype.add=function(q){if(this.get(q.name))throw Error("duplicate name '"+q.name+"' in "+this);if(q instanceof M4)return this.methods[q.name]=q,q.parent=this,DZ(this);return $$.prototype.add.call(this,q)};t0.prototype.remove=function(q){if(q instanceof M4){if(this.methods[q.name]!==q)throw Error(q+" is not a member of "+this);return delete this.methods[q.name],q.parent=null,DZ(this)}return $$.prototype.remove.call(this,q)};t0.prototype.create=function(q,Y,T){var X=new wH.Service(q,Y,T);for(var J=0,Q;J<this.methodsArray.length;++J){var U=PY.lcFirst((Q=this._methodsArray[J]).resolve().name).replace(/[^$\w_]/g,"");X[U]=PY.codegen(["r","c"],PY.isReserved(U)?U+"_":U)("return this.rpcCall(m,q,s,r,c)")({m:Q,q:Q.resolvedRequestType.ctor,s:Q.resolvedResponseType.ctor})}return X}});var WT=B((sv,IZ)=>{IZ.exports=h1;var SH=x1();function h1($){if($)for(var q=Object.keys($),Y=0;Y<q.length;++Y)this[q[Y]]=$[q[Y]]}h1.create=function(q){return this.$type.create(q)};h1.encode=function(q,Y){return this.$type.encode(q,Y)};h1.encodeDelimited=function(q,Y){return this.$type.encodeDelimited(q,Y)};h1.decode=function(q){return this.$type.decode(q)};h1.decodeDelimited=function(q){return this.$type.decodeDelimited(q)};h1.verify=function(q){return this.$type.verify(q)};h1.fromObject=function(q){return this.$type.fromObject(q)};h1.toObject=function(q,Y){return this.$type.toObject(q,Y)};h1.prototype.toJSON=function(){return this.$type.toObject(this,SH.toJSONOptions)}});var B4=B((tv,HZ)=>{HZ.exports=jH;var CH=P1(),q$=p$(),NZ=L0();function yH($){return"missing required '"+$.name+"'"}function jH($){var q=NZ.codegen(["r","l","e"],$.name+"$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("var c=l===undefined?r.len:r.pos+l,m=new this.ctor"+($.fieldsArray.filter(function(U){return U.map}).length?",k,value":""))("while(r.pos<c){")("var t=r.uint32()")("if(t===e)")("break")("switch(t>>>3){"),Y=0;for(;Y<$.fieldsArray.length;++Y){var T=$._fieldsArray[Y].resolve(),X=T.resolvedType instanceof CH?"int32":T.type,J="m"+NZ.safeProp(T.name);if(q("case %i: {",T.id),T.map){if(q("if(%s===util.emptyObject)",J)("%s={}",J)("var c2 = r.uint32()+r.pos"),q$.defaults[T.keyType]!==void 0)q("k=%j",q$.defaults[T.keyType]);else q("k=null");if(q$.defaults[X]!==void 0)q("value=%j",q$.defaults[X]);else q("value=null");if(q("while(r.pos<c2){")("var tag2=r.uint32()")("switch(tag2>>>3){")("case 1: k=r.%s(); break",T.keyType)("case 2:"),q$.basic[X]===void 0)q("value=types[%i].decode(r,r.uint32())",Y);else q("value=r.%s()",X);if(q("break")("default:")("r.skipType(tag2&7)")("break")("}")("}"),q$.long[T.keyType]!==void 0)q('%s[typeof k==="object"?util.longToHash(k):k]=value',J);else q("%s[k]=value",J)}else if(T.repeated){if(q("if(!(%s&&%s.length))",J,J)("%s=[]",J),q$.packed[X]!==void 0)q("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos<c2)")("%s.push(r.%s())",J,X)("}else");if(q$.basic[X]===void 0)q(T.delimited?"%s.push(types[%i].decode(r,undefined,((t&~7)|4)))":"%s.push(types[%i].decode(r,r.uint32()))",J,Y);else q("%s.push(r.%s())",J,X)}else if(q$.basic[X]===void 0)q(T.delimited?"%s=types[%i].decode(r,undefined,((t&~7)|4))":"%s=types[%i].decode(r,r.uint32())",J,Y);else q("%s=r.%s()",J,X);q("break")("}")}q("default:")("r.skipType(t&7)")("break")("}")("}");for(Y=0;Y<$._fieldsArray.length;++Y){var Q=$._fieldsArray[Y];if(Q.required)q("if(!m.hasOwnProperty(%j))",Q.name)("throw util.ProtocolError(%j,{instance:m})",yH(Q))}return q("return m")}});var O4=B((ev,zZ)=>{zZ.exports=kH;var vH=P1(),R4=L0();function Z1($,q){return $.name+": "+q+($.repeated&&q!=="array"?"[]":$.map&&q!=="object"?"{k:"+$.keyType+"}":"")+" expected"}function P4($,q,Y,T){if(q.resolvedType)if(q.resolvedType instanceof vH){$("switch(%s){",T)("default:")("return%j",Z1(q,"enum value"));for(var X=Object.keys(q.resolvedType.values),J=0;J<X.length;++J)$("case %i:",q.resolvedType.values[X[J]]);$("break")("}")}else $("{")("var e=types[%i].verify(%s);",Y,T)("if(e)")("return%j+e",q.name+".")("}");else switch(q.type){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":$("if(!util.isInteger(%s))",T)("return%j",Z1(q,"integer"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":$("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))",T,T,T,T)("return%j",Z1(q,"integer|Long"));break;case"float":case"double":$('if(typeof %s!=="number")',T)("return%j",Z1(q,"number"));break;case"bool":$('if(typeof %s!=="boolean")',T)("return%j",Z1(q,"boolean"));break;case"string":$("if(!util.isString(%s))",T)("return%j",Z1(q,"string"));break;case"bytes":$('if(!(%s&&typeof %s.length==="number"||util.isString(%s)))',T,T,T)("return%j",Z1(q,"buffer"));break}return $}function xH($,q,Y){switch(q.keyType){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":$("if(!util.key32Re.test(%s))",Y)("return%j",Z1(q,"integer key"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":$("if(!util.key64Re.test(%s))",Y)("return%j",Z1(q,"integer|Long key"));break;case"bool":$("if(!util.key2Re.test(%s))",Y)("return%j",Z1(q,"boolean key"));break}return $}function kH($){var q=R4.codegen(["m"],$.name+"$verify")('if(typeof m!=="object"||m===null)')("return%j","object expected"),Y=$.oneofsArray,T={};if(Y.length)q("var p={}");for(var X=0;X<$.fieldsArray.length;++X){var J=$._fieldsArray[X].resolve(),Q="m"+R4.safeProp(J.name);if(J.optional)q("if(%s!=null&&m.hasOwnProperty(%j)){",Q,J.name);if(J.map)q("if(!util.isObject(%s))",Q)("return%j",Z1(J,"object"))("var k=Object.keys(%s)",Q)("for(var i=0;i<k.length;++i){"),xH(q,J,"k[i]"),P4(q,J,X,Q+"[k[i]]")("}");else if(J.repeated)q("if(!Array.isArray(%s))",Q)("return%j",Z1(J,"array"))("for(var i=0;i<%s.length;++i){",Q),P4(q,J,X,Q+"[i]")("}");else{if(J.partOf){var U=R4.safeProp(J.partOf.name);if(T[J.partOf.name]===1)q("if(p%s===1)",U)("return%j",J.partOf.name+": multiple values");T[J.partOf.name]=1,q("p%s=1",U)}P4(q,J,X,Q)}if(J.optional)q("}")}return q("return null")}});var S4=B((BZ)=>{var MZ=BZ,OY=P1(),_1=L0();function L4($,q,Y,T){var X=!1;if(q.resolvedType)if(q.resolvedType instanceof OY){$("switch(d%s){",T);for(var J=q.resolvedType.values,Q=Object.keys(J),U=0;U<Q.length;++U){if(J[Q[U]]===q.typeDefault&&!X){if($("default:")('if(typeof(d%s)==="number"){m%s=d%s;break}',T,T,T),!q.repeated)$("break");X=!0}$("case%j:",Q[U])("case %i:",J[Q[U]])("m%s=%j",T,J[Q[U]])("break")}$("}")}else $('if(typeof d%s!=="object")',T)("throw TypeError(%j)",q.fullName+": object expected")("m%s=types[%i].fromObject(d%s)",T,Y,T);else{var Z=!1;switch(q.type){case"double":case"float":$("m%s=Number(d%s)",T,T);break;case"uint32":case"fixed32":$("m%s=d%s>>>0",T,T);break;case"int32":case"sint32":case"sfixed32":$("m%s=d%s|0",T,T);break;case"uint64":Z=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":$("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",T,T,Z)('else if(typeof d%s==="string")',T)("m%s=parseInt(d%s,10)",T,T)('else if(typeof d%s==="number")',T)("m%s=d%s",T,T)('else if(typeof d%s==="object")',T)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",T,T,T,Z?"true":"");break;case"bytes":$('if(typeof d%s==="string")',T)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",T,T,T)("else if(d%s.length >= 0)",T)("m%s=d%s",T,T);break;case"string":$("m%s=String(d%s)",T,T);break;case"bool":$("m%s=Boolean(d%s)",T,T);break}}return $}MZ.fromObject=function(q){var Y=q.fieldsArray,T=_1.codegen(["d"],q.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!Y.length)return T("return new this.ctor");T("var m=new this.ctor");for(var X=0;X<Y.length;++X){var J=Y[X].resolve(),Q=_1.safeProp(J.name);if(J.map)T("if(d%s){",Q)('if(typeof d%s!=="object")',Q)("throw TypeError(%j)",J.fullName+": object expected")("m%s={}",Q)("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){",Q),L4(T,J,X,Q+"[ks[i]]")("}")("}");else if(J.repeated)T("if(d%s){",Q)("if(!Array.isArray(d%s))",Q)("throw TypeError(%j)",J.fullName+": array expected")("m%s=[]",Q)("for(var i=0;i<d%s.length;++i){",Q),L4(T,J,X,Q+"[i]")("}")("}");else{if(!(J.resolvedType instanceof OY))T("if(d%s!=null){",Q);if(L4(T,J,X,Q),!(J.resolvedType instanceof OY))T("}")}}return T("return m")};function w4($,q,Y,T){if(q.resolvedType)if(q.resolvedType instanceof OY)$("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",T,Y,T,T,Y,T,T);else $("d%s=types[%i].toObject(m%s,o)",T,Y,T);else{var X=!1;switch(q.type){case"double":case"float":$("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",T,T,T,T);break;case"uint64":X=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":$('if(typeof m%s==="number")',T)("d%s=o.longs===String?String(m%s):m%s",T,T,T)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s",T,T,T,T,X?"true":"",T);break;case"bytes":$("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",T,T,T,T,T);break;default:$("d%s=m%s",T,T);break}}return $}MZ.toObject=function(q){var Y=q.fieldsArray.slice().sort(_1.compareFieldsById);if(!Y.length)return _1.codegen()("return {}");var T=_1.codegen(["m","o"],q.name+"$toObject")("if(!o)")("o={}")("var d={}"),X=[],J=[],Q=[],U=0;for(;U<Y.length;++U)if(!Y[U].partOf)(Y[U].resolve().repeated?X:Y[U].map?J:Q).push(Y[U]);if(X.length){T("if(o.arrays||o.defaults){");for(U=0;U<X.length;++U)T("d%s=[]",_1.safeProp(X[U].name));T("}")}if(J.length){T("if(o.objects||o.defaults){");for(U=0;U<J.length;++U)T("d%s={}",_1.safeProp(J[U].name));T("}")}if(Q.length){T("if(o.defaults){");for(U=0;U<Q.length;++U){var Z=Q[U],K=_1.safeProp(Z.name);if(Z.resolvedType instanceof OY)T("d%s=o.enums===String?%j:%j",K,Z.resolvedType.valuesById[Z.typeDefault],Z.typeDefault);else if(Z.long)T("if(util.Long){")("var n=new util.Long(%i,%i,%j)",Z.typeDefault.low,Z.typeDefault.high,Z.typeDefault.unsigned)("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n",K)("}else")("d%s=o.longs===String?%j:%i",K,Z.typeDefault.toString(),Z.typeDefault.toNumber());else if(Z.bytes){var A="["+Array.prototype.slice.call(Z.typeDefault).join(",")+"]";T("if(o.bytes===String)d%s=%j",K,String.fromCharCode.apply(String,Z.typeDefault))("else{")("d%s=%s",K,A)("if(o.bytes!==Array)d%s=util.newBuffer(d%s)",K,K)("}")}else T("d%s=%j",K,Z.typeDefault)}T("}")}var W=!1;for(U=0;U<Y.length;++U){var Z=Y[U],G=q._fieldsArray.indexOf(Z),K=_1.safeProp(Z.name);if(Z.map){if(!W)W=!0,T("var ks2");T("if(m%s&&(ks2=Object.keys(m%s)).length){",K,K)("d%s={}",K)("for(var j=0;j<ks2.length;++j){"),w4(T,Z,G,K+"[ks2[j]]")("}")}else if(Z.repeated)T("if(m%s&&m%s.length){",K,K)("d%s=[]",K)("for(var j=0;j<m%s.length;++j){",K),w4(T,Z,G,K+"[j]")("}");else if(T("if(m%s!=null&&m.hasOwnProperty(%j)){",K,Z.name),w4(T,Z,G,K),Z.partOf)T("if(o.oneofs)")("d%s=%j",_1.safeProp(Z.partOf.name),Z.name);T("}")}return T("return d")}});var C4=B((RZ)=>{var hH=RZ,_H=WT();hH[".google.protobuf.Any"]={fromObject:function($){if($&&$["@type"]){var q=$["@type"].substring($["@type"].lastIndexOf("/")+1),Y=this.lookup(q);if(Y){var T=$["@type"].charAt(0)==="."?$["@type"].slice(1):$["@type"];if(T.indexOf("/")===-1)T="/"+T;return this.create({type_url:T,value:Y.encode(Y.fromObject($)).finish()})}}return this.fromObject($)},toObject:function($,q){var Y="type.googleapis.com/",T="",X="";if(q&&q.json&&$.type_url&&$.value){X=$.type_url.substring($.type_url.lastIndexOf("/")+1),T=$.type_url.substring(0,$.type_url.lastIndexOf("/")+1);var J=this.lookup(X);if(J)$=J.decode($.value)}if(!($ instanceof this.ctor)&&$ instanceof _H){var Q=$.$type.toObject($,q),U=$.$type.fullName[0]==="."?$.$type.fullName.slice(1):$.$type.fullName;if(T==="")T=Y;return X=T+U,Q["@type"]=X,Q}return this.toObject($,q)}}});var VT=B((Yx,OZ)=>{OZ.exports=K0;var K1=Pq();((K0.prototype=Object.create(K1.prototype)).constructor=K0).className="Type";var gH=P1(),v4=c$(),GT=N$(),mH=ZT(),fH=AT(),y4=WT(),j4=JT(),bH=TT(),m0=L0(),uH=x4(),dH=B4(),cH=O4(),PZ=S4(),pH=C4();function K0($,q){K1.call(this,$,q),this.fields={},this.oneofs=void 0,this.extensions=void 0,this.reserved=void 0,this.group=void 0,this._fieldsById=null,this._fieldsArray=null,this._oneofsArray=null,this._ctor=null}Object.defineProperties(K0.prototype,{fieldsById:{get:function(){if(this._fieldsById)return this._fieldsById;this._fieldsById={};for(var $=Object.keys(this.fields),q=0;q<$.length;++q){var Y=this.fields[$[q]],T=Y.id;if(this._fieldsById[T])throw Error("duplicate id "+T+" in "+this);this._fieldsById[T]=Y}return this._fieldsById}},fieldsArray:{get:function(){return this._fieldsArray||(this._fieldsArray=m0.toArray(this.fields))}},oneofsArray:{get:function(){return this._oneofsArray||(this._oneofsArray=m0.toArray(this.oneofs))}},ctor:{get:function(){return this._ctor||(this.ctor=K0.generateConstructor(this)())},set:function($){var q=$.prototype;if(!(q instanceof y4))($.prototype=new y4).constructor=$,m0.merge($.prototype,q);$.$type=$.prototype.$type=this,m0.merge($,y4,!0),this._ctor=$;var Y=0;for(;Y<this.fieldsArray.length;++Y)this._fieldsArray[Y].resolve();var T={};for(Y=0;Y<this.oneofsArray.length;++Y)T[this._oneofsArray[Y].resolve().name]={get:m0.oneOfGetter(this._oneofsArray[Y].oneof),set:m0.oneOfSetter(this._oneofsArray[Y].oneof)};if(Y)Object.defineProperties($.prototype,T)}}});K0.generateConstructor=function(q){var Y=m0.codegen(["p"],q.name);for(var T=0,X;T<q.fieldsArray.length;++T)if((X=q._fieldsArray[T]).map)Y("this%s={}",m0.safeProp(X.name));else if(X.repeated)Y("this%s=[]",m0.safeProp(X.name));return Y("if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null)")("this[ks[i]]=p[ks[i]]")};function ET($){return $._fieldsById=$._fieldsArray=$._oneofsArray=null,delete $.encode,delete $.decode,delete $.verify,$}K0.fromJSON=function(q,Y){var T=new K0(q,Y.options);T.extensions=Y.extensions,T.reserved=Y.reserved;var X=Object.keys(Y.fields),J=0;for(;J<X.length;++J)T.add((typeof Y.fields[X[J]].keyType<"u"?mH.fromJSON:GT.fromJSON)(X[J],Y.fields[X[J]]));if(Y.oneofs)for(X=Object.keys(Y.oneofs),J=0;J<X.length;++J)T.add(v4.fromJSON(X[J],Y.oneofs[X[J]]));if(Y.nested)for(X=Object.keys(Y.nested),J=0;J<X.length;++J){var Q=Y.nested[X[J]];T.add((Q.id!==void 0?GT.fromJSON:Q.fields!==void 0?K0.fromJSON:Q.values!==void 0?gH.fromJSON:Q.methods!==void 0?fH.fromJSON:K1.fromJSON)(X[J],Q))}if(Y.extensions&&Y.extensions.length)T.extensions=Y.extensions;if(Y.reserved&&Y.reserved.length)T.reserved=Y.reserved;if(Y.group)T.group=!0;if(Y.comment)T.comment=Y.comment;if(Y.edition)T._edition=Y.edition;return T._defaultEdition="proto3",T};K0.prototype.toJSON=function(q){var Y=K1.prototype.toJSON.call(this,q),T=q?Boolean(q.keepComments):!1;return m0.toObject(["edition",this._editionToJSON(),"options",Y&&Y.options||void 0,"oneofs",K1.arrayToJSON(this.oneofsArray,q),"fields",K1.arrayToJSON(this.fieldsArray.filter(function(X){return!X.declaringField}),q)||{},"extensions",this.extensions&&this.extensions.length?this.extensions:void 0,"reserved",this.reserved&&this.reserved.length?this.reserved:void 0,"group",this.group||void 0,"nested",Y&&Y.nested||void 0,"comment",T?this.comment:void 0])};K0.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;K1.prototype.resolveAll.call(this);var q=this.oneofsArray;T=0;while(T<q.length)q[T++].resolve();var Y=this.fieldsArray,T=0;while(T<Y.length)Y[T++].resolve();return this};K0.prototype._resolveFeaturesRecursive=function(q){if(!this._needsRecursiveFeatureResolution)return this;return q=this._edition||q,K1.prototype._resolveFeaturesRecursive.call(this,q),this.oneofsArray.forEach((Y)=>{Y._resolveFeatures(q)}),this.fieldsArray.forEach((Y)=>{Y._resolveFeatures(q)}),this};K0.prototype.get=function(q){return this.fields[q]||this.oneofs&&this.oneofs[q]||this.nested&&this.nested[q]||null};K0.prototype.add=function(q){if(this.get(q.name))throw Error("duplicate name '"+q.name+"' in "+this);if(q instanceof GT&&q.extend===void 0){if(this._fieldsById?this._fieldsById[q.id]:this.fieldsById[q.id])throw Error("duplicate id "+q.id+" in "+this);if(this.isReservedId(q.id))throw Error("id "+q.id+" is reserved in "+this);if(this.isReservedName(q.name))throw Error("name '"+q.name+"' is reserved in "+this);if(q.parent)q.parent.remove(q);return this.fields[q.name]=q,q.message=this,q.onAdd(this),ET(this)}if(q instanceof v4){if(!this.oneofs)this.oneofs={};return this.oneofs[q.name]=q,q.onAdd(this),ET(this)}return K1.prototype.add.call(this,q)};K0.prototype.remove=function(q){if(q instanceof GT&&q.extend===void 0){if(!this.fields||this.fields[q.name]!==q)throw Error(q+" is not a member of "+this);return delete this.fields[q.name],q.parent=null,q.onRemove(this),ET(this)}if(q instanceof v4){if(!this.oneofs||this.oneofs[q.name]!==q)throw Error(q+" is not a member of "+this);return delete this.oneofs[q.name],q.parent=null,q.onRemove(this),ET(this)}return K1.prototype.remove.call(this,q)};K0.prototype.isReservedId=function(q){return K1.isReservedId(this.reserved,q)};K0.prototype.isReservedName=function(q){return K1.isReservedName(this.reserved,q)};K0.prototype.create=function(q){return new this.ctor(q)};K0.prototype.setup=function(){var q=this.fullName,Y=[];for(var T=0;T<this.fieldsArray.length;++T)Y.push(this._fieldsArray[T].resolve().resolvedType);this.encode=uH(this)({Writer:bH,types:Y,util:m0}),this.decode=dH(this)({Reader:j4,types:Y,util:m0}),this.verify=cH(this)({types:Y,util:m0}),this.fromObject=PZ.fromObject(this)({types:Y,util:m0}),this.toObject=PZ.toObject(this)({types:Y,util:m0});var X=pH[q];if(X){var J=Object.create(this);J.fromObject=this.fromObject,this.fromObject=X.fromObject.bind(J),J.toObject=this.toObject,this.toObject=X.toObject.bind(J)}return this};K0.prototype.encode=function(q,Y){return this.setup().encode(q,Y)};K0.prototype.encodeDelimited=function(q,Y){return this.encode(q,Y&&Y.len?Y.fork():Y).ldelim()};K0.prototype.decode=function(q,Y){return this.setup().decode(q,Y)};K0.prototype.decodeDelimited=function(q){if(!(q instanceof j4))q=j4.create(q);return this.decode(q,q.uint32())};K0.prototype.verify=function(q){return this.setup().verify(q)};K0.prototype.fromObject=function(q){return this.setup().fromObject(q)};K0.prototype.toObject=function(q,Y){return this.setup().toObject(q,Y)};K0.d=function(q){return function(T){m0.decorateType(T,q)}}});var NT=B((Tx,SZ)=>{SZ.exports=e0;var IT=Pq();((e0.prototype=Object.create(IT.prototype)).constructor=e0).className="Root";var DT=N$(),k4=P1(),lH=c$(),z$=L0(),h4,_4,LY;function e0($){IT.call(this,"",$),this.deferred=[],this.files=[],this._edition="proto2",this._fullyQualifiedObjects={}}e0.fromJSON=function(q,Y){if(!Y)Y=new e0;if(q.options)Y.setOptions(q.options);return Y.addJSON(q.nested).resolveAll()};e0.prototype.resolvePath=z$.path.resolve;e0.prototype.fetch=z$.fetch;function wZ(){}e0.prototype.load=function $(q,Y,T){if(typeof Y==="function")T=Y,Y=void 0;var X=this;if(!T)return z$.asPromise($,X,q,Y);var J=T===wZ;function Q(V,F){if(!T)return;if(J)throw V;if(F)F.resolveAll();var N=T;T=null,N(V,F)}function U(V){var F=V.lastIndexOf("google/protobuf/");if(F>-1){var N=V.substring(F);if(N in LY)return N}return null}function Z(V,F){try{if(z$.isString(F)&&F.charAt(0)==="{")F=JSON.parse(F);if(!z$.isString(F))X.setOptions(F.options).addJSON(F.nested);else{_4.filename=V;var N=_4(F,X,Y),D,z=0;if(N.imports){for(;z<N.imports.length;++z)if(D=U(N.imports[z])||X.resolvePath(V,N.imports[z]))K(D)}if(N.weakImports){for(z=0;z<N.weakImports.length;++z)if(D=U(N.weakImports[z])||X.resolvePath(V,N.weakImports[z]))K(D,!0)}}}catch(S){Q(S)}if(!J&&!A)Q(null,X)}function K(V,F){if(V=U(V)||V,X.files.indexOf(V)>-1)return;if(X.files.push(V),V in LY){if(J)Z(V,LY[V]);else++A,setTimeout(function(){--A,Z(V,LY[V])});return}if(J){var N;try{N=z$.fs.readFileSync(V).toString("utf8")}catch(D){if(!F)Q(D);return}Z(V,N)}else++A,X.fetch(V,function(D,z){if(--A,!T)return;if(D){if(!F)Q(D);else if(!A)Q(null,X);return}Z(V,z)})}var A=0;if(z$.isString(q))q=[q];for(var W=0,G;W<q.length;++W)if(G=X.resolvePath("",q[W]))K(G);if(J)return X.resolveAll(),X;if(!A)Q(null,X);return X};e0.prototype.loadSync=function(q,Y){if(!z$.isNode)throw Error("not supported");return this.load(q,Y,wZ)};e0.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;if(this.deferred.length)throw Error("unresolvable extensions: "+this.deferred.map(function(q){return"'extend "+q.extend+"' in "+q.parent.fullName}).join(", "));return IT.prototype.resolveAll.call(this)};var FT=/^[A-Z]/;function LZ($,q){var Y=q.parent.lookup(q.extend);if(Y){var T=new DT(q.fullName,q.id,q.type,q.rule,void 0,q.options);if(Y.get(T.name))return!0;return T.declaringField=q,q.extensionField=T,Y.add(T),!0}return!1}e0.prototype._handleAdd=function(q){if(q instanceof DT){if(q.extend!==void 0&&!q.extensionField){if(!LZ(this,q))this.deferred.push(q)}}else if(q instanceof k4){if(FT.test(q.name))q.parent[q.name]=q.values}else if(!(q instanceof lH)){if(q instanceof h4)for(var Y=0;Y<this.deferred.length;)if(LZ(this,this.deferred[Y]))this.deferred.splice(Y,1);else++Y;for(var T=0;T<q.nestedArray.length;++T)this._handleAdd(q._nestedArray[T]);if(FT.test(q.name))q.parent[q.name]=q}if(q instanceof h4||q instanceof k4||q instanceof DT)this._fullyQualifiedObjects[q.fullName]=q};e0.prototype._handleRemove=function(q){if(q instanceof DT){if(q.extend!==void 0)if(q.extensionField)q.extensionField.parent.remove(q.extensionField),q.extensionField=null;else{var Y=this.deferred.indexOf(q);if(Y>-1)this.deferred.splice(Y,1)}}else if(q instanceof k4){if(FT.test(q.name))delete q.parent[q.name]}else if(q instanceof IT){for(var T=0;T<q.nestedArray.length;++T)this._handleRemove(q._nestedArray[T]);if(FT.test(q.name))delete q.parent[q.name]}delete this._fullyQualifiedObjects[q.fullName]};e0._configure=function($,q,Y){h4=$,_4=q,LY=Y}});var L0=B((Xx,yZ)=>{var I0=yZ.exports=x1(),CZ=E4(),g4,m4;I0.codegen=XZ();I0.fetch=QZ();I0.path=KZ();I0.fs=I0.inquire("fs");I0.toArray=function(q){if(q){var Y=Object.keys(q),T=Array(Y.length),X=0;while(X<Y.length)T[X]=q[Y[X++]];return T}return[]};I0.toObject=function(q){var Y={},T=0;while(T<q.length){var X=q[T++],J=q[T++];if(J!==void 0)Y[X]=J}return Y};var nH=/\\/g,iH=/"/g;I0.isReserved=function(q){return/^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(q)};I0.safeProp=function(q){if(!/^[$\w_]+$/.test(q)||I0.isReserved(q))return'["'+q.replace(nH,"\\\\").replace(iH,"\\\"")+'"]';return"."+q};I0.ucFirst=function(q){return q.charAt(0).toUpperCase()+q.substring(1)};var rH=/_([a-z])/g;I0.camelCase=function(q){return q.substring(0,1)+q.substring(1).replace(rH,function(Y,T){return T.toUpperCase()})};I0.compareFieldsById=function(q,Y){return q.id-Y.id};I0.decorateType=function(q,Y){if(q.$type){if(Y&&q.$type.name!==Y)I0.decorateRoot.remove(q.$type),q.$type.name=Y,I0.decorateRoot.add(q.$type);return q.$type}if(!g4)g4=VT();var T=new g4(Y||q.name);return I0.decorateRoot.add(T),T.ctor=q,Object.defineProperty(q,"$type",{value:T,enumerable:!1}),Object.defineProperty(q.prototype,"$type",{value:T,enumerable:!1}),T};var aH=0;I0.decorateEnum=function(q){if(q.$type)return q.$type;if(!m4)m4=P1();var Y=new m4("Enum"+aH++,q);return I0.decorateRoot.add(Y),Object.defineProperty(q,"$type",{value:Y,enumerable:!1}),Y};I0.setProperty=function(q,Y,T,X){function J(Q,U,Z){var K=U.shift();if(K==="__proto__"||K==="prototype")return Q;if(U.length>0)Q[K]=J(Q[K]||{},U,Z);else{var A=Q[K];if(A&&X)return Q;if(A)Z=[].concat(A).concat(Z);Q[K]=Z}return Q}if(typeof q!=="object")throw TypeError("dst must be an object");if(!Y)throw TypeError("path must be specified");return Y=Y.split("."),J(q,Y,T)};Object.defineProperty(I0,"decorateRoot",{get:function(){return CZ.decorated||(CZ.decorated=new(NT()))}})});var p$=B((jZ)=>{var wY=jZ,oH=L0(),sH=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function SY($,q){var Y=0,T={};q|=0;while(Y<$.length)T[sH[Y+q]]=$[Y++];return T}wY.basic=SY([1,5,0,0,0,5,5,0,0,0,1,1,0,2,2]);wY.defaults=SY([0,0,0,0,0,0,0,0,0,0,0,0,!1,"",oH.emptyArray,null]);wY.long=SY([0,0,0,1,1],7);wY.mapKey=SY([0,0,0,5,5,0,0,0,1,1,0,2],2);wY.packed=SY([1,5,0,0,0,5,5,0,0,0,1,1,0])});var N$=B((Qx,xZ)=>{xZ.exports=w0;var yY=H$();((w0.prototype=Object.create(yY.prototype)).constructor=w0).className="Field";var vZ=P1(),f4=p$(),z0=L0(),CY,tH=/^required|optional|repeated$/;w0.fromJSON=function(q,Y){var T=new w0(q,Y.id,Y.type,Y.rule,Y.extend,Y.options,Y.comment);if(Y.edition)T._edition=Y.edition;return T._defaultEdition="proto3",T};function w0($,q,Y,T,X,J,Q){if(z0.isObject(T))Q=X,J=T,T=X=void 0;else if(z0.isObject(X))Q=J,J=X,X=void 0;if(yY.call(this,$,J),!z0.isInteger(q)||q<0)throw TypeError("id must be a non-negative integer");if(!z0.isString(Y))throw TypeError("type must be a string");if(T!==void 0&&!tH.test(T=T.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(X!==void 0&&!z0.isString(X))throw TypeError("extend must be a string");if(T==="proto3_optional")T="optional";this.rule=T&&T!=="optional"?T:void 0,this.type=Y,this.id=q,this.extend=X||void 0,this.repeated=T==="repeated",this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=z0.Long?f4.long[Y]!==void 0:!1,this.bytes=Y==="bytes",this.resolvedType=null,this.extensionField=null,this.declaringField=null,this.comment=Q}Object.defineProperty(w0.prototype,"required",{get:function(){return this._features.field_presence==="LEGACY_REQUIRED"}});Object.defineProperty(w0.prototype,"optional",{get:function(){return!this.required}});Object.defineProperty(w0.prototype,"delimited",{get:function(){return this.resolvedType instanceof CY&&this._features.message_encoding==="DELIMITED"}});Object.defineProperty(w0.prototype,"packed",{get:function(){return this._features.repeated_field_encoding==="PACKED"}});Object.defineProperty(w0.prototype,"hasPresence",{get:function(){if(this.repeated||this.map)return!1;return this.partOf||this.declaringField||this.extensionField||this._features.field_presence!=="IMPLICIT"}});w0.prototype.setOption=function(q,Y,T){return yY.prototype.setOption.call(this,q,Y,T)};w0.prototype.toJSON=function(q){var Y=q?Boolean(q.keepComments):!1;return z0.toObject(["edition",this._editionToJSON(),"rule",this.rule!=="optional"&&this.rule||void 0,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",Y?this.comment:void 0])};w0.prototype.resolve=function(){if(this.resolved)return this;if((this.typeDefault=f4.defaults[this.type])===void 0)if(this.resolvedType=(this.declaringField?this.declaringField.parent:this.parent).lookupTypeOrEnum(this.type),this.resolvedType instanceof CY)this.typeDefault=null;else this.typeDefault=this.resolvedType.values[Object.keys(this.resolvedType.values)[0]];else if(this.options&&this.options.proto3_optional)this.typeDefault=null;if(this.options&&this.options.default!=null){if(this.typeDefault=this.options.default,this.resolvedType instanceof vZ&&typeof this.typeDefault==="string")this.typeDefault=this.resolvedType.values[this.typeDefault]}if(this.options){if(this.options.packed!==void 0&&this.resolvedType&&!(this.resolvedType instanceof vZ))delete this.options.packed;if(!Object.keys(this.options).length)this.options=void 0}if(this.long){if(this.typeDefault=z0.Long.fromNumber(this.typeDefault,this.type.charAt(0)==="u"),Object.freeze)Object.freeze(this.typeDefault)}else if(this.bytes&&typeof this.typeDefault==="string"){var q;if(z0.base64.test(this.typeDefault))z0.base64.decode(this.typeDefault,q=z0.newBuffer(z0.base64.length(this.typeDefault)),0);else z0.utf8.write(this.typeDefault,q=z0.newBuffer(z0.utf8.length(this.typeDefault)),0);this.typeDefault=q}if(this.map)this.defaultValue=z0.emptyObject;else if(this.repeated)this.defaultValue=z0.emptyArray;else this.defaultValue=this.typeDefault;if(this.parent instanceof CY)this.parent.ctor.prototype[this.name]=this.defaultValue;return yY.prototype.resolve.call(this)};w0.prototype._inferLegacyProtoFeatures=function(q){if(q!=="proto2"&&q!=="proto3")return{};var Y={};if(this.rule==="required")Y.field_presence="LEGACY_REQUIRED";if(this.parent&&f4.defaults[this.type]===void 0){var T=this.parent.get(this.type.split(".").pop());if(T&&T instanceof CY&&T.group)Y.message_encoding="DELIMITED"}if(this.getOption("packed")===!0)Y.repeated_field_encoding="PACKED";else if(this.getOption("packed")===!1)Y.repeated_field_encoding="EXPANDED";return Y};w0.prototype._resolveFeatures=function(q){return yY.prototype._resolveFeatures.call(this,this._edition||q)};w0.d=function(q,Y,T,X){if(typeof Y==="function")Y=z0.decorateType(Y).name;else if(Y&&typeof Y==="object")Y=z0.decorateEnum(Y).name;return function(Q,U){z0.decorateType(Q.constructor).add(new w0(U,q,Y,T,{default:X}))}};w0._configure=function(q){CY=q}});var c$=B((Ux,_Z)=>{_Z.exports=$1;var zT=H$();(($1.prototype=Object.create(zT.prototype)).constructor=$1).className="OneOf";var kZ=N$(),HT=L0();function $1($,q,Y,T){if(!Array.isArray(q))Y=q,q=void 0;if(zT.call(this,$,Y),!(q===void 0||Array.isArray(q)))throw TypeError("fieldNames must be an Array");this.oneof=q||[],this.fieldsArray=[],this.comment=T}$1.fromJSON=function(q,Y){return new $1(q,Y.oneof,Y.options,Y.comment)};$1.prototype.toJSON=function(q){var Y=q?Boolean(q.keepComments):!1;return HT.toObject(["options",this.options,"oneof",this.oneof,"comment",Y?this.comment:void 0])};function hZ($){if($.parent){for(var q=0;q<$.fieldsArray.length;++q)if(!$.fieldsArray[q].parent)$.parent.add($.fieldsArray[q])}}$1.prototype.add=function(q){if(!(q instanceof kZ))throw TypeError("field must be a Field");if(q.parent&&q.parent!==this.parent)q.parent.remove(q);return this.oneof.push(q.name),this.fieldsArray.push(q),q.partOf=this,hZ(this),this};$1.prototype.remove=function(q){if(!(q instanceof kZ))throw TypeError("field must be a Field");var Y=this.fieldsArray.indexOf(q);if(Y<0)throw Error(q+" is not a member of "+this);if(this.fieldsArray.splice(Y,1),Y=this.oneof.indexOf(q.name),Y>-1)this.oneof.splice(Y,1);return q.partOf=null,this};$1.prototype.onAdd=function(q){zT.prototype.onAdd.call(this,q);var Y=this;for(var T=0;T<this.oneof.length;++T){var X=q.get(this.oneof[T]);if(X&&!X.partOf)X.partOf=Y,Y.fieldsArray.push(X)}hZ(this)};$1.prototype.onRemove=function(q){for(var Y=0,T;Y<this.fieldsArray.length;++Y)if((T=this.fieldsArray[Y]).parent)T.parent.remove(T);zT.prototype.onRemove.call(this,q)};Object.defineProperty($1.prototype,"isProto3Optional",{get:function(){if(this.fieldsArray==null||this.fieldsArray.length!==1)return!1;var $=this.fieldsArray[0];return $.options!=null&&$.options.proto3_optional===!0}});$1.d=function(){var q=Array(arguments.length),Y=0;while(Y<arguments.length)q[Y]=arguments[Y++];return function(X,J){HT.decorateType(X.constructor).add(new $1(J,q)),Object.defineProperty(X,J,{get:HT.oneOfGetter(q),set:HT.oneOfSetter(q)})}}});var H$=B((Zx,gZ)=>{gZ.exports=x0;x0.className="ReflectionObject";var eH=c$(),jY=L0(),MT,$z={enum_type:"OPEN",field_presence:"EXPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"},qz={enum_type:"CLOSED",field_presence:"EXPLICIT",json_format:"LEGACY_BEST_EFFORT",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"EXPANDED",utf8_validation:"NONE"},Yz={enum_type:"OPEN",field_presence:"IMPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"};function x0($,q){if(!jY.isString($))throw TypeError("name must be a string");if(q&&!jY.isObject(q))throw TypeError("options must be an object");this.options=q,this.parsedOptions=null,this.name=$,this._edition=null,this._defaultEdition="proto2",this._features={},this._featuresResolved=!1,this.parent=null,this.resolved=!1,this.comment=null,this.filename=null}Object.defineProperties(x0.prototype,{root:{get:function(){var $=this;while($.parent!==null)$=$.parent;return $}},fullName:{get:function(){var $=[this.name],q=this.parent;while(q)$.unshift(q.name),q=q.parent;return $.join(".")}}});x0.prototype.toJSON=function(){throw Error()};x0.prototype.onAdd=function(q){if(this.parent&&this.parent!==q)this.parent.remove(this);this.parent=q,this.resolved=!1;var Y=q.root;if(Y instanceof MT)Y._handleAdd(this)};x0.prototype.onRemove=function(q){var Y=q.root;if(Y instanceof MT)Y._handleRemove(this);this.parent=null,this.resolved=!1};x0.prototype.resolve=function(){if(this.resolved)return this;if(this.root instanceof MT)this.resolved=!0;return this};x0.prototype._resolveFeaturesRecursive=function(q){return this._resolveFeatures(this._edition||q)};x0.prototype._resolveFeatures=function(q){if(this._featuresResolved)return;var Y={};if(!q)throw Error("Unknown edition for "+this.fullName);var T=Object.assign(this.options?Object.assign({},this.options.features):{},this._inferLegacyProtoFeatures(q));if(this._edition){if(q==="proto2")Y=Object.assign({},qz);else if(q==="proto3")Y=Object.assign({},Yz);else if(q==="2023")Y=Object.assign({},$z);else throw Error("Unknown edition: "+q);this._features=Object.assign(Y,T||{}),this._featuresResolved=!0;return}if(this.partOf instanceof eH){var X=Object.assign({},this.partOf._features);this._features=Object.assign(X,T||{})}else if(this.declaringField);else if(this.parent){var J=Object.assign({},this.parent._features);this._features=Object.assign(J,T||{})}else throw Error("Unable to find a parent for "+this.fullName);if(this.extensionField)this.extensionField._features=this._features;this._featuresResolved=!0};x0.prototype._inferLegacyProtoFeatures=function(){return{}};x0.prototype.getOption=function(q){if(this.options)return this.options[q];return};x0.prototype.setOption=function(q,Y,T){if(!this.options)this.options={};if(/^features\./.test(q))jY.setProperty(this.options,q,Y,T);else if(!T||this.options[q]===void 0){if(this.getOption(q)!==Y)this.resolved=!1;this.options[q]=Y}return this};x0.prototype.setParsedOption=function(q,Y,T){if(!this.parsedOptions)this.parsedOptions=[];var X=this.parsedOptions;if(T){var J=X.find(function(Z){return Object.prototype.hasOwnProperty.call(Z,q)});if(J){var Q=J[q];jY.setProperty(Q,T,Y)}else J={},J[q]=jY.setProperty({},T,Y),X.push(J)}else{var U={};U[q]=Y,X.push(U)}return this};x0.prototype.setOptions=function(q,Y){if(q)for(var T=Object.keys(q),X=0;X<T.length;++X)this.setOption(T[X],q[T[X]],Y);return this};x0.prototype.toString=function(){var q=this.constructor.className,Y=this.fullName;if(Y.length)return q+" "+Y;return q};x0.prototype._editionToJSON=function(){if(!this._edition||this._edition==="proto3")return;return this._edition};x0._configure=function($){MT=$}});var P1=B((Kx,fZ)=>{fZ.exports=O1;var b4=H$();((O1.prototype=Object.create(b4.prototype)).constructor=O1).className="Enum";var mZ=Pq(),BT=L0();function O1($,q,Y,T,X,J){if(b4.call(this,$,Y),q&&typeof q!=="object")throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=T,this.comments=X||{},this.valuesOptions=J,this._valuesFeatures={},this.reserved=void 0,q){for(var Q=Object.keys(q),U=0;U<Q.length;++U)if(typeof q[Q[U]]==="number")this.valuesById[this.values[Q[U]]=q[Q[U]]]=Q[U]}}O1.prototype._resolveFeatures=function(q){return q=this._edition||q,b4.prototype._resolveFeatures.call(this,q),Object.keys(this.values).forEach((Y)=>{var T=Object.assign({},this._features);this._valuesFeatures[Y]=Object.assign(T,this.valuesOptions&&this.valuesOptions[Y]&&this.valuesOptions[Y].features)}),this};O1.fromJSON=function(q,Y){var T=new O1(q,Y.values,Y.options,Y.comment,Y.comments);if(T.reserved=Y.reserved,Y.edition)T._edition=Y.edition;return T._defaultEdition="proto3",T};O1.prototype.toJSON=function(q){var Y=q?Boolean(q.keepComments):!1;return BT.toObject(["edition",this._editionToJSON(),"options",this.options,"valuesOptions",this.valuesOptions,"values",this.values,"reserved",this.reserved&&this.reserved.length?this.reserved:void 0,"comment",Y?this.comment:void 0,"comments",Y?this.comments:void 0])};O1.prototype.add=function(q,Y,T,X){if(!BT.isString(q))throw TypeError("name must be a string");if(!BT.isInteger(Y))throw TypeError("id must be an integer");if(this.values[q]!==void 0)throw Error("duplicate name '"+q+"' in "+this);if(this.isReservedId(Y))throw Error("id "+Y+" is reserved in "+this);if(this.isReservedName(q))throw Error("name '"+q+"' is reserved in "+this);if(this.valuesById[Y]!==void 0){if(!(this.options&&this.options.allow_alias))throw Error("duplicate id "+Y+" in "+this);this.values[q]=Y}else this.valuesById[this.values[q]=Y]=q;if(X){if(this.valuesOptions===void 0)this.valuesOptions={};this.valuesOptions[q]=X||null}return this.comments[q]=T||null,this};O1.prototype.remove=function(q){if(!BT.isString(q))throw TypeError("name must be a string");var Y=this.values[q];if(Y==null)throw Error("name '"+q+"' does not exist in "+this);if(delete this.valuesById[Y],delete this.values[q],delete this.comments[q],this.valuesOptions)delete this.valuesOptions[q];return this};O1.prototype.isReservedId=function(q){return mZ.isReservedId(this.reserved,q)};O1.prototype.isReservedName=function(q){return mZ.isReservedName(this.reserved,q)}});var x4=B((Ax,uZ)=>{uZ.exports=Xz;var Tz=P1(),u4=p$(),d4=L0();function bZ($,q,Y,T){return q.delimited?$("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",Y,T,(q.id<<3|3)>>>0,(q.id<<3|4)>>>0):$("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",Y,T,(q.id<<3|2)>>>0)}function Xz($){var q=d4.codegen(["m","w"],$.name+"$encode")("if(!w)")("w=Writer.create()"),Y,T,X=$.fieldsArray.slice().sort(d4.compareFieldsById);for(var Y=0;Y<X.length;++Y){var J=X[Y].resolve(),Q=$._fieldsArray.indexOf(J),U=J.resolvedType instanceof Tz?"int32":J.type,Z=u4.basic[U];if(T="m"+d4.safeProp(J.name),J.map){if(q("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){",T,J.name)("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){",T)("w.uint32(%i).fork().uint32(%i).%s(ks[i])",(J.id<<3|2)>>>0,8|u4.mapKey[J.keyType],J.keyType),Z===void 0)q("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",Q,T);else q(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|Z,U,T);q("}")("}")}else if(J.repeated){if(q("if(%s!=null&&%s.length){",T,T),J.packed&&u4.packed[U]!==void 0)q("w.uint32(%i).fork()",(J.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",T)("w.%s(%s[i])",U,T)("w.ldelim()");else if(q("for(var i=0;i<%s.length;++i)",T),Z===void 0)bZ(q,J,Q,T+"[i]");else q("w.uint32(%i).%s(%s[i])",(J.id<<3|Z)>>>0,U,T);q("}")}else{if(J.optional)q("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",T,J.name);if(Z===void 0)bZ(q,J,Q,T);else q("w.uint32(%i).%s(%s)",(J.id<<3|Z)>>>0,U,T)}}return q("return w")}});var cZ=B((Wx,dZ)=>{var q0=dZ.exports=YZ();q0.build="light";function Jz($,q,Y){if(typeof q==="function")Y=q,q=new q0.Root;else if(!q)q=new q0.Root;return q.load($,Y)}q0.load=Jz;function Qz($,q){if(!q)q=new q0.Root;return q.loadSync($)}q0.loadSync=Qz;q0.encoder=x4();q0.decoder=B4();q0.verifier=O4();q0.converter=S4();q0.ReflectionObject=H$();q0.Namespace=Pq();q0.Root=NT();q0.Enum=P1();q0.Type=VT();q0.Field=N$();q0.OneOf=c$();q0.MapField=ZT();q0.Service=AT();q0.Method=KT();q0.Message=WT();q0.wrappers=C4();q0.types=p$();q0.util=L0();q0.ReflectionObject._configure(q0.Root);q0.Namespace._configure(q0.Type,q0.Service,q0.Enum);q0.Root._configure(q0.Type);q0.Field._configure(q0.Type)});var p4=B((Gx,nZ)=>{nZ.exports=lZ;var c4=/[\s{}=;:[\],'"()<>]/g,Uz=/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,Zz=/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,Kz=/^ *[*/]+ */,Az=/^\s*\*?\/*/,Wz=/\n/g,Gz=/\s/,Ez=/\\(.?)/g,Vz={"0":"\x00",r:"\r",n:`
9
- `,t:"\t"};function pZ($){return $.replace(Ez,function(q,Y){switch(Y){case"\\":case"":return Y;default:return Vz[Y]||""}})}lZ.unescape=pZ;function lZ($,q){$=$.toString();var Y=0,T=$.length,X=1,J=0,Q={},U=[],Z=null;function K(H){return Error("illegal "+H+" (line "+X+")")}function A(){var H=Z==="'"?Zz:Uz;H.lastIndex=Y-1;var _=H.exec($);if(!_)throw K("string");return Y=H.lastIndex,D(Z),Z=null,pZ(_[1])}function W(H){return $.charAt(H)}function G(H,_,y){var k={type:$.charAt(H++),lineEmpty:!1,leading:y},m;if(q)m=2;else m=3;var C=H-m,j;do if(--C<0||(j=$.charAt(C))===`
10
- `){k.lineEmpty=!0;break}while(j===" "||j==="\t");var M=$.substring(H,_).split(Wz);for(var h0=0;h0<M.length;++h0)M[h0]=M[h0].replace(q?Az:Kz,"").trim();k.text=M.join(`
11
- `).trim(),Q[X]=k,J=X}function V(H){var _=F(H),y=$.substring(H,_),k=/^\s*\/\//.test(y);return k}function F(H){var _=H;while(_<T&&W(_)!==`
12
- `)_++;return _}function N(){if(U.length>0)return U.shift();if(Z)return A();var H,_,y,k,m,C=Y===0;do{if(Y===T)return null;H=!1;while(Gz.test(y=W(Y))){if(y===`
13
- `)C=!0,++X;if(++Y===T)return null}if(W(Y)==="/"){if(++Y===T)throw K("comment");if(W(Y)==="/")if(!q){m=W(k=Y+1)==="/";while(W(++Y)!==`
14
- `)if(Y===T)return null;if(++Y,m)G(k,Y-1,C),C=!0;++X,H=!0}else{if(k=Y,m=!1,V(Y-1)){m=!0;do{if(Y=F(Y),Y===T)break;if(Y++,!C)break}while(V(Y))}else Y=Math.min(T,F(Y)+1);if(m)G(k,Y,C),C=!0;X++,H=!0}else if((y=W(Y))==="*"){k=Y+1,m=q||W(k)==="*";do{if(y===`
15
- `)++X;if(++Y===T)throw K("comment");_=y,y=W(Y)}while(_!=="*"||y!=="/");if(++Y,m)G(k,Y-2,C),C=!0;H=!0}else return"/"}}while(H);var j=Y;c4.lastIndex=0;var M=c4.test(W(j++));if(!M)while(j<T&&!c4.test(W(j)))++j;var h0=$.substring(Y,Y=j);if(h0==='"'||h0==="'")Z=h0;return h0}function D(H){U.push(H)}function z(){if(!U.length){var H=N();if(H===null)return null;D(H)}return U[0]}function S(H,_){var y=z(),k=y===H;if(k)return N(),!0;if(!_)throw K("token '"+y+"', '"+H+"' expected");return!1}function v(H){var _=null,y;if(H===void 0){if(y=Q[X-1],delete Q[X-1],y&&(q||y.type==="*"||y.lineEmpty))_=y.leading?y.text:null}else{if(J<H)z();if(y=Q[H],delete Q[H],y&&!y.lineEmpty&&(q||y.type==="/"))_=y.leading?null:y.text}return _}return Object.defineProperty({next:N,peek:z,push:D,skip:S,cmnt:v},"line",{get:function(){return X}})}});var tZ=B((Ex,sZ)=>{sZ.exports=Y$;Y$.filename=null;Y$.defaults={keepCase:!1};var Dz=p4(),iZ=NT(),rZ=VT(),aZ=N$(),Fz=ZT(),oZ=c$(),Iz=P1(),Nz=AT(),Hz=KT(),zz=H$(),Mz=p$(),l4=L0(),Bz=/^[1-9][0-9]*$/,Rz=/^-?[1-9][0-9]*$/,Pz=/^0[x][0-9a-fA-F]+$/,Oz=/^-?0[x][0-9a-fA-F]+$/,Lz=/^0[0-7]+$/,wz=/^-?0[0-7]+$/,Sz=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,g1=/^[a-zA-Z_][a-zA-Z_0-9]*$/,m1=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/;function Y$($,q,Y){if(!(q instanceof iZ))Y=q,q=new iZ;if(!Y)Y=Y$.defaults;var T=Y.preferTrailingComment||!1,X=Dz($,Y.alternateCommentMode||!1),J=X.next,Q=X.push,U=X.peek,Z=X.skip,K=X.cmnt,A=!0,W,G,V,F="proto2",N=q,D=[],z={},S=Y.keepCase?function(P){return P}:l4.camelCase;function v(){D.forEach((P)=>{P._edition=F,Object.keys(z).forEach((R)=>{if(P.getOption(R)!==void 0)return;P.setOption(R,z[R],!0)})})}function H(P,R,w){var h=Y$.filename;if(!w)Y$.filename=null;return Error("illegal "+(R||"token")+" '"+P+"' ("+(h?h+", ":"")+"line "+X.line+")")}function _(){var P=[],R;do{if((R=J())!=='"'&&R!=="'")throw H(R);P.push(J()),Z(R),R=U()}while(R==='"'||R==="'");return P.join("")}function y(P){var R=J();switch(R){case"'":case'"':return Q(R),_();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return m(R,!0)}catch(w){if(P&&m1.test(R))return R;throw H(R,"value")}}function k(P,R){var w,h;do if(R&&((w=U())==='"'||w==="'")){var x=_();if(P.push(x),F>=2023)throw H(x,"id")}else try{P.push([h=C(J()),Z("to",!0)?C(J()):h])}catch(W0){if(R&&m1.test(w)&&F>=2023)P.push(w);else throw W0}while(Z(",",!0));var b={options:void 0};b.setOption=function(W0,g0){if(this.options===void 0)this.options={};this.options[W0]=g0},L(b,function(g0){if(g0==="option")T0(b,g0),Z(";");else throw H(g0)},function(){o1(b)})}function m(P,R){var w=1;if(P.charAt(0)==="-")w=-1,P=P.substring(1);switch(P){case"inf":case"INF":case"Inf":return w*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(Bz.test(P))return w*parseInt(P,10);if(Pz.test(P))return w*parseInt(P,16);if(Lz.test(P))return w*parseInt(P,8);if(Sz.test(P))return w*parseFloat(P);throw H(P,"number",R)}function C(P,R){switch(P){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!R&&P.charAt(0)==="-")throw H(P,"id");if(Rz.test(P))return parseInt(P,10);if(Oz.test(P))return parseInt(P,16);if(wz.test(P))return parseInt(P,8);throw H(P,"id")}function j(){if(W!==void 0)throw H("package");if(W=J(),!m1.test(W))throw H(W,"name");N=N.define(W),Z(";")}function M(){var P=U(),R;switch(P){case"weak":R=V||(V=[]),J();break;case"public":J();default:R=G||(G=[]);break}P=_(),Z(";"),R.push(P)}function h0(){if(Z("="),F=_(),F<2023)throw H(F,"syntax");Z(";")}function O(){if(Z("="),F=_(),!["2023"].includes(F))throw H(F,"edition");Z(";")}function E(P,R){switch(R){case"option":return T0(P,R),Z(";"),!0;case"message":return l(P,R),!0;case"enum":return b0(P,R),!0;case"service":return s3(P,R),!0;case"extend":return e3(P,R),!0}return!1}function L(P,R,w){var h=X.line;if(P){if(typeof P.comment!=="string")P.comment=K();P.filename=Y$.filename}if(Z("{",!0)){var x;while((x=J())!=="}")R(x);Z(";",!0)}else{if(w)w();if(Z(";"),P&&(typeof P.comment!=="string"||T))P.comment=K(h)||P.comment}}function l(P,R){if(!g1.test(R=J()))throw H(R,"type name");var w=new rZ(R);if(L(w,function(x){if(E(w,x))return;switch(x){case"map":D0(w,x);break;case"required":if(F!=="proto2")throw H(x);case"repeated":u(w,x);break;case"optional":if(F==="proto3")u(w,"proto3_optional");else if(F!=="proto2")throw H(x);else u(w,"optional");break;case"oneof":_0(w,x);break;case"extensions":k(w.extensions||(w.extensions=[]));break;case"reserved":k(w.reserved||(w.reserved=[]),!0);break;default:if(F==="proto2"||!m1.test(x))throw H(x);Q(x),u(w,"optional");break}}),P.add(w),P===N)D.push(w)}function u(P,R,w){var h=J();if(h==="group"){d(P,R);return}while(h.endsWith(".")||U().startsWith("."))h+=J();if(!m1.test(h))throw H(h,"type");var x=J();if(!g1.test(x))throw H(x,"name");x=S(x),Z("=");var b=new aZ(x,C(J()),h,R,w);if(L(b,function(c0){if(c0==="option")T0(b,c0),Z(";");else throw H(c0)},function(){o1(b)}),R==="proto3_optional"){var W0=new oZ("_"+x);b.setOption("proto3_optional",!0),W0.add(b),P.add(W0)}else P.add(b);if(P===N)D.push(b)}function d(P,R){if(F>=2023)throw H("group");var w=J();if(!g1.test(w))throw H(w,"name");var h=l4.lcFirst(w);if(w===h)w=l4.ucFirst(w);Z("=");var x=C(J()),b=new rZ(w);b.group=!0;var W0=new aZ(h,x,w,R);W0.filename=Y$.filename,L(b,function(c0){switch(c0){case"option":T0(b,c0),Z(";");break;case"required":case"repeated":u(b,c0);break;case"optional":if(F==="proto3")u(b,"proto3_optional");else u(b,"optional");break;case"message":l(b,c0);break;case"enum":b0(b,c0);break;case"reserved":k(b.reserved||(b.reserved=[]),!0);break;default:throw H(c0)}}),P.add(b).add(W0)}function D0(P){Z("<");var R=J();if(Mz.mapKey[R]===void 0)throw H(R,"type");Z(",");var w=J();if(!m1.test(w))throw H(w,"type");Z(">");var h=J();if(!g1.test(h))throw H(h,"name");Z("=");var x=new Fz(S(h),C(J()),R,w);L(x,function(W0){if(W0==="option")T0(x,W0),Z(";");else throw H(W0)},function(){o1(x)}),P.add(x)}function _0(P,R){if(!g1.test(R=J()))throw H(R,"name");var w=new oZ(S(R));L(w,function(x){if(x==="option")T0(w,x),Z(";");else Q(x),u(w,"optional")}),P.add(w)}function b0(P,R){if(!g1.test(R=J()))throw H(R,"name");var w=new Iz(R);if(L(w,function(x){switch(x){case"option":T0(w,x),Z(";");break;case"reserved":if(k(w.reserved||(w.reserved=[]),!0),w.reserved===void 0)w.reserved=[];break;default:R0(w,x)}}),P.add(w),P===N)D.push(w)}function R0(P,R){if(!g1.test(R))throw H(R,"name");Z("=");var w=C(J(),!0),h={options:void 0};h.getOption=function(x){return this.options[x]},h.setOption=function(x,b){zz.prototype.setOption.call(h,x,b)},h.setParsedOption=function(){return},L(h,function(b){if(b==="option")T0(h,b),Z(";");else throw H(b)},function(){o1(h)}),P.add(R,w,h.comment,h.parsedOptions||h.options)}function T0(P,R){var w,h,x=!0;if(R==="option")R=J();while(R!=="="){if(R==="("){var b=J();Z(")"),R="("+b+")"}if(x){if(x=!1,R.includes(".")&&!R.includes("(")){var W0=R.split(".");w=W0[0]+".",R=W0[1];continue}w=R}else h=h?h+=R:R;R=J()}var g0=h?w.concat(h):w,c0=u0(P,g0);h=h&&h[0]==="."?h.slice(1):h,w=w&&w[w.length-1]==="."?w.slice(0,-1):w,d0(P,w,c0,h)}function u0(P,R){if(Z("{",!0)){var w={};while(!Z("}",!0)){if(!g1.test(j0=J()))throw H(j0,"name");if(j0===null)throw H(j0,"end of input");var h,x=j0;if(Z(":",!0),U()==="{")h=u0(P,R+"."+j0);else if(U()==="["){h=[];var b;if(Z("[",!0)){do b=y(!0),h.push(b);while(Z(",",!0));if(Z("]"),typeof b<"u")V0(P,R+"."+j0,b)}}else h=y(!0),V0(P,R+"."+j0,h);var W0=w[x];if(W0)h=[].concat(W0).concat(h);w[x]=h,Z(",",!0),Z(";",!0)}return w}var g0=y(!0);return V0(P,R,g0),g0}function V0(P,R,w){if(N===P&&/^features\./.test(R)){z[R]=w;return}if(P.setOption)P.setOption(R,w)}function d0(P,R,w,h){if(P.setParsedOption)P.setParsedOption(R,w,h)}function o1(P){if(Z("[",!0)){do T0(P,"option");while(Z(",",!0));Z("]")}return P}function s3(P,R){if(!g1.test(R=J()))throw H(R,"service name");var w=new Nz(R);if(L(w,function(x){if(E(w,x))return;if(x==="rpc")t3(w,x);else throw H(x)}),P.add(w),P===N)D.push(w)}function t3(P,R){var w=K(),h=R;if(!g1.test(R=J()))throw H(R,"name");var x=R,b,W0,g0,c0;if(Z("("),Z("stream",!0))W0=!0;if(!m1.test(R=J()))throw H(R);if(b=R,Z(")"),Z("returns"),Z("("),Z("stream",!0))c0=!0;if(!m1.test(R=J()))throw H(R);g0=R,Z(")");var j6=new Hz(x,h,b,g0,W0,c0);j6.comment=w,L(j6,function(D9){if(D9==="option")T0(j6,D9),Z(";");else throw H(D9)}),P.add(j6)}function e3(P,R){if(!m1.test(R=J()))throw H(R,"reference");var w=R;L(null,function(x){switch(x){case"required":case"repeated":u(P,x,w);break;case"optional":if(F==="proto3")u(P,"proto3_optional",w);else u(P,"optional",w);break;default:if(F==="proto2"||!m1.test(x))throw H(x);Q(x),u(P,"optional",w);break}})}var j0;while((j0=J())!==null)switch(j0){case"package":if(!A)throw H(j0);j();break;case"import":if(!A)throw H(j0);M();break;case"syntax":if(!A)throw H(j0);h0();break;case"edition":if(!A)throw H(j0);O();break;case"option":T0(N,j0),Z(";",!0);break;default:if(E(N,j0)){A=!1;continue}throw H(j0)}return v(),Y$.filename=null,{package:W,imports:G,weakImports:V,root:q}}});var qK=B((Vx,$K)=>{$K.exports=L1;var Cz=/\/|\./;function L1($,q){if(!Cz.test($))$="google/protobuf/"+$+".proto",q={nested:{google:{nested:{protobuf:{nested:q}}}}};L1[$]=q}L1("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}});var eZ;L1("duration",{Duration:eZ={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}});L1("timestamp",{Timestamp:eZ});L1("empty",{Empty:{fields:{}}});L1("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}});L1("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}});L1("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}});L1.get=function(q){return L1[q]||null}});var RT=B((Dx,YK)=>{var M$=YK.exports=cZ();M$.build="full";M$.tokenize=p4();M$.parse=tZ();M$.common=qK();M$.Root._configure(M$.Type,M$.parse,M$.common)});var n4=B((Fx,yz)=>{yz.exports={nested:{google:{nested:{protobuf:{options:{go_package:"google.golang.org/protobuf/types/descriptorpb",java_package:"com.google.protobuf",java_outer_classname:"DescriptorProtos",csharp_namespace:"Google.Protobuf.Reflection",objc_class_prefix:"GPB",cc_enable_arenas:!0,optimize_for:"SPEED"},nested:{FileDescriptorSet:{edition:"proto2",fields:{file:{rule:"repeated",type:"FileDescriptorProto",id:1}},extensions:[[536000000,536000000]]},Edition:{edition:"proto2",values:{EDITION_UNKNOWN:0,EDITION_LEGACY:900,EDITION_PROTO2:998,EDITION_PROTO3:999,EDITION_2023:1000,EDITION_2024:1001,EDITION_1_TEST_ONLY:1,EDITION_2_TEST_ONLY:2,EDITION_99997_TEST_ONLY:99997,EDITION_99998_TEST_ONLY:99998,EDITION_99999_TEST_ONLY:99999,EDITION_MAX:2147483647}},FileDescriptorProto:{edition:"proto2",fields:{name:{type:"string",id:1},package:{type:"string",id:2},dependency:{rule:"repeated",type:"string",id:3},publicDependency:{rule:"repeated",type:"int32",id:10},weakDependency:{rule:"repeated",type:"int32",id:11},optionDependency:{rule:"repeated",type:"string",id:15},messageType:{rule:"repeated",type:"DescriptorProto",id:4},enumType:{rule:"repeated",type:"EnumDescriptorProto",id:5},service:{rule:"repeated",type:"ServiceDescriptorProto",id:6},extension:{rule:"repeated",type:"FieldDescriptorProto",id:7},options:{type:"FileOptions",id:8},sourceCodeInfo:{type:"SourceCodeInfo",id:9},syntax:{type:"string",id:12},edition:{type:"Edition",id:14}}},DescriptorProto:{edition:"proto2",fields:{name:{type:"string",id:1},field:{rule:"repeated",type:"FieldDescriptorProto",id:2},extension:{rule:"repeated",type:"FieldDescriptorProto",id:6},nestedType:{rule:"repeated",type:"DescriptorProto",id:3},enumType:{rule:"repeated",type:"EnumDescriptorProto",id:4},extensionRange:{rule:"repeated",type:"ExtensionRange",id:5},oneofDecl:{rule:"repeated",type:"OneofDescriptorProto",id:8},options:{type:"MessageOptions",id:7},reservedRange:{rule:"repeated",type:"ReservedRange",id:9},reservedName:{rule:"repeated",type:"string",id:10},visibility:{type:"SymbolVisibility",id:11}},nested:{ExtensionRange:{fields:{start:{type:"int32",id:1},end:{type:"int32",id:2},options:{type:"ExtensionRangeOptions",id:3}}},ReservedRange:{fields:{start:{type:"int32",id:1},end:{type:"int32",id:2}}}}},ExtensionRangeOptions:{edition:"proto2",fields:{uninterpretedOption:{rule:"repeated",type:"UninterpretedOption",id:999},declaration:{rule:"repeated",type:"Declaration",id:2,options:{retention:"RETENTION_SOURCE"}},features:{type:"FeatureSet",id:50},verification:{type:"VerificationState",id:3,options:{default:"UNVERIFIED",retention:"RETENTION_SOURCE"}}},extensions:[[1000,536870911]],nested:{Declaration:{fields:{number:{type:"int32",id:1},fullName:{type:"string",id:2},type:{type:"string",id:3},reserved:{type:"bool",id:5},repeated:{type:"bool",id:6}},reserved:[[4,4]]},VerificationState:{values:{DECLARATION:0,UNVERIFIED:1}}}},FieldDescriptorProto:{edition:"proto2",fields:{name:{type:"string",id:1},number:{type:"int32",id:3},label:{type:"Label",id:4},type:{type:"Type",id:5},typeName:{type:"string",id:6},extendee:{type:"string",id:2},defaultValue:{type:"string",id:7},oneofIndex:{type:"int32",id:9},jsonName:{type:"string",id:10},options:{type:"FieldOptions",id:8},proto3Optional:{type:"bool",id:17}},nested:{Type:{values:{TYPE_DOUBLE:1,TYPE_FLOAT:2,TYPE_INT64:3,TYPE_UINT64:4,TYPE_INT32:5,TYPE_FIXED64:6,TYPE_FIXED32:7,TYPE_BOOL:8,TYPE_STRING:9,TYPE_GROUP:10,TYPE_MESSAGE:11,TYPE_BYTES:12,TYPE_UINT32:13,TYPE_ENUM:14,TYPE_SFIXED32:15,TYPE_SFIXED64:16,TYPE_SINT32:17,TYPE_SINT64:18}},Label:{values:{LABEL_OPTIONAL:1,LABEL_REPEATED:3,LABEL_REQUIRED:2}}}},OneofDescriptorProto:{edition:"proto2",fields:{name:{type:"string",id:1},options:{type:"OneofOptions",id:2}}},EnumDescriptorProto:{edition:"proto2",fields:{name:{type:"string",id:1},value:{rule:"repeated",type:"EnumValueDescriptorProto",id:2},options:{type:"EnumOptions",id:3},reservedRange:{rule:"repeated",type:"EnumReservedRange",id:4},reservedName:{rule:"repeated",type:"string",id:5},visibility:{type:"SymbolVisibility",id:6}},nested:{EnumReservedRange:{fields:{start:{type:"int32",id:1},end:{type:"int32",id:2}}}}},EnumValueDescriptorProto:{edition:"proto2",fields:{name:{type:"string",id:1},number:{type:"int32",id:2},options:{type:"EnumValueOptions",id:3}}},ServiceDescriptorProto:{edition:"proto2",fields:{name:{type:"string",id:1},method:{rule:"repeated",type:"MethodDescriptorProto",id:2},options:{type:"ServiceOptions",id:3}}},MethodDescriptorProto:{edition:"proto2",fields:{name:{type:"string",id:1},inputType:{type:"string",id:2},outputType:{type:"string",id:3},options:{type:"MethodOptions",id:4},clientStreaming:{type:"bool",id:5},serverStreaming:{type:"bool",id:6}}},FileOptions:{edition:"proto2",fields:{javaPackage:{type:"string",id:1},javaOuterClassname:{type:"string",id:8},javaMultipleFiles:{type:"bool",id:10},javaGenerateEqualsAndHash:{type:"bool",id:20,options:{deprecated:!0}},javaStringCheckUtf8:{type:"bool",id:27},optimizeFor:{type:"OptimizeMode",id:9,options:{default:"SPEED"}},goPackage:{type:"string",id:11},ccGenericServices:{type:"bool",id:16},javaGenericServices:{type:"bool",id:17},pyGenericServices:{type:"bool",id:18},deprecated:{type:"bool",id:23},ccEnableArenas:{type:"bool",id:31,options:{default:!0}},objcClassPrefix:{type:"string",id:36},csharpNamespace:{type:"string",id:37},swiftPrefix:{type:"string",id:39},phpClassPrefix:{type:"string",id:40},phpNamespace:{type:"string",id:41},phpMetadataNamespace:{type:"string",id:44},rubyPackage:{type:"string",id:45},features:{type:"FeatureSet",id:50},uninterpretedOption:{rule:"repeated",type:"UninterpretedOption",id:999}},extensions:[[1000,536870911]],reserved:[[42,42],[38,38],"php_generic_services"],nested:{OptimizeMode:{values:{SPEED:1,CODE_SIZE:2,LITE_RUNTIME:3}}}},MessageOptions:{edition:"proto2",fields:{messageSetWireFormat:{type:"bool",id:1},noStandardDescriptorAccessor:{type:"bool",id:2},deprecated:{type:"bool",id:3},mapEntry:{type:"bool",id:7},deprecatedLegacyJsonFieldConflicts:{type:"bool",id:11,options:{deprecated:!0}},features:{type:"FeatureSet",id:12},uninterpretedOption:{rule:"repeated",type:"UninterpretedOption",id:999}},extensions:[[1000,536870911]],reserved:[[4,4],[5,5],[6,6],[8,8],[9,9]]},FieldOptions:{edition:"proto2",fields:{ctype:{type:"CType",id:1,options:{default:"STRING"}},packed:{type:"bool",id:2},jstype:{type:"JSType",id:6,options:{default:"JS_NORMAL"}},lazy:{type:"bool",id:5},unverifiedLazy:{type:"bool",id:15},deprecated:{type:"bool",id:3},weak:{type:"bool",id:10,options:{deprecated:!0}},debugRedact:{type:"bool",id:16},retention:{type:"OptionRetention",id:17},targets:{rule:"repeated",type:"OptionTargetType",id:19},editionDefaults:{rule:"repeated",type:"EditionDefault",id:20},features:{type:"FeatureSet",id:21},featureSupport:{type:"FeatureSupport",id:22},uninterpretedOption:{rule:"repeated",type:"UninterpretedOption",id:999}},extensions:[[1000,536870911]],reserved:[[4,4],[18,18]],nested:{CType:{values:{STRING:0,CORD:1,STRING_PIECE:2}},JSType:{values:{JS_NORMAL:0,JS_STRING:1,JS_NUMBER:2}},OptionRetention:{values:{RETENTION_UNKNOWN:0,RETENTION_RUNTIME:1,RETENTION_SOURCE:2}},OptionTargetType:{values:{TARGET_TYPE_UNKNOWN:0,TARGET_TYPE_FILE:1,TARGET_TYPE_EXTENSION_RANGE:2,TARGET_TYPE_MESSAGE:3,TARGET_TYPE_FIELD:4,TARGET_TYPE_ONEOF:5,TARGET_TYPE_ENUM:6,TARGET_TYPE_ENUM_ENTRY:7,TARGET_TYPE_SERVICE:8,TARGET_TYPE_METHOD:9}},EditionDefault:{fields:{edition:{type:"Edition",id:3},value:{type:"string",id:2}}},FeatureSupport:{fields:{editionIntroduced:{type:"Edition",id:1},editionDeprecated:{type:"Edition",id:2},deprecationWarning:{type:"string",id:3},editionRemoved:{type:"Edition",id:4}}}}},OneofOptions:{edition:"proto2",fields:{features:{type:"FeatureSet",id:1},uninterpretedOption:{rule:"repeated",type:"UninterpretedOption",id:999}},extensions:[[1000,536870911]]},EnumOptions:{edition:"proto2",fields:{allowAlias:{type:"bool",id:2},deprecated:{type:"bool",id:3},deprecatedLegacyJsonFieldConflicts:{type:"bool",id:6,options:{deprecated:!0}},features:{type:"FeatureSet",id:7},uninterpretedOption:{rule:"repeated",type:"UninterpretedOption",id:999}},extensions:[[1000,536870911]],reserved:[[5,5]]},EnumValueOptions:{edition:"proto2",fields:{deprecated:{type:"bool",id:1},features:{type:"FeatureSet",id:2},debugRedact:{type:"bool",id:3},featureSupport:{type:"FieldOptions.FeatureSupport",id:4},uninterpretedOption:{rule:"repeated",type:"UninterpretedOption",id:999}},extensions:[[1000,536870911]]},ServiceOptions:{edition:"proto2",fields:{features:{type:"FeatureSet",id:34},deprecated:{type:"bool",id:33},uninterpretedOption:{rule:"repeated",type:"UninterpretedOption",id:999}},extensions:[[1000,536870911]]},MethodOptions:{edition:"proto2",fields:{deprecated:{type:"bool",id:33},idempotencyLevel:{type:"IdempotencyLevel",id:34,options:{default:"IDEMPOTENCY_UNKNOWN"}},features:{type:"FeatureSet",id:35},uninterpretedOption:{rule:"repeated",type:"UninterpretedOption",id:999}},extensions:[[1000,536870911]],nested:{IdempotencyLevel:{values:{IDEMPOTENCY_UNKNOWN:0,NO_SIDE_EFFECTS:1,IDEMPOTENT:2}}}},UninterpretedOption:{edition:"proto2",fields:{name:{rule:"repeated",type:"NamePart",id:2},identifierValue:{type:"string",id:3},positiveIntValue:{type:"uint64",id:4},negativeIntValue:{type:"int64",id:5},doubleValue:{type:"double",id:6},stringValue:{type:"bytes",id:7},aggregateValue:{type:"string",id:8}},nested:{NamePart:{fields:{namePart:{rule:"required",type:"string",id:1},isExtension:{rule:"required",type:"bool",id:2}}}}},FeatureSet:{edition:"proto2",fields:{fieldPresence:{type:"FieldPresence",id:1,options:{retention:"RETENTION_RUNTIME",targets:"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2023","edition_defaults.edition":"EDITION_2023","edition_defaults.value":"EXPLICIT"}},enumType:{type:"EnumType",id:2,options:{retention:"RETENTION_RUNTIME",targets:"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2023","edition_defaults.edition":"EDITION_PROTO3","edition_defaults.value":"OPEN"}},repeatedFieldEncoding:{type:"RepeatedFieldEncoding",id:3,options:{retention:"RETENTION_RUNTIME",targets:"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2023","edition_defaults.edition":"EDITION_PROTO3","edition_defaults.value":"PACKED"}},utf8Validation:{type:"Utf8Validation",id:4,options:{retention:"RETENTION_RUNTIME",targets:"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2023","edition_defaults.edition":"EDITION_PROTO3","edition_defaults.value":"VERIFY"}},messageEncoding:{type:"MessageEncoding",id:5,options:{retention:"RETENTION_RUNTIME",targets:"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2023","edition_defaults.edition":"EDITION_LEGACY","edition_defaults.value":"LENGTH_PREFIXED"}},jsonFormat:{type:"JsonFormat",id:6,options:{retention:"RETENTION_RUNTIME",targets:"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2023","edition_defaults.edition":"EDITION_PROTO3","edition_defaults.value":"ALLOW"}},enforceNamingStyle:{type:"EnforceNamingStyle",id:7,options:{retention:"RETENTION_SOURCE",targets:"TARGET_TYPE_METHOD","feature_support.edition_introduced":"EDITION_2024","edition_defaults.edition":"EDITION_2024","edition_defaults.value":"STYLE2024"}},defaultSymbolVisibility:{type:"VisibilityFeature.DefaultSymbolVisibility",id:8,options:{retention:"RETENTION_SOURCE",targets:"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2024","edition_defaults.edition":"EDITION_2024","edition_defaults.value":"EXPORT_TOP_LEVEL"}}},extensions:[[1000,9994],[9995,9999],[1e4,1e4]],reserved:[[999,999]],nested:{FieldPresence:{values:{FIELD_PRESENCE_UNKNOWN:0,EXPLICIT:1,IMPLICIT:2,LEGACY_REQUIRED:3}},EnumType:{values:{ENUM_TYPE_UNKNOWN:0,OPEN:1,CLOSED:2}},RepeatedFieldEncoding:{values:{REPEATED_FIELD_ENCODING_UNKNOWN:0,PACKED:1,EXPANDED:2}},Utf8Validation:{values:{UTF8_VALIDATION_UNKNOWN:0,VERIFY:2,NONE:3}},MessageEncoding:{values:{MESSAGE_ENCODING_UNKNOWN:0,LENGTH_PREFIXED:1,DELIMITED:2}},JsonFormat:{values:{JSON_FORMAT_UNKNOWN:0,ALLOW:1,LEGACY_BEST_EFFORT:2}},EnforceNamingStyle:{values:{ENFORCE_NAMING_STYLE_UNKNOWN:0,STYLE2024:1,STYLE_LEGACY:2}},VisibilityFeature:{fields:{},reserved:[[1,536870911]],nested:{DefaultSymbolVisibility:{values:{DEFAULT_SYMBOL_VISIBILITY_UNKNOWN:0,EXPORT_ALL:1,EXPORT_TOP_LEVEL:2,LOCAL_ALL:3,STRICT:4}}}}}},FeatureSetDefaults:{edition:"proto2",fields:{defaults:{rule:"repeated",type:"FeatureSetEditionDefault",id:1},minimumEdition:{type:"Edition",id:4},maximumEdition:{type:"Edition",id:5}},nested:{FeatureSetEditionDefault:{fields:{edition:{type:"Edition",id:3},overridableFeatures:{type:"FeatureSet",id:4},fixedFeatures:{type:"FeatureSet",id:5}},reserved:[[1,1],[2,2],"features"]}}},SourceCodeInfo:{edition:"proto2",fields:{location:{rule:"repeated",type:"Location",id:1}},extensions:[[536000000,536000000]],nested:{Location:{fields:{path:{rule:"repeated",type:"int32",id:1,options:{packed:!0}},span:{rule:"repeated",type:"int32",id:2,options:{packed:!0}},leadingComments:{type:"string",id:3},trailingComments:{type:"string",id:4},leadingDetachedComments:{rule:"repeated",type:"string",id:6}}}}},GeneratedCodeInfo:{edition:"proto2",fields:{annotation:{rule:"repeated",type:"Annotation",id:1}},nested:{Annotation:{fields:{path:{rule:"repeated",type:"int32",id:1,options:{packed:!0}},sourceFile:{type:"string",id:2},begin:{type:"int32",id:3},end:{type:"int32",id:4},semantic:{type:"Semantic",id:5}},nested:{Semantic:{values:{NONE:0,SET:1,ALIAS:2}}}}}},SymbolVisibility:{edition:"proto2",values:{VISIBILITY_UNSET:0,VISIBILITY_LOCAL:1,VISIBILITY_EXPORT:2}}}}}}}}});var KK=B((c,ZK)=>{var q1=RT();ZK.exports=c=q1.descriptor=q1.Root.fromJSON(n4()).lookup(".google.protobuf");var{Namespace:TK,Root:vY,Enum:T$,Type:f1,Field:B$,MapField:jz,OneOf:PT,Service:xY,Method:OT}=q1;vY.fromDescriptor=function(q){if(typeof q.length==="number")q=c.FileDescriptorSet.decode(q);var Y=new vY;if(q.file){var T,X;for(var J=0,Q;J<q.file.length;++J){if(X=Y,(T=q.file[J]).package&&T.package.length)X=Y.define(T.package);var U=uz(T);if(T.name&&T.name.length)Y.files.push(X.filename=T.name);if(T.messageType)for(Q=0;Q<T.messageType.length;++Q)X.add(f1.fromDescriptor(T.messageType[Q],U));if(T.enumType)for(Q=0;Q<T.enumType.length;++Q)X.add(T$.fromDescriptor(T.enumType[Q],U));if(T.extension)for(Q=0;Q<T.extension.length;++Q)X.add(B$.fromDescriptor(T.extension[Q],U));if(T.service)for(Q=0;Q<T.service.length;++Q)X.add(xY.fromDescriptor(T.service[Q],U));var Z=Lq(T.options,c.FileOptions);if(Z){var K=Object.keys(Z);for(Q=0;Q<K.length;++Q)X.setOption(K[Q],Z[K[Q]])}}}return Y.resolveAll()};vY.prototype.toDescriptor=function(q){var Y=c.FileDescriptorSet.create();return XK(this,Y.file,q),Y};function XK($,q,Y){var T=c.FileDescriptorProto.create({name:$.filename||($.fullName.substring(1).replace(/\./g,"_")||"root")+".proto"});if(dz(Y,T),!($ instanceof vY))T.package=$.fullName.substring(1);for(var X=0,J;X<$.nestedArray.length;++X)if((J=$._nestedArray[X])instanceof f1)T.messageType.push(J.toDescriptor(Y));else if(J instanceof T$)T.enumType.push(J.toDescriptor());else if(J instanceof B$)T.extension.push(J.toDescriptor(Y));else if(J instanceof xY)T.service.push(J.toDescriptor());else if(J instanceof TK)XK(J,q,Y);if(T.options=wq($.options,c.FileOptions),T.messageType.length+T.enumType.length+T.extension.length+T.service.length)q.push(T)}var vz=0;f1.fromDescriptor=function(q,Y,T){if(typeof q.length==="number")q=c.DescriptorProto.decode(q);var X=new f1(q.name.length?q.name:"Type"+vz++,Lq(q.options,c.MessageOptions)),J;if(!T)X._edition=Y;if(q.oneofDecl)for(J=0;J<q.oneofDecl.length;++J)X.add(PT.fromDescriptor(q.oneofDecl[J]));if(q.field)for(J=0;J<q.field.length;++J){var Q=B$.fromDescriptor(q.field[J],Y,!0);if(X.add(Q),q.field[J].hasOwnProperty("oneofIndex"))X.oneofsArray[q.field[J].oneofIndex].add(Q)}if(q.extension)for(J=0;J<q.extension.length;++J)X.add(B$.fromDescriptor(q.extension[J],Y,!0));if(q.nestedType){for(J=0;J<q.nestedType.length;++J)if(X.add(f1.fromDescriptor(q.nestedType[J],Y,!0)),q.nestedType[J].options&&q.nestedType[J].options.mapEntry)X.setOption("map_entry",!0)}if(q.enumType)for(J=0;J<q.enumType.length;++J)X.add(T$.fromDescriptor(q.enumType[J],Y,!0));if(q.extensionRange&&q.extensionRange.length){X.extensions=[];for(J=0;J<q.extensionRange.length;++J)X.extensions.push([q.extensionRange[J].start,q.extensionRange[J].end])}if(q.reservedRange&&q.reservedRange.length||q.reservedName&&q.reservedName.length){if(X.reserved=[],q.reservedRange)for(J=0;J<q.reservedRange.length;++J)X.reserved.push([q.reservedRange[J].start,q.reservedRange[J].end]);if(q.reservedName)for(J=0;J<q.reservedName.length;++J)X.reserved.push(q.reservedName[J])}return X};f1.prototype.toDescriptor=function(q){var Y=c.DescriptorProto.create({name:this.name}),T;for(T=0;T<this.fieldsArray.length;++T){var X;if(Y.field.push(X=this._fieldsArray[T].toDescriptor(q)),this._fieldsArray[T]instanceof jz){var J=i4(this._fieldsArray[T].keyType,this._fieldsArray[T].resolvedKeyType,!1),Q=i4(this._fieldsArray[T].type,this._fieldsArray[T].resolvedType,!1),U=Q===11||Q===14?this._fieldsArray[T].resolvedType&&UK(this.parent,this._fieldsArray[T].resolvedType)||this._fieldsArray[T].type:void 0;Y.nestedType.push(c.DescriptorProto.create({name:X.typeName,field:[c.FieldDescriptorProto.create({name:"key",number:1,label:1,type:J}),c.FieldDescriptorProto.create({name:"value",number:2,label:1,type:Q,typeName:U})],options:c.MessageOptions.create({mapEntry:!0})}))}}for(T=0;T<this.oneofsArray.length;++T)Y.oneofDecl.push(this._oneofsArray[T].toDescriptor());for(T=0;T<this.nestedArray.length;++T)if(this._nestedArray[T]instanceof B$)Y.field.push(this._nestedArray[T].toDescriptor(q));else if(this._nestedArray[T]instanceof f1)Y.nestedType.push(this._nestedArray[T].toDescriptor(q));else if(this._nestedArray[T]instanceof T$)Y.enumType.push(this._nestedArray[T].toDescriptor());if(this.extensions)for(T=0;T<this.extensions.length;++T)Y.extensionRange.push(c.DescriptorProto.ExtensionRange.create({start:this.extensions[T][0],end:this.extensions[T][1]}));if(this.reserved)for(T=0;T<this.reserved.length;++T)if(typeof this.reserved[T]==="string")Y.reservedName.push(this.reserved[T]);else Y.reservedRange.push(c.DescriptorProto.ReservedRange.create({start:this.reserved[T][0],end:this.reserved[T][1]}));return Y.options=wq(this.options,c.MessageOptions),Y};var xz=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/;B$.fromDescriptor=function(q,Y,T){if(typeof q.length==="number")q=c.DescriptorProto.decode(q);if(typeof q.number!=="number")throw Error("missing field id");var X;if(q.typeName&&q.typeName.length)X=q.typeName;else X=mz(q.type);var J;switch(q.label){case 1:J=void 0;break;case 2:J="required";break;case 3:J="repeated";break;default:throw Error("illegal label: "+q.label)}var Q=q.extendee;if(q.extendee!==void 0)Q=Q.length?Q:void 0;var U=new B$(q.name.length?q.name:"field"+q.number,q.number,X,J,Q);if(!T)U._edition=Y;if(U.options=Lq(q.options,c.FieldOptions),q.proto3_optional)U.options.proto3_optional=!0;if(q.defaultValue&&q.defaultValue.length){var Z=q.defaultValue;switch(Z){case"true":case"TRUE":Z=!0;break;case"false":case"FALSE":Z=!1;break;default:var K=xz.exec(Z);if(K)Z=parseInt(Z);break}U.setOption("default",Z)}if(fz(q.type)){if(Y==="proto3"){if(q.options&&!q.options.packed)U.setOption("packed",!1)}else if((!Y||Y==="proto2")&&q.options&&q.options.packed)U.setOption("packed",!0)}return U};B$.prototype.toDescriptor=function(q){var Y=c.FieldDescriptorProto.create({name:this.name,number:this.id});if(this.map)Y.type=11,Y.typeName=q1.util.ucFirst(this.name),Y.label=3;else{switch(Y.type=i4(this.type,this.resolve().resolvedType,this.delimited)){case 10:case 11:case 14:Y.typeName=this.resolvedType?UK(this.parent,this.resolvedType):this.type;break}if(this.rule==="repeated")Y.label=3;else if(this.required&&q==="proto2")Y.label=2;else Y.label=1}if(Y.extendee=this.extensionField?this.extensionField.parent.fullName:this.extend,this.partOf){if((Y.oneofIndex=this.parent.oneofsArray.indexOf(this.partOf))<0)throw Error("missing oneof")}if(this.options){if(Y.options=wq(this.options,c.FieldOptions),this.options.default!=null)Y.defaultValue=String(this.options.default);if(this.options.proto3_optional)Y.proto3_optional=!0}if(q==="proto3"){if(!this.packed)(Y.options||(Y.options=c.FieldOptions.create())).packed=!1}else if((!q||q==="proto2")&&this.packed)(Y.options||(Y.options=c.FieldOptions.create())).packed=!0;return Y};var kz=0;T$.fromDescriptor=function(q,Y,T){if(typeof q.length==="number")q=c.EnumDescriptorProto.decode(q);var X={};if(q.value)for(var J=0;J<q.value.length;++J){var Q=q.value[J].name,U=q.value[J].number||0;X[Q&&Q.length?Q:"NAME"+U]=U}var Z=new T$(q.name&&q.name.length?q.name:"Enum"+kz++,X,Lq(q.options,c.EnumOptions));if(!T)Z._edition=Y;return Z};T$.prototype.toDescriptor=function(){var q=[];for(var Y=0,T=Object.keys(this.values);Y<T.length;++Y)q.push(c.EnumValueDescriptorProto.create({name:T[Y],number:this.values[T[Y]]}));return c.EnumDescriptorProto.create({name:this.name,value:q,options:wq(this.options,c.EnumOptions)})};var hz=0;PT.fromDescriptor=function(q){if(typeof q.length==="number")q=c.OneofDescriptorProto.decode(q);return new PT(q.name&&q.name.length?q.name:"oneof"+hz++)};PT.prototype.toDescriptor=function(){return c.OneofDescriptorProto.create({name:this.name})};var _z=0;xY.fromDescriptor=function(q,Y,T){if(typeof q.length==="number")q=c.ServiceDescriptorProto.decode(q);var X=new xY(q.name&&q.name.length?q.name:"Service"+_z++,Lq(q.options,c.ServiceOptions));if(!T)X._edition=Y;if(q.method)for(var J=0;J<q.method.length;++J)X.add(OT.fromDescriptor(q.method[J]));return X};xY.prototype.toDescriptor=function(){var q=[];for(var Y=0;Y<this.methodsArray.length;++Y)q.push(this._methodsArray[Y].toDescriptor());return c.ServiceDescriptorProto.create({name:this.name,method:q,options:wq(this.options,c.ServiceOptions)})};var gz=0;OT.fromDescriptor=function(q){if(typeof q.length==="number")q=c.MethodDescriptorProto.decode(q);return new OT(q.name&&q.name.length?q.name:"Method"+gz++,"rpc",q.inputType,q.outputType,Boolean(q.clientStreaming),Boolean(q.serverStreaming),Lq(q.options,c.MethodOptions))};OT.prototype.toDescriptor=function(){return c.MethodDescriptorProto.create({name:this.name,inputType:this.resolvedRequestType?this.resolvedRequestType.fullName:this.requestType,outputType:this.resolvedResponseType?this.resolvedResponseType.fullName:this.responseType,clientStreaming:this.requestStream,serverStreaming:this.responseStream,options:wq(this.options,c.MethodOptions)})};function mz($){switch($){case 1:return"double";case 2:return"float";case 3:return"int64";case 4:return"uint64";case 5:return"int32";case 6:return"fixed64";case 7:return"fixed32";case 8:return"bool";case 9:return"string";case 12:return"bytes";case 13:return"uint32";case 15:return"sfixed32";case 16:return"sfixed64";case 17:return"sint32";case 18:return"sint64"}throw Error("illegal type: "+$)}function fz($){switch($){case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 13:case 14:case 15:case 16:case 17:case 18:return!0}return!1}function i4($,q,Y){switch($){case"double":return 1;case"float":return 2;case"int64":return 3;case"uint64":return 4;case"int32":return 5;case"fixed64":return 6;case"fixed32":return 7;case"bool":return 8;case"string":return 9;case"bytes":return 12;case"uint32":return 13;case"sfixed32":return 15;case"sfixed64":return 16;case"sint32":return 17;case"sint64":return 18}if(q instanceof T$)return 14;if(q instanceof f1)return Y?10:11;throw Error("illegal type: "+$)}function JK($,q){var Y={};for(var T=0,X,J;T<q.fieldsArray.length;++T){if((J=(X=q._fieldsArray[T]).name)==="uninterpretedOption")continue;if(!Object.prototype.hasOwnProperty.call($,J))continue;var Q=bz(J);if(X.resolvedType instanceof f1)Y[Q]=JK($[J],X.resolvedType);else if(X.resolvedType instanceof T$)Y[Q]=X.resolvedType.valuesById[$[J]];else Y[Q]=$[J]}return Y}function Lq($,q){if(!$)return;return JK(q.toObject($),q)}function QK($,q){var Y={},T=Object.keys($);for(var X=0;X<T.length;++X){var J=T[X],Q=q1.util.camelCase(J);if(!Object.prototype.hasOwnProperty.call(q.fields,Q))continue;var U=q.fields[Q];if(U.resolvedType instanceof f1)Y[Q]=QK($[J],U.resolvedType);else Y[Q]=$[J];if(U.repeated&&!Array.isArray(Y[Q]))Y[Q]=[Y[Q]]}return Y}function wq($,q){if(!$)return;return q.fromObject(QK($,q))}function UK($,q){var Y=$.fullName.split("."),T=q.fullName.split("."),X=0,J=0,Q=T.length-1;if(!($ instanceof vY)&&q instanceof TK)while(X<Y.length&&J<Q&&Y[X]===T[J]){var U=q.lookup(Y[X++],!0);if(U!==null&&U!==q)break;++J}else for(;X<Y.length&&J<Q&&Y[X]===T[J];++X,++J);return T.slice(J).join(".")}function bz($){return $.substring(0,1)+$.substring(1).replace(/([A-Z])(?=[a-z]|$)/g,function(q,Y){return"_"+Y.toLowerCase()})}function uz($){if($.syntax==="editions")switch($.edition){case c.Edition.EDITION_2023:return"2023";default:throw Error("Unsupported edition "+$.edition)}if($.syntax==="proto3")return"proto3";return"proto2"}function dz($,q){if(!$)return;if($==="proto2"||$==="proto3")q.syntax=$;else switch(q.syntax="editions",$){case"2023":q.edition=c.Edition.EDITION_2023;break;default:throw Error("Unsupported edition "+$)}}});var AK=B((Ix,cz)=>{cz.exports={nested:{google:{nested:{protobuf:{nested:{Api:{fields:{name:{type:"string",id:1},methods:{rule:"repeated",type:"Method",id:2},options:{rule:"repeated",type:"Option",id:3},version:{type:"string",id:4},sourceContext:{type:"SourceContext",id:5},mixins:{rule:"repeated",type:"Mixin",id:6},syntax:{type:"Syntax",id:7}}},Method:{fields:{name:{type:"string",id:1},requestTypeUrl:{type:"string",id:2},requestStreaming:{type:"bool",id:3},responseTypeUrl:{type:"string",id:4},responseStreaming:{type:"bool",id:5},options:{rule:"repeated",type:"Option",id:6},syntax:{type:"Syntax",id:7}}},Mixin:{fields:{name:{type:"string",id:1},root:{type:"string",id:2}}},SourceContext:{fields:{fileName:{type:"string",id:1}}},Option:{fields:{name:{type:"string",id:1},value:{type:"Any",id:2}}},Syntax:{values:{SYNTAX_PROTO2:0,SYNTAX_PROTO3:1}}}}}}}}});var WK=B((Nx,pz)=>{pz.exports={nested:{google:{nested:{protobuf:{nested:{SourceContext:{fields:{fileName:{type:"string",id:1}}}}}}}}}});var GK=B((Hx,lz)=>{lz.exports={nested:{google:{nested:{protobuf:{nested:{Type:{fields:{name:{type:"string",id:1},fields:{rule:"repeated",type:"Field",id:2},oneofs:{rule:"repeated",type:"string",id:3},options:{rule:"repeated",type:"Option",id:4},sourceContext:{type:"SourceContext",id:5},syntax:{type:"Syntax",id:6}}},Field:{fields:{kind:{type:"Kind",id:1},cardinality:{type:"Cardinality",id:2},number:{type:"int32",id:3},name:{type:"string",id:4},typeUrl:{type:"string",id:6},oneofIndex:{type:"int32",id:7},packed:{type:"bool",id:8},options:{rule:"repeated",type:"Option",id:9},jsonName:{type:"string",id:10},defaultValue:{type:"string",id:11}},nested:{Kind:{values:{TYPE_UNKNOWN:0,TYPE_DOUBLE:1,TYPE_FLOAT:2,TYPE_INT64:3,TYPE_UINT64:4,TYPE_INT32:5,TYPE_FIXED64:6,TYPE_FIXED32:7,TYPE_BOOL:8,TYPE_STRING:9,TYPE_GROUP:10,TYPE_MESSAGE:11,TYPE_BYTES:12,TYPE_UINT32:13,TYPE_ENUM:14,TYPE_SFIXED32:15,TYPE_SFIXED64:16,TYPE_SINT32:17,TYPE_SINT64:18}},Cardinality:{values:{CARDINALITY_UNKNOWN:0,CARDINALITY_OPTIONAL:1,CARDINALITY_REQUIRED:2,CARDINALITY_REPEATED:3}}}},Enum:{fields:{name:{type:"string",id:1},enumvalue:{rule:"repeated",type:"EnumValue",id:2},options:{rule:"repeated",type:"Option",id:3},sourceContext:{type:"SourceContext",id:4},syntax:{type:"Syntax",id:5}}},EnumValue:{fields:{name:{type:"string",id:1},number:{type:"int32",id:2},options:{rule:"repeated",type:"Option",id:3}}},Option:{fields:{name:{type:"string",id:1},value:{type:"Any",id:2}}},Syntax:{values:{SYNTAX_PROTO2:0,SYNTAX_PROTO3:1}},Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}},SourceContext:{fields:{fileName:{type:"string",id:1}}}}}}}}}});var NK=B((FK)=>{Object.defineProperty(FK,"__esModule",{value:!0});FK.addCommonProtos=FK.loadProtosWithOptionsSync=FK.loadProtosWithOptions=void 0;var EK=e("fs"),VK=e("path"),Sq=RT();function DK($,q){let Y=$.resolvePath;$.resolvePath=(T,X)=>{if(VK.isAbsolute(X))return X;for(let J of q){let Q=VK.join(J,X);try{return EK.accessSync(Q,EK.constants.R_OK),Q}catch(U){continue}}return process.emitWarning(`${X} not found in any of the include paths ${q}`),Y(T,X)}}async function nz($,q){let Y=new Sq.Root;if(q=q||{},q.includeDirs){if(!Array.isArray(q.includeDirs))return Promise.reject(Error("The includeDirs option must be an array"));DK(Y,q.includeDirs)}let T=await Y.load($,q);return T.resolveAll(),T}FK.loadProtosWithOptions=nz;function iz($,q){let Y=new Sq.Root;if(q=q||{},q.includeDirs){if(!Array.isArray(q.includeDirs))throw Error("The includeDirs option must be an array");DK(Y,q.includeDirs)}let T=Y.loadSync($,q);return T.resolveAll(),T}FK.loadProtosWithOptionsSync=iz;function rz(){let $=AK(),q=n4(),Y=WK(),T=GK();Sq.common("api",$.nested.google.nested.protobuf.nested),Sq.common("descriptor",q.nested.google.nested.protobuf.nested),Sq.common("source_context",Y.nested.google.nested.protobuf.nested),Sq.common("type",T.nested.google.nested.protobuf.nested)}FK.addCommonProtos=rz});var HK=B((kY,r4)=>{(function($,q){function Y(T){return T.default||T}if(typeof define==="function"&&define.amd)define([],function(){var T={};return q(T),Y(T)});else if(typeof kY==="object"){if(q(kY),typeof r4==="object")r4.exports=Y(kY)}else(function(){var T={};q(T),$.Long=Y(T)})()})(typeof globalThis<"u"?globalThis:typeof self<"u"?self:kY,function($){Object.defineProperty($,"__esModule",{value:!0}),$.default=void 0;var q=null;try{q=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function Y(O,E,L){this.low=O|0,this.high=E|0,this.unsigned=!!L}Y.prototype.__isLong__,Object.defineProperty(Y.prototype,"__isLong__",{value:!0});function T(O){return(O&&O.__isLong__)===!0}function X(O){var E=Math.clz32(O&-O);return O?31-E:E}Y.isLong=T;var J={},Q={};function U(O,E){var L,l,u;if(E){if(O>>>=0,u=0<=O&&O<256){if(l=Q[O],l)return l}if(L=K(O,0,!0),u)Q[O]=L;return L}else{if(O|=0,u=-128<=O&&O<128){if(l=J[O],l)return l}if(L=K(O,O<0?-1:0,!1),u)J[O]=L;return L}}Y.fromInt=U;function Z(O,E){if(isNaN(O))return E?H:v;if(E){if(O<0)return H;if(O>=D)return C}else{if(O<=-z)return j;if(O+1>=z)return m}if(O<0)return Z(-O,E).neg();return K(O%N|0,O/N|0,E)}Y.fromNumber=Z;function K(O,E,L){return new Y(O,E,L)}Y.fromBits=K;var A=Math.pow;function W(O,E,L){if(O.length===0)throw Error("empty string");if(typeof E==="number")L=E,E=!1;else E=!!E;if(O==="NaN"||O==="Infinity"||O==="+Infinity"||O==="-Infinity")return E?H:v;if(L=L||10,L<2||36<L)throw RangeError("radix");var l;if((l=O.indexOf("-"))>0)throw Error("interior hyphen");else if(l===0)return W(O.substring(1),E,L).neg();var u=Z(A(L,8)),d=v;for(var D0=0;D0<O.length;D0+=8){var _0=Math.min(8,O.length-D0),b0=parseInt(O.substring(D0,D0+_0),L);if(_0<8){var R0=Z(A(L,_0));d=d.mul(R0).add(Z(b0))}else d=d.mul(u),d=d.add(Z(b0))}return d.unsigned=E,d}Y.fromString=W;function G(O,E){if(typeof O==="number")return Z(O,E);if(typeof O==="string")return W(O,E);return K(O.low,O.high,typeof E==="boolean"?E:O.unsigned)}Y.fromValue=G;var V=65536,F=16777216,N=V*V,D=N*N,z=D/2,S=U(F),v=U(0);Y.ZERO=v;var H=U(0,!0);Y.UZERO=H;var _=U(1);Y.ONE=_;var y=U(1,!0);Y.UONE=y;var k=U(-1);Y.NEG_ONE=k;var m=K(-1,2147483647,!1);Y.MAX_VALUE=m;var C=K(-1,-1,!0);Y.MAX_UNSIGNED_VALUE=C;var j=K(0,-2147483648,!1);Y.MIN_VALUE=j;var M=Y.prototype;if(M.toInt=function(){return this.unsigned?this.low>>>0:this.low},M.toNumber=function(){if(this.unsigned)return(this.high>>>0)*N+(this.low>>>0);return this.high*N+(this.low>>>0)},M.toString=function(E){if(E=E||10,E<2||36<E)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative())if(this.eq(j)){var L=Z(E),l=this.div(L),u=l.mul(L).sub(this);return l.toString(E)+u.toInt().toString(E)}else return"-"+this.neg().toString(E);var d=Z(A(E,6),this.unsigned),D0=this,_0="";while(!0){var b0=D0.div(d),R0=D0.sub(b0.mul(d)).toInt()>>>0,T0=R0.toString(E);if(D0=b0,D0.isZero())return T0+_0;else{while(T0.length<6)T0="0"+T0;_0=""+T0+_0}}},M.getHighBits=function(){return this.high},M.getHighBitsUnsigned=function(){return this.high>>>0},M.getLowBits=function(){return this.low},M.getLowBitsUnsigned=function(){return this.low>>>0},M.getNumBitsAbs=function(){if(this.isNegative())return this.eq(j)?64:this.neg().getNumBitsAbs();var E=this.high!=0?this.high:this.low;for(var L=31;L>0;L--)if((E&1<<L)!=0)break;return this.high!=0?L+33:L+1},M.isSafeInteger=function(){var E=this.high>>21;if(!E)return!0;if(this.unsigned)return!1;return E===-1&&!(this.low===0&&this.high===-2097152)},M.isZero=function(){return this.high===0&&this.low===0},M.eqz=M.isZero,M.isNegative=function(){return!this.unsigned&&this.high<0},M.isPositive=function(){return this.unsigned||this.high>=0},M.isOdd=function(){return(this.low&1)===1},M.isEven=function(){return(this.low&1)===0},M.equals=function(E){if(!T(E))E=G(E);if(this.unsigned!==E.unsigned&&this.high>>>31===1&&E.high>>>31===1)return!1;return this.high===E.high&&this.low===E.low},M.eq=M.equals,M.notEquals=function(E){return!this.eq(E)},M.neq=M.notEquals,M.ne=M.notEquals,M.lessThan=function(E){return this.comp(E)<0},M.lt=M.lessThan,M.lessThanOrEqual=function(E){return this.comp(E)<=0},M.lte=M.lessThanOrEqual,M.le=M.lessThanOrEqual,M.greaterThan=function(E){return this.comp(E)>0},M.gt=M.greaterThan,M.greaterThanOrEqual=function(E){return this.comp(E)>=0},M.gte=M.greaterThanOrEqual,M.ge=M.greaterThanOrEqual,M.compare=function(E){if(!T(E))E=G(E);if(this.eq(E))return 0;var L=this.isNegative(),l=E.isNegative();if(L&&!l)return-1;if(!L&&l)return 1;if(!this.unsigned)return this.sub(E).isNegative()?-1:1;return E.high>>>0>this.high>>>0||E.high===this.high&&E.low>>>0>this.low>>>0?-1:1},M.comp=M.compare,M.negate=function(){if(!this.unsigned&&this.eq(j))return j;return this.not().add(_)},M.neg=M.negate,M.add=function(E){if(!T(E))E=G(E);var L=this.high>>>16,l=this.high&65535,u=this.low>>>16,d=this.low&65535,D0=E.high>>>16,_0=E.high&65535,b0=E.low>>>16,R0=E.low&65535,T0=0,u0=0,V0=0,d0=0;return d0+=d+R0,V0+=d0>>>16,d0&=65535,V0+=u+b0,u0+=V0>>>16,V0&=65535,u0+=l+_0,T0+=u0>>>16,u0&=65535,T0+=L+D0,T0&=65535,K(V0<<16|d0,T0<<16|u0,this.unsigned)},M.subtract=function(E){if(!T(E))E=G(E);return this.add(E.neg())},M.sub=M.subtract,M.multiply=function(E){if(this.isZero())return this;if(!T(E))E=G(E);if(q){var L=q.mul(this.low,this.high,E.low,E.high);return K(L,q.get_high(),this.unsigned)}if(E.isZero())return this.unsigned?H:v;if(this.eq(j))return E.isOdd()?j:v;if(E.eq(j))return this.isOdd()?j:v;if(this.isNegative())if(E.isNegative())return this.neg().mul(E.neg());else return this.neg().mul(E).neg();else if(E.isNegative())return this.mul(E.neg()).neg();if(this.lt(S)&&E.lt(S))return Z(this.toNumber()*E.toNumber(),this.unsigned);var l=this.high>>>16,u=this.high&65535,d=this.low>>>16,D0=this.low&65535,_0=E.high>>>16,b0=E.high&65535,R0=E.low>>>16,T0=E.low&65535,u0=0,V0=0,d0=0,o1=0;return o1+=D0*T0,d0+=o1>>>16,o1&=65535,d0+=d*T0,V0+=d0>>>16,d0&=65535,d0+=D0*R0,V0+=d0>>>16,d0&=65535,V0+=u*T0,u0+=V0>>>16,V0&=65535,V0+=d*R0,u0+=V0>>>16,V0&=65535,V0+=D0*b0,u0+=V0>>>16,V0&=65535,u0+=l*T0+u*R0+d*b0+D0*_0,u0&=65535,K(d0<<16|o1,u0<<16|V0,this.unsigned)},M.mul=M.multiply,M.divide=function(E){if(!T(E))E=G(E);if(E.isZero())throw Error("division by zero");if(q){if(!this.unsigned&&this.high===-2147483648&&E.low===-1&&E.high===-1)return this;var L=(this.unsigned?q.div_u:q.div_s)(this.low,this.high,E.low,E.high);return K(L,q.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?H:v;var l,u,d;if(!this.unsigned){if(this.eq(j))if(E.eq(_)||E.eq(k))return j;else if(E.eq(j))return _;else{var D0=this.shr(1);if(l=D0.div(E).shl(1),l.eq(v))return E.isNegative()?_:k;else return u=this.sub(E.mul(l)),d=l.add(u.div(E)),d}else if(E.eq(j))return this.unsigned?H:v;if(this.isNegative()){if(E.isNegative())return this.neg().div(E.neg());return this.neg().div(E).neg()}else if(E.isNegative())return this.div(E.neg()).neg();d=v}else{if(!E.unsigned)E=E.toUnsigned();if(E.gt(this))return H;if(E.gt(this.shru(1)))return y;d=H}u=this;while(u.gte(E)){l=Math.max(1,Math.floor(u.toNumber()/E.toNumber()));var _0=Math.ceil(Math.log(l)/Math.LN2),b0=_0<=48?1:A(2,_0-48),R0=Z(l),T0=R0.mul(E);while(T0.isNegative()||T0.gt(u))l-=b0,R0=Z(l,this.unsigned),T0=R0.mul(E);if(R0.isZero())R0=_;d=d.add(R0),u=u.sub(T0)}return d},M.div=M.divide,M.modulo=function(E){if(!T(E))E=G(E);if(q){var L=(this.unsigned?q.rem_u:q.rem_s)(this.low,this.high,E.low,E.high);return K(L,q.get_high(),this.unsigned)}return this.sub(this.div(E).mul(E))},M.mod=M.modulo,M.rem=M.modulo,M.not=function(){return K(~this.low,~this.high,this.unsigned)},M.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},M.clz=M.countLeadingZeros,M.countTrailingZeros=function(){return this.low?X(this.low):X(this.high)+32},M.ctz=M.countTrailingZeros,M.and=function(E){if(!T(E))E=G(E);return K(this.low&E.low,this.high&E.high,this.unsigned)},M.or=function(E){if(!T(E))E=G(E);return K(this.low|E.low,this.high|E.high,this.unsigned)},M.xor=function(E){if(!T(E))E=G(E);return K(this.low^E.low,this.high^E.high,this.unsigned)},M.shiftLeft=function(E){if(T(E))E=E.toInt();if((E&=63)===0)return this;else if(E<32)return K(this.low<<E,this.high<<E|this.low>>>32-E,this.unsigned);else return K(0,this.low<<E-32,this.unsigned)},M.shl=M.shiftLeft,M.shiftRight=function(E){if(T(E))E=E.toInt();if((E&=63)===0)return this;else if(E<32)return K(this.low>>>E|this.high<<32-E,this.high>>E,this.unsigned);else return K(this.high>>E-32,this.high>=0?0:-1,this.unsigned)},M.shr=M.shiftRight,M.shiftRightUnsigned=function(E){if(T(E))E=E.toInt();if((E&=63)===0)return this;if(E<32)return K(this.low>>>E|this.high<<32-E,this.high>>>E,this.unsigned);if(E===32)return K(this.high,0,this.unsigned);return K(this.high>>>E-32,0,this.unsigned)},M.shru=M.shiftRightUnsigned,M.shr_u=M.shiftRightUnsigned,M.rotateLeft=function(E){var L;if(T(E))E=E.toInt();if((E&=63)===0)return this;if(E===32)return K(this.high,this.low,this.unsigned);if(E<32)return L=32-E,K(this.low<<E|this.high>>>L,this.high<<E|this.low>>>L,this.unsigned);return E-=32,L=32-E,K(this.high<<E|this.low>>>L,this.low<<E|this.high>>>L,this.unsigned)},M.rotl=M.rotateLeft,M.rotateRight=function(E){var L;if(T(E))E=E.toInt();if((E&=63)===0)return this;if(E===32)return K(this.high,this.low,this.unsigned);if(E<32)return L=32-E,K(this.high<<L|this.low>>>E,this.low<<L|this.high>>>E,this.unsigned);return E-=32,L=32-E,K(this.low<<L|this.high>>>E,this.high<<L|this.low>>>E,this.unsigned)},M.rotr=M.rotateRight,M.toSigned=function(){if(!this.unsigned)return this;return K(this.low,this.high,!1)},M.toUnsigned=function(){if(this.unsigned)return this;return K(this.low,this.high,!0)},M.toBytes=function(E){return E?this.toBytesLE():this.toBytesBE()},M.toBytesLE=function(){var E=this.high,L=this.low;return[L&255,L>>>8&255,L>>>16&255,L>>>24,E&255,E>>>8&255,E>>>16&255,E>>>24]},M.toBytesBE=function(){var E=this.high,L=this.low;return[E>>>24,E>>>16&255,E>>>8&255,E&255,L>>>24,L>>>16&255,L>>>8&255,L&255]},Y.fromBytes=function(E,L,l){return l?Y.fromBytesLE(E,L):Y.fromBytesBE(E,L)},Y.fromBytesLE=function(E,L){return new Y(E[0]|E[1]<<8|E[2]<<16|E[3]<<24,E[4]|E[5]<<8|E[6]<<16|E[7]<<24,L)},Y.fromBytesBE=function(E,L){return new Y(E[4]<<24|E[5]<<16|E[6]<<8|E[7],E[0]<<24|E[1]<<16|E[2]<<8|E[3],L)},typeof BigInt==="function")Y.fromBigInt=function(E,L){var l=Number(BigInt.asIntN(32,E)),u=Number(BigInt.asIntN(32,E>>BigInt(32)));return K(l,u,L)},Y.fromValue=function(E,L){if(typeof E==="bigint")return Y.fromBigInt(E,L);return G(E,L)},M.toBigInt=function(){var E=BigInt(this.low>>>0),L=BigInt(this.unsigned?this.high>>>0:this.high);return L<<BigInt(32)|E};var h0=$.default=Y})});var hY=B((OK)=>{Object.defineProperty(OK,"__esModule",{value:!0});OK.loadFileDescriptorSetFromObject=OK.loadFileDescriptorSetFromBuffer=OK.fromJSON=OK.loadSync=OK.load=OK.IdempotencyLevel=OK.isAnyExtension=OK.Long=void 0;var sz=A7(),b1=RT(),t4=KK(),e4=NK(),tz=HK();OK.Long=tz;function ez($){return"@type"in $&&typeof $["@type"]==="string"}OK.isAnyExtension=ez;var MK;(function($){$.IDEMPOTENCY_UNKNOWN="IDEMPOTENCY_UNKNOWN",$.NO_SIDE_EFFECTS="NO_SIDE_EFFECTS",$.IDEMPOTENT="IDEMPOTENT"})(MK=OK.IdempotencyLevel||(OK.IdempotencyLevel={}));var BK={longs:String,enums:String,bytes:String,defaults:!0,oneofs:!0,json:!0};function $M($,q){if($==="")return q;else return $+"."+q}function qM($){return $ instanceof b1.Service||$ instanceof b1.Type||$ instanceof b1.Enum}function YM($){return $ instanceof b1.Namespace||$ instanceof b1.Root}function RK($,q){let Y=$M(q,$.name);if(qM($))return[[Y,$]];else if(YM($)&&typeof $.nested<"u")return Object.keys($.nested).map((T)=>{return RK($.nested[T],Y)}).reduce((T,X)=>T.concat(X),[]);return[]}function a4($,q){return function(T){return $.toObject($.decode(T),q)}}function o4($){return function(Y){if(Array.isArray(Y))throw Error(`Failed to serialize message: expected object with ${$.name} structure, got array instead`);let T=$.fromObject(Y);return $.encode(T).finish()}}function TM($){return($||[]).reduce((q,Y)=>{for(let[T,X]of Object.entries(Y))switch(T){case"uninterpreted_option":q.uninterpreted_option.push(Y.uninterpreted_option);break;default:q[T]=X}return q},{deprecated:!1,idempotency_level:MK.IDEMPOTENCY_UNKNOWN,uninterpreted_option:[]})}function XM($,q,Y,T){let{resolvedRequestType:X,resolvedResponseType:J}=$;return{path:"/"+q+"/"+$.name,requestStream:!!$.requestStream,responseStream:!!$.responseStream,requestSerialize:o4(X),requestDeserialize:a4(X,Y),responseSerialize:o4(J),responseDeserialize:a4(J,Y),originalName:sz($.name),requestType:s4(X,Y,T),responseType:s4(J,Y,T),options:TM($.parsedOptions)}}function JM($,q,Y,T){let X={};for(let J of $.methodsArray)X[J.name]=XM(J,q,Y,T);return X}function s4($,q,Y){let T=$.toDescriptor("proto3");return{format:"Protocol Buffer 3 DescriptorProto",type:T.$type.toObject(T,BK),fileDescriptorProtos:Y,serialize:o4($),deserialize:a4($,q)}}function QM($,q){let Y=$.toDescriptor("proto3");return{format:"Protocol Buffer 3 EnumDescriptorProto",type:Y.$type.toObject(Y,BK),fileDescriptorProtos:q}}function UM($,q,Y,T){if($ instanceof b1.Service)return JM($,q,Y,T);else if($ instanceof b1.Type)return s4($,Y,T);else if($ instanceof b1.Enum)return QM($,T);else throw Error("Type mismatch in reflection object handling")}function LT($,q){let Y={};$.resolveAll();let X=$.toDescriptor("proto3").file.map((J)=>Buffer.from(t4.FileDescriptorProto.encode(J).finish()));for(let[J,Q]of RK($,""))Y[J]=UM(Q,J,q,X);return Y}function PK($,q){q=q||{};let Y=b1.Root.fromDescriptor($);return Y.resolveAll(),LT(Y,q)}function ZM($,q){return(0,e4.loadProtosWithOptions)($,q).then((Y)=>{return LT(Y,q)})}OK.load=ZM;function KM($,q){let Y=(0,e4.loadProtosWithOptionsSync)($,q);return LT(Y,q)}OK.loadSync=KM;function AM($,q){q=q||{};let Y=b1.Root.fromJSON($);return Y.resolveAll(),LT(Y,q)}OK.fromJSON=AM;function WM($,q){let Y=t4.FileDescriptorSet.decode($);return PK(Y,q)}OK.loadFileDescriptorSetFromBuffer=WM;function GM($,q){let Y=t4.FileDescriptorSet.fromObject($);return PK(Y,q)}OK.loadFileDescriptorSetFromObject=GM;(0,e4.addCommonProtos)()});var R$=B((bK)=>{var __dirname="/Users/beatrix/dev/cline-packages/node_modules/.bun/@grpc+grpc-js@1.14.3/node_modules/@grpc/grpc-js/build/src";Object.defineProperty(bK,"__esModule",{value:!0});bK.registerChannelzSocket=bK.registerChannelzServer=bK.registerChannelzSubchannel=bK.registerChannelzChannel=bK.ChannelzCallTrackerStub=bK.ChannelzCallTracker=bK.ChannelzChildrenTrackerStub=bK.ChannelzChildrenTracker=bK.ChannelzTrace=bK.ChannelzTraceStub=void 0;bK.unregisterChannelzRef=RM;bK.getChannelzHandlers=mK;bK.getChannelzServiceDefinition=fK;bK.setup=kM;var ST=e("net"),n$=GU(),_Y=l0(),gY=n(),HM=i0(),zM=r6(),MM=o6();function $X($){return{channel_id:$.id,name:$.name}}function qX($){return{subchannel_id:$.id,name:$.name}}function BM($){return{server_id:$.id}}function CT($){return{socket_id:$.id,name:$.name}}var wK=32,YX=100;class jK{constructor(){this.events=[],this.creationTimestamp=new Date,this.eventsLogged=0}addTrace(){}getTraceMessage(){return{creation_timestamp:u1(this.creationTimestamp),num_events_logged:this.eventsLogged,events:[]}}}bK.ChannelzTraceStub=jK;class vK{constructor(){this.events=[],this.eventsLogged=0,this.creationTimestamp=new Date}addTrace($,q,Y){let T=new Date;if(this.events.push({description:q,severity:$,timestamp:T,childChannel:(Y===null||Y===void 0?void 0:Y.kind)==="channel"?Y:void 0,childSubchannel:(Y===null||Y===void 0?void 0:Y.kind)==="subchannel"?Y:void 0}),this.events.length>=wK*2)this.events=this.events.slice(wK);this.eventsLogged+=1}getTraceMessage(){return{creation_timestamp:u1(this.creationTimestamp),num_events_logged:this.eventsLogged,events:this.events.map(($)=>{return{description:$.description,severity:$.severity,timestamp:u1($.timestamp),channel_ref:$.childChannel?$X($.childChannel):null,subchannel_ref:$.childSubchannel?qX($.childSubchannel):null}})}}}bK.ChannelzTrace=vK;class TX{constructor(){this.channelChildren=new n$.OrderedMap,this.subchannelChildren=new n$.OrderedMap,this.socketChildren=new n$.OrderedMap,this.trackerMap={["channel"]:this.channelChildren,["subchannel"]:this.subchannelChildren,["socket"]:this.socketChildren}}refChild($){let q=this.trackerMap[$.kind],Y=q.find($.id);if(Y.equals(q.end()))q.setElement($.id,{ref:$,count:1},Y);else Y.pointer[1].count+=1}unrefChild($){let q=this.trackerMap[$.kind],Y=q.getElementByKey($.id);if(Y!==void 0){if(Y.count-=1,Y.count===0)q.eraseElementByKey($.id)}}getChildLists(){return{channels:this.channelChildren,subchannels:this.subchannelChildren,sockets:this.socketChildren}}}bK.ChannelzChildrenTracker=TX;class xK extends TX{refChild(){}unrefChild(){}}bK.ChannelzChildrenTrackerStub=xK;class XX{constructor(){this.callsStarted=0,this.callsSucceeded=0,this.callsFailed=0,this.lastCallStartedTimestamp=null}addCallStarted(){this.callsStarted+=1,this.lastCallStartedTimestamp=new Date}addCallSucceeded(){this.callsSucceeded+=1}addCallFailed(){this.callsFailed+=1}}bK.ChannelzCallTracker=XX;class kK extends XX{addCallStarted(){}addCallSucceeded(){}addCallFailed(){}}bK.ChannelzCallTrackerStub=kK;var X$={["channel"]:new n$.OrderedMap,["subchannel"]:new n$.OrderedMap,["server"]:new n$.OrderedMap,["socket"]:new n$.OrderedMap},yT=($)=>{let q=1;function Y(){return q++}let T=X$[$];return(X,J,Q)=>{let U=Y(),Z={id:U,name:X,kind:$};if(Q)T.setElement(U,{ref:Z,getInfo:J});return Z}};bK.registerChannelzChannel=yT("channel");bK.registerChannelzSubchannel=yT("subchannel");bK.registerChannelzServer=yT("server");bK.registerChannelzSocket=yT("socket");function RM($){X$[$.kind].eraseElementByKey($.id)}function PM($){let q=Number.parseInt($,16);return[q/256|0,q%256]}function SK($){if($==="")return[];let q=$.split(":").map((T)=>PM(T));return[].concat(...q)}function OM($){return(0,ST.isIPv6)($)&&$.toLowerCase().startsWith("::ffff:")&&(0,ST.isIPv4)($.substring(7))}function CK($){return Buffer.from(Uint8Array.from($.split(".").map((q)=>Number.parseInt(q))))}function LM($){if((0,ST.isIPv4)($))return CK($);else if(OM($))return CK($.substring(7));else if((0,ST.isIPv6)($)){let q,Y,T=$.indexOf("::");if(T===-1)q=$,Y="";else q=$.substring(0,T),Y=$.substring(T+2);let X=Buffer.from(SK(q)),J=Buffer.from(SK(Y)),Q=Buffer.alloc(16-X.length-J.length,0);return Buffer.concat([X,Q,J])}else return null}function hK($){switch($){case _Y.ConnectivityState.CONNECTING:return{state:"CONNECTING"};case _Y.ConnectivityState.IDLE:return{state:"IDLE"};case _Y.ConnectivityState.READY:return{state:"READY"};case _Y.ConnectivityState.SHUTDOWN:return{state:"SHUTDOWN"};case _Y.ConnectivityState.TRANSIENT_FAILURE:return{state:"TRANSIENT_FAILURE"};default:return{state:"UNKNOWN"}}}function u1($){if(!$)return null;let q=$.getTime();return{seconds:q/1000|0,nanos:q%1000*1e6}}function _K($){let q=$.getInfo(),Y=[],T=[];return q.children.channels.forEach((X)=>{Y.push($X(X[1].ref))}),q.children.subchannels.forEach((X)=>{T.push(qX(X[1].ref))}),{ref:$X($.ref),data:{target:q.target,state:hK(q.state),calls_started:q.callTracker.callsStarted,calls_succeeded:q.callTracker.callsSucceeded,calls_failed:q.callTracker.callsFailed,last_call_started_timestamp:u1(q.callTracker.lastCallStartedTimestamp),trace:q.trace.getTraceMessage()},channel_ref:Y,subchannel_ref:T}}function wM($,q){let Y=parseInt($.request.channel_id,10),T=X$.channel.getElementByKey(Y);if(T===void 0){q({code:gY.Status.NOT_FOUND,details:"No channel data found for id "+Y});return}q(null,{channel:_K(T)})}function SM($,q){let Y=parseInt($.request.max_results,10)||YX,T=[],X=parseInt($.request.start_channel_id,10),J=X$.channel,Q;for(Q=J.lowerBound(X);!Q.equals(J.end())&&T.length<Y;Q=Q.next())T.push(_K(Q.pointer[1]));q(null,{channel:T,end:Q.equals(J.end())})}function gK($){let q=$.getInfo(),Y=[];return q.listenerChildren.sockets.forEach((T)=>{Y.push(CT(T[1].ref))}),{ref:BM($.ref),data:{calls_started:q.callTracker.callsStarted,calls_succeeded:q.callTracker.callsSucceeded,calls_failed:q.callTracker.callsFailed,last_call_started_timestamp:u1(q.callTracker.lastCallStartedTimestamp),trace:q.trace.getTraceMessage()},listen_socket:Y}}function CM($,q){let Y=parseInt($.request.server_id,10),X=X$.server.getElementByKey(Y);if(X===void 0){q({code:gY.Status.NOT_FOUND,details:"No server data found for id "+Y});return}q(null,{server:gK(X)})}function yM($,q){let Y=parseInt($.request.max_results,10)||YX,T=parseInt($.request.start_server_id,10),X=X$.server,J=[],Q;for(Q=X.lowerBound(T);!Q.equals(X.end())&&J.length<Y;Q=Q.next())J.push(gK(Q.pointer[1]));q(null,{server:J,end:Q.equals(X.end())})}function jM($,q){let Y=parseInt($.request.subchannel_id,10),T=X$.subchannel.getElementByKey(Y);if(T===void 0){q({code:gY.Status.NOT_FOUND,details:"No subchannel data found for id "+Y});return}let X=T.getInfo(),J=[];X.children.sockets.forEach((U)=>{J.push(CT(U[1].ref))});let Q={ref:qX(T.ref),data:{target:X.target,state:hK(X.state),calls_started:X.callTracker.callsStarted,calls_succeeded:X.callTracker.callsSucceeded,calls_failed:X.callTracker.callsFailed,last_call_started_timestamp:u1(X.callTracker.lastCallStartedTimestamp),trace:X.trace.getTraceMessage()},socket_ref:J};q(null,{subchannel:Q})}function yK($){var q;if((0,HM.isTcpSubchannelAddress)($))return{address:"tcpip_address",tcpip_address:{ip_address:(q=LM($.host))!==null&&q!==void 0?q:void 0,port:$.port}};else return{address:"uds_address",uds_address:{filename:$.path}}}function vM($,q){var Y,T,X,J,Q;let U=parseInt($.request.socket_id,10),Z=X$.socket.getElementByKey(U);if(Z===void 0){q({code:gY.Status.NOT_FOUND,details:"No socket data found for id "+U});return}let K=Z.getInfo(),A=K.security?{model:"tls",tls:{cipher_suite:K.security.cipherSuiteStandardName?"standard_name":"other_name",standard_name:(Y=K.security.cipherSuiteStandardName)!==null&&Y!==void 0?Y:void 0,other_name:(T=K.security.cipherSuiteOtherName)!==null&&T!==void 0?T:void 0,local_certificate:(X=K.security.localCertificate)!==null&&X!==void 0?X:void 0,remote_certificate:(J=K.security.remoteCertificate)!==null&&J!==void 0?J:void 0}}:null,W={ref:CT(Z.ref),local:K.localAddress?yK(K.localAddress):null,remote:K.remoteAddress?yK(K.remoteAddress):null,remote_name:(Q=K.remoteName)!==null&&Q!==void 0?Q:void 0,security:A,data:{keep_alives_sent:K.keepAlivesSent,streams_started:K.streamsStarted,streams_succeeded:K.streamsSucceeded,streams_failed:K.streamsFailed,last_local_stream_created_timestamp:u1(K.lastLocalStreamCreatedTimestamp),last_remote_stream_created_timestamp:u1(K.lastRemoteStreamCreatedTimestamp),messages_received:K.messagesReceived,messages_sent:K.messagesSent,last_message_received_timestamp:u1(K.lastMessageReceivedTimestamp),last_message_sent_timestamp:u1(K.lastMessageSentTimestamp),local_flow_control_window:K.localFlowControlWindow?{value:K.localFlowControlWindow}:null,remote_flow_control_window:K.remoteFlowControlWindow?{value:K.remoteFlowControlWindow}:null}};q(null,{socket:W})}function xM($,q){let Y=parseInt($.request.server_id,10),T=X$.server.getElementByKey(Y);if(T===void 0){q({code:gY.Status.NOT_FOUND,details:"No server data found for id "+Y});return}let X=parseInt($.request.start_socket_id,10),J=parseInt($.request.max_results,10)||YX,U=T.getInfo().sessionChildren.sockets,Z=[],K;for(K=U.lowerBound(X);!K.equals(U.end())&&Z.length<J;K=K.next())Z.push(CT(K.pointer[1].ref));q(null,{socket_ref:Z,end:K.equals(U.end())})}function mK(){return{GetChannel:wM,GetTopChannels:SM,GetServer:CM,GetServers:yM,GetSubchannel:jM,GetSocket:vM,GetServerSockets:xM}}var wT=null;function fK(){if(wT)return wT;let $=hY().loadSync,q=$("channelz.proto",{keepCase:!0,longs:String,enums:String,defaults:!0,oneofs:!0,includeDirs:[`${__dirname}/../../proto`]});return wT=(0,MM.loadPackageDefinition)(q).grpc.channelz.v1.Channelz.service,wT}function kM(){(0,zM.registerAdminService)(fK,mK)}});var jT=B((dK)=>{Object.defineProperty(dK,"__esModule",{value:!0});dK.getNextCallNumber=aM;var rM=0;function aM(){return rM++}});var JX=B((pK)=>{Object.defineProperty(pK,"__esModule",{value:!0});pK.CompressionAlgorithms=void 0;var cK;(function($){$[$.identity=0]="identity",$[$.deflate=1]="deflate",$[$.gzip=2]="gzip"})(cK||(pK.CompressionAlgorithms=cK={}))});var QX=B((iK)=>{Object.defineProperty(iK,"__esModule",{value:!0});iK.BaseFilter=void 0;class nK{async sendMetadata($){return $}receiveMetadata($){return $}async sendMessage($){return $}async receiveMessage($){return $}receiveTrailers($){return $}}iK.BaseFilter=nK});var ZX=B((qA)=>{Object.defineProperty(qA,"__esModule",{value:!0});qA.CompressionFilterFactory=qA.CompressionFilter=void 0;var vT=e("zlib"),oK=JX(),Cq=n(),sM=QX(),tM=Z0(),eM=($)=>{return typeof $==="number"&&typeof oK.CompressionAlgorithms[$]==="string"};class mY{async writeMessage($,q){let Y=$;if(q)Y=await this.compressMessage(Y);let T=Buffer.allocUnsafe(Y.length+5);return T.writeUInt8(q?1:0,0),T.writeUInt32BE(Y.length,1),Y.copy(T,5),T}async readMessage($){let q=$.readUInt8(0)===1,Y=$.slice(5);if(q)Y=await this.decompressMessage(Y);return Y}}class yq extends mY{async compressMessage($){return $}async writeMessage($,q){let Y=Buffer.allocUnsafe($.length+5);return Y.writeUInt8(0,0),Y.writeUInt32BE($.length,1),$.copy(Y,5),Y}decompressMessage($){return Promise.reject(Error('Received compressed message but "grpc-encoding" header was identity'))}}class sK extends mY{constructor($){super();this.maxRecvMessageLength=$}compressMessage($){return new Promise((q,Y)=>{vT.deflate($,(T,X)=>{if(T)Y(T);else q(X)})})}decompressMessage($){return new Promise((q,Y)=>{let T=0,X=[],J=vT.createInflate();J.on("data",(Q)=>{if(X.push(Q),T+=Q.byteLength,this.maxRecvMessageLength!==-1&&T>this.maxRecvMessageLength)J.destroy(),Y({code:Cq.Status.RESOURCE_EXHAUSTED,details:`Received message that decompresses to a size larger than ${this.maxRecvMessageLength}`})}),J.on("end",()=>{q(Buffer.concat(X))}),J.write($),J.end()})}}class tK extends mY{constructor($){super();this.maxRecvMessageLength=$}compressMessage($){return new Promise((q,Y)=>{vT.gzip($,(T,X)=>{if(T)Y(T);else q(X)})})}decompressMessage($){return new Promise((q,Y)=>{let T=0,X=[],J=vT.createGunzip();J.on("data",(Q)=>{if(X.push(Q),T+=Q.byteLength,this.maxRecvMessageLength!==-1&&T>this.maxRecvMessageLength)J.destroy(),Y({code:Cq.Status.RESOURCE_EXHAUSTED,details:`Received message that decompresses to a size larger than ${this.maxRecvMessageLength}`})}),J.on("end",()=>{q(Buffer.concat(X))}),J.write($),J.end()})}}class eK extends mY{constructor($){super();this.compressionName=$}compressMessage($){return Promise.reject(Error(`Received message compressed with unsupported compression method ${this.compressionName}`))}decompressMessage($){return Promise.reject(Error(`Compression method not supported: ${this.compressionName}`))}}function aK($,q){switch($){case"identity":return new yq;case"deflate":return new sK(q);case"gzip":return new tK(q);default:return new eK($)}}class UX extends sM.BaseFilter{constructor($,q){var Y,T,X;super();this.sharedFilterConfig=q,this.sendCompression=new yq,this.receiveCompression=new yq,this.currentCompressionAlgorithm="identity";let J=$["grpc.default_compression_algorithm"];if(this.maxReceiveMessageLength=(Y=$["grpc.max_receive_message_length"])!==null&&Y!==void 0?Y:Cq.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH,this.maxSendMessageLength=(T=$["grpc.max_send_message_length"])!==null&&T!==void 0?T:Cq.DEFAULT_MAX_SEND_MESSAGE_LENGTH,J!==void 0)if(eM(J)){let Q=oK.CompressionAlgorithms[J],U=(X=q.serverSupportedEncodingHeader)===null||X===void 0?void 0:X.split(",");if(!U||U.includes(Q))this.currentCompressionAlgorithm=Q,this.sendCompression=aK(this.currentCompressionAlgorithm,-1)}else tM.log(Cq.LogVerbosity.ERROR,`Invalid value provided for grpc.default_compression_algorithm option: ${J}`)}async sendMetadata($){let q=await $;if(q.set("grpc-accept-encoding","identity,deflate,gzip"),q.set("accept-encoding","identity"),this.currentCompressionAlgorithm==="identity")q.remove("grpc-encoding");else q.set("grpc-encoding",this.currentCompressionAlgorithm);return q}receiveMetadata($){let q=$.get("grpc-encoding");if(q.length>0){let T=q[0];if(typeof T==="string")this.receiveCompression=aK(T,this.maxReceiveMessageLength)}$.remove("grpc-encoding");let Y=$.get("grpc-accept-encoding")[0];if(Y){if(this.sharedFilterConfig.serverSupportedEncodingHeader=Y,!Y.split(",").includes(this.currentCompressionAlgorithm))this.sendCompression=new yq,this.currentCompressionAlgorithm="identity"}return $.remove("grpc-accept-encoding"),$}async sendMessage($){var q;let Y=await $;if(this.maxSendMessageLength!==-1&&Y.message.length>this.maxSendMessageLength)throw{code:Cq.Status.RESOURCE_EXHAUSTED,details:`Attempted to send message with a size larger than ${this.maxSendMessageLength}`};let T;if(this.sendCompression instanceof yq)T=!1;else T=(((q=Y.flags)!==null&&q!==void 0?q:0)&2)===0;return{message:await this.sendCompression.writeMessage(Y.message,T),flags:Y.flags}}async receiveMessage($){return this.receiveCompression.readMessage(await $)}}qA.CompressionFilter=UX;class $A{constructor($,q){this.options=q,this.sharedFilterConfig={}}createFilter(){return new UX(this.options,this.sharedFilterConfig)}}qA.CompressionFilterFactory=$A});var fY=B((TA)=>{Object.defineProperty(TA,"__esModule",{value:!0});TA.restrictControlPlaneStatusCode=YB;var d1=n(),qB=[d1.Status.OK,d1.Status.INVALID_ARGUMENT,d1.Status.NOT_FOUND,d1.Status.ALREADY_EXISTS,d1.Status.FAILED_PRECONDITION,d1.Status.ABORTED,d1.Status.OUT_OF_RANGE,d1.Status.DATA_LOSS];function YB($,q){if(qB.includes($))return{code:d1.Status.INTERNAL,details:`Invalid status from control plane: ${$} ${d1.Status[$]} ${q}`};else return{code:$,details:q}}});var jq=B((XA)=>{Object.defineProperty(XA,"__esModule",{value:!0});XA.minDeadline=XB;XA.getDeadlineTimeoutString=QB;XA.getRelativeTimeout=ZB;XA.deadlineToString=KB;XA.formatDateDifference=AB;function XB(...$){let q=1/0;for(let Y of $){let T=Y instanceof Date?Y.getTime():Y;if(T<q)q=T}return q}var JB=[["m",1],["S",1000],["M",60000],["H",3600000]];function QB($){let q=new Date().getTime();if($ instanceof Date)$=$.getTime();let Y=Math.max($-q,0);for(let[T,X]of JB){let J=Y/X;if(J<1e8)return String(Math.ceil(J))+T}throw Error("Deadline is too far in the future")}var UB=2147483647;function ZB($){let q=$ instanceof Date?$.getTime():$,Y=new Date().getTime(),T=q-Y;if(T<0)return 0;else if(T>UB)return 1/0;else return T}function KB($){if($ instanceof Date)return $.toISOString();else{let q=new Date($);if(Number.isNaN(q.getTime()))return""+$;else return q.toISOString()}}function AB($,q){return((q.getTime()-$.getTime())/1000).toFixed(3)+"s"}});var xT=B((JA)=>{Object.defineProperty(JA,"__esModule",{value:!0});JA.FilterStackFactory=JA.FilterStack=void 0;class KX{constructor($){this.filters=$}sendMetadata($){let q=$;for(let Y=0;Y<this.filters.length;Y++)q=this.filters[Y].sendMetadata(q);return q}receiveMetadata($){let q=$;for(let Y=this.filters.length-1;Y>=0;Y--)q=this.filters[Y].receiveMetadata(q);return q}sendMessage($){let q=$;for(let Y=0;Y<this.filters.length;Y++)q=this.filters[Y].sendMessage(q);return q}receiveMessage($){let q=$;for(let Y=this.filters.length-1;Y>=0;Y--)q=this.filters[Y].receiveMessage(q);return q}receiveTrailers($){let q=$;for(let Y=this.filters.length-1;Y>=0;Y--)q=this.filters[Y].receiveTrailers(q);return q}push($){this.filters.unshift(...$)}getFilters(){return this.filters}}JA.FilterStack=KX;class AX{constructor($){this.factories=$}push($){this.factories.unshift(...$)}clone(){return new AX([...this.factories])}createFilter(){return new KX(this.factories.map(($)=>$.createFilter()))}}JA.FilterStackFactory=AX});var WA=B((KA)=>{Object.defineProperty(KA,"__esModule",{value:!0});KA.SingleSubchannelChannel=void 0;var IB=jT(),bY=R$(),NB=ZX(),HB=l0(),uY=n(),zB=fY(),MB=jq(),BB=xT(),WX=P0(),RB=H1(),kT=p0();class UA{constructor($,q,Y,T,X){var J,Q;this.subchannel=$,this.method=q,this.options=T,this.callNumber=X,this.childCall=null,this.pendingMessage=null,this.readPending=!1,this.halfClosePending=!1,this.pendingStatus=null,this.readFilterPending=!1,this.writeFilterPending=!1;let U=this.method.split("/"),Z="";if(U.length>=2)Z=U[1];let K=(Q=(J=(0,kT.splitHostPort)(this.options.host))===null||J===void 0?void 0:J.host)!==null&&Q!==void 0?Q:"localhost";this.serviceUrl=`https://${K}/${Z}`;let A=(0,MB.getRelativeTimeout)(T.deadline);if(A!==1/0)if(A<=0)this.cancelWithStatus(uY.Status.DEADLINE_EXCEEDED,"Deadline exceeded");else setTimeout(()=>{this.cancelWithStatus(uY.Status.DEADLINE_EXCEEDED,"Deadline exceeded")},A);this.filterStack=Y.createFilter()}cancelWithStatus($,q){if(this.childCall)this.childCall.cancelWithStatus($,q);else this.pendingStatus={code:$,details:q,metadata:new WX.Metadata}}getPeer(){var $,q;return(q=($=this.childCall)===null||$===void 0?void 0:$.getPeer())!==null&&q!==void 0?q:this.subchannel.getAddress()}async start($,q){if(this.pendingStatus){q.onReceiveStatus(this.pendingStatus);return}if(this.subchannel.getConnectivityState()!==HB.ConnectivityState.READY){q.onReceiveStatus({code:uY.Status.UNAVAILABLE,details:"Subchannel not ready",metadata:new WX.Metadata});return}let Y=await this.filterStack.sendMetadata(Promise.resolve($)),T;try{T=await this.subchannel.getCallCredentials().generateMetadata({method_name:this.method,service_url:this.serviceUrl})}catch(J){let Q=J,{code:U,details:Z}=(0,zB.restrictControlPlaneStatusCode)(typeof Q.code==="number"?Q.code:uY.Status.UNKNOWN,`Getting metadata from plugin failed with error: ${Q.message}`);q.onReceiveStatus({code:U,details:Z,metadata:new WX.Metadata});return}T.merge(Y);let X={onReceiveMetadata:async(J)=>{q.onReceiveMetadata(await this.filterStack.receiveMetadata(J))},onReceiveMessage:async(J)=>{this.readFilterPending=!0;let Q=await this.filterStack.receiveMessage(J);if(this.readFilterPending=!1,q.onReceiveMessage(Q),this.pendingStatus)q.onReceiveStatus(this.pendingStatus)},onReceiveStatus:async(J)=>{let Q=await this.filterStack.receiveTrailers(J);if(this.readFilterPending)this.pendingStatus=Q;else q.onReceiveStatus(Q)}};if(this.childCall=this.subchannel.createCall(T,this.options.host,this.method,X),this.readPending)this.childCall.startRead();if(this.pendingMessage)this.childCall.sendMessageWithContext(this.pendingMessage.context,this.pendingMessage.message);if(this.halfClosePending&&!this.writeFilterPending)this.childCall.halfClose()}async sendMessageWithContext($,q){this.writeFilterPending=!0;let Y=await this.filterStack.sendMessage(Promise.resolve({message:q,flags:$.flags}));if(this.writeFilterPending=!1,this.childCall){if(this.childCall.sendMessageWithContext($,Y.message),this.halfClosePending)this.childCall.halfClose()}else this.pendingMessage={context:$,message:Y.message}}startRead(){if(this.childCall)this.childCall.startRead();else this.readPending=!0}halfClose(){if(this.childCall&&!this.writeFilterPending)this.childCall.halfClose();else this.halfClosePending=!0}getCallNumber(){return this.callNumber}setCredentials($){throw Error("Method not implemented.")}getAuthContext(){if(this.childCall)return this.childCall.getAuthContext();else return null}}class ZA{constructor($,q,Y){if(this.subchannel=$,this.target=q,this.channelzEnabled=!1,this.channelzTrace=new bY.ChannelzTrace,this.callTracker=new bY.ChannelzCallTracker,this.childrenTracker=new bY.ChannelzChildrenTracker,this.channelzEnabled=Y["grpc.enable_channelz"]!==0,this.channelzRef=(0,bY.registerChannelzChannel)((0,kT.uriToString)(q),()=>({target:`${(0,kT.uriToString)(q)} (${$.getAddress()})`,state:this.subchannel.getConnectivityState(),trace:this.channelzTrace,callTracker:this.callTracker,children:this.childrenTracker.getChildLists()}),this.channelzEnabled),this.channelzEnabled)this.childrenTracker.refChild($.getChannelzRef());this.filterStackFactory=new BB.FilterStackFactory([new NB.CompressionFilterFactory(this,Y)])}close(){if(this.channelzEnabled)this.childrenTracker.unrefChild(this.subchannel.getChannelzRef());(0,bY.unregisterChannelzRef)(this.channelzRef)}getTarget(){return(0,kT.uriToString)(this.target)}getConnectivityState($){throw Error("Method not implemented.")}watchConnectivityState($,q,Y){throw Error("Method not implemented.")}getChannelzRef(){return this.channelzRef}createCall($,q){let Y={deadline:q,host:(0,RB.getDefaultAuthority)(this.target),flags:uY.Propagate.DEFAULTS,parentCall:null};return new UA(this.subchannel,$,this.filterStackFactory,Y,(0,IB.getNextCallNumber)())}}KA.SingleSubchannelChannel=ZA});var DA=B((EA)=>{Object.defineProperty(EA,"__esModule",{value:!0});EA.Subchannel=void 0;var Q0=l0(),PB=Fq(),GX=Z0(),hT=n(),OB=p0(),LB=i0(),c1=R$(),wB=WA(),SB="subchannel",CB=2147483647;class GA{constructor($,q,Y,T,X){var J;this.channelTarget=$,this.subchannelAddress=q,this.options=Y,this.connector=X,this.connectivityState=Q0.ConnectivityState.IDLE,this.transport=null,this.continueConnecting=!1,this.stateListeners=new Set,this.refcount=0,this.channelzEnabled=!0,this.dataProducers=new Map,this.subchannelChannel=null;let Q={initialDelay:Y["grpc.initial_reconnect_backoff_ms"],maxDelay:Y["grpc.max_reconnect_backoff_ms"]};if(this.backoffTimeout=new PB.BackoffTimeout(()=>{this.handleBackoffTimer()},Q),this.backoffTimeout.unref(),this.subchannelAddressString=(0,LB.subchannelAddressToString)(q),this.keepaliveTime=(J=Y["grpc.keepalive_time_ms"])!==null&&J!==void 0?J:-1,Y["grpc.enable_channelz"]===0)this.channelzEnabled=!1,this.channelzTrace=new c1.ChannelzTraceStub,this.callTracker=new c1.ChannelzCallTrackerStub,this.childrenTracker=new c1.ChannelzChildrenTrackerStub,this.streamTracker=new c1.ChannelzCallTrackerStub;else this.channelzTrace=new c1.ChannelzTrace,this.callTracker=new c1.ChannelzCallTracker,this.childrenTracker=new c1.ChannelzChildrenTracker,this.streamTracker=new c1.ChannelzCallTracker;this.channelzRef=(0,c1.registerChannelzSubchannel)(this.subchannelAddressString,()=>this.getChannelzInfo(),this.channelzEnabled),this.channelzTrace.addTrace("CT_INFO","Subchannel created"),this.trace("Subchannel constructed with options "+JSON.stringify(Y,void 0,2)),this.secureConnector=T._createSecureConnector($,Y)}getChannelzInfo(){return{state:this.connectivityState,trace:this.channelzTrace,callTracker:this.callTracker,children:this.childrenTracker.getChildLists(),target:this.subchannelAddressString}}trace($){GX.trace(hT.LogVerbosity.DEBUG,SB,"("+this.channelzRef.id+") "+this.subchannelAddressString+" "+$)}refTrace($){GX.trace(hT.LogVerbosity.DEBUG,"subchannel_refcount","("+this.channelzRef.id+") "+this.subchannelAddressString+" "+$)}handleBackoffTimer(){if(this.continueConnecting)this.transitionToState([Q0.ConnectivityState.TRANSIENT_FAILURE],Q0.ConnectivityState.CONNECTING);else this.transitionToState([Q0.ConnectivityState.TRANSIENT_FAILURE],Q0.ConnectivityState.IDLE)}startBackoff(){this.backoffTimeout.runOnce()}stopBackoff(){this.backoffTimeout.stop(),this.backoffTimeout.reset()}startConnectingInternal(){let $=this.options;if($["grpc.keepalive_time_ms"]){let q=Math.min(this.keepaliveTime,CB);$=Object.assign(Object.assign({},$),{"grpc.keepalive_time_ms":q})}this.connector.connect(this.subchannelAddress,this.secureConnector,$).then((q)=>{if(this.transitionToState([Q0.ConnectivityState.CONNECTING],Q0.ConnectivityState.READY)){if(this.transport=q,this.channelzEnabled)this.childrenTracker.refChild(q.getChannelzRef());q.addDisconnectListener((Y)=>{if(this.transitionToState([Q0.ConnectivityState.READY],Q0.ConnectivityState.IDLE),Y&&this.keepaliveTime>0)this.keepaliveTime*=2,GX.log(hT.LogVerbosity.ERROR,`Connection to ${(0,OB.uriToString)(this.channelTarget)} at ${this.subchannelAddressString} rejected by server because of excess pings. Increasing ping interval to ${this.keepaliveTime} ms`)})}else q.shutdown()},(q)=>{this.transitionToState([Q0.ConnectivityState.CONNECTING],Q0.ConnectivityState.TRANSIENT_FAILURE,`${q}`)})}transitionToState($,q,Y){var T,X;if($.indexOf(this.connectivityState)===-1)return!1;if(Y)this.trace(Q0.ConnectivityState[this.connectivityState]+" -> "+Q0.ConnectivityState[q]+' with error "'+Y+'"');else this.trace(Q0.ConnectivityState[this.connectivityState]+" -> "+Q0.ConnectivityState[q]);if(this.channelzEnabled)this.channelzTrace.addTrace("CT_INFO","Connectivity state change to "+Q0.ConnectivityState[q]);let J=this.connectivityState;switch(this.connectivityState=q,q){case Q0.ConnectivityState.READY:this.stopBackoff();break;case Q0.ConnectivityState.CONNECTING:this.startBackoff(),this.startConnectingInternal(),this.continueConnecting=!1;break;case Q0.ConnectivityState.TRANSIENT_FAILURE:if(this.channelzEnabled&&this.transport)this.childrenTracker.unrefChild(this.transport.getChannelzRef());if((T=this.transport)===null||T===void 0||T.shutdown(),this.transport=null,!this.backoffTimeout.isRunning())process.nextTick(()=>{this.handleBackoffTimer()});break;case Q0.ConnectivityState.IDLE:if(this.channelzEnabled&&this.transport)this.childrenTracker.unrefChild(this.transport.getChannelzRef());(X=this.transport)===null||X===void 0||X.shutdown(),this.transport=null;break;default:throw Error(`Invalid state: unknown ConnectivityState ${q}`)}for(let Q of this.stateListeners)Q(this,J,q,this.keepaliveTime,Y);return!0}ref(){this.refTrace("refcount "+this.refcount+" -> "+(this.refcount+1)),this.refcount+=1}unref(){if(this.refTrace("refcount "+this.refcount+" -> "+(this.refcount-1)),this.refcount-=1,this.refcount===0)this.channelzTrace.addTrace("CT_INFO","Shutting down"),(0,c1.unregisterChannelzRef)(this.channelzRef),this.secureConnector.destroy(),process.nextTick(()=>{this.transitionToState([Q0.ConnectivityState.CONNECTING,Q0.ConnectivityState.READY],Q0.ConnectivityState.IDLE)})}unrefIfOneRef(){if(this.refcount===1)return this.unref(),!0;return!1}createCall($,q,Y,T){if(!this.transport)throw Error("Cannot create call, subchannel not READY");let X;if(this.channelzEnabled)this.callTracker.addCallStarted(),this.streamTracker.addCallStarted(),X={onCallEnd:(J)=>{if(J.code===hT.Status.OK)this.callTracker.addCallSucceeded();else this.callTracker.addCallFailed()}};else X={};return this.transport.createCall($,q,Y,T,X)}startConnecting(){process.nextTick(()=>{if(!this.transitionToState([Q0.ConnectivityState.IDLE],Q0.ConnectivityState.CONNECTING)){if(this.connectivityState===Q0.ConnectivityState.TRANSIENT_FAILURE)this.continueConnecting=!0}})}getConnectivityState(){return this.connectivityState}addConnectivityStateListener($){this.stateListeners.add($)}removeConnectivityStateListener($){this.stateListeners.delete($)}resetBackoff(){process.nextTick(()=>{this.backoffTimeout.reset(),this.transitionToState([Q0.ConnectivityState.TRANSIENT_FAILURE],Q0.ConnectivityState.CONNECTING)})}getAddress(){return this.subchannelAddressString}getChannelzRef(){return this.channelzRef}isHealthy(){return!0}addHealthStateWatcher($){}removeHealthStateWatcher($){}getRealSubchannel(){return this}realSubchannelEquals($){return $.getRealSubchannel()===this}throttleKeepalive($){if($>this.keepaliveTime)this.keepaliveTime=$}getCallCredentials(){return this.secureConnector.getCallCredentials()}getChannel(){if(!this.subchannelChannel)this.subchannelChannel=new wB.SingleSubchannelChannel(this,this.channelTarget,this.options);return this.subchannelChannel}addDataWatcher($){throw Error("Not implemented")}getOrCreateDataProducer($,q){let Y=this.dataProducers.get($);if(Y)return Y;let T=q(this);return this.dataProducers.set($,T),T}removeDataProducer($){this.dataProducers.delete($)}}EA.Subchannel=GA});var NA=B((FA)=>{var EX;Object.defineProperty(FA,"__esModule",{value:!0});FA.GRPC_NODE_USE_ALTERNATIVE_RESOLVER=void 0;FA.GRPC_NODE_USE_ALTERNATIVE_RESOLVER=((EX=process.env.GRPC_NODE_USE_ALTERNATIVE_RESOLVER)!==null&&EX!==void 0?EX:"false")==="true"});var FX=B((RA)=>{Object.defineProperty(RA,"__esModule",{value:!0});RA.DEFAULT_PORT=void 0;RA.setup=gB;var HA=H1(),VX=e("dns"),yB=g9(),DX=n(),vq=m$(),jB=P0(),vB=Z0(),xB=n(),P$=p0(),zA=e("net"),kB=Fq(),MA=NA(),hB="dns_resolver";function p1($){vB.trace(xB.LogVerbosity.DEBUG,hB,$)}RA.DEFAULT_PORT=443;var _B=30000;class BA{constructor($,q,Y){var T,X,J;if(this.target=$,this.listener=q,this.pendingLookupPromise=null,this.pendingTxtPromise=null,this.latestLookupResult=null,this.latestServiceConfigResult=null,this.continueResolving=!1,this.isNextResolutionTimerRunning=!1,this.isServiceConfigEnabled=!0,this.returnedIpResult=!1,this.alternativeResolver=new VX.promises.Resolver,p1("Resolver constructed for target "+(0,P$.uriToString)($)),$.authority)this.alternativeResolver.setServers([$.authority]);let Q=(0,P$.splitHostPort)($.path);if(Q===null)this.ipResult=null,this.dnsHostname=null,this.port=null;else if((0,zA.isIPv4)(Q.host)||(0,zA.isIPv6)(Q.host))this.ipResult=[{addresses:[{host:Q.host,port:(T=Q.port)!==null&&T!==void 0?T:RA.DEFAULT_PORT}]}],this.dnsHostname=null,this.port=null;else this.ipResult=null,this.dnsHostname=Q.host,this.port=(X=Q.port)!==null&&X!==void 0?X:RA.DEFAULT_PORT;if(this.percentage=Math.random()*100,Y["grpc.service_config_disable_resolution"]===1)this.isServiceConfigEnabled=!1;this.defaultResolutionError={code:DX.Status.UNAVAILABLE,details:`Name resolution failed for target ${(0,P$.uriToString)(this.target)}`,metadata:new jB.Metadata};let U={initialDelay:Y["grpc.initial_reconnect_backoff_ms"],maxDelay:Y["grpc.max_reconnect_backoff_ms"]};this.backoff=new kB.BackoffTimeout(()=>{if(this.continueResolving)this.startResolutionWithBackoff()},U),this.backoff.unref(),this.minTimeBetweenResolutionsMs=(J=Y["grpc.dns_min_time_between_resolutions_ms"])!==null&&J!==void 0?J:_B,this.nextResolutionTimer=setTimeout(()=>{},0),clearTimeout(this.nextResolutionTimer)}startResolution(){if(this.ipResult!==null){if(!this.returnedIpResult)p1("Returning IP address for target "+(0,P$.uriToString)(this.target)),setImmediate(()=>{this.listener((0,vq.statusOrFromValue)(this.ipResult),{},null,"")}),this.returnedIpResult=!0;this.backoff.stop(),this.backoff.reset(),this.stopNextResolutionTimer();return}if(this.dnsHostname===null)p1("Failed to parse DNS address "+(0,P$.uriToString)(this.target)),setImmediate(()=>{this.listener((0,vq.statusOrFromError)({code:DX.Status.UNAVAILABLE,details:`Failed to parse DNS address ${(0,P$.uriToString)(this.target)}`}),{},null,"")}),this.stopNextResolutionTimer();else{if(this.pendingLookupPromise!==null)return;p1("Looking up DNS hostname "+this.dnsHostname),this.latestLookupResult=null;let $=this.dnsHostname;if(this.pendingLookupPromise=this.lookup($),this.pendingLookupPromise.then((q)=>{if(this.pendingLookupPromise===null)return;this.pendingLookupPromise=null,this.latestLookupResult=(0,vq.statusOrFromValue)(q.map((X)=>({addresses:[X]})));let Y="["+q.map((X)=>X.host+":"+X.port).join(",")+"]";p1("Resolved addresses for target "+(0,P$.uriToString)(this.target)+": "+Y);let T=this.listener(this.latestLookupResult,{},this.latestServiceConfigResult,"");this.handleHealthStatus(T)},(q)=>{if(this.pendingLookupPromise===null)return;p1("Resolution error for target "+(0,P$.uriToString)(this.target)+": "+q.message),this.pendingLookupPromise=null,this.stopNextResolutionTimer(),this.listener((0,vq.statusOrFromError)(this.defaultResolutionError),{},this.latestServiceConfigResult,"")}),this.isServiceConfigEnabled&&this.pendingTxtPromise===null)this.pendingTxtPromise=this.resolveTxt($),this.pendingTxtPromise.then((q)=>{if(this.pendingTxtPromise===null)return;this.pendingTxtPromise=null;let Y;try{if(Y=(0,yB.extractAndSelectServiceConfig)(q,this.percentage),Y)this.latestServiceConfigResult=(0,vq.statusOrFromValue)(Y);else this.latestServiceConfigResult=null}catch(T){this.latestServiceConfigResult=(0,vq.statusOrFromError)({code:DX.Status.UNAVAILABLE,details:`Parsing service config failed with error ${T.message}`})}if(this.latestLookupResult!==null)this.listener(this.latestLookupResult,{},this.latestServiceConfigResult,"")},(q)=>{})}}handleHealthStatus($){if($)this.backoff.stop(),this.backoff.reset();else this.continueResolving=!0}async lookup($){if(MA.GRPC_NODE_USE_ALTERNATIVE_RESOLVER){p1("Using alternative DNS resolver.");let Y=await Promise.allSettled([this.alternativeResolver.resolve4($),this.alternativeResolver.resolve6($)]);if(Y.every((T)=>T.status==="rejected"))throw Error(Y[0].reason);return Y.reduce((T,X)=>{return X.status==="fulfilled"?[...T,...X.value]:T},[]).map((T)=>({host:T,port:+this.port}))}return(await VX.promises.lookup($,{all:!0})).map((Y)=>({host:Y.address,port:+this.port}))}async resolveTxt($){if(MA.GRPC_NODE_USE_ALTERNATIVE_RESOLVER)return p1("Using alternative DNS resolver."),this.alternativeResolver.resolveTxt($);return VX.promises.resolveTxt($)}startNextResolutionTimer(){var $,q;clearTimeout(this.nextResolutionTimer),this.nextResolutionTimer=setTimeout(()=>{if(this.stopNextResolutionTimer(),this.continueResolving)this.startResolutionWithBackoff()},this.minTimeBetweenResolutionsMs),(q=($=this.nextResolutionTimer).unref)===null||q===void 0||q.call($),this.isNextResolutionTimerRunning=!0}stopNextResolutionTimer(){clearTimeout(this.nextResolutionTimer),this.isNextResolutionTimerRunning=!1}startResolutionWithBackoff(){if(this.pendingLookupPromise===null)this.continueResolving=!1,this.backoff.runOnce(),this.startNextResolutionTimer(),this.startResolution()}updateResolution(){if(this.pendingLookupPromise===null)if(this.isNextResolutionTimerRunning||this.backoff.isRunning()){if(this.isNextResolutionTimerRunning)p1('resolution update delayed by "min time between resolutions" rate limit');else p1("resolution update delayed by backoff timer until "+this.backoff.getEndTime().toISOString());this.continueResolving=!0}else this.startResolutionWithBackoff()}destroy(){this.continueResolving=!1,this.backoff.reset(),this.backoff.stop(),this.stopNextResolutionTimer(),this.pendingLookupPromise=null,this.pendingTxtPromise=null,this.latestLookupResult=null,this.latestServiceConfigResult=null,this.returnedIpResult=!1}static getDefaultAuthority($){return $.path}}function gB(){(0,HA.registerResolver)("dns",BA),(0,HA.registerDefaultScheme)("dns")}});var IX=B((SA)=>{Object.defineProperty(SA,"__esModule",{value:!0});SA.parseCIDR=LA;SA.mapProxyName=rB;SA.getProxiedConnection=aB;var dY=Z0(),xq=n(),OA=e("net"),fB=e("http"),bB=Z0(),PA=i0(),cY=p0(),uB=e("url"),dB=FX(),cB="proxy";function kq($){bB.trace(xq.LogVerbosity.DEBUG,cB,$)}function pB(){let $="",q="";if(process.env.grpc_proxy)q="grpc_proxy",$=process.env.grpc_proxy;else if(process.env.https_proxy)q="https_proxy",$=process.env.https_proxy;else if(process.env.http_proxy)q="http_proxy",$=process.env.http_proxy;else return{};let Y;try{Y=new uB.URL($)}catch(U){return(0,dY.log)(xq.LogVerbosity.ERROR,`cannot parse value of "${q}" env var`),{}}if(Y.protocol!=="http:")return(0,dY.log)(xq.LogVerbosity.ERROR,`"${Y.protocol}" scheme not supported in proxy URI`),{};let T=null;if(Y.username)if(Y.password)(0,dY.log)(xq.LogVerbosity.INFO,"userinfo found in proxy URI"),T=decodeURIComponent(`${Y.username}:${Y.password}`);else T=Y.username;let{hostname:X,port:J}=Y;if(J==="")J="80";let Q={address:`${X}:${J}`};if(T)Q.creds=T;return kq("Proxy server "+Q.address+" set by environment variable "+q),Q}function lB(){let $=process.env.no_grpc_proxy,q="no_grpc_proxy";if(!$)$=process.env.no_proxy,q="no_proxy";if($)return kq("No proxy server list set by environment variable "+q),$.split(",");else return[]}function LA($){let q=$.split("/");if(q.length!==2)return null;let Y=parseInt(q[1],10);if(!(0,OA.isIPv4)(q[0])||Number.isNaN(Y)||Y<0||Y>32)return null;return{ip:wA(q[0]),prefixLength:Y}}function wA($){return $.split(".").reduce((q,Y)=>(q<<8)+parseInt(Y,10),0)}function nB($,q){let Y=$.ip,T=-1<<32-$.prefixLength;return(wA(q)&T)===(Y&T)}function iB($){for(let q of lB()){let Y=LA(q);if((0,OA.isIPv4)($)&&Y&&nB(Y,$))return!0;else if($.endsWith(q))return!0}return!1}function rB($,q){var Y;let T={target:$,extraOptions:{}};if(((Y=q["grpc.enable_http_proxy"])!==null&&Y!==void 0?Y:1)===0)return T;if($.scheme==="unix")return T;let X=pB();if(!X.address)return T;let J=(0,cY.splitHostPort)($.path);if(!J)return T;let Q=J.host;if(iB(Q))return kq("Not using proxy for target in no_proxy list: "+(0,cY.uriToString)($)),T;let U={"grpc.http_connect_target":(0,cY.uriToString)($)};if(X.creds)U["grpc.http_connect_creds"]=X.creds;return{target:{scheme:"dns",path:X.address},extraOptions:U}}function aB($,q){var Y;if(!("grpc.http_connect_target"in q))return Promise.resolve(null);let T=q["grpc.http_connect_target"],X=(0,cY.parseUri)(T);if(X===null)return Promise.resolve(null);let J=(0,cY.splitHostPort)(X.path);if(J===null)return Promise.resolve(null);let Q=`${J.host}:${(Y=J.port)!==null&&Y!==void 0?Y:dB.DEFAULT_PORT}`,U={method:"CONNECT",path:Q},Z={Host:Q};if((0,PA.isTcpSubchannelAddress)($))U.host=$.host,U.port=$.port;else U.socketPath=$.path;if("grpc.http_connect_creds"in q)Z["Proxy-Authorization"]="Basic "+Buffer.from(q["grpc.http_connect_creds"]).toString("base64");U.headers=Z;let K=(0,PA.subchannelAddressToString)($);return kq("Using proxy "+K+" to connect to "+U.path),new Promise((A,W)=>{let G=fB.request(U);G.once("connect",(V,F,N)=>{if(G.removeAllListeners(),F.removeAllListeners(),V.statusCode===200){if(kq("Successfully connected to "+U.path+" through proxy "+K),N.length>0)F.unshift(N);kq("Successfully established a plaintext connection to "+U.path+" through proxy "+K),A(F)}else(0,dY.log)(xq.LogVerbosity.ERROR,"Failed to connect to "+U.path+" through proxy "+K+" with status "+V.statusCode),W()}),G.once("error",(V)=>{G.removeAllListeners(),(0,dY.log)(xq.LogVerbosity.ERROR,"Failed to connect to proxy "+K+" with error "+V.message),W()}),G.end()})}});var NX=B((yA)=>{Object.defineProperty(yA,"__esModule",{value:!0});yA.StreamDecoder=void 0;var l1;(function($){$[$.NO_DATA=0]="NO_DATA",$[$.READING_SIZE=1]="READING_SIZE",$[$.READING_MESSAGE=2]="READING_MESSAGE"})(l1||(l1={}));class CA{constructor($){this.maxReadMessageLength=$,this.readState=l1.NO_DATA,this.readCompressFlag=Buffer.alloc(1),this.readPartialSize=Buffer.alloc(4),this.readSizeRemaining=4,this.readMessageSize=0,this.readPartialMessage=[],this.readMessageRemaining=0}write($){let q=0,Y,T=[];while(q<$.length)switch(this.readState){case l1.NO_DATA:this.readCompressFlag=$.slice(q,q+1),q+=1,this.readState=l1.READING_SIZE,this.readPartialSize.fill(0),this.readSizeRemaining=4,this.readMessageSize=0,this.readMessageRemaining=0,this.readPartialMessage=[];break;case l1.READING_SIZE:if(Y=Math.min($.length-q,this.readSizeRemaining),$.copy(this.readPartialSize,4-this.readSizeRemaining,q,q+Y),this.readSizeRemaining-=Y,q+=Y,this.readSizeRemaining===0){if(this.readMessageSize=this.readPartialSize.readUInt32BE(0),this.maxReadMessageLength!==-1&&this.readMessageSize>this.maxReadMessageLength)throw Error(`Received message larger than max (${this.readMessageSize} vs ${this.maxReadMessageLength})`);if(this.readMessageRemaining=this.readMessageSize,this.readMessageRemaining>0)this.readState=l1.READING_MESSAGE;else{let X=Buffer.concat([this.readCompressFlag,this.readPartialSize],5);this.readState=l1.NO_DATA,T.push(X)}}break;case l1.READING_MESSAGE:if(Y=Math.min($.length-q,this.readMessageRemaining),this.readPartialMessage.push($.slice(q,q+Y)),this.readMessageRemaining-=Y,q+=Y,this.readMessageRemaining===0){let X=[this.readCompressFlag,this.readPartialSize].concat(this.readPartialMessage),J=Buffer.concat(X,this.readMessageSize+5);this.readState=l1.NO_DATA,T.push(J)}break;default:throw Error("Unexpected read state")}return T}}yA.StreamDecoder=CA});var hA=B((xA)=>{Object.defineProperty(xA,"__esModule",{value:!0});xA.Http2SubchannelCall=void 0;var J$=e("http2"),eB=e("os"),U0=n(),Q$=P0(),$R=NX(),qR=Z0(),YR=n(),TR="subchannel_call";function XR($){for(let[q,Y]of Object.entries(eB.constants.errno))if(Y===$)return q;return"Unknown system error "+$}function HX($){let q=`Received HTTP status code ${$}`,Y;switch($){case 400:Y=U0.Status.INTERNAL;break;case 401:Y=U0.Status.UNAUTHENTICATED;break;case 403:Y=U0.Status.PERMISSION_DENIED;break;case 404:Y=U0.Status.UNIMPLEMENTED;break;case 429:case 502:case 503:case 504:Y=U0.Status.UNAVAILABLE;break;default:Y=U0.Status.UNKNOWN}return{code:Y,details:q,metadata:new Q$.Metadata}}class vA{constructor($,q,Y,T,X){var J;this.http2Stream=$,this.callEventTracker=q,this.listener=Y,this.transport=T,this.callId=X,this.isReadFilterPending=!1,this.isPushPending=!1,this.canPush=!1,this.readsClosed=!1,this.statusOutput=!1,this.unpushedReadMessages=[],this.finalStatus=null,this.internalError=null,this.serverEndedCall=!1,this.connectionDropped=!1;let Q=(J=T.getOptions()["grpc.max_receive_message_length"])!==null&&J!==void 0?J:U0.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH;this.decoder=new $R.StreamDecoder(Q),$.on("response",(U,Z)=>{let K="";for(let A of Object.keys(U))K+="\t\t"+A+": "+U[A]+`
16
- `;if(this.trace(`Received server headers:
17
- `+K),this.httpStatusCode=U[":status"],Z&J$.constants.NGHTTP2_FLAG_END_STREAM)this.handleTrailers(U);else{let A;try{A=Q$.Metadata.fromHttp2Headers(U)}catch(W){this.endCall({code:U0.Status.UNKNOWN,details:W.message,metadata:new Q$.Metadata});return}this.listener.onReceiveMetadata(A)}}),$.on("trailers",(U)=>{this.handleTrailers(U)}),$.on("data",(U)=>{if(this.statusOutput)return;this.trace("receive HTTP/2 data frame of length "+U.length);let Z;try{Z=this.decoder.write(U)}catch(K){if(this.httpStatusCode!==void 0&&this.httpStatusCode!==200){let A=HX(this.httpStatusCode);this.cancelWithStatus(A.code,A.details)}else this.cancelWithStatus(U0.Status.RESOURCE_EXHAUSTED,K.message);return}for(let K of Z)this.trace("parsed message of length "+K.length),this.callEventTracker.addMessageReceived(),this.tryPush(K)}),$.on("end",()=>{this.readsClosed=!0,this.maybeOutputStatus()}),$.on("close",()=>{this.serverEndedCall=!0,process.nextTick(()=>{var U;if(this.trace("HTTP/2 stream closed with code "+$.rstCode),((U=this.finalStatus)===null||U===void 0?void 0:U.code)===U0.Status.OK)return;let Z,K="";switch($.rstCode){case J$.constants.NGHTTP2_NO_ERROR:if(this.finalStatus!==null)return;if(this.httpStatusCode&&this.httpStatusCode!==200){let A=HX(this.httpStatusCode);Z=A.code,K=A.details}else Z=U0.Status.INTERNAL,K=`Received RST_STREAM with code ${$.rstCode} (Call ended without gRPC status)`;break;case J$.constants.NGHTTP2_REFUSED_STREAM:Z=U0.Status.UNAVAILABLE,K="Stream refused by server";break;case J$.constants.NGHTTP2_CANCEL:if(this.connectionDropped)Z=U0.Status.UNAVAILABLE,K="Connection dropped";else Z=U0.Status.CANCELLED,K="Call cancelled";break;case J$.constants.NGHTTP2_ENHANCE_YOUR_CALM:Z=U0.Status.RESOURCE_EXHAUSTED,K="Bandwidth exhausted or memory limit exceeded";break;case J$.constants.NGHTTP2_INADEQUATE_SECURITY:Z=U0.Status.PERMISSION_DENIED,K="Protocol not secure enough";break;case J$.constants.NGHTTP2_INTERNAL_ERROR:if(Z=U0.Status.INTERNAL,this.internalError===null)K=`Received RST_STREAM with code ${$.rstCode} (Internal server error)`;else if(this.internalError.code==="ECONNRESET"||this.internalError.code==="ETIMEDOUT")Z=U0.Status.UNAVAILABLE,K=this.internalError.message;else K=`Received RST_STREAM with code ${$.rstCode} triggered by internal client error: ${this.internalError.message}`;break;default:Z=U0.Status.INTERNAL,K=`Received RST_STREAM with code ${$.rstCode}`}this.endCall({code:Z,details:K,metadata:new Q$.Metadata,rstCode:$.rstCode})})}),$.on("error",(U)=>{if(U.code!=="ERR_HTTP2_STREAM_ERROR")this.trace("Node error event: message="+U.message+" code="+U.code+" errno="+XR(U.errno)+" syscall="+U.syscall),this.internalError=U;this.callEventTracker.onStreamEnd(!1)})}getDeadlineInfo(){return[`remote_addr=${this.getPeer()}`]}onDisconnect(){this.connectionDropped=!0,setImmediate(()=>{this.endCall({code:U0.Status.UNAVAILABLE,details:"Connection dropped",metadata:new Q$.Metadata})})}outputStatus(){if(!this.statusOutput)this.statusOutput=!0,this.trace("ended with status: code="+this.finalStatus.code+' details="'+this.finalStatus.details+'"'),this.callEventTracker.onCallEnd(this.finalStatus),process.nextTick(()=>{this.listener.onReceiveStatus(this.finalStatus)}),this.http2Stream.resume()}trace($){qR.trace(YR.LogVerbosity.DEBUG,TR,"["+this.callId+"] "+$)}endCall($){if(this.finalStatus===null||this.finalStatus.code===U0.Status.OK)this.finalStatus=$,this.maybeOutputStatus();this.destroyHttp2Stream()}maybeOutputStatus(){if(this.finalStatus!==null){if(this.finalStatus.code!==U0.Status.OK||this.readsClosed&&this.unpushedReadMessages.length===0&&!this.isReadFilterPending&&!this.isPushPending)this.outputStatus()}}push($){this.trace("pushing to reader message of length "+($ instanceof Buffer?$.length:null)),this.canPush=!1,this.isPushPending=!0,process.nextTick(()=>{if(this.isPushPending=!1,this.statusOutput)return;this.listener.onReceiveMessage($),this.maybeOutputStatus()})}tryPush($){if(this.canPush)this.http2Stream.pause(),this.push($);else this.trace("unpushedReadMessages.push message of length "+$.length),this.unpushedReadMessages.push($)}handleTrailers($){this.serverEndedCall=!0,this.callEventTracker.onStreamEnd(!0);let q="";for(let J of Object.keys($))q+="\t\t"+J+": "+$[J]+`
18
- `;this.trace(`Received server trailers:
19
- `+q);let Y;try{Y=Q$.Metadata.fromHttp2Headers($)}catch(J){Y=new Q$.Metadata}let T=Y.getMap(),X;if(typeof T["grpc-status"]==="string"){let J=Number(T["grpc-status"]);this.trace("received status code "+J+" from server"),Y.remove("grpc-status");let Q="";if(typeof T["grpc-message"]==="string"){try{Q=decodeURI(T["grpc-message"])}catch(U){Q=T["grpc-message"]}Y.remove("grpc-message"),this.trace('received status details string "'+Q+'" from server')}X={code:J,details:Q,metadata:Y}}else if(this.httpStatusCode)X=HX(this.httpStatusCode),X.metadata=Y;else X={code:U0.Status.UNKNOWN,details:"No status information received",metadata:Y};this.endCall(X)}destroyHttp2Stream(){var $;if(this.http2Stream.destroyed)return;if(this.serverEndedCall)this.http2Stream.end();else{let q;if((($=this.finalStatus)===null||$===void 0?void 0:$.code)===U0.Status.OK)q=J$.constants.NGHTTP2_NO_ERROR;else q=J$.constants.NGHTTP2_CANCEL;this.trace("close http2 stream with code "+q),this.http2Stream.close(q)}}cancelWithStatus($,q){this.trace("cancelWithStatus code: "+$+' details: "'+q+'"'),this.endCall({code:$,details:q,metadata:new Q$.Metadata})}getStatus(){return this.finalStatus}getPeer(){return this.transport.getPeerName()}getCallNumber(){return this.callId}getAuthContext(){return this.transport.getAuthContext()}startRead(){if(this.finalStatus!==null&&this.finalStatus.code!==U0.Status.OK){this.readsClosed=!0,this.maybeOutputStatus();return}if(this.canPush=!0,this.unpushedReadMessages.length>0){let $=this.unpushedReadMessages.shift();this.push($);return}this.http2Stream.resume()}sendMessageWithContext($,q){this.trace("write() called with message of length "+q.length);let Y=(T)=>{process.nextTick(()=>{var X;let J=U0.Status.UNAVAILABLE;if((T===null||T===void 0?void 0:T.code)==="ERR_STREAM_WRITE_AFTER_END")J=U0.Status.INTERNAL;if(T)this.cancelWithStatus(J,`Write error: ${T.message}`);(X=$.callback)===null||X===void 0||X.call($)})};this.trace("sending data chunk of length "+q.length),this.callEventTracker.addMessageSent();try{this.http2Stream.write(q,Y)}catch(T){this.endCall({code:U0.Status.UNAVAILABLE,details:`Write failed with error ${T.message}`,metadata:new Q$.Metadata})}}halfClose(){this.trace("end() called"),this.trace("calling end() on HTTP/2 stream"),this.http2Stream.end()}}xA.Http2SubchannelCall=vA});var bA=B((mA)=>{Object.defineProperty(mA,"__esModule",{value:!0});mA.Http2SubchannelConnector=void 0;var i$=e("http2"),JR=e("tls"),gT=R$(),pY=n(),QR=IX(),hq=Z0(),UR=H1(),mT=i0(),zX=p0(),ZR=e("net"),KR=hA(),AR=jT(),MX="transport",WR="transport_flowctrl",GR=z9().version,{HTTP2_HEADER_AUTHORITY:ER,HTTP2_HEADER_CONTENT_TYPE:VR,HTTP2_HEADER_METHOD:DR,HTTP2_HEADER_PATH:FR,HTTP2_HEADER_TE:IR,HTTP2_HEADER_USER_AGENT:NR}=i$.constants,HR=20000,zR=Buffer.from("too_many_pings","ascii");class _A{constructor($,q,Y,T){if(this.session=$,this.options=Y,this.remoteName=T,this.keepaliveTimer=null,this.pendingSendKeepalivePing=!1,this.activeCalls=new Set,this.disconnectListeners=[],this.disconnectHandled=!1,this.channelzEnabled=!0,this.keepalivesSent=0,this.messagesSent=0,this.messagesReceived=0,this.lastMessageSentTimestamp=null,this.lastMessageReceivedTimestamp=null,this.subchannelAddressString=(0,mT.subchannelAddressToString)(q),Y["grpc.enable_channelz"]===0)this.channelzEnabled=!1,this.streamTracker=new gT.ChannelzCallTrackerStub;else this.streamTracker=new gT.ChannelzCallTracker;if(this.channelzRef=(0,gT.registerChannelzSocket)(this.subchannelAddressString,()=>this.getChannelzInfo(),this.channelzEnabled),this.userAgent=[Y["grpc.primary_user_agent"],`grpc-node-js/${GR}`,Y["grpc.secondary_user_agent"]].filter((X)=>X).join(" "),"grpc.keepalive_time_ms"in Y)this.keepaliveTimeMs=Y["grpc.keepalive_time_ms"];else this.keepaliveTimeMs=-1;if("grpc.keepalive_timeout_ms"in Y)this.keepaliveTimeoutMs=Y["grpc.keepalive_timeout_ms"];else this.keepaliveTimeoutMs=HR;if("grpc.keepalive_permit_without_calls"in Y)this.keepaliveWithoutCalls=Y["grpc.keepalive_permit_without_calls"]===1;else this.keepaliveWithoutCalls=!1;if($.once("close",()=>{this.trace("session closed"),this.handleDisconnect()}),$.once("goaway",(X,J,Q)=>{let U=!1;if(X===i$.constants.NGHTTP2_ENHANCE_YOUR_CALM&&Q&&Q.equals(zR))U=!0;this.trace("connection closed by GOAWAY with code "+X+" and data "+(Q===null||Q===void 0?void 0:Q.toString())),this.reportDisconnectToOwner(U)}),$.once("error",(X)=>{this.trace("connection closed with error "+X.message),this.handleDisconnect()}),$.socket.once("close",(X)=>{this.trace("connection closed. hadError="+X),this.handleDisconnect()}),hq.isTracerEnabled(MX))$.on("remoteSettings",(X)=>{this.trace("new settings received"+(this.session!==$?" on the old connection":"")+": "+JSON.stringify(X))}),$.on("localSettings",(X)=>{this.trace("local settings acknowledged by remote"+(this.session!==$?" on the old connection":"")+": "+JSON.stringify(X))});if(this.keepaliveWithoutCalls)this.maybeStartKeepalivePingTimer();if($.socket instanceof JR.TLSSocket)this.authContext={transportSecurityType:"ssl",sslPeerCertificate:$.socket.getPeerCertificate()};else this.authContext={}}getChannelzInfo(){var $,q,Y;let T=this.session.socket,X=T.remoteAddress?(0,mT.stringToSubchannelAddress)(T.remoteAddress,T.remotePort):null,J=T.localAddress?(0,mT.stringToSubchannelAddress)(T.localAddress,T.localPort):null,Q;if(this.session.encrypted){let Z=T,K=Z.getCipher(),A=Z.getCertificate(),W=Z.getPeerCertificate();Q={cipherSuiteStandardName:($=K.standardName)!==null&&$!==void 0?$:null,cipherSuiteOtherName:K.standardName?null:K.name,localCertificate:A&&"raw"in A?A.raw:null,remoteCertificate:W&&"raw"in W?W.raw:null}}else Q=null;return{remoteAddress:X,localAddress:J,security:Q,remoteName:this.remoteName,streamsStarted:this.streamTracker.callsStarted,streamsSucceeded:this.streamTracker.callsSucceeded,streamsFailed:this.streamTracker.callsFailed,messagesSent:this.messagesSent,messagesReceived:this.messagesReceived,keepAlivesSent:this.keepalivesSent,lastLocalStreamCreatedTimestamp:this.streamTracker.lastCallStartedTimestamp,lastRemoteStreamCreatedTimestamp:null,lastMessageSentTimestamp:this.lastMessageSentTimestamp,lastMessageReceivedTimestamp:this.lastMessageReceivedTimestamp,localFlowControlWindow:(q=this.session.state.localWindowSize)!==null&&q!==void 0?q:null,remoteFlowControlWindow:(Y=this.session.state.remoteWindowSize)!==null&&Y!==void 0?Y:null}}trace($){hq.trace(pY.LogVerbosity.DEBUG,MX,"("+this.channelzRef.id+") "+this.subchannelAddressString+" "+$)}keepaliveTrace($){hq.trace(pY.LogVerbosity.DEBUG,"keepalive","("+this.channelzRef.id+") "+this.subchannelAddressString+" "+$)}flowControlTrace($){hq.trace(pY.LogVerbosity.DEBUG,WR,"("+this.channelzRef.id+") "+this.subchannelAddressString+" "+$)}internalsTrace($){hq.trace(pY.LogVerbosity.DEBUG,"transport_internals","("+this.channelzRef.id+") "+this.subchannelAddressString+" "+$)}reportDisconnectToOwner($){if(this.disconnectHandled)return;this.disconnectHandled=!0,this.disconnectListeners.forEach((q)=>q($))}handleDisconnect(){this.clearKeepaliveTimeout(),this.reportDisconnectToOwner(!1);for(let $ of this.activeCalls)$.onDisconnect();setImmediate(()=>{this.session.destroy()})}addDisconnectListener($){this.disconnectListeners.push($)}canSendPing(){return!this.session.destroyed&&this.keepaliveTimeMs>0&&(this.keepaliveWithoutCalls||this.activeCalls.size>0)}maybeSendPing(){var $,q;if(!this.canSendPing()){this.pendingSendKeepalivePing=!0;return}if(this.keepaliveTimer){console.error("keepaliveTimeout is not null");return}if(this.channelzEnabled)this.keepalivesSent+=1;this.keepaliveTrace("Sending ping with timeout "+this.keepaliveTimeoutMs+"ms"),this.keepaliveTimer=setTimeout(()=>{this.keepaliveTimer=null,this.keepaliveTrace("Ping timeout passed without response"),this.handleDisconnect()},this.keepaliveTimeoutMs),(q=($=this.keepaliveTimer).unref)===null||q===void 0||q.call($);let Y="";try{if(!this.session.ping((X,J,Q)=>{if(this.clearKeepaliveTimeout(),X)this.keepaliveTrace("Ping failed with error "+X.message),this.handleDisconnect();else this.keepaliveTrace("Received ping response"),this.maybeStartKeepalivePingTimer()}))Y="Ping returned false"}catch(T){Y=(T instanceof Error?T.message:"")||"Unknown error"}if(Y)this.keepaliveTrace("Ping send failed: "+Y),this.handleDisconnect()}maybeStartKeepalivePingTimer(){var $,q;if(!this.canSendPing())return;if(this.pendingSendKeepalivePing)this.pendingSendKeepalivePing=!1,this.maybeSendPing();else if(!this.keepaliveTimer)this.keepaliveTrace("Starting keepalive timer for "+this.keepaliveTimeMs+"ms"),this.keepaliveTimer=setTimeout(()=>{this.keepaliveTimer=null,this.maybeSendPing()},this.keepaliveTimeMs),(q=($=this.keepaliveTimer).unref)===null||q===void 0||q.call($)}clearKeepaliveTimeout(){if(this.keepaliveTimer)clearTimeout(this.keepaliveTimer),this.keepaliveTimer=null}removeActiveCall($){if(this.activeCalls.delete($),this.activeCalls.size===0)this.session.unref()}addActiveCall($){if(this.activeCalls.add($),this.activeCalls.size===1){if(this.session.ref(),!this.keepaliveWithoutCalls)this.maybeStartKeepalivePingTimer()}}createCall($,q,Y,T,X){let J=$.toHttp2Headers();J[ER]=q,J[NR]=this.userAgent,J[VR]="application/grpc",J[DR]="POST",J[FR]=Y,J[IR]="trailers";let Q;try{Q=this.session.request(J)}catch(K){throw this.handleDisconnect(),K}this.flowControlTrace("local window size: "+this.session.state.localWindowSize+" remote window size: "+this.session.state.remoteWindowSize),this.internalsTrace("session.closed="+this.session.closed+" session.destroyed="+this.session.destroyed+" session.socket.destroyed="+this.session.socket.destroyed);let U,Z;if(this.channelzEnabled)this.streamTracker.addCallStarted(),U={addMessageSent:()=>{var K;this.messagesSent+=1,this.lastMessageSentTimestamp=new Date,(K=X.addMessageSent)===null||K===void 0||K.call(X)},addMessageReceived:()=>{var K;this.messagesReceived+=1,this.lastMessageReceivedTimestamp=new Date,(K=X.addMessageReceived)===null||K===void 0||K.call(X)},onCallEnd:(K)=>{var A;(A=X.onCallEnd)===null||A===void 0||A.call(X,K),this.removeActiveCall(Z)},onStreamEnd:(K)=>{var A;if(K)this.streamTracker.addCallSucceeded();else this.streamTracker.addCallFailed();(A=X.onStreamEnd)===null||A===void 0||A.call(X,K)}};else U={addMessageSent:()=>{var K;(K=X.addMessageSent)===null||K===void 0||K.call(X)},addMessageReceived:()=>{var K;(K=X.addMessageReceived)===null||K===void 0||K.call(X)},onCallEnd:(K)=>{var A;(A=X.onCallEnd)===null||A===void 0||A.call(X,K),this.removeActiveCall(Z)},onStreamEnd:(K)=>{var A;(A=X.onStreamEnd)===null||A===void 0||A.call(X,K)}};return Z=new KR.Http2SubchannelCall(Q,U,T,this,(0,AR.getNextCallNumber)()),this.addActiveCall(Z),Z}getChannelzRef(){return this.channelzRef}getPeerName(){return this.subchannelAddressString}getOptions(){return this.options}getAuthContext(){return this.authContext}shutdown(){this.session.close(),(0,gT.unregisterChannelzRef)(this.channelzRef)}}class gA{constructor($){this.channelTarget=$,this.session=null,this.isShutdown=!1}trace($){hq.trace(pY.LogVerbosity.DEBUG,MX,(0,zX.uriToString)(this.channelTarget)+" "+$)}createSession($,q,Y){if(this.isShutdown)return Promise.reject();if($.socket.closed)return Promise.reject("Connection closed before starting HTTP/2 handshake");return new Promise((T,X)=>{var J,Q,U,Z,K,A,W,G;let V=null,F=this.channelTarget;if("grpc.http_connect_target"in Y){let C=(0,zX.parseUri)(Y["grpc.http_connect_target"]);if(C)F=C,V=(0,zX.uriToString)(C)}let N=$.secure?"https":"http",D=(0,UR.getDefaultAuthority)(F),z=()=>{var C;(C=this.session)===null||C===void 0||C.destroy(),this.session=null,setImmediate(()=>{if(!m)m=!0,X(`${k.trim()} (${new Date().toISOString()})`)})},S=(C)=>{var j;if((j=this.session)===null||j===void 0||j.destroy(),k=C.message,this.trace("connection failed with error "+k),!m)m=!0,X(`${k} (${new Date().toISOString()})`)},v={createConnection:(C,j)=>{return $.socket},settings:{initialWindowSize:(Z=(J=Y["grpc-node.flow_control_window"])!==null&&J!==void 0?J:(U=(Q=i$.getDefaultSettings)===null||Q===void 0?void 0:Q.call(i$))===null||U===void 0?void 0:U.initialWindowSize)!==null&&Z!==void 0?Z:65535},maxSendHeaderBlockLength:Number.MAX_SAFE_INTEGER,maxSessionMemory:(K=Y["grpc-node.max_session_memory"])!==null&&K!==void 0?K:Number.MAX_SAFE_INTEGER},H=i$.connect(`${N}://${D}`,v),_=(G=(W=(A=i$.getDefaultSettings)===null||A===void 0?void 0:A.call(i$))===null||W===void 0?void 0:W.initialWindowSize)!==null&&G!==void 0?G:65535,y=Y["grpc-node.flow_control_window"];this.session=H;let k="Failed to connect",m=!1;H.unref(),H.once("remoteSettings",()=>{var C;if(y&&y>_)try{H.setLocalWindowSize(y)}catch(j){let M=y-((C=H.state.localWindowSize)!==null&&C!==void 0?C:_);if(M>0)H.incrementWindowSize(M)}H.removeAllListeners(),$.socket.removeListener("close",z),$.socket.removeListener("error",S),T(new _A(H,q,Y,V)),this.session=null}),H.once("close",z),H.once("error",S),$.socket.once("close",z),$.socket.once("error",S)})}tcpConnect($,q){return(0,QR.getProxiedConnection)($,q).then((Y)=>{if(Y)return Y;else return new Promise((T,X)=>{let J=()=>{X(Error("Socket closed"))},Q=(Z)=>{X(Z)},U=ZR.connect($,()=>{U.removeListener("close",J),U.removeListener("error",Q),T(U)});U.once("close",J),U.once("error",Q)})})}async connect($,q,Y){if(this.isShutdown)return Promise.reject();let T=null,X=null,J=(0,mT.subchannelAddressToString)($);try{return this.trace(J+" Waiting for secureConnector to be ready"),await q.waitForReady(),this.trace(J+" secureConnector is ready"),T=await this.tcpConnect($,Y),T.setNoDelay(),this.trace(J+" Established TCP connection"),X=await q.connect(T),this.trace(J+" Established secure connection"),this.createSession(X,$,Y)}catch(Q){throw T===null||T===void 0||T.destroy(),X===null||X===void 0||X.socket.destroy(),Q}}shutdown(){var $;this.isShutdown=!0,($=this.session)===null||$===void 0||$.close(),this.session=null}}mA.Http2SubchannelConnector=gA});var cA=B((uA)=>{Object.defineProperty(uA,"__esModule",{value:!0});uA.SubchannelPool=void 0;uA.getSubchannelPool=SR;var MR=sQ(),BR=DA(),RR=i0(),PR=p0(),OR=bA(),LR=1e4;class fT{constructor(){this.pool=Object.create(null),this.cleanupTimer=null}unrefUnusedSubchannels(){let $=!0;for(let q in this.pool){let T=this.pool[q].filter((X)=>!X.subchannel.unrefIfOneRef());if(T.length>0)$=!1;this.pool[q]=T}if($&&this.cleanupTimer!==null)clearInterval(this.cleanupTimer),this.cleanupTimer=null}ensureCleanupTask(){var $,q;if(this.cleanupTimer===null)this.cleanupTimer=setInterval(()=>{this.unrefUnusedSubchannels()},LR),(q=($=this.cleanupTimer).unref)===null||q===void 0||q.call($)}getOrCreateSubchannel($,q,Y,T){this.ensureCleanupTask();let X=(0,PR.uriToString)($);if(X in this.pool){let Q=this.pool[X];for(let U of Q)if((0,RR.subchannelAddressEqual)(q,U.subchannelAddress)&&(0,MR.channelOptionsEqual)(Y,U.channelArguments)&&T._equals(U.channelCredentials))return U.subchannel}let J=new BR.Subchannel($,q,Y,T,new OR.Http2SubchannelConnector($));if(!(X in this.pool))this.pool[X]=[];return this.pool[X].push({subchannelAddress:q,channelArguments:Y,channelCredentials:T,subchannel:J}),J.ref(),J}}uA.SubchannelPool=fT;var wR=new fT;function SR($){if($)return wR;else return new fT}});var aA=B((iA)=>{Object.defineProperty(iA,"__esModule",{value:!0});iA.LoadBalancingCall=void 0;var pA=l0(),bT=n(),lA=jq(),uT=P0(),lY=s1(),yR=p0(),jR=Z0(),BX=fY(),vR=e("http2"),xR="load_balancing_call";class nA{constructor($,q,Y,T,X,J,Q){var U,Z;this.channel=$,this.callConfig=q,this.methodName=Y,this.host=T,this.credentials=X,this.deadline=J,this.callNumber=Q,this.child=null,this.readPending=!1,this.pendingMessage=null,this.pendingHalfClose=!1,this.ended=!1,this.metadata=null,this.listener=null,this.onCallEnded=null,this.childStartTime=null;let K=this.methodName.split("/"),A="";if(K.length>=2)A=K[1];let W=(Z=(U=(0,yR.splitHostPort)(this.host))===null||U===void 0?void 0:U.host)!==null&&Z!==void 0?Z:"localhost";this.serviceUrl=`https://${W}/${A}`,this.startTime=new Date}getDeadlineInfo(){var $,q;let Y=[];if(this.childStartTime){if(this.childStartTime>this.startTime){if(($=this.metadata)===null||$===void 0?void 0:$.getOptions().waitForReady)Y.push("wait_for_ready");Y.push(`LB pick: ${(0,lA.formatDateDifference)(this.startTime,this.childStartTime)}`)}return Y.push(...this.child.getDeadlineInfo()),Y}else{if((q=this.metadata)===null||q===void 0?void 0:q.getOptions().waitForReady)Y.push("wait_for_ready");Y.push("Waiting for LB pick")}return Y}trace($){jR.trace(bT.LogVerbosity.DEBUG,xR,"["+this.callNumber+"] "+$)}outputStatus($,q){var Y,T;if(!this.ended){this.ended=!0,this.trace("ended with status: code="+$.code+' details="'+$.details+'" start time='+this.startTime.toISOString());let X=Object.assign(Object.assign({},$),{progress:q});(Y=this.listener)===null||Y===void 0||Y.onReceiveStatus(X),(T=this.onCallEnded)===null||T===void 0||T.call(this,X.code,X.details,X.metadata)}}doPick(){var $,q;if(this.ended)return;if(!this.metadata)throw Error("doPick called before start");this.trace("Pick called");let Y=this.metadata.clone(),T=this.channel.doPick(Y,this.callConfig.pickInformation),X=T.subchannel?"("+T.subchannel.getChannelzRef().id+") "+T.subchannel.getAddress():""+T.subchannel;switch(this.trace("Pick result: "+lY.PickResultType[T.pickResultType]+" subchannel: "+X+" status: "+(($=T.status)===null||$===void 0?void 0:$.code)+" "+((q=T.status)===null||q===void 0?void 0:q.details)),T.pickResultType){case lY.PickResultType.COMPLETE:this.credentials.compose(T.subchannel.getCallCredentials()).generateMetadata({method_name:this.methodName,service_url:this.serviceUrl}).then((Z)=>{var K;if(this.ended){this.trace("Credentials metadata generation finished after call ended");return}if(Y.merge(Z),Y.get("authorization").length>1)this.outputStatus({code:bT.Status.INTERNAL,details:'"authorization" metadata cannot have multiple values',metadata:new uT.Metadata},"PROCESSED");if(T.subchannel.getConnectivityState()!==pA.ConnectivityState.READY){this.trace("Picked subchannel "+X+" has state "+pA.ConnectivityState[T.subchannel.getConnectivityState()]+" after getting credentials metadata. Retrying pick"),this.doPick();return}if(this.deadline!==1/0)Y.set("grpc-timeout",(0,lA.getDeadlineTimeoutString)(this.deadline));try{this.child=T.subchannel.getRealSubchannel().createCall(Y,this.host,this.methodName,{onReceiveMetadata:(A)=>{this.trace("Received metadata"),this.listener.onReceiveMetadata(A)},onReceiveMessage:(A)=>{this.trace("Received message"),this.listener.onReceiveMessage(A)},onReceiveStatus:(A)=>{if(this.trace("Received status"),A.rstCode===vR.constants.NGHTTP2_REFUSED_STREAM)this.outputStatus(A,"REFUSED");else this.outputStatus(A,"PROCESSED")}}),this.childStartTime=new Date}catch(A){this.trace("Failed to start call on picked subchannel "+X+" with error "+A.message),this.outputStatus({code:bT.Status.INTERNAL,details:"Failed to start HTTP/2 stream with error "+A.message,metadata:new uT.Metadata},"NOT_STARTED");return}if((K=T.onCallStarted)===null||K===void 0||K.call(T),this.onCallEnded=T.onCallEnded,this.trace("Created child call ["+this.child.getCallNumber()+"]"),this.readPending)this.child.startRead();if(this.pendingMessage)this.child.sendMessageWithContext(this.pendingMessage.context,this.pendingMessage.message);if(this.pendingHalfClose)this.child.halfClose()},(Z)=>{let{code:K,details:A}=(0,BX.restrictControlPlaneStatusCode)(typeof Z.code==="number"?Z.code:bT.Status.UNKNOWN,`Getting metadata from plugin failed with error: ${Z.message}`);this.outputStatus({code:K,details:A,metadata:new uT.Metadata},"PROCESSED")});break;case lY.PickResultType.DROP:let{code:Q,details:U}=(0,BX.restrictControlPlaneStatusCode)(T.status.code,T.status.details);setImmediate(()=>{this.outputStatus({code:Q,details:U,metadata:T.status.metadata},"DROP")});break;case lY.PickResultType.TRANSIENT_FAILURE:if(this.metadata.getOptions().waitForReady)this.channel.queueCallForPick(this);else{let{code:Z,details:K}=(0,BX.restrictControlPlaneStatusCode)(T.status.code,T.status.details);setImmediate(()=>{this.outputStatus({code:Z,details:K,metadata:T.status.metadata},"PROCESSED")})}break;case lY.PickResultType.QUEUE:this.channel.queueCallForPick(this)}}cancelWithStatus($,q){var Y;this.trace("cancelWithStatus code: "+$+' details: "'+q+'"'),(Y=this.child)===null||Y===void 0||Y.cancelWithStatus($,q),this.outputStatus({code:$,details:q,metadata:new uT.Metadata},"PROCESSED")}getPeer(){var $,q;return(q=($=this.child)===null||$===void 0?void 0:$.getPeer())!==null&&q!==void 0?q:this.channel.getTarget()}start($,q){this.trace("start called"),this.listener=q,this.metadata=$,this.doPick()}sendMessageWithContext($,q){if(this.trace("write() called with message of length "+q.length),this.child)this.child.sendMessageWithContext($,q);else this.pendingMessage={context:$,message:q}}startRead(){if(this.trace("startRead called"),this.child)this.child.startRead();else this.readPending=!0}halfClose(){if(this.trace("halfClose called"),this.child)this.child.halfClose();else this.pendingHalfClose=!0}setCredentials($){throw Error("Method not implemented.")}getCallNumber(){return this.callNumber}getAuthContext(){if(this.child)return this.child.getAuthContext();else return null}}iA.LoadBalancingCall=nA});var $W=B((tA)=>{Object.defineProperty(tA,"__esModule",{value:!0});tA.ResolvingCall=void 0;var kR=m6(),r$=n(),a$=jq(),oA=P0(),hR=Z0(),_R=fY(),gR="resolving_call";class sA{constructor($,q,Y,T,X){if(this.channel=$,this.method=q,this.filterStackFactory=T,this.callNumber=X,this.child=null,this.readPending=!1,this.pendingMessage=null,this.pendingHalfClose=!1,this.ended=!1,this.readFilterPending=!1,this.writeFilterPending=!1,this.pendingChildStatus=null,this.metadata=null,this.listener=null,this.statusWatchers=[],this.deadlineTimer=setTimeout(()=>{},0),this.filterStack=null,this.deadlineStartTime=null,this.configReceivedTime=null,this.childStartTime=null,this.credentials=kR.CallCredentials.createEmpty(),this.deadline=Y.deadline,this.host=Y.host,Y.parentCall){if(Y.flags&r$.Propagate.CANCELLATION)Y.parentCall.on("cancelled",()=>{this.cancelWithStatus(r$.Status.CANCELLED,"Cancelled by parent call")});if(Y.flags&r$.Propagate.DEADLINE)this.trace("Propagating deadline from parent: "+Y.parentCall.getDeadline()),this.deadline=(0,a$.minDeadline)(this.deadline,Y.parentCall.getDeadline())}this.trace("Created"),this.runDeadlineTimer()}trace($){hR.trace(r$.LogVerbosity.DEBUG,gR,"["+this.callNumber+"] "+$)}runDeadlineTimer(){clearTimeout(this.deadlineTimer),this.deadlineStartTime=new Date,this.trace("Deadline: "+(0,a$.deadlineToString)(this.deadline));let $=(0,a$.getRelativeTimeout)(this.deadline);if($!==1/0){this.trace("Deadline will be reached in "+$+"ms");let q=()=>{if(!this.deadlineStartTime){this.cancelWithStatus(r$.Status.DEADLINE_EXCEEDED,"Deadline exceeded");return}let Y=[],T=new Date;if(Y.push(`Deadline exceeded after ${(0,a$.formatDateDifference)(this.deadlineStartTime,T)}`),this.configReceivedTime){if(this.configReceivedTime>this.deadlineStartTime)Y.push(`name resolution: ${(0,a$.formatDateDifference)(this.deadlineStartTime,this.configReceivedTime)}`);if(this.childStartTime){if(this.childStartTime>this.configReceivedTime)Y.push(`metadata filters: ${(0,a$.formatDateDifference)(this.configReceivedTime,this.childStartTime)}`)}else Y.push("waiting for metadata filters")}else Y.push("waiting for name resolution");if(this.child)Y.push(...this.child.getDeadlineInfo());this.cancelWithStatus(r$.Status.DEADLINE_EXCEEDED,Y.join(","))};if($<=0)process.nextTick(q);else this.deadlineTimer=setTimeout(q,$)}}outputStatus($){if(!this.ended){if(this.ended=!0,!this.filterStack)this.filterStack=this.filterStackFactory.createFilter();clearTimeout(this.deadlineTimer);let q=this.filterStack.receiveTrailers($);this.trace("ended with status: code="+q.code+' details="'+q.details+'"'),this.statusWatchers.forEach((Y)=>Y(q)),process.nextTick(()=>{var Y;(Y=this.listener)===null||Y===void 0||Y.onReceiveStatus(q)})}}sendMessageOnChild($,q){if(!this.child)throw Error("sendMessageonChild called with child not populated");let Y=this.child;this.writeFilterPending=!0,this.filterStack.sendMessage(Promise.resolve({message:q,flags:$.flags})).then((T)=>{if(this.writeFilterPending=!1,Y.sendMessageWithContext($,T.message),this.pendingHalfClose)Y.halfClose()},(T)=>{this.cancelWithStatus(T.code,T.details)})}getConfig(){if(this.ended)return;if(!this.metadata||!this.listener)throw Error("getConfig called before start");let $=this.channel.getConfig(this.method,this.metadata);if($.type==="NONE"){this.channel.queueCallForConfig(this);return}else if($.type==="ERROR"){if(this.metadata.getOptions().waitForReady)this.channel.queueCallForConfig(this);else this.outputStatus($.error);return}this.configReceivedTime=new Date;let q=$.config;if(q.status!==r$.Status.OK){let{code:Y,details:T}=(0,_R.restrictControlPlaneStatusCode)(q.status,"Failed to route call to method "+this.method);this.outputStatus({code:Y,details:T,metadata:new oA.Metadata});return}if(q.methodConfig.timeout){let Y=new Date;Y.setSeconds(Y.getSeconds()+q.methodConfig.timeout.seconds),Y.setMilliseconds(Y.getMilliseconds()+q.methodConfig.timeout.nanos/1e6),this.deadline=(0,a$.minDeadline)(this.deadline,Y),this.runDeadlineTimer()}this.filterStackFactory.push(q.dynamicFilterFactories),this.filterStack=this.filterStackFactory.createFilter(),this.filterStack.sendMetadata(Promise.resolve(this.metadata)).then((Y)=>{if(this.child=this.channel.createRetryingCall(q,this.method,this.host,this.credentials,this.deadline),this.trace("Created child ["+this.child.getCallNumber()+"]"),this.childStartTime=new Date,this.child.start(Y,{onReceiveMetadata:(T)=>{this.trace("Received metadata"),this.listener.onReceiveMetadata(this.filterStack.receiveMetadata(T))},onReceiveMessage:(T)=>{this.trace("Received message"),this.readFilterPending=!0,this.filterStack.receiveMessage(T).then((X)=>{if(this.trace("Finished filtering received message"),this.readFilterPending=!1,this.listener.onReceiveMessage(X),this.pendingChildStatus)this.outputStatus(this.pendingChildStatus)},(X)=>{this.cancelWithStatus(X.code,X.details)})},onReceiveStatus:(T)=>{if(this.trace("Received status"),this.readFilterPending)this.pendingChildStatus=T;else this.outputStatus(T)}}),this.readPending)this.child.startRead();if(this.pendingMessage)this.sendMessageOnChild(this.pendingMessage.context,this.pendingMessage.message);else if(this.pendingHalfClose)this.child.halfClose()},(Y)=>{this.outputStatus(Y)})}reportResolverError($){var q;if((q=this.metadata)===null||q===void 0?void 0:q.getOptions().waitForReady)this.channel.queueCallForConfig(this);else this.outputStatus($)}cancelWithStatus($,q){var Y;this.trace("cancelWithStatus code: "+$+' details: "'+q+'"'),(Y=this.child)===null||Y===void 0||Y.cancelWithStatus($,q),this.outputStatus({code:$,details:q,metadata:new oA.Metadata})}getPeer(){var $,q;return(q=($=this.child)===null||$===void 0?void 0:$.getPeer())!==null&&q!==void 0?q:this.channel.getTarget()}start($,q){this.trace("start called"),this.metadata=$.clone(),this.listener=q,this.getConfig()}sendMessageWithContext($,q){if(this.trace("write() called with message of length "+q.length),this.child)this.sendMessageOnChild($,q);else this.pendingMessage={context:$,message:q}}startRead(){if(this.trace("startRead called"),this.child)this.child.startRead();else this.readPending=!0}halfClose(){if(this.trace("halfClose called"),this.child&&!this.writeFilterPending)this.child.halfClose();else this.pendingHalfClose=!0}setCredentials($){this.credentials=$}addStatusWatcher($){this.statusWatchers.push($)}getCallNumber(){return this.callNumber}getAuthContext(){if(this.child)return this.child.getAuthContext();else return null}}tA.ResolvingCall=sA});var QW=B((XW)=>{Object.defineProperty(XW,"__esModule",{value:!0});XW.RetryingCall=XW.MessageBufferTracker=XW.RetryThrottler=void 0;var dT=n(),mR=jq(),fR=P0(),bR=Z0(),uR="retrying_call";class qW{constructor($,q,Y){if(this.maxTokens=$,this.tokenRatio=q,Y)this.tokens=Y.tokens*($/Y.maxTokens);else this.tokens=$}addCallSucceeded(){this.tokens=Math.min(this.tokens+this.tokenRatio,this.maxTokens)}addCallFailed(){this.tokens=Math.max(this.tokens-1,0)}canRetryCall(){return this.tokens>this.maxTokens/2}}XW.RetryThrottler=qW;class YW{constructor($,q){this.totalLimit=$,this.limitPerCall=q,this.totalAllocated=0,this.allocatedPerCall=new Map}allocate($,q){var Y;let T=(Y=this.allocatedPerCall.get(q))!==null&&Y!==void 0?Y:0;if(this.limitPerCall-T<$||this.totalLimit-this.totalAllocated<$)return!1;return this.allocatedPerCall.set(q,T+$),this.totalAllocated+=$,!0}free($,q){var Y;if(this.totalAllocated<$)throw Error(`Invalid buffer allocation state: call ${q} freed ${$} > total allocated ${this.totalAllocated}`);this.totalAllocated-=$;let T=(Y=this.allocatedPerCall.get(q))!==null&&Y!==void 0?Y:0;if(T<$)throw Error(`Invalid buffer allocation state: call ${q} freed ${$} > allocated for call ${T}`);this.allocatedPerCall.set(q,T-$)}freeAll($){var q;let Y=(q=this.allocatedPerCall.get($))!==null&&q!==void 0?q:0;if(this.totalAllocated<Y)throw Error(`Invalid buffer allocation state: call ${$} allocated ${Y} > total allocated ${this.totalAllocated}`);this.totalAllocated-=Y,this.allocatedPerCall.delete($)}}XW.MessageBufferTracker=YW;var RX="grpc-previous-rpc-attempts",dR=5;class TW{constructor($,q,Y,T,X,J,Q,U,Z){var K;this.channel=$,this.callConfig=q,this.methodName=Y,this.host=T,this.credentials=X,this.deadline=J,this.callNumber=Q,this.bufferTracker=U,this.retryThrottler=Z,this.listener=null,this.initialMetadata=null,this.underlyingCalls=[],this.writeBuffer=[],this.writeBufferOffset=0,this.readStarted=!1,this.transparentRetryUsed=!1,this.attempts=0,this.hedgingTimer=null,this.committedCallIndex=null,this.initialRetryBackoffSec=0,this.nextRetryBackoffSec=0;let A=(K=$.getOptions()["grpc-node.retry_max_attempts_limit"])!==null&&K!==void 0?K:dR;if($.getOptions()["grpc.enable_retries"]===0)this.state="NO_RETRY",this.maxAttempts=1;else if(q.methodConfig.retryPolicy){this.state="RETRY";let W=q.methodConfig.retryPolicy;this.nextRetryBackoffSec=this.initialRetryBackoffSec=Number(W.initialBackoff.substring(0,W.initialBackoff.length-1)),this.maxAttempts=Math.min(W.maxAttempts,A)}else if(q.methodConfig.hedgingPolicy)this.state="HEDGING",this.maxAttempts=Math.min(q.methodConfig.hedgingPolicy.maxAttempts,A);else this.state="TRANSPARENT_ONLY",this.maxAttempts=1;this.startTime=new Date}getDeadlineInfo(){if(this.underlyingCalls.length===0)return[];let $=[],q=this.underlyingCalls[this.underlyingCalls.length-1];if(this.underlyingCalls.length>1)$.push(`previous attempts: ${this.underlyingCalls.length-1}`);if(q.startTime>this.startTime)$.push(`time to current attempt start: ${(0,mR.formatDateDifference)(this.startTime,q.startTime)}`);return $.push(...q.call.getDeadlineInfo()),$}getCallNumber(){return this.callNumber}trace($){bR.trace(dT.LogVerbosity.DEBUG,uR,"["+this.callNumber+"] "+$)}reportStatus($){this.trace("ended with status: code="+$.code+' details="'+$.details+'" start time='+this.startTime.toISOString()),this.bufferTracker.freeAll(this.callNumber),this.writeBufferOffset=this.writeBufferOffset+this.writeBuffer.length,this.writeBuffer=[],process.nextTick(()=>{var q;(q=this.listener)===null||q===void 0||q.onReceiveStatus({code:$.code,details:$.details,metadata:$.metadata})})}cancelWithStatus($,q){this.trace("cancelWithStatus code: "+$+' details: "'+q+'"'),this.reportStatus({code:$,details:q,metadata:new fR.Metadata});for(let{call:Y}of this.underlyingCalls)Y.cancelWithStatus($,q)}getPeer(){if(this.committedCallIndex!==null)return this.underlyingCalls[this.committedCallIndex].call.getPeer();else return"unknown"}getBufferEntry($){var q;return(q=this.writeBuffer[$-this.writeBufferOffset])!==null&&q!==void 0?q:{entryType:"FREED",allocated:!1}}getNextBufferIndex(){return this.writeBufferOffset+this.writeBuffer.length}clearSentMessages(){if(this.state!=="COMMITTED")return;let $;if(this.underlyingCalls[this.committedCallIndex].state==="COMPLETED")$=this.getNextBufferIndex();else $=this.underlyingCalls[this.committedCallIndex].nextMessageToSend;for(let q=this.writeBufferOffset;q<$;q++){let Y=this.getBufferEntry(q);if(Y.allocated)this.bufferTracker.free(Y.message.message.length,this.callNumber)}this.writeBuffer=this.writeBuffer.slice($-this.writeBufferOffset),this.writeBufferOffset=$}commitCall($){var q,Y;if(this.state==="COMMITTED")return;this.trace("Committing call ["+this.underlyingCalls[$].call.getCallNumber()+"] at index "+$),this.state="COMMITTED",(Y=(q=this.callConfig).onCommitted)===null||Y===void 0||Y.call(q),this.committedCallIndex=$;for(let T=0;T<this.underlyingCalls.length;T++){if(T===$)continue;if(this.underlyingCalls[T].state==="COMPLETED")continue;this.underlyingCalls[T].state="COMPLETED",this.underlyingCalls[T].call.cancelWithStatus(dT.Status.CANCELLED,"Discarded in favor of other hedged attempt")}this.clearSentMessages()}commitCallWithMostMessages(){if(this.state==="COMMITTED")return;let $=-1,q=-1;for(let[Y,T]of this.underlyingCalls.entries())if(T.state==="ACTIVE"&&T.nextMessageToSend>$)$=T.nextMessageToSend,q=Y;if(q===-1)this.state="TRANSPARENT_ONLY";else this.commitCall(q)}isStatusCodeInList($,q){return $.some((Y)=>{var T;return Y===q||Y.toString().toLowerCase()===((T=dT.Status[q])===null||T===void 0?void 0:T.toLowerCase())})}getNextRetryJitter(){return Math.random()*0.3999999999999999+0.8}getNextRetryBackoffMs(){var $;let q=($=this.callConfig)===null||$===void 0?void 0:$.methodConfig.retryPolicy;if(!q)return 0;let T=this.getNextRetryJitter()*this.nextRetryBackoffSec*1000,X=Number(q.maxBackoff.substring(0,q.maxBackoff.length-1));return this.nextRetryBackoffSec=Math.min(this.nextRetryBackoffSec*q.backoffMultiplier,X),T}maybeRetryCall($,q){if(this.state!=="RETRY"){q(!1);return}if(this.attempts>=this.maxAttempts){q(!1);return}let Y;if($===null)Y=this.getNextRetryBackoffMs();else if($<0){this.state="TRANSPARENT_ONLY",q(!1);return}else Y=$,this.nextRetryBackoffSec=this.initialRetryBackoffSec;setTimeout(()=>{var T,X;if(this.state!=="RETRY"){q(!1);return}if((X=(T=this.retryThrottler)===null||T===void 0?void 0:T.canRetryCall())!==null&&X!==void 0?X:!0)q(!0),this.attempts+=1,this.startNewAttempt();else this.trace("Retry attempt denied by throttling policy"),q(!1)},Y)}countActiveCalls(){let $=0;for(let q of this.underlyingCalls)if((q===null||q===void 0?void 0:q.state)==="ACTIVE")$+=1;return $}handleProcessedStatus($,q,Y){var T,X,J;switch(this.state){case"COMMITTED":case"NO_RETRY":case"TRANSPARENT_ONLY":this.commitCall(q),this.reportStatus($);break;case"HEDGING":if(this.isStatusCodeInList((T=this.callConfig.methodConfig.hedgingPolicy.nonFatalStatusCodes)!==null&&T!==void 0?T:[],$.code)){(X=this.retryThrottler)===null||X===void 0||X.addCallFailed();let Q;if(Y===null)Q=0;else if(Y<0){this.state="TRANSPARENT_ONLY",this.commitCall(q),this.reportStatus($);return}else Q=Y;setTimeout(()=>{if(this.maybeStartHedgingAttempt(),this.countActiveCalls()===0)this.commitCall(q),this.reportStatus($)},Q)}else this.commitCall(q),this.reportStatus($);break;case"RETRY":if(this.isStatusCodeInList(this.callConfig.methodConfig.retryPolicy.retryableStatusCodes,$.code))(J=this.retryThrottler)===null||J===void 0||J.addCallFailed(),this.maybeRetryCall(Y,(Q)=>{if(!Q)this.commitCall(q),this.reportStatus($)});else this.commitCall(q),this.reportStatus($);break}}getPushback($){let q=$.get("grpc-retry-pushback-ms");if(q.length===0)return null;try{return parseInt(q[0])}catch(Y){return-1}}handleChildStatus($,q){var Y;if(this.underlyingCalls[q].state==="COMPLETED")return;if(this.trace("state="+this.state+" handling status with progress "+$.progress+" from child ["+this.underlyingCalls[q].call.getCallNumber()+"] in state "+this.underlyingCalls[q].state),this.underlyingCalls[q].state="COMPLETED",$.code===dT.Status.OK){(Y=this.retryThrottler)===null||Y===void 0||Y.addCallSucceeded(),this.commitCall(q),this.reportStatus($);return}if(this.state==="NO_RETRY"){this.commitCall(q),this.reportStatus($);return}if(this.state==="COMMITTED"){this.reportStatus($);return}let T=this.getPushback($.metadata);switch($.progress){case"NOT_STARTED":this.startNewAttempt();break;case"REFUSED":if(this.transparentRetryUsed)this.handleProcessedStatus($,q,T);else this.transparentRetryUsed=!0,this.startNewAttempt();break;case"DROP":this.commitCall(q),this.reportStatus($);break;case"PROCESSED":this.handleProcessedStatus($,q,T);break}}maybeStartHedgingAttempt(){if(this.state!=="HEDGING")return;if(!this.callConfig.methodConfig.hedgingPolicy)return;if(this.attempts>=this.maxAttempts)return;this.attempts+=1,this.startNewAttempt(),this.maybeStartHedgingTimer()}maybeStartHedgingTimer(){var $,q,Y;if(this.hedgingTimer)clearTimeout(this.hedgingTimer);if(this.state!=="HEDGING")return;if(!this.callConfig.methodConfig.hedgingPolicy)return;let T=this.callConfig.methodConfig.hedgingPolicy;if(this.attempts>=this.maxAttempts)return;let X=($=T.hedgingDelay)!==null&&$!==void 0?$:"0s",J=Number(X.substring(0,X.length-1));this.hedgingTimer=setTimeout(()=>{this.maybeStartHedgingAttempt()},J*1000),(Y=(q=this.hedgingTimer).unref)===null||Y===void 0||Y.call(q)}startNewAttempt(){let $=this.channel.createLoadBalancingCall(this.callConfig,this.methodName,this.host,this.credentials,this.deadline);this.trace("Created child call ["+$.getCallNumber()+"] for attempt "+this.attempts);let q=this.underlyingCalls.length;this.underlyingCalls.push({state:"ACTIVE",call:$,nextMessageToSend:0,startTime:new Date});let Y=this.attempts-1,T=this.initialMetadata.clone();if(Y>0)T.set(RX,`${Y}`);let X=!1;if($.start(T,{onReceiveMetadata:(J)=>{if(this.trace("Received metadata from child ["+$.getCallNumber()+"]"),this.commitCall(q),X=!0,Y>0)J.set(RX,`${Y}`);if(this.underlyingCalls[q].state==="ACTIVE")this.listener.onReceiveMetadata(J)},onReceiveMessage:(J)=>{if(this.trace("Received message from child ["+$.getCallNumber()+"]"),this.commitCall(q),this.underlyingCalls[q].state==="ACTIVE")this.listener.onReceiveMessage(J)},onReceiveStatus:(J)=>{if(this.trace("Received status from child ["+$.getCallNumber()+"]"),!X&&Y>0)J.metadata.set(RX,`${Y}`);this.handleChildStatus(J,q)}}),this.sendNextChildMessage(q),this.readStarted)$.startRead()}start($,q){this.trace("start called"),this.listener=q,this.initialMetadata=$,this.attempts+=1,this.startNewAttempt(),this.maybeStartHedgingTimer()}handleChildWriteCompleted($,q){var Y,T;(T=(Y=this.getBufferEntry(q)).callback)===null||T===void 0||T.call(Y),this.clearSentMessages();let X=this.underlyingCalls[$];X.nextMessageToSend+=1,this.sendNextChildMessage($)}sendNextChildMessage($){let q=this.underlyingCalls[$];if(q.state==="COMPLETED")return;let Y=q.nextMessageToSend;if(this.getBufferEntry(Y)){let T=this.getBufferEntry(Y);switch(T.entryType){case"MESSAGE":if(q.call.sendMessageWithContext({callback:(J)=>{this.handleChildWriteCompleted($,Y)}},T.message.message),this.getBufferEntry(Y+1).entryType==="HALF_CLOSE")this.trace("Sending halfClose immediately after message to child ["+q.call.getCallNumber()+"] - optimizing for unary/final message"),q.nextMessageToSend+=1,q.call.halfClose();break;case"HALF_CLOSE":q.nextMessageToSend+=1,q.call.halfClose();break;case"FREED":break}}}sendMessageWithContext($,q){this.trace("write() called with message of length "+q.length);let Y={message:q,flags:$.flags},T=this.getNextBufferIndex(),X={entryType:"MESSAGE",message:Y,allocated:this.bufferTracker.allocate(q.length,this.callNumber)};if(this.writeBuffer.push(X),X.allocated){process.nextTick(()=>{var J;(J=$.callback)===null||J===void 0||J.call($)});for(let[J,Q]of this.underlyingCalls.entries())if(Q.state==="ACTIVE"&&Q.nextMessageToSend===T)Q.call.sendMessageWithContext({callback:(U)=>{this.handleChildWriteCompleted(J,T)}},q)}else{if(this.commitCallWithMostMessages(),this.committedCallIndex===null)return;let J=this.underlyingCalls[this.committedCallIndex];if(X.callback=$.callback,J.state==="ACTIVE"&&J.nextMessageToSend===T)J.call.sendMessageWithContext({callback:(Q)=>{this.handleChildWriteCompleted(this.committedCallIndex,T)}},q)}}startRead(){this.trace("startRead called"),this.readStarted=!0;for(let $ of this.underlyingCalls)if(($===null||$===void 0?void 0:$.state)==="ACTIVE")$.call.startRead()}halfClose(){this.trace("halfClose called");let $=this.getNextBufferIndex();this.writeBuffer.push({entryType:"HALF_CLOSE",allocated:!1});for(let q of this.underlyingCalls)if((q===null||q===void 0?void 0:q.state)==="ACTIVE"){if(q.nextMessageToSend===$||q.nextMessageToSend===$-1)this.trace("Sending halfClose immediately to child ["+q.call.getCallNumber()+"] - all messages already sent"),q.nextMessageToSend+=1,q.call.halfClose()}}setCredentials($){throw Error("Method not implemented.")}getMethod(){return this.methodName}getHost(){return this.host}getAuthContext(){if(this.committedCallIndex!==null)return this.underlyingCalls[this.committedCallIndex].call.getAuthContext();else return null}}XW.RetryingCall=TW});var nY=B((ZW)=>{Object.defineProperty(ZW,"__esModule",{value:!0});ZW.BaseSubchannelWrapper=void 0;class UW{constructor($){this.child=$,this.healthy=!0,this.healthListeners=new Set,this.refcount=0,this.dataWatchers=new Set,$.addHealthStateWatcher((q)=>{if(this.healthy)this.updateHealthListeners()})}updateHealthListeners(){for(let $ of this.healthListeners)$(this.isHealthy())}getConnectivityState(){return this.child.getConnectivityState()}addConnectivityStateListener($){this.child.addConnectivityStateListener($)}removeConnectivityStateListener($){this.child.removeConnectivityStateListener($)}startConnecting(){this.child.startConnecting()}getAddress(){return this.child.getAddress()}throttleKeepalive($){this.child.throttleKeepalive($)}ref(){this.child.ref(),this.refcount+=1}unref(){if(this.child.unref(),this.refcount-=1,this.refcount===0)this.destroy()}destroy(){for(let $ of this.dataWatchers)$.destroy()}getChannelzRef(){return this.child.getChannelzRef()}isHealthy(){return this.healthy&&this.child.isHealthy()}addHealthStateWatcher($){this.healthListeners.add($)}removeHealthStateWatcher($){this.healthListeners.delete($)}addDataWatcher($){$.setSubchannel(this.getRealSubchannel()),this.dataWatchers.add($)}setHealthy($){if($!==this.healthy){if(this.healthy=$,this.child.isHealthy())this.updateHealthListeners()}}getRealSubchannel(){return this.child.getRealSubchannel()}realSubchannelEquals($){return this.getRealSubchannel()===$.getRealSubchannel()}getCallCredentials(){return this.child.getCallCredentials()}getChannel(){return this.child.getChannel()}}ZW.BaseSubchannelWrapper=UW});var wX=B((DW)=>{Object.defineProperty(DW,"__esModule",{value:!0});DW.InternalChannel=DW.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX=void 0;var lR=Dq(),nR=rQ(),iR=cA(),LX=s1(),rR=P0(),O$=n(),aR=xT(),oR=ZX(),AW=H1(),cT=Z0(),sR=IX(),pT=p0(),A1=l0(),iY=R$(),tR=aA(),eR=jq(),$2=$W(),PX=jT(),q2=fY(),OX=QW(),Y2=nY(),T2=2147483647,X2=1000,J2=1800000,lT=new Map,Q2=16777216,U2=1048576;class WW extends Y2.BaseSubchannelWrapper{constructor($,q){super($);this.channel=q,this.refCount=0,this.subchannelStateListener=(Y,T,X,J)=>{q.throttleKeepalive(J)}}ref(){if(this.refCount===0)this.child.addConnectivityStateListener(this.subchannelStateListener),this.channel.addWrappedSubchannel(this);this.child.ref(),this.refCount+=1}unref(){if(this.child.unref(),this.refCount-=1,this.refCount<=0)this.child.removeConnectivityStateListener(this.subchannelStateListener),this.channel.removeWrappedSubchannel(this)}}class GW{pick($){return{pickResultType:LX.PickResultType.DROP,status:{code:O$.Status.UNAVAILABLE,details:"Channel closed before call started",metadata:new rR.Metadata},subchannel:null,onCallStarted:null,onCallEnded:null}}}DW.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX="grpc.internal.no_subchannel";class EW{constructor($){this.target=$,this.trace=new iY.ChannelzTrace,this.callTracker=new iY.ChannelzCallTracker,this.childrenTracker=new iY.ChannelzChildrenTracker,this.state=A1.ConnectivityState.IDLE}getChannelzInfoCallback(){return()=>{return{target:this.target,state:this.state,trace:this.trace,callTracker:this.callTracker,children:this.childrenTracker.getChildLists()}}}}class VW{constructor($,q,Y){var T,X,J,Q,U,Z;if(this.credentials=q,this.options=Y,this.connectivityState=A1.ConnectivityState.IDLE,this.currentPicker=new LX.UnavailablePicker,this.configSelectionQueue=[],this.pickQueue=[],this.connectivityStateWatchers=[],this.callRefTimer=null,this.configSelector=null,this.currentResolutionError=null,this.wrappedSubchannels=new Set,this.callCount=0,this.idleTimer=null,this.channelzEnabled=!0,this.randomChannelId=Math.floor(Math.random()*Number.MAX_SAFE_INTEGER),typeof $!=="string")throw TypeError("Channel target must be a string");if(!(q instanceof lR.ChannelCredentials))throw TypeError("Channel credentials must be a ChannelCredentials object");if(Y){if(typeof Y!=="object")throw TypeError("Channel options must be an object")}this.channelzInfoTracker=new EW($);let K=(0,pT.parseUri)($);if(K===null)throw Error(`Could not parse target name "${$}"`);let A=(0,AW.mapUriDefaultScheme)(K);if(A===null)throw Error(`Could not find a default scheme for target name "${$}"`);if(this.options["grpc.enable_channelz"]===0)this.channelzEnabled=!1;if(this.channelzRef=(0,iY.registerChannelzChannel)($,this.channelzInfoTracker.getChannelzInfoCallback(),this.channelzEnabled),this.channelzEnabled)this.channelzInfoTracker.trace.addTrace("CT_INFO","Channel created");if(this.options["grpc.default_authority"])this.defaultAuthority=this.options["grpc.default_authority"];else this.defaultAuthority=(0,AW.getDefaultAuthority)(A);let W=(0,sR.mapProxyName)(A,Y);this.target=W.target,this.options=Object.assign({},this.options,W.extraOptions),this.subchannelPool=(0,iR.getSubchannelPool)(((T=this.options["grpc.use_local_subchannel_pool"])!==null&&T!==void 0?T:0)===0),this.retryBufferTracker=new OX.MessageBufferTracker((X=this.options["grpc.retry_buffer_size"])!==null&&X!==void 0?X:Q2,(J=this.options["grpc.per_rpc_retry_buffer_size"])!==null&&J!==void 0?J:U2),this.keepaliveTime=(Q=this.options["grpc.keepalive_time_ms"])!==null&&Q!==void 0?Q:-1,this.idleTimeoutMs=Math.max((U=this.options["grpc.client_idle_timeout_ms"])!==null&&U!==void 0?U:J2,X2);let G={createSubchannel:(F,N)=>{let D={};for(let[v,H]of Object.entries(N))if(!v.startsWith(DW.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX))D[v]=H;let z=this.subchannelPool.getOrCreateSubchannel(this.target,F,D,this.credentials);if(z.throttleKeepalive(this.keepaliveTime),this.channelzEnabled)this.channelzInfoTracker.trace.addTrace("CT_INFO","Created subchannel or used existing subchannel",z.getChannelzRef());return new WW(z,this)},updateState:(F,N)=>{this.currentPicker=N;let D=this.pickQueue.slice();if(this.pickQueue=[],D.length>0)this.callRefTimerUnref();for(let z of D)z.doPick();this.updateState(F)},requestReresolution:()=>{throw Error("Resolving load balancer should never call requestReresolution")},addChannelzChild:(F)=>{if(this.channelzEnabled)this.channelzInfoTracker.childrenTracker.refChild(F)},removeChannelzChild:(F)=>{if(this.channelzEnabled)this.channelzInfoTracker.childrenTracker.unrefChild(F)}};this.resolvingLoadBalancer=new nR.ResolvingLoadBalancer(this.target,G,this.options,(F,N)=>{var D;if(F.retryThrottling)lT.set(this.getTarget(),new OX.RetryThrottler(F.retryThrottling.maxTokens,F.retryThrottling.tokenRatio,lT.get(this.getTarget())));else lT.delete(this.getTarget());if(this.channelzEnabled)this.channelzInfoTracker.trace.addTrace("CT_INFO","Address resolution succeeded");(D=this.configSelector)===null||D===void 0||D.unref(),this.configSelector=N,this.currentResolutionError=null,process.nextTick(()=>{let z=this.configSelectionQueue;if(this.configSelectionQueue=[],z.length>0)this.callRefTimerUnref();for(let S of z)S.getConfig()})},(F)=>{if(this.channelzEnabled)this.channelzInfoTracker.trace.addTrace("CT_WARNING","Address resolution failed with code "+F.code+' and details "'+F.details+'"');if(this.configSelectionQueue.length>0)this.trace("Name resolution failed with calls queued for config selection");if(this.configSelector===null)this.currentResolutionError=Object.assign(Object.assign({},(0,q2.restrictControlPlaneStatusCode)(F.code,F.details)),{metadata:F.metadata});let N=this.configSelectionQueue;if(this.configSelectionQueue=[],N.length>0)this.callRefTimerUnref();for(let D of N)D.reportResolverError(F)}),this.filterStackFactory=new aR.FilterStackFactory([new oR.CompressionFilterFactory(this,this.options)]),this.trace("Channel constructed with options "+JSON.stringify(Y,void 0,2));let V=Error();if((0,cT.isTracerEnabled)("channel_stacktrace"))(0,cT.trace)(O$.LogVerbosity.DEBUG,"channel_stacktrace","("+this.channelzRef.id+`) Channel constructed
20
- `+((Z=V.stack)===null||Z===void 0?void 0:Z.substring(V.stack.indexOf(`
21
- `)+1)));this.lastActivityTimestamp=new Date}trace($,q){(0,cT.trace)(q!==null&&q!==void 0?q:O$.LogVerbosity.DEBUG,"channel","("+this.channelzRef.id+") "+(0,pT.uriToString)(this.target)+" "+$)}callRefTimerRef(){var $,q,Y,T;if(!this.callRefTimer)this.callRefTimer=setInterval(()=>{},T2);if(!((q=($=this.callRefTimer).hasRef)===null||q===void 0?void 0:q.call($)))this.trace("callRefTimer.ref | configSelectionQueue.length="+this.configSelectionQueue.length+" pickQueue.length="+this.pickQueue.length),(T=(Y=this.callRefTimer).ref)===null||T===void 0||T.call(Y)}callRefTimerUnref(){var $,q,Y;if(!(($=this.callRefTimer)===null||$===void 0?void 0:$.hasRef)||this.callRefTimer.hasRef())this.trace("callRefTimer.unref | configSelectionQueue.length="+this.configSelectionQueue.length+" pickQueue.length="+this.pickQueue.length),(Y=(q=this.callRefTimer)===null||q===void 0?void 0:q.unref)===null||Y===void 0||Y.call(q)}removeConnectivityStateWatcher($){let q=this.connectivityStateWatchers.findIndex((Y)=>Y===$);if(q>=0)this.connectivityStateWatchers.splice(q,1)}updateState($){if((0,cT.trace)(O$.LogVerbosity.DEBUG,"connectivity_state","("+this.channelzRef.id+") "+(0,pT.uriToString)(this.target)+" "+A1.ConnectivityState[this.connectivityState]+" -> "+A1.ConnectivityState[$]),this.channelzEnabled)this.channelzInfoTracker.trace.addTrace("CT_INFO","Connectivity state change to "+A1.ConnectivityState[$]);this.connectivityState=$,this.channelzInfoTracker.state=$;let q=this.connectivityStateWatchers.slice();for(let Y of q)if($!==Y.currentState){if(Y.timer)clearTimeout(Y.timer);this.removeConnectivityStateWatcher(Y),Y.callback()}if($!==A1.ConnectivityState.TRANSIENT_FAILURE)this.currentResolutionError=null}throttleKeepalive($){if($>this.keepaliveTime){this.keepaliveTime=$;for(let q of this.wrappedSubchannels)q.throttleKeepalive($)}}addWrappedSubchannel($){this.wrappedSubchannels.add($)}removeWrappedSubchannel($){this.wrappedSubchannels.delete($)}doPick($,q){return this.currentPicker.pick({metadata:$,extraPickInfo:q})}queueCallForPick($){this.pickQueue.push($),this.callRefTimerRef()}getConfig($,q){if(this.connectivityState!==A1.ConnectivityState.SHUTDOWN)this.resolvingLoadBalancer.exitIdle();if(this.configSelector)return{type:"SUCCESS",config:this.configSelector.invoke($,q,this.randomChannelId)};else if(this.currentResolutionError)return{type:"ERROR",error:this.currentResolutionError};else return{type:"NONE"}}queueCallForConfig($){this.configSelectionQueue.push($),this.callRefTimerRef()}enterIdle(){if(this.resolvingLoadBalancer.destroy(),this.updateState(A1.ConnectivityState.IDLE),this.currentPicker=new LX.QueuePicker(this.resolvingLoadBalancer),this.idleTimer)clearTimeout(this.idleTimer),this.idleTimer=null;if(this.callRefTimer)clearInterval(this.callRefTimer),this.callRefTimer=null}startIdleTimeout($){var q,Y;this.idleTimer=setTimeout(()=>{if(this.callCount>0){this.startIdleTimeout(this.idleTimeoutMs);return}let X=new Date().valueOf()-this.lastActivityTimestamp.valueOf();if(X>=this.idleTimeoutMs)this.trace("Idle timer triggered after "+this.idleTimeoutMs+"ms of inactivity"),this.enterIdle();else this.startIdleTimeout(this.idleTimeoutMs-X)},$),(Y=(q=this.idleTimer).unref)===null||Y===void 0||Y.call(q)}maybeStartIdleTimer(){if(this.connectivityState!==A1.ConnectivityState.SHUTDOWN&&!this.idleTimer)this.startIdleTimeout(this.idleTimeoutMs)}onCallStart(){if(this.channelzEnabled)this.channelzInfoTracker.callTracker.addCallStarted();this.callCount+=1}onCallEnd($){if(this.channelzEnabled)if($.code===O$.Status.OK)this.channelzInfoTracker.callTracker.addCallSucceeded();else this.channelzInfoTracker.callTracker.addCallFailed();this.callCount-=1,this.lastActivityTimestamp=new Date,this.maybeStartIdleTimer()}createLoadBalancingCall($,q,Y,T,X){let J=(0,PX.getNextCallNumber)();return this.trace("createLoadBalancingCall ["+J+'] method="'+q+'"'),new tR.LoadBalancingCall(this,$,q,Y,T,X,J)}createRetryingCall($,q,Y,T,X){let J=(0,PX.getNextCallNumber)();return this.trace("createRetryingCall ["+J+'] method="'+q+'"'),new OX.RetryingCall(this,$,q,Y,T,X,J,this.retryBufferTracker,lT.get(this.getTarget()))}createResolvingCall($,q,Y,T,X){let J=(0,PX.getNextCallNumber)();this.trace("createResolvingCall ["+J+'] method="'+$+'", deadline='+(0,eR.deadlineToString)(q));let Q={deadline:q,flags:X!==null&&X!==void 0?X:O$.Propagate.DEFAULTS,host:Y!==null&&Y!==void 0?Y:this.defaultAuthority,parentCall:T},U=new $2.ResolvingCall(this,$,Q,this.filterStackFactory.clone(),J);return this.onCallStart(),U.addStatusWatcher((Z)=>{this.onCallEnd(Z)}),U}close(){var $;this.resolvingLoadBalancer.destroy(),this.updateState(A1.ConnectivityState.SHUTDOWN),this.currentPicker=new GW;for(let q of this.configSelectionQueue)q.cancelWithStatus(O$.Status.UNAVAILABLE,"Channel closed before call started");this.configSelectionQueue=[];for(let q of this.pickQueue)q.cancelWithStatus(O$.Status.UNAVAILABLE,"Channel closed before call started");if(this.pickQueue=[],this.callRefTimer)clearInterval(this.callRefTimer);if(this.idleTimer)clearTimeout(this.idleTimer);if(this.channelzEnabled)(0,iY.unregisterChannelzRef)(this.channelzRef);this.subchannelPool.unrefUnusedSubchannels(),($=this.configSelector)===null||$===void 0||$.unref(),this.configSelector=null}getTarget(){return(0,pT.uriToString)(this.target)}getConnectivityState($){let q=this.connectivityState;if($)this.resolvingLoadBalancer.exitIdle(),this.lastActivityTimestamp=new Date,this.maybeStartIdleTimer();return q}watchConnectivityState($,q,Y){if(this.connectivityState===A1.ConnectivityState.SHUTDOWN)throw Error("Channel has been shut down");let T=null;if(q!==1/0){let J=q instanceof Date?q:new Date(q),Q=new Date;if(q===-1/0||J<=Q){process.nextTick(Y,Error("Deadline passed without connectivity state change"));return}T=setTimeout(()=>{this.removeConnectivityStateWatcher(X),Y(Error("Deadline passed without connectivity state change"))},J.getTime()-Q.getTime())}let X={currentState:$,callback:Y,timer:T};this.connectivityStateWatchers.push(X)}getChannelzRef(){return this.channelzRef}createCall($,q,Y,T,X){if(typeof $!=="string")throw TypeError("Channel#createCall: method must be a string");if(!(typeof q==="number"||q instanceof Date))throw TypeError("Channel#createCall: deadline must be a number or Date");if(this.connectivityState===A1.ConnectivityState.SHUTDOWN)throw Error("Channel has been shut down");return this.createResolvingCall($,q,Y,T,X)}getOptions(){return this.options}}DW.InternalChannel=VW});var n9=B((HW)=>{Object.defineProperty(HW,"__esModule",{value:!0});HW.ChannelImplementation=void 0;var Z2=Dq(),K2=wX();class NW{constructor($,q,Y){if(typeof $!=="string")throw TypeError("Channel target must be a string");if(!(q instanceof Z2.ChannelCredentials))throw TypeError("Channel credentials must be a ChannelCredentials object");if(Y){if(typeof Y!=="object")throw TypeError("Channel options must be an object")}this.internalChannel=new K2.InternalChannel($,q,Y)}close(){this.internalChannel.close()}getTarget(){return this.internalChannel.getTarget()}getConnectivityState($){return this.internalChannel.getConnectivityState($)}watchConnectivityState($,q,Y){this.internalChannel.watchConnectivityState($,q,Y)}getChannelzRef(){return this.internalChannel.getChannelzRef()}createCall($,q,Y,T,X){if(typeof $!=="string")throw TypeError("Channel#createCall: method must be a string");if(!(typeof q==="number"||q instanceof Date))throw TypeError("Channel#createCall: deadline must be a number or Date");return this.internalChannel.createCall($,q,Y,T,X)}}HW.ChannelImplementation=NW});var SW=B((LW)=>{Object.defineProperty(LW,"__esModule",{value:!0});LW.ServerDuplexStreamImpl=LW.ServerWritableStreamImpl=LW.ServerReadableStreamImpl=LW.ServerUnaryCallImpl=void 0;LW.serverErrorToStatus=yX;var A2=e("events"),SX=e("stream"),CX=n(),MW=P0();function yX($,q){var Y;let T={code:CX.Status.UNKNOWN,details:"message"in $?$.message:"Unknown Error",metadata:(Y=q!==null&&q!==void 0?q:$.metadata)!==null&&Y!==void 0?Y:null};if("code"in $&&typeof $.code==="number"&&Number.isInteger($.code)){if(T.code=$.code,"details"in $&&typeof $.details==="string")T.details=$.details}return T}class BW extends A2.EventEmitter{constructor($,q,Y,T){super();this.path=$,this.call=q,this.metadata=Y,this.request=T,this.cancelled=!1}getPeer(){return this.call.getPeer()}sendMetadata($){this.call.sendMetadata($)}getDeadline(){return this.call.getDeadline()}getPath(){return this.path}getHost(){return this.call.getHost()}getAuthContext(){return this.call.getAuthContext()}getMetricsRecorder(){return this.call.getMetricsRecorder()}}LW.ServerUnaryCallImpl=BW;class RW extends SX.Readable{constructor($,q,Y){super({objectMode:!0});this.path=$,this.call=q,this.metadata=Y,this.cancelled=!1}_read($){this.call.startRead()}getPeer(){return this.call.getPeer()}sendMetadata($){this.call.sendMetadata($)}getDeadline(){return this.call.getDeadline()}getPath(){return this.path}getHost(){return this.call.getHost()}getAuthContext(){return this.call.getAuthContext()}getMetricsRecorder(){return this.call.getMetricsRecorder()}}LW.ServerReadableStreamImpl=RW;class PW extends SX.Writable{constructor($,q,Y,T){super({objectMode:!0});this.path=$,this.call=q,this.metadata=Y,this.request=T,this.pendingStatus={code:CX.Status.OK,details:"OK"},this.cancelled=!1,this.trailingMetadata=new MW.Metadata,this.on("error",(X)=>{this.pendingStatus=yX(X),this.end()})}getPeer(){return this.call.getPeer()}sendMetadata($){this.call.sendMetadata($)}getDeadline(){return this.call.getDeadline()}getPath(){return this.path}getHost(){return this.call.getHost()}getAuthContext(){return this.call.getAuthContext()}getMetricsRecorder(){return this.call.getMetricsRecorder()}_write($,q,Y){this.call.sendMessage($,Y)}_final($){var q;$(null),this.call.sendStatus(Object.assign(Object.assign({},this.pendingStatus),{metadata:(q=this.pendingStatus.metadata)!==null&&q!==void 0?q:this.trailingMetadata}))}end($){if($)this.trailingMetadata=$;return super.end()}}LW.ServerWritableStreamImpl=PW;class OW extends SX.Duplex{constructor($,q,Y){super({objectMode:!0});this.path=$,this.call=q,this.metadata=Y,this.pendingStatus={code:CX.Status.OK,details:"OK"},this.cancelled=!1,this.trailingMetadata=new MW.Metadata,this.on("error",(T)=>{this.pendingStatus=yX(T),this.end()})}getPeer(){return this.call.getPeer()}sendMetadata($){this.call.sendMetadata($)}getDeadline(){return this.call.getDeadline()}getPath(){return this.path}getHost(){return this.call.getHost()}getAuthContext(){return this.call.getAuthContext()}getMetricsRecorder(){return this.call.getMetricsRecorder()}_read($){this.call.startRead()}_write($,q,Y){this.call.sendMessage($,Y)}_final($){var q;$(null),this.call.sendStatus(Object.assign(Object.assign({},this.pendingStatus),{metadata:(q=this.pendingStatus.metadata)!==null&&q!==void 0?q:this.trailingMetadata}))}end($){if($)this.trailingMetadata=$;return super.end()}}LW.ServerDuplexStreamImpl=OW});var nT=B((CW)=>{Object.defineProperty(CW,"__esModule",{value:!0});CW.ServerCredentials=void 0;CW.createCertificateProviderServerCredentials=D2;CW.createServerCredentialsWithInterceptors=F2;var jX=j9();class _q{constructor($,q){this.serverConstructorOptions=$,this.watchers=new Set,this.latestContextOptions=null,this.latestContextOptions=q!==null&&q!==void 0?q:null}_addWatcher($){this.watchers.add($)}_removeWatcher($){this.watchers.delete($)}getWatcherCount(){return this.watchers.size}updateSecureContextOptions($){this.latestContextOptions=$;for(let q of this.watchers)q(this.latestContextOptions)}_isSecure(){return this.serverConstructorOptions!==null}_getSecureContextOptions(){return this.latestContextOptions}_getConstructorOptions(){return this.serverConstructorOptions}_getInterceptors(){return[]}static createInsecure(){return new vX}static createSsl($,q,Y=!1){var T;if($!==null&&!Buffer.isBuffer($))throw TypeError("rootCerts must be null or a Buffer");if(!Array.isArray(q))throw TypeError("keyCertPairs must be an array");if(typeof Y!=="boolean")throw TypeError("checkClientCertificate must be a boolean");let X=[],J=[];for(let Q=0;Q<q.length;Q++){let U=q[Q];if(U===null||typeof U!=="object")throw TypeError(`keyCertPair[${Q}] must be an object`);if(!Buffer.isBuffer(U.private_key))throw TypeError(`keyCertPair[${Q}].private_key must be a Buffer`);if(!Buffer.isBuffer(U.cert_chain))throw TypeError(`keyCertPair[${Q}].cert_chain must be a Buffer`);X.push(U.cert_chain),J.push(U.private_key)}return new xX({requestCert:Y,ciphers:jX.CIPHER_SUITES},{ca:(T=$!==null&&$!==void 0?$:(0,jX.getDefaultRootsData)())!==null&&T!==void 0?T:void 0,cert:X,key:J})}}CW.ServerCredentials=_q;class vX extends _q{constructor(){super(null)}_getSettings(){return null}_equals($){return $ instanceof vX}}class xX extends _q{constructor($,q){super($,q);this.options=Object.assign(Object.assign({},$),q)}_equals($){if(this===$)return!0;if(!($ instanceof xX))return!1;if(Buffer.isBuffer(this.options.ca)&&Buffer.isBuffer($.options.ca)){if(!this.options.ca.equals($.options.ca))return!1}else if(this.options.ca!==$.options.ca)return!1;if(Array.isArray(this.options.cert)&&Array.isArray($.options.cert)){if(this.options.cert.length!==$.options.cert.length)return!1;for(let q=0;q<this.options.cert.length;q++){let Y=this.options.cert[q],T=$.options.cert[q];if(Buffer.isBuffer(Y)&&Buffer.isBuffer(T)){if(!Y.equals(T))return!1}else if(Y!==T)return!1}}else if(this.options.cert!==$.options.cert)return!1;if(Array.isArray(this.options.key)&&Array.isArray($.options.key)){if(this.options.key.length!==$.options.key.length)return!1;for(let q=0;q<this.options.key.length;q++){let Y=this.options.key[q],T=$.options.key[q];if(Buffer.isBuffer(Y)&&Buffer.isBuffer(T)){if(!Y.equals(T))return!1}else if(Y!==T)return!1}}else if(this.options.key!==$.options.key)return!1;if(this.options.requestCert!==$.options.requestCert)return!1;return!0}}class kX extends _q{constructor($,q,Y){super({requestCert:q!==null,rejectUnauthorized:Y,ciphers:jX.CIPHER_SUITES});this.identityCertificateProvider=$,this.caCertificateProvider=q,this.requireClientCertificate=Y,this.latestCaUpdate=null,this.latestIdentityUpdate=null,this.caCertificateUpdateListener=this.handleCaCertificateUpdate.bind(this),this.identityCertificateUpdateListener=this.handleIdentityCertitificateUpdate.bind(this)}_addWatcher($){var q;if(this.getWatcherCount()===0)(q=this.caCertificateProvider)===null||q===void 0||q.addCaCertificateListener(this.caCertificateUpdateListener),this.identityCertificateProvider.addIdentityCertificateListener(this.identityCertificateUpdateListener);super._addWatcher($)}_removeWatcher($){var q;if(super._removeWatcher($),this.getWatcherCount()===0)(q=this.caCertificateProvider)===null||q===void 0||q.removeCaCertificateListener(this.caCertificateUpdateListener),this.identityCertificateProvider.removeIdentityCertificateListener(this.identityCertificateUpdateListener)}_equals($){if(this===$)return!0;if(!($ instanceof kX))return!1;return this.caCertificateProvider===$.caCertificateProvider&&this.identityCertificateProvider===$.identityCertificateProvider&&this.requireClientCertificate===$.requireClientCertificate}calculateSecureContextOptions(){var $;if(this.latestIdentityUpdate===null)return null;if(this.caCertificateProvider!==null&&this.latestCaUpdate===null)return null;return{ca:($=this.latestCaUpdate)===null||$===void 0?void 0:$.caCertificate,cert:[this.latestIdentityUpdate.certificate],key:[this.latestIdentityUpdate.privateKey]}}finalizeUpdate(){let $=this.calculateSecureContextOptions();this.updateSecureContextOptions($)}handleCaCertificateUpdate($){this.latestCaUpdate=$,this.finalizeUpdate()}handleIdentityCertitificateUpdate($){this.latestIdentityUpdate=$,this.finalizeUpdate()}}function D2($,q,Y){return new kX($,q,Y)}class hX extends _q{constructor($,q){super({});this.childCredentials=$,this.interceptors=q}_isSecure(){return this.childCredentials._isSecure()}_equals($){if(!($ instanceof hX))return!1;if(!this.childCredentials._equals($.childCredentials))return!1;if(this.interceptors.length!==$.interceptors.length)return!1;for(let q=0;q<this.interceptors.length;q++)if(this.interceptors[q]!==$.interceptors[q])return!1;return!0}_getInterceptors(){return this.interceptors}_addWatcher($){this.childCredentials._addWatcher($)}_removeWatcher($){this.childCredentials._removeWatcher($)}_getConstructorOptions(){return this.childCredentials._getConstructorOptions()}_getSecureContextOptions(){return this.childCredentials._getSecureContextOptions()}}function F2($,q){return new hX($,q)}});var rY=B((jW)=>{Object.defineProperty(jW,"__esModule",{value:!0});jW.durationMessageToDuration=H2;jW.msToDuration=z2;jW.durationToMs=M2;jW.isDuration=B2;jW.isDurationMessage=R2;jW.parseDuration=O2;jW.durationToString=L2;function H2($){return{seconds:Number.parseInt($.seconds),nanos:$.nanos}}function z2($){return{seconds:$/1000|0,nanos:$%1000*1e6|0}}function M2($){return $.seconds*1000+$.nanos/1e6|0}function B2($){return typeof $.seconds==="number"&&typeof $.nanos==="number"}function R2($){return typeof $.seconds==="string"&&typeof $.nanos==="number"}var P2=/^(\d+)(?:\.(\d+))?s$/;function O2($){let q=$.match(P2);if(!q)return null;return{seconds:Number.parseInt(q[1],10),nanos:q[2]?Number.parseInt(q[2].padEnd(9,"0"),10):0}}function L2($){if($.nanos===0)return`${$.seconds}s`;let q;if($.nanos%1e6===0)q=1e6;else if($.nanos%1000===0)q=1000;else q=1;return`${$.seconds}.${$.nanos/q}s`}});var rT=B((dW)=>{var __dirname="/Users/beatrix/dev/cline-packages/node_modules/.bun/@grpc+grpc-js@1.14.3/node_modules/@grpc/grpc-js/build/src";Object.defineProperty(dW,"__esModule",{value:!0});dW.OrcaOobMetricsSubchannelWrapper=dW.GRPC_METRICS_HEADER=dW.ServerMetricRecorder=dW.PerRequestMetricRecorder=void 0;dW.createOrcaClient=gW;dW.createMetricsReader=b2;var k2=o6(),_X=rY(),h2=Dq(),_2=nY(),vW=n(),g2=Fq(),m2=l0(),xW=null;function iT(){if(xW)return xW;let $=hY().loadSync,q=$("xds/service/orca/v3/orca.proto",{keepCase:!0,longs:String,enums:String,defaults:!0,oneofs:!0,includeDirs:[`${__dirname}/../../proto/xds`,`${__dirname}/../../proto/protoc-gen-validate`]});return(0,k2.loadPackageDefinition)(q)}class hW{constructor(){this.message={}}recordRequestCostMetric($,q){if(!this.message.request_cost)this.message.request_cost={};this.message.request_cost[$]=q}recordUtilizationMetric($,q){if(!this.message.utilization)this.message.utilization={};this.message.utilization[$]=q}recordNamedMetric($,q){if(!this.message.named_metrics)this.message.named_metrics={};this.message.named_metrics[$]=q}recordCPUUtilizationMetric($){this.message.cpu_utilization=$}recordMemoryUtilizationMetric($){this.message.mem_utilization=$}recordApplicationUtilizationMetric($){this.message.application_utilization=$}recordQpsMetric($){this.message.rps_fractional=$}recordEpsMetric($){this.message.eps=$}serialize(){return iT().xds.data.orca.v3.OrcaLoadReport.serialize(this.message)}}dW.PerRequestMetricRecorder=hW;var f2=30000;class _W{constructor(){this.message={},this.serviceImplementation={StreamCoreMetrics:($)=>{let q=$.request.report_interval?(0,_X.durationToMs)((0,_X.durationMessageToDuration)($.request.report_interval)):f2,Y=setInterval(()=>{$.write(this.message)},q);$.on("cancelled",()=>{clearInterval(Y)})}}}putUtilizationMetric($,q){if(!this.message.utilization)this.message.utilization={};this.message.utilization[$]=q}setAllUtilizationMetrics($){this.message.utilization=Object.assign({},$)}deleteUtilizationMetric($){var q;(q=this.message.utilization)===null||q===void 0||delete q[$]}setCpuUtilizationMetric($){this.message.cpu_utilization=$}deleteCpuUtilizationMetric(){delete this.message.cpu_utilization}setApplicationUtilizationMetric($){this.message.application_utilization=$}deleteApplicationUtilizationMetric(){delete this.message.application_utilization}setQpsMetric($){this.message.rps_fractional=$}deleteQpsMetric(){delete this.message.rps_fractional}setEpsMetric($){this.message.eps=$}deleteEpsMetric(){delete this.message.eps}addToServer($){let q=iT().xds.service.orca.v3.OpenRcaService.service;$.addService(q,this.serviceImplementation)}}dW.ServerMetricRecorder=_W;function gW($){return new(iT()).xds.service.orca.v3.OpenRcaService("unused",h2.ChannelCredentials.createInsecure(),{channelOverride:$})}dW.GRPC_METRICS_HEADER="endpoint-load-metrics-bin";var kW="grpc_orca_load_report";function b2($,q){return(Y,T,X)=>{let J=X.getOpaque(kW);if(J)$(J);else{let Q=X.get(dW.GRPC_METRICS_HEADER);if(Q.length>0)J=iT().xds.data.orca.v3.OrcaLoadReport.deserialize(Q[0]),$(J),X.setOpaque(kW,J)}if(q)q(Y,T,X)}}var mW="orca_oob_metrics";class fW{constructor($,q){this.metricsListener=$,this.intervalMs=q,this.dataProducer=null}setSubchannel($){let q=$.getOrCreateDataProducer(mW,u2);this.dataProducer=q,q.addDataWatcher(this)}destroy(){var $;($=this.dataProducer)===null||$===void 0||$.removeDataWatcher(this)}getInterval(){return this.intervalMs}onMetricsUpdate($){this.metricsListener($)}}class bW{constructor($){this.subchannel=$,this.dataWatchers=new Set,this.orcaSupported=!0,this.metricsCall=null,this.currentInterval=1/0,this.backoffTimer=new g2.BackoffTimeout(()=>this.updateMetricsSubscription()),this.subchannelStateListener=()=>this.updateMetricsSubscription();let q=$.getChannel();this.client=gW(q),$.addConnectivityStateListener(this.subchannelStateListener)}addDataWatcher($){this.dataWatchers.add($),this.updateMetricsSubscription()}removeDataWatcher($){var q;if(this.dataWatchers.delete($),this.dataWatchers.size===0)this.subchannel.removeDataProducer(mW),(q=this.metricsCall)===null||q===void 0||q.cancel(),this.metricsCall=null,this.client.close(),this.subchannel.removeConnectivityStateListener(this.subchannelStateListener);else this.updateMetricsSubscription()}updateMetricsSubscription(){var $;if(this.dataWatchers.size===0||!this.orcaSupported||this.subchannel.getConnectivityState()!==m2.ConnectivityState.READY)return;let q=Math.min(...Array.from(this.dataWatchers).map((Y)=>Y.getInterval()));if(!this.metricsCall||q!==this.currentInterval){($=this.metricsCall)===null||$===void 0||$.cancel(),this.currentInterval=q;let Y=this.client.streamCoreMetrics({report_interval:(0,_X.msToDuration)(q)});this.metricsCall=Y,Y.on("data",(T)=>{this.dataWatchers.forEach((X)=>{X.onMetricsUpdate(T)})}),Y.on("error",(T)=>{if(this.metricsCall=null,T.code===vW.Status.UNIMPLEMENTED){this.orcaSupported=!1;return}if(T.code===vW.Status.CANCELLED)return;this.backoffTimer.runOnce()})}}}class uW extends _2.BaseSubchannelWrapper{constructor($,q,Y){super($);this.addDataWatcher(new fW(q,Y))}getWrappedSubchannel(){return this.child}}dW.OrcaOobMetricsSubchannelWrapper=uW;function u2($){return new bW($)}});var bX=B((XG)=>{Object.defineProperty(XG,"__esModule",{value:!0});XG.BaseServerInterceptingCall=XG.ServerInterceptingCall=XG.ResponderBuilder=XG.ServerListenerBuilder=void 0;XG.isInterceptingServerListener=r2;XG.getServerInterceptingCall=e2;var sT=P0(),a0=n(),gq=e("http2"),lW=k6(),nW=e("zlib"),n2=NX(),sW=Z0(),i2=e("tls"),iW=rT(),tW="server_call";function o$($){sW.trace(a0.LogVerbosity.DEBUG,tW,$)}class eW{constructor(){this.metadata=void 0,this.message=void 0,this.halfClose=void 0,this.cancel=void 0}withOnReceiveMetadata($){return this.metadata=$,this}withOnReceiveMessage($){return this.message=$,this}withOnReceiveHalfClose($){return this.halfClose=$,this}withOnCancel($){return this.cancel=$,this}build(){return{onReceiveMetadata:this.metadata,onReceiveMessage:this.message,onReceiveHalfClose:this.halfClose,onCancel:this.cancel}}}XG.ServerListenerBuilder=eW;function r2($){return $.onReceiveMetadata!==void 0&&$.onReceiveMetadata.length===1}class $G{constructor($,q){this.listener=$,this.nextListener=q,this.cancelled=!1,this.processingMetadata=!1,this.hasPendingMessage=!1,this.pendingMessage=null,this.processingMessage=!1,this.hasPendingHalfClose=!1}processPendingMessage(){if(this.hasPendingMessage)this.nextListener.onReceiveMessage(this.pendingMessage),this.pendingMessage=null,this.hasPendingMessage=!1}processPendingHalfClose(){if(this.hasPendingHalfClose)this.nextListener.onReceiveHalfClose(),this.hasPendingHalfClose=!1}onReceiveMetadata($){if(this.cancelled)return;this.processingMetadata=!0,this.listener.onReceiveMetadata($,(q)=>{if(this.processingMetadata=!1,this.cancelled)return;this.nextListener.onReceiveMetadata(q),this.processPendingMessage(),this.processPendingHalfClose()})}onReceiveMessage($){if(this.cancelled)return;this.processingMessage=!0,this.listener.onReceiveMessage($,(q)=>{if(this.processingMessage=!1,this.cancelled)return;if(this.processingMetadata)this.pendingMessage=q,this.hasPendingMessage=!0;else this.nextListener.onReceiveMessage(q),this.processPendingHalfClose()})}onReceiveHalfClose(){if(this.cancelled)return;this.listener.onReceiveHalfClose(()=>{if(this.cancelled)return;if(this.processingMetadata||this.processingMessage)this.hasPendingHalfClose=!0;else this.nextListener.onReceiveHalfClose()})}onCancel(){this.cancelled=!0,this.listener.onCancel(),this.nextListener.onCancel()}}class qG{constructor(){this.start=void 0,this.metadata=void 0,this.message=void 0,this.status=void 0}withStart($){return this.start=$,this}withSendMetadata($){return this.metadata=$,this}withSendMessage($){return this.message=$,this}withSendStatus($){return this.status=$,this}build(){return{start:this.start,sendMetadata:this.metadata,sendMessage:this.message,sendStatus:this.status}}}XG.ResponderBuilder=qG;var aT={onReceiveMetadata:($,q)=>{q($)},onReceiveMessage:($,q)=>{q($)},onReceiveHalfClose:($)=>{$()},onCancel:()=>{}},oT={start:($)=>{$()},sendMetadata:($,q)=>{q($)},sendMessage:($,q)=>{q($)},sendStatus:($,q)=>{q($)}};class YG{constructor($,q){var Y,T,X,J;this.nextCall=$,this.processingMetadata=!1,this.sentMetadata=!1,this.processingMessage=!1,this.pendingMessage=null,this.pendingMessageCallback=null,this.pendingStatus=null,this.responder={start:(Y=q===null||q===void 0?void 0:q.start)!==null&&Y!==void 0?Y:oT.start,sendMetadata:(T=q===null||q===void 0?void 0:q.sendMetadata)!==null&&T!==void 0?T:oT.sendMetadata,sendMessage:(X=q===null||q===void 0?void 0:q.sendMessage)!==null&&X!==void 0?X:oT.sendMessage,sendStatus:(J=q===null||q===void 0?void 0:q.sendStatus)!==null&&J!==void 0?J:oT.sendStatus}}processPendingMessage(){if(this.pendingMessageCallback)this.nextCall.sendMessage(this.pendingMessage,this.pendingMessageCallback),this.pendingMessage=null,this.pendingMessageCallback=null}processPendingStatus(){if(this.pendingStatus)this.nextCall.sendStatus(this.pendingStatus),this.pendingStatus=null}start($){this.responder.start((q)=>{var Y,T,X,J;let Q={onReceiveMetadata:(Y=q===null||q===void 0?void 0:q.onReceiveMetadata)!==null&&Y!==void 0?Y:aT.onReceiveMetadata,onReceiveMessage:(T=q===null||q===void 0?void 0:q.onReceiveMessage)!==null&&T!==void 0?T:aT.onReceiveMessage,onReceiveHalfClose:(X=q===null||q===void 0?void 0:q.onReceiveHalfClose)!==null&&X!==void 0?X:aT.onReceiveHalfClose,onCancel:(J=q===null||q===void 0?void 0:q.onCancel)!==null&&J!==void 0?J:aT.onCancel},U=new $G(Q,$);this.nextCall.start(U)})}sendMetadata($){this.processingMetadata=!0,this.sentMetadata=!0,this.responder.sendMetadata($,(q)=>{this.processingMetadata=!1,this.nextCall.sendMetadata(q),this.processPendingMessage(),this.processPendingStatus()})}sendMessage($,q){if(this.processingMessage=!0,!this.sentMetadata)this.sendMetadata(new sT.Metadata);this.responder.sendMessage($,(Y)=>{if(this.processingMessage=!1,this.processingMetadata)this.pendingMessage=Y,this.pendingMessageCallback=q;else this.nextCall.sendMessage(Y,q)})}sendStatus($){this.responder.sendStatus($,(q)=>{if(this.processingMetadata||this.processingMessage)this.pendingStatus=q;else this.nextCall.sendStatus(q)})}startRead(){this.nextCall.startRead()}getPeer(){return this.nextCall.getPeer()}getDeadline(){return this.nextCall.getDeadline()}getHost(){return this.nextCall.getHost()}getAuthContext(){return this.nextCall.getAuthContext()}getConnectionInfo(){return this.nextCall.getConnectionInfo()}getMetricsRecorder(){return this.nextCall.getMetricsRecorder()}}XG.ServerInterceptingCall=YG;var TG="grpc-accept-encoding",mX="grpc-encoding",rW="grpc-message",aW="grpc-status",gX="grpc-timeout",a2=/(\d{1,8})\s*([HMSmun])/,o2={H:3600000,M:60000,S:1000,m:1,u:0.001,n:0.000001},s2={[TG]:"identity,deflate,gzip",[mX]:"identity"},oW={[gq.constants.HTTP2_HEADER_STATUS]:gq.constants.HTTP_STATUS_OK,[gq.constants.HTTP2_HEADER_CONTENT_TYPE]:"application/grpc+proto"},t2={waitForTrailers:!0};class fX{constructor($,q,Y,T,X){var J,Q;if(this.stream=$,this.callEventTracker=Y,this.handler=T,this.listener=null,this.deadlineTimer=null,this.deadline=1/0,this.maxSendMessageSize=a0.DEFAULT_MAX_SEND_MESSAGE_LENGTH,this.maxReceiveMessageSize=a0.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH,this.cancelled=!1,this.metadataSent=!1,this.wantTrailers=!1,this.cancelNotified=!1,this.incomingEncoding="identity",this.readQueue=[],this.isReadPending=!1,this.receivedHalfClose=!1,this.streamEnded=!1,this.metricsRecorder=new iW.PerRequestMetricRecorder,this.stream.once("error",(W)=>{}),this.stream.once("close",()=>{var W;if(o$("Request to method "+((W=this.handler)===null||W===void 0?void 0:W.path)+" stream closed with rstCode "+this.stream.rstCode),this.callEventTracker&&!this.streamEnded)this.streamEnded=!0,this.callEventTracker.onStreamEnd(!1),this.callEventTracker.onCallEnd({code:a0.Status.CANCELLED,details:"Stream closed before sending status",metadata:null});this.notifyOnCancel()}),this.stream.on("data",(W)=>{this.handleDataFrame(W)}),this.stream.pause(),this.stream.on("end",()=>{this.handleEndEvent()}),"grpc.max_send_message_length"in X)this.maxSendMessageSize=X["grpc.max_send_message_length"];if("grpc.max_receive_message_length"in X)this.maxReceiveMessageSize=X["grpc.max_receive_message_length"];this.host=(J=q[":authority"])!==null&&J!==void 0?J:q.host,this.decoder=new n2.StreamDecoder(this.maxReceiveMessageSize);let U=sT.Metadata.fromHttp2Headers(q);if(sW.isTracerEnabled(tW))o$("Request to "+this.handler.path+" received headers "+JSON.stringify(U.toJSON()));let Z=U.get(gX);if(Z.length>0)this.handleTimeoutHeader(Z[0]);let K=U.get(mX);if(K.length>0)this.incomingEncoding=K[0];U.remove(gX),U.remove(mX),U.remove(TG),U.remove(gq.constants.HTTP2_HEADER_ACCEPT_ENCODING),U.remove(gq.constants.HTTP2_HEADER_TE),U.remove(gq.constants.HTTP2_HEADER_CONTENT_TYPE),this.metadata=U;let A=(Q=$.session)===null||Q===void 0?void 0:Q.socket;this.connectionInfo={localAddress:A===null||A===void 0?void 0:A.localAddress,localPort:A===null||A===void 0?void 0:A.localPort,remoteAddress:A===null||A===void 0?void 0:A.remoteAddress,remotePort:A===null||A===void 0?void 0:A.remotePort},this.shouldSendMetrics=!!X["grpc.server_call_metric_recording"]}handleTimeoutHeader($){let q=$.toString().match(a2);if(q===null){let X={code:a0.Status.INTERNAL,details:`Invalid ${gX} value "${$}"`,metadata:null};process.nextTick(()=>{this.sendStatus(X)});return}let Y=+q[1]*o2[q[2]]|0,T=new Date;this.deadline=T.setMilliseconds(T.getMilliseconds()+Y),this.deadlineTimer=setTimeout(()=>{let X={code:a0.Status.DEADLINE_EXCEEDED,details:"Deadline exceeded",metadata:null};this.sendStatus(X)},Y)}checkCancelled(){if(!this.cancelled&&(this.stream.destroyed||this.stream.closed))this.notifyOnCancel(),this.cancelled=!0;return this.cancelled}notifyOnCancel(){if(this.cancelNotified)return;if(this.cancelNotified=!0,this.cancelled=!0,process.nextTick(()=>{var $;($=this.listener)===null||$===void 0||$.onCancel()}),this.deadlineTimer)clearTimeout(this.deadlineTimer);this.stream.resume()}maybeSendMetadata(){if(!this.metadataSent)this.sendMetadata(new sT.Metadata)}serializeMessage($){let q=this.handler.serialize($),Y=q.byteLength,T=Buffer.allocUnsafe(Y+5);return T.writeUInt8(0,0),T.writeUInt32BE(Y,1),q.copy(T,5),T}decompressMessage($,q){let Y=$.subarray(5);if(q==="identity")return Y;else if(q==="deflate"||q==="gzip"){let T;if(q==="deflate")T=nW.createInflate();else T=nW.createGunzip();return new Promise((X,J)=>{let Q=0,U=[];T.on("data",(Z)=>{if(U.push(Z),Q+=Z.byteLength,this.maxReceiveMessageSize!==-1&&Q>this.maxReceiveMessageSize)T.destroy(),J({code:a0.Status.RESOURCE_EXHAUSTED,details:`Received message that decompresses to a size larger than ${this.maxReceiveMessageSize}`})}),T.on("end",()=>{X(Buffer.concat(U))}),T.write(Y),T.end()})}else return Promise.reject({code:a0.Status.UNIMPLEMENTED,details:`Received message compressed with unsupported encoding "${q}"`})}async decompressAndMaybePush($){if($.type!=="COMPRESSED")throw Error(`Invalid queue entry type: ${$.type}`);let Y=$.compressedMessage.readUInt8(0)===1?this.incomingEncoding:"identity",T;try{T=await this.decompressMessage($.compressedMessage,Y)}catch(X){this.sendStatus(X);return}try{$.parsedMessage=this.handler.deserialize(T)}catch(X){this.sendStatus({code:a0.Status.INTERNAL,details:`Error deserializing request: ${X.message}`});return}$.type="READABLE",this.maybePushNextMessage()}maybePushNextMessage(){if(this.listener&&this.isReadPending&&this.readQueue.length>0&&this.readQueue[0].type!=="COMPRESSED"){this.isReadPending=!1;let $=this.readQueue.shift();if($.type==="READABLE")this.listener.onReceiveMessage($.parsedMessage);else this.listener.onReceiveHalfClose()}}handleDataFrame($){var q;if(this.checkCancelled())return;o$("Request to "+this.handler.path+" received data frame of size "+$.length);let Y;try{Y=this.decoder.write($)}catch(T){this.sendStatus({code:a0.Status.RESOURCE_EXHAUSTED,details:T.message});return}for(let T of Y){this.stream.pause();let X={type:"COMPRESSED",compressedMessage:T,parsedMessage:null};this.readQueue.push(X),this.decompressAndMaybePush(X),(q=this.callEventTracker)===null||q===void 0||q.addMessageReceived()}}handleEndEvent(){this.readQueue.push({type:"HALF_CLOSE",compressedMessage:null,parsedMessage:null}),this.receivedHalfClose=!0,this.maybePushNextMessage()}start($){if(o$("Request to "+this.handler.path+" start called"),this.checkCancelled())return;this.listener=$,$.onReceiveMetadata(this.metadata)}sendMetadata($){if(this.checkCancelled())return;if(this.metadataSent)return;this.metadataSent=!0;let q=$?$.toHttp2Headers():null,Y=Object.assign(Object.assign(Object.assign({},oW),s2),q);this.stream.respond(Y,t2)}sendMessage($,q){if(this.checkCancelled())return;let Y;try{Y=this.serializeMessage($)}catch(T){this.sendStatus({code:a0.Status.INTERNAL,details:`Error serializing response: ${(0,lW.getErrorMessage)(T)}`,metadata:null});return}if(this.maxSendMessageSize!==-1&&Y.length-5>this.maxSendMessageSize){this.sendStatus({code:a0.Status.RESOURCE_EXHAUSTED,details:`Sent message larger than max (${Y.length} vs. ${this.maxSendMessageSize})`,metadata:null});return}this.maybeSendMetadata(),o$("Request to "+this.handler.path+" sent data frame of size "+Y.length),this.stream.write(Y,(T)=>{var X;if(T){this.sendStatus({code:a0.Status.INTERNAL,details:`Error writing message: ${(0,lW.getErrorMessage)(T)}`,metadata:null});return}(X=this.callEventTracker)===null||X===void 0||X.addMessageSent(),q()})}sendStatus($){var q,Y,T;if(this.checkCancelled())return;o$("Request to method "+((q=this.handler)===null||q===void 0?void 0:q.path)+" ended with status code: "+a0.Status[$.code]+" details: "+$.details);let X=(T=(Y=$.metadata)===null||Y===void 0?void 0:Y.clone())!==null&&T!==void 0?T:new sT.Metadata;if(this.shouldSendMetrics)X.set(iW.GRPC_METRICS_HEADER,this.metricsRecorder.serialize());if(this.metadataSent)if(!this.wantTrailers)this.wantTrailers=!0,this.stream.once("wantTrailers",()=>{if(this.callEventTracker&&!this.streamEnded)this.streamEnded=!0,this.callEventTracker.onStreamEnd(!0),this.callEventTracker.onCallEnd($);let J=Object.assign({[aW]:$.code,[rW]:encodeURI($.details)},X.toHttp2Headers());this.stream.sendTrailers(J),this.notifyOnCancel()}),this.stream.end();else this.notifyOnCancel();else{if(this.callEventTracker&&!this.streamEnded)this.streamEnded=!0,this.callEventTracker.onStreamEnd(!0),this.callEventTracker.onCallEnd($);let J=Object.assign(Object.assign({[aW]:$.code,[rW]:encodeURI($.details)},oW),X.toHttp2Headers());this.stream.respond(J,{endStream:!0}),this.notifyOnCancel()}}startRead(){if(o$("Request to "+this.handler.path+" startRead called"),this.checkCancelled())return;if(this.isReadPending=!0,this.readQueue.length===0){if(!this.receivedHalfClose)this.stream.resume()}else this.maybePushNextMessage()}getPeer(){var $;let q=($=this.stream.session)===null||$===void 0?void 0:$.socket;if(q===null||q===void 0?void 0:q.remoteAddress)if(q.remotePort)return`${q.remoteAddress}:${q.remotePort}`;else return q.remoteAddress;else return"unknown"}getDeadline(){return this.deadline}getHost(){return this.host}getAuthContext(){var $;if((($=this.stream.session)===null||$===void 0?void 0:$.socket)instanceof i2.TLSSocket){let q=this.stream.session.socket.getPeerCertificate();return{transportSecurityType:"ssl",sslPeerCertificate:q.raw?q:void 0}}else return{}}getConnectionInfo(){return this.connectionInfo}getMetricsRecorder(){return this.metricsRecorder}}XG.BaseServerInterceptingCall=fX;function e2($,q,Y,T,X,J){let Q={path:X.path,requestStream:X.type==="clientStream"||X.type==="bidi",responseStream:X.type==="serverStream"||X.type==="bidi",requestDeserialize:X.deserialize,responseSerialize:X.serialize},U=new fX(q,Y,T,X,J);return $.reduce((Z,K)=>{return K(Q,Z)},U)}});var GG=B((w$)=>{var JP=w$&&w$.__runInitializers||function($,q,Y){var T=arguments.length>2;for(var X=0;X<q.length;X++)Y=T?q[X].call($,Y):q[X].call($);return T?Y:void 0},QP=w$&&w$.__esDecorate||function($,q,Y,T,X,J){function Q(z){if(z!==void 0&&typeof z!=="function")throw TypeError("Function expected");return z}var U=T.kind,Z=U==="getter"?"get":U==="setter"?"set":"value",K=!q&&$?T.static?$:$.prototype:null,A=q||(K?Object.getOwnPropertyDescriptor(K,T.name):{}),W,G=!1;for(var V=Y.length-1;V>=0;V--){var F={};for(var N in T)F[N]=N==="access"?{}:T[N];for(var N in T.access)F.access[N]=T.access[N];F.addInitializer=function(z){if(G)throw TypeError("Cannot add initializers after decoration has completed");J.push(Q(z||null))};var D=(0,Y[V])(U==="accessor"?{get:A.get,set:A.set}:A[Z],F);if(U==="accessor"){if(D===void 0)continue;if(D===null||typeof D!=="object")throw TypeError("Object expected");if(W=Q(D.get))A.get=W;if(W=Q(D.set))A.set=W;if(W=Q(D.init))X.unshift(W)}else if(W=Q(D))if(U==="field")X.unshift(W);else A[Z]=W}if(K)Object.defineProperty(K,T.name,A);G=!0};Object.defineProperty(w$,"__esModule",{value:!0});w$.Server=void 0;var o0=e("http2"),UP=e("util"),N0=n(),bq=SW(),uX=nT(),QG=H1(),fq=Z0(),L$=i0(),w1=p0(),B0=R$(),UG=bX(),mq=2147483647,dX=2147483647,ZP=20000,ZG=2147483647,{HTTP2_HEADER_PATH:KG}=o0.constants,KP="server",AG=Buffer.from("max_age");function WG($){fq.trace(N0.LogVerbosity.DEBUG,"server_call",$)}function AP(){}function WP($){return function(q,Y){return UP.deprecate(q,$)}}function cX($){return{code:N0.Status.UNIMPLEMENTED,details:`The server does not implement the method ${$}`}}function GP($,q){let Y=cX(q);switch($){case"unary":return(T,X)=>{X(Y,null)};case"clientStream":return(T,X)=>{X(Y,null)};case"serverStream":return(T)=>{T.emit("error",Y)};case"bidi":return(T)=>{T.emit("error",Y)};default:throw Error(`Invalid handlerType ${$}`)}}var EP=(()=>{var $;let q=[],Y;return $=class{constructor(X){var J,Q,U,Z,K,A;if(this.boundPorts=(JP(this,q),new Map),this.http2Servers=new Map,this.sessionIdleTimeouts=new Map,this.handlers=new Map,this.sessions=new Map,this.started=!1,this.shutdown=!1,this.serverAddressString="null",this.channelzEnabled=!0,this.options=X!==null&&X!==void 0?X:{},this.options["grpc.enable_channelz"]===0)this.channelzEnabled=!1,this.channelzTrace=new B0.ChannelzTraceStub,this.callTracker=new B0.ChannelzCallTrackerStub,this.listenerChildrenTracker=new B0.ChannelzChildrenTrackerStub,this.sessionChildrenTracker=new B0.ChannelzChildrenTrackerStub;else this.channelzTrace=new B0.ChannelzTrace,this.callTracker=new B0.ChannelzCallTracker,this.listenerChildrenTracker=new B0.ChannelzChildrenTracker,this.sessionChildrenTracker=new B0.ChannelzChildrenTracker;if(this.channelzRef=(0,B0.registerChannelzServer)("server",()=>this.getChannelzInfo(),this.channelzEnabled),this.channelzTrace.addTrace("CT_INFO","Server created"),this.maxConnectionAgeMs=(J=this.options["grpc.max_connection_age_ms"])!==null&&J!==void 0?J:mq,this.maxConnectionAgeGraceMs=(Q=this.options["grpc.max_connection_age_grace_ms"])!==null&&Q!==void 0?Q:mq,this.keepaliveTimeMs=(U=this.options["grpc.keepalive_time_ms"])!==null&&U!==void 0?U:dX,this.keepaliveTimeoutMs=(Z=this.options["grpc.keepalive_timeout_ms"])!==null&&Z!==void 0?Z:ZP,this.sessionIdleTimeout=(K=this.options["grpc.max_connection_idle_ms"])!==null&&K!==void 0?K:ZG,this.commonServerOptions={maxSendHeaderBlockLength:Number.MAX_SAFE_INTEGER},"grpc-node.max_session_memory"in this.options)this.commonServerOptions.maxSessionMemory=this.options["grpc-node.max_session_memory"];else this.commonServerOptions.maxSessionMemory=Number.MAX_SAFE_INTEGER;if("grpc.max_concurrent_streams"in this.options)this.commonServerOptions.settings={maxConcurrentStreams:this.options["grpc.max_concurrent_streams"]};this.interceptors=(A=this.options.interceptors)!==null&&A!==void 0?A:[],this.trace("Server constructed")}getChannelzInfo(){return{trace:this.channelzTrace,callTracker:this.callTracker,listenerChildren:this.listenerChildrenTracker.getChildLists(),sessionChildren:this.sessionChildrenTracker.getChildLists()}}getChannelzSessionInfo(X){var J,Q,U;let Z=this.sessions.get(X),K=X.socket,A=K.remoteAddress?(0,L$.stringToSubchannelAddress)(K.remoteAddress,K.remotePort):null,W=K.localAddress?(0,L$.stringToSubchannelAddress)(K.localAddress,K.localPort):null,G;if(X.encrypted){let F=K,N=F.getCipher(),D=F.getCertificate(),z=F.getPeerCertificate();G={cipherSuiteStandardName:(J=N.standardName)!==null&&J!==void 0?J:null,cipherSuiteOtherName:N.standardName?null:N.name,localCertificate:D&&"raw"in D?D.raw:null,remoteCertificate:z&&"raw"in z?z.raw:null}}else G=null;return{remoteAddress:A,localAddress:W,security:G,remoteName:null,streamsStarted:Z.streamTracker.callsStarted,streamsSucceeded:Z.streamTracker.callsSucceeded,streamsFailed:Z.streamTracker.callsFailed,messagesSent:Z.messagesSent,messagesReceived:Z.messagesReceived,keepAlivesSent:Z.keepAlivesSent,lastLocalStreamCreatedTimestamp:null,lastRemoteStreamCreatedTimestamp:Z.streamTracker.lastCallStartedTimestamp,lastMessageSentTimestamp:Z.lastMessageSentTimestamp,lastMessageReceivedTimestamp:Z.lastMessageReceivedTimestamp,localFlowControlWindow:(Q=X.state.localWindowSize)!==null&&Q!==void 0?Q:null,remoteFlowControlWindow:(U=X.state.remoteWindowSize)!==null&&U!==void 0?U:null}}trace(X){fq.trace(N0.LogVerbosity.DEBUG,KP,"("+this.channelzRef.id+") "+X)}keepaliveTrace(X){fq.trace(N0.LogVerbosity.DEBUG,"keepalive","("+this.channelzRef.id+") "+X)}addProtoService(){throw Error("Not implemented. Use addService() instead")}addService(X,J){if(X===null||typeof X!=="object"||J===null||typeof J!=="object")throw Error("addService() requires two objects as arguments");let Q=Object.keys(X);if(Q.length===0)throw Error("Cannot add an empty service to a server");Q.forEach((U)=>{let Z=X[U],K;if(Z.requestStream)if(Z.responseStream)K="bidi";else K="clientStream";else if(Z.responseStream)K="serverStream";else K="unary";let A=J[U],W;if(A===void 0&&typeof Z.originalName==="string")A=J[Z.originalName];if(A!==void 0)W=A.bind(J);else W=GP(K,U);if(this.register(Z.path,W,Z.responseSerialize,Z.requestDeserialize,K)===!1)throw Error(`Method handler for ${Z.path} already provided.`)})}removeService(X){if(X===null||typeof X!=="object")throw Error("removeService() requires object as argument");Object.keys(X).forEach((Q)=>{let U=X[Q];this.unregister(U.path)})}bind(X,J){throw Error("Not implemented. Use bindAsync() instead")}experimentalRegisterListenerToChannelz(X){return(0,B0.registerChannelzSocket)((0,L$.subchannelAddressToString)(X),()=>{return{localAddress:X,remoteAddress:null,security:null,remoteName:null,streamsStarted:0,streamsSucceeded:0,streamsFailed:0,messagesSent:0,messagesReceived:0,keepAlivesSent:0,lastLocalStreamCreatedTimestamp:null,lastRemoteStreamCreatedTimestamp:null,lastMessageSentTimestamp:null,lastMessageReceivedTimestamp:null,localFlowControlWindow:null,remoteFlowControlWindow:null}},this.channelzEnabled)}experimentalUnregisterListenerFromChannelz(X){(0,B0.unregisterChannelzRef)(X)}createHttp2Server(X){let J;if(X._isSecure()){let Q=X._getConstructorOptions(),U=X._getSecureContextOptions(),Z=Object.assign(Object.assign(Object.assign(Object.assign({},this.commonServerOptions),Q),U),{enableTrace:this.options["grpc-node.tls_enable_trace"]===1}),K=U!==null;this.trace("Initial credentials valid: "+K),J=o0.createSecureServer(Z),J.prependListener("connection",(W)=>{if(!K)this.trace("Dropped connection from "+JSON.stringify(W.address())+" due to unloaded credentials"),W.destroy()}),J.on("secureConnection",(W)=>{W.on("error",(G)=>{this.trace("An incoming TLS connection closed with error: "+G.message)})});let A=(W)=>{if(W){let G=J;try{G.setSecureContext(W)}catch(V){fq.log(N0.LogVerbosity.ERROR,"Failed to set secure context with error "+V.message),W=null}}K=W!==null,this.trace("Post-update credentials valid: "+K)};X._addWatcher(A),J.on("close",()=>{X._removeWatcher(A)})}else J=o0.createServer(this.commonServerOptions);return J.setTimeout(0,AP),this._setupHandlers(J,X._getInterceptors()),J}bindOneAddress(X,J){this.trace("Attempting to bind "+(0,L$.subchannelAddressToString)(X));let Q=this.createHttp2Server(J.credentials);return new Promise((U,Z)=>{let K=(A)=>{this.trace("Failed to bind "+(0,L$.subchannelAddressToString)(X)+" with error "+A.message),U({port:"port"in X?X.port:1,error:A.message})};Q.once("error",K),Q.listen(X,()=>{let A=Q.address(),W;if(typeof A==="string")W={path:A};else W={host:A.address,port:A.port};let G=this.experimentalRegisterListenerToChannelz(W);this.listenerChildrenTracker.refChild(G),this.http2Servers.set(Q,{channelzRef:G,sessions:new Set,ownsChannelzRef:!0}),J.listeningServers.add(Q),this.trace("Successfully bound "+(0,L$.subchannelAddressToString)(W)),U({port:"port"in W?W.port:1}),Q.removeListener("error",K)})})}async bindManyPorts(X,J){if(X.length===0)return{count:0,port:0,errors:[]};if((0,L$.isTcpSubchannelAddress)(X[0])&&X[0].port===0){let Q=await this.bindOneAddress(X[0],J);if(Q.error){let U=await this.bindManyPorts(X.slice(1),J);return Object.assign(Object.assign({},U),{errors:[Q.error,...U.errors]})}else{let U=X.slice(1).map((A)=>(0,L$.isTcpSubchannelAddress)(A)?{host:A.host,port:Q.port}:A),Z=await Promise.all(U.map((A)=>this.bindOneAddress(A,J))),K=[Q,...Z];return{count:K.filter((A)=>A.error===void 0).length,port:Q.port,errors:K.filter((A)=>A.error).map((A)=>A.error)}}}else{let Q=await Promise.all(X.map((U)=>this.bindOneAddress(U,J)));return{count:Q.filter((U)=>U.error===void 0).length,port:Q[0].port,errors:Q.filter((U)=>U.error).map((U)=>U.error)}}}async bindAddressList(X,J){let Q=await this.bindManyPorts(X,J);if(Q.count>0){if(Q.count<X.length)fq.log(N0.LogVerbosity.INFO,`WARNING Only ${Q.count} addresses added out of total ${X.length} resolved`);return Q.port}else{let U=`No address added out of total ${X.length} resolved`;throw fq.log(N0.LogVerbosity.ERROR,U),Error(`${U} errors: [${Q.errors.join(",")}]`)}}resolvePort(X){return new Promise((J,Q)=>{let U=!1,Z=(A,W,G,V)=>{if(U)return!0;if(U=!0,!A.ok)return Q(Error(A.error.details)),!0;let F=[].concat(...A.value.map((N)=>N.addresses));if(F.length===0)return Q(Error(`No addresses resolved for port ${X}`)),!0;return J(F),!0};(0,QG.createResolver)(X,Z,this.options).updateResolution()})}async bindPort(X,J){let Q=await this.resolvePort(X);if(J.cancelled)throw this.completeUnbind(J),Error("bindAsync operation cancelled by unbind call");let U=await this.bindAddressList(Q,J);if(J.cancelled)throw this.completeUnbind(J),Error("bindAsync operation cancelled by unbind call");return U}normalizePort(X){let J=(0,w1.parseUri)(X);if(J===null)throw Error(`Could not parse port "${X}"`);let Q=(0,QG.mapUriDefaultScheme)(J);if(Q===null)throw Error(`Could not get a default scheme for port "${X}"`);return Q}bindAsync(X,J,Q){if(this.shutdown)throw Error("bindAsync called after shutdown");if(typeof X!=="string")throw TypeError("port must be a string");if(J===null||!(J instanceof uX.ServerCredentials))throw TypeError("creds must be a ServerCredentials object");if(typeof Q!=="function")throw TypeError("callback must be a function");this.trace("bindAsync port="+X);let U=this.normalizePort(X),Z=(G,V)=>{process.nextTick(()=>Q(G,V))},K=this.boundPorts.get((0,w1.uriToString)(U));if(K){if(!J._equals(K.credentials)){Z(Error(`${X} already bound with incompatible credentials`),0);return}if(K.cancelled=!1,K.completionPromise)K.completionPromise.then((G)=>Q(null,G),(G)=>Q(G,0));else Z(null,K.portNumber);return}K={mapKey:(0,w1.uriToString)(U),originalUri:U,completionPromise:null,cancelled:!1,portNumber:0,credentials:J,listeningServers:new Set};let A=(0,w1.splitHostPort)(U.path),W=this.bindPort(U,K);if(K.completionPromise=W,(A===null||A===void 0?void 0:A.port)===0)W.then((G)=>{let V={scheme:U.scheme,authority:U.authority,path:(0,w1.combineHostPort)({host:A.host,port:G})};K.mapKey=(0,w1.uriToString)(V),K.completionPromise=null,K.portNumber=G,this.boundPorts.set(K.mapKey,K),Q(null,G)},(G)=>{Q(G,0)});else this.boundPorts.set(K.mapKey,K),W.then((G)=>{K.completionPromise=null,K.portNumber=G,Q(null,G)},(G)=>{Q(G,0)})}registerInjectorToChannelz(){return(0,B0.registerChannelzSocket)("injector",()=>{return{localAddress:null,remoteAddress:null,security:null,remoteName:null,streamsStarted:0,streamsSucceeded:0,streamsFailed:0,messagesSent:0,messagesReceived:0,keepAlivesSent:0,lastLocalStreamCreatedTimestamp:null,lastRemoteStreamCreatedTimestamp:null,lastMessageSentTimestamp:null,lastMessageReceivedTimestamp:null,localFlowControlWindow:null,remoteFlowControlWindow:null}},this.channelzEnabled)}experimentalCreateConnectionInjectorWithChannelzRef(X,J,Q=!1){if(X===null||!(X instanceof uX.ServerCredentials))throw TypeError("creds must be a ServerCredentials object");if(this.channelzEnabled)this.listenerChildrenTracker.refChild(J);let U=this.createHttp2Server(X),Z=new Set;return this.http2Servers.set(U,{channelzRef:J,sessions:Z,ownsChannelzRef:Q}),{injectConnection:(K)=>{U.emit("connection",K)},drain:(K)=>{var A,W;for(let G of Z)this.closeSession(G);(W=(A=setTimeout(()=>{for(let G of Z)G.destroy(o0.constants.NGHTTP2_CANCEL)},K)).unref)===null||W===void 0||W.call(A)},destroy:()=>{this.closeServer(U);for(let K of Z)this.closeSession(K)}}}createConnectionInjector(X){if(X===null||!(X instanceof uX.ServerCredentials))throw TypeError("creds must be a ServerCredentials object");let J=this.registerInjectorToChannelz();return this.experimentalCreateConnectionInjectorWithChannelzRef(X,J,!0)}closeServer(X,J){this.trace("Closing server with address "+JSON.stringify(X.address()));let Q=this.http2Servers.get(X);X.close(()=>{if(Q&&Q.ownsChannelzRef)this.listenerChildrenTracker.unrefChild(Q.channelzRef),(0,B0.unregisterChannelzRef)(Q.channelzRef);this.http2Servers.delete(X),J===null||J===void 0||J()})}closeSession(X,J){var Q;this.trace("Closing session initiated by "+((Q=X.socket)===null||Q===void 0?void 0:Q.remoteAddress));let U=this.sessions.get(X),Z=()=>{if(U)this.sessionChildrenTracker.unrefChild(U.ref),(0,B0.unregisterChannelzRef)(U.ref);J===null||J===void 0||J()};if(X.closed)queueMicrotask(Z);else X.close(Z)}completeUnbind(X){for(let J of X.listeningServers){let Q=this.http2Servers.get(J);if(this.closeServer(J,()=>{X.listeningServers.delete(J)}),Q)for(let U of Q.sessions)this.closeSession(U)}this.boundPorts.delete(X.mapKey)}unbind(X){this.trace("unbind port="+X);let J=this.normalizePort(X),Q=(0,w1.splitHostPort)(J.path);if((Q===null||Q===void 0?void 0:Q.port)===0)throw Error("Cannot unbind port 0");let U=this.boundPorts.get((0,w1.uriToString)(J));if(U)if(this.trace("unbinding "+U.mapKey+" originally bound as "+(0,w1.uriToString)(U.originalUri)),U.completionPromise)U.cancelled=!0;else this.completeUnbind(U)}drain(X,J){var Q,U;this.trace("drain port="+X+" graceTimeMs="+J);let Z=this.normalizePort(X),K=(0,w1.splitHostPort)(Z.path);if((K===null||K===void 0?void 0:K.port)===0)throw Error("Cannot drain port 0");let A=this.boundPorts.get((0,w1.uriToString)(Z));if(!A)return;let W=new Set;for(let G of A.listeningServers){let V=this.http2Servers.get(G);if(V)for(let F of V.sessions)W.add(F),this.closeSession(F,()=>{W.delete(F)})}(U=(Q=setTimeout(()=>{for(let G of W)G.destroy(o0.constants.NGHTTP2_CANCEL)},J)).unref)===null||U===void 0||U.call(Q)}forceShutdown(){for(let X of this.boundPorts.values())X.cancelled=!0;this.boundPorts.clear();for(let X of this.http2Servers.keys())this.closeServer(X);this.sessions.forEach((X,J)=>{this.closeSession(J),J.destroy(o0.constants.NGHTTP2_CANCEL)}),this.sessions.clear(),(0,B0.unregisterChannelzRef)(this.channelzRef),this.shutdown=!0}register(X,J,Q,U,Z){if(this.handlers.has(X))return!1;return this.handlers.set(X,{func:J,serialize:Q,deserialize:U,type:Z,path:X}),!0}unregister(X){return this.handlers.delete(X)}start(){if(this.http2Servers.size===0||[...this.http2Servers.keys()].every((X)=>!X.listening))throw Error("server must be bound in order to start");if(this.started===!0)throw Error("server is already started");this.started=!0}tryShutdown(X){var J;let Q=(K)=>{(0,B0.unregisterChannelzRef)(this.channelzRef),X(K)},U=0;function Z(){if(U--,U===0)Q()}this.shutdown=!0;for(let[K,A]of this.http2Servers.entries()){U++;let W=A.channelzRef.name;this.trace("Waiting for server "+W+" to close"),this.closeServer(K,()=>{this.trace("Server "+W+" finished closing"),Z()});for(let G of A.sessions.keys()){U++;let V=(J=G.socket)===null||J===void 0?void 0:J.remoteAddress;this.trace("Waiting for session "+V+" to close"),this.closeSession(G,()=>{this.trace("Session "+V+" finished closing"),Z()})}}if(U===0)Q()}addHttp2Port(){throw Error("Not yet implemented")}getChannelzRef(){return this.channelzRef}_verifyContentType(X,J){let Q=J[o0.constants.HTTP2_HEADER_CONTENT_TYPE];if(typeof Q!=="string"||!Q.startsWith("application/grpc"))return X.respond({[o0.constants.HTTP2_HEADER_STATUS]:o0.constants.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE},{endStream:!0}),!1;return!0}_retrieveHandler(X){WG("Received call to method "+X+" at address "+this.serverAddressString);let J=this.handlers.get(X);if(J===void 0)return WG("No handler registered for method "+X+". Sending UNIMPLEMENTED status."),null;return J}_respondWithError(X,J,Q=null){var U,Z;let K=Object.assign({"grpc-status":(U=X.code)!==null&&U!==void 0?U:N0.Status.INTERNAL,"grpc-message":X.details,[o0.constants.HTTP2_HEADER_STATUS]:o0.constants.HTTP_STATUS_OK,[o0.constants.HTTP2_HEADER_CONTENT_TYPE]:"application/grpc+proto"},(Z=X.metadata)===null||Z===void 0?void 0:Z.toHttp2Headers());J.respond(K,{endStream:!0}),this.callTracker.addCallFailed(),Q===null||Q===void 0||Q.streamTracker.addCallFailed()}_channelzHandler(X,J,Q){this.onStreamOpened(J);let U=this.sessions.get(J.session);if(this.callTracker.addCallStarted(),U===null||U===void 0||U.streamTracker.addCallStarted(),!this._verifyContentType(J,Q)){this.callTracker.addCallFailed(),U===null||U===void 0||U.streamTracker.addCallFailed();return}let Z=Q[KG],K=this._retrieveHandler(Z);if(!K){this._respondWithError(cX(Z),J,U);return}let A={addMessageSent:()=>{if(U)U.messagesSent+=1,U.lastMessageSentTimestamp=new Date},addMessageReceived:()=>{if(U)U.messagesReceived+=1,U.lastMessageReceivedTimestamp=new Date},onCallEnd:(G)=>{if(G.code===N0.Status.OK)this.callTracker.addCallSucceeded();else this.callTracker.addCallFailed()},onStreamEnd:(G)=>{if(U)if(G)U.streamTracker.addCallSucceeded();else U.streamTracker.addCallFailed()}},W=(0,UG.getServerInterceptingCall)([...X,...this.interceptors],J,Q,A,K,this.options);if(!this._runHandlerForCall(W,K))this.callTracker.addCallFailed(),U===null||U===void 0||U.streamTracker.addCallFailed(),W.sendStatus({code:N0.Status.INTERNAL,details:`Unknown handler type: ${K.type}`})}_streamHandler(X,J,Q){if(this.onStreamOpened(J),this._verifyContentType(J,Q)!==!0)return;let U=Q[KG],Z=this._retrieveHandler(U);if(!Z){this._respondWithError(cX(U),J,null);return}let K=(0,UG.getServerInterceptingCall)([...X,...this.interceptors],J,Q,null,Z,this.options);if(!this._runHandlerForCall(K,Z))K.sendStatus({code:N0.Status.INTERNAL,details:`Unknown handler type: ${Z.type}`})}_runHandlerForCall(X,J){let{type:Q}=J;if(Q==="unary")VP(X,J);else if(Q==="clientStream")DP(X,J);else if(Q==="serverStream")FP(X,J);else if(Q==="bidi")IP(X,J);else return!1;return!0}_setupHandlers(X,J){if(X===null)return;let Q=X.address(),U="null";if(Q)if(typeof Q==="string")U=Q;else U=Q.address+":"+Q.port;this.serverAddressString=U;let Z=this.channelzEnabled?this._channelzHandler:this._streamHandler,K=this.channelzEnabled?this._channelzSessionHandler(X):this._sessionHandler(X);X.on("stream",Z.bind(this,J)),X.on("session",K)}_sessionHandler(X){return(J)=>{var Q,U;(Q=this.http2Servers.get(X))===null||Q===void 0||Q.sessions.add(J);let Z=null,K=null,A=null,W=!1,G=this.enableIdleTimeout(J);if(this.maxConnectionAgeMs!==mq){let z=this.maxConnectionAgeMs/10,S=Math.random()*z*2-z;Z=setTimeout(()=>{var v,H;W=!0,this.trace("Connection dropped by max connection age: "+((v=J.socket)===null||v===void 0?void 0:v.remoteAddress));try{J.goaway(o0.constants.NGHTTP2_NO_ERROR,2147483647,AG)}catch(_){J.destroy();return}if(J.close(),this.maxConnectionAgeGraceMs!==mq)K=setTimeout(()=>{J.destroy()},this.maxConnectionAgeGraceMs),(H=K.unref)===null||H===void 0||H.call(K)},this.maxConnectionAgeMs+S),(U=Z.unref)===null||U===void 0||U.call(Z)}let V=()=>{if(A)clearTimeout(A),A=null},F=()=>{return!J.destroyed&&this.keepaliveTimeMs<dX&&this.keepaliveTimeMs>0},N,D=()=>{var z;if(!F())return;this.keepaliveTrace("Starting keepalive timer for "+this.keepaliveTimeMs+"ms"),A=setTimeout(()=>{V(),N()},this.keepaliveTimeMs),(z=A.unref)===null||z===void 0||z.call(A)};N=()=>{var z;if(!F())return;this.keepaliveTrace("Sending ping with timeout "+this.keepaliveTimeoutMs+"ms");let S="";try{if(!J.ping((H,_,y)=>{if(V(),H)this.keepaliveTrace("Ping failed with error: "+H.message),W=!0,J.destroy();else this.keepaliveTrace("Received ping response"),D()}))S="Ping returned false"}catch(v){S=(v instanceof Error?v.message:"")||"Unknown error"}if(S){this.keepaliveTrace("Ping send failed: "+S),this.trace("Connection dropped due to ping send error: "+S),W=!0,J.destroy();return}A=setTimeout(()=>{V(),this.keepaliveTrace("Ping timeout passed without response"),this.trace("Connection dropped by keepalive timeout"),W=!0,J.destroy()},this.keepaliveTimeoutMs),(z=A.unref)===null||z===void 0||z.call(A)},D(),J.on("close",()=>{var z,S;if(!W)this.trace(`Connection dropped by client ${(z=J.socket)===null||z===void 0?void 0:z.remoteAddress}`);if(Z)clearTimeout(Z);if(K)clearTimeout(K);if(V(),G!==null)clearTimeout(G.timeout),this.sessionIdleTimeouts.delete(J);(S=this.http2Servers.get(X))===null||S===void 0||S.sessions.delete(J)})}}_channelzSessionHandler(X){return(J)=>{var Q,U,Z,K;let A=(0,B0.registerChannelzSocket)((U=(Q=J.socket)===null||Q===void 0?void 0:Q.remoteAddress)!==null&&U!==void 0?U:"unknown",this.getChannelzSessionInfo.bind(this,J),this.channelzEnabled),W={ref:A,streamTracker:new B0.ChannelzCallTracker,messagesSent:0,messagesReceived:0,keepAlivesSent:0,lastMessageSentTimestamp:null,lastMessageReceivedTimestamp:null};(Z=this.http2Servers.get(X))===null||Z===void 0||Z.sessions.add(J),this.sessions.set(J,W);let G=`${J.socket.remoteAddress}:${J.socket.remotePort}`;this.channelzTrace.addTrace("CT_INFO","Connection established by client "+G),this.trace("Connection established by client "+G),this.sessionChildrenTracker.refChild(A);let V=null,F=null,N=null,D=!1,z=this.enableIdleTimeout(J);if(this.maxConnectionAgeMs!==mq){let y=this.maxConnectionAgeMs/10,k=Math.random()*y*2-y;V=setTimeout(()=>{var m;D=!0,this.channelzTrace.addTrace("CT_INFO","Connection dropped by max connection age from "+G);try{J.goaway(o0.constants.NGHTTP2_NO_ERROR,2147483647,AG)}catch(C){J.destroy();return}if(J.close(),this.maxConnectionAgeGraceMs!==mq)F=setTimeout(()=>{J.destroy()},this.maxConnectionAgeGraceMs),(m=F.unref)===null||m===void 0||m.call(F)},this.maxConnectionAgeMs+k),(K=V.unref)===null||K===void 0||K.call(V)}let S=()=>{if(N)clearTimeout(N),N=null},v=()=>{return!J.destroyed&&this.keepaliveTimeMs<dX&&this.keepaliveTimeMs>0},H,_=()=>{var y;if(!v())return;this.keepaliveTrace("Starting keepalive timer for "+this.keepaliveTimeMs+"ms"),N=setTimeout(()=>{S(),H()},this.keepaliveTimeMs),(y=N.unref)===null||y===void 0||y.call(N)};H=()=>{var y;if(!v())return;this.keepaliveTrace("Sending ping with timeout "+this.keepaliveTimeoutMs+"ms");let k="";try{if(!J.ping((C,j,M)=>{if(S(),C)this.keepaliveTrace("Ping failed with error: "+C.message),this.channelzTrace.addTrace("CT_INFO","Connection dropped due to error of a ping frame "+C.message+" return in "+j),D=!0,J.destroy();else this.keepaliveTrace("Received ping response"),_()}))k="Ping returned false"}catch(m){k=(m instanceof Error?m.message:"")||"Unknown error"}if(k){this.keepaliveTrace("Ping send failed: "+k),this.channelzTrace.addTrace("CT_INFO","Connection dropped due to ping send error: "+k),D=!0,J.destroy();return}W.keepAlivesSent+=1,N=setTimeout(()=>{S(),this.keepaliveTrace("Ping timeout passed without response"),this.channelzTrace.addTrace("CT_INFO","Connection dropped by keepalive timeout from "+G),D=!0,J.destroy()},this.keepaliveTimeoutMs),(y=N.unref)===null||y===void 0||y.call(N)},_(),J.on("close",()=>{var y;if(!D)this.channelzTrace.addTrace("CT_INFO","Connection dropped by client "+G);if(this.sessionChildrenTracker.unrefChild(A),(0,B0.unregisterChannelzRef)(A),V)clearTimeout(V);if(F)clearTimeout(F);if(S(),z!==null)clearTimeout(z.timeout),this.sessionIdleTimeouts.delete(J);(y=this.http2Servers.get(X))===null||y===void 0||y.sessions.delete(J),this.sessions.delete(J)})}}enableIdleTimeout(X){var J,Q;if(this.sessionIdleTimeout>=ZG)return null;let U={activeStreams:0,lastIdle:Date.now(),onClose:this.onStreamClose.bind(this,X),timeout:setTimeout(this.onIdleTimeout,this.sessionIdleTimeout,this,X)};(Q=(J=U.timeout).unref)===null||Q===void 0||Q.call(J),this.sessionIdleTimeouts.set(X,U);let{socket:Z}=X;return this.trace("Enable idle timeout for "+Z.remoteAddress+":"+Z.remotePort),U}onIdleTimeout(X,J){let{socket:Q}=J,U=X.sessionIdleTimeouts.get(J);if(U!==void 0&&U.activeStreams===0)if(Date.now()-U.lastIdle>=X.sessionIdleTimeout)X.trace("Session idle timeout triggered for "+(Q===null||Q===void 0?void 0:Q.remoteAddress)+":"+(Q===null||Q===void 0?void 0:Q.remotePort)+" last idle at "+U.lastIdle),X.closeSession(J);else U.timeout.refresh()}onStreamOpened(X){let J=X.session,Q=this.sessionIdleTimeouts.get(J);if(Q)Q.activeStreams+=1,X.once("close",Q.onClose)}onStreamClose(X){var J,Q;let U=this.sessionIdleTimeouts.get(X);if(U){if(U.activeStreams-=1,U.activeStreams===0)U.lastIdle=Date.now(),U.timeout.refresh(),this.trace("Session onStreamClose"+((J=X.socket)===null||J===void 0?void 0:J.remoteAddress)+":"+((Q=X.socket)===null||Q===void 0?void 0:Q.remotePort)+" at "+U.lastIdle)}}},(()=>{let T=typeof Symbol==="function"&&Symbol.metadata?Object.create(null):void 0;if(Y=[WP("Calling start() is no longer necessary. It can be safely omitted.")],QP($,null,Y,{kind:"method",name:"start",static:!1,private:!1,access:{has:(X)=>("start"in X),get:(X)=>X.start},metadata:T},null,q),T)Object.defineProperty($,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:T})})(),$})();w$.Server=EP;async function VP($,q){let Y;function T(Q,U,Z,K){if(Q){$.sendStatus((0,bq.serverErrorToStatus)(Q,Z));return}$.sendMessage(U,()=>{$.sendStatus({code:N0.Status.OK,details:"OK",metadata:Z!==null&&Z!==void 0?Z:null})})}let X,J=null;$.start({onReceiveMetadata(Q){X=Q,$.startRead()},onReceiveMessage(Q){if(J){$.sendStatus({code:N0.Status.UNIMPLEMENTED,details:`Received a second request message for server streaming method ${q.path}`,metadata:null});return}J=Q,$.startRead()},onReceiveHalfClose(){if(!J){$.sendStatus({code:N0.Status.UNIMPLEMENTED,details:`Received no request message for server streaming method ${q.path}`,metadata:null});return}Y=new bq.ServerWritableStreamImpl(q.path,$,X,J);try{q.func(Y,T)}catch(Q){$.sendStatus({code:N0.Status.UNKNOWN,details:`Server method handler threw error ${Q.message}`,metadata:null})}},onCancel(){if(Y)Y.cancelled=!0,Y.emit("cancelled","cancelled")}})}function DP($,q){let Y;function T(X,J,Q,U){if(X){$.sendStatus((0,bq.serverErrorToStatus)(X,Q));return}$.sendMessage(J,()=>{$.sendStatus({code:N0.Status.OK,details:"OK",metadata:Q!==null&&Q!==void 0?Q:null})})}$.start({onReceiveMetadata(X){Y=new bq.ServerDuplexStreamImpl(q.path,$,X);try{q.func(Y,T)}catch(J){$.sendStatus({code:N0.Status.UNKNOWN,details:`Server method handler threw error ${J.message}`,metadata:null})}},onReceiveMessage(X){Y.push(X)},onReceiveHalfClose(){Y.push(null)},onCancel(){if(Y)Y.cancelled=!0,Y.emit("cancelled","cancelled"),Y.destroy()}})}function FP($,q){let Y,T,X=null;$.start({onReceiveMetadata(J){T=J,$.startRead()},onReceiveMessage(J){if(X){$.sendStatus({code:N0.Status.UNIMPLEMENTED,details:`Received a second request message for server streaming method ${q.path}`,metadata:null});return}X=J,$.startRead()},onReceiveHalfClose(){if(!X){$.sendStatus({code:N0.Status.UNIMPLEMENTED,details:`Received no request message for server streaming method ${q.path}`,metadata:null});return}Y=new bq.ServerWritableStreamImpl(q.path,$,T,X);try{q.func(Y)}catch(J){$.sendStatus({code:N0.Status.UNKNOWN,details:`Server method handler threw error ${J.message}`,metadata:null})}},onCancel(){if(Y)Y.cancelled=!0,Y.emit("cancelled","cancelled"),Y.destroy()}})}function IP($,q){let Y;$.start({onReceiveMetadata(T){Y=new bq.ServerDuplexStreamImpl(q.path,$,T);try{q.func(Y)}catch(X){$.sendStatus({code:N0.Status.UNKNOWN,details:`Server method handler threw error ${X.message}`,metadata:null})}},onReceiveMessage(T){Y.push(T)},onReceiveHalfClose(){Y.push(null)},onCancel(){if(Y)Y.cancelled=!0,Y.emit("cancelled","cancelled"),Y.destroy()}})}});var FG=B((VG)=>{Object.defineProperty(VG,"__esModule",{value:!0});VG.StatusBuilder=void 0;class EG{constructor(){this.code=null,this.details=null,this.metadata=null}withCode($){return this.code=$,this}withDetails($){return this.details=$,this}withMetadata($){return this.metadata=$,this}build(){let $={};if(this.code!==null)$.code=this.code;if(this.details!==null)$.details=this.details;if(this.metadata!==null)$.metadata=this.metadata;return $}}VG.StatusBuilder=EG});var sY=B((PG)=>{Object.defineProperty(PG,"__esModule",{value:!0});PG.LeafLoadBalancer=PG.PickFirstLoadBalancer=PG.PickFirstLoadBalancingConfig=void 0;PG.shuffled=MG;PG.setup=OP;var pX=V$(),H0=l0(),S$=s1(),IG=i0(),NP=Z0(),HP=n(),NG=i0(),HG=e("net"),zP=m$(),MP="pick_first";function aY($){NP.trace(HP.LogVerbosity.DEBUG,MP,$)}var oY="pick_first",BP=250;class uq{constructor($){this.shuffleAddressList=$}getLoadBalancerName(){return oY}toJsonObject(){return{[oY]:{shuffleAddressList:this.shuffleAddressList}}}getShuffleAddressList(){return this.shuffleAddressList}static createFromJson($){if("shuffleAddressList"in $&&typeof $.shuffleAddressList!=="boolean")throw Error("pick_first config field shuffleAddressList must be a boolean if provided");return new uq($.shuffleAddressList===!0)}}PG.PickFirstLoadBalancingConfig=uq;class zG{constructor($){this.subchannel=$}pick($){return{pickResultType:S$.PickResultType.COMPLETE,subchannel:this.subchannel,status:null,onCallStarted:null,onCallEnded:null}}}function MG($){let q=$.slice();for(let Y=q.length-1;Y>1;Y--){let T=Math.floor(Math.random()*(Y+1)),X=q[Y];q[Y]=q[T],q[T]=X}return q}function RP($){if($.length===0)return[];let q=[],Y=[],T=[],X=(0,NG.isTcpSubchannelAddress)($[0])&&(0,HG.isIPv6)($[0].host);for(let U of $)if((0,NG.isTcpSubchannelAddress)(U)&&(0,HG.isIPv6)(U.host))Y.push(U);else T.push(U);let J=X?Y:T,Q=X?T:Y;for(let U=0;U<Math.max(J.length,Q.length);U++){if(U<J.length)q.push(J[U]);if(U<Q.length)q.push(Q[U])}return q}var BG="grpc-node.internal.pick-first.report_health_status";class tT{constructor($){this.channelControlHelper=$,this.children=[],this.currentState=H0.ConnectivityState.IDLE,this.currentSubchannelIndex=0,this.currentPick=null,this.subchannelStateListener=(q,Y,T,X,J)=>{this.onSubchannelStateUpdate(q,Y,T,J)},this.pickedSubchannelHealthListener=()=>this.calculateAndReportNewState(),this.stickyTransientFailureMode=!1,this.reportHealthStatus=!1,this.lastError=null,this.latestAddressList=null,this.latestOptions={},this.latestResolutionNote="",this.connectionDelayTimeout=setTimeout(()=>{},0),clearTimeout(this.connectionDelayTimeout)}allChildrenHaveReportedTF(){return this.children.every(($)=>$.hasReportedTransientFailure)}resetChildrenReportedTF(){this.children.every(($)=>$.hasReportedTransientFailure=!1)}calculateAndReportNewState(){var $;if(this.currentPick)if(this.reportHealthStatus&&!this.currentPick.isHealthy()){let q=`Picked subchannel ${this.currentPick.getAddress()} is unhealthy`;this.updateState(H0.ConnectivityState.TRANSIENT_FAILURE,new S$.UnavailablePicker({details:q}),q)}else this.updateState(H0.ConnectivityState.READY,new zG(this.currentPick),null);else if((($=this.latestAddressList)===null||$===void 0?void 0:$.length)===0){let q=`No connection established. Last error: ${this.lastError}. Resolution note: ${this.latestResolutionNote}`;this.updateState(H0.ConnectivityState.TRANSIENT_FAILURE,new S$.UnavailablePicker({details:q}),q)}else if(this.children.length===0)this.updateState(H0.ConnectivityState.IDLE,new S$.QueuePicker(this),null);else if(this.stickyTransientFailureMode){let q=`No connection established. Last error: ${this.lastError}. Resolution note: ${this.latestResolutionNote}`;this.updateState(H0.ConnectivityState.TRANSIENT_FAILURE,new S$.UnavailablePicker({details:q}),q)}else this.updateState(H0.ConnectivityState.CONNECTING,new S$.QueuePicker(this),null)}requestReresolution(){this.channelControlHelper.requestReresolution()}maybeEnterStickyTransientFailureMode(){if(!this.allChildrenHaveReportedTF())return;if(this.requestReresolution(),this.resetChildrenReportedTF(),this.stickyTransientFailureMode){this.calculateAndReportNewState();return}this.stickyTransientFailureMode=!0;for(let{subchannel:$}of this.children)$.startConnecting();this.calculateAndReportNewState()}removeCurrentPick(){if(this.currentPick!==null)this.currentPick.removeConnectivityStateListener(this.subchannelStateListener),this.channelControlHelper.removeChannelzChild(this.currentPick.getChannelzRef()),this.currentPick.removeHealthStateWatcher(this.pickedSubchannelHealthListener),this.currentPick.unref(),this.currentPick=null}onSubchannelStateUpdate($,q,Y,T){var X;if((X=this.currentPick)===null||X===void 0?void 0:X.realSubchannelEquals($)){if(Y!==H0.ConnectivityState.READY)this.removeCurrentPick(),this.calculateAndReportNewState();return}for(let[J,Q]of this.children.entries())if($.realSubchannelEquals(Q.subchannel)){if(Y===H0.ConnectivityState.READY)this.pickSubchannel(Q.subchannel);if(Y===H0.ConnectivityState.TRANSIENT_FAILURE){if(Q.hasReportedTransientFailure=!0,T)this.lastError=T;if(this.maybeEnterStickyTransientFailureMode(),J===this.currentSubchannelIndex)this.startNextSubchannelConnecting(J+1)}Q.subchannel.startConnecting();return}}startNextSubchannelConnecting($){clearTimeout(this.connectionDelayTimeout);for(let[q,Y]of this.children.entries())if(q>=$){let T=Y.subchannel.getConnectivityState();if(T===H0.ConnectivityState.IDLE||T===H0.ConnectivityState.CONNECTING){this.startConnecting(q);return}}this.maybeEnterStickyTransientFailureMode()}startConnecting($){var q,Y;if(clearTimeout(this.connectionDelayTimeout),this.currentSubchannelIndex=$,this.children[$].subchannel.getConnectivityState()===H0.ConnectivityState.IDLE)aY("Start connecting to subchannel with address "+this.children[$].subchannel.getAddress()),process.nextTick(()=>{var T;(T=this.children[$])===null||T===void 0||T.subchannel.startConnecting()});this.connectionDelayTimeout=setTimeout(()=>{this.startNextSubchannelConnecting($+1)},BP),(Y=(q=this.connectionDelayTimeout).unref)===null||Y===void 0||Y.call(q)}pickSubchannel($){aY("Pick subchannel with address "+$.getAddress()),this.stickyTransientFailureMode=!1,$.ref(),this.channelControlHelper.addChannelzChild($.getChannelzRef()),this.removeCurrentPick(),this.resetSubchannelList(),$.addConnectivityStateListener(this.subchannelStateListener),$.addHealthStateWatcher(this.pickedSubchannelHealthListener),this.currentPick=$,clearTimeout(this.connectionDelayTimeout),this.calculateAndReportNewState()}updateState($,q,Y){aY(H0.ConnectivityState[this.currentState]+" -> "+H0.ConnectivityState[$]),this.currentState=$,this.channelControlHelper.updateState($,q,Y)}resetSubchannelList(){for(let $ of this.children)$.subchannel.removeConnectivityStateListener(this.subchannelStateListener),$.subchannel.unref(),this.channelControlHelper.removeChannelzChild($.subchannel.getChannelzRef());this.currentSubchannelIndex=0,this.children=[]}connectToAddressList($,q){aY("connectToAddressList(["+$.map((T)=>(0,IG.subchannelAddressToString)(T))+"])");let Y=$.map((T)=>({subchannel:this.channelControlHelper.createSubchannel(T,q),hasReportedTransientFailure:!1}));for(let{subchannel:T}of Y)if(T.getConnectivityState()===H0.ConnectivityState.READY){this.pickSubchannel(T);return}for(let{subchannel:T}of Y)T.ref(),this.channelControlHelper.addChannelzChild(T.getChannelzRef());this.resetSubchannelList(),this.children=Y;for(let{subchannel:T}of this.children)T.addConnectivityStateListener(this.subchannelStateListener);for(let T of this.children)if(T.subchannel.getConnectivityState()===H0.ConnectivityState.TRANSIENT_FAILURE)T.hasReportedTransientFailure=!0;this.startNextSubchannelConnecting(0),this.calculateAndReportNewState()}updateAddressList($,q,Y,T){if(!(q instanceof uq))return!1;if(!$.ok){if(this.children.length===0&&this.currentPick===null)this.channelControlHelper.updateState(H0.ConnectivityState.TRANSIENT_FAILURE,new S$.UnavailablePicker($.error),$.error.details);return!0}let X=$.value;if(this.reportHealthStatus=Y[BG],q.getShuffleAddressList())X=MG(X);let J=[].concat(...X.map((U)=>U.addresses));aY("updateAddressList(["+J.map((U)=>(0,IG.subchannelAddressToString)(U))+"])");let Q=RP(J);if(this.latestAddressList=Q,this.latestOptions=Y,this.connectToAddressList(Q,Y),this.latestResolutionNote=T,J.length>0)return!0;else return this.lastError="No addresses resolved",!1}exitIdle(){if(this.currentState===H0.ConnectivityState.IDLE&&this.latestAddressList)this.connectToAddressList(this.latestAddressList,this.latestOptions)}resetBackoff(){}destroy(){this.resetSubchannelList(),this.removeCurrentPick()}getTypeName(){return oY}}PG.PickFirstLoadBalancer=tT;var PP=new uq(!1);class RG{constructor($,q,Y,T){this.endpoint=$,this.options=Y,this.resolutionNote=T,this.latestState=H0.ConnectivityState.IDLE;let X=(0,pX.createChildChannelControlHelper)(q,{updateState:(J,Q,U)=>{this.latestState=J,this.latestPicker=Q,q.updateState(J,Q,U)}});this.pickFirstBalancer=new tT(X),this.latestPicker=new S$.QueuePicker(this.pickFirstBalancer)}startConnecting(){this.pickFirstBalancer.updateAddressList((0,zP.statusOrFromValue)([this.endpoint]),PP,Object.assign(Object.assign({},this.options),{[BG]:!0}),this.resolutionNote)}updateEndpoint($,q){if(this.options=q,this.endpoint=$,this.latestState!==H0.ConnectivityState.IDLE)this.startConnecting()}getConnectivityState(){return this.latestState}getPicker(){return this.latestPicker}getEndpoint(){return this.endpoint}exitIdle(){this.pickFirstBalancer.exitIdle()}destroy(){this.pickFirstBalancer.destroy()}}PG.LeafLoadBalancer=RG;function OP(){(0,pX.registerLoadBalancerType)(oY,tT,uq),(0,pX.registerDefaultLoadBalancerType)(oY)}});var CG=B((wG)=>{Object.defineProperty(wG,"__esModule",{value:!0});wG.FileWatcherCertificateProvider=void 0;var yP=e("fs"),jP=Z0(),vP=n(),xP=e("util"),kP="certificate_provider";function eT($){jP.trace(vP.LogVerbosity.DEBUG,kP,$)}var lX=(0,xP.promisify)(yP.readFile);class LG{constructor($){if(this.config=$,this.refreshTimer=null,this.fileResultPromise=null,this.latestCaUpdate=void 0,this.caListeners=new Set,this.latestIdentityUpdate=void 0,this.identityListeners=new Set,this.lastUpdateTime=null,$.certificateFile===void 0!==($.privateKeyFile===void 0))throw Error("certificateFile and privateKeyFile must be set or unset together");if($.certificateFile===void 0&&$.caCertificateFile===void 0)throw Error("At least one of certificateFile and caCertificateFile must be set");eT("File watcher constructed with config "+JSON.stringify($))}updateCertificates(){if(this.fileResultPromise)return;this.fileResultPromise=Promise.allSettled([this.config.certificateFile?lX(this.config.certificateFile):Promise.reject(),this.config.privateKeyFile?lX(this.config.privateKeyFile):Promise.reject(),this.config.caCertificateFile?lX(this.config.caCertificateFile):Promise.reject()]),this.fileResultPromise.then(([$,q,Y])=>{if(!this.refreshTimer)return;if(eT("File watcher read certificates certificate "+$.status+", privateKey "+q.status+", CA certificate "+Y.status),this.lastUpdateTime=new Date,this.fileResultPromise=null,$.status==="fulfilled"&&q.status==="fulfilled")this.latestIdentityUpdate={certificate:$.value,privateKey:q.value};else this.latestIdentityUpdate=null;if(Y.status==="fulfilled")this.latestCaUpdate={caCertificate:Y.value};else this.latestCaUpdate=null;for(let T of this.identityListeners)T(this.latestIdentityUpdate);for(let T of this.caListeners)T(this.latestCaUpdate)}),eT("File watcher initiated certificate update")}maybeStartWatchingFiles(){if(!this.refreshTimer){let $=this.lastUpdateTime?new Date().getTime()-this.lastUpdateTime.getTime():1/0;if($>this.config.refreshIntervalMs)this.updateCertificates();if($>this.config.refreshIntervalMs*2)this.latestCaUpdate=void 0,this.latestIdentityUpdate=void 0;this.refreshTimer=setInterval(()=>this.updateCertificates(),this.config.refreshIntervalMs),eT("File watcher started watching")}}maybeStopWatchingFiles(){if(this.caListeners.size===0&&this.identityListeners.size===0){if(this.fileResultPromise=null,this.refreshTimer)clearInterval(this.refreshTimer),this.refreshTimer=null}}addCaCertificateListener($){if(this.caListeners.add($),this.maybeStartWatchingFiles(),this.latestCaUpdate!==void 0)process.nextTick($,this.latestCaUpdate)}removeCaCertificateListener($){this.caListeners.delete($),this.maybeStopWatchingFiles()}addIdentityCertificateListener($){if(this.identityListeners.add($),this.maybeStartWatchingFiles(),this.latestIdentityUpdate!==void 0)process.nextTick($,this.latestIdentityUpdate)}removeIdentityCertificateListener($){this.identityListeners.delete($),this.maybeStopWatchingFiles()}}wG.FileWatcherCertificateProvider=LG});var rX=B((s)=>{Object.defineProperty(s,"__esModule",{value:!0});s.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX=s.createCertificateProviderChannelCredentials=s.FileWatcherCertificateProvider=s.createCertificateProviderServerCredentials=s.createServerCredentialsWithInterceptors=s.BaseSubchannelWrapper=s.registerAdminService=s.FilterStackFactory=s.BaseFilter=s.statusOrFromError=s.statusOrFromValue=s.PickResultType=s.QueuePicker=s.UnavailablePicker=s.ChildLoadBalancerHandler=s.EndpointMap=s.endpointHasAddress=s.endpointToString=s.subchannelAddressToString=s.LeafLoadBalancer=s.isLoadBalancerNameRegistered=s.parseLoadBalancingConfig=s.selectLbConfigFromList=s.registerLoadBalancerType=s.createChildChannelControlHelper=s.BackoffTimeout=s.parseDuration=s.durationToMs=s.splitHostPort=s.uriToString=s.CHANNEL_ARGS_CONFIG_SELECTOR_KEY=s.createResolver=s.registerResolver=s.log=s.trace=void 0;var yG=Z0();Object.defineProperty(s,"trace",{enumerable:!0,get:function(){return yG.trace}});Object.defineProperty(s,"log",{enumerable:!0,get:function(){return yG.log}});var nX=H1();Object.defineProperty(s,"registerResolver",{enumerable:!0,get:function(){return nX.registerResolver}});Object.defineProperty(s,"createResolver",{enumerable:!0,get:function(){return nX.createResolver}});Object.defineProperty(s,"CHANNEL_ARGS_CONFIG_SELECTOR_KEY",{enumerable:!0,get:function(){return nX.CHANNEL_ARGS_CONFIG_SELECTOR_KEY}});var jG=p0();Object.defineProperty(s,"uriToString",{enumerable:!0,get:function(){return jG.uriToString}});Object.defineProperty(s,"splitHostPort",{enumerable:!0,get:function(){return jG.splitHostPort}});var vG=rY();Object.defineProperty(s,"durationToMs",{enumerable:!0,get:function(){return vG.durationToMs}});Object.defineProperty(s,"parseDuration",{enumerable:!0,get:function(){return vG.parseDuration}});var hP=Fq();Object.defineProperty(s,"BackoffTimeout",{enumerable:!0,get:function(){return hP.BackoffTimeout}});var tY=V$();Object.defineProperty(s,"createChildChannelControlHelper",{enumerable:!0,get:function(){return tY.createChildChannelControlHelper}});Object.defineProperty(s,"registerLoadBalancerType",{enumerable:!0,get:function(){return tY.registerLoadBalancerType}});Object.defineProperty(s,"selectLbConfigFromList",{enumerable:!0,get:function(){return tY.selectLbConfigFromList}});Object.defineProperty(s,"parseLoadBalancingConfig",{enumerable:!0,get:function(){return tY.parseLoadBalancingConfig}});Object.defineProperty(s,"isLoadBalancerNameRegistered",{enumerable:!0,get:function(){return tY.isLoadBalancerNameRegistered}});var _P=sY();Object.defineProperty(s,"LeafLoadBalancer",{enumerable:!0,get:function(){return _P.LeafLoadBalancer}});var $8=i0();Object.defineProperty(s,"subchannelAddressToString",{enumerable:!0,get:function(){return $8.subchannelAddressToString}});Object.defineProperty(s,"endpointToString",{enumerable:!0,get:function(){return $8.endpointToString}});Object.defineProperty(s,"endpointHasAddress",{enumerable:!0,get:function(){return $8.endpointHasAddress}});Object.defineProperty(s,"EndpointMap",{enumerable:!0,get:function(){return $8.EndpointMap}});var gP=n6();Object.defineProperty(s,"ChildLoadBalancerHandler",{enumerable:!0,get:function(){return gP.ChildLoadBalancerHandler}});var iX=s1();Object.defineProperty(s,"UnavailablePicker",{enumerable:!0,get:function(){return iX.UnavailablePicker}});Object.defineProperty(s,"QueuePicker",{enumerable:!0,get:function(){return iX.QueuePicker}});Object.defineProperty(s,"PickResultType",{enumerable:!0,get:function(){return iX.PickResultType}});var xG=m$();Object.defineProperty(s,"statusOrFromValue",{enumerable:!0,get:function(){return xG.statusOrFromValue}});Object.defineProperty(s,"statusOrFromError",{enumerable:!0,get:function(){return xG.statusOrFromError}});var mP=QX();Object.defineProperty(s,"BaseFilter",{enumerable:!0,get:function(){return mP.BaseFilter}});var fP=xT();Object.defineProperty(s,"FilterStackFactory",{enumerable:!0,get:function(){return fP.FilterStackFactory}});var bP=r6();Object.defineProperty(s,"registerAdminService",{enumerable:!0,get:function(){return bP.registerAdminService}});var uP=nY();Object.defineProperty(s,"BaseSubchannelWrapper",{enumerable:!0,get:function(){return uP.BaseSubchannelWrapper}});var kG=nT();Object.defineProperty(s,"createServerCredentialsWithInterceptors",{enumerable:!0,get:function(){return kG.createServerCredentialsWithInterceptors}});Object.defineProperty(s,"createCertificateProviderServerCredentials",{enumerable:!0,get:function(){return kG.createCertificateProviderServerCredentials}});var dP=CG();Object.defineProperty(s,"FileWatcherCertificateProvider",{enumerable:!0,get:function(){return dP.FileWatcherCertificateProvider}});var cP=Dq();Object.defineProperty(s,"createCertificateProviderChannelCredentials",{enumerable:!0,get:function(){return cP.createCertificateProviderChannelCredentials}});var pP=wX();Object.defineProperty(s,"SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX",{enumerable:!0,get:function(){return pP.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX}})});var gG=B((_G)=>{Object.defineProperty(_G,"__esModule",{value:!0});_G.setup=rP;var nP=H1(),iP=m$();class hG{constructor($,q,Y){this.listener=q,this.hasReturnedResult=!1,this.endpoints=[];let T;if($.authority==="")T="/"+$.path;else T=$.path;this.endpoints=[{addresses:[{path:T}]}]}updateResolution(){if(!this.hasReturnedResult)this.hasReturnedResult=!0,process.nextTick(this.listener,(0,iP.statusOrFromValue)(this.endpoints),{},null,"")}destroy(){this.hasReturnedResult=!1}static getDefaultAuthority($){return"localhost"}}function rP(){(0,nP.registerResolver)("unix",hG)}});var pG=B((cG)=>{Object.defineProperty(cG,"__esModule",{value:!0});cG.setup=$O;var mG=e("net"),fG=m$(),q8=n(),aX=P0(),bG=H1(),oP=i0(),uG=p0(),sP=Z0(),tP="ip_resolver";function dG($){sP.trace(q8.LogVerbosity.DEBUG,tP,$)}var oX="ipv4",sX="ipv6",eP=443;class tX{constructor($,q,Y){var T;this.listener=q,this.endpoints=[],this.error=null,this.hasReturnedResult=!1,dG("Resolver constructed for target "+(0,uG.uriToString)($));let X=[];if(!($.scheme===oX||$.scheme===sX)){this.error={code:q8.Status.UNAVAILABLE,details:`Unrecognized scheme ${$.scheme} in IP resolver`,metadata:new aX.Metadata};return}let J=$.path.split(",");for(let Q of J){let U=(0,uG.splitHostPort)(Q);if(U===null){this.error={code:q8.Status.UNAVAILABLE,details:`Failed to parse ${$.scheme} address ${Q}`,metadata:new aX.Metadata};return}if($.scheme===oX&&!(0,mG.isIPv4)(U.host)||$.scheme===sX&&!(0,mG.isIPv6)(U.host)){this.error={code:q8.Status.UNAVAILABLE,details:`Failed to parse ${$.scheme} address ${Q}`,metadata:new aX.Metadata};return}X.push({host:U.host,port:(T=U.port)!==null&&T!==void 0?T:eP})}this.endpoints=X.map((Q)=>({addresses:[Q]})),dG("Parsed "+$.scheme+" address list "+X.map(oP.subchannelAddressToString))}updateResolution(){if(!this.hasReturnedResult)this.hasReturnedResult=!0,process.nextTick(()=>{if(this.error)this.listener((0,fG.statusOrFromError)(this.error),{},null,"");else this.listener((0,fG.statusOrFromValue)(this.endpoints),{},null,"")})}destroy(){this.hasReturnedResult=!1}static getDefaultAuthority($){return $.path.split(",")[0]}}function $O(){(0,bG.registerResolver)(oX,tX),(0,bG.registerResolver)(sX,tX)}});var sG=B((aG)=>{Object.defineProperty(aG,"__esModule",{value:!0});aG.RoundRobinLoadBalancer=void 0;aG.setup=UO;var iG=V$(),k0=l0(),eY=s1(),YO=Z0(),TO=n(),lG=i0(),XO=sY(),JO="round_robin";function nG($){YO.trace(TO.LogVerbosity.DEBUG,JO,$)}var Y8="round_robin";class T8{getLoadBalancerName(){return Y8}constructor(){}toJsonObject(){return{[Y8]:{}}}static createFromJson($){return new T8}}class rG{constructor($,q=0){this.children=$,this.nextIndex=q}pick($){let q=this.children[this.nextIndex].picker;return this.nextIndex=(this.nextIndex+1)%this.children.length,q.pick($)}peekNextEndpoint(){return this.children[this.nextIndex].endpoint}}function QO($,q){return[...$.slice(q),...$.slice(0,q)]}class eX{constructor($){this.channelControlHelper=$,this.children=[],this.currentState=k0.ConnectivityState.IDLE,this.currentReadyPicker=null,this.updatesPaused=!1,this.lastError=null,this.childChannelControlHelper=(0,iG.createChildChannelControlHelper)($,{updateState:(q,Y,T)=>{if(this.currentState===k0.ConnectivityState.READY&&q!==k0.ConnectivityState.READY)this.channelControlHelper.requestReresolution();if(T)this.lastError=T;this.calculateAndUpdateState()}})}countChildrenWithState($){return this.children.filter((q)=>q.getConnectivityState()===$).length}calculateAndUpdateState(){if(this.updatesPaused)return;if(this.countChildrenWithState(k0.ConnectivityState.READY)>0){let $=this.children.filter((Y)=>Y.getConnectivityState()===k0.ConnectivityState.READY),q=0;if(this.currentReadyPicker!==null){let Y=this.currentReadyPicker.peekNextEndpoint();if(q=$.findIndex((T)=>(0,lG.endpointEqual)(T.getEndpoint(),Y)),q<0)q=0}this.updateState(k0.ConnectivityState.READY,new rG($.map((Y)=>({endpoint:Y.getEndpoint(),picker:Y.getPicker()})),q),null)}else if(this.countChildrenWithState(k0.ConnectivityState.CONNECTING)>0)this.updateState(k0.ConnectivityState.CONNECTING,new eY.QueuePicker(this),null);else if(this.countChildrenWithState(k0.ConnectivityState.TRANSIENT_FAILURE)>0){let $=`round_robin: No connection established. Last error: ${this.lastError}`;this.updateState(k0.ConnectivityState.TRANSIENT_FAILURE,new eY.UnavailablePicker({details:$}),$)}else this.updateState(k0.ConnectivityState.IDLE,new eY.QueuePicker(this),null);for(let $ of this.children)if($.getConnectivityState()===k0.ConnectivityState.IDLE)$.exitIdle()}updateState($,q,Y){if(nG(k0.ConnectivityState[this.currentState]+" -> "+k0.ConnectivityState[$]),$===k0.ConnectivityState.READY)this.currentReadyPicker=q;else this.currentReadyPicker=null;this.currentState=$,this.channelControlHelper.updateState($,q,Y)}resetSubchannelList(){for(let $ of this.children)$.destroy();this.children=[]}updateAddressList($,q,Y,T){if(!(q instanceof T8))return!1;if(!$.ok){if(this.children.length===0)this.updateState(k0.ConnectivityState.TRANSIENT_FAILURE,new eY.UnavailablePicker($.error),$.error.details);return!0}let X=Math.random()*$.value.length|0,J=QO($.value,X);if(this.resetSubchannelList(),J.length===0){let Q=`No addresses resolved. Resolution note: ${T}`;this.updateState(k0.ConnectivityState.TRANSIENT_FAILURE,new eY.UnavailablePicker({details:Q}),Q)}nG("Connect to endpoint list "+J.map(lG.endpointToString)),this.updatesPaused=!0,this.children=J.map((Q)=>new XO.LeafLoadBalancer(Q,this.childChannelControlHelper,Y,T));for(let Q of this.children)Q.startConnecting();return this.updatesPaused=!1,this.calculateAndUpdateState(),!0}exitIdle(){}resetBackoff(){}destroy(){this.resetSubchannelList()}getTypeName(){return Y8}}aG.RoundRobinLoadBalancer=eX;function UO(){(0,iG.registerLoadBalancerType)(Y8,eX,T8)}});var JE=B((TE)=>{var $5;Object.defineProperty(TE,"__esModule",{value:!0});TE.OutlierDetectionLoadBalancer=TE.OutlierDetectionLoadBalancingConfig=void 0;TE.setup=HO;var KO=l0(),tG=n(),s$=rY(),eG=rX(),AO=V$(),WO=n6(),GO=s1(),q5=i0(),EO=nY(),VO=Z0(),DO="outlier_detection";function S0($){VO.trace(tG.LogVerbosity.DEBUG,DO,$)}var X5="outlier_detection",FO=(($5=process.env.GRPC_EXPERIMENTAL_ENABLE_OUTLIER_DETECTION)!==null&&$5!==void 0?$5:"true")==="true",IO={stdev_factor:1900,enforcement_percentage:100,minimum_hosts:5,request_volume:100},NO={threshold:85,enforcement_percentage:100,minimum_hosts:5,request_volume:50};function dq($,q,Y,T){if(q in $&&$[q]!==void 0&&typeof $[q]!==Y){let X=T?`${T}.${q}`:q;throw Error(`outlier detection config ${X} parse error: expected ${Y}, got ${typeof $[q]}`)}}function Y5($,q,Y){let T=Y?`${Y}.${q}`:q;if(q in $&&$[q]!==void 0){if(!(0,s$.isDuration)($[q]))throw Error(`outlier detection config ${T} parse error: expected Duration, got ${typeof $[q]}`);if(!($[q].seconds>=0&&$[q].seconds<=315576000000&&$[q].nanos>=0&&$[q].nanos<=999999999))throw Error(`outlier detection config ${T} parse error: values out of range for non-negative Duaration`)}}function X8($,q,Y){let T=Y?`${Y}.${q}`:q;if(dq($,q,"number",Y),q in $&&$[q]!==void 0&&!($[q]>=0&&$[q]<=100))throw Error(`outlier detection config ${T} parse error: value out of range for percentage (0-100)`)}class $6{constructor($,q,Y,T,X,J,Q){if(this.childPolicy=Q,Q.getLoadBalancerName()==="pick_first")throw Error("outlier_detection LB policy cannot have a pick_first child policy");this.intervalMs=$!==null&&$!==void 0?$:1e4,this.baseEjectionTimeMs=q!==null&&q!==void 0?q:30000,this.maxEjectionTimeMs=Y!==null&&Y!==void 0?Y:300000,this.maxEjectionPercent=T!==null&&T!==void 0?T:10,this.successRateEjection=X?Object.assign(Object.assign({},IO),X):null,this.failurePercentageEjection=J?Object.assign(Object.assign({},NO),J):null}getLoadBalancerName(){return X5}toJsonObject(){var $,q;return{outlier_detection:{interval:(0,s$.msToDuration)(this.intervalMs),base_ejection_time:(0,s$.msToDuration)(this.baseEjectionTimeMs),max_ejection_time:(0,s$.msToDuration)(this.maxEjectionTimeMs),max_ejection_percent:this.maxEjectionPercent,success_rate_ejection:($=this.successRateEjection)!==null&&$!==void 0?$:void 0,failure_percentage_ejection:(q=this.failurePercentageEjection)!==null&&q!==void 0?q:void 0,child_policy:[this.childPolicy.toJsonObject()]}}}getIntervalMs(){return this.intervalMs}getBaseEjectionTimeMs(){return this.baseEjectionTimeMs}getMaxEjectionTimeMs(){return this.maxEjectionTimeMs}getMaxEjectionPercent(){return this.maxEjectionPercent}getSuccessRateEjectionConfig(){return this.successRateEjection}getFailurePercentageEjectionConfig(){return this.failurePercentageEjection}getChildPolicy(){return this.childPolicy}static createFromJson($){var q;if(Y5($,"interval"),Y5($,"base_ejection_time"),Y5($,"max_ejection_time"),X8($,"max_ejection_percent"),"success_rate_ejection"in $&&$.success_rate_ejection!==void 0){if(typeof $.success_rate_ejection!=="object")throw Error("outlier detection config success_rate_ejection must be an object");dq($.success_rate_ejection,"stdev_factor","number","success_rate_ejection"),X8($.success_rate_ejection,"enforcement_percentage","success_rate_ejection"),dq($.success_rate_ejection,"minimum_hosts","number","success_rate_ejection"),dq($.success_rate_ejection,"request_volume","number","success_rate_ejection")}if("failure_percentage_ejection"in $&&$.failure_percentage_ejection!==void 0){if(typeof $.failure_percentage_ejection!=="object")throw Error("outlier detection config failure_percentage_ejection must be an object");X8($.failure_percentage_ejection,"threshold","failure_percentage_ejection"),X8($.failure_percentage_ejection,"enforcement_percentage","failure_percentage_ejection"),dq($.failure_percentage_ejection,"minimum_hosts","number","failure_percentage_ejection"),dq($.failure_percentage_ejection,"request_volume","number","failure_percentage_ejection")}if(!("child_policy"in $)||!Array.isArray($.child_policy))throw Error("outlier detection config child_policy must be an array");let Y=(0,AO.selectLbConfigFromList)($.child_policy);if(!Y)throw Error("outlier detection config child_policy: no valid recognized policy found");return new $6($.interval?(0,s$.durationToMs)($.interval):null,$.base_ejection_time?(0,s$.durationToMs)($.base_ejection_time):null,$.max_ejection_time?(0,s$.durationToMs)($.max_ejection_time):null,(q=$.max_ejection_percent)!==null&&q!==void 0?q:null,$.success_rate_ejection,$.failure_percentage_ejection,Y)}}TE.OutlierDetectionLoadBalancingConfig=$6;class $E extends EO.BaseSubchannelWrapper{constructor($,q){super($);this.mapEntry=q,this.refCount=0}ref(){this.child.ref(),this.refCount+=1}unref(){if(this.child.unref(),this.refCount-=1,this.refCount<=0){if(this.mapEntry){let $=this.mapEntry.subchannelWrappers.indexOf(this);if($>=0)this.mapEntry.subchannelWrappers.splice($,1)}}}eject(){this.setHealthy(!1)}uneject(){this.setHealthy(!0)}getMapEntry(){return this.mapEntry}getWrappedSubchannel(){return this.child}}function T5(){return{success:0,failure:0}}class qE{constructor(){this.activeBucket=T5(),this.inactiveBucket=T5()}addSuccess(){this.activeBucket.success+=1}addFailure(){this.activeBucket.failure+=1}switchBuckets(){this.inactiveBucket=this.activeBucket,this.activeBucket=T5()}getLastSuccesses(){return this.inactiveBucket.success}getLastFailures(){return this.inactiveBucket.failure}}class YE{constructor($,q){this.wrappedPicker=$,this.countCalls=q}pick($){let q=this.wrappedPicker.pick($);if(q.pickResultType===GO.PickResultType.COMPLETE){let Y=q.subchannel,T=Y.getMapEntry();if(T){let X=q.onCallEnded;if(this.countCalls)X=(J,Q,U)=>{var Z;if(J===tG.Status.OK)T.counter.addSuccess();else T.counter.addFailure();(Z=q.onCallEnded)===null||Z===void 0||Z.call(q,J,Q,U)};return Object.assign(Object.assign({},q),{subchannel:Y.getWrappedSubchannel(),onCallEnded:X})}else return Object.assign(Object.assign({},q),{subchannel:Y.getWrappedSubchannel()})}else return q}}class J5{constructor($){this.entryMap=new q5.EndpointMap,this.latestConfig=null,this.timerStartTime=null,this.childBalancer=new WO.ChildLoadBalancerHandler((0,eG.createChildChannelControlHelper)($,{createSubchannel:(q,Y)=>{let T=$.createSubchannel(q,Y),X=this.entryMap.getForSubchannelAddress(q),J=new $E(T,X);if((X===null||X===void 0?void 0:X.currentEjectionTimestamp)!==null)J.eject();return X===null||X===void 0||X.subchannelWrappers.push(J),J},updateState:(q,Y,T)=>{if(q===KO.ConnectivityState.READY)$.updateState(q,new YE(Y,this.isCountingEnabled()),T);else $.updateState(q,Y,T)}})),this.ejectionTimer=setInterval(()=>{},0),clearInterval(this.ejectionTimer)}isCountingEnabled(){return this.latestConfig!==null&&(this.latestConfig.getSuccessRateEjectionConfig()!==null||this.latestConfig.getFailurePercentageEjectionConfig()!==null)}getCurrentEjectionPercent(){let $=0;for(let q of this.entryMap.values())if(q.currentEjectionTimestamp!==null)$+=1;return $*100/this.entryMap.size}runSuccessRateCheck($){if(!this.latestConfig)return;let q=this.latestConfig.getSuccessRateEjectionConfig();if(!q)return;S0("Running success rate check");let Y=q.request_volume,T=0,X=[];for(let[A,W]of this.entryMap.entries()){let G=W.counter.getLastSuccesses(),V=W.counter.getLastFailures();if(S0("Stats for "+(0,q5.endpointToString)(A)+": successes="+G+" failures="+V+" targetRequestVolume="+Y),G+V>=Y)T+=1,X.push(G/(G+V))}if(S0("Found "+T+" success rate candidates; currentEjectionPercent="+this.getCurrentEjectionPercent()+" successRates=["+X+"]"),T<q.minimum_hosts)return;let J=X.reduce((A,W)=>A+W)/X.length,Q=0;for(let A of X){let W=A-J;Q+=W*W}let U=Q/X.length,Z=Math.sqrt(U),K=J-Z*(q.stdev_factor/1000);S0("stdev="+Z+" ejectionThreshold="+K);for(let[A,W]of this.entryMap.entries()){if(this.getCurrentEjectionPercent()>=this.latestConfig.getMaxEjectionPercent())break;let G=W.counter.getLastSuccesses(),V=W.counter.getLastFailures();if(G+V<Y)continue;let F=G/(G+V);if(S0("Checking candidate "+A+" successRate="+F),F<K){let N=Math.random()*100;if(S0("Candidate "+A+" randomNumber="+N+" enforcement_percentage="+q.enforcement_percentage),N<q.enforcement_percentage)S0("Ejecting candidate "+A),this.eject(W,$)}}}runFailurePercentageCheck($){if(!this.latestConfig)return;let q=this.latestConfig.getFailurePercentageEjectionConfig();if(!q)return;S0("Running failure percentage check. threshold="+q.threshold+" request volume threshold="+q.request_volume);let Y=0;for(let T of this.entryMap.values()){let X=T.counter.getLastSuccesses(),J=T.counter.getLastFailures();if(X+J>=q.request_volume)Y+=1}if(Y<q.minimum_hosts)return;for(let[T,X]of this.entryMap.entries()){if(this.getCurrentEjectionPercent()>=this.latestConfig.getMaxEjectionPercent())break;let J=X.counter.getLastSuccesses(),Q=X.counter.getLastFailures();if(S0("Candidate successes="+J+" failures="+Q),J+Q<q.request_volume)continue;if(Q*100/(Q+J)>q.threshold){let Z=Math.random()*100;if(S0("Candidate "+T+" randomNumber="+Z+" enforcement_percentage="+q.enforcement_percentage),Z<q.enforcement_percentage)S0("Ejecting candidate "+T),this.eject(X,$)}}}eject($,q){$.currentEjectionTimestamp=new Date,$.ejectionTimeMultiplier+=1;for(let Y of $.subchannelWrappers)Y.eject()}uneject($){$.currentEjectionTimestamp=null;for(let q of $.subchannelWrappers)q.uneject()}switchAllBuckets(){for(let $ of this.entryMap.values())$.counter.switchBuckets()}startTimer($){var q,Y;this.ejectionTimer=setTimeout(()=>this.runChecks(),$),(Y=(q=this.ejectionTimer).unref)===null||Y===void 0||Y.call(q)}runChecks(){let $=new Date;if(S0("Ejection timer running"),this.switchAllBuckets(),!this.latestConfig)return;this.timerStartTime=$,this.startTimer(this.latestConfig.getIntervalMs()),this.runSuccessRateCheck($),this.runFailurePercentageCheck($);for(let[q,Y]of this.entryMap.entries())if(Y.currentEjectionTimestamp===null){if(Y.ejectionTimeMultiplier>0)Y.ejectionTimeMultiplier-=1}else{let T=this.latestConfig.getBaseEjectionTimeMs(),X=this.latestConfig.getMaxEjectionTimeMs(),J=new Date(Y.currentEjectionTimestamp.getTime());if(J.setMilliseconds(J.getMilliseconds()+Math.min(T*Y.ejectionTimeMultiplier,Math.max(T,X))),J<new Date)S0("Unejecting "+q),this.uneject(Y)}}updateAddressList($,q,Y,T){if(!(q instanceof $6))return!1;if(S0("Received update with config: "+JSON.stringify(q.toJsonObject(),void 0,2)),$.ok){for(let J of $.value)if(!this.entryMap.has(J))S0("Adding map entry for "+(0,q5.endpointToString)(J)),this.entryMap.set(J,{counter:new qE,currentEjectionTimestamp:null,ejectionTimeMultiplier:0,subchannelWrappers:[]});this.entryMap.deleteMissing($.value)}let X=q.getChildPolicy();if(this.childBalancer.updateAddressList($,X,Y,T),q.getSuccessRateEjectionConfig()||q.getFailurePercentageEjectionConfig())if(this.timerStartTime){S0("Previous timer existed. Replacing timer"),clearTimeout(this.ejectionTimer);let J=q.getIntervalMs()-(new Date().getTime()-this.timerStartTime.getTime());this.startTimer(J)}else S0("Starting new timer"),this.timerStartTime=new Date,this.startTimer(q.getIntervalMs()),this.switchAllBuckets();else{S0("Counting disabled. Cancelling timer."),this.timerStartTime=null,clearTimeout(this.ejectionTimer);for(let J of this.entryMap.values())this.uneject(J),J.ejectionTimeMultiplier=0}return this.latestConfig=q,!0}exitIdle(){this.childBalancer.exitIdle()}resetBackoff(){this.childBalancer.resetBackoff()}destroy(){clearTimeout(this.ejectionTimer),this.childBalancer.destroy()}getTypeName(){return X5}}TE.OutlierDetectionLoadBalancer=J5;function HO(){if(FO)(0,eG.registerLoadBalancerType)(X5,J5,$6)}});var KE=B((UE)=>{Object.defineProperty(UE,"__esModule",{value:!0});UE.PriorityQueue=void 0;var cq=0,Q5=($)=>Math.floor($/2),J8=($)=>$*2+1,q6=($)=>$*2+2;class QE{constructor($=(q,Y)=>q>Y){this.comparator=$,this.heap=[]}size(){return this.heap.length}isEmpty(){return this.size()==0}peek(){return this.heap[cq]}push(...$){return $.forEach((q)=>{this.heap.push(q),this.siftUp()}),this.size()}pop(){let $=this.peek(),q=this.size()-1;if(q>cq)this.swap(cq,q);return this.heap.pop(),this.siftDown(),$}replace($){let q=this.peek();return this.heap[cq]=$,this.siftDown(),q}greater($,q){return this.comparator(this.heap[$],this.heap[q])}swap($,q){[this.heap[$],this.heap[q]]=[this.heap[q],this.heap[$]]}siftUp(){let $=this.size()-1;while($>cq&&this.greater($,Q5($)))this.swap($,Q5($)),$=Q5($)}siftDown(){let $=cq;while(J8($)<this.size()&&this.greater(J8($),$)||q6($)<this.size()&&this.greater(q6($),$)){let q=q6($)<this.size()&&this.greater(q6($),J8($))?q6($):J8($);this.swap($,q),$=q}}}UE.PriorityQueue=QE});var NE=B((FE)=>{Object.defineProperty(FE,"__esModule",{value:!0});FE.WeightedRoundRobinLoadBalancingConfig=void 0;FE.setup=vO;var C0=l0(),BO=n(),Y1=rY(),GE=V$(),RO=sY(),PO=Z0(),EE=rT(),pq=s1(),OO=KE(),AE=i0(),LO="weighted_round_robin";function U5($){PO.trace(BO.LogVerbosity.DEBUG,LO,$)}var Z5="weighted_round_robin",wO=1e4,SO=1e4,CO=180000,yO=1000,jO=1;function WE($,q,Y){if(q in $&&$[q]!==void 0&&typeof $[q]!==Y)throw Error(`weighted round robin config ${q} parse error: expected ${Y}, got ${typeof $[q]}`)}function Q8($,q){if(q in $&&$[q]!==void 0&&$[q]!==null){let Y;if((0,Y1.isDuration)($[q]))Y=$[q];else if((0,Y1.isDurationMessage)($[q]))Y=(0,Y1.durationMessageToDuration)($[q]);else if(typeof $[q]==="string"){let T=(0,Y1.parseDuration)($[q]);if(!T)throw Error(`weighted round robin config ${q}: failed to parse duration string ${$[q]}`);Y=T}else throw Error(`weighted round robin config ${q}: expected duration, got ${typeof $[q]}`);return(0,Y1.durationToMs)(Y)}return null}class Y6{constructor($,q,Y,T,X,J){this.enableOobLoadReport=$!==null&&$!==void 0?$:!1,this.oobLoadReportingPeriodMs=q!==null&&q!==void 0?q:wO,this.blackoutPeriodMs=Y!==null&&Y!==void 0?Y:SO,this.weightExpirationPeriodMs=T!==null&&T!==void 0?T:CO,this.weightUpdatePeriodMs=Math.max(X!==null&&X!==void 0?X:yO,100),this.errorUtilizationPenalty=J!==null&&J!==void 0?J:jO}getLoadBalancerName(){return Z5}toJsonObject(){return{enable_oob_load_report:this.enableOobLoadReport,oob_load_reporting_period:(0,Y1.durationToString)((0,Y1.msToDuration)(this.oobLoadReportingPeriodMs)),blackout_period:(0,Y1.durationToString)((0,Y1.msToDuration)(this.blackoutPeriodMs)),weight_expiration_period:(0,Y1.durationToString)((0,Y1.msToDuration)(this.weightExpirationPeriodMs)),weight_update_period:(0,Y1.durationToString)((0,Y1.msToDuration)(this.weightUpdatePeriodMs)),error_utilization_penalty:this.errorUtilizationPenalty}}static createFromJson($){if(WE($,"enable_oob_load_report","boolean"),WE($,"error_utilization_penalty","number"),$.error_utilization_penalty<0)throw Error("weighted round robin config error_utilization_penalty < 0");return new Y6($.enable_oob_load_report,Q8($,"oob_load_reporting_period"),Q8($,"blackout_period"),Q8($,"weight_expiration_period"),Q8($,"weight_update_period"),$.error_utilization_penalty)}getEnableOobLoadReport(){return this.enableOobLoadReport}getOobLoadReportingPeriodMs(){return this.oobLoadReportingPeriodMs}getBlackoutPeriodMs(){return this.blackoutPeriodMs}getWeightExpirationPeriodMs(){return this.weightExpirationPeriodMs}getWeightUpdatePeriodMs(){return this.weightUpdatePeriodMs}getErrorUtilizationPenalty(){return this.errorUtilizationPenalty}}FE.WeightedRoundRobinLoadBalancingConfig=Y6;class VE{constructor($,q){this.metricsHandler=q,this.queue=new OO.PriorityQueue((X,J)=>X.deadline<J.deadline);let Y=$.filter((X)=>X.weight>0),T;if(Y.length<2)T=1;else{let X=0;for(let{weight:J}of Y)X+=J;T=X/Y.length}for(let X of $){let J=X.weight>0?1/X.weight:T;this.queue.push({endpointName:X.endpointName,picker:X.picker,period:J,deadline:Math.random()*J})}}pick($){let q=this.queue.pop();this.queue.push(Object.assign(Object.assign({},q),{deadline:q.deadline+q.period}));let Y=q.picker.pick($);if(Y.pickResultType===pq.PickResultType.COMPLETE)if(this.metricsHandler)return Object.assign(Object.assign({},Y),{onCallEnded:(0,EE.createMetricsReader)((T)=>this.metricsHandler(T,q.endpointName),Y.onCallEnded)});else{let T=Y.subchannel;return Object.assign(Object.assign({},Y),{subchannel:T.getWrappedSubchannel()})}else return Y}}class DE{constructor($){this.channelControlHelper=$,this.latestConfig=null,this.children=new Map,this.currentState=C0.ConnectivityState.IDLE,this.updatesPaused=!1,this.lastError=null,this.weightUpdateTimer=null}countChildrenWithState($){let q=0;for(let Y of this.children.values())if(Y.child.getConnectivityState()===$)q+=1;return q}updateWeight($,q){var Y,T;let{rps_fractional:X,application_utilization:J}=q;if(J>0&&X>0)J+=q.eps/X*((T=(Y=this.latestConfig)===null||Y===void 0?void 0:Y.getErrorUtilizationPenalty())!==null&&T!==void 0?T:0);let Q=J===0?0:X/J;if(Q===0)return;let U=new Date;if($.nonEmptySince===null)$.nonEmptySince=U;$.lastUpdated=U,$.weight=Q}getWeight($){if(!this.latestConfig)return 0;let q=new Date().getTime();if(q-$.lastUpdated.getTime()>=this.latestConfig.getWeightExpirationPeriodMs())return $.nonEmptySince=null,0;let Y=this.latestConfig.getBlackoutPeriodMs();if(Y>0&&($.nonEmptySince===null||q-$.nonEmptySince.getTime()<Y))return 0;return $.weight}calculateAndUpdateState(){if(this.updatesPaused||!this.latestConfig)return;if(this.countChildrenWithState(C0.ConnectivityState.READY)>0){let $=[];for(let[Y,T]of this.children){if(T.child.getConnectivityState()!==C0.ConnectivityState.READY)continue;$.push({endpointName:Y,picker:T.child.getPicker(),weight:this.getWeight(T)})}U5("Created picker with weights: "+$.map((Y)=>Y.endpointName+":"+Y.weight).join(","));let q;if(!this.latestConfig.getEnableOobLoadReport())q=(Y,T)=>{let X=this.children.get(T);if(X)this.updateWeight(X,Y)};else q=null;this.updateState(C0.ConnectivityState.READY,new VE($,q),null)}else if(this.countChildrenWithState(C0.ConnectivityState.CONNECTING)>0)this.updateState(C0.ConnectivityState.CONNECTING,new pq.QueuePicker(this),null);else if(this.countChildrenWithState(C0.ConnectivityState.TRANSIENT_FAILURE)>0){let $=`weighted_round_robin: No connection established. Last error: ${this.lastError}`;this.updateState(C0.ConnectivityState.TRANSIENT_FAILURE,new pq.UnavailablePicker({details:$}),$)}else this.updateState(C0.ConnectivityState.IDLE,new pq.QueuePicker(this),null);for(let{child:$}of this.children.values())if($.getConnectivityState()===C0.ConnectivityState.IDLE)$.exitIdle()}updateState($,q,Y){U5(C0.ConnectivityState[this.currentState]+" -> "+C0.ConnectivityState[$]),this.currentState=$,this.channelControlHelper.updateState($,q,Y)}updateAddressList($,q,Y,T){var X,J;if(!(q instanceof Y6))return!1;if(!$.ok){if(this.children.size===0)this.updateState(C0.ConnectivityState.TRANSIENT_FAILURE,new pq.UnavailablePicker($.error),$.error.details);return!0}if($.value.length===0){let Z=`No addresses resolved. Resolution note: ${T}`;return this.updateState(C0.ConnectivityState.TRANSIENT_FAILURE,new pq.UnavailablePicker({details:Z}),Z),!1}U5("Connect to endpoint list "+$.value.map(AE.endpointToString));let Q=new Date,U=new Set;this.updatesPaused=!0,this.latestConfig=q;for(let Z of $.value){let K=(0,AE.endpointToString)(Z);U.add(K);let A=this.children.get(K);if(!A)A={child:new RO.LeafLoadBalancer(Z,(0,GE.createChildChannelControlHelper)(this.channelControlHelper,{updateState:(W,G,V)=>{if(this.currentState===C0.ConnectivityState.READY&&W!==C0.ConnectivityState.READY)this.channelControlHelper.requestReresolution();if(W===C0.ConnectivityState.READY)A.nonEmptySince=null;if(V)this.lastError=V;this.calculateAndUpdateState()},createSubchannel:(W,G)=>{let V=this.channelControlHelper.createSubchannel(W,G);if(A===null||A===void 0?void 0:A.oobMetricsListener)return new EE.OrcaOobMetricsSubchannelWrapper(V,A.oobMetricsListener,this.latestConfig.getOobLoadReportingPeriodMs());else return V}}),Y,T),lastUpdated:Q,nonEmptySince:null,weight:0,oobMetricsListener:null},this.children.set(K,A);if(q.getEnableOobLoadReport())A.oobMetricsListener=(W)=>{this.updateWeight(A,W)};else A.oobMetricsListener=null}for(let[Z,K]of this.children)if(U.has(Z))K.child.startConnecting();else K.child.destroy(),this.children.delete(Z);if(this.updatesPaused=!1,this.calculateAndUpdateState(),this.weightUpdateTimer)clearInterval(this.weightUpdateTimer);return this.weightUpdateTimer=(J=(X=setInterval(()=>{if(this.currentState===C0.ConnectivityState.READY)this.calculateAndUpdateState()},q.getWeightUpdatePeriodMs())).unref)===null||J===void 0?void 0:J.call(X),!0}exitIdle(){}resetBackoff(){}destroy(){for(let $ of this.children.values())$.child.destroy();if(this.children.clear(),this.weightUpdateTimer)clearInterval(this.weightUpdateTimer)}getTypeName(){return Z5}}function vO(){(0,GE.registerLoadBalancerType)(Z5,DE,Y6)}});var T6=B((J0)=>{Object.defineProperty(J0,"__esModule",{value:!0});J0.experimental=J0.ServerMetricRecorder=J0.ServerInterceptingCall=J0.ResponderBuilder=J0.ServerListenerBuilder=J0.addAdminServicesToServer=J0.getChannelzHandlers=J0.getChannelzServiceDefinition=J0.InterceptorConfigurationError=J0.InterceptingCall=J0.RequesterBuilder=J0.ListenerBuilder=J0.StatusBuilder=J0.getClientChannel=J0.ServerCredentials=J0.Server=J0.setLogVerbosity=J0.setLogger=J0.load=J0.loadObject=J0.CallCredentials=J0.ChannelCredentials=J0.waitForClientReady=J0.closeClient=J0.Channel=J0.makeGenericClientConstructor=J0.makeClientConstructor=J0.loadPackageDefinition=J0.Client=J0.compressionAlgorithms=J0.propagate=J0.connectivityState=J0.status=J0.logVerbosity=J0.Metadata=J0.credentials=void 0;var U8=m6();Object.defineProperty(J0,"CallCredentials",{enumerable:!0,get:function(){return U8.CallCredentials}});var kO=n9();Object.defineProperty(J0,"Channel",{enumerable:!0,get:function(){return kO.ChannelImplementation}});var hO=JX();Object.defineProperty(J0,"compressionAlgorithms",{enumerable:!0,get:function(){return hO.CompressionAlgorithms}});var _O=l0();Object.defineProperty(J0,"connectivityState",{enumerable:!0,get:function(){return _O.ConnectivityState}});var Z8=Dq();Object.defineProperty(J0,"ChannelCredentials",{enumerable:!0,get:function(){return Z8.ChannelCredentials}});var HE=l9();Object.defineProperty(J0,"Client",{enumerable:!0,get:function(){return HE.Client}});var K5=n();Object.defineProperty(J0,"logVerbosity",{enumerable:!0,get:function(){return K5.LogVerbosity}});Object.defineProperty(J0,"status",{enumerable:!0,get:function(){return K5.Status}});Object.defineProperty(J0,"propagate",{enumerable:!0,get:function(){return K5.Propagate}});var zE=Z0(),A5=o6();Object.defineProperty(J0,"loadPackageDefinition",{enumerable:!0,get:function(){return A5.loadPackageDefinition}});Object.defineProperty(J0,"makeClientConstructor",{enumerable:!0,get:function(){return A5.makeClientConstructor}});Object.defineProperty(J0,"makeGenericClientConstructor",{enumerable:!0,get:function(){return A5.makeClientConstructor}});var gO=P0();Object.defineProperty(J0,"Metadata",{enumerable:!0,get:function(){return gO.Metadata}});var mO=GG();Object.defineProperty(J0,"Server",{enumerable:!0,get:function(){return mO.Server}});var fO=nT();Object.defineProperty(J0,"ServerCredentials",{enumerable:!0,get:function(){return fO.ServerCredentials}});var bO=FG();Object.defineProperty(J0,"StatusBuilder",{enumerable:!0,get:function(){return bO.StatusBuilder}});J0.credentials={combineChannelCredentials:($,...q)=>{return q.reduce((Y,T)=>Y.compose(T),$)},combineCallCredentials:($,...q)=>{return q.reduce((Y,T)=>Y.compose(T),$)},createInsecure:Z8.ChannelCredentials.createInsecure,createSsl:Z8.ChannelCredentials.createSsl,createFromSecureContext:Z8.ChannelCredentials.createFromSecureContext,createFromMetadataGenerator:U8.CallCredentials.createFromMetadataGenerator,createFromGoogleCredential:U8.CallCredentials.createFromGoogleCredential,createEmpty:U8.CallCredentials.createEmpty};var uO=($)=>$.close();J0.closeClient=uO;var dO=($,q,Y)=>$.waitForReady(q,Y);J0.waitForClientReady=dO;var cO=($,q)=>{throw Error("Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead")};J0.loadObject=cO;var pO=($,q,Y)=>{throw Error("Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead")};J0.load=pO;var lO=($)=>{zE.setLogger($)};J0.setLogger=lO;var nO=($)=>{zE.setLoggerVerbosity($)};J0.setLogVerbosity=nO;var iO=($)=>{return HE.Client.prototype.getChannel.call($)};J0.getClientChannel=iO;var K8=c9();Object.defineProperty(J0,"ListenerBuilder",{enumerable:!0,get:function(){return K8.ListenerBuilder}});Object.defineProperty(J0,"RequesterBuilder",{enumerable:!0,get:function(){return K8.RequesterBuilder}});Object.defineProperty(J0,"InterceptingCall",{enumerable:!0,get:function(){return K8.InterceptingCall}});Object.defineProperty(J0,"InterceptorConfigurationError",{enumerable:!0,get:function(){return K8.InterceptorConfigurationError}});var ME=R$();Object.defineProperty(J0,"getChannelzServiceDefinition",{enumerable:!0,get:function(){return ME.getChannelzServiceDefinition}});Object.defineProperty(J0,"getChannelzHandlers",{enumerable:!0,get:function(){return ME.getChannelzHandlers}});var rO=r6();Object.defineProperty(J0,"addAdminServicesToServer",{enumerable:!0,get:function(){return rO.addAdminServicesToServer}});var W5=bX();Object.defineProperty(J0,"ServerListenerBuilder",{enumerable:!0,get:function(){return W5.ServerListenerBuilder}});Object.defineProperty(J0,"ResponderBuilder",{enumerable:!0,get:function(){return W5.ResponderBuilder}});Object.defineProperty(J0,"ServerInterceptingCall",{enumerable:!0,get:function(){return W5.ServerInterceptingCall}});var aO=rT();Object.defineProperty(J0,"ServerMetricRecorder",{enumerable:!0,get:function(){return aO.ServerMetricRecorder}});var oO=rX();J0.experimental=oO;var sO=FX(),tO=gG(),eO=pG(),$L=sY(),qL=sG(),YL=JE(),TL=NE(),XL=R$();(()=>{sO.setup(),tO.setup(),eO.setup(),$L.setup(),qL.setup(),YL.setup(),TL.setup(),XL.setup()})()});import{z as W$}from"zod";var aJ=W$.enum(["connector.started","connector.stopping","message.received","message.completed","message.failed","session.started","session.reused","thread.reset","schedule.delivery.started","schedule.delivery.sent","schedule.delivery.failed"]),ZD=W$.object({adapter:W$.string(),botUserName:W$.string().optional(),event:aJ,payload:W$.record(W$.string(),W$.unknown()),ts:W$.string()});var oJ=[{modelsDevKey:"openai",generatedProviderId:"openai",runtimeProviderId:"openai-native"},{modelsDevKey:"openai",generatedProviderId:"openai",runtimeProviderId:"openai-codex"},{modelsDevKey:"anthropic",generatedProviderId:"anthropic"},{modelsDevKey:"anthropic",generatedProviderId:"anthropic",runtimeProviderId:"claude-code"},{modelsDevKey:"google",generatedProviderId:"gemini"},{modelsDevKey:"deepseek",generatedProviderId:"deepseek"},{modelsDevKey:"xai",generatedProviderId:"xai"},{modelsDevKey:"togetherai",runtimeProviderId:"together",generatedProviderId:"together"},{modelsDevKey:"sap-ai-core",runtimeProviderId:"sapaicore",generatedProviderId:"sapaicore"},{modelsDevKey:"fireworks-ai",runtimeProviderId:"fireworks",generatedProviderId:"fireworks"},{modelsDevKey:"groq",runtimeProviderId:"groq",generatedProviderId:"groq"},{modelsDevKey:"cerebras",runtimeProviderId:"cerebras",generatedProviderId:"cerebras"},{modelsDevKey:"sambanova",runtimeProviderId:"sambanova",generatedProviderId:"sambanova"},{modelsDevKey:"nebius",runtimeProviderId:"nebius",generatedProviderId:"nebius"},{modelsDevKey:"huggingface",runtimeProviderId:"huggingface",generatedProviderId:"huggingface"},{modelsDevKey:"openrouter",runtimeProviderId:"cline",generatedProviderId:"openrouter"},{modelsDevKey:"ollama",runtimeProviderId:"ollama-cloud"},{modelsDevKey:"ollama-cloud",generatedProviderId:"ollama"},{modelsDevKey:"vercel",runtimeProviderId:"dify",generatedProviderId:"vercel-ai-gateway"},{modelsDevKey:"vercel",generatedProviderId:"vercel-ai-gateway"},{modelsDevKey:"aihubmix",runtimeProviderId:"aihubmix",generatedProviderId:"aihubmix"},{modelsDevKey:"hicap",runtimeProviderId:"hicap"},{modelsDevKey:"nous-research",runtimeProviderId:"nousResearch"},{modelsDevKey:"huawei-cloud-maas",runtimeProviderId:"huawei-cloud-maas"},{modelsDevKey:"baseten",runtimeProviderId:"baseten",generatedProviderId:"baseten"},{modelsDevKey:"google-vertex-anthropic",generatedProviderId:"vertex"},{modelsDevKey:"lmstudio",generatedProviderId:"lmstudio"},{modelsDevKey:"zai",generatedProviderId:"zai"},{modelsDevKey:"requesty",generatedProviderId:"requesty"},{modelsDevKey:"amazon-bedrock",generatedProviderId:"bedrock"},{modelsDevKey:"moonshotai",generatedProviderId:"moonshot"},{modelsDevKey:"minimax",generatedProviderId:"minimax"}];function KD($){return Object.fromEntries(oJ.flatMap((q)=>{let Y=$==="modelsDevKey"?q.modelsDevKey:q.generatedProviderId;return Y?[[q.modelsDevKey,Y]]:[]}))}var AD=KD("generatedProviderId");import{z as v0}from"zod";var WD=v0.object({agentId:v0.string(),conversationId:v0.string(),iteration:v0.number(),abortSignal:v0.custom().optional(),metadata:v0.record(v0.string(),v0.unknown()).optional()}),GD=v0.object({id:v0.string(),name:v0.string(),input:v0.unknown(),output:v0.unknown(),error:v0.string().optional(),durationMs:v0.number(),startedAt:v0.date(),endedAt:v0.date()});import{z as sJ}from"zod";function I1($,q){let Y=$.safeParse(q);if(!Y.success)throw Error(sJ.prettifyError(Y.error));return Y.data}function N1($){return sJ.toJSONSchema($)}function v6($,q="act"){return`<user_input mode="${q}">${$}</user_input>`}function F9($){if(!$?.trim())return"";return tJ($,"user_input")}function tJ($,q){if(!$?.trim())return"";if(!q)return $;let Y=new RegExp(`<${q}.*?>(.*?)</${q}>`,"g");return $.replace(Y,"$1")}var I9="runtime.team.progress.v1",N9="runtime.team.lifecycle.v1";function ED($){let q=$?.trim();return q?q:void 0}function x6($){return ED($?.rootSessionId)}var H9=["running","completed","failed","cancelled"];var aq=Aq(T6(),1),xE=Aq(hY(),1),z8=Aq(T6(),1),gE=Aq(T6(),1),mE=Aq(hY(),1);import{existsSync as kL}from"node:fs";import{dirname as SE,join as $q}from"node:path";import{fileURLToPath as hL}from"node:url";import{createInterface as dL}from"node:readline";import{createInterface as rL}from"node:readline";import{randomUUID as Xw}from"node:crypto";var EL={JAN:1,FEB:2,MAR:3,APR:4,MAY:5,JUN:6,JUL:7,AUG:8,SEP:9,OCT:10,NOV:11,DEC:12},VL={SUN:0,MON:1,TUE:2,WED:3,THU:4,FRI:5,SAT:6};function DL($,q){let Y=$.trim().toUpperCase();if(!q)return Y;for(let[T,X]of Object.entries(q))if(Y.includes(T))return Y.replaceAll(T,String(X));return Y}function A8($,q,Y){let T=Number.parseInt($,10);if(!Number.isInteger(T))throw Error(`invalid cron value "${$}"`);if(T<q||T>Y)throw Error(`cron value out of range: ${$}`);return T}function RE($,q,Y,T,X,J,Q=!1){if(T<=0)throw Error("cron step must be positive");if(q>Y)throw Error("cron range start must be <= end");if(q<X||Y>J)throw Error(`cron range ${q}-${Y} out of bounds`);for(let U=q;U<=Y;U+=T){if(Q&&U===7){$.add(0);continue}$.add(U)}}function X6($,q,Y,T,X=!1){let J=DL($,T);if(J==="*")return{kind:"any"};let Q=new Set,U=J.split(",").map((Z)=>Z.trim());for(let Z of U){if(!Z)continue;let[K,A]=Z.split("/"),W=A!==void 0?A8(A,1,Number.MAX_SAFE_INTEGER):1;if(K==="*"){RE(Q,q,Y,W,q,Y,X);continue}if(K.includes("-")){let[V,F]=K.split("-").map((z)=>z.trim()),N=A8(V,q,Y),D=A8(F,q,Y);RE(Q,N,D,W,q,Y,X);continue}let G=A8(K,q,Y);if(X&&G===7)Q.add(0);else Q.add(G)}if(Q.size===0)throw Error(`invalid cron part "${$}"`);return{kind:"list",values:Q}}function PE($){let q=$.trim().split(/\s+/).map((Y)=>Y.trim());if(q.length!==5)throw Error("cron pattern must contain exactly 5 fields");return{minute:X6(q[0],0,59),hour:X6(q[1],0,23),dayOfMonth:X6(q[2],1,31),month:X6(q[3],1,12,EL),dayOfWeek:X6(q[4],0,7,VL,!0)}}function J6($,q){if($.kind==="any")return!0;return $.values?.has(q)===!0}function FL($){return new Date($.getFullYear(),$.getMonth(),$.getDate(),$.getHours(),$.getMinutes(),0,0)}function IL($,q){let Y=q.getMonth()+1,T=q.getDate(),X=q.getDay();return J6($.minute,q.getMinutes())&&J6($.hour,q.getHours())&&J6($.month,Y)&&J6($.dayOfMonth,T)&&J6($.dayOfWeek,X)}function W8($){PE($)}function lq($,q){let Y=PE($),T=FL(q);T.setMinutes(T.getMinutes()+1);let X=527040;for(let J=0;J<X;J+=1){if(IL(Y,T))return T.toISOString();T.setMinutes(T.getMinutes()+1)}throw Error("unable to resolve next run for cron pattern within 1 year")}class G8{globalMaxConcurrency;activeExecutions=new Map;constructor($){this.globalMaxConcurrency=Math.max(1,Math.floor($))}acquire($,q,Y){if(this.getGlobalActiveCount()>=this.globalMaxConcurrency)return!1;let X=Math.max(1,Math.floor(Y)),J=this.activeExecutions.get($)??new Set;if(J.size>=X)return!1;return J.add(q),this.activeExecutions.set($,J),!0}release($,q){let Y=this.activeExecutions.get($);if(!Y)return;if(Y.delete(q),Y.size===0)this.activeExecutions.delete($)}getGlobalActiveCount(){let $=0;for(let q of this.activeExecutions.values())$+=q.size;return $}getScheduleActiveCount($){return this.activeExecutions.get($)?.size??0}}import{randomUUID as LE}from"node:crypto";import{join as PL}from"node:path";import{createRequire as NL}from"node:module";function X0(){return new Date().toISOString()}function T1($){return $?1:0}function f($){return typeof $==="string"?$:""}function i($){if(typeof $!=="string")return;let q=$.trim();return q.length>0?q:void 0}function X1($){return $===1||$===!0}function t$($){let q=NL(import.meta.url);if(typeof globalThis.Bun<"u"){let{Database:J}=q("bun:sqlite"),Q=new J($,{create:!0});return{prepare:(U)=>{let Z=Q.query(U);return{run:(...K)=>Z.run(...K),get:(...K)=>Z.get(...K),all:(...K)=>Z.all(...K)}},exec:(U)=>Q.exec(U)}}try{let J=["node",":sqlite"].join(""),{DatabaseSync:Q}=q(J),U=new Q($);return{prepare:(Z)=>{let K=U.prepare(Z);return{run:(...A)=>K.run(...A),get:(...A)=>K.get(...A)??null,all:(...A)=>K.all(...A)}},exec:(Z)=>U.exec(Z)}}catch{}let T=["better","-sqlite3"].join("");return new(q(T))($)}function Q6($,q={}){if($.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec(`
22
- CREATE TABLE IF NOT EXISTS sessions (
23
- session_id TEXT PRIMARY KEY,
24
- source TEXT NOT NULL,
25
- pid INTEGER NOT NULL,
26
- started_at TEXT NOT NULL,
27
- ended_at TEXT,
28
- exit_code INTEGER,
29
- status TEXT NOT NULL,
30
- status_lock INTEGER NOT NULL DEFAULT 0,
31
- interactive INTEGER NOT NULL,
32
- provider TEXT NOT NULL,
33
- model TEXT NOT NULL,
34
- cwd TEXT NOT NULL,
35
- workspace_root TEXT NOT NULL,
36
- team_name TEXT,
37
- enable_tools INTEGER NOT NULL,
38
- enable_spawn INTEGER NOT NULL,
39
- enable_teams INTEGER NOT NULL,
40
- parent_session_id TEXT,
41
- parent_agent_id TEXT,
42
- agent_id TEXT,
43
- conversation_id TEXT,
44
- is_subagent INTEGER NOT NULL DEFAULT 0,
45
- prompt TEXT,
46
- metadata_json TEXT,
47
- transcript_path TEXT NOT NULL,
48
- hook_path TEXT NOT NULL,
49
- messages_path TEXT,
50
- updated_at TEXT NOT NULL
51
- );
52
- `),$.exec(`
53
- CREATE TABLE IF NOT EXISTS subagent_spawn_queue (
54
- id INTEGER PRIMARY KEY AUTOINCREMENT,
55
- root_session_id TEXT NOT NULL,
56
- parent_agent_id TEXT NOT NULL,
57
- task TEXT,
58
- system_prompt TEXT,
59
- created_at TEXT NOT NULL,
60
- consumed_at TEXT
61
- );
62
- `),$.exec(`
63
- CREATE TABLE IF NOT EXISTS schedules (
64
- schedule_id TEXT PRIMARY KEY,
65
- name TEXT NOT NULL,
66
- cron_pattern TEXT NOT NULL,
67
- prompt TEXT NOT NULL,
68
- provider TEXT NOT NULL,
69
- model TEXT NOT NULL,
70
- mode TEXT NOT NULL DEFAULT 'act',
71
- workspace_root TEXT,
72
- cwd TEXT,
73
- system_prompt TEXT,
74
- max_iterations INTEGER,
75
- timeout_seconds INTEGER,
76
- max_parallel INTEGER NOT NULL DEFAULT 1,
77
- enabled INTEGER NOT NULL DEFAULT 1,
78
- created_at TEXT NOT NULL,
79
- updated_at TEXT NOT NULL,
80
- last_run_at TEXT,
81
- next_run_at TEXT,
82
- claim_token TEXT,
83
- claim_started_at TEXT,
84
- claim_until_at TEXT,
85
- created_by TEXT,
86
- tags TEXT,
87
- metadata_json TEXT
88
- );
89
- `),$.exec(`
90
- CREATE TABLE IF NOT EXISTS schedule_executions (
91
- execution_id TEXT PRIMARY KEY,
92
- schedule_id TEXT NOT NULL,
93
- session_id TEXT,
94
- triggered_at TEXT NOT NULL,
95
- started_at TEXT,
96
- ended_at TEXT,
97
- status TEXT NOT NULL,
98
- exit_code INTEGER,
99
- error_message TEXT,
100
- iterations INTEGER,
101
- tokens_used INTEGER,
102
- cost_usd REAL,
103
- FOREIGN KEY (schedule_id) REFERENCES schedules(schedule_id) ON DELETE CASCADE,
104
- FOREIGN KEY (session_id) REFERENCES sessions(session_id) ON DELETE SET NULL
105
- );
106
- `),$.exec(`
107
- CREATE INDEX IF NOT EXISTS idx_schedule_executions_schedule
108
- ON schedule_executions(schedule_id, triggered_at DESC);
109
- `),$.exec(`
110
- CREATE INDEX IF NOT EXISTS idx_schedules_next_run
111
- ON schedules(enabled, next_run_at);
112
- `),!q.includeLegacyMigrations)return;let Y=$.prepare("PRAGMA table_info(sessions);").all(),T=(Q)=>Y.some((U)=>U.name===Q);if(!T("workspace_root"))$.exec("ALTER TABLE sessions ADD COLUMN workspace_root TEXT;"),$.exec("UPDATE sessions SET workspace_root = cwd WHERE workspace_root IS NULL OR workspace_root = '';");if(!T("parent_session_id"))$.exec("ALTER TABLE sessions ADD COLUMN parent_session_id TEXT;");if(!T("parent_agent_id"))$.exec("ALTER TABLE sessions ADD COLUMN parent_agent_id TEXT;");if(!T("agent_id"))$.exec("ALTER TABLE sessions ADD COLUMN agent_id TEXT;");if(!T("conversation_id"))$.exec("ALTER TABLE sessions ADD COLUMN conversation_id TEXT;");if(!T("is_subagent"))$.exec("ALTER TABLE sessions ADD COLUMN is_subagent INTEGER NOT NULL DEFAULT 0;");if(!T("messages_path"))$.exec("ALTER TABLE sessions ADD COLUMN messages_path TEXT;");if(!T("metadata_json"))$.exec("ALTER TABLE sessions ADD COLUMN metadata_json TEXT;");let X=$.prepare("PRAGMA table_info(schedules);").all(),J=(Q)=>X.some((U)=>U.name===Q);if(!J("claim_token"))$.exec("ALTER TABLE schedules ADD COLUMN claim_token TEXT;");if(!J("claim_started_at"))$.exec("ALTER TABLE schedules ADD COLUMN claim_started_at TEXT;");if(!J("claim_until_at"))$.exec("ALTER TABLE schedules ADD COLUMN claim_until_at TEXT;")}import{existsSync as HL,mkdirSync as zL}from"node:fs";import{dirname as ML,join as A0}from"node:path";var E8="agents",U6="hooks",S1="skills",Z6="rules",K6="workflows",G5="plugins",OE="cline_mcp_settings.json",e$=process?.env?.HOME||"~",BL=!1;function E5($){if(BL)return;let q=$.trim();if(!q)return;e$=q}function A6(){return A0(e$,"Documents","Cline")}function V8(){return A0(A6(),"Agents")}function W6(){return A0(A6(),"Hooks")}function G6(){return A0(A6(),"Rules")}function E6(){return A0(A6(),"Workflows")}function C1(){let $=process.env.CLINE_DATA_DIR?.trim();if($)return $;return A0(e$,".cline","data")}function C$(){let $=process.env.CLINE_SESSION_DATA_DIR?.trim();if($)return $;return A0(C1(),"sessions")}function D8(){let $=process.env.CLINE_TEAM_DATA_DIR?.trim();if($)return $;return A0(C1(),"teams")}function V5(){let $=process.env.CLINE_PROVIDER_SETTINGS_PATH?.trim();if($)return $;return A0(C1(),"settings","providers.json")}function D5(){let $=process.env.CLINE_MCP_SETTINGS_PATH?.trim();if($)return $;return A0(C1(),"settings",OE)}function V6($){let q=new Set,Y=[];for(let T of $){if(!T||q.has(T))continue;q.add(T),Y.push(T)}return Y}function RL($){if(!$)return[];return[A0($,".clinerules",S1),A0($,".cline",S1),A0($,".claude",S1),A0($,".agents",S1)]}function F5(){return A0(C1(),"settings",E8)}function I5(){return[V8(),F5()]}function N5($){return V6([$?A0($,".clinerules",U6):"",W6()])}function D6($){return V6([...RL($),A0(C1(),"settings",S1),A0(e$,".cline",S1),A0(e$,".agents",S1)])}function H5($){return V6([$?A0($,".clinerules"):"",A0(C1(),"settings",Z6),G6()])}function z5($){return V6([$?A0($,".clinerules","workflows"):"",A0(C1(),"settings",K6),E6()])}function M5($){return V6([$?A0($,".clinerules",G5):"",A0(e$,".cline",G5),A0(e$,".agents",G5)])}function B5($){let q=ML($);if(!HL(q))zL(q,{recursive:!0})}function OL(){return PL(C$(),"sessions.db")}function LL($){if(!$)return;try{let q=JSON.parse($);if(q&&typeof q==="object"&&!Array.isArray(q))return q}catch{}return}function wL($){if(!$)return;try{let q=JSON.parse($);if(!Array.isArray(q))return;let Y=q.map((T)=>typeof T==="string"?T.trim():"").filter((T)=>T.length>0);return Y.length>0?Y:void 0}catch{return}}function SL($){return $==="plan"?"plan":"act"}function CL($){if($==="pending"||$==="running"||$==="success"||$==="failed"||$==="timeout"||$==="aborted")return $;return"failed"}class F8{db;constructor($={}){let q=$.sessionsDbPath??OL();this.db=t$(q),Q6(this.db,{includeLegacyMigrations:!0})}createSchedule($){let q=X0(),Y=`sched_${LE()}`,T=$.cronPattern.trim(),X=$.enabled===!1?void 0:lq(T,new Date),J={scheduleId:Y,name:$.name.trim(),cronPattern:T,prompt:$.prompt,provider:$.provider.trim(),model:$.model.trim(),mode:$.mode==="plan"?"plan":"act",workspaceRoot:$.workspaceRoot?.trim()||void 0,cwd:$.cwd?.trim()||void 0,systemPrompt:$.systemPrompt,maxIterations:typeof $.maxIterations==="number"?Math.floor($.maxIterations):void 0,timeoutSeconds:typeof $.timeoutSeconds==="number"?Math.floor($.timeoutSeconds):void 0,maxParallel:typeof $.maxParallel==="number"?Math.max(1,Math.floor($.maxParallel)):1,enabled:$.enabled!==!1,createdAt:q,updatedAt:q,lastRunAt:void 0,nextRunAt:X,createdBy:$.createdBy?.trim()||void 0,tags:$.tags?.filter((Q)=>Q.trim().length>0),metadata:$.metadata};return this.db.prepare(`INSERT INTO schedules (
113
- schedule_id, name, cron_pattern, prompt,
114
- provider, model, mode, workspace_root, cwd, system_prompt,
115
- max_iterations, timeout_seconds, max_parallel,
116
- enabled, created_at, updated_at, last_run_at, next_run_at,
117
- claim_token, claim_started_at, claim_until_at,
118
- created_by, tags, metadata_json
119
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(J.scheduleId,J.name,J.cronPattern,J.prompt,J.provider,J.model,J.mode,J.workspaceRoot??null,J.cwd??null,J.systemPrompt??null,J.maxIterations??null,J.timeoutSeconds??null,J.maxParallel,J.enabled?1:0,J.createdAt,J.updatedAt,J.lastRunAt??null,J.nextRunAt??null,null,null,null,J.createdBy??null,J.tags?JSON.stringify(J.tags):null,J.metadata?JSON.stringify(J.metadata):null),J}getSchedule($){let q=this.db.prepare("SELECT * FROM schedules WHERE schedule_id = ?").get($);if(!q)return;return this.toScheduleRecord(q)}listSchedules($={}){let q=[],Y=[];if(typeof $.enabled==="boolean")q.push("enabled = ?"),Y.push($.enabled?1:0);if($.tags&&$.tags.length>0)for(let Q of $.tags)q.push("tags LIKE ?"),Y.push(`%"${Q.trim()}"%`);let T=q.length>0?`WHERE ${q.join(" AND ")}`:"",X=typeof $.limit==="number"&&$.limit>0?Math.floor($.limit):200;return this.db.prepare(`SELECT * FROM schedules ${T} ORDER BY created_at DESC LIMIT ?`).all(...Y,X).map((Q)=>this.toScheduleRecord(Q))}listDueSchedules($){return this.db.prepare(`SELECT * FROM schedules
120
- WHERE enabled = 1 AND next_run_at IS NOT NULL AND next_run_at <= ?
121
- ORDER BY next_run_at ASC`).all($).map((Y)=>this.toScheduleRecord(Y))}updateSchedule($,q){let Y=this.getSchedule($);if(!Y)return;let T={...Y,name:q.name?.trim()??Y.name,cronPattern:q.cronPattern?.trim()??Y.cronPattern,prompt:q.prompt??Y.prompt,provider:q.provider?.trim()??Y.provider,model:q.model?.trim()??Y.model,mode:q.mode??Y.mode,workspaceRoot:q.workspaceRoot!==void 0?q.workspaceRoot.trim()||void 0:Y.workspaceRoot,cwd:q.cwd!==void 0?q.cwd.trim()||void 0:Y.cwd,systemPrompt:q.systemPrompt!==void 0?q.systemPrompt:Y.systemPrompt,maxIterations:q.maxIterations===null?void 0:q.maxIterations!==void 0?Math.floor(q.maxIterations):Y.maxIterations,timeoutSeconds:q.timeoutSeconds===null?void 0:q.timeoutSeconds!==void 0?Math.floor(q.timeoutSeconds):Y.timeoutSeconds,maxParallel:q.maxParallel!==void 0?Math.max(1,Math.floor(q.maxParallel)):Y.maxParallel,enabled:q.enabled??Y.enabled,createdBy:q.createdBy===null?void 0:q.createdBy!==void 0?q.createdBy.trim()||void 0:Y.createdBy,tags:q.tags??Y.tags,metadata:q.metadata??Y.metadata,updatedAt:X0()},X=T.cronPattern!==Y.cronPattern,J=T.enabled!==Y.enabled;if(X||J)T.nextRunAt=T.enabled?lq(T.cronPattern,new Date):void 0;return this.db.prepare(`UPDATE schedules SET
122
- name = ?, cron_pattern = ?, prompt = ?,
123
- provider = ?, model = ?, mode = ?, workspace_root = ?, cwd = ?, system_prompt = ?,
124
- max_iterations = ?, timeout_seconds = ?, max_parallel = ?,
125
- enabled = ?, updated_at = ?, last_run_at = ?, next_run_at = ?,
126
- created_by = ?, tags = ?, metadata_json = ?
127
- WHERE schedule_id = ?`).run(T.name,T.cronPattern,T.prompt,T.provider,T.model,T.mode,T.workspaceRoot??null,T.cwd??null,T.systemPrompt??null,T.maxIterations??null,T.timeoutSeconds??null,T.maxParallel,T.enabled?1:0,T.updatedAt,T.lastRunAt??null,T.nextRunAt??null,T.createdBy??null,T.tags?JSON.stringify(T.tags):null,T.metadata?JSON.stringify(T.metadata):null,T.scheduleId),T}markScheduleTriggered($,q){let Y=this.getSchedule($);if(!Y)return;let T=Y.enabled?lq(Y.cronPattern,new Date(q)):void 0;this.db.prepare("UPDATE schedules SET last_run_at = ?, next_run_at = ?, updated_at = ? WHERE schedule_id = ?").run(q,T??null,X0(),$)}claimDueSchedules($,q,Y=50){let T=[],X=Math.max(1,Math.floor(Y)),J=Math.max(1000,Math.floor(q)),Q=new Date(new Date($).getTime()+J).toISOString(),U=X0(),Z=`SELECT * FROM schedules
128
- WHERE enabled = 1
129
- AND next_run_at IS NOT NULL
130
- AND next_run_at <= ?
131
- AND (claim_until_at IS NULL OR claim_until_at <= ?)
132
- ORDER BY next_run_at ASC
133
- LIMIT ?`,K=`UPDATE schedules SET
134
- claim_token = ?, claim_started_at = ?, claim_until_at = ?, updated_at = ?
135
- WHERE schedule_id = ?
136
- AND enabled = 1
137
- AND next_run_at = ?
138
- AND (claim_until_at IS NULL OR claim_until_at <= ?)`,A=this.db.prepare(`UPDATE schedules SET
139
- claim_token = ?, claim_started_at = ?, claim_until_at = ?, updated_at = ?
140
- WHERE schedule_id = ?
141
- AND enabled = 1
142
- AND next_run_at = ?
143
- AND (claim_until_at IS NULL OR claim_until_at <= ?)`);this.db.exec("BEGIN IMMEDIATE;");try{let W=this.db.prepare(`SELECT * FROM schedules
144
- WHERE enabled = 1
145
- AND next_run_at IS NOT NULL
146
- AND next_run_at <= ?
147
- AND (claim_until_at IS NULL OR claim_until_at <= ?)
148
- ORDER BY next_run_at ASC
149
- LIMIT ?`).all($,$,X);for(let G of W){let V=f(G.schedule_id),F=f(G.next_run_at);if(!V||!F)continue;let N=`claim_${LE()}`;if((A.run(N,U,Q,U,V,F,$).changes??0)!==1)continue;T.push({schedule:this.toScheduleRecord(G),claimToken:N,triggeredAt:F,leaseUntilAt:Q})}return this.db.exec("COMMIT;"),T}catch(W){throw this.db.exec("ROLLBACK;"),W}}renewScheduleClaim($,q,Y){let T=X0();return(this.db.prepare(`UPDATE schedules
150
- SET claim_until_at = ?, updated_at = ?
151
- WHERE schedule_id = ? AND claim_token = ?`).run(Y,T,$,q).changes??0)===1}releaseScheduleClaim($,q){let Y=X0();return(this.db.prepare(`UPDATE schedules
152
- SET claim_token = NULL, claim_started_at = NULL, claim_until_at = NULL, updated_at = ?
153
- WHERE schedule_id = ? AND claim_token = ?`).run(Y,$,q).changes??0)===1}completeScheduleClaim($,q,Y){let T=this.db.prepare(`SELECT cron_pattern, enabled
154
- FROM schedules
155
- WHERE schedule_id = ? AND claim_token = ?`).get($,q);if(!T)return!1;let X=f(T.cron_pattern),Q=Number(T.enabled??0)===1&&X?lq(X,new Date(Y)):void 0,U=X0();return(this.db.prepare(`UPDATE schedules SET
156
- last_run_at = ?, next_run_at = ?, claim_token = NULL, claim_started_at = NULL, claim_until_at = NULL, updated_at = ?
157
- WHERE schedule_id = ? AND claim_token = ?`).run(Y,Q??null,U,$,q).changes??0)===1}deleteSchedule($){return(this.db.prepare("DELETE FROM schedules WHERE schedule_id = ?").run($).changes??0)>0}recordExecution($){this.db.prepare(`INSERT OR REPLACE INTO schedule_executions (
158
- execution_id, schedule_id, session_id,
159
- triggered_at, started_at, ended_at, status,
160
- exit_code, error_message, iterations, tokens_used, cost_usd
161
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run($.executionId,$.scheduleId,$.sessionId??null,$.triggeredAt,$.startedAt??null,$.endedAt??null,$.status,$.exitCode??null,$.errorMessage??null,$.iterations??null,$.tokensUsed??null,$.costUsd??null)}getExecution($){let q=this.db.prepare("SELECT * FROM schedule_executions WHERE execution_id = ?").get($);if(!q)return;return this.toScheduleExecutionRecord(q)}listExecutions($){let q=[],Y=[];if($.scheduleId)q.push("schedule_id = ?"),Y.push($.scheduleId);if($.status)q.push("status = ?"),Y.push($.status);let T=q.length>0?`WHERE ${q.join(" AND ")}`:"",X=typeof $.limit==="number"&&$.limit>0?Math.floor($.limit):50;return this.db.prepare(`SELECT * FROM schedule_executions ${T}
162
- ORDER BY triggered_at DESC LIMIT ?`).all(...Y,X).map((Q)=>this.toScheduleExecutionRecord(Q))}getExecutionStats($){let q=this.listExecutions({scheduleId:$,limit:1e4});if(q.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let Y=0,T=0,X=0,J;for(let Q of q){if(Q.status==="success")Y+=1;if(!J&&Q.status!=="success")J=Q;if(Q.startedAt&&Q.endedAt){let U=new Date(Q.endedAt).getTime()-new Date(Q.startedAt).getTime();if(Number.isFinite(U)&&U>=0)X+=U,T+=1}}return{totalRuns:q.length,successRate:Y/q.length,avgDurationSeconds:T>0?X/T/1000:0,lastFailure:J}}listUpcomingRuns($=20){return this.db.prepare(`SELECT schedule_id, name, next_run_at FROM schedules
163
- WHERE enabled = 1 AND next_run_at IS NOT NULL
164
- ORDER BY next_run_at ASC LIMIT ?`).all(Math.max(1,Math.floor($))).map((Y)=>({scheduleId:f(Y.schedule_id),name:f(Y.name),nextRunAt:f(Y.next_run_at)})).filter((Y)=>Y.scheduleId&&Y.nextRunAt)}toScheduleRecord($){return{scheduleId:f($.schedule_id),name:f($.name),cronPattern:f($.cron_pattern),prompt:f($.prompt),provider:f($.provider),model:f($.model),mode:SL(i($.mode)),workspaceRoot:i($.workspace_root),cwd:i($.cwd),systemPrompt:i($.system_prompt),maxIterations:typeof $.max_iterations==="number"?$.max_iterations:void 0,timeoutSeconds:typeof $.timeout_seconds==="number"?$.timeout_seconds:void 0,maxParallel:typeof $.max_parallel==="number"&&$.max_parallel>0?$.max_parallel:1,enabled:Number($.enabled??0)===1,createdAt:f($.created_at),updatedAt:f($.updated_at),lastRunAt:i($.last_run_at),nextRunAt:i($.next_run_at),createdBy:i($.created_by),tags:wL(i($.tags)),metadata:LL(i($.metadata_json))}}toScheduleExecutionRecord($){return{executionId:f($.execution_id),scheduleId:f($.schedule_id),sessionId:i($.session_id),triggeredAt:f($.triggered_at),startedAt:i($.started_at),endedAt:i($.ended_at),status:CL(i($.status)),exitCode:typeof $.exit_code==="number"?$.exit_code:void 0,errorMessage:i($.error_message),iterations:typeof $.iterations==="number"?$.iterations:void 0,tokensUsed:typeof $.tokens_used==="number"?$.tokens_used:void 0,costUsd:typeof $.cost_usd==="number"?$.cost_usd:void 0}}}import{randomUUID as yL}from"node:crypto";function jL($){if($ instanceof Error)return $.message;return String($)}function vL($){let q=typeof $.inputTokens==="number"?$.inputTokens:void 0,Y=typeof $.outputTokens==="number"?$.outputTokens:void 0;return{iterations:typeof $.iterations==="number"?$.iterations:void 0,tokensUsed:q!==void 0&&Y!==void 0?q+Y:void 0,costUsd:typeof $.usage?.totalCost==="number"?$.usage.totalCost:void 0}}class R5 extends Error{constructor($){super($);this.name="TimeoutError"}}async function xL($,q){if(q<=0)return await $;let Y,T=new Promise((X,J)=>{Y=setTimeout(()=>{J(new R5("scheduled execution timed out"))},q)});try{return await Promise.race([$,T])}finally{if(Y)clearTimeout(Y)}}class I8{store;resourceLimiter;options;claimLeaseMs;activeExecutions=new Map;timer;started=!1;ticking=!1;constructor($){this.options=$,this.store=new F8({sessionsDbPath:$.sessionsDbPath}),this.resourceLimiter=new G8($.globalMaxConcurrency??10),this.claimLeaseMs=Math.max(5000,wE($.claimLeaseSeconds,90)*1000)}async start(){if(this.started)return;this.started=!0,await this.tick();let $=Math.max(5000,wE(this.options.pollIntervalMs,30000));this.timer=setInterval(()=>{this.tick()},$)}async stop(){if(!this.started)return;if(this.started=!1,this.timer)clearInterval(this.timer),this.timer=void 0;let $=Array.from(this.activeExecutions.values());await Promise.all($.map(async(q)=>{try{await this.options.runtimeHandlers.abortSession(q.sessionId)}catch{}}))}createSchedule($){if(W8($.cronPattern),!$.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return this.store.createSchedule($)}getSchedule($){return this.store.getSchedule($)}listSchedules($={}){return this.store.listSchedules($)}updateSchedule($,q){if(q.cronPattern!==void 0)W8(q.cronPattern);let Y=this.store.getSchedule($);if(!Y)return;let T=q.workspaceRoot!==void 0?q.workspaceRoot.trim():Y.workspaceRoot??"";if((q.enabled??Y.enabled)&&!T)throw Error("workspaceRoot is required for enabled schedules");return this.store.updateSchedule($,q)}deleteSchedule($){return this.store.deleteSchedule($)}pauseSchedule($){return this.updateSchedule($,{enabled:!1})}resumeSchedule($){return this.updateSchedule($,{enabled:!0})}async triggerScheduleNow($){let q=this.store.getSchedule($);if(!q)return;return await this.executeSchedule(q,X0(),"manual")}listScheduleExecutions($){return this.store.listExecutions($)}getScheduleStats($){return this.store.getExecutionStats($)}getActiveExecutions(){return Array.from(this.activeExecutions.values())}getUpcomingRuns($=20){return this.store.listUpcomingRuns($)}async tick(){if(this.ticking)return;this.ticking=!0;try{let $=this.store.claimDueSchedules(X0(),this.claimLeaseMs);await Promise.allSettled($.map((q)=>this.executeClaimedSchedule(q)))}finally{this.ticking=!1}}async executeClaimedSchedule($){let q=this.startClaimLeaseHeartbeat($);try{let Y=await this.executeSchedule($.schedule,$.triggeredAt,"scheduled"),T=Y.startedAt??$.triggeredAt;if(!this.store.completeScheduleClaim($.schedule.scheduleId,$.claimToken,T))this.publishEvent("schedule.execution.claimLost",{scheduleId:$.schedule.scheduleId,executionId:Y.executionId,claimToken:$.claimToken})}finally{q()}}startClaimLeaseHeartbeat($){let q=Math.max(1000,Math.floor(this.claimLeaseMs/2)),Y=setInterval(()=>{let T=new Date(Date.now()+this.claimLeaseMs).toISOString();if(!this.store.renewScheduleClaim($.schedule.scheduleId,$.claimToken,T))clearInterval(Y)},q);return()=>{clearInterval(Y)}}buildStartRequest($){let q=$.workspaceRoot?.trim();if(!q)throw Error("schedule requires workspaceRoot");return{workspaceRoot:q,cwd:$.cwd?.trim()||q,provider:$.provider,model:$.model,mode:$.mode,apiKey:"",systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,enableTools:!0,enableSpawn:!0,enableTeams:!0,autoApproveTools:!0,teamName:`scheduled-${$.scheduleId}`,missionStepInterval:3,missionTimeIntervalMs:120000}}async executeSchedule($,q,Y){let T=`exec_${yL()}`,X={executionId:T,scheduleId:$.scheduleId,triggeredAt:q,status:"pending"};if(this.store.recordExecution(X),!this.resourceLimiter.acquire($.scheduleId,T,$.maxParallel)){let K={...X,status:"failed",endedAt:X0(),errorMessage:"concurrency limit reached"};return this.store.recordExecution(K),K}let Q,U,Z;try{let K=this.buildStartRequest($);if(Q=(await this.options.runtimeHandlers.startSession(K)).sessionId.trim(),!Q)throw Error("runtime start returned empty sessionId");let W=X0();U=W,Z=typeof $.timeoutSeconds==="number"&&$.timeoutSeconds>0?new Date(new Date(W).getTime()+$.timeoutSeconds*1000).toISOString():void 0;let G={...X,sessionId:Q,startedAt:U,status:"running"};this.store.recordExecution(G),this.activeExecutions.set(T,{executionId:T,scheduleId:$.scheduleId,sessionId:Q,startedAt:W,timeoutAt:Z}),this.publishEvent("schedule.execution.started",{scheduleId:$.scheduleId,executionId:T,sessionId:Q,trigger:Y,triggeredAt:q});let V={config:K,prompt:$.prompt},F=this.options.runtimeHandlers.sendSession(Q,V),N=await xL(F,($.timeoutSeconds??0)*1000),D=vL(N.result),z={...G,status:"success",endedAt:X0(),iterations:D.iterations,tokensUsed:D.tokensUsed,costUsd:D.costUsd};return this.store.recordExecution(z),this.publishEvent("schedule.execution.completed",{scheduleId:$.scheduleId,executionId:T,sessionId:Q,status:z.status,durationMs:z.startedAt&&z.endedAt?new Date(z.endedAt).getTime()-new Date(z.startedAt).getTime():void 0}),z}catch(K){let A=K instanceof R5?"timeout":"failed";if(Q&&A==="timeout")try{await this.options.runtimeHandlers.abortSession(Q)}catch{}let W={executionId:T,scheduleId:$.scheduleId,sessionId:Q,triggeredAt:q,startedAt:U,endedAt:X0(),status:A,errorMessage:jL(K)};return this.store.recordExecution(W),this.publishEvent("schedule.execution.completed",{scheduleId:$.scheduleId,executionId:T,sessionId:Q,status:W.status,errorMessage:W.errorMessage}),W}finally{if(Q)try{await this.options.runtimeHandlers.stopSession(Q)}catch{}this.activeExecutions.delete(T),this.resourceLimiter.release($.scheduleId,T)}}publishEvent($,q){this.options.eventPublisher?.($,q)}}function wE($,q){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return q;return Math.floor($)}var a=Aq(T6(),1);import{randomUUID as jE}from"node:crypto";import{randomUUID as Jw}from"node:crypto";import{randomUUID as vE}from"node:crypto";function kE($){let q=SE(hL($)),Y=new Set([$q(q,"proto","rpc.proto"),$q(q,"..","proto","rpc.proto"),$q(q,"..","src","proto","rpc.proto"),$q(q,"..","..","src","proto","rpc.proto"),$q(process.cwd(),"src","proto","rpc.proto"),$q(process.cwd(),"packages","rpc","src","proto","rpc.proto")]),T=process.cwd();while(!0){Y.add($q(T,"packages","rpc","src","proto","rpc.proto"));let X=SE(T);if(X===T)break;T=X}for(let X of Y)if(kL(X))return X;throw Error("Unable to resolve rpc.proto path")}var _L="cline.rpc.v1",hE="ClineGateway";function gL(){return kE(import.meta.url)}function mL(){let $=xE.loadSync(gL(),{keepCase:!1,longs:String,enums:String,defaults:!0,oneofs:!0}),q=aq.loadPackageDefinition($).cline?.rpc?.v1?.ClineGateway?.service;if(!q)throw Error(`Unable to load ${_L}.${hE} from proto`);return q}function fL($){return new(aq.makeGenericClientConstructor(mL(),hE))($,aq.credentials.createInsecure())}function N8($){if($===null||$===void 0)return{nullValue:"NULL_VALUE"};if(typeof $==="string")return{stringValue:$};if(typeof $==="number")return{numberValue:Number.isFinite($)?$:0};if(typeof $==="boolean")return{boolValue:$};if(Array.isArray($))return{listValue:{values:$.map((q)=>N8(q))}};if(typeof $==="object"){let q={fields:{}};for(let[Y,T]of Object.entries($))q.fields??={},q.fields[Y]=N8(T);return{structValue:q}}return{stringValue:String($)}}function H8($){if(!$)return;if($.nullValue!==void 0)return null;if($.stringValue!==void 0)return $.stringValue;if($.numberValue!==void 0)return $.numberValue;if($.boolValue!==void 0)return $.boolValue;if($.listValue)return($.listValue.values??[]).map((q)=>H8(q));if($.structValue){let q={};for(let[Y,T]of Object.entries($.structValue.fields??{}))q[Y]=H8(T);return q}return}function J1($){let q={};for(let[Y,T]of Object.entries($??{}))q[Y]=N8(T);return{fields:q}}function f0($){if(!$?.fields)return;let q={};for(let[Y,T]of Object.entries($.fields))q[Y]=H8(T);return q}function qq($){return N8($)}function Yq($){return H8($??void 0)}function bL($){return{sessionId:$.sessionId,source:$.source,pid:$.pid,startedAt:$.startedAt,endedAt:$.endedAt??"",exitCode:$.exitCode??0,status:$.status,statusLock:$.statusLock,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??"",enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:$.parentSessionId??"",parentAgentId:$.parentAgentId??"",agentId:$.agentId??"",conversationId:$.conversationId??"",isSubagent:$.isSubagent,prompt:$.prompt??"",transcriptPath:$.transcriptPath,hookPath:$.hookPath,messagesPath:$.messagesPath??"",updatedAt:$.updatedAt,metadata:J1($.metadata)}}function CE($){return{sessionId:$.sessionId??"",source:$.source??"",pid:Number($.pid??0),startedAt:$.startedAt??"",endedAt:$.endedAt?$.endedAt:null,exitCode:typeof $.exitCode==="number"?$.exitCode:null,status:$.status??"running",statusLock:Number($.statusLock??0),interactive:$.interactive===!0,provider:$.provider??"",model:$.model??"",cwd:$.cwd??"",workspaceRoot:$.workspaceRoot??"",teamName:$.teamName||void 0,enableTools:$.enableTools===!0,enableSpawn:$.enableSpawn===!0,enableTeams:$.enableTeams===!0,parentSessionId:$.parentSessionId||void 0,parentAgentId:$.parentAgentId||void 0,agentId:$.agentId||void 0,conversationId:$.conversationId||void 0,isSubagent:$.isSubagent===!0,prompt:$.prompt||void 0,metadata:f0($.metadata),transcriptPath:$.transcriptPath??"",hookPath:$.hookPath??"",messagesPath:$.messagesPath||void 0,updatedAt:$.updatedAt??""}}function uL($){let q=$?.trim();if(!q)return;try{let Y=JSON.parse(q);if(!Array.isArray(Y))return;let T=Y.map((X)=>typeof X==="string"?X.trim():"").filter((X)=>X.length>0);return T.length>0?T:void 0}catch{return}}function nq($){return{scheduleId:$.scheduleId??"",name:$.name??"",cronPattern:$.cronPattern??"",prompt:$.prompt??"",provider:$.provider??"",model:$.model??"",mode:$.mode==="plan"?"plan":"act",workspaceRoot:$.workspaceRoot?.trim()||void 0,cwd:$.cwd?.trim()||void 0,systemPrompt:$.systemPrompt?.trim()||void 0,maxIterations:$.hasMaxIterations?$.maxIterations:void 0,timeoutSeconds:$.hasTimeoutSeconds?$.timeoutSeconds:void 0,maxParallel:typeof $.maxParallel==="number"&&$.maxParallel>0?$.maxParallel:1,enabled:$.enabled===!0,createdAt:$.createdAt??"",updatedAt:$.updatedAt??"",lastRunAt:$.lastRunAt?.trim()||void 0,nextRunAt:$.nextRunAt?.trim()||void 0,createdBy:$.createdBy?.trim()||void 0,tags:uL($.tagsJson??void 0),metadata:f0($.metadata)}}function P5($){return{executionId:$.executionId??"",scheduleId:$.scheduleId??"",sessionId:$.sessionId?.trim()||void 0,triggeredAt:$.triggeredAt??"",startedAt:$.startedAt?.trim()||void 0,endedAt:$.endedAt?.trim()||void 0,status:$.status==="pending"||$.status==="running"||$.status==="success"||$.status==="failed"||$.status==="timeout"||$.status==="aborted"?$.status:"failed",exitCode:$.hasExitCode?$.exitCode:void 0,errorMessage:$.errorMessage?.trim()||void 0,iterations:$.hasIterations?$.iterations:void 0,tokensUsed:$.hasTokensUsed?$.tokensUsed:void 0,costUsd:$.hasCostUsd?$.costUsd:void 0}}class F6{client;constructor($){this.client=fL($.address)}close(){this.client.close()}async upsertSession($){await this.unary((q)=>{let Y={session:bL($)};this.client.UpsertSession(Y,q)})}async getSession($){let q=await this.unary((Y)=>{this.client.GetSession({sessionId:$},Y)});if(!q.session)return;return CE(q.session)}async listSessions($){return((await this.unary((q)=>{this.client.ListSessions($,q)})).sessions??[]).map((q)=>CE(q))}async updateSession($){let q={sessionId:$.sessionId,status:$.status,endedAt:$.endedAt??void 0,setRunning:$.setRunning};if($.exitCode!==void 0)q.hasExitCode=!0,q.exitCode=$.exitCode??0;if($.prompt!==void 0)q.hasPrompt=!0,q.prompt=$.prompt??"";if($.metadata!==void 0)q.hasMetadata=!0,q.metadata=J1($.metadata??void 0);if($.parentSessionId!==void 0)q.hasParentSessionId=!0,q.parentSessionId=$.parentSessionId??"";if($.parentAgentId!==void 0)q.hasParentAgentId=!0,q.parentAgentId=$.parentAgentId??"";if($.agentId!==void 0)q.hasAgentId=!0,q.agentId=$.agentId??"";if($.conversationId!==void 0)q.hasConversationId=!0,q.conversationId=$.conversationId??"";if($.expectedStatusLock!==void 0)q.hasExpectedStatusLock=!0,q.expectedStatusLock=$.expectedStatusLock;let Y=await this.unary((T)=>{this.client.UpdateSession(q,T)});return{updated:Y.updated===!0,statusLock:Number(Y.statusLock??0)}}async deleteSession($,q=!1){return(await this.unary((Y)=>{this.client.DeleteSession({sessionId:$,cascade:q},Y)})).deleted===!0}async enqueueSpawnRequest($){await this.unary((q)=>{this.client.EnqueueSpawnRequest($,q)})}async claimSpawnRequest($,q){let Y=(await this.unary((T)=>{let X={rootSessionId:$,parentAgentId:q};this.client.ClaimSpawnRequest(X,T)})).item?.task?.trim();return Y?Y:void 0}async startRuntimeSession($){let q={workspaceRoot:$.workspaceRoot,cwd:$.cwd??"",provider:$.provider,model:$.model,mode:$.mode,apiKey:$.apiKey,systemPrompt:$.systemPrompt??"",maxIterations:$.maxIterations??0,hasMaxIterations:typeof $.maxIterations==="number",enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,autoApproveTools:$.autoApproveTools??!1,hasAutoApproveTools:typeof $.autoApproveTools==="boolean",teamName:$.teamName,missionStepInterval:$.missionStepInterval,missionTimeIntervalMs:$.missionTimeIntervalMs,toolPolicies:Object.fromEntries(Object.entries($.toolPolicies??{}).map(([X,J])=>[X,{enabled:J.enabled!==!1,autoApprove:J.autoApprove??!1}])),initialMessages:($.initialMessages??[]).map((X)=>({role:X.role??"",content:qq(X.content)})),logger:$.logger?{enabled:$.logger.enabled??!1,level:$.logger.level??"",destination:$.logger.destination??"",name:$.logger.name??"",bindings:J1($.logger.bindings)}:void 0},Y=await this.unary((X)=>{this.client.StartRuntimeSession({request:q},X)}),T=Y.startResult?{sessionId:Y.startResult.sessionId??"",manifestPath:Y.startResult.manifestPath??"",transcriptPath:Y.startResult.transcriptPath??"",hookPath:Y.startResult.hookPath??"",messagesPath:Y.startResult.messagesPath??""}:void 0;return{sessionId:Y.sessionId??"",startResult:T}}async sendRuntimeSession($,q){let Y={config:{workspaceRoot:q.config.workspaceRoot,cwd:q.config.cwd??"",provider:q.config.provider,model:q.config.model,mode:q.config.mode,apiKey:q.config.apiKey,systemPrompt:q.config.systemPrompt??"",maxIterations:q.config.maxIterations??0,hasMaxIterations:typeof q.config.maxIterations==="number",enableTools:q.config.enableTools,enableSpawn:q.config.enableSpawn,enableTeams:q.config.enableTeams,autoApproveTools:q.config.autoApproveTools??!1,hasAutoApproveTools:typeof q.config.autoApproveTools==="boolean",teamName:q.config.teamName,missionStepInterval:q.config.missionStepInterval,missionTimeIntervalMs:q.config.missionTimeIntervalMs,toolPolicies:Object.fromEntries(Object.entries(q.config.toolPolicies??{}).map(([X,J])=>[X,{enabled:J.enabled!==!1,autoApprove:J.autoApprove??!1}])),initialMessages:(q.config.initialMessages??[]).map((X)=>({role:X.role??"",content:qq(X.content)})),logger:q.config.logger?{enabled:q.config.logger.enabled??!1,level:q.config.logger.level??"",destination:q.config.logger.destination??"",name:q.config.logger.name??"",bindings:J1(q.config.logger.bindings)}:void 0},messages:(q.messages??[]).map((X)=>({role:X.role??"",content:qq(X.content)})),prompt:q.prompt,attachments:q.attachments?{userImages:q.attachments.userImages??[],userFiles:(q.attachments.userFiles??[]).map((X)=>({name:X.name,content:X.content}))}:void 0},T=await this.unary((X)=>{this.client.SendRuntimeSession({sessionId:$,request:Y},X)});return{result:{text:T.result?.text??"",usage:{inputTokens:Number(T.result?.usage?.inputTokens??0),outputTokens:Number(T.result?.usage?.outputTokens??0),cacheReadTokens:T.result?.usage?.hasCacheReadTokens?Number(T.result?.usage?.cacheReadTokens??0):void 0,cacheWriteTokens:T.result?.usage?.hasCacheWriteTokens?Number(T.result?.usage?.cacheWriteTokens??0):void 0,totalCost:T.result?.usage?.hasTotalCost?Number(T.result?.usage?.totalCost??0):void 0},inputTokens:Number(T.result?.inputTokens??0),outputTokens:Number(T.result?.outputTokens??0),iterations:Number(T.result?.iterations??0),finishReason:T.result?.finishReason??"",messages:(T.result?.messages??[]).map((X)=>({role:X.role??"",content:Yq(X.content)})),toolCalls:(T.result?.toolCalls??[]).map((X)=>({name:X.name??"",input:X.hasInput?Yq(X.input):void 0,output:X.hasOutput?Yq(X.output):void 0,error:X.error?.trim()||void 0,durationMs:X.hasDurationMs?Number(X.durationMs??0):void 0}))}}}async abortRuntimeSession($){return{applied:(await this.unary((q)=>{this.client.AbortRuntimeSession({sessionId:$},q)})).applied===!0}}async requestToolApproval($){let q={approvalId:$.approvalId,sessionId:$.sessionId,taskId:$.taskId,toolCallId:$.toolCallId,toolName:$.toolName,inputJson:$.inputJson,requesterClientId:$.requesterClientId,timeoutMs:$.timeoutMs},Y=await this.unary((T)=>{this.client.RequestToolApproval(q,T)});return{approvalId:Y.approvalId??"",decided:Y.decided===!0,approved:Y.approved===!0,reason:Y.reason??""}}async respondToolApproval($){let q={approvalId:$.approvalId,approved:$.approved,reason:$.reason,responderClientId:$.responderClientId},Y=await this.unary((T)=>{this.client.RespondToolApproval(q,T)});return{approvalId:Y.approvalId??"",applied:Y.applied===!0}}async listPendingApprovals($){return((await this.unary((q)=>{this.client.ListPendingApprovals({sessionId:$},q)})).approvals??[]).map((q)=>({approvalId:q.approvalId??"",sessionId:q.sessionId??"",taskId:q.taskId??"",toolCallId:q.toolCallId??"",toolName:q.toolName??"",inputJson:q.inputJson??"",requesterClientId:q.requesterClientId??"",createdAt:q.createdAt??""}))}async createSchedule($){let q=await this.unary((Y)=>{this.client.CreateSchedule({name:$.name,cronPattern:$.cronPattern,prompt:$.prompt,provider:$.provider,model:$.model,mode:$.mode??"act",workspaceRoot:$.workspaceRoot,cwd:$.cwd,systemPrompt:$.systemPrompt,maxIterations:$.maxIterations??0,hasMaxIterations:typeof $.maxIterations==="number",timeoutSeconds:$.timeoutSeconds??0,hasTimeoutSeconds:typeof $.timeoutSeconds==="number",maxParallel:$.maxParallel??1,enabled:$.enabled??!0,createdBy:$.createdBy,tagsJson:$.tags?JSON.stringify($.tags):"",metadata:J1($.metadata)},Y)});return q.schedule?nq(q.schedule):void 0}async getSchedule($){let q=await this.unary((Y)=>{this.client.GetSchedule({scheduleId:$},Y)});return q.schedule?nq(q.schedule):void 0}async listSchedules($){return((await this.unary((q)=>{this.client.ListSchedules({limit:$?.limit??100,hasEnabled:typeof $?.enabled==="boolean",enabled:$?.enabled??!1,tagsJson:$?.tags?JSON.stringify($.tags):""},q)})).schedules??[]).map((q)=>nq(q))}async updateSchedule($,q){let Y={scheduleId:$};if(q.name!==void 0)Y.hasName=!0,Y.name=q.name;if(q.cronPattern!==void 0)Y.hasCronPattern=!0,Y.cronPattern=q.cronPattern;if(q.prompt!==void 0)Y.hasPrompt=!0,Y.prompt=q.prompt;if(q.provider!==void 0)Y.hasProvider=!0,Y.provider=q.provider;if(q.model!==void 0)Y.hasModel=!0,Y.model=q.model;if(q.mode!==void 0)Y.hasMode=!0,Y.mode=q.mode;if(q.workspaceRoot!==void 0)Y.hasWorkspaceRoot=!0,Y.workspaceRoot=q.workspaceRoot;if(q.cwd!==void 0)Y.hasCwd=!0,Y.cwd=q.cwd;if(q.systemPrompt!==void 0)Y.hasSystemPrompt=!0,Y.systemPrompt=q.systemPrompt;if(q.maxIterations===null)Y.clearMaxIterations=!0;else if(q.maxIterations!==void 0)Y.hasMaxIterations=!0,Y.maxIterations=q.maxIterations;if(q.timeoutSeconds===null)Y.clearTimeoutSeconds=!0;else if(q.timeoutSeconds!==void 0)Y.hasTimeoutSeconds=!0,Y.timeoutSeconds=q.timeoutSeconds;if(q.maxParallel!==void 0)Y.hasMaxParallel=!0,Y.maxParallel=q.maxParallel;if(q.enabled!==void 0)Y.hasEnabled=!0,Y.enabled=q.enabled;if(q.createdBy===null)Y.clearCreatedBy=!0;else if(q.createdBy!==void 0)Y.hasCreatedBy=!0,Y.createdBy=q.createdBy;if(q.tags!==void 0)Y.hasTagsJson=!0,Y.tagsJson=JSON.stringify(q.tags);if(q.metadata!==void 0)Y.hasMetadata=!0,Y.metadata=J1(q.metadata);let T=await this.unary((X)=>{this.client.UpdateSchedule(Y,X)});return T.schedule?nq(T.schedule):void 0}async deleteSchedule($){return(await this.unary((q)=>{this.client.DeleteSchedule({scheduleId:$},q)})).deleted===!0}async pauseSchedule($){let q=await this.unary((Y)=>{this.client.PauseSchedule({scheduleId:$},Y)});return q.schedule?nq(q.schedule):void 0}async resumeSchedule($){let q=await this.unary((Y)=>{this.client.ResumeSchedule({scheduleId:$},Y)});return q.schedule?nq(q.schedule):void 0}async triggerScheduleNow($){let q=await this.unary((Y)=>{this.client.TriggerScheduleNow({scheduleId:$},Y)});return q.execution?P5(q.execution):void 0}async listScheduleExecutions($){return((await this.unary((q)=>{this.client.ListScheduleExecutions({scheduleId:$.scheduleId,status:$.status,limit:$.limit??50},q)})).executions??[]).map((q)=>P5(q))}async getScheduleStats($){let q=await this.unary((Y)=>{this.client.GetScheduleStats({scheduleId:$},Y)});return{totalRuns:Number(q.totalRuns??0),successRate:Number(q.successRate??0),avgDurationSeconds:Number(q.avgDurationSeconds??0),lastFailure:q.lastFailure?P5(q.lastFailure):void 0}}async getActiveScheduledExecutions(){return((await this.unary(($)=>{this.client.GetActiveScheduledExecutions({},$)})).executions??[]).map(($)=>({executionId:$.executionId??"",scheduleId:$.scheduleId??"",sessionId:$.sessionId??"",startedAt:$.startedAt??"",timeoutAt:$.timeoutAt?.trim()||void 0}))}async getUpcomingScheduledRuns($=20){return((await this.unary((q)=>{this.client.GetUpcomingScheduledRuns({limit:$},q)})).runs??[]).map((q)=>({scheduleId:q.scheduleId??"",name:q.name??"",nextRunAt:q.nextRunAt??""}))}async stopRuntimeSession($){return{applied:(await this.unary((q)=>{this.client.StopRuntimeSession({sessionId:$},q)})).applied===!0}}async runProviderAction($){let q=$.action==="listProviders"?{listProviders:{}}:$.action==="getProviderModels"?{getProviderModels:{providerId:$.providerId}}:$.action==="addProvider"?{addProvider:{providerId:$.providerId,name:$.name,baseUrl:$.baseUrl,apiKey:$.apiKey??"",headers:$.headers??{},timeoutMs:$.timeoutMs??0,hasTimeoutMs:typeof $.timeoutMs==="number",models:$.models??[],defaultModelId:$.defaultModelId??"",modelsSourceUrl:$.modelsSourceUrl??"",capabilities:$.capabilities??[]}}:$.action==="saveProviderSettings"?{saveProviderSettings:{providerId:$.providerId,enabled:$.enabled??!1,hasEnabled:typeof $.enabled==="boolean",apiKey:$.apiKey??"",hasApiKey:$.apiKey!==void 0,baseUrl:$.baseUrl??"",hasBaseUrl:$.baseUrl!==void 0}}:{clineAccount:{operation:$.operation,userId:"userId"in $?$.userId??"":"",organizationId:"organizationId"in $?$.organizationId??"":"",memberId:"memberId"in $?$.memberId??"":"",clearOrganizationId:"organizationId"in $&&$.organizationId===null}},Y=await this.unary((T)=>{this.client.RunProviderAction({request:q},T)});return{result:Yq(Y.result)}}async runProviderOAuthLogin($){let q=await this.unary((Y)=>{this.client.RunProviderOAuthLogin({provider:$},Y)});return{provider:q.provider??"",accessToken:q.apiKey??""}}async publishEvent($){let q=await this.unary((Y)=>{this.client.PublishEvent({eventId:$.eventId,sessionId:$.sessionId,taskId:$.taskId,eventType:$.eventType,payload:J1($.payload),sourceClientId:$.sourceClientId},Y)});return{eventId:q.eventId??"",accepted:q.accepted===!0}}streamEvents($,q={}){let Y=!1,T=this.client.StreamEvents({clientId:$.clientId??"",sessionIds:$.sessionIds??[]}),X=(U)=>{q.onEvent?.({eventId:U.eventId??"",sessionId:U.sessionId??"",taskId:U.taskId?.trim()?U.taskId:void 0,eventType:U.eventType??"",payload:f0(U.payload)??{},sourceClientId:U.sourceClientId?.trim()?U.sourceClientId:void 0,ts:U.ts??""})},J=(U)=>{let Z=(typeof U.code==="number"?Number(U.code):void 0)===1||U.message.includes("CANCELLED");if(Y&&Z)return;q.onError?.(U)},Q=()=>{q.onEnd?.()};return T.on("data",X),T.on("error",J),T.on("end",Q),()=>{Y=!0,T.cancel()}}streamTeamProgress($,q={}){return this.streamEvents($,{onEvent:(Y)=>{if(Y.eventType===I9){try{let T=Y.payload;if(T.type==="team_progress_projection"&&T.version===1)q.onProjection?.(T)}catch{}return}if(Y.eventType===N9)try{q.onLifecycle?.(Y.payload)}catch{}},onError:q.onError,onEnd:q.onEnd})}async unary($){return await new Promise((q,Y)=>{$((T,X)=>{if(T){Y(T);return}q(X??{})})})}}class I6{client;constructor($=I6.resolveAddress()){this.client=new F6({address:$})}static resolveAddress(){return process.env.CLINE_RPC_ADDRESS?.trim()||"127.0.0.1:4317"}async startSession($){let q=(await this.client.startRuntimeSession($)).sessionId?.trim();if(!q)throw Error("runtime start returned an empty session id");return q}async sendSession($,q){return(await this.client.sendRuntimeSession($,q)).result}async abortSession($){return(await this.client.abortRuntimeSession($)).applied}streamEvents($,q,Y){return this.client.streamEvents({clientId:$,sessionIds:q},{onEvent:Y.onEvent,onError:Y.onError})}close(){this.client.close()}}function cL($){let q=new Set,Y=[];for(let T of $){let X=T.trim();if(!X||q.has(X))continue;q.add(X),Y.push(X)}return Y}function pL($,q){if($.length!==q.length)return!1;for(let Y=0;Y<$.length;Y+=1)if($[Y]!==q[Y])return!1;return!0}function lL($,q){let Y=typeof $.accumulated==="string"?$.accumulated:void 0;if(typeof Y==="string"){if(Y.startsWith(q))return{delta:Y.slice(q.length),nextAccumulated:Y};if(q.startsWith(Y))return{delta:"",nextAccumulated:q}}let T=typeof $.text==="string"?$.text:"";return{delta:T,nextAccumulated:`${q}${T}`}}function _E($){let q,Y=[],T=new Map,X=()=>{q?.(),q=void 0},J=()=>{if(X(),Y.length===0)return;q=$.client.streamEvents($.clientId,Y,{onEvent:(Q)=>{let U=Q.payload;if(Q.eventType==="runtime.chat.text_delta"){let Z=T.get(Q.sessionId)??"",K=lL(U,Z);if(T.set(Q.sessionId,K.nextAccumulated),!K.delta)return;$.writeLine({type:"chat_text",sessionId:Q.sessionId,chunk:K.delta});return}if(Q.eventType==="runtime.chat.tool_call_start"){$.writeLine({type:"tool_call_start",sessionId:Q.sessionId,toolCallId:typeof U.toolCallId==="string"?U.toolCallId:void 0,toolName:typeof U.toolName==="string"?U.toolName:void 0,input:U.input});return}if(Q.eventType==="runtime.chat.tool_call_end")$.writeLine({type:"tool_call_end",sessionId:Q.sessionId,toolCallId:typeof U.toolCallId==="string"?U.toolCallId:void 0,toolName:typeof U.toolName==="string"?U.toolName:void 0,output:U.output,error:typeof U.error==="string"?U.error:void 0,durationMs:typeof U.durationMs==="number"?U.durationMs:void 0})},onError:(Q)=>{$.writeLine({type:"error",message:Q.message})}})};return{applySessions:(Q)=>{let U=cL(Q).sort();if(pL(Y,U))return;Y=U;for(let Z of Array.from(T.keys()))if(!U.includes(Z))T.delete(Z);J()},resetSession:(Q)=>{let U=Q?.trim();if(U){T.delete(U);return}T.clear()},stop:X}}function nL(){let $=process.env.CLINE_RPC_RUNTIME_SEND_TIMEOUT_MS?.trim(),q=$?Number.parseInt($,10):Number.NaN;if(Number.isInteger(q)&&q>0)return q;return 120000}async function iL($){let q=new I6,Y=_E({client:q,clientId:$.clientId,writeLine:(Q)=>{$.writeLine(Q)}}),T=(Q)=>{$.writeLine(Q)},X=async(Q,U)=>{if(U.action==="start"){$.onBeforeStart?.(U.config);let Z=await q.startSession(U.config);return T({type:"response",requestId:Q,response:{sessionId:Z}}),!1}if(U.action==="send"){$.onBeforeSend?.(U.request);let Z=nL(),K=await Promise.race([q.sendSession(U.sessionId,U.request),new Promise((W,G)=>{setTimeout(()=>{G(Error(`runtime send timed out after ${Z}ms for session ${U.sessionId}`))},Z)})]),A=$.parseSendResult?$.parseSendResult(K):K;return T({type:"response",requestId:Q,response:{result:A}}),!1}if(U.action==="abort"){let Z=await q.abortSession(U.sessionId);return T({type:"response",requestId:Q,response:{ok:Z}}),!1}if(U.action==="set_sessions")return Y.applySessions(U.sessionIds??[]),T({type:"response",requestId:Q,response:{ok:!0}}),!1;if(U.action==="reset")return Y.resetSession(U.sessionId),T({type:"response",requestId:Q,response:{ok:!0}}),!1;if(U.action==="shutdown")return T({type:"response",requestId:Q,response:{ok:!0}}),!0;return!1};$.writeLine({type:"ready"});let J=dL({input:process.stdin,output:process.stderr,terminal:!1});try{for await(let Q of J){let U=Q.trim();if(!U)continue;let Z;try{Z=JSON.parse(U)}catch{$.writeLine({type:"error",message:"invalid bridge request json"});continue}if(Z.type!=="request"){T({type:"response",requestId:Z.requestId||"",error:"invalid bridge request envelope"});continue}let K=Z.requestId?.trim();if(!K){$.writeLine({type:"error",message:"bridge request missing requestId"});continue}try{if(await X(K,Z.command))break}catch(A){let W=A instanceof Error?A.message:String(A);T({type:"response",requestId:K,error:W})}}}finally{Y.stop(),q.close()}}async function aL($){let q=new I6,Y=_E({client:q,clientId:$.clientId,writeLine:$.writeLine});$.writeLine({type:"ready"}),await new Promise((T)=>{let X=rL({input:process.stdin,output:process.stderr,terminal:!1}),J=()=>{Y.stop(),q.close(),T()};X.on("line",(Q)=>{let U=Q.trim();if(!U)return;let Z;try{Z=JSON.parse(U)}catch{$.writeLine({type:"error",message:"invalid bridge control json"});return}if(Z.type==="set_sessions"){Y.applySessions(Z.sessionIds??[]);return}if(Z.type==="shutdown")X.close()}),X.on("close",J)})}var fE="127.0.0.1:4317",oL="cline.rpc.v1",bE="ClineGateway";function sL($){let q=$.trim(),Y=q.lastIndexOf(":");if(Y<=0||Y>=q.length-1)throw Error(`Invalid RPC address: ${$}`);let T=q.slice(0,Y),X=Number.parseInt(q.slice(Y+1),10);if(!Number.isInteger(X)||X<=0)throw Error(`Invalid RPC port in address: ${$}`);return{host:T,port:X}}function tL(){return kE(import.meta.url)}function uE(){let $=mE.loadSync(tL(),{keepCase:!1,longs:String,enums:String,defaults:!0,oneofs:!0}),q=gE.loadPackageDefinition($).cline?.rpc?.v1?.ClineGateway?.service;if(!q)throw Error(`Unable to load ${oL}.${bE} from proto`);return q}function Tq(){return new Date().toISOString()}function I($){return typeof $==="string"?$:""}function eL($){if(!$||typeof $!=="object")return{};let q={};for(let[Y,T]of Object.entries($)){let X=Y.trim();if(!X)continue;let J=I(T).trim();if(!J)continue;q[X]=J}return q}function $w($){if(!Array.isArray($)||$.length===0)return;let q=new Set;for(let Y of $){let T=Y.trim();if(T)q.add(T)}return q.size>0?q:void 0}function dE($){if($==="running"||$==="completed"||$==="failed"||$==="cancelled")return $;return"running"}function yE($){return{sessionId:$.sessionId,source:$.source,pid:$.pid,startedAt:$.startedAt,endedAt:$.endedAt??"",exitCode:$.exitCode??0,status:$.status,statusLock:$.statusLock,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??"",enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:$.parentSessionId??"",parentAgentId:$.parentAgentId??"",agentId:$.agentId??"",conversationId:$.conversationId??"",isSubagent:$.isSubagent,prompt:$.prompt??"",transcriptPath:$.transcriptPath,hookPath:$.hookPath,messagesPath:$.messagesPath??"",updatedAt:$.updatedAt,metadata:J1($.metadata)}}function qw($){let q=I($.sessionId).trim(),Y=I($.source).trim(),T=I($.startedAt).trim(),X=I($.provider).trim(),J=I($.model).trim(),Q=I($.cwd).trim(),U=I($.workspaceRoot).trim(),Z=I($.transcriptPath).trim(),K=I($.hookPath).trim();if(!q||!Y||!T||!X||!J||!Q||!U||!Z||!K)throw Error("session record is missing required fields");return{sessionId:q,source:Y,pid:Number($.pid??0),startedAt:T,endedAt:I($.endedAt).trim()||null,exitCode:typeof $.exitCode==="number"?Math.floor($.exitCode):null,status:dE(I($.status).trim()),statusLock:typeof $.statusLock==="number"?Math.floor($.statusLock):0,interactive:$.interactive===!0,provider:X,model:J,cwd:Q,workspaceRoot:U,teamName:I($.teamName).trim()||void 0,enableTools:$.enableTools===!0,enableSpawn:$.enableSpawn===!0,enableTeams:$.enableTeams===!0,parentSessionId:I($.parentSessionId).trim()||void 0,parentAgentId:I($.parentAgentId).trim()||void 0,agentId:I($.agentId).trim()||void 0,conversationId:I($.conversationId).trim()||void 0,isSubagent:$.isSubagent===!0,prompt:I($.prompt).trim()||void 0,metadata:f0($.metadata),transcriptPath:Z,hookPath:K,messagesPath:I($.messagesPath).trim()||void 0,updatedAt:I($.updatedAt).trim()||Tq()}}function O5($){let q=I($).trim();if(!q)return;try{let Y=JSON.parse(q);if(!Array.isArray(Y))return;let T=Y.map((X)=>typeof X==="string"?X.trim():"").filter((X)=>X.length>0);return T.length>0?T:void 0}catch{return}}function iq($){return{scheduleId:$.scheduleId,name:$.name,cronPattern:$.cronPattern,prompt:$.prompt,provider:$.provider,model:$.model,mode:$.mode,workspaceRoot:$.workspaceRoot??"",cwd:$.cwd??"",systemPrompt:$.systemPrompt??"",maxIterations:$.maxIterations??0,hasMaxIterations:typeof $.maxIterations==="number",timeoutSeconds:$.timeoutSeconds??0,hasTimeoutSeconds:typeof $.timeoutSeconds==="number",maxParallel:$.maxParallel,enabled:$.enabled,createdAt:$.createdAt,updatedAt:$.updatedAt,lastRunAt:$.lastRunAt??"",nextRunAt:$.nextRunAt??"",createdBy:$.createdBy??"",tagsJson:$.tags?JSON.stringify($.tags):"",metadata:J1($.metadata)}}function L5($){return{executionId:$.executionId,scheduleId:$.scheduleId,sessionId:$.sessionId??"",triggeredAt:$.triggeredAt,startedAt:$.startedAt??"",endedAt:$.endedAt??"",status:$.status,exitCode:$.exitCode??0,hasExitCode:typeof $.exitCode==="number",errorMessage:$.errorMessage??"",iterations:$.iterations??0,hasIterations:typeof $.iterations==="number",tokensUsed:$.tokensUsed??0,hasTokensUsed:typeof $.tokensUsed==="number",costUsd:$.costUsd??0,hasCostUsd:typeof $.costUsd==="number"}}function w5($){return new(z8.makeGenericClientConstructor(uE(),bE))($,z8.credentials.createInsecure())}async function S5($){return await new Promise((q)=>{let Y;try{Y=w5($)}catch{q(void 0);return}Y.Health({},(T,X)=>{if(Y?.close(),T||!X){q(void 0);return}q(X)})})}async function Yw($){return await new Promise((q)=>{let Y;try{Y=w5($)}catch{q(void 0);return}Y.Shutdown({},(T,X)=>{if(Y?.close(),T||!X){q(void 0);return}q(X)})})}async function Tw($,q){return await new Promise((Y)=>{let T;try{T=w5($)}catch{Y(void 0);return}T.RegisterClient({clientId:q.clientId,clientType:q.clientType,metadata:q.metadata??{}},(X,J)=>{if(T?.close(),X||!J){Y(void 0);return}Y({clientId:I(J.clientId).trim(),registered:J.registered===!0})})})}var Qw=300000;class cE{publishEvent;approvals=new Map;constructor($){this.publishEvent=$}async requestToolApproval($){let q=I($.sessionId).trim(),Y=I($.toolCallId).trim(),T=I($.toolName).trim();if(!q||!Y||!T)throw Error("sessionId, toolCallId, and toolName are required");let X=I($.approvalId).trim()||`apr_${Jw()}`;if(!this.approvals.get(X)){let Z={approvalId:X,sessionId:q,taskId:I($.taskId).trim()||void 0,toolCallId:Y,toolName:T,inputJson:I($.inputJson),requesterClientId:I($.requesterClientId).trim()||void 0,createdAt:Tq(),status:"pending",waiters:[]};this.approvals.set(X,Z),this.publishEvent({eventId:"",sessionId:q,taskId:Z.taskId,eventType:"approval.requested",payload:J1(Z),sourceClientId:Z.requesterClientId})}let J=this.approvals.get(X);if(!J)throw Error("approval state not found");if(J.status==="approved"||J.status==="rejected")return{approvalId:X,decided:!0,approved:J.status==="approved",reason:J.reason??""};let Q=typeof $.timeoutMs==="number"&&$.timeoutMs>0?Math.floor($.timeoutMs):Qw,U=await new Promise((Z)=>{let K=setTimeout(()=>{Z({decided:!1,approved:!1,reason:"Tool approval request timed out"})},Q);J.waiters.push((A)=>{clearTimeout(K),Z(A)})});return{approvalId:X,decided:U.decided,approved:U.approved,reason:U.reason??""}}respondToolApproval($){let q=I($.approvalId).trim();if(!q)throw Error("approvalId is required");let Y=this.approvals.get(q);if(!Y)return{approvalId:q,applied:!1};Y.status=$.approved===!0?"approved":"rejected",Y.reason=I($.reason).trim()||void 0;let T={decided:!0,approved:Y.status==="approved",reason:Y.reason};for(let X of Y.waiters.splice(0))X(T);return this.publishEvent({eventId:"",sessionId:Y.sessionId,taskId:Y.taskId,eventType:"approval.decided",payload:J1({approvalId:q,approved:T.approved,reason:T.reason??"",responderClientId:I($.responderClientId).trim()||""}),sourceClientId:I($.responderClientId).trim()||""}),{approvalId:q,applied:!0}}listPendingApprovals($){let q=I($.sessionId).trim(),Y=[];for(let T of this.approvals.values()){if(T.status!=="pending")continue;if(q&&T.sessionId!==q)continue;Y.push({approvalId:T.approvalId,sessionId:T.sessionId,taskId:T.taskId??"",toolCallId:T.toolCallId,toolName:T.toolName,inputJson:T.inputJson,requesterClientId:T.requesterClientId??"",createdAt:T.createdAt})}return Y.sort((T,X)=>(T.createdAt??"").localeCompare(X.createdAt??"")),{approvals:Y}}}class pE{subscribers=new Map;nextSubscriberId=1;publishEvent($){let q=I($.sessionId).trim();if(!q)throw Error("sessionId is required");let Y={eventId:I($.eventId).trim()||`evt_${vE()}`,sessionId:q,taskId:I($.taskId).trim()||void 0,eventType:I($.eventType).trim()||"unknown",payload:f0($.payload)??{},sourceClientId:I($.sourceClientId).trim()||void 0,ts:Tq()};return this.dispatchEvent(Y),{eventId:Y.eventId,accepted:!0}}addSubscriber($){let q=$.request,Y=$w(q.sessionIds),T=this.nextSubscriberId;return this.nextSubscriberId+=1,this.subscribers.set(T,{call:$,filterSessionIds:Y}),$.on("cancelled",()=>{this.subscribers.delete(T)}),$.on("close",()=>{this.subscribers.delete(T)}),T}removeSubscriber($){this.subscribers.delete($)}broadcastServerEvent($,q){let Y=`evt_${vE()}`,T=Tq();for(let X of this.subscribers.values())X.call.write({eventId:Y,sessionId:"__rpc__",taskId:"",eventType:$,payload:J1(q),sourceClientId:"rpc-server",ts:T})}dispatchEvent($){for(let q of this.subscribers.values()){if(q.filterSessionIds&&!q.filterSessionIds.has($.sessionId))continue;q.call.write({eventId:$.eventId,sessionId:$.sessionId,taskId:$.taskId??"",eventType:$.eventType,payload:J1($.payload),sourceClientId:$.sourceClientId??"",ts:$.ts})}}}class lE{scheduler;constructor($){this.scheduler=$}createSchedule($){let q=this.requireScheduler(),Y={name:I($.name).trim(),cronPattern:I($.cronPattern).trim(),prompt:I($.prompt),provider:I($.provider).trim(),model:I($.model).trim(),mode:I($.mode).trim()==="plan"?"plan":"act",workspaceRoot:I($.workspaceRoot).trim()||void 0,cwd:I($.cwd).trim()||void 0,systemPrompt:I($.systemPrompt)||void 0,maxIterations:$.hasMaxIterations?Math.floor($.maxIterations??0):void 0,timeoutSeconds:$.hasTimeoutSeconds?Math.floor($.timeoutSeconds??0):void 0,maxParallel:typeof $.maxParallel==="number"&&$.maxParallel>0?Math.floor($.maxParallel):1,enabled:$.enabled!==!1,createdBy:I($.createdBy).trim()||void 0,tags:O5(I($.tagsJson)),metadata:f0($.metadata)};if(!Y.name||!Y.cronPattern||!Y.prompt.trim()||!Y.provider||!Y.model)throw Error("name, cronPattern, prompt, provider, and model are required");let T=q.createSchedule(Y);return{schedule:iq(T)}}getSchedule($){let q=this.requireScheduler(),Y=I($.scheduleId).trim();if(!Y)throw Error("scheduleId is required");let T=q.getSchedule(Y);return T?{schedule:iq(T)}:{}}listSchedules($){return{schedules:this.requireScheduler().listSchedules({enabled:$.hasEnabled?$.enabled===!0:void 0,limit:typeof $.limit==="number"&&$.limit>0?Math.floor($.limit):void 0,tags:O5(I($.tagsJson))}).map((q)=>iq(q))}}updateSchedule($){let q=this.requireScheduler(),Y=I($.scheduleId).trim();if(!Y)throw Error("scheduleId is required");let T={};if($.hasName)T.name=I($.name);if($.hasCronPattern)T.cronPattern=I($.cronPattern);if($.hasPrompt)T.prompt=I($.prompt);if($.hasProvider)T.provider=I($.provider);if($.hasModel)T.model=I($.model);if($.hasMode)T.mode=I($.mode).trim()==="plan"?"plan":"act";if($.hasWorkspaceRoot)T.workspaceRoot=I($.workspaceRoot);if($.hasCwd)T.cwd=I($.cwd);if($.hasSystemPrompt)T.systemPrompt=I($.systemPrompt);if($.clearMaxIterations)T.maxIterations=null;else if($.hasMaxIterations)T.maxIterations=Math.floor($.maxIterations??0);if($.clearTimeoutSeconds)T.timeoutSeconds=null;else if($.hasTimeoutSeconds)T.timeoutSeconds=Math.floor($.timeoutSeconds??0);if($.hasMaxParallel)T.maxParallel=Math.floor($.maxParallel??1);if($.hasEnabled)T.enabled=$.enabled===!0;if($.clearCreatedBy)T.createdBy=null;else if($.hasCreatedBy)T.createdBy=I($.createdBy);if($.hasTagsJson)T.tags=O5(I($.tagsJson))??[];if($.hasMetadata)T.metadata=f0($.metadata)??{};let X=q.updateSchedule(Y,T);return{updated:X!==void 0,schedule:X?iq(X):void 0}}deleteSchedule($){let q=this.requireScheduler(),Y=I($.scheduleId).trim();if(!Y)throw Error("scheduleId is required");return{deleted:q.deleteSchedule(Y)}}pauseSchedule($){let q=this.requireScheduler(),Y=I($.scheduleId).trim();if(!Y)throw Error("scheduleId is required");let T=q.pauseSchedule(Y);return{updated:T!==void 0,schedule:T?iq(T):void 0}}resumeSchedule($){let q=this.requireScheduler(),Y=I($.scheduleId).trim();if(!Y)throw Error("scheduleId is required");let T=q.resumeSchedule(Y);return{updated:T!==void 0,schedule:T?iq(T):void 0}}async triggerScheduleNow($){let q=this.requireScheduler(),Y=I($.scheduleId).trim();if(!Y)throw Error("scheduleId is required");let T=await q.triggerScheduleNow(Y);return T?{execution:L5(T)}:{}}listScheduleExecutions($){let q=this.requireScheduler(),Y=I($.scheduleId).trim()||void 0,T=I($.status).trim()||void 0;return{executions:q.listScheduleExecutions({scheduleId:Y,status:T==="pending"||T==="running"||T==="success"||T==="failed"||T==="timeout"||T==="aborted"?T:void 0,limit:typeof $.limit==="number"&&$.limit>0?Math.floor($.limit):void 0}).map((X)=>L5(X))}}getScheduleStats($){let q=this.requireScheduler(),Y=I($.scheduleId).trim();if(!Y)throw Error("scheduleId is required");let T=q.getScheduleStats(Y);return{totalRuns:T.totalRuns,successRate:T.successRate,avgDurationSeconds:T.avgDurationSeconds,lastFailure:T.lastFailure?L5(T.lastFailure):void 0}}getActiveScheduledExecutions($){return{executions:this.requireScheduler().getActiveExecutions().map((q)=>({executionId:q.executionId,scheduleId:q.scheduleId,sessionId:q.sessionId,startedAt:q.startedAt,timeoutAt:q.timeoutAt??""}))}}getUpcomingScheduledRuns($){let q=this.requireScheduler(),Y=typeof $.limit==="number"&&$.limit>0?Math.floor($.limit):20;return{runs:q.getUpcomingRuns(Y).map((T)=>({scheduleId:T.scheduleId,name:T.name,nextRunAt:T.nextRunAt}))}}requireScheduler(){if(!this.scheduler)throw Error("scheduler service is not configured");return this.scheduler}}class nE{serverId=jE();address;startedAt;runtimeHandlers;sessions=new Map;tasks=new Map;clients=new Map;store;eventService=new pE;approvalService=new cE(($)=>this.eventService.publishEvent($));scheduleService;constructor($,q,Y,T){this.address=$,this.startedAt=Tq(),this.store=q,this.runtimeHandlers=Y,this.scheduleService=new lE(T),this.store.init()}health(){return{serverId:this.serverId,address:this.address,running:!0,startedAt:this.startedAt}}registerClient($){let q=I($.clientId).trim()||`client_${jE()}`,Y=I($.clientType).trim()||void 0,T=eL($),X=Tq(),J=this.clients.get(q),Q=J?{...J,clientType:Y??J.clientType,metadata:Object.keys(T).length>0?{...J.metadata??{},...T}:J.metadata,lastRegisteredAt:X,activationCount:J.activationCount+1}:{clientId:q,clientType:Y,metadata:Object.keys(T).length>0?T:void 0,firstRegisteredAt:X,lastRegisteredAt:X,activationCount:1};return this.clients.set(q,Q),this.broadcastServerEvent("rpc.client.activated",{clientId:Q.clientId,clientType:Q.clientType,metadata:Q.metadata??{},firstRegisteredAt:Q.firstRegisteredAt,lastRegisteredAt:Q.lastRegisteredAt,activationCount:Q.activationCount}),{clientId:q,registered:!0}}ensureSession($){let q=I($.sessionId).trim();if(!q)throw Error("sessionId is required");let Y=this.sessions.get(q);if(Y)return Y.status=I($.status).trim()||Y.status,Y.workspaceRoot=I($.workspaceRoot).trim()||Y.workspaceRoot,Y.clientId=I($.clientId).trim()||Y.clientId,Y.metadata=f0($.metadata)??Y.metadata,{sessionId:q,created:!1,status:Y.status};let T=I($.status).trim()||"running";return this.sessions.set(q,{sessionId:q,status:T,workspaceRoot:I($.workspaceRoot).trim()||void 0,clientId:I($.clientId).trim()||void 0,metadata:f0($.metadata)}),{sessionId:q,created:!0,status:T}}upsertSession($){if(!$.session)throw Error("session is required");return this.store.upsertSession(qw($.session)),{persisted:!0}}getSession($){let q=I($.sessionId).trim();if(!q)throw Error("sessionId is required");let Y=this.store.getSession(q);if(!Y)return{};return{session:yE(Y)}}listSessions($){let q=typeof $.limit==="number"&&$.limit>0?Math.floor($.limit):200;return{sessions:this.store.listSessions({limit:q,parentSessionId:I($.parentSessionId).trim()||void 0,status:I($.status).trim()||void 0}).map((Y)=>yE(Y))}}updateSession($){let q=I($.sessionId).trim();if(!q)throw Error("sessionId is required");return this.store.updateSession({sessionId:q,status:$.status?dE($.status):void 0,endedAt:$.endedAt?$.endedAt:void 0,exitCode:$.hasExitCode?$.exitCode??null:void 0,prompt:$.hasPrompt?$.prompt??null:void 0,metadata:$.hasMetadata?f0($.metadata)??null:void 0,parentSessionId:$.hasParentSessionId?$.parentSessionId??null:void 0,parentAgentId:$.hasParentAgentId?$.parentAgentId??null:void 0,agentId:$.hasAgentId?$.agentId??null:void 0,conversationId:$.hasConversationId?$.conversationId??null:void 0,expectedStatusLock:$.hasExpectedStatusLock?$.expectedStatusLock:void 0,setRunning:$.setRunning===!0})}deleteSession($){let q=I($.sessionId).trim();if(!q)throw Error("sessionId is required");let Y=this.store.deleteSession(q);if($.cascade===!0)this.store.deleteSessionsByParent(q);return{deleted:Y}}enqueueSpawnRequest($){let q=I($.rootSessionId).trim(),Y=I($.parentAgentId).trim();if(!q||!Y)throw Error("rootSessionId and parentAgentId are required");return this.store.enqueueSpawnRequest({rootSessionId:q,parentAgentId:Y,task:I($.task).trim()||void 0,systemPrompt:I($.systemPrompt).trim()||void 0}),{enqueued:!0}}claimSpawnRequest($){let q=I($.rootSessionId).trim(),Y=I($.parentAgentId).trim();if(!q||!Y)throw Error("rootSessionId and parentAgentId are required");let T=this.store.claimSpawnRequest(q,Y);if(!T)return{};return{item:{id:String(T.id),rootSessionId:T.rootSessionId,parentAgentId:T.parentAgentId,task:T.task??"",systemPrompt:T.systemPrompt??"",createdAt:T.createdAt,consumedAt:T.consumedAt??""}}}async startRuntimeSession($){let q=this.runtimeHandlers?.startSession;if(!q)throw Error("runtime start handler is not configured");let Y=$.request?{workspaceRoot:I($.request.workspaceRoot),cwd:I($.request.cwd),provider:I($.request.provider),model:I($.request.model),mode:I($.request.mode),apiKey:I($.request.apiKey),systemPrompt:I($.request.systemPrompt),maxIterations:$.request.hasMaxIterations?$.request.maxIterations:void 0,enableTools:$.request.enableTools===!0,enableSpawn:$.request.enableSpawn===!0,enableTeams:$.request.enableTeams===!0,autoApproveTools:$.request.hasAutoApproveTools?$.request.autoApproveTools===!0:void 0,teamName:I($.request.teamName),missionStepInterval:$.request.missionStepInterval??3,missionTimeIntervalMs:$.request.missionTimeIntervalMs??120000,toolPolicies:Object.fromEntries(Object.entries($.request.toolPolicies??{}).map(([J,Q])=>[J,{enabled:Q?.enabled===!0,autoApprove:Q?.autoApprove===!0}])),initialMessages:($.request.initialMessages??[]).map((J)=>({role:I(J.role),content:Yq(J.content)})),logger:$.request.logger?{enabled:$.request.logger.enabled===!0,level:I($.request.logger.level),destination:I($.request.logger.destination),name:I($.request.logger.name),bindings:f0($.request.logger.bindings)}:void 0}:void 0;if(!Y)throw Error("runtime start request is required");let T=await q(Y),X=I(T.sessionId).trim();if(!X)throw Error("runtime start handler returned empty sessionId");return{sessionId:X,startResult:T.startResult?{sessionId:I(T.startResult.sessionId),manifestPath:I(T.startResult.manifestPath),transcriptPath:I(T.startResult.transcriptPath),hookPath:I(T.startResult.hookPath),messagesPath:I(T.startResult.messagesPath)}:void 0}}async sendRuntimeSession($){let q=this.runtimeHandlers?.sendSession;if(!q)throw Error("runtime send handler is not configured");let Y=I($.sessionId).trim();if(!Y)throw Error("sessionId is required");let T=$.request?{config:{workspaceRoot:I($.request.config?.workspaceRoot),cwd:I($.request.config?.cwd),provider:I($.request.config?.provider),model:I($.request.config?.model),mode:I($.request.config?.mode),apiKey:I($.request.config?.apiKey),systemPrompt:I($.request.config?.systemPrompt),maxIterations:$.request.config?.hasMaxIterations?$.request.config?.maxIterations:void 0,enableTools:$.request.config?.enableTools===!0,enableSpawn:$.request.config?.enableSpawn===!0,enableTeams:$.request.config?.enableTeams===!0,autoApproveTools:$.request.config?.hasAutoApproveTools?$.request.config?.autoApproveTools===!0:void 0,teamName:I($.request.config?.teamName),missionStepInterval:$.request.config?.missionStepInterval??3,missionTimeIntervalMs:$.request.config?.missionTimeIntervalMs??120000,toolPolicies:Object.fromEntries(Object.entries($.request.config?.toolPolicies??{}).map(([J,Q])=>[J,{enabled:Q?.enabled===!0,autoApprove:Q?.autoApprove===!0}])),initialMessages:($.request.config?.initialMessages??[]).map((J)=>({role:I(J.role),content:Yq(J.content)})),logger:$.request.config?.logger?{enabled:$.request.config.logger.enabled===!0,level:I($.request.config.logger.level),destination:I($.request.config.logger.destination),name:I($.request.config.logger.name),bindings:f0($.request.config.logger.bindings)}:void 0},messages:($.request.messages??[]).map((J)=>({role:I(J.role),content:Yq(J.content)})),prompt:I($.request.prompt),attachments:$.request.attachments?{userImages:$.request.attachments.userImages??[],userFiles:($.request.attachments.userFiles??[]).map((J)=>({name:I(J.name),content:I(J.content)}))}:void 0}:void 0;if(!T)throw Error("runtime send request is required");let X=await q(Y,T);return{result:{text:I(X.result.text),usage:{inputTokens:X.result.usage.inputTokens,outputTokens:X.result.usage.outputTokens,cacheReadTokens:X.result.usage.cacheReadTokens??0,hasCacheReadTokens:typeof X.result.usage.cacheReadTokens==="number",cacheWriteTokens:X.result.usage.cacheWriteTokens??0,hasCacheWriteTokens:typeof X.result.usage.cacheWriteTokens==="number",totalCost:X.result.usage.totalCost??0,hasTotalCost:typeof X.result.usage.totalCost==="number"},inputTokens:X.result.inputTokens,outputTokens:X.result.outputTokens,iterations:X.result.iterations,finishReason:I(X.result.finishReason),messages:(X.result.messages??[]).map((J)=>({role:I(J.role),content:qq(J.content)})),toolCalls:(X.result.toolCalls??[]).map((J)=>({name:I(J.name),input:qq(J.input),hasInput:J.input!==void 0,output:qq(J.output),hasOutput:J.output!==void 0,error:I(J.error),durationMs:J.durationMs??0,hasDurationMs:typeof J.durationMs==="number"}))}}}async stopRuntimeSession($){let q=this.runtimeHandlers?.stopSession;if(!q)throw Error("runtime stop handler is not configured");let Y=I($.sessionId).trim();if(!Y)throw Error("sessionId is required");return{applied:(await q(Y)).applied===!0}}async abortRuntimeSession($){let q=this.runtimeHandlers?.abortSession;if(!q)throw Error("runtime abort handler is not configured");let Y=I($.sessionId).trim();if(!Y)throw Error("sessionId is required");return{applied:(await q(Y)).applied===!0}}async runProviderAction($){let q=this.runtimeHandlers?.runProviderAction;if(!q)throw Error("provider action handler is not configured");if(!$.request)throw Error("provider action request is required");let Y;if($.request.listProviders)Y={action:"listProviders"};else if($.request.getProviderModels)Y={action:"getProviderModels",providerId:I($.request.getProviderModels.providerId)};else if($.request.addProvider)Y={action:"addProvider",providerId:I($.request.addProvider.providerId),name:I($.request.addProvider.name),baseUrl:I($.request.addProvider.baseUrl),apiKey:I($.request.addProvider.apiKey)||void 0,headers:$.request.addProvider.headers??void 0,timeoutMs:$.request.addProvider.hasTimeoutMs?$.request.addProvider.timeoutMs:void 0,models:$.request.addProvider.models??void 0,defaultModelId:I($.request.addProvider.defaultModelId)||void 0,modelsSourceUrl:I($.request.addProvider.modelsSourceUrl)||void 0,capabilities:$.request.addProvider.capabilities};else if($.request.saveProviderSettings)Y={action:"saveProviderSettings",providerId:I($.request.saveProviderSettings.providerId),enabled:$.request.saveProviderSettings.hasEnabled?$.request.saveProviderSettings.enabled:void 0,apiKey:$.request.saveProviderSettings.hasApiKey?$.request.saveProviderSettings.apiKey:void 0,baseUrl:$.request.saveProviderSettings.hasBaseUrl?$.request.saveProviderSettings.baseUrl:void 0};else{let X=I($.request.clineAccount?.operation);if(X==="fetchMe")Y={action:"clineAccount",operation:"fetchMe"};else if(X==="fetchBalance")Y={action:"clineAccount",operation:"fetchBalance",userId:I($.request.clineAccount?.userId)||void 0};else if(X==="fetchUsageTransactions")Y={action:"clineAccount",operation:"fetchUsageTransactions",userId:I($.request.clineAccount?.userId)||void 0};else if(X==="fetchPaymentTransactions")Y={action:"clineAccount",operation:"fetchPaymentTransactions",userId:I($.request.clineAccount?.userId)||void 0};else if(X==="fetchUserOrganizations")Y={action:"clineAccount",operation:"fetchUserOrganizations"};else if(X==="fetchOrganizationBalance")Y={action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:I($.request.clineAccount?.organizationId)};else if(X==="fetchOrganizationUsageTransactions")Y={action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:I($.request.clineAccount?.organizationId),memberId:I($.request.clineAccount?.memberId)||void 0};else Y={action:"clineAccount",operation:"switchAccount",organizationId:$.request.clineAccount?.clearOrganizationId?null:I($.request.clineAccount?.organizationId)||void 0}}let T=await q(Y);return{result:qq(T.result)}}async runProviderOAuthLogin($){let q=this.runtimeHandlers?.runProviderOAuthLogin;if(!q)throw Error("provider oauth handler is not configured");let Y=I($.provider).trim();if(!Y)throw Error("provider is required");let T=await q(Y);return{provider:I(T.provider).trim(),apiKey:I(T.accessToken)}}startTask($){let q=I($.sessionId).trim(),Y=I($.taskId).trim();if(!q||!Y)throw Error("sessionId and taskId are required");let T=`${q}:${Y}`;return this.tasks.set(T,{sessionId:q,taskId:Y,title:I($.title).trim()||void 0,status:"running",payload:f0($.payload)??void 0}),this.eventService.publishEvent({eventId:"",sessionId:q,taskId:Y,eventType:"task.started",payload:f0($.payload)??{},sourceClientId:""}),{sessionId:q,taskId:Y,status:"running",updated:!0}}completeTask($){let q=I($.sessionId).trim(),Y=I($.taskId).trim();if(!q||!Y)throw Error("sessionId and taskId are required");let T=`${q}:${Y}`,X=I($.status).trim()||"completed",J=this.tasks.get(T);if(!J)return{sessionId:q,taskId:Y,status:X,updated:!1};return J.status=X,J.result=f0($.result)??void 0,this.eventService.publishEvent({eventId:"",sessionId:q,taskId:Y,eventType:"task.completed",payload:f0($.result)??{},sourceClientId:""}),{sessionId:q,taskId:Y,status:X,updated:!0}}publishEvent($){return this.eventService.publishEvent($)}addSubscriber($){return this.eventService.addSubscriber($)}removeSubscriber($){this.eventService.removeSubscriber($)}requestToolApproval($){return this.approvalService.requestToolApproval($)}respondToolApproval($){return this.approvalService.respondToolApproval($)}listPendingApprovals($){return this.approvalService.listPendingApprovals($)}createSchedule($){return this.scheduleService.createSchedule($)}getSchedule($){return this.scheduleService.getSchedule($)}listSchedules($){return this.scheduleService.listSchedules($)}updateSchedule($){return this.scheduleService.updateSchedule($)}deleteSchedule($){return this.scheduleService.deleteSchedule($)}pauseSchedule($){return this.scheduleService.pauseSchedule($)}resumeSchedule($){return this.scheduleService.resumeSchedule($)}triggerScheduleNow($){return this.scheduleService.triggerScheduleNow($)}listScheduleExecutions($){return this.scheduleService.listScheduleExecutions($)}getScheduleStats($){return this.scheduleService.getScheduleStats($)}getActiveScheduledExecutions($){return this.scheduleService.getActiveScheduledExecutions($)}getUpcomingScheduledRuns($){return this.scheduleService.getUpcomingScheduledRuns($)}broadcastServerEvent($,q){this.eventService.broadcastServerEvent($,q)}}var rq,y$;async function Uw($){if(rq)return rq;if(y$)return y$;return y$=new Promise((q,Y)=>{let T=$.address?.trim()||process.env.CLINE_RPC_ADDRESS?.trim()||fE;try{sL(T)}catch(A){y$=void 0,Y(A instanceof Error?A:Error(String(A)));return}if(!$.sessionBackend){y$=void 0,Y(Error("startRpcServer requires options.sessionBackend"));return}let X=$.scheduler?.enabled!==!1,J,Q=X&&$.runtimeHandlers?.startSession&&$.runtimeHandlers?.sendSession&&$.runtimeHandlers?.abortSession&&$.runtimeHandlers?.stopSession?new I8({runtimeHandlers:{startSession:$.runtimeHandlers.startSession,sendSession:$.runtimeHandlers.sendSession,abortSession:$.runtimeHandlers.abortSession,stopSession:$.runtimeHandlers.stopSession},sessionsDbPath:$.scheduler?.sessionsDbPath,pollIntervalMs:$.scheduler?.pollIntervalMs,globalMaxConcurrency:$.scheduler?.globalMaxConcurrency,eventPublisher:(A,W)=>{J.broadcastServerEvent(A,W)}}):void 0;J=new nE(T,$.sessionBackend,$.runtimeHandlers,Q);let U=new a.Server,Z=!1,K=async()=>{if(Z)return;Z=!0;try{J.broadcastServerEvent("rpc.server.shutting_down",{serverId:J.health().serverId,address:T,reason:"shutdown_requested"})}catch{}try{await $.runtimeHandlers?.dispose?.()}catch{}try{await Q?.stop()}catch{}await new Promise((A)=>{U.tryShutdown(()=>{A()})}),rq=void 0,y$=void 0};if(U.addService(uE(),{Health:(A,W)=>{W(null,J.health())},Shutdown:(A,W)=>{W(null,{accepted:!0}),setImmediate(()=>{K()})},RegisterClient:(A,W)=>{try{W(null,J.registerClient(A.request))}catch(G){W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)}},EnsureSession:(A,W)=>{try{W(null,J.ensureSession(A.request))}catch(G){W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)}},UpsertSession:(A,W)=>{try{W(null,J.upsertSession(A.request))}catch(G){W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)}},GetSession:(A,W)=>{try{W(null,J.getSession(A.request))}catch(G){W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)}},ListSessions:(A,W)=>{try{W(null,J.listSessions(A.request))}catch(G){W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)}},UpdateSession:(A,W)=>{try{W(null,J.updateSession(A.request))}catch(G){W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)}},DeleteSession:(A,W)=>{try{W(null,J.deleteSession(A.request))}catch(G){W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)}},EnqueueSpawnRequest:(A,W)=>{try{W(null,J.enqueueSpawnRequest(A.request))}catch(G){W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)}},ClaimSpawnRequest:(A,W)=>{try{W(null,J.claimSpawnRequest(A.request))}catch(G){W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)}},StartRuntimeSession:(A,W)=>{J.startRuntimeSession(A.request).then((G)=>{W(null,G)}).catch((G)=>{W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)})},SendRuntimeSession:(A,W)=>{J.sendRuntimeSession(A.request).then((G)=>{W(null,G)}).catch((G)=>{W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)})},StopRuntimeSession:(A,W)=>{J.stopRuntimeSession(A.request).then((G)=>{W(null,G)}).catch((G)=>{W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)})},AbortRuntimeSession:(A,W)=>{J.abortRuntimeSession(A.request).then((G)=>{W(null,G)}).catch((G)=>{W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)})},RunProviderAction:(A,W)=>{J.runProviderAction(A.request).then((G)=>{W(null,G)}).catch((G)=>{W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)})},RunProviderOAuthLogin:(A,W)=>{J.runProviderOAuthLogin(A.request).then((G)=>{W(null,G)}).catch((G)=>{W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)})},StartTask:(A,W)=>{try{W(null,J.startTask(A.request))}catch(G){W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)}},CompleteTask:(A,W)=>{try{W(null,J.completeTask(A.request))}catch(G){W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)}},PublishEvent:(A,W)=>{try{W(null,J.publishEvent(A.request))}catch(G){W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)}},StreamEvents:(A)=>{let W=J.addSubscriber(A);A.on("error",()=>{J.removeSubscriber(W)})},RequestToolApproval:(A,W)=>{J.requestToolApproval(A.request).then((G)=>{W(null,G)}).catch((G)=>{W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)})},RespondToolApproval:(A,W)=>{try{W(null,J.respondToolApproval(A.request))}catch(G){W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)}},ListPendingApprovals:(A,W)=>{try{W(null,J.listPendingApprovals(A.request))}catch(G){W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)}},CreateSchedule:(A,W)=>{try{W(null,J.createSchedule(A.request))}catch(G){W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)}},GetSchedule:(A,W)=>{try{W(null,J.getSchedule(A.request))}catch(G){W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)}},ListSchedules:(A,W)=>{try{W(null,J.listSchedules(A.request))}catch(G){W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)}},UpdateSchedule:(A,W)=>{try{W(null,J.updateSchedule(A.request))}catch(G){W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)}},DeleteSchedule:(A,W)=>{try{W(null,J.deleteSchedule(A.request))}catch(G){W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)}},PauseSchedule:(A,W)=>{try{W(null,J.pauseSchedule(A.request))}catch(G){W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)}},ResumeSchedule:(A,W)=>{try{W(null,J.resumeSchedule(A.request))}catch(G){W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)}},TriggerScheduleNow:(A,W)=>{J.triggerScheduleNow(A.request).then((G)=>{W(null,G)}).catch((G)=>{W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)})},ListScheduleExecutions:(A,W)=>{try{W(null,J.listScheduleExecutions(A.request))}catch(G){W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)}},GetScheduleStats:(A,W)=>{try{W(null,J.getScheduleStats(A.request))}catch(G){W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)}},GetActiveScheduledExecutions:(A,W)=>{try{W(null,J.getActiveScheduledExecutions(A.request))}catch(G){W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)}},GetUpcomingScheduledRuns:(A,W)=>{try{W(null,J.getUpcomingScheduledRuns(A.request))}catch(G){W({code:a.status.INVALID_ARGUMENT,message:String(G)},null)}}}),Q)Q.start();U.bindAsync(T,a.ServerCredentials.createInsecure(),(A,W)=>{if(A){y$=void 0,Y(A);return}let G=J.health().serverId??`srv_${Xw()}`,V=Tq(),F={serverId:G,address:T,port:W,startedAt:V,stop:K};rq=F,q(F)})}),y$}async function Zw(){if(rq)await rq.stop()}function C5(){return fE}class y5{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor($){let q=$.apiBaseUrl.trim();if(!q)throw Error("apiBaseUrl is required");this.apiBaseUrl=q,this.getAuthTokenFn=$.getAuthToken,this.getCurrentUserIdFn=$.getCurrentUserId,this.getOrganizationMemberIdFn=$.getOrganizationMemberId,this.getHeadersFn=$.getHeaders,this.requestTimeoutMs=$.requestTimeoutMs??30000,this.fetchImpl=$.fetchImpl??fetch}async fetchMe(){return this.request("/api/v1/users/me")}async fetchBalance($){let q=await this.resolveUserId($);return this.request(`/api/v1/users/${encodeURIComponent(q)}/balance`)}async fetchUsageTransactions($){let q=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(q)}/usages`)).items??[]}async fetchPaymentTransactions($){let q=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(q)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchOrganizationBalance($){let q=$.trim();if(!q)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(q)}/balance`)}async fetchOrganizationUsageTransactions($){let q=$.organizationId.trim();if(!q)throw Error("organizationId is required");let Y=await this.resolveOrganizationMemberId(q,$.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent(q)}/members/${encodeURIComponent(Y)}/usages`)).items??[]}async switchAccount($){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:$?.trim()||null},expectNoContent:!0})}async resolveUserId($){let q=$?.trim();if(q)return q;let T=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(T)return T;let X=await this.fetchMe();if(!X.id?.trim())throw Error("Unable to resolve current user id");return X.id}async resolveOrganizationMemberId($,q){let Y=q?.trim();if(Y)return Y;let X=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn($):void 0)?.trim();if(X)return X;let Q=(await this.fetchUserOrganizations()).find((U)=>U.organizationId===$)?.memberId;if(!Q?.trim())throw Error(`Unable to resolve memberId for organization ${$}`);return Q}async request($,q){let Y=(await this.getAuthTokenFn())?.trim();if(!Y)throw Error("No Cline account auth token found");let T=this.getHeadersFn?await this.getHeadersFn():{},X=new AbortController,J=setTimeout(()=>X.abort(),this.requestTimeoutMs);try{let Q=await this.fetchImpl(new URL($,this.apiBaseUrl),{method:q?.method??"GET",headers:{Authorization:`Bearer ${Y}`,"Content-Type":"application/json",...T??{}},body:q?.body!==void 0?JSON.stringify(q.body):void 0,signal:X.signal});if(Q.status===204||q?.expectNoContent){if(!Q.ok)throw Error(`Cline account request failed with status ${Q.status}`);return}let U=await Q.text(),Z;if(U.trim())Z=JSON.parse(U);if(!Q.ok){let K=typeof Z==="object"&&Z!==null&&"error"in Z?String(Z.error):`Cline account request failed with status ${Q.status}`;throw Error(K)}if(typeof Z==="object"&&Z!==null){let K=Z;if(typeof K.success==="boolean"){if(!K.success)throw Error(K.error||"Cline account request failed");if(K.data!==void 0)return K.data}}if(Z===void 0||Z===null)throw Error("Cline account response payload was empty");return Z}finally{clearTimeout(J)}}}function iE($){return $.action==="clineAccount"}async function rE($,q){switch($.operation){case"fetchMe":return q.fetchMe();case"fetchBalance":return q.fetchBalance($.userId);case"fetchUsageTransactions":return q.fetchUsageTransactions($.userId);case"fetchPaymentTransactions":return q.fetchPaymentTransactions($.userId);case"fetchUserOrganizations":return q.fetchUserOrganizations();case"fetchOrganizationBalance":return q.fetchOrganizationBalance($.organizationId);case"fetchOrganizationUsageTransactions":return q.fetchOrganizationUsageTransactions({organizationId:$.organizationId,memberId:$.memberId});case"switchAccount":return await q.switchAccount($.organizationId),{updated:!0};default:throw Error(`Unsupported Cline account operation: ${String($)}`)}}class j5{executor;constructor($){this.executor=$}async fetchMe(){return this.request({action:"clineAccount",operation:"fetchMe"})}async fetchBalance($){return this.request({action:"clineAccount",operation:"fetchBalance",...$?.trim()?{userId:$.trim()}:{}})}async fetchUsageTransactions($){return this.request({action:"clineAccount",operation:"fetchUsageTransactions",...$?.trim()?{userId:$.trim()}:{}})}async fetchPaymentTransactions($){return this.request({action:"clineAccount",operation:"fetchPaymentTransactions",...$?.trim()?{userId:$.trim()}:{}})}async fetchUserOrganizations(){return this.request({action:"clineAccount",operation:"fetchUserOrganizations"})}async fetchOrganizationBalance($){let q=$.trim();if(!q)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:q})}async fetchOrganizationUsageTransactions($){let q=$.organizationId.trim();if(!q)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:q,...$.memberId?.trim()?{memberId:$.memberId.trim()}:{}})}async switchAccount($){await this.request({action:"clineAccount",operation:"switchAccount",organizationId:$?.trim()||null})}async request($){return(await this.executor.runProviderAction($)).result}}import ow from"yaml";import{z as V1}from"zod";var n1={READ_FILES:"read_files",SEARCH_CODEBASE:"search_codebase",RUN_COMMANDS:"run_commands",FETCH_WEB_CONTENT:"fetch_web_content",APPLY_PATCH:"apply_patch",EDITOR:"editor",SKILLS:"skills",ASK:"ask_question"},Xq=[n1.READ_FILES,n1.SEARCH_CODEBASE,n1.RUN_COMMANDS,n1.FETCH_WEB_CONTENT,n1.APPLY_PATCH,n1.EDITOR,n1.SKILLS,n1.ASK];import{createTool as j$}from"@clinebot/agents";import{z as o}from"zod";var Kw=o.string().describe("The absolute file path of a text file to read content from"),M8=o.object({file_paths:o.array(Kw).describe("Array of absolute file paths to get full content from. Prefer this tool over running terminal command to get file content for better performance and reliability.")}),aE=o.union([M8,o.array(o.string()),o.string()]),B8=o.object({queries:o.array(o.string()).describe("Array of regex search queries to execute")}),v5=o.string(),R8=o.object({commands:o.array(v5).describe("Array of shell commands to execute.")}),oE=o.union([R8,o.array(v5),v5]),sE=o.object({url:o.string().describe("The URL to fetch"),prompt:o.string().min(2).describe("Analysis prompt for the fetched content")}),P8=o.object({requests:o.array(sE).describe("Array of the URLs for the web fetch requests")}),O8=o.object({command:o.enum(["create","str_replace","insert"]).describe("Editor command to execute: create, str_replace, insert"),path:o.string().min(1).describe("Absolute file path"),file_text:o.string().nullish().describe("Full file content required for 'create' command"),old_str:o.string().nullish().describe("Exact text to replace (must match exactly once) for 'str_replace' command"),new_str:o.string().nullish().describe("Replacement text for 'str_replace' or 'insert' commands"),insert_line:o.number().int().nullish().describe("Optional one-based line index for 'insert' command")}).refine(($)=>$.command!=="create"||$.file_text!=null,{path:["file_text"],message:"file_text is required for command=create"}).refine(($)=>$.command!=="str_replace"||$.old_str!=null,{path:["old_str"],message:"old_str is required for command=str_replace"}).refine(($)=>$.command!=="insert"||$.insert_line!=null,{path:["insert_line"],message:"insert_line is required for command=insert"}).refine(($)=>$.command!=="insert"||$.new_str!=null,{path:["new_str"],message:"new_str is required for command=insert"}),L8=o.object({input:o.string().min(1).describe("The apply_patch text payload, including patch instructions")}),tE=o.union([L8,o.string()]),w8=o.object({skill:o.string().min(1).describe('The skill name. E.g., "commit", "review-pr", "pdf", or "ms-office-suite:pdf"'),args:o.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),S8=o.object({question:o.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:o.array(o.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")});function oq($){if($ instanceof Error)return $.message;return String($)}function v$($,q,Y){return Promise.race([$,new Promise((T,X)=>{setTimeout(()=>X(Error(Y)),q)})])}var Aw=`This is a custom utility that makes it more convenient to add, remove, move, or edit code in a single file. \`apply_patch\` effectively allows you to execute a diff/patch against a file, but the format of the diff specification is unique to this task, so pay careful attention to these instructions. To use the \`apply_patch\` command, you should pass a message of the following structure as "input":
165
-
166
- %%bash
167
- apply_patch <<"EOF"
168
- *** Begin Patch
169
- [YOUR_PATCH]
170
- *** End Patch
171
- EOF
172
-
173
- Where [YOUR_PATCH] is the actual content of your patch, specified in the following V4A diff format.
174
-
175
- *** [ACTION] File: [path/to/file] -> ACTION can be one of Add, Update, or Delete.
176
-
177
- In a Add File section, every line of the new file (including blank/empty lines) MUST start with a \`+\` prefix. Do not include any unprefixed lines inside an Add section
178
- In a Update/Delete section, repeat the following for each snippet of code that needs to be changed:
179
- [context_before] -> See below for further instructions on context.
180
- - [old_code] -> Precede the old code with a minus sign.
181
- + [new_code] -> Precede the new, replacement code with a plus sign.
182
- [context_after] -> See below for further instructions on context.
183
-
184
- For instructions on [context_before] and [context_after]:
185
- - By default, show 3 lines of code immediately above and 3 lines immediately below each change. If a change is within 3 lines of a previous change, do NOT duplicate the first change’s [context_after] lines in the second change’s [context_before] lines.
186
- - If 3 lines of context is insufficient to uniquely identify the snippet of code within the file, use the @@ operator to indicate the class or function to which the snippet belongs. For instance, we might have:
187
- @@ class BaseClass
188
- [3 lines of pre-context]
189
- - [old_code]
190
- + [new_code]
191
- [3 lines of post-context]
192
-
193
- - If a code block is repeated so many times in a class or function such that even a single @@ statement and 3 lines of context cannot uniquely identify the snippet of code, you can use multiple \`@@\` statements to jump to the right context. For instance:
194
-
195
- @@ class BaseClass
196
- @@ def method():
197
- [3 lines of pre-context]
198
- - [old_code]
199
- + [new_code]
200
- [3 lines of post-context]
201
-
202
- Note, then, that we do not use line numbers in this diff format, as the context is enough to uniquely identify code. An example of a message that you might pass as "input" to this function, in order to apply a patch, is shown below.
203
-
204
- %%bash
205
- apply_patch <<"EOF"
206
- *** Begin Patch
207
- *** Update File: pygorithm/searching/binary_search.py
208
- @@ class BaseClass
209
- @@ def search():
210
- - pass
211
- + raise NotImplementedError()
212
-
213
- @@ class Subclass
214
- @@ def search():
215
- - pass
216
- + raise NotImplementedError()
217
-
218
- *** End Patch
219
- EOF`;function eE($,q={}){let Y=q.fileReadTimeoutMs??1e4;return j$({name:"read_files",description:"Read the FULL content of text file at the provided absolute paths. Returns file contents or error messages for each path. ",inputSchema:N1(M8),timeoutMs:Y*2,retryable:!0,maxRetries:1,execute:async(T,X)=>{let J=I1(aE,T),Q=Array.isArray(J)?J:typeof J==="object"?J.file_paths:[J];return Promise.all(Q.map(async(U)=>{try{let Z=await v$($(U,X),Y,`File read timed out after ${Y}ms`);return{query:U,result:Z,success:!0}}catch(Z){let K=oq(Z);return{query:U,result:"",error:`Error reading file: ${K}`,success:!1}}}))}})}function $V($,q={}){let Y=q.searchTimeoutMs??30000,T=q.cwd??process.cwd();return j$({name:"search_codebase",description:"Perform regex pattern searches across the codebase. Supports multiple parallel searches. Use for finding code patterns, function definitions, class names, imports, etc.",inputSchema:N1(B8),timeoutMs:Y*2,retryable:!0,maxRetries:1,execute:async(X,J)=>{let Q=I1(B8,X);return Promise.all(Q.queries.map(async(U)=>{try{let Z=await v$($(U,T,J),Y,`Search timed out after ${Y}ms`),K=Z.length>0&&!Z.includes("No results found");return{query:U,result:Z,success:K}}catch(Z){let K=oq(Z);return{query:U,result:"",error:`Search failed: ${K}`,success:!1}}}))}})}function qV($,q={}){let Y=q.bashTimeoutMs??30000,T=q.cwd??process.cwd();return j$({name:"run_commands",description:"Run shell commands at the root of the project. Use for listing files, checking git status, running builds, executing tests, etc. Commands should be properly shell-escaped.",inputSchema:N1(R8),timeoutMs:Y*2,retryable:!1,maxRetries:0,execute:async(X,J)=>{let Q=I1(oE,X),U=Array.isArray(Q)?Q:typeof Q==="object"?Q.commands:[Q];return Promise.all(U.map(async(Z)=>{try{let K=await v$($(Z,T,J),Y,`Command timed out after ${Y}ms`);return{query:Z,result:K,success:!0}}catch(K){let A=oq(K);return{query:Z,result:"",error:`Command failed: ${A}`,success:!1}}}))}})}function YV($,q={}){let Y=q.webFetchTimeoutMs??30000;return j$({name:"fetch_web_content",description:"Fetch content from URLs and analyze them using the provided prompts. Use for retrieving documentation, API references, or any web content. Each request includes a URL and a prompt describing what information to extract.",inputSchema:N1(P8),timeoutMs:Y*2,retryable:!0,maxRetries:2,execute:async(T,X)=>{let J=I1(P8,T);return Promise.all(J.requests.map(async(Q)=>{try{let U=await v$($(Q.url,Q.prompt,X),Y,`Web fetch timed out after ${Y}ms`);return{query:Q.url,result:U,success:!0}}catch(U){let Z=oq(U);return{query:Q.url,result:"",error:`Error fetching web content: ${Z}`,success:!1}}}))}})}function TV($,q={}){let Y=q.applyPatchTimeoutMs??30000,T=q.cwd??process.cwd();return j$({name:"apply_patch",description:Aw,inputSchema:N1(L8),timeoutMs:Y,retryable:!1,maxRetries:0,execute:async(X,J)=>{let Q=I1(tE,X),U=typeof Q==="string"?Q:Q.input;try{return{query:"apply_patch",result:await v$($({input:U},T,J),Y,`apply_patch timed out after ${Y}ms`),success:!0}}catch(Z){return{query:"apply_patch",result:"",error:`apply_patch failed: ${oq(Z)}`,success:!1}}}})}function XV($,q={}){let Y=q.editorTimeoutMs??30000,T=q.cwd??process.cwd();return j$({name:"editor",description:"Edit file using absolute path with create, string replacement, and line insert operations. Supported commands: create, str_replace, insert.",inputSchema:N1(O8),timeoutMs:Y,retryable:!1,maxRetries:0,execute:async(X,J)=>{let Q=I1(O8,X);try{let U=await v$($(Q,T,J),Y,`Editor operation timed out after ${Y}ms`);return{query:`${Q.command}:${Q.path}`,result:U,success:!0}}catch(U){let Z=oq(U);return{query:`${Q.command}:${Q.path}`,result:"",error:`Editor operation failed: ${Z}`,success:!1}}}})}function JV($,q={}){let Y=q.skillsTimeoutMs??15000;return j$({name:"skills",description:'Execute a skill within the main conversation. When users ask you to perform tasks, check if any available skills match. When users reference a slash command (for example "/commit" or "/review-pr"), invoke this tool. Input: `skill` (required) and optional `args`. Example: `skill: "pdf"`, `skill: "commit", args: "-m \\"Fix bug\\""`, `skill: "review-pr", args: "123"`, `skill: "ms-office-suite:pdf"`. Available skills are listed in system-reminder messages in the conversation. When a skill matches the user\'s request, invoking this tool is a blocking requirement before any other response. Never mention a skill without invoking this tool.',inputSchema:N1(w8),timeoutMs:Y,retryable:!1,maxRetries:0,execute:async(T,X)=>{let J=I1(w8,T);return v$($(J.skill,J.args||void 0,X),Y,`Skills operation timed out after ${Y}ms`)}})}function QV($,q={}){let Y=q.askQuestionTimeoutMs??15000;return j$({name:"ask_question",description:"Ask user a question for clarifying or gathering information needed to complete the task. For example, ask the user clarifying questions about a key implementation decision. You should only ask one question. Provide an array of 2-5 options for the user to choose from. Never include an option to toggle to Act mode.",inputSchema:N1(S8),timeoutMs:Y,retryable:!1,maxRetries:0,execute:async(T,X)=>{let J=I1(S8,T);return v$($(J.question,J.options,X),Y,`ask_question timed out after ${Y}ms`)}})}function sq($){let{executors:q,enableReadFiles:Y=!0,enableSearch:T=!0,enableBash:X=!0,enableWebFetch:J=!0,enableApplyPatch:Q=!1,enableEditor:U=!0,enableSkills:Z=!0,enableAskQuestion:K=!0,...A}=$,W=[];if(Y&&q.readFile)W.push(eE(q.readFile,A));if(T&&q.search)W.push($V(q.search,A));if(X&&q.bash)W.push(qV(q.bash,A));if(J&&q.webFetch)W.push(YV(q.webFetch,A));if(U&&q.editor)W.push(XV(q.editor,A));else if(Q&&q.applyPatch)W.push(TV(q.applyPatch,A));if(Z&&q.skills)W.push(JV(q.skills,A));if(K&&q.askQuestion)W.push(QV(q.askQuestion,A));return W}import*as G1 from"node:fs/promises";import*as E1 from"node:path";var r={BEGIN:"*** Begin Patch",END:"*** End Patch",ADD:"*** Add File: ",UPDATE:"*** Update File: ",DELETE:"*** Delete File: ",MOVE:"*** Move to: ",SECTION:"@@",END_FILE:"*** End of File"},ZV=["%%bash","apply_patch","EOF","```"];class y0 extends Error{constructor($){super($);this.name="DiffError"}}function W1($){let q={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return $.normalize("NFC").replace(/./gu,(Y)=>q[Y]??Y).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class x5{lines;currentFiles;patch={actions:{},warnings:[]};index=0;fuzz=0;currentPath;constructor($,q){this.lines=$;this.currentFiles=q}parse(){this.skipBeginSentinel();while(this.hasMoreLines()&&!this.isEndMarker())this.parseNextAction();if(this.patch.warnings?.length===0)delete this.patch.warnings;return{patch:this.patch,fuzz:this.fuzz}}addWarning($){if(!this.patch.warnings)this.patch.warnings=[];this.patch.warnings.push($)}skipBeginSentinel(){if(this.lines[this.index]?.startsWith(r.BEGIN))this.index++}hasMoreLines(){return this.index<this.lines.length}isEndMarker(){return this.lines[this.index]?.startsWith(r.END)??!1}parseNextAction(){let $=this.lines[this.index];if($?.startsWith(r.UPDATE)){this.parseUpdate($.substring(r.UPDATE.length).trim());return}if($?.startsWith(r.DELETE)){this.parseDelete($.substring(r.DELETE.length).trim());return}if($?.startsWith(r.ADD)){this.parseAdd($.substring(r.ADD.length).trim());return}throw new y0(`Unknown line while parsing: ${$}`)}checkDuplicate($,q){if($ in this.patch.actions)throw new y0(`Duplicate ${q} for file: ${$}`)}parseUpdate($){this.checkDuplicate($,"update"),this.currentPath=$,this.index++;let q=this.lines[this.index]?.startsWith(r.MOVE)?(this.lines[this.index++]??"").substring(r.MOVE.length).trim():void 0;if(!($ in this.currentFiles))throw new y0(`Update File Error: Missing File: ${$}`);let Y=this.currentFiles[$]??"",T=this.parseUpdateFile(Y,$);T.movePath=q,this.patch.actions[$]=T,this.currentPath=void 0}parseUpdateFile($,q){let Y={type:"update",chunks:[]},T=$.split(`
220
- `),X=0,J=[r.END,r.UPDATE,r.DELETE,r.ADD,r.END_FILE];while(!J.some((Q)=>this.lines[this.index]?.startsWith(Q.trim()))){let Q=this.lines[this.index],U=Q?.startsWith("@@ ")?Q.substring(3):void 0;if(U!==void 0||(Q==="@@"?Q:void 0)!==void 0)this.index++;else if(X!==0)throw new y0(`Invalid Line:
221
- ${this.lines[this.index]}`);if(U?.trim()){let D=W1(U.trim());for(let z=X;z<T.length;z++){let S=T[z];if(S&&(W1(S)===D||W1(S.trim())===D)){if(X=z+1,W1(S.trim())===D&&W1(S)!==D)this.fuzz++;break}}}let[K,A,W,G]=Ew(this.lines,this.index),[V,F,N]=Gw(T,K,X,G);if(V===-1){let D=K.join(`
222
- `);this.addWarning({path:this.currentPath||q,chunkIndex:Y.chunks.length,message:`Could not find matching context (similarity: ${N.toFixed(2)}). Chunk skipped.`,context:D.length>200?`${D.substring(0,200)}...`:D}),this.index=W}else{this.fuzz+=F;for(let D of A)D.origIndex+=V,Y.chunks.push(D);X=V+K.length,this.index=W}}return Y}parseDelete($){if(this.checkDuplicate($,"delete"),!($ in this.currentFiles))throw new y0(`Delete File Error: Missing File: ${$}`);this.patch.actions[$]={type:"delete",chunks:[]},this.index++}parseAdd($){if(this.checkDuplicate($,"add"),$ in this.currentFiles)throw new y0(`Add File Error: File already exists: ${$}`);this.index++;let q=[],Y=[r.END,r.UPDATE,r.DELETE,r.ADD];while(this.hasMoreLines()&&!Y.some((T)=>this.lines[this.index]?.startsWith(T.trim()))){let T=this.lines[this.index++];if(T===void 0)break;if(!T.startsWith("+"))throw new y0(`Invalid Add File line (missing '+'): ${T}`);q.push(T.substring(1))}this.patch.actions[$]={type:"add",newFile:q.join(`
223
- `),chunks:[]}}}function UV($,q){let Y=$.length>q.length?$:q,T=$.length>q.length?q:$;if(Y.length===0)return 1;let X=Ww(T,Y);return(Y.length-X)/Y.length}function Ww($,q){let Y=q.length+1,T=$.length+1,X=Array(Y*T).fill(0),J=(U,Z)=>X[U*T+Z]??0,Q=(U,Z,K)=>{X[U*T+Z]=K};for(let U=0;U<=q.length;U++)Q(U,0,U);for(let U=0;U<=$.length;U++)Q(0,U,U);for(let U=1;U<=q.length;U++)for(let Z=1;Z<=$.length;Z++)if(q[U-1]===$[Z-1])Q(U,Z,J(U-1,Z-1));else Q(U,Z,1+Math.min(J(U-1,Z-1),J(U,Z-1),J(U-1,Z)));return J(q.length,$.length)}function Gw($,q,Y,T){if(q.length===0)return[Y,0,1];let X=0,J=(Q)=>{let U=W1(q.join(`
224
- `));for(let K=Q;K<$.length;K++){let A=W1($.slice(K,K+q.length).join(`
225
- `));if(A===U)return[K,0,1];let W=UV(A,U);if(W>X)X=W}for(let K=Q;K<$.length;K++){let A=W1($.slice(K,K+q.length).map((G)=>G.trimEnd()).join(`
226
- `)),W=W1(q.map((G)=>G.trimEnd()).join(`
227
- `));if(A===W)return[K,1,1]}for(let K=Q;K<$.length;K++){let A=W1($.slice(K,K+q.length).map((G)=>G.trim()).join(`
228
- `)),W=W1(q.map((G)=>G.trim()).join(`
229
- `));if(A===W)return[K,100,1]}let Z=0.66;for(let K=Q;K<$.length;K++){let A=W1($.slice(K,K+q.length).join(`
230
- `)),W=UV(A,U);if(W>=Z)return[K,1000,W];if(W>X)X=W}return[-1,0,X]};if(T){let[Q,U,Z]=J($.length-q.length);if(Q!==-1)return[Q,U,Z];return[Q,U,Z]=J(Y),[Q,U+1e4,Z]}return J(Y)}function Ew($,q){let Y=q,T=[],X=[],J=[],Q=[],U="keep",Z=["@@",r.END,r.UPDATE,r.DELETE,r.ADD,r.END_FILE];while(Y<$.length){let K=$[Y];if(!K||Z.some((G)=>K.startsWith(G.trim())))break;if(K==="***")break;if(K.startsWith("***"))throw new y0(`Invalid line: ${K}`);Y++;let A=U,W=K;if(W[0]==="+")U="add";else if(W[0]==="-")U="delete";else if(W[0]===" ")U="keep";else U="keep",W=` ${W}`;if(W=W.slice(1),U==="keep"&&A!==U){if(J.length||X.length)Q.push({origIndex:T.length-X.length,delLines:X,insLines:J});X=[],J=[]}if(U==="delete")X.push(W),T.push(W);else if(U==="add")J.push(W);else T.push(W)}if(J.length||X.length)Q.push({origIndex:T.length-X.length,delLines:X,insLines:J});if(Y<$.length&&$[Y]===r.END_FILE)return Y++,[T,Q,Y,!0];return[T,Q,Y,!1]}function k5($,q,Y){let T=E1.isAbsolute(q),X=T?E1.normalize(q):E1.resolve($,q);if(!Y||T)return X;let J=E1.relative($,X);if(J.startsWith("..")||E1.isAbsolute(J))throw new y0(`Path must stay within cwd: ${q}`);return X}function KV($){let q=[],Y=!1,T=!1,X=!1;for(let J=0;J<$.length;J++){let Q=$[J];if(!Y&&ZV.some((Z)=>Q.startsWith(Z)))continue;if(Q.startsWith(r.BEGIN)){Y=!0,T=!0,q.push(Q);continue}if(Q===r.END){Y=!1,q.push(Q);continue}let U=Q.startsWith(r.ADD)||Q.startsWith(r.UPDATE)||Q.startsWith(r.DELETE)||Q.startsWith(r.MOVE)||Q.startsWith(r.SECTION)||Q.startsWith("+")||Q.startsWith("-")||Q.startsWith(" ")||Q==="***";if(U&&J!==$.length-1)X=!0;if(Y||!T&&U||Q===""&&X)q.push(Q)}while(q.length>0&&q[q.length-1]==="")q.pop();return!T&&!X?$:q}function Vw($){let q=$.split(`
231
- `).map((X)=>X.replace(/\r$/,""));q=KV(q);let Y=q.length>0&&q[0].startsWith(r.BEGIN),T=q.length>0&&q[q.length-1]===r.END;if(!Y&&!T)return[r.BEGIN,...q,r.END];if(Y&&T)return q;throw new y0("Invalid patch text - incomplete sentinels. Try breaking it into smaller patches.")}function Dw($,q){let Y=KV($.split(`
232
- `)),T=[];for(let X of Y)for(let J of q){if(!X.startsWith(J))continue;let Q=X.substring(J.length).trim();if(!$.trim().endsWith(Q))T.push(Q);break}return T}function Fw($,q,Y){if(q.length===0)return $;let T=$.split(`
233
- `),X=[],J=0;for(let Q of q){if(Q.origIndex>T.length)throw new y0(`${Y}: chunk.origIndex ${Q.origIndex} > lines.length ${T.length}`);if(J>Q.origIndex)throw new y0(`${Y}: currentIndex ${J} > chunk.origIndex ${Q.origIndex}`);X.push(...T.slice(J,Q.origIndex)),X.push(...Q.insLines),J=Q.origIndex+Q.delLines.length}return X.push(...T.slice(J)),X.join(`
234
- `)}async function Iw($,q,Y,T){let X=Dw($,[r.UPDATE,r.DELETE]),J={};for(let Q of X){let U=k5(q,Q,T),Z;try{Z=await G1.readFile(U,Y)}catch{throw new y0(`File not found: ${Q}`)}J[Q]=Z.replace(/\r\n/g,`
235
- `)}return J}function Nw($,q){let Y={};for(let[T,X]of Object.entries($.actions))switch(X.type){case"delete":Y[T]={type:"delete",oldContent:q[T]};break;case"add":if(X.newFile===void 0)throw new y0("ADD action without file content");Y[T]={type:"add",newContent:X.newFile};break;case"update":Y[T]={type:"update",oldContent:q[T],newContent:Fw(q[T]??"",X.chunks,T),movePath:X.movePath};break}return Y}async function Hw($,q,Y,T){let X=[];for(let[J,Q]of Object.entries($)){let U=k5(q,J,T);switch(Q.type){case"delete":await G1.rm(U,{force:!0}),X.push(`${J}: [deleted]`);break;case"add":if(Q.newContent===void 0)throw new y0(`Cannot create ${J} with no content`);await G1.mkdir(E1.dirname(U),{recursive:!0}),await G1.writeFile(U,Q.newContent,{encoding:Y}),X.push(J);break;case"update":{if(Q.newContent===void 0)throw new y0(`UPDATE change for ${J} has no new content`);if(Q.movePath){let Z=k5(q,Q.movePath,T);await G1.mkdir(E1.dirname(Z),{recursive:!0}),await G1.writeFile(Z,Q.newContent,{encoding:Y}),await G1.rm(U,{force:!0}),X.push(`${J} -> ${Q.movePath}`)}else await G1.writeFile(U,Q.newContent,{encoding:Y}),X.push(J);break}}}return X}function C8($={}){let{encoding:q="utf-8",restrictToCwd:Y=!0}=$;return async(T,X,J)=>{let Q=Vw(T.input),U=await Iw(T.input,X,q,Y),Z=new x5(Q,U),{patch:K,fuzz:A}=Z.parse(),W=Nw(K,U),G=await Hw(W,X,q,Y),V=["Successfully applied patch to the following files:"];for(let F of G)V.push(F);if(A>0)V.push(`Note: Patch applied with fuzz factor ${A}`);if(K.warnings&&K.warnings.length>0)for(let F of K.warnings)V.push(`Warning (${F.path}): ${F.message}`);return V.join(`
236
- `)}}import{spawn as AV}from"node:child_process";function y8($={}){let{shell:q=process.platform==="win32"?"cmd.exe":"/bin/bash",timeoutMs:Y=30000,maxOutputBytes:T=1e6,env:X={},combineOutput:J=!0}=$;return async(Q,U,Z)=>{return new Promise((K,A)=>{let W=process.platform==="win32"?["/c",Q]:["-c",Q],G=process.platform==="win32",V=AV(q,W,{cwd:U,env:{...process.env,...X},stdio:["pipe","pipe","pipe"],detached:!G}),F=V.pid,N="",D="",z=0,S=!1,v=!1,H=(C)=>{if(v)return;v=!0,A(C)},_=(C)=>{if(v)return;v=!0,K(C)},y=()=>{if(!F)return;if(G){AV("taskkill",["/pid",String(F),"/T","/F"],{stdio:"ignore",windowsHide:!0}).unref();return}try{process.kill(-F,"SIGKILL")}catch{V.kill("SIGKILL")}},k=setTimeout(()=>{S=!0,y(),H(Error(`Command timed out after ${Y}ms`))},Y),m=()=>{S=!0,y(),H(Error("Command was aborted"))};if(Z.abortSignal)Z.abortSignal.addEventListener("abort",m);V.stdout?.on("data",(C)=>{if(z+=C.length,z<=T)N+=C.toString()}),V.stderr?.on("data",(C)=>{if(z+=C.length,z<=T)D+=C.toString()}),V.on("close",(C)=>{if(clearTimeout(k),Z.abortSignal)Z.abortSignal.removeEventListener("abort",m);if(S)return;let j=J?N+(D?`
237
- [stderr]
238
- ${D}`:""):N;if(z>T)j+=`
239
-
240
- [Output truncated: ${z} bytes total, showing first ${T} bytes]`;if(C!==0){let M=D||`Command exited with code ${C}`;H(Error(M))}else _(j)}),V.on("error",(C)=>{if(clearTimeout(k),Z.abortSignal)Z.abortSignal.removeEventListener("abort",m);H(Error(`Failed to execute command: ${C.message}`))})})}}import*as U$ from"node:fs/promises";import*as y1 from"node:path";function zw($,q,Y){let T=y1.isAbsolute(q),X=T?y1.normalize(q):y1.resolve($,q);if(!Y)return X;if(T)return X;let J=y1.relative($,X);if(J.startsWith("..")||y1.isAbsolute(J))throw Error(`Path must stay within cwd: ${q}`);return X}function Mw($,q){if(q.length===0)return 0;return $.split(q).length-1}function Bw($,q,Y){let T=$.split(`
241
- `),X=q.split(`
242
- `),J=Math.max(T.length,X.length),Q=["```diff"],U=0;for(let Z=0;Z<J;Z++){if(U>=Y){Q.push("... diff truncated ...");break}let K=T[Z],A=X[Z];if(K===A)continue;let W=Z+1;if(K!==void 0)Q.push(`-${W}: ${K}`),U++;if(A!==void 0&&U<Y)Q.push(`+${W}: ${A}`),U++}return Q.push("```"),Q.join(`
243
- `)}async function Rw($,q,Y){return await U$.mkdir(y1.dirname($),{recursive:!0}),await U$.writeFile($,q,{encoding:Y}),`File created successfully at: ${$}`}async function Pw($,q,Y,T,X){let J=await U$.readFile($,T),Q=Mw(J,q);if(Q===0)throw Error(`No replacement performed: text not found in ${$}.`);if(Q>1)throw Error(`No replacement performed: multiple occurrences of text found in ${$}.`);let U=J.replace(q,Y??"");await U$.writeFile($,U,{encoding:T});let Z=Bw(J,U,X);return`Edited ${$}
244
- ${Z}`}async function Ow($,q,Y,T){let J=(await U$.readFile($,T)).split(`
245
- `),Q=q-1;if(Q<0||Q>J.length)throw Error(`Invalid line number: ${q}. Valid range: 1-${J.length}`);return J.splice(Q,0,...Y.split(`
246
- `)),await U$.writeFile($,J.join(`
247
- `),{encoding:T}),`Inserted content at line ${q} in ${$}.`}function j8($={}){let{encoding:q="utf-8",restrictToCwd:Y=!0,maxDiffLines:T=200}=$;return async(X,J,Q)=>{let U=zw(J,X.path,Y);switch(X.command){case"create":if(X.file_text==null)throw Error("Parameter `file_text` is required for command: create");return Rw(U,X.file_text,q);case"str_replace":if(X.old_str==null)throw Error("Parameter `old_str` is required for command: str_replace");return Pw(U,X.old_str,X.new_str,q,T);case"insert":if(X.insert_line==null)throw Error("Parameter `insert_line` is required for insert command.");if(X.new_str==null)throw Error("Parameter `new_str` is required for insert command.");return Ow(U,X.insert_line,X.new_str,q);default:throw Error(`Unrecognized command ${X.command}. Allowed commands are: create, str_replace, insert`)}}}import*as v8 from"node:fs/promises";import*as tq from"node:path";var Lw={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0};function x8($={}){let{maxFileSizeBytes:q,encoding:Y,includeLineNumbers:T}={...Lw,...$};return async(X,J)=>{let Q=tq.isAbsolute(X)?tq.normalize(X):tq.resolve(process.cwd(),X),U=await v8.stat(Q);if(!U.isFile())throw Error(`Path is not a file: ${Q}`);if(U.size>q)throw Error(`File too large: ${U.size} bytes (max: ${q} bytes). Consider reading specific sections or using a different approach.`);let Z=await v8.readFile(Q,Y);if(T){let K=Z.split(`
248
- `),A=String(K.length).length;return K.map((W,G)=>`${String(G+1).padStart(A," ")} | ${W}`).join(`
249
- `)}return Z}}import*as FV from"node:fs/promises";import*as h8 from"node:path";import{spawn as ww}from"node:child_process";import{readdir as Sw}from"node:fs/promises";import g5 from"node:path";import{isMainThread as GV,parentPort as WV,Worker as Cw}from"node:worker_threads";var yw=15000,jw=1000,vw=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]),h5=new Map;function xw($,q){return g5.relative($,q).split(g5.sep).join("/")}async function kw($){let Y=(await new Promise((T,X)=>{let J=ww("rg",["--files","--hidden","-g","!.git"],{cwd:$,stdio:["ignore","pipe","pipe"]}),Q="",U="";J.stdout.on("data",(Z)=>{Q+=Z.toString()}),J.stderr.on("data",(Z)=>{U+=Z.toString()}),J.on("error",X),J.on("close",(Z)=>{if(Z===0){T(Q);return}X(Error(U||`rg exited with code ${Z}`))})})).split(/\r?\n/).map((T)=>T.trim()).filter((T)=>T.length>0).map((T)=>T.replace(/\\/g,"/"));return new Set(Y)}async function EV($,q,Y){let T=await Sw(q,{withFileTypes:!0});for(let X of T){let J=g5.join(q,X.name);if(X.isDirectory()){if(vw.has(X.name))continue;await EV($,J,Y);continue}if(X.isFile())Y.add(xw($,J))}}async function hw($){let q=new Set;return await EV($,$,q),q}async function m5($){try{return await kw($)}catch{return hw($)}}function _w(){if(GV||!WV)return;let $=WV;$.on("message",(q)=>{if(q.type!=="index")return;m5(q.cwd).then((Y)=>{let T={type:"indexResult",requestId:q.requestId,files:Array.from(Y)};$.postMessage(T)}).catch((Y)=>{let T={type:"indexResult",requestId:q.requestId,error:Y instanceof Error?Y.message:"Failed to build file index"};$.postMessage(T)})})}class VV{worker=new Cw(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",($)=>{if($.type!=="indexResult")return;let q=this.pending.get($.requestId);if(!q)return;if(this.pending.delete($.requestId),$.error){q.reject(Error($.error));return}q.resolve($.files??[])}),this.worker.on("error",($)=>{this.flushPending($)}),this.worker.on("exit",($)=>{if($!==0)this.flushPending(Error(`File index worker exited with code ${$}`))})}requestIndex($){let q=++this.nextRequestId,Y=new Promise((X,J)=>{let Q=setTimeout(()=>{this.pending.delete(q),J(Error("Timed out waiting for file index worker response"))},jw);Q.unref(),this.pending.set(q,{resolve:(U)=>{clearTimeout(Q),X(U)},reject:(U)=>{clearTimeout(Q),J(U)}})}),T={type:"index",requestId:q,cwd:$};return this.worker.postMessage(T),Y}flushPending($){for(let[q,Y]of this.pending.entries())Y.reject($),this.pending.delete(q)}}_w();var _5;function gw(){if(!GV)return null;if(_5===void 0)_5=new VV;return _5}async function mw($){let q=gw();if(!q)return m5($);try{let Y=await q.requestIndex($);return new Set(Y)}catch{return m5($)}}async function Jq($,q={}){let Y=q.ttlMs??yw,T=Date.now(),X=h5.get($);if(X&&Y>0&&T-X.lastBuiltAt<=Y&&X.files.size>0)return X.files;if(X?.pending)return X.pending;let J=mw($).then((Q)=>{return h5.set($,{files:Q,lastBuiltAt:Date.now(),pending:null}),Q});return h5.set($,{files:X?.files??new Set,lastBuiltAt:X?.lastBuiltAt??0,pending:J}),J}async function DV($,q={}){await Jq($,{...q,ttlMs:0})}import{stat as fw}from"node:fs/promises";import Qq from"node:path";var bw=/[),.:;!?`'"]+$/,uw=/^[(`'"]+/;function dw($){let q=$.matchAll(/(^|[\s])@([^\s]+)/g),Y=[];for(let T of q){let X=(T[2]??"").trim();if(X.length===0)continue;let J=X.replace(uw,"").replace(bw,"");if(J.length===0||J.includes("@"))continue;Y.push(J)}return Array.from(new Set(Y))}function cw($,q){let Y=$.replace(/\\/g,"/"),T=Qq.isAbsolute(Y)?Qq.resolve(Y):Qq.resolve(q,Y),X=Qq.relative(q,T);if(X.startsWith("..")||Qq.isAbsolute(X))return;return X.split(Qq.sep).join("/")}async function k8($,q,Y={}){let T=dw($);if(T.length===0)return{prompt:$,matchedFiles:[],ignoredMentions:[]};let{maxFiles:X,maxFileBytes:J,maxTotalBytes:Q}=Y,U=await Jq(q,{ttlMs:Y.ttlMs}),Z=[],K=[],A=[],W=0;for(let G of T){if(X&&A.length>=X){K.push(G);continue}let V=cw(G,q);if(!V||!U.has(V)){K.push(G);continue}if(!J||!Q){Z.push(V);continue}let F=Qq.join(q,V);try{if(!(await fw(F)).isFile()){K.push(G);continue}let D=W+J;if(D>Q){K.push(G);continue}W+=D,Z.push(V)}catch{K.push(G)}}return{prompt:$,matchedFiles:Z,ignoredMentions:K}}var pw=["ts","tsx","js","jsx","mjs","cjs","json","md","mdx","txt","yaml","yml","toml","py","rb","go","rs","java","kt","swift","c","cpp","h","hpp","css","scss","less","html","vue","svelte","sql","sh","bash","zsh","fish","ps1","env","gitignore","dockerignore","editorconfig"],lw=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"];function nw($,q,Y,T){let X=$.split("/"),J=X[X.length-1]??"";if(X.length-1>T)return!1;for(let Z=0;Z<X.length-1;Z++)if(q.has(X[Z]??""))return!1;let U=h8.posix.extname(J).slice(1).toLowerCase();return Y.has(U)||!U&&!J.startsWith(".")}function _8($={}){let{includeExtensions:q=pw,excludeDirs:Y=lw,maxResults:T=100,contextLines:X=2,maxDepth:J=20}=$,Q=new Set(Y),U=new Set(q.map((Z)=>Z.toLowerCase()));return async(Z,K,A)=>{let W;try{W=new RegExp(Z,"gim")}catch(D){throw Error(`Invalid regex pattern: ${Z}. ${D instanceof Error?D.message:""}`)}let G=[],V=0,F=await Jq(K);for(let D of F){if(!nw(D,Q,U,J))continue;if(G.length>=T)break;V++;let z=h8.join(K,D);try{let v=(await FV.readFile(z,"utf-8")).split(`
250
- `);for(let H=0;H<v.length;H++){let _=v[H];W.lastIndex=0;let y;while((y=W.exec(_))!==null){if(G.length>=T)break;let k=Math.max(0,H-X),m=Math.min(v.length-1,H+X),C=[];for(let j=k;j<=m;j++){let M=j===H?">":" ";C.push(`${M} ${j+1}: ${v[j]}`)}if(G.push({file:D,line:H+1,column:y.index+1,match:y[0],context:C}),y.index===W.lastIndex)W.lastIndex++}}}catch{}}if(G.length===0)return`No results found for pattern: ${Z}
251
- Searched ${V} files.`;let N=[`Found ${G.length} result${G.length===1?"":"s"} for pattern: ${Z}`,`Searched ${V} files.`,""];for(let D of G)N.push(`${D.file}:${D.line}:${D.column}`),N.push(...D.context),N.push("");if(G.length>=T)N.push(`(Showing first ${T} results. Refine your search for more specific results.)`);return N.join(`
252
- `)}}function iw($){return $.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<!--[\s\S]*?-->/g,"").replace(/<(p|div|br|hr|h[1-6]|li|tr)[^>]*>/gi,`
253
- `).replace(/<[^>]+>/g," ").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#(\d+);/g,(q,Y)=>String.fromCharCode(parseInt(Y,10))).replace(/\s+/g," ").replace(/\n\s+/g,`
254
- `).replace(/\n{3,}/g,`
255
-
256
- `).trim()}function g8($={}){let{timeoutMs:q=30000,maxResponseBytes:Y=5000000,userAgent:T="Mozilla/5.0 (compatible; AgentBot/1.0)",headers:X={},followRedirects:J=!0}=$;return async(Q,U,Z)=>{let K;try{K=new URL(Q)}catch{throw Error(`Invalid URL: ${Q}`)}if(!["http:","https:"].includes(K.protocol))throw Error(`Invalid protocol: ${K.protocol}. Only http and https are supported.`);let A=new AbortController,W=setTimeout(()=>A.abort(),q),G;if(Z.abortSignal)G=()=>A.abort(),Z.abortSignal.addEventListener("abort",G);try{let V=await fetch(Q,{method:"GET",headers:{"User-Agent":T,Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,text/plain;q=0.8,*/*;q=0.7","Accept-Language":"en-US,en;q=0.9",...X},redirect:J?"follow":"manual",signal:A.signal});if(clearTimeout(W),!J&&V.status>=300&&V.status<400)return`Redirect to: ${V.headers.get("location")}`;if(!V.ok)throw Error(`HTTP ${V.status}: ${V.statusText}`);let F=V.headers.get("content-type")||"",N=V.body?.getReader();if(!N)throw Error("Failed to read response body");let D=[],z=0;while(!0){let{done:k,value:m}=await N.read();if(k)break;if(z+=m.length,z>Y)throw N.cancel(),Error(`Response too large: exceeded ${Y} bytes`);D.push(m)}let S=new Uint8Array(z),v=0;for(let k of D)S.set(k,v),v+=k.length;let H=new TextDecoder("utf-8").decode(S),_;if(F.includes("text/html")||F.includes("application/xhtml"))_=iw(H);else if(F.includes("application/json"))try{let k=JSON.parse(H);_=JSON.stringify(k,null,2)}catch{_=H}else _=H;let y=[`URL: ${Q}`,`Content-Type: ${F}`,`Size: ${z} bytes`,"","--- Content ---",_.slice(0,50000)];if(_.length>50000)y.push(`
257
- [Content truncated: showing first 50000 of ${_.length} characters]`);return y.push("","--- Analysis Request ---",`Prompt: ${U}`),y.join(`
258
- `)}catch(V){if(clearTimeout(W),V instanceof Error){if(V.name==="AbortError")throw Error(`Request timed out after ${q}ms`);throw V}throw Error(`Fetch failed: ${String(V)}`)}finally{if(Z.abortSignal&&G)Z.abortSignal.removeEventListener("abort",G)}}}function m8($={}){return{readFile:x8($.fileRead),search:_8($.search),bash:y8($.bash),webFetch:g8($.webFetch),applyPatch:C8($.applyPatch),editor:j8($.editor)}}var rw={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"},f5=[{name:"openai-native-use-apply-patch",mode:"act",providerIdIncludes:["openai-native"],enableTools:["apply_patch"],disableTools:["editor"]},{name:"codex-and-gpt-use-apply-patch",mode:"act",modelIdIncludes:["codex","gpt"],enableTools:["apply_patch"],disableTools:["editor"]}];function IV($,q){if(!q||q.length===0)return!0;let Y=$.toLowerCase();return q.some((T)=>Y.includes(T.toLowerCase()))}function aw($,q,Y,T){if($.mode&&$.mode!=="any"&&$.mode!==T)return!1;return IV(q,$.providerIdIncludes)&&IV(Y,$.modelIdIncludes)}function b5($,q,Y,T){if(!T||T.length===0)return{};let X=new Map;for(let Q of T){if(!aw(Q,$,q,Y))continue;for(let U of Q.disableTools??[])X.set(U,!1);for(let U of Q.enableTools??[])X.set(U,!0)}let J={};for(let[Q,U]of X.entries())J[rw[Q]]=U;return J}var Z$={browser:{enableReadFiles:!1,enableSearch:!1,enableBash:!1,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!1,enableSkills:!0,enableAskQuestion:!0},search:{enableReadFiles:!0,enableSearch:!0,enableBash:!1,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!1,enableSkills:!1,enableAskQuestion:!1},development:{enableReadFiles:!0,enableSearch:!0,enableBash:!0,enableWebFetch:!0,enableApplyPatch:!1,enableEditor:!0,enableSkills:!0,enableAskQuestion:!0},readonly:{enableReadFiles:!0,enableSearch:!0,enableBash:!0,enableWebFetch:!0,enableApplyPatch:!1,enableEditor:!1,enableSkills:!0,enableAskQuestion:!0},minimal:{enableReadFiles:!1,enableSearch:!1,enableBash:!1,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!1,enableSkills:!1,enableAskQuestion:!0},yolo:{enableReadFiles:!0,enableSearch:!0,enableBash:!0,enableWebFetch:!0,enableApplyPatch:!1,enableEditor:!0,enableSkills:!0,enableAskQuestion:!0}};function NV($){if($!=="yolo")return{};let q={enabled:!0,autoApprove:!0},Y={"*":q};for(let T of Xq)Y[T]=q;return Y}function HV($,q){let Y=Z$[$];return sq({...Y,...q})}function N6($={}){let{executorOptions:q={},executors:Y,...T}=$,X={...m8(q),...Y??{}};return sq({...T,executors:X})}var sw=V1.object({name:V1.string().trim().min(1),description:V1.string().trim().min(1),modelId:V1.string().trim().min(1).optional(),tools:V1.union([V1.string(),V1.array(V1.string())]).optional(),skills:V1.union([V1.string(),V1.array(V1.string())]).optional()}),tw=new Set(Xq);function zV($){return/\.(yaml|yml)$/i.test($)}function MV($){return $.trim().toLowerCase()}function ew($){let q=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,Y=$.match(q);if(!Y)return{data:{},body:$,hadFrontmatter:!1};let[,T,X]=Y;try{let J=ow.parse(T);return{data:J&&typeof J==="object"&&!Array.isArray(J)?J:{},body:X,hadFrontmatter:!0}}catch(J){let Q=J instanceof Error?J.message:String(J);return{data:{},body:$,hadFrontmatter:!0,parseError:Q}}}function $S($){let q=$.trim();if(!q)throw Error("Tool name cannot be empty.");if(!tw.has(q))throw Error(`Unknown tool '${q}'. Expected one of: ${Xq.join(", ")}.`);return q}function qS($){if(!$)return[];let q=Array.isArray($)?$:$.split(",");return Array.from(new Set(q.map($S)))}function YS($){let q=$.trim();if(!q)throw Error("Skill name cannot be empty.");return q}function TS($){if($===void 0)return;let q=Array.isArray($)?$:$.split(",");return Array.from(new Set(q.map(YS)))}function eq($){let{data:q,body:Y,hadFrontmatter:T,parseError:X}=ew($);if(X)throw Error(`Failed to parse YAML frontmatter: ${X}`);if(!T)throw Error("Missing YAML frontmatter block in agent config file.");let J=sw.parse(q),Q=Y.trim();if(!Q)throw Error("Missing system prompt body in agent config file.");return{name:J.name,description:J.description,modelId:J.modelId,tools:qS(J.tools),skills:TS(J.skills),systemPrompt:Q}}function f8($,q){if($.length===0)return[];let Y=new Map(q.map((T)=>[T.name,T]));return $.map((T)=>{let X=Y.get(T);if(!X)throw Error(`Configured tool '${T}' is unavailable. Available tools: ${q.map((J)=>J.name).join(", ")}.`);return X})}function b8($,q){let Y={systemPrompt:$.systemPrompt};if($.modelId)Y.modelId=$.modelId;if($.tools.length>0){if(!q?.availableTools)throw Error("Configured tools cannot be converted into AgentConfig.tools without availableTools.");Y.tools=f8($.tools,q.availableTools)}return Y}function u5($,q){let Y=eq($);return b8(Y,q)}import{createHash as XS}from"node:crypto";import{watch as JS}from"node:fs";import{readdir as QS,readFile as US}from"node:fs/promises";import{join as ZS}from"node:path";function KS($){return XS("sha1").update($).digest("hex")}function AS($){return Boolean($&&typeof $==="object"&&"code"in $)}function BV($){return AS($)&&$.code==="ENOENT"}class Uq{definitions;debounceMs;emitParseErrors;listeners=new Set;recordsByType=new Map;watchersByDirectory=new Map;baseTypesByDirectory=new Map;watchedTypesByDirectory=new Map;discoveredDirectoriesByType=new Map;definitionsByType=new Map;pendingTypes=new Set;flushTimer;refreshQueue=Promise.resolve();started=!1;constructor($,q){if($.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=$,this.debounceMs=q?.debounceMs??75,this.emitParseErrors=q?.emitParseErrors??!1;for(let Y of $){if(this.definitionsByType.has(Y.type))throw Error(`Duplicate unified config definition type '${Y.type}'.`);this.definitionsByType.set(Y.type,Y),this.recordsByType.set(Y.type,new Map),this.discoveredDirectoriesByType.set(Y.type,new Set);for(let T of Y.directories){let X=this.baseTypesByDirectory.get(T);if(X)X.add(Y.type);else this.baseTypesByDirectory.set(T,new Set([Y.type]))}}}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}async start(){if(this.started)return;this.started=!0,await this.refreshAll(),this.startDirectoryWatchers()}stop(){if(this.started=!1,this.flushTimer)clearTimeout(this.flushTimer),this.flushTimer=void 0;this.pendingTypes.clear();for(let $ of this.watchersByDirectory.values())$.close();this.watchersByDirectory.clear(),this.watchedTypesByDirectory=new Map}async refreshAll(){await this.enqueueRefresh(async()=>{for(let $ of this.definitions)await this.refreshTypeInternal($)})}async refreshType($){let q=this.definitionsByType.get($);if(!q)throw Error(`Unknown unified config type '${$}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal(q)})}getSnapshot($){let q=this.recordsByType.get($);return new Map([...q?.entries()??[]].map(([Y,T])=>[Y,{...T}]))}getAllSnapshots(){let $=new Map;for(let[q,Y]of this.recordsByType.entries())$.set(q,new Map([...Y.entries()].map(([T,X])=>[T,{...X}])));return $}emit($){for(let q of this.listeners)q($)}enqueueRefresh($){return this.refreshQueue=this.refreshQueue.then($,$),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let $=this.buildDesiredTypesByDirectory();for(let[q,Y]of this.watchersByDirectory.entries()){if($.has(q))continue;Y.close(),this.watchersByDirectory.delete(q)}this.watchedTypesByDirectory=$;for(let q of $.keys()){if(this.watchersByDirectory.has(q))continue;try{let Y=JS(q,()=>{let T=this.watchedTypesByDirectory.get(q);if(!T)return;for(let X of T)this.pendingTypes.add(X);this.scheduleFlush()});this.watchersByDirectory.set(q,Y),Y.on("error",(T)=>{let X=this.watchedTypesByDirectory.get(q);if(!X)return;for(let J of X)this.emit({kind:"error",type:J,error:T,filePath:q})})}catch(Y){if(!BV(Y)){let T=$.get(q);if(!T)continue;for(let X of T)this.emit({kind:"error",type:X,error:Y,filePath:q})}}}}scheduleFlush(){if(this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=setTimeout(()=>{this.flushTimer=void 0;let $=[...this.pendingTypes];this.pendingTypes.clear(),this.enqueueRefresh(async()=>{for(let q of $){let Y=this.definitionsByType.get(q);if(!Y)continue;await this.refreshTypeInternal(Y)}})},this.debounceMs)}async refreshTypeInternal($){let{records:q,discoveredDirectories:Y}=await this.loadDefinition($),T=this.recordsByType.get($.type)??new Map;for(let[X,J]of T.entries()){if(q.has(X))continue;this.emit({kind:"remove",type:$.type,id:X,filePath:J.filePath})}for(let[X,J]of q.entries()){let Q=T.get(X);if(Q&&Q.filePath===J.filePath&&Q.fingerprint===J.fingerprint)continue;this.emit({kind:"upsert",record:{type:J.type,id:X,item:J.item,filePath:J.filePath}})}if(this.recordsByType.set($.type,q),this.discoveredDirectoriesByType.set($.type,Y),this.started)this.syncDirectoryWatchers()}async loadDefinition($){let q=new Map,Y=new Set;for(let T of $.directories){Y.add(T);let X=$.discoverFiles?await $.discoverFiles(T):await this.readDirectoryFileCandidates(T);for(let J of X){let{fileName:Q,filePath:U}=J;if(Y.add(J.directoryPath),$.includeFile&&!$.includeFile(Q,U))continue;try{let Z=await US(U,"utf8"),K={type:$.type,directoryPath:J.directoryPath,fileName:Q,filePath:U,content:Z},A=$.parseFile(K),W=$.resolveId(A,K).trim();if(!W)continue;q.set(W,{type:$.type,id:W,item:A,filePath:U,fingerprint:KS(Z)})}catch(Z){if(this.emitParseErrors)this.emit({kind:"error",type:$.type,error:Z,filePath:U})}}}return{records:q,discoveredDirectories:Y}}buildDesiredTypesByDirectory(){let $=new Map;for(let[q,Y]of this.baseTypesByDirectory.entries())$.set(q,new Set(Y));for(let[q,Y]of this.discoveredDirectoriesByType.entries())for(let T of Y){let X=$.get(T);if(X)X.add(q);else $.set(T,new Set([q]))}return $}async readDirectoryFileCandidates($){try{return(await QS($,{withFileTypes:!0})).filter((Y)=>Y.isFile()).map((Y)=>({directoryPath:$,fileName:Y.name,filePath:ZS($,Y.name)})).sort((Y,T)=>Y.fileName.localeCompare(T.fileName))}catch(q){if(BV(q))return[];throw q}}}function RV(){return I5()}function WS($){if(Array.isArray($))return[...$];if(typeof $==="string")return[$];return RV()}function d5($){return{type:"agent",directories:WS($),includeFile:(q)=>zV(q),parseFile:(q)=>eq(q.content),resolveId:(q)=>MV(q.name)}}function PV($){return new Uq([d5($?.directoryPathOrPaths)],{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}import{existsSync as GS,readdirSync as ES}from"node:fs";import{basename as VS,extname as DS,join as FS}from"node:path";function c5($){return N5($)}var u8;((K)=>{K.TaskStart="TaskStart";K.TaskResume="TaskResume";K.TaskCancel="TaskCancel";K.TaskComplete="TaskComplete";K.PreToolUse="PreToolUse";K.PostToolUse="PostToolUse";K.UserPromptSubmit="UserPromptSubmit";K.PreCompact="PreCompact";K.SessionShutdown="SessionShutdown"})(u8||={});var p5={["TaskStart"]:"agent_start",["TaskResume"]:"agent_resume",["TaskCancel"]:"agent_abort",["TaskComplete"]:"agent_end",["PreToolUse"]:"tool_call",["PostToolUse"]:"tool_result",["UserPromptSubmit"]:"prompt_submit",["PreCompact"]:void 0,["SessionShutdown"]:"session_shutdown"},IS=new Map(Object.values(u8).map(($)=>[$.toLowerCase(),$]));function l5($){let q=VS($,DS($)).trim().toLowerCase();return IS.get(q)}function d8($){let q=[],Y=new Set,T=c5($).filter((X)=>GS(X));for(let X of T)try{for(let J of ES(X,{withFileTypes:!0})){if(!J.isFile())continue;let Q=l5(J.name);if(!Q)continue;let U=FS(X,J.name);if(Y.has(U))continue;Y.add(U),q.push({fileName:Q,hookEventName:p5[Q],path:U})}}catch{}return q.sort((X,J)=>X.path.localeCompare(J.path))}import{existsSync as r5,readdirSync as PS,statSync as OS}from"node:fs";import{join as LS,resolve as CV}from"node:path";import{resolve as NS}from"node:path";import{pathToFileURL as HS}from"node:url";function LV($){return typeof $==="object"&&$!==null}function OV($){return Array.isArray($)&&$.every((q)=>typeof q==="string")}function zS($,q){if(!LV($.manifest))throw Error(`Invalid plugin module at ${q}: missing required "manifest"`);if(!OV($.manifest.capabilities))throw Error(`Invalid plugin module at ${q}: manifest.capabilities must be a string array`);if($.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${q}: manifest.capabilities cannot be empty`);if(Object.hasOwn($.manifest,"hookStages")&&!OV($.manifest.hookStages))throw Error(`Invalid plugin module at ${q}: manifest.hookStages must be a string array when provided`)}function MS($,q){if(!LV($))throw Error(`Invalid plugin module at ${q}: expected object export`);if(typeof $.name!=="string"||$.name.length===0)throw Error(`Invalid plugin module at ${q}: expected non-empty "name"`);if(!Object.hasOwn($,"manifest"))throw Error(`Invalid plugin module at ${q}: missing required "manifest"`);zS($,q)}async function n5($,q={}){let Y=NS(q.cwd??process.cwd(),$),T=await import(HS(Y).href),X=q.exportName??"plugin",J=T.default??T[X];return MS(J,Y),J}async function c8($,q={}){let Y=[];for(let T of $)Y.push(await n5(T,q));return Y}import{spawn as BS}from"node:child_process";function wV($){if($ instanceof Error)return $;return Error(String($))}class p8{options;process=null;requestCounter=0;pending=new Map;constructor($){this.options=$}start(){if(this.process&&this.process.exitCode===null)return;let $=BS(process.execPath,["-e",this.options.bootstrapScript],{stdio:["ignore","ignore","ignore","ipc"]});this.process=$,$.on("message",(q)=>{this.onMessage(q)}),$.on("error",(q)=>{this.failPending(Error(`${this.options.name??"sandbox"} process error: ${wV(q).message}`))}),$.on("exit",(q,Y)=>{this.process=null,this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(q)}, signal=${String(Y)})`))})}async call($,q,Y={}){this.start();let T=this.process;if(!T||T.exitCode!==null)throw Error(`${this.options.name??"sandbox"} process is not available`);let X=`req_${++this.requestCounter}`,J={type:"call",id:X,method:$,args:q};return await new Promise((Q,U)=>{let Z={resolve:(K)=>Q(K),reject:U};if((Y.timeoutMs??0)>0)Z.timeout=setTimeout(()=>{this.pending.delete(X),this.shutdown().catch(()=>{}),U(Error(`${this.options.name??"sandbox"} call timed out after ${Y.timeoutMs}ms: ${$}`))},Y.timeoutMs);this.pending.set(X,Z),T.send(J,(K)=>{if(!K)return;let A=this.pending.get(X);if(!A)return;if(this.pending.delete(X),A.timeout)clearTimeout(A.timeout);A.reject(Error(`${this.options.name??"sandbox"} failed to send call "${$}": ${wV(K).message}`))})})}async shutdown(){let $=this.process;if(this.process=null,!$||$.exitCode!==null){this.failPending(Error(`${this.options.name??"sandbox"} shutdown`));return}await new Promise((q)=>{let Y=setTimeout(()=>{try{$.kill("SIGKILL")}catch{}q()},300);$.once("exit",()=>{clearTimeout(Y),q()});try{$.kill("SIGTERM")}catch{clearTimeout(Y),q()}}),this.failPending(Error(`${this.options.name??"sandbox"} shutdown`))}onMessage($){if(!$||$.type!=="response"||!$.id)return;let q=this.pending.get($.id);if(!q)return;if(this.pending.delete($.id),q.timeout)clearTimeout(q.timeout);if($.ok){q.resolve($.result);return}q.reject(Error($.error?.message||`${this.options.name??"sandbox"} call failed`))}failPending($){for(let[q,Y]of this.pending.entries()){if(this.pending.delete(q),Y.timeout)clearTimeout(Y.timeout);Y.reject($)}}}var RS=`
259
- const { pathToFileURL } = require("node:url");
260
- let pluginCounter = 0;
261
- const pluginState = new Map();
262
-
263
- function toErrorPayload(error) {
264
- const message = error instanceof Error ? error.message : String(error);
265
- const stack = error instanceof Error ? error.stack : undefined;
266
- return { message, stack };
267
- }
268
-
269
- function sendResponse(id, ok, result, error) {
270
- if (!process.send) return;
271
- process.send({ type: "response", id, ok, result, error });
272
- }
273
-
274
- function sanitizeObject(value) {
275
- if (!value || typeof value !== "object") return {};
276
- return value;
277
- }
278
-
279
- async function initialize(args) {
280
- const descriptors = [];
281
- const exportName = (args && args.exportName) || "plugin";
282
- for (const pluginPath of args.pluginPaths || []) {
283
- const moduleExports = await import(pathToFileURL(pluginPath).href);
284
- const plugin = moduleExports.default || moduleExports[exportName];
285
- if (!plugin || typeof plugin !== "object") {
286
- throw new Error(\`Invalid plugin module: \${pluginPath}\`);
287
- }
288
- if (typeof plugin.name !== "string" || !plugin.name) {
289
- throw new Error(\`Invalid plugin name: \${pluginPath}\`);
290
- }
291
- if (!plugin.manifest || typeof plugin.manifest !== "object") {
292
- throw new Error(\`Invalid plugin manifest: \${pluginPath}\`);
293
- }
294
-
295
- const pluginId = \`plugin_\${++pluginCounter}\`;
296
- const contributions = {
297
- tools: [],
298
- commands: [],
299
- shortcuts: [],
300
- flags: [],
301
- messageRenderers: [],
302
- providers: [],
303
- };
304
- const handlers = {
305
- tools: new Map(),
306
- commands: new Map(),
307
- messageRenderers: new Map(),
308
- };
309
-
310
- const makeId = (prefix) => \`\${pluginId}_\${prefix}_\${Math.random().toString(36).slice(2, 10)}\`;
311
- const api = {
312
- registerTool: (tool) => {
313
- const id = makeId("tool");
314
- handlers.tools.set(id, tool.execute);
315
- contributions.tools.push({
316
- id,
317
- name: tool.name,
318
- description: tool.description,
319
- inputSchema: tool.inputSchema,
320
- timeoutMs: tool.timeoutMs,
321
- retryable: tool.retryable,
322
- });
323
- },
324
- registerCommand: (command) => {
325
- const id = makeId("command");
326
- if (typeof command.handler === "function") {
327
- handlers.commands.set(id, command.handler);
328
- }
329
- contributions.commands.push({
330
- id,
331
- name: command.name,
332
- description: command.description,
333
- });
334
- },
335
- registerShortcut: (shortcut) => {
336
- contributions.shortcuts.push({
337
- id: makeId("shortcut"),
338
- name: shortcut.name,
339
- value: shortcut.value,
340
- description: shortcut.description,
341
- });
342
- },
343
- registerFlag: (flag) => {
344
- contributions.flags.push({
345
- id: makeId("flag"),
346
- name: flag.name,
347
- description: flag.description,
348
- defaultValue: flag.defaultValue,
349
- });
350
- },
351
- registerMessageRenderer: (renderer) => {
352
- const id = makeId("renderer");
353
- handlers.messageRenderers.set(id, renderer.render);
354
- contributions.messageRenderers.push({ id, name: renderer.name });
355
- },
356
- registerProvider: (provider) => {
357
- contributions.providers.push({
358
- id: makeId("provider"),
359
- name: provider.name,
360
- description: provider.description,
361
- metadata: sanitizeObject(provider.metadata),
362
- });
363
- },
364
- };
365
-
366
- if (typeof plugin.setup === "function") {
367
- await plugin.setup(api);
368
- }
369
-
370
- pluginState.set(pluginId, { plugin, handlers });
371
- descriptors.push({
372
- pluginId,
373
- name: plugin.name,
374
- manifest: plugin.manifest,
375
- contributions,
376
- });
377
- }
378
- return descriptors;
379
- }
380
-
381
- function getPlugin(pluginId) {
382
- const state = pluginState.get(pluginId);
383
- if (!state) {
384
- throw new Error(\`Unknown sandbox plugin id: \${pluginId}\`);
385
- }
386
- return state;
387
- }
388
-
389
- async function invokeHook(args) {
390
- const state = getPlugin(args.pluginId);
391
- const handler = state.plugin[args.hookName];
392
- if (typeof handler !== "function") {
393
- return undefined;
394
- }
395
- return await handler(args.payload);
396
- }
397
-
398
- async function executeTool(args) {
399
- const state = getPlugin(args.pluginId);
400
- const handler = state.handlers.tools.get(args.contributionId);
401
- if (typeof handler !== "function") {
402
- throw new Error("Unknown sandbox tool contribution");
403
- }
404
- return await handler(args.input, args.context);
405
- }
406
-
407
- async function executeCommand(args) {
408
- const state = getPlugin(args.pluginId);
409
- const handler = state.handlers.commands.get(args.contributionId);
410
- if (typeof handler !== "function") {
411
- return "";
412
- }
413
- return await handler(args.input);
414
- }
415
-
416
- async function renderMessage(args) {
417
- const state = getPlugin(args.pluginId);
418
- const handler = state.handlers.messageRenderers.get(args.contributionId);
419
- if (typeof handler !== "function") {
420
- return "";
421
- }
422
- return await handler(args.message);
423
- }
424
-
425
- const methods = { initialize, invokeHook, executeTool, executeCommand, renderMessage };
426
-
427
- process.on("message", async (message) => {
428
- if (!message || message.type !== "call") {
429
- return;
430
- }
431
- const method = methods[message.method];
432
- if (!method) {
433
- sendResponse(message.id, false, undefined, { message: \`Unknown method: \${String(message.method)}\` });
434
- return;
435
- }
436
- try {
437
- const result = await method(message.args || {});
438
- sendResponse(message.id, true, result);
439
- } catch (error) {
440
- sendResponse(message.id, false, undefined, toErrorPayload(error));
441
- }
442
- });
443
- `;function K$($,q){return $.manifest.hookStages?.includes(q)===!0}function i5($,q){return typeof $==="number"&&$>0?$:q}async function SV($){let q=new p8({name:"plugin-sandbox",bootstrapScript:RS}),Y=i5($.importTimeoutMs,4000),T=i5($.hookTimeoutMs,3000),X=i5($.contributionTimeoutMs,5000),J;try{J=await q.call("initialize",{pluginPaths:$.pluginPaths,exportName:$.exportName},{timeoutMs:Y})}catch(U){throw await q.shutdown().catch(()=>{}),U}return{extensions:J.map((U)=>{let Z={name:U.name,manifest:U.manifest,setup:(K)=>{for(let A of U.contributions.tools){let W={name:A.name,description:A.description??"",inputSchema:A.inputSchema??{type:"object",properties:{}},timeoutMs:A.timeoutMs,retryable:A.retryable,execute:async(G,V)=>await q.call("executeTool",{pluginId:U.pluginId,contributionId:A.id,input:G,context:V},{timeoutMs:X})};K.registerTool(W)}for(let A of U.contributions.commands)K.registerCommand({name:A.name,description:A.description,handler:async(W)=>await q.call("executeCommand",{pluginId:U.pluginId,contributionId:A.id,input:W},{timeoutMs:X})});for(let A of U.contributions.shortcuts)K.registerShortcut({name:A.name,value:A.value??"",description:A.description});for(let A of U.contributions.flags)K.registerFlag({name:A.name,description:A.description,defaultValue:A.defaultValue});for(let A of U.contributions.messageRenderers)K.registerMessageRenderer({name:A.name,render:()=>`[sandbox renderer ${A.name} requires async bridge]`});for(let A of U.contributions.providers)K.registerProvider({name:A.name,description:A.description,metadata:A.metadata})}};if(K$(Z,"input"))Z.onInput=async(K)=>await q.call("invokeHook",{pluginId:U.pluginId,hookName:"onInput",payload:K},{timeoutMs:T});if(K$(Z,"session_start"))Z.onSessionStart=async(K)=>await q.call("invokeHook",{pluginId:U.pluginId,hookName:"onSessionStart",payload:K},{timeoutMs:T});if(K$(Z,"before_agent_start"))Z.onBeforeAgentStart=async(K)=>await q.call("invokeHook",{pluginId:U.pluginId,hookName:"onBeforeAgentStart",payload:K},{timeoutMs:T});if(K$(Z,"tool_call_before"))Z.onToolCall=async(K)=>await q.call("invokeHook",{pluginId:U.pluginId,hookName:"onToolCall",payload:K},{timeoutMs:T});if(K$(Z,"tool_call_after"))Z.onToolResult=async(K)=>await q.call("invokeHook",{pluginId:U.pluginId,hookName:"onToolResult",payload:K},{timeoutMs:T});if(K$(Z,"turn_end"))Z.onAgentEnd=async(K)=>await q.call("invokeHook",{pluginId:U.pluginId,hookName:"onAgentEnd",payload:K},{timeoutMs:T});if(K$(Z,"session_shutdown"))Z.onSessionShutdown=async(K)=>await q.call("invokeHook",{pluginId:U.pluginId,hookName:"onSessionShutdown",payload:K},{timeoutMs:T});if(K$(Z,"runtime_event"))Z.onRuntimeEvent=async(K)=>{await q.call("invokeHook",{pluginId:U.pluginId,hookName:"onRuntimeEvent",payload:K},{timeoutMs:T})};if(K$(Z,"error"))Z.onError=async(K)=>{await q.call("invokeHook",{pluginId:U.pluginId,hookName:"onError",payload:K},{timeoutMs:T})};return Z}),shutdown:async()=>{await q.shutdown()}}}var yV=new Set([".js",".mjs",".cjs",".ts",".mts",".cts"]);function a5($){return M5($)}function jV($){let q=$.lastIndexOf(".");if(q===-1)return!1;return yV.has($.slice(q))}function l8($){let q=CV($);if(!r5(q))return[];let Y=[],T=[q];while(T.length>0){let X=T.pop();if(!X)continue;for(let J of PS(X,{withFileTypes:!0})){let Q=LS(X,J.name);if(J.isDirectory()){T.push(Q);continue}if(J.isFile()&&jV(Q))Y.push(Q)}}return Y.sort((X,J)=>X.localeCompare(J))}function wS($,q){let Y=[];for(let T of $){let X=T.trim();if(!X)continue;let J=CV(q,X);if(!r5(J))throw Error(`Plugin path does not exist: ${J}`);if(OS(J).isDirectory()){Y.push(...l8(J));continue}if(!jV(J))throw Error(`Plugin file must use a supported extension (${[...yV].join(", ")}): ${J}`);Y.push(J)}return Y}function o5($={}){let q=$.cwd??process.cwd(),Y=a5($.workspacePath).flatMap((Q)=>l8(Q)).filter((Q)=>r5(Q)),T=wS($.pluginPaths??[],q),X=[],J=new Set;for(let Q of[...T,...Y]){if(J.has(Q))continue;J.add(Q),X.push(Q)}return X}async function n8($={}){let q=o5($);if(q.length===0)return{extensions:[]};if($.mode==="in_process")return{extensions:await c8(q,{cwd:$.cwd,exportName:$.exportName})};let Y=await SV({pluginPaths:q,exportName:$.exportName,importTimeoutMs:$.importTimeoutMs,hookTimeoutMs:$.hookTimeoutMs,contributionTimeoutMs:$.contributionTimeoutMs});return{extensions:Y.extensions??[],shutdown:Y.shutdown}}import{readdir as vV,stat as SS}from"node:fs/promises";import{basename as s8,dirname as CS,extname as s5,join as i8}from"node:path";import yS from"yaml";var r8="SKILL.md",jS=new Set([".md",".markdown",".txt"]);function t5($){return $.trim().toLowerCase()}function a8($){return jS.has(s5($).toLowerCase())}function e5($){let q=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,Y=$.match(q);if(!Y)return{data:{},body:$,hadFrontmatter:!1};let[,T,X]=Y;try{let J=yS.parse(T);return{data:J&&typeof J==="object"&&!Array.isArray(J)?J:{},body:X,hadFrontmatter:!0}}catch(J){let Q=J instanceof Error?J.message:String(J);return{data:{},body:$,hadFrontmatter:!0,parseError:Q}}}function o8($,q,Y){if($===void 0||$===null){if(Y)throw Error(`Missing required frontmatter field '${q}'.`);return}if(typeof $!=="string")throw Error(`Frontmatter field '${q}' must be a string.`);let T=$.trim();if(!T&&Y)throw Error(`Frontmatter field '${q}' cannot be empty.`);return T||void 0}function $Y($,q){if($===void 0||$===null)return;if(typeof $!=="boolean")throw Error(`Frontmatter field '${q}' must be a boolean.`);return $}function $J($,q){let{data:Y,body:T,parseError:X}=e5($);if(X)throw Error(`Failed to parse YAML frontmatter: ${X}`);let J=T.trim();if(!J)throw Error("Missing instructions body in skill file.");let U=o8(Y.name,"name",!1)??q.trim();if(!U)throw Error("Missing skill name.");return{name:U,description:o8(Y.description,"description",!1),disabled:$Y(Y.disabled,"disabled")??($Y(Y.enabled,"enabled")===!1?!0:void 0),instructions:J,frontmatter:Y}}function qJ($,q){let{data:Y,body:T,parseError:X}=e5($);if(X)throw Error(`Failed to parse YAML frontmatter: ${X}`);let J=T.trim();if(!J)throw Error("Missing instructions body in rule file.");let Q=o8(Y.name,"name",!1)??q.trim();if(!Q)throw Error("Missing rule name.");return{name:Q,disabled:$Y(Y.disabled,"disabled")??($Y(Y.enabled,"enabled")===!1?!0:void 0),instructions:J,frontmatter:Y}}function YJ($,q){let{data:Y,body:T,parseError:X}=e5($);if(X)throw Error(`Failed to parse YAML frontmatter: ${X}`);let J=T.trim();if(!J)throw Error("Missing instructions body in workflow file.");let Q=o8(Y.name,"name",!1)??q.trim();if(!Q)throw Error("Missing workflow name.");return{name:Q,disabled:$Y(Y.disabled,"disabled")??($Y(Y.enabled,"enabled")===!1?!0:void 0),instructions:J,frontmatter:Y}}function TJ($){return D6($)}function XJ($){return H5($)}function JJ($){return z5($)}async function vS($){try{let q=await vV($,{withFileTypes:!0}),Y=[];for(let T of q){if(T.isFile()&&T.name===r8){Y.push({directoryPath:$,fileName:T.name,filePath:i8($,T.name)});continue}if(T.isDirectory())Y.push({directoryPath:i8($,T.name),fileName:r8,filePath:i8($,T.name,r8)})}return Y}catch(q){if(q.code==="ENOENT")return[];throw q}}async function xV($){try{if((await SS($)).isFile())return[{directoryPath:CS($),fileName:s8($),filePath:$}]}catch(q){if(q.code!=="ENOENT")throw q}try{return(await vV($,{withFileTypes:!0})).filter((Y)=>Y.isFile()&&a8(Y.name)).map((Y)=>({directoryPath:$,fileName:Y.name,filePath:i8($,Y.name)}))}catch(q){if(q.code==="ENOENT")return[];throw q}}function QJ($){return{type:"skill",directories:$?.directories??TJ($?.workspacePath),discoverFiles:vS,includeFile:(Y)=>Y===r8,parseFile:(Y)=>$J(Y.content,s8(Y.directoryPath)),resolveId:(Y)=>t5(Y.name)}}function UJ($){return{type:"rule",directories:$?.directories??XJ($?.workspacePath),discoverFiles:xV,includeFile:(Y,T)=>Y===".clinerules"||a8(Y)||a8(T),parseFile:(Y)=>qJ(Y.content,s8(Y.filePath,s5(Y.filePath))),resolveId:(Y)=>t5(Y.name)}}function ZJ($){return{type:"workflow",directories:$?.directories??JJ($?.workspacePath),discoverFiles:xV,includeFile:(Y)=>a8(Y),parseFile:(Y)=>YJ(Y.content,s8(Y.filePath,s5(Y.filePath))),resolveId:(Y)=>t5(Y.name)}}function t8($){let q=[QJ($?.skills),UJ($?.rules),ZJ($?.workflows)];return new Uq(q,{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}function xS($){return{onAuth:({url:q,instructions:Y})=>{if($.onOutput?.(Y??"Complete sign-in in your browser."),$.openUrl)Promise.resolve($.openUrl(q)).catch((T)=>{$.onOpenUrlError?.({url:q,error:T})});$.onOutput?.(q)},onPrompt:$.onPrompt}}function kS(){let $;return{promise:new Promise((Y)=>{$=Y}),resolve:$}}async function Zq($){let q=await import("node:http"),Y=$.host??"127.0.0.1",T=$.timeoutMs??300000,X=$.successHtml??hS,J=kS(),Q=!1,U=null,Z=null,K=(G)=>{if(Q)return;Q=!0,J.resolve(G)},A=()=>{if(U)clearTimeout(U),U=null;if(Z)Z.close(),Z=null},W=async()=>{return U=setTimeout(()=>{A(),K(null)},T),J.promise};for(let G of $.ports){let V=q.createServer((N,D)=>{try{let z=new URL(N.url||"",`http://${Y}:${G}`);if(z.pathname!==$.callbackPath){D.statusCode=404,D.end("Not found");return}let S={url:z,code:z.searchParams.get("code")??void 0,state:z.searchParams.get("state")??void 0,provider:z.searchParams.get("provider")??void 0,error:z.searchParams.get("error")??void 0};if(S.error){D.statusCode=400,D.end(`Authentication failed: ${S.error}`),A(),K(S);return}if(!S.code){D.statusCode=400,D.end("Missing authorization code");return}if($.expectedState&&S.state!==$.expectedState){D.statusCode=400,D.end("State mismatch");return}D.statusCode=200,D.setHeader("Content-Type","text/html; charset=utf-8"),D.end(X),A(),K(S)}catch{D.statusCode=500,D.end("Internal error")}}),F=await new Promise((N)=>{let D=(z)=>{V.off("error",D),N({bound:!1,error:z})};V.once("error",D),V.listen(G,Y,()=>{V.off("error",D),Z=V,N({bound:!0})})});if(F.error){if(F.error.code==="EADDRINUSE")continue;throw A(),F.error}if(F.bound)return{callbackUrl:`http://${Y}:${G}${$.callbackPath}`,waitForCallback:W,cancelWait:()=>{A(),K(null)},close:()=>{A(),K(null)}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var hS=`<!DOCTYPE html>
444
- <html lang="en">
445
- <head>
446
- <meta charset="utf-8">
447
- <meta name="viewport" content="width=device-width, initial-scale=1">
448
- <title>Authentication Successful</title>
449
- <style>
450
- * { margin: 0; padding: 0; box-sizing: border-box; }
451
- body {
452
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
453
- min-height: 100vh;
454
- display: flex;
455
- align-items: center;
456
- justify-content: center;
457
- background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
458
- color: #fff;
459
- }
460
- .container { text-align: center; padding: 48px; max-width: 420px; }
461
- .icon {
462
- width: 72px; height: 72px; margin: 0 auto 24px;
463
- background: linear-gradient(135deg, #10a37f 0%, #1a7f64 100%);
464
- border-radius: 50%;
465
- display: flex; align-items: center; justify-content: center;
466
- }
467
- .icon svg { width: 36px; height: 36px; stroke: #fff; stroke-width: 3; fill: none; }
468
- h1 { font-size: 24px; font-weight: 600; margin-bottom: 12px; }
469
- p { font-size: 15px; color: rgba(255,255,255,0.7); line-height: 1.5; }
470
- .closing { margin-top: 32px; font-size: 13px; color: rgba(255,255,255,0.5); }
471
- </style>
472
- </head>
473
- <body>
474
- <div class="container">
475
- <div class="icon">
476
- <svg viewBox="0 0 24 24"><polyline points="20 6 9 17 4 12"></polyline></svg>
477
- </div>
478
- <h1>Authentication Successful</h1>
479
- <p>You're now signed in. You can close this window.</p>
480
- <p class="closing">This window will close automatically...</p>
481
- </div>
482
- <script>setTimeout(() => window.close(), 3000);</script>
483
- </body>
484
- </html>`;function kV($){let q="";for(let Y=0;Y<$.length;Y+=1)q+=String.fromCharCode($[Y]??0);return btoa(q).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function _S($){let Y=new TextEncoder().encode($),T=await crypto.subtle.digest("SHA-256",Y);return new Uint8Array(T)}function gS($=32){let q=new Uint8Array($);return crypto.getRandomValues(q),kV(q)}async function e8(){let $=gS(),q=kV(await _S($));return{verifier:$,challenge:q}}function $9($){return $.endsWith("/")?$.slice(0,-1):$}function q9($,q){return new URL(q,`${$9($)}/`).toString()}function qY($,q={}){let Y=$.trim();if(!Y)return{};try{let T=new URL(Y);return{code:T.searchParams.get("code")??void 0,state:T.searchParams.get("state")??void 0,provider:q.includeProvider?T.searchParams.get("provider")??void 0:void 0}}catch{}if(q.allowHashCodeState&&Y.includes("#")){let[T,X]=Y.split("#",2);return{code:T||void 0,state:X||void 0}}if(Y.includes("code=")){let T=new URLSearchParams(Y);return{code:T.get("code")??void 0,state:T.get("state")??void 0,provider:q.includeProvider?T.get("provider")??void 0:void 0}}return{code:Y}}function mS($){if(typeof atob==="function")try{return atob($)}catch{return null}if(typeof Buffer<"u")try{return Buffer.from($,"base64").toString("utf8")}catch{return null}return null}function D1($){if(!$)return null;try{let q=$.split(".");if(q.length!==3)return null;let Y=q[1];if(!Y)return null;let T=Y.replace(/-/g,"+").replace(/_/g,"/"),X=T.padEnd(T.length+(4-T.length%4)%4,"="),J=mS(X);if(!J)return null;return JSON.parse(J)}catch{return null}}function H6($){try{let q=JSON.parse($),Y=q.error,T=typeof Y==="string"?Y:Y&&typeof Y==="object"&&typeof Y.type==="string"?Y.type:void 0,X=typeof q.error_description==="string"?q.error_description:typeof q.message==="string"?q.message:Y&&typeof Y==="object"&&typeof Y.message==="string"?Y.message:void 0;return{code:T,message:X}}catch{return{}}}function Kq($,q){return Date.now()>=$.expires-q}async function YY($){if(!$.onManualCodeInput){let J=await $.waitForCallback();return{code:J?.code,state:J?.state,provider:J?.provider,error:J?.error}}let q,Y,T=$.onManualCodeInput().then((J)=>{q=J,$.cancelWait()}).catch((J)=>{Y=J instanceof Error?J:Error(String(J)),$.cancelWait()}),X=await $.waitForCallback();if(Y)throw Y;if(X?.code||X?.error)return{code:X.code,state:X.state,provider:X.provider,error:X.error};if(q)return qY(q,$.parseOptions);if(await T,Y)throw Y;if(q)return qY(q,$.parseOptions);return{}}var KJ={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",refresh:"/api/v1/auth/refresh"},fS="/auth",hV=Array.from({length:11},($,q)=>48801+q),bS=300000,uS=30000,AJ=30000;class Y9 extends Error{status;errorCode;constructor($,q){super($);this.name="ClineOAuthTokenError",this.status=q?.status,this.errorCode=q?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid|expired|revoked|unauthorized/i.test(this.message);return!1}}function dS(){let $=globalThis.crypto;if(!$)return Math.random().toString(16).slice(2);let q=new Uint8Array(16);return $.getRandomValues(q),Array.from(q,(Y)=>Y.toString(16).padStart(2,"0")).join("")}function cS($){let q=Date.parse($);if(Number.isNaN(q))throw Error(`Invalid expiresAt value: ${$}`);return q}function _V($,q,Y={}){let T=$.userInfo.clineUserId??Y.accountId,X=$.refreshToken??Y.refresh;if(!X)throw Error("Token response did not include a refresh token");return{access:$.accessToken,refresh:X,expires:cS($.expiresAt),accountId:T??void 0,email:$.userInfo.email||Y.email,metadata:{provider:q,tokenType:$.tokenType,userInfo:$.userInfo}}}async function WJ($){if(!$)return{};return typeof $==="function"?await $():$}async function pS($,q){let Y=new URL(q9($.apiBaseUrl,KJ.authorize));Y.searchParams.set("client_type","extension"),Y.searchParams.set("callback_url",q.callbackUrl),Y.searchParams.set("redirect_uri",q.callbackUrl),Y.searchParams.set("state",q.state);let T=await fetch(Y.toString(),{method:"GET",redirect:"manual",headers:await WJ($.headers),signal:AbortSignal.timeout($.requestTimeoutMs??AJ)});if(T.status>=300&&T.status<400){let J=T.headers.get("location");if(J)return J}if(!T.ok){let J=await T.text().catch(()=>"");throw Error(`Authentication request failed: ${T.status} ${J}`)}let X=await T.json();if(typeof X.redirect_url==="string"&&X.redirect_url.length>0)return X.redirect_url;throw Error("Authentication request did not return a redirect URL")}async function lS($,q,Y,T){let X={grant_type:"authorization_code",code:$,client_type:"extension",redirect_uri:q,provider:T??Y.provider},J=await fetch(q9(Y.apiBaseUrl,KJ.token),{method:"POST",headers:{"Content-Type":"application/json",...await WJ(Y.headers)},body:JSON.stringify(X),signal:AbortSignal.timeout(Y.requestTimeoutMs??AJ)});if(!J.ok){let U=await J.text().catch(()=>""),Z=H6(U);throw new Y9(`Token exchange failed: ${J.status}${Z.message?` - ${Z.message}`:""}`,{status:J.status,errorCode:Z.code})}let Q=await J.json();if(!Q.success||!Q.data?.accessToken)throw Error("Invalid token exchange response");return _V(Q.data,T??Y.provider)}async function gV($){let q=$.callbackPorts?.length?$.callbackPorts:hV,Y=$.callbackPath??fS,T=dS(),X=await Zq({ports:q,callbackPath:Y}),J=X.callbackUrl||`http://127.0.0.1:${q[0]??hV[0]}${Y}`,Q=await pS($,{callbackUrl:J,state:T});$.callbacks.onAuth({url:Q,instructions:"Continue the authentication process in your browser."});try{let U,Z=$.provider,K=await YY({waitForCallback:X.waitForCallback,cancelWait:X.cancelWait,onManualCodeInput:$.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(K.error)throw Error(`OAuth error: ${K.error}`);if(K.state&&K.state!==T)throw Error("State mismatch");if(U=K.code,Z=K.provider??Z,!U){let A=await $.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),W=qY(A,{includeProvider:!0});if(W.state&&W.state!==T)throw Error("State mismatch");U=W.code,Z=W.provider??Z}if(!U)throw Error("Missing authorization code");return lS(U,J,$,Z)}finally{X.close()}}async function GJ($,q){let Y=await fetch(q9(q.apiBaseUrl,KJ.refresh),{method:"POST",headers:{"Content-Type":"application/json",...await WJ(q.headers)},body:JSON.stringify({refreshToken:$.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout(q.requestTimeoutMs??AJ)});if(!Y.ok){let J=await Y.text().catch(()=>""),Q=H6(J);throw new Y9(`Token refresh failed: ${Y.status}${Q.message?` - ${Q.message}`:""}`,{status:Y.status,errorCode:Q.code})}let T=await Y.json();if(!T.success||!T.data?.accessToken)throw Error("Invalid token refresh response");let X=$.metadata?.provider??q.provider;return _V(T.data,X,$)}async function EJ($,q,Y){if(!$)return null;let T=Y?.refreshBufferMs??bS,X=Y?.retryableTokenGraceMs??uS;if(Y?.forceRefresh!==!0&&!Kq($,T))return $;try{return await GJ($,q)}catch(Q){if(Q instanceof Y9&&Q.isLikelyInvalidGrant())return null;if($.expires-Date.now()>X)return $;return null}}function nS($){return{id:"cline",name:"Cline Account",usesCallbackServer:!0,async login(q){return gV({...$,callbacks:q})},async refreshToken(q){return GJ(q,$)},getApiKey(q){return`workos:${q.access}`}}}import{nanoid as iS}from"nanoid";var M0={authorizationEndpoint:"https://auth.openai.com/oauth/authorize",tokenEndpoint:"https://auth.openai.com/oauth/token",clientId:"app_EMoamEEZ73f0CkXaXp7hrann",redirectUri:"http://localhost:1455/auth/callback",scopes:"openid profile email offline_access",callbackPort:1455,jwtClaimPath:"https://api.openai.com/auth",refreshBufferMs:300000,retryableTokenGraceMs:30000,httpTimeoutMs:30000};class T9 extends Error{status;errorCode;constructor($,q){super($);this.name="OpenAICodexOAuthTokenError",this.status=q?.status,this.errorCode=q?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid_grant|revoked|expired|invalid refresh/i.test(this.message);return!1}}async function rS($,q,Y=M0.redirectUri){let T=await fetch(M0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:M0.clientId,code:$,code_verifier:q,redirect_uri:Y}),signal:AbortSignal.timeout(M0.httpTimeoutMs)});if(!T.ok)return{type:"failed"};let X=await T.json();if(!X.access_token||!X.refresh_token||typeof X.expires_in!=="number")return{type:"failed"};return{type:"success",access:X.access_token,refresh:X.refresh_token,expires:Date.now()+X.expires_in*1000,email:X.email,idToken:X.id_token}}async function aS($){try{let q=await fetch(M0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:$,client_id:M0.clientId}),signal:AbortSignal.timeout(M0.httpTimeoutMs)});if(!q.ok){let T=await q.text().catch(()=>""),X=H6(T);throw new T9(`Token refresh failed: ${q.status}${X.message?` - ${X.message}`:""}`,{status:q.status,errorCode:X.code})}let Y=await q.json();if(!Y.access_token||!Y.refresh_token||typeof Y.expires_in!=="number")return{type:"failed"};return{type:"success",access:Y.access_token,refresh:Y.refresh_token,expires:Date.now()+Y.expires_in*1000,email:Y.email,idToken:Y.id_token}}catch(q){if(q instanceof T9)throw q;return{type:"failed"}}}async function oS($="pi"){let{verifier:q,challenge:Y}=await e8(),T=iS(32),X=new URL(M0.authorizationEndpoint);return X.searchParams.set("response_type","code"),X.searchParams.set("client_id",M0.clientId),X.searchParams.set("redirect_uri",M0.redirectUri),X.searchParams.set("scope",M0.scopes),X.searchParams.set("code_challenge",Y),X.searchParams.set("code_challenge_method","S256"),X.searchParams.set("state",T),X.searchParams.set("id_token_add_organizations","true"),X.searchParams.set("codex_cli_simplified_flow","true"),X.searchParams.set("originator",$),{verifier:q,state:T,url:X.toString()}}function sS(){try{let $=new URL(M0.redirectUri),q=$.port.length>0?Number.parseInt($.port,10):M0.callbackPort;return{host:$.hostname||"localhost",port:Number.isFinite(q)?q:M0.callbackPort,callbackPath:$.pathname||"/auth/callback",redirectUri:$.toString()}}catch{return{host:"localhost",port:M0.callbackPort,callbackPath:"/auth/callback",redirectUri:M0.redirectUri}}}function mV($,q){let Y=q?D1(q):D1($),T=Y?Y:D1($),J=T?.[M0.jwtClaimPath]?.chatgpt_account_id;if(typeof J==="string"&&J.length>0)return J;let Q=T?.organizations;if(Array.isArray(Q)&&Q.length>0){let Z=Q[0];if(typeof Z?.id==="string"&&Z.id.length>0)return Z.id}let U=T?.chatgpt_account_id;if(typeof U==="string"&&U.length>0)return U;return null}function fV($,q){let Y=mV($.access,$.idToken)??q?.accountId;if(!Y)throw Error("Failed to extract accountId from token");return{access:$.access,refresh:$.refresh||q?.refresh||"",expires:$.expires,accountId:Y,email:$.email??q?.email,metadata:{...q?.metadata??{},provider:"openai-codex"}}}async function bV($){let q=sS(),{verifier:Y,state:T,url:X}=await oS($.originator),J=await Zq({host:q.host,ports:[q.port],callbackPath:q.callbackPath,expectedState:T});$.onAuth({url:X,instructions:"Continue the authentication process in your browser."});let Q;try{let U=await YY({waitForCallback:J.waitForCallback,cancelWait:J.cancelWait,onManualCodeInput:$.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(U.state&&U.state!==T)throw Error("State mismatch");if(Q=U.code,!Q){let K=await $.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),A=qY(K,{allowHashCodeState:!0});if(A.state&&A.state!==T)throw Error("State mismatch");Q=A.code}if(!Q)throw Error("Missing authorization code");let Z=await rS(Q,Y,q.redirectUri);if(Z.type!=="success")throw Error("Token exchange failed");return fV(Z)}finally{J.close()}}async function VJ($,q){let Y=await aS($);if(Y.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let T=fV(Y,q);if(!T.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return T}async function DJ($,q){if(!$)return null;let Y=q?.refreshBufferMs??M0.refreshBufferMs,T=q?.retryableTokenGraceMs??M0.retryableTokenGraceMs;if(q?.forceRefresh!==!0&&!Kq($,Y))return $;try{return await VJ($.refresh,$)}catch(J){if(J instanceof T9&&J.isLikelyInvalidGrant())return null;if($.expires-Date.now()>T)return $;return null}}function tS($,q=M0.refreshBufferMs){return Kq($,q)}function eS($){let q=$.accountId??mV($.access);if(!q)throw Error("Failed to extract accountId from token");return{...$,accountId:q,metadata:{...$.metadata??{},provider:"openai-codex"}}}var $C={id:"openai-codex",name:"ChatGPT Plus/Pro (ChatGPT Subscription)",usesCallbackServer:!0,async login($){return bV({onAuth:$.onAuth,onPrompt:$.onPrompt,onProgress:$.onProgress,onManualCodeInput:$.onManualCodeInput})},async refreshToken($){return VJ($.refresh,$)},getApiKey($){return $.access}};import{nanoid as uV}from"nanoid";var dV="a8331954c0cf48ba99b5dd223a14c6ea",cV="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",pV="openid offline_access",lV="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",nV="c1aba3deed5740659981a752714eba33",iV="https://login-ext.identity.oraclecloud.com",rV="openid offline_access",aV="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",oV="opc-request-id",qC="/auth/oca",YC=Array.from({length:11},($,q)=>48801+q),TC=300000,XC=30000,sV=30000,JC=600000;class X9 extends Error{status;errorCode;constructor($,q){super($);this.name="OcaOAuthTokenError",this.status=q?.status,this.errorCode=q?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;return this.status===400||this.status===401||this.status===403}}var x$={internal:{clientId:dV,idcsUrl:cV,scopes:pV,baseUrl:lV},external:{clientId:nV,idcsUrl:iV,scopes:rV,baseUrl:aV}},z6=new Map,FJ=new Map;function tV($){if(typeof $==="function")return $();return $??"internal"}function eV($){return{internal:{clientId:$?.internal?.clientId??x$.internal.clientId,idcsUrl:$?.internal?.idcsUrl??x$.internal.idcsUrl,scopes:$?.internal?.scopes??x$.internal.scopes,baseUrl:$?.internal?.baseUrl??x$.internal.baseUrl},external:{clientId:$?.external?.clientId??x$.external.clientId,idcsUrl:$?.external?.idcsUrl??x$.external.idcsUrl,scopes:$?.external?.scopes??x$.external.scopes,baseUrl:$?.external?.baseUrl??x$.external.baseUrl}}}function QC($=Date.now()){let q=$-JC;for(let[Y,T]of z6.entries())if(T.createdAt<q)z6.delete(Y)}function UC($,q,Y){if(typeof $.expires_in==="number"&&$.expires_in>0)return Date.now()+$.expires_in*1000;let X=D1(q)?.exp;if(typeof X==="number"&&X>0)return X*1000;let Q=D1(Y)?.exp;if(typeof Q==="number"&&Q>0)return Q*1000;return Date.now()+3600000}function $3($,q,Y){let T=$.access_token;if(!T)throw Error("Token response did not include an access token");let X=$.refresh_token??Y?.refresh;if(!X)throw Error("Token response did not include a refresh token");let J=D1($.id_token),Q=D1(T),U=J?.sub??Q?.sub,Z=J?.email??Q?.email;return{access:T,refresh:X,expires:UC($,T,$.id_token),accountId:U??Y?.accountId,email:Z??Y?.email,metadata:{...Y?.metadata??{},provider:"oca",mode:q,subject:U,idToken:$.id_token}}}async function q3($,q){let Y=$9($),T=FJ.get(Y);if(T)return T;let X=`${Y}/.well-known/openid-configuration`,J=await fetch(X,{method:"GET",signal:AbortSignal.timeout(q)});if(!J.ok){let Z=`${Y}/oauth2/v1/token`;return FJ.set(Y,Z),Z}let U=(await J.json()).token_endpoint||`${Y}/oauth2/v1/token`;return FJ.set(Y,U),U}function Y3($){return{code:$.error,message:$.error_description}}async function ZC($){let q=z6.get($.state);if(!q)throw Error("No PKCE verifier found for this state");z6.delete($.state);let Y=$.mode==="external"?$.config.external:$.config.internal,T=await q3(Y.idcsUrl,$.requestTimeoutMs),X=new URLSearchParams({grant_type:"authorization_code",code:$.code,redirect_uri:q.redirectUri,client_id:Y.clientId,code_verifier:q.verifier}),J=await fetch(T,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:X,signal:AbortSignal.timeout($.requestTimeoutMs)}),Q=await J.json();if(!J.ok){let Z=Y3(Q);throw new X9(`Token exchange failed: ${J.status}${Z.message?` - ${Z.message}`:""}`,{status:J.status,errorCode:Z.code})}let U=D1(Q.id_token);if(!Q.id_token||!U)throw Error("No ID token received from OCA");if(U.nonce!==q.nonce)throw Error("OIDC nonce verification failed");return $3(Q,$.mode)}function KC($){let q=$.mode==="external"?$.config.external:$.config.internal,Y=new URL(`${$9(q.idcsUrl)}/oauth2/v1/authorize`);return Y.searchParams.set("client_id",q.clientId),Y.searchParams.set("response_type","code"),Y.searchParams.set("scope",q.scopes),Y.searchParams.set("code_challenge",$.challenge),Y.searchParams.set("code_challenge_method","S256"),Y.searchParams.set("redirect_uri",$.callbackUrl),Y.searchParams.set("state",$.state),Y.searchParams.set("nonce",$.nonce),Y.toString()}async function T3($){let q=eV($.config),Y=tV($.mode),T=$.callbackPorts?.length?$.callbackPorts:YC,X=$.callbackPath??qC,J=$.requestTimeoutMs??sV,Q=await Zq({ports:T,callbackPath:X}),U=Q.callbackUrl;if(!U)throw Error("Unable to bind local OAuth callback server");let Z=uV(16),K=uV(16),{verifier:A,challenge:W}=await e8();QC(),z6.set(Z,{verifier:A,nonce:K,mode:Y,redirectUri:U,createdAt:Date.now()});let G=KC({callbackUrl:U,mode:Y,state:Z,nonce:K,challenge:W,config:q});$.callbacks.onAuth({url:G,instructions:"Continue the authentication process in your browser."});try{let V=await YY({waitForCallback:Q.waitForCallback,cancelWait:Q.cancelWait,onManualCodeInput:$.callbacks.onManualCodeInput}),F=V.code,N=V.state;if(V.error)throw Error(`OAuth error: ${V.error}`);if(!F){if(!$.callbacks.onManualCodeInput)throw Error("Timed out waiting for OCA callback");throw Error("Missing authorization code")}if(!N||N!==Z)throw Error("State mismatch");return await ZC({code:F,state:N,mode:Y,config:q,requestTimeoutMs:J})}finally{Q.close()}}async function IJ($,q={}){let Y=eV(q.config),T=q.requestTimeoutMs??sV,X=$.metadata?.mode,J=X==="internal"||X==="external"?X:tV(q.mode),Q=J==="external"?Y.external:Y.internal,U=await q3(Q.idcsUrl,T),Z=new URLSearchParams({grant_type:"refresh_token",refresh_token:$.refresh,client_id:Q.clientId}),K=await fetch(U,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Z,signal:AbortSignal.timeout(T)}),A=await K.json();if(!K.ok){let W=Y3(A);throw new X9(`Token refresh failed: ${K.status}${W.message?` - ${W.message}`:""}`,{status:K.status,errorCode:W.code})}return $3(A,J,$)}async function NJ($,q,Y){if(!$)return null;let T=q?.refreshBufferMs??Y?.refreshBufferMs??TC,X=q?.retryableTokenGraceMs??Y?.retryableTokenGraceMs??XC;if(q?.forceRefresh!==!0&&!Kq($,T))return $;try{return await IJ($,Y)}catch(Q){if(Q instanceof X9&&Q.isLikelyInvalidGrant())return null;if($.expires-Date.now()>X)return $;return null}}function AC($={}){return{id:"oca",name:"Oracle Code Assist",usesCallbackServer:!0,async login(q){return T3({...$,callbacks:q})},async refreshToken(q){return IJ(q,$)},getApiKey(q){return q.access}}}async function X3($,q){let Y=new TextEncoder,T=async(K)=>{let A=await crypto.subtle.digest("SHA-256",Y.encode(K));return Array.from(new Uint8Array(A).slice(0,4),(W)=>W.toString(16).padStart(2,"0")).join("")},[X,J]=await Promise.all([T(q),T($)]),Q=Math.floor(Date.now()/1000).toString(16).padStart(8,"0"),U=new Uint32Array(1);crypto.getRandomValues(U);let Z=(U[0]??0).toString(16).padStart(8,"0");return X+J+Q+Z}async function WC($){let q=await X3($.taskId,$.accessToken);return{Authorization:`Bearer ${$.accessToken}`,"Content-Type":"application/json",client:$.metadata?.client??"Cline","client-version":$.metadata?.clientVersion??"unknown","client-ide":$.metadata?.clientIde??"unknown","client-ide-version":$.metadata?.clientIdeVersion??"unknown",[oV]:q}}import{existsSync as GC,readFileSync as EC}from"node:fs";import{z as t}from"zod";var M6=t.record(t.string(),t.string()),J3=t.record(t.string(),t.unknown()),VC=t.object({type:t.literal("stdio"),command:t.string().min(1),args:t.array(t.string()).optional(),cwd:t.string().min(1).optional(),env:M6.optional()}),DC=t.object({type:t.literal("sse"),url:t.string().url(),headers:M6.optional()}),FC=t.object({type:t.literal("streamableHttp"),url:t.string().url(),headers:M6.optional()}),IC=t.discriminatedUnion("type",[VC,DC,FC]),NC=t.object({transport:IC,disabled:t.boolean().optional(),metadata:J3.optional()}),HC=t.enum(["stdio","sse","http","streamableHttp"]).optional(),Q3=t.object({type:t.enum(["stdio","sse","streamableHttp"]).optional(),transportType:HC,disabled:t.boolean().optional(),metadata:J3.optional()});function HJ($){if(!$)return;if($==="http")return"streamableHttp";return $}var zC=Q3.extend({command:t.string().min(1),args:t.array(t.string()).optional(),cwd:t.string().min(1).optional(),env:M6.optional()}).superRefine(($,q)=>{let Y=$.type??HJ($.transportType);if(Y&&Y!=="stdio")q.addIssue({code:t.ZodIssueCode.custom,message:'Expected type "stdio" for command-based MCP server',path:["type"]})}).transform(($)=>({transport:{type:"stdio",command:$.command,args:$.args,cwd:$.cwd,env:$.env},disabled:$.disabled,metadata:$.metadata})),MC=Q3.extend({url:t.string().url(),headers:M6.optional()}).superRefine(($,q)=>{let Y=$.type??HJ($.transportType)??"sse";if(Y!=="sse"&&Y!=="streamableHttp")q.addIssue({code:t.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform(($)=>{if(($.type??HJ($.transportType)??"sse")==="streamableHttp")return{transport:{type:"streamableHttp",url:$.url,headers:$.headers},disabled:$.disabled,metadata:$.metadata};return{transport:{type:"sse",url:$.url,headers:$.headers},disabled:$.disabled,metadata:$.metadata}}),BC=t.union([NC,zC,MC]),RC=t.object({mcpServers:t.record(t.string(),BC)}).strict();function J9(){return D5()}function zJ($={}){let q=$.filePath??J9(),Y=EC(q,"utf8"),T;try{T=JSON.parse(Y)}catch(J){let Q=J instanceof Error?J.message:String(J);throw Error(`Failed to parse MCP settings JSON at "${q}": ${Q}`)}let X=RC.safeParse(T);if(!X.success){let J=X.error.issues.map((Q)=>{let U=Q.path.join(".");return U?`${U}: ${Q.message}`:Q.message}).join("; ");throw Error(`Invalid MCP settings at "${q}": ${J}`)}return X.data}function U3($={}){let q=$.filePath??J9();return GC(q)}function MJ($={}){let q=zJ($);return Object.entries(q.mcpServers).map(([Y,T])=>({name:Y,transport:T.transport,disabled:T.disabled,metadata:T.metadata}))}async function Z3($,q={}){let Y=MJ(q);for(let T of Y)await $.registerServer(T);return Y}function F1(){return Date.now()}function PC($){return $.map((q)=>({name:q.name,description:q.description,inputSchema:q.inputSchema}))}class BJ{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor($){this.clientFactory=$.clientFactory,this.toolsCacheTtlMs=$.toolsCacheTtlMs??5000}async registerServer($){await this.runExclusive($.name,async()=>{let q=this.servers.get($.name);if(!q){this.servers.set($.name,{registration:{...$},status:"disconnected",updatedAt:F1()});return}let Y=JSON.stringify(q.registration.transport)!==JSON.stringify($.transport);if(q.registration={...$},q.updatedAt=F1(),Y)await this.disconnectState(q),q.client=void 0,q.toolCache=void 0,q.toolCacheUpdatedAt=void 0})}async unregisterServer($){await this.runExclusive($,async()=>{let q=this.requireServer($);await this.disconnectState(q),this.servers.delete($)})}async connectServer($){await this.runExclusive($,async()=>{let q=this.requireServer($);await this.connectState(q)})}async disconnectServer($){await this.runExclusive($,async()=>{let q=this.requireServer($);await this.disconnectState(q)})}async setServerDisabled($,q){await this.runExclusive($,async()=>{let Y=this.requireServer($);if(Y.registration={...Y.registration,disabled:q},Y.updatedAt=F1(),q)await this.disconnectState(Y)})}listServers(){return[...this.servers.values()].map(($)=>({name:$.registration.name,status:$.status,disabled:$.registration.disabled===!0,lastError:$.lastError,toolCount:$.toolCache?.length??0,updatedAt:$.updatedAt,metadata:$.registration.metadata})).sort(($,q)=>$.name.localeCompare(q.name))}async listTools($){let q=this.requireServer($),Y=q.toolCacheUpdatedAt??0;if(q.toolCache&&F1()-Y<=this.toolsCacheTtlMs)return q.toolCache;return this.refreshTools($)}async refreshTools($){return this.runExclusive($,async()=>{let q=this.requireServer($),T=await(await this.ensureConnectedClient(q)).listTools(),X=PC(T);return q.toolCache=X,q.toolCacheUpdatedAt=F1(),q.updatedAt=F1(),X})}async callTool($){return this.runExclusive($.serverName,async()=>{let q=this.requireServer($.serverName),Y=await this.ensureConnectedClient(q);return q.updatedAt=F1(),Y.callTool({name:$.toolName,arguments:$.arguments,context:$.context})})}async dispose(){let $=[...this.servers.keys()];for(let q of $)await this.unregisterServer(q)}async ensureConnectedClient($){if(await this.connectState($),!$.client)throw Error(`MCP server "${$.registration.name}" does not have an initialized client.`);return $.client}async connectState($){if($.registration.disabled)throw Error(`MCP server "${$.registration.name}" is disabled and cannot be connected.`);if($.status==="connected"&&$.client)return;$.status="connecting",$.updatedAt=F1();try{let q=$.client??await this.clientFactory($.registration);await q.connect(),$.client=q,$.status="connected",$.lastError=void 0,$.updatedAt=F1()}catch(q){throw $.status="disconnected",$.lastError=q instanceof Error?q.message:String(q),$.updatedAt=F1(),q}}async disconnectState($){if(!$.client){$.status="disconnected",$.updatedAt=F1();return}try{await $.client.disconnect()}finally{$.status="disconnected",$.updatedAt=F1()}}requireServer($){let q=this.servers.get($);if(!q)throw Error(`Unknown MCP server: ${$}`);return q}async runExclusive($,q){let Y=this.operationLocks.get($)??Promise.resolve(),T,X=new Promise((Q)=>{T=Q}),J=Y.catch(()=>{return}).then(()=>X);this.operationLocks.set($,J),await Y.catch(()=>{return});try{return await q()}finally{if(T?.(),this.operationLocks.get($)===J)this.operationLocks.delete($)}}}function K3($){return $.disabled!==!0}function A3($){if($.length===0)return"";return`
485
-
486
- # Rules
487
- ${$.map((Y)=>`## ${Y.name}
488
- ${Y.instructions}`).join(`
489
-
490
- `)}`}function W3($){return[...$.getSnapshot("rule").values()].map((Y)=>Y.item).filter(K3).sort((Y,T)=>Y.name.localeCompare(T.name))}function OC($){return A3(W3($))}import{existsSync as PJ,readdirSync as jC}from"node:fs";import{join as G3}from"node:path";import{AgentTeamsRuntime as vC,bootstrapAgentTeams as xC}from"@clinebot/agents";import{nanoid as kC}from"nanoid";import{existsSync as LC,mkdirSync as wC}from"node:fs";import{join as SC}from"node:path";function CC(){return D8()}function TY($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function yC($){return{...$,tasks:$.tasks.map((q)=>({...q,createdAt:new Date(q.createdAt),updatedAt:new Date(q.updatedAt)})),mailbox:$.mailbox.map((q)=>({...q,sentAt:new Date(q.sentAt),readAt:q.readAt?new Date(q.readAt):void 0})),missionLog:$.missionLog.map((q)=>({...q,ts:new Date(q.ts)})),runs:($.runs??[]).map((q)=>({...q,startedAt:new Date(q.startedAt),endedAt:q.endedAt?new Date(q.endedAt):void 0,nextAttemptAt:q.nextAttemptAt?new Date(q.nextAttemptAt):void 0,heartbeatAt:q.heartbeatAt?new Date(q.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((q)=>({...q,createdAt:new Date(q.createdAt),finalizedAt:q.finalizedAt?new Date(q.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((q)=>({...q,createdAt:new Date(q.createdAt),reviewedAt:q.reviewedAt?new Date(q.reviewedAt):void 0}))}}class RJ{teamDirPath;db;constructor($={}){this.teamDirPath=$.teamDir??CC()}init(){this.getRawDb()}ensureTeamDir(){if(!LC(this.teamDirPath))wC(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return SC(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let $=t$(this.dbPath());return this.ensureSchema($),this.db=$,$}ensureSchema($){$.exec(`
491
- CREATE TABLE IF NOT EXISTS team_events (
492
- id INTEGER PRIMARY KEY AUTOINCREMENT,
493
- team_name TEXT NOT NULL,
494
- ts TEXT NOT NULL,
495
- event_type TEXT NOT NULL,
496
- payload_json TEXT NOT NULL,
497
- causation_id TEXT,
498
- correlation_id TEXT
499
- );
500
- CREATE INDEX IF NOT EXISTS idx_team_events_name_ts
501
- ON team_events(team_name, ts DESC);
502
-
503
- CREATE TABLE IF NOT EXISTS team_runtime_snapshot (
504
- team_name TEXT PRIMARY KEY,
505
- state_json TEXT NOT NULL,
506
- teammates_json TEXT NOT NULL,
507
- updated_at TEXT NOT NULL
508
- );
509
-
510
- CREATE TABLE IF NOT EXISTS team_tasks (
511
- team_name TEXT NOT NULL,
512
- task_id TEXT NOT NULL,
513
- title TEXT NOT NULL,
514
- description TEXT NOT NULL,
515
- status TEXT NOT NULL,
516
- assignee TEXT,
517
- depends_on_json TEXT NOT NULL,
518
- summary TEXT,
519
- version INTEGER NOT NULL DEFAULT 1,
520
- updated_at TEXT NOT NULL,
521
- PRIMARY KEY(team_name, task_id)
522
- );
523
-
524
- CREATE TABLE IF NOT EXISTS team_runs (
525
- team_name TEXT NOT NULL,
526
- run_id TEXT NOT NULL,
527
- agent_id TEXT NOT NULL,
528
- task_id TEXT,
529
- status TEXT NOT NULL,
530
- message TEXT NOT NULL,
531
- started_at TEXT,
532
- ended_at TEXT,
533
- error TEXT,
534
- lease_owner TEXT,
535
- heartbeat_at TEXT,
536
- version INTEGER NOT NULL DEFAULT 1,
537
- PRIMARY KEY(team_name, run_id)
538
- );
539
- CREATE INDEX IF NOT EXISTS idx_team_runs_status
540
- ON team_runs(team_name, status);
541
-
542
- CREATE TABLE IF NOT EXISTS team_outcomes (
543
- team_name TEXT NOT NULL,
544
- outcome_id TEXT NOT NULL,
545
- title TEXT NOT NULL,
546
- status TEXT NOT NULL,
547
- schema_json TEXT NOT NULL,
548
- finalized_at TEXT,
549
- version INTEGER NOT NULL DEFAULT 1,
550
- PRIMARY KEY(team_name, outcome_id)
551
- );
552
-
553
- CREATE TABLE IF NOT EXISTS team_outcome_fragments (
554
- team_name TEXT NOT NULL,
555
- outcome_id TEXT NOT NULL,
556
- fragment_id TEXT NOT NULL,
557
- section TEXT NOT NULL,
558
- source_agent_id TEXT NOT NULL,
559
- source_run_id TEXT,
560
- content TEXT NOT NULL,
561
- status TEXT NOT NULL,
562
- reviewed_by TEXT,
563
- reviewed_at TEXT,
564
- version INTEGER NOT NULL DEFAULT 1,
565
- PRIMARY KEY(team_name, fragment_id)
566
- );
567
- `)}run($,q=[]){return this.getRawDb().prepare($).run(...q)}queryOne($,q=[]){return this.getRawDb().prepare($).get(...q)??void 0}queryAll($,q=[]){return this.getRawDb().prepare($).all(...q)}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map(($)=>$.team_name)}readState($){let q=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[TY($)]);if(!q)return;return yC(JSON.parse(q.state_json))}readHistory($,q=200){return this.queryAll("SELECT event_type, payload_json, ts FROM team_events WHERE team_name = ? ORDER BY id DESC LIMIT ?",[TY($),q]).map((Y)=>({eventType:Y.event_type,payload:JSON.parse(Y.payload_json),ts:Y.ts}))}loadRuntime($){let q=TY($),Y=this.readState(q),T=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[q]),X=T?JSON.parse(T.teammates_json):[],J=this.markInProgressRunsInterrupted(q,"runtime_recovered");return{state:Y,teammates:X,interruptedRunIds:J}}appendTeamEvent($,q,Y,T){this.run(`INSERT INTO team_events (team_name, ts, event_type, payload_json, causation_id, correlation_id)
568
- VALUES (?, ?, ?, ?, NULL, ?)`,[TY($),X0(),q,JSON.stringify(Y),T??null])}persistRuntime($,q,Y){let T=TY($),X=X0();this.run(`INSERT INTO team_runtime_snapshot (team_name, state_json, teammates_json, updated_at)
569
- VALUES (?, ?, ?, ?)
570
- ON CONFLICT(team_name) DO UPDATE SET
571
- state_json = excluded.state_json,
572
- teammates_json = excluded.teammates_json,
573
- updated_at = excluded.updated_at`,[T,JSON.stringify(q),JSON.stringify(Y),X]);for(let J of q.tasks)this.run(`INSERT INTO team_tasks (team_name, task_id, title, description, status, assignee, depends_on_json, summary, version, updated_at)
574
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?)
575
- ON CONFLICT(team_name, task_id) DO UPDATE SET
576
- title = excluded.title,
577
- description = excluded.description,
578
- status = excluded.status,
579
- assignee = excluded.assignee,
580
- depends_on_json = excluded.depends_on_json,
581
- summary = excluded.summary,
582
- version = team_tasks.version + 1,
583
- updated_at = excluded.updated_at`,[T,J.id,J.title,J.description,J.status,J.assignee??null,JSON.stringify(J.dependsOn??[]),J.summary??null,J.updatedAt.toISOString()]);for(let J of q.runs??[])this.run(`INSERT INTO team_runs (team_name, run_id, agent_id, task_id, status, message, started_at, ended_at, error, lease_owner, heartbeat_at, version)
584
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
585
- ON CONFLICT(team_name, run_id) DO UPDATE SET
586
- agent_id = excluded.agent_id,
587
- task_id = excluded.task_id,
588
- status = excluded.status,
589
- message = excluded.message,
590
- started_at = excluded.started_at,
591
- ended_at = excluded.ended_at,
592
- error = excluded.error,
593
- lease_owner = excluded.lease_owner,
594
- heartbeat_at = excluded.heartbeat_at,
595
- version = team_runs.version + 1`,[T,J.id,J.agentId,J.taskId??null,J.status,J.message,J.startedAt?J.startedAt.toISOString():null,J.endedAt?J.endedAt.toISOString():null,J.error??null,J.leaseOwner??null,J.heartbeatAt?J.heartbeatAt.toISOString():null]);for(let J of q.outcomes??[])this.run(`INSERT INTO team_outcomes (team_name, outcome_id, title, status, schema_json, finalized_at, version)
596
- VALUES (?, ?, ?, ?, ?, ?, 1)
597
- ON CONFLICT(team_name, outcome_id) DO UPDATE SET
598
- title = excluded.title,
599
- status = excluded.status,
600
- schema_json = excluded.schema_json,
601
- finalized_at = excluded.finalized_at,
602
- version = team_outcomes.version + 1`,[T,J.id,J.title,J.status,JSON.stringify({requiredSections:J.requiredSections}),J.finalizedAt?J.finalizedAt.toISOString():null]);for(let J of q.outcomeFragments??[])this.run(`INSERT INTO team_outcome_fragments (team_name, outcome_id, fragment_id, section, source_agent_id, source_run_id, content, status, reviewed_by, reviewed_at, version)
603
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
604
- ON CONFLICT(team_name, fragment_id) DO UPDATE SET
605
- outcome_id = excluded.outcome_id,
606
- section = excluded.section,
607
- source_agent_id = excluded.source_agent_id,
608
- source_run_id = excluded.source_run_id,
609
- content = excluded.content,
610
- status = excluded.status,
611
- reviewed_by = excluded.reviewed_by,
612
- reviewed_at = excluded.reviewed_at,
613
- version = team_outcome_fragments.version + 1`,[T,J.outcomeId,J.id,J.section,J.sourceAgentId,J.sourceRunId??null,J.content,J.status,J.reviewedBy??null,J.reviewedAt?J.reviewedAt.toISOString():null])}markInProgressRunsInterrupted($,q){let Y=TY($),T=this.queryAll("SELECT run_id FROM team_runs WHERE team_name = ? AND status IN ('queued', 'running')",[Y]);if(T.length===0)return[];let X=X0();return this.run(`UPDATE team_runs SET status = 'interrupted', error = ?, ended_at = ?, version = version + 1
614
- WHERE team_name = ? AND status IN ('queued', 'running')`,[q,X,Y]),T.map((J)=>J.run_id)}handleTeamEvent($,q){this.appendTeamEvent($,q.type,q)}}var hC="# Workspace Configuration";function F3(){return`agent-team-${kC(5)}`}function E3($,q,Y,T,X,J,Q){let U=Y==="plan"?Z$.readonly:Z$.development,Z=b5(q,T,Y,X??f5);return N6({cwd:$,...U,...Z,enableSkills:!!J,executors:{...J?{skills:J}:{},...Q??{}}})}var V3="SKILL.md";function _C($){return OJ($).filter((q)=>!q.disabled).map((q)=>q.name.trim()).filter((q)=>q.length>0).sort((q,Y)=>q.localeCompare(Y))}function OJ($){return[...$.getSnapshot("skill").entries()].map(([Y,T])=>{let X=T.item;return{id:Y,name:X.name.trim(),description:X.description?.trim(),disabled:X.disabled===!0}})}function D3($){for(let q of D6($)){if(!PJ(q))continue;let Y=G3(q,V3);if(PJ(Y))return!0;try{let T=jC(q,{withFileTypes:!0});for(let X of T){if(!X.isDirectory())continue;if(PJ(G3(q,X.name,V3)))return!0}}catch{}}return!1}function gC($,q){let Y=q.trim().replace(/^\/+/,"").toLowerCase();if(!Y)return{error:"Missing skill name."};let T=$.getSnapshot("skill"),X=T.get(Y);if(X){let Z=X.item;if(Z.disabled===!0)return{error:`Skill "${Z.name}" is configured but disabled.`};return{id:Y,skill:Z}}let J=Y.includes(":")?Y.split(":").at(-1)??Y:Y,Q=[...T.entries()].filter(([Z])=>{if(Z===J)return!0;return Z.endsWith(`:${J}`)});if(Q.length===1){let[Z,K]=Q[0],A=K.item;if(A.disabled===!0)return{error:`Skill "${A.name}" is configured but disabled.`};return{id:Z,skill:A}}if(Q.length>1)return{error:`Skill "${q}" is ambiguous. Use one of: ${Q.map(([Z])=>Z).join(", ")}`};let U=_C($);return{error:U.length>0?`Skill "${q}" not found. Available skills: ${U.join(", ")}`:"No skills are currently available."}}function mC($,q){let Y=new Set,T=async(X,J)=>{await q;let Q=gC($,X);if("error"in Q)return Q.error;let{id:U,skill:Z}=Q;if(Y.has(U))return`Skill "${Z.name}" is already running.`;Y.add(U);try{let K=J?.trim(),A=K?`
615
- <command-args>${K}</command-args>`:"",W=Z.description?.trim()?`Description: ${Z.description.trim()}
616
-
617
- `:"";return`<command-name>${Z.name}</command-name>${A}
618
- <command-instructions>
619
- ${W}${Z.instructions}
620
- </command-instructions>`}finally{Y.delete(U)}};return Object.defineProperty(T,"configuredSkills",{get:()=>OJ($),enumerable:!0,configurable:!1}),T}function fC($,q){if(!$)return;for(let Y of $.getTeammateIds())try{$.shutdownTeammate(Y,q)}catch{}}function bC($){let q=$.lastIndexOf(hC);if(q<0)return;let Y=$.slice(q).trim();return Y.length>0?Y:void 0}function uC($){return{mode:$.mode==="plan"?"plan":"act",enableTools:$.enableTools!==!1,enableSpawnAgent:$.enableSpawnAgent!==!1,enableAgentTeams:$.enableAgentTeams!==!1,missionLogIntervalSteps:typeof $.missionLogIntervalSteps==="number"&&Number.isFinite($.missionLogIntervalSteps)?$.missionLogIntervalSteps:3,missionLogIntervalMs:typeof $.missionLogIntervalMs==="number"&&Number.isFinite($.missionLogIntervalMs)?$.missionLogIntervalMs:120000}}class Q9{build($){let{config:q,hooks:Y,extensions:T,logger:X,createSpawnTool:J,onTeamRestored:Q,userInstructionWatcher:U,defaultToolExecutors:Z}=$,K=$.onTeamEvent??(()=>{}),A=uC(q),W=[],G=q.teamName?.trim()||F3(),V=!1,F=Boolean(U),N=U,D=Promise.resolve(),z;if(!N&&A.enableTools&&D3(q.cwd))N=t8({skills:{workspacePath:q.cwd},rules:{workspacePath:q.cwd},workflows:{workspacePath:q.cwd}}),D=N.start().catch(()=>{});if(A.enableTools&&N&&(F||D3(q.cwd)||OJ(N).length>0))z=mC(N,D);if(A.enableTools)W.push(...E3(q.cwd,q.providerId,A.mode,q.modelId,q.toolRoutingRules,z,Z));let S,v=A.enableAgentTeams?new RJ:void 0;v?.init();let H=v?.loadRuntime(G),_=H?.state,y=H?.teammates??[],k=new Map(y.map((j)=>[j.agentId,j])),m=()=>{if(!A.enableAgentTeams)return;if(!S){if(S=new vC({teamName:G,leadAgentId:"lead",missionLogIntervalSteps:A.missionLogIntervalSteps,missionLogIntervalMs:A.missionLogIntervalMs,onTeamEvent:(j)=>{if(K(j),S&&v){if(j.type==="teammate_spawned"&&j.teammate?.rolePrompt){let M={agentId:j.agentId,rolePrompt:j.teammate.rolePrompt,modelId:j.teammate.modelId,maxIterations:j.teammate.maxIterations};k.set(M.agentId,M)}if(j.type==="teammate_shutdown")k.delete(j.agentId);v.handleTeamEvent(G,j),v.persistRuntime(G,S.exportState(),Array.from(k.values()))}}}),_)S.hydrateState(_),S.markStaleRunsInterrupted("runtime_recovered")}if(!V){if(!S)return;V=!0;let j=xC({runtime:S,leadAgentId:"lead",restoredFromPersistence:Boolean(_),restoredTeammates:y,createBaseTools:A.enableTools?()=>E3(q.cwd,q.providerId,A.mode,q.modelId,q.toolRoutingRules,z,Z):void 0,teammateRuntime:{providerId:q.providerId,modelId:q.modelId,cwd:q.cwd,apiKey:q.apiKey??"",baseUrl:q.baseUrl,headers:q.headers,providerConfig:q.providerConfig,knownModels:q.knownModels,thinking:q.thinking,clineWorkspaceMetadata:q.providerId==="cline"?bC(q.systemPrompt):void 0,maxIterations:q.maxIterations,hooks:Y,extensions:T??q.extensions,logger:X??q.logger}});if(j.restoredFromPersistence)Q?.();W.push(...j.tools)}return S};if(A.enableSpawnAgent&&J){let j=J();W.push({...j,execute:async(M,h0)=>{return m(),j.execute(M,h0)}})}if(A.enableAgentTeams)m();let C=S?()=>{let j=S;if(!j)return;let M=j.listTasks(),h0=M.some((L)=>L.status==="in_progress"||L.status==="pending"),O=j.listRuns({}),E=O.some((L)=>L.status==="running"||L.status==="queued");if(h0||E){let L=M.filter((d)=>d.status==="in_progress"||d.status==="pending").map((d)=>`${d.id} (${d.status}): ${d.title}`).join(", "),l=O.filter((d)=>d.status==="running"||d.status==="queued").map((d)=>`${d.id} (${d.status})`).join(", "),u=[];if(L)u.push(`Unfinished tasks: ${L}`);if(l)u.push(`Active runs: ${l}`);return`[SYSTEM] You still have team obligations. ${u.join(". ")}. Use team_run_task to delegate work, or team_complete_task to mark tasks done, or team_await_run / team_await_all_runs to wait for active runs. Do NOT stop until all tasks are completed.`}return}:void 0;return{tools:W,logger:X??q.logger,teamRuntime:S,completionGuard:C,shutdown:(j)=>{if(fC(S,j),!F)N?.stop()}}}}import{mkdir as dC,readFile as cC,unlink as LJ,writeFile as pC}from"node:fs/promises";import{join as I3}from"node:path";function lC($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function nC($){return new Promise((q)=>setTimeout(q,$))}async function iC($,q={}){let Y=q.approvalDir?.trim(),T=q.sessionId?.trim();if(!Y||!T)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await dC(Y,{recursive:!0});let X=lC(`${$.toolCallId}`),J=I3(Y,`${T}.request.${X}.json`),Q=I3(Y,`${T}.decision.${X}.json`),U=q.nowIso??(()=>new Date().toISOString());await pC(J,`${JSON.stringify({requestId:X,sessionId:T,createdAt:U(),toolCallId:$.toolCallId,toolName:$.toolName,input:$.input,iteration:$.iteration,agentId:$.agentId,conversationId:$.conversationId},null,2)}
621
- `,"utf8");let Z=q.timeoutMs??300000,K=q.pollIntervalMs??200,A=Date.now();while(Date.now()-A<Z){try{let W=await cC(Q,"utf8"),G=JSON.parse(W),V={approved:G.approved===!0,reason:typeof G.reason==="string"?G.reason:void 0};try{await LJ(Q)}catch{}try{await LJ(J)}catch{}return V}catch{}await nC(K)}try{await LJ(J)}catch{}return{approved:!1,reason:"Tool approval request timed out"}}function rC($){return $.disabled!==!0}function N3($){return[...$.getSnapshot("workflow").entries()].map(([Y,T])=>({id:Y,workflow:T.item})).filter(({workflow:Y})=>rC(Y)).map(({id:Y,workflow:T})=>({id:Y,name:T.name,instructions:T.instructions})).sort((Y,T)=>Y.name.localeCompare(T.name))}function aC($,q){if(!$.startsWith("/")||$.length<2)return $;let Y=$.match(/^\/(\S+)/);if(!Y)return $;let T=Y[1];if(!T)return $;let X=T.length+1,J=$.slice(X),Q=N3(q).find((U)=>U.name===T);return Q?`${Q.instructions}${J}`:$}import{existsSync as uJ,readFileSync as dJ}from"node:fs";import{readFile as fy,stat as by}from"node:fs/promises";import{homedir as uy}from"node:os";import{isAbsolute as dy,join as O6,resolve as cy}from"node:path";import{Agent as py,createSpawnAgentTool as ly}from"@clinebot/agents";import{nanoid as ny}from"nanoid";import{spawn as oC}from"node:child_process";import{appendFileSync as sC,readFileSync as tC}from"node:fs";function Z9($){if(!$||typeof $!=="object")return{};let q={};for(let[Y,T]of Object.entries($))q[Y]=typeof T==="string"?T:JSON.stringify(T);return q}function U9($,q,Y){let T=Y instanceof Error?`: ${Y.message}`:"",X=`${q}${T}`;if($?.warn){$.warn(X);return}console.warn(X)}function H3($,q){if(!q)return $;if(!$)return{...q};let Y=[$.context,q.context].filter((X)=>typeof X==="string"&&X.length>0).join(`
622
- `),T=[...$.appendMessages??[],...q.appendMessages??[]];return{cancel:$.cancel===!0||q.cancel===!0?!0:void 0,review:$.review===!0||q.review===!0?!0:void 0,context:Y||void 0,overrideInput:q.overrideInput!==void 0?q.overrideInput:$.overrideInput,systemPrompt:q.systemPrompt!==void 0?q.systemPrompt:$.systemPrompt,appendMessages:T.length>0?T:void 0}}function eC($){if(!$||typeof $!=="object")return;let q=$,Y=typeof q.context==="string"?q.context:typeof q.contextModification==="string"?q.contextModification:typeof q.errorMessage==="string"?q.errorMessage:void 0;return{cancel:typeof q.cancel==="boolean"?q.cancel:void 0,review:typeof q.review==="boolean"?q.review:void 0,context:Y,overrideInput:Object.hasOwn(q,"overrideInput")?q.overrideInput:void 0}}function z3($){let q=String($??"").toLowerCase();return q.includes("cancel")||q.includes("abort")||q.includes("interrupt")}function $y($){B5($)}function s0($,q){let Y=process.env.CLINE_USER_ID?.trim()||process.env.USER?.trim()||"unknown",T={rootSessionId:q.rootSessionId||$.conversationId,hookLogPath:q.hookLogPath};return{clineVersion:process.env.CLINE_VERSION?.trim()||"",timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:T,workspaceRoots:q.workspacePath?[q.workspacePath]:[],userId:Y,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function qy($){let q=$.trim();if(!q)return{};let T=q.split(`
623
- `).map((J)=>J.trim()).filter(Boolean).filter((J)=>J.startsWith("HOOK_CONTROL\t")).map((J)=>J.slice(13)),X=T.length>0?T[T.length-1]:q;try{return{parsedJson:JSON.parse(X)}}catch(J){return{parseError:J instanceof Error?J.message:"Failed to parse hook stdout JSON"}}}async function M3($,q){if(q.command.length===0)throw Error("runHookCommand requires non-empty command");let Y=oC(q.command[0],q.command.slice(1),{cwd:q.cwd,env:q.env,stdio:q.detached?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:q.detached}),T=JSON.stringify($);if(!Y.stdin)throw Error("hook command failed to create stdin");if(Y.stdin.write(T),Y.stdin.end(),q.detached){await new Promise((Z,K)=>{Y.once("error",K),Y.once("spawn",()=>Z())}),Y.unref();return}if(!Y.stdout||!Y.stderr)throw Error("hook command failed to create stdout/stderr");let X="",J="",Q=!1,U;return Y.stdout.on("data",(Z)=>{X+=Z.toString()}),Y.stderr.on("data",(Z)=>{J+=Z.toString()}),await new Promise((Z,K)=>{if(Y.once("error",K),(q.timeoutMs??0)>0)U=setTimeout(()=>{Q=!0,Y.kill("SIGKILL")},q.timeoutMs);Y.once("close",(A)=>{if(U)clearTimeout(U);let{parsedJson:W,parseError:G}=qy(X);Z({exitCode:A,stdout:X,stderr:J,parsedJson:W,parseError:G,timedOut:Q})})})}function Yy($){try{let Y=tC($,"utf8").split(/\r?\n/,1)[0]?.trim();if(!Y?.startsWith("#!"))return;let T=Y.slice(2).trim();if(!T)return;let X=T.split(/\s+/).filter(Boolean);return X.length>0?X:void 0}catch{return}}function Ty($){let q=Yy($);if(q&&q.length>0)return[...q,$];let Y=$.toLowerCase();if(Y.endsWith(".sh")||Y.endsWith(".bash")||Y.endsWith(".zsh"))return["/bin/bash",$];if(Y.endsWith(".js")||Y.endsWith(".mjs")||Y.endsWith(".cjs"))return["node",$];if(Y.endsWith(".ts")||Y.endsWith(".mts")||Y.endsWith(".cts"))return["bun","run",$];return["/bin/bash",$]}function Xy($){let q={};for(let Y of d8($)){if(!Y.hookEventName)continue;let T=q[Y.hookEventName]??[];T.push(Ty(Y.path)),q[Y.hookEventName]=T}return q}async function Jy($){let q;for(let Y of $.commands){let T=Y.join(" ");try{let X=await M3($.payload,{command:Y,cwd:$.cwd,env:process.env,detached:!1,timeoutMs:$.timeoutMs});if(X?.timedOut){U9($.logger,`hook command timed out: ${T}`);continue}if(X?.parseError){U9($.logger,`hook command returned invalid JSON control output: ${T} (${X.parseError})`);continue}q=H3(q,eC(X?.parsedJson))}catch(X){U9($.logger,`hook command failed: ${T}`,X)}}return q}function XY($){for(let q of $.commands){let Y=q.join(" ");M3($.payload,{command:q,cwd:$.cwd,env:process.env,detached:!0}).catch((T)=>{U9($.logger,`hook command failed: ${Y}`,T)})}}function B3($){let q={cwd:$.workspacePath,workspacePath:$.workspacePath,hookLogPath:$.hookLogPath,rootSessionId:$.rootSessionId},Y=(T)=>{let X=`${JSON.stringify({ts:new Date().toISOString(),...T})}
624
- `;$y($.hookLogPath),sC($.hookLogPath,X,"utf8")};return{onRunStart:async(T)=>{Y({...s0(T,q),hookName:"agent_start",taskStart:{taskMetadata:{}}}),Y({...s0(T,q),hookName:"prompt_submit",userPromptSubmit:{prompt:T.userMessage,attachments:[]}});return},onToolCallStart:async(T)=>{Y({...s0(T,q),hookName:"tool_call",iteration:T.iteration,tool_call:{id:T.call.id,name:T.call.name,input:T.call.input},preToolUse:{toolName:T.call.name,parameters:Z9(T.call.input)}});return},onToolCallEnd:async(T)=>{Y({...s0(T,q),hookName:"tool_result",iteration:T.iteration,tool_result:T.record,postToolUse:{toolName:T.record.name,parameters:Z9(T.record.input),result:typeof T.record.output==="string"?T.record.output:JSON.stringify(T.record.output),success:!T.record.error,executionTimeMs:T.record.durationMs}});return},onTurnEnd:async(T)=>{Y({...s0(T,q),hookName:"agent_end",iteration:T.iteration,turn:T.turn,taskComplete:{taskMetadata:{}}});return},onSessionShutdown:async(T)=>{if(z3(T.reason))Y({...s0(T,q),hookName:"agent_abort",reason:T.reason,taskCancel:{taskMetadata:{}}});Y({...s0(T,q),hookName:"session_shutdown",reason:T.reason});return}}}function R3($){let q=Xy($.workspacePath);if(!Object.values(q).some((Z)=>(Z?.length??0)>0))return;let T=async(Z)=>{let K=q.agent_start??[];if(K.length>0)XY({commands:K,cwd:$.cwd,logger:$.logger,payload:{...s0(Z,$),hookName:"agent_start",taskStart:{taskMetadata:{}}}});let A=q.prompt_submit??[];if(A.length>0)XY({commands:A,cwd:$.cwd,logger:$.logger,payload:{...s0(Z,$),hookName:"prompt_submit",userPromptSubmit:{prompt:Z.userMessage,attachments:[]}}})},X=async(Z)=>{let K=q.tool_call??[];if(K.length===0)return;return Jy({commands:K,cwd:$.cwd,logger:$.logger,timeoutMs:$.toolCallTimeoutMs??120000,payload:{...s0(Z,$),hookName:"tool_call",iteration:Z.iteration,tool_call:{id:Z.call.id,name:Z.call.name,input:Z.call.input},preToolUse:{toolName:Z.call.name,parameters:Z9(Z.call.input)}}})},J=async(Z)=>{let K=q.tool_result??[];if(K.length===0)return;XY({commands:K,cwd:$.cwd,logger:$.logger,payload:{...s0(Z,$),hookName:"tool_result",iteration:Z.iteration,tool_result:Z.record,postToolUse:{toolName:Z.record.name,parameters:Z9(Z.record.input),result:typeof Z.record.output==="string"?Z.record.output:JSON.stringify(Z.record.output),success:!Z.record.error,executionTimeMs:Z.record.durationMs}}})},Q=async(Z)=>{let K=q.agent_end??[];if(K.length===0)return;XY({commands:K,cwd:$.cwd,logger:$.logger,payload:{...s0(Z,$),hookName:"agent_end",iteration:Z.iteration,turn:Z.turn,taskComplete:{taskMetadata:{}}}})},U=async(Z)=>{if(z3(Z.reason)){let A=q.agent_abort??[];if(A.length>0)XY({commands:A,cwd:$.cwd,logger:$.logger,payload:{...s0(Z,$),hookName:"agent_abort",reason:Z.reason,taskCancel:{taskMetadata:{}}}})}let K=q.session_shutdown??[];if(K.length===0)return;XY({commands:K,cwd:$.cwd,logger:$.logger,payload:{...s0(Z,$),hookName:"session_shutdown",reason:Z.reason}})};return{onRunStart:async(Z)=>{await T(Z);return},onToolCallStart:async(Z)=>X(Z),onToolCallEnd:async(Z)=>{await J(Z);return},onTurnEnd:async(Z)=>{await Q(Z);return},onSessionShutdown:async(Z)=>{await U(Z);return}}}function i1($,q){let Y=$.map((T)=>T[q]).filter((T)=>typeof T==="function");if(Y.length===0)return;return async(T)=>{let X;for(let J of Y){let Q=await J(T);X=H3(X,Q)}return X}}function P3($){let q=$.filter((Y)=>Y!==void 0);if(q.length===0)return;return{onRunStart:i1(q,"onRunStart"),onRunEnd:i1(q,"onRunEnd"),onIterationStart:i1(q,"onIterationStart"),onIterationEnd:i1(q,"onIterationEnd"),onTurnStart:i1(q,"onTurnStart"),onTurnEnd:i1(q,"onTurnEnd"),onToolCallStart:i1(q,"onToolCallStart"),onToolCallEnd:i1(q,"onToolCallEnd"),onSessionShutdown:i1(q,"onSessionShutdown"),onError:i1(q,"onError")}}import{existsSync as S3,mkdirSync as Ny,readFileSync as Hy,writeFileSync as zy}from"node:fs";import{basename as C3,dirname as yJ}from"node:path";import{providers as wJ}from"@clinebot/llms";import{z as k$}from"zod";var O3=wJ.ProviderSettingsSchema,B6=wJ.toProviderConfig,Qy=k$.object({settings:wJ.ProviderSettingsSchema,updatedAt:k$.string().datetime(),tokenSource:k$.enum(["manual","oauth","migration"]).default("manual")}),SJ=k$.object({version:k$.literal(1),lastUsedProvider:k$.string().min(1).optional(),providers:k$.record(k$.string(),Qy)});function R6(){return{version:1,providers:{}}}import{existsSync as Uy,readFileSync as Zy}from"node:fs";import{join as L3}from"node:path";import{models as Ky,providers as Ay}from"@clinebot/llms";function p($){let q=$?.trim();return q?q:void 0}function w3($){if(!Uy($))return;try{let q=Zy($,"utf8"),Y=JSON.parse(q);if(Y&&typeof Y==="object"&&!Array.isArray(Y))return Y}catch{}return}function Wy($){let q=$.dataDir??C1(),Y=$.globalStatePath??L3(q,"globalState.json"),T=$.secretsPath??L3(q,"secrets.json"),X=w3(Y),J=w3(T);if(!X&&!J)return;return{globalState:X??{},secrets:J??{}}}function Gy($,q,Y,T){let X=Y==="plan"?"planMode":"actMode",J=q===T?p(Y==="plan"?$.planModeApiModelId:$.actModeApiModelId):void 0,U={openrouter:`${X}OpenRouterModelId`,cline:`${X}ClineModelId`,openai:`${X}OpenAiModelId`,ollama:`${X}OllamaModelId`,lmstudio:`${X}LmStudioModelId`,litellm:`${X}LiteLlmModelId`,requesty:`${X}RequestyModelId`,together:`${X}TogetherModelId`,fireworks:`${X}FireworksModelId`,sapaicore:`${X}SapAiCoreModelId`,groq:`${X}GroqModelId`,baseten:`${X}BasetenModelId`,huggingface:`${X}HuggingFaceModelId`,"huawei-cloud-maas":`${X}HuaweiCloudMaasModelId`,oca:`${X}OcaModelId`,aihubmix:`${X}AihubmixModelId`,hicap:`${X}HicapModelId`,nousResearch:`${X}NousResearchModelId`,"vercel-ai-gateway":`${X}VercelAiGatewayModelId`}[q];return(U?p(typeof $[U]==="string"?$[U]:void 0):void 0)??J}function Ey($,q,Y){let T=Y==="plan"?$.planModeReasoningEffort:$.actModeReasoningEffort,X=Y==="plan"?$.geminiPlanModeThinkingLevel:$.geminiActModeThinkingLevel,J=Y==="plan"?$.planModeThinkingBudgetTokens:$.actModeThinkingBudgetTokens,Q=(q==="gemini"?X:void 0)??T,U=Q==="none"||Q==="low"||Q==="medium"||Q==="high"?Q:void 0,Z=typeof J==="number"&&Number.isInteger(J)&&J>0?J:void 0;if(!U&&Z===void 0)return;return{...U?{effort:U}:{},...Z!==void 0?{budgetTokens:Z}:{}}}function Vy($){let q=$["openai-codex-oauth-credentials"];if(!q)return;try{let Y=JSON.parse(q),T=p(Y.access_token),X=p(Y.refresh_token),J=p(Y.accountId);if(!T&&!X&&!J)return;return{...T?{apiKey:T}:{},auth:{...T?{accessToken:T}:{},...X?{refreshToken:X}:{},...J?{accountId:J}:{}}}}catch{return}}function Dy($){let q=Ky.getGeneratedModelsForProvider($);return Object.keys(q)[0]??void 0}function Fy($,q,Y,T){let X=p(T==="plan"?q.planModeApiProvider:q.actModeApiProvider),J=Gy(q,$,T,X)??Dy($),Q=Ey(q,$,T),U=typeof q.requestTimeoutMs==="number"&&Number.isInteger(q.requestTimeoutMs)&&q.requestTimeoutMs>0?q.requestTimeoutMs:void 0,Z={anthropic:Y.apiKey,cline:Y.clineApiKey,openai:Y.openAiApiKey,"openai-native":Y.openAiNativeApiKey,openrouter:Y.openRouterApiKey,bedrock:Y.awsBedrockApiKey,gemini:Y.geminiApiKey,ollama:Y.ollamaApiKey,deepseek:Y.deepSeekApiKey,requesty:Y.requestyApiKey,together:Y.togetherApiKey,fireworks:Y.fireworksApiKey,qwen:Y.qwenApiKey,doubao:Y.doubaoApiKey,mistral:Y.mistralApiKey,litellm:Y.liteLlmApiKey,asksage:Y.asksageApiKey,xai:Y.xaiApiKey,moonshot:Y.moonshotApiKey,zai:Y.zaiApiKey,huggingface:Y.huggingFaceApiKey,nebius:Y.nebiusApiKey,sambanova:Y.sambanovaApiKey,cerebras:Y.cerebrasApiKey,groq:Y.groqApiKey,"huawei-cloud-maas":Y.huaweiCloudMaasApiKey,baseten:Y.basetenApiKey,"vercel-ai-gateway":Y.vercelAiGatewayApiKey,dify:Y.difyApiKey,minimax:Y.minimaxApiKey,hicap:Y.hicapApiKey,aihubmix:Y.aihubmixApiKey,nousResearch:Y.nousResearchApiKey,oca:Y.ocaApiKey,sapaicore:Y.sapAiCoreClientId},K={};if($==="openai-codex")Object.assign(K,Vy(Y));if($==="cline"){let D=p(Y["cline:clineAccountId"]??Y.clineAccountId);if(D)K.auth={...K.auth??{},accountId:D}}if($==="openai"&&q.openAiHeaders)K.headers=q.openAiHeaders;if($==="bedrock")K.aws={accessKey:p(Y.awsAccessKey),secretKey:p(Y.awsSecretKey),sessionToken:p(Y.awsSessionToken),region:p(q.awsRegion),authentication:q.awsAuthentication,profile:q.awsUseProfile?p(q.awsProfile):void 0,usePromptCache:q.awsBedrockUsePromptCache,useCrossRegionInference:q.awsUseCrossRegionInference,useGlobalInference:q.awsUseGlobalInference,endpoint:p(q.awsBedrockEndpoint),customModelBaseId:p(T==="plan"?q.planModeAwsBedrockCustomModelBaseId:q.actModeAwsBedrockCustomModelBaseId)};if($==="vertex")K.gcp={projectId:p(q.vertexProjectId),region:p(q.vertexRegion)};if($==="openai"&&(q.azureApiVersion||q.azureIdentity!==void 0))K.azure={apiVersion:p(q.azureApiVersion),useIdentity:q.azureIdentity};if($==="sapaicore")K.sap={clientId:p(Y.sapAiCoreClientId),clientSecret:p(Y.sapAiCoreClientSecret),tokenUrl:p(q.sapAiCoreTokenUrl),resourceGroup:p(q.sapAiResourceGroup),deploymentId:p(T==="plan"?q.planModeSapAiCoreDeploymentId:q.actModeSapAiCoreDeploymentId),useOrchestrationMode:q.sapAiCoreUseOrchestrationMode};if($==="oca"){K.oca={mode:q.ocaMode};let D=p(Y.ocaRefreshToken);if(D)K.auth={...K.auth??{},refreshToken:D}}if($==="qwen")K.apiLine=q.qwenApiLine;if($==="moonshot")K.apiLine=q.moonshotApiLine;if($==="zai")K.apiLine=q.zaiApiLine;if($==="minimax")K.apiLine=q.minimaxApiLine;let A={anthropic:q.anthropicBaseUrl,openai:q.openAiBaseUrl,ollama:q.ollamaBaseUrl,lmstudio:q.lmStudioBaseUrl,litellm:q.liteLlmBaseUrl,gemini:q.geminiBaseUrl,requesty:q.requestyBaseUrl,asksage:q.asksageApiUrl,dify:q.difyBaseUrl,oca:q.ocaBaseUrl,aihubmix:q.aihubmixBaseUrl,sapaicore:q.sapAiCoreBaseUrl},W=p(Z[$]),G=p(A[$]),V={provider:$,...W?{apiKey:W}:{},...J?{model:J}:{},...G?{baseUrl:G}:{},...Q?{reasoning:Q}:{},...U?{timeout:U}:{},...K},F=Ay.ProviderSettingsSchema.safeParse(V);if(!F.success)return;return Object.keys(V).filter((D)=>D!=="provider").length>0?F.data:void 0}function Iy($,q){let Y=new Set;for(let T of[$.actModeApiProvider,$.planModeApiProvider]){let X=p(T);if(X)Y.add(X)}if(p(q.apiKey))Y.add("anthropic");if(p(q.openRouterApiKey))Y.add("openrouter");if(p(q.openAiApiKey))Y.add("openai");if(p(q.openAiNativeApiKey))Y.add("openai-native");if(p(q["openai-codex-oauth-credentials"]))Y.add("openai-codex");if(p(q.geminiApiKey))Y.add("gemini");if(p(q.ollamaApiKey))Y.add("ollama");if(p(q.awsAccessKey)||p(q.awsBedrockApiKey))Y.add("bedrock");if(p($.vertexProjectId)||p($.vertexRegion))Y.add("vertex");if(p(q.clineApiKey))Y.add("cline");if(p(q.ocaApiKey))Y.add("oca");return Y}function CJ($){let q=$.providerSettingsManager.read(),Y=Wy($);if(!Y)return{migrated:!1,providerCount:Object.keys(q.providers).length,lastUsedProvider:q.lastUsedProvider};let{globalState:T,secrets:X}=Y,J=T.mode==="plan"?"plan":"act",Q=Iy(T,X),U=R6();U.providers={...q.providers},U.lastUsedProvider=q.lastUsedProvider;let Z=new Date().toISOString(),K=0;for(let W of Q){if(U.providers[W])continue;let G=Fy(W,T,X,J);if(!G)continue;U.providers[W]={settings:G,updatedAt:Z,tokenSource:"migration"},K+=1}if(K===0)return{migrated:!1,providerCount:Object.keys(q.providers).length,lastUsedProvider:q.lastUsedProvider};let A=p(J==="plan"?T.planModeApiProvider:T.actModeApiProvider);return U.lastUsedProvider=q.lastUsedProvider??(A&&U.providers[A]?A:Object.keys(U.providers)[0]),$.providerSettingsManager.write(U),{migrated:!0,providerCount:Object.keys(U.providers).length,lastUsedProvider:U.lastUsedProvider}}function My(){return new Date().toISOString()}function By($){if(C3($)!=="providers.json")return;let q=yJ($);if(C3(q)!=="settings")return;return yJ(q)}class JY{filePath;dataDir;constructor($={}){if(this.filePath=$.filePath??V5(),this.dataDir=$.dataDir??By(this.filePath),this.dataDir||!$.filePath)CJ({providerSettingsManager:this,dataDir:this.dataDir})}getFilePath(){return this.filePath}read(){if(!S3(this.filePath))return R6();try{let $=Hy(this.filePath,"utf8"),q=JSON.parse($),Y=SJ.safeParse(q);if(Y.success)return Y.data}catch{}return R6()}write($){let q=SJ.parse($),Y=yJ(this.filePath);if(!S3(Y))Ny(Y,{recursive:!0});zy(this.filePath,`${JSON.stringify(q,null,2)}
625
- `,"utf8")}saveProviderSettings($,q={}){let Y=O3.parse($),T=this.read(),X=Y.provider,J=q.setLastUsed!==!1,Q=T.providers[X],U=q.tokenSource??Q?.tokenSource??"manual",Z={...T,providers:{...T.providers,[X]:{settings:Y,updatedAt:My(),tokenSource:U}},lastUsedProvider:J?X:T.lastUsedProvider};return this.write(Z),Z}getProviderSettings($){return this.read().providers[$]?.settings}getLastUsedProviderSettings(){let $=this.read(),q=$.lastUsedProvider;if(!q)return;return $.providers[q]?.settings}getProviderConfig($){let q=this.getProviderSettings($);if(!q)return;return B6(q)}getLastUsedProviderConfig(){let $=this.getLastUsedProviderSettings();if(!$)return;return B6($)}}function r1(){return new Date().toISOString()}function y3($,q){if(q<=0)return 0;return Math.round($/q*100)}function Ry($,q){let Y=new Set;for(let X of q)if(X.status==="reviewed")Y.add(`${X.outcomeId}:${X.section}`);let T=new Set;for(let X of $){if(X.status==="finalized")continue;for(let J of X.requiredSections)if(!Y.has(`${X.id}:${J}`))T.add(`${X.id}:${J}`)}return[...T].sort((X,J)=>X.localeCompare(J))}function jJ($,q){let Y={idle:0,running:0,stopped:0},T={pending:0,in_progress:0,blocked:0,completed:0},X={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},J={draft:0,in_review:0,finalized:0},Q={draft:0,reviewed:0,rejected:0},U=0,Z=0;for(let D of q.members)if(Y[D.status]+=1,D.role==="lead")U+=1;else Z+=1;let K=[],A=[],W=q.tasks.filter((D)=>D.status==="completed").length,G=new Map(q.tasks.map((D)=>[D.id,D]));for(let D of q.tasks){if(T[D.status]+=1,D.status==="blocked"){K.push(D.id);continue}if(D.status!=="pending")continue;if(D.dependsOn.every((S)=>{return G.get(S)?.status==="completed"}))A.push(D.id)}let V=[],F,N=0;for(let D of q.runs){if(X[D.status]+=1,D.status==="queued"||D.status==="running")V.push(D.id);let z=D.startedAt.getTime();if(z>=N)N=z,F=D.id}for(let D of q.outcomes)J[D.status]+=1;for(let D of q.outcomeFragments)Q[D.status]+=1;return{teamName:$,updatedAt:r1(),members:{total:q.members.length,byStatus:Y,leadCount:U,teammateCount:Z},tasks:{total:q.tasks.length,byStatus:T,blockedTaskIds:K,readyTaskIds:A,completionPct:y3(W,q.tasks.length)},runs:{total:q.runs.length,byStatus:X,activeRunIds:V,latestRunId:F},outcomes:{total:q.outcomes.length,byStatus:J,finalizedPct:y3(J.finalized,q.outcomes.length),missingRequiredSections:Ry(q.outcomes,q.outcomeFragments)},fragments:{total:q.outcomeFragments.length,byStatus:Q}}}function vJ($){let{event:q}=$;switch(q.type){case"team_task_updated":return{teamName:$.teamName,sessionId:$.sessionId,eventType:q.type,ts:r1(),taskId:q.task.id,agentId:q.task.assignee??q.task.createdBy};case"run_queued":case"run_started":case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":return{teamName:$.teamName,sessionId:$.sessionId,eventType:q.type,ts:r1(),runId:q.run.id,taskId:q.run.taskId,agentId:q.run.agentId,message:q.run.error};case"run_progress":return{teamName:$.teamName,sessionId:$.sessionId,eventType:q.type,ts:r1(),runId:q.run.id,taskId:q.run.taskId,agentId:q.run.agentId,message:q.message};case"outcome_created":case"outcome_finalized":return{teamName:$.teamName,sessionId:$.sessionId,eventType:q.type,ts:r1(),outcomeId:q.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:$.teamName,sessionId:$.sessionId,eventType:q.type,ts:r1(),outcomeId:q.fragment.outcomeId,fragmentId:q.fragment.id,agentId:q.fragment.sourceAgentId};case"team_message":return{teamName:$.teamName,sessionId:$.sessionId,eventType:q.type,ts:r1(),taskId:q.message.taskId,agentId:q.message.fromAgentId,message:q.message.subject};case"team_mission_log":return{teamName:$.teamName,sessionId:$.sessionId,eventType:q.type,ts:r1(),taskId:q.entry.taskId,agentId:q.entry.agentId,message:q.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:$.teamName,sessionId:$.sessionId,eventType:q.type,ts:r1(),agentId:q.agentId}}return{teamName:$.teamName,sessionId:$.sessionId,eventType:q.type,ts:r1()}}var xJ=H9,P6;((Q)=>{Q.CLI="cli";Q.CLI_SUBAGENT="cli-subagent";Q.CORE="core";Q.CORE_SUBAGENT="core-subagent";Q.DESKTOP="desktop";Q.DESKTOP_CHAT="desktop-chat"})(P6||={});var Py="https://api.cline.bot",kJ="workos:",Oy=["cline","oca","openai-codex"];function Ly($){return Oy.includes($)}function wy($,q){if($==="cline")return`${kJ}${q}`;return q}function Sy($,q){if($==="cline"&&q.toLowerCase().startsWith(kJ))return q.slice(kJ.length);return q}function Cy($){let Y=D1($)?.exp;if(typeof Y==="number"&&Y>0)return Y*1000;return null}function yy($,q){let Y=$.auth?.expiresAt;if(typeof Y==="number"&&Number.isFinite(Y)&&Y>0)return Y;let T=Cy(q);if(T)return T;return Date.now()-1}function jy($,q){let Y=q.auth?.accessToken?.trim(),T=q.auth?.refreshToken?.trim();if(!Y||!T)return null;let X=Sy($,Y);if(!X)return null;return{access:X,refresh:T,expires:yy(q,X),accountId:q.auth?.accountId}}function vy($,q){let Y=$?.expiresAt,T=q?.expiresAt;return $?.accessToken===q?.accessToken&&$?.refreshToken===q?.refreshToken&&$?.accountId===q?.accountId&&Y===T}class K9 extends Error{providerId;constructor($){super(`OAuth credentials for provider "${$}" are no longer valid. Re-run authentication for this provider.`);this.name="OAuthReauthRequiredError",this.providerId=$}}class hJ{providerSettingsManager;refreshInFlight=new Map;constructor($){this.providerSettingsManager=$?.providerSettingsManager??new JY}async resolveProviderApiKey($){if(!Ly($.providerId))return null;return this.resolveWithSingleFlight($.providerId,$.forceRefresh)}async resolveWithSingleFlight($,q=!1){let Y=this.refreshInFlight.get($);if(Y)return Y;let T=this.resolveProviderApiKeyInternal($,q).catch((X)=>{throw X}).finally(()=>{this.refreshInFlight.delete($)});return this.refreshInFlight.set($,T),T}async resolveProviderApiKeyInternal($,q){let Y=this.providerSettingsManager.getProviderSettings($);if(!Y)return null;let T=jy($,Y);if(!T)return null;let X=await this.resolveCredentials($,Y,T,q);if(!X)throw new K9($);let J=wy($,X.access),Q={...Y.auth??{},accessToken:J,refreshToken:X.refresh,accountId:X.accountId};Q.expiresAt=X.expires;let U={...Y,auth:Q},Z=!vy(Y.auth,U.auth);if(Z)this.providerSettingsManager.saveProviderSettings(U,{setLastUsed:!1,tokenSource:"oauth"});return{providerId:$,apiKey:J,accountId:X.accountId,refreshed:Z}}async resolveCredentials($,q,Y,T){if($==="cline")return EJ(Y,{apiBaseUrl:q.baseUrl?.trim()||Py},{forceRefresh:T});if($==="oca")return NJ(Y,{forceRefresh:T},{mode:q.oca?.mode});return DJ(Y,{forceRefresh:T})}}import{existsSync as _J,mkdirSync as xy,readdirSync as ky,rmdirSync as hy,unlinkSync as _y}from"node:fs";import{dirname as j3,join as h$}from"node:path";function G0(){return new Date().toISOString()}function A$($){if(!$||!_J($))return;try{_y($)}catch{}}class gJ{ensureSessionsDir;constructor($){this.ensureSessionsDir=$}sessionArtifactsDir($){return h$(this.ensureSessionsDir(),$)}ensureSessionArtifactsDir($){let q=this.sessionArtifactsDir($);if(!_J(q))xy(q,{recursive:!0});return q}sessionTranscriptPath($){return h$(this.ensureSessionArtifactsDir($),`${$}.log`)}sessionHookPath($){return h$(this.ensureSessionArtifactsDir($),`${$}.hooks.jsonl`)}sessionMessagesPath($){return h$(this.ensureSessionArtifactsDir($),`${$}.messages.json`)}sessionManifestPath($,q=!0){let Y=q?this.ensureSessionArtifactsDir($):this.sessionArtifactsDir($);return h$(Y,`${$}.json`)}removeSessionDirIfEmpty($){let q=this.sessionArtifactsDir($),Y=this.ensureSessionsDir();while(q.startsWith(Y)&&q!==Y){if(!_J(q)){q=j3(q);continue}try{if(ky(q).length>0)break;hy(q)}catch{break}q=j3(q)}}subagentArtifactPaths($,q,Y){let T=this.ensureSessionArtifactsDir($);return{transcriptPath:h$(T,`${$}.log`),hookPath:h$(T,`${$}.hooks.jsonl`),messagesPath:h$(T,`${$}.messages.json`)}}}import{z as E0}from"zod";var gy=E0.enum(xJ),QY=E0.object({version:E0.literal(1),session_id:E0.string().min(1),source:E0.enum(P6),pid:E0.number().int(),started_at:E0.string().min(1),ended_at:E0.string().min(1).optional(),exit_code:E0.number().int().nullable().optional(),status:gy,interactive:E0.boolean(),provider:E0.string().min(1),model:E0.string().min(1),cwd:E0.string().min(1),workspace_root:E0.string().min(1),team_name:E0.string().min(1).optional(),enable_tools:E0.boolean(),enable_spawn:E0.boolean(),enable_teams:E0.boolean(),prompt:E0.string().optional(),metadata:E0.record(E0.string(),E0.unknown()).optional(),messages_path:E0.string().min(1).optional()});var my="# Workspace Configuration";function v3($){let q=$.lastIndexOf(my);if(q<0)return;let Y=$.slice(q).trim();return Y.length>0?Y:void 0}function x3($){if(!$)return!1;return Object.values($).some((q)=>typeof q==="function")}function k3($,q){let Y=[...$??[],...q??[]];if(Y.length===0)return;let T=[],X=new Set;for(let J of Y){if(X.has(J.name))continue;X.add(J.name),T.push(J)}return T}function h3($){return JSON.stringify($,(q,Y)=>{if(Y instanceof Error)return{name:Y.name,message:Y.message,stack:Y.stack};return Y})}function _3($,q){let Y=$.map((U)=>({...U})),T=[...Y].reverse().findIndex((U)=>U.role==="assistant");if(T===-1)return Y;let X=Y.length-1-T,J=Y[X],Q=q.usage;return Y[X]={...J,providerId:J.providerId??q.model.provider,modelId:J.modelId??q.model.id,modelInfo:J.modelInfo??{id:q.model.id,provider:q.model.provider},metrics:{...J.metrics??{},inputTokens:Q.inputTokens,outputTokens:Q.outputTokens,cacheReadTokens:Q.cacheReadTokens,cacheWriteTokens:Q.cacheWriteTokens,cost:Q.totalCost},ts:J.ts??q.endedAt.getTime()},Y}function mJ($){let q=typeof $.metadata_json==="string"&&$.metadata_json.trim().length>0?(()=>{try{let Y=JSON.parse($.metadata_json);if(Y&&typeof Y==="object"&&!Array.isArray(Y))return Y}catch{}return})():void 0;return{sessionId:$.session_id,source:$.source,pid:$.pid,startedAt:$.started_at,endedAt:$.ended_at??null,exitCode:$.exit_code??null,status:$.status,interactive:$.interactive===1,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspace_root,teamName:$.team_name??void 0,enableTools:$.enable_tools===1,enableSpawn:$.enable_spawn===1,enableTeams:$.enable_teams===1,parentSessionId:$.parent_session_id??void 0,parentAgentId:$.parent_agent_id??void 0,agentId:$.agent_id??void 0,conversationId:$.conversation_id??void 0,isSubagent:$.is_subagent===1,prompt:$.prompt??void 0,metadata:q,transcriptPath:$.transcript_path,hookPath:$.hook_path,messagesPath:$.messages_path??void 0,updatedAt:$.updated_at??G0()}}function fJ(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function bJ($,q){return{inputTokens:$.inputTokens+Math.max(0,q.inputTokens??0),outputTokens:$.outputTokens+Math.max(0,q.outputTokens??0),cacheReadTokens:$.cacheReadTokens+Math.max(0,q.cacheReadTokens??0),cacheWriteTokens:$.cacheWriteTokens+Math.max(0,q.cacheWriteTokens??0),totalCost:$.totalCost+Math.max(0,q.totalCost??0)}}var g3=5000,iy=20480000;async function ry($){let q=await by($);if(!q.isFile())throw Error("Path is not a file");if(q.size>iy)throw Error("File is too large to read into context.");let Y=await fy($,"utf8");if(Y.includes("\x00"))throw Error("Cannot read binary file into context.");return Y}class A9{sessionService;runtimeBuilder;createAgentInstance;defaultToolExecutors;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultRequestToolApproval;listeners=new Set;sessions=new Map;usageBySession=new Map;constructor($){let q=uy();if(q)E5(q);this.sessionService=$.sessionService,this.runtimeBuilder=$.runtimeBuilder??new Q9,this.createAgentInstance=$.createAgent??((Y)=>new py(Y)),this.defaultToolExecutors=$.defaultToolExecutors,this.defaultToolPolicies=$.toolPolicies,this.providerSettingsManager=$.providerSettingsManager??new JY,this.oauthTokenManager=$.oauthTokenManager??new hJ({providerSettingsManager:this.providerSettingsManager}),this.defaultRequestToolApproval=$.requestToolApproval}resolveStoredProviderSettings($){let q=this.providerSettingsManager.getProviderSettings($);if(q)return q;return{provider:$}}buildResolvedProviderConfig($){let q=this.resolveStoredProviderSettings($.providerId),Y={...q,provider:$.providerId,model:$.modelId,apiKey:$.apiKey??q.apiKey,baseUrl:$.baseUrl??q.baseUrl,headers:$.headers??q.headers,reasoning:typeof $.thinking==="boolean"||typeof $.reasoningEffort==="string"?{...q.reasoning??{},...typeof $.thinking==="boolean"?{enabled:$.thinking}:{},...typeof $.reasoningEffort==="string"?{effort:$.reasoningEffort}:{}}:q.reasoning},T=B6(Y);if($.knownModels)T.knownModels=$.knownModels;return T}async start($){let q=$.source??"cli",Y=G0(),T=$.config.sessionId?.trim()??"",X=T.length>0?T:`${Date.now()}_${ny(5)}`;this.usageBySession.set(X,fJ());let J=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!J)throw Error("session service method not available: ensureSessionsDir");let Q=O6(J,X),U=O6(Q,`${X}.log`),Z=O6(Q,`${X}.hooks.jsonl`),K=O6(Q,`${X}.messages.json`),A=O6(Q,`${X}.json`),W=QY.parse({version:1,session_id:X,source:q,pid:process.pid,started_at:Y,status:"running",interactive:$.interactive===!0,provider:$.config.providerId,model:$.config.modelId,cwd:$.config.cwd,workspace_root:$.config.workspaceRoot??$.config.cwd,team_name:$.config.teamName,enable_tools:$.config.enableTools,enable_spawn:$.config.enableSpawnAgent,enable_teams:$.config.enableAgentTeams,prompt:$.prompt?.trim()||void 0,messages_path:K}),G=R3({cwd:$.config.cwd,workspacePath:$.config.workspaceRoot??$.config.cwd,rootSessionId:X,hookLogPath:Z,logger:$.config.logger}),V=x3($.config.hooks)?void 0:B3({hookLogPath:Z,rootSessionId:X,workspacePath:$.config.workspaceRoot??$.config.cwd}),F=P3([$.config.hooks,G,V]),N=await n8({pluginPaths:$.config.pluginPaths,workspacePath:$.config.workspaceRoot??$.config.cwd,cwd:$.config.cwd}),D=k3($.config.extensions,N.extensions),z={...$.config,hooks:F,extensions:D},S=this.buildResolvedProviderConfig(z),v={...z,providerConfig:S},H=this.runtimeBuilder.build({config:v,hooks:F,extensions:D,logger:v.logger,onTeamEvent:(C)=>{this.handleTeamEvent(X,C),v.onTeamEvent?.(C)},createSpawnTool:()=>this.createSpawnTool(v,X),onTeamRestored:$.onTeamRestored,userInstructionWatcher:$.userInstructionWatcher,defaultToolExecutors:$.defaultToolExecutors??this.defaultToolExecutors}),_=[...H.tools,...v.extraTools??[]],y=this.createAgentInstance({providerId:S.providerId,modelId:S.modelId,apiKey:S.apiKey,baseUrl:S.baseUrl,headers:S.headers,knownModels:S.knownModels,providerConfig:S,thinking:v.thinking,reasoningEffort:v.reasoningEffort??S.reasoningEffort,systemPrompt:v.systemPrompt,maxIterations:v.maxIterations,maxConsecutiveMistakes:v.maxConsecutiveMistakes,tools:_,hooks:F,extensions:D,hookErrorMode:v.hookErrorMode,initialMessages:$.initialMessages,userFileContentLoader:ry,toolPolicies:$.toolPolicies??this.defaultToolPolicies,requestToolApproval:$.requestToolApproval??this.defaultRequestToolApproval,onConsecutiveMistakeLimitReached:v.onConsecutiveMistakeLimitReached,completionGuard:H.completionGuard,logger:H.logger??v.logger,onEvent:(C)=>{let j=this.sessions.get(X);if(C.type==="usage"&&j?.turnUsageBaseline)this.usageBySession.set(X,bJ(j.turnUsageBaseline,{inputTokens:C.totalInputTokens,outputTokens:C.totalOutputTokens,totalCost:C.totalCost}));this.emit({type:"agent_event",payload:{sessionId:X,event:C}}),this.emit({type:"chunk",payload:{sessionId:X,stream:"agent",chunk:h3(C),ts:Date.now()}})}}),k={sessionId:X,config:v,source:q,startedAt:Y,pendingPrompt:W.prompt,runtime:H,agent:y,started:!1,aborting:!1,interactive:$.interactive===!0,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pluginSandboxShutdown:N.shutdown};this.sessions.set(k.sessionId,k),this.emitStatus(k.sessionId,"running");let m;try{if($.prompt?.trim()){if(m=await this.runTurn(k,{prompt:$.prompt,userImages:$.userImages,userFiles:$.userFiles}),!k.interactive)await this.finalizeSingleRun(k,m.finishReason)}}catch(C){throw await this.failSession(k),C}return{sessionId:X,manifest:W,manifestPath:A,transcriptPath:U,hookPath:Z,messagesPath:K,result:m}}async send($){let q=this.sessions.get($.sessionId);if(!q)throw Error(`session not found: ${$.sessionId}`);try{let Y=await this.runTurn(q,{prompt:$.prompt,userImages:$.userImages,userFiles:$.userFiles});if(!q.interactive)await this.finalizeSingleRun(q,Y.finishReason);return Y}catch(Y){throw await this.failSession(q),Y}}async getAccumulatedUsage($){let q=this.usageBySession.get($);if(!q)return;return{...q}}async abort($){let q=this.sessions.get($);if(!q)return;q.aborting=!0,q.agent.abort()}async stop($){let q=this.sessions.get($);if(!q)return;await this.shutdownSession(q,{status:"cancelled",exitCode:null,shutdownReason:"session_stop",endReason:"stopped"})}async dispose($="session_manager_dispose"){let q=[...this.sessions.values()];if(q.length===0)return;await Promise.allSettled(q.map(async(Y)=>{await this.shutdownSession(Y,{status:"cancelled",exitCode:null,shutdownReason:$,endReason:"disposed"})})),this.usageBySession.clear()}async get($){let q=await this.getRow($);return q?mJ(q):void 0}async list($=200){return(await this.listRows($)).map((Y)=>mJ(Y))}async delete($){if(this.sessions.has($))await this.stop($);let q=await this.invoke("deleteSession",$);if(q.deleted)this.usageBySession.delete($);return q.deleted}async readTranscript($,q){let Y=await this.getRow($);if(!Y?.transcript_path||!uJ(Y.transcript_path))return"";let T=dJ(Y.transcript_path,"utf8");if(typeof q==="number"&&Number.isFinite(q))return T.slice(-Math.max(0,Math.floor(q)));return T}async readMessages($){let Y=(await this.getRow($))?.messages_path?.trim();if(!Y||!uJ(Y))return[];try{let T=dJ(Y,"utf8");if(!T.trim())return[];let X=JSON.parse(T);return Array.isArray(X)?X:Array.isArray(X.messages)?X.messages??[]:[]}catch{return[]}}async readHooks($,q=200){let Y=await this.getRow($);if(!Y?.hook_path||!uJ(Y.hook_path))return[];return dJ(Y.hook_path,"utf8").split(`
626
- `).map((J)=>J.trim()).filter((J)=>J.length>0).slice(-Math.max(1,Math.floor(q))).map((J)=>{try{return JSON.parse(J)}catch{return{raw:J}}})}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}async runTurn($,q){let Y=await this.prepareTurnInput($,q),T=Y.prompt.trim();if(!T)throw Error("prompt cannot be empty");await this.ensureSessionPersisted($),await this.syncOAuthCredentials($);let X=await this.executeAgentTurn($,T,Y.userImages,Y.userFiles);while(this.shouldAutoContinueTeamRuns($,X.finishReason)){let J=await this.waitForTeamRunUpdates($);if(J.length===0)break;let Q=this.buildTeamRunContinuationPrompt($,J);X=await this.executeAgentTurn($,Q)}return X}async executeAgentTurn($,q,Y,T){let X=$.started||$.agent.getMessages().length>0,J=$.agent.getMessages(),Q=this.usageBySession.get($.sessionId)??fJ();$.turnUsageBaseline=Q;try{let U=X?await this.runWithAuthRetry($,()=>$.agent.continue(q,Y,T),J):await this.runWithAuthRetry($,()=>$.agent.run(q,Y,T),J);$.started=!0;let Z=_3(U.messages,U);return this.usageBySession.set($.sessionId,bJ(Q,U.usage)),await this.invoke("persistSessionMessages",$.sessionId,Z,$.config.systemPrompt),U}catch(U){throw await this.invoke("persistSessionMessages",$.sessionId,$.agent.getMessages(),$.config.systemPrompt),U}finally{$.turnUsageBaseline=void 0}}async prepareTurnInput($,q){let Y=$.config.workspaceRoot??$.config.cwd,T=F9(q.prompt).trim();if(!T)return{prompt:"",userImages:q.userImages,userFiles:this.resolveAbsoluteFilePaths($.config.cwd,q.userFiles)};let X=await k8(T,Y),J=v6(X.prompt,$.config.mode==="plan"?"plan":"act"),Q=this.resolveAbsoluteFilePaths($.config.cwd,q.userFiles),U=this.resolveAbsoluteFilePaths(Y,X.matchedFiles),Z=Array.from(new Set([...Q,...U]));return{prompt:J,userImages:q.userImages,userFiles:Z.length>0?Z:void 0}}resolveAbsoluteFilePaths($,q){if(!q||q.length===0)return[];let Y=q.map((T)=>T.trim()).filter((T)=>T.length>0).map((T)=>dy(T)?T:cy($,T));return Array.from(new Set(Y))}async ensureSessionPersisted($){if($.artifacts)return;$.artifacts=await this.invoke("createRootSessionWithArtifacts",{sessionId:$.sessionId,source:$.source,pid:process.pid,interactive:$.interactive,provider:$.config.providerId,model:$.config.modelId,cwd:$.config.cwd,workspaceRoot:$.config.workspaceRoot??$.config.cwd,teamName:$.config.teamName,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,prompt:$.pendingPrompt,startedAt:$.startedAt})}async finalizeSingleRun($,q){if(this.hasPendingTeamRunWork($))return;if(q==="aborted"||$.aborting)await this.shutdownSession($,{status:"cancelled",exitCode:null,shutdownReason:"session_complete",endReason:q});else await this.shutdownSession($,{status:"completed",exitCode:0,shutdownReason:"session_complete",endReason:q})}async failSession($){await this.shutdownSession($,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession($,q){if(this.notifyTeamRunWaiters($),$.artifacts)await this.updateStatus($,q.status,q.exitCode);if($.artifacts)await $.agent.shutdown(q.shutdownReason);if(await Promise.resolve($.runtime.shutdown(q.shutdownReason)),$.pluginSandboxShutdown)await $.pluginSandboxShutdown();this.sessions.delete($.sessionId),this.emit({type:"ended",payload:{sessionId:$.sessionId,reason:q.endReason,ts:Date.now()}})}async updateStatus($,q,Y){if(!$.artifacts)return;let T=await this.invoke("updateSessionStatus",$.sessionId,q,Y);if(!T.updated)return;$.artifacts.manifest.status=q,$.artifacts.manifest.ended_at=T.endedAt??G0(),$.artifacts.manifest.exit_code=typeof Y==="number"?Y:null,await this.invoke("writeSessionManifest",$.artifacts.manifestPath,$.artifacts.manifest),this.emitStatus($.sessionId,q)}emitStatus($,q){this.emit({type:"status",payload:{sessionId:$,status:q}})}async listRows($){let q=Math.max(1,Math.floor($));return this.invoke("listSessions",Math.min(q,g3))}async getRow($){let q=$.trim();if(!q)return;return(await this.listRows(g3)).find((T)=>T.session_id===q)}createSpawnTool($,q){let Y=()=>{if(!$.enableTools)return[];let X=$.mode==="plan"?Z$.readonly:Z$.development;return N6({cwd:$.cwd,...X,executors:this.defaultToolExecutors})},T=()=>{let X=Y();if($.enableSpawnAgent)X.push(this.createSpawnTool($,q));return X};return ly({providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,apiKey:$.apiKey,baseUrl:$.baseUrl,providerConfig:$.providerConfig,knownModels:$.knownModels,clineWorkspaceMetadata:$.providerId==="cline"?v3($.systemPrompt):void 0,createSubAgentTools:T,hooks:$.hooks,extensions:$.extensions,toolPolicies:this.defaultToolPolicies,requestToolApproval:this.defaultRequestToolApproval,logger:$.logger,onSubAgentStart:(X)=>{this.invokeOptional("handleSubAgentStart",q,X)},onSubAgentEnd:(X)=>{this.invokeOptional("handleSubAgentEnd",q,X)}})}async handleTeamEvent($,q){let Y=this.sessions.get($);if(Y)switch(q.type){case"run_queued":case"run_started":Y.activeTeamRunIds.add(q.run.id);break;case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":{let X;if(q.type==="run_failed")X=q.run.error;else if(q.type==="run_cancelled")X=q.run.error??q.reason;else if(q.type==="run_interrupted")X=q.run.error??q.reason;Y.activeTeamRunIds.delete(q.run.id),Y.pendingTeamRunUpdates.push({runId:q.run.id,agentId:q.run.agentId,taskId:q.run.taskId,status:q.type.replace("run_",""),error:X,iterations:q.run.result?.iterations}),this.notifyTeamRunWaiters(Y);break}default:break}switch(q.type){case"task_start":await this.invokeOptional("onTeamTaskStart",$,q.agentId,q.message);break;case"task_end":if(q.error){await this.invokeOptional("onTeamTaskEnd",$,q.agentId,"failed",`[error] ${q.error.message}`,q.messages);break}if(q.result?.finishReason==="aborted"){await this.invokeOptional("onTeamTaskEnd",$,q.agentId,"cancelled","[done] aborted",q.result.messages);break}await this.invokeOptional("onTeamTaskEnd",$,q.agentId,"completed",`[done] ${q.result?.finishReason??"completed"}`,q.result?.messages);break;default:break}if(!Y?.runtime.teamRuntime)return;let T=Y.config.teamName?.trim()||"team";this.emit({type:"team_progress",payload:{sessionId:$,teamName:T,lifecycle:vJ({teamName:T,sessionId:$,event:q}),summary:jJ(T,Y.runtime.teamRuntime.exportState())}})}hasPendingTeamRunWork($){return $.activeTeamRunIds.size>0||$.pendingTeamRunUpdates.length>0}shouldAutoContinueTeamRuns($,q){if($.aborting||q==="aborted"||q==="error")return!1;if(!$.config.enableAgentTeams)return!1;return this.hasPendingTeamRunWork($)}notifyTeamRunWaiters($){let q=$.teamRunWaiters.splice(0);for(let Y of q)Y()}async waitForTeamRunUpdates($){while(!0){if($.aborting)return[];if($.pendingTeamRunUpdates.length>0){let q=[...$.pendingTeamRunUpdates];return $.pendingTeamRunUpdates.length=0,q}if($.activeTeamRunIds.size===0)return[];await new Promise((q)=>{$.teamRunWaiters.push(q)})}}buildTeamRunContinuationPrompt($,q){let Y=q.map((J)=>{let Q=`- ${J.runId} (${J.agentId}) -> ${J.status}`,U=J.taskId?` task=${J.taskId}`:"",Z=typeof J.iterations==="number"?` iterations=${J.iterations}`:"",K=J.error?` error=${J.error}`:"";return`${Q}${U}${Z}${K}`}),T=$.activeTeamRunIds.size,X=T>0?`There are still ${T} teammate run(s) in progress. Continue coordination and decide whether to wait for more updates.`:"No teammate runs are currently in progress. Continue coordination using these updates.";return v6(`System-delivered teammate async run updates:
627
- ${Y.join(`
628
- `)}
629
-
630
- ${X}`,$.config.mode==="plan"?"plan":"act")}emit($){for(let q of this.listeners)q($)}async invoke($,...q){let Y=this.sessionService[$];if(typeof Y!=="function")throw Error(`session service method not available: ${$}`);return Promise.resolve(Y.apply(this.sessionService,q))}async invokeOptional($,...q){let Y=this.sessionService[$];if(typeof Y!=="function")return;await Promise.resolve(Y.apply(this.sessionService,q))}async invokeOptionalValue($,...q){let Y=this.sessionService[$];if(typeof Y!=="function")return;return await Promise.resolve(Y.apply(this.sessionService,q))}async runWithAuthRetry($,q,Y){try{return await q()}catch(T){if(!this.isLikelyAuthError(T,$.config.providerId))throw T;return await this.syncOAuthCredentials($,{forceRefresh:!0}),$.agent.restore(Y),q()}}isLikelyAuthError($,q){if(q!=="cline"&&q!=="oca"&&q!=="openai-codex")return!1;let Y=$ instanceof Error?$.message.toLowerCase():String($);return Y.includes("401")||Y.includes("403")||Y.includes("unauthorized")||Y.includes("forbidden")||Y.includes("invalid token")||Y.includes("expired token")||Y.includes("authentication")}async syncOAuthCredentials($,q){let Y=null;try{Y=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId,forceRefresh:q?.forceRefresh})}catch(X){if(X instanceof K9)throw Error(`OAuth session for "${X.providerId}" requires re-authentication. Run "clite auth ${X.providerId}" and retry.`);throw X}if(!Y?.apiKey)return;if($.config.apiKey===Y.apiKey)return;$.config.apiKey=Y.apiKey,$.agent.updateConnection?.({apiKey:Y.apiKey}),$.runtime.teamRuntime?.updateTeammateConnections({apiKey:Y.apiKey})}}import{existsSync as $j,mkdirSync as qj}from"node:fs";import{appendFileSync as m3,existsSync as oy,readFileSync as sy,writeFileSync as w6}from"node:fs";import{nanoid as ty}from"nanoid";import{z as lJ}from"zod";import{nanoid as ay}from"nanoid";function L6($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function W9($,q){let Y=L6($),T=L6(q),X=`${Y}__${T}`;return X.length>180?X.slice(0,180):X}function cJ($,q){let Y=L6($),T=L6(q);return`${Y}__teamtask__${T}__${ay(6)}`}function pJ($){switch($.hookName){case"agent_end":return"completed";case"session_shutdown":{let q=String($.reason??"").toLowerCase();if(q.includes("cancel")||q.includes("abort")||q.includes("interrupt"))return"cancelled";if(q.includes("fail")||q.includes("error"))return"failed";return"completed"}default:return"running"}}var f3="cli_subagent",ey=lJ.object({task:lJ.string().optional(),systemPrompt:lJ.string().optional()}).passthrough();function b3($){if(!$||Object.keys($).length===0)return null;return JSON.stringify($)}class S6{adapter;teamTaskSessionsByAgent=new Map;artifacts;constructor($){this.adapter=$;this.artifacts=new gJ(()=>this.ensureSessionsDir())}teamTaskQueueKey($,q){return`${$}::${q}`}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}sessionTranscriptPath($){return this.artifacts.sessionTranscriptPath($)}sessionHookPath($){return this.artifacts.sessionHookPath($)}sessionMessagesPath($){return this.artifacts.sessionMessagesPath($)}sessionManifestPath($,q=!0){return this.artifacts.sessionManifestPath($,q)}async sessionPathFromStore($,q){let T=(await this.adapter.getSession($))?.[q];return typeof T==="string"&&T.trim().length>0?T:void 0}activeTeamTaskSessionId($,q){let Y=this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey($,q));if(!Y||Y.length===0)return;return Y[Y.length-1]}subagentArtifactPaths($,q,Y,T){return this.artifacts.subagentArtifactPaths(q,T,this.activeTeamTaskSessionId($,Y))}writeSessionManifestFile($,q){let Y=QY.parse(q);w6($,`${JSON.stringify(Y,null,2)}
631
- `,"utf8")}createRootSessionId(){return`${Date.now()}_${ty(5)}`}async createRootSessionWithArtifacts($){let q=$.startedAt??G0(),Y=$.sessionId.trim(),T=Y.length>0?Y:this.createRootSessionId(),X=this.sessionTranscriptPath(T),J=this.sessionHookPath(T),Q=this.sessionMessagesPath(T),U=this.sessionManifestPath(T),Z=QY.parse({version:1,session_id:T,source:$.source,pid:$.pid,started_at:q,status:"running",interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName,enable_tools:$.enableTools,enable_spawn:$.enableSpawn,enable_teams:$.enableTeams,prompt:$.prompt?.trim()||void 0,metadata:$.metadata,messages_path:Q});return await this.adapter.upsertSession({session_id:T,source:$.source,pid:$.pid,started_at:q,ended_at:null,exit_code:null,status:"running",status_lock:0,interactive:$.interactive?1:0,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName??null,enable_tools:$.enableTools?1:0,enable_spawn:$.enableSpawn?1:0,enable_teams:$.enableTeams?1:0,parent_session_id:null,parent_agent_id:null,agent_id:null,conversation_id:null,is_subagent:0,prompt:Z.prompt??null,metadata_json:b3(Z.metadata),transcript_path:X,hook_path:J,messages_path:Q,updated_at:G0()}),w6(Q,`${JSON.stringify({version:1,updated_at:q,messages:[]},null,2)}
632
- `,"utf8"),this.writeSessionManifestFile(U,Z),{manifestPath:U,transcriptPath:X,hookPath:J,messagesPath:Q,manifest:Z}}writeSessionManifest($,q){this.writeSessionManifestFile($,q)}async updateSessionStatus($,q,Y){for(let T=0;T<4;T++){let X=await this.adapter.getSession($);if(!X||typeof X.status_lock!=="number")return{updated:!1};let J=G0();if((await this.adapter.updateSession({sessionId:$,status:q,endedAt:J,exitCode:typeof Y==="number"?Y:null,expectedStatusLock:X.status_lock})).updated){if(q==="cancelled")await this.applyStatusToRunningChildSessions($,"cancelled");return{updated:!0,endedAt:J}}}return{updated:!1}}async updateSession($){for(let q=0;q<4;q++){let Y=await this.adapter.getSession($.sessionId);if(!Y||typeof Y.status_lock!=="number")return{updated:!1};if(!(await this.adapter.updateSession({sessionId:$.sessionId,prompt:$.prompt,metadataJson:$.metadata===void 0?void 0:b3($.metadata),expectedStatusLock:Y.status_lock})).updated)continue;let X=this.sessionManifestPath($.sessionId,!1);if(oy(X))try{let J=QY.parse(JSON.parse(sy(X,"utf8")));if($.prompt!==void 0)J.prompt=$.prompt??void 0;if($.metadata!==void 0)J.metadata=$.metadata??void 0;this.writeSessionManifestFile(X,J)}catch{}return{updated:!0}}return{updated:!1}}async queueSpawnRequest($){if($.hookName!=="tool_call"||$.parent_agent_id!==null)return;if($.tool_call?.name!=="spawn_agent")return;let q=x6($.sessionContext);if(!q)return;let Y=ey.safeParse($.tool_call.input),T=Y.success?Y.data.task:void 0,X=Y.success?Y.data.systemPrompt:void 0;await this.adapter.enqueueSpawnRequest({rootSessionId:q,parentAgentId:$.agent_id,task:T,systemPrompt:X})}async readRootSession($){return await this.adapter.getSession($)??null}async claimQueuedSpawnTask($,q){return await this.adapter.claimSpawnRequest($,q)}async upsertSubagentSession($){let q=$.rootSessionId;if(!q)return;let Y=await this.readRootSession(q);if(!Y)return;let T=W9(q,$.agentId),X=await this.adapter.getSession(T),J=G0(),Q=this.subagentArtifactPaths(q,T,$.parentAgentId,$.agentId),U=$.prompt??X?.prompt??void 0;if(!U)U=await this.claimQueuedSpawnTask(q,$.parentAgentId)??`Subagent run by ${$.parentAgentId}`;if(!X)return await this.adapter.upsertSession({session_id:T,source:f3,pid:process.ppid,started_at:J,ended_at:null,exit_code:null,status:"running",status_lock:0,interactive:0,provider:Y.provider,model:Y.model,cwd:Y.cwd,workspace_root:Y.workspace_root,team_name:Y.team_name??null,enable_tools:Y.enable_tools,enable_spawn:Y.enable_spawn,enable_teams:Y.enable_teams,parent_session_id:q,parent_agent_id:$.parentAgentId,agent_id:$.agentId,conversation_id:$.conversationId,is_subagent:1,prompt:U,metadata_json:null,transcript_path:Q.transcriptPath,hook_path:Q.hookPath,messages_path:Q.messagesPath,updated_at:J}),w6(Q.messagesPath,`${JSON.stringify({version:1,updated_at:J,messages:[]},null,2)}
633
- `,"utf8"),T;return await this.adapter.updateSession({sessionId:T,setRunning:!0,parentSessionId:q,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:X.prompt??U??null,expectedStatusLock:X.status_lock}),T}async upsertSubagentSessionFromHook($){if(!$.parent_agent_id)return;let q=x6($.sessionContext);if(!q)return;if($.hookName==="session_shutdown"){let Y=W9(q,$.agent_id);return await this.adapter.getSession(Y)?Y:void 0}return await this.upsertSubagentSession({agentId:$.agent_id,parentAgentId:$.parent_agent_id,conversationId:$.taskId,rootSessionId:q})}async appendSubagentHookAudit($,q){let Y=`${JSON.stringify({ts:G0(),...q})}
634
- `,T=await this.sessionPathFromStore($,"hook_path")??this.sessionHookPath($);m3(T,Y,"utf8")}async appendSubagentTranscriptLine($,q){if(!q.trim())return;let Y=await this.sessionPathFromStore($,"transcript_path")??this.sessionTranscriptPath($);m3(Y,`${q}
635
- `,"utf8")}async persistSessionMessages($,q,Y){let T=await this.sessionPathFromStore($,"messages_path")??this.sessionMessagesPath($),X={version:1,updated_at:G0(),messages:q};if(Y!==void 0&&Y!=="")X.systemPrompt=Y;w6(T,`${JSON.stringify(X,null,2)}
636
- `,"utf8")}async applySubagentStatus($,q){await this.applySubagentStatusBySessionId($,pJ(q))}async applySubagentStatusBySessionId($,q){let Y=await this.adapter.getSession($);if(!Y||typeof Y.status_lock!=="number")return;let T=G0(),X=q==="running"?null:T,J=q==="failed"?1:0;await this.adapter.updateSession({sessionId:$,status:q,endedAt:X,exitCode:q==="running"?null:J,expectedStatusLock:Y.status_lock})}async applyStatusToRunningChildSessions($,q){if(!$)return;let Y=await this.adapter.listSessions({limit:2000,parentSessionId:$,status:"running"});for(let T of Y)await this.applySubagentStatusBySessionId(T.session_id,q)}async createTeamTaskSubSession($,q,Y){let T=await this.readRootSession($);if(!T)return;let X=cJ($,q),J=G0(),Q=this.sessionTranscriptPath(X),U=this.sessionHookPath(X),Z=this.sessionMessagesPath(X);return await this.adapter.upsertSession({session_id:X,source:f3,pid:process.ppid,started_at:J,ended_at:null,exit_code:null,status:"running",status_lock:0,interactive:0,provider:T.provider,model:T.model,cwd:T.cwd,workspace_root:T.workspace_root,team_name:T.team_name??null,enable_tools:T.enable_tools,enable_spawn:T.enable_spawn,enable_teams:T.enable_teams,parent_session_id:$,parent_agent_id:"lead",agent_id:q,conversation_id:null,is_subagent:1,prompt:Y||`Team task for ${q}`,metadata_json:null,transcript_path:Q,hook_path:U,messages_path:Z,updated_at:J}),w6(Z,`${JSON.stringify({version:1,updated_at:J,messages:[]},null,2)}
637
- `,"utf8"),await this.appendSubagentTranscriptLine(X,`[start] ${Y}`),X}async onTeamTaskStart($,q,Y){let T=await this.createTeamTaskSubSession($,q,Y);if(!T)return;let X=this.teamTaskQueueKey($,q),J=this.teamTaskSessionsByAgent.get(X)??[];J.push(T),this.teamTaskSessionsByAgent.set(X,J)}async onTeamTaskEnd($,q,Y,T,X){let J=this.teamTaskQueueKey($,q),Q=this.teamTaskSessionsByAgent.get(J);if(!Q||Q.length===0)return;let U=Q.shift();if(Q.length===0)this.teamTaskSessionsByAgent.delete(J);else this.teamTaskSessionsByAgent.set(J,Q);if(!U)return;if(X)await this.persistSessionMessages(U,X);await this.appendSubagentTranscriptLine(U,T??`[done] ${Y}`),await this.applySubagentStatusBySessionId(U,Y)}async handleSubAgentStart($,q){let Y=await this.upsertSubagentSession({agentId:q.subAgentId,parentAgentId:q.parentAgentId,conversationId:q.conversationId,prompt:q.input.task,rootSessionId:$});if(!Y)return;await this.appendSubagentTranscriptLine(Y,`[start] ${q.input.task}`),await this.applySubagentStatusBySessionId(Y,"running")}async handleSubAgentEnd($,q){let Y=await this.upsertSubagentSession({agentId:q.subAgentId,parentAgentId:q.parentAgentId,conversationId:q.conversationId,prompt:q.input.task,rootSessionId:$});if(!Y)return;if(q.error){await this.appendSubagentTranscriptLine(Y,`[error] ${q.error.message}`),await this.applySubagentStatusBySessionId(Y,"failed");return}if(await this.appendSubagentTranscriptLine(Y,`[done] ${q.result?.finishReason??"completed"}`),q.result?.finishReason==="aborted"){await this.applySubagentStatusBySessionId(Y,"cancelled");return}await this.applySubagentStatusBySessionId(Y,"completed")}isPidAlive($){if(!Number.isFinite($)||$<=0)return!1;try{return process.kill(Math.floor($),0),!0}catch(q){return typeof q==="object"&&q!==null&&"code"in q&&q.code==="EPERM"}}async listSessions($=200){let q=Math.max(1,Math.floor($)),Y=Math.min(q*5,2000),T=await this.adapter.listSessions({limit:Y}),X=T.filter((J)=>J.status==="running"&&!this.isPidAlive(J.pid));if(X.length>0){for(let J of X)await this.updateSessionStatus(J.session_id,"failed",1);T=await this.adapter.listSessions({limit:Y})}return T.slice(0,q)}async deleteSession($){let q=$.trim();if(!q)throw Error("session id is required");let Y=await this.adapter.getSession(q);if(!Y)return{deleted:!1};if(await this.adapter.deleteSession(q,!1),!Y.is_subagent){let T=await this.adapter.listSessions({limit:2000,parentSessionId:q});await this.adapter.deleteSession(q,!0);for(let X of T)A$(X.transcript_path),A$(X.hook_path),A$(X.messages_path),A$(this.sessionManifestPath(X.session_id,!1)),this.artifacts.removeSessionDirIfEmpty(X.session_id)}return A$(Y.transcript_path),A$(Y.hook_path),A$(Y.messages_path),A$(this.sessionManifestPath(q,!1)),this.artifacts.removeSessionDirIfEmpty(q),{deleted:!0}}}function u3($){return{session_id:$.sessionId,source:$.source,pid:$.pid,started_at:$.startedAt,ended_at:$.endedAt??null,exit_code:$.exitCode??null,status:$.status,status_lock:$.statusLock,interactive:$.interactive?1:0,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName??null,enable_tools:$.enableTools?1:0,enable_spawn:$.enableSpawn?1:0,enable_teams:$.enableTeams?1:0,parent_session_id:$.parentSessionId??null,parent_agent_id:$.parentAgentId??null,agent_id:$.agentId??null,conversation_id:$.conversationId??null,is_subagent:$.isSubagent?1:0,prompt:$.prompt??null,metadata_json:$.metadata?JSON.stringify($.metadata):null,transcript_path:$.transcriptPath,hook_path:$.hookPath,messages_path:$.messagesPath??null,updated_at:$.updatedAt}}function Yj($){return{sessionId:$.session_id,source:$.source,pid:$.pid,startedAt:$.started_at,endedAt:$.ended_at??null,exitCode:$.exit_code??null,status:$.status,statusLock:$.status_lock??0,interactive:$.interactive===1,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspace_root,teamName:$.team_name??void 0,enableTools:$.enable_tools===1,enableSpawn:$.enable_spawn===1,enableTeams:$.enable_teams===1,parentSessionId:$.parent_session_id??void 0,parentAgentId:$.parent_agent_id??void 0,agentId:$.agent_id??void 0,conversationId:$.conversation_id??void 0,isSubagent:$.is_subagent===1,prompt:$.prompt??void 0,metadata:(()=>{if(!$.metadata_json)return;try{let q=JSON.parse($.metadata_json);if(q&&typeof q==="object"&&!Array.isArray(q))return q}catch{}return})(),transcriptPath:$.transcript_path,hookPath:$.hook_path,messagesPath:$.messages_path??void 0,updatedAt:$.updated_at??G0()}}class d3{client;constructor($){this.client=$}ensureSessionsDir(){return""}async upsertSession($){await this.client.upsertSession(Yj($))}async getSession($){let q=await this.client.getSession($);return q?u3(q):void 0}async listSessions($){return(await this.client.listSessions($)).map((Y)=>u3(Y))}async updateSession($){return await this.client.updateSession({sessionId:$.sessionId,status:$.status,endedAt:$.endedAt,exitCode:$.exitCode,prompt:$.prompt,metadata:$.metadataJson===void 0?void 0:$.metadataJson?JSON.parse($.metadataJson):null,parentSessionId:$.parentSessionId,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,expectedStatusLock:$.expectedStatusLock,setRunning:$.setRunning})}async deleteSession($,q){return await this.client.deleteSession($,q)}async enqueueSpawnRequest($){await this.client.enqueueSpawnRequest($)}async claimSpawnRequest($,q){return await this.client.claimSpawnRequest($,q)}}class G9 extends S6{sessionsDirPath;client;constructor($){let q=new F6({address:$.address?.trim()||"127.0.0.1:4317"});super(new d3(q));this.sessionsDirPath=$.sessionsDir,this.client=q}ensureSessionsDir(){if(!$j(this.sessionsDirPath))qj(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}close(){this.client.close()}}import{spawn as Uj}from"node:child_process";import{existsSync as n3,mkdirSync as Zj,readFileSync as Kj,writeFileSync as Aj}from"node:fs";import{resolve as i3}from"node:path";import{nanoid as Wj}from"nanoid";import{existsSync as Tj,mkdirSync as Xj}from"node:fs";import{join as Jj}from"node:path";function Qj(){return C$()}class UY{sessionsDirPath;db;constructor($={}){this.sessionsDirPath=$.sessionsDir??Qj()}init(){this.getRawDb()}ensureSessionsDir(){if(!Tj(this.sessionsDirPath))Xj(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return Jj(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let $=t$(this.sessionDbPath());return Q6($,{includeLegacyMigrations:!0}),this.db=$,$}run($,q=[]){return this.getRawDb().prepare($).run(...q)}queryOne($,q=[]){return this.getRawDb().prepare($).get(...q)??void 0}queryAll($,q=[]){return this.getRawDb().prepare($).all(...q)}create($){let q=X0();this.run(`INSERT OR REPLACE INTO sessions (
638
- session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
639
- provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
640
- parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
641
- metadata_json, transcript_path, hook_path, messages_path, updated_at
642
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,0,T1($.interactive),$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,T1($.enableTools),T1($.enableSpawn),T1($.enableTeams),$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,T1($.isSubagent),$.prompt??null,$.metadata?JSON.stringify($.metadata):null,$.transcriptPath??"",$.hookPath??"",$.messagesPath??null,q])}update($){let q=[],Y=[];if($.endedAt!==void 0)q.push("ended_at = ?"),Y.push($.endedAt);if($.exitCode!==void 0)q.push("exit_code = ?"),Y.push($.exitCode);if($.status!==void 0)q.push("status = ?"),Y.push($.status);if($.prompt!==void 0)q.push("prompt = ?"),Y.push($.prompt);if($.metadata!==void 0)q.push("metadata_json = ?"),Y.push($.metadata?JSON.stringify($.metadata):null);if($.parentSessionId!==void 0)q.push("parent_session_id = ?"),Y.push($.parentSessionId);if($.parentAgentId!==void 0)q.push("parent_agent_id = ?"),Y.push($.parentAgentId);if($.agentId!==void 0)q.push("agent_id = ?"),Y.push($.agentId);if($.conversationId!==void 0)q.push("conversation_id = ?"),Y.push($.conversationId);if(q.length===0)return;q.push("updated_at = ?"),Y.push(X0()),Y.push($.sessionId),this.run(`UPDATE sessions SET ${q.join(", ")} WHERE session_id = ?`,Y)}updateStatus($,q,Y){this.update({sessionId:$,status:q,endedAt:q==="running"?null:X0(),exitCode:q==="running"?null:Y??(q==="failed"?1:0)})}get($){let q=this.queryOne(`SELECT session_id, source, pid, started_at, ended_at, exit_code, status, interactive,
643
- provider, model, cwd, workspace_root, team_name,
644
- enable_tools, enable_spawn, enable_teams,
645
- parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent,
646
- prompt, metadata_json, transcript_path, hook_path, messages_path, updated_at
647
- FROM sessions WHERE session_id = ?`,[$]);if(!q)return;return{sessionId:f(q.session_id),source:f(q.source),pid:Number(q.pid??0),startedAt:f(q.started_at),endedAt:q.ended_at??null,exitCode:q.exit_code??null,status:f(q.status),interactive:X1(q.interactive),provider:f(q.provider),model:f(q.model),cwd:f(q.cwd),workspaceRoot:f(q.workspace_root),teamName:i(q.team_name),enableTools:X1(q.enable_tools),enableSpawn:X1(q.enable_spawn),enableTeams:X1(q.enable_teams),parentSessionId:i(q.parent_session_id),parentAgentId:i(q.parent_agent_id),agentId:i(q.agent_id),conversationId:i(q.conversation_id),isSubagent:X1(q.is_subagent),prompt:i(q.prompt),metadata:(()=>{let Y=i(q.metadata_json);if(!Y)return;try{let T=JSON.parse(Y);if(T&&typeof T==="object"&&!Array.isArray(T))return T}catch{}return})(),transcriptPath:i(q.transcript_path),hookPath:i(q.hook_path),messagesPath:i(q.messages_path),updatedAt:i(q.updated_at)??X0()}}list($=200){let q=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[$]),Y=[];for(let T of q){let X=this.get(f(T.session_id));if(X)Y.push(X)}return Y}delete($,q=!1){let Y=this.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(q)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return Y>0}}class c3{store;constructor($){this.store=$}ensureSessionsDir(){return this.store.ensureSessionsDir()}async upsertSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
648
- session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
649
- provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
650
- parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
651
- metadata_json, transcript_path, hook_path, messages_path, updated_at
652
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.session_id,$.source,$.pid,$.started_at,$.ended_at??null,$.exit_code??null,$.status,typeof $.status_lock==="number"?$.status_lock:0,$.interactive,$.provider,$.model,$.cwd,$.workspace_root,$.team_name??null,$.enable_tools,$.enable_spawn,$.enable_teams,$.parent_session_id??null,$.parent_agent_id??null,$.agent_id??null,$.conversation_id??null,$.is_subagent,$.prompt??null,$.metadata_json??null,$.transcript_path,$.hook_path,$.messages_path??null,$.updated_at??G0()])}async getSession($){return this.store.queryOne(`SELECT session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
653
- provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
654
- parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
655
- metadata_json, transcript_path, hook_path, messages_path, updated_at
656
- FROM sessions WHERE session_id = ?`,[$])??void 0}async listSessions($){let q=[],Y=[];if($.parentSessionId)q.push("parent_session_id = ?"),Y.push($.parentSessionId);if($.status)q.push("status = ?"),Y.push($.status);let T=q.length>0?`WHERE ${q.join(" AND ")}`:"";return this.store.queryAll(`SELECT session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
657
- provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
658
- parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
659
- metadata_json, transcript_path, hook_path, messages_path, updated_at
660
- FROM sessions
661
- ${T}
662
- ORDER BY started_at DESC
663
- LIMIT ?`,[...Y,$.limit])}async updateSession($){if($.setRunning){if($.expectedStatusLock===void 0)return{updated:!1,statusLock:0};return{updated:(this.store.run(`UPDATE sessions
664
- SET status = 'running', ended_at = NULL, exit_code = NULL, updated_at = ?, status_lock = ?,
665
- parent_session_id = ?, parent_agent_id = ?, agent_id = ?, conversation_id = ?, is_subagent = 1,
666
- prompt = COALESCE(prompt, ?)
667
- WHERE session_id = ? AND status_lock = ?`,[G0(),$.expectedStatusLock+1,$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,$.prompt??null,$.sessionId,$.expectedStatusLock]).changes??0)>0,statusLock:$.expectedStatusLock+1}}let q=[],Y=[];if($.status!==void 0)q.push("status = ?"),Y.push($.status);if($.endedAt!==void 0)q.push("ended_at = ?"),Y.push($.endedAt);if($.exitCode!==void 0)q.push("exit_code = ?"),Y.push($.exitCode);if($.prompt!==void 0)q.push("prompt = ?"),Y.push($.prompt??null);if($.metadataJson!==void 0)q.push("metadata_json = ?"),Y.push($.metadataJson??null);if($.parentSessionId!==void 0)q.push("parent_session_id = ?"),Y.push($.parentSessionId??null);if($.parentAgentId!==void 0)q.push("parent_agent_id = ?"),Y.push($.parentAgentId??null);if($.agentId!==void 0)q.push("agent_id = ?"),Y.push($.agentId??null);if($.conversationId!==void 0)q.push("conversation_id = ?"),Y.push($.conversationId??null);if(q.length===0){let Q=await this.getSession($.sessionId);return{updated:!!Q,statusLock:Q?.status_lock??0}}let T=0;if($.expectedStatusLock!==void 0)T=$.expectedStatusLock+1,q.push("status_lock = ?"),Y.push(T);q.push("updated_at = ?"),Y.push(G0());let X=`UPDATE sessions SET ${q.join(", ")} WHERE session_id = ?`;if(Y.push($.sessionId),$.expectedStatusLock!==void 0)X+=" AND status_lock = ?",Y.push($.expectedStatusLock);if((this.store.run(X,Y).changes??0)===0)return{updated:!1,statusLock:0};if($.expectedStatusLock===void 0)T=(await this.getSession($.sessionId))?.status_lock??0;return{updated:!0,statusLock:T}}async deleteSession($,q){let Y=this.store.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(q)this.store.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return Y>0}async enqueueSpawnRequest($){this.store.run(`INSERT INTO subagent_spawn_queue (root_session_id, parent_agent_id, task, system_prompt, created_at, consumed_at)
668
- VALUES (?, ?, ?, ?, ?, NULL)`,[$.rootSessionId,$.parentAgentId,$.task??null,$.systemPrompt??null,G0()])}async claimSpawnRequest($,q){let Y=this.store.queryOne(`SELECT id, task FROM subagent_spawn_queue
669
- WHERE root_session_id = ? AND parent_agent_id = ? AND consumed_at IS NULL
670
- ORDER BY id ASC LIMIT 1`,[$,q]);if(!Y||typeof Y.id!=="number")return;return this.store.run("UPDATE subagent_spawn_queue SET consumed_at = ? WHERE id = ?",[G0(),Y.id]),Y.task??void 0}}class E9 extends S6{store;constructor($){super(new c3($));this.store=$}createRootSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
671
- session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
672
- provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
673
- parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
674
- metadata_json, transcript_path, hook_path, messages_path, updated_at
675
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,null,null,"running",0,$.interactive?1:0,$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,$.enableTools?1:0,$.enableSpawn?1:0,$.enableTeams?1:0,null,null,null,null,0,$.prompt??null,$.metadata?JSON.stringify($.metadata):null,$.transcriptPath,$.hookPath,$.messagesPath,G0()])}}var Gj=process.env.CLINE_RPC_ADDRESS?.trim()||C5(),a1,C6;function Ej($){let q=process.execPath,Y=process.argv[1]?.trim();if(!Y)return;let T=i3(process.cwd(),Y);if(!n3(T))return;let X=process.execArgv.find((U)=>U.startsWith("--conditions=")),J=[...X?[X]:[],T,"rpc","start","--address",$];Uj(q,J,{detached:!0,stdio:"ignore",env:{...process.env,CLINE_NO_INTERACTIVE:"1"},cwd:process.cwd()}).unref()}async function p3($){try{if(!await S5($))return;return new G9({address:$,sessionsDir:C$()})}catch{return}}function l3(){return new E9(new UY)}function Vj($){if(typeof $==="string"&&$.trim().length>0)return $.trim();let q=C$(),Y=i3(q,"machine-id");try{if(n3(Y)){let X=Kj(Y,"utf8").trim();if(X.length>0)return X}}catch{}let T=Wj();try{Zj(q,{recursive:!0}),Aj(Y,T,"utf8")}catch{}return T}async function r3($){if(a1)return a1;if(C6)return await C6;let q=$.backendMode??"auto",Y=$.rpcAddress?.trim()||Gj,T=Math.max(1,$.rpcConnectAttempts??5),X=Math.max(0,$.rpcConnectDelayMs??100),J=$.autoStartRpcServer!==!1;return C6=(async()=>{if(q==="local")return a1=l3(),a1;let Q=await p3(Y);if(Q)return a1=Q,a1;if(q==="rpc")throw Error(`RPC backend unavailable at ${Y}`);if(J){try{Ej(Y)}catch{}for(let U=0;U<T;U+=1){let Z=await p3(Y);if(Z)return a1=Z,a1;if(X>0)await new Promise((K)=>setTimeout(K,X))}}return a1=l3(),a1})().finally(()=>{C6=void 0}),await C6}async function Dj($){let q=$.sessionService??await r3($);return new A9({sessionService:q,defaultToolExecutors:$.defaultToolExecutors,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval,distinctId:Vj($.distinctId)})}class nJ{store;constructor($={}){this.store=new UY({sessionsDir:$.sessionsDir})}init(){this.store.init()}upsertSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
676
- session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
677
- provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
678
- parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
679
- metadata_json, transcript_path, hook_path, messages_path, updated_at
680
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,$.statusLock,T1($.interactive),$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,T1($.enableTools),T1($.enableSpawn),T1($.enableTeams),$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,T1($.isSubagent),$.prompt??null,$.metadata?JSON.stringify($.metadata):null,$.transcriptPath,$.hookPath,$.messagesPath??null,$.updatedAt||X0()])}getSession($){let q=this.store.queryOne(`SELECT session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
681
- provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
682
- parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
683
- metadata_json, transcript_path, hook_path, messages_path, updated_at
684
- FROM sessions WHERE session_id = ?`,[$]);if(!q)return;return{sessionId:f(q.session_id),source:f(q.source),pid:Number(q.pid??0),startedAt:f(q.started_at),endedAt:q.ended_at??null,exitCode:q.exit_code??null,status:f(q.status),statusLock:Number(q.status_lock??0),interactive:X1(q.interactive),provider:f(q.provider),model:f(q.model),cwd:f(q.cwd),workspaceRoot:f(q.workspace_root),teamName:i(q.team_name),enableTools:X1(q.enable_tools),enableSpawn:X1(q.enable_spawn),enableTeams:X1(q.enable_teams),parentSessionId:i(q.parent_session_id),parentAgentId:i(q.parent_agent_id),agentId:i(q.agent_id),conversationId:i(q.conversation_id),isSubagent:X1(q.is_subagent),prompt:i(q.prompt),metadata:(()=>{let Y=i(q.metadata_json);if(!Y)return;try{let T=JSON.parse(Y);if(T&&typeof T==="object"&&!Array.isArray(T))return T}catch{}return})(),transcriptPath:f(q.transcript_path),hookPath:f(q.hook_path),messagesPath:i(q.messages_path),updatedAt:f(q.updated_at)||X0()}}listSessions($){let q=[],Y=[];if($.parentSessionId)q.push("parent_session_id = ?"),Y.push($.parentSessionId);if($.status)q.push("status = ?"),Y.push($.status);let T=q.length>0?`WHERE ${q.join(" AND ")}`:"",X=Math.max(1,Math.floor($.limit)),J=this.store.queryAll(`SELECT session_id FROM sessions ${T} ORDER BY started_at DESC LIMIT ?`,[...Y,X]),Q=[];for(let U of J){if(!U.session_id)continue;let Z=this.getSession(U.session_id);if(Z)Q.push(Z)}return Q}updateSession($){let q=this.getSession($.sessionId);if(!q)return{updated:!1,statusLock:0};if(typeof $.expectedStatusLock==="number"&&q.statusLock!==$.expectedStatusLock)return{updated:!1,statusLock:q.statusLock};let Y=q.statusLock+1,T=$.setRunning?"running":$.status??q.status,X=$.setRunning===!0?null:$.endedAt!==void 0?$.endedAt:q.endedAt??null,J=$.setRunning===!0?null:$.exitCode!==void 0?$.exitCode:q.exitCode??null,Q=$.prompt!==void 0?$.prompt??void 0:q.prompt,U=$.metadata!==void 0?$.metadata??void 0:q.metadata;return this.store.run(`UPDATE sessions
685
- SET status = ?, ended_at = ?, exit_code = ?, prompt = ?, metadata_json = ?,
686
- parent_session_id = ?, parent_agent_id = ?, agent_id = ?, conversation_id = ?,
687
- status_lock = ?, updated_at = ?
688
- WHERE session_id = ?`,[T,X,J,Q??null,U?JSON.stringify(U):null,$.parentSessionId!==void 0?$.parentSessionId??null:q.parentSessionId??null,$.parentAgentId!==void 0?$.parentAgentId??null:q.parentAgentId??null,$.agentId!==void 0?$.agentId??null:q.agentId??null,$.conversationId!==void 0?$.conversationId??null:q.conversationId??null,Y,X0(),$.sessionId]),{updated:!0,statusLock:Y}}deleteSession($){return(this.store.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0)>0}deleteSessionsByParent($){this.store.run("DELETE FROM sessions WHERE parent_session_id = ?",[$])}enqueueSpawnRequest($){this.store.run(`INSERT INTO subagent_spawn_queue (root_session_id, parent_agent_id, task, system_prompt, created_at, consumed_at)
689
- VALUES (?, ?, ?, ?, ?, NULL)`,[$.rootSessionId,$.parentAgentId,$.task??null,$.systemPrompt??null,X0()])}claimSpawnRequest($,q){let Y=this.store.queryOne(`SELECT id, root_session_id, parent_agent_id, task, system_prompt, created_at, consumed_at
690
- FROM subagent_spawn_queue
691
- WHERE root_session_id = ? AND parent_agent_id = ? AND consumed_at IS NULL
692
- ORDER BY id ASC LIMIT 1`,[$,q]);if(!Y||typeof Y.id!=="number")return;let T=X0();return this.store.run("UPDATE subagent_spawn_queue SET consumed_at = ? WHERE id = ?",[T,Y.id]),{id:Y.id,rootSessionId:f(Y.root_session_id),parentAgentId:f(Y.parent_agent_id),task:i(Y.task),systemPrompt:i(Y.system_prompt),createdAt:f(Y.created_at),consumedAt:T}}}function Fj($={}){return new nJ($)}import{basename as Ij,resolve as Nj}from"node:path";import Hj from"simple-git";import{z as j1}from"zod";var a3=j1.object({rootPath:j1.string().min(1),hint:j1.string().min(1).optional(),associatedRemoteUrls:j1.array(j1.string().min(1)).optional(),latestGitCommitHash:j1.string().min(1).optional(),latestGitBranchName:j1.string().min(1).optional()}),ZY=j1.object({currentWorkspacePath:j1.string().min(1).optional(),workspaces:j1.record(j1.string().min(1),a3)});function zj(){return{workspaces:{}}}function y6($){return Nj($)}async function V9($){let q=y6($),Y={rootPath:q,hint:Ij(q)};try{let T=Hj({baseDir:q});if(!await T.checkIsRepo())return Y;let J=await T.getRemotes(!0);if(J.length>0){let Z=J.map((K)=>{let A=K.refs.fetch||K.refs.push;return`${K.name}: ${A}`});Y.associatedRemoteUrls=Z}let Q=(await T.revparse(["HEAD"])).trim();if(Q.length>0)Y.latestGitCommitHash=Q;let U=(await T.branch()).current.trim();if(U.length>0)Y.latestGitBranchName=U}catch{}return Y}function iJ($,q){let Y={...$,workspaces:{...$.workspaces,[q.rootPath]:q}};if(!Y.currentWorkspacePath)Y.currentWorkspacePath=q.rootPath;return ZY.parse(Y)}async function Mj($){let q=await V9($),Y={workspaces:{[q.rootPath]:{hint:q.hint,associatedRemoteUrls:q.associatedRemoteUrls,latestGitCommitHash:q.latestGitCommitHash,latestGitBranchName:q.latestGitBranchName}}};return`# Workspace Configuration
693
- ${JSON.stringify(Y,null,2)}`}class o3{manifest;listeners=new Set;constructor($){this.manifest=ZY.parse($??{workspaces:{}})}async addWorkspacePath($){let q=await V9($);return this.manifest=iJ(this.manifest,q),this.emit({type:"workspace_added",workspace:q}),q}async switchWorkspace($){let q=y6($),Y=this.manifest.workspaces[q];if(Y)return this.manifest=ZY.parse({...this.manifest,currentWorkspacePath:q}),this.emit({type:"workspace_switched",workspace:Y}),Y;let T=await this.addWorkspacePath(q);return this.manifest=ZY.parse({...this.manifest,currentWorkspacePath:T.rootPath}),this.emit({type:"workspace_switched",workspace:T}),T}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}getCurrentWorkspace(){let $=this.manifest.currentWorkspacePath;if(!$)return;return this.manifest.workspaces[$]}getWorkspace($){let q=y6($);return this.manifest.workspaces[q]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit($){for(let q of this.listeners)q($)}}export{iJ as upsertWorkspaceInfo,b8 as toPartialAgentConfig,l5 as toHookConfigFileName,Zw as stopRpcServer,Uw as startRpcServer,Zq as startLocalOAuthServer,L6 as sanitizeSessionToken,aL as runRpcRuntimeEventBridge,iL as runRpcRuntimeCommandBridge,JJ as resolveWorkflowsConfigSearchPaths,aC as resolveWorkflowSlashCommandFromWatcher,TJ as resolveSkillsConfigSearchPaths,r3 as resolveSessionBackend,XJ as resolveRulesConfigSearchPaths,a5 as resolvePluginConfigSearchPaths,MJ as resolveMcpServerRegistrations,c5 as resolveHooksConfigSearchPaths,E6 as resolveDocumentsWorkflowsDirectoryPath,G6 as resolveDocumentsRulesDirectoryPath,W6 as resolveDocumentsHooksDirectoryPath,J9 as resolveDefaultMcpSettingsPath,n8 as resolveAndLoadAgentPlugins,f8 as resolveAgentTools,o5 as resolveAgentPluginPaths,Yw as requestRpcServerShutdown,iC as requestDesktopToolApproval,Tw as registerRpcClient,Z3 as registerMcpServersFromSettingsFile,VJ as refreshOpenAICodexToken,IJ as refreshOcaToken,GJ as refreshClineToken,DV as prewarmFileIndex,YJ as parseWorkflowConfigFromMarkdown,$J as parseSkillConfigFromMarkdown,qJ as parseRuleConfigFromMarkdown,u5 as parsePartialAgentConfigFromYaml,eq as parseAgentConfigFromYaml,$C as openaiCodexOAuthProvider,y6 as normalizeWorkspacePath,eS as normalizeOpenAICodexCredentials,CJ as migrateLegacyProviderSettings,cJ as makeTeamTaskSubSessionId,W9 as makeSubSessionId,bV as loginOpenAICodex,T3 as loginOcaOAuth,gV as loginClineOAuth,OC as loadRulesForSystemPromptFromWatcher,zJ as loadMcpSettingsFile,c8 as loadAgentPluginsFromPaths,n5 as loadAgentPluginFromPath,d8 as listHookConfigFiles,W3 as listEnabledRulesFromWatcher,N3 as listAvailableWorkflowsFromWatcher,K3 as isRuleEnabled,iE as isRpcClineAccountActionRequest,tS as isOpenAICodexTokenExpired,U3 as hasMcpSettingsFile,DJ as getValidOpenAICodexCredentials,NJ as getValidOcaCredentials,EJ as getValidClineCredentials,S5 as getRpcServerHealth,C5 as getRpcServerDefaultAddress,Jq as getFileIndex,V9 as generateWorkspaceInfo,X3 as generateOcaOpcRequestId,A3 as formatRulesForSystemPrompt,rE as executeRpcClineAccountAction,k8 as enrichPromptWithMentions,zj as emptyWorkspaceManifest,l8 as discoverPluginModulePaths,pJ as deriveSubsessionStatus,ZJ as createWorkflowsConfigDefinition,t8 as createUserInstructionConfigWatcher,NV as createToolPoliciesWithPreset,F3 as createTeamName,Fj as createSqliteRpcSessionBackend,QJ as createSkillsConfigDefinition,Dj as createSessionHost,UJ as createRulesConfigDefinition,WC as createOcaRequestHeaders,AC as createOcaOAuthProvider,xS as createOAuthClientCallbacks,HV as createDefaultToolsWithPreset,sq as createDefaultTools,m8 as createDefaultExecutors,nS as createClineOAuthProvider,N6 as createBuiltinTools,PV as createAgentConfigWatcher,d5 as createAgentConfigDefinition,Mj as buildWorkspaceMetadata,ZY as WorkspaceManifestSchema,a3 as WorkspaceInfoSchema,K6 as WORKFLOWS_CONFIG_DIRECTORY_NAME,Uq as UnifiedConfigFileWatcher,Z$ as ToolPresets,p8 as SubprocessSandbox,UY as SqliteSessionStore,nJ as SqliteRpcSessionBackend,P6 as SessionSource,S1 as SKILLS_CONFIG_DIRECTORY_NAME,xJ as SESSION_STATUSES,F6 as RpcSessionClient,I6 as RpcRuntimeChatClient,G9 as RpcCoreSessionService,j5 as RpcClineAccountService,Z6 as RULES_CONFIG_DIRECTORY_NAME,JY as ProviderSettingsManager,oV as OCI_HEADER_OPC_REQUEST_ID,o3 as InMemoryWorkspaceManager,BJ as InMemoryMcpManager,u8 as HookConfigFileName,p5 as HOOK_CONFIG_FILE_EVENT_MAP,U6 as HOOKS_CONFIG_DIRECTORY_NAME,n1 as DefaultToolNames,A9 as DefaultSessionManager,Q9 as DefaultRuntimeBuilder,lV as DEFAULT_INTERNAL_OCA_BASE_URL,cV as DEFAULT_INTERNAL_IDCS_URL,pV as DEFAULT_INTERNAL_IDCS_SCOPES,dV as DEFAULT_INTERNAL_IDCS_CLIENT_ID,aV as DEFAULT_EXTERNAL_OCA_BASE_URL,iV as DEFAULT_EXTERNAL_IDCS_URL,rV as DEFAULT_EXTERNAL_IDCS_SCOPES,nV as DEFAULT_EXTERNAL_IDCS_CLIENT_ID,E9 as CoreSessionService,y5 as ClineAccountService,Xq as ALL_DEFAULT_TOOL_NAMES};