@mcp-use/inspector 0.9.0-canary.5 → 0.9.0-canary.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/display-A5IEINAP-Diuf_-in.js","assets/index-CHOOqKAT.js","assets/index-Cf47sZoD.css"])))=>i.map(i=>d[i]);
2
- var Dl=Object.defineProperty;var Ul=(t,e,n)=>e in t?Dl(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var hi=(t,e,n)=>Ul(t,typeof e!="symbol"?e+"":e,n);import{bv as di,bw as Fl,bx as Vl,_ as O,by as ve,bz as Bl,bj as Wl,p as to,bA as g,a as dn,bB as Xe,bC as zl,bD as Os,bE as Mr,bF as Pr,bG as Hl,bH as Gl,bI as Kl,bJ as Jl}from"./index-CHOOqKAT.js";import{bK as Tg,bL as kg,bM as Eg,bN as xg,bO as Ag,bP as Mg,bQ as Pg,bR as Ng}from"./index-CHOOqKAT.js";import{L as no,S as vr,t as ql,o as Yl,l as Xl,a as ro,T as Zl,D as Ql,b as so}from"./index-D7lutfXP.js";import{o as Qr}from"./__vite-browser-external-DFygW7-s.js";import{j as er,d as fi,i as ec}from"./path-C9FudP8b.js";import{ag as tc,ah as Is,ai as nc,W as Tn,aj as xe,g as nn,ak as rc,al as fn,am as fe,H as rt,an as io,j as sc,ao as es,_ as q,ap as Xt,a0 as oe,J as N,aq as ee,e as ic,C as oc,ar as ac,as as lc,V as oo,B as cc,at as uc,p as pi,au as hc,av as ao,aw as dc,ax as _e,ay as pn,az as an,M as lo,aA as fc,I as Oe,aB as $s,K as ts,L as Vt,a8 as Bt,aC as pc,aD as mc,aE as gc,aF as yc,aG as wc,aH as _c,aI as bc,aJ as vc,aK as Sc,aL as Cc,aM as Tc,aN as kc,aO as Ec,aP as xc,aQ as Ac,aR as Mc,aS as Pc,aT as Nc,aU as Oc,aV as Ic,aW as $c,aX as Rc,aY as jc,aZ as Lc,a_ as Dc,a$ as Uc,b0 as Fc,b1 as Vc,b2 as Bc,X as Wc,b3 as zc,b4 as Hc,b5 as Gc,D as Le,z as ln,m as Re,Z as Kc,$ as Ze,b6 as Wt,b7 as Jc,N as qc,b8 as mi,b9 as Yc,ba as gi,bb as yi,bc as Rs,bd as wi,a7 as ns,be as Xc,a4 as Zc,bf as js,bg as Ke,bh as tr,u as W,bi as le,bj as Qc,bk as Me,bl as vt,bm as eu,bn as Ls,o as U,bo as tu,i as nu,T as ru,bp as nr,bq as Fe,br as F,bs as co,w as ne,bt as su,bu as $n,bv as iu,bw as uo,bx as zt,by as mn,bz as rr,bA as sr,b as ou,bB as au,ac as lu,aa as cu,a9 as uu,bC as hu,a3 as Rn}from"./index-C9XlRV8D.js";import{E as ho,c as du,e as fu}from"./embeddings-Duw58exF.js";import"./index-DRz5BQNA.js";const pu=t=>{const e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},mu=()=>{const t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(r){return t[r]??null}const n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return r=>{switch(r.code){case"invalid_type":return`Invalid input: expected ${r.expected}, received ${pu(r.input)}`;case"invalid_value":return r.values.length===1?`Invalid input: expected ${Fl(r.values[0])}`:`Invalid option: expected one of ${di(r.values,"|")}`;case"too_big":{const s=r.inclusive?"<=":"<",i=e(r.origin);return i?`Too big: expected ${r.origin??"value"} to have ${s}${r.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${r.origin??"value"} to be ${s}${r.maximum.toString()}`}case"too_small":{const s=r.inclusive?">=":">",i=e(r.origin);return i?`Too small: expected ${r.origin} to have ${s}${r.minimum.toString()} ${i.unit}`:`Too small: expected ${r.origin} to be ${s}${r.minimum.toString()}`}case"invalid_format":{const s=r;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${n[s.format]??r.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${r.divisor}`;case"unrecognized_keys":return`Unrecognized key${r.keys.length>1?"s":""}: ${di(r.keys,", ")}`;case"invalid_key":return`Invalid key in ${r.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${r.origin}`;default:return"Invalid input"}}};function gu(){return{localeError:mu()}}Vl(gu());var Nr,An,Or=0,Ir=0;function yu(t,e,n){var r=0,s=e||new Array(16);t=t||{};var i=t.node,o=t.clockseq;if(t._v6||(i||(i=Nr),o==null&&(o=An)),i==null||o==null){var a=t.random||(t.rng||tc)();i==null&&(i=[a[0],a[1],a[2],a[3],a[4],a[5]],!Nr&&!t._v6&&(i[0]|=1,Nr=i)),o==null&&(o=(a[6]<<8|a[7])&16383,An===void 0&&!t._v6&&(An=o))}var l=t.msecs!==void 0?t.msecs:Date.now(),c=t.nsecs!==void 0?t.nsecs:Ir+1,u=l-Or+(c-Ir)/1e4;if(u<0&&t.clockseq===void 0&&(o=o+1&16383),(u<0||l>Or)&&t.nsecs===void 0&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Or=l,Ir=c,An=o,l+=122192928e5;var h=((l&268435455)*1e4+c)%4294967296;s[r++]=h>>>24&255,s[r++]=h>>>16&255,s[r++]=h>>>8&255,s[r++]=h&255;var d=l/4294967296*1e4&268435455;s[r++]=d>>>8&255,s[r++]=d&255,s[r++]=d>>>24&15|16,s[r++]=d>>>16&255,s[r++]=o>>>8|128,s[r++]=o&255;for(var f=0;f<6;++f)s[r+f]=i[f];return e||Is(s)}function wu(t){var e=typeof t=="string"?nc(t):t,n=_u(e);return typeof t=="string"?Is(n):n}function _u(t,e=!1){return Uint8Array.of((t[6]&15)<<4|t[7]>>4&15,(t[7]&15)<<4|(t[4]&240)>>4,(t[4]&15)<<4|(t[5]&240)>>4,(t[5]&15)<<4|(t[0]&240)>>4,(t[0]&15)<<4|(t[1]&240)>>4,(t[1]&15)<<4|(t[2]&240)>>4,96|t[2]&15,t[3],t[8],t[9],t[10],t[11],t[12],t[13],t[14],t[15])}function _i(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),n.push.apply(n,r)}return n}function bi(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?_i(Object(n),!0).forEach(function(r){bu(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):_i(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function bu(t,e,n){return(e=vu(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function vu(t){var e=Su(t,"string");return typeof e=="symbol"?e:e+""}function Su(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Cu(t={},e,n=0){var r=yu(bi(bi({},t),{},{_v6:!0}),new Uint8Array(16));return r=wu(r),Is(r)}async function*Tu(t){for await(const e of t)if(e.event==="on_chat_model_stream"&&e.data?.chunk?.text){const n=e.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}}O(Tu,"streamEventsToAISDK");function ku(t){return new ReadableStream({async start(e){try{for await(const n of t)e.enqueue(n);e.close()}catch(n){e.error(n)}}})}O(ku,"createReadableStreamFromGenerator");async function*Eu(t){for await(const e of t)switch(e.event){case"on_chat_model_stream":if(e.data?.chunk?.text){const n=e.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}break;case"on_tool_start":yield`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/display-A5IEINAP-PpmJDTVa.js","assets/index-IFdSquJo.js","assets/index-CHNXgq6o.css"])))=>i.map(i=>d[i]);
2
+ var Dl=Object.defineProperty;var Ul=(t,e,n)=>e in t?Dl(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var hi=(t,e,n)=>Ul(t,typeof e!="symbol"?e+"":e,n);import{bv as di,bw as Fl,bx as Vl,_ as O,by as ve,bz as Bl,bj as Wl,p as to,bA as g,a as dn,bB as Xe,bC as zl,bD as Os,bE as Mr,bF as Pr,bG as Hl,bH as Gl,bI as Kl,bJ as Jl}from"./index-IFdSquJo.js";import{bK as Tg,bL as kg,bM as Eg,bN as xg,bO as Ag,bP as Mg,bQ as Pg,bR as Ng}from"./index-IFdSquJo.js";import{L as no,S as vr,t as ql,o as Yl,l as Xl,a as ro,T as Zl,D as Ql,b as so}from"./index-CI3g_RcQ.js";import{o as Qr}from"./__vite-browser-external-DFygW7-s.js";import{j as er,d as fi,i as ec}from"./path-C9FudP8b.js";import{ag as tc,ah as Is,ai as nc,W as Tn,aj as xe,g as nn,ak as rc,al as fn,am as fe,H as rt,an as io,j as sc,ao as es,_ as q,ap as Xt,a0 as oe,J as N,aq as ee,e as ic,C as oc,ar as ac,as as lc,V as oo,B as cc,at as uc,p as pi,au as hc,av as ao,aw as dc,ax as _e,ay as pn,az as an,M as lo,aA as fc,I as Oe,aB as $s,K as ts,L as Vt,a8 as Bt,aC as pc,aD as mc,aE as gc,aF as yc,aG as wc,aH as _c,aI as bc,aJ as vc,aK as Sc,aL as Cc,aM as Tc,aN as kc,aO as Ec,aP as xc,aQ as Ac,aR as Mc,aS as Pc,aT as Nc,aU as Oc,aV as Ic,aW as $c,aX as Rc,aY as jc,aZ as Lc,a_ as Dc,a$ as Uc,b0 as Fc,b1 as Vc,b2 as Bc,X as Wc,b3 as zc,b4 as Hc,b5 as Gc,D as Le,z as ln,m as Re,Z as Kc,$ as Ze,b6 as Wt,b7 as Jc,N as qc,b8 as mi,b9 as Yc,ba as gi,bb as yi,bc as Rs,bd as wi,a7 as ns,be as Xc,a4 as Zc,bf as js,bg as Ke,bh as tr,u as W,bi as le,bj as Qc,bk as Me,bl as vt,bm as eu,bn as Ls,o as U,bo as tu,i as nu,T as ru,bp as nr,bq as Fe,br as F,bs as co,w as ne,bt as su,bu as $n,bv as iu,bw as uo,bx as zt,by as mn,bz as rr,bA as sr,b as ou,bB as au,ac as lu,aa as cu,a9 as uu,bC as hu,a3 as Rn}from"./index-Cx63umjv.js";import{E as ho,c as du,e as fu}from"./embeddings-DHqEojuq.js";import"./index-DRz5BQNA.js";const pu=t=>{const e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},mu=()=>{const t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(r){return t[r]??null}const n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return r=>{switch(r.code){case"invalid_type":return`Invalid input: expected ${r.expected}, received ${pu(r.input)}`;case"invalid_value":return r.values.length===1?`Invalid input: expected ${Fl(r.values[0])}`:`Invalid option: expected one of ${di(r.values,"|")}`;case"too_big":{const s=r.inclusive?"<=":"<",i=e(r.origin);return i?`Too big: expected ${r.origin??"value"} to have ${s}${r.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${r.origin??"value"} to be ${s}${r.maximum.toString()}`}case"too_small":{const s=r.inclusive?">=":">",i=e(r.origin);return i?`Too small: expected ${r.origin} to have ${s}${r.minimum.toString()} ${i.unit}`:`Too small: expected ${r.origin} to be ${s}${r.minimum.toString()}`}case"invalid_format":{const s=r;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${n[s.format]??r.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${r.divisor}`;case"unrecognized_keys":return`Unrecognized key${r.keys.length>1?"s":""}: ${di(r.keys,", ")}`;case"invalid_key":return`Invalid key in ${r.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${r.origin}`;default:return"Invalid input"}}};function gu(){return{localeError:mu()}}Vl(gu());var Nr,An,Or=0,Ir=0;function yu(t,e,n){var r=0,s=e||new Array(16);t=t||{};var i=t.node,o=t.clockseq;if(t._v6||(i||(i=Nr),o==null&&(o=An)),i==null||o==null){var a=t.random||(t.rng||tc)();i==null&&(i=[a[0],a[1],a[2],a[3],a[4],a[5]],!Nr&&!t._v6&&(i[0]|=1,Nr=i)),o==null&&(o=(a[6]<<8|a[7])&16383,An===void 0&&!t._v6&&(An=o))}var l=t.msecs!==void 0?t.msecs:Date.now(),c=t.nsecs!==void 0?t.nsecs:Ir+1,u=l-Or+(c-Ir)/1e4;if(u<0&&t.clockseq===void 0&&(o=o+1&16383),(u<0||l>Or)&&t.nsecs===void 0&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Or=l,Ir=c,An=o,l+=122192928e5;var h=((l&268435455)*1e4+c)%4294967296;s[r++]=h>>>24&255,s[r++]=h>>>16&255,s[r++]=h>>>8&255,s[r++]=h&255;var d=l/4294967296*1e4&268435455;s[r++]=d>>>8&255,s[r++]=d&255,s[r++]=d>>>24&15|16,s[r++]=d>>>16&255,s[r++]=o>>>8|128,s[r++]=o&255;for(var f=0;f<6;++f)s[r+f]=i[f];return e||Is(s)}function wu(t){var e=typeof t=="string"?nc(t):t,n=_u(e);return typeof t=="string"?Is(n):n}function _u(t,e=!1){return Uint8Array.of((t[6]&15)<<4|t[7]>>4&15,(t[7]&15)<<4|(t[4]&240)>>4,(t[4]&15)<<4|(t[5]&240)>>4,(t[5]&15)<<4|(t[0]&240)>>4,(t[0]&15)<<4|(t[1]&240)>>4,(t[1]&15)<<4|(t[2]&240)>>4,96|t[2]&15,t[3],t[8],t[9],t[10],t[11],t[12],t[13],t[14],t[15])}function _i(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),n.push.apply(n,r)}return n}function bi(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?_i(Object(n),!0).forEach(function(r){bu(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):_i(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function bu(t,e,n){return(e=vu(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function vu(t){var e=Su(t,"string");return typeof e=="symbol"?e:e+""}function Su(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Cu(t={},e,n=0){var r=yu(bi(bi({},t),{},{_v6:!0}),new Uint8Array(16));return r=wu(r),Is(r)}async function*Tu(t){for await(const e of t)if(e.event==="on_chat_model_stream"&&e.data?.chunk?.text){const n=e.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}}O(Tu,"streamEventsToAISDK");function ku(t){return new ReadableStream({async start(e){try{for await(const n of t)e.enqueue(n);e.close()}catch(n){e.error(n)}}})}O(ku,"createReadableStreamFromGenerator");async function*Eu(t){for await(const e of t)switch(e.event){case"on_chat_model_stream":if(e.data?.chunk?.text){const n=e.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}break;case"on_tool_start":yield`
3
3
  🔧 Using tool: ${e.name}
4
4
  `;break;case"on_tool_end":yield`
5
5
  ✅ Tool completed: ${e.name}
@@ -372,7 +372,7 @@ You can then use these server-specific tools in subsequent steps.
372
372
  Here are the tools *currently* available to you (this list includes server management tools and will
373
373
  change when you connect to a server):
374
374
  {tool_descriptions}
375
- `,Ft,vg=(Ft=class{llm;client;connectors;maxSteps;autoInitialize;memoryEnabled;disallowedTools;additionalTools;toolsUsedNames=[];useServerManager;verbose;observe;systemPrompt;systemPromptTemplateOverride;additionalInstructions;_initialized=!1;conversationHistory=[];_agentExecutor=null;sessions={};systemMessage=null;_tools=[];adapter;serverManager=null;telemetry;modelProvider;modelName;observabilityManager;callbacks=[];metadata={};tags=[];isRemote=!1;remoteAgent=null;constructor(e){if(e.agentId){this.isRemote=!0,this.remoteAgent=new ig({agentId:e.agentId,apiKey:e.apiKey,baseUrl:e.baseUrl}),this.maxSteps=e.maxSteps??5,this.memoryEnabled=e.memoryEnabled??!0,this.autoInitialize=e.autoInitialize??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.connectors=[],this.disallowedTools=[],this.additionalTools=[],this.useServerManager=!1,this.adapter=new gt,this.telemetry=Ns.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Qi({customCallbacks:e.callbacks,agentId:e.agentId}),this.callbacks=[];return}if(!e.llm)throw new Error("llm is required for local execution. For remote execution, provide agentId instead.");if(this.llm=e.llm,this.client=e.client,this.connectors=e.connectors??[],this.maxSteps=e.maxSteps??5,this.autoInitialize=e.autoInitialize??!1,this.memoryEnabled=e.memoryEnabled??!0,this.systemPrompt=e.systemPrompt??null,this.systemPromptTemplateOverride=e.systemPromptTemplate??null,this.additionalInstructions=e.additionalInstructions??null,this.disallowedTools=e.disallowedTools??[],this.additionalTools=e.additionalTools??[],this.toolsUsedNames=e.toolsUsedNames??[],this.useServerManager=e.useServerManager??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,!this.client&&this.connectors.length===0)throw new Error("Either 'client' or at least one 'connector' must be provided.");if(this.useServerManager){if(!this.client)throw new Error("'client' must be provided when 'useServerManager' is true.");this.adapter=e.adapter??new gt(this.disallowedTools),this.serverManager=e.serverManagerFactory?.(this.client)??new Zm(this.client,this.adapter)}else this.adapter=e.adapter??new gt(this.disallowedTools);if(this.telemetry=Ns.getInstance(),this.llm){const[n,r]=Ol(this.llm);this.modelProvider=n,this.modelName=r}else this.modelProvider="unknown",this.modelName="unknown";this.observabilityManager=new Qi({customCallbacks:e.callbacks,verbose:this.verbose,observe:this.observe,agentId:e.agentId,metadataProvider:O(()=>this.getMetadata(),"metadataProvider"),tagsProvider:O(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:O(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:O(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:O(()=>this._initialized,"get"),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}g.info("🚀 Initializing MCP agent and connecting to services..."),this.callbacks=await this.observabilityManager.getCallbacks();const e=await this.observabilityManager.getHandlerNames();if(e.length>0&&g.info(`📊 Observability enabled with: ${e.join(", ")}`),this.useServerManager&&this.serverManager){await this.serverManager.initialize();const r=this.serverManager.tools;this._tools=r,this._tools.push(...this.additionalTools),g.info(`🔧 Server manager mode active with ${r.length} management tools`),await this.createSystemMessageFromTools(this._tools)}else{if(this.client){if(this.sessions=this.client.getAllActiveSessions(),g.info(`🔌 Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(s=>s!=="code_mode").length===0&&(g.info("🔄 No active sessions found, creating new ones..."),this.sessions=await this.client.createAllSessions(),g.info(`✅ Created ${Object.keys(this.sessions).length} new sessions`)),this.client.codeMode){const s=this.sessions.code_mode;if(s)this._tools=await this.adapter.createToolsFromConnectors([s.connector]),g.info(`🛠️ Created ${this._tools.length} code mode tools`);else throw new Error("Code mode enabled but code_mode session not found")}else this._tools=await gt.createTools(this.client),g.info(`🛠️ Created ${this._tools.length} LangChain tools from client`);this._tools.push(...this.additionalTools)}else{g.info(`🔗 Connecting to ${this.connectors.length} direct connectors...`);for(const r of this.connectors)r.isClientConnected||await r.connect();this._tools=await this.adapter.createToolsFromConnectors(this.connectors),this._tools.push(...this.additionalTools),g.info(`🛠️ Created ${this._tools.length} LangChain tools from connectors`)}g.info(`🧰 Found ${this._tools.length} tools across all connectors`),await this.createSystemMessageFromTools(this._tools)}this._agentExecutor=this.createAgent(),this._initialized=!0;const n=this.getMCPServerInfo();Object.keys(n).length>0&&(this.setMetadata(n),g.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),g.info("✨ Agent initialization complete")}async createSystemMessageFromTools(e){const n=this.systemPromptTemplateOverride??og;this.systemMessage=Rl(e,n,ag,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(r=>!(r instanceof _e))])}createAgent(){if(!this.llm)throw new Error("LLM is required to create agent");const e=this.systemMessage?.content??"You are a helpful assistant.",n=this._tools.map(i=>i.name);g.info(`🧠 Agent ready with tools: ${n.join(", ")}`);const r=[Al({runLimit:this.maxSteps})],s=yl({model:this.llm,tools:this._tools,systemPrompt:e,middleware:r});return g.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`),s}getConversationHistory(){return[...this.conversationHistory]}clearConversationHistory(){this.conversationHistory=this.memoryEnabled&&this.systemMessage?[this.systemMessage]:[]}addToHistory(e){this.memoryEnabled&&this.conversationHistory.push(e)}getSystemMessage(){return this.systemMessage}setSystemMessage(e){this.systemMessage=new _e(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(n=>!(n instanceof _e)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),g.debug("Agent recreated with new system message"))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new gt(this.disallowedTools),this._initialized&&g.debug("Agent already initialized. Changes will take effect on next initialization.")}getDisallowedTools(){return this.disallowedTools}setMetadata(e){const n=this.sanitizeMetadata(e);this.metadata={...this.metadata,...n},g.debug(`Metadata set: ${JSON.stringify(this.metadata)}`)}getMetadata(){return{...this.metadata}}setTags(e){const n=this.sanitizeTags(e);this.tags=[...new Set([...this.tags,...n])],g.debug(`Tags set: ${JSON.stringify(this.tags)}`)}getTags(){return[...this.tags]}sanitizeMetadata(e){const n={};for(const[r,s]of Object.entries(e)){if(typeof r!="string"||r.length===0){g.warn(`Invalid metadata key: ${r}. Skipping.`);continue}const i=r.replace(/[^\w-]/g,"_");if(s==null)n[i]=s;else if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")n[i]=s;else if(Array.isArray(s)){const o=s.filter(a=>typeof a=="string"||typeof a=="number"||typeof a=="boolean");o.length>0&&(n[i]=o)}else if(typeof s=="object")try{const o=JSON.stringify(s);o.length>1e3?(g.warn(`Metadata value for key '${i}' is too large. Truncating.`),n[i]=`${o.substring(0,1e3)}...`):n[i]=s}catch(o){g.warn(`Failed to serialize metadata value for key '${i}': ${o}. Skipping.`)}else g.warn(`Unsupported metadata value type for key '${i}': ${typeof s}. Skipping.`)}return n}sanitizeTags(e){return e.filter(n=>typeof n=="string"&&n.length>0).map(n=>n.replace(/[^\w:-]/g,"_")).filter(n=>n.length<=50)}getMCPServerInfo(){const e={};try{if(this.client){const n=this.client.getServerNames();e.mcp_servers_count=n.length,e.mcp_server_names=n;const r={};for(const s of n)try{const i=this.client.getServerConfig(s);if(i){let o="unknown";i.command?o="command":i.url?o="http":i.ws_url&&(o="websocket"),r[s]={type:o,has_args:!!i.args,has_env:!!i.env,has_headers:!!i.headers,url:i.url||null,command:i.command||null}}}catch(i){g.warn(`Failed to get config for server '${s}': ${i}`),r[s]={type:"error",error:"config_unavailable"}}e.mcp_server_configs=r}else this.connectors&&this.connectors.length>0&&(e.mcp_servers_count=this.connectors.length,e.mcp_server_names=this.connectors.map(n=>n.publicIdentifier),e.mcp_server_types=this.connectors.map(n=>n.constructor.name))}catch(n){g.warn(`Failed to collect MCP server info: ${n}`),e.error="collection_failed"}return e}_normalizeOutput(e){try{if(typeof e=="string")return e;if(e&&typeof e=="object"&&"content"in e)return this._normalizeOutput(e.content);if(Array.isArray(e)){const n=[];for(const r of e)if(typeof r=="object"&&r!==null)"text"in r&&typeof r.text=="string"?n.push(r.text):"content"in r?n.push(this._normalizeOutput(r.content)):n.push(String(r));else{const s=r&&typeof r=="object"&&"text"in r?r.text:null;if(typeof s=="string")n.push(s);else{const i=r&&typeof r=="object"&&"content"in r?r.content:r;n.push(this._normalizeOutput(i))}}return n.join("")}return String(e)}catch{return String(e)}}_isAIMessageLike(e){if(e instanceof N)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="ai"||r==="assistant")return!0}catch{}if(typeof n._getType=="function")try{const r=n._getType();if(r==="ai"||r==="assistant")return!0}catch{}return"type"in n?n.type==="ai"||n.type==="assistant":"role"in n?n.role==="ai"||n.role==="assistant":!1}_messageHasToolCalls(e){return typeof e=="object"&&e!==null&&"tool_calls"in e&&Array.isArray(e.tool_calls)?e.tool_calls.length>0:!1}_isHumanMessageLike(e){if(e instanceof oe)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="human"||r==="user")return!0}catch{}return"type"in n&&(n.type==="human"||n.type==="user")||"role"in n&&(n.role==="human"||n.role==="user")}_isToolMessageLike(e){if(e instanceof U)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{if(n.getType()==="tool")return!0}catch{}return"type"in n&&n.type==="tool"}_getMessageContent(e){if(e instanceof N||e&&typeof e=="object"&&"content"in e)return e.content}async _consumeAndReturn(e){for(;;){const{done:n,value:r}=await e.next();if(n)return r}}async run(e,n,r,s,i){if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(e,n,r,s,i);const o=this.stream(e,n,r,s,i);return this._consumeAndReturn(o)}async*stream(e,n,r=!0,s,i){if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(e,n,r,s,i);let o=!1;const a=Date.now();let l=!1,c=null,u=0;try{if(r&&!this._initialized?(await this.initialize(),o=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),o=!0),!this._agentExecutor)throw new Error("MCP agent failed to initialize");if(this.useServerManager&&this.serverManager){const C=this.serverManager.tools,m=new Set(C.map(b=>b.name)),w=new Set(this._tools.map(b=>b.name));(m.size!==w.size||[...m].some(b=>!w.has(b)))&&(g.info(`🔄 Tools changed before execution, updating agent. New tools: ${[...m].join(", ")}`),this._tools=C,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const h=s??this.conversationHistory,d=[];for(const C of h)(this._isHumanMessageLike(C)||this._isAIMessageLike(C))&&d.push(C);const f=e.length>50?`${e.slice(0,50).replace(/\n/g," ")}...`:e.replace(/\n/g," ");g.info(`💬 Received query: '${f}'`),g.info("🏁 Starting agent execution");const y=3;let p=0;const S=[...d,new oe(e)];for(;p<=y;){const C={messages:S};let m=!1;const w=await this._agentExecutor.stream(C,{streamMode:"updates",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const b of w){for(const[T,x]of Object.entries(b))if(g.debug(`📦 Node '${T}' output: ${JSON.stringify(x)}`),x&&typeof x=="object"&&"messages"in x){let _=x.messages;Array.isArray(_)||(_=[_]);for(const v of _)S.includes(v)||S.push(v);for(const v of _){if("tool_calls"in v&&Array.isArray(v.tool_calls)&&v.tool_calls.length>0)for(const A of v.tool_calls){const E=A.name||"unknown",P=A.args||{};this.toolsUsedNames.push(E),u++;let $=JSON.stringify(P);$.length>100&&($=`${$.slice(0,97)}...`),g.info(`🔧 Tool call: ${E} with input: ${$}`),yield{action:{tool:E,toolInput:P,log:`Calling tool ${E}`},observation:""}}if(this._isToolMessageLike(v)){const A=v.content;let E=String(A);if(E.length>100&&(E=`${E.slice(0,97)}...`),E=E.replace(/\n/g," "),g.info(`📄 Tool result: ${E}`),this.useServerManager&&this.serverManager){const P=this.serverManager.tools,$=new Set(P.map(X=>X.name)),V=new Set(this._tools.map(X=>X.name));if($.size!==V.size||[...$].some(X=>!V.has(X))){g.info(`🔄 Tools changed during execution. New tools: ${[...$].join(", ")}`),this._tools=P,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),m=!0,p++,g.info(`🔃 Restarting execution with updated tools (restart ${p}/${y})`);break}}}this._isAIMessageLike(v)&&!this._messageHasToolCalls(v)&&(c=this._normalizeOutput(this._getMessageContent(v)),g.info("✅ Agent finished with output"))}if(m)break}if(m)break}if(!m)break;if(p>y){g.warn(`⚠️ Max restarts (${y}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled&&(this.addToHistory(new oe(e)),c&&this.addToHistory(new N(c))),i&&c)try{g.info("🔧 Attempting structured output...");const C=await this._attemptStructuredOutput(c,this.llm,i);return this.memoryEnabled&&this.addToHistory(new N(`Structured result: ${JSON.stringify(C)}`)),g.info("✅ Structured output successful"),l=!0,C}catch(C){throw g.error(`❌ Structured output failed: ${C}`),new Error(`Failed to generate structured output: ${C instanceof Error?C.message:String(C)}`)}return g.info(`🎉 Agent execution complete in ${((Date.now()-a)/1e3).toFixed(2)} seconds`),l=!0,c||"No output generated"}catch(h){throw g.error(`❌ Error running query: ${h}`),o&&r&&(g.info("🧹 Cleaning up resources after error"),await this.close()),h}finally{const h=Date.now()-a;let d=0;this.client?d=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(d=this.connectors.length);const f=this.memoryEnabled?this.conversationHistory.length:0,y=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:"stream",query:e,success:l,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:d,serverIdentifiers:this.connectors.map(p=>p.publicIdentifier),totalToolsAvailable:y.length,toolsAvailableNames:y.map(p=>p.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:n??null,manageConnector:r,externalHistoryUsed:s!==void 0,stepsTaken:u,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:c||"",executionTimeMs:h,errorType:l?null:"execution_error",conversationHistoryLength:f}),r&&!this.client&&o&&(g.info("🧹 Closing agent after stream completion"),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(g.debug("Flushing observability traces..."),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}g.info("🔌 Closing MCPAgent resources…"),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)g.info("🔄 Closing client and cleaning up resources"),await this.client.close(),this.sessions={};else for(const e of this.connectors)g.info("🔄 Disconnecting connector"),await e.disconnect();"connectorToolMap"in this.adapter&&(this.adapter=new gt)}finally{this._initialized=!1,g.info("👋 Agent closed successfully")}}async*prettyStreamEvents(e,n,r=!0,s,i){const{prettyStreamEvents:o}=await dn(async()=>{const{prettyStreamEvents:l}=await import("./display-A5IEINAP-Diuf_-in.js");return{prettyStreamEvents:l}},__vite__mapDeps([0,1,2])),a="";for await(const l of o(this.streamEvents(e,n,r,s,i)))yield;return a}async*streamEvents(e,n,r=!0,s,i){let o=!1;const a=Date.now();let l=!1,c=0,u=0,h="";i&&(e=this._enhanceQueryWithSchema(e,i));try{r&&!this._initialized?(await this.initialize(),o=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),o=!0);const d=this._agentExecutor;if(!d)throw new Error("MCP agent failed to initialize");this.maxSteps=n??this.maxSteps;const f=typeof e=="string"&&e.length>50?`${e.slice(0,50).replace(/\n/g," ")}...`:typeof e=="string"?e.replace(/\n/g," "):String(e);g.info(`💬 Received query for streamEvents: '${f}'`),this.memoryEnabled&&(g.info(`🔄 Adding user message to history: ${f}`),this.addToHistory(new oe({content:e})));const y=s??this.conversationHistory,p=[];for(const m of y)this._isHumanMessageLike(m)||this._isAIMessageLike(m)||this._isToolMessageLike(m)?p.push(m):g.info(`⚠️ Skipped message of type: ${m.constructor?.name||typeof m}`);const S=[...p,new oe(e)];g.info("callbacks",this.callbacks);const C=d.streamEvents({messages:S},{streamMode:"messages",version:"v2",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const m of C)if(c++,!(!m||typeof m!="object")){if(m.event==="on_chat_model_stream"&&m.data?.chunk?.content&&(u+=m.data.chunk.content.length),m.event==="on_chat_model_stream"&&m.data?.chunk){const w=m.data.chunk;if(w.content){h||(h="");const b=this._normalizeOutput(w.content);h+=b,g.debug(`📝 Accumulated response length: ${h.length}`)}}if(yield m,m.event==="on_chain_end"&&m.data?.output&&!h){const w=m.data.output;Array.isArray(w)&&w.length>0&&w[0]?.text?h=w[0].text:typeof w=="string"?h=w:w&&typeof w=="object"&&"output"in w&&(h=w.output)}}if(i&&h){g.info("🔧 Attempting structured output conversion...");try{let m=!1,w=null,b=null;this._attemptStructuredOutput(h,this.llm,i).then(x=>(m=!0,w=x,x)).catch(x=>{throw m=!0,b=x,x});let T=0;for(;!m;)await new Promise(x=>setTimeout(x,2e3)),m||(T++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${T*2}s)`,elapsed:T*2}});if(b)throw b;w&&(yield{event:"on_structured_output",data:{output:w}},this.memoryEnabled&&this.addToHistory(new N(`Structured result: ${JSON.stringify(w)}`)),g.info("✅ Structured output successful"))}catch(m){g.warn(`⚠️ Structured output failed: ${m}`),yield{event:"on_structured_output_error",data:{error:m instanceof Error?m.message:String(m)}}}}else this.memoryEnabled&&h&&this.addToHistory(new N(h));console.log(`
375
+ `,Ft,vg=(Ft=class{llm;client;connectors;maxSteps;autoInitialize;memoryEnabled;disallowedTools;additionalTools;toolsUsedNames=[];useServerManager;verbose;observe;systemPrompt;systemPromptTemplateOverride;additionalInstructions;_initialized=!1;conversationHistory=[];_agentExecutor=null;sessions={};systemMessage=null;_tools=[];adapter;serverManager=null;telemetry;modelProvider;modelName;observabilityManager;callbacks=[];metadata={};tags=[];isRemote=!1;remoteAgent=null;constructor(e){if(e.agentId){this.isRemote=!0,this.remoteAgent=new ig({agentId:e.agentId,apiKey:e.apiKey,baseUrl:e.baseUrl}),this.maxSteps=e.maxSteps??5,this.memoryEnabled=e.memoryEnabled??!0,this.autoInitialize=e.autoInitialize??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.connectors=[],this.disallowedTools=[],this.additionalTools=[],this.useServerManager=!1,this.adapter=new gt,this.telemetry=Ns.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Qi({customCallbacks:e.callbacks,agentId:e.agentId}),this.callbacks=[];return}if(!e.llm)throw new Error("llm is required for local execution. For remote execution, provide agentId instead.");if(this.llm=e.llm,this.client=e.client,this.connectors=e.connectors??[],this.maxSteps=e.maxSteps??5,this.autoInitialize=e.autoInitialize??!1,this.memoryEnabled=e.memoryEnabled??!0,this.systemPrompt=e.systemPrompt??null,this.systemPromptTemplateOverride=e.systemPromptTemplate??null,this.additionalInstructions=e.additionalInstructions??null,this.disallowedTools=e.disallowedTools??[],this.additionalTools=e.additionalTools??[],this.toolsUsedNames=e.toolsUsedNames??[],this.useServerManager=e.useServerManager??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,!this.client&&this.connectors.length===0)throw new Error("Either 'client' or at least one 'connector' must be provided.");if(this.useServerManager){if(!this.client)throw new Error("'client' must be provided when 'useServerManager' is true.");this.adapter=e.adapter??new gt(this.disallowedTools),this.serverManager=e.serverManagerFactory?.(this.client)??new Zm(this.client,this.adapter)}else this.adapter=e.adapter??new gt(this.disallowedTools);if(this.telemetry=Ns.getInstance(),this.llm){const[n,r]=Ol(this.llm);this.modelProvider=n,this.modelName=r}else this.modelProvider="unknown",this.modelName="unknown";this.observabilityManager=new Qi({customCallbacks:e.callbacks,verbose:this.verbose,observe:this.observe,agentId:e.agentId,metadataProvider:O(()=>this.getMetadata(),"metadataProvider"),tagsProvider:O(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:O(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:O(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:O(()=>this._initialized,"get"),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}g.info("🚀 Initializing MCP agent and connecting to services..."),this.callbacks=await this.observabilityManager.getCallbacks();const e=await this.observabilityManager.getHandlerNames();if(e.length>0&&g.info(`📊 Observability enabled with: ${e.join(", ")}`),this.useServerManager&&this.serverManager){await this.serverManager.initialize();const r=this.serverManager.tools;this._tools=r,this._tools.push(...this.additionalTools),g.info(`🔧 Server manager mode active with ${r.length} management tools`),await this.createSystemMessageFromTools(this._tools)}else{if(this.client){if(this.sessions=this.client.getAllActiveSessions(),g.info(`🔌 Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(s=>s!=="code_mode").length===0&&(g.info("🔄 No active sessions found, creating new ones..."),this.sessions=await this.client.createAllSessions(),g.info(`✅ Created ${Object.keys(this.sessions).length} new sessions`)),this.client.codeMode){const s=this.sessions.code_mode;if(s)this._tools=await this.adapter.createToolsFromConnectors([s.connector]),g.info(`🛠️ Created ${this._tools.length} code mode tools`);else throw new Error("Code mode enabled but code_mode session not found")}else this._tools=await gt.createTools(this.client),g.info(`🛠️ Created ${this._tools.length} LangChain tools from client`);this._tools.push(...this.additionalTools)}else{g.info(`🔗 Connecting to ${this.connectors.length} direct connectors...`);for(const r of this.connectors)r.isClientConnected||await r.connect();this._tools=await this.adapter.createToolsFromConnectors(this.connectors),this._tools.push(...this.additionalTools),g.info(`🛠️ Created ${this._tools.length} LangChain tools from connectors`)}g.info(`🧰 Found ${this._tools.length} tools across all connectors`),await this.createSystemMessageFromTools(this._tools)}this._agentExecutor=this.createAgent(),this._initialized=!0;const n=this.getMCPServerInfo();Object.keys(n).length>0&&(this.setMetadata(n),g.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),g.info("✨ Agent initialization complete")}async createSystemMessageFromTools(e){const n=this.systemPromptTemplateOverride??og;this.systemMessage=Rl(e,n,ag,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(r=>!(r instanceof _e))])}createAgent(){if(!this.llm)throw new Error("LLM is required to create agent");const e=this.systemMessage?.content??"You are a helpful assistant.",n=this._tools.map(i=>i.name);g.info(`🧠 Agent ready with tools: ${n.join(", ")}`);const r=[Al({runLimit:this.maxSteps})],s=yl({model:this.llm,tools:this._tools,systemPrompt:e,middleware:r});return g.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`),s}getConversationHistory(){return[...this.conversationHistory]}clearConversationHistory(){this.conversationHistory=this.memoryEnabled&&this.systemMessage?[this.systemMessage]:[]}addToHistory(e){this.memoryEnabled&&this.conversationHistory.push(e)}getSystemMessage(){return this.systemMessage}setSystemMessage(e){this.systemMessage=new _e(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(n=>!(n instanceof _e)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),g.debug("Agent recreated with new system message"))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new gt(this.disallowedTools),this._initialized&&g.debug("Agent already initialized. Changes will take effect on next initialization.")}getDisallowedTools(){return this.disallowedTools}setMetadata(e){const n=this.sanitizeMetadata(e);this.metadata={...this.metadata,...n},g.debug(`Metadata set: ${JSON.stringify(this.metadata)}`)}getMetadata(){return{...this.metadata}}setTags(e){const n=this.sanitizeTags(e);this.tags=[...new Set([...this.tags,...n])],g.debug(`Tags set: ${JSON.stringify(this.tags)}`)}getTags(){return[...this.tags]}sanitizeMetadata(e){const n={};for(const[r,s]of Object.entries(e)){if(typeof r!="string"||r.length===0){g.warn(`Invalid metadata key: ${r}. Skipping.`);continue}const i=r.replace(/[^\w-]/g,"_");if(s==null)n[i]=s;else if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")n[i]=s;else if(Array.isArray(s)){const o=s.filter(a=>typeof a=="string"||typeof a=="number"||typeof a=="boolean");o.length>0&&(n[i]=o)}else if(typeof s=="object")try{const o=JSON.stringify(s);o.length>1e3?(g.warn(`Metadata value for key '${i}' is too large. Truncating.`),n[i]=`${o.substring(0,1e3)}...`):n[i]=s}catch(o){g.warn(`Failed to serialize metadata value for key '${i}': ${o}. Skipping.`)}else g.warn(`Unsupported metadata value type for key '${i}': ${typeof s}. Skipping.`)}return n}sanitizeTags(e){return e.filter(n=>typeof n=="string"&&n.length>0).map(n=>n.replace(/[^\w:-]/g,"_")).filter(n=>n.length<=50)}getMCPServerInfo(){const e={};try{if(this.client){const n=this.client.getServerNames();e.mcp_servers_count=n.length,e.mcp_server_names=n;const r={};for(const s of n)try{const i=this.client.getServerConfig(s);if(i){let o="unknown";i.command?o="command":i.url?o="http":i.ws_url&&(o="websocket"),r[s]={type:o,has_args:!!i.args,has_env:!!i.env,has_headers:!!i.headers,url:i.url||null,command:i.command||null}}}catch(i){g.warn(`Failed to get config for server '${s}': ${i}`),r[s]={type:"error",error:"config_unavailable"}}e.mcp_server_configs=r}else this.connectors&&this.connectors.length>0&&(e.mcp_servers_count=this.connectors.length,e.mcp_server_names=this.connectors.map(n=>n.publicIdentifier),e.mcp_server_types=this.connectors.map(n=>n.constructor.name))}catch(n){g.warn(`Failed to collect MCP server info: ${n}`),e.error="collection_failed"}return e}_normalizeOutput(e){try{if(typeof e=="string")return e;if(e&&typeof e=="object"&&"content"in e)return this._normalizeOutput(e.content);if(Array.isArray(e)){const n=[];for(const r of e)if(typeof r=="object"&&r!==null)"text"in r&&typeof r.text=="string"?n.push(r.text):"content"in r?n.push(this._normalizeOutput(r.content)):n.push(String(r));else{const s=r&&typeof r=="object"&&"text"in r?r.text:null;if(typeof s=="string")n.push(s);else{const i=r&&typeof r=="object"&&"content"in r?r.content:r;n.push(this._normalizeOutput(i))}}return n.join("")}return String(e)}catch{return String(e)}}_isAIMessageLike(e){if(e instanceof N)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="ai"||r==="assistant")return!0}catch{}if(typeof n._getType=="function")try{const r=n._getType();if(r==="ai"||r==="assistant")return!0}catch{}return"type"in n?n.type==="ai"||n.type==="assistant":"role"in n?n.role==="ai"||n.role==="assistant":!1}_messageHasToolCalls(e){return typeof e=="object"&&e!==null&&"tool_calls"in e&&Array.isArray(e.tool_calls)?e.tool_calls.length>0:!1}_isHumanMessageLike(e){if(e instanceof oe)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="human"||r==="user")return!0}catch{}return"type"in n&&(n.type==="human"||n.type==="user")||"role"in n&&(n.role==="human"||n.role==="user")}_isToolMessageLike(e){if(e instanceof U)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{if(n.getType()==="tool")return!0}catch{}return"type"in n&&n.type==="tool"}_getMessageContent(e){if(e instanceof N||e&&typeof e=="object"&&"content"in e)return e.content}async _consumeAndReturn(e){for(;;){const{done:n,value:r}=await e.next();if(n)return r}}async run(e,n,r,s,i){if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(e,n,r,s,i);const o=this.stream(e,n,r,s,i);return this._consumeAndReturn(o)}async*stream(e,n,r=!0,s,i){if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(e,n,r,s,i);let o=!1;const a=Date.now();let l=!1,c=null,u=0;try{if(r&&!this._initialized?(await this.initialize(),o=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),o=!0),!this._agentExecutor)throw new Error("MCP agent failed to initialize");if(this.useServerManager&&this.serverManager){const C=this.serverManager.tools,m=new Set(C.map(b=>b.name)),w=new Set(this._tools.map(b=>b.name));(m.size!==w.size||[...m].some(b=>!w.has(b)))&&(g.info(`🔄 Tools changed before execution, updating agent. New tools: ${[...m].join(", ")}`),this._tools=C,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const h=s??this.conversationHistory,d=[];for(const C of h)(this._isHumanMessageLike(C)||this._isAIMessageLike(C))&&d.push(C);const f=e.length>50?`${e.slice(0,50).replace(/\n/g," ")}...`:e.replace(/\n/g," ");g.info(`💬 Received query: '${f}'`),g.info("🏁 Starting agent execution");const y=3;let p=0;const S=[...d,new oe(e)];for(;p<=y;){const C={messages:S};let m=!1;const w=await this._agentExecutor.stream(C,{streamMode:"updates",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const b of w){for(const[T,x]of Object.entries(b))if(g.debug(`📦 Node '${T}' output: ${JSON.stringify(x)}`),x&&typeof x=="object"&&"messages"in x){let _=x.messages;Array.isArray(_)||(_=[_]);for(const v of _)S.includes(v)||S.push(v);for(const v of _){if("tool_calls"in v&&Array.isArray(v.tool_calls)&&v.tool_calls.length>0)for(const A of v.tool_calls){const E=A.name||"unknown",P=A.args||{};this.toolsUsedNames.push(E),u++;let $=JSON.stringify(P);$.length>100&&($=`${$.slice(0,97)}...`),g.info(`🔧 Tool call: ${E} with input: ${$}`),yield{action:{tool:E,toolInput:P,log:`Calling tool ${E}`},observation:""}}if(this._isToolMessageLike(v)){const A=v.content;let E=String(A);if(E.length>100&&(E=`${E.slice(0,97)}...`),E=E.replace(/\n/g," "),g.info(`📄 Tool result: ${E}`),this.useServerManager&&this.serverManager){const P=this.serverManager.tools,$=new Set(P.map(X=>X.name)),V=new Set(this._tools.map(X=>X.name));if($.size!==V.size||[...$].some(X=>!V.has(X))){g.info(`🔄 Tools changed during execution. New tools: ${[...$].join(", ")}`),this._tools=P,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),m=!0,p++,g.info(`🔃 Restarting execution with updated tools (restart ${p}/${y})`);break}}}this._isAIMessageLike(v)&&!this._messageHasToolCalls(v)&&(c=this._normalizeOutput(this._getMessageContent(v)),g.info("✅ Agent finished with output"))}if(m)break}if(m)break}if(!m)break;if(p>y){g.warn(`⚠️ Max restarts (${y}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled&&(this.addToHistory(new oe(e)),c&&this.addToHistory(new N(c))),i&&c)try{g.info("🔧 Attempting structured output...");const C=await this._attemptStructuredOutput(c,this.llm,i);return this.memoryEnabled&&this.addToHistory(new N(`Structured result: ${JSON.stringify(C)}`)),g.info("✅ Structured output successful"),l=!0,C}catch(C){throw g.error(`❌ Structured output failed: ${C}`),new Error(`Failed to generate structured output: ${C instanceof Error?C.message:String(C)}`)}return g.info(`🎉 Agent execution complete in ${((Date.now()-a)/1e3).toFixed(2)} seconds`),l=!0,c||"No output generated"}catch(h){throw g.error(`❌ Error running query: ${h}`),o&&r&&(g.info("🧹 Cleaning up resources after error"),await this.close()),h}finally{const h=Date.now()-a;let d=0;this.client?d=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(d=this.connectors.length);const f=this.memoryEnabled?this.conversationHistory.length:0,y=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:"stream",query:e,success:l,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:d,serverIdentifiers:this.connectors.map(p=>p.publicIdentifier),totalToolsAvailable:y.length,toolsAvailableNames:y.map(p=>p.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:n??null,manageConnector:r,externalHistoryUsed:s!==void 0,stepsTaken:u,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:c||"",executionTimeMs:h,errorType:l?null:"execution_error",conversationHistoryLength:f}),r&&!this.client&&o&&(g.info("🧹 Closing agent after stream completion"),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(g.debug("Flushing observability traces..."),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}g.info("🔌 Closing MCPAgent resources…"),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)g.info("🔄 Closing client and cleaning up resources"),await this.client.close(),this.sessions={};else for(const e of this.connectors)g.info("🔄 Disconnecting connector"),await e.disconnect();"connectorToolMap"in this.adapter&&(this.adapter=new gt)}finally{this._initialized=!1,g.info("👋 Agent closed successfully")}}async*prettyStreamEvents(e,n,r=!0,s,i){const{prettyStreamEvents:o}=await dn(async()=>{const{prettyStreamEvents:l}=await import("./display-A5IEINAP-PpmJDTVa.js");return{prettyStreamEvents:l}},__vite__mapDeps([0,1,2])),a="";for await(const l of o(this.streamEvents(e,n,r,s,i)))yield;return a}async*streamEvents(e,n,r=!0,s,i){let o=!1;const a=Date.now();let l=!1,c=0,u=0,h="";i&&(e=this._enhanceQueryWithSchema(e,i));try{r&&!this._initialized?(await this.initialize(),o=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),o=!0);const d=this._agentExecutor;if(!d)throw new Error("MCP agent failed to initialize");this.maxSteps=n??this.maxSteps;const f=typeof e=="string"&&e.length>50?`${e.slice(0,50).replace(/\n/g," ")}...`:typeof e=="string"?e.replace(/\n/g," "):String(e);g.info(`💬 Received query for streamEvents: '${f}'`),this.memoryEnabled&&(g.info(`🔄 Adding user message to history: ${f}`),this.addToHistory(new oe({content:e})));const y=s??this.conversationHistory,p=[];for(const m of y)this._isHumanMessageLike(m)||this._isAIMessageLike(m)||this._isToolMessageLike(m)?p.push(m):g.info(`⚠️ Skipped message of type: ${m.constructor?.name||typeof m}`);const S=[...p,new oe(e)];g.info("callbacks",this.callbacks);const C=d.streamEvents({messages:S},{streamMode:"messages",version:"v2",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const m of C)if(c++,!(!m||typeof m!="object")){if(m.event==="on_chat_model_stream"&&m.data?.chunk?.content&&(u+=m.data.chunk.content.length),m.event==="on_chat_model_stream"&&m.data?.chunk){const w=m.data.chunk;if(w.content){h||(h="");const b=this._normalizeOutput(w.content);h+=b,g.debug(`📝 Accumulated response length: ${h.length}`)}}if(yield m,m.event==="on_chain_end"&&m.data?.output&&!h){const w=m.data.output;Array.isArray(w)&&w.length>0&&w[0]?.text?h=w[0].text:typeof w=="string"?h=w:w&&typeof w=="object"&&"output"in w&&(h=w.output)}}if(i&&h){g.info("🔧 Attempting structured output conversion...");try{let m=!1,w=null,b=null;this._attemptStructuredOutput(h,this.llm,i).then(x=>(m=!0,w=x,x)).catch(x=>{throw m=!0,b=x,x});let T=0;for(;!m;)await new Promise(x=>setTimeout(x,2e3)),m||(T++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${T*2}s)`,elapsed:T*2}});if(b)throw b;w&&(yield{event:"on_structured_output",data:{output:w}},this.memoryEnabled&&this.addToHistory(new N(`Structured result: ${JSON.stringify(w)}`)),g.info("✅ Structured output successful"))}catch(m){g.warn(`⚠️ Structured output failed: ${m}`),yield{event:"on_structured_output_error",data:{error:m instanceof Error?m.message:String(m)}}}}else this.memoryEnabled&&h&&this.addToHistory(new N(h));console.log(`
376
376
 
377
377
  `),g.info(`🎉 StreamEvents complete - ${c} events emitted`),l=!0}catch(d){throw g.error(`❌ Error during streamEvents: ${d}`),o&&r&&(g.info("🧹 Cleaning up resources after initialization error in streamEvents"),await this.close()),d}finally{const d=Date.now()-a;let f=0;this.client?f=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(f=this.connectors.length);const y=this.memoryEnabled?this.conversationHistory.length:0;await this.telemetry.trackAgentExecution({executionMethod:"streamEvents",query:e,success:l,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:f,serverIdentifiers:this.connectors.map(p=>p.publicIdentifier),totalToolsAvailable:this._tools.length,toolsAvailableNames:this._tools.map(p=>p.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:n??null,manageConnector:r,externalHistoryUsed:s!==void 0,response:`[STREAMED RESPONSE - ${u} chars]`,executionTimeMs:d,errorType:l?null:"streaming_error",conversationHistoryLength:y}),r&&!this.client&&o&&(g.info("🧹 Closing agent after streamEvents completion"),await this.close())}}async _attemptStructuredOutput(e,n,r){g.info(`🔄 Attempting structured output with schema: ${JSON.stringify(r,null,2)}`),g.info(`🔄 Raw result: ${JSON.stringify(e,null,2)}`);let s=null,i="";if(g.debug(`🔄 Structured output requested, schema: ${JSON.stringify(Rn(r),null,2)}`),n&&"withStructuredOutput"in n&&typeof n.withStructuredOutput=="function")s=n.withStructuredOutput(r);else if(n)s=n;else throw new Error("LLM is required for structured output");const o=Rn(r),{$schema:a,additionalProperties:l,...c}=o;i=JSON.stringify(c,null,2),g.info(`🔄 Schema description: ${i}`);let u="";typeof e=="string"?u=e:e&&typeof e=="object"&&(u=JSON.stringify(e)),g.info("rawResult",e),u||(u=JSON.stringify(e));const h=3;let d="";for(let f=1;f<=h;f++){g.info(`🔄 Structured output attempt ${f}/${h}`);let y=`
378
378
  Please format the following information according to the EXACT schema specified below.
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-8BCSxqXJ.js","assets/index-CHOOqKAT.js","assets/index-Cf47sZoD.css"])))=>i.map(i=>d[i]);
2
- import{_ as a,a as k}from"./index-CHOOqKAT.js";var y=null,L=null,O=null,J=!1,V=typeof process<"u"&&process.versions?.node;(async()=>{if(V)try{O=(await k(()=>import("./util-t-trnxQI.js").then(e=>e.u),[])).stripVTControlCharacters}catch{}try{y=(await k(()=>import("./index-JiKw9JSs.js"),[])).default}catch{}try{L=(await k(()=>import("./index-8BCSxqXJ.js").then(e=>e.i),__vite__mapDeps([0,1,2]))).highlight}catch{}V&&(!y||!L)&&(J||(J=!0,console.warn(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-OksJgzlF.js","assets/index-IFdSquJo.js","assets/index-CHNXgq6o.css"])))=>i.map(i=>d[i]);
2
+ import{_ as a,a as k}from"./index-IFdSquJo.js";var y=null,L=null,O=null,J=!1,V=typeof process<"u"&&process.versions?.node;(async()=>{if(V)try{O=(await k(()=>import("./util-t-trnxQI.js").then(e=>e.u),[])).stripVTControlCharacters}catch{}try{y=(await k(()=>import("./index-JiKw9JSs.js"),[])).default}catch{}try{L=(await k(()=>import("./index-OksJgzlF.js").then(e=>e.i),__vite__mapDeps([0,1,2]))).highlight}catch{}V&&(!y||!L)&&(J||(J=!0,console.warn(`
3
3
  ✨ For enhanced console output with colors and syntax highlighting, install:
4
4
 
5
5
  npm install chalk cli-highlight
@@ -1 +1 @@
1
- import{_ as c,A as d}from"./index-C9XlRV8D.js";var l={};c(l,{chunkArray:()=>u});const u=(r,s)=>r.reduce((a,n,o)=>{const e=Math.floor(o/s),t=a[e]||[];return a[e]=t.concat([n]),a},[]);var _={};c(_,{Embeddings:()=>h});var h=class{caller;constructor(r){this.caller=new d(r??{})}};export{h as E,l as c,_ as e};
1
+ import{_ as c,A as d}from"./index-Cx63umjv.js";var l={};c(l,{chunkArray:()=>u});const u=(r,s)=>r.reduce((a,n,o)=>{const e=Math.floor(o/s),t=a[e]||[];return a[e]=t.concat([n]),a},[]);var _={};c(_,{Embeddings:()=>h});var h=class{caller;constructor(r){this.caller=new d(r??{})}};export{h as E,l as c,_ as e};
@@ -1,4 +1,4 @@
1
- import{c as Be,s as K,b as me,r as E,F as B,R as ye,S as Re,d as ze,u as je,e as b,E as T,m as we,f as W,g as $e,h as Ve,i as ge,j as We,k as ve,l as x,w as Se,n as qe,o as Je,q as Xe,t as Ke,v as Qe,O as Ge,x as Ye,y as Ee,z as N,A as Ze,B as et,C as tt,D as O,G as rt,H as ee,I as at,J as Q,K as F,L as nt,N as st,M as ot,P as it,Q as Ce,T as lt,U as ut,V as dt,W as ct,X as ft,Y as ht,Z as pt,$ as mt,a0 as yt,a1 as Rt}from"./index-CHOOqKAT.js";import{a2 as Cr,a3 as br,a4 as _r,a5 as xr,a6 as Dr,a7 as Fr,a8 as Ar,a9 as Hr,aa as kr,ab as Pr,ac as Tr,ad as Nr,ae as Lr,af as Or,ag as Ur,ah as Ir,ai as Mr,aj as Br,ak as zr,al as jr,am as $r,an as Vr,ao as Wr,ap as qr,aq as Jr,ar as Xr,as as Kr,at as Qr,au as Gr,av as Yr,aw as Zr,ax as ea,ay as ta,az as ra,aA as aa,aB as na,aC as sa,aD as oa,aE as ia,aF as la,aG as ua,aH as da,aI as ca,aJ as fa,aK as ha,aL as pa,aM as ma,aN as ya,aO as Ra,aP as wa,aQ as ga,aR as va,aS as Sa,aT as Ea,aU as Ca,aV as ba,aW as _a,aX as xa,aY as Da,aZ as Fa,a_ as Aa,a$ as Ha,b0 as ka,b1 as Pa,b2 as Ta,b3 as Na,b4 as La,b5 as Oa,b6 as Ua,b7 as Ia,b8 as Ma,b9 as Ba,ba as za,bb as ja,bc as $a,bd as Va,be as Wa,bf as qa}from"./index-CHOOqKAT.js";var k={},te;function wt(){if(te)return k;te=1,Object.defineProperty(k,"__esModule",{value:!0}),k.parse=l,k.serialize=i;const e=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,r=/^[\u0021-\u003A\u003C-\u007E]*$/,t=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,a=/^[\u0020-\u003A\u003D-\u007E]*$/,n=Object.prototype.toString,o=(()=>{const c=function(){};return c.prototype=Object.create(null),c})();function l(c,y){const f=new o,p=c.length;if(p<2)return f;const w=y?.decode||u;let m=0;do{const g=c.indexOf("=",m);if(g===-1)break;const v=c.indexOf(";",m),S=v===-1?p:v;if(g>S){m=c.lastIndexOf(";",g-1)+1;continue}const C=d(c,m,g),Z=s(c,g,C),H=c.slice(C,Z);if(f[H]===void 0){let _=d(c,g+1,S),Ie=s(c,S,_);const Me=w(c.slice(_,Ie));f[H]=Me}m=S+1}while(m<p);return f}function d(c,y,f){do{const p=c.charCodeAt(y);if(p!==32&&p!==9)return y}while(++y<f);return f}function s(c,y,f){for(;y>f;){const p=c.charCodeAt(--y);if(p!==32&&p!==9)return y+1}return f}function i(c,y,f){const p=f?.encode||encodeURIComponent;if(!e.test(c))throw new TypeError(`argument name is invalid: ${c}`);const w=p(y);if(!r.test(w))throw new TypeError(`argument val is invalid: ${y}`);let m=c+"="+w;if(!f)return m;if(f.maxAge!==void 0){if(!Number.isInteger(f.maxAge))throw new TypeError(`option maxAge is invalid: ${f.maxAge}`);m+="; Max-Age="+f.maxAge}if(f.domain){if(!t.test(f.domain))throw new TypeError(`option domain is invalid: ${f.domain}`);m+="; Domain="+f.domain}if(f.path){if(!a.test(f.path))throw new TypeError(`option path is invalid: ${f.path}`);m+="; Path="+f.path}if(f.expires){if(!h(f.expires)||!Number.isFinite(f.expires.valueOf()))throw new TypeError(`option expires is invalid: ${f.expires}`);m+="; Expires="+f.expires.toUTCString()}if(f.httpOnly&&(m+="; HttpOnly"),f.secure&&(m+="; Secure"),f.partitioned&&(m+="; Partitioned"),f.priority)switch(typeof f.priority=="string"?f.priority.toLowerCase():void 0){case"low":m+="; Priority=Low";break;case"medium":m+="; Priority=Medium";break;case"high":m+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${f.priority}`)}if(f.sameSite)switch(typeof f.sameSite=="string"?f.sameSite.toLowerCase():f.sameSite){case!0:case"strict":m+="; SameSite=Strict";break;case"lax":m+="; SameSite=Lax";break;case"none":m+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${f.sameSite}`)}return m}function u(c){if(c.indexOf("%")===-1)return c;try{return decodeURIComponent(c)}catch{return c}}function h(c){return n.call(c)==="[object Date]"}return k}var re=wt(),A={exports:{}},ae;function gt(){if(ae)return A.exports;ae=1;var e={decodeValues:!0,map:!1,silent:!1};function r(s){return typeof s!="string"||s in{}}function t(){return Object.create(null)}function a(s){return typeof s=="string"&&!!s.trim()}function n(s,i){var u=s.split(";").filter(a),h=u.shift(),c=o(h),y=c.name,f=c.value;if(i=i?Object.assign({},e,i):e,r(y))return null;try{f=i.decodeValues?decodeURIComponent(f):f}catch(w){console.error("set-cookie-parser: failed to decode cookie value. Set options.decodeValues=false to disable decoding.",w)}var p=t();return p.name=y,p.value=f,u.forEach(function(w){var m=w.split("="),g=m.shift().trimLeft().toLowerCase();if(!r(g)){var v=m.join("=");if(g==="expires")p.expires=new Date(v);else if(g==="max-age"){var S=parseInt(v,10);Number.isNaN(S)||(p.maxAge=S)}else g==="secure"?p.secure=!0:g==="httponly"?p.httpOnly=!0:g==="samesite"?p.sameSite=v:g==="partitioned"?p.partitioned=!0:g&&(p[g]=v)}}),p}function o(s){var i="",u="",h=s.split("=");return h.length>1?(i=h.shift(),u=h.join("=")):u=s,{name:i,value:u}}function l(s,i){if(i=i?Object.assign({},e,i):e,!s)return i.map?t():[];if(s.headers)if(typeof s.headers.getSetCookie=="function")s=s.headers.getSetCookie();else if(s.headers["set-cookie"])s=s.headers["set-cookie"];else{var u=s.headers[Object.keys(s.headers).find(function(c){return c.toLowerCase()==="set-cookie"})];!u&&s.headers.cookie&&!i.silent&&console.warn("Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning."),s=u}if(Array.isArray(s)||(s=[s]),i.map){var h=t();return s.filter(a).reduce(function(c,y){var f=n(y,i);return f&&!r(f.name)&&(c[f.name]=f),c},h)}else return s.filter(a).map(function(c){return n(c,i)}).filter(Boolean)}function d(s){if(Array.isArray(s))return s;if(typeof s!="string")return[];var i=[],u=0,h,c,y,f,p;function w(){for(;u<s.length&&/\s/.test(s.charAt(u));)u+=1;return u<s.length}function m(){return c=s.charAt(u),c!=="="&&c!==";"&&c!==","}for(;u<s.length;){for(h=u,p=!1;w();)if(c=s.charAt(u),c===","){for(y=u,u+=1,w(),f=u;u<s.length&&m();)u+=1;u<s.length&&s.charAt(u)==="="?(p=!0,u=f,i.push(s.substring(h,y)),h=u):u=y+1}else u+=1;(!p||u>=s.length)&&i.push(s.substring(h,s.length))}return i}return A.exports=l,A.exports.parse=l,A.exports.parseString=n,A.exports.splitCookiesString=d,A.exports}var vt=gt(),St={};function ur({context:e,url:r,nonce:t}){typeof r=="string"&&(r=new URL(r));let{manifest:a,routeModules:n,criticalCss:o,serverHandoffString:l}=e,d=Be(a.routes,n,e.future,e.isSpaMode);e.staticHandlerContext.loaderData={...e.staticHandlerContext.loaderData};for(let i of e.staticHandlerContext.matches){let u=i.route.id,h=n[u],c=e.manifest.routes[u];h&&c&&K(u,h.clientLoader,c.hasLoader,e.isSpaMode)&&(h.HydrateFallback||!c.hasLoader)&&delete e.staticHandlerContext.loaderData[u]}let s=me(d,e.staticHandlerContext);return E.createElement(E.Fragment,null,E.createElement(B.Provider,{value:{manifest:a,routeModules:n,criticalCss:o,serverHandoffString:l,future:e.future,ssr:e.ssr,isSpaMode:e.isSpaMode,routeDiscovery:e.routeDiscovery,serializeError:e.serializeError,renderMeta:e.renderMeta}},E.createElement(ye,{location:s.state.location},E.createElement(Re,{router:s,context:e.staticHandlerContext,hydrate:!1}))),e.serverHandoffStream?E.createElement(E.Suspense,null,E.createElement(ze,{context:e,identifier:0,reader:e.serverHandoffStream.getReader(),textDecoder:new TextDecoder,nonce:t})):null)}function dr(e,r){return function({initialEntries:a,initialIndex:n,hydrationData:o,future:l}){let d=E.useRef(),s=E.useRef();if(d.current==null){s.current={future:{unstable_subResourceIntegrity:l?.unstable_subResourceIntegrity===!0,v8_middleware:l?.v8_middleware===!0},manifest:{routes:{},entry:{imports:[],module:""},url:"",version:""},routeModules:{},ssr:!1,isSpaMode:!1,routeDiscovery:{mode:"lazy",manifestPath:"/__manifest"}};let i=be($e(e,u=>u),r!==void 0?r:l?.v8_middleware?new W:{},s.current.manifest,s.current.routeModules);d.current=Ve(i,{initialEntries:a,initialIndex:n,hydrationData:o})}return E.createElement(B.Provider,{value:s.current},E.createElement(ge,{router:d.current}))}}function be(e,r,t,a,n){return e.map(o=>{if(!o.id)throw new Error("Expected a route.id in react-router processRoutes() function");let l={id:o.id,path:o.path,index:o.index,Component:o.Component?Qe(o.Component):void 0,HydrateFallback:o.HydrateFallback?Ke(o.HydrateFallback):void 0,ErrorBoundary:o.ErrorBoundary?Xe(o.ErrorBoundary):void 0,action:o.action?s=>o.action({...s,context:r}):void 0,loader:o.loader?s=>o.loader({...s,context:r}):void 0,middleware:o.middleware?o.middleware.map(s=>(...i)=>s({...i[0],context:r},i[1])):void 0,handle:o.handle,shouldRevalidate:o.shouldRevalidate},d={id:o.id,path:o.path,index:o.index,parentId:n,hasAction:o.action!=null,hasLoader:o.loader!=null,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:o.ErrorBoundary!=null,module:"build/stub-path-to-module.js",clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0};return t.routes[l.id]=d,a[o.id]={default:l.Component||Ge,ErrorBoundary:l.ErrorBoundary||void 0,handle:o.handle,links:o.links,meta:o.meta,shouldRevalidate:o.shouldRevalidate},o.children&&(l.children=be(o.children,r,t,a,l.id)),l})}var G=new TextEncoder,Et=async(e,r)=>{let t=G.encode(e),a=await _e(r,["sign"]),n=await crypto.subtle.sign("HMAC",a,t),o=btoa(String.fromCharCode(...new Uint8Array(n))).replace(/=+$/,"");return e+"."+o},Ct=async(e,r)=>{let t=e.lastIndexOf("."),a=e.slice(0,t),n=e.slice(t+1),o=G.encode(a),l=await _e(r,["verify"]);try{let d=bt(atob(n));return await crypto.subtle.verify("HMAC",l,d,o)?a:!1}catch{return!1}},_e=async(e,r)=>crypto.subtle.importKey("raw",G.encode(e),{name:"HMAC",hash:"SHA-256"},!1,r);function bt(e){let r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r}var xe=(e,r={})=>{let{secrets:t=[],...a}={path:"/",sameSite:"lax",...r};return Ht(e,a.expires),{get name(){return e},get isSigned(){return t.length>0},get expires(){return typeof a.maxAge<"u"?new Date(Date.now()+a.maxAge*1e3):a.expires},async parse(n,o){if(!n)return null;let l=re.parse(n,{...a,...o});if(e in l){let d=l[e];return typeof d=="string"&&d!==""?await xt(d,t):""}else return null},async serialize(n,o){return re.serialize(e,n===""?"":await _t(n,t),{...a,...o})}}},De=e=>e!=null&&typeof e.name=="string"&&typeof e.isSigned=="boolean"&&typeof e.parse=="function"&&typeof e.serialize=="function";async function _t(e,r){let t=Dt(e);return r.length>0&&(t=await Et(t,r[0])),t}async function xt(e,r){if(r.length>0){for(let t of r){let a=await Ct(e,t);if(a!==!1)return ne(a)}return null}return ne(e)}function Dt(e){return btoa(At(encodeURIComponent(JSON.stringify(e))))}function ne(e){try{return JSON.parse(decodeURIComponent(Ft(atob(e))))}catch{return{}}}function Ft(e){let r=e.toString(),t="",a=0,n,o;for(;a<r.length;)n=r.charAt(a++),/[\w*+\-./@]/.exec(n)?t+=n:(o=n.charCodeAt(0),o<256?t+="%"+se(o,2):t+="%u"+se(o,4).toUpperCase());return t}function se(e,r){let t=e.toString(16);for(;t.length<r;)t="0"+t;return t}function At(e){let r=e.toString(),t="",a=0,n,o;for(;a<r.length;){if(n=r.charAt(a++),n==="%"){if(r.charAt(a)==="u"){if(o=r.slice(a+1,a+5),/^[\da-f]{4}$/i.exec(o)){t+=String.fromCharCode(parseInt(o,16)),a+=5;continue}}else if(o=r.slice(a,a+2),/^[\da-f]{2}$/i.exec(o)){t+=String.fromCharCode(parseInt(o,16)),a+=2;continue}}t+=n}return t}function Ht(e,r){Se(!r,`The "${e}" cookie has an "expires" property set. This will cause the expires value to not be updated when the session is committed. Instead, you should set the expires value when serializing the cookie. You can use \`commitSession(session, { expires })\` if using a session storage object, or \`cookie.serialize("value", { expires })\` if you're using the cookie directly.`)}function kt(e){return Object.keys(e).reduce((r,t)=>{let a=e[t];return a&&(r[t]=a.module),r},{})}var Pt=(e=>(e.Development="development",e.Production="production",e.Test="test",e))(Pt||{});function Tt(e){return e==="development"||e==="production"||e==="test"}function z(e,r){if(e instanceof Error&&r!=="development"){let t=new Error("Unexpected Server Error");return t.stack=void 0,t}return e}function I(e,r){return Object.entries(e).reduce((t,[a,n])=>Object.assign(t,{[a]:z(n,r)}),{})}function Fe(e,r){let t=z(e,r);return{message:t.message,stack:t.stack}}function oe(e,r){if(!e)return null;let t=Object.entries(e),a={};for(let[n,o]of t)if(x(o))a[n]={...o,__type:"RouteErrorResponse"};else if(o instanceof Error){let l=z(o,r);a[n]={message:l.message,stack:l.stack,__type:"Error",...l.name!=="Error"?{__subType:l.name}:{}}}else a[n]=o;return a}function q(e,r,t){let a=we(e,r,t);return a?a.map(n=>({params:n.params,pathname:n.pathname,route:n.route})):null}async function ie(e,r){let t=await e({request:Lt(Nt(r.request)),params:r.params,context:r.context,unstable_pattern:r.unstable_pattern});if(at(t)&&t.init&&t.init.status&&Q(t.init.status))throw new Response(null,t.init);return t}function Nt(e){let r=new URL(e.url),t=r.searchParams.getAll("index");r.searchParams.delete("index");let a=[];for(let o of t)o&&a.push(o);for(let o of a)r.searchParams.append("index",o);let n={method:e.method,body:e.body,headers:e.headers,signal:e.signal};return n.body&&(n.duplex="half"),new Request(r.href,n)}function Lt(e){let r=new URL(e.url);r.searchParams.delete("_routes");let t={method:e.method,body:e.body,headers:e.headers,signal:e.signal};return t.body&&(t.duplex="half"),new Request(r.href,t)}function U(e,r){if(e===!1||e===null||typeof e>"u")throw console.error("The following error is a bug in React Router; please open an issue! https://github.com/remix-run/react-router/issues/new/choose"),new Error(r)}var Ae="__reactRouterDevServerHooks";function cr(e){globalThis[Ae]=e}function j(){return globalThis[Ae]}function He(e,r){if(typeof process<"u")try{if(St?.IS_RR_BUILD_REQUEST==="yes")return e.headers.get(r)}catch{}return null}function ke(e){let r={};return Object.values(e).forEach(t=>{if(t){let a=t.parentId||"";r[a]||(r[a]=[]),r[a].push(t)}}),r}function Pe(e,r="",t=ke(e)){return(t[r]||[]).map(a=>({...a,children:Pe(e,a.id,t)}))}function Te(e,r,t="",a=ke(e)){return(a[t]||[]).map(n=>{let o={hasErrorBoundary:n.id==="root"||n.module.ErrorBoundary!=null,id:n.id,path:n.path,middleware:n.module.middleware,loader:n.module.loader?async l=>{let d=He(l.request,"X-React-Router-Prerender-Data");if(d!=null){let i=d&&decodeURI(d);U(i,"Missing prerendered data for route");let u=new TextEncoder().encode(i),h=new ReadableStream({start(f){f.enqueue(u),f.close()}}),y=(await Ee(h,globalThis)).value;if(y&&N in y){let f=y[N],p={status:f.status};throw f.reload?Ze(f.redirect,p):f.replace?et(f.redirect,p):tt(f.redirect,p)}else{U(y&&n.id in y,"Unable to decode prerendered data");let f=y[n.id];return U("data"in f,"Unable to process prerendered data"),f.data}}return await ie(n.module.loader,l)}:void 0,action:n.module.action?l=>ie(n.module.action,l):void 0,handle:n.module.handle};return n.index?{index:!0,...o}:{caseSensitive:n.caseSensitive,children:Te(e,r,n.id,a),...o}})}function le(e){return it(JSON.stringify(e))}function Y(e,r){return Ot(e,t=>{let a=r.routes[t.route.id];return U(a,`Route with id "${t.route.id}" not found in build`),a.module.headers})}function Ot(e,r,t){let a=e.errors?e.matches.findIndex(d=>e.errors[d.route.id]):-1,n=a>=0?e.matches.slice(0,a+1):e.matches,o;if(a>=0){let{actionHeaders:d,actionData:s,loaderHeaders:i,loaderData:u}=e;e.matches.slice(a).some(h=>{let c=h.route.id;return d[c]&&(!s||!s.hasOwnProperty(c))?o=d[c]:i[c]&&!u.hasOwnProperty(c)&&(o=i[c]),o!=null})}const l=new Headers(t);return n.reduce((d,s,i)=>{let{id:u}=s.route,h=e.loaderHeaders[u]||new Headers,c=e.actionHeaders[u]||new Headers,y=o!=null&&i===n.length-1,f=y&&o!==h&&o!==c,p=r(s);if(p==null){let m=new Headers(d);return f&&D(o,m),D(c,m),D(h,m),m}let w=new Headers(typeof p=="function"?p({loaderHeaders:h,parentHeaders:d,actionHeaders:c,errorHeaders:y?o:void 0}):p);return f&&D(o,w),D(c,w),D(h,w),D(d,w),w},new Headers(l))}function D(e,r){let t=e.get("Set-Cookie");if(t){let a=vt.splitCookiesString(t),n=new Set(r.getSetCookie());a.forEach(o=>{n.has(o)||r.append("Set-Cookie",o)})}}var Ne=new Set([...st,304]);async function Ut(e,r,t,a,n,o,l){try{let u=new Request(n,{method:a.method,body:a.body,headers:a.headers,signal:a.signal,...a.body?{duplex:"half"}:void 0}),h=await t.query(u,{requestContext:o,skipLoaderErrorBubbling:!0,skipRevalidation:!0,generateMiddlewareResponse:e.future.v8_middleware?async c=>{try{let y=await c(u);return d(y)}catch(y){return s(y)}}:void 0});return d(h)}catch(u){return s(u)}function d(u){return F(u)?u:i(u)}function s(u){return l(u),L(a,e,r,{result:{error:u},headers:new Headers,status:500})}function i(u){let h=Y(u,e);if(Q(u.statusCode)&&h.has("Location"))return new Response(null,{status:u.statusCode,headers:h});u.errors&&(Object.values(u.errors).forEach(y=>{(!x(y)||y.error)&&l(y)}),u.errors=I(u.errors,r));let c;return u.errors?c={error:Object.values(u.errors)[0]}:c={data:Object.values(u.actionData||{})[0]},L(a,e,r,{result:c,headers:h,status:u.statusCode})}}async function It(e,r,t,a,n,o,l){let d=new URL(a.url).searchParams.get("_routes"),s=d?new Set(d.split(",")):null;try{let c=new Request(n,{headers:a.headers,signal:a.signal}),y=await t.query(c,{requestContext:o,filterMatchesToLoad:f=>!s||s.has(f.route.id),skipLoaderErrorBubbling:!0,generateMiddlewareResponse:e.future.v8_middleware?async f=>{try{let p=await f(c);return i(p)}catch(p){return u(p)}}:void 0});return i(y)}catch(c){return u(c)}function i(c){return F(c)?c:h(c)}function u(c){return l(c),L(a,e,r,{result:{error:c},headers:new Headers,status:500})}function h(c){let y=Y(c,e);if(Q(c.statusCode)&&y.has("Location"))return new Response(null,{status:c.statusCode,headers:y});c.errors&&(Object.values(c.errors).forEach(w=>{(!x(w)||w.error)&&l(w)}),c.errors=I(c.errors,r));let f={},p=new Set(c.matches.filter(w=>s?s.has(w.route.id):w.route.loader!=null).map(w=>w.route.id));if(c.errors)for(let[w,m]of Object.entries(c.errors))f[w]={error:m};for(let[w,m]of Object.entries(c.loaderData))!(w in f)&&p.has(w)&&(f[w]={data:m});return L(a,e,r,{result:f,headers:y,status:c.statusCode})}}function L(e,r,t,{result:a,headers:n,status:o}){let l=new Headers(n);return l.set("X-Remix-Response","yes"),Ne.has(o)?new Response(null,{status:o,headers:l}):(l.set("Content-Type","text/x-script"),l.delete("Content-Length"),new Response(J(a,e.signal,r.entry.module.streamTimeout,t),{status:o||200,headers:l}))}function ue(e,r,t,a){let n=Mt(e.status,e.headers,t.basename),o=new Headers(e.headers);return o.delete("Location"),o.set("Content-Type","text/x-script"),L(r,t,a,{result:r.method==="GET"?{[N]:n}:n,headers:o,status:ve})}function Mt(e,r,t){let a=r.get("Location");return t&&(a=O(a,t)||a),{redirect:a,status:e,revalidate:r.has("X-Remix-Revalidate")||r.has("Set-Cookie"),reload:r.has("X-Remix-Reload-Document"),replace:r.has("X-Remix-Replace")}}function J(e,r,t,a){let n=new AbortController,o=setTimeout(()=>n.abort(new Error("Server Timeout")),typeof t=="number"?t:4950);return r.addEventListener("abort",()=>clearTimeout(o)),ot(e,{signal:n.signal,plugins:[l=>{if(l instanceof Error){let{name:d,message:s,stack:i}=a==="production"?z(l,a):l;return["SanitizedError",d,s,i]}if(l instanceof T){let{data:d,status:s,statusText:i}=l;return["ErrorResponse",d,s,i]}if(l&&typeof l=="object"&&N in l)return["SingleFetchRedirect",l[N]]}],postPlugins:[l=>{if(l&&typeof l=="object")return["SingleFetchClassInstance",Object.fromEntries(Object.entries(l))]},()=>["SingleFetchFallback"]]})}function de(e,r){let t=Pe(e.routes),a=Te(e.routes,e.future),n=Tt(r)?r:"production",o=qe(a,{basename:e.basename,unstable_instrumentations:e.entry.module.unstable_instrumentations}),l=e.entry.module.handleError||((s,{request:i})=>{n!=="test"&&!i.signal.aborted&&console.error(x(s)&&s.error?s.error:s)}),d=async(s,i)=>{let u={},h,c=S=>{r==="development"&&j()?.processRequestError?.(S),l(S,{context:h,params:u,request:s})};if(e.future.v8_middleware){if(i&&!(i instanceof W)){let S=new Error("Invalid `context` value provided to `handleRequest`. When middleware is enabled you must return an instance of `RouterContextProvider` from your `getLoadContext` function.");return c(S),M(S,n)}h=i||new W}else h=i||{};let y=new URL(s.url),f=e.basename||"/",p=y.pathname;O(p,f)==="/_root.data"?p=f:p.endsWith(".data")&&(p=p.replace(/\.data$/,"")),O(p,f)!=="/"&&p.endsWith("/")&&(p=p.slice(0,-1));let w=He(s,"X-React-Router-SPA-Mode")==="yes";if(!e.ssr){let S=decodeURI(p);if(f!=="/"){let C=O(S,f);if(C==null)return l(new T(404,"Not Found",`Refusing to prerender the \`${S}\` path because it does not start with the basename \`${f}\``),{context:h,params:u,request:s}),new Response("Not Found",{status:404,statusText:"Not Found"});S=C}if(e.prerender.length===0)w=!0;else if(!e.prerender.includes(S)&&!e.prerender.includes(S+"/")){if(y.pathname.endsWith(".data"))return l(new T(404,"Not Found",`Refusing to SSR the path \`${S}\` because \`ssr:false\` is set and the path is not included in the \`prerender\` config, so in production the path will be a 404.`),{context:h,params:u,request:s}),new Response("Not Found",{status:404,statusText:"Not Found"});w=!0}}let m=rt(e.routeDiscovery.manifestPath,f);if(y.pathname===m)try{return await Bt(e,t,y)}catch(S){return c(S),new Response("Unknown Server Error",{status:500})}let g=q(t,p,e.basename);g&&g.length>0&&Object.assign(u,g[0].params);let v;if(y.pathname.endsWith(".data")){let S=new URL(s.url);S.pathname=p;let C=q(t,S.pathname,e.basename);v=await zt(n,e,o,s,S,h,c),ee(v)&&(v=ue(v,s,e,n)),e.entry.module.handleDataRequest&&(v=await e.entry.module.handleDataRequest(v,{context:h,params:C?C[0].params:{},request:s}),ee(v)&&(v=ue(v,s,e,n)))}else if(!w&&g&&g[g.length-1].route.module.default==null&&g[g.length-1].route.module.ErrorBoundary==null)v=await $t(n,e,o,g.slice(-1)[0].route.id,s,h,c);else{let{pathname:S}=y,C;e.unstable_getCriticalCss?C=await e.unstable_getCriticalCss({pathname:S}):r==="development"&&j()?.getCriticalCss&&(C=await j()?.getCriticalCss?.(S)),v=await jt(n,e,o,s,h,c,w,C)}return s.method==="HEAD"?new Response(null,{headers:v.headers,status:v.status,statusText:v.statusText}):v};return e.entry.module.unstable_instrumentations&&(d=Je(d,e.entry.module.unstable_instrumentations.map(s=>s.handler).filter(Boolean))),{routes:t,dataRoutes:a,serverMode:n,staticHandler:o,errorHandler:l,requestHandler:d}}var fr=(e,r)=>{let t,a,n,o,l,d;return async function(i,u){if(t=typeof e=="function"?await e():e,typeof e=="function"){let h=de(t,r);a=h.routes,n=h.serverMode,o=h.staticHandler,l=h.errorHandler,d=h.requestHandler}else if(!a||!n||!o||!l||!d){let h=de(t,r);a=h.routes,n=h.serverMode,o=h.staticHandler,l=h.errorHandler,d=h.requestHandler}return d(i,u)}};async function Bt(e,r,t){if(e.assets.version!==t.searchParams.get("version"))return new Response(null,{status:204,headers:{"X-Remix-Reload-Document":"true"}});let a={};if(t.searchParams.has("paths")){let n=new Set;(t.searchParams.get("paths")||"").split(",").filter(Boolean).forEach(d=>{d.startsWith("/")||(d=`/${d}`);let s=d.split("/").slice(1);s.forEach((i,u)=>{let h=s.slice(0,u+1).join("/");n.add(`/${h}`)})});for(let d of n){let s=q(r,d,e.basename);if(s)for(let i of s){let u=i.route.id,h=e.assets.routes[u];h&&(a[u]=h)}}return Response.json(a,{headers:{"Cache-Control":"public, max-age=31536000, immutable"}})}return new Response("Invalid Request",{status:400})}async function zt(e,r,t,a,n,o,l){return a.method!=="GET"?await Ut(r,e,t,a,n,o,l):await It(r,e,t,a,n,o,l)}async function jt(e,r,t,a,n,o,l,d){try{let i=await t.query(a,{requestContext:n,generateMiddlewareResponse:r.future.v8_middleware?async u=>{try{let h=await u(a);return F(h)||(h=await s(h,l)),h}catch(h){return o(h),new Response(null,{status:500})}}:void 0});return F(i)||(i=await s(i,l)),i}catch(i){return o(i),new Response(null,{status:500})}async function s(i,u){let h=Y(i,r);if(Ne.has(i.statusCode))return new Response(null,{status:i.statusCode,headers:h});i.errors&&(Object.values(i.errors).forEach(w=>{(!x(w)||w.error)&&o(w)}),i.errors=I(i.errors,e));let c={loaderData:i.loaderData,actionData:i.actionData,errors:oe(i.errors,e)},y={basename:r.basename,future:r.future,routeDiscovery:r.routeDiscovery,ssr:r.ssr,isSpaMode:u},f={manifest:r.assets,routeModules:kt(r.routes),staticHandlerContext:i,criticalCss:d,serverHandoffString:le({...y,criticalCss:d}),serverHandoffStream:J(c,a.signal,r.entry.module.streamTimeout,e),renderMeta:{},future:r.future,ssr:r.ssr,routeDiscovery:r.routeDiscovery,isSpaMode:u,serializeError:w=>Fe(w,e)},p=r.entry.module.default;try{return await p(a,i.statusCode,h,f,n)}catch(w){o(w);let m=w;if(F(w))try{let v=await Wt(w);m=new T(w.status,w.statusText,v)}catch{}i=nt(t.dataRoutes,i,m),i.errors&&(i.errors=I(i.errors,e));let g={loaderData:i.loaderData,actionData:i.actionData,errors:oe(i.errors,e)};f={...f,staticHandlerContext:i,serverHandoffString:le(y),serverHandoffStream:J(g,a.signal,r.entry.module.streamTimeout,e),renderMeta:{}};try{return await p(a,i.statusCode,h,f,n)}catch(v){return o(v),M(v,e)}}}}async function $t(e,r,t,a,n,o,l){try{let i=await t.queryRoute(n,{routeId:a,requestContext:o,generateMiddlewareResponse:r.future.v8_middleware?async u=>{try{let h=await u(n);return d(h)}catch(h){return s(h)}}:void 0});return d(i)}catch(i){return s(i)}function d(i){return F(i)?i:typeof i=="string"?new Response(i):Response.json(i)}function s(i){if(F(i))return i;if(x(i))return l(i),Vt(i,e);if(i instanceof Error&&i.message==="Expected a response from queryRoute"){let u=new Error("Expected a Response to be returned from resource route handler");return l(u),M(u,e)}return l(i),M(i,e)}}function Vt(e,r){return Response.json(Fe(e.error||new Error("Unexpected Server Error"),r),{status:e.status,statusText:e.statusText})}function M(e,r){let t="Unexpected Server Error";return r!=="production"&&(t+=`
1
+ import{c as Be,s as K,b as me,r as E,F as B,R as ye,S as Re,d as ze,u as je,e as b,E as T,m as we,f as W,g as $e,h as Ve,i as ge,j as We,k as ve,l as x,w as Se,n as qe,o as Je,q as Xe,t as Ke,v as Qe,O as Ge,x as Ye,y as Ee,z as N,A as Ze,B as et,C as tt,D as O,G as rt,H as ee,I as at,J as Q,K as F,L as nt,N as st,M as ot,P as it,Q as Ce,T as lt,U as ut,V as dt,W as ct,X as ft,Y as ht,Z as pt,$ as mt,a0 as yt,a1 as Rt}from"./index-IFdSquJo.js";import{a2 as Cr,a3 as br,a4 as _r,a5 as xr,a6 as Dr,a7 as Fr,a8 as Ar,a9 as Hr,aa as kr,ab as Pr,ac as Tr,ad as Nr,ae as Lr,af as Or,ag as Ur,ah as Ir,ai as Mr,aj as Br,ak as zr,al as jr,am as $r,an as Vr,ao as Wr,ap as qr,aq as Jr,ar as Xr,as as Kr,at as Qr,au as Gr,av as Yr,aw as Zr,ax as ea,ay as ta,az as ra,aA as aa,aB as na,aC as sa,aD as oa,aE as ia,aF as la,aG as ua,aH as da,aI as ca,aJ as fa,aK as ha,aL as pa,aM as ma,aN as ya,aO as Ra,aP as wa,aQ as ga,aR as va,aS as Sa,aT as Ea,aU as Ca,aV as ba,aW as _a,aX as xa,aY as Da,aZ as Fa,a_ as Aa,a$ as Ha,b0 as ka,b1 as Pa,b2 as Ta,b3 as Na,b4 as La,b5 as Oa,b6 as Ua,b7 as Ia,b8 as Ma,b9 as Ba,ba as za,bb as ja,bc as $a,bd as Va,be as Wa,bf as qa}from"./index-IFdSquJo.js";var k={},te;function wt(){if(te)return k;te=1,Object.defineProperty(k,"__esModule",{value:!0}),k.parse=l,k.serialize=i;const e=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,r=/^[\u0021-\u003A\u003C-\u007E]*$/,t=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,a=/^[\u0020-\u003A\u003D-\u007E]*$/,n=Object.prototype.toString,o=(()=>{const c=function(){};return c.prototype=Object.create(null),c})();function l(c,y){const f=new o,p=c.length;if(p<2)return f;const w=y?.decode||u;let m=0;do{const g=c.indexOf("=",m);if(g===-1)break;const v=c.indexOf(";",m),S=v===-1?p:v;if(g>S){m=c.lastIndexOf(";",g-1)+1;continue}const C=d(c,m,g),Z=s(c,g,C),H=c.slice(C,Z);if(f[H]===void 0){let _=d(c,g+1,S),Ie=s(c,S,_);const Me=w(c.slice(_,Ie));f[H]=Me}m=S+1}while(m<p);return f}function d(c,y,f){do{const p=c.charCodeAt(y);if(p!==32&&p!==9)return y}while(++y<f);return f}function s(c,y,f){for(;y>f;){const p=c.charCodeAt(--y);if(p!==32&&p!==9)return y+1}return f}function i(c,y,f){const p=f?.encode||encodeURIComponent;if(!e.test(c))throw new TypeError(`argument name is invalid: ${c}`);const w=p(y);if(!r.test(w))throw new TypeError(`argument val is invalid: ${y}`);let m=c+"="+w;if(!f)return m;if(f.maxAge!==void 0){if(!Number.isInteger(f.maxAge))throw new TypeError(`option maxAge is invalid: ${f.maxAge}`);m+="; Max-Age="+f.maxAge}if(f.domain){if(!t.test(f.domain))throw new TypeError(`option domain is invalid: ${f.domain}`);m+="; Domain="+f.domain}if(f.path){if(!a.test(f.path))throw new TypeError(`option path is invalid: ${f.path}`);m+="; Path="+f.path}if(f.expires){if(!h(f.expires)||!Number.isFinite(f.expires.valueOf()))throw new TypeError(`option expires is invalid: ${f.expires}`);m+="; Expires="+f.expires.toUTCString()}if(f.httpOnly&&(m+="; HttpOnly"),f.secure&&(m+="; Secure"),f.partitioned&&(m+="; Partitioned"),f.priority)switch(typeof f.priority=="string"?f.priority.toLowerCase():void 0){case"low":m+="; Priority=Low";break;case"medium":m+="; Priority=Medium";break;case"high":m+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${f.priority}`)}if(f.sameSite)switch(typeof f.sameSite=="string"?f.sameSite.toLowerCase():f.sameSite){case!0:case"strict":m+="; SameSite=Strict";break;case"lax":m+="; SameSite=Lax";break;case"none":m+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${f.sameSite}`)}return m}function u(c){if(c.indexOf("%")===-1)return c;try{return decodeURIComponent(c)}catch{return c}}function h(c){return n.call(c)==="[object Date]"}return k}var re=wt(),A={exports:{}},ae;function gt(){if(ae)return A.exports;ae=1;var e={decodeValues:!0,map:!1,silent:!1};function r(s){return typeof s!="string"||s in{}}function t(){return Object.create(null)}function a(s){return typeof s=="string"&&!!s.trim()}function n(s,i){var u=s.split(";").filter(a),h=u.shift(),c=o(h),y=c.name,f=c.value;if(i=i?Object.assign({},e,i):e,r(y))return null;try{f=i.decodeValues?decodeURIComponent(f):f}catch(w){console.error("set-cookie-parser: failed to decode cookie value. Set options.decodeValues=false to disable decoding.",w)}var p=t();return p.name=y,p.value=f,u.forEach(function(w){var m=w.split("="),g=m.shift().trimLeft().toLowerCase();if(!r(g)){var v=m.join("=");if(g==="expires")p.expires=new Date(v);else if(g==="max-age"){var S=parseInt(v,10);Number.isNaN(S)||(p.maxAge=S)}else g==="secure"?p.secure=!0:g==="httponly"?p.httpOnly=!0:g==="samesite"?p.sameSite=v:g==="partitioned"?p.partitioned=!0:g&&(p[g]=v)}}),p}function o(s){var i="",u="",h=s.split("=");return h.length>1?(i=h.shift(),u=h.join("=")):u=s,{name:i,value:u}}function l(s,i){if(i=i?Object.assign({},e,i):e,!s)return i.map?t():[];if(s.headers)if(typeof s.headers.getSetCookie=="function")s=s.headers.getSetCookie();else if(s.headers["set-cookie"])s=s.headers["set-cookie"];else{var u=s.headers[Object.keys(s.headers).find(function(c){return c.toLowerCase()==="set-cookie"})];!u&&s.headers.cookie&&!i.silent&&console.warn("Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning."),s=u}if(Array.isArray(s)||(s=[s]),i.map){var h=t();return s.filter(a).reduce(function(c,y){var f=n(y,i);return f&&!r(f.name)&&(c[f.name]=f),c},h)}else return s.filter(a).map(function(c){return n(c,i)}).filter(Boolean)}function d(s){if(Array.isArray(s))return s;if(typeof s!="string")return[];var i=[],u=0,h,c,y,f,p;function w(){for(;u<s.length&&/\s/.test(s.charAt(u));)u+=1;return u<s.length}function m(){return c=s.charAt(u),c!=="="&&c!==";"&&c!==","}for(;u<s.length;){for(h=u,p=!1;w();)if(c=s.charAt(u),c===","){for(y=u,u+=1,w(),f=u;u<s.length&&m();)u+=1;u<s.length&&s.charAt(u)==="="?(p=!0,u=f,i.push(s.substring(h,y)),h=u):u=y+1}else u+=1;(!p||u>=s.length)&&i.push(s.substring(h,s.length))}return i}return A.exports=l,A.exports.parse=l,A.exports.parseString=n,A.exports.splitCookiesString=d,A.exports}var vt=gt(),St={};function ur({context:e,url:r,nonce:t}){typeof r=="string"&&(r=new URL(r));let{manifest:a,routeModules:n,criticalCss:o,serverHandoffString:l}=e,d=Be(a.routes,n,e.future,e.isSpaMode);e.staticHandlerContext.loaderData={...e.staticHandlerContext.loaderData};for(let i of e.staticHandlerContext.matches){let u=i.route.id,h=n[u],c=e.manifest.routes[u];h&&c&&K(u,h.clientLoader,c.hasLoader,e.isSpaMode)&&(h.HydrateFallback||!c.hasLoader)&&delete e.staticHandlerContext.loaderData[u]}let s=me(d,e.staticHandlerContext);return E.createElement(E.Fragment,null,E.createElement(B.Provider,{value:{manifest:a,routeModules:n,criticalCss:o,serverHandoffString:l,future:e.future,ssr:e.ssr,isSpaMode:e.isSpaMode,routeDiscovery:e.routeDiscovery,serializeError:e.serializeError,renderMeta:e.renderMeta}},E.createElement(ye,{location:s.state.location},E.createElement(Re,{router:s,context:e.staticHandlerContext,hydrate:!1}))),e.serverHandoffStream?E.createElement(E.Suspense,null,E.createElement(ze,{context:e,identifier:0,reader:e.serverHandoffStream.getReader(),textDecoder:new TextDecoder,nonce:t})):null)}function dr(e,r){return function({initialEntries:a,initialIndex:n,hydrationData:o,future:l}){let d=E.useRef(),s=E.useRef();if(d.current==null){s.current={future:{unstable_subResourceIntegrity:l?.unstable_subResourceIntegrity===!0,v8_middleware:l?.v8_middleware===!0},manifest:{routes:{},entry:{imports:[],module:""},url:"",version:""},routeModules:{},ssr:!1,isSpaMode:!1,routeDiscovery:{mode:"lazy",manifestPath:"/__manifest"}};let i=be($e(e,u=>u),r!==void 0?r:l?.v8_middleware?new W:{},s.current.manifest,s.current.routeModules);d.current=Ve(i,{initialEntries:a,initialIndex:n,hydrationData:o})}return E.createElement(B.Provider,{value:s.current},E.createElement(ge,{router:d.current}))}}function be(e,r,t,a,n){return e.map(o=>{if(!o.id)throw new Error("Expected a route.id in react-router processRoutes() function");let l={id:o.id,path:o.path,index:o.index,Component:o.Component?Qe(o.Component):void 0,HydrateFallback:o.HydrateFallback?Ke(o.HydrateFallback):void 0,ErrorBoundary:o.ErrorBoundary?Xe(o.ErrorBoundary):void 0,action:o.action?s=>o.action({...s,context:r}):void 0,loader:o.loader?s=>o.loader({...s,context:r}):void 0,middleware:o.middleware?o.middleware.map(s=>(...i)=>s({...i[0],context:r},i[1])):void 0,handle:o.handle,shouldRevalidate:o.shouldRevalidate},d={id:o.id,path:o.path,index:o.index,parentId:n,hasAction:o.action!=null,hasLoader:o.loader!=null,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:o.ErrorBoundary!=null,module:"build/stub-path-to-module.js",clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0};return t.routes[l.id]=d,a[o.id]={default:l.Component||Ge,ErrorBoundary:l.ErrorBoundary||void 0,handle:o.handle,links:o.links,meta:o.meta,shouldRevalidate:o.shouldRevalidate},o.children&&(l.children=be(o.children,r,t,a,l.id)),l})}var G=new TextEncoder,Et=async(e,r)=>{let t=G.encode(e),a=await _e(r,["sign"]),n=await crypto.subtle.sign("HMAC",a,t),o=btoa(String.fromCharCode(...new Uint8Array(n))).replace(/=+$/,"");return e+"."+o},Ct=async(e,r)=>{let t=e.lastIndexOf("."),a=e.slice(0,t),n=e.slice(t+1),o=G.encode(a),l=await _e(r,["verify"]);try{let d=bt(atob(n));return await crypto.subtle.verify("HMAC",l,d,o)?a:!1}catch{return!1}},_e=async(e,r)=>crypto.subtle.importKey("raw",G.encode(e),{name:"HMAC",hash:"SHA-256"},!1,r);function bt(e){let r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r}var xe=(e,r={})=>{let{secrets:t=[],...a}={path:"/",sameSite:"lax",...r};return Ht(e,a.expires),{get name(){return e},get isSigned(){return t.length>0},get expires(){return typeof a.maxAge<"u"?new Date(Date.now()+a.maxAge*1e3):a.expires},async parse(n,o){if(!n)return null;let l=re.parse(n,{...a,...o});if(e in l){let d=l[e];return typeof d=="string"&&d!==""?await xt(d,t):""}else return null},async serialize(n,o){return re.serialize(e,n===""?"":await _t(n,t),{...a,...o})}}},De=e=>e!=null&&typeof e.name=="string"&&typeof e.isSigned=="boolean"&&typeof e.parse=="function"&&typeof e.serialize=="function";async function _t(e,r){let t=Dt(e);return r.length>0&&(t=await Et(t,r[0])),t}async function xt(e,r){if(r.length>0){for(let t of r){let a=await Ct(e,t);if(a!==!1)return ne(a)}return null}return ne(e)}function Dt(e){return btoa(At(encodeURIComponent(JSON.stringify(e))))}function ne(e){try{return JSON.parse(decodeURIComponent(Ft(atob(e))))}catch{return{}}}function Ft(e){let r=e.toString(),t="",a=0,n,o;for(;a<r.length;)n=r.charAt(a++),/[\w*+\-./@]/.exec(n)?t+=n:(o=n.charCodeAt(0),o<256?t+="%"+se(o,2):t+="%u"+se(o,4).toUpperCase());return t}function se(e,r){let t=e.toString(16);for(;t.length<r;)t="0"+t;return t}function At(e){let r=e.toString(),t="",a=0,n,o;for(;a<r.length;){if(n=r.charAt(a++),n==="%"){if(r.charAt(a)==="u"){if(o=r.slice(a+1,a+5),/^[\da-f]{4}$/i.exec(o)){t+=String.fromCharCode(parseInt(o,16)),a+=5;continue}}else if(o=r.slice(a,a+2),/^[\da-f]{2}$/i.exec(o)){t+=String.fromCharCode(parseInt(o,16)),a+=2;continue}}t+=n}return t}function Ht(e,r){Se(!r,`The "${e}" cookie has an "expires" property set. This will cause the expires value to not be updated when the session is committed. Instead, you should set the expires value when serializing the cookie. You can use \`commitSession(session, { expires })\` if using a session storage object, or \`cookie.serialize("value", { expires })\` if you're using the cookie directly.`)}function kt(e){return Object.keys(e).reduce((r,t)=>{let a=e[t];return a&&(r[t]=a.module),r},{})}var Pt=(e=>(e.Development="development",e.Production="production",e.Test="test",e))(Pt||{});function Tt(e){return e==="development"||e==="production"||e==="test"}function z(e,r){if(e instanceof Error&&r!=="development"){let t=new Error("Unexpected Server Error");return t.stack=void 0,t}return e}function I(e,r){return Object.entries(e).reduce((t,[a,n])=>Object.assign(t,{[a]:z(n,r)}),{})}function Fe(e,r){let t=z(e,r);return{message:t.message,stack:t.stack}}function oe(e,r){if(!e)return null;let t=Object.entries(e),a={};for(let[n,o]of t)if(x(o))a[n]={...o,__type:"RouteErrorResponse"};else if(o instanceof Error){let l=z(o,r);a[n]={message:l.message,stack:l.stack,__type:"Error",...l.name!=="Error"?{__subType:l.name}:{}}}else a[n]=o;return a}function q(e,r,t){let a=we(e,r,t);return a?a.map(n=>({params:n.params,pathname:n.pathname,route:n.route})):null}async function ie(e,r){let t=await e({request:Lt(Nt(r.request)),params:r.params,context:r.context,unstable_pattern:r.unstable_pattern});if(at(t)&&t.init&&t.init.status&&Q(t.init.status))throw new Response(null,t.init);return t}function Nt(e){let r=new URL(e.url),t=r.searchParams.getAll("index");r.searchParams.delete("index");let a=[];for(let o of t)o&&a.push(o);for(let o of a)r.searchParams.append("index",o);let n={method:e.method,body:e.body,headers:e.headers,signal:e.signal};return n.body&&(n.duplex="half"),new Request(r.href,n)}function Lt(e){let r=new URL(e.url);r.searchParams.delete("_routes");let t={method:e.method,body:e.body,headers:e.headers,signal:e.signal};return t.body&&(t.duplex="half"),new Request(r.href,t)}function U(e,r){if(e===!1||e===null||typeof e>"u")throw console.error("The following error is a bug in React Router; please open an issue! https://github.com/remix-run/react-router/issues/new/choose"),new Error(r)}var Ae="__reactRouterDevServerHooks";function cr(e){globalThis[Ae]=e}function j(){return globalThis[Ae]}function He(e,r){if(typeof process<"u")try{if(St?.IS_RR_BUILD_REQUEST==="yes")return e.headers.get(r)}catch{}return null}function ke(e){let r={};return Object.values(e).forEach(t=>{if(t){let a=t.parentId||"";r[a]||(r[a]=[]),r[a].push(t)}}),r}function Pe(e,r="",t=ke(e)){return(t[r]||[]).map(a=>({...a,children:Pe(e,a.id,t)}))}function Te(e,r,t="",a=ke(e)){return(a[t]||[]).map(n=>{let o={hasErrorBoundary:n.id==="root"||n.module.ErrorBoundary!=null,id:n.id,path:n.path,middleware:n.module.middleware,loader:n.module.loader?async l=>{let d=He(l.request,"X-React-Router-Prerender-Data");if(d!=null){let i=d&&decodeURI(d);U(i,"Missing prerendered data for route");let u=new TextEncoder().encode(i),h=new ReadableStream({start(f){f.enqueue(u),f.close()}}),y=(await Ee(h,globalThis)).value;if(y&&N in y){let f=y[N],p={status:f.status};throw f.reload?Ze(f.redirect,p):f.replace?et(f.redirect,p):tt(f.redirect,p)}else{U(y&&n.id in y,"Unable to decode prerendered data");let f=y[n.id];return U("data"in f,"Unable to process prerendered data"),f.data}}return await ie(n.module.loader,l)}:void 0,action:n.module.action?l=>ie(n.module.action,l):void 0,handle:n.module.handle};return n.index?{index:!0,...o}:{caseSensitive:n.caseSensitive,children:Te(e,r,n.id,a),...o}})}function le(e){return it(JSON.stringify(e))}function Y(e,r){return Ot(e,t=>{let a=r.routes[t.route.id];return U(a,`Route with id "${t.route.id}" not found in build`),a.module.headers})}function Ot(e,r,t){let a=e.errors?e.matches.findIndex(d=>e.errors[d.route.id]):-1,n=a>=0?e.matches.slice(0,a+1):e.matches,o;if(a>=0){let{actionHeaders:d,actionData:s,loaderHeaders:i,loaderData:u}=e;e.matches.slice(a).some(h=>{let c=h.route.id;return d[c]&&(!s||!s.hasOwnProperty(c))?o=d[c]:i[c]&&!u.hasOwnProperty(c)&&(o=i[c]),o!=null})}const l=new Headers(t);return n.reduce((d,s,i)=>{let{id:u}=s.route,h=e.loaderHeaders[u]||new Headers,c=e.actionHeaders[u]||new Headers,y=o!=null&&i===n.length-1,f=y&&o!==h&&o!==c,p=r(s);if(p==null){let m=new Headers(d);return f&&D(o,m),D(c,m),D(h,m),m}let w=new Headers(typeof p=="function"?p({loaderHeaders:h,parentHeaders:d,actionHeaders:c,errorHeaders:y?o:void 0}):p);return f&&D(o,w),D(c,w),D(h,w),D(d,w),w},new Headers(l))}function D(e,r){let t=e.get("Set-Cookie");if(t){let a=vt.splitCookiesString(t),n=new Set(r.getSetCookie());a.forEach(o=>{n.has(o)||r.append("Set-Cookie",o)})}}var Ne=new Set([...st,304]);async function Ut(e,r,t,a,n,o,l){try{let u=new Request(n,{method:a.method,body:a.body,headers:a.headers,signal:a.signal,...a.body?{duplex:"half"}:void 0}),h=await t.query(u,{requestContext:o,skipLoaderErrorBubbling:!0,skipRevalidation:!0,generateMiddlewareResponse:e.future.v8_middleware?async c=>{try{let y=await c(u);return d(y)}catch(y){return s(y)}}:void 0});return d(h)}catch(u){return s(u)}function d(u){return F(u)?u:i(u)}function s(u){return l(u),L(a,e,r,{result:{error:u},headers:new Headers,status:500})}function i(u){let h=Y(u,e);if(Q(u.statusCode)&&h.has("Location"))return new Response(null,{status:u.statusCode,headers:h});u.errors&&(Object.values(u.errors).forEach(y=>{(!x(y)||y.error)&&l(y)}),u.errors=I(u.errors,r));let c;return u.errors?c={error:Object.values(u.errors)[0]}:c={data:Object.values(u.actionData||{})[0]},L(a,e,r,{result:c,headers:h,status:u.statusCode})}}async function It(e,r,t,a,n,o,l){let d=new URL(a.url).searchParams.get("_routes"),s=d?new Set(d.split(",")):null;try{let c=new Request(n,{headers:a.headers,signal:a.signal}),y=await t.query(c,{requestContext:o,filterMatchesToLoad:f=>!s||s.has(f.route.id),skipLoaderErrorBubbling:!0,generateMiddlewareResponse:e.future.v8_middleware?async f=>{try{let p=await f(c);return i(p)}catch(p){return u(p)}}:void 0});return i(y)}catch(c){return u(c)}function i(c){return F(c)?c:h(c)}function u(c){return l(c),L(a,e,r,{result:{error:c},headers:new Headers,status:500})}function h(c){let y=Y(c,e);if(Q(c.statusCode)&&y.has("Location"))return new Response(null,{status:c.statusCode,headers:y});c.errors&&(Object.values(c.errors).forEach(w=>{(!x(w)||w.error)&&l(w)}),c.errors=I(c.errors,r));let f={},p=new Set(c.matches.filter(w=>s?s.has(w.route.id):w.route.loader!=null).map(w=>w.route.id));if(c.errors)for(let[w,m]of Object.entries(c.errors))f[w]={error:m};for(let[w,m]of Object.entries(c.loaderData))!(w in f)&&p.has(w)&&(f[w]={data:m});return L(a,e,r,{result:f,headers:y,status:c.statusCode})}}function L(e,r,t,{result:a,headers:n,status:o}){let l=new Headers(n);return l.set("X-Remix-Response","yes"),Ne.has(o)?new Response(null,{status:o,headers:l}):(l.set("Content-Type","text/x-script"),l.delete("Content-Length"),new Response(J(a,e.signal,r.entry.module.streamTimeout,t),{status:o||200,headers:l}))}function ue(e,r,t,a){let n=Mt(e.status,e.headers,t.basename),o=new Headers(e.headers);return o.delete("Location"),o.set("Content-Type","text/x-script"),L(r,t,a,{result:r.method==="GET"?{[N]:n}:n,headers:o,status:ve})}function Mt(e,r,t){let a=r.get("Location");return t&&(a=O(a,t)||a),{redirect:a,status:e,revalidate:r.has("X-Remix-Revalidate")||r.has("Set-Cookie"),reload:r.has("X-Remix-Reload-Document"),replace:r.has("X-Remix-Replace")}}function J(e,r,t,a){let n=new AbortController,o=setTimeout(()=>n.abort(new Error("Server Timeout")),typeof t=="number"?t:4950);return r.addEventListener("abort",()=>clearTimeout(o)),ot(e,{signal:n.signal,plugins:[l=>{if(l instanceof Error){let{name:d,message:s,stack:i}=a==="production"?z(l,a):l;return["SanitizedError",d,s,i]}if(l instanceof T){let{data:d,status:s,statusText:i}=l;return["ErrorResponse",d,s,i]}if(l&&typeof l=="object"&&N in l)return["SingleFetchRedirect",l[N]]}],postPlugins:[l=>{if(l&&typeof l=="object")return["SingleFetchClassInstance",Object.fromEntries(Object.entries(l))]},()=>["SingleFetchFallback"]]})}function de(e,r){let t=Pe(e.routes),a=Te(e.routes,e.future),n=Tt(r)?r:"production",o=qe(a,{basename:e.basename,unstable_instrumentations:e.entry.module.unstable_instrumentations}),l=e.entry.module.handleError||((s,{request:i})=>{n!=="test"&&!i.signal.aborted&&console.error(x(s)&&s.error?s.error:s)}),d=async(s,i)=>{let u={},h,c=S=>{r==="development"&&j()?.processRequestError?.(S),l(S,{context:h,params:u,request:s})};if(e.future.v8_middleware){if(i&&!(i instanceof W)){let S=new Error("Invalid `context` value provided to `handleRequest`. When middleware is enabled you must return an instance of `RouterContextProvider` from your `getLoadContext` function.");return c(S),M(S,n)}h=i||new W}else h=i||{};let y=new URL(s.url),f=e.basename||"/",p=y.pathname;O(p,f)==="/_root.data"?p=f:p.endsWith(".data")&&(p=p.replace(/\.data$/,"")),O(p,f)!=="/"&&p.endsWith("/")&&(p=p.slice(0,-1));let w=He(s,"X-React-Router-SPA-Mode")==="yes";if(!e.ssr){let S=decodeURI(p);if(f!=="/"){let C=O(S,f);if(C==null)return l(new T(404,"Not Found",`Refusing to prerender the \`${S}\` path because it does not start with the basename \`${f}\``),{context:h,params:u,request:s}),new Response("Not Found",{status:404,statusText:"Not Found"});S=C}if(e.prerender.length===0)w=!0;else if(!e.prerender.includes(S)&&!e.prerender.includes(S+"/")){if(y.pathname.endsWith(".data"))return l(new T(404,"Not Found",`Refusing to SSR the path \`${S}\` because \`ssr:false\` is set and the path is not included in the \`prerender\` config, so in production the path will be a 404.`),{context:h,params:u,request:s}),new Response("Not Found",{status:404,statusText:"Not Found"});w=!0}}let m=rt(e.routeDiscovery.manifestPath,f);if(y.pathname===m)try{return await Bt(e,t,y)}catch(S){return c(S),new Response("Unknown Server Error",{status:500})}let g=q(t,p,e.basename);g&&g.length>0&&Object.assign(u,g[0].params);let v;if(y.pathname.endsWith(".data")){let S=new URL(s.url);S.pathname=p;let C=q(t,S.pathname,e.basename);v=await zt(n,e,o,s,S,h,c),ee(v)&&(v=ue(v,s,e,n)),e.entry.module.handleDataRequest&&(v=await e.entry.module.handleDataRequest(v,{context:h,params:C?C[0].params:{},request:s}),ee(v)&&(v=ue(v,s,e,n)))}else if(!w&&g&&g[g.length-1].route.module.default==null&&g[g.length-1].route.module.ErrorBoundary==null)v=await $t(n,e,o,g.slice(-1)[0].route.id,s,h,c);else{let{pathname:S}=y,C;e.unstable_getCriticalCss?C=await e.unstable_getCriticalCss({pathname:S}):r==="development"&&j()?.getCriticalCss&&(C=await j()?.getCriticalCss?.(S)),v=await jt(n,e,o,s,h,c,w,C)}return s.method==="HEAD"?new Response(null,{headers:v.headers,status:v.status,statusText:v.statusText}):v};return e.entry.module.unstable_instrumentations&&(d=Je(d,e.entry.module.unstable_instrumentations.map(s=>s.handler).filter(Boolean))),{routes:t,dataRoutes:a,serverMode:n,staticHandler:o,errorHandler:l,requestHandler:d}}var fr=(e,r)=>{let t,a,n,o,l,d;return async function(i,u){if(t=typeof e=="function"?await e():e,typeof e=="function"){let h=de(t,r);a=h.routes,n=h.serverMode,o=h.staticHandler,l=h.errorHandler,d=h.requestHandler}else if(!a||!n||!o||!l||!d){let h=de(t,r);a=h.routes,n=h.serverMode,o=h.staticHandler,l=h.errorHandler,d=h.requestHandler}return d(i,u)}};async function Bt(e,r,t){if(e.assets.version!==t.searchParams.get("version"))return new Response(null,{status:204,headers:{"X-Remix-Reload-Document":"true"}});let a={};if(t.searchParams.has("paths")){let n=new Set;(t.searchParams.get("paths")||"").split(",").filter(Boolean).forEach(d=>{d.startsWith("/")||(d=`/${d}`);let s=d.split("/").slice(1);s.forEach((i,u)=>{let h=s.slice(0,u+1).join("/");n.add(`/${h}`)})});for(let d of n){let s=q(r,d,e.basename);if(s)for(let i of s){let u=i.route.id,h=e.assets.routes[u];h&&(a[u]=h)}}return Response.json(a,{headers:{"Cache-Control":"public, max-age=31536000, immutable"}})}return new Response("Invalid Request",{status:400})}async function zt(e,r,t,a,n,o,l){return a.method!=="GET"?await Ut(r,e,t,a,n,o,l):await It(r,e,t,a,n,o,l)}async function jt(e,r,t,a,n,o,l,d){try{let i=await t.query(a,{requestContext:n,generateMiddlewareResponse:r.future.v8_middleware?async u=>{try{let h=await u(a);return F(h)||(h=await s(h,l)),h}catch(h){return o(h),new Response(null,{status:500})}}:void 0});return F(i)||(i=await s(i,l)),i}catch(i){return o(i),new Response(null,{status:500})}async function s(i,u){let h=Y(i,r);if(Ne.has(i.statusCode))return new Response(null,{status:i.statusCode,headers:h});i.errors&&(Object.values(i.errors).forEach(w=>{(!x(w)||w.error)&&o(w)}),i.errors=I(i.errors,e));let c={loaderData:i.loaderData,actionData:i.actionData,errors:oe(i.errors,e)},y={basename:r.basename,future:r.future,routeDiscovery:r.routeDiscovery,ssr:r.ssr,isSpaMode:u},f={manifest:r.assets,routeModules:kt(r.routes),staticHandlerContext:i,criticalCss:d,serverHandoffString:le({...y,criticalCss:d}),serverHandoffStream:J(c,a.signal,r.entry.module.streamTimeout,e),renderMeta:{},future:r.future,ssr:r.ssr,routeDiscovery:r.routeDiscovery,isSpaMode:u,serializeError:w=>Fe(w,e)},p=r.entry.module.default;try{return await p(a,i.statusCode,h,f,n)}catch(w){o(w);let m=w;if(F(w))try{let v=await Wt(w);m=new T(w.status,w.statusText,v)}catch{}i=nt(t.dataRoutes,i,m),i.errors&&(i.errors=I(i.errors,e));let g={loaderData:i.loaderData,actionData:i.actionData,errors:oe(i.errors,e)};f={...f,staticHandlerContext:i,serverHandoffString:le(y),serverHandoffStream:J(g,a.signal,r.entry.module.streamTimeout,e),renderMeta:{}};try{return await p(a,i.statusCode,h,f,n)}catch(v){return o(v),M(v,e)}}}}async function $t(e,r,t,a,n,o,l){try{let i=await t.queryRoute(n,{routeId:a,requestContext:o,generateMiddlewareResponse:r.future.v8_middleware?async u=>{try{let h=await u(n);return d(h)}catch(h){return s(h)}}:void 0});return d(i)}catch(i){return s(i)}function d(i){return F(i)?i:typeof i=="string"?new Response(i):Response.json(i)}function s(i){if(F(i))return i;if(x(i))return l(i),Vt(i,e);if(i instanceof Error&&i.message==="Expected a response from queryRoute"){let u=new Error("Expected a Response to be returned from resource route handler");return l(u),M(u,e)}return l(i),M(i,e)}}function Vt(e,r){return Response.json(Fe(e.error||new Error("Unexpected Server Error"),r),{status:e.status,statusText:e.statusText})}function M(e,r){let t="Unexpected Server Error";return r!=="production"&&(t+=`
2
2
 
3
3
  ${String(e)}`),new Response(t,{status:500,headers:{"Content-Type":"text/plain"}})}function Wt(e){let r=e.headers.get("Content-Type");return r&&/\bapplication\/json\b/.test(r)?e.body==null?null:e.json():e.text()}function $(e){return`__flash_${e}__`}var Le=(e={},r="")=>{let t=new Map(Object.entries(e));return{get id(){return r},get data(){return Object.fromEntries(t)},has(a){return t.has(a)||t.has($(a))},get(a){if(t.has(a))return t.get(a);let n=$(a);if(t.has(n)){let o=t.get(n);return t.delete(n),o}},set(a,n){t.set(a,n)},flash(a,n){t.set($(a),n)},unset(a){t.delete(a)}}},hr=e=>e!=null&&typeof e.id=="string"&&typeof e.data<"u"&&typeof e.has=="function"&&typeof e.get=="function"&&typeof e.set=="function"&&typeof e.flash=="function"&&typeof e.unset=="function";function qt({cookie:e,createData:r,readData:t,updateData:a,deleteData:n}){let o=De(e)?e:xe(e?.name||"__session",e);return Oe(o),{async getSession(l,d){let s=l&&await o.parse(l,d),i=s&&await t(s);return Le(i||{},s||"")},async commitSession(l,d){let{id:s,data:i}=l,u=d?.maxAge!=null?new Date(Date.now()+d.maxAge*1e3):d?.expires!=null?d.expires:o.expires;return s?await a(s,i,u):s=await r(i,u),o.serialize(s,d)},async destroySession(l,d){return await n(l.id),o.serialize("",{...d,maxAge:void 0,expires:new Date(0)})}}}function Oe(e){Se(e.isSigned,`The "${e.name}" cookie is not signed, but session cookies should be signed to prevent tampering on the client before they are sent back to the server. See https://reactrouter.com/explanation/sessions-and-cookies#signing-cookies for more information.`)}function pr({cookie:e}={}){let r=De(e)?e:xe(e?.name||"__session",e);return Oe(r),{async getSession(t,a){return Le(t&&await r.parse(t,a)||{})},async commitSession(t,a){let n=await r.serialize(t.data,a);if(n.length>4096)throw new Error("Cookie length will exceed browser maximum. Length: "+n.length);return n},async destroySession(t,a){return r.serialize("",{...a,maxAge:void 0,expires:new Date(0)})}}}function mr({cookie:e}={}){let r=new Map;return qt({cookie:e,async createData(t,a){let n=Math.random().toString(36).substring(2,10);return r.set(n,{data:t,expires:a}),n},async readData(t){if(r.has(t)){let{data:a,expires:n}=r.get(t);if(!n||n>new Date)return a;n&&r.delete(t)}return null},async updateData(t,a,n){r.set(t,{data:a,expires:n})},async deleteData(t){r.delete(t)}})}function yr(e,...r){let t=r[0],a=e.replace(/\/*\*?$/,"").replace(/\/:([\w-]+)(\?)?/g,(n,o,l)=>{const d=l===void 0,s=t?t[o]:void 0;if(d&&s===void 0)throw new Error(`Path '${e}' requires param '${o}' but it was not provided`);return s===void 0?"":"/"+s});if(e.endsWith("*")){const n=t?t["*"]:void 0;n!==void 0&&(a+="/"+n)}return a||"/"}var X=new TextEncoder,ce="</body></html>";function fe(e){let r=new TextDecoder,t,a=new Promise(s=>t=s),n=!1,o=[],l=null;function d(s){for(let i of o){let u=r.decode(i,{stream:!0});u.endsWith(ce)&&(u=u.slice(0,-ce.length)),s.enqueue(X.encode(u))}o.length=0,l=null}return new TransformStream({transform(s,i){o.push(s),!l&&(l=setTimeout(async()=>{d(i),n||(n=!0,Jt(e,i).catch(u=>i.error(u)).then(t))},0))},async flush(s){await a,l&&(clearTimeout(l),d(s)),s.enqueue(X.encode("</body></html>"))}})}async function Jt(e,r){let t=new TextDecoder("utf-8",{fatal:!0});const a=e.getReader();try{let o;for(;(o=await a.read())&&!o.done;){const l=o.value;try{V(JSON.stringify(t.decode(l,{stream:!0})),r)}catch{let s=JSON.stringify(btoa(String.fromCodePoint(...l)));V(`Uint8Array.from(atob(${s}), m => m.codePointAt(0))`,r)}}}finally{a.releaseLock()}let n=t.decode();n.length&&V(JSON.stringify(n),r)}function V(e,r){r.enqueue(X.encode(`<script>${Xt(`(self.__FLIGHT_DATA||=[]).push(${e})`)}<\/script>`))}function Xt(e){return e.replace(/<!--/g,"<\\!--").replace(/<\/(script)/gi,"</\\$1")}var Kt=class extends b.Component{constructor(e){super(e),this.state={error:null,location:e.location}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,r){return r.location!==e.location?{error:null,location:e.location}:{error:r.error,location:r.location}}render(){return this.state.error?b.createElement(Ue,{error:this.state.error,renderAppShell:!0}):this.props.children}};function he({renderAppShell:e,title:r,children:t}){return e?b.createElement("html",{lang:"en"},b.createElement("head",null,b.createElement("meta",{charSet:"utf-8"}),b.createElement("meta",{name:"viewport",content:"width=device-width,initial-scale=1,viewport-fit=cover"}),b.createElement("title",null,r)),b.createElement("body",null,b.createElement("main",{style:{fontFamily:"system-ui, sans-serif",padding:"2rem"}},t))):t}function Ue({error:e,renderAppShell:r}){console.error(e);let t=b.createElement("script",{dangerouslySetInnerHTML:{__html:`
4
4
  console.log(
@@ -1,4 +1,4 @@
1
- import{M as Ss,t as xa,a1 as ka,a2 as S,a3 as As,a4 as Sa,a5 as Aa,W as Ca,X as jn,j as Ke,P as Cs,a6 as Ln,Y as Dn,H as Ze,a7 as Oa,a8 as Ia,Z as Fn,$ as Ta,Q as Os,S as Is,J as ke,o as Ts,a9 as $a,L as cn,aa as Bn,ab as Ra,ac as Pa,ad as Ea,U as Un,ae as Wn,af as Ma,K as Jt,a as Na}from"./index-C9XlRV8D.js";import{bg as ja}from"./index-CHOOqKAT.js";import{J as qn,c as La,p as $s,m as Kt}from"./index-D7lutfXP.js";import"./embeddings-Duw58exF.js";import"./index-DRz5BQNA.js";const xe=t=>t();function Be(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function Da(t){return t.role!=="system"&&t.role!=="developer"&&t.role!=="assistant"&&t.role!=="user"&&t.role!=="function"&&t.role!=="tool"&&console.warn(`Unknown message role: ${t.role}`),t.role}function Ue(t){const e=t._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":if(!Ss.isInstance(t))throw new Error("Invalid generic chat message");return Da(t);default:throw new Error(`Unknown message type: ${e}`)}}function Fa(t){const{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:n,azureOpenAIApiKey:s,azureOpenAIBasePath:r,baseURL:a,azureADTokenProvider:i,azureOpenAIEndpoint:o}=t;if((s||i)&&r&&e)return`${r}/${e}`;if((s||i)&&o&&e)return`${o}/openai/deployments/${e}`;if(s||i){if(!n)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!e)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${n}.openai.azure.com/openai/deployments/${e}`}return a}function Ba(t,e){let n;return xa(t)?n=ka(t):n=t,e?.strict!==void 0&&(n.function.strict=e.strict),n}function Ua(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function Wa(t){const e=["namespace functions {",""];for(const n of t)n.description&&e.push(`// ${n.description}`),Object.keys(n.parameters.properties??{}).length>0?(e.push(`type ${n.name} = (_: {`),e.push(Rs(n.parameters,0)),e.push("}) => any;")):e.push(`type ${n.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
1
+ import{M as Ss,t as xa,a1 as ka,a2 as S,a3 as As,a4 as Sa,a5 as Aa,W as Ca,X as jn,j as Ke,P as Cs,a6 as Ln,Y as Dn,H as Ze,a7 as Oa,a8 as Ia,Z as Fn,$ as Ta,Q as Os,S as Is,J as ke,o as Ts,a9 as $a,L as cn,aa as Bn,ab as Ra,ac as Pa,ad as Ea,U as Un,ae as Wn,af as Ma,K as Jt,a as Na}from"./index-Cx63umjv.js";import{bg as ja}from"./index-IFdSquJo.js";import{J as qn,c as La,p as $s,m as Kt}from"./index-CI3g_RcQ.js";import"./embeddings-DHqEojuq.js";import"./index-DRz5BQNA.js";const xe=t=>t();function Be(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function Da(t){return t.role!=="system"&&t.role!=="developer"&&t.role!=="assistant"&&t.role!=="user"&&t.role!=="function"&&t.role!=="tool"&&console.warn(`Unknown message role: ${t.role}`),t.role}function Ue(t){const e=t._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":if(!Ss.isInstance(t))throw new Error("Invalid generic chat message");return Da(t);default:throw new Error(`Unknown message type: ${e}`)}}function Fa(t){const{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:n,azureOpenAIApiKey:s,azureOpenAIBasePath:r,baseURL:a,azureADTokenProvider:i,azureOpenAIEndpoint:o}=t;if((s||i)&&r&&e)return`${r}/${e}`;if((s||i)&&o&&e)return`${o}/openai/deployments/${e}`;if(s||i){if(!n)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!e)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${n}.openai.azure.com/openai/deployments/${e}`}return a}function Ba(t,e){let n;return xa(t)?n=ka(t):n=t,e?.strict!==void 0&&(n.function.strict=e.strict),n}function Ua(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function Wa(t){const e=["namespace functions {",""];for(const n of t)n.description&&e.push(`// ${n.description}`),Object.keys(n.parameters.properties??{}).length>0?(e.push(`type ${n.name} = (_: {`),e.push(Rs(n.parameters,0)),e.push("}) => any;")):e.push(`type ${n.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
2
2
  `)}function Rs(t,e){const n=[];for(const[s,r]of Object.entries(t.properties??{}))r.description&&e<2&&n.push(`// ${r.description}`),t.required?.includes(s)?n.push(`${s}: ${ut(r,e)},`):n.push(`${s}?: ${ut(r,e)},`);return n.map(s=>" ".repeat(e)+s).join(`
3
3
  `)}function ut(t,e){if(Ua(t))return t.anyOf.map(n=>ut(n,e)).join(" | ");switch(t.type){case"string":return t.enum?t.enum.map(n=>`"${n}"`).join(" | "):"string";case"number":return t.enum?t.enum.map(n=>`${n}`).join(" | "):"number";case"integer":return t.enum?t.enum.map(n=>`${n}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",Rs(t,e+2),"}"].join(`
4
4
  `);case"array":return t.items?`${ut(t.items,e)}[]`:"any[]";default:return""}}function Ps(t){if(t)return t==="any"||t==="required"?"required":t==="auto"?"auto":t==="none"?"none":typeof t=="string"?{type:"function",function:{name:t}}:t}function un(t){return"type"in t&&t.type!=="function"}function qa(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function dt(t){return typeof t=="object"&&t!==null&&"metadata"in t&&typeof t.metadata=="object"&&t.metadata!==null&&"customTool"in t.metadata&&typeof t.metadata.customTool=="object"&&t.metadata.customTool!==null}function Es(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function Ja(t){if(t.type==="custom_tool_call")return{...t,type:"tool_call",call_id:t.id,id:t.call_id,name:t.name,isCustomTool:!0,args:{input:t.input}}}function Ka(t){return t.type==="tool_call"&&"isCustomTool"in t&&t.isCustomTool===!0}function Za(t){const e=()=>{if(t.custom.format){if(t.custom.format.type==="grammar")return{type:"grammar",definition:t.custom.format.grammar.definition,syntax:t.custom.format.grammar.syntax};if(t.custom.format.type==="text")return{type:"text"}}};return{type:"custom",name:t.custom.name,description:t.custom.description,format:e()}}function za(t){const e=()=>{if(t.format){if(t.format.type==="grammar")return{type:"grammar",grammar:{definition:t.format.definition,syntax:t.format.syntax}};if(t.format.type==="text")return{type:"text"}}};return{type:"custom",custom:{name:t.name,description:t.description,format:e()}}}function Zt(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}const zt=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){const e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};class x extends Error{}class q extends x{constructor(e,n,s,r){super(`${q.makeMessage(e,n,s)}`),this.status=e,this.headers=r,this.requestID=r?.get("x-request-id"),this.error=n;const a=n;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,n,s){const r=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):s;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,n,s,r){if(!e||!r)return new kt({message:s,cause:zt(n)});const a=n?.error;return e===400?new Ms(e,a,s,r):e===401?new Ns(e,a,s,r):e===403?new js(e,a,s,r):e===404?new Ls(e,a,s,r):e===409?new Ds(e,a,s,r):e===422?new Fs(e,a,s,r):e===429?new Bs(e,a,s,r):e>=500?new Us(e,a,s,r):new q(e,a,s,r)}}class X extends q{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class kt extends q{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}}class St extends kt{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Ms extends q{}class Ns extends q{}class js extends q{}class Ls extends q{}class Ds extends q{}class Fs extends q{}class Bs extends q{}class Us extends q{}class Ws extends x{constructor(){super("Could not parse response content as the length limit was reached")}}class qs extends x{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class Oe extends Error{constructor(e){super(e)}}function ht(t){return t!==void 0&&"function"in t&&t.function!==void 0}function Ha(t,e){const n={...t};return Object.defineProperties(n,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),n}function dn(t){return t?.$brand==="auto-parseable-response-format"}function We(t){return t?.$brand==="auto-parseable-tool"}function Va(t,e){return!e||!Js(e)?{...t,choices:t.choices.map(n=>(Ks(n.message.tool_calls),{...n,message:{...n.message,parsed:null,...n.message.tool_calls?{tool_calls:n.message.tool_calls}:void 0}}))}:hn(t,e)}function hn(t,e){const n=t.choices.map(s=>{if(s.finish_reason==="length")throw new Ws;if(s.finish_reason==="content_filter")throw new qs;return Ks(s.message.tool_calls),{...s,message:{...s.message,...s.message.tool_calls?{tool_calls:s.message.tool_calls?.map(r=>Ga(e,r))??void 0}:void 0,parsed:s.message.content&&!s.message.refusal?Xa(e,s.message.content):null}}});return{...t,choices:n}}function Xa(t,e){return t.response_format?.type!=="json_schema"?null:t.response_format?.type==="json_schema"?"$parseRaw"in t.response_format?t.response_format.$parseRaw(e):JSON.parse(e):null}function Ga(t,e){const n=t.tools?.find(s=>ht(s)&&s.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:We(n)?n.$parseRaw(e.function.arguments):n?.function.strict?JSON.parse(e.function.arguments):null}}}function Qa(t,e){if(!t||!("tools"in t)||!t.tools)return!1;const n=t.tools?.find(s=>ht(s)&&s.function?.name===e.function.name);return ht(n)&&(We(n)||n?.function.strict||!1)}function Js(t){return dn(t.response_format)?!0:t.tools?.some(e=>We(e)||e.type==="function"&&e.function.strict===!0)??!1}function Ks(t){for(const e of t||[])if(e.type!=="function")throw new x(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Ya(t){for(const e of t??[]){if(e.type!=="function")throw new x(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new x(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}const ei=Symbol("Let zodToJsonSchema decide on which parser to use"),Jn={name:void 0,$refStrategy:"root",effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",nullableStrategy:"from-target",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},ti=t=>typeof t=="string"?{...Jn,basePath:["#"],definitions:{},name:t}:{...Jn,basePath:["#"],definitions:{},...t},Ht=t=>"_def"in t?t._def:t;function ni(t){if(!t)return!0;for(const e in t)return!1;return!0}const si=t=>{const e=ti(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:n,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(e.definitions).map(([s,r])=>[Ht(r),{def:Ht(r),path:[...e.basePath,e.definitionPath,s],jsonSchema:void 0}]))}};function Zs(t,e,n,s){s?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function T(t,e,n,s,r){t[e]=n,Zs(t,e,s,r)}function ri(){return{}}function ai(t,e){const n={type:"array"};return t.type?._def?.typeName!==S.ZodAny&&(n.items=O(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&T(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&T(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(T(n,"minItems",t.exactLength.value,t.exactLength.message,e),T(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}function ii(t,e){const n={type:"integer",format:"int64"};if(!t.checks)return n;for(const s of t.checks)switch(s.kind){case"min":e.target==="jsonSchema7"?s.inclusive?T(n,"minimum",s.value,s.message,e):T(n,"exclusiveMinimum",s.value,s.message,e):(s.inclusive||(n.exclusiveMinimum=!0),T(n,"minimum",s.value,s.message,e));break;case"max":e.target==="jsonSchema7"?s.inclusive?T(n,"maximum",s.value,s.message,e):T(n,"exclusiveMaximum",s.value,s.message,e):(s.inclusive||(n.exclusiveMaximum=!0),T(n,"maximum",s.value,s.message,e));break;case"multipleOf":T(n,"multipleOf",s.value,s.message,e);break}return n}function oi(){return{type:"boolean"}}function li(t,e){return O(t.type._def,e)}const ci=(t,e)=>O(t.innerType._def,e);function zs(t,e,n){const s=n??e.dateStrategy;if(Array.isArray(s))return{anyOf:s.map((r,a)=>zs(t,e,r))};switch(s){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return ui(t,e)}}const ui=(t,e)=>{const n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(const s of t.checks)switch(s.kind){case"min":T(n,"minimum",s.value,s.message,e);break;case"max":T(n,"maximum",s.value,s.message,e);break}return n};function di(t,e){return{...O(t.innerType._def,e),default:t.defaultValue()}}function hi(t,e,n){return e.effectStrategy==="input"?O(t.schema._def,e,n):{}}function fi(t){return{type:"string",enum:[...t.values]}}const pi=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function mi(t,e){const n=[O(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),O(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(a=>!!a);let s=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const r=[];return n.forEach(a=>{if(pi(a))r.push(...a.allOf),a.unevaluatedProperties===void 0&&(s=void 0);else{let i=a;if("additionalProperties"in a&&a.additionalProperties===!1){const{additionalProperties:o,...c}=a;i=c}else s=void 0;r.push(i)}}),r.length?{allOf:r,...s}:void 0}function _i(t,e){const n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}let Nt;const le={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Nt===void 0&&(Nt=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Nt),base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function Hs(t,e){const n={type:"string"};function s(r){return e.patternStrategy==="escape"?gi(r):r}if(t.checks)for(const r of t.checks)switch(r.kind){case"min":T(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":T(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":G(n,"email",r.message,e);break;case"format:idn-email":G(n,"idn-email",r.message,e);break;case"pattern:zod":Q(n,le.email,r.message,e);break}break;case"url":G(n,"uri",r.message,e);break;case"uuid":G(n,"uuid",r.message,e);break;case"regex":Q(n,r.regex,r.message,e);break;case"cuid":Q(n,le.cuid,r.message,e);break;case"cuid2":Q(n,le.cuid2,r.message,e);break;case"startsWith":Q(n,RegExp(`^${s(r.value)}`),r.message,e);break;case"endsWith":Q(n,RegExp(`${s(r.value)}$`),r.message,e);break;case"datetime":G(n,"date-time",r.message,e);break;case"date":G(n,"date",r.message,e);break;case"time":G(n,"time",r.message,e);break;case"duration":G(n,"duration",r.message,e);break;case"length":T(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),T(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":{Q(n,RegExp(s(r.value)),r.message,e);break}case"ip":{r.version!=="v6"&&G(n,"ipv4",r.message,e),r.version!=="v4"&&G(n,"ipv6",r.message,e);break}case"emoji":Q(n,le.emoji,r.message,e);break;case"ulid":{Q(n,le.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{G(n,"binary",r.message,e);break}case"contentEncoding:base64":{T(n,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{Q(n,le.base64,r.message,e);break}}break}case"nanoid":Q(n,le.nanoid,r.message,e)}return n}const gi=t=>Array.from(t).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),G=(t,e,n,s)=>{t.format||t.anyOf?.some(r=>r.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&s.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...n&&s.errorMessages&&{errorMessage:{format:n}}})):T(t,"format",e,n,s)},Q=(t,e,n,s)=>{t.pattern||t.allOf?.some(r=>r.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&s.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Kn(e,s),...n&&s.errorMessages&&{errorMessage:{pattern:n}}})):T(t,"pattern",Kn(e,s),n,s)},Kn=(t,e)=>{const n=typeof t=="function"?t():t;if(!e.applyRegexFlags||!n.flags)return n.source;const s={i:n.flags.includes("i"),m:n.flags.includes("m"),s:n.flags.includes("s")},r=s.i?n.source.toLowerCase():n.source;let a="",i=!1,o=!1,c=!1;for(let l=0;l<r.length;l++){if(i){a+=r[l],i=!1;continue}if(s.i){if(o){if(r[l].match(/[a-z]/)){c?(a+=r[l],a+=`${r[l-2]}-${r[l]}`.toUpperCase(),c=!1):r[l+1]==="-"&&r[l+2]?.match(/[a-z]/)?(a+=r[l],c=!0):a+=`${r[l]}${r[l].toUpperCase()}`;continue}}else if(r[l].match(/[a-z]/)){a+=`[${r[l]}${r[l].toUpperCase()}]`;continue}}if(s.m){if(r[l]==="^"){a+=`(^|(?<=[\r