@juspay/neurolink 13.8.23 → 13.8.24

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.
@@ -120,7 +120,7 @@ Answer false when: ${Gp(r)}`)}}if(e.type==="choice")return{type:"choice",instruc
120
120
 
121
121
  *Using a platform specific import* - Make sure your code imports either '@google/genai/web' or '@google/genai/node' instead of '@google/genai'.
122
122
  `)}async function fen(e,t,r,n){var o;const i=await mHe(e,t,r,n),s=await i?.json();if(((o=i?.headers)===null||o===void 0?void 0:o[LA])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return s.file}async function gen(e,t,r,n){var o;const i=await mHe(e,t,r,n),s=await i?.json();if(((o=i?.headers)===null||o===void 0?void 0:o[LA])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");const a=BVe(s),u=new ZX;return Object.assign(u,a),u}async function mHe(e,t,r,n){var o,i,s;let a=t;const u=n?.baseUrl||((o=r.clientOptions.httpOptions)===null||o===void 0?void 0:o.baseUrl);if(u){const m=new URL(u),h=new URL(t);h.protocol=m.protocol,h.host=m.host,h.port=m.port,a=h.toString()}let l=0,c=0,d=new a0(new Response),p="upload";for(l=e.size;c<l;){const m=Math.min(zKe,l-c),h=e.slice(c,c+m);c+m>=l&&(p+=", finalize");let g=0,y=qKe;for(;g<GKe;){const v=Object.assign(Object.assign({},n?.headers||{}),{"X-Goog-Upload-Command":p,"X-Goog-Upload-Offset":String(c)});if(d=await r.request({path:"",body:h,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},n),{apiVersion:"",baseUrl:a,headers:v})}),!((i=d?.headers)===null||i===void 0)&&i[LA])break;g++,await ven(y),y=y*jKe}if(c+=m,((s=d?.headers)===null||s===void 0?void 0:s[LA])!=="active")break;if(l<=c)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return d}async function yen(e){return{size:e.size,type:e.type}}function ven(e){return new Promise(t=>setTimeout(t,e))}function wen(e){const t={},r=b(e,["file"]);return r!=null&&_(t,["file"],r),t}function ben(e){const t={},r=b(e,["sdkHttpResponse"]);return r!=null&&_(t,["sdkHttpResponse"],r),t}function Ten(e){const t={},r=b(e,["name"]);return r!=null&&_(t,["_url","file"],ZVe(r)),t}function _en(e){const t={},r=b(e,["sdkHttpResponse"]);return r!=null&&_(t,["sdkHttpResponse"],r),t}function Een(e){const t={},r=b(e,["name"]);return r!=null&&_(t,["_url","file"],ZVe(r)),t}function Sen(e){const t={},r=b(e,["uris"]);return r!=null&&_(t,["uris"],r),t}function ken(e,t){const r={},n=b(e,["pageSize"]);t!==void 0&&n!=null&&_(t,["_query","pageSize"],n);const o=b(e,["pageToken"]);return t!==void 0&&o!=null&&_(t,["_query","pageToken"],o),r}function Aen(e){const t={},r=b(e,["config"]);return r!=null&&ken(r,t),t}function Cen(e){const t={},r=b(e,["sdkHttpResponse"]);r!=null&&_(t,["sdkHttpResponse"],r);const n=b(e,["nextPageToken"]);n!=null&&_(t,["nextPageToken"],n);const o=b(e,["files"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(s=>s)),_(t,["files"],i)}return t}function xen(e){const t={},r=b(e,["sdkHttpResponse"]);r!=null&&_(t,["sdkHttpResponse"],r);const n=b(e,["files"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(i=>i)),_(t,["files"],o)}return t}function Ien(e,t){const r={},n=b(e,["force"]);return t!==void 0&&n!=null&&_(t,["_query","force"],n),r}function Ren(e){const t={},r=b(e,["name"]);r!=null&&_(t,["_url","name"],r);const n=b(e,["config"]);return n!=null&&Ien(n,t),t}function Men(e){const t={},r=b(e,["name"]);return r!=null&&_(t,["_url","name"],r),t}function Pen(e,t){const r={},n=b(e,["pageSize"]);t!==void 0&&n!=null&&_(t,["_query","pageSize"],n);const o=b(e,["pageToken"]);return t!==void 0&&o!=null&&_(t,["_query","pageToken"],o),r}function Den(e){const t={},r=b(e,["parent"]);r!=null&&_(t,["_url","parent"],r);const n=b(e,["config"]);return n!=null&&Pen(n,t),t}function Oen(e){const t={},r=b(e,["sdkHttpResponse"]);r!=null&&_(t,["sdkHttpResponse"],r);const n=b(e,["nextPageToken"]);n!=null&&_(t,["nextPageToken"],n);const o=b(e,["documents"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(s=>s)),_(t,["documents"],i)}return t}function Nen(){return"Deno"in globalThis}function CA(){var e,t,r,n,o,i;if($A)return $A;const s=globalThis;let a={};return Nen()?a=(n=(r=(t=(e=s.Deno)===null||e===void 0?void 0:e.env)===null||t===void 0?void 0:t.toObject)===null||r===void 0?void 0:r.call(t))!==null&&n!==void 0?n:{}:a=(i=(o=s.process)===null||o===void 0?void 0:o.env)!==null&&i!==void 0?i:{},$A=a,$A}function Len(e){var t,r;const n=Object.assign({},e),o=CA();return typeof o.GOOGLE_GENAI_API_VERSION<"u"&&((t=n.api_version)!==null&&t!==void 0||(n.api_version=o.GOOGLE_GENAI_API_VERSION)),typeof o.GOOGLE_GENAI_USER_PROJECT<"u"&&((r=n.user_project)!==null&&r!==void 0||(n.user_project=o.GOOGLE_GENAI_USER_PROJECT)),n}function $en(e){const[,t,...r]=e.pathname.split("/");if(!t)return e;const n=decodeURIComponent(t);if(!n.includes("/"))return e;const o=new URL(e);return o.pathname=`/${n}/${r.join("/")}`,o}async function Fen(e,t){if(yHe(e))return e.resolveGoogleGenAISecurity(t);const r=typeof e=="function"?await e():e;return gHe(r)?hHe(r):hHe(void 0)}function Uen(e){var t,r;if(yHe(e))return(r=(t=e.getDefaultHeaders)===null||t===void 0?void 0:t.call(e))!==null&&r!==void 0?r:e.defaultHeaders;if(gHe(e))return e.default_headers}function hHe(e){var t,r;const n=CA(),o=Object.assign(Object.assign({},e),{api_key:(t=e?.api_key)!==null&&t!==void 0?t:n.GOOGLE_GENAI_API_KEY,access_token:(r=e?.access_token)!==null&&r!==void 0?r:n.GOOGLE_GENAI_ACCESS_TOKEN});return vHe(o)?o:void 0}function Ben(e){var t,r;const n={};for(const[i,s]of e){const a=i.toLowerCase();a!=="authorization"&&a!=="x-goog-api-key"&&(n[i]=s)}const o={access_token:(t=e.get("authorization"))!==null&&t!==void 0?t:void 0,api_key:(r=e.get("x-goog-api-key"))!==null&&r!==void 0?r:void 0,default_headers:Object.keys(n).length?n:void 0};return vHe(o)?o:void 0}function fHe(e,t){if(t)for(const[r,n]of new Headers(t))e.get(r)===null&&e.set(r,n)}function zen(e,t){e.options.user_project!==void 0&&t.get("x-goog-user-project")===null&&t.set("x-goog-user-project",e.options.user_project)}function Gen(e,t){if(t){if(t.api_key){e.set("x-goog-api-key",t.api_key);return}t.access_token&&e.set("Authorization",jen(t.access_token))}}function qen(e){return e.get("authorization")!==null||e.get("x-goog-api-key")!==null}function jen(e){return e.slice(0,7).toLowerCase()==="bearer "?e:`Bearer ${e}`}function gHe(e){return typeof e=="object"&&e!==null}function yHe(e){return typeof e=="object"&&e!==null&&"resolveGoogleGenAISecurity"in e&&typeof e.resolveGoogleGenAISecurity=="function"}function vHe(e){return e.api_key!==void 0||e.access_token!==void 0||e.default_headers!==void 0}function Ven(){var e,t;return typeof((t=(e=globalThis.process)===null||e===void 0?void 0:e.versions)===null||t===void 0?void 0:t.node)=="string"}function Hen(e){if(!e||typeof e!="object")return!1;if("options"in e){const t=e.options;return!!t?.fetcher}return!0}function Wen(){return{dispatch(e,t){const r=globalThis[JKe];if(!r||typeof r.dispatch!="function")throw new TypeError("Undici globalDispatcher is not available in this Node.js runtime.");return r.dispatch(Object.assign(Object.assign({},e),{headersTimeout:0,bodyTimeout:0}),t)}}}function i0(e){return Qen(e)?e:Ken(e)?Jen(e):e instanceof u0?Xen(e):e}function Ken(e){return e instanceof Tc?!0:e instanceof Error&&typeof e.statusCode=="number"&&typeof e.body=="string"}function Jen(e){const t=Yen(e),r=Uu.generate(e.statusCode,t,e.message,e.headers);return xA(r,"body",e.body),xA(r,"contentType",e.contentType),xA(r,"rawResponse",e.rawResponse),xA(r,"statusCode",e.statusCode),xA(r,"cause",e),r}function Xen(e){return e instanceof aY?new eJe({message:e.message}):e instanceof sY?new QKe({message:e.message}):e instanceof uY?new UA({message:e.message,cause:e}):new UA({message:e.message,cause:e})}function Yen(e){const t=wHe(e,"data$");if(t&&typeof t=="object")return t;try{const n=JSON.parse(e.body);if(n&&typeof n=="object")return n}catch{}const r=wHe(e,"error");return r&&typeof r=="object"?r:void 0}function wHe(e,t){return e&&typeof e=="object"?e[t]:void 0}function bHe(e){if(!e)return"";try{return JSON.stringify(e)}catch{return String(e)}}function Zen(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Qen(e){return typeof e=="object"&&e!==null?Uu.prototype.isPrototypeOf(e):!1}function xA(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:r,writable:!1})}function hb(e,t){var r;if(t==="*")return!0;let n=((r=e.headers.get("content-type"))===null||r===void 0?void 0:r.trim())||"application/octet-stream";n=n.toLowerCase();const o=t.toLowerCase().trim().split(cY),[i="",...s]=o;if(i.split("/").length!==2)return!1;const a=n.split(cY),[u="",...l]=a,[c="",d=""]=u.split("/");if(!c||!d||i!=="*/*"&&u!==i&&`${c}/*`!==i&&`*/${d}`!==i||l.length<s.length)return!1;const p=new Set(l);for(const m of s)if(!p.has(m))return!1;return!0}function mr(e,t){const r=`${e.status}`,n=Array.isArray(t)?t:[t];return n.length?n.some(o=>{const i=`${o}`;if(i==="default")return!0;if(!cJe.test(`${i}`))return i===r;const s=i.charAt(0);if(!s)throw new Error("Invalid status code range");const a=r.charAt(0);if(!a)throw new Error(`Invalid response status code: ${r}`);return a===s}):!1}function etn(e,t,r){return mr(e,t)&&hb(e,r)}function THe(e){if(typeof e!="object"||e==null)return!1;const t=e instanceof TypeError&&e.message.toLowerCase().startsWith("failed to fetch"),r=e instanceof TypeError&&e.message.toLowerCase().startsWith("fetch failed"),n="name"in e&&e.name==="ConnectionError",o="code"in e&&typeof e.code=="string"&&e.code.toLowerCase()==="econnreset";return t||r||o||n}function _He(e){if(typeof e!="object"||e==null)return!1;const t="name"in e&&e.name==="TimeoutError",r="code"in e&&e.code===23,n="code"in e&&typeof e.code=="string"&&e.code.toLowerCase()==="econnaborted";return t||r||n}function ttn(e){if(typeof e!="object"||e==null)return!1;const t="name"in e&&e.name==="AbortError",r="code"in e&&e.code===20,n="code"in e&&typeof e.code=="string"&&e.code.toLowerCase()==="econnaborted";return t||r||n}function rtn(e){const t=new YKe;e.registerBeforeCreateRequestHook(t),e.registerBeforeRequestHook(t)}function EHe(e){return{ok:!0,value:e}}function Vp(e){return{ok:!1,error:e}}function uJ(e){return btoa(String.fromCodePoint(...e))}function ntn(e){return new TextEncoder().encode(e)}function otn(e){return uJ(ntn(e))}function Tr(e,t){const r=/\{([a-zA-Z0-9_][a-zA-Z0-9_-]*?)\}/g;return function(o={}){return e.replace(r,function(i,s){if(!dJe.call(o,s))throw new Error(`Parameter '${s}' is required`);const a=o[s];if(typeof a!="string"&&typeof a!="number")throw new Error(`Parameter '${s}' must be a string or number`);return`${a}`}).replace(/^\/+/,"")}}function itn(e){var t;let r=e.server_url;const n={};if(!r){const i=(t=e.server_idx)!==null&&t!==void 0?t:0;if(i<0||i>=pY.length)throw new Error(`Invalid server index ${i}`);r=pY[i]||""}const o=Tr(r)(n);return new URL(o)}function stn(...e){const t=[];for(const r of e)r&&t.push(r);switch(t.length){case 0:case 1:return t[0]||null;default:return"any"in AbortSignal&&typeof AbortSignal.any=="function"?AbortSignal.any(t):atn(t)}}function atn(e){const t=new AbortController,r=t.signal;if(!e.length)return t.signal;if(e.length===1)return e[0]||t.signal;for(const s of e)if(s.aborted)return s;function n(){t.abort(this.reason),i()}const o=[];function i(){for(const s of o){const a=s.deref();a&&a.removeEventListener("abort",n)}}for(const s of e)o.push(new WeakRef(s)),s.addEventListener("abort",n);return r}function Ar(e){const t={};for(const[r,n]of Object.entries(e))typeof n<"u"&&(t[r]=n);return t}function Ih(e){if(e===null||typeof e!="object"||Object.prototype.toString.call(e)!=="[object Object]")return!1;const t=Object.getPrototypeOf(e);if(t===null||t===Object.prototype)return!0;try{return Object.getPrototypeOf(t)===null}catch{return!1}}function SHe(e,t){return pO(e,t==="percentExceptReserved"?"percent":t)}function pO(e,t){switch(t){case"percent":return encodeURIComponent(e);case"percentExceptReserved":return encodeURIComponent(e).replace(mJe,r=>decodeURIComponent(r));default:return e}}function utn(e){return(t,r,n)=>{let o="";const i=n?.explode?kHe(t,r):[[t,r]];if(i.every(([l,c])=>c==null))return;const s=l=>pO(l,n?.charEncoding),a=l=>s(AHe(l)),u=s(e);return i.forEach(([l,c])=>{var d,p;let m="",h=null;c!=null&&(Array.isArray(c)?h=(d=xHe(c,g=>`${a(g)}`))===null||d===void 0?void 0:d.join(u):Ih(c)?h=(p=IHe(Object.entries(c),([g,y])=>`${s(g)}${u}${a(y)}`))===null||p===void 0?void 0:p.join(u):h=`${a(c)}`,h!=null&&(m=`${SHe(l,n?.charEncoding)}=${h}`,!(!m||m==="=")&&(o+=`&${m}`)))}),o.slice(1)}}function Al(e,t,r){if(typeof t>"u")return;const o=(i=>pO(i,r?.charEncoding))(JSON.stringify(t,CHe));return r?.explode?o:`${SHe(e,r?.charEncoding)}=${o}`}function kHe(e,t){return Array.isArray(t)?t.map(r=>[e,r]):Ih(t)?Object.entries(t??{}).map(([n,o])=>[n,o]):[[e,t]]}function AHe(e){return e==null?"":e instanceof Date?e.toISOString():e instanceof Uint8Array?uJ(e):typeof e=="object"?JSON.stringify(e,CHe):`${e}`}function CHe(e,t){return t instanceof Uint8Array?uJ(t):t}function xHe(e,t){const r=e.reduce((n,o)=>{if(o==null)return n;const i=t(o);return i==null||n.push(i),n},[]);return r.length?r:null}function IHe(e,t){const r=[];for(const[n,o]of e){if(o==null)continue;const i=t([n,o]);i!=null&&r.push(i)}return r.length?r:null}function ltn(...e){return e.filter(Boolean).join("&")}function ctn(e){return function(r,n){var o,i,s;const a=Object.assign(Object.assign({},n),{explode:(o=n?.explode)!==null&&o!==void 0?o:!0,charEncoding:(i=n?.charEncoding)!==null&&i!==void 0?i:"percent"}),u=new Set((s=n?.allowEmptyValue)!==null&&s!==void 0?s:[]),l=Object.entries(r).map(([c,d])=>u.has(c)&&(d==null||d===""||Array.isArray(d)&&d.length===0)?`${encodeURIComponent(c)}=`:e(c,d,a));return ltn(...l)}}async function dtn(e,t){var r;switch(t.config.strategy){case"backoff":return mtn(RHe(e,{statusCodes:t.statusCodes,retryConnectionErrors:!!t.config.retryConnectionErrors}),(r=t.config.backoff)!==null&&r!==void 0?r:hY);case"attempt-count-backoff":return htn(RHe(e,{statusCodes:t.statusCodes,retryConnectionErrors:!!t.config.retryConnectionErrors}),Object.assign(Object.assign({},hY),t.config.backoff),t.config);default:return await e(0)}}function RHe(e,t){return async r=>{try{const n=await e(r);if(ptn(n,t.statusCodes))throw new l0("Response failed with retryable status code",n);return n}catch(n){throw n instanceof l0||t.retryConnectionErrors&&(_He(n)||THe(n))?n:new DO("Permanent error",{cause:n})}}}function ptn(e,t){const r=`${e.status}`;return t.some(n=>{if(!hJe.test(n))return n===r;const o=n.charAt(0);if(!o)throw new Error("Invalid status code range");const i=r.charAt(0);if(!i)throw new Error(`Invalid response status code: ${r}`);return i===o})}async function mtn(e,t){const{maxElapsedTime:r,initialInterval:n,exponent:o,maxInterval:i}=t,s=Date.now();let a=0;for(;;)try{return await e(a)}catch(u){if(u instanceof DO)throw u.cause;if(Date.now()-s>r){if(u instanceof l0)return u.response;throw u}let c=0;u instanceof l0&&(c=MHe(u.response)),c<=0&&(c=n*Math.pow(a,o)+Math.random()*1e3);const d=Math.min(c,i);await PHe(d),a++}}async function htn(e,t,r){let n=0;for(;;)try{return await e(n)}catch(o){if(o instanceof DO)throw o.cause;if(n>=r.maxRetries){if(o instanceof l0)return o.response;throw o}let i=0;o instanceof l0&&(i=MHe(o.response)),i<=0&&(i=t.initialInterval*Math.pow(t.exponent,n)*(1-Math.random()*.25));const s=Math.min(i,t.maxInterval);await PHe(s),n++}}function MHe(e){const t=e.headers.get("retry-after-ms");if(t){const i=Number(t);if(Number.isFinite(i)&&i>=0)return i}const r=e.headers.get("retry-after")||"";if(!r)return 0;const n=Number(r);if(Number.isInteger(n))return n*1e3;const o=Date.parse(r);if(Number.isInteger(o)){const i=o-Date.now();return i>0?Math.ceil(i):0}return 0}async function PHe(e){return new Promise(t=>setTimeout(t,e))}async function ftn(e,t){if(!e)return;const r=t.headers.get("content-type"),n=r?.split(";")[0]||"";e.group(`> Request: ${t.method} ${t.url}`),e.group("Headers:");for(const[o,i]of t.headers.entries())e.log(`${o}: ${i}`);switch(e.groupEnd(),e.group("Body:"),!0){case fY.test(n):e.log(await t.clone().json());break;case n.startsWith("text/"):e.log(await t.clone().text());break;case n==="multipart/form-data":{const o=await t.clone().formData();for(const[i,s]of o){const a=s instanceof Blob?"<Blob>":s;e.log(`${i}: ${a}`)}break}default:e.log(`<${r}>`);break}e.groupEnd(),e.groupEnd()}async function gtn(e,t,r){if(!e)return;const n=t.headers.get("content-type"),o=n?.split(";")[0]||"";e.group(`< Response: ${r.method} ${r.url}`),e.log("Status Code:",t.status,t.statusText),e.group("Headers:");for(const[i,s]of t.headers.entries())e.log(`${i}: ${s}`);switch(e.groupEnd(),e.group("Body:"),!0){case(hb(t,"application/json")||fY.test(o)&&!gY.test(o)):e.log(await t.clone().json());break;case(hb(t,"application/jsonl")||gY.test(o)):case hb(t,"text/event-stream"):e.log(`<${n}>`);break;case hb(t,"text/*"):e.log(await t.clone().text());break;case hb(t,"multipart/form-data"):{const i=await t.clone().formData();for(const[s,a]of i){const u=a instanceof Blob?"<Blob>":a;e.log(`${s}: ${u}`)}break}default:e.log(`<${n}>`);break}e.groupEnd(),e.groupEnd()}function DHe(e){try{return JSON.parse(e)}catch{return e}}function ytn(e,t={}){var r,n;const o=t.flattened===!0,i=(r=t.sentinel)!==null&&r!==void 0?r:"";return new yJe(e,s=>i!==""&&s.data===i?{done:!0,value:void 0}:o?{done:!1,value:s.data==null?void 0:DHe(s.data)}:{done:!1,value:Object.assign(Object.assign({},s),{data:s.data==null?s.data:DHe(s.data)})},{dataRequired:(n=t.dataRequired)!==null&&n!==void 0?n:!0})}function vtn(e,t,r){for(let n=r;n<t;n++)if(!(e[n]!==zu&&e[n]!==Gu))for(const o of vY){if(n+o.length>t)continue;let i=!0;for(let s=0;s<o.length;s++)if(e[n+s]!==o[s]){i=!1;break}if(i)return{index:n,length:o.length}}return null}function wtn(e,t,r,n){const i=new TextDecoder().decode(e).split(/\r\n|\r|\n/),s=[],a={};let u=!0;for(const l of i){if(!l||l.startsWith(":"))continue;u=!1;const c=l.indexOf(":");let d=l,p="";c>0&&(d=l.slice(0,c),p=l[c+1]===" "?l.slice(c+2):l.slice(c+1)),d==="data"?s.push(p):d==="event"?a.event=p:d==="id"&&!p.includes("\0")?r.eventId=p:d==="retry"&&/^\d+$/.test(p)&&(a.retry=Number(p))}if(!u){if(a.id=r.eventId,s.length)a.data=s.join(`
123
- `);else if(n)return;return t(a)}}function Rh(e,t,r){return Object.assign(Object.assign({},r),{err:!0,enc:"json",codes:e,errorClass:t})}function Lr(e,t){return Object.assign(Object.assign({},t),{enc:"json",codes:e})}function OHe(e,t,r){return Object.assign(Object.assign(Object.assign({},r),{enc:"sse",codes:e}),t?{sse:t}:{})}function NHe(e,t){return Object.assign(Object.assign({},t),{enc:"nil",codes:e})}function vt(e){return{enc:"fail",codes:e}}function Cr(...e){return async function(r,n,o){let i,s;for(const p of e){const{codes:m}=p,h="ctype"in p?p.ctype:wJe[p.enc];if(h&&etn(r,m,h)){s=p;break}else if(!h&&mr(r,m)){s=p;break}}if(!s)return[{ok:!1,error:new yY("Unexpected Status or Content-Type",{response:r,request:n,body:await r.text().catch(()=>"")})},i];const a=s.enc;let u="";switch(a){case"json":u=await r.text();try{i=JSON.parse(u)}catch(p){if(!("err"in s))throw p;i=u}break;case"jsonl":i=r.body;break;case"bytes":i=new Uint8Array(await r.arrayBuffer());break;case"stream":i=r.body;break;case"text":u=await r.text(),i=u;break;case"sse":if(r.body){const p="sse"in s&&s.sse||{};i=ytn(r.body,p)}else i=null;break;case"nil":u=await r.text(),i=void 0;break;case"fail":u=await r.text(),i=u;break;default:throw new Error(`Unsupported response type: ${a}`)}if(s.enc==="fail")return[{ok:!1,error:new yY("API error occurred",{request:n,response:r,body:u})},i];const l=s.key||o?.resultKey;let c;const d=s.hdrs?{headers:btn(r.headers)}:null;return"err"in s?c=Object.assign(Object.assign(Object.assign({},o?.extraFields),d),Ih(i)?i:null):l?c=Object.assign(Object.assign(Object.assign({},o?.extraFields),d),{[l]:i}):s.hdrs?c=Object.assign(Object.assign(Object.assign({},o?.extraFields),d),Ih(i)?i:null):c=i,"err"in s?[{ok:!1,error:s.errorClass?new s.errorClass(c,{request:n,response:r,body:u}):c},i]:[{ok:!0,value:c},i]}}function btn(e){const t={};for(const[r,n]of e.entries())t[r]=n.split(bJe);return t}function Ttn(...e){const t={basic:{},headers:{},queryParams:{},cookies:{},oauth2:{type:"none"}},r=e.find(n=>n.every(o=>{if(o.value==null)return!1;if(o.type==="http:basic")return o.value.username!=null||o.value.password!=null;if(o.type==="http:custom")return null;if(o.type==="oauth2:password")return typeof o.value=="string"&&!!o.value;if(o.type==="oauth2:client_credentials")return typeof o.value=="string"?!!o.value:o.value.client_id!=null||o.value.client_secret!=null;if(typeof o.value=="string")return!!o.value;throw new Error(`Unrecognized security type: ${o.type} (value type: ${typeof o.value})`)}));return r==null?null:(r.forEach(n=>{if(n.value==null)return;const{type:o}=n;switch(o){case"apiKey:header":t.headers[n.fieldName]=n.value;break;case"apiKey:query":t.queryParams[n.fieldName]=n.value;break;case"apiKey:cookie":t.cookies[n.fieldName]=n.value;break;case"http:basic":_tn(t,n);break;case"http:custom":break;case"http:bearer":mO(t,n);break;case"oauth2":mO(t,n);break;case"oauth2:password":mO(t,n);break;case"oauth2:client_credentials":break;case"openIdConnect":mO(t,n);break;default:throw TJe.unrecognizedType(o)}}),t)}function _tn(e,t){t.value!=null&&(e.basic=t.value)}function mO(e,t){if(typeof t.value!="string"||!t.value)return;let r=t.value;r.slice(0,7).toLowerCase()!=="bearer "&&(r=`Bearer ${r}`),t.fieldName!==void 0&&(e.headers[t.fieldName]=r)}function xr(e,t){var r,n;let o=[[{fieldName:"accessToken",type:"http:custom",value:(r=e?.access_token)!==null&&r!==void 0?r:CA().GOOGLE_GENAI_ACCESS_TOKEN},{fieldName:"apiKey",type:"http:custom",value:(n=e?.api_key)!==null&&n!==void 0?n:CA().GOOGLE_GENAI_API_KEY},{fieldName:"defaultHeaders",type:"http:custom",value:e?.default_headers}]];return Ttn(...o)}async function Ir(e){if(e!=null)return typeof e=="function"?e():e}function Rr(e){const t=e.$inspect(),r=t.then(([o,i])=>{if(!o.ok)throw o.error;return[o.value,i]}),n=t.then(([o,i])=>{var s;if(!o.ok&&!(!((s=i.response)===null||s===void 0)&&s.ok))throw o.error;return i});return r.catch(()=>{}),n.catch(()=>{}),new fr(r,n)}function LHe(e,t,r,n){return new fr(Etn(e,t,r,n))}async function Etn(e,t,r,n){var o,i,s;const u={body:t,api_version:r},l=Al("body",u.body,{explode:!0}),c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/agents")(c),p=new Headers(Ar({"Content-Type":"application/json",Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"CreateAgent",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"POST",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function $He(e,t,r,n){return new fr(Stn(e,t,r,n))}async function Stn(e,t,r,n){var o,i,s;const u={id:t,api_version:r},l=null,c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),agentsId:gt("agentsId",u.id,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/agents/{agentsId}")(c),p=new Headers(Ar({Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"DeleteAgent",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"DELETE",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function FHe(e,t,r,n){return new fr(ktn(e,t,r,n))}async function ktn(e,t,r,n){var o,i,s;const u={id:t,api_version:r},l=null,c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),agentsId:gt("agentsId",u.id,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/agents/{agentsId}")(c),p=new Headers(Ar({Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"GetAgent",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"GET",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function UHe(e,t,r,n,o,i){return new fr(Atn(e,t,r,n,o,i))}async function Atn(e,t,r,n,o,i){var s,a,u;const c={api_version:t,page_size:r,page_token:n,parent:o},d=null,p={api_version:gt("api_version",(s=c?.api_version)!==null&&s!==void 0?s:e._options.api_version,{explode:!1,charEncoding:"percent"})},m=Tr("/{api_version}/agents")(p),h=Bu({page_size:c?.page_size,page_token:c?.page_token,parent:c?.parent}),g=new Headers(Ar({Accept:"application/json"})),y=await Ir(e._options.security),v=xr(y),w={options:e._options,base_url:(u=(a=i?.server_url)!==null&&a!==void 0?a:e._baseURL)!==null&&u!==void 0?u:"",operation_id:"ListAgents",o_auth2_scopes:null,resolved_security:v,security_source:e._options.security,retry_config:i?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},T=e._createRequest(w,{security:v,method:"GET",baseURL:i?.server_url,path:m,headers:g,query:h,body:d,userAgent:e._options.user_agent,timeout_ms:i?.timeout_ms||e._options.timeout_ms||-1},i);if(!T.ok)return[T,{status:"invalid"}];const E=T.value,k=await e._do(E,{context:w,isErrorStatusCode:R=>mr({status:R},["4XX","5XX"]),retryConfig:w.retry_config,retryCodes:w.retry_codes});if(!k.ok)return[k,{status:"request-error",request:E}];const A=k.value,[C]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(A,E);return C.ok?[C,{status:"complete",request:E,response:A}]:[C,{status:"complete",request:E,response:A}]}function BHe(e,t,r,n){return new fr(Ctn(e,t,r,n))}async function Ctn(e,t,r,n){var o,i,s;const u={body:t,api_version:r},l=Al("body",u.body,{explode:!0}),c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/credentials")(c),p=new Headers(Ar({"Content-Type":"application/json",Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"CreateCredential",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"POST",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function zHe(e,t,r,n){return new fr(xtn(e,t,r,n))}async function xtn(e,t,r,n){var o,i,s;const u={id:t,api_version:r},l=null,c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:gt("id",u.id,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/credentials/{id}")(c),p=new Headers(Ar({Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"DeleteCredential",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"DELETE",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function GHe(e,t,r,n){return new fr(Itn(e,t,r,n))}async function Itn(e,t,r,n){var o,i,s;const u={id:t,api_version:r},l=null,c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:gt("id",u.id,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/credentials/{id}")(c),p=new Headers(Ar({Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"GetCredential",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"GET",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function qHe(e,t,r,n,o){return new fr(Rtn(e,t,r,n,o))}async function Rtn(e,t,r,n,o){var i,s,a;const l={api_version:t,page_size:r,page_token:n},c=null,d={api_version:gt("api_version",(i=l?.api_version)!==null&&i!==void 0?i:e._options.api_version,{explode:!1,charEncoding:"percent"})},p=Tr("/{api_version}/credentials")(d),m=Bu({page_size:l?.page_size,page_token:l?.page_token}),h=new Headers(Ar({Accept:"application/json"})),g=await Ir(e._options.security),y=xr(g),v={options:e._options,base_url:(a=(s=o?.server_url)!==null&&s!==void 0?s:e._baseURL)!==null&&a!==void 0?a:"",operation_id:"ListCredentials",o_auth2_scopes:null,resolved_security:y,security_source:e._options.security,retry_config:o?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},w=e._createRequest(v,{security:y,method:"GET",baseURL:o?.server_url,path:p,headers:h,query:m,body:c,userAgent:e._options.user_agent,timeout_ms:o?.timeout_ms||e._options.timeout_ms||-1},o);if(!w.ok)return[w,{status:"invalid"}];const T=w.value,E=await e._do(T,{context:v,isErrorStatusCode:C=>mr({status:C},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!E.ok)return[E,{status:"request-error",request:T}];const k=E.value,[A]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(k,T);return A.ok?[A,{status:"complete",request:T,response:k}]:[A,{status:"complete",request:T,response:k}]}function jHe(e,t,r,n,o,i){return new fr(Mtn(e,t,r,n,o,i))}async function Mtn(e,t,r,n,o,i){var s,a,u;const c={id:t,body:r,api_version:n,update_mask:o},d=Al("body",c.body,{explode:!0}),p={api_version:gt("api_version",(s=c.api_version)!==null&&s!==void 0?s:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:gt("id",c.id,{explode:!1,charEncoding:"percent"})},m=Tr("/{api_version}/credentials/{id}")(p),h=Bu({update_mask:c.update_mask}),g=new Headers(Ar({"Content-Type":"application/json",Accept:"application/json"})),y=await Ir(e._options.security),v=xr(y),w={options:e._options,base_url:(u=(a=i?.server_url)!==null&&a!==void 0?a:e._baseURL)!==null&&u!==void 0?u:"",operation_id:"UpdateCredential",o_auth2_scopes:null,resolved_security:v,security_source:e._options.security,retry_config:i?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},T=e._createRequest(w,{security:v,method:"PATCH",baseURL:i?.server_url,path:m,headers:g,query:h,body:d,userAgent:e._options.user_agent,timeout_ms:i?.timeout_ms||e._options.timeout_ms||-1},i);if(!T.ok)return[T,{status:"invalid"}];const E=T.value,k=await e._do(E,{context:w,isErrorStatusCode:R=>mr({status:R},["4XX","5XX"]),retryConfig:w.retry_config,retryCodes:w.retry_codes});if(!k.ok)return[k,{status:"request-error",request:E}];const A=k.value,[C]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(A,E);return C.ok?[C,{status:"complete",request:E,response:A}]:[C,{status:"complete",request:E,response:A}]}function VHe(e,t,r,n){return new fr(Ptn(e,t,r,n))}async function Ptn(e,t,r,n){var o,i,s;const u={body:t,api_version:r},l=Al("body",u.body,{explode:!0}),c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/environments")(c),p=new Headers(Ar({"Content-Type":"application/json",Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"CreateEnvironment",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"POST",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function HHe(e,t,r,n){return new fr(Dtn(e,t,r,n))}async function Dtn(e,t,r,n){var o,i,s;const u={id:t,api_version:r},l=null,c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:gt("id",u.id,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/environments/{id}")(c),p=new Headers(Ar({Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"DeleteEnvironment",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"DELETE",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function WHe(e,t,r,n){return new fr(Otn(e,t,r,n))}async function Otn(e,t,r,n){var o,i,s;const u={id:t,api_version:r},l=null,c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:gt("id",u.id,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/environments/{id}")(c),p=new Headers(Ar({Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"GetEnvironment",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"GET",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function KHe(e,t,r,n,o){return new fr(Ntn(e,t,r,n,o))}async function Ntn(e,t,r,n,o){var i,s,a;const l={api_version:t,page_size:r,page_token:n},c=null,d={api_version:gt("api_version",(i=l?.api_version)!==null&&i!==void 0?i:e._options.api_version,{explode:!1,charEncoding:"percent"})},p=Tr("/{api_version}/environments")(d),m=Bu({page_size:l?.page_size,page_token:l?.page_token}),h=new Headers(Ar({Accept:"application/json"})),g=await Ir(e._options.security),y=xr(g),v={options:e._options,base_url:(a=(s=o?.server_url)!==null&&s!==void 0?s:e._baseURL)!==null&&a!==void 0?a:"",operation_id:"ListEnvironments",o_auth2_scopes:null,resolved_security:y,security_source:e._options.security,retry_config:o?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},w=e._createRequest(v,{security:y,method:"GET",baseURL:o?.server_url,path:p,headers:h,query:m,body:c,userAgent:e._options.user_agent,timeout_ms:o?.timeout_ms||e._options.timeout_ms||-1},o);if(!w.ok)return[w,{status:"invalid"}];const T=w.value,E=await e._do(T,{context:v,isErrorStatusCode:C=>mr({status:C},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!E.ok)return[E,{status:"request-error",request:T}];const k=E.value,[A]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(k,T);return A.ok?[A,{status:"complete",request:T,response:k}]:[A,{status:"complete",request:T,response:k}]}function JHe(e,t,r,n,o,i,s,a){return new fr(Ltn(e,t,r,n,o,i,s,a))}async function Ltn(e,t,r,n,o,i,s,a){var u,l,c;const p={environment:t,path:r,api_version:n,page_size:o,page_token:i,recursive:s},m=null,h={api_version:gt("api_version",(u=p.api_version)!==null&&u!==void 0?u:e._options.api_version,{explode:!1,charEncoding:"percent"}),environment:gt("environment",p.environment,{explode:!1,charEncoding:"percent"}),path:gt("path",p.path,{explode:!1,charEncoding:"percentExceptReserved"})},g=Tr("/{api_version}/environments/{environment}/files/{path}")(h),y=Bu({page_size:p.page_size,page_token:p.page_token,recursive:p.recursive}),v=new Headers(Ar({Accept:"application/json"})),w=await Ir(e._options.security),T=xr(w),E={options:e._options,base_url:(c=(l=a?.server_url)!==null&&l!==void 0?l:e._baseURL)!==null&&c!==void 0?c:"",operation_id:"GetEnvironmentFiles",o_auth2_scopes:null,resolved_security:T,security_source:e._options.security,retry_config:a?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:a?.retry_codes||["408","409","429","5XX"]},k=e._createRequest(E,{security:T,method:"GET",baseURL:a?.server_url,path:g,headers:v,query:y,body:m,userAgent:e._options.user_agent,timeout_ms:a?.timeout_ms||e._options.timeout_ms||-1},a);if(!k.ok)return[k,{status:"invalid"}];const A=k.value,C=await e._do(A,{context:E,isErrorStatusCode:P=>mr({status:P},["4XX","5XX"]),retryConfig:E.retry_config,retryCodes:E.retry_codes});if(!C.ok)return[C,{status:"request-error",request:A}];const R=C.value,[x]=await Cr(Lr(200),vt("4XX"),vt("5XX"))(R,A);return x.ok?[x,{status:"complete",request:A,response:R}]:[x,{status:"complete",request:A,response:R}]}function XHe(e,t,r,n,o,i,s,a,u,l,c){return new fr($tn(e,t,r,n,o,i,s,a,u,l,c))}async function $tn(e,t,r,n,o,i,s,a,u,l,c){var d,p,m;const g={environment:t,path:r,"X-Goog-Upload-Command":n,"X-Goog-Upload-Header-Content-Length":o,"X-Goog-Upload-Header-Content-Type":i,"X-Goog-Upload-Protocol":s,api_version:a,extract:u,overwrite:l},y=null,v={api_version:gt("api_version",(d=g.api_version)!==null&&d!==void 0?d:e._options.api_version,{explode:!1,charEncoding:"percent"}),environment:gt("environment",g.environment,{explode:!1,charEncoding:"percent"}),path:gt("path",g.path,{explode:!1,charEncoding:"percentExceptReserved"})},w=Tr("/upload/{api_version}/environments/{environment}/files/{path}")(v),T=Bu({extract:g.extract,overwrite:g.overwrite}),E=new Headers(Ar({Accept:"*/*","X-Goog-Upload-Command":gt("X-Goog-Upload-Command",g["X-Goog-Upload-Command"],{explode:!1,charEncoding:"none"}),"X-Goog-Upload-Header-Content-Length":gt("X-Goog-Upload-Header-Content-Length",g["X-Goog-Upload-Header-Content-Length"],{explode:!1,charEncoding:"none"}),"X-Goog-Upload-Header-Content-Type":gt("X-Goog-Upload-Header-Content-Type",g["X-Goog-Upload-Header-Content-Type"],{explode:!1,charEncoding:"none"}),"X-Goog-Upload-Protocol":gt("X-Goog-Upload-Protocol",g["X-Goog-Upload-Protocol"],{explode:!1,charEncoding:"none"})})),k=await Ir(e._options.security),A=xr(k),C={options:e._options,base_url:(m=(p=c?.server_url)!==null&&p!==void 0?p:e._baseURL)!==null&&m!==void 0?m:"",operation_id:"StartEnvironmentFileUpload",o_auth2_scopes:null,resolved_security:A,security_source:e._options.security,retry_config:c?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:c?.retry_codes||["408","409","429","5XX"]},R=e._createRequest(C,{security:A,method:"PUT",baseURL:c?.server_url,path:w,headers:E,query:T,body:y,userAgent:e._options.user_agent,timeout_ms:c?.timeout_ms||e._options.timeout_ms||-1},c);if(!R.ok)return[R,{status:"invalid"}];const x=R.value,P=await e._do(x,{context:C,isErrorStatusCode:N=>mr({status:N},["4XX","5XX"]),retryConfig:C.retry_config,retryCodes:C.retry_codes});if(!P.ok)return[P,{status:"request-error",request:x}];const D=P.value,L={httpMeta:{response:D,request:x}},[O]=await Cr(NHe(200,{hdrs:!0}),vt("4XX"),vt("5XX"))(D,x,{extraFields:L});return O.ok?[O,{status:"complete",request:x,response:D}]:[O,{status:"complete",request:x,response:D}]}function YHe(e,t,r,n){return new fr(Ftn(e,t,r,n))}async function Ftn(e,t,r,n){var o,i,s;const u={id:t,api_version:r},l=null,c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),interactionsId:gt("interactionsId",u.id,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/interactions/{interactionsId}/cancel")(c),p=new Headers(Ar({Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"cancelInteractionById",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"POST",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:A=>mr({status:A},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,E={httpMeta:{response:T,request:v}},[k]=await Cr(Lr(200),Rh("4XX",IJe),Rh("5XX",xJe))(T,v,{extraFields:E});return k.ok?[k,{status:"complete",request:v,response:T}]:[k,{status:"complete",request:v,response:T}]}function ZHe(e,t,r,n){return new fr(Utn(e,t,r,n))}async function Utn(e,t,r,n){var o,i,s,a;const u={body:t,api_version:r},l=u,c=Al("body",l.body,{explode:!0}),d={api_version:gt("api_version",(o=l.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"})},p=Tr("/{api_version}/interactions")(d),m=new Headers(Ar({"Content-Type":"application/json",Accept:!((i=u?.body)===null||i===void 0)&&i.stream?"text/event-stream":"application/json"})),h=await Ir(e._options.security),g=xr(h),y={options:e._options,base_url:(a=(s=n?.server_url)!==null&&s!==void 0?s:e._baseURL)!==null&&a!==void 0?a:"",operation_id:"CreateInteraction",o_auth2_scopes:null,resolved_security:g,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},v=e._createRequest(y,{security:g,method:"POST",baseURL:n?.server_url,path:p,headers:m,body:c,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!v.ok)return[v,{status:"invalid"}];const w=v.value,T=await e._do(w,{context:y,isErrorStatusCode:C=>mr({status:C},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:w}];const E=T.value,k={httpMeta:{response:E,request:w}},[A]=await Cr(Lr(200),OHe(200,{sentinel:"[DONE]",flattened:!0}),Rh("4XX",MJe),Rh("5XX",RJe))(E,w,{extraFields:k});return A.ok?[A,{status:"complete",request:w,response:E}]:[A,{status:"complete",request:w,response:E}]}function Btn(e,t,r,n){return new fr(ztn(e,t,r,n))}async function ztn(e,t,r,n){var o,i,s;const u={id:t,api_version:r},l=null,c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),interactionsId:gt("interactionsId",u.id,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/interactions/{interactionsId}")(c),p=new Headers(Ar({Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"deleteInteraction",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"DELETE",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:A=>mr({status:A},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,E={httpMeta:{response:T,request:v}},[k]=await Cr(NHe(200),Rh("4XX",DJe),Rh("5XX",PJe))(T,v,{extraFields:E});return k.ok?[k,{status:"complete",request:v,response:T}]:[k,{status:"complete",request:v,response:T}]}function QHe(e,t,r,n,o,i,s){return new fr(Gtn(e,t,r,n,o,i,s))}async function Gtn(e,t,r,n,o,i,s){var a,u,l;const c={id:t,api_version:r,include_input:n,last_event_id:o,stream:i},d=c,p=null,m={api_version:gt("api_version",(a=d.api_version)!==null&&a!==void 0?a:e._options.api_version,{explode:!1,charEncoding:"percent"}),interactionsId:gt("interactionsId",d.id,{explode:!1,charEncoding:"percent"})},h=Tr("/{api_version}/interactions/{interactionsId}")(m),g=Bu({include_input:d.include_input,last_event_id:d.last_event_id,stream:d.stream}),y=new Headers(Ar({Accept:c?.stream?"text/event-stream":"application/json"})),v=await Ir(e._options.security),w=xr(v),T={options:e._options,base_url:(l=(u=s?.server_url)!==null&&u!==void 0?u:e._baseURL)!==null&&l!==void 0?l:"",operation_id:"getInteractionById",o_auth2_scopes:null,resolved_security:w,security_source:e._options.security,retry_config:s?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:s?.retry_codes||["408","409","429","5XX"]},E=e._createRequest(T,{security:w,method:"GET",baseURL:s?.server_url,path:h,headers:y,query:g,body:p,userAgent:e._options.user_agent,timeout_ms:s?.timeout_ms||e._options.timeout_ms||-1},s);if(!E.ok)return[E,{status:"invalid"}];const k=E.value,A=await e._do(k,{context:T,isErrorStatusCode:P=>mr({status:P},["4XX","5XX"]),retryConfig:T.retry_config,retryCodes:T.retry_codes});if(!A.ok)return[A,{status:"request-error",request:k}];const C=A.value,R={httpMeta:{response:C,request:k}},[x]=await Cr(Lr(200),OHe(200,{sentinel:"[DONE]",flattened:!0}),Rh("4XX",NJe),Rh("5XX",OJe))(C,k,{extraFields:R});return x.ok?[x,{status:"complete",request:k,response:C}]:[x,{status:"complete",request:k,response:C}]}function eWe(e,t,r,n){return new fr(qtn(e,t,r,n))}async function qtn(e,t,r,n){var o,i,s;const u={body:t,api_version:r},l=Al("body",u.body,{explode:!0}),c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/triggers")(c),p=new Headers(Ar({"Content-Type":"application/json",Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"CreateTrigger",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"POST",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function tWe(e,t,r,n){return new fr(jtn(e,t,r,n))}async function jtn(e,t,r,n){var o,i,s;const u={id:t,api_version:r},l=null,c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:gt("id",u.id,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/triggers/{id}")(c),p=new Headers(Ar({Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"DeleteTrigger",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"DELETE",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function rWe(e,t,r,n){return new fr(Vtn(e,t,r,n))}async function Vtn(e,t,r,n){var o,i,s;const u={id:t,api_version:r},l=null,c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:gt("id",u.id,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/triggers/{id}")(c),p=new Headers(Ar({Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"GetTrigger",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"GET",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function nWe(e,t,r,n,o,i){return new fr(Htn(e,t,r,n,o,i))}async function Htn(e,t,r,n,o,i){var s,a,u;const c={trigger_id:t,api_version:r,page_size:n,page_token:o},d=null,p={api_version:gt("api_version",(s=c.api_version)!==null&&s!==void 0?s:e._options.api_version,{explode:!1,charEncoding:"percent"}),triggerId:gt("triggerId",c.trigger_id,{explode:!1,charEncoding:"percent"})},m=Tr("/{api_version}/triggers/{triggerId}/executions")(p),h=Bu({page_size:c.page_size,page_token:c.page_token}),g=new Headers(Ar({Accept:"application/json"})),y=await Ir(e._options.security),v=xr(y),w={options:e._options,base_url:(u=(a=i?.server_url)!==null&&a!==void 0?a:e._baseURL)!==null&&u!==void 0?u:"",operation_id:"ListTriggerExecutions",o_auth2_scopes:null,resolved_security:v,security_source:e._options.security,retry_config:i?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},T=e._createRequest(w,{security:v,method:"GET",baseURL:i?.server_url,path:m,headers:g,query:h,body:d,userAgent:e._options.user_agent,timeout_ms:i?.timeout_ms||e._options.timeout_ms||-1},i);if(!T.ok)return[T,{status:"invalid"}];const E=T.value,k=await e._do(E,{context:w,isErrorStatusCode:R=>mr({status:R},["4XX","5XX"]),retryConfig:w.retry_config,retryCodes:w.retry_codes});if(!k.ok)return[k,{status:"request-error",request:E}];const A=k.value,[C]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(A,E);return C.ok?[C,{status:"complete",request:E,response:A}]:[C,{status:"complete",request:E,response:A}]}function oWe(e,t,r,n,o,i){return new fr(Wtn(e,t,r,n,o,i))}async function Wtn(e,t,r,n,o,i){var s,a,u;const c={api_version:t,filter:r,page_size:n,page_token:o},d=null,p={api_version:gt("api_version",(s=c?.api_version)!==null&&s!==void 0?s:e._options.api_version,{explode:!1,charEncoding:"percent"})},m=Tr("/{api_version}/triggers")(p),h=Bu({filter:c?.filter,page_size:c?.page_size,page_token:c?.page_token}),g=new Headers(Ar({Accept:"application/json"})),y=await Ir(e._options.security),v=xr(y),w={options:e._options,base_url:(u=(a=i?.server_url)!==null&&a!==void 0?a:e._baseURL)!==null&&u!==void 0?u:"",operation_id:"ListTriggers",o_auth2_scopes:null,resolved_security:v,security_source:e._options.security,retry_config:i?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},T=e._createRequest(w,{security:v,method:"GET",baseURL:i?.server_url,path:m,headers:g,query:h,body:d,userAgent:e._options.user_agent,timeout_ms:i?.timeout_ms||e._options.timeout_ms||-1},i);if(!T.ok)return[T,{status:"invalid"}];const E=T.value,k=await e._do(E,{context:w,isErrorStatusCode:R=>mr({status:R},["4XX","5XX"]),retryConfig:w.retry_config,retryCodes:w.retry_codes});if(!k.ok)return[k,{status:"request-error",request:E}];const A=k.value,[C]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(A,E);return C.ok?[C,{status:"complete",request:E,response:A}]:[C,{status:"complete",request:E,response:A}]}function iWe(e,t,r,n){return new fr(Ktn(e,t,r,n))}async function Ktn(e,t,r,n){var o,i,s;const u={trigger_id:t,api_version:r},l=null,c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),triggerId:gt("triggerId",u.trigger_id,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/triggers/{triggerId}/executions")(c),p=new Headers(Ar({Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"RunTrigger",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"POST",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function sWe(e,t,r,n,o){return new fr(Jtn(e,t,r,n,o))}async function Jtn(e,t,r,n,o){var i,s,a;const l={id:t,body:r,api_version:n},c=Al("body",l.body,{explode:!0}),d={api_version:gt("api_version",(i=l.api_version)!==null&&i!==void 0?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:gt("id",l.id,{explode:!1,charEncoding:"percent"})},p=Tr("/{api_version}/triggers/{id}")(d),m=new Headers(Ar({"Content-Type":"application/json",Accept:"application/json"})),h=await Ir(e._options.security),g=xr(h),y={options:e._options,base_url:(a=(s=o?.server_url)!==null&&s!==void 0?s:e._baseURL)!==null&&a!==void 0?a:"",operation_id:"UpdateTrigger",o_auth2_scopes:null,resolved_security:g,security_source:e._options.security,retry_config:o?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},v=e._createRequest(y,{security:g,method:"PATCH",baseURL:o?.server_url,path:p,headers:m,body:c,userAgent:e._options.user_agent,timeout_ms:o?.timeout_ms||e._options.timeout_ms||-1},o);if(!v.ok)return[v,{status:"invalid"}];const w=v.value,T=await e._do(w,{context:y,isErrorStatusCode:A=>mr({status:A},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:w}];const E=T.value,[k]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(E,w);return k.ok?[k,{status:"complete",request:w,response:E}]:[k,{status:"complete",request:w,response:E}]}function aWe(e,t,r,n){return new fr(Xtn(e,t,r,n))}async function Xtn(e,t,r,n){var o,i,s;const u={body:t,api_version:r},l=Al("body",u.body,{explode:!0}),c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/voices")(c),p=new Headers(Ar({"Content-Type":"application/json",Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"CreateVoice",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"POST",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function uWe(e,t,r,n){return new fr(Ytn(e,t,r,n))}async function Ytn(e,t,r,n){var o,i,s;const u={id:t,api_version:r},l=null,c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),voicesId:gt("voicesId",u.id,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/voices/{voicesId}")(c),p=new Headers(Ar({Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"DeleteVoice",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"DELETE",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function lWe(e,t,r,n){return new fr(Ztn(e,t,r,n))}async function Ztn(e,t,r,n){var o,i,s;const u={id:t,api_version:r},l=null,c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),voicesId:gt("voicesId",u.id,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/voices/{voicesId}")(c),p=new Headers(Ar({Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"GetVoice",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"GET",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function cWe(e,t,r,n,o,i,s,a,u,l,c,d,p,m){return new fr(Qtn(e,t,r,n,o,i,s,a,u,l,c,d,p,m))}async function Qtn(e,t,r,n,o,i,s,a,u,l,c,d,p,m){var h,g,y;const w={api_version:t,accent:r,contexts:n,gender:o,language_code:i,page_size:s,page_token:a,persona:u,pitch:l,region_code:c,search:d,type:p},T=null,E={api_version:gt("api_version",(h=w?.api_version)!==null&&h!==void 0?h:e._options.api_version,{explode:!1,charEncoding:"percent"})},k=Tr("/{api_version}/voices")(E),A=Bu({accent:w?.accent,context:w?.contexts,gender:w?.gender,language_code:w?.language_code,page_size:w?.page_size,page_token:w?.page_token,persona:w?.persona,pitch:w?.pitch,region_code:w?.region_code,search:w?.search,type:w?.type}),C=new Headers(Ar({Accept:"application/json"})),R=await Ir(e._options.security),x=xr(R),P={options:e._options,base_url:(y=(g=m?.server_url)!==null&&g!==void 0?g:e._baseURL)!==null&&y!==void 0?y:"",operation_id:"ListVoices",o_auth2_scopes:null,resolved_security:x,security_source:e._options.security,retry_config:m?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:m?.retry_codes||["408","409","429","5XX"]},D=e._createRequest(P,{security:x,method:"GET",baseURL:m?.server_url,path:k,headers:C,query:A,body:T,userAgent:e._options.user_agent,timeout_ms:m?.timeout_ms||e._options.timeout_ms||-1},m);if(!D.ok)return[D,{status:"invalid"}];const L=D.value,O=await e._do(L,{context:P,isErrorStatusCode:$=>mr({status:$},["4XX","5XX"]),retryConfig:P.retry_config,retryCodes:P.retry_codes});if(!O.ok)return[O,{status:"request-error",request:L}];const N=O.value,[U]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(N,L);return U.ok?[U,{status:"complete",request:L,response:N}]:[U,{status:"complete",request:L,response:N}]}function dWe(e,t,r,n){return new fr(ern(e,t,r,n))}async function ern(e,t,r,n){var o,i,s;const u={body:t,api_version:r},l=Al("body",u.body,{explode:!0}),c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/webhooks")(c),p=new Headers(Ar({"Content-Type":"application/json",Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"CreateWebhook",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"POST",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function pWe(e,t,r,n){return new fr(trn(e,t,r,n))}async function trn(e,t,r,n){var o,i,s;const u={id:t,api_version:r},l=null,c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:gt("id",u.id,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/webhooks/{id}")(c),p=new Headers(Ar({Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"DeleteWebhook",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"DELETE",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function mWe(e,t,r,n){return new fr(rrn(e,t,r,n))}async function rrn(e,t,r,n){var o,i,s;const u={id:t,api_version:r},l=null,c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:gt("id",u.id,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/webhooks/{id}")(c),p=new Headers(Ar({Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"GetWebhook",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"GET",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function hWe(e,t,r,n,o){return new fr(nrn(e,t,r,n,o))}async function nrn(e,t,r,n,o){var i,s,a;const l={api_version:t,page_size:r,page_token:n},c=null,d={api_version:gt("api_version",(i=l?.api_version)!==null&&i!==void 0?i:e._options.api_version,{explode:!1,charEncoding:"percent"})},p=Tr("/{api_version}/webhooks")(d),m=Bu({page_size:l?.page_size,page_token:l?.page_token}),h=new Headers(Ar({Accept:"application/json"})),g=await Ir(e._options.security),y=xr(g),v={options:e._options,base_url:(a=(s=o?.server_url)!==null&&s!==void 0?s:e._baseURL)!==null&&a!==void 0?a:"",operation_id:"ListWebhooks",o_auth2_scopes:null,resolved_security:y,security_source:e._options.security,retry_config:o?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},w=e._createRequest(v,{security:y,method:"GET",baseURL:o?.server_url,path:p,headers:h,query:m,body:c,userAgent:e._options.user_agent,timeout_ms:o?.timeout_ms||e._options.timeout_ms||-1},o);if(!w.ok)return[w,{status:"invalid"}];const T=w.value,E=await e._do(T,{context:v,isErrorStatusCode:C=>mr({status:C},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!E.ok)return[E,{status:"request-error",request:T}];const k=E.value,[A]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(k,T);return A.ok?[A,{status:"complete",request:T,response:k}]:[A,{status:"complete",request:T,response:k}]}function fWe(e,t,r,n,o){return new fr(orn(e,t,r,n,o))}async function orn(e,t,r,n,o){var i,s,a;const l={id:t,api_version:r,body:n},c=Al("body",l.body,{explode:!0}),d={api_version:gt("api_version",(i=l.api_version)!==null&&i!==void 0?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:gt("id",l.id,{explode:!1,charEncoding:"percent"})},p=Tr("/{api_version}/webhooks/{id}:ping")(d),m=new Headers(Ar({"Content-Type":"application/json",Accept:"application/json"})),h=await Ir(e._options.security),g=xr(h),y={options:e._options,base_url:(a=(s=o?.server_url)!==null&&s!==void 0?s:e._baseURL)!==null&&a!==void 0?a:"",operation_id:"PingWebhook",o_auth2_scopes:null,resolved_security:g,security_source:e._options.security,retry_config:o?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},v=e._createRequest(y,{security:g,method:"POST",baseURL:o?.server_url,path:p,headers:m,body:c,userAgent:e._options.user_agent,timeout_ms:o?.timeout_ms||e._options.timeout_ms||-1},o);if(!v.ok)return[v,{status:"invalid"}];const w=v.value,T=await e._do(w,{context:y,isErrorStatusCode:A=>mr({status:A},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:w}];const E=T.value,[k]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(E,w);return k.ok?[k,{status:"complete",request:w,response:E}]:[k,{status:"complete",request:w,response:E}]}function gWe(e,t,r,n,o){return new fr(irn(e,t,r,n,o))}async function irn(e,t,r,n,o){var i,s,a;const l={id:t,body:r,api_version:n},c=Al("body",l.body,{explode:!0}),d={api_version:gt("api_version",(i=l.api_version)!==null&&i!==void 0?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:gt("id",l.id,{explode:!1,charEncoding:"percent"})},p=Tr("/{api_version}/webhooks/{id}:rotateSigningSecret")(d),m=new Headers(Ar({"Content-Type":"application/json",Accept:"application/json"})),h=await Ir(e._options.security),g=xr(h),y={options:e._options,base_url:(a=(s=o?.server_url)!==null&&s!==void 0?s:e._baseURL)!==null&&a!==void 0?a:"",operation_id:"RotateSigningSecret",o_auth2_scopes:null,resolved_security:g,security_source:e._options.security,retry_config:o?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},v=e._createRequest(y,{security:g,method:"POST",baseURL:o?.server_url,path:p,headers:m,body:c,userAgent:e._options.user_agent,timeout_ms:o?.timeout_ms||e._options.timeout_ms||-1},o);if(!v.ok)return[v,{status:"invalid"}];const w=v.value,T=await e._do(w,{context:y,isErrorStatusCode:A=>mr({status:A},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:w}];const E=T.value,[k]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(E,w);return k.ok?[k,{status:"complete",request:w,response:E}]:[k,{status:"complete",request:w,response:E}]}function yWe(e,t,r,n,o,i){return new fr(srn(e,t,r,n,o,i))}async function srn(e,t,r,n,o,i){var s,a,u;const c={id:t,body:r,api_version:n,update_mask:o},d=Al("body",c.body,{explode:!0}),p={api_version:gt("api_version",(s=c.api_version)!==null&&s!==void 0?s:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:gt("id",c.id,{explode:!1,charEncoding:"percent"})},m=Tr("/{api_version}/webhooks/{id}")(p),h=Bu({update_mask:c.update_mask}),g=new Headers(Ar({"Content-Type":"application/json",Accept:"application/json"})),y=await Ir(e._options.security),v=xr(y),w={options:e._options,base_url:(u=(a=i?.server_url)!==null&&a!==void 0?a:e._baseURL)!==null&&u!==void 0?u:"",operation_id:"UpdateWebhook",o_auth2_scopes:null,resolved_security:v,security_source:e._options.security,retry_config:i?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},T=e._createRequest(w,{security:v,method:"PATCH",baseURL:i?.server_url,path:m,headers:g,query:h,body:d,userAgent:e._options.user_agent,timeout_ms:i?.timeout_ms||e._options.timeout_ms||-1},i);if(!T.ok)return[T,{status:"invalid"}];const E=T.value,k=await e._do(E,{context:w,isErrorStatusCode:R=>mr({status:R},["4XX","5XX"]),retryConfig:w.retry_config,retryCodes:w.retry_codes});if(!k.ok)return[k,{status:"request-error",request:E}];const A=k.value,[C]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(A,E);return C.ok?[C,{status:"complete",request:E,response:A}]:[C,{status:"complete",request:E,response:A}]}function arn(e){const t=e.getBaseUrl();if(!t)throw new Error("Base URL must be set.");return t.replace(/\/+$/,"")}function urn(e){const t=lrn(e.getApiVersion()),r=e.getProject(),n=e.getLocation();return e.isVertexAI()&&t&&r&&n?`${t}/projects/${encodeURIComponent(r)}/locations/${encodeURIComponent(n)}`:t}function Za(e,t={}){var r,n,o,i,s,a,u,l,c,d;const{timeout:p}=t,m=hi(t,["timeout"]),h=m.http_client||(r=e.getFetch)===null||r===void 0?void 0:r.call(e),g=(n=m.http_client)!==null&&n!==void 0?n:h?new lY({fetcher:h}):void 0,y=(i=(o=m.timeout_ms)!==null&&o!==void 0?o:p)!==null&&i!==void 0?i:(s=e.getTimeout)===null||s===void 0?void 0:s.call(e);return new BJe(Object.assign(Object.assign({},m),{http_client:g,api_version:(a=m.api_version)!==null&&a!==void 0?a:urn(e),security:(u=m.security)!==null&&u!==void 0?u:new XKe({defaultHeaders:Object.assign(Object.assign({},(l=e.getDefaultHeaders)===null||l===void 0?void 0:l.call(e)),(c=e.getHeaders)===null||c===void 0?void 0:c.call(e)),getAuthHeaders:w=>e.getAuthHeaders(w)}),server_url:(d=m.server_url)!==null&&d!==void 0?d:arn(e),timeout_ms:y}))}function lrn(e){return e.replace(/^\/+|\/+$/g,"")}function hr(e,t=!1){var r,n,o,i;if(!e&&!t)return;const s=e??{},{timeout:a,maxRetries:u,defaultBaseURL:l,query:c,body:d,fetchOptions:p}=s,m=hi(s,["timeout","maxRetries","defaultBaseURL","query","body","fetchOptions"]),h=Object.assign({},m);hO(c)?h.extra_query=c:vWe("query",c),hO(d)?h.extra_body=d:vWe("body",d);const g=(r=m.fetch_options)!==null&&r!==void 0?r:p;g&&(h.fetch_options=g);const y=(n=m.server_url)!==null&&n!==void 0?n:l;y&&(h.server_url=y);const v=(o=m.timeout_ms)!==null&&o!==void 0?o:a;if(v!==void 0&&(h.timeout_ms=v),u!==void 0&&(h.retries={strategy:"attempt-count-backoff",retryConnectionErrors:!0,maxRetries:u}),t){const w=new Headers((i=h.headers)!==null&&i!==void 0?i:g?.headers);w.set("Accept","text/event-stream"),h.headers=w}return h}function vWe(e,t){t!=null&&console.warn(`GoogleGenAI.interactions: request option ${e} is not supported by the Google GenAI interactions bridge and will be ignored.`)}async function $r(e){const[t,r]=await e.$inspect();if(!t.ok)throw i0(t.error);return crn(t.value,r)}async function lJ(e){try{return await e()}catch(t){throw i0(t)}}function wWe(e){const t=e;return new Proxy(e,{get(r,n){if(n!==Symbol.asyncIterator){const o=Reflect.get(r,n,r);return typeof o=="function"?o.bind(r):o}return function(){const i=t[Symbol.asyncIterator]();return{async next(...s){try{return await i.next(...s)}catch(a){throw i0(a)}},async return(s){if(!i.return)return{done:!0,value:s};try{return await i.return(s)}catch(a){throw i0(a)}},async throw(s){if(!i.throw)throw i0(s);try{return await i.throw(s)}catch(a){throw i0(a)}},[Symbol.asyncIterator](){return this}}}}})}function crn(e,t){return!hO(e)||t.status!=="complete"?e:Object.assign(Object.assign({},e),{sdkHttpResponse:drn(t.response,e)})}function drn(e,t){const r={};for(const[n,o]of e.headers.entries())r[n]=o;return{headers:r,responseInternal:e,json:async()=>t}}function cJ(e){const t=prn(e);return t?hrn(t):e}function prn(e){if(hO(e)){if(Array.isArray(e.steps))return e;if(mrn(e)){const t=e.outputs;if(Array.isArray(t)){const{outputs:r}=e,n=hi(e,["outputs"]);return Object.assign(Object.assign({},n),{steps:[{type:"model_output",content:t}]})}}return Object.assign(Object.assign({},e),{steps:[]})}}function mrn(e){const t=e.model;return typeof t=="string"&&zJe.has(t)}function hO(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hrn(e){var t,r;const n=frn(e),o=(t=n.steps)!==null&&t!==void 0?t:[],i=[];let s=!1;e:for(let d=o.length-1;d>=0;d--){const p=o[d];if(p.type==="user_input")break;if(p.type==="thought")continue;if(p.type!=="model_output"){if(s)break;continue}if(!p.content)continue;const m=p.content;for(let h=m.length-1;h>=0;h--){const g=m[h];if(g.type==="text")s=!0,i.push((r=g.text)!==null&&r!==void 0?r:"");else if(s)break e}}let a,u,l;for(let d=o.length-1;d>=0;d--){const p=o[d];if(p.type==="user_input")break;if(p.type==="model_output"&&p.content)for(let m=p.content.length-1;m>=0;m--){const h=p.content[m];h.type==="image"&&!a&&(a=h),h.type==="audio"&&!u&&(u=h),h.type==="video"&&!l&&(l=h)}}const c=i.reverse().join("");return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},n),c&&{output_text:c}),a?{output_image:a}:{}),u?{output_audio:u}:{}),l?{output_video:l}:{})}function frn(e){return Object.assign(Object.assign({},e),{created:bWe(e.created),updated:bWe(e.updated)})}function bWe(e){return e instanceof Date?e.toISOString():e}function grn(e){const t=e.slice(e.lastIndexOf(".")+1).toLowerCase();return{txt:"text/plain",json:"application/json",js:"text/javascript",mjs:"text/javascript",ts:"text/plain",py:"text/x-python",html:"text/html",htm:"text/html",css:"text/css",csv:"text/csv",xml:"application/xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",pdf:"application/pdf",zip:"application/zip",tar:"application/x-tar",gz:"application/gzip"}[t]}function yrn(e){const t={},r=b(e,["apiKey"]);if(r!=null&&_(t,["apiKey"],r),b(e,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function TWe(e){const t={},r=b(e,["parts"]);if(r!=null){let o=r;Array.isArray(o)&&(o=o.map(i=>$rn(i))),_(t,["parts"],o)}const n=b(e,["role"]);return n!=null&&_(t,["role"],n),t}function _We(e){const t={},r=b(e,["parts"]);if(r!=null){let o=r;Array.isArray(o)&&(o=o.map(i=>Frn(i))),_(t,["parts"],o)}const n=b(e,["role"]);return n!=null&&_(t,["role"],n),t}function vrn(e){const t={},r=b(e,["args"]);r!=null&&_(t,["args"],r);const n=b(e,["id"]);n!=null&&_(t,["id"],n);const o=b(e,["name"]);if(o!=null&&_(t,["name"],o),b(e,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function wrn(e){const t={},r=b(e,["modelSelectionConfig"]);r!=null&&_(t,["modelConfig"],r);const n=b(e,["responseJsonSchema"]);n!=null&&_(t,["responseJsonSchema"],n);const o=b(e,["audioTranscriptionConfig"]);o!=null&&_(t,["audioTranscriptionConfig"],o);const i=b(e,["audioTimestamp"]);i!=null&&_(t,["audioTimestamp"],i);const s=b(e,["candidateCount"]);s!=null&&_(t,["candidateCount"],s);const a=b(e,["enableAffectiveDialog"]);a!=null&&_(t,["enableAffectiveDialog"],a);const u=b(e,["frequencyPenalty"]);u!=null&&_(t,["frequencyPenalty"],u);const l=b(e,["logprobs"]);l!=null&&_(t,["logprobs"],l);const c=b(e,["maxOutputTokens"]);c!=null&&_(t,["maxOutputTokens"],c);const d=b(e,["mediaResolution"]);d!=null&&_(t,["mediaResolution"],d);const p=b(e,["presencePenalty"]);p!=null&&_(t,["presencePenalty"],p);const m=b(e,["responseFormat"]);if(m!=null){let D=m;Array.isArray(D)&&(D=D.map(L=>L)),_(t,["responseFormat"],D)}const h=b(e,["responseLogprobs"]);h!=null&&_(t,["responseLogprobs"],h);const g=b(e,["responseMimeType"]);g!=null&&_(t,["responseMimeType"],g);const y=b(e,["responseModalities"]);y!=null&&_(t,["responseModalities"],y);const v=b(e,["responseSchema"]);v!=null&&_(t,["responseSchema"],v);const w=b(e,["routingConfig"]);w!=null&&_(t,["routingConfig"],w);const T=b(e,["seed"]);T!=null&&_(t,["seed"],T);const E=b(e,["speechConfig"]);E!=null&&_(t,["speechConfig"],EWe(E));const k=b(e,["stopSequences"]);k!=null&&_(t,["stopSequences"],k);const A=b(e,["temperature"]);A!=null&&_(t,["temperature"],A);const C=b(e,["thinkingConfig"]);C!=null&&_(t,["thinkingConfig"],C);const R=b(e,["topK"]);R!=null&&_(t,["topK"],R);const x=b(e,["topP"]);if(x!=null&&_(t,["topP"],x),b(e,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const P=b(e,["translationConfig"]);return P!=null&&_(t,["translationConfig"],P),t}function brn(e){const t={},r=b(e,["authConfig"]);r!=null&&_(t,["authConfig"],yrn(r));const n=b(e,["enableWidget"]);if(n!=null&&_(t,["enableWidget"],n),b(e,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function Trn(e){const t={};if(b(e,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const r=b(e,["searchTypes"]);r!=null&&_(t,["searchTypes"],r);const n=b(e,["timeRangeFilter"]);return n!=null&&_(t,["timeRangeFilter"],n),t}function _rn(e){const t={},r=b(e,["systemInstruction"]);r!=null&&_(t,["systemInstruction"],TWe(Ii(r)));const n=b(e,["tools"]);return n!=null&&_(t,["tools"],Srn(n)),t}function Ern(e){const t={},r=b(e,["systemInstruction"]);r!=null&&_(t,["systemInstruction"],_We(Ii(r)));const n=b(e,["tools"]);return n!=null&&_(t,["tools"],krn(n)),t}function Srn(e){const t={},r=b(e,["tools"]);if(r!=null){let n=xh(r);Array.isArray(n)&&(n=n.map(o=>SWe(Ch(o)))),_(t,["tools"],n)}return t}function krn(e){const t={},r=b(e,["tools"]);if(r!=null){let n=xh(r);Array.isArray(n)&&(n=n.map(o=>kWe(Ch(o)))),_(t,["tools"],n)}return t}function Arn(e,t){const r={},n=b(e,["generationConfig"]);t!==void 0&&n!=null&&_(t,["setup","generationConfig"],n);const o=b(e,["responseModalities"]);t!==void 0&&o!=null&&_(t,["setup","generationConfig","responseModalities"],o);const i=b(e,["temperature"]);t!==void 0&&i!=null&&_(t,["setup","generationConfig","temperature"],i);const s=b(e,["topP"]);t!==void 0&&s!=null&&_(t,["setup","generationConfig","topP"],s);const a=b(e,["topK"]);t!==void 0&&a!=null&&_(t,["setup","generationConfig","topK"],a);const u=b(e,["maxOutputTokens"]);t!==void 0&&u!=null&&_(t,["setup","generationConfig","maxOutputTokens"],u);const l=b(e,["mediaResolution"]);t!==void 0&&l!=null&&_(t,["setup","generationConfig","mediaResolution"],l);const c=b(e,["seed"]);t!==void 0&&c!=null&&_(t,["setup","generationConfig","seed"],c);const d=b(e,["speechConfig"]);t!==void 0&&d!=null&&_(t,["setup","generationConfig","speechConfig"],iJ(d));const p=b(e,["thinkingConfig"]);t!==void 0&&p!=null&&_(t,["setup","generationConfig","thinkingConfig"],p);const m=b(e,["enableAffectiveDialog"]);t!==void 0&&m!=null&&_(t,["setup","generationConfig","enableAffectiveDialog"],m);const h=b(e,["systemInstruction"]);t!==void 0&&h!=null&&_(t,["setup","systemInstruction"],TWe(Ii(h)));const g=b(e,["tools"]);if(t!==void 0&&g!=null){let P=xh(g);Array.isArray(P)&&(P=P.map(D=>SWe(Ch(D)))),_(t,["setup","tools"],P)}const y=b(e,["sessionResumption"]);t!==void 0&&y!=null&&_(t,["setup","sessionResumption"],zrn(y));const v=b(e,["inputAudioTranscription"]);t!==void 0&&v!=null&&_(t,["setup","inputAudioTranscription"],v);const w=b(e,["outputAudioTranscription"]);t!==void 0&&w!=null&&_(t,["setup","outputAudioTranscription"],w);const T=b(e,["realtimeInputConfig"]);t!==void 0&&T!=null&&_(t,["setup","realtimeInputConfig"],T);const E=b(e,["contextWindowCompression"]);t!==void 0&&E!=null&&_(t,["setup","contextWindowCompression"],E);const k=b(e,["proactivity"]);if(t!==void 0&&k!=null&&_(t,["setup","proactivity"],k),b(e,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const A=b(e,["avatarConfig"]);t!==void 0&&A!=null&&_(t,["setup","avatarConfig"],A);const C=b(e,["safetySettings"]);if(t!==void 0&&C!=null){let P=C;Array.isArray(P)&&(P=P.map(D=>Brn(D))),_(t,["setup","safetySettings"],P)}const R=b(e,["translationConfig"]);t!==void 0&&R!=null&&_(t,["setup","generationConfig","translationConfig"],R);const x=b(e,["labels"]);return t!==void 0&&x!=null&&_(t,["setup","labels"],x),r}function Crn(e,t){const r={},n=b(e,["generationConfig"]);t!==void 0&&n!=null&&_(t,["setup","generationConfig"],wrn(n));const o=b(e,["responseModalities"]);t!==void 0&&o!=null&&_(t,["setup","generationConfig","responseModalities"],o);const i=b(e,["temperature"]);t!==void 0&&i!=null&&_(t,["setup","generationConfig","temperature"],i);const s=b(e,["topP"]);t!==void 0&&s!=null&&_(t,["setup","generationConfig","topP"],s);const a=b(e,["topK"]);t!==void 0&&a!=null&&_(t,["setup","generationConfig","topK"],a);const u=b(e,["maxOutputTokens"]);t!==void 0&&u!=null&&_(t,["setup","generationConfig","maxOutputTokens"],u);const l=b(e,["mediaResolution"]);t!==void 0&&l!=null&&_(t,["setup","generationConfig","mediaResolution"],l);const c=b(e,["seed"]);t!==void 0&&c!=null&&_(t,["setup","generationConfig","seed"],c);const d=b(e,["speechConfig"]);t!==void 0&&d!=null&&_(t,["setup","generationConfig","speechConfig"],EWe(iJ(d)));const p=b(e,["thinkingConfig"]);t!==void 0&&p!=null&&_(t,["setup","generationConfig","thinkingConfig"],p);const m=b(e,["enableAffectiveDialog"]);t!==void 0&&m!=null&&_(t,["setup","generationConfig","enableAffectiveDialog"],m);const h=b(e,["systemInstruction"]);t!==void 0&&h!=null&&_(t,["setup","systemInstruction"],_We(Ii(h)));const g=b(e,["tools"]);if(t!==void 0&&g!=null){let D=xh(g);Array.isArray(D)&&(D=D.map(L=>kWe(Ch(L)))),_(t,["setup","tools"],D)}const y=b(e,["sessionResumption"]);t!==void 0&&y!=null&&_(t,["setup","sessionResumption"],y);const v=b(e,["inputAudioTranscription"]);t!==void 0&&v!=null&&_(t,["setup","inputAudioTranscription"],v);const w=b(e,["outputAudioTranscription"]);t!==void 0&&w!=null&&_(t,["setup","outputAudioTranscription"],w);const T=b(e,["realtimeInputConfig"]);t!==void 0&&T!=null&&_(t,["setup","realtimeInputConfig"],T);const E=b(e,["contextWindowCompression"]);t!==void 0&&E!=null&&_(t,["setup","contextWindowCompression"],E);const k=b(e,["proactivity"]);t!==void 0&&k!=null&&_(t,["setup","proactivity"],k);const A=b(e,["explicitVadSignal"]);t!==void 0&&A!=null&&_(t,["setup","explicitVadSignal"],A);const C=b(e,["avatarConfig"]);t!==void 0&&C!=null&&_(t,["setup","avatarConfig"],C);const R=b(e,["safetySettings"]);if(t!==void 0&&R!=null){let D=R;Array.isArray(D)&&(D=D.map(L=>L)),_(t,["setup","safetySettings"],D)}const x=b(e,["translationConfig"]);t!==void 0&&x!=null&&_(t,["setup","generationConfig","translationConfig"],x);const P=b(e,["labels"]);return t!==void 0&&P!=null&&_(t,["setup","labels"],P),r}function xrn(e,t){const r={},n=b(t,["model"]);n!=null&&_(r,["setup","model"],Qr(e,n));const o=b(t,["config"]);return o!=null&&_(r,["config"],Arn(o,r)),r}function Irn(e,t){const r={},n=b(t,["model"]);n!=null&&_(r,["setup","model"],Qr(e,n));const o=b(t,["config"]);return o!=null&&_(r,["config"],Crn(o,r)),r}function Rrn(e){const t={},r=b(e,["musicGenerationConfig"]);return r!=null&&_(t,["musicGenerationConfig"],r),t}function Mrn(e){const t={},r=b(e,["weightedPrompts"]);if(r!=null){let n=r;Array.isArray(n)&&(n=n.map(o=>o)),_(t,["weightedPrompts"],n)}return t}function Prn(e){const t={},r=b(e,["media"]);if(r!=null){let l=jVe(r);Array.isArray(l)&&(l=l.map(c=>c)),_(t,["mediaChunks"],l)}const n=b(e,["audio"]);n!=null&&_(t,["audio"],HVe(n));const o=b(e,["audioStreamEnd"]);o!=null&&_(t,["audioStreamEnd"],o);const i=b(e,["video"]);i!=null&&_(t,["video"],VVe(i));const s=b(e,["text"]);s!=null&&_(t,["text"],s);const a=b(e,["activityStart"]);a!=null&&_(t,["activityStart"],a);const u=b(e,["activityEnd"]);return u!=null&&_(t,["activityEnd"],u),t}function Drn(e){const t={},r=b(e,["media"]);if(r!=null){let l=jVe(r);Array.isArray(l)&&(l=l.map(c=>c)),_(t,["mediaChunks"],l)}const n=b(e,["audio"]);n!=null&&_(t,["audio"],HVe(n));const o=b(e,["audioStreamEnd"]);o!=null&&_(t,["audioStreamEnd"],o);const i=b(e,["video"]);i!=null&&_(t,["video"],VVe(i));const s=b(e,["text"]);s!=null&&_(t,["text"],s);const a=b(e,["activityStart"]);a!=null&&_(t,["activityStart"],a);const u=b(e,["activityEnd"]);return u!=null&&_(t,["activityEnd"],u),t}function Orn(e){const t={},r=b(e,["setupComplete"]);r!=null&&_(t,["setupComplete"],r);const n=b(e,["serverContent"]);n!=null&&_(t,["serverContent"],n);const o=b(e,["toolCall"]);o!=null&&_(t,["toolCall"],o);const i=b(e,["toolCallCancellation"]);i!=null&&_(t,["toolCallCancellation"],i);const s=b(e,["usageMetadata"]);s!=null&&_(t,["usageMetadata"],qrn(s));const a=b(e,["goAway"]);a!=null&&_(t,["goAway"],a);const u=b(e,["sessionResumptionUpdate"]);u!=null&&_(t,["sessionResumptionUpdate"],u);const l=b(e,["voiceActivityDetectionSignal"]);l!=null&&_(t,["voiceActivityDetectionSignal"],l);const c=b(e,["voiceActivity"]);return c!=null&&_(t,["voiceActivity"],jrn(c)),t}function Nrn(e){const t={};if(b(e,["name"])!==void 0)throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(b(e,["streamableHttpTransport"])!==void 0)throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}function Lrn(e){const t={},r=b(e,["speakerVoiceConfigs"]);if(r!=null){let n=r;Array.isArray(n)&&(n=n.map(o=>Grn(o))),_(t,["speakerVoiceConfigs"],n)}return t}function $rn(e){const t={},r=b(e,["mediaResolution"]);r!=null&&_(t,["mediaResolution"],r);const n=b(e,["toolCall"]);n!=null&&_(t,["toolCall"],n);const o=b(e,["toolResponse"]);o!=null&&_(t,["toolResponse"],o);const i=b(e,["audioTranscription"]);i!=null&&_(t,["audioTranscription"],i);const s=b(e,["codeExecutionResult"]);s!=null&&_(t,["codeExecutionResult"],s);const a=b(e,["executableCode"]);a!=null&&_(t,["executableCode"],a);const u=b(e,["fileData"]);u!=null&&_(t,["fileData"],u);const l=b(e,["functionCall"]);l!=null&&_(t,["functionCall"],vrn(l));const c=b(e,["functionResponse"]);c!=null&&_(t,["functionResponse"],c);const d=b(e,["inlineData"]);d!=null&&_(t,["inlineData"],d);const p=b(e,["text"]);p!=null&&_(t,["text"],p);const m=b(e,["thought"]);m!=null&&_(t,["thought"],m);const h=b(e,["thoughtSignature"]);h!=null&&_(t,["thoughtSignature"],h);const g=b(e,["videoMetadata"]);g!=null&&_(t,["videoMetadata"],g);const y=b(e,["partMetadata"]);y!=null&&_(t,["partMetadata"],y);const v=b(e,["mediaProcessing"]);v!=null&&_(t,["mediaProcessing"],v);const w=b(e,["speechMetadata"]);return w!=null&&_(t,["speechMetadata"],w),t}function Frn(e){const t={},r=b(e,["mediaResolution"]);if(r!=null&&_(t,["mediaResolution"],r),b(e,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(b(e,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const n=b(e,["audioTranscription"]);n!=null&&_(t,["audioTranscription"],n);const o=b(e,["codeExecutionResult"]);o!=null&&_(t,["codeExecutionResult"],o);const i=b(e,["executableCode"]);i!=null&&_(t,["executableCode"],i);const s=b(e,["fileData"]);s!=null&&_(t,["fileData"],s);const a=b(e,["functionCall"]);a!=null&&_(t,["functionCall"],a);const u=b(e,["functionResponse"]);u!=null&&_(t,["functionResponse"],u);const l=b(e,["inlineData"]);l!=null&&_(t,["inlineData"],l);const c=b(e,["text"]);c!=null&&_(t,["text"],c);const d=b(e,["thought"]);d!=null&&_(t,["thought"],d);const p=b(e,["thoughtSignature"]);p!=null&&_(t,["thoughtSignature"],p);const m=b(e,["videoMetadata"]);if(m!=null&&_(t,["videoMetadata"],m),b(e,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const h=b(e,["mediaProcessing"]);h!=null&&_(t,["mediaProcessing"],h);const g=b(e,["speechMetadata"]);return g!=null&&_(t,["speechMetadata"],g),t}function Urn(e){const t={},r=b(e,["mimeType"]);r!=null&&_(t,["mimeType"],r);const n=b(e,["voiceSampleAudio"]);if(n!=null&&_(t,["voiceSampleAudio"],n),b(e,["consentAudio"])!==void 0)throw new Error("consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(b(e,["voiceConsentSignature"])!==void 0)throw new Error("voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}function Brn(e){const t={},r=b(e,["category"]);if(r!=null&&_(t,["category"],r),b(e,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=b(e,["threshold"]);return n!=null&&_(t,["threshold"],n),t}function zrn(e){const t={},r=b(e,["handle"]);if(r!=null&&_(t,["handle"],r),b(e,["transparent"])!==void 0)throw new Error("transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function Grn(e){const t={},r=b(e,["speaker"]);r!=null&&_(t,["speaker"],r);const n=b(e,["voiceConfig"]);return n!=null&&_(t,["voiceConfig"],AWe(n)),t}function EWe(e){const t={},r=b(e,["voiceConfig"]);r!=null&&_(t,["voiceConfig"],AWe(r));const n=b(e,["languageCode"]);n!=null&&_(t,["languageCode"],n);const o=b(e,["multiSpeakerVoiceConfig"]);return o!=null&&_(t,["multiSpeakerVoiceConfig"],Lrn(o)),t}function SWe(e){const t={};if(b(e,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const r=b(e,["googleMaps"]);r!=null&&_(t,["googleMaps"],brn(r));const n=b(e,["mcpServers"]);if(n!=null){let d=n;Array.isArray(d)&&(d=d.map(p=>p)),_(t,["mcpServers"],d)}const o=b(e,["codeExecution"]);o!=null&&_(t,["codeExecution"],o);const i=b(e,["computerUse"]);if(i!=null&&_(t,["computerUse"],i),b(e,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const s=b(e,["functionDeclarations"]);if(s!=null){let d=s;Array.isArray(d)&&(d=d.map(p=>p)),_(t,["functionDeclarations"],d)}const a=b(e,["googleSearch"]);a!=null&&_(t,["googleSearch"],Trn(a));const u=b(e,["googleSearchRetrieval"]);if(u!=null&&_(t,["googleSearchRetrieval"],u),b(e,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const l=b(e,["urlContext"]);l!=null&&_(t,["urlContext"],l);const c=b(e,["fileSearch"]);return c!=null&&_(t,["fileSearch"],c),t}function kWe(e){const t={},r=b(e,["retrieval"]);r!=null&&_(t,["retrieval"],r);const n=b(e,["googleMaps"]);n!=null&&_(t,["googleMaps"],n);const o=b(e,["mcpServers"]);if(o!=null){let h=o;Array.isArray(h)&&(h=h.map(g=>Nrn(g))),_(t,["mcpServers"],h)}const i=b(e,["codeExecution"]);i!=null&&_(t,["codeExecution"],i);const s=b(e,["computerUse"]);s!=null&&_(t,["computerUse"],s);const a=b(e,["enterpriseWebSearch"]);a!=null&&_(t,["enterpriseWebSearch"],a);const u=b(e,["exaAiSearch"]);u!=null&&_(t,["exaAiSearch"],u);const l=b(e,["functionDeclarations"]);if(l!=null){let h=l;Array.isArray(h)&&(h=h.map(g=>g)),_(t,["functionDeclarations"],h)}const c=b(e,["googleSearch"]);c!=null&&_(t,["googleSearch"],c);const d=b(e,["googleSearchRetrieval"]);d!=null&&_(t,["googleSearchRetrieval"],d);const p=b(e,["parallelAiSearch"]);p!=null&&_(t,["parallelAiSearch"],p);const m=b(e,["urlContext"]);if(m!=null&&_(t,["urlContext"],m),b(e,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}function qrn(e){const t={},r=b(e,["candidatesTokenCount"]);r!=null&&_(t,["responseTokenCount"],r);const n=b(e,["candidatesTokensDetails"]);if(n!=null){let m=n;Array.isArray(m)&&(m=m.map(h=>h)),_(t,["responseTokensDetails"],m)}const o=b(e,["cacheTokensDetails"]);if(o!=null){let m=o;Array.isArray(m)&&(m=m.map(h=>h)),_(t,["cacheTokensDetails"],m)}const i=b(e,["cachedContentTokenCount"]);i!=null&&_(t,["cachedContentTokenCount"],i);const s=b(e,["promptTokenCount"]);s!=null&&_(t,["promptTokenCount"],s);const a=b(e,["promptTokensDetails"]);if(a!=null){let m=a;Array.isArray(m)&&(m=m.map(h=>h)),_(t,["promptTokensDetails"],m)}const u=b(e,["thoughtsTokenCount"]);u!=null&&_(t,["thoughtsTokenCount"],u);const l=b(e,["toolUsePromptTokenCount"]);l!=null&&_(t,["toolUsePromptTokenCount"],l);const c=b(e,["toolUsePromptTokensDetails"]);if(c!=null){let m=c;Array.isArray(m)&&(m=m.map(h=>h)),_(t,["toolUsePromptTokensDetails"],m)}const d=b(e,["totalTokenCount"]);d!=null&&_(t,["totalTokenCount"],d);const p=b(e,["trafficType"]);return p!=null&&_(t,["trafficType"],p),t}function jrn(e){const t={},r=b(e,["type"]);r!=null&&_(t,["voiceActivityType"],r);const n=b(e,["audioOffset"]);return n!=null&&_(t,["audioOffset"],n),t}function AWe(e){const t={},r=b(e,["replicatedVoiceConfig"]);r!=null&&_(t,["replicatedVoiceConfig"],Urn(r));const n=b(e,["prebuiltVoiceConfig"]);n!=null&&_(t,["prebuiltVoiceConfig"],n);const o=b(e,["voice"]);return o!=null&&_(t,["voice"],o),t}function Vrn(e,t){const r={},n=b(e,["apiKey"]);if(n!=null&&_(r,["apiKey"],n),b(e,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return r}function Hrn(e,t){const r={},n=b(e,["content"]);n!=null&&_(r,["content"],n);const o=b(e,["citationMetadata"]);o!=null&&_(r,["citationMetadata"],Wrn(o));const i=b(e,["tokenCount"]);i!=null&&_(r,["tokenCount"],i);const s=b(e,["finishReason"]);s!=null&&_(r,["finishReason"],s);const a=b(e,["groundingMetadata"]);a!=null&&_(r,["groundingMetadata"],a);const u=b(e,["avgLogprobs"]);u!=null&&_(r,["avgLogprobs"],u);const l=b(e,["index"]);l!=null&&_(r,["index"],l);const c=b(e,["logprobsResult"]);c!=null&&_(r,["logprobsResult"],c);const d=b(e,["safetyRatings"]);if(d!=null){let h=d;Array.isArray(h)&&(h=h.map(g=>g)),_(r,["safetyRatings"],h)}const p=b(e,["urlContextMetadata"]);p!=null&&_(r,["urlContextMetadata"],p);const m=b(e,["continuationToken"]);return m!=null&&_(r,["continuationToken"],m),r}function Wrn(e,t){const r={},n=b(e,["citationSources"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(i=>i)),_(r,["citations"],o)}return r}function Krn(e,t,r){const n={},o=b(t,["model"]);o!=null&&_(n,["_url","model"],Qr(e,o));const i=b(t,["contents"]);if(i!=null){let s=Ya(i);Array.isArray(s)&&(s=s.map(a=>fb(a))),_(n,["contents"],s)}return n}function Jrn(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["tokensInfo"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(s=>s)),_(r,["tokensInfo"],i)}return r}function Xrn(e,t){const r={},n=b(e,["values"]);n!=null&&_(r,["values"],n);const o=b(e,["statistics"]);return o!=null&&_(r,["statistics"],Yrn(o)),r}function Yrn(e,t){const r={},n=b(e,["truncated"]);n!=null&&_(r,["truncated"],n);const o=b(e,["token_count"]);o!=null&&_(r,["tokenCount"],o);const i=b(e,["tokensDetails"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(a=>a)),_(r,["tokensDetails"],s)}return r}function IA(e,t){const r={},n=b(e,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(s=>ton(s))),_(r,["parts"],i)}const o=b(e,["role"]);return o!=null&&_(r,["role"],o),r}function fb(e,t){const r={},n=b(e,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(s=>ron(s))),_(r,["parts"],i)}const o=b(e,["role"]);return o!=null&&_(r,["role"],o),r}function Zrn(e,t){const r={},n=b(e,["controlType"]);n!=null&&_(r,["controlType"],n);const o=b(e,["enableControlImageComputation"]);return o!=null&&_(r,["computeControl"],o),r}function Qrn(e,t){const r={};if(b(e,["systemInstruction"])!==void 0)throw new Error("systemInstruction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["tools"])!==void 0)throw new Error("tools parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["generationConfig"])!==void 0)throw new Error("generationConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return r}function enn(e,t,r){const n={},o=b(e,["systemInstruction"]);t!==void 0&&o!=null&&_(t,["systemInstruction"],fb(Ii(o)));const i=b(e,["tools"]);if(t!==void 0&&i!=null){let a=i;Array.isArray(a)&&(a=a.map(u=>OWe(u))),_(t,["tools"],a)}const s=b(e,["generationConfig"]);return t!==void 0&&s!=null&&_(t,["generationConfig"],Unn(s)),n}function tnn(e,t,r){const n={},o=b(t,["model"]);o!=null&&_(n,["_url","model"],Qr(e,o));const i=b(t,["contents"]);if(i!=null){let a=Ya(i);Array.isArray(a)&&(a=a.map(u=>IA(u))),_(n,["contents"],a)}const s=b(t,["config"]);return s!=null&&Qrn(s),n}function rnn(e,t,r){const n={},o=b(t,["model"]);o!=null&&_(n,["_url","model"],Qr(e,o));const i=b(t,["contents"]);if(i!=null){let a=Ya(i);Array.isArray(a)&&(a=a.map(u=>fb(u))),_(n,["contents"],a)}const s=b(t,["config"]);return s!=null&&enn(s,n),n}function nnn(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["totalTokens"]);o!=null&&_(r,["totalTokens"],o);const i=b(e,["cachedContentTokenCount"]);return i!=null&&_(r,["cachedContentTokenCount"],i),r}function onn(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["totalTokens"]);return o!=null&&_(r,["totalTokens"],o),r}function inn(e,t,r){const n={},o=b(t,["model"]);return o!=null&&_(n,["_url","name"],Qr(e,o)),n}function snn(e,t,r){const n={},o=b(t,["model"]);return o!=null&&_(n,["_url","name"],Qr(e,o)),n}function ann(e,t){const r={},n=b(e,["sdkHttpResponse"]);return n!=null&&_(r,["sdkHttpResponse"],n),r}function unn(e,t){const r={},n=b(e,["sdkHttpResponse"]);return n!=null&&_(r,["sdkHttpResponse"],n),r}function lnn(e,t,r){const n={},o=b(e,["outputGcsUri"]);t!==void 0&&o!=null&&_(t,["parameters","storageUri"],o);const i=b(e,["negativePrompt"]);t!==void 0&&i!=null&&_(t,["parameters","negativePrompt"],i);const s=b(e,["numberOfImages"]);t!==void 0&&s!=null&&_(t,["parameters","sampleCount"],s);const a=b(e,["aspectRatio"]);t!==void 0&&a!=null&&_(t,["parameters","aspectRatio"],a);const u=b(e,["guidanceScale"]);t!==void 0&&u!=null&&_(t,["parameters","guidanceScale"],u);const l=b(e,["seed"]);t!==void 0&&l!=null&&_(t,["parameters","seed"],l);const c=b(e,["safetyFilterLevel"]);t!==void 0&&c!=null&&_(t,["parameters","safetySetting"],c);const d=b(e,["personGeneration"]);t!==void 0&&d!=null&&_(t,["parameters","personGeneration"],d);const p=b(e,["includeSafetyAttributes"]);t!==void 0&&p!=null&&_(t,["parameters","includeSafetyAttributes"],p);const m=b(e,["includeRaiReason"]);t!==void 0&&m!=null&&_(t,["parameters","includeRaiReason"],m);const h=b(e,["language"]);t!==void 0&&h!=null&&_(t,["parameters","language"],h);const g=b(e,["outputMimeType"]);t!==void 0&&g!=null&&_(t,["parameters","outputOptions","mimeType"],g);const y=b(e,["outputCompressionQuality"]);t!==void 0&&y!=null&&_(t,["parameters","outputOptions","compressionQuality"],y);const v=b(e,["addWatermark"]);t!==void 0&&v!=null&&_(t,["parameters","addWatermark"],v);const w=b(e,["labels"]);t!==void 0&&w!=null&&_(t,["labels"],w);const T=b(e,["editMode"]);t!==void 0&&T!=null&&_(t,["parameters","editMode"],T);const E=b(e,["baseSteps"]);return t!==void 0&&E!=null&&_(t,["parameters","editConfig","baseSteps"],E),n}function cnn(e,t,r){const n={},o=b(t,["model"]);o!=null&&_(n,["_url","model"],Qr(e,o));const i=b(t,["prompt"]);i!=null&&_(n,["instances[0]","prompt"],i);const s=b(t,["referenceImages"]);if(s!=null){let u=s;Array.isArray(u)&&(u=u.map(l=>uon(l))),_(n,["instances[0]","referenceImages"],u)}const a=b(t,["config"]);return a!=null&&lnn(a,n),n}function dnn(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["predictions"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(s=>fO(s))),_(r,["generatedImages"],i)}return r}function pnn(e,t,r){const n={},o=b(e,["taskType"]);t!==void 0&&o!=null&&_(t,["requests[]","taskType"],o);const i=b(e,["title"]);t!==void 0&&i!=null&&_(t,["requests[]","title"],i);const s=b(e,["outputDimensionality"]);if(t!==void 0&&s!=null&&_(t,["requests[]","outputDimensionality"],s),b(e,["mimeType"])!==void 0)throw new Error("mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["documentOcr"])!==void 0)throw new Error("documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["audioTrackExtraction"])!==void 0)throw new Error("audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function mnn(e,t,r){const n={};let o=b(r,["embeddingApiType"]);if(o===void 0&&(o="PREDICT"),o==="PREDICT"){const d=b(e,["taskType"]);t!==void 0&&d!=null&&_(t,["instances[]","task_type"],d)}else if(o==="EMBED_CONTENT"){const d=b(e,["taskType"]);t!==void 0&&d!=null&&_(t,["embedContentConfig","taskType"],d)}let i=b(r,["embeddingApiType"]);if(i===void 0&&(i="PREDICT"),i==="PREDICT"){const d=b(e,["title"]);t!==void 0&&d!=null&&_(t,["instances[]","title"],d)}else if(i==="EMBED_CONTENT"){const d=b(e,["title"]);t!==void 0&&d!=null&&_(t,["embedContentConfig","title"],d)}let s=b(r,["embeddingApiType"]);if(s===void 0&&(s="PREDICT"),s==="PREDICT"){const d=b(e,["outputDimensionality"]);t!==void 0&&d!=null&&_(t,["parameters","outputDimensionality"],d)}else if(s==="EMBED_CONTENT"){const d=b(e,["outputDimensionality"]);t!==void 0&&d!=null&&_(t,["embedContentConfig","outputDimensionality"],d)}let a=b(r,["embeddingApiType"]);if(a===void 0&&(a="PREDICT"),a==="PREDICT"){const d=b(e,["mimeType"]);t!==void 0&&d!=null&&_(t,["instances[]","mimeType"],d)}let u=b(r,["embeddingApiType"]);if(u===void 0&&(u="PREDICT"),u==="PREDICT"){const d=b(e,["autoTruncate"]);t!==void 0&&d!=null&&_(t,["parameters","autoTruncate"],d)}else if(u==="EMBED_CONTENT"){const d=b(e,["autoTruncate"]);t!==void 0&&d!=null&&_(t,["embedContentConfig","autoTruncate"],d)}let l=b(r,["embeddingApiType"]);if(l===void 0&&(l="PREDICT"),l==="EMBED_CONTENT"){const d=b(e,["documentOcr"]);t!==void 0&&d!=null&&_(t,["embedContentConfig","documentOcr"],d)}let c=b(r,["embeddingApiType"]);if(c===void 0&&(c="PREDICT"),c==="EMBED_CONTENT"){const d=b(e,["audioTrackExtraction"]);t!==void 0&&d!=null&&_(t,["embedContentConfig","audioTrackExtraction"],d)}return n}function hnn(e,t,r){const n={},o=b(t,["model"]);o!=null&&_(n,["_url","model"],Qr(e,o));const i=b(t,["contents"]);if(i!=null){let l=rJ(e,i);Array.isArray(l)&&(l=l.map(c=>c)),_(n,["requests[]","content"],l)}const s=b(t,["content"]);s!=null&&IA(Ii(s));const a=b(t,["config"]);a!=null&&pnn(a,n);const u=b(t,["model"]);return u!==void 0&&_(n,["requests[]","model"],Qr(e,u)),n}function fnn(e,t,r){const n={},o=b(t,["model"]);o!=null&&_(n,["_url","model"],Qr(e,o));let i=b(r,["embeddingApiType"]);if(i===void 0&&(i="PREDICT"),i==="PREDICT"){const u=b(t,["contents"]);if(u!=null){let l=rJ(e,u);Array.isArray(l)&&(l=l.map(c=>c)),_(n,["instances[]","content"],l)}}let s=b(r,["embeddingApiType"]);if(s===void 0&&(s="PREDICT"),s==="EMBED_CONTENT"){const u=b(t,["content"]);u!=null&&_(n,["content"],fb(Ii(u)))}const a=b(t,["config"]);return a!=null&&mnn(a,n,r),n}function gnn(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["embeddings"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(a=>a)),_(r,["embeddings"],s)}const i=b(e,["metadata"]);return i!=null&&_(r,["metadata"],i),r}function ynn(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["predictions[]","embeddings"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(a=>Xrn(a))),_(r,["embeddings"],s)}const i=b(e,["metadata"]);if(i!=null&&_(r,["metadata"],i),t&&b(t,["embeddingApiType"])==="EMBED_CONTENT"){const s=b(e,["embedding"]),a=b(e,["usageMetadata"]),u=b(e,["truncated"]);if(s){const l={};a&&a.promptTokenCount&&(l.tokenCount=a.promptTokenCount),a&&a.promptTokensDetails&&(l.tokensDetails=a.promptTokensDetails),u&&(l.truncated=u),s.statistics=l,_(r,["embeddings"],[s])}}return r}function vnn(e,t){const r={},n=b(e,["endpoint"]);n!=null&&_(r,["name"],n);const o=b(e,["deployedModelId"]);return o!=null&&_(r,["deployedModelId"],o),r}function wnn(e,t){const r={},n=b(e,["args"]);n!=null&&_(r,["args"],n);const o=b(e,["id"]);o!=null&&_(r,["id"],o);const i=b(e,["name"]);if(i!=null&&_(r,["name"],i),b(e,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return r}function bnn(e,t){const r={},n=b(e,["allowedFunctionNames"]);n!=null&&_(r,["allowedFunctionNames"],n);const o=b(e,["mode"]);if(o!=null&&_(r,["mode"],o),b(e,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return r}function Tnn(e,t,r,n){const o={},i=b(t,["serviceTier"]);r!==void 0&&i!=null&&_(r,["serviceTier"],i);const s=b(t,["systemInstruction"]);r!==void 0&&s!=null&&_(r,["systemInstruction"],IA(Ii(s)));const a=b(t,["temperature"]);a!=null&&_(o,["temperature"],a);const u=b(t,["topP"]);u!=null&&_(o,["topP"],u);const l=b(t,["topK"]);l!=null&&_(o,["topK"],l);const c=b(t,["candidateCount"]);c!=null&&_(o,["candidateCount"],c);const d=b(t,["maxOutputTokens"]);d!=null&&_(o,["maxOutputTokens"],d);const p=b(t,["stopSequences"]);p!=null&&_(o,["stopSequences"],p);const m=b(t,["responseLogprobs"]);m!=null&&_(o,["responseLogprobs"],m);const h=b(t,["logprobs"]);h!=null&&_(o,["logprobs"],h);const g=b(t,["presencePenalty"]);g!=null&&_(o,["presencePenalty"],g);const y=b(t,["frequencyPenalty"]);y!=null&&_(o,["frequencyPenalty"],y);const v=b(t,["seed"]);v!=null&&_(o,["seed"],v);const w=b(t,["responseMimeType"]);w!=null&&_(o,["responseMimeType"],w);const T=b(t,["responseSchema"]);T!=null&&_(o,["responseSchema"],nJ(T));const E=b(t,["responseJsonSchema"]);if(E!=null&&_(o,["responseJsonSchema"],E),b(t,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(t,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const k=b(t,["safetySettings"]);if(r!==void 0&&k!=null){let q=k;Array.isArray(q)&&(q=q.map(H=>con(H))),_(r,["safetySettings"],q)}const A=b(t,["tools"]);if(r!==void 0&&A!=null){let q=xh(A);Array.isArray(q)&&(q=q.map(H=>won(Ch(H)))),_(r,["tools"],q)}const C=b(t,["toolConfig"]);r!==void 0&&C!=null&&_(r,["toolConfig"],yon(C));const R=b(t,["labels"]);r!==void 0&&R!=null&&_(r,["labels"],R);const x=b(t,["cachedContent"]);r!==void 0&&x!=null&&_(r,["cachedContent"],jp(e,x));const P=b(t,["responseModalities"]);P!=null&&_(o,["responseModalities"],P);const D=b(t,["mediaResolution"]);D!=null&&_(o,["mediaResolution"],D);const L=b(t,["speechConfig"]);if(L!=null&&_(o,["speechConfig"],oJ(L)),b(t,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const O=b(t,["thinkingConfig"]);O!=null&&_(o,["thinkingConfig"],O);const N=b(t,["audioTranscriptionConfig"]);N!=null&&_(o,["audioTranscriptionConfig"],N);const U=b(t,["imageConfig"]);U!=null&&_(o,["imageConfig"],jnn(U));const $=b(t,["enableEnhancedCivicAnswers"]);if($!=null&&_(o,["enableEnhancedCivicAnswers"],$),b(t,["modelArmorConfig"])!==void 0)throw new Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const G=b(t,["continuationToken"]);if(r!==void 0&&G!=null&&_(r,["continuationToken"],G),b(t,["generationOutputConfig"])!==void 0)throw new Error("generationOutputConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const B=b(t,["store"]);return r!==void 0&&B!=null&&_(r,["store"],B),o}function _nn(e,t,r,n){const o={},i=b(t,["serviceTier"]);r!==void 0&&i!=null&&_(r,["serviceTier"],i);const s=b(t,["systemInstruction"]);r!==void 0&&s!=null&&_(r,["systemInstruction"],fb(Ii(s)));const a=b(t,["temperature"]);a!=null&&_(o,["temperature"],a);const u=b(t,["topP"]);u!=null&&_(o,["topP"],u);const l=b(t,["topK"]);l!=null&&_(o,["topK"],l);const c=b(t,["candidateCount"]);c!=null&&_(o,["candidateCount"],c);const d=b(t,["maxOutputTokens"]);d!=null&&_(o,["maxOutputTokens"],d);const p=b(t,["stopSequences"]);p!=null&&_(o,["stopSequences"],p);const m=b(t,["responseLogprobs"]);m!=null&&_(o,["responseLogprobs"],m);const h=b(t,["logprobs"]);h!=null&&_(o,["logprobs"],h);const g=b(t,["presencePenalty"]);g!=null&&_(o,["presencePenalty"],g);const y=b(t,["frequencyPenalty"]);y!=null&&_(o,["frequencyPenalty"],y);const v=b(t,["seed"]);v!=null&&_(o,["seed"],v);const w=b(t,["responseMimeType"]);w!=null&&_(o,["responseMimeType"],w);const T=b(t,["responseSchema"]);T!=null&&_(o,["responseSchema"],nJ(T));const E=b(t,["responseJsonSchema"]);E!=null&&_(o,["responseJsonSchema"],E);const k=b(t,["routingConfig"]);k!=null&&_(o,["routingConfig"],k);const A=b(t,["modelSelectionConfig"]);A!=null&&_(o,["modelConfig"],A);const C=b(t,["safetySettings"]);if(r!==void 0&&C!=null){let X=C;Array.isArray(X)&&(X=X.map(oe=>oe)),_(r,["safetySettings"],X)}const R=b(t,["tools"]);if(r!==void 0&&R!=null){let X=xh(R);Array.isArray(X)&&(X=X.map(oe=>OWe(Ch(oe)))),_(r,["tools"],X)}const x=b(t,["toolConfig"]);r!==void 0&&x!=null&&_(r,["toolConfig"],von(x));const P=b(t,["labels"]);r!==void 0&&P!=null&&_(r,["labels"],P);const D=b(t,["cachedContent"]);r!==void 0&&D!=null&&_(r,["cachedContent"],jp(e,D));const L=b(t,["responseModalities"]);L!=null&&_(o,["responseModalities"],L);const O=b(t,["mediaResolution"]);O!=null&&_(o,["mediaResolution"],O);const N=b(t,["speechConfig"]);N!=null&&_(o,["speechConfig"],DWe(oJ(N)));const U=b(t,["audioTimestamp"]);U!=null&&_(o,["audioTimestamp"],U);const $=b(t,["thinkingConfig"]);$!=null&&_(o,["thinkingConfig"],$);const G=b(t,["audioTranscriptionConfig"]);G!=null&&_(o,["audioTranscriptionConfig"],G);const B=b(t,["imageConfig"]);if(B!=null&&_(o,["imageConfig"],Vnn(B)),b(t,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const q=b(t,["modelArmorConfig"]);r!==void 0&&q!=null&&_(r,["modelArmorConfig"],q);const H=b(t,["continuationToken"]);r!==void 0&&H!=null&&_(r,["continuationToken"],H);const ne=b(t,["generationOutputConfig"]);if(r!==void 0&&ne!=null&&_(r,["outputConfig"],ne),b(t,["store"])!==void 0)throw new Error("store parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return o}function CWe(e,t,r){const n={},o=b(t,["model"]);o!=null&&_(n,["_url","model"],Qr(e,o));const i=b(t,["contents"]);if(i!=null){let a=Ya(i);Array.isArray(a)&&(a=a.map(u=>IA(u))),_(n,["contents"],a)}const s=b(t,["config"]);return s!=null&&_(n,["generationConfig"],Tnn(e,s,n)),n}function xWe(e,t,r){const n={},o=b(t,["model"]);o!=null&&_(n,["_url","model"],Qr(e,o));const i=b(t,["contents"]);if(i!=null){let a=Ya(i);Array.isArray(a)&&(a=a.map(u=>fb(u))),_(n,["contents"],a)}const s=b(t,["config"]);return s!=null&&_(n,["generationConfig"],_nn(e,s,n)),n}function IWe(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["candidates"]);if(o!=null){let c=o;Array.isArray(c)&&(c=c.map(d=>Hrn(d))),_(r,["candidates"],c)}const i=b(e,["modelVersion"]);i!=null&&_(r,["modelVersion"],i);const s=b(e,["promptFeedback"]);s!=null&&_(r,["promptFeedback"],s);const a=b(e,["responseId"]);a!=null&&_(r,["responseId"],a);const u=b(e,["usageMetadata"]);u!=null&&_(r,["usageMetadata"],u);const l=b(e,["modelStatus"]);return l!=null&&_(r,["modelStatus"],l),r}function RWe(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["candidates"]);if(o!=null){let c=o;Array.isArray(c)&&(c=c.map(d=>d)),_(r,["candidates"],c)}const i=b(e,["createTime"]);i!=null&&_(r,["createTime"],i);const s=b(e,["modelVersion"]);s!=null&&_(r,["modelVersion"],s);const a=b(e,["promptFeedback"]);a!=null&&_(r,["promptFeedback"],a);const u=b(e,["responseId"]);u!=null&&_(r,["responseId"],u);const l=b(e,["usageMetadata"]);return l!=null&&_(r,["usageMetadata"],l),r}function Enn(e,t,r){const n={},o=b(e,["outputGcsUri"]);t!==void 0&&o!=null&&_(t,["parameters","storageUri"],o);const i=b(e,["negativePrompt"]);t!==void 0&&i!=null&&_(t,["parameters","negativePrompt"],i);const s=b(e,["numberOfImages"]);t!==void 0&&s!=null&&_(t,["parameters","sampleCount"],s);const a=b(e,["aspectRatio"]);t!==void 0&&a!=null&&_(t,["parameters","aspectRatio"],a);const u=b(e,["guidanceScale"]);t!==void 0&&u!=null&&_(t,["parameters","guidanceScale"],u);const l=b(e,["seed"]);t!==void 0&&l!=null&&_(t,["parameters","seed"],l);const c=b(e,["safetyFilterLevel"]);t!==void 0&&c!=null&&_(t,["parameters","safetySetting"],c);const d=b(e,["personGeneration"]);t!==void 0&&d!=null&&_(t,["parameters","personGeneration"],d);const p=b(e,["includeSafetyAttributes"]);t!==void 0&&p!=null&&_(t,["parameters","includeSafetyAttributes"],p);const m=b(e,["includeRaiReason"]);t!==void 0&&m!=null&&_(t,["parameters","includeRaiReason"],m);const h=b(e,["language"]);t!==void 0&&h!=null&&_(t,["parameters","language"],h);const g=b(e,["outputMimeType"]);t!==void 0&&g!=null&&_(t,["parameters","outputOptions","mimeType"],g);const y=b(e,["outputCompressionQuality"]);t!==void 0&&y!=null&&_(t,["parameters","outputOptions","compressionQuality"],y);const v=b(e,["addWatermark"]);t!==void 0&&v!=null&&_(t,["parameters","addWatermark"],v);const w=b(e,["labels"]);t!==void 0&&w!=null&&_(t,["labels"],w);const T=b(e,["imageSize"]);t!==void 0&&T!=null&&_(t,["parameters","sampleImageSize"],T);const E=b(e,["enhancePrompt"]);return t!==void 0&&E!=null&&_(t,["parameters","enhancePrompt"],E),n}function Snn(e,t,r){const n={},o=b(t,["model"]);o!=null&&_(n,["_url","model"],Qr(e,o));const i=b(t,["prompt"]);i!=null&&_(n,["instances[0]","prompt"],i);const s=b(t,["config"]);return s!=null&&Enn(s,n),n}function knn(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["predictions"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(a=>fO(a))),_(r,["generatedImages"],s)}const i=b(e,["positivePromptSafetyAttributes"]);return i!=null&&_(r,["positivePromptSafetyAttributes"],PWe(i)),r}function Ann(e,t,r){const n={},o=b(e,["numberOfVideos"]);if(t!==void 0&&o!=null&&_(t,["parameters","sampleCount"],o),b(e,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["fps"])!==void 0)throw new Error("fps parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const i=b(e,["durationSeconds"]);if(t!==void 0&&i!=null&&_(t,["parameters","durationSeconds"],i),b(e,["seed"])!==void 0)throw new Error("seed parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const s=b(e,["aspectRatio"]);t!==void 0&&s!=null&&_(t,["parameters","aspectRatio"],s);const a=b(e,["resolution"]);t!==void 0&&a!=null&&_(t,["parameters","resolution"],a);const u=b(e,["personGeneration"]);if(t!==void 0&&u!=null&&_(t,["parameters","personGeneration"],u),b(e,["pubsubTopic"])!==void 0)throw new Error("pubsubTopic parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const l=b(e,["negativePrompt"]);t!==void 0&&l!=null&&_(t,["parameters","negativePrompt"],l);const c=b(e,["enhancePrompt"]);if(t!==void 0&&c!=null&&_(t,["parameters","enhancePrompt"],c),b(e,["generateAudio"])!==void 0)throw new Error("generateAudio parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const d=b(e,["lastFrame"]);t!==void 0&&d!=null&&_(t,["instances[0]","lastFrame"],gO(d));const p=b(e,["referenceImages"]);if(t!==void 0&&p!=null){let h=p;Array.isArray(h)&&(h=h.map(g=>Pon(g))),_(t,["instances[0]","referenceImages"],h)}if(b(e,["mask"])!==void 0)throw new Error("mask parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["compressionQuality"])!==void 0)throw new Error("compressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const m=b(e,["webhookConfig"]);if(t!==void 0&&m!=null&&_(t,["webhookConfig"],m),b(e,["resizeMode"])!==void 0)throw new Error("resizeMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function Cnn(e,t,r){const n={},o=b(e,["numberOfVideos"]);t!==void 0&&o!=null&&_(t,["parameters","sampleCount"],o);const i=b(e,["outputGcsUri"]);t!==void 0&&i!=null&&_(t,["parameters","storageUri"],i);const s=b(e,["fps"]);t!==void 0&&s!=null&&_(t,["parameters","fps"],s);const a=b(e,["durationSeconds"]);t!==void 0&&a!=null&&_(t,["parameters","durationSeconds"],a);const u=b(e,["seed"]);t!==void 0&&u!=null&&_(t,["parameters","seed"],u);const l=b(e,["aspectRatio"]);t!==void 0&&l!=null&&_(t,["parameters","aspectRatio"],l);const c=b(e,["resolution"]);t!==void 0&&c!=null&&_(t,["parameters","resolution"],c);const d=b(e,["personGeneration"]);t!==void 0&&d!=null&&_(t,["parameters","personGeneration"],d);const p=b(e,["pubsubTopic"]);t!==void 0&&p!=null&&_(t,["parameters","pubsubTopic"],p);const m=b(e,["negativePrompt"]);t!==void 0&&m!=null&&_(t,["parameters","negativePrompt"],m);const h=b(e,["enhancePrompt"]);t!==void 0&&h!=null&&_(t,["parameters","enhancePrompt"],h);const g=b(e,["generateAudio"]);t!==void 0&&g!=null&&_(t,["parameters","generateAudio"],g);const y=b(e,["lastFrame"]);t!==void 0&&y!=null&&_(t,["instances[0]","lastFrame"],wc(y));const v=b(e,["referenceImages"]);if(t!==void 0&&v!=null){let A=v;Array.isArray(A)&&(A=A.map(C=>Don(C))),_(t,["instances[0]","referenceImages"],A)}const w=b(e,["mask"]);t!==void 0&&w!=null&&_(t,["instances[0]","mask"],Mon(w));const T=b(e,["compressionQuality"]);t!==void 0&&T!=null&&_(t,["parameters","compressionQuality"],T);const E=b(e,["labels"]);if(t!==void 0&&E!=null&&_(t,["labels"],E),b(e,["webhookConfig"])!==void 0)throw new Error("webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const k=b(e,["resizeMode"]);return t!==void 0&&k!=null&&_(t,["parameters","resizeMode"],k),n}function xnn(e,t){const r={},n=b(e,["name"]);n!=null&&_(r,["name"],n);const o=b(e,["metadata"]);o!=null&&_(r,["metadata"],o);const i=b(e,["done"]);i!=null&&_(r,["done"],i);const s=b(e,["error"]);s!=null&&_(r,["error"],s);const a=b(e,["response","generateVideoResponse"]);return a!=null&&_(r,["response"],Pnn(a)),r}function Inn(e,t){const r={},n=b(e,["name"]);n!=null&&_(r,["name"],n);const o=b(e,["metadata"]);o!=null&&_(r,["metadata"],o);const i=b(e,["done"]);i!=null&&_(r,["done"],i);const s=b(e,["error"]);s!=null&&_(r,["error"],s);const a=b(e,["response"]);return a!=null&&_(r,["response"],Dnn(a)),r}function Rnn(e,t,r){const n={},o=b(t,["model"]);o!=null&&_(n,["_url","model"],Qr(e,o));const i=b(t,["prompt"]);i!=null&&_(n,["instances[0]","prompt"],i);const s=b(t,["image"]);s!=null&&_(n,["instances[0]","image"],gO(s));const a=b(t,["video"]);a!=null&&_(n,["instances[0]","video"],NWe(a));const u=b(t,["source"]);u!=null&&Onn(u,n);const l=b(t,["config"]);return l!=null&&Ann(l,n),n}function Mnn(e,t,r){const n={},o=b(t,["model"]);o!=null&&_(n,["_url","model"],Qr(e,o));const i=b(t,["prompt"]);i!=null&&_(n,["instances[0]","prompt"],i);const s=b(t,["image"]);s!=null&&_(n,["instances[0]","image"],wc(s));const a=b(t,["video"]);a!=null&&_(n,["instances[0]","video"],LWe(a));const u=b(t,["source"]);u!=null&&Nnn(u,n);const l=b(t,["config"]);return l!=null&&Cnn(l,n),n}function Pnn(e,t){const r={},n=b(e,["generatedSamples"]);if(n!=null){let s=n;Array.isArray(s)&&(s=s.map(a=>$nn(a))),_(r,["generatedVideos"],s)}const o=b(e,["raiMediaFilteredCount"]);o!=null&&_(r,["raiMediaFilteredCount"],o);const i=b(e,["raiMediaFilteredReasons"]);return i!=null&&_(r,["raiMediaFilteredReasons"],i),r}function Dnn(e,t){const r={},n=b(e,["videos"]);if(n!=null){let s=n;Array.isArray(s)&&(s=s.map(a=>Fnn(a))),_(r,["generatedVideos"],s)}const o=b(e,["raiMediaFilteredCount"]);o!=null&&_(r,["raiMediaFilteredCount"],o);const i=b(e,["raiMediaFilteredReasons"]);return i!=null&&_(r,["raiMediaFilteredReasons"],i),r}function Onn(e,t,r){const n={},o=b(e,["prompt"]);t!==void 0&&o!=null&&_(t,["instances[0]","prompt"],o);const i=b(e,["image"]);t!==void 0&&i!=null&&_(t,["instances[0]","image"],gO(i));const s=b(e,["video"]);return t!==void 0&&s!=null&&_(t,["instances[0]","video"],NWe(s)),n}function Nnn(e,t,r){const n={},o=b(e,["prompt"]);t!==void 0&&o!=null&&_(t,["instances[0]","prompt"],o);const i=b(e,["image"]);t!==void 0&&i!=null&&_(t,["instances[0]","image"],wc(i));const s=b(e,["video"]);return t!==void 0&&s!=null&&_(t,["instances[0]","video"],LWe(s)),n}function fO(e,t){const r={},n=b(e,["_self"]);n!=null&&_(r,["image"],MWe(n));const o=b(e,["raiFilteredReason"]);o!=null&&_(r,["raiFilteredReason"],o);const i=b(e,["_self"]);i!=null&&_(r,["safetyAttributes"],PWe(i));const s=b(e,["prompt"]);return s!=null&&_(r,["enhancedPrompt"],s),r}function Lnn(e,t){const r={},n=b(e,["_self"]);n!=null&&_(r,["mask"],MWe(n));const o=b(e,["labels"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(s=>s)),_(r,["labels"],i)}return r}function $nn(e,t){const r={},n=b(e,["video"]);return n!=null&&_(r,["video"],Ion(n)),r}function Fnn(e,t){const r={},n=b(e,["_self"]);return n!=null&&_(r,["video"],Ron(n)),r}function Unn(e,t){const r={},n=b(e,["modelSelectionConfig"]);n!=null&&_(r,["modelConfig"],n);const o=b(e,["responseJsonSchema"]);o!=null&&_(r,["responseJsonSchema"],o);const i=b(e,["audioTranscriptionConfig"]);i!=null&&_(r,["audioTranscriptionConfig"],i);const s=b(e,["audioTimestamp"]);s!=null&&_(r,["audioTimestamp"],s);const a=b(e,["candidateCount"]);a!=null&&_(r,["candidateCount"],a);const u=b(e,["enableAffectiveDialog"]);u!=null&&_(r,["enableAffectiveDialog"],u);const l=b(e,["frequencyPenalty"]);l!=null&&_(r,["frequencyPenalty"],l);const c=b(e,["logprobs"]);c!=null&&_(r,["logprobs"],c);const d=b(e,["maxOutputTokens"]);d!=null&&_(r,["maxOutputTokens"],d);const p=b(e,["mediaResolution"]);p!=null&&_(r,["mediaResolution"],p);const m=b(e,["presencePenalty"]);m!=null&&_(r,["presencePenalty"],m);const h=b(e,["responseFormat"]);if(h!=null){let L=h;Array.isArray(L)&&(L=L.map(O=>O)),_(r,["responseFormat"],L)}const g=b(e,["responseLogprobs"]);g!=null&&_(r,["responseLogprobs"],g);const y=b(e,["responseMimeType"]);y!=null&&_(r,["responseMimeType"],y);const v=b(e,["responseModalities"]);v!=null&&_(r,["responseModalities"],v);const w=b(e,["responseSchema"]);w!=null&&_(r,["responseSchema"],w);const T=b(e,["routingConfig"]);T!=null&&_(r,["routingConfig"],T);const E=b(e,["seed"]);E!=null&&_(r,["seed"],E);const k=b(e,["speechConfig"]);k!=null&&_(r,["speechConfig"],DWe(k));const A=b(e,["stopSequences"]);A!=null&&_(r,["stopSequences"],A);const C=b(e,["temperature"]);C!=null&&_(r,["temperature"],C);const R=b(e,["thinkingConfig"]);R!=null&&_(r,["thinkingConfig"],R);const x=b(e,["topK"]);x!=null&&_(r,["topK"],x);const P=b(e,["topP"]);if(P!=null&&_(r,["topP"],P),b(e,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const D=b(e,["translationConfig"]);return D!=null&&_(r,["translationConfig"],D),r}function Bnn(e,t,r){const n={},o=b(t,["model"]);return o!=null&&_(n,["_url","name"],Qr(e,o)),n}function znn(e,t,r){const n={},o=b(t,["model"]);return o!=null&&_(n,["_url","name"],Qr(e,o)),n}function Gnn(e,t){const r={},n=b(e,["authConfig"]);n!=null&&_(r,["authConfig"],Vrn(n));const o=b(e,["enableWidget"]);if(o!=null&&_(r,["enableWidget"],o),b(e,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return r}function qnn(e,t){const r={};if(b(e,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=b(e,["searchTypes"]);n!=null&&_(r,["searchTypes"],n);const o=b(e,["timeRangeFilter"]);return o!=null&&_(r,["timeRangeFilter"],o),r}function jnn(e,t){const r={},n=b(e,["aspectRatio"]);n!=null&&_(r,["aspectRatio"],n);const o=b(e,["imageSize"]);if(o!=null&&_(r,["imageSize"],o),b(e,["personGeneration"])!==void 0)throw new Error("personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["imageOutputOptions"])!==void 0)throw new Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["prominentPeople"])!==void 0)throw new Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return r}function Vnn(e,t){const r={},n=b(e,["aspectRatio"]);n!=null&&_(r,["aspectRatio"],n);const o=b(e,["imageSize"]);o!=null&&_(r,["imageSize"],o);const i=b(e,["personGeneration"]);i!=null&&_(r,["personGeneration"],i);const s=b(e,["outputMimeType"]);s!=null&&_(r,["imageOutputOptions","mimeType"],s);const a=b(e,["outputCompressionQuality"]);a!=null&&_(r,["imageOutputOptions","compressionQuality"],a);const u=b(e,["imageOutputOptions"]);u!=null&&_(r,["imageOutputOptions"],u);const l=b(e,["prominentPeople"]);return l!=null&&_(r,["prominentPeople"],l),r}function MWe(e,t){const r={},n=b(e,["gcsUri"]);n!=null&&_(r,["gcsUri"],n);const o=b(e,["bytesBase64Encoded"]);o!=null&&_(r,["imageBytes"],n0(o));const i=b(e,["mimeType"]);return i!=null&&_(r,["mimeType"],i),r}function gO(e,t){const r={};if(b(e,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=b(e,["imageBytes"]);n!=null&&_(r,["bytesBase64Encoded"],n0(n));const o=b(e,["mimeType"]);return o!=null&&_(r,["mimeType"],o),r}function wc(e,t){const r={},n=b(e,["gcsUri"]);n!=null&&_(r,["gcsUri"],n);const o=b(e,["imageBytes"]);o!=null&&_(r,["bytesBase64Encoded"],n0(o));const i=b(e,["mimeType"]);return i!=null&&_(r,["mimeType"],i),r}function Hnn(e,t,r,n){const o={},i=b(t,["pageSize"]);r!==void 0&&i!=null&&_(r,["_query","pageSize"],i);const s=b(t,["pageToken"]);r!==void 0&&s!=null&&_(r,["_query","pageToken"],s);const a=b(t,["filter"]);r!==void 0&&a!=null&&_(r,["_query","filter"],a);const u=b(t,["queryBase"]);return r!==void 0&&u!=null&&_(r,["_url","models_url"],QVe(e,u)),o}function Wnn(e,t,r,n){const o={},i=b(t,["pageSize"]);r!==void 0&&i!=null&&_(r,["_query","pageSize"],i);const s=b(t,["pageToken"]);r!==void 0&&s!=null&&_(r,["_query","pageToken"],s);const a=b(t,["filter"]);r!==void 0&&a!=null&&_(r,["_query","filter"],a);const u=b(t,["queryBase"]);return r!==void 0&&u!=null&&_(r,["_url","models_url"],QVe(e,u)),o}function Knn(e,t,r){const n={},o=b(t,["config"]);return o!=null&&Hnn(e,o,n),n}function Jnn(e,t,r){const n={},o=b(t,["config"]);return o!=null&&Wnn(e,o,n),n}function Xnn(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["nextPageToken"]);o!=null&&_(r,["nextPageToken"],o);const i=b(e,["_self"]);if(i!=null){let s=eHe(i);Array.isArray(s)&&(s=s.map(a=>dJ(a))),_(r,["models"],s)}return r}function Ynn(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["nextPageToken"]);o!=null&&_(r,["nextPageToken"],o);const i=b(e,["_self"]);if(i!=null){let s=eHe(i);Array.isArray(s)&&(s=s.map(a=>pJ(a))),_(r,["models"],s)}return r}function Znn(e,t){const r={},n=b(e,["maskMode"]);n!=null&&_(r,["maskMode"],n);const o=b(e,["segmentationClasses"]);o!=null&&_(r,["maskClasses"],o);const i=b(e,["maskDilation"]);return i!=null&&_(r,["dilation"],i),r}function Qnn(e,t){const r={};if(b(e,["name"])!==void 0)throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(b(e,["streamableHttpTransport"])!==void 0)throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return r}function dJ(e,t){const r={},n=b(e,["name"]);n!=null&&_(r,["name"],n);const o=b(e,["displayName"]);o!=null&&_(r,["displayName"],o);const i=b(e,["description"]);i!=null&&_(r,["description"],i);const s=b(e,["version"]);s!=null&&_(r,["version"],s);const a=b(e,["_self"]);a!=null&&_(r,["tunedModelInfo"],bon(a));const u=b(e,["inputTokenLimit"]);u!=null&&_(r,["inputTokenLimit"],u);const l=b(e,["outputTokenLimit"]);l!=null&&_(r,["outputTokenLimit"],l);const c=b(e,["supportedGenerationMethods"]);c!=null&&_(r,["supportedActions"],c);const d=b(e,["temperature"]);d!=null&&_(r,["temperature"],d);const p=b(e,["maxTemperature"]);p!=null&&_(r,["maxTemperature"],p);const m=b(e,["topP"]);m!=null&&_(r,["topP"],m);const h=b(e,["topK"]);h!=null&&_(r,["topK"],h);const g=b(e,["thinking"]);return g!=null&&_(r,["thinking"],g),r}function pJ(e,t){const r={},n=b(e,["name"]);n!=null&&_(r,["name"],n);const o=b(e,["displayName"]);o!=null&&_(r,["displayName"],o);const i=b(e,["description"]);i!=null&&_(r,["description"],i);const s=b(e,["versionId"]);s!=null&&_(r,["version"],s);const a=b(e,["deployedModels"]);if(a!=null){let p=a;Array.isArray(p)&&(p=p.map(m=>vnn(m))),_(r,["endpoints"],p)}const u=b(e,["labels"]);u!=null&&_(r,["labels"],u);const l=b(e,["_self"]);l!=null&&_(r,["tunedModelInfo"],Ton(l));const c=b(e,["defaultCheckpointId"]);c!=null&&_(r,["defaultCheckpointId"],c);const d=b(e,["checkpoints"]);if(d!=null){let p=d;Array.isArray(p)&&(p=p.map(m=>m)),_(r,["checkpoints"],p)}return r}function eon(e,t){const r={},n=b(e,["speakerVoiceConfigs"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(i=>gon(i))),_(r,["speakerVoiceConfigs"],o)}return r}function ton(e,t){const r={},n=b(e,["mediaResolution"]);n!=null&&_(r,["mediaResolution"],n);const o=b(e,["toolCall"]);o!=null&&_(r,["toolCall"],o);const i=b(e,["toolResponse"]);i!=null&&_(r,["toolResponse"],i);const s=b(e,["audioTranscription"]);s!=null&&_(r,["audioTranscription"],s);const a=b(e,["codeExecutionResult"]);a!=null&&_(r,["codeExecutionResult"],a);const u=b(e,["executableCode"]);u!=null&&_(r,["executableCode"],u);const l=b(e,["fileData"]);l!=null&&_(r,["fileData"],l);const c=b(e,["functionCall"]);c!=null&&_(r,["functionCall"],wnn(c));const d=b(e,["functionResponse"]);d!=null&&_(r,["functionResponse"],d);const p=b(e,["inlineData"]);p!=null&&_(r,["inlineData"],p);const m=b(e,["text"]);m!=null&&_(r,["text"],m);const h=b(e,["thought"]);h!=null&&_(r,["thought"],h);const g=b(e,["thoughtSignature"]);g!=null&&_(r,["thoughtSignature"],g);const y=b(e,["videoMetadata"]);y!=null&&_(r,["videoMetadata"],y);const v=b(e,["partMetadata"]);v!=null&&_(r,["partMetadata"],v);const w=b(e,["mediaProcessing"]);w!=null&&_(r,["mediaProcessing"],w);const T=b(e,["speechMetadata"]);return T!=null&&_(r,["speechMetadata"],T),r}function ron(e,t){const r={},n=b(e,["mediaResolution"]);if(n!=null&&_(r,["mediaResolution"],n),b(e,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(b(e,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const o=b(e,["audioTranscription"]);o!=null&&_(r,["audioTranscription"],o);const i=b(e,["codeExecutionResult"]);i!=null&&_(r,["codeExecutionResult"],i);const s=b(e,["executableCode"]);s!=null&&_(r,["executableCode"],s);const a=b(e,["fileData"]);a!=null&&_(r,["fileData"],a);const u=b(e,["functionCall"]);u!=null&&_(r,["functionCall"],u);const l=b(e,["functionResponse"]);l!=null&&_(r,["functionResponse"],l);const c=b(e,["inlineData"]);c!=null&&_(r,["inlineData"],c);const d=b(e,["text"]);d!=null&&_(r,["text"],d);const p=b(e,["thought"]);p!=null&&_(r,["thought"],p);const m=b(e,["thoughtSignature"]);m!=null&&_(r,["thoughtSignature"],m);const h=b(e,["videoMetadata"]);if(h!=null&&_(r,["videoMetadata"],h),b(e,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const g=b(e,["mediaProcessing"]);g!=null&&_(r,["mediaProcessing"],g);const y=b(e,["speechMetadata"]);return y!=null&&_(r,["speechMetadata"],y),r}function non(e,t){const r={},n=b(e,["productImage"]);return n!=null&&_(r,["image"],wc(n)),r}function oon(e,t,r){const n={},o=b(e,["numberOfImages"]);t!==void 0&&o!=null&&_(t,["parameters","sampleCount"],o);const i=b(e,["baseSteps"]);t!==void 0&&i!=null&&_(t,["parameters","baseSteps"],i);const s=b(e,["outputGcsUri"]);t!==void 0&&s!=null&&_(t,["parameters","storageUri"],s);const a=b(e,["seed"]);t!==void 0&&a!=null&&_(t,["parameters","seed"],a);const u=b(e,["safetyFilterLevel"]);t!==void 0&&u!=null&&_(t,["parameters","safetySetting"],u);const l=b(e,["personGeneration"]);t!==void 0&&l!=null&&_(t,["parameters","personGeneration"],l);const c=b(e,["addWatermark"]);t!==void 0&&c!=null&&_(t,["parameters","addWatermark"],c);const d=b(e,["outputMimeType"]);t!==void 0&&d!=null&&_(t,["parameters","outputOptions","mimeType"],d);const p=b(e,["outputCompressionQuality"]);t!==void 0&&p!=null&&_(t,["parameters","outputOptions","compressionQuality"],p);const m=b(e,["enhancePrompt"]);t!==void 0&&m!=null&&_(t,["parameters","enhancePrompt"],m);const h=b(e,["labels"]);return t!==void 0&&h!=null&&_(t,["labels"],h),n}function ion(e,t,r){const n={},o=b(t,["model"]);o!=null&&_(n,["_url","model"],Qr(e,o));const i=b(t,["source"]);i!=null&&aon(i,n);const s=b(t,["config"]);return s!=null&&oon(s,n),n}function son(e,t){const r={},n=b(e,["predictions"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(i=>fO(i))),_(r,["generatedImages"],o)}return r}function aon(e,t,r){const n={},o=b(e,["prompt"]);t!==void 0&&o!=null&&_(t,["instances[0]","prompt"],o);const i=b(e,["personImage"]);t!==void 0&&i!=null&&_(t,["instances[0]","personImage","image"],wc(i));const s=b(e,["productImages"]);if(t!==void 0&&s!=null){let a=s;Array.isArray(a)&&(a=a.map(u=>non(u))),_(t,["instances[0]","productImages"],a)}return n}function uon(e,t){const r={},n=b(e,["referenceImage"]);n!=null&&_(r,["referenceImage"],wc(n));const o=b(e,["referenceId"]);o!=null&&_(r,["referenceId"],o);const i=b(e,["referenceType"]);i!=null&&_(r,["referenceType"],i);const s=b(e,["maskImageConfig"]);s!=null&&_(r,["maskImageConfig"],Znn(s));const a=b(e,["controlImageConfig"]);a!=null&&_(r,["controlImageConfig"],Zrn(a));const u=b(e,["styleImageConfig"]);u!=null&&_(r,["styleImageConfig"],u);const l=b(e,["subjectImageConfig"]);return l!=null&&_(r,["subjectImageConfig"],l),r}function lon(e,t){const r={},n=b(e,["mimeType"]);n!=null&&_(r,["mimeType"],n);const o=b(e,["voiceSampleAudio"]);if(o!=null&&_(r,["voiceSampleAudio"],o),b(e,["consentAudio"])!==void 0)throw new Error("consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(b(e,["voiceConsentSignature"])!==void 0)throw new Error("voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return r}function PWe(e,t){const r={},n=b(e,["safetyAttributes","categories"]);n!=null&&_(r,["categories"],n);const o=b(e,["safetyAttributes","scores"]);o!=null&&_(r,["scores"],o);const i=b(e,["contentType"]);return i!=null&&_(r,["contentType"],i),r}function con(e,t){const r={},n=b(e,["category"]);if(n!=null&&_(r,["category"],n),b(e,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=b(e,["threshold"]);return o!=null&&_(r,["threshold"],o),r}function don(e,t){const r={},n=b(e,["image"]);return n!=null&&_(r,["image"],wc(n)),r}function pon(e,t,r){const n={},o=b(e,["mode"]);t!==void 0&&o!=null&&_(t,["parameters","mode"],o);const i=b(e,["maxPredictions"]);t!==void 0&&i!=null&&_(t,["parameters","maxPredictions"],i);const s=b(e,["confidenceThreshold"]);t!==void 0&&s!=null&&_(t,["parameters","confidenceThreshold"],s);const a=b(e,["maskDilation"]);t!==void 0&&a!=null&&_(t,["parameters","maskDilation"],a);const u=b(e,["binaryColorThreshold"]);t!==void 0&&u!=null&&_(t,["parameters","binaryColorThreshold"],u);const l=b(e,["labels"]);return t!==void 0&&l!=null&&_(t,["labels"],l),n}function mon(e,t,r){const n={},o=b(t,["model"]);o!=null&&_(n,["_url","model"],Qr(e,o));const i=b(t,["source"]);i!=null&&fon(i,n);const s=b(t,["config"]);return s!=null&&pon(s,n),n}function hon(e,t){const r={},n=b(e,["predictions"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(i=>Lnn(i))),_(r,["generatedMasks"],o)}return r}function fon(e,t,r){const n={},o=b(e,["prompt"]);t!==void 0&&o!=null&&_(t,["instances[0]","prompt"],o);const i=b(e,["image"]);t!==void 0&&i!=null&&_(t,["instances[0]","image"],wc(i));const s=b(e,["scribbleImage"]);return t!==void 0&&s!=null&&_(t,["instances[0]","scribble"],don(s)),n}function gon(e,t){const r={},n=b(e,["speaker"]);n!=null&&_(r,["speaker"],n);const o=b(e,["voiceConfig"]);return o!=null&&_(r,["voiceConfig"],$We(o)),r}function DWe(e,t){const r={},n=b(e,["voiceConfig"]);n!=null&&_(r,["voiceConfig"],$We(n));const o=b(e,["languageCode"]);o!=null&&_(r,["languageCode"],o);const i=b(e,["multiSpeakerVoiceConfig"]);return i!=null&&_(r,["multiSpeakerVoiceConfig"],eon(i)),r}function yon(e,t){const r={},n=b(e,["functionCallingConfig"]);n!=null&&_(r,["functionCallingConfig"],bnn(n));const o=b(e,["retrievalConfig"]);o!=null&&_(r,["retrievalConfig"],o);const i=b(e,["includeServerSideToolInvocations"]);return i!=null&&_(r,["includeServerSideToolInvocations"],i),r}function von(e,t){const r={},n=b(e,["functionCallingConfig"]);n!=null&&_(r,["functionCallingConfig"],n);const o=b(e,["retrievalConfig"]);if(o!=null&&_(r,["retrievalConfig"],o),b(e,["includeServerSideToolInvocations"])!==void 0)throw new Error("includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return r}function won(e,t){const r={};if(b(e,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=b(e,["googleMaps"]);n!=null&&_(r,["googleMaps"],Gnn(n));const o=b(e,["mcpServers"]);if(o!=null){let p=o;Array.isArray(p)&&(p=p.map(m=>m)),_(r,["mcpServers"],p)}const i=b(e,["codeExecution"]);i!=null&&_(r,["codeExecution"],i);const s=b(e,["computerUse"]);if(s!=null&&_(r,["computerUse"],s),b(e,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const a=b(e,["functionDeclarations"]);if(a!=null){let p=a;Array.isArray(p)&&(p=p.map(m=>m)),_(r,["functionDeclarations"],p)}const u=b(e,["googleSearch"]);u!=null&&_(r,["googleSearch"],qnn(u));const l=b(e,["googleSearchRetrieval"]);if(l!=null&&_(r,["googleSearchRetrieval"],l),b(e,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const c=b(e,["urlContext"]);c!=null&&_(r,["urlContext"],c);const d=b(e,["fileSearch"]);return d!=null&&_(r,["fileSearch"],d),r}function OWe(e,t){const r={},n=b(e,["retrieval"]);n!=null&&_(r,["retrieval"],n);const o=b(e,["googleMaps"]);o!=null&&_(r,["googleMaps"],o);const i=b(e,["mcpServers"]);if(i!=null){let g=i;Array.isArray(g)&&(g=g.map(y=>Qnn(y))),_(r,["mcpServers"],g)}const s=b(e,["codeExecution"]);s!=null&&_(r,["codeExecution"],s);const a=b(e,["computerUse"]);a!=null&&_(r,["computerUse"],a);const u=b(e,["enterpriseWebSearch"]);u!=null&&_(r,["enterpriseWebSearch"],u);const l=b(e,["exaAiSearch"]);l!=null&&_(r,["exaAiSearch"],l);const c=b(e,["functionDeclarations"]);if(c!=null){let g=c;Array.isArray(g)&&(g=g.map(y=>y)),_(r,["functionDeclarations"],g)}const d=b(e,["googleSearch"]);d!=null&&_(r,["googleSearch"],d);const p=b(e,["googleSearchRetrieval"]);p!=null&&_(r,["googleSearchRetrieval"],p);const m=b(e,["parallelAiSearch"]);m!=null&&_(r,["parallelAiSearch"],m);const h=b(e,["urlContext"]);if(h!=null&&_(r,["urlContext"],h),b(e,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return r}function bon(e,t){const r={},n=b(e,["baseModel"]);n!=null&&_(r,["baseModel"],n);const o=b(e,["createTime"]);o!=null&&_(r,["createTime"],o);const i=b(e,["updateTime"]);return i!=null&&_(r,["updateTime"],i),r}function Ton(e,t){const r={},n=b(e,["labels","google-vertex-llm-tuning-base-model-id"]);n!=null&&_(r,["baseModel"],n);const o=b(e,["createTime"]);o!=null&&_(r,["createTime"],o);const i=b(e,["updateTime"]);return i!=null&&_(r,["updateTime"],i),r}function _on(e,t,r){const n={},o=b(e,["displayName"]);t!==void 0&&o!=null&&_(t,["displayName"],o);const i=b(e,["description"]);t!==void 0&&i!=null&&_(t,["description"],i);const s=b(e,["defaultCheckpointId"]);return t!==void 0&&s!=null&&_(t,["defaultCheckpointId"],s),n}function Eon(e,t,r){const n={},o=b(e,["displayName"]);t!==void 0&&o!=null&&_(t,["displayName"],o);const i=b(e,["description"]);t!==void 0&&i!=null&&_(t,["description"],i);const s=b(e,["defaultCheckpointId"]);return t!==void 0&&s!=null&&_(t,["defaultCheckpointId"],s),n}function Son(e,t,r){const n={},o=b(t,["model"]);o!=null&&_(n,["_url","name"],Qr(e,o));const i=b(t,["config"]);return i!=null&&_on(i,n),n}function kon(e,t,r){const n={},o=b(t,["model"]);o!=null&&_(n,["_url","model"],Qr(e,o));const i=b(t,["config"]);return i!=null&&Eon(i,n),n}function Aon(e,t,r){const n={},o=b(e,["outputGcsUri"]);t!==void 0&&o!=null&&_(t,["parameters","storageUri"],o);const i=b(e,["safetyFilterLevel"]);t!==void 0&&i!=null&&_(t,["parameters","safetySetting"],i);const s=b(e,["personGeneration"]);t!==void 0&&s!=null&&_(t,["parameters","personGeneration"],s);const a=b(e,["includeRaiReason"]);t!==void 0&&a!=null&&_(t,["parameters","includeRaiReason"],a);const u=b(e,["outputMimeType"]);t!==void 0&&u!=null&&_(t,["parameters","outputOptions","mimeType"],u);const l=b(e,["outputCompressionQuality"]);t!==void 0&&l!=null&&_(t,["parameters","outputOptions","compressionQuality"],l);const c=b(e,["enhanceInputImage"]);t!==void 0&&c!=null&&_(t,["parameters","upscaleConfig","enhanceInputImage"],c);const d=b(e,["imagePreservationFactor"]);t!==void 0&&d!=null&&_(t,["parameters","upscaleConfig","imagePreservationFactor"],d);const p=b(e,["labels"]);t!==void 0&&p!=null&&_(t,["labels"],p);const m=b(e,["numberOfImages"]);t!==void 0&&m!=null&&_(t,["parameters","sampleCount"],m);const h=b(e,["mode"]);return t!==void 0&&h!=null&&_(t,["parameters","mode"],h),n}function Con(e,t,r){const n={},o=b(t,["model"]);o!=null&&_(n,["_url","model"],Qr(e,o));const i=b(t,["image"]);i!=null&&_(n,["instances[0]","image"],wc(i));const s=b(t,["upscaleFactor"]);s!=null&&_(n,["parameters","upscaleConfig","upscaleFactor"],s);const a=b(t,["config"]);return a!=null&&Aon(a,n),n}function xon(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["predictions"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(s=>fO(s))),_(r,["generatedImages"],i)}return r}function Ion(e,t){const r={},n=b(e,["uri"]);n!=null&&_(r,["uri"],n);const o=b(e,["encodedVideo"]);o!=null&&_(r,["videoBytes"],n0(o));const i=b(e,["encoding"]);return i!=null&&_(r,["mimeType"],i),r}function Ron(e,t){const r={},n=b(e,["gcsUri"]);n!=null&&_(r,["uri"],n);const o=b(e,["bytesBase64Encoded"]);o!=null&&_(r,["videoBytes"],n0(o));const i=b(e,["mimeType"]);return i!=null&&_(r,["mimeType"],i),r}function Mon(e,t){const r={},n=b(e,["image"]);n!=null&&_(r,["_self"],wc(n));const o=b(e,["maskMode"]);return o!=null&&_(r,["maskMode"],o),r}function Pon(e,t){const r={},n=b(e,["image"]);n!=null&&_(r,["image"],gO(n));const o=b(e,["referenceType"]);return o!=null&&_(r,["referenceType"],o),r}function Don(e,t){const r={},n=b(e,["image"]);n!=null&&_(r,["image"],wc(n));const o=b(e,["referenceType"]);return o!=null&&_(r,["referenceType"],o),r}function NWe(e,t){const r={},n=b(e,["uri"]);n!=null&&_(r,["uri"],n);const o=b(e,["videoBytes"]);o!=null&&_(r,["encodedVideo"],n0(o));const i=b(e,["mimeType"]);return i!=null&&_(r,["encoding"],i),r}function LWe(e,t){const r={},n=b(e,["uri"]);n!=null&&_(r,["gcsUri"],n);const o=b(e,["videoBytes"]);o!=null&&_(r,["bytesBase64Encoded"],n0(o));const i=b(e,["mimeType"]);return i!=null&&_(r,["mimeType"],i),r}function $We(e,t){const r={},n=b(e,["replicatedVoiceConfig"]);n!=null&&_(r,["replicatedVoiceConfig"],lon(n));const o=b(e,["prebuiltVoiceConfig"]);o!=null&&_(r,["prebuiltVoiceConfig"],o);const i=b(e,["voice"]);return i!=null&&_(r,["voice"],i),r}function FWe(e){for(const t of e)if(Oon(t)||typeof t=="object"&&"inputSchema"in t)return!0;return bY}function UWe(e){var t;const r=(t=e[PO])!==null&&t!==void 0?t:"";e[PO]=(r+` ${XJe}`).trimStart()}function Oon(e){return e!==null&&typeof e=="object"&&e instanceof OO}function Non(e){return o0(this,arguments,function*(r,n=100){let o,i=0;for(;i<n;){const s=yield cn(r.listTools({cursor:o}));for(const a of s.tools)yield yield cn(a),i++;if(!s.nextCursor)break;o=s.nextCursor}})}function Lon(e){return e!==null&&typeof e=="object"&&"listTools"in e&&typeof e.listTools=="function"}function $on(...e){if(bY=!0,e.length===0)throw new Error("No MCP clients provided");const t=e[e.length-1];return Lon(t)?OO.create(e,{}):OO.create(e.slice(0,e.length-1),t)}async function Fon(e,t,r){const n=new YX;let o;r.data instanceof Blob?o=JSON.parse(await r.data.text()):o=JSON.parse(r.data),Object.assign(n,o),t(n)}function Uon(e){const t={};return e.forEach((r,n)=>{t[n]=r}),t}function Bon(e){const t=new Headers;for(const[r,n]of Object.entries(e))t.append(r,n);return t}async function zon(e,t,r){const n=new XX;let o;r.data instanceof Blob?o=await r.data.text():r.data instanceof ArrayBuffer?o=new TextDecoder().decode(r.data):o=r.data;const i=JSON.parse(o);if(e.isVertexAI()){const s=Orn(i);Object.assign(n,s)}else Object.assign(n,i);t(n)}function Gon(e){const t={};return e.forEach((r,n)=>{t[n]=r}),t}function qon(e){const t=new Headers;for(const[r,n]of Object.entries(e))t.append(r,n);return t}function BWe(e){var t,r,n;if(!((t=e?.automaticFunctionCalling)===null||t===void 0)&&t.disable)return!0;let o=!1;for(const s of(r=e?.tools)!==null&&r!==void 0?r:[])if(gb(s)){o=!0;break}if(!o)return!0;const i=(n=e?.automaticFunctionCalling)===null||n===void 0?void 0:n.maximumRemoteCalls;return i&&(i<0||!Number.isInteger(i))||i==0?(console.warn("Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:",i),!0):!1}function gb(e){return"callTool"in e&&typeof e.callTool=="function"}function jon(e){var t,r,n;return(n=(r=(t=e.config)===null||t===void 0?void 0:t.tools)===null||r===void 0?void 0:r.some(o=>gb(o)))!==null&&n!==void 0?n:!1}function zWe(e){var t;const r=[];return!((t=e?.config)===null||t===void 0)&&t.tools&&e.config.tools.forEach((n,o)=>{if(gb(n))return;const i=n;i.functionDeclarations&&i.functionDeclarations.length>0&&r.push(o)}),r}function GWe(e){var t;return!(!((t=e?.automaticFunctionCalling)===null||t===void 0)&&t.ignoreCallHistory)}function yO(e,t=!0){return!e||e.automaticContinuation===void 0||e.automaticContinuation===null?t:!!e.automaticContinuation}function mJ(e){return e===void 0||e===PA.CONTINUATION}function qWe(e,t,r,n=!1){return e&&!n&&!!t&&mJ(r)}function Von(e,t,r){var n;const o=(n=e.candidates)===null||n===void 0?void 0:n[0];o?.finishReason!==void 0&&qWe(t,r,o.finishReason)&&(o.finishReason=void 0)}function Hon(e,t){var r;return!!(!((r=t?.abortSignal)===null||r===void 0)&&r.aborted)||e instanceof Error&&e.name==="AbortError"}function jWe(e){return{startToken:e,hasPromptFeedback:!1,hasYieldedContent:!1,receivedAnyChunk:!1}}function Won(e){var t;const r=(t=e?.candidates)===null||t===void 0?void 0:t[0];if(r?.continuationToken&&mJ(r.finishReason))return r.continuationToken}function VWe(e,t,r=!1){const n=e?.automaticContinuation!==void 0&&e?.automaticContinuation!==null,o=r&&n;if(!t&&!o)return e;if(!e)return t?{continuationToken:t}:void 0;const i=Object.assign({},e);return t&&(i.continuationToken=t),o&&delete i.automaticContinuation,i}function Kon(e,t){var r,n;const o=new Map,i=[];for(const s of[...e,...t]){const a=s.modality;o.has(a)||(o.set(a,0),i.push(a)),o.set(a,((r=o.get(a))!==null&&r!==void 0?r:0)+((n=s.tokenCount)!==null&&n!==void 0?n:0))}return i.map(s=>{var a;return{modality:s,tokenCount:(a=o.get(s))!==null&&a!==void 0?a:0}})}function Jon(e,t){const r=new Map,n=[];for(const o of[...e,...t]){const i=o.category;r.has(i)||n.push(i),r.set(i,o)}return n.map(o=>r.get(o))}function HWe(e){if(typeof e!="object"||e===null||Array.isArray(e)||e instanceof a0)return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype||e instanceof bc||e instanceof DX||e instanceof _O}function WWe(e,t){return e.endsWith("TokensDetails")?!0:t.length>0&&typeof t[0]=="object"&&t[0]!==null&&"modality"in t[0]}function Xon(e,t){if(e.length===0)return t;if(t.length===0)return e.map(o=>MA(o,{},!0,!1));const r=[],n=Math.min(e.length,t.length);for(let o=0;o<n;o++)r.push(MA(e[o],t[o],!0,!1));return e.length>n&&r.push(...e.slice(n)),t.length>n&&r.push(...t.slice(n)),r}function vO(e){var t;if(e)return(t=e._initialPromptTokenCount)!==null&&t!==void 0?t:e.promptTokenCount}function RA(e,t){const r=t??vO(e);return r!==void 0&&Object.defineProperty(e,"_initialPromptTokenCount",{value:r,enumerable:!1,configurable:!0,writable:!0}),!(e instanceof _O)&&!Object.prototype.hasOwnProperty.call(e,"initialPromptTokenCount")&&Object.defineProperty(e,"initialPromptTokenCount",{get(){return vO(this)},enumerable:!1,configurable:!0}),e}function KWe(e,t){var r;if(!t)return e&&RA(e);if(!e)return RA(t);const n=(r=vO(e))!==null&&r!==void 0?r:vO(t),o=MA(e,t,!1,!0);return RA(o,n)}function Yon(e,t){const r=t.groundingMetadata,n=r?.groundingSupports;if(!Array.isArray(n)||n.length===0)return t;const o=e.content,i=Array.isArray(o?.parts)?o.parts.length:0,s=e.groundingMetadata,a=Array.isArray(s?.groundingChunks)?s.groundingChunks.length:0;if(i===0&&a===0)return t;const u=n.map(l=>{var c;if(!l||typeof l!="object")return l;const d=Object.assign({},l);return a>0&&Array.isArray(l.groundingChunkIndices)&&l.groundingChunkIndices.length>0&&(d.groundingChunkIndices=l.groundingChunkIndices.map(p=>p+a)),i>0&&l.segment&&typeof l.segment=="object"&&(d.segment=Object.assign(Object.assign({},l.segment),{partIndex:((c=l.segment.partIndex)!==null&&c!==void 0?c:0)+i})),d});return Object.assign(Object.assign({},t),{groundingMetadata:Object.assign(Object.assign({},r),{groundingSupports:u})})}function MA(e,t,r=!1,n=!1){r&&(t=Yon(e,t));const o={},i=new Set([...Object.keys(e),...Object.keys(t)]);for(const s of i){const a=e[s],u=t[s];if(r&&(s==="continuationToken"||s==="finishReason"||s==="finishMessage")){u!==void 0&&(o[s]=u);continue}if(!r&&!n&&s==="candidates"&&Array.isArray(a)){o[s]=Xon(a,Array.isArray(u)?u:[]);continue}if(s==="usageMetadata"){const l=KWe(a,u);l!==void 0&&(o[s]=l);continue}u==null?a!==void 0&&(o[s]=a):a==null?o[s]=u:typeof a=="number"&&typeof u=="number"&&(n||s==="tokenCount"||s.endsWith("TokenCount")||s.endsWith("Count")||s.endsWith("Sum"))?o[s]=a+u:Array.isArray(a)&&Array.isArray(u)?WWe(s,a)||WWe(s,u)?o[s]=Kon(a,u):s==="safetyRatings"?o[s]=Jon(a,u):o[s]=[...a,...u]:HWe(a)&&HWe(u)?o[s]=MA(a,u,!1,s==="usageMetadata"||n):o[s]=u}return o}function Zon(e){if(e.length===0)return new bc;if(e.length===1)return e[0].usageMetadata&&RA(e[0].usageMetadata),e[0];let t=e[0];for(let n=1;n<e.length;n++)t=MA(t,e[n],!1,!1);const r=new bc;return Object.assign(r,t),r}function Qon(e){const t={},r=b(e,["apiKey"]);if(r!=null&&_(t,["apiKey"],r),b(e,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function ein(e){const t={},r=b(e,["parts"]);if(r!=null){let o=r;Array.isArray(o)&&(o=o.map(i=>uin(i))),_(t,["parts"],o)}const n=b(e,["role"]);return n!=null&&_(t,["role"],n),t}function tin(e,t,r){const n={},o=b(t,["expireTime"]);r!==void 0&&o!=null&&_(r,["expireTime"],o);const i=b(t,["newSessionExpireTime"]);r!==void 0&&i!=null&&_(r,["newSessionExpireTime"],i);const s=b(t,["uses"]);r!==void 0&&s!=null&&_(r,["uses"],s);const a=b(t,["liveConnectConstraints"]);r!==void 0&&a!=null&&_(r,["bidiGenerateContentSetup"],ain(e,a));const u=b(t,["lockAdditionalFields"]);return r!==void 0&&u!=null&&_(r,["fieldMask"],u),n}function rin(e,t){const r={},n=b(t,["config"]);return n!=null&&_(r,["config"],tin(e,n,r)),r}function nin(e){const t={},r=b(e,["args"]);r!=null&&_(t,["args"],r);const n=b(e,["id"]);n!=null&&_(t,["id"],n);const o=b(e,["name"]);if(o!=null&&_(t,["name"],o),b(e,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function oin(e){const t={},r=b(e,["authConfig"]);r!=null&&_(t,["authConfig"],Qon(r));const n=b(e,["enableWidget"]);if(n!=null&&_(t,["enableWidget"],n),b(e,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function iin(e){const t={};if(b(e,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const r=b(e,["searchTypes"]);r!=null&&_(t,["searchTypes"],r);const n=b(e,["timeRangeFilter"]);return n!=null&&_(t,["timeRangeFilter"],n),t}function sin(e,t){const r={},n=b(e,["generationConfig"]);t!==void 0&&n!=null&&_(t,["setup","generationConfig"],n);const o=b(e,["responseModalities"]);t!==void 0&&o!=null&&_(t,["setup","generationConfig","responseModalities"],o);const i=b(e,["temperature"]);t!==void 0&&i!=null&&_(t,["setup","generationConfig","temperature"],i);const s=b(e,["topP"]);t!==void 0&&s!=null&&_(t,["setup","generationConfig","topP"],s);const a=b(e,["topK"]);t!==void 0&&a!=null&&_(t,["setup","generationConfig","topK"],a);const u=b(e,["maxOutputTokens"]);t!==void 0&&u!=null&&_(t,["setup","generationConfig","maxOutputTokens"],u);const l=b(e,["mediaResolution"]);t!==void 0&&l!=null&&_(t,["setup","generationConfig","mediaResolution"],l);const c=b(e,["seed"]);t!==void 0&&c!=null&&_(t,["setup","generationConfig","seed"],c);const d=b(e,["speechConfig"]);t!==void 0&&d!=null&&_(t,["setup","generationConfig","speechConfig"],iJ(d));const p=b(e,["thinkingConfig"]);t!==void 0&&p!=null&&_(t,["setup","generationConfig","thinkingConfig"],p);const m=b(e,["enableAffectiveDialog"]);t!==void 0&&m!=null&&_(t,["setup","generationConfig","enableAffectiveDialog"],m);const h=b(e,["systemInstruction"]);t!==void 0&&h!=null&&_(t,["setup","systemInstruction"],ein(Ii(h)));const g=b(e,["tools"]);if(t!==void 0&&g!=null){let P=xh(g);Array.isArray(P)&&(P=P.map(D=>din(Ch(D)))),_(t,["setup","tools"],P)}const y=b(e,["sessionResumption"]);t!==void 0&&y!=null&&_(t,["setup","sessionResumption"],cin(y));const v=b(e,["inputAudioTranscription"]);t!==void 0&&v!=null&&_(t,["setup","inputAudioTranscription"],v);const w=b(e,["outputAudioTranscription"]);t!==void 0&&w!=null&&_(t,["setup","outputAudioTranscription"],w);const T=b(e,["realtimeInputConfig"]);t!==void 0&&T!=null&&_(t,["setup","realtimeInputConfig"],T);const E=b(e,["contextWindowCompression"]);t!==void 0&&E!=null&&_(t,["setup","contextWindowCompression"],E);const k=b(e,["proactivity"]);if(t!==void 0&&k!=null&&_(t,["setup","proactivity"],k),b(e,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const A=b(e,["avatarConfig"]);t!==void 0&&A!=null&&_(t,["setup","avatarConfig"],A);const C=b(e,["safetySettings"]);if(t!==void 0&&C!=null){let P=C;Array.isArray(P)&&(P=P.map(D=>lin(D))),_(t,["setup","safetySettings"],P)}const R=b(e,["translationConfig"]);t!==void 0&&R!=null&&_(t,["setup","generationConfig","translationConfig"],R);const x=b(e,["labels"]);return t!==void 0&&x!=null&&_(t,["setup","labels"],x),r}function ain(e,t){const r={},n=b(t,["model"]);n!=null&&_(r,["setup","model"],Qr(e,n));const o=b(t,["config"]);return o!=null&&_(r,["config"],sin(o,r)),r}function uin(e){const t={},r=b(e,["mediaResolution"]);r!=null&&_(t,["mediaResolution"],r);const n=b(e,["toolCall"]);n!=null&&_(t,["toolCall"],n);const o=b(e,["toolResponse"]);o!=null&&_(t,["toolResponse"],o);const i=b(e,["audioTranscription"]);i!=null&&_(t,["audioTranscription"],i);const s=b(e,["codeExecutionResult"]);s!=null&&_(t,["codeExecutionResult"],s);const a=b(e,["executableCode"]);a!=null&&_(t,["executableCode"],a);const u=b(e,["fileData"]);u!=null&&_(t,["fileData"],u);const l=b(e,["functionCall"]);l!=null&&_(t,["functionCall"],nin(l));const c=b(e,["functionResponse"]);c!=null&&_(t,["functionResponse"],c);const d=b(e,["inlineData"]);d!=null&&_(t,["inlineData"],d);const p=b(e,["text"]);p!=null&&_(t,["text"],p);const m=b(e,["thought"]);m!=null&&_(t,["thought"],m);const h=b(e,["thoughtSignature"]);h!=null&&_(t,["thoughtSignature"],h);const g=b(e,["videoMetadata"]);g!=null&&_(t,["videoMetadata"],g);const y=b(e,["partMetadata"]);y!=null&&_(t,["partMetadata"],y);const v=b(e,["mediaProcessing"]);v!=null&&_(t,["mediaProcessing"],v);const w=b(e,["speechMetadata"]);return w!=null&&_(t,["speechMetadata"],w),t}function lin(e){const t={},r=b(e,["category"]);if(r!=null&&_(t,["category"],r),b(e,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=b(e,["threshold"]);return n!=null&&_(t,["threshold"],n),t}function cin(e){const t={},r=b(e,["handle"]);if(r!=null&&_(t,["handle"],r),b(e,["transparent"])!==void 0)throw new Error("transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function din(e){const t={};if(b(e,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const r=b(e,["googleMaps"]);r!=null&&_(t,["googleMaps"],oin(r));const n=b(e,["mcpServers"]);if(n!=null){let d=n;Array.isArray(d)&&(d=d.map(p=>p)),_(t,["mcpServers"],d)}const o=b(e,["codeExecution"]);o!=null&&_(t,["codeExecution"],o);const i=b(e,["computerUse"]);if(i!=null&&_(t,["computerUse"],i),b(e,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const s=b(e,["functionDeclarations"]);if(s!=null){let d=s;Array.isArray(d)&&(d=d.map(p=>p)),_(t,["functionDeclarations"],d)}const a=b(e,["googleSearch"]);a!=null&&_(t,["googleSearch"],iin(a));const u=b(e,["googleSearchRetrieval"]);if(u!=null&&_(t,["googleSearchRetrieval"],u),b(e,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const l=b(e,["urlContext"]);l!=null&&_(t,["urlContext"],l);const c=b(e,["fileSearch"]);return c!=null&&_(t,["fileSearch"],c),t}function pin(e){const t=[];for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)){const n=e[r];if(typeof n=="object"&&n!=null&&Object.keys(n).length>0){const o=Object.keys(n).map(i=>`${r}.${i}`);t.push(...o)}else t.push(r)}return t.join(",")}function min(e,t){let r=null;const n=e.bidiGenerateContentSetup;if(typeof n=="object"&&n!==null&&"setup"in n){const i=n.setup;typeof i=="object"&&i!==null?(e.bidiGenerateContentSetup=i,r=i):delete e.bidiGenerateContentSetup}else n!==void 0&&delete e.bidiGenerateContentSetup;const o=e.fieldMask;if(r){const i=pin(r);if(Array.isArray(t?.lockAdditionalFields)&&t?.lockAdditionalFields.length===0)i?e.fieldMask=i:delete e.fieldMask;else if(t?.lockAdditionalFields&&t.lockAdditionalFields.length>0&&o!==null&&Array.isArray(o)&&o.length>0){const s=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"];let a=[];o.length>0&&(a=o.map(l=>s.includes(l)?`generationConfig.${l}`:l));const u=[];i&&u.push(i),a.length>0&&u.push(...a),u.length>0?e.fieldMask=u.join(","):delete e.fieldMask}else delete e.fieldMask}else o!==null&&Array.isArray(o)&&o.length>0?e.fieldMask=o.join(","):delete e.fieldMask;return e}function hin(e,t){const r={},n=b(e,["name"]);return n!=null&&_(r,["_url","name"],n),r}function fin(e,t){const r={},n=b(e,["name"]);return n!=null&&_(r,["_url","name"],n),r}function gin(e,t){const r={},n=b(e,["sdkHttpResponse"]);return n!=null&&_(r,["sdkHttpResponse"],n),r}function yin(e,t){const r={},n=b(e,["sdkHttpResponse"]);return n!=null&&_(r,["sdkHttpResponse"],n),r}function hJ(e,t){const r={},n=b(e,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(s=>Min(s))),_(r,["parts"],i)}const o=b(e,["role"]);return o!=null&&_(r,["role"],o),r}function vin(e,t,r){const n={};if(b(e,["validationDataset"])!==void 0)throw new Error("validationDataset parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=b(e,["tunedModelDisplayName"]);if(t!==void 0&&o!=null&&_(t,["displayName"],o),b(e,["description"])!==void 0)throw new Error("description parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const i=b(e,["epochCount"]);t!==void 0&&i!=null&&_(t,["tuningTask","hyperparameters","epochCount"],i);const s=b(e,["learningRateMultiplier"]);if(s!=null&&_(n,["tuningTask","hyperparameters","learningRateMultiplier"],s),b(e,["exportLastCheckpointOnly"])!==void 0)throw new Error("exportLastCheckpointOnly parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["preTunedModelCheckpointId"])!==void 0)throw new Error("preTunedModelCheckpointId parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["adapterSize"])!==void 0)throw new Error("adapterSize parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["tuningMode"])!==void 0)throw new Error("tuningMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["customBaseModel"])!==void 0)throw new Error("customBaseModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const a=b(e,["batchSize"]);t!==void 0&&a!=null&&_(t,["tuningTask","hyperparameters","batchSize"],a);const u=b(e,["learningRate"]);if(t!==void 0&&u!=null&&_(t,["tuningTask","hyperparameters","learningRate"],u),b(e,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["beta"])!==void 0)throw new Error("beta parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["baseTeacherModel"])!==void 0)throw new Error("baseTeacherModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["tunedTeacherModelSource"])!==void 0)throw new Error("tunedTeacherModelSource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["sftLossWeightMultiplier"])!==void 0)throw new Error("sftLossWeightMultiplier parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["outputUri"])!==void 0)throw new Error("outputUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["rewardConfig"])!==void 0)throw new Error("rewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["compositeRewardConfig"])!==void 0)throw new Error("compositeRewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["samplesPerPrompt"])!==void 0)throw new Error("samplesPerPrompt parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["evaluateInterval"])!==void 0)throw new Error("evaluateInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["checkpointInterval"])!==void 0)throw new Error("checkpointInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["maxOutputTokens"])!==void 0)throw new Error("maxOutputTokens parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["thinkingLevel"])!==void 0)throw new Error("thinkingLevel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["validationDatasetUri"])!==void 0)throw new Error("validationDatasetUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["encryptionSpec"])!==void 0)throw new Error("encryptionSpec parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function win(e,t,r){const n={};let o=b(r,["config","method"]);if(o===void 0&&(o="SUPERVISED_FINE_TUNING"),o==="SUPERVISED_FINE_TUNING"){const N=b(e,["validationDataset"]);t!==void 0&&N!=null&&_(t,["supervisedTuningSpec"],wO(N))}else if(o==="PREFERENCE_TUNING"){const N=b(e,["validationDataset"]);t!==void 0&&N!=null&&_(t,["preferenceOptimizationSpec"],wO(N))}else if(o==="DISTILLATION"){const N=b(e,["validationDataset"]);t!==void 0&&N!=null&&_(t,["distillationSpec"],wO(N))}else if(o==="REINFORCEMENT_TUNING"){const N=b(e,["validationDataset"]);t!==void 0&&N!=null&&_(t,["reinforcementTuningSpec"],wO(N))}const i=b(e,["tunedModelDisplayName"]);t!==void 0&&i!=null&&_(t,["tunedModelDisplayName"],i);const s=b(e,["description"]);t!==void 0&&s!=null&&_(t,["description"],s);let a=b(r,["config","method"]);if(a===void 0&&(a="SUPERVISED_FINE_TUNING"),a==="SUPERVISED_FINE_TUNING"){const N=b(e,["epochCount"]);t!==void 0&&N!=null&&_(t,["supervisedTuningSpec","hyperParameters","epochCount"],N)}else if(a==="PREFERENCE_TUNING"){const N=b(e,["epochCount"]);t!==void 0&&N!=null&&_(t,["preferenceOptimizationSpec","hyperParameters","epochCount"],N)}else if(a==="DISTILLATION"){const N=b(e,["epochCount"]);t!==void 0&&N!=null&&_(t,["distillationSpec","hyperParameters","epochCount"],N)}else if(a==="REINFORCEMENT_TUNING"){const N=b(e,["epochCount"]);t!==void 0&&N!=null&&_(t,["reinforcementTuningSpec","hyperParameters","epochCount"],N)}let u=b(r,["config","method"]);if(u===void 0&&(u="SUPERVISED_FINE_TUNING"),u==="SUPERVISED_FINE_TUNING"){const N=b(e,["learningRateMultiplier"]);t!==void 0&&N!=null&&_(t,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],N)}else if(u==="PREFERENCE_TUNING"){const N=b(e,["learningRateMultiplier"]);t!==void 0&&N!=null&&_(t,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],N)}else if(u==="DISTILLATION"){const N=b(e,["learningRateMultiplier"]);t!==void 0&&N!=null&&_(t,["distillationSpec","hyperParameters","learningRateMultiplier"],N)}else if(u==="REINFORCEMENT_TUNING"){const N=b(e,["learningRateMultiplier"]);t!==void 0&&N!=null&&_(t,["reinforcementTuningSpec","hyperParameters","learningRateMultiplier"],N)}let l=b(r,["config","method"]);if(l===void 0&&(l="SUPERVISED_FINE_TUNING"),l==="SUPERVISED_FINE_TUNING"){const N=b(e,["exportLastCheckpointOnly"]);t!==void 0&&N!=null&&_(t,["supervisedTuningSpec","exportLastCheckpointOnly"],N)}else if(l==="PREFERENCE_TUNING"){const N=b(e,["exportLastCheckpointOnly"]);t!==void 0&&N!=null&&_(t,["preferenceOptimizationSpec","exportLastCheckpointOnly"],N)}else if(l==="DISTILLATION"){const N=b(e,["exportLastCheckpointOnly"]);t!==void 0&&N!=null&&_(t,["distillationSpec","exportLastCheckpointOnly"],N)}let c=b(r,["config","method"]);if(c===void 0&&(c="SUPERVISED_FINE_TUNING"),c==="SUPERVISED_FINE_TUNING"){const N=b(e,["adapterSize"]);t!==void 0&&N!=null&&_(t,["supervisedTuningSpec","hyperParameters","adapterSize"],N)}else if(c==="PREFERENCE_TUNING"){const N=b(e,["adapterSize"]);t!==void 0&&N!=null&&_(t,["preferenceOptimizationSpec","hyperParameters","adapterSize"],N)}else if(c==="DISTILLATION"){const N=b(e,["adapterSize"]);t!==void 0&&N!=null&&_(t,["distillationSpec","hyperParameters","adapterSize"],N)}else if(c==="REINFORCEMENT_TUNING"){const N=b(e,["adapterSize"]);t!==void 0&&N!=null&&_(t,["reinforcementTuningSpec","hyperParameters","adapterSize"],N)}let d=b(r,["config","method"]);if(d===void 0&&(d="SUPERVISED_FINE_TUNING"),d==="SUPERVISED_FINE_TUNING"){const N=b(e,["tuningMode"]);t!==void 0&&N!=null&&_(t,["supervisedTuningSpec","tuningMode"],N)}else if(d==="DISTILLATION"){const N=b(e,["tuningMode"]);t!==void 0&&N!=null&&_(t,["distillationSpec","tuningMode"],N)}const p=b(e,["customBaseModel"]);t!==void 0&&p!=null&&_(t,["customBaseModel"],p);let m=b(r,["config","method"]);if(m===void 0&&(m="SUPERVISED_FINE_TUNING"),m==="SUPERVISED_FINE_TUNING"){const N=b(e,["batchSize"]);t!==void 0&&N!=null&&_(t,["supervisedTuningSpec","hyperParameters","batchSize"],N)}else if(m==="DISTILLATION"){const N=b(e,["batchSize"]);t!==void 0&&N!=null&&_(t,["distillationSpec","hyperParameters","batchSize"],N)}else if(m==="REINFORCEMENT_TUNING"){const N=b(e,["batchSize"]);t!==void 0&&N!=null&&_(t,["reinforcementTuningSpec","hyperParameters","batchSize"],N)}let h=b(r,["config","method"]);if(h===void 0&&(h="SUPERVISED_FINE_TUNING"),h==="SUPERVISED_FINE_TUNING"){const N=b(e,["learningRate"]);t!==void 0&&N!=null&&_(t,["supervisedTuningSpec","hyperParameters","learningRate"],N)}else if(h==="DISTILLATION"){const N=b(e,["learningRate"]);t!==void 0&&N!=null&&_(t,["distillationSpec","hyperParameters","learningRate"],N)}const g=b(e,["labels"]);t!==void 0&&g!=null&&_(t,["labels"],g);const y=b(e,["beta"]);t!==void 0&&y!=null&&_(t,["preferenceOptimizationSpec","hyperParameters","beta"],y);const v=b(e,["baseTeacherModel"]);t!==void 0&&v!=null&&_(t,["distillationSpec","baseTeacherModel"],v);const w=b(e,["tunedTeacherModelSource"]);t!==void 0&&w!=null&&_(t,["distillationSpec","tunedTeacherModelSource"],w);const T=b(e,["sftLossWeightMultiplier"]);t!==void 0&&T!=null&&_(t,["distillationSpec","hyperParameters","sftLossWeightMultiplier"],T);const E=b(e,["outputUri"]);t!==void 0&&E!=null&&_(t,["outputUri"],E);const k=b(e,["rewardConfig"]);t!==void 0&&k!=null&&_(t,["reinforcementTuningSpec","singleRewardConfig"],k);const A=b(e,["compositeRewardConfig"]);t!==void 0&&A!=null&&_(t,["reinforcementTuningSpec","compositeRewardConfig"],A);const C=b(e,["samplesPerPrompt"]);t!==void 0&&C!=null&&_(t,["reinforcementTuningSpec","hyperParameters","samplesPerPrompt"],C);const R=b(e,["evaluateInterval"]);t!==void 0&&R!=null&&_(t,["reinforcementTuningSpec","hyperParameters","evaluateInterval"],R);const x=b(e,["checkpointInterval"]);t!==void 0&&x!=null&&_(t,["reinforcementTuningSpec","hyperParameters","checkpointInterval"],x);const P=b(e,["maxOutputTokens"]);t!==void 0&&P!=null&&_(t,["reinforcementTuningSpec","hyperParameters","maxOutputTokens"],P);const D=b(e,["thinkingLevel"]);t!==void 0&&D!=null&&_(t,["reinforcementTuningSpec","hyperParameters","thinkingLevel"],D);const L=b(e,["validationDatasetUri"]);t!==void 0&&L!=null&&_(t,["reinforcementTuningSpec","validationDatasetUri"],L);const O=b(e,["encryptionSpec"]);return t!==void 0&&O!=null&&_(t,["encryptionSpec"],O),n}function bin(e,t){const r={},n=b(e,["baseModel"]);n!=null&&_(r,["baseModel"],n);const o=b(e,["preTunedModel"]);o!=null&&_(r,["preTunedModel"],o);const i=b(e,["trainingDataset"]);i!=null&&Nin(i);const s=b(e,["config"]);return s!=null&&vin(s,r),r}function Tin(e,t){const r={},n=b(e,["baseModel"]);n!=null&&_(r,["baseModel"],n);const o=b(e,["preTunedModel"]);o!=null&&_(r,["preTunedModel"],o);const i=b(e,["trainingDataset"]);i!=null&&Lin(i,r,t);const s=b(e,["config"]);return s!=null&&win(s,r,t),r}function JWe(e,t){const r={},n=b(e,["epochCount"]);n!=null&&_(r,["epochCount"],n);const o=b(e,["learningRateMultiplier"]);o!=null&&_(r,["learningRateMultiplier"],o);const i=b(e,["adapterSize"]);i!=null&&_(r,["adapterSize"],i);const s=b(e,["batchSize"]);s!=null&&_(r,["batchSize"],s);const a=b(e,["learningRate"]);a!=null&&_(r,["learningRate"],a);const u=b(e,["generationConfig"]);return u!=null&&_(r,["generationConfig"],Sin(u)),r}function _in(e,t){const r={},n=b(e,["promptDatasetUri"]);n!=null&&_(r,["promptDatasetUri"],n);const o=b(e,["validationDatasetUri"]);o!=null&&_(r,["validationDatasetUri"],o);const i=b(e,["baseTeacherModel"]);i!=null&&_(r,["baseTeacherModel"],i);const s=b(e,["tunedTeacherModelSource"]);s!=null&&_(r,["tunedTeacherModelSource"],s);const a=b(e,["hyperparameters"]);return a!=null&&_(r,["hyperparameters"],JWe(a)),r}function Ein(e,t){const r={},n=b(e,["baseTeacherModel"]);n!=null&&_(r,["baseTeacherModel"],n);const o=b(e,["hyperParameters"]);o!=null&&_(r,["hyperParameters"],JWe(o));const i=b(e,["pipelineRootDirectory"]);i!=null&&_(r,["pipelineRootDirectory"],i);const s=b(e,["promptDatasetUri"]);s!=null&&_(r,["promptDatasetUri"],s);const a=b(e,["studentModel"]);a!=null&&_(r,["studentModel"],a);const u=b(e,["trainingDatasetUri"]);u!=null&&_(r,["trainingDatasetUri"],u);const l=b(e,["tunedTeacherModelSource"]);l!=null&&_(r,["tunedTeacherModelSource"],l);const c=b(e,["tuningMode"]);c!=null&&_(r,["tuningMode"],c);const d=b(e,["validationDatasetUri"]);return d!=null&&_(r,["validationDatasetUri"],d),r}function Sin(e,t){const r={},n=b(e,["modelConfig"]);n!=null&&_(r,["modelSelectionConfig"],n);const o=b(e,["responseJsonSchema"]);o!=null&&_(r,["responseJsonSchema"],o);const i=b(e,["audioTranscriptionConfig"]);i!=null&&_(r,["audioTranscriptionConfig"],i);const s=b(e,["audioTimestamp"]);s!=null&&_(r,["audioTimestamp"],s);const a=b(e,["candidateCount"]);a!=null&&_(r,["candidateCount"],a);const u=b(e,["enableAffectiveDialog"]);u!=null&&_(r,["enableAffectiveDialog"],u);const l=b(e,["frequencyPenalty"]);l!=null&&_(r,["frequencyPenalty"],l);const c=b(e,["logprobs"]);c!=null&&_(r,["logprobs"],c);const d=b(e,["maxOutputTokens"]);d!=null&&_(r,["maxOutputTokens"],d);const p=b(e,["mediaResolution"]);p!=null&&_(r,["mediaResolution"],p);const m=b(e,["presencePenalty"]);m!=null&&_(r,["presencePenalty"],m);const h=b(e,["responseFormat"]);if(h!=null){let L=h;Array.isArray(L)&&(L=L.map(O=>O)),_(r,["responseFormat"],L)}const g=b(e,["responseLogprobs"]);g!=null&&_(r,["responseLogprobs"],g);const y=b(e,["responseMimeType"]);y!=null&&_(r,["responseMimeType"],y);const v=b(e,["responseModalities"]);v!=null&&_(r,["responseModalities"],v);const w=b(e,["responseSchema"]);w!=null&&_(r,["responseSchema"],w);const T=b(e,["routingConfig"]);T!=null&&_(r,["routingConfig"],T);const E=b(e,["seed"]);E!=null&&_(r,["seed"],E);const k=b(e,["speechConfig"]);k!=null&&_(r,["speechConfig"],k);const A=b(e,["stopSequences"]);A!=null&&_(r,["stopSequences"],A);const C=b(e,["temperature"]);C!=null&&_(r,["temperature"],C);const R=b(e,["thinkingConfig"]);R!=null&&_(r,["thinkingConfig"],R);const x=b(e,["topK"]);x!=null&&_(r,["topK"],x);const P=b(e,["topP"]);P!=null&&_(r,["topP"],P);const D=b(e,["translationConfig"]);return D!=null&&_(r,["translationConfig"],D),r}function kin(e,t){const r={},n=b(e,["name"]);return n!=null&&_(r,["_url","name"],n),r}function Ain(e,t){const r={},n=b(e,["name"]);return n!=null&&_(r,["_url","name"],n),r}function Cin(e,t,r){const n={},o=b(e,["pageSize"]);t!==void 0&&o!=null&&_(t,["_query","pageSize"],o);const i=b(e,["pageToken"]);t!==void 0&&i!=null&&_(t,["_query","pageToken"],i);const s=b(e,["filter"]);return t!==void 0&&s!=null&&_(t,["_query","filter"],s),n}function xin(e,t){const r={},n=b(e,["config"]);return n!=null&&Cin(n,r),r}function Iin(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["nextPageToken"]);o!=null&&_(r,["nextPageToken"],o);const i=b(e,["tuningJobs"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(a=>fJ(a))),_(r,["tuningJobs"],s)}return r}function Rin(e,t){const r={};if(b(e,["name"])!==void 0)throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(b(e,["streamableHttpTransport"])!==void 0)throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return r}function Min(e,t){const r={},n=b(e,["mediaResolution"]);if(n!=null&&_(r,["mediaResolution"],n),b(e,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(b(e,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const o=b(e,["audioTranscription"]);o!=null&&_(r,["audioTranscription"],o);const i=b(e,["codeExecutionResult"]);i!=null&&_(r,["codeExecutionResult"],i);const s=b(e,["executableCode"]);s!=null&&_(r,["executableCode"],s);const a=b(e,["fileData"]);a!=null&&_(r,["fileData"],a);const u=b(e,["functionCall"]);u!=null&&_(r,["functionCall"],u);const l=b(e,["functionResponse"]);l!=null&&_(r,["functionResponse"],l);const c=b(e,["inlineData"]);c!=null&&_(r,["inlineData"],c);const d=b(e,["text"]);d!=null&&_(r,["text"],d);const p=b(e,["thought"]);p!=null&&_(r,["thought"],p);const m=b(e,["thoughtSignature"]);m!=null&&_(r,["thoughtSignature"],m);const h=b(e,["videoMetadata"]);if(h!=null&&_(r,["videoMetadata"],h),b(e,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const g=b(e,["mediaProcessing"]);g!=null&&_(r,["mediaProcessing"],g);const y=b(e,["speechMetadata"]);return y!=null&&_(r,["speechMetadata"],y),r}function Pin(e,t){const r={},n=b(e,["references"]);n!=null&&_(r,["references"],n);const o=b(e,["contents"]);if(o!=null){let a=o;Array.isArray(a)&&(a=a.map(u=>hJ(u))),_(r,["contents"],a)}const i=b(e,["systemInstruction"]);i!=null&&_(r,["systemInstruction"],hJ(i));const s=b(e,["tools"]);if(s!=null){let a=s;Array.isArray(a)&&(a=a.map(u=>Din(u))),_(r,["tools"],a)}return r}function Din(e,t){const r={},n=b(e,["retrieval"]);n!=null&&_(r,["retrieval"],n);const o=b(e,["googleMaps"]);o!=null&&_(r,["googleMaps"],o);const i=b(e,["mcpServers"]);if(i!=null){let g=i;Array.isArray(g)&&(g=g.map(y=>Rin(y))),_(r,["mcpServers"],g)}const s=b(e,["codeExecution"]);s!=null&&_(r,["codeExecution"],s);const a=b(e,["computerUse"]);a!=null&&_(r,["computerUse"],a);const u=b(e,["enterpriseWebSearch"]);u!=null&&_(r,["enterpriseWebSearch"],u);const l=b(e,["exaAiSearch"]);l!=null&&_(r,["exaAiSearch"],l);const c=b(e,["functionDeclarations"]);if(c!=null){let g=c;Array.isArray(g)&&(g=g.map(y=>y)),_(r,["functionDeclarations"],g)}const d=b(e,["googleSearch"]);d!=null&&_(r,["googleSearch"],d);const p=b(e,["googleSearchRetrieval"]);p!=null&&_(r,["googleSearchRetrieval"],p);const m=b(e,["parallelAiSearch"]);m!=null&&_(r,["parallelAiSearch"],m);const h=b(e,["urlContext"]);if(h!=null&&_(r,["urlContext"],h),b(e,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return r}function Oin(e,t){const r={},n=b(e,["name"]);n!=null&&_(r,["model"],n);const o=b(e,["name"]);return o!=null&&_(r,["endpoint"],o),r}function Nin(e,t){const r={};if(b(e,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["vertexDatasetResource"])!==void 0)throw new Error("vertexDatasetResource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=b(e,["examples"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(i=>i)),_(r,["examples","examples"],o)}return r}function Lin(e,t,r){const n={};let o=b(r,["config","method"]);if(o===void 0&&(o="SUPERVISED_FINE_TUNING"),o==="SUPERVISED_FINE_TUNING"){const s=b(e,["gcsUri"]);t!==void 0&&s!=null&&_(t,["supervisedTuningSpec","trainingDatasetUri"],s)}else if(o==="PREFERENCE_TUNING"){const s=b(e,["gcsUri"]);t!==void 0&&s!=null&&_(t,["preferenceOptimizationSpec","trainingDatasetUri"],s)}else if(o==="DISTILLATION"){const s=b(e,["gcsUri"]);t!==void 0&&s!=null&&_(t,["distillationSpec","promptDatasetUri"],s)}else if(o==="REINFORCEMENT_TUNING"){const s=b(e,["gcsUri"]);t!==void 0&&s!=null&&_(t,["reinforcementTuningSpec","trainingDatasetUri"],s)}let i=b(r,["config","method"]);if(i===void 0&&(i="SUPERVISED_FINE_TUNING"),i==="SUPERVISED_FINE_TUNING"){const s=b(e,["vertexDatasetResource"]);t!==void 0&&s!=null&&_(t,["supervisedTuningSpec","trainingDatasetUri"],s)}else if(i==="PREFERENCE_TUNING"){const s=b(e,["vertexDatasetResource"]);t!==void 0&&s!=null&&_(t,["preferenceOptimizationSpec","trainingDatasetUri"],s)}else if(i==="DISTILLATION"){const s=b(e,["vertexDatasetResource"]);t!==void 0&&s!=null&&_(t,["distillationSpec","promptDatasetUri"],s)}else if(i==="REINFORCEMENT_TUNING"){const s=b(e,["vertexDatasetResource"]);t!==void 0&&s!=null&&_(t,["reinforcementTuningSpec","trainingDatasetUri"],s)}if(b(e,["examples"])!==void 0)throw new Error("examples parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function $in(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["name"]);o!=null&&_(r,["name"],o);const i=b(e,["state"]);i!=null&&_(r,["state"],YVe(i));const s=b(e,["createTime"]);s!=null&&_(r,["createTime"],s);const a=b(e,["tuningTask","startTime"]);a!=null&&_(r,["startTime"],a);const u=b(e,["tuningTask","completeTime"]);u!=null&&_(r,["endTime"],u);const l=b(e,["updateTime"]);l!=null&&_(r,["updateTime"],l);const c=b(e,["description"]);c!=null&&_(r,["description"],c);const d=b(e,["baseModel"]);d!=null&&_(r,["baseModel"],d);const p=b(e,["_self"]);return p!=null&&_(r,["tunedModel"],Oin(p)),r}function fJ(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["name"]);o!=null&&_(r,["name"],o);const i=b(e,["state"]);i!=null&&_(r,["state"],YVe(i));const s=b(e,["createTime"]);s!=null&&_(r,["createTime"],s);const a=b(e,["startTime"]);a!=null&&_(r,["startTime"],a);const u=b(e,["endTime"]);u!=null&&_(r,["endTime"],u);const l=b(e,["updateTime"]);l!=null&&_(r,["updateTime"],l);const c=b(e,["error"]);c!=null&&_(r,["error"],c);const d=b(e,["description"]);d!=null&&_(r,["description"],d);const p=b(e,["baseModel"]);p!=null&&_(r,["baseModel"],p);const m=b(e,["tunedModel"]);m!=null&&_(r,["tunedModel"],m);const h=b(e,["preTunedModel"]);h!=null&&_(r,["preTunedModel"],h);const g=b(e,["supervisedTuningSpec"]);g!=null&&_(r,["supervisedTuningSpec"],g);const y=b(e,["preferenceOptimizationSpec"]);y!=null&&_(r,["preferenceOptimizationSpec"],y);const v=b(e,["distillationSamplingSpec"]);v!=null&&_(r,["distillationSamplingSpec"],_in(v));const w=b(e,["distillationSpec"]);w!=null&&_(r,["distillationSpec"],Ein(w));const T=b(e,["reinforcementTuningSpec"]);T!=null&&_(r,["reinforcementTuningSpec"],T);const E=b(e,["tuningDataStats"]);E!=null&&_(r,["tuningDataStats"],E);const k=b(e,["encryptionSpec"]);k!=null&&_(r,["encryptionSpec"],k);const A=b(e,["partnerModelTuningSpec"]);A!=null&&_(r,["partnerModelTuningSpec"],A);const C=b(e,["customBaseModel"]);C!=null&&_(r,["customBaseModel"],C);const R=b(e,["evaluateDatasetRuns"]);if(R!=null){let ne=R;Array.isArray(ne)&&(ne=ne.map(X=>X)),_(r,["evaluateDatasetRuns"],ne)}const x=b(e,["experiment"]);x!=null&&_(r,["experiment"],x);const P=b(e,["fullFineTuningSpec"]);P!=null&&_(r,["fullFineTuningSpec"],P);const D=b(e,["labels"]);D!=null&&_(r,["labels"],D);const L=b(e,["outputUri"]);L!=null&&_(r,["outputUri"],L);const O=b(e,["pipelineJob"]);O!=null&&_(r,["pipelineJob"],O);const N=b(e,["serviceAccount"]);N!=null&&_(r,["serviceAccount"],N);const U=b(e,["tunedModelDisplayName"]);U!=null&&_(r,["tunedModelDisplayName"],U);const $=b(e,["tuningJobMetadata"]);$!=null&&_(r,["tuningJobMetadata"],$);const G=b(e,["tuningJobState"]);G!=null&&_(r,["tuningJobState"],G);const B=b(e,["veoLoraTuningSpec"]);B!=null&&_(r,["veoLoraTuningSpec"],B);const q=b(e,["veoTuningSpec"]);q!=null&&_(r,["veoTuningSpec"],q);const H=b(e,["gcsMetricsUri"]);return H!=null&&_(r,["gcsMetricsUri"],H),r}function Fin(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["name"]);o!=null&&_(r,["name"],o);const i=b(e,["metadata"]);i!=null&&_(r,["metadata"],i);const s=b(e,["done"]);s!=null&&_(r,["done"],s);const a=b(e,["error"]);return a!=null&&_(r,["error"],a),r}function wO(e,t){const r={},n=b(e,["gcsUri"]);n!=null&&_(r,["validationDatasetUri"],n);const o=b(e,["vertexDatasetResource"]);return o!=null&&_(r,["validationDatasetUri"],o),r}function Uin(e,t){const r={},n=b(e,["parent"]);n!=null&&_(r,["_url","parent"],n);const o=b(e,["sampleResponse"]);o!=null&&_(r,["sampleResponse"],hJ(o));const i=b(e,["example"]);i!=null&&_(r,["example"],Pin(i));const s=b(e,["singleRewardConfig"]);s!=null&&_(r,["singleRewardConfig"],s);const a=b(e,["compositeRewardConfig"]);return a!=null&&_(r,["compositeRewardConfig"],a),r}function Bin(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["overallReward"]);o!=null&&_(r,["overallReward"],o);const i=b(e,["error"]);i!=null&&_(r,["error"],i);const s=b(e,["rewardInfoDetails"]);return s!=null&&_(r,["rewardInfoDetails"],s),r}var XWe,Id,gJ,yJ,vJ,wJ,Hp,bJ,TJ,_J,EJ,SJ,kJ,AJ,CJ,xJ,IJ,RJ,MJ,PJ,DJ,OJ,NJ,PA,LJ,$J,FJ,UJ,BJ,zJ,GJ,qJ,DA,jJ,VJ,HJ,WJ,KJ,JJ,XJ,YJ,bO,ZJ,QJ,eX,tX,rX,nX,oX,iX,sX,aX,TO,uX,OA,lX,cX,dX,pX,mX,hX,fX,gX,yX,vX,wX,bX,TX,_X,EX,SX,kX,AX,CX,xX,IX,RX,MX,PX,s0,YWe,ZWe,QWe,eKe,tKe,a0,DX,_O,bc,EO,OX,NX,LX,$X,FX,SO,kO,rKe,nKe,oKe,iKe,sKe,AO,UX,aKe,CO,uKe,lKe,cKe,BX,xO,zX,IO,RO,GX,qX,jX,dKe,VX,HX,WX,KX,JX,pKe,mKe,hKe,MO,fKe,gKe,yKe,vKe,wKe,bKe,TKe,XX,_Ke,EKe,YX,SKe,ZX,Rd,Wp,QX,eY,tY,rY,NA,kKe,AKe,CKe,PO,xKe,IKe,RKe,MKe,PKe,nY,DKe,OKe,NKe,LKe,$Ke,FKe,UKe,BKe,zKe,GKe,qKe,jKe,LA,VKe,HKe,oY,WKe,KKe,$A,JKe,XKe,YKe,u0,iY,FA,sY,aY,uY,Tc,ZKe,Uu,QKe,UA,eJe,tJe,rJe,nJe,oJe,iJe,sJe,aJe,uJe,lJe,lY,cY,cJe,dY,dJe,pY,pJe,mJe,mY,gt,Bu,hY,DO,l0,hJe,BA,fJe,gJe,_c,fY,gY,yY,yJe,zu,Gu,vY,vJe,wJe,bJe,wY,TJe,_Je,fr,EJe,SJe,kJe,AJe,CJe,xJe,IJe,RJe,MJe,PJe,DJe,OJe,NJe,LJe,$Je,FJe,UJe,BJe,zJe,GJe,qJe,jJe,VJe,HJe,WJe,KJe,JJe,XJe,bY,OO,YJe,ZJe,QJe,TY,eXe,_Y,EY,tXe,rXe,yb,SY,kY,nXe,AY,oXe,iXe,sXe,zA=S({"node_modules/.pnpm/@google+genai@2.31.0_@modelcontextprotocol+sdk@1.32.1_@cfworker+json-schema@4.1.1_zod@4.6.7_/node_modules/@google/genai/dist/index.mjs"(){XWe=ml(GYr(),1),Id=class{},(function(e){e.MEDIA_PROCESSING_UNSPECIFIED="MEDIA_PROCESSING_UNSPECIFIED",e.STATIC="STATIC",e.AGENTIC="AGENTIC"})(gJ||(gJ={})),(function(e){e.OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",e.OUTCOME_OK="OUTCOME_OK",e.OUTCOME_FAILED="OUTCOME_FAILED",e.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED"})(yJ||(yJ={})),(function(e){e.LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",e.PYTHON="PYTHON"})(vJ||(vJ={})),(function(e){e.SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",e.SILENT="SILENT",e.WHEN_IDLE="WHEN_IDLE",e.INTERRUPT="INTERRUPT"})(wJ||(wJ={})),(function(e){e.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",e.STRING="STRING",e.NUMBER="NUMBER",e.INTEGER="INTEGER",e.BOOLEAN="BOOLEAN",e.ARRAY="ARRAY",e.OBJECT="OBJECT",e.NULL="NULL"})(Hp||(Hp={})),(function(e){e.AUTH_TYPE_UNSPECIFIED="AUTH_TYPE_UNSPECIFIED",e.NO_AUTH="NO_AUTH",e.API_KEY_AUTH="API_KEY_AUTH",e.HTTP_BASIC_AUTH="HTTP_BASIC_AUTH",e.GOOGLE_SERVICE_ACCOUNT_AUTH="GOOGLE_SERVICE_ACCOUNT_AUTH",e.OAUTH="OAUTH",e.OIDC_AUTH="OIDC_AUTH"})(bJ||(bJ={})),(function(e){e.HTTP_IN_UNSPECIFIED="HTTP_IN_UNSPECIFIED",e.HTTP_IN_QUERY="HTTP_IN_QUERY",e.HTTP_IN_HEADER="HTTP_IN_HEADER",e.HTTP_IN_PATH="HTTP_IN_PATH",e.HTTP_IN_BODY="HTTP_IN_BODY",e.HTTP_IN_COOKIE="HTTP_IN_COOKIE"})(TJ||(TJ={})),(function(e){e.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",e.SIMPLE_SEARCH="SIMPLE_SEARCH",e.ELASTIC_SEARCH="ELASTIC_SEARCH"})(_J||(_J={})),(function(e){e.SAFETY_POLICY_UNSPECIFIED="SAFETY_POLICY_UNSPECIFIED",e.FINANCIAL_TRANSACTIONS="FINANCIAL_TRANSACTIONS",e.SENSITIVE_DATA_MODIFICATION="SENSITIVE_DATA_MODIFICATION",e.COMMUNICATION_TOOL="COMMUNICATION_TOOL",e.ACCOUNT_CREATION="ACCOUNT_CREATION",e.DATA_MODIFICATION="DATA_MODIFICATION",e.USER_CONSENT_MANAGEMENT="USER_CONSENT_MANAGEMENT",e.LEGAL_TERMS_AND_AGREEMENTS="LEGAL_TERMS_AND_AGREEMENTS"})(EJ||(EJ={})),(function(e){e.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",e.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER",e.ENVIRONMENT_MOBILE="ENVIRONMENT_MOBILE",e.ENVIRONMENT_DESKTOP="ENVIRONMENT_DESKTOP"})(SJ||(SJ={})),(function(e){e.PHISH_BLOCK_THRESHOLD_UNSPECIFIED="PHISH_BLOCK_THRESHOLD_UNSPECIFIED",e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_HIGH_AND_ABOVE="BLOCK_HIGH_AND_ABOVE",e.BLOCK_HIGHER_AND_ABOVE="BLOCK_HIGHER_AND_ABOVE",e.BLOCK_VERY_HIGH_AND_ABOVE="BLOCK_VERY_HIGH_AND_ABOVE",e.BLOCK_ONLY_EXTREMELY_HIGH="BLOCK_ONLY_EXTREMELY_HIGH"})(kJ||(kJ={})),(function(e){e.UNSPECIFIED="UNSPECIFIED",e.BLOCKING="BLOCKING",e.NON_BLOCKING="NON_BLOCKING"})(AJ||(AJ={})),(function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.MODE_DYNAMIC="MODE_DYNAMIC"})(CJ||(CJ={})),(function(e){e.THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",e.MINIMAL="MINIMAL",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH"})(xJ||(xJ={})),(function(e){e.DONT_ALLOW="DONT_ALLOW",e.ALLOW_ADULT="ALLOW_ADULT",e.ALLOW_ALL="ALLOW_ALL"})(IJ||(IJ={})),(function(e){e.PROMINENT_PEOPLE_UNSPECIFIED="PROMINENT_PEOPLE_UNSPECIFIED",e.ALLOW_PROMINENT_PEOPLE="ALLOW_PROMINENT_PEOPLE",e.BLOCK_PROMINENT_PEOPLE="BLOCK_PROMINENT_PEOPLE"})(RJ||(RJ={})),(function(e){e.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",e.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",e.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",e.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",e.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",e.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY",e.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK",e.HARM_CATEGORY_IMAGE_HATE="HARM_CATEGORY_IMAGE_HATE",e.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT",e.HARM_CATEGORY_IMAGE_HARASSMENT="HARM_CATEGORY_IMAGE_HARASSMENT",e.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"})(MJ||(MJ={})),(function(e){e.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",e.SEVERITY="SEVERITY",e.PROBABILITY="PROBABILITY"})(PJ||(PJ={})),(function(e){e.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",e.BLOCK_NONE="BLOCK_NONE",e.OFF="OFF"})(DJ||(DJ={})),(function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.AUTO="AUTO",e.ANY="ANY",e.NONE="NONE",e.VALIDATED="VALIDATED"})(OJ||(OJ={})),(function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.VERBATIM="VERBATIM",e.SMART="SMART"})(NJ||(NJ={})),(function(e){e.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",e.STOP="STOP",e.MAX_TOKENS="MAX_TOKENS",e.SAFETY="SAFETY",e.RECITATION="RECITATION",e.LANGUAGE="LANGUAGE",e.OTHER="OTHER",e.BLOCKLIST="BLOCKLIST",e.PROHIBITED_CONTENT="PROHIBITED_CONTENT",e.SPII="SPII",e.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",e.IMAGE_SAFETY="IMAGE_SAFETY",e.UNEXPECTED_TOOL_CALL="UNEXPECTED_TOOL_CALL",e.TOO_MANY_TOOL_CALLS="TOO_MANY_TOOL_CALLS",e.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",e.NO_IMAGE="NO_IMAGE",e.IMAGE_RECITATION="IMAGE_RECITATION",e.IMAGE_OTHER="IMAGE_OTHER",e.CONTINUATION="CONTINUATION"})(PA||(PA={})),(function(e){e.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",e.NEGLIGIBLE="NEGLIGIBLE",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH"})(LJ||(LJ={})),(function(e){e.HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",e.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",e.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",e.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",e.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH"})($J||($J={})),(function(e){e.URL_RETRIEVAL_STATUS_UNSPECIFIED="URL_RETRIEVAL_STATUS_UNSPECIFIED",e.URL_RETRIEVAL_STATUS_SUCCESS="URL_RETRIEVAL_STATUS_SUCCESS",e.URL_RETRIEVAL_STATUS_ERROR="URL_RETRIEVAL_STATUS_ERROR",e.URL_RETRIEVAL_STATUS_PAYWALL="URL_RETRIEVAL_STATUS_PAYWALL",e.URL_RETRIEVAL_STATUS_UNSAFE="URL_RETRIEVAL_STATUS_UNSAFE"})(FJ||(FJ={})),(function(e){e.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",e.SAFETY="SAFETY",e.OTHER="OTHER",e.BLOCKLIST="BLOCKLIST",e.PROHIBITED_CONTENT="PROHIBITED_CONTENT",e.IMAGE_SAFETY="IMAGE_SAFETY",e.MODEL_ARMOR="MODEL_ARMOR",e.JAILBREAK="JAILBREAK"})(UJ||(UJ={})),(function(e){e.TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",e.ON_DEMAND="ON_DEMAND",e.ON_DEMAND_PRIORITY="ON_DEMAND_PRIORITY",e.ON_DEMAND_FLEX="ON_DEMAND_FLEX",e.ON_DEMAND_OFFPEAK="ON_DEMAND_OFFPEAK",e.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT"})(BJ||(BJ={})),(function(e){e.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",e.TEXT="TEXT",e.IMAGE="IMAGE",e.VIDEO="VIDEO",e.AUDIO="AUDIO",e.DOCUMENT="DOCUMENT"})(zJ||(zJ={})),(function(e){e.MODEL_STAGE_UNSPECIFIED="MODEL_STAGE_UNSPECIFIED",e.UNSTABLE_EXPERIMENTAL="UNSTABLE_EXPERIMENTAL",e.EXPERIMENTAL="EXPERIMENTAL",e.PREVIEW="PREVIEW",e.STABLE="STABLE",e.LEGACY="LEGACY",e.DEPRECATED="DEPRECATED",e.RETIRED="RETIRED"})(GJ||(GJ={})),(function(e){e.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",e.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",e.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",e.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH"})(qJ||(qJ={})),(function(e){e.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",e.TEXT="TEXT",e.IMAGE="IMAGE",e.AUDIO="AUDIO",e.VIDEO="VIDEO"})(DA||(DA={})),(function(e){e.DELIVERY_UNSPECIFIED="DELIVERY_UNSPECIFIED",e.INLINE="INLINE",e.URI="URI"})(jJ||(jJ={})),(function(e){e.ASPECT_RATIO_UNSPECIFIED="ASPECT_RATIO_UNSPECIFIED",e.ASPECT_RATIO_ONE_BY_ONE="ASPECT_RATIO_ONE_BY_ONE",e.ASPECT_RATIO_TWO_BY_THREE="ASPECT_RATIO_TWO_BY_THREE",e.ASPECT_RATIO_THREE_BY_TWO="ASPECT_RATIO_THREE_BY_TWO",e.ASPECT_RATIO_THREE_BY_FOUR="ASPECT_RATIO_THREE_BY_FOUR",e.ASPECT_RATIO_FOUR_BY_THREE="ASPECT_RATIO_FOUR_BY_THREE",e.ASPECT_RATIO_FOUR_BY_FIVE="ASPECT_RATIO_FOUR_BY_FIVE",e.ASPECT_RATIO_FIVE_BY_FOUR="ASPECT_RATIO_FIVE_BY_FOUR",e.ASPECT_RATIO_NINE_BY_SIXTEEN="ASPECT_RATIO_NINE_BY_SIXTEEN",e.ASPECT_RATIO_SIXTEEN_BY_NINE="ASPECT_RATIO_SIXTEEN_BY_NINE",e.ASPECT_RATIO_TWENTY_ONE_BY_NINE="ASPECT_RATIO_TWENTY_ONE_BY_NINE",e.ASPECT_RATIO_ONE_BY_EIGHT="ASPECT_RATIO_ONE_BY_EIGHT",e.ASPECT_RATIO_EIGHT_BY_ONE="ASPECT_RATIO_EIGHT_BY_ONE",e.ASPECT_RATIO_ONE_BY_FOUR="ASPECT_RATIO_ONE_BY_FOUR",e.ASPECT_RATIO_FOUR_BY_ONE="ASPECT_RATIO_FOUR_BY_ONE"})(VJ||(VJ={})),(function(e){e.IMAGE_SIZE_UNSPECIFIED="IMAGE_SIZE_UNSPECIFIED",e.IMAGE_SIZE_FIVE_TWELVE="IMAGE_SIZE_FIVE_TWELVE",e.IMAGE_SIZE_ONE_K="IMAGE_SIZE_ONE_K",e.IMAGE_SIZE_TWO_K="IMAGE_SIZE_TWO_K",e.IMAGE_SIZE_FOUR_K="IMAGE_SIZE_FOUR_K"})(HJ||(HJ={})),(function(e){e.TUNING_MODE_UNSPECIFIED="TUNING_MODE_UNSPECIFIED",e.TUNING_MODE_FULL="TUNING_MODE_FULL",e.TUNING_MODE_PEFT_ADAPTER="TUNING_MODE_PEFT_ADAPTER"})(WJ||(WJ={})),(function(e){e.ADAPTER_SIZE_UNSPECIFIED="ADAPTER_SIZE_UNSPECIFIED",e.ADAPTER_SIZE_ONE="ADAPTER_SIZE_ONE",e.ADAPTER_SIZE_TWO="ADAPTER_SIZE_TWO",e.ADAPTER_SIZE_FOUR="ADAPTER_SIZE_FOUR",e.ADAPTER_SIZE_EIGHT="ADAPTER_SIZE_EIGHT",e.ADAPTER_SIZE_SIXTEEN="ADAPTER_SIZE_SIXTEEN",e.ADAPTER_SIZE_THIRTY_TWO="ADAPTER_SIZE_THIRTY_TWO"})(KJ||(KJ={})),(function(e){e.RESPONSE_PARSE_TYPE_UNSPECIFIED="RESPONSE_PARSE_TYPE_UNSPECIFIED",e.IDENTITY="IDENTITY",e.REGEX_EXTRACT="REGEX_EXTRACT"})(JJ||(JJ={})),(function(e){e.MATCH_OPERATION_UNSPECIFIED="MATCH_OPERATION_UNSPECIFIED",e.REGEX_CONTAINS="REGEX_CONTAINS",e.PARTIAL_MATCH="PARTIAL_MATCH",e.EXACT_MATCH="EXACT_MATCH"})(XJ||(XJ={})),(function(e){e.REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED="REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED",e.MINIMAL="MINIMAL",e.HIGH="HIGH"})(YJ||(YJ={})),(function(e){e.JOB_STATE_UNSPECIFIED="JOB_STATE_UNSPECIFIED",e.JOB_STATE_QUEUED="JOB_STATE_QUEUED",e.JOB_STATE_PENDING="JOB_STATE_PENDING",e.JOB_STATE_RUNNING="JOB_STATE_RUNNING",e.JOB_STATE_SUCCEEDED="JOB_STATE_SUCCEEDED",e.JOB_STATE_FAILED="JOB_STATE_FAILED",e.JOB_STATE_CANCELLING="JOB_STATE_CANCELLING",e.JOB_STATE_CANCELLED="JOB_STATE_CANCELLED",e.JOB_STATE_PAUSED="JOB_STATE_PAUSED",e.JOB_STATE_EXPIRED="JOB_STATE_EXPIRED",e.JOB_STATE_UPDATING="JOB_STATE_UPDATING",e.JOB_STATE_PARTIALLY_SUCCEEDED="JOB_STATE_PARTIALLY_SUCCEEDED"})(bO||(bO={})),(function(e){e.TUNING_JOB_STATE_UNSPECIFIED="TUNING_JOB_STATE_UNSPECIFIED",e.TUNING_JOB_STATE_WAITING_FOR_QUOTA="TUNING_JOB_STATE_WAITING_FOR_QUOTA",e.TUNING_JOB_STATE_PROCESSING_DATASET="TUNING_JOB_STATE_PROCESSING_DATASET",e.TUNING_JOB_STATE_WAITING_FOR_CAPACITY="TUNING_JOB_STATE_WAITING_FOR_CAPACITY",e.TUNING_JOB_STATE_TUNING="TUNING_JOB_STATE_TUNING",e.TUNING_JOB_STATE_POST_PROCESSING="TUNING_JOB_STATE_POST_PROCESSING"})(ZJ||(ZJ={})),(function(e){e.AGGREGATION_METRIC_UNSPECIFIED="AGGREGATION_METRIC_UNSPECIFIED",e.AVERAGE="AVERAGE",e.MODE="MODE",e.STANDARD_DEVIATION="STANDARD_DEVIATION",e.VARIANCE="VARIANCE",e.MINIMUM="MINIMUM",e.MAXIMUM="MAXIMUM",e.MEDIAN="MEDIAN",e.PERCENTILE_P90="PERCENTILE_P90",e.PERCENTILE_P95="PERCENTILE_P95",e.PERCENTILE_P99="PERCENTILE_P99"})(QJ||(QJ={})),(function(e){e.PAIRWISE_CHOICE_UNSPECIFIED="PAIRWISE_CHOICE_UNSPECIFIED",e.BASELINE="BASELINE",e.CANDIDATE="CANDIDATE",e.TIE="TIE"})(eX||(eX={})),(function(e){e.VIDEO_ORIENTATION_UNSPECIFIED="VIDEO_ORIENTATION_UNSPECIFIED",e.LANDSCAPE="LANDSCAPE",e.PORTRAIT="PORTRAIT"})(tX||(tX={})),(function(e){e.TUNING_SPEED_UNSPECIFIED="TUNING_SPEED_UNSPECIFIED",e.REGULAR="REGULAR",e.FAST="FAST"})(rX||(rX={})),(function(e){e.TUNING_TASK_UNSPECIFIED="TUNING_TASK_UNSPECIFIED",e.TUNING_TASK_I2V="TUNING_TASK_I2V",e.TUNING_TASK_T2V="TUNING_TASK_T2V",e.TUNING_TASK_R2V="TUNING_TASK_R2V"})(nX||(nX={})),(function(e){e.STATE_UNSPECIFIED="STATE_UNSPECIFIED",e.STATE_PENDING="STATE_PENDING",e.STATE_ACTIVE="STATE_ACTIVE",e.STATE_FAILED="STATE_FAILED"})(oX||(oX={})),(function(e){e.UNSPECIFIED="unspecified",e.FLEX="flex",e.STANDARD="standard",e.PRIORITY="priority"})(iX||(iX={})),(function(e){e.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",e.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",e.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",e.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",e.MEDIA_RESOLUTION_ULTRA_HIGH="MEDIA_RESOLUTION_ULTRA_HIGH"})(sX||(sX={})),(function(e){e.TOOL_TYPE_UNSPECIFIED="TOOL_TYPE_UNSPECIFIED",e.GOOGLE_SEARCH_WEB="GOOGLE_SEARCH_WEB",e.GOOGLE_SEARCH_IMAGE="GOOGLE_SEARCH_IMAGE",e.URL_CONTEXT="URL_CONTEXT",e.GOOGLE_MAPS="GOOGLE_MAPS",e.FILE_SEARCH="FILE_SEARCH",e.MEDIA_PROCESSING="MEDIA_PROCESSING"})(aX||(aX={})),(function(e){e.COLLECTION="COLLECTION"})(TO||(TO={})),(function(e){e.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",e.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",e.BALANCED="BALANCED",e.PRIORITIZE_COST="PRIORITIZE_COST"})(uX||(uX={})),(function(e){e.PREDICT="PREDICT",e.EMBED_CONTENT="EMBED_CONTENT"})(OA||(OA={})),(function(e){e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",e.BLOCK_NONE="BLOCK_NONE"})(lX||(lX={})),(function(e){e.auto="auto",e.en="en",e.ja="ja",e.ko="ko",e.hi="hi",e.zh="zh",e.pt="pt",e.es="es"})(cX||(cX={})),(function(e){e.MASK_MODE_DEFAULT="MASK_MODE_DEFAULT",e.MASK_MODE_USER_PROVIDED="MASK_MODE_USER_PROVIDED",e.MASK_MODE_BACKGROUND="MASK_MODE_BACKGROUND",e.MASK_MODE_FOREGROUND="MASK_MODE_FOREGROUND",e.MASK_MODE_SEMANTIC="MASK_MODE_SEMANTIC"})(dX||(dX={})),(function(e){e.CONTROL_TYPE_DEFAULT="CONTROL_TYPE_DEFAULT",e.CONTROL_TYPE_CANNY="CONTROL_TYPE_CANNY",e.CONTROL_TYPE_SCRIBBLE="CONTROL_TYPE_SCRIBBLE",e.CONTROL_TYPE_FACE_MESH="CONTROL_TYPE_FACE_MESH"})(pX||(pX={})),(function(e){e.SUBJECT_TYPE_DEFAULT="SUBJECT_TYPE_DEFAULT",e.SUBJECT_TYPE_PERSON="SUBJECT_TYPE_PERSON",e.SUBJECT_TYPE_ANIMAL="SUBJECT_TYPE_ANIMAL",e.SUBJECT_TYPE_PRODUCT="SUBJECT_TYPE_PRODUCT"})(mX||(mX={})),(function(e){e.EDIT_MODE_DEFAULT="EDIT_MODE_DEFAULT",e.EDIT_MODE_INPAINT_REMOVAL="EDIT_MODE_INPAINT_REMOVAL",e.EDIT_MODE_INPAINT_INSERTION="EDIT_MODE_INPAINT_INSERTION",e.EDIT_MODE_OUTPAINT="EDIT_MODE_OUTPAINT",e.EDIT_MODE_CONTROLLED_EDITING="EDIT_MODE_CONTROLLED_EDITING",e.EDIT_MODE_STYLE="EDIT_MODE_STYLE",e.EDIT_MODE_BGSWAP="EDIT_MODE_BGSWAP",e.EDIT_MODE_PRODUCT_IMAGE="EDIT_MODE_PRODUCT_IMAGE"})(hX||(hX={})),(function(e){e.FOREGROUND="FOREGROUND",e.BACKGROUND="BACKGROUND",e.PROMPT="PROMPT",e.SEMANTIC="SEMANTIC",e.INTERACTIVE="INTERACTIVE"})(fX||(fX={})),(function(e){e.ASSET="ASSET",e.STYLE="STYLE"})(gX||(gX={})),(function(e){e.INSERT="INSERT",e.REMOVE="REMOVE",e.REMOVE_STATIC="REMOVE_STATIC",e.OUTPAINT="OUTPAINT"})(yX||(yX={})),(function(e){e.OPTIMIZED="OPTIMIZED",e.LOSSLESS="LOSSLESS"})(vX||(vX={})),(function(e){e.CROP="CROP",e.PAD="PAD"})(wX||(wX={})),(function(e){e.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",e.PREFERENCE_TUNING="PREFERENCE_TUNING",e.DISTILLATION="DISTILLATION",e.REINFORCEMENT_TUNING="REINFORCEMENT_TUNING"})(bX||(bX={})),(function(e){e.STATE_UNSPECIFIED="STATE_UNSPECIFIED",e.PROCESSING="PROCESSING",e.ACTIVE="ACTIVE",e.FAILED="FAILED"})(TX||(TX={})),(function(e){e.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",e.UPLOADED="UPLOADED",e.GENERATED="GENERATED",e.REGISTERED="REGISTERED"})(_X||(_X={})),(function(e){e.TURN_COMPLETE_REASON_UNSPECIFIED="TURN_COMPLETE_REASON_UNSPECIFIED",e.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",e.RESPONSE_REJECTED="RESPONSE_REJECTED",e.NEED_MORE_INPUT="NEED_MORE_INPUT",e.PROHIBITED_INPUT_CONTENT="PROHIBITED_INPUT_CONTENT",e.IMAGE_PROHIBITED_INPUT_CONTENT="IMAGE_PROHIBITED_INPUT_CONTENT",e.INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED="INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED",e.INPUT_IMAGE_CELEBRITY="INPUT_IMAGE_CELEBRITY",e.INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED="INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED",e.INPUT_TEXT_NCII_PROHIBITED="INPUT_TEXT_NCII_PROHIBITED",e.INPUT_OTHER="INPUT_OTHER",e.INPUT_IP_PROHIBITED="INPUT_IP_PROHIBITED",e.BLOCKLIST="BLOCKLIST",e.UNSAFE_PROMPT_FOR_IMAGE_GENERATION="UNSAFE_PROMPT_FOR_IMAGE_GENERATION",e.GENERATED_IMAGE_SAFETY="GENERATED_IMAGE_SAFETY",e.GENERATED_CONTENT_SAFETY="GENERATED_CONTENT_SAFETY",e.GENERATED_AUDIO_SAFETY="GENERATED_AUDIO_SAFETY",e.GENERATED_VIDEO_SAFETY="GENERATED_VIDEO_SAFETY",e.GENERATED_CONTENT_PROHIBITED="GENERATED_CONTENT_PROHIBITED",e.GENERATED_CONTENT_BLOCKLIST="GENERATED_CONTENT_BLOCKLIST",e.GENERATED_IMAGE_PROHIBITED="GENERATED_IMAGE_PROHIBITED",e.GENERATED_IMAGE_CELEBRITY="GENERATED_IMAGE_CELEBRITY",e.GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER="GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER",e.GENERATED_IMAGE_IDENTIFIABLE_PEOPLE="GENERATED_IMAGE_IDENTIFIABLE_PEOPLE",e.GENERATED_IMAGE_MINORS="GENERATED_IMAGE_MINORS",e.OUTPUT_IMAGE_IP_PROHIBITED="OUTPUT_IMAGE_IP_PROHIBITED",e.GENERATED_OTHER="GENERATED_OTHER",e.MAX_REGENERATION_REACHED="MAX_REGENERATION_REACHED"})(EX||(EX={})),(function(e){e.INTERACTION_STATUS_UNSPECIFIED="INTERACTION_STATUS_UNSPECIFIED",e.IN_PROGRESS="IN_PROGRESS",e.REQUIRES_ACTION="REQUIRES_ACTION",e.IDLE="IDLE"})(SX||(SX={})),(function(e){e.VAD_SIGNAL_TYPE_UNSPECIFIED="VAD_SIGNAL_TYPE_UNSPECIFIED",e.VAD_SIGNAL_TYPE_SOS="VAD_SIGNAL_TYPE_SOS",e.VAD_SIGNAL_TYPE_EOS="VAD_SIGNAL_TYPE_EOS"})(kX||(kX={})),(function(e){e.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",e.ACTIVITY_START="ACTIVITY_START",e.ACTIVITY_END="ACTIVITY_END"})(AX||(AX={})),(function(e){e.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",e.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",e.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"})(CX||(CX={})),(function(e){e.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",e.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",e.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"})(xX||(xX={})),(function(e){e.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",e.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",e.NO_INTERRUPTION="NO_INTERRUPTION"})(IX||(IX={})),(function(e){e.TURN_COVERAGE_UNSPECIFIED="TURN_COVERAGE_UNSPECIFIED",e.TURN_INCLUDES_ONLY_ACTIVITY="TURN_INCLUDES_ONLY_ACTIVITY",e.TURN_INCLUDES_ALL_INPUT="TURN_INCLUDES_ALL_INPUT",e.TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO="TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO"})(RX||(RX={})),(function(e){e.SCALE_UNSPECIFIED="SCALE_UNSPECIFIED",e.C_MAJOR_A_MINOR="C_MAJOR_A_MINOR",e.D_FLAT_MAJOR_B_FLAT_MINOR="D_FLAT_MAJOR_B_FLAT_MINOR",e.D_MAJOR_B_MINOR="D_MAJOR_B_MINOR",e.E_FLAT_MAJOR_C_MINOR="E_FLAT_MAJOR_C_MINOR",e.E_MAJOR_D_FLAT_MINOR="E_MAJOR_D_FLAT_MINOR",e.F_MAJOR_D_MINOR="F_MAJOR_D_MINOR",e.G_FLAT_MAJOR_E_FLAT_MINOR="G_FLAT_MAJOR_E_FLAT_MINOR",e.G_MAJOR_E_MINOR="G_MAJOR_E_MINOR",e.A_FLAT_MAJOR_F_MINOR="A_FLAT_MAJOR_F_MINOR",e.A_MAJOR_G_FLAT_MINOR="A_MAJOR_G_FLAT_MINOR",e.B_FLAT_MAJOR_G_MINOR="B_FLAT_MAJOR_G_MINOR",e.B_MAJOR_A_FLAT_MINOR="B_MAJOR_A_FLAT_MINOR"})(MX||(MX={})),(function(e){e.MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",e.QUALITY="QUALITY",e.DIVERSITY="DIVERSITY",e.VOCALIZATION="VOCALIZATION"})(PX||(PX={})),(function(e){e.PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",e.PLAY="PLAY",e.PAUSE="PAUSE",e.STOP="STOP",e.RESET_CONTEXT="RESET_CONTEXT"})(s0||(s0={})),YWe=class{},ZWe=class{},QWe=class{},eKe=class{},tKe=class{},a0=class{constructor(e){const t={};for(const r of e.headers.entries())t[r[0]]=r[1];this.headers=t,this.responseInternal=e}json(){return this.responseInternal.json()}},DX=class{},_O=class{},bc=class{get text(){var e,t,r,n,o,i,s,a;if(((n=(r=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||r===void 0?void 0:r.parts)===null||n===void 0?void 0:n.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning text from the first one.");let u="",l=!1;const c=[];for(const d of(a=(s=(i=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||i===void 0?void 0:i.content)===null||s===void 0?void 0:s.parts)!==null&&a!==void 0?a:[]){for(const[p,m]of Object.entries(d))p!=="text"&&p!=="thought"&&p!=="thoughtSignature"&&(m!==null||m!==void 0)&&c.push(p);if(typeof d.text=="string"){if(typeof d.thought=="boolean"&&d.thought)continue;l=!0,u+=d.text}}return c.length>0&&console.warn(`there are non-text parts ${c} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),l?u:void 0}get data(){var e,t,r,n,o,i,s,a;if(((n=(r=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||r===void 0?void 0:r.parts)===null||n===void 0?void 0:n.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning data from the first one.");let u="";const l=[];for(const c of(a=(s=(i=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||i===void 0?void 0:i.content)===null||s===void 0?void 0:s.parts)!==null&&a!==void 0?a:[]){for(const[d,p]of Object.entries(c))d!=="inlineData"&&(p!==null||p!==void 0)&&l.push(d);c.inlineData&&typeof c.inlineData.data=="string"&&(u+=atob(c.inlineData.data))}return l.length>0&&console.warn(`there are non-data parts ${l} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),u.length>0?btoa(u):void 0}get functionCalls(){var e,t,r,n,o,i,s,a;if(((n=(r=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||r===void 0?void 0:r.parts)===null||n===void 0?void 0:n.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning function calls from the first one.");const u=(a=(s=(i=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||i===void 0?void 0:i.content)===null||s===void 0?void 0:s.parts)===null||a===void 0?void 0:a.filter(l=>l.functionCall).map(l=>l.functionCall).filter(l=>l!==void 0);if(u?.length!==0)return u}get executableCode(){var e,t,r,n,o,i,s,a,u;if(((n=(r=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||r===void 0?void 0:r.parts)===null||n===void 0?void 0:n.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning executable code from the first one.");const l=(a=(s=(i=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||i===void 0?void 0:i.content)===null||s===void 0?void 0:s.parts)===null||a===void 0?void 0:a.filter(c=>c.executableCode).map(c=>c.executableCode).filter(c=>c!==void 0);if(l?.length!==0)return(u=l?.[0])===null||u===void 0?void 0:u.code}get codeExecutionResult(){var e,t,r,n,o,i,s,a,u;if(((n=(r=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||r===void 0?void 0:r.parts)===null||n===void 0?void 0:n.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning code execution result from the first one.");const l=(a=(s=(i=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||i===void 0?void 0:i.content)===null||s===void 0?void 0:s.parts)===null||a===void 0?void 0:a.filter(c=>c.codeExecutionResult).map(c=>c.codeExecutionResult).filter(c=>c!==void 0);if(l?.length!==0)return(u=l?.[0])===null||u===void 0?void 0:u.output}get initialPromptTokenCount(){var e;if(this.usageMetadata)return(e=this.usageMetadata._initialPromptTokenCount)!==null&&e!==void 0?e:this.usageMetadata.promptTokenCount}},EO=class{},OX=class{},NX=class{},LX=class{},$X=class{},FX=class{},SO=class{},kO=class{},rKe=class{},nKe=class{},oKe=class{},iKe=class{},sKe=class{},AO=class{},UX=class{},aKe=class{},CO=class i5r{_fromAPIResponse({apiResponse:t,_isVertexAI:r}){const n=new i5r;let o;const i=t;return r?o=WYr(i):o=HYr(i),Object.assign(n,o),n}},uKe=class{},lKe=class{},cKe=class{},BX=class{},xO=class{},zX=class{},IO=class{},RO=class{},GX=class{},qX=class{},jX=class{},dKe=class{},VX=class s5r{_fromAPIResponse({apiResponse:t,_isVertexAI:r}){const n=new s5r,i=eZr(t);return Object.assign(n,i),n}},HX=class{},WX=class{},KX=class{},JX=class{},pKe=class{},mKe=class{},hKe=class{},MO=class{},fKe=class{},gKe=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_RAW",referenceImage:this.referenceImage,referenceId:this.referenceId}}},yKe=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_MASK",referenceImage:this.referenceImage,referenceId:this.referenceId,maskImageConfig:this.config}}},vKe=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_CONTROL",referenceImage:this.referenceImage,referenceId:this.referenceId,controlImageConfig:this.config}}},wKe=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_STYLE",referenceImage:this.referenceImage,referenceId:this.referenceId,styleImageConfig:this.config}}},bKe=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_SUBJECT",referenceImage:this.referenceImage,referenceId:this.referenceId,subjectImageConfig:this.config}}},TKe=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_CONTENT",referenceImage:this.referenceImage,referenceId:this.referenceId}}},XX=class{get text(){var e,t,r;let n="",o=!1;const i=[];for(const s of(r=(t=(e=this.serverContent)===null||e===void 0?void 0:e.modelTurn)===null||t===void 0?void 0:t.parts)!==null&&r!==void 0?r:[]){for(const[a,u]of Object.entries(s))a!=="text"&&a!=="thought"&&u!==null&&i.push(a);if(typeof s.text=="string"){if(typeof s.thought=="boolean"&&s.thought)continue;o=!0,n+=s.text}}return i.length>0&&console.warn(`there are non-text parts ${i} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),o?n:void 0}get data(){var e,t,r;let n="";const o=[];for(const i of(r=(t=(e=this.serverContent)===null||e===void 0?void 0:e.modelTurn)===null||t===void 0?void 0:t.parts)!==null&&r!==void 0?r:[]){for(const[s,a]of Object.entries(i))s!=="inlineData"&&a!==null&&o.push(s);i.inlineData&&typeof i.inlineData.data=="string"&&(n+=atob(i.inlineData.data))}return o.length>0&&console.warn(`there are non-data parts ${o} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),n.length>0?btoa(n):void 0}},_Ke=class{},EKe=class{constructor(){this.functionResponses=[]}},YX=class{get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}},SKe=class{},ZX=class a5r{_fromAPIResponse({apiResponse:t,_isVertexAI:r}){const n=new a5r,i=BVe(t);return Object.assign(n,i),n}},(function(e){e.PAGED_ITEM_BATCH_JOBS="batchJobs",e.PAGED_ITEM_MODELS="models",e.PAGED_ITEM_TUNING_JOBS="tuningJobs",e.PAGED_ITEM_FILES="files",e.PAGED_ITEM_CACHED_CONTENTS="cachedContents",e.PAGED_ITEM_FILE_SEARCH_STORES="fileSearchStores",e.PAGED_ITEM_DOCUMENTS="documents",e.PAGED_ITEM_SKILLS="skills"})(Rd||(Rd={})),Wp=class{constructor(e,t,r,n){this.pageInternal=[],this.paramsInternal={},this.requestInternal=t,this.init(e,r,n)}init(e,t,r){var n,o;this.nameInternal=e,this.pageInternal=t[this.nameInternal]||[],this.sdkHttpResponseInternal=t?.sdkHttpResponse,this.idxInternal=0;let i={config:{}};!r||Object.keys(r).length===0?i={config:{}}:typeof r=="object"?i=Object.assign({},r):i=r,i.config&&(i.config.pageToken=t.nextPageToken),this.paramsInternal=i,this.pageInternalSize=(o=(n=i.config)===null||n===void 0?void 0:n.pageSize)!==null&&o!==void 0?o:this.pageInternal.length}initNextPage(e){this.init(this.nameInternal,e,this.paramsInternal)}get page(){return this.pageInternal}get name(){return this.nameInternal}get pageSize(){return this.pageInternalSize}get sdkHttpResponse(){return this.sdkHttpResponseInternal}get params(){return this.paramsInternal}get pageLength(){return this.pageInternal.length}getItem(e){return this.pageInternal[e]}[Symbol.asyncIterator](){return{next:async()=>{if(this.idxInternal>=this.pageLength)if(this.hasNextPage())await this.nextPage();else return{value:void 0,done:!0};const e=this.getItem(this.idxInternal);return this.idxInternal+=1,{value:e,done:!1}},return:async()=>({value:void 0,done:!0})}}async nextPage(){if(!this.hasNextPage())throw new Error("No more pages to fetch.");const e=await this.requestInternal(this.params);return this.initNextPage(e),this.page}hasNextPage(){var e;return((e=this.params.config)===null||e===void 0?void 0:e.pageToken)!==void 0}},QX=class extends Id{constructor(e){super(),this.apiClient=e,this.list=async(t={})=>new Wp(Rd.PAGED_ITEM_BATCH_JOBS,r=>this.listInternal(r),await this.listInternal(t),t),this.create=async t=>(this.apiClient.isVertexAI()&&(t.config=this.formatDestination(t.src,t.config)),this.createInternal(t)),this.createEmbeddings=async t=>{if(console.warn("batches.createEmbeddings() is experimental and may change without notice."),this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support batches.createEmbeddings.");return this.createEmbeddingsInternal(t)}}createInlinedGenerateContentRequest(e){const t=iHe(this.apiClient,e),r=t._url,n=ct("{model}:batchGenerateContent",r),s=t.batch.inputConfig.requests,a=s.requests,u=[];for(const l of a){const c=Object.assign({},l);if(c.systemInstruction){const d=c.systemInstruction;delete c.systemInstruction;const p=c.request;p.systemInstruction=d,c.request=p}u.push(c)}return s.requests=u,delete t.config,delete t._url,delete t._query,{path:n,body:t}}getGcsUri(e){if(typeof e=="string")return e.startsWith("gs://")?e:void 0;if(!Array.isArray(e)&&e.gcsUri&&e.gcsUri.length>0)return e.gcsUri[0]}getBigqueryUri(e){if(typeof e=="string")return e.startsWith("bq://")?e:void 0;if(!Array.isArray(e))return e.bigqueryUri}formatDestination(e,t){const r=t?Object.assign({},t):{},n=Date.now().toString();if(r.displayName||(r.displayName=`genaiBatchJob_${n}`),r.dest===void 0){const o=this.getGcsUri(e),i=this.getBigqueryUri(e);if(o)o.endsWith(".jsonl")?r.dest=`${o.slice(0,-6)}/dest`:r.dest=`${o}_dest_${n}`;else if(i)r.dest=`${i}_dest_${n}`;else throw new Error("Unsupported source for Gemini Enterprise Agent Platform (previously known as Vertex AI): No GCS or BigQuery URI found.")}return r}async createInternal(e){var t,r,n,o;let i,s="",a={};if(this.apiClient.isVertexAI()){const u=FZr(this.apiClient,e);return s=ct("batchPredictionJobs",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json()),i.then(l=>sJ(l))}else{const u=iHe(this.apiClient,e);return s=ct("{model}:batchGenerateContent",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(l=>l.json()),i.then(l=>dO(l))}}async createEmbeddingsInternal(e){var t,r;let n,o="",i={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=BZr(this.apiClient,e);return o=ct("{model}:asyncBatchEmbedContent",s._url),i=s._query,delete s._url,delete s._query,n=this.apiClient.request({path:o,queryParams:i,body:JSON.stringify(s),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(a=>a.json()),n.then(a=>dO(a))}}async get(e){var t,r,n,o;let i,s="",a={};if(this.apiClient.isVertexAI()){const u=QZr(this.apiClient,e);return s=ct("batchPredictionJobs/{name}",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json()),i.then(l=>sJ(l))}else{const u=ZZr(this.apiClient,e);return s=ct("batches/{name}",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(l=>l.json()),i.then(l=>dO(l))}}async cancel(e){var t,r,n,o;let i="",s={};if(this.apiClient.isVertexAI()){const a=DZr(this.apiClient,e);i=ct("batchPredictionJobs/{name}:cancel",a._url),s=a._query,delete a._url,delete a._query,await this.apiClient.request({path:i,queryParams:s,body:JSON.stringify(a),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal})}else{const a=PZr(this.apiClient,e);i=ct("batches/{name}:cancel",a._url),s=a._query,delete a._url,delete a._query,await this.apiClient.request({path:i,queryParams:s,body:JSON.stringify(a),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal})}}async listInternal(e){var t,r,n,o;let i,s="",a={};if(this.apiClient.isVertexAI()){const u=uQr(e);return s=ct("batchPredictionJobs",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json().then(c=>{const d=c;return d.sdkHttpResponse={headers:l.headers},d})),i.then(l=>{const c=cQr(l),d=new MO;return Object.assign(d,c),d})}else{const u=aQr(e);return s=ct("batches",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(l=>l.json().then(c=>{const d=c;return d.sdkHttpResponse={headers:l.headers},d})),i.then(l=>{const c=lQr(l),d=new MO;return Object.assign(d,c),d})}}async delete(e){var t,r,n,o;let i,s="",a={};if(this.apiClient.isVertexAI()){const u=GZr(this.apiClient,e);return s=ct("batchPredictionJobs/{name}",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json().then(c=>{const d=c;return d.sdkHttpResponse={headers:l.headers},d})),i.then(l=>jZr(l))}else{const u=zZr(this.apiClient,e);return s=ct("batches/{name}",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(l=>l.json().then(c=>{const d=c;return d.sdkHttpResponse={headers:l.headers},d})),i.then(l=>qZr(l))}}},eY=class extends Id{constructor(e){super(),this.apiClient=e,this.list=async(t={})=>new Wp(Rd.PAGED_ITEM_CACHED_CONTENTS,r=>this.listInternal(r),await this.listInternal(t),t)}async create(e){var t,r,n,o;let i,s="",a={};if(this.apiClient.isVertexAI()){const u=TQr(this.apiClient,e);return s=ct("cachedContents",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json()),i.then(l=>l)}else{const u=bQr(this.apiClient,e);return s=ct("cachedContents",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(l=>l.json()),i.then(l=>l)}}async get(e){var t,r,n,o;let i,s="",a={};if(this.apiClient.isVertexAI()){const u=IQr(this.apiClient,e);return s=ct("{name}",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json()),i.then(l=>l)}else{const u=xQr(this.apiClient,e);return s=ct("{name}",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(l=>l.json()),i.then(l=>l)}}async delete(e){var t,r,n,o;let i,s="",a={};if(this.apiClient.isVertexAI()){const u=EQr(this.apiClient,e);return s=ct("{name}",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json().then(c=>{const d=c;return d.sdkHttpResponse={headers:l.headers},d})),i.then(l=>{const c=kQr(l),d=new IO;return Object.assign(d,c),d})}else{const u=_Qr(this.apiClient,e);return s=ct("{name}",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(l=>l.json().then(c=>{const d=c;return d.sdkHttpResponse={headers:l.headers},d})),i.then(l=>{const c=SQr(l),d=new IO;return Object.assign(d,c),d})}}async update(e){var t,r,n,o;let i,s="",a={};if(this.apiClient.isVertexAI()){const u=KQr(this.apiClient,e);return s=ct("{name}",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"PATCH",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json()),i.then(l=>l)}else{const u=WQr(this.apiClient,e);return s=ct("{name}",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"PATCH",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(l=>l.json()),i.then(l=>l)}}async listInternal(e){var t,r,n,o;let i,s="",a={};if(this.apiClient.isVertexAI()){const u=NQr(e);return s=ct("cachedContents",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json().then(c=>{const d=c;return d.sdkHttpResponse={headers:l.headers},d})),i.then(l=>{const c=$Qr(l),d=new RO;return Object.assign(d,c),d})}else{const u=OQr(e);return s=ct("cachedContents",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(l=>l.json().then(c=>{const d=c;return d.sdkHttpResponse={headers:l.headers},d})),i.then(l=>{const c=LQr(l),d=new RO;return Object.assign(d,c),d})}}},tY=class{constructor(e,t){this.modelsModule=e,this.apiClient=t}create(e){return new rY(this.apiClient,this.modelsModule,e.model,e.config,structuredClone(e.history))}},rY=class{constructor(e,t,r,n={},o=[]){this.apiClient=e,this.modelsModule=t,this.model=r,this.config=n,this.history=o,this.sendPromise=Promise.resolve(),XQr(o)}async sendMessage(e){var t;await this.sendPromise;const r=Ii(e.message),n=this.modelsModule.generateContent({model:this.model,contents:this.getHistory(!0).concat(r),config:(t=e.config)!==null&&t!==void 0?t:this.config});return this.sendPromise=(async()=>{var o,i,s;const a=await n,u=(i=(o=a.candidates)===null||o===void 0?void 0:o[0])===null||i===void 0?void 0:i.content,l=a.automaticFunctionCallingHistory,c=this.getHistory(!0).length;let d=[];l!=null&&(d=(s=l.slice(c))!==null&&s!==void 0?s:[]);const p=u?[u]:[];this.recordHistory(r,p,d)})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),n}async sendMessageStream(e){var t;await this.sendPromise;const r=Ii(e.message),n=this.modelsModule.generateContentStream({model:this.model,contents:this.getHistory(!0).concat(r),config:(t=e.config)!==null&&t!==void 0?t:this.config});this.sendPromise=n.then(()=>{}).catch(()=>{});const o=await n;return this.processStreamResponse(o,r)}getHistory(e=!1){const t=e?cHe(this.history):this.history;return structuredClone(t)}processStreamResponse(e,t){return o0(this,arguments,function*(){var n,o,i,s,a,u,l,c;const d=[];let p=!0,m=!1;try{for(var h=!0,g=pb(e),y;y=yield cn(g.next()),n=y.done,!n;h=!0){s=y.value,h=!1;const v=s;if(JQr(v)){const w=(u=(a=v.candidates)===null||a===void 0?void 0:a[0])===null||u===void 0?void 0:u.content;w!==void 0&&d.push(w)}else p=!1;((c=(l=v.candidates)===null||l===void 0?void 0:l[0])===null||c===void 0?void 0:c.finishReason)!==void 0&&(m=!0),yield yield cn(v)}}catch(v){o={error:v}}finally{try{!h&&!n&&(i=g.return)&&(yield cn(i.call(g)))}finally{if(o)throw o.error}}this.recordHistory(t,p&&m?d:[])})}recordHistory(e,t,r){let n=[];t.length>0&&t.every(o=>o.role!==void 0)?n=t:n.push({role:"model",parts:[]}),r&&r.length>0?this.history.push(...cHe(r)):this.history.push(e),this.history.push(...n)}},NA=class u5r extends Error{constructor(t){super(t.message),this.name="ApiError",this.status=t.status,Object.setPrototypeOf(this,u5r.prototype)}},kKe="Content-Type",AKe="X-Server-Timeout",CKe="User-Agent",PO="x-goog-api-client",xKe="2.31.0",IKe=`google-genai-sdk/${xKe}`,RKe="v1beta1",MKe="v1beta",PKe=new Set(["us","eu"]),nY=Symbol.for("undici.globalDispatcher.1"),DKe=5,OKe=1,NKe=60,LKe=2,$Ke=1,FKe=[408,429,500,502,503,504],UKe=class{constructor(e){var t,r,n;this.clientOptions=Object.assign({},e),this.customBaseUrl=(t=e.httpOptions)===null||t===void 0?void 0:t.baseUrl;const o={};if(this.clientOptions.vertexai){if(!this.clientOptions.location&&!this.clientOptions.apiKey&&!this.customBaseUrl&&(this.clientOptions.location="global"),!(this.clientOptions.project&&this.clientOptions.location||this.clientOptions.apiKey)&&!this.customBaseUrl)throw new Error("Authentication is not set up. Please provide either a project and location, or an API key, or a custom base URL.");const s=e.project&&e.location||!!e.apiKey;this.customBaseUrl&&!s?(o.baseUrl=this.customBaseUrl,this.clientOptions.project=void 0,this.clientOptions.location=void 0):this.clientOptions.apiKey&&!this.clientOptions.project||this.clientOptions.location==="global"?o.baseUrl="https://aiplatform.googleapis.com/":this.clientOptions.project&&this.clientOptions.location&&PKe.has(this.clientOptions.location)?o.baseUrl=`https://aiplatform.${this.clientOptions.location}.rep.googleapis.com/`:this.clientOptions.project&&this.clientOptions.location&&(o.baseUrl=`https://${this.clientOptions.location}-aiplatform.googleapis.com/`),o.apiVersion=(r=this.clientOptions.apiVersion)!==null&&r!==void 0?r:RKe}else this.clientOptions.apiKey||console.warn("API key should be set when using the Gemini API."),o.apiVersion=(n=this.clientOptions.apiVersion)!==null&&n!==void 0?n:MKe,o.baseUrl="https://generativelanguage.googleapis.com/";o.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=o,e.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(o,e.httpOptions))}isVertexAI(){var e;return(e=this.clientOptions.vertexai)!==null&&e!==void 0?e:!1}getProject(){return this.clientOptions.project}getLocation(){return this.clientOptions.location}getCustomBaseUrl(){return this.customBaseUrl}async getAuthHeaders(){const e=new Headers;return await this.clientOptions.auth.addAuthHeaders(e),e}getApiVersion(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.apiVersion!==void 0)return this.clientOptions.httpOptions.apiVersion;throw new Error("API version is not set.")}getBaseUrl(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.baseUrl!==void 0)return this.clientOptions.httpOptions.baseUrl;throw new Error("Base URL is not set.")}getRequestUrl(){return this.getRequestUrlInternal(this.clientOptions.httpOptions)}getHeaders(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.headers!==void 0)return this.clientOptions.httpOptions.headers;throw new Error("Headers are not set.")}getFetch(){var e;return(e=this.clientOptions.httpOptions)===null||e===void 0?void 0:e.fetch}getTimeout(){var e;return(e=this.clientOptions.httpOptions)===null||e===void 0?void 0:e.timeout}getRequestUrlInternal(e){if(!e||e.baseUrl===void 0||e.apiVersion===void 0)throw new Error("HTTP options are not correctly set.");const r=[e.baseUrl.endsWith("/")?e.baseUrl.slice(0,-1):e.baseUrl];return e.apiVersion&&e.apiVersion!==""&&r.push(e.apiVersion),r.join("/")}getBaseResourcePath(){return`projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`}getApiKey(){return this.clientOptions.apiKey}getWebsocketBaseUrl(){const e=this.getBaseUrl(),t=new URL(e);return t.protocol=t.protocol=="http:"?"ws":"wss",t.toString()}setBaseUrl(e){if(this.clientOptions.httpOptions)this.clientOptions.httpOptions.baseUrl=e;else throw new Error("HTTP options are not correctly set.")}constructUrl(e,t,r){const n=[this.getRequestUrlInternal(t)];return r&&n.push(this.getBaseResourcePath()),e!==""&&n.push(e),new URL(`${n.join("/")}`)}shouldPrependVertexProjectPath(e,t){return!(t.baseUrl&&t.baseUrlResourceScope===TO.COLLECTION||!this.clientOptions.vertexai||!this.clientOptions.project||!this.clientOptions.location||e.path.startsWith("projects/")||e.httpMethod==="GET"&&e.path.startsWith("publishers/google/models"))}async request(e){let t=this.clientOptions.httpOptions;e.httpOptions&&(t=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));const r=this.shouldPrependVertexProjectPath(e,t),n=this.constructUrl(e.path,t,r);if(e.queryParams)for(const[i,s]of Object.entries(e.queryParams))n.searchParams.append(i,String(s));let o={};if(e.httpMethod==="GET"){if(e.body&&e.body!=="{}")throw new Error("Request body should be empty for GET request, but got non empty request body")}else o.body=e.body;return o=await this.includeExtraHttpOptionsToRequestInit(o,t,n.toString()),this.unaryApiCall(n,o,e.httpMethod,t.retryOptions,t.timeout,e.abortSignal,t.fetch)}patchHttpOptions(e,t){const r=JSON.parse(JSON.stringify(e));e.fetch&&(r.fetch=e.fetch);for(const[n,o]of Object.entries(t))typeof o=="object"?r[n]=Object.assign(Object.assign({},r[n]),o):o!==void 0&&(r[n]=o);return r}async requestStream(e){let t=this.clientOptions.httpOptions;e.httpOptions&&(t=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));const r=this.shouldPrependVertexProjectPath(e,t),n=this.constructUrl(e.path,t,r);(!n.searchParams.has("alt")||n.searchParams.get("alt")!=="sse")&&n.searchParams.set("alt","sse");let o={};return o.body=e.body,o=await this.includeExtraHttpOptionsToRequestInit(o,t,n.toString()),this.streamApiCall(n,o,e.httpMethod,t.retryOptions,t.timeout,e.abortSignal,t.fetch)}async includeExtraHttpOptionsToRequestInit(e,t,r){return den()&&!t?.fetch&&!("dispatcher"in e)&&(e.dispatcher=pen()),t&&t.extraBody!==null&&hen(e,t.extraBody),e.headers=await this.getHeadersInternal(t,r),e}async unaryApiCall(e,t,r,n,o,i,s){return this.apiCall(e.toString(),Object.assign(Object.assign({},t),{method:r}),n,o,i,s).then(async a=>(await aJ(a),new a0(a))).catch(a=>{throw a instanceof Error?a:new Error(`exception ${a} sending request`,{cause:a})})}async streamApiCall(e,t,r,n,o,i,s){return this.apiCall(e.toString(),Object.assign(Object.assign({},t),{method:r}),n,o,i,s).then(async a=>(await aJ(a),this.processStreamResponse(a))).catch(a=>{throw a instanceof Error?a:new Error(`exception ${a} sending request`,{cause:a})})}processStreamResponse(e){return o0(this,arguments,function*(){var r;const n=(r=e?.body)===null||r===void 0?void 0:r.getReader(),o=new TextDecoder("utf-8");if(!n)throw new Error("Response body is empty");try{let i="";const s="data:",a=[`
123
+ `);else if(n)return;return t(a)}}function Rh(e,t,r){return Object.assign(Object.assign({},r),{err:!0,enc:"json",codes:e,errorClass:t})}function Lr(e,t){return Object.assign(Object.assign({},t),{enc:"json",codes:e})}function OHe(e,t,r){return Object.assign(Object.assign(Object.assign({},r),{enc:"sse",codes:e}),t?{sse:t}:{})}function NHe(e,t){return Object.assign(Object.assign({},t),{enc:"nil",codes:e})}function vt(e){return{enc:"fail",codes:e}}function Cr(...e){return async function(r,n,o){let i,s;for(const p of e){const{codes:m}=p,h="ctype"in p?p.ctype:wJe[p.enc];if(h&&etn(r,m,h)){s=p;break}else if(!h&&mr(r,m)){s=p;break}}if(!s)return[{ok:!1,error:new yY("Unexpected Status or Content-Type",{response:r,request:n,body:await r.text().catch(()=>"")})},i];const a=s.enc;let u="";switch(a){case"json":u=await r.text();try{i=JSON.parse(u)}catch(p){if(!("err"in s))throw p;i=u}break;case"jsonl":i=r.body;break;case"bytes":i=new Uint8Array(await r.arrayBuffer());break;case"stream":i=r.body;break;case"text":u=await r.text(),i=u;break;case"sse":if(r.body){const p="sse"in s&&s.sse||{};i=ytn(r.body,p)}else i=null;break;case"nil":u=await r.text(),i=void 0;break;case"fail":u=await r.text(),i=u;break;default:throw new Error(`Unsupported response type: ${a}`)}if(s.enc==="fail")return[{ok:!1,error:new yY("API error occurred",{request:n,response:r,body:u})},i];const l=s.key||o?.resultKey;let c;const d=s.hdrs?{headers:btn(r.headers)}:null;return"err"in s?c=Object.assign(Object.assign(Object.assign({},o?.extraFields),d),Ih(i)?i:null):l?c=Object.assign(Object.assign(Object.assign({},o?.extraFields),d),{[l]:i}):s.hdrs?c=Object.assign(Object.assign(Object.assign({},o?.extraFields),d),Ih(i)?i:null):c=i,"err"in s?[{ok:!1,error:s.errorClass?new s.errorClass(c,{request:n,response:r,body:u}):c},i]:[{ok:!0,value:c},i]}}function btn(e){const t={};for(const[r,n]of e.entries())t[r]=n.split(bJe);return t}function Ttn(...e){const t={basic:{},headers:{},queryParams:{},cookies:{},oauth2:{type:"none"}},r=e.find(n=>n.every(o=>{if(o.value==null)return!1;if(o.type==="http:basic")return o.value.username!=null||o.value.password!=null;if(o.type==="http:custom")return null;if(o.type==="oauth2:password")return typeof o.value=="string"&&!!o.value;if(o.type==="oauth2:client_credentials")return typeof o.value=="string"?!!o.value:o.value.client_id!=null||o.value.client_secret!=null;if(typeof o.value=="string")return!!o.value;throw new Error(`Unrecognized security type: ${o.type} (value type: ${typeof o.value})`)}));return r==null?null:(r.forEach(n=>{if(n.value==null)return;const{type:o}=n;switch(o){case"apiKey:header":t.headers[n.fieldName]=n.value;break;case"apiKey:query":t.queryParams[n.fieldName]=n.value;break;case"apiKey:cookie":t.cookies[n.fieldName]=n.value;break;case"http:basic":_tn(t,n);break;case"http:custom":break;case"http:bearer":mO(t,n);break;case"oauth2":mO(t,n);break;case"oauth2:password":mO(t,n);break;case"oauth2:client_credentials":break;case"openIdConnect":mO(t,n);break;default:throw TJe.unrecognizedType(o)}}),t)}function _tn(e,t){t.value!=null&&(e.basic=t.value)}function mO(e,t){if(typeof t.value!="string"||!t.value)return;let r=t.value;r.slice(0,7).toLowerCase()!=="bearer "&&(r=`Bearer ${r}`),t.fieldName!==void 0&&(e.headers[t.fieldName]=r)}function xr(e,t){var r,n;let o=[[{fieldName:"accessToken",type:"http:custom",value:(r=e?.access_token)!==null&&r!==void 0?r:CA().GOOGLE_GENAI_ACCESS_TOKEN},{fieldName:"apiKey",type:"http:custom",value:(n=e?.api_key)!==null&&n!==void 0?n:CA().GOOGLE_GENAI_API_KEY},{fieldName:"defaultHeaders",type:"http:custom",value:e?.default_headers}]];return Ttn(...o)}async function Ir(e){if(e!=null)return typeof e=="function"?e():e}function Rr(e){const t=e.$inspect(),r=t.then(([o,i])=>{if(!o.ok)throw o.error;return[o.value,i]}),n=t.then(([o,i])=>{var s;if(!o.ok&&!(!((s=i.response)===null||s===void 0)&&s.ok))throw o.error;return i});return r.catch(()=>{}),n.catch(()=>{}),new fr(r,n)}function LHe(e,t,r,n){return new fr(Etn(e,t,r,n))}async function Etn(e,t,r,n){var o,i,s;const u={body:t,api_version:r},l=Al("body",u.body,{explode:!0}),c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/agents")(c),p=new Headers(Ar({"Content-Type":"application/json",Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"CreateAgent",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"POST",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function $He(e,t,r,n){return new fr(Stn(e,t,r,n))}async function Stn(e,t,r,n){var o,i,s;const u={id:t,api_version:r},l=null,c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),agentsId:gt("agentsId",u.id,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/agents/{agentsId}")(c),p=new Headers(Ar({Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"DeleteAgent",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"DELETE",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function FHe(e,t,r,n){return new fr(ktn(e,t,r,n))}async function ktn(e,t,r,n){var o,i,s;const u={id:t,api_version:r},l=null,c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),agentsId:gt("agentsId",u.id,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/agents/{agentsId}")(c),p=new Headers(Ar({Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"GetAgent",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"GET",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function UHe(e,t,r,n,o,i){return new fr(Atn(e,t,r,n,o,i))}async function Atn(e,t,r,n,o,i){var s,a,u;const c={api_version:t,page_size:r,page_token:n,parent:o},d=null,p={api_version:gt("api_version",(s=c?.api_version)!==null&&s!==void 0?s:e._options.api_version,{explode:!1,charEncoding:"percent"})},m=Tr("/{api_version}/agents")(p),h=Bu({page_size:c?.page_size,page_token:c?.page_token,parent:c?.parent}),g=new Headers(Ar({Accept:"application/json"})),y=await Ir(e._options.security),v=xr(y),w={options:e._options,base_url:(u=(a=i?.server_url)!==null&&a!==void 0?a:e._baseURL)!==null&&u!==void 0?u:"",operation_id:"ListAgents",o_auth2_scopes:null,resolved_security:v,security_source:e._options.security,retry_config:i?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},T=e._createRequest(w,{security:v,method:"GET",baseURL:i?.server_url,path:m,headers:g,query:h,body:d,userAgent:e._options.user_agent,timeout_ms:i?.timeout_ms||e._options.timeout_ms||-1},i);if(!T.ok)return[T,{status:"invalid"}];const E=T.value,k=await e._do(E,{context:w,isErrorStatusCode:R=>mr({status:R},["4XX","5XX"]),retryConfig:w.retry_config,retryCodes:w.retry_codes});if(!k.ok)return[k,{status:"request-error",request:E}];const A=k.value,[C]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(A,E);return C.ok?[C,{status:"complete",request:E,response:A}]:[C,{status:"complete",request:E,response:A}]}function BHe(e,t,r,n){return new fr(Ctn(e,t,r,n))}async function Ctn(e,t,r,n){var o,i,s;const u={body:t,api_version:r},l=Al("body",u.body,{explode:!0}),c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/credentials")(c),p=new Headers(Ar({"Content-Type":"application/json",Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"CreateCredential",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"POST",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function zHe(e,t,r,n){return new fr(xtn(e,t,r,n))}async function xtn(e,t,r,n){var o,i,s;const u={id:t,api_version:r},l=null,c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:gt("id",u.id,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/credentials/{id}")(c),p=new Headers(Ar({Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"DeleteCredential",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"DELETE",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function GHe(e,t,r,n){return new fr(Itn(e,t,r,n))}async function Itn(e,t,r,n){var o,i,s;const u={id:t,api_version:r},l=null,c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:gt("id",u.id,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/credentials/{id}")(c),p=new Headers(Ar({Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"GetCredential",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"GET",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function qHe(e,t,r,n,o){return new fr(Rtn(e,t,r,n,o))}async function Rtn(e,t,r,n,o){var i,s,a;const l={api_version:t,page_size:r,page_token:n},c=null,d={api_version:gt("api_version",(i=l?.api_version)!==null&&i!==void 0?i:e._options.api_version,{explode:!1,charEncoding:"percent"})},p=Tr("/{api_version}/credentials")(d),m=Bu({page_size:l?.page_size,page_token:l?.page_token}),h=new Headers(Ar({Accept:"application/json"})),g=await Ir(e._options.security),y=xr(g),v={options:e._options,base_url:(a=(s=o?.server_url)!==null&&s!==void 0?s:e._baseURL)!==null&&a!==void 0?a:"",operation_id:"ListCredentials",o_auth2_scopes:null,resolved_security:y,security_source:e._options.security,retry_config:o?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},w=e._createRequest(v,{security:y,method:"GET",baseURL:o?.server_url,path:p,headers:h,query:m,body:c,userAgent:e._options.user_agent,timeout_ms:o?.timeout_ms||e._options.timeout_ms||-1},o);if(!w.ok)return[w,{status:"invalid"}];const T=w.value,E=await e._do(T,{context:v,isErrorStatusCode:C=>mr({status:C},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!E.ok)return[E,{status:"request-error",request:T}];const k=E.value,[A]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(k,T);return A.ok?[A,{status:"complete",request:T,response:k}]:[A,{status:"complete",request:T,response:k}]}function jHe(e,t,r,n,o,i){return new fr(Mtn(e,t,r,n,o,i))}async function Mtn(e,t,r,n,o,i){var s,a,u;const c={id:t,body:r,api_version:n,update_mask:o},d=Al("body",c.body,{explode:!0}),p={api_version:gt("api_version",(s=c.api_version)!==null&&s!==void 0?s:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:gt("id",c.id,{explode:!1,charEncoding:"percent"})},m=Tr("/{api_version}/credentials/{id}")(p),h=Bu({update_mask:c.update_mask}),g=new Headers(Ar({"Content-Type":"application/json",Accept:"application/json"})),y=await Ir(e._options.security),v=xr(y),w={options:e._options,base_url:(u=(a=i?.server_url)!==null&&a!==void 0?a:e._baseURL)!==null&&u!==void 0?u:"",operation_id:"UpdateCredential",o_auth2_scopes:null,resolved_security:v,security_source:e._options.security,retry_config:i?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},T=e._createRequest(w,{security:v,method:"PATCH",baseURL:i?.server_url,path:m,headers:g,query:h,body:d,userAgent:e._options.user_agent,timeout_ms:i?.timeout_ms||e._options.timeout_ms||-1},i);if(!T.ok)return[T,{status:"invalid"}];const E=T.value,k=await e._do(E,{context:w,isErrorStatusCode:R=>mr({status:R},["4XX","5XX"]),retryConfig:w.retry_config,retryCodes:w.retry_codes});if(!k.ok)return[k,{status:"request-error",request:E}];const A=k.value,[C]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(A,E);return C.ok?[C,{status:"complete",request:E,response:A}]:[C,{status:"complete",request:E,response:A}]}function VHe(e,t,r,n){return new fr(Ptn(e,t,r,n))}async function Ptn(e,t,r,n){var o,i,s;const u={body:t,api_version:r},l=Al("body",u.body,{explode:!0}),c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/environments")(c),p=new Headers(Ar({"Content-Type":"application/json",Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"CreateEnvironment",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"POST",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function HHe(e,t,r,n){return new fr(Dtn(e,t,r,n))}async function Dtn(e,t,r,n){var o,i,s;const u={id:t,api_version:r},l=null,c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:gt("id",u.id,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/environments/{id}")(c),p=new Headers(Ar({Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"DeleteEnvironment",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"DELETE",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function WHe(e,t,r,n){return new fr(Otn(e,t,r,n))}async function Otn(e,t,r,n){var o,i,s;const u={id:t,api_version:r},l=null,c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:gt("id",u.id,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/environments/{id}")(c),p=new Headers(Ar({Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"GetEnvironment",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"GET",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function KHe(e,t,r,n,o){return new fr(Ntn(e,t,r,n,o))}async function Ntn(e,t,r,n,o){var i,s,a;const l={api_version:t,page_size:r,page_token:n},c=null,d={api_version:gt("api_version",(i=l?.api_version)!==null&&i!==void 0?i:e._options.api_version,{explode:!1,charEncoding:"percent"})},p=Tr("/{api_version}/environments")(d),m=Bu({page_size:l?.page_size,page_token:l?.page_token}),h=new Headers(Ar({Accept:"application/json"})),g=await Ir(e._options.security),y=xr(g),v={options:e._options,base_url:(a=(s=o?.server_url)!==null&&s!==void 0?s:e._baseURL)!==null&&a!==void 0?a:"",operation_id:"ListEnvironments",o_auth2_scopes:null,resolved_security:y,security_source:e._options.security,retry_config:o?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},w=e._createRequest(v,{security:y,method:"GET",baseURL:o?.server_url,path:p,headers:h,query:m,body:c,userAgent:e._options.user_agent,timeout_ms:o?.timeout_ms||e._options.timeout_ms||-1},o);if(!w.ok)return[w,{status:"invalid"}];const T=w.value,E=await e._do(T,{context:v,isErrorStatusCode:C=>mr({status:C},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!E.ok)return[E,{status:"request-error",request:T}];const k=E.value,[A]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(k,T);return A.ok?[A,{status:"complete",request:T,response:k}]:[A,{status:"complete",request:T,response:k}]}function JHe(e,t,r,n,o,i,s,a){return new fr(Ltn(e,t,r,n,o,i,s,a))}async function Ltn(e,t,r,n,o,i,s,a){var u,l,c;const p={environment:t,path:r,api_version:n,page_size:o,page_token:i,recursive:s},m=null,h={api_version:gt("api_version",(u=p.api_version)!==null&&u!==void 0?u:e._options.api_version,{explode:!1,charEncoding:"percent"}),environment:gt("environment",p.environment,{explode:!1,charEncoding:"percent"}),path:gt("path",p.path,{explode:!1,charEncoding:"percentExceptReserved"})},g=Tr("/{api_version}/environments/{environment}/files/{path}")(h),y=Bu({page_size:p.page_size,page_token:p.page_token,recursive:p.recursive}),v=new Headers(Ar({Accept:"application/json"})),w=await Ir(e._options.security),T=xr(w),E={options:e._options,base_url:(c=(l=a?.server_url)!==null&&l!==void 0?l:e._baseURL)!==null&&c!==void 0?c:"",operation_id:"GetEnvironmentFiles",o_auth2_scopes:null,resolved_security:T,security_source:e._options.security,retry_config:a?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:a?.retry_codes||["408","409","429","5XX"]},k=e._createRequest(E,{security:T,method:"GET",baseURL:a?.server_url,path:g,headers:v,query:y,body:m,userAgent:e._options.user_agent,timeout_ms:a?.timeout_ms||e._options.timeout_ms||-1},a);if(!k.ok)return[k,{status:"invalid"}];const A=k.value,C=await e._do(A,{context:E,isErrorStatusCode:P=>mr({status:P},["4XX","5XX"]),retryConfig:E.retry_config,retryCodes:E.retry_codes});if(!C.ok)return[C,{status:"request-error",request:A}];const R=C.value,[x]=await Cr(Lr(200),vt("4XX"),vt("5XX"))(R,A);return x.ok?[x,{status:"complete",request:A,response:R}]:[x,{status:"complete",request:A,response:R}]}function XHe(e,t,r,n,o,i,s,a,u,l,c){return new fr($tn(e,t,r,n,o,i,s,a,u,l,c))}async function $tn(e,t,r,n,o,i,s,a,u,l,c){var d,p,m;const g={environment:t,path:r,"X-Goog-Upload-Command":n,"X-Goog-Upload-Header-Content-Length":o,"X-Goog-Upload-Header-Content-Type":i,"X-Goog-Upload-Protocol":s,api_version:a,extract:u,overwrite:l},y=null,v={api_version:gt("api_version",(d=g.api_version)!==null&&d!==void 0?d:e._options.api_version,{explode:!1,charEncoding:"percent"}),environment:gt("environment",g.environment,{explode:!1,charEncoding:"percent"}),path:gt("path",g.path,{explode:!1,charEncoding:"percentExceptReserved"})},w=Tr("/upload/{api_version}/environments/{environment}/files/{path}")(v),T=Bu({extract:g.extract,overwrite:g.overwrite}),E=new Headers(Ar({Accept:"*/*","X-Goog-Upload-Command":gt("X-Goog-Upload-Command",g["X-Goog-Upload-Command"],{explode:!1,charEncoding:"none"}),"X-Goog-Upload-Header-Content-Length":gt("X-Goog-Upload-Header-Content-Length",g["X-Goog-Upload-Header-Content-Length"],{explode:!1,charEncoding:"none"}),"X-Goog-Upload-Header-Content-Type":gt("X-Goog-Upload-Header-Content-Type",g["X-Goog-Upload-Header-Content-Type"],{explode:!1,charEncoding:"none"}),"X-Goog-Upload-Protocol":gt("X-Goog-Upload-Protocol",g["X-Goog-Upload-Protocol"],{explode:!1,charEncoding:"none"})})),k=await Ir(e._options.security),A=xr(k),C={options:e._options,base_url:(m=(p=c?.server_url)!==null&&p!==void 0?p:e._baseURL)!==null&&m!==void 0?m:"",operation_id:"StartEnvironmentFileUpload",o_auth2_scopes:null,resolved_security:A,security_source:e._options.security,retry_config:c?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:c?.retry_codes||["408","409","429","5XX"]},R=e._createRequest(C,{security:A,method:"PUT",baseURL:c?.server_url,path:w,headers:E,query:T,body:y,userAgent:e._options.user_agent,timeout_ms:c?.timeout_ms||e._options.timeout_ms||-1},c);if(!R.ok)return[R,{status:"invalid"}];const x=R.value,P=await e._do(x,{context:C,isErrorStatusCode:N=>mr({status:N},["4XX","5XX"]),retryConfig:C.retry_config,retryCodes:C.retry_codes});if(!P.ok)return[P,{status:"request-error",request:x}];const D=P.value,L={httpMeta:{response:D,request:x}},[O]=await Cr(NHe(200,{hdrs:!0}),vt("4XX"),vt("5XX"))(D,x,{extraFields:L});return O.ok?[O,{status:"complete",request:x,response:D}]:[O,{status:"complete",request:x,response:D}]}function YHe(e,t,r,n){return new fr(Ftn(e,t,r,n))}async function Ftn(e,t,r,n){var o,i,s;const u={id:t,api_version:r},l=null,c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),interactionsId:gt("interactionsId",u.id,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/interactions/{interactionsId}/cancel")(c),p=new Headers(Ar({Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"cancelInteractionById",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"POST",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:A=>mr({status:A},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,E={httpMeta:{response:T,request:v}},[k]=await Cr(Lr(200),Rh("4XX",IJe),Rh("5XX",xJe))(T,v,{extraFields:E});return k.ok?[k,{status:"complete",request:v,response:T}]:[k,{status:"complete",request:v,response:T}]}function ZHe(e,t,r,n){return new fr(Utn(e,t,r,n))}async function Utn(e,t,r,n){var o,i,s,a;const u={body:t,api_version:r},l=u,c=Al("body",l.body,{explode:!0}),d={api_version:gt("api_version",(o=l.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"})},p=Tr("/{api_version}/interactions")(d),m=new Headers(Ar({"Content-Type":"application/json",Accept:!((i=u?.body)===null||i===void 0)&&i.stream?"text/event-stream":"application/json"})),h=await Ir(e._options.security),g=xr(h),y={options:e._options,base_url:(a=(s=n?.server_url)!==null&&s!==void 0?s:e._baseURL)!==null&&a!==void 0?a:"",operation_id:"CreateInteraction",o_auth2_scopes:null,resolved_security:g,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},v=e._createRequest(y,{security:g,method:"POST",baseURL:n?.server_url,path:p,headers:m,body:c,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!v.ok)return[v,{status:"invalid"}];const w=v.value,T=await e._do(w,{context:y,isErrorStatusCode:C=>mr({status:C},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:w}];const E=T.value,k={httpMeta:{response:E,request:w}},[A]=await Cr(Lr(200),OHe(200,{sentinel:"[DONE]",flattened:!0}),Rh("4XX",MJe),Rh("5XX",RJe))(E,w,{extraFields:k});return A.ok?[A,{status:"complete",request:w,response:E}]:[A,{status:"complete",request:w,response:E}]}function Btn(e,t,r,n){return new fr(ztn(e,t,r,n))}async function ztn(e,t,r,n){var o,i,s;const u={id:t,api_version:r},l=null,c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),interactionsId:gt("interactionsId",u.id,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/interactions/{interactionsId}")(c),p=new Headers(Ar({Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"deleteInteraction",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"DELETE",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:A=>mr({status:A},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,E={httpMeta:{response:T,request:v}},[k]=await Cr(NHe(200),Rh("4XX",DJe),Rh("5XX",PJe))(T,v,{extraFields:E});return k.ok?[k,{status:"complete",request:v,response:T}]:[k,{status:"complete",request:v,response:T}]}function QHe(e,t,r,n,o,i,s){return new fr(Gtn(e,t,r,n,o,i,s))}async function Gtn(e,t,r,n,o,i,s){var a,u,l;const c={id:t,api_version:r,include_input:n,last_event_id:o,stream:i},d=c,p=null,m={api_version:gt("api_version",(a=d.api_version)!==null&&a!==void 0?a:e._options.api_version,{explode:!1,charEncoding:"percent"}),interactionsId:gt("interactionsId",d.id,{explode:!1,charEncoding:"percent"})},h=Tr("/{api_version}/interactions/{interactionsId}")(m),g=Bu({include_input:d.include_input,last_event_id:d.last_event_id,stream:d.stream}),y=new Headers(Ar({Accept:c?.stream?"text/event-stream":"application/json"})),v=await Ir(e._options.security),w=xr(v),T={options:e._options,base_url:(l=(u=s?.server_url)!==null&&u!==void 0?u:e._baseURL)!==null&&l!==void 0?l:"",operation_id:"getInteractionById",o_auth2_scopes:null,resolved_security:w,security_source:e._options.security,retry_config:s?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:s?.retry_codes||["408","409","429","5XX"]},E=e._createRequest(T,{security:w,method:"GET",baseURL:s?.server_url,path:h,headers:y,query:g,body:p,userAgent:e._options.user_agent,timeout_ms:s?.timeout_ms||e._options.timeout_ms||-1},s);if(!E.ok)return[E,{status:"invalid"}];const k=E.value,A=await e._do(k,{context:T,isErrorStatusCode:P=>mr({status:P},["4XX","5XX"]),retryConfig:T.retry_config,retryCodes:T.retry_codes});if(!A.ok)return[A,{status:"request-error",request:k}];const C=A.value,R={httpMeta:{response:C,request:k}},[x]=await Cr(Lr(200),OHe(200,{sentinel:"[DONE]",flattened:!0}),Rh("4XX",NJe),Rh("5XX",OJe))(C,k,{extraFields:R});return x.ok?[x,{status:"complete",request:k,response:C}]:[x,{status:"complete",request:k,response:C}]}function eWe(e,t,r,n){return new fr(qtn(e,t,r,n))}async function qtn(e,t,r,n){var o,i,s;const u={body:t,api_version:r},l=Al("body",u.body,{explode:!0}),c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/triggers")(c),p=new Headers(Ar({"Content-Type":"application/json",Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"CreateTrigger",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"POST",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function tWe(e,t,r,n){return new fr(jtn(e,t,r,n))}async function jtn(e,t,r,n){var o,i,s;const u={id:t,api_version:r},l=null,c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:gt("id",u.id,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/triggers/{id}")(c),p=new Headers(Ar({Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"DeleteTrigger",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"DELETE",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function rWe(e,t,r,n){return new fr(Vtn(e,t,r,n))}async function Vtn(e,t,r,n){var o,i,s;const u={id:t,api_version:r},l=null,c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:gt("id",u.id,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/triggers/{id}")(c),p=new Headers(Ar({Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"GetTrigger",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"GET",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function nWe(e,t,r,n,o,i){return new fr(Htn(e,t,r,n,o,i))}async function Htn(e,t,r,n,o,i){var s,a,u;const c={trigger_id:t,api_version:r,page_size:n,page_token:o},d=null,p={api_version:gt("api_version",(s=c.api_version)!==null&&s!==void 0?s:e._options.api_version,{explode:!1,charEncoding:"percent"}),triggerId:gt("triggerId",c.trigger_id,{explode:!1,charEncoding:"percent"})},m=Tr("/{api_version}/triggers/{triggerId}/executions")(p),h=Bu({page_size:c.page_size,page_token:c.page_token}),g=new Headers(Ar({Accept:"application/json"})),y=await Ir(e._options.security),v=xr(y),w={options:e._options,base_url:(u=(a=i?.server_url)!==null&&a!==void 0?a:e._baseURL)!==null&&u!==void 0?u:"",operation_id:"ListTriggerExecutions",o_auth2_scopes:null,resolved_security:v,security_source:e._options.security,retry_config:i?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},T=e._createRequest(w,{security:v,method:"GET",baseURL:i?.server_url,path:m,headers:g,query:h,body:d,userAgent:e._options.user_agent,timeout_ms:i?.timeout_ms||e._options.timeout_ms||-1},i);if(!T.ok)return[T,{status:"invalid"}];const E=T.value,k=await e._do(E,{context:w,isErrorStatusCode:R=>mr({status:R},["4XX","5XX"]),retryConfig:w.retry_config,retryCodes:w.retry_codes});if(!k.ok)return[k,{status:"request-error",request:E}];const A=k.value,[C]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(A,E);return C.ok?[C,{status:"complete",request:E,response:A}]:[C,{status:"complete",request:E,response:A}]}function oWe(e,t,r,n,o,i){return new fr(Wtn(e,t,r,n,o,i))}async function Wtn(e,t,r,n,o,i){var s,a,u;const c={api_version:t,filter:r,page_size:n,page_token:o},d=null,p={api_version:gt("api_version",(s=c?.api_version)!==null&&s!==void 0?s:e._options.api_version,{explode:!1,charEncoding:"percent"})},m=Tr("/{api_version}/triggers")(p),h=Bu({filter:c?.filter,page_size:c?.page_size,page_token:c?.page_token}),g=new Headers(Ar({Accept:"application/json"})),y=await Ir(e._options.security),v=xr(y),w={options:e._options,base_url:(u=(a=i?.server_url)!==null&&a!==void 0?a:e._baseURL)!==null&&u!==void 0?u:"",operation_id:"ListTriggers",o_auth2_scopes:null,resolved_security:v,security_source:e._options.security,retry_config:i?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},T=e._createRequest(w,{security:v,method:"GET",baseURL:i?.server_url,path:m,headers:g,query:h,body:d,userAgent:e._options.user_agent,timeout_ms:i?.timeout_ms||e._options.timeout_ms||-1},i);if(!T.ok)return[T,{status:"invalid"}];const E=T.value,k=await e._do(E,{context:w,isErrorStatusCode:R=>mr({status:R},["4XX","5XX"]),retryConfig:w.retry_config,retryCodes:w.retry_codes});if(!k.ok)return[k,{status:"request-error",request:E}];const A=k.value,[C]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(A,E);return C.ok?[C,{status:"complete",request:E,response:A}]:[C,{status:"complete",request:E,response:A}]}function iWe(e,t,r,n){return new fr(Ktn(e,t,r,n))}async function Ktn(e,t,r,n){var o,i,s;const u={trigger_id:t,api_version:r},l=null,c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),triggerId:gt("triggerId",u.trigger_id,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/triggers/{triggerId}/executions")(c),p=new Headers(Ar({Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"RunTrigger",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"POST",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function sWe(e,t,r,n,o){return new fr(Jtn(e,t,r,n,o))}async function Jtn(e,t,r,n,o){var i,s,a;const l={id:t,body:r,api_version:n},c=Al("body",l.body,{explode:!0}),d={api_version:gt("api_version",(i=l.api_version)!==null&&i!==void 0?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:gt("id",l.id,{explode:!1,charEncoding:"percent"})},p=Tr("/{api_version}/triggers/{id}")(d),m=new Headers(Ar({"Content-Type":"application/json",Accept:"application/json"})),h=await Ir(e._options.security),g=xr(h),y={options:e._options,base_url:(a=(s=o?.server_url)!==null&&s!==void 0?s:e._baseURL)!==null&&a!==void 0?a:"",operation_id:"UpdateTrigger",o_auth2_scopes:null,resolved_security:g,security_source:e._options.security,retry_config:o?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},v=e._createRequest(y,{security:g,method:"PATCH",baseURL:o?.server_url,path:p,headers:m,body:c,userAgent:e._options.user_agent,timeout_ms:o?.timeout_ms||e._options.timeout_ms||-1},o);if(!v.ok)return[v,{status:"invalid"}];const w=v.value,T=await e._do(w,{context:y,isErrorStatusCode:A=>mr({status:A},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:w}];const E=T.value,[k]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(E,w);return k.ok?[k,{status:"complete",request:w,response:E}]:[k,{status:"complete",request:w,response:E}]}function aWe(e,t,r,n){return new fr(Xtn(e,t,r,n))}async function Xtn(e,t,r,n){var o,i,s;const u={body:t,api_version:r},l=Al("body",u.body,{explode:!0}),c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/voices")(c),p=new Headers(Ar({"Content-Type":"application/json",Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"CreateVoice",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"POST",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function uWe(e,t,r,n){return new fr(Ytn(e,t,r,n))}async function Ytn(e,t,r,n){var o,i,s;const u={id:t,api_version:r},l=null,c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),voicesId:gt("voicesId",u.id,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/voices/{voicesId}")(c),p=new Headers(Ar({Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"DeleteVoice",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"DELETE",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function lWe(e,t,r,n){return new fr(Ztn(e,t,r,n))}async function Ztn(e,t,r,n){var o,i,s;const u={id:t,api_version:r},l=null,c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),voicesId:gt("voicesId",u.id,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/voices/{voicesId}")(c),p=new Headers(Ar({Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"GetVoice",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"GET",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function cWe(e,t,r,n,o,i,s,a,u,l,c,d,p,m){return new fr(Qtn(e,t,r,n,o,i,s,a,u,l,c,d,p,m))}async function Qtn(e,t,r,n,o,i,s,a,u,l,c,d,p,m){var h,g,y;const w={api_version:t,accent:r,contexts:n,gender:o,language_code:i,page_size:s,page_token:a,persona:u,pitch:l,region_code:c,search:d,type:p},T=null,E={api_version:gt("api_version",(h=w?.api_version)!==null&&h!==void 0?h:e._options.api_version,{explode:!1,charEncoding:"percent"})},k=Tr("/{api_version}/voices")(E),A=Bu({accent:w?.accent,context:w?.contexts,gender:w?.gender,language_code:w?.language_code,page_size:w?.page_size,page_token:w?.page_token,persona:w?.persona,pitch:w?.pitch,region_code:w?.region_code,search:w?.search,type:w?.type}),C=new Headers(Ar({Accept:"application/json"})),R=await Ir(e._options.security),x=xr(R),P={options:e._options,base_url:(y=(g=m?.server_url)!==null&&g!==void 0?g:e._baseURL)!==null&&y!==void 0?y:"",operation_id:"ListVoices",o_auth2_scopes:null,resolved_security:x,security_source:e._options.security,retry_config:m?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:m?.retry_codes||["408","409","429","5XX"]},D=e._createRequest(P,{security:x,method:"GET",baseURL:m?.server_url,path:k,headers:C,query:A,body:T,userAgent:e._options.user_agent,timeout_ms:m?.timeout_ms||e._options.timeout_ms||-1},m);if(!D.ok)return[D,{status:"invalid"}];const L=D.value,O=await e._do(L,{context:P,isErrorStatusCode:$=>mr({status:$},["4XX","5XX"]),retryConfig:P.retry_config,retryCodes:P.retry_codes});if(!O.ok)return[O,{status:"request-error",request:L}];const N=O.value,[U]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(N,L);return U.ok?[U,{status:"complete",request:L,response:N}]:[U,{status:"complete",request:L,response:N}]}function dWe(e,t,r,n){return new fr(ern(e,t,r,n))}async function ern(e,t,r,n){var o,i,s;const u={body:t,api_version:r},l=Al("body",u.body,{explode:!0}),c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/webhooks")(c),p=new Headers(Ar({"Content-Type":"application/json",Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"CreateWebhook",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"POST",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function pWe(e,t,r,n){return new fr(trn(e,t,r,n))}async function trn(e,t,r,n){var o,i,s;const u={id:t,api_version:r},l=null,c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:gt("id",u.id,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/webhooks/{id}")(c),p=new Headers(Ar({Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"DeleteWebhook",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"DELETE",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function mWe(e,t,r,n){return new fr(rrn(e,t,r,n))}async function rrn(e,t,r,n){var o,i,s;const u={id:t,api_version:r},l=null,c={api_version:gt("api_version",(o=u.api_version)!==null&&o!==void 0?o:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:gt("id",u.id,{explode:!1,charEncoding:"percent"})},d=Tr("/{api_version}/webhooks/{id}")(c),p=new Headers(Ar({Accept:"application/json"})),m=await Ir(e._options.security),h=xr(m),g={options:e._options,base_url:(s=(i=n?.server_url)!==null&&i!==void 0?i:e._baseURL)!==null&&s!==void 0?s:"",operation_id:"GetWebhook",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:n?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:n?.retry_codes||["408","409","429","5XX"]},y=e._createRequest(g,{security:h,method:"GET",baseURL:n?.server_url,path:d,headers:p,body:l,userAgent:e._options.user_agent,timeout_ms:n?.timeout_ms||e._options.timeout_ms||-1},n);if(!y.ok)return[y,{status:"invalid"}];const v=y.value,w=await e._do(v,{context:g,isErrorStatusCode:k=>mr({status:k},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!w.ok)return[w,{status:"request-error",request:v}];const T=w.value,[E]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(T,v);return E.ok?[E,{status:"complete",request:v,response:T}]:[E,{status:"complete",request:v,response:T}]}function hWe(e,t,r,n,o){return new fr(nrn(e,t,r,n,o))}async function nrn(e,t,r,n,o){var i,s,a;const l={api_version:t,page_size:r,page_token:n},c=null,d={api_version:gt("api_version",(i=l?.api_version)!==null&&i!==void 0?i:e._options.api_version,{explode:!1,charEncoding:"percent"})},p=Tr("/{api_version}/webhooks")(d),m=Bu({page_size:l?.page_size,page_token:l?.page_token}),h=new Headers(Ar({Accept:"application/json"})),g=await Ir(e._options.security),y=xr(g),v={options:e._options,base_url:(a=(s=o?.server_url)!==null&&s!==void 0?s:e._baseURL)!==null&&a!==void 0?a:"",operation_id:"ListWebhooks",o_auth2_scopes:null,resolved_security:y,security_source:e._options.security,retry_config:o?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},w=e._createRequest(v,{security:y,method:"GET",baseURL:o?.server_url,path:p,headers:h,query:m,body:c,userAgent:e._options.user_agent,timeout_ms:o?.timeout_ms||e._options.timeout_ms||-1},o);if(!w.ok)return[w,{status:"invalid"}];const T=w.value,E=await e._do(T,{context:v,isErrorStatusCode:C=>mr({status:C},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!E.ok)return[E,{status:"request-error",request:T}];const k=E.value,[A]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(k,T);return A.ok?[A,{status:"complete",request:T,response:k}]:[A,{status:"complete",request:T,response:k}]}function fWe(e,t,r,n,o){return new fr(orn(e,t,r,n,o))}async function orn(e,t,r,n,o){var i,s,a;const l={id:t,api_version:r,body:n},c=Al("body",l.body,{explode:!0}),d={api_version:gt("api_version",(i=l.api_version)!==null&&i!==void 0?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:gt("id",l.id,{explode:!1,charEncoding:"percent"})},p=Tr("/{api_version}/webhooks/{id}:ping")(d),m=new Headers(Ar({"Content-Type":"application/json",Accept:"application/json"})),h=await Ir(e._options.security),g=xr(h),y={options:e._options,base_url:(a=(s=o?.server_url)!==null&&s!==void 0?s:e._baseURL)!==null&&a!==void 0?a:"",operation_id:"PingWebhook",o_auth2_scopes:null,resolved_security:g,security_source:e._options.security,retry_config:o?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},v=e._createRequest(y,{security:g,method:"POST",baseURL:o?.server_url,path:p,headers:m,body:c,userAgent:e._options.user_agent,timeout_ms:o?.timeout_ms||e._options.timeout_ms||-1},o);if(!v.ok)return[v,{status:"invalid"}];const w=v.value,T=await e._do(w,{context:y,isErrorStatusCode:A=>mr({status:A},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:w}];const E=T.value,[k]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(E,w);return k.ok?[k,{status:"complete",request:w,response:E}]:[k,{status:"complete",request:w,response:E}]}function gWe(e,t,r,n,o){return new fr(irn(e,t,r,n,o))}async function irn(e,t,r,n,o){var i,s,a;const l={id:t,body:r,api_version:n},c=Al("body",l.body,{explode:!0}),d={api_version:gt("api_version",(i=l.api_version)!==null&&i!==void 0?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:gt("id",l.id,{explode:!1,charEncoding:"percent"})},p=Tr("/{api_version}/webhooks/{id}:rotateSigningSecret")(d),m=new Headers(Ar({"Content-Type":"application/json",Accept:"application/json"})),h=await Ir(e._options.security),g=xr(h),y={options:e._options,base_url:(a=(s=o?.server_url)!==null&&s!==void 0?s:e._baseURL)!==null&&a!==void 0?a:"",operation_id:"RotateSigningSecret",o_auth2_scopes:null,resolved_security:g,security_source:e._options.security,retry_config:o?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},v=e._createRequest(y,{security:g,method:"POST",baseURL:o?.server_url,path:p,headers:m,body:c,userAgent:e._options.user_agent,timeout_ms:o?.timeout_ms||e._options.timeout_ms||-1},o);if(!v.ok)return[v,{status:"invalid"}];const w=v.value,T=await e._do(w,{context:y,isErrorStatusCode:A=>mr({status:A},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!T.ok)return[T,{status:"request-error",request:w}];const E=T.value,[k]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(E,w);return k.ok?[k,{status:"complete",request:w,response:E}]:[k,{status:"complete",request:w,response:E}]}function yWe(e,t,r,n,o,i){return new fr(srn(e,t,r,n,o,i))}async function srn(e,t,r,n,o,i){var s,a,u;const c={id:t,body:r,api_version:n,update_mask:o},d=Al("body",c.body,{explode:!0}),p={api_version:gt("api_version",(s=c.api_version)!==null&&s!==void 0?s:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:gt("id",c.id,{explode:!1,charEncoding:"percent"})},m=Tr("/{api_version}/webhooks/{id}")(p),h=Bu({update_mask:c.update_mask}),g=new Headers(Ar({"Content-Type":"application/json",Accept:"application/json"})),y=await Ir(e._options.security),v=xr(y),w={options:e._options,base_url:(u=(a=i?.server_url)!==null&&a!==void 0?a:e._baseURL)!==null&&u!==void 0?u:"",operation_id:"UpdateWebhook",o_auth2_scopes:null,resolved_security:v,security_source:e._options.security,retry_config:i?.retries||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},T=e._createRequest(w,{security:v,method:"PATCH",baseURL:i?.server_url,path:m,headers:g,query:h,body:d,userAgent:e._options.user_agent,timeout_ms:i?.timeout_ms||e._options.timeout_ms||-1},i);if(!T.ok)return[T,{status:"invalid"}];const E=T.value,k=await e._do(E,{context:w,isErrorStatusCode:R=>mr({status:R},["4XX","5XX"]),retryConfig:w.retry_config,retryCodes:w.retry_codes});if(!k.ok)return[k,{status:"request-error",request:E}];const A=k.value,[C]=await Cr(vt("4XX"),vt("5XX"),Lr("default"))(A,E);return C.ok?[C,{status:"complete",request:E,response:A}]:[C,{status:"complete",request:E,response:A}]}function arn(e){const t=e.getBaseUrl();if(!t)throw new Error("Base URL must be set.");return t.replace(/\/+$/,"")}function urn(e){const t=lrn(e.getApiVersion()),r=e.getProject(),n=e.getLocation();return e.isVertexAI()&&t&&r&&n?`${t}/projects/${encodeURIComponent(r)}/locations/${encodeURIComponent(n)}`:t}function Za(e,t={}){var r,n,o,i,s,a,u,l,c,d;const{timeout:p}=t,m=hi(t,["timeout"]),h=m.http_client||(r=e.getFetch)===null||r===void 0?void 0:r.call(e),g=(n=m.http_client)!==null&&n!==void 0?n:h?new lY({fetcher:h}):void 0,y=(i=(o=m.timeout_ms)!==null&&o!==void 0?o:p)!==null&&i!==void 0?i:(s=e.getTimeout)===null||s===void 0?void 0:s.call(e);return new BJe(Object.assign(Object.assign({},m),{http_client:g,api_version:(a=m.api_version)!==null&&a!==void 0?a:urn(e),security:(u=m.security)!==null&&u!==void 0?u:new XKe({defaultHeaders:Object.assign(Object.assign({},(l=e.getDefaultHeaders)===null||l===void 0?void 0:l.call(e)),(c=e.getHeaders)===null||c===void 0?void 0:c.call(e)),getAuthHeaders:w=>e.getAuthHeaders(w)}),server_url:(d=m.server_url)!==null&&d!==void 0?d:arn(e),timeout_ms:y}))}function lrn(e){return e.replace(/^\/+|\/+$/g,"")}function hr(e,t=!1){var r,n,o,i;if(!e&&!t)return;const s=e??{},{timeout:a,maxRetries:u,defaultBaseURL:l,query:c,body:d,fetchOptions:p}=s,m=hi(s,["timeout","maxRetries","defaultBaseURL","query","body","fetchOptions"]),h=Object.assign({},m);hO(c)?h.extra_query=c:vWe("query",c),hO(d)?h.extra_body=d:vWe("body",d);const g=(r=m.fetch_options)!==null&&r!==void 0?r:p;g&&(h.fetch_options=g);const y=(n=m.server_url)!==null&&n!==void 0?n:l;y&&(h.server_url=y);const v=(o=m.timeout_ms)!==null&&o!==void 0?o:a;if(v!==void 0&&(h.timeout_ms=v),u!==void 0&&(h.retries={strategy:"attempt-count-backoff",retryConnectionErrors:!0,maxRetries:u}),t){const w=new Headers((i=h.headers)!==null&&i!==void 0?i:g?.headers);w.set("Accept","text/event-stream"),h.headers=w}return h}function vWe(e,t){t!=null&&console.warn(`GoogleGenAI.interactions: request option ${e} is not supported by the Google GenAI interactions bridge and will be ignored.`)}async function $r(e){const[t,r]=await e.$inspect();if(!t.ok)throw i0(t.error);return crn(t.value,r)}async function lJ(e){try{return await e()}catch(t){throw i0(t)}}function wWe(e){const t=e;return new Proxy(e,{get(r,n){if(n!==Symbol.asyncIterator){const o=Reflect.get(r,n,r);return typeof o=="function"?o.bind(r):o}return function(){const i=t[Symbol.asyncIterator]();return{async next(...s){try{return await i.next(...s)}catch(a){throw i0(a)}},async return(s){if(!i.return)return{done:!0,value:s};try{return await i.return(s)}catch(a){throw i0(a)}},async throw(s){if(!i.throw)throw i0(s);try{return await i.throw(s)}catch(a){throw i0(a)}},[Symbol.asyncIterator](){return this}}}}})}function crn(e,t){return!hO(e)||t.status!=="complete"?e:Object.assign(Object.assign({},e),{sdkHttpResponse:drn(t.response,e)})}function drn(e,t){const r={};for(const[n,o]of e.headers.entries())r[n]=o;return{headers:r,responseInternal:e,json:async()=>t}}function cJ(e){const t=prn(e);return t?hrn(t):e}function prn(e){if(hO(e)){if(Array.isArray(e.steps))return e;if(mrn(e)){const t=e.outputs;if(Array.isArray(t)){const{outputs:r}=e,n=hi(e,["outputs"]);return Object.assign(Object.assign({},n),{steps:[{type:"model_output",content:t}]})}}return Object.assign(Object.assign({},e),{steps:[]})}}function mrn(e){const t=e.model;return typeof t=="string"&&zJe.has(t)}function hO(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hrn(e){var t,r;const n=frn(e),o=(t=n.steps)!==null&&t!==void 0?t:[],i=[];let s=!1;e:for(let d=o.length-1;d>=0;d--){const p=o[d];if(p.type==="user_input")break;if(p.type==="thought")continue;if(p.type!=="model_output"){if(s)break;continue}if(!p.content)continue;const m=p.content;for(let h=m.length-1;h>=0;h--){const g=m[h];if(g.type==="text")s=!0,i.push((r=g.text)!==null&&r!==void 0?r:"");else if(s)break e}}let a,u,l;for(let d=o.length-1;d>=0;d--){const p=o[d];if(p.type==="user_input")break;if(p.type==="model_output"&&p.content)for(let m=p.content.length-1;m>=0;m--){const h=p.content[m];h.type==="image"&&!a&&(a=h),h.type==="audio"&&!u&&(u=h),h.type==="video"&&!l&&(l=h)}}const c=i.reverse().join("");return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},n),c&&{output_text:c}),a?{output_image:a}:{}),u?{output_audio:u}:{}),l?{output_video:l}:{})}function frn(e){return Object.assign(Object.assign({},e),{created:bWe(e.created),updated:bWe(e.updated)})}function bWe(e){return e instanceof Date?e.toISOString():e}function grn(e){const t=e.slice(e.lastIndexOf(".")+1).toLowerCase();return{txt:"text/plain",json:"application/json",js:"text/javascript",mjs:"text/javascript",ts:"text/plain",py:"text/x-python",html:"text/html",htm:"text/html",css:"text/css",csv:"text/csv",xml:"application/xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",pdf:"application/pdf",zip:"application/zip",tar:"application/x-tar",gz:"application/gzip"}[t]}function yrn(e){const t={},r=b(e,["apiKey"]);if(r!=null&&_(t,["apiKey"],r),b(e,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function TWe(e){const t={},r=b(e,["parts"]);if(r!=null){let o=r;Array.isArray(o)&&(o=o.map(i=>$rn(i))),_(t,["parts"],o)}const n=b(e,["role"]);return n!=null&&_(t,["role"],n),t}function _We(e){const t={},r=b(e,["parts"]);if(r!=null){let o=r;Array.isArray(o)&&(o=o.map(i=>Frn(i))),_(t,["parts"],o)}const n=b(e,["role"]);return n!=null&&_(t,["role"],n),t}function vrn(e){const t={},r=b(e,["args"]);r!=null&&_(t,["args"],r);const n=b(e,["id"]);n!=null&&_(t,["id"],n);const o=b(e,["name"]);if(o!=null&&_(t,["name"],o),b(e,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function wrn(e){const t={},r=b(e,["modelSelectionConfig"]);r!=null&&_(t,["modelConfig"],r);const n=b(e,["responseJsonSchema"]);n!=null&&_(t,["responseJsonSchema"],n);const o=b(e,["audioTranscriptionConfig"]);o!=null&&_(t,["audioTranscriptionConfig"],o);const i=b(e,["audioTimestamp"]);i!=null&&_(t,["audioTimestamp"],i);const s=b(e,["candidateCount"]);s!=null&&_(t,["candidateCount"],s);const a=b(e,["enableAffectiveDialog"]);a!=null&&_(t,["enableAffectiveDialog"],a);const u=b(e,["frequencyPenalty"]);u!=null&&_(t,["frequencyPenalty"],u);const l=b(e,["logprobs"]);l!=null&&_(t,["logprobs"],l);const c=b(e,["maxOutputTokens"]);c!=null&&_(t,["maxOutputTokens"],c);const d=b(e,["mediaResolution"]);d!=null&&_(t,["mediaResolution"],d);const p=b(e,["presencePenalty"]);p!=null&&_(t,["presencePenalty"],p);const m=b(e,["responseFormat"]);if(m!=null){let D=m;Array.isArray(D)&&(D=D.map(L=>L)),_(t,["responseFormat"],D)}const h=b(e,["responseLogprobs"]);h!=null&&_(t,["responseLogprobs"],h);const g=b(e,["responseMimeType"]);g!=null&&_(t,["responseMimeType"],g);const y=b(e,["responseModalities"]);y!=null&&_(t,["responseModalities"],y);const v=b(e,["responseSchema"]);v!=null&&_(t,["responseSchema"],v);const w=b(e,["routingConfig"]);w!=null&&_(t,["routingConfig"],w);const T=b(e,["seed"]);T!=null&&_(t,["seed"],T);const E=b(e,["speechConfig"]);E!=null&&_(t,["speechConfig"],EWe(E));const k=b(e,["stopSequences"]);k!=null&&_(t,["stopSequences"],k);const A=b(e,["temperature"]);A!=null&&_(t,["temperature"],A);const C=b(e,["thinkingConfig"]);C!=null&&_(t,["thinkingConfig"],C);const R=b(e,["topK"]);R!=null&&_(t,["topK"],R);const x=b(e,["topP"]);if(x!=null&&_(t,["topP"],x),b(e,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const P=b(e,["translationConfig"]);return P!=null&&_(t,["translationConfig"],P),t}function brn(e){const t={},r=b(e,["authConfig"]);r!=null&&_(t,["authConfig"],yrn(r));const n=b(e,["enableWidget"]);if(n!=null&&_(t,["enableWidget"],n),b(e,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function Trn(e){const t={};if(b(e,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const r=b(e,["searchTypes"]);r!=null&&_(t,["searchTypes"],r);const n=b(e,["timeRangeFilter"]);return n!=null&&_(t,["timeRangeFilter"],n),t}function _rn(e){const t={},r=b(e,["systemInstruction"]);r!=null&&_(t,["systemInstruction"],TWe(Ii(r)));const n=b(e,["tools"]);return n!=null&&_(t,["tools"],Srn(n)),t}function Ern(e){const t={},r=b(e,["systemInstruction"]);r!=null&&_(t,["systemInstruction"],_We(Ii(r)));const n=b(e,["tools"]);return n!=null&&_(t,["tools"],krn(n)),t}function Srn(e){const t={},r=b(e,["tools"]);if(r!=null){let n=xh(r);Array.isArray(n)&&(n=n.map(o=>SWe(Ch(o)))),_(t,["tools"],n)}return t}function krn(e){const t={},r=b(e,["tools"]);if(r!=null){let n=xh(r);Array.isArray(n)&&(n=n.map(o=>kWe(Ch(o)))),_(t,["tools"],n)}return t}function Arn(e,t){const r={},n=b(e,["generationConfig"]);t!==void 0&&n!=null&&_(t,["setup","generationConfig"],n);const o=b(e,["responseModalities"]);t!==void 0&&o!=null&&_(t,["setup","generationConfig","responseModalities"],o);const i=b(e,["temperature"]);t!==void 0&&i!=null&&_(t,["setup","generationConfig","temperature"],i);const s=b(e,["topP"]);t!==void 0&&s!=null&&_(t,["setup","generationConfig","topP"],s);const a=b(e,["topK"]);t!==void 0&&a!=null&&_(t,["setup","generationConfig","topK"],a);const u=b(e,["maxOutputTokens"]);t!==void 0&&u!=null&&_(t,["setup","generationConfig","maxOutputTokens"],u);const l=b(e,["mediaResolution"]);t!==void 0&&l!=null&&_(t,["setup","generationConfig","mediaResolution"],l);const c=b(e,["seed"]);t!==void 0&&c!=null&&_(t,["setup","generationConfig","seed"],c);const d=b(e,["speechConfig"]);t!==void 0&&d!=null&&_(t,["setup","generationConfig","speechConfig"],iJ(d));const p=b(e,["thinkingConfig"]);t!==void 0&&p!=null&&_(t,["setup","generationConfig","thinkingConfig"],p);const m=b(e,["enableAffectiveDialog"]);t!==void 0&&m!=null&&_(t,["setup","generationConfig","enableAffectiveDialog"],m);const h=b(e,["systemInstruction"]);t!==void 0&&h!=null&&_(t,["setup","systemInstruction"],TWe(Ii(h)));const g=b(e,["tools"]);if(t!==void 0&&g!=null){let P=xh(g);Array.isArray(P)&&(P=P.map(D=>SWe(Ch(D)))),_(t,["setup","tools"],P)}const y=b(e,["sessionResumption"]);t!==void 0&&y!=null&&_(t,["setup","sessionResumption"],zrn(y));const v=b(e,["inputAudioTranscription"]);t!==void 0&&v!=null&&_(t,["setup","inputAudioTranscription"],v);const w=b(e,["outputAudioTranscription"]);t!==void 0&&w!=null&&_(t,["setup","outputAudioTranscription"],w);const T=b(e,["realtimeInputConfig"]);t!==void 0&&T!=null&&_(t,["setup","realtimeInputConfig"],T);const E=b(e,["contextWindowCompression"]);t!==void 0&&E!=null&&_(t,["setup","contextWindowCompression"],E);const k=b(e,["proactivity"]);if(t!==void 0&&k!=null&&_(t,["setup","proactivity"],k),b(e,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const A=b(e,["avatarConfig"]);t!==void 0&&A!=null&&_(t,["setup","avatarConfig"],A);const C=b(e,["safetySettings"]);if(t!==void 0&&C!=null){let P=C;Array.isArray(P)&&(P=P.map(D=>Brn(D))),_(t,["setup","safetySettings"],P)}const R=b(e,["translationConfig"]);t!==void 0&&R!=null&&_(t,["setup","generationConfig","translationConfig"],R);const x=b(e,["labels"]);return t!==void 0&&x!=null&&_(t,["setup","labels"],x),r}function Crn(e,t){const r={},n=b(e,["generationConfig"]);t!==void 0&&n!=null&&_(t,["setup","generationConfig"],wrn(n));const o=b(e,["responseModalities"]);t!==void 0&&o!=null&&_(t,["setup","generationConfig","responseModalities"],o);const i=b(e,["temperature"]);t!==void 0&&i!=null&&_(t,["setup","generationConfig","temperature"],i);const s=b(e,["topP"]);t!==void 0&&s!=null&&_(t,["setup","generationConfig","topP"],s);const a=b(e,["topK"]);t!==void 0&&a!=null&&_(t,["setup","generationConfig","topK"],a);const u=b(e,["maxOutputTokens"]);t!==void 0&&u!=null&&_(t,["setup","generationConfig","maxOutputTokens"],u);const l=b(e,["mediaResolution"]);t!==void 0&&l!=null&&_(t,["setup","generationConfig","mediaResolution"],l);const c=b(e,["seed"]);t!==void 0&&c!=null&&_(t,["setup","generationConfig","seed"],c);const d=b(e,["speechConfig"]);t!==void 0&&d!=null&&_(t,["setup","generationConfig","speechConfig"],EWe(iJ(d)));const p=b(e,["thinkingConfig"]);t!==void 0&&p!=null&&_(t,["setup","generationConfig","thinkingConfig"],p);const m=b(e,["enableAffectiveDialog"]);t!==void 0&&m!=null&&_(t,["setup","generationConfig","enableAffectiveDialog"],m);const h=b(e,["systemInstruction"]);t!==void 0&&h!=null&&_(t,["setup","systemInstruction"],_We(Ii(h)));const g=b(e,["tools"]);if(t!==void 0&&g!=null){let D=xh(g);Array.isArray(D)&&(D=D.map(L=>kWe(Ch(L)))),_(t,["setup","tools"],D)}const y=b(e,["sessionResumption"]);t!==void 0&&y!=null&&_(t,["setup","sessionResumption"],y);const v=b(e,["inputAudioTranscription"]);t!==void 0&&v!=null&&_(t,["setup","inputAudioTranscription"],v);const w=b(e,["outputAudioTranscription"]);t!==void 0&&w!=null&&_(t,["setup","outputAudioTranscription"],w);const T=b(e,["realtimeInputConfig"]);t!==void 0&&T!=null&&_(t,["setup","realtimeInputConfig"],T);const E=b(e,["contextWindowCompression"]);t!==void 0&&E!=null&&_(t,["setup","contextWindowCompression"],E);const k=b(e,["proactivity"]);t!==void 0&&k!=null&&_(t,["setup","proactivity"],k);const A=b(e,["explicitVadSignal"]);t!==void 0&&A!=null&&_(t,["setup","explicitVadSignal"],A);const C=b(e,["avatarConfig"]);t!==void 0&&C!=null&&_(t,["setup","avatarConfig"],C);const R=b(e,["safetySettings"]);if(t!==void 0&&R!=null){let D=R;Array.isArray(D)&&(D=D.map(L=>L)),_(t,["setup","safetySettings"],D)}const x=b(e,["translationConfig"]);t!==void 0&&x!=null&&_(t,["setup","generationConfig","translationConfig"],x);const P=b(e,["labels"]);return t!==void 0&&P!=null&&_(t,["setup","labels"],P),r}function xrn(e,t){const r={},n=b(t,["model"]);n!=null&&_(r,["setup","model"],Qr(e,n));const o=b(t,["config"]);return o!=null&&_(r,["config"],Arn(o,r)),r}function Irn(e,t){const r={},n=b(t,["model"]);n!=null&&_(r,["setup","model"],Qr(e,n));const o=b(t,["config"]);return o!=null&&_(r,["config"],Crn(o,r)),r}function Rrn(e){const t={},r=b(e,["musicGenerationConfig"]);return r!=null&&_(t,["musicGenerationConfig"],r),t}function Mrn(e){const t={},r=b(e,["weightedPrompts"]);if(r!=null){let n=r;Array.isArray(n)&&(n=n.map(o=>o)),_(t,["weightedPrompts"],n)}return t}function Prn(e){const t={},r=b(e,["media"]);if(r!=null){let l=jVe(r);Array.isArray(l)&&(l=l.map(c=>c)),_(t,["mediaChunks"],l)}const n=b(e,["audio"]);n!=null&&_(t,["audio"],HVe(n));const o=b(e,["audioStreamEnd"]);o!=null&&_(t,["audioStreamEnd"],o);const i=b(e,["video"]);i!=null&&_(t,["video"],VVe(i));const s=b(e,["text"]);s!=null&&_(t,["text"],s);const a=b(e,["activityStart"]);a!=null&&_(t,["activityStart"],a);const u=b(e,["activityEnd"]);return u!=null&&_(t,["activityEnd"],u),t}function Drn(e){const t={},r=b(e,["media"]);if(r!=null){let l=jVe(r);Array.isArray(l)&&(l=l.map(c=>c)),_(t,["mediaChunks"],l)}const n=b(e,["audio"]);n!=null&&_(t,["audio"],HVe(n));const o=b(e,["audioStreamEnd"]);o!=null&&_(t,["audioStreamEnd"],o);const i=b(e,["video"]);i!=null&&_(t,["video"],VVe(i));const s=b(e,["text"]);s!=null&&_(t,["text"],s);const a=b(e,["activityStart"]);a!=null&&_(t,["activityStart"],a);const u=b(e,["activityEnd"]);return u!=null&&_(t,["activityEnd"],u),t}function Orn(e){const t={},r=b(e,["setupComplete"]);r!=null&&_(t,["setupComplete"],r);const n=b(e,["serverContent"]);n!=null&&_(t,["serverContent"],n);const o=b(e,["toolCall"]);o!=null&&_(t,["toolCall"],o);const i=b(e,["toolCallCancellation"]);i!=null&&_(t,["toolCallCancellation"],i);const s=b(e,["usageMetadata"]);s!=null&&_(t,["usageMetadata"],qrn(s));const a=b(e,["goAway"]);a!=null&&_(t,["goAway"],a);const u=b(e,["sessionResumptionUpdate"]);u!=null&&_(t,["sessionResumptionUpdate"],u);const l=b(e,["voiceActivityDetectionSignal"]);l!=null&&_(t,["voiceActivityDetectionSignal"],l);const c=b(e,["voiceActivity"]);return c!=null&&_(t,["voiceActivity"],jrn(c)),t}function Nrn(e){const t={};if(b(e,["name"])!==void 0)throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(b(e,["streamableHttpTransport"])!==void 0)throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}function Lrn(e){const t={},r=b(e,["speakerVoiceConfigs"]);if(r!=null){let n=r;Array.isArray(n)&&(n=n.map(o=>Grn(o))),_(t,["speakerVoiceConfigs"],n)}return t}function $rn(e){const t={},r=b(e,["mediaResolution"]);r!=null&&_(t,["mediaResolution"],r);const n=b(e,["toolCall"]);n!=null&&_(t,["toolCall"],n);const o=b(e,["toolResponse"]);o!=null&&_(t,["toolResponse"],o);const i=b(e,["audioTranscription"]);i!=null&&_(t,["audioTranscription"],i);const s=b(e,["codeExecutionResult"]);s!=null&&_(t,["codeExecutionResult"],s);const a=b(e,["executableCode"]);a!=null&&_(t,["executableCode"],a);const u=b(e,["fileData"]);u!=null&&_(t,["fileData"],u);const l=b(e,["functionCall"]);l!=null&&_(t,["functionCall"],vrn(l));const c=b(e,["functionResponse"]);c!=null&&_(t,["functionResponse"],c);const d=b(e,["inlineData"]);d!=null&&_(t,["inlineData"],d);const p=b(e,["text"]);p!=null&&_(t,["text"],p);const m=b(e,["thought"]);m!=null&&_(t,["thought"],m);const h=b(e,["thoughtSignature"]);h!=null&&_(t,["thoughtSignature"],h);const g=b(e,["videoMetadata"]);g!=null&&_(t,["videoMetadata"],g);const y=b(e,["partMetadata"]);y!=null&&_(t,["partMetadata"],y);const v=b(e,["mediaProcessing"]);v!=null&&_(t,["mediaProcessing"],v);const w=b(e,["speechMetadata"]);return w!=null&&_(t,["speechMetadata"],w),t}function Frn(e){const t={},r=b(e,["mediaResolution"]);if(r!=null&&_(t,["mediaResolution"],r),b(e,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(b(e,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const n=b(e,["audioTranscription"]);n!=null&&_(t,["audioTranscription"],n);const o=b(e,["codeExecutionResult"]);o!=null&&_(t,["codeExecutionResult"],o);const i=b(e,["executableCode"]);i!=null&&_(t,["executableCode"],i);const s=b(e,["fileData"]);s!=null&&_(t,["fileData"],s);const a=b(e,["functionCall"]);a!=null&&_(t,["functionCall"],a);const u=b(e,["functionResponse"]);u!=null&&_(t,["functionResponse"],u);const l=b(e,["inlineData"]);l!=null&&_(t,["inlineData"],l);const c=b(e,["text"]);c!=null&&_(t,["text"],c);const d=b(e,["thought"]);d!=null&&_(t,["thought"],d);const p=b(e,["thoughtSignature"]);p!=null&&_(t,["thoughtSignature"],p);const m=b(e,["videoMetadata"]);if(m!=null&&_(t,["videoMetadata"],m),b(e,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const h=b(e,["mediaProcessing"]);h!=null&&_(t,["mediaProcessing"],h);const g=b(e,["speechMetadata"]);return g!=null&&_(t,["speechMetadata"],g),t}function Urn(e){const t={},r=b(e,["mimeType"]);r!=null&&_(t,["mimeType"],r);const n=b(e,["voiceSampleAudio"]);if(n!=null&&_(t,["voiceSampleAudio"],n),b(e,["consentAudio"])!==void 0)throw new Error("consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(b(e,["voiceConsentSignature"])!==void 0)throw new Error("voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}function Brn(e){const t={},r=b(e,["category"]);if(r!=null&&_(t,["category"],r),b(e,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=b(e,["threshold"]);return n!=null&&_(t,["threshold"],n),t}function zrn(e){const t={},r=b(e,["handle"]);if(r!=null&&_(t,["handle"],r),b(e,["transparent"])!==void 0)throw new Error("transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function Grn(e){const t={},r=b(e,["speaker"]);r!=null&&_(t,["speaker"],r);const n=b(e,["voiceConfig"]);return n!=null&&_(t,["voiceConfig"],AWe(n)),t}function EWe(e){const t={},r=b(e,["voiceConfig"]);r!=null&&_(t,["voiceConfig"],AWe(r));const n=b(e,["languageCode"]);n!=null&&_(t,["languageCode"],n);const o=b(e,["multiSpeakerVoiceConfig"]);return o!=null&&_(t,["multiSpeakerVoiceConfig"],Lrn(o)),t}function SWe(e){const t={};if(b(e,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const r=b(e,["googleMaps"]);r!=null&&_(t,["googleMaps"],brn(r));const n=b(e,["mcpServers"]);if(n!=null){let d=n;Array.isArray(d)&&(d=d.map(p=>p)),_(t,["mcpServers"],d)}const o=b(e,["codeExecution"]);o!=null&&_(t,["codeExecution"],o);const i=b(e,["computerUse"]);if(i!=null&&_(t,["computerUse"],i),b(e,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const s=b(e,["functionDeclarations"]);if(s!=null){let d=s;Array.isArray(d)&&(d=d.map(p=>p)),_(t,["functionDeclarations"],d)}const a=b(e,["googleSearch"]);a!=null&&_(t,["googleSearch"],Trn(a));const u=b(e,["googleSearchRetrieval"]);if(u!=null&&_(t,["googleSearchRetrieval"],u),b(e,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const l=b(e,["urlContext"]);l!=null&&_(t,["urlContext"],l);const c=b(e,["fileSearch"]);return c!=null&&_(t,["fileSearch"],c),t}function kWe(e){const t={},r=b(e,["retrieval"]);r!=null&&_(t,["retrieval"],r);const n=b(e,["googleMaps"]);n!=null&&_(t,["googleMaps"],n);const o=b(e,["mcpServers"]);if(o!=null){let h=o;Array.isArray(h)&&(h=h.map(g=>Nrn(g))),_(t,["mcpServers"],h)}const i=b(e,["codeExecution"]);i!=null&&_(t,["codeExecution"],i);const s=b(e,["computerUse"]);s!=null&&_(t,["computerUse"],s);const a=b(e,["enterpriseWebSearch"]);a!=null&&_(t,["enterpriseWebSearch"],a);const u=b(e,["exaAiSearch"]);u!=null&&_(t,["exaAiSearch"],u);const l=b(e,["functionDeclarations"]);if(l!=null){let h=l;Array.isArray(h)&&(h=h.map(g=>g)),_(t,["functionDeclarations"],h)}const c=b(e,["googleSearch"]);c!=null&&_(t,["googleSearch"],c);const d=b(e,["googleSearchRetrieval"]);d!=null&&_(t,["googleSearchRetrieval"],d);const p=b(e,["parallelAiSearch"]);p!=null&&_(t,["parallelAiSearch"],p);const m=b(e,["urlContext"]);if(m!=null&&_(t,["urlContext"],m),b(e,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}function qrn(e){const t={},r=b(e,["candidatesTokenCount"]);r!=null&&_(t,["responseTokenCount"],r);const n=b(e,["candidatesTokensDetails"]);if(n!=null){let m=n;Array.isArray(m)&&(m=m.map(h=>h)),_(t,["responseTokensDetails"],m)}const o=b(e,["cacheTokensDetails"]);if(o!=null){let m=o;Array.isArray(m)&&(m=m.map(h=>h)),_(t,["cacheTokensDetails"],m)}const i=b(e,["cachedContentTokenCount"]);i!=null&&_(t,["cachedContentTokenCount"],i);const s=b(e,["promptTokenCount"]);s!=null&&_(t,["promptTokenCount"],s);const a=b(e,["promptTokensDetails"]);if(a!=null){let m=a;Array.isArray(m)&&(m=m.map(h=>h)),_(t,["promptTokensDetails"],m)}const u=b(e,["thoughtsTokenCount"]);u!=null&&_(t,["thoughtsTokenCount"],u);const l=b(e,["toolUsePromptTokenCount"]);l!=null&&_(t,["toolUsePromptTokenCount"],l);const c=b(e,["toolUsePromptTokensDetails"]);if(c!=null){let m=c;Array.isArray(m)&&(m=m.map(h=>h)),_(t,["toolUsePromptTokensDetails"],m)}const d=b(e,["totalTokenCount"]);d!=null&&_(t,["totalTokenCount"],d);const p=b(e,["trafficType"]);return p!=null&&_(t,["trafficType"],p),t}function jrn(e){const t={},r=b(e,["type"]);r!=null&&_(t,["voiceActivityType"],r);const n=b(e,["audioOffset"]);return n!=null&&_(t,["audioOffset"],n),t}function AWe(e){const t={},r=b(e,["replicatedVoiceConfig"]);r!=null&&_(t,["replicatedVoiceConfig"],Urn(r));const n=b(e,["prebuiltVoiceConfig"]);n!=null&&_(t,["prebuiltVoiceConfig"],n);const o=b(e,["voice"]);return o!=null&&_(t,["voice"],o),t}function Vrn(e,t){const r={},n=b(e,["apiKey"]);if(n!=null&&_(r,["apiKey"],n),b(e,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return r}function Hrn(e,t){const r={},n=b(e,["content"]);n!=null&&_(r,["content"],n);const o=b(e,["citationMetadata"]);o!=null&&_(r,["citationMetadata"],Wrn(o));const i=b(e,["tokenCount"]);i!=null&&_(r,["tokenCount"],i);const s=b(e,["finishReason"]);s!=null&&_(r,["finishReason"],s);const a=b(e,["groundingMetadata"]);a!=null&&_(r,["groundingMetadata"],a);const u=b(e,["avgLogprobs"]);u!=null&&_(r,["avgLogprobs"],u);const l=b(e,["index"]);l!=null&&_(r,["index"],l);const c=b(e,["logprobsResult"]);c!=null&&_(r,["logprobsResult"],c);const d=b(e,["safetyRatings"]);if(d!=null){let h=d;Array.isArray(h)&&(h=h.map(g=>g)),_(r,["safetyRatings"],h)}const p=b(e,["urlContextMetadata"]);p!=null&&_(r,["urlContextMetadata"],p);const m=b(e,["continuationToken"]);return m!=null&&_(r,["continuationToken"],m),r}function Wrn(e,t){const r={},n=b(e,["citationSources"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(i=>i)),_(r,["citations"],o)}return r}function Krn(e,t,r){const n={},o=b(t,["model"]);o!=null&&_(n,["_url","model"],Qr(e,o));const i=b(t,["contents"]);if(i!=null){let s=Ya(i);Array.isArray(s)&&(s=s.map(a=>fb(a))),_(n,["contents"],s)}return n}function Jrn(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["tokensInfo"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(s=>s)),_(r,["tokensInfo"],i)}return r}function Xrn(e,t){const r={},n=b(e,["values"]);n!=null&&_(r,["values"],n);const o=b(e,["statistics"]);return o!=null&&_(r,["statistics"],Yrn(o)),r}function Yrn(e,t){const r={},n=b(e,["truncated"]);n!=null&&_(r,["truncated"],n);const o=b(e,["token_count"]);o!=null&&_(r,["tokenCount"],o);const i=b(e,["tokensDetails"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(a=>a)),_(r,["tokensDetails"],s)}return r}function IA(e,t){const r={},n=b(e,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(s=>ton(s))),_(r,["parts"],i)}const o=b(e,["role"]);return o!=null&&_(r,["role"],o),r}function fb(e,t){const r={},n=b(e,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(s=>ron(s))),_(r,["parts"],i)}const o=b(e,["role"]);return o!=null&&_(r,["role"],o),r}function Zrn(e,t){const r={},n=b(e,["controlType"]);n!=null&&_(r,["controlType"],n);const o=b(e,["enableControlImageComputation"]);return o!=null&&_(r,["computeControl"],o),r}function Qrn(e,t){const r={};if(b(e,["systemInstruction"])!==void 0)throw new Error("systemInstruction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["tools"])!==void 0)throw new Error("tools parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["generationConfig"])!==void 0)throw new Error("generationConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return r}function enn(e,t,r){const n={},o=b(e,["systemInstruction"]);t!==void 0&&o!=null&&_(t,["systemInstruction"],fb(Ii(o)));const i=b(e,["tools"]);if(t!==void 0&&i!=null){let a=i;Array.isArray(a)&&(a=a.map(u=>OWe(u))),_(t,["tools"],a)}const s=b(e,["generationConfig"]);return t!==void 0&&s!=null&&_(t,["generationConfig"],Unn(s)),n}function tnn(e,t,r){const n={},o=b(t,["model"]);o!=null&&_(n,["_url","model"],Qr(e,o));const i=b(t,["contents"]);if(i!=null){let a=Ya(i);Array.isArray(a)&&(a=a.map(u=>IA(u))),_(n,["contents"],a)}const s=b(t,["config"]);return s!=null&&Qrn(s),n}function rnn(e,t,r){const n={},o=b(t,["model"]);o!=null&&_(n,["_url","model"],Qr(e,o));const i=b(t,["contents"]);if(i!=null){let a=Ya(i);Array.isArray(a)&&(a=a.map(u=>fb(u))),_(n,["contents"],a)}const s=b(t,["config"]);return s!=null&&enn(s,n),n}function nnn(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["totalTokens"]);o!=null&&_(r,["totalTokens"],o);const i=b(e,["cachedContentTokenCount"]);return i!=null&&_(r,["cachedContentTokenCount"],i),r}function onn(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["totalTokens"]);return o!=null&&_(r,["totalTokens"],o),r}function inn(e,t,r){const n={},o=b(t,["model"]);return o!=null&&_(n,["_url","name"],Qr(e,o)),n}function snn(e,t,r){const n={},o=b(t,["model"]);return o!=null&&_(n,["_url","name"],Qr(e,o)),n}function ann(e,t){const r={},n=b(e,["sdkHttpResponse"]);return n!=null&&_(r,["sdkHttpResponse"],n),r}function unn(e,t){const r={},n=b(e,["sdkHttpResponse"]);return n!=null&&_(r,["sdkHttpResponse"],n),r}function lnn(e,t,r){const n={},o=b(e,["outputGcsUri"]);t!==void 0&&o!=null&&_(t,["parameters","storageUri"],o);const i=b(e,["negativePrompt"]);t!==void 0&&i!=null&&_(t,["parameters","negativePrompt"],i);const s=b(e,["numberOfImages"]);t!==void 0&&s!=null&&_(t,["parameters","sampleCount"],s);const a=b(e,["aspectRatio"]);t!==void 0&&a!=null&&_(t,["parameters","aspectRatio"],a);const u=b(e,["guidanceScale"]);t!==void 0&&u!=null&&_(t,["parameters","guidanceScale"],u);const l=b(e,["seed"]);t!==void 0&&l!=null&&_(t,["parameters","seed"],l);const c=b(e,["safetyFilterLevel"]);t!==void 0&&c!=null&&_(t,["parameters","safetySetting"],c);const d=b(e,["personGeneration"]);t!==void 0&&d!=null&&_(t,["parameters","personGeneration"],d);const p=b(e,["includeSafetyAttributes"]);t!==void 0&&p!=null&&_(t,["parameters","includeSafetyAttributes"],p);const m=b(e,["includeRaiReason"]);t!==void 0&&m!=null&&_(t,["parameters","includeRaiReason"],m);const h=b(e,["language"]);t!==void 0&&h!=null&&_(t,["parameters","language"],h);const g=b(e,["outputMimeType"]);t!==void 0&&g!=null&&_(t,["parameters","outputOptions","mimeType"],g);const y=b(e,["outputCompressionQuality"]);t!==void 0&&y!=null&&_(t,["parameters","outputOptions","compressionQuality"],y);const v=b(e,["addWatermark"]);t!==void 0&&v!=null&&_(t,["parameters","addWatermark"],v);const w=b(e,["labels"]);t!==void 0&&w!=null&&_(t,["labels"],w);const T=b(e,["editMode"]);t!==void 0&&T!=null&&_(t,["parameters","editMode"],T);const E=b(e,["baseSteps"]);return t!==void 0&&E!=null&&_(t,["parameters","editConfig","baseSteps"],E),n}function cnn(e,t,r){const n={},o=b(t,["model"]);o!=null&&_(n,["_url","model"],Qr(e,o));const i=b(t,["prompt"]);i!=null&&_(n,["instances[0]","prompt"],i);const s=b(t,["referenceImages"]);if(s!=null){let u=s;Array.isArray(u)&&(u=u.map(l=>uon(l))),_(n,["instances[0]","referenceImages"],u)}const a=b(t,["config"]);return a!=null&&lnn(a,n),n}function dnn(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["predictions"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(s=>fO(s))),_(r,["generatedImages"],i)}return r}function pnn(e,t,r){const n={},o=b(e,["taskType"]);t!==void 0&&o!=null&&_(t,["requests[]","taskType"],o);const i=b(e,["title"]);t!==void 0&&i!=null&&_(t,["requests[]","title"],i);const s=b(e,["outputDimensionality"]);if(t!==void 0&&s!=null&&_(t,["requests[]","outputDimensionality"],s),b(e,["mimeType"])!==void 0)throw new Error("mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["documentOcr"])!==void 0)throw new Error("documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["audioTrackExtraction"])!==void 0)throw new Error("audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function mnn(e,t,r){const n={};let o=b(r,["embeddingApiType"]);if(o===void 0&&(o="PREDICT"),o==="PREDICT"){const d=b(e,["taskType"]);t!==void 0&&d!=null&&_(t,["instances[]","task_type"],d)}else if(o==="EMBED_CONTENT"){const d=b(e,["taskType"]);t!==void 0&&d!=null&&_(t,["embedContentConfig","taskType"],d)}let i=b(r,["embeddingApiType"]);if(i===void 0&&(i="PREDICT"),i==="PREDICT"){const d=b(e,["title"]);t!==void 0&&d!=null&&_(t,["instances[]","title"],d)}else if(i==="EMBED_CONTENT"){const d=b(e,["title"]);t!==void 0&&d!=null&&_(t,["embedContentConfig","title"],d)}let s=b(r,["embeddingApiType"]);if(s===void 0&&(s="PREDICT"),s==="PREDICT"){const d=b(e,["outputDimensionality"]);t!==void 0&&d!=null&&_(t,["parameters","outputDimensionality"],d)}else if(s==="EMBED_CONTENT"){const d=b(e,["outputDimensionality"]);t!==void 0&&d!=null&&_(t,["embedContentConfig","outputDimensionality"],d)}let a=b(r,["embeddingApiType"]);if(a===void 0&&(a="PREDICT"),a==="PREDICT"){const d=b(e,["mimeType"]);t!==void 0&&d!=null&&_(t,["instances[]","mimeType"],d)}let u=b(r,["embeddingApiType"]);if(u===void 0&&(u="PREDICT"),u==="PREDICT"){const d=b(e,["autoTruncate"]);t!==void 0&&d!=null&&_(t,["parameters","autoTruncate"],d)}else if(u==="EMBED_CONTENT"){const d=b(e,["autoTruncate"]);t!==void 0&&d!=null&&_(t,["embedContentConfig","autoTruncate"],d)}let l=b(r,["embeddingApiType"]);if(l===void 0&&(l="PREDICT"),l==="EMBED_CONTENT"){const d=b(e,["documentOcr"]);t!==void 0&&d!=null&&_(t,["embedContentConfig","documentOcr"],d)}let c=b(r,["embeddingApiType"]);if(c===void 0&&(c="PREDICT"),c==="EMBED_CONTENT"){const d=b(e,["audioTrackExtraction"]);t!==void 0&&d!=null&&_(t,["embedContentConfig","audioTrackExtraction"],d)}return n}function hnn(e,t,r){const n={},o=b(t,["model"]);o!=null&&_(n,["_url","model"],Qr(e,o));const i=b(t,["contents"]);if(i!=null){let l=rJ(e,i);Array.isArray(l)&&(l=l.map(c=>c)),_(n,["requests[]","content"],l)}const s=b(t,["content"]);s!=null&&IA(Ii(s));const a=b(t,["config"]);a!=null&&pnn(a,n);const u=b(t,["model"]);return u!==void 0&&_(n,["requests[]","model"],Qr(e,u)),n}function fnn(e,t,r){const n={},o=b(t,["model"]);o!=null&&_(n,["_url","model"],Qr(e,o));let i=b(r,["embeddingApiType"]);if(i===void 0&&(i="PREDICT"),i==="PREDICT"){const u=b(t,["contents"]);if(u!=null){let l=rJ(e,u);Array.isArray(l)&&(l=l.map(c=>c)),_(n,["instances[]","content"],l)}}let s=b(r,["embeddingApiType"]);if(s===void 0&&(s="PREDICT"),s==="EMBED_CONTENT"){const u=b(t,["content"]);u!=null&&_(n,["content"],fb(Ii(u)))}const a=b(t,["config"]);return a!=null&&mnn(a,n,r),n}function gnn(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["embeddings"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(a=>a)),_(r,["embeddings"],s)}const i=b(e,["metadata"]);return i!=null&&_(r,["metadata"],i),r}function ynn(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["predictions[]","embeddings"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(a=>Xrn(a))),_(r,["embeddings"],s)}const i=b(e,["metadata"]);if(i!=null&&_(r,["metadata"],i),t&&b(t,["embeddingApiType"])==="EMBED_CONTENT"){const s=b(e,["embedding"]),a=b(e,["usageMetadata"]),u=b(e,["truncated"]);if(s){const l={};a&&a.promptTokenCount&&(l.tokenCount=a.promptTokenCount),a&&a.promptTokensDetails&&(l.tokensDetails=a.promptTokensDetails),u&&(l.truncated=u),s.statistics=l,_(r,["embeddings"],[s])}}return r}function vnn(e,t){const r={},n=b(e,["endpoint"]);n!=null&&_(r,["name"],n);const o=b(e,["deployedModelId"]);return o!=null&&_(r,["deployedModelId"],o),r}function wnn(e,t){const r={},n=b(e,["args"]);n!=null&&_(r,["args"],n);const o=b(e,["id"]);o!=null&&_(r,["id"],o);const i=b(e,["name"]);if(i!=null&&_(r,["name"],i),b(e,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return r}function bnn(e,t){const r={},n=b(e,["allowedFunctionNames"]);n!=null&&_(r,["allowedFunctionNames"],n);const o=b(e,["mode"]);if(o!=null&&_(r,["mode"],o),b(e,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return r}function Tnn(e,t,r,n){const o={},i=b(t,["serviceTier"]);r!==void 0&&i!=null&&_(r,["serviceTier"],i);const s=b(t,["systemInstruction"]);r!==void 0&&s!=null&&_(r,["systemInstruction"],IA(Ii(s)));const a=b(t,["temperature"]);a!=null&&_(o,["temperature"],a);const u=b(t,["topP"]);u!=null&&_(o,["topP"],u);const l=b(t,["topK"]);l!=null&&_(o,["topK"],l);const c=b(t,["candidateCount"]);c!=null&&_(o,["candidateCount"],c);const d=b(t,["maxOutputTokens"]);d!=null&&_(o,["maxOutputTokens"],d);const p=b(t,["stopSequences"]);p!=null&&_(o,["stopSequences"],p);const m=b(t,["responseLogprobs"]);m!=null&&_(o,["responseLogprobs"],m);const h=b(t,["logprobs"]);h!=null&&_(o,["logprobs"],h);const g=b(t,["presencePenalty"]);g!=null&&_(o,["presencePenalty"],g);const y=b(t,["frequencyPenalty"]);y!=null&&_(o,["frequencyPenalty"],y);const v=b(t,["seed"]);v!=null&&_(o,["seed"],v);const w=b(t,["responseMimeType"]);w!=null&&_(o,["responseMimeType"],w);const T=b(t,["responseSchema"]);T!=null&&_(o,["responseSchema"],nJ(T));const E=b(t,["responseJsonSchema"]);if(E!=null&&_(o,["responseJsonSchema"],E),b(t,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(t,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const k=b(t,["safetySettings"]);if(r!==void 0&&k!=null){let q=k;Array.isArray(q)&&(q=q.map(H=>con(H))),_(r,["safetySettings"],q)}const A=b(t,["tools"]);if(r!==void 0&&A!=null){let q=xh(A);Array.isArray(q)&&(q=q.map(H=>won(Ch(H)))),_(r,["tools"],q)}const C=b(t,["toolConfig"]);r!==void 0&&C!=null&&_(r,["toolConfig"],yon(C));const R=b(t,["labels"]);r!==void 0&&R!=null&&_(r,["labels"],R);const x=b(t,["cachedContent"]);r!==void 0&&x!=null&&_(r,["cachedContent"],jp(e,x));const P=b(t,["responseModalities"]);P!=null&&_(o,["responseModalities"],P);const D=b(t,["mediaResolution"]);D!=null&&_(o,["mediaResolution"],D);const L=b(t,["speechConfig"]);if(L!=null&&_(o,["speechConfig"],oJ(L)),b(t,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const O=b(t,["thinkingConfig"]);O!=null&&_(o,["thinkingConfig"],O);const N=b(t,["audioTranscriptionConfig"]);N!=null&&_(o,["audioTranscriptionConfig"],N);const U=b(t,["imageConfig"]);U!=null&&_(o,["imageConfig"],jnn(U));const $=b(t,["enableEnhancedCivicAnswers"]);if($!=null&&_(o,["enableEnhancedCivicAnswers"],$),b(t,["modelArmorConfig"])!==void 0)throw new Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const G=b(t,["continuationToken"]);if(r!==void 0&&G!=null&&_(r,["continuationToken"],G),b(t,["generationOutputConfig"])!==void 0)throw new Error("generationOutputConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const B=b(t,["store"]);return r!==void 0&&B!=null&&_(r,["store"],B),o}function _nn(e,t,r,n){const o={},i=b(t,["serviceTier"]);r!==void 0&&i!=null&&_(r,["serviceTier"],i);const s=b(t,["systemInstruction"]);r!==void 0&&s!=null&&_(r,["systemInstruction"],fb(Ii(s)));const a=b(t,["temperature"]);a!=null&&_(o,["temperature"],a);const u=b(t,["topP"]);u!=null&&_(o,["topP"],u);const l=b(t,["topK"]);l!=null&&_(o,["topK"],l);const c=b(t,["candidateCount"]);c!=null&&_(o,["candidateCount"],c);const d=b(t,["maxOutputTokens"]);d!=null&&_(o,["maxOutputTokens"],d);const p=b(t,["stopSequences"]);p!=null&&_(o,["stopSequences"],p);const m=b(t,["responseLogprobs"]);m!=null&&_(o,["responseLogprobs"],m);const h=b(t,["logprobs"]);h!=null&&_(o,["logprobs"],h);const g=b(t,["presencePenalty"]);g!=null&&_(o,["presencePenalty"],g);const y=b(t,["frequencyPenalty"]);y!=null&&_(o,["frequencyPenalty"],y);const v=b(t,["seed"]);v!=null&&_(o,["seed"],v);const w=b(t,["responseMimeType"]);w!=null&&_(o,["responseMimeType"],w);const T=b(t,["responseSchema"]);T!=null&&_(o,["responseSchema"],nJ(T));const E=b(t,["responseJsonSchema"]);E!=null&&_(o,["responseJsonSchema"],E);const k=b(t,["routingConfig"]);k!=null&&_(o,["routingConfig"],k);const A=b(t,["modelSelectionConfig"]);A!=null&&_(o,["modelConfig"],A);const C=b(t,["safetySettings"]);if(r!==void 0&&C!=null){let X=C;Array.isArray(X)&&(X=X.map(oe=>oe)),_(r,["safetySettings"],X)}const R=b(t,["tools"]);if(r!==void 0&&R!=null){let X=xh(R);Array.isArray(X)&&(X=X.map(oe=>OWe(Ch(oe)))),_(r,["tools"],X)}const x=b(t,["toolConfig"]);r!==void 0&&x!=null&&_(r,["toolConfig"],von(x));const P=b(t,["labels"]);r!==void 0&&P!=null&&_(r,["labels"],P);const D=b(t,["cachedContent"]);r!==void 0&&D!=null&&_(r,["cachedContent"],jp(e,D));const L=b(t,["responseModalities"]);L!=null&&_(o,["responseModalities"],L);const O=b(t,["mediaResolution"]);O!=null&&_(o,["mediaResolution"],O);const N=b(t,["speechConfig"]);N!=null&&_(o,["speechConfig"],DWe(oJ(N)));const U=b(t,["audioTimestamp"]);U!=null&&_(o,["audioTimestamp"],U);const $=b(t,["thinkingConfig"]);$!=null&&_(o,["thinkingConfig"],$);const G=b(t,["audioTranscriptionConfig"]);G!=null&&_(o,["audioTranscriptionConfig"],G);const B=b(t,["imageConfig"]);if(B!=null&&_(o,["imageConfig"],Vnn(B)),b(t,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const q=b(t,["modelArmorConfig"]);r!==void 0&&q!=null&&_(r,["modelArmorConfig"],q);const H=b(t,["continuationToken"]);r!==void 0&&H!=null&&_(r,["continuationToken"],H);const ne=b(t,["generationOutputConfig"]);if(r!==void 0&&ne!=null&&_(r,["outputConfig"],ne),b(t,["store"])!==void 0)throw new Error("store parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return o}function CWe(e,t,r){const n={},o=b(t,["model"]);o!=null&&_(n,["_url","model"],Qr(e,o));const i=b(t,["contents"]);if(i!=null){let a=Ya(i);Array.isArray(a)&&(a=a.map(u=>IA(u))),_(n,["contents"],a)}const s=b(t,["config"]);return s!=null&&_(n,["generationConfig"],Tnn(e,s,n)),n}function xWe(e,t,r){const n={},o=b(t,["model"]);o!=null&&_(n,["_url","model"],Qr(e,o));const i=b(t,["contents"]);if(i!=null){let a=Ya(i);Array.isArray(a)&&(a=a.map(u=>fb(u))),_(n,["contents"],a)}const s=b(t,["config"]);return s!=null&&_(n,["generationConfig"],_nn(e,s,n)),n}function IWe(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["candidates"]);if(o!=null){let c=o;Array.isArray(c)&&(c=c.map(d=>Hrn(d))),_(r,["candidates"],c)}const i=b(e,["modelVersion"]);i!=null&&_(r,["modelVersion"],i);const s=b(e,["promptFeedback"]);s!=null&&_(r,["promptFeedback"],s);const a=b(e,["responseId"]);a!=null&&_(r,["responseId"],a);const u=b(e,["usageMetadata"]);u!=null&&_(r,["usageMetadata"],u);const l=b(e,["modelStatus"]);return l!=null&&_(r,["modelStatus"],l),r}function RWe(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["candidates"]);if(o!=null){let c=o;Array.isArray(c)&&(c=c.map(d=>d)),_(r,["candidates"],c)}const i=b(e,["createTime"]);i!=null&&_(r,["createTime"],i);const s=b(e,["modelVersion"]);s!=null&&_(r,["modelVersion"],s);const a=b(e,["promptFeedback"]);a!=null&&_(r,["promptFeedback"],a);const u=b(e,["responseId"]);u!=null&&_(r,["responseId"],u);const l=b(e,["usageMetadata"]);return l!=null&&_(r,["usageMetadata"],l),r}function Enn(e,t,r){const n={},o=b(e,["outputGcsUri"]);t!==void 0&&o!=null&&_(t,["parameters","storageUri"],o);const i=b(e,["negativePrompt"]);t!==void 0&&i!=null&&_(t,["parameters","negativePrompt"],i);const s=b(e,["numberOfImages"]);t!==void 0&&s!=null&&_(t,["parameters","sampleCount"],s);const a=b(e,["aspectRatio"]);t!==void 0&&a!=null&&_(t,["parameters","aspectRatio"],a);const u=b(e,["guidanceScale"]);t!==void 0&&u!=null&&_(t,["parameters","guidanceScale"],u);const l=b(e,["seed"]);t!==void 0&&l!=null&&_(t,["parameters","seed"],l);const c=b(e,["safetyFilterLevel"]);t!==void 0&&c!=null&&_(t,["parameters","safetySetting"],c);const d=b(e,["personGeneration"]);t!==void 0&&d!=null&&_(t,["parameters","personGeneration"],d);const p=b(e,["includeSafetyAttributes"]);t!==void 0&&p!=null&&_(t,["parameters","includeSafetyAttributes"],p);const m=b(e,["includeRaiReason"]);t!==void 0&&m!=null&&_(t,["parameters","includeRaiReason"],m);const h=b(e,["language"]);t!==void 0&&h!=null&&_(t,["parameters","language"],h);const g=b(e,["outputMimeType"]);t!==void 0&&g!=null&&_(t,["parameters","outputOptions","mimeType"],g);const y=b(e,["outputCompressionQuality"]);t!==void 0&&y!=null&&_(t,["parameters","outputOptions","compressionQuality"],y);const v=b(e,["addWatermark"]);t!==void 0&&v!=null&&_(t,["parameters","addWatermark"],v);const w=b(e,["labels"]);t!==void 0&&w!=null&&_(t,["labels"],w);const T=b(e,["imageSize"]);t!==void 0&&T!=null&&_(t,["parameters","sampleImageSize"],T);const E=b(e,["enhancePrompt"]);return t!==void 0&&E!=null&&_(t,["parameters","enhancePrompt"],E),n}function Snn(e,t,r){const n={},o=b(t,["model"]);o!=null&&_(n,["_url","model"],Qr(e,o));const i=b(t,["prompt"]);i!=null&&_(n,["instances[0]","prompt"],i);const s=b(t,["config"]);return s!=null&&Enn(s,n),n}function knn(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["predictions"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(a=>fO(a))),_(r,["generatedImages"],s)}const i=b(e,["positivePromptSafetyAttributes"]);return i!=null&&_(r,["positivePromptSafetyAttributes"],PWe(i)),r}function Ann(e,t,r){const n={},o=b(e,["numberOfVideos"]);if(t!==void 0&&o!=null&&_(t,["parameters","sampleCount"],o),b(e,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["fps"])!==void 0)throw new Error("fps parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const i=b(e,["durationSeconds"]);if(t!==void 0&&i!=null&&_(t,["parameters","durationSeconds"],i),b(e,["seed"])!==void 0)throw new Error("seed parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const s=b(e,["aspectRatio"]);t!==void 0&&s!=null&&_(t,["parameters","aspectRatio"],s);const a=b(e,["resolution"]);t!==void 0&&a!=null&&_(t,["parameters","resolution"],a);const u=b(e,["personGeneration"]);if(t!==void 0&&u!=null&&_(t,["parameters","personGeneration"],u),b(e,["pubsubTopic"])!==void 0)throw new Error("pubsubTopic parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const l=b(e,["negativePrompt"]);t!==void 0&&l!=null&&_(t,["parameters","negativePrompt"],l);const c=b(e,["enhancePrompt"]);if(t!==void 0&&c!=null&&_(t,["parameters","enhancePrompt"],c),b(e,["generateAudio"])!==void 0)throw new Error("generateAudio parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const d=b(e,["lastFrame"]);t!==void 0&&d!=null&&_(t,["instances[0]","lastFrame"],gO(d));const p=b(e,["referenceImages"]);if(t!==void 0&&p!=null){let h=p;Array.isArray(h)&&(h=h.map(g=>Pon(g))),_(t,["instances[0]","referenceImages"],h)}if(b(e,["mask"])!==void 0)throw new Error("mask parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["compressionQuality"])!==void 0)throw new Error("compressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const m=b(e,["webhookConfig"]);if(t!==void 0&&m!=null&&_(t,["webhookConfig"],m),b(e,["resizeMode"])!==void 0)throw new Error("resizeMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function Cnn(e,t,r){const n={},o=b(e,["numberOfVideos"]);t!==void 0&&o!=null&&_(t,["parameters","sampleCount"],o);const i=b(e,["outputGcsUri"]);t!==void 0&&i!=null&&_(t,["parameters","storageUri"],i);const s=b(e,["fps"]);t!==void 0&&s!=null&&_(t,["parameters","fps"],s);const a=b(e,["durationSeconds"]);t!==void 0&&a!=null&&_(t,["parameters","durationSeconds"],a);const u=b(e,["seed"]);t!==void 0&&u!=null&&_(t,["parameters","seed"],u);const l=b(e,["aspectRatio"]);t!==void 0&&l!=null&&_(t,["parameters","aspectRatio"],l);const c=b(e,["resolution"]);t!==void 0&&c!=null&&_(t,["parameters","resolution"],c);const d=b(e,["personGeneration"]);t!==void 0&&d!=null&&_(t,["parameters","personGeneration"],d);const p=b(e,["pubsubTopic"]);t!==void 0&&p!=null&&_(t,["parameters","pubsubTopic"],p);const m=b(e,["negativePrompt"]);t!==void 0&&m!=null&&_(t,["parameters","negativePrompt"],m);const h=b(e,["enhancePrompt"]);t!==void 0&&h!=null&&_(t,["parameters","enhancePrompt"],h);const g=b(e,["generateAudio"]);t!==void 0&&g!=null&&_(t,["parameters","generateAudio"],g);const y=b(e,["lastFrame"]);t!==void 0&&y!=null&&_(t,["instances[0]","lastFrame"],wc(y));const v=b(e,["referenceImages"]);if(t!==void 0&&v!=null){let A=v;Array.isArray(A)&&(A=A.map(C=>Don(C))),_(t,["instances[0]","referenceImages"],A)}const w=b(e,["mask"]);t!==void 0&&w!=null&&_(t,["instances[0]","mask"],Mon(w));const T=b(e,["compressionQuality"]);t!==void 0&&T!=null&&_(t,["parameters","compressionQuality"],T);const E=b(e,["labels"]);if(t!==void 0&&E!=null&&_(t,["labels"],E),b(e,["webhookConfig"])!==void 0)throw new Error("webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const k=b(e,["resizeMode"]);return t!==void 0&&k!=null&&_(t,["parameters","resizeMode"],k),n}function xnn(e,t){const r={},n=b(e,["name"]);n!=null&&_(r,["name"],n);const o=b(e,["metadata"]);o!=null&&_(r,["metadata"],o);const i=b(e,["done"]);i!=null&&_(r,["done"],i);const s=b(e,["error"]);s!=null&&_(r,["error"],s);const a=b(e,["response","generateVideoResponse"]);return a!=null&&_(r,["response"],Pnn(a)),r}function Inn(e,t){const r={},n=b(e,["name"]);n!=null&&_(r,["name"],n);const o=b(e,["metadata"]);o!=null&&_(r,["metadata"],o);const i=b(e,["done"]);i!=null&&_(r,["done"],i);const s=b(e,["error"]);s!=null&&_(r,["error"],s);const a=b(e,["response"]);return a!=null&&_(r,["response"],Dnn(a)),r}function Rnn(e,t,r){const n={},o=b(t,["model"]);o!=null&&_(n,["_url","model"],Qr(e,o));const i=b(t,["prompt"]);i!=null&&_(n,["instances[0]","prompt"],i);const s=b(t,["image"]);s!=null&&_(n,["instances[0]","image"],gO(s));const a=b(t,["video"]);a!=null&&_(n,["instances[0]","video"],NWe(a));const u=b(t,["source"]);u!=null&&Onn(u,n);const l=b(t,["config"]);return l!=null&&Ann(l,n),n}function Mnn(e,t,r){const n={},o=b(t,["model"]);o!=null&&_(n,["_url","model"],Qr(e,o));const i=b(t,["prompt"]);i!=null&&_(n,["instances[0]","prompt"],i);const s=b(t,["image"]);s!=null&&_(n,["instances[0]","image"],wc(s));const a=b(t,["video"]);a!=null&&_(n,["instances[0]","video"],LWe(a));const u=b(t,["source"]);u!=null&&Nnn(u,n);const l=b(t,["config"]);return l!=null&&Cnn(l,n),n}function Pnn(e,t){const r={},n=b(e,["generatedSamples"]);if(n!=null){let s=n;Array.isArray(s)&&(s=s.map(a=>$nn(a))),_(r,["generatedVideos"],s)}const o=b(e,["raiMediaFilteredCount"]);o!=null&&_(r,["raiMediaFilteredCount"],o);const i=b(e,["raiMediaFilteredReasons"]);return i!=null&&_(r,["raiMediaFilteredReasons"],i),r}function Dnn(e,t){const r={},n=b(e,["videos"]);if(n!=null){let s=n;Array.isArray(s)&&(s=s.map(a=>Fnn(a))),_(r,["generatedVideos"],s)}const o=b(e,["raiMediaFilteredCount"]);o!=null&&_(r,["raiMediaFilteredCount"],o);const i=b(e,["raiMediaFilteredReasons"]);return i!=null&&_(r,["raiMediaFilteredReasons"],i),r}function Onn(e,t,r){const n={},o=b(e,["prompt"]);t!==void 0&&o!=null&&_(t,["instances[0]","prompt"],o);const i=b(e,["image"]);t!==void 0&&i!=null&&_(t,["instances[0]","image"],gO(i));const s=b(e,["video"]);return t!==void 0&&s!=null&&_(t,["instances[0]","video"],NWe(s)),n}function Nnn(e,t,r){const n={},o=b(e,["prompt"]);t!==void 0&&o!=null&&_(t,["instances[0]","prompt"],o);const i=b(e,["image"]);t!==void 0&&i!=null&&_(t,["instances[0]","image"],wc(i));const s=b(e,["video"]);return t!==void 0&&s!=null&&_(t,["instances[0]","video"],LWe(s)),n}function fO(e,t){const r={},n=b(e,["_self"]);n!=null&&_(r,["image"],MWe(n));const o=b(e,["raiFilteredReason"]);o!=null&&_(r,["raiFilteredReason"],o);const i=b(e,["_self"]);i!=null&&_(r,["safetyAttributes"],PWe(i));const s=b(e,["prompt"]);return s!=null&&_(r,["enhancedPrompt"],s),r}function Lnn(e,t){const r={},n=b(e,["_self"]);n!=null&&_(r,["mask"],MWe(n));const o=b(e,["labels"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(s=>s)),_(r,["labels"],i)}return r}function $nn(e,t){const r={},n=b(e,["video"]);return n!=null&&_(r,["video"],Ion(n)),r}function Fnn(e,t){const r={},n=b(e,["_self"]);return n!=null&&_(r,["video"],Ron(n)),r}function Unn(e,t){const r={},n=b(e,["modelSelectionConfig"]);n!=null&&_(r,["modelConfig"],n);const o=b(e,["responseJsonSchema"]);o!=null&&_(r,["responseJsonSchema"],o);const i=b(e,["audioTranscriptionConfig"]);i!=null&&_(r,["audioTranscriptionConfig"],i);const s=b(e,["audioTimestamp"]);s!=null&&_(r,["audioTimestamp"],s);const a=b(e,["candidateCount"]);a!=null&&_(r,["candidateCount"],a);const u=b(e,["enableAffectiveDialog"]);u!=null&&_(r,["enableAffectiveDialog"],u);const l=b(e,["frequencyPenalty"]);l!=null&&_(r,["frequencyPenalty"],l);const c=b(e,["logprobs"]);c!=null&&_(r,["logprobs"],c);const d=b(e,["maxOutputTokens"]);d!=null&&_(r,["maxOutputTokens"],d);const p=b(e,["mediaResolution"]);p!=null&&_(r,["mediaResolution"],p);const m=b(e,["presencePenalty"]);m!=null&&_(r,["presencePenalty"],m);const h=b(e,["responseFormat"]);if(h!=null){let L=h;Array.isArray(L)&&(L=L.map(O=>O)),_(r,["responseFormat"],L)}const g=b(e,["responseLogprobs"]);g!=null&&_(r,["responseLogprobs"],g);const y=b(e,["responseMimeType"]);y!=null&&_(r,["responseMimeType"],y);const v=b(e,["responseModalities"]);v!=null&&_(r,["responseModalities"],v);const w=b(e,["responseSchema"]);w!=null&&_(r,["responseSchema"],w);const T=b(e,["routingConfig"]);T!=null&&_(r,["routingConfig"],T);const E=b(e,["seed"]);E!=null&&_(r,["seed"],E);const k=b(e,["speechConfig"]);k!=null&&_(r,["speechConfig"],DWe(k));const A=b(e,["stopSequences"]);A!=null&&_(r,["stopSequences"],A);const C=b(e,["temperature"]);C!=null&&_(r,["temperature"],C);const R=b(e,["thinkingConfig"]);R!=null&&_(r,["thinkingConfig"],R);const x=b(e,["topK"]);x!=null&&_(r,["topK"],x);const P=b(e,["topP"]);if(P!=null&&_(r,["topP"],P),b(e,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const D=b(e,["translationConfig"]);return D!=null&&_(r,["translationConfig"],D),r}function Bnn(e,t,r){const n={},o=b(t,["model"]);return o!=null&&_(n,["_url","name"],Qr(e,o)),n}function znn(e,t,r){const n={},o=b(t,["model"]);return o!=null&&_(n,["_url","name"],Qr(e,o)),n}function Gnn(e,t){const r={},n=b(e,["authConfig"]);n!=null&&_(r,["authConfig"],Vrn(n));const o=b(e,["enableWidget"]);if(o!=null&&_(r,["enableWidget"],o),b(e,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return r}function qnn(e,t){const r={};if(b(e,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=b(e,["searchTypes"]);n!=null&&_(r,["searchTypes"],n);const o=b(e,["timeRangeFilter"]);return o!=null&&_(r,["timeRangeFilter"],o),r}function jnn(e,t){const r={},n=b(e,["aspectRatio"]);n!=null&&_(r,["aspectRatio"],n);const o=b(e,["imageSize"]);if(o!=null&&_(r,["imageSize"],o),b(e,["personGeneration"])!==void 0)throw new Error("personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["imageOutputOptions"])!==void 0)throw new Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["prominentPeople"])!==void 0)throw new Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return r}function Vnn(e,t){const r={},n=b(e,["aspectRatio"]);n!=null&&_(r,["aspectRatio"],n);const o=b(e,["imageSize"]);o!=null&&_(r,["imageSize"],o);const i=b(e,["personGeneration"]);i!=null&&_(r,["personGeneration"],i);const s=b(e,["outputMimeType"]);s!=null&&_(r,["imageOutputOptions","mimeType"],s);const a=b(e,["outputCompressionQuality"]);a!=null&&_(r,["imageOutputOptions","compressionQuality"],a);const u=b(e,["imageOutputOptions"]);u!=null&&_(r,["imageOutputOptions"],u);const l=b(e,["prominentPeople"]);return l!=null&&_(r,["prominentPeople"],l),r}function MWe(e,t){const r={},n=b(e,["gcsUri"]);n!=null&&_(r,["gcsUri"],n);const o=b(e,["bytesBase64Encoded"]);o!=null&&_(r,["imageBytes"],n0(o));const i=b(e,["mimeType"]);return i!=null&&_(r,["mimeType"],i),r}function gO(e,t){const r={};if(b(e,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=b(e,["imageBytes"]);n!=null&&_(r,["bytesBase64Encoded"],n0(n));const o=b(e,["mimeType"]);return o!=null&&_(r,["mimeType"],o),r}function wc(e,t){const r={},n=b(e,["gcsUri"]);n!=null&&_(r,["gcsUri"],n);const o=b(e,["imageBytes"]);o!=null&&_(r,["bytesBase64Encoded"],n0(o));const i=b(e,["mimeType"]);return i!=null&&_(r,["mimeType"],i),r}function Hnn(e,t,r,n){const o={},i=b(t,["pageSize"]);r!==void 0&&i!=null&&_(r,["_query","pageSize"],i);const s=b(t,["pageToken"]);r!==void 0&&s!=null&&_(r,["_query","pageToken"],s);const a=b(t,["filter"]);r!==void 0&&a!=null&&_(r,["_query","filter"],a);const u=b(t,["queryBase"]);return r!==void 0&&u!=null&&_(r,["_url","models_url"],QVe(e,u)),o}function Wnn(e,t,r,n){const o={},i=b(t,["pageSize"]);r!==void 0&&i!=null&&_(r,["_query","pageSize"],i);const s=b(t,["pageToken"]);r!==void 0&&s!=null&&_(r,["_query","pageToken"],s);const a=b(t,["filter"]);r!==void 0&&a!=null&&_(r,["_query","filter"],a);const u=b(t,["queryBase"]);return r!==void 0&&u!=null&&_(r,["_url","models_url"],QVe(e,u)),o}function Knn(e,t,r){const n={},o=b(t,["config"]);return o!=null&&Hnn(e,o,n),n}function Jnn(e,t,r){const n={},o=b(t,["config"]);return o!=null&&Wnn(e,o,n),n}function Xnn(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["nextPageToken"]);o!=null&&_(r,["nextPageToken"],o);const i=b(e,["_self"]);if(i!=null){let s=eHe(i);Array.isArray(s)&&(s=s.map(a=>dJ(a))),_(r,["models"],s)}return r}function Ynn(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["nextPageToken"]);o!=null&&_(r,["nextPageToken"],o);const i=b(e,["_self"]);if(i!=null){let s=eHe(i);Array.isArray(s)&&(s=s.map(a=>pJ(a))),_(r,["models"],s)}return r}function Znn(e,t){const r={},n=b(e,["maskMode"]);n!=null&&_(r,["maskMode"],n);const o=b(e,["segmentationClasses"]);o!=null&&_(r,["maskClasses"],o);const i=b(e,["maskDilation"]);return i!=null&&_(r,["dilation"],i),r}function Qnn(e,t){const r={};if(b(e,["name"])!==void 0)throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(b(e,["streamableHttpTransport"])!==void 0)throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return r}function dJ(e,t){const r={},n=b(e,["name"]);n!=null&&_(r,["name"],n);const o=b(e,["displayName"]);o!=null&&_(r,["displayName"],o);const i=b(e,["description"]);i!=null&&_(r,["description"],i);const s=b(e,["version"]);s!=null&&_(r,["version"],s);const a=b(e,["_self"]);a!=null&&_(r,["tunedModelInfo"],bon(a));const u=b(e,["inputTokenLimit"]);u!=null&&_(r,["inputTokenLimit"],u);const l=b(e,["outputTokenLimit"]);l!=null&&_(r,["outputTokenLimit"],l);const c=b(e,["supportedGenerationMethods"]);c!=null&&_(r,["supportedActions"],c);const d=b(e,["temperature"]);d!=null&&_(r,["temperature"],d);const p=b(e,["maxTemperature"]);p!=null&&_(r,["maxTemperature"],p);const m=b(e,["topP"]);m!=null&&_(r,["topP"],m);const h=b(e,["topK"]);h!=null&&_(r,["topK"],h);const g=b(e,["thinking"]);return g!=null&&_(r,["thinking"],g),r}function pJ(e,t){const r={},n=b(e,["name"]);n!=null&&_(r,["name"],n);const o=b(e,["displayName"]);o!=null&&_(r,["displayName"],o);const i=b(e,["description"]);i!=null&&_(r,["description"],i);const s=b(e,["versionId"]);s!=null&&_(r,["version"],s);const a=b(e,["deployedModels"]);if(a!=null){let p=a;Array.isArray(p)&&(p=p.map(m=>vnn(m))),_(r,["endpoints"],p)}const u=b(e,["labels"]);u!=null&&_(r,["labels"],u);const l=b(e,["_self"]);l!=null&&_(r,["tunedModelInfo"],Ton(l));const c=b(e,["defaultCheckpointId"]);c!=null&&_(r,["defaultCheckpointId"],c);const d=b(e,["checkpoints"]);if(d!=null){let p=d;Array.isArray(p)&&(p=p.map(m=>m)),_(r,["checkpoints"],p)}return r}function eon(e,t){const r={},n=b(e,["speakerVoiceConfigs"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(i=>gon(i))),_(r,["speakerVoiceConfigs"],o)}return r}function ton(e,t){const r={},n=b(e,["mediaResolution"]);n!=null&&_(r,["mediaResolution"],n);const o=b(e,["toolCall"]);o!=null&&_(r,["toolCall"],o);const i=b(e,["toolResponse"]);i!=null&&_(r,["toolResponse"],i);const s=b(e,["audioTranscription"]);s!=null&&_(r,["audioTranscription"],s);const a=b(e,["codeExecutionResult"]);a!=null&&_(r,["codeExecutionResult"],a);const u=b(e,["executableCode"]);u!=null&&_(r,["executableCode"],u);const l=b(e,["fileData"]);l!=null&&_(r,["fileData"],l);const c=b(e,["functionCall"]);c!=null&&_(r,["functionCall"],wnn(c));const d=b(e,["functionResponse"]);d!=null&&_(r,["functionResponse"],d);const p=b(e,["inlineData"]);p!=null&&_(r,["inlineData"],p);const m=b(e,["text"]);m!=null&&_(r,["text"],m);const h=b(e,["thought"]);h!=null&&_(r,["thought"],h);const g=b(e,["thoughtSignature"]);g!=null&&_(r,["thoughtSignature"],g);const y=b(e,["videoMetadata"]);y!=null&&_(r,["videoMetadata"],y);const v=b(e,["partMetadata"]);v!=null&&_(r,["partMetadata"],v);const w=b(e,["mediaProcessing"]);w!=null&&_(r,["mediaProcessing"],w);const T=b(e,["speechMetadata"]);return T!=null&&_(r,["speechMetadata"],T),r}function ron(e,t){const r={},n=b(e,["mediaResolution"]);if(n!=null&&_(r,["mediaResolution"],n),b(e,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(b(e,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const o=b(e,["audioTranscription"]);o!=null&&_(r,["audioTranscription"],o);const i=b(e,["codeExecutionResult"]);i!=null&&_(r,["codeExecutionResult"],i);const s=b(e,["executableCode"]);s!=null&&_(r,["executableCode"],s);const a=b(e,["fileData"]);a!=null&&_(r,["fileData"],a);const u=b(e,["functionCall"]);u!=null&&_(r,["functionCall"],u);const l=b(e,["functionResponse"]);l!=null&&_(r,["functionResponse"],l);const c=b(e,["inlineData"]);c!=null&&_(r,["inlineData"],c);const d=b(e,["text"]);d!=null&&_(r,["text"],d);const p=b(e,["thought"]);p!=null&&_(r,["thought"],p);const m=b(e,["thoughtSignature"]);m!=null&&_(r,["thoughtSignature"],m);const h=b(e,["videoMetadata"]);if(h!=null&&_(r,["videoMetadata"],h),b(e,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const g=b(e,["mediaProcessing"]);g!=null&&_(r,["mediaProcessing"],g);const y=b(e,["speechMetadata"]);return y!=null&&_(r,["speechMetadata"],y),r}function non(e,t){const r={},n=b(e,["productImage"]);return n!=null&&_(r,["image"],wc(n)),r}function oon(e,t,r){const n={},o=b(e,["numberOfImages"]);t!==void 0&&o!=null&&_(t,["parameters","sampleCount"],o);const i=b(e,["baseSteps"]);t!==void 0&&i!=null&&_(t,["parameters","baseSteps"],i);const s=b(e,["outputGcsUri"]);t!==void 0&&s!=null&&_(t,["parameters","storageUri"],s);const a=b(e,["seed"]);t!==void 0&&a!=null&&_(t,["parameters","seed"],a);const u=b(e,["safetyFilterLevel"]);t!==void 0&&u!=null&&_(t,["parameters","safetySetting"],u);const l=b(e,["personGeneration"]);t!==void 0&&l!=null&&_(t,["parameters","personGeneration"],l);const c=b(e,["addWatermark"]);t!==void 0&&c!=null&&_(t,["parameters","addWatermark"],c);const d=b(e,["outputMimeType"]);t!==void 0&&d!=null&&_(t,["parameters","outputOptions","mimeType"],d);const p=b(e,["outputCompressionQuality"]);t!==void 0&&p!=null&&_(t,["parameters","outputOptions","compressionQuality"],p);const m=b(e,["enhancePrompt"]);t!==void 0&&m!=null&&_(t,["parameters","enhancePrompt"],m);const h=b(e,["labels"]);return t!==void 0&&h!=null&&_(t,["labels"],h),n}function ion(e,t,r){const n={},o=b(t,["model"]);o!=null&&_(n,["_url","model"],Qr(e,o));const i=b(t,["source"]);i!=null&&aon(i,n);const s=b(t,["config"]);return s!=null&&oon(s,n),n}function son(e,t){const r={},n=b(e,["predictions"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(i=>fO(i))),_(r,["generatedImages"],o)}return r}function aon(e,t,r){const n={},o=b(e,["prompt"]);t!==void 0&&o!=null&&_(t,["instances[0]","prompt"],o);const i=b(e,["personImage"]);t!==void 0&&i!=null&&_(t,["instances[0]","personImage","image"],wc(i));const s=b(e,["productImages"]);if(t!==void 0&&s!=null){let a=s;Array.isArray(a)&&(a=a.map(u=>non(u))),_(t,["instances[0]","productImages"],a)}return n}function uon(e,t){const r={},n=b(e,["referenceImage"]);n!=null&&_(r,["referenceImage"],wc(n));const o=b(e,["referenceId"]);o!=null&&_(r,["referenceId"],o);const i=b(e,["referenceType"]);i!=null&&_(r,["referenceType"],i);const s=b(e,["maskImageConfig"]);s!=null&&_(r,["maskImageConfig"],Znn(s));const a=b(e,["controlImageConfig"]);a!=null&&_(r,["controlImageConfig"],Zrn(a));const u=b(e,["styleImageConfig"]);u!=null&&_(r,["styleImageConfig"],u);const l=b(e,["subjectImageConfig"]);return l!=null&&_(r,["subjectImageConfig"],l),r}function lon(e,t){const r={},n=b(e,["mimeType"]);n!=null&&_(r,["mimeType"],n);const o=b(e,["voiceSampleAudio"]);if(o!=null&&_(r,["voiceSampleAudio"],o),b(e,["consentAudio"])!==void 0)throw new Error("consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(b(e,["voiceConsentSignature"])!==void 0)throw new Error("voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return r}function PWe(e,t){const r={},n=b(e,["safetyAttributes","categories"]);n!=null&&_(r,["categories"],n);const o=b(e,["safetyAttributes","scores"]);o!=null&&_(r,["scores"],o);const i=b(e,["contentType"]);return i!=null&&_(r,["contentType"],i),r}function con(e,t){const r={},n=b(e,["category"]);if(n!=null&&_(r,["category"],n),b(e,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=b(e,["threshold"]);return o!=null&&_(r,["threshold"],o),r}function don(e,t){const r={},n=b(e,["image"]);return n!=null&&_(r,["image"],wc(n)),r}function pon(e,t,r){const n={},o=b(e,["mode"]);t!==void 0&&o!=null&&_(t,["parameters","mode"],o);const i=b(e,["maxPredictions"]);t!==void 0&&i!=null&&_(t,["parameters","maxPredictions"],i);const s=b(e,["confidenceThreshold"]);t!==void 0&&s!=null&&_(t,["parameters","confidenceThreshold"],s);const a=b(e,["maskDilation"]);t!==void 0&&a!=null&&_(t,["parameters","maskDilation"],a);const u=b(e,["binaryColorThreshold"]);t!==void 0&&u!=null&&_(t,["parameters","binaryColorThreshold"],u);const l=b(e,["labels"]);return t!==void 0&&l!=null&&_(t,["labels"],l),n}function mon(e,t,r){const n={},o=b(t,["model"]);o!=null&&_(n,["_url","model"],Qr(e,o));const i=b(t,["source"]);i!=null&&fon(i,n);const s=b(t,["config"]);return s!=null&&pon(s,n),n}function hon(e,t){const r={},n=b(e,["predictions"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(i=>Lnn(i))),_(r,["generatedMasks"],o)}return r}function fon(e,t,r){const n={},o=b(e,["prompt"]);t!==void 0&&o!=null&&_(t,["instances[0]","prompt"],o);const i=b(e,["image"]);t!==void 0&&i!=null&&_(t,["instances[0]","image"],wc(i));const s=b(e,["scribbleImage"]);return t!==void 0&&s!=null&&_(t,["instances[0]","scribble"],don(s)),n}function gon(e,t){const r={},n=b(e,["speaker"]);n!=null&&_(r,["speaker"],n);const o=b(e,["voiceConfig"]);return o!=null&&_(r,["voiceConfig"],$We(o)),r}function DWe(e,t){const r={},n=b(e,["voiceConfig"]);n!=null&&_(r,["voiceConfig"],$We(n));const o=b(e,["languageCode"]);o!=null&&_(r,["languageCode"],o);const i=b(e,["multiSpeakerVoiceConfig"]);return i!=null&&_(r,["multiSpeakerVoiceConfig"],eon(i)),r}function yon(e,t){const r={},n=b(e,["functionCallingConfig"]);n!=null&&_(r,["functionCallingConfig"],bnn(n));const o=b(e,["retrievalConfig"]);o!=null&&_(r,["retrievalConfig"],o);const i=b(e,["includeServerSideToolInvocations"]);return i!=null&&_(r,["includeServerSideToolInvocations"],i),r}function von(e,t){const r={},n=b(e,["functionCallingConfig"]);n!=null&&_(r,["functionCallingConfig"],n);const o=b(e,["retrievalConfig"]);if(o!=null&&_(r,["retrievalConfig"],o),b(e,["includeServerSideToolInvocations"])!==void 0)throw new Error("includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return r}function won(e,t){const r={};if(b(e,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=b(e,["googleMaps"]);n!=null&&_(r,["googleMaps"],Gnn(n));const o=b(e,["mcpServers"]);if(o!=null){let p=o;Array.isArray(p)&&(p=p.map(m=>m)),_(r,["mcpServers"],p)}const i=b(e,["codeExecution"]);i!=null&&_(r,["codeExecution"],i);const s=b(e,["computerUse"]);if(s!=null&&_(r,["computerUse"],s),b(e,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const a=b(e,["functionDeclarations"]);if(a!=null){let p=a;Array.isArray(p)&&(p=p.map(m=>m)),_(r,["functionDeclarations"],p)}const u=b(e,["googleSearch"]);u!=null&&_(r,["googleSearch"],qnn(u));const l=b(e,["googleSearchRetrieval"]);if(l!=null&&_(r,["googleSearchRetrieval"],l),b(e,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const c=b(e,["urlContext"]);c!=null&&_(r,["urlContext"],c);const d=b(e,["fileSearch"]);return d!=null&&_(r,["fileSearch"],d),r}function OWe(e,t){const r={},n=b(e,["retrieval"]);n!=null&&_(r,["retrieval"],n);const o=b(e,["googleMaps"]);o!=null&&_(r,["googleMaps"],o);const i=b(e,["mcpServers"]);if(i!=null){let g=i;Array.isArray(g)&&(g=g.map(y=>Qnn(y))),_(r,["mcpServers"],g)}const s=b(e,["codeExecution"]);s!=null&&_(r,["codeExecution"],s);const a=b(e,["computerUse"]);a!=null&&_(r,["computerUse"],a);const u=b(e,["enterpriseWebSearch"]);u!=null&&_(r,["enterpriseWebSearch"],u);const l=b(e,["exaAiSearch"]);l!=null&&_(r,["exaAiSearch"],l);const c=b(e,["functionDeclarations"]);if(c!=null){let g=c;Array.isArray(g)&&(g=g.map(y=>y)),_(r,["functionDeclarations"],g)}const d=b(e,["googleSearch"]);d!=null&&_(r,["googleSearch"],d);const p=b(e,["googleSearchRetrieval"]);p!=null&&_(r,["googleSearchRetrieval"],p);const m=b(e,["parallelAiSearch"]);m!=null&&_(r,["parallelAiSearch"],m);const h=b(e,["urlContext"]);if(h!=null&&_(r,["urlContext"],h),b(e,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return r}function bon(e,t){const r={},n=b(e,["baseModel"]);n!=null&&_(r,["baseModel"],n);const o=b(e,["createTime"]);o!=null&&_(r,["createTime"],o);const i=b(e,["updateTime"]);return i!=null&&_(r,["updateTime"],i),r}function Ton(e,t){const r={},n=b(e,["labels","google-vertex-llm-tuning-base-model-id"]);n!=null&&_(r,["baseModel"],n);const o=b(e,["createTime"]);o!=null&&_(r,["createTime"],o);const i=b(e,["updateTime"]);return i!=null&&_(r,["updateTime"],i),r}function _on(e,t,r){const n={},o=b(e,["displayName"]);t!==void 0&&o!=null&&_(t,["displayName"],o);const i=b(e,["description"]);t!==void 0&&i!=null&&_(t,["description"],i);const s=b(e,["defaultCheckpointId"]);return t!==void 0&&s!=null&&_(t,["defaultCheckpointId"],s),n}function Eon(e,t,r){const n={},o=b(e,["displayName"]);t!==void 0&&o!=null&&_(t,["displayName"],o);const i=b(e,["description"]);t!==void 0&&i!=null&&_(t,["description"],i);const s=b(e,["defaultCheckpointId"]);return t!==void 0&&s!=null&&_(t,["defaultCheckpointId"],s),n}function Son(e,t,r){const n={},o=b(t,["model"]);o!=null&&_(n,["_url","name"],Qr(e,o));const i=b(t,["config"]);return i!=null&&_on(i,n),n}function kon(e,t,r){const n={},o=b(t,["model"]);o!=null&&_(n,["_url","model"],Qr(e,o));const i=b(t,["config"]);return i!=null&&Eon(i,n),n}function Aon(e,t,r){const n={},o=b(e,["outputGcsUri"]);t!==void 0&&o!=null&&_(t,["parameters","storageUri"],o);const i=b(e,["safetyFilterLevel"]);t!==void 0&&i!=null&&_(t,["parameters","safetySetting"],i);const s=b(e,["personGeneration"]);t!==void 0&&s!=null&&_(t,["parameters","personGeneration"],s);const a=b(e,["includeRaiReason"]);t!==void 0&&a!=null&&_(t,["parameters","includeRaiReason"],a);const u=b(e,["outputMimeType"]);t!==void 0&&u!=null&&_(t,["parameters","outputOptions","mimeType"],u);const l=b(e,["outputCompressionQuality"]);t!==void 0&&l!=null&&_(t,["parameters","outputOptions","compressionQuality"],l);const c=b(e,["enhanceInputImage"]);t!==void 0&&c!=null&&_(t,["parameters","upscaleConfig","enhanceInputImage"],c);const d=b(e,["imagePreservationFactor"]);t!==void 0&&d!=null&&_(t,["parameters","upscaleConfig","imagePreservationFactor"],d);const p=b(e,["labels"]);t!==void 0&&p!=null&&_(t,["labels"],p);const m=b(e,["numberOfImages"]);t!==void 0&&m!=null&&_(t,["parameters","sampleCount"],m);const h=b(e,["mode"]);return t!==void 0&&h!=null&&_(t,["parameters","mode"],h),n}function Con(e,t,r){const n={},o=b(t,["model"]);o!=null&&_(n,["_url","model"],Qr(e,o));const i=b(t,["image"]);i!=null&&_(n,["instances[0]","image"],wc(i));const s=b(t,["upscaleFactor"]);s!=null&&_(n,["parameters","upscaleConfig","upscaleFactor"],s);const a=b(t,["config"]);return a!=null&&Aon(a,n),n}function xon(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["predictions"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(s=>fO(s))),_(r,["generatedImages"],i)}return r}function Ion(e,t){const r={},n=b(e,["uri"]);n!=null&&_(r,["uri"],n);const o=b(e,["encodedVideo"]);o!=null&&_(r,["videoBytes"],n0(o));const i=b(e,["encoding"]);return i!=null&&_(r,["mimeType"],i),r}function Ron(e,t){const r={},n=b(e,["gcsUri"]);n!=null&&_(r,["uri"],n);const o=b(e,["bytesBase64Encoded"]);o!=null&&_(r,["videoBytes"],n0(o));const i=b(e,["mimeType"]);return i!=null&&_(r,["mimeType"],i),r}function Mon(e,t){const r={},n=b(e,["image"]);n!=null&&_(r,["_self"],wc(n));const o=b(e,["maskMode"]);return o!=null&&_(r,["maskMode"],o),r}function Pon(e,t){const r={},n=b(e,["image"]);n!=null&&_(r,["image"],gO(n));const o=b(e,["referenceType"]);return o!=null&&_(r,["referenceType"],o),r}function Don(e,t){const r={},n=b(e,["image"]);n!=null&&_(r,["image"],wc(n));const o=b(e,["referenceType"]);return o!=null&&_(r,["referenceType"],o),r}function NWe(e,t){const r={},n=b(e,["uri"]);n!=null&&_(r,["uri"],n);const o=b(e,["videoBytes"]);o!=null&&_(r,["encodedVideo"],n0(o));const i=b(e,["mimeType"]);return i!=null&&_(r,["encoding"],i),r}function LWe(e,t){const r={},n=b(e,["uri"]);n!=null&&_(r,["gcsUri"],n);const o=b(e,["videoBytes"]);o!=null&&_(r,["bytesBase64Encoded"],n0(o));const i=b(e,["mimeType"]);return i!=null&&_(r,["mimeType"],i),r}function $We(e,t){const r={},n=b(e,["replicatedVoiceConfig"]);n!=null&&_(r,["replicatedVoiceConfig"],lon(n));const o=b(e,["prebuiltVoiceConfig"]);o!=null&&_(r,["prebuiltVoiceConfig"],o);const i=b(e,["voice"]);return i!=null&&_(r,["voice"],i),r}function FWe(e){for(const t of e)if(Oon(t)||typeof t=="object"&&"inputSchema"in t)return!0;return bY}function UWe(e){var t;const r=(t=e[PO])!==null&&t!==void 0?t:"";e[PO]=(r+` ${XJe}`).trimStart()}function Oon(e){return e!==null&&typeof e=="object"&&e instanceof OO}function Non(e){return o0(this,arguments,function*(r,n=100){let o,i=0;for(;i<n;){const s=yield cn(r.listTools({cursor:o}));for(const a of s.tools)yield yield cn(a),i++;if(!s.nextCursor)break;o=s.nextCursor}})}function Lon(e){return e!==null&&typeof e=="object"&&"listTools"in e&&typeof e.listTools=="function"}function $on(...e){if(bY=!0,e.length===0)throw new Error("No MCP clients provided");const t=e[e.length-1];return Lon(t)?OO.create(e,{}):OO.create(e.slice(0,e.length-1),t)}async function Fon(e,t,r){const n=new YX;let o;r.data instanceof Blob?o=JSON.parse(await r.data.text()):o=JSON.parse(r.data),Object.assign(n,o),t(n)}function Uon(e){const t={};return e.forEach((r,n)=>{t[n]=r}),t}function Bon(e){const t=new Headers;for(const[r,n]of Object.entries(e))t.append(r,n);return t}async function zon(e,t,r){const n=new XX;let o;r.data instanceof Blob?o=await r.data.text():r.data instanceof ArrayBuffer?o=new TextDecoder().decode(r.data):o=r.data;const i=JSON.parse(o);if(e.isVertexAI()){const s=Orn(i);Object.assign(n,s)}else Object.assign(n,i);t(n)}function Gon(e){const t={};return e.forEach((r,n)=>{t[n]=r}),t}function qon(e){const t=new Headers;for(const[r,n]of Object.entries(e))t.append(r,n);return t}function BWe(e){var t,r,n;if(!((t=e?.automaticFunctionCalling)===null||t===void 0)&&t.disable)return!0;let o=!1;for(const s of(r=e?.tools)!==null&&r!==void 0?r:[])if(gb(s)){o=!0;break}if(!o)return!0;const i=(n=e?.automaticFunctionCalling)===null||n===void 0?void 0:n.maximumRemoteCalls;return i&&(i<0||!Number.isInteger(i))||i==0?(console.warn("Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:",i),!0):!1}function gb(e){return"callTool"in e&&typeof e.callTool=="function"}function jon(e){var t,r,n;return(n=(r=(t=e.config)===null||t===void 0?void 0:t.tools)===null||r===void 0?void 0:r.some(o=>gb(o)))!==null&&n!==void 0?n:!1}function zWe(e){var t;const r=[];return!((t=e?.config)===null||t===void 0)&&t.tools&&e.config.tools.forEach((n,o)=>{if(gb(n))return;const i=n;i.functionDeclarations&&i.functionDeclarations.length>0&&r.push(o)}),r}function GWe(e){var t;return!(!((t=e?.automaticFunctionCalling)===null||t===void 0)&&t.ignoreCallHistory)}function yO(e,t=!0){return!e||e.automaticContinuation===void 0||e.automaticContinuation===null?t:!!e.automaticContinuation}function mJ(e){return e===void 0||e===PA.CONTINUATION}function qWe(e,t,r,n=!1){return e&&!n&&!!t&&mJ(r)}function Von(e,t,r){var n;const o=(n=e.candidates)===null||n===void 0?void 0:n[0];o?.finishReason!==void 0&&qWe(t,r,o.finishReason)&&(o.finishReason=void 0)}function Hon(e,t){var r;return!!(!((r=t?.abortSignal)===null||r===void 0)&&r.aborted)||e instanceof Error&&e.name==="AbortError"}function jWe(e){return{startToken:e,hasPromptFeedback:!1,hasYieldedContent:!1,receivedAnyChunk:!1}}function Won(e){var t;const r=(t=e?.candidates)===null||t===void 0?void 0:t[0];if(r?.continuationToken&&mJ(r.finishReason))return r.continuationToken}function VWe(e,t,r=!1){const n=e?.automaticContinuation!==void 0&&e?.automaticContinuation!==null,o=r&&n;if(!t&&!o)return e;if(!e)return t?{continuationToken:t}:void 0;const i=Object.assign({},e);return t&&(i.continuationToken=t),o&&delete i.automaticContinuation,i}function Kon(e,t){var r,n;const o=new Map,i=[];for(const s of[...e,...t]){const a=s.modality;o.has(a)||(o.set(a,0),i.push(a)),o.set(a,((r=o.get(a))!==null&&r!==void 0?r:0)+((n=s.tokenCount)!==null&&n!==void 0?n:0))}return i.map(s=>{var a;return{modality:s,tokenCount:(a=o.get(s))!==null&&a!==void 0?a:0}})}function Jon(e,t){const r=new Map,n=[];for(const o of[...e,...t]){const i=o.category;r.has(i)||n.push(i),r.set(i,o)}return n.map(o=>r.get(o))}function HWe(e){if(typeof e!="object"||e===null||Array.isArray(e)||e instanceof a0)return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype||e instanceof bc||e instanceof DX||e instanceof _O}function WWe(e,t){return e.endsWith("TokensDetails")?!0:t.length>0&&typeof t[0]=="object"&&t[0]!==null&&"modality"in t[0]}function Xon(e,t){if(e.length===0)return t;if(t.length===0)return e.map(o=>MA(o,{},!0,!1));const r=[],n=Math.min(e.length,t.length);for(let o=0;o<n;o++)r.push(MA(e[o],t[o],!0,!1));return e.length>n&&r.push(...e.slice(n)),t.length>n&&r.push(...t.slice(n)),r}function vO(e){var t;if(e)return(t=e._initialPromptTokenCount)!==null&&t!==void 0?t:e.promptTokenCount}function RA(e,t){const r=t??vO(e);return r!==void 0&&Object.defineProperty(e,"_initialPromptTokenCount",{value:r,enumerable:!1,configurable:!0,writable:!0}),!(e instanceof _O)&&!Object.prototype.hasOwnProperty.call(e,"initialPromptTokenCount")&&Object.defineProperty(e,"initialPromptTokenCount",{get(){return vO(this)},enumerable:!1,configurable:!0}),e}function KWe(e,t){var r;if(!t)return e&&RA(e);if(!e)return RA(t);const n=(r=vO(e))!==null&&r!==void 0?r:vO(t),o=MA(e,t,!1,!0);return RA(o,n)}function Yon(e,t){const r=t.groundingMetadata,n=r?.groundingSupports;if(!Array.isArray(n)||n.length===0)return t;const o=e.content,i=Array.isArray(o?.parts)?o.parts.length:0,s=e.groundingMetadata,a=Array.isArray(s?.groundingChunks)?s.groundingChunks.length:0;if(i===0&&a===0)return t;const u=n.map(l=>{var c;if(!l||typeof l!="object")return l;const d=Object.assign({},l);return a>0&&Array.isArray(l.groundingChunkIndices)&&l.groundingChunkIndices.length>0&&(d.groundingChunkIndices=l.groundingChunkIndices.map(p=>p+a)),i>0&&l.segment&&typeof l.segment=="object"&&(d.segment=Object.assign(Object.assign({},l.segment),{partIndex:((c=l.segment.partIndex)!==null&&c!==void 0?c:0)+i})),d});return Object.assign(Object.assign({},t),{groundingMetadata:Object.assign(Object.assign({},r),{groundingSupports:u})})}function MA(e,t,r=!1,n=!1){r&&(t=Yon(e,t));const o={},i=new Set([...Object.keys(e),...Object.keys(t)]);for(const s of i){const a=e[s],u=t[s];if(r&&(s==="continuationToken"||s==="finishReason"||s==="finishMessage")){u!==void 0&&(o[s]=u);continue}if(!r&&!n&&s==="candidates"&&Array.isArray(a)){o[s]=Xon(a,Array.isArray(u)?u:[]);continue}if(s==="usageMetadata"){const l=KWe(a,u);l!==void 0&&(o[s]=l);continue}u==null?a!==void 0&&(o[s]=a):a==null?o[s]=u:typeof a=="number"&&typeof u=="number"&&(n||s==="tokenCount"||s.endsWith("TokenCount")||s.endsWith("Count")||s.endsWith("Sum"))?o[s]=a+u:Array.isArray(a)&&Array.isArray(u)?WWe(s,a)||WWe(s,u)?o[s]=Kon(a,u):s==="safetyRatings"?o[s]=Jon(a,u):o[s]=[...a,...u]:HWe(a)&&HWe(u)?o[s]=MA(a,u,!1,s==="usageMetadata"||n):o[s]=u}return o}function Zon(e){if(e.length===0)return new bc;if(e.length===1)return e[0].usageMetadata&&RA(e[0].usageMetadata),e[0];let t=e[0];for(let n=1;n<e.length;n++)t=MA(t,e[n],!1,!1);const r=new bc;return Object.assign(r,t),r}function Qon(e){const t={},r=b(e,["apiKey"]);if(r!=null&&_(t,["apiKey"],r),b(e,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function ein(e){const t={},r=b(e,["parts"]);if(r!=null){let o=r;Array.isArray(o)&&(o=o.map(i=>uin(i))),_(t,["parts"],o)}const n=b(e,["role"]);return n!=null&&_(t,["role"],n),t}function tin(e,t,r){const n={},o=b(t,["expireTime"]);r!==void 0&&o!=null&&_(r,["expireTime"],o);const i=b(t,["newSessionExpireTime"]);r!==void 0&&i!=null&&_(r,["newSessionExpireTime"],i);const s=b(t,["uses"]);r!==void 0&&s!=null&&_(r,["uses"],s);const a=b(t,["liveConnectConstraints"]);r!==void 0&&a!=null&&_(r,["bidiGenerateContentSetup"],ain(e,a));const u=b(t,["lockAdditionalFields"]);return r!==void 0&&u!=null&&_(r,["fieldMask"],u),n}function rin(e,t){const r={},n=b(t,["config"]);return n!=null&&_(r,["config"],tin(e,n,r)),r}function nin(e){const t={},r=b(e,["args"]);r!=null&&_(t,["args"],r);const n=b(e,["id"]);n!=null&&_(t,["id"],n);const o=b(e,["name"]);if(o!=null&&_(t,["name"],o),b(e,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function oin(e){const t={},r=b(e,["authConfig"]);r!=null&&_(t,["authConfig"],Qon(r));const n=b(e,["enableWidget"]);if(n!=null&&_(t,["enableWidget"],n),b(e,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function iin(e){const t={};if(b(e,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const r=b(e,["searchTypes"]);r!=null&&_(t,["searchTypes"],r);const n=b(e,["timeRangeFilter"]);return n!=null&&_(t,["timeRangeFilter"],n),t}function sin(e,t){const r={},n=b(e,["generationConfig"]);t!==void 0&&n!=null&&_(t,["setup","generationConfig"],n);const o=b(e,["responseModalities"]);t!==void 0&&o!=null&&_(t,["setup","generationConfig","responseModalities"],o);const i=b(e,["temperature"]);t!==void 0&&i!=null&&_(t,["setup","generationConfig","temperature"],i);const s=b(e,["topP"]);t!==void 0&&s!=null&&_(t,["setup","generationConfig","topP"],s);const a=b(e,["topK"]);t!==void 0&&a!=null&&_(t,["setup","generationConfig","topK"],a);const u=b(e,["maxOutputTokens"]);t!==void 0&&u!=null&&_(t,["setup","generationConfig","maxOutputTokens"],u);const l=b(e,["mediaResolution"]);t!==void 0&&l!=null&&_(t,["setup","generationConfig","mediaResolution"],l);const c=b(e,["seed"]);t!==void 0&&c!=null&&_(t,["setup","generationConfig","seed"],c);const d=b(e,["speechConfig"]);t!==void 0&&d!=null&&_(t,["setup","generationConfig","speechConfig"],iJ(d));const p=b(e,["thinkingConfig"]);t!==void 0&&p!=null&&_(t,["setup","generationConfig","thinkingConfig"],p);const m=b(e,["enableAffectiveDialog"]);t!==void 0&&m!=null&&_(t,["setup","generationConfig","enableAffectiveDialog"],m);const h=b(e,["systemInstruction"]);t!==void 0&&h!=null&&_(t,["setup","systemInstruction"],ein(Ii(h)));const g=b(e,["tools"]);if(t!==void 0&&g!=null){let P=xh(g);Array.isArray(P)&&(P=P.map(D=>din(Ch(D)))),_(t,["setup","tools"],P)}const y=b(e,["sessionResumption"]);t!==void 0&&y!=null&&_(t,["setup","sessionResumption"],cin(y));const v=b(e,["inputAudioTranscription"]);t!==void 0&&v!=null&&_(t,["setup","inputAudioTranscription"],v);const w=b(e,["outputAudioTranscription"]);t!==void 0&&w!=null&&_(t,["setup","outputAudioTranscription"],w);const T=b(e,["realtimeInputConfig"]);t!==void 0&&T!=null&&_(t,["setup","realtimeInputConfig"],T);const E=b(e,["contextWindowCompression"]);t!==void 0&&E!=null&&_(t,["setup","contextWindowCompression"],E);const k=b(e,["proactivity"]);if(t!==void 0&&k!=null&&_(t,["setup","proactivity"],k),b(e,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const A=b(e,["avatarConfig"]);t!==void 0&&A!=null&&_(t,["setup","avatarConfig"],A);const C=b(e,["safetySettings"]);if(t!==void 0&&C!=null){let P=C;Array.isArray(P)&&(P=P.map(D=>lin(D))),_(t,["setup","safetySettings"],P)}const R=b(e,["translationConfig"]);t!==void 0&&R!=null&&_(t,["setup","generationConfig","translationConfig"],R);const x=b(e,["labels"]);return t!==void 0&&x!=null&&_(t,["setup","labels"],x),r}function ain(e,t){const r={},n=b(t,["model"]);n!=null&&_(r,["setup","model"],Qr(e,n));const o=b(t,["config"]);return o!=null&&_(r,["config"],sin(o,r)),r}function uin(e){const t={},r=b(e,["mediaResolution"]);r!=null&&_(t,["mediaResolution"],r);const n=b(e,["toolCall"]);n!=null&&_(t,["toolCall"],n);const o=b(e,["toolResponse"]);o!=null&&_(t,["toolResponse"],o);const i=b(e,["audioTranscription"]);i!=null&&_(t,["audioTranscription"],i);const s=b(e,["codeExecutionResult"]);s!=null&&_(t,["codeExecutionResult"],s);const a=b(e,["executableCode"]);a!=null&&_(t,["executableCode"],a);const u=b(e,["fileData"]);u!=null&&_(t,["fileData"],u);const l=b(e,["functionCall"]);l!=null&&_(t,["functionCall"],nin(l));const c=b(e,["functionResponse"]);c!=null&&_(t,["functionResponse"],c);const d=b(e,["inlineData"]);d!=null&&_(t,["inlineData"],d);const p=b(e,["text"]);p!=null&&_(t,["text"],p);const m=b(e,["thought"]);m!=null&&_(t,["thought"],m);const h=b(e,["thoughtSignature"]);h!=null&&_(t,["thoughtSignature"],h);const g=b(e,["videoMetadata"]);g!=null&&_(t,["videoMetadata"],g);const y=b(e,["partMetadata"]);y!=null&&_(t,["partMetadata"],y);const v=b(e,["mediaProcessing"]);v!=null&&_(t,["mediaProcessing"],v);const w=b(e,["speechMetadata"]);return w!=null&&_(t,["speechMetadata"],w),t}function lin(e){const t={},r=b(e,["category"]);if(r!=null&&_(t,["category"],r),b(e,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=b(e,["threshold"]);return n!=null&&_(t,["threshold"],n),t}function cin(e){const t={},r=b(e,["handle"]);if(r!=null&&_(t,["handle"],r),b(e,["transparent"])!==void 0)throw new Error("transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}function din(e){const t={};if(b(e,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const r=b(e,["googleMaps"]);r!=null&&_(t,["googleMaps"],oin(r));const n=b(e,["mcpServers"]);if(n!=null){let d=n;Array.isArray(d)&&(d=d.map(p=>p)),_(t,["mcpServers"],d)}const o=b(e,["codeExecution"]);o!=null&&_(t,["codeExecution"],o);const i=b(e,["computerUse"]);if(i!=null&&_(t,["computerUse"],i),b(e,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const s=b(e,["functionDeclarations"]);if(s!=null){let d=s;Array.isArray(d)&&(d=d.map(p=>p)),_(t,["functionDeclarations"],d)}const a=b(e,["googleSearch"]);a!=null&&_(t,["googleSearch"],iin(a));const u=b(e,["googleSearchRetrieval"]);if(u!=null&&_(t,["googleSearchRetrieval"],u),b(e,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const l=b(e,["urlContext"]);l!=null&&_(t,["urlContext"],l);const c=b(e,["fileSearch"]);return c!=null&&_(t,["fileSearch"],c),t}function pin(e){const t=[];for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)){const n=e[r];if(typeof n=="object"&&n!=null&&Object.keys(n).length>0){const o=Object.keys(n).map(i=>`${r}.${i}`);t.push(...o)}else t.push(r)}return t.join(",")}function min(e,t){let r=null;const n=e.bidiGenerateContentSetup;if(typeof n=="object"&&n!==null&&"setup"in n){const i=n.setup;typeof i=="object"&&i!==null?(e.bidiGenerateContentSetup=i,r=i):delete e.bidiGenerateContentSetup}else n!==void 0&&delete e.bidiGenerateContentSetup;const o=e.fieldMask;if(r){const i=pin(r);if(Array.isArray(t?.lockAdditionalFields)&&t?.lockAdditionalFields.length===0)i?e.fieldMask=i:delete e.fieldMask;else if(t?.lockAdditionalFields&&t.lockAdditionalFields.length>0&&o!==null&&Array.isArray(o)&&o.length>0){const s=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"];let a=[];o.length>0&&(a=o.map(l=>s.includes(l)?`generationConfig.${l}`:l));const u=[];i&&u.push(i),a.length>0&&u.push(...a),u.length>0?e.fieldMask=u.join(","):delete e.fieldMask}else delete e.fieldMask}else o!==null&&Array.isArray(o)&&o.length>0?e.fieldMask=o.join(","):delete e.fieldMask;return e}function hin(e,t){const r={},n=b(e,["name"]);return n!=null&&_(r,["_url","name"],n),r}function fin(e,t){const r={},n=b(e,["name"]);return n!=null&&_(r,["_url","name"],n),r}function gin(e,t){const r={},n=b(e,["sdkHttpResponse"]);return n!=null&&_(r,["sdkHttpResponse"],n),r}function yin(e,t){const r={},n=b(e,["sdkHttpResponse"]);return n!=null&&_(r,["sdkHttpResponse"],n),r}function hJ(e,t){const r={},n=b(e,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(s=>Min(s))),_(r,["parts"],i)}const o=b(e,["role"]);return o!=null&&_(r,["role"],o),r}function vin(e,t,r){const n={};if(b(e,["validationDataset"])!==void 0)throw new Error("validationDataset parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=b(e,["tunedModelDisplayName"]);if(t!==void 0&&o!=null&&_(t,["displayName"],o),b(e,["description"])!==void 0)throw new Error("description parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const i=b(e,["epochCount"]);t!==void 0&&i!=null&&_(t,["tuningTask","hyperparameters","epochCount"],i);const s=b(e,["learningRateMultiplier"]);if(s!=null&&_(n,["tuningTask","hyperparameters","learningRateMultiplier"],s),b(e,["exportLastCheckpointOnly"])!==void 0)throw new Error("exportLastCheckpointOnly parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["preTunedModelCheckpointId"])!==void 0)throw new Error("preTunedModelCheckpointId parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["adapterSize"])!==void 0)throw new Error("adapterSize parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["tuningMode"])!==void 0)throw new Error("tuningMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["customBaseModel"])!==void 0)throw new Error("customBaseModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const a=b(e,["batchSize"]);t!==void 0&&a!=null&&_(t,["tuningTask","hyperparameters","batchSize"],a);const u=b(e,["learningRate"]);if(t!==void 0&&u!=null&&_(t,["tuningTask","hyperparameters","learningRate"],u),b(e,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["beta"])!==void 0)throw new Error("beta parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["baseTeacherModel"])!==void 0)throw new Error("baseTeacherModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["tunedTeacherModelSource"])!==void 0)throw new Error("tunedTeacherModelSource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["sftLossWeightMultiplier"])!==void 0)throw new Error("sftLossWeightMultiplier parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["outputUri"])!==void 0)throw new Error("outputUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["rewardConfig"])!==void 0)throw new Error("rewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["compositeRewardConfig"])!==void 0)throw new Error("compositeRewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["samplesPerPrompt"])!==void 0)throw new Error("samplesPerPrompt parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["evaluateInterval"])!==void 0)throw new Error("evaluateInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["checkpointInterval"])!==void 0)throw new Error("checkpointInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["maxOutputTokens"])!==void 0)throw new Error("maxOutputTokens parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["thinkingLevel"])!==void 0)throw new Error("thinkingLevel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["validationDatasetUri"])!==void 0)throw new Error("validationDatasetUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["encryptionSpec"])!==void 0)throw new Error("encryptionSpec parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function win(e,t,r){const n={};let o=b(r,["config","method"]);if(o===void 0&&(o="SUPERVISED_FINE_TUNING"),o==="SUPERVISED_FINE_TUNING"){const N=b(e,["validationDataset"]);t!==void 0&&N!=null&&_(t,["supervisedTuningSpec"],wO(N))}else if(o==="PREFERENCE_TUNING"){const N=b(e,["validationDataset"]);t!==void 0&&N!=null&&_(t,["preferenceOptimizationSpec"],wO(N))}else if(o==="DISTILLATION"){const N=b(e,["validationDataset"]);t!==void 0&&N!=null&&_(t,["distillationSpec"],wO(N))}else if(o==="REINFORCEMENT_TUNING"){const N=b(e,["validationDataset"]);t!==void 0&&N!=null&&_(t,["reinforcementTuningSpec"],wO(N))}const i=b(e,["tunedModelDisplayName"]);t!==void 0&&i!=null&&_(t,["tunedModelDisplayName"],i);const s=b(e,["description"]);t!==void 0&&s!=null&&_(t,["description"],s);let a=b(r,["config","method"]);if(a===void 0&&(a="SUPERVISED_FINE_TUNING"),a==="SUPERVISED_FINE_TUNING"){const N=b(e,["epochCount"]);t!==void 0&&N!=null&&_(t,["supervisedTuningSpec","hyperParameters","epochCount"],N)}else if(a==="PREFERENCE_TUNING"){const N=b(e,["epochCount"]);t!==void 0&&N!=null&&_(t,["preferenceOptimizationSpec","hyperParameters","epochCount"],N)}else if(a==="DISTILLATION"){const N=b(e,["epochCount"]);t!==void 0&&N!=null&&_(t,["distillationSpec","hyperParameters","epochCount"],N)}else if(a==="REINFORCEMENT_TUNING"){const N=b(e,["epochCount"]);t!==void 0&&N!=null&&_(t,["reinforcementTuningSpec","hyperParameters","epochCount"],N)}let u=b(r,["config","method"]);if(u===void 0&&(u="SUPERVISED_FINE_TUNING"),u==="SUPERVISED_FINE_TUNING"){const N=b(e,["learningRateMultiplier"]);t!==void 0&&N!=null&&_(t,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],N)}else if(u==="PREFERENCE_TUNING"){const N=b(e,["learningRateMultiplier"]);t!==void 0&&N!=null&&_(t,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],N)}else if(u==="DISTILLATION"){const N=b(e,["learningRateMultiplier"]);t!==void 0&&N!=null&&_(t,["distillationSpec","hyperParameters","learningRateMultiplier"],N)}else if(u==="REINFORCEMENT_TUNING"){const N=b(e,["learningRateMultiplier"]);t!==void 0&&N!=null&&_(t,["reinforcementTuningSpec","hyperParameters","learningRateMultiplier"],N)}let l=b(r,["config","method"]);if(l===void 0&&(l="SUPERVISED_FINE_TUNING"),l==="SUPERVISED_FINE_TUNING"){const N=b(e,["exportLastCheckpointOnly"]);t!==void 0&&N!=null&&_(t,["supervisedTuningSpec","exportLastCheckpointOnly"],N)}else if(l==="PREFERENCE_TUNING"){const N=b(e,["exportLastCheckpointOnly"]);t!==void 0&&N!=null&&_(t,["preferenceOptimizationSpec","exportLastCheckpointOnly"],N)}else if(l==="DISTILLATION"){const N=b(e,["exportLastCheckpointOnly"]);t!==void 0&&N!=null&&_(t,["distillationSpec","exportLastCheckpointOnly"],N)}let c=b(r,["config","method"]);if(c===void 0&&(c="SUPERVISED_FINE_TUNING"),c==="SUPERVISED_FINE_TUNING"){const N=b(e,["adapterSize"]);t!==void 0&&N!=null&&_(t,["supervisedTuningSpec","hyperParameters","adapterSize"],N)}else if(c==="PREFERENCE_TUNING"){const N=b(e,["adapterSize"]);t!==void 0&&N!=null&&_(t,["preferenceOptimizationSpec","hyperParameters","adapterSize"],N)}else if(c==="DISTILLATION"){const N=b(e,["adapterSize"]);t!==void 0&&N!=null&&_(t,["distillationSpec","hyperParameters","adapterSize"],N)}else if(c==="REINFORCEMENT_TUNING"){const N=b(e,["adapterSize"]);t!==void 0&&N!=null&&_(t,["reinforcementTuningSpec","hyperParameters","adapterSize"],N)}let d=b(r,["config","method"]);if(d===void 0&&(d="SUPERVISED_FINE_TUNING"),d==="SUPERVISED_FINE_TUNING"){const N=b(e,["tuningMode"]);t!==void 0&&N!=null&&_(t,["supervisedTuningSpec","tuningMode"],N)}else if(d==="DISTILLATION"){const N=b(e,["tuningMode"]);t!==void 0&&N!=null&&_(t,["distillationSpec","tuningMode"],N)}const p=b(e,["customBaseModel"]);t!==void 0&&p!=null&&_(t,["customBaseModel"],p);let m=b(r,["config","method"]);if(m===void 0&&(m="SUPERVISED_FINE_TUNING"),m==="SUPERVISED_FINE_TUNING"){const N=b(e,["batchSize"]);t!==void 0&&N!=null&&_(t,["supervisedTuningSpec","hyperParameters","batchSize"],N)}else if(m==="DISTILLATION"){const N=b(e,["batchSize"]);t!==void 0&&N!=null&&_(t,["distillationSpec","hyperParameters","batchSize"],N)}else if(m==="REINFORCEMENT_TUNING"){const N=b(e,["batchSize"]);t!==void 0&&N!=null&&_(t,["reinforcementTuningSpec","hyperParameters","batchSize"],N)}let h=b(r,["config","method"]);if(h===void 0&&(h="SUPERVISED_FINE_TUNING"),h==="SUPERVISED_FINE_TUNING"){const N=b(e,["learningRate"]);t!==void 0&&N!=null&&_(t,["supervisedTuningSpec","hyperParameters","learningRate"],N)}else if(h==="DISTILLATION"){const N=b(e,["learningRate"]);t!==void 0&&N!=null&&_(t,["distillationSpec","hyperParameters","learningRate"],N)}const g=b(e,["labels"]);t!==void 0&&g!=null&&_(t,["labels"],g);const y=b(e,["beta"]);t!==void 0&&y!=null&&_(t,["preferenceOptimizationSpec","hyperParameters","beta"],y);const v=b(e,["baseTeacherModel"]);t!==void 0&&v!=null&&_(t,["distillationSpec","baseTeacherModel"],v);const w=b(e,["tunedTeacherModelSource"]);t!==void 0&&w!=null&&_(t,["distillationSpec","tunedTeacherModelSource"],w);const T=b(e,["sftLossWeightMultiplier"]);t!==void 0&&T!=null&&_(t,["distillationSpec","hyperParameters","sftLossWeightMultiplier"],T);const E=b(e,["outputUri"]);t!==void 0&&E!=null&&_(t,["outputUri"],E);const k=b(e,["rewardConfig"]);t!==void 0&&k!=null&&_(t,["reinforcementTuningSpec","singleRewardConfig"],k);const A=b(e,["compositeRewardConfig"]);t!==void 0&&A!=null&&_(t,["reinforcementTuningSpec","compositeRewardConfig"],A);const C=b(e,["samplesPerPrompt"]);t!==void 0&&C!=null&&_(t,["reinforcementTuningSpec","hyperParameters","samplesPerPrompt"],C);const R=b(e,["evaluateInterval"]);t!==void 0&&R!=null&&_(t,["reinforcementTuningSpec","hyperParameters","evaluateInterval"],R);const x=b(e,["checkpointInterval"]);t!==void 0&&x!=null&&_(t,["reinforcementTuningSpec","hyperParameters","checkpointInterval"],x);const P=b(e,["maxOutputTokens"]);t!==void 0&&P!=null&&_(t,["reinforcementTuningSpec","hyperParameters","maxOutputTokens"],P);const D=b(e,["thinkingLevel"]);t!==void 0&&D!=null&&_(t,["reinforcementTuningSpec","hyperParameters","thinkingLevel"],D);const L=b(e,["validationDatasetUri"]);t!==void 0&&L!=null&&_(t,["reinforcementTuningSpec","validationDatasetUri"],L);const O=b(e,["encryptionSpec"]);return t!==void 0&&O!=null&&_(t,["encryptionSpec"],O),n}function bin(e,t){const r={},n=b(e,["baseModel"]);n!=null&&_(r,["baseModel"],n);const o=b(e,["preTunedModel"]);o!=null&&_(r,["preTunedModel"],o);const i=b(e,["trainingDataset"]);i!=null&&Nin(i);const s=b(e,["config"]);return s!=null&&vin(s,r),r}function Tin(e,t){const r={},n=b(e,["baseModel"]);n!=null&&_(r,["baseModel"],n);const o=b(e,["preTunedModel"]);o!=null&&_(r,["preTunedModel"],o);const i=b(e,["trainingDataset"]);i!=null&&Lin(i,r,t);const s=b(e,["config"]);return s!=null&&win(s,r,t),r}function JWe(e,t){const r={},n=b(e,["epochCount"]);n!=null&&_(r,["epochCount"],n);const o=b(e,["learningRateMultiplier"]);o!=null&&_(r,["learningRateMultiplier"],o);const i=b(e,["adapterSize"]);i!=null&&_(r,["adapterSize"],i);const s=b(e,["batchSize"]);s!=null&&_(r,["batchSize"],s);const a=b(e,["learningRate"]);a!=null&&_(r,["learningRate"],a);const u=b(e,["generationConfig"]);return u!=null&&_(r,["generationConfig"],Sin(u)),r}function _in(e,t){const r={},n=b(e,["promptDatasetUri"]);n!=null&&_(r,["promptDatasetUri"],n);const o=b(e,["validationDatasetUri"]);o!=null&&_(r,["validationDatasetUri"],o);const i=b(e,["baseTeacherModel"]);i!=null&&_(r,["baseTeacherModel"],i);const s=b(e,["tunedTeacherModelSource"]);s!=null&&_(r,["tunedTeacherModelSource"],s);const a=b(e,["hyperparameters"]);return a!=null&&_(r,["hyperparameters"],JWe(a)),r}function Ein(e,t){const r={},n=b(e,["baseTeacherModel"]);n!=null&&_(r,["baseTeacherModel"],n);const o=b(e,["hyperParameters"]);o!=null&&_(r,["hyperParameters"],JWe(o));const i=b(e,["pipelineRootDirectory"]);i!=null&&_(r,["pipelineRootDirectory"],i);const s=b(e,["promptDatasetUri"]);s!=null&&_(r,["promptDatasetUri"],s);const a=b(e,["studentModel"]);a!=null&&_(r,["studentModel"],a);const u=b(e,["trainingDatasetUri"]);u!=null&&_(r,["trainingDatasetUri"],u);const l=b(e,["tunedTeacherModelSource"]);l!=null&&_(r,["tunedTeacherModelSource"],l);const c=b(e,["tuningMode"]);c!=null&&_(r,["tuningMode"],c);const d=b(e,["validationDatasetUri"]);return d!=null&&_(r,["validationDatasetUri"],d),r}function Sin(e,t){const r={},n=b(e,["modelConfig"]);n!=null&&_(r,["modelSelectionConfig"],n);const o=b(e,["responseJsonSchema"]);o!=null&&_(r,["responseJsonSchema"],o);const i=b(e,["audioTranscriptionConfig"]);i!=null&&_(r,["audioTranscriptionConfig"],i);const s=b(e,["audioTimestamp"]);s!=null&&_(r,["audioTimestamp"],s);const a=b(e,["candidateCount"]);a!=null&&_(r,["candidateCount"],a);const u=b(e,["enableAffectiveDialog"]);u!=null&&_(r,["enableAffectiveDialog"],u);const l=b(e,["frequencyPenalty"]);l!=null&&_(r,["frequencyPenalty"],l);const c=b(e,["logprobs"]);c!=null&&_(r,["logprobs"],c);const d=b(e,["maxOutputTokens"]);d!=null&&_(r,["maxOutputTokens"],d);const p=b(e,["mediaResolution"]);p!=null&&_(r,["mediaResolution"],p);const m=b(e,["presencePenalty"]);m!=null&&_(r,["presencePenalty"],m);const h=b(e,["responseFormat"]);if(h!=null){let L=h;Array.isArray(L)&&(L=L.map(O=>O)),_(r,["responseFormat"],L)}const g=b(e,["responseLogprobs"]);g!=null&&_(r,["responseLogprobs"],g);const y=b(e,["responseMimeType"]);y!=null&&_(r,["responseMimeType"],y);const v=b(e,["responseModalities"]);v!=null&&_(r,["responseModalities"],v);const w=b(e,["responseSchema"]);w!=null&&_(r,["responseSchema"],w);const T=b(e,["routingConfig"]);T!=null&&_(r,["routingConfig"],T);const E=b(e,["seed"]);E!=null&&_(r,["seed"],E);const k=b(e,["speechConfig"]);k!=null&&_(r,["speechConfig"],k);const A=b(e,["stopSequences"]);A!=null&&_(r,["stopSequences"],A);const C=b(e,["temperature"]);C!=null&&_(r,["temperature"],C);const R=b(e,["thinkingConfig"]);R!=null&&_(r,["thinkingConfig"],R);const x=b(e,["topK"]);x!=null&&_(r,["topK"],x);const P=b(e,["topP"]);P!=null&&_(r,["topP"],P);const D=b(e,["translationConfig"]);return D!=null&&_(r,["translationConfig"],D),r}function kin(e,t){const r={},n=b(e,["name"]);return n!=null&&_(r,["_url","name"],n),r}function Ain(e,t){const r={},n=b(e,["name"]);return n!=null&&_(r,["_url","name"],n),r}function Cin(e,t,r){const n={},o=b(e,["pageSize"]);t!==void 0&&o!=null&&_(t,["_query","pageSize"],o);const i=b(e,["pageToken"]);t!==void 0&&i!=null&&_(t,["_query","pageToken"],i);const s=b(e,["filter"]);return t!==void 0&&s!=null&&_(t,["_query","filter"],s),n}function xin(e,t){const r={},n=b(e,["config"]);return n!=null&&Cin(n,r),r}function Iin(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["nextPageToken"]);o!=null&&_(r,["nextPageToken"],o);const i=b(e,["tuningJobs"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(a=>fJ(a))),_(r,["tuningJobs"],s)}return r}function Rin(e,t){const r={};if(b(e,["name"])!==void 0)throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(b(e,["streamableHttpTransport"])!==void 0)throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return r}function Min(e,t){const r={},n=b(e,["mediaResolution"]);if(n!=null&&_(r,["mediaResolution"],n),b(e,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(b(e,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const o=b(e,["audioTranscription"]);o!=null&&_(r,["audioTranscription"],o);const i=b(e,["codeExecutionResult"]);i!=null&&_(r,["codeExecutionResult"],i);const s=b(e,["executableCode"]);s!=null&&_(r,["executableCode"],s);const a=b(e,["fileData"]);a!=null&&_(r,["fileData"],a);const u=b(e,["functionCall"]);u!=null&&_(r,["functionCall"],u);const l=b(e,["functionResponse"]);l!=null&&_(r,["functionResponse"],l);const c=b(e,["inlineData"]);c!=null&&_(r,["inlineData"],c);const d=b(e,["text"]);d!=null&&_(r,["text"],d);const p=b(e,["thought"]);p!=null&&_(r,["thought"],p);const m=b(e,["thoughtSignature"]);m!=null&&_(r,["thoughtSignature"],m);const h=b(e,["videoMetadata"]);if(h!=null&&_(r,["videoMetadata"],h),b(e,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const g=b(e,["mediaProcessing"]);g!=null&&_(r,["mediaProcessing"],g);const y=b(e,["speechMetadata"]);return y!=null&&_(r,["speechMetadata"],y),r}function Pin(e,t){const r={},n=b(e,["references"]);n!=null&&_(r,["references"],n);const o=b(e,["contents"]);if(o!=null){let a=o;Array.isArray(a)&&(a=a.map(u=>hJ(u))),_(r,["contents"],a)}const i=b(e,["systemInstruction"]);i!=null&&_(r,["systemInstruction"],hJ(i));const s=b(e,["tools"]);if(s!=null){let a=s;Array.isArray(a)&&(a=a.map(u=>Din(u))),_(r,["tools"],a)}return r}function Din(e,t){const r={},n=b(e,["retrieval"]);n!=null&&_(r,["retrieval"],n);const o=b(e,["googleMaps"]);o!=null&&_(r,["googleMaps"],o);const i=b(e,["mcpServers"]);if(i!=null){let g=i;Array.isArray(g)&&(g=g.map(y=>Rin(y))),_(r,["mcpServers"],g)}const s=b(e,["codeExecution"]);s!=null&&_(r,["codeExecution"],s);const a=b(e,["computerUse"]);a!=null&&_(r,["computerUse"],a);const u=b(e,["enterpriseWebSearch"]);u!=null&&_(r,["enterpriseWebSearch"],u);const l=b(e,["exaAiSearch"]);l!=null&&_(r,["exaAiSearch"],l);const c=b(e,["functionDeclarations"]);if(c!=null){let g=c;Array.isArray(g)&&(g=g.map(y=>y)),_(r,["functionDeclarations"],g)}const d=b(e,["googleSearch"]);d!=null&&_(r,["googleSearch"],d);const p=b(e,["googleSearchRetrieval"]);p!=null&&_(r,["googleSearchRetrieval"],p);const m=b(e,["parallelAiSearch"]);m!=null&&_(r,["parallelAiSearch"],m);const h=b(e,["urlContext"]);if(h!=null&&_(r,["urlContext"],h),b(e,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return r}function Oin(e,t){const r={},n=b(e,["name"]);n!=null&&_(r,["model"],n);const o=b(e,["name"]);return o!=null&&_(r,["endpoint"],o),r}function Nin(e,t){const r={};if(b(e,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(b(e,["vertexDatasetResource"])!==void 0)throw new Error("vertexDatasetResource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=b(e,["examples"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(i=>i)),_(r,["examples","examples"],o)}return r}function Lin(e,t,r){const n={};let o=b(r,["config","method"]);if(o===void 0&&(o="SUPERVISED_FINE_TUNING"),o==="SUPERVISED_FINE_TUNING"){const s=b(e,["gcsUri"]);t!==void 0&&s!=null&&_(t,["supervisedTuningSpec","trainingDatasetUri"],s)}else if(o==="PREFERENCE_TUNING"){const s=b(e,["gcsUri"]);t!==void 0&&s!=null&&_(t,["preferenceOptimizationSpec","trainingDatasetUri"],s)}else if(o==="DISTILLATION"){const s=b(e,["gcsUri"]);t!==void 0&&s!=null&&_(t,["distillationSpec","promptDatasetUri"],s)}else if(o==="REINFORCEMENT_TUNING"){const s=b(e,["gcsUri"]);t!==void 0&&s!=null&&_(t,["reinforcementTuningSpec","trainingDatasetUri"],s)}let i=b(r,["config","method"]);if(i===void 0&&(i="SUPERVISED_FINE_TUNING"),i==="SUPERVISED_FINE_TUNING"){const s=b(e,["vertexDatasetResource"]);t!==void 0&&s!=null&&_(t,["supervisedTuningSpec","trainingDatasetUri"],s)}else if(i==="PREFERENCE_TUNING"){const s=b(e,["vertexDatasetResource"]);t!==void 0&&s!=null&&_(t,["preferenceOptimizationSpec","trainingDatasetUri"],s)}else if(i==="DISTILLATION"){const s=b(e,["vertexDatasetResource"]);t!==void 0&&s!=null&&_(t,["distillationSpec","promptDatasetUri"],s)}else if(i==="REINFORCEMENT_TUNING"){const s=b(e,["vertexDatasetResource"]);t!==void 0&&s!=null&&_(t,["reinforcementTuningSpec","trainingDatasetUri"],s)}if(b(e,["examples"])!==void 0)throw new Error("examples parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function $in(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["name"]);o!=null&&_(r,["name"],o);const i=b(e,["state"]);i!=null&&_(r,["state"],YVe(i));const s=b(e,["createTime"]);s!=null&&_(r,["createTime"],s);const a=b(e,["tuningTask","startTime"]);a!=null&&_(r,["startTime"],a);const u=b(e,["tuningTask","completeTime"]);u!=null&&_(r,["endTime"],u);const l=b(e,["updateTime"]);l!=null&&_(r,["updateTime"],l);const c=b(e,["description"]);c!=null&&_(r,["description"],c);const d=b(e,["baseModel"]);d!=null&&_(r,["baseModel"],d);const p=b(e,["_self"]);return p!=null&&_(r,["tunedModel"],Oin(p)),r}function fJ(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["name"]);o!=null&&_(r,["name"],o);const i=b(e,["state"]);i!=null&&_(r,["state"],YVe(i));const s=b(e,["createTime"]);s!=null&&_(r,["createTime"],s);const a=b(e,["startTime"]);a!=null&&_(r,["startTime"],a);const u=b(e,["endTime"]);u!=null&&_(r,["endTime"],u);const l=b(e,["updateTime"]);l!=null&&_(r,["updateTime"],l);const c=b(e,["error"]);c!=null&&_(r,["error"],c);const d=b(e,["description"]);d!=null&&_(r,["description"],d);const p=b(e,["baseModel"]);p!=null&&_(r,["baseModel"],p);const m=b(e,["tunedModel"]);m!=null&&_(r,["tunedModel"],m);const h=b(e,["preTunedModel"]);h!=null&&_(r,["preTunedModel"],h);const g=b(e,["supervisedTuningSpec"]);g!=null&&_(r,["supervisedTuningSpec"],g);const y=b(e,["preferenceOptimizationSpec"]);y!=null&&_(r,["preferenceOptimizationSpec"],y);const v=b(e,["distillationSamplingSpec"]);v!=null&&_(r,["distillationSamplingSpec"],_in(v));const w=b(e,["distillationSpec"]);w!=null&&_(r,["distillationSpec"],Ein(w));const T=b(e,["reinforcementTuningSpec"]);T!=null&&_(r,["reinforcementTuningSpec"],T);const E=b(e,["tuningDataStats"]);E!=null&&_(r,["tuningDataStats"],E);const k=b(e,["encryptionSpec"]);k!=null&&_(r,["encryptionSpec"],k);const A=b(e,["partnerModelTuningSpec"]);A!=null&&_(r,["partnerModelTuningSpec"],A);const C=b(e,["customBaseModel"]);C!=null&&_(r,["customBaseModel"],C);const R=b(e,["evaluateDatasetRuns"]);if(R!=null){let ne=R;Array.isArray(ne)&&(ne=ne.map(X=>X)),_(r,["evaluateDatasetRuns"],ne)}const x=b(e,["experiment"]);x!=null&&_(r,["experiment"],x);const P=b(e,["fullFineTuningSpec"]);P!=null&&_(r,["fullFineTuningSpec"],P);const D=b(e,["labels"]);D!=null&&_(r,["labels"],D);const L=b(e,["outputUri"]);L!=null&&_(r,["outputUri"],L);const O=b(e,["pipelineJob"]);O!=null&&_(r,["pipelineJob"],O);const N=b(e,["serviceAccount"]);N!=null&&_(r,["serviceAccount"],N);const U=b(e,["tunedModelDisplayName"]);U!=null&&_(r,["tunedModelDisplayName"],U);const $=b(e,["tuningJobMetadata"]);$!=null&&_(r,["tuningJobMetadata"],$);const G=b(e,["tuningJobState"]);G!=null&&_(r,["tuningJobState"],G);const B=b(e,["veoLoraTuningSpec"]);B!=null&&_(r,["veoLoraTuningSpec"],B);const q=b(e,["veoTuningSpec"]);q!=null&&_(r,["veoTuningSpec"],q);const H=b(e,["gcsMetricsUri"]);return H!=null&&_(r,["gcsMetricsUri"],H),r}function Fin(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["name"]);o!=null&&_(r,["name"],o);const i=b(e,["metadata"]);i!=null&&_(r,["metadata"],i);const s=b(e,["done"]);s!=null&&_(r,["done"],s);const a=b(e,["error"]);return a!=null&&_(r,["error"],a),r}function wO(e,t){const r={},n=b(e,["gcsUri"]);n!=null&&_(r,["validationDatasetUri"],n);const o=b(e,["vertexDatasetResource"]);return o!=null&&_(r,["validationDatasetUri"],o),r}function Uin(e,t){const r={},n=b(e,["parent"]);n!=null&&_(r,["_url","parent"],n);const o=b(e,["sampleResponse"]);o!=null&&_(r,["sampleResponse"],hJ(o));const i=b(e,["example"]);i!=null&&_(r,["example"],Pin(i));const s=b(e,["singleRewardConfig"]);s!=null&&_(r,["singleRewardConfig"],s);const a=b(e,["compositeRewardConfig"]);return a!=null&&_(r,["compositeRewardConfig"],a),r}function Bin(e,t){const r={},n=b(e,["sdkHttpResponse"]);n!=null&&_(r,["sdkHttpResponse"],n);const o=b(e,["overallReward"]);o!=null&&_(r,["overallReward"],o);const i=b(e,["error"]);i!=null&&_(r,["error"],i);const s=b(e,["rewardInfoDetails"]);return s!=null&&_(r,["rewardInfoDetails"],s),r}var XWe,Id,gJ,yJ,vJ,wJ,Hp,bJ,TJ,_J,EJ,SJ,kJ,AJ,CJ,xJ,IJ,RJ,MJ,PJ,DJ,OJ,NJ,PA,LJ,$J,FJ,UJ,BJ,zJ,GJ,qJ,DA,jJ,VJ,HJ,WJ,KJ,JJ,XJ,YJ,bO,ZJ,QJ,eX,tX,rX,nX,oX,iX,sX,aX,TO,uX,OA,lX,cX,dX,pX,mX,hX,fX,gX,yX,vX,wX,bX,TX,_X,EX,SX,kX,AX,CX,xX,IX,RX,MX,PX,s0,YWe,ZWe,QWe,eKe,tKe,a0,DX,_O,bc,EO,OX,NX,LX,$X,FX,SO,kO,rKe,nKe,oKe,iKe,sKe,AO,UX,aKe,CO,uKe,lKe,cKe,BX,xO,zX,IO,RO,GX,qX,jX,dKe,VX,HX,WX,KX,JX,pKe,mKe,hKe,MO,fKe,gKe,yKe,vKe,wKe,bKe,TKe,XX,_Ke,EKe,YX,SKe,ZX,Rd,Wp,QX,eY,tY,rY,NA,kKe,AKe,CKe,PO,xKe,IKe,RKe,MKe,PKe,nY,DKe,OKe,NKe,LKe,$Ke,FKe,UKe,BKe,zKe,GKe,qKe,jKe,LA,VKe,HKe,oY,WKe,KKe,$A,JKe,XKe,YKe,u0,iY,FA,sY,aY,uY,Tc,ZKe,Uu,QKe,UA,eJe,tJe,rJe,nJe,oJe,iJe,sJe,aJe,uJe,lJe,lY,cY,cJe,dY,dJe,pY,pJe,mJe,mY,gt,Bu,hY,DO,l0,hJe,BA,fJe,gJe,_c,fY,gY,yY,yJe,zu,Gu,vY,vJe,wJe,bJe,wY,TJe,_Je,fr,EJe,SJe,kJe,AJe,CJe,xJe,IJe,RJe,MJe,PJe,DJe,OJe,NJe,LJe,$Je,FJe,UJe,BJe,zJe,GJe,qJe,jJe,VJe,HJe,WJe,KJe,JJe,XJe,bY,OO,YJe,ZJe,QJe,TY,eXe,_Y,EY,tXe,rXe,yb,SY,kY,nXe,AY,oXe,iXe,sXe,zA=S({"node_modules/.pnpm/@google+genai@2.31.0_@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7_/node_modules/@google/genai/dist/index.mjs"(){XWe=ml(GYr(),1),Id=class{},(function(e){e.MEDIA_PROCESSING_UNSPECIFIED="MEDIA_PROCESSING_UNSPECIFIED",e.STATIC="STATIC",e.AGENTIC="AGENTIC"})(gJ||(gJ={})),(function(e){e.OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",e.OUTCOME_OK="OUTCOME_OK",e.OUTCOME_FAILED="OUTCOME_FAILED",e.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED"})(yJ||(yJ={})),(function(e){e.LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",e.PYTHON="PYTHON"})(vJ||(vJ={})),(function(e){e.SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",e.SILENT="SILENT",e.WHEN_IDLE="WHEN_IDLE",e.INTERRUPT="INTERRUPT"})(wJ||(wJ={})),(function(e){e.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",e.STRING="STRING",e.NUMBER="NUMBER",e.INTEGER="INTEGER",e.BOOLEAN="BOOLEAN",e.ARRAY="ARRAY",e.OBJECT="OBJECT",e.NULL="NULL"})(Hp||(Hp={})),(function(e){e.AUTH_TYPE_UNSPECIFIED="AUTH_TYPE_UNSPECIFIED",e.NO_AUTH="NO_AUTH",e.API_KEY_AUTH="API_KEY_AUTH",e.HTTP_BASIC_AUTH="HTTP_BASIC_AUTH",e.GOOGLE_SERVICE_ACCOUNT_AUTH="GOOGLE_SERVICE_ACCOUNT_AUTH",e.OAUTH="OAUTH",e.OIDC_AUTH="OIDC_AUTH"})(bJ||(bJ={})),(function(e){e.HTTP_IN_UNSPECIFIED="HTTP_IN_UNSPECIFIED",e.HTTP_IN_QUERY="HTTP_IN_QUERY",e.HTTP_IN_HEADER="HTTP_IN_HEADER",e.HTTP_IN_PATH="HTTP_IN_PATH",e.HTTP_IN_BODY="HTTP_IN_BODY",e.HTTP_IN_COOKIE="HTTP_IN_COOKIE"})(TJ||(TJ={})),(function(e){e.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",e.SIMPLE_SEARCH="SIMPLE_SEARCH",e.ELASTIC_SEARCH="ELASTIC_SEARCH"})(_J||(_J={})),(function(e){e.SAFETY_POLICY_UNSPECIFIED="SAFETY_POLICY_UNSPECIFIED",e.FINANCIAL_TRANSACTIONS="FINANCIAL_TRANSACTIONS",e.SENSITIVE_DATA_MODIFICATION="SENSITIVE_DATA_MODIFICATION",e.COMMUNICATION_TOOL="COMMUNICATION_TOOL",e.ACCOUNT_CREATION="ACCOUNT_CREATION",e.DATA_MODIFICATION="DATA_MODIFICATION",e.USER_CONSENT_MANAGEMENT="USER_CONSENT_MANAGEMENT",e.LEGAL_TERMS_AND_AGREEMENTS="LEGAL_TERMS_AND_AGREEMENTS"})(EJ||(EJ={})),(function(e){e.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",e.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER",e.ENVIRONMENT_MOBILE="ENVIRONMENT_MOBILE",e.ENVIRONMENT_DESKTOP="ENVIRONMENT_DESKTOP"})(SJ||(SJ={})),(function(e){e.PHISH_BLOCK_THRESHOLD_UNSPECIFIED="PHISH_BLOCK_THRESHOLD_UNSPECIFIED",e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_HIGH_AND_ABOVE="BLOCK_HIGH_AND_ABOVE",e.BLOCK_HIGHER_AND_ABOVE="BLOCK_HIGHER_AND_ABOVE",e.BLOCK_VERY_HIGH_AND_ABOVE="BLOCK_VERY_HIGH_AND_ABOVE",e.BLOCK_ONLY_EXTREMELY_HIGH="BLOCK_ONLY_EXTREMELY_HIGH"})(kJ||(kJ={})),(function(e){e.UNSPECIFIED="UNSPECIFIED",e.BLOCKING="BLOCKING",e.NON_BLOCKING="NON_BLOCKING"})(AJ||(AJ={})),(function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.MODE_DYNAMIC="MODE_DYNAMIC"})(CJ||(CJ={})),(function(e){e.THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",e.MINIMAL="MINIMAL",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH"})(xJ||(xJ={})),(function(e){e.DONT_ALLOW="DONT_ALLOW",e.ALLOW_ADULT="ALLOW_ADULT",e.ALLOW_ALL="ALLOW_ALL"})(IJ||(IJ={})),(function(e){e.PROMINENT_PEOPLE_UNSPECIFIED="PROMINENT_PEOPLE_UNSPECIFIED",e.ALLOW_PROMINENT_PEOPLE="ALLOW_PROMINENT_PEOPLE",e.BLOCK_PROMINENT_PEOPLE="BLOCK_PROMINENT_PEOPLE"})(RJ||(RJ={})),(function(e){e.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",e.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",e.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",e.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",e.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",e.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY",e.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK",e.HARM_CATEGORY_IMAGE_HATE="HARM_CATEGORY_IMAGE_HATE",e.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT",e.HARM_CATEGORY_IMAGE_HARASSMENT="HARM_CATEGORY_IMAGE_HARASSMENT",e.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"})(MJ||(MJ={})),(function(e){e.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",e.SEVERITY="SEVERITY",e.PROBABILITY="PROBABILITY"})(PJ||(PJ={})),(function(e){e.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",e.BLOCK_NONE="BLOCK_NONE",e.OFF="OFF"})(DJ||(DJ={})),(function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.AUTO="AUTO",e.ANY="ANY",e.NONE="NONE",e.VALIDATED="VALIDATED"})(OJ||(OJ={})),(function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.VERBATIM="VERBATIM",e.SMART="SMART"})(NJ||(NJ={})),(function(e){e.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",e.STOP="STOP",e.MAX_TOKENS="MAX_TOKENS",e.SAFETY="SAFETY",e.RECITATION="RECITATION",e.LANGUAGE="LANGUAGE",e.OTHER="OTHER",e.BLOCKLIST="BLOCKLIST",e.PROHIBITED_CONTENT="PROHIBITED_CONTENT",e.SPII="SPII",e.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",e.IMAGE_SAFETY="IMAGE_SAFETY",e.UNEXPECTED_TOOL_CALL="UNEXPECTED_TOOL_CALL",e.TOO_MANY_TOOL_CALLS="TOO_MANY_TOOL_CALLS",e.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",e.NO_IMAGE="NO_IMAGE",e.IMAGE_RECITATION="IMAGE_RECITATION",e.IMAGE_OTHER="IMAGE_OTHER",e.CONTINUATION="CONTINUATION"})(PA||(PA={})),(function(e){e.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",e.NEGLIGIBLE="NEGLIGIBLE",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH"})(LJ||(LJ={})),(function(e){e.HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",e.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",e.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",e.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",e.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH"})($J||($J={})),(function(e){e.URL_RETRIEVAL_STATUS_UNSPECIFIED="URL_RETRIEVAL_STATUS_UNSPECIFIED",e.URL_RETRIEVAL_STATUS_SUCCESS="URL_RETRIEVAL_STATUS_SUCCESS",e.URL_RETRIEVAL_STATUS_ERROR="URL_RETRIEVAL_STATUS_ERROR",e.URL_RETRIEVAL_STATUS_PAYWALL="URL_RETRIEVAL_STATUS_PAYWALL",e.URL_RETRIEVAL_STATUS_UNSAFE="URL_RETRIEVAL_STATUS_UNSAFE"})(FJ||(FJ={})),(function(e){e.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",e.SAFETY="SAFETY",e.OTHER="OTHER",e.BLOCKLIST="BLOCKLIST",e.PROHIBITED_CONTENT="PROHIBITED_CONTENT",e.IMAGE_SAFETY="IMAGE_SAFETY",e.MODEL_ARMOR="MODEL_ARMOR",e.JAILBREAK="JAILBREAK"})(UJ||(UJ={})),(function(e){e.TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",e.ON_DEMAND="ON_DEMAND",e.ON_DEMAND_PRIORITY="ON_DEMAND_PRIORITY",e.ON_DEMAND_FLEX="ON_DEMAND_FLEX",e.ON_DEMAND_OFFPEAK="ON_DEMAND_OFFPEAK",e.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT"})(BJ||(BJ={})),(function(e){e.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",e.TEXT="TEXT",e.IMAGE="IMAGE",e.VIDEO="VIDEO",e.AUDIO="AUDIO",e.DOCUMENT="DOCUMENT"})(zJ||(zJ={})),(function(e){e.MODEL_STAGE_UNSPECIFIED="MODEL_STAGE_UNSPECIFIED",e.UNSTABLE_EXPERIMENTAL="UNSTABLE_EXPERIMENTAL",e.EXPERIMENTAL="EXPERIMENTAL",e.PREVIEW="PREVIEW",e.STABLE="STABLE",e.LEGACY="LEGACY",e.DEPRECATED="DEPRECATED",e.RETIRED="RETIRED"})(GJ||(GJ={})),(function(e){e.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",e.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",e.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",e.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH"})(qJ||(qJ={})),(function(e){e.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",e.TEXT="TEXT",e.IMAGE="IMAGE",e.AUDIO="AUDIO",e.VIDEO="VIDEO"})(DA||(DA={})),(function(e){e.DELIVERY_UNSPECIFIED="DELIVERY_UNSPECIFIED",e.INLINE="INLINE",e.URI="URI"})(jJ||(jJ={})),(function(e){e.ASPECT_RATIO_UNSPECIFIED="ASPECT_RATIO_UNSPECIFIED",e.ASPECT_RATIO_ONE_BY_ONE="ASPECT_RATIO_ONE_BY_ONE",e.ASPECT_RATIO_TWO_BY_THREE="ASPECT_RATIO_TWO_BY_THREE",e.ASPECT_RATIO_THREE_BY_TWO="ASPECT_RATIO_THREE_BY_TWO",e.ASPECT_RATIO_THREE_BY_FOUR="ASPECT_RATIO_THREE_BY_FOUR",e.ASPECT_RATIO_FOUR_BY_THREE="ASPECT_RATIO_FOUR_BY_THREE",e.ASPECT_RATIO_FOUR_BY_FIVE="ASPECT_RATIO_FOUR_BY_FIVE",e.ASPECT_RATIO_FIVE_BY_FOUR="ASPECT_RATIO_FIVE_BY_FOUR",e.ASPECT_RATIO_NINE_BY_SIXTEEN="ASPECT_RATIO_NINE_BY_SIXTEEN",e.ASPECT_RATIO_SIXTEEN_BY_NINE="ASPECT_RATIO_SIXTEEN_BY_NINE",e.ASPECT_RATIO_TWENTY_ONE_BY_NINE="ASPECT_RATIO_TWENTY_ONE_BY_NINE",e.ASPECT_RATIO_ONE_BY_EIGHT="ASPECT_RATIO_ONE_BY_EIGHT",e.ASPECT_RATIO_EIGHT_BY_ONE="ASPECT_RATIO_EIGHT_BY_ONE",e.ASPECT_RATIO_ONE_BY_FOUR="ASPECT_RATIO_ONE_BY_FOUR",e.ASPECT_RATIO_FOUR_BY_ONE="ASPECT_RATIO_FOUR_BY_ONE"})(VJ||(VJ={})),(function(e){e.IMAGE_SIZE_UNSPECIFIED="IMAGE_SIZE_UNSPECIFIED",e.IMAGE_SIZE_FIVE_TWELVE="IMAGE_SIZE_FIVE_TWELVE",e.IMAGE_SIZE_ONE_K="IMAGE_SIZE_ONE_K",e.IMAGE_SIZE_TWO_K="IMAGE_SIZE_TWO_K",e.IMAGE_SIZE_FOUR_K="IMAGE_SIZE_FOUR_K"})(HJ||(HJ={})),(function(e){e.TUNING_MODE_UNSPECIFIED="TUNING_MODE_UNSPECIFIED",e.TUNING_MODE_FULL="TUNING_MODE_FULL",e.TUNING_MODE_PEFT_ADAPTER="TUNING_MODE_PEFT_ADAPTER"})(WJ||(WJ={})),(function(e){e.ADAPTER_SIZE_UNSPECIFIED="ADAPTER_SIZE_UNSPECIFIED",e.ADAPTER_SIZE_ONE="ADAPTER_SIZE_ONE",e.ADAPTER_SIZE_TWO="ADAPTER_SIZE_TWO",e.ADAPTER_SIZE_FOUR="ADAPTER_SIZE_FOUR",e.ADAPTER_SIZE_EIGHT="ADAPTER_SIZE_EIGHT",e.ADAPTER_SIZE_SIXTEEN="ADAPTER_SIZE_SIXTEEN",e.ADAPTER_SIZE_THIRTY_TWO="ADAPTER_SIZE_THIRTY_TWO"})(KJ||(KJ={})),(function(e){e.RESPONSE_PARSE_TYPE_UNSPECIFIED="RESPONSE_PARSE_TYPE_UNSPECIFIED",e.IDENTITY="IDENTITY",e.REGEX_EXTRACT="REGEX_EXTRACT"})(JJ||(JJ={})),(function(e){e.MATCH_OPERATION_UNSPECIFIED="MATCH_OPERATION_UNSPECIFIED",e.REGEX_CONTAINS="REGEX_CONTAINS",e.PARTIAL_MATCH="PARTIAL_MATCH",e.EXACT_MATCH="EXACT_MATCH"})(XJ||(XJ={})),(function(e){e.REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED="REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED",e.MINIMAL="MINIMAL",e.HIGH="HIGH"})(YJ||(YJ={})),(function(e){e.JOB_STATE_UNSPECIFIED="JOB_STATE_UNSPECIFIED",e.JOB_STATE_QUEUED="JOB_STATE_QUEUED",e.JOB_STATE_PENDING="JOB_STATE_PENDING",e.JOB_STATE_RUNNING="JOB_STATE_RUNNING",e.JOB_STATE_SUCCEEDED="JOB_STATE_SUCCEEDED",e.JOB_STATE_FAILED="JOB_STATE_FAILED",e.JOB_STATE_CANCELLING="JOB_STATE_CANCELLING",e.JOB_STATE_CANCELLED="JOB_STATE_CANCELLED",e.JOB_STATE_PAUSED="JOB_STATE_PAUSED",e.JOB_STATE_EXPIRED="JOB_STATE_EXPIRED",e.JOB_STATE_UPDATING="JOB_STATE_UPDATING",e.JOB_STATE_PARTIALLY_SUCCEEDED="JOB_STATE_PARTIALLY_SUCCEEDED"})(bO||(bO={})),(function(e){e.TUNING_JOB_STATE_UNSPECIFIED="TUNING_JOB_STATE_UNSPECIFIED",e.TUNING_JOB_STATE_WAITING_FOR_QUOTA="TUNING_JOB_STATE_WAITING_FOR_QUOTA",e.TUNING_JOB_STATE_PROCESSING_DATASET="TUNING_JOB_STATE_PROCESSING_DATASET",e.TUNING_JOB_STATE_WAITING_FOR_CAPACITY="TUNING_JOB_STATE_WAITING_FOR_CAPACITY",e.TUNING_JOB_STATE_TUNING="TUNING_JOB_STATE_TUNING",e.TUNING_JOB_STATE_POST_PROCESSING="TUNING_JOB_STATE_POST_PROCESSING"})(ZJ||(ZJ={})),(function(e){e.AGGREGATION_METRIC_UNSPECIFIED="AGGREGATION_METRIC_UNSPECIFIED",e.AVERAGE="AVERAGE",e.MODE="MODE",e.STANDARD_DEVIATION="STANDARD_DEVIATION",e.VARIANCE="VARIANCE",e.MINIMUM="MINIMUM",e.MAXIMUM="MAXIMUM",e.MEDIAN="MEDIAN",e.PERCENTILE_P90="PERCENTILE_P90",e.PERCENTILE_P95="PERCENTILE_P95",e.PERCENTILE_P99="PERCENTILE_P99"})(QJ||(QJ={})),(function(e){e.PAIRWISE_CHOICE_UNSPECIFIED="PAIRWISE_CHOICE_UNSPECIFIED",e.BASELINE="BASELINE",e.CANDIDATE="CANDIDATE",e.TIE="TIE"})(eX||(eX={})),(function(e){e.VIDEO_ORIENTATION_UNSPECIFIED="VIDEO_ORIENTATION_UNSPECIFIED",e.LANDSCAPE="LANDSCAPE",e.PORTRAIT="PORTRAIT"})(tX||(tX={})),(function(e){e.TUNING_SPEED_UNSPECIFIED="TUNING_SPEED_UNSPECIFIED",e.REGULAR="REGULAR",e.FAST="FAST"})(rX||(rX={})),(function(e){e.TUNING_TASK_UNSPECIFIED="TUNING_TASK_UNSPECIFIED",e.TUNING_TASK_I2V="TUNING_TASK_I2V",e.TUNING_TASK_T2V="TUNING_TASK_T2V",e.TUNING_TASK_R2V="TUNING_TASK_R2V"})(nX||(nX={})),(function(e){e.STATE_UNSPECIFIED="STATE_UNSPECIFIED",e.STATE_PENDING="STATE_PENDING",e.STATE_ACTIVE="STATE_ACTIVE",e.STATE_FAILED="STATE_FAILED"})(oX||(oX={})),(function(e){e.UNSPECIFIED="unspecified",e.FLEX="flex",e.STANDARD="standard",e.PRIORITY="priority"})(iX||(iX={})),(function(e){e.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",e.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",e.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",e.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",e.MEDIA_RESOLUTION_ULTRA_HIGH="MEDIA_RESOLUTION_ULTRA_HIGH"})(sX||(sX={})),(function(e){e.TOOL_TYPE_UNSPECIFIED="TOOL_TYPE_UNSPECIFIED",e.GOOGLE_SEARCH_WEB="GOOGLE_SEARCH_WEB",e.GOOGLE_SEARCH_IMAGE="GOOGLE_SEARCH_IMAGE",e.URL_CONTEXT="URL_CONTEXT",e.GOOGLE_MAPS="GOOGLE_MAPS",e.FILE_SEARCH="FILE_SEARCH",e.MEDIA_PROCESSING="MEDIA_PROCESSING"})(aX||(aX={})),(function(e){e.COLLECTION="COLLECTION"})(TO||(TO={})),(function(e){e.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",e.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",e.BALANCED="BALANCED",e.PRIORITIZE_COST="PRIORITIZE_COST"})(uX||(uX={})),(function(e){e.PREDICT="PREDICT",e.EMBED_CONTENT="EMBED_CONTENT"})(OA||(OA={})),(function(e){e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",e.BLOCK_NONE="BLOCK_NONE"})(lX||(lX={})),(function(e){e.auto="auto",e.en="en",e.ja="ja",e.ko="ko",e.hi="hi",e.zh="zh",e.pt="pt",e.es="es"})(cX||(cX={})),(function(e){e.MASK_MODE_DEFAULT="MASK_MODE_DEFAULT",e.MASK_MODE_USER_PROVIDED="MASK_MODE_USER_PROVIDED",e.MASK_MODE_BACKGROUND="MASK_MODE_BACKGROUND",e.MASK_MODE_FOREGROUND="MASK_MODE_FOREGROUND",e.MASK_MODE_SEMANTIC="MASK_MODE_SEMANTIC"})(dX||(dX={})),(function(e){e.CONTROL_TYPE_DEFAULT="CONTROL_TYPE_DEFAULT",e.CONTROL_TYPE_CANNY="CONTROL_TYPE_CANNY",e.CONTROL_TYPE_SCRIBBLE="CONTROL_TYPE_SCRIBBLE",e.CONTROL_TYPE_FACE_MESH="CONTROL_TYPE_FACE_MESH"})(pX||(pX={})),(function(e){e.SUBJECT_TYPE_DEFAULT="SUBJECT_TYPE_DEFAULT",e.SUBJECT_TYPE_PERSON="SUBJECT_TYPE_PERSON",e.SUBJECT_TYPE_ANIMAL="SUBJECT_TYPE_ANIMAL",e.SUBJECT_TYPE_PRODUCT="SUBJECT_TYPE_PRODUCT"})(mX||(mX={})),(function(e){e.EDIT_MODE_DEFAULT="EDIT_MODE_DEFAULT",e.EDIT_MODE_INPAINT_REMOVAL="EDIT_MODE_INPAINT_REMOVAL",e.EDIT_MODE_INPAINT_INSERTION="EDIT_MODE_INPAINT_INSERTION",e.EDIT_MODE_OUTPAINT="EDIT_MODE_OUTPAINT",e.EDIT_MODE_CONTROLLED_EDITING="EDIT_MODE_CONTROLLED_EDITING",e.EDIT_MODE_STYLE="EDIT_MODE_STYLE",e.EDIT_MODE_BGSWAP="EDIT_MODE_BGSWAP",e.EDIT_MODE_PRODUCT_IMAGE="EDIT_MODE_PRODUCT_IMAGE"})(hX||(hX={})),(function(e){e.FOREGROUND="FOREGROUND",e.BACKGROUND="BACKGROUND",e.PROMPT="PROMPT",e.SEMANTIC="SEMANTIC",e.INTERACTIVE="INTERACTIVE"})(fX||(fX={})),(function(e){e.ASSET="ASSET",e.STYLE="STYLE"})(gX||(gX={})),(function(e){e.INSERT="INSERT",e.REMOVE="REMOVE",e.REMOVE_STATIC="REMOVE_STATIC",e.OUTPAINT="OUTPAINT"})(yX||(yX={})),(function(e){e.OPTIMIZED="OPTIMIZED",e.LOSSLESS="LOSSLESS"})(vX||(vX={})),(function(e){e.CROP="CROP",e.PAD="PAD"})(wX||(wX={})),(function(e){e.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",e.PREFERENCE_TUNING="PREFERENCE_TUNING",e.DISTILLATION="DISTILLATION",e.REINFORCEMENT_TUNING="REINFORCEMENT_TUNING"})(bX||(bX={})),(function(e){e.STATE_UNSPECIFIED="STATE_UNSPECIFIED",e.PROCESSING="PROCESSING",e.ACTIVE="ACTIVE",e.FAILED="FAILED"})(TX||(TX={})),(function(e){e.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",e.UPLOADED="UPLOADED",e.GENERATED="GENERATED",e.REGISTERED="REGISTERED"})(_X||(_X={})),(function(e){e.TURN_COMPLETE_REASON_UNSPECIFIED="TURN_COMPLETE_REASON_UNSPECIFIED",e.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",e.RESPONSE_REJECTED="RESPONSE_REJECTED",e.NEED_MORE_INPUT="NEED_MORE_INPUT",e.PROHIBITED_INPUT_CONTENT="PROHIBITED_INPUT_CONTENT",e.IMAGE_PROHIBITED_INPUT_CONTENT="IMAGE_PROHIBITED_INPUT_CONTENT",e.INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED="INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED",e.INPUT_IMAGE_CELEBRITY="INPUT_IMAGE_CELEBRITY",e.INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED="INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED",e.INPUT_TEXT_NCII_PROHIBITED="INPUT_TEXT_NCII_PROHIBITED",e.INPUT_OTHER="INPUT_OTHER",e.INPUT_IP_PROHIBITED="INPUT_IP_PROHIBITED",e.BLOCKLIST="BLOCKLIST",e.UNSAFE_PROMPT_FOR_IMAGE_GENERATION="UNSAFE_PROMPT_FOR_IMAGE_GENERATION",e.GENERATED_IMAGE_SAFETY="GENERATED_IMAGE_SAFETY",e.GENERATED_CONTENT_SAFETY="GENERATED_CONTENT_SAFETY",e.GENERATED_AUDIO_SAFETY="GENERATED_AUDIO_SAFETY",e.GENERATED_VIDEO_SAFETY="GENERATED_VIDEO_SAFETY",e.GENERATED_CONTENT_PROHIBITED="GENERATED_CONTENT_PROHIBITED",e.GENERATED_CONTENT_BLOCKLIST="GENERATED_CONTENT_BLOCKLIST",e.GENERATED_IMAGE_PROHIBITED="GENERATED_IMAGE_PROHIBITED",e.GENERATED_IMAGE_CELEBRITY="GENERATED_IMAGE_CELEBRITY",e.GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER="GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER",e.GENERATED_IMAGE_IDENTIFIABLE_PEOPLE="GENERATED_IMAGE_IDENTIFIABLE_PEOPLE",e.GENERATED_IMAGE_MINORS="GENERATED_IMAGE_MINORS",e.OUTPUT_IMAGE_IP_PROHIBITED="OUTPUT_IMAGE_IP_PROHIBITED",e.GENERATED_OTHER="GENERATED_OTHER",e.MAX_REGENERATION_REACHED="MAX_REGENERATION_REACHED"})(EX||(EX={})),(function(e){e.INTERACTION_STATUS_UNSPECIFIED="INTERACTION_STATUS_UNSPECIFIED",e.IN_PROGRESS="IN_PROGRESS",e.REQUIRES_ACTION="REQUIRES_ACTION",e.IDLE="IDLE"})(SX||(SX={})),(function(e){e.VAD_SIGNAL_TYPE_UNSPECIFIED="VAD_SIGNAL_TYPE_UNSPECIFIED",e.VAD_SIGNAL_TYPE_SOS="VAD_SIGNAL_TYPE_SOS",e.VAD_SIGNAL_TYPE_EOS="VAD_SIGNAL_TYPE_EOS"})(kX||(kX={})),(function(e){e.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",e.ACTIVITY_START="ACTIVITY_START",e.ACTIVITY_END="ACTIVITY_END"})(AX||(AX={})),(function(e){e.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",e.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",e.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"})(CX||(CX={})),(function(e){e.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",e.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",e.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"})(xX||(xX={})),(function(e){e.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",e.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",e.NO_INTERRUPTION="NO_INTERRUPTION"})(IX||(IX={})),(function(e){e.TURN_COVERAGE_UNSPECIFIED="TURN_COVERAGE_UNSPECIFIED",e.TURN_INCLUDES_ONLY_ACTIVITY="TURN_INCLUDES_ONLY_ACTIVITY",e.TURN_INCLUDES_ALL_INPUT="TURN_INCLUDES_ALL_INPUT",e.TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO="TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO"})(RX||(RX={})),(function(e){e.SCALE_UNSPECIFIED="SCALE_UNSPECIFIED",e.C_MAJOR_A_MINOR="C_MAJOR_A_MINOR",e.D_FLAT_MAJOR_B_FLAT_MINOR="D_FLAT_MAJOR_B_FLAT_MINOR",e.D_MAJOR_B_MINOR="D_MAJOR_B_MINOR",e.E_FLAT_MAJOR_C_MINOR="E_FLAT_MAJOR_C_MINOR",e.E_MAJOR_D_FLAT_MINOR="E_MAJOR_D_FLAT_MINOR",e.F_MAJOR_D_MINOR="F_MAJOR_D_MINOR",e.G_FLAT_MAJOR_E_FLAT_MINOR="G_FLAT_MAJOR_E_FLAT_MINOR",e.G_MAJOR_E_MINOR="G_MAJOR_E_MINOR",e.A_FLAT_MAJOR_F_MINOR="A_FLAT_MAJOR_F_MINOR",e.A_MAJOR_G_FLAT_MINOR="A_MAJOR_G_FLAT_MINOR",e.B_FLAT_MAJOR_G_MINOR="B_FLAT_MAJOR_G_MINOR",e.B_MAJOR_A_FLAT_MINOR="B_MAJOR_A_FLAT_MINOR"})(MX||(MX={})),(function(e){e.MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",e.QUALITY="QUALITY",e.DIVERSITY="DIVERSITY",e.VOCALIZATION="VOCALIZATION"})(PX||(PX={})),(function(e){e.PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",e.PLAY="PLAY",e.PAUSE="PAUSE",e.STOP="STOP",e.RESET_CONTEXT="RESET_CONTEXT"})(s0||(s0={})),YWe=class{},ZWe=class{},QWe=class{},eKe=class{},tKe=class{},a0=class{constructor(e){const t={};for(const r of e.headers.entries())t[r[0]]=r[1];this.headers=t,this.responseInternal=e}json(){return this.responseInternal.json()}},DX=class{},_O=class{},bc=class{get text(){var e,t,r,n,o,i,s,a;if(((n=(r=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||r===void 0?void 0:r.parts)===null||n===void 0?void 0:n.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning text from the first one.");let u="",l=!1;const c=[];for(const d of(a=(s=(i=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||i===void 0?void 0:i.content)===null||s===void 0?void 0:s.parts)!==null&&a!==void 0?a:[]){for(const[p,m]of Object.entries(d))p!=="text"&&p!=="thought"&&p!=="thoughtSignature"&&(m!==null||m!==void 0)&&c.push(p);if(typeof d.text=="string"){if(typeof d.thought=="boolean"&&d.thought)continue;l=!0,u+=d.text}}return c.length>0&&console.warn(`there are non-text parts ${c} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),l?u:void 0}get data(){var e,t,r,n,o,i,s,a;if(((n=(r=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||r===void 0?void 0:r.parts)===null||n===void 0?void 0:n.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning data from the first one.");let u="";const l=[];for(const c of(a=(s=(i=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||i===void 0?void 0:i.content)===null||s===void 0?void 0:s.parts)!==null&&a!==void 0?a:[]){for(const[d,p]of Object.entries(c))d!=="inlineData"&&(p!==null||p!==void 0)&&l.push(d);c.inlineData&&typeof c.inlineData.data=="string"&&(u+=atob(c.inlineData.data))}return l.length>0&&console.warn(`there are non-data parts ${l} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),u.length>0?btoa(u):void 0}get functionCalls(){var e,t,r,n,o,i,s,a;if(((n=(r=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||r===void 0?void 0:r.parts)===null||n===void 0?void 0:n.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning function calls from the first one.");const u=(a=(s=(i=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||i===void 0?void 0:i.content)===null||s===void 0?void 0:s.parts)===null||a===void 0?void 0:a.filter(l=>l.functionCall).map(l=>l.functionCall).filter(l=>l!==void 0);if(u?.length!==0)return u}get executableCode(){var e,t,r,n,o,i,s,a,u;if(((n=(r=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||r===void 0?void 0:r.parts)===null||n===void 0?void 0:n.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning executable code from the first one.");const l=(a=(s=(i=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||i===void 0?void 0:i.content)===null||s===void 0?void 0:s.parts)===null||a===void 0?void 0:a.filter(c=>c.executableCode).map(c=>c.executableCode).filter(c=>c!==void 0);if(l?.length!==0)return(u=l?.[0])===null||u===void 0?void 0:u.code}get codeExecutionResult(){var e,t,r,n,o,i,s,a,u;if(((n=(r=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||r===void 0?void 0:r.parts)===null||n===void 0?void 0:n.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning code execution result from the first one.");const l=(a=(s=(i=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||i===void 0?void 0:i.content)===null||s===void 0?void 0:s.parts)===null||a===void 0?void 0:a.filter(c=>c.codeExecutionResult).map(c=>c.codeExecutionResult).filter(c=>c!==void 0);if(l?.length!==0)return(u=l?.[0])===null||u===void 0?void 0:u.output}get initialPromptTokenCount(){var e;if(this.usageMetadata)return(e=this.usageMetadata._initialPromptTokenCount)!==null&&e!==void 0?e:this.usageMetadata.promptTokenCount}},EO=class{},OX=class{},NX=class{},LX=class{},$X=class{},FX=class{},SO=class{},kO=class{},rKe=class{},nKe=class{},oKe=class{},iKe=class{},sKe=class{},AO=class{},UX=class{},aKe=class{},CO=class i5r{_fromAPIResponse({apiResponse:t,_isVertexAI:r}){const n=new i5r;let o;const i=t;return r?o=WYr(i):o=HYr(i),Object.assign(n,o),n}},uKe=class{},lKe=class{},cKe=class{},BX=class{},xO=class{},zX=class{},IO=class{},RO=class{},GX=class{},qX=class{},jX=class{},dKe=class{},VX=class s5r{_fromAPIResponse({apiResponse:t,_isVertexAI:r}){const n=new s5r,i=eZr(t);return Object.assign(n,i),n}},HX=class{},WX=class{},KX=class{},JX=class{},pKe=class{},mKe=class{},hKe=class{},MO=class{},fKe=class{},gKe=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_RAW",referenceImage:this.referenceImage,referenceId:this.referenceId}}},yKe=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_MASK",referenceImage:this.referenceImage,referenceId:this.referenceId,maskImageConfig:this.config}}},vKe=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_CONTROL",referenceImage:this.referenceImage,referenceId:this.referenceId,controlImageConfig:this.config}}},wKe=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_STYLE",referenceImage:this.referenceImage,referenceId:this.referenceId,styleImageConfig:this.config}}},bKe=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_SUBJECT",referenceImage:this.referenceImage,referenceId:this.referenceId,subjectImageConfig:this.config}}},TKe=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_CONTENT",referenceImage:this.referenceImage,referenceId:this.referenceId}}},XX=class{get text(){var e,t,r;let n="",o=!1;const i=[];for(const s of(r=(t=(e=this.serverContent)===null||e===void 0?void 0:e.modelTurn)===null||t===void 0?void 0:t.parts)!==null&&r!==void 0?r:[]){for(const[a,u]of Object.entries(s))a!=="text"&&a!=="thought"&&u!==null&&i.push(a);if(typeof s.text=="string"){if(typeof s.thought=="boolean"&&s.thought)continue;o=!0,n+=s.text}}return i.length>0&&console.warn(`there are non-text parts ${i} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),o?n:void 0}get data(){var e,t,r;let n="";const o=[];for(const i of(r=(t=(e=this.serverContent)===null||e===void 0?void 0:e.modelTurn)===null||t===void 0?void 0:t.parts)!==null&&r!==void 0?r:[]){for(const[s,a]of Object.entries(i))s!=="inlineData"&&a!==null&&o.push(s);i.inlineData&&typeof i.inlineData.data=="string"&&(n+=atob(i.inlineData.data))}return o.length>0&&console.warn(`there are non-data parts ${o} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),n.length>0?btoa(n):void 0}},_Ke=class{},EKe=class{constructor(){this.functionResponses=[]}},YX=class{get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}},SKe=class{},ZX=class a5r{_fromAPIResponse({apiResponse:t,_isVertexAI:r}){const n=new a5r,i=BVe(t);return Object.assign(n,i),n}},(function(e){e.PAGED_ITEM_BATCH_JOBS="batchJobs",e.PAGED_ITEM_MODELS="models",e.PAGED_ITEM_TUNING_JOBS="tuningJobs",e.PAGED_ITEM_FILES="files",e.PAGED_ITEM_CACHED_CONTENTS="cachedContents",e.PAGED_ITEM_FILE_SEARCH_STORES="fileSearchStores",e.PAGED_ITEM_DOCUMENTS="documents",e.PAGED_ITEM_SKILLS="skills"})(Rd||(Rd={})),Wp=class{constructor(e,t,r,n){this.pageInternal=[],this.paramsInternal={},this.requestInternal=t,this.init(e,r,n)}init(e,t,r){var n,o;this.nameInternal=e,this.pageInternal=t[this.nameInternal]||[],this.sdkHttpResponseInternal=t?.sdkHttpResponse,this.idxInternal=0;let i={config:{}};!r||Object.keys(r).length===0?i={config:{}}:typeof r=="object"?i=Object.assign({},r):i=r,i.config&&(i.config.pageToken=t.nextPageToken),this.paramsInternal=i,this.pageInternalSize=(o=(n=i.config)===null||n===void 0?void 0:n.pageSize)!==null&&o!==void 0?o:this.pageInternal.length}initNextPage(e){this.init(this.nameInternal,e,this.paramsInternal)}get page(){return this.pageInternal}get name(){return this.nameInternal}get pageSize(){return this.pageInternalSize}get sdkHttpResponse(){return this.sdkHttpResponseInternal}get params(){return this.paramsInternal}get pageLength(){return this.pageInternal.length}getItem(e){return this.pageInternal[e]}[Symbol.asyncIterator](){return{next:async()=>{if(this.idxInternal>=this.pageLength)if(this.hasNextPage())await this.nextPage();else return{value:void 0,done:!0};const e=this.getItem(this.idxInternal);return this.idxInternal+=1,{value:e,done:!1}},return:async()=>({value:void 0,done:!0})}}async nextPage(){if(!this.hasNextPage())throw new Error("No more pages to fetch.");const e=await this.requestInternal(this.params);return this.initNextPage(e),this.page}hasNextPage(){var e;return((e=this.params.config)===null||e===void 0?void 0:e.pageToken)!==void 0}},QX=class extends Id{constructor(e){super(),this.apiClient=e,this.list=async(t={})=>new Wp(Rd.PAGED_ITEM_BATCH_JOBS,r=>this.listInternal(r),await this.listInternal(t),t),this.create=async t=>(this.apiClient.isVertexAI()&&(t.config=this.formatDestination(t.src,t.config)),this.createInternal(t)),this.createEmbeddings=async t=>{if(console.warn("batches.createEmbeddings() is experimental and may change without notice."),this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support batches.createEmbeddings.");return this.createEmbeddingsInternal(t)}}createInlinedGenerateContentRequest(e){const t=iHe(this.apiClient,e),r=t._url,n=ct("{model}:batchGenerateContent",r),s=t.batch.inputConfig.requests,a=s.requests,u=[];for(const l of a){const c=Object.assign({},l);if(c.systemInstruction){const d=c.systemInstruction;delete c.systemInstruction;const p=c.request;p.systemInstruction=d,c.request=p}u.push(c)}return s.requests=u,delete t.config,delete t._url,delete t._query,{path:n,body:t}}getGcsUri(e){if(typeof e=="string")return e.startsWith("gs://")?e:void 0;if(!Array.isArray(e)&&e.gcsUri&&e.gcsUri.length>0)return e.gcsUri[0]}getBigqueryUri(e){if(typeof e=="string")return e.startsWith("bq://")?e:void 0;if(!Array.isArray(e))return e.bigqueryUri}formatDestination(e,t){const r=t?Object.assign({},t):{},n=Date.now().toString();if(r.displayName||(r.displayName=`genaiBatchJob_${n}`),r.dest===void 0){const o=this.getGcsUri(e),i=this.getBigqueryUri(e);if(o)o.endsWith(".jsonl")?r.dest=`${o.slice(0,-6)}/dest`:r.dest=`${o}_dest_${n}`;else if(i)r.dest=`${i}_dest_${n}`;else throw new Error("Unsupported source for Gemini Enterprise Agent Platform (previously known as Vertex AI): No GCS or BigQuery URI found.")}return r}async createInternal(e){var t,r,n,o;let i,s="",a={};if(this.apiClient.isVertexAI()){const u=FZr(this.apiClient,e);return s=ct("batchPredictionJobs",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json()),i.then(l=>sJ(l))}else{const u=iHe(this.apiClient,e);return s=ct("{model}:batchGenerateContent",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(l=>l.json()),i.then(l=>dO(l))}}async createEmbeddingsInternal(e){var t,r;let n,o="",i={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=BZr(this.apiClient,e);return o=ct("{model}:asyncBatchEmbedContent",s._url),i=s._query,delete s._url,delete s._query,n=this.apiClient.request({path:o,queryParams:i,body:JSON.stringify(s),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(a=>a.json()),n.then(a=>dO(a))}}async get(e){var t,r,n,o;let i,s="",a={};if(this.apiClient.isVertexAI()){const u=QZr(this.apiClient,e);return s=ct("batchPredictionJobs/{name}",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json()),i.then(l=>sJ(l))}else{const u=ZZr(this.apiClient,e);return s=ct("batches/{name}",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(l=>l.json()),i.then(l=>dO(l))}}async cancel(e){var t,r,n,o;let i="",s={};if(this.apiClient.isVertexAI()){const a=DZr(this.apiClient,e);i=ct("batchPredictionJobs/{name}:cancel",a._url),s=a._query,delete a._url,delete a._query,await this.apiClient.request({path:i,queryParams:s,body:JSON.stringify(a),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal})}else{const a=PZr(this.apiClient,e);i=ct("batches/{name}:cancel",a._url),s=a._query,delete a._url,delete a._query,await this.apiClient.request({path:i,queryParams:s,body:JSON.stringify(a),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal})}}async listInternal(e){var t,r,n,o;let i,s="",a={};if(this.apiClient.isVertexAI()){const u=uQr(e);return s=ct("batchPredictionJobs",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json().then(c=>{const d=c;return d.sdkHttpResponse={headers:l.headers},d})),i.then(l=>{const c=cQr(l),d=new MO;return Object.assign(d,c),d})}else{const u=aQr(e);return s=ct("batches",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(l=>l.json().then(c=>{const d=c;return d.sdkHttpResponse={headers:l.headers},d})),i.then(l=>{const c=lQr(l),d=new MO;return Object.assign(d,c),d})}}async delete(e){var t,r,n,o;let i,s="",a={};if(this.apiClient.isVertexAI()){const u=GZr(this.apiClient,e);return s=ct("batchPredictionJobs/{name}",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json().then(c=>{const d=c;return d.sdkHttpResponse={headers:l.headers},d})),i.then(l=>jZr(l))}else{const u=zZr(this.apiClient,e);return s=ct("batches/{name}",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(l=>l.json().then(c=>{const d=c;return d.sdkHttpResponse={headers:l.headers},d})),i.then(l=>qZr(l))}}},eY=class extends Id{constructor(e){super(),this.apiClient=e,this.list=async(t={})=>new Wp(Rd.PAGED_ITEM_CACHED_CONTENTS,r=>this.listInternal(r),await this.listInternal(t),t)}async create(e){var t,r,n,o;let i,s="",a={};if(this.apiClient.isVertexAI()){const u=TQr(this.apiClient,e);return s=ct("cachedContents",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json()),i.then(l=>l)}else{const u=bQr(this.apiClient,e);return s=ct("cachedContents",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(l=>l.json()),i.then(l=>l)}}async get(e){var t,r,n,o;let i,s="",a={};if(this.apiClient.isVertexAI()){const u=IQr(this.apiClient,e);return s=ct("{name}",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json()),i.then(l=>l)}else{const u=xQr(this.apiClient,e);return s=ct("{name}",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(l=>l.json()),i.then(l=>l)}}async delete(e){var t,r,n,o;let i,s="",a={};if(this.apiClient.isVertexAI()){const u=EQr(this.apiClient,e);return s=ct("{name}",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json().then(c=>{const d=c;return d.sdkHttpResponse={headers:l.headers},d})),i.then(l=>{const c=kQr(l),d=new IO;return Object.assign(d,c),d})}else{const u=_Qr(this.apiClient,e);return s=ct("{name}",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(l=>l.json().then(c=>{const d=c;return d.sdkHttpResponse={headers:l.headers},d})),i.then(l=>{const c=SQr(l),d=new IO;return Object.assign(d,c),d})}}async update(e){var t,r,n,o;let i,s="",a={};if(this.apiClient.isVertexAI()){const u=KQr(this.apiClient,e);return s=ct("{name}",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"PATCH",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json()),i.then(l=>l)}else{const u=WQr(this.apiClient,e);return s=ct("{name}",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"PATCH",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(l=>l.json()),i.then(l=>l)}}async listInternal(e){var t,r,n,o;let i,s="",a={};if(this.apiClient.isVertexAI()){const u=NQr(e);return s=ct("cachedContents",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json().then(c=>{const d=c;return d.sdkHttpResponse={headers:l.headers},d})),i.then(l=>{const c=$Qr(l),d=new RO;return Object.assign(d,c),d})}else{const u=OQr(e);return s=ct("cachedContents",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(l=>l.json().then(c=>{const d=c;return d.sdkHttpResponse={headers:l.headers},d})),i.then(l=>{const c=LQr(l),d=new RO;return Object.assign(d,c),d})}}},tY=class{constructor(e,t){this.modelsModule=e,this.apiClient=t}create(e){return new rY(this.apiClient,this.modelsModule,e.model,e.config,structuredClone(e.history))}},rY=class{constructor(e,t,r,n={},o=[]){this.apiClient=e,this.modelsModule=t,this.model=r,this.config=n,this.history=o,this.sendPromise=Promise.resolve(),XQr(o)}async sendMessage(e){var t;await this.sendPromise;const r=Ii(e.message),n=this.modelsModule.generateContent({model:this.model,contents:this.getHistory(!0).concat(r),config:(t=e.config)!==null&&t!==void 0?t:this.config});return this.sendPromise=(async()=>{var o,i,s;const a=await n,u=(i=(o=a.candidates)===null||o===void 0?void 0:o[0])===null||i===void 0?void 0:i.content,l=a.automaticFunctionCallingHistory,c=this.getHistory(!0).length;let d=[];l!=null&&(d=(s=l.slice(c))!==null&&s!==void 0?s:[]);const p=u?[u]:[];this.recordHistory(r,p,d)})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),n}async sendMessageStream(e){var t;await this.sendPromise;const r=Ii(e.message),n=this.modelsModule.generateContentStream({model:this.model,contents:this.getHistory(!0).concat(r),config:(t=e.config)!==null&&t!==void 0?t:this.config});this.sendPromise=n.then(()=>{}).catch(()=>{});const o=await n;return this.processStreamResponse(o,r)}getHistory(e=!1){const t=e?cHe(this.history):this.history;return structuredClone(t)}processStreamResponse(e,t){return o0(this,arguments,function*(){var n,o,i,s,a,u,l,c;const d=[];let p=!0,m=!1;try{for(var h=!0,g=pb(e),y;y=yield cn(g.next()),n=y.done,!n;h=!0){s=y.value,h=!1;const v=s;if(JQr(v)){const w=(u=(a=v.candidates)===null||a===void 0?void 0:a[0])===null||u===void 0?void 0:u.content;w!==void 0&&d.push(w)}else p=!1;((c=(l=v.candidates)===null||l===void 0?void 0:l[0])===null||c===void 0?void 0:c.finishReason)!==void 0&&(m=!0),yield yield cn(v)}}catch(v){o={error:v}}finally{try{!h&&!n&&(i=g.return)&&(yield cn(i.call(g)))}finally{if(o)throw o.error}}this.recordHistory(t,p&&m?d:[])})}recordHistory(e,t,r){let n=[];t.length>0&&t.every(o=>o.role!==void 0)?n=t:n.push({role:"model",parts:[]}),r&&r.length>0?this.history.push(...cHe(r)):this.history.push(e),this.history.push(...n)}},NA=class u5r extends Error{constructor(t){super(t.message),this.name="ApiError",this.status=t.status,Object.setPrototypeOf(this,u5r.prototype)}},kKe="Content-Type",AKe="X-Server-Timeout",CKe="User-Agent",PO="x-goog-api-client",xKe="2.31.0",IKe=`google-genai-sdk/${xKe}`,RKe="v1beta1",MKe="v1beta",PKe=new Set(["us","eu"]),nY=Symbol.for("undici.globalDispatcher.1"),DKe=5,OKe=1,NKe=60,LKe=2,$Ke=1,FKe=[408,429,500,502,503,504],UKe=class{constructor(e){var t,r,n;this.clientOptions=Object.assign({},e),this.customBaseUrl=(t=e.httpOptions)===null||t===void 0?void 0:t.baseUrl;const o={};if(this.clientOptions.vertexai){if(!this.clientOptions.location&&!this.clientOptions.apiKey&&!this.customBaseUrl&&(this.clientOptions.location="global"),!(this.clientOptions.project&&this.clientOptions.location||this.clientOptions.apiKey)&&!this.customBaseUrl)throw new Error("Authentication is not set up. Please provide either a project and location, or an API key, or a custom base URL.");const s=e.project&&e.location||!!e.apiKey;this.customBaseUrl&&!s?(o.baseUrl=this.customBaseUrl,this.clientOptions.project=void 0,this.clientOptions.location=void 0):this.clientOptions.apiKey&&!this.clientOptions.project||this.clientOptions.location==="global"?o.baseUrl="https://aiplatform.googleapis.com/":this.clientOptions.project&&this.clientOptions.location&&PKe.has(this.clientOptions.location)?o.baseUrl=`https://aiplatform.${this.clientOptions.location}.rep.googleapis.com/`:this.clientOptions.project&&this.clientOptions.location&&(o.baseUrl=`https://${this.clientOptions.location}-aiplatform.googleapis.com/`),o.apiVersion=(r=this.clientOptions.apiVersion)!==null&&r!==void 0?r:RKe}else this.clientOptions.apiKey||console.warn("API key should be set when using the Gemini API."),o.apiVersion=(n=this.clientOptions.apiVersion)!==null&&n!==void 0?n:MKe,o.baseUrl="https://generativelanguage.googleapis.com/";o.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=o,e.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(o,e.httpOptions))}isVertexAI(){var e;return(e=this.clientOptions.vertexai)!==null&&e!==void 0?e:!1}getProject(){return this.clientOptions.project}getLocation(){return this.clientOptions.location}getCustomBaseUrl(){return this.customBaseUrl}async getAuthHeaders(){const e=new Headers;return await this.clientOptions.auth.addAuthHeaders(e),e}getApiVersion(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.apiVersion!==void 0)return this.clientOptions.httpOptions.apiVersion;throw new Error("API version is not set.")}getBaseUrl(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.baseUrl!==void 0)return this.clientOptions.httpOptions.baseUrl;throw new Error("Base URL is not set.")}getRequestUrl(){return this.getRequestUrlInternal(this.clientOptions.httpOptions)}getHeaders(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.headers!==void 0)return this.clientOptions.httpOptions.headers;throw new Error("Headers are not set.")}getFetch(){var e;return(e=this.clientOptions.httpOptions)===null||e===void 0?void 0:e.fetch}getTimeout(){var e;return(e=this.clientOptions.httpOptions)===null||e===void 0?void 0:e.timeout}getRequestUrlInternal(e){if(!e||e.baseUrl===void 0||e.apiVersion===void 0)throw new Error("HTTP options are not correctly set.");const r=[e.baseUrl.endsWith("/")?e.baseUrl.slice(0,-1):e.baseUrl];return e.apiVersion&&e.apiVersion!==""&&r.push(e.apiVersion),r.join("/")}getBaseResourcePath(){return`projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`}getApiKey(){return this.clientOptions.apiKey}getWebsocketBaseUrl(){const e=this.getBaseUrl(),t=new URL(e);return t.protocol=t.protocol=="http:"?"ws":"wss",t.toString()}setBaseUrl(e){if(this.clientOptions.httpOptions)this.clientOptions.httpOptions.baseUrl=e;else throw new Error("HTTP options are not correctly set.")}constructUrl(e,t,r){const n=[this.getRequestUrlInternal(t)];return r&&n.push(this.getBaseResourcePath()),e!==""&&n.push(e),new URL(`${n.join("/")}`)}shouldPrependVertexProjectPath(e,t){return!(t.baseUrl&&t.baseUrlResourceScope===TO.COLLECTION||!this.clientOptions.vertexai||!this.clientOptions.project||!this.clientOptions.location||e.path.startsWith("projects/")||e.httpMethod==="GET"&&e.path.startsWith("publishers/google/models"))}async request(e){let t=this.clientOptions.httpOptions;e.httpOptions&&(t=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));const r=this.shouldPrependVertexProjectPath(e,t),n=this.constructUrl(e.path,t,r);if(e.queryParams)for(const[i,s]of Object.entries(e.queryParams))n.searchParams.append(i,String(s));let o={};if(e.httpMethod==="GET"){if(e.body&&e.body!=="{}")throw new Error("Request body should be empty for GET request, but got non empty request body")}else o.body=e.body;return o=await this.includeExtraHttpOptionsToRequestInit(o,t,n.toString()),this.unaryApiCall(n,o,e.httpMethod,t.retryOptions,t.timeout,e.abortSignal,t.fetch)}patchHttpOptions(e,t){const r=JSON.parse(JSON.stringify(e));e.fetch&&(r.fetch=e.fetch);for(const[n,o]of Object.entries(t))typeof o=="object"?r[n]=Object.assign(Object.assign({},r[n]),o):o!==void 0&&(r[n]=o);return r}async requestStream(e){let t=this.clientOptions.httpOptions;e.httpOptions&&(t=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));const r=this.shouldPrependVertexProjectPath(e,t),n=this.constructUrl(e.path,t,r);(!n.searchParams.has("alt")||n.searchParams.get("alt")!=="sse")&&n.searchParams.set("alt","sse");let o={};return o.body=e.body,o=await this.includeExtraHttpOptionsToRequestInit(o,t,n.toString()),this.streamApiCall(n,o,e.httpMethod,t.retryOptions,t.timeout,e.abortSignal,t.fetch)}async includeExtraHttpOptionsToRequestInit(e,t,r){return den()&&!t?.fetch&&!("dispatcher"in e)&&(e.dispatcher=pen()),t&&t.extraBody!==null&&hen(e,t.extraBody),e.headers=await this.getHeadersInternal(t,r),e}async unaryApiCall(e,t,r,n,o,i,s){return this.apiCall(e.toString(),Object.assign(Object.assign({},t),{method:r}),n,o,i,s).then(async a=>(await aJ(a),new a0(a))).catch(a=>{throw a instanceof Error?a:new Error(`exception ${a} sending request`,{cause:a})})}async streamApiCall(e,t,r,n,o,i,s){return this.apiCall(e.toString(),Object.assign(Object.assign({},t),{method:r}),n,o,i,s).then(async a=>(await aJ(a),this.processStreamResponse(a))).catch(a=>{throw a instanceof Error?a:new Error(`exception ${a} sending request`,{cause:a})})}processStreamResponse(e){return o0(this,arguments,function*(){var r;const n=(r=e?.body)===null||r===void 0?void 0:r.getReader(),o=new TextDecoder("utf-8");if(!n)throw new Error("Response body is empty");try{let i="";const s="data:",a=[`
124
124
 
125
125
  `,"\r\r",`\r
126
126
  \r
@@ -1154,9 +1154,9 @@ Audio processing failed. Error: ${n instanceof Error?n.message:String(n)}`}}asyn
1154
1154
  - ARCHIVE (zip): Use entry_path to extract a specific file from the archive
1155
1155
  - TEXT/CODE: Use page_range as line range for targeted reading
1156
1156
 
1157
- For video extraction, the result includes images (frames) that will be visible to you. Always call list_attached_files first to discover file IDs.`,inputSchema:M.object({file_id:M.string().describe("File ID (UUID) or exact filename from list_attached_files"),start_time:M.number().optional().describe("Start timestamp in seconds (video only)"),end_time:M.number().optional().describe("End timestamp in seconds (video only)"),frame_count:M.number().int().min(1).max(20).optional().describe("Number of frames to extract in time range (video only, default: 5, max: 20)"),pages:M.array(M.number().int().min(1)).optional().describe("Specific page/slide numbers to extract (1-indexed)"),page_range:M.object({start:M.number().int().min(1),end:M.number().int().min(1)}).optional().describe("Page/slide range to extract (1-indexed, inclusive)"),sheet:M.string().optional().describe("Sheet name or 0-based index as string e.g. '0', '1' (spreadsheet only, default: first sheet)"),row_range:M.object({start:M.number().int().min(1),end:M.number().int().min(1)}).optional().describe("Row range (1-indexed, spreadsheet only)"),columns:M.array(M.string()).optional().describe("Specific column letters to include (e.g., ['A', 'B', 'D'], spreadsheet only)"),entry_path:M.string().optional().describe("File path within archive to extract (archive only)"),format:M.enum(["text","detailed","summary"]).optional().describe("Output format hint (default: text)")}),execute:async t=>{try{const r={...t,sheet:t.sheet!==void 0?/^\d+$/.test(t.sheet)?parseInt(t.sheet,10):t.sheet:void 0},n=await e.extractContent(r);return n.success?{success:!0,text:n.text,metadata:n.metadata,imageCount:n.images?.length??0,_images:n.images,error:void 0}:{success:!1,error:n.error,text:void 0,metadata:void 0,imageCount:0,_images:void 0}}catch(r){return{success:!1,error:r instanceof Error?r.message:String(r),text:void 0,metadata:void 0,imageCount:0,_images:void 0}}},toModelOutput:({output:t})=>{const r=[];if(t.text?r.push({type:"text",text:t.text}):t.error&&r.push({type:"text",text:`Error: ${t.error}`}),t._images&&t._images.length>0)for(const n of t._images)r.push({type:"image-data",data:n.toString("base64"),mediaType:"image/jpeg"});return r.length===0&&r.push({type:"text",text:"(No content extracted)"}),{type:"content",value:r}}}}function ier(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(2)} GB`}var wyn=S({"src/lib/files/fileTools.ts"(){"use strict";mn(),Sl()}}),LT,v1,Yae,ser=S({"src/lib/hitl/hitlManager.ts"(){"use strict";so(),qt(),Kk(),z(),LT=3e4,v1=!1,Yae=class extends bn{config;pendingConfirmations=new Map;statistics={totalRequests:0,pendingRequests:0,averageResponseTime:0,approvedRequests:0,rejectedRequests:0,timedOutRequests:0};constructor(e){super(),this.config=this.validateConfig(e),this.setupEventHandlers()}validateConfig(e){const t={enabled:e.enabled,dangerousActions:e.dangerousActions,timeout:e.timeout??LT,confirmationMethod:e.confirmationMethod??"event",allowArgumentModification:e.allowArgumentModification??v1,autoApproveOnTimeout:e.autoApproveOnTimeout??!1,autoApproveExclusions:Array.isArray(e.autoApproveExclusions)?[...e.autoApproveExclusions]:e.autoApproveExclusions??[],auditLogging:e.auditLogging??!1,customRules:e.customRules??[],confirmBuiltinTools:e.confirmBuiltinTools??!0};if(!t.enabled)return t;if(!Array.isArray(t.dangerousActions))throw new Jw("dangerousActions must be an array of strings");if(!Array.isArray(t.autoApproveExclusions)||t.autoApproveExclusions.some(r=>typeof r!="string"||r.length===0))throw new Jw("autoApproveExclusions must be an array of non-empty tool names");if(typeof t.timeout!="number"||t.timeout<=0)throw new Jw("timeout must be a positive number (milliseconds)");if(t.confirmationMethod!=="event")throw new Jw("confirmationMethod must be 'event' (only supported method)");if(typeof t.allowArgumentModification!="boolean")throw new Jw("allowArgumentModification must be a boolean");return t}requiresConfirmation(e,t){if(!this.config.enabled)return!1;const r=e.toLowerCase();for(const n of this.config.dangerousActions)if(r.includes(n.toLowerCase()))return!0;if(this.config.customRules){for(const n of this.config.customRules)if(n.requiresConfirmation)try{if(n.condition(e,t))return!0}catch(o){this.logAuditEvent("rule-evaluation-error",{ruleName:n.name,toolName:e,error:o instanceof Error?o.message:String(o)})}}return!1}async requestConfirmation(e,t,r){const n=this.generateConfirmationId(),o=Date.now();return this.statistics.totalRequests++,this.statistics.pendingRequests++,new Promise((i,s)=>{const a=setTimeout(()=>{this.handleTimeout(n)},this.config.timeout),u={confirmationId:n,toolName:e,arguments:t,timestamp:o,timeoutHandle:a,resolve:i,reject:s};this.pendingConfirmations.set(n,u);const l={type:"hitl:confirmation-request",payload:{confirmationId:n,toolName:e,serverId:r?.serverId,actionType:this.generateActionDescription(e,t),arguments:t,metadata:{timestamp:new Date(o).toISOString(),sessionId:r?.sessionId,userId:r?.userId,dangerousKeywords:this.getTriggeredKeywords(e,t)},timeoutMs:this.config.timeout??LT,allowModification:this.config.allowArgumentModification??v1}};this.emit("hitl:confirmation-request",l),this.config.auditLogging&&this.logAuditEvent("confirmation-requested",{confirmationId:n,toolName:e,userId:r?.userId,sessionId:r?.sessionId,timestamp:o,arguments:t})})}processUserResponse(e,t){const r=this.pendingConfirmations.get(e);if(!r){f.warn(`No pending confirmation found for ID: ${e}`);return}clearTimeout(r.timeoutHandle),this.pendingConfirmations.delete(e),this.statistics.pendingRequests--;const n=t.responseTime||Date.now()-r.timestamp;t.approved?this.statistics.approvedRequests++:this.statistics.rejectedRequests++;const o=this.statistics.approvedRequests+this.statistics.rejectedRequests;this.statistics.averageResponseTime=(this.statistics.averageResponseTime*(o-1)+n)/o;const i={approved:t.approved,reason:t.reason,modifiedArguments:t.modifiedArguments,responseTime:n};this.config.auditLogging&&this.logAuditEvent(t.approved?"confirmation-approved":"confirmation-rejected",{confirmationId:e,toolName:r.toolName,approved:t.approved,reason:t.reason,userId:t.userId,responseTime:n,arguments:r.arguments}),r.resolve(i)}handleTimeout(e){const t=this.pendingConfirmations.get(e);if(!t)return;this.pendingConfirmations.delete(e),this.statistics.pendingRequests--,this.statistics.timedOutRequests++;const r=Date.now()-t.timestamp,n=this.config.autoApproveOnTimeout===!0&&!this.config.autoApproveExclusions?.includes(t.toolName);this.config.auditLogging&&this.logAuditEvent("confirmation-timeout",{confirmationId:e,toolName:t.toolName,timeout:this.config.timeout??LT,arguments:t.arguments,autoApproved:n});const o={type:"hitl:timeout",payload:{confirmationId:e,toolName:t.toolName,timeout:this.config.timeout??LT}};if(this.emit("hitl:timeout",o),n){this.statistics.approvedRequests++;const i=this.statistics.approvedRequests+this.statistics.rejectedRequests;this.statistics.averageResponseTime=(this.statistics.averageResponseTime*(i-1)+r)/i,this.config.auditLogging&&this.logAuditEvent("confirmation-auto-approved",{confirmationId:e,toolName:t.toolName,reason:"Auto-approved due to timeout",responseTime:r,arguments:t.arguments});const s={approved:!0,reason:"Auto-approved due to timeout",responseTime:r};t.resolve(s)}else t.reject(new Wk(`Confirmation timeout for tool: ${t.toolName}`,e,this.config.timeout??LT))}setupEventHandlers(){this.on("hitl:confirmation-response",e=>{e.payload?.confirmationId&&this.processUserResponse(e.payload.confirmationId,{approved:e.payload.approved,reason:e.payload.reason,modifiedArguments:e.payload.modifiedArguments,responseTime:e.payload.metadata?.responseTime,userId:e.payload.metadata?.userId})})}generateConfirmationId(){return`hitl-${Date.now()}-${st()}`}generateActionDescription(e,t){const r=e.toLowerCase();if(r.includes("delete"))return"Delete Operation";if(r.includes("remove"))return"Remove Operation";if(r.includes("update"))return"Update Operation";if(r.includes("create"))return"Create Operation";if(r.includes("drop"))return"Drop Operation";if(r.includes("truncate"))return"Truncate Operation";if(r.includes("restart"))return"Restart Operation";if(r.includes("stop"))return"Stop Operation";if(r.includes("kill"))return"Kill Operation";if(this.config.customRules)for(const n of this.config.customRules)try{if(n.condition(e,t)&&n.customMessage)return n.customMessage}catch{}return`Execute ${e}`}getTriggeredKeywords(e,t){const r=[],n=e.toLowerCase();for(const o of this.config.dangerousActions)n.includes(o.toLowerCase())&&r.push(o);if(this.config.customRules)for(const o of this.config.customRules)try{o.requiresConfirmation&&o.condition(e,t)&&r.push(o.name)}catch{}return r}logAuditEvent(e,t){const r={timestamp:new Date().toISOString(),eventType:e,toolName:t.toolName,userId:t.userId,sessionId:t.sessionId,arguments:t.arguments,reason:t.reason,responseTime:t.responseTime,...t};f.info(`[HITL Audit] ${e}:`,r),this.emit("hitl:audit",r)}getStatistics(){return{...this.statistics}}getConfig(){return{...this.config,autoApproveExclusions:Array.isArray(this.config.autoApproveExclusions)?[...this.config.autoApproveExclusions]:this.config.autoApproveExclusions}}updateConfig(e){const t={...this.config,...e};this.config=this.validateConfig(t),this.config.auditLogging&&this.logAuditEvent("configuration-updated",{oldConfig:this.config,newConfig:t})}cleanup(){for(const[e,t]of this.pendingConfirmations)clearTimeout(t.timeoutHandle),t.reject(new Error(`HITL cleanup: confirmation ${e} cancelled`));this.pendingConfirmations.clear(),this.statistics.pendingRequests=0,this.config.auditLogging&&this.logAuditEvent("manager-cleanup",{clearedConfirmations:this.pendingConfirmations.size})}isEnabled(){return this.config.enabled}getPendingCount(){return this.pendingConfirmations.size}hasPendingConfirmation(e){return this.pendingConfirmations.has(e)}}}}),v6,aer,Zae,w6,uer,byn=S({"src/lib/mcp/batching/requestBatcher.ts"(){"use strict";so(),z(),et(),Mr(),nr(),v6=class extends bn{config;pending=new Map;serverQueues=new Map;flushTimer;executor;activeBatches=0;batchCounter=0;requestCounter=0;isDestroyed=!1;constructor(e){super(),this.config={maxBatchSize:e.maxBatchSize,maxWaitMs:e.maxWaitMs,enableParallel:e.enableParallel??!0,maxConcurrentBatches:e.maxConcurrentBatches??5,groupByServer:e.groupByServer??!0}}setExecutor(e){this.executor=e}async add(e,t,r){if(this.isDestroyed)throw ve.invalidConfiguration("batcher","Batcher has been destroyed");if(!this.executor)throw ve.missingConfiguration("batchExecutor",{hint:"Call setExecutor() before adding requests"});const n=this.generateRequestId();return new Promise((o,i)=>{const s={id:n,tool:e,args:t,serverId:r,resolve:o,reject:i,addedAt:Date.now()};if(this.pending.set(n,s),this.config.groupByServer&&r){this.serverQueues.has(r)||this.serverQueues.set(r,new Set);const a=this.serverQueues.get(r);a&&a.add(n)}this.emit("requestQueued",{requestId:n,queueSize:this.pending.size}),this.pending.size>=this.config.maxBatchSize?this.scheduleFlush("size"):this.flushTimer||(this.flushTimer=setTimeout(()=>{this.scheduleFlush("timeout")},this.config.maxWaitMs))})}async flush(){this.clearFlushTimer(),this.pending.size!==0&&(this.emit("flushTriggered",{reason:"manual",queueSize:this.pending.size}),await this.executeBatch())}get queueSize(){return this.pending.size}get activeBatchCount(){return this.activeBatches}get isIdle(){return this.pending.size===0&&this.activeBatches===0}async drain(){await this.flush();const e=3e4,t=Date.now()+e;for(;!this.isIdle;){if(Date.now()>=t)throw ve.toolTimeout("batchDrain",e);await new Promise(r=>setTimeout(r,10))}}destroy(){this.isDestroyed=!0,this.clearFlushTimer();for(const e of this.pending.values())e.reject(ve.invalidConfiguration("batcher","Batcher was destroyed before request could complete"));this.pending.clear(),this.serverQueues.clear()}generateRequestId(){return`req-${Date.now()}-${++this.requestCounter}`}generateBatchId(){return`batch-${Date.now()}-${++this.batchCounter}`}scheduleFlush(e){this.clearFlushTimer(),this.emit("flushTriggered",{reason:e,queueSize:this.pending.size}),setImmediate(()=>{this.executeBatch().catch(t=>{f.error("Batch execution failed:",t)})})}clearFlushTimer(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0)}async executeBatch(){if(this.pending.size===0)return;if(this.activeBatches>=this.config.maxConcurrentBatches){this.clearFlushTimer(),this.flushTimer=setTimeout(()=>{this.executeBatch().catch(n=>{f.error("Rescheduled batch execution failed:",n)})},10);return}const e=this.selectBatchRequests();if(e.length===0)return;const t=this.generateBatchId(),r=Date.now();this.activeBatches++,this.emit("batchStarted",{batchId:t,size:e.length}),await pt({name:"mcp.batch.execute",tracer:Be.mcp,attributes:{"mcp.batch.id":t,"mcp.batch.size":e.length,"mcp.batch.active_batches":this.activeBatches}},async n=>{let o=0,i=0;try{if(!this.executor)throw ve.missingConfiguration("batchExecutor",{hint:"Call setExecutor() before executing batches"});const s=this.executor(e.map(p=>({tool:p.tool,args:p.args,serverId:p.serverId}))),a=Math.max(5e3,Number(process.env.MCP_TOOL_TIMEOUT)||6e4);let u;const l=new Promise((p,m)=>{u=setTimeout(()=>m(ve.toolTimeout("batchExecution",a)),a)});s.catch(p=>{});const c=await Promise.race([s,l]).finally(()=>{u&&clearTimeout(u)}),d=[];for(let p=0;p<e.length;p++){const m=e[p],h=c[p],g=Date.now()-r;if(!h){const y=ve.toolExecutionFailed(m.tool,new Error(`Batch executor returned no result for request ${p}`));m.reject(y),d.push({id:m.id,success:!1,error:y,executionTime:g}),i++;continue}if(h.success)m.resolve(h.result),d.push({id:m.id,success:!0,result:h.result,executionTime:g}),o++;else{const y=h.error??ve.toolExecutionFailed(m.tool,new Error("Unknown batch execution error"));m.reject(y),d.push({id:m.id,success:!1,error:y,executionTime:g}),i++}}n.setAttribute("mcp.batch.success_count",o),n.setAttribute("mcp.batch.error_count",i),this.emit("batchCompleted",{batchId:t,results:d})}catch(s){const a=s instanceof Error?s:ve.toolExecutionFailed("batch",new Error(String(s)));for(const u of e)u.reject(a);throw this.emit("batchFailed",{batchId:t,error:a}),a}finally{this.activeBatches--}}).catch(n=>{f.error("Batch span execution failed:",n)}),this.pending.size>0&&(this.clearFlushTimer(),this.flushTimer=setTimeout(()=>{this.executeBatch().catch(n=>{f.error("Follow-up batch execution failed:",n)})},0))}selectBatchRequests(){const e=[];if(this.config.groupByServer&&this.serverQueues.size>0){const[t,r]=this.serverQueues.entries().next().value;for(const n of r){if(e.length>=this.config.maxBatchSize)break;const o=this.pending.get(n);o&&(e.push(o),this.pending.delete(n),r.delete(n))}r.size===0&&this.serverQueues.delete(t)}else{const t=Array.from(this.pending.values()).sort((r,n)=>r.addedAt-n.addedAt);for(const r of t){if(e.length>=this.config.maxBatchSize)break;e.push(r),this.pending.delete(r.id)}}return e}},aer=e=>new v6(e),Zae={maxBatchSize:10,maxWaitMs:100,enableParallel:!0,maxConcurrentBatches:5,groupByServer:!0},w6=class{batcher;toolExecutor;constructor(e){this.batcher=new v6({...Zae,...e}),this.batcher.setExecutor(async t=>{if(!this.toolExecutor)throw ve.missingConfiguration("toolExecutor",{hint:"Call setToolExecutor() before executing tool calls"});const r=this.toolExecutor;return await Promise.all(t.map(async o=>{try{return{success:!0,result:await r(o.tool,o.args,o.serverId)}}catch(i){return{success:!1,error:i instanceof Error?i:ve.toolExecutionFailed(o.tool,new Error(String(i)))}}}))})}setToolExecutor(e){this.toolExecutor=e}async execute(e,t,r){return this.batcher.add(e,t,r)}async flush(){return this.batcher.flush()}async drain(){return this.batcher.drain()}get queueSize(){return this.batcher.queueSize}get isIdle(){return this.batcher.isIdle}destroy(){this.batcher.destroy()}},uer=e=>new w6(e)}}),ler=S({"src/lib/mcp/batching/index.ts"(){"use strict";byn()}}),fy,cer,Qae,b6,der,Tyn=S({"src/lib/mcp/caching/toolCache.ts"(){"use strict";qt(),so(),Hr(),fy=class extends bn{cache=new Map;config;stats;cleanupTimer;constructor(e){super(),this.config={ttl:e.ttl,maxSize:e.maxSize,strategy:e.strategy,enableAutoCleanup:e.enableAutoCleanup??!0,cleanupInterval:e.cleanupInterval??6e4,namespace:e.namespace??""},this.stats={hits:0,misses:0,evictions:0,size:0,maxSize:this.config.maxSize,hitRate:0},this.config.enableAutoCleanup&&this.startAutoCleanup()}get(e){const t=this.getFullKey(e),r=this.cache.get(t);if(!r){this.stats.misses++,this.updateHitRate(),this.emit("miss",{key:t});return}if(this.isExpired(r)){this.deleteWithReason(t,"expired"),this.stats.misses++,this.updateHitRate(),this.emit("miss",{key:t});return}r.accessedAt=Date.now(),r.accessCount++,this.stats.hits++,this.updateHitRate();const n=this.cloneCachedValue(r.value);return this.listenerCount("hit")>0&&this.emit("hit",{key:t,value:this.cloneCachedValue(r.value)}),n}set(e,t,r){const n=this.getFullKey(e),o=r??this.config.ttl,i=Date.now();this.cache.size>=this.config.maxSize&&!this.cache.has(n)&&this.evictOne();const s={value:this.cloneCachedValue(t),expires:i+o,createdAt:i,accessedAt:i,accessCount:1,key:n};this.cache.set(n,s),this.stats.size=this.cache.size,this.emit("set",{key:n,value:t,ttl:o})}has(e){const t=this.getFullKey(e),r=this.cache.get(t);return r?this.isExpired(r)?(this.deleteWithReason(t,"expired"),!1):!0:!1}delete(e){const t=this.getFullKey(e),r=this.cache.delete(t);return r&&(this.stats.size=this.cache.size,this.emit("evict",{key:t,reason:"manual"})),r}invalidate(e){const t=this.getFullKey(e),r=this.patternToRegex(t);let n=0;for(const o of this.cache.keys())r.test(o)&&(this.cache.delete(o),n++,this.emit("evict",{key:o,reason:"manual"}));return this.stats.size=this.cache.size,n}clear(){const e=this.cache.size;this.cache.clear(),this.stats.size=0,this.emit("clear",{entriesRemoved:e})}async getOrSet(e,t,r){const n=this.get(e);if(n!==void 0)return n;const o=3e4,i=await kt(Promise.resolve(t()),o,`ToolCache getOrSet factory timed out after ${o}ms for key "${e}"`);return i===void 0||this.set(e,i,r),i}getStats(){return{...this.stats}}resetStats(){this.stats.hits=0,this.stats.misses=0,this.stats.evictions=0,this.updateHitRate()}keys(){return Array.from(this.cache.keys())}get size(){return this.cache.size}static generateKey(e,t){const r=(o,i=new WeakSet)=>{if(o===null||typeof o!="object")return JSON.stringify(o);if(o instanceof Date)return`{"$date":${JSON.stringify(o.toISOString())}}`;if(i.has(o))throw new TypeError("Circular structures are not supported in cache keys");if(i.add(o),Array.isArray(o)){const u="["+o.map(l=>r(l,i)).join(",")+"]";return i.delete(o),u}const a=Object.keys(o).sort().map(u=>JSON.stringify(u)+":"+r(o[u],i));return i.delete(o),"{"+a.join(",")+"}"},n=sc("sha256").update(r(t)).digest("hex").substring(0,16);return`${e}:${n}`}destroy(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.clear()}cloneCachedValue(e){if(e===null||typeof e!="object")return e;try{return structuredClone(e)}catch{return JSON.parse(JSON.stringify(e))}}getFullKey(e){return this.config.namespace?`${this.config.namespace}:${e}`:e}isExpired(e){return Date.now()>e.expires}deleteWithReason(e,t){const r=this.cache.delete(e);return r&&(this.stats.evictions++,this.stats.size=this.cache.size,this.emit("evict",{key:e,reason:t})),r}evictOne(){const e=this.selectEvictionCandidate();e&&(this.cache.delete(e.key),this.stats.evictions++,this.stats.size=this.cache.size,this.emit("evict",{key:e.key,reason:"capacity"}))}selectEvictionCandidate(){if(this.cache.size!==0)switch(this.config.strategy){case"lru":return this.findLRU();case"fifo":return this.findFIFO();case"lfu":return this.findLFU();default:return this.findLRU()}}findLRU(){let e,t=1/0;for(const r of this.cache.values())r.accessedAt<t&&(t=r.accessedAt,e=r);return e}findFIFO(){let e,t=1/0;for(const r of this.cache.values())r.createdAt<t&&(t=r.createdAt,e=r);return e}findLFU(){let e,t=1/0;for(const r of this.cache.values())r.accessCount<t&&(t=r.accessCount,e=r);return e}patternToRegex(e){const r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^:]*");return new RegExp(`^${r}$`)}updateHitRate(){const e=this.stats.hits+this.stats.misses;this.stats.hitRate=e>0?this.stats.hits/e:0}startAutoCleanup(){this.cleanupTimer=setInterval(()=>{this.cleanupExpired()},this.config.cleanupInterval),this.cleanupTimer.unref&&this.cleanupTimer.unref()}cleanupExpired(){const e=Date.now();for(const[t,r]of this.cache.entries())e>r.expires&&(this.cache.delete(t),this.stats.evictions++,this.emit("evict",{key:t,reason:"expired"}));this.stats.size=this.cache.size}},cer=e=>new fy(e),Qae={ttl:300*1e3,maxSize:500,strategy:"lru",enableAutoCleanup:!0,cleanupInterval:6e4},b6=class{cache;constructor(e){this.cache=new fy({...Qae,...e,namespace:e?.namespace??"tool-results"})}cacheResult(e,t,r,n){const o=fy.generateKey(e,t);this.cache.set(o,r,n)}getCachedResult(e,t){const r=fy.generateKey(e,t);return this.cache.get(r)}hasCachedResult(e,t){const r=fy.generateKey(e,t);return this.cache.has(r)}invalidateTool(e){return this.cache.invalidate(`${e}:*`)}getStats(){return this.cache.getStats()}clear(){this.cache.clear()}destroy(){this.cache.destroy()}},der=e=>new b6(e)}}),per=S({"src/lib/mcp/caching/index.ts"(){"use strict";Tyn()}}),mer={};ue(mer,{createAnnotatedTool:()=>fer,filterToolsByAnnotations:()=>ver,getAnnotationSummary:()=>wer,getToolSafetyLevel:()=>yer,inferAnnotations:()=>om,isSafeToRetry:()=>tue,mergeAnnotations:()=>eue,requiresConfirmation:()=>ger,validateAnnotations:()=>her});function om(e){const t=e.name,r=e.description.toLowerCase(),n={},o=(l,c)=>new RegExp(`\\b${c}\\b`,"i").test(l)?!0:l.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().split(/[_-]/).some(p=>p===c.toLowerCase());return["get","list","read","fetch","query","search","find","show","display","view","retrieve","check","inspect","look"].some(l=>o(r,l)||o(t,l))&&(n.readOnlyHint=!0),["delete","remove","drop","destroy","clear","purge","erase","wipe","truncate","reset"].some(l=>o(r,l)||o(t,l))&&(n.destructiveHint=!0,n.requiresConfirmation=!0),["set","update","put","upsert","replace"].some(l=>o(r,l)||o(t,l))&&!n.destructiveHint&&(n.idempotentHint=!0),["complex","analyze","process","generate","transform","compute","calculate"].some(l=>o(r,l)||o(t,l))?n.complexity="complex":r.length>100?n.complexity="medium":n.complexity="simple",n}function eue(...e){const t={};for(const r of e)if(r){const n=t.tags?[...t.tags]:[];if(Object.assign(t,r),n.length>0||r.tags){const o=r.tags??[];t.tags=[...new Set([...n,...o])]}}return t}function her(e){const t=[];if(e.readOnlyHint&&e.destructiveHint&&t.push("Tool cannot be both readOnly and destructive - these are conflicting hints"),e.rateLimitHint!==void 0&&(e.rateLimitHint<0||!Number.isFinite(e.rateLimitHint))&&t.push("rateLimitHint must be a non-negative number"),e.estimatedDuration!==void 0&&(e.estimatedDuration<0||!Number.isFinite(e.estimatedDuration))&&t.push("estimatedDuration must be a non-negative number"),e.costHint!==void 0&&(e.costHint<0||!Number.isFinite(e.costHint))&&t.push("costHint must be a non-negative number"),e.tags){for(const r of e.tags)if(typeof r!="string"||r.length===0){t.push("All tags must be non-empty strings");break}}return t}function fer(e){const t=om(e),r=eue(t,e.annotations);return{...e,annotations:r}}function ger(e){return!!(e.annotations?.requiresConfirmation||e.annotations?.destructiveHint)}function tue(e){return!!(e.annotations?.idempotentHint||e.annotations?.readOnlyHint)}function yer(e){return e.annotations?.destructiveHint?"dangerous":e.annotations?.readOnlyHint?"safe":(e.annotations?.idempotentHint,"moderate")}function ver(e,t){return e.filter(r=>{const n=r.annotations??{};return t(n)})}function wer(e){const t=[];return e.title&&t.push(e.title),e.readOnlyHint&&t.push("read-only"),e.destructiveHint&&t.push("DESTRUCTIVE"),e.idempotentHint&&t.push("idempotent"),e.requiresConfirmation&&t.push("requires confirmation"),e.complexity&&t.push(`${e.complexity} complexity`),e.estimatedDuration!==void 0&&t.push(`~${e.estimatedDuration}ms`),e.tags?.length&&t.push(`tags: ${e.tags.join(", ")}`),t.length>0?`[${t.join(" | ")}]`:"[no annotations]"}var w1=S({"src/lib/mcp/toolAnnotations.ts"(){"use strict"}}),ber={};ue(ber,{MultiServerManager:()=>b1,globalMultiServerManager:()=>rue});var b1,rue,nue=S({"src/lib/mcp/multiServerManager.ts"(){"use strict";so(),z(),et(),b1=class extends bn{config;servers=new Map;groups=new Map;metrics=new Map;roundRobinCounters=new Map;toolPreferences=new Map;constructor(e={}){super(),this.config={defaultStrategy:e.defaultStrategy??"round-robin",healthAwareRouting:e.healthAwareRouting??!0,healthCheckInterval:e.healthCheckInterval??3e4,maxFailoverRetries:e.maxFailoverRetries??3,namespaceSeparator:e.namespaceSeparator??".",autoNamespace:e.autoNamespace??!1,conflictResolution:e.conflictResolution??"first-wins"}}addServer(e){this.servers.set(e.id,e),this.metrics.set(e.id,{activeRequests:0,totalRequests:0,completedRequests:0,averageResponseTime:0,errorRate:0,isHealthy:e.status==="connected"}),this.emit("serverAdded",{serverId:e.id,server:e}),f.debug(`[MultiServerManager] Added server: ${e.id} (${e.name})`)}removeServer(e){if(!this.servers.get(e))return!1;for(const[r,n]of this.groups){const o=n.servers.indexOf(e);o!==-1&&(n.servers.splice(o,1),n.servers.length===0&&(this.groups.delete(r),this.roundRobinCounters.delete(r)))}this.servers.delete(e),this.metrics.delete(e);for(const[r,n]of this.toolPreferences)n===e&&this.toolPreferences.delete(r);return this.emit("serverRemoved",{serverId:e}),f.debug(`[MultiServerManager] Removed server: ${e}`),!0}updateServer(e,t){const r=this.servers.get(e);if(!r)throw ve.invalidConfiguration("serverId",`Server '${e}' not found`,{serverId:e});const n={...r,...t,id:e};this.servers.set(e,n);const o=this.metrics.get(e);o&&t.status!==void 0&&(o.isHealthy=t.status==="connected"),this.emit("serverUpdated",{serverId:e,server:n})}createGroup(e){for(const t of e.servers)if(!this.servers.has(t))throw ve.invalidConfiguration("serverGroup.servers",`Server '${t}' not found when creating group '${e.id}'`,{serverId:t,groupId:e.id});this.groups.set(e.id,e),this.roundRobinCounters.set(e.id,0),this.emit("groupCreated",{group:e}),f.debug(`[MultiServerManager] Created group: ${e.id} with ${e.servers.length} servers`)}removeGroup(e){const t=this.groups.delete(e);return t&&(this.roundRobinCounters.delete(e),this.emit("groupRemoved",{groupId:e})),t}addServerToGroup(e,t){const r=this.groups.get(t);if(!r)throw ve.invalidConfiguration("groupId",`Group '${t}' not found`,{groupId:t});if(!this.servers.has(e))throw ve.invalidConfiguration("serverId",`Server '${e}' not found`,{serverId:e,groupId:t});r.servers.includes(e)||(r.servers.push(e),this.emit("serverAddedToGroup",{serverId:e,groupId:t}))}removeServerFromGroup(e,t){const r=this.groups.get(t);if(!r)return!1;const n=r.servers.indexOf(e);return n!==-1?(r.servers.splice(n,1),this.emit("serverRemovedFromGroup",{serverId:e,groupId:t}),!0):!1}getUnifiedTools(){const e=new Map;for(const[t,r]of this.servers){const o=this.metrics.get(t)?.isHealthy??!0;if(!(this.config.healthAwareRouting&&!o))for(const i of r.tools||[]){const s=e.get(i.name);s?(s.hasConflict=!0,s.servers.push({serverId:t,serverName:r.name,inputSchema:i.inputSchema,priority:this.getServerPriority(t)})):e.set(i.name,{name:i.name,description:i.description,servers:[{serverId:t,serverName:r.name,inputSchema:i.inputSchema,priority:this.getServerPriority(t)}],hasConflict:!1,preferredServerId:this.toolPreferences.get(i.name)})}}for(const t of e.values())t.servers.sort((r,n)=>r.priority-n.priority),!t.preferredServerId&&t.servers.length>0&&(t.preferredServerId=t.servers[0].serverId);return Array.from(e.values())}getNamespacedTools(){const e=[];for(const[t,r]of this.servers)if(!(this.config.healthAwareRouting&&!(this.metrics.get(t)?.isHealthy??!0)))for(const n of r.tools||[])e.push({fullName:`${t}${this.config.namespaceSeparator}${n.name}`,toolName:n.name,serverId:t,serverName:r.name,description:n.description,inputSchema:n.inputSchema});return e}setToolPreference(e,t){if(!this.servers.has(t))throw ve.invalidConfiguration("serverId",`Server '${t}' not found`,{serverId:t,toolName:e});this.toolPreferences.set(e,t),this.emit("toolPreferenceSet",{toolName:e,serverId:t})}clearToolPreference(e){this.toolPreferences.delete(e)}selectServer(e,t){const r=this.toolPreferences.get(e);if(r){const u=this.servers.get(r),l=this.metrics.get(r);if(u&&(!this.config.healthAwareRouting||l?.isHealthy)&&u.tools?.some(c=>c.name===e))return{serverId:r,server:u}}let n;if(t){const u=this.groups.get(t);if(!u)return f.warn(`[MultiServerManager] Group '${t}' not found`),null;n=u.servers.filter(l=>this.servers.get(l)?.tools?.some(d=>d.name===e))}else{n=[];for(const[u,l]of this.servers)l.tools?.some(c=>c.name===e)&&n.push(u)}if(n.length===0)return null;if((t?this.groups.get(t)?.healthAware??this.config.healthAwareRouting:this.config.healthAwareRouting)&&(n=n.filter(u=>this.metrics.get(u)?.isHealthy??!0),n.length===0))return f.warn(`[MultiServerManager] No healthy servers available for tool '${e}'`),null;const i=t?this.groups.get(t)?.strategy??this.config.defaultStrategy:this.config.defaultStrategy,s=this.applyStrategy(i,n,t);if(!s)return null;const a=this.servers.get(s);return a?{serverId:s,server:a}:null}applyStrategy(e,t,r){if(t.length===0)return null;if(t.length===1)return t[0];switch(e){case"round-robin":{const n=r??"default",o=this.roundRobinCounters.get(n)??0,i=t[o%t.length];return this.roundRobinCounters.set(n,o+1),i}case"least-loaded":{let n=1/0,o=t[0];for(const i of t){const a=this.metrics.get(i)?.activeRequests??0;a<n&&(n=a,o=i)}return o}case"random":{const n=Math.floor(Math.random()*t.length);return t[n]}case"weighted":{if(!r){const u=Math.floor(Math.random()*t.length);return t[u]}const n=this.groups.get(r);if(!n?.weights){const u=Math.floor(Math.random()*t.length);return t[u]}const o=1,i=t.map(u=>{const c=(n.weights??[]).find(d=>d.serverId===u);return{serverId:u,weight:c?.weight??o}}),s=i.reduce((u,l)=>u+l.weight,0);if(s===0){const u=Math.floor(Math.random()*t.length);return t[u]}let a=Math.random()*s;for(const u of i)if(a-=u.weight,a<=0)return u.serverId;return t[0]}case"failover-only":return t.map(o=>({id:o,priority:this.getServerPriority(o,r)})).sort((o,i)=>o.priority-i.priority)[0]?.id??null;default:return t[0]}}getServerPriority(e,t){if(t){const n=this.groups.get(t);if(n?.weights){const o=n.weights.find(i=>i.serverId===e);if(o)return o.priority}}for(const n of this.groups.values())if(n.weights){const o=n.weights.find(i=>i.serverId===e);if(o)return o.priority}return Array.from(this.servers.keys()).indexOf(e)}updateMetrics(e,t){const r=this.metrics.get(e);r&&(Object.assign(r,t),this.emit("metricsUpdated",{serverId:e,metrics:{...r}}))}requestStarted(e){const t=this.metrics.get(e);t&&(t.activeRequests++,t.totalRequests++)}requestCompleted(e,t,r){const n=this.metrics.get(e);if(n){n.activeRequests=Math.max(0,n.activeRequests-1),n.completedRequests++;const o=n.averageResponseTime*(n.completedRequests-1)+t;n.averageResponseTime=o/n.completedRequests;const i=.1;n.errorRate=n.errorRate*(1-i)+(r?0:1)*i}}getServers(){return Array.from(this.servers.values())}getServer(e){return this.servers.get(e)}getGroups(){return Array.from(this.groups.values())}getGroup(e){return this.groups.get(e)}getServerMetrics(e){return this.metrics.get(e)}getAllMetrics(){return new Map(this.metrics)}getStatistics(){let e=0,t=0,r=0;for(const i of this.metrics.values())i.isHealthy&&e++,t+=i.totalRequests,r+=i.activeRequests;const n=this.getUnifiedTools(),o=n.filter(i=>i.hasConflict).length;return{totalServers:this.servers.size,healthyServers:e,totalGroups:this.groups.size,totalTools:n.length,conflictingTools:o,totalRequests:t,activeRequests:r}}},rue=new b1}}),Ter={};ue(Ter,{EnhancedToolDiscovery:()=>T6});var T6,oue=S({"src/lib/mcp/enhancedToolDiscovery.ts"(){"use strict";so(),z(),Hr(),et(),w1(),nue(),T6=class extends bn{toolRegistry=new Map;serverToolsMap=new Map;multiServerManager;discoveryInProgress=new Set;constructor(e){super(),this.multiServerManager=e??new b1}async discoverToolsWithAnnotations(e,t,r=1e4){const n=Date.now();if(this.discoveryInProgress.has(e))return{success:!1,error:`Discovery already in progress for server: ${e}`,toolCount:0,tools:[],duration:Date.now()-n,serverId:e};this.discoveryInProgress.add(e);try{f.info(`[EnhancedToolDiscovery] Starting discovery with annotations for: ${e}`);const o=await kt(t.listTools(),r,"Discovery timeout");if(!o?.tools)throw ve.toolExecutionFailed("discoverTools",new Error("No tools returned from server"),e);this.clearServerTools(e);const i=[];for(const s of o.tools){const a=this.createEnhancedToolInfo(e,s),u=this.createToolKey(e,s.name);this.toolRegistry.set(u,a);let l=this.serverToolsMap.get(e);l||(l=new Set,this.serverToolsMap.set(e,l)),l.add(s.name),i.push(a),this.emit("toolDiscovered",{serverId:e,toolName:s.name,annotations:a.annotations,timestamp:new Date})}return f.info(`[EnhancedToolDiscovery] Discovered ${i.length} tools with annotations from ${e}`),{success:!0,toolCount:i.length,tools:i,duration:Date.now()-n,serverId:e}}catch(o){const i=o instanceof Error?o.message:String(o);return f.error(`[EnhancedToolDiscovery] Discovery failed for ${e}:`,o),{success:!1,error:i,toolCount:0,tools:[],duration:Date.now()-n,serverId:e}}finally{this.discoveryInProgress.delete(e)}}createEnhancedToolInfo(e,t){const r=om({name:t.name,description:t.description??""});return{name:t.name,description:t.description??"No description provided",serverId:e,inputSchema:t.inputSchema,isAvailable:!0,annotations:r,version:"1.0.0",stats:{totalCalls:0,successfulCalls:0,failedCalls:0,averageExecutionTime:0,lastExecutionTime:0},metadata:{category:this.inferCategory(t),deprecated:!1}}}inferCategory(e){const t=e.name.toLowerCase(),r=(e.description??"").toLowerCase();return t.includes("git")||r.includes("git")?"version-control":t.includes("file")||t.includes("read")||t.includes("write")?"file-system":t.includes("api")||t.includes("http")?"api":t.includes("data")||t.includes("query")?"data":t.includes("auth")||t.includes("login")?"authentication":t.includes("deploy")||t.includes("build")?"deployment":"general"}searchTools(e){const t=Date.now();let r=Array.from(this.toolRegistry.values());if(e.name){const o=e.name.toLowerCase();r=r.filter(i=>i.name.toLowerCase().includes(o))}if(e.description){const o=e.description.toLowerCase().split(/\s+/);r=r.filter(i=>{const s=i.description.toLowerCase();return o.some(a=>s.includes(a))})}if(e.serverIds?.length){const o=e.serverIds;r=r.filter(i=>o.includes(i.serverId))}if(e.category&&(r=r.filter(o=>o.metadata?.category===e.category)),e.tags?.length){const o=e.tags;r=r.filter(i=>{const s=i.annotations?.tags??[];return o.some(a=>s.includes(a))})}if(e.annotations){const o=e.annotations;r=r.filter(i=>{if(!i.annotations)return!1;for(const[s,a]of Object.entries(o)){const u=s;if(i.annotations[u]!==a)return!1}return!0})}if(e.includeUnavailable||(r=r.filter(o=>o.isAvailable)),e.sortBy){const o=e.sortDirection==="desc"?-1:1;r.sort((i,s)=>{let a=0;switch(e.sortBy){case"name":a=i.name.localeCompare(s.name);break;case"calls":a=i.stats.totalCalls-s.stats.totalCalls;break;case"successRate":{const u=i.stats.totalCalls>0?i.stats.successfulCalls/i.stats.totalCalls:0,l=s.stats.totalCalls>0?s.stats.successfulCalls/s.stats.totalCalls:0;a=u-l;break}case"avgExecutionTime":a=i.stats.averageExecutionTime-s.stats.averageExecutionTime;break}return a*o})}const n=r.length;return e.limit&&e.limit>0&&(r=r.slice(0,e.limit)),{tools:r,totalCount:n,criteria:e,executionTime:Date.now()-t}}getToolsBySafetyLevel(e){return Array.from(this.toolRegistry.values()).filter(t=>{const r=t.annotations??{};switch(e){case"dangerous":return r.destructiveHint===!0;case"safe":return r.readOnlyHint===!0;case"moderate":return!r.destructiveHint&&!r.readOnlyHint;default:return!1}})}getToolsRequiringConfirmation(){return Array.from(this.toolRegistry.values()).filter(e=>e.annotations?.requiresConfirmation===!0||e.annotations?.destructiveHint===!0)}getReadOnlyTools(){return Array.from(this.toolRegistry.values()).filter(e=>e.annotations?.readOnlyHint===!0)}getUnifiedTools(){return this.multiServerManager.getUnifiedTools()}registerServer(e){this.multiServerManager.addServer(e)}updateToolAnnotations(e,t,r){const n=this.createToolKey(e,t),o=this.toolRegistry.get(n);return o?(o.annotations={...o.annotations,...r},this.emit("annotationsUpdated",{serverId:e,toolName:t,annotations:o.annotations,timestamp:new Date}),!0):!1}checkCompatibility(e,t,r){const n=this.createToolKey(t,e),o=this.toolRegistry.get(n),i=[],s=[],a=[];if(!o)return{compatible:!1,issues:[`Tool '${e}' not found on server '${t}'`],warnings:[],recommendations:[]};if(r&&o.version){const u=o.version.split(".").map(Number),l=r.split(".").map(Number);u.some(isNaN)||l.some(isNaN)?s.push(`Non-standard version format: tool=${o.version}, target=${r}`):u[0]!==l[0]?i.push(`Major version mismatch: tool is v${o.version}, target is v${r}`):u[1]<l[1]&&s.push(`Minor version mismatch: tool is v${o.version}, target is v${r}`)}return o.metadata?.deprecated&&(s.push("This tool is marked as deprecated"),a.push("Consider using an alternative tool if available")),o.annotations?.securityLevel==="restricted"&&a.push("This tool requires elevated permissions"),{compatible:i.length===0,issues:i,warnings:s,recommendations:a}}getTool(e,t){return this.toolRegistry.get(this.createToolKey(e,t))}getAllTools(){return Array.from(this.toolRegistry.values())}getServerTools(e){const t=this.serverToolsMap.get(e);return t?Array.from(t).map(r=>this.getTool(e,r)).filter(r=>r!==void 0):[]}clearServerTools(e){const t=this.serverToolsMap.get(e);if(t){for(const r of t)this.toolRegistry.delete(this.createToolKey(e,r));this.serverToolsMap.delete(e)}}createToolKey(e,t){return`${e}:${t}`}getStatistics(){const e={},t={},r={safe:0,moderate:0,dangerous:0};let n=0,o=0;for(const i of this.toolRegistry.values()){e[i.serverId]=(e[i.serverId]??0)+1;const s=i.metadata?.category??"general";t[s]=(t[s]??0)+1,i.annotations?.destructiveHint?r.dangerous++:i.annotations?.readOnlyHint?r.safe++:r.moderate++,i.annotations&&Object.keys(i.annotations).length>0&&n++,i.metadata?.deprecated&&o++}return{totalTools:this.toolRegistry.size,toolsByServer:e,toolsByCategory:t,toolsBySafetyLevel:r,toolsWithAnnotations:n,deprecatedTools:o}}}}}),_er,iue,sue,T1,aue=S({"src/lib/mcp/mcpCircuitBreaker.ts"(){"use strict";so(),Kt(),z(),lt(),lt(),_er=Math.max(1e4,Number(process.env.MCP_OPERATION_TIMEOUT)||6e4),iue=class extends bn{constructor(e,t={}){super(),this.name=e,this.config={failureThreshold:t.failureThreshold??5,resetTimeout:t.resetTimeout??6e4,halfOpenMaxCalls:t.halfOpenMaxCalls??3,operationTimeout:t.operationTimeout??_er,minimumCallsBeforeCalculation:t.minimumCallsBeforeCalculation??10,statisticsWindowSize:t.statisticsWindowSize??3e5},this.cleanupTimer=setInterval(()=>this.cleanupCallHistory(),6e4),this.cleanupTimer.unref&&this.cleanupTimer.unref()}name;state="closed";config;callHistory=[];lastFailureTime=0;halfOpenCalls=0;lastStateChange=new Date;cleanupTimer;async execute(e){const t=Date.now();try{if(this.state==="open"){const i=this.config.resetTimeout-(Date.now()-this.lastFailureTime);if(i>0)throw new uh({breakerName:this.name,retryAfter:new Date(this.lastFailureTime+this.config.resetTimeout),retryAfterMs:i,breakerState:"open",failureCount:this.getStats().failedCalls});this.changeState("half-open","Reset timeout reached")}if(this.state==="half-open"&&this.halfOpenCalls>=this.config.halfOpenMaxCalls)throw this.lastFailureTime=Date.now(),this.changeState("open","Half-open call limit reached, reverting to open"),new uh({breakerName:this.name,retryAfter:new Date(this.lastFailureTime+this.config.resetTimeout),retryAfterMs:this.config.resetTimeout,breakerState:"open",failureCount:this.getStats().failedCalls});if(this.state==="half-open"){const i=Qt.getActiveSpan();i&&i.addEvent("circuit.half_open_test",{"circuit.name":this.name,"circuit.half_open_call":this.halfOpenCalls+1,"circuit.half_open_max_calls":this.config.halfOpenMaxCalls})}let r;const n=i=>{r=i||"Operation resolved a failure result"},o=await this.raceWithTimeout(e(n),this.config.operationTimeout);return r!==void 0?(this.recordFailureOutcome(r,Date.now()-t),o):(this.recordCall(!0,Date.now()-t),this.state==="half-open"&&(this.halfOpenCalls++,this.halfOpenCalls>=this.config.halfOpenMaxCalls&&this.changeState("closed","Half-open test successful")),o)}catch(r){const n=Date.now()-t,o=r instanceof Error?r.message:String(r);throw this.recordFailureOutcome(o,n),r}}recordFailureOutcome(e,t){this.recordCall(!1,t),this.emit("callFailure",{error:e,duration:t,timestamp:new Date}),this.state==="half-open"?this.changeState("open",`Half-open test failed: ${e}`):this.state==="closed"&&this.checkFailureThreshold()}recordCall(e,t){const r=Date.now();this.callHistory.push({timestamp:r,success:e,duration:t}),e&&this.emit("callSuccess",{duration:t,timestamp:new Date}),e||(this.lastFailureTime=r)}checkFailureThreshold(){const e=Date.now()-this.config.statisticsWindowSize,t=this.callHistory.filter(o=>o.timestamp>=e);if(t.length<this.config.minimumCallsBeforeCalculation)return;const r=t.filter(o=>!o.success).length,n=r/t.length;ae.debug(`[CircuitBreaker:${this.name}] Failure rate: ${(n*100).toFixed(1)}% (${r}/${t.length})`),r>=this.config.failureThreshold&&(this.changeState("open",`Failure threshold exceeded: ${r} failures`),this.emit("circuitOpen",{failureRate:n,totalCalls:t.length,timestamp:new Date}))}changeState(e,t){const r=this.state;this.state=e,this.lastStateChange=new Date;const n=Qt.getActiveSpan();n&&n.addEvent("circuit.state_change",{"circuit.name":this.name,"circuit.from_state":r,"circuit.to_state":e,"circuit.reason":t.slice(0,128),"circuit.failure_count":this.callHistory.filter(o=>!o.success).length}),e==="half-open"?(this.halfOpenCalls=0,this.emit("circuitHalfOpen",{timestamp:new Date})):e==="closed"&&(this.halfOpenCalls=0,this.emit("circuitClosed",{timestamp:new Date})),ae.info(`[CircuitBreaker:${this.name}] State changed: ${r} -> ${e} (${t})`),this.emit("stateChange",{oldState:r,newState:e,reason:t,timestamp:new Date})}async raceWithTimeout(e,t){let r;const n=new Promise((o,i)=>{r=setTimeout(()=>{i(new Error(`Operation timed out after ${t}ms`))},t)});try{return await Promise.race([e,n])}finally{clearTimeout(r)}}cleanupCallHistory(){const e=Date.now()-this.config.statisticsWindowSize,t=this.callHistory.length;this.callHistory=this.callHistory.filter(n=>n.timestamp>=e);const r=t-this.callHistory.length;r>0&&ae.debug(`[CircuitBreaker:${this.name}] Cleaned up ${r} old call records`)}getStats(){const e=Date.now()-this.config.statisticsWindowSize,t=this.callHistory.filter(i=>i.timestamp>=e),r=t.filter(i=>i.success).length,n=t.length-r,o=t.length>0?n/t.length:0;return{state:this.state,totalCalls:this.callHistory.length,successfulCalls:this.callHistory.filter(i=>i.success).length,failedCalls:this.callHistory.filter(i=>!i.success).length,failureRate:o,windowCalls:t.length,lastStateChange:this.lastStateChange,nextRetryTime:this.state==="open"?new Date(this.lastFailureTime+this.config.resetTimeout):void 0,halfOpenCalls:this.halfOpenCalls}}reset(){this.changeState("closed","Manual reset"),this.callHistory=[],this.lastFailureTime=0,this.halfOpenCalls=0}forceOpen(e="Manual force open"){this.changeState("open",e),this.lastFailureTime=Date.now()}getName(){return this.name}isOpen(){return this.state==="open"}isClosed(){return this.state==="closed"}isHalfOpen(){return this.state==="half-open"}destroy(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0,ae.debug(`[CircuitBreaker:${this.name}] Cleanup timer cleared`)),this.removeAllListeners(),this.callHistory=[],ae.debug(`[CircuitBreaker:${this.name}] Destroyed and cleaned up`)}},sue=class{breakers=new Map;getBreaker(e,t){if(!this.breakers.has(e)){const n=new iue(e,t);this.breakers.set(e,n),ae.debug(`[CircuitBreakerManager] Created circuit breaker: ${e}`)}const r=this.breakers.get(e);if(!r)throw new Error(`Circuit breaker ${e} not found after creation`);return r}removeBreaker(e){const t=this.breakers.get(e);return t?(t.destroy(),this.breakers.delete(e),ae.debug(`[CircuitBreakerManager] Removed and cleaned up circuit breaker: ${e}`),!0):!1}getBreakerNames(){return Array.from(this.breakers.keys())}getAllStats(){const e={};for(const[t,r]of this.breakers)e[t]=r.getStats();return e}resetAll(){for(const e of this.breakers.values())e.reset();ae.info("[CircuitBreakerManager] Reset all circuit breakers")}getHealthSummary(){let e=0,t=0,r=0;const n=[];for(const[o,i]of this.breakers)switch(i.getStats().state){case"closed":e++;break;case"open":t++,n.push(o);break;case"half-open":r++;break}return{totalBreakers:this.breakers.size,closedBreakers:e,openBreakers:t,halfOpenBreakers:r,unhealthyBreakers:n}}destroyAll(){for(const e of this.breakers.values())e.destroy();this.breakers.clear(),ae.info("[CircuitBreakerManager] Destroyed all circuit breakers")}},T1=new sue}});function _yn(e){return new Promise(t=>setTimeout(t,e))}function _6(e,t=rp){return t.retryableStatusCodes.includes(e)}function Eer(e,t=rp){if(!e||typeof e!="object")return!1;const r=e;if(dr(e))return!1;if(r.name==="TimeoutError"||r.code==="TIMEOUT"||r.code==="ETIMEDOUT"||r.code==="ECONNRESET"||r.code==="ENOTFOUND"||r.code==="ECONNREFUSED"||r.code==="ECONNABORTED"||r.code==="EPIPE"||r.code==="ENETUNREACH"||r.code==="EHOSTUNREACH")return!0;if(r.name==="TypeError"&&typeof r.message=="string"){const n=r.message.toLowerCase();if(n.includes("fetch")||n.includes("network")||n.includes("connection"))return!0}return typeof r.status=="number"?_6(r.status,t):r.response&&typeof r.response=="object"&&typeof r.response.status=="number"?_6(r.response.status,t):typeof r.statusCode=="number"?_6(r.statusCode,t):!1}async function Ser(e,t={}){const r={...rp,...t},{traceId:n,parentSpanId:o}=E0(),i=Ie.createSpan("mcp.transport","mcp.retry",{"mcp.transport":"http","mcp.operation":"retry","mcp.maxAttempts":r.maxAttempts},o,n),s=Date.now();let a,u=0;for(let c=1;c<=r.maxAttempts;c++){u=c;try{const d=await e();i.durationMs=Date.now()-s,i.attributes["mcp.retryAttempt"]=c;const p=Ie.endSpan(i,1);return nt().recordSpan(p),d}catch(d){if(a=d,c===r.maxAttempts){f.debug(`HTTP retry: All ${r.maxAttempts} attempts exhausted`);break}if(!Eer(d,r)){f.debug("HTTP retry: Non-retryable error encountered",d instanceof Error?d.message:String(d));break}const p=ySt(c,r.initialDelay,r.backoffMultiplier,r.maxDelay,!0),m=d instanceof Error?d.message:String(d);f.warn(`HTTP retry: Attempt ${c}/${r.maxAttempts} failed: ${m}. Retrying in ${Math.round(p)}ms...`),await _yn(p)}}i.durationMs=Date.now()-s,i.attributes["mcp.retryAttempt"]=u;const l=Ie.endSpan(i,2);throw l.statusMessage=a instanceof Error?a.message:String(a),nt().recordSpan(l),a}var rp,ker=S({"src/lib/mcp/httpRetryHandler.ts"(){"use strict";et(),_St(),z(),oo(),S0(),rp={maxAttempts:3,initialDelay:1e3,maxDelay:3e4,backoffMultiplier:2,retryableStatusCodes:[408,429,500,502,503,504]}}}),uue,lue,cue,due,Aer=S({"src/lib/mcp/httpRateLimiter.ts"(){"use strict";z(),Yk(),oo(),S0(),uue={requestsPerWindow:60,windowMs:6e4,useTokenBucket:!0,refillRate:1,maxBurst:10},lue=class{tokens;lastRefill;config;waitQueue=[];processingQueue=!1;constructor(e={}){this.config={...uue,...e},this.tokens=this.config.maxBurst,this.lastRefill=Date.now(),ae.debug("[HTTPRateLimiter] Initialized with config:",{requestsPerWindow:this.config.requestsPerWindow,windowMs:this.config.windowMs,useTokenBucket:this.config.useTokenBucket,refillRate:this.config.refillRate,maxBurst:this.config.maxBurst})}refillTokens(){const e=Date.now(),n=(e-this.lastRefill)/1e3*this.config.refillRate;if(n>=1){const o=this.tokens;this.tokens=Math.min(this.config.maxBurst,this.tokens+n),this.lastRefill=e,this.tokens>o&&ae.debug(`[HTTPRateLimiter] Refilled tokens: ${o.toFixed(2)} -> ${this.tokens.toFixed(2)} (+${n.toFixed(2)})`)}}async acquire(){const{traceId:e,parentSpanId:t}=E0(),r=Ie.createSpan("mcp.transport","mcp.rateLimit",{"mcp.transport":"http","mcp.operation":"rateLimit","mcp.rateLimit.tokensAvailable":this.tokens,"mcp.rateLimit.maxBurst":this.config.maxBurst},t,e),n=Date.now();try{if(this.tryAcquire()){r.durationMs=Date.now()-n,r.attributes["mcp.rateLimit.waited"]=!1;const i=Ie.endSpan(r,1);nt().recordSpan(i);return}await new Promise((i,s)=>{this.waitQueue.push({resolve:i,reject:s}),ae.debug(`[HTTPRateLimiter] Request queued, queue length: ${this.waitQueue.length}`),this.processingQueue||this.processQueue()}),r.durationMs=Date.now()-n,r.attributes["mcp.rateLimit.waited"]=!0;const o=Ie.endSpan(r,1);nt().recordSpan(o)}catch(o){r.durationMs=Date.now()-n;const i=Ie.endSpan(r,2);throw i.statusMessage=o instanceof Error?o.message:String(o),nt().recordSpan(i),o}}async processQueue(){if(!this.processingQueue){for(this.processingQueue=!0;this.waitQueue.length>0;)if(this.refillTokens(),this.tokens>=1){const e=this.waitQueue.shift();e&&(this.tokens-=1,ae.debug(`[HTTPRateLimiter] Token granted from queue, remaining: ${this.tokens.toFixed(2)}, queue: ${this.waitQueue.length}`),e.resolve())}else{const t=(1-this.tokens)/this.config.refillRate*1e3,r=Math.max(10,Math.ceil(t));ae.debug(`[HTTPRateLimiter] Waiting ${r}ms for token refill`),await this.sleep(r)}this.processingQueue=!1}}sleep(e){return new Promise(t=>setTimeout(t,e))}tryAcquire(){return this.refillTokens(),this.tokens>=1?(this.tokens-=1,ae.debug(`[HTTPRateLimiter] Token acquired, remaining: ${this.tokens.toFixed(2)}`),!0):(ae.debug(`[HTTPRateLimiter] No tokens available, current: ${this.tokens.toFixed(2)}`),!1)}handleRateLimitResponse(e){const t=Zw(e),r=e.get("Retry-After");if(r&&t!==void 0){const i=parseInt(r,10);if(isNaN(i)){const s=new Date(r);if(!isNaN(s.getTime()))return ae.info(`[HTTPRateLimiter] Server requested retry at ${s.toISOString()} (${t}ms)`),t}else return ae.info(`[HTTPRateLimiter] Server requested retry after ${i} seconds`),t}const n=e.get("X-RateLimit-Reset");if(n&&t!==void 0){const i=parseInt(n,10);if(!isNaN(i)){const s=i>1e12?i:i*1e3;return ae.info(`[HTTPRateLimiter] Rate limit resets at ${new Date(s).toISOString()} (${t}ms)`),t}}return e.get("X-RateLimit-Remaining")==="0"&&t!==void 0?(ae.info(`[HTTPRateLimiter] Rate limit exhausted, using default backoff: ${t}ms`),t):t??0}getRemainingTokens(){return this.refillTokens(),this.tokens}reset(){for(this.tokens=this.config.maxBurst,this.lastRefill=Date.now();this.waitQueue.length>0;){const e=this.waitQueue.shift();e&&e.reject(new Error("Rate limiter was reset"))}ae.info(`[HTTPRateLimiter] Reset to initial state, tokens: ${this.tokens}`)}getStats(){return this.refillTokens(),{tokens:this.tokens,maxBurst:this.config.maxBurst,refillRate:this.config.refillRate,queueLength:this.waitQueue.length,lastRefill:new Date(this.lastRefill)}}updateConfig(e){Object.assign(this.config,e),ae.info("[HTTPRateLimiter] Configuration updated:",e)}getConfig(){return{...this.config}}},cue=class{limiters=new Map;getLimiter(e,t){let r=this.limiters.get(e);return r?t&&r.updateConfig(t):(r=new lue(t),this.limiters.set(e,r),ae.debug(`[RateLimiterManager] Created rate limiter for server: ${e}`)),r}hasLimiter(e){return this.limiters.has(e)}removeLimiter(e){const t=this.limiters.get(e);t&&(t.reset(),this.limiters.delete(e),ae.debug(`[RateLimiterManager] Removed rate limiter for server: ${e}`))}getServerIds(){return Array.from(this.limiters.keys())}getAllStats(){const e={};for(const[t,r]of this.limiters)e[t]=r.getStats();return e}resetAll(){for(const e of this.limiters.values())e.reset();ae.info("[RateLimiterManager] Reset all rate limiters")}destroyAll(){for(const e of this.limiters.values())e.reset();this.limiters.clear(),ae.info("[RateLimiterManager] Destroyed all rate limiters")}getHealthSummary(){const e=[];let t=0,r=0;for(const[o,i]of this.limiters){const s=i.getStats();s.queueLength>0&&(e.push(o),t+=s.queueLength),r+=s.tokens}const n=this.limiters.size>0?r/this.limiters.size:0;return{totalLimiters:this.limiters.size,serversWithQueuedRequests:e,totalQueuedRequests:t,averageTokensAvailable:n}}},due=new cue}});function Cer(e,t=60){if(!e.expiresAt)return!1;const r=t*1e3,n=Date.now();return e.expiresAt-r<=n}function pue(e){return Date.now()+e*1e3}var E6,xer,Ier=S({"src/lib/mcp/auth/tokenStorage.ts"(){"use strict";z(),E6=class{tokens=new Map;async getTokens(e){return this.tokens.get(e)??null}async saveTokens(e,t){this.tokens.set(e,t)}async deleteTokens(e){this.tokens.delete(e)}async hasTokens(e){return this.tokens.has(e)}async clearAll(){this.tokens.clear()}get size(){return this.tokens.size}getServerIds(){return Array.from(this.tokens.keys())}},xer=class{filePath;tokens=new Map;loaded=!1;constructor(e){this.filePath=e}async loadTokens(){if(!this.loaded)try{const t=await(await Promise.resolve().then(()=>(Ti(),F0))).readFile(this.filePath,"utf-8"),r=JSON.parse(t);this.tokens=new Map(Object.entries(r)),this.loaded=!0}catch(e){e instanceof Error&&"code"in e&&e.code!=="ENOENT"&&f.warn(`[FileTokenStorage] Error loading tokens: ${e.message}`),this.tokens=new Map,this.loaded=!0}}async saveToFile(){try{const e=await Promise.resolve().then(()=>(Ti(),F0)),t=await Promise.resolve().then(()=>(Sr(),Xm)),{randomBytes:r}=await Promise.resolve().then(()=>(qt(),ew)),n=t.dirname(this.filePath);await e.mkdir(n,{recursive:!0,mode:448});const o=Object.fromEntries(this.tokens.entries()),i=`${this.filePath}.${process.pid}.${r(6).toString("hex")}.tmp`;try{await e.writeFile(i,JSON.stringify(o,null,2),{encoding:"utf-8",mode:384,flag:"wx"}),await e.rename(i,this.filePath),await e.chmod(this.filePath,384)}catch(s){throw await e.rm(i,{force:!0}),s}}catch(e){throw f.error(`[FileTokenStorage] Error saving tokens: ${e instanceof Error?e.message:String(e)}`),e}}async getTokens(e){return await this.loadTokens(),this.tokens.get(e)??null}async saveTokens(e,t){await this.loadTokens(),this.tokens.set(e,t),await this.saveToFile()}async deleteTokens(e){await this.loadTokens(),this.tokens.delete(e),await this.saveToFile()}async hasTokens(e){return await this.loadTokens(),this.tokens.has(e)}async clearAll(){this.tokens.clear(),await this.saveToFile()}}}});function Eyn(e,t){return new S6({clientId:e.clientId,clientSecret:e.clientSecret,authorizationUrl:e.authorizationUrl,tokenUrl:e.tokenUrl,redirectUrl:e.redirectUrl,scope:e.scope,usePKCE:e.usePKCE??!0},t)}var gy,S6,Syn=S({"src/lib/mcp/auth/oauthClientProvider.ts"(){"use strict";qt(),Ier(),z(),et(),gy=3e4,S6=class{config;storage;pendingChallenges=new Map;pendingStates=new Set;constructor(e,t){this.config={...e,usePKCE:e.usePKCE??!0},this.storage=t??new E6}async tokens(e){const t=await this.storage.getTokens(e);if(!t)return null;if(Cer(t)){if(t.refreshToken)try{return await this.refreshTokens(e,t.refreshToken)}catch(r){return f.warn(`[NeuroLinkOAuthProvider] Token refresh failed: ${r instanceof Error?r.message:String(r)}`),await this.storage.deleteTokens(e),null}return await this.storage.deleteTokens(e),null}return t}async saveTokens(e,t){await this.storage.saveTokens(e,t)}async deleteTokens(e){await this.storage.deleteTokens(e)}clientInformation(){return{clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:this.config.redirectUrl}}redirectToAuthorization(e){const t=this.generateState();this.pendingStates.add(t);const r=new URL(this.config.authorizationUrl);r.searchParams.set("response_type","code"),r.searchParams.set("client_id",this.config.clientId),r.searchParams.set("redirect_uri",this.config.redirectUrl),r.searchParams.set("state",t),this.config.scope&&r.searchParams.set("scope",this.config.scope);let n;if(this.config.usePKCE){const o=this.generatePKCE();n=o.codeVerifier,this.pendingChallenges.set(t,o),r.searchParams.set("code_challenge",o.codeChallenge),r.searchParams.set("code_challenge_method",o.codeChallengeMethod)}if(this.config.additionalParams)for(const[o,i]of Object.entries(this.config.additionalParams))r.searchParams.set(o,i);return{url:r.toString(),state:t,codeVerifier:n}}async exchangeCode(e,t){if(!this.pendingStates.has(t.state))throw new Error("Invalid or expired state parameter");this.pendingStates.delete(t.state);let r=t.codeVerifier;if(this.config.usePKCE&&!r){const a=this.pendingChallenges.get(t.state);a&&(r=a.codeVerifier,this.pendingChallenges.delete(t.state))}const n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",t.code),n.set("redirect_uri",this.config.redirectUrl),n.set("client_id",this.config.clientId),this.config.clientSecret&&n.set("client_secret",this.config.clientSecret),r&&n.set("code_verifier",r);const o=await Ge(fetch(this.config.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:n.toString()}),gy,new Error(`OAuth token exchange timed out after ${gy}ms`));if(!o.ok){const a=await o.text();throw new Error(`Token exchange failed: ${o.status} ${o.statusText} - ${a}`)}const i=await o.json(),s={accessToken:i.access_token,refreshToken:i.refresh_token,expiresAt:i.expires_in?pue(i.expires_in):void 0,tokenType:i.token_type??"Bearer",scope:i.scope};return await this.saveTokens(e,s),s}async refreshTokens(e,t){const r=new URLSearchParams;r.set("grant_type","refresh_token"),r.set("refresh_token",t),r.set("client_id",this.config.clientId),this.config.clientSecret&&r.set("client_secret",this.config.clientSecret);const n=await Ge(fetch(this.config.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:r.toString()}),gy,new Error(`OAuth token refresh timed out after ${gy}ms`));if(!n.ok){const s=await n.text();throw new Error(`Token refresh failed: ${n.status} ${n.statusText} - ${s}`)}const o=await n.json(),i={accessToken:o.access_token,refreshToken:o.refresh_token??t,expiresAt:o.expires_in?pue(o.expires_in):void 0,tokenType:o.token_type??"Bearer",scope:o.scope};return await this.saveTokens(e,i),i}async revokeTokens(e,t){const r=await this.storage.getTokens(e);if(!r)return;const n=new URLSearchParams;n.set("token",r.accessToken),n.set("client_id",this.config.clientId),this.config.clientSecret&&n.set("client_secret",this.config.clientSecret);try{await Ge(fetch(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()}),gy,new Error(`OAuth token revocation timed out after ${gy}ms`))}catch(o){f.warn(`[NeuroLinkOAuthProvider] Token revocation failed: ${o instanceof Error?o.message:String(o)}`)}await this.storage.deleteTokens(e)}async getAuthorizationHeader(e){const t=await this.tokens(e);return t?`${t.tokenType} ${t.accessToken}`:null}async hasValidTokens(e){return await this.tokens(e)!==null}generateState(){return pg(32).toString("base64url")}generatePKCE(){const e=pg(32).toString("base64url"),t=sc("sha256").update(e).digest("base64url");return{codeVerifier:e,codeChallenge:t,codeChallengeMethod:"S256"}}getConfig(){return{...this.config}}getStorage(){return this.storage}cleanupPendingRequests(){this.pendingStates.size>100&&this.pendingStates.clear(),this.pendingChallenges.size>100&&this.pendingChallenges.clear()}}}}),Rer=S({"src/lib/mcp/auth/index.ts"(){"use strict";Ier(),Syn()}});function kyn(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function Ayn(e){const t=e.endsWith(".")?e.slice(0,-1):e;return t==="localhost"||t.endsWith(".localhost")}function mue(e){const t=jb(e);if(t===0)throw new Error(`"${e}" is not an IP address`);const r=t===4?"ipv4":"ipv6";return k6.check(e,r)?"loopback":xa.check(e,r)?"private":"public"}function Rc(e){return e.serverId?`MCP server "${e.serverId}" (${e.transport})`:`MCP ${e.transport} transport`}async function Cyn(e){return(await m3(e,{all:!0,verbatim:!0})).map(r=>r.address)}async function Mer(e,t){let r;try{r=new URL(e)}catch{throw new Error(`${Rc(t)}: "${e}" is not a valid URL`)}const n=r.protocol,o=Der.has(n);if(!o&&!Per.has(n))throw new Error(`${Rc(t)}: scheme "${n}" is not allowed (use https:, wss:, or http:/ws: for a loopback host)`);const i=kyn(r.hostname).toLowerCase();if(i.length===0)throw new Error(`${Rc(t)}: "${e}" has no host`);if(t.hostOwnedEgress===!0)return;const s=t.allowPrivateNetwork===!0,a=Ayn(i)?"loopback":jb(i)!==0?mue(i):void 0;if(a!==void 0){if(a==="loopback")return;if(!s){if(a==="private")throw new Error(`${Rc(t)}: "${e}" points at a private, link-local or metadata address; set "allowPrivateNetwork": true on this server if that is intended`);if(!o)throw new Error(`${Rc(t)}: "${e}" uses plaintext ${n} to a non-loopback host; use ${n==="ws:"?"wss:":"https:"}`);return}if(a==="public"&&!o)throw new Error(`${Rc(t)}: "${e}" uses plaintext ${n} to a public host; allowPrivateNetwork only permits plaintext to private addresses`);return}if(!o&&!s)throw new Error(`${Rc(t)}: "${e}" uses plaintext ${n} to a non-loopback host; use ${n==="ws:"?"wss:":"https:"}, or set "allowPrivateNetwork": true for a server on your own network`);let u;try{u=await Cyn(i)}catch(c){throw new Error(`${Rc(t)}: host "${i}" could not be resolved (${c instanceof Error?c.message:String(c)})`,{cause:c})}if(u.length===0)throw new Error(`${Rc(t)}: host "${i}" resolved to no addresses`);const l=u.map(c=>({address:c,cls:mue(c)}));if(!s){const c=l.find(d=>d.cls!=="public");if(c)throw new Error(`${Rc(t)}: host "${i}" resolves to ${c.address}, a ${c.cls} address; set "allowPrivateNetwork": true on this server if that is intended`);return}if(!o&&l.some(c=>c.cls==="public"))throw new Error(`${Rc(t)}: "${e}" uses plaintext ${n} to a host that resolves to a public address; allowPrivateNetwork only permits plaintext to private addresses`)}var Per,Der,k6,xa,Oer=S({"src/lib/mcp/transportUrlPolicy.ts"(){"use strict";fyt(),Bte(),Per=new Set(["http:","ws:"]),Der=new Set(["https:","wss:"]),k6=new Fte,k6.addSubnet("127.0.0.0",8,"ipv4"),k6.addAddress("::1","ipv6"),xa=new Fte,xa.addSubnet("0.0.0.0",8,"ipv4"),xa.addSubnet("10.0.0.0",8,"ipv4"),xa.addSubnet("100.64.0.0",10,"ipv4"),xa.addSubnet("169.254.0.0",16,"ipv4"),xa.addSubnet("172.16.0.0",12,"ipv4"),xa.addSubnet("192.0.0.0",24,"ipv4"),xa.addSubnet("192.168.0.0",16,"ipv4"),xa.addSubnet("198.18.0.0",15,"ipv4"),xa.addSubnet("224.0.0.0",4,"ipv4"),xa.addSubnet("240.0.0.0",4,"ipv4"),xa.addAddress("::","ipv6"),xa.addSubnet("fc00::",7,"ipv6"),xa.addSubnet("fe80::",10,"ipv6")}}),xyn=S({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/mini/parse.js"(){Ba()}}),Iyn=S({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/mini/schemas.js"(){}}),Ryn=S({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/mini/checks.js"(){}}),Myn=S({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/mini/iso.js"(){}}),Pyn=S({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/mini/coerce.js"(){}}),Dyn=S({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/mini/external.js"(){Ba(),xyn(),Iyn(),Ryn(),vq(),Myn(),Pyn()}}),Oyn=S({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4-mini/index.js"(){Dyn()}});function hue(e){return!!e._zod}function mf(e,t){return hue(e)?Uz(e,t):e.safeParse(t)}function Ner(e){if(!e)return;let t;if(hue(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function Ler(e){if(hue(e)){const i=e._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}const r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}const n=e.value;if(n!==void 0)return n}var fue=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.1_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js"(){Oyn()}}),Nyn=S({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/index.js"(){GV()}}),$er=S({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/index.js"(){Nyn()}}),_1,Fer,hf,E1,Gi,gue,yue,Lyn,Uer,Ber,A6,uu,$T,zer,Is,Xu,Yu,Rs,S1,vue,C6,wue,Ger,x6,FT,jt,I6,qer,yy,$yn,vy,jer,R6,Ver,UT,wy,bue,Her,Wer,Ker,Jer,Xer,Yer,Zer,Qer,Tue,_ue,etr,M6,ttr,rtr,P6,ntr,BT,zT,otr,GT,qT,itr,k1,D6,O6,N6,Fyn,L6,$6,F6,str,Eue,Sue,U6,kue,jT,by,Aue,atr,utr,Cue,ltr,xue,B6,ctr,dtr,Iue,Rue,ptr,mtr,htr,ftr,gtr,ytr,vtr,wtr,btr,Mue,Ttr,_tr,z6,G6,q6,Etr,Str,ktr,j6,Atr,Pue,Due,Ctr,xtr,Oue,Itr,Nue,A1,Uyn,Rtr,Mtr,Lue,Ptr,$ue,Dtr,Otr,Ntr,Ltr,$tr,Ftr,Utr,Btr,ztr,C1,Gtr,qtr,Fue,Uue,Bue,jtr,Vtr,Htr,Wtr,Ktr,Jtr,Xtr,Ytr,Ztr,Qtr,err,trr,rrr,nrr,orr,zue,irr,srr,Gue,arr,urr,lrr,crr,que,drr,prr,mrr,hrr,Byn,zyn,Gyn,qyn,jyn,Vyn,Ft,frr,ff=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.1_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js"(){$er(),_1="2025-11-25",Fer=[_1,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],hf="io.modelcontextprotocol/related-task",E1="2.0",Gi=IV(e=>e!==null&&(typeof e=="object"||typeof e=="function")),gue=vn([ie(),Br().int()]),yue=ie(),Lyn=ts({ttl:Br().optional(),pollInterval:Br().optional()}),Uer=it({ttl:Br().optional()}),Ber=it({taskId:ie()}),A6=ts({progressToken:gue.optional(),[hf]:Ber.optional()}),uu=it({_meta:A6.optional()}),$T=uu.extend({task:Uer.optional()}),zer=e=>$T.safeParse(e).success,Is=it({method:ie(),params:uu.loose().optional()}),Xu=it({_meta:A6.optional()}),Yu=it({method:ie(),params:Xu.loose().optional()}),Rs=ts({_meta:A6.optional()}),S1=vn([ie(),Br().int()]),vue=it({jsonrpc:Et(E1),id:S1,...Is.shape}).strict(),C6=e=>vue.safeParse(e).success,wue=it({jsonrpc:Et(E1),...Yu.shape}).strict(),Ger=e=>wue.safeParse(e).success,x6=it({jsonrpc:Et(E1),id:S1,result:Rs}).strict(),FT=e=>x6.safeParse(e).success,(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(jt||(jt={})),I6=it({jsonrpc:Et(E1),id:S1.optional(),error:it({code:Br().int(),message:ie(),data:Cn().optional()})}).strict(),qer=e=>I6.safeParse(e).success,yy=vn([vue,wue,x6,I6]),$yn=vn([x6,I6]),vy=Rs.strict(),jer=Xu.extend({requestId:S1.optional(),reason:ie().optional()}),R6=Yu.extend({method:Et("notifications/cancelled"),params:jer}),Ver=it({src:ie(),mimeType:ie().optional(),sizes:Ze(ie()).optional(),theme:Qs(["light","dark"]).optional()}),UT=it({icons:Ze(Ver).optional()}),wy=it({name:ie(),title:ie().optional()}),bue=wy.extend({...wy.shape,...UT.shape,version:ie(),websiteUrl:ie().optional(),description:ie().optional()}),Her=ok(it({applyDefaults:yn().optional()}),wn(ie(),Cn())),Wer=f2(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,ok(it({form:Her.optional(),url:Gi.optional()}),wn(ie(),Cn()).optional())),Ker=ts({list:Gi.optional(),cancel:Gi.optional(),requests:ts({sampling:ts({createMessage:Gi.optional()}).optional(),elicitation:ts({create:Gi.optional()}).optional()}).optional()}),Jer=ts({list:Gi.optional(),cancel:Gi.optional(),requests:ts({tools:ts({call:Gi.optional()}).optional()}).optional()}),Xer=it({experimental:wn(ie(),Gi).optional(),sampling:it({context:Gi.optional(),tools:Gi.optional()}).optional(),elicitation:Wer.optional(),roots:it({listChanged:yn().optional()}).optional(),tasks:Ker.optional(),extensions:wn(ie(),Gi).optional()}),Yer=uu.extend({protocolVersion:ie(),capabilities:Xer,clientInfo:bue}),Zer=Is.extend({method:Et("initialize"),params:Yer}),Qer=it({experimental:wn(ie(),Gi).optional(),logging:Gi.optional(),completions:Gi.optional(),prompts:it({listChanged:yn().optional()}).optional(),resources:it({subscribe:yn().optional(),listChanged:yn().optional()}).optional(),tools:it({listChanged:yn().optional()}).optional(),tasks:Jer.optional(),extensions:wn(ie(),Gi).optional()}),Tue=Rs.extend({protocolVersion:ie(),capabilities:Qer,serverInfo:bue,instructions:ie().optional()}),_ue=Yu.extend({method:Et("notifications/initialized"),params:Xu.optional()}),etr=e=>_ue.safeParse(e).success,M6=Is.extend({method:Et("ping"),params:uu.optional()}),ttr=it({progress:Br(),total:xn(Br()),message:xn(ie())}),rtr=it({...Xu.shape,...ttr.shape,progressToken:gue}),P6=Yu.extend({method:Et("notifications/progress"),params:rtr}),ntr=uu.extend({cursor:yue.optional()}),BT=Is.extend({params:ntr.optional()}),zT=Rs.extend({nextCursor:yue.optional()}),otr=Qs(["working","input_required","completed","failed","cancelled"]),GT=it({taskId:ie(),status:otr,ttl:vn([Br(),l2()]),createdAt:ie(),lastUpdatedAt:ie(),pollInterval:xn(Br()),statusMessage:xn(ie())}),qT=Rs.extend({task:GT}),itr=Xu.merge(GT),k1=Yu.extend({method:Et("notifications/tasks/status"),params:itr}),D6=Is.extend({method:Et("tasks/get"),params:uu.extend({taskId:ie()})}),O6=Rs.merge(GT),N6=Is.extend({method:Et("tasks/result"),params:uu.extend({taskId:ie()})}),Fyn=Rs.loose(),L6=BT.extend({method:Et("tasks/list")}),$6=zT.extend({tasks:Ze(GT)}),F6=Is.extend({method:Et("tasks/cancel"),params:uu.extend({taskId:ie()})}),str=Rs.merge(GT),Eue=it({uri:ie(),mimeType:xn(ie()),_meta:wn(ie(),Cn()).optional()}),Sue=Eue.extend({text:ie()}),U6=ie().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),kue=Eue.extend({blob:U6}),jT=Qs(["user","assistant"]),by=it({audience:Ze(jT).optional(),priority:Br().min(0).max(1).optional(),lastModified:J2.datetime({offset:!0}).optional()}),Aue=it({...wy.shape,...UT.shape,uri:ie(),description:xn(ie()),mimeType:xn(ie()),size:xn(Br()),annotations:by.optional(),_meta:xn(ts({}))}),atr=it({...wy.shape,...UT.shape,uriTemplate:ie(),description:xn(ie()),mimeType:xn(ie()),annotations:by.optional(),_meta:xn(ts({}))}),utr=BT.extend({method:Et("resources/list")}),Cue=zT.extend({resources:Ze(Aue)}),ltr=BT.extend({method:Et("resources/templates/list")}),xue=zT.extend({resourceTemplates:Ze(atr)}),B6=uu.extend({uri:ie()}),ctr=B6,dtr=Is.extend({method:Et("resources/read"),params:ctr}),Iue=Rs.extend({contents:Ze(vn([Sue,kue]))}),Rue=Yu.extend({method:Et("notifications/resources/list_changed"),params:Xu.optional()}),ptr=B6,mtr=Is.extend({method:Et("resources/subscribe"),params:ptr}),htr=B6,ftr=Is.extend({method:Et("resources/unsubscribe"),params:htr}),gtr=Xu.extend({uri:ie()}),ytr=Yu.extend({method:Et("notifications/resources/updated"),params:gtr}),vtr=it({name:ie(),description:xn(ie()),required:xn(yn())}),wtr=it({...wy.shape,...UT.shape,description:xn(ie()),arguments:xn(Ze(vtr)),_meta:xn(ts({}))}),btr=BT.extend({method:Et("prompts/list")}),Mue=zT.extend({prompts:Ze(wtr)}),Ttr=uu.extend({name:ie(),arguments:wn(ie(),ie()).optional()}),_tr=Is.extend({method:Et("prompts/get"),params:Ttr}),z6=it({type:Et("text"),text:ie(),annotations:by.optional(),_meta:wn(ie(),Cn()).optional()}),G6=it({type:Et("image"),data:U6,mimeType:ie(),annotations:by.optional(),_meta:wn(ie(),Cn()).optional()}),q6=it({type:Et("audio"),data:U6,mimeType:ie(),annotations:by.optional(),_meta:wn(ie(),Cn()).optional()}),Etr=it({type:Et("tool_use"),name:ie(),id:ie(),input:wn(ie(),Cn()),_meta:wn(ie(),Cn()).optional()}),Str=it({type:Et("resource"),resource:vn([Sue,kue]),annotations:by.optional(),_meta:wn(ie(),Cn()).optional()}),ktr=Aue.extend({type:Et("resource_link")}),j6=vn([z6,G6,q6,ktr,Str]),Atr=it({role:jT,content:j6}),Pue=Rs.extend({description:ie().optional(),messages:Ze(Atr)}),Due=Yu.extend({method:Et("notifications/prompts/list_changed"),params:Xu.optional()}),Ctr=it({title:ie().optional(),readOnlyHint:yn().optional(),destructiveHint:yn().optional(),idempotentHint:yn().optional(),openWorldHint:yn().optional()}),xtr=it({taskSupport:Qs(["required","optional","forbidden"]).optional()}),Oue=it({...wy.shape,...UT.shape,description:ie().optional(),inputSchema:it({type:Et("object"),properties:wn(ie(),Gi).optional(),required:Ze(ie()).optional()}).catchall(Cn()),outputSchema:it({type:Et("object"),properties:wn(ie(),Gi).optional(),required:Ze(ie()).optional()}).catchall(Cn()).optional(),annotations:Ctr.optional(),execution:xtr.optional(),_meta:wn(ie(),Cn()).optional()}),Itr=BT.extend({method:Et("tools/list")}),Nue=zT.extend({tools:Ze(Oue)}),A1=Rs.extend({content:Ze(j6).default([]),structuredContent:wn(ie(),Cn()).optional(),isError:yn().optional()}),Uyn=A1.or(Rs.extend({toolResult:Cn()})),Rtr=$T.extend({name:ie(),arguments:wn(ie(),Cn()).optional()}),Mtr=Is.extend({method:Et("tools/call"),params:Rtr}),Lue=Yu.extend({method:Et("notifications/tools/list_changed"),params:Xu.optional()}),Ptr=it({autoRefresh:yn().default(!0),debounceMs:Br().int().nonnegative().default(300)}),$ue=Qs(["debug","info","notice","warning","error","critical","alert","emergency"]),Dtr=uu.extend({level:$ue}),Otr=Is.extend({method:Et("logging/setLevel"),params:Dtr}),Ntr=Xu.extend({level:$ue,logger:ie().optional(),data:Cn()}),Ltr=Yu.extend({method:Et("notifications/message"),params:Ntr}),$tr=it({name:ie().optional()}),Ftr=it({hints:Ze($tr).optional(),costPriority:Br().min(0).max(1).optional(),speedPriority:Br().min(0).max(1).optional(),intelligencePriority:Br().min(0).max(1).optional()}),Utr=it({mode:Qs(["auto","required","none"]).optional()}),Btr=it({type:Et("tool_result"),toolUseId:ie().describe("The unique identifier for the corresponding tool call."),content:Ze(j6).default([]),structuredContent:it({}).loose().optional(),isError:yn().optional(),_meta:wn(ie(),Cn()).optional()}),ztr=d2("type",[z6,G6,q6]),C1=d2("type",[z6,G6,q6,Etr,Btr]),Gtr=it({role:jT,content:vn([C1,Ze(C1)]),_meta:wn(ie(),Cn()).optional()}),qtr=$T.extend({messages:Ze(Gtr),modelPreferences:Ftr.optional(),systemPrompt:ie().optional(),includeContext:Qs(["none","thisServer","allServers"]).optional(),temperature:Br().optional(),maxTokens:Br().int(),stopSequences:Ze(ie()).optional(),metadata:Gi.optional(),tools:Ze(Oue).optional(),toolChoice:Utr.optional()}),Fue=Is.extend({method:Et("sampling/createMessage"),params:qtr}),Uue=Rs.extend({model:ie(),stopReason:xn(Qs(["endTurn","stopSequence","maxTokens"]).or(ie())),role:jT,content:ztr}),Bue=Rs.extend({model:ie(),stopReason:xn(Qs(["endTurn","stopSequence","maxTokens","toolUse"]).or(ie())),role:jT,content:vn([C1,Ze(C1)])}),jtr=it({type:Et("boolean"),title:ie().optional(),description:ie().optional(),default:yn().optional()}),Vtr=it({type:Et("string"),title:ie().optional(),description:ie().optional(),minLength:Br().optional(),maxLength:Br().optional(),format:Qs(["email","uri","date","date-time"]).optional(),default:ie().optional()}),Htr=it({type:Qs(["number","integer"]),title:ie().optional(),description:ie().optional(),minimum:Br().optional(),maximum:Br().optional(),default:Br().optional()}),Wtr=it({type:Et("string"),title:ie().optional(),description:ie().optional(),enum:Ze(ie()),default:ie().optional()}),Ktr=it({type:Et("string"),title:ie().optional(),description:ie().optional(),oneOf:Ze(it({const:ie(),title:ie()})),default:ie().optional()}),Jtr=it({type:Et("string"),title:ie().optional(),description:ie().optional(),enum:Ze(ie()),enumNames:Ze(ie()).optional(),default:ie().optional()}),Xtr=vn([Wtr,Ktr]),Ytr=it({type:Et("array"),title:ie().optional(),description:ie().optional(),minItems:Br().optional(),maxItems:Br().optional(),items:it({type:Et("string"),enum:Ze(ie())}),default:Ze(ie()).optional()}),Ztr=it({type:Et("array"),title:ie().optional(),description:ie().optional(),minItems:Br().optional(),maxItems:Br().optional(),items:it({anyOf:Ze(it({const:ie(),title:ie()}))}),default:Ze(ie()).optional()}),Qtr=vn([Ytr,Ztr]),err=vn([Jtr,Xtr,Qtr]),trr=vn([err,jtr,Vtr,Htr]),rrr=$T.extend({mode:Et("form").optional(),message:ie(),requestedSchema:it({type:Et("object"),properties:wn(ie(),trr),required:Ze(ie()).optional()})}),nrr=$T.extend({mode:Et("url"),message:ie(),elicitationId:ie(),url:ie().url()}),orr=vn([rrr,nrr]),zue=Is.extend({method:Et("elicitation/create"),params:orr}),irr=Xu.extend({elicitationId:ie()}),srr=Yu.extend({method:Et("notifications/elicitation/complete"),params:irr}),Gue=Rs.extend({action:Qs(["accept","decline","cancel"]),content:f2(e=>e===null?void 0:e,wn(ie(),vn([ie(),Br(),yn(),Ze(ie())])).optional())}),arr=it({type:Et("ref/resource"),uri:ie()}),urr=it({type:Et("ref/prompt"),name:ie()}),lrr=uu.extend({ref:vn([urr,arr]),argument:it({name:ie(),value:ie()}),context:it({arguments:wn(ie(),ie()).optional()}).optional()}),crr=Is.extend({method:Et("completion/complete"),params:lrr}),que=Rs.extend({completion:ts({values:Ze(ie()).max(100),total:xn(Br().int()),hasMore:xn(yn())})}),drr=it({uri:ie().startsWith("file://"),name:ie().optional(),_meta:wn(ie(),Cn()).optional()}),prr=Is.extend({method:Et("roots/list"),params:uu.optional()}),mrr=Rs.extend({roots:Ze(drr)}),hrr=Yu.extend({method:Et("notifications/roots/list_changed"),params:Xu.optional()}),Byn=vn([M6,Zer,crr,Otr,_tr,btr,utr,ltr,dtr,mtr,ftr,Mtr,Itr,D6,N6,L6,F6]),zyn=vn([R6,P6,_ue,hrr,k1]),Gyn=vn([vy,Uue,Bue,Gue,mrr,O6,$6,qT]),qyn=vn([M6,Fue,zue,prr,D6,N6,L6,F6]),jyn=vn([R6,P6,Ltr,ytr,Rue,Lue,Due,k1,srr]),Vyn=vn([vy,Tue,que,Pue,Mue,Cue,xue,Iue,A1,Nue,O6,$6,qT]),Ft=class X5r extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===jt.UrlElicitationRequired&&n){const o=n;if(o.elicitations)return new frr(o.elicitations,r)}return new X5r(t,r,n)}},frr=class extends Ft{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(jt.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}}});function Ty(e){return e==="completed"||e==="failed"||e==="cancelled"}var Hyn=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.1_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js"(){}});function grr(e){const r=Ner(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=Ler(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function yrr(e,t){const r=mf(e,t);if(!r.success)throw r.error;return r.data}var Wyn=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.1_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js"(){fue(),MH()}});function vrr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Kyn(e,t){const r={...e};for(const n in t){const o=n,i=t[o];if(i===void 0)continue;const s=r[o];vrr(s)&&vrr(i)?r[o]={...s,...i}:r[o]=i}return r}var wrr,brr,Jyn=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.1_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js"(){fue(),ff(),Hyn(),Wyn(),wrr=6e4,brr=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(R6,t=>{this._oncancel(t)}),this.setNotificationHandler(P6,t=>{this._onprogress(t)}),this.setRequestHandler(M6,t=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(D6,async(t,r)=>{const n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new Ft(jt.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(N6,async(t,r)=>{const n=async()=>{const o=t.params.taskId;if(!await this._taskStore.getTask(o,r.sessionId))throw new Ft(jt.InvalidParams,`Task not found: ${o}`);if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(o,r.sessionId);){if(s.type==="response"||s.type==="error"){const a=s.message,u=a.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),s.type==="response")l(a);else{const c=a,d=new Ft(c.error.code,c.error.message,c.error.data);l(d)}else{const c=s.type==="response"?"Response":"Error";this._onerror(new Error(`${c} handler missing for request ${u}`))}continue}await this._transport?.send(s.message,{relatedRequestId:r.requestId})}}const i=await this._taskStore.getTask(o,r.sessionId);if(!i)throw new Ft(jt.InvalidParams,`Task not found: ${o}`);if(!Ty(i.status))return await this._waitForTaskUpdate(o,r.signal,r.sessionId),await n();if(Ty(i.status)){const s=await this._taskStore.getTaskResult(o,r.sessionId);return this._clearTaskQueue(o,r.sessionId),{...s,_meta:{...s._meta,[hf]:{taskId:o}}}}return await n()};return await n()}),this.setRequestHandler(L6,async(t,r)=>{try{const{tasks:n,nextCursor:o}=await this._taskStore.listTasks(t.params?.cursor,r.sessionId);return{tasks:n,nextCursor:o,_meta:{}}}catch(n){throw new Ft(jt.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(F6,async(t,r)=>{try{const n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new Ft(jt.InvalidParams,`Task not found: ${t.params.taskId}`);if(Ty(n.status))throw new Ft(jt.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(t.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(t.params.taskId,r.sessionId);const o=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!o)throw new Ft(jt.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...o}}catch(n){throw n instanceof Ft?n:new Ft(jt.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,n,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:o,onTimeout:n})}_resetTimeout(e){const t=this._timeoutInfo.get(e);if(!t)return!1;const r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),Ft.fromError(jt.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){const t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;const t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};const r=this.transport?.onerror;this._transport.onerror=o=>{r?.(o),this._onerror(o)};const n=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{n?.(o,i),FT(o)||qer(o)?this._onresponse(o):C6(o)?this._onrequest(o,i):Ger(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(const r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();const t=Ft.fromError(jt.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const r of e.values())r(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){const t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(r=>this._onerror(new Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,t){const r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,n=this._transport,o=e.params?._meta?.[hf]?.taskId,i=n?.sessionId,s=this._taskStore;let a=!0,u;if(o&&s&&this._taskMessageQueue&&i!==void 0&&(a=!1,u=(async()=>{if(!await s.getTask(o,i))throw new Ft(jt.InvalidParams,`Task not found: ${o}`);a=!0})()),r===void 0){const m={jsonrpc:"2.0",id:e.id,error:{code:jt.MethodNotFound,message:"Method not found"}};if(o&&u){const h={type:"error",message:m,timestamp:Date.now()};u.then(()=>this._enqueueTaskMessage(o,h,i),()=>n?.send(m)).catch(g=>this._onerror(new Error(`Failed to send an error response: ${g}`)))}else o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:m,timestamp:Date.now()},n?.sessionId).catch(h=>this._onerror(new Error(`Failed to enqueue error response: ${h}`))):n?.send(m).catch(h=>this._onerror(new Error(`Failed to send an error response: ${h}`)));return}const l=new AbortController;this._requestHandlerAbortControllers.set(e.id,l);const c=zer(e.params)?e.params.task:void 0,d=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,p={signal:l.signal,sessionId:n?.sessionId,_meta:e.params?._meta,sendNotification:async m=>{if(l.signal.aborted)return;const h={relatedRequestId:e.id};o&&(h.relatedTask={taskId:o}),await this.notification(m,h)},sendRequest:async(m,h,g)=>{if(l.signal.aborted)throw new Ft(jt.ConnectionClosed,"Request was cancelled");const y={...g,relatedRequestId:e.id};o&&!y.relatedTask&&(y.relatedTask={taskId:o});const v=y.relatedTask?.taskId??o;return v&&d&&await d.updateTaskStatus(v,"input_required"),await this.request(m,h,y)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:o,taskStore:d,taskRequestedTtl:c?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};(u??Promise.resolve()).then(()=>{if(u&&l.signal.aborted)throw new Ft(jt.ConnectionClosed,"Request was cancelled");c&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,p)).then(async m=>{if(l.signal.aborted)return;const h={result:m,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:h,timestamp:Date.now()},n?.sessionId):await n?.send(h)},async m=>{if(l.signal.aborted)return;const h={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(m.code)?m.code:jt.InternalError,message:m.message??"Internal error",...m.data!==void 0&&{data:m.data}}};o&&this._taskMessageQueue&&a?await this._enqueueTaskMessage(o,{type:"error",message:h,timestamp:Date.now()},n?.sessionId):await n?.send(h)}).catch(m=>this._onerror(new Error(`Failed to send response: ${m}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===l&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:t,...r}=e.params,n=Number(t),o=this._progressHandlers.get(n);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}const i=this._responseHandlers.get(n),s=this._timeoutInfo.get(n);if(s&&i&&s.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(a){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),i(a);return}o(r)}_onresponse(e){const t=Number(e.id),r=this._requestResolvers.get(t);if(r){if(this._requestResolvers.delete(t),FT(e))r(e);else{const i=new Ft(e.error.code,e.error.message,e.error.data);r(i)}return}const n=this._responseHandlers.get(t);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let o=!1;if(FT(e)&&e.result&&typeof e.result=="object"){const i=e.result;if(i.task&&typeof i.task=="object"){const s=i.task;typeof s.taskId=="string"&&(o=!0,this._taskProgressTokens.set(s.taskId,t))}}if(o||this._progressHandlers.delete(t),FT(e))n(e);else{const i=Ft.fromError(e.error.code,e.error.message,e.error.data);n(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,r){const{task:n}=r??{};if(!n){try{yield{type:"result",result:await this.request(e,t,r)}}catch(i){yield{type:"error",error:i instanceof Ft?i:new Ft(jt.InternalError,String(i))}}return}let o;try{const i=await this.request(e,qT,r);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new Ft(jt.InternalError,"Task creation did not return a task");for(;;){const s=await this.getTask({taskId:o},r);if(yield{type:"taskStatus",task:s},Ty(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)}:s.status==="failed"?yield{type:"error",error:new Ft(jt.InternalError,`Task ${o} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new Ft(jt.InternalError,`Task ${o} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)};return}const a=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,a)),r?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof Ft?i:new Ft(jt.InternalError,String(i))}}}request(e,t,r){const{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i,task:s,relatedTask:a}=r??{};return new Promise((u,l)=>{const c=v=>{l(v)};if(!this._transport){c(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),s&&this.assertTaskCapability(e.method)}catch(v){c(v);return}r?.signal?.throwIfAborted();const d=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:d};r?.onprogress&&(this._progressHandlers.set(d,r.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),s&&(p.params={...p.params,task:s}),a&&(p.params={...p.params,_meta:{...p.params?._meta||{},[hf]:a}});const m=v=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String(v)}},{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i}).catch(T=>this._onerror(new Error(`Failed to send cancellation: ${T}`)));const w=v instanceof Ft?v:new Ft(jt.RequestTimeout,String(v));l(w)};this._responseHandlers.set(d,v=>{if(!r?.signal?.aborted){if(v instanceof Error)return l(v);try{const w=mf(t,v.result);w.success?u(w.data):l(w.error)}catch(w){l(w)}}}),r?.signal?.addEventListener("abort",()=>{m(r?.signal?.reason)});const h=r?.timeout??wrr,g=()=>m(Ft.fromError(jt.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(d,h,r?.maxTotalTimeout,g,r?.resetTimeoutOnProgress??!1);const y=a?.taskId;if(y){const v=w=>{const T=this._responseHandlers.get(d);T?T(w):this._onerror(new Error(`Response handler missing for side-channeled request ${d}`))};this._requestResolvers.set(d,v),this._enqueueTaskMessage(y,{type:"request",message:p,timestamp:Date.now()}).catch(w=>{this._cleanupTimeout(d),l(w)})}else this._transport.send(p,{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i}).catch(v=>{this._cleanupTimeout(d),l(v)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},O6,t)}async getTaskResult(e,t,r){return this.request({method:"tasks/result",params:e},t,r)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},$6,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},str,t)}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const r=t?.relatedTask?.taskId;if(r){const s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[hf]:t.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let s={...e,jsonrpc:"2.0"};t?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[hf]:t.relatedTask}}}),this._transport?.send(s,t).catch(a=>this._onerror(a))});return}let i={...e,jsonrpc:"2.0"};t?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[hf]:t.relatedTask}}}),await this._transport.send(i,t)}setRequestHandler(e,t){const r=grr(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(n,o)=>{const i=yrr(e,n);return Promise.resolve(t(i,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){const r=grr(e);this._notificationHandlers.set(r,n=>{const o=yrr(e,n);return Promise.resolve(t(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){const t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,r){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,r??this._transport?.sessionId,n)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){const r=await this._taskMessageQueue.dequeueAll(e,t);for(const n of r)if(n.type==="request"&&C6(n.message)){const o=n.message.id,i=this._requestResolvers.get(o);i?(i(new Ft(jt.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{const o=await this._taskStore?.getTask(e,r);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,i)=>{if(t.aborted){i(new Ft(jt.InvalidRequest,"Request cancelled"));return}const s=setTimeout(o,n);t.addEventListener("abort",()=>{clearTimeout(s),i(new Ft(jt.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){const r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async n=>{if(!e)throw new Error("No request provided");return await r.createTask(n,e.id,{method:e.method,params:e.params},t)},getTask:async n=>{const o=await r.getTask(n,t);if(!o)throw new Ft(jt.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(n,o,i)=>{await r.storeTaskResult(n,o,i,t);const s=await r.getTask(n,t);if(s){const a=k1.parse({method:"notifications/tasks/status",params:s});await this.notification(a),Ty(s.status)&&this._cleanupTaskProgressHandler(n)}},getTaskResult:n=>r.getTaskResult(n,t),updateTaskStatus:async(n,o,i)=>{const s=await r.getTask(n,t);if(!s)throw new Ft(jt.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(Ty(s.status))throw new Ft(jt.InvalidParams,`Cannot update task "${n}" from terminal status "${s.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(n,o,i,t);const a=await r.getTask(n,t);if(a){const u=k1.parse({method:"notifications/tasks/status",params:a});await this.notification(u),Ty(a.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>r.listTasks(n,t)}}}}}),_y,ms,Trr,Xyn,Yyn,Zyn,Qyn,evn,tvn,rvn,nvn,ovn,ivn,svn,avn,uvn,lvn,cvn,dvn,pvn,mvn,hvn,fvn,gvn,yvn,vvn,wvn,bvn,Tvn,_vn,Evn,Svn,kvn,Avn,Cvn,xvn,Ivn,Rvn,Mvn,Pvn,Dvn,Ovn,Nvn,Lvn,$vn,Fvn,Uvn,Bvn,zvn,Gvn=S({"npm-stub:ajv"(){_y={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:_y.get}):new Proxy(function(...r){return new Proxy({},{get:_y.get})},{get:_y.get,apply(r,n,o){return new Proxy({},{get:_y.get})},construct(r,n){return new Proxy({},{get:_y.get})}})}},ms=new Proxy({},_y),Trr=ms,{BedrockClient:Xyn,ListFoundationModelsCommand:Yyn,BedrockRuntimeClient:Zyn,ConverseCommand:Qyn,ConverseStreamCommand:evn,ImageFormat:tvn,InvokeModelCommand:rvn}=ms,{SageMakerRuntimeClient:nvn,InvokeEndpointCommand:ovn,InvokeEndpointWithResponseStreamCommand:ivn}=ms,{GoogleAuth:svn,VertexAI:avn,TextToSpeechClient:uvn}=ms,{Webhook:lvn}=ms,{Hippocampus:cvn,HippocampusConfig:dvn}=ms,{createClient:pvn}=ms,{Queue:mvn,Worker:hvn,Job:fvn,QueueScheduler:gvn,FlowProducer:yvn}=ms,{Cron:vvn}=ms,{parseBuffer:wvn,selectCover:bvn}=ms,{extractRawText:Tvn,convertToHtml:_vn}=ms,{Hono:Evn}=ms,{cors:Svn,HTTPException:kvn,logger:Avn,secureHeaders:Cvn,streamSSE:xvn,timeout:Ivn}=ms,Rvn=globalThis.fetch,Mvn=globalThis.Request,Pvn=globalThis.Response,Dvn=globalThis.Headers,Ovn=globalThis.FormData,Nvn=globalThis.File,Lvn=globalThis.Blob,$vn=ms.Agent,Fvn=ms.Pool,Uvn=ms.Client,Bvn=ms.Dispatcher,zvn=ms.MockAgent}}),Ey,hs,_rr,qvn,jvn,Vvn,Hvn,Wvn,Kvn,Jvn,Xvn,Yvn,Zvn,Qvn,ewn,twn,rwn,nwn,own,iwn,swn,awn,uwn,lwn,cwn,dwn,pwn,mwn,hwn,fwn,gwn,ywn,vwn,wwn,bwn,Twn,_wn,Ewn,Swn,kwn,Awn,Cwn,xwn,Iwn,Rwn,Mwn,Pwn,Dwn,Own,Nwn=S({"npm-stub:ajv-formats"(){Ey={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Ey.get}):new Proxy(function(...r){return new Proxy({},{get:Ey.get})},{get:Ey.get,apply(r,n,o){return new Proxy({},{get:Ey.get})},construct(r,n){return new Proxy({},{get:Ey.get})}})}},hs=new Proxy({},Ey),_rr=hs,{BedrockClient:qvn,ListFoundationModelsCommand:jvn,BedrockRuntimeClient:Vvn,ConverseCommand:Hvn,ConverseStreamCommand:Wvn,ImageFormat:Kvn,InvokeModelCommand:Jvn}=hs,{SageMakerRuntimeClient:Xvn,InvokeEndpointCommand:Yvn,InvokeEndpointWithResponseStreamCommand:Zvn}=hs,{GoogleAuth:Qvn,VertexAI:ewn,TextToSpeechClient:twn}=hs,{Webhook:rwn}=hs,{Hippocampus:nwn,HippocampusConfig:own}=hs,{createClient:iwn}=hs,{Queue:swn,Worker:awn,Job:uwn,QueueScheduler:lwn,FlowProducer:cwn}=hs,{Cron:dwn}=hs,{parseBuffer:pwn,selectCover:mwn}=hs,{extractRawText:hwn,convertToHtml:fwn}=hs,{Hono:gwn}=hs,{cors:ywn,HTTPException:vwn,logger:wwn,secureHeaders:bwn,streamSSE:Twn,timeout:_wn}=hs,Ewn=globalThis.fetch,Swn=globalThis.Request,kwn=globalThis.Response,Awn=globalThis.Headers,Cwn=globalThis.FormData,xwn=globalThis.File,Iwn=globalThis.Blob,Rwn=hs.Agent,Mwn=hs.Pool,Pwn=hs.Client,Dwn=hs.Dispatcher,Own=hs.MockAgent}});function Lwn(){const e=new Trr({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return _rr(e),e}var Err,$wn=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.1_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js"(){Gvn(),Nwn(),Err=class{constructor(e){this._ajv=e??Lwn()}getValidator(e){const t="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return r=>t(r)?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}}}}),Srr,Fwn=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.1_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js"(){ff(),Srr=class{constructor(e){this._client=e}async*callToolStream(e,t=A1,r){const n=this._client,o={...r,task:r?.task??(n.isToolTask(e.name)?{}:void 0)},i=n.requestStream({method:"tools/call",params:e},t,o),s=n.getToolOutputValidator(e.name);for await(const a of i){if(a.type==="result"&&s){const u=a.result;if(!u.structuredContent&&!u.isError){yield{type:"error",error:new Ft(jt.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(u.structuredContent)try{const l=s(u.structuredContent);if(!l.valid){yield{type:"error",error:new Ft(jt.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)};return}}catch(l){if(l instanceof Ft){yield{type:"error",error:l};return}yield{type:"error",error:new Ft(jt.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)};return}}yield a}}async getTask(e,t){return this._client.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._client.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._client.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._client.cancelTask({taskId:e},t)}requestStream(e,t,r){return this._client.requestStream(e,t,r)}}}});function Uwn(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function Bwn(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var zwn=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.1_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js"(){}}),krr={};ue(krr,{Client:()=>Crr,getSupportedElicitationModes:()=>Arr});function V6(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){const r=t,n=e.properties;for(const o of Object.keys(n)){const i=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(i,"default")&&(r[o]=i.default),r[o]!==void 0&&V6(i,r[o])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)typeof r!="boolean"&&V6(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)typeof r!="boolean"&&V6(r,t)}}function Arr(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};const t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}var Crr,Gwn=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.1_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js"(){Jyn(),ff(),$wn(),fue(),Fwn(),zwn(),Crr=class extends brr{constructor(e,t){super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=t?.capabilities??{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new Err,t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Lue,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Due,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Rue,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Srr(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Kyn(this._capabilities,e)}setRequestHandler(e,t){const n=Ner(e)?.method;if(!n)throw new Error("Schema is missing a method literal");const o=Ler(n);if(typeof o!="string")throw new Error("Schema method literal must be a string");const i=o;if(i==="elicitation/create"){const s=async(a,u)=>{const l=mf(zue,a);if(!l.success){const v=l.error instanceof Error?l.error.message:String(l.error);throw new Ft(jt.InvalidParams,`Invalid elicitation request: ${v}`)}const{params:c}=l.data;c.mode=c.mode??"form";const{supportsFormMode:d,supportsUrlMode:p}=Arr(this._capabilities.elicitation);if(c.mode==="form"&&!d)throw new Ft(jt.InvalidParams,"Client does not support form-mode elicitation requests");if(c.mode==="url"&&!p)throw new Ft(jt.InvalidParams,"Client does not support URL-mode elicitation requests");const m=await Promise.resolve(t(a,u));if(c.task){const v=mf(qT,m);if(!v.success){const w=v.error instanceof Error?v.error.message:String(v.error);throw new Ft(jt.InvalidParams,`Invalid task creation result: ${w}`)}return v.data}const h=mf(Gue,m);if(!h.success){const v=h.error instanceof Error?h.error.message:String(h.error);throw new Ft(jt.InvalidParams,`Invalid elicitation result: ${v}`)}const g=h.data,y=c.mode==="form"?c.requestedSchema:void 0;if(c.mode==="form"&&g.action==="accept"&&g.content&&y&&this._capabilities.elicitation?.form?.applyDefaults)try{V6(y,g.content)}catch{}return g};return super.setRequestHandler(e,s)}if(i==="sampling/createMessage"){const s=async(a,u)=>{const l=mf(Fue,a);if(!l.success){const g=l.error instanceof Error?l.error.message:String(l.error);throw new Ft(jt.InvalidParams,`Invalid sampling request: ${g}`)}const{params:c}=l.data,d=await Promise.resolve(t(a,u));if(c.task){const g=mf(qT,d);if(!g.success){const y=g.error instanceof Error?g.error.message:String(g.error);throw new Ft(jt.InvalidParams,`Invalid task creation result: ${y}`)}return g.data}const m=c.tools||c.toolChoice?Bue:Uue,h=mf(m,d);if(!h.success){const g=h.error instanceof Error?h.error.message:String(h.error);throw new Ft(jt.InvalidParams,`Invalid sampling result: ${g}`)}return h.data};return super.setRequestHandler(e,s)}return super.setRequestHandler(e,t)}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),e.sessionId===void 0)try{const r=await this.request({method:"initialize",params:{protocolVersion:_1,capabilities:this._capabilities,clientInfo:this._clientInfo}},Tue,t);if(r===void 0)throw new Error(`Server sent invalid initialize result: ${r}`);if(!Fer.includes(r.protocolVersion))throw new Error(`Server's protocol version is not supported: ${r.protocolVersion}`);this._serverCapabilities=r.capabilities,this._serverVersion=r.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(r.protocolVersion),this._instructions=r.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(r){throw this.close(),r}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break;case"ping":break}}assertTaskCapability(e){Uwn(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&Bwn(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},vy,e)}async complete(e,t){return this.request({method:"completion/complete",params:e},que,t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},vy,t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},Pue,t)}async listPrompts(e,t){return this.request({method:"prompts/list",params:e},Mue,t)}async listResources(e,t){return this.request({method:"resources/list",params:e},Cue,t)}async listResourceTemplates(e,t){return this.request({method:"resources/templates/list",params:e},xue,t)}async readResource(e,t){return this.request({method:"resources/read",params:e},Iue,t)}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},vy,t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},vy,t)}async callTool(e,t=A1,r){if(this.isToolTaskRequired(e.name))throw new Ft(jt.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const n=await this.request({method:"tools/call",params:e},t,r),o=this.getToolOutputValidator(e.name);if(o){if(!n.structuredContent&&!n.isError)throw new Ft(jt.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(n.structuredContent)try{const i=o(n.structuredContent);if(!i.valid)throw new Ft(jt.InvalidParams,`Structured content does not match the tool's output schema: ${i.errorMessage}`)}catch(i){throw i instanceof Ft?i:new Ft(jt.InvalidParams,`Failed to validate structured content: ${i instanceof Error?i.message:String(i)}`)}}return n}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const t of e){if(t.outputSchema){const n=this._jsonSchemaValidator.getValidator(t.outputSchema);this._cachedToolOutputValidators.set(t.name,n)}const r=t.execution?.taskSupport;(r==="required"||r==="optional")&&this._cachedKnownTaskTools.add(t.name),r==="required"&&this._cachedRequiredTaskTools.add(t.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){const r=await this.request({method:"tools/list",params:e},Nue,t);return this.cacheToolMetadata(r.tools),r}_setupListChangedHandler(e,t,r,n){const o=Ptr.safeParse(r);if(!o.success)throw new Error(`Invalid ${e} listChanged options: ${o.error.message}`);if(typeof r.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);const{autoRefresh:i,debounceMs:s}=o.data,{onChanged:a}=r,u=async()=>{if(!i){a(null,null);return}try{const c=await n();a(null,c)}catch(c){const d=c instanceof Error?c:new Error(String(c));a(d,null)}},l=()=>{if(s){const c=this._listChangedDebounceTimers.get(e);c&&clearTimeout(c);const d=setTimeout(u,s);this._listChangedDebounceTimers.set(e,d)}else u()};this.setNotificationHandler(t,l)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}}}),xrr={};ue(xrr,{Agent:()=>ynr,BedrockClient:()=>Rrr,BedrockRuntimeClient:()=>Prr,Blob:()=>gnr,Client:()=>wnr,ConverseCommand:()=>Drr,ConverseStreamCommand:()=>Orr,Cron:()=>Zrr,Dispatcher:()=>bnr,File:()=>fnr,FlowProducer:()=>Yrr,FormData:()=>hnr,GoogleAuth:()=>Brr,HTTPException:()=>inr,Headers:()=>mnr,Hippocampus:()=>jrr,HippocampusConfig:()=>Vrr,Hono:()=>nnr,ImageFormat:()=>Nrr,InvokeEndpointCommand:()=>Frr,InvokeEndpointWithResponseStreamCommand:()=>Urr,InvokeModelCommand:()=>Lrr,Job:()=>Jrr,ListFoundationModelsCommand:()=>Mrr,MockAgent:()=>Enr,Pool:()=>vnr,Queue:()=>Wrr,QueueScheduler:()=>Xrr,Request:()=>dnr,Response:()=>pnr,SageMakerRuntimeClient:()=>$rr,TextToSpeechClient:()=>Grr,VertexAI:()=>zrr,Webhook:()=>qrr,Worker:()=>Krr,convertToHtml:()=>rnr,cors:()=>onr,createClient:()=>Hrr,default:()=>Irr,extractRawText:()=>tnr,fetch:()=>cnr,getGlobalDispatcher:()=>_nr,interceptors:()=>Snr,logger:()=>snr,parseBuffer:()=>Qrr,request:()=>knr,secureHeaders:()=>anr,selectCover:()=>enr,setGlobalDispatcher:()=>Tnr,streamSSE:()=>unr,timeout:()=>lnr});var Sy,qi,Irr,Rrr,Mrr,Prr,Drr,Orr,Nrr,Lrr,$rr,Frr,Urr,Brr,zrr,Grr,qrr,jrr,Vrr,Hrr,Wrr,Krr,Jrr,Xrr,Yrr,Zrr,Qrr,enr,tnr,rnr,nnr,onr,inr,snr,anr,unr,lnr,cnr,dnr,pnr,mnr,hnr,fnr,gnr,ynr,vnr,wnr,bnr,Tnr,_nr,Enr,Snr,knr,qwn=S({"npm-stub:which"(){Sy={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Sy.get}):new Proxy(function(...r){return new Proxy({},{get:Sy.get})},{get:Sy.get,apply(r,n,o){return new Proxy({},{get:Sy.get})},construct(r,n){return new Proxy({},{get:Sy.get})}})}},qi=new Proxy({},Sy),Irr=qi,{BedrockClient:Rrr,ListFoundationModelsCommand:Mrr,BedrockRuntimeClient:Prr,ConverseCommand:Drr,ConverseStreamCommand:Orr,ImageFormat:Nrr,InvokeModelCommand:Lrr}=qi,{SageMakerRuntimeClient:$rr,InvokeEndpointCommand:Frr,InvokeEndpointWithResponseStreamCommand:Urr}=qi,{GoogleAuth:Brr,VertexAI:zrr,TextToSpeechClient:Grr}=qi,{Webhook:qrr}=qi,{Hippocampus:jrr,HippocampusConfig:Vrr}=qi,{createClient:Hrr}=qi,{Queue:Wrr,Worker:Krr,Job:Jrr,QueueScheduler:Xrr,FlowProducer:Yrr}=qi,{Cron:Zrr}=qi,{parseBuffer:Qrr,selectCover:enr}=qi,{extractRawText:tnr,convertToHtml:rnr}=qi,{Hono:nnr}=qi,{cors:onr,HTTPException:inr,logger:snr,secureHeaders:anr,streamSSE:unr,timeout:lnr}=qi,cnr=globalThis.fetch,dnr=globalThis.Request,pnr=globalThis.Response,mnr=globalThis.Headers,hnr=globalThis.FormData,fnr=globalThis.File,gnr=globalThis.Blob,ynr=qi.Agent,vnr=qi.Pool,wnr=qi.Client,bnr=qi.Dispatcher,Tnr=()=>{},_nr=()=>qi,Enr=qi.MockAgent,Snr={redirect:()=>e=>e,retry:()=>e=>e},knr=async(e,t)=>{const r=await globalThis.fetch(e,t);return{statusCode:r.status,headers:Object.fromEntries(r.headers.entries()),body:{text:()=>r.text(),json:()=>r.json(),arrayBuffer:()=>r.arrayBuffer()}}}}}),jwn=dn({"node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js"(e,t){"use strict";var r=(n={})=>{const o=n.env||process.env;return(n.platform||process.platform)!=="win32"?"PATH":Object.keys(o).reverse().find(s=>s.toUpperCase()==="PATH")||"Path"};t.exports=r,t.exports.default=r}}),Vwn=dn({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js"(e,t){"use strict";var r=(Sr(),fn(Xm)),n=(qwn(),fn(xrr)),o=jwn();function i(a,u){const l=a.options.env||process.env,c=process.cwd(),d=a.options.cwd!=null,p=d&&process.chdir!==void 0&&!process.chdir.disabled;if(p)try{process.chdir(a.options.cwd)}catch{}let m;try{m=n.sync(a.command,{path:l[o({env:l})],pathExt:u?r.delimiter:void 0})}catch{}finally{p&&process.chdir(c)}return m&&(m=r.resolve(d?a.options.cwd:"",m)),m}function s(a){return i(a)||i(a,!0)}t.exports=s}}),Hwn=dn({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/escape.js"(e,t){"use strict";var r=/([()\][%!^"`<>&|;, *?])/g;function n(i){return i=i.replace(r,"^$1"),i}function o(i,s){return i=`${i}`,i=i.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),i=i.replace(/(?=(\\+?)?)\1$/,"$1$1"),i=`"${i}"`,i=i.replace(r,"^$1"),s&&(i=i.replace(r,"^$1")),i}t.exports.command=n,t.exports.argument=o}}),Wwn=dn({"node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js"(e,t){"use strict";t.exports=/^#!(.*)/}}),Kwn=dn({"node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js"(e,t){"use strict";var r=Wwn();t.exports=(n="")=>{const o=n.match(r);if(!o)return null;const[i,s]=o[0].replace(/#! ?/,"").split(" "),a=i.split("/").pop();return a==="env"?s:s?`${a} ${s}`:a}}}),Jwn=dn({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js"(e,t){"use strict";var r=(ro(),fn(kd)),n=Kwn();function o(i){const a=Buffer.alloc(150);let u;try{u=r.openSync(i,"r"),r.readSync(u,a,0,150,0),r.closeSync(u)}catch{}return n(a.toString())}t.exports=o}}),Xwn=dn({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js"(e,t){"use strict";var r=(Sr(),fn(Xm)),n=Vwn(),o=Hwn(),i=Jwn(),s=process.platform==="win32",a=/\.(?:com|exe)$/i,u=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function l(p){p.file=n(p);const m=p.file&&i(p.file);return m?(p.args.unshift(p.file),p.command=m,n(p)):p.file}function c(p){if(!s)return p;const m=l(p),h=!a.test(m);if(p.options.forceShell||h){const g=u.test(m);p.command=r.normalize(p.command),p.command=o.command(p.command),p.args=p.args.map(v=>o.argument(v,g));const y=[p.command].concat(p.args).join(" ");p.args=["/d","/s","/c",`"${y}"`],p.command=process.env.comspec||"cmd.exe",p.options.windowsVerbatimArguments=!0}return p}function d(p,m,h){m&&!Array.isArray(m)&&(h=m,m=null),m=m?m.slice(0):[],h=Object.assign({},h);const g={command:p,args:m,options:h,file:void 0,original:{command:p,args:m}};return h.shell?g:c(g)}t.exports=d}}),Ywn=dn({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/enoent.js"(e,t){"use strict";var r=process.platform==="win32";function n(a,u){return Object.assign(new Error(`${u} ${a.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${u} ${a.command}`,path:a.command,spawnargs:a.args})}function o(a,u){if(!r)return;const l=a.emit;a.emit=function(c,d){if(c==="exit"){const p=i(d,u);if(p)return l.call(a,"error",p)}return l.apply(a,arguments)}}function i(a,u){return r&&a===1&&!u.file?n(u.original,"spawn"):null}function s(a,u){return r&&a===1&&!u.file?n(u.original,"spawnSync"):null}t.exports={hookChildProcess:o,verifyENOENT:i,verifyENOENTSync:s,notFoundError:n}}}),Zwn=dn({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/index.js"(e,t){"use strict";var r=(VBe(),fn(l5e)),n=Xwn(),o=Ywn();function i(a,u,l){const c=n(a,u,l),d=r.spawn(c.command,c.args,c.options);return o.hookChildProcess(d,c),d}function s(a,u,l){const c=n(a,u,l),d=r.spawnSync(c.command,c.args,c.options);return d.error=d.error||o.verifyENOENTSync(d.status,c),d}t.exports=i,t.exports.spawn=i,t.exports.sync=s,t.exports._parse=n,t.exports._enoent=o}}),H6,Qwn,ebn,tbn,rbn,W6,Anr,jue,nbn,obn,ibn,sbn,abn=S({"node-stub:node:process"(){H6={},Qwn=globalThis.crypto,ebn=globalThis.ReadableStream||class{},tbn=globalThis.URL,rbn=globalThis.URLSearchParams,W6=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},W6.custom=Symbol.for("nodejs.util.inspect.custom"),W6.colors={},W6.styles={},Anr=globalThis.TextDecoder,jue=globalThis.TextEncoder,nbn=globalThis.performance||{now:()=>Date.now()},obn=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),i=new Uint8Array(o.length);for(let s=0;s<o.length;s++)i[s]=o.charCodeAt(s);return i}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let i=0;i<t.length;i+=2)o[i/2]=parseInt(t.substr(i,2),16);return o}return new jue().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((i,s)=>i+s.length,0),n=new Uint8Array(r);let o=0;for(const i of t)n.set(i,o),o+=i.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new jue().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new Anr().decode(this)}},ibn=globalThis.clearTimeout,sbn=globalThis.clearInterval}}),ubn,Vue,Cnr,lbn,cbn,dbn,K6,xnr,Hue,pbn,mbn,hbn,fbn,Wue=S({"node-stub:node:stream"(){ubn=globalThis.crypto,Vue=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},Cnr=class{pipe(){return this}on(){return this}},lbn=globalThis.ReadableStream||class{},cbn=globalThis.URL,dbn=globalThis.URLSearchParams,K6=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},K6.custom=Symbol.for("nodejs.util.inspect.custom"),K6.colors={},K6.styles={},xnr=globalThis.TextDecoder,Hue=globalThis.TextEncoder,pbn=globalThis.performance||{now:()=>Date.now()},mbn=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),i=new Uint8Array(o.length);for(let s=0;s<o.length;s++)i[s]=o.charCodeAt(s);return i}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let i=0;i<t.length;i+=2)o[i/2]=parseInt(t.substr(i,2),16);return o}return new Hue().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((i,s)=>i+s.length,0),n=new Uint8Array(r);let o=0;for(const i of t)n.set(i,o),o+=i.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new Hue().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new xnr().decode(this)}},hbn=globalThis.clearTimeout,fbn=globalThis.clearInterval}});function gbn(e){return yy.parse(JSON.parse(e))}function ybn(e){return JSON.stringify(e)+`
1158
- `}var Inr,Rnr,vbn=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.1_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js"(){ff(),Inr=10*1024*1024,Rnr=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??Inr}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;const e=this._buffer.indexOf(`
1159
- `);if(e===-1)return null;const t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),gbn(t)}clear(){this._buffer=void 0}}}}),Kue={};ue(Kue,{DEFAULT_INHERITED_ENV_VARS:()=>Jue,StdioClientTransport:()=>Dnr,getDefaultEnvironment:()=>Mnr});function Mnr(){const e={};for(const t of Jue){const r=H6.env[t];r!==void 0&&(r.startsWith("()")||(e[t]=r))}return e}var Pnr,Jue,Dnr,Onr=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.1_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"(){Pnr=ml(Zwn(),1),abn(),Wue(),vbn(),Jue=H6.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"],Dnr=class{constructor(e){this._stderrStream=null,this._serverParams=e,this._readBuffer=new Rnr({maxBufferSize:e.maxBufferSize}),(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new Cnr)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,t)=>{this._process=(0,Pnr.default)(this._serverParams.command,this._serverParams.args??[],{env:{...Mnr(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:H6.platform==="win32",cwd:this._serverParams.cwd}),this._process.on("error",r=>{t(r),this.onerror?.(r)}),this._process.on("spawn",()=>{e()}),this._process.on("close",r=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",r=>{this.onerror?.(r)}),this._process.stdout?.on("data",r=>{try{this._readBuffer.append(r),this.processReadBuffer()}catch(n){this.onerror?.(n),this.close().catch(()=>{})}}),this._process.stdout?.on("error",r=>{this.onerror?.(r)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{const e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._process){const e=this._process;this._process=void 0;const t=new Promise(r=>{e.once("close",()=>{r()})});try{e.stdin?.end()}catch{}if(await Promise.race([t,new Promise(r=>setTimeout(r,2e3).unref())]),e.exitCode===null){try{e.kill("SIGTERM")}catch{}await Promise.race([t,new Promise(r=>setTimeout(r,2e3).unref())])}if(e.exitCode===null)try{e.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(e){return new Promise(t=>{if(!this._process?.stdin)throw new Error("Not connected");const r=ybn(e);this._process.stdin.write(r)?t():this._process.stdin.once("drain",t)})}}}});function Xue(e){}function Yue(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=Xue,onError:r=Xue,onRetry:n=Xue,onComment:o}=e,i=[];let s=!0,a,u="",l=0,c;function d(v){if(s&&(s=!1,v.charCodeAt(0)===239&&v.charCodeAt(1)===187&&v.charCodeAt(2)===191&&(v=v.slice(3))),i.length===0){const E=p(v);E!==""&&i.push(E);return}if(v.indexOf(`
1157
+ For video extraction, the result includes images (frames) that will be visible to you. Always call list_attached_files first to discover file IDs.`,inputSchema:M.object({file_id:M.string().describe("File ID (UUID) or exact filename from list_attached_files"),start_time:M.number().optional().describe("Start timestamp in seconds (video only)"),end_time:M.number().optional().describe("End timestamp in seconds (video only)"),frame_count:M.number().int().min(1).max(20).optional().describe("Number of frames to extract in time range (video only, default: 5, max: 20)"),pages:M.array(M.number().int().min(1)).optional().describe("Specific page/slide numbers to extract (1-indexed)"),page_range:M.object({start:M.number().int().min(1),end:M.number().int().min(1)}).optional().describe("Page/slide range to extract (1-indexed, inclusive)"),sheet:M.string().optional().describe("Sheet name or 0-based index as string e.g. '0', '1' (spreadsheet only, default: first sheet)"),row_range:M.object({start:M.number().int().min(1),end:M.number().int().min(1)}).optional().describe("Row range (1-indexed, spreadsheet only)"),columns:M.array(M.string()).optional().describe("Specific column letters to include (e.g., ['A', 'B', 'D'], spreadsheet only)"),entry_path:M.string().optional().describe("File path within archive to extract (archive only)"),format:M.enum(["text","detailed","summary"]).optional().describe("Output format hint (default: text)")}),execute:async t=>{try{const r={...t,sheet:t.sheet!==void 0?/^\d+$/.test(t.sheet)?parseInt(t.sheet,10):t.sheet:void 0},n=await e.extractContent(r);return n.success?{success:!0,text:n.text,metadata:n.metadata,imageCount:n.images?.length??0,_images:n.images,error:void 0}:{success:!1,error:n.error,text:void 0,metadata:void 0,imageCount:0,_images:void 0}}catch(r){return{success:!1,error:r instanceof Error?r.message:String(r),text:void 0,metadata:void 0,imageCount:0,_images:void 0}}},toModelOutput:({output:t})=>{const r=[];if(t.text?r.push({type:"text",text:t.text}):t.error&&r.push({type:"text",text:`Error: ${t.error}`}),t._images&&t._images.length>0)for(const n of t._images)r.push({type:"image-data",data:n.toString("base64"),mediaType:"image/jpeg"});return r.length===0&&r.push({type:"text",text:"(No content extracted)"}),{type:"content",value:r}}}}function ier(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(2)} GB`}var wyn=S({"src/lib/files/fileTools.ts"(){"use strict";mn(),Sl()}}),LT,v1,Yae,ser=S({"src/lib/hitl/hitlManager.ts"(){"use strict";so(),qt(),Kk(),z(),LT=3e4,v1=!1,Yae=class extends bn{config;pendingConfirmations=new Map;statistics={totalRequests:0,pendingRequests:0,averageResponseTime:0,approvedRequests:0,rejectedRequests:0,timedOutRequests:0};constructor(e){super(),this.config=this.validateConfig(e),this.setupEventHandlers()}validateConfig(e){const t={enabled:e.enabled,dangerousActions:e.dangerousActions,timeout:e.timeout??LT,confirmationMethod:e.confirmationMethod??"event",allowArgumentModification:e.allowArgumentModification??v1,autoApproveOnTimeout:e.autoApproveOnTimeout??!1,autoApproveExclusions:Array.isArray(e.autoApproveExclusions)?[...e.autoApproveExclusions]:e.autoApproveExclusions??[],auditLogging:e.auditLogging??!1,customRules:e.customRules??[],confirmBuiltinTools:e.confirmBuiltinTools??!0};if(!t.enabled)return t;if(!Array.isArray(t.dangerousActions))throw new Jw("dangerousActions must be an array of strings");if(!Array.isArray(t.autoApproveExclusions)||t.autoApproveExclusions.some(r=>typeof r!="string"||r.length===0))throw new Jw("autoApproveExclusions must be an array of non-empty tool names");if(typeof t.timeout!="number"||t.timeout<=0)throw new Jw("timeout must be a positive number (milliseconds)");if(t.confirmationMethod!=="event")throw new Jw("confirmationMethod must be 'event' (only supported method)");if(typeof t.allowArgumentModification!="boolean")throw new Jw("allowArgumentModification must be a boolean");return t}requiresConfirmation(e,t){if(!this.config.enabled)return!1;const r=e.toLowerCase();for(const n of this.config.dangerousActions)if(r.includes(n.toLowerCase()))return!0;if(this.config.customRules){for(const n of this.config.customRules)if(n.requiresConfirmation)try{if(n.condition(e,t))return!0}catch(o){this.logAuditEvent("rule-evaluation-error",{ruleName:n.name,toolName:e,error:o instanceof Error?o.message:String(o)})}}return!1}async requestConfirmation(e,t,r){const n=this.generateConfirmationId(),o=Date.now();return this.statistics.totalRequests++,this.statistics.pendingRequests++,new Promise((i,s)=>{const a=setTimeout(()=>{this.handleTimeout(n)},this.config.timeout),u={confirmationId:n,toolName:e,arguments:t,timestamp:o,timeoutHandle:a,resolve:i,reject:s};this.pendingConfirmations.set(n,u);const l={type:"hitl:confirmation-request",payload:{confirmationId:n,toolName:e,serverId:r?.serverId,actionType:this.generateActionDescription(e,t),arguments:t,metadata:{timestamp:new Date(o).toISOString(),sessionId:r?.sessionId,userId:r?.userId,dangerousKeywords:this.getTriggeredKeywords(e,t)},timeoutMs:this.config.timeout??LT,allowModification:this.config.allowArgumentModification??v1}};this.emit("hitl:confirmation-request",l),this.config.auditLogging&&this.logAuditEvent("confirmation-requested",{confirmationId:n,toolName:e,userId:r?.userId,sessionId:r?.sessionId,timestamp:o,arguments:t})})}processUserResponse(e,t){const r=this.pendingConfirmations.get(e);if(!r){f.warn(`No pending confirmation found for ID: ${e}`);return}clearTimeout(r.timeoutHandle),this.pendingConfirmations.delete(e),this.statistics.pendingRequests--;const n=t.responseTime||Date.now()-r.timestamp;t.approved?this.statistics.approvedRequests++:this.statistics.rejectedRequests++;const o=this.statistics.approvedRequests+this.statistics.rejectedRequests;this.statistics.averageResponseTime=(this.statistics.averageResponseTime*(o-1)+n)/o;const i={approved:t.approved,reason:t.reason,modifiedArguments:t.modifiedArguments,responseTime:n};this.config.auditLogging&&this.logAuditEvent(t.approved?"confirmation-approved":"confirmation-rejected",{confirmationId:e,toolName:r.toolName,approved:t.approved,reason:t.reason,userId:t.userId,responseTime:n,arguments:r.arguments}),r.resolve(i)}handleTimeout(e){const t=this.pendingConfirmations.get(e);if(!t)return;this.pendingConfirmations.delete(e),this.statistics.pendingRequests--,this.statistics.timedOutRequests++;const r=Date.now()-t.timestamp,n=this.config.autoApproveOnTimeout===!0&&!this.config.autoApproveExclusions?.includes(t.toolName);this.config.auditLogging&&this.logAuditEvent("confirmation-timeout",{confirmationId:e,toolName:t.toolName,timeout:this.config.timeout??LT,arguments:t.arguments,autoApproved:n});const o={type:"hitl:timeout",payload:{confirmationId:e,toolName:t.toolName,timeout:this.config.timeout??LT}};if(this.emit("hitl:timeout",o),n){this.statistics.approvedRequests++;const i=this.statistics.approvedRequests+this.statistics.rejectedRequests;this.statistics.averageResponseTime=(this.statistics.averageResponseTime*(i-1)+r)/i,this.config.auditLogging&&this.logAuditEvent("confirmation-auto-approved",{confirmationId:e,toolName:t.toolName,reason:"Auto-approved due to timeout",responseTime:r,arguments:t.arguments});const s={approved:!0,reason:"Auto-approved due to timeout",responseTime:r};t.resolve(s)}else t.reject(new Wk(`Confirmation timeout for tool: ${t.toolName}`,e,this.config.timeout??LT))}setupEventHandlers(){this.on("hitl:confirmation-response",e=>{e.payload?.confirmationId&&this.processUserResponse(e.payload.confirmationId,{approved:e.payload.approved,reason:e.payload.reason,modifiedArguments:e.payload.modifiedArguments,responseTime:e.payload.metadata?.responseTime,userId:e.payload.metadata?.userId})})}generateConfirmationId(){return`hitl-${Date.now()}-${st()}`}generateActionDescription(e,t){const r=e.toLowerCase();if(r.includes("delete"))return"Delete Operation";if(r.includes("remove"))return"Remove Operation";if(r.includes("update"))return"Update Operation";if(r.includes("create"))return"Create Operation";if(r.includes("drop"))return"Drop Operation";if(r.includes("truncate"))return"Truncate Operation";if(r.includes("restart"))return"Restart Operation";if(r.includes("stop"))return"Stop Operation";if(r.includes("kill"))return"Kill Operation";if(this.config.customRules)for(const n of this.config.customRules)try{if(n.condition(e,t)&&n.customMessage)return n.customMessage}catch{}return`Execute ${e}`}getTriggeredKeywords(e,t){const r=[],n=e.toLowerCase();for(const o of this.config.dangerousActions)n.includes(o.toLowerCase())&&r.push(o);if(this.config.customRules)for(const o of this.config.customRules)try{o.requiresConfirmation&&o.condition(e,t)&&r.push(o.name)}catch{}return r}logAuditEvent(e,t){const r={timestamp:new Date().toISOString(),eventType:e,toolName:t.toolName,userId:t.userId,sessionId:t.sessionId,arguments:t.arguments,reason:t.reason,responseTime:t.responseTime,...t};f.info(`[HITL Audit] ${e}:`,r),this.emit("hitl:audit",r)}getStatistics(){return{...this.statistics}}getConfig(){return{...this.config,autoApproveExclusions:Array.isArray(this.config.autoApproveExclusions)?[...this.config.autoApproveExclusions]:this.config.autoApproveExclusions}}updateConfig(e){const t={...this.config,...e};this.config=this.validateConfig(t),this.config.auditLogging&&this.logAuditEvent("configuration-updated",{oldConfig:this.config,newConfig:t})}cleanup(){for(const[e,t]of this.pendingConfirmations)clearTimeout(t.timeoutHandle),t.reject(new Error(`HITL cleanup: confirmation ${e} cancelled`));this.pendingConfirmations.clear(),this.statistics.pendingRequests=0,this.config.auditLogging&&this.logAuditEvent("manager-cleanup",{clearedConfirmations:this.pendingConfirmations.size})}isEnabled(){return this.config.enabled}getPendingCount(){return this.pendingConfirmations.size}hasPendingConfirmation(e){return this.pendingConfirmations.has(e)}}}}),v6,aer,Zae,w6,uer,byn=S({"src/lib/mcp/batching/requestBatcher.ts"(){"use strict";so(),z(),et(),Mr(),nr(),v6=class extends bn{config;pending=new Map;serverQueues=new Map;flushTimer;executor;activeBatches=0;batchCounter=0;requestCounter=0;isDestroyed=!1;constructor(e){super(),this.config={maxBatchSize:e.maxBatchSize,maxWaitMs:e.maxWaitMs,enableParallel:e.enableParallel??!0,maxConcurrentBatches:e.maxConcurrentBatches??5,groupByServer:e.groupByServer??!0}}setExecutor(e){this.executor=e}async add(e,t,r){if(this.isDestroyed)throw ve.invalidConfiguration("batcher","Batcher has been destroyed");if(!this.executor)throw ve.missingConfiguration("batchExecutor",{hint:"Call setExecutor() before adding requests"});const n=this.generateRequestId();return new Promise((o,i)=>{const s={id:n,tool:e,args:t,serverId:r,resolve:o,reject:i,addedAt:Date.now()};if(this.pending.set(n,s),this.config.groupByServer&&r){this.serverQueues.has(r)||this.serverQueues.set(r,new Set);const a=this.serverQueues.get(r);a&&a.add(n)}this.emit("requestQueued",{requestId:n,queueSize:this.pending.size}),this.pending.size>=this.config.maxBatchSize?this.scheduleFlush("size"):this.flushTimer||(this.flushTimer=setTimeout(()=>{this.scheduleFlush("timeout")},this.config.maxWaitMs))})}async flush(){this.clearFlushTimer(),this.pending.size!==0&&(this.emit("flushTriggered",{reason:"manual",queueSize:this.pending.size}),await this.executeBatch())}get queueSize(){return this.pending.size}get activeBatchCount(){return this.activeBatches}get isIdle(){return this.pending.size===0&&this.activeBatches===0}async drain(){await this.flush();const e=3e4,t=Date.now()+e;for(;!this.isIdle;){if(Date.now()>=t)throw ve.toolTimeout("batchDrain",e);await new Promise(r=>setTimeout(r,10))}}destroy(){this.isDestroyed=!0,this.clearFlushTimer();for(const e of this.pending.values())e.reject(ve.invalidConfiguration("batcher","Batcher was destroyed before request could complete"));this.pending.clear(),this.serverQueues.clear()}generateRequestId(){return`req-${Date.now()}-${++this.requestCounter}`}generateBatchId(){return`batch-${Date.now()}-${++this.batchCounter}`}scheduleFlush(e){this.clearFlushTimer(),this.emit("flushTriggered",{reason:e,queueSize:this.pending.size}),setImmediate(()=>{this.executeBatch().catch(t=>{f.error("Batch execution failed:",t)})})}clearFlushTimer(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0)}async executeBatch(){if(this.pending.size===0)return;if(this.activeBatches>=this.config.maxConcurrentBatches){this.clearFlushTimer(),this.flushTimer=setTimeout(()=>{this.executeBatch().catch(n=>{f.error("Rescheduled batch execution failed:",n)})},10);return}const e=this.selectBatchRequests();if(e.length===0)return;const t=this.generateBatchId(),r=Date.now();this.activeBatches++,this.emit("batchStarted",{batchId:t,size:e.length}),await pt({name:"mcp.batch.execute",tracer:Be.mcp,attributes:{"mcp.batch.id":t,"mcp.batch.size":e.length,"mcp.batch.active_batches":this.activeBatches}},async n=>{let o=0,i=0;try{if(!this.executor)throw ve.missingConfiguration("batchExecutor",{hint:"Call setExecutor() before executing batches"});const s=this.executor(e.map(p=>({tool:p.tool,args:p.args,serverId:p.serverId}))),a=Math.max(5e3,Number(process.env.MCP_TOOL_TIMEOUT)||6e4);let u;const l=new Promise((p,m)=>{u=setTimeout(()=>m(ve.toolTimeout("batchExecution",a)),a)});s.catch(p=>{});const c=await Promise.race([s,l]).finally(()=>{u&&clearTimeout(u)}),d=[];for(let p=0;p<e.length;p++){const m=e[p],h=c[p],g=Date.now()-r;if(!h){const y=ve.toolExecutionFailed(m.tool,new Error(`Batch executor returned no result for request ${p}`));m.reject(y),d.push({id:m.id,success:!1,error:y,executionTime:g}),i++;continue}if(h.success)m.resolve(h.result),d.push({id:m.id,success:!0,result:h.result,executionTime:g}),o++;else{const y=h.error??ve.toolExecutionFailed(m.tool,new Error("Unknown batch execution error"));m.reject(y),d.push({id:m.id,success:!1,error:y,executionTime:g}),i++}}n.setAttribute("mcp.batch.success_count",o),n.setAttribute("mcp.batch.error_count",i),this.emit("batchCompleted",{batchId:t,results:d})}catch(s){const a=s instanceof Error?s:ve.toolExecutionFailed("batch",new Error(String(s)));for(const u of e)u.reject(a);throw this.emit("batchFailed",{batchId:t,error:a}),a}finally{this.activeBatches--}}).catch(n=>{f.error("Batch span execution failed:",n)}),this.pending.size>0&&(this.clearFlushTimer(),this.flushTimer=setTimeout(()=>{this.executeBatch().catch(n=>{f.error("Follow-up batch execution failed:",n)})},0))}selectBatchRequests(){const e=[];if(this.config.groupByServer&&this.serverQueues.size>0){const[t,r]=this.serverQueues.entries().next().value;for(const n of r){if(e.length>=this.config.maxBatchSize)break;const o=this.pending.get(n);o&&(e.push(o),this.pending.delete(n),r.delete(n))}r.size===0&&this.serverQueues.delete(t)}else{const t=Array.from(this.pending.values()).sort((r,n)=>r.addedAt-n.addedAt);for(const r of t){if(e.length>=this.config.maxBatchSize)break;e.push(r),this.pending.delete(r.id)}}return e}},aer=e=>new v6(e),Zae={maxBatchSize:10,maxWaitMs:100,enableParallel:!0,maxConcurrentBatches:5,groupByServer:!0},w6=class{batcher;toolExecutor;constructor(e){this.batcher=new v6({...Zae,...e}),this.batcher.setExecutor(async t=>{if(!this.toolExecutor)throw ve.missingConfiguration("toolExecutor",{hint:"Call setToolExecutor() before executing tool calls"});const r=this.toolExecutor;return await Promise.all(t.map(async o=>{try{return{success:!0,result:await r(o.tool,o.args,o.serverId)}}catch(i){return{success:!1,error:i instanceof Error?i:ve.toolExecutionFailed(o.tool,new Error(String(i)))}}}))})}setToolExecutor(e){this.toolExecutor=e}async execute(e,t,r){return this.batcher.add(e,t,r)}async flush(){return this.batcher.flush()}async drain(){return this.batcher.drain()}get queueSize(){return this.batcher.queueSize}get isIdle(){return this.batcher.isIdle}destroy(){this.batcher.destroy()}},uer=e=>new w6(e)}}),ler=S({"src/lib/mcp/batching/index.ts"(){"use strict";byn()}}),fy,cer,Qae,b6,der,Tyn=S({"src/lib/mcp/caching/toolCache.ts"(){"use strict";qt(),so(),Hr(),fy=class extends bn{cache=new Map;config;stats;cleanupTimer;constructor(e){super(),this.config={ttl:e.ttl,maxSize:e.maxSize,strategy:e.strategy,enableAutoCleanup:e.enableAutoCleanup??!0,cleanupInterval:e.cleanupInterval??6e4,namespace:e.namespace??""},this.stats={hits:0,misses:0,evictions:0,size:0,maxSize:this.config.maxSize,hitRate:0},this.config.enableAutoCleanup&&this.startAutoCleanup()}get(e){const t=this.getFullKey(e),r=this.cache.get(t);if(!r){this.stats.misses++,this.updateHitRate(),this.emit("miss",{key:t});return}if(this.isExpired(r)){this.deleteWithReason(t,"expired"),this.stats.misses++,this.updateHitRate(),this.emit("miss",{key:t});return}r.accessedAt=Date.now(),r.accessCount++,this.stats.hits++,this.updateHitRate();const n=this.cloneCachedValue(r.value);return this.listenerCount("hit")>0&&this.emit("hit",{key:t,value:this.cloneCachedValue(r.value)}),n}set(e,t,r){const n=this.getFullKey(e),o=r??this.config.ttl,i=Date.now();this.cache.size>=this.config.maxSize&&!this.cache.has(n)&&this.evictOne();const s={value:this.cloneCachedValue(t),expires:i+o,createdAt:i,accessedAt:i,accessCount:1,key:n};this.cache.set(n,s),this.stats.size=this.cache.size,this.emit("set",{key:n,value:t,ttl:o})}has(e){const t=this.getFullKey(e),r=this.cache.get(t);return r?this.isExpired(r)?(this.deleteWithReason(t,"expired"),!1):!0:!1}delete(e){const t=this.getFullKey(e),r=this.cache.delete(t);return r&&(this.stats.size=this.cache.size,this.emit("evict",{key:t,reason:"manual"})),r}invalidate(e){const t=this.getFullKey(e),r=this.patternToRegex(t);let n=0;for(const o of this.cache.keys())r.test(o)&&(this.cache.delete(o),n++,this.emit("evict",{key:o,reason:"manual"}));return this.stats.size=this.cache.size,n}clear(){const e=this.cache.size;this.cache.clear(),this.stats.size=0,this.emit("clear",{entriesRemoved:e})}async getOrSet(e,t,r){const n=this.get(e);if(n!==void 0)return n;const o=3e4,i=await kt(Promise.resolve(t()),o,`ToolCache getOrSet factory timed out after ${o}ms for key "${e}"`);return i===void 0||this.set(e,i,r),i}getStats(){return{...this.stats}}resetStats(){this.stats.hits=0,this.stats.misses=0,this.stats.evictions=0,this.updateHitRate()}keys(){return Array.from(this.cache.keys())}get size(){return this.cache.size}static generateKey(e,t){const r=(o,i=new WeakSet)=>{if(o===null||typeof o!="object")return JSON.stringify(o);if(o instanceof Date)return`{"$date":${JSON.stringify(o.toISOString())}}`;if(i.has(o))throw new TypeError("Circular structures are not supported in cache keys");if(i.add(o),Array.isArray(o)){const u="["+o.map(l=>r(l,i)).join(",")+"]";return i.delete(o),u}const a=Object.keys(o).sort().map(u=>JSON.stringify(u)+":"+r(o[u],i));return i.delete(o),"{"+a.join(",")+"}"},n=sc("sha256").update(r(t)).digest("hex").substring(0,16);return`${e}:${n}`}destroy(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.clear()}cloneCachedValue(e){if(e===null||typeof e!="object")return e;try{return structuredClone(e)}catch{return JSON.parse(JSON.stringify(e))}}getFullKey(e){return this.config.namespace?`${this.config.namespace}:${e}`:e}isExpired(e){return Date.now()>e.expires}deleteWithReason(e,t){const r=this.cache.delete(e);return r&&(this.stats.evictions++,this.stats.size=this.cache.size,this.emit("evict",{key:e,reason:t})),r}evictOne(){const e=this.selectEvictionCandidate();e&&(this.cache.delete(e.key),this.stats.evictions++,this.stats.size=this.cache.size,this.emit("evict",{key:e.key,reason:"capacity"}))}selectEvictionCandidate(){if(this.cache.size!==0)switch(this.config.strategy){case"lru":return this.findLRU();case"fifo":return this.findFIFO();case"lfu":return this.findLFU();default:return this.findLRU()}}findLRU(){let e,t=1/0;for(const r of this.cache.values())r.accessedAt<t&&(t=r.accessedAt,e=r);return e}findFIFO(){let e,t=1/0;for(const r of this.cache.values())r.createdAt<t&&(t=r.createdAt,e=r);return e}findLFU(){let e,t=1/0;for(const r of this.cache.values())r.accessCount<t&&(t=r.accessCount,e=r);return e}patternToRegex(e){const r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^:]*");return new RegExp(`^${r}$`)}updateHitRate(){const e=this.stats.hits+this.stats.misses;this.stats.hitRate=e>0?this.stats.hits/e:0}startAutoCleanup(){this.cleanupTimer=setInterval(()=>{this.cleanupExpired()},this.config.cleanupInterval),this.cleanupTimer.unref&&this.cleanupTimer.unref()}cleanupExpired(){const e=Date.now();for(const[t,r]of this.cache.entries())e>r.expires&&(this.cache.delete(t),this.stats.evictions++,this.emit("evict",{key:t,reason:"expired"}));this.stats.size=this.cache.size}},cer=e=>new fy(e),Qae={ttl:300*1e3,maxSize:500,strategy:"lru",enableAutoCleanup:!0,cleanupInterval:6e4},b6=class{cache;constructor(e){this.cache=new fy({...Qae,...e,namespace:e?.namespace??"tool-results"})}cacheResult(e,t,r,n){const o=fy.generateKey(e,t);this.cache.set(o,r,n)}getCachedResult(e,t){const r=fy.generateKey(e,t);return this.cache.get(r)}hasCachedResult(e,t){const r=fy.generateKey(e,t);return this.cache.has(r)}invalidateTool(e){return this.cache.invalidate(`${e}:*`)}getStats(){return this.cache.getStats()}clear(){this.cache.clear()}destroy(){this.cache.destroy()}},der=e=>new b6(e)}}),per=S({"src/lib/mcp/caching/index.ts"(){"use strict";Tyn()}}),mer={};ue(mer,{createAnnotatedTool:()=>fer,filterToolsByAnnotations:()=>ver,getAnnotationSummary:()=>wer,getToolSafetyLevel:()=>yer,inferAnnotations:()=>om,isSafeToRetry:()=>tue,mergeAnnotations:()=>eue,requiresConfirmation:()=>ger,validateAnnotations:()=>her});function om(e){const t=e.name,r=e.description.toLowerCase(),n={},o=(l,c)=>new RegExp(`\\b${c}\\b`,"i").test(l)?!0:l.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().split(/[_-]/).some(p=>p===c.toLowerCase());return["get","list","read","fetch","query","search","find","show","display","view","retrieve","check","inspect","look"].some(l=>o(r,l)||o(t,l))&&(n.readOnlyHint=!0),["delete","remove","drop","destroy","clear","purge","erase","wipe","truncate","reset"].some(l=>o(r,l)||o(t,l))&&(n.destructiveHint=!0,n.requiresConfirmation=!0),["set","update","put","upsert","replace"].some(l=>o(r,l)||o(t,l))&&!n.destructiveHint&&(n.idempotentHint=!0),["complex","analyze","process","generate","transform","compute","calculate"].some(l=>o(r,l)||o(t,l))?n.complexity="complex":r.length>100?n.complexity="medium":n.complexity="simple",n}function eue(...e){const t={};for(const r of e)if(r){const n=t.tags?[...t.tags]:[];if(Object.assign(t,r),n.length>0||r.tags){const o=r.tags??[];t.tags=[...new Set([...n,...o])]}}return t}function her(e){const t=[];if(e.readOnlyHint&&e.destructiveHint&&t.push("Tool cannot be both readOnly and destructive - these are conflicting hints"),e.rateLimitHint!==void 0&&(e.rateLimitHint<0||!Number.isFinite(e.rateLimitHint))&&t.push("rateLimitHint must be a non-negative number"),e.estimatedDuration!==void 0&&(e.estimatedDuration<0||!Number.isFinite(e.estimatedDuration))&&t.push("estimatedDuration must be a non-negative number"),e.costHint!==void 0&&(e.costHint<0||!Number.isFinite(e.costHint))&&t.push("costHint must be a non-negative number"),e.tags){for(const r of e.tags)if(typeof r!="string"||r.length===0){t.push("All tags must be non-empty strings");break}}return t}function fer(e){const t=om(e),r=eue(t,e.annotations);return{...e,annotations:r}}function ger(e){return!!(e.annotations?.requiresConfirmation||e.annotations?.destructiveHint)}function tue(e){return!!(e.annotations?.idempotentHint||e.annotations?.readOnlyHint)}function yer(e){return e.annotations?.destructiveHint?"dangerous":e.annotations?.readOnlyHint?"safe":(e.annotations?.idempotentHint,"moderate")}function ver(e,t){return e.filter(r=>{const n=r.annotations??{};return t(n)})}function wer(e){const t=[];return e.title&&t.push(e.title),e.readOnlyHint&&t.push("read-only"),e.destructiveHint&&t.push("DESTRUCTIVE"),e.idempotentHint&&t.push("idempotent"),e.requiresConfirmation&&t.push("requires confirmation"),e.complexity&&t.push(`${e.complexity} complexity`),e.estimatedDuration!==void 0&&t.push(`~${e.estimatedDuration}ms`),e.tags?.length&&t.push(`tags: ${e.tags.join(", ")}`),t.length>0?`[${t.join(" | ")}]`:"[no annotations]"}var w1=S({"src/lib/mcp/toolAnnotations.ts"(){"use strict"}}),ber={};ue(ber,{MultiServerManager:()=>b1,globalMultiServerManager:()=>rue});var b1,rue,nue=S({"src/lib/mcp/multiServerManager.ts"(){"use strict";so(),z(),et(),b1=class extends bn{config;servers=new Map;groups=new Map;metrics=new Map;roundRobinCounters=new Map;toolPreferences=new Map;constructor(e={}){super(),this.config={defaultStrategy:e.defaultStrategy??"round-robin",healthAwareRouting:e.healthAwareRouting??!0,healthCheckInterval:e.healthCheckInterval??3e4,maxFailoverRetries:e.maxFailoverRetries??3,namespaceSeparator:e.namespaceSeparator??".",autoNamespace:e.autoNamespace??!1,conflictResolution:e.conflictResolution??"first-wins"}}addServer(e){this.servers.set(e.id,e),this.metrics.set(e.id,{activeRequests:0,totalRequests:0,completedRequests:0,averageResponseTime:0,errorRate:0,isHealthy:e.status==="connected"}),this.emit("serverAdded",{serverId:e.id,server:e}),f.debug(`[MultiServerManager] Added server: ${e.id} (${e.name})`)}removeServer(e){if(!this.servers.get(e))return!1;for(const[r,n]of this.groups){const o=n.servers.indexOf(e);o!==-1&&(n.servers.splice(o,1),n.servers.length===0&&(this.groups.delete(r),this.roundRobinCounters.delete(r)))}this.servers.delete(e),this.metrics.delete(e);for(const[r,n]of this.toolPreferences)n===e&&this.toolPreferences.delete(r);return this.emit("serverRemoved",{serverId:e}),f.debug(`[MultiServerManager] Removed server: ${e}`),!0}updateServer(e,t){const r=this.servers.get(e);if(!r)throw ve.invalidConfiguration("serverId",`Server '${e}' not found`,{serverId:e});const n={...r,...t,id:e};this.servers.set(e,n);const o=this.metrics.get(e);o&&t.status!==void 0&&(o.isHealthy=t.status==="connected"),this.emit("serverUpdated",{serverId:e,server:n})}createGroup(e){for(const t of e.servers)if(!this.servers.has(t))throw ve.invalidConfiguration("serverGroup.servers",`Server '${t}' not found when creating group '${e.id}'`,{serverId:t,groupId:e.id});this.groups.set(e.id,e),this.roundRobinCounters.set(e.id,0),this.emit("groupCreated",{group:e}),f.debug(`[MultiServerManager] Created group: ${e.id} with ${e.servers.length} servers`)}removeGroup(e){const t=this.groups.delete(e);return t&&(this.roundRobinCounters.delete(e),this.emit("groupRemoved",{groupId:e})),t}addServerToGroup(e,t){const r=this.groups.get(t);if(!r)throw ve.invalidConfiguration("groupId",`Group '${t}' not found`,{groupId:t});if(!this.servers.has(e))throw ve.invalidConfiguration("serverId",`Server '${e}' not found`,{serverId:e,groupId:t});r.servers.includes(e)||(r.servers.push(e),this.emit("serverAddedToGroup",{serverId:e,groupId:t}))}removeServerFromGroup(e,t){const r=this.groups.get(t);if(!r)return!1;const n=r.servers.indexOf(e);return n!==-1?(r.servers.splice(n,1),this.emit("serverRemovedFromGroup",{serverId:e,groupId:t}),!0):!1}getUnifiedTools(){const e=new Map;for(const[t,r]of this.servers){const o=this.metrics.get(t)?.isHealthy??!0;if(!(this.config.healthAwareRouting&&!o))for(const i of r.tools||[]){const s=e.get(i.name);s?(s.hasConflict=!0,s.servers.push({serverId:t,serverName:r.name,inputSchema:i.inputSchema,priority:this.getServerPriority(t)})):e.set(i.name,{name:i.name,description:i.description,servers:[{serverId:t,serverName:r.name,inputSchema:i.inputSchema,priority:this.getServerPriority(t)}],hasConflict:!1,preferredServerId:this.toolPreferences.get(i.name)})}}for(const t of e.values())t.servers.sort((r,n)=>r.priority-n.priority),!t.preferredServerId&&t.servers.length>0&&(t.preferredServerId=t.servers[0].serverId);return Array.from(e.values())}getNamespacedTools(){const e=[];for(const[t,r]of this.servers)if(!(this.config.healthAwareRouting&&!(this.metrics.get(t)?.isHealthy??!0)))for(const n of r.tools||[])e.push({fullName:`${t}${this.config.namespaceSeparator}${n.name}`,toolName:n.name,serverId:t,serverName:r.name,description:n.description,inputSchema:n.inputSchema});return e}setToolPreference(e,t){if(!this.servers.has(t))throw ve.invalidConfiguration("serverId",`Server '${t}' not found`,{serverId:t,toolName:e});this.toolPreferences.set(e,t),this.emit("toolPreferenceSet",{toolName:e,serverId:t})}clearToolPreference(e){this.toolPreferences.delete(e)}selectServer(e,t){const r=this.toolPreferences.get(e);if(r){const u=this.servers.get(r),l=this.metrics.get(r);if(u&&(!this.config.healthAwareRouting||l?.isHealthy)&&u.tools?.some(c=>c.name===e))return{serverId:r,server:u}}let n;if(t){const u=this.groups.get(t);if(!u)return f.warn(`[MultiServerManager] Group '${t}' not found`),null;n=u.servers.filter(l=>this.servers.get(l)?.tools?.some(d=>d.name===e))}else{n=[];for(const[u,l]of this.servers)l.tools?.some(c=>c.name===e)&&n.push(u)}if(n.length===0)return null;if((t?this.groups.get(t)?.healthAware??this.config.healthAwareRouting:this.config.healthAwareRouting)&&(n=n.filter(u=>this.metrics.get(u)?.isHealthy??!0),n.length===0))return f.warn(`[MultiServerManager] No healthy servers available for tool '${e}'`),null;const i=t?this.groups.get(t)?.strategy??this.config.defaultStrategy:this.config.defaultStrategy,s=this.applyStrategy(i,n,t);if(!s)return null;const a=this.servers.get(s);return a?{serverId:s,server:a}:null}applyStrategy(e,t,r){if(t.length===0)return null;if(t.length===1)return t[0];switch(e){case"round-robin":{const n=r??"default",o=this.roundRobinCounters.get(n)??0,i=t[o%t.length];return this.roundRobinCounters.set(n,o+1),i}case"least-loaded":{let n=1/0,o=t[0];for(const i of t){const a=this.metrics.get(i)?.activeRequests??0;a<n&&(n=a,o=i)}return o}case"random":{const n=Math.floor(Math.random()*t.length);return t[n]}case"weighted":{if(!r){const u=Math.floor(Math.random()*t.length);return t[u]}const n=this.groups.get(r);if(!n?.weights){const u=Math.floor(Math.random()*t.length);return t[u]}const o=1,i=t.map(u=>{const c=(n.weights??[]).find(d=>d.serverId===u);return{serverId:u,weight:c?.weight??o}}),s=i.reduce((u,l)=>u+l.weight,0);if(s===0){const u=Math.floor(Math.random()*t.length);return t[u]}let a=Math.random()*s;for(const u of i)if(a-=u.weight,a<=0)return u.serverId;return t[0]}case"failover-only":return t.map(o=>({id:o,priority:this.getServerPriority(o,r)})).sort((o,i)=>o.priority-i.priority)[0]?.id??null;default:return t[0]}}getServerPriority(e,t){if(t){const n=this.groups.get(t);if(n?.weights){const o=n.weights.find(i=>i.serverId===e);if(o)return o.priority}}for(const n of this.groups.values())if(n.weights){const o=n.weights.find(i=>i.serverId===e);if(o)return o.priority}return Array.from(this.servers.keys()).indexOf(e)}updateMetrics(e,t){const r=this.metrics.get(e);r&&(Object.assign(r,t),this.emit("metricsUpdated",{serverId:e,metrics:{...r}}))}requestStarted(e){const t=this.metrics.get(e);t&&(t.activeRequests++,t.totalRequests++)}requestCompleted(e,t,r){const n=this.metrics.get(e);if(n){n.activeRequests=Math.max(0,n.activeRequests-1),n.completedRequests++;const o=n.averageResponseTime*(n.completedRequests-1)+t;n.averageResponseTime=o/n.completedRequests;const i=.1;n.errorRate=n.errorRate*(1-i)+(r?0:1)*i}}getServers(){return Array.from(this.servers.values())}getServer(e){return this.servers.get(e)}getGroups(){return Array.from(this.groups.values())}getGroup(e){return this.groups.get(e)}getServerMetrics(e){return this.metrics.get(e)}getAllMetrics(){return new Map(this.metrics)}getStatistics(){let e=0,t=0,r=0;for(const i of this.metrics.values())i.isHealthy&&e++,t+=i.totalRequests,r+=i.activeRequests;const n=this.getUnifiedTools(),o=n.filter(i=>i.hasConflict).length;return{totalServers:this.servers.size,healthyServers:e,totalGroups:this.groups.size,totalTools:n.length,conflictingTools:o,totalRequests:t,activeRequests:r}}},rue=new b1}}),Ter={};ue(Ter,{EnhancedToolDiscovery:()=>T6});var T6,oue=S({"src/lib/mcp/enhancedToolDiscovery.ts"(){"use strict";so(),z(),Hr(),et(),w1(),nue(),T6=class extends bn{toolRegistry=new Map;serverToolsMap=new Map;multiServerManager;discoveryInProgress=new Set;constructor(e){super(),this.multiServerManager=e??new b1}async discoverToolsWithAnnotations(e,t,r=1e4){const n=Date.now();if(this.discoveryInProgress.has(e))return{success:!1,error:`Discovery already in progress for server: ${e}`,toolCount:0,tools:[],duration:Date.now()-n,serverId:e};this.discoveryInProgress.add(e);try{f.info(`[EnhancedToolDiscovery] Starting discovery with annotations for: ${e}`);const o=await kt(t.listTools(),r,"Discovery timeout");if(!o?.tools)throw ve.toolExecutionFailed("discoverTools",new Error("No tools returned from server"),e);this.clearServerTools(e);const i=[];for(const s of o.tools){const a=this.createEnhancedToolInfo(e,s),u=this.createToolKey(e,s.name);this.toolRegistry.set(u,a);let l=this.serverToolsMap.get(e);l||(l=new Set,this.serverToolsMap.set(e,l)),l.add(s.name),i.push(a),this.emit("toolDiscovered",{serverId:e,toolName:s.name,annotations:a.annotations,timestamp:new Date})}return f.info(`[EnhancedToolDiscovery] Discovered ${i.length} tools with annotations from ${e}`),{success:!0,toolCount:i.length,tools:i,duration:Date.now()-n,serverId:e}}catch(o){const i=o instanceof Error?o.message:String(o);return f.error(`[EnhancedToolDiscovery] Discovery failed for ${e}:`,o),{success:!1,error:i,toolCount:0,tools:[],duration:Date.now()-n,serverId:e}}finally{this.discoveryInProgress.delete(e)}}createEnhancedToolInfo(e,t){const r=om({name:t.name,description:t.description??""});return{name:t.name,description:t.description??"No description provided",serverId:e,inputSchema:t.inputSchema,isAvailable:!0,annotations:r,version:"1.0.0",stats:{totalCalls:0,successfulCalls:0,failedCalls:0,averageExecutionTime:0,lastExecutionTime:0},metadata:{category:this.inferCategory(t),deprecated:!1}}}inferCategory(e){const t=e.name.toLowerCase(),r=(e.description??"").toLowerCase();return t.includes("git")||r.includes("git")?"version-control":t.includes("file")||t.includes("read")||t.includes("write")?"file-system":t.includes("api")||t.includes("http")?"api":t.includes("data")||t.includes("query")?"data":t.includes("auth")||t.includes("login")?"authentication":t.includes("deploy")||t.includes("build")?"deployment":"general"}searchTools(e){const t=Date.now();let r=Array.from(this.toolRegistry.values());if(e.name){const o=e.name.toLowerCase();r=r.filter(i=>i.name.toLowerCase().includes(o))}if(e.description){const o=e.description.toLowerCase().split(/\s+/);r=r.filter(i=>{const s=i.description.toLowerCase();return o.some(a=>s.includes(a))})}if(e.serverIds?.length){const o=e.serverIds;r=r.filter(i=>o.includes(i.serverId))}if(e.category&&(r=r.filter(o=>o.metadata?.category===e.category)),e.tags?.length){const o=e.tags;r=r.filter(i=>{const s=i.annotations?.tags??[];return o.some(a=>s.includes(a))})}if(e.annotations){const o=e.annotations;r=r.filter(i=>{if(!i.annotations)return!1;for(const[s,a]of Object.entries(o)){const u=s;if(i.annotations[u]!==a)return!1}return!0})}if(e.includeUnavailable||(r=r.filter(o=>o.isAvailable)),e.sortBy){const o=e.sortDirection==="desc"?-1:1;r.sort((i,s)=>{let a=0;switch(e.sortBy){case"name":a=i.name.localeCompare(s.name);break;case"calls":a=i.stats.totalCalls-s.stats.totalCalls;break;case"successRate":{const u=i.stats.totalCalls>0?i.stats.successfulCalls/i.stats.totalCalls:0,l=s.stats.totalCalls>0?s.stats.successfulCalls/s.stats.totalCalls:0;a=u-l;break}case"avgExecutionTime":a=i.stats.averageExecutionTime-s.stats.averageExecutionTime;break}return a*o})}const n=r.length;return e.limit&&e.limit>0&&(r=r.slice(0,e.limit)),{tools:r,totalCount:n,criteria:e,executionTime:Date.now()-t}}getToolsBySafetyLevel(e){return Array.from(this.toolRegistry.values()).filter(t=>{const r=t.annotations??{};switch(e){case"dangerous":return r.destructiveHint===!0;case"safe":return r.readOnlyHint===!0;case"moderate":return!r.destructiveHint&&!r.readOnlyHint;default:return!1}})}getToolsRequiringConfirmation(){return Array.from(this.toolRegistry.values()).filter(e=>e.annotations?.requiresConfirmation===!0||e.annotations?.destructiveHint===!0)}getReadOnlyTools(){return Array.from(this.toolRegistry.values()).filter(e=>e.annotations?.readOnlyHint===!0)}getUnifiedTools(){return this.multiServerManager.getUnifiedTools()}registerServer(e){this.multiServerManager.addServer(e)}updateToolAnnotations(e,t,r){const n=this.createToolKey(e,t),o=this.toolRegistry.get(n);return o?(o.annotations={...o.annotations,...r},this.emit("annotationsUpdated",{serverId:e,toolName:t,annotations:o.annotations,timestamp:new Date}),!0):!1}checkCompatibility(e,t,r){const n=this.createToolKey(t,e),o=this.toolRegistry.get(n),i=[],s=[],a=[];if(!o)return{compatible:!1,issues:[`Tool '${e}' not found on server '${t}'`],warnings:[],recommendations:[]};if(r&&o.version){const u=o.version.split(".").map(Number),l=r.split(".").map(Number);u.some(isNaN)||l.some(isNaN)?s.push(`Non-standard version format: tool=${o.version}, target=${r}`):u[0]!==l[0]?i.push(`Major version mismatch: tool is v${o.version}, target is v${r}`):u[1]<l[1]&&s.push(`Minor version mismatch: tool is v${o.version}, target is v${r}`)}return o.metadata?.deprecated&&(s.push("This tool is marked as deprecated"),a.push("Consider using an alternative tool if available")),o.annotations?.securityLevel==="restricted"&&a.push("This tool requires elevated permissions"),{compatible:i.length===0,issues:i,warnings:s,recommendations:a}}getTool(e,t){return this.toolRegistry.get(this.createToolKey(e,t))}getAllTools(){return Array.from(this.toolRegistry.values())}getServerTools(e){const t=this.serverToolsMap.get(e);return t?Array.from(t).map(r=>this.getTool(e,r)).filter(r=>r!==void 0):[]}clearServerTools(e){const t=this.serverToolsMap.get(e);if(t){for(const r of t)this.toolRegistry.delete(this.createToolKey(e,r));this.serverToolsMap.delete(e)}}createToolKey(e,t){return`${e}:${t}`}getStatistics(){const e={},t={},r={safe:0,moderate:0,dangerous:0};let n=0,o=0;for(const i of this.toolRegistry.values()){e[i.serverId]=(e[i.serverId]??0)+1;const s=i.metadata?.category??"general";t[s]=(t[s]??0)+1,i.annotations?.destructiveHint?r.dangerous++:i.annotations?.readOnlyHint?r.safe++:r.moderate++,i.annotations&&Object.keys(i.annotations).length>0&&n++,i.metadata?.deprecated&&o++}return{totalTools:this.toolRegistry.size,toolsByServer:e,toolsByCategory:t,toolsBySafetyLevel:r,toolsWithAnnotations:n,deprecatedTools:o}}}}}),_er,iue,sue,T1,aue=S({"src/lib/mcp/mcpCircuitBreaker.ts"(){"use strict";so(),Kt(),z(),lt(),lt(),_er=Math.max(1e4,Number(process.env.MCP_OPERATION_TIMEOUT)||6e4),iue=class extends bn{constructor(e,t={}){super(),this.name=e,this.config={failureThreshold:t.failureThreshold??5,resetTimeout:t.resetTimeout??6e4,halfOpenMaxCalls:t.halfOpenMaxCalls??3,operationTimeout:t.operationTimeout??_er,minimumCallsBeforeCalculation:t.minimumCallsBeforeCalculation??10,statisticsWindowSize:t.statisticsWindowSize??3e5},this.cleanupTimer=setInterval(()=>this.cleanupCallHistory(),6e4),this.cleanupTimer.unref&&this.cleanupTimer.unref()}name;state="closed";config;callHistory=[];lastFailureTime=0;halfOpenCalls=0;lastStateChange=new Date;cleanupTimer;async execute(e){const t=Date.now();try{if(this.state==="open"){const i=this.config.resetTimeout-(Date.now()-this.lastFailureTime);if(i>0)throw new uh({breakerName:this.name,retryAfter:new Date(this.lastFailureTime+this.config.resetTimeout),retryAfterMs:i,breakerState:"open",failureCount:this.getStats().failedCalls});this.changeState("half-open","Reset timeout reached")}if(this.state==="half-open"&&this.halfOpenCalls>=this.config.halfOpenMaxCalls)throw this.lastFailureTime=Date.now(),this.changeState("open","Half-open call limit reached, reverting to open"),new uh({breakerName:this.name,retryAfter:new Date(this.lastFailureTime+this.config.resetTimeout),retryAfterMs:this.config.resetTimeout,breakerState:"open",failureCount:this.getStats().failedCalls});if(this.state==="half-open"){const i=Qt.getActiveSpan();i&&i.addEvent("circuit.half_open_test",{"circuit.name":this.name,"circuit.half_open_call":this.halfOpenCalls+1,"circuit.half_open_max_calls":this.config.halfOpenMaxCalls})}let r;const n=i=>{r=i||"Operation resolved a failure result"},o=await this.raceWithTimeout(e(n),this.config.operationTimeout);return r!==void 0?(this.recordFailureOutcome(r,Date.now()-t),o):(this.recordCall(!0,Date.now()-t),this.state==="half-open"&&(this.halfOpenCalls++,this.halfOpenCalls>=this.config.halfOpenMaxCalls&&this.changeState("closed","Half-open test successful")),o)}catch(r){const n=Date.now()-t,o=r instanceof Error?r.message:String(r);throw this.recordFailureOutcome(o,n),r}}recordFailureOutcome(e,t){this.recordCall(!1,t),this.emit("callFailure",{error:e,duration:t,timestamp:new Date}),this.state==="half-open"?this.changeState("open",`Half-open test failed: ${e}`):this.state==="closed"&&this.checkFailureThreshold()}recordCall(e,t){const r=Date.now();this.callHistory.push({timestamp:r,success:e,duration:t}),e&&this.emit("callSuccess",{duration:t,timestamp:new Date}),e||(this.lastFailureTime=r)}checkFailureThreshold(){const e=Date.now()-this.config.statisticsWindowSize,t=this.callHistory.filter(o=>o.timestamp>=e);if(t.length<this.config.minimumCallsBeforeCalculation)return;const r=t.filter(o=>!o.success).length,n=r/t.length;ae.debug(`[CircuitBreaker:${this.name}] Failure rate: ${(n*100).toFixed(1)}% (${r}/${t.length})`),r>=this.config.failureThreshold&&(this.changeState("open",`Failure threshold exceeded: ${r} failures`),this.emit("circuitOpen",{failureRate:n,totalCalls:t.length,timestamp:new Date}))}changeState(e,t){const r=this.state;this.state=e,this.lastStateChange=new Date;const n=Qt.getActiveSpan();n&&n.addEvent("circuit.state_change",{"circuit.name":this.name,"circuit.from_state":r,"circuit.to_state":e,"circuit.reason":t.slice(0,128),"circuit.failure_count":this.callHistory.filter(o=>!o.success).length}),e==="half-open"?(this.halfOpenCalls=0,this.emit("circuitHalfOpen",{timestamp:new Date})):e==="closed"&&(this.halfOpenCalls=0,this.emit("circuitClosed",{timestamp:new Date})),ae.info(`[CircuitBreaker:${this.name}] State changed: ${r} -> ${e} (${t})`),this.emit("stateChange",{oldState:r,newState:e,reason:t,timestamp:new Date})}async raceWithTimeout(e,t){let r;const n=new Promise((o,i)=>{r=setTimeout(()=>{i(new Error(`Operation timed out after ${t}ms`))},t)});try{return await Promise.race([e,n])}finally{clearTimeout(r)}}cleanupCallHistory(){const e=Date.now()-this.config.statisticsWindowSize,t=this.callHistory.length;this.callHistory=this.callHistory.filter(n=>n.timestamp>=e);const r=t-this.callHistory.length;r>0&&ae.debug(`[CircuitBreaker:${this.name}] Cleaned up ${r} old call records`)}getStats(){const e=Date.now()-this.config.statisticsWindowSize,t=this.callHistory.filter(i=>i.timestamp>=e),r=t.filter(i=>i.success).length,n=t.length-r,o=t.length>0?n/t.length:0;return{state:this.state,totalCalls:this.callHistory.length,successfulCalls:this.callHistory.filter(i=>i.success).length,failedCalls:this.callHistory.filter(i=>!i.success).length,failureRate:o,windowCalls:t.length,lastStateChange:this.lastStateChange,nextRetryTime:this.state==="open"?new Date(this.lastFailureTime+this.config.resetTimeout):void 0,halfOpenCalls:this.halfOpenCalls}}reset(){this.changeState("closed","Manual reset"),this.callHistory=[],this.lastFailureTime=0,this.halfOpenCalls=0}forceOpen(e="Manual force open"){this.changeState("open",e),this.lastFailureTime=Date.now()}getName(){return this.name}isOpen(){return this.state==="open"}isClosed(){return this.state==="closed"}isHalfOpen(){return this.state==="half-open"}destroy(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0,ae.debug(`[CircuitBreaker:${this.name}] Cleanup timer cleared`)),this.removeAllListeners(),this.callHistory=[],ae.debug(`[CircuitBreaker:${this.name}] Destroyed and cleaned up`)}},sue=class{breakers=new Map;getBreaker(e,t){if(!this.breakers.has(e)){const n=new iue(e,t);this.breakers.set(e,n),ae.debug(`[CircuitBreakerManager] Created circuit breaker: ${e}`)}const r=this.breakers.get(e);if(!r)throw new Error(`Circuit breaker ${e} not found after creation`);return r}removeBreaker(e){const t=this.breakers.get(e);return t?(t.destroy(),this.breakers.delete(e),ae.debug(`[CircuitBreakerManager] Removed and cleaned up circuit breaker: ${e}`),!0):!1}getBreakerNames(){return Array.from(this.breakers.keys())}getAllStats(){const e={};for(const[t,r]of this.breakers)e[t]=r.getStats();return e}resetAll(){for(const e of this.breakers.values())e.reset();ae.info("[CircuitBreakerManager] Reset all circuit breakers")}getHealthSummary(){let e=0,t=0,r=0;const n=[];for(const[o,i]of this.breakers)switch(i.getStats().state){case"closed":e++;break;case"open":t++,n.push(o);break;case"half-open":r++;break}return{totalBreakers:this.breakers.size,closedBreakers:e,openBreakers:t,halfOpenBreakers:r,unhealthyBreakers:n}}destroyAll(){for(const e of this.breakers.values())e.destroy();this.breakers.clear(),ae.info("[CircuitBreakerManager] Destroyed all circuit breakers")}},T1=new sue}});function _yn(e){return new Promise(t=>setTimeout(t,e))}function _6(e,t=rp){return t.retryableStatusCodes.includes(e)}function Eer(e,t=rp){if(!e||typeof e!="object")return!1;const r=e;if(dr(e))return!1;if(r.name==="TimeoutError"||r.code==="TIMEOUT"||r.code==="ETIMEDOUT"||r.code==="ECONNRESET"||r.code==="ENOTFOUND"||r.code==="ECONNREFUSED"||r.code==="ECONNABORTED"||r.code==="EPIPE"||r.code==="ENETUNREACH"||r.code==="EHOSTUNREACH")return!0;if(r.name==="TypeError"&&typeof r.message=="string"){const n=r.message.toLowerCase();if(n.includes("fetch")||n.includes("network")||n.includes("connection"))return!0}return typeof r.status=="number"?_6(r.status,t):r.response&&typeof r.response=="object"&&typeof r.response.status=="number"?_6(r.response.status,t):typeof r.statusCode=="number"?_6(r.statusCode,t):!1}async function Ser(e,t={}){const r={...rp,...t},{traceId:n,parentSpanId:o}=E0(),i=Ie.createSpan("mcp.transport","mcp.retry",{"mcp.transport":"http","mcp.operation":"retry","mcp.maxAttempts":r.maxAttempts},o,n),s=Date.now();let a,u=0;for(let c=1;c<=r.maxAttempts;c++){u=c;try{const d=await e();i.durationMs=Date.now()-s,i.attributes["mcp.retryAttempt"]=c;const p=Ie.endSpan(i,1);return nt().recordSpan(p),d}catch(d){if(a=d,c===r.maxAttempts){f.debug(`HTTP retry: All ${r.maxAttempts} attempts exhausted`);break}if(!Eer(d,r)){f.debug("HTTP retry: Non-retryable error encountered",d instanceof Error?d.message:String(d));break}const p=ySt(c,r.initialDelay,r.backoffMultiplier,r.maxDelay,!0),m=d instanceof Error?d.message:String(d);f.warn(`HTTP retry: Attempt ${c}/${r.maxAttempts} failed: ${m}. Retrying in ${Math.round(p)}ms...`),await _yn(p)}}i.durationMs=Date.now()-s,i.attributes["mcp.retryAttempt"]=u;const l=Ie.endSpan(i,2);throw l.statusMessage=a instanceof Error?a.message:String(a),nt().recordSpan(l),a}var rp,ker=S({"src/lib/mcp/httpRetryHandler.ts"(){"use strict";et(),_St(),z(),oo(),S0(),rp={maxAttempts:3,initialDelay:1e3,maxDelay:3e4,backoffMultiplier:2,retryableStatusCodes:[408,429,500,502,503,504]}}}),uue,lue,cue,due,Aer=S({"src/lib/mcp/httpRateLimiter.ts"(){"use strict";z(),Yk(),oo(),S0(),uue={requestsPerWindow:60,windowMs:6e4,useTokenBucket:!0,refillRate:1,maxBurst:10},lue=class{tokens;lastRefill;config;waitQueue=[];processingQueue=!1;constructor(e={}){this.config={...uue,...e},this.tokens=this.config.maxBurst,this.lastRefill=Date.now(),ae.debug("[HTTPRateLimiter] Initialized with config:",{requestsPerWindow:this.config.requestsPerWindow,windowMs:this.config.windowMs,useTokenBucket:this.config.useTokenBucket,refillRate:this.config.refillRate,maxBurst:this.config.maxBurst})}refillTokens(){const e=Date.now(),n=(e-this.lastRefill)/1e3*this.config.refillRate;if(n>=1){const o=this.tokens;this.tokens=Math.min(this.config.maxBurst,this.tokens+n),this.lastRefill=e,this.tokens>o&&ae.debug(`[HTTPRateLimiter] Refilled tokens: ${o.toFixed(2)} -> ${this.tokens.toFixed(2)} (+${n.toFixed(2)})`)}}async acquire(){const{traceId:e,parentSpanId:t}=E0(),r=Ie.createSpan("mcp.transport","mcp.rateLimit",{"mcp.transport":"http","mcp.operation":"rateLimit","mcp.rateLimit.tokensAvailable":this.tokens,"mcp.rateLimit.maxBurst":this.config.maxBurst},t,e),n=Date.now();try{if(this.tryAcquire()){r.durationMs=Date.now()-n,r.attributes["mcp.rateLimit.waited"]=!1;const i=Ie.endSpan(r,1);nt().recordSpan(i);return}await new Promise((i,s)=>{this.waitQueue.push({resolve:i,reject:s}),ae.debug(`[HTTPRateLimiter] Request queued, queue length: ${this.waitQueue.length}`),this.processingQueue||this.processQueue()}),r.durationMs=Date.now()-n,r.attributes["mcp.rateLimit.waited"]=!0;const o=Ie.endSpan(r,1);nt().recordSpan(o)}catch(o){r.durationMs=Date.now()-n;const i=Ie.endSpan(r,2);throw i.statusMessage=o instanceof Error?o.message:String(o),nt().recordSpan(i),o}}async processQueue(){if(!this.processingQueue){for(this.processingQueue=!0;this.waitQueue.length>0;)if(this.refillTokens(),this.tokens>=1){const e=this.waitQueue.shift();e&&(this.tokens-=1,ae.debug(`[HTTPRateLimiter] Token granted from queue, remaining: ${this.tokens.toFixed(2)}, queue: ${this.waitQueue.length}`),e.resolve())}else{const t=(1-this.tokens)/this.config.refillRate*1e3,r=Math.max(10,Math.ceil(t));ae.debug(`[HTTPRateLimiter] Waiting ${r}ms for token refill`),await this.sleep(r)}this.processingQueue=!1}}sleep(e){return new Promise(t=>setTimeout(t,e))}tryAcquire(){return this.refillTokens(),this.tokens>=1?(this.tokens-=1,ae.debug(`[HTTPRateLimiter] Token acquired, remaining: ${this.tokens.toFixed(2)}`),!0):(ae.debug(`[HTTPRateLimiter] No tokens available, current: ${this.tokens.toFixed(2)}`),!1)}handleRateLimitResponse(e){const t=Zw(e),r=e.get("Retry-After");if(r&&t!==void 0){const i=parseInt(r,10);if(isNaN(i)){const s=new Date(r);if(!isNaN(s.getTime()))return ae.info(`[HTTPRateLimiter] Server requested retry at ${s.toISOString()} (${t}ms)`),t}else return ae.info(`[HTTPRateLimiter] Server requested retry after ${i} seconds`),t}const n=e.get("X-RateLimit-Reset");if(n&&t!==void 0){const i=parseInt(n,10);if(!isNaN(i)){const s=i>1e12?i:i*1e3;return ae.info(`[HTTPRateLimiter] Rate limit resets at ${new Date(s).toISOString()} (${t}ms)`),t}}return e.get("X-RateLimit-Remaining")==="0"&&t!==void 0?(ae.info(`[HTTPRateLimiter] Rate limit exhausted, using default backoff: ${t}ms`),t):t??0}getRemainingTokens(){return this.refillTokens(),this.tokens}reset(){for(this.tokens=this.config.maxBurst,this.lastRefill=Date.now();this.waitQueue.length>0;){const e=this.waitQueue.shift();e&&e.reject(new Error("Rate limiter was reset"))}ae.info(`[HTTPRateLimiter] Reset to initial state, tokens: ${this.tokens}`)}getStats(){return this.refillTokens(),{tokens:this.tokens,maxBurst:this.config.maxBurst,refillRate:this.config.refillRate,queueLength:this.waitQueue.length,lastRefill:new Date(this.lastRefill)}}updateConfig(e){Object.assign(this.config,e),ae.info("[HTTPRateLimiter] Configuration updated:",e)}getConfig(){return{...this.config}}},cue=class{limiters=new Map;getLimiter(e,t){let r=this.limiters.get(e);return r?t&&r.updateConfig(t):(r=new lue(t),this.limiters.set(e,r),ae.debug(`[RateLimiterManager] Created rate limiter for server: ${e}`)),r}hasLimiter(e){return this.limiters.has(e)}removeLimiter(e){const t=this.limiters.get(e);t&&(t.reset(),this.limiters.delete(e),ae.debug(`[RateLimiterManager] Removed rate limiter for server: ${e}`))}getServerIds(){return Array.from(this.limiters.keys())}getAllStats(){const e={};for(const[t,r]of this.limiters)e[t]=r.getStats();return e}resetAll(){for(const e of this.limiters.values())e.reset();ae.info("[RateLimiterManager] Reset all rate limiters")}destroyAll(){for(const e of this.limiters.values())e.reset();this.limiters.clear(),ae.info("[RateLimiterManager] Destroyed all rate limiters")}getHealthSummary(){const e=[];let t=0,r=0;for(const[o,i]of this.limiters){const s=i.getStats();s.queueLength>0&&(e.push(o),t+=s.queueLength),r+=s.tokens}const n=this.limiters.size>0?r/this.limiters.size:0;return{totalLimiters:this.limiters.size,serversWithQueuedRequests:e,totalQueuedRequests:t,averageTokensAvailable:n}}},due=new cue}});function Cer(e,t=60){if(!e.expiresAt)return!1;const r=t*1e3,n=Date.now();return e.expiresAt-r<=n}function pue(e){return Date.now()+e*1e3}var E6,xer,Ier=S({"src/lib/mcp/auth/tokenStorage.ts"(){"use strict";z(),E6=class{tokens=new Map;async getTokens(e){return this.tokens.get(e)??null}async saveTokens(e,t){this.tokens.set(e,t)}async deleteTokens(e){this.tokens.delete(e)}async hasTokens(e){return this.tokens.has(e)}async clearAll(){this.tokens.clear()}get size(){return this.tokens.size}getServerIds(){return Array.from(this.tokens.keys())}},xer=class{filePath;tokens=new Map;loaded=!1;constructor(e){this.filePath=e}async loadTokens(){if(!this.loaded)try{const t=await(await Promise.resolve().then(()=>(Ti(),F0))).readFile(this.filePath,"utf-8"),r=JSON.parse(t);this.tokens=new Map(Object.entries(r)),this.loaded=!0}catch(e){e instanceof Error&&"code"in e&&e.code!=="ENOENT"&&f.warn(`[FileTokenStorage] Error loading tokens: ${e.message}`),this.tokens=new Map,this.loaded=!0}}async saveToFile(){try{const e=await Promise.resolve().then(()=>(Ti(),F0)),t=await Promise.resolve().then(()=>(Sr(),Xm)),{randomBytes:r}=await Promise.resolve().then(()=>(qt(),ew)),n=t.dirname(this.filePath);await e.mkdir(n,{recursive:!0,mode:448});const o=Object.fromEntries(this.tokens.entries()),i=`${this.filePath}.${process.pid}.${r(6).toString("hex")}.tmp`;try{await e.writeFile(i,JSON.stringify(o,null,2),{encoding:"utf-8",mode:384,flag:"wx"}),await e.rename(i,this.filePath),await e.chmod(this.filePath,384)}catch(s){throw await e.rm(i,{force:!0}),s}}catch(e){throw f.error(`[FileTokenStorage] Error saving tokens: ${e instanceof Error?e.message:String(e)}`),e}}async getTokens(e){return await this.loadTokens(),this.tokens.get(e)??null}async saveTokens(e,t){await this.loadTokens(),this.tokens.set(e,t),await this.saveToFile()}async deleteTokens(e){await this.loadTokens(),this.tokens.delete(e),await this.saveToFile()}async hasTokens(e){return await this.loadTokens(),this.tokens.has(e)}async clearAll(){this.tokens.clear(),await this.saveToFile()}}}});function Eyn(e,t){return new S6({clientId:e.clientId,clientSecret:e.clientSecret,authorizationUrl:e.authorizationUrl,tokenUrl:e.tokenUrl,redirectUrl:e.redirectUrl,scope:e.scope,usePKCE:e.usePKCE??!0},t)}var gy,S6,Syn=S({"src/lib/mcp/auth/oauthClientProvider.ts"(){"use strict";qt(),Ier(),z(),et(),gy=3e4,S6=class{config;storage;pendingChallenges=new Map;pendingStates=new Set;constructor(e,t){this.config={...e,usePKCE:e.usePKCE??!0},this.storage=t??new E6}async tokens(e){const t=await this.storage.getTokens(e);if(!t)return null;if(Cer(t)){if(t.refreshToken)try{return await this.refreshTokens(e,t.refreshToken)}catch(r){return f.warn(`[NeuroLinkOAuthProvider] Token refresh failed: ${r instanceof Error?r.message:String(r)}`),await this.storage.deleteTokens(e),null}return await this.storage.deleteTokens(e),null}return t}async saveTokens(e,t){await this.storage.saveTokens(e,t)}async deleteTokens(e){await this.storage.deleteTokens(e)}clientInformation(){return{clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:this.config.redirectUrl}}redirectToAuthorization(e){const t=this.generateState();this.pendingStates.add(t);const r=new URL(this.config.authorizationUrl);r.searchParams.set("response_type","code"),r.searchParams.set("client_id",this.config.clientId),r.searchParams.set("redirect_uri",this.config.redirectUrl),r.searchParams.set("state",t),this.config.scope&&r.searchParams.set("scope",this.config.scope);let n;if(this.config.usePKCE){const o=this.generatePKCE();n=o.codeVerifier,this.pendingChallenges.set(t,o),r.searchParams.set("code_challenge",o.codeChallenge),r.searchParams.set("code_challenge_method",o.codeChallengeMethod)}if(this.config.additionalParams)for(const[o,i]of Object.entries(this.config.additionalParams))r.searchParams.set(o,i);return{url:r.toString(),state:t,codeVerifier:n}}async exchangeCode(e,t){if(!this.pendingStates.has(t.state))throw new Error("Invalid or expired state parameter");this.pendingStates.delete(t.state);let r=t.codeVerifier;if(this.config.usePKCE&&!r){const a=this.pendingChallenges.get(t.state);a&&(r=a.codeVerifier,this.pendingChallenges.delete(t.state))}const n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",t.code),n.set("redirect_uri",this.config.redirectUrl),n.set("client_id",this.config.clientId),this.config.clientSecret&&n.set("client_secret",this.config.clientSecret),r&&n.set("code_verifier",r);const o=await Ge(fetch(this.config.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:n.toString()}),gy,new Error(`OAuth token exchange timed out after ${gy}ms`));if(!o.ok){const a=await o.text();throw new Error(`Token exchange failed: ${o.status} ${o.statusText} - ${a}`)}const i=await o.json(),s={accessToken:i.access_token,refreshToken:i.refresh_token,expiresAt:i.expires_in?pue(i.expires_in):void 0,tokenType:i.token_type??"Bearer",scope:i.scope};return await this.saveTokens(e,s),s}async refreshTokens(e,t){const r=new URLSearchParams;r.set("grant_type","refresh_token"),r.set("refresh_token",t),r.set("client_id",this.config.clientId),this.config.clientSecret&&r.set("client_secret",this.config.clientSecret);const n=await Ge(fetch(this.config.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:r.toString()}),gy,new Error(`OAuth token refresh timed out after ${gy}ms`));if(!n.ok){const s=await n.text();throw new Error(`Token refresh failed: ${n.status} ${n.statusText} - ${s}`)}const o=await n.json(),i={accessToken:o.access_token,refreshToken:o.refresh_token??t,expiresAt:o.expires_in?pue(o.expires_in):void 0,tokenType:o.token_type??"Bearer",scope:o.scope};return await this.saveTokens(e,i),i}async revokeTokens(e,t){const r=await this.storage.getTokens(e);if(!r)return;const n=new URLSearchParams;n.set("token",r.accessToken),n.set("client_id",this.config.clientId),this.config.clientSecret&&n.set("client_secret",this.config.clientSecret);try{await Ge(fetch(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()}),gy,new Error(`OAuth token revocation timed out after ${gy}ms`))}catch(o){f.warn(`[NeuroLinkOAuthProvider] Token revocation failed: ${o instanceof Error?o.message:String(o)}`)}await this.storage.deleteTokens(e)}async getAuthorizationHeader(e){const t=await this.tokens(e);return t?`${t.tokenType} ${t.accessToken}`:null}async hasValidTokens(e){return await this.tokens(e)!==null}generateState(){return pg(32).toString("base64url")}generatePKCE(){const e=pg(32).toString("base64url"),t=sc("sha256").update(e).digest("base64url");return{codeVerifier:e,codeChallenge:t,codeChallengeMethod:"S256"}}getConfig(){return{...this.config}}getStorage(){return this.storage}cleanupPendingRequests(){this.pendingStates.size>100&&this.pendingStates.clear(),this.pendingChallenges.size>100&&this.pendingChallenges.clear()}}}}),Rer=S({"src/lib/mcp/auth/index.ts"(){"use strict";Ier(),Syn()}});function kyn(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function Ayn(e){const t=e.endsWith(".")?e.slice(0,-1):e;return t==="localhost"||t.endsWith(".localhost")}function mue(e){const t=jb(e);if(t===0)throw new Error(`"${e}" is not an IP address`);const r=t===4?"ipv4":"ipv6";return k6.check(e,r)?"loopback":xa.check(e,r)?"private":"public"}function Rc(e){return e.serverId?`MCP server "${e.serverId}" (${e.transport})`:`MCP ${e.transport} transport`}async function Cyn(e){return(await m3(e,{all:!0,verbatim:!0})).map(r=>r.address)}async function Mer(e,t){let r;try{r=new URL(e)}catch{throw new Error(`${Rc(t)}: "${e}" is not a valid URL`)}const n=r.protocol,o=Der.has(n);if(!o&&!Per.has(n))throw new Error(`${Rc(t)}: scheme "${n}" is not allowed (use https:, wss:, or http:/ws: for a loopback host)`);const i=kyn(r.hostname).toLowerCase();if(i.length===0)throw new Error(`${Rc(t)}: "${e}" has no host`);if(t.hostOwnedEgress===!0)return;const s=t.allowPrivateNetwork===!0,a=Ayn(i)?"loopback":jb(i)!==0?mue(i):void 0;if(a!==void 0){if(a==="loopback")return;if(!s){if(a==="private")throw new Error(`${Rc(t)}: "${e}" points at a private, link-local or metadata address; set "allowPrivateNetwork": true on this server if that is intended`);if(!o)throw new Error(`${Rc(t)}: "${e}" uses plaintext ${n} to a non-loopback host; use ${n==="ws:"?"wss:":"https:"}`);return}if(a==="public"&&!o)throw new Error(`${Rc(t)}: "${e}" uses plaintext ${n} to a public host; allowPrivateNetwork only permits plaintext to private addresses`);return}if(!o&&!s)throw new Error(`${Rc(t)}: "${e}" uses plaintext ${n} to a non-loopback host; use ${n==="ws:"?"wss:":"https:"}, or set "allowPrivateNetwork": true for a server on your own network`);let u;try{u=await Cyn(i)}catch(c){throw new Error(`${Rc(t)}: host "${i}" could not be resolved (${c instanceof Error?c.message:String(c)})`,{cause:c})}if(u.length===0)throw new Error(`${Rc(t)}: host "${i}" resolved to no addresses`);const l=u.map(c=>({address:c,cls:mue(c)}));if(!s){const c=l.find(d=>d.cls!=="public");if(c)throw new Error(`${Rc(t)}: host "${i}" resolves to ${c.address}, a ${c.cls} address; set "allowPrivateNetwork": true on this server if that is intended`);return}if(!o&&l.some(c=>c.cls==="public"))throw new Error(`${Rc(t)}: "${e}" uses plaintext ${n} to a host that resolves to a public address; allowPrivateNetwork only permits plaintext to private addresses`)}var Per,Der,k6,xa,Oer=S({"src/lib/mcp/transportUrlPolicy.ts"(){"use strict";fyt(),Bte(),Per=new Set(["http:","ws:"]),Der=new Set(["https:","wss:"]),k6=new Fte,k6.addSubnet("127.0.0.0",8,"ipv4"),k6.addAddress("::1","ipv6"),xa=new Fte,xa.addSubnet("0.0.0.0",8,"ipv4"),xa.addSubnet("10.0.0.0",8,"ipv4"),xa.addSubnet("100.64.0.0",10,"ipv4"),xa.addSubnet("169.254.0.0",16,"ipv4"),xa.addSubnet("172.16.0.0",12,"ipv4"),xa.addSubnet("192.0.0.0",24,"ipv4"),xa.addSubnet("192.168.0.0",16,"ipv4"),xa.addSubnet("198.18.0.0",15,"ipv4"),xa.addSubnet("224.0.0.0",4,"ipv4"),xa.addSubnet("240.0.0.0",4,"ipv4"),xa.addAddress("::","ipv6"),xa.addSubnet("fc00::",7,"ipv6"),xa.addSubnet("fe80::",10,"ipv6")}}),xyn=S({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/mini/parse.js"(){Ba()}}),Iyn=S({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/mini/schemas.js"(){}}),Ryn=S({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/mini/checks.js"(){}}),Myn=S({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/mini/iso.js"(){}}),Pyn=S({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/mini/coerce.js"(){}}),Dyn=S({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/mini/external.js"(){Ba(),xyn(),Iyn(),Ryn(),vq(),Myn(),Pyn()}}),Oyn=S({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4-mini/index.js"(){Dyn()}});function hue(e){return!!e._zod}function mf(e,t){return hue(e)?Uz(e,t):e.safeParse(t)}function Ner(e){if(!e)return;let t;if(hue(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function Ler(e){if(hue(e)){const i=e._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}const r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}const n=e.value;if(n!==void 0)return n}var fue=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js"(){Oyn()}}),Nyn=S({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/index.js"(){GV()}}),$er=S({"node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/index.js"(){Nyn()}}),_1,Fer,hf,E1,Gi,gue,yue,Lyn,Uer,Ber,A6,uu,$T,zer,Is,Xu,Yu,Rs,S1,vue,C6,wue,Ger,x6,FT,jt,I6,qer,yy,$yn,vy,jer,R6,Ver,UT,wy,bue,Her,Wer,Ker,Jer,Xer,Yer,Zer,Qer,Tue,_ue,etr,M6,ttr,rtr,P6,ntr,BT,zT,otr,GT,qT,itr,k1,D6,O6,N6,Fyn,L6,$6,F6,str,Eue,Sue,U6,kue,jT,by,Aue,atr,utr,Cue,ltr,xue,B6,ctr,dtr,Iue,Rue,ptr,mtr,htr,ftr,gtr,ytr,vtr,wtr,btr,Mue,Ttr,_tr,z6,G6,q6,Etr,Str,ktr,j6,Atr,Pue,Due,Ctr,xtr,Oue,Itr,Nue,A1,Uyn,Rtr,Mtr,Lue,Ptr,$ue,Dtr,Otr,Ntr,Ltr,$tr,Ftr,Utr,Btr,ztr,C1,Gtr,qtr,Fue,Uue,Bue,jtr,Vtr,Htr,Wtr,Ktr,Jtr,Xtr,Ytr,Ztr,Qtr,err,trr,rrr,nrr,orr,zue,irr,srr,Gue,arr,urr,lrr,crr,que,drr,prr,mrr,hrr,Byn,zyn,Gyn,qyn,jyn,Vyn,Ft,frr,ff=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js"(){$er(),_1="2025-11-25",Fer=[_1,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],hf="io.modelcontextprotocol/related-task",E1="2.0",Gi=IV(e=>e!==null&&(typeof e=="object"||typeof e=="function")),gue=vn([ie(),Br().int()]),yue=ie(),Lyn=ts({ttl:Br().optional(),pollInterval:Br().optional()}),Uer=it({ttl:Br().optional()}),Ber=it({taskId:ie()}),A6=ts({progressToken:gue.optional(),[hf]:Ber.optional()}),uu=it({_meta:A6.optional()}),$T=uu.extend({task:Uer.optional()}),zer=e=>$T.safeParse(e).success,Is=it({method:ie(),params:uu.loose().optional()}),Xu=it({_meta:A6.optional()}),Yu=it({method:ie(),params:Xu.loose().optional()}),Rs=ts({_meta:A6.optional()}),S1=vn([ie(),Br().int()]),vue=it({jsonrpc:Et(E1),id:S1,...Is.shape}).strict(),C6=e=>vue.safeParse(e).success,wue=it({jsonrpc:Et(E1),...Yu.shape}).strict(),Ger=e=>wue.safeParse(e).success,x6=it({jsonrpc:Et(E1),id:S1,result:Rs}).strict(),FT=e=>x6.safeParse(e).success,(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(jt||(jt={})),I6=it({jsonrpc:Et(E1),id:S1.optional(),error:it({code:Br().int(),message:ie(),data:Cn().optional()})}).strict(),qer=e=>I6.safeParse(e).success,yy=vn([vue,wue,x6,I6]),$yn=vn([x6,I6]),vy=Rs.strict(),jer=Xu.extend({requestId:S1.optional(),reason:ie().optional()}),R6=Yu.extend({method:Et("notifications/cancelled"),params:jer}),Ver=it({src:ie(),mimeType:ie().optional(),sizes:Ze(ie()).optional(),theme:Qs(["light","dark"]).optional()}),UT=it({icons:Ze(Ver).optional()}),wy=it({name:ie(),title:ie().optional()}),bue=wy.extend({...wy.shape,...UT.shape,version:ie(),websiteUrl:ie().optional(),description:ie().optional()}),Her=ok(it({applyDefaults:yn().optional()}),wn(ie(),Cn())),Wer=f2(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,ok(it({form:Her.optional(),url:Gi.optional()}),wn(ie(),Cn()).optional())),Ker=ts({list:Gi.optional(),cancel:Gi.optional(),requests:ts({sampling:ts({createMessage:Gi.optional()}).optional(),elicitation:ts({create:Gi.optional()}).optional()}).optional()}),Jer=ts({list:Gi.optional(),cancel:Gi.optional(),requests:ts({tools:ts({call:Gi.optional()}).optional()}).optional()}),Xer=it({experimental:wn(ie(),Gi).optional(),sampling:it({context:Gi.optional(),tools:Gi.optional()}).optional(),elicitation:Wer.optional(),roots:it({listChanged:yn().optional()}).optional(),tasks:Ker.optional(),extensions:wn(ie(),Gi).optional()}),Yer=uu.extend({protocolVersion:ie(),capabilities:Xer,clientInfo:bue}),Zer=Is.extend({method:Et("initialize"),params:Yer}),Qer=it({experimental:wn(ie(),Gi).optional(),logging:Gi.optional(),completions:Gi.optional(),prompts:it({listChanged:yn().optional()}).optional(),resources:it({subscribe:yn().optional(),listChanged:yn().optional()}).optional(),tools:it({listChanged:yn().optional()}).optional(),tasks:Jer.optional(),extensions:wn(ie(),Gi).optional()}),Tue=Rs.extend({protocolVersion:ie(),capabilities:Qer,serverInfo:bue,instructions:ie().optional()}),_ue=Yu.extend({method:Et("notifications/initialized"),params:Xu.optional()}),etr=e=>_ue.safeParse(e).success,M6=Is.extend({method:Et("ping"),params:uu.optional()}),ttr=it({progress:Br(),total:xn(Br()),message:xn(ie())}),rtr=it({...Xu.shape,...ttr.shape,progressToken:gue}),P6=Yu.extend({method:Et("notifications/progress"),params:rtr}),ntr=uu.extend({cursor:yue.optional()}),BT=Is.extend({params:ntr.optional()}),zT=Rs.extend({nextCursor:yue.optional()}),otr=Qs(["working","input_required","completed","failed","cancelled"]),GT=it({taskId:ie(),status:otr,ttl:vn([Br(),l2()]),createdAt:ie(),lastUpdatedAt:ie(),pollInterval:xn(Br()),statusMessage:xn(ie())}),qT=Rs.extend({task:GT}),itr=Xu.merge(GT),k1=Yu.extend({method:Et("notifications/tasks/status"),params:itr}),D6=Is.extend({method:Et("tasks/get"),params:uu.extend({taskId:ie()})}),O6=Rs.merge(GT),N6=Is.extend({method:Et("tasks/result"),params:uu.extend({taskId:ie()})}),Fyn=Rs.loose(),L6=BT.extend({method:Et("tasks/list")}),$6=zT.extend({tasks:Ze(GT)}),F6=Is.extend({method:Et("tasks/cancel"),params:uu.extend({taskId:ie()})}),str=Rs.merge(GT),Eue=it({uri:ie(),mimeType:xn(ie()),_meta:wn(ie(),Cn()).optional()}),Sue=Eue.extend({text:ie()}),U6=ie().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),kue=Eue.extend({blob:U6}),jT=Qs(["user","assistant"]),by=it({audience:Ze(jT).optional(),priority:Br().min(0).max(1).optional(),lastModified:J2.datetime({offset:!0}).optional()}),Aue=it({...wy.shape,...UT.shape,uri:ie(),description:xn(ie()),mimeType:xn(ie()),size:xn(Br()),annotations:by.optional(),_meta:xn(ts({}))}),atr=it({...wy.shape,...UT.shape,uriTemplate:ie(),description:xn(ie()),mimeType:xn(ie()),annotations:by.optional(),_meta:xn(ts({}))}),utr=BT.extend({method:Et("resources/list")}),Cue=zT.extend({resources:Ze(Aue)}),ltr=BT.extend({method:Et("resources/templates/list")}),xue=zT.extend({resourceTemplates:Ze(atr)}),B6=uu.extend({uri:ie()}),ctr=B6,dtr=Is.extend({method:Et("resources/read"),params:ctr}),Iue=Rs.extend({contents:Ze(vn([Sue,kue]))}),Rue=Yu.extend({method:Et("notifications/resources/list_changed"),params:Xu.optional()}),ptr=B6,mtr=Is.extend({method:Et("resources/subscribe"),params:ptr}),htr=B6,ftr=Is.extend({method:Et("resources/unsubscribe"),params:htr}),gtr=Xu.extend({uri:ie()}),ytr=Yu.extend({method:Et("notifications/resources/updated"),params:gtr}),vtr=it({name:ie(),description:xn(ie()),required:xn(yn())}),wtr=it({...wy.shape,...UT.shape,description:xn(ie()),arguments:xn(Ze(vtr)),_meta:xn(ts({}))}),btr=BT.extend({method:Et("prompts/list")}),Mue=zT.extend({prompts:Ze(wtr)}),Ttr=uu.extend({name:ie(),arguments:wn(ie(),ie()).optional()}),_tr=Is.extend({method:Et("prompts/get"),params:Ttr}),z6=it({type:Et("text"),text:ie(),annotations:by.optional(),_meta:wn(ie(),Cn()).optional()}),G6=it({type:Et("image"),data:U6,mimeType:ie(),annotations:by.optional(),_meta:wn(ie(),Cn()).optional()}),q6=it({type:Et("audio"),data:U6,mimeType:ie(),annotations:by.optional(),_meta:wn(ie(),Cn()).optional()}),Etr=it({type:Et("tool_use"),name:ie(),id:ie(),input:wn(ie(),Cn()),_meta:wn(ie(),Cn()).optional()}),Str=it({type:Et("resource"),resource:vn([Sue,kue]),annotations:by.optional(),_meta:wn(ie(),Cn()).optional()}),ktr=Aue.extend({type:Et("resource_link")}),j6=vn([z6,G6,q6,ktr,Str]),Atr=it({role:jT,content:j6}),Pue=Rs.extend({description:ie().optional(),messages:Ze(Atr)}),Due=Yu.extend({method:Et("notifications/prompts/list_changed"),params:Xu.optional()}),Ctr=it({title:ie().optional(),readOnlyHint:yn().optional(),destructiveHint:yn().optional(),idempotentHint:yn().optional(),openWorldHint:yn().optional()}),xtr=it({taskSupport:Qs(["required","optional","forbidden"]).optional()}),Oue=it({...wy.shape,...UT.shape,description:ie().optional(),inputSchema:it({type:Et("object"),properties:wn(ie(),Gi).optional(),required:Ze(ie()).optional()}).catchall(Cn()),outputSchema:it({type:Et("object"),properties:wn(ie(),Gi).optional(),required:Ze(ie()).optional()}).catchall(Cn()).optional(),annotations:Ctr.optional(),execution:xtr.optional(),_meta:wn(ie(),Cn()).optional()}),Itr=BT.extend({method:Et("tools/list")}),Nue=zT.extend({tools:Ze(Oue)}),A1=Rs.extend({content:Ze(j6).default([]),structuredContent:wn(ie(),Cn()).optional(),isError:yn().optional()}),Uyn=A1.or(Rs.extend({toolResult:Cn()})),Rtr=$T.extend({name:ie(),arguments:wn(ie(),Cn()).optional()}),Mtr=Is.extend({method:Et("tools/call"),params:Rtr}),Lue=Yu.extend({method:Et("notifications/tools/list_changed"),params:Xu.optional()}),Ptr=it({autoRefresh:yn().default(!0),debounceMs:Br().int().nonnegative().default(300)}),$ue=Qs(["debug","info","notice","warning","error","critical","alert","emergency"]),Dtr=uu.extend({level:$ue}),Otr=Is.extend({method:Et("logging/setLevel"),params:Dtr}),Ntr=Xu.extend({level:$ue,logger:ie().optional(),data:Cn()}),Ltr=Yu.extend({method:Et("notifications/message"),params:Ntr}),$tr=it({name:ie().optional()}),Ftr=it({hints:Ze($tr).optional(),costPriority:Br().min(0).max(1).optional(),speedPriority:Br().min(0).max(1).optional(),intelligencePriority:Br().min(0).max(1).optional()}),Utr=it({mode:Qs(["auto","required","none"]).optional()}),Btr=it({type:Et("tool_result"),toolUseId:ie().describe("The unique identifier for the corresponding tool call."),content:Ze(j6).default([]),structuredContent:it({}).loose().optional(),isError:yn().optional(),_meta:wn(ie(),Cn()).optional()}),ztr=d2("type",[z6,G6,q6]),C1=d2("type",[z6,G6,q6,Etr,Btr]),Gtr=it({role:jT,content:vn([C1,Ze(C1)]),_meta:wn(ie(),Cn()).optional()}),qtr=$T.extend({messages:Ze(Gtr),modelPreferences:Ftr.optional(),systemPrompt:ie().optional(),includeContext:Qs(["none","thisServer","allServers"]).optional(),temperature:Br().optional(),maxTokens:Br().int(),stopSequences:Ze(ie()).optional(),metadata:Gi.optional(),tools:Ze(Oue).optional(),toolChoice:Utr.optional()}),Fue=Is.extend({method:Et("sampling/createMessage"),params:qtr}),Uue=Rs.extend({model:ie(),stopReason:xn(Qs(["endTurn","stopSequence","maxTokens"]).or(ie())),role:jT,content:ztr}),Bue=Rs.extend({model:ie(),stopReason:xn(Qs(["endTurn","stopSequence","maxTokens","toolUse"]).or(ie())),role:jT,content:vn([C1,Ze(C1)])}),jtr=it({type:Et("boolean"),title:ie().optional(),description:ie().optional(),default:yn().optional()}),Vtr=it({type:Et("string"),title:ie().optional(),description:ie().optional(),minLength:Br().optional(),maxLength:Br().optional(),format:Qs(["email","uri","date","date-time"]).optional(),default:ie().optional()}),Htr=it({type:Qs(["number","integer"]),title:ie().optional(),description:ie().optional(),minimum:Br().optional(),maximum:Br().optional(),default:Br().optional()}),Wtr=it({type:Et("string"),title:ie().optional(),description:ie().optional(),enum:Ze(ie()),default:ie().optional()}),Ktr=it({type:Et("string"),title:ie().optional(),description:ie().optional(),oneOf:Ze(it({const:ie(),title:ie()})),default:ie().optional()}),Jtr=it({type:Et("string"),title:ie().optional(),description:ie().optional(),enum:Ze(ie()),enumNames:Ze(ie()).optional(),default:ie().optional()}),Xtr=vn([Wtr,Ktr]),Ytr=it({type:Et("array"),title:ie().optional(),description:ie().optional(),minItems:Br().optional(),maxItems:Br().optional(),items:it({type:Et("string"),enum:Ze(ie())}),default:Ze(ie()).optional()}),Ztr=it({type:Et("array"),title:ie().optional(),description:ie().optional(),minItems:Br().optional(),maxItems:Br().optional(),items:it({anyOf:Ze(it({const:ie(),title:ie()}))}),default:Ze(ie()).optional()}),Qtr=vn([Ytr,Ztr]),err=vn([Jtr,Xtr,Qtr]),trr=vn([err,jtr,Vtr,Htr]),rrr=$T.extend({mode:Et("form").optional(),message:ie(),requestedSchema:it({type:Et("object"),properties:wn(ie(),trr),required:Ze(ie()).optional()})}),nrr=$T.extend({mode:Et("url"),message:ie(),elicitationId:ie(),url:ie().url()}),orr=vn([rrr,nrr]),zue=Is.extend({method:Et("elicitation/create"),params:orr}),irr=Xu.extend({elicitationId:ie()}),srr=Yu.extend({method:Et("notifications/elicitation/complete"),params:irr}),Gue=Rs.extend({action:Qs(["accept","decline","cancel"]),content:f2(e=>e===null?void 0:e,wn(ie(),vn([ie(),Br(),yn(),Ze(ie())])).optional())}),arr=it({type:Et("ref/resource"),uri:ie()}),urr=it({type:Et("ref/prompt"),name:ie()}),lrr=uu.extend({ref:vn([urr,arr]),argument:it({name:ie(),value:ie()}),context:it({arguments:wn(ie(),ie()).optional()}).optional()}),crr=Is.extend({method:Et("completion/complete"),params:lrr}),que=Rs.extend({completion:ts({values:Ze(ie()).max(100),total:xn(Br().int()),hasMore:xn(yn())})}),drr=it({uri:ie().startsWith("file://"),name:ie().optional(),_meta:wn(ie(),Cn()).optional()}),prr=Is.extend({method:Et("roots/list"),params:uu.optional()}),mrr=Rs.extend({roots:Ze(drr)}),hrr=Yu.extend({method:Et("notifications/roots/list_changed"),params:Xu.optional()}),Byn=vn([M6,Zer,crr,Otr,_tr,btr,utr,ltr,dtr,mtr,ftr,Mtr,Itr,D6,N6,L6,F6]),zyn=vn([R6,P6,_ue,hrr,k1]),Gyn=vn([vy,Uue,Bue,Gue,mrr,O6,$6,qT]),qyn=vn([M6,Fue,zue,prr,D6,N6,L6,F6]),jyn=vn([R6,P6,Ltr,ytr,Rue,Lue,Due,k1,srr]),Vyn=vn([vy,Tue,que,Pue,Mue,Cue,xue,Iue,A1,Nue,O6,$6,qT]),Ft=class X5r extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===jt.UrlElicitationRequired&&n){const o=n;if(o.elicitations)return new frr(o.elicitations,r)}return new X5r(t,r,n)}},frr=class extends Ft{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(jt.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}}});function Ty(e){return e==="completed"||e==="failed"||e==="cancelled"}var Hyn=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js"(){}});function grr(e){const r=Ner(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=Ler(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function yrr(e,t){const r=mf(e,t);if(!r.success)throw r.error;return r.data}var Wyn=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js"(){fue(),MH()}});function vrr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Kyn(e,t){const r={...e};for(const n in t){const o=n,i=t[o];if(i===void 0)continue;const s=r[o];vrr(s)&&vrr(i)?r[o]={...s,...i}:r[o]=i}return r}var wrr,brr,Jyn=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js"(){fue(),ff(),Hyn(),Wyn(),wrr=6e4,brr=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(R6,t=>{this._oncancel(t)}),this.setNotificationHandler(P6,t=>{this._onprogress(t)}),this.setRequestHandler(M6,t=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(D6,async(t,r)=>{const n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new Ft(jt.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(N6,async(t,r)=>{const n=async()=>{const o=t.params.taskId;if(!await this._taskStore.getTask(o,r.sessionId))throw new Ft(jt.InvalidParams,`Task not found: ${o}`);if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(o,r.sessionId);){if(s.type==="response"||s.type==="error"){const a=s.message,u=a.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),s.type==="response")l(a);else{const c=a,d=new Ft(c.error.code,c.error.message,c.error.data);l(d)}else{const c=s.type==="response"?"Response":"Error";this._onerror(new Error(`${c} handler missing for request ${u}`))}continue}await this._transport?.send(s.message,{relatedRequestId:r.requestId})}}const i=await this._taskStore.getTask(o,r.sessionId);if(!i)throw new Ft(jt.InvalidParams,`Task not found: ${o}`);if(!Ty(i.status))return await this._waitForTaskUpdate(o,r.signal,r.sessionId),await n();if(Ty(i.status)){const s=await this._taskStore.getTaskResult(o,r.sessionId);return this._clearTaskQueue(o,r.sessionId),{...s,_meta:{...s._meta,[hf]:{taskId:o}}}}return await n()};return await n()}),this.setRequestHandler(L6,async(t,r)=>{try{const{tasks:n,nextCursor:o}=await this._taskStore.listTasks(t.params?.cursor,r.sessionId);return{tasks:n,nextCursor:o,_meta:{}}}catch(n){throw new Ft(jt.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(F6,async(t,r)=>{try{const n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new Ft(jt.InvalidParams,`Task not found: ${t.params.taskId}`);if(Ty(n.status))throw new Ft(jt.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(t.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(t.params.taskId,r.sessionId);const o=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!o)throw new Ft(jt.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...o}}catch(n){throw n instanceof Ft?n:new Ft(jt.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,n,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:o,onTimeout:n})}_resetTimeout(e){const t=this._timeoutInfo.get(e);if(!t)return!1;const r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),Ft.fromError(jt.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){const t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;const t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};const r=this.transport?.onerror;this._transport.onerror=o=>{r?.(o),this._onerror(o)};const n=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{n?.(o,i),FT(o)||qer(o)?this._onresponse(o):C6(o)?this._onrequest(o,i):Ger(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(const r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();const t=Ft.fromError(jt.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const r of e.values())r(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){const t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(r=>this._onerror(new Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,t){const r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,n=this._transport,o=e.params?._meta?.[hf]?.taskId,i=n?.sessionId,s=this._taskStore;let a=!0,u;if(o&&s&&this._taskMessageQueue&&i!==void 0&&(a=!1,u=(async()=>{if(!await s.getTask(o,i))throw new Ft(jt.InvalidParams,`Task not found: ${o}`);a=!0})()),r===void 0){const m={jsonrpc:"2.0",id:e.id,error:{code:jt.MethodNotFound,message:"Method not found"}};if(o&&u){const h={type:"error",message:m,timestamp:Date.now()};u.then(()=>this._enqueueTaskMessage(o,h,i),()=>n?.send(m)).catch(g=>this._onerror(new Error(`Failed to send an error response: ${g}`)))}else o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:m,timestamp:Date.now()},n?.sessionId).catch(h=>this._onerror(new Error(`Failed to enqueue error response: ${h}`))):n?.send(m).catch(h=>this._onerror(new Error(`Failed to send an error response: ${h}`)));return}const l=new AbortController;this._requestHandlerAbortControllers.set(e.id,l);const c=zer(e.params)?e.params.task:void 0,d=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,p={signal:l.signal,sessionId:n?.sessionId,_meta:e.params?._meta,sendNotification:async m=>{if(l.signal.aborted)return;const h={relatedRequestId:e.id};o&&(h.relatedTask={taskId:o}),await this.notification(m,h)},sendRequest:async(m,h,g)=>{if(l.signal.aborted)throw new Ft(jt.ConnectionClosed,"Request was cancelled");const y={...g,relatedRequestId:e.id};o&&!y.relatedTask&&(y.relatedTask={taskId:o});const v=y.relatedTask?.taskId??o;return v&&d&&await d.updateTaskStatus(v,"input_required"),await this.request(m,h,y)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:o,taskStore:d,taskRequestedTtl:c?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};(u??Promise.resolve()).then(()=>{if(u&&l.signal.aborted)throw new Ft(jt.ConnectionClosed,"Request was cancelled");c&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,p)).then(async m=>{if(l.signal.aborted)return;const h={result:m,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:h,timestamp:Date.now()},n?.sessionId):await n?.send(h)},async m=>{if(l.signal.aborted)return;const h={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(m.code)?m.code:jt.InternalError,message:m.message??"Internal error",...m.data!==void 0&&{data:m.data}}};o&&this._taskMessageQueue&&a?await this._enqueueTaskMessage(o,{type:"error",message:h,timestamp:Date.now()},n?.sessionId):await n?.send(h)}).catch(m=>this._onerror(new Error(`Failed to send response: ${m}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===l&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:t,...r}=e.params,n=Number(t),o=this._progressHandlers.get(n);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}const i=this._responseHandlers.get(n),s=this._timeoutInfo.get(n);if(s&&i&&s.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(a){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),i(a);return}o(r)}_onresponse(e){const t=Number(e.id),r=this._requestResolvers.get(t);if(r){if(this._requestResolvers.delete(t),FT(e))r(e);else{const i=new Ft(e.error.code,e.error.message,e.error.data);r(i)}return}const n=this._responseHandlers.get(t);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let o=!1;if(FT(e)&&e.result&&typeof e.result=="object"){const i=e.result;if(i.task&&typeof i.task=="object"){const s=i.task;typeof s.taskId=="string"&&(o=!0,this._taskProgressTokens.set(s.taskId,t))}}if(o||this._progressHandlers.delete(t),FT(e))n(e);else{const i=Ft.fromError(e.error.code,e.error.message,e.error.data);n(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,r){const{task:n}=r??{};if(!n){try{yield{type:"result",result:await this.request(e,t,r)}}catch(i){yield{type:"error",error:i instanceof Ft?i:new Ft(jt.InternalError,String(i))}}return}let o;try{const i=await this.request(e,qT,r);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new Ft(jt.InternalError,"Task creation did not return a task");for(;;){const s=await this.getTask({taskId:o},r);if(yield{type:"taskStatus",task:s},Ty(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)}:s.status==="failed"?yield{type:"error",error:new Ft(jt.InternalError,`Task ${o} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new Ft(jt.InternalError,`Task ${o} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)};return}const a=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,a)),r?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof Ft?i:new Ft(jt.InternalError,String(i))}}}request(e,t,r){const{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i,task:s,relatedTask:a}=r??{};return new Promise((u,l)=>{const c=v=>{l(v)};if(!this._transport){c(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),s&&this.assertTaskCapability(e.method)}catch(v){c(v);return}r?.signal?.throwIfAborted();const d=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:d};r?.onprogress&&(this._progressHandlers.set(d,r.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),s&&(p.params={...p.params,task:s}),a&&(p.params={...p.params,_meta:{...p.params?._meta||{},[hf]:a}});const m=v=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String(v)}},{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i}).catch(T=>this._onerror(new Error(`Failed to send cancellation: ${T}`)));const w=v instanceof Ft?v:new Ft(jt.RequestTimeout,String(v));l(w)};this._responseHandlers.set(d,v=>{if(!r?.signal?.aborted){if(v instanceof Error)return l(v);try{const w=mf(t,v.result);w.success?u(w.data):l(w.error)}catch(w){l(w)}}}),r?.signal?.addEventListener("abort",()=>{m(r?.signal?.reason)});const h=r?.timeout??wrr,g=()=>m(Ft.fromError(jt.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(d,h,r?.maxTotalTimeout,g,r?.resetTimeoutOnProgress??!1);const y=a?.taskId;if(y){const v=w=>{const T=this._responseHandlers.get(d);T?T(w):this._onerror(new Error(`Response handler missing for side-channeled request ${d}`))};this._requestResolvers.set(d,v),this._enqueueTaskMessage(y,{type:"request",message:p,timestamp:Date.now()}).catch(w=>{this._cleanupTimeout(d),l(w)})}else this._transport.send(p,{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i}).catch(v=>{this._cleanupTimeout(d),l(v)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},O6,t)}async getTaskResult(e,t,r){return this.request({method:"tasks/result",params:e},t,r)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},$6,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},str,t)}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const r=t?.relatedTask?.taskId;if(r){const s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[hf]:t.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let s={...e,jsonrpc:"2.0"};t?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[hf]:t.relatedTask}}}),this._transport?.send(s,t).catch(a=>this._onerror(a))});return}let i={...e,jsonrpc:"2.0"};t?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[hf]:t.relatedTask}}}),await this._transport.send(i,t)}setRequestHandler(e,t){const r=grr(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(n,o)=>{const i=yrr(e,n);return Promise.resolve(t(i,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){const r=grr(e);this._notificationHandlers.set(r,n=>{const o=yrr(e,n);return Promise.resolve(t(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){const t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,r){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,r??this._transport?.sessionId,n)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){const r=await this._taskMessageQueue.dequeueAll(e,t);for(const n of r)if(n.type==="request"&&C6(n.message)){const o=n.message.id,i=this._requestResolvers.get(o);i?(i(new Ft(jt.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{const o=await this._taskStore?.getTask(e,r);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,i)=>{if(t.aborted){i(new Ft(jt.InvalidRequest,"Request cancelled"));return}const s=setTimeout(o,n);t.addEventListener("abort",()=>{clearTimeout(s),i(new Ft(jt.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){const r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async n=>{if(!e)throw new Error("No request provided");return await r.createTask(n,e.id,{method:e.method,params:e.params},t)},getTask:async n=>{const o=await r.getTask(n,t);if(!o)throw new Ft(jt.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(n,o,i)=>{await r.storeTaskResult(n,o,i,t);const s=await r.getTask(n,t);if(s){const a=k1.parse({method:"notifications/tasks/status",params:s});await this.notification(a),Ty(s.status)&&this._cleanupTaskProgressHandler(n)}},getTaskResult:n=>r.getTaskResult(n,t),updateTaskStatus:async(n,o,i)=>{const s=await r.getTask(n,t);if(!s)throw new Ft(jt.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(Ty(s.status))throw new Ft(jt.InvalidParams,`Cannot update task "${n}" from terminal status "${s.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(n,o,i,t);const a=await r.getTask(n,t);if(a){const u=k1.parse({method:"notifications/tasks/status",params:a});await this.notification(u),Ty(a.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>r.listTasks(n,t)}}}}}),_y,ms,Trr,Xyn,Yyn,Zyn,Qyn,evn,tvn,rvn,nvn,ovn,ivn,svn,avn,uvn,lvn,cvn,dvn,pvn,mvn,hvn,fvn,gvn,yvn,vvn,wvn,bvn,Tvn,_vn,Evn,Svn,kvn,Avn,Cvn,xvn,Ivn,Rvn,Mvn,Pvn,Dvn,Ovn,Nvn,Lvn,$vn,Fvn,Uvn,Bvn,zvn,Gvn=S({"npm-stub:ajv"(){_y={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:_y.get}):new Proxy(function(...r){return new Proxy({},{get:_y.get})},{get:_y.get,apply(r,n,o){return new Proxy({},{get:_y.get})},construct(r,n){return new Proxy({},{get:_y.get})}})}},ms=new Proxy({},_y),Trr=ms,{BedrockClient:Xyn,ListFoundationModelsCommand:Yyn,BedrockRuntimeClient:Zyn,ConverseCommand:Qyn,ConverseStreamCommand:evn,ImageFormat:tvn,InvokeModelCommand:rvn}=ms,{SageMakerRuntimeClient:nvn,InvokeEndpointCommand:ovn,InvokeEndpointWithResponseStreamCommand:ivn}=ms,{GoogleAuth:svn,VertexAI:avn,TextToSpeechClient:uvn}=ms,{Webhook:lvn}=ms,{Hippocampus:cvn,HippocampusConfig:dvn}=ms,{createClient:pvn}=ms,{Queue:mvn,Worker:hvn,Job:fvn,QueueScheduler:gvn,FlowProducer:yvn}=ms,{Cron:vvn}=ms,{parseBuffer:wvn,selectCover:bvn}=ms,{extractRawText:Tvn,convertToHtml:_vn}=ms,{Hono:Evn}=ms,{cors:Svn,HTTPException:kvn,logger:Avn,secureHeaders:Cvn,streamSSE:xvn,timeout:Ivn}=ms,Rvn=globalThis.fetch,Mvn=globalThis.Request,Pvn=globalThis.Response,Dvn=globalThis.Headers,Ovn=globalThis.FormData,Nvn=globalThis.File,Lvn=globalThis.Blob,$vn=ms.Agent,Fvn=ms.Pool,Uvn=ms.Client,Bvn=ms.Dispatcher,zvn=ms.MockAgent}}),Ey,hs,_rr,qvn,jvn,Vvn,Hvn,Wvn,Kvn,Jvn,Xvn,Yvn,Zvn,Qvn,ewn,twn,rwn,nwn,own,iwn,swn,awn,uwn,lwn,cwn,dwn,pwn,mwn,hwn,fwn,gwn,ywn,vwn,wwn,bwn,Twn,_wn,Ewn,Swn,kwn,Awn,Cwn,xwn,Iwn,Rwn,Mwn,Pwn,Dwn,Own,Nwn=S({"npm-stub:ajv-formats"(){Ey={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Ey.get}):new Proxy(function(...r){return new Proxy({},{get:Ey.get})},{get:Ey.get,apply(r,n,o){return new Proxy({},{get:Ey.get})},construct(r,n){return new Proxy({},{get:Ey.get})}})}},hs=new Proxy({},Ey),_rr=hs,{BedrockClient:qvn,ListFoundationModelsCommand:jvn,BedrockRuntimeClient:Vvn,ConverseCommand:Hvn,ConverseStreamCommand:Wvn,ImageFormat:Kvn,InvokeModelCommand:Jvn}=hs,{SageMakerRuntimeClient:Xvn,InvokeEndpointCommand:Yvn,InvokeEndpointWithResponseStreamCommand:Zvn}=hs,{GoogleAuth:Qvn,VertexAI:ewn,TextToSpeechClient:twn}=hs,{Webhook:rwn}=hs,{Hippocampus:nwn,HippocampusConfig:own}=hs,{createClient:iwn}=hs,{Queue:swn,Worker:awn,Job:uwn,QueueScheduler:lwn,FlowProducer:cwn}=hs,{Cron:dwn}=hs,{parseBuffer:pwn,selectCover:mwn}=hs,{extractRawText:hwn,convertToHtml:fwn}=hs,{Hono:gwn}=hs,{cors:ywn,HTTPException:vwn,logger:wwn,secureHeaders:bwn,streamSSE:Twn,timeout:_wn}=hs,Ewn=globalThis.fetch,Swn=globalThis.Request,kwn=globalThis.Response,Awn=globalThis.Headers,Cwn=globalThis.FormData,xwn=globalThis.File,Iwn=globalThis.Blob,Rwn=hs.Agent,Mwn=hs.Pool,Pwn=hs.Client,Dwn=hs.Dispatcher,Own=hs.MockAgent}});function Lwn(){const e=new Trr({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return _rr(e),e}var Err,$wn=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js"(){Gvn(),Nwn(),Err=class{constructor(e){this._ajv=e??Lwn()}getValidator(e){const t="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return r=>t(r)?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}}}}),Srr,Fwn=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js"(){ff(),Srr=class{constructor(e){this._client=e}async*callToolStream(e,t=A1,r){const n=this._client,o={...r,task:r?.task??(n.isToolTask(e.name)?{}:void 0)},i=n.requestStream({method:"tools/call",params:e},t,o),s=n.getToolOutputValidator(e.name);for await(const a of i){if(a.type==="result"&&s){const u=a.result;if(!u.structuredContent&&!u.isError){yield{type:"error",error:new Ft(jt.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(u.structuredContent)try{const l=s(u.structuredContent);if(!l.valid){yield{type:"error",error:new Ft(jt.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)};return}}catch(l){if(l instanceof Ft){yield{type:"error",error:l};return}yield{type:"error",error:new Ft(jt.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)};return}}yield a}}async getTask(e,t){return this._client.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._client.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._client.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._client.cancelTask({taskId:e},t)}requestStream(e,t,r){return this._client.requestStream(e,t,r)}}}});function Uwn(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function Bwn(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var zwn=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js"(){}}),krr={};ue(krr,{Client:()=>Crr,getSupportedElicitationModes:()=>Arr});function V6(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){const r=t,n=e.properties;for(const o of Object.keys(n)){const i=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(i,"default")&&(r[o]=i.default),r[o]!==void 0&&V6(i,r[o])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)typeof r!="boolean"&&V6(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)typeof r!="boolean"&&V6(r,t)}}function Arr(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};const t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}var Crr,Gwn=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js"(){Jyn(),ff(),$wn(),fue(),Fwn(),zwn(),Crr=class extends brr{constructor(e,t){super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=t?.capabilities??{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new Err,t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Lue,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Due,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Rue,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Srr(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Kyn(this._capabilities,e)}setRequestHandler(e,t){const n=Ner(e)?.method;if(!n)throw new Error("Schema is missing a method literal");const o=Ler(n);if(typeof o!="string")throw new Error("Schema method literal must be a string");const i=o;if(i==="elicitation/create"){const s=async(a,u)=>{const l=mf(zue,a);if(!l.success){const v=l.error instanceof Error?l.error.message:String(l.error);throw new Ft(jt.InvalidParams,`Invalid elicitation request: ${v}`)}const{params:c}=l.data;c.mode=c.mode??"form";const{supportsFormMode:d,supportsUrlMode:p}=Arr(this._capabilities.elicitation);if(c.mode==="form"&&!d)throw new Ft(jt.InvalidParams,"Client does not support form-mode elicitation requests");if(c.mode==="url"&&!p)throw new Ft(jt.InvalidParams,"Client does not support URL-mode elicitation requests");const m=await Promise.resolve(t(a,u));if(c.task){const v=mf(qT,m);if(!v.success){const w=v.error instanceof Error?v.error.message:String(v.error);throw new Ft(jt.InvalidParams,`Invalid task creation result: ${w}`)}return v.data}const h=mf(Gue,m);if(!h.success){const v=h.error instanceof Error?h.error.message:String(h.error);throw new Ft(jt.InvalidParams,`Invalid elicitation result: ${v}`)}const g=h.data,y=c.mode==="form"?c.requestedSchema:void 0;if(c.mode==="form"&&g.action==="accept"&&g.content&&y&&this._capabilities.elicitation?.form?.applyDefaults)try{V6(y,g.content)}catch{}return g};return super.setRequestHandler(e,s)}if(i==="sampling/createMessage"){const s=async(a,u)=>{const l=mf(Fue,a);if(!l.success){const g=l.error instanceof Error?l.error.message:String(l.error);throw new Ft(jt.InvalidParams,`Invalid sampling request: ${g}`)}const{params:c}=l.data,d=await Promise.resolve(t(a,u));if(c.task){const g=mf(qT,d);if(!g.success){const y=g.error instanceof Error?g.error.message:String(g.error);throw new Ft(jt.InvalidParams,`Invalid task creation result: ${y}`)}return g.data}const m=c.tools||c.toolChoice?Bue:Uue,h=mf(m,d);if(!h.success){const g=h.error instanceof Error?h.error.message:String(h.error);throw new Ft(jt.InvalidParams,`Invalid sampling result: ${g}`)}return h.data};return super.setRequestHandler(e,s)}return super.setRequestHandler(e,t)}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),e.sessionId===void 0)try{const r=await this.request({method:"initialize",params:{protocolVersion:_1,capabilities:this._capabilities,clientInfo:this._clientInfo}},Tue,t);if(r===void 0)throw new Error(`Server sent invalid initialize result: ${r}`);if(!Fer.includes(r.protocolVersion))throw new Error(`Server's protocol version is not supported: ${r.protocolVersion}`);this._serverCapabilities=r.capabilities,this._serverVersion=r.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(r.protocolVersion),this._instructions=r.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(r){throw this.close(),r}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break;case"ping":break}}assertTaskCapability(e){Uwn(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&Bwn(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},vy,e)}async complete(e,t){return this.request({method:"completion/complete",params:e},que,t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},vy,t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},Pue,t)}async listPrompts(e,t){return this.request({method:"prompts/list",params:e},Mue,t)}async listResources(e,t){return this.request({method:"resources/list",params:e},Cue,t)}async listResourceTemplates(e,t){return this.request({method:"resources/templates/list",params:e},xue,t)}async readResource(e,t){return this.request({method:"resources/read",params:e},Iue,t)}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},vy,t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},vy,t)}async callTool(e,t=A1,r){if(this.isToolTaskRequired(e.name))throw new Ft(jt.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const n=await this.request({method:"tools/call",params:e},t,r),o=this.getToolOutputValidator(e.name);if(o){if(!n.structuredContent&&!n.isError)throw new Ft(jt.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(n.structuredContent)try{const i=o(n.structuredContent);if(!i.valid)throw new Ft(jt.InvalidParams,`Structured content does not match the tool's output schema: ${i.errorMessage}`)}catch(i){throw i instanceof Ft?i:new Ft(jt.InvalidParams,`Failed to validate structured content: ${i instanceof Error?i.message:String(i)}`)}}return n}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const t of e){if(t.outputSchema){const n=this._jsonSchemaValidator.getValidator(t.outputSchema);this._cachedToolOutputValidators.set(t.name,n)}const r=t.execution?.taskSupport;(r==="required"||r==="optional")&&this._cachedKnownTaskTools.add(t.name),r==="required"&&this._cachedRequiredTaskTools.add(t.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){const r=await this.request({method:"tools/list",params:e},Nue,t);return this.cacheToolMetadata(r.tools),r}_setupListChangedHandler(e,t,r,n){const o=Ptr.safeParse(r);if(!o.success)throw new Error(`Invalid ${e} listChanged options: ${o.error.message}`);if(typeof r.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);const{autoRefresh:i,debounceMs:s}=o.data,{onChanged:a}=r,u=async()=>{if(!i){a(null,null);return}try{const c=await n();a(null,c)}catch(c){const d=c instanceof Error?c:new Error(String(c));a(d,null)}},l=()=>{if(s){const c=this._listChangedDebounceTimers.get(e);c&&clearTimeout(c);const d=setTimeout(u,s);this._listChangedDebounceTimers.set(e,d)}else u()};this.setNotificationHandler(t,l)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}}}),xrr={};ue(xrr,{Agent:()=>ynr,BedrockClient:()=>Rrr,BedrockRuntimeClient:()=>Prr,Blob:()=>gnr,Client:()=>wnr,ConverseCommand:()=>Drr,ConverseStreamCommand:()=>Orr,Cron:()=>Zrr,Dispatcher:()=>bnr,File:()=>fnr,FlowProducer:()=>Yrr,FormData:()=>hnr,GoogleAuth:()=>Brr,HTTPException:()=>inr,Headers:()=>mnr,Hippocampus:()=>jrr,HippocampusConfig:()=>Vrr,Hono:()=>nnr,ImageFormat:()=>Nrr,InvokeEndpointCommand:()=>Frr,InvokeEndpointWithResponseStreamCommand:()=>Urr,InvokeModelCommand:()=>Lrr,Job:()=>Jrr,ListFoundationModelsCommand:()=>Mrr,MockAgent:()=>Enr,Pool:()=>vnr,Queue:()=>Wrr,QueueScheduler:()=>Xrr,Request:()=>dnr,Response:()=>pnr,SageMakerRuntimeClient:()=>$rr,TextToSpeechClient:()=>Grr,VertexAI:()=>zrr,Webhook:()=>qrr,Worker:()=>Krr,convertToHtml:()=>rnr,cors:()=>onr,createClient:()=>Hrr,default:()=>Irr,extractRawText:()=>tnr,fetch:()=>cnr,getGlobalDispatcher:()=>_nr,interceptors:()=>Snr,logger:()=>snr,parseBuffer:()=>Qrr,request:()=>knr,secureHeaders:()=>anr,selectCover:()=>enr,setGlobalDispatcher:()=>Tnr,streamSSE:()=>unr,timeout:()=>lnr});var Sy,qi,Irr,Rrr,Mrr,Prr,Drr,Orr,Nrr,Lrr,$rr,Frr,Urr,Brr,zrr,Grr,qrr,jrr,Vrr,Hrr,Wrr,Krr,Jrr,Xrr,Yrr,Zrr,Qrr,enr,tnr,rnr,nnr,onr,inr,snr,anr,unr,lnr,cnr,dnr,pnr,mnr,hnr,fnr,gnr,ynr,vnr,wnr,bnr,Tnr,_nr,Enr,Snr,knr,qwn=S({"npm-stub:which"(){Sy={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Sy.get}):new Proxy(function(...r){return new Proxy({},{get:Sy.get})},{get:Sy.get,apply(r,n,o){return new Proxy({},{get:Sy.get})},construct(r,n){return new Proxy({},{get:Sy.get})}})}},qi=new Proxy({},Sy),Irr=qi,{BedrockClient:Rrr,ListFoundationModelsCommand:Mrr,BedrockRuntimeClient:Prr,ConverseCommand:Drr,ConverseStreamCommand:Orr,ImageFormat:Nrr,InvokeModelCommand:Lrr}=qi,{SageMakerRuntimeClient:$rr,InvokeEndpointCommand:Frr,InvokeEndpointWithResponseStreamCommand:Urr}=qi,{GoogleAuth:Brr,VertexAI:zrr,TextToSpeechClient:Grr}=qi,{Webhook:qrr}=qi,{Hippocampus:jrr,HippocampusConfig:Vrr}=qi,{createClient:Hrr}=qi,{Queue:Wrr,Worker:Krr,Job:Jrr,QueueScheduler:Xrr,FlowProducer:Yrr}=qi,{Cron:Zrr}=qi,{parseBuffer:Qrr,selectCover:enr}=qi,{extractRawText:tnr,convertToHtml:rnr}=qi,{Hono:nnr}=qi,{cors:onr,HTTPException:inr,logger:snr,secureHeaders:anr,streamSSE:unr,timeout:lnr}=qi,cnr=globalThis.fetch,dnr=globalThis.Request,pnr=globalThis.Response,mnr=globalThis.Headers,hnr=globalThis.FormData,fnr=globalThis.File,gnr=globalThis.Blob,ynr=qi.Agent,vnr=qi.Pool,wnr=qi.Client,bnr=qi.Dispatcher,Tnr=()=>{},_nr=()=>qi,Enr=qi.MockAgent,Snr={redirect:()=>e=>e,retry:()=>e=>e},knr=async(e,t)=>{const r=await globalThis.fetch(e,t);return{statusCode:r.status,headers:Object.fromEntries(r.headers.entries()),body:{text:()=>r.text(),json:()=>r.json(),arrayBuffer:()=>r.arrayBuffer()}}}}}),jwn=dn({"node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js"(e,t){"use strict";var r=(n={})=>{const o=n.env||process.env;return(n.platform||process.platform)!=="win32"?"PATH":Object.keys(o).reverse().find(s=>s.toUpperCase()==="PATH")||"Path"};t.exports=r,t.exports.default=r}}),Vwn=dn({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js"(e,t){"use strict";var r=(Sr(),fn(Xm)),n=(qwn(),fn(xrr)),o=jwn();function i(a,u){const l=a.options.env||process.env,c=process.cwd(),d=a.options.cwd!=null,p=d&&process.chdir!==void 0&&!process.chdir.disabled;if(p)try{process.chdir(a.options.cwd)}catch{}let m;try{m=n.sync(a.command,{path:l[o({env:l})],pathExt:u?r.delimiter:void 0})}catch{}finally{p&&process.chdir(c)}return m&&(m=r.resolve(d?a.options.cwd:"",m)),m}function s(a){return i(a)||i(a,!0)}t.exports=s}}),Hwn=dn({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/escape.js"(e,t){"use strict";var r=/([()\][%!^"`<>&|;, *?])/g;function n(i){return i=i.replace(r,"^$1"),i}function o(i,s){return i=`${i}`,i=i.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),i=i.replace(/(?=(\\+?)?)\1$/,"$1$1"),i=`"${i}"`,i=i.replace(r,"^$1"),s&&(i=i.replace(r,"^$1")),i}t.exports.command=n,t.exports.argument=o}}),Wwn=dn({"node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js"(e,t){"use strict";t.exports=/^#!(.*)/}}),Kwn=dn({"node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js"(e,t){"use strict";var r=Wwn();t.exports=(n="")=>{const o=n.match(r);if(!o)return null;const[i,s]=o[0].replace(/#! ?/,"").split(" "),a=i.split("/").pop();return a==="env"?s:s?`${a} ${s}`:a}}}),Jwn=dn({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js"(e,t){"use strict";var r=(ro(),fn(kd)),n=Kwn();function o(i){const a=Buffer.alloc(150);let u;try{u=r.openSync(i,"r"),r.readSync(u,a,0,150,0),r.closeSync(u)}catch{}return n(a.toString())}t.exports=o}}),Xwn=dn({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js"(e,t){"use strict";var r=(Sr(),fn(Xm)),n=Vwn(),o=Hwn(),i=Jwn(),s=process.platform==="win32",a=/\.(?:com|exe)$/i,u=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function l(p){p.file=n(p);const m=p.file&&i(p.file);return m?(p.args.unshift(p.file),p.command=m,n(p)):p.file}function c(p){if(!s)return p;const m=l(p),h=!a.test(m);if(p.options.forceShell||h){const g=u.test(m);p.command=r.normalize(p.command),p.command=o.command(p.command),p.args=p.args.map(v=>o.argument(v,g));const y=[p.command].concat(p.args).join(" ");p.args=["/d","/s","/c",`"${y}"`],p.command=process.env.comspec||"cmd.exe",p.options.windowsVerbatimArguments=!0}return p}function d(p,m,h){m&&!Array.isArray(m)&&(h=m,m=null),m=m?m.slice(0):[],h=Object.assign({},h);const g={command:p,args:m,options:h,file:void 0,original:{command:p,args:m}};return h.shell?g:c(g)}t.exports=d}}),Ywn=dn({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/enoent.js"(e,t){"use strict";var r=process.platform==="win32";function n(a,u){return Object.assign(new Error(`${u} ${a.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${u} ${a.command}`,path:a.command,spawnargs:a.args})}function o(a,u){if(!r)return;const l=a.emit;a.emit=function(c,d){if(c==="exit"){const p=i(d,u);if(p)return l.call(a,"error",p)}return l.apply(a,arguments)}}function i(a,u){return r&&a===1&&!u.file?n(u.original,"spawn"):null}function s(a,u){return r&&a===1&&!u.file?n(u.original,"spawnSync"):null}t.exports={hookChildProcess:o,verifyENOENT:i,verifyENOENTSync:s,notFoundError:n}}}),Zwn=dn({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/index.js"(e,t){"use strict";var r=(VBe(),fn(l5e)),n=Xwn(),o=Ywn();function i(a,u,l){const c=n(a,u,l),d=r.spawn(c.command,c.args,c.options);return o.hookChildProcess(d,c),d}function s(a,u,l){const c=n(a,u,l),d=r.spawnSync(c.command,c.args,c.options);return d.error=d.error||o.verifyENOENTSync(d.status,c),d}t.exports=i,t.exports.spawn=i,t.exports.sync=s,t.exports._parse=n,t.exports._enoent=o}}),H6,Qwn,ebn,tbn,rbn,W6,Anr,jue,nbn,obn,ibn,sbn,abn=S({"node-stub:node:process"(){H6={},Qwn=globalThis.crypto,ebn=globalThis.ReadableStream||class{},tbn=globalThis.URL,rbn=globalThis.URLSearchParams,W6=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},W6.custom=Symbol.for("nodejs.util.inspect.custom"),W6.colors={},W6.styles={},Anr=globalThis.TextDecoder,jue=globalThis.TextEncoder,nbn=globalThis.performance||{now:()=>Date.now()},obn=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),i=new Uint8Array(o.length);for(let s=0;s<o.length;s++)i[s]=o.charCodeAt(s);return i}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let i=0;i<t.length;i+=2)o[i/2]=parseInt(t.substr(i,2),16);return o}return new jue().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((i,s)=>i+s.length,0),n=new Uint8Array(r);let o=0;for(const i of t)n.set(i,o),o+=i.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new jue().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new Anr().decode(this)}},ibn=globalThis.clearTimeout,sbn=globalThis.clearInterval}}),ubn,Vue,Cnr,lbn,cbn,dbn,K6,xnr,Hue,pbn,mbn,hbn,fbn,Wue=S({"node-stub:node:stream"(){ubn=globalThis.crypto,Vue=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},Cnr=class{pipe(){return this}on(){return this}},lbn=globalThis.ReadableStream||class{},cbn=globalThis.URL,dbn=globalThis.URLSearchParams,K6=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},K6.custom=Symbol.for("nodejs.util.inspect.custom"),K6.colors={},K6.styles={},xnr=globalThis.TextDecoder,Hue=globalThis.TextEncoder,pbn=globalThis.performance||{now:()=>Date.now()},mbn=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),i=new Uint8Array(o.length);for(let s=0;s<o.length;s++)i[s]=o.charCodeAt(s);return i}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let i=0;i<t.length;i+=2)o[i/2]=parseInt(t.substr(i,2),16);return o}return new Hue().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((i,s)=>i+s.length,0),n=new Uint8Array(r);let o=0;for(const i of t)n.set(i,o),o+=i.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new Hue().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new xnr().decode(this)}},hbn=globalThis.clearTimeout,fbn=globalThis.clearInterval}});function gbn(e){return yy.parse(JSON.parse(e))}function ybn(e){return JSON.stringify(e)+`
1158
+ `}var Inr,Rnr,vbn=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js"(){ff(),Inr=10*1024*1024,Rnr=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??Inr}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;const e=this._buffer.indexOf(`
1159
+ `);if(e===-1)return null;const t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),gbn(t)}clear(){this._buffer=void 0}}}}),Kue={};ue(Kue,{DEFAULT_INHERITED_ENV_VARS:()=>Jue,StdioClientTransport:()=>Dnr,getDefaultEnvironment:()=>Mnr});function Mnr(){const e={};for(const t of Jue){const r=H6.env[t];r!==void 0&&(r.startsWith("()")||(e[t]=r))}return e}var Pnr,Jue,Dnr,Onr=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"(){Pnr=ml(Zwn(),1),abn(),Wue(),vbn(),Jue=H6.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"],Dnr=class{constructor(e){this._stderrStream=null,this._serverParams=e,this._readBuffer=new Rnr({maxBufferSize:e.maxBufferSize}),(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new Cnr)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,t)=>{this._process=(0,Pnr.default)(this._serverParams.command,this._serverParams.args??[],{env:{...Mnr(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:H6.platform==="win32",cwd:this._serverParams.cwd}),this._process.on("error",r=>{t(r),this.onerror?.(r)}),this._process.on("spawn",()=>{e()}),this._process.on("close",r=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",r=>{this.onerror?.(r)}),this._process.stdout?.on("data",r=>{try{this._readBuffer.append(r),this.processReadBuffer()}catch(n){this.onerror?.(n),this.close().catch(()=>{})}}),this._process.stdout?.on("error",r=>{this.onerror?.(r)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{const e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._process){const e=this._process;this._process=void 0;const t=new Promise(r=>{e.once("close",()=>{r()})});try{e.stdin?.end()}catch{}if(await Promise.race([t,new Promise(r=>setTimeout(r,2e3).unref())]),e.exitCode===null){try{e.kill("SIGTERM")}catch{}await Promise.race([t,new Promise(r=>setTimeout(r,2e3).unref())])}if(e.exitCode===null)try{e.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(e){return new Promise(t=>{if(!this._process?.stdin)throw new Error("Not connected");const r=ybn(e);this._process.stdin.write(r)?t():this._process.stdin.once("drain",t)})}}}});function Xue(e){}function Yue(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=Xue,onError:r=Xue,onRetry:n=Xue,onComment:o}=e,i=[];let s=!0,a,u="",l=0,c;function d(v){if(s&&(s=!1,v.charCodeAt(0)===239&&v.charCodeAt(1)===187&&v.charCodeAt(2)===191&&(v=v.slice(3))),i.length===0){const E=p(v);E!==""&&i.push(E);return}if(v.indexOf(`
1160
1160
  `)===-1&&v.indexOf("\r")===-1){i.push(v);return}i.push(v);const w=i.join("");i.length=0;const T=p(w);T!==""&&i.push(T)}function p(v){let w=0;if(v.indexOf("\r")===-1){let T=v.indexOf(`
1161
1161
  `,w);for(;T!==-1;){if(w===T){l>0&&t({id:a,event:c,data:u}),a=void 0,u="",l=0,c=void 0,w=T+1,T=v.indexOf(`
1162
1162
  `,w);continue}const E=v.charCodeAt(w);if(Nnr(v,w,E)){const k=v.charCodeAt(w+5)===gf?w+6:w+5,A=v.slice(k,T);if(l===0&&v.charCodeAt(T+1)===Que){t({id:a,event:c,data:A}),a=void 0,u="",c=void 0,w=T+2,T=v.indexOf(`
@@ -1165,7 +1165,7 @@ ${A}`,l++}else Lnr(v,w,E)?c=v.slice(v.charCodeAt(w+6)===gf?w+7:w+6,T)||void 0:m(
1165
1165
  `,w)}return v.slice(w)}for(;w<v.length;){const T=v.indexOf("\r",w),E=v.indexOf(`
1166
1166
  `,w);let k=-1;if(T!==-1&&E!==-1?k=T<E?T:E:T!==-1?T===v.length-1?k=-1:k=T:E!==-1&&(k=E),k===-1)break;m(v,w,k),w=k+1,v.charCodeAt(w-1)===$nr&&v.charCodeAt(w)===Que&&w++}return v.slice(w)}function m(v,w,T){if(w===T){g();return}const E=v.charCodeAt(w);if(Nnr(v,w,E)){const P=v.charCodeAt(w+5)===gf?w+6:w+5,D=v.slice(P,T);u=l===0?D:`${u}
1167
1167
  ${D}`,l++;return}if(Lnr(v,w,E)){c=v.slice(v.charCodeAt(w+6)===gf?w+7:w+6,T)||void 0;return}if(E===105&&v.charCodeAt(w+1)===100&&v.charCodeAt(w+2)===58){const P=v.slice(v.charCodeAt(w+3)===gf?w+4:w+3,T);a=P.includes("\0")?void 0:P;return}if(E===58){if(o){const P=v.slice(w,T);o(P.slice(v.charCodeAt(w+1)===gf?2:1))}return}const k=v.slice(w,T),A=k.indexOf(":");if(A===-1){h(k,"",k);return}const C=k.slice(0,A),R=k.charCodeAt(A+1)===gf?2:1,x=k.slice(A+R);h(C,x,k)}function h(v,w,T){switch(v){case"event":c=w||void 0;break;case"data":u=l===0?w:`${u}
1168
- ${w}`,l++;break;case"id":a=w.includes("\0")?void 0:w;break;case"retry":/^\d+$/.test(w)?n(parseInt(w,10)):r(new Zue(`Invalid \`retry\` value: "${w}"`,{type:"invalid-retry",value:w,line:T}));break;default:r(new Zue(`Unknown field "${v.length>20?`${v.slice(0,20)}\u2026`:v}"`,{type:"unknown-field",field:v,value:w,line:T}));break}}function g(){l>0&&t({id:a,event:c,data:u}),a=void 0,u="",l=0,c=void 0}function y(v={}){if(v.consume&&i.length>0){const w=i.join("");m(w,0,w.length)}s=!0,a=void 0,u="",l=0,c=void 0,i.length=0}return{feed:d,reset:y}}function Nnr(e,t,r){return r===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function Lnr(e,t,r){return r===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}var Zue,Que,$nr,gf,ele=S({"node_modules/.pnpm/eventsource-parser@3.0.8/node_modules/eventsource-parser/dist/index.js"(){Zue=class extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}},Que=10,$nr=13,gf=32}});function wbn(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function tle(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(tle).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${tle(e.cause)}`:e.message:`${e}`}function Fnr(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}function bbn(){const e="document"in globalThis?globalThis.document:void 0;return e&&typeof e=="object"&&"baseURI"in e&&typeof e.baseURI=="string"?e.baseURI:void 0}var rle,nle,J6,_r,ji,Bo,np,lu,ky,VT,X6,Y6,x1,HT,I1,yf,WT,KT,JT,R1,Mc,ole,ile,sle,Unr,ale,ule,M1,lle,cle,P1,Tbn=S({"node_modules/.pnpm/eventsource@3.0.7/node_modules/eventsource/dist/index.js"(){ele(),rle=class extends Event{constructor(e,t){var r,n;super(e),this.code=(r=t?.code)!=null?r:void 0,this.message=(n=t?.message)!=null?n:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,t,r){return r(Fnr(this),t)}[Symbol.for("Deno.customInspect")](e,t){return e(Fnr(this),t)}},nle=e=>{throw TypeError(e)},J6=(e,t,r)=>t.has(e)||nle("Cannot "+r),_r=(e,t,r)=>(J6(e,t,"read from private field"),r?r.call(e):t.get(e)),ji=(e,t,r)=>t.has(e)?nle("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Bo=(e,t,r,n)=>(J6(e,t,"write to private field"),t.set(e,r),r),np=(e,t,r)=>(J6(e,t,"access private method"),r),P1=class extends EventTarget{constructor(e,t){var r,n;super(),ji(this,Mc),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,ji(this,lu),ji(this,ky),ji(this,VT),ji(this,X6),ji(this,Y6),ji(this,x1),ji(this,HT),ji(this,I1,null),ji(this,yf),ji(this,WT),ji(this,KT,null),ji(this,JT,null),ji(this,R1,null),ji(this,ile,async o=>{var i;_r(this,WT).reset();const{body:s,redirected:a,status:u,headers:l}=o;if(u===204){np(this,Mc,M1).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(a?Bo(this,VT,new URL(o.url)):Bo(this,VT,void 0),u!==200){np(this,Mc,M1).call(this,`Non-200 status code (${u})`,u);return}if(!(l.get("content-type")||"").startsWith("text/event-stream")){np(this,Mc,M1).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(_r(this,lu)===this.CLOSED)return;Bo(this,lu,this.OPEN);const c=new Event("open");if((i=_r(this,R1))==null||i.call(this,c),this.dispatchEvent(c),typeof s!="object"||!s||!("getReader"in s)){np(this,Mc,M1).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}const d=new TextDecoder,p=s.getReader();let m=!0;do{const{done:h,value:g}=await p.read();g&&_r(this,WT).feed(d.decode(g,{stream:!h})),h&&(m=!1,_r(this,WT).reset(),np(this,Mc,lle).call(this))}while(m)}),ji(this,sle,o=>{Bo(this,yf,void 0),!(o.name==="AbortError"||o.type==="aborted")&&np(this,Mc,lle).call(this,tle(o))}),ji(this,ale,o=>{typeof o.id=="string"&&Bo(this,I1,o.id);const i=new MessageEvent(o.event||"message",{data:o.data,origin:_r(this,VT)?_r(this,VT).origin:_r(this,ky).origin,lastEventId:o.id||""});_r(this,JT)&&(!o.event||o.event==="message")&&_r(this,JT).call(this,i),this.dispatchEvent(i)}),ji(this,ule,o=>{Bo(this,x1,o)}),ji(this,cle,()=>{Bo(this,HT,void 0),_r(this,lu)===this.CONNECTING&&np(this,Mc,ole).call(this)});try{if(e instanceof URL)Bo(this,ky,e);else if(typeof e=="string")Bo(this,ky,new URL(e,bbn()));else throw new Error("Invalid URL")}catch{throw wbn("An invalid or illegal string was specified")}Bo(this,WT,Yue({onEvent:_r(this,ale),onRetry:_r(this,ule)})),Bo(this,lu,this.CONNECTING),Bo(this,x1,3e3),Bo(this,Y6,(r=t?.fetch)!=null?r:globalThis.fetch),Bo(this,X6,(n=t?.withCredentials)!=null?n:!1),np(this,Mc,ole).call(this)}get readyState(){return _r(this,lu)}get url(){return _r(this,ky).href}get withCredentials(){return _r(this,X6)}get onerror(){return _r(this,KT)}set onerror(e){Bo(this,KT,e)}get onmessage(){return _r(this,JT)}set onmessage(e){Bo(this,JT,e)}get onopen(){return _r(this,R1)}set onopen(e){Bo(this,R1,e)}addEventListener(e,t,r){const n=t;super.addEventListener(e,n,r)}removeEventListener(e,t,r){const n=t;super.removeEventListener(e,n,r)}close(){_r(this,HT)&&clearTimeout(_r(this,HT)),_r(this,lu)!==this.CLOSED&&(_r(this,yf)&&_r(this,yf).abort(),Bo(this,lu,this.CLOSED),Bo(this,yf,void 0))}},lu=new WeakMap,ky=new WeakMap,VT=new WeakMap,X6=new WeakMap,Y6=new WeakMap,x1=new WeakMap,HT=new WeakMap,I1=new WeakMap,yf=new WeakMap,WT=new WeakMap,KT=new WeakMap,JT=new WeakMap,R1=new WeakMap,Mc=new WeakSet,ole=function(){Bo(this,lu,this.CONNECTING),Bo(this,yf,new AbortController),_r(this,Y6)(_r(this,ky),np(this,Mc,Unr).call(this)).then(_r(this,ile)).catch(_r(this,sle))},ile=new WeakMap,sle=new WeakMap,Unr=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",..._r(this,I1)?{"Last-Event-ID":_r(this,I1)}:void 0},cache:"no-store",signal:(e=_r(this,yf))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},ale=new WeakMap,ule=new WeakMap,M1=function(e,t){var r;_r(this,lu)!==this.CLOSED&&Bo(this,lu,this.CLOSED);const n=new rle("error",{code:t,message:e});(r=_r(this,KT))==null||r.call(this,n),this.dispatchEvent(n)},lle=function(e,t){var r;if(_r(this,lu)===this.CLOSED)return;Bo(this,lu,this.CONNECTING);const n=new rle("error",{code:t,message:e});(r=_r(this,KT))==null||r.call(this,n),this.dispatchEvent(n),Bo(this,HT,setTimeout(_r(this,cle),_r(this,x1)))},cle=new WeakMap,P1.CONNECTING=0,P1.OPEN=1,P1.CLOSED=2}});function Z6(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function Bnr(e=fetch,t){return t?async(r,n)=>{const o={...t,...n,headers:n?.headers?{...Z6(t.headers),...Z6(n.headers)}:t.headers};return e(r,o)}:e}function _bn(e,t){return e.protocol===t.protocol&&e.hostname===t.hostname&&e.port===t.port?!0:e.hostname===t.hostname&&e.protocol==="http:"&&e.port===""&&t.protocol==="https:"&&t.port===""}function znr(e,t){const r=qnr.includes(e.status)?e.headers.get("location"):null;try{return r?new URL(r,t):void 0}catch{return}}function dle(e,t,r,n,o=0){const i=znr(n,t),s=n.status===307||n.status===308||(r?.method??"GET").toUpperCase()==="GET";if(!i||o===Gnr||!s)return;const a=new URL(t);if(!((i.username||i.password)&&(i.username!==a.username||i.password!==a.password)||!_bn(a,i)))return Promise.resolve(n.body?.cancel()).then(()=>e(i,{...r,redirect:"manual"})).then(l=>dle(e,i,r,l,o+1)??l)}function Q6(e){const t=(r,n)=>(e??fetch)(r,n);return mle.add(t),t}function Ay(e=fetch){return mle.has(e)?e:(t,r)=>r?.redirect==="error"||r?.redirect==="manual"?e(t,r):Promise.resolve(e(t,{...r,redirect:"manual"})).then(n=>dle(e,t,r,n)??n)}function ple(e,t){if(e.type==="opaqueredirect")return"Redirect not followed: this runtime does not expose the redirect target";const r=e.url||t,n=znr(e,r);if(n)return n.username=n.password=n.search=n.hash="",n.protocol==="http:"&&new URL(r).protocol==="https:"?(n.protocol="https:",`Redirect to plain http not followed; try ${n.href} instead`):`Redirect to ${n.href} not followed`}var Gnr,qnr,mle,hle=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.1_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js"(){Gnr=5,qnr=[301,302,303,307,308],mle=new WeakSet}}),Cy,fs,jnr,Ebn,Sbn,kbn,Abn,Cbn,xbn,Ibn,Rbn,Mbn,Pbn,Dbn,Obn,Nbn,Lbn,$bn,Fbn,Ubn,Bbn,zbn,Gbn,qbn,jbn,Vbn,Hbn,Wbn,Kbn,Jbn,Xbn,Ybn,Zbn,Qbn,eTn,tTn,rTn,nTn,oTn,iTn,sTn,aTn,uTn,lTn,cTn,dTn,pTn,mTn,hTn,fTn=S({"npm-stub:pkce-challenge"(){Cy={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Cy.get}):new Proxy(function(...r){return new Proxy({},{get:Cy.get})},{get:Cy.get,apply(r,n,o){return new Proxy({},{get:Cy.get})},construct(r,n){return new Proxy({},{get:Cy.get})}})}},fs=new Proxy({},Cy),jnr=fs,{BedrockClient:Ebn,ListFoundationModelsCommand:Sbn,BedrockRuntimeClient:kbn,ConverseCommand:Abn,ConverseStreamCommand:Cbn,ImageFormat:xbn,InvokeModelCommand:Ibn}=fs,{SageMakerRuntimeClient:Rbn,InvokeEndpointCommand:Mbn,InvokeEndpointWithResponseStreamCommand:Pbn}=fs,{GoogleAuth:Dbn,VertexAI:Obn,TextToSpeechClient:Nbn}=fs,{Webhook:Lbn}=fs,{Hippocampus:$bn,HippocampusConfig:Fbn}=fs,{createClient:Ubn}=fs,{Queue:Bbn,Worker:zbn,Job:Gbn,QueueScheduler:qbn,FlowProducer:jbn}=fs,{Cron:Vbn}=fs,{parseBuffer:Hbn,selectCover:Wbn}=fs,{extractRawText:Kbn,convertToHtml:Jbn}=fs,{Hono:Xbn}=fs,{cors:Ybn,HTTPException:Zbn,logger:Qbn,secureHeaders:eTn,streamSSE:tTn,timeout:rTn}=fs,nTn=globalThis.fetch,oTn=globalThis.Request,iTn=globalThis.Response,sTn=globalThis.Headers,aTn=globalThis.FormData,uTn=globalThis.File,lTn=globalThis.Blob,cTn=fs.Agent,dTn=fs.Pool,pTn=fs.Client,mTn=fs.Dispatcher,hTn=fs.MockAgent}}),Ms,Vnr,fle,Hnr,Wnr,Knr,Jnr,gle,Xnr,Ynr,Znr,gTn,yTn,Qnr=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.1_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js"(){$er(),Ms=wV().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:NV.custom,message:"URL must be parseable",fatal:!0}),jM}).refine(e=>{const t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Vnr=ts({resource:ie().url(),authorization_servers:Ze(Ms).optional(),jwks_uri:ie().url().optional(),scopes_supported:Ze(ie()).optional(),bearer_methods_supported:Ze(ie()).optional(),resource_signing_alg_values_supported:Ze(ie()).optional(),resource_name:ie().optional(),resource_documentation:ie().optional(),resource_policy_uri:ie().url().optional(),resource_tos_uri:ie().url().optional(),tls_client_certificate_bound_access_tokens:yn().optional(),authorization_details_types_supported:Ze(ie()).optional(),dpop_signing_alg_values_supported:Ze(ie()).optional(),dpop_bound_access_tokens_required:yn().optional()}),fle=ts({issuer:ie(),authorization_endpoint:Ms,token_endpoint:Ms,registration_endpoint:Ms.optional(),scopes_supported:Ze(ie()).optional(),response_types_supported:Ze(ie()),response_modes_supported:Ze(ie()).optional(),grant_types_supported:Ze(ie()).optional(),token_endpoint_auth_methods_supported:Ze(ie()).optional(),token_endpoint_auth_signing_alg_values_supported:Ze(ie()).optional(),service_documentation:Ms.optional(),revocation_endpoint:Ms.optional(),revocation_endpoint_auth_methods_supported:Ze(ie()).optional(),revocation_endpoint_auth_signing_alg_values_supported:Ze(ie()).optional(),introspection_endpoint:ie().optional(),introspection_endpoint_auth_methods_supported:Ze(ie()).optional(),introspection_endpoint_auth_signing_alg_values_supported:Ze(ie()).optional(),code_challenge_methods_supported:Ze(ie()).optional(),client_id_metadata_document_supported:yn().optional()}),Hnr=ts({issuer:ie(),authorization_endpoint:Ms,token_endpoint:Ms,userinfo_endpoint:Ms.optional(),jwks_uri:Ms,registration_endpoint:Ms.optional(),scopes_supported:Ze(ie()).optional(),response_types_supported:Ze(ie()),response_modes_supported:Ze(ie()).optional(),grant_types_supported:Ze(ie()).optional(),acr_values_supported:Ze(ie()).optional(),subject_types_supported:Ze(ie()),id_token_signing_alg_values_supported:Ze(ie()),id_token_encryption_alg_values_supported:Ze(ie()).optional(),id_token_encryption_enc_values_supported:Ze(ie()).optional(),userinfo_signing_alg_values_supported:Ze(ie()).optional(),userinfo_encryption_alg_values_supported:Ze(ie()).optional(),userinfo_encryption_enc_values_supported:Ze(ie()).optional(),request_object_signing_alg_values_supported:Ze(ie()).optional(),request_object_encryption_alg_values_supported:Ze(ie()).optional(),request_object_encryption_enc_values_supported:Ze(ie()).optional(),token_endpoint_auth_methods_supported:Ze(ie()).optional(),token_endpoint_auth_signing_alg_values_supported:Ze(ie()).optional(),display_values_supported:Ze(ie()).optional(),claim_types_supported:Ze(ie()).optional(),claims_supported:Ze(ie()).optional(),service_documentation:ie().optional(),claims_locales_supported:Ze(ie()).optional(),ui_locales_supported:Ze(ie()).optional(),claims_parameter_supported:yn().optional(),request_parameter_supported:yn().optional(),request_uri_parameter_supported:yn().optional(),require_request_uri_registration:yn().optional(),op_policy_uri:Ms.optional(),op_tos_uri:Ms.optional(),client_id_metadata_document_supported:yn().optional()}),Wnr=it({...Hnr.shape,...fle.pick({code_challenge_methods_supported:!0}).shape}),Knr=it({access_token:ie(),id_token:ie().optional(),token_type:ie(),expires_in:zV.number().optional(),scope:ie().optional(),refresh_token:ie().optional(),issuer:ie().optional().catch(void 0)}).strip(),Jnr=it({error:ie(),error_description:ie().optional(),error_uri:ie().optional()}),gle=Ms.optional().or(Et("").transform(()=>{})),Xnr=it({redirect_uris:Ze(Ms),token_endpoint_auth_method:ie().optional(),grant_types:Ze(ie()).optional(),response_types:Ze(ie()).optional(),client_name:ie().optional(),client_uri:Ms.optional(),logo_uri:gle,scope:ie().optional(),contacts:Ze(ie()).optional(),tos_uri:gle,policy_uri:ie().optional(),jwks_uri:Ms.optional(),jwks:bV().optional(),software_id:ie().optional(),software_version:ie().optional(),software_statement:ie().optional()}).strip(),Ynr=it({client_id:ie(),client_secret:ie().optional(),client_id_issued_at:Br().optional(),client_secret_expires_at:Br().optional(),issuer:ie().optional().catch(void 0)}).strip(),Znr=Xnr.merge(Ynr),gTn=it({error:ie(),error_description:ie().optional()}).strip(),yTn=it({token:ie(),token_type_hint:ie().optional()}).strip()}});function vTn(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function wTn({requestedResource:e,configuredResource:t}){const r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",i=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(i)}var bTn=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.1_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js"(){}}),gs,e$,D1,O1,N1,t$,r$,n$,xy,o$,i$,s$,a$,u$,l$,L1,c$,d$,eor,TTn=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.1_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js"(){gs=class extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){const e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},e$=class extends gs{},e$.errorCode="invalid_request",D1=class extends gs{},D1.errorCode="invalid_client",O1=class extends gs{},O1.errorCode="invalid_grant",N1=class extends gs{},N1.errorCode="unauthorized_client",t$=class extends gs{},t$.errorCode="unsupported_grant_type",r$=class extends gs{},r$.errorCode="invalid_scope",n$=class extends gs{},n$.errorCode="access_denied",xy=class extends gs{},xy.errorCode="server_error",o$=class extends gs{},o$.errorCode="temporarily_unavailable",i$=class extends gs{},i$.errorCode="unsupported_response_type",s$=class extends gs{},s$.errorCode="unsupported_token_type",a$=class extends gs{},a$.errorCode="invalid_token",u$=class extends gs{},u$.errorCode="method_not_allowed",l$=class extends gs{},l$.errorCode="too_many_requests",L1=class extends gs{},L1.errorCode="invalid_client_metadata",c$=class extends gs{},c$.errorCode="insufficient_scope",d$=class extends gs{},d$.errorCode="invalid_target",eor={[e$.errorCode]:e$,[D1.errorCode]:D1,[O1.errorCode]:O1,[N1.errorCode]:N1,[t$.errorCode]:t$,[r$.errorCode]:r$,[n$.errorCode]:n$,[xy.errorCode]:xy,[o$.errorCode]:o$,[i$.errorCode]:i$,[s$.errorCode]:s$,[a$.errorCode]:a$,[u$.errorCode]:u$,[l$.errorCode]:l$,[L1.errorCode]:L1,[c$.errorCode]:c$,[d$.errorCode]:d$}}});function _Tn(e){return["client_secret_basic","client_secret_post","none"].includes(e)}function ETn(e,t){const r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&_Tn(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?r?"client_secret_basic":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function STn(e,t,r,n){const{client_id:o,client_secret:i}=t;switch(e){case"client_secret_basic":kTn(o,i,r);return;case"client_secret_post":ATn(o,i,n);return;case"none":CTn(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function kTn(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}function ATn(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function CTn(e,t){t.set("client_id",e)}async function tor(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=Jnr.parse(JSON.parse(r)),{error:o,error_description:i,error_uri:s}=n,a=eor[o]||xy;return new a(i||"",s)}catch(n){const o=e instanceof Response?ple(e,e.url):void 0,i=`${t?`HTTP ${t}: `:""}${o??`Invalid OAuth error response: ${n}. Raw body: ${r}`}`;return new xy(i)}}function xTn(e,t){let[r,n]=[e,t];try{[r,n]=[new URL(e).href,new URL(t).href]}catch{}return r===n||r.endsWith("/")&&r.slice(0,-1)===n||n.endsWith("/")&&n.slice(0,-1)===r}function yle(e,t){if(e)return typeof e.issuer!="string"?e.issuer==null?e:{...e,issuer:void 0}:xTn(e.issuer,t)?e:void 0}function ror(e,t){return new Error(`OAuth client information is bound to authorization server ${e.issuer} and is not presented to ${t}. Clear the stored client information, or correct \`expectedIssuer\`, if the authorization server has moved.`)}async function Iy(e,t){try{return await vle(e,t)}catch(r){if(r instanceof D1||r instanceof N1)return await e.invalidateCredentials?.("all"),await vle(e,t);if(r instanceof O1)return await e.invalidateCredentials?.("tokens"),await vle(e,t);throw r}}async function vle(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:i}){const s=await e.discoveryState?.();let a,u,l,c=o;if(!c&&s?.resourceMetadataUrl&&(c=new URL(s.resourceMetadataUrl)),s?.authorizationServerUrl){if(u=s.authorizationServerUrl,a=s.resourceMetadata,l=s.authorizationServerMetadata??await ior(u,{fetchFn:i}),!a)try{a=await nor(t,{resourceMetadataUrl:c},i)}catch{}(l!==s.authorizationServerMetadata||a!==s.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:c?.toString(),resourceMetadata:a,authorizationServerMetadata:l})}else{const x=await NTn(t,{resourceMetadataUrl:c,fetchFn:i});u=x.authorizationServerUrl,l=x.authorizationServerMetadata,a=x.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:c?.toString(),resourceMetadata:a,authorizationServerMetadata:l})}const d=String(u),p=await RTn(t,e,a),m=p&&a&&!e.validateResourceURL?a.resource:p,h=n||a?.scopes_supported?.join(" ")||e.clientMetadata.scope,g=await Promise.resolve(e.clientInformation());let y=yle(g,d);const v=e.saveClientInformation!==void 0&&!!e.redirectUrl;if(g&&!y&&!v)throw ror(g,d);const w=y?.issuer==null?y:void 0,T=async()=>{try{w&&await e.saveClientInformation?.({...w,issuer:d})}catch{}};if(!y){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const x=l?.client_id_metadata_document_supported===!0,P=e.clientMetadataUrl;if(P&&!ITn(P))throw new L1(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${P}`);if(x&&P)y={client_id:P,issuer:d},await e.saveClientInformation?.(y);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");y={...await BTn(u,{metadata:l,clientMetadata:e.clientMetadata,scope:h,fetchFn:i}),issuer:d},await e.saveClientInformation(y)}}const E=!e.redirectUrl;if(r!==void 0||E){const x=await UTn(e,u,{metadata:l,resource:m,authorizationCode:r,fetchFn:i});return await T(),await e.saveTokens({...x,issuer:d}),"AUTHORIZED"}const k=yle(await e.tokens(),d);if(k?.refresh_token&&k.issuer==null&&console.warn("[mcp-sdk] stored OAuth tokens have no 'issuer' property (saved by an earlier version, or by a provider that does not keep it) and are used as-is; make sure your OAuthClientProvider stores what saveTokens() and saveClientInformation() receive unchanged."),k?.refresh_token)try{const x=await FTn(u,{metadata:l,clientInformation:y,refreshToken:k.refresh_token,resource:m,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await T(),await e.saveTokens({...x,issuer:d}),"AUTHORIZED"}catch(x){if(!(!(x instanceof gs)||x instanceof xy))throw x}const A=e.state?await e.state():void 0,{authorizationUrl:C,codeVerifier:R}=await LTn(u,{metadata:l,clientInformation:y,state:A,redirectUrl:e.redirectUrl,scope:h,resource:m});return await e.saveCodeVerifier(R),await e.redirectToAuthorization(C),"REDIRECT"}function ITn(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function RTn(e,t,r){const n=vTn(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!wTn({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function p$(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const o=wle(e,"resource_metadata")||void 0;let i;if(o)try{i=new URL(o)}catch{}const s=wle(e,"scope")||void 0,a=wle(e,"error")||void 0;return{resourceMetadataUrl:i,scope:s,error:a}}function wle(e,t){const r=e.headers.get("WWW-Authenticate");if(!r)return null;const n=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),o=r.match(n);return o?o[1]||o[2]:null}async function nor(e,t,r=fetch){const n=await DTn(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.body?.cancel(),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return Vnr.parse(await n.json())}async function ble(e,t,r=fetch){try{return await Ay(r)(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?ble(e,void 0,r):void 0;throw n}}function MTn(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function oor(e,t,r=fetch){return await ble(e,{"MCP-Protocol-Version":t},r)}function PTn(e,t){return!e||!e.ok&&e.status<500&&t!=="/"}async function DTn(e,t,r,n){const o=new URL(e),i=n?.protocolVersion??_1;let s;if(n?.metadataUrl)s=new URL(n.metadataUrl);else{const u=MTn(t,o.pathname);s=new URL(u,n?.metadataServerUrl??o),s.search=o.search}let a=await oor(s,i,r);if(!n?.metadataUrl&&PTn(a,o.pathname)){const u=new URL(`/.well-known/${t}`,o);a=await oor(u,i,r)}return a}function OTn(e){const t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let o=t.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"}),n.push({url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}async function ior(e,{fetchFn:t=fetch,protocolVersion:r=_1}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},o=OTn(e);for(const{url:i,type:s}of o){const a=await ble(i,n,t);if(a){if(!a.ok){if(await a.body?.cancel(),a.status<500)continue;throw new Error(`HTTP ${a.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}return s==="oauth"?fle.parse(await a.json()):Wnr.parse(await a.json())}}}async function NTn(e,t){let r,n;try{r=await nor(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(n=r.authorization_servers[0])}catch{}n||(n=String(new URL("/",e)));const o=await ior(n,{fetchFn:t?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:o,resourceMetadata:r}}function sor(e){return typeof e=="string"?e:e.href}async function LTn(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:i,resource:s}){let a;if(t){if(a=new URL(t.authorization_endpoint),!t.response_types_supported.includes(m$))throw new Error(`Incompatible auth server: does not support response type ${m$}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(h$))throw new Error(`Incompatible auth server: does not support code challenge method ${h$}`)}else a=new URL("/authorize",e);const u=await jnr(),l=u.code_verifier,c=u.code_challenge;return a.searchParams.set("response_type",m$),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",c),a.searchParams.set("code_challenge_method",h$),a.searchParams.set("redirect_uri",String(n)),i&&a.searchParams.set("state",i),o&&a.searchParams.set("scope",o),o?.includes("offline_access")&&a.searchParams.append("prompt","consent"),s&&a.searchParams.set("resource",sor(s)),{authorizationUrl:a,codeVerifier:l}}function $Tn(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function aor(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:i,fetchFn:s}){const a=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(i&&r.set("resource",sor(i)),o)await o(u,r,a,t);else if(n){const c=t?.token_endpoint_auth_methods_supported??[],d=ETn(n,c);STn(d,n,u,r)}const l=await Ay(s??fetch)(a,{method:"POST",headers:u,body:r});if(!l.ok)throw await tor(l);return uor.parse(await l.json())}async function FTn(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:i,fetchFn:s}){const a=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),u=await aor(e,{metadata:t,tokenRequestParams:a,clientInformation:r,addClientAuthentication:i,resource:o,fetchFn:s});return{refresh_token:n,...u}}async function UTn(e,t,{metadata:r,resource:n,authorizationCode:o,fetchFn:i}={}){const s=async()=>{const c=await e.clientInformation(),d=yle(c,String(t));if(c&&!d)throw ror(c,String(t));return d};let a=await s();const u=e.clientMetadata.scope;let l;if(e.prepareTokenRequest&&(l=await e.prepareTokenRequest(u)),!l){if(!o)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");const c=await e.codeVerifier();l=$Tn(o,c,e.redirectUrl)}return a??(a=await s()),aor(t,{metadata:r,tokenRequestParams:l,clientInformation:a,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:i})}async function BTn(e,{metadata:t,clientMetadata:r,scope:n,fetchFn:o}){let i;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(t.registration_endpoint)}else i=new URL("/register",e);const s=await Ay(o??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...n!==void 0?{scope:n}:{}})});if(!s.ok)throw await tor(s);return lor.parse(await s.json())}var Ll,m$,h$,uor,lor,cor=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.1_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"(){fTn(),ff(),Qnr(),Qnr(),bTn(),TTn(),hle(),Ll=class extends Error{constructor(e){super(e??"Unauthorized")}},m$="code",h$="S256",uor=Knr.omit({issuer:!0}),lor=Znr.omit({issuer:!0})}}),dor={};ue(dor,{SSEClientTransport:()=>por,SseError:()=>Tle});var Tle,por,zTn=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.1_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"(){Tbn(),hle(),ff(),cor(),Tle=class extends Error{constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r}},por=class{constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=t?.eventSourceInit,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=Bnr(t?.fetch,t?.requestInit),this._followRedirects=t?.redirectPolicy==="follow",this._followRedirects&&(this._fetch=Q6(this._fetch),this._fetchWithInit=Q6(this._fetchWithInit))}_unfollowedRedirect(e,t){const r=ple(e,t);return r&&!this._followRedirects?`${r} (redirectPolicy: 'same-origin')`:r}async _authThenStart(){if(!this._authProvider)throw new Ll("No auth provider");let e;try{e=await Iy(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(t){throw this.onerror?.(t),t}if(e!=="AUTHORIZED")throw new Ll;return await this._startOrAuth()}async _commonHeaders(){const e={};if(this._authProvider){const r=await this._authProvider.tokens();r&&(e.Authorization=`Bearer ${r.access_token}`)}this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);const t=Z6(this._requestInit?.headers);return new Headers({...e,...t})}_startOrAuth(){const e=this?._eventSourceInit?.fetch??this._fetch??fetch,t=this._followRedirects?e:Ay(e);let r;return new Promise((n,o)=>{this._eventSource=new P1(this._url.href,{...this._eventSourceInit,fetch:async(i,s)=>{const a=await this._commonHeaders();a.set("Accept","text/event-stream");const u=await t(i,{...s,headers:a});if(r=this._unfollowedRedirect(u,i),u.status===401&&u.headers.has("www-authenticate")){const{resourceMetadataUrl:l,scope:c}=p$(u);this._resourceMetadataUrl=l,this._scope=c}return u}}),this._abortController=new AbortController,this._eventSource.onerror=i=>{if(i.code===401&&this._authProvider){this._authThenStart().then(n,o);return}const s=new Tle(i.code,r??i.message,i);o(s),this.onerror?.(s)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",i=>{const s=i;try{if(this._endpoint=new URL(s.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(a){o(a),this.onerror?.(a),this.close();return}n()}),this._eventSource.onmessage=i=>{const s=i;let a;try{a=yy.parse(JSON.parse(s.data))}catch(u){this.onerror?.(u);return}this.onmessage?.(a)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new Ll("No auth provider");if(await Iy(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Ll("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){if(!this._endpoint)throw new Error("Not connected");try{const t=await this._commonHeaders();t.set("content-type","application/json");const r={...this._requestInit,method:"POST",headers:t,body:JSON.stringify(e),signal:this._abortController?.signal},n=await Ay(this._fetch??fetch)(this._endpoint,r);if(!n.ok){const o=await n.text().catch(()=>null);if(n.status===401&&this._authProvider){const{resourceMetadataUrl:i,scope:s}=p$(n);if(this._resourceMetadataUrl=i,this._scope=s,await Iy(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Ll;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${n.status}): ${this._unfollowedRedirect(n,this._endpoint)??o}`)}await n.body?.cancel()}catch(t){throw this.onerror?.(t),t}}setProtocolVersion(e){this._protocolVersion=e}}}}),mor={};ue(mor,{WebSocketClientTransport:()=>gor});var hor,gor,GTn=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.1_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/websocket.js"(){ff(),hor="mcp",gor=class{constructor(e){this._url=e}start(){if(this._socket)throw new Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,t)=>{this._socket=new WebSocket(this._url,hor),this._socket.onerror=r=>{const n="error"in r?r.error:new Error(`WebSocket error: ${JSON.stringify(r)}`);t(n),this.onerror?.(n)},this._socket.onopen=()=>{e()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=r=>{let n;try{n=yy.parse(JSON.parse(r.data))}catch(o){this.onerror?.(o);return}this.onmessage?.(n)}})}async close(){this._socket?.close()}send(e){return new Promise((t,r)=>{if(!this._socket){r(new Error("Not connected"));return}this._socket?.send(JSON.stringify(e)),t()})}}}}),qTn=dn({"node_modules/.pnpm/content-type@1.0.5/node_modules/content-type/index.js"(e){"use strict";var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,r=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,n=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,o=/\\([\u000b\u0020-\u00ff])/g,i=/([\\"])/g,s=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.format=a,e.parse=u;function a(p){if(!p||typeof p!="object")throw new TypeError("argument obj is required");var m=p.parameters,h=p.type;if(!h||!s.test(h))throw new TypeError("invalid type");var g=h;if(m&&typeof m=="object")for(var y,v=Object.keys(m).sort(),w=0;w<v.length;w++){if(y=v[w],!n.test(y))throw new TypeError("invalid parameter name");g+="; "+y+"="+c(m[y])}return g}function u(p){if(!p)throw new TypeError("argument string is required");var m=typeof p=="object"?l(p):p;if(typeof m!="string")throw new TypeError("argument string is required to be a string");var h=m.indexOf(";"),g=h!==-1?m.slice(0,h).trim():m.trim();if(!s.test(g))throw new TypeError("invalid media type");var y=new d(g.toLowerCase());if(h!==-1){var v,w,T;for(t.lastIndex=h;w=t.exec(m);){if(w.index!==h)throw new TypeError("invalid parameter format");h+=w[0].length,v=w[1].toLowerCase(),T=w[2],T.charCodeAt(0)===34&&(T=T.slice(1,-1),T.indexOf("\\")!==-1&&(T=T.replace(o,"$1"))),y.parameters[v]=T}if(h!==m.length)throw new TypeError("invalid parameter format")}return y}function l(p){var m;if(typeof p.getHeader=="function"?m=p.getHeader("content-type"):typeof p.headers=="object"&&(m=p.headers&&p.headers["content-type"]),typeof m!="string")throw new TypeError("content-type header is missing from object");return m}function c(p){var m=String(p);if(n.test(m))return m;if(m.length>0&&!r.test(m))throw new TypeError("invalid parameter value");return'"'+m.replace(i,"\\$1")+'"'}function d(p){this.parameters=Object.create(null),this.type=p}}});function jTn(e){if(e)try{return yor.default.parse(e).type}catch{const t=(e.split(";",1)[0]??"").trim().toLowerCase();return t===""||e.slice(t.length).includes(",")?void 0:t}}var yor,VTn=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.1_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/mediaType.js"(){yor=ml(qTn(),1)}}),vor,HTn=S({"node_modules/.pnpm/eventsource-parser@3.0.8/node_modules/eventsource-parser/dist/stream.js"(){ele(),vor=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:r}={}){let n;super({start(o){n=Yue({onEvent:i=>{o.enqueue(i)},onError(i){e==="terminate"?o.error(i):typeof e=="function"&&e(i)},onRetry:t,onComment:r})},transform(o){n.feed(o)}})}}}}),wor={};ue(wor,{StreamableHTTPClientTransport:()=>Tor,StreamableHTTPError:()=>vf});var bor,vf,Tor,WTn=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.1_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js"(){VTn(),hle(),ff(),cor(),HTn(),bor={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},vf=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},Tor=class{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=Bnr(t?.fetch,t?.requestInit),this._followRedirects=t?.redirectPolicy==="follow",this._followRedirects&&(this._fetch=Q6(this._fetch),this._fetchWithInit=Q6(this._fetchWithInit)),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??bor}_unfollowedRedirect(e,t){const r=ple(e,t);return r&&!this._followRedirects?`${r} (redirectPolicy: 'same-origin')`:r}async _authThenStart(){if(!this._authProvider)throw new Ll("No auth provider");let e;try{e=await Iy(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(t){throw this.onerror?.(t),t}if(e!=="AUTHORIZED")throw new Ll;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){const e={};if(this._authProvider){const r=await this._authProvider.tokens();r&&(e.Authorization=`Bearer ${r.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);const t=Z6(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){const{resumptionToken:t}=e;try{const r=await this._commonHeaders();r.set("Accept","text/event-stream"),t&&r.set("last-event-id",t);const n=this._fetch??fetch,o={method:"GET",headers:r,signal:this._abortController?.signal};let i=await n(this._url,this._followRedirects?o:{...o,redirect:"manual"});const s=this._followRedirects?void 0:dle(n,this._url,o,i);if(s&&(i=await s),!i.ok){if(await i.body?.cancel(),i.status===401&&this._authProvider)return await this._authThenStart();if(i.status===405)return;throw new vf(i.status,`Failed to open SSE stream: ${this._unfollowedRedirect(i,this._url)??i.statusText}`)}this._handleSseStream(i.body,e,!0)}catch(r){throw this.onerror?.(r),r}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const t=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(r,e),n)}_scheduleReconnection(e,t=0){const r=this._reconnectionOptions.maxRetries;if(t>=r){this.onerror?.(new Error(`Maximum reconnection attempts (${r}) exceeded.`));return}const n=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(o=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(e,t+1)})},n)}_handleSseStream(e,t,r){if(!e)return;const{onresumptiontoken:n,replayMessageId:o}=t;let i,s=!1,a=!1;(async()=>{try{const l=e.pipeThrough(new TextDecoderStream).pipeThrough(new vor({onRetry:p=>{this._serverRetryMs=p}})).getReader();for(;;){const{value:p,done:m}=await l.read();if(m)break;if(p.id&&(i=p.id,s=!0,n?.(p.id)),!!p.data&&(!p.event||p.event==="message"))try{const h=yy.parse(JSON.parse(p.data));FT(h)&&(a=!0,o!==void 0&&(h.id=o)),this.onmessage?.(h)}catch(h){this.onerror?.(h)}}(r||s)&&!a&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:n,replayMessageId:o},0)}catch(l){if(this.onerror?.(new Error(`SSE stream disconnected: ${l}`)),(r||s)&&!a&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:n,replayMessageId:o},0)}catch(p){this.onerror?.(new Error(`Failed to reconnect: ${p instanceof Error?p.message:String(p)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Ll("No auth provider");if(await Iy(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Ll("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{const{resumptionToken:r,onresumptiontoken:n}=t||{};if(r){this._startOrAuthSse({resumptionToken:r,replayMessageId:C6(e)?e.id:void 0}).catch(p=>this.onerror?.(p));return}const o=await this._commonHeaders();o.set("content-type","application/json"),o.set("accept","application/json, text/event-stream");const i={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:this._abortController?.signal},s=await Ay(this._fetch??fetch)(this._url,i),a=s.headers.get("mcp-session-id");if(a&&(this._sessionId=a),!s.ok){const p=await s.text().catch(()=>null);if(s.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new vf(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:m,scope:h}=p$(s);if(this._resourceMetadataUrl=m,this._scope=h,await Iy(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Ll;return this._hasCompletedAuthFlow=!0,this.send(e)}if(s.status===403&&this._authProvider){const{resourceMetadataUrl:m,scope:h,error:g}=p$(s);if(g==="insufficient_scope"){const y=s.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===y)throw new vf(403,"Server returned 403 after trying upscoping");if(h&&(this._scope=h),m&&(this._resourceMetadataUrl=m),this._lastUpscopingHeader=y??void 0,await Iy(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Ll;return this.send(e)}}throw new vf(s.status,`Error POSTing to endpoint: ${this._unfollowedRedirect(s,this._url)??p}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,s.status===202){await s.body?.cancel(),etr(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(p=>this.onerror?.(p));return}const l=(Array.isArray(e)?e:[e]).filter(p=>"method"in p&&"id"in p&&p.id!==void 0).length>0,c=s.headers.get("content-type"),d=jTn(c);if(l)if(d==="text/event-stream")this._handleSseStream(s.body,{onresumptiontoken:n},!1);else if(d==="application/json"){const p=await s.json(),m=Array.isArray(p)?p.map(h=>yy.parse(h)):[yy.parse(p)];for(const h of m)this.onmessage?.(h)}else throw await s.body?.cancel(),new vf(-1,`Unexpected content type: ${c}`);else await s.body?.cancel()}catch(r){throw this.onerror?.(r),r}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{const e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},r=await Ay(this._fetch??fetch)(this._url,t);if(await r.body?.cancel(),!r.ok&&r.status!==405)throw new vf(r.status,`Failed to terminate session: ${this._unfollowedRedirect(r,this._url)??r.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}}}}),_or={};ue(_or,{MCPClientFactory:()=>wf,terminateLiveStdioServers:()=>y$});var Eor,_le,Sor,Ele,f$,g$,Sle,kle,Ale,y$,kor,Aor,wf,Cle=S({"src/lib/mcp/mcpClientFactory.ts"(){"use strict";z(),aue(),lt(),ker(),Aer(),Rer(),Oer(),oo(),S0(),Eor=Math.max(5e3,Number(process.env.MCP_CLIENT_TIMEOUT)||6e4),_le=20,Sor=class{lines=[];partial="";append(e){this.partial+=e.toString();const t=this.partial.split(/\r?\n/);this.partial=t.pop()??"";for(const r of t)r.trim().length!==0&&(this.lines.push(r),this.lines.length>_le&&this.lines.shift())}snapshot(){const e=[...this.lines];return this.partial.trim().length>0&&e.push(this.partial),e.slice(-_le)}},Ele=new WeakMap,f$=new Set,g$=new Set,Sle=!1,Ale=(e,t)=>{const r=Reflect.get(e,"_process");return r instanceof t?r:void 0},y$=()=>{for(const e of f$){const t=kle&&Ale(e,kle);try{t?t.kill("SIGTERM"):"pid"in e&&typeof e.pid=="number"&&process.kill(e.pid,"SIGTERM")}catch{}}for(const e of g$)try{e.kill("SIGKILL")}catch{}},kor=(e,t)=>{const r=Ale(e,t);if(!r||r.exitCode!==null||r.signalCode!==null)return;g$.add(r);const n=()=>{g$.delete(r)};r.once("exit",n),r.once("close",n)},Aor=(e,t)=>{Sle||(Sle=!0,process.on("exit",y$)),kle=t,f$.add(e),e.onclose=()=>{f$.delete(e)};const r=e.close.bind(e);e.close=async()=>{kor(e,t),await r()}},wf=class{static NEUROLINK_IMPLEMENTATION={name:"neurolink-sdk",version:"1.0.0"};static DEFAULT_CAPABILITIES={roots:{listChanged:!1}};static async createClient(e,t=Eor){const r=e.httpOptions?.connectionTimeout;r!==void 0&&(t=Math.min(t,r));const n=Date.now(),{traceId:o,parentSpanId:i}=E0(),s=Ie.createSpan("mcp.transport","mcp.connect",{"mcp.transport":e.transport,"mcp.operation":"connect","mcp.server_id":e.id},i,o);try{ae.info(`[MCPClientFactory] Creating client for ${e.id}`,{transport:e.transport,command:e.command,hasRetryConfig:!!e.retryConfig,hasRateLimiting:!!e.rateLimiting,hasAuth:!!e.auth}),(e.transport==="http"||e.transport==="sse")&&e.rateLimiting&&(await due.getLimiter(e.id,{requestsPerWindow:e.rateLimiting.requestsPerMinute??60,windowMs:6e4,maxBurst:e.rateLimiting.maxBurst??10,useTokenBucket:e.rateLimiting.useTokenBucket??!0,refillRate:(e.rateLimiting.requestsPerMinute??60)/60}).acquire(),ae.debug(`[MCPClientFactory] Rate limit token acquired for ${e.id}`));const a=T1.getBreaker(`mcp-client-${e.id}`,{failureThreshold:3,resetTimeout:3e4,operationTimeout:t}),u=async()=>await a.execute(async()=>await this.createClientInternal(e,t));let l;(e.transport==="http"||e.transport==="sse")&&e.retryConfig?(ae.debug(`[MCPClientFactory] Using retry logic for ${e.id}`,{maxAttempts:e.retryConfig.maxAttempts??rp.maxAttempts}),l=await Ser(u,{maxAttempts:e.retryConfig.maxAttempts??rp.maxAttempts,initialDelay:e.retryConfig.initialDelay??rp.initialDelay,maxDelay:e.retryConfig.maxDelay??rp.maxDelay,backoffMultiplier:e.retryConfig.backoffMultiplier??rp.backoffMultiplier})):l=await u(),ae.info(`[MCPClientFactory] Client created successfully for ${e.id}`,{duration:Date.now()-n,capabilities:l.capabilities}),s.durationMs=Date.now()-n;const c=Ie.endSpan(s,1);return nt().recordSpan(c),{...l,success:!0,duration:Date.now()-n}}catch(a){const u=a instanceof Error?a.message:String(a);if(a instanceof uh){ae.warn(`[MCPClientFactory] Client creation blocked by circuit breaker for ${e.id}`,{serverId:e.id,breakerState:a.breakerState,retryAfter:a.retryAfter,retryAfterMs:a.retryAfterMs,failureCount:a.failureCount}),s.durationMs=Date.now()-n;const c=Ie.endSpan(s,2);return c.statusMessage=`Circuit breaker open: ${u}`,nt().recordSpan(c),{success:!1,error:u,duration:Date.now()-n}}ae.debug(`[MCPClientFactory] Failed to create client for ${e.id}:`,a),s.durationMs=Date.now()-n;const l=Ie.endSpan(s,2);return l.statusMessage=u,nt().recordSpan(l),{success:!1,error:u,duration:Date.now()-n}}}static async createClientInternal(e,t){const n=(await this.createTransport(e)).transport;try{const{Client:o}=await Promise.resolve().then(()=>(Gwn(),krr)),i=new o(this.NEUROLINK_IMPLEMENTATION,{capabilities:this.DEFAULT_CAPABILITIES}),s=e.httpOptions?.requestTimeout;if(s!==void 0){const u=i.request.bind(i);i.request=(l,c,d)=>u(l,c,{...d,timeout:Math.min(s,d?.timeout??s),maxTotalTimeout:Math.min(s,d?.maxTotalTimeout??s)})}await this.raceWithTimeout(i.connect(n,{timeout:t}),t,`Client connection timeout for ${e.id}`);const a=await this.performHandshake(i,t);return ae.debug(`[MCPClientFactory] Handshake completed for ${e.id}`,{capabilities:a}),{client:i,transport:n,capabilities:a}}catch(o){try{await n.close()}catch(s){ae.debug("[MCPClientFactory] Error closing transport during cleanup:",s)}const i=this.getStderrTail(n);throw o instanceof Error&&i.length>0?new Error(`${o.message}
1168
+ ${w}`,l++;break;case"id":a=w.includes("\0")?void 0:w;break;case"retry":/^\d+$/.test(w)?n(parseInt(w,10)):r(new Zue(`Invalid \`retry\` value: "${w}"`,{type:"invalid-retry",value:w,line:T}));break;default:r(new Zue(`Unknown field "${v.length>20?`${v.slice(0,20)}\u2026`:v}"`,{type:"unknown-field",field:v,value:w,line:T}));break}}function g(){l>0&&t({id:a,event:c,data:u}),a=void 0,u="",l=0,c=void 0}function y(v={}){if(v.consume&&i.length>0){const w=i.join("");m(w,0,w.length)}s=!0,a=void 0,u="",l=0,c=void 0,i.length=0}return{feed:d,reset:y}}function Nnr(e,t,r){return r===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function Lnr(e,t,r){return r===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}var Zue,Que,$nr,gf,ele=S({"node_modules/.pnpm/eventsource-parser@3.0.8/node_modules/eventsource-parser/dist/index.js"(){Zue=class extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}},Que=10,$nr=13,gf=32}});function wbn(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function tle(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(tle).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${tle(e.cause)}`:e.message:`${e}`}function Fnr(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}function bbn(){const e="document"in globalThis?globalThis.document:void 0;return e&&typeof e=="object"&&"baseURI"in e&&typeof e.baseURI=="string"?e.baseURI:void 0}var rle,nle,J6,_r,ji,Bo,np,lu,ky,VT,X6,Y6,x1,HT,I1,yf,WT,KT,JT,R1,Mc,ole,ile,sle,Unr,ale,ule,M1,lle,cle,P1,Tbn=S({"node_modules/.pnpm/eventsource@3.0.7/node_modules/eventsource/dist/index.js"(){ele(),rle=class extends Event{constructor(e,t){var r,n;super(e),this.code=(r=t?.code)!=null?r:void 0,this.message=(n=t?.message)!=null?n:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,t,r){return r(Fnr(this),t)}[Symbol.for("Deno.customInspect")](e,t){return e(Fnr(this),t)}},nle=e=>{throw TypeError(e)},J6=(e,t,r)=>t.has(e)||nle("Cannot "+r),_r=(e,t,r)=>(J6(e,t,"read from private field"),r?r.call(e):t.get(e)),ji=(e,t,r)=>t.has(e)?nle("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Bo=(e,t,r,n)=>(J6(e,t,"write to private field"),t.set(e,r),r),np=(e,t,r)=>(J6(e,t,"access private method"),r),P1=class extends EventTarget{constructor(e,t){var r,n;super(),ji(this,Mc),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,ji(this,lu),ji(this,ky),ji(this,VT),ji(this,X6),ji(this,Y6),ji(this,x1),ji(this,HT),ji(this,I1,null),ji(this,yf),ji(this,WT),ji(this,KT,null),ji(this,JT,null),ji(this,R1,null),ji(this,ile,async o=>{var i;_r(this,WT).reset();const{body:s,redirected:a,status:u,headers:l}=o;if(u===204){np(this,Mc,M1).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(a?Bo(this,VT,new URL(o.url)):Bo(this,VT,void 0),u!==200){np(this,Mc,M1).call(this,`Non-200 status code (${u})`,u);return}if(!(l.get("content-type")||"").startsWith("text/event-stream")){np(this,Mc,M1).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(_r(this,lu)===this.CLOSED)return;Bo(this,lu,this.OPEN);const c=new Event("open");if((i=_r(this,R1))==null||i.call(this,c),this.dispatchEvent(c),typeof s!="object"||!s||!("getReader"in s)){np(this,Mc,M1).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}const d=new TextDecoder,p=s.getReader();let m=!0;do{const{done:h,value:g}=await p.read();g&&_r(this,WT).feed(d.decode(g,{stream:!h})),h&&(m=!1,_r(this,WT).reset(),np(this,Mc,lle).call(this))}while(m)}),ji(this,sle,o=>{Bo(this,yf,void 0),!(o.name==="AbortError"||o.type==="aborted")&&np(this,Mc,lle).call(this,tle(o))}),ji(this,ale,o=>{typeof o.id=="string"&&Bo(this,I1,o.id);const i=new MessageEvent(o.event||"message",{data:o.data,origin:_r(this,VT)?_r(this,VT).origin:_r(this,ky).origin,lastEventId:o.id||""});_r(this,JT)&&(!o.event||o.event==="message")&&_r(this,JT).call(this,i),this.dispatchEvent(i)}),ji(this,ule,o=>{Bo(this,x1,o)}),ji(this,cle,()=>{Bo(this,HT,void 0),_r(this,lu)===this.CONNECTING&&np(this,Mc,ole).call(this)});try{if(e instanceof URL)Bo(this,ky,e);else if(typeof e=="string")Bo(this,ky,new URL(e,bbn()));else throw new Error("Invalid URL")}catch{throw wbn("An invalid or illegal string was specified")}Bo(this,WT,Yue({onEvent:_r(this,ale),onRetry:_r(this,ule)})),Bo(this,lu,this.CONNECTING),Bo(this,x1,3e3),Bo(this,Y6,(r=t?.fetch)!=null?r:globalThis.fetch),Bo(this,X6,(n=t?.withCredentials)!=null?n:!1),np(this,Mc,ole).call(this)}get readyState(){return _r(this,lu)}get url(){return _r(this,ky).href}get withCredentials(){return _r(this,X6)}get onerror(){return _r(this,KT)}set onerror(e){Bo(this,KT,e)}get onmessage(){return _r(this,JT)}set onmessage(e){Bo(this,JT,e)}get onopen(){return _r(this,R1)}set onopen(e){Bo(this,R1,e)}addEventListener(e,t,r){const n=t;super.addEventListener(e,n,r)}removeEventListener(e,t,r){const n=t;super.removeEventListener(e,n,r)}close(){_r(this,HT)&&clearTimeout(_r(this,HT)),_r(this,lu)!==this.CLOSED&&(_r(this,yf)&&_r(this,yf).abort(),Bo(this,lu,this.CLOSED),Bo(this,yf,void 0))}},lu=new WeakMap,ky=new WeakMap,VT=new WeakMap,X6=new WeakMap,Y6=new WeakMap,x1=new WeakMap,HT=new WeakMap,I1=new WeakMap,yf=new WeakMap,WT=new WeakMap,KT=new WeakMap,JT=new WeakMap,R1=new WeakMap,Mc=new WeakSet,ole=function(){Bo(this,lu,this.CONNECTING),Bo(this,yf,new AbortController),_r(this,Y6)(_r(this,ky),np(this,Mc,Unr).call(this)).then(_r(this,ile)).catch(_r(this,sle))},ile=new WeakMap,sle=new WeakMap,Unr=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",..._r(this,I1)?{"Last-Event-ID":_r(this,I1)}:void 0},cache:"no-store",signal:(e=_r(this,yf))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},ale=new WeakMap,ule=new WeakMap,M1=function(e,t){var r;_r(this,lu)!==this.CLOSED&&Bo(this,lu,this.CLOSED);const n=new rle("error",{code:t,message:e});(r=_r(this,KT))==null||r.call(this,n),this.dispatchEvent(n)},lle=function(e,t){var r;if(_r(this,lu)===this.CLOSED)return;Bo(this,lu,this.CONNECTING);const n=new rle("error",{code:t,message:e});(r=_r(this,KT))==null||r.call(this,n),this.dispatchEvent(n),Bo(this,HT,setTimeout(_r(this,cle),_r(this,x1)))},cle=new WeakMap,P1.CONNECTING=0,P1.OPEN=1,P1.CLOSED=2}});function Z6(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function Bnr(e=fetch,t){return t?async(r,n)=>{const o={...t,...n,headers:n?.headers?{...Z6(t.headers),...Z6(n.headers)}:t.headers};return e(r,o)}:e}function _bn(e,t){return e.protocol===t.protocol&&e.hostname===t.hostname&&e.port===t.port?!0:e.hostname===t.hostname&&e.protocol==="http:"&&e.port===""&&t.protocol==="https:"&&t.port===""}function znr(e,t){const r=qnr.includes(e.status)?e.headers.get("location"):null;try{return r?new URL(r,t):void 0}catch{return}}function dle(e,t,r,n,o=0){const i=znr(n,t),s=n.status===307||n.status===308||(r?.method??"GET").toUpperCase()==="GET";if(!i||o===Gnr||!s)return;const a=new URL(t);if(!((i.username||i.password)&&(i.username!==a.username||i.password!==a.password)||!_bn(a,i)))return Promise.resolve(n.body?.cancel()).then(()=>e(i,{...r,redirect:"manual"})).then(l=>dle(e,i,r,l,o+1)??l)}function Q6(e){const t=(r,n)=>(e??fetch)(r,n);return mle.add(t),t}function Ay(e=fetch){return mle.has(e)?e:(t,r)=>r?.redirect==="error"||r?.redirect==="manual"?e(t,r):Promise.resolve(e(t,{...r,redirect:"manual"})).then(n=>dle(e,t,r,n)??n)}function ple(e,t){if(e.type==="opaqueredirect")return"Redirect not followed: this runtime does not expose the redirect target";const r=e.url||t,n=znr(e,r);if(n)return n.username=n.password=n.search=n.hash="",n.protocol==="http:"&&new URL(r).protocol==="https:"?(n.protocol="https:",`Redirect to plain http not followed; try ${n.href} instead`):`Redirect to ${n.href} not followed`}var Gnr,qnr,mle,hle=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js"(){Gnr=5,qnr=[301,302,303,307,308],mle=new WeakSet}}),Cy,fs,jnr,Ebn,Sbn,kbn,Abn,Cbn,xbn,Ibn,Rbn,Mbn,Pbn,Dbn,Obn,Nbn,Lbn,$bn,Fbn,Ubn,Bbn,zbn,Gbn,qbn,jbn,Vbn,Hbn,Wbn,Kbn,Jbn,Xbn,Ybn,Zbn,Qbn,eTn,tTn,rTn,nTn,oTn,iTn,sTn,aTn,uTn,lTn,cTn,dTn,pTn,mTn,hTn,fTn=S({"npm-stub:pkce-challenge"(){Cy={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Cy.get}):new Proxy(function(...r){return new Proxy({},{get:Cy.get})},{get:Cy.get,apply(r,n,o){return new Proxy({},{get:Cy.get})},construct(r,n){return new Proxy({},{get:Cy.get})}})}},fs=new Proxy({},Cy),jnr=fs,{BedrockClient:Ebn,ListFoundationModelsCommand:Sbn,BedrockRuntimeClient:kbn,ConverseCommand:Abn,ConverseStreamCommand:Cbn,ImageFormat:xbn,InvokeModelCommand:Ibn}=fs,{SageMakerRuntimeClient:Rbn,InvokeEndpointCommand:Mbn,InvokeEndpointWithResponseStreamCommand:Pbn}=fs,{GoogleAuth:Dbn,VertexAI:Obn,TextToSpeechClient:Nbn}=fs,{Webhook:Lbn}=fs,{Hippocampus:$bn,HippocampusConfig:Fbn}=fs,{createClient:Ubn}=fs,{Queue:Bbn,Worker:zbn,Job:Gbn,QueueScheduler:qbn,FlowProducer:jbn}=fs,{Cron:Vbn}=fs,{parseBuffer:Hbn,selectCover:Wbn}=fs,{extractRawText:Kbn,convertToHtml:Jbn}=fs,{Hono:Xbn}=fs,{cors:Ybn,HTTPException:Zbn,logger:Qbn,secureHeaders:eTn,streamSSE:tTn,timeout:rTn}=fs,nTn=globalThis.fetch,oTn=globalThis.Request,iTn=globalThis.Response,sTn=globalThis.Headers,aTn=globalThis.FormData,uTn=globalThis.File,lTn=globalThis.Blob,cTn=fs.Agent,dTn=fs.Pool,pTn=fs.Client,mTn=fs.Dispatcher,hTn=fs.MockAgent}}),Ms,Vnr,fle,Hnr,Wnr,Knr,Jnr,gle,Xnr,Ynr,Znr,gTn,yTn,Qnr=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js"(){$er(),Ms=wV().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:NV.custom,message:"URL must be parseable",fatal:!0}),jM}).refine(e=>{const t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Vnr=ts({resource:ie().url(),authorization_servers:Ze(Ms).optional(),jwks_uri:ie().url().optional(),scopes_supported:Ze(ie()).optional(),bearer_methods_supported:Ze(ie()).optional(),resource_signing_alg_values_supported:Ze(ie()).optional(),resource_name:ie().optional(),resource_documentation:ie().optional(),resource_policy_uri:ie().url().optional(),resource_tos_uri:ie().url().optional(),tls_client_certificate_bound_access_tokens:yn().optional(),authorization_details_types_supported:Ze(ie()).optional(),dpop_signing_alg_values_supported:Ze(ie()).optional(),dpop_bound_access_tokens_required:yn().optional()}),fle=ts({issuer:ie(),authorization_endpoint:Ms,token_endpoint:Ms,registration_endpoint:Ms.optional(),scopes_supported:Ze(ie()).optional(),response_types_supported:Ze(ie()),response_modes_supported:Ze(ie()).optional(),grant_types_supported:Ze(ie()).optional(),token_endpoint_auth_methods_supported:Ze(ie()).optional(),token_endpoint_auth_signing_alg_values_supported:Ze(ie()).optional(),service_documentation:Ms.optional(),revocation_endpoint:Ms.optional(),revocation_endpoint_auth_methods_supported:Ze(ie()).optional(),revocation_endpoint_auth_signing_alg_values_supported:Ze(ie()).optional(),introspection_endpoint:ie().optional(),introspection_endpoint_auth_methods_supported:Ze(ie()).optional(),introspection_endpoint_auth_signing_alg_values_supported:Ze(ie()).optional(),code_challenge_methods_supported:Ze(ie()).optional(),client_id_metadata_document_supported:yn().optional()}),Hnr=ts({issuer:ie(),authorization_endpoint:Ms,token_endpoint:Ms,userinfo_endpoint:Ms.optional(),jwks_uri:Ms,registration_endpoint:Ms.optional(),scopes_supported:Ze(ie()).optional(),response_types_supported:Ze(ie()),response_modes_supported:Ze(ie()).optional(),grant_types_supported:Ze(ie()).optional(),acr_values_supported:Ze(ie()).optional(),subject_types_supported:Ze(ie()),id_token_signing_alg_values_supported:Ze(ie()),id_token_encryption_alg_values_supported:Ze(ie()).optional(),id_token_encryption_enc_values_supported:Ze(ie()).optional(),userinfo_signing_alg_values_supported:Ze(ie()).optional(),userinfo_encryption_alg_values_supported:Ze(ie()).optional(),userinfo_encryption_enc_values_supported:Ze(ie()).optional(),request_object_signing_alg_values_supported:Ze(ie()).optional(),request_object_encryption_alg_values_supported:Ze(ie()).optional(),request_object_encryption_enc_values_supported:Ze(ie()).optional(),token_endpoint_auth_methods_supported:Ze(ie()).optional(),token_endpoint_auth_signing_alg_values_supported:Ze(ie()).optional(),display_values_supported:Ze(ie()).optional(),claim_types_supported:Ze(ie()).optional(),claims_supported:Ze(ie()).optional(),service_documentation:ie().optional(),claims_locales_supported:Ze(ie()).optional(),ui_locales_supported:Ze(ie()).optional(),claims_parameter_supported:yn().optional(),request_parameter_supported:yn().optional(),request_uri_parameter_supported:yn().optional(),require_request_uri_registration:yn().optional(),op_policy_uri:Ms.optional(),op_tos_uri:Ms.optional(),client_id_metadata_document_supported:yn().optional()}),Wnr=it({...Hnr.shape,...fle.pick({code_challenge_methods_supported:!0}).shape}),Knr=it({access_token:ie(),id_token:ie().optional(),token_type:ie(),expires_in:zV.number().optional(),scope:ie().optional(),refresh_token:ie().optional(),issuer:ie().optional().catch(void 0)}).strip(),Jnr=it({error:ie(),error_description:ie().optional(),error_uri:ie().optional()}),gle=Ms.optional().or(Et("").transform(()=>{})),Xnr=it({redirect_uris:Ze(Ms),token_endpoint_auth_method:ie().optional(),grant_types:Ze(ie()).optional(),response_types:Ze(ie()).optional(),client_name:ie().optional(),client_uri:Ms.optional(),logo_uri:gle,scope:ie().optional(),contacts:Ze(ie()).optional(),tos_uri:gle,policy_uri:ie().optional(),jwks_uri:Ms.optional(),jwks:bV().optional(),software_id:ie().optional(),software_version:ie().optional(),software_statement:ie().optional()}).strip(),Ynr=it({client_id:ie(),client_secret:ie().optional(),client_id_issued_at:Br().optional(),client_secret_expires_at:Br().optional(),issuer:ie().optional().catch(void 0)}).strip(),Znr=Xnr.merge(Ynr),gTn=it({error:ie(),error_description:ie().optional()}).strip(),yTn=it({token:ie(),token_type_hint:ie().optional()}).strip()}});function vTn(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function wTn({requestedResource:e,configuredResource:t}){const r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",i=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(i)}var bTn=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js"(){}}),gs,e$,D1,O1,N1,t$,r$,n$,xy,o$,i$,s$,a$,u$,l$,L1,c$,d$,eor,TTn=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js"(){gs=class extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){const e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},e$=class extends gs{},e$.errorCode="invalid_request",D1=class extends gs{},D1.errorCode="invalid_client",O1=class extends gs{},O1.errorCode="invalid_grant",N1=class extends gs{},N1.errorCode="unauthorized_client",t$=class extends gs{},t$.errorCode="unsupported_grant_type",r$=class extends gs{},r$.errorCode="invalid_scope",n$=class extends gs{},n$.errorCode="access_denied",xy=class extends gs{},xy.errorCode="server_error",o$=class extends gs{},o$.errorCode="temporarily_unavailable",i$=class extends gs{},i$.errorCode="unsupported_response_type",s$=class extends gs{},s$.errorCode="unsupported_token_type",a$=class extends gs{},a$.errorCode="invalid_token",u$=class extends gs{},u$.errorCode="method_not_allowed",l$=class extends gs{},l$.errorCode="too_many_requests",L1=class extends gs{},L1.errorCode="invalid_client_metadata",c$=class extends gs{},c$.errorCode="insufficient_scope",d$=class extends gs{},d$.errorCode="invalid_target",eor={[e$.errorCode]:e$,[D1.errorCode]:D1,[O1.errorCode]:O1,[N1.errorCode]:N1,[t$.errorCode]:t$,[r$.errorCode]:r$,[n$.errorCode]:n$,[xy.errorCode]:xy,[o$.errorCode]:o$,[i$.errorCode]:i$,[s$.errorCode]:s$,[a$.errorCode]:a$,[u$.errorCode]:u$,[l$.errorCode]:l$,[L1.errorCode]:L1,[c$.errorCode]:c$,[d$.errorCode]:d$}}});function _Tn(e){return["client_secret_basic","client_secret_post","none"].includes(e)}function ETn(e,t){const r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&_Tn(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?r?"client_secret_basic":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function STn(e,t,r,n){const{client_id:o,client_secret:i}=t;switch(e){case"client_secret_basic":kTn(o,i,r);return;case"client_secret_post":ATn(o,i,n);return;case"none":CTn(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function kTn(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}function ATn(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function CTn(e,t){t.set("client_id",e)}async function tor(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=Jnr.parse(JSON.parse(r)),{error:o,error_description:i,error_uri:s}=n,a=eor[o]||xy;return new a(i||"",s)}catch(n){const o=e instanceof Response?ple(e,e.url):void 0,i=`${t?`HTTP ${t}: `:""}${o??`Invalid OAuth error response: ${n}. Raw body: ${r}`}`;return new xy(i)}}function xTn(e,t){let[r,n]=[e,t];try{[r,n]=[new URL(e).href,new URL(t).href]}catch{}return r===n||r.endsWith("/")&&r.slice(0,-1)===n||n.endsWith("/")&&n.slice(0,-1)===r}function yle(e,t){if(e)return typeof e.issuer!="string"?e.issuer==null?e:{...e,issuer:void 0}:xTn(e.issuer,t)?e:void 0}function ror(e,t){return new Error(`OAuth client information is bound to authorization server ${e.issuer} and is not presented to ${t}. Clear the stored client information, or correct \`expectedIssuer\`, if the authorization server has moved.`)}async function Iy(e,t){try{return await vle(e,t)}catch(r){if(r instanceof D1||r instanceof N1)return await e.invalidateCredentials?.("all"),await vle(e,t);if(r instanceof O1)return await e.invalidateCredentials?.("tokens"),await vle(e,t);throw r}}async function vle(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:i}){const s=await e.discoveryState?.();let a,u,l,c=o;if(!c&&s?.resourceMetadataUrl&&(c=new URL(s.resourceMetadataUrl)),s?.authorizationServerUrl){if(u=s.authorizationServerUrl,a=s.resourceMetadata,l=s.authorizationServerMetadata??await ior(u,{fetchFn:i}),!a)try{a=await nor(t,{resourceMetadataUrl:c},i)}catch{}(l!==s.authorizationServerMetadata||a!==s.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:c?.toString(),resourceMetadata:a,authorizationServerMetadata:l})}else{const x=await NTn(t,{resourceMetadataUrl:c,fetchFn:i});u=x.authorizationServerUrl,l=x.authorizationServerMetadata,a=x.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:c?.toString(),resourceMetadata:a,authorizationServerMetadata:l})}const d=String(u),p=await RTn(t,e,a),m=p&&a&&!e.validateResourceURL?a.resource:p,h=n||a?.scopes_supported?.join(" ")||e.clientMetadata.scope,g=await Promise.resolve(e.clientInformation());let y=yle(g,d);const v=e.saveClientInformation!==void 0&&!!e.redirectUrl;if(g&&!y&&!v)throw ror(g,d);const w=y?.issuer==null?y:void 0,T=async()=>{try{w&&await e.saveClientInformation?.({...w,issuer:d})}catch{}};if(!y){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const x=l?.client_id_metadata_document_supported===!0,P=e.clientMetadataUrl;if(P&&!ITn(P))throw new L1(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${P}`);if(x&&P)y={client_id:P,issuer:d},await e.saveClientInformation?.(y);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");y={...await BTn(u,{metadata:l,clientMetadata:e.clientMetadata,scope:h,fetchFn:i}),issuer:d},await e.saveClientInformation(y)}}const E=!e.redirectUrl;if(r!==void 0||E){const x=await UTn(e,u,{metadata:l,resource:m,authorizationCode:r,fetchFn:i});return await T(),await e.saveTokens({...x,issuer:d}),"AUTHORIZED"}const k=yle(await e.tokens(),d);if(k?.refresh_token&&k.issuer==null&&console.warn("[mcp-sdk] stored OAuth tokens have no 'issuer' property (saved by an earlier version, or by a provider that does not keep it) and are used as-is; make sure your OAuthClientProvider stores what saveTokens() and saveClientInformation() receive unchanged."),k?.refresh_token)try{const x=await FTn(u,{metadata:l,clientInformation:y,refreshToken:k.refresh_token,resource:m,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await T(),await e.saveTokens({...x,issuer:d}),"AUTHORIZED"}catch(x){if(!(!(x instanceof gs)||x instanceof xy))throw x}const A=e.state?await e.state():void 0,{authorizationUrl:C,codeVerifier:R}=await LTn(u,{metadata:l,clientInformation:y,state:A,redirectUrl:e.redirectUrl,scope:h,resource:m});return await e.saveCodeVerifier(R),await e.redirectToAuthorization(C),"REDIRECT"}function ITn(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function RTn(e,t,r){const n=vTn(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!wTn({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function p$(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const o=wle(e,"resource_metadata")||void 0;let i;if(o)try{i=new URL(o)}catch{}const s=wle(e,"scope")||void 0,a=wle(e,"error")||void 0;return{resourceMetadataUrl:i,scope:s,error:a}}function wle(e,t){const r=e.headers.get("WWW-Authenticate");if(!r)return null;const n=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),o=r.match(n);return o?o[1]||o[2]:null}async function nor(e,t,r=fetch){const n=await DTn(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.body?.cancel(),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return Vnr.parse(await n.json())}async function ble(e,t,r=fetch){try{return await Ay(r)(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?ble(e,void 0,r):void 0;throw n}}function MTn(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function oor(e,t,r=fetch){return await ble(e,{"MCP-Protocol-Version":t},r)}function PTn(e,t){return!e||!e.ok&&e.status<500&&t!=="/"}async function DTn(e,t,r,n){const o=new URL(e),i=n?.protocolVersion??_1;let s;if(n?.metadataUrl)s=new URL(n.metadataUrl);else{const u=MTn(t,o.pathname);s=new URL(u,n?.metadataServerUrl??o),s.search=o.search}let a=await oor(s,i,r);if(!n?.metadataUrl&&PTn(a,o.pathname)){const u=new URL(`/.well-known/${t}`,o);a=await oor(u,i,r)}return a}function OTn(e){const t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let o=t.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"}),n.push({url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}async function ior(e,{fetchFn:t=fetch,protocolVersion:r=_1}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},o=OTn(e);for(const{url:i,type:s}of o){const a=await ble(i,n,t);if(a){if(!a.ok){if(await a.body?.cancel(),a.status<500)continue;throw new Error(`HTTP ${a.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}return s==="oauth"?fle.parse(await a.json()):Wnr.parse(await a.json())}}}async function NTn(e,t){let r,n;try{r=await nor(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(n=r.authorization_servers[0])}catch{}n||(n=String(new URL("/",e)));const o=await ior(n,{fetchFn:t?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:o,resourceMetadata:r}}function sor(e){return typeof e=="string"?e:e.href}async function LTn(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:i,resource:s}){let a;if(t){if(a=new URL(t.authorization_endpoint),!t.response_types_supported.includes(m$))throw new Error(`Incompatible auth server: does not support response type ${m$}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(h$))throw new Error(`Incompatible auth server: does not support code challenge method ${h$}`)}else a=new URL("/authorize",e);const u=await jnr(),l=u.code_verifier,c=u.code_challenge;return a.searchParams.set("response_type",m$),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",c),a.searchParams.set("code_challenge_method",h$),a.searchParams.set("redirect_uri",String(n)),i&&a.searchParams.set("state",i),o&&a.searchParams.set("scope",o),o?.includes("offline_access")&&a.searchParams.append("prompt","consent"),s&&a.searchParams.set("resource",sor(s)),{authorizationUrl:a,codeVerifier:l}}function $Tn(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function aor(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:i,fetchFn:s}){const a=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(i&&r.set("resource",sor(i)),o)await o(u,r,a,t);else if(n){const c=t?.token_endpoint_auth_methods_supported??[],d=ETn(n,c);STn(d,n,u,r)}const l=await Ay(s??fetch)(a,{method:"POST",headers:u,body:r});if(!l.ok)throw await tor(l);return uor.parse(await l.json())}async function FTn(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:i,fetchFn:s}){const a=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),u=await aor(e,{metadata:t,tokenRequestParams:a,clientInformation:r,addClientAuthentication:i,resource:o,fetchFn:s});return{refresh_token:n,...u}}async function UTn(e,t,{metadata:r,resource:n,authorizationCode:o,fetchFn:i}={}){const s=async()=>{const c=await e.clientInformation(),d=yle(c,String(t));if(c&&!d)throw ror(c,String(t));return d};let a=await s();const u=e.clientMetadata.scope;let l;if(e.prepareTokenRequest&&(l=await e.prepareTokenRequest(u)),!l){if(!o)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");const c=await e.codeVerifier();l=$Tn(o,c,e.redirectUrl)}return a??(a=await s()),aor(t,{metadata:r,tokenRequestParams:l,clientInformation:a,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:i})}async function BTn(e,{metadata:t,clientMetadata:r,scope:n,fetchFn:o}){let i;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(t.registration_endpoint)}else i=new URL("/register",e);const s=await Ay(o??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...n!==void 0?{scope:n}:{}})});if(!s.ok)throw await tor(s);return lor.parse(await s.json())}var Ll,m$,h$,uor,lor,cor=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"(){fTn(),ff(),Qnr(),Qnr(),bTn(),TTn(),hle(),Ll=class extends Error{constructor(e){super(e??"Unauthorized")}},m$="code",h$="S256",uor=Knr.omit({issuer:!0}),lor=Znr.omit({issuer:!0})}}),dor={};ue(dor,{SSEClientTransport:()=>por,SseError:()=>Tle});var Tle,por,zTn=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"(){Tbn(),hle(),ff(),cor(),Tle=class extends Error{constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r}},por=class{constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=t?.eventSourceInit,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=Bnr(t?.fetch,t?.requestInit),this._followRedirects=t?.redirectPolicy==="follow",this._followRedirects&&(this._fetch=Q6(this._fetch),this._fetchWithInit=Q6(this._fetchWithInit))}_unfollowedRedirect(e,t){const r=ple(e,t);return r&&!this._followRedirects?`${r} (redirectPolicy: 'same-origin')`:r}async _authThenStart(){if(!this._authProvider)throw new Ll("No auth provider");let e;try{e=await Iy(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(t){throw this.onerror?.(t),t}if(e!=="AUTHORIZED")throw new Ll;return await this._startOrAuth()}async _commonHeaders(){const e={};if(this._authProvider){const r=await this._authProvider.tokens();r&&(e.Authorization=`Bearer ${r.access_token}`)}this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);const t=Z6(this._requestInit?.headers);return new Headers({...e,...t})}_startOrAuth(){const e=this?._eventSourceInit?.fetch??this._fetch??fetch,t=this._followRedirects?e:Ay(e);let r;return new Promise((n,o)=>{this._eventSource=new P1(this._url.href,{...this._eventSourceInit,fetch:async(i,s)=>{const a=await this._commonHeaders();a.set("Accept","text/event-stream");const u=await t(i,{...s,headers:a});if(r=this._unfollowedRedirect(u,i),u.status===401&&u.headers.has("www-authenticate")){const{resourceMetadataUrl:l,scope:c}=p$(u);this._resourceMetadataUrl=l,this._scope=c}return u}}),this._abortController=new AbortController,this._eventSource.onerror=i=>{if(i.code===401&&this._authProvider){this._authThenStart().then(n,o);return}const s=new Tle(i.code,r??i.message,i);o(s),this.onerror?.(s)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",i=>{const s=i;try{if(this._endpoint=new URL(s.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(a){o(a),this.onerror?.(a),this.close();return}n()}),this._eventSource.onmessage=i=>{const s=i;let a;try{a=yy.parse(JSON.parse(s.data))}catch(u){this.onerror?.(u);return}this.onmessage?.(a)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new Ll("No auth provider");if(await Iy(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Ll("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){if(!this._endpoint)throw new Error("Not connected");try{const t=await this._commonHeaders();t.set("content-type","application/json");const r={...this._requestInit,method:"POST",headers:t,body:JSON.stringify(e),signal:this._abortController?.signal},n=await Ay(this._fetch??fetch)(this._endpoint,r);if(!n.ok){const o=await n.text().catch(()=>null);if(n.status===401&&this._authProvider){const{resourceMetadataUrl:i,scope:s}=p$(n);if(this._resourceMetadataUrl=i,this._scope=s,await Iy(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Ll;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${n.status}): ${this._unfollowedRedirect(n,this._endpoint)??o}`)}await n.body?.cancel()}catch(t){throw this.onerror?.(t),t}}setProtocolVersion(e){this._protocolVersion=e}}}}),mor={};ue(mor,{WebSocketClientTransport:()=>gor});var hor,gor,GTn=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/websocket.js"(){ff(),hor="mcp",gor=class{constructor(e){this._url=e}start(){if(this._socket)throw new Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,t)=>{this._socket=new WebSocket(this._url,hor),this._socket.onerror=r=>{const n="error"in r?r.error:new Error(`WebSocket error: ${JSON.stringify(r)}`);t(n),this.onerror?.(n)},this._socket.onopen=()=>{e()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=r=>{let n;try{n=yy.parse(JSON.parse(r.data))}catch(o){this.onerror?.(o);return}this.onmessage?.(n)}})}async close(){this._socket?.close()}send(e){return new Promise((t,r)=>{if(!this._socket){r(new Error("Not connected"));return}this._socket?.send(JSON.stringify(e)),t()})}}}}),qTn=dn({"node_modules/.pnpm/content-type@1.0.5/node_modules/content-type/index.js"(e){"use strict";var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,r=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,n=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,o=/\\([\u000b\u0020-\u00ff])/g,i=/([\\"])/g,s=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.format=a,e.parse=u;function a(p){if(!p||typeof p!="object")throw new TypeError("argument obj is required");var m=p.parameters,h=p.type;if(!h||!s.test(h))throw new TypeError("invalid type");var g=h;if(m&&typeof m=="object")for(var y,v=Object.keys(m).sort(),w=0;w<v.length;w++){if(y=v[w],!n.test(y))throw new TypeError("invalid parameter name");g+="; "+y+"="+c(m[y])}return g}function u(p){if(!p)throw new TypeError("argument string is required");var m=typeof p=="object"?l(p):p;if(typeof m!="string")throw new TypeError("argument string is required to be a string");var h=m.indexOf(";"),g=h!==-1?m.slice(0,h).trim():m.trim();if(!s.test(g))throw new TypeError("invalid media type");var y=new d(g.toLowerCase());if(h!==-1){var v,w,T;for(t.lastIndex=h;w=t.exec(m);){if(w.index!==h)throw new TypeError("invalid parameter format");h+=w[0].length,v=w[1].toLowerCase(),T=w[2],T.charCodeAt(0)===34&&(T=T.slice(1,-1),T.indexOf("\\")!==-1&&(T=T.replace(o,"$1"))),y.parameters[v]=T}if(h!==m.length)throw new TypeError("invalid parameter format")}return y}function l(p){var m;if(typeof p.getHeader=="function"?m=p.getHeader("content-type"):typeof p.headers=="object"&&(m=p.headers&&p.headers["content-type"]),typeof m!="string")throw new TypeError("content-type header is missing from object");return m}function c(p){var m=String(p);if(n.test(m))return m;if(m.length>0&&!r.test(m))throw new TypeError("invalid parameter value");return'"'+m.replace(i,"\\$1")+'"'}function d(p){this.parameters=Object.create(null),this.type=p}}});function jTn(e){if(e)try{return yor.default.parse(e).type}catch{const t=(e.split(";",1)[0]??"").trim().toLowerCase();return t===""||e.slice(t.length).includes(",")?void 0:t}}var yor,VTn=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/mediaType.js"(){yor=ml(qTn(),1)}}),vor,HTn=S({"node_modules/.pnpm/eventsource-parser@3.0.8/node_modules/eventsource-parser/dist/stream.js"(){ele(),vor=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:r}={}){let n;super({start(o){n=Yue({onEvent:i=>{o.enqueue(i)},onError(i){e==="terminate"?o.error(i):typeof e=="function"&&e(i)},onRetry:t,onComment:r})},transform(o){n.feed(o)}})}}}}),wor={};ue(wor,{StreamableHTTPClientTransport:()=>Tor,StreamableHTTPError:()=>vf});var bor,vf,Tor,WTn=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js"(){VTn(),hle(),ff(),cor(),HTn(),bor={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},vf=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},Tor=class{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=Bnr(t?.fetch,t?.requestInit),this._followRedirects=t?.redirectPolicy==="follow",this._followRedirects&&(this._fetch=Q6(this._fetch),this._fetchWithInit=Q6(this._fetchWithInit)),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??bor}_unfollowedRedirect(e,t){const r=ple(e,t);return r&&!this._followRedirects?`${r} (redirectPolicy: 'same-origin')`:r}async _authThenStart(){if(!this._authProvider)throw new Ll("No auth provider");let e;try{e=await Iy(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(t){throw this.onerror?.(t),t}if(e!=="AUTHORIZED")throw new Ll;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){const e={};if(this._authProvider){const r=await this._authProvider.tokens();r&&(e.Authorization=`Bearer ${r.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);const t=Z6(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){const{resumptionToken:t}=e;try{const r=await this._commonHeaders();r.set("Accept","text/event-stream"),t&&r.set("last-event-id",t);const n=this._fetch??fetch,o={method:"GET",headers:r,signal:this._abortController?.signal};let i=await n(this._url,this._followRedirects?o:{...o,redirect:"manual"});const s=this._followRedirects?void 0:dle(n,this._url,o,i);if(s&&(i=await s),!i.ok){if(await i.body?.cancel(),i.status===401&&this._authProvider)return await this._authThenStart();if(i.status===405)return;throw new vf(i.status,`Failed to open SSE stream: ${this._unfollowedRedirect(i,this._url)??i.statusText}`)}this._handleSseStream(i.body,e,!0)}catch(r){throw this.onerror?.(r),r}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const t=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(r,e),n)}_scheduleReconnection(e,t=0){const r=this._reconnectionOptions.maxRetries;if(t>=r){this.onerror?.(new Error(`Maximum reconnection attempts (${r}) exceeded.`));return}const n=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(o=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(e,t+1)})},n)}_handleSseStream(e,t,r){if(!e)return;const{onresumptiontoken:n,replayMessageId:o}=t;let i,s=!1,a=!1;(async()=>{try{const l=e.pipeThrough(new TextDecoderStream).pipeThrough(new vor({onRetry:p=>{this._serverRetryMs=p}})).getReader();for(;;){const{value:p,done:m}=await l.read();if(m)break;if(p.id&&(i=p.id,s=!0,n?.(p.id)),!!p.data&&(!p.event||p.event==="message"))try{const h=yy.parse(JSON.parse(p.data));FT(h)&&(a=!0,o!==void 0&&(h.id=o)),this.onmessage?.(h)}catch(h){this.onerror?.(h)}}(r||s)&&!a&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:n,replayMessageId:o},0)}catch(l){if(this.onerror?.(new Error(`SSE stream disconnected: ${l}`)),(r||s)&&!a&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:n,replayMessageId:o},0)}catch(p){this.onerror?.(new Error(`Failed to reconnect: ${p instanceof Error?p.message:String(p)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Ll("No auth provider");if(await Iy(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Ll("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{const{resumptionToken:r,onresumptiontoken:n}=t||{};if(r){this._startOrAuthSse({resumptionToken:r,replayMessageId:C6(e)?e.id:void 0}).catch(p=>this.onerror?.(p));return}const o=await this._commonHeaders();o.set("content-type","application/json"),o.set("accept","application/json, text/event-stream");const i={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:this._abortController?.signal},s=await Ay(this._fetch??fetch)(this._url,i),a=s.headers.get("mcp-session-id");if(a&&(this._sessionId=a),!s.ok){const p=await s.text().catch(()=>null);if(s.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new vf(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:m,scope:h}=p$(s);if(this._resourceMetadataUrl=m,this._scope=h,await Iy(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Ll;return this._hasCompletedAuthFlow=!0,this.send(e)}if(s.status===403&&this._authProvider){const{resourceMetadataUrl:m,scope:h,error:g}=p$(s);if(g==="insufficient_scope"){const y=s.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===y)throw new vf(403,"Server returned 403 after trying upscoping");if(h&&(this._scope=h),m&&(this._resourceMetadataUrl=m),this._lastUpscopingHeader=y??void 0,await Iy(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Ll;return this.send(e)}}throw new vf(s.status,`Error POSTing to endpoint: ${this._unfollowedRedirect(s,this._url)??p}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,s.status===202){await s.body?.cancel(),etr(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(p=>this.onerror?.(p));return}const l=(Array.isArray(e)?e:[e]).filter(p=>"method"in p&&"id"in p&&p.id!==void 0).length>0,c=s.headers.get("content-type"),d=jTn(c);if(l)if(d==="text/event-stream")this._handleSseStream(s.body,{onresumptiontoken:n},!1);else if(d==="application/json"){const p=await s.json(),m=Array.isArray(p)?p.map(h=>yy.parse(h)):[yy.parse(p)];for(const h of m)this.onmessage?.(h)}else throw await s.body?.cancel(),new vf(-1,`Unexpected content type: ${c}`);else await s.body?.cancel()}catch(r){throw this.onerror?.(r),r}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{const e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},r=await Ay(this._fetch??fetch)(this._url,t);if(await r.body?.cancel(),!r.ok&&r.status!==405)throw new vf(r.status,`Failed to terminate session: ${this._unfollowedRedirect(r,this._url)??r.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}}}}),_or={};ue(_or,{MCPClientFactory:()=>wf,terminateLiveStdioServers:()=>y$});var Eor,_le,Sor,Ele,f$,g$,Sle,kle,Ale,y$,kor,Aor,wf,Cle=S({"src/lib/mcp/mcpClientFactory.ts"(){"use strict";z(),aue(),lt(),ker(),Aer(),Rer(),Oer(),oo(),S0(),Eor=Math.max(5e3,Number(process.env.MCP_CLIENT_TIMEOUT)||6e4),_le=20,Sor=class{lines=[];partial="";append(e){this.partial+=e.toString();const t=this.partial.split(/\r?\n/);this.partial=t.pop()??"";for(const r of t)r.trim().length!==0&&(this.lines.push(r),this.lines.length>_le&&this.lines.shift())}snapshot(){const e=[...this.lines];return this.partial.trim().length>0&&e.push(this.partial),e.slice(-_le)}},Ele=new WeakMap,f$=new Set,g$=new Set,Sle=!1,Ale=(e,t)=>{const r=Reflect.get(e,"_process");return r instanceof t?r:void 0},y$=()=>{for(const e of f$){const t=kle&&Ale(e,kle);try{t?t.kill("SIGTERM"):"pid"in e&&typeof e.pid=="number"&&process.kill(e.pid,"SIGTERM")}catch{}}for(const e of g$)try{e.kill("SIGKILL")}catch{}},kor=(e,t)=>{const r=Ale(e,t);if(!r||r.exitCode!==null||r.signalCode!==null)return;g$.add(r);const n=()=>{g$.delete(r)};r.once("exit",n),r.once("close",n)},Aor=(e,t)=>{Sle||(Sle=!0,process.on("exit",y$)),kle=t,f$.add(e),e.onclose=()=>{f$.delete(e)};const r=e.close.bind(e);e.close=async()=>{kor(e,t),await r()}},wf=class{static NEUROLINK_IMPLEMENTATION={name:"neurolink-sdk",version:"1.0.0"};static DEFAULT_CAPABILITIES={roots:{listChanged:!1}};static async createClient(e,t=Eor){const r=e.httpOptions?.connectionTimeout;r!==void 0&&(t=Math.min(t,r));const n=Date.now(),{traceId:o,parentSpanId:i}=E0(),s=Ie.createSpan("mcp.transport","mcp.connect",{"mcp.transport":e.transport,"mcp.operation":"connect","mcp.server_id":e.id},i,o);try{ae.info(`[MCPClientFactory] Creating client for ${e.id}`,{transport:e.transport,command:e.command,hasRetryConfig:!!e.retryConfig,hasRateLimiting:!!e.rateLimiting,hasAuth:!!e.auth}),(e.transport==="http"||e.transport==="sse")&&e.rateLimiting&&(await due.getLimiter(e.id,{requestsPerWindow:e.rateLimiting.requestsPerMinute??60,windowMs:6e4,maxBurst:e.rateLimiting.maxBurst??10,useTokenBucket:e.rateLimiting.useTokenBucket??!0,refillRate:(e.rateLimiting.requestsPerMinute??60)/60}).acquire(),ae.debug(`[MCPClientFactory] Rate limit token acquired for ${e.id}`));const a=T1.getBreaker(`mcp-client-${e.id}`,{failureThreshold:3,resetTimeout:3e4,operationTimeout:t}),u=async()=>await a.execute(async()=>await this.createClientInternal(e,t));let l;(e.transport==="http"||e.transport==="sse")&&e.retryConfig?(ae.debug(`[MCPClientFactory] Using retry logic for ${e.id}`,{maxAttempts:e.retryConfig.maxAttempts??rp.maxAttempts}),l=await Ser(u,{maxAttempts:e.retryConfig.maxAttempts??rp.maxAttempts,initialDelay:e.retryConfig.initialDelay??rp.initialDelay,maxDelay:e.retryConfig.maxDelay??rp.maxDelay,backoffMultiplier:e.retryConfig.backoffMultiplier??rp.backoffMultiplier})):l=await u(),ae.info(`[MCPClientFactory] Client created successfully for ${e.id}`,{duration:Date.now()-n,capabilities:l.capabilities}),s.durationMs=Date.now()-n;const c=Ie.endSpan(s,1);return nt().recordSpan(c),{...l,success:!0,duration:Date.now()-n}}catch(a){const u=a instanceof Error?a.message:String(a);if(a instanceof uh){ae.warn(`[MCPClientFactory] Client creation blocked by circuit breaker for ${e.id}`,{serverId:e.id,breakerState:a.breakerState,retryAfter:a.retryAfter,retryAfterMs:a.retryAfterMs,failureCount:a.failureCount}),s.durationMs=Date.now()-n;const c=Ie.endSpan(s,2);return c.statusMessage=`Circuit breaker open: ${u}`,nt().recordSpan(c),{success:!1,error:u,duration:Date.now()-n}}ae.debug(`[MCPClientFactory] Failed to create client for ${e.id}:`,a),s.durationMs=Date.now()-n;const l=Ie.endSpan(s,2);return l.statusMessage=u,nt().recordSpan(l),{success:!1,error:u,duration:Date.now()-n}}}static async createClientInternal(e,t){const n=(await this.createTransport(e)).transport;try{const{Client:o}=await Promise.resolve().then(()=>(Gwn(),krr)),i=new o(this.NEUROLINK_IMPLEMENTATION,{capabilities:this.DEFAULT_CAPABILITIES}),s=e.httpOptions?.requestTimeout;if(s!==void 0){const u=i.request.bind(i);i.request=(l,c,d)=>u(l,c,{...d,timeout:Math.min(s,d?.timeout??s),maxTotalTimeout:Math.min(s,d?.maxTotalTimeout??s)})}await this.raceWithTimeout(i.connect(n,{timeout:t}),t,`Client connection timeout for ${e.id}`);const a=await this.performHandshake(i,t);return ae.debug(`[MCPClientFactory] Handshake completed for ${e.id}`,{capabilities:a}),{client:i,transport:n,capabilities:a}}catch(o){try{await n.close()}catch(s){ae.debug("[MCPClientFactory] Error closing transport during cleanup:",s)}const i=this.getStderrTail(n);throw o instanceof Error&&i.length>0?new Error(`${o.message}
1169
1169
  Server stderr (last ${i.length} lines):
1170
1170
  ${i.join(`
1171
1171
  `)}`,{cause:o}):o}}static getStderrTail(e){return Ele.get(e)?.snapshot()??[]}static async createTransport(e){switch(e.transport){case"stdio":return this.createStdioTransport(e);case"sse":return await this.assertNetworkUrlAllowed(e),this.createSSETransport(e);case"websocket":return await this.assertNetworkUrlAllowed(e),this.createWebSocketTransport(e);case"http":return await this.assertNetworkUrlAllowed(e),this.createHTTPTransport(e);default:throw new Error(`Unsupported transport type: ${e.transport}`)}}static async assertNetworkUrlAllowed(e){if(!e.url)throw new Error(`URL is required for ${e.transport} transport`);await Mer(e.url,{transport:e.transport,allowPrivateNetwork:e.allowPrivateNetwork,hostOwnedEgress:typeof e.fetch=="function",serverId:e.id})}static async createStdioTransport(e){if(ae.debug(`[MCPClientFactory] Creating stdio transport for ${e.id}`,{command:e.command,args:e.args}),!e.command)throw new Error("Command is required for stdio transport");const{StdioClientTransport:t,getDefaultEnvironment:r}=await Promise.resolve().then(()=>(Onr(),Kue)),{ChildProcess:n}=await Promise.resolve().then(()=>(Ac(),T3)),o=e.inheritParentEnv===!0?{...process.env}:r(),i=new t({command:e.command,args:e.args||[],env:Object.fromEntries(Object.entries({...o,...e.env}).filter(([,a])=>a!==void 0).map(([a,u])=>[a,String(u)])),cwd:e.cwd,stderr:"pipe"});Aor(i,n);const s=new Sor;return Ele.set(i,s),i.stderr?.on("data",a=>{if(s.append(a),ae.shouldLog("debug")){const u=a.toString().trim();u.length>0&&ae.debug(`[MCPClientFactory] ${e.id} stderr:`,u)}}),{transport:i}}static async createSSETransport(e){if(!e.url)throw new Error("URL is required for SSE transport");ae.debug(`[MCPClientFactory] Creating SSE transport for ${e.id}`,{url:e.url});try{const t=new URL(e.url),{SSEClientTransport:r}=await Promise.resolve().then(()=>(zTn(),dor)),n=this.createEnhancedFetch(e,e.httpOptions?.requestTimeout??6e4);return{transport:new r(t,{requestInit:{headers:e.headers},fetch:n,eventSourceInit:{fetch:n}})}}catch(t){throw new Error(`Invalid SSE URL: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}static async createWebSocketTransport(e){if(!e.url)throw new Error("URL is required for WebSocket transport");ae.debug(`[MCPClientFactory] Creating WebSocket transport for ${e.id}`,{url:e.url});const t=Object.keys(e.headers??{}).length;if(t>0||e.auth!==void 0)throw new Error(`WebSocket transport for ${e.id} cannot send the configured ${t>0?"headers":"auth"}: the WebSocket handshake carries no custom headers. Use the "http" or "sse" transport for an authenticated server, or remove the credentials.`);let r,n;try{r=new URL(e.url),n=await Promise.resolve().then(()=>(GTn(),mor))}catch(a){throw new Error(`Invalid WebSocket URL: ${a instanceof Error?a.message:String(a)}`,{cause:a})}const o=new n.WebSocketClientTransport(r),i=e.httpOptions?.connectionTimeout??3e4,s=o.start.bind(o);return o.start=async()=>{try{await this.raceWithTimeout(s(),i,`WebSocket connection timeout for ${e.id} after ${i}ms`)}catch(a){throw await o.close().catch(()=>{}),a}},{transport:o}}static async createHTTPTransport(e){if(!e.url)throw new Error("URL is required for HTTP transport");const t={connectionTimeout:e.httpOptions?.connectionTimeout??3e4,requestTimeout:e.httpOptions?.requestTimeout??6e4,idleTimeout:e.httpOptions?.idleTimeout??12e4,keepAliveTimeout:e.httpOptions?.keepAliveTimeout??3e4};ae.debug(`[MCPClientFactory] Creating HTTP transport for ${e.id}`,{url:e.url,hasHeaders:!!e.headers,hasAuth:!!e.auth,authType:e.auth?.type,httpOptions:t});try{const r=new URL(e.url),n=await this.setupAuthProvider(e),o={...e.headers??{}};if(e.auth){const l=await this.getAuthorizationHeader(e,n);l&&(o.Authorization=l)}const i=this.createEnhancedFetch(e,t.requestTimeout,n),s={headers:Object.keys(o).length>0?o:void 0},{StreamableHTTPClientTransport:a}=await Promise.resolve().then(()=>(WTn(),wor));return{transport:new a(r,{requestInit:s,fetch:i})}}catch(r){throw new Error(`Invalid HTTP URL: ${r instanceof Error?r.message:String(r)}`,{cause:r})}}static createFetchWithTimeout(e,t){return async(r,n)=>{const o=new AbortController,i=setTimeout(()=>o.abort(),e);try{const s=await t(r,{...n,redirect:"manual",signal:n?.signal?AbortSignal.any([o.signal,n.signal]):o.signal});if(s.status>=300&&s.status<400)throw await s.body?.cancel(),new Error("MCP transport redirects are not permitted");return s}finally{clearTimeout(i)}}}static createEnhancedFetch(e,t,r){const n=this.createFetchWithTimeout(t,e.fetch??globalThis.fetch);return async(o,i)=>{if(r&&e.auth?.type==="oauth2")try{const s=await r.getAuthorizationHeader(e.id);if(s){const a=i?.headers??{},u=new Headers(a);u.set("Authorization",s),i={...i,headers:u}}}catch(s){ae.warn(`[MCPClientFactory] OAuth token refresh failed for ${e.id}:`,s instanceof Error?s.message:String(s))}return n(o,i)}}static async setupAuthProvider(e){if(e.auth?.type==="oauth2"&&e.auth.oauth){const t=new E6,r={clientId:e.auth.oauth.clientId,clientSecret:e.auth.oauth.clientSecret,authorizationUrl:e.auth.oauth.authorizationUrl,tokenUrl:e.auth.oauth.tokenUrl,redirectUrl:e.auth.oauth.redirectUrl,scope:e.auth.oauth.scope,usePKCE:e.auth.oauth.usePKCE??!0},n=new S6(r,t);return ae.debug(`[MCPClientFactory] OAuth provider created for ${e.id}`,{clientId:r.clientId,usePKCE:r.usePKCE}),n}}static async getAuthorizationHeader(e,t){if(e.auth)switch(e.auth.type){case"oauth2":return t?await t.getAuthorizationHeader(e.id)??void 0:void 0;case"bearer":return e.auth.token?`Bearer ${e.auth.token}`:void 0;case"api-key":return;default:return}}static async performHandshake(e,t){try{const r=await this.raceWithTimeout(this.getServerInfo(e),t,"Handshake timeout");return this.extractCapabilities(r)}catch(r){return ae.warn("[MCPClientFactory] Handshake failed, but connection may still be valid:",r),this.DEFAULT_CAPABILITIES}}static async getServerInfo(e){try{return{tools:(await e.listTools()).tools||[],capabilities:this.DEFAULT_CAPABILITIES}}catch{return ae.debug("[MCPClientFactory] Tool listing failed, server may not support tools yet"),{tools:[],capabilities:this.DEFAULT_CAPABILITIES}}}static extractCapabilities(e){return{...this.DEFAULT_CAPABILITIES,...e.tools?{tools:{}}:{}}}static async raceWithTimeout(e,t,r,n){let o,i;const s=new Promise((a,u)=>{o=setTimeout(()=>{u(new Error(r))},t),n&&(i=()=>{clearTimeout(o),u(new Error(`Operation aborted: ${r}`))},n.addEventListener("abort",i))});try{return await Promise.race([e,s])}finally{clearTimeout(o),n&&i&&n.removeEventListener("abort",i)}}static async closeClient(e,t,r){const n=[];try{await e.close()}catch(o){n.push(`Client close error: ${o instanceof Error?o.message:String(o)}`)}try{await t.close()}catch(o){n.push(`Transport close error: ${o instanceof Error?o.message:String(o)}`)}if(r&&!r.killed)try{r.kill("SIGTERM"),await new Promise(o=>{const i=setTimeout(()=>{if(!r.killed){ae.warn("[MCPClientFactory] Force killing process");try{r.kill("SIGKILL")}catch(s){ae.debug("[MCPClientFactory] Error in force kill:",s)}}o()},5e3);r.on("exit",()=>{clearTimeout(i),o()})})}catch(o){n.push(`Process kill error: ${o instanceof Error?o.message:String(o)}`)}n.length>0&&ae.warn("[MCPClientFactory] Errors during client cleanup:",n)}static async testConnection(e,t=5e3){let r,n,o;try{const i=await this.createClient(e,t);if(!i.success)return{success:!1,error:i.error};if(r=i.client,n=i.transport,o=i.process,r)try{await r.listTools()}catch{ae.debug("[MCPClientFactory] Tool listing failed during test, but connection may be valid")}return{success:!0,capabilities:i.capabilities}}catch(i){return{success:!1,error:i instanceof Error?i.message:String(i)}}finally{if(r&&n)try{await this.closeClient(r,n,o)}catch(i){ae.debug("[MCPClientFactory] Error cleaning up test connection:",i)}}}static validateClientConfig(e){const t=[];if(e.command||t.push("Command is required"),e.transport||t.push("Transport is required"),["stdio","sse","websocket","http"].includes(e.transport)||t.push("Transport must be stdio, sse, websocket, or http"),e.transport==="sse"||e.transport==="websocket"||e.transport==="http")if(!e.url)t.push(`URL is required for ${e.transport} transport`);else try{new URL(e.url)}catch{t.push(`Invalid URL for ${e.transport} transport`)}return e.transport==="stdio"&&(Array.isArray(e.args)||t.push("Args array is required for stdio transport")),{isValid:t.length===0,errors:t}}static getSupportedTransports(){return["stdio","sse","websocket","http"]}static getDefaultCapabilities(){return{...this.DEFAULT_CAPABILITIES}}}}});function v$(e){let t;try{t=typeof e=="string"?JSON.parse(e):e}catch{return""}if(!t||typeof t!="object")return"";const r=t.content;return Array.isArray(r)?r.filter(o=>o!==null&&typeof o=="object"&&o.type==="text"&&typeof o.text=="string"&&o.text.length>0).map(o=>o.text).join(" ").substring(0,500):""}function KTn(e){let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return}if(!t||typeof t!="object"||t.isError!==!0)return;const r=v$(t);return r?`MCP tool returned isError: ${r}`:"MCP tool returned isError: true"}function w$(e){const t=KTn(e);return t||(e!==null&&typeof e=="object"&&typeof e.error=="string"&&e.error.length>0?e.error:null)}var xle=S({"src/lib/utils/mcpErrorText.ts"(){"use strict"}});function Cor(e,t){if(t<=0)return"";try{const r=JSON.stringify(e);return typeof r!="string"?"":r.length<=t?r:r.slice(0,Math.max(0,t-1))+"\u2026"}catch{return""}}function b$(e,t=0){if(t>10)return"[...]";if(e==null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>b$(n,t+1));const r={};for(const[n,o]of Object.entries(e))Ior.test(n)?r[n]="[REDACTED]":r[n]=b$(o,t+1);return r}var xor,Ior,Ile,Ror,JTn=S({"src/lib/mcp/toolDiscoveryService.ts"(){"use strict";so(),z(),aue(),_h(),rm(),et(),Fse(),xle(),Kt(),nr(),Mr(),xor=Be.mcp,Ior=/^(password|passwd|secret|token|api[_-]?key|apikey|access[_-]?key|authorization|auth|bearer|credential|cookie|session[_-]?id|private[_-]?key|client[_-]?secret|refresh[_-]?token|x-api-key)$/i,Ile=Math.max(5e3,Number(process.env.MCP_TOOL_TIMEOUT)||6e4),Ror=class extends bn{serverToolStorage=new Map;toolRegistry=new Map;serverTools=new Map;discoveryInProgress=new Set;outputNormalizer;constructor(){super()}setOutputNormalizer(e){this.outputNormalizer=e}async discoverTools(e,t,r=Ile,n=()=>!0,o=!1){return pt({name:"mcp.discoverTools",tracer:Be.mcp,attributes:{"mcp.server_id":e}},async i=>{const s=Date.now();let a=!1;try{if(!n())throw new Error(`Discovery owner for '${e}' is no longer current`);if(this.discoveryInProgress.has(e))return{success:!1,error:`Discovery already in progress for server: ${e}`,toolCount:0,tools:[],duration:Date.now()-s,serverId:e};this.discoveryInProgress.add(e),a=!0,ae.info(`[ToolDiscoveryService] Starting tool discovery for server: ${e}`);const u=()=>this.performToolDiscovery(e,t,r),l=o?await u():await T1.getBreaker(`tool-discovery-${e}`,{failureThreshold:2,resetTimeout:6e4,operationTimeout:r}).execute(u),c=await this.registerDiscoveredTools(e,l,n);i.setAttribute("mcp.tools_discovered",c.length);const d={success:!0,toolCount:c.length,tools:c,duration:Date.now()-s,serverId:e};return this.emit("discoveryCompleted",{serverId:e,toolCount:c.length,duration:d.duration,timestamp:new Date}),ae.info(`[ToolDiscoveryService] Discovery completed for ${e}: ${c.length} tools`),d}catch(u){const l=u instanceof Error?u.message:String(u);return i.setStatus({code:qe.ERROR,message:l}),i.recordException(u instanceof Error?u:new Error(l)),ae.error(`[ToolDiscoveryService] Discovery failed for ${e}:`,u),this.emit("discoveryFailed",{serverId:e,error:l,timestamp:new Date}),{success:!1,error:l,toolCount:0,tools:[],duration:Date.now()-s,serverId:e}}finally{a&&this.discoveryInProgress.delete(e)}})}async performToolDiscovery(e,t,r){const n=await this.raceWithTimeout(t.listTools(),r,"Tool discovery timeout");if(!n||!n.tools)throw new Error("No tools returned from server");return ae.debug(`[ToolDiscoveryService] Discovered ${n.tools.length} tools from ${e}`),n.tools}async registerDiscoveredTools(e,t,r){const n=[];if(!r())throw new Error(`Discovery owner for '${e}' is no longer current`);this.clearServerTools(e);for(const o of t)try{const i=await this.createToolInfo(e,o);if(!r())throw new Error(`Discovery owner for '${e}' is no longer current`);const s=this.validateTool(i);if(!s.isValid){ae.warn(`[ToolDiscoveryService] Skipping invalid tool ${o.name} from ${e}:`,s.errors);continue}s.metadata&&(i.metadata={...i.metadata,...s.metadata});const a=this.createToolKey(e,o.name);this.toolRegistry.set(a,i),this.serverToolStorage.has(e)||this.serverToolStorage.set(e,[]);const u=this.serverToolStorage.get(e);if(!u)throw new Error(`Server tools storage not found for ${e}`);u.find(c=>c.name===o.name)||u.push(i),this.serverTools.has(e)||this.serverTools.set(e,new Set);const l=this.serverTools.get(e);l&&l.add(o.name),n.push(i),this.emit("toolRegistered",{serverId:e,toolName:o.name,toolInfo:i,timestamp:new Date}),ae.debug(`[ToolDiscoveryService] Registered tool: ${o.name} from ${e}`)}catch(i){if(!r())throw i;ae.error(`[ToolDiscoveryService] Failed to register tool ${o.name} from ${e}:`,i)}if(!r())throw new Error(`Discovery owner for '${e}' is no longer current`);return n}async createToolInfo(e,t){return{name:t.name,description:t.description||"No description provided",serverId:e,inputSchema:t.inputSchema,...t.annotations?{annotations:{...t.annotations}}:{},isAvailable:!0,stats:{totalCalls:0,successfulCalls:0,failedCalls:0,averageExecutionTime:0,lastExecutionTime:0},metadata:{category:this.inferToolCategory(t),version:"1.0.0",deprecated:!1}}}inferToolCategory(e){const t=e.name.toLowerCase(),r=(e.description||"").toLowerCase();return t.includes("git")||r.includes("git")?"version-control":t.includes("file")||t.includes("read")||t.includes("write")?"file-system":t.includes("api")||t.includes("http")||t.includes("request")?"api":t.includes("data")||t.includes("query")||t.includes("search")?"data":t.includes("auth")||t.includes("login")||t.includes("token")?"authentication":t.includes("deploy")||t.includes("build")||t.includes("ci")?"deployment":"general"}validateTool(e){const t=[],r=[],n=Zx(e.name);n&&t.push(n.message);const o=RL(e.description);if(o&&r.push(o.message),e.serverId||t.push("Server ID is required"),e.inputSchema)try{JSON.stringify(e.inputSchema)}catch{t.push("Input schema is not valid JSON")}const i={category:typeof e.metadata?.category=="string"?e.metadata.category:"general",complexity:this.inferComplexity(e),requiresAuth:this.inferAuthRequirement(e),isDeprecated:typeof e.metadata?.deprecated=="boolean"?e.metadata.deprecated:!1};return{isValid:t.length===0,errors:t,warnings:r,metadata:i}}inferComplexity(e){const t=e.inputSchema;if(!t||!t.properties)return"simple";const r=Object.keys(t.properties).length;return r<=2?"simple":r<=5?"moderate":"complex"}inferAuthRequirement(e){const t=e.name.toLowerCase(),r=e.description.toLowerCase();return t.includes("auth")||t.includes("login")||t.includes("token")||r.includes("authentication")||r.includes("credentials")||r.includes("permission")}async executeTool(e,t,r,n,o={}){const i=Date.now();try{const s=this.createToolKey(t,e),a=this.toolRegistry.get(s);if(!a)throw new Error(`Tool '${e}' not found for server '${t}'`);if(!a.isAvailable)throw new Error(`Tool '${e}' is not available`);let u=n;o.validateInput!==!1&&(u=this.validateToolParameters(a,n)),ae.debug(`[ToolDiscoveryService] Executing tool: ${e} on ${t}`,{parameters:u});const l=o.timeout||Ile,c=T1.getBreaker(`tool-execution-${t}-${e}`,{failureThreshold:3,resetTimeout:3e4,operationTimeout:l});let d=!1;const p=await c.execute(async h=>xor.startActiveSpan("mcp.callTool",{kind:gn.CLIENT,attributes:{"mcp.server_id":t,"mcp.tool_name":e,"mcp.timeout_ms":l,"ai.tool.name":e,"mcp.request":Cor({name:e,arguments:b$(u)},2048)}},async g=>{try{const y=l,v=await Ge(r.callTool({name:e,arguments:u},void 0,{timeout:l}),y,new Error(`Tool execution timeout: ${e}`)),w=v;if(w&&w.isError===!0){const k=v$(w);g.setStatus({code:qe.ERROR,message:k||`Tool ${e} returned isError`}),d=!0,h(k||`Tool ${e} returned isError`)}else g.setStatus({code:qe.OK});let T=v,E=v;if(this.outputNormalizer)try{const k=await this.outputNormalizer.normalize(v,{toolName:e,serverId:t});g.setAttribute("mcp.output.strategy",k.isExternalized?"externalize":"inline"),k.isExternalized&&g.setAttribute("mcp.output.original_bytes",k.originalBytes),T=k.result,E=k.result}catch(k){ae.warn(`[ToolDiscoveryService] McpOutputNormalizer failed for ${e}: ${k instanceof Error?k.message:String(k)} \u2014 returning raw result`)}return g.setAttribute("mcp.response",Cor(b$(T),2048)),E}catch(y){throw g.setStatus({code:qe.ERROR,message:y.message}),g.recordException(y),y}finally{g.end()}})),m=Date.now()-i;return this.updateToolStats(s,!d,m),o.validateOutput!==!1&&this.validateToolOutput(p),ae.debug(`[ToolDiscoveryService] Tool execution completed: ${e}`,{duration:m,hasContent:!!p?.content}),{success:!0,data:p,isErrorResult:d,duration:m,metadata:{toolName:e,serverId:t,timestamp:Date.now()}}}catch(s){const a=Date.now()-i,u=s instanceof Error?s.message:String(s),l=this.createToolKey(t,e);return this.updateToolStats(l,!1,a),s instanceof uh?(ae.warn(`[ToolDiscoveryService] Tool blocked by circuit breaker: ${e} on ${t}`,{breakerState:s.breakerState,retryAfter:s.retryAfter,retryAfterMs:s.retryAfterMs,failureCount:s.failureCount}),{success:!1,error:s.message,data:{isError:!0,content:[{type:"text",text:`TOOL TEMPORARILY UNAVAILABLE: "${e}" has been disabled after ${s.failureCount} failures. This is a circuit breaker protection \u2014 do NOT retry this tool. It will become available again after ${Math.ceil(s.retryAfterMs/1e3)} seconds (at ${s.retryAfter}). Instead, inform the user that the operation failed and suggest trying again later.`}]},duration:a,metadata:{toolName:e,serverId:t,timestamp:Date.now(),circuitBreaker:{state:s.breakerState,retryAfter:s.retryAfter,retryAfterMs:s.retryAfterMs,failureCount:s.failureCount}}}):(ae.error(`[ToolDiscoveryService] Tool execution failed: ${e}`,s),{success:!1,error:u,duration:a,metadata:{toolName:e,serverId:t,timestamp:Date.now()}})}}validateToolParameters(e,t){if(!e.inputSchema)return t;const r=e.inputSchema,n=r.properties&&typeof r.properties=="object"?r.properties:{},o=Array.isArray(r.required)?r.required.filter(u=>typeof u=="string"):[],i=()=>Object.entries(n).map(([u,l])=>`${u}${o.includes(u)?"":"?"}: ${l.type??"any"}`).join(", "),s=o.filter(u=>!(u in t));if(s.length>0)throw new Error(`Missing required parameter${s.length>1?"s":""}: ${s.join(", ")}. Expected arguments: { ${i()} }; received keys: [${Object.keys(t).join(", ")}]`);let a;for(const[u,l]of Object.entries(n))if(u in t){const c=t[u],d=Lse(c,l);d!==c&&(ae.debug(`[ToolDiscoveryService] Coerced parameter '${u}' for tool '${e.name}': ${typeof c} \u2192 ${typeof d}`),a=a??{...t},a[u]=d),this.validateParameterType(u,a?a[u]:c,l)}return a??t}validateParameterType(e,t,r){if(!r.type)return;const n=r.type,o=typeof t;switch(n){case"string":if(o!=="string")throw new Error(`Parameter '${e}' must be a string, got ${o}`);break;case"number":if(o!=="number")throw new Error(`Parameter '${e}' must be a number, got ${o}`);break;case"integer":if(o!=="number"||!Number.isInteger(t))throw new Error(`Parameter '${e}' must be an integer, got ${o==="number"?String(t):o}`);break;case"boolean":if(o!=="boolean")throw new Error(`Parameter '${e}' must be a boolean, got ${o}`);break;case"array":if(!Array.isArray(t))throw new Error(`Parameter '${e}' must be an array, got ${o}`);break;case"object":if(o!=="object"||t===null||Array.isArray(t))throw new Error(`Parameter '${e}' must be an object, got ${o}`);break}}validateToolOutput(e){if(SXr(e)){ae.debug("[ToolDiscoveryService] Tool returned null/undefined, treating as empty response");return}ae.debug("[ToolDiscoveryService] Tool response received",{type:typeof e,isArray:Array.isArray(e),isObject:XD(e),hasKeys:XD(e)?Object.keys(e).length:0,fullResponse:e})}updateToolStats(e,t,r){const n=this.toolRegistry.get(e);if(!n)return;n.stats.totalCalls++,n.lastCalled=new Date,n.stats.lastExecutionTime=r,t?n.stats.successfulCalls++:n.stats.failedCalls++;const o=n.stats.averageExecutionTime*(n.stats.totalCalls-1)+r;n.stats.averageExecutionTime=o/n.stats.totalCalls}getTool(e,t){const r=this.createToolKey(t,e);return this.toolRegistry.get(r)}getServerTools(e){const t=this.serverToolStorage.get(e);if(t)return t.map(o=>({name:o.name,description:o.description,serverId:e,inputSchema:o.inputSchema,...o.annotations?{annotations:{...o.annotations}}:{},isAvailable:!0,stats:{totalCalls:0,successfulCalls:0,failedCalls:0,averageExecutionTime:0,lastExecutionTime:0}}));const r=[],n=this.serverTools.get(e);if(n)for(const o of n){const i=this.createToolKey(e,o),s=this.toolRegistry.get(i);s&&r.push(s)}return r}getAllTools(){const e=[];for(const[r,n]of this.serverToolStorage.entries())for(const o of n)e.push({name:o.name,description:o.description,serverId:r,inputSchema:o.inputSchema,...o.annotations?{annotations:{...o.annotations}}:{},isAvailable:!0,stats:{totalCalls:0,successfulCalls:0,failedCalls:0,averageExecutionTime:0,lastExecutionTime:0}});const t=Array.from(this.toolRegistry.values()).filter(r=>!e.some(n=>n.name===r.name&&n.serverId===r.serverId));return[...e,...t]}clearServerTools(e){const t=this.serverToolStorage.get(e);if(t){for(const n of t)this.emit("toolUnregistered",{serverId:e,toolName:n.name,timestamp:new Date});this.serverToolStorage.delete(e)}const r=this.serverTools.get(e);if(r){for(const n of r){const o=this.createToolKey(e,n);this.toolRegistry.delete(o),(!t||!t.find(i=>i.name===n))&&this.emit("toolUnregistered",{serverId:e,toolName:n,timestamp:new Date})}this.serverTools.delete(e)}ae.debug(`[ToolDiscoveryService] Cleared tools for server: ${e}`)}updateToolAvailability(e,t,r){const n=this.createToolKey(t,e),o=this.toolRegistry.get(n);o&&(o.isAvailable=r,ae.debug(`[ToolDiscoveryService] Updated availability for ${e}: ${r}`))}createToolKey(e,t){return`${e}:${t}`}async raceWithTimeout(e,t,r){let n;const o=new Promise((i,s)=>{n=setTimeout(()=>{s(new Error(r))},t)});try{return await Promise.race([e,o])}finally{clearTimeout(n)}}destroy(){ae.debug("[ToolDiscoveryService] Starting cleanup..."),this.removeAllListeners(),this.serverToolStorage.clear(),this.toolRegistry.clear(),this.serverTools.clear(),this.discoveryInProgress.clear(),ae.debug("[ToolDiscoveryService] Destroyed and cleaned up")}resetStatistics(){for(const e of this.toolRegistry.values())e.stats={totalCalls:0,successfulCalls:0,failedCalls:0,averageExecutionTime:0,lastExecutionTime:0},e.lastCalled=void 0;ae.debug("[ToolDiscoveryService] Statistics reset for all tools")}getListenerCount(){const e=["discoveryCompleted","discoveryFailed","toolRegistered","toolUnregistered"];let t=0;for(const r of e)t+=this.listenerCount(r);return t}getStatistics(){const e={},t={};let r=0,n=0;for(const o of this.toolRegistry.values()){e[o.serverId]=(e[o.serverId]||0)+1;const i=typeof o.metadata?.category=="string"?o.metadata.category:"unknown";t[i]=(t[i]||0)+1,o.isAvailable?r++:n++}return{totalTools:this.toolRegistry.size,availableTools:r,unavailableTools:n,totalServers:this.serverTools.size,toolsByServer:e,toolsByCategory:t}}}}}),Mor,XTn=S({"src/lib/mcp/registry.ts"(){"use strict";z(),Mor=class{plugins=new Map;register(e){this.plugins.set(e.metadata.name,e),vr.debug(`Registered plugin: ${e.metadata.name}`)}unregister(e){const t=this.plugins.delete(e);return t&&vr.debug(`Unregistered plugin: ${e}`),t}get(e){return this.plugins.get(e)}list(){return Array.from(this.plugins.values())}has(e){return this.plugins.has(e)}clear(){this.plugins.clear(),vr.info("Registry cleared")}async registerServer(e,t,r){const n={metadata:{name:e,description:typeof t=="object"&&t&&t.description||"No description"},tools:typeof t=="object"&&t?t.tools:{},configuration:typeof t=="object"&&t?t:{}};this.register(n)}async executeTool(e,t,r){return vr.info(`Executing tool: ${e}`),{result:`Mock execution of ${e}`,args:t}}async listTools(e){return this.list().map(r=>({name:r.metadata.name,description:r.metadata.description||"No description",serverId:r.metadata.name,category:"general"}))}registerServerSync(e){this.register(e)}executeToolSync(e,t){return vr.info(`Executing tool (sync): ${e}`),{result:`Mock execution of ${e}`,args:t}}listToolsSync(){return this.list().map(t=>({name:t.metadata.name,description:t.metadata.description||"No description"}))}listServers(){return Array.from(this.plugins.keys())}}}});function Ia(e){return e.existingCategory&&["external","in-memory","built-in","user-defined"].includes(e.existingCategory)?e.existingCategory:e.isCustomTool?"user-defined":e.isBuiltIn?"built-in":e.isExternal?"external":e.serverId?.startsWith("custom-tool-")?"user-defined":e.serverId?.includes("external")?"external":e.serverId==="direct"?"built-in":"in-memory"}function YTn(e,t){switch(t){case"external":return`External MCP server: ${e}`;case"built-in":return`Built-in tool server: ${e}`;case"custom":case"user-defined":return`Custom tool server: ${e}`;case"in-memory":return`In-memory MCP server: ${e}`;default:return e}}function Por(e){const t=e.id||`server-${e.name}`,r=e.category||Ia({isCustomTool:e.isCustomTool,isExternal:e.isExternal,isBuiltIn:e.isBuiltIn,serverId:t}),n=e.tools||(e.tool?[e.tool]:[]);return{id:t,name:e.name,transport:e.transport||"stdio",status:e.status||"connected",tools:n,description:e.description||YTn(e.name,r),...e.command&&{command:e.command},...e.args&&{args:e.args},...e.env&&{env:e.env},metadata:{category:r,toolCount:n.length}}}function ZTn(e,t,r,n,o){const i=Por({id:`custom-tool-${e}`,name:e,tool:{name:e,description:t.description||e,inputSchema:t.inputSchema||{},execute:t.execute},isCustomTool:!0});return i.metadata&&(r!==void 0&&(i.metadata.toolTimeoutMs=r),n!==void 0&&(i.metadata.toolMaxRetries=n),o!==void 0&&(i.metadata.toolTotalTimeoutMs=o)),i}var Rle=S({"src/lib/utils/mcpDefaults.ts"(){"use strict"}}),Dor,QTn=S({"src/lib/mcp/flexibleToolValidator.ts"(){"use strict";z(),Dor=class{static MAX_TOOL_NAME_LENGTH=1e3;static MIN_TOOL_NAME_LENGTH=1;static validateToolName(e){const t=[];if(!e||typeof e!="string")return{isValid:!1,error:"Tool name is required and must be a string"};if(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/.test(e))return{isValid:!1,error:"Tool name contains control characters that could break systems"};const n=e.trim();return n.length===0?{isValid:!1,error:"Tool name cannot be empty or whitespace-only"}:n.length<this.MIN_TOOL_NAME_LENGTH?{isValid:!1,error:`Tool name must be at least ${this.MIN_TOOL_NAME_LENGTH} character long`}:n.length>this.MAX_TOOL_NAME_LENGTH?{isValid:!1,error:`Tool name exceeds maximum length of ${this.MAX_TOOL_NAME_LENGTH} characters`}:(n!==e&&t.push("Tool name has leading/trailing whitespace (will be trimmed)"),n.length>200&&t.push("Tool name is unusually long but allowed"),vr.debug(`\u2705 FlexibleToolValidator: Tool '${e}' passed universal safety checks`),{isValid:!0,warnings:t.length>0?t:void 0})}static validateToolInfo(e,t){const r=this.validateToolName(e);if(!r.isValid)return r;const n=[...r.warnings||[]];return t.description&&typeof t.description!="string"?{isValid:!1,error:"Tool description must be a string if provided"}:t.serverId&&typeof t.serverId!="string"?{isValid:!1,error:"Tool serverId must be a string if provided"}:(vr.debug(`\u2705 FlexibleToolValidator: Tool info for '${e}' passed validation`),{isValid:!0,warnings:n.length>0?n:void 0})}static getValidationInfo(){return{philosophy:"Maximum flexibility with universal safety only - following Anthropic's MCP specification",checks:["Empty or whitespace-only names","Excessive length (over 1000 characters)","Control characters that could break systems"],whatIsAllowed:["Dots (github.create_repo, filesystem.read_file)","Hyphens and underscores (my-tool, user_helper)","Numbers (tool1, my_tool_v2)","Unicode characters (\u{1F680}_tool, caf\xE9_manager)","Mixed case (createRepo, ReadFile)","Long descriptive names (enterprise_database_connection_manager)","Any legitimate MCP tool naming pattern"],examples:{valid:["github.create_repo","filesystem.read_file","my-custom-tool","user_helper","tool1","\u{1F680}_rocket_tool","enterprise.database.connection.manager","UPPERCASE_TOOL","mixed_Case.Tool-Name_123"],invalid:[""," ","tool\0","a".repeat(1001)]}}}}}}),Oor={};ue(Oor,{AuthError:()=>Ct,AuthErrorCodes:()=>T$});var T$,Ct,sa=S({"src/lib/auth/errors.ts"(){"use strict";vC(),T$={INVALID_TOKEN:"AUTH-001",EXPIRED_TOKEN:"AUTH-002",MISSING_TOKEN:"AUTH-003",TOKEN_DECODE_FAILED:"AUTH-004",INVALID_SIGNATURE:"AUTH-005",SESSION_NOT_FOUND:"AUTH-010",SESSION_EXPIRED:"AUTH-011",SESSION_REVOKED:"AUTH-012",INSUFFICIENT_PERMISSIONS:"AUTH-020",INSUFFICIENT_ROLES:"AUTH-021",ACCESS_DENIED:"AUTH-022",USER_NOT_FOUND:"AUTH-030",USER_DISABLED:"AUTH-031",EMAIL_NOT_VERIFIED:"AUTH-032",MFA_REQUIRED:"AUTH-033",PROVIDER_ERROR:"AUTH-040",PROVIDER_NOT_FOUND:"AUTH-041",PROVIDER_INIT_FAILED:"AUTH-042",CONFIGURATION_ERROR:"AUTH-043",CREATION_FAILED:"AUTH-050",REGISTRATION_FAILED:"AUTH-051",DUPLICATE_REGISTRATION:"AUTH-052",MIDDLEWARE_ERROR:"AUTH-060",RATE_LIMITED:"AUTH-061",JWKS_FETCH_FAILED:"AUTH-070",JWKS_KEY_NOT_FOUND:"AUTH-071"},Ct=x0("Auth",T$)}}),_$={};ue(_$,{AuthContextHolder:()=>k$,createAuthenticatedContext:()=>qor,getAuthContext:()=>E$,getCurrentSession:()=>Lor,getCurrentUser:()=>$1,globalAuthContext:()=>Ry,hasAllPermissions:()=>Bor,hasAnyRole:()=>Uor,hasPermission:()=>S$,hasRole:()=>Ple,isAuthenticated:()=>$or,requireAuth:()=>Mle,requirePermission:()=>zor,requireRole:()=>Gor,requireUser:()=>For,runWithAuthContext:()=>Nor});function Nor(e,t){return XT.run(e,t)}function E$(){return XT.getStore()??Ry.get()}function $1(){return(XT.getStore()??Ry.get())?.user}function Lor(){return(XT.getStore()??Ry.get())?.session}function $or(){return XT.getStore()!==void 0||Ry.isAuthenticated()}function Mle(){const e=E$();if(!e)throw Ct.create("MISSING_TOKEN","Authentication required");return e}function For(e){const t=Mle();if(t.user.id!==e)throw Ct.create("ACCESS_DENIED","User mismatch");return t}function S$(e){const t=$1();if(!t)return!1;if(t.permissions.includes(e)||t.permissions.includes("*"))return!0;const r=e.split(":");for(let n=r.length-1;n>0;n--){const o=[...r.slice(0,n),"*"].join(":");if(t.permissions.includes(o))return!0}return!1}function Ple(e){return $1()?.roles.includes(e)??!1}function Uor(e){const t=$1();return t?e.some(r=>t.roles.includes(r)):!1}function Bor(e){return e.every(t=>S$(t))}function zor(e){if(!S$(e))throw Ct.create("INSUFFICIENT_PERMISSIONS",`Permission denied: ${e}`)}function Gor(e){if(!Ple(e))throw Ct.create("INSUFFICIENT_ROLES",`Role required: ${e}`)}function qor(e,t,r,n){return{...r,user:e,session:t,request:r,authenticatedAt:new Date,provider:n}}var XT,k$,Ry,F1=S({"src/lib/auth/authContext.ts"(){"use strict";n6(),sa(),XT=new RT,k$=class{context;set(e){this.context=e}get(){return this.context}clear(){this.context=void 0}getUser(){return this.context?.user}getSession(){return this.context?.session}isAuthenticated(){return this.context!==void 0}hasPermission(e){const t=this.context?.user;if(!t)return!1;if(t.permissions.includes(e)||t.permissions.includes("*"))return!0;const r=e.split(":");for(let n=r.length-1;n>0;n--){const o=[...r.slice(0,n),"*"].join(":");if(t.permissions.includes(o))return!0}return!1}hasRole(e){return this.context?.user.roles.includes(e)??!1}},Ry=new k$}}),A$,Dle,Ole=S({"src/lib/mcp/toolRegistry.ts"(){"use strict";XTn(),z(),qt(),QD(),VO(),hZ(),ds(),Rle(),QTn(),et(),Kk(),Rl(),Kt(),F1(),A$=class extends Mor{tools=new Map;toolImplementations=new Map;toolExecutionStats=new Map;builtInServerInfos=[];hitlManager;fileToolRootResolver=()=>HO({});constructor(){super(),kK()||this.registerDirectTools()}setHITLManager(e){this.hitlManager=e,e&&e.isEnabled()?vr.info("HITL safety mechanisms enabled for tool execution"):vr.debug("HITL safety mechanisms disabled or not configured")}getHITLManager(){return this.hitlManager}setFileToolRootResolver(e){this.fileToolRootResolver=e}directToolFor(e,t,r){const n=pZ(r)??this.fileToolRootResolver();return n.roots===null?t:aZ(n)[e]??t}registerDirectTools(){vr.debug("Auto-registering direct tools...");for(const[e,t]of Object.entries(Tb)){if(!t){vr.warn(`Skipping undefined tool during registration: ${e}`);continue}const r=`direct.${e}`,n=bi(t.inputSchema),o={name:e,description:t.description||`Direct tool: ${e}`,inputSchema:n,serverId:"direct",category:Ia({isBuiltIn:!0,serverId:"direct"})};this.tools.set(r,o),this.toolImplementations.set(r,{execute:async(i,s)=>{try{return{success:!0,data:await this.directToolFor(e,t,s).execute(i,{toolCallId:s?.sessionId||"unknown",messages:[]}),metadata:{toolName:e,serverId:"direct",executionTime:0}}}catch(a){return{success:!1,error:a instanceof Error?a.message:String(a),metadata:{toolName:e,serverId:"direct",executionTime:0}}}},description:t.description,inputSchema:n}),vr.debug(`Registered direct tool: ${e} as ${r}`)}vr.debug(`Auto-registered ${Object.keys(Tb).length} direct tools`)}async registerServer(e,t,r){let n;if(typeof e=="string"){const u=e;n=Por({id:u,name:u,tools:[],isExternal:!0})}else n=e;const o=n.id,i={};for(const u of n.tools)i[u.name]={execute:u.execute||(async()=>{throw new Error(`Tool ${u.name} has no execute function`)}),description:u.description,inputSchema:u.inputSchema,category:Ia({existingCategory:n.metadata?.category,serverId:n.id})};const s={metadata:{name:n.name,description:n.description,category:Ia({existingCategory:n.metadata?.category,serverId:n.id})},tools:i,configuration:{}};this.register(s);const a=n.tools;for(const u of a){const c=o.startsWith("custom-tool-")?u.name:`${o}.${u.name}`,d=n.metadata?.toolTimeoutMs,p=n.metadata?.toolMaxRetries,m=n.metadata?.toolTotalTimeoutMs,h={name:u.name,description:u.description,inputSchema:u.inputSchema,outputSchema:void 0,serverId:o,category:Ia({existingCategory:n.metadata?.category,serverId:n.id}),permissions:[],...d!==void 0&&{timeoutMs:d},...p!==void 0&&{maxRetries:p},...m!==void 0&&{totalTimeoutMs:m}};this.tools.set(c,h),this.toolImplementations.set(c,{execute:u.execute||(async()=>{throw new Error(`Tool ${u.name} has no execute function`)}),description:u.description,inputSchema:u.inputSchema,category:Ia({existingCategory:n.metadata?.category,serverId:n.id}),...d!==void 0&&{timeoutMs:d},...p!==void 0&&{maxRetries:p},...m!==void 0&&{totalTimeoutMs:m}})}if(a.length>0){const u=Ia({existingCategory:n.metadata?.category,serverId:n.id});u==="in-memory"&&(this.builtInServerInfos.push(n),vr.debug(`Added ${u} server to builtInServerInfos: ${o} with ${a.length} tools`))}}async executeTool(e,t,r){const n=Date.now();let o;const i=this.tools.get(e);if(i)o=i.serverId;else for(const s of this.tools.values())if(s.name===e){o=s.serverId;break}return pt({name:"tool.registry.execute",tracer:Be.mcp,attributes:{"tool.name":e,[$e.MCP_SERVER_ID]:o||"builtin",[$e.NL_INTERNAL]:!0}},async s=>{try{vr.info(`\u{1F527} [TOOL_EXECUTION] Starting execution: ${e}`,{hasArgs:t!==void 0,hasContext:r!==void 0,sessionId:r?.sessionId});const{tool:a,toolId:u}=this.resolveToolExecutionTarget(e);if(!a)throw new Error(`Tool '${e}' not found in registry`);const l=a.serverId||"unknown",c=l==="direct"?"builtin":l.startsWith("custom-tool-")?"custom":"mcp";s.setAttribute("tool.type",c),s.setAttribute($e.MCP_SERVER_ID,l);const d=this.createExecutionContext(r),p=this.toolImplementations.get(u);if(vr.debug(`Looking for tool '${e}' (toolId: '${u}'), found: ${!!p}, type: ${typeof p?.execute}`),vr.debug("Available tools:",Array.from(this.toolImplementations.keys())),!p||typeof p?.execute!="function")throw new Error(`Tool '${e}' implementation not found or not executable`);let m;try{m=JSON.stringify(t).slice(0,4096)}catch{m="[unserializable]"}s.setAttribute("tool.arguments_present",t!==void 0),s.setAttribute("tool.arguments_size",m.length);let h=t;const g=r?.hitlState;if(!g?.triggered&&this.hitlManager&&this.hitlManager.isEnabled())if(this.hitlManager.requiresConfirmation(e,t)){vr.info(`Tool '${e}' requires HITL confirmation`),s.addEvent("tool.hitl_requested");try{g&&(g.triggered=!0);const k=await this.hitlManager.requestConfirmation(e,t,{serverId:a.serverId,sessionId:d.sessionId,userId:d.userId});if(!k.approved)throw s.addEvent("tool.hitl_rejected"),new Kw(`Tool execution rejected by user: ${k.reason||"No reason provided"}`,e,k.reason);s.addEvent("tool.hitl_approved"),k.modifiedArguments!==void 0&&(h=k.modifiedArguments,vr.info(`Tool '${e}' arguments modified by user`)),vr.info(`Tool '${e}' approved for execution (response time: ${k.responseTime}ms)`)}catch(k){throw k instanceof Wk?(vr.warn(`Tool '${e}' execution timed out waiting for user confirmation`),k):k instanceof Kw?(vr.info(`Tool '${e}' execution rejected by user`),k):(vr.error(`HITL confirmation failed for tool '${e}':`,k),new Error(`HITL confirmation failed: ${k instanceof Error?k.message:String(k)}`,{cause:k}))}}else vr.debug(`Tool '${e}' does not require HITL confirmation`);vr.debug(`Executing tool '${e}' with args:`,h);const y=await p.execute(h,d);let v;if(y&&typeof y=="object"&&"success"in y&&typeof y.success=="boolean"){const E=y;v={...E,usage:{...E.usage||{},executionTime:Date.now()-n},metadata:{...E.metadata||{},toolName:e,serverId:a.serverId,sessionId:d.sessionId,executionTime:Date.now()-n}}}else v={success:!0,data:y,usage:{executionTime:Date.now()-n},metadata:{toolName:e,serverId:a.serverId,sessionId:d.sessionId,executionTime:Date.now()-n}};const w=Date.now()-n;this.updateStats(e,w);let T;try{T=JSON.stringify(v.data)??"undefined"}catch{T="[unserializable]"}return s.setAttribute("tool.result_length",T.length),s.setAttribute("tool.success",!0),vr.debug(`Tool '${e}' executed successfully in ${w}ms`),v}catch(a){vr.error(`Tool execution failed: ${e}`,a),s.setAttribute("tool.success",!1);const u=a instanceof Error?a.message:String(a);if(u.includes("not found in registry")||u.includes("not executable"))throw a;return s.setStatus({code:qe.ERROR,message:u}),a instanceof Error&&s.recordException(a),{success:!1,data:null,error:a instanceof Error?a.message:String(a),usage:{executionTime:Date.now()-n},metadata:{toolName:e,sessionId:r?.sessionId}}}})}async listTools(e){const t=new Map;for(const o of this.tools.values()){const i=`${o.serverId||"unknown"}.${o.name}`;t.has(i)||t.set(i,o)}let r=Array.from(t.values()),n;return e&&("sessionId"in e||"userId"in e?n=void 0:n=e),n&&(n.category&&(r=r.filter(o=>o.category===n.category)),n.serverId&&(r=r.filter(o=>o.serverId===n.serverId)),n.serverCategory&&(r=r.filter(o=>this.get(o.serverId||"")?.metadata?.category===n.serverCategory)),n.permissions&&n.permissions.length>0&&(r=r.filter(o=>{const i=o.permissions||[];return n.permissions?.some(s=>i.includes(s))??!1}))),vr.debug(`Listed ${r.length} unique tools (${n?"filtered":"unfiltered"})`),r}resolveToolExecutionTarget(e){let t=this.tools.get(e);vr.info(`\u{1F50D} [TOOL_LOOKUP] Direct lookup result for '${e}':`,!!t);let r=e;if(!t){const n=Array.from(this.tools.entries()).filter(([,o])=>o.name===e);if(n.length>1)throw ve.toolExecutionFailed(e,new Error(`Ambiguous tool name '${e}'. Use fully-qualified name 'serverId.${e}'.`));n.length===1&&([r,t]=n[0])}return{tool:t,toolId:r}}createExecutionContext(e){let t;try{t=E$()?.user?.id}catch{}return{...e,sessionId:e?.sessionId??st(),userId:e?.userId??t}}getToolInfo(e){let t=this.tools.get(e);if(!t){for(const r of this.tools.values())if(r.name===e){t=r;break}}if(t)return{tool:t,server:{id:t.serverId||"unknown-server"}}}updateStats(e,t){const r=this.toolExecutionStats.get(e)||{count:0,totalTime:0};r.count+=1,r.totalTime+=t,this.toolExecutionStats.set(e,r)}getExecutionStats(){const e={};for(const[t,r]of this.toolExecutionStats.entries())e[t]={count:r.count,totalTime:r.totalTime,averageTime:r.totalTime/r.count};return e}clearStats(){this.toolExecutionStats.clear()}getBuiltInServerInfos(){return this.builtInServerInfos}getToolsByCategory(e){const t=new Map;for(const[r,n]of this.tools.entries())n.category===e&&!t.has(r)&&t.set(r,n);return Array.from(t.values())}getAvailableTools(e){const t=Array.from(this.tools.values()),r=[],n=[];for(const o of t){const i=`${o.serverId||"unknown"}.${o.name}`,s=e.get(i);s&&s.getState()==="open"?r.push(o.name):n.push(o)}return{tools:n,unavailableTools:r}}hasTool(e){if(this.tools.has(e))return!0;for(const t of this.tools.values())if(t.name===e)return!0;return!1}async registerTool(e,t,r){vr.debug(`Registering tool: ${e}`);const n=Dor.validateToolInfo(e,{description:t.description,serverId:t.serverId});if(!n.isValid)throw vr.error(`Tool registration failed for ${e}: ${n.error}`),new Error(`Tool validation failed: ${n.error}`);n.warnings&&n.warnings.length>0&&vr.warn(`Tool registration warnings for ${e}:`,n.warnings),vr.debug(`\u2705 Tool '${e}' passed flexible validation - registration proceeding`),this.tools.set(e,t),this.toolImplementations.set(e,r),vr.debug(`Successfully registered tool: ${e}`)}removeTool(e){let t=!1;if(this.tools.has(e))this.tools.delete(e),this.toolImplementations.delete(e),this.toolExecutionStats.delete(e),vr.info(`Removed tool: ${e}`),t=!0;else for(const[r,n]of Array.from(this.tools.entries()))n.name===e&&(this.tools.delete(r),this.toolImplementations.delete(r),this.toolExecutionStats.delete(r),vr.info(`Removed tool: ${r}`),t=!0);return t}getToolCount(){return this.tools.size}getStats(){const e=this.list(),t=Array.from(this.tools.values()),r={};for(const o of e){const i=o.metadata?.category||"uncategorized";r[i]=(r[i]||0)+1}const n={};for(const o of t){const i=o.category||"uncategorized";n[i]=(n[i]||0)+1}return{totalServers:e.length,totalTools:t.length,serversByCategory:r,toolsByCategory:n,executionStats:this.getExecutionStats()}}unregisterServer(e){const t=[];for(const[i,s]of this.tools.entries())s.serverId===e&&(this.tools.delete(i),this.toolImplementations.delete(i),this.toolExecutionStats.delete(i),t.push(i));const r=this.builtInServerInfos.length;this.builtInServerInfos=this.builtInServerInfos.filter(i=>i.id!==e);const n=r>this.builtInServerInfos.length,o=this.unregister(e);return vr.info(`Unregistered server ${e}, removed ${t.length} tools${n?" and server from builtInServerInfos":""}`),o}},Dle=new A$}});function C$(e,t){if(typeof e=="string")return e.replace(Wor,(r,n)=>{const o=n.trim();if(!Jor.test(o))return ae.warn(`[ExternalServerManager] ${t}: "${r}" is not a valid environment variable reference (names must match ^[A-Z][A-Z0-9_]*$); left as written`),r;const i=process.env[o];return i===void 0?(ae.warn(`[ExternalServerManager] ${t}: environment variable ${o} is not defined, using empty string`),""):i});if(Array.isArray(e))return e.map(r=>C$(r,t));if(Yt(e)){const r={};for(const[n,o]of Object.entries(e))r[n]=C$(o,t);return r}return e}function x$(e,t){if(typeof e=="string"){Kor.test(e)&&ae.warn(`[ExternalServerManager] ${t} contains a \${VAR} reference; environment variables are never expanded in ${t} (only in env and args). The value is used as written.`);return}if(Array.isArray(e)){for(const r of e)x$(r,t);return}if(Yt(e))for(const[r,n]of Object.entries(e))x$(n,`${t}.${r}`)}function jor(e){const t=e instanceof Error?e.message:String(e);return Xor.test(t)}function e_n(e){if(!e||e.length===0)return e;const t=[...e];for(let r=0;r<t.length;r++){const n=t[r].indexOf("=");if(n!==-1){const o=t[r].substring(0,n);Ule.test(o)&&(t[r]=`${o}=[REDACTED]`);continue}Ule.test(t[r])&&r+1<t.length&&!t[r+1].startsWith("--")&&(t[r+1]="[REDACTED]",r++)}return t}function Nle(e){return XD(e)?Object.values(e).every(r=>r===null||typeof r=="string"||typeof r=="number"||typeof r=="boolean"?!0:Array.isArray(r)?r.every(n=>Nle(n)||typeof n=="string"||typeof n=="number"||typeof n=="boolean"||n===null):Yt(r)?Nle(r):!1):!1}function I$(e){return Nle(e)?e:void 0}function t_n(e){if(!Yt(e))return!1;const t=e;if(t.blockedTools!==void 0&&(!Array.isArray(t.blockedTools)||!t.blockedTools.every(o=>typeof o=="string")))return!1;const r=typeof t.command=="string",n=typeof t.url=="string";return!r&&!n?!1:(t.command===void 0||typeof t.command=="string")&&(t.args===void 0||Array.isArray(t.args))&&(t.env===void 0||Yt(t.env))&&(t.transport===void 0||typeof t.transport=="string")&&(t.timeout===void 0||typeof t.timeout=="number")&&(t.retries===void 0||typeof t.retries=="number")&&(t.healthCheckInterval===void 0||typeof t.healthCheckInterval=="number")&&(t.autoRestart===void 0||typeof t.autoRestart=="boolean")&&(t.cwd===void 0||typeof t.cwd=="string")&&(t.url===void 0||typeof t.url=="string")&&(t.headers===void 0||Yt(t.headers))&&(t.httpOptions===void 0||Yt(t.httpOptions))&&(t.retryConfig===void 0||Yt(t.retryConfig))&&(t.rateLimiting===void 0||Yt(t.rateLimiting))&&(t.inheritParentEnv===void 0||typeof t.inheritParentEnv=="boolean")&&(t.allowPrivateNetwork===void 0||typeof t.allowPrivateNetwork=="boolean")&&(t.metadata===void 0||Yt(t.metadata))}function Vor(e,t){if(!t_n(t))throw new Error(`Invalid server config for ${e}: missing required properties or wrong types`);return t.headers!==void 0&&x$(t.headers,`${e}.headers`),t.url!==void 0&&x$(t.url,`${e}.url`),{id:e,name:e,description:typeof t.description=="string"?t.description:`External MCP server: ${e}`,transport:typeof t.transport=="string"?t.transport:"stdio",status:"initializing",tools:[],command:typeof t.command=="string"?t.command:void 0,args:Array.isArray(t.args)?C$(t.args.map(r=>String(r)),`${e}.args`):[],env:Yt(t.env)?C$(t.env,`${e}.env`):{},inheritParentEnv:typeof t.inheritParentEnv=="boolean"?t.inheritParentEnv:void 0,allowPrivateNetwork:typeof t.allowPrivateNetwork=="boolean"?t.allowPrivateNetwork:void 0,timeout:typeof t.timeout=="number"?t.timeout:void 0,retries:typeof t.retries=="number"?t.retries:void 0,healthCheckInterval:typeof t.healthCheckInterval=="number"?t.healthCheckInterval:void 0,autoRestart:typeof t.autoRestart=="boolean"?t.autoRestart:void 0,cwd:typeof t.cwd=="string"?t.cwd:void 0,url:typeof t.url=="string"?t.url:void 0,headers:Yt(t.headers)?t.headers:void 0,fetch:Hor(t.fetch),httpOptions:Yt(t.httpOptions)?t.httpOptions:void 0,retryConfig:Yt(t.retryConfig)?t.retryConfig:void 0,rateLimiting:Yt(t.rateLimiting)?t.rateLimiting:void 0,blockedTools:Array.isArray(t.blockedTools)?t.blockedTools:void 0,metadata:I$(t.metadata)}}var Lle,Hor,Wor,Kor,Jor,Xor,$le,Fle,Ule,R$,Ble,zle,Yor,Zor,Qor,M$,eir,Gle,tir=S({"src/lib/mcp/externalServerManager.ts"(){"use strict";so(),z(),Cle(),JTn(),Ole(),Kk(),Rle(),_h(),vse(),nr(),Kt(),process.stdin&&typeof process.stdin.unref=="function"&&(process.stdin.unref(),process.stdin.prependListener("newListener",e=>{(e==="data"||e==="readable")&&process.stdin.ref()})),Lle=e=>typeof e=="function",Hor=e=>{if(e!=null){if(!Lle(e))throw new Error("MCP fetch hook must be a function");return e}},Wor=/\$\{([^}]*)\}/g,Kor=/\$\{[^}]*\}/,Jor=/^[A-Z][A-Z0-9_]*$/,Xor=/^Not connected$|MCP error -32000: Connection closed/,$le=class extends Error{constructor(e,t,r){super(`Server '${e}' discovered ${t} tool(s), below the configured minTools=${r}`),this.serverId=e,this.toolsDiscovered=t,this.minTools=r,this.name="InsufficientToolsError"}serverId;toolsDiscovered;minTools;readiness="insufficient_tools"},Fle=2,Ule=/^--(api-key|token|secret|password|key|figma-api-key|access-token|auth|credential)$/i,R$=new Set,Ble=!1,zle=async()=>{await Promise.all(Array.from(R$).map(e=>e.shutdown().catch(t=>{ae.error("[ExternalServerManager] Error during process-exit cleanup:",t)})))},Yor=()=>{zle()},Zor=Symbol.for("signal-exit emitter"),Qor=()=>{const t=globalThis[Zor]?.count;return typeof t=="number"&&t>0?t:0},M$=e=>{const t=process.listenerCount(e)-Qor()>1;zle().finally(()=>{t||(process.removeListener(e,M$),y$(),process.kill(process.pid,e))})},eir=e=>{R$.add(e),Ble||(Ble=!0,process.prependListener("SIGINT",M$),process.prependListener("SIGTERM",M$),process.on("beforeExit",Yor))},Gle=class extends bn{servers=new Map;config;isShuttingDown=!1;healthChecksInFlight=new Set;inFlightToolCalls=new Map;unresponsiveChecks=new Map;consecutiveFailures=new Map;retryDeadlines=new Map;lastHealth=new Map;lifecycleStates=new Map;closedClients=new WeakSet;toolDiscovery;enableMainRegistryIntegration;hitlManager;constructor(e={},t={}){super();const r=Math.max(5e3,Number(process.env.MCP_CLIENT_TIMEOUT)||6e4);this.config={maxServers:e.maxServers??10,defaultTimeout:e.defaultTimeout??r,defaultHealthCheckInterval:e.defaultHealthCheckInterval??3e4,enableAutoRestart:e.enableAutoRestart??!0,maxRestartAttempts:e.maxRestartAttempts??3,restartBackoffMultiplier:e.restartBackoffMultiplier??2,enablePerformanceMonitoring:e.enablePerformanceMonitoring??!0,logLevel:e.logLevel??"info"},this.enableMainRegistryIntegration=t.enableMainRegistryIntegration??!1,this.toolDiscovery=new Ror,this.toolDiscovery.on("toolRegistered",n=>{this.emit("toolDiscovered",{...n,serverName:this.getServerName(n.serverId)})}),this.toolDiscovery.on("toolUnregistered",n=>{this.emit("toolRemoved",{...n,serverName:this.getServerName(n.serverId)})}),eir(this)}setOutputNormalizer(e){this.toolDiscovery.setOutputNormalizer(e),ae.debug("[ExternalServerManager] MCP output normalizer attached to ToolDiscoveryService")}setHITLManager(e){this.hitlManager=e,e&&e.isEnabled()?ae.info("[ExternalServerManager] HITL safety mechanisms enabled for external tool execution"):ae.debug("[ExternalServerManager] HITL safety mechanisms disabled or not configured")}getHITLManager(){return this.hitlManager}getServerName(e){return this.servers.get(e)?.config?.name||e}async loadMCPConfiguration(e,t={}){return t.parallel?this.loadMCPConfigurationParallel(e):this.loadMCPConfigurationSequential(e)}async loadMCPConfigurationParallel(e){const t=await Promise.resolve().then(()=>(ro(),kd)),r=await Promise.resolve().then(()=>(Sr(),Xm)),n=e||r.join(process.cwd(),".mcp-config.json");if(!t.existsSync(n))return ae.debug(`[ExternalServerManager] No MCP config found at ${n}`),{serversLoaded:0,errors:[]};ae.debug(`[ExternalServerManager] Loading MCP configuration in PARALLEL mode from ${n}`);try{const o=t.readFileSync(n,"utf8"),i=JSON.parse(o);if(!i.mcpServers||typeof i.mcpServers!="object")return ae.debug("[ExternalServerManager] No mcpServers found in configuration"),{serversLoaded:0,errors:[]};const s=Object.entries(i.mcpServers).map(async([c,d])=>{try{const p=Vor(c,d),m=await this.addServer(c,p);return{serverId:c,result:m}}catch(p){const m=`Failed to load MCP server ${c}: ${p instanceof Error?p.message:String(p)}`;return{serverId:c,error:m}}}),a=await Promise.allSettled(s);let u=0;const l=[];for(const c of a)if(c.status==="fulfilled"){const{serverId:d,result:p,error:m}=c.value;if(p&&p.success)u++,ae.debug(`[ExternalServerManager] Successfully loaded MCP server in parallel: ${d}`);else if(m)l.push(m),ae.error(`[ExternalServerManager] Failed to load server ${d}: ${m}`);else if(p&&!p.success){const h=`Failed to load server ${d}: ${p.error}`;l.push(h),ae.error(`[ExternalServerManager] ${h}`)}}else{const d=`Unexpected error during parallel loading: ${c.reason}`;l.push(d),ae.error(`[ExternalServerManager] ${d}`)}return ae.info(`[ExternalServerManager] PARALLEL MCP configuration loading complete: ${u} servers loaded, ${l.length} errors`),{serversLoaded:u,errors:l}}catch(o){const i=`Failed to load MCP configuration in parallel mode: ${o instanceof Error?o.message:String(o)}`;return ae.error(`[ExternalServerManager] ${i}`),{serversLoaded:0,errors:[i]}}}async loadMCPConfigurationSequential(e){const t=await Promise.resolve().then(()=>(ro(),kd)),r=await Promise.resolve().then(()=>(Sr(),Xm)),n=e||r.join(process.cwd(),".mcp-config.json");if(!t.existsSync(n))return ae.debug(`[ExternalServerManager] No MCP config found at ${n}`),{serversLoaded:0,errors:[]};ae.debug(`[ExternalServerManager] Loading MCP configuration from ${n}`);try{const o=t.readFileSync(n,"utf8"),i=JSON.parse(o);if(!i.mcpServers||typeof i.mcpServers!="object")return ae.debug("[ExternalServerManager] No mcpServers found in configuration"),{serversLoaded:0,errors:[]};let s=0;const a=[];for(const[u,l]of Object.entries(i.mcpServers))try{const c=Vor(u,l),d=await this.addServer(u,c);if(d.success)s++,ae.debug(`[ExternalServerManager] Successfully loaded MCP server: ${u}`);else{const p=`Failed to load server ${u}: ${d.error}`;a.push(p),ae.error(`[ExternalServerManager] ${p}`)}}catch(c){const d=`Failed to load MCP server ${u}: ${c instanceof Error?c.message:String(c)}`;a.push(d),ae.error(`[ExternalServerManager] ${d}`)}return ae.info(`[ExternalServerManager] MCP configuration loading complete: ${s} servers loaded, ${a.length} errors`),{serversLoaded:s,errors:a}}catch(o){const i=`Failed to load MCP configuration: ${o instanceof Error?o.message:String(o)}`;return ae.error(`[ExternalServerManager] ${i}`),{serversLoaded:0,errors:[i]}}}validateConfig(e){const t=[],r=[],n=[];(!e.id||typeof e.id!="string")&&t.push("Server ID is required and must be a string"),["stdio","sse","websocket","http"].includes(e.transport)||t.push("Transport must be one of: stdio, sse, websocket, http"),e.fetch!==void 0&&!Lle(e.fetch)&&t.push("MCP fetch hook must be a function");for(const[o,i]of Object.entries({connectionTimeout:e.httpOptions?.connectionTimeout,requestTimeout:e.httpOptions?.requestTimeout}))i!==void 0&&(!Number.isFinite(i)||i<=0)&&t.push(`${o} must be a positive finite number`);return e.transport==="stdio"?((!e.command||typeof e.command!="string")&&t.push("Command is required and must be a string for stdio transport"),Array.isArray(e.args)||t.push("Args must be an array")):(e.transport==="sse"||e.transport==="websocket"||e.transport==="http")&&(!e.url||typeof e.url!="string")&&t.push(`URL is required for ${e.transport} transport`),e.timeout&&e.timeout<5e3&&r.push("Timeout less than 5 seconds may cause connection issues"),e.retries&&e.retries>5&&r.push("High retry count may slow down error recovery"),e.healthCheckInterval||n.push("Consider setting a health check interval for better reliability"),e.autoRestart===void 0&&n.push("Consider enabling auto-restart for production use"),{isValid:t.length===0,errors:t,warnings:r,suggestions:n}}convertConfigToMCPServerInfo(e,t){return{id:e,name:String(t.metadata?.title||e),description:`External MCP server (${t.transport})`,status:"initializing",transport:t.transport,command:t.command,args:t.args,env:t.env,tools:[],blockedTools:t.blockedTools,timeout:t.timeout,retries:t.retries,healthCheckInterval:t.healthCheckInterval,autoRestart:t.autoRestart,minTools:t.minTools,cwd:t.cwd,inheritParentEnv:t.inheritParentEnv,allowPrivateNetwork:t.allowPrivateNetwork,url:t.url,headers:t.headers,fetch:t.fetch,httpOptions:t.httpOptions,retryConfig:t.retryConfig,rateLimiting:t.rateLimiting,auth:t.auth,metadata:{category:"external",...I$(t.metadata)||{}}}}async addServer(e,t){const r=Date.now();let n;try{const o="transport"in t&&"command"in t&&!("tools"in t)?this.convertConfigToMCPServerInfo(e,t):t;if(this.servers.size>=this.config.maxServers)return{success:!1,error:`Maximum number of servers (${this.config.maxServers}) reached`,serverId:e,duration:Date.now()-r};const i={id:e,name:o.name,description:o.description,transport:o.transport,status:o.status,tools:o.tools,command:o.command||"",args:o.args||[],env:o.env||{},timeout:o.timeout,retries:o.retries,healthCheckInterval:o.healthCheckInterval,autoRestart:o.autoRestart,minTools:o.minTools,cwd:o.cwd,inheritParentEnv:o.inheritParentEnv,allowPrivateNetwork:o.allowPrivateNetwork,url:o.url,blockedTools:o.blockedTools,metadata:I$(o.metadata),headers:o.headers,auth:o.auth,fetch:o.fetch,httpOptions:o.httpOptions,retryConfig:o.retryConfig,rateLimiting:o.rateLimiting},s=this.validateConfig(i);if(!s.isValid)return{success:!1,error:`Configuration validation failed: ${s.errors.join(", ")}`,serverId:e,duration:Date.now()-r};if(this.servers.has(e))return{success:!1,error:`Server with ID '${e}' already exists`,serverId:e,duration:Date.now()-r};ae.info(`[ExternalServerManager] Adding server: ${e}`,{command:o.command,transport:o.transport});const a={...o,process:null,client:null,transportInstance:null,status:"initializing",reconnectAttempts:0,maxReconnectAttempts:this.config.maxRestartAttempts,toolsMap:new Map,metrics:{totalConnections:0,totalDisconnections:0,totalErrors:0,totalToolCalls:0,averageResponseTime:0,lastResponseTime:0},config:i};n=a,this.servers.set(e,a),await this.startServer(e);const u=this.servers.get(e);if(!u)throw new Error(`Server ${e} not found after registration`);return{success:!0,data:{config:u.config,process:u.process,pid:u.pid,client:u.client,transport:u.transportInstance,status:u.status,lastError:u.lastError,startTime:u.startTime,lastHealthCheck:u.lastHealthCheck,reconnectAttempts:u.reconnectAttempts,maxReconnectAttempts:u.maxReconnectAttempts,tools:u.toolsMap,toolsArray:u.toolsArray,capabilities:u.capabilities,healthTimer:u.healthTimer,restartTimer:u.restartTimer,metrics:u.metrics},serverId:e,duration:Date.now()-r,metadata:{timestamp:Date.now(),operation:"addServer",readiness:"ready",toolsDiscovered:u.tools.length}}}catch(o){return ae.debug(`[ExternalServerManager] Failed to add server ${e}:`,o),n!==void 0&&this.servers.get(e)===n&&n.status!=="stopping"&&(this.servers.delete(e),this.consecutiveFailures.delete(e),this.retryDeadlines.delete(e),this.lastHealth.delete(e),this.lifecycleStates.delete(e)),o instanceof $le?{success:!1,error:o.message,serverId:e,duration:Date.now()-r,metadata:{timestamp:Date.now(),operation:"addServer",readiness:o.readiness,toolsDiscovered:o.toolsDiscovered}}:{success:!1,error:o instanceof Error?o.message:String(o),serverId:e,duration:Date.now()-r}}}async removeServer(e){const t=Date.now();try{const r=this.servers.get(e);if(!r)return{success:!1,error:`Server '${e}' not found`,serverId:e,duration:Date.now()-t};ae.info(`[ExternalServerManager] Removing server: ${e}`);const n=this.getServerName(e);return await this.stopServer(e),this.servers.get(e)===r&&(this.servers.delete(e),this.consecutiveFailures.delete(e),this.retryDeadlines.delete(e),this.lastHealth.delete(e),this.lifecycleStates.delete(e),this.emit("disconnected",{serverId:e,serverName:n,reason:"Manually removed",timestamp:new Date})),{success:!0,serverId:e,duration:Date.now()-t,metadata:{timestamp:Date.now(),operation:"removeServer"}}}catch(r){return ae.error(`[ExternalServerManager] Failed to remove server ${e}:`,r),{success:!1,error:r instanceof Error?r.message:String(r),serverId:e,duration:Date.now()-t}}}async startServer(e){const t=this.servers.get(e);if(!t)throw new Error(`Server '${e}' not found`);const r=t.config,n=Be.mcp.startSpan("mcp.server.start",{attributes:{"mcp.server_id":e,"mcp.transport":r.transport,"mcp.command_name":r.command&&r.command.split(/[\\/]/).pop()||"","mcp.command_present":!!r.command}});try{this.updateServerStatus(e,"connecting"),this.toolDiscovery.clearServerTools(e),t.toolsMap.clear(),t.toolsArray=void 0,t.tools=[],ae.debug(`[ExternalServerManager] Starting server: ${e}`,{command:r.command,args:e_n(r.args),transport:r.transport});const o=await wf.createClient(r,r.timeout||this.config.defaultTimeout);if(!o.success||!o.client||!o.transport)throw new Error(`Failed to create MCP client: ${o.error}`);if(this.servers.get(e)!==t||this.isShuttingDown)throw await wf.closeClient(o.client,o.transport,o.process??void 0),new Error(`MCP startup for '${e}' was superseded`);t.client=o.client,t.transportInstance=o.transport,t.process=o.process||null;const{StdioClientTransport:i}=await Promise.resolve().then(()=>(Onr(),Kue));t.pid=o.transport instanceof i?o.transport.pid??void 0:void 0,t.capabilities=I$(o.capabilities),t.startTime=new Date,t.lastHealthCheck=new Date,t.metrics.totalConnections++,this.unresponsiveChecks.delete(e),this.attachClientLifecycle(e,o.client,o.transport);const s=()=>{if(this.servers.get(e)!==t||t.client!==o.client||o.client.transport!==o.transport||this.closedClients.has(o.client)||t.status!=="initializing"||this.isShuttingDown)throw new Error(`MCP connection for '${e}' was lost during startup`)};s(),await this.discoverServerTools(e),s();const a=r.minTools??0;if(t.toolsMap.size<a){const u=t.toolsMap.size;throw ae.warn(`[ExternalServerManager] Server '${e}' discovered ${u} tool(s), below the configured minTools=${a}; tearing the connection back down`),await this.closeInstanceConnection(e,t),new $le(e,u,a)}this.enableMainRegistryIntegration&&await this.registerServerToolsWithMainRegistry(e),s(),this.consecutiveFailures.delete(e),this.lastHealth.delete(e),this.retryDeadlines.delete(e),t.lastError=void 0,this.updateServerStatus(e,"connected"),this.startHealthMonitoring(e),this.emit("connected",{serverId:e,serverName:this.getServerName(e),toolCount:t.toolsMap.size,timestamp:new Date}),n.setAttribute("mcp.tool_count",t.toolsMap.size),n.setStatus({code:qe.OK}),ae.info(`[ExternalServerManager] Server started successfully: ${e}`)}catch(o){if(ae.debug(`[ExternalServerManager] Failed to start server ${e}:`,o),this.servers.get(e)===t&&t.status!=="stopping"){await this.closeInstanceConnection(e,t);const i=this.servers.get(e);i===t&&i.status!=="stopping"&&!this.isShuttingDown&&(this.updateServerStatus(e,"failed",t),t.lastError=o instanceof Error?o.message:String(o),this.consecutiveFailures.set(e,(this.consecutiveFailures.get(e)??0)+1),this.emit("failed",{serverId:e,serverName:this.getServerName(e),error:t.lastError,timestamp:new Date}))}else this.servers.get(e)!==t&&t.client&&t.transportInstance&&(t.client.onclose=void 0,t.client.onerror=void 0,await wf.closeClient(t.client,t.transportInstance,t.process??void 0),t.client=null,t.transportInstance=null,t.process=null);throw n.recordException(o instanceof Error?o:new Error(String(o))),n.setStatus({code:qe.ERROR,message:o instanceof Error?o.message:String(o)}),o}finally{n.end()}}async closeInstanceConnection(e,t){if(this.enableMainRegistryIntegration&&this.unregisterServerToolsFromMainRegistry(e),this.toolDiscovery.clearServerTools(e),t.toolsMap.clear(),t.toolsArray=void 0,t.tools=[],!(!t.client||!t.transportInstance)){t.client.onclose=void 0,t.client.onerror=void 0;try{await wf.closeClient(t.client,t.transportInstance,t.process??void 0)}catch(r){ae.debug(`[ExternalServerManager] Error closing client for ${e}:`,r)}t.client=null,t.transportInstance=null,t.process=null,t.pid=void 0}}async stopServer(e){const t=this.servers.get(e);if(!t)return;const r=Be.mcp.startSpan("mcp.server.stop",{attributes:{"mcp.server_id":e}});try{this.updateServerStatus(e,"stopping",t),t.healthTimer&&(clearInterval(t.healthTimer),t.healthTimer=void 0),t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0),this.enableMainRegistryIntegration&&this.unregisterServerToolsFromMainRegistry(e),this.toolDiscovery.clearServerTools(e),await this.closeInstanceConnection(e,t),this.updateServerStatus(e,"stopped",t),r.setStatus({code:qe.OK}),ae.info(`[ExternalServerManager] Server stopped: ${e}`)}catch(n){ae.error(`[ExternalServerManager] Error stopping server ${e}:`,n),this.updateServerStatus(e,"failed",t),r.recordException(n instanceof Error?n:new Error(String(n))),r.setStatus({code:qe.ERROR,message:n instanceof Error?n.message:String(n)})}finally{r.end()}}updateServerStatus(e,t,r){const n=this.servers.get(e);if(!n||r!==void 0&&n!==r)return;const o=n.status;this.lifecycleStates.set(e,t);const i=t==="connecting"||t==="restarting"?"initializing":t==="stopping"||t==="stopped"?"stopping":t==="connected"?"connected":t==="disconnected"?"disconnected":"failed";n.status=i,this.emit("statusChanged",{serverId:e,serverName:this.getServerName(e),oldStatus:o,newStatus:t,timestamp:new Date}),ae.debug(`[ExternalServerManager] Status changed for ${e}: ${o} -> ${t}`)}attachClientLifecycle(e,t,r){t.onclose=()=>{this.closedClients.add(t);const n=this.servers.get(e),o=n?.pid?` (pid ${n.pid})`:"",i=wf.getStderrTail(r),s=i.length>0?`Server process closed${o}; last stderr: ${i.slice(-5).join(" | ")}`:`Server process closed${o}`;this.handleConnectionLost(e,t,s,i)},t.onerror=n=>{ae.warn(`[ExternalServerManager] Transport error for ${e}: ${n.message}`)}}handleConnectionLost(e,t,r,n=[],o=!1){const i=this.servers.get(e);!i||i.client!==t||i.status!=="connected"||(ae.warn(`[ExternalServerManager] Connection lost for ${e}: ${r}`,n.length>0?{stderrTail:n}:void 0),i.lastError=r,this.handleServerDisconnection(e,r,o))}trackToolCall(e,t){const r=(this.inFlightToolCalls.get(e)??0)+t;r<=0?this.inFlightToolCalls.delete(e):this.inFlightToolCalls.set(e,r)}handleServerError(e,t){const r=this.servers.get(e);r&&(r.lastError=t.message,r.metrics.totalErrors++,this.consecutiveFailures.set(e,(this.consecutiveFailures.get(e)??0)+1),ae.error(`[ExternalServerManager] Server error for ${e}:`,t),this.emit("failed",{serverId:e,serverName:this.getServerName(e),error:t.message,timestamp:new Date}),(r.config.autoRestart??this.config.enableAutoRestart)&&!this.isShuttingDown?this.scheduleRestart(e):this.updateServerStatus(e,"failed"))}handleServerDisconnection(e,t,r=!1){const n=this.servers.get(e);n&&(n.metrics.totalDisconnections++,r||this.consecutiveFailures.set(e,(this.consecutiveFailures.get(e)??0)+1),ae.warn(`[ExternalServerManager] Server disconnected ${e}: ${t}`),this.emit("disconnected",{serverId:e,serverName:this.getServerName(e),reason:t,timestamp:new Date}),(n.config.autoRestart??this.config.enableAutoRestart)&&!this.isShuttingDown?this.scheduleRestart(e):this.updateServerStatus(e,"disconnected"))}scheduleRestart(e){const t=this.servers.get(e);if(!t||t.restartTimer)return;if(t.reconnectAttempts>=t.maxReconnectAttempts){ae.error(`[ExternalServerManager] Max restart attempts reached for ${e}`),this.updateServerStatus(e,"failed"),this.retryDeadlines.delete(e);return}t.reconnectAttempts++,this.updateServerStatus(e,"restarting");const r=Math.min(1e3*Math.pow(this.config.restartBackoffMultiplier,t.reconnectAttempts-1),3e4);ae.info(`[ExternalServerManager] Scheduling restart for ${e} in ${r}ms (attempt ${t.reconnectAttempts})`),this.retryDeadlines.set(e,new Date(Date.now()+r));const n=this.getServerStatuses().find(o=>o.serverId===e);n&&this.emit("healthCheck",{serverId:e,serverName:this.getServerName(e),health:n,timestamp:new Date}),t.restartTimer=setTimeout(async()=>{this.retryDeadlines.delete(e);const o=Be.mcp.startSpan("mcp.server.restart",{attributes:{"mcp.server_id":e,"mcp.restart_attempt":t.reconnectAttempts,"mcp.restart_delay_ms":r}});try{if(this.servers.get(e)!==t||(await this.stopServer(e),this.servers.get(e)!==t)||(await this.startServer(e),this.servers.get(e)!==t))return;t.reconnectAttempts=0,o.setStatus({code:qe.OK})}catch(i){ae.error(`[ExternalServerManager] Restart failed for ${e}:`,i),o.recordException(i instanceof Error?i:new Error(String(i))),o.setStatus({code:qe.ERROR,message:i instanceof Error?i.message:String(i)}),this.servers.get(e)===t&&this.scheduleRestart(e)}finally{o.end()}},r)}startHealthMonitoring(e){const t=this.servers.get(e);if(!t||!this.config.enablePerformanceMonitoring)return;const r=t.config.healthCheckInterval??this.config.defaultHealthCheckInterval;t.healthTimer=setInterval(async()=>{await this.performHealthCheck(e)},r),t.healthTimer.unref&&t.healthTimer.unref()}async performHealthCheck(e){const t=this.servers.get(e);if(!t||t.status!=="connected"||!t.client||this.healthChecksInFlight.has(e))return;this.healthChecksInFlight.add(e);const r=t.client,n=t.config.healthCheckInterval??this.config.defaultHealthCheckInterval,o=Math.max(1,Math.min(t.config.timeout||this.config.defaultTimeout,n)),i=Date.now(),s=[];let a=!0,u=!1,l=!1;try{try{if(await r.ping({timeout:o}),t.client!==r||t.status!=="connected")return;this.unresponsiveChecks.delete(e),this.consecutiveFailures.delete(e),t.lastError=void 0}catch(p){if(t.client!==r||t.status!=="connected")return;if(a=!1,this.consecutiveFailures.set(e,(this.consecutiveFailures.get(e)??0)+1),t.lastError=p instanceof Error?p.message:String(p),jor(p))u=!0,s.push("connection closed");else{const m=this.inFlightToolCalls.get(e)??0;if(m>0)s.push(`ping timed out after ${o}ms while ${m} tool call(s) in flight`);else{const h=(this.unresponsiveChecks.get(e)??0)+1;this.unresponsiveChecks.set(e,h),s.push(`ping timed out after ${o}ms while idle (${h}/${Fle})`),l=h>=Fle}}}const c=Date.now()-i;t.lastHealthCheck=new Date;const d={serverId:e,isHealthy:a,status:this.lifecycleStates.get(e)??t.status,checkedAt:new Date,responseTime:c,toolCount:t.toolsMap.size,issues:s,consecutiveFailures:this.consecutiveFailures.get(e)??0,lastError:t.lastError,nextRetryAt:this.retryDeadlines.get(e),performance:{uptime:t.startTime?Date.now()-t.startTime.getTime():0,averageResponseTime:t.metrics.averageResponseTime}};this.lastHealth.set(e,d),this.emit("healthCheck",{serverId:e,serverName:this.getServerName(e),health:d,timestamp:new Date}),u||l?this.handleConnectionLost(e,r,`Health check failed: ${s.join(", ")}`,[],!0):a||ae.warn(`[ExternalServerManager] Health check failed for ${e}:`,s)}catch(c){ae.error(`[ExternalServerManager] Health check error for ${e}:`,c)}finally{this.healthChecksInFlight.delete(e)}}getServer(e){const t=this.servers.get(e);if(t)return{config:t.config,process:t.process,pid:t.pid,client:t.client,transport:t.transportInstance,status:t.status,lastError:t.lastError,startTime:t.startTime,lastHealthCheck:t.lastHealthCheck,reconnectAttempts:t.reconnectAttempts,maxReconnectAttempts:t.maxReconnectAttempts,tools:t.toolsMap,toolsArray:t.toolsArray,capabilities:t.capabilities,healthTimer:t.healthTimer,restartTimer:t.restartTimer,metrics:t.metrics}}getAllServers(){const e=new Map;for(const[t,r]of this.servers.entries())e.set(t,{config:r.config,process:r.process,pid:r.pid,client:r.client,transport:r.transportInstance,status:r.status,lastError:r.lastError,startTime:r.startTime,lastHealthCheck:r.lastHealthCheck,reconnectAttempts:r.reconnectAttempts,maxReconnectAttempts:r.maxReconnectAttempts,tools:r.toolsMap,toolsArray:r.toolsArray,capabilities:r.capabilities,healthTimer:r.healthTimer,restartTimer:r.restartTimer,metrics:r.metrics});return e}listServers(){return Array.from(this.servers.values())}getServerStatuses(){const e=[];for(const[t,r]of Array.from(this.servers.entries())){const n=r.startTime?Date.now()-r.startTime.getTime():0;e.push({serverId:t,isHealthy:r.status==="connected"&&(this.lastHealth.get(t)?.isHealthy??!0),status:this.lifecycleStates.get(t)??r.status,checkedAt:r.lastHealthCheck||new Date,toolCount:r.toolsMap.size,issues:r.lastError?[r.lastError]:[],consecutiveFailures:this.consecutiveFailures.get(t)??0,lastError:r.lastError,nextRetryAt:this.retryDeadlines.get(t),performance:{uptime:n,averageResponseTime:r.metrics.averageResponseTime}})}return e}async shutdown(){if(this.isShuttingDown)return;this.isShuttingDown=!0,R$.delete(this),ae.info("[ExternalServerManager] Shutting down all servers...");const e=Array.from(this.servers.keys()).map(t=>this.stopServer(t).catch(r=>{ae.error(`[ExternalServerManager] Error shutting down ${t}:`,r)}));await Promise.all(e),this.servers.clear(),this.toolDiscovery.destroy(),this.removeAllListeners(),ae.info("[ExternalServerManager] All servers shut down and resources cleaned up")}async destroy(){return this.shutdown()}getStatistics(){let e=0,t=0,r=0,n=0,o=0;for(const i of Array.from(this.servers.values()))i.status==="connected"?e++:i.status==="failed"&&t++,r+=i.toolsMap.size,n+=i.metrics.totalConnections,o+=i.metrics.totalErrors;return{totalServers:this.servers.size,connectedServers:e,failedServers:t,totalTools:r,totalConnections:n,totalErrors:o}}async discoverServerTools(e){const t=this.servers.get(e);if(!t||!t.client)throw new Error(`Server '${e}' not found or not connected`);if(t.client.getServerCapabilities()?.tools!==void 0)try{ae.debug(`[ExternalServerManager] Discovering tools for server: ${e}`);const r=t.client,n=()=>this.servers.get(e)===t&&t.client===r&&t.status==="initializing"&&r.transport===t.transportInstance&&!this.closedClients.has(r)&&!this.isShuttingDown,o=await this.toolDiscovery.discoverTools(e,r,t.config.timeout||this.config.defaultTimeout,n,!0);if(!n())throw new Error(`MCP discovery for '${e}' was superseded`);if(o.success){t.toolsMap.clear(),t.toolsArray=void 0,t.tools=[];const i=t.blockedTools||[];let s=0;for(const a of o.tools){if(i.includes(a.name)){ae.info(`[ExternalServerManager] Blocking tool '${a.name}' from server '${e}' (configured in blockedTools)`),s++;continue}t.toolsMap.set(a.name,a),t.tools.push({name:a.name,description:a.description,inputSchema:a.inputSchema})}ae.info(`[ExternalServerManager] Discovered ${o.toolCount} tools for ${e} (${s} blocked, ${t.toolsMap.size} available)`)}else throw new Error(`Tool discovery failed for ${e}: ${o.error??"unknown failure"}`)}catch(r){throw ae.error(`[ExternalServerManager] Tool discovery error for ${e}:`,r),r}}async registerServerToolsWithMainRegistry(e){const t=this.servers.get(e);if(!t)throw new Error(`Server '${e}' not found`);try{ae.debug(`[ExternalServerManager] Registering ${t.toolsMap.size} tools with main registry for server: ${e}`);const r=[];for(const[s,a]of t.toolsMap.entries()){const u=`${e}.${s}`,l={name:s,description:a.description||s,inputSchema:a.inputSchema||{},serverId:e,category:Ia({isExternal:!0,serverId:e})};try{r.push(Dle.registerTool(u,l,{execute:async(c,d)=>await this.executeTool(e,s,c,{timeout:t.config.timeout||this.config.defaultTimeout})})),ae.debug(`[ExternalServerManager] Registered tool with main registry: ${u}`)}catch(c){ae.warn(`[ExternalServerManager] Failed to register tool ${u} with main registry:`,c)}}const n=await Promise.allSettled(r),o=n.filter(s=>s.status==="fulfilled").length,i=n.length-o;ae.info(`[ExternalServerManager] Registered ${o}/${n.length} tools with main registry for ${e}${i?` (${i} failed)`:""}`)}catch(r){ae.error(`[ExternalServerManager] Failed to register tools with main registry for ${e}:`,r)}}unregisterServerToolsFromMainRegistry(e){const t=this.servers.get(e);if(!(!t||!this.enableMainRegistryIntegration))try{ae.debug(`[ExternalServerManager] Unregistering tools from main registry for server: ${e}`);for(const[r]of t.toolsMap.entries()){const n=`${e}.${r}`;try{Dle.removeTool(n),ae.debug(`[ExternalServerManager] Unregistered tool from main registry: ${n}`)}catch(o){ae.debug(`[ExternalServerManager] Failed to unregister tool ${n}:`,o)}}ae.debug(`[ExternalServerManager] Completed unregistering tools from main registry for ${e}`)}catch(r){ae.error(`[ExternalServerManager] Error unregistering tools from main registry for ${e}:`,r)}}async executeTool(e,t,r,n){const o=this.servers.get(e);if(!o)throw new Error(`Server '${e}' not found`);const i=o.client;if(!i)throw new Error(`Server '${e}' is not connected`);if(o.status!=="connected")throw new Error(`Server '${e}' is not in connected state: ${o.status}`);if((o.blockedTools||[]).includes(t))throw new Error(`Tool '${t}' is blocked on server '${e}' by configuration`);const a=Date.now();try{let u=r;if(this.hitlManager&&this.hitlManager.isEnabled())if(this.hitlManager.requiresConfirmation(t,r)){ae.info(`[ExternalServerManager] External tool '${t}' on server '${e}' requires HITL confirmation`);try{const m=await this.hitlManager.requestConfirmation(t,r,{serverId:e,sessionId:`external-${e}-${Date.now()}`,userId:void 0});if(!m.approved)throw new Kw(`External tool execution rejected by user: ${m.reason||"No reason provided"}`,t,m.reason);m.modifiedArguments!==void 0&&(u=m.modifiedArguments,ae.info(`[ExternalServerManager] External tool '${t}' arguments modified by user`)),ae.info(`[ExternalServerManager] External tool '${t}' approved for execution (response time: ${m.responseTime}ms)`)}catch(m){throw m instanceof Wk?(ae.warn(`[ExternalServerManager] External tool '${t}' execution timed out waiting for user confirmation`),m):m instanceof Kw?(ae.info(`[ExternalServerManager] External tool '${t}' execution rejected by user`),m):(ae.error(`[ExternalServerManager] HITL confirmation failed for external tool '${t}':`,m),new Error(`HITL confirmation failed: ${m instanceof Error?m.message:String(m)}`,{cause:m}))}}else ae.debug(`[ExternalServerManager] External tool '${t}' does not require HITL confirmation`);this.trackToolCall(e,1);let l;try{l=await this.toolDiscovery.executeTool(t,e,i,u,{timeout:n?.timeout||o.config.timeout||this.config.defaultTimeout})}finally{this.trackToolCall(e,-1)}const c=Date.now()-a;o.metrics.totalToolCalls++,o.metrics.lastResponseTime=c;const d=o.metrics.averageResponseTime*(o.metrics.totalToolCalls-1)+c;if(o.metrics.averageResponseTime=d/o.metrics.totalToolCalls,l.success){const p=l.isErrorResult===!0;return p&&o.metrics.totalErrors++,ae.debug(p?`[ExternalServerManager] Tool returned a resolved MCP error: ${t} on ${e}`:`[ExternalServerManager] Tool executed successfully: ${t} on ${e}`,{duration:c}),TXt(t,c,!p),l.data}else throw new Error(l.error||"Tool execution failed")}catch(u){throw o.metrics.totalErrors++,TXt(t,Date.now()-a,!1),ae.error(`[ExternalServerManager] Tool execution failed: ${t} on ${e}`,u),jor(u)&&this.handleConnectionLost(e,i,`Connection lost during tool call '${t}': ${u instanceof Error?u.message:String(u)}`),u}}getAllTools(){return this.toolDiscovery.getAllTools()}getServerTools(e){return this.toolDiscovery.getServerTools(e)}getToolDiscovery(){return this.toolDiscovery}}}});function r_n(e,t,r,n){return{content:[{type:"text",text:`[MCP Tool Output \u2014 ${r.toolName} | ${r.serverId}]