@clinebot/core 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +88 -0
- package/dist/account/cline-account-service.d.ts +34 -0
- package/dist/account/index.d.ts +3 -0
- package/dist/account/rpc.d.ts +38 -0
- package/dist/account/types.d.ts +74 -0
- package/dist/agents/agent-config-loader.d.ts +18 -0
- package/dist/agents/agent-config-parser.d.ts +25 -0
- package/dist/agents/hooks-config-loader.d.ts +23 -0
- package/dist/agents/index.d.ts +11 -0
- package/dist/agents/plugin-config-loader.d.ts +22 -0
- package/dist/agents/plugin-loader.d.ts +9 -0
- package/dist/agents/plugin-sandbox.d.ts +12 -0
- package/dist/agents/unified-config-file-watcher.d.ts +77 -0
- package/dist/agents/user-instruction-config-loader.d.ts +63 -0
- package/dist/auth/client.d.ts +11 -0
- package/dist/auth/cline.d.ts +41 -0
- package/dist/auth/codex.d.ts +39 -0
- package/dist/auth/oca.d.ts +22 -0
- package/dist/auth/server.d.ts +22 -0
- package/dist/auth/types.d.ts +72 -0
- package/dist/auth/utils.d.ts +32 -0
- package/dist/chat/chat-schema.d.ts +145 -0
- package/dist/default-tools/constants.d.ts +23 -0
- package/dist/default-tools/definitions.d.ts +96 -0
- package/dist/default-tools/executors/apply-patch-parser.d.ts +68 -0
- package/dist/default-tools/executors/apply-patch.d.ts +26 -0
- package/dist/default-tools/executors/bash.d.ts +49 -0
- package/dist/default-tools/executors/editor.d.ts +31 -0
- package/dist/default-tools/executors/file-read.d.ts +40 -0
- package/dist/default-tools/executors/index.d.ts +44 -0
- package/dist/default-tools/executors/search.d.ts +50 -0
- package/dist/default-tools/executors/web-fetch.d.ts +58 -0
- package/dist/default-tools/index.d.ts +57 -0
- package/dist/default-tools/presets.d.ts +124 -0
- package/dist/default-tools/schemas.d.ts +121 -0
- package/dist/default-tools/types.d.ts +237 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.js +220 -0
- package/dist/input/file-indexer.d.ts +5 -0
- package/dist/input/index.d.ts +4 -0
- package/dist/input/mention-enricher.d.ts +12 -0
- package/dist/mcp/config-loader.d.ts +15 -0
- package/dist/mcp/index.d.ts +4 -0
- package/dist/mcp/manager.d.ts +24 -0
- package/dist/mcp/types.d.ts +66 -0
- package/dist/runtime/hook-file-hooks.d.ts +18 -0
- package/dist/runtime/rules.d.ts +5 -0
- package/dist/runtime/runtime-builder.d.ts +5 -0
- package/dist/runtime/sandbox/subprocess-sandbox.d.ts +19 -0
- package/dist/runtime/session-runtime.d.ts +36 -0
- package/dist/runtime/tool-approval.d.ts +9 -0
- package/dist/runtime/workflows.d.ts +13 -0
- package/dist/server/index.d.ts +47 -0
- package/dist/server/index.js +641 -0
- package/dist/session/default-session-manager.d.ts +77 -0
- package/dist/session/rpc-session-service.d.ts +12 -0
- package/dist/session/runtime-oauth-token-manager.d.ts +28 -0
- package/dist/session/session-artifacts.d.ts +19 -0
- package/dist/session/session-graph.d.ts +15 -0
- package/dist/session/session-host.d.ts +21 -0
- package/dist/session/session-manager.d.ts +50 -0
- package/dist/session/session-manifest.d.ts +30 -0
- package/dist/session/session-service.d.ts +113 -0
- package/dist/session/sqlite-rpc-session-backend.d.ts +30 -0
- package/dist/session/unified-session-persistence-service.d.ts +93 -0
- package/dist/session/workspace-manager.d.ts +28 -0
- package/dist/session/workspace-manifest.d.ts +25 -0
- package/dist/storage/provider-settings-legacy-migration.d.ts +13 -0
- package/dist/storage/provider-settings-manager.d.ts +20 -0
- package/dist/storage/sqlite-session-store.d.ts +29 -0
- package/dist/storage/sqlite-team-store.d.ts +31 -0
- package/dist/storage/team-store.d.ts +2 -0
- package/dist/team/index.d.ts +1 -0
- package/dist/team/projections.d.ts +8 -0
- package/dist/types/common.d.ts +10 -0
- package/dist/types/config.d.ts +37 -0
- package/dist/types/events.d.ts +54 -0
- package/dist/types/provider-settings.d.ts +20 -0
- package/dist/types/sessions.d.ts +9 -0
- package/dist/types/storage.d.ts +37 -0
- package/dist/types/workspace.d.ts +7 -0
- package/dist/types.d.ts +26 -0
- package/package.json +63 -0
- package/src/account/cline-account-service.test.ts +101 -0
- package/src/account/cline-account-service.ts +267 -0
- package/src/account/index.ts +20 -0
- package/src/account/rpc.test.ts +62 -0
- package/src/account/rpc.ts +172 -0
- package/src/account/types.ts +80 -0
- package/src/agents/agent-config-loader.test.ts +234 -0
- package/src/agents/agent-config-loader.ts +107 -0
- package/src/agents/agent-config-parser.ts +191 -0
- package/src/agents/hooks-config-loader.ts +97 -0
- package/src/agents/index.ts +84 -0
- package/src/agents/plugin-config-loader.test.ts +91 -0
- package/src/agents/plugin-config-loader.ts +160 -0
- package/src/agents/plugin-loader.test.ts +102 -0
- package/src/agents/plugin-loader.ts +105 -0
- package/src/agents/plugin-sandbox.test.ts +120 -0
- package/src/agents/plugin-sandbox.ts +471 -0
- package/src/agents/unified-config-file-watcher.test.ts +196 -0
- package/src/agents/unified-config-file-watcher.ts +483 -0
- package/src/agents/user-instruction-config-loader.test.ts +158 -0
- package/src/agents/user-instruction-config-loader.ts +438 -0
- package/src/auth/client.test.ts +40 -0
- package/src/auth/client.ts +25 -0
- package/src/auth/cline.test.ts +130 -0
- package/src/auth/cline.ts +414 -0
- package/src/auth/codex.test.ts +170 -0
- package/src/auth/codex.ts +466 -0
- package/src/auth/oca.test.ts +215 -0
- package/src/auth/oca.ts +546 -0
- package/src/auth/server.ts +216 -0
- package/src/auth/types.ts +78 -0
- package/src/auth/utils.test.ts +128 -0
- package/src/auth/utils.ts +247 -0
- package/src/chat/chat-schema.ts +82 -0
- package/src/default-tools/constants.ts +35 -0
- package/src/default-tools/definitions.test.ts +233 -0
- package/src/default-tools/definitions.ts +632 -0
- package/src/default-tools/executors/apply-patch-parser.ts +520 -0
- package/src/default-tools/executors/apply-patch.ts +359 -0
- package/src/default-tools/executors/bash.ts +205 -0
- package/src/default-tools/executors/editor.ts +231 -0
- package/src/default-tools/executors/file-read.test.ts +25 -0
- package/src/default-tools/executors/file-read.ts +94 -0
- package/src/default-tools/executors/index.ts +75 -0
- package/src/default-tools/executors/search.ts +278 -0
- package/src/default-tools/executors/web-fetch.ts +259 -0
- package/src/default-tools/index.ts +161 -0
- package/src/default-tools/presets.test.ts +63 -0
- package/src/default-tools/presets.ts +168 -0
- package/src/default-tools/schemas.ts +228 -0
- package/src/default-tools/types.ts +324 -0
- package/src/index.ts +119 -0
- package/src/input/file-indexer.d.ts +11 -0
- package/src/input/file-indexer.test.ts +87 -0
- package/src/input/file-indexer.ts +280 -0
- package/src/input/index.ts +7 -0
- package/src/input/mention-enricher.test.ts +82 -0
- package/src/input/mention-enricher.ts +119 -0
- package/src/mcp/config-loader.test.ts +238 -0
- package/src/mcp/config-loader.ts +219 -0
- package/src/mcp/index.ts +26 -0
- package/src/mcp/manager.test.ts +106 -0
- package/src/mcp/manager.ts +262 -0
- package/src/mcp/types.ts +88 -0
- package/src/runtime/hook-file-hooks.test.ts +106 -0
- package/src/runtime/hook-file-hooks.ts +736 -0
- package/src/runtime/index.ts +27 -0
- package/src/runtime/rules.ts +34 -0
- package/src/runtime/runtime-builder.team-persistence.test.ts +203 -0
- package/src/runtime/runtime-builder.test.ts +215 -0
- package/src/runtime/runtime-builder.ts +515 -0
- package/src/runtime/runtime-parity.test.ts +132 -0
- package/src/runtime/sandbox/subprocess-sandbox.ts +207 -0
- package/src/runtime/session-runtime.ts +44 -0
- package/src/runtime/tool-approval.ts +104 -0
- package/src/runtime/workflows.test.ts +119 -0
- package/src/runtime/workflows.ts +54 -0
- package/src/server/index.ts +282 -0
- package/src/session/default-session-manager.e2e.test.ts +354 -0
- package/src/session/default-session-manager.test.ts +816 -0
- package/src/session/default-session-manager.ts +1286 -0
- package/src/session/index.ts +37 -0
- package/src/session/rpc-session-service.ts +189 -0
- package/src/session/runtime-oauth-token-manager.test.ts +137 -0
- package/src/session/runtime-oauth-token-manager.ts +265 -0
- package/src/session/session-artifacts.ts +106 -0
- package/src/session/session-graph.ts +90 -0
- package/src/session/session-host.ts +190 -0
- package/src/session/session-manager.ts +56 -0
- package/src/session/session-manifest.ts +29 -0
- package/src/session/session-service.team-persistence.test.ts +48 -0
- package/src/session/session-service.ts +610 -0
- package/src/session/sqlite-rpc-session-backend.ts +303 -0
- package/src/session/unified-session-persistence-service.ts +781 -0
- package/src/session/workspace-manager.ts +98 -0
- package/src/session/workspace-manifest.ts +100 -0
- package/src/storage/artifact-store.ts +1 -0
- package/src/storage/index.ts +11 -0
- package/src/storage/provider-settings-legacy-migration.test.ts +175 -0
- package/src/storage/provider-settings-legacy-migration.ts +637 -0
- package/src/storage/provider-settings-manager.test.ts +111 -0
- package/src/storage/provider-settings-manager.ts +129 -0
- package/src/storage/session-store.ts +1 -0
- package/src/storage/sqlite-session-store.ts +270 -0
- package/src/storage/sqlite-team-store.ts +443 -0
- package/src/storage/team-store.ts +5 -0
- package/src/team/index.ts +4 -0
- package/src/team/projections.ts +285 -0
- package/src/types/common.ts +14 -0
- package/src/types/config.ts +64 -0
- package/src/types/events.ts +46 -0
- package/src/types/index.ts +24 -0
- package/src/types/provider-settings.ts +43 -0
- package/src/types/sessions.ts +16 -0
- package/src/types/storage.ts +64 -0
- package/src/types/workspace.ts +7 -0
- package/src/types.ts +127 -0
|
@@ -0,0 +1,641 @@
|
|
|
1
|
+
import{createRequire as CA}from"node:module";var BA=Object.create;var{getPrototypeOf:IA,defineProperty:k7,getOwnPropertyNames:OA}=Object;var PA=Object.prototype.hasOwnProperty;function LA($){return this[$]}var SA,wA,KY=($,Y,X)=>{var Q=$!=null&&typeof $==="object";if(Q){var J=Y?SA??=new WeakMap:wA??=new WeakMap,Z=J.get($);if(Z)return Z}X=$!=null?BA(IA($)):{};let T=Y||!$||!$.__esModule?k7(X,"default",{value:$,enumerable:!0}):X;for(let K of OA($))if(!PA.call(T,K))k7(T,K,{get:LA.bind($,K),enumerable:!0});if(Q)J.set($,T);return T};var M=($,Y)=>()=>(Y||$((Y={exports:{}}).exports,Y),Y.exports);var s=CA(import.meta.url);var i=M((ST)=>{Object.defineProperty(ST,"__esModule",{value:!0});ST.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH=ST.DEFAULT_MAX_SEND_MESSAGE_LENGTH=ST.Propagate=ST.LogVerbosity=ST.Status=void 0;var OT;(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"})(OT||(ST.Status=OT={}));var PT;(function($){$[$.DEBUG=0]="DEBUG",$[$.INFO=1]="INFO",$[$.ERROR=2]="ERROR",$[$.NONE=3]="NONE"})(PT||(ST.LogVerbosity=PT={}));var LT;(function($){$[$.DEADLINE=1]="DEADLINE",$[$.CENSUS_STATS_CONTEXT=2]="CENSUS_STATS_CONTEXT",$[$.CENSUS_TRACING_CONTEXT=4]="CENSUS_TRACING_CONTEXT",$[$.CANCELLATION=8]="CANCELLATION",$[$.DEFAULTS=65535]="DEFAULTS"})(LT||(ST.Propagate=LT={}));ST.DEFAULT_MAX_SEND_MESSAGE_LENGTH=-1;ST.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH=4194304});var L5=M((Yh,qz)=>{qz.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=M((jT)=>{var S5,w5,C5,y5;Object.defineProperty(jT,"__esModule",{value:!0});jT.log=jT.setLoggerVerbosity=jT.setLogger=jT.getLogger=void 0;jT.trace=yz;jT.isTracerEnabled=yT;var q$=i(),Nz=s("process"),Mz=L5().version,Bz={error:($,...Y)=>{console.error("E "+$,...Y)},info:($,...Y)=>{console.error("I "+$,...Y)},debug:($,...Y)=>{console.error("D "+$,...Y)}},c$=Bz,NY=q$.LogVerbosity.ERROR,Iz=(w5=(S5=process.env.GRPC_NODE_VERBOSITY)!==null&&S5!==void 0?S5:process.env.GRPC_VERBOSITY)!==null&&w5!==void 0?w5:"";switch(Iz.toUpperCase()){case"DEBUG":NY=q$.LogVerbosity.DEBUG;break;case"INFO":NY=q$.LogVerbosity.INFO;break;case"ERROR":NY=q$.LogVerbosity.ERROR;break;case"NONE":NY=q$.LogVerbosity.NONE;break;default:}var Oz=()=>{return c$};jT.getLogger=Oz;var Pz=($)=>{c$=$};jT.setLogger=Pz;var Lz=($)=>{NY=$};jT.setLoggerVerbosity=Lz;var Sz=($,...Y)=>{let X;if($>=NY){switch($){case q$.LogVerbosity.DEBUG:X=c$.debug;break;case q$.LogVerbosity.INFO:X=c$.info;break;case q$.LogVerbosity.ERROR:X=c$.error;break}if(!X)X=c$.error;if(X)X.bind(c$)(...Y)}};jT.log=Sz;var wz=(y5=(C5=process.env.GRPC_NODE_TRACE)!==null&&C5!==void 0?C5:process.env.GRPC_TRACE)!==null&&y5!==void 0?y5:"",j5=new Set,CT=new Set;for(let $ of wz.split(","))if($.startsWith("-"))CT.add($.substring(1));else j5.add($);var Cz=j5.has("all");function yz($,Y,X){if(yT(Y))jT.log($,new Date().toISOString()+" | v"+Mz+" "+Nz.pid+" | "+Y+" | "+X)}function yT($){return!CT.has($)&&(Cz||j5.has($))}});var q9=M((xT)=>{Object.defineProperty(xT,"__esModule",{value:!0});xT.getErrorMessage=_z;xT.getErrorCode=gz;function _z($){if($ instanceof Error)return $.message;else return String($)}function gz($){if(typeof $==="object"&&$!==null&&"code"in $&&typeof $.code==="number")return $.code;else return null}});var P0=M((hT)=>{Object.defineProperty(hT,"__esModule",{value:!0});hT.Metadata=void 0;var bz=Z0(),uz=i(),dz=q9(),pz=/^[:0-9a-z_.-]+$/,cz=/^[ -~]*$/;function nz($){return pz.test($)}function lz($){return cz.test($)}function kT($){return $.endsWith("-bin")}function iz($){return!$.startsWith("grpc-")}function N9($){return $.toLowerCase()}function vT($,Y){if(!nz($))throw Error('Metadata key "'+$+'" contains illegal characters');if(Y!==null&&Y!==void 0)if(kT($)){if(!Buffer.isBuffer(Y))throw Error("keys that end with '-bin' must have Buffer values")}else{if(Buffer.isBuffer(Y))throw Error("keys that don't end with '-bin' must have String values");if(!lz(Y))throw Error('Metadata string value "'+Y+'" contains illegal characters')}}class M9{constructor($={}){this.internalRepr=new Map,this.opaqueData=new Map,this.options=$}set($,Y){$=N9($),vT($,Y),this.internalRepr.set($,[Y])}add($,Y){$=N9($),vT($,Y);let X=this.internalRepr.get($);if(X===void 0)this.internalRepr.set($,[Y]);else X.push(Y)}remove($){$=N9($),this.internalRepr.delete($)}get($){return $=N9($),this.internalRepr.get($)||[]}getMap(){let $={};for(let[Y,X]of this.internalRepr)if(X.length>0){let Q=X[0];$[Y]=Buffer.isBuffer(Q)?Buffer.from(Q):Q}return $}clone(){let $=new M9(this.options),Y=$.internalRepr;for(let[X,Q]of this.internalRepr){let J=Q.map((Z)=>{if(Buffer.isBuffer(Z))return Buffer.from(Z);else return Z});Y.set(X,J)}return $}merge($){for(let[Y,X]of $.internalRepr){let Q=(this.internalRepr.get(Y)||[]).concat(X);this.internalRepr.set(Y,Q)}}setOptions($){this.options=$}getOptions(){return this.options}toHttp2Headers(){let $={};for(let[Y,X]of this.internalRepr){if(Y.startsWith(":"))continue;$[Y]=X.map(rz)}return $}toJSON(){let $={};for(let[Y,X]of this.internalRepr)$[Y]=X;return $}setOpaque($,Y){this.opaqueData.set($,Y)}getOpaque($){return this.opaqueData.get($)}static fromHttp2Headers($){let Y=new M9;for(let X of Object.keys($)){if(X.charAt(0)===":")continue;let Q=$[X];try{if(kT(X)){if(Array.isArray(Q))Q.forEach((J)=>{Y.add(X,Buffer.from(J,"base64"))});else if(Q!==void 0)if(iz(X))Q.split(",").forEach((J)=>{Y.add(X,Buffer.from(J.trim(),"base64"))});else Y.add(X,Buffer.from(Q,"base64"))}else if(Array.isArray(Q))Q.forEach((J)=>{Y.add(X,J)});else if(Q!==void 0)Y.add(X,Q)}catch(J){let Z=`Failed to add metadata entry ${X}: ${Q}. ${(0,dz.getErrorMessage)(J)}. For more information see https://github.com/grpc/grpc-node/issues/1173`;(0,bz.log)(uz.LogVerbosity.ERROR,Z)}}return Y}}hT.Metadata=M9;var rz=($)=>{return Buffer.isBuffer($)?$.toString("base64"):$}});var I9=M((gT)=>{Object.defineProperty(gT,"__esModule",{value:!0});gT.CallCredentials=void 0;var v5=P0();function oz($){return"getRequestHeaders"in $&&typeof $.getRequestHeaders==="function"}class MY{static createFromMetadataGenerator($){return new k5($)}static createFromGoogleCredential($){return MY.createFromMetadataGenerator((Y,X)=>{let Q;if(oz($))Q=$.getRequestHeaders(Y.service_url);else Q=new Promise((J,Z)=>{$.getRequestMetadata(Y.service_url,(T,K)=>{if(T){Z(T);return}if(!K){Z(Error("Headers not set by metadata plugin"));return}J(K)})});Q.then((J)=>{let Z=new v5.Metadata;for(let T of Object.keys(J))Z.add(T,J[T]);X(null,Z)},(J)=>{X(J)})})}static createEmpty(){return new h5}}gT.CallCredentials=MY;class B9 extends MY{constructor($){super();this.creds=$}async generateMetadata($){let Y=new v5.Metadata,X=await Promise.all(this.creds.map((Q)=>Q.generateMetadata($)));for(let Q of X)Y.merge(Q);return Y}compose($){return new B9(this.creds.concat([$]))}_equals($){if(this===$)return!0;if($ instanceof B9)return this.creds.every((Y,X)=>Y._equals($.creds[X]));else return!1}}class k5 extends MY{constructor($){super();this.metadataGenerator=$}generateMetadata($){return new Promise((Y,X)=>{this.metadataGenerator($,(Q,J)=>{if(J!==void 0)Y(J);else X(Q)})})}compose($){return new B9([this,$])}_equals($){if(this===$)return!0;if($ instanceof k5)return this.metadataGenerator===$.metadataGenerator;else return!1}}class h5 extends MY{generateMetadata($){return Promise.resolve(new v5.Metadata)}compose($){return $}_equals($){return $ instanceof h5}}});var g5=M((bT)=>{Object.defineProperty(bT,"__esModule",{value:!0});bT.CIPHER_SUITES=void 0;bT.getDefaultRootsData=az;var sz=s("fs");bT.CIPHER_SUITES=process.env.GRPC_SSL_CIPHER_SUITES;var mT=process.env.GRPC_DEFAULT_SSL_ROOTS_FILE_PATH,_5=null;function az(){if(mT){if(_5===null)_5=sz.readFileSync(mT);return _5}return null}});var c0=M((pT)=>{Object.defineProperty(pT,"__esModule",{value:!0});pT.parseUri=$q;pT.splitHostPort=Yq;pT.combineHostPort=Xq;pT.uriToString=Qq;var ez=/^(?:([A-Za-z0-9+.-]+):)?(?:\/\/([^/]*)\/)?(.+)$/;function $q($){let Y=ez.exec($);if(Y===null)return null;return{scheme:Y[1],authority:Y[2],path:Y[3]}}var dT=/^\d+$/;function Yq($){if($.startsWith("[")){let Y=$.indexOf("]");if(Y===-1)return null;let X=$.substring(1,Y);if(X.indexOf(":")===-1)return null;if($.length>Y+1)if($[Y+1]===":"){let Q=$.substring(Y+2);if(dT.test(Q))return{host:X,port:+Q};else return null}else return null;else return{host:X}}else{let Y=$.split(":");if(Y.length===2)if(dT.test(Y[1]))return{host:Y[0],port:+Y[1]};else return null;else return{host:$}}}function Xq($){if($.port===void 0)return $.host;else if($.host.includes(":"))return`[${$.host}]:${$.port}`;else return`${$.host}:${$.port}`}function Qq($){let Y="";if($.scheme!==void 0)Y+=$.scheme+":";if($.authority!==void 0)Y+="//"+$.authority+"/";return Y+=$.path,Y}});var M1=M((cT)=>{Object.defineProperty(cT,"__esModule",{value:!0});cT.CHANNEL_ARGS_CONFIG_SELECTOR_KEY=void 0;cT.registerResolver=Uq;cT.registerDefaultScheme=Gq;cT.createResolver=Wq;cT.getDefaultAuthority=Rq;cT.mapUriDefaultScheme=Eq;var m5=c0();cT.CHANNEL_ARGS_CONFIG_SELECTOR_KEY="grpc.internal.config_selector";var BY={},f5=null;function Uq($,Y){BY[$]=Y}function Gq($){f5=$}function Wq($,Y,X){if($.scheme!==void 0&&$.scheme in BY)return new BY[$.scheme]($,Y,X);else throw Error(`No resolver could be created for target ${(0,m5.uriToString)($)}`)}function Rq($){if($.scheme!==void 0&&$.scheme in BY)return BY[$.scheme].getDefaultAuthority($);else throw Error(`Invalid target ${(0,m5.uriToString)($)}`)}function Eq($){if($.scheme===void 0||!($.scheme in BY))if(f5!==null)return{scheme:f5,authority:void 0,path:(0,m5.uriToString)($)};else return null;return $}});var OY=M((oT)=>{Object.defineProperty(oT,"__esModule",{value:!0});oT.ChannelCredentials=void 0;oT.createCertificateProviderChannelCredentials=Mq;var B6=s("tls"),L9=I9(),u5=g5(),lT=c0(),zq=M1(),qq=Z0(),Nq=i();function b5($,Y){if($&&!($ instanceof Buffer))throw TypeError(`${Y}, if provided, must be a Buffer.`)}class IY{compose($){return new P9(this,$)}static createSsl($,Y,X,Q){var J;if(b5($,"Root certificate"),b5(Y,"Private key"),b5(X,"Certificate chain"),Y&&!X)throw Error("Private key must be given with accompanying certificate chain");if(!Y&&X)throw Error("Certificate chain must be given with accompanying private key");let Z=(0,B6.createSecureContext)({ca:(J=$!==null&&$!==void 0?$:(0,u5.getDefaultRootsData)())!==null&&J!==void 0?J:void 0,key:Y!==null&&Y!==void 0?Y:void 0,cert:X!==null&&X!==void 0?X:void 0,ciphers:u5.CIPHER_SUITES});return new O9(Z,Q!==null&&Q!==void 0?Q:{})}static createFromSecureContext($,Y){return new O9($,Y!==null&&Y!==void 0?Y:{})}static createInsecure(){return new d5}}oT.ChannelCredentials=IY;class d5 extends IY{constructor(){super()}compose($){throw Error("Cannot compose insecure credentials")}_isSecure(){return!1}_equals($){return $ instanceof d5}_createSecureConnector($,Y,X){return{connect(Q){return Promise.resolve({socket:Q,secure:!1})},waitForReady:()=>{return Promise.resolve()},getCallCredentials:()=>{return X!==null&&X!==void 0?X:L9.CallCredentials.createEmpty()},destroy(){}}}}function iT($,Y,X,Q){var J,Z;let T={secureContext:$},K=X;if("grpc.http_connect_target"in Q){let R=(0,lT.parseUri)(Q["grpc.http_connect_target"]);if(R)K=R}let U=(0,zq.getDefaultAuthority)(K),G=(0,lT.splitHostPort)(U),W=(J=G===null||G===void 0?void 0:G.host)!==null&&J!==void 0?J:U;if(T.host=W,Y.checkServerIdentity)T.checkServerIdentity=Y.checkServerIdentity;if(Y.rejectUnauthorized!==void 0)T.rejectUnauthorized=Y.rejectUnauthorized;if(T.ALPNProtocols=["h2"],Q["grpc.ssl_target_name_override"]){let R=Q["grpc.ssl_target_name_override"],V=(Z=T.checkServerIdentity)!==null&&Z!==void 0?Z:B6.checkServerIdentity;T.checkServerIdentity=(A,H)=>{return V(R,H)},T.servername=R}else T.servername=W;if(Q["grpc-node.tls_enable_trace"])T.enableTrace=!0;return T}class rT{constructor($,Y){this.connectionOptions=$,this.callCredentials=Y}connect($){let Y=Object.assign({socket:$},this.connectionOptions);return new Promise((X,Q)=>{let J=(0,B6.connect)(Y,()=>{var Z;if(((Z=this.connectionOptions.rejectUnauthorized)!==null&&Z!==void 0?Z:!0)&&!J.authorized){Q(J.authorizationError);return}X({socket:J,secure:!0})});J.on("error",(Z)=>{Q(Z)})})}waitForReady(){return Promise.resolve()}getCallCredentials(){return this.callCredentials}destroy(){}}class O9 extends IY{constructor($,Y){super();this.secureContext=$,this.verifyOptions=Y}_isSecure(){return!0}_equals($){if(this===$)return!0;if($ instanceof O9)return this.secureContext===$.secureContext&&this.verifyOptions.checkServerIdentity===$.verifyOptions.checkServerIdentity;else return!1}_createSecureConnector($,Y,X){let Q=iT(this.secureContext,this.verifyOptions,$,Y);return new rT(Q,X!==null&&X!==void 0?X:L9.CallCredentials.createEmpty())}}class M6 extends IY{constructor($,Y,X){super();this.caCertificateProvider=$,this.identityCertificateProvider=Y,this.verifyOptions=X,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 Y,X;if(this===$)return!0;if($ instanceof M6)return this.caCertificateProvider===$.caCertificateProvider&&this.identityCertificateProvider===$.identityCertificateProvider&&((Y=this.verifyOptions)===null||Y===void 0?void 0:Y.checkServerIdentity)===((X=$.verifyOptions)===null||X===void 0?void 0:X.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($,Y,X){return this.ref(),new M6.SecureConnectorImpl(this,$,Y,X!==null&&X!==void 0?X:L9.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 $,Y;if(!this.latestCaUpdate)return null;if(this.identityCertificateProvider!==null&&!this.latestIdentityUpdate)return null;try{return(0,B6.createSecureContext)({ca:this.latestCaUpdate.caCertificate,key:($=this.latestIdentityUpdate)===null||$===void 0?void 0:$.privateKey,cert:(Y=this.latestIdentityUpdate)===null||Y===void 0?void 0:Y.certificate,ciphers:u5.CIPHER_SUITES})}catch(X){return(0,qq.log)(Nq.LogVerbosity.ERROR,"Failed to createSecureContext with error "+X.message),null}}}M6.SecureConnectorImpl=class{constructor($,Y,X,Q){this.parent=$,this.channelTarget=Y,this.options=X,this.callCredentials=Q}connect($){return new Promise((Y,X)=>{let Q=this.parent.getLatestSecureContext();if(!Q){X(Error("Failed to load credentials"));return}if($.closed)X(Error("Socket closed while loading credentials"));let J=iT(Q,this.parent.verifyOptions,this.channelTarget,this.options),Z=Object.assign({socket:$},J),T=()=>{X(Error("Socket closed"))},K=(G)=>{X(G)},U=(0,B6.connect)(Z,()=>{var G;if(U.removeListener("close",T),U.removeListener("error",K),((G=this.parent.verifyOptions.rejectUnauthorized)!==null&&G!==void 0?G:!0)&&!U.authorized){X(U.authorizationError);return}Y({socket:U,secure:!0})});U.once("close",T),U.once("error",K)})}async waitForReady(){await this.parent.getSecureContext()}getCallCredentials(){return this.callCredentials}destroy(){this.parent.unref()}};function Mq($,Y,X){return new M6($,Y,X!==null&&X!==void 0?X:{})}class P9 extends IY{constructor($,Y){super();if(this.channelCredentials=$,this.callCredentials=Y,!$._isSecure())throw Error("Cannot compose insecure credentials")}compose($){let Y=this.callCredentials.compose($);return new P9(this.channelCredentials,Y)}_isSecure(){return!0}_equals($){if(this===$)return!0;if($ instanceof P9)return this.channelCredentials._equals($.channelCredentials)&&this.callCredentials._equals($.callCredentials);else return!1}_createSecureConnector($,Y,X){let Q=this.callCredentials.compose(X!==null&&X!==void 0?X:L9.CallCredentials.createEmpty());return this.channelCredentials._createSecureConnector($,Y,Q)}}});var M$=M((tT)=>{Object.defineProperty(tT,"__esModule",{value:!0});tT.createChildChannelControlHelper=Pq;tT.registerLoadBalancerType=Lq;tT.registerDefaultLoadBalancerType=Sq;tT.createLoadBalancer=wq;tT.isLoadBalancerNameRegistered=Cq;tT.parseLoadBalancingConfig=aT;tT.getDefaultConfig=yq;tT.selectLbConfigFromList=jq;var Iq=Z0(),Oq=i();function Pq($,Y){var X,Q,J,Z,T,K,U,G,W,R;return{createSubchannel:(Q=(X=Y.createSubchannel)===null||X===void 0?void 0:X.bind(Y))!==null&&Q!==void 0?Q:$.createSubchannel.bind($),updateState:(Z=(J=Y.updateState)===null||J===void 0?void 0:J.bind(Y))!==null&&Z!==void 0?Z:$.updateState.bind($),requestReresolution:(K=(T=Y.requestReresolution)===null||T===void 0?void 0:T.bind(Y))!==null&&K!==void 0?K:$.requestReresolution.bind($),addChannelzChild:(G=(U=Y.addChannelzChild)===null||U===void 0?void 0:U.bind(Y))!==null&&G!==void 0?G:$.addChannelzChild.bind($),removeChannelzChild:(R=(W=Y.removeChannelzChild)===null||W===void 0?void 0:W.bind(Y))!==null&&R!==void 0?R:$.removeChannelzChild.bind($)}}var N$={},I6=null;function Lq($,Y,X){N$[$]={LoadBalancer:Y,LoadBalancingConfig:X}}function Sq($){I6=$}function wq($,Y){let X=$.getLoadBalancerName();if(X in N$)return new N$[X].LoadBalancer(Y);else return null}function Cq($){return $ in N$}function aT($){let Y=Object.keys($);if(Y.length!==1)throw Error("Provided load balancing config has multiple conflicting entries");let X=Y[0];if(X in N$)try{return N$[X].LoadBalancingConfig.createFromJson($[X])}catch(Q){throw Error(`${X}: ${Q.message}`)}else throw Error(`Unrecognized load balancing config name ${X}`)}function yq(){if(!I6)throw Error("No default load balancer type registered");return new N$[I6].LoadBalancingConfig}function jq($,Y=!1){for(let X of $)try{return aT(X)}catch(Q){(0,Iq.log)(Oq.LogVerbosity.DEBUG,"Config parsing failed with error",Q.message);continue}if(Y)if(I6)return new N$[I6].LoadBalancingConfig;else return null;else return null}});var p5=M((YK)=>{Object.defineProperty(YK,"__esModule",{value:!0});YK.validateRetryThrottling=eT;YK.validateServiceConfig=$K;YK.extractAndSelectServiceConfig=oq;var bq=s("os"),S9=i(),w9=/^\d+(\.\d{1,9})?s$/,uq="node";function dq($){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 pq($){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"||!w9.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"||!w9.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 Y of $.retryableStatusCodes)if(typeof Y==="number"){if(!Object.values(S9.Status).includes(Y))throw Error("Invalid method config retry policy: retryableStatusCodes value not in status code range")}else if(typeof Y==="string"){if(!Object.values(S9.Status).includes(Y.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 cq($){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"||!w9.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 X of $.nonFatalStatusCodes)if(typeof X==="number"){if(!Object.values(S9.Status).includes(X))throw Error("Invalid method config hedging policy: nonFatalStatusCodes value not in status code range")}else if(typeof X==="string"){if(!Object.values(S9.Status).includes(X.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 Y={maxAttempts:$.maxAttempts};if($.hedgingDelay)Y.hedgingDelay=$.hedgingDelay;if($.nonFatalStatusCodes)Y.nonFatalStatusCodes=$.nonFatalStatusCodes;return Y}function nq($){var Y;let X={name:[]};if(!("name"in $)||!Array.isArray($.name))throw Error("Invalid method config: invalid name array");for(let Q of $.name)X.name.push(dq(Q));if("waitForReady"in $){if(typeof $.waitForReady!=="boolean")throw Error("Invalid method config: invalid waitForReady");X.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");X.timeout=$.timeout}else if(typeof $.timeout==="string"&&w9.test($.timeout)){let Q=$.timeout.substring(0,$.timeout.length-1).split(".");X.timeout={seconds:Q[0]|0,nanos:((Y=Q[1])!==null&&Y!==void 0?Y:0)|0}}else throw Error("Invalid method config: invalid timeout");if("maxRequestBytes"in $){if(typeof $.maxRequestBytes!=="number")throw Error("Invalid method config: invalid maxRequestBytes");X.maxRequestBytes=$.maxRequestBytes}if("maxResponseBytes"in $){if(typeof $.maxResponseBytes!=="number")throw Error("Invalid method config: invalid maxRequestBytes");X.maxResponseBytes=$.maxResponseBytes}if("retryPolicy"in $)if("hedgingPolicy"in $)throw Error("Invalid method config: retryPolicy and hedgingPolicy cannot both be specified");else X.retryPolicy=pq($.retryPolicy);else if("hedgingPolicy"in $)X.hedgingPolicy=cq($.hedgingPolicy);return X}function eT($){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 lq($){if(!(typeof $==="object"&&$!==null))throw Error(`Invalid loadBalancingConfig: unexpected type ${typeof $}`);let Y=Object.keys($);if(Y.length>1)throw Error(`Invalid loadBalancingConfig: unexpected multiple keys ${Y}`);if(Y.length===0)throw Error("Invalid loadBalancingConfig: load balancing policy name required");return{[Y[0]]:$[Y[0]]}}function $K($){let Y={loadBalancingConfig:[],methodConfig:[]};if("loadBalancingPolicy"in $)if(typeof $.loadBalancingPolicy==="string")Y.loadBalancingPolicy=$.loadBalancingPolicy;else throw Error("Invalid service config: invalid loadBalancingPolicy");if("loadBalancingConfig"in $)if(Array.isArray($.loadBalancingConfig))for(let Q of $.loadBalancingConfig)Y.loadBalancingConfig.push(lq(Q));else throw Error("Invalid service config: invalid loadBalancingConfig");if("methodConfig"in $){if(Array.isArray($.methodConfig))for(let Q of $.methodConfig)Y.methodConfig.push(nq(Q))}if("retryThrottling"in $)Y.retryThrottling=eT($.retryThrottling);let X=[];for(let Q of Y.methodConfig)for(let J of Q.name){for(let Z of X)if(J.service===Z.service&&J.method===Z.method)throw Error(`Invalid service config: duplicate name ${J.service}/${J.method}`);X.push(J)}return Y}function iq($){if(!("serviceConfig"in $))throw Error("Invalid service config choice: missing service config");let Y={serviceConfig:$K($.serviceConfig)};if("clientLanguage"in $)if(Array.isArray($.clientLanguage)){Y.clientLanguage=[];for(let Q of $.clientLanguage)if(typeof Q==="string")Y.clientLanguage.push(Q);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)){Y.clientHostname=[];for(let Q of $.clientHostname)if(typeof Q==="string")Y.clientHostname.push(Q);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)Y.percentage=$.percentage;else throw Error("Invalid service config choice: invalid percentage");let X=["clientLanguage","percentage","clientHostname","serviceConfig"];for(let Q in $)if(!X.includes(Q))throw Error(`Invalid service config choice: unexpected field ${Q}`);return Y}function rq($,Y){if(!Array.isArray($))throw Error("Invalid service config list");for(let X of $){let Q=iq(X);if(typeof Q.percentage==="number"&&Y>Q.percentage)continue;if(Array.isArray(Q.clientHostname)){let J=!1;for(let Z of Q.clientHostname)if(Z===bq.hostname())J=!0;if(!J)continue}if(Array.isArray(Q.clientLanguage)){let J=!1;for(let Z of Q.clientLanguage)if(Z===uq)J=!0;if(!J)continue}return Q.serviceConfig}throw Error("No matching service config found")}function oq($,Y){for(let X of $)if(X.length>0&&X[0].startsWith("grpc_config=")){let Q=X.join("").substring(12),J=JSON.parse(Q);return rq(J,Y)}return null}});var n0=M((QK)=>{Object.defineProperty(QK,"__esModule",{value:!0});QK.ConnectivityState=void 0;var XK;(function($){$[$.IDLE=0]="IDLE",$[$.CONNECTING=1]="CONNECTING",$[$.READY=2]="READY",$[$.TRANSIENT_FAILURE=3]="TRANSIENT_FAILURE",$[$.SHUTDOWN=4]="SHUTDOWN"})(XK||(QK.ConnectivityState=XK={}))});var Y$=M((KK)=>{Object.defineProperty(KK,"__esModule",{value:!0});KK.QueuePicker=KK.UnavailablePicker=KK.PickResultType=void 0;var eq=P0(),$N=i(),C9;(function($){$[$.COMPLETE=0]="COMPLETE",$[$.QUEUE=1]="QUEUE",$[$.TRANSIENT_FAILURE=2]="TRANSIENT_FAILURE",$[$.DROP=3]="DROP"})(C9||(KK.PickResultType=C9={}));class ZK{constructor($){this.status=Object.assign({code:$N.Status.UNAVAILABLE,details:"No connection established",metadata:new eq.Metadata},$)}pick($){return{pickResultType:C9.TRANSIENT_FAILURE,subchannel:null,status:this.status,onCallStarted:null,onCallEnded:null}}}KK.UnavailablePicker=ZK;class TK{constructor($,Y){this.loadBalancer=$,this.childPicker=Y,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:C9.QUEUE,subchannel:null,status:null,onCallStarted:null,onCallEnded:null}}}KK.QueuePicker=TK});var PY=M((GK)=>{Object.defineProperty(GK,"__esModule",{value:!0});GK.BackoffTimeout=void 0;var QN=i(),JN=Z0(),ZN="backoff",TN=1000,KN=1.6,UN=120000,GN=0.2;function WN($,Y){return Math.random()*(Y-$)+$}class y9{constructor($,Y){if(this.callback=$,this.initialDelay=TN,this.multiplier=KN,this.maxDelay=UN,this.jitter=GN,this.running=!1,this.hasRef=!0,this.startTime=new Date,this.endTime=new Date,this.id=y9.getNextId(),Y){if(Y.initialDelay)this.initialDelay=Y.initialDelay;if(Y.multiplier)this.multiplier=Y.multiplier;if(Y.jitter)this.jitter=Y.jitter;if(Y.maxDelay)this.maxDelay=Y.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($){JN.trace(QN.LogVerbosity.DEBUG,ZN,"{"+this.id+"} "+$)}runTimer($){var Y,X;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)(X=(Y=this.timerId).unref)===null||X===void 0||X.call(Y)}runOnce(){this.trace("runOnce()"),this.running=!0,this.startTime=new Date,this.runTimer(this.nextDelay);let $=Math.min(this.nextDelay*this.multiplier,this.maxDelay),Y=$*this.jitter;this.nextDelay=$+WN(-Y,Y)}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,Y=this.startTime;if(Y.setMilliseconds(Y.getMilliseconds()+this.nextDelay),clearTimeout(this.timerId),$<Y)this.runTimer(Y.getTime()-$.getTime());else this.running=!1}}isRunning(){return this.running}ref(){var $,Y;this.hasRef=!0,(Y=($=this.timerId).ref)===null||Y===void 0||Y.call($)}unref(){var $,Y;this.hasRef=!1,(Y=($=this.timerId).unref)===null||Y===void 0||Y.call($)}getEndTime(){return this.endTime}}GK.BackoffTimeout=y9;y9.nextId=0});var j9=M((EK)=>{Object.defineProperty(EK,"__esModule",{value:!0});EK.ChildLoadBalancerHandler=void 0;var RN=M$(),EN=n0(),VN="child_load_balancer_helper";class RK{constructor($){this.channelControlHelper=$,this.currentChild=null,this.pendingChild=null,this.latestConfig=null,this.ChildPolicyHelper=class{constructor(Y){this.parent=Y,this.child=null}createSubchannel(Y,X){return this.parent.channelControlHelper.createSubchannel(Y,X)}updateState(Y,X,Q){var J;if(this.calledByPendingChild()){if(Y===EN.ConnectivityState.CONNECTING)return;(J=this.parent.currentChild)===null||J===void 0||J.destroy(),this.parent.currentChild=this.parent.pendingChild,this.parent.pendingChild=null}else if(!this.calledByCurrentChild())return;this.parent.channelControlHelper.updateState(Y,X,Q)}requestReresolution(){var Y;let X=(Y=this.parent.pendingChild)!==null&&Y!==void 0?Y:this.parent.currentChild;if(this.child===X)this.parent.channelControlHelper.requestReresolution()}setChild(Y){this.child=Y}addChannelzChild(Y){this.parent.channelControlHelper.addChannelzChild(Y)}removeChannelzChild(Y){this.parent.channelControlHelper.removeChannelzChild(Y)}calledByPendingChild(){return this.child===this.parent.pendingChild}calledByCurrentChild(){return this.child===this.parent.currentChild}}}configUpdateRequiresNewPolicyInstance($,Y){return $.getLoadBalancerName()!==Y.getLoadBalancerName()}updateAddressList($,Y,X,Q){let J;if(this.currentChild===null||this.latestConfig===null||this.configUpdateRequiresNewPolicyInstance(this.latestConfig,Y)){let Z=new this.ChildPolicyHelper(this),T=(0,RN.createLoadBalancer)(Y,Z);if(Z.setChild(T),this.currentChild===null)this.currentChild=T,J=this.currentChild;else{if(this.pendingChild)this.pendingChild.destroy();this.pendingChild=T,J=this.pendingChild}}else if(this.pendingChild===null)J=this.currentChild;else J=this.pendingChild;return this.latestConfig=Y,J.updateAddressList($,Y,X,Q)}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 VN}}EK.ChildLoadBalancerHandler=RK});var qK=M((HK)=>{Object.defineProperty(HK,"__esModule",{value:!0});HK.ResolvingLoadBalancer=void 0;var AN=M$(),DN=p5(),i0=n0(),AK=M1(),O6=Y$(),FN=PY(),c5=i(),HN=P0(),zN=Z0(),qN=i(),NN=c0(),MN=j9(),BN="resolving_load_balancer";function DK($){zN.trace(qN.LogVerbosity.DEBUG,BN,$)}var IN=["SERVICE_AND_METHOD","SERVICE","EMPTY"];function ON($,Y,X,Q){for(let J of X.name)switch(Q){case"EMPTY":if(!J.service&&!J.method)return!0;break;case"SERVICE":if(J.service===$&&!J.method)return!0;break;case"SERVICE_AND_METHOD":if(J.service===$&&J.method===Y)return!0}return!1}function PN($,Y,X,Q){for(let J of X)if(ON($,Y,J,Q))return J;return null}function LN($){return{invoke(Y,X){var Q,J;let Z=Y.split("/").filter((U)=>U.length>0),T=(Q=Z[0])!==null&&Q!==void 0?Q:"",K=(J=Z[1])!==null&&J!==void 0?J:"";if($&&$.methodConfig)for(let U of IN){let G=PN(T,K,$.methodConfig,U);if(G)return{methodConfig:G,pickInformation:{},status:c5.Status.OK,dynamicFilterFactories:[]}}return{methodConfig:{name:[]},pickInformation:{},status:c5.Status.OK,dynamicFilterFactories:[]}},unref(){}}}class FK{constructor($,Y,X,Q,J){if(this.target=$,this.channelControlHelper=Y,this.channelOptions=X,this.onSuccessfulResolution=Q,this.onFailedResolution=J,this.latestChildState=i0.ConnectivityState.IDLE,this.latestChildPicker=new O6.QueuePicker(this),this.latestChildErrorMessage=null,this.currentState=i0.ConnectivityState.IDLE,this.previousServiceConfig=null,this.continueResolving=!1,X["grpc.service_config"])this.defaultServiceConfig=(0,DN.validateServiceConfig)(JSON.parse(X["grpc.service_config"]));else this.defaultServiceConfig={loadBalancingConfig:[],methodConfig:[]};this.updateState(i0.ConnectivityState.IDLE,new O6.QueuePicker(this),null),this.childLoadBalancer=new MN.ChildLoadBalancerHandler({createSubchannel:Y.createSubchannel.bind(Y),requestReresolution:()=>{if(this.backoffTimeout.isRunning())DK("requestReresolution delayed by backoff timer until "+this.backoffTimeout.getEndTime().toISOString()),this.continueResolving=!0;else this.updateResolution()},updateState:(T,K,U)=>{this.latestChildState=T,this.latestChildPicker=K,this.latestChildErrorMessage=U,this.updateState(T,K,U)},addChannelzChild:Y.addChannelzChild.bind(Y),removeChannelzChild:Y.removeChannelzChild.bind(Y)}),this.innerResolver=(0,AK.createResolver)($,this.handleResolverResult.bind(this),X);let Z={initialDelay:X["grpc.initial_reconnect_backoff_ms"],maxDelay:X["grpc.max_reconnect_backoff_ms"]};this.backoffTimeout=new FN.BackoffTimeout(()=>{if(this.continueResolving)this.updateResolution(),this.continueResolving=!1;else this.updateState(this.latestChildState,this.latestChildPicker,this.latestChildErrorMessage)},Z),this.backoffTimeout.unref()}handleResolverResult($,Y,X,Q){var J,Z;this.backoffTimeout.stop(),this.backoffTimeout.reset();let T=!0,K=null;if(X===null)K=this.defaultServiceConfig;else if(X.ok)K=X.value;else if(this.previousServiceConfig!==null)K=this.previousServiceConfig;else T=!1,this.handleResolutionFailure(X.error);if(K!==null){let U=(J=K===null||K===void 0?void 0:K.loadBalancingConfig)!==null&&J!==void 0?J:[],G=(0,AN.selectLbConfigFromList)(U,!0);if(G===null)T=!1,this.handleResolutionFailure({code:c5.Status.UNAVAILABLE,details:"All load balancer options in service config are not compatible",metadata:new HN.Metadata});else T=this.childLoadBalancer.updateAddressList($,G,Object.assign(Object.assign({},this.channelOptions),Y),Q)}if(T)this.onSuccessfulResolution(K,(Z=Y[AK.CHANNEL_ARGS_CONFIG_SELECTOR_KEY])!==null&&Z!==void 0?Z:LN(K));return T}updateResolution(){if(this.innerResolver.updateResolution(),this.currentState===i0.ConnectivityState.IDLE)this.updateState(i0.ConnectivityState.CONNECTING,this.latestChildPicker,this.latestChildErrorMessage);this.backoffTimeout.runOnce()}updateState($,Y,X){if(DK((0,NN.uriToString)(this.target)+" "+i0.ConnectivityState[this.currentState]+" -> "+i0.ConnectivityState[$]),$===i0.ConnectivityState.IDLE)Y=new O6.QueuePicker(this,Y);this.currentState=$,this.channelControlHelper.updateState($,Y,X)}handleResolutionFailure($){if(this.latestChildState===i0.ConnectivityState.IDLE)this.updateState(i0.ConnectivityState.TRANSIENT_FAILURE,new O6.UnavailablePicker($),$.details),this.onFailedResolution($)}exitIdle(){if(this.currentState===i0.ConnectivityState.IDLE||this.currentState===i0.ConnectivityState.TRANSIENT_FAILURE)if(this.backoffTimeout.isRunning())this.continueResolving=!0;else this.updateResolution();this.childLoadBalancer.exitIdle()}updateAddressList($,Y){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=i0.ConnectivityState.IDLE,this.latestChildPicker=new O6.QueuePicker(this),this.currentState=i0.ConnectivityState.IDLE,this.previousServiceConfig=null,this.continueResolving=!1}getTypeName(){return"resolving_load_balancer"}}HK.ResolvingLoadBalancer=FK});var BK=M((NK)=>{Object.defineProperty(NK,"__esModule",{value:!0});NK.recognizedOptions=void 0;NK.channelOptionsEqual=SN;NK.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 SN($,Y){let X=Object.keys($).sort(),Q=Object.keys(Y).sort();if(X.length!==Q.length)return!1;for(let J=0;J<X.length;J+=1){if(X[J]!==Q[J])return!1;if($[X[J]]!==Y[Q[J]])return!1}return!0}});var r0=M((SK)=>{Object.defineProperty(SK,"__esModule",{value:!0});SK.EndpointMap=void 0;SK.isTcpSubchannelAddress=L6;SK.subchannelAddressEqual=x9;SK.subchannelAddressToString=OK;SK.stringToSubchannelAddress=yN;SK.endpointEqual=jN;SK.endpointToString=xN;SK.endpointHasAddress=PK;var IK=s("net");function L6($){return"port"in $}function x9($,Y){if(!$&&!Y)return!0;if(!$||!Y)return!1;if(L6($))return L6(Y)&&$.host===Y.host&&$.port===Y.port;else return!L6(Y)&&$.path===Y.path}function OK($){if(L6($))if((0,IK.isIPv6)($.host))return"["+$.host+"]:"+$.port;else return $.host+":"+$.port;else return $.path}var CN=443;function yN($,Y){if((0,IK.isIP)($))return{host:$,port:Y!==null&&Y!==void 0?Y:CN};else return{path:$}}function jN($,Y){if($.addresses.length!==Y.addresses.length)return!1;for(let X=0;X<$.addresses.length;X++)if(!x9($.addresses[X],Y.addresses[X]))return!1;return!0}function xN($){return"["+$.addresses.map(OK).join(", ")+"]"}function PK($,Y){for(let X of $.addresses)if(x9(X,Y))return!0;return!1}function P6($,Y){if($.addresses.length!==Y.addresses.length)return!1;for(let X of $.addresses){let Q=!1;for(let J of Y.addresses)if(x9(X,J)){Q=!0;break}if(!Q)return!1}return!0}class LK{constructor(){this.map=new Set}get size(){return this.map.size}getForSubchannelAddress($){for(let Y of this.map)if(PK(Y.key,$))return Y.value;return}deleteMissing($){let Y=[];for(let X of this.map){let Q=!1;for(let J of $)if(P6(J,X.key))Q=!0;if(!Q)Y.push(X.value),this.map.delete(X)}return Y}get($){for(let Y of this.map)if(P6($,Y.key))return Y.value;return}set($,Y){for(let X of this.map)if(P6($,X.key)){X.value=Y;return}this.map.add({key:$,value:Y})}delete($){for(let Y of this.map)if(P6($,Y.key)){this.map.delete(Y);return}}has($){for(let Y of this.map)if(P6($,Y.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]}}SK.EndpointMap=LK});var gK=M((_K)=>{Object.defineProperty(_K,"t",{value:!0});class n5{constructor($,Y,X=1){this.i=void 0,this.h=void 0,this.o=void 0,this.u=$,this.l=Y,this.p=X}I(){let $=this,Y=$.o.o===$;if(Y&&$.p===1)$=$.h;else if($.i){$=$.i;while($.h)$=$.h}else{if(Y)return $.o;let X=$.o;while(X.i===$)$=X,X=$.o;$=X}return $}B(){let $=this;if($.h){$=$.h;while($.i)$=$.i;return $}else{let Y=$.o;while(Y.h===$)$=Y,Y=$.o;if($.h!==Y)return Y;else return $}}_(){let $=this.o,Y=this.h,X=Y.i;if($.o===this)$.o=Y;else if($.i===this)$.i=Y;else $.h=Y;if(Y.o=$,Y.i=this,this.o=Y,this.h=X,X)X.o=this;return Y}g(){let $=this.o,Y=this.i,X=Y.h;if($.o===this)$.o=Y;else if($.i===this)$.i=Y;else $.h=Y;if(Y.o=$,Y.h=this,this.o=Y,this.i=X,X)X.o=this;return Y}}class CK extends n5{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 yK{constructor($=0){this.iteratorType=$}equals($){return this.T===$.T}}class jK{constructor(){this.m=0}get length(){return this.m}size(){return this.m}empty(){return this.m===0}}class xK extends jK{}function n$(){throw RangeError("Iterator access denied!")}class vK extends xK{constructor($=function(X,Q){if(X<Q)return-1;if(X>Q)return 1;return 0},Y=!1){super();this.v=void 0,this.A=$,this.enableIndex=Y,this.N=Y?CK:n5,this.C=new this.N}R($,Y){let X=this.C;while($){let Q=this.A($.u,Y);if(Q<0)$=$.h;else if(Q>0)X=$,$=$.i;else return $}return X}K($,Y){let X=this.C;while($)if(this.A($.u,Y)<=0)$=$.h;else X=$,$=$.i;return X}L($,Y){let X=this.C;while($){let Q=this.A($.u,Y);if(Q<0)X=$,$=$.h;else if(Q>0)$=$.i;else return $}return X}k($,Y){let X=this.C;while($)if(this.A($.u,Y)<0)X=$,$=$.h;else $=$.i;return X}P($){while(!0){let Y=$.o;if(Y===this.C)return;if($.p===1){$.p=0;return}if($===Y.i){let X=Y.h;if(X.p===1)if(X.p=0,Y.p=1,Y===this.v)this.v=Y._();else Y._();else if(X.h&&X.h.p===1){if(X.p=Y.p,Y.p=0,X.h.p=0,Y===this.v)this.v=Y._();else Y._();return}else if(X.i&&X.i.p===1)X.p=1,X.i.p=0,X.g();else X.p=1,$=Y}else{let X=Y.i;if(X.p===1)if(X.p=0,Y.p=1,Y===this.v)this.v=Y.g();else Y.g();else if(X.i&&X.i.p===1){if(X.p=Y.p,Y.p=0,X.i.p=0,Y===this.v)this.v=Y.g();else Y.g();return}else if(X.h&&X.h.p===1)X.p=1,X.h.p=0,X._();else X.p=1,$=Y}}}S($){if(this.m===1){this.clear();return}let Y=$;while(Y.i||Y.h){if(Y.h){Y=Y.h;while(Y.i)Y=Y.i}else Y=Y.i;let Q=$.u;$.u=Y.u,Y.u=Q;let J=$.l;$.l=Y.l,Y.l=J,$=Y}if(this.C.i===Y)this.C.i=Y.o;else if(this.C.h===Y)this.C.h=Y.o;this.P(Y);let X=Y.o;if(Y===X.i)X.i=void 0;else X.h=void 0;if(this.m-=1,this.v.p=0,this.enableIndex)while(X!==this.C)X.M-=1,X=X.o}U($){let Y=typeof $==="number"?$:void 0,X=typeof $==="function"?$:void 0,Q=typeof $>"u"?[]:void 0,J=0,Z=this.v,T=[];while(T.length||Z)if(Z)T.push(Z),Z=Z.i;else{if(Z=T.pop(),J===Y)return Z;Q&&Q.push(Z),X&&X(Z,J,this),J+=1,Z=Z.h}return Q}j($){while(!0){let Y=$.o;if(Y.p===0)return;let X=Y.o;if(Y===X.i){let Q=X.h;if(Q&&Q.p===1){if(Q.p=Y.p=0,X===this.v)return;X.p=1,$=X;continue}else if($===Y.h){if($.p=0,$.i)$.i.o=Y;if($.h)$.h.o=X;if(Y.h=$.i,X.i=$.h,$.i=Y,$.h=X,X===this.v)this.v=$,this.C.o=$;else{let J=X.o;if(J.i===X)J.i=$;else J.h=$}$.o=X.o,Y.o=$,X.o=$,X.p=1}else{if(Y.p=0,X===this.v)this.v=X.g();else X.g();X.p=1;return}}else{let Q=X.i;if(Q&&Q.p===1){if(Q.p=Y.p=0,X===this.v)return;X.p=1,$=X;continue}else if($===Y.i){if($.p=0,$.i)$.i.o=X;if($.h)$.h.o=Y;if(X.h=$.i,Y.i=$.h,$.i=X,$.h=Y,X===this.v)this.v=$,this.C.o=$;else{let J=X.o;if(J.i===X)J.i=$;else J.h=$}$.o=X.o,Y.o=$,X.o=$,X.p=1}else{if(Y.p=0,X===this.v)this.v=X._();else X._();X.p=1;return}}if(this.enableIndex)Y.O(),X.O(),$.O();return}}q($,Y,X){if(this.v===void 0)return this.m+=1,this.v=new this.N($,Y,0),this.v.o=this.C,this.C.o=this.C.i=this.C.h=this.v,this.m;let Q,J=this.C.i,Z=this.A(J.u,$);if(Z===0)return J.l=Y,this.m;else if(Z>0)J.i=new this.N($,Y),J.i.o=J,Q=J.i,this.C.i=Q;else{let T=this.C.h,K=this.A(T.u,$);if(K===0)return T.l=Y,this.m;else if(K<0)T.h=new this.N($,Y),T.h.o=T,Q=T.h,this.C.h=Q;else{if(X!==void 0){let U=X.T;if(U!==this.C){let G=this.A(U.u,$);if(G===0)return U.l=Y,this.m;else if(G>0){let W=U.I(),R=this.A(W.u,$);if(R===0)return W.l=Y,this.m;else if(R<0)if(Q=new this.N($,Y),W.h===void 0)W.h=Q,Q.o=W;else U.i=Q,Q.o=U}}}if(Q===void 0){Q=this.v;while(!0){let U=this.A(Q.u,$);if(U>0){if(Q.i===void 0){Q.i=new this.N($,Y),Q.i.o=Q,Q=Q.i;break}Q=Q.i}else if(U<0){if(Q.h===void 0){Q.h=new this.N($,Y),Q.h.o=Q,Q=Q.h;break}Q=Q.h}else return Q.l=Y,this.m}}}}if(this.enableIndex){let T=Q.o;while(T!==this.C)T.M+=1,T=T.o}return this.j(Q),this.m+=1,this.m}H($,Y){while($){let X=this.A($.u,Y);if(X<0)$=$.h;else if(X>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($,Y){let X=$.T;if(X===this.C)n$();if(this.m===1)return X.u=Y,!0;let Q=X.B().u;if(X===this.C.i){if(this.A(Q,Y)>0)return X.u=Y,!0;return!1}let J=X.I().u;if(X===this.C.h){if(this.A(J,Y)<0)return X.u=Y,!0;return!1}if(this.A(J,Y)>=0||this.A(Q,Y)<=0)return!1;return X.u=Y,!0}eraseElementByPos($){if($<0||$>this.m-1)throw RangeError();let Y=this.U($);return this.S(Y),this.m}eraseElementByKey($){if(this.m===0)return!1;let Y=this.H(this.v,$);if(Y===this.C)return!1;return this.S(Y),!0}eraseElementByIterator($){let Y=$.T;if(Y===this.C)n$();let X=Y.h===void 0;if($.iteratorType===0){if(X)$.next()}else if(!X||Y.i===void 0)$.next();return this.S(Y),$}getHeight(){if(this.m===0)return 0;function $(Y){if(!Y)return 0;return Math.max($(Y.i),$(Y.h))+1}return $(this.v)}}class kK extends yK{constructor($,Y,X){super(X);if(this.T=$,this.C=Y,this.iteratorType===0)this.pre=function(){if(this.T===this.C.i)n$();return this.T=this.T.I(),this},this.next=function(){if(this.T===this.C)n$();return this.T=this.T.B(),this};else this.pre=function(){if(this.T===this.C.h)n$();return this.T=this.T.B(),this},this.next=function(){if(this.T===this.C)n$();return this.T=this.T.I(),this}}get index(){let $=this.T,Y=this.C.o;if($===this.C){if(Y)return Y.M-1;return 0}let X=0;if($.i)X+=$.i.M;while($!==Y){let Q=$.o;if($===Q.h){if(X+=1,Q.i)X+=Q.i.M}$=Q}return X}isAccessible(){return this.T!==this.C}}class B1 extends kK{constructor($,Y,X,Q){super($,Y,Q);this.container=X}get pointer(){if(this.T===this.C)n$();let $=this;return new Proxy([],{get(Y,X){if(X==="0")return $.T.u;else if(X==="1")return $.T.l;return Y[0]=$.T.u,Y[1]=$.T.l,Y[X]},set(Y,X,Q){if(X!=="1")throw TypeError("prop must be 1");return $.T.l=Q,!0}})}copy(){return new B1(this.T,this.C,this.container,this.iteratorType)}}class hK extends vK{constructor($=[],Y,X){super(Y,X);let Q=this;$.forEach(function(J){Q.setElement(J[0],J[1])})}begin(){return new B1(this.C.i||this.C,this.C,this)}end(){return new B1(this.C,this.C,this)}rBegin(){return new B1(this.C.h||this.C,this.C,this,1)}rEnd(){return new B1(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 Y=this.R(this.v,$);return new B1(Y,this.C,this)}upperBound($){let Y=this.K(this.v,$);return new B1(Y,this.C,this)}reverseLowerBound($){let Y=this.L(this.v,$);return new B1(Y,this.C,this)}reverseUpperBound($){let Y=this.k(this.v,$);return new B1(Y,this.C,this)}forEach($){this.U(function(Y,X,Q){$([Y.u,Y.l],X,Q)})}setElement($,Y,X){return this.q($,Y,X)}getElementByPos($){if($<0||$>this.m-1)throw RangeError();let Y=this.U($);return[Y.u,Y.l]}find($){let Y=this.H(this.v,$);return new B1(Y,this.C,this)}getElementByKey($){return this.H(this.v,$).l}union($){let Y=this;return $.forEach(function(X){Y.setElement(X[0],X[1])}),this.m}*[Symbol.iterator](){let $=this.m,Y=this.U();for(let X=0;X<$;++X){let Q=Y[X];yield[Q.u,Q.l]}}}_K.OrderedMap=hK});var v9=M((mK)=>{Object.defineProperty(mK,"__esModule",{value:!0});mK.registerAdminService=uN;mK.addAdminServicesToServer=dN;var fK=[];function uN($,Y){fK.push({getServiceDefinition:$,getHandlers:Y})}function dN($){for(let{getServiceDefinition:Y,getHandlers:X}of fK)$.addService(Y(),X())}});var lK=M((cK)=>{Object.defineProperty(cK,"__esModule",{value:!0});cK.ClientDuplexStreamImpl=cK.ClientWritableStreamImpl=cK.ClientReadableStreamImpl=cK.ClientUnaryCallImpl=void 0;cK.callErrorFromStatus=lN;var nN=s("events"),l5=s("stream"),S6=i();function lN($,Y){let X=`${$.code} ${S6.Status[$.code]}: ${$.details}`,J=`${Error(X).stack}
|
|
2
|
+
for call at
|
|
3
|
+
${Y}`;return Object.assign(Error(X),$,{stack:J})}class bK extends nN.EventEmitter{constructor(){super()}cancel(){var $;($=this.call)===null||$===void 0||$.cancelWithStatus(S6.Status.CANCELLED,"Cancelled on client")}getPeer(){var $,Y;return(Y=($=this.call)===null||$===void 0?void 0:$.getPeer())!==null&&Y!==void 0?Y:"unknown"}getAuthContext(){var $,Y;return(Y=($=this.call)===null||$===void 0?void 0:$.getAuthContext())!==null&&Y!==void 0?Y:null}}cK.ClientUnaryCallImpl=bK;class uK extends l5.Readable{constructor($){super({objectMode:!0});this.deserialize=$}cancel(){var $;($=this.call)===null||$===void 0||$.cancelWithStatus(S6.Status.CANCELLED,"Cancelled on client")}getPeer(){var $,Y;return(Y=($=this.call)===null||$===void 0?void 0:$.getPeer())!==null&&Y!==void 0?Y:"unknown"}getAuthContext(){var $,Y;return(Y=($=this.call)===null||$===void 0?void 0:$.getAuthContext())!==null&&Y!==void 0?Y:null}_read($){var Y;(Y=this.call)===null||Y===void 0||Y.startRead()}}cK.ClientReadableStreamImpl=uK;class dK extends l5.Writable{constructor($){super({objectMode:!0});this.serialize=$}cancel(){var $;($=this.call)===null||$===void 0||$.cancelWithStatus(S6.Status.CANCELLED,"Cancelled on client")}getPeer(){var $,Y;return(Y=($=this.call)===null||$===void 0?void 0:$.getPeer())!==null&&Y!==void 0?Y:"unknown"}getAuthContext(){var $,Y;return(Y=($=this.call)===null||$===void 0?void 0:$.getAuthContext())!==null&&Y!==void 0?Y:null}_write($,Y,X){var Q;let J={callback:X},Z=Number(Y);if(!Number.isNaN(Z))J.flags=Z;(Q=this.call)===null||Q===void 0||Q.sendMessageWithContext(J,$)}_final($){var Y;(Y=this.call)===null||Y===void 0||Y.halfClose(),$()}}cK.ClientWritableStreamImpl=dK;class pK extends l5.Duplex{constructor($,Y){super({objectMode:!0});this.serialize=$,this.deserialize=Y}cancel(){var $;($=this.call)===null||$===void 0||$.cancelWithStatus(S6.Status.CANCELLED,"Cancelled on client")}getPeer(){var $,Y;return(Y=($=this.call)===null||$===void 0?void 0:$.getPeer())!==null&&Y!==void 0?Y:"unknown"}getAuthContext(){var $,Y;return(Y=($=this.call)===null||$===void 0?void 0:$.getAuthContext())!==null&&Y!==void 0?Y:null}_read($){var Y;(Y=this.call)===null||Y===void 0||Y.startRead()}_write($,Y,X){var Q;let J={callback:X},Z=Number(Y);if(!Number.isNaN(Z))J.flags=Z;(Q=this.call)===null||Q===void 0||Q.sendMessageWithContext(J,$)}_final($){var Y;(Y=this.call)===null||Y===void 0||Y.halfClose(),$()}}cK.ClientDuplexStreamImpl=pK});var l$=M((rK)=>{Object.defineProperty(rK,"__esModule",{value:!0});rK.InterceptingListenerImpl=void 0;rK.statusOrFromValue=tN;rK.statusOrFromError=eN;rK.isInterceptingListener=$M;var aN=P0();function tN($){return{ok:!0,value:$}}function eN($){var Y;return{ok:!1,error:Object.assign(Object.assign({},$),{metadata:(Y=$.metadata)!==null&&Y!==void 0?Y:new aN.Metadata})}}function $M($){return $.onReceiveMetadata!==void 0&&$.onReceiveMetadata.length===1}class iK{constructor($,Y){this.listener=$,this.nextListener=Y,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($,(Y)=>{this.processingMetadata=!1,this.nextListener.onReceiveMetadata(Y),this.processPendingMessage(),this.processPendingStatus()})}onReceiveMessage($){this.processingMessage=!0,this.listener.onReceiveMessage($,(Y)=>{if(this.processingMessage=!1,this.processingMetadata)this.pendingMessage=Y,this.hasPendingMessage=!0;else this.nextListener.onReceiveMessage(Y),this.processPendingStatus()})}onReceiveStatus($){this.listener.onReceiveStatus($,(Y)=>{if(this.processingMetadata||this.processingMessage)this.pendingStatus=Y;else this.nextListener.onReceiveStatus(Y)})}}rK.InterceptingListenerImpl=iK});var o5=M((JU)=>{Object.defineProperty(JU,"__esModule",{value:!0});JU.InterceptingCall=JU.RequesterBuilder=JU.ListenerBuilder=JU.InterceptorConfigurationError=void 0;JU.getInterceptingCall=KM;var JM=P0(),sK=l$(),aK=i(),tK=q9();class C6 extends Error{constructor($){super($);this.name="InterceptorConfigurationError",Error.captureStackTrace(this,C6)}}JU.InterceptorConfigurationError=C6;class eK{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}}}JU.ListenerBuilder=eK;class $U{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}}}JU.RequesterBuilder=$U;var i5={onReceiveMetadata:($,Y)=>{Y($)},onReceiveMessage:($,Y)=>{Y($)},onReceiveStatus:($,Y)=>{Y($)}},w6={start:($,Y,X)=>{X($,Y)},sendMessage:($,Y)=>{Y($)},halfClose:($)=>{$()},cancel:($)=>{$()}};class YU{constructor($,Y){var X,Q,J,Z;if(this.nextCall=$,this.processingMetadata=!1,this.pendingMessageContext=null,this.processingMessage=!1,this.pendingHalfClose=!1,Y)this.requester={start:(X=Y.start)!==null&&X!==void 0?X:w6.start,sendMessage:(Q=Y.sendMessage)!==null&&Q!==void 0?Q:w6.sendMessage,halfClose:(J=Y.halfClose)!==null&&J!==void 0?J:w6.halfClose,cancel:(Z=Y.cancel)!==null&&Z!==void 0?Z:w6.cancel};else this.requester=w6}cancelWithStatus($,Y){this.requester.cancel(()=>{this.nextCall.cancelWithStatus($,Y)})}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($,Y){var X,Q,J,Z,T,K;let U={onReceiveMetadata:(Q=(X=Y===null||Y===void 0?void 0:Y.onReceiveMetadata)===null||X===void 0?void 0:X.bind(Y))!==null&&Q!==void 0?Q:(G)=>{},onReceiveMessage:(Z=(J=Y===null||Y===void 0?void 0:Y.onReceiveMessage)===null||J===void 0?void 0:J.bind(Y))!==null&&Z!==void 0?Z:(G)=>{},onReceiveStatus:(K=(T=Y===null||Y===void 0?void 0:Y.onReceiveStatus)===null||T===void 0?void 0:T.bind(Y))!==null&&K!==void 0?K:(G)=>{}};this.processingMetadata=!0,this.requester.start($,U,(G,W)=>{var R,V,A;this.processingMetadata=!1;let H;if((0,sK.isInterceptingListener)(W))H=W;else{let z={onReceiveMetadata:(R=W.onReceiveMetadata)!==null&&R!==void 0?R:i5.onReceiveMetadata,onReceiveMessage:(V=W.onReceiveMessage)!==null&&V!==void 0?V:i5.onReceiveMessage,onReceiveStatus:(A=W.onReceiveStatus)!==null&&A!==void 0?A:i5.onReceiveStatus};H=new sK.InterceptingListenerImpl(z,U)}this.nextCall.start(G,H),this.processPendingMessage(),this.processPendingHalfClose()})}sendMessageWithContext($,Y){this.processingMessage=!0,this.requester.sendMessage(Y,(X)=>{if(this.processingMessage=!1,this.processingMetadata)this.pendingMessageContext=$,this.pendingMessage=Y;else this.nextCall.sendMessageWithContext($,X),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()}}JU.InterceptingCall=YU;function ZM($,Y,X){var Q,J;let Z=(Q=X.deadline)!==null&&Q!==void 0?Q:1/0,T=X.host,K=(J=X.parent)!==null&&J!==void 0?J:null,U=X.propagate_flags,G=X.credentials,W=$.createCall(Y,Z,T,K,U);if(G)W.setCredentials(G);return W}class r5{constructor($,Y){this.call=$,this.methodDefinition=Y}cancelWithStatus($,Y){this.call.cancelWithStatus($,Y)}getPeer(){return this.call.getPeer()}sendMessageWithContext($,Y){let X;try{X=this.methodDefinition.requestSerialize(Y)}catch(Q){this.call.cancelWithStatus(aK.Status.INTERNAL,`Request message serialization failure: ${(0,tK.getErrorMessage)(Q)}`);return}this.call.sendMessageWithContext($,X)}sendMessage($){this.sendMessageWithContext({},$)}start($,Y){let X=null;this.call.start($,{onReceiveMetadata:(Q)=>{var J;(J=Y===null||Y===void 0?void 0:Y.onReceiveMetadata)===null||J===void 0||J.call(Y,Q)},onReceiveMessage:(Q)=>{var J;let Z;try{Z=this.methodDefinition.responseDeserialize(Q)}catch(T){X={code:aK.Status.INTERNAL,details:`Response message parsing error: ${(0,tK.getErrorMessage)(T)}`,metadata:new JM.Metadata},this.call.cancelWithStatus(X.code,X.details);return}(J=Y===null||Y===void 0?void 0:Y.onReceiveMessage)===null||J===void 0||J.call(Y,Z)},onReceiveStatus:(Q)=>{var J,Z;if(X)(J=Y===null||Y===void 0?void 0:Y.onReceiveStatus)===null||J===void 0||J.call(Y,X);else(Z=Y===null||Y===void 0?void 0:Y.onReceiveStatus)===null||Z===void 0||Z.call(Y,Q)}})}startRead(){this.call.startRead()}halfClose(){this.call.halfClose()}getAuthContext(){return this.call.getAuthContext()}}class XU extends r5{constructor($,Y){super($,Y)}start($,Y){var X,Q;let J=!1,Z={onReceiveMetadata:(Q=(X=Y===null||Y===void 0?void 0:Y.onReceiveMetadata)===null||X===void 0?void 0:X.bind(Y))!==null&&Q!==void 0?Q:(T)=>{},onReceiveMessage:(T)=>{var K;J=!0,(K=Y===null||Y===void 0?void 0:Y.onReceiveMessage)===null||K===void 0||K.call(Y,T)},onReceiveStatus:(T)=>{var K,U;if(!J)(K=Y===null||Y===void 0?void 0:Y.onReceiveMessage)===null||K===void 0||K.call(Y,null);(U=Y===null||Y===void 0?void 0:Y.onReceiveStatus)===null||U===void 0||U.call(Y,T)}};super.start($,Z),this.call.startRead()}}class QU extends r5{}function TM($,Y,X){let Q=ZM($,X.path,Y);if(X.responseStream)return new QU(Q,X);else return new XU(Q,X)}function KM($,Y,X,Q){if($.clientInterceptors.length>0&&$.clientInterceptorProviders.length>0)throw new C6("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 C6("Both interceptors and interceptor_providers were passed as call options. Only one of these is allowed.");let J=[];if($.callInterceptors.length>0||$.callInterceptorProviders.length>0)J=[].concat($.callInterceptors,$.callInterceptorProviders.map((K)=>K(Y))).filter((K)=>K);else J=[].concat($.clientInterceptors,$.clientInterceptorProviders.map((K)=>K(Y))).filter((K)=>K);let Z=Object.assign({},X,{method_definition:Y});return J.reduceRight((K,U)=>{return(G)=>U(G,K)},(K)=>TM(Q,K,Y))(Z)}});var a5=M((KU)=>{Object.defineProperty(KU,"__esModule",{value:!0});KU.Client=void 0;var k1=lK(),EM=t5(),VM=n0(),B$=i(),LY=P0(),k9=o5(),I1=Symbol(),SY=Symbol(),wY=Symbol(),X$=Symbol();function s5($){return typeof $==="function"}function CY($){var Y;return((Y=$.stack)===null||Y===void 0?void 0:Y.split(`
|
|
4
|
+
`).slice(1).join(`
|
|
5
|
+
`))||"no stack trace available"}class TU{constructor($,Y,X={}){var Q,J;if(X=Object.assign({},X),this[SY]=(Q=X.interceptors)!==null&&Q!==void 0?Q:[],delete X.interceptors,this[wY]=(J=X.interceptor_providers)!==null&&J!==void 0?J:[],delete X.interceptor_providers,this[SY].length>0&&this[wY].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[X$]=X.callInvocationTransformer,delete X.callInvocationTransformer,X.channelOverride)this[I1]=X.channelOverride;else if(X.channelFactoryOverride){let Z=X.channelFactoryOverride;delete X.channelFactoryOverride,this[I1]=Z($,Y,X)}else this[I1]=new EM.ChannelImplementation($,Y,X)}close(){this[I1].close()}getChannel(){return this[I1]}waitForReady($,Y){let X=(Q)=>{if(Q){Y(Error("Failed to connect before the deadline"));return}let J;try{J=this[I1].getConnectivityState(!0)}catch(Z){Y(Error("The channel has been closed"));return}if(J===VM.ConnectivityState.READY)Y();else try{this[I1].watchConnectivityState(J,$,X)}catch(Z){Y(Error("The channel has been closed"))}};setImmediate(X)}checkOptionalUnaryResponseArguments($,Y,X){if(s5($))return{metadata:new LY.Metadata,options:{},callback:$};else if(s5(Y))if($ instanceof LY.Metadata)return{metadata:$,options:{},callback:Y};else return{metadata:new LY.Metadata,options:$,callback:Y};else{if(!($ instanceof LY.Metadata&&Y instanceof Object&&s5(X)))throw Error("Incorrect arguments passed");return{metadata:$,options:Y,callback:X}}}makeUnaryRequest($,Y,X,Q,J,Z,T){var K,U;let G=this.checkOptionalUnaryResponseArguments(J,Z,T),W={path:$,requestStream:!1,responseStream:!1,requestSerialize:Y,responseDeserialize:X},R={argument:Q,metadata:G.metadata,call:new k1.ClientUnaryCallImpl,channel:this[I1],methodDefinition:W,callOptions:G.options,callback:G.callback};if(this[X$])R=this[X$](R);let V=R.call,A={clientInterceptors:this[SY],clientInterceptorProviders:this[wY],callInterceptors:(K=R.callOptions.interceptors)!==null&&K!==void 0?K:[],callInterceptorProviders:(U=R.callOptions.interceptor_providers)!==null&&U!==void 0?U:[]},H=(0,k9.getInterceptingCall)(A,R.methodDefinition,R.callOptions,R.channel);V.call=H;let z=null,D=!1,B=Error();return H.start(R.metadata,{onReceiveMetadata:(w)=>{V.emit("metadata",w)},onReceiveMessage(w){if(z!==null)H.cancelWithStatus(B$.Status.UNIMPLEMENTED,"Too many responses received");z=w},onReceiveStatus(w){if(D)return;if(D=!0,w.code===B$.Status.OK)if(z===null){let x=CY(B);R.callback((0,k1.callErrorFromStatus)({code:B$.Status.UNIMPLEMENTED,details:"No message received",metadata:w.metadata},x))}else R.callback(null,z);else{let x=CY(B);R.callback((0,k1.callErrorFromStatus)(w,x))}B=null,V.emit("status",w)}}),H.sendMessage(Q),H.halfClose(),V}makeClientStreamRequest($,Y,X,Q,J,Z){var T,K;let U=this.checkOptionalUnaryResponseArguments(Q,J,Z),G={path:$,requestStream:!0,responseStream:!1,requestSerialize:Y,responseDeserialize:X},W={metadata:U.metadata,call:new k1.ClientWritableStreamImpl(Y),channel:this[I1],methodDefinition:G,callOptions:U.options,callback:U.callback};if(this[X$])W=this[X$](W);let R=W.call,V={clientInterceptors:this[SY],clientInterceptorProviders:this[wY],callInterceptors:(T=W.callOptions.interceptors)!==null&&T!==void 0?T:[],callInterceptorProviders:(K=W.callOptions.interceptor_providers)!==null&&K!==void 0?K:[]},A=(0,k9.getInterceptingCall)(V,W.methodDefinition,W.callOptions,W.channel);R.call=A;let H=null,z=!1,D=Error();return A.start(W.metadata,{onReceiveMetadata:(B)=>{R.emit("metadata",B)},onReceiveMessage(B){if(H!==null)A.cancelWithStatus(B$.Status.UNIMPLEMENTED,"Too many responses received");H=B,A.startRead()},onReceiveStatus(B){if(z)return;if(z=!0,B.code===B$.Status.OK)if(H===null){let w=CY(D);W.callback((0,k1.callErrorFromStatus)({code:B$.Status.UNIMPLEMENTED,details:"No message received",metadata:B.metadata},w))}else W.callback(null,H);else{let w=CY(D);W.callback((0,k1.callErrorFromStatus)(B,w))}D=null,R.emit("status",B)}}),R}checkMetadataAndOptions($,Y){let X,Q;if($ instanceof LY.Metadata)if(X=$,Y)Q=Y;else Q={};else{if($)Q=$;else Q={};X=new LY.Metadata}return{metadata:X,options:Q}}makeServerStreamRequest($,Y,X,Q,J,Z){var T,K;let U=this.checkMetadataAndOptions(J,Z),G={path:$,requestStream:!1,responseStream:!0,requestSerialize:Y,responseDeserialize:X},W={argument:Q,metadata:U.metadata,call:new k1.ClientReadableStreamImpl(X),channel:this[I1],methodDefinition:G,callOptions:U.options};if(this[X$])W=this[X$](W);let R=W.call,V={clientInterceptors:this[SY],clientInterceptorProviders:this[wY],callInterceptors:(T=W.callOptions.interceptors)!==null&&T!==void 0?T:[],callInterceptorProviders:(K=W.callOptions.interceptor_providers)!==null&&K!==void 0?K:[]},A=(0,k9.getInterceptingCall)(V,W.methodDefinition,W.callOptions,W.channel);R.call=A;let H=!1,z=Error();return A.start(W.metadata,{onReceiveMetadata(D){R.emit("metadata",D)},onReceiveMessage(D){R.push(D)},onReceiveStatus(D){if(H)return;if(H=!0,R.push(null),D.code!==B$.Status.OK){let B=CY(z);R.emit("error",(0,k1.callErrorFromStatus)(D,B))}z=null,R.emit("status",D)}}),A.sendMessage(Q),A.halfClose(),R}makeBidiStreamRequest($,Y,X,Q,J){var Z,T;let K=this.checkMetadataAndOptions(Q,J),U={path:$,requestStream:!0,responseStream:!0,requestSerialize:Y,responseDeserialize:X},G={metadata:K.metadata,call:new k1.ClientDuplexStreamImpl(Y,X),channel:this[I1],methodDefinition:U,callOptions:K.options};if(this[X$])G=this[X$](G);let W=G.call,R={clientInterceptors:this[SY],clientInterceptorProviders:this[wY],callInterceptors:(Z=G.callOptions.interceptors)!==null&&Z!==void 0?Z:[],callInterceptorProviders:(T=G.callOptions.interceptor_providers)!==null&&T!==void 0?T:[]},V=(0,k9.getInterceptingCall)(R,G.methodDefinition,G.callOptions,G.channel);W.call=V;let A=!1,H=Error();return V.start(G.metadata,{onReceiveMetadata(z){W.emit("metadata",z)},onReceiveMessage(z){W.push(z)},onReceiveStatus(z){if(A)return;if(A=!0,W.push(null),z.code!==B$.Status.OK){let D=CY(H);W.emit("error",(0,k1.callErrorFromStatus)(z,D))}H=null,W.emit("status",z)}}),W}}KU.Client=TU});var h9=M((WU)=>{Object.defineProperty(WU,"__esModule",{value:!0});WU.makeClientConstructor=GU;WU.loadPackageDefinition=HM;var y6=a5(),AM={unary:y6.Client.prototype.makeUnaryRequest,server_stream:y6.Client.prototype.makeServerStreamRequest,client_stream:y6.Client.prototype.makeClientStreamRequest,bidi:y6.Client.prototype.makeBidiStreamRequest};function e5($){return["__proto__","prototype","constructor"].includes($)}function GU($,Y,X){if(!X)X={};class Q extends y6.Client{}return Object.keys($).forEach((J)=>{if(e5(J))return;let Z=$[J],T;if(typeof J==="string"&&J.charAt(0)==="$")throw Error("Method names cannot start with $");if(Z.requestStream)if(Z.responseStream)T="bidi";else T="client_stream";else if(Z.responseStream)T="server_stream";else T="unary";let{requestSerialize:K,responseDeserialize:U}=Z,G=DM(AM[T],Z.path,K,U);if(Q.prototype[J]=G,Object.assign(Q.prototype[J],Z),Z.originalName&&!e5(Z.originalName))Q.prototype[Z.originalName]=Q.prototype[J]}),Q.service=$,Q.serviceName=Y,Q}function DM($,Y,X,Q){return function(...J){return $.call(this,Y,X,Q,...J)}}function FM($){return"format"in $}function HM($){let Y={};for(let X in $)if(Object.prototype.hasOwnProperty.call($,X)){let Q=$[X],J=X.split(".");if(J.some((K)=>e5(K)))continue;let Z=J[J.length-1],T=Y;for(let K of J.slice(0,-1)){if(!T[K])T[K]={};T=T[K]}if(FM(Q))T[Z]=Q;else T[Z]=GU(Q,Z,{})}return Y}});var hU=M((wh,kU)=>{var NM=1/0,MM="[object Symbol]",BM=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,IM=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,g9="\\ud800-\\udfff",zU="\\u0300-\\u036f\\ufe20-\\ufe23",qU="\\u20d0-\\u20f0",NU="\\u2700-\\u27bf",MU="a-z\\xdf-\\xf6\\xf8-\\xff",OM="\\xac\\xb1\\xd7\\xf7",PM="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",LM="\\u2000-\\u206f",SM=" \\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",BU="A-Z\\xc0-\\xd6\\xd8-\\xde",IU="\\ufe0e\\ufe0f",OU=OM+PM+LM+SM,YQ="['’]",wM="["+g9+"]",RU="["+OU+"]",_9="["+zU+qU+"]",PU="\\d+",CM="["+NU+"]",LU="["+MU+"]",SU="[^"+g9+OU+PU+NU+MU+BU+"]",$Q="\\ud83c[\\udffb-\\udfff]",yM="(?:"+_9+"|"+$Q+")",wU="[^"+g9+"]",XQ="(?:\\ud83c[\\udde6-\\uddff]){2}",QQ="[\\ud800-\\udbff][\\udc00-\\udfff]",yY="["+BU+"]",CU="\\u200d",EU="(?:"+LU+"|"+SU+")",jM="(?:"+yY+"|"+SU+")",VU="(?:"+YQ+"(?:d|ll|m|re|s|t|ve))?",AU="(?:"+YQ+"(?:D|LL|M|RE|S|T|VE))?",yU=yM+"?",jU="["+IU+"]?",xM="(?:"+CU+"(?:"+[wU,XQ,QQ].join("|")+")"+jU+yU+")*",xU=jU+yU+xM,vM="(?:"+[CM,XQ,QQ].join("|")+")"+xU,kM="(?:"+[wU+_9+"?",_9,XQ,QQ,wM].join("|")+")",hM=RegExp(YQ,"g"),_M=RegExp(_9,"g"),gM=RegExp($Q+"(?="+$Q+")|"+kM+xU,"g"),fM=RegExp([yY+"?"+LU+"+"+VU+"(?="+[RU,yY,"$"].join("|")+")",jM+"+"+AU+"(?="+[RU,yY+EU,"$"].join("|")+")",yY+"?"+EU+"+"+VU,yY+"+"+AU,PU,vM].join("|"),"g"),mM=RegExp("["+CU+g9+zU+qU+IU+"]"),bM=/[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,uM={"À":"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"},dM=typeof global=="object"&&global&&global.Object===Object&&global,pM=typeof self=="object"&&self&&self.Object===Object&&self,cM=dM||pM||Function("return this")();function nM($,Y,X,Q){var J=-1,Z=$?$.length:0;if(Q&&Z)X=$[++J];while(++J<Z)X=Y(X,$[J],J,$);return X}function lM($){return $.split("")}function iM($){return $.match(BM)||[]}function rM($){return function(Y){return $==null?void 0:$[Y]}}var oM=rM(uM);function vU($){return mM.test($)}function sM($){return bM.test($)}function aM($){return vU($)?tM($):lM($)}function tM($){return $.match(gM)||[]}function eM($){return $.match(fM)||[]}var $B=Object.prototype,YB=$B.toString,DU=cM.Symbol,FU=DU?DU.prototype:void 0,HU=FU?FU.toString:void 0;function XB($,Y,X){var Q=-1,J=$.length;if(Y<0)Y=-Y>J?0:J+Y;if(X=X>J?J:X,X<0)X+=J;J=Y>X?0:X-Y>>>0,Y>>>=0;var Z=Array(J);while(++Q<J)Z[Q]=$[Q+Y];return Z}function QB($){if(typeof $=="string")return $;if(UB($))return HU?HU.call($):"";var Y=$+"";return Y=="0"&&1/$==-NM?"-0":Y}function JB($,Y,X){var Q=$.length;return X=X===void 0?Q:X,!Y&&X>=Q?$:XB($,Y,X)}function ZB($){return function(Y){Y=f9(Y);var X=vU(Y)?aM(Y):void 0,Q=X?X[0]:Y.charAt(0),J=X?JB(X,1).join(""):Y.slice(1);return Q[$]()+J}}function TB($){return function(Y){return nM(VB(RB(Y).replace(hM,"")),$,"")}}function KB($){return!!$&&typeof $=="object"}function UB($){return typeof $=="symbol"||KB($)&&YB.call($)==MM}function f9($){return $==null?"":QB($)}var GB=TB(function($,Y,X){return Y=Y.toLowerCase(),$+(X?WB(Y):Y)});function WB($){return EB(f9($).toLowerCase())}function RB($){return $=f9($),$&&$.replace(IM,oM).replace(_M,"")}var EB=ZB("toUpperCase");function VB($,Y,X){if($=f9($),Y=X?void 0:Y,Y===void 0)return sM($)?eM($):iM($);return $.match(Y)||[]}kU.exports=GB});var JQ=M((Ch,_U)=>{_U.exports=AB;function AB($,Y){var X=Array(arguments.length-1),Q=0,J=2,Z=!0;while(J<arguments.length)X[Q++]=arguments[J++];return new Promise(function(K,U){X[Q]=function(W){if(Z)if(Z=!1,W)U(W);else{var R=Array(arguments.length-1),V=0;while(V<R.length)R[V++]=arguments[V];K.apply(null,R)}};try{$.apply(Y||null,X)}catch(G){if(Z)Z=!1,U(G)}})}});var bU=M((mU)=>{var m9=mU;m9.length=function(Y){var X=Y.length;if(!X)return 0;var Q=0;while(--X%4>1&&Y.charAt(X)==="=")++Q;return Math.ceil(Y.length*3)/4-Q};var jY=Array(64),fU=Array(123);for(R1=0;R1<64;)fU[jY[R1]=R1<26?R1+65:R1<52?R1+71:R1<62?R1-4:R1-59|43]=R1++;var R1;m9.encode=function(Y,X,Q){var J=null,Z=[],T=0,K=0,U;while(X<Q){var G=Y[X++];switch(K){case 0:Z[T++]=jY[G>>2],U=(G&3)<<4,K=1;break;case 1:Z[T++]=jY[U|G>>4],U=(G&15)<<2,K=2;break;case 2:Z[T++]=jY[U|G>>6],Z[T++]=jY[G&63],K=0;break}if(T>8191)(J||(J=[])).push(String.fromCharCode.apply(String,Z)),T=0}if(K){if(Z[T++]=jY[U],Z[T++]=61,K===1)Z[T++]=61}if(J){if(T)J.push(String.fromCharCode.apply(String,Z.slice(0,T)));return J.join("")}return String.fromCharCode.apply(String,Z.slice(0,T))};var gU="invalid encoding";m9.decode=function(Y,X,Q){var J=Q,Z=0,T;for(var K=0;K<Y.length;){var U=Y.charCodeAt(K++);if(U===61&&Z>1)break;if((U=fU[U])===void 0)throw Error(gU);switch(Z){case 0:T=U,Z=1;break;case 1:X[Q++]=T<<2|(U&48)>>4,T=U,Z=2;break;case 2:X[Q++]=(T&15)<<4|(U&60)>>2,T=U,Z=3;break;case 3:X[Q++]=(T&3)<<6|U,Z=0;break}}if(Z===1)throw Error(gU);return Q-J};m9.test=function(Y){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(Y)}});var dU=M((jh,uU)=>{uU.exports=b9;function b9(){this._listeners={}}b9.prototype.on=function(Y,X,Q){return(this._listeners[Y]||(this._listeners[Y]=[])).push({fn:X,ctx:Q||this}),this};b9.prototype.off=function(Y,X){if(Y===void 0)this._listeners={};else if(X===void 0)this._listeners[Y]=[];else{var Q=this._listeners[Y];for(var J=0;J<Q.length;)if(Q[J].fn===X)Q.splice(J,1);else++J}return this};b9.prototype.emit=function(Y){var X=this._listeners[Y];if(X){var Q=[],J=1;for(;J<arguments.length;)Q.push(arguments[J++]);for(J=0;J<X.length;)X[J].fn.apply(X[J++].ctx,Q)}return this}});var oU=M((xh,rU)=>{rU.exports=pU(pU);function pU($){if(typeof Float32Array<"u")(function(){var Y=new Float32Array([-0]),X=new Uint8Array(Y.buffer),Q=X[3]===128;function J(U,G,W){Y[0]=U,G[W]=X[0],G[W+1]=X[1],G[W+2]=X[2],G[W+3]=X[3]}function Z(U,G,W){Y[0]=U,G[W]=X[3],G[W+1]=X[2],G[W+2]=X[1],G[W+3]=X[0]}$.writeFloatLE=Q?J:Z,$.writeFloatBE=Q?Z:J;function T(U,G){return X[0]=U[G],X[1]=U[G+1],X[2]=U[G+2],X[3]=U[G+3],Y[0]}function K(U,G){return X[3]=U[G],X[2]=U[G+1],X[1]=U[G+2],X[0]=U[G+3],Y[0]}$.readFloatLE=Q?T:K,$.readFloatBE=Q?K:T})();else(function(){function Y(Q,J,Z,T){var K=J<0?1:0;if(K)J=-J;if(J===0)Q(1/J>0?0:2147483648,Z,T);else if(isNaN(J))Q(2143289344,Z,T);else if(J>340282346638528860000000000000000000000)Q((K<<31|2139095040)>>>0,Z,T);else if(J<0.000000000000000000000000000000000000011754943508222875)Q((K<<31|Math.round(J/0.000000000000000000000000000000000000000000001401298464324817))>>>0,Z,T);else{var U=Math.floor(Math.log(J)/Math.LN2),G=Math.round(J*Math.pow(2,-U)*8388608)&8388607;Q((K<<31|U+127<<23|G)>>>0,Z,T)}}$.writeFloatLE=Y.bind(null,cU),$.writeFloatBE=Y.bind(null,nU);function X(Q,J,Z){var T=Q(J,Z),K=(T>>31)*2+1,U=T>>>23&255,G=T&8388607;return U===255?G?NaN:K*(1/0):U===0?K*0.000000000000000000000000000000000000000000001401298464324817*G:K*Math.pow(2,U-150)*(G+8388608)}$.readFloatLE=X.bind(null,lU),$.readFloatBE=X.bind(null,iU)})();if(typeof Float64Array<"u")(function(){var Y=new Float64Array([-0]),X=new Uint8Array(Y.buffer),Q=X[7]===128;function J(U,G,W){Y[0]=U,G[W]=X[0],G[W+1]=X[1],G[W+2]=X[2],G[W+3]=X[3],G[W+4]=X[4],G[W+5]=X[5],G[W+6]=X[6],G[W+7]=X[7]}function Z(U,G,W){Y[0]=U,G[W]=X[7],G[W+1]=X[6],G[W+2]=X[5],G[W+3]=X[4],G[W+4]=X[3],G[W+5]=X[2],G[W+6]=X[1],G[W+7]=X[0]}$.writeDoubleLE=Q?J:Z,$.writeDoubleBE=Q?Z:J;function T(U,G){return X[0]=U[G],X[1]=U[G+1],X[2]=U[G+2],X[3]=U[G+3],X[4]=U[G+4],X[5]=U[G+5],X[6]=U[G+6],X[7]=U[G+7],Y[0]}function K(U,G){return X[7]=U[G],X[6]=U[G+1],X[5]=U[G+2],X[4]=U[G+3],X[3]=U[G+4],X[2]=U[G+5],X[1]=U[G+6],X[0]=U[G+7],Y[0]}$.readDoubleLE=Q?T:K,$.readDoubleBE=Q?K:T})();else(function(){function Y(Q,J,Z,T,K,U){var G=T<0?1:0;if(G)T=-T;if(T===0)Q(0,K,U+J),Q(1/T>0?0:2147483648,K,U+Z);else if(isNaN(T))Q(0,K,U+J),Q(2146959360,K,U+Z);else if(T>179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000)Q(0,K,U+J),Q((G<<31|2146435072)>>>0,K,U+Z);else{var W;if(T<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000022250738585072014)W=T/0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005,Q(W>>>0,K,U+J),Q((G<<31|W/4294967296)>>>0,K,U+Z);else{var R=Math.floor(Math.log(T)/Math.LN2);if(R===1024)R=1023;W=T*Math.pow(2,-R),Q(W*4503599627370496>>>0,K,U+J),Q((G<<31|R+1023<<20|W*1048576&1048575)>>>0,K,U+Z)}}}$.writeDoubleLE=Y.bind(null,cU,0,4),$.writeDoubleBE=Y.bind(null,nU,4,0);function X(Q,J,Z,T,K){var U=Q(T,K+J),G=Q(T,K+Z),W=(G>>31)*2+1,R=G>>>20&2047,V=4294967296*(G&1048575)+U;return R===2047?V?NaN:W*(1/0):R===0?W*0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005*V:W*Math.pow(2,R-1075)*(V+4503599627370496)}$.readDoubleLE=X.bind(null,lU,0,4),$.readDoubleBE=X.bind(null,iU,4,0)})();return $}function cU($,Y,X){Y[X]=$&255,Y[X+1]=$>>>8&255,Y[X+2]=$>>>16&255,Y[X+3]=$>>>24}function nU($,Y,X){Y[X]=$>>>24,Y[X+1]=$>>>16&255,Y[X+2]=$>>>8&255,Y[X+3]=$&255}function lU($,Y){return($[Y]|$[Y+1]<<8|$[Y+2]<<16|$[Y+3]<<24)>>>0}function iU($,Y){return($[Y]<<24|$[Y+1]<<16|$[Y+2]<<8|$[Y+3])>>>0}});var TQ=M((sU,ZQ)=>{ZQ.exports=DB;function DB(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch($){}return null}});var tU=M((aU)=>{var KQ=aU;KQ.length=function(Y){var X=0,Q=0;for(var J=0;J<Y.length;++J)if(Q=Y.charCodeAt(J),Q<128)X+=1;else if(Q<2048)X+=2;else if((Q&64512)===55296&&(Y.charCodeAt(J+1)&64512)===56320)++J,X+=4;else X+=3;return X};KQ.read=function(Y,X,Q){var J=Q-X;if(J<1)return"";var Z=null,T=[],K=0,U;while(X<Q){if(U=Y[X++],U<128)T[K++]=U;else if(U>191&&U<224)T[K++]=(U&31)<<6|Y[X++]&63;else if(U>239&&U<365)U=((U&7)<<18|(Y[X++]&63)<<12|(Y[X++]&63)<<6|Y[X++]&63)-65536,T[K++]=55296+(U>>10),T[K++]=56320+(U&1023);else T[K++]=(U&15)<<12|(Y[X++]&63)<<6|Y[X++]&63;if(K>8191)(Z||(Z=[])).push(String.fromCharCode.apply(String,T)),K=0}if(Z){if(K)Z.push(String.fromCharCode.apply(String,T.slice(0,K)));return Z.join("")}return String.fromCharCode.apply(String,T.slice(0,K))};KQ.write=function(Y,X,Q){var J=Q,Z,T;for(var K=0;K<Y.length;++K)if(Z=Y.charCodeAt(K),Z<128)X[Q++]=Z;else if(Z<2048)X[Q++]=Z>>6|192,X[Q++]=Z&63|128;else if((Z&64512)===55296&&((T=Y.charCodeAt(K+1))&64512)===56320)Z=65536+((Z&1023)<<10)+(T&1023),++K,X[Q++]=Z>>18|240,X[Q++]=Z>>12&63|128,X[Q++]=Z>>6&63|128,X[Q++]=Z&63|128;else X[Q++]=Z>>12|224,X[Q++]=Z>>6&63|128,X[Q++]=Z&63|128;return Q-J}});var $G=M((kh,eU)=>{eU.exports=FB;function FB($,Y,X){var Q=X||8192,J=Q>>>1,Z=null,T=Q;return function(U){if(U<1||U>J)return $(U);if(T+U>Q)Z=$(Q),T=0;var G=Y.call(Z,T,T+=U);if(T&7)T=(T|7)+1;return G}}});var XG=M((hh,YG)=>{YG.exports=L0;var j6=h1();function L0($,Y){this.lo=$>>>0,this.hi=Y>>>0}var i$=L0.zero=new L0(0,0);i$.toNumber=function(){return 0};i$.zzEncode=i$.zzDecode=function(){return this};i$.length=function(){return 1};var HB=L0.zeroHash="\x00\x00\x00\x00\x00\x00\x00\x00";L0.fromNumber=function(Y){if(Y===0)return i$;var X=Y<0;if(X)Y=-Y;var Q=Y>>>0,J=(Y-Q)/4294967296>>>0;if(X){if(J=~J>>>0,Q=~Q>>>0,++Q>4294967295){if(Q=0,++J>4294967295)J=0}}return new L0(Q,J)};L0.from=function(Y){if(typeof Y==="number")return L0.fromNumber(Y);if(j6.isString(Y))if(j6.Long)Y=j6.Long.fromString(Y);else return L0.fromNumber(parseInt(Y,10));return Y.low||Y.high?new L0(Y.low>>>0,Y.high>>>0):i$};L0.prototype.toNumber=function(Y){if(!Y&&this.hi>>>31){var X=~this.lo+1>>>0,Q=~this.hi>>>0;if(!X)Q=Q+1>>>0;return-(X+Q*4294967296)}return this.lo+this.hi*4294967296};L0.prototype.toLong=function(Y){return j6.Long?new j6.Long(this.lo|0,this.hi|0,Boolean(Y)):{low:this.lo|0,high:this.hi|0,unsigned:Boolean(Y)}};var I$=String.prototype.charCodeAt;L0.fromHash=function(Y){if(Y===HB)return i$;return new L0((I$.call(Y,0)|I$.call(Y,1)<<8|I$.call(Y,2)<<16|I$.call(Y,3)<<24)>>>0,(I$.call(Y,4)|I$.call(Y,5)<<8|I$.call(Y,6)<<16|I$.call(Y,7)<<24)>>>0)};L0.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)};L0.prototype.zzEncode=function(){var Y=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^Y)>>>0,this.lo=(this.lo<<1^Y)>>>0,this};L0.prototype.zzDecode=function(){var Y=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^Y)>>>0,this.hi=(this.hi>>>1^Y)>>>0,this};L0.prototype.length=function(){var Y=this.lo,X=(this.lo>>>28|this.hi<<4)>>>0,Q=this.hi>>>24;return Q===0?X===0?Y<16384?Y<128?1:2:Y<2097152?3:4:X<16384?X<128?5:6:X<2097152?7:8:Q<128?9:10}});var h1=M((UQ)=>{var g=UQ;g.asPromise=JQ();g.base64=bU();g.EventEmitter=dU();g.float=oU();g.inquire=TQ();g.utf8=tU();g.pool=$G();g.LongBits=XG();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||UQ;g.emptyArray=Object.freeze?Object.freeze([]):[];g.emptyObject=Object.freeze?Object.freeze({}):{};g.isInteger=Number.isInteger||function(Y){return typeof Y==="number"&&isFinite(Y)&&Math.floor(Y)===Y};g.isString=function(Y){return typeof Y==="string"||Y instanceof String};g.isObject=function(Y){return Y&&typeof Y==="object"};g.isset=g.isSet=function(Y,X){var Q=Y[X];if(Q!=null&&Y.hasOwnProperty(X))return typeof Q!=="object"||(Array.isArray(Q)?Q.length:Object.keys(Q).length)>0;return!1};g.Buffer=function(){try{var $=g.inquire("buffer").Buffer;return $.prototype.utf8Write?$:null}catch(Y){return null}}();g._Buffer_from=null;g._Buffer_allocUnsafe=null;g.newBuffer=function(Y){return typeof Y==="number"?g.Buffer?g._Buffer_allocUnsafe(Y):new g.Array(Y):g.Buffer?g._Buffer_from(Y):typeof Uint8Array>"u"?Y:new Uint8Array(Y)};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(Y){return Y?g.LongBits.from(Y).toHash():g.LongBits.zeroHash};g.longFromHash=function(Y,X){var Q=g.LongBits.fromHash(Y);if(g.Long)return g.Long.fromBits(Q.lo,Q.hi,X);return Q.toNumber(Boolean(X))};function QG($,Y,X){for(var Q=Object.keys(Y),J=0;J<Q.length;++J)if($[Q[J]]===void 0||!X)$[Q[J]]=Y[Q[J]];return $}g.merge=QG;g.lcFirst=function(Y){return Y.charAt(0).toLowerCase()+Y.substring(1)};function JG($){function Y(X,Q){if(!(this instanceof Y))return new Y(X,Q);if(Object.defineProperty(this,"message",{get:function(){return X}}),Error.captureStackTrace)Error.captureStackTrace(this,Y);else Object.defineProperty(this,"stack",{value:Error().stack||""});if(Q)QG(this,Q)}return Y.prototype=Object.create(Error.prototype,{constructor:{value:Y,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}}),Y}g.newError=JG;g.ProtocolError=JG("ProtocolError");g.oneOfGetter=function(Y){var X={};for(var Q=0;Q<Y.length;++Q)X[Y[Q]]=1;return function(){for(var J=Object.keys(this),Z=J.length-1;Z>-1;--Z)if(X[J[Z]]===1&&this[J[Z]]!==void 0&&this[J[Z]]!==null)return J[Z]}};g.oneOfSetter=function(Y){return function(X){for(var Q=0;Q<Y.length;++Q)if(Y[Q]!==X)delete this[Y[Q]]}};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(X,Q){return new $(X,Q)},g._Buffer_allocUnsafe=$.allocUnsafe||function(X){return new $(X)}}});var d9=M((gh,UG)=>{UG.exports=e;var E1=h1(),GQ,u9=E1.LongBits,ZG=E1.base64,TG=E1.utf8;function x6($,Y,X){this.fn=$,this.len=Y,this.next=void 0,this.val=X}function RQ(){}function zB($){this.head=$.head,this.tail=$.tail,this.len=$.len,this.next=$.states}function e(){this.len=0,this.head=new x6(RQ,0,0),this.tail=this.head,this.states=null}var KG=function(){return E1.Buffer?function(){return(e.create=function(){return new GQ})()}:function(){return new e}};e.create=KG();e.alloc=function(Y){return new E1.Array(Y)};if(E1.Array!==Array)e.alloc=E1.pool(e.alloc,E1.Array.prototype.subarray);e.prototype._push=function(Y,X,Q){return this.tail=this.tail.next=new x6(Y,X,Q),this.len+=X,this};function EQ($,Y,X){Y[X]=$&255}function qB($,Y,X){while($>127)Y[X++]=$&127|128,$>>>=7;Y[X]=$}function VQ($,Y){this.len=$,this.next=void 0,this.val=Y}VQ.prototype=Object.create(x6.prototype);VQ.prototype.fn=qB;e.prototype.uint32=function(Y){return this.len+=(this.tail=this.tail.next=new VQ((Y=Y>>>0)<128?1:Y<16384?2:Y<2097152?3:Y<268435456?4:5,Y)).len,this};e.prototype.int32=function(Y){return Y<0?this._push(AQ,10,u9.fromNumber(Y)):this.uint32(Y)};e.prototype.sint32=function(Y){return this.uint32((Y<<1^Y>>31)>>>0)};function AQ($,Y,X){while($.hi)Y[X++]=$.lo&127|128,$.lo=($.lo>>>7|$.hi<<25)>>>0,$.hi>>>=7;while($.lo>127)Y[X++]=$.lo&127|128,$.lo=$.lo>>>7;Y[X++]=$.lo}e.prototype.uint64=function(Y){var X=u9.from(Y);return this._push(AQ,X.length(),X)};e.prototype.int64=e.prototype.uint64;e.prototype.sint64=function(Y){var X=u9.from(Y).zzEncode();return this._push(AQ,X.length(),X)};e.prototype.bool=function(Y){return this._push(EQ,1,Y?1:0)};function WQ($,Y,X){Y[X]=$&255,Y[X+1]=$>>>8&255,Y[X+2]=$>>>16&255,Y[X+3]=$>>>24}e.prototype.fixed32=function(Y){return this._push(WQ,4,Y>>>0)};e.prototype.sfixed32=e.prototype.fixed32;e.prototype.fixed64=function(Y){var X=u9.from(Y);return this._push(WQ,4,X.lo)._push(WQ,4,X.hi)};e.prototype.sfixed64=e.prototype.fixed64;e.prototype.float=function(Y){return this._push(E1.float.writeFloatLE,4,Y)};e.prototype.double=function(Y){return this._push(E1.float.writeDoubleLE,8,Y)};var NB=E1.Array.prototype.set?function(Y,X,Q){X.set(Y,Q)}:function(Y,X,Q){for(var J=0;J<Y.length;++J)X[Q+J]=Y[J]};e.prototype.bytes=function(Y){var X=Y.length>>>0;if(!X)return this._push(EQ,1,0);if(E1.isString(Y)){var Q=e.alloc(X=ZG.length(Y));ZG.decode(Y,Q,0),Y=Q}return this.uint32(X)._push(NB,X,Y)};e.prototype.string=function(Y){var X=TG.length(Y);return X?this.uint32(X)._push(TG.write,X,Y):this._push(EQ,1,0)};e.prototype.fork=function(){return this.states=new zB(this),this.head=this.tail=new x6(RQ,0,0),this.len=0,this};e.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 x6(RQ,0,0),this.len=0;return this};e.prototype.ldelim=function(){var Y=this.head,X=this.tail,Q=this.len;if(this.reset().uint32(Q),Q)this.tail.next=Y.next,this.tail=X,this.len+=Q;return this};e.prototype.finish=function(){var Y=this.head.next,X=this.constructor.alloc(this.len),Q=0;while(Y)Y.fn(Y.val,X,Q),Q+=Y.len,Y=Y.next;return X};e._configure=function($){GQ=$,e.create=KG(),GQ._configure()}});var RG=M((fh,WG)=>{WG.exports=_1;var GG=d9();(_1.prototype=Object.create(GG.prototype)).constructor=_1;var O$=h1();function _1(){GG.call(this)}_1._configure=function(){_1.alloc=O$._Buffer_allocUnsafe,_1.writeBytesBuffer=O$.Buffer&&O$.Buffer.prototype instanceof Uint8Array&&O$.Buffer.prototype.set.name==="set"?function(Y,X,Q){X.set(Y,Q)}:function(Y,X,Q){if(Y.copy)Y.copy(X,Q,0,Y.length);else for(var J=0;J<Y.length;)X[Q++]=Y[J++]}};_1.prototype.bytes=function(Y){if(O$.isString(Y))Y=O$._Buffer_from(Y,"base64");var X=Y.length>>>0;if(this.uint32(X),X)this._push(_1.writeBytesBuffer,X,Y);return this};function MB($,Y,X){if($.length<40)O$.utf8.write($,Y,X);else if(Y.utf8Write)Y.utf8Write($,X);else Y.write($,X)}_1.prototype.string=function(Y){var X=O$.Buffer.byteLength(Y);if(this.uint32(X),X)this._push(MB,X,Y);return this};_1._configure()});var c9=M((mh,FG)=>{FG.exports=A0;var O1=h1(),FQ,AG=O1.LongBits,BB=O1.utf8;function P1($,Y){return RangeError("index out of range: "+$.pos+" + "+(Y||1)+" > "+$.len)}function A0($){this.buf=$,this.pos=0,this.len=$.length}var EG=typeof Uint8Array<"u"?function(Y){if(Y instanceof Uint8Array||Array.isArray(Y))return new A0(Y);throw Error("illegal buffer")}:function(Y){if(Array.isArray(Y))return new A0(Y);throw Error("illegal buffer")},DG=function(){return O1.Buffer?function(X){return(A0.create=function(J){return O1.Buffer.isBuffer(J)?new FQ(J):EG(J)})(X)}:EG};A0.create=DG();A0.prototype._slice=O1.Array.prototype.subarray||O1.Array.prototype.slice;A0.prototype.uint32=function(){var Y=4294967295;return function(){if(Y=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128)return Y;if(Y=(Y|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)return Y;if(Y=(Y|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)return Y;if(Y=(Y|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)return Y;if(Y=(Y|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128)return Y;if((this.pos+=5)>this.len)throw this.pos=this.len,P1(this,10);return Y}}();A0.prototype.int32=function(){return this.uint32()|0};A0.prototype.sint32=function(){var Y=this.uint32();return Y>>>1^-(Y&1)|0};function DQ(){var $=new AG(0,0),Y=0;if(this.len-this.pos>4){for(;Y<4;++Y)if($.lo=($.lo|(this.buf[this.pos]&127)<<Y*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 $;Y=0}else{for(;Y<3;++Y){if(this.pos>=this.len)throw P1(this);if($.lo=($.lo|(this.buf[this.pos]&127)<<Y*7)>>>0,this.buf[this.pos++]<128)return $}return $.lo=($.lo|(this.buf[this.pos++]&127)<<Y*7)>>>0,$}if(this.len-this.pos>4){for(;Y<5;++Y)if($.hi=($.hi|(this.buf[this.pos]&127)<<Y*7+3)>>>0,this.buf[this.pos++]<128)return $}else for(;Y<5;++Y){if(this.pos>=this.len)throw P1(this);if($.hi=($.hi|(this.buf[this.pos]&127)<<Y*7+3)>>>0,this.buf[this.pos++]<128)return $}throw Error("invalid varint encoding")}A0.prototype.bool=function(){return this.uint32()!==0};function p9($,Y){return($[Y-4]|$[Y-3]<<8|$[Y-2]<<16|$[Y-1]<<24)>>>0}A0.prototype.fixed32=function(){if(this.pos+4>this.len)throw P1(this,4);return p9(this.buf,this.pos+=4)};A0.prototype.sfixed32=function(){if(this.pos+4>this.len)throw P1(this,4);return p9(this.buf,this.pos+=4)|0};function VG(){if(this.pos+8>this.len)throw P1(this,8);return new AG(p9(this.buf,this.pos+=4),p9(this.buf,this.pos+=4))}A0.prototype.float=function(){if(this.pos+4>this.len)throw P1(this,4);var Y=O1.float.readFloatLE(this.buf,this.pos);return this.pos+=4,Y};A0.prototype.double=function(){if(this.pos+8>this.len)throw P1(this,4);var Y=O1.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,Y};A0.prototype.bytes=function(){var Y=this.uint32(),X=this.pos,Q=this.pos+Y;if(Q>this.len)throw P1(this,Y);if(this.pos+=Y,Array.isArray(this.buf))return this.buf.slice(X,Q);if(X===Q){var J=O1.Buffer;return J?J.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,X,Q)};A0.prototype.string=function(){var Y=this.bytes();return BB.read(Y,0,Y.length)};A0.prototype.skip=function(Y){if(typeof Y==="number"){if(this.pos+Y>this.len)throw P1(this,Y);this.pos+=Y}else do if(this.pos>=this.len)throw P1(this);while(this.buf[this.pos++]&128);return this};A0.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};A0._configure=function($){FQ=$,A0.create=DG(),FQ._configure();var Y=O1.Long?"toLong":"toNumber";O1.merge(A0.prototype,{int64:function(){return DQ.call(this)[Y](!1)},uint64:function(){return DQ.call(this)[Y](!0)},sint64:function(){return DQ.call(this).zzDecode()[Y](!1)},fixed64:function(){return VG.call(this)[Y](!0)},sfixed64:function(){return VG.call(this)[Y](!1)}})}});var NG=M((bh,qG)=>{qG.exports=r$;var zG=c9();(r$.prototype=Object.create(zG.prototype)).constructor=r$;var HG=h1();function r$($){zG.call(this,$)}r$._configure=function(){if(HG.Buffer)r$.prototype._slice=HG.Buffer.prototype.slice};r$.prototype.string=function(){var Y=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+Y,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+Y,this.len))};r$._configure()});var BG=M((uh,MG)=>{MG.exports=v6;var HQ=h1();(v6.prototype=Object.create(HQ.EventEmitter.prototype)).constructor=v6;function v6($,Y,X){if(typeof $!=="function")throw TypeError("rpcImpl must be a function");HQ.EventEmitter.call(this),this.rpcImpl=$,this.requestDelimited=Boolean(Y),this.responseDelimited=Boolean(X)}v6.prototype.rpcCall=function $(Y,X,Q,J,Z){if(!J)throw TypeError("request must be specified");var T=this;if(!Z)return HQ.asPromise($,T,Y,X,Q,J);if(!T.rpcImpl){setTimeout(function(){Z(Error("already ended"))},0);return}try{return T.rpcImpl(Y,X[T.requestDelimited?"encodeDelimited":"encode"](J).finish(),function(U,G){if(U)return T.emit("error",U,Y),Z(U);if(G===null){T.end(!0);return}if(!(G instanceof Q))try{G=Q[T.responseDelimited?"decodeDelimited":"decode"](G)}catch(W){return T.emit("error",W,Y),Z(W)}return T.emit("data",G,Y),Z(null,G)})}catch(K){T.emit("error",K,Y),setTimeout(function(){Z(K)},0);return}};v6.prototype.end=function(Y){if(this.rpcImpl){if(!Y)this.rpcImpl(null,null,null);this.rpcImpl=null,this.emit("end").off()}return this}});var zQ=M((IG)=>{var IB=IG;IB.Service=BG()});var qQ=M((ph,OG)=>{OG.exports={}});var SG=M((LG)=>{var o0=LG;o0.build="minimal";o0.Writer=d9();o0.BufferWriter=RG();o0.Reader=c9();o0.BufferReader=NG();o0.util=h1();o0.rpc=zQ();o0.roots=qQ();o0.configure=PG;function PG(){o0.util._configure(),o0.Writer._configure(o0.BufferWriter),o0.Reader._configure(o0.BufferReader)}PG()});var CG=M((nh,wG)=>{wG.exports=NQ;function NQ($,Y){if(typeof $==="string")Y=$,$=void 0;var X=[];function Q(Z){if(typeof Z!=="string"){var T=J();if(NQ.verbose)console.log("codegen: "+T);if(T="return "+T,Z){var K=Object.keys(Z),U=Array(K.length+1),G=Array(K.length),W=0;while(W<K.length)U[W]=K[W],G[W]=Z[K[W++]];return U[W]=T,Function.apply(null,U).apply(null,G)}return Function(T)()}var R=Array(arguments.length-1),V=0;while(V<R.length)R[V]=arguments[++V];if(V=0,Z=Z.replace(/%([%dfijs])/g,function(H,z){var D=R[V++];switch(z){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"%"}),V!==R.length)throw Error("parameter count mismatch");return X.push(Z),Q}function J(Z){return"function "+(Z||Y||"")+"("+($&&$.join(",")||"")+`){
|
|
6
|
+
`+X.join(`
|
|
7
|
+
`)+`
|
|
8
|
+
}`}return Q.toString=J,Q}NQ.verbose=!1});var jG=M((lh,yG)=>{yG.exports=k6;var OB=JQ(),PB=TQ(),MQ=PB("fs");function k6($,Y,X){if(typeof Y==="function")X=Y,Y={};else if(!Y)Y={};if(!X)return OB(k6,this,$,Y);if(!Y.xhr&&MQ&&MQ.readFile)return MQ.readFile($,function(J,Z){return J&&typeof XMLHttpRequest<"u"?k6.xhr($,Y,X):J?X(J):X(null,Y.binary?Z:Z.toString("utf8"))});return k6.xhr($,Y,X)}k6.xhr=function(Y,X,Q){var J=new XMLHttpRequest;if(J.onreadystatechange=function(){if(J.readyState!==4)return;if(J.status!==0&&J.status!==200)return Q(Error("status "+J.status));if(X.binary){var T=J.response;if(!T){T=[];for(var K=0;K<J.responseText.length;++K)T.push(J.responseText.charCodeAt(K)&255)}return Q(null,typeof Uint8Array<"u"?new Uint8Array(T):T)}return Q(null,J.responseText)},X.binary){if("overrideMimeType"in J)J.overrideMimeType("text/plain; charset=x-user-defined");J.responseType="arraybuffer"}J.open("GET",Y),J.send()}});var kG=M((vG)=>{var IQ=vG,xG=IQ.isAbsolute=function(Y){return/^(?:\/|\w+:)/.test(Y)},BQ=IQ.normalize=function(Y){Y=Y.replace(/\\/g,"/").replace(/\/{2,}/g,"/");var X=Y.split("/"),Q=xG(Y),J="";if(Q)J=X.shift()+"/";for(var Z=0;Z<X.length;)if(X[Z]==="..")if(Z>0&&X[Z-1]!=="..")X.splice(--Z,2);else if(Q)X.splice(Z,1);else++Z;else if(X[Z]===".")X.splice(Z,1);else++Z;return J+X.join("/")};IQ.resolve=function(Y,X,Q){if(!Q)X=BQ(X);if(xG(X))return X;if(!Q)Y=BQ(Y);return(Y=Y.replace(/(?:\/|^)[^/]+$/,"")).length?BQ(Y+"/"+X):X}});var vY=M((rh,gG)=>{gG.exports=a;var n9=L$();((a.prototype=Object.create(n9.prototype)).constructor=a).className="Namespace";var OQ=P$(),l9=S0(),LB=a$(),o$,xY,s$;a.fromJSON=function(Y,X){return new a(Y,X.options).addJSON(X.nested)};function hG($,Y){if(!($&&$.length))return;var X={};for(var Q=0;Q<$.length;++Q)X[$[Q].name]=$[Q].toJSON(Y);return X}a.arrayToJSON=hG;a.isReservedId=function(Y,X){if(Y){for(var Q=0;Q<Y.length;++Q)if(typeof Y[Q]!=="string"&&Y[Q][0]<=X&&Y[Q][1]>X)return!0}return!1};a.isReservedName=function(Y,X){if(Y){for(var Q=0;Q<Y.length;++Q)if(Y[Q]===X)return!0}return!1};function a($,Y){n9.call(this,$,Y),this.nested=void 0,this._nestedArray=null,this._lookupCache={},this._needsRecursiveFeatureResolution=!0,this._needsRecursiveResolve=!0}function _G($){$._nestedArray=null,$._lookupCache={};var Y=$;while(Y=Y.parent)Y._lookupCache={};return $}Object.defineProperty(a.prototype,"nestedArray",{get:function(){return this._nestedArray||(this._nestedArray=l9.toArray(this.nested))}});a.prototype.toJSON=function(Y){return l9.toObject(["options",this.options,"nested",hG(this.nestedArray,Y)])};a.prototype.addJSON=function(Y){var X=this;if(Y)for(var Q=Object.keys(Y),J=0,Z;J<Q.length;++J)Z=Y[Q[J]],X.add((Z.fields!==void 0?o$.fromJSON:Z.values!==void 0?s$.fromJSON:Z.methods!==void 0?xY.fromJSON:Z.id!==void 0?OQ.fromJSON:a.fromJSON)(Q[J],Z));return this};a.prototype.get=function(Y){return this.nested&&this.nested[Y]||null};a.prototype.getEnum=function(Y){if(this.nested&&this.nested[Y]instanceof s$)return this.nested[Y].values;throw Error("no such enum: "+Y)};a.prototype.add=function(Y){if(!(Y instanceof OQ&&Y.extend!==void 0||Y instanceof o$||Y instanceof LB||Y instanceof s$||Y instanceof xY||Y instanceof a))throw TypeError("object must be a valid nested object");if(!this.nested)this.nested={};else{var X=this.get(Y.name);if(X)if(X instanceof a&&Y instanceof a&&!(X instanceof o$||X instanceof xY)){var Q=X.nestedArray;for(var J=0;J<Q.length;++J)Y.add(Q[J]);if(this.remove(X),!this.nested)this.nested={};Y.setOptions(X.options,!0)}else throw Error("duplicate name '"+Y.name+"' in "+this)}if(this.nested[Y.name]=Y,!(this instanceof o$||this instanceof xY||this instanceof s$||this instanceof OQ)){if(!Y._edition)Y._edition=Y._defaultEdition}this._needsRecursiveFeatureResolution=!0,this._needsRecursiveResolve=!0;var Z=this;while(Z=Z.parent)Z._needsRecursiveFeatureResolution=!0,Z._needsRecursiveResolve=!0;return Y.onAdd(this),_G(this)};a.prototype.remove=function(Y){if(!(Y instanceof n9))throw TypeError("object must be a ReflectionObject");if(Y.parent!==this)throw Error(Y+" is not a member of "+this);if(delete this.nested[Y.name],!Object.keys(this.nested).length)this.nested=void 0;return Y.onRemove(this),_G(this)};a.prototype.define=function(Y,X){if(l9.isString(Y))Y=Y.split(".");else if(!Array.isArray(Y))throw TypeError("illegal path");if(Y&&Y.length&&Y[0]==="")throw Error("path must be relative");var Q=this;while(Y.length>0){var J=Y.shift();if(Q.nested&&Q.nested[J]){if(Q=Q.nested[J],!(Q instanceof a))throw Error("path conflicts with non-namespace objects")}else Q.add(Q=new a(J))}if(X)Q.addJSON(X);return Q};a.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;this._resolveFeaturesRecursive(this._edition);var Y=this.nestedArray,X=0;this.resolve();while(X<Y.length)if(Y[X]instanceof a)Y[X++].resolveAll();else Y[X++].resolve();return this._needsRecursiveResolve=!1,this};a.prototype._resolveFeaturesRecursive=function(Y){if(!this._needsRecursiveFeatureResolution)return this;return this._needsRecursiveFeatureResolution=!1,Y=this._edition||Y,n9.prototype._resolveFeaturesRecursive.call(this,Y),this.nestedArray.forEach((X)=>{X._resolveFeaturesRecursive(Y)}),this};a.prototype.lookup=function(Y,X,Q){if(typeof X==="boolean")Q=X,X=void 0;else if(X&&!Array.isArray(X))X=[X];if(l9.isString(Y)&&Y.length){if(Y===".")return this.root;Y=Y.split(".")}else if(!Y.length)return this;var J=Y.join(".");if(Y[0]==="")return this.root.lookup(Y.slice(1),X);var Z=this.root._fullyQualifiedObjects&&this.root._fullyQualifiedObjects["."+J];if(Z&&(!X||X.indexOf(Z.constructor)>-1))return Z;if(Z=this._lookupImpl(Y,J),Z&&(!X||X.indexOf(Z.constructor)>-1))return Z;if(Q)return null;var T=this;while(T.parent){if(Z=T.parent._lookupImpl(Y,J),Z&&(!X||X.indexOf(Z.constructor)>-1))return Z;T=T.parent}return null};a.prototype._lookupImpl=function(Y,X){if(Object.prototype.hasOwnProperty.call(this._lookupCache,X))return this._lookupCache[X];var Q=this.get(Y[0]),J=null;if(Q){if(Y.length===1)J=Q;else if(Q instanceof a)Y=Y.slice(1),J=Q._lookupImpl(Y,Y.join("."))}else for(var Z=0;Z<this.nestedArray.length;++Z)if(this._nestedArray[Z]instanceof a&&(Q=this._nestedArray[Z]._lookupImpl(Y,X)))J=Q;return this._lookupCache[X]=J,J};a.prototype.lookupType=function(Y){var X=this.lookup(Y,[o$]);if(!X)throw Error("no such type: "+Y);return X};a.prototype.lookupEnum=function(Y){var X=this.lookup(Y,[s$]);if(!X)throw Error("no such Enum '"+Y+"' in "+this);return X};a.prototype.lookupTypeOrEnum=function(Y){var X=this.lookup(Y,[o$,s$]);if(!X)throw Error("no such Type or Enum '"+Y+"' in "+this);return X};a.prototype.lookupService=function(Y){var X=this.lookup(Y,[xY]);if(!X)throw Error("no such Service '"+Y+"' in "+this);return X};a._configure=function($,Y,X){o$=$,xY=Y,s$=X}});var i9=M((oh,fG)=>{fG.exports=Q$;var PQ=P$();((Q$.prototype=Object.create(PQ.prototype)).constructor=Q$).className="MapField";var SB=t$(),h6=S0();function Q$($,Y,X,Q,J,Z){if(PQ.call(this,$,Y,Q,void 0,void 0,J,Z),!h6.isString(X))throw TypeError("keyType must be a string");this.keyType=X,this.resolvedKeyType=null,this.map=!0}Q$.fromJSON=function(Y,X){return new Q$(Y,X.id,X.keyType,X.type,X.options,X.comment)};Q$.prototype.toJSON=function(Y){var X=Y?Boolean(Y.keepComments):!1;return h6.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",X?this.comment:void 0])};Q$.prototype.resolve=function(){if(this.resolved)return this;if(SB.mapKey[this.keyType]===void 0)throw Error("invalid key type: "+this.keyType);return PQ.prototype.resolve.call(this)};Q$.d=function(Y,X,Q){if(typeof Q==="function")Q=h6.decorateType(Q).name;else if(Q&&typeof Q==="object")Q=h6.decorateEnum(Q).name;return function(Z,T){h6.decorateType(Z.constructor).add(new Q$(T,Y,X,Q))}}});var r9=M((sh,mG)=>{mG.exports=e$;var LQ=L$();((e$.prototype=Object.create(LQ.prototype)).constructor=e$).className="Method";var kY=S0();function e$($,Y,X,Q,J,Z,T,K,U){if(kY.isObject(J))T=J,J=Z=void 0;else if(kY.isObject(Z))T=Z,Z=void 0;if(!(Y===void 0||kY.isString(Y)))throw TypeError("type must be a string");if(!kY.isString(X))throw TypeError("requestType must be a string");if(!kY.isString(Q))throw TypeError("responseType must be a string");LQ.call(this,$,T),this.type=Y||"rpc",this.requestType=X,this.requestStream=J?!0:void 0,this.responseType=Q,this.responseStream=Z?!0:void 0,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=K,this.parsedOptions=U}e$.fromJSON=function(Y,X){return new e$(Y,X.type,X.requestType,X.responseType,X.requestStream,X.responseStream,X.options,X.comment,X.parsedOptions)};e$.prototype.toJSON=function(Y){var X=Y?Boolean(Y.keepComments):!1;return kY.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",X?this.comment:void 0,"parsedOptions",this.parsedOptions])};e$.prototype.resolve=function(){if(this.resolved)return this;return this.resolvedRequestType=this.parent.lookupType(this.requestType),this.resolvedResponseType=this.parent.lookupType(this.responseType),LQ.prototype.resolve.call(this)}});var o9=M((ah,uG)=>{uG.exports=$1;var J$=vY();(($1.prototype=Object.create(J$.prototype)).constructor=$1).className="Service";var SQ=r9(),_6=S0(),wB=zQ();function $1($,Y){J$.call(this,$,Y),this.methods={},this._methodsArray=null}$1.fromJSON=function(Y,X){var Q=new $1(Y,X.options);if(X.methods)for(var J=Object.keys(X.methods),Z=0;Z<J.length;++Z)Q.add(SQ.fromJSON(J[Z],X.methods[J[Z]]));if(X.nested)Q.addJSON(X.nested);if(X.edition)Q._edition=X.edition;return Q.comment=X.comment,Q._defaultEdition="proto3",Q};$1.prototype.toJSON=function(Y){var X=J$.prototype.toJSON.call(this,Y),Q=Y?Boolean(Y.keepComments):!1;return _6.toObject(["edition",this._editionToJSON(),"options",X&&X.options||void 0,"methods",J$.arrayToJSON(this.methodsArray,Y)||{},"nested",X&&X.nested||void 0,"comment",Q?this.comment:void 0])};Object.defineProperty($1.prototype,"methodsArray",{get:function(){return this._methodsArray||(this._methodsArray=_6.toArray(this.methods))}});function bG($){return $._methodsArray=null,$}$1.prototype.get=function(Y){return this.methods[Y]||J$.prototype.get.call(this,Y)};$1.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;J$.prototype.resolve.call(this);var Y=this.methodsArray;for(var X=0;X<Y.length;++X)Y[X].resolve();return this};$1.prototype._resolveFeaturesRecursive=function(Y){if(!this._needsRecursiveFeatureResolution)return this;return Y=this._edition||Y,J$.prototype._resolveFeaturesRecursive.call(this,Y),this.methodsArray.forEach((X)=>{X._resolveFeaturesRecursive(Y)}),this};$1.prototype.add=function(Y){if(this.get(Y.name))throw Error("duplicate name '"+Y.name+"' in "+this);if(Y instanceof SQ)return this.methods[Y.name]=Y,Y.parent=this,bG(this);return J$.prototype.add.call(this,Y)};$1.prototype.remove=function(Y){if(Y instanceof SQ){if(this.methods[Y.name]!==Y)throw Error(Y+" is not a member of "+this);return delete this.methods[Y.name],Y.parent=null,bG(this)}return J$.prototype.remove.call(this,Y)};$1.prototype.create=function(Y,X,Q){var J=new wB.Service(Y,X,Q);for(var Z=0,T;Z<this.methodsArray.length;++Z){var K=_6.lcFirst((T=this._methodsArray[Z]).resolve().name).replace(/[^$\w_]/g,"");J[K]=_6.codegen(["r","c"],_6.isReserved(K)?K+"_":K)("return this.rpcCall(m,q,s,r,c)")({m:T,q:T.resolvedRequestType.ctor,s:T.resolvedResponseType.ctor})}return J}});var s9=M((th,dG)=>{dG.exports=g1;var CB=h1();function g1($){if($)for(var Y=Object.keys($),X=0;X<Y.length;++X)this[Y[X]]=$[Y[X]]}g1.create=function(Y){return this.$type.create(Y)};g1.encode=function(Y,X){return this.$type.encode(Y,X)};g1.encodeDelimited=function(Y,X){return this.$type.encodeDelimited(Y,X)};g1.decode=function(Y){return this.$type.decode(Y)};g1.decodeDelimited=function(Y){return this.$type.decodeDelimited(Y)};g1.verify=function(Y){return this.$type.verify(Y)};g1.fromObject=function(Y){return this.$type.fromObject(Y)};g1.toObject=function(Y,X){return this.$type.toObject(Y,X)};g1.prototype.toJSON=function(){return this.$type.toObject(this,CB.toJSONOptions)}});var wQ=M((eh,cG)=>{cG.exports=xB;var yB=L1(),Z$=t$(),pG=S0();function jB($){return"missing required '"+$.name+"'"}function xB($){var Y=pG.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(K){return K.map}).length?",k,value":""))("while(r.pos<c){")("var t=r.uint32()")("if(t===e)")("break")("switch(t>>>3){"),X=0;for(;X<$.fieldsArray.length;++X){var Q=$._fieldsArray[X].resolve(),J=Q.resolvedType instanceof yB?"int32":Q.type,Z="m"+pG.safeProp(Q.name);if(Y("case %i: {",Q.id),Q.map){if(Y("if(%s===util.emptyObject)",Z)("%s={}",Z)("var c2 = r.uint32()+r.pos"),Z$.defaults[Q.keyType]!==void 0)Y("k=%j",Z$.defaults[Q.keyType]);else Y("k=null");if(Z$.defaults[J]!==void 0)Y("value=%j",Z$.defaults[J]);else Y("value=null");if(Y("while(r.pos<c2){")("var tag2=r.uint32()")("switch(tag2>>>3){")("case 1: k=r.%s(); break",Q.keyType)("case 2:"),Z$.basic[J]===void 0)Y("value=types[%i].decode(r,r.uint32())",X);else Y("value=r.%s()",J);if(Y("break")("default:")("r.skipType(tag2&7)")("break")("}")("}"),Z$.long[Q.keyType]!==void 0)Y('%s[typeof k==="object"?util.longToHash(k):k]=value',Z);else Y("%s[k]=value",Z)}else if(Q.repeated){if(Y("if(!(%s&&%s.length))",Z,Z)("%s=[]",Z),Z$.packed[J]!==void 0)Y("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos<c2)")("%s.push(r.%s())",Z,J)("}else");if(Z$.basic[J]===void 0)Y(Q.delimited?"%s.push(types[%i].decode(r,undefined,((t&~7)|4)))":"%s.push(types[%i].decode(r,r.uint32()))",Z,X);else Y("%s.push(r.%s())",Z,J)}else if(Z$.basic[J]===void 0)Y(Q.delimited?"%s=types[%i].decode(r,undefined,((t&~7)|4))":"%s=types[%i].decode(r,r.uint32())",Z,X);else Y("%s=r.%s()",Z,J);Y("break")("}")}Y("default:")("r.skipType(t&7)")("break")("}")("}");for(X=0;X<$._fieldsArray.length;++X){var T=$._fieldsArray[X];if(T.required)Y("if(!m.hasOwnProperty(%j))",T.name)("throw util.ProtocolError(%j,{instance:m})",jB(T))}return Y("return m")}});var jQ=M(($_,nG)=>{nG.exports=hB;var vB=L1(),CQ=S0();function V1($,Y){return $.name+": "+Y+($.repeated&&Y!=="array"?"[]":$.map&&Y!=="object"?"{k:"+$.keyType+"}":"")+" expected"}function yQ($,Y,X,Q){if(Y.resolvedType)if(Y.resolvedType instanceof vB){$("switch(%s){",Q)("default:")("return%j",V1(Y,"enum value"));for(var J=Object.keys(Y.resolvedType.values),Z=0;Z<J.length;++Z)$("case %i:",Y.resolvedType.values[J[Z]]);$("break")("}")}else $("{")("var e=types[%i].verify(%s);",X,Q)("if(e)")("return%j+e",Y.name+".")("}");else switch(Y.type){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":$("if(!util.isInteger(%s))",Q)("return%j",V1(Y,"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)))",Q,Q,Q,Q)("return%j",V1(Y,"integer|Long"));break;case"float":case"double":$('if(typeof %s!=="number")',Q)("return%j",V1(Y,"number"));break;case"bool":$('if(typeof %s!=="boolean")',Q)("return%j",V1(Y,"boolean"));break;case"string":$("if(!util.isString(%s))",Q)("return%j",V1(Y,"string"));break;case"bytes":$('if(!(%s&&typeof %s.length==="number"||util.isString(%s)))',Q,Q,Q)("return%j",V1(Y,"buffer"));break}return $}function kB($,Y,X){switch(Y.keyType){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":$("if(!util.key32Re.test(%s))",X)("return%j",V1(Y,"integer key"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":$("if(!util.key64Re.test(%s))",X)("return%j",V1(Y,"integer|Long key"));break;case"bool":$("if(!util.key2Re.test(%s))",X)("return%j",V1(Y,"boolean key"));break}return $}function hB($){var Y=CQ.codegen(["m"],$.name+"$verify")('if(typeof m!=="object"||m===null)')("return%j","object expected"),X=$.oneofsArray,Q={};if(X.length)Y("var p={}");for(var J=0;J<$.fieldsArray.length;++J){var Z=$._fieldsArray[J].resolve(),T="m"+CQ.safeProp(Z.name);if(Z.optional)Y("if(%s!=null&&m.hasOwnProperty(%j)){",T,Z.name);if(Z.map)Y("if(!util.isObject(%s))",T)("return%j",V1(Z,"object"))("var k=Object.keys(%s)",T)("for(var i=0;i<k.length;++i){"),kB(Y,Z,"k[i]"),yQ(Y,Z,J,T+"[k[i]]")("}");else if(Z.repeated)Y("if(!Array.isArray(%s))",T)("return%j",V1(Z,"array"))("for(var i=0;i<%s.length;++i){",T),yQ(Y,Z,J,T+"[i]")("}");else{if(Z.partOf){var K=CQ.safeProp(Z.partOf.name);if(Q[Z.partOf.name]===1)Y("if(p%s===1)",K)("return%j",Z.partOf.name+": multiple values");Q[Z.partOf.name]=1,Y("p%s=1",K)}yQ(Y,Z,J,T)}if(Z.optional)Y("}")}return Y("return null")}});var kQ=M((iG)=>{var lG=iG,g6=L1(),f1=S0();function xQ($,Y,X,Q){var J=!1;if(Y.resolvedType)if(Y.resolvedType instanceof g6){$("switch(d%s){",Q);for(var Z=Y.resolvedType.values,T=Object.keys(Z),K=0;K<T.length;++K){if(Z[T[K]]===Y.typeDefault&&!J){if($("default:")('if(typeof(d%s)==="number"){m%s=d%s;break}',Q,Q,Q),!Y.repeated)$("break");J=!0}$("case%j:",T[K])("case %i:",Z[T[K]])("m%s=%j",Q,Z[T[K]])("break")}$("}")}else $('if(typeof d%s!=="object")',Q)("throw TypeError(%j)",Y.fullName+": object expected")("m%s=types[%i].fromObject(d%s)",Q,X,Q);else{var U=!1;switch(Y.type){case"double":case"float":$("m%s=Number(d%s)",Q,Q);break;case"uint32":case"fixed32":$("m%s=d%s>>>0",Q,Q);break;case"int32":case"sint32":case"sfixed32":$("m%s=d%s|0",Q,Q);break;case"uint64":U=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":$("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",Q,Q,U)('else if(typeof d%s==="string")',Q)("m%s=parseInt(d%s,10)",Q,Q)('else if(typeof d%s==="number")',Q)("m%s=d%s",Q,Q)('else if(typeof d%s==="object")',Q)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",Q,Q,Q,U?"true":"");break;case"bytes":$('if(typeof d%s==="string")',Q)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",Q,Q,Q)("else if(d%s.length >= 0)",Q)("m%s=d%s",Q,Q);break;case"string":$("m%s=String(d%s)",Q,Q);break;case"bool":$("m%s=Boolean(d%s)",Q,Q);break}}return $}lG.fromObject=function(Y){var X=Y.fieldsArray,Q=f1.codegen(["d"],Y.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!X.length)return Q("return new this.ctor");Q("var m=new this.ctor");for(var J=0;J<X.length;++J){var Z=X[J].resolve(),T=f1.safeProp(Z.name);if(Z.map)Q("if(d%s){",T)('if(typeof d%s!=="object")',T)("throw TypeError(%j)",Z.fullName+": object expected")("m%s={}",T)("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){",T),xQ(Q,Z,J,T+"[ks[i]]")("}")("}");else if(Z.repeated)Q("if(d%s){",T)("if(!Array.isArray(d%s))",T)("throw TypeError(%j)",Z.fullName+": array expected")("m%s=[]",T)("for(var i=0;i<d%s.length;++i){",T),xQ(Q,Z,J,T+"[i]")("}")("}");else{if(!(Z.resolvedType instanceof g6))Q("if(d%s!=null){",T);if(xQ(Q,Z,J,T),!(Z.resolvedType instanceof g6))Q("}")}}return Q("return m")};function vQ($,Y,X,Q){if(Y.resolvedType)if(Y.resolvedType instanceof g6)$("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",Q,X,Q,Q,X,Q,Q);else $("d%s=types[%i].toObject(m%s,o)",Q,X,Q);else{var J=!1;switch(Y.type){case"double":case"float":$("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",Q,Q,Q,Q);break;case"uint64":J=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":$('if(typeof m%s==="number")',Q)("d%s=o.longs===String?String(m%s):m%s",Q,Q,Q)("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",Q,Q,Q,Q,J?"true":"",Q);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",Q,Q,Q,Q,Q);break;default:$("d%s=m%s",Q,Q);break}}return $}lG.toObject=function(Y){var X=Y.fieldsArray.slice().sort(f1.compareFieldsById);if(!X.length)return f1.codegen()("return {}");var Q=f1.codegen(["m","o"],Y.name+"$toObject")("if(!o)")("o={}")("var d={}"),J=[],Z=[],T=[],K=0;for(;K<X.length;++K)if(!X[K].partOf)(X[K].resolve().repeated?J:X[K].map?Z:T).push(X[K]);if(J.length){Q("if(o.arrays||o.defaults){");for(K=0;K<J.length;++K)Q("d%s=[]",f1.safeProp(J[K].name));Q("}")}if(Z.length){Q("if(o.objects||o.defaults){");for(K=0;K<Z.length;++K)Q("d%s={}",f1.safeProp(Z[K].name));Q("}")}if(T.length){Q("if(o.defaults){");for(K=0;K<T.length;++K){var U=T[K],G=f1.safeProp(U.name);if(U.resolvedType instanceof g6)Q("d%s=o.enums===String?%j:%j",G,U.resolvedType.valuesById[U.typeDefault],U.typeDefault);else if(U.long)Q("if(util.Long){")("var n=new util.Long(%i,%i,%j)",U.typeDefault.low,U.typeDefault.high,U.typeDefault.unsigned)("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n",G)("}else")("d%s=o.longs===String?%j:%i",G,U.typeDefault.toString(),U.typeDefault.toNumber());else if(U.bytes){var W="["+Array.prototype.slice.call(U.typeDefault).join(",")+"]";Q("if(o.bytes===String)d%s=%j",G,String.fromCharCode.apply(String,U.typeDefault))("else{")("d%s=%s",G,W)("if(o.bytes!==Array)d%s=util.newBuffer(d%s)",G,G)("}")}else Q("d%s=%j",G,U.typeDefault)}Q("}")}var R=!1;for(K=0;K<X.length;++K){var U=X[K],V=Y._fieldsArray.indexOf(U),G=f1.safeProp(U.name);if(U.map){if(!R)R=!0,Q("var ks2");Q("if(m%s&&(ks2=Object.keys(m%s)).length){",G,G)("d%s={}",G)("for(var j=0;j<ks2.length;++j){"),vQ(Q,U,V,G+"[ks2[j]]")("}")}else if(U.repeated)Q("if(m%s&&m%s.length){",G,G)("d%s=[]",G)("for(var j=0;j<m%s.length;++j){",G),vQ(Q,U,V,G+"[j]")("}");else if(Q("if(m%s!=null&&m.hasOwnProperty(%j)){",G,U.name),vQ(Q,U,V,G),U.partOf)Q("if(o.oneofs)")("d%s=%j",f1.safeProp(U.partOf.name),U.name);Q("}")}return Q("return d")}});var hQ=M((rG)=>{var _B=rG,gB=s9();_B[".google.protobuf.Any"]={fromObject:function($){if($&&$["@type"]){var Y=$["@type"].substring($["@type"].lastIndexOf("/")+1),X=this.lookup(Y);if(X){var Q=$["@type"].charAt(0)==="."?$["@type"].slice(1):$["@type"];if(Q.indexOf("/")===-1)Q="/"+Q;return this.create({type_url:Q,value:X.encode(X.fromObject($)).finish()})}}return this.fromObject($)},toObject:function($,Y){var X="type.googleapis.com/",Q="",J="";if(Y&&Y.json&&$.type_url&&$.value){J=$.type_url.substring($.type_url.lastIndexOf("/")+1),Q=$.type_url.substring(0,$.type_url.lastIndexOf("/")+1);var Z=this.lookup(J);if(Z)$=Z.decode($.value)}if(!($ instanceof this.ctor)&&$ instanceof gB){var T=$.$type.toObject($,Y),K=$.$type.fullName[0]==="."?$.$type.fullName.slice(1):$.$type.fullName;if(Q==="")Q=X;return J=Q+K,T["@type"]=J,T}return this.toObject($,Y)}}});var e9=M((Q_,sG)=>{sG.exports=T0;var A1=vY();((T0.prototype=Object.create(A1.prototype)).constructor=T0).className="Type";var fB=L1(),fQ=a$(),a9=P$(),mB=i9(),bB=o9(),_Q=s9(),gQ=c9(),uB=d9(),m0=S0(),dB=mQ(),pB=wQ(),cB=jQ(),oG=kQ(),nB=hQ();function T0($,Y){A1.call(this,$,Y),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(T0.prototype,{fieldsById:{get:function(){if(this._fieldsById)return this._fieldsById;this._fieldsById={};for(var $=Object.keys(this.fields),Y=0;Y<$.length;++Y){var X=this.fields[$[Y]],Q=X.id;if(this._fieldsById[Q])throw Error("duplicate id "+Q+" in "+this);this._fieldsById[Q]=X}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=T0.generateConstructor(this)())},set:function($){var Y=$.prototype;if(!(Y instanceof _Q))($.prototype=new _Q).constructor=$,m0.merge($.prototype,Y);$.$type=$.prototype.$type=this,m0.merge($,_Q,!0),this._ctor=$;var X=0;for(;X<this.fieldsArray.length;++X)this._fieldsArray[X].resolve();var Q={};for(X=0;X<this.oneofsArray.length;++X)Q[this._oneofsArray[X].resolve().name]={get:m0.oneOfGetter(this._oneofsArray[X].oneof),set:m0.oneOfSetter(this._oneofsArray[X].oneof)};if(X)Object.defineProperties($.prototype,Q)}}});T0.generateConstructor=function(Y){var X=m0.codegen(["p"],Y.name);for(var Q=0,J;Q<Y.fieldsArray.length;++Q)if((J=Y._fieldsArray[Q]).map)X("this%s={}",m0.safeProp(J.name));else if(J.repeated)X("this%s=[]",m0.safeProp(J.name));return X("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 t9($){return $._fieldsById=$._fieldsArray=$._oneofsArray=null,delete $.encode,delete $.decode,delete $.verify,$}T0.fromJSON=function(Y,X){var Q=new T0(Y,X.options);Q.extensions=X.extensions,Q.reserved=X.reserved;var J=Object.keys(X.fields),Z=0;for(;Z<J.length;++Z)Q.add((typeof X.fields[J[Z]].keyType<"u"?mB.fromJSON:a9.fromJSON)(J[Z],X.fields[J[Z]]));if(X.oneofs)for(J=Object.keys(X.oneofs),Z=0;Z<J.length;++Z)Q.add(fQ.fromJSON(J[Z],X.oneofs[J[Z]]));if(X.nested)for(J=Object.keys(X.nested),Z=0;Z<J.length;++Z){var T=X.nested[J[Z]];Q.add((T.id!==void 0?a9.fromJSON:T.fields!==void 0?T0.fromJSON:T.values!==void 0?fB.fromJSON:T.methods!==void 0?bB.fromJSON:A1.fromJSON)(J[Z],T))}if(X.extensions&&X.extensions.length)Q.extensions=X.extensions;if(X.reserved&&X.reserved.length)Q.reserved=X.reserved;if(X.group)Q.group=!0;if(X.comment)Q.comment=X.comment;if(X.edition)Q._edition=X.edition;return Q._defaultEdition="proto3",Q};T0.prototype.toJSON=function(Y){var X=A1.prototype.toJSON.call(this,Y),Q=Y?Boolean(Y.keepComments):!1;return m0.toObject(["edition",this._editionToJSON(),"options",X&&X.options||void 0,"oneofs",A1.arrayToJSON(this.oneofsArray,Y),"fields",A1.arrayToJSON(this.fieldsArray.filter(function(J){return!J.declaringField}),Y)||{},"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",X&&X.nested||void 0,"comment",Q?this.comment:void 0])};T0.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;A1.prototype.resolveAll.call(this);var Y=this.oneofsArray;Q=0;while(Q<Y.length)Y[Q++].resolve();var X=this.fieldsArray,Q=0;while(Q<X.length)X[Q++].resolve();return this};T0.prototype._resolveFeaturesRecursive=function(Y){if(!this._needsRecursiveFeatureResolution)return this;return Y=this._edition||Y,A1.prototype._resolveFeaturesRecursive.call(this,Y),this.oneofsArray.forEach((X)=>{X._resolveFeatures(Y)}),this.fieldsArray.forEach((X)=>{X._resolveFeatures(Y)}),this};T0.prototype.get=function(Y){return this.fields[Y]||this.oneofs&&this.oneofs[Y]||this.nested&&this.nested[Y]||null};T0.prototype.add=function(Y){if(this.get(Y.name))throw Error("duplicate name '"+Y.name+"' in "+this);if(Y instanceof a9&&Y.extend===void 0){if(this._fieldsById?this._fieldsById[Y.id]:this.fieldsById[Y.id])throw Error("duplicate id "+Y.id+" in "+this);if(this.isReservedId(Y.id))throw Error("id "+Y.id+" is reserved in "+this);if(this.isReservedName(Y.name))throw Error("name '"+Y.name+"' is reserved in "+this);if(Y.parent)Y.parent.remove(Y);return this.fields[Y.name]=Y,Y.message=this,Y.onAdd(this),t9(this)}if(Y instanceof fQ){if(!this.oneofs)this.oneofs={};return this.oneofs[Y.name]=Y,Y.onAdd(this),t9(this)}return A1.prototype.add.call(this,Y)};T0.prototype.remove=function(Y){if(Y instanceof a9&&Y.extend===void 0){if(!this.fields||this.fields[Y.name]!==Y)throw Error(Y+" is not a member of "+this);return delete this.fields[Y.name],Y.parent=null,Y.onRemove(this),t9(this)}if(Y instanceof fQ){if(!this.oneofs||this.oneofs[Y.name]!==Y)throw Error(Y+" is not a member of "+this);return delete this.oneofs[Y.name],Y.parent=null,Y.onRemove(this),t9(this)}return A1.prototype.remove.call(this,Y)};T0.prototype.isReservedId=function(Y){return A1.isReservedId(this.reserved,Y)};T0.prototype.isReservedName=function(Y){return A1.isReservedName(this.reserved,Y)};T0.prototype.create=function(Y){return new this.ctor(Y)};T0.prototype.setup=function(){var Y=this.fullName,X=[];for(var Q=0;Q<this.fieldsArray.length;++Q)X.push(this._fieldsArray[Q].resolve().resolvedType);this.encode=dB(this)({Writer:uB,types:X,util:m0}),this.decode=pB(this)({Reader:gQ,types:X,util:m0}),this.verify=cB(this)({types:X,util:m0}),this.fromObject=oG.fromObject(this)({types:X,util:m0}),this.toObject=oG.toObject(this)({types:X,util:m0});var J=nB[Y];if(J){var Z=Object.create(this);Z.fromObject=this.fromObject,this.fromObject=J.fromObject.bind(Z),Z.toObject=this.toObject,this.toObject=J.toObject.bind(Z)}return this};T0.prototype.encode=function(Y,X){return this.setup().encode(Y,X)};T0.prototype.encodeDelimited=function(Y,X){return this.encode(Y,X&&X.len?X.fork():X).ldelim()};T0.prototype.decode=function(Y,X){return this.setup().decode(Y,X)};T0.prototype.decodeDelimited=function(Y){if(!(Y instanceof gQ))Y=gQ.create(Y);return this.decode(Y,Y.uint32())};T0.prototype.verify=function(Y){return this.setup().verify(Y)};T0.prototype.fromObject=function(Y){return this.setup().fromObject(Y)};T0.prototype.toObject=function(Y,X){return this.setup().toObject(Y,X)};T0.d=function(Y){return function(Q){m0.decorateType(Q,Y)}}});var Q4=M((J_,eG)=>{eG.exports=Y1;var X4=vY();((Y1.prototype=Object.create(X4.prototype)).constructor=Y1).className="Root";var $4=P$(),bQ=L1(),lB=a$(),S$=S0(),uQ,dQ,f6;function Y1($){X4.call(this,"",$),this.deferred=[],this.files=[],this._edition="proto2",this._fullyQualifiedObjects={}}Y1.fromJSON=function(Y,X){if(!X)X=new Y1;if(Y.options)X.setOptions(Y.options);return X.addJSON(Y.nested).resolveAll()};Y1.prototype.resolvePath=S$.path.resolve;Y1.prototype.fetch=S$.fetch;function tG(){}Y1.prototype.load=function $(Y,X,Q){if(typeof X==="function")Q=X,X=void 0;var J=this;if(!Q)return S$.asPromise($,J,Y,X);var Z=Q===tG;function T(A,H){if(!Q)return;if(Z)throw A;if(H)H.resolveAll();var z=Q;Q=null,z(A,H)}function K(A){var H=A.lastIndexOf("google/protobuf/");if(H>-1){var z=A.substring(H);if(z in f6)return z}return null}function U(A,H){try{if(S$.isString(H)&&H.charAt(0)==="{")H=JSON.parse(H);if(!S$.isString(H))J.setOptions(H.options).addJSON(H.nested);else{dQ.filename=A;var z=dQ(H,J,X),D,B=0;if(z.imports){for(;B<z.imports.length;++B)if(D=K(z.imports[B])||J.resolvePath(A,z.imports[B]))G(D)}if(z.weakImports){for(B=0;B<z.weakImports.length;++B)if(D=K(z.weakImports[B])||J.resolvePath(A,z.weakImports[B]))G(D,!0)}}}catch(w){T(w)}if(!Z&&!W)T(null,J)}function G(A,H){if(A=K(A)||A,J.files.indexOf(A)>-1)return;if(J.files.push(A),A in f6){if(Z)U(A,f6[A]);else++W,setTimeout(function(){--W,U(A,f6[A])});return}if(Z){var z;try{z=S$.fs.readFileSync(A).toString("utf8")}catch(D){if(!H)T(D);return}U(A,z)}else++W,J.fetch(A,function(D,B){if(--W,!Q)return;if(D){if(!H)T(D);else if(!W)T(null,J);return}U(A,B)})}var W=0;if(S$.isString(Y))Y=[Y];for(var R=0,V;R<Y.length;++R)if(V=J.resolvePath("",Y[R]))G(V);if(Z)return J.resolveAll(),J;if(!W)T(null,J);return J};Y1.prototype.loadSync=function(Y,X){if(!S$.isNode)throw Error("not supported");return this.load(Y,X,tG)};Y1.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;if(this.deferred.length)throw Error("unresolvable extensions: "+this.deferred.map(function(Y){return"'extend "+Y.extend+"' in "+Y.parent.fullName}).join(", "));return X4.prototype.resolveAll.call(this)};var Y4=/^[A-Z]/;function aG($,Y){var X=Y.parent.lookup(Y.extend);if(X){var Q=new $4(Y.fullName,Y.id,Y.type,Y.rule,void 0,Y.options);if(X.get(Q.name))return!0;return Q.declaringField=Y,Y.extensionField=Q,X.add(Q),!0}return!1}Y1.prototype._handleAdd=function(Y){if(Y instanceof $4){if(Y.extend!==void 0&&!Y.extensionField){if(!aG(this,Y))this.deferred.push(Y)}}else if(Y instanceof bQ){if(Y4.test(Y.name))Y.parent[Y.name]=Y.values}else if(!(Y instanceof lB)){if(Y instanceof uQ)for(var X=0;X<this.deferred.length;)if(aG(this,this.deferred[X]))this.deferred.splice(X,1);else++X;for(var Q=0;Q<Y.nestedArray.length;++Q)this._handleAdd(Y._nestedArray[Q]);if(Y4.test(Y.name))Y.parent[Y.name]=Y}if(Y instanceof uQ||Y instanceof bQ||Y instanceof $4)this._fullyQualifiedObjects[Y.fullName]=Y};Y1.prototype._handleRemove=function(Y){if(Y instanceof $4){if(Y.extend!==void 0)if(Y.extensionField)Y.extensionField.parent.remove(Y.extensionField),Y.extensionField=null;else{var X=this.deferred.indexOf(Y);if(X>-1)this.deferred.splice(X,1)}}else if(Y instanceof bQ){if(Y4.test(Y.name))delete Y.parent[Y.name]}else if(Y instanceof X4){for(var Q=0;Q<Y.nestedArray.length;++Q)this._handleRemove(Y._nestedArray[Q]);if(Y4.test(Y.name))delete Y.parent[Y.name]}delete this._fullyQualifiedObjects[Y.fullName]};Y1._configure=function($,Y,X){uQ=$,dQ=Y,f6=X}});var S0=M((Z_,YW)=>{var D0=YW.exports=h1(),$W=qQ(),pQ,cQ;D0.codegen=CG();D0.fetch=jG();D0.path=kG();D0.fs=D0.inquire("fs");D0.toArray=function(Y){if(Y){var X=Object.keys(Y),Q=Array(X.length),J=0;while(J<X.length)Q[J]=Y[X[J++]];return Q}return[]};D0.toObject=function(Y){var X={},Q=0;while(Q<Y.length){var J=Y[Q++],Z=Y[Q++];if(Z!==void 0)X[J]=Z}return X};var iB=/\\/g,rB=/"/g;D0.isReserved=function(Y){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(Y)};D0.safeProp=function(Y){if(!/^[$\w_]+$/.test(Y)||D0.isReserved(Y))return'["'+Y.replace(iB,"\\\\").replace(rB,"\\\"")+'"]';return"."+Y};D0.ucFirst=function(Y){return Y.charAt(0).toUpperCase()+Y.substring(1)};var oB=/_([a-z])/g;D0.camelCase=function(Y){return Y.substring(0,1)+Y.substring(1).replace(oB,function(X,Q){return Q.toUpperCase()})};D0.compareFieldsById=function(Y,X){return Y.id-X.id};D0.decorateType=function(Y,X){if(Y.$type){if(X&&Y.$type.name!==X)D0.decorateRoot.remove(Y.$type),Y.$type.name=X,D0.decorateRoot.add(Y.$type);return Y.$type}if(!pQ)pQ=e9();var Q=new pQ(X||Y.name);return D0.decorateRoot.add(Q),Q.ctor=Y,Object.defineProperty(Y,"$type",{value:Q,enumerable:!1}),Object.defineProperty(Y.prototype,"$type",{value:Q,enumerable:!1}),Q};var sB=0;D0.decorateEnum=function(Y){if(Y.$type)return Y.$type;if(!cQ)cQ=L1();var X=new cQ("Enum"+sB++,Y);return D0.decorateRoot.add(X),Object.defineProperty(Y,"$type",{value:X,enumerable:!1}),X};D0.setProperty=function(Y,X,Q,J){function Z(T,K,U){var G=K.shift();if(G==="__proto__"||G==="prototype")return T;if(K.length>0)T[G]=Z(T[G]||{},K,U);else{var W=T[G];if(W&&J)return T;if(W)U=[].concat(W).concat(U);T[G]=U}return T}if(typeof Y!=="object")throw TypeError("dst must be an object");if(!X)throw TypeError("path must be specified");return X=X.split("."),Z(Y,X,Q)};Object.defineProperty(D0,"decorateRoot",{get:function(){return $W.decorated||($W.decorated=new(Q4()))}})});var t$=M((XW)=>{var m6=XW,aB=S0(),tB=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function b6($,Y){var X=0,Q={};Y|=0;while(X<$.length)Q[tB[X+Y]]=$[X++];return Q}m6.basic=b6([1,5,0,0,0,5,5,0,0,0,1,1,0,2,2]);m6.defaults=b6([0,0,0,0,0,0,0,0,0,0,0,0,!1,"",aB.emptyArray,null]);m6.long=b6([0,0,0,1,1],7);m6.mapKey=b6([0,0,0,5,5,0,0,0,1,1,0,2],2);m6.packed=b6([1,5,0,0,0,5,5,0,0,0,1,1,0])});var P$=M((K_,JW)=>{JW.exports=w0;var d6=L$();((w0.prototype=Object.create(d6.prototype)).constructor=w0).className="Field";var QW=L1(),nQ=t$(),N0=S0(),u6,eB=/^required|optional|repeated$/;w0.fromJSON=function(Y,X){var Q=new w0(Y,X.id,X.type,X.rule,X.extend,X.options,X.comment);if(X.edition)Q._edition=X.edition;return Q._defaultEdition="proto3",Q};function w0($,Y,X,Q,J,Z,T){if(N0.isObject(Q))T=J,Z=Q,Q=J=void 0;else if(N0.isObject(J))T=Z,Z=J,J=void 0;if(d6.call(this,$,Z),!N0.isInteger(Y)||Y<0)throw TypeError("id must be a non-negative integer");if(!N0.isString(X))throw TypeError("type must be a string");if(Q!==void 0&&!eB.test(Q=Q.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(J!==void 0&&!N0.isString(J))throw TypeError("extend must be a string");if(Q==="proto3_optional")Q="optional";this.rule=Q&&Q!=="optional"?Q:void 0,this.type=X,this.id=Y,this.extend=J||void 0,this.repeated=Q==="repeated",this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=N0.Long?nQ.long[X]!==void 0:!1,this.bytes=X==="bytes",this.resolvedType=null,this.extensionField=null,this.declaringField=null,this.comment=T}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 u6&&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(Y,X,Q){return d6.prototype.setOption.call(this,Y,X,Q)};w0.prototype.toJSON=function(Y){var X=Y?Boolean(Y.keepComments):!1;return N0.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",X?this.comment:void 0])};w0.prototype.resolve=function(){if(this.resolved)return this;if((this.typeDefault=nQ.defaults[this.type])===void 0)if(this.resolvedType=(this.declaringField?this.declaringField.parent:this.parent).lookupTypeOrEnum(this.type),this.resolvedType instanceof u6)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 QW&&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 QW))delete this.options.packed;if(!Object.keys(this.options).length)this.options=void 0}if(this.long){if(this.typeDefault=N0.Long.fromNumber(this.typeDefault,this.type.charAt(0)==="u"),Object.freeze)Object.freeze(this.typeDefault)}else if(this.bytes&&typeof this.typeDefault==="string"){var Y;if(N0.base64.test(this.typeDefault))N0.base64.decode(this.typeDefault,Y=N0.newBuffer(N0.base64.length(this.typeDefault)),0);else N0.utf8.write(this.typeDefault,Y=N0.newBuffer(N0.utf8.length(this.typeDefault)),0);this.typeDefault=Y}if(this.map)this.defaultValue=N0.emptyObject;else if(this.repeated)this.defaultValue=N0.emptyArray;else this.defaultValue=this.typeDefault;if(this.parent instanceof u6)this.parent.ctor.prototype[this.name]=this.defaultValue;return d6.prototype.resolve.call(this)};w0.prototype._inferLegacyProtoFeatures=function(Y){if(Y!=="proto2"&&Y!=="proto3")return{};var X={};if(this.rule==="required")X.field_presence="LEGACY_REQUIRED";if(this.parent&&nQ.defaults[this.type]===void 0){var Q=this.parent.get(this.type.split(".").pop());if(Q&&Q instanceof u6&&Q.group)X.message_encoding="DELIMITED"}if(this.getOption("packed")===!0)X.repeated_field_encoding="PACKED";else if(this.getOption("packed")===!1)X.repeated_field_encoding="EXPANDED";return X};w0.prototype._resolveFeatures=function(Y){return d6.prototype._resolveFeatures.call(this,this._edition||Y)};w0.d=function(Y,X,Q,J){if(typeof X==="function")X=N0.decorateType(X).name;else if(X&&typeof X==="object")X=N0.decorateEnum(X).name;return function(T,K){N0.decorateType(T.constructor).add(new w0(K,Y,X,Q,{default:J}))}};w0._configure=function(Y){u6=Y}});var a$=M((U_,KW)=>{KW.exports=X1;var Z4=L$();((X1.prototype=Object.create(Z4.prototype)).constructor=X1).className="OneOf";var ZW=P$(),J4=S0();function X1($,Y,X,Q){if(!Array.isArray(Y))X=Y,Y=void 0;if(Z4.call(this,$,X),!(Y===void 0||Array.isArray(Y)))throw TypeError("fieldNames must be an Array");this.oneof=Y||[],this.fieldsArray=[],this.comment=Q}X1.fromJSON=function(Y,X){return new X1(Y,X.oneof,X.options,X.comment)};X1.prototype.toJSON=function(Y){var X=Y?Boolean(Y.keepComments):!1;return J4.toObject(["options",this.options,"oneof",this.oneof,"comment",X?this.comment:void 0])};function TW($){if($.parent){for(var Y=0;Y<$.fieldsArray.length;++Y)if(!$.fieldsArray[Y].parent)$.parent.add($.fieldsArray[Y])}}X1.prototype.add=function(Y){if(!(Y instanceof ZW))throw TypeError("field must be a Field");if(Y.parent&&Y.parent!==this.parent)Y.parent.remove(Y);return this.oneof.push(Y.name),this.fieldsArray.push(Y),Y.partOf=this,TW(this),this};X1.prototype.remove=function(Y){if(!(Y instanceof ZW))throw TypeError("field must be a Field");var X=this.fieldsArray.indexOf(Y);if(X<0)throw Error(Y+" is not a member of "+this);if(this.fieldsArray.splice(X,1),X=this.oneof.indexOf(Y.name),X>-1)this.oneof.splice(X,1);return Y.partOf=null,this};X1.prototype.onAdd=function(Y){Z4.prototype.onAdd.call(this,Y);var X=this;for(var Q=0;Q<this.oneof.length;++Q){var J=Y.get(this.oneof[Q]);if(J&&!J.partOf)J.partOf=X,X.fieldsArray.push(J)}TW(this)};X1.prototype.onRemove=function(Y){for(var X=0,Q;X<this.fieldsArray.length;++X)if((Q=this.fieldsArray[X]).parent)Q.parent.remove(Q);Z4.prototype.onRemove.call(this,Y)};Object.defineProperty(X1.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}});X1.d=function(){var Y=Array(arguments.length),X=0;while(X<arguments.length)Y[X]=arguments[X++];return function(J,Z){J4.decorateType(J.constructor).add(new X1(Z,Y)),Object.defineProperty(J,Z,{get:J4.oneOfGetter(Y),set:J4.oneOfSetter(Y)})}}});var L$=M((G_,UW)=>{UW.exports=v0;v0.className="ReflectionObject";var $I=a$(),p6=S0(),T4,YI={enum_type:"OPEN",field_presence:"EXPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"},XI={enum_type:"CLOSED",field_presence:"EXPLICIT",json_format:"LEGACY_BEST_EFFORT",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"EXPANDED",utf8_validation:"NONE"},QI={enum_type:"OPEN",field_presence:"IMPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"};function v0($,Y){if(!p6.isString($))throw TypeError("name must be a string");if(Y&&!p6.isObject(Y))throw TypeError("options must be an object");this.options=Y,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(v0.prototype,{root:{get:function(){var $=this;while($.parent!==null)$=$.parent;return $}},fullName:{get:function(){var $=[this.name],Y=this.parent;while(Y)$.unshift(Y.name),Y=Y.parent;return $.join(".")}}});v0.prototype.toJSON=function(){throw Error()};v0.prototype.onAdd=function(Y){if(this.parent&&this.parent!==Y)this.parent.remove(this);this.parent=Y,this.resolved=!1;var X=Y.root;if(X instanceof T4)X._handleAdd(this)};v0.prototype.onRemove=function(Y){var X=Y.root;if(X instanceof T4)X._handleRemove(this);this.parent=null,this.resolved=!1};v0.prototype.resolve=function(){if(this.resolved)return this;if(this.root instanceof T4)this.resolved=!0;return this};v0.prototype._resolveFeaturesRecursive=function(Y){return this._resolveFeatures(this._edition||Y)};v0.prototype._resolveFeatures=function(Y){if(this._featuresResolved)return;var X={};if(!Y)throw Error("Unknown edition for "+this.fullName);var Q=Object.assign(this.options?Object.assign({},this.options.features):{},this._inferLegacyProtoFeatures(Y));if(this._edition){if(Y==="proto2")X=Object.assign({},XI);else if(Y==="proto3")X=Object.assign({},QI);else if(Y==="2023")X=Object.assign({},YI);else throw Error("Unknown edition: "+Y);this._features=Object.assign(X,Q||{}),this._featuresResolved=!0;return}if(this.partOf instanceof $I){var J=Object.assign({},this.partOf._features);this._features=Object.assign(J,Q||{})}else if(this.declaringField);else if(this.parent){var Z=Object.assign({},this.parent._features);this._features=Object.assign(Z,Q||{})}else throw Error("Unable to find a parent for "+this.fullName);if(this.extensionField)this.extensionField._features=this._features;this._featuresResolved=!0};v0.prototype._inferLegacyProtoFeatures=function(){return{}};v0.prototype.getOption=function(Y){if(this.options)return this.options[Y];return};v0.prototype.setOption=function(Y,X,Q){if(!this.options)this.options={};if(/^features\./.test(Y))p6.setProperty(this.options,Y,X,Q);else if(!Q||this.options[Y]===void 0){if(this.getOption(Y)!==X)this.resolved=!1;this.options[Y]=X}return this};v0.prototype.setParsedOption=function(Y,X,Q){if(!this.parsedOptions)this.parsedOptions=[];var J=this.parsedOptions;if(Q){var Z=J.find(function(U){return Object.prototype.hasOwnProperty.call(U,Y)});if(Z){var T=Z[Y];p6.setProperty(T,Q,X)}else Z={},Z[Y]=p6.setProperty({},Q,X),J.push(Z)}else{var K={};K[Y]=X,J.push(K)}return this};v0.prototype.setOptions=function(Y,X){if(Y)for(var Q=Object.keys(Y),J=0;J<Q.length;++J)this.setOption(Q[J],Y[Q[J]],X);return this};v0.prototype.toString=function(){var Y=this.constructor.className,X=this.fullName;if(X.length)return Y+" "+X;return Y};v0.prototype._editionToJSON=function(){if(!this._edition||this._edition==="proto3")return;return this._edition};v0._configure=function($){T4=$}});var L1=M((W_,WW)=>{WW.exports=S1;var lQ=L$();((S1.prototype=Object.create(lQ.prototype)).constructor=S1).className="Enum";var GW=vY(),K4=S0();function S1($,Y,X,Q,J,Z){if(lQ.call(this,$,X),Y&&typeof Y!=="object")throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=Q,this.comments=J||{},this.valuesOptions=Z,this._valuesFeatures={},this.reserved=void 0,Y){for(var T=Object.keys(Y),K=0;K<T.length;++K)if(typeof Y[T[K]]==="number")this.valuesById[this.values[T[K]]=Y[T[K]]]=T[K]}}S1.prototype._resolveFeatures=function(Y){return Y=this._edition||Y,lQ.prototype._resolveFeatures.call(this,Y),Object.keys(this.values).forEach((X)=>{var Q=Object.assign({},this._features);this._valuesFeatures[X]=Object.assign(Q,this.valuesOptions&&this.valuesOptions[X]&&this.valuesOptions[X].features)}),this};S1.fromJSON=function(Y,X){var Q=new S1(Y,X.values,X.options,X.comment,X.comments);if(Q.reserved=X.reserved,X.edition)Q._edition=X.edition;return Q._defaultEdition="proto3",Q};S1.prototype.toJSON=function(Y){var X=Y?Boolean(Y.keepComments):!1;return K4.toObject(["edition",this._editionToJSON(),"options",this.options,"valuesOptions",this.valuesOptions,"values",this.values,"reserved",this.reserved&&this.reserved.length?this.reserved:void 0,"comment",X?this.comment:void 0,"comments",X?this.comments:void 0])};S1.prototype.add=function(Y,X,Q,J){if(!K4.isString(Y))throw TypeError("name must be a string");if(!K4.isInteger(X))throw TypeError("id must be an integer");if(this.values[Y]!==void 0)throw Error("duplicate name '"+Y+"' in "+this);if(this.isReservedId(X))throw Error("id "+X+" is reserved in "+this);if(this.isReservedName(Y))throw Error("name '"+Y+"' is reserved in "+this);if(this.valuesById[X]!==void 0){if(!(this.options&&this.options.allow_alias))throw Error("duplicate id "+X+" in "+this);this.values[Y]=X}else this.valuesById[this.values[Y]=X]=Y;if(J){if(this.valuesOptions===void 0)this.valuesOptions={};this.valuesOptions[Y]=J||null}return this.comments[Y]=Q||null,this};S1.prototype.remove=function(Y){if(!K4.isString(Y))throw TypeError("name must be a string");var X=this.values[Y];if(X==null)throw Error("name '"+Y+"' does not exist in "+this);if(delete this.valuesById[X],delete this.values[Y],delete this.comments[Y],this.valuesOptions)delete this.valuesOptions[Y];return this};S1.prototype.isReservedId=function(Y){return GW.isReservedId(this.reserved,Y)};S1.prototype.isReservedName=function(Y){return GW.isReservedName(this.reserved,Y)}});var mQ=M((R_,EW)=>{EW.exports=ZI;var JI=L1(),iQ=t$(),rQ=S0();function RW($,Y,X,Q){return Y.delimited?$("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",X,Q,(Y.id<<3|3)>>>0,(Y.id<<3|4)>>>0):$("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",X,Q,(Y.id<<3|2)>>>0)}function ZI($){var Y=rQ.codegen(["m","w"],$.name+"$encode")("if(!w)")("w=Writer.create()"),X,Q,J=$.fieldsArray.slice().sort(rQ.compareFieldsById);for(var X=0;X<J.length;++X){var Z=J[X].resolve(),T=$._fieldsArray.indexOf(Z),K=Z.resolvedType instanceof JI?"int32":Z.type,U=iQ.basic[K];if(Q="m"+rQ.safeProp(Z.name),Z.map){if(Y("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){",Q,Z.name)("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){",Q)("w.uint32(%i).fork().uint32(%i).%s(ks[i])",(Z.id<<3|2)>>>0,8|iQ.mapKey[Z.keyType],Z.keyType),U===void 0)Y("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",T,Q);else Y(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|U,K,Q);Y("}")("}")}else if(Z.repeated){if(Y("if(%s!=null&&%s.length){",Q,Q),Z.packed&&iQ.packed[K]!==void 0)Y("w.uint32(%i).fork()",(Z.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",Q)("w.%s(%s[i])",K,Q)("w.ldelim()");else if(Y("for(var i=0;i<%s.length;++i)",Q),U===void 0)RW(Y,Z,T,Q+"[i]");else Y("w.uint32(%i).%s(%s[i])",(Z.id<<3|U)>>>0,K,Q);Y("}")}else{if(Z.optional)Y("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",Q,Z.name);if(U===void 0)RW(Y,Z,T,Q);else Y("w.uint32(%i).%s(%s)",(Z.id<<3|U)>>>0,K,Q)}}return Y("return w")}});var AW=M((E_,VW)=>{var t=VW.exports=SG();t.build="light";function TI($,Y,X){if(typeof Y==="function")X=Y,Y=new t.Root;else if(!Y)Y=new t.Root;return Y.load($,X)}t.load=TI;function KI($,Y){if(!Y)Y=new t.Root;return Y.loadSync($)}t.loadSync=KI;t.encoder=mQ();t.decoder=wQ();t.verifier=jQ();t.converter=kQ();t.ReflectionObject=L$();t.Namespace=vY();t.Root=Q4();t.Enum=L1();t.Type=e9();t.Field=P$();t.OneOf=a$();t.MapField=i9();t.Service=o9();t.Method=r9();t.Message=s9();t.wrappers=hQ();t.types=t$();t.util=S0();t.ReflectionObject._configure(t.Root);t.Namespace._configure(t.Type,t.Service,t.Enum);t.Root._configure(t.Type);t.Field._configure(t.Type)});var sQ=M((V_,HW)=>{HW.exports=FW;var oQ=/[\s{}=;:[\],'"()<>]/g,UI=/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,GI=/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,WI=/^ *[*/]+ */,RI=/^\s*\*?\/*/,EI=/\n/g,VI=/\s/,AI=/\\(.?)/g,DI={"0":"\x00",r:"\r",n:`
|
|
9
|
+
`,t:"\t"};function DW($){return $.replace(AI,function(Y,X){switch(X){case"\\":case"":return X;default:return DI[X]||""}})}FW.unescape=DW;function FW($,Y){$=$.toString();var X=0,Q=$.length,J=1,Z=0,T={},K=[],U=null;function G(q){return Error("illegal "+q+" (line "+J+")")}function W(){var q=U==="'"?GI:UI;q.lastIndex=X-1;var _=q.exec($);if(!_)throw G("string");return X=q.lastIndex,D(U),U=null,DW(_[1])}function R(q){return $.charAt(q)}function V(q,_,C){var k={type:$.charAt(q++),lineEmpty:!1,leading:C},f;if(Y)f=2;else f=3;var y=q-f,j;do if(--y<0||(j=$.charAt(y))===`
|
|
10
|
+
`){k.lineEmpty=!0;break}while(j===" "||j==="\t");var N=$.substring(q,_).split(EI);for(var _0=0;_0<N.length;++_0)N[_0]=N[_0].replace(Y?RI:WI,"").trim();k.text=N.join(`
|
|
11
|
+
`).trim(),T[J]=k,Z=J}function A(q){var _=H(q),C=$.substring(q,_),k=/^\s*\/\//.test(C);return k}function H(q){var _=q;while(_<Q&&R(_)!==`
|
|
12
|
+
`)_++;return _}function z(){if(K.length>0)return K.shift();if(U)return W();var q,_,C,k,f,y=X===0;do{if(X===Q)return null;q=!1;while(VI.test(C=R(X))){if(C===`
|
|
13
|
+
`)y=!0,++J;if(++X===Q)return null}if(R(X)==="/"){if(++X===Q)throw G("comment");if(R(X)==="/")if(!Y){f=R(k=X+1)==="/";while(R(++X)!==`
|
|
14
|
+
`)if(X===Q)return null;if(++X,f)V(k,X-1,y),y=!0;++J,q=!0}else{if(k=X,f=!1,A(X-1)){f=!0;do{if(X=H(X),X===Q)break;if(X++,!y)break}while(A(X))}else X=Math.min(Q,H(X)+1);if(f)V(k,X,y),y=!0;J++,q=!0}else if((C=R(X))==="*"){k=X+1,f=Y||R(k)==="*";do{if(C===`
|
|
15
|
+
`)++J;if(++X===Q)throw G("comment");_=C,C=R(X)}while(_!=="*"||C!=="/");if(++X,f)V(k,X-2,y),y=!0;q=!0}else return"/"}}while(q);var j=X;oQ.lastIndex=0;var N=oQ.test(R(j++));if(!N)while(j<Q&&!oQ.test(R(j)))++j;var _0=$.substring(X,X=j);if(_0==='"'||_0==="'")U=_0;return _0}function D(q){K.push(q)}function B(){if(!K.length){var q=z();if(q===null)return null;D(q)}return K[0]}function w(q,_){var C=B(),k=C===q;if(k)return z(),!0;if(!_)throw G("token '"+C+"', '"+q+"' expected");return!1}function x(q){var _=null,C;if(q===void 0){if(C=T[J-1],delete T[J-1],C&&(Y||C.type==="*"||C.lineEmpty))_=C.leading?C.text:null}else{if(Z<q)B();if(C=T[q],delete T[q],C&&!C.lineEmpty&&(Y||C.type==="/"))_=C.leading?null:C.text}return _}return Object.defineProperty({next:z,peek:B,push:D,skip:w,cmnt:x},"line",{get:function(){return J}})}});var IW=M((A_,BW)=>{BW.exports=T$;T$.filename=null;T$.defaults={keepCase:!1};var FI=sQ(),zW=Q4(),qW=e9(),NW=P$(),HI=i9(),MW=a$(),zI=L1(),qI=o9(),NI=r9(),MI=L$(),BI=t$(),aQ=S0(),II=/^[1-9][0-9]*$/,OI=/^-?[1-9][0-9]*$/,PI=/^0[x][0-9a-fA-F]+$/,LI=/^-?0[x][0-9a-fA-F]+$/,SI=/^0[0-7]+$/,wI=/^-?0[0-7]+$/,CI=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,m1=/^[a-zA-Z_][a-zA-Z_0-9]*$/,b1=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/;function T$($,Y,X){if(!(Y instanceof zW))X=Y,Y=new zW;if(!X)X=T$.defaults;var Q=X.preferTrailingComment||!1,J=FI($,X.alternateCommentMode||!1),Z=J.next,T=J.push,K=J.peek,U=J.skip,G=J.cmnt,W=!0,R,V,A,H="proto2",z=Y,D=[],B={},w=X.keepCase?function(O){return O}:aQ.camelCase;function x(){D.forEach((O)=>{O._edition=H,Object.keys(B).forEach((I)=>{if(O.getOption(I)!==void 0)return;O.setOption(I,B[I],!0)})})}function q(O,I,S){var h=T$.filename;if(!S)T$.filename=null;return Error("illegal "+(I||"token")+" '"+O+"' ("+(h?h+", ":"")+"line "+J.line+")")}function _(){var O=[],I;do{if((I=Z())!=='"'&&I!=="'")throw q(I);O.push(Z()),U(I),I=K()}while(I==='"'||I==="'");return O.join("")}function C(O){var I=Z();switch(I){case"'":case'"':return T(I),_();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return f(I,!0)}catch(S){if(O&&b1.test(I))return I;throw q(I,"value")}}function k(O,I){var S,h;do if(I&&((S=K())==='"'||S==="'")){var v=_();if(O.push(v),H>=2023)throw q(v,"id")}else try{O.push([h=y(Z()),U("to",!0)?y(Z()):h])}catch(G0){if(I&&b1.test(S)&&H>=2023)O.push(S);else throw G0}while(U(",",!0));var m={options:void 0};m.setOption=function(G0,f0){if(this.options===void 0)this.options={};this.options[G0]=f0},L(m,function(f0){if(f0==="option")$0(m,f0),U(";");else throw q(f0)},function(){s1(m)})}function f(O,I){var S=1;if(O.charAt(0)==="-")S=-1,O=O.substring(1);switch(O){case"inf":case"INF":case"Inf":return S*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(II.test(O))return S*parseInt(O,10);if(PI.test(O))return S*parseInt(O,16);if(SI.test(O))return S*parseInt(O,8);if(CI.test(O))return S*parseFloat(O);throw q(O,"number",I)}function y(O,I){switch(O){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!I&&O.charAt(0)==="-")throw q(O,"id");if(OI.test(O))return parseInt(O,10);if(LI.test(O))return parseInt(O,16);if(wI.test(O))return parseInt(O,8);throw q(O,"id")}function j(){if(R!==void 0)throw q("package");if(R=Z(),!b1.test(R))throw q(R,"name");z=z.define(R),U(";")}function N(){var O=K(),I;switch(O){case"weak":I=A||(A=[]),Z();break;case"public":Z();default:I=V||(V=[]);break}O=_(),U(";"),I.push(O)}function _0(){if(U("="),H=_(),H<2023)throw q(H,"syntax");U(";")}function P(){if(U("="),H=_(),!["2023"].includes(H))throw q(H,"edition");U(";")}function E(O,I){switch(I){case"option":return $0(O,I),U(";"),!0;case"message":return n(O,I),!0;case"enum":return b0(O,I),!0;case"service":return qA(O,I),!0;case"extend":return MA(O,I),!0}return!1}function L(O,I,S){var h=J.line;if(O){if(typeof O.comment!=="string")O.comment=G();O.filename=T$.filename}if(U("{",!0)){var v;while((v=Z())!=="}")I(v);U(";",!0)}else{if(S)S();if(U(";"),O&&(typeof O.comment!=="string"||Q))O.comment=G(h)||O.comment}}function n(O,I){if(!m1.test(I=Z()))throw q(I,"type name");var S=new qW(I);if(L(S,function(v){if(E(S,v))return;switch(v){case"map":V0(S,v);break;case"required":if(H!=="proto2")throw q(v);case"repeated":u(S,v);break;case"optional":if(H==="proto3")u(S,"proto3_optional");else if(H!=="proto2")throw q(v);else u(S,"optional");break;case"oneof":g0(S,v);break;case"extensions":k(S.extensions||(S.extensions=[]));break;case"reserved":k(S.reserved||(S.reserved=[]),!0);break;default:if(H==="proto2"||!b1.test(v))throw q(v);T(v),u(S,"optional");break}}),O.add(S),O===z)D.push(S)}function u(O,I,S){var h=Z();if(h==="group"){d(O,I);return}while(h.endsWith(".")||K().startsWith("."))h+=Z();if(!b1.test(h))throw q(h,"type");var v=Z();if(!m1.test(v))throw q(v,"name");v=w(v),U("=");var m=new NW(v,y(Z()),h,I,S);if(L(m,function(p0){if(p0==="option")$0(m,p0),U(";");else throw q(p0)},function(){s1(m)}),I==="proto3_optional"){var G0=new MW("_"+v);m.setOption("proto3_optional",!0),G0.add(m),O.add(G0)}else O.add(m);if(O===z)D.push(m)}function d(O,I){if(H>=2023)throw q("group");var S=Z();if(!m1.test(S))throw q(S,"name");var h=aQ.lcFirst(S);if(S===h)S=aQ.ucFirst(S);U("=");var v=y(Z()),m=new qW(S);m.group=!0;var G0=new NW(h,v,S,I);G0.filename=T$.filename,L(m,function(p0){switch(p0){case"option":$0(m,p0),U(";");break;case"required":case"repeated":u(m,p0);break;case"optional":if(H==="proto3")u(m,"proto3_optional");else u(m,"optional");break;case"message":n(m,p0);break;case"enum":b0(m,p0);break;case"reserved":k(m.reserved||(m.reserved=[]),!0);break;default:throw q(p0)}}),O.add(m).add(G0)}function V0(O){U("<");var I=Z();if(BI.mapKey[I]===void 0)throw q(I,"type");U(",");var S=Z();if(!b1.test(S))throw q(S,"type");U(">");var h=Z();if(!m1.test(h))throw q(h,"name");U("=");var v=new HI(w(h),y(Z()),I,S);L(v,function(G0){if(G0==="option")$0(v,G0),U(";");else throw q(G0)},function(){s1(v)}),O.add(v)}function g0(O,I){if(!m1.test(I=Z()))throw q(I,"name");var S=new MW(w(I));L(S,function(v){if(v==="option")$0(S,v),U(";");else T(v),u(S,"optional")}),O.add(S)}function b0(O,I){if(!m1.test(I=Z()))throw q(I,"name");var S=new zI(I);if(L(S,function(v){switch(v){case"option":$0(S,v),U(";");break;case"reserved":if(k(S.reserved||(S.reserved=[]),!0),S.reserved===void 0)S.reserved=[];break;default:B0(S,v)}}),O.add(S),O===z)D.push(S)}function B0(O,I){if(!m1.test(I))throw q(I,"name");U("=");var S=y(Z(),!0),h={options:void 0};h.getOption=function(v){return this.options[v]},h.setOption=function(v,m){MI.prototype.setOption.call(h,v,m)},h.setParsedOption=function(){return},L(h,function(m){if(m==="option")$0(h,m),U(";");else throw q(m)},function(){s1(h)}),O.add(I,S,h.comment,h.parsedOptions||h.options)}function $0(O,I){var S,h,v=!0;if(I==="option")I=Z();while(I!=="="){if(I==="("){var m=Z();U(")"),I="("+m+")"}if(v){if(v=!1,I.includes(".")&&!I.includes("(")){var G0=I.split(".");S=G0[0]+".",I=G0[1];continue}S=I}else h=h?h+=I:I;I=Z()}var f0=h?S.concat(h):S,p0=u0(O,f0);h=h&&h[0]==="."?h.slice(1):h,S=S&&S[S.length-1]==="."?S.slice(0,-1):S,d0(O,S,p0,h)}function u0(O,I){if(U("{",!0)){var S={};while(!U("}",!0)){if(!m1.test(j0=Z()))throw q(j0,"name");if(j0===null)throw q(j0,"end of input");var h,v=j0;if(U(":",!0),K()==="{")h=u0(O,I+"."+j0);else if(K()==="["){h=[];var m;if(U("[",!0)){do m=C(!0),h.push(m);while(U(",",!0));if(U("]"),typeof m<"u")R0(O,I+"."+j0,m)}}else h=C(!0),R0(O,I+"."+j0,h);var G0=S[v];if(G0)h=[].concat(G0).concat(h);S[v]=h,U(",",!0),U(";",!0)}return S}var f0=C(!0);return R0(O,I,f0),f0}function R0(O,I,S){if(z===O&&/^features\./.test(I)){B[I]=S;return}if(O.setOption)O.setOption(I,S)}function d0(O,I,S,h){if(O.setParsedOption)O.setParsedOption(I,S,h)}function s1(O){if(U("[",!0)){do $0(O,"option");while(U(",",!0));U("]")}return O}function qA(O,I){if(!m1.test(I=Z()))throw q(I,"service name");var S=new qI(I);if(L(S,function(v){if(E(S,v))return;if(v==="rpc")NA(S,v);else throw q(v)}),O.add(S),O===z)D.push(S)}function NA(O,I){var S=G(),h=I;if(!m1.test(I=Z()))throw q(I,"name");var v=I,m,G0,f0,p0;if(U("("),U("stream",!0))G0=!0;if(!b1.test(I=Z()))throw q(I);if(m=I,U(")"),U("returns"),U("("),U("stream",!0))p0=!0;if(!b1.test(I=Z()))throw q(I);f0=I,U(")");var B8=new NI(v,h,m,f0,G0,p0);B8.comment=S,L(B8,function(ZX){if(ZX==="option")$0(B8,ZX),U(";");else throw q(ZX)}),O.add(B8)}function MA(O,I){if(!b1.test(I=Z()))throw q(I,"reference");var S=I;L(null,function(v){switch(v){case"required":case"repeated":u(O,v,S);break;case"optional":if(H==="proto3")u(O,"proto3_optional",S);else u(O,"optional",S);break;default:if(H==="proto2"||!b1.test(v))throw q(v);T(v),u(O,"optional",S);break}})}var j0;while((j0=Z())!==null)switch(j0){case"package":if(!W)throw q(j0);j();break;case"import":if(!W)throw q(j0);N();break;case"syntax":if(!W)throw q(j0);_0();break;case"edition":if(!W)throw q(j0);P();break;case"option":$0(z,j0),U(";",!0);break;default:if(E(z,j0)){W=!1;continue}throw q(j0)}return x(),T$.filename=null,{package:R,imports:V,weakImports:A,root:Y}}});var LW=M((D_,PW)=>{PW.exports=w1;var yI=/\/|\./;function w1($,Y){if(!yI.test($))$="google/protobuf/"+$+".proto",Y={nested:{google:{nested:{protobuf:{nested:Y}}}}};w1[$]=Y}w1("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}});var OW;w1("duration",{Duration:OW={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}});w1("timestamp",{Timestamp:OW});w1("empty",{Empty:{fields:{}}});w1("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}}}});w1("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}}}});w1("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}});w1.get=function(Y){return w1[Y]||null}});var U4=M((F_,SW)=>{var w$=SW.exports=AW();w$.build="full";w$.tokenize=sQ();w$.parse=IW();w$.common=LW();w$.Root._configure(w$.Type,w$.parse,w$.common)});var tQ=M((H_,jI)=>{jI.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 kW=M((p,vW)=>{var Q1=U4();vW.exports=p=Q1.descriptor=Q1.Root.fromJSON(tQ()).lookup(".google.protobuf");var{Namespace:wW,Root:c6,Enum:K$,Type:u1,Field:C$,MapField:xI,OneOf:G4,Service:n6,Method:W4}=Q1;c6.fromDescriptor=function(Y){if(typeof Y.length==="number")Y=p.FileDescriptorSet.decode(Y);var X=new c6;if(Y.file){var Q,J;for(var Z=0,T;Z<Y.file.length;++Z){if(J=X,(Q=Y.file[Z]).package&&Q.package.length)J=X.define(Q.package);var K=dI(Q);if(Q.name&&Q.name.length)X.files.push(J.filename=Q.name);if(Q.messageType)for(T=0;T<Q.messageType.length;++T)J.add(u1.fromDescriptor(Q.messageType[T],K));if(Q.enumType)for(T=0;T<Q.enumType.length;++T)J.add(K$.fromDescriptor(Q.enumType[T],K));if(Q.extension)for(T=0;T<Q.extension.length;++T)J.add(C$.fromDescriptor(Q.extension[T],K));if(Q.service)for(T=0;T<Q.service.length;++T)J.add(n6.fromDescriptor(Q.service[T],K));var U=hY(Q.options,p.FileOptions);if(U){var G=Object.keys(U);for(T=0;T<G.length;++T)J.setOption(G[T],U[G[T]])}}}return X.resolveAll()};c6.prototype.toDescriptor=function(Y){var X=p.FileDescriptorSet.create();return CW(this,X.file,Y),X};function CW($,Y,X){var Q=p.FileDescriptorProto.create({name:$.filename||($.fullName.substring(1).replace(/\./g,"_")||"root")+".proto"});if(pI(X,Q),!($ instanceof c6))Q.package=$.fullName.substring(1);for(var J=0,Z;J<$.nestedArray.length;++J)if((Z=$._nestedArray[J])instanceof u1)Q.messageType.push(Z.toDescriptor(X));else if(Z instanceof K$)Q.enumType.push(Z.toDescriptor());else if(Z instanceof C$)Q.extension.push(Z.toDescriptor(X));else if(Z instanceof n6)Q.service.push(Z.toDescriptor());else if(Z instanceof wW)CW(Z,Y,X);if(Q.options=_Y($.options,p.FileOptions),Q.messageType.length+Q.enumType.length+Q.extension.length+Q.service.length)Y.push(Q)}var vI=0;u1.fromDescriptor=function(Y,X,Q){if(typeof Y.length==="number")Y=p.DescriptorProto.decode(Y);var J=new u1(Y.name.length?Y.name:"Type"+vI++,hY(Y.options,p.MessageOptions)),Z;if(!Q)J._edition=X;if(Y.oneofDecl)for(Z=0;Z<Y.oneofDecl.length;++Z)J.add(G4.fromDescriptor(Y.oneofDecl[Z]));if(Y.field)for(Z=0;Z<Y.field.length;++Z){var T=C$.fromDescriptor(Y.field[Z],X,!0);if(J.add(T),Y.field[Z].hasOwnProperty("oneofIndex"))J.oneofsArray[Y.field[Z].oneofIndex].add(T)}if(Y.extension)for(Z=0;Z<Y.extension.length;++Z)J.add(C$.fromDescriptor(Y.extension[Z],X,!0));if(Y.nestedType){for(Z=0;Z<Y.nestedType.length;++Z)if(J.add(u1.fromDescriptor(Y.nestedType[Z],X,!0)),Y.nestedType[Z].options&&Y.nestedType[Z].options.mapEntry)J.setOption("map_entry",!0)}if(Y.enumType)for(Z=0;Z<Y.enumType.length;++Z)J.add(K$.fromDescriptor(Y.enumType[Z],X,!0));if(Y.extensionRange&&Y.extensionRange.length){J.extensions=[];for(Z=0;Z<Y.extensionRange.length;++Z)J.extensions.push([Y.extensionRange[Z].start,Y.extensionRange[Z].end])}if(Y.reservedRange&&Y.reservedRange.length||Y.reservedName&&Y.reservedName.length){if(J.reserved=[],Y.reservedRange)for(Z=0;Z<Y.reservedRange.length;++Z)J.reserved.push([Y.reservedRange[Z].start,Y.reservedRange[Z].end]);if(Y.reservedName)for(Z=0;Z<Y.reservedName.length;++Z)J.reserved.push(Y.reservedName[Z])}return J};u1.prototype.toDescriptor=function(Y){var X=p.DescriptorProto.create({name:this.name}),Q;for(Q=0;Q<this.fieldsArray.length;++Q){var J;if(X.field.push(J=this._fieldsArray[Q].toDescriptor(Y)),this._fieldsArray[Q]instanceof xI){var Z=eQ(this._fieldsArray[Q].keyType,this._fieldsArray[Q].resolvedKeyType,!1),T=eQ(this._fieldsArray[Q].type,this._fieldsArray[Q].resolvedType,!1),K=T===11||T===14?this._fieldsArray[Q].resolvedType&&xW(this.parent,this._fieldsArray[Q].resolvedType)||this._fieldsArray[Q].type:void 0;X.nestedType.push(p.DescriptorProto.create({name:J.typeName,field:[p.FieldDescriptorProto.create({name:"key",number:1,label:1,type:Z}),p.FieldDescriptorProto.create({name:"value",number:2,label:1,type:T,typeName:K})],options:p.MessageOptions.create({mapEntry:!0})}))}}for(Q=0;Q<this.oneofsArray.length;++Q)X.oneofDecl.push(this._oneofsArray[Q].toDescriptor());for(Q=0;Q<this.nestedArray.length;++Q)if(this._nestedArray[Q]instanceof C$)X.field.push(this._nestedArray[Q].toDescriptor(Y));else if(this._nestedArray[Q]instanceof u1)X.nestedType.push(this._nestedArray[Q].toDescriptor(Y));else if(this._nestedArray[Q]instanceof K$)X.enumType.push(this._nestedArray[Q].toDescriptor());if(this.extensions)for(Q=0;Q<this.extensions.length;++Q)X.extensionRange.push(p.DescriptorProto.ExtensionRange.create({start:this.extensions[Q][0],end:this.extensions[Q][1]}));if(this.reserved)for(Q=0;Q<this.reserved.length;++Q)if(typeof this.reserved[Q]==="string")X.reservedName.push(this.reserved[Q]);else X.reservedRange.push(p.DescriptorProto.ReservedRange.create({start:this.reserved[Q][0],end:this.reserved[Q][1]}));return X.options=_Y(this.options,p.MessageOptions),X};var kI=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/;C$.fromDescriptor=function(Y,X,Q){if(typeof Y.length==="number")Y=p.DescriptorProto.decode(Y);if(typeof Y.number!=="number")throw Error("missing field id");var J;if(Y.typeName&&Y.typeName.length)J=Y.typeName;else J=mI(Y.type);var Z;switch(Y.label){case 1:Z=void 0;break;case 2:Z="required";break;case 3:Z="repeated";break;default:throw Error("illegal label: "+Y.label)}var T=Y.extendee;if(Y.extendee!==void 0)T=T.length?T:void 0;var K=new C$(Y.name.length?Y.name:"field"+Y.number,Y.number,J,Z,T);if(!Q)K._edition=X;if(K.options=hY(Y.options,p.FieldOptions),Y.proto3_optional)K.options.proto3_optional=!0;if(Y.defaultValue&&Y.defaultValue.length){var U=Y.defaultValue;switch(U){case"true":case"TRUE":U=!0;break;case"false":case"FALSE":U=!1;break;default:var G=kI.exec(U);if(G)U=parseInt(U);break}K.setOption("default",U)}if(bI(Y.type)){if(X==="proto3"){if(Y.options&&!Y.options.packed)K.setOption("packed",!1)}else if((!X||X==="proto2")&&Y.options&&Y.options.packed)K.setOption("packed",!0)}return K};C$.prototype.toDescriptor=function(Y){var X=p.FieldDescriptorProto.create({name:this.name,number:this.id});if(this.map)X.type=11,X.typeName=Q1.util.ucFirst(this.name),X.label=3;else{switch(X.type=eQ(this.type,this.resolve().resolvedType,this.delimited)){case 10:case 11:case 14:X.typeName=this.resolvedType?xW(this.parent,this.resolvedType):this.type;break}if(this.rule==="repeated")X.label=3;else if(this.required&&Y==="proto2")X.label=2;else X.label=1}if(X.extendee=this.extensionField?this.extensionField.parent.fullName:this.extend,this.partOf){if((X.oneofIndex=this.parent.oneofsArray.indexOf(this.partOf))<0)throw Error("missing oneof")}if(this.options){if(X.options=_Y(this.options,p.FieldOptions),this.options.default!=null)X.defaultValue=String(this.options.default);if(this.options.proto3_optional)X.proto3_optional=!0}if(Y==="proto3"){if(!this.packed)(X.options||(X.options=p.FieldOptions.create())).packed=!1}else if((!Y||Y==="proto2")&&this.packed)(X.options||(X.options=p.FieldOptions.create())).packed=!0;return X};var hI=0;K$.fromDescriptor=function(Y,X,Q){if(typeof Y.length==="number")Y=p.EnumDescriptorProto.decode(Y);var J={};if(Y.value)for(var Z=0;Z<Y.value.length;++Z){var T=Y.value[Z].name,K=Y.value[Z].number||0;J[T&&T.length?T:"NAME"+K]=K}var U=new K$(Y.name&&Y.name.length?Y.name:"Enum"+hI++,J,hY(Y.options,p.EnumOptions));if(!Q)U._edition=X;return U};K$.prototype.toDescriptor=function(){var Y=[];for(var X=0,Q=Object.keys(this.values);X<Q.length;++X)Y.push(p.EnumValueDescriptorProto.create({name:Q[X],number:this.values[Q[X]]}));return p.EnumDescriptorProto.create({name:this.name,value:Y,options:_Y(this.options,p.EnumOptions)})};var _I=0;G4.fromDescriptor=function(Y){if(typeof Y.length==="number")Y=p.OneofDescriptorProto.decode(Y);return new G4(Y.name&&Y.name.length?Y.name:"oneof"+_I++)};G4.prototype.toDescriptor=function(){return p.OneofDescriptorProto.create({name:this.name})};var gI=0;n6.fromDescriptor=function(Y,X,Q){if(typeof Y.length==="number")Y=p.ServiceDescriptorProto.decode(Y);var J=new n6(Y.name&&Y.name.length?Y.name:"Service"+gI++,hY(Y.options,p.ServiceOptions));if(!Q)J._edition=X;if(Y.method)for(var Z=0;Z<Y.method.length;++Z)J.add(W4.fromDescriptor(Y.method[Z]));return J};n6.prototype.toDescriptor=function(){var Y=[];for(var X=0;X<this.methodsArray.length;++X)Y.push(this._methodsArray[X].toDescriptor());return p.ServiceDescriptorProto.create({name:this.name,method:Y,options:_Y(this.options,p.ServiceOptions)})};var fI=0;W4.fromDescriptor=function(Y){if(typeof Y.length==="number")Y=p.MethodDescriptorProto.decode(Y);return new W4(Y.name&&Y.name.length?Y.name:"Method"+fI++,"rpc",Y.inputType,Y.outputType,Boolean(Y.clientStreaming),Boolean(Y.serverStreaming),hY(Y.options,p.MethodOptions))};W4.prototype.toDescriptor=function(){return p.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:_Y(this.options,p.MethodOptions)})};function mI($){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 bI($){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 eQ($,Y,X){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(Y instanceof K$)return 14;if(Y instanceof u1)return X?10:11;throw Error("illegal type: "+$)}function yW($,Y){var X={};for(var Q=0,J,Z;Q<Y.fieldsArray.length;++Q){if((Z=(J=Y._fieldsArray[Q]).name)==="uninterpretedOption")continue;if(!Object.prototype.hasOwnProperty.call($,Z))continue;var T=uI(Z);if(J.resolvedType instanceof u1)X[T]=yW($[Z],J.resolvedType);else if(J.resolvedType instanceof K$)X[T]=J.resolvedType.valuesById[$[Z]];else X[T]=$[Z]}return X}function hY($,Y){if(!$)return;return yW(Y.toObject($),Y)}function jW($,Y){var X={},Q=Object.keys($);for(var J=0;J<Q.length;++J){var Z=Q[J],T=Q1.util.camelCase(Z);if(!Object.prototype.hasOwnProperty.call(Y.fields,T))continue;var K=Y.fields[T];if(K.resolvedType instanceof u1)X[T]=jW($[Z],K.resolvedType);else X[T]=$[Z];if(K.repeated&&!Array.isArray(X[T]))X[T]=[X[T]]}return X}function _Y($,Y){if(!$)return;return Y.fromObject(jW($,Y))}function xW($,Y){var X=$.fullName.split("."),Q=Y.fullName.split("."),J=0,Z=0,T=Q.length-1;if(!($ instanceof c6)&&Y instanceof wW)while(J<X.length&&Z<T&&X[J]===Q[Z]){var K=Y.lookup(X[J++],!0);if(K!==null&&K!==Y)break;++Z}else for(;J<X.length&&Z<T&&X[J]===Q[Z];++J,++Z);return Q.slice(Z).join(".")}function uI($){return $.substring(0,1)+$.substring(1).replace(/([A-Z])(?=[a-z]|$)/g,function(Y,X){return"_"+X.toLowerCase()})}function dI($){if($.syntax==="editions")switch($.edition){case p.Edition.EDITION_2023:return"2023";default:throw Error("Unsupported edition "+$.edition)}if($.syntax==="proto3")return"proto3";return"proto2"}function pI($,Y){if(!$)return;if($==="proto2"||$==="proto3")Y.syntax=$;else switch(Y.syntax="editions",$){case"2023":Y.edition=p.Edition.EDITION_2023;break;default:throw Error("Unsupported edition "+$)}}});var hW=M((z_,cI)=>{cI.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 _W=M((q_,nI)=>{nI.exports={nested:{google:{nested:{protobuf:{nested:{SourceContext:{fields:{fileName:{type:"string",id:1}}}}}}}}}});var gW=M((N_,lI)=>{lI.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 pW=M((uW)=>{Object.defineProperty(uW,"__esModule",{value:!0});uW.addCommonProtos=uW.loadProtosWithOptionsSync=uW.loadProtosWithOptions=void 0;var fW=s("fs"),mW=s("path"),gY=U4();function bW($,Y){let X=$.resolvePath;$.resolvePath=(Q,J)=>{if(mW.isAbsolute(J))return J;for(let Z of Y){let T=mW.join(Z,J);try{return fW.accessSync(T,fW.constants.R_OK),T}catch(K){continue}}return process.emitWarning(`${J} not found in any of the include paths ${Y}`),X(Q,J)}}async function iI($,Y){let X=new gY.Root;if(Y=Y||{},Y.includeDirs){if(!Array.isArray(Y.includeDirs))return Promise.reject(Error("The includeDirs option must be an array"));bW(X,Y.includeDirs)}let Q=await X.load($,Y);return Q.resolveAll(),Q}uW.loadProtosWithOptions=iI;function rI($,Y){let X=new gY.Root;if(Y=Y||{},Y.includeDirs){if(!Array.isArray(Y.includeDirs))throw Error("The includeDirs option must be an array");bW(X,Y.includeDirs)}let Q=X.loadSync($,Y);return Q.resolveAll(),Q}uW.loadProtosWithOptionsSync=rI;function oI(){let $=hW(),Y=tQ(),X=_W(),Q=gW();gY.common("api",$.nested.google.nested.protobuf.nested),gY.common("descriptor",Y.nested.google.nested.protobuf.nested),gY.common("source_context",X.nested.google.nested.protobuf.nested),gY.common("type",Q.nested.google.nested.protobuf.nested)}uW.addCommonProtos=oI});var cW=M((l6,$J)=>{(function($,Y){function X(Q){return Q.default||Q}if(typeof define==="function"&&define.amd)define([],function(){var Q={};return Y(Q),X(Q)});else if(typeof l6==="object"){if(Y(l6),typeof $J==="object")$J.exports=X(l6)}else(function(){var Q={};Y(Q),$.Long=X(Q)})()})(typeof globalThis<"u"?globalThis:typeof self<"u"?self:l6,function($){Object.defineProperty($,"__esModule",{value:!0}),$.default=void 0;var Y=null;try{Y=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 X(P,E,L){this.low=P|0,this.high=E|0,this.unsigned=!!L}X.prototype.__isLong__,Object.defineProperty(X.prototype,"__isLong__",{value:!0});function Q(P){return(P&&P.__isLong__)===!0}function J(P){var E=Math.clz32(P&-P);return P?31-E:E}X.isLong=Q;var Z={},T={};function K(P,E){var L,n,u;if(E){if(P>>>=0,u=0<=P&&P<256){if(n=T[P],n)return n}if(L=G(P,0,!0),u)T[P]=L;return L}else{if(P|=0,u=-128<=P&&P<128){if(n=Z[P],n)return n}if(L=G(P,P<0?-1:0,!1),u)Z[P]=L;return L}}X.fromInt=K;function U(P,E){if(isNaN(P))return E?q:x;if(E){if(P<0)return q;if(P>=D)return y}else{if(P<=-B)return j;if(P+1>=B)return f}if(P<0)return U(-P,E).neg();return G(P%z|0,P/z|0,E)}X.fromNumber=U;function G(P,E,L){return new X(P,E,L)}X.fromBits=G;var W=Math.pow;function R(P,E,L){if(P.length===0)throw Error("empty string");if(typeof E==="number")L=E,E=!1;else E=!!E;if(P==="NaN"||P==="Infinity"||P==="+Infinity"||P==="-Infinity")return E?q:x;if(L=L||10,L<2||36<L)throw RangeError("radix");var n;if((n=P.indexOf("-"))>0)throw Error("interior hyphen");else if(n===0)return R(P.substring(1),E,L).neg();var u=U(W(L,8)),d=x;for(var V0=0;V0<P.length;V0+=8){var g0=Math.min(8,P.length-V0),b0=parseInt(P.substring(V0,V0+g0),L);if(g0<8){var B0=U(W(L,g0));d=d.mul(B0).add(U(b0))}else d=d.mul(u),d=d.add(U(b0))}return d.unsigned=E,d}X.fromString=R;function V(P,E){if(typeof P==="number")return U(P,E);if(typeof P==="string")return R(P,E);return G(P.low,P.high,typeof E==="boolean"?E:P.unsigned)}X.fromValue=V;var A=65536,H=16777216,z=A*A,D=z*z,B=D/2,w=K(H),x=K(0);X.ZERO=x;var q=K(0,!0);X.UZERO=q;var _=K(1);X.ONE=_;var C=K(1,!0);X.UONE=C;var k=K(-1);X.NEG_ONE=k;var f=G(-1,2147483647,!1);X.MAX_VALUE=f;var y=G(-1,-1,!0);X.MAX_UNSIGNED_VALUE=y;var j=G(0,-2147483648,!1);X.MIN_VALUE=j;var N=X.prototype;if(N.toInt=function(){return this.unsigned?this.low>>>0:this.low},N.toNumber=function(){if(this.unsigned)return(this.high>>>0)*z+(this.low>>>0);return this.high*z+(this.low>>>0)},N.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=U(E),n=this.div(L),u=n.mul(L).sub(this);return n.toString(E)+u.toInt().toString(E)}else return"-"+this.neg().toString(E);var d=U(W(E,6),this.unsigned),V0=this,g0="";while(!0){var b0=V0.div(d),B0=V0.sub(b0.mul(d)).toInt()>>>0,$0=B0.toString(E);if(V0=b0,V0.isZero())return $0+g0;else{while($0.length<6)$0="0"+$0;g0=""+$0+g0}}},N.getHighBits=function(){return this.high},N.getHighBitsUnsigned=function(){return this.high>>>0},N.getLowBits=function(){return this.low},N.getLowBitsUnsigned=function(){return this.low>>>0},N.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},N.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)},N.isZero=function(){return this.high===0&&this.low===0},N.eqz=N.isZero,N.isNegative=function(){return!this.unsigned&&this.high<0},N.isPositive=function(){return this.unsigned||this.high>=0},N.isOdd=function(){return(this.low&1)===1},N.isEven=function(){return(this.low&1)===0},N.equals=function(E){if(!Q(E))E=V(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},N.eq=N.equals,N.notEquals=function(E){return!this.eq(E)},N.neq=N.notEquals,N.ne=N.notEquals,N.lessThan=function(E){return this.comp(E)<0},N.lt=N.lessThan,N.lessThanOrEqual=function(E){return this.comp(E)<=0},N.lte=N.lessThanOrEqual,N.le=N.lessThanOrEqual,N.greaterThan=function(E){return this.comp(E)>0},N.gt=N.greaterThan,N.greaterThanOrEqual=function(E){return this.comp(E)>=0},N.gte=N.greaterThanOrEqual,N.ge=N.greaterThanOrEqual,N.compare=function(E){if(!Q(E))E=V(E);if(this.eq(E))return 0;var L=this.isNegative(),n=E.isNegative();if(L&&!n)return-1;if(!L&&n)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},N.comp=N.compare,N.negate=function(){if(!this.unsigned&&this.eq(j))return j;return this.not().add(_)},N.neg=N.negate,N.add=function(E){if(!Q(E))E=V(E);var L=this.high>>>16,n=this.high&65535,u=this.low>>>16,d=this.low&65535,V0=E.high>>>16,g0=E.high&65535,b0=E.low>>>16,B0=E.low&65535,$0=0,u0=0,R0=0,d0=0;return d0+=d+B0,R0+=d0>>>16,d0&=65535,R0+=u+b0,u0+=R0>>>16,R0&=65535,u0+=n+g0,$0+=u0>>>16,u0&=65535,$0+=L+V0,$0&=65535,G(R0<<16|d0,$0<<16|u0,this.unsigned)},N.subtract=function(E){if(!Q(E))E=V(E);return this.add(E.neg())},N.sub=N.subtract,N.multiply=function(E){if(this.isZero())return this;if(!Q(E))E=V(E);if(Y){var L=Y.mul(this.low,this.high,E.low,E.high);return G(L,Y.get_high(),this.unsigned)}if(E.isZero())return this.unsigned?q:x;if(this.eq(j))return E.isOdd()?j:x;if(E.eq(j))return this.isOdd()?j:x;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(w)&&E.lt(w))return U(this.toNumber()*E.toNumber(),this.unsigned);var n=this.high>>>16,u=this.high&65535,d=this.low>>>16,V0=this.low&65535,g0=E.high>>>16,b0=E.high&65535,B0=E.low>>>16,$0=E.low&65535,u0=0,R0=0,d0=0,s1=0;return s1+=V0*$0,d0+=s1>>>16,s1&=65535,d0+=d*$0,R0+=d0>>>16,d0&=65535,d0+=V0*B0,R0+=d0>>>16,d0&=65535,R0+=u*$0,u0+=R0>>>16,R0&=65535,R0+=d*B0,u0+=R0>>>16,R0&=65535,R0+=V0*b0,u0+=R0>>>16,R0&=65535,u0+=n*$0+u*B0+d*b0+V0*g0,u0&=65535,G(d0<<16|s1,u0<<16|R0,this.unsigned)},N.mul=N.multiply,N.divide=function(E){if(!Q(E))E=V(E);if(E.isZero())throw Error("division by zero");if(Y){if(!this.unsigned&&this.high===-2147483648&&E.low===-1&&E.high===-1)return this;var L=(this.unsigned?Y.div_u:Y.div_s)(this.low,this.high,E.low,E.high);return G(L,Y.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?q:x;var n,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 V0=this.shr(1);if(n=V0.div(E).shl(1),n.eq(x))return E.isNegative()?_:k;else return u=this.sub(E.mul(n)),d=n.add(u.div(E)),d}else if(E.eq(j))return this.unsigned?q:x;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=x}else{if(!E.unsigned)E=E.toUnsigned();if(E.gt(this))return q;if(E.gt(this.shru(1)))return C;d=q}u=this;while(u.gte(E)){n=Math.max(1,Math.floor(u.toNumber()/E.toNumber()));var g0=Math.ceil(Math.log(n)/Math.LN2),b0=g0<=48?1:W(2,g0-48),B0=U(n),$0=B0.mul(E);while($0.isNegative()||$0.gt(u))n-=b0,B0=U(n,this.unsigned),$0=B0.mul(E);if(B0.isZero())B0=_;d=d.add(B0),u=u.sub($0)}return d},N.div=N.divide,N.modulo=function(E){if(!Q(E))E=V(E);if(Y){var L=(this.unsigned?Y.rem_u:Y.rem_s)(this.low,this.high,E.low,E.high);return G(L,Y.get_high(),this.unsigned)}return this.sub(this.div(E).mul(E))},N.mod=N.modulo,N.rem=N.modulo,N.not=function(){return G(~this.low,~this.high,this.unsigned)},N.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},N.clz=N.countLeadingZeros,N.countTrailingZeros=function(){return this.low?J(this.low):J(this.high)+32},N.ctz=N.countTrailingZeros,N.and=function(E){if(!Q(E))E=V(E);return G(this.low&E.low,this.high&E.high,this.unsigned)},N.or=function(E){if(!Q(E))E=V(E);return G(this.low|E.low,this.high|E.high,this.unsigned)},N.xor=function(E){if(!Q(E))E=V(E);return G(this.low^E.low,this.high^E.high,this.unsigned)},N.shiftLeft=function(E){if(Q(E))E=E.toInt();if((E&=63)===0)return this;else if(E<32)return G(this.low<<E,this.high<<E|this.low>>>32-E,this.unsigned);else return G(0,this.low<<E-32,this.unsigned)},N.shl=N.shiftLeft,N.shiftRight=function(E){if(Q(E))E=E.toInt();if((E&=63)===0)return this;else if(E<32)return G(this.low>>>E|this.high<<32-E,this.high>>E,this.unsigned);else return G(this.high>>E-32,this.high>=0?0:-1,this.unsigned)},N.shr=N.shiftRight,N.shiftRightUnsigned=function(E){if(Q(E))E=E.toInt();if((E&=63)===0)return this;if(E<32)return G(this.low>>>E|this.high<<32-E,this.high>>>E,this.unsigned);if(E===32)return G(this.high,0,this.unsigned);return G(this.high>>>E-32,0,this.unsigned)},N.shru=N.shiftRightUnsigned,N.shr_u=N.shiftRightUnsigned,N.rotateLeft=function(E){var L;if(Q(E))E=E.toInt();if((E&=63)===0)return this;if(E===32)return G(this.high,this.low,this.unsigned);if(E<32)return L=32-E,G(this.low<<E|this.high>>>L,this.high<<E|this.low>>>L,this.unsigned);return E-=32,L=32-E,G(this.high<<E|this.low>>>L,this.low<<E|this.high>>>L,this.unsigned)},N.rotl=N.rotateLeft,N.rotateRight=function(E){var L;if(Q(E))E=E.toInt();if((E&=63)===0)return this;if(E===32)return G(this.high,this.low,this.unsigned);if(E<32)return L=32-E,G(this.high<<L|this.low>>>E,this.low<<L|this.high>>>E,this.unsigned);return E-=32,L=32-E,G(this.low<<L|this.high>>>E,this.high<<L|this.low>>>E,this.unsigned)},N.rotr=N.rotateRight,N.toSigned=function(){if(!this.unsigned)return this;return G(this.low,this.high,!1)},N.toUnsigned=function(){if(this.unsigned)return this;return G(this.low,this.high,!0)},N.toBytes=function(E){return E?this.toBytesLE():this.toBytesBE()},N.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]},N.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]},X.fromBytes=function(E,L,n){return n?X.fromBytesLE(E,L):X.fromBytesBE(E,L)},X.fromBytesLE=function(E,L){return new X(E[0]|E[1]<<8|E[2]<<16|E[3]<<24,E[4]|E[5]<<8|E[6]<<16|E[7]<<24,L)},X.fromBytesBE=function(E,L){return new X(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")X.fromBigInt=function(E,L){var n=Number(BigInt.asIntN(32,E)),u=Number(BigInt.asIntN(32,E>>BigInt(32)));return G(n,u,L)},X.fromValue=function(E,L){if(typeof E==="bigint")return X.fromBigInt(E,L);return V(E,L)},N.toBigInt=function(){var E=BigInt(this.low>>>0),L=BigInt(this.unsigned?this.high>>>0:this.high);return L<<BigInt(32)|E};var _0=$.default=X})});var i6=M((sW)=>{Object.defineProperty(sW,"__esModule",{value:!0});sW.loadFileDescriptorSetFromObject=sW.loadFileDescriptorSetFromBuffer=sW.fromJSON=sW.loadSync=sW.load=sW.IdempotencyLevel=sW.isAnyExtension=sW.Long=void 0;var tI=hU(),d1=U4(),JJ=kW(),ZJ=pW(),eI=cW();sW.Long=eI;function $2($){return"@type"in $&&typeof $["@type"]==="string"}sW.isAnyExtension=$2;var lW;(function($){$.IDEMPOTENCY_UNKNOWN="IDEMPOTENCY_UNKNOWN",$.NO_SIDE_EFFECTS="NO_SIDE_EFFECTS",$.IDEMPOTENT="IDEMPOTENT"})(lW=sW.IdempotencyLevel||(sW.IdempotencyLevel={}));var iW={longs:String,enums:String,bytes:String,defaults:!0,oneofs:!0,json:!0};function Y2($,Y){if($==="")return Y;else return $+"."+Y}function X2($){return $ instanceof d1.Service||$ instanceof d1.Type||$ instanceof d1.Enum}function Q2($){return $ instanceof d1.Namespace||$ instanceof d1.Root}function rW($,Y){let X=Y2(Y,$.name);if(X2($))return[[X,$]];else if(Q2($)&&typeof $.nested<"u")return Object.keys($.nested).map((Q)=>{return rW($.nested[Q],X)}).reduce((Q,J)=>Q.concat(J),[]);return[]}function YJ($,Y){return function(Q){return $.toObject($.decode(Q),Y)}}function XJ($){return function(X){if(Array.isArray(X))throw Error(`Failed to serialize message: expected object with ${$.name} structure, got array instead`);let Q=$.fromObject(X);return $.encode(Q).finish()}}function J2($){return($||[]).reduce((Y,X)=>{for(let[Q,J]of Object.entries(X))switch(Q){case"uninterpreted_option":Y.uninterpreted_option.push(X.uninterpreted_option);break;default:Y[Q]=J}return Y},{deprecated:!1,idempotency_level:lW.IDEMPOTENCY_UNKNOWN,uninterpreted_option:[]})}function Z2($,Y,X,Q){let{resolvedRequestType:J,resolvedResponseType:Z}=$;return{path:"/"+Y+"/"+$.name,requestStream:!!$.requestStream,responseStream:!!$.responseStream,requestSerialize:XJ(J),requestDeserialize:YJ(J,X),responseSerialize:XJ(Z),responseDeserialize:YJ(Z,X),originalName:tI($.name),requestType:QJ(J,X,Q),responseType:QJ(Z,X,Q),options:J2($.parsedOptions)}}function T2($,Y,X,Q){let J={};for(let Z of $.methodsArray)J[Z.name]=Z2(Z,Y,X,Q);return J}function QJ($,Y,X){let Q=$.toDescriptor("proto3");return{format:"Protocol Buffer 3 DescriptorProto",type:Q.$type.toObject(Q,iW),fileDescriptorProtos:X,serialize:XJ($),deserialize:YJ($,Y)}}function K2($,Y){let X=$.toDescriptor("proto3");return{format:"Protocol Buffer 3 EnumDescriptorProto",type:X.$type.toObject(X,iW),fileDescriptorProtos:Y}}function U2($,Y,X,Q){if($ instanceof d1.Service)return T2($,Y,X,Q);else if($ instanceof d1.Type)return QJ($,X,Q);else if($ instanceof d1.Enum)return K2($,Q);else throw Error("Type mismatch in reflection object handling")}function R4($,Y){let X={};$.resolveAll();let J=$.toDescriptor("proto3").file.map((Z)=>Buffer.from(JJ.FileDescriptorProto.encode(Z).finish()));for(let[Z,T]of rW($,""))X[Z]=U2(T,Z,Y,J);return X}function oW($,Y){Y=Y||{};let X=d1.Root.fromDescriptor($);return X.resolveAll(),R4(X,Y)}function G2($,Y){return(0,ZJ.loadProtosWithOptions)($,Y).then((X)=>{return R4(X,Y)})}sW.load=G2;function W2($,Y){let X=(0,ZJ.loadProtosWithOptionsSync)($,Y);return R4(X,Y)}sW.loadSync=W2;function R2($,Y){Y=Y||{};let X=d1.Root.fromJSON($);return X.resolveAll(),R4(X,Y)}sW.fromJSON=R2;function E2($,Y){let X=JJ.FileDescriptorSet.decode($);return oW(X,Y)}sW.loadFileDescriptorSetFromBuffer=E2;function V2($,Y){let X=JJ.FileDescriptorSet.fromObject($);return oW(X,Y)}sW.loadFileDescriptorSetFromObject=V2;(0,ZJ.addCommonProtos)()});var y$=M((RR)=>{var __dirname="/Users/beatrix/dev/clinee/sdk-wip/node_modules/.bun/@grpc+grpc-js@1.14.3/node_modules/@grpc/grpc-js/build/src";Object.defineProperty(RR,"__esModule",{value:!0});RR.registerChannelzSocket=RR.registerChannelzServer=RR.registerChannelzSubchannel=RR.registerChannelzChannel=RR.ChannelzCallTrackerStub=RR.ChannelzCallTracker=RR.ChannelzChildrenTrackerStub=RR.ChannelzChildrenTracker=RR.ChannelzTrace=RR.ChannelzTraceStub=void 0;RR.unregisterChannelzRef=O2;RR.getChannelzHandlers=GR;RR.getChannelzServiceDefinition=WR;RR.setup=h2;var V4=s("net"),$Y=gK(),r6=n0(),o6=i(),N2=r0(),M2=v9(),B2=h9();function TJ($){return{channel_id:$.id,name:$.name}}function KJ($){return{subchannel_id:$.id,name:$.name}}function I2($){return{server_id:$.id}}function A4($){return{socket_id:$.id,name:$.name}}var tW=32,UJ=100;class XR{constructor(){this.events=[],this.creationTimestamp=new Date,this.eventsLogged=0}addTrace(){}getTraceMessage(){return{creation_timestamp:p1(this.creationTimestamp),num_events_logged:this.eventsLogged,events:[]}}}RR.ChannelzTraceStub=XR;class QR{constructor(){this.events=[],this.eventsLogged=0,this.creationTimestamp=new Date}addTrace($,Y,X){let Q=new Date;if(this.events.push({description:Y,severity:$,timestamp:Q,childChannel:(X===null||X===void 0?void 0:X.kind)==="channel"?X:void 0,childSubchannel:(X===null||X===void 0?void 0:X.kind)==="subchannel"?X:void 0}),this.events.length>=tW*2)this.events=this.events.slice(tW);this.eventsLogged+=1}getTraceMessage(){return{creation_timestamp:p1(this.creationTimestamp),num_events_logged:this.eventsLogged,events:this.events.map(($)=>{return{description:$.description,severity:$.severity,timestamp:p1($.timestamp),channel_ref:$.childChannel?TJ($.childChannel):null,subchannel_ref:$.childSubchannel?KJ($.childSubchannel):null}})}}}RR.ChannelzTrace=QR;class GJ{constructor(){this.channelChildren=new $Y.OrderedMap,this.subchannelChildren=new $Y.OrderedMap,this.socketChildren=new $Y.OrderedMap,this.trackerMap={["channel"]:this.channelChildren,["subchannel"]:this.subchannelChildren,["socket"]:this.socketChildren}}refChild($){let Y=this.trackerMap[$.kind],X=Y.find($.id);if(X.equals(Y.end()))Y.setElement($.id,{ref:$,count:1},X);else X.pointer[1].count+=1}unrefChild($){let Y=this.trackerMap[$.kind],X=Y.getElementByKey($.id);if(X!==void 0){if(X.count-=1,X.count===0)Y.eraseElementByKey($.id)}}getChildLists(){return{channels:this.channelChildren,subchannels:this.subchannelChildren,sockets:this.socketChildren}}}RR.ChannelzChildrenTracker=GJ;class JR extends GJ{refChild(){}unrefChild(){}}RR.ChannelzChildrenTrackerStub=JR;class WJ{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}}RR.ChannelzCallTracker=WJ;class ZR extends WJ{addCallStarted(){}addCallSucceeded(){}addCallFailed(){}}RR.ChannelzCallTrackerStub=ZR;var U$={["channel"]:new $Y.OrderedMap,["subchannel"]:new $Y.OrderedMap,["server"]:new $Y.OrderedMap,["socket"]:new $Y.OrderedMap},D4=($)=>{let Y=1;function X(){return Y++}let Q=U$[$];return(J,Z,T)=>{let K=X(),U={id:K,name:J,kind:$};if(T)Q.setElement(K,{ref:U,getInfo:Z});return U}};RR.registerChannelzChannel=D4("channel");RR.registerChannelzSubchannel=D4("subchannel");RR.registerChannelzServer=D4("server");RR.registerChannelzSocket=D4("socket");function O2($){U$[$.kind].eraseElementByKey($.id)}function P2($){let Y=Number.parseInt($,16);return[Y/256|0,Y%256]}function eW($){if($==="")return[];let Y=$.split(":").map((Q)=>P2(Q));return[].concat(...Y)}function L2($){return(0,V4.isIPv6)($)&&$.toLowerCase().startsWith("::ffff:")&&(0,V4.isIPv4)($.substring(7))}function $R($){return Buffer.from(Uint8Array.from($.split(".").map((Y)=>Number.parseInt(Y))))}function S2($){if((0,V4.isIPv4)($))return $R($);else if(L2($))return $R($.substring(7));else if((0,V4.isIPv6)($)){let Y,X,Q=$.indexOf("::");if(Q===-1)Y=$,X="";else Y=$.substring(0,Q),X=$.substring(Q+2);let J=Buffer.from(eW(Y)),Z=Buffer.from(eW(X)),T=Buffer.alloc(16-J.length-Z.length,0);return Buffer.concat([J,T,Z])}else return null}function TR($){switch($){case r6.ConnectivityState.CONNECTING:return{state:"CONNECTING"};case r6.ConnectivityState.IDLE:return{state:"IDLE"};case r6.ConnectivityState.READY:return{state:"READY"};case r6.ConnectivityState.SHUTDOWN:return{state:"SHUTDOWN"};case r6.ConnectivityState.TRANSIENT_FAILURE:return{state:"TRANSIENT_FAILURE"};default:return{state:"UNKNOWN"}}}function p1($){if(!$)return null;let Y=$.getTime();return{seconds:Y/1000|0,nanos:Y%1000*1e6}}function KR($){let Y=$.getInfo(),X=[],Q=[];return Y.children.channels.forEach((J)=>{X.push(TJ(J[1].ref))}),Y.children.subchannels.forEach((J)=>{Q.push(KJ(J[1].ref))}),{ref:TJ($.ref),data:{target:Y.target,state:TR(Y.state),calls_started:Y.callTracker.callsStarted,calls_succeeded:Y.callTracker.callsSucceeded,calls_failed:Y.callTracker.callsFailed,last_call_started_timestamp:p1(Y.callTracker.lastCallStartedTimestamp),trace:Y.trace.getTraceMessage()},channel_ref:X,subchannel_ref:Q}}function w2($,Y){let X=parseInt($.request.channel_id,10),Q=U$.channel.getElementByKey(X);if(Q===void 0){Y({code:o6.Status.NOT_FOUND,details:"No channel data found for id "+X});return}Y(null,{channel:KR(Q)})}function C2($,Y){let X=parseInt($.request.max_results,10)||UJ,Q=[],J=parseInt($.request.start_channel_id,10),Z=U$.channel,T;for(T=Z.lowerBound(J);!T.equals(Z.end())&&Q.length<X;T=T.next())Q.push(KR(T.pointer[1]));Y(null,{channel:Q,end:T.equals(Z.end())})}function UR($){let Y=$.getInfo(),X=[];return Y.listenerChildren.sockets.forEach((Q)=>{X.push(A4(Q[1].ref))}),{ref:I2($.ref),data:{calls_started:Y.callTracker.callsStarted,calls_succeeded:Y.callTracker.callsSucceeded,calls_failed:Y.callTracker.callsFailed,last_call_started_timestamp:p1(Y.callTracker.lastCallStartedTimestamp),trace:Y.trace.getTraceMessage()},listen_socket:X}}function y2($,Y){let X=parseInt($.request.server_id,10),J=U$.server.getElementByKey(X);if(J===void 0){Y({code:o6.Status.NOT_FOUND,details:"No server data found for id "+X});return}Y(null,{server:UR(J)})}function j2($,Y){let X=parseInt($.request.max_results,10)||UJ,Q=parseInt($.request.start_server_id,10),J=U$.server,Z=[],T;for(T=J.lowerBound(Q);!T.equals(J.end())&&Z.length<X;T=T.next())Z.push(UR(T.pointer[1]));Y(null,{server:Z,end:T.equals(J.end())})}function x2($,Y){let X=parseInt($.request.subchannel_id,10),Q=U$.subchannel.getElementByKey(X);if(Q===void 0){Y({code:o6.Status.NOT_FOUND,details:"No subchannel data found for id "+X});return}let J=Q.getInfo(),Z=[];J.children.sockets.forEach((K)=>{Z.push(A4(K[1].ref))});let T={ref:KJ(Q.ref),data:{target:J.target,state:TR(J.state),calls_started:J.callTracker.callsStarted,calls_succeeded:J.callTracker.callsSucceeded,calls_failed:J.callTracker.callsFailed,last_call_started_timestamp:p1(J.callTracker.lastCallStartedTimestamp),trace:J.trace.getTraceMessage()},socket_ref:Z};Y(null,{subchannel:T})}function YR($){var Y;if((0,N2.isTcpSubchannelAddress)($))return{address:"tcpip_address",tcpip_address:{ip_address:(Y=S2($.host))!==null&&Y!==void 0?Y:void 0,port:$.port}};else return{address:"uds_address",uds_address:{filename:$.path}}}function v2($,Y){var X,Q,J,Z,T;let K=parseInt($.request.socket_id,10),U=U$.socket.getElementByKey(K);if(U===void 0){Y({code:o6.Status.NOT_FOUND,details:"No socket data found for id "+K});return}let G=U.getInfo(),W=G.security?{model:"tls",tls:{cipher_suite:G.security.cipherSuiteStandardName?"standard_name":"other_name",standard_name:(X=G.security.cipherSuiteStandardName)!==null&&X!==void 0?X:void 0,other_name:(Q=G.security.cipherSuiteOtherName)!==null&&Q!==void 0?Q:void 0,local_certificate:(J=G.security.localCertificate)!==null&&J!==void 0?J:void 0,remote_certificate:(Z=G.security.remoteCertificate)!==null&&Z!==void 0?Z:void 0}}:null,R={ref:A4(U.ref),local:G.localAddress?YR(G.localAddress):null,remote:G.remoteAddress?YR(G.remoteAddress):null,remote_name:(T=G.remoteName)!==null&&T!==void 0?T:void 0,security:W,data:{keep_alives_sent:G.keepAlivesSent,streams_started:G.streamsStarted,streams_succeeded:G.streamsSucceeded,streams_failed:G.streamsFailed,last_local_stream_created_timestamp:p1(G.lastLocalStreamCreatedTimestamp),last_remote_stream_created_timestamp:p1(G.lastRemoteStreamCreatedTimestamp),messages_received:G.messagesReceived,messages_sent:G.messagesSent,last_message_received_timestamp:p1(G.lastMessageReceivedTimestamp),last_message_sent_timestamp:p1(G.lastMessageSentTimestamp),local_flow_control_window:G.localFlowControlWindow?{value:G.localFlowControlWindow}:null,remote_flow_control_window:G.remoteFlowControlWindow?{value:G.remoteFlowControlWindow}:null}};Y(null,{socket:R})}function k2($,Y){let X=parseInt($.request.server_id,10),Q=U$.server.getElementByKey(X);if(Q===void 0){Y({code:o6.Status.NOT_FOUND,details:"No server data found for id "+X});return}let J=parseInt($.request.start_socket_id,10),Z=parseInt($.request.max_results,10)||UJ,K=Q.getInfo().sessionChildren.sockets,U=[],G;for(G=K.lowerBound(J);!G.equals(K.end())&&U.length<Z;G=G.next())U.push(A4(G.pointer[1].ref));Y(null,{socket_ref:U,end:G.equals(K.end())})}function GR(){return{GetChannel:w2,GetTopChannels:C2,GetServer:y2,GetServers:j2,GetSubchannel:x2,GetSocket:v2,GetServerSockets:k2}}var E4=null;function WR(){if(E4)return E4;let $=i6().loadSync,Y=$("channelz.proto",{keepCase:!0,longs:String,enums:String,defaults:!0,oneofs:!0,includeDirs:[`${__dirname}/../../proto`]});return E4=(0,B2.loadPackageDefinition)(Y).grpc.channelz.v1.Channelz.service,E4}function h2(){(0,M2.registerAdminService)(WR,GR)}});var F4=M((VR)=>{Object.defineProperty(VR,"__esModule",{value:!0});VR.getNextCallNumber=s2;var o2=0;function s2(){return o2++}});var RJ=M((DR)=>{Object.defineProperty(DR,"__esModule",{value:!0});DR.CompressionAlgorithms=void 0;var AR;(function($){$[$.identity=0]="identity",$[$.deflate=1]="deflate",$[$.gzip=2]="gzip"})(AR||(DR.CompressionAlgorithms=AR={}))});var EJ=M((zR)=>{Object.defineProperty(zR,"__esModule",{value:!0});zR.BaseFilter=void 0;class HR{async sendMetadata($){return $}receiveMetadata($){return $}async sendMessage($){return $}async receiveMessage($){return $}receiveTrailers($){return $}}zR.BaseFilter=HR});var AJ=M((LR)=>{Object.defineProperty(LR,"__esModule",{value:!0});LR.CompressionFilterFactory=LR.CompressionFilter=void 0;var H4=s("zlib"),MR=RJ(),fY=i(),t2=EJ(),e2=Z0(),$O=($)=>{return typeof $==="number"&&typeof MR.CompressionAlgorithms[$]==="string"};class s6{async writeMessage($,Y){let X=$;if(Y)X=await this.compressMessage(X);let Q=Buffer.allocUnsafe(X.length+5);return Q.writeUInt8(Y?1:0,0),Q.writeUInt32BE(X.length,1),X.copy(Q,5),Q}async readMessage($){let Y=$.readUInt8(0)===1,X=$.slice(5);if(Y)X=await this.decompressMessage(X);return X}}class mY extends s6{async compressMessage($){return $}async writeMessage($,Y){let X=Buffer.allocUnsafe($.length+5);return X.writeUInt8(0,0),X.writeUInt32BE($.length,1),$.copy(X,5),X}decompressMessage($){return Promise.reject(Error('Received compressed message but "grpc-encoding" header was identity'))}}class BR extends s6{constructor($){super();this.maxRecvMessageLength=$}compressMessage($){return new Promise((Y,X)=>{H4.deflate($,(Q,J)=>{if(Q)X(Q);else Y(J)})})}decompressMessage($){return new Promise((Y,X)=>{let Q=0,J=[],Z=H4.createInflate();Z.on("data",(T)=>{if(J.push(T),Q+=T.byteLength,this.maxRecvMessageLength!==-1&&Q>this.maxRecvMessageLength)Z.destroy(),X({code:fY.Status.RESOURCE_EXHAUSTED,details:`Received message that decompresses to a size larger than ${this.maxRecvMessageLength}`})}),Z.on("end",()=>{Y(Buffer.concat(J))}),Z.write($),Z.end()})}}class IR extends s6{constructor($){super();this.maxRecvMessageLength=$}compressMessage($){return new Promise((Y,X)=>{H4.gzip($,(Q,J)=>{if(Q)X(Q);else Y(J)})})}decompressMessage($){return new Promise((Y,X)=>{let Q=0,J=[],Z=H4.createGunzip();Z.on("data",(T)=>{if(J.push(T),Q+=T.byteLength,this.maxRecvMessageLength!==-1&&Q>this.maxRecvMessageLength)Z.destroy(),X({code:fY.Status.RESOURCE_EXHAUSTED,details:`Received message that decompresses to a size larger than ${this.maxRecvMessageLength}`})}),Z.on("end",()=>{Y(Buffer.concat(J))}),Z.write($),Z.end()})}}class OR extends s6{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 NR($,Y){switch($){case"identity":return new mY;case"deflate":return new BR(Y);case"gzip":return new IR(Y);default:return new OR($)}}class VJ extends t2.BaseFilter{constructor($,Y){var X,Q,J;super();this.sharedFilterConfig=Y,this.sendCompression=new mY,this.receiveCompression=new mY,this.currentCompressionAlgorithm="identity";let Z=$["grpc.default_compression_algorithm"];if(this.maxReceiveMessageLength=(X=$["grpc.max_receive_message_length"])!==null&&X!==void 0?X:fY.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH,this.maxSendMessageLength=(Q=$["grpc.max_send_message_length"])!==null&&Q!==void 0?Q:fY.DEFAULT_MAX_SEND_MESSAGE_LENGTH,Z!==void 0)if($O(Z)){let T=MR.CompressionAlgorithms[Z],K=(J=Y.serverSupportedEncodingHeader)===null||J===void 0?void 0:J.split(",");if(!K||K.includes(T))this.currentCompressionAlgorithm=T,this.sendCompression=NR(this.currentCompressionAlgorithm,-1)}else e2.log(fY.LogVerbosity.ERROR,`Invalid value provided for grpc.default_compression_algorithm option: ${Z}`)}async sendMetadata($){let Y=await $;if(Y.set("grpc-accept-encoding","identity,deflate,gzip"),Y.set("accept-encoding","identity"),this.currentCompressionAlgorithm==="identity")Y.remove("grpc-encoding");else Y.set("grpc-encoding",this.currentCompressionAlgorithm);return Y}receiveMetadata($){let Y=$.get("grpc-encoding");if(Y.length>0){let Q=Y[0];if(typeof Q==="string")this.receiveCompression=NR(Q,this.maxReceiveMessageLength)}$.remove("grpc-encoding");let X=$.get("grpc-accept-encoding")[0];if(X){if(this.sharedFilterConfig.serverSupportedEncodingHeader=X,!X.split(",").includes(this.currentCompressionAlgorithm))this.sendCompression=new mY,this.currentCompressionAlgorithm="identity"}return $.remove("grpc-accept-encoding"),$}async sendMessage($){var Y;let X=await $;if(this.maxSendMessageLength!==-1&&X.message.length>this.maxSendMessageLength)throw{code:fY.Status.RESOURCE_EXHAUSTED,details:`Attempted to send message with a size larger than ${this.maxSendMessageLength}`};let Q;if(this.sendCompression instanceof mY)Q=!1;else Q=(((Y=X.flags)!==null&&Y!==void 0?Y:0)&2)===0;return{message:await this.sendCompression.writeMessage(X.message,Q),flags:X.flags}}async receiveMessage($){return this.receiveCompression.readMessage(await $)}}LR.CompressionFilter=VJ;class PR{constructor($,Y){this.options=Y,this.sharedFilterConfig={}}createFilter(){return new VJ(this.options,this.sharedFilterConfig)}}LR.CompressionFilterFactory=PR});var a6=M((wR)=>{Object.defineProperty(wR,"__esModule",{value:!0});wR.restrictControlPlaneStatusCode=QO;var c1=i(),XO=[c1.Status.OK,c1.Status.INVALID_ARGUMENT,c1.Status.NOT_FOUND,c1.Status.ALREADY_EXISTS,c1.Status.FAILED_PRECONDITION,c1.Status.ABORTED,c1.Status.OUT_OF_RANGE,c1.Status.DATA_LOSS];function QO($,Y){if(XO.includes($))return{code:c1.Status.INTERNAL,details:`Invalid status from control plane: ${$} ${c1.Status[$]} ${Y}`};else return{code:$,details:Y}}});var bY=M((CR)=>{Object.defineProperty(CR,"__esModule",{value:!0});CR.minDeadline=ZO;CR.getDeadlineTimeoutString=KO;CR.getRelativeTimeout=GO;CR.deadlineToString=WO;CR.formatDateDifference=RO;function ZO(...$){let Y=1/0;for(let X of $){let Q=X instanceof Date?X.getTime():X;if(Q<Y)Y=Q}return Y}var TO=[["m",1],["S",1000],["M",60000],["H",3600000]];function KO($){let Y=new Date().getTime();if($ instanceof Date)$=$.getTime();let X=Math.max($-Y,0);for(let[Q,J]of TO){let Z=X/J;if(Z<1e8)return String(Math.ceil(Z))+Q}throw Error("Deadline is too far in the future")}var UO=2147483647;function GO($){let Y=$ instanceof Date?$.getTime():$,X=new Date().getTime(),Q=Y-X;if(Q<0)return 0;else if(Q>UO)return 1/0;else return Q}function WO($){if($ instanceof Date)return $.toISOString();else{let Y=new Date($);if(Number.isNaN(Y.getTime()))return""+$;else return Y.toISOString()}}function RO($,Y){return((Y.getTime()-$.getTime())/1000).toFixed(3)+"s"}});var z4=M((yR)=>{Object.defineProperty(yR,"__esModule",{value:!0});yR.FilterStackFactory=yR.FilterStack=void 0;class DJ{constructor($){this.filters=$}sendMetadata($){let Y=$;for(let X=0;X<this.filters.length;X++)Y=this.filters[X].sendMetadata(Y);return Y}receiveMetadata($){let Y=$;for(let X=this.filters.length-1;X>=0;X--)Y=this.filters[X].receiveMetadata(Y);return Y}sendMessage($){let Y=$;for(let X=0;X<this.filters.length;X++)Y=this.filters[X].sendMessage(Y);return Y}receiveMessage($){let Y=$;for(let X=this.filters.length-1;X>=0;X--)Y=this.filters[X].receiveMessage(Y);return Y}receiveTrailers($){let Y=$;for(let X=this.filters.length-1;X>=0;X--)Y=this.filters[X].receiveTrailers(Y);return Y}push($){this.filters.unshift(...$)}getFilters(){return this.filters}}yR.FilterStack=DJ;class FJ{constructor($){this.factories=$}push($){this.factories.unshift(...$)}clone(){return new FJ([...this.factories])}createFilter(){return new DJ(this.factories.map(($)=>$.createFilter()))}}yR.FilterStackFactory=FJ});var _R=M((kR)=>{Object.defineProperty(kR,"__esModule",{value:!0});kR.SingleSubchannelChannel=void 0;var zO=F4(),t6=y$(),qO=AJ(),NO=n0(),e6=i(),MO=a6(),BO=bY(),IO=z4(),HJ=P0(),OO=M1(),q4=c0();class xR{constructor($,Y,X,Q,J){var Z,T;this.subchannel=$,this.method=Y,this.options=Q,this.callNumber=J,this.childCall=null,this.pendingMessage=null,this.readPending=!1,this.halfClosePending=!1,this.pendingStatus=null,this.readFilterPending=!1,this.writeFilterPending=!1;let K=this.method.split("/"),U="";if(K.length>=2)U=K[1];let G=(T=(Z=(0,q4.splitHostPort)(this.options.host))===null||Z===void 0?void 0:Z.host)!==null&&T!==void 0?T:"localhost";this.serviceUrl=`https://${G}/${U}`;let W=(0,BO.getRelativeTimeout)(Q.deadline);if(W!==1/0)if(W<=0)this.cancelWithStatus(e6.Status.DEADLINE_EXCEEDED,"Deadline exceeded");else setTimeout(()=>{this.cancelWithStatus(e6.Status.DEADLINE_EXCEEDED,"Deadline exceeded")},W);this.filterStack=X.createFilter()}cancelWithStatus($,Y){if(this.childCall)this.childCall.cancelWithStatus($,Y);else this.pendingStatus={code:$,details:Y,metadata:new HJ.Metadata}}getPeer(){var $,Y;return(Y=($=this.childCall)===null||$===void 0?void 0:$.getPeer())!==null&&Y!==void 0?Y:this.subchannel.getAddress()}async start($,Y){if(this.pendingStatus){Y.onReceiveStatus(this.pendingStatus);return}if(this.subchannel.getConnectivityState()!==NO.ConnectivityState.READY){Y.onReceiveStatus({code:e6.Status.UNAVAILABLE,details:"Subchannel not ready",metadata:new HJ.Metadata});return}let X=await this.filterStack.sendMetadata(Promise.resolve($)),Q;try{Q=await this.subchannel.getCallCredentials().generateMetadata({method_name:this.method,service_url:this.serviceUrl})}catch(Z){let T=Z,{code:K,details:U}=(0,MO.restrictControlPlaneStatusCode)(typeof T.code==="number"?T.code:e6.Status.UNKNOWN,`Getting metadata from plugin failed with error: ${T.message}`);Y.onReceiveStatus({code:K,details:U,metadata:new HJ.Metadata});return}Q.merge(X);let J={onReceiveMetadata:async(Z)=>{Y.onReceiveMetadata(await this.filterStack.receiveMetadata(Z))},onReceiveMessage:async(Z)=>{this.readFilterPending=!0;let T=await this.filterStack.receiveMessage(Z);if(this.readFilterPending=!1,Y.onReceiveMessage(T),this.pendingStatus)Y.onReceiveStatus(this.pendingStatus)},onReceiveStatus:async(Z)=>{let T=await this.filterStack.receiveTrailers(Z);if(this.readFilterPending)this.pendingStatus=T;else Y.onReceiveStatus(T)}};if(this.childCall=this.subchannel.createCall(Q,this.options.host,this.method,J),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($,Y){this.writeFilterPending=!0;let X=await this.filterStack.sendMessage(Promise.resolve({message:Y,flags:$.flags}));if(this.writeFilterPending=!1,this.childCall){if(this.childCall.sendMessageWithContext($,X.message),this.halfClosePending)this.childCall.halfClose()}else this.pendingMessage={context:$,message:X.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 vR{constructor($,Y,X){if(this.subchannel=$,this.target=Y,this.channelzEnabled=!1,this.channelzTrace=new t6.ChannelzTrace,this.callTracker=new t6.ChannelzCallTracker,this.childrenTracker=new t6.ChannelzChildrenTracker,this.channelzEnabled=X["grpc.enable_channelz"]!==0,this.channelzRef=(0,t6.registerChannelzChannel)((0,q4.uriToString)(Y),()=>({target:`${(0,q4.uriToString)(Y)} (${$.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 IO.FilterStackFactory([new qO.CompressionFilterFactory(this,X)])}close(){if(this.channelzEnabled)this.childrenTracker.unrefChild(this.subchannel.getChannelzRef());(0,t6.unregisterChannelzRef)(this.channelzRef)}getTarget(){return(0,q4.uriToString)(this.target)}getConnectivityState($){throw Error("Method not implemented.")}watchConnectivityState($,Y,X){throw Error("Method not implemented.")}getChannelzRef(){return this.channelzRef}createCall($,Y){let X={deadline:Y,host:(0,OO.getDefaultAuthority)(this.target),flags:e6.Propagate.DEFAULTS,parentCall:null};return new xR(this.subchannel,$,this.filterStackFactory,X,(0,zO.getNextCallNumber)())}}kR.SingleSubchannelChannel=vR});var bR=M((fR)=>{Object.defineProperty(fR,"__esModule",{value:!0});fR.Subchannel=void 0;var X0=n0(),PO=PY(),zJ=Z0(),N4=i(),LO=c0(),SO=r0(),n1=y$(),wO=_R(),CO="subchannel",yO=2147483647;class gR{constructor($,Y,X,Q,J){var Z;this.channelTarget=$,this.subchannelAddress=Y,this.options=X,this.connector=J,this.connectivityState=X0.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 T={initialDelay:X["grpc.initial_reconnect_backoff_ms"],maxDelay:X["grpc.max_reconnect_backoff_ms"]};if(this.backoffTimeout=new PO.BackoffTimeout(()=>{this.handleBackoffTimer()},T),this.backoffTimeout.unref(),this.subchannelAddressString=(0,SO.subchannelAddressToString)(Y),this.keepaliveTime=(Z=X["grpc.keepalive_time_ms"])!==null&&Z!==void 0?Z:-1,X["grpc.enable_channelz"]===0)this.channelzEnabled=!1,this.channelzTrace=new n1.ChannelzTraceStub,this.callTracker=new n1.ChannelzCallTrackerStub,this.childrenTracker=new n1.ChannelzChildrenTrackerStub,this.streamTracker=new n1.ChannelzCallTrackerStub;else this.channelzTrace=new n1.ChannelzTrace,this.callTracker=new n1.ChannelzCallTracker,this.childrenTracker=new n1.ChannelzChildrenTracker,this.streamTracker=new n1.ChannelzCallTracker;this.channelzRef=(0,n1.registerChannelzSubchannel)(this.subchannelAddressString,()=>this.getChannelzInfo(),this.channelzEnabled),this.channelzTrace.addTrace("CT_INFO","Subchannel created"),this.trace("Subchannel constructed with options "+JSON.stringify(X,void 0,2)),this.secureConnector=Q._createSecureConnector($,X)}getChannelzInfo(){return{state:this.connectivityState,trace:this.channelzTrace,callTracker:this.callTracker,children:this.childrenTracker.getChildLists(),target:this.subchannelAddressString}}trace($){zJ.trace(N4.LogVerbosity.DEBUG,CO,"("+this.channelzRef.id+") "+this.subchannelAddressString+" "+$)}refTrace($){zJ.trace(N4.LogVerbosity.DEBUG,"subchannel_refcount","("+this.channelzRef.id+") "+this.subchannelAddressString+" "+$)}handleBackoffTimer(){if(this.continueConnecting)this.transitionToState([X0.ConnectivityState.TRANSIENT_FAILURE],X0.ConnectivityState.CONNECTING);else this.transitionToState([X0.ConnectivityState.TRANSIENT_FAILURE],X0.ConnectivityState.IDLE)}startBackoff(){this.backoffTimeout.runOnce()}stopBackoff(){this.backoffTimeout.stop(),this.backoffTimeout.reset()}startConnectingInternal(){let $=this.options;if($["grpc.keepalive_time_ms"]){let Y=Math.min(this.keepaliveTime,yO);$=Object.assign(Object.assign({},$),{"grpc.keepalive_time_ms":Y})}this.connector.connect(this.subchannelAddress,this.secureConnector,$).then((Y)=>{if(this.transitionToState([X0.ConnectivityState.CONNECTING],X0.ConnectivityState.READY)){if(this.transport=Y,this.channelzEnabled)this.childrenTracker.refChild(Y.getChannelzRef());Y.addDisconnectListener((X)=>{if(this.transitionToState([X0.ConnectivityState.READY],X0.ConnectivityState.IDLE),X&&this.keepaliveTime>0)this.keepaliveTime*=2,zJ.log(N4.LogVerbosity.ERROR,`Connection to ${(0,LO.uriToString)(this.channelTarget)} at ${this.subchannelAddressString} rejected by server because of excess pings. Increasing ping interval to ${this.keepaliveTime} ms`)})}else Y.shutdown()},(Y)=>{this.transitionToState([X0.ConnectivityState.CONNECTING],X0.ConnectivityState.TRANSIENT_FAILURE,`${Y}`)})}transitionToState($,Y,X){var Q,J;if($.indexOf(this.connectivityState)===-1)return!1;if(X)this.trace(X0.ConnectivityState[this.connectivityState]+" -> "+X0.ConnectivityState[Y]+' with error "'+X+'"');else this.trace(X0.ConnectivityState[this.connectivityState]+" -> "+X0.ConnectivityState[Y]);if(this.channelzEnabled)this.channelzTrace.addTrace("CT_INFO","Connectivity state change to "+X0.ConnectivityState[Y]);let Z=this.connectivityState;switch(this.connectivityState=Y,Y){case X0.ConnectivityState.READY:this.stopBackoff();break;case X0.ConnectivityState.CONNECTING:this.startBackoff(),this.startConnectingInternal(),this.continueConnecting=!1;break;case X0.ConnectivityState.TRANSIENT_FAILURE:if(this.channelzEnabled&&this.transport)this.childrenTracker.unrefChild(this.transport.getChannelzRef());if((Q=this.transport)===null||Q===void 0||Q.shutdown(),this.transport=null,!this.backoffTimeout.isRunning())process.nextTick(()=>{this.handleBackoffTimer()});break;case X0.ConnectivityState.IDLE:if(this.channelzEnabled&&this.transport)this.childrenTracker.unrefChild(this.transport.getChannelzRef());(J=this.transport)===null||J===void 0||J.shutdown(),this.transport=null;break;default:throw Error(`Invalid state: unknown ConnectivityState ${Y}`)}for(let T of this.stateListeners)T(this,Z,Y,this.keepaliveTime,X);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,n1.unregisterChannelzRef)(this.channelzRef),this.secureConnector.destroy(),process.nextTick(()=>{this.transitionToState([X0.ConnectivityState.CONNECTING,X0.ConnectivityState.READY],X0.ConnectivityState.IDLE)})}unrefIfOneRef(){if(this.refcount===1)return this.unref(),!0;return!1}createCall($,Y,X,Q){if(!this.transport)throw Error("Cannot create call, subchannel not READY");let J;if(this.channelzEnabled)this.callTracker.addCallStarted(),this.streamTracker.addCallStarted(),J={onCallEnd:(Z)=>{if(Z.code===N4.Status.OK)this.callTracker.addCallSucceeded();else this.callTracker.addCallFailed()}};else J={};return this.transport.createCall($,Y,X,Q,J)}startConnecting(){process.nextTick(()=>{if(!this.transitionToState([X0.ConnectivityState.IDLE],X0.ConnectivityState.CONNECTING)){if(this.connectivityState===X0.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([X0.ConnectivityState.TRANSIENT_FAILURE],X0.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 wO.SingleSubchannelChannel(this,this.channelTarget,this.options);return this.subchannelChannel}addDataWatcher($){throw Error("Not implemented")}getOrCreateDataProducer($,Y){let X=this.dataProducers.get($);if(X)return X;let Q=Y(this);return this.dataProducers.set($,Q),Q}removeDataProducer($){this.dataProducers.delete($)}}fR.Subchannel=gR});var pR=M((uR)=>{var qJ;Object.defineProperty(uR,"__esModule",{value:!0});uR.GRPC_NODE_USE_ALTERNATIVE_RESOLVER=void 0;uR.GRPC_NODE_USE_ALTERNATIVE_RESOLVER=((qJ=process.env.GRPC_NODE_USE_ALTERNATIVE_RESOLVER)!==null&&qJ!==void 0?qJ:"false")==="true"});var BJ=M((rR)=>{Object.defineProperty(rR,"__esModule",{value:!0});rR.DEFAULT_PORT=void 0;rR.setup=fO;var cR=M1(),NJ=s("dns"),jO=p5(),MJ=i(),uY=l$(),xO=P0(),vO=Z0(),kO=i(),j$=c0(),nR=s("net"),hO=PY(),lR=pR(),_O="dns_resolver";function l1($){vO.trace(kO.LogVerbosity.DEBUG,_O,$)}rR.DEFAULT_PORT=443;var gO=30000;class iR{constructor($,Y,X){var Q,J,Z;if(this.target=$,this.listener=Y,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 NJ.promises.Resolver,l1("Resolver constructed for target "+(0,j$.uriToString)($)),$.authority)this.alternativeResolver.setServers([$.authority]);let T=(0,j$.splitHostPort)($.path);if(T===null)this.ipResult=null,this.dnsHostname=null,this.port=null;else if((0,nR.isIPv4)(T.host)||(0,nR.isIPv6)(T.host))this.ipResult=[{addresses:[{host:T.host,port:(Q=T.port)!==null&&Q!==void 0?Q:rR.DEFAULT_PORT}]}],this.dnsHostname=null,this.port=null;else this.ipResult=null,this.dnsHostname=T.host,this.port=(J=T.port)!==null&&J!==void 0?J:rR.DEFAULT_PORT;if(this.percentage=Math.random()*100,X["grpc.service_config_disable_resolution"]===1)this.isServiceConfigEnabled=!1;this.defaultResolutionError={code:MJ.Status.UNAVAILABLE,details:`Name resolution failed for target ${(0,j$.uriToString)(this.target)}`,metadata:new xO.Metadata};let K={initialDelay:X["grpc.initial_reconnect_backoff_ms"],maxDelay:X["grpc.max_reconnect_backoff_ms"]};this.backoff=new hO.BackoffTimeout(()=>{if(this.continueResolving)this.startResolutionWithBackoff()},K),this.backoff.unref(),this.minTimeBetweenResolutionsMs=(Z=X["grpc.dns_min_time_between_resolutions_ms"])!==null&&Z!==void 0?Z:gO,this.nextResolutionTimer=setTimeout(()=>{},0),clearTimeout(this.nextResolutionTimer)}startResolution(){if(this.ipResult!==null){if(!this.returnedIpResult)l1("Returning IP address for target "+(0,j$.uriToString)(this.target)),setImmediate(()=>{this.listener((0,uY.statusOrFromValue)(this.ipResult),{},null,"")}),this.returnedIpResult=!0;this.backoff.stop(),this.backoff.reset(),this.stopNextResolutionTimer();return}if(this.dnsHostname===null)l1("Failed to parse DNS address "+(0,j$.uriToString)(this.target)),setImmediate(()=>{this.listener((0,uY.statusOrFromError)({code:MJ.Status.UNAVAILABLE,details:`Failed to parse DNS address ${(0,j$.uriToString)(this.target)}`}),{},null,"")}),this.stopNextResolutionTimer();else{if(this.pendingLookupPromise!==null)return;l1("Looking up DNS hostname "+this.dnsHostname),this.latestLookupResult=null;let $=this.dnsHostname;if(this.pendingLookupPromise=this.lookup($),this.pendingLookupPromise.then((Y)=>{if(this.pendingLookupPromise===null)return;this.pendingLookupPromise=null,this.latestLookupResult=(0,uY.statusOrFromValue)(Y.map((J)=>({addresses:[J]})));let X="["+Y.map((J)=>J.host+":"+J.port).join(",")+"]";l1("Resolved addresses for target "+(0,j$.uriToString)(this.target)+": "+X);let Q=this.listener(this.latestLookupResult,{},this.latestServiceConfigResult,"");this.handleHealthStatus(Q)},(Y)=>{if(this.pendingLookupPromise===null)return;l1("Resolution error for target "+(0,j$.uriToString)(this.target)+": "+Y.message),this.pendingLookupPromise=null,this.stopNextResolutionTimer(),this.listener((0,uY.statusOrFromError)(this.defaultResolutionError),{},this.latestServiceConfigResult,"")}),this.isServiceConfigEnabled&&this.pendingTxtPromise===null)this.pendingTxtPromise=this.resolveTxt($),this.pendingTxtPromise.then((Y)=>{if(this.pendingTxtPromise===null)return;this.pendingTxtPromise=null;let X;try{if(X=(0,jO.extractAndSelectServiceConfig)(Y,this.percentage),X)this.latestServiceConfigResult=(0,uY.statusOrFromValue)(X);else this.latestServiceConfigResult=null}catch(Q){this.latestServiceConfigResult=(0,uY.statusOrFromError)({code:MJ.Status.UNAVAILABLE,details:`Parsing service config failed with error ${Q.message}`})}if(this.latestLookupResult!==null)this.listener(this.latestLookupResult,{},this.latestServiceConfigResult,"")},(Y)=>{})}}handleHealthStatus($){if($)this.backoff.stop(),this.backoff.reset();else this.continueResolving=!0}async lookup($){if(lR.GRPC_NODE_USE_ALTERNATIVE_RESOLVER){l1("Using alternative DNS resolver.");let X=await Promise.allSettled([this.alternativeResolver.resolve4($),this.alternativeResolver.resolve6($)]);if(X.every((Q)=>Q.status==="rejected"))throw Error(X[0].reason);return X.reduce((Q,J)=>{return J.status==="fulfilled"?[...Q,...J.value]:Q},[]).map((Q)=>({host:Q,port:+this.port}))}return(await NJ.promises.lookup($,{all:!0})).map((X)=>({host:X.address,port:+this.port}))}async resolveTxt($){if(lR.GRPC_NODE_USE_ALTERNATIVE_RESOLVER)return l1("Using alternative DNS resolver."),this.alternativeResolver.resolveTxt($);return NJ.promises.resolveTxt($)}startNextResolutionTimer(){var $,Y;clearTimeout(this.nextResolutionTimer),this.nextResolutionTimer=setTimeout(()=>{if(this.stopNextResolutionTimer(),this.continueResolving)this.startResolutionWithBackoff()},this.minTimeBetweenResolutionsMs),(Y=($=this.nextResolutionTimer).unref)===null||Y===void 0||Y.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)l1('resolution update delayed by "min time between resolutions" rate limit');else l1("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 fO(){(0,cR.registerResolver)("dns",iR),(0,cR.registerDefaultScheme)("dns")}});var IJ=M((eR)=>{Object.defineProperty(eR,"__esModule",{value:!0});eR.parseCIDR=aR;eR.mapProxyName=oO;eR.getProxiedConnection=sO;var $8=Z0(),dY=i(),sR=s("net"),bO=s("http"),uO=Z0(),oR=r0(),Y8=c0(),dO=s("url"),pO=BJ(),cO="proxy";function pY($){uO.trace(dY.LogVerbosity.DEBUG,cO,$)}function nO(){let $="",Y="";if(process.env.grpc_proxy)Y="grpc_proxy",$=process.env.grpc_proxy;else if(process.env.https_proxy)Y="https_proxy",$=process.env.https_proxy;else if(process.env.http_proxy)Y="http_proxy",$=process.env.http_proxy;else return{};let X;try{X=new dO.URL($)}catch(K){return(0,$8.log)(dY.LogVerbosity.ERROR,`cannot parse value of "${Y}" env var`),{}}if(X.protocol!=="http:")return(0,$8.log)(dY.LogVerbosity.ERROR,`"${X.protocol}" scheme not supported in proxy URI`),{};let Q=null;if(X.username)if(X.password)(0,$8.log)(dY.LogVerbosity.INFO,"userinfo found in proxy URI"),Q=decodeURIComponent(`${X.username}:${X.password}`);else Q=X.username;let{hostname:J,port:Z}=X;if(Z==="")Z="80";let T={address:`${J}:${Z}`};if(Q)T.creds=Q;return pY("Proxy server "+T.address+" set by environment variable "+Y),T}function lO(){let $=process.env.no_grpc_proxy,Y="no_grpc_proxy";if(!$)$=process.env.no_proxy,Y="no_proxy";if($)return pY("No proxy server list set by environment variable "+Y),$.split(",");else return[]}function aR($){let Y=$.split("/");if(Y.length!==2)return null;let X=parseInt(Y[1],10);if(!(0,sR.isIPv4)(Y[0])||Number.isNaN(X)||X<0||X>32)return null;return{ip:tR(Y[0]),prefixLength:X}}function tR($){return $.split(".").reduce((Y,X)=>(Y<<8)+parseInt(X,10),0)}function iO($,Y){let X=$.ip,Q=-1<<32-$.prefixLength;return(tR(Y)&Q)===(X&Q)}function rO($){for(let Y of lO()){let X=aR(Y);if((0,sR.isIPv4)($)&&X&&iO(X,$))return!0;else if($.endsWith(Y))return!0}return!1}function oO($,Y){var X;let Q={target:$,extraOptions:{}};if(((X=Y["grpc.enable_http_proxy"])!==null&&X!==void 0?X:1)===0)return Q;if($.scheme==="unix")return Q;let J=nO();if(!J.address)return Q;let Z=(0,Y8.splitHostPort)($.path);if(!Z)return Q;let T=Z.host;if(rO(T))return pY("Not using proxy for target in no_proxy list: "+(0,Y8.uriToString)($)),Q;let K={"grpc.http_connect_target":(0,Y8.uriToString)($)};if(J.creds)K["grpc.http_connect_creds"]=J.creds;return{target:{scheme:"dns",path:J.address},extraOptions:K}}function sO($,Y){var X;if(!("grpc.http_connect_target"in Y))return Promise.resolve(null);let Q=Y["grpc.http_connect_target"],J=(0,Y8.parseUri)(Q);if(J===null)return Promise.resolve(null);let Z=(0,Y8.splitHostPort)(J.path);if(Z===null)return Promise.resolve(null);let T=`${Z.host}:${(X=Z.port)!==null&&X!==void 0?X:pO.DEFAULT_PORT}`,K={method:"CONNECT",path:T},U={Host:T};if((0,oR.isTcpSubchannelAddress)($))K.host=$.host,K.port=$.port;else K.socketPath=$.path;if("grpc.http_connect_creds"in Y)U["Proxy-Authorization"]="Basic "+Buffer.from(Y["grpc.http_connect_creds"]).toString("base64");K.headers=U;let G=(0,oR.subchannelAddressToString)($);return pY("Using proxy "+G+" to connect to "+K.path),new Promise((W,R)=>{let V=bO.request(K);V.once("connect",(A,H,z)=>{if(V.removeAllListeners(),H.removeAllListeners(),A.statusCode===200){if(pY("Successfully connected to "+K.path+" through proxy "+G),z.length>0)H.unshift(z);pY("Successfully established a plaintext connection to "+K.path+" through proxy "+G),W(H)}else(0,$8.log)(dY.LogVerbosity.ERROR,"Failed to connect to "+K.path+" through proxy "+G+" with status "+A.statusCode),R()}),V.once("error",(A)=>{V.removeAllListeners(),(0,$8.log)(dY.LogVerbosity.ERROR,"Failed to connect to proxy "+G+" with error "+A.message),R()}),V.end()})}});var OJ=M((YE)=>{Object.defineProperty(YE,"__esModule",{value:!0});YE.StreamDecoder=void 0;var i1;(function($){$[$.NO_DATA=0]="NO_DATA",$[$.READING_SIZE=1]="READING_SIZE",$[$.READING_MESSAGE=2]="READING_MESSAGE"})(i1||(i1={}));class $E{constructor($){this.maxReadMessageLength=$,this.readState=i1.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 Y=0,X,Q=[];while(Y<$.length)switch(this.readState){case i1.NO_DATA:this.readCompressFlag=$.slice(Y,Y+1),Y+=1,this.readState=i1.READING_SIZE,this.readPartialSize.fill(0),this.readSizeRemaining=4,this.readMessageSize=0,this.readMessageRemaining=0,this.readPartialMessage=[];break;case i1.READING_SIZE:if(X=Math.min($.length-Y,this.readSizeRemaining),$.copy(this.readPartialSize,4-this.readSizeRemaining,Y,Y+X),this.readSizeRemaining-=X,Y+=X,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=i1.READING_MESSAGE;else{let J=Buffer.concat([this.readCompressFlag,this.readPartialSize],5);this.readState=i1.NO_DATA,Q.push(J)}}break;case i1.READING_MESSAGE:if(X=Math.min($.length-Y,this.readMessageRemaining),this.readPartialMessage.push($.slice(Y,Y+X)),this.readMessageRemaining-=X,Y+=X,this.readMessageRemaining===0){let J=[this.readCompressFlag,this.readPartialSize].concat(this.readPartialMessage),Z=Buffer.concat(J,this.readMessageSize+5);this.readState=i1.NO_DATA,Q.push(Z)}break;default:throw Error("Unexpected read state")}return Q}}YE.StreamDecoder=$E});var TE=M((JE)=>{Object.defineProperty(JE,"__esModule",{value:!0});JE.Http2SubchannelCall=void 0;var G$=s("http2"),$P=s("os"),Q0=i(),W$=P0(),YP=OJ(),XP=Z0(),QP=i(),JP="subchannel_call";function ZP($){for(let[Y,X]of Object.entries($P.constants.errno))if(X===$)return Y;return"Unknown system error "+$}function PJ($){let Y=`Received HTTP status code ${$}`,X;switch($){case 400:X=Q0.Status.INTERNAL;break;case 401:X=Q0.Status.UNAUTHENTICATED;break;case 403:X=Q0.Status.PERMISSION_DENIED;break;case 404:X=Q0.Status.UNIMPLEMENTED;break;case 429:case 502:case 503:case 504:X=Q0.Status.UNAVAILABLE;break;default:X=Q0.Status.UNKNOWN}return{code:X,details:Y,metadata:new W$.Metadata}}class QE{constructor($,Y,X,Q,J){var Z;this.http2Stream=$,this.callEventTracker=Y,this.listener=X,this.transport=Q,this.callId=J,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 T=(Z=Q.getOptions()["grpc.max_receive_message_length"])!==null&&Z!==void 0?Z:Q0.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH;this.decoder=new YP.StreamDecoder(T),$.on("response",(K,U)=>{let G="";for(let W of Object.keys(K))G+="\t\t"+W+": "+K[W]+`
|
|
16
|
+
`;if(this.trace(`Received server headers:
|
|
17
|
+
`+G),this.httpStatusCode=K[":status"],U&G$.constants.NGHTTP2_FLAG_END_STREAM)this.handleTrailers(K);else{let W;try{W=W$.Metadata.fromHttp2Headers(K)}catch(R){this.endCall({code:Q0.Status.UNKNOWN,details:R.message,metadata:new W$.Metadata});return}this.listener.onReceiveMetadata(W)}}),$.on("trailers",(K)=>{this.handleTrailers(K)}),$.on("data",(K)=>{if(this.statusOutput)return;this.trace("receive HTTP/2 data frame of length "+K.length);let U;try{U=this.decoder.write(K)}catch(G){if(this.httpStatusCode!==void 0&&this.httpStatusCode!==200){let W=PJ(this.httpStatusCode);this.cancelWithStatus(W.code,W.details)}else this.cancelWithStatus(Q0.Status.RESOURCE_EXHAUSTED,G.message);return}for(let G of U)this.trace("parsed message of length "+G.length),this.callEventTracker.addMessageReceived(),this.tryPush(G)}),$.on("end",()=>{this.readsClosed=!0,this.maybeOutputStatus()}),$.on("close",()=>{this.serverEndedCall=!0,process.nextTick(()=>{var K;if(this.trace("HTTP/2 stream closed with code "+$.rstCode),((K=this.finalStatus)===null||K===void 0?void 0:K.code)===Q0.Status.OK)return;let U,G="";switch($.rstCode){case G$.constants.NGHTTP2_NO_ERROR:if(this.finalStatus!==null)return;if(this.httpStatusCode&&this.httpStatusCode!==200){let W=PJ(this.httpStatusCode);U=W.code,G=W.details}else U=Q0.Status.INTERNAL,G=`Received RST_STREAM with code ${$.rstCode} (Call ended without gRPC status)`;break;case G$.constants.NGHTTP2_REFUSED_STREAM:U=Q0.Status.UNAVAILABLE,G="Stream refused by server";break;case G$.constants.NGHTTP2_CANCEL:if(this.connectionDropped)U=Q0.Status.UNAVAILABLE,G="Connection dropped";else U=Q0.Status.CANCELLED,G="Call cancelled";break;case G$.constants.NGHTTP2_ENHANCE_YOUR_CALM:U=Q0.Status.RESOURCE_EXHAUSTED,G="Bandwidth exhausted or memory limit exceeded";break;case G$.constants.NGHTTP2_INADEQUATE_SECURITY:U=Q0.Status.PERMISSION_DENIED,G="Protocol not secure enough";break;case G$.constants.NGHTTP2_INTERNAL_ERROR:if(U=Q0.Status.INTERNAL,this.internalError===null)G=`Received RST_STREAM with code ${$.rstCode} (Internal server error)`;else if(this.internalError.code==="ECONNRESET"||this.internalError.code==="ETIMEDOUT")U=Q0.Status.UNAVAILABLE,G=this.internalError.message;else G=`Received RST_STREAM with code ${$.rstCode} triggered by internal client error: ${this.internalError.message}`;break;default:U=Q0.Status.INTERNAL,G=`Received RST_STREAM with code ${$.rstCode}`}this.endCall({code:U,details:G,metadata:new W$.Metadata,rstCode:$.rstCode})})}),$.on("error",(K)=>{if(K.code!=="ERR_HTTP2_STREAM_ERROR")this.trace("Node error event: message="+K.message+" code="+K.code+" errno="+ZP(K.errno)+" syscall="+K.syscall),this.internalError=K;this.callEventTracker.onStreamEnd(!1)})}getDeadlineInfo(){return[`remote_addr=${this.getPeer()}`]}onDisconnect(){this.connectionDropped=!0,setImmediate(()=>{this.endCall({code:Q0.Status.UNAVAILABLE,details:"Connection dropped",metadata:new W$.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($){XP.trace(QP.LogVerbosity.DEBUG,JP,"["+this.callId+"] "+$)}endCall($){if(this.finalStatus===null||this.finalStatus.code===Q0.Status.OK)this.finalStatus=$,this.maybeOutputStatus();this.destroyHttp2Stream()}maybeOutputStatus(){if(this.finalStatus!==null){if(this.finalStatus.code!==Q0.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 Y="";for(let Z of Object.keys($))Y+="\t\t"+Z+": "+$[Z]+`
|
|
18
|
+
`;this.trace(`Received server trailers:
|
|
19
|
+
`+Y);let X;try{X=W$.Metadata.fromHttp2Headers($)}catch(Z){X=new W$.Metadata}let Q=X.getMap(),J;if(typeof Q["grpc-status"]==="string"){let Z=Number(Q["grpc-status"]);this.trace("received status code "+Z+" from server"),X.remove("grpc-status");let T="";if(typeof Q["grpc-message"]==="string"){try{T=decodeURI(Q["grpc-message"])}catch(K){T=Q["grpc-message"]}X.remove("grpc-message"),this.trace('received status details string "'+T+'" from server')}J={code:Z,details:T,metadata:X}}else if(this.httpStatusCode)J=PJ(this.httpStatusCode),J.metadata=X;else J={code:Q0.Status.UNKNOWN,details:"No status information received",metadata:X};this.endCall(J)}destroyHttp2Stream(){var $;if(this.http2Stream.destroyed)return;if(this.serverEndedCall)this.http2Stream.end();else{let Y;if((($=this.finalStatus)===null||$===void 0?void 0:$.code)===Q0.Status.OK)Y=G$.constants.NGHTTP2_NO_ERROR;else Y=G$.constants.NGHTTP2_CANCEL;this.trace("close http2 stream with code "+Y),this.http2Stream.close(Y)}}cancelWithStatus($,Y){this.trace("cancelWithStatus code: "+$+' details: "'+Y+'"'),this.endCall({code:$,details:Y,metadata:new W$.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!==Q0.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($,Y){this.trace("write() called with message of length "+Y.length);let X=(Q)=>{process.nextTick(()=>{var J;let Z=Q0.Status.UNAVAILABLE;if((Q===null||Q===void 0?void 0:Q.code)==="ERR_STREAM_WRITE_AFTER_END")Z=Q0.Status.INTERNAL;if(Q)this.cancelWithStatus(Z,`Write error: ${Q.message}`);(J=$.callback)===null||J===void 0||J.call($)})};this.trace("sending data chunk of length "+Y.length),this.callEventTracker.addMessageSent();try{this.http2Stream.write(Y,X)}catch(Q){this.endCall({code:Q0.Status.UNAVAILABLE,details:`Write failed with error ${Q.message}`,metadata:new W$.Metadata})}}halfClose(){this.trace("end() called"),this.trace("calling end() on HTTP/2 stream"),this.http2Stream.end()}}JE.Http2SubchannelCall=QE});var RE=M((GE)=>{Object.defineProperty(GE,"__esModule",{value:!0});GE.Http2SubchannelConnector=void 0;var YY=s("http2"),TP=s("tls"),B4=y$(),X8=i(),KP=IJ(),cY=Z0(),UP=M1(),I4=r0(),LJ=c0(),GP=s("net"),WP=TE(),RP=F4(),SJ="transport",EP="transport_flowctrl",VP=L5().version,{HTTP2_HEADER_AUTHORITY:AP,HTTP2_HEADER_CONTENT_TYPE:DP,HTTP2_HEADER_METHOD:FP,HTTP2_HEADER_PATH:HP,HTTP2_HEADER_TE:zP,HTTP2_HEADER_USER_AGENT:qP}=YY.constants,NP=20000,MP=Buffer.from("too_many_pings","ascii");class KE{constructor($,Y,X,Q){if(this.session=$,this.options=X,this.remoteName=Q,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,I4.subchannelAddressToString)(Y),X["grpc.enable_channelz"]===0)this.channelzEnabled=!1,this.streamTracker=new B4.ChannelzCallTrackerStub;else this.streamTracker=new B4.ChannelzCallTracker;if(this.channelzRef=(0,B4.registerChannelzSocket)(this.subchannelAddressString,()=>this.getChannelzInfo(),this.channelzEnabled),this.userAgent=[X["grpc.primary_user_agent"],`grpc-node-js/${VP}`,X["grpc.secondary_user_agent"]].filter((J)=>J).join(" "),"grpc.keepalive_time_ms"in X)this.keepaliveTimeMs=X["grpc.keepalive_time_ms"];else this.keepaliveTimeMs=-1;if("grpc.keepalive_timeout_ms"in X)this.keepaliveTimeoutMs=X["grpc.keepalive_timeout_ms"];else this.keepaliveTimeoutMs=NP;if("grpc.keepalive_permit_without_calls"in X)this.keepaliveWithoutCalls=X["grpc.keepalive_permit_without_calls"]===1;else this.keepaliveWithoutCalls=!1;if($.once("close",()=>{this.trace("session closed"),this.handleDisconnect()}),$.once("goaway",(J,Z,T)=>{let K=!1;if(J===YY.constants.NGHTTP2_ENHANCE_YOUR_CALM&&T&&T.equals(MP))K=!0;this.trace("connection closed by GOAWAY with code "+J+" and data "+(T===null||T===void 0?void 0:T.toString())),this.reportDisconnectToOwner(K)}),$.once("error",(J)=>{this.trace("connection closed with error "+J.message),this.handleDisconnect()}),$.socket.once("close",(J)=>{this.trace("connection closed. hadError="+J),this.handleDisconnect()}),cY.isTracerEnabled(SJ))$.on("remoteSettings",(J)=>{this.trace("new settings received"+(this.session!==$?" on the old connection":"")+": "+JSON.stringify(J))}),$.on("localSettings",(J)=>{this.trace("local settings acknowledged by remote"+(this.session!==$?" on the old connection":"")+": "+JSON.stringify(J))});if(this.keepaliveWithoutCalls)this.maybeStartKeepalivePingTimer();if($.socket instanceof TP.TLSSocket)this.authContext={transportSecurityType:"ssl",sslPeerCertificate:$.socket.getPeerCertificate()};else this.authContext={}}getChannelzInfo(){var $,Y,X;let Q=this.session.socket,J=Q.remoteAddress?(0,I4.stringToSubchannelAddress)(Q.remoteAddress,Q.remotePort):null,Z=Q.localAddress?(0,I4.stringToSubchannelAddress)(Q.localAddress,Q.localPort):null,T;if(this.session.encrypted){let U=Q,G=U.getCipher(),W=U.getCertificate(),R=U.getPeerCertificate();T={cipherSuiteStandardName:($=G.standardName)!==null&&$!==void 0?$:null,cipherSuiteOtherName:G.standardName?null:G.name,localCertificate:W&&"raw"in W?W.raw:null,remoteCertificate:R&&"raw"in R?R.raw:null}}else T=null;return{remoteAddress:J,localAddress:Z,security:T,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:(Y=this.session.state.localWindowSize)!==null&&Y!==void 0?Y:null,remoteFlowControlWindow:(X=this.session.state.remoteWindowSize)!==null&&X!==void 0?X:null}}trace($){cY.trace(X8.LogVerbosity.DEBUG,SJ,"("+this.channelzRef.id+") "+this.subchannelAddressString+" "+$)}keepaliveTrace($){cY.trace(X8.LogVerbosity.DEBUG,"keepalive","("+this.channelzRef.id+") "+this.subchannelAddressString+" "+$)}flowControlTrace($){cY.trace(X8.LogVerbosity.DEBUG,EP,"("+this.channelzRef.id+") "+this.subchannelAddressString+" "+$)}internalsTrace($){cY.trace(X8.LogVerbosity.DEBUG,"transport_internals","("+this.channelzRef.id+") "+this.subchannelAddressString+" "+$)}reportDisconnectToOwner($){if(this.disconnectHandled)return;this.disconnectHandled=!0,this.disconnectListeners.forEach((Y)=>Y($))}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 $,Y;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),(Y=($=this.keepaliveTimer).unref)===null||Y===void 0||Y.call($);let X="";try{if(!this.session.ping((J,Z,T)=>{if(this.clearKeepaliveTimeout(),J)this.keepaliveTrace("Ping failed with error "+J.message),this.handleDisconnect();else this.keepaliveTrace("Received ping response"),this.maybeStartKeepalivePingTimer()}))X="Ping returned false"}catch(Q){X=(Q instanceof Error?Q.message:"")||"Unknown error"}if(X)this.keepaliveTrace("Ping send failed: "+X),this.handleDisconnect()}maybeStartKeepalivePingTimer(){var $,Y;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),(Y=($=this.keepaliveTimer).unref)===null||Y===void 0||Y.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($,Y,X,Q,J){let Z=$.toHttp2Headers();Z[AP]=Y,Z[qP]=this.userAgent,Z[DP]="application/grpc",Z[FP]="POST",Z[HP]=X,Z[zP]="trailers";let T;try{T=this.session.request(Z)}catch(G){throw this.handleDisconnect(),G}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 K,U;if(this.channelzEnabled)this.streamTracker.addCallStarted(),K={addMessageSent:()=>{var G;this.messagesSent+=1,this.lastMessageSentTimestamp=new Date,(G=J.addMessageSent)===null||G===void 0||G.call(J)},addMessageReceived:()=>{var G;this.messagesReceived+=1,this.lastMessageReceivedTimestamp=new Date,(G=J.addMessageReceived)===null||G===void 0||G.call(J)},onCallEnd:(G)=>{var W;(W=J.onCallEnd)===null||W===void 0||W.call(J,G),this.removeActiveCall(U)},onStreamEnd:(G)=>{var W;if(G)this.streamTracker.addCallSucceeded();else this.streamTracker.addCallFailed();(W=J.onStreamEnd)===null||W===void 0||W.call(J,G)}};else K={addMessageSent:()=>{var G;(G=J.addMessageSent)===null||G===void 0||G.call(J)},addMessageReceived:()=>{var G;(G=J.addMessageReceived)===null||G===void 0||G.call(J)},onCallEnd:(G)=>{var W;(W=J.onCallEnd)===null||W===void 0||W.call(J,G),this.removeActiveCall(U)},onStreamEnd:(G)=>{var W;(W=J.onStreamEnd)===null||W===void 0||W.call(J,G)}};return U=new WP.Http2SubchannelCall(T,K,Q,this,(0,RP.getNextCallNumber)()),this.addActiveCall(U),U}getChannelzRef(){return this.channelzRef}getPeerName(){return this.subchannelAddressString}getOptions(){return this.options}getAuthContext(){return this.authContext}shutdown(){this.session.close(),(0,B4.unregisterChannelzRef)(this.channelzRef)}}class UE{constructor($){this.channelTarget=$,this.session=null,this.isShutdown=!1}trace($){cY.trace(X8.LogVerbosity.DEBUG,SJ,(0,LJ.uriToString)(this.channelTarget)+" "+$)}createSession($,Y,X){if(this.isShutdown)return Promise.reject();if($.socket.closed)return Promise.reject("Connection closed before starting HTTP/2 handshake");return new Promise((Q,J)=>{var Z,T,K,U,G,W,R,V;let A=null,H=this.channelTarget;if("grpc.http_connect_target"in X){let y=(0,LJ.parseUri)(X["grpc.http_connect_target"]);if(y)H=y,A=(0,LJ.uriToString)(y)}let z=$.secure?"https":"http",D=(0,UP.getDefaultAuthority)(H),B=()=>{var y;(y=this.session)===null||y===void 0||y.destroy(),this.session=null,setImmediate(()=>{if(!f)f=!0,J(`${k.trim()} (${new Date().toISOString()})`)})},w=(y)=>{var j;if((j=this.session)===null||j===void 0||j.destroy(),k=y.message,this.trace("connection failed with error "+k),!f)f=!0,J(`${k} (${new Date().toISOString()})`)},x={createConnection:(y,j)=>{return $.socket},settings:{initialWindowSize:(U=(Z=X["grpc-node.flow_control_window"])!==null&&Z!==void 0?Z:(K=(T=YY.getDefaultSettings)===null||T===void 0?void 0:T.call(YY))===null||K===void 0?void 0:K.initialWindowSize)!==null&&U!==void 0?U:65535},maxSendHeaderBlockLength:Number.MAX_SAFE_INTEGER,maxSessionMemory:(G=X["grpc-node.max_session_memory"])!==null&&G!==void 0?G:Number.MAX_SAFE_INTEGER},q=YY.connect(`${z}://${D}`,x),_=(V=(R=(W=YY.getDefaultSettings)===null||W===void 0?void 0:W.call(YY))===null||R===void 0?void 0:R.initialWindowSize)!==null&&V!==void 0?V:65535,C=X["grpc-node.flow_control_window"];this.session=q;let k="Failed to connect",f=!1;q.unref(),q.once("remoteSettings",()=>{var y;if(C&&C>_)try{q.setLocalWindowSize(C)}catch(j){let N=C-((y=q.state.localWindowSize)!==null&&y!==void 0?y:_);if(N>0)q.incrementWindowSize(N)}q.removeAllListeners(),$.socket.removeListener("close",B),$.socket.removeListener("error",w),Q(new KE(q,Y,X,A)),this.session=null}),q.once("close",B),q.once("error",w),$.socket.once("close",B),$.socket.once("error",w)})}tcpConnect($,Y){return(0,KP.getProxiedConnection)($,Y).then((X)=>{if(X)return X;else return new Promise((Q,J)=>{let Z=()=>{J(Error("Socket closed"))},T=(U)=>{J(U)},K=GP.connect($,()=>{K.removeListener("close",Z),K.removeListener("error",T),Q(K)});K.once("close",Z),K.once("error",T)})})}async connect($,Y,X){if(this.isShutdown)return Promise.reject();let Q=null,J=null,Z=(0,I4.subchannelAddressToString)($);try{return this.trace(Z+" Waiting for secureConnector to be ready"),await Y.waitForReady(),this.trace(Z+" secureConnector is ready"),Q=await this.tcpConnect($,X),Q.setNoDelay(),this.trace(Z+" Established TCP connection"),J=await Y.connect(Q),this.trace(Z+" Established secure connection"),this.createSession(J,$,X)}catch(T){throw Q===null||Q===void 0||Q.destroy(),J===null||J===void 0||J.socket.destroy(),T}}shutdown(){var $;this.isShutdown=!0,($=this.session)===null||$===void 0||$.close(),this.session=null}}GE.Http2SubchannelConnector=UE});var AE=M((EE)=>{Object.defineProperty(EE,"__esModule",{value:!0});EE.SubchannelPool=void 0;EE.getSubchannelPool=CP;var BP=BK(),IP=bR(),OP=r0(),PP=c0(),LP=RE(),SP=1e4;class O4{constructor(){this.pool=Object.create(null),this.cleanupTimer=null}unrefUnusedSubchannels(){let $=!0;for(let Y in this.pool){let Q=this.pool[Y].filter((J)=>!J.subchannel.unrefIfOneRef());if(Q.length>0)$=!1;this.pool[Y]=Q}if($&&this.cleanupTimer!==null)clearInterval(this.cleanupTimer),this.cleanupTimer=null}ensureCleanupTask(){var $,Y;if(this.cleanupTimer===null)this.cleanupTimer=setInterval(()=>{this.unrefUnusedSubchannels()},SP),(Y=($=this.cleanupTimer).unref)===null||Y===void 0||Y.call($)}getOrCreateSubchannel($,Y,X,Q){this.ensureCleanupTask();let J=(0,PP.uriToString)($);if(J in this.pool){let T=this.pool[J];for(let K of T)if((0,OP.subchannelAddressEqual)(Y,K.subchannelAddress)&&(0,BP.channelOptionsEqual)(X,K.channelArguments)&&Q._equals(K.channelCredentials))return K.subchannel}let Z=new IP.Subchannel($,Y,X,Q,new LP.Http2SubchannelConnector($));if(!(J in this.pool))this.pool[J]=[];return this.pool[J].push({subchannelAddress:Y,channelArguments:X,channelCredentials:Q,subchannel:Z}),Z.ref(),Z}}EE.SubchannelPool=O4;var wP=new O4;function CP($){if($)return wP;else return new O4}});var NE=M((zE)=>{Object.defineProperty(zE,"__esModule",{value:!0});zE.LoadBalancingCall=void 0;var DE=n0(),P4=i(),FE=bY(),L4=P0(),Q8=Y$(),jP=c0(),xP=Z0(),wJ=a6(),vP=s("http2"),kP="load_balancing_call";class HE{constructor($,Y,X,Q,J,Z,T){var K,U;this.channel=$,this.callConfig=Y,this.methodName=X,this.host=Q,this.credentials=J,this.deadline=Z,this.callNumber=T,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 G=this.methodName.split("/"),W="";if(G.length>=2)W=G[1];let R=(U=(K=(0,jP.splitHostPort)(this.host))===null||K===void 0?void 0:K.host)!==null&&U!==void 0?U:"localhost";this.serviceUrl=`https://${R}/${W}`,this.startTime=new Date}getDeadlineInfo(){var $,Y;let X=[];if(this.childStartTime){if(this.childStartTime>this.startTime){if(($=this.metadata)===null||$===void 0?void 0:$.getOptions().waitForReady)X.push("wait_for_ready");X.push(`LB pick: ${(0,FE.formatDateDifference)(this.startTime,this.childStartTime)}`)}return X.push(...this.child.getDeadlineInfo()),X}else{if((Y=this.metadata)===null||Y===void 0?void 0:Y.getOptions().waitForReady)X.push("wait_for_ready");X.push("Waiting for LB pick")}return X}trace($){xP.trace(P4.LogVerbosity.DEBUG,kP,"["+this.callNumber+"] "+$)}outputStatus($,Y){var X,Q;if(!this.ended){this.ended=!0,this.trace("ended with status: code="+$.code+' details="'+$.details+'" start time='+this.startTime.toISOString());let J=Object.assign(Object.assign({},$),{progress:Y});(X=this.listener)===null||X===void 0||X.onReceiveStatus(J),(Q=this.onCallEnded)===null||Q===void 0||Q.call(this,J.code,J.details,J.metadata)}}doPick(){var $,Y;if(this.ended)return;if(!this.metadata)throw Error("doPick called before start");this.trace("Pick called");let X=this.metadata.clone(),Q=this.channel.doPick(X,this.callConfig.pickInformation),J=Q.subchannel?"("+Q.subchannel.getChannelzRef().id+") "+Q.subchannel.getAddress():""+Q.subchannel;switch(this.trace("Pick result: "+Q8.PickResultType[Q.pickResultType]+" subchannel: "+J+" status: "+(($=Q.status)===null||$===void 0?void 0:$.code)+" "+((Y=Q.status)===null||Y===void 0?void 0:Y.details)),Q.pickResultType){case Q8.PickResultType.COMPLETE:this.credentials.compose(Q.subchannel.getCallCredentials()).generateMetadata({method_name:this.methodName,service_url:this.serviceUrl}).then((U)=>{var G;if(this.ended){this.trace("Credentials metadata generation finished after call ended");return}if(X.merge(U),X.get("authorization").length>1)this.outputStatus({code:P4.Status.INTERNAL,details:'"authorization" metadata cannot have multiple values',metadata:new L4.Metadata},"PROCESSED");if(Q.subchannel.getConnectivityState()!==DE.ConnectivityState.READY){this.trace("Picked subchannel "+J+" has state "+DE.ConnectivityState[Q.subchannel.getConnectivityState()]+" after getting credentials metadata. Retrying pick"),this.doPick();return}if(this.deadline!==1/0)X.set("grpc-timeout",(0,FE.getDeadlineTimeoutString)(this.deadline));try{this.child=Q.subchannel.getRealSubchannel().createCall(X,this.host,this.methodName,{onReceiveMetadata:(W)=>{this.trace("Received metadata"),this.listener.onReceiveMetadata(W)},onReceiveMessage:(W)=>{this.trace("Received message"),this.listener.onReceiveMessage(W)},onReceiveStatus:(W)=>{if(this.trace("Received status"),W.rstCode===vP.constants.NGHTTP2_REFUSED_STREAM)this.outputStatus(W,"REFUSED");else this.outputStatus(W,"PROCESSED")}}),this.childStartTime=new Date}catch(W){this.trace("Failed to start call on picked subchannel "+J+" with error "+W.message),this.outputStatus({code:P4.Status.INTERNAL,details:"Failed to start HTTP/2 stream with error "+W.message,metadata:new L4.Metadata},"NOT_STARTED");return}if((G=Q.onCallStarted)===null||G===void 0||G.call(Q),this.onCallEnded=Q.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()},(U)=>{let{code:G,details:W}=(0,wJ.restrictControlPlaneStatusCode)(typeof U.code==="number"?U.code:P4.Status.UNKNOWN,`Getting metadata from plugin failed with error: ${U.message}`);this.outputStatus({code:G,details:W,metadata:new L4.Metadata},"PROCESSED")});break;case Q8.PickResultType.DROP:let{code:T,details:K}=(0,wJ.restrictControlPlaneStatusCode)(Q.status.code,Q.status.details);setImmediate(()=>{this.outputStatus({code:T,details:K,metadata:Q.status.metadata},"DROP")});break;case Q8.PickResultType.TRANSIENT_FAILURE:if(this.metadata.getOptions().waitForReady)this.channel.queueCallForPick(this);else{let{code:U,details:G}=(0,wJ.restrictControlPlaneStatusCode)(Q.status.code,Q.status.details);setImmediate(()=>{this.outputStatus({code:U,details:G,metadata:Q.status.metadata},"PROCESSED")})}break;case Q8.PickResultType.QUEUE:this.channel.queueCallForPick(this)}}cancelWithStatus($,Y){var X;this.trace("cancelWithStatus code: "+$+' details: "'+Y+'"'),(X=this.child)===null||X===void 0||X.cancelWithStatus($,Y),this.outputStatus({code:$,details:Y,metadata:new L4.Metadata},"PROCESSED")}getPeer(){var $,Y;return(Y=($=this.child)===null||$===void 0?void 0:$.getPeer())!==null&&Y!==void 0?Y:this.channel.getTarget()}start($,Y){this.trace("start called"),this.listener=Y,this.metadata=$,this.doPick()}sendMessageWithContext($,Y){if(this.trace("write() called with message of length "+Y.length),this.child)this.child.sendMessageWithContext($,Y);else this.pendingMessage={context:$,message:Y}}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}}zE.LoadBalancingCall=HE});var PE=M((IE)=>{Object.defineProperty(IE,"__esModule",{value:!0});IE.ResolvingCall=void 0;var hP=I9(),XY=i(),QY=bY(),ME=P0(),_P=Z0(),gP=a6(),fP="resolving_call";class BE{constructor($,Y,X,Q,J){if(this.channel=$,this.method=Y,this.filterStackFactory=Q,this.callNumber=J,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=hP.CallCredentials.createEmpty(),this.deadline=X.deadline,this.host=X.host,X.parentCall){if(X.flags&XY.Propagate.CANCELLATION)X.parentCall.on("cancelled",()=>{this.cancelWithStatus(XY.Status.CANCELLED,"Cancelled by parent call")});if(X.flags&XY.Propagate.DEADLINE)this.trace("Propagating deadline from parent: "+X.parentCall.getDeadline()),this.deadline=(0,QY.minDeadline)(this.deadline,X.parentCall.getDeadline())}this.trace("Created"),this.runDeadlineTimer()}trace($){_P.trace(XY.LogVerbosity.DEBUG,fP,"["+this.callNumber+"] "+$)}runDeadlineTimer(){clearTimeout(this.deadlineTimer),this.deadlineStartTime=new Date,this.trace("Deadline: "+(0,QY.deadlineToString)(this.deadline));let $=(0,QY.getRelativeTimeout)(this.deadline);if($!==1/0){this.trace("Deadline will be reached in "+$+"ms");let Y=()=>{if(!this.deadlineStartTime){this.cancelWithStatus(XY.Status.DEADLINE_EXCEEDED,"Deadline exceeded");return}let X=[],Q=new Date;if(X.push(`Deadline exceeded after ${(0,QY.formatDateDifference)(this.deadlineStartTime,Q)}`),this.configReceivedTime){if(this.configReceivedTime>this.deadlineStartTime)X.push(`name resolution: ${(0,QY.formatDateDifference)(this.deadlineStartTime,this.configReceivedTime)}`);if(this.childStartTime){if(this.childStartTime>this.configReceivedTime)X.push(`metadata filters: ${(0,QY.formatDateDifference)(this.configReceivedTime,this.childStartTime)}`)}else X.push("waiting for metadata filters")}else X.push("waiting for name resolution");if(this.child)X.push(...this.child.getDeadlineInfo());this.cancelWithStatus(XY.Status.DEADLINE_EXCEEDED,X.join(","))};if($<=0)process.nextTick(Y);else this.deadlineTimer=setTimeout(Y,$)}}outputStatus($){if(!this.ended){if(this.ended=!0,!this.filterStack)this.filterStack=this.filterStackFactory.createFilter();clearTimeout(this.deadlineTimer);let Y=this.filterStack.receiveTrailers($);this.trace("ended with status: code="+Y.code+' details="'+Y.details+'"'),this.statusWatchers.forEach((X)=>X(Y)),process.nextTick(()=>{var X;(X=this.listener)===null||X===void 0||X.onReceiveStatus(Y)})}}sendMessageOnChild($,Y){if(!this.child)throw Error("sendMessageonChild called with child not populated");let X=this.child;this.writeFilterPending=!0,this.filterStack.sendMessage(Promise.resolve({message:Y,flags:$.flags})).then((Q)=>{if(this.writeFilterPending=!1,X.sendMessageWithContext($,Q.message),this.pendingHalfClose)X.halfClose()},(Q)=>{this.cancelWithStatus(Q.code,Q.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 Y=$.config;if(Y.status!==XY.Status.OK){let{code:X,details:Q}=(0,gP.restrictControlPlaneStatusCode)(Y.status,"Failed to route call to method "+this.method);this.outputStatus({code:X,details:Q,metadata:new ME.Metadata});return}if(Y.methodConfig.timeout){let X=new Date;X.setSeconds(X.getSeconds()+Y.methodConfig.timeout.seconds),X.setMilliseconds(X.getMilliseconds()+Y.methodConfig.timeout.nanos/1e6),this.deadline=(0,QY.minDeadline)(this.deadline,X),this.runDeadlineTimer()}this.filterStackFactory.push(Y.dynamicFilterFactories),this.filterStack=this.filterStackFactory.createFilter(),this.filterStack.sendMetadata(Promise.resolve(this.metadata)).then((X)=>{if(this.child=this.channel.createRetryingCall(Y,this.method,this.host,this.credentials,this.deadline),this.trace("Created child ["+this.child.getCallNumber()+"]"),this.childStartTime=new Date,this.child.start(X,{onReceiveMetadata:(Q)=>{this.trace("Received metadata"),this.listener.onReceiveMetadata(this.filterStack.receiveMetadata(Q))},onReceiveMessage:(Q)=>{this.trace("Received message"),this.readFilterPending=!0,this.filterStack.receiveMessage(Q).then((J)=>{if(this.trace("Finished filtering received message"),this.readFilterPending=!1,this.listener.onReceiveMessage(J),this.pendingChildStatus)this.outputStatus(this.pendingChildStatus)},(J)=>{this.cancelWithStatus(J.code,J.details)})},onReceiveStatus:(Q)=>{if(this.trace("Received status"),this.readFilterPending)this.pendingChildStatus=Q;else this.outputStatus(Q)}}),this.readPending)this.child.startRead();if(this.pendingMessage)this.sendMessageOnChild(this.pendingMessage.context,this.pendingMessage.message);else if(this.pendingHalfClose)this.child.halfClose()},(X)=>{this.outputStatus(X)})}reportResolverError($){var Y;if((Y=this.metadata)===null||Y===void 0?void 0:Y.getOptions().waitForReady)this.channel.queueCallForConfig(this);else this.outputStatus($)}cancelWithStatus($,Y){var X;this.trace("cancelWithStatus code: "+$+' details: "'+Y+'"'),(X=this.child)===null||X===void 0||X.cancelWithStatus($,Y),this.outputStatus({code:$,details:Y,metadata:new ME.Metadata})}getPeer(){var $,Y;return(Y=($=this.child)===null||$===void 0?void 0:$.getPeer())!==null&&Y!==void 0?Y:this.channel.getTarget()}start($,Y){this.trace("start called"),this.metadata=$.clone(),this.listener=Y,this.getConfig()}sendMessageWithContext($,Y){if(this.trace("write() called with message of length "+Y.length),this.child)this.sendMessageOnChild($,Y);else this.pendingMessage={context:$,message:Y}}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}}IE.ResolvingCall=BE});var jE=M((CE)=>{Object.defineProperty(CE,"__esModule",{value:!0});CE.RetryingCall=CE.MessageBufferTracker=CE.RetryThrottler=void 0;var S4=i(),mP=bY(),bP=P0(),uP=Z0(),dP="retrying_call";class LE{constructor($,Y,X){if(this.maxTokens=$,this.tokenRatio=Y,X)this.tokens=X.tokens*($/X.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}}CE.RetryThrottler=LE;class SE{constructor($,Y){this.totalLimit=$,this.limitPerCall=Y,this.totalAllocated=0,this.allocatedPerCall=new Map}allocate($,Y){var X;let Q=(X=this.allocatedPerCall.get(Y))!==null&&X!==void 0?X:0;if(this.limitPerCall-Q<$||this.totalLimit-this.totalAllocated<$)return!1;return this.allocatedPerCall.set(Y,Q+$),this.totalAllocated+=$,!0}free($,Y){var X;if(this.totalAllocated<$)throw Error(`Invalid buffer allocation state: call ${Y} freed ${$} > total allocated ${this.totalAllocated}`);this.totalAllocated-=$;let Q=(X=this.allocatedPerCall.get(Y))!==null&&X!==void 0?X:0;if(Q<$)throw Error(`Invalid buffer allocation state: call ${Y} freed ${$} > allocated for call ${Q}`);this.allocatedPerCall.set(Y,Q-$)}freeAll($){var Y;let X=(Y=this.allocatedPerCall.get($))!==null&&Y!==void 0?Y:0;if(this.totalAllocated<X)throw Error(`Invalid buffer allocation state: call ${$} allocated ${X} > total allocated ${this.totalAllocated}`);this.totalAllocated-=X,this.allocatedPerCall.delete($)}}CE.MessageBufferTracker=SE;var CJ="grpc-previous-rpc-attempts",pP=5;class wE{constructor($,Y,X,Q,J,Z,T,K,U){var G;this.channel=$,this.callConfig=Y,this.methodName=X,this.host=Q,this.credentials=J,this.deadline=Z,this.callNumber=T,this.bufferTracker=K,this.retryThrottler=U,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 W=(G=$.getOptions()["grpc-node.retry_max_attempts_limit"])!==null&&G!==void 0?G:pP;if($.getOptions()["grpc.enable_retries"]===0)this.state="NO_RETRY",this.maxAttempts=1;else if(Y.methodConfig.retryPolicy){this.state="RETRY";let R=Y.methodConfig.retryPolicy;this.nextRetryBackoffSec=this.initialRetryBackoffSec=Number(R.initialBackoff.substring(0,R.initialBackoff.length-1)),this.maxAttempts=Math.min(R.maxAttempts,W)}else if(Y.methodConfig.hedgingPolicy)this.state="HEDGING",this.maxAttempts=Math.min(Y.methodConfig.hedgingPolicy.maxAttempts,W);else this.state="TRANSPARENT_ONLY",this.maxAttempts=1;this.startTime=new Date}getDeadlineInfo(){if(this.underlyingCalls.length===0)return[];let $=[],Y=this.underlyingCalls[this.underlyingCalls.length-1];if(this.underlyingCalls.length>1)$.push(`previous attempts: ${this.underlyingCalls.length-1}`);if(Y.startTime>this.startTime)$.push(`time to current attempt start: ${(0,mP.formatDateDifference)(this.startTime,Y.startTime)}`);return $.push(...Y.call.getDeadlineInfo()),$}getCallNumber(){return this.callNumber}trace($){uP.trace(S4.LogVerbosity.DEBUG,dP,"["+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 Y;(Y=this.listener)===null||Y===void 0||Y.onReceiveStatus({code:$.code,details:$.details,metadata:$.metadata})})}cancelWithStatus($,Y){this.trace("cancelWithStatus code: "+$+' details: "'+Y+'"'),this.reportStatus({code:$,details:Y,metadata:new bP.Metadata});for(let{call:X}of this.underlyingCalls)X.cancelWithStatus($,Y)}getPeer(){if(this.committedCallIndex!==null)return this.underlyingCalls[this.committedCallIndex].call.getPeer();else return"unknown"}getBufferEntry($){var Y;return(Y=this.writeBuffer[$-this.writeBufferOffset])!==null&&Y!==void 0?Y:{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 Y=this.writeBufferOffset;Y<$;Y++){let X=this.getBufferEntry(Y);if(X.allocated)this.bufferTracker.free(X.message.message.length,this.callNumber)}this.writeBuffer=this.writeBuffer.slice($-this.writeBufferOffset),this.writeBufferOffset=$}commitCall($){var Y,X;if(this.state==="COMMITTED")return;this.trace("Committing call ["+this.underlyingCalls[$].call.getCallNumber()+"] at index "+$),this.state="COMMITTED",(X=(Y=this.callConfig).onCommitted)===null||X===void 0||X.call(Y),this.committedCallIndex=$;for(let Q=0;Q<this.underlyingCalls.length;Q++){if(Q===$)continue;if(this.underlyingCalls[Q].state==="COMPLETED")continue;this.underlyingCalls[Q].state="COMPLETED",this.underlyingCalls[Q].call.cancelWithStatus(S4.Status.CANCELLED,"Discarded in favor of other hedged attempt")}this.clearSentMessages()}commitCallWithMostMessages(){if(this.state==="COMMITTED")return;let $=-1,Y=-1;for(let[X,Q]of this.underlyingCalls.entries())if(Q.state==="ACTIVE"&&Q.nextMessageToSend>$)$=Q.nextMessageToSend,Y=X;if(Y===-1)this.state="TRANSPARENT_ONLY";else this.commitCall(Y)}isStatusCodeInList($,Y){return $.some((X)=>{var Q;return X===Y||X.toString().toLowerCase()===((Q=S4.Status[Y])===null||Q===void 0?void 0:Q.toLowerCase())})}getNextRetryJitter(){return Math.random()*0.3999999999999999+0.8}getNextRetryBackoffMs(){var $;let Y=($=this.callConfig)===null||$===void 0?void 0:$.methodConfig.retryPolicy;if(!Y)return 0;let Q=this.getNextRetryJitter()*this.nextRetryBackoffSec*1000,J=Number(Y.maxBackoff.substring(0,Y.maxBackoff.length-1));return this.nextRetryBackoffSec=Math.min(this.nextRetryBackoffSec*Y.backoffMultiplier,J),Q}maybeRetryCall($,Y){if(this.state!=="RETRY"){Y(!1);return}if(this.attempts>=this.maxAttempts){Y(!1);return}let X;if($===null)X=this.getNextRetryBackoffMs();else if($<0){this.state="TRANSPARENT_ONLY",Y(!1);return}else X=$,this.nextRetryBackoffSec=this.initialRetryBackoffSec;setTimeout(()=>{var Q,J;if(this.state!=="RETRY"){Y(!1);return}if((J=(Q=this.retryThrottler)===null||Q===void 0?void 0:Q.canRetryCall())!==null&&J!==void 0?J:!0)Y(!0),this.attempts+=1,this.startNewAttempt();else this.trace("Retry attempt denied by throttling policy"),Y(!1)},X)}countActiveCalls(){let $=0;for(let Y of this.underlyingCalls)if((Y===null||Y===void 0?void 0:Y.state)==="ACTIVE")$+=1;return $}handleProcessedStatus($,Y,X){var Q,J,Z;switch(this.state){case"COMMITTED":case"NO_RETRY":case"TRANSPARENT_ONLY":this.commitCall(Y),this.reportStatus($);break;case"HEDGING":if(this.isStatusCodeInList((Q=this.callConfig.methodConfig.hedgingPolicy.nonFatalStatusCodes)!==null&&Q!==void 0?Q:[],$.code)){(J=this.retryThrottler)===null||J===void 0||J.addCallFailed();let T;if(X===null)T=0;else if(X<0){this.state="TRANSPARENT_ONLY",this.commitCall(Y),this.reportStatus($);return}else T=X;setTimeout(()=>{if(this.maybeStartHedgingAttempt(),this.countActiveCalls()===0)this.commitCall(Y),this.reportStatus($)},T)}else this.commitCall(Y),this.reportStatus($);break;case"RETRY":if(this.isStatusCodeInList(this.callConfig.methodConfig.retryPolicy.retryableStatusCodes,$.code))(Z=this.retryThrottler)===null||Z===void 0||Z.addCallFailed(),this.maybeRetryCall(X,(T)=>{if(!T)this.commitCall(Y),this.reportStatus($)});else this.commitCall(Y),this.reportStatus($);break}}getPushback($){let Y=$.get("grpc-retry-pushback-ms");if(Y.length===0)return null;try{return parseInt(Y[0])}catch(X){return-1}}handleChildStatus($,Y){var X;if(this.underlyingCalls[Y].state==="COMPLETED")return;if(this.trace("state="+this.state+" handling status with progress "+$.progress+" from child ["+this.underlyingCalls[Y].call.getCallNumber()+"] in state "+this.underlyingCalls[Y].state),this.underlyingCalls[Y].state="COMPLETED",$.code===S4.Status.OK){(X=this.retryThrottler)===null||X===void 0||X.addCallSucceeded(),this.commitCall(Y),this.reportStatus($);return}if(this.state==="NO_RETRY"){this.commitCall(Y),this.reportStatus($);return}if(this.state==="COMMITTED"){this.reportStatus($);return}let Q=this.getPushback($.metadata);switch($.progress){case"NOT_STARTED":this.startNewAttempt();break;case"REFUSED":if(this.transparentRetryUsed)this.handleProcessedStatus($,Y,Q);else this.transparentRetryUsed=!0,this.startNewAttempt();break;case"DROP":this.commitCall(Y),this.reportStatus($);break;case"PROCESSED":this.handleProcessedStatus($,Y,Q);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 $,Y,X;if(this.hedgingTimer)clearTimeout(this.hedgingTimer);if(this.state!=="HEDGING")return;if(!this.callConfig.methodConfig.hedgingPolicy)return;let Q=this.callConfig.methodConfig.hedgingPolicy;if(this.attempts>=this.maxAttempts)return;let J=($=Q.hedgingDelay)!==null&&$!==void 0?$:"0s",Z=Number(J.substring(0,J.length-1));this.hedgingTimer=setTimeout(()=>{this.maybeStartHedgingAttempt()},Z*1000),(X=(Y=this.hedgingTimer).unref)===null||X===void 0||X.call(Y)}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 Y=this.underlyingCalls.length;this.underlyingCalls.push({state:"ACTIVE",call:$,nextMessageToSend:0,startTime:new Date});let X=this.attempts-1,Q=this.initialMetadata.clone();if(X>0)Q.set(CJ,`${X}`);let J=!1;if($.start(Q,{onReceiveMetadata:(Z)=>{if(this.trace("Received metadata from child ["+$.getCallNumber()+"]"),this.commitCall(Y),J=!0,X>0)Z.set(CJ,`${X}`);if(this.underlyingCalls[Y].state==="ACTIVE")this.listener.onReceiveMetadata(Z)},onReceiveMessage:(Z)=>{if(this.trace("Received message from child ["+$.getCallNumber()+"]"),this.commitCall(Y),this.underlyingCalls[Y].state==="ACTIVE")this.listener.onReceiveMessage(Z)},onReceiveStatus:(Z)=>{if(this.trace("Received status from child ["+$.getCallNumber()+"]"),!J&&X>0)Z.metadata.set(CJ,`${X}`);this.handleChildStatus(Z,Y)}}),this.sendNextChildMessage(Y),this.readStarted)$.startRead()}start($,Y){this.trace("start called"),this.listener=Y,this.initialMetadata=$,this.attempts+=1,this.startNewAttempt(),this.maybeStartHedgingTimer()}handleChildWriteCompleted($,Y){var X,Q;(Q=(X=this.getBufferEntry(Y)).callback)===null||Q===void 0||Q.call(X),this.clearSentMessages();let J=this.underlyingCalls[$];J.nextMessageToSend+=1,this.sendNextChildMessage($)}sendNextChildMessage($){let Y=this.underlyingCalls[$];if(Y.state==="COMPLETED")return;let X=Y.nextMessageToSend;if(this.getBufferEntry(X)){let Q=this.getBufferEntry(X);switch(Q.entryType){case"MESSAGE":if(Y.call.sendMessageWithContext({callback:(Z)=>{this.handleChildWriteCompleted($,X)}},Q.message.message),this.getBufferEntry(X+1).entryType==="HALF_CLOSE")this.trace("Sending halfClose immediately after message to child ["+Y.call.getCallNumber()+"] - optimizing for unary/final message"),Y.nextMessageToSend+=1,Y.call.halfClose();break;case"HALF_CLOSE":Y.nextMessageToSend+=1,Y.call.halfClose();break;case"FREED":break}}}sendMessageWithContext($,Y){this.trace("write() called with message of length "+Y.length);let X={message:Y,flags:$.flags},Q=this.getNextBufferIndex(),J={entryType:"MESSAGE",message:X,allocated:this.bufferTracker.allocate(Y.length,this.callNumber)};if(this.writeBuffer.push(J),J.allocated){process.nextTick(()=>{var Z;(Z=$.callback)===null||Z===void 0||Z.call($)});for(let[Z,T]of this.underlyingCalls.entries())if(T.state==="ACTIVE"&&T.nextMessageToSend===Q)T.call.sendMessageWithContext({callback:(K)=>{this.handleChildWriteCompleted(Z,Q)}},Y)}else{if(this.commitCallWithMostMessages(),this.committedCallIndex===null)return;let Z=this.underlyingCalls[this.committedCallIndex];if(J.callback=$.callback,Z.state==="ACTIVE"&&Z.nextMessageToSend===Q)Z.call.sendMessageWithContext({callback:(T)=>{this.handleChildWriteCompleted(this.committedCallIndex,Q)}},Y)}}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 Y of this.underlyingCalls)if((Y===null||Y===void 0?void 0:Y.state)==="ACTIVE"){if(Y.nextMessageToSend===$||Y.nextMessageToSend===$-1)this.trace("Sending halfClose immediately to child ["+Y.call.getCallNumber()+"] - all messages already sent"),Y.nextMessageToSend+=1,Y.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}}CE.RetryingCall=wE});var J8=M((vE)=>{Object.defineProperty(vE,"__esModule",{value:!0});vE.BaseSubchannelWrapper=void 0;class xE{constructor($){this.child=$,this.healthy=!0,this.healthListeners=new Set,this.refcount=0,this.dataWatchers=new Set,$.addHealthStateWatcher((Y)=>{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()}}vE.BaseSubchannelWrapper=xE});var vJ=M((bE)=>{Object.defineProperty(bE,"__esModule",{value:!0});bE.InternalChannel=bE.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX=void 0;var lP=OY(),iP=qK(),rP=AE(),xJ=Y$(),oP=P0(),x$=i(),sP=z4(),aP=AJ(),hE=M1(),w4=Z0(),tP=IJ(),C4=c0(),D1=n0(),Z8=y$(),eP=NE(),$L=bY(),YL=PE(),yJ=F4(),XL=a6(),jJ=jE(),QL=J8(),JL=2147483647,ZL=1000,TL=1800000,y4=new Map,KL=16777216,UL=1048576;class _E extends QL.BaseSubchannelWrapper{constructor($,Y){super($);this.channel=Y,this.refCount=0,this.subchannelStateListener=(X,Q,J,Z)=>{Y.throttleKeepalive(Z)}}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 gE{pick($){return{pickResultType:xJ.PickResultType.DROP,status:{code:x$.Status.UNAVAILABLE,details:"Channel closed before call started",metadata:new oP.Metadata},subchannel:null,onCallStarted:null,onCallEnded:null}}}bE.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX="grpc.internal.no_subchannel";class fE{constructor($){this.target=$,this.trace=new Z8.ChannelzTrace,this.callTracker=new Z8.ChannelzCallTracker,this.childrenTracker=new Z8.ChannelzChildrenTracker,this.state=D1.ConnectivityState.IDLE}getChannelzInfoCallback(){return()=>{return{target:this.target,state:this.state,trace:this.trace,callTracker:this.callTracker,children:this.childrenTracker.getChildLists()}}}}class mE{constructor($,Y,X){var Q,J,Z,T,K,U;if(this.credentials=Y,this.options=X,this.connectivityState=D1.ConnectivityState.IDLE,this.currentPicker=new xJ.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(!(Y instanceof lP.ChannelCredentials))throw TypeError("Channel credentials must be a ChannelCredentials object");if(X){if(typeof X!=="object")throw TypeError("Channel options must be an object")}this.channelzInfoTracker=new fE($);let G=(0,C4.parseUri)($);if(G===null)throw Error(`Could not parse target name "${$}"`);let W=(0,hE.mapUriDefaultScheme)(G);if(W===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,Z8.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,hE.getDefaultAuthority)(W);let R=(0,tP.mapProxyName)(W,X);this.target=R.target,this.options=Object.assign({},this.options,R.extraOptions),this.subchannelPool=(0,rP.getSubchannelPool)(((Q=this.options["grpc.use_local_subchannel_pool"])!==null&&Q!==void 0?Q:0)===0),this.retryBufferTracker=new jJ.MessageBufferTracker((J=this.options["grpc.retry_buffer_size"])!==null&&J!==void 0?J:KL,(Z=this.options["grpc.per_rpc_retry_buffer_size"])!==null&&Z!==void 0?Z:UL),this.keepaliveTime=(T=this.options["grpc.keepalive_time_ms"])!==null&&T!==void 0?T:-1,this.idleTimeoutMs=Math.max((K=this.options["grpc.client_idle_timeout_ms"])!==null&&K!==void 0?K:TL,ZL);let V={createSubchannel:(H,z)=>{let D={};for(let[x,q]of Object.entries(z))if(!x.startsWith(bE.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX))D[x]=q;let B=this.subchannelPool.getOrCreateSubchannel(this.target,H,D,this.credentials);if(B.throttleKeepalive(this.keepaliveTime),this.channelzEnabled)this.channelzInfoTracker.trace.addTrace("CT_INFO","Created subchannel or used existing subchannel",B.getChannelzRef());return new _E(B,this)},updateState:(H,z)=>{this.currentPicker=z;let D=this.pickQueue.slice();if(this.pickQueue=[],D.length>0)this.callRefTimerUnref();for(let B of D)B.doPick();this.updateState(H)},requestReresolution:()=>{throw Error("Resolving load balancer should never call requestReresolution")},addChannelzChild:(H)=>{if(this.channelzEnabled)this.channelzInfoTracker.childrenTracker.refChild(H)},removeChannelzChild:(H)=>{if(this.channelzEnabled)this.channelzInfoTracker.childrenTracker.unrefChild(H)}};this.resolvingLoadBalancer=new iP.ResolvingLoadBalancer(this.target,V,this.options,(H,z)=>{var D;if(H.retryThrottling)y4.set(this.getTarget(),new jJ.RetryThrottler(H.retryThrottling.maxTokens,H.retryThrottling.tokenRatio,y4.get(this.getTarget())));else y4.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=z,this.currentResolutionError=null,process.nextTick(()=>{let B=this.configSelectionQueue;if(this.configSelectionQueue=[],B.length>0)this.callRefTimerUnref();for(let w of B)w.getConfig()})},(H)=>{if(this.channelzEnabled)this.channelzInfoTracker.trace.addTrace("CT_WARNING","Address resolution failed with code "+H.code+' and details "'+H.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,XL.restrictControlPlaneStatusCode)(H.code,H.details)),{metadata:H.metadata});let z=this.configSelectionQueue;if(this.configSelectionQueue=[],z.length>0)this.callRefTimerUnref();for(let D of z)D.reportResolverError(H)}),this.filterStackFactory=new sP.FilterStackFactory([new aP.CompressionFilterFactory(this,this.options)]),this.trace("Channel constructed with options "+JSON.stringify(X,void 0,2));let A=Error();if((0,w4.isTracerEnabled)("channel_stacktrace"))(0,w4.trace)(x$.LogVerbosity.DEBUG,"channel_stacktrace","("+this.channelzRef.id+`) Channel constructed
|
|
20
|
+
`+((U=A.stack)===null||U===void 0?void 0:U.substring(A.stack.indexOf(`
|
|
21
|
+
`)+1)));this.lastActivityTimestamp=new Date}trace($,Y){(0,w4.trace)(Y!==null&&Y!==void 0?Y:x$.LogVerbosity.DEBUG,"channel","("+this.channelzRef.id+") "+(0,C4.uriToString)(this.target)+" "+$)}callRefTimerRef(){var $,Y,X,Q;if(!this.callRefTimer)this.callRefTimer=setInterval(()=>{},JL);if(!((Y=($=this.callRefTimer).hasRef)===null||Y===void 0?void 0:Y.call($)))this.trace("callRefTimer.ref | configSelectionQueue.length="+this.configSelectionQueue.length+" pickQueue.length="+this.pickQueue.length),(Q=(X=this.callRefTimer).ref)===null||Q===void 0||Q.call(X)}callRefTimerUnref(){var $,Y,X;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),(X=(Y=this.callRefTimer)===null||Y===void 0?void 0:Y.unref)===null||X===void 0||X.call(Y)}removeConnectivityStateWatcher($){let Y=this.connectivityStateWatchers.findIndex((X)=>X===$);if(Y>=0)this.connectivityStateWatchers.splice(Y,1)}updateState($){if((0,w4.trace)(x$.LogVerbosity.DEBUG,"connectivity_state","("+this.channelzRef.id+") "+(0,C4.uriToString)(this.target)+" "+D1.ConnectivityState[this.connectivityState]+" -> "+D1.ConnectivityState[$]),this.channelzEnabled)this.channelzInfoTracker.trace.addTrace("CT_INFO","Connectivity state change to "+D1.ConnectivityState[$]);this.connectivityState=$,this.channelzInfoTracker.state=$;let Y=this.connectivityStateWatchers.slice();for(let X of Y)if($!==X.currentState){if(X.timer)clearTimeout(X.timer);this.removeConnectivityStateWatcher(X),X.callback()}if($!==D1.ConnectivityState.TRANSIENT_FAILURE)this.currentResolutionError=null}throttleKeepalive($){if($>this.keepaliveTime){this.keepaliveTime=$;for(let Y of this.wrappedSubchannels)Y.throttleKeepalive($)}}addWrappedSubchannel($){this.wrappedSubchannels.add($)}removeWrappedSubchannel($){this.wrappedSubchannels.delete($)}doPick($,Y){return this.currentPicker.pick({metadata:$,extraPickInfo:Y})}queueCallForPick($){this.pickQueue.push($),this.callRefTimerRef()}getConfig($,Y){if(this.connectivityState!==D1.ConnectivityState.SHUTDOWN)this.resolvingLoadBalancer.exitIdle();if(this.configSelector)return{type:"SUCCESS",config:this.configSelector.invoke($,Y,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(D1.ConnectivityState.IDLE),this.currentPicker=new xJ.QueuePicker(this.resolvingLoadBalancer),this.idleTimer)clearTimeout(this.idleTimer),this.idleTimer=null;if(this.callRefTimer)clearInterval(this.callRefTimer),this.callRefTimer=null}startIdleTimeout($){var Y,X;this.idleTimer=setTimeout(()=>{if(this.callCount>0){this.startIdleTimeout(this.idleTimeoutMs);return}let J=new Date().valueOf()-this.lastActivityTimestamp.valueOf();if(J>=this.idleTimeoutMs)this.trace("Idle timer triggered after "+this.idleTimeoutMs+"ms of inactivity"),this.enterIdle();else this.startIdleTimeout(this.idleTimeoutMs-J)},$),(X=(Y=this.idleTimer).unref)===null||X===void 0||X.call(Y)}maybeStartIdleTimer(){if(this.connectivityState!==D1.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===x$.Status.OK)this.channelzInfoTracker.callTracker.addCallSucceeded();else this.channelzInfoTracker.callTracker.addCallFailed();this.callCount-=1,this.lastActivityTimestamp=new Date,this.maybeStartIdleTimer()}createLoadBalancingCall($,Y,X,Q,J){let Z=(0,yJ.getNextCallNumber)();return this.trace("createLoadBalancingCall ["+Z+'] method="'+Y+'"'),new eP.LoadBalancingCall(this,$,Y,X,Q,J,Z)}createRetryingCall($,Y,X,Q,J){let Z=(0,yJ.getNextCallNumber)();return this.trace("createRetryingCall ["+Z+'] method="'+Y+'"'),new jJ.RetryingCall(this,$,Y,X,Q,J,Z,this.retryBufferTracker,y4.get(this.getTarget()))}createResolvingCall($,Y,X,Q,J){let Z=(0,yJ.getNextCallNumber)();this.trace("createResolvingCall ["+Z+'] method="'+$+'", deadline='+(0,$L.deadlineToString)(Y));let T={deadline:Y,flags:J!==null&&J!==void 0?J:x$.Propagate.DEFAULTS,host:X!==null&&X!==void 0?X:this.defaultAuthority,parentCall:Q},K=new YL.ResolvingCall(this,$,T,this.filterStackFactory.clone(),Z);return this.onCallStart(),K.addStatusWatcher((U)=>{this.onCallEnd(U)}),K}close(){var $;this.resolvingLoadBalancer.destroy(),this.updateState(D1.ConnectivityState.SHUTDOWN),this.currentPicker=new gE;for(let Y of this.configSelectionQueue)Y.cancelWithStatus(x$.Status.UNAVAILABLE,"Channel closed before call started");this.configSelectionQueue=[];for(let Y of this.pickQueue)Y.cancelWithStatus(x$.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,Z8.unregisterChannelzRef)(this.channelzRef);this.subchannelPool.unrefUnusedSubchannels(),($=this.configSelector)===null||$===void 0||$.unref(),this.configSelector=null}getTarget(){return(0,C4.uriToString)(this.target)}getConnectivityState($){let Y=this.connectivityState;if($)this.resolvingLoadBalancer.exitIdle(),this.lastActivityTimestamp=new Date,this.maybeStartIdleTimer();return Y}watchConnectivityState($,Y,X){if(this.connectivityState===D1.ConnectivityState.SHUTDOWN)throw Error("Channel has been shut down");let Q=null;if(Y!==1/0){let Z=Y instanceof Date?Y:new Date(Y),T=new Date;if(Y===-1/0||Z<=T){process.nextTick(X,Error("Deadline passed without connectivity state change"));return}Q=setTimeout(()=>{this.removeConnectivityStateWatcher(J),X(Error("Deadline passed without connectivity state change"))},Z.getTime()-T.getTime())}let J={currentState:$,callback:X,timer:Q};this.connectivityStateWatchers.push(J)}getChannelzRef(){return this.channelzRef}createCall($,Y,X,Q,J){if(typeof $!=="string")throw TypeError("Channel#createCall: method must be a string");if(!(typeof Y==="number"||Y instanceof Date))throw TypeError("Channel#createCall: deadline must be a number or Date");if(this.connectivityState===D1.ConnectivityState.SHUTDOWN)throw Error("Channel has been shut down");return this.createResolvingCall($,Y,X,Q,J)}getOptions(){return this.options}}bE.InternalChannel=mE});var t5=M((cE)=>{Object.defineProperty(cE,"__esModule",{value:!0});cE.ChannelImplementation=void 0;var GL=OY(),WL=vJ();class pE{constructor($,Y,X){if(typeof $!=="string")throw TypeError("Channel target must be a string");if(!(Y instanceof GL.ChannelCredentials))throw TypeError("Channel credentials must be a ChannelCredentials object");if(X){if(typeof X!=="object")throw TypeError("Channel options must be an object")}this.internalChannel=new WL.InternalChannel($,Y,X)}close(){this.internalChannel.close()}getTarget(){return this.internalChannel.getTarget()}getConnectivityState($){return this.internalChannel.getConnectivityState($)}watchConnectivityState($,Y,X){this.internalChannel.watchConnectivityState($,Y,X)}getChannelzRef(){return this.internalChannel.getChannelzRef()}createCall($,Y,X,Q,J){if(typeof $!=="string")throw TypeError("Channel#createCall: method must be a string");if(!(typeof Y==="number"||Y instanceof Date))throw TypeError("Channel#createCall: deadline must be a number or Date");return this.internalChannel.createCall($,Y,X,Q,J)}}cE.ChannelImplementation=pE});var eE=M((aE)=>{Object.defineProperty(aE,"__esModule",{value:!0});aE.ServerDuplexStreamImpl=aE.ServerWritableStreamImpl=aE.ServerReadableStreamImpl=aE.ServerUnaryCallImpl=void 0;aE.serverErrorToStatus=_J;var RL=s("events"),kJ=s("stream"),hJ=i(),lE=P0();function _J($,Y){var X;let Q={code:hJ.Status.UNKNOWN,details:"message"in $?$.message:"Unknown Error",metadata:(X=Y!==null&&Y!==void 0?Y:$.metadata)!==null&&X!==void 0?X:null};if("code"in $&&typeof $.code==="number"&&Number.isInteger($.code)){if(Q.code=$.code,"details"in $&&typeof $.details==="string")Q.details=$.details}return Q}class iE extends RL.EventEmitter{constructor($,Y,X,Q){super();this.path=$,this.call=Y,this.metadata=X,this.request=Q,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()}}aE.ServerUnaryCallImpl=iE;class rE extends kJ.Readable{constructor($,Y,X){super({objectMode:!0});this.path=$,this.call=Y,this.metadata=X,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()}}aE.ServerReadableStreamImpl=rE;class oE extends kJ.Writable{constructor($,Y,X,Q){super({objectMode:!0});this.path=$,this.call=Y,this.metadata=X,this.request=Q,this.pendingStatus={code:hJ.Status.OK,details:"OK"},this.cancelled=!1,this.trailingMetadata=new lE.Metadata,this.on("error",(J)=>{this.pendingStatus=_J(J),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($,Y,X){this.call.sendMessage($,X)}_final($){var Y;$(null),this.call.sendStatus(Object.assign(Object.assign({},this.pendingStatus),{metadata:(Y=this.pendingStatus.metadata)!==null&&Y!==void 0?Y:this.trailingMetadata}))}end($){if($)this.trailingMetadata=$;return super.end()}}aE.ServerWritableStreamImpl=oE;class sE extends kJ.Duplex{constructor($,Y,X){super({objectMode:!0});this.path=$,this.call=Y,this.metadata=X,this.pendingStatus={code:hJ.Status.OK,details:"OK"},this.cancelled=!1,this.trailingMetadata=new lE.Metadata,this.on("error",(Q)=>{this.pendingStatus=_J(Q),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($,Y,X){this.call.sendMessage($,X)}_final($){var Y;$(null),this.call.sendStatus(Object.assign(Object.assign({},this.pendingStatus),{metadata:(Y=this.pendingStatus.metadata)!==null&&Y!==void 0?Y:this.trailingMetadata}))}end($){if($)this.trailingMetadata=$;return super.end()}}aE.ServerDuplexStreamImpl=sE});var j4=M(($3)=>{Object.defineProperty($3,"__esModule",{value:!0});$3.ServerCredentials=void 0;$3.createCertificateProviderServerCredentials=FL;$3.createServerCredentialsWithInterceptors=HL;var gJ=g5();class nY{constructor($,Y){this.serverConstructorOptions=$,this.watchers=new Set,this.latestContextOptions=null,this.latestContextOptions=Y!==null&&Y!==void 0?Y:null}_addWatcher($){this.watchers.add($)}_removeWatcher($){this.watchers.delete($)}getWatcherCount(){return this.watchers.size}updateSecureContextOptions($){this.latestContextOptions=$;for(let Y of this.watchers)Y(this.latestContextOptions)}_isSecure(){return this.serverConstructorOptions!==null}_getSecureContextOptions(){return this.latestContextOptions}_getConstructorOptions(){return this.serverConstructorOptions}_getInterceptors(){return[]}static createInsecure(){return new fJ}static createSsl($,Y,X=!1){var Q;if($!==null&&!Buffer.isBuffer($))throw TypeError("rootCerts must be null or a Buffer");if(!Array.isArray(Y))throw TypeError("keyCertPairs must be an array");if(typeof X!=="boolean")throw TypeError("checkClientCertificate must be a boolean");let J=[],Z=[];for(let T=0;T<Y.length;T++){let K=Y[T];if(K===null||typeof K!=="object")throw TypeError(`keyCertPair[${T}] must be an object`);if(!Buffer.isBuffer(K.private_key))throw TypeError(`keyCertPair[${T}].private_key must be a Buffer`);if(!Buffer.isBuffer(K.cert_chain))throw TypeError(`keyCertPair[${T}].cert_chain must be a Buffer`);J.push(K.cert_chain),Z.push(K.private_key)}return new mJ({requestCert:X,ciphers:gJ.CIPHER_SUITES},{ca:(Q=$!==null&&$!==void 0?$:(0,gJ.getDefaultRootsData)())!==null&&Q!==void 0?Q:void 0,cert:J,key:Z})}}$3.ServerCredentials=nY;class fJ extends nY{constructor(){super(null)}_getSettings(){return null}_equals($){return $ instanceof fJ}}class mJ extends nY{constructor($,Y){super($,Y);this.options=Object.assign(Object.assign({},$),Y)}_equals($){if(this===$)return!0;if(!($ instanceof mJ))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 Y=0;Y<this.options.cert.length;Y++){let X=this.options.cert[Y],Q=$.options.cert[Y];if(Buffer.isBuffer(X)&&Buffer.isBuffer(Q)){if(!X.equals(Q))return!1}else if(X!==Q)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 Y=0;Y<this.options.key.length;Y++){let X=this.options.key[Y],Q=$.options.key[Y];if(Buffer.isBuffer(X)&&Buffer.isBuffer(Q)){if(!X.equals(Q))return!1}else if(X!==Q)return!1}}else if(this.options.key!==$.options.key)return!1;if(this.options.requestCert!==$.options.requestCert)return!1;return!0}}class bJ extends nY{constructor($,Y,X){super({requestCert:Y!==null,rejectUnauthorized:X,ciphers:gJ.CIPHER_SUITES});this.identityCertificateProvider=$,this.caCertificateProvider=Y,this.requireClientCertificate=X,this.latestCaUpdate=null,this.latestIdentityUpdate=null,this.caCertificateUpdateListener=this.handleCaCertificateUpdate.bind(this),this.identityCertificateUpdateListener=this.handleIdentityCertitificateUpdate.bind(this)}_addWatcher($){var Y;if(this.getWatcherCount()===0)(Y=this.caCertificateProvider)===null||Y===void 0||Y.addCaCertificateListener(this.caCertificateUpdateListener),this.identityCertificateProvider.addIdentityCertificateListener(this.identityCertificateUpdateListener);super._addWatcher($)}_removeWatcher($){var Y;if(super._removeWatcher($),this.getWatcherCount()===0)(Y=this.caCertificateProvider)===null||Y===void 0||Y.removeCaCertificateListener(this.caCertificateUpdateListener),this.identityCertificateProvider.removeIdentityCertificateListener(this.identityCertificateUpdateListener)}_equals($){if(this===$)return!0;if(!($ instanceof bJ))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 FL($,Y,X){return new bJ($,Y,X)}class uJ extends nY{constructor($,Y){super({});this.childCredentials=$,this.interceptors=Y}_isSecure(){return this.childCredentials._isSecure()}_equals($){if(!($ instanceof uJ))return!1;if(!this.childCredentials._equals($.childCredentials))return!1;if(this.interceptors.length!==$.interceptors.length)return!1;for(let Y=0;Y<this.interceptors.length;Y++)if(this.interceptors[Y]!==$.interceptors[Y])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 HL($,Y){return new uJ($,Y)}});var T8=M((X3)=>{Object.defineProperty(X3,"__esModule",{value:!0});X3.durationMessageToDuration=NL;X3.msToDuration=ML;X3.durationToMs=BL;X3.isDuration=IL;X3.isDurationMessage=OL;X3.parseDuration=LL;X3.durationToString=SL;function NL($){return{seconds:Number.parseInt($.seconds),nanos:$.nanos}}function ML($){return{seconds:$/1000|0,nanos:$%1000*1e6|0}}function BL($){return $.seconds*1000+$.nanos/1e6|0}function IL($){return typeof $.seconds==="number"&&typeof $.nanos==="number"}function OL($){return typeof $.seconds==="string"&&typeof $.nanos==="number"}var PL=/^(\d+)(?:\.(\d+))?s$/;function LL($){let Y=$.match(PL);if(!Y)return null;return{seconds:Number.parseInt(Y[1],10),nanos:Y[2]?Number.parseInt(Y[2].padEnd(9,"0"),10):0}}function SL($){if($.nanos===0)return`${$.seconds}s`;let Y;if($.nanos%1e6===0)Y=1e6;else if($.nanos%1000===0)Y=1000;else Y=1;return`${$.seconds}.${$.nanos/Y}s`}});var v4=M((V3)=>{var __dirname="/Users/beatrix/dev/clinee/sdk-wip/node_modules/.bun/@grpc+grpc-js@1.14.3/node_modules/@grpc/grpc-js/build/src";Object.defineProperty(V3,"__esModule",{value:!0});V3.OrcaOobMetricsSubchannelWrapper=V3.GRPC_METRICS_HEADER=V3.ServerMetricRecorder=V3.PerRequestMetricRecorder=void 0;V3.createOrcaClient=U3;V3.createMetricsReader=uL;var hL=h9(),dJ=T8(),_L=OY(),gL=J8(),Q3=i(),fL=PY(),mL=n0(),J3=null;function x4(){if(J3)return J3;let $=i6().loadSync,Y=$("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,hL.loadPackageDefinition)(Y)}class T3{constructor(){this.message={}}recordRequestCostMetric($,Y){if(!this.message.request_cost)this.message.request_cost={};this.message.request_cost[$]=Y}recordUtilizationMetric($,Y){if(!this.message.utilization)this.message.utilization={};this.message.utilization[$]=Y}recordNamedMetric($,Y){if(!this.message.named_metrics)this.message.named_metrics={};this.message.named_metrics[$]=Y}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 x4().xds.data.orca.v3.OrcaLoadReport.serialize(this.message)}}V3.PerRequestMetricRecorder=T3;var bL=30000;class K3{constructor(){this.message={},this.serviceImplementation={StreamCoreMetrics:($)=>{let Y=$.request.report_interval?(0,dJ.durationToMs)((0,dJ.durationMessageToDuration)($.request.report_interval)):bL,X=setInterval(()=>{$.write(this.message)},Y);$.on("cancelled",()=>{clearInterval(X)})}}}putUtilizationMetric($,Y){if(!this.message.utilization)this.message.utilization={};this.message.utilization[$]=Y}setAllUtilizationMetrics($){this.message.utilization=Object.assign({},$)}deleteUtilizationMetric($){var Y;(Y=this.message.utilization)===null||Y===void 0||delete Y[$]}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 Y=x4().xds.service.orca.v3.OpenRcaService.service;$.addService(Y,this.serviceImplementation)}}V3.ServerMetricRecorder=K3;function U3($){return new(x4()).xds.service.orca.v3.OpenRcaService("unused",_L.ChannelCredentials.createInsecure(),{channelOverride:$})}V3.GRPC_METRICS_HEADER="endpoint-load-metrics-bin";var Z3="grpc_orca_load_report";function uL($,Y){return(X,Q,J)=>{let Z=J.getOpaque(Z3);if(Z)$(Z);else{let T=J.get(V3.GRPC_METRICS_HEADER);if(T.length>0)Z=x4().xds.data.orca.v3.OrcaLoadReport.deserialize(T[0]),$(Z),J.setOpaque(Z3,Z)}if(Y)Y(X,Q,J)}}var G3="orca_oob_metrics";class W3{constructor($,Y){this.metricsListener=$,this.intervalMs=Y,this.dataProducer=null}setSubchannel($){let Y=$.getOrCreateDataProducer(G3,dL);this.dataProducer=Y,Y.addDataWatcher(this)}destroy(){var $;($=this.dataProducer)===null||$===void 0||$.removeDataWatcher(this)}getInterval(){return this.intervalMs}onMetricsUpdate($){this.metricsListener($)}}class R3{constructor($){this.subchannel=$,this.dataWatchers=new Set,this.orcaSupported=!0,this.metricsCall=null,this.currentInterval=1/0,this.backoffTimer=new fL.BackoffTimeout(()=>this.updateMetricsSubscription()),this.subchannelStateListener=()=>this.updateMetricsSubscription();let Y=$.getChannel();this.client=U3(Y),$.addConnectivityStateListener(this.subchannelStateListener)}addDataWatcher($){this.dataWatchers.add($),this.updateMetricsSubscription()}removeDataWatcher($){var Y;if(this.dataWatchers.delete($),this.dataWatchers.size===0)this.subchannel.removeDataProducer(G3),(Y=this.metricsCall)===null||Y===void 0||Y.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()!==mL.ConnectivityState.READY)return;let Y=Math.min(...Array.from(this.dataWatchers).map((X)=>X.getInterval()));if(!this.metricsCall||Y!==this.currentInterval){($=this.metricsCall)===null||$===void 0||$.cancel(),this.currentInterval=Y;let X=this.client.streamCoreMetrics({report_interval:(0,dJ.msToDuration)(Y)});this.metricsCall=X,X.on("data",(Q)=>{this.dataWatchers.forEach((J)=>{J.onMetricsUpdate(Q)})}),X.on("error",(Q)=>{if(this.metricsCall=null,Q.code===Q3.Status.UNIMPLEMENTED){this.orcaSupported=!1;return}if(Q.code===Q3.Status.CANCELLED)return;this.backoffTimer.runOnce()})}}}class E3 extends gL.BaseSubchannelWrapper{constructor($,Y,X){super($);this.addDataWatcher(new W3(Y,X))}getWrappedSubchannel(){return this.child}}V3.OrcaOobMetricsSubchannelWrapper=E3;function dL($){return new R3($)}});var lJ=M((C3)=>{Object.defineProperty(C3,"__esModule",{value:!0});C3.BaseServerInterceptingCall=C3.ServerInterceptingCall=C3.ResponderBuilder=C3.ServerListenerBuilder=void 0;C3.isInterceptingServerListener=oL;C3.getServerInterceptingCall=$S;var _4=P0(),s0=i(),lY=s("http2"),F3=q9(),H3=s("zlib"),iL=OJ(),B3=Z0(),rL=s("tls"),z3=v4(),I3="server_call";function JY($){B3.trace(s0.LogVerbosity.DEBUG,I3,$)}class O3{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}}}C3.ServerListenerBuilder=O3;function oL($){return $.onReceiveMetadata!==void 0&&$.onReceiveMetadata.length===1}class P3{constructor($,Y){this.listener=$,this.nextListener=Y,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($,(Y)=>{if(this.processingMetadata=!1,this.cancelled)return;this.nextListener.onReceiveMetadata(Y),this.processPendingMessage(),this.processPendingHalfClose()})}onReceiveMessage($){if(this.cancelled)return;this.processingMessage=!0,this.listener.onReceiveMessage($,(Y)=>{if(this.processingMessage=!1,this.cancelled)return;if(this.processingMetadata)this.pendingMessage=Y,this.hasPendingMessage=!0;else this.nextListener.onReceiveMessage(Y),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 L3{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}}}C3.ResponderBuilder=L3;var k4={onReceiveMetadata:($,Y)=>{Y($)},onReceiveMessage:($,Y)=>{Y($)},onReceiveHalfClose:($)=>{$()},onCancel:()=>{}},h4={start:($)=>{$()},sendMetadata:($,Y)=>{Y($)},sendMessage:($,Y)=>{Y($)},sendStatus:($,Y)=>{Y($)}};class S3{constructor($,Y){var X,Q,J,Z;this.nextCall=$,this.processingMetadata=!1,this.sentMetadata=!1,this.processingMessage=!1,this.pendingMessage=null,this.pendingMessageCallback=null,this.pendingStatus=null,this.responder={start:(X=Y===null||Y===void 0?void 0:Y.start)!==null&&X!==void 0?X:h4.start,sendMetadata:(Q=Y===null||Y===void 0?void 0:Y.sendMetadata)!==null&&Q!==void 0?Q:h4.sendMetadata,sendMessage:(J=Y===null||Y===void 0?void 0:Y.sendMessage)!==null&&J!==void 0?J:h4.sendMessage,sendStatus:(Z=Y===null||Y===void 0?void 0:Y.sendStatus)!==null&&Z!==void 0?Z:h4.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((Y)=>{var X,Q,J,Z;let T={onReceiveMetadata:(X=Y===null||Y===void 0?void 0:Y.onReceiveMetadata)!==null&&X!==void 0?X:k4.onReceiveMetadata,onReceiveMessage:(Q=Y===null||Y===void 0?void 0:Y.onReceiveMessage)!==null&&Q!==void 0?Q:k4.onReceiveMessage,onReceiveHalfClose:(J=Y===null||Y===void 0?void 0:Y.onReceiveHalfClose)!==null&&J!==void 0?J:k4.onReceiveHalfClose,onCancel:(Z=Y===null||Y===void 0?void 0:Y.onCancel)!==null&&Z!==void 0?Z:k4.onCancel},K=new P3(T,$);this.nextCall.start(K)})}sendMetadata($){this.processingMetadata=!0,this.sentMetadata=!0,this.responder.sendMetadata($,(Y)=>{this.processingMetadata=!1,this.nextCall.sendMetadata(Y),this.processPendingMessage(),this.processPendingStatus()})}sendMessage($,Y){if(this.processingMessage=!0,!this.sentMetadata)this.sendMetadata(new _4.Metadata);this.responder.sendMessage($,(X)=>{if(this.processingMessage=!1,this.processingMetadata)this.pendingMessage=X,this.pendingMessageCallback=Y;else this.nextCall.sendMessage(X,Y)})}sendStatus($){this.responder.sendStatus($,(Y)=>{if(this.processingMetadata||this.processingMessage)this.pendingStatus=Y;else this.nextCall.sendStatus(Y)})}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()}}C3.ServerInterceptingCall=S3;var w3="grpc-accept-encoding",cJ="grpc-encoding",q3="grpc-message",N3="grpc-status",pJ="grpc-timeout",sL=/(\d{1,8})\s*([HMSmun])/,aL={H:3600000,M:60000,S:1000,m:1,u:0.001,n:0.000001},tL={[w3]:"identity,deflate,gzip",[cJ]:"identity"},M3={[lY.constants.HTTP2_HEADER_STATUS]:lY.constants.HTTP_STATUS_OK,[lY.constants.HTTP2_HEADER_CONTENT_TYPE]:"application/grpc+proto"},eL={waitForTrailers:!0};class nJ{constructor($,Y,X,Q,J){var Z,T;if(this.stream=$,this.callEventTracker=X,this.handler=Q,this.listener=null,this.deadlineTimer=null,this.deadline=1/0,this.maxSendMessageSize=s0.DEFAULT_MAX_SEND_MESSAGE_LENGTH,this.maxReceiveMessageSize=s0.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 z3.PerRequestMetricRecorder,this.stream.once("error",(R)=>{}),this.stream.once("close",()=>{var R;if(JY("Request to method "+((R=this.handler)===null||R===void 0?void 0:R.path)+" stream closed with rstCode "+this.stream.rstCode),this.callEventTracker&&!this.streamEnded)this.streamEnded=!0,this.callEventTracker.onStreamEnd(!1),this.callEventTracker.onCallEnd({code:s0.Status.CANCELLED,details:"Stream closed before sending status",metadata:null});this.notifyOnCancel()}),this.stream.on("data",(R)=>{this.handleDataFrame(R)}),this.stream.pause(),this.stream.on("end",()=>{this.handleEndEvent()}),"grpc.max_send_message_length"in J)this.maxSendMessageSize=J["grpc.max_send_message_length"];if("grpc.max_receive_message_length"in J)this.maxReceiveMessageSize=J["grpc.max_receive_message_length"];this.host=(Z=Y[":authority"])!==null&&Z!==void 0?Z:Y.host,this.decoder=new iL.StreamDecoder(this.maxReceiveMessageSize);let K=_4.Metadata.fromHttp2Headers(Y);if(B3.isTracerEnabled(I3))JY("Request to "+this.handler.path+" received headers "+JSON.stringify(K.toJSON()));let U=K.get(pJ);if(U.length>0)this.handleTimeoutHeader(U[0]);let G=K.get(cJ);if(G.length>0)this.incomingEncoding=G[0];K.remove(pJ),K.remove(cJ),K.remove(w3),K.remove(lY.constants.HTTP2_HEADER_ACCEPT_ENCODING),K.remove(lY.constants.HTTP2_HEADER_TE),K.remove(lY.constants.HTTP2_HEADER_CONTENT_TYPE),this.metadata=K;let W=(T=$.session)===null||T===void 0?void 0:T.socket;this.connectionInfo={localAddress:W===null||W===void 0?void 0:W.localAddress,localPort:W===null||W===void 0?void 0:W.localPort,remoteAddress:W===null||W===void 0?void 0:W.remoteAddress,remotePort:W===null||W===void 0?void 0:W.remotePort},this.shouldSendMetrics=!!J["grpc.server_call_metric_recording"]}handleTimeoutHeader($){let Y=$.toString().match(sL);if(Y===null){let J={code:s0.Status.INTERNAL,details:`Invalid ${pJ} value "${$}"`,metadata:null};process.nextTick(()=>{this.sendStatus(J)});return}let X=+Y[1]*aL[Y[2]]|0,Q=new Date;this.deadline=Q.setMilliseconds(Q.getMilliseconds()+X),this.deadlineTimer=setTimeout(()=>{let J={code:s0.Status.DEADLINE_EXCEEDED,details:"Deadline exceeded",metadata:null};this.sendStatus(J)},X)}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 _4.Metadata)}serializeMessage($){let Y=this.handler.serialize($),X=Y.byteLength,Q=Buffer.allocUnsafe(X+5);return Q.writeUInt8(0,0),Q.writeUInt32BE(X,1),Y.copy(Q,5),Q}decompressMessage($,Y){let X=$.subarray(5);if(Y==="identity")return X;else if(Y==="deflate"||Y==="gzip"){let Q;if(Y==="deflate")Q=H3.createInflate();else Q=H3.createGunzip();return new Promise((J,Z)=>{let T=0,K=[];Q.on("data",(U)=>{if(K.push(U),T+=U.byteLength,this.maxReceiveMessageSize!==-1&&T>this.maxReceiveMessageSize)Q.destroy(),Z({code:s0.Status.RESOURCE_EXHAUSTED,details:`Received message that decompresses to a size larger than ${this.maxReceiveMessageSize}`})}),Q.on("end",()=>{J(Buffer.concat(K))}),Q.write(X),Q.end()})}else return Promise.reject({code:s0.Status.UNIMPLEMENTED,details:`Received message compressed with unsupported encoding "${Y}"`})}async decompressAndMaybePush($){if($.type!=="COMPRESSED")throw Error(`Invalid queue entry type: ${$.type}`);let X=$.compressedMessage.readUInt8(0)===1?this.incomingEncoding:"identity",Q;try{Q=await this.decompressMessage($.compressedMessage,X)}catch(J){this.sendStatus(J);return}try{$.parsedMessage=this.handler.deserialize(Q)}catch(J){this.sendStatus({code:s0.Status.INTERNAL,details:`Error deserializing request: ${J.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 Y;if(this.checkCancelled())return;JY("Request to "+this.handler.path+" received data frame of size "+$.length);let X;try{X=this.decoder.write($)}catch(Q){this.sendStatus({code:s0.Status.RESOURCE_EXHAUSTED,details:Q.message});return}for(let Q of X){this.stream.pause();let J={type:"COMPRESSED",compressedMessage:Q,parsedMessage:null};this.readQueue.push(J),this.decompressAndMaybePush(J),(Y=this.callEventTracker)===null||Y===void 0||Y.addMessageReceived()}}handleEndEvent(){this.readQueue.push({type:"HALF_CLOSE",compressedMessage:null,parsedMessage:null}),this.receivedHalfClose=!0,this.maybePushNextMessage()}start($){if(JY("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 Y=$?$.toHttp2Headers():null,X=Object.assign(Object.assign(Object.assign({},M3),tL),Y);this.stream.respond(X,eL)}sendMessage($,Y){if(this.checkCancelled())return;let X;try{X=this.serializeMessage($)}catch(Q){this.sendStatus({code:s0.Status.INTERNAL,details:`Error serializing response: ${(0,F3.getErrorMessage)(Q)}`,metadata:null});return}if(this.maxSendMessageSize!==-1&&X.length-5>this.maxSendMessageSize){this.sendStatus({code:s0.Status.RESOURCE_EXHAUSTED,details:`Sent message larger than max (${X.length} vs. ${this.maxSendMessageSize})`,metadata:null});return}this.maybeSendMetadata(),JY("Request to "+this.handler.path+" sent data frame of size "+X.length),this.stream.write(X,(Q)=>{var J;if(Q){this.sendStatus({code:s0.Status.INTERNAL,details:`Error writing message: ${(0,F3.getErrorMessage)(Q)}`,metadata:null});return}(J=this.callEventTracker)===null||J===void 0||J.addMessageSent(),Y()})}sendStatus($){var Y,X,Q;if(this.checkCancelled())return;JY("Request to method "+((Y=this.handler)===null||Y===void 0?void 0:Y.path)+" ended with status code: "+s0.Status[$.code]+" details: "+$.details);let J=(Q=(X=$.metadata)===null||X===void 0?void 0:X.clone())!==null&&Q!==void 0?Q:new _4.Metadata;if(this.shouldSendMetrics)J.set(z3.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 Z=Object.assign({[N3]:$.code,[q3]:encodeURI($.details)},J.toHttp2Headers());this.stream.sendTrailers(Z),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 Z=Object.assign(Object.assign({[N3]:$.code,[q3]:encodeURI($.details)},M3),J.toHttp2Headers());this.stream.respond(Z,{endStream:!0}),this.notifyOnCancel()}}startRead(){if(JY("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 Y=($=this.stream.session)===null||$===void 0?void 0:$.socket;if(Y===null||Y===void 0?void 0:Y.remoteAddress)if(Y.remotePort)return`${Y.remoteAddress}:${Y.remotePort}`;else return Y.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 rL.TLSSocket){let Y=this.stream.session.socket.getPeerCertificate();return{transportSecurityType:"ssl",sslPeerCertificate:Y.raw?Y:void 0}}else return{}}getConnectionInfo(){return this.connectionInfo}getMetricsRecorder(){return this.metricsRecorder}}C3.BaseServerInterceptingCall=nJ;function $S($,Y,X,Q,J,Z){let T={path:J.path,requestStream:J.type==="clientStream"||J.type==="bidi",responseStream:J.type==="serverStream"||J.type==="bidi",requestDeserialize:J.deserialize,responseSerialize:J.serialize},K=new nJ(Y,X,Q,J,Z);return $.reduce((U,G)=>{return G(T,U)},K)}});var g3=M((k$)=>{var TS=k$&&k$.__runInitializers||function($,Y,X){var Q=arguments.length>2;for(var J=0;J<Y.length;J++)X=Q?Y[J].call($,X):Y[J].call($);return Q?X:void 0},KS=k$&&k$.__esDecorate||function($,Y,X,Q,J,Z){function T(B){if(B!==void 0&&typeof B!=="function")throw TypeError("Function expected");return B}var K=Q.kind,U=K==="getter"?"get":K==="setter"?"set":"value",G=!Y&&$?Q.static?$:$.prototype:null,W=Y||(G?Object.getOwnPropertyDescriptor(G,Q.name):{}),R,V=!1;for(var A=X.length-1;A>=0;A--){var H={};for(var z in Q)H[z]=z==="access"?{}:Q[z];for(var z in Q.access)H.access[z]=Q.access[z];H.addInitializer=function(B){if(V)throw TypeError("Cannot add initializers after decoration has completed");Z.push(T(B||null))};var D=(0,X[A])(K==="accessor"?{get:W.get,set:W.set}:W[U],H);if(K==="accessor"){if(D===void 0)continue;if(D===null||typeof D!=="object")throw TypeError("Object expected");if(R=T(D.get))W.get=R;if(R=T(D.set))W.set=R;if(R=T(D.init))J.unshift(R)}else if(R=T(D))if(K==="field")J.unshift(R);else W[U]=R}if(G)Object.defineProperty(G,Q.name,W);V=!0};Object.defineProperty(k$,"__esModule",{value:!0});k$.Server=void 0;var a0=s("http2"),US=s("util"),F0=i(),oY=eE(),iJ=j4(),j3=M1(),rY=Z0(),v$=r0(),C1=c0(),M0=y$(),x3=lJ(),iY=2147483647,rJ=2147483647,GS=20000,v3=2147483647,{HTTP2_HEADER_PATH:k3}=a0.constants,WS="server",h3=Buffer.from("max_age");function _3($){rY.trace(F0.LogVerbosity.DEBUG,"server_call",$)}function RS(){}function ES($){return function(Y,X){return US.deprecate(Y,$)}}function oJ($){return{code:F0.Status.UNIMPLEMENTED,details:`The server does not implement the method ${$}`}}function VS($,Y){let X=oJ(Y);switch($){case"unary":return(Q,J)=>{J(X,null)};case"clientStream":return(Q,J)=>{J(X,null)};case"serverStream":return(Q)=>{Q.emit("error",X)};case"bidi":return(Q)=>{Q.emit("error",X)};default:throw Error(`Invalid handlerType ${$}`)}}var AS=(()=>{var $;let Y=[],X;return $=class{constructor(J){var Z,T,K,U,G,W;if(this.boundPorts=(TS(this,Y),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=J!==null&&J!==void 0?J:{},this.options["grpc.enable_channelz"]===0)this.channelzEnabled=!1,this.channelzTrace=new M0.ChannelzTraceStub,this.callTracker=new M0.ChannelzCallTrackerStub,this.listenerChildrenTracker=new M0.ChannelzChildrenTrackerStub,this.sessionChildrenTracker=new M0.ChannelzChildrenTrackerStub;else this.channelzTrace=new M0.ChannelzTrace,this.callTracker=new M0.ChannelzCallTracker,this.listenerChildrenTracker=new M0.ChannelzChildrenTracker,this.sessionChildrenTracker=new M0.ChannelzChildrenTracker;if(this.channelzRef=(0,M0.registerChannelzServer)("server",()=>this.getChannelzInfo(),this.channelzEnabled),this.channelzTrace.addTrace("CT_INFO","Server created"),this.maxConnectionAgeMs=(Z=this.options["grpc.max_connection_age_ms"])!==null&&Z!==void 0?Z:iY,this.maxConnectionAgeGraceMs=(T=this.options["grpc.max_connection_age_grace_ms"])!==null&&T!==void 0?T:iY,this.keepaliveTimeMs=(K=this.options["grpc.keepalive_time_ms"])!==null&&K!==void 0?K:rJ,this.keepaliveTimeoutMs=(U=this.options["grpc.keepalive_timeout_ms"])!==null&&U!==void 0?U:GS,this.sessionIdleTimeout=(G=this.options["grpc.max_connection_idle_ms"])!==null&&G!==void 0?G:v3,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=(W=this.options.interceptors)!==null&&W!==void 0?W:[],this.trace("Server constructed")}getChannelzInfo(){return{trace:this.channelzTrace,callTracker:this.callTracker,listenerChildren:this.listenerChildrenTracker.getChildLists(),sessionChildren:this.sessionChildrenTracker.getChildLists()}}getChannelzSessionInfo(J){var Z,T,K;let U=this.sessions.get(J),G=J.socket,W=G.remoteAddress?(0,v$.stringToSubchannelAddress)(G.remoteAddress,G.remotePort):null,R=G.localAddress?(0,v$.stringToSubchannelAddress)(G.localAddress,G.localPort):null,V;if(J.encrypted){let H=G,z=H.getCipher(),D=H.getCertificate(),B=H.getPeerCertificate();V={cipherSuiteStandardName:(Z=z.standardName)!==null&&Z!==void 0?Z:null,cipherSuiteOtherName:z.standardName?null:z.name,localCertificate:D&&"raw"in D?D.raw:null,remoteCertificate:B&&"raw"in B?B.raw:null}}else V=null;return{remoteAddress:W,localAddress:R,security:V,remoteName:null,streamsStarted:U.streamTracker.callsStarted,streamsSucceeded:U.streamTracker.callsSucceeded,streamsFailed:U.streamTracker.callsFailed,messagesSent:U.messagesSent,messagesReceived:U.messagesReceived,keepAlivesSent:U.keepAlivesSent,lastLocalStreamCreatedTimestamp:null,lastRemoteStreamCreatedTimestamp:U.streamTracker.lastCallStartedTimestamp,lastMessageSentTimestamp:U.lastMessageSentTimestamp,lastMessageReceivedTimestamp:U.lastMessageReceivedTimestamp,localFlowControlWindow:(T=J.state.localWindowSize)!==null&&T!==void 0?T:null,remoteFlowControlWindow:(K=J.state.remoteWindowSize)!==null&&K!==void 0?K:null}}trace(J){rY.trace(F0.LogVerbosity.DEBUG,WS,"("+this.channelzRef.id+") "+J)}keepaliveTrace(J){rY.trace(F0.LogVerbosity.DEBUG,"keepalive","("+this.channelzRef.id+") "+J)}addProtoService(){throw Error("Not implemented. Use addService() instead")}addService(J,Z){if(J===null||typeof J!=="object"||Z===null||typeof Z!=="object")throw Error("addService() requires two objects as arguments");let T=Object.keys(J);if(T.length===0)throw Error("Cannot add an empty service to a server");T.forEach((K)=>{let U=J[K],G;if(U.requestStream)if(U.responseStream)G="bidi";else G="clientStream";else if(U.responseStream)G="serverStream";else G="unary";let W=Z[K],R;if(W===void 0&&typeof U.originalName==="string")W=Z[U.originalName];if(W!==void 0)R=W.bind(Z);else R=VS(G,K);if(this.register(U.path,R,U.responseSerialize,U.requestDeserialize,G)===!1)throw Error(`Method handler for ${U.path} already provided.`)})}removeService(J){if(J===null||typeof J!=="object")throw Error("removeService() requires object as argument");Object.keys(J).forEach((T)=>{let K=J[T];this.unregister(K.path)})}bind(J,Z){throw Error("Not implemented. Use bindAsync() instead")}experimentalRegisterListenerToChannelz(J){return(0,M0.registerChannelzSocket)((0,v$.subchannelAddressToString)(J),()=>{return{localAddress:J,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(J){(0,M0.unregisterChannelzRef)(J)}createHttp2Server(J){let Z;if(J._isSecure()){let T=J._getConstructorOptions(),K=J._getSecureContextOptions(),U=Object.assign(Object.assign(Object.assign(Object.assign({},this.commonServerOptions),T),K),{enableTrace:this.options["grpc-node.tls_enable_trace"]===1}),G=K!==null;this.trace("Initial credentials valid: "+G),Z=a0.createSecureServer(U),Z.prependListener("connection",(R)=>{if(!G)this.trace("Dropped connection from "+JSON.stringify(R.address())+" due to unloaded credentials"),R.destroy()}),Z.on("secureConnection",(R)=>{R.on("error",(V)=>{this.trace("An incoming TLS connection closed with error: "+V.message)})});let W=(R)=>{if(R){let V=Z;try{V.setSecureContext(R)}catch(A){rY.log(F0.LogVerbosity.ERROR,"Failed to set secure context with error "+A.message),R=null}}G=R!==null,this.trace("Post-update credentials valid: "+G)};J._addWatcher(W),Z.on("close",()=>{J._removeWatcher(W)})}else Z=a0.createServer(this.commonServerOptions);return Z.setTimeout(0,RS),this._setupHandlers(Z,J._getInterceptors()),Z}bindOneAddress(J,Z){this.trace("Attempting to bind "+(0,v$.subchannelAddressToString)(J));let T=this.createHttp2Server(Z.credentials);return new Promise((K,U)=>{let G=(W)=>{this.trace("Failed to bind "+(0,v$.subchannelAddressToString)(J)+" with error "+W.message),K({port:"port"in J?J.port:1,error:W.message})};T.once("error",G),T.listen(J,()=>{let W=T.address(),R;if(typeof W==="string")R={path:W};else R={host:W.address,port:W.port};let V=this.experimentalRegisterListenerToChannelz(R);this.listenerChildrenTracker.refChild(V),this.http2Servers.set(T,{channelzRef:V,sessions:new Set,ownsChannelzRef:!0}),Z.listeningServers.add(T),this.trace("Successfully bound "+(0,v$.subchannelAddressToString)(R)),K({port:"port"in R?R.port:1}),T.removeListener("error",G)})})}async bindManyPorts(J,Z){if(J.length===0)return{count:0,port:0,errors:[]};if((0,v$.isTcpSubchannelAddress)(J[0])&&J[0].port===0){let T=await this.bindOneAddress(J[0],Z);if(T.error){let K=await this.bindManyPorts(J.slice(1),Z);return Object.assign(Object.assign({},K),{errors:[T.error,...K.errors]})}else{let K=J.slice(1).map((W)=>(0,v$.isTcpSubchannelAddress)(W)?{host:W.host,port:T.port}:W),U=await Promise.all(K.map((W)=>this.bindOneAddress(W,Z))),G=[T,...U];return{count:G.filter((W)=>W.error===void 0).length,port:T.port,errors:G.filter((W)=>W.error).map((W)=>W.error)}}}else{let T=await Promise.all(J.map((K)=>this.bindOneAddress(K,Z)));return{count:T.filter((K)=>K.error===void 0).length,port:T[0].port,errors:T.filter((K)=>K.error).map((K)=>K.error)}}}async bindAddressList(J,Z){let T=await this.bindManyPorts(J,Z);if(T.count>0){if(T.count<J.length)rY.log(F0.LogVerbosity.INFO,`WARNING Only ${T.count} addresses added out of total ${J.length} resolved`);return T.port}else{let K=`No address added out of total ${J.length} resolved`;throw rY.log(F0.LogVerbosity.ERROR,K),Error(`${K} errors: [${T.errors.join(",")}]`)}}resolvePort(J){return new Promise((Z,T)=>{let K=!1,U=(W,R,V,A)=>{if(K)return!0;if(K=!0,!W.ok)return T(Error(W.error.details)),!0;let H=[].concat(...W.value.map((z)=>z.addresses));if(H.length===0)return T(Error(`No addresses resolved for port ${J}`)),!0;return Z(H),!0};(0,j3.createResolver)(J,U,this.options).updateResolution()})}async bindPort(J,Z){let T=await this.resolvePort(J);if(Z.cancelled)throw this.completeUnbind(Z),Error("bindAsync operation cancelled by unbind call");let K=await this.bindAddressList(T,Z);if(Z.cancelled)throw this.completeUnbind(Z),Error("bindAsync operation cancelled by unbind call");return K}normalizePort(J){let Z=(0,C1.parseUri)(J);if(Z===null)throw Error(`Could not parse port "${J}"`);let T=(0,j3.mapUriDefaultScheme)(Z);if(T===null)throw Error(`Could not get a default scheme for port "${J}"`);return T}bindAsync(J,Z,T){if(this.shutdown)throw Error("bindAsync called after shutdown");if(typeof J!=="string")throw TypeError("port must be a string");if(Z===null||!(Z instanceof iJ.ServerCredentials))throw TypeError("creds must be a ServerCredentials object");if(typeof T!=="function")throw TypeError("callback must be a function");this.trace("bindAsync port="+J);let K=this.normalizePort(J),U=(V,A)=>{process.nextTick(()=>T(V,A))},G=this.boundPorts.get((0,C1.uriToString)(K));if(G){if(!Z._equals(G.credentials)){U(Error(`${J} already bound with incompatible credentials`),0);return}if(G.cancelled=!1,G.completionPromise)G.completionPromise.then((V)=>T(null,V),(V)=>T(V,0));else U(null,G.portNumber);return}G={mapKey:(0,C1.uriToString)(K),originalUri:K,completionPromise:null,cancelled:!1,portNumber:0,credentials:Z,listeningServers:new Set};let W=(0,C1.splitHostPort)(K.path),R=this.bindPort(K,G);if(G.completionPromise=R,(W===null||W===void 0?void 0:W.port)===0)R.then((V)=>{let A={scheme:K.scheme,authority:K.authority,path:(0,C1.combineHostPort)({host:W.host,port:V})};G.mapKey=(0,C1.uriToString)(A),G.completionPromise=null,G.portNumber=V,this.boundPorts.set(G.mapKey,G),T(null,V)},(V)=>{T(V,0)});else this.boundPorts.set(G.mapKey,G),R.then((V)=>{G.completionPromise=null,G.portNumber=V,T(null,V)},(V)=>{T(V,0)})}registerInjectorToChannelz(){return(0,M0.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(J,Z,T=!1){if(J===null||!(J instanceof iJ.ServerCredentials))throw TypeError("creds must be a ServerCredentials object");if(this.channelzEnabled)this.listenerChildrenTracker.refChild(Z);let K=this.createHttp2Server(J),U=new Set;return this.http2Servers.set(K,{channelzRef:Z,sessions:U,ownsChannelzRef:T}),{injectConnection:(G)=>{K.emit("connection",G)},drain:(G)=>{var W,R;for(let V of U)this.closeSession(V);(R=(W=setTimeout(()=>{for(let V of U)V.destroy(a0.constants.NGHTTP2_CANCEL)},G)).unref)===null||R===void 0||R.call(W)},destroy:()=>{this.closeServer(K);for(let G of U)this.closeSession(G)}}}createConnectionInjector(J){if(J===null||!(J instanceof iJ.ServerCredentials))throw TypeError("creds must be a ServerCredentials object");let Z=this.registerInjectorToChannelz();return this.experimentalCreateConnectionInjectorWithChannelzRef(J,Z,!0)}closeServer(J,Z){this.trace("Closing server with address "+JSON.stringify(J.address()));let T=this.http2Servers.get(J);J.close(()=>{if(T&&T.ownsChannelzRef)this.listenerChildrenTracker.unrefChild(T.channelzRef),(0,M0.unregisterChannelzRef)(T.channelzRef);this.http2Servers.delete(J),Z===null||Z===void 0||Z()})}closeSession(J,Z){var T;this.trace("Closing session initiated by "+((T=J.socket)===null||T===void 0?void 0:T.remoteAddress));let K=this.sessions.get(J),U=()=>{if(K)this.sessionChildrenTracker.unrefChild(K.ref),(0,M0.unregisterChannelzRef)(K.ref);Z===null||Z===void 0||Z()};if(J.closed)queueMicrotask(U);else J.close(U)}completeUnbind(J){for(let Z of J.listeningServers){let T=this.http2Servers.get(Z);if(this.closeServer(Z,()=>{J.listeningServers.delete(Z)}),T)for(let K of T.sessions)this.closeSession(K)}this.boundPorts.delete(J.mapKey)}unbind(J){this.trace("unbind port="+J);let Z=this.normalizePort(J),T=(0,C1.splitHostPort)(Z.path);if((T===null||T===void 0?void 0:T.port)===0)throw Error("Cannot unbind port 0");let K=this.boundPorts.get((0,C1.uriToString)(Z));if(K)if(this.trace("unbinding "+K.mapKey+" originally bound as "+(0,C1.uriToString)(K.originalUri)),K.completionPromise)K.cancelled=!0;else this.completeUnbind(K)}drain(J,Z){var T,K;this.trace("drain port="+J+" graceTimeMs="+Z);let U=this.normalizePort(J),G=(0,C1.splitHostPort)(U.path);if((G===null||G===void 0?void 0:G.port)===0)throw Error("Cannot drain port 0");let W=this.boundPorts.get((0,C1.uriToString)(U));if(!W)return;let R=new Set;for(let V of W.listeningServers){let A=this.http2Servers.get(V);if(A)for(let H of A.sessions)R.add(H),this.closeSession(H,()=>{R.delete(H)})}(K=(T=setTimeout(()=>{for(let V of R)V.destroy(a0.constants.NGHTTP2_CANCEL)},Z)).unref)===null||K===void 0||K.call(T)}forceShutdown(){for(let J of this.boundPorts.values())J.cancelled=!0;this.boundPorts.clear();for(let J of this.http2Servers.keys())this.closeServer(J);this.sessions.forEach((J,Z)=>{this.closeSession(Z),Z.destroy(a0.constants.NGHTTP2_CANCEL)}),this.sessions.clear(),(0,M0.unregisterChannelzRef)(this.channelzRef),this.shutdown=!0}register(J,Z,T,K,U){if(this.handlers.has(J))return!1;return this.handlers.set(J,{func:Z,serialize:T,deserialize:K,type:U,path:J}),!0}unregister(J){return this.handlers.delete(J)}start(){if(this.http2Servers.size===0||[...this.http2Servers.keys()].every((J)=>!J.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(J){var Z;let T=(G)=>{(0,M0.unregisterChannelzRef)(this.channelzRef),J(G)},K=0;function U(){if(K--,K===0)T()}this.shutdown=!0;for(let[G,W]of this.http2Servers.entries()){K++;let R=W.channelzRef.name;this.trace("Waiting for server "+R+" to close"),this.closeServer(G,()=>{this.trace("Server "+R+" finished closing"),U()});for(let V of W.sessions.keys()){K++;let A=(Z=V.socket)===null||Z===void 0?void 0:Z.remoteAddress;this.trace("Waiting for session "+A+" to close"),this.closeSession(V,()=>{this.trace("Session "+A+" finished closing"),U()})}}if(K===0)T()}addHttp2Port(){throw Error("Not yet implemented")}getChannelzRef(){return this.channelzRef}_verifyContentType(J,Z){let T=Z[a0.constants.HTTP2_HEADER_CONTENT_TYPE];if(typeof T!=="string"||!T.startsWith("application/grpc"))return J.respond({[a0.constants.HTTP2_HEADER_STATUS]:a0.constants.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE},{endStream:!0}),!1;return!0}_retrieveHandler(J){_3("Received call to method "+J+" at address "+this.serverAddressString);let Z=this.handlers.get(J);if(Z===void 0)return _3("No handler registered for method "+J+". Sending UNIMPLEMENTED status."),null;return Z}_respondWithError(J,Z,T=null){var K,U;let G=Object.assign({"grpc-status":(K=J.code)!==null&&K!==void 0?K:F0.Status.INTERNAL,"grpc-message":J.details,[a0.constants.HTTP2_HEADER_STATUS]:a0.constants.HTTP_STATUS_OK,[a0.constants.HTTP2_HEADER_CONTENT_TYPE]:"application/grpc+proto"},(U=J.metadata)===null||U===void 0?void 0:U.toHttp2Headers());Z.respond(G,{endStream:!0}),this.callTracker.addCallFailed(),T===null||T===void 0||T.streamTracker.addCallFailed()}_channelzHandler(J,Z,T){this.onStreamOpened(Z);let K=this.sessions.get(Z.session);if(this.callTracker.addCallStarted(),K===null||K===void 0||K.streamTracker.addCallStarted(),!this._verifyContentType(Z,T)){this.callTracker.addCallFailed(),K===null||K===void 0||K.streamTracker.addCallFailed();return}let U=T[k3],G=this._retrieveHandler(U);if(!G){this._respondWithError(oJ(U),Z,K);return}let W={addMessageSent:()=>{if(K)K.messagesSent+=1,K.lastMessageSentTimestamp=new Date},addMessageReceived:()=>{if(K)K.messagesReceived+=1,K.lastMessageReceivedTimestamp=new Date},onCallEnd:(V)=>{if(V.code===F0.Status.OK)this.callTracker.addCallSucceeded();else this.callTracker.addCallFailed()},onStreamEnd:(V)=>{if(K)if(V)K.streamTracker.addCallSucceeded();else K.streamTracker.addCallFailed()}},R=(0,x3.getServerInterceptingCall)([...J,...this.interceptors],Z,T,W,G,this.options);if(!this._runHandlerForCall(R,G))this.callTracker.addCallFailed(),K===null||K===void 0||K.streamTracker.addCallFailed(),R.sendStatus({code:F0.Status.INTERNAL,details:`Unknown handler type: ${G.type}`})}_streamHandler(J,Z,T){if(this.onStreamOpened(Z),this._verifyContentType(Z,T)!==!0)return;let K=T[k3],U=this._retrieveHandler(K);if(!U){this._respondWithError(oJ(K),Z,null);return}let G=(0,x3.getServerInterceptingCall)([...J,...this.interceptors],Z,T,null,U,this.options);if(!this._runHandlerForCall(G,U))G.sendStatus({code:F0.Status.INTERNAL,details:`Unknown handler type: ${U.type}`})}_runHandlerForCall(J,Z){let{type:T}=Z;if(T==="unary")DS(J,Z);else if(T==="clientStream")FS(J,Z);else if(T==="serverStream")HS(J,Z);else if(T==="bidi")zS(J,Z);else return!1;return!0}_setupHandlers(J,Z){if(J===null)return;let T=J.address(),K="null";if(T)if(typeof T==="string")K=T;else K=T.address+":"+T.port;this.serverAddressString=K;let U=this.channelzEnabled?this._channelzHandler:this._streamHandler,G=this.channelzEnabled?this._channelzSessionHandler(J):this._sessionHandler(J);J.on("stream",U.bind(this,Z)),J.on("session",G)}_sessionHandler(J){return(Z)=>{var T,K;(T=this.http2Servers.get(J))===null||T===void 0||T.sessions.add(Z);let U=null,G=null,W=null,R=!1,V=this.enableIdleTimeout(Z);if(this.maxConnectionAgeMs!==iY){let B=this.maxConnectionAgeMs/10,w=Math.random()*B*2-B;U=setTimeout(()=>{var x,q;R=!0,this.trace("Connection dropped by max connection age: "+((x=Z.socket)===null||x===void 0?void 0:x.remoteAddress));try{Z.goaway(a0.constants.NGHTTP2_NO_ERROR,2147483647,h3)}catch(_){Z.destroy();return}if(Z.close(),this.maxConnectionAgeGraceMs!==iY)G=setTimeout(()=>{Z.destroy()},this.maxConnectionAgeGraceMs),(q=G.unref)===null||q===void 0||q.call(G)},this.maxConnectionAgeMs+w),(K=U.unref)===null||K===void 0||K.call(U)}let A=()=>{if(W)clearTimeout(W),W=null},H=()=>{return!Z.destroyed&&this.keepaliveTimeMs<rJ&&this.keepaliveTimeMs>0},z,D=()=>{var B;if(!H())return;this.keepaliveTrace("Starting keepalive timer for "+this.keepaliveTimeMs+"ms"),W=setTimeout(()=>{A(),z()},this.keepaliveTimeMs),(B=W.unref)===null||B===void 0||B.call(W)};z=()=>{var B;if(!H())return;this.keepaliveTrace("Sending ping with timeout "+this.keepaliveTimeoutMs+"ms");let w="";try{if(!Z.ping((q,_,C)=>{if(A(),q)this.keepaliveTrace("Ping failed with error: "+q.message),R=!0,Z.destroy();else this.keepaliveTrace("Received ping response"),D()}))w="Ping returned false"}catch(x){w=(x instanceof Error?x.message:"")||"Unknown error"}if(w){this.keepaliveTrace("Ping send failed: "+w),this.trace("Connection dropped due to ping send error: "+w),R=!0,Z.destroy();return}W=setTimeout(()=>{A(),this.keepaliveTrace("Ping timeout passed without response"),this.trace("Connection dropped by keepalive timeout"),R=!0,Z.destroy()},this.keepaliveTimeoutMs),(B=W.unref)===null||B===void 0||B.call(W)},D(),Z.on("close",()=>{var B,w;if(!R)this.trace(`Connection dropped by client ${(B=Z.socket)===null||B===void 0?void 0:B.remoteAddress}`);if(U)clearTimeout(U);if(G)clearTimeout(G);if(A(),V!==null)clearTimeout(V.timeout),this.sessionIdleTimeouts.delete(Z);(w=this.http2Servers.get(J))===null||w===void 0||w.sessions.delete(Z)})}}_channelzSessionHandler(J){return(Z)=>{var T,K,U,G;let W=(0,M0.registerChannelzSocket)((K=(T=Z.socket)===null||T===void 0?void 0:T.remoteAddress)!==null&&K!==void 0?K:"unknown",this.getChannelzSessionInfo.bind(this,Z),this.channelzEnabled),R={ref:W,streamTracker:new M0.ChannelzCallTracker,messagesSent:0,messagesReceived:0,keepAlivesSent:0,lastMessageSentTimestamp:null,lastMessageReceivedTimestamp:null};(U=this.http2Servers.get(J))===null||U===void 0||U.sessions.add(Z),this.sessions.set(Z,R);let V=`${Z.socket.remoteAddress}:${Z.socket.remotePort}`;this.channelzTrace.addTrace("CT_INFO","Connection established by client "+V),this.trace("Connection established by client "+V),this.sessionChildrenTracker.refChild(W);let A=null,H=null,z=null,D=!1,B=this.enableIdleTimeout(Z);if(this.maxConnectionAgeMs!==iY){let C=this.maxConnectionAgeMs/10,k=Math.random()*C*2-C;A=setTimeout(()=>{var f;D=!0,this.channelzTrace.addTrace("CT_INFO","Connection dropped by max connection age from "+V);try{Z.goaway(a0.constants.NGHTTP2_NO_ERROR,2147483647,h3)}catch(y){Z.destroy();return}if(Z.close(),this.maxConnectionAgeGraceMs!==iY)H=setTimeout(()=>{Z.destroy()},this.maxConnectionAgeGraceMs),(f=H.unref)===null||f===void 0||f.call(H)},this.maxConnectionAgeMs+k),(G=A.unref)===null||G===void 0||G.call(A)}let w=()=>{if(z)clearTimeout(z),z=null},x=()=>{return!Z.destroyed&&this.keepaliveTimeMs<rJ&&this.keepaliveTimeMs>0},q,_=()=>{var C;if(!x())return;this.keepaliveTrace("Starting keepalive timer for "+this.keepaliveTimeMs+"ms"),z=setTimeout(()=>{w(),q()},this.keepaliveTimeMs),(C=z.unref)===null||C===void 0||C.call(z)};q=()=>{var C;if(!x())return;this.keepaliveTrace("Sending ping with timeout "+this.keepaliveTimeoutMs+"ms");let k="";try{if(!Z.ping((y,j,N)=>{if(w(),y)this.keepaliveTrace("Ping failed with error: "+y.message),this.channelzTrace.addTrace("CT_INFO","Connection dropped due to error of a ping frame "+y.message+" return in "+j),D=!0,Z.destroy();else this.keepaliveTrace("Received ping response"),_()}))k="Ping returned false"}catch(f){k=(f instanceof Error?f.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,Z.destroy();return}R.keepAlivesSent+=1,z=setTimeout(()=>{w(),this.keepaliveTrace("Ping timeout passed without response"),this.channelzTrace.addTrace("CT_INFO","Connection dropped by keepalive timeout from "+V),D=!0,Z.destroy()},this.keepaliveTimeoutMs),(C=z.unref)===null||C===void 0||C.call(z)},_(),Z.on("close",()=>{var C;if(!D)this.channelzTrace.addTrace("CT_INFO","Connection dropped by client "+V);if(this.sessionChildrenTracker.unrefChild(W),(0,M0.unregisterChannelzRef)(W),A)clearTimeout(A);if(H)clearTimeout(H);if(w(),B!==null)clearTimeout(B.timeout),this.sessionIdleTimeouts.delete(Z);(C=this.http2Servers.get(J))===null||C===void 0||C.sessions.delete(Z),this.sessions.delete(Z)})}}enableIdleTimeout(J){var Z,T;if(this.sessionIdleTimeout>=v3)return null;let K={activeStreams:0,lastIdle:Date.now(),onClose:this.onStreamClose.bind(this,J),timeout:setTimeout(this.onIdleTimeout,this.sessionIdleTimeout,this,J)};(T=(Z=K.timeout).unref)===null||T===void 0||T.call(Z),this.sessionIdleTimeouts.set(J,K);let{socket:U}=J;return this.trace("Enable idle timeout for "+U.remoteAddress+":"+U.remotePort),K}onIdleTimeout(J,Z){let{socket:T}=Z,K=J.sessionIdleTimeouts.get(Z);if(K!==void 0&&K.activeStreams===0)if(Date.now()-K.lastIdle>=J.sessionIdleTimeout)J.trace("Session idle timeout triggered for "+(T===null||T===void 0?void 0:T.remoteAddress)+":"+(T===null||T===void 0?void 0:T.remotePort)+" last idle at "+K.lastIdle),J.closeSession(Z);else K.timeout.refresh()}onStreamOpened(J){let Z=J.session,T=this.sessionIdleTimeouts.get(Z);if(T)T.activeStreams+=1,J.once("close",T.onClose)}onStreamClose(J){var Z,T;let K=this.sessionIdleTimeouts.get(J);if(K){if(K.activeStreams-=1,K.activeStreams===0)K.lastIdle=Date.now(),K.timeout.refresh(),this.trace("Session onStreamClose"+((Z=J.socket)===null||Z===void 0?void 0:Z.remoteAddress)+":"+((T=J.socket)===null||T===void 0?void 0:T.remotePort)+" at "+K.lastIdle)}}},(()=>{let Q=typeof Symbol==="function"&&Symbol.metadata?Object.create(null):void 0;if(X=[ES("Calling start() is no longer necessary. It can be safely omitted.")],KS($,null,X,{kind:"method",name:"start",static:!1,private:!1,access:{has:(J)=>("start"in J),get:(J)=>J.start},metadata:Q},null,Y),Q)Object.defineProperty($,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:Q})})(),$})();k$.Server=AS;async function DS($,Y){let X;function Q(T,K,U,G){if(T){$.sendStatus((0,oY.serverErrorToStatus)(T,U));return}$.sendMessage(K,()=>{$.sendStatus({code:F0.Status.OK,details:"OK",metadata:U!==null&&U!==void 0?U:null})})}let J,Z=null;$.start({onReceiveMetadata(T){J=T,$.startRead()},onReceiveMessage(T){if(Z){$.sendStatus({code:F0.Status.UNIMPLEMENTED,details:`Received a second request message for server streaming method ${Y.path}`,metadata:null});return}Z=T,$.startRead()},onReceiveHalfClose(){if(!Z){$.sendStatus({code:F0.Status.UNIMPLEMENTED,details:`Received no request message for server streaming method ${Y.path}`,metadata:null});return}X=new oY.ServerWritableStreamImpl(Y.path,$,J,Z);try{Y.func(X,Q)}catch(T){$.sendStatus({code:F0.Status.UNKNOWN,details:`Server method handler threw error ${T.message}`,metadata:null})}},onCancel(){if(X)X.cancelled=!0,X.emit("cancelled","cancelled")}})}function FS($,Y){let X;function Q(J,Z,T,K){if(J){$.sendStatus((0,oY.serverErrorToStatus)(J,T));return}$.sendMessage(Z,()=>{$.sendStatus({code:F0.Status.OK,details:"OK",metadata:T!==null&&T!==void 0?T:null})})}$.start({onReceiveMetadata(J){X=new oY.ServerDuplexStreamImpl(Y.path,$,J);try{Y.func(X,Q)}catch(Z){$.sendStatus({code:F0.Status.UNKNOWN,details:`Server method handler threw error ${Z.message}`,metadata:null})}},onReceiveMessage(J){X.push(J)},onReceiveHalfClose(){X.push(null)},onCancel(){if(X)X.cancelled=!0,X.emit("cancelled","cancelled"),X.destroy()}})}function HS($,Y){let X,Q,J=null;$.start({onReceiveMetadata(Z){Q=Z,$.startRead()},onReceiveMessage(Z){if(J){$.sendStatus({code:F0.Status.UNIMPLEMENTED,details:`Received a second request message for server streaming method ${Y.path}`,metadata:null});return}J=Z,$.startRead()},onReceiveHalfClose(){if(!J){$.sendStatus({code:F0.Status.UNIMPLEMENTED,details:`Received no request message for server streaming method ${Y.path}`,metadata:null});return}X=new oY.ServerWritableStreamImpl(Y.path,$,Q,J);try{Y.func(X)}catch(Z){$.sendStatus({code:F0.Status.UNKNOWN,details:`Server method handler threw error ${Z.message}`,metadata:null})}},onCancel(){if(X)X.cancelled=!0,X.emit("cancelled","cancelled"),X.destroy()}})}function zS($,Y){let X;$.start({onReceiveMetadata(Q){X=new oY.ServerDuplexStreamImpl(Y.path,$,Q);try{Y.func(X)}catch(J){$.sendStatus({code:F0.Status.UNKNOWN,details:`Server method handler threw error ${J.message}`,metadata:null})}},onReceiveMessage(Q){X.push(Q)},onReceiveHalfClose(){X.push(null)},onCancel(){if(X)X.cancelled=!0,X.emit("cancelled","cancelled"),X.destroy()}})}});var u3=M((m3)=>{Object.defineProperty(m3,"__esModule",{value:!0});m3.StatusBuilder=void 0;class f3{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 $}}m3.StatusBuilder=f3});var G8=M((o3)=>{Object.defineProperty(o3,"__esModule",{value:!0});o3.LeafLoadBalancer=o3.PickFirstLoadBalancer=o3.PickFirstLoadBalancingConfig=void 0;o3.shuffled=l3;o3.setup=LS;var sJ=M$(),H0=n0(),h$=Y$(),d3=r0(),qS=Z0(),NS=i(),p3=r0(),c3=s("net"),MS=l$(),BS="pick_first";function K8($){qS.trace(NS.LogVerbosity.DEBUG,BS,$)}var U8="pick_first",IS=250;class sY{constructor($){this.shuffleAddressList=$}getLoadBalancerName(){return U8}toJsonObject(){return{[U8]:{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 sY($.shuffleAddressList===!0)}}o3.PickFirstLoadBalancingConfig=sY;class n3{constructor($){this.subchannel=$}pick($){return{pickResultType:h$.PickResultType.COMPLETE,subchannel:this.subchannel,status:null,onCallStarted:null,onCallEnded:null}}}function l3($){let Y=$.slice();for(let X=Y.length-1;X>1;X--){let Q=Math.floor(Math.random()*(X+1)),J=Y[X];Y[X]=Y[Q],Y[Q]=J}return Y}function OS($){if($.length===0)return[];let Y=[],X=[],Q=[],J=(0,p3.isTcpSubchannelAddress)($[0])&&(0,c3.isIPv6)($[0].host);for(let K of $)if((0,p3.isTcpSubchannelAddress)(K)&&(0,c3.isIPv6)(K.host))X.push(K);else Q.push(K);let Z=J?X:Q,T=J?Q:X;for(let K=0;K<Math.max(Z.length,T.length);K++){if(K<Z.length)Y.push(Z[K]);if(K<T.length)Y.push(T[K])}return Y}var i3="grpc-node.internal.pick-first.report_health_status";class g4{constructor($){this.channelControlHelper=$,this.children=[],this.currentState=H0.ConnectivityState.IDLE,this.currentSubchannelIndex=0,this.currentPick=null,this.subchannelStateListener=(Y,X,Q,J,Z)=>{this.onSubchannelStateUpdate(Y,X,Q,Z)},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 Y=`Picked subchannel ${this.currentPick.getAddress()} is unhealthy`;this.updateState(H0.ConnectivityState.TRANSIENT_FAILURE,new h$.UnavailablePicker({details:Y}),Y)}else this.updateState(H0.ConnectivityState.READY,new n3(this.currentPick),null);else if((($=this.latestAddressList)===null||$===void 0?void 0:$.length)===0){let Y=`No connection established. Last error: ${this.lastError}. Resolution note: ${this.latestResolutionNote}`;this.updateState(H0.ConnectivityState.TRANSIENT_FAILURE,new h$.UnavailablePicker({details:Y}),Y)}else if(this.children.length===0)this.updateState(H0.ConnectivityState.IDLE,new h$.QueuePicker(this),null);else if(this.stickyTransientFailureMode){let Y=`No connection established. Last error: ${this.lastError}. Resolution note: ${this.latestResolutionNote}`;this.updateState(H0.ConnectivityState.TRANSIENT_FAILURE,new h$.UnavailablePicker({details:Y}),Y)}else this.updateState(H0.ConnectivityState.CONNECTING,new h$.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($,Y,X,Q){var J;if((J=this.currentPick)===null||J===void 0?void 0:J.realSubchannelEquals($)){if(X!==H0.ConnectivityState.READY)this.removeCurrentPick(),this.calculateAndReportNewState();return}for(let[Z,T]of this.children.entries())if($.realSubchannelEquals(T.subchannel)){if(X===H0.ConnectivityState.READY)this.pickSubchannel(T.subchannel);if(X===H0.ConnectivityState.TRANSIENT_FAILURE){if(T.hasReportedTransientFailure=!0,Q)this.lastError=Q;if(this.maybeEnterStickyTransientFailureMode(),Z===this.currentSubchannelIndex)this.startNextSubchannelConnecting(Z+1)}T.subchannel.startConnecting();return}}startNextSubchannelConnecting($){clearTimeout(this.connectionDelayTimeout);for(let[Y,X]of this.children.entries())if(Y>=$){let Q=X.subchannel.getConnectivityState();if(Q===H0.ConnectivityState.IDLE||Q===H0.ConnectivityState.CONNECTING){this.startConnecting(Y);return}}this.maybeEnterStickyTransientFailureMode()}startConnecting($){var Y,X;if(clearTimeout(this.connectionDelayTimeout),this.currentSubchannelIndex=$,this.children[$].subchannel.getConnectivityState()===H0.ConnectivityState.IDLE)K8("Start connecting to subchannel with address "+this.children[$].subchannel.getAddress()),process.nextTick(()=>{var Q;(Q=this.children[$])===null||Q===void 0||Q.subchannel.startConnecting()});this.connectionDelayTimeout=setTimeout(()=>{this.startNextSubchannelConnecting($+1)},IS),(X=(Y=this.connectionDelayTimeout).unref)===null||X===void 0||X.call(Y)}pickSubchannel($){K8("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($,Y,X){K8(H0.ConnectivityState[this.currentState]+" -> "+H0.ConnectivityState[$]),this.currentState=$,this.channelControlHelper.updateState($,Y,X)}resetSubchannelList(){for(let $ of this.children)$.subchannel.removeConnectivityStateListener(this.subchannelStateListener),$.subchannel.unref(),this.channelControlHelper.removeChannelzChild($.subchannel.getChannelzRef());this.currentSubchannelIndex=0,this.children=[]}connectToAddressList($,Y){K8("connectToAddressList(["+$.map((Q)=>(0,d3.subchannelAddressToString)(Q))+"])");let X=$.map((Q)=>({subchannel:this.channelControlHelper.createSubchannel(Q,Y),hasReportedTransientFailure:!1}));for(let{subchannel:Q}of X)if(Q.getConnectivityState()===H0.ConnectivityState.READY){this.pickSubchannel(Q);return}for(let{subchannel:Q}of X)Q.ref(),this.channelControlHelper.addChannelzChild(Q.getChannelzRef());this.resetSubchannelList(),this.children=X;for(let{subchannel:Q}of this.children)Q.addConnectivityStateListener(this.subchannelStateListener);for(let Q of this.children)if(Q.subchannel.getConnectivityState()===H0.ConnectivityState.TRANSIENT_FAILURE)Q.hasReportedTransientFailure=!0;this.startNextSubchannelConnecting(0),this.calculateAndReportNewState()}updateAddressList($,Y,X,Q){if(!(Y instanceof sY))return!1;if(!$.ok){if(this.children.length===0&&this.currentPick===null)this.channelControlHelper.updateState(H0.ConnectivityState.TRANSIENT_FAILURE,new h$.UnavailablePicker($.error),$.error.details);return!0}let J=$.value;if(this.reportHealthStatus=X[i3],Y.getShuffleAddressList())J=l3(J);let Z=[].concat(...J.map((K)=>K.addresses));K8("updateAddressList(["+Z.map((K)=>(0,d3.subchannelAddressToString)(K))+"])");let T=OS(Z);if(this.latestAddressList=T,this.latestOptions=X,this.connectToAddressList(T,X),this.latestResolutionNote=Q,Z.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 U8}}o3.PickFirstLoadBalancer=g4;var PS=new sY(!1);class r3{constructor($,Y,X,Q){this.endpoint=$,this.options=X,this.resolutionNote=Q,this.latestState=H0.ConnectivityState.IDLE;let J=(0,sJ.createChildChannelControlHelper)(Y,{updateState:(Z,T,K)=>{this.latestState=Z,this.latestPicker=T,Y.updateState(Z,T,K)}});this.pickFirstBalancer=new g4(J),this.latestPicker=new h$.QueuePicker(this.pickFirstBalancer)}startConnecting(){this.pickFirstBalancer.updateAddressList((0,MS.statusOrFromValue)([this.endpoint]),PS,Object.assign(Object.assign({},this.options),{[i3]:!0}),this.resolutionNote)}updateEndpoint($,Y){if(this.options=Y,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()}}o3.LeafLoadBalancer=r3;function LS(){(0,sJ.registerLoadBalancerType)(U8,g4,sY),(0,sJ.registerDefaultLoadBalancerType)(U8)}});var $V=M((t3)=>{Object.defineProperty(t3,"__esModule",{value:!0});t3.FileWatcherCertificateProvider=void 0;var jS=s("fs"),xS=Z0(),vS=i(),kS=s("util"),hS="certificate_provider";function f4($){xS.trace(vS.LogVerbosity.DEBUG,hS,$)}var aJ=(0,kS.promisify)(jS.readFile);class a3{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");f4("File watcher constructed with config "+JSON.stringify($))}updateCertificates(){if(this.fileResultPromise)return;this.fileResultPromise=Promise.allSettled([this.config.certificateFile?aJ(this.config.certificateFile):Promise.reject(),this.config.privateKeyFile?aJ(this.config.privateKeyFile):Promise.reject(),this.config.caCertificateFile?aJ(this.config.caCertificateFile):Promise.reject()]),this.fileResultPromise.then(([$,Y,X])=>{if(!this.refreshTimer)return;if(f4("File watcher read certificates certificate "+$.status+", privateKey "+Y.status+", CA certificate "+X.status),this.lastUpdateTime=new Date,this.fileResultPromise=null,$.status==="fulfilled"&&Y.status==="fulfilled")this.latestIdentityUpdate={certificate:$.value,privateKey:Y.value};else this.latestIdentityUpdate=null;if(X.status==="fulfilled")this.latestCaUpdate={caCertificate:X.value};else this.latestCaUpdate=null;for(let Q of this.identityListeners)Q(this.latestIdentityUpdate);for(let Q of this.caListeners)Q(this.latestCaUpdate)}),f4("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),f4("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()}}t3.FileWatcherCertificateProvider=a3});var $7=M((r)=>{Object.defineProperty(r,"__esModule",{value:!0});r.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX=r.createCertificateProviderChannelCredentials=r.FileWatcherCertificateProvider=r.createCertificateProviderServerCredentials=r.createServerCredentialsWithInterceptors=r.BaseSubchannelWrapper=r.registerAdminService=r.FilterStackFactory=r.BaseFilter=r.statusOrFromError=r.statusOrFromValue=r.PickResultType=r.QueuePicker=r.UnavailablePicker=r.ChildLoadBalancerHandler=r.EndpointMap=r.endpointHasAddress=r.endpointToString=r.subchannelAddressToString=r.LeafLoadBalancer=r.isLoadBalancerNameRegistered=r.parseLoadBalancingConfig=r.selectLbConfigFromList=r.registerLoadBalancerType=r.createChildChannelControlHelper=r.BackoffTimeout=r.parseDuration=r.durationToMs=r.splitHostPort=r.uriToString=r.CHANNEL_ARGS_CONFIG_SELECTOR_KEY=r.createResolver=r.registerResolver=r.log=r.trace=void 0;var YV=Z0();Object.defineProperty(r,"trace",{enumerable:!0,get:function(){return YV.trace}});Object.defineProperty(r,"log",{enumerable:!0,get:function(){return YV.log}});var tJ=M1();Object.defineProperty(r,"registerResolver",{enumerable:!0,get:function(){return tJ.registerResolver}});Object.defineProperty(r,"createResolver",{enumerable:!0,get:function(){return tJ.createResolver}});Object.defineProperty(r,"CHANNEL_ARGS_CONFIG_SELECTOR_KEY",{enumerable:!0,get:function(){return tJ.CHANNEL_ARGS_CONFIG_SELECTOR_KEY}});var XV=c0();Object.defineProperty(r,"uriToString",{enumerable:!0,get:function(){return XV.uriToString}});Object.defineProperty(r,"splitHostPort",{enumerable:!0,get:function(){return XV.splitHostPort}});var QV=T8();Object.defineProperty(r,"durationToMs",{enumerable:!0,get:function(){return QV.durationToMs}});Object.defineProperty(r,"parseDuration",{enumerable:!0,get:function(){return QV.parseDuration}});var _S=PY();Object.defineProperty(r,"BackoffTimeout",{enumerable:!0,get:function(){return _S.BackoffTimeout}});var W8=M$();Object.defineProperty(r,"createChildChannelControlHelper",{enumerable:!0,get:function(){return W8.createChildChannelControlHelper}});Object.defineProperty(r,"registerLoadBalancerType",{enumerable:!0,get:function(){return W8.registerLoadBalancerType}});Object.defineProperty(r,"selectLbConfigFromList",{enumerable:!0,get:function(){return W8.selectLbConfigFromList}});Object.defineProperty(r,"parseLoadBalancingConfig",{enumerable:!0,get:function(){return W8.parseLoadBalancingConfig}});Object.defineProperty(r,"isLoadBalancerNameRegistered",{enumerable:!0,get:function(){return W8.isLoadBalancerNameRegistered}});var gS=G8();Object.defineProperty(r,"LeafLoadBalancer",{enumerable:!0,get:function(){return gS.LeafLoadBalancer}});var m4=r0();Object.defineProperty(r,"subchannelAddressToString",{enumerable:!0,get:function(){return m4.subchannelAddressToString}});Object.defineProperty(r,"endpointToString",{enumerable:!0,get:function(){return m4.endpointToString}});Object.defineProperty(r,"endpointHasAddress",{enumerable:!0,get:function(){return m4.endpointHasAddress}});Object.defineProperty(r,"EndpointMap",{enumerable:!0,get:function(){return m4.EndpointMap}});var fS=j9();Object.defineProperty(r,"ChildLoadBalancerHandler",{enumerable:!0,get:function(){return fS.ChildLoadBalancerHandler}});var eJ=Y$();Object.defineProperty(r,"UnavailablePicker",{enumerable:!0,get:function(){return eJ.UnavailablePicker}});Object.defineProperty(r,"QueuePicker",{enumerable:!0,get:function(){return eJ.QueuePicker}});Object.defineProperty(r,"PickResultType",{enumerable:!0,get:function(){return eJ.PickResultType}});var JV=l$();Object.defineProperty(r,"statusOrFromValue",{enumerable:!0,get:function(){return JV.statusOrFromValue}});Object.defineProperty(r,"statusOrFromError",{enumerable:!0,get:function(){return JV.statusOrFromError}});var mS=EJ();Object.defineProperty(r,"BaseFilter",{enumerable:!0,get:function(){return mS.BaseFilter}});var bS=z4();Object.defineProperty(r,"FilterStackFactory",{enumerable:!0,get:function(){return bS.FilterStackFactory}});var uS=v9();Object.defineProperty(r,"registerAdminService",{enumerable:!0,get:function(){return uS.registerAdminService}});var dS=J8();Object.defineProperty(r,"BaseSubchannelWrapper",{enumerable:!0,get:function(){return dS.BaseSubchannelWrapper}});var ZV=j4();Object.defineProperty(r,"createServerCredentialsWithInterceptors",{enumerable:!0,get:function(){return ZV.createServerCredentialsWithInterceptors}});Object.defineProperty(r,"createCertificateProviderServerCredentials",{enumerable:!0,get:function(){return ZV.createCertificateProviderServerCredentials}});var pS=$V();Object.defineProperty(r,"FileWatcherCertificateProvider",{enumerable:!0,get:function(){return pS.FileWatcherCertificateProvider}});var cS=OY();Object.defineProperty(r,"createCertificateProviderChannelCredentials",{enumerable:!0,get:function(){return cS.createCertificateProviderChannelCredentials}});var nS=vJ();Object.defineProperty(r,"SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX",{enumerable:!0,get:function(){return nS.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX}})});var UV=M((KV)=>{Object.defineProperty(KV,"__esModule",{value:!0});KV.setup=oS;var iS=M1(),rS=l$();class TV{constructor($,Y,X){this.listener=Y,this.hasReturnedResult=!1,this.endpoints=[];let Q;if($.authority==="")Q="/"+$.path;else Q=$.path;this.endpoints=[{addresses:[{path:Q}]}]}updateResolution(){if(!this.hasReturnedResult)this.hasReturnedResult=!0,process.nextTick(this.listener,(0,rS.statusOrFromValue)(this.endpoints),{},null,"")}destroy(){this.hasReturnedResult=!1}static getDefaultAuthority($){return"localhost"}}function oS(){(0,iS.registerResolver)("unix",TV)}});var DV=M((AV)=>{Object.defineProperty(AV,"__esModule",{value:!0});AV.setup=Yw;var GV=s("net"),WV=l$(),b4=i(),Y7=P0(),RV=M1(),aS=r0(),EV=c0(),tS=Z0(),eS="ip_resolver";function VV($){tS.trace(b4.LogVerbosity.DEBUG,eS,$)}var X7="ipv4",Q7="ipv6",$w=443;class J7{constructor($,Y,X){var Q;this.listener=Y,this.endpoints=[],this.error=null,this.hasReturnedResult=!1,VV("Resolver constructed for target "+(0,EV.uriToString)($));let J=[];if(!($.scheme===X7||$.scheme===Q7)){this.error={code:b4.Status.UNAVAILABLE,details:`Unrecognized scheme ${$.scheme} in IP resolver`,metadata:new Y7.Metadata};return}let Z=$.path.split(",");for(let T of Z){let K=(0,EV.splitHostPort)(T);if(K===null){this.error={code:b4.Status.UNAVAILABLE,details:`Failed to parse ${$.scheme} address ${T}`,metadata:new Y7.Metadata};return}if($.scheme===X7&&!(0,GV.isIPv4)(K.host)||$.scheme===Q7&&!(0,GV.isIPv6)(K.host)){this.error={code:b4.Status.UNAVAILABLE,details:`Failed to parse ${$.scheme} address ${T}`,metadata:new Y7.Metadata};return}J.push({host:K.host,port:(Q=K.port)!==null&&Q!==void 0?Q:$w})}this.endpoints=J.map((T)=>({addresses:[T]})),VV("Parsed "+$.scheme+" address list "+J.map(aS.subchannelAddressToString))}updateResolution(){if(!this.hasReturnedResult)this.hasReturnedResult=!0,process.nextTick(()=>{if(this.error)this.listener((0,WV.statusOrFromError)(this.error),{},null,"");else this.listener((0,WV.statusOrFromValue)(this.endpoints),{},null,"")})}destroy(){this.hasReturnedResult=!1}static getDefaultAuthority($){return $.path.split(",")[0]}}function Yw(){(0,RV.registerResolver)(X7,J7),(0,RV.registerResolver)(Q7,J7)}});var BV=M((NV)=>{Object.defineProperty(NV,"__esModule",{value:!0});NV.RoundRobinLoadBalancer=void 0;NV.setup=Uw;var zV=M$(),k0=n0(),R8=Y$(),Qw=Z0(),Jw=i(),FV=r0(),Zw=G8(),Tw="round_robin";function HV($){Qw.trace(Jw.LogVerbosity.DEBUG,Tw,$)}var u4="round_robin";class d4{getLoadBalancerName(){return u4}constructor(){}toJsonObject(){return{[u4]:{}}}static createFromJson($){return new d4}}class qV{constructor($,Y=0){this.children=$,this.nextIndex=Y}pick($){let Y=this.children[this.nextIndex].picker;return this.nextIndex=(this.nextIndex+1)%this.children.length,Y.pick($)}peekNextEndpoint(){return this.children[this.nextIndex].endpoint}}function Kw($,Y){return[...$.slice(Y),...$.slice(0,Y)]}class Z7{constructor($){this.channelControlHelper=$,this.children=[],this.currentState=k0.ConnectivityState.IDLE,this.currentReadyPicker=null,this.updatesPaused=!1,this.lastError=null,this.childChannelControlHelper=(0,zV.createChildChannelControlHelper)($,{updateState:(Y,X,Q)=>{if(this.currentState===k0.ConnectivityState.READY&&Y!==k0.ConnectivityState.READY)this.channelControlHelper.requestReresolution();if(Q)this.lastError=Q;this.calculateAndUpdateState()}})}countChildrenWithState($){return this.children.filter((Y)=>Y.getConnectivityState()===$).length}calculateAndUpdateState(){if(this.updatesPaused)return;if(this.countChildrenWithState(k0.ConnectivityState.READY)>0){let $=this.children.filter((X)=>X.getConnectivityState()===k0.ConnectivityState.READY),Y=0;if(this.currentReadyPicker!==null){let X=this.currentReadyPicker.peekNextEndpoint();if(Y=$.findIndex((Q)=>(0,FV.endpointEqual)(Q.getEndpoint(),X)),Y<0)Y=0}this.updateState(k0.ConnectivityState.READY,new qV($.map((X)=>({endpoint:X.getEndpoint(),picker:X.getPicker()})),Y),null)}else if(this.countChildrenWithState(k0.ConnectivityState.CONNECTING)>0)this.updateState(k0.ConnectivityState.CONNECTING,new R8.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 R8.UnavailablePicker({details:$}),$)}else this.updateState(k0.ConnectivityState.IDLE,new R8.QueuePicker(this),null);for(let $ of this.children)if($.getConnectivityState()===k0.ConnectivityState.IDLE)$.exitIdle()}updateState($,Y,X){if(HV(k0.ConnectivityState[this.currentState]+" -> "+k0.ConnectivityState[$]),$===k0.ConnectivityState.READY)this.currentReadyPicker=Y;else this.currentReadyPicker=null;this.currentState=$,this.channelControlHelper.updateState($,Y,X)}resetSubchannelList(){for(let $ of this.children)$.destroy();this.children=[]}updateAddressList($,Y,X,Q){if(!(Y instanceof d4))return!1;if(!$.ok){if(this.children.length===0)this.updateState(k0.ConnectivityState.TRANSIENT_FAILURE,new R8.UnavailablePicker($.error),$.error.details);return!0}let J=Math.random()*$.value.length|0,Z=Kw($.value,J);if(this.resetSubchannelList(),Z.length===0){let T=`No addresses resolved. Resolution note: ${Q}`;this.updateState(k0.ConnectivityState.TRANSIENT_FAILURE,new R8.UnavailablePicker({details:T}),T)}HV("Connect to endpoint list "+Z.map(FV.endpointToString)),this.updatesPaused=!0,this.children=Z.map((T)=>new Zw.LeafLoadBalancer(T,this.childChannelControlHelper,X,Q));for(let T of this.children)T.startConnecting();return this.updatesPaused=!1,this.calculateAndUpdateState(),!0}exitIdle(){}resetBackoff(){}destroy(){this.resetSubchannelList()}getTypeName(){return u4}}NV.RoundRobinLoadBalancer=Z7;function Uw(){(0,zV.registerLoadBalancerType)(u4,Z7,d4)}});var yV=M((wV)=>{var T7;Object.defineProperty(wV,"__esModule",{value:!0});wV.OutlierDetectionLoadBalancer=wV.OutlierDetectionLoadBalancingConfig=void 0;wV.setup=Nw;var Ww=n0(),IV=i(),ZY=T8(),OV=$7(),Rw=M$(),Ew=j9(),Vw=Y$(),K7=r0(),Aw=J8(),Dw=Z0(),Fw="outlier_detection";function C0($){Dw.trace(IV.LogVerbosity.DEBUG,Fw,$)}var W7="outlier_detection",Hw=((T7=process.env.GRPC_EXPERIMENTAL_ENABLE_OUTLIER_DETECTION)!==null&&T7!==void 0?T7:"true")==="true",zw={stdev_factor:1900,enforcement_percentage:100,minimum_hosts:5,request_volume:100},qw={threshold:85,enforcement_percentage:100,minimum_hosts:5,request_volume:50};function aY($,Y,X,Q){if(Y in $&&$[Y]!==void 0&&typeof $[Y]!==X){let J=Q?`${Q}.${Y}`:Y;throw Error(`outlier detection config ${J} parse error: expected ${X}, got ${typeof $[Y]}`)}}function U7($,Y,X){let Q=X?`${X}.${Y}`:Y;if(Y in $&&$[Y]!==void 0){if(!(0,ZY.isDuration)($[Y]))throw Error(`outlier detection config ${Q} parse error: expected Duration, got ${typeof $[Y]}`);if(!($[Y].seconds>=0&&$[Y].seconds<=315576000000&&$[Y].nanos>=0&&$[Y].nanos<=999999999))throw Error(`outlier detection config ${Q} parse error: values out of range for non-negative Duaration`)}}function p4($,Y,X){let Q=X?`${X}.${Y}`:Y;if(aY($,Y,"number",X),Y in $&&$[Y]!==void 0&&!($[Y]>=0&&$[Y]<=100))throw Error(`outlier detection config ${Q} parse error: value out of range for percentage (0-100)`)}class E8{constructor($,Y,X,Q,J,Z,T){if(this.childPolicy=T,T.getLoadBalancerName()==="pick_first")throw Error("outlier_detection LB policy cannot have a pick_first child policy");this.intervalMs=$!==null&&$!==void 0?$:1e4,this.baseEjectionTimeMs=Y!==null&&Y!==void 0?Y:30000,this.maxEjectionTimeMs=X!==null&&X!==void 0?X:300000,this.maxEjectionPercent=Q!==null&&Q!==void 0?Q:10,this.successRateEjection=J?Object.assign(Object.assign({},zw),J):null,this.failurePercentageEjection=Z?Object.assign(Object.assign({},qw),Z):null}getLoadBalancerName(){return W7}toJsonObject(){var $,Y;return{outlier_detection:{interval:(0,ZY.msToDuration)(this.intervalMs),base_ejection_time:(0,ZY.msToDuration)(this.baseEjectionTimeMs),max_ejection_time:(0,ZY.msToDuration)(this.maxEjectionTimeMs),max_ejection_percent:this.maxEjectionPercent,success_rate_ejection:($=this.successRateEjection)!==null&&$!==void 0?$:void 0,failure_percentage_ejection:(Y=this.failurePercentageEjection)!==null&&Y!==void 0?Y: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 Y;if(U7($,"interval"),U7($,"base_ejection_time"),U7($,"max_ejection_time"),p4($,"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");aY($.success_rate_ejection,"stdev_factor","number","success_rate_ejection"),p4($.success_rate_ejection,"enforcement_percentage","success_rate_ejection"),aY($.success_rate_ejection,"minimum_hosts","number","success_rate_ejection"),aY($.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");p4($.failure_percentage_ejection,"threshold","failure_percentage_ejection"),p4($.failure_percentage_ejection,"enforcement_percentage","failure_percentage_ejection"),aY($.failure_percentage_ejection,"minimum_hosts","number","failure_percentage_ejection"),aY($.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 X=(0,Rw.selectLbConfigFromList)($.child_policy);if(!X)throw Error("outlier detection config child_policy: no valid recognized policy found");return new E8($.interval?(0,ZY.durationToMs)($.interval):null,$.base_ejection_time?(0,ZY.durationToMs)($.base_ejection_time):null,$.max_ejection_time?(0,ZY.durationToMs)($.max_ejection_time):null,(Y=$.max_ejection_percent)!==null&&Y!==void 0?Y:null,$.success_rate_ejection,$.failure_percentage_ejection,X)}}wV.OutlierDetectionLoadBalancingConfig=E8;class PV extends Aw.BaseSubchannelWrapper{constructor($,Y){super($);this.mapEntry=Y,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 G7(){return{success:0,failure:0}}class LV{constructor(){this.activeBucket=G7(),this.inactiveBucket=G7()}addSuccess(){this.activeBucket.success+=1}addFailure(){this.activeBucket.failure+=1}switchBuckets(){this.inactiveBucket=this.activeBucket,this.activeBucket=G7()}getLastSuccesses(){return this.inactiveBucket.success}getLastFailures(){return this.inactiveBucket.failure}}class SV{constructor($,Y){this.wrappedPicker=$,this.countCalls=Y}pick($){let Y=this.wrappedPicker.pick($);if(Y.pickResultType===Vw.PickResultType.COMPLETE){let X=Y.subchannel,Q=X.getMapEntry();if(Q){let J=Y.onCallEnded;if(this.countCalls)J=(Z,T,K)=>{var U;if(Z===IV.Status.OK)Q.counter.addSuccess();else Q.counter.addFailure();(U=Y.onCallEnded)===null||U===void 0||U.call(Y,Z,T,K)};return Object.assign(Object.assign({},Y),{subchannel:X.getWrappedSubchannel(),onCallEnded:J})}else return Object.assign(Object.assign({},Y),{subchannel:X.getWrappedSubchannel()})}else return Y}}class R7{constructor($){this.entryMap=new K7.EndpointMap,this.latestConfig=null,this.timerStartTime=null,this.childBalancer=new Ew.ChildLoadBalancerHandler((0,OV.createChildChannelControlHelper)($,{createSubchannel:(Y,X)=>{let Q=$.createSubchannel(Y,X),J=this.entryMap.getForSubchannelAddress(Y),Z=new PV(Q,J);if((J===null||J===void 0?void 0:J.currentEjectionTimestamp)!==null)Z.eject();return J===null||J===void 0||J.subchannelWrappers.push(Z),Z},updateState:(Y,X,Q)=>{if(Y===Ww.ConnectivityState.READY)$.updateState(Y,new SV(X,this.isCountingEnabled()),Q);else $.updateState(Y,X,Q)}})),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 Y of this.entryMap.values())if(Y.currentEjectionTimestamp!==null)$+=1;return $*100/this.entryMap.size}runSuccessRateCheck($){if(!this.latestConfig)return;let Y=this.latestConfig.getSuccessRateEjectionConfig();if(!Y)return;C0("Running success rate check");let X=Y.request_volume,Q=0,J=[];for(let[W,R]of this.entryMap.entries()){let V=R.counter.getLastSuccesses(),A=R.counter.getLastFailures();if(C0("Stats for "+(0,K7.endpointToString)(W)+": successes="+V+" failures="+A+" targetRequestVolume="+X),V+A>=X)Q+=1,J.push(V/(V+A))}if(C0("Found "+Q+" success rate candidates; currentEjectionPercent="+this.getCurrentEjectionPercent()+" successRates=["+J+"]"),Q<Y.minimum_hosts)return;let Z=J.reduce((W,R)=>W+R)/J.length,T=0;for(let W of J){let R=W-Z;T+=R*R}let K=T/J.length,U=Math.sqrt(K),G=Z-U*(Y.stdev_factor/1000);C0("stdev="+U+" ejectionThreshold="+G);for(let[W,R]of this.entryMap.entries()){if(this.getCurrentEjectionPercent()>=this.latestConfig.getMaxEjectionPercent())break;let V=R.counter.getLastSuccesses(),A=R.counter.getLastFailures();if(V+A<X)continue;let H=V/(V+A);if(C0("Checking candidate "+W+" successRate="+H),H<G){let z=Math.random()*100;if(C0("Candidate "+W+" randomNumber="+z+" enforcement_percentage="+Y.enforcement_percentage),z<Y.enforcement_percentage)C0("Ejecting candidate "+W),this.eject(R,$)}}}runFailurePercentageCheck($){if(!this.latestConfig)return;let Y=this.latestConfig.getFailurePercentageEjectionConfig();if(!Y)return;C0("Running failure percentage check. threshold="+Y.threshold+" request volume threshold="+Y.request_volume);let X=0;for(let Q of this.entryMap.values()){let J=Q.counter.getLastSuccesses(),Z=Q.counter.getLastFailures();if(J+Z>=Y.request_volume)X+=1}if(X<Y.minimum_hosts)return;for(let[Q,J]of this.entryMap.entries()){if(this.getCurrentEjectionPercent()>=this.latestConfig.getMaxEjectionPercent())break;let Z=J.counter.getLastSuccesses(),T=J.counter.getLastFailures();if(C0("Candidate successes="+Z+" failures="+T),Z+T<Y.request_volume)continue;if(T*100/(T+Z)>Y.threshold){let U=Math.random()*100;if(C0("Candidate "+Q+" randomNumber="+U+" enforcement_percentage="+Y.enforcement_percentage),U<Y.enforcement_percentage)C0("Ejecting candidate "+Q),this.eject(J,$)}}}eject($,Y){$.currentEjectionTimestamp=new Date,$.ejectionTimeMultiplier+=1;for(let X of $.subchannelWrappers)X.eject()}uneject($){$.currentEjectionTimestamp=null;for(let Y of $.subchannelWrappers)Y.uneject()}switchAllBuckets(){for(let $ of this.entryMap.values())$.counter.switchBuckets()}startTimer($){var Y,X;this.ejectionTimer=setTimeout(()=>this.runChecks(),$),(X=(Y=this.ejectionTimer).unref)===null||X===void 0||X.call(Y)}runChecks(){let $=new Date;if(C0("Ejection timer running"),this.switchAllBuckets(),!this.latestConfig)return;this.timerStartTime=$,this.startTimer(this.latestConfig.getIntervalMs()),this.runSuccessRateCheck($),this.runFailurePercentageCheck($);for(let[Y,X]of this.entryMap.entries())if(X.currentEjectionTimestamp===null){if(X.ejectionTimeMultiplier>0)X.ejectionTimeMultiplier-=1}else{let Q=this.latestConfig.getBaseEjectionTimeMs(),J=this.latestConfig.getMaxEjectionTimeMs(),Z=new Date(X.currentEjectionTimestamp.getTime());if(Z.setMilliseconds(Z.getMilliseconds()+Math.min(Q*X.ejectionTimeMultiplier,Math.max(Q,J))),Z<new Date)C0("Unejecting "+Y),this.uneject(X)}}updateAddressList($,Y,X,Q){if(!(Y instanceof E8))return!1;if(C0("Received update with config: "+JSON.stringify(Y.toJsonObject(),void 0,2)),$.ok){for(let Z of $.value)if(!this.entryMap.has(Z))C0("Adding map entry for "+(0,K7.endpointToString)(Z)),this.entryMap.set(Z,{counter:new LV,currentEjectionTimestamp:null,ejectionTimeMultiplier:0,subchannelWrappers:[]});this.entryMap.deleteMissing($.value)}let J=Y.getChildPolicy();if(this.childBalancer.updateAddressList($,J,X,Q),Y.getSuccessRateEjectionConfig()||Y.getFailurePercentageEjectionConfig())if(this.timerStartTime){C0("Previous timer existed. Replacing timer"),clearTimeout(this.ejectionTimer);let Z=Y.getIntervalMs()-(new Date().getTime()-this.timerStartTime.getTime());this.startTimer(Z)}else C0("Starting new timer"),this.timerStartTime=new Date,this.startTimer(Y.getIntervalMs()),this.switchAllBuckets();else{C0("Counting disabled. Cancelling timer."),this.timerStartTime=null,clearTimeout(this.ejectionTimer);for(let Z of this.entryMap.values())this.uneject(Z),Z.ejectionTimeMultiplier=0}return this.latestConfig=Y,!0}exitIdle(){this.childBalancer.exitIdle()}resetBackoff(){this.childBalancer.resetBackoff()}destroy(){clearTimeout(this.ejectionTimer),this.childBalancer.destroy()}getTypeName(){return W7}}wV.OutlierDetectionLoadBalancer=R7;function Nw(){if(Hw)(0,OV.registerLoadBalancerType)(W7,R7,E8)}});var kV=M((xV)=>{Object.defineProperty(xV,"__esModule",{value:!0});xV.PriorityQueue=void 0;var tY=0,E7=($)=>Math.floor($/2),c4=($)=>$*2+1,V8=($)=>$*2+2;class jV{constructor($=(Y,X)=>Y>X){this.comparator=$,this.heap=[]}size(){return this.heap.length}isEmpty(){return this.size()==0}peek(){return this.heap[tY]}push(...$){return $.forEach((Y)=>{this.heap.push(Y),this.siftUp()}),this.size()}pop(){let $=this.peek(),Y=this.size()-1;if(Y>tY)this.swap(tY,Y);return this.heap.pop(),this.siftDown(),$}replace($){let Y=this.peek();return this.heap[tY]=$,this.siftDown(),Y}greater($,Y){return this.comparator(this.heap[$],this.heap[Y])}swap($,Y){[this.heap[$],this.heap[Y]]=[this.heap[Y],this.heap[$]]}siftUp(){let $=this.size()-1;while($>tY&&this.greater($,E7($)))this.swap($,E7($)),$=E7($)}siftDown(){let $=tY;while(c4($)<this.size()&&this.greater(c4($),$)||V8($)<this.size()&&this.greater(V8($),$)){let Y=V8($)<this.size()&&this.greater(V8($),c4($))?V8($):c4($);this.swap($,Y),$=Y}}}xV.PriorityQueue=jV});var pV=M((uV)=>{Object.defineProperty(uV,"__esModule",{value:!0});uV.WeightedRoundRobinLoadBalancingConfig=void 0;uV.setup=vw;var y0=n0(),Iw=i(),J1=T8(),gV=M$(),Ow=G8(),Pw=Z0(),fV=v4(),eY=Y$(),Lw=kV(),hV=r0(),Sw="weighted_round_robin";function V7($){Pw.trace(Iw.LogVerbosity.DEBUG,Sw,$)}var A7="weighted_round_robin",ww=1e4,Cw=1e4,yw=180000,jw=1000,xw=1;function _V($,Y,X){if(Y in $&&$[Y]!==void 0&&typeof $[Y]!==X)throw Error(`weighted round robin config ${Y} parse error: expected ${X}, got ${typeof $[Y]}`)}function n4($,Y){if(Y in $&&$[Y]!==void 0&&$[Y]!==null){let X;if((0,J1.isDuration)($[Y]))X=$[Y];else if((0,J1.isDurationMessage)($[Y]))X=(0,J1.durationMessageToDuration)($[Y]);else if(typeof $[Y]==="string"){let Q=(0,J1.parseDuration)($[Y]);if(!Q)throw Error(`weighted round robin config ${Y}: failed to parse duration string ${$[Y]}`);X=Q}else throw Error(`weighted round robin config ${Y}: expected duration, got ${typeof $[Y]}`);return(0,J1.durationToMs)(X)}return null}class A8{constructor($,Y,X,Q,J,Z){this.enableOobLoadReport=$!==null&&$!==void 0?$:!1,this.oobLoadReportingPeriodMs=Y!==null&&Y!==void 0?Y:ww,this.blackoutPeriodMs=X!==null&&X!==void 0?X:Cw,this.weightExpirationPeriodMs=Q!==null&&Q!==void 0?Q:yw,this.weightUpdatePeriodMs=Math.max(J!==null&&J!==void 0?J:jw,100),this.errorUtilizationPenalty=Z!==null&&Z!==void 0?Z:xw}getLoadBalancerName(){return A7}toJsonObject(){return{enable_oob_load_report:this.enableOobLoadReport,oob_load_reporting_period:(0,J1.durationToString)((0,J1.msToDuration)(this.oobLoadReportingPeriodMs)),blackout_period:(0,J1.durationToString)((0,J1.msToDuration)(this.blackoutPeriodMs)),weight_expiration_period:(0,J1.durationToString)((0,J1.msToDuration)(this.weightExpirationPeriodMs)),weight_update_period:(0,J1.durationToString)((0,J1.msToDuration)(this.weightUpdatePeriodMs)),error_utilization_penalty:this.errorUtilizationPenalty}}static createFromJson($){if(_V($,"enable_oob_load_report","boolean"),_V($,"error_utilization_penalty","number"),$.error_utilization_penalty<0)throw Error("weighted round robin config error_utilization_penalty < 0");return new A8($.enable_oob_load_report,n4($,"oob_load_reporting_period"),n4($,"blackout_period"),n4($,"weight_expiration_period"),n4($,"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}}uV.WeightedRoundRobinLoadBalancingConfig=A8;class mV{constructor($,Y){this.metricsHandler=Y,this.queue=new Lw.PriorityQueue((J,Z)=>J.deadline<Z.deadline);let X=$.filter((J)=>J.weight>0),Q;if(X.length<2)Q=1;else{let J=0;for(let{weight:Z}of X)J+=Z;Q=J/X.length}for(let J of $){let Z=J.weight>0?1/J.weight:Q;this.queue.push({endpointName:J.endpointName,picker:J.picker,period:Z,deadline:Math.random()*Z})}}pick($){let Y=this.queue.pop();this.queue.push(Object.assign(Object.assign({},Y),{deadline:Y.deadline+Y.period}));let X=Y.picker.pick($);if(X.pickResultType===eY.PickResultType.COMPLETE)if(this.metricsHandler)return Object.assign(Object.assign({},X),{onCallEnded:(0,fV.createMetricsReader)((Q)=>this.metricsHandler(Q,Y.endpointName),X.onCallEnded)});else{let Q=X.subchannel;return Object.assign(Object.assign({},X),{subchannel:Q.getWrappedSubchannel()})}else return X}}class bV{constructor($){this.channelControlHelper=$,this.latestConfig=null,this.children=new Map,this.currentState=y0.ConnectivityState.IDLE,this.updatesPaused=!1,this.lastError=null,this.weightUpdateTimer=null}countChildrenWithState($){let Y=0;for(let X of this.children.values())if(X.child.getConnectivityState()===$)Y+=1;return Y}updateWeight($,Y){var X,Q;let{rps_fractional:J,application_utilization:Z}=Y;if(Z>0&&J>0)Z+=Y.eps/J*((Q=(X=this.latestConfig)===null||X===void 0?void 0:X.getErrorUtilizationPenalty())!==null&&Q!==void 0?Q:0);let T=Z===0?0:J/Z;if(T===0)return;let K=new Date;if($.nonEmptySince===null)$.nonEmptySince=K;$.lastUpdated=K,$.weight=T}getWeight($){if(!this.latestConfig)return 0;let Y=new Date().getTime();if(Y-$.lastUpdated.getTime()>=this.latestConfig.getWeightExpirationPeriodMs())return $.nonEmptySince=null,0;let X=this.latestConfig.getBlackoutPeriodMs();if(X>0&&($.nonEmptySince===null||Y-$.nonEmptySince.getTime()<X))return 0;return $.weight}calculateAndUpdateState(){if(this.updatesPaused||!this.latestConfig)return;if(this.countChildrenWithState(y0.ConnectivityState.READY)>0){let $=[];for(let[X,Q]of this.children){if(Q.child.getConnectivityState()!==y0.ConnectivityState.READY)continue;$.push({endpointName:X,picker:Q.child.getPicker(),weight:this.getWeight(Q)})}V7("Created picker with weights: "+$.map((X)=>X.endpointName+":"+X.weight).join(","));let Y;if(!this.latestConfig.getEnableOobLoadReport())Y=(X,Q)=>{let J=this.children.get(Q);if(J)this.updateWeight(J,X)};else Y=null;this.updateState(y0.ConnectivityState.READY,new mV($,Y),null)}else if(this.countChildrenWithState(y0.ConnectivityState.CONNECTING)>0)this.updateState(y0.ConnectivityState.CONNECTING,new eY.QueuePicker(this),null);else if(this.countChildrenWithState(y0.ConnectivityState.TRANSIENT_FAILURE)>0){let $=`weighted_round_robin: No connection established. Last error: ${this.lastError}`;this.updateState(y0.ConnectivityState.TRANSIENT_FAILURE,new eY.UnavailablePicker({details:$}),$)}else this.updateState(y0.ConnectivityState.IDLE,new eY.QueuePicker(this),null);for(let{child:$}of this.children.values())if($.getConnectivityState()===y0.ConnectivityState.IDLE)$.exitIdle()}updateState($,Y,X){V7(y0.ConnectivityState[this.currentState]+" -> "+y0.ConnectivityState[$]),this.currentState=$,this.channelControlHelper.updateState($,Y,X)}updateAddressList($,Y,X,Q){var J,Z;if(!(Y instanceof A8))return!1;if(!$.ok){if(this.children.size===0)this.updateState(y0.ConnectivityState.TRANSIENT_FAILURE,new eY.UnavailablePicker($.error),$.error.details);return!0}if($.value.length===0){let U=`No addresses resolved. Resolution note: ${Q}`;return this.updateState(y0.ConnectivityState.TRANSIENT_FAILURE,new eY.UnavailablePicker({details:U}),U),!1}V7("Connect to endpoint list "+$.value.map(hV.endpointToString));let T=new Date,K=new Set;this.updatesPaused=!0,this.latestConfig=Y;for(let U of $.value){let G=(0,hV.endpointToString)(U);K.add(G);let W=this.children.get(G);if(!W)W={child:new Ow.LeafLoadBalancer(U,(0,gV.createChildChannelControlHelper)(this.channelControlHelper,{updateState:(R,V,A)=>{if(this.currentState===y0.ConnectivityState.READY&&R!==y0.ConnectivityState.READY)this.channelControlHelper.requestReresolution();if(R===y0.ConnectivityState.READY)W.nonEmptySince=null;if(A)this.lastError=A;this.calculateAndUpdateState()},createSubchannel:(R,V)=>{let A=this.channelControlHelper.createSubchannel(R,V);if(W===null||W===void 0?void 0:W.oobMetricsListener)return new fV.OrcaOobMetricsSubchannelWrapper(A,W.oobMetricsListener,this.latestConfig.getOobLoadReportingPeriodMs());else return A}}),X,Q),lastUpdated:T,nonEmptySince:null,weight:0,oobMetricsListener:null},this.children.set(G,W);if(Y.getEnableOobLoadReport())W.oobMetricsListener=(R)=>{this.updateWeight(W,R)};else W.oobMetricsListener=null}for(let[U,G]of this.children)if(K.has(U))G.child.startConnecting();else G.child.destroy(),this.children.delete(U);if(this.updatesPaused=!1,this.calculateAndUpdateState(),this.weightUpdateTimer)clearInterval(this.weightUpdateTimer);return this.weightUpdateTimer=(Z=(J=setInterval(()=>{if(this.currentState===y0.ConnectivityState.READY)this.calculateAndUpdateState()},Y.getWeightUpdatePeriodMs())).unref)===null||Z===void 0?void 0:Z.call(J),!0}exitIdle(){}resetBackoff(){}destroy(){for(let $ of this.children.values())$.child.destroy();if(this.children.clear(),this.weightUpdateTimer)clearInterval(this.weightUpdateTimer)}getTypeName(){return A7}}function vw(){(0,gV.registerLoadBalancerType)(A7,bV,A8)}});var D8=M((Y0)=>{Object.defineProperty(Y0,"__esModule",{value:!0});Y0.experimental=Y0.ServerMetricRecorder=Y0.ServerInterceptingCall=Y0.ResponderBuilder=Y0.ServerListenerBuilder=Y0.addAdminServicesToServer=Y0.getChannelzHandlers=Y0.getChannelzServiceDefinition=Y0.InterceptorConfigurationError=Y0.InterceptingCall=Y0.RequesterBuilder=Y0.ListenerBuilder=Y0.StatusBuilder=Y0.getClientChannel=Y0.ServerCredentials=Y0.Server=Y0.setLogVerbosity=Y0.setLogger=Y0.load=Y0.loadObject=Y0.CallCredentials=Y0.ChannelCredentials=Y0.waitForClientReady=Y0.closeClient=Y0.Channel=Y0.makeGenericClientConstructor=Y0.makeClientConstructor=Y0.loadPackageDefinition=Y0.Client=Y0.compressionAlgorithms=Y0.propagate=Y0.connectivityState=Y0.status=Y0.logVerbosity=Y0.Metadata=Y0.credentials=void 0;var l4=I9();Object.defineProperty(Y0,"CallCredentials",{enumerable:!0,get:function(){return l4.CallCredentials}});var hw=t5();Object.defineProperty(Y0,"Channel",{enumerable:!0,get:function(){return hw.ChannelImplementation}});var _w=RJ();Object.defineProperty(Y0,"compressionAlgorithms",{enumerable:!0,get:function(){return _w.CompressionAlgorithms}});var gw=n0();Object.defineProperty(Y0,"connectivityState",{enumerable:!0,get:function(){return gw.ConnectivityState}});var i4=OY();Object.defineProperty(Y0,"ChannelCredentials",{enumerable:!0,get:function(){return i4.ChannelCredentials}});var cV=a5();Object.defineProperty(Y0,"Client",{enumerable:!0,get:function(){return cV.Client}});var D7=i();Object.defineProperty(Y0,"logVerbosity",{enumerable:!0,get:function(){return D7.LogVerbosity}});Object.defineProperty(Y0,"status",{enumerable:!0,get:function(){return D7.Status}});Object.defineProperty(Y0,"propagate",{enumerable:!0,get:function(){return D7.Propagate}});var nV=Z0(),F7=h9();Object.defineProperty(Y0,"loadPackageDefinition",{enumerable:!0,get:function(){return F7.loadPackageDefinition}});Object.defineProperty(Y0,"makeClientConstructor",{enumerable:!0,get:function(){return F7.makeClientConstructor}});Object.defineProperty(Y0,"makeGenericClientConstructor",{enumerable:!0,get:function(){return F7.makeClientConstructor}});var fw=P0();Object.defineProperty(Y0,"Metadata",{enumerable:!0,get:function(){return fw.Metadata}});var mw=g3();Object.defineProperty(Y0,"Server",{enumerable:!0,get:function(){return mw.Server}});var bw=j4();Object.defineProperty(Y0,"ServerCredentials",{enumerable:!0,get:function(){return bw.ServerCredentials}});var uw=u3();Object.defineProperty(Y0,"StatusBuilder",{enumerable:!0,get:function(){return uw.StatusBuilder}});Y0.credentials={combineChannelCredentials:($,...Y)=>{return Y.reduce((X,Q)=>X.compose(Q),$)},combineCallCredentials:($,...Y)=>{return Y.reduce((X,Q)=>X.compose(Q),$)},createInsecure:i4.ChannelCredentials.createInsecure,createSsl:i4.ChannelCredentials.createSsl,createFromSecureContext:i4.ChannelCredentials.createFromSecureContext,createFromMetadataGenerator:l4.CallCredentials.createFromMetadataGenerator,createFromGoogleCredential:l4.CallCredentials.createFromGoogleCredential,createEmpty:l4.CallCredentials.createEmpty};var dw=($)=>$.close();Y0.closeClient=dw;var pw=($,Y,X)=>$.waitForReady(Y,X);Y0.waitForClientReady=pw;var cw=($,Y)=>{throw Error("Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead")};Y0.loadObject=cw;var nw=($,Y,X)=>{throw Error("Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead")};Y0.load=nw;var lw=($)=>{nV.setLogger($)};Y0.setLogger=lw;var iw=($)=>{nV.setLoggerVerbosity($)};Y0.setLogVerbosity=iw;var rw=($)=>{return cV.Client.prototype.getChannel.call($)};Y0.getClientChannel=rw;var r4=o5();Object.defineProperty(Y0,"ListenerBuilder",{enumerable:!0,get:function(){return r4.ListenerBuilder}});Object.defineProperty(Y0,"RequesterBuilder",{enumerable:!0,get:function(){return r4.RequesterBuilder}});Object.defineProperty(Y0,"InterceptingCall",{enumerable:!0,get:function(){return r4.InterceptingCall}});Object.defineProperty(Y0,"InterceptorConfigurationError",{enumerable:!0,get:function(){return r4.InterceptorConfigurationError}});var lV=y$();Object.defineProperty(Y0,"getChannelzServiceDefinition",{enumerable:!0,get:function(){return lV.getChannelzServiceDefinition}});Object.defineProperty(Y0,"getChannelzHandlers",{enumerable:!0,get:function(){return lV.getChannelzHandlers}});var ow=v9();Object.defineProperty(Y0,"addAdminServicesToServer",{enumerable:!0,get:function(){return ow.addAdminServicesToServer}});var H7=lJ();Object.defineProperty(Y0,"ServerListenerBuilder",{enumerable:!0,get:function(){return H7.ServerListenerBuilder}});Object.defineProperty(Y0,"ResponderBuilder",{enumerable:!0,get:function(){return H7.ResponderBuilder}});Object.defineProperty(Y0,"ServerInterceptingCall",{enumerable:!0,get:function(){return H7.ServerInterceptingCall}});var sw=v4();Object.defineProperty(Y0,"ServerMetricRecorder",{enumerable:!0,get:function(){return sw.ServerMetricRecorder}});var aw=$7();Y0.experimental=aw;var tw=BJ(),ew=UV(),$C=DV(),YC=G8(),XC=BV(),QC=yV(),JC=pV(),ZC=y$();(()=>{tw.setup(),ew.setup(),$C.setup(),YC.setup(),XC.setup(),QC.setup(),JC.setup(),ZC.setup()})()});class TX{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor($){let Y=$.apiBaseUrl.trim();if(!Y)throw Error("apiBaseUrl is required");this.apiBaseUrl=Y,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 Y=await this.resolveUserId($);return this.request(`/api/v1/users/${encodeURIComponent(Y)}/balance`)}async fetchUsageTransactions($){let Y=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(Y)}/usages`)).items??[]}async fetchPaymentTransactions($){let Y=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(Y)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchOrganizationBalance($){let Y=$.trim();if(!Y)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(Y)}/balance`)}async fetchOrganizationUsageTransactions($){let Y=$.organizationId.trim();if(!Y)throw Error("organizationId is required");let X=await this.resolveOrganizationMemberId(Y,$.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent(Y)}/members/${encodeURIComponent(X)}/usages`)).items??[]}async switchAccount($){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:$?.trim()||null},expectNoContent:!0})}async resolveUserId($){let Y=$?.trim();if(Y)return Y;let Q=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(Q)return Q;let J=await this.fetchMe();if(!J.id?.trim())throw Error("Unable to resolve current user id");return J.id}async resolveOrganizationMemberId($,Y){let X=Y?.trim();if(X)return X;let J=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn($):void 0)?.trim();if(J)return J;let T=(await this.fetchUserOrganizations()).find((K)=>K.organizationId===$)?.memberId;if(!T?.trim())throw Error(`Unable to resolve memberId for organization ${$}`);return T}async request($,Y){let X=(await this.getAuthTokenFn())?.trim();if(!X)throw Error("No Cline account auth token found");let Q=this.getHeadersFn?await this.getHeadersFn():{},J=new AbortController,Z=setTimeout(()=>J.abort(),this.requestTimeoutMs);try{let T=await this.fetchImpl(new URL($,this.apiBaseUrl),{method:Y?.method??"GET",headers:{Authorization:`Bearer ${X}`,"Content-Type":"application/json",...Q??{}},body:Y?.body!==void 0?JSON.stringify(Y.body):void 0,signal:J.signal});if(T.status===204||Y?.expectNoContent){if(!T.ok)throw Error(`Cline account request failed with status ${T.status}`);return}let K=await T.text(),U;if(K.trim())U=JSON.parse(K);if(!T.ok){let G=typeof U==="object"&&U!==null&&"error"in U?String(U.error):`Cline account request failed with status ${T.status}`;throw Error(G)}if(typeof U==="object"&&U!==null){let G=U;if(typeof G.success==="boolean"){if(!G.success)throw Error(G.error||"Cline account request failed");if(G.data!==void 0)return G.data}}if(U===void 0||U===null)throw Error("Cline account response payload was empty");return U}finally{clearTimeout(Z)}}}function h7($){return $.action==="clineAccount"}async function _7($,Y){switch($.operation){case"fetchMe":return Y.fetchMe();case"fetchBalance":return Y.fetchBalance($.userId);case"fetchUsageTransactions":return Y.fetchUsageTransactions($.userId);case"fetchPaymentTransactions":return Y.fetchPaymentTransactions($.userId);case"fetchUserOrganizations":return Y.fetchUserOrganizations();case"fetchOrganizationBalance":return Y.fetchOrganizationBalance($.organizationId);case"fetchOrganizationUsageTransactions":return Y.fetchOrganizationUsageTransactions({organizationId:$.organizationId,memberId:$.memberId});case"switchAccount":return await Y.switchAccount($.organizationId),{updated:!0};default:throw Error(`Unsupported Cline account operation: ${String($)}`)}}class KX{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 Y=$.trim();if(!Y)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:Y})}async fetchOrganizationUsageTransactions($){let Y=$.organizationId.trim();if(!Y)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:Y,...$.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{existsSync as yA,mkdirSync as jA}from"node:fs";import{dirname as xA,join as K0}from"node:path";var I8="agents",J6="hooks",F1="skills",Z6="rules",T6="workflows",UX="plugins",g7="cline_mcp_settings.json",_$=process?.env?.HOME||"~",vA=!1;function GX($){if(vA)return;let Y=$.trim();if(!Y)return;_$=Y}function K6(){return K0(_$,"Documents","Cline")}function O8(){return K0(K6(),"Agents")}function U6(){return K0(K6(),"Hooks")}function G6(){return K0(K6(),"Rules")}function W6(){return K0(K6(),"Workflows")}function H1(){let $=process.env.CLINE_DATA_DIR?.trim();if($)return $;return K0(_$,".cline","data")}function g$(){let $=process.env.CLINE_SESSION_DATA_DIR?.trim();if($)return $;return K0(H1(),"sessions")}function P8(){let $=process.env.CLINE_TEAM_DATA_DIR?.trim();if($)return $;return K0(H1(),"teams")}function WX(){let $=process.env.CLINE_PROVIDER_SETTINGS_PATH?.trim();if($)return $;return K0(H1(),"settings","providers.json")}function RX(){let $=process.env.CLINE_MCP_SETTINGS_PATH?.trim();if($)return $;return K0(H1(),"settings",g7)}function R6($){let Y=new Set,X=[];for(let Q of $){if(!Q||Y.has(Q))continue;Y.add(Q),X.push(Q)}return X}function kA($){if(!$)return[];return[K0($,".clinerules",F1),K0($,".cline",F1),K0($,".claude",F1),K0($,".agents",F1)]}function EX(){return K0(H1(),"settings",I8)}function VX(){return[O8(),EX()]}function AX($){return R6([$?K0($,".clinerules",J6):"",U6()])}function E6($){return R6([...kA($),K0(H1(),"settings",F1),K0(_$,".cline",F1),K0(_$,".agents",F1)])}function DX($){return R6([$?K0($,".clinerules"):"",K0(H1(),"settings",Z6),G6()])}function FX($){return R6([$?K0($,".clinerules","workflows"):"",K0(H1(),"settings",T6),W6()])}function HX($){return R6([$?K0($,".clinerules",UX):"",K0(_$,".cline",UX),K0(_$,".agents",UX)])}function zX($){let Y=xA($);if(!yA(Y))jA(Y,{recursive:!0})}import ID from"yaml";import{z as U1}from"zod";import{z as V$}from"zod";var f7=V$.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"]),hA=V$.object({adapter:V$.string(),botUserName:V$.string().optional(),event:f7,payload:V$.record(V$.string(),V$.unknown()),ts:V$.string()});var m7=[{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 _A($){return Object.fromEntries(m7.flatMap((Y)=>{let X=$==="modelsDevKey"?Y.modelsDevKey:Y.generatedProviderId;return X?[[Y.modelsDevKey,X]]:[]}))}var gA=_A("generatedProviderId");import{z as x0}from"zod";var fA=x0.object({agentId:x0.string(),conversationId:x0.string(),iteration:x0.number(),abortSignal:x0.custom().optional(),metadata:x0.record(x0.string(),x0.unknown()).optional()}),mA=x0.object({id:x0.string(),name:x0.string(),input:x0.unknown(),output:x0.unknown(),error:x0.string().optional(),durationMs:x0.number(),startedAt:x0.date(),endedAt:x0.date()});import{z as b7}from"zod";function z1($,Y){let X=$.safeParse(Y);if(!X.success)throw Error(b7.prettifyError(X.error));return X.data}function q1($){return b7.toJSONSchema($)}function L8($,Y="act"){return`<user_input mode="${Y}">${$}</user_input>`}function qX($){if(!$?.trim())return"";return u7($,"user_input")}function u7($,Y){if(!$?.trim())return"";if(!Y)return $;let X=new RegExp(`<${Y}.*?>(.*?)</${Y}>`,"g");return $.replace(X,"$1")}var NX="runtime.team.progress.v1",MX="runtime.team.lifecycle.v1";function bA($){let Y=$?.trim();return Y?Y:void 0}function S8($){return bA($?.rootSessionId)}var BX=["running","completed","failed","cancelled"];var j1={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"},f$=[j1.READ_FILES,j1.SEARCH_CODEBASE,j1.RUN_COMMANDS,j1.FETCH_WEB_CONTENT,j1.APPLY_PATCH,j1.EDITOR,j1.SKILLS,j1.ASK];import{createTool as A$}from"@clinebot/agents";import{z as b}from"zod";var uA=b.string().describe("The absolute file path of a text file to read content from"),w8=b.object({file_paths:b.array(uA).describe("Array of absolute file paths")}),d7=b.union([w8,b.array(b.string()),b.string()]),C8=b.object({queries:b.array(b.string()).describe("Array of regex search queries to execute")}),IX=b.string(),y8=b.object({commands:b.array(IX).describe("Array of shell commands to execute")}),p7=b.union([y8,b.array(IX),IX]),c7=b.object({url:b.url().describe("The URL to fetch"),prompt:b.string().min(2).describe("Analysis prompt for the fetched content")}),j8=b.object({requests:b.array(c7).describe("Array of web fetch requests")}),x8=b.object({command:b.enum(["create","str_replace","insert"]).describe("Editor command to execute: create, str_replace, insert, or undo_edit"),path:b.string().min(1).describe("Absolute file path"),file_text:b.string().optional().describe("Full file content used with create"),old_str:b.string().optional().describe("Exact text to replace (must match exactly once)"),new_str:b.string().optional().describe("Replacement or inserted text"),insert_line:b.number().int().optional().describe("Zero-based line index for insert")}).superRefine(($,Y)=>{switch($.command){case"create":if($.file_text===void 0)Y.addIssue({code:b.ZodIssueCode.custom,path:["file_text"],message:"file_text is required for command=create"});break;case"str_replace":if($.old_str===void 0)Y.addIssue({code:b.ZodIssueCode.custom,path:["old_str"],message:"old_str is required for command=str_replace"});break;case"insert":if($.insert_line===void 0)Y.addIssue({code:b.ZodIssueCode.custom,path:["insert_line"],message:"insert_line is required for command=insert"});if($.new_str===void 0)Y.addIssue({code:b.ZodIssueCode.custom,path:["new_str"],message:"new_str is required for command=insert"});break}}),v8=b.object({input:b.string().min(1).describe("The apply_patch text payload, including patch instructions")}),n7=b.union([v8,b.string()]),k8=b.object({skill:b.string().min(1).describe('The skill name. E.g., "commit", "review-pr", "pdf", or "ms-office-suite:pdf"'),args:b.string().optional().describe("Optional arguments for the skill")}),h8=b.object({question:b.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:b.array(b.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")});function UY($){if($ instanceof Error)return $.message;return String($)}function D$($,Y,X){return Promise.race([$,new Promise((Q,J)=>{setTimeout(()=>J(Error(X)),Y)})])}var dA=`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":
|
|
22
|
+
|
|
23
|
+
%%bash
|
|
24
|
+
apply_patch <<"EOF"
|
|
25
|
+
*** Begin Patch
|
|
26
|
+
[YOUR_PATCH]
|
|
27
|
+
*** End Patch
|
|
28
|
+
EOF
|
|
29
|
+
|
|
30
|
+
Where [YOUR_PATCH] is the actual content of your patch, specified in the following V4A diff format.
|
|
31
|
+
|
|
32
|
+
*** [ACTION] File: [path/to/file] -> ACTION can be one of Add, Update, or Delete.
|
|
33
|
+
|
|
34
|
+
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
|
|
35
|
+
In a Update/Delete section, repeat the following for each snippet of code that needs to be changed:
|
|
36
|
+
[context_before] -> See below for further instructions on context.
|
|
37
|
+
- [old_code] -> Precede the old code with a minus sign.
|
|
38
|
+
+ [new_code] -> Precede the new, replacement code with a plus sign.
|
|
39
|
+
[context_after] -> See below for further instructions on context.
|
|
40
|
+
|
|
41
|
+
For instructions on [context_before] and [context_after]:
|
|
42
|
+
- 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.
|
|
43
|
+
- 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:
|
|
44
|
+
@@ class BaseClass
|
|
45
|
+
[3 lines of pre-context]
|
|
46
|
+
- [old_code]
|
|
47
|
+
+ [new_code]
|
|
48
|
+
[3 lines of post-context]
|
|
49
|
+
|
|
50
|
+
- 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:
|
|
51
|
+
|
|
52
|
+
@@ class BaseClass
|
|
53
|
+
@@ def method():
|
|
54
|
+
[3 lines of pre-context]
|
|
55
|
+
- [old_code]
|
|
56
|
+
+ [new_code]
|
|
57
|
+
[3 lines of post-context]
|
|
58
|
+
|
|
59
|
+
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.
|
|
60
|
+
|
|
61
|
+
%%bash
|
|
62
|
+
apply_patch <<"EOF"
|
|
63
|
+
*** Begin Patch
|
|
64
|
+
*** Update File: pygorithm/searching/binary_search.py
|
|
65
|
+
@@ class BaseClass
|
|
66
|
+
@@ def search():
|
|
67
|
+
- pass
|
|
68
|
+
+ raise NotImplementedError()
|
|
69
|
+
|
|
70
|
+
@@ class Subclass
|
|
71
|
+
@@ def search():
|
|
72
|
+
- pass
|
|
73
|
+
+ raise NotImplementedError()
|
|
74
|
+
|
|
75
|
+
*** End Patch
|
|
76
|
+
EOF`;function l7($,Y={}){let X=Y.fileReadTimeoutMs??1e4;return A$({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:q1(w8),timeoutMs:X*2,retryable:!0,maxRetries:1,execute:async(Q,J)=>{let Z=z1(d7,Q),T=Array.isArray(Z)?Z:typeof Z==="object"?Z.file_paths:[Z];return Promise.all(T.map(async(K)=>{try{let U=await D$($(K,J),X,`File read timed out after ${X}ms`);return{query:K,result:U,success:!0}}catch(U){let G=UY(U);return{query:K,result:"",error:`Error reading file: ${G}`,success:!1}}}))}})}function i7($,Y={}){let X=Y.searchTimeoutMs??30000,Q=Y.cwd??process.cwd();return A$({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:q1(C8),timeoutMs:X*2,retryable:!0,maxRetries:1,execute:async(J,Z)=>{let T=z1(C8,J);return Promise.all(T.queries.map(async(K)=>{try{let U=await D$($(K,Q,Z),X,`Search timed out after ${X}ms`),G=U.length>0&&!U.includes("No results found");return{query:K,result:U,success:G}}catch(U){let G=UY(U);return{query:K,result:"",error:`Search failed: ${G}`,success:!1}}}))}})}function r7($,Y={}){let X=Y.bashTimeoutMs??30000,Q=Y.cwd??process.cwd();return A$({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:q1(y8),timeoutMs:X*2,retryable:!1,maxRetries:0,execute:async(J,Z)=>{let T=z1(p7,J),K=Array.isArray(T)?T:typeof T==="object"?T.commands:[T];return Promise.all(K.map(async(U)=>{try{let G=await D$($(U,Q,Z),X,`Command timed out after ${X}ms`);return{query:U,result:G,success:!0}}catch(G){let W=UY(G);return{query:U,result:"",error:`Command failed: ${W}`,success:!1}}}))}})}function o7($,Y={}){let X=Y.webFetchTimeoutMs??30000;return A$({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:q1(j8),timeoutMs:X*2,retryable:!0,maxRetries:2,execute:async(Q,J)=>{let Z=z1(j8,Q);return Promise.all(Z.requests.map(async(T)=>{try{let K=await D$($(T.url,T.prompt,J),X,`Web fetch timed out after ${X}ms`);return{query:T.url,result:K,success:!0}}catch(K){let U=UY(K);return{query:T.url,result:"",error:`Error fetching web content: ${U}`,success:!1}}}))}})}function s7($,Y={}){let X=Y.applyPatchTimeoutMs??30000,Q=Y.cwd??process.cwd();return A$({name:"apply_patch",description:dA,inputSchema:q1(v8),timeoutMs:X,retryable:!1,maxRetries:0,execute:async(J,Z)=>{let T=z1(n7,J),K=typeof T==="string"?T:T.input;try{return{query:"apply_patch",result:await D$($({input:K},Q,Z),X,`apply_patch timed out after ${X}ms`),success:!0}}catch(U){return{query:"apply_patch",result:"",error:`apply_patch failed: ${UY(U)}`,success:!1}}}})}function a7($,Y={}){let X=Y.editorTimeoutMs??30000,Q=Y.cwd??process.cwd();return A$({name:"editor",description:"Edit file using absolute path with create, string replacement, and line insert operations. Supported commands: create, str_replace, insert, undo_edit.",inputSchema:q1(x8),timeoutMs:X,retryable:!1,maxRetries:0,execute:async(J,Z)=>{let T=z1(x8,J);try{let K=await D$($(T,Q,Z),X,`Editor operation timed out after ${X}ms`);return{query:`${T.command}:${T.path}`,result:K,success:!0}}catch(K){let U=UY(K);return{query:`${T.command}:${T.path}`,result:"",error:`Editor operation failed: ${U}`,success:!1}}}})}function t7($,Y={}){let X=Y.skillsTimeoutMs??15000;return A$({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:q1(k8),timeoutMs:X,retryable:!1,maxRetries:0,execute:async(Q,J)=>{let Z=z1(k8,Q);return D$($(Z.skill,Z.args,J),X,`Skills operation timed out after ${X}ms`)}})}function e7($,Y={}){let X=Y.askQuestionTimeoutMs??15000;return A$({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:q1(h8),timeoutMs:X,retryable:!1,maxRetries:0,execute:async(Q,J)=>{let Z=z1(h8,Q);return D$($(Z.question,Z.options,J),X,`ask_question timed out after ${X}ms`)}})}function GY($){let{executors:Y,enableReadFiles:X=!0,enableSearch:Q=!0,enableBash:J=!0,enableWebFetch:Z=!0,enableApplyPatch:T=!1,enableEditor:K=!0,enableSkills:U=!0,enableAskQuestion:G=!0,...W}=$,R=[];if(X&&Y.readFile)R.push(l7(Y.readFile,W));if(Q&&Y.search)R.push(i7(Y.search,W));if(J&&Y.bash)R.push(r7(Y.bash,W));if(Z&&Y.webFetch)R.push(o7(Y.webFetch,W));if(K&&Y.editor)R.push(a7(Y.editor,W));else if(T&&Y.applyPatch)R.push(s7(Y.applyPatch,W));if(U&&Y.skills)R.push(t7(Y.skills,W));if(G&&Y.askQuestion)R.push(e7(Y.askQuestion,W));return R}import*as T1 from"node:fs/promises";import*as K1 from"node:path";var l={BEGIN:"*** Begin Patch",END:"*** End Patch",ADD:"*** Add File: ",UPDATE:"*** Update File: ",DELETE:"*** Delete File: ",MOVE:"*** Move to: ",SECTION:"@@",END_FILE:"*** End of File"},YZ=["%%bash","apply_patch","EOF","```"];class I0 extends Error{constructor($){super($);this.name="DiffError"}}function Z1($){let Y={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return $.normalize("NFC").replace(/./gu,(X)=>Y[X]??X).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class OX{lines;currentFiles;patch={actions:{},warnings:[]};index=0;fuzz=0;currentPath;constructor($,Y){this.lines=$;this.currentFiles=Y}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(l.BEGIN))this.index++}hasMoreLines(){return this.index<this.lines.length}isEndMarker(){return this.lines[this.index]?.startsWith(l.END)??!1}parseNextAction(){let $=this.lines[this.index];if($?.startsWith(l.UPDATE)){this.parseUpdate($.substring(l.UPDATE.length).trim());return}if($?.startsWith(l.DELETE)){this.parseDelete($.substring(l.DELETE.length).trim());return}if($?.startsWith(l.ADD)){this.parseAdd($.substring(l.ADD.length).trim());return}throw new I0(`Unknown line while parsing: ${$}`)}checkDuplicate($,Y){if($ in this.patch.actions)throw new I0(`Duplicate ${Y} for file: ${$}`)}parseUpdate($){this.checkDuplicate($,"update"),this.currentPath=$,this.index++;let Y=this.lines[this.index]?.startsWith(l.MOVE)?(this.lines[this.index++]??"").substring(l.MOVE.length).trim():void 0;if(!($ in this.currentFiles))throw new I0(`Update File Error: Missing File: ${$}`);let X=this.currentFiles[$]??"",Q=this.parseUpdateFile(X,$);Q.movePath=Y,this.patch.actions[$]=Q,this.currentPath=void 0}parseUpdateFile($,Y){let X={type:"update",chunks:[]},Q=$.split(`
|
|
77
|
+
`),J=0,Z=[l.END,l.UPDATE,l.DELETE,l.ADD,l.END_FILE];while(!Z.some((T)=>this.lines[this.index]?.startsWith(T.trim()))){let T=this.lines[this.index],K=T?.startsWith("@@ ")?T.substring(3):void 0;if(K!==void 0||(T==="@@"?T:void 0)!==void 0)this.index++;else if(J!==0)throw new I0(`Invalid Line:
|
|
78
|
+
${this.lines[this.index]}`);if(K?.trim()){let D=Z1(K.trim());for(let B=J;B<Q.length;B++){let w=Q[B];if(w&&(Z1(w)===D||Z1(w.trim())===D)){if(J=B+1,Z1(w.trim())===D&&Z1(w)!==D)this.fuzz++;break}}}let[G,W,R,V]=nA(this.lines,this.index),[A,H,z]=cA(Q,G,J,V);if(A===-1){let D=G.join(`
|
|
79
|
+
`);this.addWarning({path:this.currentPath||Y,chunkIndex:X.chunks.length,message:`Could not find matching context (similarity: ${z.toFixed(2)}). Chunk skipped.`,context:D.length>200?`${D.substring(0,200)}...`:D}),this.index=R}else{this.fuzz+=H;for(let D of W)D.origIndex+=A,X.chunks.push(D);J=A+G.length,this.index=R}}return X}parseDelete($){if(this.checkDuplicate($,"delete"),!($ in this.currentFiles))throw new I0(`Delete File Error: Missing File: ${$}`);this.patch.actions[$]={type:"delete",chunks:[]},this.index++}parseAdd($){if(this.checkDuplicate($,"add"),$ in this.currentFiles)throw new I0(`Add File Error: File already exists: ${$}`);this.index++;let Y=[],X=[l.END,l.UPDATE,l.DELETE,l.ADD];while(this.hasMoreLines()&&!X.some((Q)=>this.lines[this.index]?.startsWith(Q.trim()))){let Q=this.lines[this.index++];if(Q===void 0)break;if(!Q.startsWith("+"))throw new I0(`Invalid Add File line (missing '+'): ${Q}`);Y.push(Q.substring(1))}this.patch.actions[$]={type:"add",newFile:Y.join(`
|
|
80
|
+
`),chunks:[]}}}function $Z($,Y){let X=$.length>Y.length?$:Y,Q=$.length>Y.length?Y:$;if(X.length===0)return 1;let J=pA(Q,X);return(X.length-J)/X.length}function pA($,Y){let X=Y.length+1,Q=$.length+1,J=Array(X*Q).fill(0),Z=(K,U)=>J[K*Q+U]??0,T=(K,U,G)=>{J[K*Q+U]=G};for(let K=0;K<=Y.length;K++)T(K,0,K);for(let K=0;K<=$.length;K++)T(0,K,K);for(let K=1;K<=Y.length;K++)for(let U=1;U<=$.length;U++)if(Y[K-1]===$[U-1])T(K,U,Z(K-1,U-1));else T(K,U,1+Math.min(Z(K-1,U-1),Z(K,U-1),Z(K-1,U)));return Z(Y.length,$.length)}function cA($,Y,X,Q){if(Y.length===0)return[X,0,1];let J=0,Z=(T)=>{let K=Z1(Y.join(`
|
|
81
|
+
`));for(let G=T;G<$.length;G++){let W=Z1($.slice(G,G+Y.length).join(`
|
|
82
|
+
`));if(W===K)return[G,0,1];let R=$Z(W,K);if(R>J)J=R}for(let G=T;G<$.length;G++){let W=Z1($.slice(G,G+Y.length).map((V)=>V.trimEnd()).join(`
|
|
83
|
+
`)),R=Z1(Y.map((V)=>V.trimEnd()).join(`
|
|
84
|
+
`));if(W===R)return[G,1,1]}for(let G=T;G<$.length;G++){let W=Z1($.slice(G,G+Y.length).map((V)=>V.trim()).join(`
|
|
85
|
+
`)),R=Z1(Y.map((V)=>V.trim()).join(`
|
|
86
|
+
`));if(W===R)return[G,100,1]}let U=0.66;for(let G=T;G<$.length;G++){let W=Z1($.slice(G,G+Y.length).join(`
|
|
87
|
+
`)),R=$Z(W,K);if(R>=U)return[G,1000,R];if(R>J)J=R}return[-1,0,J]};if(Q){let[T,K,U]=Z($.length-Y.length);if(T!==-1)return[T,K,U];return[T,K,U]=Z(X),[T,K+1e4,U]}return Z(X)}function nA($,Y){let X=Y,Q=[],J=[],Z=[],T=[],K="keep",U=["@@",l.END,l.UPDATE,l.DELETE,l.ADD,l.END_FILE];while(X<$.length){let G=$[X];if(!G||U.some((V)=>G.startsWith(V.trim())))break;if(G==="***")break;if(G.startsWith("***"))throw new I0(`Invalid line: ${G}`);X++;let W=K,R=G;if(R[0]==="+")K="add";else if(R[0]==="-")K="delete";else if(R[0]===" ")K="keep";else K="keep",R=` ${R}`;if(R=R.slice(1),K==="keep"&&W!==K){if(Z.length||J.length)T.push({origIndex:Q.length-J.length,delLines:J,insLines:Z});J=[],Z=[]}if(K==="delete")J.push(R),Q.push(R);else if(K==="add")Z.push(R);else Q.push(R)}if(Z.length||J.length)T.push({origIndex:Q.length-J.length,delLines:J,insLines:Z});if(X<$.length&&$[X]===l.END_FILE)return X++,[Q,T,X,!0];return[Q,T,X,!1]}function PX($,Y,X){let Q=K1.isAbsolute(Y),J=Q?K1.normalize(Y):K1.resolve($,Y);if(!X||Q)return J;let Z=K1.relative($,J);if(Z.startsWith("..")||K1.isAbsolute(Z))throw new I0(`Path must stay within cwd: ${Y}`);return J}function XZ($){let Y=[],X=!1,Q=!1,J=!1;for(let Z=0;Z<$.length;Z++){let T=$[Z];if(!X&&YZ.some((U)=>T.startsWith(U)))continue;if(T.startsWith(l.BEGIN)){X=!0,Q=!0,Y.push(T);continue}if(T===l.END){X=!1,Y.push(T);continue}let K=T.startsWith(l.ADD)||T.startsWith(l.UPDATE)||T.startsWith(l.DELETE)||T.startsWith(l.MOVE)||T.startsWith(l.SECTION)||T.startsWith("+")||T.startsWith("-")||T.startsWith(" ")||T==="***";if(K&&Z!==$.length-1)J=!0;if(X||!Q&&K||T===""&&J)Y.push(T)}while(Y.length>0&&Y[Y.length-1]==="")Y.pop();return!Q&&!J?$:Y}function lA($){let Y=$.split(`
|
|
88
|
+
`).map((J)=>J.replace(/\r$/,""));Y=XZ(Y);let X=Y.length>0&&Y[0].startsWith(l.BEGIN),Q=Y.length>0&&Y[Y.length-1]===l.END;if(!X&&!Q)return[l.BEGIN,...Y,l.END];if(X&&Q)return Y;throw new I0("Invalid patch text - incomplete sentinels. Try breaking it into smaller patches.")}function iA($,Y){let X=XZ($.split(`
|
|
89
|
+
`)),Q=[];for(let J of X)for(let Z of Y){if(!J.startsWith(Z))continue;let T=J.substring(Z.length).trim();if(!$.trim().endsWith(T))Q.push(T);break}return Q}function rA($,Y,X){if(Y.length===0)return $;let Q=$.split(`
|
|
90
|
+
`),J=[],Z=0;for(let T of Y){if(T.origIndex>Q.length)throw new I0(`${X}: chunk.origIndex ${T.origIndex} > lines.length ${Q.length}`);if(Z>T.origIndex)throw new I0(`${X}: currentIndex ${Z} > chunk.origIndex ${T.origIndex}`);J.push(...Q.slice(Z,T.origIndex)),J.push(...T.insLines),Z=T.origIndex+T.delLines.length}return J.push(...Q.slice(Z)),J.join(`
|
|
91
|
+
`)}async function oA($,Y,X,Q){let J=iA($,[l.UPDATE,l.DELETE]),Z={};for(let T of J){let K=PX(Y,T,Q),U;try{U=await T1.readFile(K,X)}catch{throw new I0(`File not found: ${T}`)}Z[T]=U.replace(/\r\n/g,`
|
|
92
|
+
`)}return Z}function sA($,Y){let X={};for(let[Q,J]of Object.entries($.actions))switch(J.type){case"delete":X[Q]={type:"delete",oldContent:Y[Q]};break;case"add":if(J.newFile===void 0)throw new I0("ADD action without file content");X[Q]={type:"add",newContent:J.newFile};break;case"update":X[Q]={type:"update",oldContent:Y[Q],newContent:rA(Y[Q]??"",J.chunks,Q),movePath:J.movePath};break}return X}async function aA($,Y,X,Q){let J=[];for(let[Z,T]of Object.entries($)){let K=PX(Y,Z,Q);switch(T.type){case"delete":await T1.rm(K,{force:!0}),J.push(`${Z}: [deleted]`);break;case"add":if(T.newContent===void 0)throw new I0(`Cannot create ${Z} with no content`);await T1.mkdir(K1.dirname(K),{recursive:!0}),await T1.writeFile(K,T.newContent,{encoding:X}),J.push(Z);break;case"update":{if(T.newContent===void 0)throw new I0(`UPDATE change for ${Z} has no new content`);if(T.movePath){let U=PX(Y,T.movePath,Q);await T1.mkdir(K1.dirname(U),{recursive:!0}),await T1.writeFile(U,T.newContent,{encoding:X}),await T1.rm(K,{force:!0}),J.push(`${Z} -> ${T.movePath}`)}else await T1.writeFile(K,T.newContent,{encoding:X}),J.push(Z);break}}}return J}function _8($={}){let{encoding:Y="utf-8",restrictToCwd:X=!0}=$;return async(Q,J,Z)=>{let T=lA(Q.input),K=await oA(Q.input,J,Y,X),U=new OX(T,K),{patch:G,fuzz:W}=U.parse(),R=sA(G,K),V=await aA(R,J,Y,X),A=["Successfully applied patch to the following files:"];for(let H of V)A.push(H);if(W>0)A.push(`Note: Patch applied with fuzz factor ${W}`);if(G.warnings&&G.warnings.length>0)for(let H of G.warnings)A.push(`Warning (${H.path}): ${H.message}`);return A.join(`
|
|
93
|
+
`)}}import{spawn as QZ}from"node:child_process";function g8($={}){let{shell:Y=process.platform==="win32"?"cmd.exe":"/bin/bash",timeoutMs:X=30000,maxOutputBytes:Q=1e6,env:J={},combineOutput:Z=!0}=$;return async(T,K,U)=>{return new Promise((G,W)=>{let R=process.platform==="win32"?["/c",T]:["-c",T],V=process.platform==="win32",A=QZ(Y,R,{cwd:K,env:{...process.env,...J},stdio:["pipe","pipe","pipe"],detached:!V}),H=A.pid,z="",D="",B=0,w=!1,x=!1,q=(y)=>{if(x)return;x=!0,W(y)},_=(y)=>{if(x)return;x=!0,G(y)},C=()=>{if(!H)return;if(V){QZ("taskkill",["/pid",String(H),"/T","/F"],{stdio:"ignore",windowsHide:!0}).unref();return}try{process.kill(-H,"SIGKILL")}catch{A.kill("SIGKILL")}},k=setTimeout(()=>{w=!0,C(),q(Error(`Command timed out after ${X}ms`))},X),f=()=>{w=!0,C(),q(Error("Command was aborted"))};if(U.abortSignal)U.abortSignal.addEventListener("abort",f);A.stdout?.on("data",(y)=>{if(B+=y.length,B<=Q)z+=y.toString()}),A.stderr?.on("data",(y)=>{if(B+=y.length,B<=Q)D+=y.toString()}),A.on("close",(y)=>{if(clearTimeout(k),U.abortSignal)U.abortSignal.removeEventListener("abort",f);if(w)return;let j=Z?z+(D?`
|
|
94
|
+
[stderr]
|
|
95
|
+
${D}`:""):z;if(B>Q)j+=`
|
|
96
|
+
|
|
97
|
+
[Output truncated: ${B} bytes total, showing first ${Q} bytes]`;if(y!==0){let N=D||`Command exited with code ${y}`;q(Error(N))}else _(j)}),A.on("error",(y)=>{if(clearTimeout(k),U.abortSignal)U.abortSignal.removeEventListener("abort",f);q(Error(`Failed to execute command: ${y.message}`))})})}}import*as a1 from"node:fs/promises";import*as N1 from"node:path";function tA($,Y,X){let Q=N1.isAbsolute(Y),J=Q?N1.normalize(Y):N1.resolve($,Y);if(!X)return J;if(Q)return J;let Z=N1.relative($,J);if(Z.startsWith("..")||N1.isAbsolute(Z))throw Error(`Path must stay within cwd: ${Y}`);return J}function eA($,Y){if(Y.length===0)return 0;return $.split(Y).length-1}function $D($,Y,X){let Q=$.split(`
|
|
98
|
+
`),J=Y.split(`
|
|
99
|
+
`),Z=Math.max(Q.length,J.length),T=["```diff"],K=0;for(let U=0;U<Z;U++){if(K>=X){T.push("... diff truncated ...");break}let G=Q[U],W=J[U];if(G===W)continue;let R=U+1;if(G!==void 0)T.push(`-${R}: ${G}`),K++;if(W!==void 0&&K<X)T.push(`+${R}: ${W}`),K++}return T.push("```"),T.join(`
|
|
100
|
+
`)}async function YD($,Y,X){return await a1.mkdir(N1.dirname($),{recursive:!0}),await a1.writeFile($,Y,{encoding:X}),`File created successfully at: ${$}`}async function XD($,Y,X,Q,J){let Z=await a1.readFile($,Q),T=eA(Z,Y);if(T===0)throw Error(`No replacement performed: text not found in ${$}.`);if(T>1)throw Error(`No replacement performed: multiple occurrences of text found in ${$}.`);let K=Z.replace(Y,X??"");await a1.writeFile($,K,{encoding:Q});let U=$D(Z,K,J);return`Edited ${$}
|
|
101
|
+
${U}`}async function QD($,Y,X,Q){let Z=(await a1.readFile($,Q)).split(`
|
|
102
|
+
`);if(Y<0||Y>Z.length)throw Error(`Invalid line number: ${Y}. Valid range: 0-${Z.length}`);return Z.splice(Y,0,...X.split(`
|
|
103
|
+
`)),await a1.writeFile($,Z.join(`
|
|
104
|
+
`),{encoding:Q}),`Inserted content at line ${Y} in ${$}.`}function f8($={}){let{encoding:Y="utf-8",restrictToCwd:X=!0,maxDiffLines:Q=200}=$;return async(J,Z,T)=>{let K=tA(Z,J.path,X);switch(J.command){case"create":if(J.file_text===void 0)throw Error("Parameter `file_text` is required for command: create");return YD(K,J.file_text,Y);case"str_replace":if(J.old_str===void 0)throw Error("Parameter `old_str` is required for command: str_replace");return XD(K,J.old_str,J.new_str,Y,Q);case"insert":if(J.insert_line===void 0)throw Error("Parameter `insert_line` is required for insert command.");if(J.new_str===void 0)throw Error("Parameter `new_str` is required for insert command.");return QD(K,J.insert_line,J.new_str,Y);default:throw Error(`Unrecognized command ${J.command}. Allowed commands are: create, str_replace, insert`)}}}import*as m8 from"node:fs/promises";import*as WY from"node:path";function b8($={}){let{maxFileSizeBytes:Y=1e7,encoding:X="utf-8",includeLineNumbers:Q=!1}=$;return async(J,Z)=>{let T=WY.isAbsolute(J)?WY.normalize(J):WY.resolve(process.cwd(),J),K=await m8.stat(T);if(!K.isFile())throw Error(`Path is not a file: ${T}`);if(K.size>Y)throw Error(`File too large: ${K.size} bytes (max: ${Y} bytes). Consider reading specific sections or using a different approach.`);let U=await m8.readFile(T,X);if(Q){let G=U.split(`
|
|
105
|
+
`),W=String(G.length).length;return G.map((R,V)=>`${String(V+1).padStart(W," ")} | ${R}`).join(`
|
|
106
|
+
`)}return U}}import*as WZ from"node:fs/promises";import*as d8 from"node:path";import{spawn as JD}from"node:child_process";import{readdir as ZD}from"node:fs/promises";import SX from"node:path";import{isMainThread as TZ,parentPort as JZ,Worker as TD}from"node:worker_threads";var KD=15000,UD=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]),LX=new Map;function GD($,Y){return SX.relative($,Y).split(SX.sep).join("/")}async function WD($){let X=(await new Promise((Q,J)=>{let Z=JD("rg",["--files","--hidden","-g","!.git"],{cwd:$,stdio:["ignore","pipe","pipe"]}),T="",K="";Z.stdout.on("data",(U)=>{T+=U.toString()}),Z.stderr.on("data",(U)=>{K+=U.toString()}),Z.on("error",J),Z.on("close",(U)=>{if(U===0){Q(T);return}J(Error(K||`rg exited with code ${U}`))})})).split(/\r?\n/).map((Q)=>Q.trim()).filter((Q)=>Q.length>0).map((Q)=>Q.replace(/\\/g,"/"));return new Set(X)}async function KZ($,Y,X){let Q=await ZD(Y,{withFileTypes:!0});for(let J of Q){let Z=SX.join(Y,J.name);if(J.isDirectory()){if(UD.has(J.name))continue;await KZ($,Z,X);continue}if(J.isFile())X.add(GD($,Z))}}async function RD($){let Y=new Set;return await KZ($,$,Y),Y}async function wX($){try{return await WD($)}catch{return RD($)}}function ED(){if(TZ||!JZ)return;let $=JZ;$.on("message",(Y)=>{if(Y.type!=="index")return;wX(Y.cwd).then((X)=>{let Q={type:"indexResult",requestId:Y.requestId,files:Array.from(X)};$.postMessage(Q)}).catch((X)=>{let Q={type:"indexResult",requestId:Y.requestId,error:X instanceof Error?X.message:"Failed to build file index"};$.postMessage(Q)})})}class UZ{worker=new TD(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",($)=>{if($.type!=="indexResult")return;let Y=this.pending.get($.requestId);if(!Y)return;if(this.pending.delete($.requestId),$.error){Y.reject(Error($.error));return}Y.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 Y=++this.nextRequestId,X=new Promise((J,Z)=>{this.pending.set(Y,{resolve:J,reject:Z})}),Q={type:"index",requestId:Y,cwd:$};return this.worker.postMessage(Q),X}flushPending($){for(let[Y,X]of this.pending.entries())X.reject($),this.pending.delete(Y)}}ED();var ZZ=TZ?new UZ:null;async function VD($){if(!ZZ)return wX($);try{let Y=await ZZ.requestIndex($);return new Set(Y)}catch{return wX($)}}async function m$($,Y={}){let X=Y.ttlMs??KD,Q=Date.now(),J=LX.get($);if(J&&X>0&&Q-J.lastBuiltAt<=X&&J.files.size>0)return J.files;if(J?.pending)return J.pending;let Z=VD($).then((T)=>{return LX.set($,{files:T,lastBuiltAt:Date.now(),pending:null}),T});return LX.set($,{files:J?.files??new Set,lastBuiltAt:J?.lastBuiltAt??0,pending:Z}),Z}async function GZ($,Y={}){await m$($,{...Y,ttlMs:0})}import{stat as AD}from"node:fs/promises";import b$ from"node:path";var DD=/[),.:;!?`'"]+$/,FD=/^[(`'"]+/;function HD($){let Y=$.matchAll(/(^|[\s])@([^\s]+)/g),X=[];for(let Q of Y){let J=(Q[2]??"").trim();if(J.length===0)continue;let Z=J.replace(FD,"").replace(DD,"");if(Z.length===0||Z.includes("@"))continue;X.push(Z)}return Array.from(new Set(X))}function zD($,Y){let X=$.replace(/\\/g,"/"),Q=b$.isAbsolute(X)?b$.resolve(X):b$.resolve(Y,X),J=b$.relative(Y,Q);if(J.startsWith("..")||b$.isAbsolute(J))return;return J.split(b$.sep).join("/")}async function u8($,Y,X={}){let Q=HD($);if(Q.length===0)return{prompt:$,matchedFiles:[],ignoredMentions:[]};let{maxFiles:J,maxFileBytes:Z,maxTotalBytes:T}=X,K=await m$(Y,{ttlMs:X.ttlMs}),U=[],G=[],W=[],R=0;for(let V of Q){if(J&&W.length>=J){G.push(V);continue}let A=zD(V,Y);if(!A||!K.has(A)){G.push(V);continue}if(!Z||!T){U.push(A);continue}let H=b$.join(Y,A);try{if(!(await AD(H)).isFile()){G.push(V);continue}let D=R+Z;if(D>T){G.push(V);continue}R+=D,U.push(A)}catch{G.push(V)}}return{prompt:$,matchedFiles:U,ignoredMentions:G}}var qD=["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"],ND=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"];function MD($,Y,X,Q){let J=$.split("/"),Z=J[J.length-1]??"";if(J.length-1>Q)return!1;for(let U=0;U<J.length-1;U++)if(Y.has(J[U]??""))return!1;let K=d8.posix.extname(Z).slice(1).toLowerCase();return X.has(K)||!K&&!Z.startsWith(".")}function p8($={}){let{includeExtensions:Y=qD,excludeDirs:X=ND,maxResults:Q=100,contextLines:J=2,maxDepth:Z=20}=$,T=new Set(X),K=new Set(Y.map((U)=>U.toLowerCase()));return async(U,G,W)=>{let R;try{R=new RegExp(U,"gim")}catch(D){throw Error(`Invalid regex pattern: ${U}. ${D instanceof Error?D.message:""}`)}let V=[],A=0,H=await m$(G);for(let D of H){if(!MD(D,T,K,Z))continue;if(V.length>=Q)break;A++;let B=d8.join(G,D);try{let x=(await WZ.readFile(B,"utf-8")).split(`
|
|
107
|
+
`);for(let q=0;q<x.length;q++){let _=x[q];R.lastIndex=0;let C;while((C=R.exec(_))!==null){if(V.length>=Q)break;let k=Math.max(0,q-J),f=Math.min(x.length-1,q+J),y=[];for(let j=k;j<=f;j++){let N=j===q?">":" ";y.push(`${N} ${j+1}: ${x[j]}`)}if(V.push({file:D,line:q+1,column:C.index+1,match:C[0],context:y}),C.index===R.lastIndex)R.lastIndex++}}}catch{}}if(V.length===0)return`No results found for pattern: ${U}
|
|
108
|
+
Searched ${A} files.`;let z=[`Found ${V.length} result${V.length===1?"":"s"} for pattern: ${U}`,`Searched ${A} files.`,""];for(let D of V)z.push(`${D.file}:${D.line}:${D.column}`),z.push(...D.context),z.push("");if(V.length>=Q)z.push(`(Showing first ${Q} results. Refine your search for more specific results.)`);return z.join(`
|
|
109
|
+
`)}}function BD($){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,`
|
|
110
|
+
`).replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/&#(\d+);/g,(Y,X)=>String.fromCharCode(parseInt(X,10))).replace(/\s+/g," ").replace(/\n\s+/g,`
|
|
111
|
+
`).replace(/\n{3,}/g,`
|
|
112
|
+
|
|
113
|
+
`).trim()}function c8($={}){let{timeoutMs:Y=30000,maxResponseBytes:X=5000000,userAgent:Q="Mozilla/5.0 (compatible; AgentBot/1.0)",headers:J={},followRedirects:Z=!0}=$;return async(T,K,U)=>{let G;try{G=new URL(T)}catch{throw Error(`Invalid URL: ${T}`)}if(!["http:","https:"].includes(G.protocol))throw Error(`Invalid protocol: ${G.protocol}. Only http and https are supported.`);let W=new AbortController,R=setTimeout(()=>W.abort(),Y),V;if(U.abortSignal)V=()=>W.abort(),U.abortSignal.addEventListener("abort",V);try{let A=await fetch(T,{method:"GET",headers:{"User-Agent":Q,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",...J},redirect:Z?"follow":"manual",signal:W.signal});if(clearTimeout(R),!Z&&A.status>=300&&A.status<400)return`Redirect to: ${A.headers.get("location")}`;if(!A.ok)throw Error(`HTTP ${A.status}: ${A.statusText}`);let H=A.headers.get("content-type")||"",z=A.body?.getReader();if(!z)throw Error("Failed to read response body");let D=[],B=0;while(!0){let{done:k,value:f}=await z.read();if(k)break;if(B+=f.length,B>X)throw z.cancel(),Error(`Response too large: exceeded ${X} bytes`);D.push(f)}let w=new Uint8Array(B),x=0;for(let k of D)w.set(k,x),x+=k.length;let q=new TextDecoder("utf-8").decode(w),_;if(H.includes("text/html")||H.includes("application/xhtml"))_=BD(q);else if(H.includes("application/json"))try{let k=JSON.parse(q);_=JSON.stringify(k,null,2)}catch{_=q}else _=q;let C=[`URL: ${T}`,`Content-Type: ${H}`,`Size: ${B} bytes`,"","--- Content ---",_.slice(0,50000)];if(_.length>50000)C.push(`
|
|
114
|
+
[Content truncated: showing first 50000 of ${_.length} characters]`);return C.push("","--- Analysis Request ---",`Prompt: ${K}`),C.join(`
|
|
115
|
+
`)}catch(A){if(clearTimeout(R),A instanceof Error){if(A.name==="AbortError")throw Error(`Request timed out after ${Y}ms`);throw A}throw Error(`Fetch failed: ${String(A)}`)}finally{if(U.abortSignal&&V)U.abortSignal.removeEventListener("abort",V)}}}function n8($={}){return{readFile:b8($.fileRead),search:p8($.search),bash:g8($.bash),webFetch:c8($.webFetch),applyPatch:_8($.applyPatch),editor:f8($.editor)}}var t1={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 RZ($){if($!=="yolo")return{};let Y={enabled:!0,autoApprove:!0},X={"*":Y};for(let Q of f$)X[Q]=Y;return X}function EZ($,Y){let X=t1[$];return GY({...X,...Y})}function V6($={}){let{executorOptions:Y={},executors:X,...Q}=$,J={...n8(Y),...X??{}};return GY({...Q,executors:J})}var OD=U1.object({name:U1.string().trim().min(1),description:U1.string().trim().min(1),modelId:U1.string().trim().min(1).optional(),tools:U1.union([U1.string(),U1.array(U1.string())]).optional(),skills:U1.union([U1.string(),U1.array(U1.string())]).optional()}),PD=new Set(f$);function VZ($){return/\.(yaml|yml)$/i.test($)}function AZ($){return $.trim().toLowerCase()}function LD($){let Y=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,X=$.match(Y);if(!X)return{data:{},body:$,hadFrontmatter:!1};let[,Q,J]=X;try{let Z=ID.parse(Q);return{data:Z&&typeof Z==="object"&&!Array.isArray(Z)?Z:{},body:J,hadFrontmatter:!0}}catch(Z){let T=Z instanceof Error?Z.message:String(Z);return{data:{},body:$,hadFrontmatter:!0,parseError:T}}}function SD($){let Y=$.trim();if(!Y)throw Error("Tool name cannot be empty.");if(!PD.has(Y))throw Error(`Unknown tool '${Y}'. Expected one of: ${f$.join(", ")}.`);return Y}function wD($){if(!$)return[];let Y=Array.isArray($)?$:$.split(",");return Array.from(new Set(Y.map(SD)))}function CD($){let Y=$.trim();if(!Y)throw Error("Skill name cannot be empty.");return Y}function yD($){if($===void 0)return;let Y=Array.isArray($)?$:$.split(",");return Array.from(new Set(Y.map(CD)))}function RY($){let{data:Y,body:X,hadFrontmatter:Q,parseError:J}=LD($);if(J)throw Error(`Failed to parse YAML frontmatter: ${J}`);if(!Q)throw Error("Missing YAML frontmatter block in agent config file.");let Z=OD.parse(Y),T=X.trim();if(!T)throw Error("Missing system prompt body in agent config file.");return{name:Z.name,description:Z.description,modelId:Z.modelId,tools:wD(Z.tools),skills:yD(Z.skills),systemPrompt:T}}function l8($,Y){if($.length===0)return[];let X=new Map(Y.map((Q)=>[Q.name,Q]));return $.map((Q)=>{let J=X.get(Q);if(!J)throw Error(`Configured tool '${Q}' is unavailable. Available tools: ${Y.map((Z)=>Z.name).join(", ")}.`);return J})}function i8($,Y){let X={systemPrompt:$.systemPrompt};if($.modelId)X.modelId=$.modelId;if($.tools.length>0){if(!Y?.availableTools)throw Error("Configured tools cannot be converted into AgentConfig.tools without availableTools.");X.tools=l8($.tools,Y.availableTools)}return X}function CX($,Y){let X=RY($);return i8(X,Y)}import{createHash as jD}from"node:crypto";import{watch as xD}from"node:fs";import{readdir as vD,readFile as kD}from"node:fs/promises";import{join as hD}from"node:path";function _D($){return jD("sha1").update($).digest("hex")}function gD($){return Boolean($&&typeof $==="object"&&"code"in $)}function DZ($){return gD($)&&$.code==="ENOENT"}class u${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($,Y){if($.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=$,this.debounceMs=Y?.debounceMs??75,this.emitParseErrors=Y?.emitParseErrors??!1;for(let X of $){if(this.definitionsByType.has(X.type))throw Error(`Duplicate unified config definition type '${X.type}'.`);this.definitionsByType.set(X.type,X),this.recordsByType.set(X.type,new Map),this.discoveredDirectoriesByType.set(X.type,new Set);for(let Q of X.directories){let J=this.baseTypesByDirectory.get(Q);if(J)J.add(X.type);else this.baseTypesByDirectory.set(Q,new Set([X.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 Y=this.definitionsByType.get($);if(!Y)throw Error(`Unknown unified config type '${$}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal(Y)})}getSnapshot($){let Y=this.recordsByType.get($);return new Map([...Y?.entries()??[]].map(([X,Q])=>[X,{...Q}]))}getAllSnapshots(){let $=new Map;for(let[Y,X]of this.recordsByType.entries())$.set(Y,new Map([...X.entries()].map(([Q,J])=>[Q,{...J}])));return $}emit($){for(let Y of this.listeners)Y($)}enqueueRefresh($){return this.refreshQueue=this.refreshQueue.then($,$),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let $=this.buildDesiredTypesByDirectory();for(let[Y,X]of this.watchersByDirectory.entries()){if($.has(Y))continue;X.close(),this.watchersByDirectory.delete(Y)}this.watchedTypesByDirectory=$;for(let Y of $.keys()){if(this.watchersByDirectory.has(Y))continue;try{let X=xD(Y,()=>{let Q=this.watchedTypesByDirectory.get(Y);if(!Q)return;for(let J of Q)this.pendingTypes.add(J);this.scheduleFlush()});this.watchersByDirectory.set(Y,X),X.on("error",(Q)=>{let J=this.watchedTypesByDirectory.get(Y);if(!J)return;for(let Z of J)this.emit({kind:"error",type:Z,error:Q,filePath:Y})})}catch(X){if(!DZ(X)){let Q=$.get(Y);if(!Q)continue;for(let J of Q)this.emit({kind:"error",type:J,error:X,filePath:Y})}}}}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 Y of $){let X=this.definitionsByType.get(Y);if(!X)continue;await this.refreshTypeInternal(X)}})},this.debounceMs)}async refreshTypeInternal($){let{records:Y,discoveredDirectories:X}=await this.loadDefinition($),Q=this.recordsByType.get($.type)??new Map;for(let[J,Z]of Q.entries()){if(Y.has(J))continue;this.emit({kind:"remove",type:$.type,id:J,filePath:Z.filePath})}for(let[J,Z]of Y.entries()){let T=Q.get(J);if(T&&T.filePath===Z.filePath&&T.fingerprint===Z.fingerprint)continue;this.emit({kind:"upsert",record:{type:Z.type,id:J,item:Z.item,filePath:Z.filePath}})}if(this.recordsByType.set($.type,Y),this.discoveredDirectoriesByType.set($.type,X),this.started)this.syncDirectoryWatchers()}async loadDefinition($){let Y=new Map,X=new Set;for(let Q of $.directories){X.add(Q);let J=$.discoverFiles?await $.discoverFiles(Q):await this.readDirectoryFileCandidates(Q);for(let Z of J){let{fileName:T,filePath:K}=Z;if(X.add(Z.directoryPath),$.includeFile&&!$.includeFile(T,K))continue;try{let U=await kD(K,"utf8"),G={type:$.type,directoryPath:Z.directoryPath,fileName:T,filePath:K,content:U},W=$.parseFile(G),R=$.resolveId(W,G).trim();if(!R)continue;Y.set(R,{type:$.type,id:R,item:W,filePath:K,fingerprint:_D(U)})}catch(U){if(this.emitParseErrors)this.emit({kind:"error",type:$.type,error:U,filePath:K})}}}return{records:Y,discoveredDirectories:X}}buildDesiredTypesByDirectory(){let $=new Map;for(let[Y,X]of this.baseTypesByDirectory.entries())$.set(Y,new Set(X));for(let[Y,X]of this.discoveredDirectoriesByType.entries())for(let Q of X){let J=$.get(Q);if(J)J.add(Y);else $.set(Q,new Set([Y]))}return $}async readDirectoryFileCandidates($){try{return(await vD($,{withFileTypes:!0})).filter((X)=>X.isFile()).map((X)=>({directoryPath:$,fileName:X.name,filePath:hD($,X.name)})).sort((X,Q)=>X.fileName.localeCompare(Q.fileName))}catch(Y){if(DZ(Y))return[];throw Y}}}function FZ(){return VX()}function fD($){if(Array.isArray($))return[...$];if(typeof $==="string")return[$];return FZ()}function yX($){return{type:"agent",directories:fD($),includeFile:(Y)=>VZ(Y),parseFile:(Y)=>RY(Y.content),resolveId:(Y)=>AZ(Y.name)}}function HZ($){return new u$([yX($?.directoryPathOrPaths)],{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}import{existsSync as mD,readdirSync as bD}from"node:fs";import{basename as uD,extname as dD,join as pD}from"node:path";function jX($){return AX($)}var r8;((G)=>{G.TaskStart="TaskStart";G.TaskResume="TaskResume";G.TaskCancel="TaskCancel";G.TaskComplete="TaskComplete";G.PreToolUse="PreToolUse";G.PostToolUse="PostToolUse";G.UserPromptSubmit="UserPromptSubmit";G.PreCompact="PreCompact";G.SessionShutdown="SessionShutdown"})(r8||={});var xX={["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"},cD=new Map(Object.values(r8).map(($)=>[$.toLowerCase(),$]));function vX($){let Y=uD($,dD($)).trim().toLowerCase();return cD.get(Y)}function o8($){let Y=[],X=new Set,Q=jX($).filter((J)=>mD(J));for(let J of Q)try{for(let Z of bD(J,{withFileTypes:!0})){if(!Z.isFile())continue;let T=vX(Z.name);if(!T)continue;let K=pD(J,Z.name);if(X.has(K))continue;X.add(K),Y.push({fileName:T,hookEventName:xX[T],path:K})}}catch{}return Y.sort((J,Z)=>J.path.localeCompare(Z.path))}import{existsSync as _X,readdirSync as aD,statSync as tD}from"node:fs";import{join as eD,resolve as BZ}from"node:path";import{resolve as nD}from"node:path";import{pathToFileURL as lD}from"node:url";function qZ($){return typeof $==="object"&&$!==null}function zZ($){return Array.isArray($)&&$.every((Y)=>typeof Y==="string")}function iD($,Y){if(!qZ($.manifest))throw Error(`Invalid plugin module at ${Y}: missing required "manifest"`);if(!zZ($.manifest.capabilities))throw Error(`Invalid plugin module at ${Y}: manifest.capabilities must be a string array`);if($.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${Y}: manifest.capabilities cannot be empty`);if(Object.hasOwn($.manifest,"hookStages")&&!zZ($.manifest.hookStages))throw Error(`Invalid plugin module at ${Y}: manifest.hookStages must be a string array when provided`)}function rD($,Y){if(!qZ($))throw Error(`Invalid plugin module at ${Y}: expected object export`);if(typeof $.name!=="string"||$.name.length===0)throw Error(`Invalid plugin module at ${Y}: expected non-empty "name"`);if(!Object.hasOwn($,"manifest"))throw Error(`Invalid plugin module at ${Y}: missing required "manifest"`);iD($,Y)}async function kX($,Y={}){let X=nD(Y.cwd??process.cwd(),$),Q=await import(lD(X).href),J=Y.exportName??"plugin",Z=Q.default??Q[J];return rD(Z,X),Z}async function s8($,Y={}){let X=[];for(let Q of $)X.push(await kX(Q,Y));return X}import{spawn as oD}from"node:child_process";function NZ($){if($ instanceof Error)return $;return Error(String($))}class a8{options;process=null;requestCounter=0;pending=new Map;constructor($){this.options=$}start(){if(this.process&&this.process.exitCode===null)return;let $=oD(process.execPath,["-e",this.options.bootstrapScript],{stdio:["ignore","ignore","ignore","ipc"]});this.process=$,$.on("message",(Y)=>{this.onMessage(Y)}),$.on("error",(Y)=>{this.failPending(Error(`${this.options.name??"sandbox"} process error: ${NZ(Y).message}`))}),$.on("exit",(Y,X)=>{this.process=null,this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(Y)}, signal=${String(X)})`))})}async call($,Y,X={}){this.start();let Q=this.process;if(!Q||Q.exitCode!==null)throw Error(`${this.options.name??"sandbox"} process is not available`);let J=`req_${++this.requestCounter}`,Z={type:"call",id:J,method:$,args:Y};return await new Promise((T,K)=>{let U={resolve:(G)=>T(G),reject:K};if((X.timeoutMs??0)>0)U.timeout=setTimeout(()=>{this.pending.delete(J),this.shutdown().catch(()=>{}),K(Error(`${this.options.name??"sandbox"} call timed out after ${X.timeoutMs}ms: ${$}`))},X.timeoutMs);this.pending.set(J,U),Q.send(Z,(G)=>{if(!G)return;let W=this.pending.get(J);if(!W)return;if(this.pending.delete(J),W.timeout)clearTimeout(W.timeout);W.reject(Error(`${this.options.name??"sandbox"} failed to send call "${$}": ${NZ(G).message}`))})})}async shutdown(){let $=this.process;if(this.process=null,!$||$.exitCode!==null){this.failPending(Error(`${this.options.name??"sandbox"} shutdown`));return}await new Promise((Y)=>{let X=setTimeout(()=>{try{$.kill("SIGKILL")}catch{}Y()},300);$.once("exit",()=>{clearTimeout(X),Y()});try{$.kill("SIGTERM")}catch{clearTimeout(X),Y()}}),this.failPending(Error(`${this.options.name??"sandbox"} shutdown`))}onMessage($){if(!$||$.type!=="response"||!$.id)return;let Y=this.pending.get($.id);if(!Y)return;if(this.pending.delete($.id),Y.timeout)clearTimeout(Y.timeout);if($.ok){Y.resolve($.result);return}Y.reject(Error($.error?.message||`${this.options.name??"sandbox"} call failed`))}failPending($){for(let[Y,X]of this.pending.entries()){if(this.pending.delete(Y),X.timeout)clearTimeout(X.timeout);X.reject($)}}}var sD=`
|
|
116
|
+
const { pathToFileURL } = require("node:url");
|
|
117
|
+
let pluginCounter = 0;
|
|
118
|
+
const pluginState = new Map();
|
|
119
|
+
|
|
120
|
+
function toErrorPayload(error) {
|
|
121
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
122
|
+
const stack = error instanceof Error ? error.stack : undefined;
|
|
123
|
+
return { message, stack };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function sendResponse(id, ok, result, error) {
|
|
127
|
+
if (!process.send) return;
|
|
128
|
+
process.send({ type: "response", id, ok, result, error });
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function sanitizeObject(value) {
|
|
132
|
+
if (!value || typeof value !== "object") return {};
|
|
133
|
+
return value;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async function initialize(args) {
|
|
137
|
+
const descriptors = [];
|
|
138
|
+
const exportName = (args && args.exportName) || "plugin";
|
|
139
|
+
for (const pluginPath of args.pluginPaths || []) {
|
|
140
|
+
const moduleExports = await import(pathToFileURL(pluginPath).href);
|
|
141
|
+
const plugin = moduleExports.default || moduleExports[exportName];
|
|
142
|
+
if (!plugin || typeof plugin !== "object") {
|
|
143
|
+
throw new Error(\`Invalid plugin module: \${pluginPath}\`);
|
|
144
|
+
}
|
|
145
|
+
if (typeof plugin.name !== "string" || !plugin.name) {
|
|
146
|
+
throw new Error(\`Invalid plugin name: \${pluginPath}\`);
|
|
147
|
+
}
|
|
148
|
+
if (!plugin.manifest || typeof plugin.manifest !== "object") {
|
|
149
|
+
throw new Error(\`Invalid plugin manifest: \${pluginPath}\`);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const pluginId = \`plugin_\${++pluginCounter}\`;
|
|
153
|
+
const contributions = {
|
|
154
|
+
tools: [],
|
|
155
|
+
commands: [],
|
|
156
|
+
shortcuts: [],
|
|
157
|
+
flags: [],
|
|
158
|
+
messageRenderers: [],
|
|
159
|
+
providers: [],
|
|
160
|
+
};
|
|
161
|
+
const handlers = {
|
|
162
|
+
tools: new Map(),
|
|
163
|
+
commands: new Map(),
|
|
164
|
+
messageRenderers: new Map(),
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
const makeId = (prefix) => \`\${pluginId}_\${prefix}_\${Math.random().toString(36).slice(2, 10)}\`;
|
|
168
|
+
const api = {
|
|
169
|
+
registerTool: (tool) => {
|
|
170
|
+
const id = makeId("tool");
|
|
171
|
+
handlers.tools.set(id, tool.execute);
|
|
172
|
+
contributions.tools.push({
|
|
173
|
+
id,
|
|
174
|
+
name: tool.name,
|
|
175
|
+
description: tool.description,
|
|
176
|
+
inputSchema: tool.inputSchema,
|
|
177
|
+
timeoutMs: tool.timeoutMs,
|
|
178
|
+
retryable: tool.retryable,
|
|
179
|
+
});
|
|
180
|
+
},
|
|
181
|
+
registerCommand: (command) => {
|
|
182
|
+
const id = makeId("command");
|
|
183
|
+
if (typeof command.handler === "function") {
|
|
184
|
+
handlers.commands.set(id, command.handler);
|
|
185
|
+
}
|
|
186
|
+
contributions.commands.push({
|
|
187
|
+
id,
|
|
188
|
+
name: command.name,
|
|
189
|
+
description: command.description,
|
|
190
|
+
});
|
|
191
|
+
},
|
|
192
|
+
registerShortcut: (shortcut) => {
|
|
193
|
+
contributions.shortcuts.push({
|
|
194
|
+
id: makeId("shortcut"),
|
|
195
|
+
name: shortcut.name,
|
|
196
|
+
value: shortcut.value,
|
|
197
|
+
description: shortcut.description,
|
|
198
|
+
});
|
|
199
|
+
},
|
|
200
|
+
registerFlag: (flag) => {
|
|
201
|
+
contributions.flags.push({
|
|
202
|
+
id: makeId("flag"),
|
|
203
|
+
name: flag.name,
|
|
204
|
+
description: flag.description,
|
|
205
|
+
defaultValue: flag.defaultValue,
|
|
206
|
+
});
|
|
207
|
+
},
|
|
208
|
+
registerMessageRenderer: (renderer) => {
|
|
209
|
+
const id = makeId("renderer");
|
|
210
|
+
handlers.messageRenderers.set(id, renderer.render);
|
|
211
|
+
contributions.messageRenderers.push({ id, name: renderer.name });
|
|
212
|
+
},
|
|
213
|
+
registerProvider: (provider) => {
|
|
214
|
+
contributions.providers.push({
|
|
215
|
+
id: makeId("provider"),
|
|
216
|
+
name: provider.name,
|
|
217
|
+
description: provider.description,
|
|
218
|
+
metadata: sanitizeObject(provider.metadata),
|
|
219
|
+
});
|
|
220
|
+
},
|
|
221
|
+
};
|
|
222
|
+
|
|
223
|
+
if (typeof plugin.setup === "function") {
|
|
224
|
+
await plugin.setup(api);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
pluginState.set(pluginId, { plugin, handlers });
|
|
228
|
+
descriptors.push({
|
|
229
|
+
pluginId,
|
|
230
|
+
name: plugin.name,
|
|
231
|
+
manifest: plugin.manifest,
|
|
232
|
+
contributions,
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
return descriptors;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function getPlugin(pluginId) {
|
|
239
|
+
const state = pluginState.get(pluginId);
|
|
240
|
+
if (!state) {
|
|
241
|
+
throw new Error(\`Unknown sandbox plugin id: \${pluginId}\`);
|
|
242
|
+
}
|
|
243
|
+
return state;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
async function invokeHook(args) {
|
|
247
|
+
const state = getPlugin(args.pluginId);
|
|
248
|
+
const handler = state.plugin[args.hookName];
|
|
249
|
+
if (typeof handler !== "function") {
|
|
250
|
+
return undefined;
|
|
251
|
+
}
|
|
252
|
+
return await handler(args.payload);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
async function executeTool(args) {
|
|
256
|
+
const state = getPlugin(args.pluginId);
|
|
257
|
+
const handler = state.handlers.tools.get(args.contributionId);
|
|
258
|
+
if (typeof handler !== "function") {
|
|
259
|
+
throw new Error("Unknown sandbox tool contribution");
|
|
260
|
+
}
|
|
261
|
+
return await handler(args.input, args.context);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
async function executeCommand(args) {
|
|
265
|
+
const state = getPlugin(args.pluginId);
|
|
266
|
+
const handler = state.handlers.commands.get(args.contributionId);
|
|
267
|
+
if (typeof handler !== "function") {
|
|
268
|
+
return "";
|
|
269
|
+
}
|
|
270
|
+
return await handler(args.input);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
async function renderMessage(args) {
|
|
274
|
+
const state = getPlugin(args.pluginId);
|
|
275
|
+
const handler = state.handlers.messageRenderers.get(args.contributionId);
|
|
276
|
+
if (typeof handler !== "function") {
|
|
277
|
+
return "";
|
|
278
|
+
}
|
|
279
|
+
return await handler(args.message);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
const methods = { initialize, invokeHook, executeTool, executeCommand, renderMessage };
|
|
283
|
+
|
|
284
|
+
process.on("message", async (message) => {
|
|
285
|
+
if (!message || message.type !== "call") {
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
const method = methods[message.method];
|
|
289
|
+
if (!method) {
|
|
290
|
+
sendResponse(message.id, false, undefined, { message: \`Unknown method: \${String(message.method)}\` });
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
try {
|
|
294
|
+
const result = await method(message.args || {});
|
|
295
|
+
sendResponse(message.id, true, result);
|
|
296
|
+
} catch (error) {
|
|
297
|
+
sendResponse(message.id, false, undefined, toErrorPayload(error));
|
|
298
|
+
}
|
|
299
|
+
});
|
|
300
|
+
`;function e1($,Y){return $.manifest.hookStages?.includes(Y)===!0}function hX($,Y){return typeof $==="number"&&$>0?$:Y}async function MZ($){let Y=new a8({name:"plugin-sandbox",bootstrapScript:sD}),X=hX($.importTimeoutMs,4000),Q=hX($.hookTimeoutMs,3000),J=hX($.contributionTimeoutMs,5000),Z;try{Z=await Y.call("initialize",{pluginPaths:$.pluginPaths,exportName:$.exportName},{timeoutMs:X})}catch(K){throw await Y.shutdown().catch(()=>{}),K}return{extensions:Z.map((K)=>{let U={name:K.name,manifest:K.manifest,setup:(G)=>{for(let W of K.contributions.tools){let R={name:W.name,description:W.description??"",inputSchema:W.inputSchema??{type:"object",properties:{}},timeoutMs:W.timeoutMs,retryable:W.retryable,execute:async(V,A)=>await Y.call("executeTool",{pluginId:K.pluginId,contributionId:W.id,input:V,context:A},{timeoutMs:J})};G.registerTool(R)}for(let W of K.contributions.commands)G.registerCommand({name:W.name,description:W.description,handler:async(R)=>await Y.call("executeCommand",{pluginId:K.pluginId,contributionId:W.id,input:R},{timeoutMs:J})});for(let W of K.contributions.shortcuts)G.registerShortcut({name:W.name,value:W.value??"",description:W.description});for(let W of K.contributions.flags)G.registerFlag({name:W.name,description:W.description,defaultValue:W.defaultValue});for(let W of K.contributions.messageRenderers)G.registerMessageRenderer({name:W.name,render:()=>`[sandbox renderer ${W.name} requires async bridge]`});for(let W of K.contributions.providers)G.registerProvider({name:W.name,description:W.description,metadata:W.metadata})}};if(e1(U,"input"))U.onInput=async(G)=>await Y.call("invokeHook",{pluginId:K.pluginId,hookName:"onInput",payload:G},{timeoutMs:Q});if(e1(U,"session_start"))U.onSessionStart=async(G)=>await Y.call("invokeHook",{pluginId:K.pluginId,hookName:"onSessionStart",payload:G},{timeoutMs:Q});if(e1(U,"before_agent_start"))U.onBeforeAgentStart=async(G)=>await Y.call("invokeHook",{pluginId:K.pluginId,hookName:"onBeforeAgentStart",payload:G},{timeoutMs:Q});if(e1(U,"tool_call_before"))U.onToolCall=async(G)=>await Y.call("invokeHook",{pluginId:K.pluginId,hookName:"onToolCall",payload:G},{timeoutMs:Q});if(e1(U,"tool_call_after"))U.onToolResult=async(G)=>await Y.call("invokeHook",{pluginId:K.pluginId,hookName:"onToolResult",payload:G},{timeoutMs:Q});if(e1(U,"turn_end"))U.onAgentEnd=async(G)=>await Y.call("invokeHook",{pluginId:K.pluginId,hookName:"onAgentEnd",payload:G},{timeoutMs:Q});if(e1(U,"session_shutdown"))U.onSessionShutdown=async(G)=>await Y.call("invokeHook",{pluginId:K.pluginId,hookName:"onSessionShutdown",payload:G},{timeoutMs:Q});if(e1(U,"runtime_event"))U.onRuntimeEvent=async(G)=>{await Y.call("invokeHook",{pluginId:K.pluginId,hookName:"onRuntimeEvent",payload:G},{timeoutMs:Q})};if(e1(U,"error"))U.onError=async(G)=>{await Y.call("invokeHook",{pluginId:K.pluginId,hookName:"onError",payload:G},{timeoutMs:Q})};return U}),shutdown:async()=>{await Y.shutdown()}}}var IZ=new Set([".js",".mjs",".cjs",".ts",".mts",".cts"]);function gX($){return HX($)}function OZ($){let Y=$.lastIndexOf(".");if(Y===-1)return!1;return IZ.has($.slice(Y))}function t8($){let Y=BZ($);if(!_X(Y))return[];let X=[],Q=[Y];while(Q.length>0){let J=Q.pop();if(!J)continue;for(let Z of aD(J,{withFileTypes:!0})){let T=eD(J,Z.name);if(Z.isDirectory()){Q.push(T);continue}if(Z.isFile()&&OZ(T))X.push(T)}}return X.sort((J,Z)=>J.localeCompare(Z))}function $F($,Y){let X=[];for(let Q of $){let J=Q.trim();if(!J)continue;let Z=BZ(Y,J);if(!_X(Z))throw Error(`Plugin path does not exist: ${Z}`);if(tD(Z).isDirectory()){X.push(...t8(Z));continue}if(!OZ(Z))throw Error(`Plugin file must use a supported extension (${[...IZ].join(", ")}): ${Z}`);X.push(Z)}return X}function fX($={}){let Y=$.cwd??process.cwd(),X=gX($.workspacePath).flatMap((T)=>t8(T)).filter((T)=>_X(T)),Q=$F($.pluginPaths??[],Y),J=[],Z=new Set;for(let T of[...Q,...X]){if(Z.has(T))continue;Z.add(T),J.push(T)}return J}async function e8($={}){let Y=fX($);if(Y.length===0)return{extensions:[]};if($.mode==="in_process")return{extensions:await s8(Y,{cwd:$.cwd,exportName:$.exportName})};let X=await MZ({pluginPaths:Y,exportName:$.exportName,importTimeoutMs:$.importTimeoutMs,hookTimeoutMs:$.hookTimeoutMs,contributionTimeoutMs:$.contributionTimeoutMs});return{extensions:X.extensions??[],shutdown:X.shutdown}}import{readdir as PZ,stat as YF}from"node:fs/promises";import{basename as J9,dirname as XF,extname as mX,join as $9}from"node:path";import QF from"yaml";var Y9="SKILL.md",JF=new Set([".md",".markdown",".txt"]);function bX($){return $.trim().toLowerCase()}function X9($){return JF.has(mX($).toLowerCase())}function uX($){let Y=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,X=$.match(Y);if(!X)return{data:{},body:$,hadFrontmatter:!1};let[,Q,J]=X;try{let Z=QF.parse(Q);return{data:Z&&typeof Z==="object"&&!Array.isArray(Z)?Z:{},body:J,hadFrontmatter:!0}}catch(Z){let T=Z instanceof Error?Z.message:String(Z);return{data:{},body:$,hadFrontmatter:!0,parseError:T}}}function Q9($,Y,X){if($===void 0||$===null){if(X)throw Error(`Missing required frontmatter field '${Y}'.`);return}if(typeof $!=="string")throw Error(`Frontmatter field '${Y}' must be a string.`);let Q=$.trim();if(!Q&&X)throw Error(`Frontmatter field '${Y}' cannot be empty.`);return Q||void 0}function EY($,Y){if($===void 0||$===null)return;if(typeof $!=="boolean")throw Error(`Frontmatter field '${Y}' must be a boolean.`);return $}function dX($,Y){let{data:X,body:Q,parseError:J}=uX($);if(J)throw Error(`Failed to parse YAML frontmatter: ${J}`);let Z=Q.trim();if(!Z)throw Error("Missing instructions body in skill file.");let K=Q9(X.name,"name",!1)??Y.trim();if(!K)throw Error("Missing skill name.");return{name:K,description:Q9(X.description,"description",!1),disabled:EY(X.disabled,"disabled")??(EY(X.enabled,"enabled")===!1?!0:void 0),instructions:Z,frontmatter:X}}function pX($,Y){let{data:X,body:Q,parseError:J}=uX($);if(J)throw Error(`Failed to parse YAML frontmatter: ${J}`);let Z=Q.trim();if(!Z)throw Error("Missing instructions body in rule file.");let T=Q9(X.name,"name",!1)??Y.trim();if(!T)throw Error("Missing rule name.");return{name:T,disabled:EY(X.disabled,"disabled")??(EY(X.enabled,"enabled")===!1?!0:void 0),instructions:Z,frontmatter:X}}function cX($,Y){let{data:X,body:Q,parseError:J}=uX($);if(J)throw Error(`Failed to parse YAML frontmatter: ${J}`);let Z=Q.trim();if(!Z)throw Error("Missing instructions body in workflow file.");let T=Q9(X.name,"name",!1)??Y.trim();if(!T)throw Error("Missing workflow name.");return{name:T,disabled:EY(X.disabled,"disabled")??(EY(X.enabled,"enabled")===!1?!0:void 0),instructions:Z,frontmatter:X}}function nX($){return E6($)}function lX($){return DX($)}function iX($){return FX($)}async function ZF($){try{let Y=await PZ($,{withFileTypes:!0}),X=[];for(let Q of Y){if(Q.isFile()&&Q.name===Y9){X.push({directoryPath:$,fileName:Q.name,filePath:$9($,Q.name)});continue}if(Q.isDirectory())X.push({directoryPath:$9($,Q.name),fileName:Y9,filePath:$9($,Q.name,Y9)})}return X}catch(Y){if(Y.code==="ENOENT")return[];throw Y}}async function LZ($){try{if((await YF($)).isFile())return[{directoryPath:XF($),fileName:J9($),filePath:$}]}catch(Y){if(Y.code!=="ENOENT")throw Y}try{return(await PZ($,{withFileTypes:!0})).filter((X)=>X.isFile()&&X9(X.name)).map((X)=>({directoryPath:$,fileName:X.name,filePath:$9($,X.name)}))}catch(Y){if(Y.code==="ENOENT")return[];throw Y}}function rX($){return{type:"skill",directories:$?.directories??nX($?.workspacePath),discoverFiles:ZF,includeFile:(X)=>X===Y9,parseFile:(X)=>dX(X.content,J9(X.directoryPath)),resolveId:(X)=>bX(X.name)}}function oX($){return{type:"rule",directories:$?.directories??lX($?.workspacePath),discoverFiles:LZ,includeFile:(X,Q)=>X===".clinerules"||X9(X)||X9(Q),parseFile:(X)=>pX(X.content,J9(X.filePath,mX(X.filePath))),resolveId:(X)=>bX(X.name)}}function sX($){return{type:"workflow",directories:$?.directories??iX($?.workspacePath),discoverFiles:LZ,includeFile:(X)=>X9(X),parseFile:(X)=>cX(X.content,J9(X.filePath,mX(X.filePath))),resolveId:(X)=>bX(X.name)}}function Z9($){let Y=[rX($?.skills),oX($?.rules),sX($?.workflows)];return new u$(Y,{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}function TF($){return{onAuth:({url:Y,instructions:X})=>{if($.onOutput?.(X??"Complete sign-in in your browser."),$.openUrl)Promise.resolve($.openUrl(Y)).catch((Q)=>{$.onOpenUrlError?.({url:Y,error:Q})});$.onOutput?.(Y)},onPrompt:$.onPrompt}}function KF(){let $;return{promise:new Promise((X)=>{$=X}),resolve:$}}async function d$($){let Y=await import("node:http"),X=$.host??"127.0.0.1",Q=$.timeoutMs??300000,J=$.successHtml??UF,Z=KF(),T=!1,K=null,U=null,G=(V)=>{if(T)return;T=!0,Z.resolve(V)},W=()=>{if(K)clearTimeout(K),K=null;if(U)U.close(),U=null},R=async()=>{return K=setTimeout(()=>{W(),G(null)},Q),Z.promise};for(let V of $.ports){let A=Y.createServer((z,D)=>{try{let B=new URL(z.url||"",`http://${X}:${V}`);if(B.pathname!==$.callbackPath){D.statusCode=404,D.end("Not found");return}let w={url:B,code:B.searchParams.get("code")??void 0,state:B.searchParams.get("state")??void 0,provider:B.searchParams.get("provider")??void 0,error:B.searchParams.get("error")??void 0};if(w.error){D.statusCode=400,D.end(`Authentication failed: ${w.error}`),W(),G(w);return}if(!w.code){D.statusCode=400,D.end("Missing authorization code");return}if($.expectedState&&w.state!==$.expectedState){D.statusCode=400,D.end("State mismatch");return}D.statusCode=200,D.setHeader("Content-Type","text/html; charset=utf-8"),D.end(J),W(),G(w)}catch{D.statusCode=500,D.end("Internal error")}}),H=await new Promise((z)=>{let D=(B)=>{A.off("error",D),z({bound:!1,error:B})};A.once("error",D),A.listen(V,X,()=>{A.off("error",D),U=A,z({bound:!0})})});if(H.error){if(H.error.code==="EADDRINUSE")continue;throw W(),H.error}if(H.bound)return{callbackUrl:`http://${X}:${V}${$.callbackPath}`,waitForCallback:R,cancelWait:()=>{W(),G(null)},close:()=>{W(),G(null)}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var UF=`<!DOCTYPE html>
|
|
301
|
+
<html lang="en">
|
|
302
|
+
<head>
|
|
303
|
+
<meta charset="utf-8">
|
|
304
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
305
|
+
<title>Authentication Successful</title>
|
|
306
|
+
<style>
|
|
307
|
+
* { margin: 0; padding: 0; box-sizing: border-box; }
|
|
308
|
+
body {
|
|
309
|
+
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
|
|
310
|
+
min-height: 100vh;
|
|
311
|
+
display: flex;
|
|
312
|
+
align-items: center;
|
|
313
|
+
justify-content: center;
|
|
314
|
+
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
|
|
315
|
+
color: #fff;
|
|
316
|
+
}
|
|
317
|
+
.container { text-align: center; padding: 48px; max-width: 420px; }
|
|
318
|
+
.icon {
|
|
319
|
+
width: 72px; height: 72px; margin: 0 auto 24px;
|
|
320
|
+
background: linear-gradient(135deg, #10a37f 0%, #1a7f64 100%);
|
|
321
|
+
border-radius: 50%;
|
|
322
|
+
display: flex; align-items: center; justify-content: center;
|
|
323
|
+
}
|
|
324
|
+
.icon svg { width: 36px; height: 36px; stroke: #fff; stroke-width: 3; fill: none; }
|
|
325
|
+
h1 { font-size: 24px; font-weight: 600; margin-bottom: 12px; }
|
|
326
|
+
p { font-size: 15px; color: rgba(255,255,255,0.7); line-height: 1.5; }
|
|
327
|
+
.closing { margin-top: 32px; font-size: 13px; color: rgba(255,255,255,0.5); }
|
|
328
|
+
</style>
|
|
329
|
+
</head>
|
|
330
|
+
<body>
|
|
331
|
+
<div class="container">
|
|
332
|
+
<div class="icon">
|
|
333
|
+
<svg viewBox="0 0 24 24"><polyline points="20 6 9 17 4 12"></polyline></svg>
|
|
334
|
+
</div>
|
|
335
|
+
<h1>Authentication Successful</h1>
|
|
336
|
+
<p>You're now signed in. You can close this window.</p>
|
|
337
|
+
<p class="closing">This window will close automatically...</p>
|
|
338
|
+
</div>
|
|
339
|
+
<script>setTimeout(() => window.close(), 3000);</script>
|
|
340
|
+
</body>
|
|
341
|
+
</html>`;function SZ($){let Y="";for(let X=0;X<$.length;X+=1)Y+=String.fromCharCode($[X]??0);return btoa(Y).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function GF($){let X=new TextEncoder().encode($),Q=await crypto.subtle.digest("SHA-256",X);return new Uint8Array(Q)}function WF($=32){let Y=new Uint8Array($);return crypto.getRandomValues(Y),SZ(Y)}async function T9(){let $=WF(),Y=SZ(await GF($));return{verifier:$,challenge:Y}}function K9($){return $.endsWith("/")?$.slice(0,-1):$}function U9($,Y){return new URL(Y,`${K9($)}/`).toString()}function VY($,Y={}){let X=$.trim();if(!X)return{};try{let Q=new URL(X);return{code:Q.searchParams.get("code")??void 0,state:Q.searchParams.get("state")??void 0,provider:Y.includeProvider?Q.searchParams.get("provider")??void 0:void 0}}catch{}if(Y.allowHashCodeState&&X.includes("#")){let[Q,J]=X.split("#",2);return{code:Q||void 0,state:J||void 0}}if(X.includes("code=")){let Q=new URLSearchParams(X);return{code:Q.get("code")??void 0,state:Q.get("state")??void 0,provider:Y.includeProvider?Q.get("provider")??void 0:void 0}}return{code:X}}function RF($){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 G1($){if(!$)return null;try{let Y=$.split(".");if(Y.length!==3)return null;let X=Y[1];if(!X)return null;let Q=X.replace(/-/g,"+").replace(/_/g,"/"),J=Q.padEnd(Q.length+(4-Q.length%4)%4,"="),Z=RF(J);if(!Z)return null;return JSON.parse(Z)}catch{return null}}function A6($){try{let Y=JSON.parse($),X=Y.error,Q=typeof X==="string"?X:X&&typeof X==="object"&&typeof X.type==="string"?X.type:void 0,J=typeof Y.error_description==="string"?Y.error_description:typeof Y.message==="string"?Y.message:X&&typeof X==="object"&&typeof X.message==="string"?X.message:void 0;return{code:Q,message:J}}catch{return{}}}function p$($,Y){return Date.now()>=$.expires-Y}async function AY($){if(!$.onManualCodeInput){let Z=await $.waitForCallback();return{code:Z?.code,state:Z?.state,provider:Z?.provider,error:Z?.error}}let Y,X,Q=$.onManualCodeInput().then((Z)=>{Y=Z,$.cancelWait()}).catch((Z)=>{X=Z instanceof Error?Z:Error(String(Z)),$.cancelWait()}),J=await $.waitForCallback();if(X)throw X;if(J?.code||J?.error)return{code:J.code,state:J.state,provider:J.provider,error:J.error};if(Y)return VY(Y,$.parseOptions);if(await Q,X)throw X;if(Y)return VY(Y,$.parseOptions);return{}}var aX={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",refresh:"/api/v1/auth/refresh"},EF="/auth",wZ=Array.from({length:11},($,Y)=>48801+Y),VF=300000,AF=30000,tX=30000;class G9 extends Error{status;errorCode;constructor($,Y){super($);this.name="ClineOAuthTokenError",this.status=Y?.status,this.errorCode=Y?.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 DF(){let $=globalThis.crypto;if(!$)return Math.random().toString(16).slice(2);let Y=new Uint8Array(16);return $.getRandomValues(Y),Array.from(Y,(X)=>X.toString(16).padStart(2,"0")).join("")}function FF($){let Y=Date.parse($);if(Number.isNaN(Y))throw Error(`Invalid expiresAt value: ${$}`);return Y}function CZ($,Y,X={}){let Q=$.userInfo.clineUserId??X.accountId,J=$.refreshToken??X.refresh;if(!J)throw Error("Token response did not include a refresh token");return{access:$.accessToken,refresh:J,expires:FF($.expiresAt),accountId:Q??void 0,email:$.userInfo.email||X.email,metadata:{provider:Y,tokenType:$.tokenType,userInfo:$.userInfo}}}async function eX($){if(!$)return{};return typeof $==="function"?await $():$}async function HF($,Y){let X=new URL(U9($.apiBaseUrl,aX.authorize));X.searchParams.set("client_type","extension"),X.searchParams.set("callback_url",Y.callbackUrl),X.searchParams.set("redirect_uri",Y.callbackUrl),X.searchParams.set("state",Y.state);let Q=await fetch(X.toString(),{method:"GET",redirect:"manual",headers:await eX($.headers),signal:AbortSignal.timeout($.requestTimeoutMs??tX)});if(Q.status>=300&&Q.status<400){let Z=Q.headers.get("location");if(Z)return Z}if(!Q.ok){let Z=await Q.text().catch(()=>"");throw Error(`Authentication request failed: ${Q.status} ${Z}`)}let J=await Q.json();if(typeof J.redirect_url==="string"&&J.redirect_url.length>0)return J.redirect_url;throw Error("Authentication request did not return a redirect URL")}async function zF($,Y,X,Q){let J={grant_type:"authorization_code",code:$,client_type:"extension",redirect_uri:Y,provider:Q??X.provider},Z=await fetch(U9(X.apiBaseUrl,aX.token),{method:"POST",headers:{"Content-Type":"application/json",...await eX(X.headers)},body:JSON.stringify(J),signal:AbortSignal.timeout(X.requestTimeoutMs??tX)});if(!Z.ok){let K=await Z.text().catch(()=>""),U=A6(K);throw new G9(`Token exchange failed: ${Z.status}${U.message?` - ${U.message}`:""}`,{status:Z.status,errorCode:U.code})}let T=await Z.json();if(!T.success||!T.data?.accessToken)throw Error("Invalid token exchange response");return CZ(T.data,Q??X.provider)}async function yZ($){let Y=$.callbackPorts?.length?$.callbackPorts:wZ,X=$.callbackPath??EF,Q=DF(),J=await d$({ports:Y,callbackPath:X}),Z=J.callbackUrl||`http://127.0.0.1:${Y[0]??wZ[0]}${X}`,T=await HF($,{callbackUrl:Z,state:Q});$.callbacks.onAuth({url:T,instructions:"Continue the authentication process in your browser."});try{let K,U=$.provider,G=await AY({waitForCallback:J.waitForCallback,cancelWait:J.cancelWait,onManualCodeInput:$.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(G.error)throw Error(`OAuth error: ${G.error}`);if(G.state&&G.state!==Q)throw Error("State mismatch");if(K=G.code,U=G.provider??U,!K){let W=await $.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),R=VY(W,{includeProvider:!0});if(R.state&&R.state!==Q)throw Error("State mismatch");K=R.code,U=R.provider??U}if(!K)throw Error("Missing authorization code");return zF(K,Z,$,U)}finally{J.close()}}async function $5($,Y){let X=await fetch(U9(Y.apiBaseUrl,aX.refresh),{method:"POST",headers:{"Content-Type":"application/json",...await eX(Y.headers)},body:JSON.stringify({refreshToken:$.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout(Y.requestTimeoutMs??tX)});if(!X.ok){let Z=await X.text().catch(()=>""),T=A6(Z);throw new G9(`Token refresh failed: ${X.status}${T.message?` - ${T.message}`:""}`,{status:X.status,errorCode:T.code})}let Q=await X.json();if(!Q.success||!Q.data?.accessToken)throw Error("Invalid token refresh response");let J=$.metadata?.provider??Y.provider;return CZ(Q.data,J,$)}async function Y5($,Y,X){if(!$)return null;let Q=X?.refreshBufferMs??VF,J=X?.retryableTokenGraceMs??AF;if(X?.forceRefresh!==!0&&!p$($,Q))return $;try{return await $5($,Y)}catch(T){if(T instanceof G9&&T.isLikelyInvalidGrant())return null;if($.expires-Date.now()>J)return $;return null}}function qF($){return{id:"cline",name:"Cline Account",usesCallbackServer:!0,async login(Y){return yZ({...$,callbacks:Y})},async refreshToken(Y){return $5(Y,$)},getApiKey(Y){return`workos:${Y.access}`}}}import{nanoid as NF}from"nanoid";var q0={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 W9 extends Error{status;errorCode;constructor($,Y){super($);this.name="OpenAICodexOAuthTokenError",this.status=Y?.status,this.errorCode=Y?.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 MF($,Y,X=q0.redirectUri){let Q=await fetch(q0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:q0.clientId,code:$,code_verifier:Y,redirect_uri:X}),signal:AbortSignal.timeout(q0.httpTimeoutMs)});if(!Q.ok)return{type:"failed"};let J=await Q.json();if(!J.access_token||!J.refresh_token||typeof J.expires_in!=="number")return{type:"failed"};return{type:"success",access:J.access_token,refresh:J.refresh_token,expires:Date.now()+J.expires_in*1000,email:J.email,idToken:J.id_token}}async function BF($){try{let Y=await fetch(q0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:$,client_id:q0.clientId}),signal:AbortSignal.timeout(q0.httpTimeoutMs)});if(!Y.ok){let Q=await Y.text().catch(()=>""),J=A6(Q);throw new W9(`Token refresh failed: ${Y.status}${J.message?` - ${J.message}`:""}`,{status:Y.status,errorCode:J.code})}let X=await Y.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}}catch(Y){if(Y instanceof W9)throw Y;return{type:"failed"}}}async function IF($="pi"){let{verifier:Y,challenge:X}=await T9(),Q=NF(32),J=new URL(q0.authorizationEndpoint);return J.searchParams.set("response_type","code"),J.searchParams.set("client_id",q0.clientId),J.searchParams.set("redirect_uri",q0.redirectUri),J.searchParams.set("scope",q0.scopes),J.searchParams.set("code_challenge",X),J.searchParams.set("code_challenge_method","S256"),J.searchParams.set("state",Q),J.searchParams.set("id_token_add_organizations","true"),J.searchParams.set("codex_cli_simplified_flow","true"),J.searchParams.set("originator",$),{verifier:Y,state:Q,url:J.toString()}}function OF(){try{let $=new URL(q0.redirectUri),Y=$.port.length>0?Number.parseInt($.port,10):q0.callbackPort;return{host:$.hostname||"localhost",port:Number.isFinite(Y)?Y:q0.callbackPort,callbackPath:$.pathname||"/auth/callback",redirectUri:$.toString()}}catch{return{host:"localhost",port:q0.callbackPort,callbackPath:"/auth/callback",redirectUri:q0.redirectUri}}}function jZ($,Y){let X=Y?G1(Y):G1($),Q=X?X:G1($),Z=Q?.[q0.jwtClaimPath]?.chatgpt_account_id;if(typeof Z==="string"&&Z.length>0)return Z;let T=Q?.organizations;if(Array.isArray(T)&&T.length>0){let U=T[0];if(typeof U?.id==="string"&&U.id.length>0)return U.id}let K=Q?.chatgpt_account_id;if(typeof K==="string"&&K.length>0)return K;return null}function xZ($,Y){let X=jZ($.access,$.idToken)??Y?.accountId;if(!X)throw Error("Failed to extract accountId from token");return{access:$.access,refresh:$.refresh||Y?.refresh||"",expires:$.expires,accountId:X,email:$.email??Y?.email,metadata:{...Y?.metadata??{},provider:"openai-codex"}}}async function vZ($){let Y=OF(),{verifier:X,state:Q,url:J}=await IF($.originator),Z=await d$({host:Y.host,ports:[Y.port],callbackPath:Y.callbackPath,expectedState:Q});$.onAuth({url:J,instructions:"Continue the authentication process in your browser."});let T;try{let K=await AY({waitForCallback:Z.waitForCallback,cancelWait:Z.cancelWait,onManualCodeInput:$.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(K.state&&K.state!==Q)throw Error("State mismatch");if(T=K.code,!T){let G=await $.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),W=VY(G,{allowHashCodeState:!0});if(W.state&&W.state!==Q)throw Error("State mismatch");T=W.code}if(!T)throw Error("Missing authorization code");let U=await MF(T,X,Y.redirectUri);if(U.type!=="success")throw Error("Token exchange failed");return xZ(U)}finally{Z.close()}}async function X5($,Y){let X=await BF($);if(X.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let Q=xZ(X,Y);if(!Q.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return Q}async function Q5($,Y){if(!$)return null;let X=Y?.refreshBufferMs??q0.refreshBufferMs,Q=Y?.retryableTokenGraceMs??q0.retryableTokenGraceMs;if(Y?.forceRefresh!==!0&&!p$($,X))return $;try{return await X5($.refresh,$)}catch(Z){if(Z instanceof W9&&Z.isLikelyInvalidGrant())return null;if($.expires-Date.now()>Q)return $;return null}}function PF($,Y=q0.refreshBufferMs){return p$($,Y)}function LF($){let Y=$.accountId??jZ($.access);if(!Y)throw Error("Failed to extract accountId from token");return{...$,accountId:Y,metadata:{...$.metadata??{},provider:"openai-codex"}}}var SF={id:"openai-codex",name:"ChatGPT Plus/Pro (ChatGPT Subscription)",usesCallbackServer:!0,async login($){return vZ({onAuth:$.onAuth,onPrompt:$.onPrompt,onProgress:$.onProgress,onManualCodeInput:$.onManualCodeInput})},async refreshToken($){return X5($.refresh,$)},getApiKey($){return $.access}};import{nanoid as kZ}from"nanoid";var hZ="a8331954c0cf48ba99b5dd223a14c6ea",_Z="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",gZ="openid offline_access",fZ="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",mZ="c1aba3deed5740659981a752714eba33",bZ="https://login-ext.identity.oraclecloud.com",uZ="openid offline_access",dZ="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",pZ="opc-request-id",wF="/auth/oca",CF=Array.from({length:11},($,Y)=>48801+Y),yF=300000,jF=30000,cZ=30000,xF=600000;class R9 extends Error{status;errorCode;constructor($,Y){super($);this.name="OcaOAuthTokenError",this.status=Y?.status,this.errorCode=Y?.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 F$={internal:{clientId:hZ,idcsUrl:_Z,scopes:gZ,baseUrl:fZ},external:{clientId:mZ,idcsUrl:bZ,scopes:uZ,baseUrl:dZ}},D6=new Map,J5=new Map;function nZ($){if(typeof $==="function")return $();return $??"internal"}function lZ($){return{internal:{clientId:$?.internal?.clientId??F$.internal.clientId,idcsUrl:$?.internal?.idcsUrl??F$.internal.idcsUrl,scopes:$?.internal?.scopes??F$.internal.scopes,baseUrl:$?.internal?.baseUrl??F$.internal.baseUrl},external:{clientId:$?.external?.clientId??F$.external.clientId,idcsUrl:$?.external?.idcsUrl??F$.external.idcsUrl,scopes:$?.external?.scopes??F$.external.scopes,baseUrl:$?.external?.baseUrl??F$.external.baseUrl}}}function vF($=Date.now()){let Y=$-xF;for(let[X,Q]of D6.entries())if(Q.createdAt<Y)D6.delete(X)}function kF($,Y,X){if(typeof $.expires_in==="number"&&$.expires_in>0)return Date.now()+$.expires_in*1000;let J=G1(Y)?.exp;if(typeof J==="number"&&J>0)return J*1000;let T=G1(X)?.exp;if(typeof T==="number"&&T>0)return T*1000;return Date.now()+3600000}function iZ($,Y,X){let Q=$.access_token;if(!Q)throw Error("Token response did not include an access token");let J=$.refresh_token??X?.refresh;if(!J)throw Error("Token response did not include a refresh token");let Z=G1($.id_token),T=G1(Q),K=Z?.sub??T?.sub,U=Z?.email??T?.email;return{access:Q,refresh:J,expires:kF($,Q,$.id_token),accountId:K??X?.accountId,email:U??X?.email,metadata:{...X?.metadata??{},provider:"oca",mode:Y,subject:K,idToken:$.id_token}}}async function rZ($,Y){let X=K9($),Q=J5.get(X);if(Q)return Q;let J=`${X}/.well-known/openid-configuration`,Z=await fetch(J,{method:"GET",signal:AbortSignal.timeout(Y)});if(!Z.ok){let U=`${X}/oauth2/v1/token`;return J5.set(X,U),U}let K=(await Z.json()).token_endpoint||`${X}/oauth2/v1/token`;return J5.set(X,K),K}function oZ($){return{code:$.error,message:$.error_description}}async function hF($){let Y=D6.get($.state);if(!Y)throw Error("No PKCE verifier found for this state");D6.delete($.state);let X=$.mode==="external"?$.config.external:$.config.internal,Q=await rZ(X.idcsUrl,$.requestTimeoutMs),J=new URLSearchParams({grant_type:"authorization_code",code:$.code,redirect_uri:Y.redirectUri,client_id:X.clientId,code_verifier:Y.verifier}),Z=await fetch(Q,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:J,signal:AbortSignal.timeout($.requestTimeoutMs)}),T=await Z.json();if(!Z.ok){let U=oZ(T);throw new R9(`Token exchange failed: ${Z.status}${U.message?` - ${U.message}`:""}`,{status:Z.status,errorCode:U.code})}let K=G1(T.id_token);if(!T.id_token||!K)throw Error("No ID token received from OCA");if(K.nonce!==Y.nonce)throw Error("OIDC nonce verification failed");return iZ(T,$.mode)}function _F($){let Y=$.mode==="external"?$.config.external:$.config.internal,X=new URL(`${K9(Y.idcsUrl)}/oauth2/v1/authorize`);return X.searchParams.set("client_id",Y.clientId),X.searchParams.set("response_type","code"),X.searchParams.set("scope",Y.scopes),X.searchParams.set("code_challenge",$.challenge),X.searchParams.set("code_challenge_method","S256"),X.searchParams.set("redirect_uri",$.callbackUrl),X.searchParams.set("state",$.state),X.searchParams.set("nonce",$.nonce),X.toString()}async function sZ($){let Y=lZ($.config),X=nZ($.mode),Q=$.callbackPorts?.length?$.callbackPorts:CF,J=$.callbackPath??wF,Z=$.requestTimeoutMs??cZ,T=await d$({ports:Q,callbackPath:J}),K=T.callbackUrl;if(!K)throw Error("Unable to bind local OAuth callback server");let U=kZ(16),G=kZ(16),{verifier:W,challenge:R}=await T9();vF(),D6.set(U,{verifier:W,nonce:G,mode:X,redirectUri:K,createdAt:Date.now()});let V=_F({callbackUrl:K,mode:X,state:U,nonce:G,challenge:R,config:Y});$.callbacks.onAuth({url:V,instructions:"Continue the authentication process in your browser."});try{let A=await AY({waitForCallback:T.waitForCallback,cancelWait:T.cancelWait,onManualCodeInput:$.callbacks.onManualCodeInput}),H=A.code,z=A.state;if(A.error)throw Error(`OAuth error: ${A.error}`);if(!H){if(!$.callbacks.onManualCodeInput)throw Error("Timed out waiting for OCA callback");throw Error("Missing authorization code")}if(!z||z!==U)throw Error("State mismatch");return await hF({code:H,state:z,mode:X,config:Y,requestTimeoutMs:Z})}finally{T.close()}}async function Z5($,Y={}){let X=lZ(Y.config),Q=Y.requestTimeoutMs??cZ,J=$.metadata?.mode,Z=J==="internal"||J==="external"?J:nZ(Y.mode),T=Z==="external"?X.external:X.internal,K=await rZ(T.idcsUrl,Q),U=new URLSearchParams({grant_type:"refresh_token",refresh_token:$.refresh,client_id:T.clientId}),G=await fetch(K,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:U,signal:AbortSignal.timeout(Q)}),W=await G.json();if(!G.ok){let R=oZ(W);throw new R9(`Token refresh failed: ${G.status}${R.message?` - ${R.message}`:""}`,{status:G.status,errorCode:R.code})}return iZ(W,Z,$)}async function T5($,Y,X){if(!$)return null;let Q=Y?.refreshBufferMs??X?.refreshBufferMs??yF,J=Y?.retryableTokenGraceMs??X?.retryableTokenGraceMs??jF;if(Y?.forceRefresh!==!0&&!p$($,Q))return $;try{return await Z5($,X)}catch(T){if(T instanceof R9&&T.isLikelyInvalidGrant())return null;if($.expires-Date.now()>J)return $;return null}}function gF($={}){return{id:"oca",name:"Oracle Code Assist",usesCallbackServer:!0,async login(Y){return sZ({...$,callbacks:Y})},async refreshToken(Y){return Z5(Y,$)},getApiKey(Y){return Y.access}}}async function aZ($,Y){let X=new TextEncoder,Q=async(G)=>{let W=await crypto.subtle.digest("SHA-256",X.encode(G));return Array.from(new Uint8Array(W).slice(0,4),(R)=>R.toString(16).padStart(2,"0")).join("")},[J,Z]=await Promise.all([Q(Y),Q($)]),T=Math.floor(Date.now()/1000).toString(16).padStart(8,"0"),K=new Uint32Array(1);crypto.getRandomValues(K);let U=(K[0]??0).toString(16).padStart(8,"0");return J+Z+T+U}async function fF($){let Y=await aZ($.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",[pZ]:Y}}import{existsSync as mF,readFileSync as bF}from"node:fs";import{z as o}from"zod";var F6=o.record(o.string(),o.string()),tZ=o.record(o.string(),o.unknown()),uF=o.object({type:o.literal("stdio"),command:o.string().min(1),args:o.array(o.string()).optional(),cwd:o.string().min(1).optional(),env:F6.optional()}),dF=o.object({type:o.literal("sse"),url:o.string().url(),headers:F6.optional()}),pF=o.object({type:o.literal("streamableHttp"),url:o.string().url(),headers:F6.optional()}),cF=o.discriminatedUnion("type",[uF,dF,pF]),nF=o.object({transport:cF,disabled:o.boolean().optional(),metadata:tZ.optional()}),lF=o.enum(["stdio","sse","http","streamableHttp"]).optional(),eZ=o.object({type:o.enum(["stdio","sse","streamableHttp"]).optional(),transportType:lF,disabled:o.boolean().optional(),metadata:tZ.optional()});function K5($){if(!$)return;if($==="http")return"streamableHttp";return $}var iF=eZ.extend({command:o.string().min(1),args:o.array(o.string()).optional(),cwd:o.string().min(1).optional(),env:F6.optional()}).superRefine(($,Y)=>{let X=$.type??K5($.transportType);if(X&&X!=="stdio")Y.addIssue({code:o.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})),rF=eZ.extend({url:o.string().url(),headers:F6.optional()}).superRefine(($,Y)=>{let X=$.type??K5($.transportType)??"sse";if(X!=="sse"&&X!=="streamableHttp")Y.addIssue({code:o.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform(($)=>{if(($.type??K5($.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}}),oF=o.union([nF,iF,rF]),sF=o.object({mcpServers:o.record(o.string(),oF)}).strict();function E9(){return RX()}function U5($={}){let Y=$.filePath??E9(),X=bF(Y,"utf8"),Q;try{Q=JSON.parse(X)}catch(Z){let T=Z instanceof Error?Z.message:String(Z);throw Error(`Failed to parse MCP settings JSON at "${Y}": ${T}`)}let J=sF.safeParse(Q);if(!J.success){let Z=J.error.issues.map((T)=>{let K=T.path.join(".");return K?`${K}: ${T.message}`:T.message}).join("; ");throw Error(`Invalid MCP settings at "${Y}": ${Z}`)}return J.data}function $T($={}){let Y=$.filePath??E9();return mF(Y)}function G5($={}){let Y=U5($);return Object.entries(Y.mcpServers).map(([X,Q])=>({name:X,transport:Q.transport,disabled:Q.disabled,metadata:Q.metadata}))}async function YT($,Y={}){let X=G5(Y);for(let Q of X)await $.registerServer(Q);return X}function W1(){return Date.now()}function aF($){return $.map((Y)=>({name:Y.name,description:Y.description,inputSchema:Y.inputSchema}))}class W5{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor($){this.clientFactory=$.clientFactory,this.toolsCacheTtlMs=$.toolsCacheTtlMs??5000}async registerServer($){await this.runExclusive($.name,async()=>{let Y=this.servers.get($.name);if(!Y){this.servers.set($.name,{registration:{...$},status:"disconnected",updatedAt:W1()});return}let X=JSON.stringify(Y.registration.transport)!==JSON.stringify($.transport);if(Y.registration={...$},Y.updatedAt=W1(),X)await this.disconnectState(Y),Y.client=void 0,Y.toolCache=void 0,Y.toolCacheUpdatedAt=void 0})}async unregisterServer($){await this.runExclusive($,async()=>{let Y=this.requireServer($);await this.disconnectState(Y),this.servers.delete($)})}async connectServer($){await this.runExclusive($,async()=>{let Y=this.requireServer($);await this.connectState(Y)})}async disconnectServer($){await this.runExclusive($,async()=>{let Y=this.requireServer($);await this.disconnectState(Y)})}async setServerDisabled($,Y){await this.runExclusive($,async()=>{let X=this.requireServer($);if(X.registration={...X.registration,disabled:Y},X.updatedAt=W1(),Y)await this.disconnectState(X)})}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(($,Y)=>$.name.localeCompare(Y.name))}async listTools($){let Y=this.requireServer($),X=Y.toolCacheUpdatedAt??0;if(Y.toolCache&&W1()-X<=this.toolsCacheTtlMs)return Y.toolCache;return this.refreshTools($)}async refreshTools($){return this.runExclusive($,async()=>{let Y=this.requireServer($),Q=await(await this.ensureConnectedClient(Y)).listTools(),J=aF(Q);return Y.toolCache=J,Y.toolCacheUpdatedAt=W1(),Y.updatedAt=W1(),J})}async callTool($){return this.runExclusive($.serverName,async()=>{let Y=this.requireServer($.serverName),X=await this.ensureConnectedClient(Y);return Y.updatedAt=W1(),X.callTool({name:$.toolName,arguments:$.arguments,context:$.context})})}async dispose(){let $=[...this.servers.keys()];for(let Y of $)await this.unregisterServer(Y)}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=W1();try{let Y=$.client??await this.clientFactory($.registration);await Y.connect(),$.client=Y,$.status="connected",$.lastError=void 0,$.updatedAt=W1()}catch(Y){throw $.status="disconnected",$.lastError=Y instanceof Error?Y.message:String(Y),$.updatedAt=W1(),Y}}async disconnectState($){if(!$.client){$.status="disconnected",$.updatedAt=W1();return}try{await $.client.disconnect()}finally{$.status="disconnected",$.updatedAt=W1()}}requireServer($){let Y=this.servers.get($);if(!Y)throw Error(`Unknown MCP server: ${$}`);return Y}async runExclusive($,Y){let X=this.operationLocks.get($)??Promise.resolve(),Q,J=new Promise((T)=>{Q=T}),Z=X.catch(()=>{return}).then(()=>J);this.operationLocks.set($,Z),await X.catch(()=>{return});try{return await Y()}finally{if(Q?.(),this.operationLocks.get($)===Z)this.operationLocks.delete($)}}}function XT($){return $.disabled!==!0}function QT($){if($.length===0)return"";return`
|
|
342
|
+
|
|
343
|
+
# Rules
|
|
344
|
+
${$.map((X)=>`## ${X.name}
|
|
345
|
+
${X.instructions}`).join(`
|
|
346
|
+
|
|
347
|
+
`)}`}function JT($){return[...$.getSnapshot("rule").values()].map((X)=>X.item).filter(XT).sort((X,Q)=>X.name.localeCompare(Q.name))}function tF($){return QT(JT($))}import{existsSync as E5,readdirSync as ZH}from"node:fs";import{join as ZT}from"node:path";import{AgentTeamsRuntime as TH,bootstrapAgentTeams as KH}from"@clinebot/agents";import{nanoid as UH}from"nanoid";import{existsSync as $H,mkdirSync as YH}from"node:fs";import{join as XH}from"node:path";import{createRequire as eF}from"node:module";function O0(){return new Date().toISOString()}function t0($){return $?1:0}function J0($){return typeof $==="string"?$:""}function U0($){if(typeof $!=="string")return;let Y=$.trim();return Y.length>0?Y:void 0}function e0($){return $===1||$===!0}function DY($){let Y=eF(import.meta.url);if(typeof globalThis.Bun<"u"){let{Database:Z}=Y("bun:sqlite"),T=new Z($,{create:!0});return{prepare:(K)=>{let U=T.query(K);return{run:(...G)=>U.run(...G),get:(...G)=>U.get(...G),all:(...G)=>U.all(...G)}},exec:(K)=>T.exec(K)}}let Q=["better","-sqlite3"].join("");return new(Y(Q))($)}function V9($,Y={}){if($.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec(`
|
|
348
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
349
|
+
session_id TEXT PRIMARY KEY,
|
|
350
|
+
source TEXT NOT NULL,
|
|
351
|
+
pid INTEGER NOT NULL,
|
|
352
|
+
started_at TEXT NOT NULL,
|
|
353
|
+
ended_at TEXT,
|
|
354
|
+
exit_code INTEGER,
|
|
355
|
+
status TEXT NOT NULL,
|
|
356
|
+
status_lock INTEGER NOT NULL DEFAULT 0,
|
|
357
|
+
interactive INTEGER NOT NULL,
|
|
358
|
+
provider TEXT NOT NULL,
|
|
359
|
+
model TEXT NOT NULL,
|
|
360
|
+
cwd TEXT NOT NULL,
|
|
361
|
+
workspace_root TEXT NOT NULL,
|
|
362
|
+
team_name TEXT,
|
|
363
|
+
enable_tools INTEGER NOT NULL,
|
|
364
|
+
enable_spawn INTEGER NOT NULL,
|
|
365
|
+
enable_teams INTEGER NOT NULL,
|
|
366
|
+
parent_session_id TEXT,
|
|
367
|
+
parent_agent_id TEXT,
|
|
368
|
+
agent_id TEXT,
|
|
369
|
+
conversation_id TEXT,
|
|
370
|
+
is_subagent INTEGER NOT NULL DEFAULT 0,
|
|
371
|
+
prompt TEXT,
|
|
372
|
+
metadata_json TEXT,
|
|
373
|
+
transcript_path TEXT NOT NULL,
|
|
374
|
+
hook_path TEXT NOT NULL,
|
|
375
|
+
messages_path TEXT,
|
|
376
|
+
updated_at TEXT NOT NULL
|
|
377
|
+
);
|
|
378
|
+
`),$.exec(`
|
|
379
|
+
CREATE TABLE IF NOT EXISTS subagent_spawn_queue (
|
|
380
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
381
|
+
root_session_id TEXT NOT NULL,
|
|
382
|
+
parent_agent_id TEXT NOT NULL,
|
|
383
|
+
task TEXT,
|
|
384
|
+
system_prompt TEXT,
|
|
385
|
+
created_at TEXT NOT NULL,
|
|
386
|
+
consumed_at TEXT
|
|
387
|
+
);
|
|
388
|
+
`),$.exec(`
|
|
389
|
+
CREATE TABLE IF NOT EXISTS schedules (
|
|
390
|
+
schedule_id TEXT PRIMARY KEY,
|
|
391
|
+
name TEXT NOT NULL,
|
|
392
|
+
cron_pattern TEXT NOT NULL,
|
|
393
|
+
prompt TEXT NOT NULL,
|
|
394
|
+
provider TEXT NOT NULL,
|
|
395
|
+
model TEXT NOT NULL,
|
|
396
|
+
mode TEXT NOT NULL DEFAULT 'act',
|
|
397
|
+
workspace_root TEXT,
|
|
398
|
+
cwd TEXT,
|
|
399
|
+
system_prompt TEXT,
|
|
400
|
+
max_iterations INTEGER,
|
|
401
|
+
timeout_seconds INTEGER,
|
|
402
|
+
max_parallel INTEGER NOT NULL DEFAULT 1,
|
|
403
|
+
enabled INTEGER NOT NULL DEFAULT 1,
|
|
404
|
+
created_at TEXT NOT NULL,
|
|
405
|
+
updated_at TEXT NOT NULL,
|
|
406
|
+
last_run_at TEXT,
|
|
407
|
+
next_run_at TEXT,
|
|
408
|
+
claim_token TEXT,
|
|
409
|
+
claim_started_at TEXT,
|
|
410
|
+
claim_until_at TEXT,
|
|
411
|
+
created_by TEXT,
|
|
412
|
+
tags TEXT,
|
|
413
|
+
metadata_json TEXT
|
|
414
|
+
);
|
|
415
|
+
`),$.exec(`
|
|
416
|
+
CREATE TABLE IF NOT EXISTS schedule_executions (
|
|
417
|
+
execution_id TEXT PRIMARY KEY,
|
|
418
|
+
schedule_id TEXT NOT NULL,
|
|
419
|
+
session_id TEXT,
|
|
420
|
+
triggered_at TEXT NOT NULL,
|
|
421
|
+
started_at TEXT,
|
|
422
|
+
ended_at TEXT,
|
|
423
|
+
status TEXT NOT NULL,
|
|
424
|
+
exit_code INTEGER,
|
|
425
|
+
error_message TEXT,
|
|
426
|
+
iterations INTEGER,
|
|
427
|
+
tokens_used INTEGER,
|
|
428
|
+
cost_usd REAL,
|
|
429
|
+
FOREIGN KEY (schedule_id) REFERENCES schedules(schedule_id) ON DELETE CASCADE,
|
|
430
|
+
FOREIGN KEY (session_id) REFERENCES sessions(session_id) ON DELETE SET NULL
|
|
431
|
+
);
|
|
432
|
+
`),$.exec(`
|
|
433
|
+
CREATE INDEX IF NOT EXISTS idx_schedule_executions_schedule
|
|
434
|
+
ON schedule_executions(schedule_id, triggered_at DESC);
|
|
435
|
+
`),$.exec(`
|
|
436
|
+
CREATE INDEX IF NOT EXISTS idx_schedules_next_run
|
|
437
|
+
ON schedules(enabled, next_run_at);
|
|
438
|
+
`),!Y.includeLegacyMigrations)return;let X=$.prepare("PRAGMA table_info(sessions);").all(),Q=(T)=>X.some((K)=>K.name===T);if(!Q("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(!Q("parent_session_id"))$.exec("ALTER TABLE sessions ADD COLUMN parent_session_id TEXT;");if(!Q("parent_agent_id"))$.exec("ALTER TABLE sessions ADD COLUMN parent_agent_id TEXT;");if(!Q("agent_id"))$.exec("ALTER TABLE sessions ADD COLUMN agent_id TEXT;");if(!Q("conversation_id"))$.exec("ALTER TABLE sessions ADD COLUMN conversation_id TEXT;");if(!Q("is_subagent"))$.exec("ALTER TABLE sessions ADD COLUMN is_subagent INTEGER NOT NULL DEFAULT 0;");if(!Q("messages_path"))$.exec("ALTER TABLE sessions ADD COLUMN messages_path TEXT;");if(!Q("metadata_json"))$.exec("ALTER TABLE sessions ADD COLUMN metadata_json TEXT;");let J=$.prepare("PRAGMA table_info(schedules);").all(),Z=(T)=>J.some((K)=>K.name===T);if(!Z("claim_token"))$.exec("ALTER TABLE schedules ADD COLUMN claim_token TEXT;");if(!Z("claim_started_at"))$.exec("ALTER TABLE schedules ADD COLUMN claim_started_at TEXT;");if(!Z("claim_until_at"))$.exec("ALTER TABLE schedules ADD COLUMN claim_until_at TEXT;")}function QH(){return P8()}function FY($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function JH($){return{...$,tasks:$.tasks.map((Y)=>({...Y,createdAt:new Date(Y.createdAt),updatedAt:new Date(Y.updatedAt)})),mailbox:$.mailbox.map((Y)=>({...Y,sentAt:new Date(Y.sentAt),readAt:Y.readAt?new Date(Y.readAt):void 0})),missionLog:$.missionLog.map((Y)=>({...Y,ts:new Date(Y.ts)})),runs:($.runs??[]).map((Y)=>({...Y,startedAt:new Date(Y.startedAt),endedAt:Y.endedAt?new Date(Y.endedAt):void 0,nextAttemptAt:Y.nextAttemptAt?new Date(Y.nextAttemptAt):void 0,heartbeatAt:Y.heartbeatAt?new Date(Y.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((Y)=>({...Y,createdAt:new Date(Y.createdAt),finalizedAt:Y.finalizedAt?new Date(Y.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((Y)=>({...Y,createdAt:new Date(Y.createdAt),reviewedAt:Y.reviewedAt?new Date(Y.reviewedAt):void 0}))}}class R5{teamDirPath;db;constructor($={}){this.teamDirPath=$.teamDir??QH()}init(){this.getRawDb()}ensureTeamDir(){if(!$H(this.teamDirPath))YH(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return XH(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let $=DY(this.dbPath());return this.ensureSchema($),this.db=$,$}ensureSchema($){$.exec(`
|
|
439
|
+
CREATE TABLE IF NOT EXISTS team_events (
|
|
440
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
441
|
+
team_name TEXT NOT NULL,
|
|
442
|
+
ts TEXT NOT NULL,
|
|
443
|
+
event_type TEXT NOT NULL,
|
|
444
|
+
payload_json TEXT NOT NULL,
|
|
445
|
+
causation_id TEXT,
|
|
446
|
+
correlation_id TEXT
|
|
447
|
+
);
|
|
448
|
+
CREATE INDEX IF NOT EXISTS idx_team_events_name_ts
|
|
449
|
+
ON team_events(team_name, ts DESC);
|
|
450
|
+
|
|
451
|
+
CREATE TABLE IF NOT EXISTS team_runtime_snapshot (
|
|
452
|
+
team_name TEXT PRIMARY KEY,
|
|
453
|
+
state_json TEXT NOT NULL,
|
|
454
|
+
teammates_json TEXT NOT NULL,
|
|
455
|
+
updated_at TEXT NOT NULL
|
|
456
|
+
);
|
|
457
|
+
|
|
458
|
+
CREATE TABLE IF NOT EXISTS team_tasks (
|
|
459
|
+
team_name TEXT NOT NULL,
|
|
460
|
+
task_id TEXT NOT NULL,
|
|
461
|
+
title TEXT NOT NULL,
|
|
462
|
+
description TEXT NOT NULL,
|
|
463
|
+
status TEXT NOT NULL,
|
|
464
|
+
assignee TEXT,
|
|
465
|
+
depends_on_json TEXT NOT NULL,
|
|
466
|
+
summary TEXT,
|
|
467
|
+
version INTEGER NOT NULL DEFAULT 1,
|
|
468
|
+
updated_at TEXT NOT NULL,
|
|
469
|
+
PRIMARY KEY(team_name, task_id)
|
|
470
|
+
);
|
|
471
|
+
|
|
472
|
+
CREATE TABLE IF NOT EXISTS team_runs (
|
|
473
|
+
team_name TEXT NOT NULL,
|
|
474
|
+
run_id TEXT NOT NULL,
|
|
475
|
+
agent_id TEXT NOT NULL,
|
|
476
|
+
task_id TEXT,
|
|
477
|
+
status TEXT NOT NULL,
|
|
478
|
+
message TEXT NOT NULL,
|
|
479
|
+
started_at TEXT,
|
|
480
|
+
ended_at TEXT,
|
|
481
|
+
error TEXT,
|
|
482
|
+
lease_owner TEXT,
|
|
483
|
+
heartbeat_at TEXT,
|
|
484
|
+
version INTEGER NOT NULL DEFAULT 1,
|
|
485
|
+
PRIMARY KEY(team_name, run_id)
|
|
486
|
+
);
|
|
487
|
+
CREATE INDEX IF NOT EXISTS idx_team_runs_status
|
|
488
|
+
ON team_runs(team_name, status);
|
|
489
|
+
|
|
490
|
+
CREATE TABLE IF NOT EXISTS team_outcomes (
|
|
491
|
+
team_name TEXT NOT NULL,
|
|
492
|
+
outcome_id TEXT NOT NULL,
|
|
493
|
+
title TEXT NOT NULL,
|
|
494
|
+
status TEXT NOT NULL,
|
|
495
|
+
schema_json TEXT NOT NULL,
|
|
496
|
+
finalized_at TEXT,
|
|
497
|
+
version INTEGER NOT NULL DEFAULT 1,
|
|
498
|
+
PRIMARY KEY(team_name, outcome_id)
|
|
499
|
+
);
|
|
500
|
+
|
|
501
|
+
CREATE TABLE IF NOT EXISTS team_outcome_fragments (
|
|
502
|
+
team_name TEXT NOT NULL,
|
|
503
|
+
outcome_id TEXT NOT NULL,
|
|
504
|
+
fragment_id TEXT NOT NULL,
|
|
505
|
+
section TEXT NOT NULL,
|
|
506
|
+
source_agent_id TEXT NOT NULL,
|
|
507
|
+
source_run_id TEXT,
|
|
508
|
+
content TEXT NOT NULL,
|
|
509
|
+
status TEXT NOT NULL,
|
|
510
|
+
reviewed_by TEXT,
|
|
511
|
+
reviewed_at TEXT,
|
|
512
|
+
version INTEGER NOT NULL DEFAULT 1,
|
|
513
|
+
PRIMARY KEY(team_name, fragment_id)
|
|
514
|
+
);
|
|
515
|
+
`)}run($,Y=[]){return this.getRawDb().prepare($).run(...Y)}queryOne($,Y=[]){return this.getRawDb().prepare($).get(...Y)??void 0}queryAll($,Y=[]){return this.getRawDb().prepare($).all(...Y)}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map(($)=>$.team_name)}readState($){let Y=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[FY($)]);if(!Y)return;return JH(JSON.parse(Y.state_json))}readHistory($,Y=200){return this.queryAll("SELECT event_type, payload_json, ts FROM team_events WHERE team_name = ? ORDER BY id DESC LIMIT ?",[FY($),Y]).map((X)=>({eventType:X.event_type,payload:JSON.parse(X.payload_json),ts:X.ts}))}loadRuntime($){let Y=FY($),X=this.readState(Y),Q=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[Y]),J=Q?JSON.parse(Q.teammates_json):[],Z=this.markInProgressRunsInterrupted(Y,"runtime_recovered");return{state:X,teammates:J,interruptedRunIds:Z}}appendTeamEvent($,Y,X,Q){this.run(`INSERT INTO team_events (team_name, ts, event_type, payload_json, causation_id, correlation_id)
|
|
516
|
+
VALUES (?, ?, ?, ?, NULL, ?)`,[FY($),O0(),Y,JSON.stringify(X),Q??null])}persistRuntime($,Y,X){let Q=FY($),J=O0();this.run(`INSERT INTO team_runtime_snapshot (team_name, state_json, teammates_json, updated_at)
|
|
517
|
+
VALUES (?, ?, ?, ?)
|
|
518
|
+
ON CONFLICT(team_name) DO UPDATE SET
|
|
519
|
+
state_json = excluded.state_json,
|
|
520
|
+
teammates_json = excluded.teammates_json,
|
|
521
|
+
updated_at = excluded.updated_at`,[Q,JSON.stringify(Y),JSON.stringify(X),J]);for(let Z of Y.tasks)this.run(`INSERT INTO team_tasks (team_name, task_id, title, description, status, assignee, depends_on_json, summary, version, updated_at)
|
|
522
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?)
|
|
523
|
+
ON CONFLICT(team_name, task_id) DO UPDATE SET
|
|
524
|
+
title = excluded.title,
|
|
525
|
+
description = excluded.description,
|
|
526
|
+
status = excluded.status,
|
|
527
|
+
assignee = excluded.assignee,
|
|
528
|
+
depends_on_json = excluded.depends_on_json,
|
|
529
|
+
summary = excluded.summary,
|
|
530
|
+
version = team_tasks.version + 1,
|
|
531
|
+
updated_at = excluded.updated_at`,[Q,Z.id,Z.title,Z.description,Z.status,Z.assignee??null,JSON.stringify(Z.dependsOn??[]),Z.summary??null,Z.updatedAt.toISOString()]);for(let Z of Y.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)
|
|
532
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
|
|
533
|
+
ON CONFLICT(team_name, run_id) DO UPDATE SET
|
|
534
|
+
agent_id = excluded.agent_id,
|
|
535
|
+
task_id = excluded.task_id,
|
|
536
|
+
status = excluded.status,
|
|
537
|
+
message = excluded.message,
|
|
538
|
+
started_at = excluded.started_at,
|
|
539
|
+
ended_at = excluded.ended_at,
|
|
540
|
+
error = excluded.error,
|
|
541
|
+
lease_owner = excluded.lease_owner,
|
|
542
|
+
heartbeat_at = excluded.heartbeat_at,
|
|
543
|
+
version = team_runs.version + 1`,[Q,Z.id,Z.agentId,Z.taskId??null,Z.status,Z.message,Z.startedAt?Z.startedAt.toISOString():null,Z.endedAt?Z.endedAt.toISOString():null,Z.error??null,Z.leaseOwner??null,Z.heartbeatAt?Z.heartbeatAt.toISOString():null]);for(let Z of Y.outcomes??[])this.run(`INSERT INTO team_outcomes (team_name, outcome_id, title, status, schema_json, finalized_at, version)
|
|
544
|
+
VALUES (?, ?, ?, ?, ?, ?, 1)
|
|
545
|
+
ON CONFLICT(team_name, outcome_id) DO UPDATE SET
|
|
546
|
+
title = excluded.title,
|
|
547
|
+
status = excluded.status,
|
|
548
|
+
schema_json = excluded.schema_json,
|
|
549
|
+
finalized_at = excluded.finalized_at,
|
|
550
|
+
version = team_outcomes.version + 1`,[Q,Z.id,Z.title,Z.status,JSON.stringify({requiredSections:Z.requiredSections}),Z.finalizedAt?Z.finalizedAt.toISOString():null]);for(let Z of Y.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)
|
|
551
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
|
|
552
|
+
ON CONFLICT(team_name, fragment_id) DO UPDATE SET
|
|
553
|
+
outcome_id = excluded.outcome_id,
|
|
554
|
+
section = excluded.section,
|
|
555
|
+
source_agent_id = excluded.source_agent_id,
|
|
556
|
+
source_run_id = excluded.source_run_id,
|
|
557
|
+
content = excluded.content,
|
|
558
|
+
status = excluded.status,
|
|
559
|
+
reviewed_by = excluded.reviewed_by,
|
|
560
|
+
reviewed_at = excluded.reviewed_at,
|
|
561
|
+
version = team_outcome_fragments.version + 1`,[Q,Z.outcomeId,Z.id,Z.section,Z.sourceAgentId,Z.sourceRunId??null,Z.content,Z.status,Z.reviewedBy??null,Z.reviewedAt?Z.reviewedAt.toISOString():null])}markInProgressRunsInterrupted($,Y){let X=FY($),Q=this.queryAll("SELECT run_id FROM team_runs WHERE team_name = ? AND status IN ('queued', 'running')",[X]);if(Q.length===0)return[];let J=O0();return this.run(`UPDATE team_runs SET status = 'interrupted', error = ?, ended_at = ?, version = version + 1
|
|
562
|
+
WHERE team_name = ? AND status IN ('queued', 'running')`,[Y,J,X]),Q.map((Z)=>Z.run_id)}handleTeamEvent($,Y){this.appendTeamEvent($,Y.type,Y)}}var GH="# Workspace Configuration";function GT(){return`agent-team-${UH(5)}`}function TT($,Y,X,Q){let J=Y==="plan"?t1.readonly:t1.development;return V6({cwd:$,...J,enableSkills:!!X,executors:{...X?{skills:X}:{},...Q??{}}})}var KT="SKILL.md";function WH($){return V5($).filter((Y)=>!Y.disabled).map((Y)=>Y.name.trim()).filter((Y)=>Y.length>0).sort((Y,X)=>Y.localeCompare(X))}function V5($){return[...$.getSnapshot("skill").entries()].map(([X,Q])=>{let J=Q.item;return{id:X,name:J.name.trim(),description:J.description?.trim(),disabled:J.disabled===!0}})}function UT($){for(let Y of E6($)){if(!E5(Y))continue;let X=ZT(Y,KT);if(E5(X))return!0;try{let Q=ZH(Y,{withFileTypes:!0});for(let J of Q){if(!J.isDirectory())continue;if(E5(ZT(Y,J.name,KT)))return!0}}catch{}}return!1}function RH($,Y){let X=Y.trim().replace(/^\/+/,"").toLowerCase();if(!X)return{error:"Missing skill name."};let Q=$.getSnapshot("skill"),J=Q.get(X);if(J){let U=J.item;if(U.disabled===!0)return{error:`Skill "${U.name}" is configured but disabled.`};return{id:X,skill:U}}let Z=X.includes(":")?X.split(":").at(-1)??X:X,T=[...Q.entries()].filter(([U])=>{if(U===Z)return!0;return U.endsWith(`:${Z}`)});if(T.length===1){let[U,G]=T[0],W=G.item;if(W.disabled===!0)return{error:`Skill "${W.name}" is configured but disabled.`};return{id:U,skill:W}}if(T.length>1)return{error:`Skill "${Y}" is ambiguous. Use one of: ${T.map(([U])=>U).join(", ")}`};let K=WH($);return{error:K.length>0?`Skill "${Y}" not found. Available skills: ${K.join(", ")}`:"No skills are currently available."}}function EH($,Y){let X=new Set,Q=async(J,Z)=>{await Y;let T=RH($,J);if("error"in T)return T.error;let{id:K,skill:U}=T;if(X.has(K))return`Skill "${U.name}" is already running.`;X.add(K);try{let G=Z?.trim(),W=G?`
|
|
563
|
+
<command-args>${G}</command-args>`:"",R=U.description?.trim()?`Description: ${U.description.trim()}
|
|
564
|
+
|
|
565
|
+
`:"";return`<command-name>${U.name}</command-name>${W}
|
|
566
|
+
<command-instructions>
|
|
567
|
+
${R}${U.instructions}
|
|
568
|
+
</command-instructions>`}finally{X.delete(K)}};return Object.defineProperty(Q,"configuredSkills",{get:()=>V5($),enumerable:!0,configurable:!1}),Q}function VH($,Y){if(!$)return;for(let X of $.getTeammateIds())try{$.shutdownTeammate(X,Y)}catch{}}function AH($){let Y=$.lastIndexOf(GH);if(Y<0)return;let X=$.slice(Y).trim();return X.length>0?X:void 0}function DH($){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 A9{build($){let{config:Y,hooks:X,extensions:Q,logger:J,createSpawnTool:Z,onTeamRestored:T,userInstructionWatcher:K,defaultToolExecutors:U}=$,G=$.onTeamEvent??(()=>{}),W=DH(Y),R=[],V=Y.teamName?.trim()||GT(),A=!1,H=Boolean(K),z=K,D=Promise.resolve(),B;if(!z&&W.enableTools&&UT(Y.cwd))z=Z9({skills:{workspacePath:Y.cwd},rules:{workspacePath:Y.cwd},workflows:{workspacePath:Y.cwd}}),D=z.start().catch(()=>{});if(W.enableTools&&z&&(H||UT(Y.cwd)||V5(z).length>0))B=EH(z,D);if(W.enableTools)R.push(...TT(Y.cwd,W.mode,B,U));let w,x=W.enableAgentTeams?new R5:void 0;x?.init();let q=x?.loadRuntime(V),_=q?.state,C=q?.teammates??[],k=new Map(C.map((j)=>[j.agentId,j])),f=()=>{if(!W.enableAgentTeams)return;if(!w){if(w=new TH({teamName:V,leadAgentId:"lead",missionLogIntervalSteps:W.missionLogIntervalSteps,missionLogIntervalMs:W.missionLogIntervalMs,onTeamEvent:(j)=>{if(G(j),w&&x){if(j.type==="teammate_spawned"&&j.teammate?.rolePrompt){let N={agentId:j.agentId,rolePrompt:j.teammate.rolePrompt,modelId:j.teammate.modelId,maxIterations:j.teammate.maxIterations};k.set(N.agentId,N)}if(j.type==="teammate_shutdown")k.delete(j.agentId);x.handleTeamEvent(V,j),x.persistRuntime(V,w.exportState(),Array.from(k.values()))}}}),_)w.hydrateState(_),w.markStaleRunsInterrupted("runtime_recovered")}if(!A){if(!w)return;A=!0;let j=KH({runtime:w,leadAgentId:"lead",restoredFromPersistence:Boolean(_),restoredTeammates:C,createBaseTools:W.enableTools?()=>TT(Y.cwd,W.mode,B,U):void 0,teammateRuntime:{providerId:Y.providerId,modelId:Y.modelId,cwd:Y.cwd,apiKey:Y.apiKey??"",baseUrl:Y.baseUrl,headers:Y.headers,providerConfig:Y.providerConfig,knownModels:Y.knownModels,thinking:Y.thinking,clineWorkspaceMetadata:Y.providerId==="cline"?AH(Y.systemPrompt):void 0,maxIterations:Y.maxIterations,hooks:X,extensions:Q??Y.extensions,logger:J??Y.logger}});if(j.restoredFromPersistence)T?.();R.push(...j.tools)}return w};if(W.enableSpawnAgent&&Z){let j=Z();R.push({...j,execute:async(N,_0)=>{return f(),j.execute(N,_0)}})}if(W.enableAgentTeams)f();let y=w?()=>{let j=w;if(!j)return;let N=j.listTasks(),_0=N.some((L)=>L.status==="in_progress"||L.status==="pending"),P=j.listRuns({}),E=P.some((L)=>L.status==="running"||L.status==="queued");if(_0||E){let L=N.filter((d)=>d.status==="in_progress"||d.status==="pending").map((d)=>`${d.id} (${d.status}): ${d.title}`).join(", "),n=P.filter((d)=>d.status==="running"||d.status==="queued").map((d)=>`${d.id} (${d.status})`).join(", "),u=[];if(L)u.push(`Unfinished tasks: ${L}`);if(n)u.push(`Active runs: ${n}`);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:R,logger:J??Y.logger,teamRuntime:w,completionGuard:y,shutdown:(j)=>{if(VH(w,j),!H)z?.stop()}}}}import{mkdir as FH,readFile as HH,unlink as A5,writeFile as zH}from"node:fs/promises";import{join as WT}from"node:path";function qH($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function NH($){return new Promise((Y)=>setTimeout(Y,$))}async function MH($,Y={}){let X=Y.approvalDir?.trim(),Q=Y.sessionId?.trim();if(!X||!Q)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await FH(X,{recursive:!0});let J=qH(`${$.toolCallId}`),Z=WT(X,`${Q}.request.${J}.json`),T=WT(X,`${Q}.decision.${J}.json`),K=Y.nowIso??(()=>new Date().toISOString());await zH(Z,`${JSON.stringify({requestId:J,sessionId:Q,createdAt:K(),toolCallId:$.toolCallId,toolName:$.toolName,input:$.input,iteration:$.iteration,agentId:$.agentId,conversationId:$.conversationId},null,2)}
|
|
569
|
+
`,"utf8");let U=Y.timeoutMs??300000,G=Y.pollIntervalMs??200,W=Date.now();while(Date.now()-W<U){try{let R=await HH(T,"utf8"),V=JSON.parse(R),A={approved:V.approved===!0,reason:typeof V.reason==="string"?V.reason:void 0};try{await A5(T)}catch{}try{await A5(Z)}catch{}return A}catch{}await NH(G)}try{await A5(Z)}catch{}return{approved:!1,reason:"Tool approval request timed out"}}function BH($){return $.disabled!==!0}function RT($){return[...$.getSnapshot("workflow").entries()].map(([X,Q])=>({id:X,workflow:Q.item})).filter(({workflow:X})=>BH(X)).map(({id:X,workflow:Q})=>({id:X,name:Q.name,instructions:Q.instructions})).sort((X,Q)=>X.name.localeCompare(Q.name))}function IH($,Y){if(!$.startsWith("/")||$.length<2)return $;let X=$.match(/^\/(\S+)/);if(!X)return $;let Q=X[1];if(!Q)return $;let J=Q.length+1,Z=$.slice(J),T=RT(Y).find((K)=>K.name===Q);return T?`${T.instructions}${Z}`:$}import{existsSync as O5,readFileSync as P5}from"node:fs";import{readFile as Yz,stat as Xz}from"node:fs/promises";import{homedir as Qz}from"node:os";import{isAbsolute as Jz,join as N6,resolve as Zz}from"node:path";import{Agent as Tz,createSpawnAgentTool as Kz}from"@clinebot/agents";import{nanoid as Uz}from"nanoid";import{spawn as OH}from"node:child_process";import{appendFileSync as PH,readFileSync as LH}from"node:fs";function F9($){if(!$||typeof $!=="object")return{};let Y={};for(let[X,Q]of Object.entries($))Y[X]=typeof Q==="string"?Q:JSON.stringify(Q);return Y}function D9($,Y,X){let Q=X instanceof Error?`: ${X.message}`:"",J=`${Y}${Q}`;if($?.warn){$.warn(J);return}console.warn(J)}function ET($,Y){if(!Y)return $;if(!$)return{...Y};let X=[$.context,Y.context].filter((J)=>typeof J==="string"&&J.length>0).join(`
|
|
570
|
+
`),Q=[...$.appendMessages??[],...Y.appendMessages??[]];return{cancel:$.cancel===!0||Y.cancel===!0?!0:void 0,review:$.review===!0||Y.review===!0?!0:void 0,context:X||void 0,overrideInput:Y.overrideInput!==void 0?Y.overrideInput:$.overrideInput,systemPrompt:Y.systemPrompt!==void 0?Y.systemPrompt:$.systemPrompt,appendMessages:Q.length>0?Q:void 0}}function SH($){if(!$||typeof $!=="object")return;let Y=$,X=typeof Y.context==="string"?Y.context:typeof Y.contextModification==="string"?Y.contextModification:typeof Y.errorMessage==="string"?Y.errorMessage:void 0;return{cancel:typeof Y.cancel==="boolean"?Y.cancel:void 0,review:typeof Y.review==="boolean"?Y.review:void 0,context:X,overrideInput:Object.hasOwn(Y,"overrideInput")?Y.overrideInput:void 0}}function VT($){let Y=String($??"").toLowerCase();return Y.includes("cancel")||Y.includes("abort")||Y.includes("interrupt")}function wH($){zX($)}function l0($,Y){let X=process.env.CLINE_USER_ID?.trim()||process.env.USER?.trim()||"unknown",Q={rootSessionId:Y.rootSessionId||$.conversationId,hookLogPath:Y.hookLogPath};return{clineVersion:process.env.CLINE_VERSION?.trim()||"",timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:Q,workspaceRoots:Y.workspacePath?[Y.workspacePath]:[],userId:X,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function CH($){let Y=$.trim();if(!Y)return{};let Q=Y.split(`
|
|
571
|
+
`).map((Z)=>Z.trim()).filter(Boolean).filter((Z)=>Z.startsWith("HOOK_CONTROL\t")).map((Z)=>Z.slice(13)),J=Q.length>0?Q[Q.length-1]:Y;try{return{parsedJson:JSON.parse(J)}}catch(Z){return{parseError:Z instanceof Error?Z.message:"Failed to parse hook stdout JSON"}}}async function AT($,Y){if(Y.command.length===0)throw Error("runHookCommand requires non-empty command");let X=OH(Y.command[0],Y.command.slice(1),{cwd:Y.cwd,env:Y.env,stdio:Y.detached?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:Y.detached}),Q=JSON.stringify($);if(!X.stdin)throw Error("hook command failed to create stdin");if(X.stdin.write(Q),X.stdin.end(),Y.detached){await new Promise((U,G)=>{X.once("error",G),X.once("spawn",()=>U())}),X.unref();return}if(!X.stdout||!X.stderr)throw Error("hook command failed to create stdout/stderr");let J="",Z="",T=!1,K;return X.stdout.on("data",(U)=>{J+=U.toString()}),X.stderr.on("data",(U)=>{Z+=U.toString()}),await new Promise((U,G)=>{if(X.once("error",G),(Y.timeoutMs??0)>0)K=setTimeout(()=>{T=!0,X.kill("SIGKILL")},Y.timeoutMs);X.once("close",(W)=>{if(K)clearTimeout(K);let{parsedJson:R,parseError:V}=CH(J);U({exitCode:W,stdout:J,stderr:Z,parsedJson:R,parseError:V,timedOut:T})})})}function yH($){try{let X=LH($,"utf8").split(/\r?\n/,1)[0]?.trim();if(!X?.startsWith("#!"))return;let Q=X.slice(2).trim();if(!Q)return;let J=Q.split(/\s+/).filter(Boolean);return J.length>0?J:void 0}catch{return}}function jH($){let Y=yH($);if(Y&&Y.length>0)return[...Y,$];let X=$.toLowerCase();if(X.endsWith(".sh")||X.endsWith(".bash")||X.endsWith(".zsh"))return["/bin/bash",$];if(X.endsWith(".js")||X.endsWith(".mjs")||X.endsWith(".cjs"))return["node",$];if(X.endsWith(".ts")||X.endsWith(".mts")||X.endsWith(".cts"))return["bun","run",$];return["/bin/bash",$]}function xH($){let Y={};for(let X of o8($)){if(!X.hookEventName)continue;let Q=Y[X.hookEventName]??[];Q.push(jH(X.path)),Y[X.hookEventName]=Q}return Y}async function vH($){let Y;for(let X of $.commands){let Q=X.join(" ");try{let J=await AT($.payload,{command:X,cwd:$.cwd,env:process.env,detached:!1,timeoutMs:$.timeoutMs});if(J?.timedOut){D9($.logger,`hook command timed out: ${Q}`);continue}if(J?.parseError){D9($.logger,`hook command returned invalid JSON control output: ${Q} (${J.parseError})`);continue}Y=ET(Y,SH(J?.parsedJson))}catch(J){D9($.logger,`hook command failed: ${Q}`,J)}}return Y}function HY($){for(let Y of $.commands){let X=Y.join(" ");AT($.payload,{command:Y,cwd:$.cwd,env:process.env,detached:!0}).catch((Q)=>{D9($.logger,`hook command failed: ${X}`,Q)})}}function DT($){let Y={cwd:$.workspacePath,workspacePath:$.workspacePath,hookLogPath:$.hookLogPath,rootSessionId:$.rootSessionId},X=(Q)=>{let J=`${JSON.stringify({ts:new Date().toISOString(),...Q})}
|
|
572
|
+
`;wH($.hookLogPath),PH($.hookLogPath,J,"utf8")};return{onRunStart:async(Q)=>{X({...l0(Q,Y),hookName:"agent_start",taskStart:{taskMetadata:{}}}),X({...l0(Q,Y),hookName:"prompt_submit",userPromptSubmit:{prompt:Q.userMessage,attachments:[]}});return},onToolCallStart:async(Q)=>{X({...l0(Q,Y),hookName:"tool_call",iteration:Q.iteration,tool_call:{id:Q.call.id,name:Q.call.name,input:Q.call.input},preToolUse:{toolName:Q.call.name,parameters:F9(Q.call.input)}});return},onToolCallEnd:async(Q)=>{X({...l0(Q,Y),hookName:"tool_result",iteration:Q.iteration,tool_result:Q.record,postToolUse:{toolName:Q.record.name,parameters:F9(Q.record.input),result:typeof Q.record.output==="string"?Q.record.output:JSON.stringify(Q.record.output),success:!Q.record.error,executionTimeMs:Q.record.durationMs}});return},onTurnEnd:async(Q)=>{X({...l0(Q,Y),hookName:"agent_end",iteration:Q.iteration,turn:Q.turn,taskComplete:{taskMetadata:{}}});return},onSessionShutdown:async(Q)=>{if(VT(Q.reason))X({...l0(Q,Y),hookName:"agent_abort",reason:Q.reason,taskCancel:{taskMetadata:{}}});X({...l0(Q,Y),hookName:"session_shutdown",reason:Q.reason});return}}}function FT($){let Y=xH($.workspacePath);if(!Object.values(Y).some((U)=>(U?.length??0)>0))return;let Q=async(U)=>{let G=Y.agent_start??[];if(G.length>0)HY({commands:G,cwd:$.cwd,logger:$.logger,payload:{...l0(U,$),hookName:"agent_start",taskStart:{taskMetadata:{}}}});let W=Y.prompt_submit??[];if(W.length>0)HY({commands:W,cwd:$.cwd,logger:$.logger,payload:{...l0(U,$),hookName:"prompt_submit",userPromptSubmit:{prompt:U.userMessage,attachments:[]}}})},J=async(U)=>{let G=Y.tool_call??[];if(G.length===0)return;return vH({commands:G,cwd:$.cwd,logger:$.logger,timeoutMs:$.toolCallTimeoutMs??120000,payload:{...l0(U,$),hookName:"tool_call",iteration:U.iteration,tool_call:{id:U.call.id,name:U.call.name,input:U.call.input},preToolUse:{toolName:U.call.name,parameters:F9(U.call.input)}}})},Z=async(U)=>{let G=Y.tool_result??[];if(G.length===0)return;HY({commands:G,cwd:$.cwd,logger:$.logger,payload:{...l0(U,$),hookName:"tool_result",iteration:U.iteration,tool_result:U.record,postToolUse:{toolName:U.record.name,parameters:F9(U.record.input),result:typeof U.record.output==="string"?U.record.output:JSON.stringify(U.record.output),success:!U.record.error,executionTimeMs:U.record.durationMs}}})},T=async(U)=>{let G=Y.agent_end??[];if(G.length===0)return;HY({commands:G,cwd:$.cwd,logger:$.logger,payload:{...l0(U,$),hookName:"agent_end",iteration:U.iteration,turn:U.turn,taskComplete:{taskMetadata:{}}}})},K=async(U)=>{if(VT(U.reason)){let W=Y.agent_abort??[];if(W.length>0)HY({commands:W,cwd:$.cwd,logger:$.logger,payload:{...l0(U,$),hookName:"agent_abort",reason:U.reason,taskCancel:{taskMetadata:{}}}})}let G=Y.session_shutdown??[];if(G.length===0)return;HY({commands:G,cwd:$.cwd,logger:$.logger,payload:{...l0(U,$),hookName:"session_shutdown",reason:U.reason}})};return{onRunStart:async(U)=>{await Q(U);return},onToolCallStart:async(U)=>J(U),onToolCallEnd:async(U)=>{await Z(U);return},onTurnEnd:async(U)=>{await T(U);return},onSessionShutdown:async(U)=>{await K(U);return}}}function x1($,Y){let X=$.map((Q)=>Q[Y]).filter((Q)=>typeof Q==="function");if(X.length===0)return;return async(Q)=>{let J;for(let Z of X){let T=await Z(Q);J=ET(J,T)}return J}}function HT($){let Y=$.filter((X)=>X!==void 0);if(Y.length===0)return;return{onRunStart:x1(Y,"onRunStart"),onRunEnd:x1(Y,"onRunEnd"),onIterationStart:x1(Y,"onIterationStart"),onIterationEnd:x1(Y,"onIterationEnd"),onTurnStart:x1(Y,"onTurnStart"),onTurnEnd:x1(Y,"onTurnEnd"),onToolCallStart:x1(Y,"onToolCallStart"),onToolCallEnd:x1(Y,"onToolCallEnd"),onSessionShutdown:x1(Y,"onSessionShutdown"),onError:x1(Y,"onError")}}import{existsSync as qT,mkdirSync as hH,readFileSync as _H,writeFileSync as gH}from"node:fs";import{dirname as fH}from"node:path";import{providers as D5}from"@clinebot/llms";import{z as H$}from"zod";var zT=D5.ProviderSettingsSchema,H6=D5.toProviderConfig,kH=H$.object({settings:D5.ProviderSettingsSchema,updatedAt:H$.string().datetime(),tokenSource:H$.enum(["manual","oauth","migration"]).default("manual")}),F5=H$.object({version:H$.literal(1),lastUsedProvider:H$.string().min(1).optional(),providers:H$.record(H$.string(),kH)});function z6(){return{version:1,providers:{}}}function mH(){return new Date().toISOString()}class zY{filePath;constructor($={}){this.filePath=$.filePath??WX()}getFilePath(){return this.filePath}read(){if(!qT(this.filePath))return z6();try{let $=_H(this.filePath,"utf8"),Y=JSON.parse($),X=F5.safeParse(Y);if(X.success)return X.data}catch{}return z6()}write($){let Y=F5.parse($),X=fH(this.filePath);if(!qT(X))hH(X,{recursive:!0});gH(this.filePath,`${JSON.stringify(Y,null,2)}
|
|
573
|
+
`,"utf8")}saveProviderSettings($,Y={}){let X=zT.parse($),Q=this.read(),J=X.provider,Z=Y.setLastUsed!==!1,T=Q.providers[J],K=Y.tokenSource??T?.tokenSource??"manual",U={...Q,providers:{...Q.providers,[J]:{settings:X,updatedAt:mH(),tokenSource:K}},lastUsedProvider:Z?J:Q.lastUsedProvider};return this.write(U),U}getProviderSettings($){return this.read().providers[$]?.settings}getLastUsedProviderSettings(){let $=this.read(),Y=$.lastUsedProvider;if(!Y)return;return $.providers[Y]?.settings}getProviderConfig($){let Y=this.getProviderSettings($);if(!Y)return;return H6(Y)}getLastUsedProviderConfig(){let $=this.getLastUsedProviderSettings();if(!$)return;return H6($)}}function v1(){return new Date().toISOString()}function NT($,Y){if(Y<=0)return 0;return Math.round($/Y*100)}function bH($,Y){let X=new Set;for(let J of Y)if(J.status==="reviewed")X.add(`${J.outcomeId}:${J.section}`);let Q=new Set;for(let J of $){if(J.status==="finalized")continue;for(let Z of J.requiredSections)if(!X.has(`${J.id}:${Z}`))Q.add(`${J.id}:${Z}`)}return[...Q].sort((J,Z)=>J.localeCompare(Z))}function H5($,Y){let X={idle:0,running:0,stopped:0},Q={pending:0,in_progress:0,blocked:0,completed:0},J={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},Z={draft:0,in_review:0,finalized:0},T={draft:0,reviewed:0,rejected:0},K=0,U=0;for(let D of Y.members)if(X[D.status]+=1,D.role==="lead")K+=1;else U+=1;let G=[],W=[],R=Y.tasks.filter((D)=>D.status==="completed").length,V=new Map(Y.tasks.map((D)=>[D.id,D]));for(let D of Y.tasks){if(Q[D.status]+=1,D.status==="blocked"){G.push(D.id);continue}if(D.status!=="pending")continue;if(D.dependsOn.every((w)=>{return V.get(w)?.status==="completed"}))W.push(D.id)}let A=[],H,z=0;for(let D of Y.runs){if(J[D.status]+=1,D.status==="queued"||D.status==="running")A.push(D.id);let B=D.startedAt.getTime();if(B>=z)z=B,H=D.id}for(let D of Y.outcomes)Z[D.status]+=1;for(let D of Y.outcomeFragments)T[D.status]+=1;return{teamName:$,updatedAt:v1(),members:{total:Y.members.length,byStatus:X,leadCount:K,teammateCount:U},tasks:{total:Y.tasks.length,byStatus:Q,blockedTaskIds:G,readyTaskIds:W,completionPct:NT(R,Y.tasks.length)},runs:{total:Y.runs.length,byStatus:J,activeRunIds:A,latestRunId:H},outcomes:{total:Y.outcomes.length,byStatus:Z,finalizedPct:NT(Z.finalized,Y.outcomes.length),missingRequiredSections:bH(Y.outcomes,Y.outcomeFragments)},fragments:{total:Y.outcomeFragments.length,byStatus:T}}}function z5($){let{event:Y}=$;switch(Y.type){case"team_task_updated":return{teamName:$.teamName,sessionId:$.sessionId,eventType:Y.type,ts:v1(),taskId:Y.task.id,agentId:Y.task.assignee??Y.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:Y.type,ts:v1(),runId:Y.run.id,taskId:Y.run.taskId,agentId:Y.run.agentId,message:Y.run.error};case"run_progress":return{teamName:$.teamName,sessionId:$.sessionId,eventType:Y.type,ts:v1(),runId:Y.run.id,taskId:Y.run.taskId,agentId:Y.run.agentId,message:Y.message};case"outcome_created":case"outcome_finalized":return{teamName:$.teamName,sessionId:$.sessionId,eventType:Y.type,ts:v1(),outcomeId:Y.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:$.teamName,sessionId:$.sessionId,eventType:Y.type,ts:v1(),outcomeId:Y.fragment.outcomeId,fragmentId:Y.fragment.id,agentId:Y.fragment.sourceAgentId};case"team_message":return{teamName:$.teamName,sessionId:$.sessionId,eventType:Y.type,ts:v1(),taskId:Y.message.taskId,agentId:Y.message.fromAgentId,message:Y.message.subject};case"team_mission_log":return{teamName:$.teamName,sessionId:$.sessionId,eventType:Y.type,ts:v1(),taskId:Y.entry.taskId,agentId:Y.entry.agentId,message:Y.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:$.teamName,sessionId:$.sessionId,eventType:Y.type,ts:v1(),agentId:Y.agentId}}return{teamName:$.teamName,sessionId:$.sessionId,eventType:Y.type,ts:v1()}}var q5=BX,q6;((T)=>{T.CLI="cli";T.CLI_SUBAGENT="cli-subagent";T.CORE="core";T.CORE_SUBAGENT="core-subagent";T.DESKTOP="desktop";T.DESKTOP_CHAT="desktop-chat"})(q6||={});var uH="https://api.cline.bot",N5="workos:",dH=["cline","oca","openai-codex"];function pH($){return dH.includes($)}function cH($,Y){if($==="cline")return`${N5}${Y}`;return Y}function nH($,Y){if($==="cline"&&Y.toLowerCase().startsWith(N5))return Y.slice(N5.length);return Y}function lH($){let X=G1($)?.exp;if(typeof X==="number"&&X>0)return X*1000;return null}function iH($,Y){let X=$.auth?.expiresAt;if(typeof X==="number"&&Number.isFinite(X)&&X>0)return X;let Q=lH(Y);if(Q)return Q;return Date.now()-1}function rH($,Y){let X=Y.auth?.accessToken?.trim(),Q=Y.auth?.refreshToken?.trim();if(!X||!Q)return null;let J=nH($,X);if(!J)return null;return{access:J,refresh:Q,expires:iH(Y,J),accountId:Y.auth?.accountId}}function oH($,Y){let X=$?.expiresAt,Q=Y?.expiresAt;return $?.accessToken===Y?.accessToken&&$?.refreshToken===Y?.refreshToken&&$?.accountId===Y?.accountId&&X===Q}class H9 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 M5{providerSettingsManager;refreshInFlight=new Map;constructor($){this.providerSettingsManager=$?.providerSettingsManager??new zY}async resolveProviderApiKey($){if(!pH($.providerId))return null;return this.resolveWithSingleFlight($.providerId,$.forceRefresh)}async resolveWithSingleFlight($,Y=!1){let X=this.refreshInFlight.get($);if(X)return X;let Q=this.resolveProviderApiKeyInternal($,Y).catch((J)=>{throw J}).finally(()=>{this.refreshInFlight.delete($)});return this.refreshInFlight.set($,Q),Q}async resolveProviderApiKeyInternal($,Y){let X=this.providerSettingsManager.getProviderSettings($);if(!X)return null;let Q=rH($,X);if(!Q)return null;let J=await this.resolveCredentials($,X,Q,Y);if(!J)throw new H9($);let Z=cH($,J.access),T={...X.auth??{},accessToken:Z,refreshToken:J.refresh,accountId:J.accountId};T.expiresAt=J.expires;let K={...X,auth:T},U=!oH(X.auth,K.auth);if(U)this.providerSettingsManager.saveProviderSettings(K,{setLastUsed:!1,tokenSource:"oauth"});return{providerId:$,apiKey:Z,accountId:J.accountId,refreshed:U}}async resolveCredentials($,Y,X,Q){if($==="cline")return Y5(X,{apiBaseUrl:Y.baseUrl?.trim()||uH},{forceRefresh:Q});if($==="oca")return T5(X,{forceRefresh:Q},{mode:Y.oca?.mode});return Q5(X,{forceRefresh:Q})}}import{existsSync as B5,mkdirSync as sH,readdirSync as aH,rmdirSync as tH,unlinkSync as eH}from"node:fs";import{dirname as MT,join as z$}from"node:path";function E0(){return new Date().toISOString()}function $$($){if(!$||!B5($))return;try{eH($)}catch{}}class I5{ensureSessionsDir;constructor($){this.ensureSessionsDir=$}sessionArtifactsDir($){return z$(this.ensureSessionsDir(),$)}ensureSessionArtifactsDir($){let Y=this.sessionArtifactsDir($);if(!B5(Y))sH(Y,{recursive:!0});return Y}sessionTranscriptPath($){return z$(this.ensureSessionArtifactsDir($),`${$}.log`)}sessionHookPath($){return z$(this.ensureSessionArtifactsDir($),`${$}.hooks.jsonl`)}sessionMessagesPath($){return z$(this.ensureSessionArtifactsDir($),`${$}.messages.json`)}sessionManifestPath($,Y=!0){let X=Y?this.ensureSessionArtifactsDir($):this.sessionArtifactsDir($);return z$(X,`${$}.json`)}removeSessionDirIfEmpty($){let Y=this.sessionArtifactsDir($),X=this.ensureSessionsDir();while(Y.startsWith(X)&&Y!==X){if(!B5(Y)){Y=MT(Y);continue}try{if(aH(Y).length>0)break;tH(Y)}catch{break}Y=MT(Y)}}subagentArtifactPaths($,Y,X){let Q=this.ensureSessionArtifactsDir($);return{transcriptPath:z$(Q,`${$}.log`),hookPath:z$(Q,`${$}.hooks.jsonl`),messagesPath:z$(Q,`${$}.messages.json`)}}}import{z as W0}from"zod";var $z=W0.enum(q5),qY=W0.object({version:W0.literal(1),session_id:W0.string().min(1),source:W0.enum(q6),pid:W0.number().int(),started_at:W0.string().min(1),ended_at:W0.string().min(1).optional(),exit_code:W0.number().int().nullable().optional(),status:$z,interactive:W0.boolean(),provider:W0.string().min(1),model:W0.string().min(1),cwd:W0.string().min(1),workspace_root:W0.string().min(1),team_name:W0.string().min(1).optional(),enable_tools:W0.boolean(),enable_spawn:W0.boolean(),enable_teams:W0.boolean(),prompt:W0.string().optional(),metadata:W0.record(W0.string(),W0.unknown()).optional(),messages_path:W0.string().min(1).optional()});var BT=5000,Gz=20480000;async function Wz($){let Y=await Xz($);if(!Y.isFile())throw Error("Path is not a file");if(Y.size>Gz)throw Error("File is too large to read into context.");let X=await Yz($,"utf8");if(X.includes("\x00"))throw Error("Cannot read binary file into context.");return X}function Rz($){if(!$)return!1;return Object.values($).some((Y)=>typeof Y==="function")}function Ez($,Y){let X=[...$??[],...Y??[]];if(X.length===0)return;let Q=[],J=new Set;for(let Z of X){if(J.has(Z.name))continue;J.add(Z.name),Q.push(Z)}return Q}function Vz($){return JSON.stringify($,(Y,X)=>{if(X instanceof Error)return{name:X.name,message:X.message,stack:X.stack};return X})}function Az($,Y){let X=$.map((K)=>({...K})),Q=[...X].reverse().findIndex((K)=>K.role==="assistant");if(Q===-1)return X;let J=X.length-1-Q,Z=X[J],T=Y.usage;return X[J]={...Z,providerId:Z.providerId??Y.model.provider,modelId:Z.modelId??Y.model.id,modelInfo:Z.modelInfo??{id:Y.model.id,provider:Y.model.provider},metrics:{...Z.metrics??{},inputTokens:T.inputTokens,outputTokens:T.outputTokens,cacheReadTokens:T.cacheReadTokens,cacheWriteTokens:T.cacheWriteTokens,cost:T.totalCost},ts:Z.ts??Y.endedAt.getTime()},X}function IT($){let Y=typeof $.metadata_json==="string"&&$.metadata_json.trim().length>0?(()=>{try{let X=JSON.parse($.metadata_json);if(X&&typeof X==="object"&&!Array.isArray(X))return X}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:Y,transcriptPath:$.transcript_path,hookPath:$.hook_path,messagesPath:$.messages_path??void 0,updatedAt:$.updated_at??E0()}}class z9{sessionService;runtimeBuilder;createAgentInstance;defaultToolExecutors;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultRequestToolApproval;listeners=new Set;sessions=new Map;constructor($){let Y=Qz();if(Y)GX(Y);this.sessionService=$.sessionService,this.runtimeBuilder=$.runtimeBuilder??new A9,this.createAgentInstance=$.createAgent??((X)=>new Tz(X)),this.defaultToolExecutors=$.defaultToolExecutors,this.defaultToolPolicies=$.toolPolicies,this.providerSettingsManager=$.providerSettingsManager??new zY,this.oauthTokenManager=$.oauthTokenManager??new M5({providerSettingsManager:this.providerSettingsManager}),this.defaultRequestToolApproval=$.requestToolApproval}resolveStoredProviderSettings($){let Y=this.providerSettingsManager.getProviderSettings($);if(Y)return Y;return{provider:$}}buildResolvedProviderConfig($){let Y=this.resolveStoredProviderSettings($.providerId),X={...Y,provider:$.providerId,model:$.modelId,apiKey:$.apiKey??Y.apiKey,baseUrl:$.baseUrl??Y.baseUrl,headers:$.headers??Y.headers,reasoning:typeof $.thinking==="boolean"?{...Y.reasoning??{},enabled:$.thinking}:Y.reasoning},Q=H6(X);if($.knownModels)Q.knownModels=$.knownModels;return Q}async start($){let Y=$.source??"cli",X=E0(),Q=$.config.sessionId?.trim()??"",J=Q.length>0?Q:`${Date.now()}_${Uz(5)}`,Z=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!Z)throw Error("session service method not available: ensureSessionsDir");let T=N6(Z,J),K=N6(T,`${J}.log`),U=N6(T,`${J}.hooks.jsonl`),G=N6(T,`${J}.messages.json`),W=N6(T,`${J}.json`),R=qY.parse({version:1,session_id:J,source:Y,pid:process.pid,started_at:X,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:G}),V=FT({cwd:$.config.cwd,workspacePath:$.config.workspaceRoot??$.config.cwd,rootSessionId:J,hookLogPath:U,logger:$.config.logger}),A=Rz($.config.hooks)?void 0:DT({hookLogPath:U,rootSessionId:J,workspacePath:$.config.workspaceRoot??$.config.cwd}),H=HT([$.config.hooks,V,A]),z=await e8({pluginPaths:$.config.pluginPaths,workspacePath:$.config.workspaceRoot??$.config.cwd,cwd:$.config.cwd}),D=Ez($.config.extensions,z.extensions),B={...$.config,hooks:H,extensions:D},w=this.buildResolvedProviderConfig(B),x={...B,providerConfig:w},q=this.runtimeBuilder.build({config:x,hooks:H,extensions:D,logger:x.logger,onTeamEvent:(y)=>{this.handleTeamEvent(J,y),x.onTeamEvent?.(y)},createSpawnTool:()=>this.createSpawnTool(x,J),onTeamRestored:$.onTeamRestored,userInstructionWatcher:$.userInstructionWatcher,defaultToolExecutors:$.defaultToolExecutors??this.defaultToolExecutors}),_=[...q.tools,...x.extraTools??[]],C=this.createAgentInstance({providerId:w.providerId,modelId:w.modelId,apiKey:w.apiKey,baseUrl:w.baseUrl,headers:w.headers,knownModels:w.knownModels,providerConfig:w,thinking:x.thinking,systemPrompt:x.systemPrompt,maxIterations:x.maxIterations,tools:_,hooks:H,extensions:D,hookErrorMode:x.hookErrorMode,initialMessages:$.initialMessages,userFileContentLoader:Wz,toolPolicies:$.toolPolicies??this.defaultToolPolicies,requestToolApproval:$.requestToolApproval??this.defaultRequestToolApproval,completionGuard:q.completionGuard,logger:q.logger??x.logger,onEvent:(y)=>{this.emit({type:"agent_event",payload:{sessionId:J,event:y}}),this.emit({type:"chunk",payload:{sessionId:J,stream:"agent",chunk:Vz(y),ts:Date.now()}})}}),k={sessionId:J,config:x,source:Y,startedAt:X,pendingPrompt:R.prompt,runtime:q,agent:C,started:!1,aborting:!1,interactive:$.interactive===!0,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pluginSandboxShutdown:z.shutdown};this.sessions.set(k.sessionId,k),this.emitStatus(k.sessionId,"running");let f;try{if($.prompt?.trim()){if(f=await this.runTurn(k,{prompt:$.prompt,userImages:$.userImages,userFiles:$.userFiles}),!k.interactive)await this.finalizeSingleRun(k,f.finishReason)}}catch(y){throw await this.failSession(k),y}return{sessionId:J,manifest:R,manifestPath:W,transcriptPath:K,hookPath:U,messagesPath:G,result:f}}async send($){let Y=this.sessions.get($.sessionId);if(!Y)throw Error(`session not found: ${$.sessionId}`);try{let X=await this.runTurn(Y,{prompt:$.prompt,userImages:$.userImages,userFiles:$.userFiles});if(!Y.interactive)await this.finalizeSingleRun(Y,X.finishReason);return X}catch(X){throw await this.failSession(Y),X}}async abort($){let Y=this.sessions.get($);if(!Y)return;Y.aborting=!0,Y.agent.abort()}async stop($){let Y=this.sessions.get($);if(!Y)return;await this.shutdownSession(Y,{status:"cancelled",exitCode:null,shutdownReason:"session_stop",endReason:"stopped"})}async dispose($="session_manager_dispose"){let Y=[...this.sessions.values()];if(Y.length===0)return;await Promise.allSettled(Y.map(async(X)=>{await this.shutdownSession(X,{status:"cancelled",exitCode:null,shutdownReason:$,endReason:"disposed"})}))}async get($){let Y=await this.getRow($);return Y?IT(Y):void 0}async list($=200){return(await this.listRows($)).map((X)=>IT(X))}async delete($){if(this.sessions.has($))await this.stop($);return(await this.invoke("deleteSession",$)).deleted}async readTranscript($,Y){let X=await this.getRow($);if(!X?.transcript_path||!O5(X.transcript_path))return"";let Q=P5(X.transcript_path,"utf8");if(typeof Y==="number"&&Number.isFinite(Y))return Q.slice(-Math.max(0,Math.floor(Y)));return Q}async readMessages($){let X=(await this.getRow($))?.messages_path?.trim();if(!X||!O5(X))return[];try{let Q=P5(X,"utf8");if(!Q.trim())return[];let J=JSON.parse(Q);return Array.isArray(J)?J:Array.isArray(J.messages)?J.messages??[]:[]}catch{return[]}}async readHooks($,Y=200){let X=await this.getRow($);if(!X?.hook_path||!O5(X.hook_path))return[];return P5(X.hook_path,"utf8").split(`
|
|
574
|
+
`).map((Z)=>Z.trim()).filter((Z)=>Z.length>0).slice(-Math.max(1,Math.floor(Y))).map((Z)=>{try{return JSON.parse(Z)}catch{return{raw:Z}}})}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}async runTurn($,Y){let X=await this.prepareTurnInput($,Y),Q=X.prompt.trim();if(!Q)throw Error("prompt cannot be empty");await this.ensureSessionPersisted($),await this.syncOAuthCredentials($);let J=await this.executeAgentTurn($,Q,X.userImages,X.userFiles);while(this.shouldAutoContinueTeamRuns($,J.finishReason)){let Z=await this.waitForTeamRunUpdates($);if(Z.length===0)break;let T=this.buildTeamRunContinuationPrompt($,Z);J=await this.executeAgentTurn($,T)}return J}async executeAgentTurn($,Y,X,Q){let J=$.started||$.agent.getMessages().length>0,Z=$.agent.getMessages(),T=J?await this.runWithAuthRetry($,()=>$.agent.continue(Y,X,Q),Z):await this.runWithAuthRetry($,()=>$.agent.run(Y,X,Q),Z);$.started=!0;let K=Az(T.messages,T);return await this.invoke("persistSessionMessages",$.sessionId,K),T}async prepareTurnInput($,Y){let X=$.config.workspaceRoot??$.config.cwd,Q=qX(Y.prompt).trim();if(!Q)return{prompt:"",userImages:Y.userImages,userFiles:this.resolveAbsoluteFilePaths($.config.cwd,Y.userFiles)};let J=await u8(Q,X),Z=L8(J.prompt,$.config.mode==="plan"?"plan":"act"),T=this.resolveAbsoluteFilePaths($.config.cwd,Y.userFiles),K=this.resolveAbsoluteFilePaths(X,J.matchedFiles),U=Array.from(new Set([...T,...K]));return{prompt:Z,userImages:Y.userImages,userFiles:U.length>0?U:void 0}}resolveAbsoluteFilePaths($,Y){if(!Y||Y.length===0)return[];let X=Y.map((Q)=>Q.trim()).filter((Q)=>Q.length>0).map((Q)=>Jz(Q)?Q:Zz($,Q));return Array.from(new Set(X))}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($,Y){if(this.hasPendingTeamRunWork($))return;if(Y==="aborted"||$.aborting)await this.shutdownSession($,{status:"cancelled",exitCode:null,shutdownReason:"session_complete",endReason:Y});else await this.shutdownSession($,{status:"completed",exitCode:0,shutdownReason:"session_complete",endReason:Y})}async failSession($){await this.shutdownSession($,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession($,Y){if(this.notifyTeamRunWaiters($),$.artifacts)await this.updateStatus($,Y.status,Y.exitCode);if($.artifacts)await $.agent.shutdown(Y.shutdownReason);if(await Promise.resolve($.runtime.shutdown(Y.shutdownReason)),$.pluginSandboxShutdown)await $.pluginSandboxShutdown();this.sessions.delete($.sessionId),this.emit({type:"ended",payload:{sessionId:$.sessionId,reason:Y.endReason,ts:Date.now()}})}async updateStatus($,Y,X){if(!$.artifacts)return;let Q=await this.invoke("updateSessionStatus",$.sessionId,Y,X);if(!Q.updated)return;$.artifacts.manifest.status=Y,$.artifacts.manifest.ended_at=Q.endedAt??E0(),$.artifacts.manifest.exit_code=typeof X==="number"?X:null,await this.invoke("writeSessionManifest",$.artifacts.manifestPath,$.artifacts.manifest),this.emitStatus($.sessionId,Y)}emitStatus($,Y){this.emit({type:"status",payload:{sessionId:$,status:Y}})}async listRows($){let Y=Math.max(1,Math.floor($));return this.invoke("listSessions",Math.min(Y,BT))}async getRow($){let Y=$.trim();if(!Y)return;return(await this.listRows(BT)).find((Q)=>Q.session_id===Y)}createSpawnTool($,Y){let X=()=>{if(!$.enableTools)return[];let J=$.mode==="plan"?t1.readonly:t1.development;return V6({cwd:$.cwd,...J,executors:this.defaultToolExecutors})},Q=()=>{let J=X();if($.enableSpawnAgent)J.push(this.createSpawnTool($,Y));return J};return Kz({providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey,baseUrl:$.baseUrl,providerConfig:$.providerConfig,knownModels:$.knownModels,createSubAgentTools:Q,hooks:$.hooks,extensions:$.extensions,toolPolicies:this.defaultToolPolicies,requestToolApproval:this.defaultRequestToolApproval,logger:$.logger,onSubAgentStart:(J)=>{this.invokeOptional("handleSubAgentStart",Y,J)},onSubAgentEnd:(J)=>{this.invokeOptional("handleSubAgentEnd",Y,J)}})}async handleTeamEvent($,Y){let X=this.sessions.get($);if(X)switch(Y.type){case"run_queued":case"run_started":X.activeTeamRunIds.add(Y.run.id);break;case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":{let J;if(Y.type==="run_failed")J=Y.run.error;else if(Y.type==="run_cancelled")J=Y.run.error??Y.reason;else if(Y.type==="run_interrupted")J=Y.run.error??Y.reason;X.activeTeamRunIds.delete(Y.run.id),X.pendingTeamRunUpdates.push({runId:Y.run.id,agentId:Y.run.agentId,taskId:Y.run.taskId,status:Y.type.replace("run_",""),error:J,iterations:Y.run.result?.iterations}),this.notifyTeamRunWaiters(X);break}default:break}switch(Y.type){case"task_start":await this.invokeOptional("onTeamTaskStart",$,Y.agentId,Y.message);break;case"task_end":if(Y.error){await this.invokeOptional("onTeamTaskEnd",$,Y.agentId,"failed",`[error] ${Y.error.message}`);break}if(Y.result?.finishReason==="aborted"){await this.invokeOptional("onTeamTaskEnd",$,Y.agentId,"cancelled","[done] aborted",Y.result.messages);break}await this.invokeOptional("onTeamTaskEnd",$,Y.agentId,"completed",`[done] ${Y.result?.finishReason??"completed"}`,Y.result?.messages);break;default:break}if(!X?.runtime.teamRuntime)return;let Q=X.config.teamName?.trim()||"team";this.emit({type:"team_progress",payload:{sessionId:$,teamName:Q,lifecycle:z5({teamName:Q,sessionId:$,event:Y}),summary:H5(Q,X.runtime.teamRuntime.exportState())}})}hasPendingTeamRunWork($){return $.activeTeamRunIds.size>0||$.pendingTeamRunUpdates.length>0}shouldAutoContinueTeamRuns($,Y){if($.aborting||Y==="aborted"||Y==="error")return!1;if(!$.config.enableAgentTeams)return!1;return this.hasPendingTeamRunWork($)}notifyTeamRunWaiters($){let Y=$.teamRunWaiters.splice(0);for(let X of Y)X()}async waitForTeamRunUpdates($){while(!0){if($.aborting)return[];if($.pendingTeamRunUpdates.length>0){let Y=[...$.pendingTeamRunUpdates];return $.pendingTeamRunUpdates.length=0,Y}if($.activeTeamRunIds.size===0)return[];await new Promise((Y)=>{$.teamRunWaiters.push(Y)})}}buildTeamRunContinuationPrompt($,Y){let X=Y.map((Z)=>{let T=`- ${Z.runId} (${Z.agentId}) -> ${Z.status}`,K=Z.taskId?` task=${Z.taskId}`:"",U=typeof Z.iterations==="number"?` iterations=${Z.iterations}`:"",G=Z.error?` error=${Z.error}`:"";return`${T}${K}${U}${G}`}),Q=$.activeTeamRunIds.size,J=Q>0?`There are still ${Q} 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 L8(`System-delivered teammate async run updates:
|
|
575
|
+
${X.join(`
|
|
576
|
+
`)}
|
|
577
|
+
|
|
578
|
+
${J}`,$.config.mode==="plan"?"plan":"act")}emit($){for(let Y of this.listeners)Y($)}async invoke($,...Y){let X=this.sessionService[$];if(typeof X!=="function")throw Error(`session service method not available: ${$}`);return Promise.resolve(X.apply(this.sessionService,Y))}async invokeOptional($,...Y){let X=this.sessionService[$];if(typeof X!=="function")return;await Promise.resolve(X.apply(this.sessionService,Y))}async invokeOptionalValue($,...Y){let X=this.sessionService[$];if(typeof X!=="function")return;return await Promise.resolve(X.apply(this.sessionService,Y))}async runWithAuthRetry($,Y,X){try{return await Y()}catch(Q){if(!this.isLikelyAuthError(Q,$.config.providerId))throw Q;return await this.syncOAuthCredentials($,{forceRefresh:!0}),$.agent.restore(X),Y()}}isLikelyAuthError($,Y){if(Y!=="cline"&&Y!=="oca"&&Y!=="openai-codex")return!1;let X=$ instanceof Error?$.message.toLowerCase():String($);return X.includes("401")||X.includes("403")||X.includes("unauthorized")||X.includes("forbidden")||X.includes("invalid token")||X.includes("expired token")||X.includes("authentication")}async syncOAuthCredentials($,Y){let X=null;try{X=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId,forceRefresh:Y?.forceRefresh})}catch(J){if(J instanceof H9)throw Error(`OAuth session for "${J.providerId}" requires re-authentication. Run "clite auth ${J.providerId}" and retry.`);throw J}if(!X?.apiKey)return;if($.config.apiKey===X.apiKey)return;$.config.apiKey=X.apiKey,$.agent.updateConnection?.({apiKey:X.apiKey}),$.runtime.teamRuntime?.updateTeammateConnections({apiKey:X.apiKey})}}import{existsSync as lC,mkdirSync as iC}from"node:fs";var $6=KY(D8(),1),rV=KY(i6(),1);import{existsSync as AC}from"node:fs";import{dirname as DC,join as z7}from"node:path";import{fileURLToPath as FC}from"node:url";var HC="cline.rpc.v1",oV="ClineGateway";function zC(){let $=DC(FC(import.meta.url)),Y=[z7($,"proto","rpc.proto"),z7($,"..","src","proto","rpc.proto"),z7(process.cwd(),"packages","rpc","src","proto","rpc.proto")];for(let X of Y)if(AC(X))return X;throw Error("Unable to resolve rpc.proto path")}function qC(){let $=rV.loadSync(zC(),{keepCase:!1,longs:String,enums:String,defaults:!0,oneofs:!0}),X=$6.loadPackageDefinition($).cline?.rpc?.v1?.ClineGateway?.service;if(!X)throw Error(`Unable to load ${HC}.${oV} from proto`);return X}function sV($){return new($6.makeGenericClientConstructor(qC(),oV))($,$6.credentials.createInsecure())}function o4($){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)=>o4(Q))}};if(typeof $==="object"){let Y={fields:{}};for(let[X,Q]of Object.entries($))Y.fields??={},Y.fields[X]=o4(Q);return{structValue:Y}}return{stringValue:String($)}}function s4($){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((Y)=>s4(Y));if($.structValue){let Y={};for(let[X,Q]of Object.entries($.structValue.fields??{}))Y[X]=s4(Q);return Y}return}function h0($){let Y={};for(let[X,Q]of Object.entries($??{}))Y[X]=o4(Q);return{fields:Y}}function z0($){if(!$?.fields)return;let Y={};for(let[X,Q]of Object.entries($.fields))Y[X]=s4(Q);return Y}function R$($){return o4($)}function E$($){return s4($??void 0)}function NC($){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:h0($.metadata)}}function aV($){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:z0($.metadata),transcriptPath:$.transcriptPath??"",hookPath:$.hookPath??"",messagesPath:$.messagesPath||void 0,updatedAt:$.updatedAt??""}}function MC($){let Y=$?.trim();if(!Y)return;try{let X=JSON.parse(Y);if(!Array.isArray(X))return;let Q=X.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0);return Q.length>0?Q:void 0}catch{return}}function Y6($){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:MC($.tagsJson??void 0),metadata:z0($.metadata)}}function q7($){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 F8{client;constructor($){this.client=sV($.address)}close(){this.client.close()}async upsertSession($){await this.unary((Y)=>{let X={session:NC($)};this.client.UpsertSession(X,Y)})}async getSession($){let Y=await this.unary((X)=>{this.client.GetSession({sessionId:$},X)});if(!Y.session)return;return aV(Y.session)}async listSessions($){return((await this.unary((X)=>{this.client.ListSessions($,X)})).sessions??[]).map((X)=>aV(X))}async updateSession($){let Y={sessionId:$.sessionId,status:$.status,endedAt:$.endedAt??void 0,setRunning:$.setRunning};if($.exitCode!==void 0)Y.hasExitCode=!0,Y.exitCode=$.exitCode??0;if($.prompt!==void 0)Y.hasPrompt=!0,Y.prompt=$.prompt??"";if($.metadata!==void 0)Y.hasMetadata=!0,Y.metadata=h0($.metadata??void 0);if($.parentSessionId!==void 0)Y.hasParentSessionId=!0,Y.parentSessionId=$.parentSessionId??"";if($.parentAgentId!==void 0)Y.hasParentAgentId=!0,Y.parentAgentId=$.parentAgentId??"";if($.agentId!==void 0)Y.hasAgentId=!0,Y.agentId=$.agentId??"";if($.conversationId!==void 0)Y.hasConversationId=!0,Y.conversationId=$.conversationId??"";if($.expectedStatusLock!==void 0)Y.hasExpectedStatusLock=!0,Y.expectedStatusLock=$.expectedStatusLock;let X=await this.unary((Q)=>{this.client.UpdateSession(Y,Q)});return{updated:X.updated===!0,statusLock:Number(X.statusLock??0)}}async deleteSession($,Y=!1){return(await this.unary((Q)=>{this.client.DeleteSession({sessionId:$,cascade:Y},Q)})).deleted===!0}async enqueueSpawnRequest($){await this.unary((Y)=>{this.client.EnqueueSpawnRequest($,Y)})}async claimSpawnRequest($,Y){let Q=(await this.unary((J)=>{let Z={rootSessionId:$,parentAgentId:Y};this.client.ClaimSpawnRequest(Z,J)})).item?.task?.trim();return Q?Q:void 0}async startRuntimeSession($){let Y={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(([J,Z])=>[J,{enabled:Z.enabled??!1,autoApprove:Z.autoApprove??!1}])),initialMessages:($.initialMessages??[]).map((J)=>({role:J.role??"",content:R$(J.content)})),logger:$.logger?{enabled:$.logger.enabled??!1,level:$.logger.level??"",destination:$.logger.destination??"",name:$.logger.name??"",bindings:h0($.logger.bindings)}:void 0},X=await this.unary((J)=>{this.client.StartRuntimeSession({request:Y},J)}),Q=X.startResult?{sessionId:X.startResult.sessionId??"",manifestPath:X.startResult.manifestPath??"",transcriptPath:X.startResult.transcriptPath??"",hookPath:X.startResult.hookPath??"",messagesPath:X.startResult.messagesPath??""}:void 0;return{sessionId:X.sessionId??"",startResult:Q}}async sendRuntimeSession($,Y){let X={config:{workspaceRoot:Y.config.workspaceRoot,cwd:Y.config.cwd??"",provider:Y.config.provider,model:Y.config.model,mode:Y.config.mode,apiKey:Y.config.apiKey,systemPrompt:Y.config.systemPrompt??"",maxIterations:Y.config.maxIterations??0,hasMaxIterations:typeof Y.config.maxIterations==="number",enableTools:Y.config.enableTools,enableSpawn:Y.config.enableSpawn,enableTeams:Y.config.enableTeams,autoApproveTools:Y.config.autoApproveTools??!1,hasAutoApproveTools:typeof Y.config.autoApproveTools==="boolean",teamName:Y.config.teamName,missionStepInterval:Y.config.missionStepInterval,missionTimeIntervalMs:Y.config.missionTimeIntervalMs,toolPolicies:Object.fromEntries(Object.entries(Y.config.toolPolicies??{}).map(([J,Z])=>[J,{enabled:Z.enabled??!1,autoApprove:Z.autoApprove??!1}])),initialMessages:(Y.config.initialMessages??[]).map((J)=>({role:J.role??"",content:R$(J.content)})),logger:Y.config.logger?{enabled:Y.config.logger.enabled??!1,level:Y.config.logger.level??"",destination:Y.config.logger.destination??"",name:Y.config.logger.name??"",bindings:h0(Y.config.logger.bindings)}:void 0},messages:(Y.messages??[]).map((J)=>({role:J.role??"",content:R$(J.content)})),prompt:Y.prompt,attachments:Y.attachments?{userImages:Y.attachments.userImages??[],userFiles:(Y.attachments.userFiles??[]).map((J)=>({name:J.name,content:J.content}))}:void 0},Q=await this.unary((J)=>{this.client.SendRuntimeSession({sessionId:$,request:X},J)});return{result:{text:Q.result?.text??"",usage:{inputTokens:Number(Q.result?.usage?.inputTokens??0),outputTokens:Number(Q.result?.usage?.outputTokens??0),cacheReadTokens:Q.result?.usage?.hasCacheReadTokens?Number(Q.result?.usage?.cacheReadTokens??0):void 0,cacheWriteTokens:Q.result?.usage?.hasCacheWriteTokens?Number(Q.result?.usage?.cacheWriteTokens??0):void 0,totalCost:Q.result?.usage?.hasTotalCost?Number(Q.result?.usage?.totalCost??0):void 0},inputTokens:Number(Q.result?.inputTokens??0),outputTokens:Number(Q.result?.outputTokens??0),iterations:Number(Q.result?.iterations??0),finishReason:Q.result?.finishReason??"",messages:(Q.result?.messages??[]).map((J)=>({role:J.role??"",content:E$(J.content)})),toolCalls:(Q.result?.toolCalls??[]).map((J)=>({name:J.name??"",input:J.hasInput?E$(J.input):void 0,output:J.hasOutput?E$(J.output):void 0,error:J.error?.trim()||void 0,durationMs:J.hasDurationMs?Number(J.durationMs??0):void 0}))}}}async abortRuntimeSession($){return{applied:(await this.unary((X)=>{this.client.AbortRuntimeSession({sessionId:$},X)})).applied===!0}}async requestToolApproval($){let Y={approvalId:$.approvalId,sessionId:$.sessionId,taskId:$.taskId,toolCallId:$.toolCallId,toolName:$.toolName,inputJson:$.inputJson,requesterClientId:$.requesterClientId,timeoutMs:$.timeoutMs},X=await this.unary((Q)=>{this.client.RequestToolApproval(Y,Q)});return{approvalId:X.approvalId??"",decided:X.decided===!0,approved:X.approved===!0,reason:X.reason??""}}async respondToolApproval($){let Y={approvalId:$.approvalId,approved:$.approved,reason:$.reason,responderClientId:$.responderClientId},X=await this.unary((Q)=>{this.client.RespondToolApproval(Y,Q)});return{approvalId:X.approvalId??"",applied:X.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 Y=await this.unary((X)=>{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:h0($.metadata)},X)});return Y.schedule?Y6(Y.schedule):void 0}async getSchedule($){let Y=await this.unary((X)=>{this.client.GetSchedule({scheduleId:$},X)});return Y.schedule?Y6(Y.schedule):void 0}async listSchedules($){return((await this.unary((X)=>{this.client.ListSchedules({limit:$?.limit??100,hasEnabled:typeof $?.enabled==="boolean",enabled:$?.enabled??!1,tagsJson:$?.tags?JSON.stringify($.tags):""},X)})).schedules??[]).map((X)=>Y6(X))}async updateSchedule($,Y){let X={scheduleId:$};if(Y.name!==void 0)X.hasName=!0,X.name=Y.name;if(Y.cronPattern!==void 0)X.hasCronPattern=!0,X.cronPattern=Y.cronPattern;if(Y.prompt!==void 0)X.hasPrompt=!0,X.prompt=Y.prompt;if(Y.provider!==void 0)X.hasProvider=!0,X.provider=Y.provider;if(Y.model!==void 0)X.hasModel=!0,X.model=Y.model;if(Y.mode!==void 0)X.hasMode=!0,X.mode=Y.mode;if(Y.workspaceRoot!==void 0)X.hasWorkspaceRoot=!0,X.workspaceRoot=Y.workspaceRoot;if(Y.cwd!==void 0)X.hasCwd=!0,X.cwd=Y.cwd;if(Y.systemPrompt!==void 0)X.hasSystemPrompt=!0,X.systemPrompt=Y.systemPrompt;if(Y.maxIterations===null)X.clearMaxIterations=!0;else if(Y.maxIterations!==void 0)X.hasMaxIterations=!0,X.maxIterations=Y.maxIterations;if(Y.timeoutSeconds===null)X.clearTimeoutSeconds=!0;else if(Y.timeoutSeconds!==void 0)X.hasTimeoutSeconds=!0,X.timeoutSeconds=Y.timeoutSeconds;if(Y.maxParallel!==void 0)X.hasMaxParallel=!0,X.maxParallel=Y.maxParallel;if(Y.enabled!==void 0)X.hasEnabled=!0,X.enabled=Y.enabled;if(Y.createdBy===null)X.clearCreatedBy=!0;else if(Y.createdBy!==void 0)X.hasCreatedBy=!0,X.createdBy=Y.createdBy;if(Y.tags!==void 0)X.hasTagsJson=!0,X.tagsJson=JSON.stringify(Y.tags);if(Y.metadata!==void 0)X.hasMetadata=!0,X.metadata=h0(Y.metadata);let Q=await this.unary((J)=>{this.client.UpdateSchedule(X,J)});return Q.schedule?Y6(Q.schedule):void 0}async deleteSchedule($){return(await this.unary((X)=>{this.client.DeleteSchedule({scheduleId:$},X)})).deleted===!0}async pauseSchedule($){let Y=await this.unary((X)=>{this.client.PauseSchedule({scheduleId:$},X)});return Y.schedule?Y6(Y.schedule):void 0}async resumeSchedule($){let Y=await this.unary((X)=>{this.client.ResumeSchedule({scheduleId:$},X)});return Y.schedule?Y6(Y.schedule):void 0}async triggerScheduleNow($){let Y=await this.unary((X)=>{this.client.TriggerScheduleNow({scheduleId:$},X)});return Y.execution?q7(Y.execution):void 0}async listScheduleExecutions($){return((await this.unary((X)=>{this.client.ListScheduleExecutions({scheduleId:$.scheduleId,status:$.status,limit:$.limit??50},X)})).executions??[]).map((X)=>q7(X))}async getScheduleStats($){let Y=await this.unary((X)=>{this.client.GetScheduleStats({scheduleId:$},X)});return{totalRuns:Number(Y.totalRuns??0),successRate:Number(Y.successRate??0),avgDurationSeconds:Number(Y.avgDurationSeconds??0),lastFailure:Y.lastFailure?q7(Y.lastFailure):void 0}}async getActiveScheduledExecutions(){return((await this.unary((Y)=>{this.client.GetActiveScheduledExecutions({},Y)})).executions??[]).map((Y)=>({executionId:Y.executionId??"",scheduleId:Y.scheduleId??"",sessionId:Y.sessionId??"",startedAt:Y.startedAt??"",timeoutAt:Y.timeoutAt?.trim()||void 0}))}async getUpcomingScheduledRuns($=20){return((await this.unary((X)=>{this.client.GetUpcomingScheduledRuns({limit:$},X)})).runs??[]).map((X)=>({scheduleId:X.scheduleId??"",name:X.name??"",nextRunAt:X.nextRunAt??""}))}async stopRuntimeSession($){return{applied:(await this.unary((X)=>{this.client.StopRuntimeSession({sessionId:$},X)})).applied===!0}}async runProviderAction($){let Y=$.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}},X=await this.unary((Q)=>{this.client.RunProviderAction({request:Y},Q)});return{result:E$(X.result)}}async runProviderOAuthLogin($){let Y=await this.unary((X)=>{this.client.RunProviderOAuthLogin({provider:$},X)});return{provider:Y.provider??"",accessToken:Y.apiKey??""}}async publishEvent($){let Y=await this.unary((X)=>{this.client.PublishEvent({eventId:$.eventId,sessionId:$.sessionId,taskId:$.taskId,eventType:$.eventType,payload:h0($.payload),sourceClientId:$.sourceClientId},X)});return{eventId:Y.eventId??"",accepted:Y.accepted===!0}}streamEvents($,Y={}){let X=!1,Q=this.client.StreamEvents({clientId:$.clientId??"",sessionIds:$.sessionIds??[]}),J=(K)=>{Y.onEvent?.({eventId:K.eventId??"",sessionId:K.sessionId??"",taskId:K.taskId?.trim()?K.taskId:void 0,eventType:K.eventType??"",payload:z0(K.payload)??{},sourceClientId:K.sourceClientId?.trim()?K.sourceClientId:void 0,ts:K.ts??""})},Z=(K)=>{let G=(typeof K.code==="number"?Number(K.code):void 0)===1||K.message.includes("CANCELLED");if(X&&G)return;Y.onError?.(K)},T=()=>{Y.onEnd?.()};return Q.on("data",J),Q.on("error",Z),Q.on("end",T),()=>{X=!0,Q.cancel()}}streamTeamProgress($,Y={}){return this.streamEvents($,{onEvent:(X)=>{if(X.eventType===NX){try{let Q=X.payload;if(Q.type==="team_progress_projection"&&Q.version===1)Y.onProjection?.(Q)}catch{}return}if(X.eventType===MX)try{Y.onLifecycle?.(X.payload)}catch{}},onError:Y.onError,onEnd:Y.onEnd})}async unary($){return await new Promise((Y,X)=>{$((Q,J)=>{if(Q){X(Q);return}Y(J??{})})})}}var e4=KY(D8(),1);var eV=KY(D8(),1),$A=KY(i6(),1);import{existsSync as IC}from"node:fs";import{dirname as OC,join as N7}from"node:path";import{fileURLToPath as PC}from"node:url";var LC="cline.rpc.v1",M7="ClineGateway";function SC(){let $=OC(PC(import.meta.url)),Y=[N7($,"..","proto","rpc.proto"),N7($,"..","..","src","proto","rpc.proto"),N7(process.cwd(),"packages","rpc","src","proto","rpc.proto")];for(let X of Y)if(IC(X))return X;throw Error("Unable to resolve rpc.proto path")}function B7(){let $=$A.loadSync(SC(),{keepCase:!1,longs:String,enums:String,defaults:!0,oneofs:!0}),X=eV.loadPackageDefinition($).cline?.rpc?.v1?.ClineGateway?.service;if(!X)throw Error(`Unable to load ${LC}.${M7} from proto`);return X}function r1(){return new Date().toISOString()}function F($){return typeof $==="string"?$:""}function YA($){if(!$||typeof $!=="object")return{};let Y={};for(let[X,Q]of Object.entries($)){let J=X.trim();if(!J)continue;let Z=F(Q).trim();if(!Z)continue;Y[J]=Z}return Y}function XA($){if(!Array.isArray($)||$.length===0)return;let Y=new Set;for(let X of $){let Q=X.trim();if(Q)Y.add(Q)}return Y.size>0?Y:void 0}function I7($){if($==="running"||$==="completed"||$==="failed"||$==="cancelled")return $;return"running"}function O7($){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:h0($.metadata)}}function QA($){let Y=F($.sessionId).trim(),X=F($.source).trim(),Q=F($.startedAt).trim(),J=F($.provider).trim(),Z=F($.model).trim(),T=F($.cwd).trim(),K=F($.workspaceRoot).trim(),U=F($.transcriptPath).trim(),G=F($.hookPath).trim();if(!Y||!X||!Q||!J||!Z||!T||!K||!U||!G)throw Error("session record is missing required fields");return{sessionId:Y,source:X,pid:Number($.pid??0),startedAt:Q,endedAt:F($.endedAt).trim()||null,exitCode:typeof $.exitCode==="number"?Math.floor($.exitCode):null,status:I7(F($.status).trim()),statusLock:typeof $.statusLock==="number"?Math.floor($.statusLock):0,interactive:$.interactive===!0,provider:J,model:Z,cwd:T,workspaceRoot:K,teamName:F($.teamName).trim()||void 0,enableTools:$.enableTools===!0,enableSpawn:$.enableSpawn===!0,enableTeams:$.enableTeams===!0,parentSessionId:F($.parentSessionId).trim()||void 0,parentAgentId:F($.parentAgentId).trim()||void 0,agentId:F($.agentId).trim()||void 0,conversationId:F($.conversationId).trim()||void 0,isSubagent:$.isSubagent===!0,prompt:F($.prompt).trim()||void 0,metadata:z0($.metadata),transcriptPath:U,hookPath:G,messagesPath:F($.messagesPath).trim()||void 0,updatedAt:F($.updatedAt).trim()||r1()}}function a4($){let Y=F($).trim();if(!Y)return;try{let X=JSON.parse(Y);if(!Array.isArray(X))return;let Q=X.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0);return Q.length>0?Q:void 0}catch{return}}function TY($){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:h0($.metadata)}}function t4($){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 wC($){return new(e4.makeGenericClientConstructor(B7(),M7))($,e4.credentials.createInsecure())}async function $X($){return await new Promise((Y)=>{let X;try{X=wC($)}catch{Y(void 0);return}X.Health({},(Q,J)=>{if(X?.close(),Q||!J){Y(void 0);return}Y(J)})})}var w7=KY(D8(),1);import{randomUUID as ZA}from"node:crypto";import{randomUUID as kC}from"node:crypto";var hC=300000;class P7{publishEvent;approvals=new Map;constructor($){this.publishEvent=$}async requestToolApproval($){let Y=F($.sessionId).trim(),X=F($.toolCallId).trim(),Q=F($.toolName).trim();if(!Y||!X||!Q)throw Error("sessionId, toolCallId, and toolName are required");let J=F($.approvalId).trim()||`apr_${kC()}`;if(!this.approvals.get(J)){let G={approvalId:J,sessionId:Y,taskId:F($.taskId).trim()||void 0,toolCallId:X,toolName:Q,inputJson:F($.inputJson),requesterClientId:F($.requesterClientId).trim()||void 0,createdAt:r1(),status:"pending",waiters:[]};this.approvals.set(J,G),this.publishEvent({eventId:"",sessionId:Y,taskId:G.taskId,eventType:"approval.requested",payload:h0(G),sourceClientId:G.requesterClientId})}let T=this.approvals.get(J);if(!T)throw Error("approval state not found");if(T.status==="approved"||T.status==="rejected")return{approvalId:J,decided:!0,approved:T.status==="approved",reason:T.reason??""};let K=typeof $.timeoutMs==="number"&&$.timeoutMs>0?Math.floor($.timeoutMs):hC,U=await new Promise((G)=>{let W=setTimeout(()=>{G({decided:!1,approved:!1,reason:"Tool approval request timed out"})},K);T.waiters.push((R)=>{clearTimeout(W),G(R)})});return{approvalId:J,decided:U.decided,approved:U.approved,reason:U.reason??""}}respondToolApproval($){let Y=F($.approvalId).trim();if(!Y)throw Error("approvalId is required");let X=this.approvals.get(Y);if(!X)return{approvalId:Y,applied:!1};X.status=$.approved===!0?"approved":"rejected",X.reason=F($.reason).trim()||void 0;let Q={decided:!0,approved:X.status==="approved",reason:X.reason};for(let J of X.waiters.splice(0))J(Q);return this.publishEvent({eventId:"",sessionId:X.sessionId,taskId:X.taskId,eventType:"approval.decided",payload:h0({approvalId:Y,approved:Q.approved,reason:Q.reason??"",responderClientId:F($.responderClientId).trim()||""}),sourceClientId:F($.responderClientId).trim()||""}),{approvalId:Y,applied:!0}}listPendingApprovals($){let Y=F($.sessionId).trim(),X=[];for(let Q of this.approvals.values()){if(Q.status!=="pending")continue;if(Y&&Q.sessionId!==Y)continue;X.push({approvalId:Q.approvalId,sessionId:Q.sessionId,taskId:Q.taskId??"",toolCallId:Q.toolCallId,toolName:Q.toolName,inputJson:Q.inputJson,requesterClientId:Q.requesterClientId??"",createdAt:Q.createdAt})}return X.sort((Q,J)=>(Q.createdAt??"").localeCompare(J.createdAt??"")),{approvals:X}}}import{randomUUID as JA}from"node:crypto";class L7{subscribers=new Map;nextSubscriberId=1;publishEvent($){let Y=F($.sessionId).trim();if(!Y)throw Error("sessionId is required");let X={eventId:F($.eventId).trim()||`evt_${JA()}`,sessionId:Y,taskId:F($.taskId).trim()||void 0,eventType:F($.eventType).trim()||"unknown",payload:z0($.payload)??{},sourceClientId:F($.sourceClientId).trim()||void 0,ts:r1()};return this.dispatchEvent(X),{eventId:X.eventId,accepted:!0}}addSubscriber($){let Y=$.request,X=XA(Y.sessionIds),Q=this.nextSubscriberId;return this.nextSubscriberId+=1,this.subscribers.set(Q,{call:$,filterSessionIds:X}),$.on("cancelled",()=>{this.subscribers.delete(Q)}),$.on("close",()=>{this.subscribers.delete(Q)}),Q}removeSubscriber($){this.subscribers.delete($)}broadcastServerEvent($,Y){let X=`evt_${JA()}`,Q=r1();for(let J of this.subscribers.values())J.call.write({eventId:X,sessionId:"__rpc__",taskId:"",eventType:$,payload:h0(Y),sourceClientId:"rpc-server",ts:Q})}dispatchEvent($){for(let Y of this.subscribers.values()){if(Y.filterSessionIds&&!Y.filterSessionIds.has($.sessionId))continue;Y.call.write({eventId:$.eventId,sessionId:$.sessionId,taskId:$.taskId??"",eventType:$.eventType,payload:h0($.payload),sourceClientId:$.sourceClientId??"",ts:$.ts})}}}class S7{scheduler;constructor($){this.scheduler=$}createSchedule($){let Y=this.requireScheduler(),X={name:F($.name).trim(),cronPattern:F($.cronPattern).trim(),prompt:F($.prompt),provider:F($.provider).trim(),model:F($.model).trim(),mode:F($.mode).trim()==="plan"?"plan":"act",workspaceRoot:F($.workspaceRoot).trim()||void 0,cwd:F($.cwd).trim()||void 0,systemPrompt:F($.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:F($.createdBy).trim()||void 0,tags:a4(F($.tagsJson)),metadata:z0($.metadata)};if(!X.name||!X.cronPattern||!X.prompt.trim()||!X.provider||!X.model)throw Error("name, cronPattern, prompt, provider, and model are required");let Q=Y.createSchedule(X);return{schedule:TY(Q)}}getSchedule($){let Y=this.requireScheduler(),X=F($.scheduleId).trim();if(!X)throw Error("scheduleId is required");let Q=Y.getSchedule(X);return Q?{schedule:TY(Q)}:{}}listSchedules($){return{schedules:this.requireScheduler().listSchedules({enabled:$.hasEnabled?$.enabled===!0:void 0,limit:typeof $.limit==="number"&&$.limit>0?Math.floor($.limit):void 0,tags:a4(F($.tagsJson))}).map((Q)=>TY(Q))}}updateSchedule($){let Y=this.requireScheduler(),X=F($.scheduleId).trim();if(!X)throw Error("scheduleId is required");let Q={};if($.hasName)Q.name=F($.name);if($.hasCronPattern)Q.cronPattern=F($.cronPattern);if($.hasPrompt)Q.prompt=F($.prompt);if($.hasProvider)Q.provider=F($.provider);if($.hasModel)Q.model=F($.model);if($.hasMode)Q.mode=F($.mode).trim()==="plan"?"plan":"act";if($.hasWorkspaceRoot)Q.workspaceRoot=F($.workspaceRoot);if($.hasCwd)Q.cwd=F($.cwd);if($.hasSystemPrompt)Q.systemPrompt=F($.systemPrompt);if($.clearMaxIterations)Q.maxIterations=null;else if($.hasMaxIterations)Q.maxIterations=Math.floor($.maxIterations??0);if($.clearTimeoutSeconds)Q.timeoutSeconds=null;else if($.hasTimeoutSeconds)Q.timeoutSeconds=Math.floor($.timeoutSeconds??0);if($.hasMaxParallel)Q.maxParallel=Math.floor($.maxParallel??1);if($.hasEnabled)Q.enabled=$.enabled===!0;if($.clearCreatedBy)Q.createdBy=null;else if($.hasCreatedBy)Q.createdBy=F($.createdBy);if($.hasTagsJson)Q.tags=a4(F($.tagsJson))??[];if($.hasMetadata)Q.metadata=z0($.metadata)??{};let J=Y.updateSchedule(X,Q);return{updated:J!==void 0,schedule:J?TY(J):void 0}}deleteSchedule($){let Y=this.requireScheduler(),X=F($.scheduleId).trim();if(!X)throw Error("scheduleId is required");return{deleted:Y.deleteSchedule(X)}}pauseSchedule($){let Y=this.requireScheduler(),X=F($.scheduleId).trim();if(!X)throw Error("scheduleId is required");let Q=Y.pauseSchedule(X);return{updated:Q!==void 0,schedule:Q?TY(Q):void 0}}resumeSchedule($){let Y=this.requireScheduler(),X=F($.scheduleId).trim();if(!X)throw Error("scheduleId is required");let Q=Y.resumeSchedule(X);return{updated:Q!==void 0,schedule:Q?TY(Q):void 0}}async triggerScheduleNow($){let Y=this.requireScheduler(),X=F($.scheduleId).trim();if(!X)throw Error("scheduleId is required");let Q=await Y.triggerScheduleNow(X);return Q?{execution:t4(Q)}:{}}listScheduleExecutions($){let Y=this.requireScheduler(),X=F($.scheduleId).trim()||void 0,Q=F($.status).trim()||void 0;return{executions:Y.listScheduleExecutions({scheduleId:X,status:Q==="pending"||Q==="running"||Q==="success"||Q==="failed"||Q==="timeout"||Q==="aborted"?Q:void 0,limit:typeof $.limit==="number"&&$.limit>0?Math.floor($.limit):void 0}).map((Z)=>t4(Z))}}getScheduleStats($){let Y=this.requireScheduler(),X=F($.scheduleId).trim();if(!X)throw Error("scheduleId is required");let Q=Y.getScheduleStats(X);return{totalRuns:Q.totalRuns,successRate:Q.successRate,avgDurationSeconds:Q.avgDurationSeconds,lastFailure:Q.lastFailure?t4(Q.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 Y=this.requireScheduler(),X=typeof $.limit==="number"&&$.limit>0?Math.floor($.limit):20;return{runs:Y.getUpcomingRuns(X).map((J)=>({scheduleId:J.scheduleId,name:J.name,nextRunAt:J.nextRunAt}))}}requireScheduler(){if(!this.scheduler)throw Error("scheduler service is not configured");return this.scheduler}}class TA{serverId=ZA();address;startedAt;runtimeHandlers;sessions=new Map;tasks=new Map;clients=new Map;store;eventService=new L7;approvalService=new P7(($)=>this.eventService.publishEvent($));scheduleService;constructor($,Y,X,Q){this.address=$,this.startedAt=r1(),this.store=Y,this.runtimeHandlers=X,this.scheduleService=new S7(Q),this.store.init()}health(){return{serverId:this.serverId,address:this.address,running:!0,startedAt:this.startedAt}}registerClient($){let X=F($.clientId).trim()||`client_${ZA()}`,Q=F($.clientType).trim()||void 0,J=YA($),Z=r1(),T=this.clients.get(X),K=T?{...T,clientType:Q??T.clientType,metadata:Object.keys(J).length>0?{...T.metadata??{},...J}:T.metadata,lastRegisteredAt:Z,activationCount:T.activationCount+1}:{clientId:X,clientType:Q,metadata:Object.keys(J).length>0?J:void 0,firstRegisteredAt:Z,lastRegisteredAt:Z,activationCount:1};return this.clients.set(X,K),this.broadcastServerEvent("rpc.client.activated",{clientId:K.clientId,clientType:K.clientType,metadata:K.metadata??{},firstRegisteredAt:K.firstRegisteredAt,lastRegisteredAt:K.lastRegisteredAt,activationCount:K.activationCount}),{clientId:X,registered:!0}}ensureSession($){let Y=F($.sessionId).trim();if(!Y)throw Error("sessionId is required");let X=this.sessions.get(Y);if(X)return X.status=F($.status).trim()||X.status,X.workspaceRoot=F($.workspaceRoot).trim()||X.workspaceRoot,X.clientId=F($.clientId).trim()||X.clientId,X.metadata=z0($.metadata)??X.metadata,{sessionId:Y,created:!1,status:X.status};let Q=F($.status).trim()||"running";return this.sessions.set(Y,{sessionId:Y,status:Q,workspaceRoot:F($.workspaceRoot).trim()||void 0,clientId:F($.clientId).trim()||void 0,metadata:z0($.metadata)}),{sessionId:Y,created:!0,status:Q}}upsertSession($){if(!$.session)throw Error("session is required");return this.store.upsertSession(QA($.session)),{persisted:!0}}getSession($){let Y=F($.sessionId).trim();if(!Y)throw Error("sessionId is required");let X=this.store.getSession(Y);if(!X)return{};return{session:O7(X)}}listSessions($){let Y=typeof $.limit==="number"&&$.limit>0?Math.floor($.limit):200;return{sessions:this.store.listSessions({limit:Y,parentSessionId:F($.parentSessionId).trim()||void 0,status:F($.status).trim()||void 0}).map((Q)=>O7(Q))}}updateSession($){let Y=F($.sessionId).trim();if(!Y)throw Error("sessionId is required");return this.store.updateSession({sessionId:Y,status:$.status?I7($.status):void 0,endedAt:$.endedAt?$.endedAt:void 0,exitCode:$.hasExitCode?$.exitCode??null:void 0,prompt:$.hasPrompt?$.prompt??null:void 0,metadata:$.hasMetadata?z0($.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 Y=F($.sessionId).trim();if(!Y)throw Error("sessionId is required");let X=this.store.deleteSession(Y);if($.cascade===!0)this.store.deleteSessionsByParent(Y);return{deleted:X}}enqueueSpawnRequest($){let Y=F($.rootSessionId).trim(),X=F($.parentAgentId).trim();if(!Y||!X)throw Error("rootSessionId and parentAgentId are required");return this.store.enqueueSpawnRequest({rootSessionId:Y,parentAgentId:X,task:F($.task).trim()||void 0,systemPrompt:F($.systemPrompt).trim()||void 0}),{enqueued:!0}}claimSpawnRequest($){let Y=F($.rootSessionId).trim(),X=F($.parentAgentId).trim();if(!Y||!X)throw Error("rootSessionId and parentAgentId are required");let Q=this.store.claimSpawnRequest(Y,X);if(!Q)return{};return{item:{id:String(Q.id),rootSessionId:Q.rootSessionId,parentAgentId:Q.parentAgentId,task:Q.task??"",systemPrompt:Q.systemPrompt??"",createdAt:Q.createdAt,consumedAt:Q.consumedAt??""}}}async startRuntimeSession($){let Y=this.runtimeHandlers?.startSession;if(!Y)throw Error("runtime start handler is not configured");let X=$.request?{workspaceRoot:F($.request.workspaceRoot),cwd:F($.request.cwd),provider:F($.request.provider),model:F($.request.model),mode:F($.request.mode),apiKey:F($.request.apiKey),systemPrompt:F($.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:F($.request.teamName),missionStepInterval:$.request.missionStepInterval??3,missionTimeIntervalMs:$.request.missionTimeIntervalMs??120000,toolPolicies:Object.fromEntries(Object.entries($.request.toolPolicies??{}).map(([Z,T])=>[Z,{enabled:T?.enabled===!0,autoApprove:T?.autoApprove===!0}])),initialMessages:($.request.initialMessages??[]).map((Z)=>({role:F(Z.role),content:E$(Z.content)})),logger:$.request.logger?{enabled:$.request.logger.enabled===!0,level:F($.request.logger.level),destination:F($.request.logger.destination),name:F($.request.logger.name),bindings:z0($.request.logger.bindings)}:void 0}:void 0;if(!X)throw Error("runtime start request is required");let Q=await Y(X),J=F(Q.sessionId).trim();if(!J)throw Error("runtime start handler returned empty sessionId");return{sessionId:J,startResult:Q.startResult?{sessionId:F(Q.startResult.sessionId),manifestPath:F(Q.startResult.manifestPath),transcriptPath:F(Q.startResult.transcriptPath),hookPath:F(Q.startResult.hookPath),messagesPath:F(Q.startResult.messagesPath)}:void 0}}async sendRuntimeSession($){let Y=this.runtimeHandlers?.sendSession;if(!Y)throw Error("runtime send handler is not configured");let X=F($.sessionId).trim();if(!X)throw Error("sessionId is required");let Q=$.request?{config:{workspaceRoot:F($.request.config?.workspaceRoot),cwd:F($.request.config?.cwd),provider:F($.request.config?.provider),model:F($.request.config?.model),mode:F($.request.config?.mode),apiKey:F($.request.config?.apiKey),systemPrompt:F($.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:F($.request.config?.teamName),missionStepInterval:$.request.config?.missionStepInterval??3,missionTimeIntervalMs:$.request.config?.missionTimeIntervalMs??120000,toolPolicies:Object.fromEntries(Object.entries($.request.config?.toolPolicies??{}).map(([Z,T])=>[Z,{enabled:T?.enabled===!0,autoApprove:T?.autoApprove===!0}])),initialMessages:($.request.config?.initialMessages??[]).map((Z)=>({role:F(Z.role),content:E$(Z.content)})),logger:$.request.config?.logger?{enabled:$.request.config.logger.enabled===!0,level:F($.request.config.logger.level),destination:F($.request.config.logger.destination),name:F($.request.config.logger.name),bindings:z0($.request.config.logger.bindings)}:void 0},messages:($.request.messages??[]).map((Z)=>({role:F(Z.role),content:E$(Z.content)})),prompt:F($.request.prompt),attachments:$.request.attachments?{userImages:$.request.attachments.userImages??[],userFiles:($.request.attachments.userFiles??[]).map((Z)=>({name:F(Z.name),content:F(Z.content)}))}:void 0}:void 0;if(!Q)throw Error("runtime send request is required");let J=await Y(X,Q);return{result:{text:F(J.result.text),usage:{inputTokens:J.result.usage.inputTokens,outputTokens:J.result.usage.outputTokens,cacheReadTokens:J.result.usage.cacheReadTokens??0,hasCacheReadTokens:typeof J.result.usage.cacheReadTokens==="number",cacheWriteTokens:J.result.usage.cacheWriteTokens??0,hasCacheWriteTokens:typeof J.result.usage.cacheWriteTokens==="number",totalCost:J.result.usage.totalCost??0,hasTotalCost:typeof J.result.usage.totalCost==="number"},inputTokens:J.result.inputTokens,outputTokens:J.result.outputTokens,iterations:J.result.iterations,finishReason:F(J.result.finishReason),messages:(J.result.messages??[]).map((Z)=>({role:F(Z.role),content:R$(Z.content)})),toolCalls:(J.result.toolCalls??[]).map((Z)=>({name:F(Z.name),input:R$(Z.input),hasInput:Z.input!==void 0,output:R$(Z.output),hasOutput:Z.output!==void 0,error:F(Z.error),durationMs:Z.durationMs??0,hasDurationMs:typeof Z.durationMs==="number"}))}}}async stopRuntimeSession($){let Y=this.runtimeHandlers?.stopSession;if(!Y)throw Error("runtime stop handler is not configured");let X=F($.sessionId).trim();if(!X)throw Error("sessionId is required");return{applied:(await Y(X)).applied===!0}}async abortRuntimeSession($){let Y=this.runtimeHandlers?.abortSession;if(!Y)throw Error("runtime abort handler is not configured");let X=F($.sessionId).trim();if(!X)throw Error("sessionId is required");return{applied:(await Y(X)).applied===!0}}async runProviderAction($){let Y=this.runtimeHandlers?.runProviderAction;if(!Y)throw Error("provider action handler is not configured");if(!$.request)throw Error("provider action request is required");let X;if($.request.listProviders)X={action:"listProviders"};else if($.request.getProviderModels)X={action:"getProviderModels",providerId:F($.request.getProviderModels.providerId)};else if($.request.addProvider)X={action:"addProvider",providerId:F($.request.addProvider.providerId),name:F($.request.addProvider.name),baseUrl:F($.request.addProvider.baseUrl),apiKey:F($.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:F($.request.addProvider.defaultModelId)||void 0,modelsSourceUrl:F($.request.addProvider.modelsSourceUrl)||void 0,capabilities:$.request.addProvider.capabilities};else if($.request.saveProviderSettings)X={action:"saveProviderSettings",providerId:F($.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 J=F($.request.clineAccount?.operation);if(J==="fetchMe")X={action:"clineAccount",operation:"fetchMe"};else if(J==="fetchBalance")X={action:"clineAccount",operation:"fetchBalance",userId:F($.request.clineAccount?.userId)||void 0};else if(J==="fetchUsageTransactions")X={action:"clineAccount",operation:"fetchUsageTransactions",userId:F($.request.clineAccount?.userId)||void 0};else if(J==="fetchPaymentTransactions")X={action:"clineAccount",operation:"fetchPaymentTransactions",userId:F($.request.clineAccount?.userId)||void 0};else if(J==="fetchUserOrganizations")X={action:"clineAccount",operation:"fetchUserOrganizations"};else if(J==="fetchOrganizationBalance")X={action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:F($.request.clineAccount?.organizationId)};else if(J==="fetchOrganizationUsageTransactions")X={action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:F($.request.clineAccount?.organizationId),memberId:F($.request.clineAccount?.memberId)||void 0};else X={action:"clineAccount",operation:"switchAccount",organizationId:$.request.clineAccount?.clearOrganizationId?null:F($.request.clineAccount?.organizationId)||void 0}}let Q=await Y(X);return{result:R$(Q.result)}}async runProviderOAuthLogin($){let Y=this.runtimeHandlers?.runProviderOAuthLogin;if(!Y)throw Error("provider oauth handler is not configured");let X=F($.provider).trim();if(!X)throw Error("provider is required");let Q=await Y(X);return{provider:F(Q.provider).trim(),apiKey:F(Q.accessToken)}}startTask($){let Y=F($.sessionId).trim(),X=F($.taskId).trim();if(!Y||!X)throw Error("sessionId and taskId are required");let Q=`${Y}:${X}`;return this.tasks.set(Q,{sessionId:Y,taskId:X,title:F($.title).trim()||void 0,status:"running",payload:z0($.payload)??void 0}),this.eventService.publishEvent({eventId:"",sessionId:Y,taskId:X,eventType:"task.started",payload:z0($.payload)??{},sourceClientId:""}),{sessionId:Y,taskId:X,status:"running",updated:!0}}completeTask($){let Y=F($.sessionId).trim(),X=F($.taskId).trim();if(!Y||!X)throw Error("sessionId and taskId are required");let Q=`${Y}:${X}`,J=F($.status).trim()||"completed",Z=this.tasks.get(Q);if(!Z)return{sessionId:Y,taskId:X,status:J,updated:!1};return Z.status=J,Z.result=z0($.result)??void 0,this.eventService.publishEvent({eventId:"",sessionId:Y,taskId:X,eventType:"task.completed",payload:z0($.result)??{},sourceClientId:""}),{sessionId:Y,taskId:X,status:J,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($,Y){this.eventService.broadcastServerEvent($,Y)}}import{appendFileSync as KA,existsSync as dC,readFileSync as pC,writeFileSync as z8}from"node:fs";import{nanoid as cC}from"nanoid";import{z as j7}from"zod";import{nanoid as uC}from"nanoid";function H8($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function YX($,Y){let X=H8($),Q=H8(Y),J=`${X}__${Q}`;return J.length>180?J.slice(0,180):J}function C7($,Y){let X=H8($),Q=H8(Y);return`${X}__teamtask__${Q}__${uC(6)}`}function y7($){switch($.hookName){case"agent_end":return"completed";case"session_shutdown":{let Y=String($.reason??"").toLowerCase();if(Y.includes("cancel")||Y.includes("abort")||Y.includes("interrupt"))return"cancelled";if(Y.includes("fail")||Y.includes("error"))return"failed";return"completed"}default:return"running"}}var UA="cli_subagent",nC=j7.object({task:j7.string().optional(),systemPrompt:j7.string().optional()}).passthrough();function GA($){if(!$||Object.keys($).length===0)return null;return JSON.stringify($)}class q8{adapter;teamTaskSessionsByAgent=new Map;artifacts;constructor($){this.adapter=$;this.artifacts=new I5(()=>this.ensureSessionsDir())}teamTaskQueueKey($,Y){return`${$}::${Y}`}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}sessionTranscriptPath($){return this.artifacts.sessionTranscriptPath($)}sessionHookPath($){return this.artifacts.sessionHookPath($)}sessionMessagesPath($){return this.artifacts.sessionMessagesPath($)}sessionManifestPath($,Y=!0){return this.artifacts.sessionManifestPath($,Y)}async sessionPathFromStore($,Y){let Q=(await this.adapter.getSession($))?.[Y];return typeof Q==="string"&&Q.trim().length>0?Q:void 0}activeTeamTaskSessionId($,Y){let X=this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey($,Y));if(!X||X.length===0)return;return X[X.length-1]}subagentArtifactPaths($,Y,X,Q){return this.artifacts.subagentArtifactPaths(Y,Q,this.activeTeamTaskSessionId($,X))}writeSessionManifestFile($,Y){let X=qY.parse(Y);z8($,`${JSON.stringify(X,null,2)}
|
|
579
|
+
`,"utf8")}createRootSessionId(){return`${Date.now()}_${cC(5)}`}async createRootSessionWithArtifacts($){let Y=$.startedAt??E0(),X=$.sessionId.trim(),Q=X.length>0?X:this.createRootSessionId(),J=this.sessionTranscriptPath(Q),Z=this.sessionHookPath(Q),T=this.sessionMessagesPath(Q),K=this.sessionManifestPath(Q),U=qY.parse({version:1,session_id:Q,source:$.source,pid:$.pid,started_at:Y,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:T});return await this.adapter.upsertSession({session_id:Q,source:$.source,pid:$.pid,started_at:Y,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:U.prompt??null,metadata_json:GA(U.metadata),transcript_path:J,hook_path:Z,messages_path:T,updated_at:E0()}),z8(T,`${JSON.stringify({version:1,updated_at:Y,messages:[]},null,2)}
|
|
580
|
+
`,"utf8"),this.writeSessionManifestFile(K,U),{manifestPath:K,transcriptPath:J,hookPath:Z,messagesPath:T,manifest:U}}writeSessionManifest($,Y){this.writeSessionManifestFile($,Y)}async updateSessionStatus($,Y,X){for(let Q=0;Q<4;Q++){let J=await this.adapter.getSession($);if(!J||typeof J.status_lock!=="number")return{updated:!1};let Z=E0();if((await this.adapter.updateSession({sessionId:$,status:Y,endedAt:Z,exitCode:typeof X==="number"?X:null,expectedStatusLock:J.status_lock})).updated){if(Y==="cancelled")await this.applyStatusToRunningChildSessions($,"cancelled");return{updated:!0,endedAt:Z}}}return{updated:!1}}async updateSession($){for(let Y=0;Y<4;Y++){let X=await this.adapter.getSession($.sessionId);if(!X||typeof X.status_lock!=="number")return{updated:!1};if(!(await this.adapter.updateSession({sessionId:$.sessionId,prompt:$.prompt,metadataJson:$.metadata===void 0?void 0:GA($.metadata),expectedStatusLock:X.status_lock})).updated)continue;let J=this.sessionManifestPath($.sessionId,!1);if(dC(J))try{let Z=qY.parse(JSON.parse(pC(J,"utf8")));if($.prompt!==void 0)Z.prompt=$.prompt??void 0;if($.metadata!==void 0)Z.metadata=$.metadata??void 0;this.writeSessionManifestFile(J,Z)}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 Y=S8($.sessionContext);if(!Y)return;let X=nC.safeParse($.tool_call.input),Q=X.success?X.data.task:void 0,J=X.success?X.data.systemPrompt:void 0;await this.adapter.enqueueSpawnRequest({rootSessionId:Y,parentAgentId:$.agent_id,task:Q,systemPrompt:J})}async readRootSession($){return await this.adapter.getSession($)??null}async claimQueuedSpawnTask($,Y){return await this.adapter.claimSpawnRequest($,Y)}async upsertSubagentSession($){let Y=$.rootSessionId;if(!Y)return;let X=await this.readRootSession(Y);if(!X)return;let Q=YX(Y,$.agentId),J=await this.adapter.getSession(Q),Z=E0(),T=this.subagentArtifactPaths(Y,Q,$.parentAgentId,$.agentId),K=$.prompt??J?.prompt??void 0;if(!K)K=await this.claimQueuedSpawnTask(Y,$.parentAgentId)??`Subagent run by ${$.parentAgentId}`;if(!J)return await this.adapter.upsertSession({session_id:Q,source:UA,pid:process.ppid,started_at:Z,ended_at:null,exit_code:null,status:"running",status_lock:0,interactive:0,provider:X.provider,model:X.model,cwd:X.cwd,workspace_root:X.workspace_root,team_name:X.team_name??null,enable_tools:X.enable_tools,enable_spawn:X.enable_spawn,enable_teams:X.enable_teams,parent_session_id:Y,parent_agent_id:$.parentAgentId,agent_id:$.agentId,conversation_id:$.conversationId,is_subagent:1,prompt:K,metadata_json:null,transcript_path:T.transcriptPath,hook_path:T.hookPath,messages_path:T.messagesPath,updated_at:Z}),z8(T.messagesPath,`${JSON.stringify({version:1,updated_at:Z,messages:[]},null,2)}
|
|
581
|
+
`,"utf8"),Q;return await this.adapter.updateSession({sessionId:Q,setRunning:!0,parentSessionId:Y,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:J.prompt??K??null,expectedStatusLock:J.status_lock}),Q}async upsertSubagentSessionFromHook($){if(!$.parent_agent_id)return;let Y=S8($.sessionContext);if(!Y)return;if($.hookName==="session_shutdown"){let X=YX(Y,$.agent_id);return await this.adapter.getSession(X)?X:void 0}return await this.upsertSubagentSession({agentId:$.agent_id,parentAgentId:$.parent_agent_id,conversationId:$.taskId,rootSessionId:Y})}async appendSubagentHookAudit($,Y){let X=`${JSON.stringify({ts:E0(),...Y})}
|
|
582
|
+
`,Q=await this.sessionPathFromStore($,"hook_path")??this.sessionHookPath($);KA(Q,X,"utf8")}async appendSubagentTranscriptLine($,Y){if(!Y.trim())return;let X=await this.sessionPathFromStore($,"transcript_path")??this.sessionTranscriptPath($);KA(X,`${Y}
|
|
583
|
+
`,"utf8")}async persistSessionMessages($,Y){let X=await this.sessionPathFromStore($,"messages_path")??this.sessionMessagesPath($);z8(X,`${JSON.stringify({version:1,updated_at:E0(),messages:Y},null,2)}
|
|
584
|
+
`,"utf8")}async applySubagentStatus($,Y){await this.applySubagentStatusBySessionId($,y7(Y))}async applySubagentStatusBySessionId($,Y){let X=await this.adapter.getSession($);if(!X||typeof X.status_lock!=="number")return;let Q=E0(),J=Y==="running"?null:Q,Z=Y==="failed"?1:0;await this.adapter.updateSession({sessionId:$,status:Y,endedAt:J,exitCode:Y==="running"?null:Z,expectedStatusLock:X.status_lock})}async applyStatusToRunningChildSessions($,Y){if(!$)return;let X=await this.adapter.listSessions({limit:2000,parentSessionId:$,status:"running"});for(let Q of X)await this.applySubagentStatusBySessionId(Q.session_id,Y)}async createTeamTaskSubSession($,Y,X){let Q=await this.readRootSession($);if(!Q)return;let J=C7($,Y),Z=E0(),T=this.sessionTranscriptPath(J),K=this.sessionHookPath(J),U=this.sessionMessagesPath(J);return await this.adapter.upsertSession({session_id:J,source:UA,pid:process.ppid,started_at:Z,ended_at:null,exit_code:null,status:"running",status_lock:0,interactive:0,provider:Q.provider,model:Q.model,cwd:Q.cwd,workspace_root:Q.workspace_root,team_name:Q.team_name??null,enable_tools:Q.enable_tools,enable_spawn:Q.enable_spawn,enable_teams:Q.enable_teams,parent_session_id:$,parent_agent_id:"lead",agent_id:Y,conversation_id:null,is_subagent:1,prompt:X||`Team task for ${Y}`,metadata_json:null,transcript_path:T,hook_path:K,messages_path:U,updated_at:Z}),z8(U,`${JSON.stringify({version:1,updated_at:Z,messages:[]},null,2)}
|
|
585
|
+
`,"utf8"),await this.appendSubagentTranscriptLine(J,`[start] ${X}`),J}async onTeamTaskStart($,Y,X){let Q=await this.createTeamTaskSubSession($,Y,X);if(!Q)return;let J=this.teamTaskQueueKey($,Y),Z=this.teamTaskSessionsByAgent.get(J)??[];Z.push(Q),this.teamTaskSessionsByAgent.set(J,Z)}async onTeamTaskEnd($,Y,X,Q,J){let Z=this.teamTaskQueueKey($,Y),T=this.teamTaskSessionsByAgent.get(Z);if(!T||T.length===0)return;let K=T.shift();if(T.length===0)this.teamTaskSessionsByAgent.delete(Z);else this.teamTaskSessionsByAgent.set(Z,T);if(!K)return;if(J)await this.persistSessionMessages(K,J);await this.appendSubagentTranscriptLine(K,Q??`[done] ${X}`),await this.applySubagentStatusBySessionId(K,X)}async handleSubAgentStart($,Y){let X=await this.upsertSubagentSession({agentId:Y.subAgentId,parentAgentId:Y.parentAgentId,conversationId:Y.conversationId,prompt:Y.input.task,rootSessionId:$});if(!X)return;await this.appendSubagentTranscriptLine(X,`[start] ${Y.input.task}`),await this.applySubagentStatusBySessionId(X,"running")}async handleSubAgentEnd($,Y){let X=await this.upsertSubagentSession({agentId:Y.subAgentId,parentAgentId:Y.parentAgentId,conversationId:Y.conversationId,prompt:Y.input.task,rootSessionId:$});if(!X)return;if(Y.error){await this.appendSubagentTranscriptLine(X,`[error] ${Y.error.message}`),await this.applySubagentStatusBySessionId(X,"failed");return}if(await this.appendSubagentTranscriptLine(X,`[done] ${Y.result?.finishReason??"completed"}`),Y.result?.finishReason==="aborted"){await this.applySubagentStatusBySessionId(X,"cancelled");return}await this.applySubagentStatusBySessionId(X,"completed")}isPidAlive($){if(!Number.isFinite($)||$<=0)return!1;try{return process.kill(Math.floor($),0),!0}catch(Y){return typeof Y==="object"&&Y!==null&&"code"in Y&&Y.code==="EPERM"}}async listSessions($=200){let Y=Math.max(1,Math.floor($)),X=Math.min(Y*5,2000),Q=await this.adapter.listSessions({limit:X}),J=Q.filter((Z)=>Z.status==="running"&&!this.isPidAlive(Z.pid));if(J.length>0){for(let Z of J)await this.updateSessionStatus(Z.session_id,"failed",1);Q=await this.adapter.listSessions({limit:X})}return Q.slice(0,Y)}async deleteSession($){let Y=$.trim();if(!Y)throw Error("session id is required");let X=await this.adapter.getSession(Y);if(!X)return{deleted:!1};if(await this.adapter.deleteSession(Y,!1),!X.is_subagent){let Q=await this.adapter.listSessions({limit:2000,parentSessionId:Y});await this.adapter.deleteSession(Y,!0);for(let J of Q)$$(J.transcript_path),$$(J.hook_path),$$(J.messages_path),$$(this.sessionManifestPath(J.session_id,!1)),this.artifacts.removeSessionDirIfEmpty(J.session_id)}return $$(X.transcript_path),$$(X.hook_path),$$(X.messages_path),$$(this.sessionManifestPath(Y,!1)),this.artifacts.removeSessionDirIfEmpty(Y),{deleted:!0}}}function WA($){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 rC($){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 Y=JSON.parse($.metadata_json);if(Y&&typeof Y==="object"&&!Array.isArray(Y))return Y}catch{}return})(),transcriptPath:$.transcript_path,hookPath:$.hook_path,messagesPath:$.messages_path??void 0,updatedAt:$.updated_at??E0()}}class RA{client;constructor($){this.client=$}ensureSessionsDir(){return""}async upsertSession($){await this.client.upsertSession(rC($))}async getSession($){let Y=await this.client.getSession($);return Y?WA(Y):void 0}async listSessions($){return(await this.client.listSessions($)).map((X)=>WA(X))}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($,Y){return await this.client.deleteSession($,Y)}async enqueueSpawnRequest($){await this.client.enqueueSpawnRequest($)}async claimSpawnRequest($,Y){return await this.client.claimSpawnRequest($,Y)}}class XX extends q8{sessionsDirPath;client;constructor($){let Y=new F8({address:$.address?.trim()||"127.0.0.1:4317"});super(new RA(Y));this.sessionsDirPath=$.sessionsDir,this.client=Y}ensureSessionsDir(){if(!lC(this.sessionsDirPath))iC(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}close(){this.client.close()}}import{spawn as eC}from"node:child_process";import{existsSync as $y,mkdirSync as Yy,readFileSync as Xy,writeFileSync as Qy}from"node:fs";import{resolve as Jy}from"node:path";import{nanoid as Zy}from"nanoid";import{existsSync as oC,mkdirSync as sC}from"node:fs";import{join as aC}from"node:path";function tC(){return g$()}class X6{sessionsDirPath;db;constructor($={}){this.sessionsDirPath=$.sessionsDir??tC()}init(){this.getRawDb()}ensureSessionsDir(){if(!oC(this.sessionsDirPath))sC(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return aC(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let $=DY(this.sessionDbPath());return V9($,{includeLegacyMigrations:!0}),this.db=$,$}run($,Y=[]){return this.getRawDb().prepare($).run(...Y)}queryOne($,Y=[]){return this.getRawDb().prepare($).get(...Y)??void 0}queryAll($,Y=[]){return this.getRawDb().prepare($).all(...Y)}create($){let Y=O0();this.run(`INSERT OR REPLACE INTO sessions (
|
|
586
|
+
session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
|
|
587
|
+
provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
|
|
588
|
+
parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
|
|
589
|
+
metadata_json, transcript_path, hook_path, messages_path, updated_at
|
|
590
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,0,t0($.interactive),$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,t0($.enableTools),t0($.enableSpawn),t0($.enableTeams),$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,t0($.isSubagent),$.prompt??null,$.metadata?JSON.stringify($.metadata):null,$.transcriptPath??"",$.hookPath??"",$.messagesPath??null,Y])}update($){let Y=[],X=[];if($.endedAt!==void 0)Y.push("ended_at = ?"),X.push($.endedAt);if($.exitCode!==void 0)Y.push("exit_code = ?"),X.push($.exitCode);if($.status!==void 0)Y.push("status = ?"),X.push($.status);if($.prompt!==void 0)Y.push("prompt = ?"),X.push($.prompt);if($.metadata!==void 0)Y.push("metadata_json = ?"),X.push($.metadata?JSON.stringify($.metadata):null);if($.parentSessionId!==void 0)Y.push("parent_session_id = ?"),X.push($.parentSessionId);if($.parentAgentId!==void 0)Y.push("parent_agent_id = ?"),X.push($.parentAgentId);if($.agentId!==void 0)Y.push("agent_id = ?"),X.push($.agentId);if($.conversationId!==void 0)Y.push("conversation_id = ?"),X.push($.conversationId);if(Y.length===0)return;Y.push("updated_at = ?"),X.push(O0()),X.push($.sessionId),this.run(`UPDATE sessions SET ${Y.join(", ")} WHERE session_id = ?`,X)}updateStatus($,Y,X){this.update({sessionId:$,status:Y,endedAt:Y==="running"?null:O0(),exitCode:Y==="running"?null:X??(Y==="failed"?1:0)})}get($){let Y=this.queryOne(`SELECT session_id, source, pid, started_at, ended_at, exit_code, status, interactive,
|
|
591
|
+
provider, model, cwd, workspace_root, team_name,
|
|
592
|
+
enable_tools, enable_spawn, enable_teams,
|
|
593
|
+
parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent,
|
|
594
|
+
prompt, metadata_json, transcript_path, hook_path, messages_path, updated_at
|
|
595
|
+
FROM sessions WHERE session_id = ?`,[$]);if(!Y)return;return{sessionId:J0(Y.session_id),source:J0(Y.source),pid:Number(Y.pid??0),startedAt:J0(Y.started_at),endedAt:Y.ended_at??null,exitCode:Y.exit_code??null,status:J0(Y.status),interactive:e0(Y.interactive),provider:J0(Y.provider),model:J0(Y.model),cwd:J0(Y.cwd),workspaceRoot:J0(Y.workspace_root),teamName:U0(Y.team_name),enableTools:e0(Y.enable_tools),enableSpawn:e0(Y.enable_spawn),enableTeams:e0(Y.enable_teams),parentSessionId:U0(Y.parent_session_id),parentAgentId:U0(Y.parent_agent_id),agentId:U0(Y.agent_id),conversationId:U0(Y.conversation_id),isSubagent:e0(Y.is_subagent),prompt:U0(Y.prompt),metadata:(()=>{let X=U0(Y.metadata_json);if(!X)return;try{let Q=JSON.parse(X);if(Q&&typeof Q==="object"&&!Array.isArray(Q))return Q}catch{}return})(),transcriptPath:U0(Y.transcript_path),hookPath:U0(Y.hook_path),messagesPath:U0(Y.messages_path),updatedAt:U0(Y.updated_at)??O0()}}list($=200){let Y=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[$]),X=[];for(let Q of Y){let J=this.get(J0(Q.session_id));if(J)X.push(J)}return X}delete($,Y=!1){let X=this.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(Y)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return X>0}}class EA{store;constructor($){this.store=$}ensureSessionsDir(){return this.store.ensureSessionsDir()}async upsertSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
|
|
596
|
+
session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
|
|
597
|
+
provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
|
|
598
|
+
parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
|
|
599
|
+
metadata_json, transcript_path, hook_path, messages_path, updated_at
|
|
600
|
+
) 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??E0()])}async getSession($){return this.store.queryOne(`SELECT session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
|
|
601
|
+
provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
|
|
602
|
+
parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
|
|
603
|
+
metadata_json, transcript_path, hook_path, messages_path, updated_at
|
|
604
|
+
FROM sessions WHERE session_id = ?`,[$])??void 0}async listSessions($){let Y=[],X=[];if($.parentSessionId)Y.push("parent_session_id = ?"),X.push($.parentSessionId);if($.status)Y.push("status = ?"),X.push($.status);let Q=Y.length>0?`WHERE ${Y.join(" AND ")}`:"";return this.store.queryAll(`SELECT session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
|
|
605
|
+
provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
|
|
606
|
+
parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
|
|
607
|
+
metadata_json, transcript_path, hook_path, messages_path, updated_at
|
|
608
|
+
FROM sessions
|
|
609
|
+
${Q}
|
|
610
|
+
ORDER BY started_at DESC
|
|
611
|
+
LIMIT ?`,[...X,$.limit])}async updateSession($){if($.setRunning){if($.expectedStatusLock===void 0)return{updated:!1,statusLock:0};return{updated:(this.store.run(`UPDATE sessions
|
|
612
|
+
SET status = 'running', ended_at = NULL, exit_code = NULL, updated_at = ?, status_lock = ?,
|
|
613
|
+
parent_session_id = ?, parent_agent_id = ?, agent_id = ?, conversation_id = ?, is_subagent = 1,
|
|
614
|
+
prompt = COALESCE(prompt, ?)
|
|
615
|
+
WHERE session_id = ? AND status_lock = ?`,[E0(),$.expectedStatusLock+1,$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,$.prompt??null,$.sessionId,$.expectedStatusLock]).changes??0)>0,statusLock:$.expectedStatusLock+1}}let Y=[],X=[];if($.status!==void 0)Y.push("status = ?"),X.push($.status);if($.endedAt!==void 0)Y.push("ended_at = ?"),X.push($.endedAt);if($.exitCode!==void 0)Y.push("exit_code = ?"),X.push($.exitCode);if($.prompt!==void 0)Y.push("prompt = ?"),X.push($.prompt??null);if($.metadataJson!==void 0)Y.push("metadata_json = ?"),X.push($.metadataJson??null);if($.parentSessionId!==void 0)Y.push("parent_session_id = ?"),X.push($.parentSessionId??null);if($.parentAgentId!==void 0)Y.push("parent_agent_id = ?"),X.push($.parentAgentId??null);if($.agentId!==void 0)Y.push("agent_id = ?"),X.push($.agentId??null);if($.conversationId!==void 0)Y.push("conversation_id = ?"),X.push($.conversationId??null);if(Y.length===0){let T=await this.getSession($.sessionId);return{updated:!!T,statusLock:T?.status_lock??0}}let Q=0;if($.expectedStatusLock!==void 0)Q=$.expectedStatusLock+1,Y.push("status_lock = ?"),X.push(Q);Y.push("updated_at = ?"),X.push(E0());let J=`UPDATE sessions SET ${Y.join(", ")} WHERE session_id = ?`;if(X.push($.sessionId),$.expectedStatusLock!==void 0)J+=" AND status_lock = ?",X.push($.expectedStatusLock);if((this.store.run(J,X).changes??0)===0)return{updated:!1,statusLock:0};if($.expectedStatusLock===void 0)Q=(await this.getSession($.sessionId))?.status_lock??0;return{updated:!0,statusLock:Q}}async deleteSession($,Y){let X=this.store.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(Y)this.store.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return X>0}async enqueueSpawnRequest($){this.store.run(`INSERT INTO subagent_spawn_queue (root_session_id, parent_agent_id, task, system_prompt, created_at, consumed_at)
|
|
616
|
+
VALUES (?, ?, ?, ?, ?, NULL)`,[$.rootSessionId,$.parentAgentId,$.task??null,$.systemPrompt??null,E0()])}async claimSpawnRequest($,Y){let X=this.store.queryOne(`SELECT id, task FROM subagent_spawn_queue
|
|
617
|
+
WHERE root_session_id = ? AND parent_agent_id = ? AND consumed_at IS NULL
|
|
618
|
+
ORDER BY id ASC LIMIT 1`,[$,Y]);if(!X||typeof X.id!=="number")return;return this.store.run("UPDATE subagent_spawn_queue SET consumed_at = ? WHERE id = ?",[E0(),X.id]),X.task??void 0}}class QX extends q8{store;constructor($){super(new EA($));this.store=$}createRootSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
|
|
619
|
+
session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
|
|
620
|
+
provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
|
|
621
|
+
parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
|
|
622
|
+
metadata_json, transcript_path, hook_path, messages_path, updated_at
|
|
623
|
+
) 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,E0()])}}var Ty=process.env.CLINE_RPC_ADDRESS?.trim()||"127.0.0.1:4317",o1,N8;function Ky($){if(!$)return!1;return/\.(?:[cm]?[jt]s|tsx?)$/i.test($)}function Uy($){let Y=process.argv[0],X=process.argv[1],Q=["rpc","start","--address",$],J=X&&Ky(X)?[X,...Q]:Q;eC(Y,J,{detached:!0,stdio:"ignore",env:process.env,cwd:process.cwd()}).unref()}async function VA($){try{if(!await $X($))return;return new XX({address:$,sessionsDir:g$()})}catch{return}}function AA(){return new QX(new X6)}function Gy($){if(typeof $==="string"&&$.trim().length>0)return $.trim();let Y=g$(),X=Jy(Y,"machine-id");try{if($y(X)){let J=Xy(X,"utf8").trim();if(J.length>0)return J}}catch{}let Q=Zy();try{Yy(Y,{recursive:!0}),Qy(X,Q,"utf8")}catch{}return Q}async function Wy($){if(o1)return o1;if(N8)return await N8;let Y=$.backendMode??"auto",X=$.rpcAddress?.trim()||Ty,Q=Math.max(1,$.rpcConnectAttempts??5),J=Math.max(0,$.rpcConnectDelayMs??100),Z=$.autoStartRpcServer!==!1;return N8=(async()=>{if(Y==="local")return o1=AA(),o1;let T=await VA(X);if(T)return o1=T,o1;if(Y==="rpc")throw Error(`RPC backend unavailable at ${X}`);if(Z){try{Uy(X)}catch{}for(let K=0;K<Q;K+=1){let U=await VA(X);if(U)return o1=U,o1;if(J>0)await new Promise((G)=>setTimeout(G,J))}}return o1=AA(),o1})().finally(()=>{N8=void 0}),await N8}async function Ry($){let Y=$.sessionService??await Wy($);return new z9({sessionService:Y,defaultToolExecutors:$.defaultToolExecutors,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval,distinctId:Gy($.distinctId)})}class x7{store;constructor($={}){this.store=new X6({sessionsDir:$.sessionsDir})}init(){this.store.init()}upsertSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
|
|
624
|
+
session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
|
|
625
|
+
provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
|
|
626
|
+
parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
|
|
627
|
+
metadata_json, transcript_path, hook_path, messages_path, updated_at
|
|
628
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,$.statusLock,t0($.interactive),$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,t0($.enableTools),t0($.enableSpawn),t0($.enableTeams),$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,t0($.isSubagent),$.prompt??null,$.metadata?JSON.stringify($.metadata):null,$.transcriptPath,$.hookPath,$.messagesPath??null,$.updatedAt||O0()])}getSession($){let Y=this.store.queryOne(`SELECT session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
|
|
629
|
+
provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
|
|
630
|
+
parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
|
|
631
|
+
metadata_json, transcript_path, hook_path, messages_path, updated_at
|
|
632
|
+
FROM sessions WHERE session_id = ?`,[$]);if(!Y)return;return{sessionId:J0(Y.session_id),source:J0(Y.source),pid:Number(Y.pid??0),startedAt:J0(Y.started_at),endedAt:Y.ended_at??null,exitCode:Y.exit_code??null,status:J0(Y.status),statusLock:Number(Y.status_lock??0),interactive:e0(Y.interactive),provider:J0(Y.provider),model:J0(Y.model),cwd:J0(Y.cwd),workspaceRoot:J0(Y.workspace_root),teamName:U0(Y.team_name),enableTools:e0(Y.enable_tools),enableSpawn:e0(Y.enable_spawn),enableTeams:e0(Y.enable_teams),parentSessionId:U0(Y.parent_session_id),parentAgentId:U0(Y.parent_agent_id),agentId:U0(Y.agent_id),conversationId:U0(Y.conversation_id),isSubagent:e0(Y.is_subagent),prompt:U0(Y.prompt),metadata:(()=>{let X=U0(Y.metadata_json);if(!X)return;try{let Q=JSON.parse(X);if(Q&&typeof Q==="object"&&!Array.isArray(Q))return Q}catch{}return})(),transcriptPath:J0(Y.transcript_path),hookPath:J0(Y.hook_path),messagesPath:U0(Y.messages_path),updatedAt:J0(Y.updated_at)||O0()}}listSessions($){let Y=[],X=[];if($.parentSessionId)Y.push("parent_session_id = ?"),X.push($.parentSessionId);if($.status)Y.push("status = ?"),X.push($.status);let Q=Y.length>0?`WHERE ${Y.join(" AND ")}`:"",J=Math.max(1,Math.floor($.limit)),Z=this.store.queryAll(`SELECT session_id FROM sessions ${Q} ORDER BY started_at DESC LIMIT ?`,[...X,J]),T=[];for(let K of Z){if(!K.session_id)continue;let U=this.getSession(K.session_id);if(U)T.push(U)}return T}updateSession($){let Y=this.getSession($.sessionId);if(!Y)return{updated:!1,statusLock:0};if(typeof $.expectedStatusLock==="number"&&Y.statusLock!==$.expectedStatusLock)return{updated:!1,statusLock:Y.statusLock};let X=Y.statusLock+1,Q=$.setRunning?"running":$.status??Y.status,J=$.setRunning===!0?null:$.endedAt!==void 0?$.endedAt:Y.endedAt??null,Z=$.setRunning===!0?null:$.exitCode!==void 0?$.exitCode:Y.exitCode??null,T=$.prompt!==void 0?$.prompt??void 0:Y.prompt,K=$.metadata!==void 0?$.metadata??void 0:Y.metadata;return this.store.run(`UPDATE sessions
|
|
633
|
+
SET status = ?, ended_at = ?, exit_code = ?, prompt = ?, metadata_json = ?,
|
|
634
|
+
parent_session_id = ?, parent_agent_id = ?, agent_id = ?, conversation_id = ?,
|
|
635
|
+
status_lock = ?, updated_at = ?
|
|
636
|
+
WHERE session_id = ?`,[Q,J,Z,T??null,K?JSON.stringify(K):null,$.parentSessionId!==void 0?$.parentSessionId??null:Y.parentSessionId??null,$.parentAgentId!==void 0?$.parentAgentId??null:Y.parentAgentId??null,$.agentId!==void 0?$.agentId??null:Y.agentId??null,$.conversationId!==void 0?$.conversationId??null:Y.conversationId??null,X,O0(),$.sessionId]),{updated:!0,statusLock:X}}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)
|
|
637
|
+
VALUES (?, ?, ?, ?, ?, NULL)`,[$.rootSessionId,$.parentAgentId,$.task??null,$.systemPrompt??null,O0()])}claimSpawnRequest($,Y){let X=this.store.queryOne(`SELECT id, root_session_id, parent_agent_id, task, system_prompt, created_at, consumed_at
|
|
638
|
+
FROM subagent_spawn_queue
|
|
639
|
+
WHERE root_session_id = ? AND parent_agent_id = ? AND consumed_at IS NULL
|
|
640
|
+
ORDER BY id ASC LIMIT 1`,[$,Y]);if(!X||typeof X.id!=="number")return;let Q=O0();return this.store.run("UPDATE subagent_spawn_queue SET consumed_at = ? WHERE id = ?",[Q,X.id]),{id:X.id,rootSessionId:J0(X.root_session_id),parentAgentId:J0(X.parent_agent_id),task:U0(X.task),systemPrompt:U0(X.system_prompt),createdAt:J0(X.created_at),consumedAt:Q}}}function Ey($={}){return new x7($)}import{basename as Vy,resolve as Ay}from"node:path";import Dy from"simple-git";import{z as y1}from"zod";var DA=y1.object({rootPath:y1.string().min(1),hint:y1.string().min(1).optional(),associatedRemoteUrls:y1.array(y1.string().min(1)).optional(),latestGitCommitHash:y1.string().min(1).optional(),latestGitBranchName:y1.string().min(1).optional()}),Q6=y1.object({currentWorkspacePath:y1.string().min(1).optional(),workspaces:y1.record(y1.string().min(1),DA)});function Fy(){return{workspaces:{}}}function M8($){return Ay($)}async function JX($){let Y=M8($),X={rootPath:Y,hint:Vy(Y)};try{let Q=Dy({baseDir:Y});if(!await Q.checkIsRepo())return X;let Z=await Q.getRemotes(!0);if(Z.length>0){let U=Z.map((G)=>{let W=G.refs.fetch||G.refs.push;return`${G.name}: ${W}`});X.associatedRemoteUrls=U}let T=(await Q.revparse(["HEAD"])).trim();if(T.length>0)X.latestGitCommitHash=T;let K=(await Q.branch()).current.trim();if(K.length>0)X.latestGitBranchName=K}catch{}return X}function v7($,Y){let X={...$,workspaces:{...$.workspaces,[Y.rootPath]:Y}};if(!X.currentWorkspacePath)X.currentWorkspacePath=Y.rootPath;return Q6.parse(X)}async function Hy($){let Y=await JX($),X={workspaces:{[Y.rootPath]:{hint:Y.hint,associatedRemoteUrls:Y.associatedRemoteUrls,latestGitCommitHash:Y.latestGitCommitHash,latestGitBranchName:Y.latestGitBranchName}}};return`# Workspace Configuration
|
|
641
|
+
${JSON.stringify(X,null,2)}`}class FA{manifest;listeners=new Set;constructor($){this.manifest=Q6.parse($??{workspaces:{}})}async addWorkspacePath($){let Y=await JX($);return this.manifest=v7(this.manifest,Y),this.emit({type:"workspace_added",workspace:Y}),Y}async switchWorkspace($){let Y=M8($),X=this.manifest.workspaces[Y];if(X)return this.manifest=Q6.parse({...this.manifest,currentWorkspacePath:Y}),this.emit({type:"workspace_switched",workspace:X}),X;let Q=await this.addWorkspacePath(Y);return this.manifest=Q6.parse({...this.manifest,currentWorkspacePath:Q.rootPath}),this.emit({type:"workspace_switched",workspace:Q}),Q}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}getCurrentWorkspace(){let $=this.manifest.currentWorkspacePath;if(!$)return;return this.manifest.workspaces[$]}getWorkspace($){let Y=M8($);return this.manifest.workspaces[Y]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit($){for(let Y of this.listeners)Y($)}}import{existsSync as zy,readFileSync as qy}from"node:fs";import{join as HA}from"node:path";import{models as Ny,providers as My}from"@clinebot/llms";function c($){let Y=$?.trim();return Y?Y:void 0}function zA($){if(!zy($))return;try{let Y=qy($,"utf8"),X=JSON.parse(Y);if(X&&typeof X==="object"&&!Array.isArray(X))return X}catch{}return}function By($){let Y=$.dataDir??H1(),X=$.globalStatePath??HA(Y,"globalState.json"),Q=$.secretsPath??HA(Y,"secrets.json"),J=zA(X),Z=zA(Q);if(!J&&!Z)return;return{globalState:J??{},secrets:Z??{}}}function Iy($,Y,X,Q){let J=X==="plan"?"planMode":"actMode",Z=Y===Q?c(X==="plan"?$.planModeApiModelId:$.actModeApiModelId):void 0,K={openrouter:`${J}OpenRouterModelId`,cline:`${J}ClineModelId`,openai:`${J}OpenAiModelId`,ollama:`${J}OllamaModelId`,lmstudio:`${J}LmStudioModelId`,litellm:`${J}LiteLlmModelId`,requesty:`${J}RequestyModelId`,together:`${J}TogetherModelId`,fireworks:`${J}FireworksModelId`,sapaicore:`${J}SapAiCoreModelId`,groq:`${J}GroqModelId`,baseten:`${J}BasetenModelId`,huggingface:`${J}HuggingFaceModelId`,"huawei-cloud-maas":`${J}HuaweiCloudMaasModelId`,oca:`${J}OcaModelId`,aihubmix:`${J}AihubmixModelId`,hicap:`${J}HicapModelId`,nousResearch:`${J}NousResearchModelId`,"vercel-ai-gateway":`${J}VercelAiGatewayModelId`}[Y];return(K?c(typeof $[K]==="string"?$[K]:void 0):void 0)??Z}function Oy($,Y,X){let Q=X==="plan"?$.planModeReasoningEffort:$.actModeReasoningEffort,J=X==="plan"?$.geminiPlanModeThinkingLevel:$.geminiActModeThinkingLevel,Z=X==="plan"?$.planModeThinkingBudgetTokens:$.actModeThinkingBudgetTokens,T=(Y==="gemini"?J:void 0)??Q,K=T==="none"||T==="low"||T==="medium"||T==="high"?T:void 0,U=typeof Z==="number"&&Number.isInteger(Z)&&Z>0?Z:void 0;if(!K&&U===void 0)return;return{...K?{effort:K}:{},...U!==void 0?{budgetTokens:U}:{}}}function Py($){let Y=$["openai-codex-oauth-credentials"];if(!Y)return;try{let X=JSON.parse(Y),Q=c(X.access_token),J=c(X.refresh_token),Z=c(X.accountId);if(!Q&&!J&&!Z)return;return{...Q?{apiKey:Q}:{},auth:{...Q?{accessToken:Q}:{},...J?{refreshToken:J}:{},...Z?{accountId:Z}:{}}}}catch{return}}function Ly($){let Y=Ny.getGeneratedModelsForProvider($);return Object.keys(Y)[0]??void 0}function Sy($,Y,X,Q){let J=c(Q==="plan"?Y.planModeApiProvider:Y.actModeApiProvider),Z=Iy(Y,$,Q,J)??Ly($),T=Oy(Y,$,Q),K=typeof Y.requestTimeoutMs==="number"&&Number.isInteger(Y.requestTimeoutMs)&&Y.requestTimeoutMs>0?Y.requestTimeoutMs:void 0,U={anthropic:X.apiKey,cline:X.clineApiKey,openai:X.openAiApiKey,"openai-native":X.openAiNativeApiKey,openrouter:X.openRouterApiKey,bedrock:X.awsBedrockApiKey,gemini:X.geminiApiKey,ollama:X.ollamaApiKey,deepseek:X.deepSeekApiKey,requesty:X.requestyApiKey,together:X.togetherApiKey,fireworks:X.fireworksApiKey,qwen:X.qwenApiKey,doubao:X.doubaoApiKey,mistral:X.mistralApiKey,litellm:X.liteLlmApiKey,asksage:X.asksageApiKey,xai:X.xaiApiKey,moonshot:X.moonshotApiKey,zai:X.zaiApiKey,huggingface:X.huggingFaceApiKey,nebius:X.nebiusApiKey,sambanova:X.sambanovaApiKey,cerebras:X.cerebrasApiKey,groq:X.groqApiKey,"huawei-cloud-maas":X.huaweiCloudMaasApiKey,baseten:X.basetenApiKey,"vercel-ai-gateway":X.vercelAiGatewayApiKey,dify:X.difyApiKey,minimax:X.minimaxApiKey,hicap:X.hicapApiKey,aihubmix:X.aihubmixApiKey,nousResearch:X.nousResearchApiKey,oca:X.ocaApiKey,sapaicore:X.sapAiCoreClientId},G={};if($==="openai-codex")Object.assign(G,Py(X));if($==="cline"){let D=c(X["cline:clineAccountId"]??X.clineAccountId);if(D)G.auth={...G.auth??{},accountId:D}}if($==="openai"&&Y.openAiHeaders)G.headers=Y.openAiHeaders;if($==="bedrock")G.aws={accessKey:c(X.awsAccessKey),secretKey:c(X.awsSecretKey),sessionToken:c(X.awsSessionToken),region:c(Y.awsRegion),authentication:Y.awsAuthentication,profile:Y.awsUseProfile?c(Y.awsProfile):void 0,usePromptCache:Y.awsBedrockUsePromptCache,useCrossRegionInference:Y.awsUseCrossRegionInference,useGlobalInference:Y.awsUseGlobalInference,endpoint:c(Y.awsBedrockEndpoint),customModelBaseId:c(Q==="plan"?Y.planModeAwsBedrockCustomModelBaseId:Y.actModeAwsBedrockCustomModelBaseId)};if($==="vertex")G.gcp={projectId:c(Y.vertexProjectId),region:c(Y.vertexRegion)};if($==="openai"&&(Y.azureApiVersion||Y.azureIdentity!==void 0))G.azure={apiVersion:c(Y.azureApiVersion),useIdentity:Y.azureIdentity};if($==="sapaicore")G.sap={clientId:c(X.sapAiCoreClientId),clientSecret:c(X.sapAiCoreClientSecret),tokenUrl:c(Y.sapAiCoreTokenUrl),resourceGroup:c(Y.sapAiResourceGroup),deploymentId:c(Q==="plan"?Y.planModeSapAiCoreDeploymentId:Y.actModeSapAiCoreDeploymentId),useOrchestrationMode:Y.sapAiCoreUseOrchestrationMode};if($==="oca"){G.oca={mode:Y.ocaMode};let D=c(X.ocaRefreshToken);if(D)G.auth={...G.auth??{},refreshToken:D}}if($==="qwen")G.apiLine=Y.qwenApiLine;if($==="moonshot")G.apiLine=Y.moonshotApiLine;if($==="zai")G.apiLine=Y.zaiApiLine;if($==="minimax")G.apiLine=Y.minimaxApiLine;let W={anthropic:Y.anthropicBaseUrl,openai:Y.openAiBaseUrl,ollama:Y.ollamaBaseUrl,lmstudio:Y.lmStudioBaseUrl,litellm:Y.liteLlmBaseUrl,gemini:Y.geminiBaseUrl,requesty:Y.requestyBaseUrl,asksage:Y.asksageApiUrl,dify:Y.difyBaseUrl,oca:Y.ocaBaseUrl,aihubmix:Y.aihubmixBaseUrl,sapaicore:Y.sapAiCoreBaseUrl},R=c(U[$]),V=c(W[$]),A={provider:$,...R?{apiKey:R}:{},...Z?{model:Z}:{},...V?{baseUrl:V}:{},...T?{reasoning:T}:{},...K?{timeout:K}:{},...G},H=My.ProviderSettingsSchema.safeParse(A);if(!H.success)return;return Object.keys(A).filter((D)=>D!=="provider").length>0?H.data:void 0}function wy($,Y){let X=new Set;for(let Q of[$.actModeApiProvider,$.planModeApiProvider]){let J=c(Q);if(J)X.add(J)}if(c(Y.apiKey))X.add("anthropic");if(c(Y.openRouterApiKey))X.add("openrouter");if(c(Y.openAiApiKey))X.add("openai");if(c(Y.openAiNativeApiKey))X.add("openai-native");if(c(Y["openai-codex-oauth-credentials"]))X.add("openai-codex");if(c(Y.geminiApiKey))X.add("gemini");if(c(Y.ollamaApiKey))X.add("ollama");if(c(Y.awsAccessKey)||c(Y.awsBedrockApiKey))X.add("bedrock");if(c($.vertexProjectId)||c($.vertexRegion))X.add("vertex");if(c(Y.clineApiKey))X.add("cline");if(c(Y.ocaApiKey))X.add("oca");return X}function Cy($){let Y=$.providerSettingsManager.read(),X=By($);if(!X)return{migrated:!1,providerCount:Object.keys(Y.providers).length,lastUsedProvider:Y.lastUsedProvider};let{globalState:Q,secrets:J}=X,Z=Q.mode==="plan"?"plan":"act",T=wy(Q,J),K=z6();K.providers={...Y.providers},K.lastUsedProvider=Y.lastUsedProvider;let U=new Date().toISOString(),G=0;for(let R of T){if(K.providers[R])continue;let V=Sy(R,Q,J,Z);if(!V)continue;K.providers[R]={settings:V,updatedAt:U,tokenSource:"migration"},G+=1}if(G===0)return{migrated:!1,providerCount:Object.keys(Y.providers).length,lastUsedProvider:Y.lastUsedProvider};let W=c(Z==="plan"?Q.planModeApiProvider:Q.actModeApiProvider);return K.lastUsedProvider=Y.lastUsedProvider??(W&&K.providers[W]?W:Object.keys(K.providers)[0]),$.providerSettingsManager.write(K),{migrated:!0,providerCount:Object.keys(K.providers).length,lastUsedProvider:K.lastUsedProvider}}export{v7 as upsertWorkspaceInfo,i8 as toPartialAgentConfig,vX as toHookConfigFileName,d$ as startLocalOAuthServer,H8 as sanitizeSessionToken,iX as resolveWorkflowsConfigSearchPaths,IH as resolveWorkflowSlashCommandFromWatcher,nX as resolveSkillsConfigSearchPaths,lX as resolveRulesConfigSearchPaths,gX as resolvePluginConfigSearchPaths,G5 as resolveMcpServerRegistrations,jX as resolveHooksConfigSearchPaths,W6 as resolveDocumentsWorkflowsDirectoryPath,G6 as resolveDocumentsRulesDirectoryPath,U6 as resolveDocumentsHooksDirectoryPath,E9 as resolveDefaultMcpSettingsPath,e8 as resolveAndLoadAgentPlugins,l8 as resolveAgentTools,fX as resolveAgentPluginPaths,MH as requestDesktopToolApproval,YT as registerMcpServersFromSettingsFile,X5 as refreshOpenAICodexToken,Z5 as refreshOcaToken,$5 as refreshClineToken,GZ as prewarmFileIndex,cX as parseWorkflowConfigFromMarkdown,dX as parseSkillConfigFromMarkdown,pX as parseRuleConfigFromMarkdown,CX as parsePartialAgentConfigFromYaml,RY as parseAgentConfigFromYaml,SF as openaiCodexOAuthProvider,M8 as normalizeWorkspacePath,LF as normalizeOpenAICodexCredentials,Cy as migrateLegacyProviderSettings,C7 as makeTeamTaskSubSessionId,YX as makeSubSessionId,vZ as loginOpenAICodex,sZ as loginOcaOAuth,yZ as loginClineOAuth,tF as loadRulesForSystemPromptFromWatcher,U5 as loadMcpSettingsFile,s8 as loadAgentPluginsFromPaths,kX as loadAgentPluginFromPath,o8 as listHookConfigFiles,JT as listEnabledRulesFromWatcher,RT as listAvailableWorkflowsFromWatcher,XT as isRuleEnabled,h7 as isRpcClineAccountActionRequest,PF as isOpenAICodexTokenExpired,$T as hasMcpSettingsFile,Q5 as getValidOpenAICodexCredentials,T5 as getValidOcaCredentials,Y5 as getValidClineCredentials,m$ as getFileIndex,JX as generateWorkspaceInfo,aZ as generateOcaOpcRequestId,QT as formatRulesForSystemPrompt,_7 as executeRpcClineAccountAction,u8 as enrichPromptWithMentions,Fy as emptyWorkspaceManifest,t8 as discoverPluginModulePaths,y7 as deriveSubsessionStatus,sX as createWorkflowsConfigDefinition,Z9 as createUserInstructionConfigWatcher,RZ as createToolPoliciesWithPreset,GT as createTeamName,Ey as createSqliteRpcSessionBackend,rX as createSkillsConfigDefinition,Ry as createSessionHost,oX as createRulesConfigDefinition,fF as createOcaRequestHeaders,gF as createOcaOAuthProvider,TF as createOAuthClientCallbacks,EZ as createDefaultToolsWithPreset,GY as createDefaultTools,n8 as createDefaultExecutors,qF as createClineOAuthProvider,V6 as createBuiltinTools,HZ as createAgentConfigWatcher,yX as createAgentConfigDefinition,Hy as buildWorkspaceMetadata,Q6 as WorkspaceManifestSchema,DA as WorkspaceInfoSchema,T6 as WORKFLOWS_CONFIG_DIRECTORY_NAME,u$ as UnifiedConfigFileWatcher,t1 as ToolPresets,a8 as SubprocessSandbox,X6 as SqliteSessionStore,x7 as SqliteRpcSessionBackend,q6 as SessionSource,F1 as SKILLS_CONFIG_DIRECTORY_NAME,q5 as SESSION_STATUSES,XX as RpcCoreSessionService,KX as RpcClineAccountService,Z6 as RULES_CONFIG_DIRECTORY_NAME,zY as ProviderSettingsManager,pZ as OCI_HEADER_OPC_REQUEST_ID,FA as InMemoryWorkspaceManager,W5 as InMemoryMcpManager,r8 as HookConfigFileName,xX as HOOK_CONFIG_FILE_EVENT_MAP,J6 as HOOKS_CONFIG_DIRECTORY_NAME,j1 as DefaultToolNames,z9 as DefaultSessionManager,A9 as DefaultRuntimeBuilder,fZ as DEFAULT_INTERNAL_OCA_BASE_URL,_Z as DEFAULT_INTERNAL_IDCS_URL,gZ as DEFAULT_INTERNAL_IDCS_SCOPES,hZ as DEFAULT_INTERNAL_IDCS_CLIENT_ID,dZ as DEFAULT_EXTERNAL_OCA_BASE_URL,bZ as DEFAULT_EXTERNAL_IDCS_URL,uZ as DEFAULT_EXTERNAL_IDCS_SCOPES,mZ as DEFAULT_EXTERNAL_IDCS_CLIENT_ID,QX as CoreSessionService,TX as ClineAccountService,f$ as ALL_DEFAULT_TOOL_NAMES};
|