@clinebot/core 0.0.2 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,24 @@
1
- import{z as V}from"zod";var Zn=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"]),oe=V.object({adapter:V.string(),botUserName:V.string().optional(),event:Zn,payload:V.record(V.string(),V.unknown()),ts:V.string()});var Gn=[{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 ae(n){return Object.fromEntries(Gn.flatMap((t)=>{let e=n==="modelsDevKey"?t.modelsDevKey:t.generatedProviderId;return e?[[t.modelsDevKey,e]]:[]}))}var me=ae("generatedProviderId");import{z as M}from"zod";var ue=M.object({agentId:M.string(),conversationId:M.string(),iteration:M.number(),abortSignal:M.custom().optional(),metadata:M.record(M.string(),M.unknown()).optional()}),ce=M.object({id:M.string(),name:M.string(),input:M.unknown(),output:M.unknown(),error:M.string().optional(),durationMs:M.number(),startedAt:M.date(),endedAt:M.date()});import{z as ln}from"zod";function X(n,t){let e=n.safeParse(t);if(!e.success)throw Error(ln.prettifyError(e.error));return e.data}function $(n){return ln.toJSONSchema(n)}function nt(n){if(!n?.trim())return"";return tt(n,"user_input")}function tt(n,t){if(!n?.trim())return"";if(!t)return n;let e=new RegExp(`<${t}.*?>(.*?)</${t}>`,"g");return n.replace(e,"$1")}var et="runtime.team.progress.v1",rt="runtime.team.lifecycle.v1";function de(n){let t=n?.trim();return t?t:void 0}function st(n){return de(n?.hookLogPath)}var Mn=["running","completed","failed","cancelled"];import{existsSync as it,mkdirSync as ot}from"node:fs";import{dirname as at,join as W}from"node:path";var mt="cline_mcp_settings.json",Nn=process?.env?.HOME||"~",ut=!1;function ct(n){let t=n.trim();if(!t)return;Nn=t,ut=!0}function dt(n){if(ut)return;let t=n.trim();if(!t)return;Nn=t}function K(){let n=process.env.CLINE_DATA_DIR?.trim();if(n)return n;return W(Nn,".cline","data")}function gt(){let n=process.env.CLINE_SESSION_DATA_DIR?.trim();if(n)return n;return W(K(),"sessions")}function Dn(){let n=process.env.CLINE_TEAM_DATA_DIR?.trim();if(n)return n;return W(K(),"teams")}function Ln(){let n=process.env.CLINE_PROVIDER_SETTINGS_PATH?.trim();if(n)return n;return W(K(),"settings","providers.json")}function Sn(){let n=process.env.CLINE_MCP_SETTINGS_PATH?.trim();if(n)return n;return W(K(),"settings",mt)}function kn(n){let t=at(n);if(!it(t))ot(t,{recursive:!0})}function Tt(n){if(n?.trim())return kn(n),at(n);let t=W(K(),"hooks");if(!it(t))ot(t,{recursive:!0});return t}class Pn{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor(n){let t=n.apiBaseUrl.trim();if(!t)throw Error("apiBaseUrl is required");this.apiBaseUrl=t,this.getAuthTokenFn=n.getAuthToken,this.getCurrentUserIdFn=n.getCurrentUserId,this.getOrganizationMemberIdFn=n.getOrganizationMemberId,this.getHeadersFn=n.getHeaders,this.requestTimeoutMs=n.requestTimeoutMs??30000,this.fetchImpl=n.fetchImpl??fetch}async fetchMe(){return this.request("/api/v1/users/me")}async fetchBalance(n){let t=await this.resolveUserId(n);return this.request(`/api/v1/users/${encodeURIComponent(t)}/balance`)}async fetchUsageTransactions(n){let t=await this.resolveUserId(n);return(await this.request(`/api/v1/users/${encodeURIComponent(t)}/usages`)).items??[]}async fetchPaymentTransactions(n){let t=await this.resolveUserId(n);return(await this.request(`/api/v1/users/${encodeURIComponent(t)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchOrganizationBalance(n){let t=n.trim();if(!t)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(t)}/balance`)}async fetchOrganizationUsageTransactions(n){let t=n.organizationId.trim();if(!t)throw Error("organizationId is required");let e=await this.resolveOrganizationMemberId(t,n.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent(t)}/members/${encodeURIComponent(e)}/usages`)).items??[]}async switchAccount(n){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:n?.trim()||null},expectNoContent:!0})}async resolveUserId(n){let t=n?.trim();if(t)return t;let s=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(s)return s;let r=await this.fetchMe();if(!r.id?.trim())throw Error("Unable to resolve current user id");return r.id}async resolveOrganizationMemberId(n,t){let e=t?.trim();if(e)return e;let r=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn(n):void 0)?.trim();if(r)return r;let o=(await this.fetchUserOrganizations()).find((a)=>a.organizationId===n)?.memberId;if(!o?.trim())throw Error(`Unable to resolve memberId for organization ${n}`);return o}async request(n,t){let e=(await this.getAuthTokenFn())?.trim();if(!e)throw Error("No Cline account auth token found");let s=this.getHeadersFn?await this.getHeadersFn():{},r=new AbortController,i=setTimeout(()=>r.abort(),this.requestTimeoutMs);try{let o=await this.fetchImpl(new URL(n,this.apiBaseUrl),{method:t?.method??"GET",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",...s??{}},body:t?.body!==void 0?JSON.stringify(t.body):void 0,signal:r.signal});if(o.status===204||t?.expectNoContent){if(!o.ok)throw Error(`Cline account request failed with status ${o.status}`);return}let a=await o.text(),m;if(a.trim())m=JSON.parse(a);if(!o.ok){let u=typeof m==="object"&&m!==null&&"error"in m?String(m.error):`Cline account request failed with status ${o.status}`;throw Error(u)}if(typeof m==="object"&&m!==null){let u=m;if(typeof u.success==="boolean"){if(!u.success)throw Error(u.error||"Cline account request failed");if(u.data!==void 0)return u.data}}if(m===void 0||m===null)throw Error("Cline account response payload was empty");return m}finally{clearTimeout(i)}}}function pt(n){return n.action==="clineAccount"}async function _t(n,t){switch(n.operation){case"fetchMe":return t.fetchMe();case"fetchBalance":return t.fetchBalance(n.userId);case"fetchUsageTransactions":return t.fetchUsageTransactions(n.userId);case"fetchPaymentTransactions":return t.fetchPaymentTransactions(n.userId);case"fetchUserOrganizations":return t.fetchUserOrganizations();case"fetchOrganizationBalance":return t.fetchOrganizationBalance(n.organizationId);case"fetchOrganizationUsageTransactions":return t.fetchOrganizationUsageTransactions({organizationId:n.organizationId,memberId:n.memberId});case"switchAccount":return await t.switchAccount(n.organizationId),{updated:!0};default:throw Error(`Unsupported Cline account operation: ${String(n)}`)}}class Fn{executor;constructor(n){this.executor=n}async fetchMe(){return this.request({action:"clineAccount",operation:"fetchMe"})}async fetchBalance(n){return this.request({action:"clineAccount",operation:"fetchBalance",...n?.trim()?{userId:n.trim()}:{}})}async fetchUsageTransactions(n){return this.request({action:"clineAccount",operation:"fetchUsageTransactions",...n?.trim()?{userId:n.trim()}:{}})}async fetchPaymentTransactions(n){return this.request({action:"clineAccount",operation:"fetchPaymentTransactions",...n?.trim()?{userId:n.trim()}:{}})}async fetchUserOrganizations(){return this.request({action:"clineAccount",operation:"fetchUserOrganizations"})}async fetchOrganizationBalance(n){let t=n.trim();if(!t)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:t})}async fetchOrganizationUsageTransactions(n){let t=n.organizationId.trim();if(!t)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:t,...n.memberId?.trim()?{memberId:n.memberId.trim()}:{}})}async switchAccount(n){await this.request({action:"clineAccount",operation:"switchAccount",organizationId:n?.trim()||null})}async request(n){return(await this.executor.runProviderAction(n)).result}}import{z as T}from"zod";var ft=T.object({workspaceRoot:T.string().min(1),cwd:T.string().optional(),provider:T.string().min(1),model:T.string().min(1),mode:T.enum(["act","plan"]).default("act"),apiKey:T.string(),systemPrompt:T.string().optional(),rules:T.string().optional(),maxIterations:T.number().int().positive().optional(),enableTools:T.boolean(),enableSpawn:T.boolean(),enableTeams:T.boolean(),autoApproveTools:T.boolean().optional(),teamName:T.string().min(1),missionStepInterval:T.number().int().positive(),missionTimeIntervalMs:T.number().int().positive()}),ht=T.enum(["idle","starting","running","stopping","completed","cancelled","failed","error"]),At=T.enum(["user","assistant","tool","system","status","error"]),Et=T.object({id:T.string().min(1),sessionId:T.string().nullable(),role:At,content:T.string(),createdAt:T.number().int().nonnegative(),meta:T.object({stream:T.enum(["stdout","stderr"]).optional(),toolName:T.string().optional(),iteration:T.number().int().nonnegative().optional(),agentId:T.string().optional(),conversationId:T.string().optional(),hookEventName:T.string().optional(),inputTokens:T.number().int().nonnegative().optional(),outputTokens:T.number().int().nonnegative().optional()}).optional()}),Ct=T.object({toolCalls:T.number().int().nonnegative(),tokensIn:T.number().int().nonnegative(),tokensOut:T.number().int().nonnegative()}),ge=T.object({sessionId:T.string().nullable(),status:ht,config:ft,messages:T.array(Et),rawTranscript:T.string(),error:T.string().nullable(),summary:Ct});var q={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"},rn=[q.READ_FILES,q.SEARCH_CODEBASE,q.RUN_COMMANDS,q.FETCH_WEB_CONTENT,q.APPLY_PATCH,q.EDITOR,q.SKILLS,q.ASK];import{createTool as Y}from"@clinebot/agents";import{z as A}from"zod";var Te=A.string().describe("The absolute file path of a text file to read content from"),sn=A.object({file_paths:A.array(Te).describe("Array of absolute file paths to get full content from. Prefer this tool over running terminal command to get file content for better performance and reliability.")}),vt=A.union([sn,A.array(A.string()),A.string()]),on=A.object({queries:A.array(A.string()).describe("Array of regex search queries to execute")}),wn=A.string(),an=A.object({commands:A.array(wn).describe("Array of shell commands to execute.")}),Ot=A.union([an,A.array(wn),wn]),Rt=A.object({url:A.string().describe("The URL to fetch"),prompt:A.string().min(2).describe("Analysis prompt for the fetched content")}),mn=A.object({requests:A.array(Rt).describe("Array of the URLs for the web fetch requests")}),un=A.object({command:A.enum(["create","str_replace","insert"]).describe("Editor command to execute: create, str_replace, insert"),path:A.string().min(1).describe("Absolute file path"),file_text:A.string().nullish().describe("Full file content required for 'create' command"),old_str:A.string().nullish().describe("Exact text to replace (must match exactly once) for 'str_replace' command"),new_str:A.string().nullish().describe("Replacement text for 'str_replace' or 'insert' commands"),insert_line:A.number().int().nullish().describe("Optional one-based line index for 'insert' command")}).refine((n)=>n.command!=="create"||n.file_text!=null,{path:["file_text"],message:"file_text is required for command=create"}).refine((n)=>n.command!=="str_replace"||n.old_str!=null,{path:["old_str"],message:"old_str is required for command=str_replace"}).refine((n)=>n.command!=="insert"||n.insert_line!=null,{path:["insert_line"],message:"insert_line is required for command=insert"}).refine((n)=>n.command!=="insert"||n.new_str!=null,{path:["new_str"],message:"new_str is required for command=insert"}),cn=A.object({input:A.string().min(1).describe("The apply_patch text payload, including patch instructions")}),It=A.union([cn,A.string()]),dn=A.object({skill:A.string().min(1).describe('The skill name. E.g., "commit", "review-pr", "pdf", or "ms-office-suite:pdf"'),args:A.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),gn=A.object({question:A.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:A.array(A.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")});function Q(n){if(n instanceof Error)return n.message;return String(n)}function j(n,t,e){return Promise.race([n,new Promise((s,r)=>{setTimeout(()=>r(Error(e)),t)})])}var pe=`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":
1
+ import{createRequire as AD}from"node:module";var qD=Object.create;var{getPrototypeOf:XD,defineProperty:bJ,getOwnPropertyNames:JD}=Object;var QD=Object.prototype.hasOwnProperty;function UD($){return this[$]}var ZD,KD,ZY=($,Y,T)=>{var q=$!=null&&typeof $==="object";if(q){var X=Y?ZD??=new WeakMap:KD??=new WeakMap,J=X.get($);if(J)return J}T=$!=null?qD(XD($)):{};let Q=Y||!$||!$.__esModule?bJ(T,"default",{value:$,enumerable:!0}):T;for(let U of JD($))if(!QD.call(Q,U))bJ(Q,U,{get:UD.bind($,U),enumerable:!0});if(q)X.set($,Q);return Q};var M=($,Y)=>()=>(Y||$((Y={exports:{}}).exports,Y),Y.exports);var s=AD(import.meta.url);var i=M((q7)=>{Object.defineProperty(q7,"__esModule",{value:!0});q7.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH=q7.DEFAULT_MAX_SEND_MESSAGE_LENGTH=q7.Propagate=q7.LogVerbosity=q7.Status=void 0;var $7;(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"})($7||(q7.Status=$7={}));var Y7;(function($){$[$.DEBUG=0]="DEBUG",$[$.INFO=1]="INFO",$[$.ERROR=2]="ERROR",$[$.NONE=3]="NONE"})(Y7||(q7.LogVerbosity=Y7={}));var T7;(function($){$[$.DEADLINE=1]="DEADLINE",$[$.CENSUS_STATS_CONTEXT=2]="CENSUS_STATS_CONTEXT",$[$.CENSUS_TRACING_CONTEXT=4]="CENSUS_TRACING_CONTEXT",$[$.CANCELLATION=8]="CANCELLATION",$[$.DEFAULTS=65535]="DEFAULTS"})(T7||(q7.Propagate=T7={}));q7.DEFAULT_MAX_SEND_MESSAGE_LENGTH=-1;q7.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH=4194304});var m4=M((v_,jz)=>{jz.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 U0=M((U7)=>{var f4,b4,u4,d4;Object.defineProperty(U7,"__esModule",{value:!0});U7.log=U7.setLoggerVerbosity=U7.setLogger=U7.getLogger=void 0;U7.trace=dz;U7.isTracerEnabled=Q7;var z$=i(),vz=s("process"),xz=m4().version,kz={error:($,...Y)=>{console.error("E "+$,...Y)},info:($,...Y)=>{console.error("I "+$,...Y)},debug:($,...Y)=>{console.error("D "+$,...Y)}},c$=kz,MY=z$.LogVerbosity.ERROR,hz=(b4=(f4=process.env.GRPC_NODE_VERBOSITY)!==null&&f4!==void 0?f4:process.env.GRPC_VERBOSITY)!==null&&b4!==void 0?b4:"";switch(hz.toUpperCase()){case"DEBUG":MY=z$.LogVerbosity.DEBUG;break;case"INFO":MY=z$.LogVerbosity.INFO;break;case"ERROR":MY=z$.LogVerbosity.ERROR;break;case"NONE":MY=z$.LogVerbosity.NONE;break;default:}var _z=()=>{return c$};U7.getLogger=_z;var gz=($)=>{c$=$};U7.setLogger=gz;var mz=($)=>{MY=$};U7.setLoggerVerbosity=mz;var fz=($,...Y)=>{let T;if($>=MY){switch($){case z$.LogVerbosity.DEBUG:T=c$.debug;break;case z$.LogVerbosity.INFO:T=c$.info;break;case z$.LogVerbosity.ERROR:T=c$.error;break}if(!T)T=c$.error;if(T)T.bind(c$)(...Y)}};U7.log=fz;var bz=(d4=(u4=process.env.GRPC_NODE_TRACE)!==null&&u4!==void 0?u4:process.env.GRPC_TRACE)!==null&&d4!==void 0?d4:"",c4=new Set,J7=new Set;for(let $ of bz.split(","))if($.startsWith("-"))J7.add($.substring(1));else c4.add($);var uz=c4.has("all");function dz($,Y,T){if(Q7(Y))U7.log($,new Date().toISOString()+" | v"+xz+" "+vz.pid+" | "+Y+" | "+T)}function Q7($){return!J7.has($)&&(uz||c4.has($))}});var x8=M((Z7)=>{Object.defineProperty(Z7,"__esModule",{value:!0});Z7.getErrorMessage=rz;Z7.getErrorCode=az;function rz($){if($ instanceof Error)return $.message;else return String($)}function az($){if(typeof $==="object"&&$!==null&&"code"in $&&typeof $.code==="number")return $.code;else return null}});var P0=M((W7)=>{Object.defineProperty(W7,"__esModule",{value:!0});W7.Metadata=void 0;var tz=U0(),ez=i(),$I=x8(),YI=/^[:0-9a-z_.-]+$/,TI=/^[ -~]*$/;function qI($){return YI.test($)}function XI($){return TI.test($)}function A7($){return $.endsWith("-bin")}function JI($){return!$.startsWith("grpc-")}function k8($){return $.toLowerCase()}function K7($,Y){if(!qI($))throw Error('Metadata key "'+$+'" contains illegal characters');if(Y!==null&&Y!==void 0)if(A7($)){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(!XI(Y))throw Error('Metadata string value "'+Y+'" contains illegal characters')}}class h8{constructor($={}){this.internalRepr=new Map,this.opaqueData=new Map,this.options=$}set($,Y){$=k8($),K7($,Y),this.internalRepr.set($,[Y])}add($,Y){$=k8($),K7($,Y);let T=this.internalRepr.get($);if(T===void 0)this.internalRepr.set($,[Y]);else T.push(Y)}remove($){$=k8($),this.internalRepr.delete($)}get($){return $=k8($),this.internalRepr.get($)||[]}getMap(){let $={};for(let[Y,T]of this.internalRepr)if(T.length>0){let q=T[0];$[Y]=Buffer.isBuffer(q)?Buffer.from(q):q}return $}clone(){let $=new h8(this.options),Y=$.internalRepr;for(let[T,q]of this.internalRepr){let X=q.map((J)=>{if(Buffer.isBuffer(J))return Buffer.from(J);else return J});Y.set(T,X)}return $}merge($){for(let[Y,T]of $.internalRepr){let q=(this.internalRepr.get(Y)||[]).concat(T);this.internalRepr.set(Y,q)}}setOptions($){this.options=$}getOptions(){return this.options}toHttp2Headers(){let $={};for(let[Y,T]of this.internalRepr){if(Y.startsWith(":"))continue;$[Y]=T.map(QI)}return $}toJSON(){let $={};for(let[Y,T]of this.internalRepr)$[Y]=T;return $}setOpaque($,Y){this.opaqueData.set($,Y)}getOpaque($){return this.opaqueData.get($)}static fromHttp2Headers($){let Y=new h8;for(let T of Object.keys($)){if(T.charAt(0)===":")continue;let q=$[T];try{if(A7(T)){if(Array.isArray(q))q.forEach((X)=>{Y.add(T,Buffer.from(X,"base64"))});else if(q!==void 0)if(JI(T))q.split(",").forEach((X)=>{Y.add(T,Buffer.from(X.trim(),"base64"))});else Y.add(T,Buffer.from(q,"base64"))}else if(Array.isArray(q))q.forEach((X)=>{Y.add(T,X)});else if(q!==void 0)Y.add(T,q)}catch(X){let J=`Failed to add metadata entry ${T}: ${q}. ${(0,$I.getErrorMessage)(X)}. For more information see https://github.com/grpc/grpc-node/issues/1173`;(0,tz.log)(ez.LogVerbosity.ERROR,J)}}return Y}}W7.Metadata=h8;var QI=($)=>{return Buffer.isBuffer($)?$.toString("base64"):$}});var g8=M((E7)=>{Object.defineProperty(E7,"__esModule",{value:!0});E7.CallCredentials=void 0;var l4=P0();function UI($){return"getRequestHeaders"in $&&typeof $.getRequestHeaders==="function"}class BY{static createFromMetadataGenerator($){return new n4($)}static createFromGoogleCredential($){return BY.createFromMetadataGenerator((Y,T)=>{let q;if(UI($))q=$.getRequestHeaders(Y.service_url);else q=new Promise((X,J)=>{$.getRequestMetadata(Y.service_url,(Q,U)=>{if(Q){J(Q);return}if(!U){J(Error("Headers not set by metadata plugin"));return}X(U)})});q.then((X)=>{let J=new l4.Metadata;for(let Q of Object.keys(X))J.add(Q,X[Q]);T(null,J)},(X)=>{T(X)})})}static createEmpty(){return new i4}}E7.CallCredentials=BY;class _8 extends BY{constructor($){super();this.creds=$}async generateMetadata($){let Y=new l4.Metadata,T=await Promise.all(this.creds.map((q)=>q.generateMetadata($)));for(let q of T)Y.merge(q);return Y}compose($){return new _8(this.creds.concat([$]))}_equals($){if(this===$)return!0;if($ instanceof _8)return this.creds.every((Y,T)=>Y._equals($.creds[T]));else return!1}}class n4 extends BY{constructor($){super();this.metadataGenerator=$}generateMetadata($){return new Promise((Y,T)=>{this.metadataGenerator($,(q,X)=>{if(X!==void 0)Y(X);else T(q)})})}compose($){return new _8([this,$])}_equals($){if(this===$)return!0;if($ instanceof n4)return this.metadataGenerator===$.metadataGenerator;else return!1}}class i4 extends BY{generateMetadata($){return Promise.resolve(new l4.Metadata)}compose($){return $}_equals($){return $ instanceof i4}}});var a4=M((F7)=>{Object.defineProperty(F7,"__esModule",{value:!0});F7.CIPHER_SUITES=void 0;F7.getDefaultRootsData=KI;var ZI=s("fs");F7.CIPHER_SUITES=process.env.GRPC_SSL_CIPHER_SUITES;var D7=process.env.GRPC_DEFAULT_SSL_ROOTS_FILE_PATH,r4=null;function KI(){if(D7){if(r4===null)r4=ZI.readFileSync(D7);return r4}return null}});var p0=M((z7)=>{Object.defineProperty(z7,"__esModule",{value:!0});z7.parseUri=GI;z7.splitHostPort=EI;z7.combineHostPort=VI;z7.uriToString=DI;var WI=/^(?:([A-Za-z0-9+.-]+):)?(?:\/\/([^/]*)\/)?(.+)$/;function GI($){let Y=WI.exec($);if(Y===null)return null;return{scheme:Y[1],authority:Y[2],path:Y[3]}}var H7=/^\d+$/;function EI($){if($.startsWith("[")){let Y=$.indexOf("]");if(Y===-1)return null;let T=$.substring(1,Y);if(T.indexOf(":")===-1)return null;if($.length>Y+1)if($[Y+1]===":"){let q=$.substring(Y+2);if(H7.test(q))return{host:T,port:+q};else return null}else return null;else return{host:T}}else{let Y=$.split(":");if(Y.length===2)if(H7.test(Y[1]))return{host:Y[0],port:+Y[1]};else return null;else return{host:$}}}function VI($){if($.port===void 0)return $.host;else if($.host.includes(":"))return`[${$.host}]:${$.port}`;else return`${$.host}:${$.port}`}function DI($){let Y="";if($.scheme!==void 0)Y+=$.scheme+":";if($.authority!==void 0)Y+="//"+$.authority+"/";return Y+=$.path,Y}});var B1=M((I7)=>{Object.defineProperty(I7,"__esModule",{value:!0});I7.CHANNEL_ARGS_CONFIG_SELECTOR_KEY=void 0;I7.registerResolver=II;I7.registerDefaultScheme=MI;I7.createResolver=BI;I7.getDefaultAuthority=RI;I7.mapUriDefaultScheme=OI;var s4=p0();I7.CHANNEL_ARGS_CONFIG_SELECTOR_KEY="grpc.internal.config_selector";var RY={},o4=null;function II($,Y){RY[$]=Y}function MI($){o4=$}function BI($,Y,T){if($.scheme!==void 0&&$.scheme in RY)return new RY[$.scheme]($,Y,T);else throw Error(`No resolver could be created for target ${(0,s4.uriToString)($)}`)}function RI($){if($.scheme!==void 0&&$.scheme in RY)return RY[$.scheme].getDefaultAuthority($);else throw Error(`Invalid target ${(0,s4.uriToString)($)}`)}function OI($){if($.scheme===void 0||!($.scheme in RY))if(o4!==null)return{scheme:o4,authority:void 0,path:(0,s4.uriToString)($)};else return null;return $}});var PY=M((P7)=>{Object.defineProperty(P7,"__esModule",{value:!0});P7.ChannelCredentials=void 0;P7.createCertificateProviderChannelCredentials=xI;var wT=s("tls"),b8=g8(),e4=a4(),B7=p0(),yI=B1(),jI=U0(),vI=i();function t4($,Y){if($&&!($ instanceof Buffer))throw TypeError(`${Y}, if provided, must be a Buffer.`)}class OY{compose($){return new f8(this,$)}static createSsl($,Y,T,q){var X;if(t4($,"Root certificate"),t4(Y,"Private key"),t4(T,"Certificate chain"),Y&&!T)throw Error("Private key must be given with accompanying certificate chain");if(!Y&&T)throw Error("Certificate chain must be given with accompanying private key");let J=(0,wT.createSecureContext)({ca:(X=$!==null&&$!==void 0?$:(0,e4.getDefaultRootsData)())!==null&&X!==void 0?X:void 0,key:Y!==null&&Y!==void 0?Y:void 0,cert:T!==null&&T!==void 0?T:void 0,ciphers:e4.CIPHER_SUITES});return new m8(J,q!==null&&q!==void 0?q:{})}static createFromSecureContext($,Y){return new m8($,Y!==null&&Y!==void 0?Y:{})}static createInsecure(){return new $X}}P7.ChannelCredentials=OY;class $X extends OY{constructor(){super()}compose($){throw Error("Cannot compose insecure credentials")}_isSecure(){return!1}_equals($){return $ instanceof $X}_createSecureConnector($,Y,T){return{connect(q){return Promise.resolve({socket:q,secure:!1})},waitForReady:()=>{return Promise.resolve()},getCallCredentials:()=>{return T!==null&&T!==void 0?T:b8.CallCredentials.createEmpty()},destroy(){}}}}function R7($,Y,T,q){var X,J;let Q={secureContext:$},U=T;if("grpc.http_connect_target"in q){let W=(0,B7.parseUri)(q["grpc.http_connect_target"]);if(W)U=W}let Z=(0,yI.getDefaultAuthority)(U),K=(0,B7.splitHostPort)(Z),A=(X=K===null||K===void 0?void 0:K.host)!==null&&X!==void 0?X:Z;if(Q.host=A,Y.checkServerIdentity)Q.checkServerIdentity=Y.checkServerIdentity;if(Y.rejectUnauthorized!==void 0)Q.rejectUnauthorized=Y.rejectUnauthorized;if(Q.ALPNProtocols=["h2"],q["grpc.ssl_target_name_override"]){let W=q["grpc.ssl_target_name_override"],E=(J=Q.checkServerIdentity)!==null&&J!==void 0?J:wT.checkServerIdentity;Q.checkServerIdentity=(D,F)=>{return E(W,F)},Q.servername=W}else Q.servername=A;if(q["grpc-node.tls_enable_trace"])Q.enableTrace=!0;return Q}class O7{constructor($,Y){this.connectionOptions=$,this.callCredentials=Y}connect($){let Y=Object.assign({socket:$},this.connectionOptions);return new Promise((T,q)=>{let X=(0,wT.connect)(Y,()=>{var J;if(((J=this.connectionOptions.rejectUnauthorized)!==null&&J!==void 0?J:!0)&&!X.authorized){q(X.authorizationError);return}T({socket:X,secure:!0})});X.on("error",(J)=>{q(J)})})}waitForReady(){return Promise.resolve()}getCallCredentials(){return this.callCredentials}destroy(){}}class m8 extends OY{constructor($,Y){super();this.secureContext=$,this.verifyOptions=Y}_isSecure(){return!0}_equals($){if(this===$)return!0;if($ instanceof m8)return this.secureContext===$.secureContext&&this.verifyOptions.checkServerIdentity===$.verifyOptions.checkServerIdentity;else return!1}_createSecureConnector($,Y,T){let q=R7(this.secureContext,this.verifyOptions,$,Y);return new O7(q,T!==null&&T!==void 0?T:b8.CallCredentials.createEmpty())}}class LT extends OY{constructor($,Y,T){super();this.caCertificateProvider=$,this.identityCertificateProvider=Y,this.verifyOptions=T,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,T;if(this===$)return!0;if($ instanceof LT)return this.caCertificateProvider===$.caCertificateProvider&&this.identityCertificateProvider===$.identityCertificateProvider&&((Y=this.verifyOptions)===null||Y===void 0?void 0:Y.checkServerIdentity)===((T=$.verifyOptions)===null||T===void 0?void 0:T.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,T){return this.ref(),new LT.SecureConnectorImpl(this,$,Y,T!==null&&T!==void 0?T:b8.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,wT.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:e4.CIPHER_SUITES})}catch(T){return(0,jI.log)(vI.LogVerbosity.ERROR,"Failed to createSecureContext with error "+T.message),null}}}LT.SecureConnectorImpl=class{constructor($,Y,T,q){this.parent=$,this.channelTarget=Y,this.options=T,this.callCredentials=q}connect($){return new Promise((Y,T)=>{let q=this.parent.getLatestSecureContext();if(!q){T(Error("Failed to load credentials"));return}if($.closed)T(Error("Socket closed while loading credentials"));let X=R7(q,this.parent.verifyOptions,this.channelTarget,this.options),J=Object.assign({socket:$},X),Q=()=>{T(Error("Socket closed"))},U=(K)=>{T(K)},Z=(0,wT.connect)(J,()=>{var K;if(Z.removeListener("close",Q),Z.removeListener("error",U),((K=this.parent.verifyOptions.rejectUnauthorized)!==null&&K!==void 0?K:!0)&&!Z.authorized){T(Z.authorizationError);return}Y({socket:Z,secure:!0})});Z.once("close",Q),Z.once("error",U)})}async waitForReady(){await this.parent.getSecureContext()}getCallCredentials(){return this.callCredentials}destroy(){this.parent.unref()}};function xI($,Y,T){return new LT($,Y,T!==null&&T!==void 0?T:{})}class f8 extends OY{constructor($,Y){super();if(this.channelCredentials=$,this.callCredentials=Y,!$._isSecure())throw Error("Cannot compose insecure credentials")}compose($){let Y=this.callCredentials.compose($);return new f8(this.channelCredentials,Y)}_isSecure(){return!0}_equals($){if(this===$)return!0;if($ instanceof f8)return this.channelCredentials._equals($.channelCredentials)&&this.callCredentials._equals($.callCredentials);else return!1}_createSecureConnector($,Y,T){let q=this.callCredentials.compose(T!==null&&T!==void 0?T:b8.CallCredentials.createEmpty());return this.channelCredentials._createSecureConnector($,Y,q)}}});var M$=M((S7)=>{Object.defineProperty(S7,"__esModule",{value:!0});S7.createChildChannelControlHelper=gI;S7.registerLoadBalancerType=mI;S7.registerDefaultLoadBalancerType=fI;S7.createLoadBalancer=bI;S7.isLoadBalancerNameRegistered=uI;S7.parseLoadBalancingConfig=w7;S7.getDefaultConfig=dI;S7.selectLbConfigFromList=cI;var hI=U0(),_I=i();function gI($,Y){var T,q,X,J,Q,U,Z,K,A,W;return{createSubchannel:(q=(T=Y.createSubchannel)===null||T===void 0?void 0:T.bind(Y))!==null&&q!==void 0?q:$.createSubchannel.bind($),updateState:(J=(X=Y.updateState)===null||X===void 0?void 0:X.bind(Y))!==null&&J!==void 0?J:$.updateState.bind($),requestReresolution:(U=(Q=Y.requestReresolution)===null||Q===void 0?void 0:Q.bind(Y))!==null&&U!==void 0?U:$.requestReresolution.bind($),addChannelzChild:(K=(Z=Y.addChannelzChild)===null||Z===void 0?void 0:Z.bind(Y))!==null&&K!==void 0?K:$.addChannelzChild.bind($),removeChannelzChild:(W=(A=Y.removeChannelzChild)===null||A===void 0?void 0:A.bind(Y))!==null&&W!==void 0?W:$.removeChannelzChild.bind($)}}var I$={},ST=null;function mI($,Y,T){I$[$]={LoadBalancer:Y,LoadBalancingConfig:T}}function fI($){ST=$}function bI($,Y){let T=$.getLoadBalancerName();if(T in I$)return new I$[T].LoadBalancer(Y);else return null}function uI($){return $ in I$}function w7($){let Y=Object.keys($);if(Y.length!==1)throw Error("Provided load balancing config has multiple conflicting entries");let T=Y[0];if(T in I$)try{return I$[T].LoadBalancingConfig.createFromJson($[T])}catch(q){throw Error(`${T}: ${q.message}`)}else throw Error(`Unrecognized load balancing config name ${T}`)}function dI(){if(!ST)throw Error("No default load balancer type registered");return new I$[ST].LoadBalancingConfig}function cI($,Y=!1){for(let T of $)try{return w7(T)}catch(q){(0,hI.log)(_I.LogVerbosity.DEBUG,"Config parsing failed with error",q.message);continue}if(Y)if(ST)return new I$[ST].LoadBalancingConfig;else return null;else return null}});var YX=M((j7)=>{Object.defineProperty(j7,"__esModule",{value:!0});j7.validateRetryThrottling=C7;j7.validateServiceConfig=y7;j7.extractAndSelectServiceConfig=UM;var tI=s("os"),u8=i(),d8=/^\d+(\.\d{1,9})?s$/,eI="node";function $M($){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 YM($){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"||!d8.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"||!d8.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(u8.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(u8.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 TM($){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"||!d8.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 T of $.nonFatalStatusCodes)if(typeof T==="number"){if(!Object.values(u8.Status).includes(T))throw Error("Invalid method config hedging policy: nonFatalStatusCodes value not in status code range")}else if(typeof T==="string"){if(!Object.values(u8.Status).includes(T.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 qM($){var Y;let T={name:[]};if(!("name"in $)||!Array.isArray($.name))throw Error("Invalid method config: invalid name array");for(let q of $.name)T.name.push($M(q));if("waitForReady"in $){if(typeof $.waitForReady!=="boolean")throw Error("Invalid method config: invalid waitForReady");T.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");T.timeout=$.timeout}else if(typeof $.timeout==="string"&&d8.test($.timeout)){let q=$.timeout.substring(0,$.timeout.length-1).split(".");T.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");T.maxRequestBytes=$.maxRequestBytes}if("maxResponseBytes"in $){if(typeof $.maxResponseBytes!=="number")throw Error("Invalid method config: invalid maxRequestBytes");T.maxResponseBytes=$.maxResponseBytes}if("retryPolicy"in $)if("hedgingPolicy"in $)throw Error("Invalid method config: retryPolicy and hedgingPolicy cannot both be specified");else T.retryPolicy=YM($.retryPolicy);else if("hedgingPolicy"in $)T.hedgingPolicy=TM($.hedgingPolicy);return T}function C7($){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 XM($){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 y7($){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(XM(q));else throw Error("Invalid service config: invalid loadBalancingConfig");if("methodConfig"in $){if(Array.isArray($.methodConfig))for(let q of $.methodConfig)Y.methodConfig.push(qM(q))}if("retryThrottling"in $)Y.retryThrottling=C7($.retryThrottling);let T=[];for(let q of Y.methodConfig)for(let X of q.name){for(let J of T)if(X.service===J.service&&X.method===J.method)throw Error(`Invalid service config: duplicate name ${X.service}/${X.method}`);T.push(X)}return Y}function JM($){if(!("serviceConfig"in $))throw Error("Invalid service config choice: missing service config");let Y={serviceConfig:y7($.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 T=["clientLanguage","percentage","clientHostname","serviceConfig"];for(let q in $)if(!T.includes(q))throw Error(`Invalid service config choice: unexpected field ${q}`);return Y}function QM($,Y){if(!Array.isArray($))throw Error("Invalid service config list");for(let T of $){let q=JM(T);if(typeof q.percentage==="number"&&Y>q.percentage)continue;if(Array.isArray(q.clientHostname)){let X=!1;for(let J of q.clientHostname)if(J===tI.hostname())X=!0;if(!X)continue}if(Array.isArray(q.clientLanguage)){let X=!1;for(let J of q.clientLanguage)if(J===eI)X=!0;if(!X)continue}return q.serviceConfig}throw Error("No matching service config found")}function UM($,Y){for(let T of $)if(T.length>0&&T[0].startsWith("grpc_config=")){let q=T.join("").substring(12),X=JSON.parse(q);return QM(X,Y)}return null}});var l0=M((x7)=>{Object.defineProperty(x7,"__esModule",{value:!0});x7.ConnectivityState=void 0;var v7;(function($){$[$.IDLE=0]="IDLE",$[$.CONNECTING=1]="CONNECTING",$[$.READY=2]="READY",$[$.TRANSIENT_FAILURE=3]="TRANSIENT_FAILURE",$[$.SHUTDOWN=4]="SHUTDOWN"})(v7||(x7.ConnectivityState=v7={}))});var Y$=M((g7)=>{Object.defineProperty(g7,"__esModule",{value:!0});g7.QueuePicker=g7.UnavailablePicker=g7.PickResultType=void 0;var WM=P0(),GM=i(),c8;(function($){$[$.COMPLETE=0]="COMPLETE",$[$.QUEUE=1]="QUEUE",$[$.TRANSIENT_FAILURE=2]="TRANSIENT_FAILURE",$[$.DROP=3]="DROP"})(c8||(g7.PickResultType=c8={}));class h7{constructor($){this.status=Object.assign({code:GM.Status.UNAVAILABLE,details:"No connection established",metadata:new WM.Metadata},$)}pick($){return{pickResultType:c8.TRANSIENT_FAILURE,subchannel:null,status:this.status,onCallStarted:null,onCallEnded:null}}}g7.UnavailablePicker=h7;class _7{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:c8.QUEUE,subchannel:null,status:null,onCallStarted:null,onCallEnded:null}}}g7.QueuePicker=_7});var LY=M((f7)=>{Object.defineProperty(f7,"__esModule",{value:!0});f7.BackoffTimeout=void 0;var DM=i(),FM=U0(),NM="backoff",HM=1000,zM=1.6,IM=120000,MM=0.2;function BM($,Y){return Math.random()*(Y-$)+$}class p8{constructor($,Y){if(this.callback=$,this.initialDelay=HM,this.multiplier=zM,this.maxDelay=IM,this.jitter=MM,this.running=!1,this.hasRef=!0,this.startTime=new Date,this.endTime=new Date,this.id=p8.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($){FM.trace(DM.LogVerbosity.DEBUG,NM,"{"+this.id+"} "+$)}runTimer($){var Y,T;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)(T=(Y=this.timerId).unref)===null||T===void 0||T.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=$+BM(-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}}f7.BackoffTimeout=p8;p8.nextId=0});var l8=M((d7)=>{Object.defineProperty(d7,"__esModule",{value:!0});d7.ChildLoadBalancerHandler=void 0;var RM=M$(),OM=l0(),PM="child_load_balancer_helper";class u7{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,T){return this.parent.channelControlHelper.createSubchannel(Y,T)}updateState(Y,T,q){var X;if(this.calledByPendingChild()){if(Y===OM.ConnectivityState.CONNECTING)return;(X=this.parent.currentChild)===null||X===void 0||X.destroy(),this.parent.currentChild=this.parent.pendingChild,this.parent.pendingChild=null}else if(!this.calledByCurrentChild())return;this.parent.channelControlHelper.updateState(Y,T,q)}requestReresolution(){var Y;let T=(Y=this.parent.pendingChild)!==null&&Y!==void 0?Y:this.parent.currentChild;if(this.child===T)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,T,q){let X;if(this.currentChild===null||this.latestConfig===null||this.configUpdateRequiresNewPolicyInstance(this.latestConfig,Y)){let J=new this.ChildPolicyHelper(this),Q=(0,RM.createLoadBalancer)(Y,J);if(J.setChild(Q),this.currentChild===null)this.currentChild=Q,X=this.currentChild;else{if(this.pendingChild)this.pendingChild.destroy();this.pendingChild=Q,X=this.pendingChild}}else if(this.pendingChild===null)X=this.currentChild;else X=this.pendingChild;return this.latestConfig=Y,X.updateAddressList($,Y,T,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 PM}}d7.ChildLoadBalancerHandler=u7});var a7=M((i7)=>{Object.defineProperty(i7,"__esModule",{value:!0});i7.ResolvingLoadBalancer=void 0;var LM=M$(),wM=YX(),i0=l0(),p7=B1(),CT=Y$(),SM=LY(),TX=i(),CM=P0(),yM=U0(),jM=i(),vM=p0(),xM=l8(),kM="resolving_load_balancer";function l7($){yM.trace(jM.LogVerbosity.DEBUG,kM,$)}var hM=["SERVICE_AND_METHOD","SERVICE","EMPTY"];function _M($,Y,T,q){for(let X of T.name)switch(q){case"EMPTY":if(!X.service&&!X.method)return!0;break;case"SERVICE":if(X.service===$&&!X.method)return!0;break;case"SERVICE_AND_METHOD":if(X.service===$&&X.method===Y)return!0}return!1}function gM($,Y,T,q){for(let X of T)if(_M($,Y,X,q))return X;return null}function mM($){return{invoke(Y,T){var q,X;let J=Y.split("/").filter((Z)=>Z.length>0),Q=(q=J[0])!==null&&q!==void 0?q:"",U=(X=J[1])!==null&&X!==void 0?X:"";if($&&$.methodConfig)for(let Z of hM){let K=gM(Q,U,$.methodConfig,Z);if(K)return{methodConfig:K,pickInformation:{},status:TX.Status.OK,dynamicFilterFactories:[]}}return{methodConfig:{name:[]},pickInformation:{},status:TX.Status.OK,dynamicFilterFactories:[]}},unref(){}}}class n7{constructor($,Y,T,q,X){if(this.target=$,this.channelControlHelper=Y,this.channelOptions=T,this.onSuccessfulResolution=q,this.onFailedResolution=X,this.latestChildState=i0.ConnectivityState.IDLE,this.latestChildPicker=new CT.QueuePicker(this),this.latestChildErrorMessage=null,this.currentState=i0.ConnectivityState.IDLE,this.previousServiceConfig=null,this.continueResolving=!1,T["grpc.service_config"])this.defaultServiceConfig=(0,wM.validateServiceConfig)(JSON.parse(T["grpc.service_config"]));else this.defaultServiceConfig={loadBalancingConfig:[],methodConfig:[]};this.updateState(i0.ConnectivityState.IDLE,new CT.QueuePicker(this),null),this.childLoadBalancer=new xM.ChildLoadBalancerHandler({createSubchannel:Y.createSubchannel.bind(Y),requestReresolution:()=>{if(this.backoffTimeout.isRunning())l7("requestReresolution delayed by backoff timer until "+this.backoffTimeout.getEndTime().toISOString()),this.continueResolving=!0;else this.updateResolution()},updateState:(Q,U,Z)=>{this.latestChildState=Q,this.latestChildPicker=U,this.latestChildErrorMessage=Z,this.updateState(Q,U,Z)},addChannelzChild:Y.addChannelzChild.bind(Y),removeChannelzChild:Y.removeChannelzChild.bind(Y)}),this.innerResolver=(0,p7.createResolver)($,this.handleResolverResult.bind(this),T);let J={initialDelay:T["grpc.initial_reconnect_backoff_ms"],maxDelay:T["grpc.max_reconnect_backoff_ms"]};this.backoffTimeout=new SM.BackoffTimeout(()=>{if(this.continueResolving)this.updateResolution(),this.continueResolving=!1;else this.updateState(this.latestChildState,this.latestChildPicker,this.latestChildErrorMessage)},J),this.backoffTimeout.unref()}handleResolverResult($,Y,T,q){var X,J;this.backoffTimeout.stop(),this.backoffTimeout.reset();let Q=!0,U=null;if(T===null)U=this.defaultServiceConfig;else if(T.ok)U=T.value;else if(this.previousServiceConfig!==null)U=this.previousServiceConfig;else Q=!1,this.handleResolutionFailure(T.error);if(U!==null){let Z=(X=U===null||U===void 0?void 0:U.loadBalancingConfig)!==null&&X!==void 0?X:[],K=(0,LM.selectLbConfigFromList)(Z,!0);if(K===null)Q=!1,this.handleResolutionFailure({code:TX.Status.UNAVAILABLE,details:"All load balancer options in service config are not compatible",metadata:new CM.Metadata});else Q=this.childLoadBalancer.updateAddressList($,K,Object.assign(Object.assign({},this.channelOptions),Y),q)}if(Q)this.onSuccessfulResolution(U,(J=Y[p7.CHANNEL_ARGS_CONFIG_SELECTOR_KEY])!==null&&J!==void 0?J:mM(U));return Q}updateResolution(){if(this.innerResolver.updateResolution(),this.currentState===i0.ConnectivityState.IDLE)this.updateState(i0.ConnectivityState.CONNECTING,this.latestChildPicker,this.latestChildErrorMessage);this.backoffTimeout.runOnce()}updateState($,Y,T){if(l7((0,vM.uriToString)(this.target)+" "+i0.ConnectivityState[this.currentState]+" -> "+i0.ConnectivityState[$]),$===i0.ConnectivityState.IDLE)Y=new CT.QueuePicker(this,Y);this.currentState=$,this.channelControlHelper.updateState($,Y,T)}handleResolutionFailure($){if(this.latestChildState===i0.ConnectivityState.IDLE)this.updateState(i0.ConnectivityState.TRANSIENT_FAILURE,new CT.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 CT.QueuePicker(this),this.currentState=i0.ConnectivityState.IDLE,this.previousServiceConfig=null,this.continueResolving=!1}getTypeName(){return"resolving_load_balancer"}}i7.ResolvingLoadBalancer=n7});var t7=M((o7)=>{Object.defineProperty(o7,"__esModule",{value:!0});o7.recognizedOptions=void 0;o7.channelOptionsEqual=fM;o7.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 fM($,Y){let T=Object.keys($).sort(),q=Object.keys(Y).sort();if(T.length!==q.length)return!1;for(let X=0;X<T.length;X+=1){if(T[X]!==q[X])return!1;if($[T[X]]!==Y[q[X]])return!1}return!0}});var r0=M((qZ)=>{Object.defineProperty(qZ,"__esModule",{value:!0});qZ.EndpointMap=void 0;qZ.isTcpSubchannelAddress=jT;qZ.subchannelAddressEqual=n8;qZ.subchannelAddressToString=$Z;qZ.stringToSubchannelAddress=dM;qZ.endpointEqual=cM;qZ.endpointToString=pM;qZ.endpointHasAddress=YZ;var e7=s("net");function jT($){return"port"in $}function n8($,Y){if(!$&&!Y)return!0;if(!$||!Y)return!1;if(jT($))return jT(Y)&&$.host===Y.host&&$.port===Y.port;else return!jT(Y)&&$.path===Y.path}function $Z($){if(jT($))if((0,e7.isIPv6)($.host))return"["+$.host+"]:"+$.port;else return $.host+":"+$.port;else return $.path}var uM=443;function dM($,Y){if((0,e7.isIP)($))return{host:$,port:Y!==null&&Y!==void 0?Y:uM};else return{path:$}}function cM($,Y){if($.addresses.length!==Y.addresses.length)return!1;for(let T=0;T<$.addresses.length;T++)if(!n8($.addresses[T],Y.addresses[T]))return!1;return!0}function pM($){return"["+$.addresses.map($Z).join(", ")+"]"}function YZ($,Y){for(let T of $.addresses)if(n8(T,Y))return!0;return!1}function yT($,Y){if($.addresses.length!==Y.addresses.length)return!1;for(let T of $.addresses){let q=!1;for(let X of Y.addresses)if(n8(T,X)){q=!0;break}if(!q)return!1}return!0}class TZ{constructor(){this.map=new Set}get size(){return this.map.size}getForSubchannelAddress($){for(let Y of this.map)if(YZ(Y.key,$))return Y.value;return}deleteMissing($){let Y=[];for(let T of this.map){let q=!1;for(let X of $)if(yT(X,T.key))q=!0;if(!q)Y.push(T.value),this.map.delete(T)}return Y}get($){for(let Y of this.map)if(yT($,Y.key))return Y.value;return}set($,Y){for(let T of this.map)if(yT($,T.key)){T.value=Y;return}this.map.add({key:$,value:Y})}delete($){for(let Y of this.map)if(yT($,Y.key)){this.map.delete(Y);return}}has($){for(let Y of this.map)if(yT($,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]}}qZ.EndpointMap=TZ});var EZ=M((GZ)=>{Object.defineProperty(GZ,"t",{value:!0});class qX{constructor($,Y,T=1){this.i=void 0,this.h=void 0,this.o=void 0,this.u=$,this.l=Y,this.p=T}I(){let $=this,Y=$.o.o===$;if(Y&&$.p===1)$=$.h;else if($.i){$=$.i;while($.h)$=$.h}else{if(Y)return $.o;let T=$.o;while(T.i===$)$=T,T=$.o;$=T}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,T=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=T,T)T.o=this;return Y}g(){let $=this.o,Y=this.i,T=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=T,T)T.o=this;return Y}}class JZ extends qX{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 QZ{constructor($=0){this.iteratorType=$}equals($){return this.T===$.T}}class UZ{constructor(){this.m=0}get length(){return this.m}size(){return this.m}empty(){return this.m===0}}class ZZ extends UZ{}function p$(){throw RangeError("Iterator access denied!")}class KZ extends ZZ{constructor($=function(T,q){if(T<q)return-1;if(T>q)return 1;return 0},Y=!1){super();this.v=void 0,this.A=$,this.enableIndex=Y,this.N=Y?JZ:qX,this.C=new this.N}R($,Y){let T=this.C;while($){let q=this.A($.u,Y);if(q<0)$=$.h;else if(q>0)T=$,$=$.i;else return $}return T}K($,Y){let T=this.C;while($)if(this.A($.u,Y)<=0)$=$.h;else T=$,$=$.i;return T}L($,Y){let T=this.C;while($){let q=this.A($.u,Y);if(q<0)T=$,$=$.h;else if(q>0)$=$.i;else return $}return T}k($,Y){let T=this.C;while($)if(this.A($.u,Y)<0)T=$,$=$.h;else $=$.i;return T}P($){while(!0){let Y=$.o;if(Y===this.C)return;if($.p===1){$.p=0;return}if($===Y.i){let T=Y.h;if(T.p===1)if(T.p=0,Y.p=1,Y===this.v)this.v=Y._();else Y._();else if(T.h&&T.h.p===1){if(T.p=Y.p,Y.p=0,T.h.p=0,Y===this.v)this.v=Y._();else Y._();return}else if(T.i&&T.i.p===1)T.p=1,T.i.p=0,T.g();else T.p=1,$=Y}else{let T=Y.i;if(T.p===1)if(T.p=0,Y.p=1,Y===this.v)this.v=Y.g();else Y.g();else if(T.i&&T.i.p===1){if(T.p=Y.p,Y.p=0,T.i.p=0,Y===this.v)this.v=Y.g();else Y.g();return}else if(T.h&&T.h.p===1)T.p=1,T.h.p=0,T._();else T.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 X=$.l;$.l=Y.l,Y.l=X,$=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 T=Y.o;if(Y===T.i)T.i=void 0;else T.h=void 0;if(this.m-=1,this.v.p=0,this.enableIndex)while(T!==this.C)T.M-=1,T=T.o}U($){let Y=typeof $==="number"?$:void 0,T=typeof $==="function"?$:void 0,q=typeof $>"u"?[]:void 0,X=0,J=this.v,Q=[];while(Q.length||J)if(J)Q.push(J),J=J.i;else{if(J=Q.pop(),X===Y)return J;q&&q.push(J),T&&T(J,X,this),X+=1,J=J.h}return q}j($){while(!0){let Y=$.o;if(Y.p===0)return;let T=Y.o;if(Y===T.i){let q=T.h;if(q&&q.p===1){if(q.p=Y.p=0,T===this.v)return;T.p=1,$=T;continue}else if($===Y.h){if($.p=0,$.i)$.i.o=Y;if($.h)$.h.o=T;if(Y.h=$.i,T.i=$.h,$.i=Y,$.h=T,T===this.v)this.v=$,this.C.o=$;else{let X=T.o;if(X.i===T)X.i=$;else X.h=$}$.o=T.o,Y.o=$,T.o=$,T.p=1}else{if(Y.p=0,T===this.v)this.v=T.g();else T.g();T.p=1;return}}else{let q=T.i;if(q&&q.p===1){if(q.p=Y.p=0,T===this.v)return;T.p=1,$=T;continue}else if($===Y.i){if($.p=0,$.i)$.i.o=T;if($.h)$.h.o=Y;if(T.h=$.i,Y.i=$.h,$.i=T,$.h=Y,T===this.v)this.v=$,this.C.o=$;else{let X=T.o;if(X.i===T)X.i=$;else X.h=$}$.o=T.o,Y.o=$,T.o=$,T.p=1}else{if(Y.p=0,T===this.v)this.v=T._();else T._();T.p=1;return}}if(this.enableIndex)Y.O(),T.O(),$.O();return}}q($,Y,T){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,X=this.C.i,J=this.A(X.u,$);if(J===0)return X.l=Y,this.m;else if(J>0)X.i=new this.N($,Y),X.i.o=X,q=X.i,this.C.i=q;else{let Q=this.C.h,U=this.A(Q.u,$);if(U===0)return Q.l=Y,this.m;else if(U<0)Q.h=new this.N($,Y),Q.h.o=Q,q=Q.h,this.C.h=q;else{if(T!==void 0){let Z=T.T;if(Z!==this.C){let K=this.A(Z.u,$);if(K===0)return Z.l=Y,this.m;else if(K>0){let A=Z.I(),W=this.A(A.u,$);if(W===0)return A.l=Y,this.m;else if(W<0)if(q=new this.N($,Y),A.h===void 0)A.h=q,q.o=A;else Z.i=q,q.o=Z}}}if(q===void 0){q=this.v;while(!0){let Z=this.A(q.u,$);if(Z>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(Z<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 Q=q.o;while(Q!==this.C)Q.M+=1,Q=Q.o}return this.j(q),this.m+=1,this.m}H($,Y){while($){let T=this.A($.u,Y);if(T<0)$=$.h;else if(T>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 T=$.T;if(T===this.C)p$();if(this.m===1)return T.u=Y,!0;let q=T.B().u;if(T===this.C.i){if(this.A(q,Y)>0)return T.u=Y,!0;return!1}let X=T.I().u;if(T===this.C.h){if(this.A(X,Y)<0)return T.u=Y,!0;return!1}if(this.A(X,Y)>=0||this.A(q,Y)<=0)return!1;return T.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)p$();let T=Y.h===void 0;if($.iteratorType===0){if(T)$.next()}else if(!T||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 AZ extends QZ{constructor($,Y,T){super(T);if(this.T=$,this.C=Y,this.iteratorType===0)this.pre=function(){if(this.T===this.C.i)p$();return this.T=this.T.I(),this},this.next=function(){if(this.T===this.C)p$();return this.T=this.T.B(),this};else this.pre=function(){if(this.T===this.C.h)p$();return this.T=this.T.B(),this},this.next=function(){if(this.T===this.C)p$();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 T=0;if($.i)T+=$.i.M;while($!==Y){let q=$.o;if($===q.h){if(T+=1,q.i)T+=q.i.M}$=q}return T}isAccessible(){return this.T!==this.C}}class R1 extends AZ{constructor($,Y,T,q){super($,Y,q);this.container=T}get pointer(){if(this.T===this.C)p$();let $=this;return new Proxy([],{get(Y,T){if(T==="0")return $.T.u;else if(T==="1")return $.T.l;return Y[0]=$.T.u,Y[1]=$.T.l,Y[T]},set(Y,T,q){if(T!=="1")throw TypeError("prop must be 1");return $.T.l=q,!0}})}copy(){return new R1(this.T,this.C,this.container,this.iteratorType)}}class WZ extends KZ{constructor($=[],Y,T){super(Y,T);let q=this;$.forEach(function(X){q.setElement(X[0],X[1])})}begin(){return new R1(this.C.i||this.C,this.C,this)}end(){return new R1(this.C,this.C,this)}rBegin(){return new R1(this.C.h||this.C,this.C,this,1)}rEnd(){return new R1(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 R1(Y,this.C,this)}upperBound($){let Y=this.K(this.v,$);return new R1(Y,this.C,this)}reverseLowerBound($){let Y=this.L(this.v,$);return new R1(Y,this.C,this)}reverseUpperBound($){let Y=this.k(this.v,$);return new R1(Y,this.C,this)}forEach($){this.U(function(Y,T,q){$([Y.u,Y.l],T,q)})}setElement($,Y,T){return this.q($,Y,T)}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 R1(Y,this.C,this)}getElementByKey($){return this.H(this.v,$).l}union($){let Y=this;return $.forEach(function(T){Y.setElement(T[0],T[1])}),this.m}*[Symbol.iterator](){let $=this.m,Y=this.U();for(let T=0;T<$;++T){let q=Y[T];yield[q.u,q.l]}}}GZ.OrderedMap=WZ});var i8=M((DZ)=>{Object.defineProperty(DZ,"__esModule",{value:!0});DZ.registerAdminService=eM;DZ.addAdminServicesToServer=$B;var VZ=[];function eM($,Y){VZ.push({getServiceDefinition:$,getHandlers:Y})}function $B($){for(let{getServiceDefinition:Y,getHandlers:T}of VZ)$.addService(Y(),T())}});var BZ=M((IZ)=>{Object.defineProperty(IZ,"__esModule",{value:!0});IZ.ClientDuplexStreamImpl=IZ.ClientWritableStreamImpl=IZ.ClientReadableStreamImpl=IZ.ClientUnaryCallImpl=void 0;IZ.callErrorFromStatus=XB;var qB=s("events"),XX=s("stream"),vT=i();function XB($,Y){let T=`${$.code} ${vT.Status[$.code]}: ${$.details}`,X=`${Error(T).stack}
2
+ for call at
3
+ ${Y}`;return Object.assign(Error(T),$,{stack:X})}class FZ extends qB.EventEmitter{constructor(){super()}cancel(){var $;($=this.call)===null||$===void 0||$.cancelWithStatus(vT.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}}IZ.ClientUnaryCallImpl=FZ;class NZ extends XX.Readable{constructor($){super({objectMode:!0});this.deserialize=$}cancel(){var $;($=this.call)===null||$===void 0||$.cancelWithStatus(vT.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()}}IZ.ClientReadableStreamImpl=NZ;class HZ extends XX.Writable{constructor($){super({objectMode:!0});this.serialize=$}cancel(){var $;($=this.call)===null||$===void 0||$.cancelWithStatus(vT.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,T){var q;let X={callback:T},J=Number(Y);if(!Number.isNaN(J))X.flags=J;(q=this.call)===null||q===void 0||q.sendMessageWithContext(X,$)}_final($){var Y;(Y=this.call)===null||Y===void 0||Y.halfClose(),$()}}IZ.ClientWritableStreamImpl=HZ;class zZ extends XX.Duplex{constructor($,Y){super({objectMode:!0});this.serialize=$,this.deserialize=Y}cancel(){var $;($=this.call)===null||$===void 0||$.cancelWithStatus(vT.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,T){var q;let X={callback:T},J=Number(Y);if(!Number.isNaN(J))X.flags=J;(q=this.call)===null||q===void 0||q.sendMessageWithContext(X,$)}_final($){var Y;(Y=this.call)===null||Y===void 0||Y.halfClose(),$()}}IZ.ClientDuplexStreamImpl=zZ});var l$=M((OZ)=>{Object.defineProperty(OZ,"__esModule",{value:!0});OZ.InterceptingListenerImpl=void 0;OZ.statusOrFromValue=AB;OZ.statusOrFromError=WB;OZ.isInterceptingListener=GB;var KB=P0();function AB($){return{ok:!0,value:$}}function WB($){var Y;return{ok:!1,error:Object.assign(Object.assign({},$),{metadata:(Y=$.metadata)!==null&&Y!==void 0?Y:new KB.Metadata})}}function GB($){return $.onReceiveMetadata!==void 0&&$.onReceiveMetadata.length===1}class RZ{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)})}}OZ.InterceptingListenerImpl=RZ});var UX=M((kZ)=>{Object.defineProperty(kZ,"__esModule",{value:!0});kZ.InterceptingCall=kZ.RequesterBuilder=kZ.ListenerBuilder=kZ.InterceptorConfigurationError=void 0;kZ.getInterceptingCall=zB;var FB=P0(),LZ=l$(),wZ=i(),SZ=x8();class kT extends Error{constructor($){super($);this.name="InterceptorConfigurationError",Error.captureStackTrace(this,kT)}}kZ.InterceptorConfigurationError=kT;class CZ{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}}}kZ.ListenerBuilder=CZ;class yZ{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}}}kZ.RequesterBuilder=yZ;var JX={onReceiveMetadata:($,Y)=>{Y($)},onReceiveMessage:($,Y)=>{Y($)},onReceiveStatus:($,Y)=>{Y($)}},xT={start:($,Y,T)=>{T($,Y)},sendMessage:($,Y)=>{Y($)},halfClose:($)=>{$()},cancel:($)=>{$()}};class jZ{constructor($,Y){var T,q,X,J;if(this.nextCall=$,this.processingMetadata=!1,this.pendingMessageContext=null,this.processingMessage=!1,this.pendingHalfClose=!1,Y)this.requester={start:(T=Y.start)!==null&&T!==void 0?T:xT.start,sendMessage:(q=Y.sendMessage)!==null&&q!==void 0?q:xT.sendMessage,halfClose:(X=Y.halfClose)!==null&&X!==void 0?X:xT.halfClose,cancel:(J=Y.cancel)!==null&&J!==void 0?J:xT.cancel};else this.requester=xT}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 T,q,X,J,Q,U;let Z={onReceiveMetadata:(q=(T=Y===null||Y===void 0?void 0:Y.onReceiveMetadata)===null||T===void 0?void 0:T.bind(Y))!==null&&q!==void 0?q:(K)=>{},onReceiveMessage:(J=(X=Y===null||Y===void 0?void 0:Y.onReceiveMessage)===null||X===void 0?void 0:X.bind(Y))!==null&&J!==void 0?J:(K)=>{},onReceiveStatus:(U=(Q=Y===null||Y===void 0?void 0:Y.onReceiveStatus)===null||Q===void 0?void 0:Q.bind(Y))!==null&&U!==void 0?U:(K)=>{}};this.processingMetadata=!0,this.requester.start($,Z,(K,A)=>{var W,E,D;this.processingMetadata=!1;let F;if((0,LZ.isInterceptingListener)(A))F=A;else{let H={onReceiveMetadata:(W=A.onReceiveMetadata)!==null&&W!==void 0?W:JX.onReceiveMetadata,onReceiveMessage:(E=A.onReceiveMessage)!==null&&E!==void 0?E:JX.onReceiveMessage,onReceiveStatus:(D=A.onReceiveStatus)!==null&&D!==void 0?D:JX.onReceiveStatus};F=new LZ.InterceptingListenerImpl(H,Z)}this.nextCall.start(K,F),this.processPendingMessage(),this.processPendingHalfClose()})}sendMessageWithContext($,Y){this.processingMessage=!0,this.requester.sendMessage(Y,(T)=>{if(this.processingMessage=!1,this.processingMetadata)this.pendingMessageContext=$,this.pendingMessage=Y;else this.nextCall.sendMessageWithContext($,T),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()}}kZ.InterceptingCall=jZ;function NB($,Y,T){var q,X;let J=(q=T.deadline)!==null&&q!==void 0?q:1/0,Q=T.host,U=(X=T.parent)!==null&&X!==void 0?X:null,Z=T.propagate_flags,K=T.credentials,A=$.createCall(Y,J,Q,U,Z);if(K)A.setCredentials(K);return A}class QX{constructor($,Y){this.call=$,this.methodDefinition=Y}cancelWithStatus($,Y){this.call.cancelWithStatus($,Y)}getPeer(){return this.call.getPeer()}sendMessageWithContext($,Y){let T;try{T=this.methodDefinition.requestSerialize(Y)}catch(q){this.call.cancelWithStatus(wZ.Status.INTERNAL,`Request message serialization failure: ${(0,SZ.getErrorMessage)(q)}`);return}this.call.sendMessageWithContext($,T)}sendMessage($){this.sendMessageWithContext({},$)}start($,Y){let T=null;this.call.start($,{onReceiveMetadata:(q)=>{var X;(X=Y===null||Y===void 0?void 0:Y.onReceiveMetadata)===null||X===void 0||X.call(Y,q)},onReceiveMessage:(q)=>{var X;let J;try{J=this.methodDefinition.responseDeserialize(q)}catch(Q){T={code:wZ.Status.INTERNAL,details:`Response message parsing error: ${(0,SZ.getErrorMessage)(Q)}`,metadata:new FB.Metadata},this.call.cancelWithStatus(T.code,T.details);return}(X=Y===null||Y===void 0?void 0:Y.onReceiveMessage)===null||X===void 0||X.call(Y,J)},onReceiveStatus:(q)=>{var X,J;if(T)(X=Y===null||Y===void 0?void 0:Y.onReceiveStatus)===null||X===void 0||X.call(Y,T);else(J=Y===null||Y===void 0?void 0:Y.onReceiveStatus)===null||J===void 0||J.call(Y,q)}})}startRead(){this.call.startRead()}halfClose(){this.call.halfClose()}getAuthContext(){return this.call.getAuthContext()}}class vZ extends QX{constructor($,Y){super($,Y)}start($,Y){var T,q;let X=!1,J={onReceiveMetadata:(q=(T=Y===null||Y===void 0?void 0:Y.onReceiveMetadata)===null||T===void 0?void 0:T.bind(Y))!==null&&q!==void 0?q:(Q)=>{},onReceiveMessage:(Q)=>{var U;X=!0,(U=Y===null||Y===void 0?void 0:Y.onReceiveMessage)===null||U===void 0||U.call(Y,Q)},onReceiveStatus:(Q)=>{var U,Z;if(!X)(U=Y===null||Y===void 0?void 0:Y.onReceiveMessage)===null||U===void 0||U.call(Y,null);(Z=Y===null||Y===void 0?void 0:Y.onReceiveStatus)===null||Z===void 0||Z.call(Y,Q)}};super.start($,J),this.call.startRead()}}class xZ extends QX{}function HB($,Y,T){let q=NB($,T.path,Y);if(T.responseStream)return new xZ(q,T);else return new vZ(q,T)}function zB($,Y,T,q){if($.clientInterceptors.length>0&&$.clientInterceptorProviders.length>0)throw new kT("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 kT("Both interceptors and interceptor_providers were passed as call options. Only one of these is allowed.");let X=[];if($.callInterceptors.length>0||$.callInterceptorProviders.length>0)X=[].concat($.callInterceptors,$.callInterceptorProviders.map((U)=>U(Y))).filter((U)=>U);else X=[].concat($.clientInterceptors,$.clientInterceptorProviders.map((U)=>U(Y))).filter((U)=>U);let J=Object.assign({},T,{method_definition:Y});return X.reduceRight((U,Z)=>{return(K)=>Z(K,U)},(U)=>HB(q,U,Y))(J)}});var KX=M((gZ)=>{Object.defineProperty(gZ,"__esModule",{value:!0});gZ.Client=void 0;var h1=BZ(),OB=AX(),PB=l0(),B$=i(),wY=P0(),r8=UX(),O1=Symbol(),SY=Symbol(),CY=Symbol(),T$=Symbol();function ZX($){return typeof $==="function"}function yY($){var Y;return((Y=$.stack)===null||Y===void 0?void 0:Y.split(`
4
+ `).slice(1).join(`
5
+ `))||"no stack trace available"}class _Z{constructor($,Y,T={}){var q,X;if(T=Object.assign({},T),this[SY]=(q=T.interceptors)!==null&&q!==void 0?q:[],delete T.interceptors,this[CY]=(X=T.interceptor_providers)!==null&&X!==void 0?X:[],delete T.interceptor_providers,this[SY].length>0&&this[CY].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[T$]=T.callInvocationTransformer,delete T.callInvocationTransformer,T.channelOverride)this[O1]=T.channelOverride;else if(T.channelFactoryOverride){let J=T.channelFactoryOverride;delete T.channelFactoryOverride,this[O1]=J($,Y,T)}else this[O1]=new OB.ChannelImplementation($,Y,T)}close(){this[O1].close()}getChannel(){return this[O1]}waitForReady($,Y){let T=(q)=>{if(q){Y(Error("Failed to connect before the deadline"));return}let X;try{X=this[O1].getConnectivityState(!0)}catch(J){Y(Error("The channel has been closed"));return}if(X===PB.ConnectivityState.READY)Y();else try{this[O1].watchConnectivityState(X,$,T)}catch(J){Y(Error("The channel has been closed"))}};setImmediate(T)}checkOptionalUnaryResponseArguments($,Y,T){if(ZX($))return{metadata:new wY.Metadata,options:{},callback:$};else if(ZX(Y))if($ instanceof wY.Metadata)return{metadata:$,options:{},callback:Y};else return{metadata:new wY.Metadata,options:$,callback:Y};else{if(!($ instanceof wY.Metadata&&Y instanceof Object&&ZX(T)))throw Error("Incorrect arguments passed");return{metadata:$,options:Y,callback:T}}}makeUnaryRequest($,Y,T,q,X,J,Q){var U,Z;let K=this.checkOptionalUnaryResponseArguments(X,J,Q),A={path:$,requestStream:!1,responseStream:!1,requestSerialize:Y,responseDeserialize:T},W={argument:q,metadata:K.metadata,call:new h1.ClientUnaryCallImpl,channel:this[O1],methodDefinition:A,callOptions:K.options,callback:K.callback};if(this[T$])W=this[T$](W);let E=W.call,D={clientInterceptors:this[SY],clientInterceptorProviders:this[CY],callInterceptors:(U=W.callOptions.interceptors)!==null&&U!==void 0?U:[],callInterceptorProviders:(Z=W.callOptions.interceptor_providers)!==null&&Z!==void 0?Z:[]},F=(0,r8.getInterceptingCall)(D,W.methodDefinition,W.callOptions,W.channel);E.call=F;let H=null,V=!1,B=Error();return F.start(W.metadata,{onReceiveMetadata:(S)=>{E.emit("metadata",S)},onReceiveMessage(S){if(H!==null)F.cancelWithStatus(B$.Status.UNIMPLEMENTED,"Too many responses received");H=S},onReceiveStatus(S){if(V)return;if(V=!0,S.code===B$.Status.OK)if(H===null){let v=yY(B);W.callback((0,h1.callErrorFromStatus)({code:B$.Status.UNIMPLEMENTED,details:"No message received",metadata:S.metadata},v))}else W.callback(null,H);else{let v=yY(B);W.callback((0,h1.callErrorFromStatus)(S,v))}B=null,E.emit("status",S)}}),F.sendMessage(q),F.halfClose(),E}makeClientStreamRequest($,Y,T,q,X,J){var Q,U;let Z=this.checkOptionalUnaryResponseArguments(q,X,J),K={path:$,requestStream:!0,responseStream:!1,requestSerialize:Y,responseDeserialize:T},A={metadata:Z.metadata,call:new h1.ClientWritableStreamImpl(Y),channel:this[O1],methodDefinition:K,callOptions:Z.options,callback:Z.callback};if(this[T$])A=this[T$](A);let W=A.call,E={clientInterceptors:this[SY],clientInterceptorProviders:this[CY],callInterceptors:(Q=A.callOptions.interceptors)!==null&&Q!==void 0?Q:[],callInterceptorProviders:(U=A.callOptions.interceptor_providers)!==null&&U!==void 0?U:[]},D=(0,r8.getInterceptingCall)(E,A.methodDefinition,A.callOptions,A.channel);W.call=D;let F=null,H=!1,V=Error();return D.start(A.metadata,{onReceiveMetadata:(B)=>{W.emit("metadata",B)},onReceiveMessage(B){if(F!==null)D.cancelWithStatus(B$.Status.UNIMPLEMENTED,"Too many responses received");F=B,D.startRead()},onReceiveStatus(B){if(H)return;if(H=!0,B.code===B$.Status.OK)if(F===null){let S=yY(V);A.callback((0,h1.callErrorFromStatus)({code:B$.Status.UNIMPLEMENTED,details:"No message received",metadata:B.metadata},S))}else A.callback(null,F);else{let S=yY(V);A.callback((0,h1.callErrorFromStatus)(B,S))}V=null,W.emit("status",B)}}),W}checkMetadataAndOptions($,Y){let T,q;if($ instanceof wY.Metadata)if(T=$,Y)q=Y;else q={};else{if($)q=$;else q={};T=new wY.Metadata}return{metadata:T,options:q}}makeServerStreamRequest($,Y,T,q,X,J){var Q,U;let Z=this.checkMetadataAndOptions(X,J),K={path:$,requestStream:!1,responseStream:!0,requestSerialize:Y,responseDeserialize:T},A={argument:q,metadata:Z.metadata,call:new h1.ClientReadableStreamImpl(T),channel:this[O1],methodDefinition:K,callOptions:Z.options};if(this[T$])A=this[T$](A);let W=A.call,E={clientInterceptors:this[SY],clientInterceptorProviders:this[CY],callInterceptors:(Q=A.callOptions.interceptors)!==null&&Q!==void 0?Q:[],callInterceptorProviders:(U=A.callOptions.interceptor_providers)!==null&&U!==void 0?U:[]},D=(0,r8.getInterceptingCall)(E,A.methodDefinition,A.callOptions,A.channel);W.call=D;let F=!1,H=Error();return D.start(A.metadata,{onReceiveMetadata(V){W.emit("metadata",V)},onReceiveMessage(V){W.push(V)},onReceiveStatus(V){if(F)return;if(F=!0,W.push(null),V.code!==B$.Status.OK){let B=yY(H);W.emit("error",(0,h1.callErrorFromStatus)(V,B))}H=null,W.emit("status",V)}}),D.sendMessage(q),D.halfClose(),W}makeBidiStreamRequest($,Y,T,q,X){var J,Q;let U=this.checkMetadataAndOptions(q,X),Z={path:$,requestStream:!0,responseStream:!0,requestSerialize:Y,responseDeserialize:T},K={metadata:U.metadata,call:new h1.ClientDuplexStreamImpl(Y,T),channel:this[O1],methodDefinition:Z,callOptions:U.options};if(this[T$])K=this[T$](K);let A=K.call,W={clientInterceptors:this[SY],clientInterceptorProviders:this[CY],callInterceptors:(J=K.callOptions.interceptors)!==null&&J!==void 0?J:[],callInterceptorProviders:(Q=K.callOptions.interceptor_providers)!==null&&Q!==void 0?Q:[]},E=(0,r8.getInterceptingCall)(W,K.methodDefinition,K.callOptions,K.channel);A.call=E;let D=!1,F=Error();return E.start(K.metadata,{onReceiveMetadata(H){A.emit("metadata",H)},onReceiveMessage(H){A.push(H)},onReceiveStatus(H){if(D)return;if(D=!0,A.push(null),H.code!==B$.Status.OK){let V=yY(F);A.emit("error",(0,h1.callErrorFromStatus)(H,V))}F=null,A.emit("status",H)}}),A}}gZ.Client=_Z});var a8=M((bZ)=>{Object.defineProperty(bZ,"__esModule",{value:!0});bZ.makeClientConstructor=fZ;bZ.loadPackageDefinition=CB;var hT=KX(),LB={unary:hT.Client.prototype.makeUnaryRequest,server_stream:hT.Client.prototype.makeServerStreamRequest,client_stream:hT.Client.prototype.makeClientStreamRequest,bidi:hT.Client.prototype.makeBidiStreamRequest};function WX($){return["__proto__","prototype","constructor"].includes($)}function fZ($,Y,T){if(!T)T={};class q extends hT.Client{}return Object.keys($).forEach((X)=>{if(WX(X))return;let J=$[X],Q;if(typeof X==="string"&&X.charAt(0)==="$")throw Error("Method names cannot start with $");if(J.requestStream)if(J.responseStream)Q="bidi";else Q="client_stream";else if(J.responseStream)Q="server_stream";else Q="unary";let{requestSerialize:U,responseDeserialize:Z}=J,K=wB(LB[Q],J.path,U,Z);if(q.prototype[X]=K,Object.assign(q.prototype[X],J),J.originalName&&!WX(J.originalName))q.prototype[J.originalName]=q.prototype[X]}),q.service=$,q.serviceName=Y,q}function wB($,Y,T,q){return function(...X){return $.call(this,Y,T,q,...X)}}function SB($){return"format"in $}function CB($){let Y={};for(let T in $)if(Object.prototype.hasOwnProperty.call($,T)){let q=$[T],X=T.split(".");if(X.some((U)=>WX(U)))continue;let J=X[X.length-1],Q=Y;for(let U of X.slice(0,-1)){if(!Q[U])Q[U]={};Q=Q[U]}if(SB(q))Q[J]=q;else Q[J]=fZ(q,J,{})}return Y}});var WK=M((Jg,AK)=>{var vB=1/0,xB="[object Symbol]",kB=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,hB=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,s8="\\ud800-\\udfff",rZ="\\u0300-\\u036f\\ufe20-\\ufe23",aZ="\\u20d0-\\u20f0",oZ="\\u2700-\\u27bf",sZ="a-z\\xdf-\\xf6\\xf8-\\xff",_B="\\xac\\xb1\\xd7\\xf7",gB="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",mB="\\u2000-\\u206f",fB=" \\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",tZ="A-Z\\xc0-\\xd6\\xd8-\\xde",eZ="\\ufe0e\\ufe0f",$K=_B+gB+mB+fB,EX="['’]",bB="["+s8+"]",uZ="["+$K+"]",o8="["+rZ+aZ+"]",YK="\\d+",uB="["+oZ+"]",TK="["+sZ+"]",qK="[^"+s8+$K+YK+oZ+sZ+tZ+"]",GX="\\ud83c[\\udffb-\\udfff]",dB="(?:"+o8+"|"+GX+")",XK="[^"+s8+"]",VX="(?:\\ud83c[\\udde6-\\uddff]){2}",DX="[\\ud800-\\udbff][\\udc00-\\udfff]",jY="["+tZ+"]",JK="\\u200d",dZ="(?:"+TK+"|"+qK+")",cB="(?:"+jY+"|"+qK+")",cZ="(?:"+EX+"(?:d|ll|m|re|s|t|ve))?",pZ="(?:"+EX+"(?:D|LL|M|RE|S|T|VE))?",QK=dB+"?",UK="["+eZ+"]?",pB="(?:"+JK+"(?:"+[XK,VX,DX].join("|")+")"+UK+QK+")*",ZK=UK+QK+pB,lB="(?:"+[uB,VX,DX].join("|")+")"+ZK,nB="(?:"+[XK+o8+"?",o8,VX,DX,bB].join("|")+")",iB=RegExp(EX,"g"),rB=RegExp(o8,"g"),aB=RegExp(GX+"(?="+GX+")|"+nB+ZK,"g"),oB=RegExp([jY+"?"+TK+"+"+cZ+"(?="+[uZ,jY,"$"].join("|")+")",cB+"+"+pZ+"(?="+[uZ,jY+dZ,"$"].join("|")+")",jY+"?"+dZ+"+"+cZ,jY+"+"+pZ,YK,lB].join("|"),"g"),sB=RegExp("["+JK+s8+rZ+aZ+eZ+"]"),tB=/[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,eB={"À":"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"},$R=typeof global=="object"&&global&&global.Object===Object&&global,YR=typeof self=="object"&&self&&self.Object===Object&&self,TR=$R||YR||Function("return this")();function qR($,Y,T,q){var X=-1,J=$?$.length:0;if(q&&J)T=$[++X];while(++X<J)T=Y(T,$[X],X,$);return T}function XR($){return $.split("")}function JR($){return $.match(kB)||[]}function QR($){return function(Y){return $==null?void 0:$[Y]}}var UR=QR(eB);function KK($){return sB.test($)}function ZR($){return tB.test($)}function KR($){return KK($)?AR($):XR($)}function AR($){return $.match(aB)||[]}function WR($){return $.match(oB)||[]}var GR=Object.prototype,ER=GR.toString,lZ=TR.Symbol,nZ=lZ?lZ.prototype:void 0,iZ=nZ?nZ.toString:void 0;function VR($,Y,T){var q=-1,X=$.length;if(Y<0)Y=-Y>X?0:X+Y;if(T=T>X?X:T,T<0)T+=X;X=Y>T?0:T-Y>>>0,Y>>>=0;var J=Array(X);while(++q<X)J[q]=$[q+Y];return J}function DR($){if(typeof $=="string")return $;if(IR($))return iZ?iZ.call($):"";var Y=$+"";return Y=="0"&&1/$==-vB?"-0":Y}function FR($,Y,T){var q=$.length;return T=T===void 0?q:T,!Y&&T>=q?$:VR($,Y,T)}function NR($){return function(Y){Y=t8(Y);var T=KK(Y)?KR(Y):void 0,q=T?T[0]:Y.charAt(0),X=T?FR(T,1).join(""):Y.slice(1);return q[$]()+X}}function HR($){return function(Y){return qR(PR(RR(Y).replace(iB,"")),$,"")}}function zR($){return!!$&&typeof $=="object"}function IR($){return typeof $=="symbol"||zR($)&&ER.call($)==xB}function t8($){return $==null?"":DR($)}var MR=HR(function($,Y,T){return Y=Y.toLowerCase(),$+(T?BR(Y):Y)});function BR($){return OR(t8($).toLowerCase())}function RR($){return $=t8($),$&&$.replace(hB,UR).replace(rB,"")}var OR=NR("toUpperCase");function PR($,Y,T){if($=t8($),Y=T?void 0:Y,Y===void 0)return ZR($)?WR($):JR($);return $.match(Y)||[]}AK.exports=MR});var FX=M((Qg,GK)=>{GK.exports=LR;function LR($,Y){var T=Array(arguments.length-1),q=0,X=2,J=!0;while(X<arguments.length)T[q++]=arguments[X++];return new Promise(function(U,Z){T[q]=function(A){if(J)if(J=!1,A)Z(A);else{var W=Array(arguments.length-1),E=0;while(E<W.length)W[E++]=arguments[E];U.apply(null,W)}};try{$.apply(Y||null,T)}catch(K){if(J)J=!1,Z(K)}})}});var FK=M((DK)=>{var e8=DK;e8.length=function(Y){var T=Y.length;if(!T)return 0;var q=0;while(--T%4>1&&Y.charAt(T)==="=")++q;return Math.ceil(Y.length*3)/4-q};var vY=Array(64),VK=Array(123);for(E1=0;E1<64;)VK[vY[E1]=E1<26?E1+65:E1<52?E1+71:E1<62?E1-4:E1-59|43]=E1++;var E1;e8.encode=function(Y,T,q){var X=null,J=[],Q=0,U=0,Z;while(T<q){var K=Y[T++];switch(U){case 0:J[Q++]=vY[K>>2],Z=(K&3)<<4,U=1;break;case 1:J[Q++]=vY[Z|K>>4],Z=(K&15)<<2,U=2;break;case 2:J[Q++]=vY[Z|K>>6],J[Q++]=vY[K&63],U=0;break}if(Q>8191)(X||(X=[])).push(String.fromCharCode.apply(String,J)),Q=0}if(U){if(J[Q++]=vY[Z],J[Q++]=61,U===1)J[Q++]=61}if(X){if(Q)X.push(String.fromCharCode.apply(String,J.slice(0,Q)));return X.join("")}return String.fromCharCode.apply(String,J.slice(0,Q))};var EK="invalid encoding";e8.decode=function(Y,T,q){var X=q,J=0,Q;for(var U=0;U<Y.length;){var Z=Y.charCodeAt(U++);if(Z===61&&J>1)break;if((Z=VK[Z])===void 0)throw Error(EK);switch(J){case 0:Q=Z,J=1;break;case 1:T[q++]=Q<<2|(Z&48)>>4,Q=Z,J=2;break;case 2:T[q++]=(Q&15)<<4|(Z&60)>>2,Q=Z,J=3;break;case 3:T[q++]=(Q&3)<<6|Z,J=0;break}}if(J===1)throw Error(EK);return q-X};e8.test=function(Y){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(Y)}});var HK=M((Zg,NK)=>{NK.exports=$q;function $q(){this._listeners={}}$q.prototype.on=function(Y,T,q){return(this._listeners[Y]||(this._listeners[Y]=[])).push({fn:T,ctx:q||this}),this};$q.prototype.off=function(Y,T){if(Y===void 0)this._listeners={};else if(T===void 0)this._listeners[Y]=[];else{var q=this._listeners[Y];for(var X=0;X<q.length;)if(q[X].fn===T)q.splice(X,1);else++X}return this};$q.prototype.emit=function(Y){var T=this._listeners[Y];if(T){var q=[],X=1;for(;X<arguments.length;)q.push(arguments[X++]);for(X=0;X<T.length;)T[X].fn.apply(T[X++].ctx,q)}return this}});var PK=M((Kg,OK)=>{OK.exports=zK(zK);function zK($){if(typeof Float32Array<"u")(function(){var Y=new Float32Array([-0]),T=new Uint8Array(Y.buffer),q=T[3]===128;function X(Z,K,A){Y[0]=Z,K[A]=T[0],K[A+1]=T[1],K[A+2]=T[2],K[A+3]=T[3]}function J(Z,K,A){Y[0]=Z,K[A]=T[3],K[A+1]=T[2],K[A+2]=T[1],K[A+3]=T[0]}$.writeFloatLE=q?X:J,$.writeFloatBE=q?J:X;function Q(Z,K){return T[0]=Z[K],T[1]=Z[K+1],T[2]=Z[K+2],T[3]=Z[K+3],Y[0]}function U(Z,K){return T[3]=Z[K],T[2]=Z[K+1],T[1]=Z[K+2],T[0]=Z[K+3],Y[0]}$.readFloatLE=q?Q:U,$.readFloatBE=q?U:Q})();else(function(){function Y(q,X,J,Q){var U=X<0?1:0;if(U)X=-X;if(X===0)q(1/X>0?0:2147483648,J,Q);else if(isNaN(X))q(2143289344,J,Q);else if(X>340282346638528860000000000000000000000)q((U<<31|2139095040)>>>0,J,Q);else if(X<0.000000000000000000000000000000000000011754943508222875)q((U<<31|Math.round(X/0.000000000000000000000000000000000000000000001401298464324817))>>>0,J,Q);else{var Z=Math.floor(Math.log(X)/Math.LN2),K=Math.round(X*Math.pow(2,-Z)*8388608)&8388607;q((U<<31|Z+127<<23|K)>>>0,J,Q)}}$.writeFloatLE=Y.bind(null,IK),$.writeFloatBE=Y.bind(null,MK);function T(q,X,J){var Q=q(X,J),U=(Q>>31)*2+1,Z=Q>>>23&255,K=Q&8388607;return Z===255?K?NaN:U*(1/0):Z===0?U*0.000000000000000000000000000000000000000000001401298464324817*K:U*Math.pow(2,Z-150)*(K+8388608)}$.readFloatLE=T.bind(null,BK),$.readFloatBE=T.bind(null,RK)})();if(typeof Float64Array<"u")(function(){var Y=new Float64Array([-0]),T=new Uint8Array(Y.buffer),q=T[7]===128;function X(Z,K,A){Y[0]=Z,K[A]=T[0],K[A+1]=T[1],K[A+2]=T[2],K[A+3]=T[3],K[A+4]=T[4],K[A+5]=T[5],K[A+6]=T[6],K[A+7]=T[7]}function J(Z,K,A){Y[0]=Z,K[A]=T[7],K[A+1]=T[6],K[A+2]=T[5],K[A+3]=T[4],K[A+4]=T[3],K[A+5]=T[2],K[A+6]=T[1],K[A+7]=T[0]}$.writeDoubleLE=q?X:J,$.writeDoubleBE=q?J:X;function Q(Z,K){return T[0]=Z[K],T[1]=Z[K+1],T[2]=Z[K+2],T[3]=Z[K+3],T[4]=Z[K+4],T[5]=Z[K+5],T[6]=Z[K+6],T[7]=Z[K+7],Y[0]}function U(Z,K){return T[7]=Z[K],T[6]=Z[K+1],T[5]=Z[K+2],T[4]=Z[K+3],T[3]=Z[K+4],T[2]=Z[K+5],T[1]=Z[K+6],T[0]=Z[K+7],Y[0]}$.readDoubleLE=q?Q:U,$.readDoubleBE=q?U:Q})();else(function(){function Y(q,X,J,Q,U,Z){var K=Q<0?1:0;if(K)Q=-Q;if(Q===0)q(0,U,Z+X),q(1/Q>0?0:2147483648,U,Z+J);else if(isNaN(Q))q(0,U,Z+X),q(2146959360,U,Z+J);else if(Q>179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000)q(0,U,Z+X),q((K<<31|2146435072)>>>0,U,Z+J);else{var A;if(Q<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000022250738585072014)A=Q/0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005,q(A>>>0,U,Z+X),q((K<<31|A/4294967296)>>>0,U,Z+J);else{var W=Math.floor(Math.log(Q)/Math.LN2);if(W===1024)W=1023;A=Q*Math.pow(2,-W),q(A*4503599627370496>>>0,U,Z+X),q((K<<31|W+1023<<20|A*1048576&1048575)>>>0,U,Z+J)}}}$.writeDoubleLE=Y.bind(null,IK,0,4),$.writeDoubleBE=Y.bind(null,MK,4,0);function T(q,X,J,Q,U){var Z=q(Q,U+X),K=q(Q,U+J),A=(K>>31)*2+1,W=K>>>20&2047,E=4294967296*(K&1048575)+Z;return W===2047?E?NaN:A*(1/0):W===0?A*0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005*E:A*Math.pow(2,W-1075)*(E+4503599627370496)}$.readDoubleLE=T.bind(null,BK,0,4),$.readDoubleBE=T.bind(null,RK,4,0)})();return $}function IK($,Y,T){Y[T]=$&255,Y[T+1]=$>>>8&255,Y[T+2]=$>>>16&255,Y[T+3]=$>>>24}function MK($,Y,T){Y[T]=$>>>24,Y[T+1]=$>>>16&255,Y[T+2]=$>>>8&255,Y[T+3]=$&255}function BK($,Y){return($[Y]|$[Y+1]<<8|$[Y+2]<<16|$[Y+3]<<24)>>>0}function RK($,Y){return($[Y]<<24|$[Y+1]<<16|$[Y+2]<<8|$[Y+3])>>>0}});var HX=M((LK,NX)=>{NX.exports=wR;function wR(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch($){}return null}});var SK=M((wK)=>{var zX=wK;zX.length=function(Y){var T=0,q=0;for(var X=0;X<Y.length;++X)if(q=Y.charCodeAt(X),q<128)T+=1;else if(q<2048)T+=2;else if((q&64512)===55296&&(Y.charCodeAt(X+1)&64512)===56320)++X,T+=4;else T+=3;return T};zX.read=function(Y,T,q){var X=q-T;if(X<1)return"";var J=null,Q=[],U=0,Z;while(T<q){if(Z=Y[T++],Z<128)Q[U++]=Z;else if(Z>191&&Z<224)Q[U++]=(Z&31)<<6|Y[T++]&63;else if(Z>239&&Z<365)Z=((Z&7)<<18|(Y[T++]&63)<<12|(Y[T++]&63)<<6|Y[T++]&63)-65536,Q[U++]=55296+(Z>>10),Q[U++]=56320+(Z&1023);else Q[U++]=(Z&15)<<12|(Y[T++]&63)<<6|Y[T++]&63;if(U>8191)(J||(J=[])).push(String.fromCharCode.apply(String,Q)),U=0}if(J){if(U)J.push(String.fromCharCode.apply(String,Q.slice(0,U)));return J.join("")}return String.fromCharCode.apply(String,Q.slice(0,U))};zX.write=function(Y,T,q){var X=q,J,Q;for(var U=0;U<Y.length;++U)if(J=Y.charCodeAt(U),J<128)T[q++]=J;else if(J<2048)T[q++]=J>>6|192,T[q++]=J&63|128;else if((J&64512)===55296&&((Q=Y.charCodeAt(U+1))&64512)===56320)J=65536+((J&1023)<<10)+(Q&1023),++U,T[q++]=J>>18|240,T[q++]=J>>12&63|128,T[q++]=J>>6&63|128,T[q++]=J&63|128;else T[q++]=J>>12|224,T[q++]=J>>6&63|128,T[q++]=J&63|128;return q-X}});var yK=M((Wg,CK)=>{CK.exports=SR;function SR($,Y,T){var q=T||8192,X=q>>>1,J=null,Q=q;return function(Z){if(Z<1||Z>X)return $(Z);if(Q+Z>q)J=$(q),Q=0;var K=Y.call(J,Q,Q+=Z);if(Q&7)Q=(Q|7)+1;return K}}});var vK=M((Gg,jK)=>{jK.exports=L0;var _T=_1();function L0($,Y){this.lo=$>>>0,this.hi=Y>>>0}var n$=L0.zero=new L0(0,0);n$.toNumber=function(){return 0};n$.zzEncode=n$.zzDecode=function(){return this};n$.length=function(){return 1};var CR=L0.zeroHash="\x00\x00\x00\x00\x00\x00\x00\x00";L0.fromNumber=function(Y){if(Y===0)return n$;var T=Y<0;if(T)Y=-Y;var q=Y>>>0,X=(Y-q)/4294967296>>>0;if(T){if(X=~X>>>0,q=~q>>>0,++q>4294967295){if(q=0,++X>4294967295)X=0}}return new L0(q,X)};L0.from=function(Y){if(typeof Y==="number")return L0.fromNumber(Y);if(_T.isString(Y))if(_T.Long)Y=_T.Long.fromString(Y);else return L0.fromNumber(parseInt(Y,10));return Y.low||Y.high?new L0(Y.low>>>0,Y.high>>>0):n$};L0.prototype.toNumber=function(Y){if(!Y&&this.hi>>>31){var T=~this.lo+1>>>0,q=~this.hi>>>0;if(!T)q=q+1>>>0;return-(T+q*4294967296)}return this.lo+this.hi*4294967296};L0.prototype.toLong=function(Y){return _T.Long?new _T.Long(this.lo|0,this.hi|0,Boolean(Y)):{low:this.lo|0,high:this.hi|0,unsigned:Boolean(Y)}};var R$=String.prototype.charCodeAt;L0.fromHash=function(Y){if(Y===CR)return n$;return new L0((R$.call(Y,0)|R$.call(Y,1)<<8|R$.call(Y,2)<<16|R$.call(Y,3)<<24)>>>0,(R$.call(Y,4)|R$.call(Y,5)<<8|R$.call(Y,6)<<16|R$.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,T=(this.lo>>>28|this.hi<<4)>>>0,q=this.hi>>>24;return q===0?T===0?Y<16384?Y<128?1:2:Y<2097152?3:4:T<16384?T<128?5:6:T<2097152?7:8:q<128?9:10}});var _1=M((IX)=>{var g=IX;g.asPromise=FX();g.base64=FK();g.EventEmitter=HK();g.float=PK();g.inquire=HX();g.utf8=SK();g.pool=yK();g.LongBits=vK();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||IX;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,T){var q=Y[T];if(q!=null&&Y.hasOwnProperty(T))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,T){var q=g.LongBits.fromHash(Y);if(g.Long)return g.Long.fromBits(q.lo,q.hi,T);return q.toNumber(Boolean(T))};function xK($,Y,T){for(var q=Object.keys(Y),X=0;X<q.length;++X)if($[q[X]]===void 0||!T)$[q[X]]=Y[q[X]];return $}g.merge=xK;g.lcFirst=function(Y){return Y.charAt(0).toLowerCase()+Y.substring(1)};function kK($){function Y(T,q){if(!(this instanceof Y))return new Y(T,q);if(Object.defineProperty(this,"message",{get:function(){return T}}),Error.captureStackTrace)Error.captureStackTrace(this,Y);else Object.defineProperty(this,"stack",{value:Error().stack||""});if(q)xK(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=kK;g.ProtocolError=kK("ProtocolError");g.oneOfGetter=function(Y){var T={};for(var q=0;q<Y.length;++q)T[Y[q]]=1;return function(){for(var X=Object.keys(this),J=X.length-1;J>-1;--J)if(T[X[J]]===1&&this[X[J]]!==void 0&&this[X[J]]!==null)return X[J]}};g.oneOfSetter=function(Y){return function(T){for(var q=0;q<Y.length;++q)if(Y[q]!==T)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(T,q){return new $(T,q)},g._Buffer_allocUnsafe=$.allocUnsafe||function(T){return new $(T)}}});var Tq=M((Vg,mK)=>{mK.exports=$0;var V1=_1(),MX,Yq=V1.LongBits,hK=V1.base64,_K=V1.utf8;function gT($,Y,T){this.fn=$,this.len=Y,this.next=void 0,this.val=T}function RX(){}function yR($){this.head=$.head,this.tail=$.tail,this.len=$.len,this.next=$.states}function $0(){this.len=0,this.head=new gT(RX,0,0),this.tail=this.head,this.states=null}var gK=function(){return V1.Buffer?function(){return($0.create=function(){return new MX})()}:function(){return new $0}};$0.create=gK();$0.alloc=function(Y){return new V1.Array(Y)};if(V1.Array!==Array)$0.alloc=V1.pool($0.alloc,V1.Array.prototype.subarray);$0.prototype._push=function(Y,T,q){return this.tail=this.tail.next=new gT(Y,T,q),this.len+=T,this};function OX($,Y,T){Y[T]=$&255}function jR($,Y,T){while($>127)Y[T++]=$&127|128,$>>>=7;Y[T]=$}function PX($,Y){this.len=$,this.next=void 0,this.val=Y}PX.prototype=Object.create(gT.prototype);PX.prototype.fn=jR;$0.prototype.uint32=function(Y){return this.len+=(this.tail=this.tail.next=new PX((Y=Y>>>0)<128?1:Y<16384?2:Y<2097152?3:Y<268435456?4:5,Y)).len,this};$0.prototype.int32=function(Y){return Y<0?this._push(LX,10,Yq.fromNumber(Y)):this.uint32(Y)};$0.prototype.sint32=function(Y){return this.uint32((Y<<1^Y>>31)>>>0)};function LX($,Y,T){while($.hi)Y[T++]=$.lo&127|128,$.lo=($.lo>>>7|$.hi<<25)>>>0,$.hi>>>=7;while($.lo>127)Y[T++]=$.lo&127|128,$.lo=$.lo>>>7;Y[T++]=$.lo}$0.prototype.uint64=function(Y){var T=Yq.from(Y);return this._push(LX,T.length(),T)};$0.prototype.int64=$0.prototype.uint64;$0.prototype.sint64=function(Y){var T=Yq.from(Y).zzEncode();return this._push(LX,T.length(),T)};$0.prototype.bool=function(Y){return this._push(OX,1,Y?1:0)};function BX($,Y,T){Y[T]=$&255,Y[T+1]=$>>>8&255,Y[T+2]=$>>>16&255,Y[T+3]=$>>>24}$0.prototype.fixed32=function(Y){return this._push(BX,4,Y>>>0)};$0.prototype.sfixed32=$0.prototype.fixed32;$0.prototype.fixed64=function(Y){var T=Yq.from(Y);return this._push(BX,4,T.lo)._push(BX,4,T.hi)};$0.prototype.sfixed64=$0.prototype.fixed64;$0.prototype.float=function(Y){return this._push(V1.float.writeFloatLE,4,Y)};$0.prototype.double=function(Y){return this._push(V1.float.writeDoubleLE,8,Y)};var vR=V1.Array.prototype.set?function(Y,T,q){T.set(Y,q)}:function(Y,T,q){for(var X=0;X<Y.length;++X)T[q+X]=Y[X]};$0.prototype.bytes=function(Y){var T=Y.length>>>0;if(!T)return this._push(OX,1,0);if(V1.isString(Y)){var q=$0.alloc(T=hK.length(Y));hK.decode(Y,q,0),Y=q}return this.uint32(T)._push(vR,T,Y)};$0.prototype.string=function(Y){var T=_K.length(Y);return T?this.uint32(T)._push(_K.write,T,Y):this._push(OX,1,0)};$0.prototype.fork=function(){return this.states=new yR(this),this.head=this.tail=new gT(RX,0,0),this.len=0,this};$0.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 gT(RX,0,0),this.len=0;return this};$0.prototype.ldelim=function(){var Y=this.head,T=this.tail,q=this.len;if(this.reset().uint32(q),q)this.tail.next=Y.next,this.tail=T,this.len+=q;return this};$0.prototype.finish=function(){var Y=this.head.next,T=this.constructor.alloc(this.len),q=0;while(Y)Y.fn(Y.val,T,q),q+=Y.len,Y=Y.next;return T};$0._configure=function($){MX=$,$0.create=gK(),MX._configure()}});var uK=M((Dg,bK)=>{bK.exports=g1;var fK=Tq();(g1.prototype=Object.create(fK.prototype)).constructor=g1;var O$=_1();function g1(){fK.call(this)}g1._configure=function(){g1.alloc=O$._Buffer_allocUnsafe,g1.writeBytesBuffer=O$.Buffer&&O$.Buffer.prototype instanceof Uint8Array&&O$.Buffer.prototype.set.name==="set"?function(Y,T,q){T.set(Y,q)}:function(Y,T,q){if(Y.copy)Y.copy(T,q,0,Y.length);else for(var X=0;X<Y.length;)T[q++]=Y[X++]}};g1.prototype.bytes=function(Y){if(O$.isString(Y))Y=O$._Buffer_from(Y,"base64");var T=Y.length>>>0;if(this.uint32(T),T)this._push(g1.writeBytesBuffer,T,Y);return this};function xR($,Y,T){if($.length<40)O$.utf8.write($,Y,T);else if(Y.utf8Write)Y.utf8Write($,T);else Y.write($,T)}g1.prototype.string=function(Y){var T=O$.Buffer.byteLength(Y);if(this.uint32(T),T)this._push(xR,T,Y);return this};g1._configure()});var Xq=M((Fg,nK)=>{nK.exports=D0;var P1=_1(),SX,pK=P1.LongBits,kR=P1.utf8;function L1($,Y){return RangeError("index out of range: "+$.pos+" + "+(Y||1)+" > "+$.len)}function D0($){this.buf=$,this.pos=0,this.len=$.length}var dK=typeof Uint8Array<"u"?function(Y){if(Y instanceof Uint8Array||Array.isArray(Y))return new D0(Y);throw Error("illegal buffer")}:function(Y){if(Array.isArray(Y))return new D0(Y);throw Error("illegal buffer")},lK=function(){return P1.Buffer?function(T){return(D0.create=function(X){return P1.Buffer.isBuffer(X)?new SX(X):dK(X)})(T)}:dK};D0.create=lK();D0.prototype._slice=P1.Array.prototype.subarray||P1.Array.prototype.slice;D0.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,L1(this,10);return Y}}();D0.prototype.int32=function(){return this.uint32()|0};D0.prototype.sint32=function(){var Y=this.uint32();return Y>>>1^-(Y&1)|0};function wX(){var $=new pK(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 L1(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 L1(this);if($.hi=($.hi|(this.buf[this.pos]&127)<<Y*7+3)>>>0,this.buf[this.pos++]<128)return $}throw Error("invalid varint encoding")}D0.prototype.bool=function(){return this.uint32()!==0};function qq($,Y){return($[Y-4]|$[Y-3]<<8|$[Y-2]<<16|$[Y-1]<<24)>>>0}D0.prototype.fixed32=function(){if(this.pos+4>this.len)throw L1(this,4);return qq(this.buf,this.pos+=4)};D0.prototype.sfixed32=function(){if(this.pos+4>this.len)throw L1(this,4);return qq(this.buf,this.pos+=4)|0};function cK(){if(this.pos+8>this.len)throw L1(this,8);return new pK(qq(this.buf,this.pos+=4),qq(this.buf,this.pos+=4))}D0.prototype.float=function(){if(this.pos+4>this.len)throw L1(this,4);var Y=P1.float.readFloatLE(this.buf,this.pos);return this.pos+=4,Y};D0.prototype.double=function(){if(this.pos+8>this.len)throw L1(this,4);var Y=P1.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,Y};D0.prototype.bytes=function(){var Y=this.uint32(),T=this.pos,q=this.pos+Y;if(q>this.len)throw L1(this,Y);if(this.pos+=Y,Array.isArray(this.buf))return this.buf.slice(T,q);if(T===q){var X=P1.Buffer;return X?X.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,T,q)};D0.prototype.string=function(){var Y=this.bytes();return kR.read(Y,0,Y.length)};D0.prototype.skip=function(Y){if(typeof Y==="number"){if(this.pos+Y>this.len)throw L1(this,Y);this.pos+=Y}else do if(this.pos>=this.len)throw L1(this);while(this.buf[this.pos++]&128);return this};D0.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};D0._configure=function($){SX=$,D0.create=lK(),SX._configure();var Y=P1.Long?"toLong":"toNumber";P1.merge(D0.prototype,{int64:function(){return wX.call(this)[Y](!1)},uint64:function(){return wX.call(this)[Y](!0)},sint64:function(){return wX.call(this).zzDecode()[Y](!1)},fixed64:function(){return cK.call(this)[Y](!0)},sfixed64:function(){return cK.call(this)[Y](!1)}})}});var oK=M((Ng,aK)=>{aK.exports=i$;var rK=Xq();(i$.prototype=Object.create(rK.prototype)).constructor=i$;var iK=_1();function i$($){rK.call(this,$)}i$._configure=function(){if(iK.Buffer)i$.prototype._slice=iK.Buffer.prototype.slice};i$.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))};i$._configure()});var tK=M((Hg,sK)=>{sK.exports=mT;var CX=_1();(mT.prototype=Object.create(CX.EventEmitter.prototype)).constructor=mT;function mT($,Y,T){if(typeof $!=="function")throw TypeError("rpcImpl must be a function");CX.EventEmitter.call(this),this.rpcImpl=$,this.requestDelimited=Boolean(Y),this.responseDelimited=Boolean(T)}mT.prototype.rpcCall=function $(Y,T,q,X,J){if(!X)throw TypeError("request must be specified");var Q=this;if(!J)return CX.asPromise($,Q,Y,T,q,X);if(!Q.rpcImpl){setTimeout(function(){J(Error("already ended"))},0);return}try{return Q.rpcImpl(Y,T[Q.requestDelimited?"encodeDelimited":"encode"](X).finish(),function(Z,K){if(Z)return Q.emit("error",Z,Y),J(Z);if(K===null){Q.end(!0);return}if(!(K instanceof q))try{K=q[Q.responseDelimited?"decodeDelimited":"decode"](K)}catch(A){return Q.emit("error",A,Y),J(A)}return Q.emit("data",K,Y),J(null,K)})}catch(U){Q.emit("error",U,Y),setTimeout(function(){J(U)},0);return}};mT.prototype.end=function(Y){if(this.rpcImpl){if(!Y)this.rpcImpl(null,null,null);this.rpcImpl=null,this.emit("end").off()}return this}});var yX=M((eK)=>{var hR=eK;hR.Service=tK()});var jX=M((Ig,$A)=>{$A.exports={}});var qA=M((TA)=>{var a0=TA;a0.build="minimal";a0.Writer=Tq();a0.BufferWriter=uK();a0.Reader=Xq();a0.BufferReader=oK();a0.util=_1();a0.rpc=yX();a0.roots=jX();a0.configure=YA;function YA(){a0.util._configure(),a0.Writer._configure(a0.BufferWriter),a0.Reader._configure(a0.BufferReader)}YA()});var JA=M((Bg,XA)=>{XA.exports=vX;function vX($,Y){if(typeof $==="string")Y=$,$=void 0;var T=[];function q(J){if(typeof J!=="string"){var Q=X();if(vX.verbose)console.log("codegen: "+Q);if(Q="return "+Q,J){var U=Object.keys(J),Z=Array(U.length+1),K=Array(U.length),A=0;while(A<U.length)Z[A]=U[A],K[A]=J[U[A++]];return Z[A]=Q,Function.apply(null,Z).apply(null,K)}return Function(Q)()}var W=Array(arguments.length-1),E=0;while(E<W.length)W[E]=arguments[++E];if(E=0,J=J.replace(/%([%dfijs])/g,function(F,H){var V=W[E++];switch(H){case"d":case"f":return String(Number(V));case"i":return String(Math.floor(V));case"j":return JSON.stringify(V);case"s":return String(V)}return"%"}),E!==W.length)throw Error("parameter count mismatch");return T.push(J),q}function X(J){return"function "+(J||Y||"")+"("+($&&$.join(",")||"")+`){
6
+ `+T.join(`
7
+ `)+`
8
+ }`}return q.toString=X,q}vX.verbose=!1});var UA=M((Rg,QA)=>{QA.exports=fT;var _R=FX(),gR=HX(),xX=gR("fs");function fT($,Y,T){if(typeof Y==="function")T=Y,Y={};else if(!Y)Y={};if(!T)return _R(fT,this,$,Y);if(!Y.xhr&&xX&&xX.readFile)return xX.readFile($,function(X,J){return X&&typeof XMLHttpRequest<"u"?fT.xhr($,Y,T):X?T(X):T(null,Y.binary?J:J.toString("utf8"))});return fT.xhr($,Y,T)}fT.xhr=function(Y,T,q){var X=new XMLHttpRequest;if(X.onreadystatechange=function(){if(X.readyState!==4)return;if(X.status!==0&&X.status!==200)return q(Error("status "+X.status));if(T.binary){var Q=X.response;if(!Q){Q=[];for(var U=0;U<X.responseText.length;++U)Q.push(X.responseText.charCodeAt(U)&255)}return q(null,typeof Uint8Array<"u"?new Uint8Array(Q):Q)}return q(null,X.responseText)},T.binary){if("overrideMimeType"in X)X.overrideMimeType("text/plain; charset=x-user-defined");X.responseType="arraybuffer"}X.open("GET",Y),X.send()}});var AA=M((KA)=>{var hX=KA,ZA=hX.isAbsolute=function(Y){return/^(?:\/|\w+:)/.test(Y)},kX=hX.normalize=function(Y){Y=Y.replace(/\\/g,"/").replace(/\/{2,}/g,"/");var T=Y.split("/"),q=ZA(Y),X="";if(q)X=T.shift()+"/";for(var J=0;J<T.length;)if(T[J]==="..")if(J>0&&T[J-1]!=="..")T.splice(--J,2);else if(q)T.splice(J,1);else++J;else if(T[J]===".")T.splice(J,1);else++J;return X+T.join("/")};hX.resolve=function(Y,T,q){if(!q)T=kX(T);if(ZA(T))return T;if(!q)Y=kX(Y);return(Y=Y.replace(/(?:\/|^)[^/]+$/,"")).length?kX(Y+"/"+T):T}});var kY=M((Pg,EA)=>{EA.exports=t;var Jq=L$();((t.prototype=Object.create(Jq.prototype)).constructor=t).className="Namespace";var _X=P$(),Qq=w0(),mR=o$(),r$,xY,a$;t.fromJSON=function(Y,T){return new t(Y,T.options).addJSON(T.nested)};function WA($,Y){if(!($&&$.length))return;var T={};for(var q=0;q<$.length;++q)T[$[q].name]=$[q].toJSON(Y);return T}t.arrayToJSON=WA;t.isReservedId=function(Y,T){if(Y){for(var q=0;q<Y.length;++q)if(typeof Y[q]!=="string"&&Y[q][0]<=T&&Y[q][1]>T)return!0}return!1};t.isReservedName=function(Y,T){if(Y){for(var q=0;q<Y.length;++q)if(Y[q]===T)return!0}return!1};function t($,Y){Jq.call(this,$,Y),this.nested=void 0,this._nestedArray=null,this._lookupCache={},this._needsRecursiveFeatureResolution=!0,this._needsRecursiveResolve=!0}function GA($){$._nestedArray=null,$._lookupCache={};var Y=$;while(Y=Y.parent)Y._lookupCache={};return $}Object.defineProperty(t.prototype,"nestedArray",{get:function(){return this._nestedArray||(this._nestedArray=Qq.toArray(this.nested))}});t.prototype.toJSON=function(Y){return Qq.toObject(["options",this.options,"nested",WA(this.nestedArray,Y)])};t.prototype.addJSON=function(Y){var T=this;if(Y)for(var q=Object.keys(Y),X=0,J;X<q.length;++X)J=Y[q[X]],T.add((J.fields!==void 0?r$.fromJSON:J.values!==void 0?a$.fromJSON:J.methods!==void 0?xY.fromJSON:J.id!==void 0?_X.fromJSON:t.fromJSON)(q[X],J));return this};t.prototype.get=function(Y){return this.nested&&this.nested[Y]||null};t.prototype.getEnum=function(Y){if(this.nested&&this.nested[Y]instanceof a$)return this.nested[Y].values;throw Error("no such enum: "+Y)};t.prototype.add=function(Y){if(!(Y instanceof _X&&Y.extend!==void 0||Y instanceof r$||Y instanceof mR||Y instanceof a$||Y instanceof xY||Y instanceof t))throw TypeError("object must be a valid nested object");if(!this.nested)this.nested={};else{var T=this.get(Y.name);if(T)if(T instanceof t&&Y instanceof t&&!(T instanceof r$||T instanceof xY)){var q=T.nestedArray;for(var X=0;X<q.length;++X)Y.add(q[X]);if(this.remove(T),!this.nested)this.nested={};Y.setOptions(T.options,!0)}else throw Error("duplicate name '"+Y.name+"' in "+this)}if(this.nested[Y.name]=Y,!(this instanceof r$||this instanceof xY||this instanceof a$||this instanceof _X)){if(!Y._edition)Y._edition=Y._defaultEdition}this._needsRecursiveFeatureResolution=!0,this._needsRecursiveResolve=!0;var J=this;while(J=J.parent)J._needsRecursiveFeatureResolution=!0,J._needsRecursiveResolve=!0;return Y.onAdd(this),GA(this)};t.prototype.remove=function(Y){if(!(Y instanceof Jq))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),GA(this)};t.prototype.define=function(Y,T){if(Qq.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 X=Y.shift();if(q.nested&&q.nested[X]){if(q=q.nested[X],!(q instanceof t))throw Error("path conflicts with non-namespace objects")}else q.add(q=new t(X))}if(T)q.addJSON(T);return q};t.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;this._resolveFeaturesRecursive(this._edition);var Y=this.nestedArray,T=0;this.resolve();while(T<Y.length)if(Y[T]instanceof t)Y[T++].resolveAll();else Y[T++].resolve();return this._needsRecursiveResolve=!1,this};t.prototype._resolveFeaturesRecursive=function(Y){if(!this._needsRecursiveFeatureResolution)return this;return this._needsRecursiveFeatureResolution=!1,Y=this._edition||Y,Jq.prototype._resolveFeaturesRecursive.call(this,Y),this.nestedArray.forEach((T)=>{T._resolveFeaturesRecursive(Y)}),this};t.prototype.lookup=function(Y,T,q){if(typeof T==="boolean")q=T,T=void 0;else if(T&&!Array.isArray(T))T=[T];if(Qq.isString(Y)&&Y.length){if(Y===".")return this.root;Y=Y.split(".")}else if(!Y.length)return this;var X=Y.join(".");if(Y[0]==="")return this.root.lookup(Y.slice(1),T);var J=this.root._fullyQualifiedObjects&&this.root._fullyQualifiedObjects["."+X];if(J&&(!T||T.indexOf(J.constructor)>-1))return J;if(J=this._lookupImpl(Y,X),J&&(!T||T.indexOf(J.constructor)>-1))return J;if(q)return null;var Q=this;while(Q.parent){if(J=Q.parent._lookupImpl(Y,X),J&&(!T||T.indexOf(J.constructor)>-1))return J;Q=Q.parent}return null};t.prototype._lookupImpl=function(Y,T){if(Object.prototype.hasOwnProperty.call(this._lookupCache,T))return this._lookupCache[T];var q=this.get(Y[0]),X=null;if(q){if(Y.length===1)X=q;else if(q instanceof t)Y=Y.slice(1),X=q._lookupImpl(Y,Y.join("."))}else for(var J=0;J<this.nestedArray.length;++J)if(this._nestedArray[J]instanceof t&&(q=this._nestedArray[J]._lookupImpl(Y,T)))X=q;return this._lookupCache[T]=X,X};t.prototype.lookupType=function(Y){var T=this.lookup(Y,[r$]);if(!T)throw Error("no such type: "+Y);return T};t.prototype.lookupEnum=function(Y){var T=this.lookup(Y,[a$]);if(!T)throw Error("no such Enum '"+Y+"' in "+this);return T};t.prototype.lookupTypeOrEnum=function(Y){var T=this.lookup(Y,[r$,a$]);if(!T)throw Error("no such Type or Enum '"+Y+"' in "+this);return T};t.prototype.lookupService=function(Y){var T=this.lookup(Y,[xY]);if(!T)throw Error("no such Service '"+Y+"' in "+this);return T};t._configure=function($,Y,T){r$=$,xY=Y,a$=T}});var Uq=M((Lg,VA)=>{VA.exports=q$;var gX=P$();((q$.prototype=Object.create(gX.prototype)).constructor=q$).className="MapField";var fR=s$(),bT=w0();function q$($,Y,T,q,X,J){if(gX.call(this,$,Y,q,void 0,void 0,X,J),!bT.isString(T))throw TypeError("keyType must be a string");this.keyType=T,this.resolvedKeyType=null,this.map=!0}q$.fromJSON=function(Y,T){return new q$(Y,T.id,T.keyType,T.type,T.options,T.comment)};q$.prototype.toJSON=function(Y){var T=Y?Boolean(Y.keepComments):!1;return bT.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",T?this.comment:void 0])};q$.prototype.resolve=function(){if(this.resolved)return this;if(fR.mapKey[this.keyType]===void 0)throw Error("invalid key type: "+this.keyType);return gX.prototype.resolve.call(this)};q$.d=function(Y,T,q){if(typeof q==="function")q=bT.decorateType(q).name;else if(q&&typeof q==="object")q=bT.decorateEnum(q).name;return function(J,Q){bT.decorateType(J.constructor).add(new q$(Q,Y,T,q))}}});var Zq=M((wg,DA)=>{DA.exports=t$;var mX=L$();((t$.prototype=Object.create(mX.prototype)).constructor=t$).className="Method";var hY=w0();function t$($,Y,T,q,X,J,Q,U,Z){if(hY.isObject(X))Q=X,X=J=void 0;else if(hY.isObject(J))Q=J,J=void 0;if(!(Y===void 0||hY.isString(Y)))throw TypeError("type must be a string");if(!hY.isString(T))throw TypeError("requestType must be a string");if(!hY.isString(q))throw TypeError("responseType must be a string");mX.call(this,$,Q),this.type=Y||"rpc",this.requestType=T,this.requestStream=X?!0:void 0,this.responseType=q,this.responseStream=J?!0:void 0,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=U,this.parsedOptions=Z}t$.fromJSON=function(Y,T){return new t$(Y,T.type,T.requestType,T.responseType,T.requestStream,T.responseStream,T.options,T.comment,T.parsedOptions)};t$.prototype.toJSON=function(Y){var T=Y?Boolean(Y.keepComments):!1;return hY.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",T?this.comment:void 0,"parsedOptions",this.parsedOptions])};t$.prototype.resolve=function(){if(this.resolved)return this;return this.resolvedRequestType=this.parent.lookupType(this.requestType),this.resolvedResponseType=this.parent.lookupType(this.responseType),mX.prototype.resolve.call(this)}});var Kq=M((Sg,NA)=>{NA.exports=Y1;var X$=kY();((Y1.prototype=Object.create(X$.prototype)).constructor=Y1).className="Service";var fX=Zq(),uT=w0(),bR=yX();function Y1($,Y){X$.call(this,$,Y),this.methods={},this._methodsArray=null}Y1.fromJSON=function(Y,T){var q=new Y1(Y,T.options);if(T.methods)for(var X=Object.keys(T.methods),J=0;J<X.length;++J)q.add(fX.fromJSON(X[J],T.methods[X[J]]));if(T.nested)q.addJSON(T.nested);if(T.edition)q._edition=T.edition;return q.comment=T.comment,q._defaultEdition="proto3",q};Y1.prototype.toJSON=function(Y){var T=X$.prototype.toJSON.call(this,Y),q=Y?Boolean(Y.keepComments):!1;return uT.toObject(["edition",this._editionToJSON(),"options",T&&T.options||void 0,"methods",X$.arrayToJSON(this.methodsArray,Y)||{},"nested",T&&T.nested||void 0,"comment",q?this.comment:void 0])};Object.defineProperty(Y1.prototype,"methodsArray",{get:function(){return this._methodsArray||(this._methodsArray=uT.toArray(this.methods))}});function FA($){return $._methodsArray=null,$}Y1.prototype.get=function(Y){return this.methods[Y]||X$.prototype.get.call(this,Y)};Y1.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;X$.prototype.resolve.call(this);var Y=this.methodsArray;for(var T=0;T<Y.length;++T)Y[T].resolve();return this};Y1.prototype._resolveFeaturesRecursive=function(Y){if(!this._needsRecursiveFeatureResolution)return this;return Y=this._edition||Y,X$.prototype._resolveFeaturesRecursive.call(this,Y),this.methodsArray.forEach((T)=>{T._resolveFeaturesRecursive(Y)}),this};Y1.prototype.add=function(Y){if(this.get(Y.name))throw Error("duplicate name '"+Y.name+"' in "+this);if(Y instanceof fX)return this.methods[Y.name]=Y,Y.parent=this,FA(this);return X$.prototype.add.call(this,Y)};Y1.prototype.remove=function(Y){if(Y instanceof fX){if(this.methods[Y.name]!==Y)throw Error(Y+" is not a member of "+this);return delete this.methods[Y.name],Y.parent=null,FA(this)}return X$.prototype.remove.call(this,Y)};Y1.prototype.create=function(Y,T,q){var X=new bR.Service(Y,T,q);for(var J=0,Q;J<this.methodsArray.length;++J){var U=uT.lcFirst((Q=this._methodsArray[J]).resolve().name).replace(/[^$\w_]/g,"");X[U]=uT.codegen(["r","c"],uT.isReserved(U)?U+"_":U)("return this.rpcCall(m,q,s,r,c)")({m:Q,q:Q.resolvedRequestType.ctor,s:Q.resolvedResponseType.ctor})}return X}});var Aq=M((Cg,HA)=>{HA.exports=m1;var uR=_1();function m1($){if($)for(var Y=Object.keys($),T=0;T<Y.length;++T)this[Y[T]]=$[Y[T]]}m1.create=function(Y){return this.$type.create(Y)};m1.encode=function(Y,T){return this.$type.encode(Y,T)};m1.encodeDelimited=function(Y,T){return this.$type.encodeDelimited(Y,T)};m1.decode=function(Y){return this.$type.decode(Y)};m1.decodeDelimited=function(Y){return this.$type.decodeDelimited(Y)};m1.verify=function(Y){return this.$type.verify(Y)};m1.fromObject=function(Y){return this.$type.fromObject(Y)};m1.toObject=function(Y,T){return this.$type.toObject(Y,T)};m1.prototype.toJSON=function(){return this.$type.toObject(this,uR.toJSONOptions)}});var bX=M((yg,IA)=>{IA.exports=pR;var dR=w1(),J$=s$(),zA=w0();function cR($){return"missing required '"+$.name+"'"}function pR($){var Y=zA.codegen(["r","l","e"],$.name+"$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("var c=l===undefined?r.len:r.pos+l,m=new this.ctor"+($.fieldsArray.filter(function(U){return U.map}).length?",k,value":""))("while(r.pos<c){")("var t=r.uint32()")("if(t===e)")("break")("switch(t>>>3){"),T=0;for(;T<$.fieldsArray.length;++T){var q=$._fieldsArray[T].resolve(),X=q.resolvedType instanceof dR?"int32":q.type,J="m"+zA.safeProp(q.name);if(Y("case %i: {",q.id),q.map){if(Y("if(%s===util.emptyObject)",J)("%s={}",J)("var c2 = r.uint32()+r.pos"),J$.defaults[q.keyType]!==void 0)Y("k=%j",J$.defaults[q.keyType]);else Y("k=null");if(J$.defaults[X]!==void 0)Y("value=%j",J$.defaults[X]);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:"),J$.basic[X]===void 0)Y("value=types[%i].decode(r,r.uint32())",T);else Y("value=r.%s()",X);if(Y("break")("default:")("r.skipType(tag2&7)")("break")("}")("}"),J$.long[q.keyType]!==void 0)Y('%s[typeof k==="object"?util.longToHash(k):k]=value',J);else Y("%s[k]=value",J)}else if(q.repeated){if(Y("if(!(%s&&%s.length))",J,J)("%s=[]",J),J$.packed[X]!==void 0)Y("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos<c2)")("%s.push(r.%s())",J,X)("}else");if(J$.basic[X]===void 0)Y(q.delimited?"%s.push(types[%i].decode(r,undefined,((t&~7)|4)))":"%s.push(types[%i].decode(r,r.uint32()))",J,T);else Y("%s.push(r.%s())",J,X)}else if(J$.basic[X]===void 0)Y(q.delimited?"%s=types[%i].decode(r,undefined,((t&~7)|4))":"%s=types[%i].decode(r,r.uint32())",J,T);else Y("%s=r.%s()",J,X);Y("break")("}")}Y("default:")("r.skipType(t&7)")("break")("}")("}");for(T=0;T<$._fieldsArray.length;++T){var Q=$._fieldsArray[T];if(Q.required)Y("if(!m.hasOwnProperty(%j))",Q.name)("throw util.ProtocolError(%j,{instance:m})",cR(Q))}return Y("return m")}});var cX=M((jg,MA)=>{MA.exports=iR;var lR=w1(),uX=w0();function D1($,Y){return $.name+": "+Y+($.repeated&&Y!=="array"?"[]":$.map&&Y!=="object"?"{k:"+$.keyType+"}":"")+" expected"}function dX($,Y,T,q){if(Y.resolvedType)if(Y.resolvedType instanceof lR){$("switch(%s){",q)("default:")("return%j",D1(Y,"enum value"));for(var X=Object.keys(Y.resolvedType.values),J=0;J<X.length;++J)$("case %i:",Y.resolvedType.values[X[J]]);$("break")("}")}else $("{")("var e=types[%i].verify(%s);",T,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",D1(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",D1(Y,"integer|Long"));break;case"float":case"double":$('if(typeof %s!=="number")',q)("return%j",D1(Y,"number"));break;case"bool":$('if(typeof %s!=="boolean")',q)("return%j",D1(Y,"boolean"));break;case"string":$("if(!util.isString(%s))",q)("return%j",D1(Y,"string"));break;case"bytes":$('if(!(%s&&typeof %s.length==="number"||util.isString(%s)))',q,q,q)("return%j",D1(Y,"buffer"));break}return $}function nR($,Y,T){switch(Y.keyType){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":$("if(!util.key32Re.test(%s))",T)("return%j",D1(Y,"integer key"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":$("if(!util.key64Re.test(%s))",T)("return%j",D1(Y,"integer|Long key"));break;case"bool":$("if(!util.key2Re.test(%s))",T)("return%j",D1(Y,"boolean key"));break}return $}function iR($){var Y=uX.codegen(["m"],$.name+"$verify")('if(typeof m!=="object"||m===null)')("return%j","object expected"),T=$.oneofsArray,q={};if(T.length)Y("var p={}");for(var X=0;X<$.fieldsArray.length;++X){var J=$._fieldsArray[X].resolve(),Q="m"+uX.safeProp(J.name);if(J.optional)Y("if(%s!=null&&m.hasOwnProperty(%j)){",Q,J.name);if(J.map)Y("if(!util.isObject(%s))",Q)("return%j",D1(J,"object"))("var k=Object.keys(%s)",Q)("for(var i=0;i<k.length;++i){"),nR(Y,J,"k[i]"),dX(Y,J,X,Q+"[k[i]]")("}");else if(J.repeated)Y("if(!Array.isArray(%s))",Q)("return%j",D1(J,"array"))("for(var i=0;i<%s.length;++i){",Q),dX(Y,J,X,Q+"[i]")("}");else{if(J.partOf){var U=uX.safeProp(J.partOf.name);if(q[J.partOf.name]===1)Y("if(p%s===1)",U)("return%j",J.partOf.name+": multiple values");q[J.partOf.name]=1,Y("p%s=1",U)}dX(Y,J,X,Q)}if(J.optional)Y("}")}return Y("return null")}});var nX=M((RA)=>{var BA=RA,dT=w1(),f1=w0();function pX($,Y,T,q){var X=!1;if(Y.resolvedType)if(Y.resolvedType instanceof dT){$("switch(d%s){",q);for(var J=Y.resolvedType.values,Q=Object.keys(J),U=0;U<Q.length;++U){if(J[Q[U]]===Y.typeDefault&&!X){if($("default:")('if(typeof(d%s)==="number"){m%s=d%s;break}',q,q,q),!Y.repeated)$("break");X=!0}$("case%j:",Q[U])("case %i:",J[Q[U]])("m%s=%j",q,J[Q[U]])("break")}$("}")}else $('if(typeof d%s!=="object")',q)("throw TypeError(%j)",Y.fullName+": object expected")("m%s=types[%i].fromObject(d%s)",q,T,q);else{var Z=!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":Z=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":$("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",q,q,Z)('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,Z?"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 $}BA.fromObject=function(Y){var T=Y.fieldsArray,q=f1.codegen(["d"],Y.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!T.length)return q("return new this.ctor");q("var m=new this.ctor");for(var X=0;X<T.length;++X){var J=T[X].resolve(),Q=f1.safeProp(J.name);if(J.map)q("if(d%s){",Q)('if(typeof d%s!=="object")',Q)("throw TypeError(%j)",J.fullName+": object expected")("m%s={}",Q)("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){",Q),pX(q,J,X,Q+"[ks[i]]")("}")("}");else if(J.repeated)q("if(d%s){",Q)("if(!Array.isArray(d%s))",Q)("throw TypeError(%j)",J.fullName+": array expected")("m%s=[]",Q)("for(var i=0;i<d%s.length;++i){",Q),pX(q,J,X,Q+"[i]")("}")("}");else{if(!(J.resolvedType instanceof dT))q("if(d%s!=null){",Q);if(pX(q,J,X,Q),!(J.resolvedType instanceof dT))q("}")}}return q("return m")};function lX($,Y,T,q){if(Y.resolvedType)if(Y.resolvedType instanceof dT)$("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",q,T,q,q,T,q,q);else $("d%s=types[%i].toObject(m%s,o)",q,T,q);else{var X=!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":X=!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,X?"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 $}BA.toObject=function(Y){var T=Y.fieldsArray.slice().sort(f1.compareFieldsById);if(!T.length)return f1.codegen()("return {}");var q=f1.codegen(["m","o"],Y.name+"$toObject")("if(!o)")("o={}")("var d={}"),X=[],J=[],Q=[],U=0;for(;U<T.length;++U)if(!T[U].partOf)(T[U].resolve().repeated?X:T[U].map?J:Q).push(T[U]);if(X.length){q("if(o.arrays||o.defaults){");for(U=0;U<X.length;++U)q("d%s=[]",f1.safeProp(X[U].name));q("}")}if(J.length){q("if(o.objects||o.defaults){");for(U=0;U<J.length;++U)q("d%s={}",f1.safeProp(J[U].name));q("}")}if(Q.length){q("if(o.defaults){");for(U=0;U<Q.length;++U){var Z=Q[U],K=f1.safeProp(Z.name);if(Z.resolvedType instanceof dT)q("d%s=o.enums===String?%j:%j",K,Z.resolvedType.valuesById[Z.typeDefault],Z.typeDefault);else if(Z.long)q("if(util.Long){")("var n=new util.Long(%i,%i,%j)",Z.typeDefault.low,Z.typeDefault.high,Z.typeDefault.unsigned)("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n",K)("}else")("d%s=o.longs===String?%j:%i",K,Z.typeDefault.toString(),Z.typeDefault.toNumber());else if(Z.bytes){var A="["+Array.prototype.slice.call(Z.typeDefault).join(",")+"]";q("if(o.bytes===String)d%s=%j",K,String.fromCharCode.apply(String,Z.typeDefault))("else{")("d%s=%s",K,A)("if(o.bytes!==Array)d%s=util.newBuffer(d%s)",K,K)("}")}else q("d%s=%j",K,Z.typeDefault)}q("}")}var W=!1;for(U=0;U<T.length;++U){var Z=T[U],E=Y._fieldsArray.indexOf(Z),K=f1.safeProp(Z.name);if(Z.map){if(!W)W=!0,q("var ks2");q("if(m%s&&(ks2=Object.keys(m%s)).length){",K,K)("d%s={}",K)("for(var j=0;j<ks2.length;++j){"),lX(q,Z,E,K+"[ks2[j]]")("}")}else if(Z.repeated)q("if(m%s&&m%s.length){",K,K)("d%s=[]",K)("for(var j=0;j<m%s.length;++j){",K),lX(q,Z,E,K+"[j]")("}");else if(q("if(m%s!=null&&m.hasOwnProperty(%j)){",K,Z.name),lX(q,Z,E,K),Z.partOf)q("if(o.oneofs)")("d%s=%j",f1.safeProp(Z.partOf.name),Z.name);q("}")}return q("return d")}});var iX=M((OA)=>{var rR=OA,aR=Aq();rR[".google.protobuf.Any"]={fromObject:function($){if($&&$["@type"]){var Y=$["@type"].substring($["@type"].lastIndexOf("/")+1),T=this.lookup(Y);if(T){var q=$["@type"].charAt(0)==="."?$["@type"].slice(1):$["@type"];if(q.indexOf("/")===-1)q="/"+q;return this.create({type_url:q,value:T.encode(T.fromObject($)).finish()})}}return this.fromObject($)},toObject:function($,Y){var T="type.googleapis.com/",q="",X="";if(Y&&Y.json&&$.type_url&&$.value){X=$.type_url.substring($.type_url.lastIndexOf("/")+1),q=$.type_url.substring(0,$.type_url.lastIndexOf("/")+1);var J=this.lookup(X);if(J)$=J.decode($.value)}if(!($ instanceof this.ctor)&&$ instanceof aR){var Q=$.$type.toObject($,Y),U=$.$type.fullName[0]==="."?$.$type.fullName.slice(1):$.$type.fullName;if(q==="")q=T;return X=q+U,Q["@type"]=X,Q}return this.toObject($,Y)}}});var Eq=M((kg,LA)=>{LA.exports=Z0;var F1=kY();((Z0.prototype=Object.create(F1.prototype)).constructor=Z0).className="Type";var oR=w1(),oX=o$(),Wq=P$(),sR=Uq(),tR=Kq(),rX=Aq(),aX=Xq(),eR=Tq(),m0=w0(),$2=sX(),Y2=bX(),T2=cX(),PA=nX(),q2=iX();function Z0($,Y){F1.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(Z0.prototype,{fieldsById:{get:function(){if(this._fieldsById)return this._fieldsById;this._fieldsById={};for(var $=Object.keys(this.fields),Y=0;Y<$.length;++Y){var T=this.fields[$[Y]],q=T.id;if(this._fieldsById[q])throw Error("duplicate id "+q+" in "+this);this._fieldsById[q]=T}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=Z0.generateConstructor(this)())},set:function($){var Y=$.prototype;if(!(Y instanceof rX))($.prototype=new rX).constructor=$,m0.merge($.prototype,Y);$.$type=$.prototype.$type=this,m0.merge($,rX,!0),this._ctor=$;var T=0;for(;T<this.fieldsArray.length;++T)this._fieldsArray[T].resolve();var q={};for(T=0;T<this.oneofsArray.length;++T)q[this._oneofsArray[T].resolve().name]={get:m0.oneOfGetter(this._oneofsArray[T].oneof),set:m0.oneOfSetter(this._oneofsArray[T].oneof)};if(T)Object.defineProperties($.prototype,q)}}});Z0.generateConstructor=function(Y){var T=m0.codegen(["p"],Y.name);for(var q=0,X;q<Y.fieldsArray.length;++q)if((X=Y._fieldsArray[q]).map)T("this%s={}",m0.safeProp(X.name));else if(X.repeated)T("this%s=[]",m0.safeProp(X.name));return T("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 Gq($){return $._fieldsById=$._fieldsArray=$._oneofsArray=null,delete $.encode,delete $.decode,delete $.verify,$}Z0.fromJSON=function(Y,T){var q=new Z0(Y,T.options);q.extensions=T.extensions,q.reserved=T.reserved;var X=Object.keys(T.fields),J=0;for(;J<X.length;++J)q.add((typeof T.fields[X[J]].keyType<"u"?sR.fromJSON:Wq.fromJSON)(X[J],T.fields[X[J]]));if(T.oneofs)for(X=Object.keys(T.oneofs),J=0;J<X.length;++J)q.add(oX.fromJSON(X[J],T.oneofs[X[J]]));if(T.nested)for(X=Object.keys(T.nested),J=0;J<X.length;++J){var Q=T.nested[X[J]];q.add((Q.id!==void 0?Wq.fromJSON:Q.fields!==void 0?Z0.fromJSON:Q.values!==void 0?oR.fromJSON:Q.methods!==void 0?tR.fromJSON:F1.fromJSON)(X[J],Q))}if(T.extensions&&T.extensions.length)q.extensions=T.extensions;if(T.reserved&&T.reserved.length)q.reserved=T.reserved;if(T.group)q.group=!0;if(T.comment)q.comment=T.comment;if(T.edition)q._edition=T.edition;return q._defaultEdition="proto3",q};Z0.prototype.toJSON=function(Y){var T=F1.prototype.toJSON.call(this,Y),q=Y?Boolean(Y.keepComments):!1;return m0.toObject(["edition",this._editionToJSON(),"options",T&&T.options||void 0,"oneofs",F1.arrayToJSON(this.oneofsArray,Y),"fields",F1.arrayToJSON(this.fieldsArray.filter(function(X){return!X.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",T&&T.nested||void 0,"comment",q?this.comment:void 0])};Z0.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;F1.prototype.resolveAll.call(this);var Y=this.oneofsArray;q=0;while(q<Y.length)Y[q++].resolve();var T=this.fieldsArray,q=0;while(q<T.length)T[q++].resolve();return this};Z0.prototype._resolveFeaturesRecursive=function(Y){if(!this._needsRecursiveFeatureResolution)return this;return Y=this._edition||Y,F1.prototype._resolveFeaturesRecursive.call(this,Y),this.oneofsArray.forEach((T)=>{T._resolveFeatures(Y)}),this.fieldsArray.forEach((T)=>{T._resolveFeatures(Y)}),this};Z0.prototype.get=function(Y){return this.fields[Y]||this.oneofs&&this.oneofs[Y]||this.nested&&this.nested[Y]||null};Z0.prototype.add=function(Y){if(this.get(Y.name))throw Error("duplicate name '"+Y.name+"' in "+this);if(Y instanceof Wq&&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),Gq(this)}if(Y instanceof oX){if(!this.oneofs)this.oneofs={};return this.oneofs[Y.name]=Y,Y.onAdd(this),Gq(this)}return F1.prototype.add.call(this,Y)};Z0.prototype.remove=function(Y){if(Y instanceof Wq&&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),Gq(this)}if(Y instanceof oX){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),Gq(this)}return F1.prototype.remove.call(this,Y)};Z0.prototype.isReservedId=function(Y){return F1.isReservedId(this.reserved,Y)};Z0.prototype.isReservedName=function(Y){return F1.isReservedName(this.reserved,Y)};Z0.prototype.create=function(Y){return new this.ctor(Y)};Z0.prototype.setup=function(){var Y=this.fullName,T=[];for(var q=0;q<this.fieldsArray.length;++q)T.push(this._fieldsArray[q].resolve().resolvedType);this.encode=$2(this)({Writer:eR,types:T,util:m0}),this.decode=Y2(this)({Reader:aX,types:T,util:m0}),this.verify=T2(this)({types:T,util:m0}),this.fromObject=PA.fromObject(this)({types:T,util:m0}),this.toObject=PA.toObject(this)({types:T,util:m0});var X=q2[Y];if(X){var J=Object.create(this);J.fromObject=this.fromObject,this.fromObject=X.fromObject.bind(J),J.toObject=this.toObject,this.toObject=X.toObject.bind(J)}return this};Z0.prototype.encode=function(Y,T){return this.setup().encode(Y,T)};Z0.prototype.encodeDelimited=function(Y,T){return this.encode(Y,T&&T.len?T.fork():T).ldelim()};Z0.prototype.decode=function(Y,T){return this.setup().decode(Y,T)};Z0.prototype.decodeDelimited=function(Y){if(!(Y instanceof aX))Y=aX.create(Y);return this.decode(Y,Y.uint32())};Z0.prototype.verify=function(Y){return this.setup().verify(Y)};Z0.prototype.fromObject=function(Y){return this.setup().fromObject(Y)};Z0.prototype.toObject=function(Y,T){return this.setup().toObject(Y,T)};Z0.d=function(Y){return function(q){m0.decorateType(q,Y)}}});var Nq=M((hg,CA)=>{CA.exports=T1;var Fq=kY();((T1.prototype=Object.create(Fq.prototype)).constructor=T1).className="Root";var Vq=P$(),tX=w1(),X2=o$(),w$=w0(),eX,$5,cT;function T1($){Fq.call(this,"",$),this.deferred=[],this.files=[],this._edition="proto2",this._fullyQualifiedObjects={}}T1.fromJSON=function(Y,T){if(!T)T=new T1;if(Y.options)T.setOptions(Y.options);return T.addJSON(Y.nested).resolveAll()};T1.prototype.resolvePath=w$.path.resolve;T1.prototype.fetch=w$.fetch;function SA(){}T1.prototype.load=function $(Y,T,q){if(typeof T==="function")q=T,T=void 0;var X=this;if(!q)return w$.asPromise($,X,Y,T);var J=q===SA;function Q(D,F){if(!q)return;if(J)throw D;if(F)F.resolveAll();var H=q;q=null,H(D,F)}function U(D){var F=D.lastIndexOf("google/protobuf/");if(F>-1){var H=D.substring(F);if(H in cT)return H}return null}function Z(D,F){try{if(w$.isString(F)&&F.charAt(0)==="{")F=JSON.parse(F);if(!w$.isString(F))X.setOptions(F.options).addJSON(F.nested);else{$5.filename=D;var H=$5(F,X,T),V,B=0;if(H.imports){for(;B<H.imports.length;++B)if(V=U(H.imports[B])||X.resolvePath(D,H.imports[B]))K(V)}if(H.weakImports){for(B=0;B<H.weakImports.length;++B)if(V=U(H.weakImports[B])||X.resolvePath(D,H.weakImports[B]))K(V,!0)}}}catch(S){Q(S)}if(!J&&!A)Q(null,X)}function K(D,F){if(D=U(D)||D,X.files.indexOf(D)>-1)return;if(X.files.push(D),D in cT){if(J)Z(D,cT[D]);else++A,setTimeout(function(){--A,Z(D,cT[D])});return}if(J){var H;try{H=w$.fs.readFileSync(D).toString("utf8")}catch(V){if(!F)Q(V);return}Z(D,H)}else++A,X.fetch(D,function(V,B){if(--A,!q)return;if(V){if(!F)Q(V);else if(!A)Q(null,X);return}Z(D,B)})}var A=0;if(w$.isString(Y))Y=[Y];for(var W=0,E;W<Y.length;++W)if(E=X.resolvePath("",Y[W]))K(E);if(J)return X.resolveAll(),X;if(!A)Q(null,X);return X};T1.prototype.loadSync=function(Y,T){if(!w$.isNode)throw Error("not supported");return this.load(Y,T,SA)};T1.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 Fq.prototype.resolveAll.call(this)};var Dq=/^[A-Z]/;function wA($,Y){var T=Y.parent.lookup(Y.extend);if(T){var q=new Vq(Y.fullName,Y.id,Y.type,Y.rule,void 0,Y.options);if(T.get(q.name))return!0;return q.declaringField=Y,Y.extensionField=q,T.add(q),!0}return!1}T1.prototype._handleAdd=function(Y){if(Y instanceof Vq){if(Y.extend!==void 0&&!Y.extensionField){if(!wA(this,Y))this.deferred.push(Y)}}else if(Y instanceof tX){if(Dq.test(Y.name))Y.parent[Y.name]=Y.values}else if(!(Y instanceof X2)){if(Y instanceof eX)for(var T=0;T<this.deferred.length;)if(wA(this,this.deferred[T]))this.deferred.splice(T,1);else++T;for(var q=0;q<Y.nestedArray.length;++q)this._handleAdd(Y._nestedArray[q]);if(Dq.test(Y.name))Y.parent[Y.name]=Y}if(Y instanceof eX||Y instanceof tX||Y instanceof Vq)this._fullyQualifiedObjects[Y.fullName]=Y};T1.prototype._handleRemove=function(Y){if(Y instanceof Vq){if(Y.extend!==void 0)if(Y.extensionField)Y.extensionField.parent.remove(Y.extensionField),Y.extensionField=null;else{var T=this.deferred.indexOf(Y);if(T>-1)this.deferred.splice(T,1)}}else if(Y instanceof tX){if(Dq.test(Y.name))delete Y.parent[Y.name]}else if(Y instanceof Fq){for(var q=0;q<Y.nestedArray.length;++q)this._handleRemove(Y._nestedArray[q]);if(Dq.test(Y.name))delete Y.parent[Y.name]}delete this._fullyQualifiedObjects[Y.fullName]};T1._configure=function($,Y,T){eX=$,$5=Y,cT=T}});var w0=M((_g,jA)=>{var F0=jA.exports=_1(),yA=jX(),Y5,T5;F0.codegen=JA();F0.fetch=UA();F0.path=AA();F0.fs=F0.inquire("fs");F0.toArray=function(Y){if(Y){var T=Object.keys(Y),q=Array(T.length),X=0;while(X<T.length)q[X]=Y[T[X++]];return q}return[]};F0.toObject=function(Y){var T={},q=0;while(q<Y.length){var X=Y[q++],J=Y[q++];if(J!==void 0)T[X]=J}return T};var J2=/\\/g,Q2=/"/g;F0.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)};F0.safeProp=function(Y){if(!/^[$\w_]+$/.test(Y)||F0.isReserved(Y))return'["'+Y.replace(J2,"\\\\").replace(Q2,"\\\"")+'"]';return"."+Y};F0.ucFirst=function(Y){return Y.charAt(0).toUpperCase()+Y.substring(1)};var U2=/_([a-z])/g;F0.camelCase=function(Y){return Y.substring(0,1)+Y.substring(1).replace(U2,function(T,q){return q.toUpperCase()})};F0.compareFieldsById=function(Y,T){return Y.id-T.id};F0.decorateType=function(Y,T){if(Y.$type){if(T&&Y.$type.name!==T)F0.decorateRoot.remove(Y.$type),Y.$type.name=T,F0.decorateRoot.add(Y.$type);return Y.$type}if(!Y5)Y5=Eq();var q=new Y5(T||Y.name);return F0.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 Z2=0;F0.decorateEnum=function(Y){if(Y.$type)return Y.$type;if(!T5)T5=w1();var T=new T5("Enum"+Z2++,Y);return F0.decorateRoot.add(T),Object.defineProperty(Y,"$type",{value:T,enumerable:!1}),T};F0.setProperty=function(Y,T,q,X){function J(Q,U,Z){var K=U.shift();if(K==="__proto__"||K==="prototype")return Q;if(U.length>0)Q[K]=J(Q[K]||{},U,Z);else{var A=Q[K];if(A&&X)return Q;if(A)Z=[].concat(A).concat(Z);Q[K]=Z}return Q}if(typeof Y!=="object")throw TypeError("dst must be an object");if(!T)throw TypeError("path must be specified");return T=T.split("."),J(Y,T,q)};Object.defineProperty(F0,"decorateRoot",{get:function(){return yA.decorated||(yA.decorated=new(Nq()))}})});var s$=M((vA)=>{var pT=vA,K2=w0(),A2=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function lT($,Y){var T=0,q={};Y|=0;while(T<$.length)q[A2[T+Y]]=$[T++];return q}pT.basic=lT([1,5,0,0,0,5,5,0,0,0,1,1,0,2,2]);pT.defaults=lT([0,0,0,0,0,0,0,0,0,0,0,0,!1,"",K2.emptyArray,null]);pT.long=lT([0,0,0,1,1],7);pT.mapKey=lT([0,0,0,5,5,0,0,0,1,1,0,2],2);pT.packed=lT([1,5,0,0,0,5,5,0,0,0,1,1,0])});var P$=M((mg,kA)=>{kA.exports=S0;var iT=L$();((S0.prototype=Object.create(iT.prototype)).constructor=S0).className="Field";var xA=w1(),q5=s$(),I0=w0(),nT,W2=/^required|optional|repeated$/;S0.fromJSON=function(Y,T){var q=new S0(Y,T.id,T.type,T.rule,T.extend,T.options,T.comment);if(T.edition)q._edition=T.edition;return q._defaultEdition="proto3",q};function S0($,Y,T,q,X,J,Q){if(I0.isObject(q))Q=X,J=q,q=X=void 0;else if(I0.isObject(X))Q=J,J=X,X=void 0;if(iT.call(this,$,J),!I0.isInteger(Y)||Y<0)throw TypeError("id must be a non-negative integer");if(!I0.isString(T))throw TypeError("type must be a string");if(q!==void 0&&!W2.test(q=q.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(X!==void 0&&!I0.isString(X))throw TypeError("extend must be a string");if(q==="proto3_optional")q="optional";this.rule=q&&q!=="optional"?q:void 0,this.type=T,this.id=Y,this.extend=X||void 0,this.repeated=q==="repeated",this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=I0.Long?q5.long[T]!==void 0:!1,this.bytes=T==="bytes",this.resolvedType=null,this.extensionField=null,this.declaringField=null,this.comment=Q}Object.defineProperty(S0.prototype,"required",{get:function(){return this._features.field_presence==="LEGACY_REQUIRED"}});Object.defineProperty(S0.prototype,"optional",{get:function(){return!this.required}});Object.defineProperty(S0.prototype,"delimited",{get:function(){return this.resolvedType instanceof nT&&this._features.message_encoding==="DELIMITED"}});Object.defineProperty(S0.prototype,"packed",{get:function(){return this._features.repeated_field_encoding==="PACKED"}});Object.defineProperty(S0.prototype,"hasPresence",{get:function(){if(this.repeated||this.map)return!1;return this.partOf||this.declaringField||this.extensionField||this._features.field_presence!=="IMPLICIT"}});S0.prototype.setOption=function(Y,T,q){return iT.prototype.setOption.call(this,Y,T,q)};S0.prototype.toJSON=function(Y){var T=Y?Boolean(Y.keepComments):!1;return I0.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",T?this.comment:void 0])};S0.prototype.resolve=function(){if(this.resolved)return this;if((this.typeDefault=q5.defaults[this.type])===void 0)if(this.resolvedType=(this.declaringField?this.declaringField.parent:this.parent).lookupTypeOrEnum(this.type),this.resolvedType instanceof nT)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 xA&&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 xA))delete this.options.packed;if(!Object.keys(this.options).length)this.options=void 0}if(this.long){if(this.typeDefault=I0.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(I0.base64.test(this.typeDefault))I0.base64.decode(this.typeDefault,Y=I0.newBuffer(I0.base64.length(this.typeDefault)),0);else I0.utf8.write(this.typeDefault,Y=I0.newBuffer(I0.utf8.length(this.typeDefault)),0);this.typeDefault=Y}if(this.map)this.defaultValue=I0.emptyObject;else if(this.repeated)this.defaultValue=I0.emptyArray;else this.defaultValue=this.typeDefault;if(this.parent instanceof nT)this.parent.ctor.prototype[this.name]=this.defaultValue;return iT.prototype.resolve.call(this)};S0.prototype._inferLegacyProtoFeatures=function(Y){if(Y!=="proto2"&&Y!=="proto3")return{};var T={};if(this.rule==="required")T.field_presence="LEGACY_REQUIRED";if(this.parent&&q5.defaults[this.type]===void 0){var q=this.parent.get(this.type.split(".").pop());if(q&&q instanceof nT&&q.group)T.message_encoding="DELIMITED"}if(this.getOption("packed")===!0)T.repeated_field_encoding="PACKED";else if(this.getOption("packed")===!1)T.repeated_field_encoding="EXPANDED";return T};S0.prototype._resolveFeatures=function(Y){return iT.prototype._resolveFeatures.call(this,this._edition||Y)};S0.d=function(Y,T,q,X){if(typeof T==="function")T=I0.decorateType(T).name;else if(T&&typeof T==="object")T=I0.decorateEnum(T).name;return function(Q,U){I0.decorateType(Q.constructor).add(new S0(U,Y,T,q,{default:X}))}};S0._configure=function(Y){nT=Y}});var o$=M((fg,gA)=>{gA.exports=q1;var zq=L$();((q1.prototype=Object.create(zq.prototype)).constructor=q1).className="OneOf";var hA=P$(),Hq=w0();function q1($,Y,T,q){if(!Array.isArray(Y))T=Y,Y=void 0;if(zq.call(this,$,T),!(Y===void 0||Array.isArray(Y)))throw TypeError("fieldNames must be an Array");this.oneof=Y||[],this.fieldsArray=[],this.comment=q}q1.fromJSON=function(Y,T){return new q1(Y,T.oneof,T.options,T.comment)};q1.prototype.toJSON=function(Y){var T=Y?Boolean(Y.keepComments):!1;return Hq.toObject(["options",this.options,"oneof",this.oneof,"comment",T?this.comment:void 0])};function _A($){if($.parent){for(var Y=0;Y<$.fieldsArray.length;++Y)if(!$.fieldsArray[Y].parent)$.parent.add($.fieldsArray[Y])}}q1.prototype.add=function(Y){if(!(Y instanceof hA))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,_A(this),this};q1.prototype.remove=function(Y){if(!(Y instanceof hA))throw TypeError("field must be a Field");var T=this.fieldsArray.indexOf(Y);if(T<0)throw Error(Y+" is not a member of "+this);if(this.fieldsArray.splice(T,1),T=this.oneof.indexOf(Y.name),T>-1)this.oneof.splice(T,1);return Y.partOf=null,this};q1.prototype.onAdd=function(Y){zq.prototype.onAdd.call(this,Y);var T=this;for(var q=0;q<this.oneof.length;++q){var X=Y.get(this.oneof[q]);if(X&&!X.partOf)X.partOf=T,T.fieldsArray.push(X)}_A(this)};q1.prototype.onRemove=function(Y){for(var T=0,q;T<this.fieldsArray.length;++T)if((q=this.fieldsArray[T]).parent)q.parent.remove(q);zq.prototype.onRemove.call(this,Y)};Object.defineProperty(q1.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}});q1.d=function(){var Y=Array(arguments.length),T=0;while(T<arguments.length)Y[T]=arguments[T++];return function(X,J){Hq.decorateType(X.constructor).add(new q1(J,Y)),Object.defineProperty(X,J,{get:Hq.oneOfGetter(Y),set:Hq.oneOfSetter(Y)})}}});var L$=M((bg,mA)=>{mA.exports=x0;x0.className="ReflectionObject";var G2=o$(),rT=w0(),Iq,E2={enum_type:"OPEN",field_presence:"EXPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"},V2={enum_type:"CLOSED",field_presence:"EXPLICIT",json_format:"LEGACY_BEST_EFFORT",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"EXPANDED",utf8_validation:"NONE"},D2={enum_type:"OPEN",field_presence:"IMPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"};function x0($,Y){if(!rT.isString($))throw TypeError("name must be a string");if(Y&&!rT.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(x0.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(".")}}});x0.prototype.toJSON=function(){throw Error()};x0.prototype.onAdd=function(Y){if(this.parent&&this.parent!==Y)this.parent.remove(this);this.parent=Y,this.resolved=!1;var T=Y.root;if(T instanceof Iq)T._handleAdd(this)};x0.prototype.onRemove=function(Y){var T=Y.root;if(T instanceof Iq)T._handleRemove(this);this.parent=null,this.resolved=!1};x0.prototype.resolve=function(){if(this.resolved)return this;if(this.root instanceof Iq)this.resolved=!0;return this};x0.prototype._resolveFeaturesRecursive=function(Y){return this._resolveFeatures(this._edition||Y)};x0.prototype._resolveFeatures=function(Y){if(this._featuresResolved)return;var T={};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")T=Object.assign({},V2);else if(Y==="proto3")T=Object.assign({},D2);else if(Y==="2023")T=Object.assign({},E2);else throw Error("Unknown edition: "+Y);this._features=Object.assign(T,q||{}),this._featuresResolved=!0;return}if(this.partOf instanceof G2){var X=Object.assign({},this.partOf._features);this._features=Object.assign(X,q||{})}else if(this.declaringField);else if(this.parent){var J=Object.assign({},this.parent._features);this._features=Object.assign(J,q||{})}else throw Error("Unable to find a parent for "+this.fullName);if(this.extensionField)this.extensionField._features=this._features;this._featuresResolved=!0};x0.prototype._inferLegacyProtoFeatures=function(){return{}};x0.prototype.getOption=function(Y){if(this.options)return this.options[Y];return};x0.prototype.setOption=function(Y,T,q){if(!this.options)this.options={};if(/^features\./.test(Y))rT.setProperty(this.options,Y,T,q);else if(!q||this.options[Y]===void 0){if(this.getOption(Y)!==T)this.resolved=!1;this.options[Y]=T}return this};x0.prototype.setParsedOption=function(Y,T,q){if(!this.parsedOptions)this.parsedOptions=[];var X=this.parsedOptions;if(q){var J=X.find(function(Z){return Object.prototype.hasOwnProperty.call(Z,Y)});if(J){var Q=J[Y];rT.setProperty(Q,q,T)}else J={},J[Y]=rT.setProperty({},q,T),X.push(J)}else{var U={};U[Y]=T,X.push(U)}return this};x0.prototype.setOptions=function(Y,T){if(Y)for(var q=Object.keys(Y),X=0;X<q.length;++X)this.setOption(q[X],Y[q[X]],T);return this};x0.prototype.toString=function(){var Y=this.constructor.className,T=this.fullName;if(T.length)return Y+" "+T;return Y};x0.prototype._editionToJSON=function(){if(!this._edition||this._edition==="proto3")return;return this._edition};x0._configure=function($){Iq=$}});var w1=M((ug,bA)=>{bA.exports=S1;var X5=L$();((S1.prototype=Object.create(X5.prototype)).constructor=S1).className="Enum";var fA=kY(),Mq=w0();function S1($,Y,T,q,X,J){if(X5.call(this,$,T),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=X||{},this.valuesOptions=J,this._valuesFeatures={},this.reserved=void 0,Y){for(var Q=Object.keys(Y),U=0;U<Q.length;++U)if(typeof Y[Q[U]]==="number")this.valuesById[this.values[Q[U]]=Y[Q[U]]]=Q[U]}}S1.prototype._resolveFeatures=function(Y){return Y=this._edition||Y,X5.prototype._resolveFeatures.call(this,Y),Object.keys(this.values).forEach((T)=>{var q=Object.assign({},this._features);this._valuesFeatures[T]=Object.assign(q,this.valuesOptions&&this.valuesOptions[T]&&this.valuesOptions[T].features)}),this};S1.fromJSON=function(Y,T){var q=new S1(Y,T.values,T.options,T.comment,T.comments);if(q.reserved=T.reserved,T.edition)q._edition=T.edition;return q._defaultEdition="proto3",q};S1.prototype.toJSON=function(Y){var T=Y?Boolean(Y.keepComments):!1;return Mq.toObject(["edition",this._editionToJSON(),"options",this.options,"valuesOptions",this.valuesOptions,"values",this.values,"reserved",this.reserved&&this.reserved.length?this.reserved:void 0,"comment",T?this.comment:void 0,"comments",T?this.comments:void 0])};S1.prototype.add=function(Y,T,q,X){if(!Mq.isString(Y))throw TypeError("name must be a string");if(!Mq.isInteger(T))throw TypeError("id must be an integer");if(this.values[Y]!==void 0)throw Error("duplicate name '"+Y+"' in "+this);if(this.isReservedId(T))throw Error("id "+T+" is reserved in "+this);if(this.isReservedName(Y))throw Error("name '"+Y+"' is reserved in "+this);if(this.valuesById[T]!==void 0){if(!(this.options&&this.options.allow_alias))throw Error("duplicate id "+T+" in "+this);this.values[Y]=T}else this.valuesById[this.values[Y]=T]=Y;if(X){if(this.valuesOptions===void 0)this.valuesOptions={};this.valuesOptions[Y]=X||null}return this.comments[Y]=q||null,this};S1.prototype.remove=function(Y){if(!Mq.isString(Y))throw TypeError("name must be a string");var T=this.values[Y];if(T==null)throw Error("name '"+Y+"' does not exist in "+this);if(delete this.valuesById[T],delete this.values[Y],delete this.comments[Y],this.valuesOptions)delete this.valuesOptions[Y];return this};S1.prototype.isReservedId=function(Y){return fA.isReservedId(this.reserved,Y)};S1.prototype.isReservedName=function(Y){return fA.isReservedName(this.reserved,Y)}});var sX=M((dg,dA)=>{dA.exports=N2;var F2=w1(),J5=s$(),Q5=w0();function uA($,Y,T,q){return Y.delimited?$("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",T,q,(Y.id<<3|3)>>>0,(Y.id<<3|4)>>>0):$("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",T,q,(Y.id<<3|2)>>>0)}function N2($){var Y=Q5.codegen(["m","w"],$.name+"$encode")("if(!w)")("w=Writer.create()"),T,q,X=$.fieldsArray.slice().sort(Q5.compareFieldsById);for(var T=0;T<X.length;++T){var J=X[T].resolve(),Q=$._fieldsArray.indexOf(J),U=J.resolvedType instanceof F2?"int32":J.type,Z=J5.basic[U];if(q="m"+Q5.safeProp(J.name),J.map){if(Y("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){",q,J.name)("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){",q)("w.uint32(%i).fork().uint32(%i).%s(ks[i])",(J.id<<3|2)>>>0,8|J5.mapKey[J.keyType],J.keyType),Z===void 0)Y("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",Q,q);else Y(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|Z,U,q);Y("}")("}")}else if(J.repeated){if(Y("if(%s!=null&&%s.length){",q,q),J.packed&&J5.packed[U]!==void 0)Y("w.uint32(%i).fork()",(J.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",q)("w.%s(%s[i])",U,q)("w.ldelim()");else if(Y("for(var i=0;i<%s.length;++i)",q),Z===void 0)uA(Y,J,Q,q+"[i]");else Y("w.uint32(%i).%s(%s[i])",(J.id<<3|Z)>>>0,U,q);Y("}")}else{if(J.optional)Y("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",q,J.name);if(Z===void 0)uA(Y,J,Q,q);else Y("w.uint32(%i).%s(%s)",(J.id<<3|Z)>>>0,U,q)}}return Y("return w")}});var pA=M((cg,cA)=>{var e=cA.exports=qA();e.build="light";function H2($,Y,T){if(typeof Y==="function")T=Y,Y=new e.Root;else if(!Y)Y=new e.Root;return Y.load($,T)}e.load=H2;function z2($,Y){if(!Y)Y=new e.Root;return Y.loadSync($)}e.loadSync=z2;e.encoder=sX();e.decoder=bX();e.verifier=cX();e.converter=nX();e.ReflectionObject=L$();e.Namespace=kY();e.Root=Nq();e.Enum=w1();e.Type=Eq();e.Field=P$();e.OneOf=o$();e.MapField=Uq();e.Service=Kq();e.Method=Zq();e.Message=Aq();e.wrappers=iX();e.types=s$();e.util=w0();e.ReflectionObject._configure(e.Root);e.Namespace._configure(e.Type,e.Service,e.Enum);e.Root._configure(e.Type);e.Field._configure(e.Type)});var Z5=M((pg,iA)=>{iA.exports=nA;var U5=/[\s{}=;:[\],'"()<>]/g,I2=/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,M2=/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,B2=/^ *[*/]+ */,R2=/^\s*\*?\/*/,O2=/\n/g,P2=/\s/,L2=/\\(.?)/g,w2={"0":"\x00",r:"\r",n:`
9
+ `,t:"\t"};function lA($){return $.replace(L2,function(Y,T){switch(T){case"\\":case"":return T;default:return w2[T]||""}})}nA.unescape=lA;function nA($,Y){$=$.toString();var T=0,q=$.length,X=1,J=0,Q={},U=[],Z=null;function K(z){return Error("illegal "+z+" (line "+X+")")}function A(){var z=Z==="'"?M2:I2;z.lastIndex=T-1;var _=z.exec($);if(!_)throw K("string");return T=z.lastIndex,V(Z),Z=null,lA(_[1])}function W(z){return $.charAt(z)}function E(z,_,y){var k={type:$.charAt(z++),lineEmpty:!1,leading:y},m;if(Y)m=2;else m=3;var C=z-m,j;do if(--C<0||(j=$.charAt(C))===`
10
+ `){k.lineEmpty=!0;break}while(j===" "||j==="\t");var I=$.substring(z,_).split(O2);for(var h0=0;h0<I.length;++h0)I[h0]=I[h0].replace(Y?R2:B2,"").trim();k.text=I.join(`
11
+ `).trim(),Q[X]=k,J=X}function D(z){var _=F(z),y=$.substring(z,_),k=/^\s*\/\//.test(y);return k}function F(z){var _=z;while(_<q&&W(_)!==`
12
+ `)_++;return _}function H(){if(U.length>0)return U.shift();if(Z)return A();var z,_,y,k,m,C=T===0;do{if(T===q)return null;z=!1;while(P2.test(y=W(T))){if(y===`
13
+ `)C=!0,++X;if(++T===q)return null}if(W(T)==="/"){if(++T===q)throw K("comment");if(W(T)==="/")if(!Y){m=W(k=T+1)==="/";while(W(++T)!==`
14
+ `)if(T===q)return null;if(++T,m)E(k,T-1,C),C=!0;++X,z=!0}else{if(k=T,m=!1,D(T-1)){m=!0;do{if(T=F(T),T===q)break;if(T++,!C)break}while(D(T))}else T=Math.min(q,F(T)+1);if(m)E(k,T,C),C=!0;X++,z=!0}else if((y=W(T))==="*"){k=T+1,m=Y||W(k)==="*";do{if(y===`
15
+ `)++X;if(++T===q)throw K("comment");_=y,y=W(T)}while(_!=="*"||y!=="/");if(++T,m)E(k,T-2,C),C=!0;z=!0}else return"/"}}while(z);var j=T;U5.lastIndex=0;var I=U5.test(W(j++));if(!I)while(j<q&&!U5.test(W(j)))++j;var h0=$.substring(T,T=j);if(h0==='"'||h0==="'")Z=h0;return h0}function V(z){U.push(z)}function B(){if(!U.length){var z=H();if(z===null)return null;V(z)}return U[0]}function S(z,_){var y=B(),k=y===z;if(k)return H(),!0;if(!_)throw K("token '"+y+"', '"+z+"' expected");return!1}function v(z){var _=null,y;if(z===void 0){if(y=Q[X-1],delete Q[X-1],y&&(Y||y.type==="*"||y.lineEmpty))_=y.leading?y.text:null}else{if(J<z)B();if(y=Q[z],delete Q[z],y&&!y.lineEmpty&&(Y||y.type==="/"))_=y.leading?null:y.text}return _}return Object.defineProperty({next:H,peek:B,push:V,skip:S,cmnt:v},"line",{get:function(){return X}})}});var eA=M((lg,tA)=>{tA.exports=Q$;Q$.filename=null;Q$.defaults={keepCase:!1};var S2=Z5(),rA=Nq(),aA=Eq(),oA=P$(),C2=Uq(),sA=o$(),y2=w1(),j2=Kq(),v2=Zq(),x2=L$(),k2=s$(),K5=w0(),h2=/^[1-9][0-9]*$/,_2=/^-?[1-9][0-9]*$/,g2=/^0[x][0-9a-fA-F]+$/,m2=/^-?0[x][0-9a-fA-F]+$/,f2=/^0[0-7]+$/,b2=/^-?0[0-7]+$/,u2=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,b1=/^[a-zA-Z_][a-zA-Z_0-9]*$/,u1=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/;function Q$($,Y,T){if(!(Y instanceof rA))T=Y,Y=new rA;if(!T)T=Q$.defaults;var q=T.preferTrailingComment||!1,X=S2($,T.alternateCommentMode||!1),J=X.next,Q=X.push,U=X.peek,Z=X.skip,K=X.cmnt,A=!0,W,E,D,F="proto2",H=Y,V=[],B={},S=T.keepCase?function(O){return O}:K5.camelCase;function v(){V.forEach((O)=>{O._edition=F,Object.keys(B).forEach((R)=>{if(O.getOption(R)!==void 0)return;O.setOption(R,B[R],!0)})})}function z(O,R,w){var h=Q$.filename;if(!w)Q$.filename=null;return Error("illegal "+(R||"token")+" '"+O+"' ("+(h?h+", ":"")+"line "+X.line+")")}function _(){var O=[],R;do{if((R=J())!=='"'&&R!=="'")throw z(R);O.push(J()),Z(R),R=U()}while(R==='"'||R==="'");return O.join("")}function y(O){var R=J();switch(R){case"'":case'"':return Q(R),_();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return m(R,!0)}catch(w){if(O&&u1.test(R))return R;throw z(R,"value")}}function k(O,R){var w,h;do if(R&&((w=U())==='"'||w==="'")){var x=_();if(O.push(x),F>=2023)throw z(x,"id")}else try{O.push([h=C(J()),Z("to",!0)?C(J()):h])}catch(A0){if(R&&u1.test(w)&&F>=2023)O.push(w);else throw A0}while(Z(",",!0));var f={options:void 0};f.setOption=function(A0,g0){if(this.options===void 0)this.options={};this.options[A0]=g0},L(f,function(g0){if(g0==="option")Y0(f,g0),Z(";");else throw z(g0)},function(){o1(f)})}function m(O,R){var w=1;if(O.charAt(0)==="-")w=-1,O=O.substring(1);switch(O){case"inf":case"INF":case"Inf":return w*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(h2.test(O))return w*parseInt(O,10);if(g2.test(O))return w*parseInt(O,16);if(f2.test(O))return w*parseInt(O,8);if(u2.test(O))return w*parseFloat(O);throw z(O,"number",R)}function C(O,R){switch(O){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!R&&O.charAt(0)==="-")throw z(O,"id");if(_2.test(O))return parseInt(O,10);if(m2.test(O))return parseInt(O,16);if(b2.test(O))return parseInt(O,8);throw z(O,"id")}function j(){if(W!==void 0)throw z("package");if(W=J(),!u1.test(W))throw z(W,"name");H=H.define(W),Z(";")}function I(){var O=U(),R;switch(O){case"weak":R=D||(D=[]),J();break;case"public":J();default:R=E||(E=[]);break}O=_(),Z(";"),R.push(O)}function h0(){if(Z("="),F=_(),F<2023)throw z(F,"syntax");Z(";")}function P(){if(Z("="),F=_(),!["2023"].includes(F))throw z(F,"edition");Z(";")}function G(O,R){switch(R){case"option":return Y0(O,R),Z(";"),!0;case"message":return l(O,R),!0;case"enum":return b0(O,R),!0;case"service":return $D(O,R),!0;case"extend":return TD(O,R),!0}return!1}function L(O,R,w){var h=X.line;if(O){if(typeof O.comment!=="string")O.comment=K();O.filename=Q$.filename}if(Z("{",!0)){var x;while((x=J())!=="}")R(x);Z(";",!0)}else{if(w)w();if(Z(";"),O&&(typeof O.comment!=="string"||q))O.comment=K(h)||O.comment}}function l(O,R){if(!b1.test(R=J()))throw z(R,"type name");var w=new aA(R);if(L(w,function(x){if(G(w,x))return;switch(x){case"map":V0(w,x);break;case"required":if(F!=="proto2")throw z(x);case"repeated":u(w,x);break;case"optional":if(F==="proto3")u(w,"proto3_optional");else if(F!=="proto2")throw z(x);else u(w,"optional");break;case"oneof":_0(w,x);break;case"extensions":k(w.extensions||(w.extensions=[]));break;case"reserved":k(w.reserved||(w.reserved=[]),!0);break;default:if(F==="proto2"||!u1.test(x))throw z(x);Q(x),u(w,"optional");break}}),O.add(w),O===H)V.push(w)}function u(O,R,w){var h=J();if(h==="group"){d(O,R);return}while(h.endsWith(".")||U().startsWith("."))h+=J();if(!u1.test(h))throw z(h,"type");var x=J();if(!b1.test(x))throw z(x,"name");x=S(x),Z("=");var f=new oA(x,C(J()),h,R,w);if(L(f,function(c0){if(c0==="option")Y0(f,c0),Z(";");else throw z(c0)},function(){o1(f)}),R==="proto3_optional"){var A0=new sA("_"+x);f.setOption("proto3_optional",!0),A0.add(f),O.add(A0)}else O.add(f);if(O===H)V.push(f)}function d(O,R){if(F>=2023)throw z("group");var w=J();if(!b1.test(w))throw z(w,"name");var h=K5.lcFirst(w);if(w===h)w=K5.ucFirst(w);Z("=");var x=C(J()),f=new aA(w);f.group=!0;var A0=new oA(h,x,w,R);A0.filename=Q$.filename,L(f,function(c0){switch(c0){case"option":Y0(f,c0),Z(";");break;case"required":case"repeated":u(f,c0);break;case"optional":if(F==="proto3")u(f,"proto3_optional");else u(f,"optional");break;case"message":l(f,c0);break;case"enum":b0(f,c0);break;case"reserved":k(f.reserved||(f.reserved=[]),!0);break;default:throw z(c0)}}),O.add(f).add(A0)}function V0(O){Z("<");var R=J();if(k2.mapKey[R]===void 0)throw z(R,"type");Z(",");var w=J();if(!u1.test(w))throw z(w,"type");Z(">");var h=J();if(!b1.test(h))throw z(h,"name");Z("=");var x=new C2(S(h),C(J()),R,w);L(x,function(A0){if(A0==="option")Y0(x,A0),Z(";");else throw z(A0)},function(){o1(x)}),O.add(x)}function _0(O,R){if(!b1.test(R=J()))throw z(R,"name");var w=new sA(S(R));L(w,function(x){if(x==="option")Y0(w,x),Z(";");else Q(x),u(w,"optional")}),O.add(w)}function b0(O,R){if(!b1.test(R=J()))throw z(R,"name");var w=new y2(R);if(L(w,function(x){switch(x){case"option":Y0(w,x),Z(";");break;case"reserved":if(k(w.reserved||(w.reserved=[]),!0),w.reserved===void 0)w.reserved=[];break;default:B0(w,x)}}),O.add(w),O===H)V.push(w)}function B0(O,R){if(!b1.test(R))throw z(R,"name");Z("=");var w=C(J(),!0),h={options:void 0};h.getOption=function(x){return this.options[x]},h.setOption=function(x,f){x2.prototype.setOption.call(h,x,f)},h.setParsedOption=function(){return},L(h,function(f){if(f==="option")Y0(h,f),Z(";");else throw z(f)},function(){o1(h)}),O.add(R,w,h.comment,h.parsedOptions||h.options)}function Y0(O,R){var w,h,x=!0;if(R==="option")R=J();while(R!=="="){if(R==="("){var f=J();Z(")"),R="("+f+")"}if(x){if(x=!1,R.includes(".")&&!R.includes("(")){var A0=R.split(".");w=A0[0]+".",R=A0[1];continue}w=R}else h=h?h+=R:R;R=J()}var g0=h?w.concat(h):w,c0=u0(O,g0);h=h&&h[0]==="."?h.slice(1):h,w=w&&w[w.length-1]==="."?w.slice(0,-1):w,d0(O,w,c0,h)}function u0(O,R){if(Z("{",!0)){var w={};while(!Z("}",!0)){if(!b1.test(j0=J()))throw z(j0,"name");if(j0===null)throw z(j0,"end of input");var h,x=j0;if(Z(":",!0),U()==="{")h=u0(O,R+"."+j0);else if(U()==="["){h=[];var f;if(Z("[",!0)){do f=y(!0),h.push(f);while(Z(",",!0));if(Z("]"),typeof f<"u")E0(O,R+"."+j0,f)}}else h=y(!0),E0(O,R+"."+j0,h);var A0=w[x];if(A0)h=[].concat(A0).concat(h);w[x]=h,Z(",",!0),Z(";",!0)}return w}var g0=y(!0);return E0(O,R,g0),g0}function E0(O,R,w){if(H===O&&/^features\./.test(R)){B[R]=w;return}if(O.setOption)O.setOption(R,w)}function d0(O,R,w,h){if(O.setParsedOption)O.setParsedOption(R,w,h)}function o1(O){if(Z("[",!0)){do Y0(O,"option");while(Z(",",!0));Z("]")}return O}function $D(O,R){if(!b1.test(R=J()))throw z(R,"service name");var w=new j2(R);if(L(w,function(x){if(G(w,x))return;if(x==="rpc")YD(w,x);else throw z(x)}),O.add(w),O===H)V.push(w)}function YD(O,R){var w=K(),h=R;if(!b1.test(R=J()))throw z(R,"name");var x=R,f,A0,g0,c0;if(Z("("),Z("stream",!0))A0=!0;if(!u1.test(R=J()))throw z(R);if(f=R,Z(")"),Z("returns"),Z("("),Z("stream",!0))c0=!0;if(!u1.test(R=J()))throw z(R);g0=R,Z(")");var L6=new v2(x,h,f,g0,A0,c0);L6.comment=w,L(L6,function(F9){if(F9==="option")Y0(L6,F9),Z(";");else throw z(F9)}),O.add(L6)}function TD(O,R){if(!u1.test(R=J()))throw z(R,"reference");var w=R;L(null,function(x){switch(x){case"required":case"repeated":u(O,x,w);break;case"optional":if(F==="proto3")u(O,"proto3_optional",w);else u(O,"optional",w);break;default:if(F==="proto2"||!u1.test(x))throw z(x);Q(x),u(O,"optional",w);break}})}var j0;while((j0=J())!==null)switch(j0){case"package":if(!A)throw z(j0);j();break;case"import":if(!A)throw z(j0);I();break;case"syntax":if(!A)throw z(j0);h0();break;case"edition":if(!A)throw z(j0);P();break;case"option":Y0(H,j0),Z(";",!0);break;default:if(G(H,j0)){A=!1;continue}throw z(j0)}return v(),Q$.filename=null,{package:W,imports:E,weakImports:D,root:Y}}});var TW=M((ng,YW)=>{YW.exports=C1;var d2=/\/|\./;function C1($,Y){if(!d2.test($))$="google/protobuf/"+$+".proto",Y={nested:{google:{nested:{protobuf:{nested:Y}}}}};C1[$]=Y}C1("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}});var $W;C1("duration",{Duration:$W={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}});C1("timestamp",{Timestamp:$W});C1("empty",{Empty:{fields:{}}});C1("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}}}});C1("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}}}});C1("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}});C1.get=function(Y){return C1[Y]||null}});var Bq=M((ig,qW)=>{var S$=qW.exports=pA();S$.build="full";S$.tokenize=Z5();S$.parse=eA();S$.common=TW();S$.Root._configure(S$.Type,S$.parse,S$.common)});var A5=M((rg,c2)=>{c2.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 AW=M((p,KW)=>{var X1=Bq();KW.exports=p=X1.descriptor=X1.Root.fromJSON(A5()).lookup(".google.protobuf");var{Namespace:XW,Root:aT,Enum:U$,Type:d1,Field:C$,MapField:p2,OneOf:Rq,Service:oT,Method:Oq}=X1;aT.fromDescriptor=function(Y){if(typeof Y.length==="number")Y=p.FileDescriptorSet.decode(Y);var T=new aT;if(Y.file){var q,X;for(var J=0,Q;J<Y.file.length;++J){if(X=T,(q=Y.file[J]).package&&q.package.length)X=T.define(q.package);var U=$O(q);if(q.name&&q.name.length)T.files.push(X.filename=q.name);if(q.messageType)for(Q=0;Q<q.messageType.length;++Q)X.add(d1.fromDescriptor(q.messageType[Q],U));if(q.enumType)for(Q=0;Q<q.enumType.length;++Q)X.add(U$.fromDescriptor(q.enumType[Q],U));if(q.extension)for(Q=0;Q<q.extension.length;++Q)X.add(C$.fromDescriptor(q.extension[Q],U));if(q.service)for(Q=0;Q<q.service.length;++Q)X.add(oT.fromDescriptor(q.service[Q],U));var Z=_Y(q.options,p.FileOptions);if(Z){var K=Object.keys(Z);for(Q=0;Q<K.length;++Q)X.setOption(K[Q],Z[K[Q]])}}}return T.resolveAll()};aT.prototype.toDescriptor=function(Y){var T=p.FileDescriptorSet.create();return JW(this,T.file,Y),T};function JW($,Y,T){var q=p.FileDescriptorProto.create({name:$.filename||($.fullName.substring(1).replace(/\./g,"_")||"root")+".proto"});if(YO(T,q),!($ instanceof aT))q.package=$.fullName.substring(1);for(var X=0,J;X<$.nestedArray.length;++X)if((J=$._nestedArray[X])instanceof d1)q.messageType.push(J.toDescriptor(T));else if(J instanceof U$)q.enumType.push(J.toDescriptor());else if(J instanceof C$)q.extension.push(J.toDescriptor(T));else if(J instanceof oT)q.service.push(J.toDescriptor());else if(J instanceof XW)JW(J,Y,T);if(q.options=gY($.options,p.FileOptions),q.messageType.length+q.enumType.length+q.extension.length+q.service.length)Y.push(q)}var l2=0;d1.fromDescriptor=function(Y,T,q){if(typeof Y.length==="number")Y=p.DescriptorProto.decode(Y);var X=new d1(Y.name.length?Y.name:"Type"+l2++,_Y(Y.options,p.MessageOptions)),J;if(!q)X._edition=T;if(Y.oneofDecl)for(J=0;J<Y.oneofDecl.length;++J)X.add(Rq.fromDescriptor(Y.oneofDecl[J]));if(Y.field)for(J=0;J<Y.field.length;++J){var Q=C$.fromDescriptor(Y.field[J],T,!0);if(X.add(Q),Y.field[J].hasOwnProperty("oneofIndex"))X.oneofsArray[Y.field[J].oneofIndex].add(Q)}if(Y.extension)for(J=0;J<Y.extension.length;++J)X.add(C$.fromDescriptor(Y.extension[J],T,!0));if(Y.nestedType){for(J=0;J<Y.nestedType.length;++J)if(X.add(d1.fromDescriptor(Y.nestedType[J],T,!0)),Y.nestedType[J].options&&Y.nestedType[J].options.mapEntry)X.setOption("map_entry",!0)}if(Y.enumType)for(J=0;J<Y.enumType.length;++J)X.add(U$.fromDescriptor(Y.enumType[J],T,!0));if(Y.extensionRange&&Y.extensionRange.length){X.extensions=[];for(J=0;J<Y.extensionRange.length;++J)X.extensions.push([Y.extensionRange[J].start,Y.extensionRange[J].end])}if(Y.reservedRange&&Y.reservedRange.length||Y.reservedName&&Y.reservedName.length){if(X.reserved=[],Y.reservedRange)for(J=0;J<Y.reservedRange.length;++J)X.reserved.push([Y.reservedRange[J].start,Y.reservedRange[J].end]);if(Y.reservedName)for(J=0;J<Y.reservedName.length;++J)X.reserved.push(Y.reservedName[J])}return X};d1.prototype.toDescriptor=function(Y){var T=p.DescriptorProto.create({name:this.name}),q;for(q=0;q<this.fieldsArray.length;++q){var X;if(T.field.push(X=this._fieldsArray[q].toDescriptor(Y)),this._fieldsArray[q]instanceof p2){var J=W5(this._fieldsArray[q].keyType,this._fieldsArray[q].resolvedKeyType,!1),Q=W5(this._fieldsArray[q].type,this._fieldsArray[q].resolvedType,!1),U=Q===11||Q===14?this._fieldsArray[q].resolvedType&&ZW(this.parent,this._fieldsArray[q].resolvedType)||this._fieldsArray[q].type:void 0;T.nestedType.push(p.DescriptorProto.create({name:X.typeName,field:[p.FieldDescriptorProto.create({name:"key",number:1,label:1,type:J}),p.FieldDescriptorProto.create({name:"value",number:2,label:1,type:Q,typeName:U})],options:p.MessageOptions.create({mapEntry:!0})}))}}for(q=0;q<this.oneofsArray.length;++q)T.oneofDecl.push(this._oneofsArray[q].toDescriptor());for(q=0;q<this.nestedArray.length;++q)if(this._nestedArray[q]instanceof C$)T.field.push(this._nestedArray[q].toDescriptor(Y));else if(this._nestedArray[q]instanceof d1)T.nestedType.push(this._nestedArray[q].toDescriptor(Y));else if(this._nestedArray[q]instanceof U$)T.enumType.push(this._nestedArray[q].toDescriptor());if(this.extensions)for(q=0;q<this.extensions.length;++q)T.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")T.reservedName.push(this.reserved[q]);else T.reservedRange.push(p.DescriptorProto.ReservedRange.create({start:this.reserved[q][0],end:this.reserved[q][1]}));return T.options=gY(this.options,p.MessageOptions),T};var n2=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/;C$.fromDescriptor=function(Y,T,q){if(typeof Y.length==="number")Y=p.DescriptorProto.decode(Y);if(typeof Y.number!=="number")throw Error("missing field id");var X;if(Y.typeName&&Y.typeName.length)X=Y.typeName;else X=s2(Y.type);var J;switch(Y.label){case 1:J=void 0;break;case 2:J="required";break;case 3:J="repeated";break;default:throw Error("illegal label: "+Y.label)}var Q=Y.extendee;if(Y.extendee!==void 0)Q=Q.length?Q:void 0;var U=new C$(Y.name.length?Y.name:"field"+Y.number,Y.number,X,J,Q);if(!q)U._edition=T;if(U.options=_Y(Y.options,p.FieldOptions),Y.proto3_optional)U.options.proto3_optional=!0;if(Y.defaultValue&&Y.defaultValue.length){var Z=Y.defaultValue;switch(Z){case"true":case"TRUE":Z=!0;break;case"false":case"FALSE":Z=!1;break;default:var K=n2.exec(Z);if(K)Z=parseInt(Z);break}U.setOption("default",Z)}if(t2(Y.type)){if(T==="proto3"){if(Y.options&&!Y.options.packed)U.setOption("packed",!1)}else if((!T||T==="proto2")&&Y.options&&Y.options.packed)U.setOption("packed",!0)}return U};C$.prototype.toDescriptor=function(Y){var T=p.FieldDescriptorProto.create({name:this.name,number:this.id});if(this.map)T.type=11,T.typeName=X1.util.ucFirst(this.name),T.label=3;else{switch(T.type=W5(this.type,this.resolve().resolvedType,this.delimited)){case 10:case 11:case 14:T.typeName=this.resolvedType?ZW(this.parent,this.resolvedType):this.type;break}if(this.rule==="repeated")T.label=3;else if(this.required&&Y==="proto2")T.label=2;else T.label=1}if(T.extendee=this.extensionField?this.extensionField.parent.fullName:this.extend,this.partOf){if((T.oneofIndex=this.parent.oneofsArray.indexOf(this.partOf))<0)throw Error("missing oneof")}if(this.options){if(T.options=gY(this.options,p.FieldOptions),this.options.default!=null)T.defaultValue=String(this.options.default);if(this.options.proto3_optional)T.proto3_optional=!0}if(Y==="proto3"){if(!this.packed)(T.options||(T.options=p.FieldOptions.create())).packed=!1}else if((!Y||Y==="proto2")&&this.packed)(T.options||(T.options=p.FieldOptions.create())).packed=!0;return T};var i2=0;U$.fromDescriptor=function(Y,T,q){if(typeof Y.length==="number")Y=p.EnumDescriptorProto.decode(Y);var X={};if(Y.value)for(var J=0;J<Y.value.length;++J){var Q=Y.value[J].name,U=Y.value[J].number||0;X[Q&&Q.length?Q:"NAME"+U]=U}var Z=new U$(Y.name&&Y.name.length?Y.name:"Enum"+i2++,X,_Y(Y.options,p.EnumOptions));if(!q)Z._edition=T;return Z};U$.prototype.toDescriptor=function(){var Y=[];for(var T=0,q=Object.keys(this.values);T<q.length;++T)Y.push(p.EnumValueDescriptorProto.create({name:q[T],number:this.values[q[T]]}));return p.EnumDescriptorProto.create({name:this.name,value:Y,options:gY(this.options,p.EnumOptions)})};var r2=0;Rq.fromDescriptor=function(Y){if(typeof Y.length==="number")Y=p.OneofDescriptorProto.decode(Y);return new Rq(Y.name&&Y.name.length?Y.name:"oneof"+r2++)};Rq.prototype.toDescriptor=function(){return p.OneofDescriptorProto.create({name:this.name})};var a2=0;oT.fromDescriptor=function(Y,T,q){if(typeof Y.length==="number")Y=p.ServiceDescriptorProto.decode(Y);var X=new oT(Y.name&&Y.name.length?Y.name:"Service"+a2++,_Y(Y.options,p.ServiceOptions));if(!q)X._edition=T;if(Y.method)for(var J=0;J<Y.method.length;++J)X.add(Oq.fromDescriptor(Y.method[J]));return X};oT.prototype.toDescriptor=function(){var Y=[];for(var T=0;T<this.methodsArray.length;++T)Y.push(this._methodsArray[T].toDescriptor());return p.ServiceDescriptorProto.create({name:this.name,method:Y,options:gY(this.options,p.ServiceOptions)})};var o2=0;Oq.fromDescriptor=function(Y){if(typeof Y.length==="number")Y=p.MethodDescriptorProto.decode(Y);return new Oq(Y.name&&Y.name.length?Y.name:"Method"+o2++,"rpc",Y.inputType,Y.outputType,Boolean(Y.clientStreaming),Boolean(Y.serverStreaming),_Y(Y.options,p.MethodOptions))};Oq.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:gY(this.options,p.MethodOptions)})};function s2($){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 t2($){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 W5($,Y,T){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 U$)return 14;if(Y instanceof d1)return T?10:11;throw Error("illegal type: "+$)}function QW($,Y){var T={};for(var q=0,X,J;q<Y.fieldsArray.length;++q){if((J=(X=Y._fieldsArray[q]).name)==="uninterpretedOption")continue;if(!Object.prototype.hasOwnProperty.call($,J))continue;var Q=e2(J);if(X.resolvedType instanceof d1)T[Q]=QW($[J],X.resolvedType);else if(X.resolvedType instanceof U$)T[Q]=X.resolvedType.valuesById[$[J]];else T[Q]=$[J]}return T}function _Y($,Y){if(!$)return;return QW(Y.toObject($),Y)}function UW($,Y){var T={},q=Object.keys($);for(var X=0;X<q.length;++X){var J=q[X],Q=X1.util.camelCase(J);if(!Object.prototype.hasOwnProperty.call(Y.fields,Q))continue;var U=Y.fields[Q];if(U.resolvedType instanceof d1)T[Q]=UW($[J],U.resolvedType);else T[Q]=$[J];if(U.repeated&&!Array.isArray(T[Q]))T[Q]=[T[Q]]}return T}function gY($,Y){if(!$)return;return Y.fromObject(UW($,Y))}function ZW($,Y){var T=$.fullName.split("."),q=Y.fullName.split("."),X=0,J=0,Q=q.length-1;if(!($ instanceof aT)&&Y instanceof XW)while(X<T.length&&J<Q&&T[X]===q[J]){var U=Y.lookup(T[X++],!0);if(U!==null&&U!==Y)break;++J}else for(;X<T.length&&J<Q&&T[X]===q[J];++X,++J);return q.slice(J).join(".")}function e2($){return $.substring(0,1)+$.substring(1).replace(/([A-Z])(?=[a-z]|$)/g,function(Y,T){return"_"+T.toLowerCase()})}function $O($){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 YO($,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 WW=M((ag,TO)=>{TO.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 GW=M((og,qO)=>{qO.exports={nested:{google:{nested:{protobuf:{nested:{SourceContext:{fields:{fileName:{type:"string",id:1}}}}}}}}}});var EW=M((sg,XO)=>{XO.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 zW=M((NW)=>{Object.defineProperty(NW,"__esModule",{value:!0});NW.addCommonProtos=NW.loadProtosWithOptionsSync=NW.loadProtosWithOptions=void 0;var VW=s("fs"),DW=s("path"),mY=Bq();function FW($,Y){let T=$.resolvePath;$.resolvePath=(q,X)=>{if(DW.isAbsolute(X))return X;for(let J of Y){let Q=DW.join(J,X);try{return VW.accessSync(Q,VW.constants.R_OK),Q}catch(U){continue}}return process.emitWarning(`${X} not found in any of the include paths ${Y}`),T(q,X)}}async function JO($,Y){let T=new mY.Root;if(Y=Y||{},Y.includeDirs){if(!Array.isArray(Y.includeDirs))return Promise.reject(Error("The includeDirs option must be an array"));FW(T,Y.includeDirs)}let q=await T.load($,Y);return q.resolveAll(),q}NW.loadProtosWithOptions=JO;function QO($,Y){let T=new mY.Root;if(Y=Y||{},Y.includeDirs){if(!Array.isArray(Y.includeDirs))throw Error("The includeDirs option must be an array");FW(T,Y.includeDirs)}let q=T.loadSync($,Y);return q.resolveAll(),q}NW.loadProtosWithOptionsSync=QO;function UO(){let $=WW(),Y=A5(),T=GW(),q=EW();mY.common("api",$.nested.google.nested.protobuf.nested),mY.common("descriptor",Y.nested.google.nested.protobuf.nested),mY.common("source_context",T.nested.google.nested.protobuf.nested),mY.common("type",q.nested.google.nested.protobuf.nested)}NW.addCommonProtos=UO});var IW=M((sT,G5)=>{(function($,Y){function T(q){return q.default||q}if(typeof define==="function"&&define.amd)define([],function(){var q={};return Y(q),T(q)});else if(typeof sT==="object"){if(Y(sT),typeof G5==="object")G5.exports=T(sT)}else(function(){var q={};Y(q),$.Long=T(q)})()})(typeof globalThis<"u"?globalThis:typeof self<"u"?self:sT,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 T(P,G,L){this.low=P|0,this.high=G|0,this.unsigned=!!L}T.prototype.__isLong__,Object.defineProperty(T.prototype,"__isLong__",{value:!0});function q(P){return(P&&P.__isLong__)===!0}function X(P){var G=Math.clz32(P&-P);return P?31-G:G}T.isLong=q;var J={},Q={};function U(P,G){var L,l,u;if(G){if(P>>>=0,u=0<=P&&P<256){if(l=Q[P],l)return l}if(L=K(P,0,!0),u)Q[P]=L;return L}else{if(P|=0,u=-128<=P&&P<128){if(l=J[P],l)return l}if(L=K(P,P<0?-1:0,!1),u)J[P]=L;return L}}T.fromInt=U;function Z(P,G){if(isNaN(P))return G?z:v;if(G){if(P<0)return z;if(P>=V)return C}else{if(P<=-B)return j;if(P+1>=B)return m}if(P<0)return Z(-P,G).neg();return K(P%H|0,P/H|0,G)}T.fromNumber=Z;function K(P,G,L){return new T(P,G,L)}T.fromBits=K;var A=Math.pow;function W(P,G,L){if(P.length===0)throw Error("empty string");if(typeof G==="number")L=G,G=!1;else G=!!G;if(P==="NaN"||P==="Infinity"||P==="+Infinity"||P==="-Infinity")return G?z:v;if(L=L||10,L<2||36<L)throw RangeError("radix");var l;if((l=P.indexOf("-"))>0)throw Error("interior hyphen");else if(l===0)return W(P.substring(1),G,L).neg();var u=Z(A(L,8)),d=v;for(var V0=0;V0<P.length;V0+=8){var _0=Math.min(8,P.length-V0),b0=parseInt(P.substring(V0,V0+_0),L);if(_0<8){var B0=Z(A(L,_0));d=d.mul(B0).add(Z(b0))}else d=d.mul(u),d=d.add(Z(b0))}return d.unsigned=G,d}T.fromString=W;function E(P,G){if(typeof P==="number")return Z(P,G);if(typeof P==="string")return W(P,G);return K(P.low,P.high,typeof G==="boolean"?G:P.unsigned)}T.fromValue=E;var D=65536,F=16777216,H=D*D,V=H*H,B=V/2,S=U(F),v=U(0);T.ZERO=v;var z=U(0,!0);T.UZERO=z;var _=U(1);T.ONE=_;var y=U(1,!0);T.UONE=y;var k=U(-1);T.NEG_ONE=k;var m=K(-1,2147483647,!1);T.MAX_VALUE=m;var C=K(-1,-1,!0);T.MAX_UNSIGNED_VALUE=C;var j=K(0,-2147483648,!1);T.MIN_VALUE=j;var I=T.prototype;if(I.toInt=function(){return this.unsigned?this.low>>>0:this.low},I.toNumber=function(){if(this.unsigned)return(this.high>>>0)*H+(this.low>>>0);return this.high*H+(this.low>>>0)},I.toString=function(G){if(G=G||10,G<2||36<G)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative())if(this.eq(j)){var L=Z(G),l=this.div(L),u=l.mul(L).sub(this);return l.toString(G)+u.toInt().toString(G)}else return"-"+this.neg().toString(G);var d=Z(A(G,6),this.unsigned),V0=this,_0="";while(!0){var b0=V0.div(d),B0=V0.sub(b0.mul(d)).toInt()>>>0,Y0=B0.toString(G);if(V0=b0,V0.isZero())return Y0+_0;else{while(Y0.length<6)Y0="0"+Y0;_0=""+Y0+_0}}},I.getHighBits=function(){return this.high},I.getHighBitsUnsigned=function(){return this.high>>>0},I.getLowBits=function(){return this.low},I.getLowBitsUnsigned=function(){return this.low>>>0},I.getNumBitsAbs=function(){if(this.isNegative())return this.eq(j)?64:this.neg().getNumBitsAbs();var G=this.high!=0?this.high:this.low;for(var L=31;L>0;L--)if((G&1<<L)!=0)break;return this.high!=0?L+33:L+1},I.isSafeInteger=function(){var G=this.high>>21;if(!G)return!0;if(this.unsigned)return!1;return G===-1&&!(this.low===0&&this.high===-2097152)},I.isZero=function(){return this.high===0&&this.low===0},I.eqz=I.isZero,I.isNegative=function(){return!this.unsigned&&this.high<0},I.isPositive=function(){return this.unsigned||this.high>=0},I.isOdd=function(){return(this.low&1)===1},I.isEven=function(){return(this.low&1)===0},I.equals=function(G){if(!q(G))G=E(G);if(this.unsigned!==G.unsigned&&this.high>>>31===1&&G.high>>>31===1)return!1;return this.high===G.high&&this.low===G.low},I.eq=I.equals,I.notEquals=function(G){return!this.eq(G)},I.neq=I.notEquals,I.ne=I.notEquals,I.lessThan=function(G){return this.comp(G)<0},I.lt=I.lessThan,I.lessThanOrEqual=function(G){return this.comp(G)<=0},I.lte=I.lessThanOrEqual,I.le=I.lessThanOrEqual,I.greaterThan=function(G){return this.comp(G)>0},I.gt=I.greaterThan,I.greaterThanOrEqual=function(G){return this.comp(G)>=0},I.gte=I.greaterThanOrEqual,I.ge=I.greaterThanOrEqual,I.compare=function(G){if(!q(G))G=E(G);if(this.eq(G))return 0;var L=this.isNegative(),l=G.isNegative();if(L&&!l)return-1;if(!L&&l)return 1;if(!this.unsigned)return this.sub(G).isNegative()?-1:1;return G.high>>>0>this.high>>>0||G.high===this.high&&G.low>>>0>this.low>>>0?-1:1},I.comp=I.compare,I.negate=function(){if(!this.unsigned&&this.eq(j))return j;return this.not().add(_)},I.neg=I.negate,I.add=function(G){if(!q(G))G=E(G);var L=this.high>>>16,l=this.high&65535,u=this.low>>>16,d=this.low&65535,V0=G.high>>>16,_0=G.high&65535,b0=G.low>>>16,B0=G.low&65535,Y0=0,u0=0,E0=0,d0=0;return d0+=d+B0,E0+=d0>>>16,d0&=65535,E0+=u+b0,u0+=E0>>>16,E0&=65535,u0+=l+_0,Y0+=u0>>>16,u0&=65535,Y0+=L+V0,Y0&=65535,K(E0<<16|d0,Y0<<16|u0,this.unsigned)},I.subtract=function(G){if(!q(G))G=E(G);return this.add(G.neg())},I.sub=I.subtract,I.multiply=function(G){if(this.isZero())return this;if(!q(G))G=E(G);if(Y){var L=Y.mul(this.low,this.high,G.low,G.high);return K(L,Y.get_high(),this.unsigned)}if(G.isZero())return this.unsigned?z:v;if(this.eq(j))return G.isOdd()?j:v;if(G.eq(j))return this.isOdd()?j:v;if(this.isNegative())if(G.isNegative())return this.neg().mul(G.neg());else return this.neg().mul(G).neg();else if(G.isNegative())return this.mul(G.neg()).neg();if(this.lt(S)&&G.lt(S))return Z(this.toNumber()*G.toNumber(),this.unsigned);var l=this.high>>>16,u=this.high&65535,d=this.low>>>16,V0=this.low&65535,_0=G.high>>>16,b0=G.high&65535,B0=G.low>>>16,Y0=G.low&65535,u0=0,E0=0,d0=0,o1=0;return o1+=V0*Y0,d0+=o1>>>16,o1&=65535,d0+=d*Y0,E0+=d0>>>16,d0&=65535,d0+=V0*B0,E0+=d0>>>16,d0&=65535,E0+=u*Y0,u0+=E0>>>16,E0&=65535,E0+=d*B0,u0+=E0>>>16,E0&=65535,E0+=V0*b0,u0+=E0>>>16,E0&=65535,u0+=l*Y0+u*B0+d*b0+V0*_0,u0&=65535,K(d0<<16|o1,u0<<16|E0,this.unsigned)},I.mul=I.multiply,I.divide=function(G){if(!q(G))G=E(G);if(G.isZero())throw Error("division by zero");if(Y){if(!this.unsigned&&this.high===-2147483648&&G.low===-1&&G.high===-1)return this;var L=(this.unsigned?Y.div_u:Y.div_s)(this.low,this.high,G.low,G.high);return K(L,Y.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?z:v;var l,u,d;if(!this.unsigned){if(this.eq(j))if(G.eq(_)||G.eq(k))return j;else if(G.eq(j))return _;else{var V0=this.shr(1);if(l=V0.div(G).shl(1),l.eq(v))return G.isNegative()?_:k;else return u=this.sub(G.mul(l)),d=l.add(u.div(G)),d}else if(G.eq(j))return this.unsigned?z:v;if(this.isNegative()){if(G.isNegative())return this.neg().div(G.neg());return this.neg().div(G).neg()}else if(G.isNegative())return this.div(G.neg()).neg();d=v}else{if(!G.unsigned)G=G.toUnsigned();if(G.gt(this))return z;if(G.gt(this.shru(1)))return y;d=z}u=this;while(u.gte(G)){l=Math.max(1,Math.floor(u.toNumber()/G.toNumber()));var _0=Math.ceil(Math.log(l)/Math.LN2),b0=_0<=48?1:A(2,_0-48),B0=Z(l),Y0=B0.mul(G);while(Y0.isNegative()||Y0.gt(u))l-=b0,B0=Z(l,this.unsigned),Y0=B0.mul(G);if(B0.isZero())B0=_;d=d.add(B0),u=u.sub(Y0)}return d},I.div=I.divide,I.modulo=function(G){if(!q(G))G=E(G);if(Y){var L=(this.unsigned?Y.rem_u:Y.rem_s)(this.low,this.high,G.low,G.high);return K(L,Y.get_high(),this.unsigned)}return this.sub(this.div(G).mul(G))},I.mod=I.modulo,I.rem=I.modulo,I.not=function(){return K(~this.low,~this.high,this.unsigned)},I.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},I.clz=I.countLeadingZeros,I.countTrailingZeros=function(){return this.low?X(this.low):X(this.high)+32},I.ctz=I.countTrailingZeros,I.and=function(G){if(!q(G))G=E(G);return K(this.low&G.low,this.high&G.high,this.unsigned)},I.or=function(G){if(!q(G))G=E(G);return K(this.low|G.low,this.high|G.high,this.unsigned)},I.xor=function(G){if(!q(G))G=E(G);return K(this.low^G.low,this.high^G.high,this.unsigned)},I.shiftLeft=function(G){if(q(G))G=G.toInt();if((G&=63)===0)return this;else if(G<32)return K(this.low<<G,this.high<<G|this.low>>>32-G,this.unsigned);else return K(0,this.low<<G-32,this.unsigned)},I.shl=I.shiftLeft,I.shiftRight=function(G){if(q(G))G=G.toInt();if((G&=63)===0)return this;else if(G<32)return K(this.low>>>G|this.high<<32-G,this.high>>G,this.unsigned);else return K(this.high>>G-32,this.high>=0?0:-1,this.unsigned)},I.shr=I.shiftRight,I.shiftRightUnsigned=function(G){if(q(G))G=G.toInt();if((G&=63)===0)return this;if(G<32)return K(this.low>>>G|this.high<<32-G,this.high>>>G,this.unsigned);if(G===32)return K(this.high,0,this.unsigned);return K(this.high>>>G-32,0,this.unsigned)},I.shru=I.shiftRightUnsigned,I.shr_u=I.shiftRightUnsigned,I.rotateLeft=function(G){var L;if(q(G))G=G.toInt();if((G&=63)===0)return this;if(G===32)return K(this.high,this.low,this.unsigned);if(G<32)return L=32-G,K(this.low<<G|this.high>>>L,this.high<<G|this.low>>>L,this.unsigned);return G-=32,L=32-G,K(this.high<<G|this.low>>>L,this.low<<G|this.high>>>L,this.unsigned)},I.rotl=I.rotateLeft,I.rotateRight=function(G){var L;if(q(G))G=G.toInt();if((G&=63)===0)return this;if(G===32)return K(this.high,this.low,this.unsigned);if(G<32)return L=32-G,K(this.high<<L|this.low>>>G,this.low<<L|this.high>>>G,this.unsigned);return G-=32,L=32-G,K(this.low<<L|this.high>>>G,this.high<<L|this.low>>>G,this.unsigned)},I.rotr=I.rotateRight,I.toSigned=function(){if(!this.unsigned)return this;return K(this.low,this.high,!1)},I.toUnsigned=function(){if(this.unsigned)return this;return K(this.low,this.high,!0)},I.toBytes=function(G){return G?this.toBytesLE():this.toBytesBE()},I.toBytesLE=function(){var G=this.high,L=this.low;return[L&255,L>>>8&255,L>>>16&255,L>>>24,G&255,G>>>8&255,G>>>16&255,G>>>24]},I.toBytesBE=function(){var G=this.high,L=this.low;return[G>>>24,G>>>16&255,G>>>8&255,G&255,L>>>24,L>>>16&255,L>>>8&255,L&255]},T.fromBytes=function(G,L,l){return l?T.fromBytesLE(G,L):T.fromBytesBE(G,L)},T.fromBytesLE=function(G,L){return new T(G[0]|G[1]<<8|G[2]<<16|G[3]<<24,G[4]|G[5]<<8|G[6]<<16|G[7]<<24,L)},T.fromBytesBE=function(G,L){return new T(G[4]<<24|G[5]<<16|G[6]<<8|G[7],G[0]<<24|G[1]<<16|G[2]<<8|G[3],L)},typeof BigInt==="function")T.fromBigInt=function(G,L){var l=Number(BigInt.asIntN(32,G)),u=Number(BigInt.asIntN(32,G>>BigInt(32)));return K(l,u,L)},T.fromValue=function(G,L){if(typeof G==="bigint")return T.fromBigInt(G,L);return E(G,L)},I.toBigInt=function(){var G=BigInt(this.low>>>0),L=BigInt(this.unsigned?this.high>>>0:this.high);return L<<BigInt(32)|G};var h0=$.default=T})});var tT=M((LW)=>{Object.defineProperty(LW,"__esModule",{value:!0});LW.loadFileDescriptorSetFromObject=LW.loadFileDescriptorSetFromBuffer=LW.fromJSON=LW.loadSync=LW.load=LW.IdempotencyLevel=LW.isAnyExtension=LW.Long=void 0;var AO=WK(),c1=Bq(),F5=AW(),N5=zW(),WO=IW();LW.Long=WO;function GO($){return"@type"in $&&typeof $["@type"]==="string"}LW.isAnyExtension=GO;var BW;(function($){$.IDEMPOTENCY_UNKNOWN="IDEMPOTENCY_UNKNOWN",$.NO_SIDE_EFFECTS="NO_SIDE_EFFECTS",$.IDEMPOTENT="IDEMPOTENT"})(BW=LW.IdempotencyLevel||(LW.IdempotencyLevel={}));var RW={longs:String,enums:String,bytes:String,defaults:!0,oneofs:!0,json:!0};function EO($,Y){if($==="")return Y;else return $+"."+Y}function VO($){return $ instanceof c1.Service||$ instanceof c1.Type||$ instanceof c1.Enum}function DO($){return $ instanceof c1.Namespace||$ instanceof c1.Root}function OW($,Y){let T=EO(Y,$.name);if(VO($))return[[T,$]];else if(DO($)&&typeof $.nested<"u")return Object.keys($.nested).map((q)=>{return OW($.nested[q],T)}).reduce((q,X)=>q.concat(X),[]);return[]}function E5($,Y){return function(q){return $.toObject($.decode(q),Y)}}function V5($){return function(T){if(Array.isArray(T))throw Error(`Failed to serialize message: expected object with ${$.name} structure, got array instead`);let q=$.fromObject(T);return $.encode(q).finish()}}function FO($){return($||[]).reduce((Y,T)=>{for(let[q,X]of Object.entries(T))switch(q){case"uninterpreted_option":Y.uninterpreted_option.push(T.uninterpreted_option);break;default:Y[q]=X}return Y},{deprecated:!1,idempotency_level:BW.IDEMPOTENCY_UNKNOWN,uninterpreted_option:[]})}function NO($,Y,T,q){let{resolvedRequestType:X,resolvedResponseType:J}=$;return{path:"/"+Y+"/"+$.name,requestStream:!!$.requestStream,responseStream:!!$.responseStream,requestSerialize:V5(X),requestDeserialize:E5(X,T),responseSerialize:V5(J),responseDeserialize:E5(J,T),originalName:AO($.name),requestType:D5(X,T,q),responseType:D5(J,T,q),options:FO($.parsedOptions)}}function HO($,Y,T,q){let X={};for(let J of $.methodsArray)X[J.name]=NO(J,Y,T,q);return X}function D5($,Y,T){let q=$.toDescriptor("proto3");return{format:"Protocol Buffer 3 DescriptorProto",type:q.$type.toObject(q,RW),fileDescriptorProtos:T,serialize:V5($),deserialize:E5($,Y)}}function zO($,Y){let T=$.toDescriptor("proto3");return{format:"Protocol Buffer 3 EnumDescriptorProto",type:T.$type.toObject(T,RW),fileDescriptorProtos:Y}}function IO($,Y,T,q){if($ instanceof c1.Service)return HO($,Y,T,q);else if($ instanceof c1.Type)return D5($,T,q);else if($ instanceof c1.Enum)return zO($,q);else throw Error("Type mismatch in reflection object handling")}function Pq($,Y){let T={};$.resolveAll();let X=$.toDescriptor("proto3").file.map((J)=>Buffer.from(F5.FileDescriptorProto.encode(J).finish()));for(let[J,Q]of OW($,""))T[J]=IO(Q,J,Y,X);return T}function PW($,Y){Y=Y||{};let T=c1.Root.fromDescriptor($);return T.resolveAll(),Pq(T,Y)}function MO($,Y){return(0,N5.loadProtosWithOptions)($,Y).then((T)=>{return Pq(T,Y)})}LW.load=MO;function BO($,Y){let T=(0,N5.loadProtosWithOptionsSync)($,Y);return Pq(T,Y)}LW.loadSync=BO;function RO($,Y){Y=Y||{};let T=c1.Root.fromJSON($);return T.resolveAll(),Pq(T,Y)}LW.fromJSON=RO;function OO($,Y){let T=F5.FileDescriptorSet.decode($);return PW(T,Y)}LW.loadFileDescriptorSetFromBuffer=OO;function PO($,Y){let T=F5.FileDescriptorSet.fromObject($);return PW(T,Y)}LW.loadFileDescriptorSetFromObject=PO;(0,N5.addCommonProtos)()});var y$=M((uW)=>{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(uW,"__esModule",{value:!0});uW.registerChannelzSocket=uW.registerChannelzServer=uW.registerChannelzSubchannel=uW.registerChannelzChannel=uW.ChannelzCallTrackerStub=uW.ChannelzCallTracker=uW.ChannelzChildrenTrackerStub=uW.ChannelzChildrenTracker=uW.ChannelzTrace=uW.ChannelzTraceStub=void 0;uW.unregisterChannelzRef=_O;uW.getChannelzHandlers=fW;uW.getChannelzServiceDefinition=bW;uW.setup=iO;var wq=s("net"),e$=EZ(),eT=l0(),$6=i(),vO=r0(),xO=i8(),kO=a8();function H5($){return{channel_id:$.id,name:$.name}}function z5($){return{subchannel_id:$.id,name:$.name}}function hO($){return{server_id:$.id}}function Sq($){return{socket_id:$.id,name:$.name}}var SW=32,I5=100;class vW{constructor(){this.events=[],this.creationTimestamp=new Date,this.eventsLogged=0}addTrace(){}getTraceMessage(){return{creation_timestamp:p1(this.creationTimestamp),num_events_logged:this.eventsLogged,events:[]}}}uW.ChannelzTraceStub=vW;class xW{constructor(){this.events=[],this.eventsLogged=0,this.creationTimestamp=new Date}addTrace($,Y,T){let q=new Date;if(this.events.push({description:Y,severity:$,timestamp:q,childChannel:(T===null||T===void 0?void 0:T.kind)==="channel"?T:void 0,childSubchannel:(T===null||T===void 0?void 0:T.kind)==="subchannel"?T:void 0}),this.events.length>=SW*2)this.events=this.events.slice(SW);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?H5($.childChannel):null,subchannel_ref:$.childSubchannel?z5($.childSubchannel):null}})}}}uW.ChannelzTrace=xW;class M5{constructor(){this.channelChildren=new e$.OrderedMap,this.subchannelChildren=new e$.OrderedMap,this.socketChildren=new e$.OrderedMap,this.trackerMap={["channel"]:this.channelChildren,["subchannel"]:this.subchannelChildren,["socket"]:this.socketChildren}}refChild($){let Y=this.trackerMap[$.kind],T=Y.find($.id);if(T.equals(Y.end()))Y.setElement($.id,{ref:$,count:1},T);else T.pointer[1].count+=1}unrefChild($){let Y=this.trackerMap[$.kind],T=Y.getElementByKey($.id);if(T!==void 0){if(T.count-=1,T.count===0)Y.eraseElementByKey($.id)}}getChildLists(){return{channels:this.channelChildren,subchannels:this.subchannelChildren,sockets:this.socketChildren}}}uW.ChannelzChildrenTracker=M5;class kW extends M5{refChild(){}unrefChild(){}}uW.ChannelzChildrenTrackerStub=kW;class B5{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}}uW.ChannelzCallTracker=B5;class hW extends B5{addCallStarted(){}addCallSucceeded(){}addCallFailed(){}}uW.ChannelzCallTrackerStub=hW;var Z$={["channel"]:new e$.OrderedMap,["subchannel"]:new e$.OrderedMap,["server"]:new e$.OrderedMap,["socket"]:new e$.OrderedMap},Cq=($)=>{let Y=1;function T(){return Y++}let q=Z$[$];return(X,J,Q)=>{let U=T(),Z={id:U,name:X,kind:$};if(Q)q.setElement(U,{ref:Z,getInfo:J});return Z}};uW.registerChannelzChannel=Cq("channel");uW.registerChannelzSubchannel=Cq("subchannel");uW.registerChannelzServer=Cq("server");uW.registerChannelzSocket=Cq("socket");function _O($){Z$[$.kind].eraseElementByKey($.id)}function gO($){let Y=Number.parseInt($,16);return[Y/256|0,Y%256]}function CW($){if($==="")return[];let Y=$.split(":").map((q)=>gO(q));return[].concat(...Y)}function mO($){return(0,wq.isIPv6)($)&&$.toLowerCase().startsWith("::ffff:")&&(0,wq.isIPv4)($.substring(7))}function yW($){return Buffer.from(Uint8Array.from($.split(".").map((Y)=>Number.parseInt(Y))))}function fO($){if((0,wq.isIPv4)($))return yW($);else if(mO($))return yW($.substring(7));else if((0,wq.isIPv6)($)){let Y,T,q=$.indexOf("::");if(q===-1)Y=$,T="";else Y=$.substring(0,q),T=$.substring(q+2);let X=Buffer.from(CW(Y)),J=Buffer.from(CW(T)),Q=Buffer.alloc(16-X.length-J.length,0);return Buffer.concat([X,Q,J])}else return null}function _W($){switch($){case eT.ConnectivityState.CONNECTING:return{state:"CONNECTING"};case eT.ConnectivityState.IDLE:return{state:"IDLE"};case eT.ConnectivityState.READY:return{state:"READY"};case eT.ConnectivityState.SHUTDOWN:return{state:"SHUTDOWN"};case eT.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 gW($){let Y=$.getInfo(),T=[],q=[];return Y.children.channels.forEach((X)=>{T.push(H5(X[1].ref))}),Y.children.subchannels.forEach((X)=>{q.push(z5(X[1].ref))}),{ref:H5($.ref),data:{target:Y.target,state:_W(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:T,subchannel_ref:q}}function bO($,Y){let T=parseInt($.request.channel_id,10),q=Z$.channel.getElementByKey(T);if(q===void 0){Y({code:$6.Status.NOT_FOUND,details:"No channel data found for id "+T});return}Y(null,{channel:gW(q)})}function uO($,Y){let T=parseInt($.request.max_results,10)||I5,q=[],X=parseInt($.request.start_channel_id,10),J=Z$.channel,Q;for(Q=J.lowerBound(X);!Q.equals(J.end())&&q.length<T;Q=Q.next())q.push(gW(Q.pointer[1]));Y(null,{channel:q,end:Q.equals(J.end())})}function mW($){let Y=$.getInfo(),T=[];return Y.listenerChildren.sockets.forEach((q)=>{T.push(Sq(q[1].ref))}),{ref:hO($.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:T}}function dO($,Y){let T=parseInt($.request.server_id,10),X=Z$.server.getElementByKey(T);if(X===void 0){Y({code:$6.Status.NOT_FOUND,details:"No server data found for id "+T});return}Y(null,{server:mW(X)})}function cO($,Y){let T=parseInt($.request.max_results,10)||I5,q=parseInt($.request.start_server_id,10),X=Z$.server,J=[],Q;for(Q=X.lowerBound(q);!Q.equals(X.end())&&J.length<T;Q=Q.next())J.push(mW(Q.pointer[1]));Y(null,{server:J,end:Q.equals(X.end())})}function pO($,Y){let T=parseInt($.request.subchannel_id,10),q=Z$.subchannel.getElementByKey(T);if(q===void 0){Y({code:$6.Status.NOT_FOUND,details:"No subchannel data found for id "+T});return}let X=q.getInfo(),J=[];X.children.sockets.forEach((U)=>{J.push(Sq(U[1].ref))});let Q={ref:z5(q.ref),data:{target:X.target,state:_W(X.state),calls_started:X.callTracker.callsStarted,calls_succeeded:X.callTracker.callsSucceeded,calls_failed:X.callTracker.callsFailed,last_call_started_timestamp:p1(X.callTracker.lastCallStartedTimestamp),trace:X.trace.getTraceMessage()},socket_ref:J};Y(null,{subchannel:Q})}function jW($){var Y;if((0,vO.isTcpSubchannelAddress)($))return{address:"tcpip_address",tcpip_address:{ip_address:(Y=fO($.host))!==null&&Y!==void 0?Y:void 0,port:$.port}};else return{address:"uds_address",uds_address:{filename:$.path}}}function lO($,Y){var T,q,X,J,Q;let U=parseInt($.request.socket_id,10),Z=Z$.socket.getElementByKey(U);if(Z===void 0){Y({code:$6.Status.NOT_FOUND,details:"No socket data found for id "+U});return}let K=Z.getInfo(),A=K.security?{model:"tls",tls:{cipher_suite:K.security.cipherSuiteStandardName?"standard_name":"other_name",standard_name:(T=K.security.cipherSuiteStandardName)!==null&&T!==void 0?T:void 0,other_name:(q=K.security.cipherSuiteOtherName)!==null&&q!==void 0?q:void 0,local_certificate:(X=K.security.localCertificate)!==null&&X!==void 0?X:void 0,remote_certificate:(J=K.security.remoteCertificate)!==null&&J!==void 0?J:void 0}}:null,W={ref:Sq(Z.ref),local:K.localAddress?jW(K.localAddress):null,remote:K.remoteAddress?jW(K.remoteAddress):null,remote_name:(Q=K.remoteName)!==null&&Q!==void 0?Q:void 0,security:A,data:{keep_alives_sent:K.keepAlivesSent,streams_started:K.streamsStarted,streams_succeeded:K.streamsSucceeded,streams_failed:K.streamsFailed,last_local_stream_created_timestamp:p1(K.lastLocalStreamCreatedTimestamp),last_remote_stream_created_timestamp:p1(K.lastRemoteStreamCreatedTimestamp),messages_received:K.messagesReceived,messages_sent:K.messagesSent,last_message_received_timestamp:p1(K.lastMessageReceivedTimestamp),last_message_sent_timestamp:p1(K.lastMessageSentTimestamp),local_flow_control_window:K.localFlowControlWindow?{value:K.localFlowControlWindow}:null,remote_flow_control_window:K.remoteFlowControlWindow?{value:K.remoteFlowControlWindow}:null}};Y(null,{socket:W})}function nO($,Y){let T=parseInt($.request.server_id,10),q=Z$.server.getElementByKey(T);if(q===void 0){Y({code:$6.Status.NOT_FOUND,details:"No server data found for id "+T});return}let X=parseInt($.request.start_socket_id,10),J=parseInt($.request.max_results,10)||I5,U=q.getInfo().sessionChildren.sockets,Z=[],K;for(K=U.lowerBound(X);!K.equals(U.end())&&Z.length<J;K=K.next())Z.push(Sq(K.pointer[1].ref));Y(null,{socket_ref:Z,end:K.equals(U.end())})}function fW(){return{GetChannel:bO,GetTopChannels:uO,GetServer:dO,GetServers:cO,GetSubchannel:pO,GetSocket:lO,GetServerSockets:nO}}var Lq=null;function bW(){if(Lq)return Lq;let $=tT().loadSync,Y=$("channelz.proto",{keepCase:!0,longs:String,enums:String,defaults:!0,oneofs:!0,includeDirs:[`${__dirname}/../../proto`]});return Lq=(0,kO.loadPackageDefinition)(Y).grpc.channelz.v1.Channelz.service,Lq}function iO(){(0,xO.registerAdminService)(bW,fW)}});var yq=M((cW)=>{Object.defineProperty(cW,"__esModule",{value:!0});cW.getNextCallNumber=ZP;var UP=0;function ZP(){return UP++}});var R5=M((lW)=>{Object.defineProperty(lW,"__esModule",{value:!0});lW.CompressionAlgorithms=void 0;var pW;(function($){$[$.identity=0]="identity",$[$.deflate=1]="deflate",$[$.gzip=2]="gzip"})(pW||(lW.CompressionAlgorithms=pW={}))});var O5=M((rW)=>{Object.defineProperty(rW,"__esModule",{value:!0});rW.BaseFilter=void 0;class iW{async sendMetadata($){return $}receiveMetadata($){return $}async sendMessage($){return $}async receiveMessage($){return $}receiveTrailers($){return $}}rW.BaseFilter=iW});var L5=M((TG)=>{Object.defineProperty(TG,"__esModule",{value:!0});TG.CompressionFilterFactory=TG.CompressionFilter=void 0;var jq=s("zlib"),sW=R5(),fY=i(),AP=O5(),WP=U0(),GP=($)=>{return typeof $==="number"&&typeof sW.CompressionAlgorithms[$]==="string"};class Y6{async writeMessage($,Y){let T=$;if(Y)T=await this.compressMessage(T);let q=Buffer.allocUnsafe(T.length+5);return q.writeUInt8(Y?1:0,0),q.writeUInt32BE(T.length,1),T.copy(q,5),q}async readMessage($){let Y=$.readUInt8(0)===1,T=$.slice(5);if(Y)T=await this.decompressMessage(T);return T}}class bY extends Y6{async compressMessage($){return $}async writeMessage($,Y){let T=Buffer.allocUnsafe($.length+5);return T.writeUInt8(0,0),T.writeUInt32BE($.length,1),$.copy(T,5),T}decompressMessage($){return Promise.reject(Error('Received compressed message but "grpc-encoding" header was identity'))}}class tW extends Y6{constructor($){super();this.maxRecvMessageLength=$}compressMessage($){return new Promise((Y,T)=>{jq.deflate($,(q,X)=>{if(q)T(q);else Y(X)})})}decompressMessage($){return new Promise((Y,T)=>{let q=0,X=[],J=jq.createInflate();J.on("data",(Q)=>{if(X.push(Q),q+=Q.byteLength,this.maxRecvMessageLength!==-1&&q>this.maxRecvMessageLength)J.destroy(),T({code:fY.Status.RESOURCE_EXHAUSTED,details:`Received message that decompresses to a size larger than ${this.maxRecvMessageLength}`})}),J.on("end",()=>{Y(Buffer.concat(X))}),J.write($),J.end()})}}class eW extends Y6{constructor($){super();this.maxRecvMessageLength=$}compressMessage($){return new Promise((Y,T)=>{jq.gzip($,(q,X)=>{if(q)T(q);else Y(X)})})}decompressMessage($){return new Promise((Y,T)=>{let q=0,X=[],J=jq.createGunzip();J.on("data",(Q)=>{if(X.push(Q),q+=Q.byteLength,this.maxRecvMessageLength!==-1&&q>this.maxRecvMessageLength)J.destroy(),T({code:fY.Status.RESOURCE_EXHAUSTED,details:`Received message that decompresses to a size larger than ${this.maxRecvMessageLength}`})}),J.on("end",()=>{Y(Buffer.concat(X))}),J.write($),J.end()})}}class $G extends Y6{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 oW($,Y){switch($){case"identity":return new bY;case"deflate":return new tW(Y);case"gzip":return new eW(Y);default:return new $G($)}}class P5 extends AP.BaseFilter{constructor($,Y){var T,q,X;super();this.sharedFilterConfig=Y,this.sendCompression=new bY,this.receiveCompression=new bY,this.currentCompressionAlgorithm="identity";let J=$["grpc.default_compression_algorithm"];if(this.maxReceiveMessageLength=(T=$["grpc.max_receive_message_length"])!==null&&T!==void 0?T: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,J!==void 0)if(GP(J)){let Q=sW.CompressionAlgorithms[J],U=(X=Y.serverSupportedEncodingHeader)===null||X===void 0?void 0:X.split(",");if(!U||U.includes(Q))this.currentCompressionAlgorithm=Q,this.sendCompression=oW(this.currentCompressionAlgorithm,-1)}else WP.log(fY.LogVerbosity.ERROR,`Invalid value provided for grpc.default_compression_algorithm option: ${J}`)}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=oW(q,this.maxReceiveMessageLength)}$.remove("grpc-encoding");let T=$.get("grpc-accept-encoding")[0];if(T){if(this.sharedFilterConfig.serverSupportedEncodingHeader=T,!T.split(",").includes(this.currentCompressionAlgorithm))this.sendCompression=new bY,this.currentCompressionAlgorithm="identity"}return $.remove("grpc-accept-encoding"),$}async sendMessage($){var Y;let T=await $;if(this.maxSendMessageLength!==-1&&T.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 bY)q=!1;else q=(((Y=T.flags)!==null&&Y!==void 0?Y:0)&2)===0;return{message:await this.sendCompression.writeMessage(T.message,q),flags:T.flags}}async receiveMessage($){return this.receiveCompression.readMessage(await $)}}TG.CompressionFilter=P5;class YG{constructor($,Y){this.options=Y,this.sharedFilterConfig={}}createFilter(){return new P5(this.options,this.sharedFilterConfig)}}TG.CompressionFilterFactory=YG});var T6=M((XG)=>{Object.defineProperty(XG,"__esModule",{value:!0});XG.restrictControlPlaneStatusCode=DP;var l1=i(),VP=[l1.Status.OK,l1.Status.INVALID_ARGUMENT,l1.Status.NOT_FOUND,l1.Status.ALREADY_EXISTS,l1.Status.FAILED_PRECONDITION,l1.Status.ABORTED,l1.Status.OUT_OF_RANGE,l1.Status.DATA_LOSS];function DP($,Y){if(VP.includes($))return{code:l1.Status.INTERNAL,details:`Invalid status from control plane: ${$} ${l1.Status[$]} ${Y}`};else return{code:$,details:Y}}});var uY=M((JG)=>{Object.defineProperty(JG,"__esModule",{value:!0});JG.minDeadline=NP;JG.getDeadlineTimeoutString=zP;JG.getRelativeTimeout=MP;JG.deadlineToString=BP;JG.formatDateDifference=RP;function NP(...$){let Y=1/0;for(let T of $){let q=T instanceof Date?T.getTime():T;if(q<Y)Y=q}return Y}var HP=[["m",1],["S",1000],["M",60000],["H",3600000]];function zP($){let Y=new Date().getTime();if($ instanceof Date)$=$.getTime();let T=Math.max($-Y,0);for(let[q,X]of HP){let J=T/X;if(J<1e8)return String(Math.ceil(J))+q}throw Error("Deadline is too far in the future")}var IP=2147483647;function MP($){let Y=$ instanceof Date?$.getTime():$,T=new Date().getTime(),q=Y-T;if(q<0)return 0;else if(q>IP)return 1/0;else return q}function BP($){if($ instanceof Date)return $.toISOString();else{let Y=new Date($);if(Number.isNaN(Y.getTime()))return""+$;else return Y.toISOString()}}function RP($,Y){return((Y.getTime()-$.getTime())/1000).toFixed(3)+"s"}});var vq=M((QG)=>{Object.defineProperty(QG,"__esModule",{value:!0});QG.FilterStackFactory=QG.FilterStack=void 0;class w5{constructor($){this.filters=$}sendMetadata($){let Y=$;for(let T=0;T<this.filters.length;T++)Y=this.filters[T].sendMetadata(Y);return Y}receiveMetadata($){let Y=$;for(let T=this.filters.length-1;T>=0;T--)Y=this.filters[T].receiveMetadata(Y);return Y}sendMessage($){let Y=$;for(let T=0;T<this.filters.length;T++)Y=this.filters[T].sendMessage(Y);return Y}receiveMessage($){let Y=$;for(let T=this.filters.length-1;T>=0;T--)Y=this.filters[T].receiveMessage(Y);return Y}receiveTrailers($){let Y=$;for(let T=this.filters.length-1;T>=0;T--)Y=this.filters[T].receiveTrailers(Y);return Y}push($){this.filters.unshift(...$)}getFilters(){return this.filters}}QG.FilterStack=w5;class S5{constructor($){this.factories=$}push($){this.factories.unshift(...$)}clone(){return new S5([...this.factories])}createFilter(){return new w5(this.factories.map(($)=>$.createFilter()))}}QG.FilterStackFactory=S5});var GG=M((AG)=>{Object.defineProperty(AG,"__esModule",{value:!0});AG.SingleSubchannelChannel=void 0;var yP=yq(),q6=y$(),jP=L5(),vP=l0(),X6=i(),xP=T6(),kP=uY(),hP=vq(),C5=P0(),_P=B1(),xq=p0();class ZG{constructor($,Y,T,q,X){var J,Q;this.subchannel=$,this.method=Y,this.options=q,this.callNumber=X,this.childCall=null,this.pendingMessage=null,this.readPending=!1,this.halfClosePending=!1,this.pendingStatus=null,this.readFilterPending=!1,this.writeFilterPending=!1;let U=this.method.split("/"),Z="";if(U.length>=2)Z=U[1];let K=(Q=(J=(0,xq.splitHostPort)(this.options.host))===null||J===void 0?void 0:J.host)!==null&&Q!==void 0?Q:"localhost";this.serviceUrl=`https://${K}/${Z}`;let A=(0,kP.getRelativeTimeout)(q.deadline);if(A!==1/0)if(A<=0)this.cancelWithStatus(X6.Status.DEADLINE_EXCEEDED,"Deadline exceeded");else setTimeout(()=>{this.cancelWithStatus(X6.Status.DEADLINE_EXCEEDED,"Deadline exceeded")},A);this.filterStack=T.createFilter()}cancelWithStatus($,Y){if(this.childCall)this.childCall.cancelWithStatus($,Y);else this.pendingStatus={code:$,details:Y,metadata:new C5.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()!==vP.ConnectivityState.READY){Y.onReceiveStatus({code:X6.Status.UNAVAILABLE,details:"Subchannel not ready",metadata:new C5.Metadata});return}let T=await this.filterStack.sendMetadata(Promise.resolve($)),q;try{q=await this.subchannel.getCallCredentials().generateMetadata({method_name:this.method,service_url:this.serviceUrl})}catch(J){let Q=J,{code:U,details:Z}=(0,xP.restrictControlPlaneStatusCode)(typeof Q.code==="number"?Q.code:X6.Status.UNKNOWN,`Getting metadata from plugin failed with error: ${Q.message}`);Y.onReceiveStatus({code:U,details:Z,metadata:new C5.Metadata});return}q.merge(T);let X={onReceiveMetadata:async(J)=>{Y.onReceiveMetadata(await this.filterStack.receiveMetadata(J))},onReceiveMessage:async(J)=>{this.readFilterPending=!0;let Q=await this.filterStack.receiveMessage(J);if(this.readFilterPending=!1,Y.onReceiveMessage(Q),this.pendingStatus)Y.onReceiveStatus(this.pendingStatus)},onReceiveStatus:async(J)=>{let Q=await this.filterStack.receiveTrailers(J);if(this.readFilterPending)this.pendingStatus=Q;else Y.onReceiveStatus(Q)}};if(this.childCall=this.subchannel.createCall(q,this.options.host,this.method,X),this.readPending)this.childCall.startRead();if(this.pendingMessage)this.childCall.sendMessageWithContext(this.pendingMessage.context,this.pendingMessage.message);if(this.halfClosePending&&!this.writeFilterPending)this.childCall.halfClose()}async sendMessageWithContext($,Y){this.writeFilterPending=!0;let T=await this.filterStack.sendMessage(Promise.resolve({message:Y,flags:$.flags}));if(this.writeFilterPending=!1,this.childCall){if(this.childCall.sendMessageWithContext($,T.message),this.halfClosePending)this.childCall.halfClose()}else this.pendingMessage={context:$,message:T.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 KG{constructor($,Y,T){if(this.subchannel=$,this.target=Y,this.channelzEnabled=!1,this.channelzTrace=new q6.ChannelzTrace,this.callTracker=new q6.ChannelzCallTracker,this.childrenTracker=new q6.ChannelzChildrenTracker,this.channelzEnabled=T["grpc.enable_channelz"]!==0,this.channelzRef=(0,q6.registerChannelzChannel)((0,xq.uriToString)(Y),()=>({target:`${(0,xq.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 hP.FilterStackFactory([new jP.CompressionFilterFactory(this,T)])}close(){if(this.channelzEnabled)this.childrenTracker.unrefChild(this.subchannel.getChannelzRef());(0,q6.unregisterChannelzRef)(this.channelzRef)}getTarget(){return(0,xq.uriToString)(this.target)}getConnectivityState($){throw Error("Method not implemented.")}watchConnectivityState($,Y,T){throw Error("Method not implemented.")}getChannelzRef(){return this.channelzRef}createCall($,Y){let T={deadline:Y,host:(0,_P.getDefaultAuthority)(this.target),flags:X6.Propagate.DEFAULTS,parentCall:null};return new ZG(this.subchannel,$,this.filterStackFactory,T,(0,yP.getNextCallNumber)())}}AG.SingleSubchannelChannel=KG});var FG=M((VG)=>{Object.defineProperty(VG,"__esModule",{value:!0});VG.Subchannel=void 0;var q0=l0(),gP=LY(),y5=U0(),kq=i(),mP=p0(),fP=r0(),n1=y$(),bP=GG(),uP="subchannel",dP=2147483647;class EG{constructor($,Y,T,q,X){var J;this.channelTarget=$,this.subchannelAddress=Y,this.options=T,this.connector=X,this.connectivityState=q0.ConnectivityState.IDLE,this.transport=null,this.continueConnecting=!1,this.stateListeners=new Set,this.refcount=0,this.channelzEnabled=!0,this.dataProducers=new Map,this.subchannelChannel=null;let Q={initialDelay:T["grpc.initial_reconnect_backoff_ms"],maxDelay:T["grpc.max_reconnect_backoff_ms"]};if(this.backoffTimeout=new gP.BackoffTimeout(()=>{this.handleBackoffTimer()},Q),this.backoffTimeout.unref(),this.subchannelAddressString=(0,fP.subchannelAddressToString)(Y),this.keepaliveTime=(J=T["grpc.keepalive_time_ms"])!==null&&J!==void 0?J:-1,T["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(T,void 0,2)),this.secureConnector=q._createSecureConnector($,T)}getChannelzInfo(){return{state:this.connectivityState,trace:this.channelzTrace,callTracker:this.callTracker,children:this.childrenTracker.getChildLists(),target:this.subchannelAddressString}}trace($){y5.trace(kq.LogVerbosity.DEBUG,uP,"("+this.channelzRef.id+") "+this.subchannelAddressString+" "+$)}refTrace($){y5.trace(kq.LogVerbosity.DEBUG,"subchannel_refcount","("+this.channelzRef.id+") "+this.subchannelAddressString+" "+$)}handleBackoffTimer(){if(this.continueConnecting)this.transitionToState([q0.ConnectivityState.TRANSIENT_FAILURE],q0.ConnectivityState.CONNECTING);else this.transitionToState([q0.ConnectivityState.TRANSIENT_FAILURE],q0.ConnectivityState.IDLE)}startBackoff(){this.backoffTimeout.runOnce()}stopBackoff(){this.backoffTimeout.stop(),this.backoffTimeout.reset()}startConnectingInternal(){let $=this.options;if($["grpc.keepalive_time_ms"]){let Y=Math.min(this.keepaliveTime,dP);$=Object.assign(Object.assign({},$),{"grpc.keepalive_time_ms":Y})}this.connector.connect(this.subchannelAddress,this.secureConnector,$).then((Y)=>{if(this.transitionToState([q0.ConnectivityState.CONNECTING],q0.ConnectivityState.READY)){if(this.transport=Y,this.channelzEnabled)this.childrenTracker.refChild(Y.getChannelzRef());Y.addDisconnectListener((T)=>{if(this.transitionToState([q0.ConnectivityState.READY],q0.ConnectivityState.IDLE),T&&this.keepaliveTime>0)this.keepaliveTime*=2,y5.log(kq.LogVerbosity.ERROR,`Connection to ${(0,mP.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([q0.ConnectivityState.CONNECTING],q0.ConnectivityState.TRANSIENT_FAILURE,`${Y}`)})}transitionToState($,Y,T){var q,X;if($.indexOf(this.connectivityState)===-1)return!1;if(T)this.trace(q0.ConnectivityState[this.connectivityState]+" -> "+q0.ConnectivityState[Y]+' with error "'+T+'"');else this.trace(q0.ConnectivityState[this.connectivityState]+" -> "+q0.ConnectivityState[Y]);if(this.channelzEnabled)this.channelzTrace.addTrace("CT_INFO","Connectivity state change to "+q0.ConnectivityState[Y]);let J=this.connectivityState;switch(this.connectivityState=Y,Y){case q0.ConnectivityState.READY:this.stopBackoff();break;case q0.ConnectivityState.CONNECTING:this.startBackoff(),this.startConnectingInternal(),this.continueConnecting=!1;break;case q0.ConnectivityState.TRANSIENT_FAILURE:if(this.channelzEnabled&&this.transport)this.childrenTracker.unrefChild(this.transport.getChannelzRef());if((q=this.transport)===null||q===void 0||q.shutdown(),this.transport=null,!this.backoffTimeout.isRunning())process.nextTick(()=>{this.handleBackoffTimer()});break;case q0.ConnectivityState.IDLE:if(this.channelzEnabled&&this.transport)this.childrenTracker.unrefChild(this.transport.getChannelzRef());(X=this.transport)===null||X===void 0||X.shutdown(),this.transport=null;break;default:throw Error(`Invalid state: unknown ConnectivityState ${Y}`)}for(let Q of this.stateListeners)Q(this,J,Y,this.keepaliveTime,T);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([q0.ConnectivityState.CONNECTING,q0.ConnectivityState.READY],q0.ConnectivityState.IDLE)})}unrefIfOneRef(){if(this.refcount===1)return this.unref(),!0;return!1}createCall($,Y,T,q){if(!this.transport)throw Error("Cannot create call, subchannel not READY");let X;if(this.channelzEnabled)this.callTracker.addCallStarted(),this.streamTracker.addCallStarted(),X={onCallEnd:(J)=>{if(J.code===kq.Status.OK)this.callTracker.addCallSucceeded();else this.callTracker.addCallFailed()}};else X={};return this.transport.createCall($,Y,T,q,X)}startConnecting(){process.nextTick(()=>{if(!this.transitionToState([q0.ConnectivityState.IDLE],q0.ConnectivityState.CONNECTING)){if(this.connectivityState===q0.ConnectivityState.TRANSIENT_FAILURE)this.continueConnecting=!0}})}getConnectivityState(){return this.connectivityState}addConnectivityStateListener($){this.stateListeners.add($)}removeConnectivityStateListener($){this.stateListeners.delete($)}resetBackoff(){process.nextTick(()=>{this.backoffTimeout.reset(),this.transitionToState([q0.ConnectivityState.TRANSIENT_FAILURE],q0.ConnectivityState.CONNECTING)})}getAddress(){return this.subchannelAddressString}getChannelzRef(){return this.channelzRef}isHealthy(){return!0}addHealthStateWatcher($){}removeHealthStateWatcher($){}getRealSubchannel(){return this}realSubchannelEquals($){return $.getRealSubchannel()===this}throttleKeepalive($){if($>this.keepaliveTime)this.keepaliveTime=$}getCallCredentials(){return this.secureConnector.getCallCredentials()}getChannel(){if(!this.subchannelChannel)this.subchannelChannel=new bP.SingleSubchannelChannel(this,this.channelTarget,this.options);return this.subchannelChannel}addDataWatcher($){throw Error("Not implemented")}getOrCreateDataProducer($,Y){let T=this.dataProducers.get($);if(T)return T;let q=Y(this);return this.dataProducers.set($,q),q}removeDataProducer($){this.dataProducers.delete($)}}VG.Subchannel=EG});var zG=M((NG)=>{var j5;Object.defineProperty(NG,"__esModule",{value:!0});NG.GRPC_NODE_USE_ALTERNATIVE_RESOLVER=void 0;NG.GRPC_NODE_USE_ALTERNATIVE_RESOLVER=((j5=process.env.GRPC_NODE_USE_ALTERNATIVE_RESOLVER)!==null&&j5!==void 0?j5:"false")==="true"});var k5=M((OG)=>{Object.defineProperty(OG,"__esModule",{value:!0});OG.DEFAULT_PORT=void 0;OG.setup=oP;var IG=B1(),v5=s("dns"),cP=YX(),x5=i(),dY=l$(),pP=P0(),lP=U0(),nP=i(),j$=p0(),MG=s("net"),iP=LY(),BG=zG(),rP="dns_resolver";function i1($){lP.trace(nP.LogVerbosity.DEBUG,rP,$)}OG.DEFAULT_PORT=443;var aP=30000;class RG{constructor($,Y,T){var q,X,J;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 v5.promises.Resolver,i1("Resolver constructed for target "+(0,j$.uriToString)($)),$.authority)this.alternativeResolver.setServers([$.authority]);let Q=(0,j$.splitHostPort)($.path);if(Q===null)this.ipResult=null,this.dnsHostname=null,this.port=null;else if((0,MG.isIPv4)(Q.host)||(0,MG.isIPv6)(Q.host))this.ipResult=[{addresses:[{host:Q.host,port:(q=Q.port)!==null&&q!==void 0?q:OG.DEFAULT_PORT}]}],this.dnsHostname=null,this.port=null;else this.ipResult=null,this.dnsHostname=Q.host,this.port=(X=Q.port)!==null&&X!==void 0?X:OG.DEFAULT_PORT;if(this.percentage=Math.random()*100,T["grpc.service_config_disable_resolution"]===1)this.isServiceConfigEnabled=!1;this.defaultResolutionError={code:x5.Status.UNAVAILABLE,details:`Name resolution failed for target ${(0,j$.uriToString)(this.target)}`,metadata:new pP.Metadata};let U={initialDelay:T["grpc.initial_reconnect_backoff_ms"],maxDelay:T["grpc.max_reconnect_backoff_ms"]};this.backoff=new iP.BackoffTimeout(()=>{if(this.continueResolving)this.startResolutionWithBackoff()},U),this.backoff.unref(),this.minTimeBetweenResolutionsMs=(J=T["grpc.dns_min_time_between_resolutions_ms"])!==null&&J!==void 0?J:aP,this.nextResolutionTimer=setTimeout(()=>{},0),clearTimeout(this.nextResolutionTimer)}startResolution(){if(this.ipResult!==null){if(!this.returnedIpResult)i1("Returning IP address for target "+(0,j$.uriToString)(this.target)),setImmediate(()=>{this.listener((0,dY.statusOrFromValue)(this.ipResult),{},null,"")}),this.returnedIpResult=!0;this.backoff.stop(),this.backoff.reset(),this.stopNextResolutionTimer();return}if(this.dnsHostname===null)i1("Failed to parse DNS address "+(0,j$.uriToString)(this.target)),setImmediate(()=>{this.listener((0,dY.statusOrFromError)({code:x5.Status.UNAVAILABLE,details:`Failed to parse DNS address ${(0,j$.uriToString)(this.target)}`}),{},null,"")}),this.stopNextResolutionTimer();else{if(this.pendingLookupPromise!==null)return;i1("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,dY.statusOrFromValue)(Y.map((X)=>({addresses:[X]})));let T="["+Y.map((X)=>X.host+":"+X.port).join(",")+"]";i1("Resolved addresses for target "+(0,j$.uriToString)(this.target)+": "+T);let q=this.listener(this.latestLookupResult,{},this.latestServiceConfigResult,"");this.handleHealthStatus(q)},(Y)=>{if(this.pendingLookupPromise===null)return;i1("Resolution error for target "+(0,j$.uriToString)(this.target)+": "+Y.message),this.pendingLookupPromise=null,this.stopNextResolutionTimer(),this.listener((0,dY.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 T;try{if(T=(0,cP.extractAndSelectServiceConfig)(Y,this.percentage),T)this.latestServiceConfigResult=(0,dY.statusOrFromValue)(T);else this.latestServiceConfigResult=null}catch(q){this.latestServiceConfigResult=(0,dY.statusOrFromError)({code:x5.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(BG.GRPC_NODE_USE_ALTERNATIVE_RESOLVER){i1("Using alternative DNS resolver.");let T=await Promise.allSettled([this.alternativeResolver.resolve4($),this.alternativeResolver.resolve6($)]);if(T.every((q)=>q.status==="rejected"))throw Error(T[0].reason);return T.reduce((q,X)=>{return X.status==="fulfilled"?[...q,...X.value]:q},[]).map((q)=>({host:q,port:+this.port}))}return(await v5.promises.lookup($,{all:!0})).map((T)=>({host:T.address,port:+this.port}))}async resolveTxt($){if(BG.GRPC_NODE_USE_ALTERNATIVE_RESOLVER)return i1("Using alternative DNS resolver."),this.alternativeResolver.resolveTxt($);return v5.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)i1('resolution update delayed by "min time between resolutions" rate limit');else i1("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 oP(){(0,IG.registerResolver)("dns",RG),(0,IG.registerDefaultScheme)("dns")}});var h5=M((CG)=>{Object.defineProperty(CG,"__esModule",{value:!0});CG.parseCIDR=wG;CG.mapProxyName=UL;CG.getProxiedConnection=ZL;var J6=U0(),cY=i(),LG=s("net"),tP=s("http"),eP=U0(),PG=r0(),Q6=p0(),$L=s("url"),YL=k5(),TL="proxy";function pY($){eP.trace(cY.LogVerbosity.DEBUG,TL,$)}function qL(){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 T;try{T=new $L.URL($)}catch(U){return(0,J6.log)(cY.LogVerbosity.ERROR,`cannot parse value of "${Y}" env var`),{}}if(T.protocol!=="http:")return(0,J6.log)(cY.LogVerbosity.ERROR,`"${T.protocol}" scheme not supported in proxy URI`),{};let q=null;if(T.username)if(T.password)(0,J6.log)(cY.LogVerbosity.INFO,"userinfo found in proxy URI"),q=decodeURIComponent(`${T.username}:${T.password}`);else q=T.username;let{hostname:X,port:J}=T;if(J==="")J="80";let Q={address:`${X}:${J}`};if(q)Q.creds=q;return pY("Proxy server "+Q.address+" set by environment variable "+Y),Q}function XL(){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 wG($){let Y=$.split("/");if(Y.length!==2)return null;let T=parseInt(Y[1],10);if(!(0,LG.isIPv4)(Y[0])||Number.isNaN(T)||T<0||T>32)return null;return{ip:SG(Y[0]),prefixLength:T}}function SG($){return $.split(".").reduce((Y,T)=>(Y<<8)+parseInt(T,10),0)}function JL($,Y){let T=$.ip,q=-1<<32-$.prefixLength;return(SG(Y)&q)===(T&q)}function QL($){for(let Y of XL()){let T=wG(Y);if((0,LG.isIPv4)($)&&T&&JL(T,$))return!0;else if($.endsWith(Y))return!0}return!1}function UL($,Y){var T;let q={target:$,extraOptions:{}};if(((T=Y["grpc.enable_http_proxy"])!==null&&T!==void 0?T:1)===0)return q;if($.scheme==="unix")return q;let X=qL();if(!X.address)return q;let J=(0,Q6.splitHostPort)($.path);if(!J)return q;let Q=J.host;if(QL(Q))return pY("Not using proxy for target in no_proxy list: "+(0,Q6.uriToString)($)),q;let U={"grpc.http_connect_target":(0,Q6.uriToString)($)};if(X.creds)U["grpc.http_connect_creds"]=X.creds;return{target:{scheme:"dns",path:X.address},extraOptions:U}}function ZL($,Y){var T;if(!("grpc.http_connect_target"in Y))return Promise.resolve(null);let q=Y["grpc.http_connect_target"],X=(0,Q6.parseUri)(q);if(X===null)return Promise.resolve(null);let J=(0,Q6.splitHostPort)(X.path);if(J===null)return Promise.resolve(null);let Q=`${J.host}:${(T=J.port)!==null&&T!==void 0?T:YL.DEFAULT_PORT}`,U={method:"CONNECT",path:Q},Z={Host:Q};if((0,PG.isTcpSubchannelAddress)($))U.host=$.host,U.port=$.port;else U.socketPath=$.path;if("grpc.http_connect_creds"in Y)Z["Proxy-Authorization"]="Basic "+Buffer.from(Y["grpc.http_connect_creds"]).toString("base64");U.headers=Z;let K=(0,PG.subchannelAddressToString)($);return pY("Using proxy "+K+" to connect to "+U.path),new Promise((A,W)=>{let E=tP.request(U);E.once("connect",(D,F,H)=>{if(E.removeAllListeners(),F.removeAllListeners(),D.statusCode===200){if(pY("Successfully connected to "+U.path+" through proxy "+K),H.length>0)F.unshift(H);pY("Successfully established a plaintext connection to "+U.path+" through proxy "+K),A(F)}else(0,J6.log)(cY.LogVerbosity.ERROR,"Failed to connect to "+U.path+" through proxy "+K+" with status "+D.statusCode),W()}),E.once("error",(D)=>{E.removeAllListeners(),(0,J6.log)(cY.LogVerbosity.ERROR,"Failed to connect to proxy "+K+" with error "+D.message),W()}),E.end()})}});var _5=M((jG)=>{Object.defineProperty(jG,"__esModule",{value:!0});jG.StreamDecoder=void 0;var r1;(function($){$[$.NO_DATA=0]="NO_DATA",$[$.READING_SIZE=1]="READING_SIZE",$[$.READING_MESSAGE=2]="READING_MESSAGE"})(r1||(r1={}));class yG{constructor($){this.maxReadMessageLength=$,this.readState=r1.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,T,q=[];while(Y<$.length)switch(this.readState){case r1.NO_DATA:this.readCompressFlag=$.slice(Y,Y+1),Y+=1,this.readState=r1.READING_SIZE,this.readPartialSize.fill(0),this.readSizeRemaining=4,this.readMessageSize=0,this.readMessageRemaining=0,this.readPartialMessage=[];break;case r1.READING_SIZE:if(T=Math.min($.length-Y,this.readSizeRemaining),$.copy(this.readPartialSize,4-this.readSizeRemaining,Y,Y+T),this.readSizeRemaining-=T,Y+=T,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=r1.READING_MESSAGE;else{let X=Buffer.concat([this.readCompressFlag,this.readPartialSize],5);this.readState=r1.NO_DATA,q.push(X)}}break;case r1.READING_MESSAGE:if(T=Math.min($.length-Y,this.readMessageRemaining),this.readPartialMessage.push($.slice(Y,Y+T)),this.readMessageRemaining-=T,Y+=T,this.readMessageRemaining===0){let X=[this.readCompressFlag,this.readPartialSize].concat(this.readPartialMessage),J=Buffer.concat(X,this.readMessageSize+5);this.readState=r1.NO_DATA,q.push(J)}break;default:throw Error("Unexpected read state")}return q}}jG.StreamDecoder=yG});var _G=M((kG)=>{Object.defineProperty(kG,"__esModule",{value:!0});kG.Http2SubchannelCall=void 0;var K$=s("http2"),GL=s("os"),X0=i(),A$=P0(),EL=_5(),VL=U0(),DL=i(),FL="subchannel_call";function NL($){for(let[Y,T]of Object.entries(GL.constants.errno))if(T===$)return Y;return"Unknown system error "+$}function g5($){let Y=`Received HTTP status code ${$}`,T;switch($){case 400:T=X0.Status.INTERNAL;break;case 401:T=X0.Status.UNAUTHENTICATED;break;case 403:T=X0.Status.PERMISSION_DENIED;break;case 404:T=X0.Status.UNIMPLEMENTED;break;case 429:case 502:case 503:case 504:T=X0.Status.UNAVAILABLE;break;default:T=X0.Status.UNKNOWN}return{code:T,details:Y,metadata:new A$.Metadata}}class xG{constructor($,Y,T,q,X){var J;this.http2Stream=$,this.callEventTracker=Y,this.listener=T,this.transport=q,this.callId=X,this.isReadFilterPending=!1,this.isPushPending=!1,this.canPush=!1,this.readsClosed=!1,this.statusOutput=!1,this.unpushedReadMessages=[],this.finalStatus=null,this.internalError=null,this.serverEndedCall=!1,this.connectionDropped=!1;let Q=(J=q.getOptions()["grpc.max_receive_message_length"])!==null&&J!==void 0?J:X0.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH;this.decoder=new EL.StreamDecoder(Q),$.on("response",(U,Z)=>{let K="";for(let A of Object.keys(U))K+="\t\t"+A+": "+U[A]+`
16
+ `;if(this.trace(`Received server headers:
17
+ `+K),this.httpStatusCode=U[":status"],Z&K$.constants.NGHTTP2_FLAG_END_STREAM)this.handleTrailers(U);else{let A;try{A=A$.Metadata.fromHttp2Headers(U)}catch(W){this.endCall({code:X0.Status.UNKNOWN,details:W.message,metadata:new A$.Metadata});return}this.listener.onReceiveMetadata(A)}}),$.on("trailers",(U)=>{this.handleTrailers(U)}),$.on("data",(U)=>{if(this.statusOutput)return;this.trace("receive HTTP/2 data frame of length "+U.length);let Z;try{Z=this.decoder.write(U)}catch(K){if(this.httpStatusCode!==void 0&&this.httpStatusCode!==200){let A=g5(this.httpStatusCode);this.cancelWithStatus(A.code,A.details)}else this.cancelWithStatus(X0.Status.RESOURCE_EXHAUSTED,K.message);return}for(let K of Z)this.trace("parsed message of length "+K.length),this.callEventTracker.addMessageReceived(),this.tryPush(K)}),$.on("end",()=>{this.readsClosed=!0,this.maybeOutputStatus()}),$.on("close",()=>{this.serverEndedCall=!0,process.nextTick(()=>{var U;if(this.trace("HTTP/2 stream closed with code "+$.rstCode),((U=this.finalStatus)===null||U===void 0?void 0:U.code)===X0.Status.OK)return;let Z,K="";switch($.rstCode){case K$.constants.NGHTTP2_NO_ERROR:if(this.finalStatus!==null)return;if(this.httpStatusCode&&this.httpStatusCode!==200){let A=g5(this.httpStatusCode);Z=A.code,K=A.details}else Z=X0.Status.INTERNAL,K=`Received RST_STREAM with code ${$.rstCode} (Call ended without gRPC status)`;break;case K$.constants.NGHTTP2_REFUSED_STREAM:Z=X0.Status.UNAVAILABLE,K="Stream refused by server";break;case K$.constants.NGHTTP2_CANCEL:if(this.connectionDropped)Z=X0.Status.UNAVAILABLE,K="Connection dropped";else Z=X0.Status.CANCELLED,K="Call cancelled";break;case K$.constants.NGHTTP2_ENHANCE_YOUR_CALM:Z=X0.Status.RESOURCE_EXHAUSTED,K="Bandwidth exhausted or memory limit exceeded";break;case K$.constants.NGHTTP2_INADEQUATE_SECURITY:Z=X0.Status.PERMISSION_DENIED,K="Protocol not secure enough";break;case K$.constants.NGHTTP2_INTERNAL_ERROR:if(Z=X0.Status.INTERNAL,this.internalError===null)K=`Received RST_STREAM with code ${$.rstCode} (Internal server error)`;else if(this.internalError.code==="ECONNRESET"||this.internalError.code==="ETIMEDOUT")Z=X0.Status.UNAVAILABLE,K=this.internalError.message;else K=`Received RST_STREAM with code ${$.rstCode} triggered by internal client error: ${this.internalError.message}`;break;default:Z=X0.Status.INTERNAL,K=`Received RST_STREAM with code ${$.rstCode}`}this.endCall({code:Z,details:K,metadata:new A$.Metadata,rstCode:$.rstCode})})}),$.on("error",(U)=>{if(U.code!=="ERR_HTTP2_STREAM_ERROR")this.trace("Node error event: message="+U.message+" code="+U.code+" errno="+NL(U.errno)+" syscall="+U.syscall),this.internalError=U;this.callEventTracker.onStreamEnd(!1)})}getDeadlineInfo(){return[`remote_addr=${this.getPeer()}`]}onDisconnect(){this.connectionDropped=!0,setImmediate(()=>{this.endCall({code:X0.Status.UNAVAILABLE,details:"Connection dropped",metadata:new A$.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($){VL.trace(DL.LogVerbosity.DEBUG,FL,"["+this.callId+"] "+$)}endCall($){if(this.finalStatus===null||this.finalStatus.code===X0.Status.OK)this.finalStatus=$,this.maybeOutputStatus();this.destroyHttp2Stream()}maybeOutputStatus(){if(this.finalStatus!==null){if(this.finalStatus.code!==X0.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 J of Object.keys($))Y+="\t\t"+J+": "+$[J]+`
18
+ `;this.trace(`Received server trailers:
19
+ `+Y);let T;try{T=A$.Metadata.fromHttp2Headers($)}catch(J){T=new A$.Metadata}let q=T.getMap(),X;if(typeof q["grpc-status"]==="string"){let J=Number(q["grpc-status"]);this.trace("received status code "+J+" from server"),T.remove("grpc-status");let Q="";if(typeof q["grpc-message"]==="string"){try{Q=decodeURI(q["grpc-message"])}catch(U){Q=q["grpc-message"]}T.remove("grpc-message"),this.trace('received status details string "'+Q+'" from server')}X={code:J,details:Q,metadata:T}}else if(this.httpStatusCode)X=g5(this.httpStatusCode),X.metadata=T;else X={code:X0.Status.UNKNOWN,details:"No status information received",metadata:T};this.endCall(X)}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)===X0.Status.OK)Y=K$.constants.NGHTTP2_NO_ERROR;else Y=K$.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 A$.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!==X0.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 T=(q)=>{process.nextTick(()=>{var X;let J=X0.Status.UNAVAILABLE;if((q===null||q===void 0?void 0:q.code)==="ERR_STREAM_WRITE_AFTER_END")J=X0.Status.INTERNAL;if(q)this.cancelWithStatus(J,`Write error: ${q.message}`);(X=$.callback)===null||X===void 0||X.call($)})};this.trace("sending data chunk of length "+Y.length),this.callEventTracker.addMessageSent();try{this.http2Stream.write(Y,T)}catch(q){this.endCall({code:X0.Status.UNAVAILABLE,details:`Write failed with error ${q.message}`,metadata:new A$.Metadata})}}halfClose(){this.trace("end() called"),this.trace("calling end() on HTTP/2 stream"),this.http2Stream.end()}}kG.Http2SubchannelCall=xG});var uG=M((fG)=>{Object.defineProperty(fG,"__esModule",{value:!0});fG.Http2SubchannelConnector=void 0;var $Y=s("http2"),HL=s("tls"),_q=y$(),U6=i(),zL=h5(),lY=U0(),IL=B1(),gq=r0(),m5=p0(),ML=s("net"),BL=_G(),RL=yq(),f5="transport",OL="transport_flowctrl",PL=m4().version,{HTTP2_HEADER_AUTHORITY:LL,HTTP2_HEADER_CONTENT_TYPE:wL,HTTP2_HEADER_METHOD:SL,HTTP2_HEADER_PATH:CL,HTTP2_HEADER_TE:yL,HTTP2_HEADER_USER_AGENT:jL}=$Y.constants,vL=20000,xL=Buffer.from("too_many_pings","ascii");class gG{constructor($,Y,T,q){if(this.session=$,this.options=T,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,gq.subchannelAddressToString)(Y),T["grpc.enable_channelz"]===0)this.channelzEnabled=!1,this.streamTracker=new _q.ChannelzCallTrackerStub;else this.streamTracker=new _q.ChannelzCallTracker;if(this.channelzRef=(0,_q.registerChannelzSocket)(this.subchannelAddressString,()=>this.getChannelzInfo(),this.channelzEnabled),this.userAgent=[T["grpc.primary_user_agent"],`grpc-node-js/${PL}`,T["grpc.secondary_user_agent"]].filter((X)=>X).join(" "),"grpc.keepalive_time_ms"in T)this.keepaliveTimeMs=T["grpc.keepalive_time_ms"];else this.keepaliveTimeMs=-1;if("grpc.keepalive_timeout_ms"in T)this.keepaliveTimeoutMs=T["grpc.keepalive_timeout_ms"];else this.keepaliveTimeoutMs=vL;if("grpc.keepalive_permit_without_calls"in T)this.keepaliveWithoutCalls=T["grpc.keepalive_permit_without_calls"]===1;else this.keepaliveWithoutCalls=!1;if($.once("close",()=>{this.trace("session closed"),this.handleDisconnect()}),$.once("goaway",(X,J,Q)=>{let U=!1;if(X===$Y.constants.NGHTTP2_ENHANCE_YOUR_CALM&&Q&&Q.equals(xL))U=!0;this.trace("connection closed by GOAWAY with code "+X+" and data "+(Q===null||Q===void 0?void 0:Q.toString())),this.reportDisconnectToOwner(U)}),$.once("error",(X)=>{this.trace("connection closed with error "+X.message),this.handleDisconnect()}),$.socket.once("close",(X)=>{this.trace("connection closed. hadError="+X),this.handleDisconnect()}),lY.isTracerEnabled(f5))$.on("remoteSettings",(X)=>{this.trace("new settings received"+(this.session!==$?" on the old connection":"")+": "+JSON.stringify(X))}),$.on("localSettings",(X)=>{this.trace("local settings acknowledged by remote"+(this.session!==$?" on the old connection":"")+": "+JSON.stringify(X))});if(this.keepaliveWithoutCalls)this.maybeStartKeepalivePingTimer();if($.socket instanceof HL.TLSSocket)this.authContext={transportSecurityType:"ssl",sslPeerCertificate:$.socket.getPeerCertificate()};else this.authContext={}}getChannelzInfo(){var $,Y,T;let q=this.session.socket,X=q.remoteAddress?(0,gq.stringToSubchannelAddress)(q.remoteAddress,q.remotePort):null,J=q.localAddress?(0,gq.stringToSubchannelAddress)(q.localAddress,q.localPort):null,Q;if(this.session.encrypted){let Z=q,K=Z.getCipher(),A=Z.getCertificate(),W=Z.getPeerCertificate();Q={cipherSuiteStandardName:($=K.standardName)!==null&&$!==void 0?$:null,cipherSuiteOtherName:K.standardName?null:K.name,localCertificate:A&&"raw"in A?A.raw:null,remoteCertificate:W&&"raw"in W?W.raw:null}}else Q=null;return{remoteAddress:X,localAddress:J,security:Q,remoteName:this.remoteName,streamsStarted:this.streamTracker.callsStarted,streamsSucceeded:this.streamTracker.callsSucceeded,streamsFailed:this.streamTracker.callsFailed,messagesSent:this.messagesSent,messagesReceived:this.messagesReceived,keepAlivesSent:this.keepalivesSent,lastLocalStreamCreatedTimestamp:this.streamTracker.lastCallStartedTimestamp,lastRemoteStreamCreatedTimestamp:null,lastMessageSentTimestamp:this.lastMessageSentTimestamp,lastMessageReceivedTimestamp:this.lastMessageReceivedTimestamp,localFlowControlWindow:(Y=this.session.state.localWindowSize)!==null&&Y!==void 0?Y:null,remoteFlowControlWindow:(T=this.session.state.remoteWindowSize)!==null&&T!==void 0?T:null}}trace($){lY.trace(U6.LogVerbosity.DEBUG,f5,"("+this.channelzRef.id+") "+this.subchannelAddressString+" "+$)}keepaliveTrace($){lY.trace(U6.LogVerbosity.DEBUG,"keepalive","("+this.channelzRef.id+") "+this.subchannelAddressString+" "+$)}flowControlTrace($){lY.trace(U6.LogVerbosity.DEBUG,OL,"("+this.channelzRef.id+") "+this.subchannelAddressString+" "+$)}internalsTrace($){lY.trace(U6.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 T="";try{if(!this.session.ping((X,J,Q)=>{if(this.clearKeepaliveTimeout(),X)this.keepaliveTrace("Ping failed with error "+X.message),this.handleDisconnect();else this.keepaliveTrace("Received ping response"),this.maybeStartKeepalivePingTimer()}))T="Ping returned false"}catch(q){T=(q instanceof Error?q.message:"")||"Unknown error"}if(T)this.keepaliveTrace("Ping send failed: "+T),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,T,q,X){let J=$.toHttp2Headers();J[LL]=Y,J[jL]=this.userAgent,J[wL]="application/grpc",J[SL]="POST",J[CL]=T,J[yL]="trailers";let Q;try{Q=this.session.request(J)}catch(K){throw this.handleDisconnect(),K}this.flowControlTrace("local window size: "+this.session.state.localWindowSize+" remote window size: "+this.session.state.remoteWindowSize),this.internalsTrace("session.closed="+this.session.closed+" session.destroyed="+this.session.destroyed+" session.socket.destroyed="+this.session.socket.destroyed);let U,Z;if(this.channelzEnabled)this.streamTracker.addCallStarted(),U={addMessageSent:()=>{var K;this.messagesSent+=1,this.lastMessageSentTimestamp=new Date,(K=X.addMessageSent)===null||K===void 0||K.call(X)},addMessageReceived:()=>{var K;this.messagesReceived+=1,this.lastMessageReceivedTimestamp=new Date,(K=X.addMessageReceived)===null||K===void 0||K.call(X)},onCallEnd:(K)=>{var A;(A=X.onCallEnd)===null||A===void 0||A.call(X,K),this.removeActiveCall(Z)},onStreamEnd:(K)=>{var A;if(K)this.streamTracker.addCallSucceeded();else this.streamTracker.addCallFailed();(A=X.onStreamEnd)===null||A===void 0||A.call(X,K)}};else U={addMessageSent:()=>{var K;(K=X.addMessageSent)===null||K===void 0||K.call(X)},addMessageReceived:()=>{var K;(K=X.addMessageReceived)===null||K===void 0||K.call(X)},onCallEnd:(K)=>{var A;(A=X.onCallEnd)===null||A===void 0||A.call(X,K),this.removeActiveCall(Z)},onStreamEnd:(K)=>{var A;(A=X.onStreamEnd)===null||A===void 0||A.call(X,K)}};return Z=new BL.Http2SubchannelCall(Q,U,q,this,(0,RL.getNextCallNumber)()),this.addActiveCall(Z),Z}getChannelzRef(){return this.channelzRef}getPeerName(){return this.subchannelAddressString}getOptions(){return this.options}getAuthContext(){return this.authContext}shutdown(){this.session.close(),(0,_q.unregisterChannelzRef)(this.channelzRef)}}class mG{constructor($){this.channelTarget=$,this.session=null,this.isShutdown=!1}trace($){lY.trace(U6.LogVerbosity.DEBUG,f5,(0,m5.uriToString)(this.channelTarget)+" "+$)}createSession($,Y,T){if(this.isShutdown)return Promise.reject();if($.socket.closed)return Promise.reject("Connection closed before starting HTTP/2 handshake");return new Promise((q,X)=>{var J,Q,U,Z,K,A,W,E;let D=null,F=this.channelTarget;if("grpc.http_connect_target"in T){let C=(0,m5.parseUri)(T["grpc.http_connect_target"]);if(C)F=C,D=(0,m5.uriToString)(C)}let H=$.secure?"https":"http",V=(0,IL.getDefaultAuthority)(F),B=()=>{var C;(C=this.session)===null||C===void 0||C.destroy(),this.session=null,setImmediate(()=>{if(!m)m=!0,X(`${k.trim()} (${new Date().toISOString()})`)})},S=(C)=>{var j;if((j=this.session)===null||j===void 0||j.destroy(),k=C.message,this.trace("connection failed with error "+k),!m)m=!0,X(`${k} (${new Date().toISOString()})`)},v={createConnection:(C,j)=>{return $.socket},settings:{initialWindowSize:(Z=(J=T["grpc-node.flow_control_window"])!==null&&J!==void 0?J:(U=(Q=$Y.getDefaultSettings)===null||Q===void 0?void 0:Q.call($Y))===null||U===void 0?void 0:U.initialWindowSize)!==null&&Z!==void 0?Z:65535},maxSendHeaderBlockLength:Number.MAX_SAFE_INTEGER,maxSessionMemory:(K=T["grpc-node.max_session_memory"])!==null&&K!==void 0?K:Number.MAX_SAFE_INTEGER},z=$Y.connect(`${H}://${V}`,v),_=(E=(W=(A=$Y.getDefaultSettings)===null||A===void 0?void 0:A.call($Y))===null||W===void 0?void 0:W.initialWindowSize)!==null&&E!==void 0?E:65535,y=T["grpc-node.flow_control_window"];this.session=z;let k="Failed to connect",m=!1;z.unref(),z.once("remoteSettings",()=>{var C;if(y&&y>_)try{z.setLocalWindowSize(y)}catch(j){let I=y-((C=z.state.localWindowSize)!==null&&C!==void 0?C:_);if(I>0)z.incrementWindowSize(I)}z.removeAllListeners(),$.socket.removeListener("close",B),$.socket.removeListener("error",S),q(new gG(z,Y,T,D)),this.session=null}),z.once("close",B),z.once("error",S),$.socket.once("close",B),$.socket.once("error",S)})}tcpConnect($,Y){return(0,zL.getProxiedConnection)($,Y).then((T)=>{if(T)return T;else return new Promise((q,X)=>{let J=()=>{X(Error("Socket closed"))},Q=(Z)=>{X(Z)},U=ML.connect($,()=>{U.removeListener("close",J),U.removeListener("error",Q),q(U)});U.once("close",J),U.once("error",Q)})})}async connect($,Y,T){if(this.isShutdown)return Promise.reject();let q=null,X=null,J=(0,gq.subchannelAddressToString)($);try{return this.trace(J+" Waiting for secureConnector to be ready"),await Y.waitForReady(),this.trace(J+" secureConnector is ready"),q=await this.tcpConnect($,T),q.setNoDelay(),this.trace(J+" Established TCP connection"),X=await Y.connect(q),this.trace(J+" Established secure connection"),this.createSession(X,$,T)}catch(Q){throw q===null||q===void 0||q.destroy(),X===null||X===void 0||X.socket.destroy(),Q}}shutdown(){var $;this.isShutdown=!0,($=this.session)===null||$===void 0||$.close(),this.session=null}}fG.Http2SubchannelConnector=mG});var pG=M((dG)=>{Object.defineProperty(dG,"__esModule",{value:!0});dG.SubchannelPool=void 0;dG.getSubchannelPool=uL;var kL=t7(),hL=FG(),_L=r0(),gL=p0(),mL=uG(),fL=1e4;class mq{constructor(){this.pool=Object.create(null),this.cleanupTimer=null}unrefUnusedSubchannels(){let $=!0;for(let Y in this.pool){let q=this.pool[Y].filter((X)=>!X.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()},fL),(Y=($=this.cleanupTimer).unref)===null||Y===void 0||Y.call($)}getOrCreateSubchannel($,Y,T,q){this.ensureCleanupTask();let X=(0,gL.uriToString)($);if(X in this.pool){let Q=this.pool[X];for(let U of Q)if((0,_L.subchannelAddressEqual)(Y,U.subchannelAddress)&&(0,kL.channelOptionsEqual)(T,U.channelArguments)&&q._equals(U.channelCredentials))return U.subchannel}let J=new hL.Subchannel($,Y,T,q,new mL.Http2SubchannelConnector($));if(!(X in this.pool))this.pool[X]=[];return this.pool[X].push({subchannelAddress:Y,channelArguments:T,channelCredentials:q,subchannel:J}),J.ref(),J}}dG.SubchannelPool=mq;var bL=new mq;function uL($){if($)return bL;else return new mq}});var oG=M((rG)=>{Object.defineProperty(rG,"__esModule",{value:!0});rG.LoadBalancingCall=void 0;var lG=l0(),fq=i(),nG=uY(),bq=P0(),Z6=Y$(),cL=p0(),pL=U0(),b5=T6(),lL=s("http2"),nL="load_balancing_call";class iG{constructor($,Y,T,q,X,J,Q){var U,Z;this.channel=$,this.callConfig=Y,this.methodName=T,this.host=q,this.credentials=X,this.deadline=J,this.callNumber=Q,this.child=null,this.readPending=!1,this.pendingMessage=null,this.pendingHalfClose=!1,this.ended=!1,this.metadata=null,this.listener=null,this.onCallEnded=null,this.childStartTime=null;let K=this.methodName.split("/"),A="";if(K.length>=2)A=K[1];let W=(Z=(U=(0,cL.splitHostPort)(this.host))===null||U===void 0?void 0:U.host)!==null&&Z!==void 0?Z:"localhost";this.serviceUrl=`https://${W}/${A}`,this.startTime=new Date}getDeadlineInfo(){var $,Y;let T=[];if(this.childStartTime){if(this.childStartTime>this.startTime){if(($=this.metadata)===null||$===void 0?void 0:$.getOptions().waitForReady)T.push("wait_for_ready");T.push(`LB pick: ${(0,nG.formatDateDifference)(this.startTime,this.childStartTime)}`)}return T.push(...this.child.getDeadlineInfo()),T}else{if((Y=this.metadata)===null||Y===void 0?void 0:Y.getOptions().waitForReady)T.push("wait_for_ready");T.push("Waiting for LB pick")}return T}trace($){pL.trace(fq.LogVerbosity.DEBUG,nL,"["+this.callNumber+"] "+$)}outputStatus($,Y){var T,q;if(!this.ended){this.ended=!0,this.trace("ended with status: code="+$.code+' details="'+$.details+'" start time='+this.startTime.toISOString());let X=Object.assign(Object.assign({},$),{progress:Y});(T=this.listener)===null||T===void 0||T.onReceiveStatus(X),(q=this.onCallEnded)===null||q===void 0||q.call(this,X.code,X.details,X.metadata)}}doPick(){var $,Y;if(this.ended)return;if(!this.metadata)throw Error("doPick called before start");this.trace("Pick called");let T=this.metadata.clone(),q=this.channel.doPick(T,this.callConfig.pickInformation),X=q.subchannel?"("+q.subchannel.getChannelzRef().id+") "+q.subchannel.getAddress():""+q.subchannel;switch(this.trace("Pick result: "+Z6.PickResultType[q.pickResultType]+" subchannel: "+X+" status: "+(($=q.status)===null||$===void 0?void 0:$.code)+" "+((Y=q.status)===null||Y===void 0?void 0:Y.details)),q.pickResultType){case Z6.PickResultType.COMPLETE:this.credentials.compose(q.subchannel.getCallCredentials()).generateMetadata({method_name:this.methodName,service_url:this.serviceUrl}).then((Z)=>{var K;if(this.ended){this.trace("Credentials metadata generation finished after call ended");return}if(T.merge(Z),T.get("authorization").length>1)this.outputStatus({code:fq.Status.INTERNAL,details:'"authorization" metadata cannot have multiple values',metadata:new bq.Metadata},"PROCESSED");if(q.subchannel.getConnectivityState()!==lG.ConnectivityState.READY){this.trace("Picked subchannel "+X+" has state "+lG.ConnectivityState[q.subchannel.getConnectivityState()]+" after getting credentials metadata. Retrying pick"),this.doPick();return}if(this.deadline!==1/0)T.set("grpc-timeout",(0,nG.getDeadlineTimeoutString)(this.deadline));try{this.child=q.subchannel.getRealSubchannel().createCall(T,this.host,this.methodName,{onReceiveMetadata:(A)=>{this.trace("Received metadata"),this.listener.onReceiveMetadata(A)},onReceiveMessage:(A)=>{this.trace("Received message"),this.listener.onReceiveMessage(A)},onReceiveStatus:(A)=>{if(this.trace("Received status"),A.rstCode===lL.constants.NGHTTP2_REFUSED_STREAM)this.outputStatus(A,"REFUSED");else this.outputStatus(A,"PROCESSED")}}),this.childStartTime=new Date}catch(A){this.trace("Failed to start call on picked subchannel "+X+" with error "+A.message),this.outputStatus({code:fq.Status.INTERNAL,details:"Failed to start HTTP/2 stream with error "+A.message,metadata:new bq.Metadata},"NOT_STARTED");return}if((K=q.onCallStarted)===null||K===void 0||K.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()},(Z)=>{let{code:K,details:A}=(0,b5.restrictControlPlaneStatusCode)(typeof Z.code==="number"?Z.code:fq.Status.UNKNOWN,`Getting metadata from plugin failed with error: ${Z.message}`);this.outputStatus({code:K,details:A,metadata:new bq.Metadata},"PROCESSED")});break;case Z6.PickResultType.DROP:let{code:Q,details:U}=(0,b5.restrictControlPlaneStatusCode)(q.status.code,q.status.details);setImmediate(()=>{this.outputStatus({code:Q,details:U,metadata:q.status.metadata},"DROP")});break;case Z6.PickResultType.TRANSIENT_FAILURE:if(this.metadata.getOptions().waitForReady)this.channel.queueCallForPick(this);else{let{code:Z,details:K}=(0,b5.restrictControlPlaneStatusCode)(q.status.code,q.status.details);setImmediate(()=>{this.outputStatus({code:Z,details:K,metadata:q.status.metadata},"PROCESSED")})}break;case Z6.PickResultType.QUEUE:this.channel.queueCallForPick(this)}}cancelWithStatus($,Y){var T;this.trace("cancelWithStatus code: "+$+' details: "'+Y+'"'),(T=this.child)===null||T===void 0||T.cancelWithStatus($,Y),this.outputStatus({code:$,details:Y,metadata:new bq.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}}rG.LoadBalancingCall=iG});var YE=M((eG)=>{Object.defineProperty(eG,"__esModule",{value:!0});eG.ResolvingCall=void 0;var iL=g8(),YY=i(),TY=uY(),sG=P0(),rL=U0(),aL=T6(),oL="resolving_call";class tG{constructor($,Y,T,q,X){if(this.channel=$,this.method=Y,this.filterStackFactory=q,this.callNumber=X,this.child=null,this.readPending=!1,this.pendingMessage=null,this.pendingHalfClose=!1,this.ended=!1,this.readFilterPending=!1,this.writeFilterPending=!1,this.pendingChildStatus=null,this.metadata=null,this.listener=null,this.statusWatchers=[],this.deadlineTimer=setTimeout(()=>{},0),this.filterStack=null,this.deadlineStartTime=null,this.configReceivedTime=null,this.childStartTime=null,this.credentials=iL.CallCredentials.createEmpty(),this.deadline=T.deadline,this.host=T.host,T.parentCall){if(T.flags&YY.Propagate.CANCELLATION)T.parentCall.on("cancelled",()=>{this.cancelWithStatus(YY.Status.CANCELLED,"Cancelled by parent call")});if(T.flags&YY.Propagate.DEADLINE)this.trace("Propagating deadline from parent: "+T.parentCall.getDeadline()),this.deadline=(0,TY.minDeadline)(this.deadline,T.parentCall.getDeadline())}this.trace("Created"),this.runDeadlineTimer()}trace($){rL.trace(YY.LogVerbosity.DEBUG,oL,"["+this.callNumber+"] "+$)}runDeadlineTimer(){clearTimeout(this.deadlineTimer),this.deadlineStartTime=new Date,this.trace("Deadline: "+(0,TY.deadlineToString)(this.deadline));let $=(0,TY.getRelativeTimeout)(this.deadline);if($!==1/0){this.trace("Deadline will be reached in "+$+"ms");let Y=()=>{if(!this.deadlineStartTime){this.cancelWithStatus(YY.Status.DEADLINE_EXCEEDED,"Deadline exceeded");return}let T=[],q=new Date;if(T.push(`Deadline exceeded after ${(0,TY.formatDateDifference)(this.deadlineStartTime,q)}`),this.configReceivedTime){if(this.configReceivedTime>this.deadlineStartTime)T.push(`name resolution: ${(0,TY.formatDateDifference)(this.deadlineStartTime,this.configReceivedTime)}`);if(this.childStartTime){if(this.childStartTime>this.configReceivedTime)T.push(`metadata filters: ${(0,TY.formatDateDifference)(this.configReceivedTime,this.childStartTime)}`)}else T.push("waiting for metadata filters")}else T.push("waiting for name resolution");if(this.child)T.push(...this.child.getDeadlineInfo());this.cancelWithStatus(YY.Status.DEADLINE_EXCEEDED,T.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((T)=>T(Y)),process.nextTick(()=>{var T;(T=this.listener)===null||T===void 0||T.onReceiveStatus(Y)})}}sendMessageOnChild($,Y){if(!this.child)throw Error("sendMessageonChild called with child not populated");let T=this.child;this.writeFilterPending=!0,this.filterStack.sendMessage(Promise.resolve({message:Y,flags:$.flags})).then((q)=>{if(this.writeFilterPending=!1,T.sendMessageWithContext($,q.message),this.pendingHalfClose)T.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!==YY.Status.OK){let{code:T,details:q}=(0,aL.restrictControlPlaneStatusCode)(Y.status,"Failed to route call to method "+this.method);this.outputStatus({code:T,details:q,metadata:new sG.Metadata});return}if(Y.methodConfig.timeout){let T=new Date;T.setSeconds(T.getSeconds()+Y.methodConfig.timeout.seconds),T.setMilliseconds(T.getMilliseconds()+Y.methodConfig.timeout.nanos/1e6),this.deadline=(0,TY.minDeadline)(this.deadline,T),this.runDeadlineTimer()}this.filterStackFactory.push(Y.dynamicFilterFactories),this.filterStack=this.filterStackFactory.createFilter(),this.filterStack.sendMetadata(Promise.resolve(this.metadata)).then((T)=>{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(T,{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((X)=>{if(this.trace("Finished filtering received message"),this.readFilterPending=!1,this.listener.onReceiveMessage(X),this.pendingChildStatus)this.outputStatus(this.pendingChildStatus)},(X)=>{this.cancelWithStatus(X.code,X.details)})},onReceiveStatus:(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()},(T)=>{this.outputStatus(T)})}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 T;this.trace("cancelWithStatus code: "+$+' details: "'+Y+'"'),(T=this.child)===null||T===void 0||T.cancelWithStatus($,Y),this.outputStatus({code:$,details:Y,metadata:new sG.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}}eG.ResolvingCall=tG});var UE=M((JE)=>{Object.defineProperty(JE,"__esModule",{value:!0});JE.RetryingCall=JE.MessageBufferTracker=JE.RetryThrottler=void 0;var uq=i(),sL=uY(),tL=P0(),eL=U0(),$w="retrying_call";class TE{constructor($,Y,T){if(this.maxTokens=$,this.tokenRatio=Y,T)this.tokens=T.tokens*($/T.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}}JE.RetryThrottler=TE;class qE{constructor($,Y){this.totalLimit=$,this.limitPerCall=Y,this.totalAllocated=0,this.allocatedPerCall=new Map}allocate($,Y){var T;let q=(T=this.allocatedPerCall.get(Y))!==null&&T!==void 0?T:0;if(this.limitPerCall-q<$||this.totalLimit-this.totalAllocated<$)return!1;return this.allocatedPerCall.set(Y,q+$),this.totalAllocated+=$,!0}free($,Y){var T;if(this.totalAllocated<$)throw Error(`Invalid buffer allocation state: call ${Y} freed ${$} > total allocated ${this.totalAllocated}`);this.totalAllocated-=$;let q=(T=this.allocatedPerCall.get(Y))!==null&&T!==void 0?T: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 T=(Y=this.allocatedPerCall.get($))!==null&&Y!==void 0?Y:0;if(this.totalAllocated<T)throw Error(`Invalid buffer allocation state: call ${$} allocated ${T} > total allocated ${this.totalAllocated}`);this.totalAllocated-=T,this.allocatedPerCall.delete($)}}JE.MessageBufferTracker=qE;var u5="grpc-previous-rpc-attempts",Yw=5;class XE{constructor($,Y,T,q,X,J,Q,U,Z){var K;this.channel=$,this.callConfig=Y,this.methodName=T,this.host=q,this.credentials=X,this.deadline=J,this.callNumber=Q,this.bufferTracker=U,this.retryThrottler=Z,this.listener=null,this.initialMetadata=null,this.underlyingCalls=[],this.writeBuffer=[],this.writeBufferOffset=0,this.readStarted=!1,this.transparentRetryUsed=!1,this.attempts=0,this.hedgingTimer=null,this.committedCallIndex=null,this.initialRetryBackoffSec=0,this.nextRetryBackoffSec=0;let A=(K=$.getOptions()["grpc-node.retry_max_attempts_limit"])!==null&&K!==void 0?K:Yw;if($.getOptions()["grpc.enable_retries"]===0)this.state="NO_RETRY",this.maxAttempts=1;else if(Y.methodConfig.retryPolicy){this.state="RETRY";let W=Y.methodConfig.retryPolicy;this.nextRetryBackoffSec=this.initialRetryBackoffSec=Number(W.initialBackoff.substring(0,W.initialBackoff.length-1)),this.maxAttempts=Math.min(W.maxAttempts,A)}else if(Y.methodConfig.hedgingPolicy)this.state="HEDGING",this.maxAttempts=Math.min(Y.methodConfig.hedgingPolicy.maxAttempts,A);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,sL.formatDateDifference)(this.startTime,Y.startTime)}`);return $.push(...Y.call.getDeadlineInfo()),$}getCallNumber(){return this.callNumber}trace($){eL.trace(uq.LogVerbosity.DEBUG,$w,"["+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 tL.Metadata});for(let{call:T}of this.underlyingCalls)T.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 T=this.getBufferEntry(Y);if(T.allocated)this.bufferTracker.free(T.message.message.length,this.callNumber)}this.writeBuffer=this.writeBuffer.slice($-this.writeBufferOffset),this.writeBufferOffset=$}commitCall($){var Y,T;if(this.state==="COMMITTED")return;this.trace("Committing call ["+this.underlyingCalls[$].call.getCallNumber()+"] at index "+$),this.state="COMMITTED",(T=(Y=this.callConfig).onCommitted)===null||T===void 0||T.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(uq.Status.CANCELLED,"Discarded in favor of other hedged attempt")}this.clearSentMessages()}commitCallWithMostMessages(){if(this.state==="COMMITTED")return;let $=-1,Y=-1;for(let[T,q]of this.underlyingCalls.entries())if(q.state==="ACTIVE"&&q.nextMessageToSend>$)$=q.nextMessageToSend,Y=T;if(Y===-1)this.state="TRANSPARENT_ONLY";else this.commitCall(Y)}isStatusCodeInList($,Y){return $.some((T)=>{var q;return T===Y||T.toString().toLowerCase()===((q=uq.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,X=Number(Y.maxBackoff.substring(0,Y.maxBackoff.length-1));return this.nextRetryBackoffSec=Math.min(this.nextRetryBackoffSec*Y.backoffMultiplier,X),q}maybeRetryCall($,Y){if(this.state!=="RETRY"){Y(!1);return}if(this.attempts>=this.maxAttempts){Y(!1);return}let T;if($===null)T=this.getNextRetryBackoffMs();else if($<0){this.state="TRANSPARENT_ONLY",Y(!1);return}else T=$,this.nextRetryBackoffSec=this.initialRetryBackoffSec;setTimeout(()=>{var q,X;if(this.state!=="RETRY"){Y(!1);return}if((X=(q=this.retryThrottler)===null||q===void 0?void 0:q.canRetryCall())!==null&&X!==void 0?X:!0)Y(!0),this.attempts+=1,this.startNewAttempt();else this.trace("Retry attempt denied by throttling policy"),Y(!1)},T)}countActiveCalls(){let $=0;for(let Y of this.underlyingCalls)if((Y===null||Y===void 0?void 0:Y.state)==="ACTIVE")$+=1;return $}handleProcessedStatus($,Y,T){var q,X,J;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)){(X=this.retryThrottler)===null||X===void 0||X.addCallFailed();let Q;if(T===null)Q=0;else if(T<0){this.state="TRANSPARENT_ONLY",this.commitCall(Y),this.reportStatus($);return}else Q=T;setTimeout(()=>{if(this.maybeStartHedgingAttempt(),this.countActiveCalls()===0)this.commitCall(Y),this.reportStatus($)},Q)}else this.commitCall(Y),this.reportStatus($);break;case"RETRY":if(this.isStatusCodeInList(this.callConfig.methodConfig.retryPolicy.retryableStatusCodes,$.code))(J=this.retryThrottler)===null||J===void 0||J.addCallFailed(),this.maybeRetryCall(T,(Q)=>{if(!Q)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(T){return-1}}handleChildStatus($,Y){var T;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===uq.Status.OK){(T=this.retryThrottler)===null||T===void 0||T.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,T;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 X=($=q.hedgingDelay)!==null&&$!==void 0?$:"0s",J=Number(X.substring(0,X.length-1));this.hedgingTimer=setTimeout(()=>{this.maybeStartHedgingAttempt()},J*1000),(T=(Y=this.hedgingTimer).unref)===null||T===void 0||T.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 T=this.attempts-1,q=this.initialMetadata.clone();if(T>0)q.set(u5,`${T}`);let X=!1;if($.start(q,{onReceiveMetadata:(J)=>{if(this.trace("Received metadata from child ["+$.getCallNumber()+"]"),this.commitCall(Y),X=!0,T>0)J.set(u5,`${T}`);if(this.underlyingCalls[Y].state==="ACTIVE")this.listener.onReceiveMetadata(J)},onReceiveMessage:(J)=>{if(this.trace("Received message from child ["+$.getCallNumber()+"]"),this.commitCall(Y),this.underlyingCalls[Y].state==="ACTIVE")this.listener.onReceiveMessage(J)},onReceiveStatus:(J)=>{if(this.trace("Received status from child ["+$.getCallNumber()+"]"),!X&&T>0)J.metadata.set(u5,`${T}`);this.handleChildStatus(J,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 T,q;(q=(T=this.getBufferEntry(Y)).callback)===null||q===void 0||q.call(T),this.clearSentMessages();let X=this.underlyingCalls[$];X.nextMessageToSend+=1,this.sendNextChildMessage($)}sendNextChildMessage($){let Y=this.underlyingCalls[$];if(Y.state==="COMPLETED")return;let T=Y.nextMessageToSend;if(this.getBufferEntry(T)){let q=this.getBufferEntry(T);switch(q.entryType){case"MESSAGE":if(Y.call.sendMessageWithContext({callback:(J)=>{this.handleChildWriteCompleted($,T)}},q.message.message),this.getBufferEntry(T+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 T={message:Y,flags:$.flags},q=this.getNextBufferIndex(),X={entryType:"MESSAGE",message:T,allocated:this.bufferTracker.allocate(Y.length,this.callNumber)};if(this.writeBuffer.push(X),X.allocated){process.nextTick(()=>{var J;(J=$.callback)===null||J===void 0||J.call($)});for(let[J,Q]of this.underlyingCalls.entries())if(Q.state==="ACTIVE"&&Q.nextMessageToSend===q)Q.call.sendMessageWithContext({callback:(U)=>{this.handleChildWriteCompleted(J,q)}},Y)}else{if(this.commitCallWithMostMessages(),this.committedCallIndex===null)return;let J=this.underlyingCalls[this.committedCallIndex];if(X.callback=$.callback,J.state==="ACTIVE"&&J.nextMessageToSend===q)J.call.sendMessageWithContext({callback:(Q)=>{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}}JE.RetryingCall=XE});var K6=M((KE)=>{Object.defineProperty(KE,"__esModule",{value:!0});KE.BaseSubchannelWrapper=void 0;class ZE{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()}}KE.BaseSubchannelWrapper=ZE});var l5=M((FE)=>{Object.defineProperty(FE,"__esModule",{value:!0});FE.InternalChannel=FE.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX=void 0;var Xw=PY(),Jw=a7(),Qw=pG(),p5=Y$(),Uw=P0(),v$=i(),Zw=vq(),Kw=L5(),WE=B1(),dq=U0(),Aw=h5(),cq=p0(),N1=l0(),A6=y$(),Ww=oG(),Gw=uY(),Ew=YE(),d5=yq(),Vw=T6(),c5=UE(),Dw=K6(),Fw=2147483647,Nw=1000,Hw=1800000,pq=new Map,zw=16777216,Iw=1048576;class GE extends Dw.BaseSubchannelWrapper{constructor($,Y){super($);this.channel=Y,this.refCount=0,this.subchannelStateListener=(T,q,X,J)=>{Y.throttleKeepalive(J)}}ref(){if(this.refCount===0)this.child.addConnectivityStateListener(this.subchannelStateListener),this.channel.addWrappedSubchannel(this);this.child.ref(),this.refCount+=1}unref(){if(this.child.unref(),this.refCount-=1,this.refCount<=0)this.child.removeConnectivityStateListener(this.subchannelStateListener),this.channel.removeWrappedSubchannel(this)}}class EE{pick($){return{pickResultType:p5.PickResultType.DROP,status:{code:v$.Status.UNAVAILABLE,details:"Channel closed before call started",metadata:new Uw.Metadata},subchannel:null,onCallStarted:null,onCallEnded:null}}}FE.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX="grpc.internal.no_subchannel";class VE{constructor($){this.target=$,this.trace=new A6.ChannelzTrace,this.callTracker=new A6.ChannelzCallTracker,this.childrenTracker=new A6.ChannelzChildrenTracker,this.state=N1.ConnectivityState.IDLE}getChannelzInfoCallback(){return()=>{return{target:this.target,state:this.state,trace:this.trace,callTracker:this.callTracker,children:this.childrenTracker.getChildLists()}}}}class DE{constructor($,Y,T){var q,X,J,Q,U,Z;if(this.credentials=Y,this.options=T,this.connectivityState=N1.ConnectivityState.IDLE,this.currentPicker=new p5.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 Xw.ChannelCredentials))throw TypeError("Channel credentials must be a ChannelCredentials object");if(T){if(typeof T!=="object")throw TypeError("Channel options must be an object")}this.channelzInfoTracker=new VE($);let K=(0,cq.parseUri)($);if(K===null)throw Error(`Could not parse target name "${$}"`);let A=(0,WE.mapUriDefaultScheme)(K);if(A===null)throw Error(`Could not find a default scheme for target name "${$}"`);if(this.options["grpc.enable_channelz"]===0)this.channelzEnabled=!1;if(this.channelzRef=(0,A6.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,WE.getDefaultAuthority)(A);let W=(0,Aw.mapProxyName)(A,T);this.target=W.target,this.options=Object.assign({},this.options,W.extraOptions),this.subchannelPool=(0,Qw.getSubchannelPool)(((q=this.options["grpc.use_local_subchannel_pool"])!==null&&q!==void 0?q:0)===0),this.retryBufferTracker=new c5.MessageBufferTracker((X=this.options["grpc.retry_buffer_size"])!==null&&X!==void 0?X:zw,(J=this.options["grpc.per_rpc_retry_buffer_size"])!==null&&J!==void 0?J:Iw),this.keepaliveTime=(Q=this.options["grpc.keepalive_time_ms"])!==null&&Q!==void 0?Q:-1,this.idleTimeoutMs=Math.max((U=this.options["grpc.client_idle_timeout_ms"])!==null&&U!==void 0?U:Hw,Nw);let E={createSubchannel:(F,H)=>{let V={};for(let[v,z]of Object.entries(H))if(!v.startsWith(FE.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX))V[v]=z;let B=this.subchannelPool.getOrCreateSubchannel(this.target,F,V,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 GE(B,this)},updateState:(F,H)=>{this.currentPicker=H;let V=this.pickQueue.slice();if(this.pickQueue=[],V.length>0)this.callRefTimerUnref();for(let B of V)B.doPick();this.updateState(F)},requestReresolution:()=>{throw Error("Resolving load balancer should never call requestReresolution")},addChannelzChild:(F)=>{if(this.channelzEnabled)this.channelzInfoTracker.childrenTracker.refChild(F)},removeChannelzChild:(F)=>{if(this.channelzEnabled)this.channelzInfoTracker.childrenTracker.unrefChild(F)}};this.resolvingLoadBalancer=new Jw.ResolvingLoadBalancer(this.target,E,this.options,(F,H)=>{var V;if(F.retryThrottling)pq.set(this.getTarget(),new c5.RetryThrottler(F.retryThrottling.maxTokens,F.retryThrottling.tokenRatio,pq.get(this.getTarget())));else pq.delete(this.getTarget());if(this.channelzEnabled)this.channelzInfoTracker.trace.addTrace("CT_INFO","Address resolution succeeded");(V=this.configSelector)===null||V===void 0||V.unref(),this.configSelector=H,this.currentResolutionError=null,process.nextTick(()=>{let B=this.configSelectionQueue;if(this.configSelectionQueue=[],B.length>0)this.callRefTimerUnref();for(let S of B)S.getConfig()})},(F)=>{if(this.channelzEnabled)this.channelzInfoTracker.trace.addTrace("CT_WARNING","Address resolution failed with code "+F.code+' and details "'+F.details+'"');if(this.configSelectionQueue.length>0)this.trace("Name resolution failed with calls queued for config selection");if(this.configSelector===null)this.currentResolutionError=Object.assign(Object.assign({},(0,Vw.restrictControlPlaneStatusCode)(F.code,F.details)),{metadata:F.metadata});let H=this.configSelectionQueue;if(this.configSelectionQueue=[],H.length>0)this.callRefTimerUnref();for(let V of H)V.reportResolverError(F)}),this.filterStackFactory=new Zw.FilterStackFactory([new Kw.CompressionFilterFactory(this,this.options)]),this.trace("Channel constructed with options "+JSON.stringify(T,void 0,2));let D=Error();if((0,dq.isTracerEnabled)("channel_stacktrace"))(0,dq.trace)(v$.LogVerbosity.DEBUG,"channel_stacktrace","("+this.channelzRef.id+`) Channel constructed
20
+ `+((Z=D.stack)===null||Z===void 0?void 0:Z.substring(D.stack.indexOf(`
21
+ `)+1)));this.lastActivityTimestamp=new Date}trace($,Y){(0,dq.trace)(Y!==null&&Y!==void 0?Y:v$.LogVerbosity.DEBUG,"channel","("+this.channelzRef.id+") "+(0,cq.uriToString)(this.target)+" "+$)}callRefTimerRef(){var $,Y,T,q;if(!this.callRefTimer)this.callRefTimer=setInterval(()=>{},Fw);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=(T=this.callRefTimer).ref)===null||q===void 0||q.call(T)}callRefTimerUnref(){var $,Y,T;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),(T=(Y=this.callRefTimer)===null||Y===void 0?void 0:Y.unref)===null||T===void 0||T.call(Y)}removeConnectivityStateWatcher($){let Y=this.connectivityStateWatchers.findIndex((T)=>T===$);if(Y>=0)this.connectivityStateWatchers.splice(Y,1)}updateState($){if((0,dq.trace)(v$.LogVerbosity.DEBUG,"connectivity_state","("+this.channelzRef.id+") "+(0,cq.uriToString)(this.target)+" "+N1.ConnectivityState[this.connectivityState]+" -> "+N1.ConnectivityState[$]),this.channelzEnabled)this.channelzInfoTracker.trace.addTrace("CT_INFO","Connectivity state change to "+N1.ConnectivityState[$]);this.connectivityState=$,this.channelzInfoTracker.state=$;let Y=this.connectivityStateWatchers.slice();for(let T of Y)if($!==T.currentState){if(T.timer)clearTimeout(T.timer);this.removeConnectivityStateWatcher(T),T.callback()}if($!==N1.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!==N1.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(N1.ConnectivityState.IDLE),this.currentPicker=new p5.QueuePicker(this.resolvingLoadBalancer),this.idleTimer)clearTimeout(this.idleTimer),this.idleTimer=null;if(this.callRefTimer)clearInterval(this.callRefTimer),this.callRefTimer=null}startIdleTimeout($){var Y,T;this.idleTimer=setTimeout(()=>{if(this.callCount>0){this.startIdleTimeout(this.idleTimeoutMs);return}let X=new Date().valueOf()-this.lastActivityTimestamp.valueOf();if(X>=this.idleTimeoutMs)this.trace("Idle timer triggered after "+this.idleTimeoutMs+"ms of inactivity"),this.enterIdle();else this.startIdleTimeout(this.idleTimeoutMs-X)},$),(T=(Y=this.idleTimer).unref)===null||T===void 0||T.call(Y)}maybeStartIdleTimer(){if(this.connectivityState!==N1.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===v$.Status.OK)this.channelzInfoTracker.callTracker.addCallSucceeded();else this.channelzInfoTracker.callTracker.addCallFailed();this.callCount-=1,this.lastActivityTimestamp=new Date,this.maybeStartIdleTimer()}createLoadBalancingCall($,Y,T,q,X){let J=(0,d5.getNextCallNumber)();return this.trace("createLoadBalancingCall ["+J+'] method="'+Y+'"'),new Ww.LoadBalancingCall(this,$,Y,T,q,X,J)}createRetryingCall($,Y,T,q,X){let J=(0,d5.getNextCallNumber)();return this.trace("createRetryingCall ["+J+'] method="'+Y+'"'),new c5.RetryingCall(this,$,Y,T,q,X,J,this.retryBufferTracker,pq.get(this.getTarget()))}createResolvingCall($,Y,T,q,X){let J=(0,d5.getNextCallNumber)();this.trace("createResolvingCall ["+J+'] method="'+$+'", deadline='+(0,Gw.deadlineToString)(Y));let Q={deadline:Y,flags:X!==null&&X!==void 0?X:v$.Propagate.DEFAULTS,host:T!==null&&T!==void 0?T:this.defaultAuthority,parentCall:q},U=new Ew.ResolvingCall(this,$,Q,this.filterStackFactory.clone(),J);return this.onCallStart(),U.addStatusWatcher((Z)=>{this.onCallEnd(Z)}),U}close(){var $;this.resolvingLoadBalancer.destroy(),this.updateState(N1.ConnectivityState.SHUTDOWN),this.currentPicker=new EE;for(let Y of this.configSelectionQueue)Y.cancelWithStatus(v$.Status.UNAVAILABLE,"Channel closed before call started");this.configSelectionQueue=[];for(let Y of this.pickQueue)Y.cancelWithStatus(v$.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,A6.unregisterChannelzRef)(this.channelzRef);this.subchannelPool.unrefUnusedSubchannels(),($=this.configSelector)===null||$===void 0||$.unref(),this.configSelector=null}getTarget(){return(0,cq.uriToString)(this.target)}getConnectivityState($){let Y=this.connectivityState;if($)this.resolvingLoadBalancer.exitIdle(),this.lastActivityTimestamp=new Date,this.maybeStartIdleTimer();return Y}watchConnectivityState($,Y,T){if(this.connectivityState===N1.ConnectivityState.SHUTDOWN)throw Error("Channel has been shut down");let q=null;if(Y!==1/0){let J=Y instanceof Date?Y:new Date(Y),Q=new Date;if(Y===-1/0||J<=Q){process.nextTick(T,Error("Deadline passed without connectivity state change"));return}q=setTimeout(()=>{this.removeConnectivityStateWatcher(X),T(Error("Deadline passed without connectivity state change"))},J.getTime()-Q.getTime())}let X={currentState:$,callback:T,timer:q};this.connectivityStateWatchers.push(X)}getChannelzRef(){return this.channelzRef}createCall($,Y,T,q,X){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===N1.ConnectivityState.SHUTDOWN)throw Error("Channel has been shut down");return this.createResolvingCall($,Y,T,q,X)}getOptions(){return this.options}}FE.InternalChannel=DE});var AX=M((IE)=>{Object.defineProperty(IE,"__esModule",{value:!0});IE.ChannelImplementation=void 0;var Mw=PY(),Bw=l5();class zE{constructor($,Y,T){if(typeof $!=="string")throw TypeError("Channel target must be a string");if(!(Y instanceof Mw.ChannelCredentials))throw TypeError("Channel credentials must be a ChannelCredentials object");if(T){if(typeof T!=="object")throw TypeError("Channel options must be an object")}this.internalChannel=new Bw.InternalChannel($,Y,T)}close(){this.internalChannel.close()}getTarget(){return this.internalChannel.getTarget()}getConnectivityState($){return this.internalChannel.getConnectivityState($)}watchConnectivityState($,Y,T){this.internalChannel.watchConnectivityState($,Y,T)}getChannelzRef(){return this.internalChannel.getChannelzRef()}createCall($,Y,T,q,X){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,T,q,X)}}IE.ChannelImplementation=zE});var CE=M((wE)=>{Object.defineProperty(wE,"__esModule",{value:!0});wE.ServerDuplexStreamImpl=wE.ServerWritableStreamImpl=wE.ServerReadableStreamImpl=wE.ServerUnaryCallImpl=void 0;wE.serverErrorToStatus=r5;var Rw=s("events"),n5=s("stream"),i5=i(),BE=P0();function r5($,Y){var T;let q={code:i5.Status.UNKNOWN,details:"message"in $?$.message:"Unknown Error",metadata:(T=Y!==null&&Y!==void 0?Y:$.metadata)!==null&&T!==void 0?T: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 RE extends Rw.EventEmitter{constructor($,Y,T,q){super();this.path=$,this.call=Y,this.metadata=T,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()}}wE.ServerUnaryCallImpl=RE;class OE extends n5.Readable{constructor($,Y,T){super({objectMode:!0});this.path=$,this.call=Y,this.metadata=T,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()}}wE.ServerReadableStreamImpl=OE;class PE extends n5.Writable{constructor($,Y,T,q){super({objectMode:!0});this.path=$,this.call=Y,this.metadata=T,this.request=q,this.pendingStatus={code:i5.Status.OK,details:"OK"},this.cancelled=!1,this.trailingMetadata=new BE.Metadata,this.on("error",(X)=>{this.pendingStatus=r5(X),this.end()})}getPeer(){return this.call.getPeer()}sendMetadata($){this.call.sendMetadata($)}getDeadline(){return this.call.getDeadline()}getPath(){return this.path}getHost(){return this.call.getHost()}getAuthContext(){return this.call.getAuthContext()}getMetricsRecorder(){return this.call.getMetricsRecorder()}_write($,Y,T){this.call.sendMessage($,T)}_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()}}wE.ServerWritableStreamImpl=PE;class LE extends n5.Duplex{constructor($,Y,T){super({objectMode:!0});this.path=$,this.call=Y,this.metadata=T,this.pendingStatus={code:i5.Status.OK,details:"OK"},this.cancelled=!1,this.trailingMetadata=new BE.Metadata,this.on("error",(q)=>{this.pendingStatus=r5(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,T){this.call.sendMessage($,T)}_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()}}wE.ServerDuplexStreamImpl=LE});var lq=M((yE)=>{Object.defineProperty(yE,"__esModule",{value:!0});yE.ServerCredentials=void 0;yE.createCertificateProviderServerCredentials=Sw;yE.createServerCredentialsWithInterceptors=Cw;var a5=a4();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 o5}static createSsl($,Y,T=!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 T!=="boolean")throw TypeError("checkClientCertificate must be a boolean");let X=[],J=[];for(let Q=0;Q<Y.length;Q++){let U=Y[Q];if(U===null||typeof U!=="object")throw TypeError(`keyCertPair[${Q}] must be an object`);if(!Buffer.isBuffer(U.private_key))throw TypeError(`keyCertPair[${Q}].private_key must be a Buffer`);if(!Buffer.isBuffer(U.cert_chain))throw TypeError(`keyCertPair[${Q}].cert_chain must be a Buffer`);X.push(U.cert_chain),J.push(U.private_key)}return new s5({requestCert:T,ciphers:a5.CIPHER_SUITES},{ca:(q=$!==null&&$!==void 0?$:(0,a5.getDefaultRootsData)())!==null&&q!==void 0?q:void 0,cert:X,key:J})}}yE.ServerCredentials=nY;class o5 extends nY{constructor(){super(null)}_getSettings(){return null}_equals($){return $ instanceof o5}}class s5 extends nY{constructor($,Y){super($,Y);this.options=Object.assign(Object.assign({},$),Y)}_equals($){if(this===$)return!0;if(!($ instanceof s5))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 T=this.options.cert[Y],q=$.options.cert[Y];if(Buffer.isBuffer(T)&&Buffer.isBuffer(q)){if(!T.equals(q))return!1}else if(T!==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 T=this.options.key[Y],q=$.options.key[Y];if(Buffer.isBuffer(T)&&Buffer.isBuffer(q)){if(!T.equals(q))return!1}else if(T!==q)return!1}}else if(this.options.key!==$.options.key)return!1;if(this.options.requestCert!==$.options.requestCert)return!1;return!0}}class t5 extends nY{constructor($,Y,T){super({requestCert:Y!==null,rejectUnauthorized:T,ciphers:a5.CIPHER_SUITES});this.identityCertificateProvider=$,this.caCertificateProvider=Y,this.requireClientCertificate=T,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 t5))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 Sw($,Y,T){return new t5($,Y,T)}class e5 extends nY{constructor($,Y){super({});this.childCredentials=$,this.interceptors=Y}_isSecure(){return this.childCredentials._isSecure()}_equals($){if(!($ instanceof e5))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 Cw($,Y){return new e5($,Y)}});var W6=M((vE)=>{Object.defineProperty(vE,"__esModule",{value:!0});vE.durationMessageToDuration=vw;vE.msToDuration=xw;vE.durationToMs=kw;vE.isDuration=hw;vE.isDurationMessage=_w;vE.parseDuration=mw;vE.durationToString=fw;function vw($){return{seconds:Number.parseInt($.seconds),nanos:$.nanos}}function xw($){return{seconds:$/1000|0,nanos:$%1000*1e6|0}}function kw($){return $.seconds*1000+$.nanos/1e6|0}function hw($){return typeof $.seconds==="number"&&typeof $.nanos==="number"}function _w($){return typeof $.seconds==="string"&&typeof $.nanos==="number"}var gw=/^(\d+)(?:\.(\d+))?s$/;function mw($){let Y=$.match(gw);if(!Y)return null;return{seconds:Number.parseInt(Y[1],10),nanos:Y[2]?Number.parseInt(Y[2].padEnd(9,"0"),10):0}}function fw($){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 iq=M((cE)=>{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(cE,"__esModule",{value:!0});cE.OrcaOobMetricsSubchannelWrapper=cE.GRPC_METRICS_HEADER=cE.ServerMetricRecorder=cE.PerRequestMetricRecorder=void 0;cE.createOrcaClient=mE;cE.createMetricsReader=ew;var iw=a8(),$J=W6(),rw=PY(),aw=K6(),xE=i(),ow=LY(),sw=l0(),kE=null;function nq(){if(kE)return kE;let $=tT().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,iw.loadPackageDefinition)(Y)}class _E{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 nq().xds.data.orca.v3.OrcaLoadReport.serialize(this.message)}}cE.PerRequestMetricRecorder=_E;var tw=30000;class gE{constructor(){this.message={},this.serviceImplementation={StreamCoreMetrics:($)=>{let Y=$.request.report_interval?(0,$J.durationToMs)((0,$J.durationMessageToDuration)($.request.report_interval)):tw,T=setInterval(()=>{$.write(this.message)},Y);$.on("cancelled",()=>{clearInterval(T)})}}}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=nq().xds.service.orca.v3.OpenRcaService.service;$.addService(Y,this.serviceImplementation)}}cE.ServerMetricRecorder=gE;function mE($){return new(nq()).xds.service.orca.v3.OpenRcaService("unused",rw.ChannelCredentials.createInsecure(),{channelOverride:$})}cE.GRPC_METRICS_HEADER="endpoint-load-metrics-bin";var hE="grpc_orca_load_report";function ew($,Y){return(T,q,X)=>{let J=X.getOpaque(hE);if(J)$(J);else{let Q=X.get(cE.GRPC_METRICS_HEADER);if(Q.length>0)J=nq().xds.data.orca.v3.OrcaLoadReport.deserialize(Q[0]),$(J),X.setOpaque(hE,J)}if(Y)Y(T,q,X)}}var fE="orca_oob_metrics";class bE{constructor($,Y){this.metricsListener=$,this.intervalMs=Y,this.dataProducer=null}setSubchannel($){let Y=$.getOrCreateDataProducer(fE,$S);this.dataProducer=Y,Y.addDataWatcher(this)}destroy(){var $;($=this.dataProducer)===null||$===void 0||$.removeDataWatcher(this)}getInterval(){return this.intervalMs}onMetricsUpdate($){this.metricsListener($)}}class uE{constructor($){this.subchannel=$,this.dataWatchers=new Set,this.orcaSupported=!0,this.metricsCall=null,this.currentInterval=1/0,this.backoffTimer=new ow.BackoffTimeout(()=>this.updateMetricsSubscription()),this.subchannelStateListener=()=>this.updateMetricsSubscription();let Y=$.getChannel();this.client=mE(Y),$.addConnectivityStateListener(this.subchannelStateListener)}addDataWatcher($){this.dataWatchers.add($),this.updateMetricsSubscription()}removeDataWatcher($){var Y;if(this.dataWatchers.delete($),this.dataWatchers.size===0)this.subchannel.removeDataProducer(fE),(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()!==sw.ConnectivityState.READY)return;let Y=Math.min(...Array.from(this.dataWatchers).map((T)=>T.getInterval()));if(!this.metricsCall||Y!==this.currentInterval){($=this.metricsCall)===null||$===void 0||$.cancel(),this.currentInterval=Y;let T=this.client.streamCoreMetrics({report_interval:(0,$J.msToDuration)(Y)});this.metricsCall=T,T.on("data",(q)=>{this.dataWatchers.forEach((X)=>{X.onMetricsUpdate(q)})}),T.on("error",(q)=>{if(this.metricsCall=null,q.code===xE.Status.UNIMPLEMENTED){this.orcaSupported=!1;return}if(q.code===xE.Status.CANCELLED)return;this.backoffTimer.runOnce()})}}}class dE extends aw.BaseSubchannelWrapper{constructor($,Y,T){super($);this.addDataWatcher(new bE(Y,T))}getWrappedSubchannel(){return this.child}}cE.OrcaOobMetricsSubchannelWrapper=dE;function $S($){return new uE($)}});var XJ=M((JV)=>{Object.defineProperty(JV,"__esModule",{value:!0});JV.BaseServerInterceptingCall=JV.ServerInterceptingCall=JV.ResponderBuilder=JV.ServerListenerBuilder=void 0;JV.isInterceptingServerListener=US;JV.getServerInterceptingCall=GS;var oq=P0(),o0=i(),iY=s("http2"),nE=x8(),iE=s("zlib"),JS=_5(),tE=U0(),QS=s("tls"),rE=iq(),eE="server_call";function qY($){tE.trace(o0.LogVerbosity.DEBUG,eE,$)}class $V{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}}}JV.ServerListenerBuilder=$V;function US($){return $.onReceiveMetadata!==void 0&&$.onReceiveMetadata.length===1}class YV{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 TV{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}}}JV.ResponderBuilder=TV;var rq={onReceiveMetadata:($,Y)=>{Y($)},onReceiveMessage:($,Y)=>{Y($)},onReceiveHalfClose:($)=>{$()},onCancel:()=>{}},aq={start:($)=>{$()},sendMetadata:($,Y)=>{Y($)},sendMessage:($,Y)=>{Y($)},sendStatus:($,Y)=>{Y($)}};class qV{constructor($,Y){var T,q,X,J;this.nextCall=$,this.processingMetadata=!1,this.sentMetadata=!1,this.processingMessage=!1,this.pendingMessage=null,this.pendingMessageCallback=null,this.pendingStatus=null,this.responder={start:(T=Y===null||Y===void 0?void 0:Y.start)!==null&&T!==void 0?T:aq.start,sendMetadata:(q=Y===null||Y===void 0?void 0:Y.sendMetadata)!==null&&q!==void 0?q:aq.sendMetadata,sendMessage:(X=Y===null||Y===void 0?void 0:Y.sendMessage)!==null&&X!==void 0?X:aq.sendMessage,sendStatus:(J=Y===null||Y===void 0?void 0:Y.sendStatus)!==null&&J!==void 0?J:aq.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 T,q,X,J;let Q={onReceiveMetadata:(T=Y===null||Y===void 0?void 0:Y.onReceiveMetadata)!==null&&T!==void 0?T:rq.onReceiveMetadata,onReceiveMessage:(q=Y===null||Y===void 0?void 0:Y.onReceiveMessage)!==null&&q!==void 0?q:rq.onReceiveMessage,onReceiveHalfClose:(X=Y===null||Y===void 0?void 0:Y.onReceiveHalfClose)!==null&&X!==void 0?X:rq.onReceiveHalfClose,onCancel:(J=Y===null||Y===void 0?void 0:Y.onCancel)!==null&&J!==void 0?J:rq.onCancel},U=new YV(Q,$);this.nextCall.start(U)})}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 oq.Metadata);this.responder.sendMessage($,(T)=>{if(this.processingMessage=!1,this.processingMetadata)this.pendingMessage=T,this.pendingMessageCallback=Y;else this.nextCall.sendMessage(T,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()}}JV.ServerInterceptingCall=qV;var XV="grpc-accept-encoding",TJ="grpc-encoding",aE="grpc-message",oE="grpc-status",YJ="grpc-timeout",ZS=/(\d{1,8})\s*([HMSmun])/,KS={H:3600000,M:60000,S:1000,m:1,u:0.001,n:0.000001},AS={[XV]:"identity,deflate,gzip",[TJ]:"identity"},sE={[iY.constants.HTTP2_HEADER_STATUS]:iY.constants.HTTP_STATUS_OK,[iY.constants.HTTP2_HEADER_CONTENT_TYPE]:"application/grpc+proto"},WS={waitForTrailers:!0};class qJ{constructor($,Y,T,q,X){var J,Q;if(this.stream=$,this.callEventTracker=T,this.handler=q,this.listener=null,this.deadlineTimer=null,this.deadline=1/0,this.maxSendMessageSize=o0.DEFAULT_MAX_SEND_MESSAGE_LENGTH,this.maxReceiveMessageSize=o0.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 rE.PerRequestMetricRecorder,this.stream.once("error",(W)=>{}),this.stream.once("close",()=>{var W;if(qY("Request to method "+((W=this.handler)===null||W===void 0?void 0:W.path)+" stream closed with rstCode "+this.stream.rstCode),this.callEventTracker&&!this.streamEnded)this.streamEnded=!0,this.callEventTracker.onStreamEnd(!1),this.callEventTracker.onCallEnd({code:o0.Status.CANCELLED,details:"Stream closed before sending status",metadata:null});this.notifyOnCancel()}),this.stream.on("data",(W)=>{this.handleDataFrame(W)}),this.stream.pause(),this.stream.on("end",()=>{this.handleEndEvent()}),"grpc.max_send_message_length"in X)this.maxSendMessageSize=X["grpc.max_send_message_length"];if("grpc.max_receive_message_length"in X)this.maxReceiveMessageSize=X["grpc.max_receive_message_length"];this.host=(J=Y[":authority"])!==null&&J!==void 0?J:Y.host,this.decoder=new JS.StreamDecoder(this.maxReceiveMessageSize);let U=oq.Metadata.fromHttp2Headers(Y);if(tE.isTracerEnabled(eE))qY("Request to "+this.handler.path+" received headers "+JSON.stringify(U.toJSON()));let Z=U.get(YJ);if(Z.length>0)this.handleTimeoutHeader(Z[0]);let K=U.get(TJ);if(K.length>0)this.incomingEncoding=K[0];U.remove(YJ),U.remove(TJ),U.remove(XV),U.remove(iY.constants.HTTP2_HEADER_ACCEPT_ENCODING),U.remove(iY.constants.HTTP2_HEADER_TE),U.remove(iY.constants.HTTP2_HEADER_CONTENT_TYPE),this.metadata=U;let A=(Q=$.session)===null||Q===void 0?void 0:Q.socket;this.connectionInfo={localAddress:A===null||A===void 0?void 0:A.localAddress,localPort:A===null||A===void 0?void 0:A.localPort,remoteAddress:A===null||A===void 0?void 0:A.remoteAddress,remotePort:A===null||A===void 0?void 0:A.remotePort},this.shouldSendMetrics=!!X["grpc.server_call_metric_recording"]}handleTimeoutHeader($){let Y=$.toString().match(ZS);if(Y===null){let X={code:o0.Status.INTERNAL,details:`Invalid ${YJ} value "${$}"`,metadata:null};process.nextTick(()=>{this.sendStatus(X)});return}let T=+Y[1]*KS[Y[2]]|0,q=new Date;this.deadline=q.setMilliseconds(q.getMilliseconds()+T),this.deadlineTimer=setTimeout(()=>{let X={code:o0.Status.DEADLINE_EXCEEDED,details:"Deadline exceeded",metadata:null};this.sendStatus(X)},T)}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 oq.Metadata)}serializeMessage($){let Y=this.handler.serialize($),T=Y.byteLength,q=Buffer.allocUnsafe(T+5);return q.writeUInt8(0,0),q.writeUInt32BE(T,1),Y.copy(q,5),q}decompressMessage($,Y){let T=$.subarray(5);if(Y==="identity")return T;else if(Y==="deflate"||Y==="gzip"){let q;if(Y==="deflate")q=iE.createInflate();else q=iE.createGunzip();return new Promise((X,J)=>{let Q=0,U=[];q.on("data",(Z)=>{if(U.push(Z),Q+=Z.byteLength,this.maxReceiveMessageSize!==-1&&Q>this.maxReceiveMessageSize)q.destroy(),J({code:o0.Status.RESOURCE_EXHAUSTED,details:`Received message that decompresses to a size larger than ${this.maxReceiveMessageSize}`})}),q.on("end",()=>{X(Buffer.concat(U))}),q.write(T),q.end()})}else return Promise.reject({code:o0.Status.UNIMPLEMENTED,details:`Received message compressed with unsupported encoding "${Y}"`})}async decompressAndMaybePush($){if($.type!=="COMPRESSED")throw Error(`Invalid queue entry type: ${$.type}`);let T=$.compressedMessage.readUInt8(0)===1?this.incomingEncoding:"identity",q;try{q=await this.decompressMessage($.compressedMessage,T)}catch(X){this.sendStatus(X);return}try{$.parsedMessage=this.handler.deserialize(q)}catch(X){this.sendStatus({code:o0.Status.INTERNAL,details:`Error deserializing request: ${X.message}`});return}$.type="READABLE",this.maybePushNextMessage()}maybePushNextMessage(){if(this.listener&&this.isReadPending&&this.readQueue.length>0&&this.readQueue[0].type!=="COMPRESSED"){this.isReadPending=!1;let $=this.readQueue.shift();if($.type==="READABLE")this.listener.onReceiveMessage($.parsedMessage);else this.listener.onReceiveHalfClose()}}handleDataFrame($){var Y;if(this.checkCancelled())return;qY("Request to "+this.handler.path+" received data frame of size "+$.length);let T;try{T=this.decoder.write($)}catch(q){this.sendStatus({code:o0.Status.RESOURCE_EXHAUSTED,details:q.message});return}for(let q of T){this.stream.pause();let X={type:"COMPRESSED",compressedMessage:q,parsedMessage:null};this.readQueue.push(X),this.decompressAndMaybePush(X),(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(qY("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,T=Object.assign(Object.assign(Object.assign({},sE),AS),Y);this.stream.respond(T,WS)}sendMessage($,Y){if(this.checkCancelled())return;let T;try{T=this.serializeMessage($)}catch(q){this.sendStatus({code:o0.Status.INTERNAL,details:`Error serializing response: ${(0,nE.getErrorMessage)(q)}`,metadata:null});return}if(this.maxSendMessageSize!==-1&&T.length-5>this.maxSendMessageSize){this.sendStatus({code:o0.Status.RESOURCE_EXHAUSTED,details:`Sent message larger than max (${T.length} vs. ${this.maxSendMessageSize})`,metadata:null});return}this.maybeSendMetadata(),qY("Request to "+this.handler.path+" sent data frame of size "+T.length),this.stream.write(T,(q)=>{var X;if(q){this.sendStatus({code:o0.Status.INTERNAL,details:`Error writing message: ${(0,nE.getErrorMessage)(q)}`,metadata:null});return}(X=this.callEventTracker)===null||X===void 0||X.addMessageSent(),Y()})}sendStatus($){var Y,T,q;if(this.checkCancelled())return;qY("Request to method "+((Y=this.handler)===null||Y===void 0?void 0:Y.path)+" ended with status code: "+o0.Status[$.code]+" details: "+$.details);let X=(q=(T=$.metadata)===null||T===void 0?void 0:T.clone())!==null&&q!==void 0?q:new oq.Metadata;if(this.shouldSendMetrics)X.set(rE.GRPC_METRICS_HEADER,this.metricsRecorder.serialize());if(this.metadataSent)if(!this.wantTrailers)this.wantTrailers=!0,this.stream.once("wantTrailers",()=>{if(this.callEventTracker&&!this.streamEnded)this.streamEnded=!0,this.callEventTracker.onStreamEnd(!0),this.callEventTracker.onCallEnd($);let J=Object.assign({[oE]:$.code,[aE]:encodeURI($.details)},X.toHttp2Headers());this.stream.sendTrailers(J),this.notifyOnCancel()}),this.stream.end();else this.notifyOnCancel();else{if(this.callEventTracker&&!this.streamEnded)this.streamEnded=!0,this.callEventTracker.onStreamEnd(!0),this.callEventTracker.onCallEnd($);let J=Object.assign(Object.assign({[oE]:$.code,[aE]:encodeURI($.details)},sE),X.toHttp2Headers());this.stream.respond(J,{endStream:!0}),this.notifyOnCancel()}}startRead(){if(qY("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 QS.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}}JV.BaseServerInterceptingCall=qJ;function GS($,Y,T,q,X,J){let Q={path:X.path,requestStream:X.type==="clientStream"||X.type==="bidi",responseStream:X.type==="serverStream"||X.type==="bidi",requestDeserialize:X.deserialize,responseSerialize:X.serialize},U=new qJ(Y,T,q,X,J);return $.reduce((Z,K)=>{return K(Q,Z)},U)}});var EV=M((k$)=>{var HS=k$&&k$.__runInitializers||function($,Y,T){var q=arguments.length>2;for(var X=0;X<Y.length;X++)T=q?Y[X].call($,T):Y[X].call($);return q?T:void 0},zS=k$&&k$.__esDecorate||function($,Y,T,q,X,J){function Q(B){if(B!==void 0&&typeof B!=="function")throw TypeError("Function expected");return B}var U=q.kind,Z=U==="getter"?"get":U==="setter"?"set":"value",K=!Y&&$?q.static?$:$.prototype:null,A=Y||(K?Object.getOwnPropertyDescriptor(K,q.name):{}),W,E=!1;for(var D=T.length-1;D>=0;D--){var F={};for(var H in q)F[H]=H==="access"?{}:q[H];for(var H in q.access)F.access[H]=q.access[H];F.addInitializer=function(B){if(E)throw TypeError("Cannot add initializers after decoration has completed");J.push(Q(B||null))};var V=(0,T[D])(U==="accessor"?{get:A.get,set:A.set}:A[Z],F);if(U==="accessor"){if(V===void 0)continue;if(V===null||typeof V!=="object")throw TypeError("Object expected");if(W=Q(V.get))A.get=W;if(W=Q(V.set))A.set=W;if(W=Q(V.init))X.unshift(W)}else if(W=Q(V))if(U==="field")X.unshift(W);else A[Z]=W}if(K)Object.defineProperty(K,q.name,A);E=!0};Object.defineProperty(k$,"__esModule",{value:!0});k$.Server=void 0;var s0=s("http2"),IS=s("util"),N0=i(),oY=CE(),JJ=lq(),UV=B1(),aY=U0(),x$=r0(),y1=p0(),M0=y$(),ZV=XJ(),rY=2147483647,QJ=2147483647,MS=20000,KV=2147483647,{HTTP2_HEADER_PATH:AV}=s0.constants,BS="server",WV=Buffer.from("max_age");function GV($){aY.trace(N0.LogVerbosity.DEBUG,"server_call",$)}function RS(){}function OS($){return function(Y,T){return IS.deprecate(Y,$)}}function UJ($){return{code:N0.Status.UNIMPLEMENTED,details:`The server does not implement the method ${$}`}}function PS($,Y){let T=UJ(Y);switch($){case"unary":return(q,X)=>{X(T,null)};case"clientStream":return(q,X)=>{X(T,null)};case"serverStream":return(q)=>{q.emit("error",T)};case"bidi":return(q)=>{q.emit("error",T)};default:throw Error(`Invalid handlerType ${$}`)}}var LS=(()=>{var $;let Y=[],T;return $=class{constructor(X){var J,Q,U,Z,K,A;if(this.boundPorts=(HS(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=X!==null&&X!==void 0?X:{},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=(J=this.options["grpc.max_connection_age_ms"])!==null&&J!==void 0?J:rY,this.maxConnectionAgeGraceMs=(Q=this.options["grpc.max_connection_age_grace_ms"])!==null&&Q!==void 0?Q:rY,this.keepaliveTimeMs=(U=this.options["grpc.keepalive_time_ms"])!==null&&U!==void 0?U:QJ,this.keepaliveTimeoutMs=(Z=this.options["grpc.keepalive_timeout_ms"])!==null&&Z!==void 0?Z:MS,this.sessionIdleTimeout=(K=this.options["grpc.max_connection_idle_ms"])!==null&&K!==void 0?K:KV,this.commonServerOptions={maxSendHeaderBlockLength:Number.MAX_SAFE_INTEGER},"grpc-node.max_session_memory"in this.options)this.commonServerOptions.maxSessionMemory=this.options["grpc-node.max_session_memory"];else this.commonServerOptions.maxSessionMemory=Number.MAX_SAFE_INTEGER;if("grpc.max_concurrent_streams"in this.options)this.commonServerOptions.settings={maxConcurrentStreams:this.options["grpc.max_concurrent_streams"]};this.interceptors=(A=this.options.interceptors)!==null&&A!==void 0?A:[],this.trace("Server constructed")}getChannelzInfo(){return{trace:this.channelzTrace,callTracker:this.callTracker,listenerChildren:this.listenerChildrenTracker.getChildLists(),sessionChildren:this.sessionChildrenTracker.getChildLists()}}getChannelzSessionInfo(X){var J,Q,U;let Z=this.sessions.get(X),K=X.socket,A=K.remoteAddress?(0,x$.stringToSubchannelAddress)(K.remoteAddress,K.remotePort):null,W=K.localAddress?(0,x$.stringToSubchannelAddress)(K.localAddress,K.localPort):null,E;if(X.encrypted){let F=K,H=F.getCipher(),V=F.getCertificate(),B=F.getPeerCertificate();E={cipherSuiteStandardName:(J=H.standardName)!==null&&J!==void 0?J:null,cipherSuiteOtherName:H.standardName?null:H.name,localCertificate:V&&"raw"in V?V.raw:null,remoteCertificate:B&&"raw"in B?B.raw:null}}else E=null;return{remoteAddress:A,localAddress:W,security:E,remoteName:null,streamsStarted:Z.streamTracker.callsStarted,streamsSucceeded:Z.streamTracker.callsSucceeded,streamsFailed:Z.streamTracker.callsFailed,messagesSent:Z.messagesSent,messagesReceived:Z.messagesReceived,keepAlivesSent:Z.keepAlivesSent,lastLocalStreamCreatedTimestamp:null,lastRemoteStreamCreatedTimestamp:Z.streamTracker.lastCallStartedTimestamp,lastMessageSentTimestamp:Z.lastMessageSentTimestamp,lastMessageReceivedTimestamp:Z.lastMessageReceivedTimestamp,localFlowControlWindow:(Q=X.state.localWindowSize)!==null&&Q!==void 0?Q:null,remoteFlowControlWindow:(U=X.state.remoteWindowSize)!==null&&U!==void 0?U:null}}trace(X){aY.trace(N0.LogVerbosity.DEBUG,BS,"("+this.channelzRef.id+") "+X)}keepaliveTrace(X){aY.trace(N0.LogVerbosity.DEBUG,"keepalive","("+this.channelzRef.id+") "+X)}addProtoService(){throw Error("Not implemented. Use addService() instead")}addService(X,J){if(X===null||typeof X!=="object"||J===null||typeof J!=="object")throw Error("addService() requires two objects as arguments");let Q=Object.keys(X);if(Q.length===0)throw Error("Cannot add an empty service to a server");Q.forEach((U)=>{let Z=X[U],K;if(Z.requestStream)if(Z.responseStream)K="bidi";else K="clientStream";else if(Z.responseStream)K="serverStream";else K="unary";let A=J[U],W;if(A===void 0&&typeof Z.originalName==="string")A=J[Z.originalName];if(A!==void 0)W=A.bind(J);else W=PS(K,U);if(this.register(Z.path,W,Z.responseSerialize,Z.requestDeserialize,K)===!1)throw Error(`Method handler for ${Z.path} already provided.`)})}removeService(X){if(X===null||typeof X!=="object")throw Error("removeService() requires object as argument");Object.keys(X).forEach((Q)=>{let U=X[Q];this.unregister(U.path)})}bind(X,J){throw Error("Not implemented. Use bindAsync() instead")}experimentalRegisterListenerToChannelz(X){return(0,M0.registerChannelzSocket)((0,x$.subchannelAddressToString)(X),()=>{return{localAddress:X,remoteAddress:null,security:null,remoteName:null,streamsStarted:0,streamsSucceeded:0,streamsFailed:0,messagesSent:0,messagesReceived:0,keepAlivesSent:0,lastLocalStreamCreatedTimestamp:null,lastRemoteStreamCreatedTimestamp:null,lastMessageSentTimestamp:null,lastMessageReceivedTimestamp:null,localFlowControlWindow:null,remoteFlowControlWindow:null}},this.channelzEnabled)}experimentalUnregisterListenerFromChannelz(X){(0,M0.unregisterChannelzRef)(X)}createHttp2Server(X){let J;if(X._isSecure()){let Q=X._getConstructorOptions(),U=X._getSecureContextOptions(),Z=Object.assign(Object.assign(Object.assign(Object.assign({},this.commonServerOptions),Q),U),{enableTrace:this.options["grpc-node.tls_enable_trace"]===1}),K=U!==null;this.trace("Initial credentials valid: "+K),J=s0.createSecureServer(Z),J.prependListener("connection",(W)=>{if(!K)this.trace("Dropped connection from "+JSON.stringify(W.address())+" due to unloaded credentials"),W.destroy()}),J.on("secureConnection",(W)=>{W.on("error",(E)=>{this.trace("An incoming TLS connection closed with error: "+E.message)})});let A=(W)=>{if(W){let E=J;try{E.setSecureContext(W)}catch(D){aY.log(N0.LogVerbosity.ERROR,"Failed to set secure context with error "+D.message),W=null}}K=W!==null,this.trace("Post-update credentials valid: "+K)};X._addWatcher(A),J.on("close",()=>{X._removeWatcher(A)})}else J=s0.createServer(this.commonServerOptions);return J.setTimeout(0,RS),this._setupHandlers(J,X._getInterceptors()),J}bindOneAddress(X,J){this.trace("Attempting to bind "+(0,x$.subchannelAddressToString)(X));let Q=this.createHttp2Server(J.credentials);return new Promise((U,Z)=>{let K=(A)=>{this.trace("Failed to bind "+(0,x$.subchannelAddressToString)(X)+" with error "+A.message),U({port:"port"in X?X.port:1,error:A.message})};Q.once("error",K),Q.listen(X,()=>{let A=Q.address(),W;if(typeof A==="string")W={path:A};else W={host:A.address,port:A.port};let E=this.experimentalRegisterListenerToChannelz(W);this.listenerChildrenTracker.refChild(E),this.http2Servers.set(Q,{channelzRef:E,sessions:new Set,ownsChannelzRef:!0}),J.listeningServers.add(Q),this.trace("Successfully bound "+(0,x$.subchannelAddressToString)(W)),U({port:"port"in W?W.port:1}),Q.removeListener("error",K)})})}async bindManyPorts(X,J){if(X.length===0)return{count:0,port:0,errors:[]};if((0,x$.isTcpSubchannelAddress)(X[0])&&X[0].port===0){let Q=await this.bindOneAddress(X[0],J);if(Q.error){let U=await this.bindManyPorts(X.slice(1),J);return Object.assign(Object.assign({},U),{errors:[Q.error,...U.errors]})}else{let U=X.slice(1).map((A)=>(0,x$.isTcpSubchannelAddress)(A)?{host:A.host,port:Q.port}:A),Z=await Promise.all(U.map((A)=>this.bindOneAddress(A,J))),K=[Q,...Z];return{count:K.filter((A)=>A.error===void 0).length,port:Q.port,errors:K.filter((A)=>A.error).map((A)=>A.error)}}}else{let Q=await Promise.all(X.map((U)=>this.bindOneAddress(U,J)));return{count:Q.filter((U)=>U.error===void 0).length,port:Q[0].port,errors:Q.filter((U)=>U.error).map((U)=>U.error)}}}async bindAddressList(X,J){let Q=await this.bindManyPorts(X,J);if(Q.count>0){if(Q.count<X.length)aY.log(N0.LogVerbosity.INFO,`WARNING Only ${Q.count} addresses added out of total ${X.length} resolved`);return Q.port}else{let U=`No address added out of total ${X.length} resolved`;throw aY.log(N0.LogVerbosity.ERROR,U),Error(`${U} errors: [${Q.errors.join(",")}]`)}}resolvePort(X){return new Promise((J,Q)=>{let U=!1,Z=(A,W,E,D)=>{if(U)return!0;if(U=!0,!A.ok)return Q(Error(A.error.details)),!0;let F=[].concat(...A.value.map((H)=>H.addresses));if(F.length===0)return Q(Error(`No addresses resolved for port ${X}`)),!0;return J(F),!0};(0,UV.createResolver)(X,Z,this.options).updateResolution()})}async bindPort(X,J){let Q=await this.resolvePort(X);if(J.cancelled)throw this.completeUnbind(J),Error("bindAsync operation cancelled by unbind call");let U=await this.bindAddressList(Q,J);if(J.cancelled)throw this.completeUnbind(J),Error("bindAsync operation cancelled by unbind call");return U}normalizePort(X){let J=(0,y1.parseUri)(X);if(J===null)throw Error(`Could not parse port "${X}"`);let Q=(0,UV.mapUriDefaultScheme)(J);if(Q===null)throw Error(`Could not get a default scheme for port "${X}"`);return Q}bindAsync(X,J,Q){if(this.shutdown)throw Error("bindAsync called after shutdown");if(typeof X!=="string")throw TypeError("port must be a string");if(J===null||!(J instanceof JJ.ServerCredentials))throw TypeError("creds must be a ServerCredentials object");if(typeof Q!=="function")throw TypeError("callback must be a function");this.trace("bindAsync port="+X);let U=this.normalizePort(X),Z=(E,D)=>{process.nextTick(()=>Q(E,D))},K=this.boundPorts.get((0,y1.uriToString)(U));if(K){if(!J._equals(K.credentials)){Z(Error(`${X} already bound with incompatible credentials`),0);return}if(K.cancelled=!1,K.completionPromise)K.completionPromise.then((E)=>Q(null,E),(E)=>Q(E,0));else Z(null,K.portNumber);return}K={mapKey:(0,y1.uriToString)(U),originalUri:U,completionPromise:null,cancelled:!1,portNumber:0,credentials:J,listeningServers:new Set};let A=(0,y1.splitHostPort)(U.path),W=this.bindPort(U,K);if(K.completionPromise=W,(A===null||A===void 0?void 0:A.port)===0)W.then((E)=>{let D={scheme:U.scheme,authority:U.authority,path:(0,y1.combineHostPort)({host:A.host,port:E})};K.mapKey=(0,y1.uriToString)(D),K.completionPromise=null,K.portNumber=E,this.boundPorts.set(K.mapKey,K),Q(null,E)},(E)=>{Q(E,0)});else this.boundPorts.set(K.mapKey,K),W.then((E)=>{K.completionPromise=null,K.portNumber=E,Q(null,E)},(E)=>{Q(E,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(X,J,Q=!1){if(X===null||!(X instanceof JJ.ServerCredentials))throw TypeError("creds must be a ServerCredentials object");if(this.channelzEnabled)this.listenerChildrenTracker.refChild(J);let U=this.createHttp2Server(X),Z=new Set;return this.http2Servers.set(U,{channelzRef:J,sessions:Z,ownsChannelzRef:Q}),{injectConnection:(K)=>{U.emit("connection",K)},drain:(K)=>{var A,W;for(let E of Z)this.closeSession(E);(W=(A=setTimeout(()=>{for(let E of Z)E.destroy(s0.constants.NGHTTP2_CANCEL)},K)).unref)===null||W===void 0||W.call(A)},destroy:()=>{this.closeServer(U);for(let K of Z)this.closeSession(K)}}}createConnectionInjector(X){if(X===null||!(X instanceof JJ.ServerCredentials))throw TypeError("creds must be a ServerCredentials object");let J=this.registerInjectorToChannelz();return this.experimentalCreateConnectionInjectorWithChannelzRef(X,J,!0)}closeServer(X,J){this.trace("Closing server with address "+JSON.stringify(X.address()));let Q=this.http2Servers.get(X);X.close(()=>{if(Q&&Q.ownsChannelzRef)this.listenerChildrenTracker.unrefChild(Q.channelzRef),(0,M0.unregisterChannelzRef)(Q.channelzRef);this.http2Servers.delete(X),J===null||J===void 0||J()})}closeSession(X,J){var Q;this.trace("Closing session initiated by "+((Q=X.socket)===null||Q===void 0?void 0:Q.remoteAddress));let U=this.sessions.get(X),Z=()=>{if(U)this.sessionChildrenTracker.unrefChild(U.ref),(0,M0.unregisterChannelzRef)(U.ref);J===null||J===void 0||J()};if(X.closed)queueMicrotask(Z);else X.close(Z)}completeUnbind(X){for(let J of X.listeningServers){let Q=this.http2Servers.get(J);if(this.closeServer(J,()=>{X.listeningServers.delete(J)}),Q)for(let U of Q.sessions)this.closeSession(U)}this.boundPorts.delete(X.mapKey)}unbind(X){this.trace("unbind port="+X);let J=this.normalizePort(X),Q=(0,y1.splitHostPort)(J.path);if((Q===null||Q===void 0?void 0:Q.port)===0)throw Error("Cannot unbind port 0");let U=this.boundPorts.get((0,y1.uriToString)(J));if(U)if(this.trace("unbinding "+U.mapKey+" originally bound as "+(0,y1.uriToString)(U.originalUri)),U.completionPromise)U.cancelled=!0;else this.completeUnbind(U)}drain(X,J){var Q,U;this.trace("drain port="+X+" graceTimeMs="+J);let Z=this.normalizePort(X),K=(0,y1.splitHostPort)(Z.path);if((K===null||K===void 0?void 0:K.port)===0)throw Error("Cannot drain port 0");let A=this.boundPorts.get((0,y1.uriToString)(Z));if(!A)return;let W=new Set;for(let E of A.listeningServers){let D=this.http2Servers.get(E);if(D)for(let F of D.sessions)W.add(F),this.closeSession(F,()=>{W.delete(F)})}(U=(Q=setTimeout(()=>{for(let E of W)E.destroy(s0.constants.NGHTTP2_CANCEL)},J)).unref)===null||U===void 0||U.call(Q)}forceShutdown(){for(let X of this.boundPorts.values())X.cancelled=!0;this.boundPorts.clear();for(let X of this.http2Servers.keys())this.closeServer(X);this.sessions.forEach((X,J)=>{this.closeSession(J),J.destroy(s0.constants.NGHTTP2_CANCEL)}),this.sessions.clear(),(0,M0.unregisterChannelzRef)(this.channelzRef),this.shutdown=!0}register(X,J,Q,U,Z){if(this.handlers.has(X))return!1;return this.handlers.set(X,{func:J,serialize:Q,deserialize:U,type:Z,path:X}),!0}unregister(X){return this.handlers.delete(X)}start(){if(this.http2Servers.size===0||[...this.http2Servers.keys()].every((X)=>!X.listening))throw Error("server must be bound in order to start");if(this.started===!0)throw Error("server is already started");this.started=!0}tryShutdown(X){var J;let Q=(K)=>{(0,M0.unregisterChannelzRef)(this.channelzRef),X(K)},U=0;function Z(){if(U--,U===0)Q()}this.shutdown=!0;for(let[K,A]of this.http2Servers.entries()){U++;let W=A.channelzRef.name;this.trace("Waiting for server "+W+" to close"),this.closeServer(K,()=>{this.trace("Server "+W+" finished closing"),Z()});for(let E of A.sessions.keys()){U++;let D=(J=E.socket)===null||J===void 0?void 0:J.remoteAddress;this.trace("Waiting for session "+D+" to close"),this.closeSession(E,()=>{this.trace("Session "+D+" finished closing"),Z()})}}if(U===0)Q()}addHttp2Port(){throw Error("Not yet implemented")}getChannelzRef(){return this.channelzRef}_verifyContentType(X,J){let Q=J[s0.constants.HTTP2_HEADER_CONTENT_TYPE];if(typeof Q!=="string"||!Q.startsWith("application/grpc"))return X.respond({[s0.constants.HTTP2_HEADER_STATUS]:s0.constants.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE},{endStream:!0}),!1;return!0}_retrieveHandler(X){GV("Received call to method "+X+" at address "+this.serverAddressString);let J=this.handlers.get(X);if(J===void 0)return GV("No handler registered for method "+X+". Sending UNIMPLEMENTED status."),null;return J}_respondWithError(X,J,Q=null){var U,Z;let K=Object.assign({"grpc-status":(U=X.code)!==null&&U!==void 0?U:N0.Status.INTERNAL,"grpc-message":X.details,[s0.constants.HTTP2_HEADER_STATUS]:s0.constants.HTTP_STATUS_OK,[s0.constants.HTTP2_HEADER_CONTENT_TYPE]:"application/grpc+proto"},(Z=X.metadata)===null||Z===void 0?void 0:Z.toHttp2Headers());J.respond(K,{endStream:!0}),this.callTracker.addCallFailed(),Q===null||Q===void 0||Q.streamTracker.addCallFailed()}_channelzHandler(X,J,Q){this.onStreamOpened(J);let U=this.sessions.get(J.session);if(this.callTracker.addCallStarted(),U===null||U===void 0||U.streamTracker.addCallStarted(),!this._verifyContentType(J,Q)){this.callTracker.addCallFailed(),U===null||U===void 0||U.streamTracker.addCallFailed();return}let Z=Q[AV],K=this._retrieveHandler(Z);if(!K){this._respondWithError(UJ(Z),J,U);return}let A={addMessageSent:()=>{if(U)U.messagesSent+=1,U.lastMessageSentTimestamp=new Date},addMessageReceived:()=>{if(U)U.messagesReceived+=1,U.lastMessageReceivedTimestamp=new Date},onCallEnd:(E)=>{if(E.code===N0.Status.OK)this.callTracker.addCallSucceeded();else this.callTracker.addCallFailed()},onStreamEnd:(E)=>{if(U)if(E)U.streamTracker.addCallSucceeded();else U.streamTracker.addCallFailed()}},W=(0,ZV.getServerInterceptingCall)([...X,...this.interceptors],J,Q,A,K,this.options);if(!this._runHandlerForCall(W,K))this.callTracker.addCallFailed(),U===null||U===void 0||U.streamTracker.addCallFailed(),W.sendStatus({code:N0.Status.INTERNAL,details:`Unknown handler type: ${K.type}`})}_streamHandler(X,J,Q){if(this.onStreamOpened(J),this._verifyContentType(J,Q)!==!0)return;let U=Q[AV],Z=this._retrieveHandler(U);if(!Z){this._respondWithError(UJ(U),J,null);return}let K=(0,ZV.getServerInterceptingCall)([...X,...this.interceptors],J,Q,null,Z,this.options);if(!this._runHandlerForCall(K,Z))K.sendStatus({code:N0.Status.INTERNAL,details:`Unknown handler type: ${Z.type}`})}_runHandlerForCall(X,J){let{type:Q}=J;if(Q==="unary")wS(X,J);else if(Q==="clientStream")SS(X,J);else if(Q==="serverStream")CS(X,J);else if(Q==="bidi")yS(X,J);else return!1;return!0}_setupHandlers(X,J){if(X===null)return;let Q=X.address(),U="null";if(Q)if(typeof Q==="string")U=Q;else U=Q.address+":"+Q.port;this.serverAddressString=U;let Z=this.channelzEnabled?this._channelzHandler:this._streamHandler,K=this.channelzEnabled?this._channelzSessionHandler(X):this._sessionHandler(X);X.on("stream",Z.bind(this,J)),X.on("session",K)}_sessionHandler(X){return(J)=>{var Q,U;(Q=this.http2Servers.get(X))===null||Q===void 0||Q.sessions.add(J);let Z=null,K=null,A=null,W=!1,E=this.enableIdleTimeout(J);if(this.maxConnectionAgeMs!==rY){let B=this.maxConnectionAgeMs/10,S=Math.random()*B*2-B;Z=setTimeout(()=>{var v,z;W=!0,this.trace("Connection dropped by max connection age: "+((v=J.socket)===null||v===void 0?void 0:v.remoteAddress));try{J.goaway(s0.constants.NGHTTP2_NO_ERROR,2147483647,WV)}catch(_){J.destroy();return}if(J.close(),this.maxConnectionAgeGraceMs!==rY)K=setTimeout(()=>{J.destroy()},this.maxConnectionAgeGraceMs),(z=K.unref)===null||z===void 0||z.call(K)},this.maxConnectionAgeMs+S),(U=Z.unref)===null||U===void 0||U.call(Z)}let D=()=>{if(A)clearTimeout(A),A=null},F=()=>{return!J.destroyed&&this.keepaliveTimeMs<QJ&&this.keepaliveTimeMs>0},H,V=()=>{var B;if(!F())return;this.keepaliveTrace("Starting keepalive timer for "+this.keepaliveTimeMs+"ms"),A=setTimeout(()=>{D(),H()},this.keepaliveTimeMs),(B=A.unref)===null||B===void 0||B.call(A)};H=()=>{var B;if(!F())return;this.keepaliveTrace("Sending ping with timeout "+this.keepaliveTimeoutMs+"ms");let S="";try{if(!J.ping((z,_,y)=>{if(D(),z)this.keepaliveTrace("Ping failed with error: "+z.message),W=!0,J.destroy();else this.keepaliveTrace("Received ping response"),V()}))S="Ping returned false"}catch(v){S=(v instanceof Error?v.message:"")||"Unknown error"}if(S){this.keepaliveTrace("Ping send failed: "+S),this.trace("Connection dropped due to ping send error: "+S),W=!0,J.destroy();return}A=setTimeout(()=>{D(),this.keepaliveTrace("Ping timeout passed without response"),this.trace("Connection dropped by keepalive timeout"),W=!0,J.destroy()},this.keepaliveTimeoutMs),(B=A.unref)===null||B===void 0||B.call(A)},V(),J.on("close",()=>{var B,S;if(!W)this.trace(`Connection dropped by client ${(B=J.socket)===null||B===void 0?void 0:B.remoteAddress}`);if(Z)clearTimeout(Z);if(K)clearTimeout(K);if(D(),E!==null)clearTimeout(E.timeout),this.sessionIdleTimeouts.delete(J);(S=this.http2Servers.get(X))===null||S===void 0||S.sessions.delete(J)})}}_channelzSessionHandler(X){return(J)=>{var Q,U,Z,K;let A=(0,M0.registerChannelzSocket)((U=(Q=J.socket)===null||Q===void 0?void 0:Q.remoteAddress)!==null&&U!==void 0?U:"unknown",this.getChannelzSessionInfo.bind(this,J),this.channelzEnabled),W={ref:A,streamTracker:new M0.ChannelzCallTracker,messagesSent:0,messagesReceived:0,keepAlivesSent:0,lastMessageSentTimestamp:null,lastMessageReceivedTimestamp:null};(Z=this.http2Servers.get(X))===null||Z===void 0||Z.sessions.add(J),this.sessions.set(J,W);let E=`${J.socket.remoteAddress}:${J.socket.remotePort}`;this.channelzTrace.addTrace("CT_INFO","Connection established by client "+E),this.trace("Connection established by client "+E),this.sessionChildrenTracker.refChild(A);let D=null,F=null,H=null,V=!1,B=this.enableIdleTimeout(J);if(this.maxConnectionAgeMs!==rY){let y=this.maxConnectionAgeMs/10,k=Math.random()*y*2-y;D=setTimeout(()=>{var m;V=!0,this.channelzTrace.addTrace("CT_INFO","Connection dropped by max connection age from "+E);try{J.goaway(s0.constants.NGHTTP2_NO_ERROR,2147483647,WV)}catch(C){J.destroy();return}if(J.close(),this.maxConnectionAgeGraceMs!==rY)F=setTimeout(()=>{J.destroy()},this.maxConnectionAgeGraceMs),(m=F.unref)===null||m===void 0||m.call(F)},this.maxConnectionAgeMs+k),(K=D.unref)===null||K===void 0||K.call(D)}let S=()=>{if(H)clearTimeout(H),H=null},v=()=>{return!J.destroyed&&this.keepaliveTimeMs<QJ&&this.keepaliveTimeMs>0},z,_=()=>{var y;if(!v())return;this.keepaliveTrace("Starting keepalive timer for "+this.keepaliveTimeMs+"ms"),H=setTimeout(()=>{S(),z()},this.keepaliveTimeMs),(y=H.unref)===null||y===void 0||y.call(H)};z=()=>{var y;if(!v())return;this.keepaliveTrace("Sending ping with timeout "+this.keepaliveTimeoutMs+"ms");let k="";try{if(!J.ping((C,j,I)=>{if(S(),C)this.keepaliveTrace("Ping failed with error: "+C.message),this.channelzTrace.addTrace("CT_INFO","Connection dropped due to error of a ping frame "+C.message+" return in "+j),V=!0,J.destroy();else this.keepaliveTrace("Received ping response"),_()}))k="Ping returned false"}catch(m){k=(m instanceof Error?m.message:"")||"Unknown error"}if(k){this.keepaliveTrace("Ping send failed: "+k),this.channelzTrace.addTrace("CT_INFO","Connection dropped due to ping send error: "+k),V=!0,J.destroy();return}W.keepAlivesSent+=1,H=setTimeout(()=>{S(),this.keepaliveTrace("Ping timeout passed without response"),this.channelzTrace.addTrace("CT_INFO","Connection dropped by keepalive timeout from "+E),V=!0,J.destroy()},this.keepaliveTimeoutMs),(y=H.unref)===null||y===void 0||y.call(H)},_(),J.on("close",()=>{var y;if(!V)this.channelzTrace.addTrace("CT_INFO","Connection dropped by client "+E);if(this.sessionChildrenTracker.unrefChild(A),(0,M0.unregisterChannelzRef)(A),D)clearTimeout(D);if(F)clearTimeout(F);if(S(),B!==null)clearTimeout(B.timeout),this.sessionIdleTimeouts.delete(J);(y=this.http2Servers.get(X))===null||y===void 0||y.sessions.delete(J),this.sessions.delete(J)})}}enableIdleTimeout(X){var J,Q;if(this.sessionIdleTimeout>=KV)return null;let U={activeStreams:0,lastIdle:Date.now(),onClose:this.onStreamClose.bind(this,X),timeout:setTimeout(this.onIdleTimeout,this.sessionIdleTimeout,this,X)};(Q=(J=U.timeout).unref)===null||Q===void 0||Q.call(J),this.sessionIdleTimeouts.set(X,U);let{socket:Z}=X;return this.trace("Enable idle timeout for "+Z.remoteAddress+":"+Z.remotePort),U}onIdleTimeout(X,J){let{socket:Q}=J,U=X.sessionIdleTimeouts.get(J);if(U!==void 0&&U.activeStreams===0)if(Date.now()-U.lastIdle>=X.sessionIdleTimeout)X.trace("Session idle timeout triggered for "+(Q===null||Q===void 0?void 0:Q.remoteAddress)+":"+(Q===null||Q===void 0?void 0:Q.remotePort)+" last idle at "+U.lastIdle),X.closeSession(J);else U.timeout.refresh()}onStreamOpened(X){let J=X.session,Q=this.sessionIdleTimeouts.get(J);if(Q)Q.activeStreams+=1,X.once("close",Q.onClose)}onStreamClose(X){var J,Q;let U=this.sessionIdleTimeouts.get(X);if(U){if(U.activeStreams-=1,U.activeStreams===0)U.lastIdle=Date.now(),U.timeout.refresh(),this.trace("Session onStreamClose"+((J=X.socket)===null||J===void 0?void 0:J.remoteAddress)+":"+((Q=X.socket)===null||Q===void 0?void 0:Q.remotePort)+" at "+U.lastIdle)}}},(()=>{let q=typeof Symbol==="function"&&Symbol.metadata?Object.create(null):void 0;if(T=[OS("Calling start() is no longer necessary. It can be safely omitted.")],zS($,null,T,{kind:"method",name:"start",static:!1,private:!1,access:{has:(X)=>("start"in X),get:(X)=>X.start},metadata:q},null,Y),q)Object.defineProperty($,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:q})})(),$})();k$.Server=LS;async function wS($,Y){let T;function q(Q,U,Z,K){if(Q){$.sendStatus((0,oY.serverErrorToStatus)(Q,Z));return}$.sendMessage(U,()=>{$.sendStatus({code:N0.Status.OK,details:"OK",metadata:Z!==null&&Z!==void 0?Z:null})})}let X,J=null;$.start({onReceiveMetadata(Q){X=Q,$.startRead()},onReceiveMessage(Q){if(J){$.sendStatus({code:N0.Status.UNIMPLEMENTED,details:`Received a second request message for server streaming method ${Y.path}`,metadata:null});return}J=Q,$.startRead()},onReceiveHalfClose(){if(!J){$.sendStatus({code:N0.Status.UNIMPLEMENTED,details:`Received no request message for server streaming method ${Y.path}`,metadata:null});return}T=new oY.ServerWritableStreamImpl(Y.path,$,X,J);try{Y.func(T,q)}catch(Q){$.sendStatus({code:N0.Status.UNKNOWN,details:`Server method handler threw error ${Q.message}`,metadata:null})}},onCancel(){if(T)T.cancelled=!0,T.emit("cancelled","cancelled")}})}function SS($,Y){let T;function q(X,J,Q,U){if(X){$.sendStatus((0,oY.serverErrorToStatus)(X,Q));return}$.sendMessage(J,()=>{$.sendStatus({code:N0.Status.OK,details:"OK",metadata:Q!==null&&Q!==void 0?Q:null})})}$.start({onReceiveMetadata(X){T=new oY.ServerDuplexStreamImpl(Y.path,$,X);try{Y.func(T,q)}catch(J){$.sendStatus({code:N0.Status.UNKNOWN,details:`Server method handler threw error ${J.message}`,metadata:null})}},onReceiveMessage(X){T.push(X)},onReceiveHalfClose(){T.push(null)},onCancel(){if(T)T.cancelled=!0,T.emit("cancelled","cancelled"),T.destroy()}})}function CS($,Y){let T,q,X=null;$.start({onReceiveMetadata(J){q=J,$.startRead()},onReceiveMessage(J){if(X){$.sendStatus({code:N0.Status.UNIMPLEMENTED,details:`Received a second request message for server streaming method ${Y.path}`,metadata:null});return}X=J,$.startRead()},onReceiveHalfClose(){if(!X){$.sendStatus({code:N0.Status.UNIMPLEMENTED,details:`Received no request message for server streaming method ${Y.path}`,metadata:null});return}T=new oY.ServerWritableStreamImpl(Y.path,$,q,X);try{Y.func(T)}catch(J){$.sendStatus({code:N0.Status.UNKNOWN,details:`Server method handler threw error ${J.message}`,metadata:null})}},onCancel(){if(T)T.cancelled=!0,T.emit("cancelled","cancelled"),T.destroy()}})}function yS($,Y){let T;$.start({onReceiveMetadata(q){T=new oY.ServerDuplexStreamImpl(Y.path,$,q);try{Y.func(T)}catch(X){$.sendStatus({code:N0.Status.UNKNOWN,details:`Server method handler threw error ${X.message}`,metadata:null})}},onReceiveMessage(q){T.push(q)},onReceiveHalfClose(){T.push(null)},onCancel(){if(T)T.cancelled=!0,T.emit("cancelled","cancelled"),T.destroy()}})}});var NV=M((DV)=>{Object.defineProperty(DV,"__esModule",{value:!0});DV.StatusBuilder=void 0;class VV{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 $}}DV.StatusBuilder=VV});var V6=M((PV)=>{Object.defineProperty(PV,"__esModule",{value:!0});PV.LeafLoadBalancer=PV.PickFirstLoadBalancer=PV.PickFirstLoadBalancingConfig=void 0;PV.shuffled=BV;PV.setup=mS;var ZJ=M$(),H0=l0(),h$=Y$(),HV=r0(),jS=U0(),vS=i(),zV=r0(),IV=s("net"),xS=l$(),kS="pick_first";function G6($){jS.trace(vS.LogVerbosity.DEBUG,kS,$)}var E6="pick_first",hS=250;class sY{constructor($){this.shuffleAddressList=$}getLoadBalancerName(){return E6}toJsonObject(){return{[E6]:{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)}}PV.PickFirstLoadBalancingConfig=sY;class MV{constructor($){this.subchannel=$}pick($){return{pickResultType:h$.PickResultType.COMPLETE,subchannel:this.subchannel,status:null,onCallStarted:null,onCallEnded:null}}}function BV($){let Y=$.slice();for(let T=Y.length-1;T>1;T--){let q=Math.floor(Math.random()*(T+1)),X=Y[T];Y[T]=Y[q],Y[q]=X}return Y}function _S($){if($.length===0)return[];let Y=[],T=[],q=[],X=(0,zV.isTcpSubchannelAddress)($[0])&&(0,IV.isIPv6)($[0].host);for(let U of $)if((0,zV.isTcpSubchannelAddress)(U)&&(0,IV.isIPv6)(U.host))T.push(U);else q.push(U);let J=X?T:q,Q=X?q:T;for(let U=0;U<Math.max(J.length,Q.length);U++){if(U<J.length)Y.push(J[U]);if(U<Q.length)Y.push(Q[U])}return Y}var RV="grpc-node.internal.pick-first.report_health_status";class sq{constructor($){this.channelControlHelper=$,this.children=[],this.currentState=H0.ConnectivityState.IDLE,this.currentSubchannelIndex=0,this.currentPick=null,this.subchannelStateListener=(Y,T,q,X,J)=>{this.onSubchannelStateUpdate(Y,T,q,J)},this.pickedSubchannelHealthListener=()=>this.calculateAndReportNewState(),this.stickyTransientFailureMode=!1,this.reportHealthStatus=!1,this.lastError=null,this.latestAddressList=null,this.latestOptions={},this.latestResolutionNote="",this.connectionDelayTimeout=setTimeout(()=>{},0),clearTimeout(this.connectionDelayTimeout)}allChildrenHaveReportedTF(){return this.children.every(($)=>$.hasReportedTransientFailure)}resetChildrenReportedTF(){this.children.every(($)=>$.hasReportedTransientFailure=!1)}calculateAndReportNewState(){var $;if(this.currentPick)if(this.reportHealthStatus&&!this.currentPick.isHealthy()){let 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 MV(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,T,q){var X;if((X=this.currentPick)===null||X===void 0?void 0:X.realSubchannelEquals($)){if(T!==H0.ConnectivityState.READY)this.removeCurrentPick(),this.calculateAndReportNewState();return}for(let[J,Q]of this.children.entries())if($.realSubchannelEquals(Q.subchannel)){if(T===H0.ConnectivityState.READY)this.pickSubchannel(Q.subchannel);if(T===H0.ConnectivityState.TRANSIENT_FAILURE){if(Q.hasReportedTransientFailure=!0,q)this.lastError=q;if(this.maybeEnterStickyTransientFailureMode(),J===this.currentSubchannelIndex)this.startNextSubchannelConnecting(J+1)}Q.subchannel.startConnecting();return}}startNextSubchannelConnecting($){clearTimeout(this.connectionDelayTimeout);for(let[Y,T]of this.children.entries())if(Y>=$){let q=T.subchannel.getConnectivityState();if(q===H0.ConnectivityState.IDLE||q===H0.ConnectivityState.CONNECTING){this.startConnecting(Y);return}}this.maybeEnterStickyTransientFailureMode()}startConnecting($){var Y,T;if(clearTimeout(this.connectionDelayTimeout),this.currentSubchannelIndex=$,this.children[$].subchannel.getConnectivityState()===H0.ConnectivityState.IDLE)G6("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)},hS),(T=(Y=this.connectionDelayTimeout).unref)===null||T===void 0||T.call(Y)}pickSubchannel($){G6("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,T){G6(H0.ConnectivityState[this.currentState]+" -> "+H0.ConnectivityState[$]),this.currentState=$,this.channelControlHelper.updateState($,Y,T)}resetSubchannelList(){for(let $ of this.children)$.subchannel.removeConnectivityStateListener(this.subchannelStateListener),$.subchannel.unref(),this.channelControlHelper.removeChannelzChild($.subchannel.getChannelzRef());this.currentSubchannelIndex=0,this.children=[]}connectToAddressList($,Y){G6("connectToAddressList(["+$.map((q)=>(0,HV.subchannelAddressToString)(q))+"])");let T=$.map((q)=>({subchannel:this.channelControlHelper.createSubchannel(q,Y),hasReportedTransientFailure:!1}));for(let{subchannel:q}of T)if(q.getConnectivityState()===H0.ConnectivityState.READY){this.pickSubchannel(q);return}for(let{subchannel:q}of T)q.ref(),this.channelControlHelper.addChannelzChild(q.getChannelzRef());this.resetSubchannelList(),this.children=T;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,T,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 X=$.value;if(this.reportHealthStatus=T[RV],Y.getShuffleAddressList())X=BV(X);let J=[].concat(...X.map((U)=>U.addresses));G6("updateAddressList(["+J.map((U)=>(0,HV.subchannelAddressToString)(U))+"])");let Q=_S(J);if(this.latestAddressList=Q,this.latestOptions=T,this.connectToAddressList(Q,T),this.latestResolutionNote=q,J.length>0)return!0;else return this.lastError="No addresses resolved",!1}exitIdle(){if(this.currentState===H0.ConnectivityState.IDLE&&this.latestAddressList)this.connectToAddressList(this.latestAddressList,this.latestOptions)}resetBackoff(){}destroy(){this.resetSubchannelList(),this.removeCurrentPick()}getTypeName(){return E6}}PV.PickFirstLoadBalancer=sq;var gS=new sY(!1);class OV{constructor($,Y,T,q){this.endpoint=$,this.options=T,this.resolutionNote=q,this.latestState=H0.ConnectivityState.IDLE;let X=(0,ZJ.createChildChannelControlHelper)(Y,{updateState:(J,Q,U)=>{this.latestState=J,this.latestPicker=Q,Y.updateState(J,Q,U)}});this.pickFirstBalancer=new sq(X),this.latestPicker=new h$.QueuePicker(this.pickFirstBalancer)}startConnecting(){this.pickFirstBalancer.updateAddressList((0,xS.statusOrFromValue)([this.endpoint]),gS,Object.assign(Object.assign({},this.options),{[RV]:!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()}}PV.LeafLoadBalancer=OV;function mS(){(0,ZJ.registerLoadBalancerType)(E6,sq,sY),(0,ZJ.registerDefaultLoadBalancerType)(E6)}});var yV=M((SV)=>{Object.defineProperty(SV,"__esModule",{value:!0});SV.FileWatcherCertificateProvider=void 0;var cS=s("fs"),pS=U0(),lS=i(),nS=s("util"),iS="certificate_provider";function tq($){pS.trace(lS.LogVerbosity.DEBUG,iS,$)}var KJ=(0,nS.promisify)(cS.readFile);class wV{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");tq("File watcher constructed with config "+JSON.stringify($))}updateCertificates(){if(this.fileResultPromise)return;this.fileResultPromise=Promise.allSettled([this.config.certificateFile?KJ(this.config.certificateFile):Promise.reject(),this.config.privateKeyFile?KJ(this.config.privateKeyFile):Promise.reject(),this.config.caCertificateFile?KJ(this.config.caCertificateFile):Promise.reject()]),this.fileResultPromise.then(([$,Y,T])=>{if(!this.refreshTimer)return;if(tq("File watcher read certificates certificate "+$.status+", privateKey "+Y.status+", CA certificate "+T.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(T.status==="fulfilled")this.latestCaUpdate={caCertificate:T.value};else this.latestCaUpdate=null;for(let q of this.identityListeners)q(this.latestIdentityUpdate);for(let q of this.caListeners)q(this.latestCaUpdate)}),tq("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),tq("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()}}SV.FileWatcherCertificateProvider=wV});var GJ=M((a)=>{Object.defineProperty(a,"__esModule",{value:!0});a.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX=a.createCertificateProviderChannelCredentials=a.FileWatcherCertificateProvider=a.createCertificateProviderServerCredentials=a.createServerCredentialsWithInterceptors=a.BaseSubchannelWrapper=a.registerAdminService=a.FilterStackFactory=a.BaseFilter=a.statusOrFromError=a.statusOrFromValue=a.PickResultType=a.QueuePicker=a.UnavailablePicker=a.ChildLoadBalancerHandler=a.EndpointMap=a.endpointHasAddress=a.endpointToString=a.subchannelAddressToString=a.LeafLoadBalancer=a.isLoadBalancerNameRegistered=a.parseLoadBalancingConfig=a.selectLbConfigFromList=a.registerLoadBalancerType=a.createChildChannelControlHelper=a.BackoffTimeout=a.parseDuration=a.durationToMs=a.splitHostPort=a.uriToString=a.CHANNEL_ARGS_CONFIG_SELECTOR_KEY=a.createResolver=a.registerResolver=a.log=a.trace=void 0;var jV=U0();Object.defineProperty(a,"trace",{enumerable:!0,get:function(){return jV.trace}});Object.defineProperty(a,"log",{enumerable:!0,get:function(){return jV.log}});var AJ=B1();Object.defineProperty(a,"registerResolver",{enumerable:!0,get:function(){return AJ.registerResolver}});Object.defineProperty(a,"createResolver",{enumerable:!0,get:function(){return AJ.createResolver}});Object.defineProperty(a,"CHANNEL_ARGS_CONFIG_SELECTOR_KEY",{enumerable:!0,get:function(){return AJ.CHANNEL_ARGS_CONFIG_SELECTOR_KEY}});var vV=p0();Object.defineProperty(a,"uriToString",{enumerable:!0,get:function(){return vV.uriToString}});Object.defineProperty(a,"splitHostPort",{enumerable:!0,get:function(){return vV.splitHostPort}});var xV=W6();Object.defineProperty(a,"durationToMs",{enumerable:!0,get:function(){return xV.durationToMs}});Object.defineProperty(a,"parseDuration",{enumerable:!0,get:function(){return xV.parseDuration}});var rS=LY();Object.defineProperty(a,"BackoffTimeout",{enumerable:!0,get:function(){return rS.BackoffTimeout}});var D6=M$();Object.defineProperty(a,"createChildChannelControlHelper",{enumerable:!0,get:function(){return D6.createChildChannelControlHelper}});Object.defineProperty(a,"registerLoadBalancerType",{enumerable:!0,get:function(){return D6.registerLoadBalancerType}});Object.defineProperty(a,"selectLbConfigFromList",{enumerable:!0,get:function(){return D6.selectLbConfigFromList}});Object.defineProperty(a,"parseLoadBalancingConfig",{enumerable:!0,get:function(){return D6.parseLoadBalancingConfig}});Object.defineProperty(a,"isLoadBalancerNameRegistered",{enumerable:!0,get:function(){return D6.isLoadBalancerNameRegistered}});var aS=V6();Object.defineProperty(a,"LeafLoadBalancer",{enumerable:!0,get:function(){return aS.LeafLoadBalancer}});var eq=r0();Object.defineProperty(a,"subchannelAddressToString",{enumerable:!0,get:function(){return eq.subchannelAddressToString}});Object.defineProperty(a,"endpointToString",{enumerable:!0,get:function(){return eq.endpointToString}});Object.defineProperty(a,"endpointHasAddress",{enumerable:!0,get:function(){return eq.endpointHasAddress}});Object.defineProperty(a,"EndpointMap",{enumerable:!0,get:function(){return eq.EndpointMap}});var oS=l8();Object.defineProperty(a,"ChildLoadBalancerHandler",{enumerable:!0,get:function(){return oS.ChildLoadBalancerHandler}});var WJ=Y$();Object.defineProperty(a,"UnavailablePicker",{enumerable:!0,get:function(){return WJ.UnavailablePicker}});Object.defineProperty(a,"QueuePicker",{enumerable:!0,get:function(){return WJ.QueuePicker}});Object.defineProperty(a,"PickResultType",{enumerable:!0,get:function(){return WJ.PickResultType}});var kV=l$();Object.defineProperty(a,"statusOrFromValue",{enumerable:!0,get:function(){return kV.statusOrFromValue}});Object.defineProperty(a,"statusOrFromError",{enumerable:!0,get:function(){return kV.statusOrFromError}});var sS=O5();Object.defineProperty(a,"BaseFilter",{enumerable:!0,get:function(){return sS.BaseFilter}});var tS=vq();Object.defineProperty(a,"FilterStackFactory",{enumerable:!0,get:function(){return tS.FilterStackFactory}});var eS=i8();Object.defineProperty(a,"registerAdminService",{enumerable:!0,get:function(){return eS.registerAdminService}});var $C=K6();Object.defineProperty(a,"BaseSubchannelWrapper",{enumerable:!0,get:function(){return $C.BaseSubchannelWrapper}});var hV=lq();Object.defineProperty(a,"createServerCredentialsWithInterceptors",{enumerable:!0,get:function(){return hV.createServerCredentialsWithInterceptors}});Object.defineProperty(a,"createCertificateProviderServerCredentials",{enumerable:!0,get:function(){return hV.createCertificateProviderServerCredentials}});var YC=yV();Object.defineProperty(a,"FileWatcherCertificateProvider",{enumerable:!0,get:function(){return YC.FileWatcherCertificateProvider}});var TC=PY();Object.defineProperty(a,"createCertificateProviderChannelCredentials",{enumerable:!0,get:function(){return TC.createCertificateProviderChannelCredentials}});var qC=l5();Object.defineProperty(a,"SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX",{enumerable:!0,get:function(){return qC.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX}})});var mV=M((gV)=>{Object.defineProperty(gV,"__esModule",{value:!0});gV.setup=UC;var JC=B1(),QC=l$();class _V{constructor($,Y,T){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,QC.statusOrFromValue)(this.endpoints),{},null,"")}destroy(){this.hasReturnedResult=!1}static getDefaultAuthority($){return"localhost"}}function UC(){(0,JC.registerResolver)("unix",_V)}});var lV=M((pV)=>{Object.defineProperty(pV,"__esModule",{value:!0});pV.setup=EC;var fV=s("net"),bV=l$(),$9=i(),EJ=P0(),uV=B1(),KC=r0(),dV=p0(),AC=U0(),WC="ip_resolver";function cV($){AC.trace($9.LogVerbosity.DEBUG,WC,$)}var VJ="ipv4",DJ="ipv6",GC=443;class FJ{constructor($,Y,T){var q;this.listener=Y,this.endpoints=[],this.error=null,this.hasReturnedResult=!1,cV("Resolver constructed for target "+(0,dV.uriToString)($));let X=[];if(!($.scheme===VJ||$.scheme===DJ)){this.error={code:$9.Status.UNAVAILABLE,details:`Unrecognized scheme ${$.scheme} in IP resolver`,metadata:new EJ.Metadata};return}let J=$.path.split(",");for(let Q of J){let U=(0,dV.splitHostPort)(Q);if(U===null){this.error={code:$9.Status.UNAVAILABLE,details:`Failed to parse ${$.scheme} address ${Q}`,metadata:new EJ.Metadata};return}if($.scheme===VJ&&!(0,fV.isIPv4)(U.host)||$.scheme===DJ&&!(0,fV.isIPv6)(U.host)){this.error={code:$9.Status.UNAVAILABLE,details:`Failed to parse ${$.scheme} address ${Q}`,metadata:new EJ.Metadata};return}X.push({host:U.host,port:(q=U.port)!==null&&q!==void 0?q:GC})}this.endpoints=X.map((Q)=>({addresses:[Q]})),cV("Parsed "+$.scheme+" address list "+X.map(KC.subchannelAddressToString))}updateResolution(){if(!this.hasReturnedResult)this.hasReturnedResult=!0,process.nextTick(()=>{if(this.error)this.listener((0,bV.statusOrFromError)(this.error),{},null,"");else this.listener((0,bV.statusOrFromValue)(this.endpoints),{},null,"")})}destroy(){this.hasReturnedResult=!1}static getDefaultAuthority($){return $.path.split(",")[0]}}function EC(){(0,uV.registerResolver)(VJ,FJ),(0,uV.registerResolver)(DJ,FJ)}});var tV=M((oV)=>{Object.defineProperty(oV,"__esModule",{value:!0});oV.RoundRobinLoadBalancer=void 0;oV.setup=IC;var rV=M$(),k0=l0(),F6=Y$(),DC=U0(),FC=i(),nV=r0(),NC=V6(),HC="round_robin";function iV($){DC.trace(FC.LogVerbosity.DEBUG,HC,$)}var Y9="round_robin";class T9{getLoadBalancerName(){return Y9}constructor(){}toJsonObject(){return{[Y9]:{}}}static createFromJson($){return new T9}}class aV{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 zC($,Y){return[...$.slice(Y),...$.slice(0,Y)]}class NJ{constructor($){this.channelControlHelper=$,this.children=[],this.currentState=k0.ConnectivityState.IDLE,this.currentReadyPicker=null,this.updatesPaused=!1,this.lastError=null,this.childChannelControlHelper=(0,rV.createChildChannelControlHelper)($,{updateState:(Y,T,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((T)=>T.getConnectivityState()===k0.ConnectivityState.READY),Y=0;if(this.currentReadyPicker!==null){let T=this.currentReadyPicker.peekNextEndpoint();if(Y=$.findIndex((q)=>(0,nV.endpointEqual)(q.getEndpoint(),T)),Y<0)Y=0}this.updateState(k0.ConnectivityState.READY,new aV($.map((T)=>({endpoint:T.getEndpoint(),picker:T.getPicker()})),Y),null)}else if(this.countChildrenWithState(k0.ConnectivityState.CONNECTING)>0)this.updateState(k0.ConnectivityState.CONNECTING,new F6.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 F6.UnavailablePicker({details:$}),$)}else this.updateState(k0.ConnectivityState.IDLE,new F6.QueuePicker(this),null);for(let $ of this.children)if($.getConnectivityState()===k0.ConnectivityState.IDLE)$.exitIdle()}updateState($,Y,T){if(iV(k0.ConnectivityState[this.currentState]+" -> "+k0.ConnectivityState[$]),$===k0.ConnectivityState.READY)this.currentReadyPicker=Y;else this.currentReadyPicker=null;this.currentState=$,this.channelControlHelper.updateState($,Y,T)}resetSubchannelList(){for(let $ of this.children)$.destroy();this.children=[]}updateAddressList($,Y,T,q){if(!(Y instanceof T9))return!1;if(!$.ok){if(this.children.length===0)this.updateState(k0.ConnectivityState.TRANSIENT_FAILURE,new F6.UnavailablePicker($.error),$.error.details);return!0}let X=Math.random()*$.value.length|0,J=zC($.value,X);if(this.resetSubchannelList(),J.length===0){let Q=`No addresses resolved. Resolution note: ${q}`;this.updateState(k0.ConnectivityState.TRANSIENT_FAILURE,new F6.UnavailablePicker({details:Q}),Q)}iV("Connect to endpoint list "+J.map(nV.endpointToString)),this.updatesPaused=!0,this.children=J.map((Q)=>new NC.LeafLoadBalancer(Q,this.childChannelControlHelper,T,q));for(let Q of this.children)Q.startConnecting();return this.updatesPaused=!1,this.calculateAndUpdateState(),!0}exitIdle(){}resetBackoff(){}destroy(){this.resetSubchannelList()}getTypeName(){return Y9}}oV.RoundRobinLoadBalancer=NJ;function IC(){(0,rV.registerLoadBalancerType)(Y9,NJ,T9)}});var Q3=M((X3)=>{var HJ;Object.defineProperty(X3,"__esModule",{value:!0});X3.OutlierDetectionLoadBalancer=X3.OutlierDetectionLoadBalancingConfig=void 0;X3.setup=vC;var BC=l0(),eV=i(),XY=W6(),$3=GJ(),RC=M$(),OC=l8(),PC=Y$(),zJ=r0(),LC=K6(),wC=U0(),SC="outlier_detection";function C0($){wC.trace(eV.LogVerbosity.DEBUG,SC,$)}var BJ="outlier_detection",CC=((HJ=process.env.GRPC_EXPERIMENTAL_ENABLE_OUTLIER_DETECTION)!==null&&HJ!==void 0?HJ:"true")==="true",yC={stdev_factor:1900,enforcement_percentage:100,minimum_hosts:5,request_volume:100},jC={threshold:85,enforcement_percentage:100,minimum_hosts:5,request_volume:50};function tY($,Y,T,q){if(Y in $&&$[Y]!==void 0&&typeof $[Y]!==T){let X=q?`${q}.${Y}`:Y;throw Error(`outlier detection config ${X} parse error: expected ${T}, got ${typeof $[Y]}`)}}function IJ($,Y,T){let q=T?`${T}.${Y}`:Y;if(Y in $&&$[Y]!==void 0){if(!(0,XY.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 q9($,Y,T){let q=T?`${T}.${Y}`:Y;if(tY($,Y,"number",T),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 N6{constructor($,Y,T,q,X,J,Q){if(this.childPolicy=Q,Q.getLoadBalancerName()==="pick_first")throw Error("outlier_detection LB policy cannot have a pick_first child policy");this.intervalMs=$!==null&&$!==void 0?$:1e4,this.baseEjectionTimeMs=Y!==null&&Y!==void 0?Y:30000,this.maxEjectionTimeMs=T!==null&&T!==void 0?T:300000,this.maxEjectionPercent=q!==null&&q!==void 0?q:10,this.successRateEjection=X?Object.assign(Object.assign({},yC),X):null,this.failurePercentageEjection=J?Object.assign(Object.assign({},jC),J):null}getLoadBalancerName(){return BJ}toJsonObject(){var $,Y;return{outlier_detection:{interval:(0,XY.msToDuration)(this.intervalMs),base_ejection_time:(0,XY.msToDuration)(this.baseEjectionTimeMs),max_ejection_time:(0,XY.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(IJ($,"interval"),IJ($,"base_ejection_time"),IJ($,"max_ejection_time"),q9($,"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");tY($.success_rate_ejection,"stdev_factor","number","success_rate_ejection"),q9($.success_rate_ejection,"enforcement_percentage","success_rate_ejection"),tY($.success_rate_ejection,"minimum_hosts","number","success_rate_ejection"),tY($.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");q9($.failure_percentage_ejection,"threshold","failure_percentage_ejection"),q9($.failure_percentage_ejection,"enforcement_percentage","failure_percentage_ejection"),tY($.failure_percentage_ejection,"minimum_hosts","number","failure_percentage_ejection"),tY($.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 T=(0,RC.selectLbConfigFromList)($.child_policy);if(!T)throw Error("outlier detection config child_policy: no valid recognized policy found");return new N6($.interval?(0,XY.durationToMs)($.interval):null,$.base_ejection_time?(0,XY.durationToMs)($.base_ejection_time):null,$.max_ejection_time?(0,XY.durationToMs)($.max_ejection_time):null,(Y=$.max_ejection_percent)!==null&&Y!==void 0?Y:null,$.success_rate_ejection,$.failure_percentage_ejection,T)}}X3.OutlierDetectionLoadBalancingConfig=N6;class Y3 extends LC.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 MJ(){return{success:0,failure:0}}class T3{constructor(){this.activeBucket=MJ(),this.inactiveBucket=MJ()}addSuccess(){this.activeBucket.success+=1}addFailure(){this.activeBucket.failure+=1}switchBuckets(){this.inactiveBucket=this.activeBucket,this.activeBucket=MJ()}getLastSuccesses(){return this.inactiveBucket.success}getLastFailures(){return this.inactiveBucket.failure}}class q3{constructor($,Y){this.wrappedPicker=$,this.countCalls=Y}pick($){let Y=this.wrappedPicker.pick($);if(Y.pickResultType===PC.PickResultType.COMPLETE){let T=Y.subchannel,q=T.getMapEntry();if(q){let X=Y.onCallEnded;if(this.countCalls)X=(J,Q,U)=>{var Z;if(J===eV.Status.OK)q.counter.addSuccess();else q.counter.addFailure();(Z=Y.onCallEnded)===null||Z===void 0||Z.call(Y,J,Q,U)};return Object.assign(Object.assign({},Y),{subchannel:T.getWrappedSubchannel(),onCallEnded:X})}else return Object.assign(Object.assign({},Y),{subchannel:T.getWrappedSubchannel()})}else return Y}}class RJ{constructor($){this.entryMap=new zJ.EndpointMap,this.latestConfig=null,this.timerStartTime=null,this.childBalancer=new OC.ChildLoadBalancerHandler((0,$3.createChildChannelControlHelper)($,{createSubchannel:(Y,T)=>{let q=$.createSubchannel(Y,T),X=this.entryMap.getForSubchannelAddress(Y),J=new Y3(q,X);if((X===null||X===void 0?void 0:X.currentEjectionTimestamp)!==null)J.eject();return X===null||X===void 0||X.subchannelWrappers.push(J),J},updateState:(Y,T,q)=>{if(Y===BC.ConnectivityState.READY)$.updateState(Y,new q3(T,this.isCountingEnabled()),q);else $.updateState(Y,T,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 T=Y.request_volume,q=0,X=[];for(let[A,W]of this.entryMap.entries()){let E=W.counter.getLastSuccesses(),D=W.counter.getLastFailures();if(C0("Stats for "+(0,zJ.endpointToString)(A)+": successes="+E+" failures="+D+" targetRequestVolume="+T),E+D>=T)q+=1,X.push(E/(E+D))}if(C0("Found "+q+" success rate candidates; currentEjectionPercent="+this.getCurrentEjectionPercent()+" successRates=["+X+"]"),q<Y.minimum_hosts)return;let J=X.reduce((A,W)=>A+W)/X.length,Q=0;for(let A of X){let W=A-J;Q+=W*W}let U=Q/X.length,Z=Math.sqrt(U),K=J-Z*(Y.stdev_factor/1000);C0("stdev="+Z+" ejectionThreshold="+K);for(let[A,W]of this.entryMap.entries()){if(this.getCurrentEjectionPercent()>=this.latestConfig.getMaxEjectionPercent())break;let E=W.counter.getLastSuccesses(),D=W.counter.getLastFailures();if(E+D<T)continue;let F=E/(E+D);if(C0("Checking candidate "+A+" successRate="+F),F<K){let H=Math.random()*100;if(C0("Candidate "+A+" randomNumber="+H+" enforcement_percentage="+Y.enforcement_percentage),H<Y.enforcement_percentage)C0("Ejecting candidate "+A),this.eject(W,$)}}}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 T=0;for(let q of this.entryMap.values()){let X=q.counter.getLastSuccesses(),J=q.counter.getLastFailures();if(X+J>=Y.request_volume)T+=1}if(T<Y.minimum_hosts)return;for(let[q,X]of this.entryMap.entries()){if(this.getCurrentEjectionPercent()>=this.latestConfig.getMaxEjectionPercent())break;let J=X.counter.getLastSuccesses(),Q=X.counter.getLastFailures();if(C0("Candidate successes="+J+" failures="+Q),J+Q<Y.request_volume)continue;if(Q*100/(Q+J)>Y.threshold){let Z=Math.random()*100;if(C0("Candidate "+q+" randomNumber="+Z+" enforcement_percentage="+Y.enforcement_percentage),Z<Y.enforcement_percentage)C0("Ejecting candidate "+q),this.eject(X,$)}}}eject($,Y){$.currentEjectionTimestamp=new Date,$.ejectionTimeMultiplier+=1;for(let T of $.subchannelWrappers)T.eject()}uneject($){$.currentEjectionTimestamp=null;for(let Y of $.subchannelWrappers)Y.uneject()}switchAllBuckets(){for(let $ of this.entryMap.values())$.counter.switchBuckets()}startTimer($){var Y,T;this.ejectionTimer=setTimeout(()=>this.runChecks(),$),(T=(Y=this.ejectionTimer).unref)===null||T===void 0||T.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,T]of this.entryMap.entries())if(T.currentEjectionTimestamp===null){if(T.ejectionTimeMultiplier>0)T.ejectionTimeMultiplier-=1}else{let q=this.latestConfig.getBaseEjectionTimeMs(),X=this.latestConfig.getMaxEjectionTimeMs(),J=new Date(T.currentEjectionTimestamp.getTime());if(J.setMilliseconds(J.getMilliseconds()+Math.min(q*T.ejectionTimeMultiplier,Math.max(q,X))),J<new Date)C0("Unejecting "+Y),this.uneject(T)}}updateAddressList($,Y,T,q){if(!(Y instanceof N6))return!1;if(C0("Received update with config: "+JSON.stringify(Y.toJsonObject(),void 0,2)),$.ok){for(let J of $.value)if(!this.entryMap.has(J))C0("Adding map entry for "+(0,zJ.endpointToString)(J)),this.entryMap.set(J,{counter:new T3,currentEjectionTimestamp:null,ejectionTimeMultiplier:0,subchannelWrappers:[]});this.entryMap.deleteMissing($.value)}let X=Y.getChildPolicy();if(this.childBalancer.updateAddressList($,X,T,q),Y.getSuccessRateEjectionConfig()||Y.getFailurePercentageEjectionConfig())if(this.timerStartTime){C0("Previous timer existed. Replacing timer"),clearTimeout(this.ejectionTimer);let J=Y.getIntervalMs()-(new Date().getTime()-this.timerStartTime.getTime());this.startTimer(J)}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 J of this.entryMap.values())this.uneject(J),J.ejectionTimeMultiplier=0}return this.latestConfig=Y,!0}exitIdle(){this.childBalancer.exitIdle()}resetBackoff(){this.childBalancer.resetBackoff()}destroy(){clearTimeout(this.ejectionTimer),this.childBalancer.destroy()}getTypeName(){return BJ}}X3.OutlierDetectionLoadBalancer=RJ;function vC(){if(CC)(0,$3.registerLoadBalancerType)(BJ,RJ,N6)}});var A3=M((Z3)=>{Object.defineProperty(Z3,"__esModule",{value:!0});Z3.PriorityQueue=void 0;var eY=0,OJ=($)=>Math.floor($/2),X9=($)=>$*2+1,H6=($)=>$*2+2;class U3{constructor($=(Y,T)=>Y>T){this.comparator=$,this.heap=[]}size(){return this.heap.length}isEmpty(){return this.size()==0}peek(){return this.heap[eY]}push(...$){return $.forEach((Y)=>{this.heap.push(Y),this.siftUp()}),this.size()}pop(){let $=this.peek(),Y=this.size()-1;if(Y>eY)this.swap(eY,Y);return this.heap.pop(),this.siftDown(),$}replace($){let Y=this.peek();return this.heap[eY]=$,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($>eY&&this.greater($,OJ($)))this.swap($,OJ($)),$=OJ($)}siftDown(){let $=eY;while(X9($)<this.size()&&this.greater(X9($),$)||H6($)<this.size()&&this.greater(H6($),$)){let Y=H6($)<this.size()&&this.greater(H6($),X9($))?H6($):X9($);this.swap($,Y),$=Y}}}Z3.PriorityQueue=U3});var z3=M((N3)=>{Object.defineProperty(N3,"__esModule",{value:!0});N3.WeightedRoundRobinLoadBalancingConfig=void 0;N3.setup=lC;var y0=l0(),hC=i(),J1=W6(),E3=M$(),_C=V6(),gC=U0(),V3=iq(),$T=Y$(),mC=A3(),W3=r0(),fC="weighted_round_robin";function PJ($){gC.trace(hC.LogVerbosity.DEBUG,fC,$)}var LJ="weighted_round_robin",bC=1e4,uC=1e4,dC=180000,cC=1000,pC=1;function G3($,Y,T){if(Y in $&&$[Y]!==void 0&&typeof $[Y]!==T)throw Error(`weighted round robin config ${Y} parse error: expected ${T}, got ${typeof $[Y]}`)}function J9($,Y){if(Y in $&&$[Y]!==void 0&&$[Y]!==null){let T;if((0,J1.isDuration)($[Y]))T=$[Y];else if((0,J1.isDurationMessage)($[Y]))T=(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]}`);T=q}else throw Error(`weighted round robin config ${Y}: expected duration, got ${typeof $[Y]}`);return(0,J1.durationToMs)(T)}return null}class z6{constructor($,Y,T,q,X,J){this.enableOobLoadReport=$!==null&&$!==void 0?$:!1,this.oobLoadReportingPeriodMs=Y!==null&&Y!==void 0?Y:bC,this.blackoutPeriodMs=T!==null&&T!==void 0?T:uC,this.weightExpirationPeriodMs=q!==null&&q!==void 0?q:dC,this.weightUpdatePeriodMs=Math.max(X!==null&&X!==void 0?X:cC,100),this.errorUtilizationPenalty=J!==null&&J!==void 0?J:pC}getLoadBalancerName(){return LJ}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(G3($,"enable_oob_load_report","boolean"),G3($,"error_utilization_penalty","number"),$.error_utilization_penalty<0)throw Error("weighted round robin config error_utilization_penalty < 0");return new z6($.enable_oob_load_report,J9($,"oob_load_reporting_period"),J9($,"blackout_period"),J9($,"weight_expiration_period"),J9($,"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}}N3.WeightedRoundRobinLoadBalancingConfig=z6;class D3{constructor($,Y){this.metricsHandler=Y,this.queue=new mC.PriorityQueue((X,J)=>X.deadline<J.deadline);let T=$.filter((X)=>X.weight>0),q;if(T.length<2)q=1;else{let X=0;for(let{weight:J}of T)X+=J;q=X/T.length}for(let X of $){let J=X.weight>0?1/X.weight:q;this.queue.push({endpointName:X.endpointName,picker:X.picker,period:J,deadline:Math.random()*J})}}pick($){let Y=this.queue.pop();this.queue.push(Object.assign(Object.assign({},Y),{deadline:Y.deadline+Y.period}));let T=Y.picker.pick($);if(T.pickResultType===$T.PickResultType.COMPLETE)if(this.metricsHandler)return Object.assign(Object.assign({},T),{onCallEnded:(0,V3.createMetricsReader)((q)=>this.metricsHandler(q,Y.endpointName),T.onCallEnded)});else{let q=T.subchannel;return Object.assign(Object.assign({},T),{subchannel:q.getWrappedSubchannel()})}else return T}}class F3{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 T of this.children.values())if(T.child.getConnectivityState()===$)Y+=1;return Y}updateWeight($,Y){var T,q;let{rps_fractional:X,application_utilization:J}=Y;if(J>0&&X>0)J+=Y.eps/X*((q=(T=this.latestConfig)===null||T===void 0?void 0:T.getErrorUtilizationPenalty())!==null&&q!==void 0?q:0);let Q=J===0?0:X/J;if(Q===0)return;let U=new Date;if($.nonEmptySince===null)$.nonEmptySince=U;$.lastUpdated=U,$.weight=Q}getWeight($){if(!this.latestConfig)return 0;let Y=new Date().getTime();if(Y-$.lastUpdated.getTime()>=this.latestConfig.getWeightExpirationPeriodMs())return $.nonEmptySince=null,0;let T=this.latestConfig.getBlackoutPeriodMs();if(T>0&&($.nonEmptySince===null||Y-$.nonEmptySince.getTime()<T))return 0;return $.weight}calculateAndUpdateState(){if(this.updatesPaused||!this.latestConfig)return;if(this.countChildrenWithState(y0.ConnectivityState.READY)>0){let $=[];for(let[T,q]of this.children){if(q.child.getConnectivityState()!==y0.ConnectivityState.READY)continue;$.push({endpointName:T,picker:q.child.getPicker(),weight:this.getWeight(q)})}PJ("Created picker with weights: "+$.map((T)=>T.endpointName+":"+T.weight).join(","));let Y;if(!this.latestConfig.getEnableOobLoadReport())Y=(T,q)=>{let X=this.children.get(q);if(X)this.updateWeight(X,T)};else Y=null;this.updateState(y0.ConnectivityState.READY,new D3($,Y),null)}else if(this.countChildrenWithState(y0.ConnectivityState.CONNECTING)>0)this.updateState(y0.ConnectivityState.CONNECTING,new $T.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 $T.UnavailablePicker({details:$}),$)}else this.updateState(y0.ConnectivityState.IDLE,new $T.QueuePicker(this),null);for(let{child:$}of this.children.values())if($.getConnectivityState()===y0.ConnectivityState.IDLE)$.exitIdle()}updateState($,Y,T){PJ(y0.ConnectivityState[this.currentState]+" -> "+y0.ConnectivityState[$]),this.currentState=$,this.channelControlHelper.updateState($,Y,T)}updateAddressList($,Y,T,q){var X,J;if(!(Y instanceof z6))return!1;if(!$.ok){if(this.children.size===0)this.updateState(y0.ConnectivityState.TRANSIENT_FAILURE,new $T.UnavailablePicker($.error),$.error.details);return!0}if($.value.length===0){let Z=`No addresses resolved. Resolution note: ${q}`;return this.updateState(y0.ConnectivityState.TRANSIENT_FAILURE,new $T.UnavailablePicker({details:Z}),Z),!1}PJ("Connect to endpoint list "+$.value.map(W3.endpointToString));let Q=new Date,U=new Set;this.updatesPaused=!0,this.latestConfig=Y;for(let Z of $.value){let K=(0,W3.endpointToString)(Z);U.add(K);let A=this.children.get(K);if(!A)A={child:new _C.LeafLoadBalancer(Z,(0,E3.createChildChannelControlHelper)(this.channelControlHelper,{updateState:(W,E,D)=>{if(this.currentState===y0.ConnectivityState.READY&&W!==y0.ConnectivityState.READY)this.channelControlHelper.requestReresolution();if(W===y0.ConnectivityState.READY)A.nonEmptySince=null;if(D)this.lastError=D;this.calculateAndUpdateState()},createSubchannel:(W,E)=>{let D=this.channelControlHelper.createSubchannel(W,E);if(A===null||A===void 0?void 0:A.oobMetricsListener)return new V3.OrcaOobMetricsSubchannelWrapper(D,A.oobMetricsListener,this.latestConfig.getOobLoadReportingPeriodMs());else return D}}),T,q),lastUpdated:Q,nonEmptySince:null,weight:0,oobMetricsListener:null},this.children.set(K,A);if(Y.getEnableOobLoadReport())A.oobMetricsListener=(W)=>{this.updateWeight(A,W)};else A.oobMetricsListener=null}for(let[Z,K]of this.children)if(U.has(Z))K.child.startConnecting();else K.child.destroy(),this.children.delete(Z);if(this.updatesPaused=!1,this.calculateAndUpdateState(),this.weightUpdateTimer)clearInterval(this.weightUpdateTimer);return this.weightUpdateTimer=(J=(X=setInterval(()=>{if(this.currentState===y0.ConnectivityState.READY)this.calculateAndUpdateState()},Y.getWeightUpdatePeriodMs())).unref)===null||J===void 0?void 0:J.call(X),!0}exitIdle(){}resetBackoff(){}destroy(){for(let $ of this.children.values())$.child.destroy();if(this.children.clear(),this.weightUpdateTimer)clearInterval(this.weightUpdateTimer)}getTypeName(){return LJ}}function lC(){(0,E3.registerLoadBalancerType)(LJ,F3,z6)}});var I6=M((T0)=>{Object.defineProperty(T0,"__esModule",{value:!0});T0.experimental=T0.ServerMetricRecorder=T0.ServerInterceptingCall=T0.ResponderBuilder=T0.ServerListenerBuilder=T0.addAdminServicesToServer=T0.getChannelzHandlers=T0.getChannelzServiceDefinition=T0.InterceptorConfigurationError=T0.InterceptingCall=T0.RequesterBuilder=T0.ListenerBuilder=T0.StatusBuilder=T0.getClientChannel=T0.ServerCredentials=T0.Server=T0.setLogVerbosity=T0.setLogger=T0.load=T0.loadObject=T0.CallCredentials=T0.ChannelCredentials=T0.waitForClientReady=T0.closeClient=T0.Channel=T0.makeGenericClientConstructor=T0.makeClientConstructor=T0.loadPackageDefinition=T0.Client=T0.compressionAlgorithms=T0.propagate=T0.connectivityState=T0.status=T0.logVerbosity=T0.Metadata=T0.credentials=void 0;var Q9=g8();Object.defineProperty(T0,"CallCredentials",{enumerable:!0,get:function(){return Q9.CallCredentials}});var iC=AX();Object.defineProperty(T0,"Channel",{enumerable:!0,get:function(){return iC.ChannelImplementation}});var rC=R5();Object.defineProperty(T0,"compressionAlgorithms",{enumerable:!0,get:function(){return rC.CompressionAlgorithms}});var aC=l0();Object.defineProperty(T0,"connectivityState",{enumerable:!0,get:function(){return aC.ConnectivityState}});var U9=PY();Object.defineProperty(T0,"ChannelCredentials",{enumerable:!0,get:function(){return U9.ChannelCredentials}});var I3=KX();Object.defineProperty(T0,"Client",{enumerable:!0,get:function(){return I3.Client}});var wJ=i();Object.defineProperty(T0,"logVerbosity",{enumerable:!0,get:function(){return wJ.LogVerbosity}});Object.defineProperty(T0,"status",{enumerable:!0,get:function(){return wJ.Status}});Object.defineProperty(T0,"propagate",{enumerable:!0,get:function(){return wJ.Propagate}});var M3=U0(),SJ=a8();Object.defineProperty(T0,"loadPackageDefinition",{enumerable:!0,get:function(){return SJ.loadPackageDefinition}});Object.defineProperty(T0,"makeClientConstructor",{enumerable:!0,get:function(){return SJ.makeClientConstructor}});Object.defineProperty(T0,"makeGenericClientConstructor",{enumerable:!0,get:function(){return SJ.makeClientConstructor}});var oC=P0();Object.defineProperty(T0,"Metadata",{enumerable:!0,get:function(){return oC.Metadata}});var sC=EV();Object.defineProperty(T0,"Server",{enumerable:!0,get:function(){return sC.Server}});var tC=lq();Object.defineProperty(T0,"ServerCredentials",{enumerable:!0,get:function(){return tC.ServerCredentials}});var eC=NV();Object.defineProperty(T0,"StatusBuilder",{enumerable:!0,get:function(){return eC.StatusBuilder}});T0.credentials={combineChannelCredentials:($,...Y)=>{return Y.reduce((T,q)=>T.compose(q),$)},combineCallCredentials:($,...Y)=>{return Y.reduce((T,q)=>T.compose(q),$)},createInsecure:U9.ChannelCredentials.createInsecure,createSsl:U9.ChannelCredentials.createSsl,createFromSecureContext:U9.ChannelCredentials.createFromSecureContext,createFromMetadataGenerator:Q9.CallCredentials.createFromMetadataGenerator,createFromGoogleCredential:Q9.CallCredentials.createFromGoogleCredential,createEmpty:Q9.CallCredentials.createEmpty};var $y=($)=>$.close();T0.closeClient=$y;var Yy=($,Y,T)=>$.waitForReady(Y,T);T0.waitForClientReady=Yy;var Ty=($,Y)=>{throw Error("Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead")};T0.loadObject=Ty;var qy=($,Y,T)=>{throw Error("Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead")};T0.load=qy;var Xy=($)=>{M3.setLogger($)};T0.setLogger=Xy;var Jy=($)=>{M3.setLoggerVerbosity($)};T0.setLogVerbosity=Jy;var Qy=($)=>{return I3.Client.prototype.getChannel.call($)};T0.getClientChannel=Qy;var Z9=UX();Object.defineProperty(T0,"ListenerBuilder",{enumerable:!0,get:function(){return Z9.ListenerBuilder}});Object.defineProperty(T0,"RequesterBuilder",{enumerable:!0,get:function(){return Z9.RequesterBuilder}});Object.defineProperty(T0,"InterceptingCall",{enumerable:!0,get:function(){return Z9.InterceptingCall}});Object.defineProperty(T0,"InterceptorConfigurationError",{enumerable:!0,get:function(){return Z9.InterceptorConfigurationError}});var B3=y$();Object.defineProperty(T0,"getChannelzServiceDefinition",{enumerable:!0,get:function(){return B3.getChannelzServiceDefinition}});Object.defineProperty(T0,"getChannelzHandlers",{enumerable:!0,get:function(){return B3.getChannelzHandlers}});var Uy=i8();Object.defineProperty(T0,"addAdminServicesToServer",{enumerable:!0,get:function(){return Uy.addAdminServicesToServer}});var CJ=XJ();Object.defineProperty(T0,"ServerListenerBuilder",{enumerable:!0,get:function(){return CJ.ServerListenerBuilder}});Object.defineProperty(T0,"ResponderBuilder",{enumerable:!0,get:function(){return CJ.ResponderBuilder}});Object.defineProperty(T0,"ServerInterceptingCall",{enumerable:!0,get:function(){return CJ.ServerInterceptingCall}});var Zy=iq();Object.defineProperty(T0,"ServerMetricRecorder",{enumerable:!0,get:function(){return Zy.ServerMetricRecorder}});var Ky=GJ();T0.experimental=Ky;var Ay=k5(),Wy=mV(),Gy=lV(),Ey=V6(),Vy=tV(),Dy=Q3(),Fy=z3(),Ny=y$();(()=>{Ay.setup(),Wy.setup(),Gy.setup(),Ey.setup(),Vy.setup(),Dy.setup(),Fy.setup(),Ny.setup()})()});import{existsSync as uJ,mkdirSync as dJ}from"node:fs";import{dirname as cJ,join as J0}from"node:path";var w6="agents",UT="hooks",H1="skills",ZT="rules",KT="workflows",N9="plugins",pJ="cline_mcp_settings.json",W$=process?.env?.HOME||"~",lJ=!1;function nJ($){let Y=$.trim();if(!Y)return;W$=Y,lJ=!0}function S6($){if(lJ)return;let Y=$.trim();if(!Y)return;W$=Y}function AT(){return J0(W$,"Documents","Cline")}function C6(){return J0(AT(),"Agents")}function WT(){return J0(AT(),"Hooks")}function GT(){return J0(AT(),"Rules")}function ET(){return J0(AT(),"Workflows")}function t0(){let $=process.env.CLINE_DATA_DIR?.trim();if($)return $;return J0(W$,".cline","data")}function G$(){let $=process.env.CLINE_SESSION_DATA_DIR?.trim();if($)return $;return J0(t0(),"sessions")}function y6(){let $=process.env.CLINE_TEAM_DATA_DIR?.trim();if($)return $;return J0(t0(),"teams")}function H9(){let $=process.env.CLINE_PROVIDER_SETTINGS_PATH?.trim();if($)return $;return J0(t0(),"settings","providers.json")}function z9(){let $=process.env.CLINE_MCP_SETTINGS_PATH?.trim();if($)return $;return J0(t0(),"settings",pJ)}function VT($){let Y=new Set,T=[];for(let q of $){if(!q||Y.has(q))continue;Y.add(q),T.push(q)}return T}function WD($){if(!$)return[];return[J0($,".clinerules",H1),J0($,".cline",H1),J0($,".claude",H1),J0($,".agents",H1)]}function I9(){return J0(t0(),"settings",w6)}function M9(){return[C6(),I9()]}function B9($){return VT([$?J0($,".clinerules",UT):"",WT()])}function DT($){return VT([...WD($),J0(t0(),"settings",H1),J0(W$,".cline",H1),J0(W$,".agents",H1)])}function R9($){return VT([$?J0($,".clinerules"):"",J0(t0(),"settings",ZT),GT()])}function O9($){return VT([$?J0($,".clinerules","workflows"):"",J0(t0(),"settings",KT),ET()])}function P9($){return VT([$?J0($,".clinerules",N9):"",J0(W$,".cline",N9),J0(W$,".agents",N9)])}function FT($){let Y=cJ($);if(!uJ(Y))dJ(Y,{recursive:!0})}function iJ($){if($?.trim())return FT($),cJ($);let Y=J0(t0(),"hooks");if(!uJ(Y))dJ(Y,{recursive:!0});return Y}import XF from"yaml";import{z as A1}from"zod";import{z as E$}from"zod";var rJ=E$.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"]),GD=E$.object({adapter:E$.string(),botUserName:E$.string().optional(),event:rJ,payload:E$.record(E$.string(),E$.unknown()),ts:E$.string()});var aJ=[{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 ED($){return Object.fromEntries(aJ.flatMap((Y)=>{let T=$==="modelsDevKey"?Y.modelsDevKey:Y.generatedProviderId;return T?[[Y.modelsDevKey,T]]:[]}))}var VD=ED("generatedProviderId");import{z as v0}from"zod";var DD=v0.object({agentId:v0.string(),conversationId:v0.string(),iteration:v0.number(),abortSignal:v0.custom().optional(),metadata:v0.record(v0.string(),v0.unknown()).optional()}),FD=v0.object({id:v0.string(),name:v0.string(),input:v0.unknown(),output:v0.unknown(),error:v0.string().optional(),durationMs:v0.number(),startedAt:v0.date(),endedAt:v0.date()});import{z as oJ}from"zod";function z1($,Y){let T=$.safeParse(Y);if(!T.success)throw Error(oJ.prettifyError(T.error));return T.data}function I1($){return oJ.toJSONSchema($)}function j6($,Y="act"){return`<user_input mode="${Y}">${$}</user_input>`}function v6($){if(!$?.trim())return"";return sJ($,"user_input")}function sJ($,Y){if(!$?.trim())return"";if(!Y)return $;let T=new RegExp(`<${Y}.*?>(.*?)</${Y}>`,"g");return $.replace(T,"$1")}var x6="runtime.team.progress.v1",k6="runtime.team.lifecycle.v1";function tJ($){let Y=$?.trim();return Y?Y:void 0}function h6($){return tJ($?.rootSessionId)}function eJ($){return tJ($?.hookLogPath)}var L9=["running","completed","failed","cancelled"];var v1={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"},_$=[v1.READ_FILES,v1.SEARCH_CODEBASE,v1.RUN_COMMANDS,v1.FETCH_WEB_CONTENT,v1.APPLY_PATCH,v1.EDITOR,v1.SKILLS,v1.ASK];import{createTool as V$}from"@clinebot/agents";import{z as r}from"zod";var ND=r.string().describe("The absolute file path of a text file to read content from"),_6=r.object({file_paths:r.array(ND).describe("Array of absolute file paths to get full content from. Prefer this tool over running terminal command to get file content for better performance and reliability.")}),$Q=r.union([_6,r.array(r.string()),r.string()]),g6=r.object({queries:r.array(r.string()).describe("Array of regex search queries to execute")}),w9=r.string(),m6=r.object({commands:r.array(w9).describe("Array of shell commands to execute.")}),YQ=r.union([m6,r.array(w9),w9]),TQ=r.object({url:r.string().describe("The URL to fetch"),prompt:r.string().min(2).describe("Analysis prompt for the fetched content")}),f6=r.object({requests:r.array(TQ).describe("Array of the URLs for the web fetch requests")}),b6=r.object({command:r.enum(["create","str_replace","insert"]).describe("Editor command to execute: create, str_replace, insert"),path:r.string().min(1).describe("Absolute file path"),file_text:r.string().nullish().describe("Full file content required for 'create' command"),old_str:r.string().nullish().describe("Exact text to replace (must match exactly once) for 'str_replace' command"),new_str:r.string().nullish().describe("Replacement text for 'str_replace' or 'insert' commands"),insert_line:r.number().int().nullish().describe("Optional one-based line index for 'insert' command")}).refine(($)=>$.command!=="create"||$.file_text!=null,{path:["file_text"],message:"file_text is required for command=create"}).refine(($)=>$.command!=="str_replace"||$.old_str!=null,{path:["old_str"],message:"old_str is required for command=str_replace"}).refine(($)=>$.command!=="insert"||$.insert_line!=null,{path:["insert_line"],message:"insert_line is required for command=insert"}).refine(($)=>$.command!=="insert"||$.new_str!=null,{path:["new_str"],message:"new_str is required for command=insert"}),u6=r.object({input:r.string().min(1).describe("The apply_patch text payload, including patch instructions")}),qQ=r.union([u6,r.string()]),d6=r.object({skill:r.string().min(1).describe('The skill name. E.g., "commit", "review-pr", "pdf", or "ms-office-suite:pdf"'),args:r.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),c6=r.object({question:r.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:r.array(r.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")});function KY($){if($ instanceof Error)return $.message;return String($)}function D$($,Y,T){return Promise.race([$,new Promise((q,X)=>{setTimeout(()=>X(Error(T)),Y)})])}var HD=`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":
2
22
 
3
23
  %%bash
4
24
  apply_patch <<"EOF"
@@ -53,47 +73,364 @@ apply_patch <<"EOF"
53
73
  + raise NotImplementedError()
54
74
 
55
75
  *** End Patch
56
- EOF`;function Ut(n,t={}){let e=t.fileReadTimeoutMs??1e4;return Y({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:$(sn),timeoutMs:e*2,retryable:!0,maxRetries:1,execute:async(s,r)=>{let i=X(vt,s),o=Array.isArray(i)?i:typeof i==="object"?i.file_paths:[i];return Promise.all(o.map(async(a)=>{try{let m=await j(n(a,r),e,`File read timed out after ${e}ms`);return{query:a,result:m,success:!0}}catch(m){let u=Q(m);return{query:a,result:"",error:`Error reading file: ${u}`,success:!1}}}))}})}function Mt(n,t={}){let e=t.searchTimeoutMs??30000,s=t.cwd??process.cwd();return Y({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:$(on),timeoutMs:e*2,retryable:!0,maxRetries:1,execute:async(r,i)=>{let o=X(on,r);return Promise.all(o.queries.map(async(a)=>{try{let m=await j(n(a,s,i),e,`Search timed out after ${e}ms`),u=m.length>0&&!m.includes("No results found");return{query:a,result:m,success:u}}catch(m){let u=Q(m);return{query:a,result:"",error:`Search failed: ${u}`,success:!1}}}))}})}function Nt(n,t={}){let e=t.bashTimeoutMs??30000,s=t.cwd??process.cwd();return Y({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:$(an),timeoutMs:e*2,retryable:!1,maxRetries:0,execute:async(r,i)=>{let o=X(Ot,r),a=Array.isArray(o)?o:typeof o==="object"?o.commands:[o];return Promise.all(a.map(async(m)=>{try{let u=await j(n(m,s,i),e,`Command timed out after ${e}ms`);return{query:m,result:u,success:!0}}catch(u){let g=Q(u);return{query:m,result:"",error:`Command failed: ${g}`,success:!1}}}))}})}function Dt(n,t={}){let e=t.webFetchTimeoutMs??30000;return Y({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:$(mn),timeoutMs:e*2,retryable:!0,maxRetries:2,execute:async(s,r)=>{let i=X(mn,s);return Promise.all(i.requests.map(async(o)=>{try{let a=await j(n(o.url,o.prompt,r),e,`Web fetch timed out after ${e}ms`);return{query:o.url,result:a,success:!0}}catch(a){let m=Q(a);return{query:o.url,result:"",error:`Error fetching web content: ${m}`,success:!1}}}))}})}function Lt(n,t={}){let e=t.applyPatchTimeoutMs??30000,s=t.cwd??process.cwd();return Y({name:"apply_patch",description:pe,inputSchema:$(cn),timeoutMs:e,retryable:!1,maxRetries:0,execute:async(r,i)=>{let o=X(It,r),a=typeof o==="string"?o:o.input;try{return{query:"apply_patch",result:await j(n({input:a},s,i),e,`apply_patch timed out after ${e}ms`),success:!0}}catch(m){return{query:"apply_patch",result:"",error:`apply_patch failed: ${Q(m)}`,success:!1}}}})}function St(n,t={}){let e=t.editorTimeoutMs??30000,s=t.cwd??process.cwd();return Y({name:"editor",description:"Edit file using absolute path with create, string replacement, and line insert operations. Supported commands: create, str_replace, insert.",inputSchema:$(un),timeoutMs:e,retryable:!1,maxRetries:0,execute:async(r,i)=>{let o=X(un,r);try{let a=await j(n(o,s,i),e,`Editor operation timed out after ${e}ms`);return{query:`${o.command}:${o.path}`,result:a,success:!0}}catch(a){let m=Q(a);return{query:`${o.command}:${o.path}`,result:"",error:`Editor operation failed: ${m}`,success:!1}}}})}function kt(n,t={}){let e=t.skillsTimeoutMs??15000;return Y({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:$(dn),timeoutMs:e,retryable:!1,maxRetries:0,execute:async(s,r)=>{let i=X(dn,s);return j(n(i.skill,i.args||void 0,r),e,`Skills operation timed out after ${e}ms`)}})}function Pt(n,t={}){let e=t.askQuestionTimeoutMs??15000;return Y({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:$(gn),timeoutMs:e,retryable:!1,maxRetries:0,execute:async(s,r)=>{let i=X(gn,s);return j(n(i.question,i.options,r),e,`ask_question timed out after ${e}ms`)}})}function Z(n){let{executors:t,enableReadFiles:e=!0,enableSearch:s=!0,enableBash:r=!0,enableWebFetch:i=!0,enableApplyPatch:o=!1,enableEditor:a=!0,enableSkills:m=!0,enableAskQuestion:u=!0,...g}=n,d=[];if(e&&t.readFile)d.push(Ut(t.readFile,g));if(s&&t.search)d.push(Mt(t.search,g));if(r&&t.bash)d.push(Nt(t.bash,g));if(i&&t.webFetch)d.push(Dt(t.webFetch,g));if(a&&t.editor)d.push(St(t.editor,g));else if(o&&t.applyPatch)d.push(Lt(t.applyPatch,g));if(m&&t.skills)d.push(kt(t.skills,g));if(u&&t.askQuestion)d.push(Pt(t.askQuestion,g));return d}import*as k from"node:fs/promises";import*as P from"node:path";var h={BEGIN:"*** Begin Patch",END:"*** End Patch",ADD:"*** Add File: ",UPDATE:"*** Update File: ",DELETE:"*** Delete File: ",MOVE:"*** Move to: ",SECTION:"@@",END_FILE:"*** End of File"},wt=["%%bash","apply_patch","EOF","```"];class I extends Error{constructor(n){super(n);this.name="DiffError"}}function S(n){let t={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return n.normalize("NFC").replace(/./gu,(e)=>t[e]??e).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class Bn{lines;currentFiles;patch={actions:{},warnings:[]};index=0;fuzz=0;currentPath;constructor(n,t){this.lines=n;this.currentFiles=t}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(n){if(!this.patch.warnings)this.patch.warnings=[];this.patch.warnings.push(n)}skipBeginSentinel(){if(this.lines[this.index]?.startsWith(h.BEGIN))this.index++}hasMoreLines(){return this.index<this.lines.length}isEndMarker(){return this.lines[this.index]?.startsWith(h.END)??!1}parseNextAction(){let n=this.lines[this.index];if(n?.startsWith(h.UPDATE)){this.parseUpdate(n.substring(h.UPDATE.length).trim());return}if(n?.startsWith(h.DELETE)){this.parseDelete(n.substring(h.DELETE.length).trim());return}if(n?.startsWith(h.ADD)){this.parseAdd(n.substring(h.ADD.length).trim());return}throw new I(`Unknown line while parsing: ${n}`)}checkDuplicate(n,t){if(n in this.patch.actions)throw new I(`Duplicate ${t} for file: ${n}`)}parseUpdate(n){this.checkDuplicate(n,"update"),this.currentPath=n,this.index++;let t=this.lines[this.index]?.startsWith(h.MOVE)?(this.lines[this.index++]??"").substring(h.MOVE.length).trim():void 0;if(!(n in this.currentFiles))throw new I(`Update File Error: Missing File: ${n}`);let e=this.currentFiles[n]??"",s=this.parseUpdateFile(e,n);s.movePath=t,this.patch.actions[n]=s,this.currentPath=void 0}parseUpdateFile(n,t){let e={type:"update",chunks:[]},s=n.split(`
57
- `),r=0,i=[h.END,h.UPDATE,h.DELETE,h.ADD,h.END_FILE];while(!i.some((o)=>this.lines[this.index]?.startsWith(o.trim()))){let o=this.lines[this.index],a=o?.startsWith("@@ ")?o.substring(3):void 0;if(a!==void 0||(o==="@@"?o:void 0)!==void 0)this.index++;else if(r!==0)throw new I(`Invalid Line:
58
- ${this.lines[this.index]}`);if(a?.trim()){let c=S(a.trim());for(let v=r;v<s.length;v++){let N=s[v];if(N&&(S(N)===c||S(N.trim())===c)){if(r=v+1,S(N.trim())===c&&S(N)!==c)this.fuzz++;break}}}let[u,g,d,p]=he(this.lines,this.index),[f,C,O]=fe(s,u,r,p);if(f===-1){let c=u.join(`
59
- `);this.addWarning({path:this.currentPath||t,chunkIndex:e.chunks.length,message:`Could not find matching context (similarity: ${O.toFixed(2)}). Chunk skipped.`,context:c.length>200?`${c.substring(0,200)}...`:c}),this.index=d}else{this.fuzz+=C;for(let c of g)c.origIndex+=f,e.chunks.push(c);r=f+u.length,this.index=d}}return e}parseDelete(n){if(this.checkDuplicate(n,"delete"),!(n in this.currentFiles))throw new I(`Delete File Error: Missing File: ${n}`);this.patch.actions[n]={type:"delete",chunks:[]},this.index++}parseAdd(n){if(this.checkDuplicate(n,"add"),n in this.currentFiles)throw new I(`Add File Error: File already exists: ${n}`);this.index++;let t=[],e=[h.END,h.UPDATE,h.DELETE,h.ADD];while(this.hasMoreLines()&&!e.some((s)=>this.lines[this.index]?.startsWith(s.trim()))){let s=this.lines[this.index++];if(s===void 0)break;if(!s.startsWith("+"))throw new I(`Invalid Add File line (missing '+'): ${s}`);t.push(s.substring(1))}this.patch.actions[n]={type:"add",newFile:t.join(`
60
- `),chunks:[]}}}function Ft(n,t){let e=n.length>t.length?n:t,s=n.length>t.length?t:n;if(e.length===0)return 1;let r=_e(s,e);return(e.length-r)/e.length}function _e(n,t){let e=t.length+1,s=n.length+1,r=Array(e*s).fill(0),i=(a,m)=>r[a*s+m]??0,o=(a,m,u)=>{r[a*s+m]=u};for(let a=0;a<=t.length;a++)o(a,0,a);for(let a=0;a<=n.length;a++)o(0,a,a);for(let a=1;a<=t.length;a++)for(let m=1;m<=n.length;m++)if(t[a-1]===n[m-1])o(a,m,i(a-1,m-1));else o(a,m,1+Math.min(i(a-1,m-1),i(a,m-1),i(a-1,m)));return i(t.length,n.length)}function fe(n,t,e,s){if(t.length===0)return[e,0,1];let r=0,i=(o)=>{let a=S(t.join(`
61
- `));for(let u=o;u<n.length;u++){let g=S(n.slice(u,u+t.length).join(`
62
- `));if(g===a)return[u,0,1];let d=Ft(g,a);if(d>r)r=d}for(let u=o;u<n.length;u++){let g=S(n.slice(u,u+t.length).map((p)=>p.trimEnd()).join(`
63
- `)),d=S(t.map((p)=>p.trimEnd()).join(`
64
- `));if(g===d)return[u,1,1]}for(let u=o;u<n.length;u++){let g=S(n.slice(u,u+t.length).map((p)=>p.trim()).join(`
65
- `)),d=S(t.map((p)=>p.trim()).join(`
66
- `));if(g===d)return[u,100,1]}let m=0.66;for(let u=o;u<n.length;u++){let g=S(n.slice(u,u+t.length).join(`
67
- `)),d=Ft(g,a);if(d>=m)return[u,1000,d];if(d>r)r=d}return[-1,0,r]};if(s){let[o,a,m]=i(n.length-t.length);if(o!==-1)return[o,a,m];return[o,a,m]=i(e),[o,a+1e4,m]}return i(e)}function he(n,t){let e=t,s=[],r=[],i=[],o=[],a="keep",m=["@@",h.END,h.UPDATE,h.DELETE,h.ADD,h.END_FILE];while(e<n.length){let u=n[e];if(!u||m.some((p)=>u.startsWith(p.trim())))break;if(u==="***")break;if(u.startsWith("***"))throw new I(`Invalid line: ${u}`);e++;let g=a,d=u;if(d[0]==="+")a="add";else if(d[0]==="-")a="delete";else if(d[0]===" ")a="keep";else a="keep",d=` ${d}`;if(d=d.slice(1),a==="keep"&&g!==a){if(i.length||r.length)o.push({origIndex:s.length-r.length,delLines:r,insLines:i});r=[],i=[]}if(a==="delete")r.push(d),s.push(d);else if(a==="add")i.push(d);else s.push(d)}if(i.length||r.length)o.push({origIndex:s.length-r.length,delLines:r,insLines:i});if(e<n.length&&n[e]===h.END_FILE)return e++,[s,o,e,!0];return[s,o,e,!1]}function Xn(n,t,e){let s=P.isAbsolute(t),r=s?P.normalize(t):P.resolve(n,t);if(!e||s)return r;let i=P.relative(n,r);if(i.startsWith("..")||P.isAbsolute(i))throw new I(`Path must stay within cwd: ${t}`);return r}function Bt(n){let t=[],e=!1,s=!1,r=!1;for(let i=0;i<n.length;i++){let o=n[i];if(!e&&wt.some((m)=>o.startsWith(m)))continue;if(o.startsWith(h.BEGIN)){e=!0,s=!0,t.push(o);continue}if(o===h.END){e=!1,t.push(o);continue}let a=o.startsWith(h.ADD)||o.startsWith(h.UPDATE)||o.startsWith(h.DELETE)||o.startsWith(h.MOVE)||o.startsWith(h.SECTION)||o.startsWith("+")||o.startsWith("-")||o.startsWith(" ")||o==="***";if(a&&i!==n.length-1)r=!0;if(e||!s&&a||o===""&&r)t.push(o)}while(t.length>0&&t[t.length-1]==="")t.pop();return!s&&!r?n:t}function Ae(n){let t=n.split(`
68
- `).map((r)=>r.replace(/\r$/,""));t=Bt(t);let e=t.length>0&&t[0].startsWith(h.BEGIN),s=t.length>0&&t[t.length-1]===h.END;if(!e&&!s)return[h.BEGIN,...t,h.END];if(e&&s)return t;throw new I("Invalid patch text - incomplete sentinels. Try breaking it into smaller patches.")}function Ee(n,t){let e=Bt(n.split(`
69
- `)),s=[];for(let r of e)for(let i of t){if(!r.startsWith(i))continue;let o=r.substring(i.length).trim();if(!n.trim().endsWith(o))s.push(o);break}return s}function Ce(n,t,e){if(t.length===0)return n;let s=n.split(`
70
- `),r=[],i=0;for(let o of t){if(o.origIndex>s.length)throw new I(`${e}: chunk.origIndex ${o.origIndex} > lines.length ${s.length}`);if(i>o.origIndex)throw new I(`${e}: currentIndex ${i} > chunk.origIndex ${o.origIndex}`);r.push(...s.slice(i,o.origIndex)),r.push(...o.insLines),i=o.origIndex+o.delLines.length}return r.push(...s.slice(i)),r.join(`
71
- `)}async function ve(n,t,e,s){let r=Ee(n,[h.UPDATE,h.DELETE]),i={};for(let o of r){let a=Xn(t,o,s),m;try{m=await k.readFile(a,e)}catch{throw new I(`File not found: ${o}`)}i[o]=m.replace(/\r\n/g,`
72
- `)}return i}function Oe(n,t){let e={};for(let[s,r]of Object.entries(n.actions))switch(r.type){case"delete":e[s]={type:"delete",oldContent:t[s]};break;case"add":if(r.newFile===void 0)throw new I("ADD action without file content");e[s]={type:"add",newContent:r.newFile};break;case"update":e[s]={type:"update",oldContent:t[s],newContent:Ce(t[s]??"",r.chunks,s),movePath:r.movePath};break}return e}async function Re(n,t,e,s){let r=[];for(let[i,o]of Object.entries(n)){let a=Xn(t,i,s);switch(o.type){case"delete":await k.rm(a,{force:!0}),r.push(`${i}: [deleted]`);break;case"add":if(o.newContent===void 0)throw new I(`Cannot create ${i} with no content`);await k.mkdir(P.dirname(a),{recursive:!0}),await k.writeFile(a,o.newContent,{encoding:e}),r.push(i);break;case"update":{if(o.newContent===void 0)throw new I(`UPDATE change for ${i} has no new content`);if(o.movePath){let m=Xn(t,o.movePath,s);await k.mkdir(P.dirname(m),{recursive:!0}),await k.writeFile(m,o.newContent,{encoding:e}),await k.rm(a,{force:!0}),r.push(`${i} -> ${o.movePath}`)}else await k.writeFile(a,o.newContent,{encoding:e}),r.push(i);break}}}return r}function Tn(n={}){let{encoding:t="utf-8",restrictToCwd:e=!0}=n;return async(s,r,i)=>{let o=Ae(s.input),a=await ve(s.input,r,t,e),m=new Bn(o,a),{patch:u,fuzz:g}=m.parse(),d=Oe(u,a),p=await Re(d,r,t,e),f=["Successfully applied patch to the following files:"];for(let C of p)f.push(C);if(g>0)f.push(`Note: Patch applied with fuzz factor ${g}`);if(u.warnings&&u.warnings.length>0)for(let C of u.warnings)f.push(`Warning (${C.path}): ${C.message}`);return f.join(`
73
- `)}}import{spawn as Xt}from"node:child_process";function pn(n={}){let{shell:t=process.platform==="win32"?"cmd.exe":"/bin/bash",timeoutMs:e=30000,maxOutputBytes:s=1e6,env:r={},combineOutput:i=!0}=n;return async(o,a,m)=>{return new Promise((u,g)=>{let d=process.platform==="win32"?["/c",o]:["-c",o],p=process.platform==="win32",f=Xt(t,d,{cwd:a,env:{...process.env,...r},stdio:["pipe","pipe","pipe"],detached:!p}),C=f.pid,O="",c="",v=0,N=!1,D=!1,U=(R)=>{if(D)return;D=!0,g(R)},w=(R)=>{if(D)return;D=!0,u(R)},B=()=>{if(!C)return;if(p){Xt("taskkill",["/pid",String(C),"/T","/F"],{stdio:"ignore",windowsHide:!0}).unref();return}try{process.kill(-C,"SIGKILL")}catch{f.kill("SIGKILL")}},L=setTimeout(()=>{N=!0,B(),U(Error(`Command timed out after ${e}ms`))},e),x=()=>{N=!0,B(),U(Error("Command was aborted"))};if(m.abortSignal)m.abortSignal.addEventListener("abort",x);f.stdout?.on("data",(R)=>{if(v+=R.length,v<=s)O+=R.toString()}),f.stderr?.on("data",(R)=>{if(v+=R.length,v<=s)c+=R.toString()}),f.on("close",(R)=>{if(clearTimeout(L),m.abortSignal)m.abortSignal.removeEventListener("abort",x);if(N)return;let H=i?O+(c?`
76
+ EOF`;function XQ($,Y={}){let T=Y.fileReadTimeoutMs??1e4;return V$({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:I1(_6),timeoutMs:T*2,retryable:!0,maxRetries:1,execute:async(q,X)=>{let J=z1($Q,q),Q=Array.isArray(J)?J:typeof J==="object"?J.file_paths:[J];return Promise.all(Q.map(async(U)=>{try{let Z=await D$($(U,X),T,`File read timed out after ${T}ms`);return{query:U,result:Z,success:!0}}catch(Z){let K=KY(Z);return{query:U,result:"",error:`Error reading file: ${K}`,success:!1}}}))}})}function JQ($,Y={}){let T=Y.searchTimeoutMs??30000,q=Y.cwd??process.cwd();return V$({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:I1(g6),timeoutMs:T*2,retryable:!0,maxRetries:1,execute:async(X,J)=>{let Q=z1(g6,X);return Promise.all(Q.queries.map(async(U)=>{try{let Z=await D$($(U,q,J),T,`Search timed out after ${T}ms`),K=Z.length>0&&!Z.includes("No results found");return{query:U,result:Z,success:K}}catch(Z){let K=KY(Z);return{query:U,result:"",error:`Search failed: ${K}`,success:!1}}}))}})}function QQ($,Y={}){let T=Y.bashTimeoutMs??30000,q=Y.cwd??process.cwd();return V$({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:I1(m6),timeoutMs:T*2,retryable:!1,maxRetries:0,execute:async(X,J)=>{let Q=z1(YQ,X),U=Array.isArray(Q)?Q:typeof Q==="object"?Q.commands:[Q];return Promise.all(U.map(async(Z)=>{try{let K=await D$($(Z,q,J),T,`Command timed out after ${T}ms`);return{query:Z,result:K,success:!0}}catch(K){let A=KY(K);return{query:Z,result:"",error:`Command failed: ${A}`,success:!1}}}))}})}function UQ($,Y={}){let T=Y.webFetchTimeoutMs??30000;return V$({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:I1(f6),timeoutMs:T*2,retryable:!0,maxRetries:2,execute:async(q,X)=>{let J=z1(f6,q);return Promise.all(J.requests.map(async(Q)=>{try{let U=await D$($(Q.url,Q.prompt,X),T,`Web fetch timed out after ${T}ms`);return{query:Q.url,result:U,success:!0}}catch(U){let Z=KY(U);return{query:Q.url,result:"",error:`Error fetching web content: ${Z}`,success:!1}}}))}})}function ZQ($,Y={}){let T=Y.applyPatchTimeoutMs??30000,q=Y.cwd??process.cwd();return V$({name:"apply_patch",description:HD,inputSchema:I1(u6),timeoutMs:T,retryable:!1,maxRetries:0,execute:async(X,J)=>{let Q=z1(qQ,X),U=typeof Q==="string"?Q:Q.input;try{return{query:"apply_patch",result:await D$($({input:U},q,J),T,`apply_patch timed out after ${T}ms`),success:!0}}catch(Z){return{query:"apply_patch",result:"",error:`apply_patch failed: ${KY(Z)}`,success:!1}}}})}function KQ($,Y={}){let T=Y.editorTimeoutMs??30000,q=Y.cwd??process.cwd();return V$({name:"editor",description:"Edit file using absolute path with create, string replacement, and line insert operations. Supported commands: create, str_replace, insert.",inputSchema:I1(b6),timeoutMs:T,retryable:!1,maxRetries:0,execute:async(X,J)=>{let Q=z1(b6,X);try{let U=await D$($(Q,q,J),T,`Editor operation timed out after ${T}ms`);return{query:`${Q.command}:${Q.path}`,result:U,success:!0}}catch(U){let Z=KY(U);return{query:`${Q.command}:${Q.path}`,result:"",error:`Editor operation failed: ${Z}`,success:!1}}}})}function AQ($,Y={}){let T=Y.skillsTimeoutMs??15000;return V$({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:I1(d6),timeoutMs:T,retryable:!1,maxRetries:0,execute:async(q,X)=>{let J=z1(d6,q);return D$($(J.skill,J.args||void 0,X),T,`Skills operation timed out after ${T}ms`)}})}function WQ($,Y={}){let T=Y.askQuestionTimeoutMs??15000;return V$({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:I1(c6),timeoutMs:T,retryable:!1,maxRetries:0,execute:async(q,X)=>{let J=z1(c6,q);return D$($(J.question,J.options,X),T,`ask_question timed out after ${T}ms`)}})}function AY($){let{executors:Y,enableReadFiles:T=!0,enableSearch:q=!0,enableBash:X=!0,enableWebFetch:J=!0,enableApplyPatch:Q=!1,enableEditor:U=!0,enableSkills:Z=!0,enableAskQuestion:K=!0,...A}=$,W=[];if(T&&Y.readFile)W.push(XQ(Y.readFile,A));if(q&&Y.search)W.push(JQ(Y.search,A));if(X&&Y.bash)W.push(QQ(Y.bash,A));if(J&&Y.webFetch)W.push(UQ(Y.webFetch,A));if(U&&Y.editor)W.push(KQ(Y.editor,A));else if(Q&&Y.applyPatch)W.push(ZQ(Y.applyPatch,A));if(Z&&Y.skills)W.push(AQ(Y.skills,A));if(K&&Y.askQuestion)W.push(WQ(Y.askQuestion,A));return W}import*as Z1 from"node:fs/promises";import*as K1 from"node:path";var n={BEGIN:"*** Begin Patch",END:"*** End Patch",ADD:"*** Add File: ",UPDATE:"*** Update File: ",DELETE:"*** Delete File: ",MOVE:"*** Move to: ",SECTION:"@@",END_FILE:"*** End of File"},EQ=["%%bash","apply_patch","EOF","```"];class R0 extends Error{constructor($){super($);this.name="DiffError"}}function U1($){let Y={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return $.normalize("NFC").replace(/./gu,(T)=>Y[T]??T).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class S9{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(n.BEGIN))this.index++}hasMoreLines(){return this.index<this.lines.length}isEndMarker(){return this.lines[this.index]?.startsWith(n.END)??!1}parseNextAction(){let $=this.lines[this.index];if($?.startsWith(n.UPDATE)){this.parseUpdate($.substring(n.UPDATE.length).trim());return}if($?.startsWith(n.DELETE)){this.parseDelete($.substring(n.DELETE.length).trim());return}if($?.startsWith(n.ADD)){this.parseAdd($.substring(n.ADD.length).trim());return}throw new R0(`Unknown line while parsing: ${$}`)}checkDuplicate($,Y){if($ in this.patch.actions)throw new R0(`Duplicate ${Y} for file: ${$}`)}parseUpdate($){this.checkDuplicate($,"update"),this.currentPath=$,this.index++;let Y=this.lines[this.index]?.startsWith(n.MOVE)?(this.lines[this.index++]??"").substring(n.MOVE.length).trim():void 0;if(!($ in this.currentFiles))throw new R0(`Update File Error: Missing File: ${$}`);let T=this.currentFiles[$]??"",q=this.parseUpdateFile(T,$);q.movePath=Y,this.patch.actions[$]=q,this.currentPath=void 0}parseUpdateFile($,Y){let T={type:"update",chunks:[]},q=$.split(`
77
+ `),X=0,J=[n.END,n.UPDATE,n.DELETE,n.ADD,n.END_FILE];while(!J.some((Q)=>this.lines[this.index]?.startsWith(Q.trim()))){let Q=this.lines[this.index],U=Q?.startsWith("@@ ")?Q.substring(3):void 0;if(U!==void 0||(Q==="@@"?Q:void 0)!==void 0)this.index++;else if(X!==0)throw new R0(`Invalid Line:
78
+ ${this.lines[this.index]}`);if(U?.trim()){let V=U1(U.trim());for(let B=X;B<q.length;B++){let S=q[B];if(S&&(U1(S)===V||U1(S.trim())===V)){if(X=B+1,U1(S.trim())===V&&U1(S)!==V)this.fuzz++;break}}}let[K,A,W,E]=MD(this.lines,this.index),[D,F,H]=ID(q,K,X,E);if(D===-1){let V=K.join(`
79
+ `);this.addWarning({path:this.currentPath||Y,chunkIndex:T.chunks.length,message:`Could not find matching context (similarity: ${H.toFixed(2)}). Chunk skipped.`,context:V.length>200?`${V.substring(0,200)}...`:V}),this.index=W}else{this.fuzz+=F;for(let V of A)V.origIndex+=D,T.chunks.push(V);X=D+K.length,this.index=W}}return T}parseDelete($){if(this.checkDuplicate($,"delete"),!($ in this.currentFiles))throw new R0(`Delete File Error: Missing File: ${$}`);this.patch.actions[$]={type:"delete",chunks:[]},this.index++}parseAdd($){if(this.checkDuplicate($,"add"),$ in this.currentFiles)throw new R0(`Add File Error: File already exists: ${$}`);this.index++;let Y=[],T=[n.END,n.UPDATE,n.DELETE,n.ADD];while(this.hasMoreLines()&&!T.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 R0(`Invalid Add File line (missing '+'): ${q}`);Y.push(q.substring(1))}this.patch.actions[$]={type:"add",newFile:Y.join(`
80
+ `),chunks:[]}}}function GQ($,Y){let T=$.length>Y.length?$:Y,q=$.length>Y.length?Y:$;if(T.length===0)return 1;let X=zD(q,T);return(T.length-X)/T.length}function zD($,Y){let T=Y.length+1,q=$.length+1,X=Array(T*q).fill(0),J=(U,Z)=>X[U*q+Z]??0,Q=(U,Z,K)=>{X[U*q+Z]=K};for(let U=0;U<=Y.length;U++)Q(U,0,U);for(let U=0;U<=$.length;U++)Q(0,U,U);for(let U=1;U<=Y.length;U++)for(let Z=1;Z<=$.length;Z++)if(Y[U-1]===$[Z-1])Q(U,Z,J(U-1,Z-1));else Q(U,Z,1+Math.min(J(U-1,Z-1),J(U,Z-1),J(U-1,Z)));return J(Y.length,$.length)}function ID($,Y,T,q){if(Y.length===0)return[T,0,1];let X=0,J=(Q)=>{let U=U1(Y.join(`
81
+ `));for(let K=Q;K<$.length;K++){let A=U1($.slice(K,K+Y.length).join(`
82
+ `));if(A===U)return[K,0,1];let W=GQ(A,U);if(W>X)X=W}for(let K=Q;K<$.length;K++){let A=U1($.slice(K,K+Y.length).map((E)=>E.trimEnd()).join(`
83
+ `)),W=U1(Y.map((E)=>E.trimEnd()).join(`
84
+ `));if(A===W)return[K,1,1]}for(let K=Q;K<$.length;K++){let A=U1($.slice(K,K+Y.length).map((E)=>E.trim()).join(`
85
+ `)),W=U1(Y.map((E)=>E.trim()).join(`
86
+ `));if(A===W)return[K,100,1]}let Z=0.66;for(let K=Q;K<$.length;K++){let A=U1($.slice(K,K+Y.length).join(`
87
+ `)),W=GQ(A,U);if(W>=Z)return[K,1000,W];if(W>X)X=W}return[-1,0,X]};if(q){let[Q,U,Z]=J($.length-Y.length);if(Q!==-1)return[Q,U,Z];return[Q,U,Z]=J(T),[Q,U+1e4,Z]}return J(T)}function MD($,Y){let T=Y,q=[],X=[],J=[],Q=[],U="keep",Z=["@@",n.END,n.UPDATE,n.DELETE,n.ADD,n.END_FILE];while(T<$.length){let K=$[T];if(!K||Z.some((E)=>K.startsWith(E.trim())))break;if(K==="***")break;if(K.startsWith("***"))throw new R0(`Invalid line: ${K}`);T++;let A=U,W=K;if(W[0]==="+")U="add";else if(W[0]==="-")U="delete";else if(W[0]===" ")U="keep";else U="keep",W=` ${W}`;if(W=W.slice(1),U==="keep"&&A!==U){if(J.length||X.length)Q.push({origIndex:q.length-X.length,delLines:X,insLines:J});X=[],J=[]}if(U==="delete")X.push(W),q.push(W);else if(U==="add")J.push(W);else q.push(W)}if(J.length||X.length)Q.push({origIndex:q.length-X.length,delLines:X,insLines:J});if(T<$.length&&$[T]===n.END_FILE)return T++,[q,Q,T,!0];return[q,Q,T,!1]}function C9($,Y,T){let q=K1.isAbsolute(Y),X=q?K1.normalize(Y):K1.resolve($,Y);if(!T||q)return X;let J=K1.relative($,X);if(J.startsWith("..")||K1.isAbsolute(J))throw new R0(`Path must stay within cwd: ${Y}`);return X}function VQ($){let Y=[],T=!1,q=!1,X=!1;for(let J=0;J<$.length;J++){let Q=$[J];if(!T&&EQ.some((Z)=>Q.startsWith(Z)))continue;if(Q.startsWith(n.BEGIN)){T=!0,q=!0,Y.push(Q);continue}if(Q===n.END){T=!1,Y.push(Q);continue}let U=Q.startsWith(n.ADD)||Q.startsWith(n.UPDATE)||Q.startsWith(n.DELETE)||Q.startsWith(n.MOVE)||Q.startsWith(n.SECTION)||Q.startsWith("+")||Q.startsWith("-")||Q.startsWith(" ")||Q==="***";if(U&&J!==$.length-1)X=!0;if(T||!q&&U||Q===""&&X)Y.push(Q)}while(Y.length>0&&Y[Y.length-1]==="")Y.pop();return!q&&!X?$:Y}function BD($){let Y=$.split(`
88
+ `).map((X)=>X.replace(/\r$/,""));Y=VQ(Y);let T=Y.length>0&&Y[0].startsWith(n.BEGIN),q=Y.length>0&&Y[Y.length-1]===n.END;if(!T&&!q)return[n.BEGIN,...Y,n.END];if(T&&q)return Y;throw new R0("Invalid patch text - incomplete sentinels. Try breaking it into smaller patches.")}function RD($,Y){let T=VQ($.split(`
89
+ `)),q=[];for(let X of T)for(let J of Y){if(!X.startsWith(J))continue;let Q=X.substring(J.length).trim();if(!$.trim().endsWith(Q))q.push(Q);break}return q}function OD($,Y,T){if(Y.length===0)return $;let q=$.split(`
90
+ `),X=[],J=0;for(let Q of Y){if(Q.origIndex>q.length)throw new R0(`${T}: chunk.origIndex ${Q.origIndex} > lines.length ${q.length}`);if(J>Q.origIndex)throw new R0(`${T}: currentIndex ${J} > chunk.origIndex ${Q.origIndex}`);X.push(...q.slice(J,Q.origIndex)),X.push(...Q.insLines),J=Q.origIndex+Q.delLines.length}return X.push(...q.slice(J)),X.join(`
91
+ `)}async function PD($,Y,T,q){let X=RD($,[n.UPDATE,n.DELETE]),J={};for(let Q of X){let U=C9(Y,Q,q),Z;try{Z=await Z1.readFile(U,T)}catch{throw new R0(`File not found: ${Q}`)}J[Q]=Z.replace(/\r\n/g,`
92
+ `)}return J}function LD($,Y){let T={};for(let[q,X]of Object.entries($.actions))switch(X.type){case"delete":T[q]={type:"delete",oldContent:Y[q]};break;case"add":if(X.newFile===void 0)throw new R0("ADD action without file content");T[q]={type:"add",newContent:X.newFile};break;case"update":T[q]={type:"update",oldContent:Y[q],newContent:OD(Y[q]??"",X.chunks,q),movePath:X.movePath};break}return T}async function wD($,Y,T,q){let X=[];for(let[J,Q]of Object.entries($)){let U=C9(Y,J,q);switch(Q.type){case"delete":await Z1.rm(U,{force:!0}),X.push(`${J}: [deleted]`);break;case"add":if(Q.newContent===void 0)throw new R0(`Cannot create ${J} with no content`);await Z1.mkdir(K1.dirname(U),{recursive:!0}),await Z1.writeFile(U,Q.newContent,{encoding:T}),X.push(J);break;case"update":{if(Q.newContent===void 0)throw new R0(`UPDATE change for ${J} has no new content`);if(Q.movePath){let Z=C9(Y,Q.movePath,q);await Z1.mkdir(K1.dirname(Z),{recursive:!0}),await Z1.writeFile(Z,Q.newContent,{encoding:T}),await Z1.rm(U,{force:!0}),X.push(`${J} -> ${Q.movePath}`)}else await Z1.writeFile(U,Q.newContent,{encoding:T}),X.push(J);break}}}return X}function p6($={}){let{encoding:Y="utf-8",restrictToCwd:T=!0}=$;return async(q,X,J)=>{let Q=BD(q.input),U=await PD(q.input,X,Y,T),Z=new S9(Q,U),{patch:K,fuzz:A}=Z.parse(),W=LD(K,U),E=await wD(W,X,Y,T),D=["Successfully applied patch to the following files:"];for(let F of E)D.push(F);if(A>0)D.push(`Note: Patch applied with fuzz factor ${A}`);if(K.warnings&&K.warnings.length>0)for(let F of K.warnings)D.push(`Warning (${F.path}): ${F.message}`);return D.join(`
93
+ `)}}import{spawn as DQ}from"node:child_process";function l6($={}){let{shell:Y=process.platform==="win32"?"cmd.exe":"/bin/bash",timeoutMs:T=30000,maxOutputBytes:q=1e6,env:X={},combineOutput:J=!0}=$;return async(Q,U,Z)=>{return new Promise((K,A)=>{let W=process.platform==="win32"?["/c",Q]:["-c",Q],E=process.platform==="win32",D=DQ(Y,W,{cwd:U,env:{...process.env,...X},stdio:["pipe","pipe","pipe"],detached:!E}),F=D.pid,H="",V="",B=0,S=!1,v=!1,z=(C)=>{if(v)return;v=!0,A(C)},_=(C)=>{if(v)return;v=!0,K(C)},y=()=>{if(!F)return;if(E){DQ("taskkill",["/pid",String(F),"/T","/F"],{stdio:"ignore",windowsHide:!0}).unref();return}try{process.kill(-F,"SIGKILL")}catch{D.kill("SIGKILL")}},k=setTimeout(()=>{S=!0,y(),z(Error(`Command timed out after ${T}ms`))},T),m=()=>{S=!0,y(),z(Error("Command was aborted"))};if(Z.abortSignal)Z.abortSignal.addEventListener("abort",m);D.stdout?.on("data",(C)=>{if(B+=C.length,B<=q)H+=C.toString()}),D.stderr?.on("data",(C)=>{if(B+=C.length,B<=q)V+=C.toString()}),D.on("close",(C)=>{if(clearTimeout(k),Z.abortSignal)Z.abortSignal.removeEventListener("abort",m);if(S)return;let j=J?H+(V?`
74
94
  [stderr]
75
- ${c}`:""):O;if(v>s)H+=`
76
-
77
- [Output truncated: ${v} bytes total, showing first ${s} bytes]`;if(R!==0){let Un=c||`Command exited with code ${R}`;U(Error(Un))}else w(H)}),f.on("error",(R)=>{if(clearTimeout(L),m.abortSignal)m.abortSignal.removeEventListener("abort",x);U(Error(`Failed to execute command: ${R.message}`))})})}}import*as b from"node:fs/promises";import*as z from"node:path";function Ie(n,t,e){let s=z.isAbsolute(t),r=s?z.normalize(t):z.resolve(n,t);if(!e)return r;if(s)return r;let i=z.relative(n,r);if(i.startsWith("..")||z.isAbsolute(i))throw Error(`Path must stay within cwd: ${t}`);return r}function Ue(n,t){if(t.length===0)return 0;return n.split(t).length-1}function Me(n,t,e){let s=n.split(`
78
- `),r=t.split(`
79
- `),i=Math.max(s.length,r.length),o=["```diff"],a=0;for(let m=0;m<i;m++){if(a>=e){o.push("... diff truncated ...");break}let u=s[m],g=r[m];if(u===g)continue;let d=m+1;if(u!==void 0)o.push(`-${d}: ${u}`),a++;if(g!==void 0&&a<e)o.push(`+${d}: ${g}`),a++}return o.push("```"),o.join(`
80
- `)}async function Ne(n,t,e){return await b.mkdir(z.dirname(n),{recursive:!0}),await b.writeFile(n,t,{encoding:e}),`File created successfully at: ${n}`}async function De(n,t,e,s,r){let i=await b.readFile(n,s),o=Ue(i,t);if(o===0)throw Error(`No replacement performed: text not found in ${n}.`);if(o>1)throw Error(`No replacement performed: multiple occurrences of text found in ${n}.`);let a=i.replace(t,e??"");await b.writeFile(n,a,{encoding:s});let m=Me(i,a,r);return`Edited ${n}
81
- ${m}`}async function Le(n,t,e,s){let i=(await b.readFile(n,s)).split(`
82
- `),o=t-1;if(o<0||o>i.length)throw Error(`Invalid line number: ${t}. Valid range: 1-${i.length}`);return i.splice(o,0,...e.split(`
83
- `)),await b.writeFile(n,i.join(`
84
- `),{encoding:s}),`Inserted content at line ${t} in ${n}.`}function _n(n={}){let{encoding:t="utf-8",restrictToCwd:e=!0,maxDiffLines:s=200}=n;return async(r,i,o)=>{let a=Ie(i,r.path,e);switch(r.command){case"create":if(r.file_text==null)throw Error("Parameter `file_text` is required for command: create");return Ne(a,r.file_text,t);case"str_replace":if(r.old_str==null)throw Error("Parameter `old_str` is required for command: str_replace");return De(a,r.old_str,r.new_str,t,s);case"insert":if(r.insert_line==null)throw Error("Parameter `insert_line` is required for insert command.");if(r.new_str==null)throw Error("Parameter `new_str` is required for insert command.");return Le(a,r.insert_line,r.new_str,t);default:throw Error(`Unrecognized command ${r.command}. Allowed commands are: create, str_replace, insert`)}}}import*as fn from"node:fs/promises";import*as G from"node:path";var Se={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0};function hn(n={}){let{maxFileSizeBytes:t,encoding:e,includeLineNumbers:s}={...Se,...n};return async(r,i)=>{let o=G.isAbsolute(r)?G.normalize(r):G.resolve(process.cwd(),r),a=await fn.stat(o);if(!a.isFile())throw Error(`Path is not a file: ${o}`);if(a.size>t)throw Error(`File too large: ${a.size} bytes (max: ${t} bytes). Consider reading specific sections or using a different approach.`);let m=await fn.readFile(o,e);if(s){let u=m.split(`
85
- `),g=String(u.length).length;return u.map((d,p)=>`${String(p+1).padStart(g," ")} | ${d}`).join(`
86
- `)}return m}}import*as Kt from"node:fs/promises";import*as En from"node:path";import{spawn as ke}from"node:child_process";import{readdir as Pe}from"node:fs/promises";import qn from"node:path";import{isMainThread as zt,parentPort as $t,Worker as Fe}from"node:worker_threads";var we=15000,Be=1000,Xe=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]),$n=new Map;function $e(n,t){return qn.relative(n,t).split(qn.sep).join("/")}async function ze(n){let e=(await new Promise((s,r)=>{let i=ke("rg",["--files","--hidden","-g","!.git"],{cwd:n,stdio:["ignore","pipe","pipe"]}),o="",a="";i.stdout.on("data",(m)=>{o+=m.toString()}),i.stderr.on("data",(m)=>{a+=m.toString()}),i.on("error",r),i.on("close",(m)=>{if(m===0){s(o);return}r(Error(a||`rg exited with code ${m}`))})})).split(/\r?\n/).map((s)=>s.trim()).filter((s)=>s.length>0).map((s)=>s.replace(/\\/g,"/"));return new Set(e)}async function qt(n,t,e){let s=await Pe(t,{withFileTypes:!0});for(let r of s){let i=qn.join(t,r.name);if(r.isDirectory()){if(Xe.has(r.name))continue;await qt(n,i,e);continue}if(r.isFile())e.add($e(n,i))}}async function qe(n){let t=new Set;return await qt(n,n,t),t}async function yn(n){try{return await ze(n)}catch{return qe(n)}}function ye(){if(zt||!$t)return;let n=$t;n.on("message",(t)=>{if(t.type!=="index")return;yn(t.cwd).then((e)=>{let s={type:"indexResult",requestId:t.requestId,files:Array.from(e)};n.postMessage(s)}).catch((e)=>{let s={type:"indexResult",requestId:t.requestId,error:e instanceof Error?e.message:"Failed to build file index"};n.postMessage(s)})})}class yt{worker=new Fe(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",(n)=>{if(n.type!=="indexResult")return;let t=this.pending.get(n.requestId);if(!t)return;if(this.pending.delete(n.requestId),n.error){t.reject(Error(n.error));return}t.resolve(n.files??[])}),this.worker.on("error",(n)=>{this.flushPending(n)}),this.worker.on("exit",(n)=>{if(n!==0)this.flushPending(Error(`File index worker exited with code ${n}`))})}requestIndex(n){let t=++this.nextRequestId,e=new Promise((r,i)=>{let o=setTimeout(()=>{this.pending.delete(t),i(Error("Timed out waiting for file index worker response"))},Be);o.unref(),this.pending.set(t,{resolve:(a)=>{clearTimeout(o),r(a)},reject:(a)=>{clearTimeout(o),i(a)}})}),s={type:"index",requestId:t,cwd:n};return this.worker.postMessage(s),e}flushPending(n){for(let[t,e]of this.pending.entries())e.reject(n),this.pending.delete(t)}}ye();var zn;function Ke(){if(!zt)return null;if(zn===void 0)zn=new yt;return zn}async function be(n){let t=Ke();if(!t)return yn(n);try{let e=await t.requestIndex(n);return new Set(e)}catch{return yn(n)}}async function An(n,t={}){let e=t.ttlMs??we,s=Date.now(),r=$n.get(n);if(r&&e>0&&s-r.lastBuiltAt<=e&&r.files.size>0)return r.files;if(r?.pending)return r.pending;let i=be(n).then((o)=>{return $n.set(n,{files:o,lastBuiltAt:Date.now(),pending:null}),o});return $n.set(n,{files:r?.files??new Set,lastBuiltAt:r?.lastBuiltAt??0,pending:i}),i}var xe=["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"],He=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"];function Ve(n,t,e,s){let r=n.split("/"),i=r[r.length-1]??"";if(r.length-1>s)return!1;for(let m=0;m<r.length-1;m++)if(t.has(r[m]??""))return!1;let a=En.posix.extname(i).slice(1).toLowerCase();return e.has(a)||!a&&!i.startsWith(".")}function Cn(n={}){let{includeExtensions:t=xe,excludeDirs:e=He,maxResults:s=100,contextLines:r=2,maxDepth:i=20}=n,o=new Set(e),a=new Set(t.map((m)=>m.toLowerCase()));return async(m,u,g)=>{let d;try{d=new RegExp(m,"gim")}catch(c){throw Error(`Invalid regex pattern: ${m}. ${c instanceof Error?c.message:""}`)}let p=[],f=0,C=await An(u);for(let c of C){if(!Ve(c,o,a,i))continue;if(p.length>=s)break;f++;let v=En.join(u,c);try{let D=(await Kt.readFile(v,"utf-8")).split(`
87
- `);for(let U=0;U<D.length;U++){let w=D[U];d.lastIndex=0;let B;while((B=d.exec(w))!==null){if(p.length>=s)break;let L=Math.max(0,U-r),x=Math.min(D.length-1,U+r),R=[];for(let H=L;H<=x;H++){let Un=H===U?">":" ";R.push(`${Un} ${H+1}: ${D[H]}`)}if(p.push({file:c,line:U+1,column:B.index+1,match:B[0],context:R}),B.index===d.lastIndex)d.lastIndex++}}}catch{}}if(p.length===0)return`No results found for pattern: ${m}
88
- Searched ${f} files.`;let O=[`Found ${p.length} result${p.length===1?"":"s"} for pattern: ${m}`,`Searched ${f} files.`,""];for(let c of p)O.push(`${c.file}:${c.line}:${c.column}`),O.push(...c.context),O.push("");if(p.length>=s)O.push(`(Showing first ${s} results. Refine your search for more specific results.)`);return O.join(`
89
- `)}}function Ye(n){return n.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,`
90
- `).replace(/<[^>]+>/g," ").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#(\d+);/g,(t,e)=>String.fromCharCode(parseInt(e,10))).replace(/\s+/g," ").replace(/\n\s+/g,`
95
+ ${V}`:""):H;if(B>q)j+=`
96
+
97
+ [Output truncated: ${B} bytes total, showing first ${q} bytes]`;if(C!==0){let I=V||`Command exited with code ${C}`;z(Error(I))}else _(j)}),D.on("error",(C)=>{if(clearTimeout(k),Z.abortSignal)Z.abortSignal.removeEventListener("abort",m);z(Error(`Failed to execute command: ${C.message}`))})})}}import*as s1 from"node:fs/promises";import*as M1 from"node:path";function SD($,Y,T){let q=M1.isAbsolute(Y),X=q?M1.normalize(Y):M1.resolve($,Y);if(!T)return X;if(q)return X;let J=M1.relative($,X);if(J.startsWith("..")||M1.isAbsolute(J))throw Error(`Path must stay within cwd: ${Y}`);return X}function CD($,Y){if(Y.length===0)return 0;return $.split(Y).length-1}function yD($,Y,T){let q=$.split(`
98
+ `),X=Y.split(`
99
+ `),J=Math.max(q.length,X.length),Q=["```diff"],U=0;for(let Z=0;Z<J;Z++){if(U>=T){Q.push("... diff truncated ...");break}let K=q[Z],A=X[Z];if(K===A)continue;let W=Z+1;if(K!==void 0)Q.push(`-${W}: ${K}`),U++;if(A!==void 0&&U<T)Q.push(`+${W}: ${A}`),U++}return Q.push("```"),Q.join(`
100
+ `)}async function jD($,Y,T){return await s1.mkdir(M1.dirname($),{recursive:!0}),await s1.writeFile($,Y,{encoding:T}),`File created successfully at: ${$}`}async function vD($,Y,T,q,X){let J=await s1.readFile($,q),Q=CD(J,Y);if(Q===0)throw Error(`No replacement performed: text not found in ${$}.`);if(Q>1)throw Error(`No replacement performed: multiple occurrences of text found in ${$}.`);let U=J.replace(Y,T??"");await s1.writeFile($,U,{encoding:q});let Z=yD(J,U,X);return`Edited ${$}
101
+ ${Z}`}async function xD($,Y,T,q){let J=(await s1.readFile($,q)).split(`
102
+ `),Q=Y-1;if(Q<0||Q>J.length)throw Error(`Invalid line number: ${Y}. Valid range: 1-${J.length}`);return J.splice(Q,0,...T.split(`
103
+ `)),await s1.writeFile($,J.join(`
104
+ `),{encoding:q}),`Inserted content at line ${Y} in ${$}.`}function n6($={}){let{encoding:Y="utf-8",restrictToCwd:T=!0,maxDiffLines:q=200}=$;return async(X,J,Q)=>{let U=SD(J,X.path,T);switch(X.command){case"create":if(X.file_text==null)throw Error("Parameter `file_text` is required for command: create");return jD(U,X.file_text,Y);case"str_replace":if(X.old_str==null)throw Error("Parameter `old_str` is required for command: str_replace");return vD(U,X.old_str,X.new_str,Y,q);case"insert":if(X.insert_line==null)throw Error("Parameter `insert_line` is required for insert command.");if(X.new_str==null)throw Error("Parameter `new_str` is required for insert command.");return xD(U,X.insert_line,X.new_str,Y);default:throw Error(`Unrecognized command ${X.command}. Allowed commands are: create, str_replace, insert`)}}}import*as i6 from"node:fs/promises";import*as WY from"node:path";var kD={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0};function r6($={}){let{maxFileSizeBytes:Y,encoding:T,includeLineNumbers:q}={...kD,...$};return async(X,J)=>{let Q=WY.isAbsolute(X)?WY.normalize(X):WY.resolve(process.cwd(),X),U=await i6.stat(Q);if(!U.isFile())throw Error(`Path is not a file: ${Q}`);if(U.size>Y)throw Error(`File too large: ${U.size} bytes (max: ${Y} bytes). Consider reading specific sections or using a different approach.`);let Z=await i6.readFile(Q,T);if(q){let K=Z.split(`
105
+ `),A=String(K.length).length;return K.map((W,E)=>`${String(E+1).padStart(A," ")} | ${W}`).join(`
106
+ `)}return Z}}import*as MQ from"node:fs/promises";import*as o6 from"node:path";import{spawn as hD}from"node:child_process";import{readdir as _D}from"node:fs/promises";import v9 from"node:path";import{isMainThread as NQ,parentPort as FQ,Worker as gD}from"node:worker_threads";var mD=15000,fD=1000,bD=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]),y9=new Map;function uD($,Y){return v9.relative($,Y).split(v9.sep).join("/")}async function dD($){let T=(await new Promise((q,X)=>{let J=hD("rg",["--files","--hidden","-g","!.git"],{cwd:$,stdio:["ignore","pipe","pipe"]}),Q="",U="";J.stdout.on("data",(Z)=>{Q+=Z.toString()}),J.stderr.on("data",(Z)=>{U+=Z.toString()}),J.on("error",X),J.on("close",(Z)=>{if(Z===0){q(Q);return}X(Error(U||`rg exited with code ${Z}`))})})).split(/\r?\n/).map((q)=>q.trim()).filter((q)=>q.length>0).map((q)=>q.replace(/\\/g,"/"));return new Set(T)}async function HQ($,Y,T){let q=await _D(Y,{withFileTypes:!0});for(let X of q){let J=v9.join(Y,X.name);if(X.isDirectory()){if(bD.has(X.name))continue;await HQ($,J,T);continue}if(X.isFile())T.add(uD($,J))}}async function cD($){let Y=new Set;return await HQ($,$,Y),Y}async function x9($){try{return await dD($)}catch{return cD($)}}function pD(){if(NQ||!FQ)return;let $=FQ;$.on("message",(Y)=>{if(Y.type!=="index")return;x9(Y.cwd).then((T)=>{let q={type:"indexResult",requestId:Y.requestId,files:Array.from(T)};$.postMessage(q)}).catch((T)=>{let q={type:"indexResult",requestId:Y.requestId,error:T instanceof Error?T.message:"Failed to build file index"};$.postMessage(q)})})}class zQ{worker=new gD(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,T=new Promise((X,J)=>{let Q=setTimeout(()=>{this.pending.delete(Y),J(Error("Timed out waiting for file index worker response"))},fD);Q.unref(),this.pending.set(Y,{resolve:(U)=>{clearTimeout(Q),X(U)},reject:(U)=>{clearTimeout(Q),J(U)}})}),q={type:"index",requestId:Y,cwd:$};return this.worker.postMessage(q),T}flushPending($){for(let[Y,T]of this.pending.entries())T.reject($),this.pending.delete(Y)}}pD();var j9;function lD(){if(!NQ)return null;if(j9===void 0)j9=new zQ;return j9}async function nD($){let Y=lD();if(!Y)return x9($);try{let T=await Y.requestIndex($);return new Set(T)}catch{return x9($)}}async function g$($,Y={}){let T=Y.ttlMs??mD,q=Date.now(),X=y9.get($);if(X&&T>0&&q-X.lastBuiltAt<=T&&X.files.size>0)return X.files;if(X?.pending)return X.pending;let J=nD($).then((Q)=>{return y9.set($,{files:Q,lastBuiltAt:Date.now(),pending:null}),Q});return y9.set($,{files:X?.files??new Set,lastBuiltAt:X?.lastBuiltAt??0,pending:J}),J}async function IQ($,Y={}){await g$($,{...Y,ttlMs:0})}import{stat as iD}from"node:fs/promises";import m$ from"node:path";var rD=/[),.:;!?`'"]+$/,aD=/^[(`'"]+/;function oD($){let Y=$.matchAll(/(^|[\s])@([^\s]+)/g),T=[];for(let q of Y){let X=(q[2]??"").trim();if(X.length===0)continue;let J=X.replace(aD,"").replace(rD,"");if(J.length===0||J.includes("@"))continue;T.push(J)}return Array.from(new Set(T))}function sD($,Y){let T=$.replace(/\\/g,"/"),q=m$.isAbsolute(T)?m$.resolve(T):m$.resolve(Y,T),X=m$.relative(Y,q);if(X.startsWith("..")||m$.isAbsolute(X))return;return X.split(m$.sep).join("/")}async function a6($,Y,T={}){let q=oD($);if(q.length===0)return{prompt:$,matchedFiles:[],ignoredMentions:[]};let{maxFiles:X,maxFileBytes:J,maxTotalBytes:Q}=T,U=await g$(Y,{ttlMs:T.ttlMs}),Z=[],K=[],A=[],W=0;for(let E of q){if(X&&A.length>=X){K.push(E);continue}let D=sD(E,Y);if(!D||!U.has(D)){K.push(E);continue}if(!J||!Q){Z.push(D);continue}let F=m$.join(Y,D);try{if(!(await iD(F)).isFile()){K.push(E);continue}let V=W+J;if(V>Q){K.push(E);continue}W+=V,Z.push(D)}catch{K.push(E)}}return{prompt:$,matchedFiles:Z,ignoredMentions:K}}var tD=["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"],eD=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"];function $F($,Y,T,q){let X=$.split("/"),J=X[X.length-1]??"";if(X.length-1>q)return!1;for(let Z=0;Z<X.length-1;Z++)if(Y.has(X[Z]??""))return!1;let U=o6.posix.extname(J).slice(1).toLowerCase();return T.has(U)||!U&&!J.startsWith(".")}function s6($={}){let{includeExtensions:Y=tD,excludeDirs:T=eD,maxResults:q=100,contextLines:X=2,maxDepth:J=20}=$,Q=new Set(T),U=new Set(Y.map((Z)=>Z.toLowerCase()));return async(Z,K,A)=>{let W;try{W=new RegExp(Z,"gim")}catch(V){throw Error(`Invalid regex pattern: ${Z}. ${V instanceof Error?V.message:""}`)}let E=[],D=0,F=await g$(K);for(let V of F){if(!$F(V,Q,U,J))continue;if(E.length>=q)break;D++;let B=o6.join(K,V);try{let v=(await MQ.readFile(B,"utf-8")).split(`
107
+ `);for(let z=0;z<v.length;z++){let _=v[z];W.lastIndex=0;let y;while((y=W.exec(_))!==null){if(E.length>=q)break;let k=Math.max(0,z-X),m=Math.min(v.length-1,z+X),C=[];for(let j=k;j<=m;j++){let I=j===z?">":" ";C.push(`${I} ${j+1}: ${v[j]}`)}if(E.push({file:V,line:z+1,column:y.index+1,match:y[0],context:C}),y.index===W.lastIndex)W.lastIndex++}}}catch{}}if(E.length===0)return`No results found for pattern: ${Z}
108
+ Searched ${D} files.`;let H=[`Found ${E.length} result${E.length===1?"":"s"} for pattern: ${Z}`,`Searched ${D} files.`,""];for(let V of E)H.push(`${V.file}:${V.line}:${V.column}`),H.push(...V.context),H.push("");if(E.length>=q)H.push(`(Showing first ${q} results. Refine your search for more specific results.)`);return H.join(`
109
+ `)}}function YF($){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(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#(\d+);/g,(Y,T)=>String.fromCharCode(parseInt(T,10))).replace(/\s+/g," ").replace(/\n\s+/g,`
91
111
  `).replace(/\n{3,}/g,`
92
112
 
93
- `).trim()}function vn(n={}){let{timeoutMs:t=30000,maxResponseBytes:e=5000000,userAgent:s="Mozilla/5.0 (compatible; AgentBot/1.0)",headers:r={},followRedirects:i=!0}=n;return async(o,a,m)=>{let u;try{u=new URL(o)}catch{throw Error(`Invalid URL: ${o}`)}if(!["http:","https:"].includes(u.protocol))throw Error(`Invalid protocol: ${u.protocol}. Only http and https are supported.`);let g=new AbortController,d=setTimeout(()=>g.abort(),t),p;if(m.abortSignal)p=()=>g.abort(),m.abortSignal.addEventListener("abort",p);try{let f=await fetch(o,{method:"GET",headers:{"User-Agent":s,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",...r},redirect:i?"follow":"manual",signal:g.signal});if(clearTimeout(d),!i&&f.status>=300&&f.status<400)return`Redirect to: ${f.headers.get("location")}`;if(!f.ok)throw Error(`HTTP ${f.status}: ${f.statusText}`);let C=f.headers.get("content-type")||"",O=f.body?.getReader();if(!O)throw Error("Failed to read response body");let c=[],v=0;while(!0){let{done:L,value:x}=await O.read();if(L)break;if(v+=x.length,v>e)throw O.cancel(),Error(`Response too large: exceeded ${e} bytes`);c.push(x)}let N=new Uint8Array(v),D=0;for(let L of c)N.set(L,D),D+=L.length;let U=new TextDecoder("utf-8").decode(N),w;if(C.includes("text/html")||C.includes("application/xhtml"))w=Ye(U);else if(C.includes("application/json"))try{let L=JSON.parse(U);w=JSON.stringify(L,null,2)}catch{w=U}else w=U;let B=[`URL: ${o}`,`Content-Type: ${C}`,`Size: ${v} bytes`,"","--- Content ---",w.slice(0,50000)];if(w.length>50000)B.push(`
94
- [Content truncated: showing first 50000 of ${w.length} characters]`);return B.push("","--- Analysis Request ---",`Prompt: ${a}`),B.join(`
95
- `)}catch(f){if(clearTimeout(d),f instanceof Error){if(f.name==="AbortError")throw Error(`Request timed out after ${t}ms`);throw f}throw Error(`Fetch failed: ${String(f)}`)}finally{if(m.abortSignal&&p)m.abortSignal.removeEventListener("abort",p)}}}function On(n={}){return{readFile:hn(n.fileRead),search:Cn(n.search),bash:pn(n.bash),webFetch:vn(n.webFetch),applyPatch:Tn(n.applyPatch),editor:_n(n.editor)}}var Kn={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 bt(n){if(n!=="yolo")return{};let t={enabled:!0,autoApprove:!0},e={"*":t};for(let s of rn)e[s]=t;return e}function xt(n,t){let e=Kn[n];return Z({...e,...t})}function je(n={}){let{executorOptions:t={},executors:e,...s}=n,r={...On(t),...e??{}};return Z({...s,executors:r})}import{existsSync as Je,readFileSync as We}from"node:fs";import{z as E}from"zod";var tn=E.record(E.string(),E.string()),Ht=E.record(E.string(),E.unknown()),Qe=E.object({type:E.literal("stdio"),command:E.string().min(1),args:E.array(E.string()).optional(),cwd:E.string().min(1).optional(),env:tn.optional()}),Ze=E.object({type:E.literal("sse"),url:E.string().url(),headers:tn.optional()}),Ge=E.object({type:E.literal("streamableHttp"),url:E.string().url(),headers:tn.optional()}),le=E.discriminatedUnion("type",[Qe,Ze,Ge]),nr=E.object({transport:le,disabled:E.boolean().optional(),metadata:Ht.optional()}),tr=E.enum(["stdio","sse","http","streamableHttp"]).optional(),Vt=E.object({type:E.enum(["stdio","sse","streamableHttp"]).optional(),transportType:tr,disabled:E.boolean().optional(),metadata:Ht.optional()});function bn(n){if(!n)return;if(n==="http")return"streamableHttp";return n}var er=Vt.extend({command:E.string().min(1),args:E.array(E.string()).optional(),cwd:E.string().min(1).optional(),env:tn.optional()}).superRefine((n,t)=>{let e=n.type??bn(n.transportType);if(e&&e!=="stdio")t.addIssue({code:E.ZodIssueCode.custom,message:'Expected type "stdio" for command-based MCP server',path:["type"]})}).transform((n)=>({transport:{type:"stdio",command:n.command,args:n.args,cwd:n.cwd,env:n.env},disabled:n.disabled,metadata:n.metadata})),rr=Vt.extend({url:E.string().url(),headers:tn.optional()}).superRefine((n,t)=>{let e=n.type??bn(n.transportType)??"sse";if(e!=="sse"&&e!=="streamableHttp")t.addIssue({code:E.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform((n)=>{if((n.type??bn(n.transportType)??"sse")==="streamableHttp")return{transport:{type:"streamableHttp",url:n.url,headers:n.headers},disabled:n.disabled,metadata:n.metadata};return{transport:{type:"sse",url:n.url,headers:n.headers},disabled:n.disabled,metadata:n.metadata}}),sr=E.union([nr,er,rr]),ir=E.object({mcpServers:E.record(E.string(),sr)}).strict();function Rn(){return Sn()}function xn(n={}){let t=n.filePath??Rn(),e=We(t,"utf8"),s;try{s=JSON.parse(e)}catch(i){let o=i instanceof Error?i.message:String(i);throw Error(`Failed to parse MCP settings JSON at "${t}": ${o}`)}let r=ir.safeParse(s);if(!r.success){let i=r.error.issues.map((o)=>{let a=o.path.join(".");return a?`${a}: ${o.message}`:o.message}).join("; ");throw Error(`Invalid MCP settings at "${t}": ${i}`)}return r.data}function Yt(n={}){let t=n.filePath??Rn();return Je(t)}function Hn(n={}){let t=xn(n);return Object.entries(t.mcpServers).map(([e,s])=>({name:e,transport:s.transport,disabled:s.disabled,metadata:s.metadata}))}async function jt(n,t={}){let e=Hn(t);for(let s of e)await n.registerServer(s);return e}function F(){return Date.now()}function or(n){return n.map((t)=>({name:t.name,description:t.description,inputSchema:t.inputSchema}))}class Vn{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor(n){this.clientFactory=n.clientFactory,this.toolsCacheTtlMs=n.toolsCacheTtlMs??5000}async registerServer(n){await this.runExclusive(n.name,async()=>{let t=this.servers.get(n.name);if(!t){this.servers.set(n.name,{registration:{...n},status:"disconnected",updatedAt:F()});return}let e=JSON.stringify(t.registration.transport)!==JSON.stringify(n.transport);if(t.registration={...n},t.updatedAt=F(),e)await this.disconnectState(t),t.client=void 0,t.toolCache=void 0,t.toolCacheUpdatedAt=void 0})}async unregisterServer(n){await this.runExclusive(n,async()=>{let t=this.requireServer(n);await this.disconnectState(t),this.servers.delete(n)})}async connectServer(n){await this.runExclusive(n,async()=>{let t=this.requireServer(n);await this.connectState(t)})}async disconnectServer(n){await this.runExclusive(n,async()=>{let t=this.requireServer(n);await this.disconnectState(t)})}async setServerDisabled(n,t){await this.runExclusive(n,async()=>{let e=this.requireServer(n);if(e.registration={...e.registration,disabled:t},e.updatedAt=F(),t)await this.disconnectState(e)})}listServers(){return[...this.servers.values()].map((n)=>({name:n.registration.name,status:n.status,disabled:n.registration.disabled===!0,lastError:n.lastError,toolCount:n.toolCache?.length??0,updatedAt:n.updatedAt,metadata:n.registration.metadata})).sort((n,t)=>n.name.localeCompare(t.name))}async listTools(n){let t=this.requireServer(n),e=t.toolCacheUpdatedAt??0;if(t.toolCache&&F()-e<=this.toolsCacheTtlMs)return t.toolCache;return this.refreshTools(n)}async refreshTools(n){return this.runExclusive(n,async()=>{let t=this.requireServer(n),s=await(await this.ensureConnectedClient(t)).listTools(),r=or(s);return t.toolCache=r,t.toolCacheUpdatedAt=F(),t.updatedAt=F(),r})}async callTool(n){return this.runExclusive(n.serverName,async()=>{let t=this.requireServer(n.serverName),e=await this.ensureConnectedClient(t);return t.updatedAt=F(),e.callTool({name:n.toolName,arguments:n.arguments,context:n.context})})}async dispose(){let n=[...this.servers.keys()];for(let t of n)await this.unregisterServer(t)}async ensureConnectedClient(n){if(await this.connectState(n),!n.client)throw Error(`MCP server "${n.registration.name}" does not have an initialized client.`);return n.client}async connectState(n){if(n.registration.disabled)throw Error(`MCP server "${n.registration.name}" is disabled and cannot be connected.`);if(n.status==="connected"&&n.client)return;n.status="connecting",n.updatedAt=F();try{let t=n.client??await this.clientFactory(n.registration);await t.connect(),n.client=t,n.status="connected",n.lastError=void 0,n.updatedAt=F()}catch(t){throw n.status="disconnected",n.lastError=t instanceof Error?t.message:String(t),n.updatedAt=F(),t}}async disconnectState(n){if(!n.client){n.status="disconnected",n.updatedAt=F();return}try{await n.client.disconnect()}finally{n.status="disconnected",n.updatedAt=F()}}requireServer(n){let t=this.servers.get(n);if(!t)throw Error(`Unknown MCP server: ${n}`);return t}async runExclusive(n,t){let e=this.operationLocks.get(n)??Promise.resolve(),s,r=new Promise((o)=>{s=o}),i=e.catch(()=>{return}).then(()=>r);this.operationLocks.set(n,i),await e.catch(()=>{return});try{return await t()}finally{if(s?.(),this.operationLocks.get(n)===i)this.operationLocks.delete(n)}}}import{existsSync as lt,mkdirSync as Ar,readFileSync as Er,writeFileSync as Cr}from"node:fs";import{basename as ne,dirname as Jn}from"node:path";import{providers as Yn}from"@clinebot/llms";import{z as J}from"zod";var Jt=Yn.ProviderSettingsSchema,jn=Yn.toProviderConfig,Wt=J.object({settings:Yn.ProviderSettingsSchema,updatedAt:J.string().datetime(),tokenSource:J.enum(["manual","oauth","migration"]).default("manual")}),In=J.object({version:J.literal(1),lastUsedProvider:J.string().min(1).optional(),providers:J.record(J.string(),Wt)});function l(){return{version:1,providers:{}}}import{existsSync as ar,readFileSync as mr}from"node:fs";import{join as Qt}from"node:path";import{models as ur,providers as cr}from"@clinebot/llms";function _(n){let t=n?.trim();return t?t:void 0}function Zt(n){if(!ar(n))return;try{let t=mr(n,"utf8"),e=JSON.parse(t);if(e&&typeof e==="object"&&!Array.isArray(e))return e}catch{}return}function dr(n){let t=n.dataDir??K(),e=n.globalStatePath??Qt(t,"globalState.json"),s=n.secretsPath??Qt(t,"secrets.json"),r=Zt(e),i=Zt(s);if(!r&&!i)return;return{globalState:r??{},secrets:i??{}}}function gr(n,t,e,s){let r=e==="plan"?"planMode":"actMode",i=t===s?_(e==="plan"?n.planModeApiModelId:n.actModeApiModelId):void 0,a={openrouter:`${r}OpenRouterModelId`,cline:`${r}ClineModelId`,openai:`${r}OpenAiModelId`,ollama:`${r}OllamaModelId`,lmstudio:`${r}LmStudioModelId`,litellm:`${r}LiteLlmModelId`,requesty:`${r}RequestyModelId`,together:`${r}TogetherModelId`,fireworks:`${r}FireworksModelId`,sapaicore:`${r}SapAiCoreModelId`,groq:`${r}GroqModelId`,baseten:`${r}BasetenModelId`,huggingface:`${r}HuggingFaceModelId`,"huawei-cloud-maas":`${r}HuaweiCloudMaasModelId`,oca:`${r}OcaModelId`,aihubmix:`${r}AihubmixModelId`,hicap:`${r}HicapModelId`,nousResearch:`${r}NousResearchModelId`,"vercel-ai-gateway":`${r}VercelAiGatewayModelId`}[t];return(a?_(typeof n[a]==="string"?n[a]:void 0):void 0)??i}function Tr(n,t,e){let s=e==="plan"?n.planModeReasoningEffort:n.actModeReasoningEffort,r=e==="plan"?n.geminiPlanModeThinkingLevel:n.geminiActModeThinkingLevel,i=e==="plan"?n.planModeThinkingBudgetTokens:n.actModeThinkingBudgetTokens,o=(t==="gemini"?r:void 0)??s,a=o==="none"||o==="low"||o==="medium"||o==="high"?o:void 0,m=typeof i==="number"&&Number.isInteger(i)&&i>0?i:void 0;if(!a&&m===void 0)return;return{...a?{effort:a}:{},...m!==void 0?{budgetTokens:m}:{}}}function pr(n){let t=n["openai-codex-oauth-credentials"];if(!t)return;try{let e=JSON.parse(t),s=_(e.access_token),r=_(e.refresh_token),i=_(e.accountId);if(!s&&!r&&!i)return;return{...s?{apiKey:s}:{},auth:{...s?{accessToken:s}:{},...r?{refreshToken:r}:{},...i?{accountId:i}:{}}}}catch{return}}function _r(n){let t=ur.getGeneratedModelsForProvider(n);return Object.keys(t)[0]??void 0}function fr(n,t,e,s){let r=_(s==="plan"?t.planModeApiProvider:t.actModeApiProvider),i=gr(t,n,s,r)??_r(n),o=Tr(t,n,s),a=typeof t.requestTimeoutMs==="number"&&Number.isInteger(t.requestTimeoutMs)&&t.requestTimeoutMs>0?t.requestTimeoutMs:void 0,m={anthropic:e.apiKey,cline:e.clineApiKey,openai:e.openAiApiKey,"openai-native":e.openAiNativeApiKey,openrouter:e.openRouterApiKey,bedrock:e.awsBedrockApiKey,gemini:e.geminiApiKey,ollama:e.ollamaApiKey,deepseek:e.deepSeekApiKey,requesty:e.requestyApiKey,together:e.togetherApiKey,fireworks:e.fireworksApiKey,qwen:e.qwenApiKey,doubao:e.doubaoApiKey,mistral:e.mistralApiKey,litellm:e.liteLlmApiKey,asksage:e.asksageApiKey,xai:e.xaiApiKey,moonshot:e.moonshotApiKey,zai:e.zaiApiKey,huggingface:e.huggingFaceApiKey,nebius:e.nebiusApiKey,sambanova:e.sambanovaApiKey,cerebras:e.cerebrasApiKey,groq:e.groqApiKey,"huawei-cloud-maas":e.huaweiCloudMaasApiKey,baseten:e.basetenApiKey,"vercel-ai-gateway":e.vercelAiGatewayApiKey,dify:e.difyApiKey,minimax:e.minimaxApiKey,hicap:e.hicapApiKey,aihubmix:e.aihubmixApiKey,nousResearch:e.nousResearchApiKey,oca:e.ocaApiKey,sapaicore:e.sapAiCoreClientId},u={};if(n==="openai-codex")Object.assign(u,pr(e));if(n==="cline"){let c=_(e["cline:clineAccountId"]??e.clineAccountId);if(c)u.auth={...u.auth??{},accountId:c}}if(n==="openai"&&t.openAiHeaders)u.headers=t.openAiHeaders;if(n==="bedrock")u.aws={accessKey:_(e.awsAccessKey),secretKey:_(e.awsSecretKey),sessionToken:_(e.awsSessionToken),region:_(t.awsRegion),authentication:t.awsAuthentication,profile:t.awsUseProfile?_(t.awsProfile):void 0,usePromptCache:t.awsBedrockUsePromptCache,useCrossRegionInference:t.awsUseCrossRegionInference,useGlobalInference:t.awsUseGlobalInference,endpoint:_(t.awsBedrockEndpoint),customModelBaseId:_(s==="plan"?t.planModeAwsBedrockCustomModelBaseId:t.actModeAwsBedrockCustomModelBaseId)};if(n==="vertex")u.gcp={projectId:_(t.vertexProjectId),region:_(t.vertexRegion)};if(n==="openai"&&(t.azureApiVersion||t.azureIdentity!==void 0))u.azure={apiVersion:_(t.azureApiVersion),useIdentity:t.azureIdentity};if(n==="sapaicore")u.sap={clientId:_(e.sapAiCoreClientId),clientSecret:_(e.sapAiCoreClientSecret),tokenUrl:_(t.sapAiCoreTokenUrl),resourceGroup:_(t.sapAiResourceGroup),deploymentId:_(s==="plan"?t.planModeSapAiCoreDeploymentId:t.actModeSapAiCoreDeploymentId),useOrchestrationMode:t.sapAiCoreUseOrchestrationMode};if(n==="oca"){u.oca={mode:t.ocaMode};let c=_(e.ocaRefreshToken);if(c)u.auth={...u.auth??{},refreshToken:c}}if(n==="qwen")u.apiLine=t.qwenApiLine;if(n==="moonshot")u.apiLine=t.moonshotApiLine;if(n==="zai")u.apiLine=t.zaiApiLine;if(n==="minimax")u.apiLine=t.minimaxApiLine;let g={anthropic:t.anthropicBaseUrl,openai:t.openAiBaseUrl,ollama:t.ollamaBaseUrl,lmstudio:t.lmStudioBaseUrl,litellm:t.liteLlmBaseUrl,gemini:t.geminiBaseUrl,requesty:t.requestyBaseUrl,asksage:t.asksageApiUrl,dify:t.difyBaseUrl,oca:t.ocaBaseUrl,aihubmix:t.aihubmixBaseUrl,sapaicore:t.sapAiCoreBaseUrl},d=_(m[n]),p=_(g[n]),f={provider:n,...d?{apiKey:d}:{},...i?{model:i}:{},...p?{baseUrl:p}:{},...o?{reasoning:o}:{},...a?{timeout:a}:{},...u},C=cr.ProviderSettingsSchema.safeParse(f);if(!C.success)return;return Object.keys(f).filter((c)=>c!=="provider").length>0?C.data:void 0}function hr(n,t){let e=new Set;for(let s of[n.actModeApiProvider,n.planModeApiProvider]){let r=_(s);if(r)e.add(r)}if(_(t.apiKey))e.add("anthropic");if(_(t.openRouterApiKey))e.add("openrouter");if(_(t.openAiApiKey))e.add("openai");if(_(t.openAiNativeApiKey))e.add("openai-native");if(_(t["openai-codex-oauth-credentials"]))e.add("openai-codex");if(_(t.geminiApiKey))e.add("gemini");if(_(t.ollamaApiKey))e.add("ollama");if(_(t.awsAccessKey)||_(t.awsBedrockApiKey))e.add("bedrock");if(_(n.vertexProjectId)||_(n.vertexRegion))e.add("vertex");if(_(t.clineApiKey))e.add("cline");if(_(t.ocaApiKey))e.add("oca");return e}function Gt(n){let t=n.providerSettingsManager.read(),e=dr(n);if(!e)return{migrated:!1,providerCount:Object.keys(t.providers).length,lastUsedProvider:t.lastUsedProvider};let{globalState:s,secrets:r}=e,i=s.mode==="plan"?"plan":"act",o=hr(s,r),a=l();a.providers={...t.providers},a.lastUsedProvider=t.lastUsedProvider;let m=new Date().toISOString(),u=0;for(let d of o){if(a.providers[d])continue;let p=fr(d,s,r,i);if(!p)continue;a.providers[d]={settings:p,updatedAt:m,tokenSource:"migration"},u+=1}if(u===0)return{migrated:!1,providerCount:Object.keys(t.providers).length,lastUsedProvider:t.lastUsedProvider};let g=_(i==="plan"?s.planModeApiProvider:s.actModeApiProvider);return a.lastUsedProvider=t.lastUsedProvider??(g&&a.providers[g]?g:Object.keys(a.providers)[0]),n.providerSettingsManager.write(a),{migrated:!0,providerCount:Object.keys(a.providers).length,lastUsedProvider:a.lastUsedProvider}}function vr(){return new Date().toISOString()}function Or(n){if(ne(n)!=="providers.json")return;let t=Jn(n);if(ne(t)!=="settings")return;return Jn(t)}class te{filePath;dataDir;constructor(n={}){if(this.filePath=n.filePath??Ln(),this.dataDir=n.dataDir??Or(this.filePath),this.dataDir||!n.filePath)Gt({providerSettingsManager:this,dataDir:this.dataDir})}getFilePath(){return this.filePath}read(){if(!lt(this.filePath))return l();try{let n=Er(this.filePath,"utf8"),t=JSON.parse(n),e=In.safeParse(t);if(e.success)return e.data}catch{}return l()}write(n){let t=In.parse(n),e=Jn(this.filePath);if(!lt(e))Ar(e,{recursive:!0});Cr(this.filePath,`${JSON.stringify(t,null,2)}
96
- `,"utf8")}saveProviderSettings(n,t={}){let e=Jt.parse(n),s=this.read(),r=e.provider,i=t.setLastUsed!==!1,o=s.providers[r],a=t.tokenSource??o?.tokenSource??"manual",m={...s,providers:{...s.providers,[r]:{settings:e,updatedAt:vr(),tokenSource:a}},lastUsedProvider:i?r:s.lastUsedProvider};return this.write(m),m}getProviderSettings(n){return this.read().providers[n]?.settings}getLastUsedProviderSettings(){let n=this.read(),t=n.lastUsedProvider;if(!t)return;return n.providers[t]?.settings}getProviderConfig(n){let t=this.getProviderSettings(n);if(!t)return;return jn(t)}getLastUsedProviderConfig(){let n=this.getLastUsedProviderSettings();if(!n)return;return jn(n)}}import{existsSync as Ir,mkdirSync as Ur}from"node:fs";import{join as Mr}from"node:path";import{createRequire as Rr}from"node:module";function en(){return new Date().toISOString()}function Wn(n){let t=Rr(import.meta.url);if(typeof globalThis.Bun<"u"){let{Database:i}=t("bun:sqlite"),o=new i(n,{create:!0});return{prepare:(a)=>{let m=o.query(a);return{run:(...u)=>m.run(...u),get:(...u)=>m.get(...u),all:(...u)=>m.all(...u)}},exec:(a)=>o.exec(a)}}try{let i=["node",":sqlite"].join(""),{DatabaseSync:o}=t(i),a=new o(n);return{prepare:(m)=>{let u=a.prepare(m);return{run:(...g)=>u.run(...g),get:(...g)=>u.get(...g)??null,all:(...g)=>u.all(...g)}},exec:(m)=>a.exec(m)}}catch{}let s=["better","-sqlite3"].join("");return new(t(s))(n)}function Nr(){return Dn()}function nn(n){return n.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function Dr(n){return{...n,tasks:n.tasks.map((t)=>({...t,createdAt:new Date(t.createdAt),updatedAt:new Date(t.updatedAt)})),mailbox:n.mailbox.map((t)=>({...t,sentAt:new Date(t.sentAt),readAt:t.readAt?new Date(t.readAt):void 0})),missionLog:n.missionLog.map((t)=>({...t,ts:new Date(t.ts)})),runs:(n.runs??[]).map((t)=>({...t,startedAt:new Date(t.startedAt),endedAt:t.endedAt?new Date(t.endedAt):void 0,nextAttemptAt:t.nextAttemptAt?new Date(t.nextAttemptAt):void 0,heartbeatAt:t.heartbeatAt?new Date(t.heartbeatAt):void 0})),outcomes:(n.outcomes??[]).map((t)=>({...t,createdAt:new Date(t.createdAt),finalizedAt:t.finalizedAt?new Date(t.finalizedAt):void 0})),outcomeFragments:(n.outcomeFragments??[]).map((t)=>({...t,createdAt:new Date(t.createdAt),reviewedAt:t.reviewedAt?new Date(t.reviewedAt):void 0}))}}class Qn{teamDirPath;db;constructor(n={}){this.teamDirPath=n.teamDir??Nr()}init(){this.getRawDb()}ensureTeamDir(){if(!Ir(this.teamDirPath))Ur(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return Mr(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let n=Wn(this.dbPath());return this.ensureSchema(n),this.db=n,n}ensureSchema(n){n.exec(`
113
+ `).trim()}function t6($={}){let{timeoutMs:Y=30000,maxResponseBytes:T=5000000,userAgent:q="Mozilla/5.0 (compatible; AgentBot/1.0)",headers:X={},followRedirects:J=!0}=$;return async(Q,U,Z)=>{let K;try{K=new URL(Q)}catch{throw Error(`Invalid URL: ${Q}`)}if(!["http:","https:"].includes(K.protocol))throw Error(`Invalid protocol: ${K.protocol}. Only http and https are supported.`);let A=new AbortController,W=setTimeout(()=>A.abort(),Y),E;if(Z.abortSignal)E=()=>A.abort(),Z.abortSignal.addEventListener("abort",E);try{let D=await fetch(Q,{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",...X},redirect:J?"follow":"manual",signal:A.signal});if(clearTimeout(W),!J&&D.status>=300&&D.status<400)return`Redirect to: ${D.headers.get("location")}`;if(!D.ok)throw Error(`HTTP ${D.status}: ${D.statusText}`);let F=D.headers.get("content-type")||"",H=D.body?.getReader();if(!H)throw Error("Failed to read response body");let V=[],B=0;while(!0){let{done:k,value:m}=await H.read();if(k)break;if(B+=m.length,B>T)throw H.cancel(),Error(`Response too large: exceeded ${T} bytes`);V.push(m)}let S=new Uint8Array(B),v=0;for(let k of V)S.set(k,v),v+=k.length;let z=new TextDecoder("utf-8").decode(S),_;if(F.includes("text/html")||F.includes("application/xhtml"))_=YF(z);else if(F.includes("application/json"))try{let k=JSON.parse(z);_=JSON.stringify(k,null,2)}catch{_=z}else _=z;let y=[`URL: ${Q}`,`Content-Type: ${F}`,`Size: ${B} bytes`,"","--- Content ---",_.slice(0,50000)];if(_.length>50000)y.push(`
114
+ [Content truncated: showing first 50000 of ${_.length} characters]`);return y.push("","--- Analysis Request ---",`Prompt: ${U}`),y.join(`
115
+ `)}catch(D){if(clearTimeout(W),D instanceof Error){if(D.name==="AbortError")throw Error(`Request timed out after ${Y}ms`);throw D}throw Error(`Fetch failed: ${String(D)}`)}finally{if(Z.abortSignal&&E)Z.abortSignal.removeEventListener("abort",E)}}}function e6($={}){return{readFile:r6($.fileRead),search:s6($.search),bash:l6($.bash),webFetch:t6($.webFetch),applyPatch:p6($.applyPatch),editor:n6($.editor)}}var TF={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"},k9=[{name:"openai-native-use-apply-patch",mode:"act",providerIdIncludes:["openai-native"],enableTools:["apply_patch"],disableTools:["editor"]},{name:"codex-and-gpt-use-apply-patch",mode:"act",modelIdIncludes:["codex","gpt"],enableTools:["apply_patch"],disableTools:["editor"]}];function BQ($,Y){if(!Y||Y.length===0)return!0;let T=$.toLowerCase();return Y.some((q)=>T.includes(q.toLowerCase()))}function qF($,Y,T,q){if($.mode&&$.mode!=="any"&&$.mode!==q)return!1;return BQ(Y,$.providerIdIncludes)&&BQ(T,$.modelIdIncludes)}function h9($,Y,T,q){if(!q||q.length===0)return{};let X=new Map;for(let Q of q){if(!qF(Q,$,Y,T))continue;for(let U of Q.disableTools??[])X.set(U,!1);for(let U of Q.enableTools??[])X.set(U,!0)}let J={};for(let[Q,U]of X.entries())J[TF[Q]]=U;return J}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 RQ($){if($!=="yolo")return{};let Y={enabled:!0,autoApprove:!0},T={"*":Y};for(let q of _$)T[q]=Y;return T}function OQ($,Y){let T=t1[$];return AY({...T,...Y})}function NT($={}){let{executorOptions:Y={},executors:T,...q}=$,X={...e6(Y),...T??{}};return AY({...q,executors:X})}var JF=A1.object({name:A1.string().trim().min(1),description:A1.string().trim().min(1),modelId:A1.string().trim().min(1).optional(),tools:A1.union([A1.string(),A1.array(A1.string())]).optional(),skills:A1.union([A1.string(),A1.array(A1.string())]).optional()}),QF=new Set(_$);function PQ($){return/\.(yaml|yml)$/i.test($)}function LQ($){return $.trim().toLowerCase()}function UF($){let Y=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,T=$.match(Y);if(!T)return{data:{},body:$,hadFrontmatter:!1};let[,q,X]=T;try{let J=XF.parse(q);return{data:J&&typeof J==="object"&&!Array.isArray(J)?J:{},body:X,hadFrontmatter:!0}}catch(J){let Q=J instanceof Error?J.message:String(J);return{data:{},body:$,hadFrontmatter:!0,parseError:Q}}}function ZF($){let Y=$.trim();if(!Y)throw Error("Tool name cannot be empty.");if(!QF.has(Y))throw Error(`Unknown tool '${Y}'. Expected one of: ${_$.join(", ")}.`);return Y}function KF($){if(!$)return[];let Y=Array.isArray($)?$:$.split(",");return Array.from(new Set(Y.map(ZF)))}function AF($){let Y=$.trim();if(!Y)throw Error("Skill name cannot be empty.");return Y}function WF($){if($===void 0)return;let Y=Array.isArray($)?$:$.split(",");return Array.from(new Set(Y.map(AF)))}function GY($){let{data:Y,body:T,hadFrontmatter:q,parseError:X}=UF($);if(X)throw Error(`Failed to parse YAML frontmatter: ${X}`);if(!q)throw Error("Missing YAML frontmatter block in agent config file.");let J=JF.parse(Y),Q=T.trim();if(!Q)throw Error("Missing system prompt body in agent config file.");return{name:J.name,description:J.description,modelId:J.modelId,tools:KF(J.tools),skills:WF(J.skills),systemPrompt:Q}}function $8($,Y){if($.length===0)return[];let T=new Map(Y.map((q)=>[q.name,q]));return $.map((q)=>{let X=T.get(q);if(!X)throw Error(`Configured tool '${q}' is unavailable. Available tools: ${Y.map((J)=>J.name).join(", ")}.`);return X})}function Y8($,Y){let T={systemPrompt:$.systemPrompt};if($.modelId)T.modelId=$.modelId;if($.tools.length>0){if(!Y?.availableTools)throw Error("Configured tools cannot be converted into AgentConfig.tools without availableTools.");T.tools=$8($.tools,Y.availableTools)}return T}function _9($,Y){let T=GY($);return Y8(T,Y)}import{createHash as GF}from"node:crypto";import{watch as EF}from"node:fs";import{readdir as VF,readFile as DF}from"node:fs/promises";import{join as FF}from"node:path";function NF($){return GF("sha1").update($).digest("hex")}function HF($){return Boolean($&&typeof $==="object"&&"code"in $)}function wQ($){return HF($)&&$.code==="ENOENT"}class f${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 T of $){if(this.definitionsByType.has(T.type))throw Error(`Duplicate unified config definition type '${T.type}'.`);this.definitionsByType.set(T.type,T),this.recordsByType.set(T.type,new Map),this.discoveredDirectoriesByType.set(T.type,new Set);for(let q of T.directories){let X=this.baseTypesByDirectory.get(q);if(X)X.add(T.type);else this.baseTypesByDirectory.set(q,new Set([T.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(([T,q])=>[T,{...q}]))}getAllSnapshots(){let $=new Map;for(let[Y,T]of this.recordsByType.entries())$.set(Y,new Map([...T.entries()].map(([q,X])=>[q,{...X}])));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,T]of this.watchersByDirectory.entries()){if($.has(Y))continue;T.close(),this.watchersByDirectory.delete(Y)}this.watchedTypesByDirectory=$;for(let Y of $.keys()){if(this.watchersByDirectory.has(Y))continue;try{let T=EF(Y,()=>{let q=this.watchedTypesByDirectory.get(Y);if(!q)return;for(let X of q)this.pendingTypes.add(X);this.scheduleFlush()});this.watchersByDirectory.set(Y,T),T.on("error",(q)=>{let X=this.watchedTypesByDirectory.get(Y);if(!X)return;for(let J of X)this.emit({kind:"error",type:J,error:q,filePath:Y})})}catch(T){if(!wQ(T)){let q=$.get(Y);if(!q)continue;for(let X of q)this.emit({kind:"error",type:X,error:T,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 T=this.definitionsByType.get(Y);if(!T)continue;await this.refreshTypeInternal(T)}})},this.debounceMs)}async refreshTypeInternal($){let{records:Y,discoveredDirectories:T}=await this.loadDefinition($),q=this.recordsByType.get($.type)??new Map;for(let[X,J]of q.entries()){if(Y.has(X))continue;this.emit({kind:"remove",type:$.type,id:X,filePath:J.filePath})}for(let[X,J]of Y.entries()){let Q=q.get(X);if(Q&&Q.filePath===J.filePath&&Q.fingerprint===J.fingerprint)continue;this.emit({kind:"upsert",record:{type:J.type,id:X,item:J.item,filePath:J.filePath}})}if(this.recordsByType.set($.type,Y),this.discoveredDirectoriesByType.set($.type,T),this.started)this.syncDirectoryWatchers()}async loadDefinition($){let Y=new Map,T=new Set;for(let q of $.directories){T.add(q);let X=$.discoverFiles?await $.discoverFiles(q):await this.readDirectoryFileCandidates(q);for(let J of X){let{fileName:Q,filePath:U}=J;if(T.add(J.directoryPath),$.includeFile&&!$.includeFile(Q,U))continue;try{let Z=await DF(U,"utf8"),K={type:$.type,directoryPath:J.directoryPath,fileName:Q,filePath:U,content:Z},A=$.parseFile(K),W=$.resolveId(A,K).trim();if(!W)continue;Y.set(W,{type:$.type,id:W,item:A,filePath:U,fingerprint:NF(Z)})}catch(Z){if(this.emitParseErrors)this.emit({kind:"error",type:$.type,error:Z,filePath:U})}}}return{records:Y,discoveredDirectories:T}}buildDesiredTypesByDirectory(){let $=new Map;for(let[Y,T]of this.baseTypesByDirectory.entries())$.set(Y,new Set(T));for(let[Y,T]of this.discoveredDirectoriesByType.entries())for(let q of T){let X=$.get(q);if(X)X.add(Y);else $.set(q,new Set([Y]))}return $}async readDirectoryFileCandidates($){try{return(await VF($,{withFileTypes:!0})).filter((T)=>T.isFile()).map((T)=>({directoryPath:$,fileName:T.name,filePath:FF($,T.name)})).sort((T,q)=>T.fileName.localeCompare(q.fileName))}catch(Y){if(wQ(Y))return[];throw Y}}}function SQ(){return M9()}function zF($){if(Array.isArray($))return[...$];if(typeof $==="string")return[$];return SQ()}function g9($){return{type:"agent",directories:zF($),includeFile:(Y)=>PQ(Y),parseFile:(Y)=>GY(Y.content),resolveId:(Y)=>LQ(Y.name)}}function CQ($){return new f$([g9($?.directoryPathOrPaths)],{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}import{existsSync as IF,readdirSync as MF}from"node:fs";import{basename as BF,extname as RF,join as OF}from"node:path";function m9($){return B9($)}var T8;((K)=>{K.TaskStart="TaskStart";K.TaskResume="TaskResume";K.TaskCancel="TaskCancel";K.TaskComplete="TaskComplete";K.PreToolUse="PreToolUse";K.PostToolUse="PostToolUse";K.UserPromptSubmit="UserPromptSubmit";K.PreCompact="PreCompact";K.SessionShutdown="SessionShutdown"})(T8||={});var f9={["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"},PF=new Map(Object.values(T8).map(($)=>[$.toLowerCase(),$]));function b9($){let Y=BF($,RF($)).trim().toLowerCase();return PF.get(Y)}function q8($){let Y=[],T=new Set,q=m9($).filter((X)=>IF(X));for(let X of q)try{for(let J of MF(X,{withFileTypes:!0})){if(!J.isFile())continue;let Q=b9(J.name);if(!Q)continue;let U=OF(X,J.name);if(T.has(U))continue;T.add(U),Y.push({fileName:Q,hookEventName:f9[Q],path:U})}}catch{}return Y.sort((X,J)=>X.path.localeCompare(J.path))}import{existsSync as c9,readdirSync as vF,statSync as xF}from"node:fs";import{join as kF,resolve as kQ}from"node:path";import{resolve as LF}from"node:path";import{pathToFileURL as wF}from"node:url";function jQ($){return typeof $==="object"&&$!==null}function yQ($){return Array.isArray($)&&$.every((Y)=>typeof Y==="string")}function SF($,Y){if(!jQ($.manifest))throw Error(`Invalid plugin module at ${Y}: missing required "manifest"`);if(!yQ($.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")&&!yQ($.manifest.hookStages))throw Error(`Invalid plugin module at ${Y}: manifest.hookStages must be a string array when provided`)}function CF($,Y){if(!jQ($))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"`);SF($,Y)}async function u9($,Y={}){let T=LF(Y.cwd??process.cwd(),$),q=await import(wF(T).href),X=Y.exportName??"plugin",J=q.default??q[X];return CF(J,T),J}async function X8($,Y={}){let T=[];for(let q of $)T.push(await u9(q,Y));return T}import{spawn as yF}from"node:child_process";function vQ($){if($ instanceof Error)return $;return Error(String($))}class J8{options;process=null;requestCounter=0;pending=new Map;constructor($){this.options=$}start(){if(this.process&&this.process.exitCode===null)return;let $=yF(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: ${vQ(Y).message}`))}),$.on("exit",(Y,T)=>{this.process=null,this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(Y)}, signal=${String(T)})`))})}async call($,Y,T={}){this.start();let q=this.process;if(!q||q.exitCode!==null)throw Error(`${this.options.name??"sandbox"} process is not available`);let X=`req_${++this.requestCounter}`,J={type:"call",id:X,method:$,args:Y};return await new Promise((Q,U)=>{let Z={resolve:(K)=>Q(K),reject:U};if((T.timeoutMs??0)>0)Z.timeout=setTimeout(()=>{this.pending.delete(X),this.shutdown().catch(()=>{}),U(Error(`${this.options.name??"sandbox"} call timed out after ${T.timeoutMs}ms: ${$}`))},T.timeoutMs);this.pending.set(X,Z),q.send(J,(K)=>{if(!K)return;let A=this.pending.get(X);if(!A)return;if(this.pending.delete(X),A.timeout)clearTimeout(A.timeout);A.reject(Error(`${this.options.name??"sandbox"} failed to send call "${$}": ${vQ(K).message}`))})})}async shutdown(){let $=this.process;if(this.process=null,!$||$.exitCode!==null){this.failPending(Error(`${this.options.name??"sandbox"} shutdown`));return}await new Promise((Y)=>{let T=setTimeout(()=>{try{$.kill("SIGKILL")}catch{}Y()},300);$.once("exit",()=>{clearTimeout(T),Y()});try{$.kill("SIGTERM")}catch{clearTimeout(T),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,T]of this.pending.entries()){if(this.pending.delete(Y),T.timeout)clearTimeout(T.timeout);T.reject($)}}}var jF=`
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 d9($,Y){return typeof $==="number"&&$>0?$:Y}async function xQ($){let Y=new J8({name:"plugin-sandbox",bootstrapScript:jF}),T=d9($.importTimeoutMs,4000),q=d9($.hookTimeoutMs,3000),X=d9($.contributionTimeoutMs,5000),J;try{J=await Y.call("initialize",{pluginPaths:$.pluginPaths,exportName:$.exportName},{timeoutMs:T})}catch(U){throw await Y.shutdown().catch(()=>{}),U}return{extensions:J.map((U)=>{let Z={name:U.name,manifest:U.manifest,setup:(K)=>{for(let A of U.contributions.tools){let W={name:A.name,description:A.description??"",inputSchema:A.inputSchema??{type:"object",properties:{}},timeoutMs:A.timeoutMs,retryable:A.retryable,execute:async(E,D)=>await Y.call("executeTool",{pluginId:U.pluginId,contributionId:A.id,input:E,context:D},{timeoutMs:X})};K.registerTool(W)}for(let A of U.contributions.commands)K.registerCommand({name:A.name,description:A.description,handler:async(W)=>await Y.call("executeCommand",{pluginId:U.pluginId,contributionId:A.id,input:W},{timeoutMs:X})});for(let A of U.contributions.shortcuts)K.registerShortcut({name:A.name,value:A.value??"",description:A.description});for(let A of U.contributions.flags)K.registerFlag({name:A.name,description:A.description,defaultValue:A.defaultValue});for(let A of U.contributions.messageRenderers)K.registerMessageRenderer({name:A.name,render:()=>`[sandbox renderer ${A.name} requires async bridge]`});for(let A of U.contributions.providers)K.registerProvider({name:A.name,description:A.description,metadata:A.metadata})}};if(e1(Z,"input"))Z.onInput=async(K)=>await Y.call("invokeHook",{pluginId:U.pluginId,hookName:"onInput",payload:K},{timeoutMs:q});if(e1(Z,"session_start"))Z.onSessionStart=async(K)=>await Y.call("invokeHook",{pluginId:U.pluginId,hookName:"onSessionStart",payload:K},{timeoutMs:q});if(e1(Z,"before_agent_start"))Z.onBeforeAgentStart=async(K)=>await Y.call("invokeHook",{pluginId:U.pluginId,hookName:"onBeforeAgentStart",payload:K},{timeoutMs:q});if(e1(Z,"tool_call_before"))Z.onToolCall=async(K)=>await Y.call("invokeHook",{pluginId:U.pluginId,hookName:"onToolCall",payload:K},{timeoutMs:q});if(e1(Z,"tool_call_after"))Z.onToolResult=async(K)=>await Y.call("invokeHook",{pluginId:U.pluginId,hookName:"onToolResult",payload:K},{timeoutMs:q});if(e1(Z,"turn_end"))Z.onAgentEnd=async(K)=>await Y.call("invokeHook",{pluginId:U.pluginId,hookName:"onAgentEnd",payload:K},{timeoutMs:q});if(e1(Z,"session_shutdown"))Z.onSessionShutdown=async(K)=>await Y.call("invokeHook",{pluginId:U.pluginId,hookName:"onSessionShutdown",payload:K},{timeoutMs:q});if(e1(Z,"runtime_event"))Z.onRuntimeEvent=async(K)=>{await Y.call("invokeHook",{pluginId:U.pluginId,hookName:"onRuntimeEvent",payload:K},{timeoutMs:q})};if(e1(Z,"error"))Z.onError=async(K)=>{await Y.call("invokeHook",{pluginId:U.pluginId,hookName:"onError",payload:K},{timeoutMs:q})};return Z}),shutdown:async()=>{await Y.shutdown()}}}var hQ=new Set([".js",".mjs",".cjs",".ts",".mts",".cts"]);function p9($){return P9($)}function _Q($){let Y=$.lastIndexOf(".");if(Y===-1)return!1;return hQ.has($.slice(Y))}function Q8($){let Y=kQ($);if(!c9(Y))return[];let T=[],q=[Y];while(q.length>0){let X=q.pop();if(!X)continue;for(let J of vF(X,{withFileTypes:!0})){let Q=kF(X,J.name);if(J.isDirectory()){q.push(Q);continue}if(J.isFile()&&_Q(Q))T.push(Q)}}return T.sort((X,J)=>X.localeCompare(J))}function hF($,Y){let T=[];for(let q of $){let X=q.trim();if(!X)continue;let J=kQ(Y,X);if(!c9(J))throw Error(`Plugin path does not exist: ${J}`);if(xF(J).isDirectory()){T.push(...Q8(J));continue}if(!_Q(J))throw Error(`Plugin file must use a supported extension (${[...hQ].join(", ")}): ${J}`);T.push(J)}return T}function l9($={}){let Y=$.cwd??process.cwd(),T=p9($.workspacePath).flatMap((Q)=>Q8(Q)).filter((Q)=>c9(Q)),q=hF($.pluginPaths??[],Y),X=[],J=new Set;for(let Q of[...q,...T]){if(J.has(Q))continue;J.add(Q),X.push(Q)}return X}async function U8($={}){let Y=l9($);if(Y.length===0)return{extensions:[]};if($.mode==="in_process")return{extensions:await X8(Y,{cwd:$.cwd,exportName:$.exportName})};let T=await xQ({pluginPaths:Y,exportName:$.exportName,importTimeoutMs:$.importTimeoutMs,hookTimeoutMs:$.hookTimeoutMs,contributionTimeoutMs:$.contributionTimeoutMs});return{extensions:T.extensions??[],shutdown:T.shutdown}}import{readdir as gQ,stat as _F}from"node:fs/promises";import{basename as G8,dirname as gF,extname as n9,join as Z8}from"node:path";import mF from"yaml";var K8="SKILL.md",fF=new Set([".md",".markdown",".txt"]);function i9($){return $.trim().toLowerCase()}function A8($){return fF.has(n9($).toLowerCase())}function r9($){let Y=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,T=$.match(Y);if(!T)return{data:{},body:$,hadFrontmatter:!1};let[,q,X]=T;try{let J=mF.parse(q);return{data:J&&typeof J==="object"&&!Array.isArray(J)?J:{},body:X,hadFrontmatter:!0}}catch(J){let Q=J instanceof Error?J.message:String(J);return{data:{},body:$,hadFrontmatter:!0,parseError:Q}}}function W8($,Y,T){if($===void 0||$===null){if(T)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&&T)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 a9($,Y){let{data:T,body:q,parseError:X}=r9($);if(X)throw Error(`Failed to parse YAML frontmatter: ${X}`);let J=q.trim();if(!J)throw Error("Missing instructions body in skill file.");let U=W8(T.name,"name",!1)??Y.trim();if(!U)throw Error("Missing skill name.");return{name:U,description:W8(T.description,"description",!1),disabled:EY(T.disabled,"disabled")??(EY(T.enabled,"enabled")===!1?!0:void 0),instructions:J,frontmatter:T}}function o9($,Y){let{data:T,body:q,parseError:X}=r9($);if(X)throw Error(`Failed to parse YAML frontmatter: ${X}`);let J=q.trim();if(!J)throw Error("Missing instructions body in rule file.");let Q=W8(T.name,"name",!1)??Y.trim();if(!Q)throw Error("Missing rule name.");return{name:Q,disabled:EY(T.disabled,"disabled")??(EY(T.enabled,"enabled")===!1?!0:void 0),instructions:J,frontmatter:T}}function s9($,Y){let{data:T,body:q,parseError:X}=r9($);if(X)throw Error(`Failed to parse YAML frontmatter: ${X}`);let J=q.trim();if(!J)throw Error("Missing instructions body in workflow file.");let Q=W8(T.name,"name",!1)??Y.trim();if(!Q)throw Error("Missing workflow name.");return{name:Q,disabled:EY(T.disabled,"disabled")??(EY(T.enabled,"enabled")===!1?!0:void 0),instructions:J,frontmatter:T}}function t9($){return DT($)}function e9($){return R9($)}function $4($){return O9($)}async function bF($){try{let Y=await gQ($,{withFileTypes:!0}),T=[];for(let q of Y){if(q.isFile()&&q.name===K8){T.push({directoryPath:$,fileName:q.name,filePath:Z8($,q.name)});continue}if(q.isDirectory())T.push({directoryPath:Z8($,q.name),fileName:K8,filePath:Z8($,q.name,K8)})}return T}catch(Y){if(Y.code==="ENOENT")return[];throw Y}}async function mQ($){try{if((await _F($)).isFile())return[{directoryPath:gF($),fileName:G8($),filePath:$}]}catch(Y){if(Y.code!=="ENOENT")throw Y}try{return(await gQ($,{withFileTypes:!0})).filter((T)=>T.isFile()&&A8(T.name)).map((T)=>({directoryPath:$,fileName:T.name,filePath:Z8($,T.name)}))}catch(Y){if(Y.code==="ENOENT")return[];throw Y}}function Y4($){return{type:"skill",directories:$?.directories??t9($?.workspacePath),discoverFiles:bF,includeFile:(T)=>T===K8,parseFile:(T)=>a9(T.content,G8(T.directoryPath)),resolveId:(T)=>i9(T.name)}}function T4($){return{type:"rule",directories:$?.directories??e9($?.workspacePath),discoverFiles:mQ,includeFile:(T,q)=>T===".clinerules"||A8(T)||A8(q),parseFile:(T)=>o9(T.content,G8(T.filePath,n9(T.filePath))),resolveId:(T)=>i9(T.name)}}function q4($){return{type:"workflow",directories:$?.directories??$4($?.workspacePath),discoverFiles:mQ,includeFile:(T)=>A8(T),parseFile:(T)=>s9(T.content,G8(T.filePath,n9(T.filePath))),resolveId:(T)=>i9(T.name)}}function E8($){let Y=[Y4($?.skills),T4($?.rules),q4($?.workflows)];return new f$(Y,{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}function X4($){return{onAuth:({url:Y,instructions:T})=>{if($.onOutput?.(T??"Complete sign-in in your browser."),$.openUrl)Promise.resolve($.openUrl(Y)).catch((q)=>{$.onOpenUrlError?.({url:Y,error:q})});$.onOutput?.(Y)},onPrompt:$.onPrompt}}function uF(){let $;return{promise:new Promise((T)=>{$=T}),resolve:$}}async function b$($){let Y=await import("node:http"),T=$.host??"127.0.0.1",q=$.timeoutMs??300000,X=$.successHtml??dF,J=uF(),Q=!1,U=null,Z=null,K=(E)=>{if(Q)return;Q=!0,J.resolve(E)},A=()=>{if(U)clearTimeout(U),U=null;if(Z)Z.close(),Z=null},W=async()=>{return U=setTimeout(()=>{A(),K(null)},q),J.promise};for(let E of $.ports){let D=Y.createServer((H,V)=>{try{let B=new URL(H.url||"",`http://${T}:${E}`);if(B.pathname!==$.callbackPath){V.statusCode=404,V.end("Not found");return}let S={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(S.error){V.statusCode=400,V.end(`Authentication failed: ${S.error}`),A(),K(S);return}if(!S.code){V.statusCode=400,V.end("Missing authorization code");return}if($.expectedState&&S.state!==$.expectedState){V.statusCode=400,V.end("State mismatch");return}V.statusCode=200,V.setHeader("Content-Type","text/html; charset=utf-8"),V.end(X),A(),K(S)}catch{V.statusCode=500,V.end("Internal error")}}),F=await new Promise((H)=>{let V=(B)=>{D.off("error",V),H({bound:!1,error:B})};D.once("error",V),D.listen(E,T,()=>{D.off("error",V),Z=D,H({bound:!0})})});if(F.error){if(F.error.code==="EADDRINUSE")continue;throw A(),F.error}if(F.bound)return{callbackUrl:`http://${T}:${E}${$.callbackPath}`,waitForCallback:W,cancelWait:()=>{A(),K(null)},close:()=>{A(),K(null)}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var dF=`<!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 fQ($){let Y="";for(let T=0;T<$.length;T+=1)Y+=String.fromCharCode($[T]??0);return btoa(Y).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function cF($){let T=new TextEncoder().encode($),q=await crypto.subtle.digest("SHA-256",T);return new Uint8Array(q)}function pF($=32){let Y=new Uint8Array($);return crypto.getRandomValues(Y),fQ(Y)}async function V8(){let $=pF(),Y=fQ(await cF($));return{verifier:$,challenge:Y}}function D8($){return $.endsWith("/")?$.slice(0,-1):$}function F8($,Y){return new URL(Y,`${D8($)}/`).toString()}function VY($,Y={}){let T=$.trim();if(!T)return{};try{let q=new URL(T);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&&T.includes("#")){let[q,X]=T.split("#",2);return{code:q||void 0,state:X||void 0}}if(T.includes("code=")){let q=new URLSearchParams(T);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:T}}function lF($){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 W1($){if(!$)return null;try{let Y=$.split(".");if(Y.length!==3)return null;let T=Y[1];if(!T)return null;let q=T.replace(/-/g,"+").replace(/_/g,"/"),X=q.padEnd(q.length+(4-q.length%4)%4,"="),J=lF(X);if(!J)return null;return JSON.parse(J)}catch{return null}}function HT($){try{let Y=JSON.parse($),T=Y.error,q=typeof T==="string"?T:T&&typeof T==="object"&&typeof T.type==="string"?T.type:void 0,X=typeof Y.error_description==="string"?Y.error_description:typeof Y.message==="string"?Y.message:T&&typeof T==="object"&&typeof T.message==="string"?T.message:void 0;return{code:q,message:X}}catch{return{}}}function u$($,Y){return Date.now()>=$.expires-Y}async function DY($){if(!$.onManualCodeInput){let J=await $.waitForCallback();return{code:J?.code,state:J?.state,provider:J?.provider,error:J?.error}}let Y,T,q=$.onManualCodeInput().then((J)=>{Y=J,$.cancelWait()}).catch((J)=>{T=J instanceof Error?J:Error(String(J)),$.cancelWait()}),X=await $.waitForCallback();if(T)throw T;if(X?.code||X?.error)return{code:X.code,state:X.state,provider:X.provider,error:X.error};if(Y)return VY(Y,$.parseOptions);if(await q,T)throw T;if(Y)return VY(Y,$.parseOptions);return{}}var J4={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",refresh:"/api/v1/auth/refresh"},nF="/auth",bQ=Array.from({length:11},($,Y)=>48801+Y),iF=300000,rF=30000,Q4=30000;class N8 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 aF(){let $=globalThis.crypto;if(!$)return Math.random().toString(16).slice(2);let Y=new Uint8Array(16);return $.getRandomValues(Y),Array.from(Y,(T)=>T.toString(16).padStart(2,"0")).join("")}function oF($){let Y=Date.parse($);if(Number.isNaN(Y))throw Error(`Invalid expiresAt value: ${$}`);return Y}function uQ($,Y,T={}){let q=$.userInfo.clineUserId??T.accountId,X=$.refreshToken??T.refresh;if(!X)throw Error("Token response did not include a refresh token");return{access:$.accessToken,refresh:X,expires:oF($.expiresAt),accountId:q??void 0,email:$.userInfo.email||T.email,metadata:{provider:Y,tokenType:$.tokenType,userInfo:$.userInfo}}}async function U4($){if(!$)return{};return typeof $==="function"?await $():$}async function sF($,Y){let T=new URL(F8($.apiBaseUrl,J4.authorize));T.searchParams.set("client_type","extension"),T.searchParams.set("callback_url",Y.callbackUrl),T.searchParams.set("redirect_uri",Y.callbackUrl),T.searchParams.set("state",Y.state);let q=await fetch(T.toString(),{method:"GET",redirect:"manual",headers:await U4($.headers),signal:AbortSignal.timeout($.requestTimeoutMs??Q4)});if(q.status>=300&&q.status<400){let J=q.headers.get("location");if(J)return J}if(!q.ok){let J=await q.text().catch(()=>"");throw Error(`Authentication request failed: ${q.status} ${J}`)}let X=await q.json();if(typeof X.redirect_url==="string"&&X.redirect_url.length>0)return X.redirect_url;throw Error("Authentication request did not return a redirect URL")}async function tF($,Y,T,q){let X={grant_type:"authorization_code",code:$,client_type:"extension",redirect_uri:Y,provider:q??T.provider},J=await fetch(F8(T.apiBaseUrl,J4.token),{method:"POST",headers:{"Content-Type":"application/json",...await U4(T.headers)},body:JSON.stringify(X),signal:AbortSignal.timeout(T.requestTimeoutMs??Q4)});if(!J.ok){let U=await J.text().catch(()=>""),Z=HT(U);throw new N8(`Token exchange failed: ${J.status}${Z.message?` - ${Z.message}`:""}`,{status:J.status,errorCode:Z.code})}let Q=await J.json();if(!Q.success||!Q.data?.accessToken)throw Error("Invalid token exchange response");return uQ(Q.data,q??T.provider)}async function H8($){let Y=$.callbackPorts?.length?$.callbackPorts:bQ,T=$.callbackPath??nF,q=aF(),X=await b$({ports:Y,callbackPath:T}),J=X.callbackUrl||`http://127.0.0.1:${Y[0]??bQ[0]}${T}`,Q=await sF($,{callbackUrl:J,state:q});$.callbacks.onAuth({url:Q,instructions:"Continue the authentication process in your browser."});try{let U,Z=$.provider,K=await DY({waitForCallback:X.waitForCallback,cancelWait:X.cancelWait,onManualCodeInput:$.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(K.error)throw Error(`OAuth error: ${K.error}`);if(K.state&&K.state!==q)throw Error("State mismatch");if(U=K.code,Z=K.provider??Z,!U){let A=await $.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),W=VY(A,{includeProvider:!0});if(W.state&&W.state!==q)throw Error("State mismatch");U=W.code,Z=W.provider??Z}if(!U)throw Error("Missing authorization code");return tF(U,J,$,Z)}finally{X.close()}}async function Z4($,Y){let T=await fetch(F8(Y.apiBaseUrl,J4.refresh),{method:"POST",headers:{"Content-Type":"application/json",...await U4(Y.headers)},body:JSON.stringify({refreshToken:$.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout(Y.requestTimeoutMs??Q4)});if(!T.ok){let J=await T.text().catch(()=>""),Q=HT(J);throw new N8(`Token refresh failed: ${T.status}${Q.message?` - ${Q.message}`:""}`,{status:T.status,errorCode:Q.code})}let q=await T.json();if(!q.success||!q.data?.accessToken)throw Error("Invalid token refresh response");let X=$.metadata?.provider??Y.provider;return uQ(q.data,X,$)}async function K4($,Y,T){if(!$)return null;let q=T?.refreshBufferMs??iF,X=T?.retryableTokenGraceMs??rF;if(T?.forceRefresh!==!0&&!u$($,q))return $;try{return await Z4($,Y)}catch(Q){if(Q instanceof N8&&Q.isLikelyInvalidGrant())return null;if($.expires-Date.now()>X)return $;return null}}function eF($){return{id:"cline",name:"Cline Account",usesCallbackServer:!0,async login(Y){return H8({...$,callbacks:Y})},async refreshToken(Y){return Z4(Y,$)},getApiKey(Y){return`workos:${Y.access}`}}}import{nanoid as $N}from"nanoid";var z0={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 z8 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 YN($,Y,T=z0.redirectUri){let q=await fetch(z0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:z0.clientId,code:$,code_verifier:Y,redirect_uri:T}),signal:AbortSignal.timeout(z0.httpTimeoutMs)});if(!q.ok)return{type:"failed"};let X=await q.json();if(!X.access_token||!X.refresh_token||typeof X.expires_in!=="number")return{type:"failed"};return{type:"success",access:X.access_token,refresh:X.refresh_token,expires:Date.now()+X.expires_in*1000,email:X.email,idToken:X.id_token}}async function TN($){try{let Y=await fetch(z0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:$,client_id:z0.clientId}),signal:AbortSignal.timeout(z0.httpTimeoutMs)});if(!Y.ok){let q=await Y.text().catch(()=>""),X=HT(q);throw new z8(`Token refresh failed: ${Y.status}${X.message?` - ${X.message}`:""}`,{status:Y.status,errorCode:X.code})}let T=await Y.json();if(!T.access_token||!T.refresh_token||typeof T.expires_in!=="number")return{type:"failed"};return{type:"success",access:T.access_token,refresh:T.refresh_token,expires:Date.now()+T.expires_in*1000,email:T.email,idToken:T.id_token}}catch(Y){if(Y instanceof z8)throw Y;return{type:"failed"}}}async function qN($="pi"){let{verifier:Y,challenge:T}=await V8(),q=$N(32),X=new URL(z0.authorizationEndpoint);return X.searchParams.set("response_type","code"),X.searchParams.set("client_id",z0.clientId),X.searchParams.set("redirect_uri",z0.redirectUri),X.searchParams.set("scope",z0.scopes),X.searchParams.set("code_challenge",T),X.searchParams.set("code_challenge_method","S256"),X.searchParams.set("state",q),X.searchParams.set("id_token_add_organizations","true"),X.searchParams.set("codex_cli_simplified_flow","true"),X.searchParams.set("originator",$),{verifier:Y,state:q,url:X.toString()}}function XN(){try{let $=new URL(z0.redirectUri),Y=$.port.length>0?Number.parseInt($.port,10):z0.callbackPort;return{host:$.hostname||"localhost",port:Number.isFinite(Y)?Y:z0.callbackPort,callbackPath:$.pathname||"/auth/callback",redirectUri:$.toString()}}catch{return{host:"localhost",port:z0.callbackPort,callbackPath:"/auth/callback",redirectUri:z0.redirectUri}}}function dQ($,Y){let T=Y?W1(Y):W1($),q=T?T:W1($),J=q?.[z0.jwtClaimPath]?.chatgpt_account_id;if(typeof J==="string"&&J.length>0)return J;let Q=q?.organizations;if(Array.isArray(Q)&&Q.length>0){let Z=Q[0];if(typeof Z?.id==="string"&&Z.id.length>0)return Z.id}let U=q?.chatgpt_account_id;if(typeof U==="string"&&U.length>0)return U;return null}function cQ($,Y){let T=dQ($.access,$.idToken)??Y?.accountId;if(!T)throw Error("Failed to extract accountId from token");return{access:$.access,refresh:$.refresh||Y?.refresh||"",expires:$.expires,accountId:T,email:$.email??Y?.email,metadata:{...Y?.metadata??{},provider:"openai-codex"}}}async function I8($){let Y=XN(),{verifier:T,state:q,url:X}=await qN($.originator),J=await b$({host:Y.host,ports:[Y.port],callbackPath:Y.callbackPath,expectedState:q});$.onAuth({url:X,instructions:"Continue the authentication process in your browser."});let Q;try{let U=await DY({waitForCallback:J.waitForCallback,cancelWait:J.cancelWait,onManualCodeInput:$.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(U.state&&U.state!==q)throw Error("State mismatch");if(Q=U.code,!Q){let K=await $.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),A=VY(K,{allowHashCodeState:!0});if(A.state&&A.state!==q)throw Error("State mismatch");Q=A.code}if(!Q)throw Error("Missing authorization code");let Z=await YN(Q,T,Y.redirectUri);if(Z.type!=="success")throw Error("Token exchange failed");return cQ(Z)}finally{J.close()}}async function A4($,Y){let T=await TN($);if(T.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let q=cQ(T,Y);if(!q.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return q}async function W4($,Y){if(!$)return null;let T=Y?.refreshBufferMs??z0.refreshBufferMs,q=Y?.retryableTokenGraceMs??z0.retryableTokenGraceMs;if(Y?.forceRefresh!==!0&&!u$($,T))return $;try{return await A4($.refresh,$)}catch(J){if(J instanceof z8&&J.isLikelyInvalidGrant())return null;if($.expires-Date.now()>q)return $;return null}}function JN($,Y=z0.refreshBufferMs){return u$($,Y)}function QN($){let Y=$.accountId??dQ($.access);if(!Y)throw Error("Failed to extract accountId from token");return{...$,accountId:Y,metadata:{...$.metadata??{},provider:"openai-codex"}}}var UN={id:"openai-codex",name:"ChatGPT Plus/Pro (ChatGPT Subscription)",usesCallbackServer:!0,async login($){return I8({onAuth:$.onAuth,onPrompt:$.onPrompt,onProgress:$.onProgress,onManualCodeInput:$.onManualCodeInput})},async refreshToken($){return A4($.refresh,$)},getApiKey($){return $.access}};import{nanoid as pQ}from"nanoid";var lQ="a8331954c0cf48ba99b5dd223a14c6ea",nQ="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",iQ="openid offline_access",rQ="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",aQ="c1aba3deed5740659981a752714eba33",oQ="https://login-ext.identity.oraclecloud.com",sQ="openid offline_access",tQ="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",eQ="opc-request-id",ZN="/auth/oca",KN=Array.from({length:11},($,Y)=>48801+Y),AN=300000,WN=30000,$U=30000,GN=600000;class M8 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:lQ,idcsUrl:nQ,scopes:iQ,baseUrl:rQ},external:{clientId:aQ,idcsUrl:oQ,scopes:sQ,baseUrl:tQ}},zT=new Map,G4=new Map;function YU($){if(typeof $==="function")return $();return $??"internal"}function TU($){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 EN($=Date.now()){let Y=$-GN;for(let[T,q]of zT.entries())if(q.createdAt<Y)zT.delete(T)}function VN($,Y,T){if(typeof $.expires_in==="number"&&$.expires_in>0)return Date.now()+$.expires_in*1000;let X=W1(Y)?.exp;if(typeof X==="number"&&X>0)return X*1000;let Q=W1(T)?.exp;if(typeof Q==="number"&&Q>0)return Q*1000;return Date.now()+3600000}function qU($,Y,T){let q=$.access_token;if(!q)throw Error("Token response did not include an access token");let X=$.refresh_token??T?.refresh;if(!X)throw Error("Token response did not include a refresh token");let J=W1($.id_token),Q=W1(q),U=J?.sub??Q?.sub,Z=J?.email??Q?.email;return{access:q,refresh:X,expires:VN($,q,$.id_token),accountId:U??T?.accountId,email:Z??T?.email,metadata:{...T?.metadata??{},provider:"oca",mode:Y,subject:U,idToken:$.id_token}}}async function XU($,Y){let T=D8($),q=G4.get(T);if(q)return q;let X=`${T}/.well-known/openid-configuration`,J=await fetch(X,{method:"GET",signal:AbortSignal.timeout(Y)});if(!J.ok){let Z=`${T}/oauth2/v1/token`;return G4.set(T,Z),Z}let U=(await J.json()).token_endpoint||`${T}/oauth2/v1/token`;return G4.set(T,U),U}function JU($){return{code:$.error,message:$.error_description}}async function DN($){let Y=zT.get($.state);if(!Y)throw Error("No PKCE verifier found for this state");zT.delete($.state);let T=$.mode==="external"?$.config.external:$.config.internal,q=await XU(T.idcsUrl,$.requestTimeoutMs),X=new URLSearchParams({grant_type:"authorization_code",code:$.code,redirect_uri:Y.redirectUri,client_id:T.clientId,code_verifier:Y.verifier}),J=await fetch(q,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:X,signal:AbortSignal.timeout($.requestTimeoutMs)}),Q=await J.json();if(!J.ok){let Z=JU(Q);throw new M8(`Token exchange failed: ${J.status}${Z.message?` - ${Z.message}`:""}`,{status:J.status,errorCode:Z.code})}let U=W1(Q.id_token);if(!Q.id_token||!U)throw Error("No ID token received from OCA");if(U.nonce!==Y.nonce)throw Error("OIDC nonce verification failed");return qU(Q,$.mode)}function FN($){let Y=$.mode==="external"?$.config.external:$.config.internal,T=new URL(`${D8(Y.idcsUrl)}/oauth2/v1/authorize`);return T.searchParams.set("client_id",Y.clientId),T.searchParams.set("response_type","code"),T.searchParams.set("scope",Y.scopes),T.searchParams.set("code_challenge",$.challenge),T.searchParams.set("code_challenge_method","S256"),T.searchParams.set("redirect_uri",$.callbackUrl),T.searchParams.set("state",$.state),T.searchParams.set("nonce",$.nonce),T.toString()}async function B8($){let Y=TU($.config),T=YU($.mode),q=$.callbackPorts?.length?$.callbackPorts:KN,X=$.callbackPath??ZN,J=$.requestTimeoutMs??$U,Q=await b$({ports:q,callbackPath:X}),U=Q.callbackUrl;if(!U)throw Error("Unable to bind local OAuth callback server");let Z=pQ(16),K=pQ(16),{verifier:A,challenge:W}=await V8();EN(),zT.set(Z,{verifier:A,nonce:K,mode:T,redirectUri:U,createdAt:Date.now()});let E=FN({callbackUrl:U,mode:T,state:Z,nonce:K,challenge:W,config:Y});$.callbacks.onAuth({url:E,instructions:"Continue the authentication process in your browser."});try{let D=await DY({waitForCallback:Q.waitForCallback,cancelWait:Q.cancelWait,onManualCodeInput:$.callbacks.onManualCodeInput}),F=D.code,H=D.state;if(D.error)throw Error(`OAuth error: ${D.error}`);if(!F){if(!$.callbacks.onManualCodeInput)throw Error("Timed out waiting for OCA callback");throw Error("Missing authorization code")}if(!H||H!==Z)throw Error("State mismatch");return await DN({code:F,state:H,mode:T,config:Y,requestTimeoutMs:J})}finally{Q.close()}}async function E4($,Y={}){let T=TU(Y.config),q=Y.requestTimeoutMs??$U,X=$.metadata?.mode,J=X==="internal"||X==="external"?X:YU(Y.mode),Q=J==="external"?T.external:T.internal,U=await XU(Q.idcsUrl,q),Z=new URLSearchParams({grant_type:"refresh_token",refresh_token:$.refresh,client_id:Q.clientId}),K=await fetch(U,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Z,signal:AbortSignal.timeout(q)}),A=await K.json();if(!K.ok){let W=JU(A);throw new M8(`Token refresh failed: ${K.status}${W.message?` - ${W.message}`:""}`,{status:K.status,errorCode:W.code})}return qU(A,J,$)}async function V4($,Y,T){if(!$)return null;let q=Y?.refreshBufferMs??T?.refreshBufferMs??AN,X=Y?.retryableTokenGraceMs??T?.retryableTokenGraceMs??WN;if(Y?.forceRefresh!==!0&&!u$($,q))return $;try{return await E4($,T)}catch(Q){if(Q instanceof M8&&Q.isLikelyInvalidGrant())return null;if($.expires-Date.now()>X)return $;return null}}function NN($={}){return{id:"oca",name:"Oracle Code Assist",usesCallbackServer:!0,async login(Y){return B8({...$,callbacks:Y})},async refreshToken(Y){return E4(Y,$)},getApiKey(Y){return Y.access}}}async function QU($,Y){let T=new TextEncoder,q=async(K)=>{let A=await crypto.subtle.digest("SHA-256",T.encode(K));return Array.from(new Uint8Array(A).slice(0,4),(W)=>W.toString(16).padStart(2,"0")).join("")},[X,J]=await Promise.all([q(Y),q($)]),Q=Math.floor(Date.now()/1000).toString(16).padStart(8,"0"),U=new Uint32Array(1);crypto.getRandomValues(U);let Z=(U[0]??0).toString(16).padStart(8,"0");return X+J+Q+Z}async function HN($){let Y=await QU($.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",[eQ]:Y}}import{createTool as Uh,getClineDefaultSystemPrompt as Zh}from"@clinebot/agents";class D4{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 T=await this.resolveOrganizationMemberId(Y,$.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent(Y)}/members/${encodeURIComponent(T)}/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 X=await this.fetchMe();if(!X.id?.trim())throw Error("Unable to resolve current user id");return X.id}async resolveOrganizationMemberId($,Y){let T=Y?.trim();if(T)return T;let X=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn($):void 0)?.trim();if(X)return X;let Q=(await this.fetchUserOrganizations()).find((U)=>U.organizationId===$)?.memberId;if(!Q?.trim())throw Error(`Unable to resolve memberId for organization ${$}`);return Q}async request($,Y){let T=(await this.getAuthTokenFn())?.trim();if(!T)throw Error("No Cline account auth token found");let q=this.getHeadersFn?await this.getHeadersFn():{},X=new AbortController,J=setTimeout(()=>X.abort(),this.requestTimeoutMs);try{let Q=await this.fetchImpl(new URL($,this.apiBaseUrl),{method:Y?.method??"GET",headers:{Authorization:`Bearer ${T}`,"Content-Type":"application/json",...q??{}},body:Y?.body!==void 0?JSON.stringify(Y.body):void 0,signal:X.signal});if(Q.status===204||Y?.expectNoContent){if(!Q.ok)throw Error(`Cline account request failed with status ${Q.status}`);return}let U=await Q.text(),Z;if(U.trim())Z=JSON.parse(U);if(!Q.ok){let K=typeof Z==="object"&&Z!==null&&"error"in Z?String(Z.error):`Cline account request failed with status ${Q.status}`;throw Error(K)}if(typeof Z==="object"&&Z!==null){let K=Z;if(typeof K.success==="boolean"){if(!K.success)throw Error(K.error||"Cline account request failed");if(K.data!==void 0)return K.data}}if(Z===void 0||Z===null)throw Error("Cline account response payload was empty");return Z}finally{clearTimeout(J)}}}function UU($){return $.action==="clineAccount"}async function ZU($,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 F4{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{z as b}from"zod";var KU=b.object({workspaceRoot:b.string().min(1),cwd:b.string().optional(),provider:b.string().min(1),model:b.string().min(1),mode:b.enum(["act","plan"]).default("act"),apiKey:b.string(),systemPrompt:b.string().optional(),rules:b.string().optional(),maxIterations:b.number().int().positive().optional(),enableTools:b.boolean(),enableSpawn:b.boolean(),enableTeams:b.boolean(),autoApproveTools:b.boolean().optional(),teamName:b.string().min(1),missionStepInterval:b.number().int().positive(),missionTimeIntervalMs:b.number().int().positive()}),AU=b.enum(["idle","starting","running","stopping","completed","cancelled","failed","error"]),WU=b.enum(["user","assistant","tool","system","status","error"]),GU=b.object({id:b.string().min(1),sessionId:b.string().nullable(),role:WU,content:b.string(),createdAt:b.number().int().nonnegative(),meta:b.object({stream:b.enum(["stdout","stderr"]).optional(),toolName:b.string().optional(),iteration:b.number().int().nonnegative().optional(),agentId:b.string().optional(),conversationId:b.string().optional(),hookEventName:b.string().optional(),inputTokens:b.number().int().nonnegative().optional(),outputTokens:b.number().int().nonnegative().optional()}).optional()}),EU=b.object({toolCalls:b.number().int().nonnegative(),tokensIn:b.number().int().nonnegative(),tokensOut:b.number().int().nonnegative()}),zN=b.object({sessionId:b.string().nullable(),status:AU,config:KU,messages:b.array(GU),rawTranscript:b.string(),error:b.string().nullable(),summary:EU});import{existsSync as IN,readFileSync as MN}from"node:fs";import{z as o}from"zod";var IT=o.record(o.string(),o.string()),VU=o.record(o.string(),o.unknown()),BN=o.object({type:o.literal("stdio"),command:o.string().min(1),args:o.array(o.string()).optional(),cwd:o.string().min(1).optional(),env:IT.optional()}),RN=o.object({type:o.literal("sse"),url:o.string().url(),headers:IT.optional()}),ON=o.object({type:o.literal("streamableHttp"),url:o.string().url(),headers:IT.optional()}),PN=o.discriminatedUnion("type",[BN,RN,ON]),LN=o.object({transport:PN,disabled:o.boolean().optional(),metadata:VU.optional()}),wN=o.enum(["stdio","sse","http","streamableHttp"]).optional(),DU=o.object({type:o.enum(["stdio","sse","streamableHttp"]).optional(),transportType:wN,disabled:o.boolean().optional(),metadata:VU.optional()});function N4($){if(!$)return;if($==="http")return"streamableHttp";return $}var SN=DU.extend({command:o.string().min(1),args:o.array(o.string()).optional(),cwd:o.string().min(1).optional(),env:IT.optional()}).superRefine(($,Y)=>{let T=$.type??N4($.transportType);if(T&&T!=="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})),CN=DU.extend({url:o.string().url(),headers:IT.optional()}).superRefine(($,Y)=>{let T=$.type??N4($.transportType)??"sse";if(T!=="sse"&&T!=="streamableHttp")Y.addIssue({code:o.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform(($)=>{if(($.type??N4($.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}}),yN=o.union([LN,SN,CN]),jN=o.object({mcpServers:o.record(o.string(),yN)}).strict();function R8(){return z9()}function H4($={}){let Y=$.filePath??R8(),T=MN(Y,"utf8"),q;try{q=JSON.parse(T)}catch(J){let Q=J instanceof Error?J.message:String(J);throw Error(`Failed to parse MCP settings JSON at "${Y}": ${Q}`)}let X=jN.safeParse(q);if(!X.success){let J=X.error.issues.map((Q)=>{let U=Q.path.join(".");return U?`${U}: ${Q.message}`:Q.message}).join("; ");throw Error(`Invalid MCP settings at "${Y}": ${J}`)}return X.data}function FU($={}){let Y=$.filePath??R8();return IN(Y)}function z4($={}){let Y=H4($);return Object.entries(Y.mcpServers).map(([T,q])=>({name:T,transport:q.transport,disabled:q.disabled,metadata:q.metadata}))}async function NU($,Y={}){let T=z4(Y);for(let q of T)await $.registerServer(q);return T}function G1(){return Date.now()}function vN($){return $.map((Y)=>({name:Y.name,description:Y.description,inputSchema:Y.inputSchema}))}class I4{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:G1()});return}let T=JSON.stringify(Y.registration.transport)!==JSON.stringify($.transport);if(Y.registration={...$},Y.updatedAt=G1(),T)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 T=this.requireServer($);if(T.registration={...T.registration,disabled:Y},T.updatedAt=G1(),Y)await this.disconnectState(T)})}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($),T=Y.toolCacheUpdatedAt??0;if(Y.toolCache&&G1()-T<=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(),X=vN(q);return Y.toolCache=X,Y.toolCacheUpdatedAt=G1(),Y.updatedAt=G1(),X})}async callTool($){return this.runExclusive($.serverName,async()=>{let Y=this.requireServer($.serverName),T=await this.ensureConnectedClient(Y);return Y.updatedAt=G1(),T.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=G1();try{let Y=$.client??await this.clientFactory($.registration);await Y.connect(),$.client=Y,$.status="connected",$.lastError=void 0,$.updatedAt=G1()}catch(Y){throw $.status="disconnected",$.lastError=Y instanceof Error?Y.message:String(Y),$.updatedAt=G1(),Y}}async disconnectState($){if(!$.client){$.status="disconnected",$.updatedAt=G1();return}try{await $.client.disconnect()}finally{$.status="disconnected",$.updatedAt=G1()}}requireServer($){let Y=this.servers.get($);if(!Y)throw Error(`Unknown MCP server: ${$}`);return Y}async runExclusive($,Y){let T=this.operationLocks.get($)??Promise.resolve(),q,X=new Promise((Q)=>{q=Q}),J=T.catch(()=>{return}).then(()=>X);this.operationLocks.set($,J),await T.catch(()=>{return});try{return await Y()}finally{if(q?.(),this.operationLocks.get($)===J)this.operationLocks.delete($)}}}import{existsSync as BU,mkdirSync as pN,readFileSync as lN,writeFileSync as nN}from"node:fs";import{basename as RU,dirname as R4}from"node:path";import{providers as M4}from"@clinebot/llms";import{z as N$}from"zod";var HU=M4.ProviderSettingsSchema,MT=M4.toProviderConfig,zU=N$.object({settings:M4.ProviderSettingsSchema,updatedAt:N$.string().datetime(),tokenSource:N$.enum(["manual","oauth","migration"]).default("manual")}),O8=N$.object({version:N$.literal(1),lastUsedProvider:N$.string().min(1).optional(),providers:N$.record(N$.string(),zU)});function FY(){return{version:1,providers:{}}}import{existsSync as xN,readFileSync as kN}from"node:fs";import{join as IU}from"node:path";import{models as hN,providers as _N}from"@clinebot/llms";function c($){let Y=$?.trim();return Y?Y:void 0}function MU($){if(!xN($))return;try{let Y=kN($,"utf8"),T=JSON.parse(Y);if(T&&typeof T==="object"&&!Array.isArray(T))return T}catch{}return}function gN($){let Y=$.dataDir??t0(),T=$.globalStatePath??IU(Y,"globalState.json"),q=$.secretsPath??IU(Y,"secrets.json"),X=MU(T),J=MU(q);if(!X&&!J)return;return{globalState:X??{},secrets:J??{}}}function mN($,Y,T,q){let X=T==="plan"?"planMode":"actMode",J=Y===q?c(T==="plan"?$.planModeApiModelId:$.actModeApiModelId):void 0,U={openrouter:`${X}OpenRouterModelId`,cline:`${X}ClineModelId`,openai:`${X}OpenAiModelId`,ollama:`${X}OllamaModelId`,lmstudio:`${X}LmStudioModelId`,litellm:`${X}LiteLlmModelId`,requesty:`${X}RequestyModelId`,together:`${X}TogetherModelId`,fireworks:`${X}FireworksModelId`,sapaicore:`${X}SapAiCoreModelId`,groq:`${X}GroqModelId`,baseten:`${X}BasetenModelId`,huggingface:`${X}HuggingFaceModelId`,"huawei-cloud-maas":`${X}HuaweiCloudMaasModelId`,oca:`${X}OcaModelId`,aihubmix:`${X}AihubmixModelId`,hicap:`${X}HicapModelId`,nousResearch:`${X}NousResearchModelId`,"vercel-ai-gateway":`${X}VercelAiGatewayModelId`}[Y];return(U?c(typeof $[U]==="string"?$[U]:void 0):void 0)??J}function fN($,Y,T){let q=T==="plan"?$.planModeReasoningEffort:$.actModeReasoningEffort,X=T==="plan"?$.geminiPlanModeThinkingLevel:$.geminiActModeThinkingLevel,J=T==="plan"?$.planModeThinkingBudgetTokens:$.actModeThinkingBudgetTokens,Q=(Y==="gemini"?X:void 0)??q,U=Q==="none"||Q==="low"||Q==="medium"||Q==="high"?Q:void 0,Z=typeof J==="number"&&Number.isInteger(J)&&J>0?J:void 0;if(!U&&Z===void 0)return;return{...U?{effort:U}:{},...Z!==void 0?{budgetTokens:Z}:{}}}function bN($){let Y=$["openai-codex-oauth-credentials"];if(!Y)return;try{let T=JSON.parse(Y),q=c(T.access_token),X=c(T.refresh_token),J=c(T.accountId);if(!q&&!X&&!J)return;return{...q?{apiKey:q}:{},auth:{...q?{accessToken:q}:{},...X?{refreshToken:X}:{},...J?{accountId:J}:{}}}}catch{return}}function uN($){let Y=hN.getGeneratedModelsForProvider($);return Object.keys(Y)[0]??void 0}function dN($,Y,T,q){let X=c(q==="plan"?Y.planModeApiProvider:Y.actModeApiProvider),J=mN(Y,$,q,X)??uN($),Q=fN(Y,$,q),U=typeof Y.requestTimeoutMs==="number"&&Number.isInteger(Y.requestTimeoutMs)&&Y.requestTimeoutMs>0?Y.requestTimeoutMs:void 0,Z={anthropic:T.apiKey,cline:T.clineApiKey,openai:T.openAiApiKey,"openai-native":T.openAiNativeApiKey,openrouter:T.openRouterApiKey,bedrock:T.awsBedrockApiKey,gemini:T.geminiApiKey,ollama:T.ollamaApiKey,deepseek:T.deepSeekApiKey,requesty:T.requestyApiKey,together:T.togetherApiKey,fireworks:T.fireworksApiKey,qwen:T.qwenApiKey,doubao:T.doubaoApiKey,mistral:T.mistralApiKey,litellm:T.liteLlmApiKey,asksage:T.asksageApiKey,xai:T.xaiApiKey,moonshot:T.moonshotApiKey,zai:T.zaiApiKey,huggingface:T.huggingFaceApiKey,nebius:T.nebiusApiKey,sambanova:T.sambanovaApiKey,cerebras:T.cerebrasApiKey,groq:T.groqApiKey,"huawei-cloud-maas":T.huaweiCloudMaasApiKey,baseten:T.basetenApiKey,"vercel-ai-gateway":T.vercelAiGatewayApiKey,dify:T.difyApiKey,minimax:T.minimaxApiKey,hicap:T.hicapApiKey,aihubmix:T.aihubmixApiKey,nousResearch:T.nousResearchApiKey,oca:T.ocaApiKey,sapaicore:T.sapAiCoreClientId},K={};if($==="openai-codex")Object.assign(K,bN(T));if($==="cline"){let V=c(T["cline:clineAccountId"]??T.clineAccountId);if(V)K.auth={...K.auth??{},accountId:V}}if($==="openai"&&Y.openAiHeaders)K.headers=Y.openAiHeaders;if($==="bedrock")K.aws={accessKey:c(T.awsAccessKey),secretKey:c(T.awsSecretKey),sessionToken:c(T.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")K.gcp={projectId:c(Y.vertexProjectId),region:c(Y.vertexRegion)};if($==="openai"&&(Y.azureApiVersion||Y.azureIdentity!==void 0))K.azure={apiVersion:c(Y.azureApiVersion),useIdentity:Y.azureIdentity};if($==="sapaicore")K.sap={clientId:c(T.sapAiCoreClientId),clientSecret:c(T.sapAiCoreClientSecret),tokenUrl:c(Y.sapAiCoreTokenUrl),resourceGroup:c(Y.sapAiResourceGroup),deploymentId:c(q==="plan"?Y.planModeSapAiCoreDeploymentId:Y.actModeSapAiCoreDeploymentId),useOrchestrationMode:Y.sapAiCoreUseOrchestrationMode};if($==="oca"){K.oca={mode:Y.ocaMode};let V=c(T.ocaRefreshToken);if(V)K.auth={...K.auth??{},refreshToken:V}}if($==="qwen")K.apiLine=Y.qwenApiLine;if($==="moonshot")K.apiLine=Y.moonshotApiLine;if($==="zai")K.apiLine=Y.zaiApiLine;if($==="minimax")K.apiLine=Y.minimaxApiLine;let A={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},W=c(Z[$]),E=c(A[$]),D={provider:$,...W?{apiKey:W}:{},...J?{model:J}:{},...E?{baseUrl:E}:{},...Q?{reasoning:Q}:{},...U?{timeout:U}:{},...K},F=_N.ProviderSettingsSchema.safeParse(D);if(!F.success)return;return Object.keys(D).filter((V)=>V!=="provider").length>0?F.data:void 0}function cN($,Y){let T=new Set;for(let q of[$.actModeApiProvider,$.planModeApiProvider]){let X=c(q);if(X)T.add(X)}if(c(Y.apiKey))T.add("anthropic");if(c(Y.openRouterApiKey))T.add("openrouter");if(c(Y.openAiApiKey))T.add("openai");if(c(Y.openAiNativeApiKey))T.add("openai-native");if(c(Y["openai-codex-oauth-credentials"]))T.add("openai-codex");if(c(Y.geminiApiKey))T.add("gemini");if(c(Y.ollamaApiKey))T.add("ollama");if(c(Y.awsAccessKey)||c(Y.awsBedrockApiKey))T.add("bedrock");if(c($.vertexProjectId)||c($.vertexRegion))T.add("vertex");if(c(Y.clineApiKey))T.add("cline");if(c(Y.ocaApiKey))T.add("oca");return T}function B4($){let Y=$.providerSettingsManager.read(),T=gN($);if(!T)return{migrated:!1,providerCount:Object.keys(Y.providers).length,lastUsedProvider:Y.lastUsedProvider};let{globalState:q,secrets:X}=T,J=q.mode==="plan"?"plan":"act",Q=cN(q,X),U=FY();U.providers={...Y.providers},U.lastUsedProvider=Y.lastUsedProvider;let Z=new Date().toISOString(),K=0;for(let W of Q){if(U.providers[W])continue;let E=dN(W,q,X,J);if(!E)continue;U.providers[W]={settings:E,updatedAt:Z,tokenSource:"migration"},K+=1}if(K===0)return{migrated:!1,providerCount:Object.keys(Y.providers).length,lastUsedProvider:Y.lastUsedProvider};let A=c(J==="plan"?q.planModeApiProvider:q.actModeApiProvider);return U.lastUsedProvider=Y.lastUsedProvider??(A&&U.providers[A]?A:Object.keys(U.providers)[0]),$.providerSettingsManager.write(U),{migrated:!0,providerCount:Object.keys(U.providers).length,lastUsedProvider:U.lastUsedProvider}}function iN(){return new Date().toISOString()}function rN($){if(RU($)!=="providers.json")return;let Y=R4($);if(RU(Y)!=="settings")return;return R4(Y)}class d${filePath;dataDir;constructor($={}){if(this.filePath=$.filePath??H9(),this.dataDir=$.dataDir??rN(this.filePath),this.dataDir||!$.filePath)B4({providerSettingsManager:this,dataDir:this.dataDir})}getFilePath(){return this.filePath}read(){if(!BU(this.filePath))return FY();try{let $=lN(this.filePath,"utf8"),Y=JSON.parse($),T=O8.safeParse(Y);if(T.success)return T.data}catch{}return FY()}write($){let Y=O8.parse($),T=R4(this.filePath);if(!BU(T))pN(T,{recursive:!0});nN(this.filePath,`${JSON.stringify(Y,null,2)}
342
+ `,"utf8")}saveProviderSettings($,Y={}){let T=HU.parse($),q=this.read(),X=T.provider,J=Y.setLastUsed!==!1,Q=q.providers[X],U=Y.tokenSource??Q?.tokenSource??"manual",Z={...q,providers:{...q.providers,[X]:{settings:T,updatedAt:iN(),tokenSource:U}},lastUsedProvider:J?X:q.lastUsedProvider};return this.write(Z),Z}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 MT(Y)}getLastUsedProviderConfig(){let $=this.getLastUsedProviderSettings();if(!$)return;return MT($)}}import{existsSync as oN,mkdirSync as sN}from"node:fs";import{join as tN}from"node:path";import{createRequire as aN}from"node:module";function O0(){return new Date().toISOString()}function e0($){return $?1:0}function Q0($){return typeof $==="string"?$:""}function K0($){if(typeof $!=="string")return;let Y=$.trim();return Y.length>0?Y:void 0}function $1($){return $===1||$===!0}function NY($){let Y=aN(import.meta.url);if(typeof globalThis.Bun<"u"){let{Database:J}=Y("bun:sqlite"),Q=new J($,{create:!0});return{prepare:(U)=>{let Z=Q.query(U);return{run:(...K)=>Z.run(...K),get:(...K)=>Z.get(...K),all:(...K)=>Z.all(...K)}},exec:(U)=>Q.exec(U)}}try{let J=["node",":sqlite"].join(""),{DatabaseSync:Q}=Y(J),U=new Q($);return{prepare:(Z)=>{let K=U.prepare(Z);return{run:(...A)=>K.run(...A),get:(...A)=>K.get(...A)??null,all:(...A)=>K.all(...A)}},exec:(Z)=>U.exec(Z)}}catch{}let q=["better","-sqlite3"].join("");return new(Y(q))($)}function P8($,Y={}){if($.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec(`
343
+ CREATE TABLE IF NOT EXISTS sessions (
344
+ session_id TEXT PRIMARY KEY,
345
+ source TEXT NOT NULL,
346
+ pid INTEGER NOT NULL,
347
+ started_at TEXT NOT NULL,
348
+ ended_at TEXT,
349
+ exit_code INTEGER,
350
+ status TEXT NOT NULL,
351
+ status_lock INTEGER NOT NULL DEFAULT 0,
352
+ interactive INTEGER NOT NULL,
353
+ provider TEXT NOT NULL,
354
+ model TEXT NOT NULL,
355
+ cwd TEXT NOT NULL,
356
+ workspace_root TEXT NOT NULL,
357
+ team_name TEXT,
358
+ enable_tools INTEGER NOT NULL,
359
+ enable_spawn INTEGER NOT NULL,
360
+ enable_teams INTEGER NOT NULL,
361
+ parent_session_id TEXT,
362
+ parent_agent_id TEXT,
363
+ agent_id TEXT,
364
+ conversation_id TEXT,
365
+ is_subagent INTEGER NOT NULL DEFAULT 0,
366
+ prompt TEXT,
367
+ metadata_json TEXT,
368
+ transcript_path TEXT NOT NULL,
369
+ hook_path TEXT NOT NULL,
370
+ messages_path TEXT,
371
+ updated_at TEXT NOT NULL
372
+ );
373
+ `),$.exec(`
374
+ CREATE TABLE IF NOT EXISTS subagent_spawn_queue (
375
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
376
+ root_session_id TEXT NOT NULL,
377
+ parent_agent_id TEXT NOT NULL,
378
+ task TEXT,
379
+ system_prompt TEXT,
380
+ created_at TEXT NOT NULL,
381
+ consumed_at TEXT
382
+ );
383
+ `),$.exec(`
384
+ CREATE TABLE IF NOT EXISTS schedules (
385
+ schedule_id TEXT PRIMARY KEY,
386
+ name TEXT NOT NULL,
387
+ cron_pattern TEXT NOT NULL,
388
+ prompt TEXT NOT NULL,
389
+ provider TEXT NOT NULL,
390
+ model TEXT NOT NULL,
391
+ mode TEXT NOT NULL DEFAULT 'act',
392
+ workspace_root TEXT,
393
+ cwd TEXT,
394
+ system_prompt TEXT,
395
+ max_iterations INTEGER,
396
+ timeout_seconds INTEGER,
397
+ max_parallel INTEGER NOT NULL DEFAULT 1,
398
+ enabled INTEGER NOT NULL DEFAULT 1,
399
+ created_at TEXT NOT NULL,
400
+ updated_at TEXT NOT NULL,
401
+ last_run_at TEXT,
402
+ next_run_at TEXT,
403
+ claim_token TEXT,
404
+ claim_started_at TEXT,
405
+ claim_until_at TEXT,
406
+ created_by TEXT,
407
+ tags TEXT,
408
+ metadata_json TEXT
409
+ );
410
+ `),$.exec(`
411
+ CREATE TABLE IF NOT EXISTS schedule_executions (
412
+ execution_id TEXT PRIMARY KEY,
413
+ schedule_id TEXT NOT NULL,
414
+ session_id TEXT,
415
+ triggered_at TEXT NOT NULL,
416
+ started_at TEXT,
417
+ ended_at TEXT,
418
+ status TEXT NOT NULL,
419
+ exit_code INTEGER,
420
+ error_message TEXT,
421
+ iterations INTEGER,
422
+ tokens_used INTEGER,
423
+ cost_usd REAL,
424
+ FOREIGN KEY (schedule_id) REFERENCES schedules(schedule_id) ON DELETE CASCADE,
425
+ FOREIGN KEY (session_id) REFERENCES sessions(session_id) ON DELETE SET NULL
426
+ );
427
+ `),$.exec(`
428
+ CREATE INDEX IF NOT EXISTS idx_schedule_executions_schedule
429
+ ON schedule_executions(schedule_id, triggered_at DESC);
430
+ `),$.exec(`
431
+ CREATE INDEX IF NOT EXISTS idx_schedules_next_run
432
+ ON schedules(enabled, next_run_at);
433
+ `),!Y.includeLegacyMigrations)return;let T=$.prepare("PRAGMA table_info(sessions);").all(),q=(Q)=>T.some((U)=>U.name===Q);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 X=$.prepare("PRAGMA table_info(schedules);").all(),J=(Q)=>X.some((U)=>U.name===Q);if(!J("claim_token"))$.exec("ALTER TABLE schedules ADD COLUMN claim_token TEXT;");if(!J("claim_started_at"))$.exec("ALTER TABLE schedules ADD COLUMN claim_started_at TEXT;");if(!J("claim_until_at"))$.exec("ALTER TABLE schedules ADD COLUMN claim_until_at TEXT;")}function eN(){return y6()}function HY($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function $H($){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 BT{teamDirPath;db;constructor($={}){this.teamDirPath=$.teamDir??eN()}init(){this.getRawDb()}ensureTeamDir(){if(!oN(this.teamDirPath))sN(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return tN(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let $=NY(this.dbPath());return this.ensureSchema($),this.db=$,$}ensureSchema($){$.exec(`
97
434
  CREATE TABLE IF NOT EXISTS team_events (
98
435
  id INTEGER PRIMARY KEY AUTOINCREMENT,
99
436
  team_name TEXT NOT NULL,
@@ -170,13 +507,13 @@ Searched ${f} files.`;let O=[`Found ${p.length} result${p.length===1?"":"s"} for
170
507
  version INTEGER NOT NULL DEFAULT 1,
171
508
  PRIMARY KEY(team_name, fragment_id)
172
509
  );
173
- `)}run(n,t=[]){return this.getRawDb().prepare(n).run(...t)}queryOne(n,t=[]){return this.getRawDb().prepare(n).get(...t)??void 0}queryAll(n,t=[]){return this.getRawDb().prepare(n).all(...t)}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map((n)=>n.team_name)}readState(n){let t=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[nn(n)]);if(!t)return;return Dr(JSON.parse(t.state_json))}readHistory(n,t=200){return this.queryAll("SELECT event_type, payload_json, ts FROM team_events WHERE team_name = ? ORDER BY id DESC LIMIT ?",[nn(n),t]).map((e)=>({eventType:e.event_type,payload:JSON.parse(e.payload_json),ts:e.ts}))}loadRuntime(n){let t=nn(n),e=this.readState(t),s=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[t]),r=s?JSON.parse(s.teammates_json):[],i=this.markInProgressRunsInterrupted(t,"runtime_recovered");return{state:e,teammates:r,interruptedRunIds:i}}appendTeamEvent(n,t,e,s){this.run(`INSERT INTO team_events (team_name, ts, event_type, payload_json, causation_id, correlation_id)
174
- VALUES (?, ?, ?, ?, NULL, ?)`,[nn(n),en(),t,JSON.stringify(e),s??null])}persistRuntime(n,t,e){let s=nn(n),r=en();this.run(`INSERT INTO team_runtime_snapshot (team_name, state_json, teammates_json, updated_at)
510
+ `)}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 = ?",[HY($)]);if(!Y)return;return $H(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 ?",[HY($),Y]).map((T)=>({eventType:T.event_type,payload:JSON.parse(T.payload_json),ts:T.ts}))}loadRuntime($){let Y=HY($),T=this.readState(Y),q=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[Y]),X=q?JSON.parse(q.teammates_json):[],J=this.markInProgressRunsInterrupted(Y,"runtime_recovered");return{state:T,teammates:X,interruptedRunIds:J}}appendTeamEvent($,Y,T,q){this.run(`INSERT INTO team_events (team_name, ts, event_type, payload_json, causation_id, correlation_id)
511
+ VALUES (?, ?, ?, ?, NULL, ?)`,[HY($),O0(),Y,JSON.stringify(T),q??null])}persistRuntime($,Y,T){let q=HY($),X=O0();this.run(`INSERT INTO team_runtime_snapshot (team_name, state_json, teammates_json, updated_at)
175
512
  VALUES (?, ?, ?, ?)
176
513
  ON CONFLICT(team_name) DO UPDATE SET
177
514
  state_json = excluded.state_json,
178
515
  teammates_json = excluded.teammates_json,
179
- updated_at = excluded.updated_at`,[s,JSON.stringify(t),JSON.stringify(e),r]);for(let i of t.tasks)this.run(`INSERT INTO team_tasks (team_name, task_id, title, description, status, assignee, depends_on_json, summary, version, updated_at)
516
+ updated_at = excluded.updated_at`,[q,JSON.stringify(Y),JSON.stringify(T),X]);for(let J of Y.tasks)this.run(`INSERT INTO team_tasks (team_name, task_id, title, description, status, assignee, depends_on_json, summary, version, updated_at)
180
517
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?)
181
518
  ON CONFLICT(team_name, task_id) DO UPDATE SET
182
519
  title = excluded.title,
@@ -186,7 +523,7 @@ Searched ${f} files.`;let O=[`Found ${p.length} result${p.length===1?"":"s"} for
186
523
  depends_on_json = excluded.depends_on_json,
187
524
  summary = excluded.summary,
188
525
  version = team_tasks.version + 1,
189
- updated_at = excluded.updated_at`,[s,i.id,i.title,i.description,i.status,i.assignee??null,JSON.stringify(i.dependsOn??[]),i.summary??null,i.updatedAt.toISOString()]);for(let i of t.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)
526
+ updated_at = excluded.updated_at`,[q,J.id,J.title,J.description,J.status,J.assignee??null,JSON.stringify(J.dependsOn??[]),J.summary??null,J.updatedAt.toISOString()]);for(let J of 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)
190
527
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
191
528
  ON CONFLICT(team_name, run_id) DO UPDATE SET
192
529
  agent_id = excluded.agent_id,
@@ -198,14 +535,14 @@ Searched ${f} files.`;let O=[`Found ${p.length} result${p.length===1?"":"s"} for
198
535
  error = excluded.error,
199
536
  lease_owner = excluded.lease_owner,
200
537
  heartbeat_at = excluded.heartbeat_at,
201
- version = team_runs.version + 1`,[s,i.id,i.agentId,i.taskId??null,i.status,i.message,i.startedAt?i.startedAt.toISOString():null,i.endedAt?i.endedAt.toISOString():null,i.error??null,i.leaseOwner??null,i.heartbeatAt?i.heartbeatAt.toISOString():null]);for(let i of t.outcomes??[])this.run(`INSERT INTO team_outcomes (team_name, outcome_id, title, status, schema_json, finalized_at, version)
538
+ version = team_runs.version + 1`,[q,J.id,J.agentId,J.taskId??null,J.status,J.message,J.startedAt?J.startedAt.toISOString():null,J.endedAt?J.endedAt.toISOString():null,J.error??null,J.leaseOwner??null,J.heartbeatAt?J.heartbeatAt.toISOString():null]);for(let J of Y.outcomes??[])this.run(`INSERT INTO team_outcomes (team_name, outcome_id, title, status, schema_json, finalized_at, version)
202
539
  VALUES (?, ?, ?, ?, ?, ?, 1)
203
540
  ON CONFLICT(team_name, outcome_id) DO UPDATE SET
204
541
  title = excluded.title,
205
542
  status = excluded.status,
206
543
  schema_json = excluded.schema_json,
207
544
  finalized_at = excluded.finalized_at,
208
- version = team_outcomes.version + 1`,[s,i.id,i.title,i.status,JSON.stringify({requiredSections:i.requiredSections}),i.finalizedAt?i.finalizedAt.toISOString():null]);for(let i of t.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)
545
+ version = team_outcomes.version + 1`,[q,J.id,J.title,J.status,JSON.stringify({requiredSections:J.requiredSections}),J.finalizedAt?J.finalizedAt.toISOString():null]);for(let J 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)
209
546
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
210
547
  ON CONFLICT(team_name, fragment_id) DO UPDATE SET
211
548
  outcome_id = excluded.outcome_id,
@@ -216,5 +553,90 @@ Searched ${f} files.`;let O=[`Found ${p.length} result${p.length===1?"":"s"} for
216
553
  status = excluded.status,
217
554
  reviewed_by = excluded.reviewed_by,
218
555
  reviewed_at = excluded.reviewed_at,
219
- version = team_outcome_fragments.version + 1`,[s,i.outcomeId,i.id,i.section,i.sourceAgentId,i.sourceRunId??null,i.content,i.status,i.reviewedBy??null,i.reviewedAt?i.reviewedAt.toISOString():null])}markInProgressRunsInterrupted(n,t){let e=nn(n),s=this.queryAll("SELECT run_id FROM team_runs WHERE team_name = ? AND status IN ('queued', 'running')",[e]);if(s.length===0)return[];let r=en();return this.run(`UPDATE team_runs SET status = 'interrupted', error = ?, ended_at = ?, version = version + 1
220
- WHERE team_name = ? AND status IN ('queued', 'running')`,[t,r,e]),s.map((i)=>i.run_id)}handleTeamEvent(n,t){this.appendTeamEvent(n,t.type,t)}}function y(){return new Date().toISOString()}function ee(n,t){if(t<=0)return 0;return Math.round(n/t*100)}function Lr(n,t){let e=new Set;for(let r of t)if(r.status==="reviewed")e.add(`${r.outcomeId}:${r.section}`);let s=new Set;for(let r of n){if(r.status==="finalized")continue;for(let i of r.requiredSections)if(!e.has(`${r.id}:${i}`))s.add(`${r.id}:${i}`)}return[...s].sort((r,i)=>r.localeCompare(i))}function re(n,t){let e={idle:0,running:0,stopped:0},s={pending:0,in_progress:0,blocked:0,completed:0},r={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},i={draft:0,in_review:0,finalized:0},o={draft:0,reviewed:0,rejected:0},a=0,m=0;for(let c of t.members)if(e[c.status]+=1,c.role==="lead")a+=1;else m+=1;let u=[],g=[],d=t.tasks.filter((c)=>c.status==="completed").length,p=new Map(t.tasks.map((c)=>[c.id,c]));for(let c of t.tasks){if(s[c.status]+=1,c.status==="blocked"){u.push(c.id);continue}if(c.status!=="pending")continue;if(c.dependsOn.every((N)=>{return p.get(N)?.status==="completed"}))g.push(c.id)}let f=[],C,O=0;for(let c of t.runs){if(r[c.status]+=1,c.status==="queued"||c.status==="running")f.push(c.id);let v=c.startedAt.getTime();if(v>=O)O=v,C=c.id}for(let c of t.outcomes)i[c.status]+=1;for(let c of t.outcomeFragments)o[c.status]+=1;return{teamName:n,updatedAt:y(),members:{total:t.members.length,byStatus:e,leadCount:a,teammateCount:m},tasks:{total:t.tasks.length,byStatus:s,blockedTaskIds:u,readyTaskIds:g,completionPct:ee(d,t.tasks.length)},runs:{total:t.runs.length,byStatus:r,activeRunIds:f,latestRunId:C},outcomes:{total:t.outcomes.length,byStatus:i,finalizedPct:ee(i.finalized,t.outcomes.length),missingRequiredSections:Lr(t.outcomes,t.outcomeFragments)},fragments:{total:t.outcomeFragments.length,byStatus:o}}}function se(n){let{event:t}=n;switch(t.type){case"team_task_updated":return{teamName:n.teamName,sessionId:n.sessionId,eventType:t.type,ts:y(),taskId:t.task.id,agentId:t.task.assignee??t.task.createdBy};case"run_queued":case"run_started":case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":return{teamName:n.teamName,sessionId:n.sessionId,eventType:t.type,ts:y(),runId:t.run.id,taskId:t.run.taskId,agentId:t.run.agentId,message:t.run.error};case"run_progress":return{teamName:n.teamName,sessionId:n.sessionId,eventType:t.type,ts:y(),runId:t.run.id,taskId:t.run.taskId,agentId:t.run.agentId,message:t.message};case"outcome_created":case"outcome_finalized":return{teamName:n.teamName,sessionId:n.sessionId,eventType:t.type,ts:y(),outcomeId:t.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:n.teamName,sessionId:n.sessionId,eventType:t.type,ts:y(),outcomeId:t.fragment.outcomeId,fragmentId:t.fragment.id,agentId:t.fragment.sourceAgentId};case"team_message":return{teamName:n.teamName,sessionId:n.sessionId,eventType:t.type,ts:y(),taskId:t.message.taskId,agentId:t.message.fromAgentId,message:t.message.subject};case"team_mission_log":return{teamName:n.teamName,sessionId:n.sessionId,eventType:t.type,ts:y(),taskId:t.entry.taskId,agentId:t.entry.agentId,message:t.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:n.teamName,sessionId:n.sessionId,eventType:t.type,ts:y(),agentId:t.agentId}}return{teamName:n.teamName,sessionId:n.sessionId,eventType:t.type,ts:y()}}var Sr=Mn,ie;((o)=>{o.CLI="cli";o.CLI_SUBAGENT="cli-subagent";o.CORE="core";o.CORE_SUBAGENT="core-subagent";o.DESKTOP="desktop";o.DESKTOP_CHAT="desktop-chat"})(ie||={});export{se as toTeamProgressLifecycleEvent,dt as setHomeDirIfUnset,ct as setHomeDir,gt as resolveSessionDataDir,Hn as resolveMcpServerRegistrations,st as resolveHookLogPath,Rn as resolveDefaultMcpSettingsPath,K as resolveClineDataDir,jt as registerMcpServersFromSettingsFile,nt as normalizeUserInput,xn as loadMcpSettingsFile,pt as isRpcClineAccountActionRequest,Yt as hasMcpSettingsFile,_t as executeRpcClineAccountAction,kn as ensureParentDir,Tt as ensureHookLogDir,l as emptyStoredProviderSettings,bt as createToolPoliciesWithPreset,xt as createDefaultToolsWithPreset,Z as createDefaultTools,On as createDefaultExecutors,je as createBuiltinTools,re as buildTeamProgressSummary,Kn as ToolPresets,In as StoredProviderSettingsSchema,Wt as StoredProviderSettingsEntrySchema,Qn as SqliteTeamStore,ie as SessionSource,Sr as SESSION_STATUSES,Fn as RpcClineAccountService,et as RPC_TEAM_PROGRESS_EVENT_TYPE,rt as RPC_TEAM_LIFECYCLE_EVENT_TYPE,te as ProviderSettingsManager,Vn as InMemoryMcpManager,q as DefaultToolNames,Pn as ClineAccountService,ge as ChatViewStateSchema,Ct as ChatSummarySchema,ht as ChatSessionStatusSchema,ft as ChatSessionConfigSchema,Et as ChatMessageSchema,At as ChatMessageRoleSchema,rn as ALL_DEFAULT_TOOL_NAMES};
556
+ version = team_outcome_fragments.version + 1`,[q,J.outcomeId,J.id,J.section,J.sourceAgentId,J.sourceRunId??null,J.content,J.status,J.reviewedBy??null,J.reviewedAt?J.reviewedAt.toISOString():null])}markInProgressRunsInterrupted($,Y){let T=HY($),q=this.queryAll("SELECT run_id FROM team_runs WHERE team_name = ? AND status IN ('queued', 'running')",[T]);if(q.length===0)return[];let X=O0();return this.run(`UPDATE team_runs SET status = 'interrupted', error = ?, ended_at = ?, version = version + 1
557
+ WHERE team_name = ? AND status IN ('queued', 'running')`,[Y,X,T]),q.map((J)=>J.run_id)}handleTeamEvent($,Y){this.appendTeamEvent($,Y.type,Y)}}function x1(){return new Date().toISOString()}function OU($,Y){if(Y<=0)return 0;return Math.round($/Y*100)}function YH($,Y){let T=new Set;for(let X of Y)if(X.status==="reviewed")T.add(`${X.outcomeId}:${X.section}`);let q=new Set;for(let X of $){if(X.status==="finalized")continue;for(let J of X.requiredSections)if(!T.has(`${X.id}:${J}`))q.add(`${X.id}:${J}`)}return[...q].sort((X,J)=>X.localeCompare(J))}function L8($,Y){let T={idle:0,running:0,stopped:0},q={pending:0,in_progress:0,blocked:0,completed:0},X={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},J={draft:0,in_review:0,finalized:0},Q={draft:0,reviewed:0,rejected:0},U=0,Z=0;for(let V of Y.members)if(T[V.status]+=1,V.role==="lead")U+=1;else Z+=1;let K=[],A=[],W=Y.tasks.filter((V)=>V.status==="completed").length,E=new Map(Y.tasks.map((V)=>[V.id,V]));for(let V of Y.tasks){if(q[V.status]+=1,V.status==="blocked"){K.push(V.id);continue}if(V.status!=="pending")continue;if(V.dependsOn.every((S)=>{return E.get(S)?.status==="completed"}))A.push(V.id)}let D=[],F,H=0;for(let V of Y.runs){if(X[V.status]+=1,V.status==="queued"||V.status==="running")D.push(V.id);let B=V.startedAt.getTime();if(B>=H)H=B,F=V.id}for(let V of Y.outcomes)J[V.status]+=1;for(let V of Y.outcomeFragments)Q[V.status]+=1;return{teamName:$,updatedAt:x1(),members:{total:Y.members.length,byStatus:T,leadCount:U,teammateCount:Z},tasks:{total:Y.tasks.length,byStatus:q,blockedTaskIds:K,readyTaskIds:A,completionPct:OU(W,Y.tasks.length)},runs:{total:Y.runs.length,byStatus:X,activeRunIds:D,latestRunId:F},outcomes:{total:Y.outcomes.length,byStatus:J,finalizedPct:OU(J.finalized,Y.outcomes.length),missingRequiredSections:YH(Y.outcomes,Y.outcomeFragments)},fragments:{total:Y.outcomeFragments.length,byStatus:Q}}}function w8($){let{event:Y}=$;switch(Y.type){case"team_task_updated":return{teamName:$.teamName,sessionId:$.sessionId,eventType:Y.type,ts:x1(),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:x1(),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:x1(),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:x1(),outcomeId:Y.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:$.teamName,sessionId:$.sessionId,eventType:Y.type,ts:x1(),outcomeId:Y.fragment.outcomeId,fragmentId:Y.fragment.id,agentId:Y.fragment.sourceAgentId};case"team_message":return{teamName:$.teamName,sessionId:$.sessionId,eventType:Y.type,ts:x1(),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:x1(),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:x1(),agentId:Y.agentId}}return{teamName:$.teamName,sessionId:$.sessionId,eventType:Y.type,ts:x1()}}var O4=L9,RT;((Q)=>{Q.CLI="cli";Q.CLI_SUBAGENT="cli-subagent";Q.CORE="core";Q.CORE_SUBAGENT="core-subagent";Q.DESKTOP="desktop";Q.DESKTOP_CHAT="desktop-chat"})(RT||={});import{mkdir as TH,readFile as qH,writeFile as XH}from"node:fs/promises";import{dirname as LU,join as JH}from"node:path";import{models as OT}from"@clinebot/llms";function QH($){return $.apiKey??$.auth?.apiKey}function UH($){return($.auth?.accessToken?.trim()??"").length>0}function wU($){return $.split(/[-_]/).filter(Boolean).map((Y)=>Y.charAt(0).toUpperCase()+Y.slice(1)).join(" ")}function ZH($){let Y=$.split(/\s+/).map((T)=>T.trim()).filter(Boolean);if(Y.length===0)return"?";if(Y.length===1)return Y[0].slice(0,2).toUpperCase();return`${Y[0][0]}${Y[1][0]}`.toUpperCase()}function KH($){let Y=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],T=0;for(let q of $)T=T*31+q.charCodeAt(0)>>>0;return Y[T%Y.length]}function SU($){return JH(LU($.getFilePath()),"models.json")}function AH(){return{version:1,providers:{}}}async function CU($){try{let Y=await qH($,"utf8"),T=JSON.parse(Y);if(T&&T.version===1&&T.providers&&typeof T.providers==="object")return{version:1,providers:T.providers}}catch{}return AH()}async function WH($,Y){await TH(LU($),{recursive:!0}),await XH($,`${JSON.stringify(Y,null,2)}
558
+ `,"utf8")}function GH($){if(!$||$.length===0)return;let Y=new Set;if($.includes("reasoning"))Y.add("reasoning");if($.includes("prompt-cache"))Y.add("prompt-cache");if($.includes("tools"))Y.add("tools");return Y.size>0?[...Y]:void 0}function EH($){let Y=new Set;if(!$||$.length===0)return[...Y];if($.includes("streaming"))Y.add("streaming");if($.includes("tools"))Y.add("tools");if($.includes("reasoning"))Y.add("reasoning");if($.includes("prompt-cache"))Y.add("prompt-cache");if($.includes("vision"))Y.add("images"),Y.add("files");return[...Y]}function yU($,Y){let T=EH(Y.provider.capabilities),q=Object.values(Y.models).map((Q)=>Q.id.trim()).filter((Q)=>Q.length>0),X=Y.provider.defaultModelId?.trim()||q[0]||"default",J=Object.fromEntries(q.map((Q)=>[Q,{id:Q,name:Y.models[Q]?.name??Q,capabilities:T.length>0?T:void 0,status:"active"}]));OT.registerProvider({provider:{id:$,name:Y.provider.name.trim()||wU($),protocol:"openai-chat",baseUrl:Y.provider.baseUrl,defaultModelId:X,capabilities:GH(Y.provider.capabilities)},models:J})}var PU=!1;async function VH($){if(PU)return;let Y=SU($),T=await CU(Y);for(let[q,X]of Object.entries(T.providers))yU(q,X);PU=!0}function P4($){if(Array.isArray($))return $.map((Y)=>{if(typeof Y==="string")return Y.trim();if(Y&&typeof Y==="object"&&"id"in Y){let T=Y.id;return typeof T==="string"?T.trim():""}return""}).filter((Y)=>Y.length>0);return[]}function DH($,Y){let T=P4($);if(T.length>0)return T;if(!$||typeof $!=="object")return[];let q=$,X=P4(q.data??q.models);if(X.length>0)return X;if(q.models&&typeof q.models==="object"&&!Array.isArray(q.models)){let Q=Object.keys(q.models).filter((U)=>U.trim().length>0);if(Q.length>0)return Q}let J=q.providers?.[Y];if(J&&typeof J==="object"){let U=P4(J.models??J);if(U.length>0)return U}return[]}async function FH($,Y){let T=await fetch($,{method:"GET"});if(!T.ok)throw Error(`failed to fetch models from ${$}: HTTP ${T.status}`);let q=await T.json();return DH(q,Y)}async function NH($,Y){let T=Y.providerId.trim().toLowerCase();if(!T)throw Error("providerId is required");if(OT.hasProvider(T))throw Error(`provider "${T}" already exists`);let q=Y.name.trim();if(!q)throw Error("name is required");let X=Y.baseUrl.trim();if(!X)throw Error("baseUrl is required");let J=(Y.models??[]).map((V)=>V.trim()).filter((V)=>V.length>0),Q=Y.modelsSourceUrl?.trim(),U=Q?await FH(Q,T):[],Z=[...new Set([...J,...U])];if(Z.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let K=Y.defaultModelId?.trim()&&Z.includes(Y.defaultModelId.trim())?Y.defaultModelId.trim():Z[0],A=Y.capabilities?.length?[...new Set(Y.capabilities)]:void 0,W=Object.entries(Y.headers??{}).filter(([V])=>V.trim().length>0);$.saveProviderSettings({provider:T,apiKey:Y.apiKey?.trim()?Y.apiKey:void 0,baseUrl:X,headers:W.length>0?Object.fromEntries(W):void 0,timeout:Y.timeoutMs,model:K},{setLastUsed:!1});let E=SU($),D=await CU(E),F=A?.includes("vision")??!1,H=F;return D.providers[T]={provider:{name:q,baseUrl:X,defaultModelId:K,capabilities:A,modelsSourceUrl:Q},models:Object.fromEntries(Z.map((V)=>[V,{id:V,name:V,supportsVision:F,supportsAttachments:H}]))},await WH(E,D),yU(T,D.providers[T]),{providerId:T,settingsPath:$.getFilePath(),modelsPath:E,modelsCount:Z.length}}async function HH($){let Y=$.read(),T=OT.getProviderIds().sort((X,J)=>X.localeCompare(J));return{providers:await Promise.all(T.map(async(X)=>{let J=await OT.getProvider(X),Q=Y.providers[X]?.settings,U=J?.name??wU(X);return{id:X,name:U,models:null,color:KH(X),letter:ZH(U),enabled:Boolean(Q),apiKey:Q?QH(Q):void 0,oauthAccessTokenPresent:Q?UH(Q):void 0,baseUrl:Q?.baseUrl??J?.baseUrl,defaultModelId:J?.defaultModelId,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests."}})),settingsPath:$.getFilePath()}}async function zH($){let Y=$.trim(),T=await OT.getModelsForProvider(Y),q=Object.entries(T).sort(([X],[J])=>X.localeCompare(J)).map(([X,J])=>({id:X,name:J.name??X,supportsAttachments:J.capabilities?.includes("files"),supportsVision:J.capabilities?.includes("images")}));return{providerId:Y,models:q}}function IH($,Y){let T=Y.providerId.trim(),q=$.read();if(Y.enabled===!1){if(delete q.providers[T],q.lastUsedProvider===T)delete q.lastUsedProvider;return $.write(q),{providerId:T,enabled:!1,settingsPath:$.getFilePath()}}let J={...$.getProviderSettings(T)??{},provider:T};if(Object.hasOwn(Y,"apiKey")&&typeof Y.apiKey==="string")if((Y.apiKey?.trim()??"").length===0)delete J.apiKey;else J.apiKey=Y.apiKey;if(Object.hasOwn(Y,"baseUrl")&&typeof Y.baseUrl==="string")if((Y.baseUrl?.trim()??"").length===0)delete J.baseUrl;else J.baseUrl=Y.baseUrl;return $.saveProviderSettings(J,{setLastUsed:!1}),{providerId:T,enabled:!0,settingsPath:$.getFilePath()}}function MH($){let Y=$.trim().toLowerCase();if(Y==="codex"||Y==="openai-codex")return"openai-codex";if(Y==="cline"||Y==="oca")return Y;throw Error(`provider "${$}" does not support OAuth login (supported: cline, oca, openai-codex)`)}function BH($,Y){if($==="cline")return`workos:${Y.access}`;return Y.access}async function RH($,Y,T){let q=X4({onPrompt:async(X)=>X.defaultValue??"",openUrl:T,onOpenUrlError:({error:X})=>{throw X instanceof Error?X:Error(String(X))}});if($==="cline")return H8({apiBaseUrl:Y?.baseUrl?.trim()||"https://api.cline.bot",callbacks:q});if($==="oca")return B8({mode:Y?.oca?.mode,callbacks:q});return I8(q)}function OH($,Y,T,q){let X={...T?.auth??{},accessToken:BH(Y,q),refreshToken:q.refresh,accountId:q.accountId};X.expiresAt=q.expires;let J={...T??{provider:Y},provider:Y,auth:X};return $.saveProviderSettings(J,{tokenSource:"oauth"}),J}function PH($){let Y=$?.auth?.accessToken?.trim()||$?.apiKey?.trim();return Y&&Y.length>0?Y:void 0}function jU($){return $.disabled!==!0}function vU($){if($.length===0)return"";return`
559
+
560
+ # Rules
561
+ ${$.map((T)=>`## ${T.name}
562
+ ${T.instructions}`).join(`
563
+
564
+ `)}`}function xU($){return[...$.getSnapshot("rule").values()].map((T)=>T.item).filter(jU).sort((T,q)=>T.name.localeCompare(q.name))}function LH($){return vU(xU($))}import{existsSync as L4,readdirSync as wH}from"node:fs";import{join as kU}from"node:path";import{AgentTeamsRuntime as SH,bootstrapAgentTeams as CH}from"@clinebot/agents";import{nanoid as yH}from"nanoid";var jH="# Workspace Configuration";function mU(){return`agent-team-${yH(5)}`}function hU($,Y,T,q,X,J,Q){let U=T==="plan"?t1.readonly:t1.development,Z=h9(Y,q,T,X??k9);return NT({cwd:$,...U,...Z,enableSkills:!!J,executors:{...J?{skills:J}:{},...Q??{}}})}var _U="SKILL.md";function vH($){return w4($).filter((Y)=>!Y.disabled).map((Y)=>Y.name.trim()).filter((Y)=>Y.length>0).sort((Y,T)=>Y.localeCompare(T))}function w4($){return[...$.getSnapshot("skill").entries()].map(([T,q])=>{let X=q.item;return{id:T,name:X.name.trim(),description:X.description?.trim(),disabled:X.disabled===!0}})}function gU($){for(let Y of DT($)){if(!L4(Y))continue;let T=kU(Y,_U);if(L4(T))return!0;try{let q=wH(Y,{withFileTypes:!0});for(let X of q){if(!X.isDirectory())continue;if(L4(kU(Y,X.name,_U)))return!0}}catch{}}return!1}function xH($,Y){let T=Y.trim().replace(/^\/+/,"").toLowerCase();if(!T)return{error:"Missing skill name."};let q=$.getSnapshot("skill"),X=q.get(T);if(X){let Z=X.item;if(Z.disabled===!0)return{error:`Skill "${Z.name}" is configured but disabled.`};return{id:T,skill:Z}}let J=T.includes(":")?T.split(":").at(-1)??T:T,Q=[...q.entries()].filter(([Z])=>{if(Z===J)return!0;return Z.endsWith(`:${J}`)});if(Q.length===1){let[Z,K]=Q[0],A=K.item;if(A.disabled===!0)return{error:`Skill "${A.name}" is configured but disabled.`};return{id:Z,skill:A}}if(Q.length>1)return{error:`Skill "${Y}" is ambiguous. Use one of: ${Q.map(([Z])=>Z).join(", ")}`};let U=vH($);return{error:U.length>0?`Skill "${Y}" not found. Available skills: ${U.join(", ")}`:"No skills are currently available."}}function kH($,Y){let T=new Set,q=async(X,J)=>{await Y;let Q=xH($,X);if("error"in Q)return Q.error;let{id:U,skill:Z}=Q;if(T.has(U))return`Skill "${Z.name}" is already running.`;T.add(U);try{let K=J?.trim(),A=K?`
565
+ <command-args>${K}</command-args>`:"",W=Z.description?.trim()?`Description: ${Z.description.trim()}
566
+
567
+ `:"";return`<command-name>${Z.name}</command-name>${A}
568
+ <command-instructions>
569
+ ${W}${Z.instructions}
570
+ </command-instructions>`}finally{T.delete(U)}};return Object.defineProperty(q,"configuredSkills",{get:()=>w4($),enumerable:!0,configurable:!1}),q}function hH($,Y){if(!$)return;for(let T of $.getTeammateIds())try{$.shutdownTeammate(T,Y)}catch{}}function _H($){let Y=$.lastIndexOf(jH);if(Y<0)return;let T=$.slice(Y).trim();return T.length>0?T:void 0}function gH($){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 S8{build($){let{config:Y,hooks:T,extensions:q,logger:X,createSpawnTool:J,onTeamRestored:Q,userInstructionWatcher:U,defaultToolExecutors:Z}=$,K=$.onTeamEvent??(()=>{}),A=gH(Y),W=[],E=Y.teamName?.trim()||mU(),D=!1,F=Boolean(U),H=U,V=Promise.resolve(),B;if(!H&&A.enableTools&&gU(Y.cwd))H=E8({skills:{workspacePath:Y.cwd},rules:{workspacePath:Y.cwd},workflows:{workspacePath:Y.cwd}}),V=H.start().catch(()=>{});if(A.enableTools&&H&&(F||gU(Y.cwd)||w4(H).length>0))B=kH(H,V);if(A.enableTools)W.push(...hU(Y.cwd,Y.providerId,A.mode,Y.modelId,Y.toolRoutingRules,B,Z));let S,v=A.enableAgentTeams?new BT:void 0;v?.init();let z=v?.loadRuntime(E),_=z?.state,y=z?.teammates??[],k=new Map(y.map((j)=>[j.agentId,j])),m=()=>{if(!A.enableAgentTeams)return;if(!S){if(S=new SH({teamName:E,leadAgentId:"lead",missionLogIntervalSteps:A.missionLogIntervalSteps,missionLogIntervalMs:A.missionLogIntervalMs,onTeamEvent:(j)=>{if(K(j),S&&v){if(j.type==="teammate_spawned"&&j.teammate?.rolePrompt){let I={agentId:j.agentId,rolePrompt:j.teammate.rolePrompt,modelId:j.teammate.modelId,maxIterations:j.teammate.maxIterations};k.set(I.agentId,I)}if(j.type==="teammate_shutdown")k.delete(j.agentId);v.handleTeamEvent(E,j),v.persistRuntime(E,S.exportState(),Array.from(k.values()))}}}),_)S.hydrateState(_),S.markStaleRunsInterrupted("runtime_recovered")}if(!D){if(!S)return;D=!0;let j=CH({runtime:S,leadAgentId:"lead",restoredFromPersistence:Boolean(_),restoredTeammates:y,createBaseTools:A.enableTools?()=>hU(Y.cwd,Y.providerId,A.mode,Y.modelId,Y.toolRoutingRules,B,Z):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"?_H(Y.systemPrompt):void 0,maxIterations:Y.maxIterations,hooks:T,extensions:q??Y.extensions,logger:X??Y.logger}});if(j.restoredFromPersistence)Q?.();W.push(...j.tools)}return S};if(A.enableSpawnAgent&&J){let j=J();W.push({...j,execute:async(I,h0)=>{return m(),j.execute(I,h0)}})}if(A.enableAgentTeams)m();let C=S?()=>{let j=S;if(!j)return;let I=j.listTasks(),h0=I.some((L)=>L.status==="in_progress"||L.status==="pending"),P=j.listRuns({}),G=P.some((L)=>L.status==="running"||L.status==="queued");if(h0||G){let L=I.filter((d)=>d.status==="in_progress"||d.status==="pending").map((d)=>`${d.id} (${d.status}): ${d.title}`).join(", "),l=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(l)u.push(`Active runs: ${l}`);return`[SYSTEM] You still have team obligations. ${u.join(". ")}. Use team_run_task to delegate work, or team_complete_task to mark tasks done, or team_await_run / team_await_all_runs to wait for active runs. Do NOT stop until all tasks are completed.`}return}:void 0;return{tools:W,logger:X??Y.logger,teamRuntime:S,completionGuard:C,shutdown:(j)=>{if(hH(S,j),!F)H?.stop()}}}}import{mkdir as mH,readFile as fH,unlink as S4,writeFile as bH}from"node:fs/promises";import{join as fU}from"node:path";function uH($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function dH($){return new Promise((Y)=>setTimeout(Y,$))}async function cH($,Y={}){let T=Y.approvalDir?.trim(),q=Y.sessionId?.trim();if(!T||!q)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await mH(T,{recursive:!0});let X=uH(`${$.toolCallId}`),J=fU(T,`${q}.request.${X}.json`),Q=fU(T,`${q}.decision.${X}.json`),U=Y.nowIso??(()=>new Date().toISOString());await bH(J,`${JSON.stringify({requestId:X,sessionId:q,createdAt:U(),toolCallId:$.toolCallId,toolName:$.toolName,input:$.input,iteration:$.iteration,agentId:$.agentId,conversationId:$.conversationId},null,2)}
571
+ `,"utf8");let Z=Y.timeoutMs??300000,K=Y.pollIntervalMs??200,A=Date.now();while(Date.now()-A<Z){try{let W=await fH(Q,"utf8"),E=JSON.parse(W),D={approved:E.approved===!0,reason:typeof E.reason==="string"?E.reason:void 0};try{await S4(Q)}catch{}try{await S4(J)}catch{}return D}catch{}await dH(K)}try{await S4(J)}catch{}return{approved:!1,reason:"Tool approval request timed out"}}function pH($){return $.disabled!==!0}function bU($){return[...$.getSnapshot("workflow").entries()].map(([T,q])=>({id:T,workflow:q.item})).filter(({workflow:T})=>pH(T)).map(({id:T,workflow:q})=>({id:T,name:q.name,instructions:q.instructions})).sort((T,q)=>T.name.localeCompare(q.name))}function lH($,Y){if(!$.startsWith("/")||$.length<2)return $;let T=$.match(/^\/(\S+)/);if(!T)return $;let q=T[1];if(!q)return $;let X=q.length+1,J=$.slice(X),Q=bU(Y).find((U)=>U.name===q);return Q?`${Q.instructions}${J}`:$}import{existsSync as _4,readFileSync as g4}from"node:fs";import{readFile as Nz,stat as Hz}from"node:fs/promises";import{homedir as zz}from"node:os";import{isAbsolute as Iz,join as PT,resolve as Mz}from"node:path";import{Agent as Bz,createSpawnAgentTool as Rz}from"@clinebot/agents";import{nanoid as Oz}from"nanoid";import{spawn as nH}from"node:child_process";import{appendFileSync as iH,readFileSync as rH}from"node:fs";function y8($){if(!$||typeof $!=="object")return{};let Y={};for(let[T,q]of Object.entries($))Y[T]=typeof q==="string"?q:JSON.stringify(q);return Y}function C8($,Y,T){let q=T instanceof Error?`: ${T.message}`:"",X=`${Y}${q}`;if($?.warn){$.warn(X);return}console.warn(X)}function uU($,Y){if(!Y)return $;if(!$)return{...Y};let T=[$.context,Y.context].filter((X)=>typeof X==="string"&&X.length>0).join(`
572
+ `),q=[...$.appendMessages??[],...Y.appendMessages??[]];return{cancel:$.cancel===!0||Y.cancel===!0?!0:void 0,review:$.review===!0||Y.review===!0?!0:void 0,context:T||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 aH($){if(!$||typeof $!=="object")return;let Y=$,T=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:T,overrideInput:Object.hasOwn(Y,"overrideInput")?Y.overrideInput:void 0}}function dU($){let Y=String($??"").toLowerCase();return Y.includes("cancel")||Y.includes("abort")||Y.includes("interrupt")}function oH($){FT($)}function n0($,Y){let T=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:T,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function sH($){let Y=$.trim();if(!Y)return{};let q=Y.split(`
573
+ `).map((J)=>J.trim()).filter(Boolean).filter((J)=>J.startsWith("HOOK_CONTROL\t")).map((J)=>J.slice(13)),X=q.length>0?q[q.length-1]:Y;try{return{parsedJson:JSON.parse(X)}}catch(J){return{parseError:J instanceof Error?J.message:"Failed to parse hook stdout JSON"}}}async function cU($,Y){if(Y.command.length===0)throw Error("runHookCommand requires non-empty command");let T=nH(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(!T.stdin)throw Error("hook command failed to create stdin");if(T.stdin.write(q),T.stdin.end(),Y.detached){await new Promise((Z,K)=>{T.once("error",K),T.once("spawn",()=>Z())}),T.unref();return}if(!T.stdout||!T.stderr)throw Error("hook command failed to create stdout/stderr");let X="",J="",Q=!1,U;return T.stdout.on("data",(Z)=>{X+=Z.toString()}),T.stderr.on("data",(Z)=>{J+=Z.toString()}),await new Promise((Z,K)=>{if(T.once("error",K),(Y.timeoutMs??0)>0)U=setTimeout(()=>{Q=!0,T.kill("SIGKILL")},Y.timeoutMs);T.once("close",(A)=>{if(U)clearTimeout(U);let{parsedJson:W,parseError:E}=sH(X);Z({exitCode:A,stdout:X,stderr:J,parsedJson:W,parseError:E,timedOut:Q})})})}function tH($){try{let T=rH($,"utf8").split(/\r?\n/,1)[0]?.trim();if(!T?.startsWith("#!"))return;let q=T.slice(2).trim();if(!q)return;let X=q.split(/\s+/).filter(Boolean);return X.length>0?X:void 0}catch{return}}function eH($){let Y=tH($);if(Y&&Y.length>0)return[...Y,$];let T=$.toLowerCase();if(T.endsWith(".sh")||T.endsWith(".bash")||T.endsWith(".zsh"))return["/bin/bash",$];if(T.endsWith(".js")||T.endsWith(".mjs")||T.endsWith(".cjs"))return["node",$];if(T.endsWith(".ts")||T.endsWith(".mts")||T.endsWith(".cts"))return["bun","run",$];return["/bin/bash",$]}function $z($){let Y={};for(let T of q8($)){if(!T.hookEventName)continue;let q=Y[T.hookEventName]??[];q.push(eH(T.path)),Y[T.hookEventName]=q}return Y}async function Yz($){let Y;for(let T of $.commands){let q=T.join(" ");try{let X=await cU($.payload,{command:T,cwd:$.cwd,env:process.env,detached:!1,timeoutMs:$.timeoutMs});if(X?.timedOut){C8($.logger,`hook command timed out: ${q}`);continue}if(X?.parseError){C8($.logger,`hook command returned invalid JSON control output: ${q} (${X.parseError})`);continue}Y=uU(Y,aH(X?.parsedJson))}catch(X){C8($.logger,`hook command failed: ${q}`,X)}}return Y}function zY($){for(let Y of $.commands){let T=Y.join(" ");cU($.payload,{command:Y,cwd:$.cwd,env:process.env,detached:!0}).catch((q)=>{C8($.logger,`hook command failed: ${T}`,q)})}}function pU($){let Y={cwd:$.workspacePath,workspacePath:$.workspacePath,hookLogPath:$.hookLogPath,rootSessionId:$.rootSessionId},T=(q)=>{let X=`${JSON.stringify({ts:new Date().toISOString(),...q})}
574
+ `;oH($.hookLogPath),iH($.hookLogPath,X,"utf8")};return{onRunStart:async(q)=>{T({...n0(q,Y),hookName:"agent_start",taskStart:{taskMetadata:{}}}),T({...n0(q,Y),hookName:"prompt_submit",userPromptSubmit:{prompt:q.userMessage,attachments:[]}});return},onToolCallStart:async(q)=>{T({...n0(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:y8(q.call.input)}});return},onToolCallEnd:async(q)=>{T({...n0(q,Y),hookName:"tool_result",iteration:q.iteration,tool_result:q.record,postToolUse:{toolName:q.record.name,parameters:y8(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)=>{T({...n0(q,Y),hookName:"agent_end",iteration:q.iteration,turn:q.turn,taskComplete:{taskMetadata:{}}});return},onSessionShutdown:async(q)=>{if(dU(q.reason))T({...n0(q,Y),hookName:"agent_abort",reason:q.reason,taskCancel:{taskMetadata:{}}});T({...n0(q,Y),hookName:"session_shutdown",reason:q.reason});return}}}function lU($){let Y=$z($.workspacePath);if(!Object.values(Y).some((Z)=>(Z?.length??0)>0))return;let q=async(Z)=>{let K=Y.agent_start??[];if(K.length>0)zY({commands:K,cwd:$.cwd,logger:$.logger,payload:{...n0(Z,$),hookName:"agent_start",taskStart:{taskMetadata:{}}}});let A=Y.prompt_submit??[];if(A.length>0)zY({commands:A,cwd:$.cwd,logger:$.logger,payload:{...n0(Z,$),hookName:"prompt_submit",userPromptSubmit:{prompt:Z.userMessage,attachments:[]}}})},X=async(Z)=>{let K=Y.tool_call??[];if(K.length===0)return;return Yz({commands:K,cwd:$.cwd,logger:$.logger,timeoutMs:$.toolCallTimeoutMs??120000,payload:{...n0(Z,$),hookName:"tool_call",iteration:Z.iteration,tool_call:{id:Z.call.id,name:Z.call.name,input:Z.call.input},preToolUse:{toolName:Z.call.name,parameters:y8(Z.call.input)}}})},J=async(Z)=>{let K=Y.tool_result??[];if(K.length===0)return;zY({commands:K,cwd:$.cwd,logger:$.logger,payload:{...n0(Z,$),hookName:"tool_result",iteration:Z.iteration,tool_result:Z.record,postToolUse:{toolName:Z.record.name,parameters:y8(Z.record.input),result:typeof Z.record.output==="string"?Z.record.output:JSON.stringify(Z.record.output),success:!Z.record.error,executionTimeMs:Z.record.durationMs}}})},Q=async(Z)=>{let K=Y.agent_end??[];if(K.length===0)return;zY({commands:K,cwd:$.cwd,logger:$.logger,payload:{...n0(Z,$),hookName:"agent_end",iteration:Z.iteration,turn:Z.turn,taskComplete:{taskMetadata:{}}}})},U=async(Z)=>{if(dU(Z.reason)){let A=Y.agent_abort??[];if(A.length>0)zY({commands:A,cwd:$.cwd,logger:$.logger,payload:{...n0(Z,$),hookName:"agent_abort",reason:Z.reason,taskCancel:{taskMetadata:{}}}})}let K=Y.session_shutdown??[];if(K.length===0)return;zY({commands:K,cwd:$.cwd,logger:$.logger,payload:{...n0(Z,$),hookName:"session_shutdown",reason:Z.reason}})};return{onRunStart:async(Z)=>{await q(Z);return},onToolCallStart:async(Z)=>X(Z),onToolCallEnd:async(Z)=>{await J(Z);return},onTurnEnd:async(Z)=>{await Q(Z);return},onSessionShutdown:async(Z)=>{await U(Z);return}}}function k1($,Y){let T=$.map((q)=>q[Y]).filter((q)=>typeof q==="function");if(T.length===0)return;return async(q)=>{let X;for(let J of T){let Q=await J(q);X=uU(X,Q)}return X}}function nU($){let Y=$.filter((T)=>T!==void 0);if(Y.length===0)return;return{onRunStart:k1(Y,"onRunStart"),onRunEnd:k1(Y,"onRunEnd"),onIterationStart:k1(Y,"onIterationStart"),onIterationEnd:k1(Y,"onIterationEnd"),onTurnStart:k1(Y,"onTurnStart"),onTurnEnd:k1(Y,"onTurnEnd"),onToolCallStart:k1(Y,"onToolCallStart"),onToolCallEnd:k1(Y,"onToolCallEnd"),onSessionShutdown:k1(Y,"onSessionShutdown"),onError:k1(Y,"onError")}}var Tz="https://api.cline.bot",C4="workos:",qz=["cline","oca","openai-codex"];function Xz($){return qz.includes($)}function Jz($,Y){if($==="cline")return`${C4}${Y}`;return Y}function Qz($,Y){if($==="cline"&&Y.toLowerCase().startsWith(C4))return Y.slice(C4.length);return Y}function Uz($){let T=W1($)?.exp;if(typeof T==="number"&&T>0)return T*1000;return null}function Zz($,Y){let T=$.auth?.expiresAt;if(typeof T==="number"&&Number.isFinite(T)&&T>0)return T;let q=Uz(Y);if(q)return q;return Date.now()-1}function Kz($,Y){let T=Y.auth?.accessToken?.trim(),q=Y.auth?.refreshToken?.trim();if(!T||!q)return null;let X=Qz($,T);if(!X)return null;return{access:X,refresh:q,expires:Zz(Y,X),accountId:Y.auth?.accountId}}function Az($,Y){let T=$?.expiresAt,q=Y?.expiresAt;return $?.accessToken===Y?.accessToken&&$?.refreshToken===Y?.refreshToken&&$?.accountId===Y?.accountId&&T===q}class j8 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 y4{providerSettingsManager;refreshInFlight=new Map;constructor($){this.providerSettingsManager=$?.providerSettingsManager??new d$}async resolveProviderApiKey($){if(!Xz($.providerId))return null;return this.resolveWithSingleFlight($.providerId,$.forceRefresh)}async resolveWithSingleFlight($,Y=!1){let T=this.refreshInFlight.get($);if(T)return T;let q=this.resolveProviderApiKeyInternal($,Y).catch((X)=>{throw X}).finally(()=>{this.refreshInFlight.delete($)});return this.refreshInFlight.set($,q),q}async resolveProviderApiKeyInternal($,Y){let T=this.providerSettingsManager.getProviderSettings($);if(!T)return null;let q=Kz($,T);if(!q)return null;let X=await this.resolveCredentials($,T,q,Y);if(!X)throw new j8($);let J=Jz($,X.access),Q={...T.auth??{},accessToken:J,refreshToken:X.refresh,accountId:X.accountId};Q.expiresAt=X.expires;let U={...T,auth:Q},Z=!Az(T.auth,U.auth);if(Z)this.providerSettingsManager.saveProviderSettings(U,{setLastUsed:!1,tokenSource:"oauth"});return{providerId:$,apiKey:J,accountId:X.accountId,refreshed:Z}}async resolveCredentials($,Y,T,q){if($==="cline")return K4(T,{apiBaseUrl:Y.baseUrl?.trim()||Tz},{forceRefresh:q});if($==="oca")return V4(T,{forceRefresh:q},{mode:Y.oca?.mode});return W4(T,{forceRefresh:q})}}import{existsSync as j4,mkdirSync as Wz,readdirSync as Gz,rmdirSync as Ez,unlinkSync as Vz}from"node:fs";import{dirname as iU,join as H$}from"node:path";function W0(){return new Date().toISOString()}function $$($){if(!$||!j4($))return;try{Vz($)}catch{}}class v4{ensureSessionsDir;constructor($){this.ensureSessionsDir=$}sessionArtifactsDir($){return H$(this.ensureSessionsDir(),$)}ensureSessionArtifactsDir($){let Y=this.sessionArtifactsDir($);if(!j4(Y))Wz(Y,{recursive:!0});return Y}sessionTranscriptPath($){return H$(this.ensureSessionArtifactsDir($),`${$}.log`)}sessionHookPath($){return H$(this.ensureSessionArtifactsDir($),`${$}.hooks.jsonl`)}sessionMessagesPath($){return H$(this.ensureSessionArtifactsDir($),`${$}.messages.json`)}sessionManifestPath($,Y=!0){let T=Y?this.ensureSessionArtifactsDir($):this.sessionArtifactsDir($);return H$(T,`${$}.json`)}removeSessionDirIfEmpty($){let Y=this.sessionArtifactsDir($),T=this.ensureSessionsDir();while(Y.startsWith(T)&&Y!==T){if(!j4(Y)){Y=iU(Y);continue}try{if(Gz(Y).length>0)break;Ez(Y)}catch{break}Y=iU(Y)}}subagentArtifactPaths($,Y,T){let q=this.ensureSessionArtifactsDir($);return{transcriptPath:H$(q,`${$}.log`),hookPath:H$(q,`${$}.hooks.jsonl`),messagesPath:H$(q,`${$}.messages.json`)}}}import{z as G0}from"zod";var Dz=G0.enum(O4),IY=G0.object({version:G0.literal(1),session_id:G0.string().min(1),source:G0.enum(RT),pid:G0.number().int(),started_at:G0.string().min(1),ended_at:G0.string().min(1).optional(),exit_code:G0.number().int().nullable().optional(),status:Dz,interactive:G0.boolean(),provider:G0.string().min(1),model:G0.string().min(1),cwd:G0.string().min(1),workspace_root:G0.string().min(1),team_name:G0.string().min(1).optional(),enable_tools:G0.boolean(),enable_spawn:G0.boolean(),enable_teams:G0.boolean(),prompt:G0.string().optional(),metadata:G0.record(G0.string(),G0.unknown()).optional(),messages_path:G0.string().min(1).optional()});var Fz="# Workspace Configuration";function rU($){let Y=$.lastIndexOf(Fz);if(Y<0)return;let T=$.slice(Y).trim();return T.length>0?T:void 0}function aU($){if(!$)return!1;return Object.values($).some((Y)=>typeof Y==="function")}function oU($,Y){let T=[...$??[],...Y??[]];if(T.length===0)return;let q=[],X=new Set;for(let J of T){if(X.has(J.name))continue;X.add(J.name),q.push(J)}return q}function sU($){return JSON.stringify($,(Y,T)=>{if(T instanceof Error)return{name:T.name,message:T.message,stack:T.stack};return T})}function tU($,Y){let T=$.map((U)=>({...U})),q=[...T].reverse().findIndex((U)=>U.role==="assistant");if(q===-1)return T;let X=T.length-1-q,J=T[X],Q=Y.usage;return T[X]={...J,providerId:J.providerId??Y.model.provider,modelId:J.modelId??Y.model.id,modelInfo:J.modelInfo??{id:Y.model.id,provider:Y.model.provider},metrics:{...J.metrics??{},inputTokens:Q.inputTokens,outputTokens:Q.outputTokens,cacheReadTokens:Q.cacheReadTokens,cacheWriteTokens:Q.cacheWriteTokens,cost:Q.totalCost},ts:J.ts??Y.endedAt.getTime()},T}function x4($){let Y=typeof $.metadata_json==="string"&&$.metadata_json.trim().length>0?(()=>{try{let T=JSON.parse($.metadata_json);if(T&&typeof T==="object"&&!Array.isArray(T))return T}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??W0()}}function k4(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function h4($,Y){return{inputTokens:$.inputTokens+Math.max(0,Y.inputTokens??0),outputTokens:$.outputTokens+Math.max(0,Y.outputTokens??0),cacheReadTokens:$.cacheReadTokens+Math.max(0,Y.cacheReadTokens??0),cacheWriteTokens:$.cacheWriteTokens+Math.max(0,Y.cacheWriteTokens??0),totalCost:$.totalCost+Math.max(0,Y.totalCost??0)}}var eU=5000,Pz=20480000;async function Lz($){let Y=await Hz($);if(!Y.isFile())throw Error("Path is not a file");if(Y.size>Pz)throw Error("File is too large to read into context.");let T=await Nz($,"utf8");if(T.includes("\x00"))throw Error("Cannot read binary file into context.");return T}class v8{sessionService;runtimeBuilder;createAgentInstance;defaultToolExecutors;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultRequestToolApproval;listeners=new Set;sessions=new Map;usageBySession=new Map;constructor($){let Y=zz();if(Y)S6(Y);this.sessionService=$.sessionService,this.runtimeBuilder=$.runtimeBuilder??new S8,this.createAgentInstance=$.createAgent??((T)=>new Bz(T)),this.defaultToolExecutors=$.defaultToolExecutors,this.defaultToolPolicies=$.toolPolicies,this.providerSettingsManager=$.providerSettingsManager??new d$,this.oauthTokenManager=$.oauthTokenManager??new y4({providerSettingsManager:this.providerSettingsManager}),this.defaultRequestToolApproval=$.requestToolApproval}resolveStoredProviderSettings($){let Y=this.providerSettingsManager.getProviderSettings($);if(Y)return Y;return{provider:$}}buildResolvedProviderConfig($){let Y=this.resolveStoredProviderSettings($.providerId),T={...Y,provider:$.providerId,model:$.modelId,apiKey:$.apiKey??Y.apiKey,baseUrl:$.baseUrl??Y.baseUrl,headers:$.headers??Y.headers,reasoning:typeof $.thinking==="boolean"||typeof $.reasoningEffort==="string"?{...Y.reasoning??{},...typeof $.thinking==="boolean"?{enabled:$.thinking}:{},...typeof $.reasoningEffort==="string"?{effort:$.reasoningEffort}:{}}:Y.reasoning},q=MT(T);if($.knownModels)q.knownModels=$.knownModels;return q}async start($){let Y=$.source??"cli",T=W0(),q=$.config.sessionId?.trim()??"",X=q.length>0?q:`${Date.now()}_${Oz(5)}`;this.usageBySession.set(X,k4());let J=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!J)throw Error("session service method not available: ensureSessionsDir");let Q=PT(J,X),U=PT(Q,`${X}.log`),Z=PT(Q,`${X}.hooks.jsonl`),K=PT(Q,`${X}.messages.json`),A=PT(Q,`${X}.json`),W=IY.parse({version:1,session_id:X,source:Y,pid:process.pid,started_at:T,status:"running",interactive:$.interactive===!0,provider:$.config.providerId,model:$.config.modelId,cwd:$.config.cwd,workspace_root:$.config.workspaceRoot??$.config.cwd,team_name:$.config.teamName,enable_tools:$.config.enableTools,enable_spawn:$.config.enableSpawnAgent,enable_teams:$.config.enableAgentTeams,prompt:$.prompt?.trim()||void 0,messages_path:K}),E=lU({cwd:$.config.cwd,workspacePath:$.config.workspaceRoot??$.config.cwd,rootSessionId:X,hookLogPath:Z,logger:$.config.logger}),D=aU($.config.hooks)?void 0:pU({hookLogPath:Z,rootSessionId:X,workspacePath:$.config.workspaceRoot??$.config.cwd}),F=nU([$.config.hooks,E,D]),H=await U8({pluginPaths:$.config.pluginPaths,workspacePath:$.config.workspaceRoot??$.config.cwd,cwd:$.config.cwd}),V=oU($.config.extensions,H.extensions),B={...$.config,hooks:F,extensions:V},S=this.buildResolvedProviderConfig(B),v={...B,providerConfig:S},z=this.runtimeBuilder.build({config:v,hooks:F,extensions:V,logger:v.logger,onTeamEvent:(C)=>{this.handleTeamEvent(X,C),v.onTeamEvent?.(C)},createSpawnTool:()=>this.createSpawnTool(v,X),onTeamRestored:$.onTeamRestored,userInstructionWatcher:$.userInstructionWatcher,defaultToolExecutors:$.defaultToolExecutors??this.defaultToolExecutors}),_=[...z.tools,...v.extraTools??[]],y=this.createAgentInstance({providerId:S.providerId,modelId:S.modelId,apiKey:S.apiKey,baseUrl:S.baseUrl,headers:S.headers,knownModels:S.knownModels,providerConfig:S,thinking:v.thinking,reasoningEffort:v.reasoningEffort??S.reasoningEffort,systemPrompt:v.systemPrompt,maxIterations:v.maxIterations,maxConsecutiveMistakes:v.maxConsecutiveMistakes,tools:_,hooks:F,extensions:V,hookErrorMode:v.hookErrorMode,initialMessages:$.initialMessages,userFileContentLoader:Lz,toolPolicies:$.toolPolicies??this.defaultToolPolicies,requestToolApproval:$.requestToolApproval??this.defaultRequestToolApproval,onConsecutiveMistakeLimitReached:v.onConsecutiveMistakeLimitReached,completionGuard:z.completionGuard,logger:z.logger??v.logger,onEvent:(C)=>{let j=this.sessions.get(X);if(C.type==="usage"&&j?.turnUsageBaseline)this.usageBySession.set(X,h4(j.turnUsageBaseline,{inputTokens:C.totalInputTokens,outputTokens:C.totalOutputTokens,totalCost:C.totalCost}));this.emit({type:"agent_event",payload:{sessionId:X,event:C}}),this.emit({type:"chunk",payload:{sessionId:X,stream:"agent",chunk:sU(C),ts:Date.now()}})}}),k={sessionId:X,config:v,source:Y,startedAt:T,pendingPrompt:W.prompt,runtime:z,agent:y,started:!1,aborting:!1,interactive:$.interactive===!0,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pluginSandboxShutdown:H.shutdown};this.sessions.set(k.sessionId,k),this.emitStatus(k.sessionId,"running");let m;try{if($.prompt?.trim()){if(m=await this.runTurn(k,{prompt:$.prompt,userImages:$.userImages,userFiles:$.userFiles}),!k.interactive)await this.finalizeSingleRun(k,m.finishReason)}}catch(C){throw await this.failSession(k),C}return{sessionId:X,manifest:W,manifestPath:A,transcriptPath:U,hookPath:Z,messagesPath:K,result:m}}async send($){let Y=this.sessions.get($.sessionId);if(!Y)throw Error(`session not found: ${$.sessionId}`);try{let T=await this.runTurn(Y,{prompt:$.prompt,userImages:$.userImages,userFiles:$.userFiles});if(!Y.interactive)await this.finalizeSingleRun(Y,T.finishReason);return T}catch(T){throw await this.failSession(Y),T}}async getAccumulatedUsage($){let Y=this.usageBySession.get($);if(!Y)return;return{...Y}}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(T)=>{await this.shutdownSession(T,{status:"cancelled",exitCode:null,shutdownReason:$,endReason:"disposed"})})),this.usageBySession.clear()}async get($){let Y=await this.getRow($);return Y?x4(Y):void 0}async list($=200){return(await this.listRows($)).map((T)=>x4(T))}async delete($){if(this.sessions.has($))await this.stop($);let Y=await this.invoke("deleteSession",$);if(Y.deleted)this.usageBySession.delete($);return Y.deleted}async readTranscript($,Y){let T=await this.getRow($);if(!T?.transcript_path||!_4(T.transcript_path))return"";let q=g4(T.transcript_path,"utf8");if(typeof Y==="number"&&Number.isFinite(Y))return q.slice(-Math.max(0,Math.floor(Y)));return q}async readMessages($){let T=(await this.getRow($))?.messages_path?.trim();if(!T||!_4(T))return[];try{let q=g4(T,"utf8");if(!q.trim())return[];let X=JSON.parse(q);return Array.isArray(X)?X:Array.isArray(X.messages)?X.messages??[]:[]}catch{return[]}}async readHooks($,Y=200){let T=await this.getRow($);if(!T?.hook_path||!_4(T.hook_path))return[];return g4(T.hook_path,"utf8").split(`
575
+ `).map((J)=>J.trim()).filter((J)=>J.length>0).slice(-Math.max(1,Math.floor(Y))).map((J)=>{try{return JSON.parse(J)}catch{return{raw:J}}})}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}async runTurn($,Y){let T=await this.prepareTurnInput($,Y),q=T.prompt.trim();if(!q)throw Error("prompt cannot be empty");await this.ensureSessionPersisted($),await this.syncOAuthCredentials($);let X=await this.executeAgentTurn($,q,T.userImages,T.userFiles);while(this.shouldAutoContinueTeamRuns($,X.finishReason)){let J=await this.waitForTeamRunUpdates($);if(J.length===0)break;let Q=this.buildTeamRunContinuationPrompt($,J);X=await this.executeAgentTurn($,Q)}return X}async executeAgentTurn($,Y,T,q){let X=$.started||$.agent.getMessages().length>0,J=$.agent.getMessages(),Q=this.usageBySession.get($.sessionId)??k4();$.turnUsageBaseline=Q;try{let U=X?await this.runWithAuthRetry($,()=>$.agent.continue(Y,T,q),J):await this.runWithAuthRetry($,()=>$.agent.run(Y,T,q),J);$.started=!0;let Z=tU(U.messages,U);return this.usageBySession.set($.sessionId,h4(Q,U.usage)),await this.invoke("persistSessionMessages",$.sessionId,Z,$.config.systemPrompt),U}catch(U){throw await this.invoke("persistSessionMessages",$.sessionId,$.agent.getMessages(),$.config.systemPrompt),U}finally{$.turnUsageBaseline=void 0}}async prepareTurnInput($,Y){let T=$.config.workspaceRoot??$.config.cwd,q=v6(Y.prompt).trim();if(!q)return{prompt:"",userImages:Y.userImages,userFiles:this.resolveAbsoluteFilePaths($.config.cwd,Y.userFiles)};let X=await a6(q,T),J=j6(X.prompt,$.config.mode==="plan"?"plan":"act"),Q=this.resolveAbsoluteFilePaths($.config.cwd,Y.userFiles),U=this.resolveAbsoluteFilePaths(T,X.matchedFiles),Z=Array.from(new Set([...Q,...U]));return{prompt:J,userImages:Y.userImages,userFiles:Z.length>0?Z:void 0}}resolveAbsoluteFilePaths($,Y){if(!Y||Y.length===0)return[];let T=Y.map((q)=>q.trim()).filter((q)=>q.length>0).map((q)=>Iz(q)?q:Mz($,q));return Array.from(new Set(T))}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,T){if(!$.artifacts)return;let q=await this.invoke("updateSessionStatus",$.sessionId,Y,T);if(!q.updated)return;$.artifacts.manifest.status=Y,$.artifacts.manifest.ended_at=q.endedAt??W0(),$.artifacts.manifest.exit_code=typeof T==="number"?T: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,eU))}async getRow($){let Y=$.trim();if(!Y)return;return(await this.listRows(eU)).find((q)=>q.session_id===Y)}createSpawnTool($,Y){let T=()=>{if(!$.enableTools)return[];let X=$.mode==="plan"?t1.readonly:t1.development;return NT({cwd:$.cwd,...X,executors:this.defaultToolExecutors})},q=()=>{let X=T();if($.enableSpawnAgent)X.push(this.createSpawnTool($,Y));return X};return Rz({providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,apiKey:$.apiKey,baseUrl:$.baseUrl,providerConfig:$.providerConfig,knownModels:$.knownModels,clineWorkspaceMetadata:$.providerId==="cline"?rU($.systemPrompt):void 0,createSubAgentTools:q,hooks:$.hooks,extensions:$.extensions,toolPolicies:this.defaultToolPolicies,requestToolApproval:this.defaultRequestToolApproval,logger:$.logger,onSubAgentStart:(X)=>{this.invokeOptional("handleSubAgentStart",Y,X)},onSubAgentEnd:(X)=>{this.invokeOptional("handleSubAgentEnd",Y,X)}})}async handleTeamEvent($,Y){let T=this.sessions.get($);if(T)switch(Y.type){case"run_queued":case"run_started":T.activeTeamRunIds.add(Y.run.id);break;case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":{let X;if(Y.type==="run_failed")X=Y.run.error;else if(Y.type==="run_cancelled")X=Y.run.error??Y.reason;else if(Y.type==="run_interrupted")X=Y.run.error??Y.reason;T.activeTeamRunIds.delete(Y.run.id),T.pendingTeamRunUpdates.push({runId:Y.run.id,agentId:Y.run.agentId,taskId:Y.run.taskId,status:Y.type.replace("run_",""),error:X,iterations:Y.run.result?.iterations}),this.notifyTeamRunWaiters(T);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}`,Y.messages);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(!T?.runtime.teamRuntime)return;let q=T.config.teamName?.trim()||"team";this.emit({type:"team_progress",payload:{sessionId:$,teamName:q,lifecycle:w8({teamName:q,sessionId:$,event:Y}),summary:L8(q,T.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 T of Y)T()}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 T=Y.map((J)=>{let Q=`- ${J.runId} (${J.agentId}) -> ${J.status}`,U=J.taskId?` task=${J.taskId}`:"",Z=typeof J.iterations==="number"?` iterations=${J.iterations}`:"",K=J.error?` error=${J.error}`:"";return`${Q}${U}${Z}${K}`}),q=$.activeTeamRunIds.size,X=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 j6(`System-delivered teammate async run updates:
576
+ ${T.join(`
577
+ `)}
578
+
579
+ ${X}`,$.config.mode==="plan"?"plan":"act")}emit($){for(let Y of this.listeners)Y($)}async invoke($,...Y){let T=this.sessionService[$];if(typeof T!=="function")throw Error(`session service method not available: ${$}`);return Promise.resolve(T.apply(this.sessionService,Y))}async invokeOptional($,...Y){let T=this.sessionService[$];if(typeof T!=="function")return;await Promise.resolve(T.apply(this.sessionService,Y))}async invokeOptionalValue($,...Y){let T=this.sessionService[$];if(typeof T!=="function")return;return await Promise.resolve(T.apply(this.sessionService,Y))}async runWithAuthRetry($,Y,T){try{return await Y()}catch(q){if(!this.isLikelyAuthError(q,$.config.providerId))throw q;return await this.syncOAuthCredentials($,{forceRefresh:!0}),$.agent.restore(T),Y()}}isLikelyAuthError($,Y){if(Y!=="cline"&&Y!=="oca"&&Y!=="openai-codex")return!1;let T=$ instanceof Error?$.message.toLowerCase():String($);return T.includes("401")||T.includes("403")||T.includes("unauthorized")||T.includes("forbidden")||T.includes("invalid token")||T.includes("expired token")||T.includes("authentication")}async syncOAuthCredentials($,Y){let T=null;try{T=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId,forceRefresh:Y?.forceRefresh})}catch(X){if(X instanceof j8)throw Error(`OAuth session for "${X.providerId}" requires re-authentication. Run "clite auth ${X.providerId}" and retry.`);throw X}if(!T?.apiKey)return;if($.config.apiKey===T.apiKey)return;$.config.apiKey=T.apiKey,$.agent.updateConnection?.({apiKey:T.apiKey}),$.runtime.teamRuntime?.updateTeammateConnections({apiKey:T.apiKey})}}import{existsSync as Yj,mkdirSync as Tj}from"node:fs";var XT=ZY(I6(),1),C3=ZY(tT(),1);import{existsSync as jy}from"node:fs";import{dirname as O3,join as JY}from"node:path";import{fileURLToPath as vy}from"node:url";var W9=ZY(I6(),1),v3=ZY(I6(),1),x3=ZY(tT(),1);var kJ=ZY(I6(),1);import{randomUUID as w3}from"node:crypto";import{randomUUID as iy}from"node:crypto";import{randomUUID as S3}from"node:crypto";function y3($){let Y=O3(vy($)),T=new Set([JY(Y,"proto","rpc.proto"),JY(Y,"..","proto","rpc.proto"),JY(Y,"..","src","proto","rpc.proto"),JY(Y,"..","..","src","proto","rpc.proto"),JY(process.cwd(),"src","proto","rpc.proto"),JY(process.cwd(),"packages","rpc","src","proto","rpc.proto")]),q=process.cwd();while(!0){T.add(JY(q,"packages","rpc","src","proto","rpc.proto"));let X=O3(q);if(X===q)break;q=X}for(let X of T)if(jy(X))return X;throw Error("Unable to resolve rpc.proto path")}var xy="cline.rpc.v1",j3="ClineGateway";function ky(){return y3(import.meta.url)}function hy(){let $=C3.loadSync(ky(),{keepCase:!1,longs:String,enums:String,defaults:!0,oneofs:!0}),Y=XT.loadPackageDefinition($).cline?.rpc?.v1?.ClineGateway?.service;if(!Y)throw Error(`Unable to load ${xy}.${j3} from proto`);return Y}function _y($){return new(XT.makeGenericClientConstructor(hy(),j3))($,XT.credentials.createInsecure())}function K9($){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((Y)=>K9(Y))}};if(typeof $==="object"){let Y={fields:{}};for(let[T,q]of Object.entries($))Y.fields??={},Y.fields[T]=K9(q);return{structValue:Y}}return{stringValue:String($)}}function A9($){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)=>A9(Y));if($.structValue){let Y={};for(let[T,q]of Object.entries($.structValue.fields??{}))Y[T]=A9(q);return Y}return}function Q1($){let Y={};for(let[T,q]of Object.entries($??{}))Y[T]=K9(q);return{fields:Y}}function f0($){if(!$?.fields)return;let Y={};for(let[T,q]of Object.entries($.fields))Y[T]=A9(q);return Y}function QY($){return K9($)}function UY($){return A9($??void 0)}function gy($){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:Q1($.metadata)}}function P3($){return{sessionId:$.sessionId??"",source:$.source??"",pid:Number($.pid??0),startedAt:$.startedAt??"",endedAt:$.endedAt?$.endedAt:null,exitCode:typeof $.exitCode==="number"?$.exitCode:null,status:$.status??"running",statusLock:Number($.statusLock??0),interactive:$.interactive===!0,provider:$.provider??"",model:$.model??"",cwd:$.cwd??"",workspaceRoot:$.workspaceRoot??"",teamName:$.teamName||void 0,enableTools:$.enableTools===!0,enableSpawn:$.enableSpawn===!0,enableTeams:$.enableTeams===!0,parentSessionId:$.parentSessionId||void 0,parentAgentId:$.parentAgentId||void 0,agentId:$.agentId||void 0,conversationId:$.conversationId||void 0,isSubagent:$.isSubagent===!0,prompt:$.prompt||void 0,metadata:f0($.metadata),transcriptPath:$.transcriptPath??"",hookPath:$.hookPath??"",messagesPath:$.messagesPath||void 0,updatedAt:$.updatedAt??""}}function my($){let Y=$?.trim();if(!Y)return;try{let T=JSON.parse(Y);if(!Array.isArray(T))return;let q=T.map((X)=>typeof X==="string"?X.trim():"").filter((X)=>X.length>0);return q.length>0?q:void 0}catch{return}}function YT($){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:my($.tagsJson??void 0),metadata:f0($.metadata)}}function yJ($){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 xJ{client;constructor($){this.client=_y($.address)}close(){this.client.close()}async upsertSession($){await this.unary((Y)=>{let T={session:gy($)};this.client.UpsertSession(T,Y)})}async getSession($){let Y=await this.unary((T)=>{this.client.GetSession({sessionId:$},T)});if(!Y.session)return;return P3(Y.session)}async listSessions($){return((await this.unary((Y)=>{this.client.ListSessions($,Y)})).sessions??[]).map((Y)=>P3(Y))}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=Q1($.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 T=await this.unary((q)=>{this.client.UpdateSession(Y,q)});return{updated:T.updated===!0,statusLock:Number(T.statusLock??0)}}async deleteSession($,Y=!1){return(await this.unary((T)=>{this.client.DeleteSession({sessionId:$,cascade:Y},T)})).deleted===!0}async enqueueSpawnRequest($){await this.unary((Y)=>{this.client.EnqueueSpawnRequest($,Y)})}async claimSpawnRequest($,Y){let T=(await this.unary((q)=>{let X={rootSessionId:$,parentAgentId:Y};this.client.ClaimSpawnRequest(X,q)})).item?.task?.trim();return T?T:void 0}async startRuntimeSession($){let Y={sessionId:$.sessionId??"",workspaceRoot:$.workspaceRoot,cwd:$.cwd??"",provider:$.provider,model:$.model,mode:$.mode,apiKey:$.apiKey,systemPrompt:$.systemPrompt??"",maxIterations:$.maxIterations??0,hasMaxIterations:typeof $.maxIterations==="number",enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,autoApproveTools:$.autoApproveTools??!1,hasAutoApproveTools:typeof $.autoApproveTools==="boolean",teamName:$.teamName,missionStepInterval:$.missionStepInterval,missionTimeIntervalMs:$.missionTimeIntervalMs,toolPolicies:Object.fromEntries(Object.entries($.toolPolicies??{}).map(([X,J])=>[X,{enabled:J.enabled!==!1,autoApprove:J.autoApprove??!1}])),initialMessages:($.initialMessages??[]).map((X)=>({role:X.role??"",content:QY(X.content)})),logger:$.logger?{enabled:$.logger.enabled??!1,level:$.logger.level??"",destination:$.logger.destination??"",name:$.logger.name??"",bindings:Q1($.logger.bindings)}:void 0},T=await this.unary((X)=>{this.client.StartRuntimeSession({request:Y},X)}),q=T.startResult?{sessionId:T.startResult.sessionId??"",manifestPath:T.startResult.manifestPath??"",transcriptPath:T.startResult.transcriptPath??"",hookPath:T.startResult.hookPath??"",messagesPath:T.startResult.messagesPath??""}:void 0;return{sessionId:T.sessionId??"",startResult:q}}async sendRuntimeSession($,Y){let T={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(([X,J])=>[X,{enabled:J.enabled!==!1,autoApprove:J.autoApprove??!1}])),initialMessages:(Y.config.initialMessages??[]).map((X)=>({role:X.role??"",content:QY(X.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:Q1(Y.config.logger.bindings)}:void 0},messages:(Y.messages??[]).map((X)=>({role:X.role??"",content:QY(X.content)})),prompt:Y.prompt,attachments:Y.attachments?{userImages:Y.attachments.userImages??[],userFiles:(Y.attachments.userFiles??[]).map((X)=>({name:X.name,content:X.content}))}:void 0},q=await this.unary((X)=>{this.client.SendRuntimeSession({sessionId:$,request:T},X)});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((X)=>({role:X.role??"",content:UY(X.content)})),toolCalls:(q.result?.toolCalls??[]).map((X)=>({name:X.name??"",input:X.hasInput?UY(X.input):void 0,output:X.hasOutput?UY(X.output):void 0,error:X.error?.trim()||void 0,durationMs:X.hasDurationMs?Number(X.durationMs??0):void 0}))}}}async abortRuntimeSession($){return{applied:(await this.unary((Y)=>{this.client.AbortRuntimeSession({sessionId:$},Y)})).applied===!0}}async requestToolApproval($){let Y={approvalId:$.approvalId,sessionId:$.sessionId,taskId:$.taskId,toolCallId:$.toolCallId,toolName:$.toolName,inputJson:$.inputJson,requesterClientId:$.requesterClientId,timeoutMs:$.timeoutMs},T=await this.unary((q)=>{this.client.RequestToolApproval(Y,q)});return{approvalId:T.approvalId??"",decided:T.decided===!0,approved:T.approved===!0,reason:T.reason??""}}async respondToolApproval($){let Y={approvalId:$.approvalId,approved:$.approved,reason:$.reason,responderClientId:$.responderClientId},T=await this.unary((q)=>{this.client.RespondToolApproval(Y,q)});return{approvalId:T.approvalId??"",applied:T.applied===!0}}async listPendingApprovals($){return((await this.unary((Y)=>{this.client.ListPendingApprovals({sessionId:$},Y)})).approvals??[]).map((Y)=>({approvalId:Y.approvalId??"",sessionId:Y.sessionId??"",taskId:Y.taskId??"",toolCallId:Y.toolCallId??"",toolName:Y.toolName??"",inputJson:Y.inputJson??"",requesterClientId:Y.requesterClientId??"",createdAt:Y.createdAt??""}))}async createSchedule($){let Y=await this.unary((T)=>{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:Q1($.metadata)},T)});return Y.schedule?YT(Y.schedule):void 0}async getSchedule($){let Y=await this.unary((T)=>{this.client.GetSchedule({scheduleId:$},T)});return Y.schedule?YT(Y.schedule):void 0}async listSchedules($){return((await this.unary((Y)=>{this.client.ListSchedules({limit:$?.limit??100,hasEnabled:typeof $?.enabled==="boolean",enabled:$?.enabled??!1,tagsJson:$?.tags?JSON.stringify($.tags):""},Y)})).schedules??[]).map((Y)=>YT(Y))}async updateSchedule($,Y){let T={scheduleId:$};if(Y.name!==void 0)T.hasName=!0,T.name=Y.name;if(Y.cronPattern!==void 0)T.hasCronPattern=!0,T.cronPattern=Y.cronPattern;if(Y.prompt!==void 0)T.hasPrompt=!0,T.prompt=Y.prompt;if(Y.provider!==void 0)T.hasProvider=!0,T.provider=Y.provider;if(Y.model!==void 0)T.hasModel=!0,T.model=Y.model;if(Y.mode!==void 0)T.hasMode=!0,T.mode=Y.mode;if(Y.workspaceRoot!==void 0)T.hasWorkspaceRoot=!0,T.workspaceRoot=Y.workspaceRoot;if(Y.cwd!==void 0)T.hasCwd=!0,T.cwd=Y.cwd;if(Y.systemPrompt!==void 0)T.hasSystemPrompt=!0,T.systemPrompt=Y.systemPrompt;if(Y.maxIterations===null)T.clearMaxIterations=!0;else if(Y.maxIterations!==void 0)T.hasMaxIterations=!0,T.maxIterations=Y.maxIterations;if(Y.timeoutSeconds===null)T.clearTimeoutSeconds=!0;else if(Y.timeoutSeconds!==void 0)T.hasTimeoutSeconds=!0,T.timeoutSeconds=Y.timeoutSeconds;if(Y.maxParallel!==void 0)T.hasMaxParallel=!0,T.maxParallel=Y.maxParallel;if(Y.enabled!==void 0)T.hasEnabled=!0,T.enabled=Y.enabled;if(Y.createdBy===null)T.clearCreatedBy=!0;else if(Y.createdBy!==void 0)T.hasCreatedBy=!0,T.createdBy=Y.createdBy;if(Y.tags!==void 0)T.hasTagsJson=!0,T.tagsJson=JSON.stringify(Y.tags);if(Y.metadata!==void 0)T.hasMetadata=!0,T.metadata=Q1(Y.metadata);let q=await this.unary((X)=>{this.client.UpdateSchedule(T,X)});return q.schedule?YT(q.schedule):void 0}async deleteSchedule($){return(await this.unary((Y)=>{this.client.DeleteSchedule({scheduleId:$},Y)})).deleted===!0}async pauseSchedule($){let Y=await this.unary((T)=>{this.client.PauseSchedule({scheduleId:$},T)});return Y.schedule?YT(Y.schedule):void 0}async resumeSchedule($){let Y=await this.unary((T)=>{this.client.ResumeSchedule({scheduleId:$},T)});return Y.schedule?YT(Y.schedule):void 0}async triggerScheduleNow($){let Y=await this.unary((T)=>{this.client.TriggerScheduleNow({scheduleId:$},T)});return Y.execution?yJ(Y.execution):void 0}async listScheduleExecutions($){return((await this.unary((Y)=>{this.client.ListScheduleExecutions({scheduleId:$.scheduleId,status:$.status,limit:$.limit??50},Y)})).executions??[]).map((Y)=>yJ(Y))}async getScheduleStats($){let Y=await this.unary((T)=>{this.client.GetScheduleStats({scheduleId:$},T)});return{totalRuns:Number(Y.totalRuns??0),successRate:Number(Y.successRate??0),avgDurationSeconds:Number(Y.avgDurationSeconds??0),lastFailure:Y.lastFailure?yJ(Y.lastFailure):void 0}}async getActiveScheduledExecutions(){return((await this.unary(($)=>{this.client.GetActiveScheduledExecutions({},$)})).executions??[]).map(($)=>({executionId:$.executionId??"",scheduleId:$.scheduleId??"",sessionId:$.sessionId??"",startedAt:$.startedAt??"",timeoutAt:$.timeoutAt?.trim()||void 0}))}async getUpcomingScheduledRuns($=20){return((await this.unary((Y)=>{this.client.GetUpcomingScheduledRuns({limit:$},Y)})).runs??[]).map((Y)=>({scheduleId:Y.scheduleId??"",name:Y.name??"",nextRunAt:Y.nextRunAt??""}))}async stopRuntimeSession($){return{applied:(await this.unary((Y)=>{this.client.StopRuntimeSession({sessionId:$},Y)})).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}},T=await this.unary((q)=>{this.client.RunProviderAction({request:Y},q)});return{result:UY(T.result)}}async runProviderOAuthLogin($){let Y=await this.unary((T)=>{this.client.RunProviderOAuthLogin({provider:$},T)});return{provider:Y.provider??"",accessToken:Y.apiKey??""}}async publishEvent($){let Y=await this.unary((T)=>{this.client.PublishEvent({eventId:$.eventId,sessionId:$.sessionId,taskId:$.taskId,eventType:$.eventType,payload:Q1($.payload),sourceClientId:$.sourceClientId},T)});return{eventId:Y.eventId??"",accepted:Y.accepted===!0}}streamEvents($,Y={}){let T=!1,q=this.client.StreamEvents({clientId:$.clientId??"",sessionIds:$.sessionIds??[]}),X=(U)=>{Y.onEvent?.({eventId:U.eventId??"",sessionId:U.sessionId??"",taskId:U.taskId?.trim()?U.taskId:void 0,eventType:U.eventType??"",payload:f0(U.payload)??{},sourceClientId:U.sourceClientId?.trim()?U.sourceClientId:void 0,ts:U.ts??""})},J=(U)=>{let Z=(typeof U.code==="number"?Number(U.code):void 0)===1||U.message.includes("CANCELLED");if(T&&Z)return;Y.onError?.(U)},Q=()=>{Y.onEnd?.()};return q.on("data",X),q.on("error",J),q.on("end",Q),()=>{T=!0,q.cancel()}}streamTeamProgress($,Y={}){return this.streamEvents($,{onEvent:(T)=>{if(T.eventType===x6){try{let q=T.payload;if(q.type==="team_progress_projection"&&q.version===1)Y.onProjection?.(q)}catch{}return}if(T.eventType===k6)try{Y.onLifecycle?.(T.payload)}catch{}},onError:Y.onError,onEnd:Y.onEnd})}async unary($){return await new Promise((Y,T)=>{$((q,X)=>{if(q){T(q);return}Y(X??{})})})}}var fy="127.0.0.1:4317",by="cline.rpc.v1",k3="ClineGateway";function uy(){return y3(import.meta.url)}function dy(){let $=x3.loadSync(uy(),{keepCase:!1,longs:String,enums:String,defaults:!0,oneofs:!0}),Y=v3.loadPackageDefinition($).cline?.rpc?.v1?.ClineGateway?.service;if(!Y)throw Error(`Unable to load ${by}.${k3} from proto`);return Y}function qT(){return new Date().toISOString()}function N($){return typeof $==="string"?$:""}function cy($){if(!$||typeof $!=="object")return{};let Y={};for(let[T,q]of Object.entries($)){let X=T.trim();if(!X)continue;let J=N(q).trim();if(!J)continue;Y[X]=J}return Y}function py($){if(!Array.isArray($)||$.length===0)return;let Y=new Set;for(let T of $){let q=T.trim();if(q)Y.add(q)}return Y.size>0?Y:void 0}function h3($){if($==="running"||$==="completed"||$==="failed"||$==="cancelled")return $;return"running"}function L3($){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:Q1($.metadata)}}function ly($){let Y=N($.sessionId).trim(),T=N($.source).trim(),q=N($.startedAt).trim(),X=N($.provider).trim(),J=N($.model).trim(),Q=N($.cwd).trim(),U=N($.workspaceRoot).trim(),Z=N($.transcriptPath).trim(),K=N($.hookPath).trim();if(!Y||!T||!q||!X||!J||!Q||!U||!Z||!K)throw Error("session record is missing required fields");return{sessionId:Y,source:T,pid:Number($.pid??0),startedAt:q,endedAt:N($.endedAt).trim()||null,exitCode:typeof $.exitCode==="number"?Math.floor($.exitCode):null,status:h3(N($.status).trim()),statusLock:typeof $.statusLock==="number"?Math.floor($.statusLock):0,interactive:$.interactive===!0,provider:X,model:J,cwd:Q,workspaceRoot:U,teamName:N($.teamName).trim()||void 0,enableTools:$.enableTools===!0,enableSpawn:$.enableSpawn===!0,enableTeams:$.enableTeams===!0,parentSessionId:N($.parentSessionId).trim()||void 0,parentAgentId:N($.parentAgentId).trim()||void 0,agentId:N($.agentId).trim()||void 0,conversationId:N($.conversationId).trim()||void 0,isSubagent:$.isSubagent===!0,prompt:N($.prompt).trim()||void 0,metadata:f0($.metadata),transcriptPath:Z,hookPath:K,messagesPath:N($.messagesPath).trim()||void 0,updatedAt:N($.updatedAt).trim()||qT()}}function jJ($){let Y=N($).trim();if(!Y)return;try{let T=JSON.parse(Y);if(!Array.isArray(T))return;let q=T.map((X)=>typeof X==="string"?X.trim():"").filter((X)=>X.length>0);return q.length>0?q:void 0}catch{return}}function TT($){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:Q1($.metadata)}}function vJ($){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 ny($){return new(W9.makeGenericClientConstructor(dy(),k3))($,W9.credentials.createInsecure())}async function _3($){return await new Promise((Y)=>{let T;try{T=ny($)}catch{Y(void 0);return}T.Health({},(q,X)=>{if(T?.close(),q||!X){Y(void 0);return}Y(X)})})}var ry=300000;class g3{publishEvent;approvals=new Map;constructor($){this.publishEvent=$}async requestToolApproval($){let Y=N($.sessionId).trim(),T=N($.toolCallId).trim(),q=N($.toolName).trim();if(!Y||!T||!q)throw Error("sessionId, toolCallId, and toolName are required");let X=N($.approvalId).trim()||`apr_${iy()}`;if(!this.approvals.get(X)){let Z={approvalId:X,sessionId:Y,taskId:N($.taskId).trim()||void 0,toolCallId:T,toolName:q,inputJson:N($.inputJson),requesterClientId:N($.requesterClientId).trim()||void 0,createdAt:qT(),status:"pending",waiters:[]};this.approvals.set(X,Z),this.publishEvent({eventId:"",sessionId:Y,taskId:Z.taskId,eventType:"approval.requested",payload:Q1(Z),sourceClientId:Z.requesterClientId})}let J=this.approvals.get(X);if(!J)throw Error("approval state not found");if(J.status==="approved"||J.status==="rejected")return{approvalId:X,decided:!0,approved:J.status==="approved",reason:J.reason??""};let Q=typeof $.timeoutMs==="number"&&$.timeoutMs>0?Math.floor($.timeoutMs):ry,U=await new Promise((Z)=>{let K=setTimeout(()=>{Z({decided:!1,approved:!1,reason:"Tool approval request timed out"})},Q);J.waiters.push((A)=>{clearTimeout(K),Z(A)})});return{approvalId:X,decided:U.decided,approved:U.approved,reason:U.reason??""}}respondToolApproval($){let Y=N($.approvalId).trim();if(!Y)throw Error("approvalId is required");let T=this.approvals.get(Y);if(!T)return{approvalId:Y,applied:!1};T.status=$.approved===!0?"approved":"rejected",T.reason=N($.reason).trim()||void 0;let q={decided:!0,approved:T.status==="approved",reason:T.reason};for(let X of T.waiters.splice(0))X(q);return this.publishEvent({eventId:"",sessionId:T.sessionId,taskId:T.taskId,eventType:"approval.decided",payload:Q1({approvalId:Y,approved:q.approved,reason:q.reason??"",responderClientId:N($.responderClientId).trim()||""}),sourceClientId:N($.responderClientId).trim()||""}),{approvalId:Y,applied:!0}}listPendingApprovals($){let Y=N($.sessionId).trim(),T=[];for(let q of this.approvals.values()){if(q.status!=="pending")continue;if(Y&&q.sessionId!==Y)continue;T.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 T.sort((q,X)=>(q.createdAt??"").localeCompare(X.createdAt??"")),{approvals:T}}}class m3{subscribers=new Map;nextSubscriberId=1;publishEvent($){let Y=N($.sessionId).trim();if(!Y)throw Error("sessionId is required");let T={eventId:N($.eventId).trim()||`evt_${S3()}`,sessionId:Y,taskId:N($.taskId).trim()||void 0,eventType:N($.eventType).trim()||"unknown",payload:f0($.payload)??{},sourceClientId:N($.sourceClientId).trim()||void 0,ts:qT()};return this.dispatchEvent(T),{eventId:T.eventId,accepted:!0}}addSubscriber($){let Y=$.request,T=py(Y.sessionIds),q=this.nextSubscriberId;return this.nextSubscriberId+=1,this.subscribers.set(q,{call:$,filterSessionIds:T}),$.on("cancelled",()=>{this.subscribers.delete(q)}),$.on("close",()=>{this.subscribers.delete(q)}),q}removeSubscriber($){this.subscribers.delete($)}broadcastServerEvent($,Y){let T=`evt_${S3()}`,q=qT();for(let X of this.subscribers.values())X.call.write({eventId:T,sessionId:"__rpc__",taskId:"",eventType:$,payload:Q1(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:Q1($.payload),sourceClientId:$.sourceClientId??"",ts:$.ts})}}}class f3{scheduler;constructor($){this.scheduler=$}createSchedule($){let Y=this.requireScheduler(),T={name:N($.name).trim(),cronPattern:N($.cronPattern).trim(),prompt:N($.prompt),provider:N($.provider).trim(),model:N($.model).trim(),mode:N($.mode).trim()==="plan"?"plan":"act",workspaceRoot:N($.workspaceRoot).trim()||void 0,cwd:N($.cwd).trim()||void 0,systemPrompt:N($.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:N($.createdBy).trim()||void 0,tags:jJ(N($.tagsJson)),metadata:f0($.metadata)};if(!T.name||!T.cronPattern||!T.prompt.trim()||!T.provider||!T.model)throw Error("name, cronPattern, prompt, provider, and model are required");let q=Y.createSchedule(T);return{schedule:TT(q)}}getSchedule($){let Y=this.requireScheduler(),T=N($.scheduleId).trim();if(!T)throw Error("scheduleId is required");let q=Y.getSchedule(T);return q?{schedule:TT(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:jJ(N($.tagsJson))}).map((Y)=>TT(Y))}}updateSchedule($){let Y=this.requireScheduler(),T=N($.scheduleId).trim();if(!T)throw Error("scheduleId is required");let q={};if($.hasName)q.name=N($.name);if($.hasCronPattern)q.cronPattern=N($.cronPattern);if($.hasPrompt)q.prompt=N($.prompt);if($.hasProvider)q.provider=N($.provider);if($.hasModel)q.model=N($.model);if($.hasMode)q.mode=N($.mode).trim()==="plan"?"plan":"act";if($.hasWorkspaceRoot)q.workspaceRoot=N($.workspaceRoot);if($.hasCwd)q.cwd=N($.cwd);if($.hasSystemPrompt)q.systemPrompt=N($.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=N($.createdBy);if($.hasTagsJson)q.tags=jJ(N($.tagsJson))??[];if($.hasMetadata)q.metadata=f0($.metadata)??{};let X=Y.updateSchedule(T,q);return{updated:X!==void 0,schedule:X?TT(X):void 0}}deleteSchedule($){let Y=this.requireScheduler(),T=N($.scheduleId).trim();if(!T)throw Error("scheduleId is required");return{deleted:Y.deleteSchedule(T)}}pauseSchedule($){let Y=this.requireScheduler(),T=N($.scheduleId).trim();if(!T)throw Error("scheduleId is required");let q=Y.pauseSchedule(T);return{updated:q!==void 0,schedule:q?TT(q):void 0}}resumeSchedule($){let Y=this.requireScheduler(),T=N($.scheduleId).trim();if(!T)throw Error("scheduleId is required");let q=Y.resumeSchedule(T);return{updated:q!==void 0,schedule:q?TT(q):void 0}}async triggerScheduleNow($){let Y=this.requireScheduler(),T=N($.scheduleId).trim();if(!T)throw Error("scheduleId is required");let q=await Y.triggerScheduleNow(T);return q?{execution:vJ(q)}:{}}listScheduleExecutions($){let Y=this.requireScheduler(),T=N($.scheduleId).trim()||void 0,q=N($.status).trim()||void 0;return{executions:Y.listScheduleExecutions({scheduleId:T,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((X)=>vJ(X))}}getScheduleStats($){let Y=this.requireScheduler(),T=N($.scheduleId).trim();if(!T)throw Error("scheduleId is required");let q=Y.getScheduleStats(T);return{totalRuns:q.totalRuns,successRate:q.successRate,avgDurationSeconds:q.avgDurationSeconds,lastFailure:q.lastFailure?vJ(q.lastFailure):void 0}}getActiveScheduledExecutions($){return{executions:this.requireScheduler().getActiveExecutions().map((Y)=>({executionId:Y.executionId,scheduleId:Y.scheduleId,sessionId:Y.sessionId,startedAt:Y.startedAt,timeoutAt:Y.timeoutAt??""}))}}getUpcomingScheduledRuns($){let Y=this.requireScheduler(),T=typeof $.limit==="number"&&$.limit>0?Math.floor($.limit):20;return{runs:Y.getUpcomingRuns(T).map((q)=>({scheduleId:q.scheduleId,name:q.name,nextRunAt:q.nextRunAt}))}}requireScheduler(){if(!this.scheduler)throw Error("scheduler service is not configured");return this.scheduler}}class ay{serverId=w3();address;startedAt;runtimeHandlers;sessions=new Map;tasks=new Map;clients=new Map;store;eventService=new m3;approvalService=new g3(($)=>this.eventService.publishEvent($));scheduleService;constructor($,Y,T,q){this.address=$,this.startedAt=qT(),this.store=Y,this.runtimeHandlers=T,this.scheduleService=new f3(q),this.store.init()}health(){return{serverId:this.serverId,address:this.address,running:!0,startedAt:this.startedAt}}registerClient($){let Y=N($.clientId).trim()||`client_${w3()}`,T=N($.clientType).trim()||void 0,q=cy($),X=qT(),J=this.clients.get(Y),Q=J?{...J,clientType:T??J.clientType,metadata:Object.keys(q).length>0?{...J.metadata??{},...q}:J.metadata,lastRegisteredAt:X,activationCount:J.activationCount+1}:{clientId:Y,clientType:T,metadata:Object.keys(q).length>0?q:void 0,firstRegisteredAt:X,lastRegisteredAt:X,activationCount:1};return this.clients.set(Y,Q),this.broadcastServerEvent("rpc.client.activated",{clientId:Q.clientId,clientType:Q.clientType,metadata:Q.metadata??{},firstRegisteredAt:Q.firstRegisteredAt,lastRegisteredAt:Q.lastRegisteredAt,activationCount:Q.activationCount}),{clientId:Y,registered:!0}}ensureSession($){let Y=N($.sessionId).trim();if(!Y)throw Error("sessionId is required");let T=this.sessions.get(Y);if(T)return T.status=N($.status).trim()||T.status,T.workspaceRoot=N($.workspaceRoot).trim()||T.workspaceRoot,T.clientId=N($.clientId).trim()||T.clientId,T.metadata=f0($.metadata)??T.metadata,{sessionId:Y,created:!1,status:T.status};let q=N($.status).trim()||"running";return this.sessions.set(Y,{sessionId:Y,status:q,workspaceRoot:N($.workspaceRoot).trim()||void 0,clientId:N($.clientId).trim()||void 0,metadata:f0($.metadata)}),{sessionId:Y,created:!0,status:q}}upsertSession($){if(!$.session)throw Error("session is required");return this.store.upsertSession(ly($.session)),{persisted:!0}}getSession($){let Y=N($.sessionId).trim();if(!Y)throw Error("sessionId is required");let T=this.store.getSession(Y);if(!T)return{};return{session:L3(T)}}listSessions($){let Y=typeof $.limit==="number"&&$.limit>0?Math.floor($.limit):200;return{sessions:this.store.listSessions({limit:Y,parentSessionId:N($.parentSessionId).trim()||void 0,status:N($.status).trim()||void 0}).map((T)=>L3(T))}}updateSession($){let Y=N($.sessionId).trim();if(!Y)throw Error("sessionId is required");return this.store.updateSession({sessionId:Y,status:$.status?h3($.status):void 0,endedAt:$.endedAt?$.endedAt:void 0,exitCode:$.hasExitCode?$.exitCode??null:void 0,prompt:$.hasPrompt?$.prompt??null:void 0,metadata:$.hasMetadata?f0($.metadata)??null:void 0,parentSessionId:$.hasParentSessionId?$.parentSessionId??null:void 0,parentAgentId:$.hasParentAgentId?$.parentAgentId??null:void 0,agentId:$.hasAgentId?$.agentId??null:void 0,conversationId:$.hasConversationId?$.conversationId??null:void 0,expectedStatusLock:$.hasExpectedStatusLock?$.expectedStatusLock:void 0,setRunning:$.setRunning===!0})}deleteSession($){let Y=N($.sessionId).trim();if(!Y)throw Error("sessionId is required");let T=this.store.deleteSession(Y);if($.cascade===!0)this.store.deleteSessionsByParent(Y);return{deleted:T}}enqueueSpawnRequest($){let Y=N($.rootSessionId).trim(),T=N($.parentAgentId).trim();if(!Y||!T)throw Error("rootSessionId and parentAgentId are required");return this.store.enqueueSpawnRequest({rootSessionId:Y,parentAgentId:T,task:N($.task).trim()||void 0,systemPrompt:N($.systemPrompt).trim()||void 0}),{enqueued:!0}}claimSpawnRequest($){let Y=N($.rootSessionId).trim(),T=N($.parentAgentId).trim();if(!Y||!T)throw Error("rootSessionId and parentAgentId are required");let q=this.store.claimSpawnRequest(Y,T);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 T=$.request?{sessionId:N($.request.sessionId),workspaceRoot:N($.request.workspaceRoot),cwd:N($.request.cwd),provider:N($.request.provider),model:N($.request.model),mode:N($.request.mode),apiKey:N($.request.apiKey),systemPrompt:N($.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:N($.request.teamName),missionStepInterval:$.request.missionStepInterval??3,missionTimeIntervalMs:$.request.missionTimeIntervalMs??120000,toolPolicies:Object.fromEntries(Object.entries($.request.toolPolicies??{}).map(([J,Q])=>[J,{enabled:Q?.enabled===!0,autoApprove:Q?.autoApprove===!0}])),initialMessages:($.request.initialMessages??[]).map((J)=>({role:N(J.role),content:UY(J.content)})),logger:$.request.logger?{enabled:$.request.logger.enabled===!0,level:N($.request.logger.level),destination:N($.request.logger.destination),name:N($.request.logger.name),bindings:f0($.request.logger.bindings)}:void 0}:void 0;if(!T)throw Error("runtime start request is required");let q=await Y(T),X=N(q.sessionId).trim();if(!X)throw Error("runtime start handler returned empty sessionId");return{sessionId:X,startResult:q.startResult?{sessionId:N(q.startResult.sessionId),manifestPath:N(q.startResult.manifestPath),transcriptPath:N(q.startResult.transcriptPath),hookPath:N(q.startResult.hookPath),messagesPath:N(q.startResult.messagesPath)}:void 0}}async sendRuntimeSession($){let Y=this.runtimeHandlers?.sendSession;if(!Y)throw Error("runtime send handler is not configured");let T=N($.sessionId).trim();if(!T)throw Error("sessionId is required");let q=$.request?{config:{workspaceRoot:N($.request.config?.workspaceRoot),cwd:N($.request.config?.cwd),provider:N($.request.config?.provider),model:N($.request.config?.model),mode:N($.request.config?.mode),apiKey:N($.request.config?.apiKey),systemPrompt:N($.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:N($.request.config?.teamName),missionStepInterval:$.request.config?.missionStepInterval??3,missionTimeIntervalMs:$.request.config?.missionTimeIntervalMs??120000,toolPolicies:Object.fromEntries(Object.entries($.request.config?.toolPolicies??{}).map(([J,Q])=>[J,{enabled:Q?.enabled===!0,autoApprove:Q?.autoApprove===!0}])),initialMessages:($.request.config?.initialMessages??[]).map((J)=>({role:N(J.role),content:UY(J.content)})),logger:$.request.config?.logger?{enabled:$.request.config.logger.enabled===!0,level:N($.request.config.logger.level),destination:N($.request.config.logger.destination),name:N($.request.config.logger.name),bindings:f0($.request.config.logger.bindings)}:void 0},messages:($.request.messages??[]).map((J)=>({role:N(J.role),content:UY(J.content)})),prompt:N($.request.prompt),attachments:$.request.attachments?{userImages:$.request.attachments.userImages??[],userFiles:($.request.attachments.userFiles??[]).map((J)=>({name:N(J.name),content:N(J.content)}))}:void 0}:void 0;if(!q)throw Error("runtime send request is required");let X=await Y(T,q);return{result:{text:N(X.result.text),usage:{inputTokens:X.result.usage.inputTokens,outputTokens:X.result.usage.outputTokens,cacheReadTokens:X.result.usage.cacheReadTokens??0,hasCacheReadTokens:typeof X.result.usage.cacheReadTokens==="number",cacheWriteTokens:X.result.usage.cacheWriteTokens??0,hasCacheWriteTokens:typeof X.result.usage.cacheWriteTokens==="number",totalCost:X.result.usage.totalCost??0,hasTotalCost:typeof X.result.usage.totalCost==="number"},inputTokens:X.result.inputTokens,outputTokens:X.result.outputTokens,iterations:X.result.iterations,finishReason:N(X.result.finishReason),messages:(X.result.messages??[]).map((J)=>({role:N(J.role),content:QY(J.content)})),toolCalls:(X.result.toolCalls??[]).map((J)=>({name:N(J.name),input:QY(J.input),hasInput:J.input!==void 0,output:QY(J.output),hasOutput:J.output!==void 0,error:N(J.error),durationMs:J.durationMs??0,hasDurationMs:typeof J.durationMs==="number"}))}}}async stopRuntimeSession($){let Y=this.runtimeHandlers?.stopSession;if(!Y)throw Error("runtime stop handler is not configured");let T=N($.sessionId).trim();if(!T)throw Error("sessionId is required");return{applied:(await Y(T)).applied===!0}}async abortRuntimeSession($){let Y=this.runtimeHandlers?.abortSession;if(!Y)throw Error("runtime abort handler is not configured");let T=N($.sessionId).trim();if(!T)throw Error("sessionId is required");return{applied:(await Y(T)).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 T;if($.request.listProviders)T={action:"listProviders"};else if($.request.getProviderModels)T={action:"getProviderModels",providerId:N($.request.getProviderModels.providerId)};else if($.request.addProvider)T={action:"addProvider",providerId:N($.request.addProvider.providerId),name:N($.request.addProvider.name),baseUrl:N($.request.addProvider.baseUrl),apiKey:N($.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:N($.request.addProvider.defaultModelId)||void 0,modelsSourceUrl:N($.request.addProvider.modelsSourceUrl)||void 0,capabilities:$.request.addProvider.capabilities};else if($.request.saveProviderSettings)T={action:"saveProviderSettings",providerId:N($.request.saveProviderSettings.providerId),enabled:$.request.saveProviderSettings.hasEnabled?$.request.saveProviderSettings.enabled:void 0,apiKey:$.request.saveProviderSettings.hasApiKey?$.request.saveProviderSettings.apiKey:void 0,baseUrl:$.request.saveProviderSettings.hasBaseUrl?$.request.saveProviderSettings.baseUrl:void 0};else{let X=N($.request.clineAccount?.operation);if(X==="fetchMe")T={action:"clineAccount",operation:"fetchMe"};else if(X==="fetchBalance")T={action:"clineAccount",operation:"fetchBalance",userId:N($.request.clineAccount?.userId)||void 0};else if(X==="fetchUsageTransactions")T={action:"clineAccount",operation:"fetchUsageTransactions",userId:N($.request.clineAccount?.userId)||void 0};else if(X==="fetchPaymentTransactions")T={action:"clineAccount",operation:"fetchPaymentTransactions",userId:N($.request.clineAccount?.userId)||void 0};else if(X==="fetchUserOrganizations")T={action:"clineAccount",operation:"fetchUserOrganizations"};else if(X==="fetchOrganizationBalance")T={action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:N($.request.clineAccount?.organizationId)};else if(X==="fetchOrganizationUsageTransactions")T={action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:N($.request.clineAccount?.organizationId),memberId:N($.request.clineAccount?.memberId)||void 0};else T={action:"clineAccount",operation:"switchAccount",organizationId:$.request.clineAccount?.clearOrganizationId?null:N($.request.clineAccount?.organizationId)||void 0}}let q=await Y(T);return{result:QY(q.result)}}async runProviderOAuthLogin($){let Y=this.runtimeHandlers?.runProviderOAuthLogin;if(!Y)throw Error("provider oauth handler is not configured");let T=N($.provider).trim();if(!T)throw Error("provider is required");let q=await Y(T);return{provider:N(q.provider).trim(),apiKey:N(q.accessToken)}}startTask($){let Y=N($.sessionId).trim(),T=N($.taskId).trim();if(!Y||!T)throw Error("sessionId and taskId are required");let q=`${Y}:${T}`;return this.tasks.set(q,{sessionId:Y,taskId:T,title:N($.title).trim()||void 0,status:"running",payload:f0($.payload)??void 0}),this.eventService.publishEvent({eventId:"",sessionId:Y,taskId:T,eventType:"task.started",payload:f0($.payload)??{},sourceClientId:""}),{sessionId:Y,taskId:T,status:"running",updated:!0}}completeTask($){let Y=N($.sessionId).trim(),T=N($.taskId).trim();if(!Y||!T)throw Error("sessionId and taskId are required");let q=`${Y}:${T}`,X=N($.status).trim()||"completed",J=this.tasks.get(q);if(!J)return{sessionId:Y,taskId:T,status:X,updated:!1};return J.status=X,J.result=f0($.result)??void 0,this.eventService.publishEvent({eventId:"",sessionId:Y,taskId:T,eventType:"task.completed",payload:f0($.result)??{},sourceClientId:""}),{sessionId:Y,taskId:T,status:X,updated:!0}}publishEvent($){return this.eventService.publishEvent($)}addSubscriber($){return this.eventService.addSubscriber($)}removeSubscriber($){this.eventService.removeSubscriber($)}requestToolApproval($){return this.approvalService.requestToolApproval($)}respondToolApproval($){return this.approvalService.respondToolApproval($)}listPendingApprovals($){return this.approvalService.listPendingApprovals($)}createSchedule($){return this.scheduleService.createSchedule($)}getSchedule($){return this.scheduleService.getSchedule($)}listSchedules($){return this.scheduleService.listSchedules($)}updateSchedule($){return this.scheduleService.updateSchedule($)}deleteSchedule($){return this.scheduleService.deleteSchedule($)}pauseSchedule($){return this.scheduleService.pauseSchedule($)}resumeSchedule($){return this.scheduleService.resumeSchedule($)}triggerScheduleNow($){return this.scheduleService.triggerScheduleNow($)}listScheduleExecutions($){return this.scheduleService.listScheduleExecutions($)}getScheduleStats($){return this.scheduleService.getScheduleStats($)}getActiveScheduledExecutions($){return this.scheduleService.getActiveScheduledExecutions($)}getUpcomingScheduledRuns($){return this.scheduleService.getUpcomingScheduledRuns($)}broadcastServerEvent($,Y){this.eventService.broadcastServerEvent($,Y)}}function b3(){return fy}import{appendFileSync as u3,existsSync as sy,readFileSync as ty,writeFileSync as B6}from"node:fs";import{nanoid as ey}from"nanoid";import{z as gJ}from"zod";import{nanoid as oy}from"nanoid";function M6($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function G9($,Y){let T=M6($),q=M6(Y),X=`${T}__${q}`;return X.length>180?X.slice(0,180):X}function hJ($,Y){let T=M6($),q=M6(Y);return`${T}__teamtask__${q}__${oy(6)}`}function _J($){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 d3="cli_subagent",$j=gJ.object({task:gJ.string().optional(),systemPrompt:gJ.string().optional()}).passthrough();function c3($){if(!$||Object.keys($).length===0)return null;return JSON.stringify($)}class R6{adapter;teamTaskSessionsByAgent=new Map;artifacts;constructor($){this.adapter=$;this.artifacts=new v4(()=>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 T=this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey($,Y));if(!T||T.length===0)return;return T[T.length-1]}subagentArtifactPaths($,Y,T,q){return this.artifacts.subagentArtifactPaths(Y,q,this.activeTeamTaskSessionId($,T))}writeSessionManifestFile($,Y){let T=IY.parse(Y);B6($,`${JSON.stringify(T,null,2)}
580
+ `,"utf8")}createRootSessionId(){return`${Date.now()}_${ey(5)}`}async createRootSessionWithArtifacts($){let Y=$.startedAt??W0(),T=$.sessionId.trim(),q=T.length>0?T:this.createRootSessionId(),X=this.sessionTranscriptPath(q),J=this.sessionHookPath(q),Q=this.sessionMessagesPath(q),U=this.sessionManifestPath(q),Z=IY.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:Q});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:Z.prompt??null,metadata_json:c3(Z.metadata),transcript_path:X,hook_path:J,messages_path:Q,updated_at:W0()}),B6(Q,`${JSON.stringify({version:1,updated_at:Y,messages:[]},null,2)}
581
+ `,"utf8"),this.writeSessionManifestFile(U,Z),{manifestPath:U,transcriptPath:X,hookPath:J,messagesPath:Q,manifest:Z}}writeSessionManifest($,Y){this.writeSessionManifestFile($,Y)}async updateSessionStatus($,Y,T){for(let q=0;q<4;q++){let X=await this.adapter.getSession($);if(!X||typeof X.status_lock!=="number")return{updated:!1};let J=W0();if((await this.adapter.updateSession({sessionId:$,status:Y,endedAt:J,exitCode:typeof T==="number"?T:null,expectedStatusLock:X.status_lock})).updated){if(Y==="cancelled")await this.applyStatusToRunningChildSessions($,"cancelled");return{updated:!0,endedAt:J}}}return{updated:!1}}async updateSession($){for(let Y=0;Y<4;Y++){let T=await this.adapter.getSession($.sessionId);if(!T||typeof T.status_lock!=="number")return{updated:!1};if(!(await this.adapter.updateSession({sessionId:$.sessionId,prompt:$.prompt,metadataJson:$.metadata===void 0?void 0:c3($.metadata),expectedStatusLock:T.status_lock})).updated)continue;let X=this.sessionManifestPath($.sessionId,!1);if(sy(X))try{let J=IY.parse(JSON.parse(ty(X,"utf8")));if($.prompt!==void 0)J.prompt=$.prompt??void 0;if($.metadata!==void 0)J.metadata=$.metadata??void 0;this.writeSessionManifestFile(X,J)}catch{}return{updated:!0}}return{updated:!1}}async queueSpawnRequest($){if($.hookName!=="tool_call"||$.parent_agent_id!==null)return;if($.tool_call?.name!=="spawn_agent")return;let Y=h6($.sessionContext);if(!Y)return;let T=$j.safeParse($.tool_call.input),q=T.success?T.data.task:void 0,X=T.success?T.data.systemPrompt:void 0;await this.adapter.enqueueSpawnRequest({rootSessionId:Y,parentAgentId:$.agent_id,task:q,systemPrompt:X})}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 T=await this.readRootSession(Y);if(!T)return;let q=G9(Y,$.agentId),X=await this.adapter.getSession(q),J=W0(),Q=this.subagentArtifactPaths(Y,q,$.parentAgentId,$.agentId),U=$.prompt??X?.prompt??void 0;if(!U)U=await this.claimQueuedSpawnTask(Y,$.parentAgentId)??`Subagent run by ${$.parentAgentId}`;if(!X)return await this.adapter.upsertSession({session_id:q,source:d3,pid:process.ppid,started_at:J,ended_at:null,exit_code:null,status:"running",status_lock:0,interactive:0,provider:T.provider,model:T.model,cwd:T.cwd,workspace_root:T.workspace_root,team_name:T.team_name??null,enable_tools:T.enable_tools,enable_spawn:T.enable_spawn,enable_teams:T.enable_teams,parent_session_id:Y,parent_agent_id:$.parentAgentId,agent_id:$.agentId,conversation_id:$.conversationId,is_subagent:1,prompt:U,metadata_json:null,transcript_path:Q.transcriptPath,hook_path:Q.hookPath,messages_path:Q.messagesPath,updated_at:J}),B6(Q.messagesPath,`${JSON.stringify({version:1,updated_at:J,messages:[]},null,2)}
582
+ `,"utf8"),q;return await this.adapter.updateSession({sessionId:q,setRunning:!0,parentSessionId:Y,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:X.prompt??U??null,expectedStatusLock:X.status_lock}),q}async upsertSubagentSessionFromHook($){if(!$.parent_agent_id)return;let Y=h6($.sessionContext);if(!Y)return;if($.hookName==="session_shutdown"){let T=G9(Y,$.agent_id);return await this.adapter.getSession(T)?T:void 0}return await this.upsertSubagentSession({agentId:$.agent_id,parentAgentId:$.parent_agent_id,conversationId:$.taskId,rootSessionId:Y})}async appendSubagentHookAudit($,Y){let T=`${JSON.stringify({ts:W0(),...Y})}
583
+ `,q=await this.sessionPathFromStore($,"hook_path")??this.sessionHookPath($);u3(q,T,"utf8")}async appendSubagentTranscriptLine($,Y){if(!Y.trim())return;let T=await this.sessionPathFromStore($,"transcript_path")??this.sessionTranscriptPath($);u3(T,`${Y}
584
+ `,"utf8")}async persistSessionMessages($,Y,T){let q=await this.sessionPathFromStore($,"messages_path")??this.sessionMessagesPath($),X={version:1,updated_at:W0(),messages:Y};if(T!==void 0&&T!=="")X.systemPrompt=T;B6(q,`${JSON.stringify(X,null,2)}
585
+ `,"utf8")}async applySubagentStatus($,Y){await this.applySubagentStatusBySessionId($,_J(Y))}async applySubagentStatusBySessionId($,Y){let T=await this.adapter.getSession($);if(!T||typeof T.status_lock!=="number")return;let q=W0(),X=Y==="running"?null:q,J=Y==="failed"?1:0;await this.adapter.updateSession({sessionId:$,status:Y,endedAt:X,exitCode:Y==="running"?null:J,expectedStatusLock:T.status_lock})}async applyStatusToRunningChildSessions($,Y){if(!$)return;let T=await this.adapter.listSessions({limit:2000,parentSessionId:$,status:"running"});for(let q of T)await this.applySubagentStatusBySessionId(q.session_id,Y)}async createTeamTaskSubSession($,Y,T){let q=await this.readRootSession($);if(!q)return;let X=hJ($,Y),J=W0(),Q=this.sessionTranscriptPath(X),U=this.sessionHookPath(X),Z=this.sessionMessagesPath(X);return await this.adapter.upsertSession({session_id:X,source:d3,pid:process.ppid,started_at:J,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:T||`Team task for ${Y}`,metadata_json:null,transcript_path:Q,hook_path:U,messages_path:Z,updated_at:J}),B6(Z,`${JSON.stringify({version:1,updated_at:J,messages:[]},null,2)}
586
+ `,"utf8"),await this.appendSubagentTranscriptLine(X,`[start] ${T}`),X}async onTeamTaskStart($,Y,T){let q=await this.createTeamTaskSubSession($,Y,T);if(!q)return;let X=this.teamTaskQueueKey($,Y),J=this.teamTaskSessionsByAgent.get(X)??[];J.push(q),this.teamTaskSessionsByAgent.set(X,J)}async onTeamTaskEnd($,Y,T,q,X){let J=this.teamTaskQueueKey($,Y),Q=this.teamTaskSessionsByAgent.get(J);if(!Q||Q.length===0)return;let U=Q.shift();if(Q.length===0)this.teamTaskSessionsByAgent.delete(J);else this.teamTaskSessionsByAgent.set(J,Q);if(!U)return;if(X)await this.persistSessionMessages(U,X);await this.appendSubagentTranscriptLine(U,q??`[done] ${T}`),await this.applySubagentStatusBySessionId(U,T)}async handleSubAgentStart($,Y){let T=await this.upsertSubagentSession({agentId:Y.subAgentId,parentAgentId:Y.parentAgentId,conversationId:Y.conversationId,prompt:Y.input.task,rootSessionId:$});if(!T)return;await this.appendSubagentTranscriptLine(T,`[start] ${Y.input.task}`),await this.applySubagentStatusBySessionId(T,"running")}async handleSubAgentEnd($,Y){let T=await this.upsertSubagentSession({agentId:Y.subAgentId,parentAgentId:Y.parentAgentId,conversationId:Y.conversationId,prompt:Y.input.task,rootSessionId:$});if(!T)return;if(Y.error){await this.appendSubagentTranscriptLine(T,`[error] ${Y.error.message}`),await this.applySubagentStatusBySessionId(T,"failed");return}if(await this.appendSubagentTranscriptLine(T,`[done] ${Y.result?.finishReason??"completed"}`),Y.result?.finishReason==="aborted"){await this.applySubagentStatusBySessionId(T,"cancelled");return}await this.applySubagentStatusBySessionId(T,"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($)),T=Math.min(Y*5,2000),q=await this.adapter.listSessions({limit:T}),X=q.filter((J)=>J.status==="running"&&!this.isPidAlive(J.pid));if(X.length>0){for(let J of X)await this.updateSessionStatus(J.session_id,"failed",1);q=await this.adapter.listSessions({limit:T})}return q.slice(0,Y)}async deleteSession($){let Y=$.trim();if(!Y)throw Error("session id is required");let T=await this.adapter.getSession(Y);if(!T)return{deleted:!1};if(await this.adapter.deleteSession(Y,!1),!T.is_subagent){let q=await this.adapter.listSessions({limit:2000,parentSessionId:Y});await this.adapter.deleteSession(Y,!0);for(let X of q)$$(X.transcript_path),$$(X.hook_path),$$(X.messages_path),$$(this.sessionManifestPath(X.session_id,!1)),this.artifacts.removeSessionDirIfEmpty(X.session_id)}return $$(T.transcript_path),$$(T.hook_path),$$(T.messages_path),$$(this.sessionManifestPath(Y,!1)),this.artifacts.removeSessionDirIfEmpty(Y),{deleted:!0}}}function p3($){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 qj($){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??W0()}}class l3{client;constructor($){this.client=$}ensureSessionsDir(){return""}async upsertSession($){await this.client.upsertSession(qj($))}async getSession($){let Y=await this.client.getSession($);return Y?p3(Y):void 0}async listSessions($){return(await this.client.listSessions($)).map((T)=>p3(T))}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 E9 extends R6{sessionsDirPath;client;constructor($){let Y=new xJ({address:$.address?.trim()||"127.0.0.1:4317"});super(new l3(Y));this.sessionsDirPath=$.sessionsDir,this.client=Y}ensureSessionsDir(){if(!Yj(this.sessionsDirPath))Tj(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}close(){this.client.close()}}import{spawn as Zj}from"node:child_process";import{existsSync as a3,mkdirSync as Kj,readFileSync as Aj,writeFileSync as Wj}from"node:fs";import{resolve as o3}from"node:path";import{nanoid as Gj}from"nanoid";import{existsSync as Xj,mkdirSync as Jj}from"node:fs";import{join as Qj}from"node:path";function Uj(){return G$()}class JT{sessionsDirPath;db;constructor($={}){this.sessionsDirPath=$.sessionsDir??Uj()}init(){this.getRawDb()}ensureSessionsDir(){if(!Xj(this.sessionsDirPath))Jj(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return Qj(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let $=NY(this.sessionDbPath());return P8($,{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 (
587
+ session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
588
+ provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
589
+ parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
590
+ metadata_json, transcript_path, hook_path, messages_path, updated_at
591
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,0,e0($.interactive),$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,e0($.enableTools),e0($.enableSpawn),e0($.enableTeams),$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,e0($.isSubagent),$.prompt??null,$.metadata?JSON.stringify($.metadata):null,$.transcriptPath??"",$.hookPath??"",$.messagesPath??null,Y])}update($){let Y=[],T=[];if($.endedAt!==void 0)Y.push("ended_at = ?"),T.push($.endedAt);if($.exitCode!==void 0)Y.push("exit_code = ?"),T.push($.exitCode);if($.status!==void 0)Y.push("status = ?"),T.push($.status);if($.prompt!==void 0)Y.push("prompt = ?"),T.push($.prompt);if($.metadata!==void 0)Y.push("metadata_json = ?"),T.push($.metadata?JSON.stringify($.metadata):null);if($.parentSessionId!==void 0)Y.push("parent_session_id = ?"),T.push($.parentSessionId);if($.parentAgentId!==void 0)Y.push("parent_agent_id = ?"),T.push($.parentAgentId);if($.agentId!==void 0)Y.push("agent_id = ?"),T.push($.agentId);if($.conversationId!==void 0)Y.push("conversation_id = ?"),T.push($.conversationId);if(Y.length===0)return;Y.push("updated_at = ?"),T.push(O0()),T.push($.sessionId),this.run(`UPDATE sessions SET ${Y.join(", ")} WHERE session_id = ?`,T)}updateStatus($,Y,T){this.update({sessionId:$,status:Y,endedAt:Y==="running"?null:O0(),exitCode:Y==="running"?null:T??(Y==="failed"?1:0)})}get($){let Y=this.queryOne(`SELECT session_id, source, pid, started_at, ended_at, exit_code, status, interactive,
592
+ provider, model, cwd, workspace_root, team_name,
593
+ enable_tools, enable_spawn, enable_teams,
594
+ parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent,
595
+ prompt, metadata_json, transcript_path, hook_path, messages_path, updated_at
596
+ FROM sessions WHERE session_id = ?`,[$]);if(!Y)return;return{sessionId:Q0(Y.session_id),source:Q0(Y.source),pid:Number(Y.pid??0),startedAt:Q0(Y.started_at),endedAt:Y.ended_at??null,exitCode:Y.exit_code??null,status:Q0(Y.status),interactive:$1(Y.interactive),provider:Q0(Y.provider),model:Q0(Y.model),cwd:Q0(Y.cwd),workspaceRoot:Q0(Y.workspace_root),teamName:K0(Y.team_name),enableTools:$1(Y.enable_tools),enableSpawn:$1(Y.enable_spawn),enableTeams:$1(Y.enable_teams),parentSessionId:K0(Y.parent_session_id),parentAgentId:K0(Y.parent_agent_id),agentId:K0(Y.agent_id),conversationId:K0(Y.conversation_id),isSubagent:$1(Y.is_subagent),prompt:K0(Y.prompt),metadata:(()=>{let T=K0(Y.metadata_json);if(!T)return;try{let q=JSON.parse(T);if(q&&typeof q==="object"&&!Array.isArray(q))return q}catch{}return})(),transcriptPath:K0(Y.transcript_path),hookPath:K0(Y.hook_path),messagesPath:K0(Y.messages_path),updatedAt:K0(Y.updated_at)??O0()}}list($=200){let Y=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[$]),T=[];for(let q of Y){let X=this.get(Q0(q.session_id));if(X)T.push(X)}return T}delete($,Y=!1){let T=this.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(Y)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return T>0}}class n3{store;constructor($){this.store=$}ensureSessionsDir(){return this.store.ensureSessionsDir()}async upsertSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
597
+ session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
598
+ provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
599
+ parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
600
+ metadata_json, transcript_path, hook_path, messages_path, updated_at
601
+ ) 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??W0()])}async getSession($){return this.store.queryOne(`SELECT session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
602
+ provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
603
+ parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
604
+ metadata_json, transcript_path, hook_path, messages_path, updated_at
605
+ FROM sessions WHERE session_id = ?`,[$])??void 0}async listSessions($){let Y=[],T=[];if($.parentSessionId)Y.push("parent_session_id = ?"),T.push($.parentSessionId);if($.status)Y.push("status = ?"),T.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,
606
+ provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
607
+ parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
608
+ metadata_json, transcript_path, hook_path, messages_path, updated_at
609
+ FROM sessions
610
+ ${q}
611
+ ORDER BY started_at DESC
612
+ LIMIT ?`,[...T,$.limit])}async updateSession($){if($.setRunning){if($.expectedStatusLock===void 0)return{updated:!1,statusLock:0};return{updated:(this.store.run(`UPDATE sessions
613
+ SET status = 'running', ended_at = NULL, exit_code = NULL, updated_at = ?, status_lock = ?,
614
+ parent_session_id = ?, parent_agent_id = ?, agent_id = ?, conversation_id = ?, is_subagent = 1,
615
+ prompt = COALESCE(prompt, ?)
616
+ WHERE session_id = ? AND status_lock = ?`,[W0(),$.expectedStatusLock+1,$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,$.prompt??null,$.sessionId,$.expectedStatusLock]).changes??0)>0,statusLock:$.expectedStatusLock+1}}let Y=[],T=[];if($.status!==void 0)Y.push("status = ?"),T.push($.status);if($.endedAt!==void 0)Y.push("ended_at = ?"),T.push($.endedAt);if($.exitCode!==void 0)Y.push("exit_code = ?"),T.push($.exitCode);if($.prompt!==void 0)Y.push("prompt = ?"),T.push($.prompt??null);if($.metadataJson!==void 0)Y.push("metadata_json = ?"),T.push($.metadataJson??null);if($.parentSessionId!==void 0)Y.push("parent_session_id = ?"),T.push($.parentSessionId??null);if($.parentAgentId!==void 0)Y.push("parent_agent_id = ?"),T.push($.parentAgentId??null);if($.agentId!==void 0)Y.push("agent_id = ?"),T.push($.agentId??null);if($.conversationId!==void 0)Y.push("conversation_id = ?"),T.push($.conversationId??null);if(Y.length===0){let Q=await this.getSession($.sessionId);return{updated:!!Q,statusLock:Q?.status_lock??0}}let q=0;if($.expectedStatusLock!==void 0)q=$.expectedStatusLock+1,Y.push("status_lock = ?"),T.push(q);Y.push("updated_at = ?"),T.push(W0());let X=`UPDATE sessions SET ${Y.join(", ")} WHERE session_id = ?`;if(T.push($.sessionId),$.expectedStatusLock!==void 0)X+=" AND status_lock = ?",T.push($.expectedStatusLock);if((this.store.run(X,T).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 T=this.store.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(Y)this.store.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return T>0}async enqueueSpawnRequest($){this.store.run(`INSERT INTO subagent_spawn_queue (root_session_id, parent_agent_id, task, system_prompt, created_at, consumed_at)
617
+ VALUES (?, ?, ?, ?, ?, NULL)`,[$.rootSessionId,$.parentAgentId,$.task??null,$.systemPrompt??null,W0()])}async claimSpawnRequest($,Y){let T=this.store.queryOne(`SELECT id, task FROM subagent_spawn_queue
618
+ WHERE root_session_id = ? AND parent_agent_id = ? AND consumed_at IS NULL
619
+ ORDER BY id ASC LIMIT 1`,[$,Y]);if(!T||typeof T.id!=="number")return;return this.store.run("UPDATE subagent_spawn_queue SET consumed_at = ? WHERE id = ?",[W0(),T.id]),T.task??void 0}}class V9 extends R6{store;constructor($){super(new n3($));this.store=$}createRootSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
620
+ session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
621
+ provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
622
+ parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
623
+ metadata_json, transcript_path, hook_path, messages_path, updated_at
624
+ ) 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,W0()])}}var Ej=process.env.CLINE_RPC_ADDRESS?.trim()||b3(),a1,O6;function Vj($){let Y=process.execPath,T=process.argv[1]?.trim();if(!T)return;let q=o3(process.cwd(),T);if(!a3(q))return;let X=process.execArgv.find((U)=>U.startsWith("--conditions=")),J=[...X?[X]:[],q,"rpc","start","--address",$];Zj(Y,J,{detached:!0,stdio:"ignore",env:{...process.env,CLINE_NO_INTERACTIVE:"1"},cwd:process.cwd()}).unref()}async function i3($){try{if(!await _3($))return;return new E9({address:$,sessionsDir:G$()})}catch{return}}function r3(){return new V9(new JT)}function Dj($){if(typeof $==="string"&&$.trim().length>0)return $.trim();let Y=G$(),T=o3(Y,"machine-id");try{if(a3(T)){let X=Aj(T,"utf8").trim();if(X.length>0)return X}}catch{}let q=Gj();try{Kj(Y,{recursive:!0}),Wj(T,q,"utf8")}catch{}return q}async function s3($){if(a1)return a1;if(O6)return await O6;let Y=$.backendMode??"auto",T=$.rpcAddress?.trim()||Ej,q=Math.max(1,$.rpcConnectAttempts??5),X=Math.max(0,$.rpcConnectDelayMs??100),J=$.autoStartRpcServer!==!1;return O6=(async()=>{if(Y==="local")return a1=r3(),a1;let Q=await i3(T);if(Q)return a1=Q,a1;if(Y==="rpc")throw Error(`RPC backend unavailable at ${T}`);if(J){try{Vj(T)}catch{}for(let U=0;U<q;U+=1){let Z=await i3(T);if(Z)return a1=Z,a1;if(X>0)await new Promise((K)=>setTimeout(K,X))}}return a1=r3(),a1})().finally(()=>{O6=void 0}),await O6}async function Fj($){let Y=$.sessionService??await s3($);return new v8({sessionService:Y,defaultToolExecutors:$.defaultToolExecutors,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval,distinctId:Dj($.distinctId)})}class mJ{store;constructor($={}){this.store=new JT({sessionsDir:$.sessionsDir})}init(){this.store.init()}upsertSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
625
+ session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
626
+ provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
627
+ parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
628
+ metadata_json, transcript_path, hook_path, messages_path, updated_at
629
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,$.statusLock,e0($.interactive),$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,e0($.enableTools),e0($.enableSpawn),e0($.enableTeams),$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,e0($.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,
630
+ provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
631
+ parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
632
+ metadata_json, transcript_path, hook_path, messages_path, updated_at
633
+ FROM sessions WHERE session_id = ?`,[$]);if(!Y)return;return{sessionId:Q0(Y.session_id),source:Q0(Y.source),pid:Number(Y.pid??0),startedAt:Q0(Y.started_at),endedAt:Y.ended_at??null,exitCode:Y.exit_code??null,status:Q0(Y.status),statusLock:Number(Y.status_lock??0),interactive:$1(Y.interactive),provider:Q0(Y.provider),model:Q0(Y.model),cwd:Q0(Y.cwd),workspaceRoot:Q0(Y.workspace_root),teamName:K0(Y.team_name),enableTools:$1(Y.enable_tools),enableSpawn:$1(Y.enable_spawn),enableTeams:$1(Y.enable_teams),parentSessionId:K0(Y.parent_session_id),parentAgentId:K0(Y.parent_agent_id),agentId:K0(Y.agent_id),conversationId:K0(Y.conversation_id),isSubagent:$1(Y.is_subagent),prompt:K0(Y.prompt),metadata:(()=>{let T=K0(Y.metadata_json);if(!T)return;try{let q=JSON.parse(T);if(q&&typeof q==="object"&&!Array.isArray(q))return q}catch{}return})(),transcriptPath:Q0(Y.transcript_path),hookPath:Q0(Y.hook_path),messagesPath:K0(Y.messages_path),updatedAt:Q0(Y.updated_at)||O0()}}listSessions($){let Y=[],T=[];if($.parentSessionId)Y.push("parent_session_id = ?"),T.push($.parentSessionId);if($.status)Y.push("status = ?"),T.push($.status);let q=Y.length>0?`WHERE ${Y.join(" AND ")}`:"",X=Math.max(1,Math.floor($.limit)),J=this.store.queryAll(`SELECT session_id FROM sessions ${q} ORDER BY started_at DESC LIMIT ?`,[...T,X]),Q=[];for(let U of J){if(!U.session_id)continue;let Z=this.getSession(U.session_id);if(Z)Q.push(Z)}return Q}updateSession($){let 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 T=Y.statusLock+1,q=$.setRunning?"running":$.status??Y.status,X=$.setRunning===!0?null:$.endedAt!==void 0?$.endedAt:Y.endedAt??null,J=$.setRunning===!0?null:$.exitCode!==void 0?$.exitCode:Y.exitCode??null,Q=$.prompt!==void 0?$.prompt??void 0:Y.prompt,U=$.metadata!==void 0?$.metadata??void 0:Y.metadata;return this.store.run(`UPDATE sessions
634
+ SET status = ?, ended_at = ?, exit_code = ?, prompt = ?, metadata_json = ?,
635
+ parent_session_id = ?, parent_agent_id = ?, agent_id = ?, conversation_id = ?,
636
+ status_lock = ?, updated_at = ?
637
+ WHERE session_id = ?`,[q,X,J,Q??null,U?JSON.stringify(U):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,T,O0(),$.sessionId]),{updated:!0,statusLock:T}}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)
638
+ VALUES (?, ?, ?, ?, ?, NULL)`,[$.rootSessionId,$.parentAgentId,$.task??null,$.systemPrompt??null,O0()])}claimSpawnRequest($,Y){let T=this.store.queryOne(`SELECT id, root_session_id, parent_agent_id, task, system_prompt, created_at, consumed_at
639
+ FROM subagent_spawn_queue
640
+ WHERE root_session_id = ? AND parent_agent_id = ? AND consumed_at IS NULL
641
+ ORDER BY id ASC LIMIT 1`,[$,Y]);if(!T||typeof T.id!=="number")return;let q=O0();return this.store.run("UPDATE subagent_spawn_queue SET consumed_at = ? WHERE id = ?",[q,T.id]),{id:T.id,rootSessionId:Q0(T.root_session_id),parentAgentId:Q0(T.parent_agent_id),task:K0(T.task),systemPrompt:K0(T.system_prompt),createdAt:Q0(T.created_at),consumedAt:q}}}function Nj($={}){return new mJ($)}import{basename as Hj,resolve as zj}from"node:path";import Ij from"simple-git";import{z as j1}from"zod";var t3=j1.object({rootPath:j1.string().min(1),hint:j1.string().min(1).optional(),associatedRemoteUrls:j1.array(j1.string().min(1)).optional(),latestGitCommitHash:j1.string().min(1).optional(),latestGitBranchName:j1.string().min(1).optional()}),QT=j1.object({currentWorkspacePath:j1.string().min(1).optional(),workspaces:j1.record(j1.string().min(1),t3)});function Mj(){return{workspaces:{}}}function P6($){return zj($)}async function D9($){let Y=P6($),T={rootPath:Y,hint:Hj(Y)};try{let q=Ij({baseDir:Y});if(!await q.checkIsRepo())return T;let J=await q.getRemotes(!0);if(J.length>0){let Z=J.map((K)=>{let A=K.refs.fetch||K.refs.push;return`${K.name}: ${A}`});T.associatedRemoteUrls=Z}let Q=(await q.revparse(["HEAD"])).trim();if(Q.length>0)T.latestGitCommitHash=Q;let U=(await q.branch()).current.trim();if(U.length>0)T.latestGitBranchName=U}catch{}return T}function fJ($,Y){let T={...$,workspaces:{...$.workspaces,[Y.rootPath]:Y}};if(!T.currentWorkspacePath)T.currentWorkspacePath=Y.rootPath;return QT.parse(T)}async function Bj($){let Y=await D9($),T={workspaces:{[Y.rootPath]:{hint:Y.hint,associatedRemoteUrls:Y.associatedRemoteUrls,latestGitCommitHash:Y.latestGitCommitHash,latestGitBranchName:Y.latestGitBranchName}}};return`# Workspace Configuration
642
+ ${JSON.stringify(T,null,2)}`}class e3{manifest;listeners=new Set;constructor($){this.manifest=QT.parse($??{workspaces:{}})}async addWorkspacePath($){let Y=await D9($);return this.manifest=fJ(this.manifest,Y),this.emit({type:"workspace_added",workspace:Y}),Y}async switchWorkspace($){let Y=P6($),T=this.manifest.workspaces[Y];if(T)return this.manifest=QT.parse({...this.manifest,currentWorkspacePath:Y}),this.emit({type:"workspace_switched",workspace:T}),T;let q=await this.addWorkspacePath(Y);return this.manifest=QT.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=P6($);return this.manifest.workspaces[Y]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit($){for(let Y of this.listeners)Y($)}}export{fJ as upsertWorkspaceInfo,w8 as toTeamProgressLifecycleEvent,Y8 as toPartialAgentConfig,b9 as toHookConfigFileName,b$ as startLocalOAuthServer,S6 as setHomeDirIfUnset,nJ as setHomeDir,IH as saveLocalProviderSettings,OH as saveLocalProviderOAuthCredentials,M6 as sanitizeSessionToken,$4 as resolveWorkflowsConfigSearchPaths,lH as resolveWorkflowSlashCommandFromWatcher,t9 as resolveSkillsConfigSearchPaths,G$ as resolveSessionDataDir,s3 as resolveSessionBackend,e9 as resolveRulesConfigSearchPaths,p9 as resolvePluginConfigSearchPaths,z4 as resolveMcpServerRegistrations,PH as resolveLocalClineAuthToken,m9 as resolveHooksConfigSearchPaths,eJ as resolveHookLogPath,ET as resolveDocumentsWorkflowsDirectoryPath,GT as resolveDocumentsRulesDirectoryPath,WT as resolveDocumentsHooksDirectoryPath,R8 as resolveDefaultMcpSettingsPath,t0 as resolveClineDataDir,U8 as resolveAndLoadAgentPlugins,$8 as resolveAgentTools,l9 as resolveAgentPluginPaths,cH as requestDesktopToolApproval,NU as registerMcpServersFromSettingsFile,A4 as refreshOpenAICodexToken,E4 as refreshOcaToken,Z4 as refreshClineToken,IQ as prewarmFileIndex,s9 as parseWorkflowConfigFromMarkdown,a9 as parseSkillConfigFromMarkdown,o9 as parseRuleConfigFromMarkdown,_9 as parsePartialAgentConfigFromYaml,GY as parseAgentConfigFromYaml,UN as openaiCodexOAuthProvider,P6 as normalizeWorkspacePath,v6 as normalizeUserInput,QN as normalizeOpenAICodexCredentials,MH as normalizeOAuthProvider,B4 as migrateLegacyProviderSettings,hJ as makeTeamTaskSubSessionId,G9 as makeSubSessionId,I8 as loginOpenAICodex,B8 as loginOcaOAuth,RH as loginLocalProvider,H8 as loginClineOAuth,LH as loadRulesForSystemPromptFromWatcher,H4 as loadMcpSettingsFile,X8 as loadAgentPluginsFromPaths,u9 as loadAgentPluginFromPath,HH as listLocalProviders,q8 as listHookConfigFiles,xU as listEnabledRulesFromWatcher,bU as listAvailableWorkflowsFromWatcher,jU as isRuleEnabled,UU as isRpcClineAccountActionRequest,JN as isOpenAICodexTokenExpired,FU as hasMcpSettingsFile,W4 as getValidOpenAICodexCredentials,V4 as getValidOcaCredentials,K4 as getValidClineCredentials,zH as getLocalProviderModels,g$ as getFileIndex,Zh as getClineDefaultSystemPrompt,D9 as generateWorkspaceInfo,QU as generateOcaOpcRequestId,vU as formatRulesForSystemPrompt,ZU as executeRpcClineAccountAction,FT as ensureParentDir,iJ as ensureHookLogDir,VH as ensureCustomProvidersLoaded,a6 as enrichPromptWithMentions,Mj as emptyWorkspaceManifest,FY as emptyStoredProviderSettings,Q8 as discoverPluginModulePaths,_J as deriveSubsessionStatus,q4 as createWorkflowsConfigDefinition,E8 as createUserInstructionConfigWatcher,RQ as createToolPoliciesWithPreset,Uh as createTool,mU as createTeamName,Nj as createSqliteRpcSessionBackend,Y4 as createSkillsConfigDefinition,Fj as createSessionHost,T4 as createRulesConfigDefinition,HN as createOcaRequestHeaders,NN as createOcaOAuthProvider,X4 as createOAuthClientCallbacks,OQ as createDefaultToolsWithPreset,AY as createDefaultTools,e6 as createDefaultExecutors,eF as createClineOAuthProvider,NT as createBuiltinTools,CQ as createAgentConfigWatcher,g9 as createAgentConfigDefinition,Bj as buildWorkspaceMetadata,L8 as buildTeamProgressSummary,NH as addLocalProvider,QT as WorkspaceManifestSchema,t3 as WorkspaceInfoSchema,KT as WORKFLOWS_CONFIG_DIRECTORY_NAME,f$ as UnifiedConfigFileWatcher,t1 as ToolPresets,J8 as SubprocessSandbox,O8 as StoredProviderSettingsSchema,zU as StoredProviderSettingsEntrySchema,BT as SqliteTeamStore,JT as SqliteSessionStore,mJ as SqliteRpcSessionBackend,RT as SessionSource,H1 as SKILLS_CONFIG_DIRECTORY_NAME,O4 as SESSION_STATUSES,E9 as RpcCoreSessionService,F4 as RpcClineAccountService,ZT as RULES_CONFIG_DIRECTORY_NAME,x6 as RPC_TEAM_PROGRESS_EVENT_TYPE,k6 as RPC_TEAM_LIFECYCLE_EVENT_TYPE,d$ as ProviderSettingsManager,eQ as OCI_HEADER_OPC_REQUEST_ID,e3 as InMemoryWorkspaceManager,I4 as InMemoryMcpManager,T8 as HookConfigFileName,f9 as HOOK_CONFIG_FILE_EVENT_MAP,UT as HOOKS_CONFIG_DIRECTORY_NAME,v1 as DefaultToolNames,v8 as DefaultSessionManager,S8 as DefaultRuntimeBuilder,rQ as DEFAULT_INTERNAL_OCA_BASE_URL,nQ as DEFAULT_INTERNAL_IDCS_URL,iQ as DEFAULT_INTERNAL_IDCS_SCOPES,lQ as DEFAULT_INTERNAL_IDCS_CLIENT_ID,tQ as DEFAULT_EXTERNAL_OCA_BASE_URL,oQ as DEFAULT_EXTERNAL_IDCS_URL,sQ as DEFAULT_EXTERNAL_IDCS_SCOPES,aQ as DEFAULT_EXTERNAL_IDCS_CLIENT_ID,V9 as CoreSessionService,D4 as ClineAccountService,zN as ChatViewStateSchema,EU as ChatSummarySchema,AU as ChatSessionStatusSchema,KU as ChatSessionConfigSchema,GU as ChatMessageSchema,WU as ChatMessageRoleSchema,_$ as ALL_DEFAULT_TOOL_NAMES};