@decocms/mesh 2.38.1 → 2.38.2

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.
Files changed (132) hide show
  1. package/dist/client/assets/{AlertCircle-CS-jIuIG.js → AlertCircle-z3xwiUwg.js} +1 -1
  2. package/dist/client/assets/{ArrowLeft-CBmwJeeK.js → ArrowLeft-BkoJglZy.js} +1 -1
  3. package/dist/client/assets/{ArrowUp-BcJ8dyfU.js → ArrowUp-BAMBJKzk.js} +1 -1
  4. package/dist/client/assets/{Check-DLju1Q3r.js → Check-BK9-0hKa.js} +1 -1
  5. package/dist/client/assets/{ChevronDown-B_x9h_g5.js → ChevronDown-PIP2u0bO.js} +1 -1
  6. package/dist/client/assets/{Code01-BoyKbSDG.js → Code01-Bur40qHc.js} +1 -1
  7. package/dist/client/assets/{Copy01-BQ64h9yo.js → Copy01-BOhF0ZEB.js} +1 -1
  8. package/dist/client/assets/{CpuChip02-CK9Ts0sS.js → CpuChip02-BTAUjBs1.js} +1 -1
  9. package/dist/client/assets/{DotsHorizontal-Dh8zepi-.js → DotsHorizontal-DxGrUc9a.js} +1 -1
  10. package/dist/client/assets/{DotsVertical-BLF-yOlJ.js → DotsVertical-D61roAg3.js} +1 -1
  11. package/dist/client/assets/{Download01-C789DWeK.js → Download01-DH0bL3Nt.js} +1 -1
  12. package/dist/client/assets/{Edit01-Cd37cNP3.js → Edit01-DINJ246_.js} +1 -1
  13. package/dist/client/assets/{File06-kaLJFm-q.js → File06-DVkrNas0.js} +1 -1
  14. package/dist/client/assets/{FilterLines-Cn2eFuFa.js → FilterLines-so_Nzmiv.js} +1 -1
  15. package/dist/client/assets/{FlipBackward-C5qdQsCz.js → FlipBackward-iQ8t51Yv.js} +1 -1
  16. package/dist/client/assets/{GitBranch01-Drx3lD6H.js → GitBranch01-T4MUtqYK.js} +1 -1
  17. package/dist/client/assets/{Grid01-WefRlQ2V.js → Grid01-CN_8958k.js} +1 -1
  18. package/dist/client/assets/{Home02-B8IjkIhq.js → Home02-DuEnlN2j.js} +1 -1
  19. package/dist/client/assets/{Image01-BBteb9lT.js → Image01-CAZIUcM5.js} +1 -1
  20. package/dist/client/assets/{Inbox01-DK5akTSt.js → Inbox01-CM3kHNUT.js} +1 -1
  21. package/dist/client/assets/{InfoCircle-C-QuElqT.js → InfoCircle-yeMjcoma.js} +1 -1
  22. package/dist/client/assets/{Key01-gcJPy5EX.js → Key01-9yBwokED.js} +1 -1
  23. package/dist/client/assets/{LinkExternal01-DkEBvdnT.js → LinkExternal01-DVQPzyFK.js} +1 -1
  24. package/dist/client/assets/{List-BOcQ_qLY.js → List-BuWxjuK8.js} +1 -1
  25. package/dist/client/assets/{Loading01-BnIxMZF3.js → Loading01-D1yLQLik.js} +1 -1
  26. package/dist/client/assets/{Lock01-B5oFbCso.js → Lock01-RqyglEYd.js} +1 -1
  27. package/dist/client/assets/{Play-UDbziv3X.js → Play-DVdw4qV-.js} +1 -1
  28. package/dist/client/assets/{Plus-CgVSBG5y.js → Plus-Je-soon7.js} +1 -1
  29. package/dist/client/assets/{SearchMd-BROWz6ah.js → SearchMd-CbtolPap.js} +1 -1
  30. package/dist/client/assets/{Terminal-Zq1E1BM4.js → Terminal-DYGeKWvi.js} +1 -1
  31. package/dist/client/assets/{Trash01-C--EdsjR.js → Trash01-CZvA_s0Y.js} +1 -1
  32. package/dist/client/assets/{Upload01-DPoHWsHP.js → Upload01-DhaDMFFD.js} +1 -1
  33. package/dist/client/assets/{X-DfAyL_Oh.js → X-sxVQmAsr.js} +1 -1
  34. package/dist/client/assets/{XClose-CzVie8T0.js → XClose-zzu-jidq.js} +1 -1
  35. package/dist/client/assets/{agent-detail-BxLsPk1-.js → agent-detail-BlRpinmR.js} +1 -1
  36. package/dist/client/assets/{agents-B5isnr1e.js → agents-DknJreAQ.js} +1 -1
  37. package/dist/client/assets/{alert-dialog-5PVdPXcK.js → alert-dialog-CVkwkecf.js} +1 -1
  38. package/dist/client/assets/{auth-catchall-GW49jJBl.js → auth-catchall-w4I8mOfz.js} +1 -1
  39. package/dist/client/assets/{avatar-CDCsOqPW.js → avatar-C9tVSVlv.js} +1 -1
  40. package/dist/client/assets/{badge-DdUz_4zF.js → badge-C7J4I2Hj.js} +1 -1
  41. package/dist/client/assets/{binder-CaMfr2RD.js → binder-CbjhFDGc.js} +1 -1
  42. package/dist/client/assets/{button-BIjHWY-p.js → button-CceSuFKi.js} +1 -1
  43. package/dist/client/assets/{card-O_szO-vK.js → card-BGHb8OmC.js} +1 -1
  44. package/dist/client/assets/{checkbox-C4yURLAg.js → checkbox-Cu04V43g.js} +1 -1
  45. package/dist/client/assets/{collection-detail-C-jqXdoZ.js → collection-detail-D2oIsKq-.js} +1 -1
  46. package/dist/client/assets/{collection-display-button-Ds1zEKL2.js → collection-display-button-Df_9WgFb.js} +1 -1
  47. package/dist/client/assets/{collection-header-TKDCFPjw.js → collection-header-COgMCOx8.js} +1 -1
  48. package/dist/client/assets/{collection-page-c7j4IfUq.js → collection-page-DVakSZpa.js} +1 -1
  49. package/dist/client/assets/{collection-search-DKhAjxez.js → collection-search-Fe3W5Myr.js} +1 -1
  50. package/dist/client/assets/{collection-tab-D5IqjP-f.js → collection-tab-_C4vj95J.js} +1 -1
  51. package/dist/client/assets/{collection-table-wrapper-4B7cZeoV.js → collection-table-wrapper-VkF3O5dC.js} +1 -1
  52. package/dist/client/assets/{connection-card-DH1wTNCc.js → connection-card-Bq9AH0T5.js} +1 -1
  53. package/dist/client/assets/{connection-detail-DfX4RZhC.js → connection-detail-CbrkwDLO.js} +1 -1
  54. package/dist/client/assets/{connections-BKodQMhu.js → connections-unSJ25xy.js} +1 -1
  55. package/dist/client/assets/constants-CrS7edVE.js +1 -0
  56. package/dist/client/assets/{constants-D4amfH_3.js → constants-DqnLzZpL.js} +1 -1
  57. package/dist/client/assets/{create-organization-dialog-C1ErfiJc.js → create-organization-dialog-DCA75BPi.js} +1 -1
  58. package/dist/client/assets/{dialog-DPTEgXq7.js → dialog-CL6M-Xmi.js} +1 -1
  59. package/dist/client/assets/{dropdown-menu-Qz_CAQar.js → dropdown-menu-BMu3zBVo.js} +1 -1
  60. package/dist/client/assets/{dynamic-plugin-layout-Dn93wPdR.js → dynamic-plugin-layout-CKzehx9R.js} +1 -1
  61. package/dist/client/assets/{empty-state-Cw_XUF0K.js → empty-state-B0xeJKH5.js} +1 -1
  62. package/dist/client/assets/{empty-state-DRkabEGg.js → empty-state-BHdJzPJs.js} +1 -1
  63. package/dist/client/assets/{env-vars-editor-DAoIabTH.js → env-vars-editor-CtvDpSON.js} +1 -1
  64. package/dist/client/assets/{error-boundary-CMaeLt6A.js → error-boundary-vgLVbtql.js} +1 -1
  65. package/dist/client/assets/{extract-connection-data-DxwUvuRo.js → extract-connection-data-w2VKbBVM.js} +1 -1
  66. package/dist/client/assets/{file-browser-DfLYy3MD.js → file-browser-C_o-XRN_.js} +2 -2
  67. package/dist/client/assets/{form-DaYDBDTX.js → form-DWBp_92q.js} +1 -1
  68. package/dist/client/assets/{grid-view-DIZOiKOZ.js → grid-view-D4uG2rz_.js} +1 -1
  69. package/dist/client/assets/{home-9pZ2RDY-.js → home-tcH3yRYZ.js} +1 -1
  70. package/dist/client/assets/{index-BC2cNq-q.js → index-BfBspZNA.js} +1 -1
  71. package/dist/client/assets/{index-CuL2eg3H.js → index-CQ6L3uZi.js} +1 -1
  72. package/dist/client/assets/{index-o1FfD36Q.js → index-CUpy3pKS.js} +1 -1
  73. package/dist/client/assets/{index-CfH8pE7r.js → index-D1MpJYf1.js} +1 -1
  74. package/dist/client/assets/{index-8Hmhn75x.js → index-D4QmV-sc.js} +1 -1
  75. package/dist/client/assets/{index-BwwBEfrO.js → index-DimTMp-G.js} +2 -2
  76. package/dist/client/assets/{infiniteQueryObserver-CwT1UjVu.js → infiniteQueryObserver-DeWE7Mv6.js} +1 -1
  77. package/dist/client/assets/{input-CVOvOgSp.js → input-BzZt5UMQ.js} +1 -1
  78. package/dist/client/assets/{layout-nyIHcSTg.js → layout-DqvUpliw.js} +1 -1
  79. package/dist/client/assets/{localstorage-keys-Rwfudbas.js → localstorage-keys-Pb1bSOSH.js} +1 -1
  80. package/dist/client/assets/{login-C8oIX0L8.js → login-Bw3mNwou.js} +1 -1
  81. package/dist/client/assets/{mcp-oauth-CAZFpyb5.js → mcp-oauth-DVTAVhIy.js} +1 -1
  82. package/dist/client/assets/{mcp-server-card-5ntetetx.js → mcp-server-card-BOsrfsoy.js} +1 -1
  83. package/dist/client/assets/{mcp-server-detail-CTvj-b2O.js → mcp-server-detail-DL4a0l-I.js} +2 -2
  84. package/dist/client/assets/{members-DAPobsBd.js → members-CaWwLwBY.js} +1 -1
  85. package/dist/client/assets/{monaco-editor-CrvW2h3k.js → monaco-editor-C3l8YLnM.js} +1 -1
  86. package/dist/client/assets/monitoring-BXzU__Q2.js +49 -0
  87. package/dist/client/assets/{oauth-callback-HrS0pWbo.js → oauth-callback-C29sykPI.js} +1 -1
  88. package/dist/client/assets/{page-Ci59OqVQ.js → page-D9f3s0Zn.js} +1 -1
  89. package/dist/client/assets/{page-DsaotdUI.js → page-DFTluz6T.js} +1 -1
  90. package/dist/client/assets/{pin-to-sidebar-button-DECaOYqz.js → pin-to-sidebar-button-a3_Q5PIg.js} +1 -1
  91. package/dist/client/assets/{plugin-empty-state-bbMDebZX.js → plugin-empty-state-gioOq0db.js} +1 -1
  92. package/dist/client/assets/{plugin-header-D9hNPIw1.js → plugin-header-OS_VhXuY.js} +1 -1
  93. package/dist/client/assets/{plugins-CzrAKKa7.js → plugins-6jaAX9OI.js} +1 -1
  94. package/dist/client/assets/{popover-CLj7Qdgu.js → popover-DCXtR4UV.js} +1 -1
  95. package/dist/client/assets/{registry-utils-CI8LbcR3.js → registry-utils-B1EtgBkU.js} +1 -1
  96. package/dist/client/assets/{resizable-DfGY2wYp.js → resizable-C5jfRumR.js} +1 -1
  97. package/dist/client/assets/{resource-tabs-C2i6zXNV.js → resource-tabs-BNBJ-3ue.js} +1 -1
  98. package/dist/client/assets/{select-DFt33nTB.js → select-DVxy4dZt.js} +1 -1
  99. package/dist/client/assets/{settings-5bD3UVMS.js → settings-DlMrUAFl.js} +1 -1
  100. package/dist/client/assets/{shell-layout-DzFavLHo.js → shell-layout-C02QmtDM.js} +1 -1
  101. package/dist/client/assets/{spinner-D1gxL93c.js → spinner-BK_gptNQ.js} +1 -1
  102. package/dist/client/assets/{switch-r-FGf2jr.js → switch-BEUY1ZkG.js} +1 -1
  103. package/dist/client/assets/{textarea-uS4eDm3T.js → textarea-Dok2BUMd.js} +1 -1
  104. package/dist/client/assets/{tool-set-selector-D6ybKjEp.js → tool-set-selector-BPpD_gne.js} +1 -1
  105. package/dist/client/assets/{tools-list-Cye7rRj9.js → tools-list-eucrhDw_.js} +1 -1
  106. package/dist/client/assets/{tooltip-Chg2rsW2.js → tooltip-BotDoy6T.js} +1 -1
  107. package/dist/client/assets/{typewriter-title-4XaunTHF.js → typewriter-title-C0AyXxMG.js} +1 -1
  108. package/dist/client/assets/{use-binding-Zcc6NZnM.js → use-binding-Dj1HVNst.js} +1 -1
  109. package/dist/client/assets/{use-collections-3NjL2Hto.js → use-collections-Vpvt2q4e.js} +1 -1
  110. package/dist/client/assets/{use-connection-QZl4Exm0.js → use-connection-DTjI_RtQ.js} +1 -1
  111. package/dist/client/assets/{use-create-virtual-mcp-V9sGOQA9.js → use-create-virtual-mcp-Jf2xsGTe.js} +1 -1
  112. package/dist/client/assets/{use-list-state-BJqScqZU.js → use-list-state-Bzarl2oM.js} +1 -1
  113. package/dist/client/assets/{use-members-prrLrEOF.js → use-members-BtNqo2oh.js} +1 -1
  114. package/dist/client/assets/{use-mobile-AgFIjOpH.js → use-mobile-CcOC6HBd.js} +1 -1
  115. package/dist/client/assets/{use-organization-settings-TgD9q9k_.js → use-organization-settings-CwiS3zFY.js} +1 -1
  116. package/dist/client/assets/{use-virtual-mcp-Cc3PLd72.js → use-virtual-mcp-hN6G5B_j.js} +1 -1
  117. package/dist/client/assets/useInfiniteQuery-B-B7Ix7h.js +1 -0
  118. package/dist/client/assets/{useMutation-CYk72WrK.js → useMutation-d4_WWA7-.js} +1 -1
  119. package/dist/client/assets/useQuery-BMYUlGUP.js +1 -0
  120. package/dist/client/assets/{value-CqS8gzSp.js → value-BHid2kuo.js} +1 -1
  121. package/dist/client/assets/{view-mode-toggle-0FnK0xP6.js → view-mode-toggle-DhWV5fbM.js} +1 -1
  122. package/dist/client/assets/{virtual-mcp-BNJP8KXe.js → virtual-mcp-Dyh0Ag7o.js} +1 -1
  123. package/dist/client/assets/{workflow-DvgbeJZ5.js → workflow-Bw7jESqY.js} +1 -1
  124. package/dist/client/index.html +1 -1
  125. package/dist/server/cli.js +7 -7
  126. package/dist/server/migrate.js +2 -2
  127. package/dist/server/server.js +6 -6
  128. package/package.json +1 -1
  129. package/dist/client/assets/constants-B4lpp64j.js +0 -1
  130. package/dist/client/assets/monitoring-CgnxsI_0.js +0 -49
  131. package/dist/client/assets/useInfiniteQuery-CJoNaoTX.js +0 -1
  132. package/dist/client/assets/useQuery-BNVmK_tg.js +0 -1
@@ -267,10 +267,10 @@ ${X.stack}`;return Y}if(typeof X==="object"&&X!==null){let Y=X,Q="";if(typeof Y.
267
267
  ${Y.stack}`;return Q}try{let G=JSON.stringify(Y,null,2);if(G!=="{}"&&G.length<1000){if(typeof Y.stack==="string"&&Y.stack&&Y.stack.length<2000)return`${G}
268
268
 
269
269
  Stack trace:
270
- ${Y.stack}`;return G}}catch{}if(typeof Y.toString==="function")try{let G=Y.toString();if(G!=="[object Object]")return G}catch{}let J=Object.keys(Y);if(J.length>0)return`Object with keys: ${J.join(", ")}`;return"[object Object]"}if(typeof X==="string")return X;if(typeof X==="number"||typeof X==="boolean")return String(X);if(typeof X==="function")return`[Function: ${X.name||"anon"}]`;if(typeof X==="symbol")return X.toString();if(typeof X==="bigint")return X.toString();try{return String(X)}catch{return"Unknown value (could not convert to string)"}}function XB(X,Y){switch(typeof Y){case"string":return X.newString(Y);case"number":return X.newNumber(Y);case"boolean":return Y?X.true:X.false;case"undefined":return X.undefined;case"object":{if(Y===null)return X.null;if(Array.isArray(Y)){let J=X.newArray();return Y.forEach((G,W)=>{let Z=XB(X,G);try{X.setProp(J,String(W),Z)}finally{Z.dispose?.()}}),J}let Q=X.newObject();for(let[J,G]of Object.entries(Y)){let W=XB(X,G);try{X.setProp(Q,J,W)}finally{W.dispose?.()}}return Q}case"function":{let Q=`__hostFn_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return X.newFunction(Q,(...G)=>{try{let W=G.map(($)=>X.dump($)),Z=Y(...W);if(Z&&typeof Z.then==="function"){let $=X.newPromise();return Z.then((K)=>{try{let H=XB(X,K);$.resolve(H),H.dispose(),X.runtime.executePendingJobs()}catch(H){let F=ez(H),V=X.newString(`Promise resolution error: ${F}`);$.reject(V),V.dispose(),X.runtime.executePendingJobs()}}).catch((K)=>{let H=ez(K),F=X.newString(`Promise rejection: ${H}`);$.reject(F),F.dispose(),X.runtime.executePendingJobs()}),$.handle}return XB(X,Z)}catch(W){let Z=ez(W);return X.newString(`HostFunctionError: ${Z}`)}finally{G.forEach((W)=>W.dispose())}})}case"bigint":return X.newString(Y.toString());case"symbol":return X.newString(Y.toString());default:try{return X.newString(String(Y))}catch{return X.undefined}}}var wJ1=()=>{};function PJ1(X){let Y=X.runtime.executePendingJobs(100);try{if("unwrap"in Y&&typeof Y.unwrap==="function")Y.unwrap()}finally{if("dispose"in Y&&typeof Y.dispose==="function")Y.dispose()}}async function MJ1(X,Y,Q){let J=Date.now(),G=X.resolvePromise(Y);while(!0){PJ1(X);let W=await Promise.race([G,Zy6(0).then(()=>null)]);if(W!==null)return W;if(Date.now()-J>Q)throw Error(`Timed out after ${Q}ms while awaiting a QuickJS promise`)}}async function g80({tools:X,code:Y,timeoutMs:Q}){let Z=[];try{let J=await OJ1({memoryLimitBytes:33554432,stackSizeBytes:524288});const G=Zf(Z,J.newContext({interruptAfterMs:Q}),0);const W=Zf(Z,cQ1(G),0);try{let F=G.evalCode(Y,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),q=XB(G,X);G.setProp(G.global,"tools",q);let z=G.runtime.hasPendingJob()?G.unwrapResult(await MJ1(G,V,Q)):V;if(z!==V)V.dispose();let D=G.getProp(z,"default"),N=G.typeof(D);if(N!=="function")return{error:`Code must export default a function (tools). Got ${N}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:W.logs};let L=G.callFunction(D,G.undefined,q),w=G.unwrapResult(L),C=await MJ1(G,w,Q),T=G.unwrapResult(C);if(G.runtime.hasPendingJob())PJ1(G);return{returnValue:G.dump(T),consoleLogs:W.logs}}catch(F){return console.log(F),{error:ez(F),consoleLogs:W.logs}}}catch($){var K=$,H=1}finally{oY0(Z,K,H)}}var Zy6=(X)=>new Promise((Y)=>setTimeout(Y,X));var AJ1=p(()=>{LJ1();wJ1()});var TJ1=p(()=>{AJ1()});async function $y6(X,Y){let Q;if(X.tool_selection_mode==="exclusion"){let G=(await Y.storage.connections.list(X.organization_id)).filter((Z)=>Z.status==="active"),W=new Map;for(let Z of X.connections)W.set(Z.connection_id,{selectedTools:Z.selected_tools,selectedResources:Z.selected_resources,selectedPrompts:Z.selected_prompts});Q=[];for(let Z of G){let $=W.get(Z.id);if($===void 0)Q.push({connection:Z,selectedTools:null,selectedResources:null,selectedPrompts:null});else if(($.selectedTools===null||$.selectedTools.length===0)&&($.selectedResources===null||$.selectedResources.length===0)&&($.selectedPrompts===null||$.selectedPrompts.length===0));else Q.push({connection:Z,selectedTools:$.selectedTools,selectedResources:$.selectedResources,selectedPrompts:$.selectedPrompts})}}else{let J=X.connections.map((W)=>W.connection_id),G=[];for(let W of J){let Z=await Y.storage.connections.findById(W);if(Z&&Z.status==="active")G.push(Z)}Q=G.map((W)=>{let Z=X.connections.find(($)=>$.connection_id===W.id);return{connection:W,selectedTools:Z?.selected_tools??null,selectedResources:Z?.selected_resources??null,selectedPrompts:Z?.selected_prompts??null}})}return Q}async function EJ1(X,Y){return(await Y.storage.connections.list(X)).filter((J)=>J.status==="active").map((J)=>({connection:J,selectedTools:null,selectedResources:null,selectedPrompts:null}))}async function Ky6(X,Y,Q){let J=await sz.create(X,Q),G=await J.mapSettled(async(F,V)=>{try{let z=(await F.proxy.client.listTools()).tools;if(Y==="exclusion"){if(F.selectedTools&&F.selectedTools.length>0){let D=new Set(F.selectedTools);z=z.filter((N)=>!D.has(N.name))}}else if(F.selectedTools&&F.selectedTools.length>0){let D=new Set(F.selectedTools);z=z.filter((N)=>D.has(N.name))}return{connectionId:V,connectionTitle:F.connection.title,tools:z}}catch(q){return console.error(`[code-execution] Failed to list tools for connection ${V}:`,q),null}}),W=new Set,Z=[],$=new Map,K=new Set;for(let F of G){if(F.status!=="fulfilled"||!F.value)continue;let{connectionId:V,connectionTitle:q,tools:z}=F.value;K.add(q);for(let D of z){if(W.has(D.name))continue;W.add(D.name),Z.push({...D,_meta:{connectionId:V,connectionTitle:q}}),$.set(D.name,{connectionId:V,originalName:D.name})}}return{tools:Z,callTool:async(F,V)=>{let q=$.get(F);if(!q)return{content:[{type:"text",text:`Tool not found: ${F}`}],isError:!0};let z=J.get(q.connectionId);if(!z)return{content:[{type:"text",text:`Connection not found for tool: ${F}`}],isError:!0};return await z.proxy.client.callTool({name:q.originalName,arguments:V})},categories:Array.from(K).sort()}}async function YB(X){let Y=_1(X),Q,J="inclusion";if(X.connectionId){let G=await X.storage.virtualMcps.findById(X.connectionId);if(G)Q=await $y6(G,X),J=G.tool_selection_mode;else Q=await EJ1(Y.id,X)}else Q=await EJ1(Y.id,X);return Ky6(Q,J,X)}function Hy6(X){return X.toLowerCase().split(/[\s_\-./]+/).filter((Y)=>Y.length>=2)}function Fy6(X,Y){let Q=0,J=Y.name.toLowerCase(),G=(Y.description??"").toLowerCase(),W=Y._meta.connectionTitle.toLowerCase();for(let Z of X){if(J===Z)Q+=10;else if(J.includes(Z))Q+=3;if(G.includes(Z))Q+=2;if(W.includes(Z))Q+=1}return Q}function Fb(X,Y,Q){let J=Hy6(X);if(J.length===0)return Y.slice(0,Q);return Y.map((G)=>({tool:G,score:Fy6(J,G)})).filter((G)=>G.score>0).sort((G,W)=>W.score-G.score).slice(0,Q).map((G)=>G.tool)}function Vb(X,Y){let Q=new Map(Y.map((G)=>[G.name,G]));return{tools:X.map((G)=>Q.get(G)).filter((G)=>G!==void 0).map((G)=>({name:G.name,description:G.description,connection:G._meta.connectionTitle,inputSchema:G.inputSchema,outputSchema:G.outputSchema})),notFound:X.filter((G)=>!Q.has(G))}}async function qb(X,Y,Q){let J=Object.fromEntries(Y.tools.map((G)=>[G.name,async(W)=>Y.callTool(G.name,W??{})]));return g80({code:X,tools:J,timeoutMs:Q})}function Ub(X){return{content:[{type:"text",text:JSON.stringify(X,null,2)}]}}function QB(X){return{content:[{type:"text",text:JSON.stringify(X,null,2)}],isError:!0}}function EP(X){let Y=new Set(Vy6);return X.filter((Q)=>!Y.has(Q.name))}var Vy6;var jP=p(()=>{TJ1();Vy6=["CODE_EXECUTION_SEARCH_TOOLS","CODE_EXECUTION_DESCRIBE_TOOLS","CODE_EXECUTION_RUN_CODE"]});var u80;var jJ1=p(()=>{Z6();AP();jP();u80=t0({name:"CODE_EXECUTION_SEARCH_TOOLS",description:"Search for available tools by name or description. Returns tool names and brief descriptions without full schemas. Use this to discover tools before calling CODE_EXECUTION_DESCRIBE_TOOLS for detailed schemas.",inputSchema:gQ1,outputSchema:uQ1,handler:async(X,Y)=>{U1(Y),_1(Y),await Y.access.check();let Q=await YB(Y),J=Fb(X.query,Q.tools,X.limit);return{query:X.query,results:J.map((G)=>({name:G.name,description:G.description,connection:G._meta.connectionTitle})),totalAvailable:Q.tools.length}}})});var m80;var CJ1=p(()=>{Z6();AP();jP();m80=t0({name:"CODE_EXECUTION_DESCRIBE_TOOLS",description:"Get detailed schemas for specific tools. Call after CODE_EXECUTION_SEARCH_TOOLS to get full input/output schemas before executing code.",inputSchema:mQ1,outputSchema:lQ1,handler:async(X,Y)=>{U1(Y),_1(Y),await Y.access.check();let Q=await YB(Y);return Vb(X.tools,Q.tools)}})});var l80;var IJ1=p(()=>{Z6();AP();jP();l80=t0({name:"CODE_EXECUTION_RUN_CODE",description:'Run JavaScript code in a sandbox. Code must be an ES module that `export default`s an async function that receives (tools) as its first parameter. Use CODE_EXECUTION_DESCRIBE_TOOLS to understand the input/output schemas for a tool before calling it. Use `await tools.toolName(args)` or `await tools["tool-name"](args)` to call tools.',inputSchema:dQ1,outputSchema:pQ1,handler:async(X,Y)=>{U1(Y),_1(Y),await Y.access.check();let Q=await YB(Y);return await qb(X.code,Q,X.timeoutMs)}})});var RJ1=p(()=>{jJ1();CJ1();IJ1();AP()});var Uy6,zy6,d80;var SJ1=p(()=>{gL();a0();Z6();Jb();q7();Uy6=U.object({data:V91.describe("Data for the new connection (id is auto-generated if not provided)")}),zy6=U.object({item:dJ.describe("The created connection entity")}),d80=t0({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",inputSchema:Uy6,outputSchema:zy6,handler:async(X,Y)=>{U1(Y);let Q=_1(Y);await Y.access.check();let J=f8(Y);if(!J)throw Error("User ID required to create connection");let G={...X.data,organization_id:Q.id,created_by:J};if(G.connection_type==="VIRTUAL"){let K=$K(G.connection_url);if(!K)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let H=await Y.storage.virtualMcps.findById(K);if(!H)throw Error(`Virtual MCP not found: ${K}`);if(H.organization_id!==Q.id)throw Error("Virtual MCP does not belong to the current organization");G.connection_url=sy(K)}let W=await rz({id:`pending-${Date.now()}`,title:G.title,connection_type:G.connection_type,connection_url:G.connection_url,connection_token:G.connection_token,connection_headers:G.connection_headers}).catch(()=>null),Z=W?.length?W:null,$=await Y.storage.connections.create({...G,tools:Z});return await Y.eventBus.publish(Q.id,ZW.SELF(Q.id),{type:"connection.created",data:$}),{item:$}}})});function CP(X,Y){if(X===Y)return!0;if(X==null||Y==null)return X===Y;if(typeof X!==typeof Y)return!1;if(Array.isArray(X)&&Array.isArray(Y)){if(X.length!==Y.length)return!1;return X.every((Q,J)=>CP(Q,Y[J]))}if(typeof X==="object"&&typeof Y==="object"){let Q=Object.keys(X),J=Object.keys(Y);if(Q.length!==J.length)return!1;return Q.every((G)=>J.includes(G)&&CP(X[G],Y[G]))}return!1}function hy6(){return(X)=>{if(!Array.isArray(X))return!0;let Y=[];return X.every((Q)=>{if(Y.some((G)=>CP(Q,G)))return!1;return Y.push(Q),!0})}}function zb(X,Y){return X.safeParse(Y).success}function MY(X){if(typeof X==="boolean")return X?U.any():U.never();let Y={};for(let G of sy6)G.apply(Y,X);let Q=[];if(Y.string!==!1)Q.push(Y.string||U.string());if(Y.number!==!1)Q.push(Y.number||U.number());if(Y.boolean!==!1)Q.push(Y.boolean||U.boolean());if(Y.null!==!1)Q.push(Y.null||U.null());if(Y.array!==!1)Q.push(Y.array||U.array(U.any()));if(Y.tuple!==!1&&Y.tuple!==void 0)Q.push(Y.tuple);if(Y.object!==!1)if(Y.object)Q.push(Y.object);else{let G=U.custom((W)=>{return typeof W==="object"&&W!==null&&!Array.isArray(W)},"Must be an object, not an array");Q.push(G)}if(Y.file!==!1&&Y.file!==void 0)Q.push(Y.file);let J;if(Q.length===0)J=U.never();else if(Q.length===1)J=Q[0];else if(!Object.keys(X).some((W)=>W!=="$schema"&&W!=="title"&&W!=="description"))J=U.any();else J=U.union(Q);for(let G of ty6)J=G.apply(J,X);return J}var By6=class{apply(X,Y){if(!Y.type)return;let Q=Array.isArray(Y.type)?Y.type:[Y.type],J=new Set(Q);if(!J.has("string"))X.string=!1;if(!J.has("number")&&!J.has("integer"))X.number=!1;if(!J.has("boolean"))X.boolean=!1;if(!J.has("null"))X.null=!1;if(!J.has("array"))X.array=!1;if(!J.has("object"))X.object=!1;if(J.has("integer")&&X.number!==!1){let G=X.number||U.number();if(G instanceof U.ZodNumber)X.number=G.int()}}},Dy6=class{apply(X,Y){if(Y.const===void 0)return;let Q=Y.const;if(X.string=!1,X.number=!1,X.boolean=!1,X.null=!1,X.array=!1,X.object=!1,typeof Q==="string")X.string=U.literal(Q);else if(typeof Q==="number")X.number=U.literal(Q);else if(typeof Q==="boolean")X.boolean=U.literal(Q);else if(Q===null)X.null=U.null();else if(Array.isArray(Q))X.array=void 0;else if(typeof Q==="object")X.object=void 0}},Ny6=class{apply(X,Y){if(!Y.enum)return;if(Y.enum.length===0){if(!Y.type)X.string=!1,X.number=!1,X.boolean=!1,X.null=!1,X.array=!1,X.object=!1;return}let Q={string:Y.enum.filter((J)=>typeof J==="string"),number:Y.enum.filter((J)=>typeof J==="number"),boolean:Y.enum.filter((J)=>typeof J==="boolean"),null:Y.enum.filter((J)=>J===null),array:Y.enum.filter((J)=>Array.isArray(J)),object:Y.enum.filter((J)=>typeof J==="object"&&J!==null&&!Array.isArray(J))};X.string=this.createTypeSchema(Q.string,"string"),X.number=this.createTypeSchema(Q.number,"number"),X.boolean=this.createTypeSchema(Q.boolean,"boolean"),X.null=Q.null.length>0?U.null():!1,X.array=Q.array.length>0?void 0:!1,X.object=Q.object.length>0?void 0:!1}createTypeSchema(X,Y){if(X.length===0)return!1;if(X.length===1)return U.literal(X[0]);if(Y==="string")return U.enum(X);if(Y==="number"){let[Q,J,...G]=X;return U.union([U.literal(Q),U.literal(J),...G.map((W)=>U.literal(W))])}if(Y==="boolean")return U.union([U.literal(!0),U.literal(!1)]);return!1}},Oy6=class{apply(X,Y){let Q=Y;if(Q.type==="string"&&Q.format==="binary"&&Q.contentEncoding==="binary"){let J=U.file();if(Q.minLength!==void 0)J=J.min(Q.minLength);if(Q.maxLength!==void 0)J=J.max(Q.maxLength);if(Q.contentMediaType!==void 0)J=J.mime(Q.contentMediaType);X.file=J,X.string=!1}}},Ly6=class{apply(X,Y){let Q=Y;if(Y.type===void 0&&(Q.minLength!==void 0||Q.maxLength!==void 0||Q.pattern!==void 0)){if(X.string===void 0)X.string=U.string()}}},wy6=class{apply(X,Y){let Q=Y;if(Q.minLength===void 0)return;if(X.string!==!1){let J=X.string||U.string();if(J instanceof U.ZodString)X.string=J.refine((G)=>{return Array.from(G).length>=Q.minLength},{message:`String must be at least ${Q.minLength} characters long`})}}},My6=class{apply(X,Y){let Q=Y;if(Q.maxLength===void 0)return;if(X.string!==!1){let J=X.string||U.string();if(J instanceof U.ZodString)X.string=J.refine((G)=>{return Array.from(G).length<=Q.maxLength},{message:`String must be at most ${Q.maxLength} characters long`})}}},Py6=class{apply(X,Y){let Q=Y;if(!Q.pattern)return;if(X.string!==!1){let J=X.string||U.string();if(J instanceof U.ZodString){let G=new RegExp(Q.pattern);X.string=J.regex(G)}}}},Ay6=class{apply(X,Y){let Q=Y;if(Q.minimum===void 0)return;if(X.number!==!1){let J=X.number||U.number();if(J instanceof U.ZodNumber)X.number=J.min(Q.minimum)}}},Ty6=class{apply(X,Y){let Q=Y;if(Q.maximum===void 0)return;if(X.number!==!1){let J=X.number||U.number();if(J instanceof U.ZodNumber)X.number=J.max(Q.maximum)}}},Ey6=class{apply(X,Y){let Q=Y;if(Q.exclusiveMinimum===void 0)return;if(X.number!==!1){let J=X.number||U.number();if(J instanceof U.ZodNumber)if(typeof Q.exclusiveMinimum==="number")X.number=J.gt(Q.exclusiveMinimum);else X.number=!1}}},jy6=class{apply(X,Y){let Q=Y;if(Q.exclusiveMaximum===void 0)return;if(X.number!==!1){let J=X.number||U.number();if(J instanceof U.ZodNumber)if(typeof Q.exclusiveMaximum==="number")X.number=J.lt(Q.exclusiveMaximum);else X.number=!1}}},Cy6=class{apply(X,Y){let Q=Y;if(Q.multipleOf===void 0)return;if(X.number!==!1){let J=X.number||U.number();if(J instanceof U.ZodNumber)X.number=J.refine((G)=>{if(Q.multipleOf===0)return!1;let W=G/Q.multipleOf,Z=Math.round(W),$=Math.min(Math.abs(G)*Number.EPSILON*10,Math.abs(Q.multipleOf)*Number.EPSILON*10);return Math.abs(W-Z)<=$/Math.abs(Q.multipleOf)},{message:`Must be a multiple of ${Q.multipleOf}`})}}},Iy6=class{apply(X,Y){let Q=Y;if(Y.type===void 0&&(Q.minItems!==void 0||Q.maxItems!==void 0||Q.items!==void 0||Q.prefixItems!==void 0)){if(X.array===void 0)X.array=U.array(U.any())}}},Ry6=class{apply(X,Y){let Q=Y;if(Q.minItems===void 0)return;if(X.array!==!1)X.array=(X.array||U.array(U.any())).min(Q.minItems)}},Sy6=class{apply(X,Y){let Q=Y;if(Q.maxItems===void 0)return;if(X.array!==!1)X.array=(X.array||U.array(U.any())).max(Q.maxItems)}},ky6=class{apply(X,Y){let Q=Y;if(X.array===!1)return;if(Array.isArray(Q.items))X.array=X.array||U.array(U.any());else if(Q.items&&typeof Q.items!=="boolean"&&!Q.prefixItems){let J=MY(Q.items),G=U.array(J);if(X.array&&X.array instanceof U.ZodArray){let W=X.array._def;if(W.checks)W.checks.forEach((Z)=>{if(Z._zod&&Z._zod.def){let $=Z._zod.def;if($.check==="min_length"&&$.minimum!==void 0)G=G.min($.minimum);else if($.check==="max_length"&&$.maximum!==void 0)G=G.max($.maximum)}})}X.array=G}else if(typeof Q.items==="boolean"&&Q.items===!1)if(!Q.prefixItems)X.array=U.array(U.any()).max(0);else X.array=X.array||U.array(U.any());else if(typeof Q.items==="boolean"&&Q.items===!0)X.array=X.array||U.array(U.any());else if(Q.prefixItems)X.array=X.array||U.array(U.any())}},vy6=class{apply(X,Y){if(Y.type!=="array")return;let Q=Y;if(!Array.isArray(Q.items))return;if(X.array===!1)return;let J=Q.items.map((W)=>MY(W)),G;if(J.length===0)G=U.tuple([]);else G=U.tuple(J);if(Q.minItems!==void 0&&Q.minItems>J.length)G=!1;if(Q.maxItems!==void 0&&Q.maxItems<J.length)G=!1;X.tuple=G,X.array=!1}},_y6=class{apply(X,Y){let Q=Y;if(X.object===!1)return;if(Q.properties||Q.required||Q.additionalProperties!==void 0)X.object=X.object||U.object({}).passthrough()}},yy6=class{apply(X,Y){let Q=Y;if(Y.type===void 0&&(Q.maxProperties!==void 0||Q.minProperties!==void 0)){if(X.object===void 0)X.object=U.object({}).passthrough()}}},by6=class{apply(X,Y){let Q=Y;if(Q.maxProperties===void 0)return;if(X.object!==!1){let J=X.object||U.object({}).passthrough();X.object=J.refine((G)=>Object.keys(G).length<=Q.maxProperties,{message:`Object must have at most ${Q.maxProperties} properties`})}}},fy6=class{apply(X,Y){let Q=Y;if(Q.minProperties===void 0)return;if(X.object!==!1){let J=X.object||U.object({}).passthrough();X.object=J.refine((G)=>Object.keys(G).length>=Q.minProperties,{message:`Object must have at least ${Q.minProperties} properties`})}}},xy6=class{apply(X,Y){if(!Y.not)return X;let Q=MY(Y.not);return X.refine((J)=>!zb(Q,J),{message:"Value must not match the 'not' schema"})}},gy6=class{apply(X,Y){if(Y.uniqueItems!==!0)return X;return X.refine(hy6(),{message:"Array items must be unique"})}},uy6=class{apply(X,Y){if(!Y.allOf||Y.allOf.length===0)return X;return Y.allOf.map((J)=>MY(J)).reduce((J,G)=>U.intersection(J,G),X)}},my6=class{apply(X,Y){if(!Y.anyOf||Y.anyOf.length===0)return X;let Q=Y.anyOf.length===1?MY(Y.anyOf[0]):U.union([MY(Y.anyOf[0]),MY(Y.anyOf[1]),...Y.anyOf.slice(2).map((J)=>MY(J))]);return U.intersection(X,Q)}},ly6=class{apply(X,Y){if(!Y.oneOf||Y.oneOf.length===0)return X;let Q=Y.oneOf.map((J)=>MY(J));return X.refine((J)=>{let G=0;for(let W of Q)if(W.safeParse(J).success){if(G++,G>1)return!1}return G===1},{message:"Value must match exactly one of the oneOf schemas"})}},dy6=class{apply(X,Y){let Q=Y;if(Q.prefixItems&&Array.isArray(Q.prefixItems)){let G=Q.prefixItems.map((W)=>MY(W));return X.refine((W)=>{if(!Array.isArray(W))return!0;for(let Z=0;Z<Math.min(W.length,G.length);Z++)if(!zb(G[Z],W[Z]))return!1;if(W.length>G.length){if(typeof Q.items==="boolean"&&Q.items===!1)return!1;else if(Q.items&&typeof Q.items==="object"&&!Array.isArray(Q.items)){let Z=MY(Q.items);for(let $=G.length;$<W.length;$++)if(!zb(Z,W[$]))return!1}}return!0},{message:"Array does not match prefixItems schema"})}return X}},py6=class{apply(X,Y){let Q=Y;if(!Q.properties&&!Q.required&&Q.additionalProperties!==!1)return X;if(X instanceof U.ZodObject||X instanceof U.ZodRecord){let J={};if(Q.properties){for(let[G,W]of Object.entries(Q.properties))if(W!==void 0)J[G]=MY(W)}if(Q.required&&Array.isArray(Q.required)){let G=new Set(Q.required);for(let W of Object.keys(J))if(!G.has(W))J[W]=J[W].optional()}else for(let G of Object.keys(J))J[G]=J[G].optional();if(Q.additionalProperties===!1)return U.object(J);else return U.object(J).passthrough()}return X.refine((J)=>{if(typeof J!=="object"||J===null||Array.isArray(J))return!0;if(Q.properties){for(let[G,W]of Object.entries(Q.properties))if(W!==void 0){if(Object.getOwnPropertyDescriptor(J,G)!==void 0){if(!MY(W).safeParse(J[G]).success)return!1}}}if(Q.required&&Array.isArray(Q.required)){for(let G of Q.required)if(Object.getOwnPropertyDescriptor(J,G)===void 0)return!1}if(Q.additionalProperties===!1&&Q.properties){let G=new Set(Object.keys(Q.properties));for(let W in J)if(!G.has(W))return!1}return!0},{message:"Object constraints validation failed"})}},cy6=class{apply(X,Y){if(!Y.enum||Y.enum.length===0)return X;let Q=Y.enum.filter((J)=>Array.isArray(J)||typeof J==="object"&&J!==null);if(Q.length===0)return X;return X.refine((J)=>{if(typeof J!=="object"||J===null)return!0;return Q.some((G)=>CP(J,G))},{message:"Value must match one of the enum values"})}},ny6=class{apply(X,Y){if(Y.const===void 0)return X;let Q=Y.const;if(typeof Q!=="object"||Q===null)return X;return X.refine((J)=>CP(J,Q),{message:"Value must equal the const value"})}},iy6=class{apply(X,Y){if(Y.description)X=X.describe(Y.description);return X}},ay6=class{apply(X,Y){var Q;let J=Y;if(!((Q=J.required)==null?void 0:Q.includes("__proto__"))||Y.type!==void 0)return X;return U.any().refine((G)=>this.validateRequired(G,J.required),{message:"Missing required properties"})}validateRequired(X,Y){if(typeof X!=="object"||X===null||Array.isArray(X))return!0;return Y.every((Q)=>Object.prototype.hasOwnProperty.call(X,Q))}},ry6=class{apply(X,Y){var Q;let J=Y;if(J.contains===void 0)return X;let G=MY(J.contains),W=(Q=J.minContains)!=null?Q:1,Z=J.maxContains;return X.refine(($)=>{if(!Array.isArray($))return!0;let K=0;for(let H of $)if(zb(G,H))K++;if(K<W)return!1;if(Z!==void 0&&K>Z)return!1;return!0},{message:"Array must contain required items matching the schema"})}},oy6=class{apply(X,Y){let{default:Q}=Y;if(Q===void 0)return X;if(!X.safeParse(Q).success)return X;return X.default(Q)}},sy6,ty6;var kJ1=p(()=>{c6();c6();c6();c6();c6();c6();c6();c6();c6();c6();c6();c6();c6();c6();sy6=[new Dy6,new Ny6,new By6,new Oy6,new Ly6,new Iy6,new yy6,new wy6,new My6,new Py6,new Ay6,new Ty6,new Ey6,new jy6,new Cy6,new vy6,new Ry6,new Sy6,new ky6,new by6,new fy6,new _y6],ty6=[new ay6,new cy6,new ny6,new uy6,new my6,new ly6,new dy6,new py6,new ry6,new xy6,new gy6,new oy6,new iy6]});class p80{constructor(X){this._url=X}start(){if(this._socket)throw Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((X,Y)=>{this._socket=new WebSocket(this._url,ey6),this._socket.onerror=(Q)=>{let J="error"in Q?Q.error:Error(`WebSocket error: ${JSON.stringify(Q)}`);Y(J),this.onerror?.(J)},this._socket.onopen=()=>{X()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=(Q)=>{let J;try{J=PQ.parse(JSON.parse(Q.data))}catch(G){this.onerror?.(G);return}this.onmessage?.(J)}})}async close(){this._socket?.close()}send(X){return new Promise((Y,Q)=>{if(!this._socket){Q(Error("Not connected"));return}this._socket?.send(JSON.stringify(X)),Y()})}}var ey6="mcp";var vJ1=p(()=>{qX()});function Xb6(X){let Y=X;if(!Y||typeof Y!=="object"||!("method"in Y))return null;switch(Y.method){case"initialize":{let Q=Y?.params?.protocolVersion;if(!Q)return null;return{type:"emit",message:{result:{protocolVersion:Q,capabilities:{tools:{}},serverInfo:{name:"deco-chat-server",version:"1.0.0"}},jsonrpc:Y.jsonrpc??"2.0",id:Y.id}}}case"notifications/roots/list_changed":case"notifications/initialized":case"notifications/cancelled":case"notifications/progress":return{type:"suppress"};default:return null}}var c80;var _J1=p(()=>{oq();c80=class c80 extends IG{constructor(X,Y){super(X,Y)}send(X,Y){let Q=Xb6(X);if(Q?.type==="emit")return this.onmessage?.(Q.message),Promise.resolve();if(Q?.type==="suppress")return Promise.resolve();return super.send(X,Y)}}});var yJ1,bJ1=async(X,Y,Q)=>{let J=Yb6(X.connection,Y,Q);if(!J)throw Error("Unknown MCP connection type");let G=new yJ1({name:X?.name??"MCP Client",version:"1.0.0"});return await G.connect(J),{client:G,callStreamableTool:(W,Z)=>{if(X.connection.type!=="HTTP")throw Error("HTTP connection required");let $=new Headers(Q);if(!$.has("Authorization"))$.set("Authorization",`Bearer ${X.connection.token}`);for(let[F,V]of Object.entries(X.connection.headers??{}))$.set(F,V);let K=new URL(X.connection.url),H=K.pathname.replace(/\/+$/,"")||"/";return K.pathname=`${H}/call-tool/${encodeURIComponent(W)}`,fetch(K.href,{method:"POST",redirect:"manual",body:JSON.stringify(Z),headers:$})}}},Yb6=(X,Y,Q)=>{if(X.type==="Websocket")return new p80(new URL(X.url));if(X.type!=="SSE"&&X.type!=="HTTP")return null;let G={...X.token?{authorization:`Bearer ${X.token}`}:{},...Q??{},..."headers"in X?X.headers||{}:{}};if(X.type==="SSE"){let W={requestInit:{headers:G,signal:Y}};if(X.token)W.eventSourceInit={fetch:(Z,$)=>{return fetch(Z,{...$,headers:{...G,Accept:"text/event-stream"},signal:Y})}};return new VF(new URL(X.url),W)}return new c80(new URL(X.url),{requestInit:{headers:G,signal:Y,credentials:"include"}})};var fJ1=p(()=>{eH();Xb();vJ1();qX();_J1();yJ1=class yJ1 extends l9{constructor(X,Y){super(X,Y)}async listTools(X,Y){return await this.request({method:"tools/list",params:X},HL,Y)}}});function xJ1(X){let Y=(Q)=>{if("connection"in X)return bJ1({connection:X.connection},void 0,Q);return X.client};return new Proxy({},{get(Q,J){if(J==="toJSON")return null;if(typeof J!=="string")throw Error("Name must be a string");if(J==="listTools")return $;async function G(K,H=J){let F=X?.debugId?.(),V=F?{"x-trace-debug-id":F}:void 0,{client:q,callStreamableTool:z}=await Y(V);if(X?.streamable?.[String(H)])return z(String(H),K);let{structuredContent:D,isError:N,content:L}=await q.callTool({name:String(H),arguments:K});if(N){let w=L?.[0]?.text,C=typeof w==="string"?Qb6(w):null,T=C?.code&&typeof X?.getErrorByStatusCode==="function"?X.getErrorByStatusCode(C.code,C.message,C.traceId):null;if(T)throw T;throw Error(`Tool ${String(H)} returned an error: ${JSON.stringify(D??L)}`)}return D}async function W(){let{client:K}=await Y(),{tools:H}=await K.listTools();return H}async function Z(){if(!("connection"in X))return W();let K=X.connection,H=JSON.stringify(K);try{if(!Bb.has(H))Bb.set(H,W());return await Bb.get(H)}catch(F){console.error("Failed to list tools",F),Bb.delete(H);return}}async function $(){return(await Z()??[]).map((H)=>hJ1(H,G))}return G.asTool=async()=>{let H=(await Z()??[]).find((F)=>F.name===J);if(!H)throw Error(`Tool ${J} not found`);return hJ1(H,G)},G}})}var Qb6=(X)=>{try{return JSON.parse(X)}catch{return X}},Bb,hJ1=(X,Y)=>{return{...X,id:X.name,inputSchema:X.inputSchema?MY(X.inputSchema):void 0,outputSchema:X.outputSchema?MY(X.outputSchema):void 0,execute:(Q)=>{return Y(Q.context,X.name)}}};var gJ1=p(()=>{kJ1();fJ1();Bb=new Map});function Db(X){return xJ1(X)}var Al4;var uJ1=p(()=>{gJ1();Al4=new Proxy({},{get(X,Y){if(Y==="toJSON")return null;if(Y==="forConnection")return(Q)=>Db({connection:Q});return global[Y]}})});function Nb(X){return{isImplementedBy:(Y)=>{for(let Q of X){let J=typeof Q.name==="string"?new RegExp(`^${Q.name}$`):Q.name,G=Y.find((W)=>J.test(W.name));if(!G&&Q.opt)continue;if(!G)return!1}return!0}}}var NF=(X)=>{return{...Nb(X),forClient:(Y)=>{return Db({client:Y,streamable:X.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})},forConnection:(Y)=>{return Db({connection:Y,streamable:X.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})}}};var IP=p(()=>{uJ1()});var n80,Il4;var mJ1=p(()=>{qN();n80=E6(VN(),1),Il4=n80.createContext(null)});function LF(X){return U.object({items:U.array(X).describe("Array of collection items"),totalCount:U.number().int().min(0).optional().describe("Total number of matching items (if available)"),hasMore:U.boolean().optional().describe("Whether there are more items available")})}function SP(X){return U.object({item:X.nullable().describe("The retrieved item, or null if not found")})}function Wb6(X){return U.object({data:X.partial().describe("Data for the new entity (id may be auto-generated)")})}function Zb6(X){return U.object({item:X.describe("The created entity with generated id")})}function $b6(X){return U.object({id:U.string().describe("ID of the entity to update"),data:X.partial().describe("Partial entity data to update")})}function Kb6(X){return U.object({item:X.describe("The updated entity")})}function vP(X){return U.object({item:X.describe("The deleted entity")})}function GB(X,Y,Q){let J=X.toUpperCase(),G=Q?.readOnly??!1,W=[{name:`COLLECTION_${J}_LIST`,inputSchema:OF,outputSchema:LF(Y)},{name:`COLLECTION_${J}_GET`,inputSchema:RP,outputSchema:SP(Y)}];if(!G)W.push({name:`COLLECTION_${J}_CREATE`,inputSchema:Wb6(Y),outputSchema:Zb6(Y),opt:!0},{name:`COLLECTION_${J}_UPDATE`,inputSchema:$b6(Y),outputSchema:Kb6(Y),opt:!0},{name:`COLLECTION_${J}_DELETE`,inputSchema:kP,outputSchema:vP(Y),opt:!0});return W}var JB,Jb6,lJ1,Gb6,OF,RP,kP;var x5=p(()=>{a0();JB=U.object({id:U.string().describe("Unique identifier for the entity"),title:U.string().describe("Human-readable title for the entity"),description:U.string().nullish().describe("Description of the entity"),created_at:U.string().datetime(),updated_at:U.string().datetime(),created_by:U.string().optional(),updated_by:U.string().optional()}),Jb6=U.object({field:U.array(U.string()),operator:U.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:U.unknown()}),lJ1=U.lazy(()=>U.union([Jb6,U.object({operator:U.enum(["and","or","not"]),conditions:U.array(lJ1)})])),Gb6=U.object({field:U.array(U.string()),direction:U.enum(["asc","desc"]),nulls:U.enum(["first","last"]).optional()}),OF=U.object({where:lJ1.optional().describe("Filter expression"),orderBy:U.array(Gb6).optional().describe("Sort expressions"),limit:U.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:U.number().int().min(0).optional().describe("Number of items to skip")});RP=U.object({id:U.string().describe("ID of the entity to retrieve")});kP=U.object({id:U.string().describe("ID of the entity to delete")})});var Hb6,dJ1,bl4;var pJ1=p(()=>{a0();x5();Hb6=U.object({id:U.string(),name:U.string(),description:U.string().optional(),inputSchema:U.record(U.string(),U.unknown()),outputSchema:U.record(U.string(),U.unknown()).optional()}),dJ1=JB.extend({_meta:U.object({"io.decocms":U.object({id:U.string(),verified:U.boolean(),scopeName:U.string(),appName:U.string(),friendlyName:U.string().nullable().optional(),metadata:U.record(U.string(),U.unknown()).nullable().optional(),publishedAt:U.string().datetime().optional(),updatedAt:U.string().datetime().optional(),tools:U.array(Hb6).nullable().optional().describe("Available tools exposed by this app")}).optional()}).optional(),server:U.object({$schema:U.string().optional(),_meta:U.record(U.string(),U.unknown()).optional(),name:U.string().describe("The server name (scope/app)"),title:U.string().optional().describe("User-friendly title"),description:U.string().optional().describe("Server description"),icons:U.array(U.object({src:U.string(),mimeType:U.string().optional(),sizes:U.array(U.string()).optional(),theme:U.enum(["light","dark"]).optional()})).optional(),remotes:U.array(U.object({type:U.enum(["http","stdio","sse"]),url:U.string().optional(),headers:U.array(U.unknown()).optional()})).optional(),packages:U.array(U.unknown()).optional(),repository:U.object({url:U.string(),source:U.string().optional(),subfolder:U.string().optional()}).optional(),version:U.string().optional(),websiteUrl:U.string().optional()})}),bl4=GB("registry_app",dJ1,{readOnly:!0})});var cJ1,nJ1,iJ1,aJ1,rJ1,i80;var oJ1=p(()=>{a0();IP();cJ1=U.object({specversion:U.literal("1.0").describe("CloudEvents specification version"),id:U.string().describe("Unique identifier for this event (UUID recommended)"),source:U.string().describe("Connection ID of the event publisher"),type:U.string().describe("Event type (e.g., 'order.created', 'user.signup')"),time:U.string().datetime().optional().describe("Timestamp of when the event occurred (ISO 8601)"),subject:U.string().optional().describe("Subject/resource identifier (e.g., order ID, user ID)"),datacontenttype:U.string().optional().default("application/json").describe("Content type of the data attribute"),dataschema:U.string().url().optional().describe("URI to the schema for the data attribute"),data:U.unknown().optional().describe("Event payload (any JSON value)")}),nJ1=U.object({events:U.array(cJ1).min(1).describe("Batch of CloudEvents to process")}),iJ1=U.object({success:U.boolean().optional().describe("Whether this event was processed successfully"),error:U.string().optional().describe("Error message for this event"),retryAfter:U.number().int().positive().optional().describe("Re-deliver this event after this many ms")}),aJ1=U.object({success:U.boolean().optional().describe("Batch success - applies to events not in results"),error:U.string().optional().describe("Batch error message - applies to events not in results"),processedCount:U.number().int().min(0).optional().describe("Number of events successfully processed"),retryAfter:U.number().int().positive().optional().describe("Batch retryAfter - applies to events not in results"),results:U.record(U.string(),iJ1).optional().describe("Per-event results keyed by event ID")}),rJ1=[{name:"ON_EVENTS",inputSchema:nJ1,outputSchema:aJ1}],i80=NF(rJ1)});var _P,yP,bP,fP,sJ1,tJ1,hP,xP,gP,uP,mP,lP,dP,pP,eJ1,Fb6;var X51=p(()=>{a0();IP();_P=U.object({type:U.string().min(1).max(255).describe("Event type identifier"),subject:U.string().max(255).optional().describe("Subject/resource identifier (e.g., order ID)"),data:U.unknown().optional().describe("Event payload"),deliverAt:U.string().datetime().optional().describe("Scheduled delivery time (ISO 8601). Omit for immediate delivery."),cron:U.string().max(100).optional().describe("Cron expression for recurring delivery. Use EVENT_CANCEL to stop.")}),yP=U.object({id:U.string().describe("Unique event ID"),type:U.string().describe("Event type"),source:U.string().describe("Source connection ID"),time:U.string().describe("Event timestamp")}),bP=U.object({eventType:U.string().min(1).max(255).describe("Event type to subscribe to"),publisher:U.string().optional().describe("Filter events by publisher connection ID"),filter:U.string().max(1000).optional().describe("JSONPath filter expression on event data")}),fP=U.object({subscription:U.object({id:U.string().describe("Subscription ID"),connectionId:U.string().describe("Subscriber connection ID"),eventType:U.string().describe("Event type pattern"),publisher:U.string().nullable().describe("Publisher connection filter"),filter:U.string().nullable().describe("JSONPath filter expression"),enabled:U.boolean().describe("Whether subscription is enabled"),createdAt:U.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:U.string().datetime().describe("Updated timestamp (ISO 8601)")})}),sJ1=U.object({eventType:U.string().min(1).max(255).describe("Event type to subscribe to"),publisher:U.string().optional().describe("Filter events by publisher connection ID"),filter:U.string().max(1000).optional().describe("JSONPath filter expression on event data")}),tJ1=U.object({id:U.string().describe("Subscription ID"),connectionId:U.string().describe("Subscriber connection ID"),eventType:U.string().describe("Event type pattern"),publisher:U.string().nullable().describe("Publisher connection filter"),filter:U.string().nullable().describe("JSONPath filter expression"),enabled:U.boolean().describe("Whether subscription is enabled"),createdAt:U.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:U.string().datetime().describe("Updated timestamp (ISO 8601)")}),hP=U.object({subscriptions:U.array(sJ1).describe("Desired subscriptions - system will create/update/delete to match")}),xP=U.object({created:U.number().int().min(0).describe("Number of subscriptions created"),updated:U.number().int().min(0).describe("Number of subscriptions with filter updated"),deleted:U.number().int().min(0).describe("Number of subscriptions removed"),unchanged:U.number().int().min(0).describe("Number of subscriptions unchanged"),subscriptions:U.array(tJ1).describe("Current subscriptions after sync")}),gP=U.object({subscriptionId:U.string().describe("Subscription ID to remove")}),uP=U.object({success:U.boolean().describe("Whether unsubscribe was successful"),subscriptionId:U.string().describe("Subscription ID that was removed")}),mP=U.object({eventId:U.string().describe("Event ID to cancel")}),lP=U.object({success:U.boolean().describe("Whether cancellation was successful"),eventId:U.string().describe("Event ID that was cancelled")}),dP=U.object({eventId:U.string().describe("Event ID to acknowledge")}),pP=U.object({success:U.boolean().describe("Whether ACK was successful"),eventId:U.string().describe("Event ID that was acknowledged")}),eJ1=[{name:"EVENT_PUBLISH",inputSchema:_P,outputSchema:yP},{name:"EVENT_SUBSCRIBE",inputSchema:bP,outputSchema:fP},{name:"EVENT_UNSUBSCRIBE",inputSchema:gP,outputSchema:uP},{name:"EVENT_CANCEL",inputSchema:mP,outputSchema:lP},{name:"EVENT_ACK",inputSchema:dP,outputSchema:pP},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:hP,outputSchema:xP}],Fb6=NF(eJ1)});var pl4,cl4,nl4,il4,al4,rl4,ol4,sl4,tl4,el4,Xd4,Yd4;var Y51=p(()=>{a0();pl4=U.object({prefix:U.string().optional().describe("Filter objects by prefix (e.g., 'folder/' for folder contents)"),maxKeys:U.number().optional().default(1000).describe("Maximum number of keys to return (default: 1000)"),continuationToken:U.string().optional().describe("Token for pagination from previous response"),delimiter:U.string().optional().describe("Delimiter for grouping keys (typically '/'). When set, commonPrefixes returns folder paths.")}),cl4=U.object({objects:U.array(U.object({key:U.string().describe("Object key/path"),size:U.number().describe("Object size in bytes"),lastModified:U.string().describe("Last modified timestamp"),etag:U.string().describe("Entity tag for the object")})),nextContinuationToken:U.string().optional().describe("Token for fetching next page of results"),isTruncated:U.boolean().describe("Whether there are more results available"),commonPrefixes:U.array(U.string()).optional().describe("Folder paths when delimiter is used (e.g., ['photos/2024/', 'photos/2025/'])")}),nl4=U.object({key:U.string().describe("Object key/path to get metadata for")}),il4=U.object({contentType:U.string().optional().describe("MIME type of the object"),contentLength:U.number().describe("Size of the object in bytes"),lastModified:U.string().describe("Last modified timestamp"),etag:U.string().describe("Entity tag for the object"),metadata:U.record(U.string(),U.string()).optional().describe("Custom metadata key-value pairs")}),al4=U.object({key:U.string().describe("Object key/path to generate URL for"),expiresIn:U.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)")}),rl4=U.object({url:U.string().describe("Presigned URL for downloading the object"),expiresIn:U.number().describe("Expiration time in seconds that was used")}),ol4=U.object({key:U.string().describe("Object key/path for the upload"),expiresIn:U.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)"),contentType:U.string().optional().describe("MIME type for the object being uploaded")}),sl4=U.object({url:U.string().describe("Presigned URL for uploading the object"),expiresIn:U.number().describe("Expiration time in seconds that was used")}),tl4=U.object({key:U.string().describe("Object key/path to delete")}),el4=U.object({success:U.boolean().describe("Whether the deletion was successful"),key:U.string().describe("The key that was deleted")}),Xd4=U.object({keys:U.array(U.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),Yd4=U.object({deleted:U.array(U.string()).describe("Array of successfully deleted keys"),errors:U.array(U.object({key:U.string(),message:U.string()})).describe("Array of errors for failed deletions")})});var Ob=p(()=>{IP();mJ1();pJ1();oJ1();X51();Y51()});var Vb6,qb6,Q51;var J51=p(()=>{a0();x5();Vb6=JB.extend({avatar:U.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:U.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:U.string().describe("Virtual MCP ID to use for this assistant"),model:U.object({id:U.string().describe("Model ID"),connectionId:U.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),qb6=GB("assistant",Vb6),Q51=[...qb6]});var cP,aW,W51,Ub6,zb6,Z51,Bb6,Db6,Nb6,Ob6,Lb6,wb6,$51,Mb6,Pb6,Ab6,Tb6,Eb6,jb6,Cb6,Ib6,Rb6,Sb6,Md4,kb6,Pd4,G51,vb6,_b6,a80,Lb;var wb=p(()=>{a0();IP();x5();cP=U.lazy(()=>U.union([U.null(),U.string(),U.number(),U.boolean(),U.record(U.string(),cP),U.array(cP)])),aW=U.record(U.string(),U.record(U.string(),cP)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),W51=U.object({type:U.literal("text"),text:U.string().describe("The text content"),providerOptions:aW}),Ub6=U.object({type:U.literal("text"),text:U.string().describe("The text content"),providerMetadata:U.any().optional().describe("Additional provider-specific metadata")}),zb6=U.string().describe("File data as URL string"),Z51=U.object({type:U.literal("file"),filename:U.string().optional().describe("Optional filename of the file"),data:zb6,mediaType:U.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:aW}),Bb6=U.object({type:U.literal("file"),mediaType:U.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:U.string().describe("Generated file data as base64 encoded string")}),Db6=U.object({type:U.literal("reasoning"),text:U.string().describe("The reasoning text"),providerOptions:aW}),Nb6=U.object({type:U.literal("reasoning"),text:U.string().describe("The reasoning text"),providerMetadata:U.any().optional().describe("Additional provider-specific metadata")}),Ob6=U.object({type:U.literal("tool-call"),toolCallId:U.string().describe("ID of the tool call, used to match with tool result"),toolName:U.string().describe("Name of the tool being called"),input:U.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:U.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:aW}),Lb6=U.object({type:U.literal("tool-call"),toolCallId:U.string().describe("ID of the tool call"),toolName:U.string().describe("Name of the tool being called"),input:U.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:U.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:U.any().optional().describe("Additional provider-specific metadata")}),wb6=U.union([U.object({type:U.literal("text"),value:U.string()}),U.object({type:U.literal("json"),value:cP}),U.object({type:U.literal("error-text"),value:U.string()}),U.object({type:U.literal("error-json"),value:cP}),U.object({type:U.literal("content"),value:U.array(U.union([U.object({type:U.literal("text"),text:U.string().describe("Text content")}),U.object({type:U.literal("media"),data:U.string().describe("Base-64 encoded media data"),mediaType:U.string().describe("IANA media type")})]))})]),$51=U.object({type:U.literal("tool-result"),toolCallId:U.string().describe("ID of the tool call that this result is associated with"),toolName:U.string().describe("Name of the tool that generated this result"),output:wb6.describe("Result of the tool call"),result:U.unknown().describe("Unknown result of the tool call"),providerOptions:aW}),Mb6=U.object({type:U.literal("tool-result"),toolCallId:U.string().describe("ID of the tool call that this result is associated with"),toolName:U.string().describe("Name of the tool that generated this result"),result:U.any().describe("Result of the tool call (JSON-serializable)"),isError:U.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:U.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:U.any().optional().describe("Additional provider-specific metadata")}),Pb6=U.union([U.object({type:U.literal("source"),sourceType:U.literal("url"),id:U.string().describe("The ID of the source"),url:U.string().describe("The URL of the source"),title:U.string().optional().describe("The title of the source"),providerMetadata:U.any().optional().describe("Additional provider-specific metadata")}),U.object({type:U.literal("source"),sourceType:U.literal("document"),id:U.string().describe("The ID of the source"),mediaType:U.string().describe("IANA media type of the document (e.g., application/pdf)"),title:U.string().describe("The title of the document"),filename:U.string().optional().describe("Optional filename of the document"),providerMetadata:U.any().optional().describe("Additional provider-specific metadata")})]),Ab6=U.object({role:U.literal("system"),content:U.string().describe("System message content"),providerOptions:aW}),Tb6=U.object({role:U.literal("user"),content:U.array(U.union([W51,Z51])).describe("User message content parts (text or file)"),providerOptions:aW}),Eb6=U.object({role:U.literal("assistant"),content:U.array(U.union([W51,Z51,Db6,Ob6,$51])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:aW}),jb6=U.object({role:U.literal("tool"),content:U.array($51).describe("Tool message content (tool results)"),providerOptions:aW}),Cb6=U.union([Ab6,Tb6,Eb6,jb6]),Ib6=U.array(Cb6).describe("A list of messages forming the prompt"),Rb6=U.object({prompt:Ib6.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:U.number().optional().describe("Maximum number of tokens to generate"),temperature:U.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:U.number().optional().describe("Nucleus sampling parameter"),topK:U.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:U.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:U.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:U.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:U.array(U.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:U.union([U.object({type:U.literal("text")}),U.object({type:U.literal("json"),schema:U.any().optional().describe("JSON schema that the generated output should conform to"),name:U.string().optional().describe("Name of output that should be generated"),description:U.string().optional().describe("Description of the output that should be generated")})]).optional().describe("Response format. The output can either be text or JSON. Default is text"),tools:U.array(U.any()).optional().describe("The tools that are available for the model"),toolChoice:U.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:U.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:U.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:U.any().optional().describe("Additional provider-specific options")}),Sb6=U.object({content:U.array(U.union([Ub6,Bb6,Nb6,Lb6,Mb6,Pb6])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:U.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:U.looseObject({inputTokens:U.number().optional(),outputTokens:U.number().optional(),totalTokens:U.number().optional(),reasoningTokens:U.number().optional()}).describe("Usage information for the language model call"),providerMetadata:U.any().optional().describe("Additional provider-specific metadata"),request:U.object({body:U.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:U.object({id:U.string().optional().describe("ID for the generated response"),timestamp:U.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:U.string().optional().describe("The ID of the response model that was used"),headers:U.record(U.string(),U.string()).optional().describe("Response headers"),body:U.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:U.array(U.any()).describe("Warnings for the call, e.g. unsupported settings")}),Md4=U.object({stream:U.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:U.object({body:U.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:U.object({headers:U.record(U.string(),U.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),kb6=U.object({supportedUrls:U.record(U.string(),U.array(U.string())).describe("Supported URL patterns by media type for the provider")}),Pd4=U.object({modelId:U.string().describe("The ID of the model"),logo:U.string().nullable(),description:U.string().nullable(),capabilities:U.array(U.string()),limits:U.object({contextWindow:U.number(),maxOutputTokens:U.number()}).nullable(),costs:U.object({input:U.number(),output:U.number()}).nullable(),provider:U.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),G51=U.object({modelId:U.string().describe("The ID of the model"),callOptions:Rb6}),vb6=JB.extend({logo:U.string().nullable(),description:U.string().nullable(),capabilities:U.array(U.string()),limits:U.object({contextWindow:U.number(),maxOutputTokens:U.number()}).nullable(),costs:U.object({input:U.number(),output:U.number()}).nullable(),provider:U.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),_b6=GB("llm",vb6,{readOnly:!0}),a80=[{name:"LLM_METADATA",inputSchema:U.object({modelId:U.string().describe("The ID of the model")}),outputSchema:kb6},{name:"LLM_DO_STREAM",inputSchema:G51,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:G51,outputSchema:Sb6},..._b6],Lb=NF(a80)});function bb6(X){let Y=[],Q=0;while(Q<X.length){let J=X[Q];if(J==="%")Y.push(".*");else if(J==="_")Y.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))Y.push("\\"+J);else Y.push(J);Q++}return Y.join("")}function VK(X){return typeof X==="string"||typeof X==="number"}function Mb(X,Y){if("conditions"in Y){let{operator:$,conditions:K}=Y;switch($){case"and":return K.every((H)=>Mb(X,H));case"or":return K.some((H)=>Mb(X,H));case"not":return!K.every((H)=>Mb(X,H));default:return!0}}let{field:Q,operator:J,value:G}=Y,W=Q.join("."),Z=r80(X,W);switch(J){case"eq":return Z===G;case"gt":return VK(Z)&&VK(G)&&Z>G;case"gte":return VK(Z)&&VK(G)&&Z>=G;case"lt":return VK(Z)&&VK(G)&&Z<G;case"lte":return VK(Z)&&VK(G)&&Z<=G;case"in":return Array.isArray(G)&&G.includes(Z);case"like":if(typeof Z!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let $=bb6(G);return new RegExp(`^${$}$`,"i").test(Z);case"contains":if(typeof Z!=="string"||typeof G!=="string")return!1;return Z.toLowerCase().includes(G.toLowerCase());default:return!0}}function r80(X,Y){let Q=Y.split("."),J=X;for(let G of Q){if(J==null||typeof J!=="object")return;J=J[G]}return J}function fb6(X,Y){return[...X].sort((Q,J)=>{for(let G of Y){let W=G.field.join("."),Z=r80(Q,W),$=r80(J,W),K=0;if(Z==null&&$==null)continue;if(Z==null)K=G.nulls==="first"?-1:1;else if($==null)K=G.nulls==="first"?1:-1;else if(typeof Z==="string"&&typeof $==="string")K=Z.localeCompare($);else if(typeof Z==="number"&&typeof $==="number")K=Z-$;else K=String(Z).localeCompare(String($));if(K!==0)return G.direction==="desc"?-K:K}return 0})}var yb6,hb6,xb6,o80;var K51=p(()=>{Ob();J51();x5();wb();a0();Z6();q7();yb6={LLM:a80,ASSISTANTS:Q51};hb6=OF.extend({binding:U.union([U.object({}).passthrough(),U.string()]).optional()}),xb6=LF(dJ),o80=t0({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",inputSchema:hb6,outputSchema:xb6,handler:async(X,Y)=>{await Y.access.check();let Q=_1(Y),J=X.binding?typeof X.binding==="string"?(()=>{let z=yb6[X.binding.toUpperCase()];if(!z)throw Error(`Unknown binding: ${X.binding}`);return z})():X.binding:void 0,G=J?Nb(J):void 0,Z=(await Y.storage.connections.list(Q.id)).filter((z)=>z.connection_type!=="VIRTUAL"),$=G?await Promise.all(Z.map(async(z)=>{if(!z.tools||z.tools.length===0)return null;return G.isImplementedBy(z.tools.map((N)=>({name:N.name,inputSchema:N.inputSchema,outputSchema:N.outputSchema})))?z:null})).then((z)=>z.filter((D)=>D!==null)):Z;if(X.where)$=$.filter((z)=>Mb(z,X.where));if(X.orderBy&&X.orderBy.length>0)$=fb6($,X.orderBy);let K=$.length,H=X.offset??0,F=X.limit??100,V=$.slice(H,H+F),q=H+F<K;return{items:V,totalCount:K,hasMore:q}}})});var gb6,s80;var H51=p(()=>{x5();Z6();q7();gb6=SP(dJ),s80=t0({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",inputSchema:RP,outputSchema:gb6,handler:async(X,Y)=>{let Q=_1(Y);await Y.access.check();let J=await Y.storage.connections.findById(X.id);if(!J||J.organization_id!==Q.id)return{item:null};return{item:J}}})});var Pb=(X,Y)=>{if(Y===null||Y===void 0)return;let Q=X.replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),J=Y;for(let G of Q){if(J===null||J===void 0||typeof J!=="object")return;J=J[G]}return J};function F51(X){let Y=X.split("::");if(Y.length!==2||!Y[0]||!Y[1])throw Error(`Invalid scope format: ${X}. Expected format: "KEY::SCOPE"`);return Y}function ub6(X){let Y=X.split("::");if(Y.length!==2||!Y[0]||!Y[1])return null;return Y}function mb6(X){if(typeof X==="object"&&X!==null&&"value"in X){let Y=X.value;if(typeof Y==="string")return Y}return null}function t80(X,Y){let Q={};if(!X||!Y)return Q;for(let J of Y){if(J==="*"){Q["*"]=["*"];continue}let G=ub6(J);if(!G)continue;let[W,Z]=G,$=Pb(W,X),K=mb6($);if(K){if(!Q[K])Q[K]=[];Q[K].push(Z)}}return Q}function V51(X,Y){let Q=t80(X,Y);return new Set(Object.keys(Q).filter((J)=>J!=="*"))}var e80=()=>{};class rW{db;vault;constructor(X,Y){this.db=X;this.vault=Y}async get(X){let Y=await this.db.selectFrom("downstream_tokens").selectAll().where("connectionId","=",X).executeTakeFirst();if(!Y)return null;return this.decryptToken(Y)}async upsert(X){let Y=new Date().toISOString(),Q=await this.vault.encrypt(X.accessToken),J=X.refreshToken?await this.vault.encrypt(X.refreshToken):null,G=X.clientSecret?await this.vault.encrypt(X.clientSecret):null;return await this.db.transaction().execute(async(W)=>{let Z=await W.selectFrom("downstream_tokens").select(["id","createdAt"]).where("connectionId","=",X.connectionId).executeTakeFirst();if(Z)return await W.updateTable("downstream_tokens").set({accessToken:Q,refreshToken:J,scope:X.scope,expiresAt:X.expiresAt?.toISOString()??null,clientId:X.clientId,clientSecret:G,tokenEndpoint:X.tokenEndpoint,updatedAt:Y}).where("id","=",Z.id).execute(),{id:Z.id,connectionId:X.connectionId,accessToken:X.accessToken,refreshToken:X.refreshToken,scope:X.scope,expiresAt:X.expiresAt,createdAt:Z.createdAt,updatedAt:Y,clientId:X.clientId,clientSecret:X.clientSecret,tokenEndpoint:X.tokenEndpoint};let $=t8("dtok");return await W.insertInto("downstream_tokens").values({id:$,connectionId:X.connectionId,accessToken:Q,refreshToken:J,scope:X.scope,expiresAt:X.expiresAt?.toISOString()??null,clientId:X.clientId,clientSecret:G,tokenEndpoint:X.tokenEndpoint,createdAt:Y,updatedAt:Y}).execute(),{id:$,connectionId:X.connectionId,accessToken:X.accessToken,refreshToken:X.refreshToken,scope:X.scope,expiresAt:X.expiresAt,createdAt:Y,updatedAt:Y,clientId:X.clientId,clientSecret:X.clientSecret,tokenEndpoint:X.tokenEndpoint}})}async delete(X){await this.db.deleteFrom("downstream_tokens").where("connectionId","=",X).execute()}isExpired(X,Y=0){if(!X.expiresAt)return!1;let J=(X.expiresAt instanceof Date?X.expiresAt:new Date(X.expiresAt)).getTime();if(Number.isNaN(J))return!0;return J-Y<Date.now()}async decryptToken(X){let Y=await this.vault.decrypt(X.accessToken),Q=X.refreshToken?await this.vault.decrypt(X.refreshToken):null,J=X.clientSecret?await this.vault.decrypt(X.clientSecret):null;return{id:X.id,connectionId:X.connectionId,accessToken:Y,refreshToken:Q,scope:X.scope,expiresAt:X.expiresAt,createdAt:X.createdAt,updatedAt:X.updatedAt,clientId:X.clientId,clientSecret:J,tokenEndpoint:X.tokenEndpoint}}}var Ab=p(()=>{cW()});async function pb6(X,Y,Q,J){for(let W of Y){if(W==="*")continue;let[Z]=F51(W),$=Pb(Z,X);if($===void 0||$===null)throw Error(`Scope references key "${Z}" but it's not present in state`)}let G=V51(X,Y);for(let W of G){if(W.endsWith("_self"))continue;let Z=await J.storage.connections.findById(W);if(!Z||Z.organization_id!==Q)throw Error(`Referenced connection not found: ${W}`);try{await J.access.check(W)}catch($){throw Error(`Access denied to referenced connection: ${W}. ${$.message}`)}}}var lb6,db6,XX0;var q51=p(()=>{e80();Ab();a0();Z6();Jb();q7();lb6=U.object({id:U.string().describe("ID of the connection to update"),data:q91.describe("Partial connection data to update")}),db6=U.object({item:dJ.describe("The updated connection entity")});XX0=t0({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update an existing MCP connection in the organization",inputSchema:lb6,outputSchema:db6,handler:async(X,Y)=>{U1(Y);let Q=_1(Y);if(await Y.access.check(),!f8(Y))throw Error("User ID required to update connection");let{id:G,data:W}=X,Z=await Y.storage.connections.findById(G);if(!Z||Z.organization_id!==Q.id)throw Error("Connection not found in organization");let $=W.connection_type??Z.connection_type,K=W.connection_url??Z.connection_url;if($==="VIRTUAL"){let L=$K(K);if(!L)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let w=await Y.storage.virtualMcps.findById(L);if(!w)throw Error(`Virtual MCP not found: ${L}`);if(w.organization_id!==Q.id)throw Error("Virtual MCP does not belong to the current organization");K=sy(L)}let H=W.configuration_state??Z.configuration_state,F=W.configuration_scopes??Z.configuration_scopes??[];if(W.configuration_state!==void 0||W.configuration_scopes!==void 0){if(W.configuration_state!==void 0)H=W.configuration_state;else if(H===null)H={};if(W.configuration_scopes!==void 0)F=W.configuration_scopes??[];if(F.length>0&&H)await pb6(H,F,Q.id,Y)}let V=W.connection_token??Z.connection_token;if(!V)try{let w=await new rW(Y.db,Y.vault).get(G);if(w?.accessToken)V=w.accessToken}catch{}let q=await rz({id:Z.id,title:W.title??Z.title,connection_type:$,connection_url:K,connection_token:V,connection_headers:W.connection_headers??Z.connection_headers}).catch(()=>null),z=q?.length?q:null,D={...W,connection_url:K,tools:z,configuration_state:H,configuration_scopes:F},N=await Y.storage.connections.update(G,D);if((W.configuration_state!==void 0||W.configuration_scopes!==void 0)&&H&&F.length>0)try{await(await Y.createMCPProxy(G)).client.callTool({name:"ON_MCP_CONFIGURATION",arguments:{state:H,scopes:F}})}catch(L){console.error("Failed to invoke ON_MCP_CONFIGURATION callback",L)}return{item:N}}})});var YX0;var U51=p(()=>{x5();Z6();q7();YX0=t0({name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete a connection",inputSchema:kP,outputSchema:vP(dJ),handler:async(X,Y)=>{U1(Y);let Q=_1(Y);await Y.access.check();let J=await Y.storage.connections.findById(X.id);if(!J)throw Error(`Connection not found: ${X.id}`);if(J.organization_id!==Q.id)throw Error("Connection not found in organization");return await Y.storage.connections.delete(X.id),{item:J}}})});var QX0;var z51=p(()=>{a0();Z6();QX0=t0({name:"CONNECTION_TEST",description:"Test connection health and latency",inputSchema:U.object({id:U.string()}),outputSchema:U.object({id:U.string(),healthy:U.boolean(),latencyMs:U.number()}),handler:async(X,Y)=>{let Q=_1(Y);await Y.access.check();let J=await Y.storage.connections.findById(X.id);if(!J||J.organization_id!==Q.id)throw Error("Connection not found");let G=await Y.storage.connections.testConnection(X.id);return{id:X.id,...G}}})});var B51=p(()=>{SJ1();K51();H51();q51();U51();z51()});import{sql as e6}from"kysely";function D51(X){if(X===null||X===void 0)return"NULL";if(typeof X==="number")return String(X);if(typeof X==="boolean")return X?"TRUE":"FALSE";if(typeof X==="string")return`'${X.replace(/'/g,"''")}'`;if(X instanceof Date)return`'${X.toISOString()}'`;return`'${JSON.stringify(X).replace(/'/g,"''")}'`}function ib6(X,Y){let Q=X;for(let G=Y.length;G>=1;G--){let W=`$${G}`;if(Q.includes(W))Q=Q.replaceAll(W,D51(Y[G-1]))}let J=[];for(let G=0;G<Q.length;G++)if(Q[G]==="?")J.push(G);for(let G=Math.min(J.length,Y.length)-1;G>=0;G--){let W=J[G],Z=D51(Y[G]);Q=Q.slice(0,W)+Z+Q.slice(W+1)}return Q}function N51(X){return X.replace(/-/g,"_")}function rb6(X){return`app_${N51(X)}`}function ob6(X){return`app_role_${N51(X)}`}function sb6(X){if(X instanceof Error){let Y=X.message.toLowerCase(),Q=X.code;return Q==="3F000"||Q==="42704"||Y.includes("schema")&&Y.includes("does not exist")||Y.includes("role")&&Y.includes("does not exist")}return!1}async function tb6(X,Y,Q){if(await e6`CREATE SCHEMA IF NOT EXISTS ${e6.id(Y)}`.execute(X),!(await e6`
270
+ ${Y.stack}`;return G}}catch{}if(typeof Y.toString==="function")try{let G=Y.toString();if(G!=="[object Object]")return G}catch{}let J=Object.keys(Y);if(J.length>0)return`Object with keys: ${J.join(", ")}`;return"[object Object]"}if(typeof X==="string")return X;if(typeof X==="number"||typeof X==="boolean")return String(X);if(typeof X==="function")return`[Function: ${X.name||"anon"}]`;if(typeof X==="symbol")return X.toString();if(typeof X==="bigint")return X.toString();try{return String(X)}catch{return"Unknown value (could not convert to string)"}}function XB(X,Y){switch(typeof Y){case"string":return X.newString(Y);case"number":return X.newNumber(Y);case"boolean":return Y?X.true:X.false;case"undefined":return X.undefined;case"object":{if(Y===null)return X.null;if(Array.isArray(Y)){let J=X.newArray();return Y.forEach((G,W)=>{let Z=XB(X,G);try{X.setProp(J,String(W),Z)}finally{Z.dispose?.()}}),J}let Q=X.newObject();for(let[J,G]of Object.entries(Y)){let W=XB(X,G);try{X.setProp(Q,J,W)}finally{W.dispose?.()}}return Q}case"function":{let Q=`__hostFn_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return X.newFunction(Q,(...G)=>{try{let W=G.map(($)=>X.dump($)),Z=Y(...W);if(Z&&typeof Z.then==="function"){let $=X.newPromise();return Z.then((K)=>{try{let H=XB(X,K);$.resolve(H),H.dispose(),X.runtime.executePendingJobs()}catch(H){let F=ez(H),V=X.newString(`Promise resolution error: ${F}`);$.reject(V),V.dispose(),X.runtime.executePendingJobs()}}).catch((K)=>{let H=ez(K),F=X.newString(`Promise rejection: ${H}`);$.reject(F),F.dispose(),X.runtime.executePendingJobs()}),$.handle}return XB(X,Z)}catch(W){let Z=ez(W);return X.newString(`HostFunctionError: ${Z}`)}finally{G.forEach((W)=>W.dispose())}})}case"bigint":return X.newString(Y.toString());case"symbol":return X.newString(Y.toString());default:try{return X.newString(String(Y))}catch{return X.undefined}}}var wJ1=()=>{};function PJ1(X){let Y=X.runtime.executePendingJobs(100);try{if("unwrap"in Y&&typeof Y.unwrap==="function")Y.unwrap()}finally{if("dispose"in Y&&typeof Y.dispose==="function")Y.dispose()}}async function MJ1(X,Y,Q){let J=Date.now(),G=X.resolvePromise(Y);while(!0){PJ1(X);let W=await Promise.race([G,Zy6(0).then(()=>null)]);if(W!==null)return W;if(Date.now()-J>Q)throw Error(`Timed out after ${Q}ms while awaiting a QuickJS promise`)}}async function g80({tools:X,code:Y,timeoutMs:Q}){let Z=[];try{let J=await OJ1({memoryLimitBytes:33554432,stackSizeBytes:524288});const G=Zf(Z,J.newContext({interruptAfterMs:Q}),0);const W=Zf(Z,cQ1(G),0);try{let F=G.evalCode(Y,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),q=XB(G,X);G.setProp(G.global,"tools",q);let z=G.runtime.hasPendingJob()?G.unwrapResult(await MJ1(G,V,Q)):V;if(z!==V)V.dispose();let D=G.getProp(z,"default"),N=G.typeof(D);if(N!=="function")return{error:`Code must export default a function (tools). Got ${N}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:W.logs};let L=G.callFunction(D,G.undefined,q),w=G.unwrapResult(L),C=await MJ1(G,w,Q),T=G.unwrapResult(C);if(G.runtime.hasPendingJob())PJ1(G);return{returnValue:G.dump(T),consoleLogs:W.logs}}catch(F){return console.log(F),{error:ez(F),consoleLogs:W.logs}}}catch($){var K=$,H=1}finally{oY0(Z,K,H)}}var Zy6=(X)=>new Promise((Y)=>setTimeout(Y,X));var AJ1=p(()=>{LJ1();wJ1()});var TJ1=p(()=>{AJ1()});async function $y6(X,Y){let Q;if(X.tool_selection_mode==="exclusion"){let G=(await Y.storage.connections.list(X.organization_id)).filter((Z)=>Z.status==="active"),W=new Map;for(let Z of X.connections)W.set(Z.connection_id,{selectedTools:Z.selected_tools,selectedResources:Z.selected_resources,selectedPrompts:Z.selected_prompts});Q=[];for(let Z of G){let $=W.get(Z.id);if($===void 0)Q.push({connection:Z,selectedTools:null,selectedResources:null,selectedPrompts:null});else if(($.selectedTools===null||$.selectedTools.length===0)&&($.selectedResources===null||$.selectedResources.length===0)&&($.selectedPrompts===null||$.selectedPrompts.length===0));else Q.push({connection:Z,selectedTools:$.selectedTools,selectedResources:$.selectedResources,selectedPrompts:$.selectedPrompts})}}else{let J=X.connections.map((W)=>W.connection_id),G=[];for(let W of J){let Z=await Y.storage.connections.findById(W);if(Z&&Z.status==="active")G.push(Z)}Q=G.map((W)=>{let Z=X.connections.find(($)=>$.connection_id===W.id);return{connection:W,selectedTools:Z?.selected_tools??null,selectedResources:Z?.selected_resources??null,selectedPrompts:Z?.selected_prompts??null}})}return Q}async function EJ1(X,Y){return(await Y.storage.connections.list(X)).filter((J)=>J.status==="active").map((J)=>({connection:J,selectedTools:null,selectedResources:null,selectedPrompts:null}))}async function Ky6(X,Y,Q){let J=await sz.create(X,Q),G=await J.mapSettled(async(F,V)=>{try{let z=(await F.proxy.client.listTools()).tools;if(Y==="exclusion"){if(F.selectedTools&&F.selectedTools.length>0){let D=new Set(F.selectedTools);z=z.filter((N)=>!D.has(N.name))}}else if(F.selectedTools&&F.selectedTools.length>0){let D=new Set(F.selectedTools);z=z.filter((N)=>D.has(N.name))}return{connectionId:V,connectionTitle:F.connection.title,tools:z}}catch(q){return console.error(`[code-execution] Failed to list tools for connection ${V}:`,q),null}}),W=new Set,Z=[],$=new Map,K=new Set;for(let F of G){if(F.status!=="fulfilled"||!F.value)continue;let{connectionId:V,connectionTitle:q,tools:z}=F.value;K.add(q);for(let D of z){if(W.has(D.name))continue;W.add(D.name),Z.push({...D,_meta:{connectionId:V,connectionTitle:q}}),$.set(D.name,{connectionId:V,originalName:D.name})}}return{tools:Z,callTool:async(F,V)=>{let q=$.get(F);if(!q)return{content:[{type:"text",text:`Tool not found: ${F}`}],isError:!0};let z=J.get(q.connectionId);if(!z)return{content:[{type:"text",text:`Connection not found for tool: ${F}`}],isError:!0};return await z.proxy.client.callTool({name:q.originalName,arguments:V})},categories:Array.from(K).sort()}}async function YB(X){let Y=_1(X),Q,J="inclusion";if(X.connectionId){let G=await X.storage.virtualMcps.findById(X.connectionId);if(G)Q=await $y6(G,X),J=G.tool_selection_mode;else Q=await EJ1(Y.id,X)}else Q=await EJ1(Y.id,X);return Ky6(Q,J,X)}function Hy6(X){return X.toLowerCase().split(/[\s_\-./]+/).filter((Y)=>Y.length>=2)}function Fy6(X,Y){let Q=0,J=Y.name.toLowerCase(),G=(Y.description??"").toLowerCase(),W=Y._meta.connectionTitle.toLowerCase();for(let Z of X){if(J===Z)Q+=10;else if(J.includes(Z))Q+=3;if(G.includes(Z))Q+=2;if(W.includes(Z))Q+=1}return Q}function Fb(X,Y,Q){let J=Hy6(X);if(J.length===0)return Y.slice(0,Q);return Y.map((G)=>({tool:G,score:Fy6(J,G)})).filter((G)=>G.score>0).sort((G,W)=>W.score-G.score).slice(0,Q).map((G)=>G.tool)}function Vb(X,Y){let Q=new Map(Y.map((G)=>[G.name,G]));return{tools:X.map((G)=>Q.get(G)).filter((G)=>G!==void 0).map((G)=>({name:G.name,description:G.description,connection:G._meta.connectionTitle,inputSchema:G.inputSchema,outputSchema:G.outputSchema})),notFound:X.filter((G)=>!Q.has(G))}}async function qb(X,Y,Q){let J=Object.fromEntries(Y.tools.map((G)=>[G.name,async(W)=>Y.callTool(G.name,W??{})]));return g80({code:X,tools:J,timeoutMs:Q})}function Ub(X){return{content:[{type:"text",text:JSON.stringify(X,null,2)}]}}function QB(X){return{content:[{type:"text",text:JSON.stringify(X,null,2)}],isError:!0}}function EP(X){let Y=new Set(Vy6);return X.filter((Q)=>!Y.has(Q.name))}var Vy6;var jP=p(()=>{TJ1();Vy6=["CODE_EXECUTION_SEARCH_TOOLS","CODE_EXECUTION_DESCRIBE_TOOLS","CODE_EXECUTION_RUN_CODE"]});var u80;var jJ1=p(()=>{Z6();AP();jP();u80=t0({name:"CODE_EXECUTION_SEARCH_TOOLS",description:"Search for available tools by name or description. Returns tool names and brief descriptions without full schemas. Use this to discover tools before calling CODE_EXECUTION_DESCRIBE_TOOLS for detailed schemas.",inputSchema:gQ1,outputSchema:uQ1,handler:async(X,Y)=>{U1(Y),_1(Y),await Y.access.check();let Q=await YB(Y),J=Fb(X.query,Q.tools,X.limit);return{query:X.query,results:J.map((G)=>({name:G.name,description:G.description,connection:G._meta.connectionTitle})),totalAvailable:Q.tools.length}}})});var m80;var CJ1=p(()=>{Z6();AP();jP();m80=t0({name:"CODE_EXECUTION_DESCRIBE_TOOLS",description:"Get detailed schemas for specific tools. Call after CODE_EXECUTION_SEARCH_TOOLS to get full input/output schemas before executing code.",inputSchema:mQ1,outputSchema:lQ1,handler:async(X,Y)=>{U1(Y),_1(Y),await Y.access.check();let Q=await YB(Y);return Vb(X.tools,Q.tools)}})});var l80;var IJ1=p(()=>{Z6();AP();jP();l80=t0({name:"CODE_EXECUTION_RUN_CODE",description:'Run JavaScript code in a sandbox. Code must be an ES module that `export default`s an async function that receives (tools) as its first parameter. Use CODE_EXECUTION_DESCRIBE_TOOLS to understand the input/output schemas for a tool before calling it. Use `await tools.toolName(args)` or `await tools["tool-name"](args)` to call tools.',inputSchema:dQ1,outputSchema:pQ1,handler:async(X,Y)=>{U1(Y),_1(Y),await Y.access.check();let Q=await YB(Y);return await qb(X.code,Q,X.timeoutMs)}})});var RJ1=p(()=>{jJ1();CJ1();IJ1();AP()});var Uy6,zy6,d80;var SJ1=p(()=>{gL();a0();Z6();Jb();q7();Uy6=U.object({data:V91.describe("Data for the new connection (id is auto-generated if not provided)")}),zy6=U.object({item:dJ.describe("The created connection entity")}),d80=t0({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",inputSchema:Uy6,outputSchema:zy6,handler:async(X,Y)=>{U1(Y);let Q=_1(Y);await Y.access.check();let J=f8(Y);if(!J)throw Error("User ID required to create connection");let G={...X.data,organization_id:Q.id,created_by:J};if(G.connection_type==="VIRTUAL"){let K=$K(G.connection_url);if(!K)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let H=await Y.storage.virtualMcps.findById(K);if(!H)throw Error(`Virtual MCP not found: ${K}`);if(H.organization_id!==Q.id)throw Error("Virtual MCP does not belong to the current organization");G.connection_url=sy(K)}let W=await rz({id:`pending-${Date.now()}`,title:G.title,connection_type:G.connection_type,connection_url:G.connection_url,connection_token:G.connection_token,connection_headers:G.connection_headers}).catch(()=>null),Z=W?.length?W:null,$=await Y.storage.connections.create({...G,tools:Z});return await Y.eventBus.publish(Q.id,ZW.SELF(Q.id),{type:"connection.created",data:$}),{item:$}}})});function CP(X,Y){if(X===Y)return!0;if(X==null||Y==null)return X===Y;if(typeof X!==typeof Y)return!1;if(Array.isArray(X)&&Array.isArray(Y)){if(X.length!==Y.length)return!1;return X.every((Q,J)=>CP(Q,Y[J]))}if(typeof X==="object"&&typeof Y==="object"){let Q=Object.keys(X),J=Object.keys(Y);if(Q.length!==J.length)return!1;return Q.every((G)=>J.includes(G)&&CP(X[G],Y[G]))}return!1}function hy6(){return(X)=>{if(!Array.isArray(X))return!0;let Y=[];return X.every((Q)=>{if(Y.some((G)=>CP(Q,G)))return!1;return Y.push(Q),!0})}}function zb(X,Y){return X.safeParse(Y).success}function MY(X){if(typeof X==="boolean")return X?U.any():U.never();let Y={};for(let G of sy6)G.apply(Y,X);let Q=[];if(Y.string!==!1)Q.push(Y.string||U.string());if(Y.number!==!1)Q.push(Y.number||U.number());if(Y.boolean!==!1)Q.push(Y.boolean||U.boolean());if(Y.null!==!1)Q.push(Y.null||U.null());if(Y.array!==!1)Q.push(Y.array||U.array(U.any()));if(Y.tuple!==!1&&Y.tuple!==void 0)Q.push(Y.tuple);if(Y.object!==!1)if(Y.object)Q.push(Y.object);else{let G=U.custom((W)=>{return typeof W==="object"&&W!==null&&!Array.isArray(W)},"Must be an object, not an array");Q.push(G)}if(Y.file!==!1&&Y.file!==void 0)Q.push(Y.file);let J;if(Q.length===0)J=U.never();else if(Q.length===1)J=Q[0];else if(!Object.keys(X).some((W)=>W!=="$schema"&&W!=="title"&&W!=="description"))J=U.any();else J=U.union(Q);for(let G of ty6)J=G.apply(J,X);return J}var By6=class{apply(X,Y){if(!Y.type)return;let Q=Array.isArray(Y.type)?Y.type:[Y.type],J=new Set(Q);if(!J.has("string"))X.string=!1;if(!J.has("number")&&!J.has("integer"))X.number=!1;if(!J.has("boolean"))X.boolean=!1;if(!J.has("null"))X.null=!1;if(!J.has("array"))X.array=!1;if(!J.has("object"))X.object=!1;if(J.has("integer")&&X.number!==!1){let G=X.number||U.number();if(G instanceof U.ZodNumber)X.number=G.int()}}},Dy6=class{apply(X,Y){if(Y.const===void 0)return;let Q=Y.const;if(X.string=!1,X.number=!1,X.boolean=!1,X.null=!1,X.array=!1,X.object=!1,typeof Q==="string")X.string=U.literal(Q);else if(typeof Q==="number")X.number=U.literal(Q);else if(typeof Q==="boolean")X.boolean=U.literal(Q);else if(Q===null)X.null=U.null();else if(Array.isArray(Q))X.array=void 0;else if(typeof Q==="object")X.object=void 0}},Ny6=class{apply(X,Y){if(!Y.enum)return;if(Y.enum.length===0){if(!Y.type)X.string=!1,X.number=!1,X.boolean=!1,X.null=!1,X.array=!1,X.object=!1;return}let Q={string:Y.enum.filter((J)=>typeof J==="string"),number:Y.enum.filter((J)=>typeof J==="number"),boolean:Y.enum.filter((J)=>typeof J==="boolean"),null:Y.enum.filter((J)=>J===null),array:Y.enum.filter((J)=>Array.isArray(J)),object:Y.enum.filter((J)=>typeof J==="object"&&J!==null&&!Array.isArray(J))};X.string=this.createTypeSchema(Q.string,"string"),X.number=this.createTypeSchema(Q.number,"number"),X.boolean=this.createTypeSchema(Q.boolean,"boolean"),X.null=Q.null.length>0?U.null():!1,X.array=Q.array.length>0?void 0:!1,X.object=Q.object.length>0?void 0:!1}createTypeSchema(X,Y){if(X.length===0)return!1;if(X.length===1)return U.literal(X[0]);if(Y==="string")return U.enum(X);if(Y==="number"){let[Q,J,...G]=X;return U.union([U.literal(Q),U.literal(J),...G.map((W)=>U.literal(W))])}if(Y==="boolean")return U.union([U.literal(!0),U.literal(!1)]);return!1}},Oy6=class{apply(X,Y){let Q=Y;if(Q.type==="string"&&Q.format==="binary"&&Q.contentEncoding==="binary"){let J=U.file();if(Q.minLength!==void 0)J=J.min(Q.minLength);if(Q.maxLength!==void 0)J=J.max(Q.maxLength);if(Q.contentMediaType!==void 0)J=J.mime(Q.contentMediaType);X.file=J,X.string=!1}}},Ly6=class{apply(X,Y){let Q=Y;if(Y.type===void 0&&(Q.minLength!==void 0||Q.maxLength!==void 0||Q.pattern!==void 0)){if(X.string===void 0)X.string=U.string()}}},wy6=class{apply(X,Y){let Q=Y;if(Q.minLength===void 0)return;if(X.string!==!1){let J=X.string||U.string();if(J instanceof U.ZodString)X.string=J.refine((G)=>{return Array.from(G).length>=Q.minLength},{message:`String must be at least ${Q.minLength} characters long`})}}},My6=class{apply(X,Y){let Q=Y;if(Q.maxLength===void 0)return;if(X.string!==!1){let J=X.string||U.string();if(J instanceof U.ZodString)X.string=J.refine((G)=>{return Array.from(G).length<=Q.maxLength},{message:`String must be at most ${Q.maxLength} characters long`})}}},Py6=class{apply(X,Y){let Q=Y;if(!Q.pattern)return;if(X.string!==!1){let J=X.string||U.string();if(J instanceof U.ZodString){let G=new RegExp(Q.pattern);X.string=J.regex(G)}}}},Ay6=class{apply(X,Y){let Q=Y;if(Q.minimum===void 0)return;if(X.number!==!1){let J=X.number||U.number();if(J instanceof U.ZodNumber)X.number=J.min(Q.minimum)}}},Ty6=class{apply(X,Y){let Q=Y;if(Q.maximum===void 0)return;if(X.number!==!1){let J=X.number||U.number();if(J instanceof U.ZodNumber)X.number=J.max(Q.maximum)}}},Ey6=class{apply(X,Y){let Q=Y;if(Q.exclusiveMinimum===void 0)return;if(X.number!==!1){let J=X.number||U.number();if(J instanceof U.ZodNumber)if(typeof Q.exclusiveMinimum==="number")X.number=J.gt(Q.exclusiveMinimum);else X.number=!1}}},jy6=class{apply(X,Y){let Q=Y;if(Q.exclusiveMaximum===void 0)return;if(X.number!==!1){let J=X.number||U.number();if(J instanceof U.ZodNumber)if(typeof Q.exclusiveMaximum==="number")X.number=J.lt(Q.exclusiveMaximum);else X.number=!1}}},Cy6=class{apply(X,Y){let Q=Y;if(Q.multipleOf===void 0)return;if(X.number!==!1){let J=X.number||U.number();if(J instanceof U.ZodNumber)X.number=J.refine((G)=>{if(Q.multipleOf===0)return!1;let W=G/Q.multipleOf,Z=Math.round(W),$=Math.min(Math.abs(G)*Number.EPSILON*10,Math.abs(Q.multipleOf)*Number.EPSILON*10);return Math.abs(W-Z)<=$/Math.abs(Q.multipleOf)},{message:`Must be a multiple of ${Q.multipleOf}`})}}},Iy6=class{apply(X,Y){let Q=Y;if(Y.type===void 0&&(Q.minItems!==void 0||Q.maxItems!==void 0||Q.items!==void 0||Q.prefixItems!==void 0)){if(X.array===void 0)X.array=U.array(U.any())}}},Ry6=class{apply(X,Y){let Q=Y;if(Q.minItems===void 0)return;if(X.array!==!1)X.array=(X.array||U.array(U.any())).min(Q.minItems)}},Sy6=class{apply(X,Y){let Q=Y;if(Q.maxItems===void 0)return;if(X.array!==!1)X.array=(X.array||U.array(U.any())).max(Q.maxItems)}},ky6=class{apply(X,Y){let Q=Y;if(X.array===!1)return;if(Array.isArray(Q.items))X.array=X.array||U.array(U.any());else if(Q.items&&typeof Q.items!=="boolean"&&!Q.prefixItems){let J=MY(Q.items),G=U.array(J);if(X.array&&X.array instanceof U.ZodArray){let W=X.array._def;if(W.checks)W.checks.forEach((Z)=>{if(Z._zod&&Z._zod.def){let $=Z._zod.def;if($.check==="min_length"&&$.minimum!==void 0)G=G.min($.minimum);else if($.check==="max_length"&&$.maximum!==void 0)G=G.max($.maximum)}})}X.array=G}else if(typeof Q.items==="boolean"&&Q.items===!1)if(!Q.prefixItems)X.array=U.array(U.any()).max(0);else X.array=X.array||U.array(U.any());else if(typeof Q.items==="boolean"&&Q.items===!0)X.array=X.array||U.array(U.any());else if(Q.prefixItems)X.array=X.array||U.array(U.any())}},vy6=class{apply(X,Y){if(Y.type!=="array")return;let Q=Y;if(!Array.isArray(Q.items))return;if(X.array===!1)return;let J=Q.items.map((W)=>MY(W)),G;if(J.length===0)G=U.tuple([]);else G=U.tuple(J);if(Q.minItems!==void 0&&Q.minItems>J.length)G=!1;if(Q.maxItems!==void 0&&Q.maxItems<J.length)G=!1;X.tuple=G,X.array=!1}},_y6=class{apply(X,Y){let Q=Y;if(X.object===!1)return;if(Q.properties||Q.required||Q.additionalProperties!==void 0)X.object=X.object||U.object({}).passthrough()}},yy6=class{apply(X,Y){let Q=Y;if(Y.type===void 0&&(Q.maxProperties!==void 0||Q.minProperties!==void 0)){if(X.object===void 0)X.object=U.object({}).passthrough()}}},by6=class{apply(X,Y){let Q=Y;if(Q.maxProperties===void 0)return;if(X.object!==!1){let J=X.object||U.object({}).passthrough();X.object=J.refine((G)=>Object.keys(G).length<=Q.maxProperties,{message:`Object must have at most ${Q.maxProperties} properties`})}}},fy6=class{apply(X,Y){let Q=Y;if(Q.minProperties===void 0)return;if(X.object!==!1){let J=X.object||U.object({}).passthrough();X.object=J.refine((G)=>Object.keys(G).length>=Q.minProperties,{message:`Object must have at least ${Q.minProperties} properties`})}}},xy6=class{apply(X,Y){if(!Y.not)return X;let Q=MY(Y.not);return X.refine((J)=>!zb(Q,J),{message:"Value must not match the 'not' schema"})}},gy6=class{apply(X,Y){if(Y.uniqueItems!==!0)return X;return X.refine(hy6(),{message:"Array items must be unique"})}},uy6=class{apply(X,Y){if(!Y.allOf||Y.allOf.length===0)return X;return Y.allOf.map((J)=>MY(J)).reduce((J,G)=>U.intersection(J,G),X)}},my6=class{apply(X,Y){if(!Y.anyOf||Y.anyOf.length===0)return X;let Q=Y.anyOf.length===1?MY(Y.anyOf[0]):U.union([MY(Y.anyOf[0]),MY(Y.anyOf[1]),...Y.anyOf.slice(2).map((J)=>MY(J))]);return U.intersection(X,Q)}},ly6=class{apply(X,Y){if(!Y.oneOf||Y.oneOf.length===0)return X;let Q=Y.oneOf.map((J)=>MY(J));return X.refine((J)=>{let G=0;for(let W of Q)if(W.safeParse(J).success){if(G++,G>1)return!1}return G===1},{message:"Value must match exactly one of the oneOf schemas"})}},dy6=class{apply(X,Y){let Q=Y;if(Q.prefixItems&&Array.isArray(Q.prefixItems)){let G=Q.prefixItems.map((W)=>MY(W));return X.refine((W)=>{if(!Array.isArray(W))return!0;for(let Z=0;Z<Math.min(W.length,G.length);Z++)if(!zb(G[Z],W[Z]))return!1;if(W.length>G.length){if(typeof Q.items==="boolean"&&Q.items===!1)return!1;else if(Q.items&&typeof Q.items==="object"&&!Array.isArray(Q.items)){let Z=MY(Q.items);for(let $=G.length;$<W.length;$++)if(!zb(Z,W[$]))return!1}}return!0},{message:"Array does not match prefixItems schema"})}return X}},py6=class{apply(X,Y){let Q=Y;if(!Q.properties&&!Q.required&&Q.additionalProperties!==!1)return X;if(X instanceof U.ZodObject||X instanceof U.ZodRecord){let J={};if(Q.properties){for(let[G,W]of Object.entries(Q.properties))if(W!==void 0)J[G]=MY(W)}if(Q.required&&Array.isArray(Q.required)){let G=new Set(Q.required);for(let W of Object.keys(J))if(!G.has(W))J[W]=J[W].optional()}else for(let G of Object.keys(J))J[G]=J[G].optional();if(Q.additionalProperties===!1)return U.object(J);else return U.object(J).passthrough()}return X.refine((J)=>{if(typeof J!=="object"||J===null||Array.isArray(J))return!0;if(Q.properties){for(let[G,W]of Object.entries(Q.properties))if(W!==void 0){if(Object.getOwnPropertyDescriptor(J,G)!==void 0){if(!MY(W).safeParse(J[G]).success)return!1}}}if(Q.required&&Array.isArray(Q.required)){for(let G of Q.required)if(Object.getOwnPropertyDescriptor(J,G)===void 0)return!1}if(Q.additionalProperties===!1&&Q.properties){let G=new Set(Object.keys(Q.properties));for(let W in J)if(!G.has(W))return!1}return!0},{message:"Object constraints validation failed"})}},cy6=class{apply(X,Y){if(!Y.enum||Y.enum.length===0)return X;let Q=Y.enum.filter((J)=>Array.isArray(J)||typeof J==="object"&&J!==null);if(Q.length===0)return X;return X.refine((J)=>{if(typeof J!=="object"||J===null)return!0;return Q.some((G)=>CP(J,G))},{message:"Value must match one of the enum values"})}},ny6=class{apply(X,Y){if(Y.const===void 0)return X;let Q=Y.const;if(typeof Q!=="object"||Q===null)return X;return X.refine((J)=>CP(J,Q),{message:"Value must equal the const value"})}},iy6=class{apply(X,Y){if(Y.description)X=X.describe(Y.description);return X}},ay6=class{apply(X,Y){var Q;let J=Y;if(!((Q=J.required)==null?void 0:Q.includes("__proto__"))||Y.type!==void 0)return X;return U.any().refine((G)=>this.validateRequired(G,J.required),{message:"Missing required properties"})}validateRequired(X,Y){if(typeof X!=="object"||X===null||Array.isArray(X))return!0;return Y.every((Q)=>Object.prototype.hasOwnProperty.call(X,Q))}},ry6=class{apply(X,Y){var Q;let J=Y;if(J.contains===void 0)return X;let G=MY(J.contains),W=(Q=J.minContains)!=null?Q:1,Z=J.maxContains;return X.refine(($)=>{if(!Array.isArray($))return!0;let K=0;for(let H of $)if(zb(G,H))K++;if(K<W)return!1;if(Z!==void 0&&K>Z)return!1;return!0},{message:"Array must contain required items matching the schema"})}},oy6=class{apply(X,Y){let{default:Q}=Y;if(Q===void 0)return X;if(!X.safeParse(Q).success)return X;return X.default(Q)}},sy6,ty6;var kJ1=p(()=>{c6();c6();c6();c6();c6();c6();c6();c6();c6();c6();c6();c6();c6();c6();sy6=[new Dy6,new Ny6,new By6,new Oy6,new Ly6,new Iy6,new yy6,new wy6,new My6,new Py6,new Ay6,new Ty6,new Ey6,new jy6,new Cy6,new vy6,new Ry6,new Sy6,new ky6,new by6,new fy6,new _y6],ty6=[new ay6,new cy6,new ny6,new uy6,new my6,new ly6,new dy6,new py6,new ry6,new xy6,new gy6,new oy6,new iy6]});class p80{constructor(X){this._url=X}start(){if(this._socket)throw Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((X,Y)=>{this._socket=new WebSocket(this._url,ey6),this._socket.onerror=(Q)=>{let J="error"in Q?Q.error:Error(`WebSocket error: ${JSON.stringify(Q)}`);Y(J),this.onerror?.(J)},this._socket.onopen=()=>{X()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=(Q)=>{let J;try{J=PQ.parse(JSON.parse(Q.data))}catch(G){this.onerror?.(G);return}this.onmessage?.(J)}})}async close(){this._socket?.close()}send(X){return new Promise((Y,Q)=>{if(!this._socket){Q(Error("Not connected"));return}this._socket?.send(JSON.stringify(X)),Y()})}}var ey6="mcp";var vJ1=p(()=>{qX()});function Xb6(X){let Y=X;if(!Y||typeof Y!=="object"||!("method"in Y))return null;switch(Y.method){case"initialize":{let Q=Y?.params?.protocolVersion;if(!Q)return null;return{type:"emit",message:{result:{protocolVersion:Q,capabilities:{tools:{}},serverInfo:{name:"deco-chat-server",version:"1.0.0"}},jsonrpc:Y.jsonrpc??"2.0",id:Y.id}}}case"notifications/roots/list_changed":case"notifications/initialized":case"notifications/cancelled":case"notifications/progress":return{type:"suppress"};default:return null}}var c80;var _J1=p(()=>{oq();c80=class c80 extends IG{constructor(X,Y){super(X,Y)}send(X,Y){let Q=Xb6(X);if(Q?.type==="emit")return this.onmessage?.(Q.message),Promise.resolve();if(Q?.type==="suppress")return Promise.resolve();return super.send(X,Y)}}});var yJ1,bJ1=async(X,Y,Q)=>{let J=Yb6(X.connection,Y,Q);if(!J)throw Error("Unknown MCP connection type");let G=new yJ1({name:X?.name??"MCP Client",version:"1.0.0"});return await G.connect(J),{client:G,callStreamableTool:(W,Z,$)=>{if(X.connection.type!=="HTTP")throw Error("HTTP connection required");let K=new Headers(Q);if(!K.has("Authorization"))K.set("Authorization",`Bearer ${X.connection.token}`);for(let[V,q]of Object.entries(X.connection.headers??{}))K.set(V,q);let H=new URL(X.connection.url),F=H.pathname.replace(/\/+$/,"")||"/";return H.pathname=`${F}/call-tool/${encodeURIComponent(W)}`,fetch(H.href,{method:"POST",redirect:"manual",body:JSON.stringify(Z),headers:K,signal:$})}}},Yb6=(X,Y,Q)=>{if(X.type==="Websocket")return new p80(new URL(X.url));if(X.type!=="SSE"&&X.type!=="HTTP")return null;let G={...X.token?{authorization:`Bearer ${X.token}`}:{},...Q??{},..."headers"in X?X.headers||{}:{}};if(X.type==="SSE"){let W={requestInit:{headers:G,signal:Y}};if(X.token)W.eventSourceInit={fetch:(Z,$)=>{return fetch(Z,{...$,headers:{...G,Accept:"text/event-stream"},signal:Y})}};return new VF(new URL(X.url),W)}return new c80(new URL(X.url),{requestInit:{headers:G,signal:Y,credentials:"include"}})};var fJ1=p(()=>{eH();Xb();vJ1();qX();_J1();yJ1=class yJ1 extends l9{constructor(X,Y){super(X,Y)}async listTools(X,Y){return await this.request({method:"tools/list",params:X},HL,Y)}}});function xJ1(X){let Y=(Q)=>{if("connection"in X)return bJ1({connection:X.connection},void 0,Q);return X.client};return new Proxy({},{get(Q,J){if(J==="toJSON")return null;if(typeof J!=="string")throw Error("Name must be a string");if(J==="listTools")return $;async function G(K,H){let F,V;if(typeof H==="object")F=J,V=H;else F??=J;let q=X?.debugId?.(),z=q?{"x-trace-debug-id":q}:void 0,{client:D,callStreamableTool:N}=await Y(z);if(X?.streamable?.[String(F)])return N(String(F),K,V?.signal??void 0);let{structuredContent:L,isError:w,content:C}=await D.callTool({name:String(F),arguments:K},void 0,{signal:V?.signal??void 0});if(w){let T=C?.[0]?.text,A=typeof T==="string"?Qb6(T):null,P=A?.code&&typeof X?.getErrorByStatusCode==="function"?X.getErrorByStatusCode(A.code,A.message,A.traceId):null;if(P)throw P;throw Error(`Tool ${String(F)} returned an error: ${JSON.stringify(L??C)}`)}return L}async function W(){let{client:K}=await Y(),{tools:H}=await K.listTools();return H}async function Z(){if(!("connection"in X))return W();let K=X.connection,H=JSON.stringify(K);try{if(!Bb.has(H))Bb.set(H,W());return await Bb.get(H)}catch(F){console.error("Failed to list tools",F),Bb.delete(H);return}}async function $(){return(await Z()??[]).map((H)=>hJ1(H,G))}return G.asTool=async()=>{let H=(await Z()??[]).find((F)=>F.name===J);if(!H)throw Error(`Tool ${J} not found`);return hJ1(H,G)},G}})}var Qb6=(X)=>{try{return JSON.parse(X)}catch{return X}},Bb,hJ1=(X,Y)=>{return{...X,id:X.name,inputSchema:X.inputSchema?MY(X.inputSchema):void 0,outputSchema:X.outputSchema?MY(X.outputSchema):void 0,execute:(Q)=>{return Y(Q.context,X.name)}}};var gJ1=p(()=>{kJ1();fJ1();Bb=new Map});function Db(X){return xJ1(X)}var Pl4;var uJ1=p(()=>{gJ1();Pl4=new Proxy({},{get(X,Y){if(Y==="toJSON")return null;if(Y==="forConnection")return(Q)=>Db({connection:Q});return global[Y]}})});function Nb(X){return{isImplementedBy:(Y)=>{for(let Q of X){let J=typeof Q.name==="string"?new RegExp(`^${Q.name}$`):Q.name,G=Y.find((W)=>J.test(W.name));if(!G&&Q.opt)continue;if(!G)return!1}return!0}}}var NF=(X)=>{return{...Nb(X),forClient:(Y)=>{return Db({client:Y,streamable:X.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})},forConnection:(Y)=>{return Db({connection:Y,streamable:X.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})}}};var IP=p(()=>{uJ1()});var n80,Cl4;var mJ1=p(()=>{qN();n80=E6(VN(),1),Cl4=n80.createContext(null)});function LF(X){return U.object({items:U.array(X).describe("Array of collection items"),totalCount:U.number().int().min(0).optional().describe("Total number of matching items (if available)"),hasMore:U.boolean().optional().describe("Whether there are more items available")})}function SP(X){return U.object({item:X.nullable().describe("The retrieved item, or null if not found")})}function Wb6(X){return U.object({data:X.partial().describe("Data for the new entity (id may be auto-generated)")})}function Zb6(X){return U.object({item:X.describe("The created entity with generated id")})}function $b6(X){return U.object({id:U.string().describe("ID of the entity to update"),data:X.partial().describe("Partial entity data to update")})}function Kb6(X){return U.object({item:X.describe("The updated entity")})}function vP(X){return U.object({item:X.describe("The deleted entity")})}function GB(X,Y,Q){let J=X.toUpperCase(),G=Q?.readOnly??!1,W=[{name:`COLLECTION_${J}_LIST`,inputSchema:OF,outputSchema:LF(Y)},{name:`COLLECTION_${J}_GET`,inputSchema:RP,outputSchema:SP(Y)}];if(!G)W.push({name:`COLLECTION_${J}_CREATE`,inputSchema:Wb6(Y),outputSchema:Zb6(Y),opt:!0},{name:`COLLECTION_${J}_UPDATE`,inputSchema:$b6(Y),outputSchema:Kb6(Y),opt:!0},{name:`COLLECTION_${J}_DELETE`,inputSchema:kP,outputSchema:vP(Y),opt:!0});return W}var JB,Jb6,lJ1,Gb6,OF,RP,kP;var x5=p(()=>{a0();JB=U.object({id:U.string().describe("Unique identifier for the entity"),title:U.string().describe("Human-readable title for the entity"),description:U.string().nullish().describe("Description of the entity"),created_at:U.string().datetime(),updated_at:U.string().datetime(),created_by:U.string().optional(),updated_by:U.string().optional()}),Jb6=U.object({field:U.array(U.string()),operator:U.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:U.unknown()}),lJ1=U.lazy(()=>U.union([Jb6,U.object({operator:U.enum(["and","or","not"]),conditions:U.array(lJ1)})])),Gb6=U.object({field:U.array(U.string()),direction:U.enum(["asc","desc"]),nulls:U.enum(["first","last"]).optional()}),OF=U.object({where:lJ1.optional().describe("Filter expression"),orderBy:U.array(Gb6).optional().describe("Sort expressions"),limit:U.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:U.number().int().min(0).optional().describe("Number of items to skip")});RP=U.object({id:U.string().describe("ID of the entity to retrieve")});kP=U.object({id:U.string().describe("ID of the entity to delete")})});var Hb6,dJ1,yl4;var pJ1=p(()=>{a0();x5();Hb6=U.object({id:U.string(),name:U.string(),description:U.string().optional(),inputSchema:U.record(U.string(),U.unknown()),outputSchema:U.record(U.string(),U.unknown()).optional()}),dJ1=JB.extend({_meta:U.object({"io.decocms":U.object({id:U.string(),verified:U.boolean(),scopeName:U.string(),appName:U.string(),friendlyName:U.string().nullable().optional(),metadata:U.record(U.string(),U.unknown()).nullable().optional(),publishedAt:U.string().datetime().optional(),updatedAt:U.string().datetime().optional(),tools:U.array(Hb6).nullable().optional().describe("Available tools exposed by this app")}).optional()}).optional(),server:U.object({$schema:U.string().optional(),_meta:U.record(U.string(),U.unknown()).optional(),name:U.string().describe("The server name (scope/app)"),title:U.string().optional().describe("User-friendly title"),description:U.string().optional().describe("Server description"),icons:U.array(U.object({src:U.string(),mimeType:U.string().optional(),sizes:U.array(U.string()).optional(),theme:U.enum(["light","dark"]).optional()})).optional(),remotes:U.array(U.object({type:U.enum(["http","stdio","sse"]),url:U.string().optional(),headers:U.array(U.unknown()).optional()})).optional(),packages:U.array(U.unknown()).optional(),repository:U.object({url:U.string(),source:U.string().optional(),subfolder:U.string().optional()}).optional(),version:U.string().optional(),websiteUrl:U.string().optional()})}),yl4=GB("registry_app",dJ1,{readOnly:!0})});var cJ1,nJ1,iJ1,aJ1,rJ1,i80;var oJ1=p(()=>{a0();IP();cJ1=U.object({specversion:U.literal("1.0").describe("CloudEvents specification version"),id:U.string().describe("Unique identifier for this event (UUID recommended)"),source:U.string().describe("Connection ID of the event publisher"),type:U.string().describe("Event type (e.g., 'order.created', 'user.signup')"),time:U.string().datetime().optional().describe("Timestamp of when the event occurred (ISO 8601)"),subject:U.string().optional().describe("Subject/resource identifier (e.g., order ID, user ID)"),datacontenttype:U.string().optional().default("application/json").describe("Content type of the data attribute"),dataschema:U.string().url().optional().describe("URI to the schema for the data attribute"),data:U.unknown().optional().describe("Event payload (any JSON value)")}),nJ1=U.object({events:U.array(cJ1).min(1).describe("Batch of CloudEvents to process")}),iJ1=U.object({success:U.boolean().optional().describe("Whether this event was processed successfully"),error:U.string().optional().describe("Error message for this event"),retryAfter:U.number().int().positive().optional().describe("Re-deliver this event after this many ms")}),aJ1=U.object({success:U.boolean().optional().describe("Batch success - applies to events not in results"),error:U.string().optional().describe("Batch error message - applies to events not in results"),processedCount:U.number().int().min(0).optional().describe("Number of events successfully processed"),retryAfter:U.number().int().positive().optional().describe("Batch retryAfter - applies to events not in results"),results:U.record(U.string(),iJ1).optional().describe("Per-event results keyed by event ID")}),rJ1=[{name:"ON_EVENTS",inputSchema:nJ1,outputSchema:aJ1}],i80=NF(rJ1)});var _P,yP,bP,fP,sJ1,tJ1,hP,xP,gP,uP,mP,lP,dP,pP,eJ1,Fb6;var X51=p(()=>{a0();IP();_P=U.object({type:U.string().min(1).max(255).describe("Event type identifier"),subject:U.string().max(255).optional().describe("Subject/resource identifier (e.g., order ID)"),data:U.unknown().optional().describe("Event payload"),deliverAt:U.string().datetime().optional().describe("Scheduled delivery time (ISO 8601). Omit for immediate delivery."),cron:U.string().max(100).optional().describe("Cron expression for recurring delivery. Use EVENT_CANCEL to stop.")}),yP=U.object({id:U.string().describe("Unique event ID"),type:U.string().describe("Event type"),source:U.string().describe("Source connection ID"),time:U.string().describe("Event timestamp")}),bP=U.object({eventType:U.string().min(1).max(255).describe("Event type to subscribe to"),publisher:U.string().optional().describe("Filter events by publisher connection ID"),filter:U.string().max(1000).optional().describe("JSONPath filter expression on event data")}),fP=U.object({subscription:U.object({id:U.string().describe("Subscription ID"),connectionId:U.string().describe("Subscriber connection ID"),eventType:U.string().describe("Event type pattern"),publisher:U.string().nullable().describe("Publisher connection filter"),filter:U.string().nullable().describe("JSONPath filter expression"),enabled:U.boolean().describe("Whether subscription is enabled"),createdAt:U.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:U.string().datetime().describe("Updated timestamp (ISO 8601)")})}),sJ1=U.object({eventType:U.string().min(1).max(255).describe("Event type to subscribe to"),publisher:U.string().optional().describe("Filter events by publisher connection ID"),filter:U.string().max(1000).optional().describe("JSONPath filter expression on event data")}),tJ1=U.object({id:U.string().describe("Subscription ID"),connectionId:U.string().describe("Subscriber connection ID"),eventType:U.string().describe("Event type pattern"),publisher:U.string().nullable().describe("Publisher connection filter"),filter:U.string().nullable().describe("JSONPath filter expression"),enabled:U.boolean().describe("Whether subscription is enabled"),createdAt:U.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:U.string().datetime().describe("Updated timestamp (ISO 8601)")}),hP=U.object({subscriptions:U.array(sJ1).describe("Desired subscriptions - system will create/update/delete to match")}),xP=U.object({created:U.number().int().min(0).describe("Number of subscriptions created"),updated:U.number().int().min(0).describe("Number of subscriptions with filter updated"),deleted:U.number().int().min(0).describe("Number of subscriptions removed"),unchanged:U.number().int().min(0).describe("Number of subscriptions unchanged"),subscriptions:U.array(tJ1).describe("Current subscriptions after sync")}),gP=U.object({subscriptionId:U.string().describe("Subscription ID to remove")}),uP=U.object({success:U.boolean().describe("Whether unsubscribe was successful"),subscriptionId:U.string().describe("Subscription ID that was removed")}),mP=U.object({eventId:U.string().describe("Event ID to cancel")}),lP=U.object({success:U.boolean().describe("Whether cancellation was successful"),eventId:U.string().describe("Event ID that was cancelled")}),dP=U.object({eventId:U.string().describe("Event ID to acknowledge")}),pP=U.object({success:U.boolean().describe("Whether ACK was successful"),eventId:U.string().describe("Event ID that was acknowledged")}),eJ1=[{name:"EVENT_PUBLISH",inputSchema:_P,outputSchema:yP},{name:"EVENT_SUBSCRIBE",inputSchema:bP,outputSchema:fP},{name:"EVENT_UNSUBSCRIBE",inputSchema:gP,outputSchema:uP},{name:"EVENT_CANCEL",inputSchema:mP,outputSchema:lP},{name:"EVENT_ACK",inputSchema:dP,outputSchema:pP},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:hP,outputSchema:xP}],Fb6=NF(eJ1)});var dl4,pl4,cl4,nl4,il4,al4,rl4,ol4,sl4,tl4,el4,Xd4;var Y51=p(()=>{a0();dl4=U.object({prefix:U.string().optional().describe("Filter objects by prefix (e.g., 'folder/' for folder contents)"),maxKeys:U.number().optional().default(1000).describe("Maximum number of keys to return (default: 1000)"),continuationToken:U.string().optional().describe("Token for pagination from previous response"),delimiter:U.string().optional().describe("Delimiter for grouping keys (typically '/'). When set, commonPrefixes returns folder paths.")}),pl4=U.object({objects:U.array(U.object({key:U.string().describe("Object key/path"),size:U.number().describe("Object size in bytes"),lastModified:U.string().describe("Last modified timestamp"),etag:U.string().describe("Entity tag for the object")})),nextContinuationToken:U.string().optional().describe("Token for fetching next page of results"),isTruncated:U.boolean().describe("Whether there are more results available"),commonPrefixes:U.array(U.string()).optional().describe("Folder paths when delimiter is used (e.g., ['photos/2024/', 'photos/2025/'])")}),cl4=U.object({key:U.string().describe("Object key/path to get metadata for")}),nl4=U.object({contentType:U.string().optional().describe("MIME type of the object"),contentLength:U.number().describe("Size of the object in bytes"),lastModified:U.string().describe("Last modified timestamp"),etag:U.string().describe("Entity tag for the object"),metadata:U.record(U.string(),U.string()).optional().describe("Custom metadata key-value pairs")}),il4=U.object({key:U.string().describe("Object key/path to generate URL for"),expiresIn:U.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)")}),al4=U.object({url:U.string().describe("Presigned URL for downloading the object"),expiresIn:U.number().describe("Expiration time in seconds that was used")}),rl4=U.object({key:U.string().describe("Object key/path for the upload"),expiresIn:U.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)"),contentType:U.string().optional().describe("MIME type for the object being uploaded")}),ol4=U.object({url:U.string().describe("Presigned URL for uploading the object"),expiresIn:U.number().describe("Expiration time in seconds that was used")}),sl4=U.object({key:U.string().describe("Object key/path to delete")}),tl4=U.object({success:U.boolean().describe("Whether the deletion was successful"),key:U.string().describe("The key that was deleted")}),el4=U.object({keys:U.array(U.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),Xd4=U.object({deleted:U.array(U.string()).describe("Array of successfully deleted keys"),errors:U.array(U.object({key:U.string(),message:U.string()})).describe("Array of errors for failed deletions")})});var Ob=p(()=>{IP();mJ1();pJ1();oJ1();X51();Y51()});var Vb6,qb6,Q51;var J51=p(()=>{a0();x5();Vb6=JB.extend({avatar:U.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:U.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:U.string().describe("Virtual MCP ID to use for this assistant"),model:U.object({id:U.string().describe("Model ID"),connectionId:U.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),qb6=GB("assistant",Vb6),Q51=[...qb6]});var cP,aW,W51,Ub6,zb6,Z51,Bb6,Db6,Nb6,Ob6,Lb6,wb6,$51,Mb6,Pb6,Ab6,Tb6,Eb6,jb6,Cb6,Ib6,Rb6,Sb6,wd4,kb6,Md4,G51,vb6,_b6,a80,Lb;var wb=p(()=>{a0();IP();x5();cP=U.lazy(()=>U.union([U.null(),U.string(),U.number(),U.boolean(),U.record(U.string(),cP),U.array(cP)])),aW=U.record(U.string(),U.record(U.string(),cP)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),W51=U.object({type:U.literal("text"),text:U.string().describe("The text content"),providerOptions:aW}),Ub6=U.object({type:U.literal("text"),text:U.string().describe("The text content"),providerMetadata:U.any().optional().describe("Additional provider-specific metadata")}),zb6=U.string().describe("File data as URL string"),Z51=U.object({type:U.literal("file"),filename:U.string().optional().describe("Optional filename of the file"),data:zb6,mediaType:U.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:aW}),Bb6=U.object({type:U.literal("file"),mediaType:U.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:U.string().describe("Generated file data as base64 encoded string")}),Db6=U.object({type:U.literal("reasoning"),text:U.string().describe("The reasoning text"),providerOptions:aW}),Nb6=U.object({type:U.literal("reasoning"),text:U.string().describe("The reasoning text"),providerMetadata:U.any().optional().describe("Additional provider-specific metadata")}),Ob6=U.object({type:U.literal("tool-call"),toolCallId:U.string().describe("ID of the tool call, used to match with tool result"),toolName:U.string().describe("Name of the tool being called"),input:U.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:U.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:aW}),Lb6=U.object({type:U.literal("tool-call"),toolCallId:U.string().describe("ID of the tool call"),toolName:U.string().describe("Name of the tool being called"),input:U.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:U.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:U.any().optional().describe("Additional provider-specific metadata")}),wb6=U.union([U.object({type:U.literal("text"),value:U.string()}),U.object({type:U.literal("json"),value:cP}),U.object({type:U.literal("error-text"),value:U.string()}),U.object({type:U.literal("error-json"),value:cP}),U.object({type:U.literal("content"),value:U.array(U.union([U.object({type:U.literal("text"),text:U.string().describe("Text content")}),U.object({type:U.literal("media"),data:U.string().describe("Base-64 encoded media data"),mediaType:U.string().describe("IANA media type")})]))})]),$51=U.object({type:U.literal("tool-result"),toolCallId:U.string().describe("ID of the tool call that this result is associated with"),toolName:U.string().describe("Name of the tool that generated this result"),output:wb6.describe("Result of the tool call"),result:U.unknown().describe("Unknown result of the tool call"),providerOptions:aW}),Mb6=U.object({type:U.literal("tool-result"),toolCallId:U.string().describe("ID of the tool call that this result is associated with"),toolName:U.string().describe("Name of the tool that generated this result"),result:U.any().describe("Result of the tool call (JSON-serializable)"),isError:U.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:U.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:U.any().optional().describe("Additional provider-specific metadata")}),Pb6=U.union([U.object({type:U.literal("source"),sourceType:U.literal("url"),id:U.string().describe("The ID of the source"),url:U.string().describe("The URL of the source"),title:U.string().optional().describe("The title of the source"),providerMetadata:U.any().optional().describe("Additional provider-specific metadata")}),U.object({type:U.literal("source"),sourceType:U.literal("document"),id:U.string().describe("The ID of the source"),mediaType:U.string().describe("IANA media type of the document (e.g., application/pdf)"),title:U.string().describe("The title of the document"),filename:U.string().optional().describe("Optional filename of the document"),providerMetadata:U.any().optional().describe("Additional provider-specific metadata")})]),Ab6=U.object({role:U.literal("system"),content:U.string().describe("System message content"),providerOptions:aW}),Tb6=U.object({role:U.literal("user"),content:U.array(U.union([W51,Z51])).describe("User message content parts (text or file)"),providerOptions:aW}),Eb6=U.object({role:U.literal("assistant"),content:U.array(U.union([W51,Z51,Db6,Ob6,$51])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:aW}),jb6=U.object({role:U.literal("tool"),content:U.array($51).describe("Tool message content (tool results)"),providerOptions:aW}),Cb6=U.union([Ab6,Tb6,Eb6,jb6]),Ib6=U.array(Cb6).describe("A list of messages forming the prompt"),Rb6=U.object({prompt:Ib6.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:U.number().optional().describe("Maximum number of tokens to generate"),temperature:U.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:U.number().optional().describe("Nucleus sampling parameter"),topK:U.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:U.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:U.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:U.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:U.array(U.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:U.union([U.object({type:U.literal("text")}),U.object({type:U.literal("json"),schema:U.any().optional().describe("JSON schema that the generated output should conform to"),name:U.string().optional().describe("Name of output that should be generated"),description:U.string().optional().describe("Description of the output that should be generated")})]).optional().describe("Response format. The output can either be text or JSON. Default is text"),tools:U.array(U.any()).optional().describe("The tools that are available for the model"),toolChoice:U.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:U.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:U.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:U.any().optional().describe("Additional provider-specific options")}),Sb6=U.object({content:U.array(U.union([Ub6,Bb6,Nb6,Lb6,Mb6,Pb6])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:U.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:U.looseObject({inputTokens:U.number().optional(),outputTokens:U.number().optional(),totalTokens:U.number().optional(),reasoningTokens:U.number().optional()}).describe("Usage information for the language model call"),providerMetadata:U.any().optional().describe("Additional provider-specific metadata"),request:U.object({body:U.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:U.object({id:U.string().optional().describe("ID for the generated response"),timestamp:U.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:U.string().optional().describe("The ID of the response model that was used"),headers:U.record(U.string(),U.string()).optional().describe("Response headers"),body:U.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:U.array(U.any()).describe("Warnings for the call, e.g. unsupported settings")}),wd4=U.object({stream:U.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:U.object({body:U.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:U.object({headers:U.record(U.string(),U.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),kb6=U.object({supportedUrls:U.record(U.string(),U.array(U.string())).describe("Supported URL patterns by media type for the provider")}),Md4=U.object({modelId:U.string().describe("The ID of the model"),logo:U.string().nullable(),description:U.string().nullable(),capabilities:U.array(U.string()),limits:U.object({contextWindow:U.number(),maxOutputTokens:U.number()}).nullable(),costs:U.object({input:U.number(),output:U.number()}).nullable(),provider:U.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),G51=U.object({modelId:U.string().describe("The ID of the model"),callOptions:Rb6}),vb6=JB.extend({logo:U.string().nullable(),description:U.string().nullable(),capabilities:U.array(U.string()),limits:U.object({contextWindow:U.number(),maxOutputTokens:U.number()}).nullable(),costs:U.object({input:U.number(),output:U.number()}).nullable(),provider:U.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),_b6=GB("llm",vb6,{readOnly:!0}),a80=[{name:"LLM_METADATA",inputSchema:U.object({modelId:U.string().describe("The ID of the model")}),outputSchema:kb6},{name:"LLM_DO_STREAM",inputSchema:G51,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:G51,outputSchema:Sb6},..._b6],Lb=NF(a80)});function bb6(X){let Y=[],Q=0;while(Q<X.length){let J=X[Q];if(J==="%")Y.push(".*");else if(J==="_")Y.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))Y.push("\\"+J);else Y.push(J);Q++}return Y.join("")}function VK(X){return typeof X==="string"||typeof X==="number"}function Mb(X,Y){if("conditions"in Y){let{operator:$,conditions:K}=Y;switch($){case"and":return K.every((H)=>Mb(X,H));case"or":return K.some((H)=>Mb(X,H));case"not":return!K.every((H)=>Mb(X,H));default:return!0}}let{field:Q,operator:J,value:G}=Y,W=Q.join("."),Z=r80(X,W);switch(J){case"eq":return Z===G;case"gt":return VK(Z)&&VK(G)&&Z>G;case"gte":return VK(Z)&&VK(G)&&Z>=G;case"lt":return VK(Z)&&VK(G)&&Z<G;case"lte":return VK(Z)&&VK(G)&&Z<=G;case"in":return Array.isArray(G)&&G.includes(Z);case"like":if(typeof Z!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let $=bb6(G);return new RegExp(`^${$}$`,"i").test(Z);case"contains":if(typeof Z!=="string"||typeof G!=="string")return!1;return Z.toLowerCase().includes(G.toLowerCase());default:return!0}}function r80(X,Y){let Q=Y.split("."),J=X;for(let G of Q){if(J==null||typeof J!=="object")return;J=J[G]}return J}function fb6(X,Y){return[...X].sort((Q,J)=>{for(let G of Y){let W=G.field.join("."),Z=r80(Q,W),$=r80(J,W),K=0;if(Z==null&&$==null)continue;if(Z==null)K=G.nulls==="first"?-1:1;else if($==null)K=G.nulls==="first"?1:-1;else if(typeof Z==="string"&&typeof $==="string")K=Z.localeCompare($);else if(typeof Z==="number"&&typeof $==="number")K=Z-$;else K=String(Z).localeCompare(String($));if(K!==0)return G.direction==="desc"?-K:K}return 0})}var yb6,hb6,xb6,o80;var K51=p(()=>{Ob();J51();x5();wb();a0();Z6();q7();yb6={LLM:a80,ASSISTANTS:Q51};hb6=OF.extend({binding:U.union([U.object({}).passthrough(),U.string()]).optional()}),xb6=LF(dJ),o80=t0({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",inputSchema:hb6,outputSchema:xb6,handler:async(X,Y)=>{await Y.access.check();let Q=_1(Y),J=X.binding?typeof X.binding==="string"?(()=>{let z=yb6[X.binding.toUpperCase()];if(!z)throw Error(`Unknown binding: ${X.binding}`);return z})():X.binding:void 0,G=J?Nb(J):void 0,Z=(await Y.storage.connections.list(Q.id)).filter((z)=>z.connection_type!=="VIRTUAL"),$=G?await Promise.all(Z.map(async(z)=>{if(!z.tools||z.tools.length===0)return null;return G.isImplementedBy(z.tools.map((N)=>({name:N.name,inputSchema:N.inputSchema,outputSchema:N.outputSchema})))?z:null})).then((z)=>z.filter((D)=>D!==null)):Z;if(X.where)$=$.filter((z)=>Mb(z,X.where));if(X.orderBy&&X.orderBy.length>0)$=fb6($,X.orderBy);let K=$.length,H=X.offset??0,F=X.limit??100,V=$.slice(H,H+F),q=H+F<K;return{items:V,totalCount:K,hasMore:q}}})});var gb6,s80;var H51=p(()=>{x5();Z6();q7();gb6=SP(dJ),s80=t0({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",inputSchema:RP,outputSchema:gb6,handler:async(X,Y)=>{let Q=_1(Y);await Y.access.check();let J=await Y.storage.connections.findById(X.id);if(!J||J.organization_id!==Q.id)return{item:null};return{item:J}}})});var Pb=(X,Y)=>{if(Y===null||Y===void 0)return;let Q=X.replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),J=Y;for(let G of Q){if(J===null||J===void 0||typeof J!=="object")return;J=J[G]}return J};function F51(X){let Y=X.split("::");if(Y.length!==2||!Y[0]||!Y[1])throw Error(`Invalid scope format: ${X}. Expected format: "KEY::SCOPE"`);return Y}function ub6(X){let Y=X.split("::");if(Y.length!==2||!Y[0]||!Y[1])return null;return Y}function mb6(X){if(typeof X==="object"&&X!==null&&"value"in X){let Y=X.value;if(typeof Y==="string")return Y}return null}function t80(X,Y){let Q={};if(!X||!Y)return Q;for(let J of Y){if(J==="*"){Q["*"]=["*"];continue}let G=ub6(J);if(!G)continue;let[W,Z]=G,$=Pb(W,X),K=mb6($);if(K){if(!Q[K])Q[K]=[];Q[K].push(Z)}}return Q}function V51(X,Y){let Q=t80(X,Y);return new Set(Object.keys(Q).filter((J)=>J!=="*"))}var e80=()=>{};class rW{db;vault;constructor(X,Y){this.db=X;this.vault=Y}async get(X){let Y=await this.db.selectFrom("downstream_tokens").selectAll().where("connectionId","=",X).executeTakeFirst();if(!Y)return null;return this.decryptToken(Y)}async upsert(X){let Y=new Date().toISOString(),Q=await this.vault.encrypt(X.accessToken),J=X.refreshToken?await this.vault.encrypt(X.refreshToken):null,G=X.clientSecret?await this.vault.encrypt(X.clientSecret):null;return await this.db.transaction().execute(async(W)=>{let Z=await W.selectFrom("downstream_tokens").select(["id","createdAt"]).where("connectionId","=",X.connectionId).executeTakeFirst();if(Z)return await W.updateTable("downstream_tokens").set({accessToken:Q,refreshToken:J,scope:X.scope,expiresAt:X.expiresAt?.toISOString()??null,clientId:X.clientId,clientSecret:G,tokenEndpoint:X.tokenEndpoint,updatedAt:Y}).where("id","=",Z.id).execute(),{id:Z.id,connectionId:X.connectionId,accessToken:X.accessToken,refreshToken:X.refreshToken,scope:X.scope,expiresAt:X.expiresAt,createdAt:Z.createdAt,updatedAt:Y,clientId:X.clientId,clientSecret:X.clientSecret,tokenEndpoint:X.tokenEndpoint};let $=t8("dtok");return await W.insertInto("downstream_tokens").values({id:$,connectionId:X.connectionId,accessToken:Q,refreshToken:J,scope:X.scope,expiresAt:X.expiresAt?.toISOString()??null,clientId:X.clientId,clientSecret:G,tokenEndpoint:X.tokenEndpoint,createdAt:Y,updatedAt:Y}).execute(),{id:$,connectionId:X.connectionId,accessToken:X.accessToken,refreshToken:X.refreshToken,scope:X.scope,expiresAt:X.expiresAt,createdAt:Y,updatedAt:Y,clientId:X.clientId,clientSecret:X.clientSecret,tokenEndpoint:X.tokenEndpoint}})}async delete(X){await this.db.deleteFrom("downstream_tokens").where("connectionId","=",X).execute()}isExpired(X,Y=0){if(!X.expiresAt)return!1;let J=(X.expiresAt instanceof Date?X.expiresAt:new Date(X.expiresAt)).getTime();if(Number.isNaN(J))return!0;return J-Y<Date.now()}async decryptToken(X){let Y=await this.vault.decrypt(X.accessToken),Q=X.refreshToken?await this.vault.decrypt(X.refreshToken):null,J=X.clientSecret?await this.vault.decrypt(X.clientSecret):null;return{id:X.id,connectionId:X.connectionId,accessToken:Y,refreshToken:Q,scope:X.scope,expiresAt:X.expiresAt,createdAt:X.createdAt,updatedAt:X.updatedAt,clientId:X.clientId,clientSecret:J,tokenEndpoint:X.tokenEndpoint}}}var Ab=p(()=>{cW()});async function pb6(X,Y,Q,J){for(let W of Y){if(W==="*")continue;let[Z]=F51(W),$=Pb(Z,X);if($===void 0||$===null)throw Error(`Scope references key "${Z}" but it's not present in state`)}let G=V51(X,Y);for(let W of G){if(W.endsWith("_self"))continue;let Z=await J.storage.connections.findById(W);if(!Z||Z.organization_id!==Q)throw Error(`Referenced connection not found: ${W}`);try{await J.access.check(W)}catch($){throw Error(`Access denied to referenced connection: ${W}. ${$.message}`)}}}var lb6,db6,XX0;var q51=p(()=>{e80();Ab();a0();Z6();Jb();q7();lb6=U.object({id:U.string().describe("ID of the connection to update"),data:q91.describe("Partial connection data to update")}),db6=U.object({item:dJ.describe("The updated connection entity")});XX0=t0({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update an existing MCP connection in the organization",inputSchema:lb6,outputSchema:db6,handler:async(X,Y)=>{U1(Y);let Q=_1(Y);if(await Y.access.check(),!f8(Y))throw Error("User ID required to update connection");let{id:G,data:W}=X,Z=await Y.storage.connections.findById(G);if(!Z||Z.organization_id!==Q.id)throw Error("Connection not found in organization");let $=W.connection_type??Z.connection_type,K=W.connection_url??Z.connection_url;if($==="VIRTUAL"){let L=$K(K);if(!L)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let w=await Y.storage.virtualMcps.findById(L);if(!w)throw Error(`Virtual MCP not found: ${L}`);if(w.organization_id!==Q.id)throw Error("Virtual MCP does not belong to the current organization");K=sy(L)}let H=W.configuration_state??Z.configuration_state,F=W.configuration_scopes??Z.configuration_scopes??[];if(W.configuration_state!==void 0||W.configuration_scopes!==void 0){if(W.configuration_state!==void 0)H=W.configuration_state;else if(H===null)H={};if(W.configuration_scopes!==void 0)F=W.configuration_scopes??[];if(F.length>0&&H)await pb6(H,F,Q.id,Y)}let V=W.connection_token??Z.connection_token;if(!V)try{let w=await new rW(Y.db,Y.vault).get(G);if(w?.accessToken)V=w.accessToken}catch{}let q=await rz({id:Z.id,title:W.title??Z.title,connection_type:$,connection_url:K,connection_token:V,connection_headers:W.connection_headers??Z.connection_headers}).catch(()=>null),z=q?.length?q:null,D={...W,connection_url:K,tools:z,configuration_state:H,configuration_scopes:F},N=await Y.storage.connections.update(G,D);if((W.configuration_state!==void 0||W.configuration_scopes!==void 0)&&H&&F.length>0)try{await(await Y.createMCPProxy(G)).client.callTool({name:"ON_MCP_CONFIGURATION",arguments:{state:H,scopes:F}})}catch(L){console.error("Failed to invoke ON_MCP_CONFIGURATION callback",L)}return{item:N}}})});var YX0;var U51=p(()=>{x5();Z6();q7();YX0=t0({name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete a connection",inputSchema:kP,outputSchema:vP(dJ),handler:async(X,Y)=>{U1(Y);let Q=_1(Y);await Y.access.check();let J=await Y.storage.connections.findById(X.id);if(!J)throw Error(`Connection not found: ${X.id}`);if(J.organization_id!==Q.id)throw Error("Connection not found in organization");return await Y.storage.connections.delete(X.id),{item:J}}})});var QX0;var z51=p(()=>{a0();Z6();QX0=t0({name:"CONNECTION_TEST",description:"Test connection health and latency",inputSchema:U.object({id:U.string()}),outputSchema:U.object({id:U.string(),healthy:U.boolean(),latencyMs:U.number()}),handler:async(X,Y)=>{let Q=_1(Y);await Y.access.check();let J=await Y.storage.connections.findById(X.id);if(!J||J.organization_id!==Q.id)throw Error("Connection not found");let G=await Y.storage.connections.testConnection(X.id);return{id:X.id,...G}}})});var B51=p(()=>{SJ1();K51();H51();q51();U51();z51()});import{sql as e6}from"kysely";function D51(X){if(X===null||X===void 0)return"NULL";if(typeof X==="number")return String(X);if(typeof X==="boolean")return X?"TRUE":"FALSE";if(typeof X==="string")return`'${X.replace(/'/g,"''")}'`;if(X instanceof Date)return`'${X.toISOString()}'`;return`'${JSON.stringify(X).replace(/'/g,"''")}'`}function ib6(X,Y){let Q=X;for(let G=Y.length;G>=1;G--){let W=`$${G}`;if(Q.includes(W))Q=Q.replaceAll(W,D51(Y[G-1]))}let J=[];for(let G=0;G<Q.length;G++)if(Q[G]==="?")J.push(G);for(let G=Math.min(J.length,Y.length)-1;G>=0;G--){let W=J[G],Z=D51(Y[G]);Q=Q.slice(0,W)+Z+Q.slice(W+1)}return Q}function N51(X){return X.replace(/-/g,"_")}function rb6(X){return`app_${N51(X)}`}function ob6(X){return`app_role_${N51(X)}`}function sb6(X){if(X instanceof Error){let Y=X.message.toLowerCase(),Q=X.code;return Q==="3F000"||Q==="42704"||Y.includes("schema")&&Y.includes("does not exist")||Y.includes("role")&&Y.includes("does not exist")}return!1}async function tb6(X,Y,Q){if(await e6`CREATE SCHEMA IF NOT EXISTS ${e6.id(Y)}`.execute(X),!(await e6`
271
271
  SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${Q}) as exists
272
- `.execute(X)).rows[0]?.exists)await e6`CREATE ROLE ${e6.id(Q)} NOLOGIN`.execute(X);await e6`GRANT ${e6.id(Q)} TO CURRENT_USER`.execute(X),await e6`GRANT USAGE, CREATE ON SCHEMA ${e6.id(Y)} TO ${e6.id(Q)}`.execute(X),await e6`GRANT ALL ON ALL TABLES IN SCHEMA ${e6.id(Y)} TO ${e6.id(Q)}`.execute(X),await e6`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${e6.id(Y)} TO ${e6.id(Q)}`.execute(X),await e6`ALTER DEFAULT PRIVILEGES IN SCHEMA ${e6.id(Y)} GRANT ALL ON TABLES TO ${e6.id(Q)}`.execute(X),await e6`ALTER DEFAULT PRIVILEGES IN SCHEMA ${e6.id(Y)} GRANT ALL ON SEQUENCES TO ${e6.id(Q)}`.execute(X),await e6`REVOKE ALL ON SCHEMA public FROM ${e6.id(Q)}`.execute(X)}async function eb6(X,Y,Q,J){try{return await X.transaction().execute(async(G)=>{return await e6`SET LOCAL ROLE ${e6.id(Q)}`.execute(G),await e6`SET LOCAL search_path TO ${e6.id(Y)}`.execute(G),await e6.raw(J).execute(G)})}catch(G){if(sb6(G))return await tb6(X,Y,Q),await X.transaction().execute(async(W)=>{return await e6`SET LOCAL ROLE ${e6.id(Q)}`.execute(W),await e6`SET LOCAL search_path TO ${e6.id(Y)}`.execute(W),await e6.raw(J).execute(W)});throw G}}var nb6,ab6,O51;var L51=p(()=>{a0();Z6();nb6=U.object({results:U.array(U.unknown()).optional(),success:U.boolean().optional()});ab6=U.object({sql:U.string().describe("The SQL query to run"),params:U.array(U.any()).describe("The parameters to pass to the SQL query").optional()});O51=t0({name:"DATABASES_RUN_SQL",description:"Run a SQL query against the database",inputSchema:ab6,outputSchema:U.object({result:U.array(nb6)}),handler:async(X,Y)=>{U1(Y),await Y.access.check();let Q=ib6(X.sql,X.params||[]);if(!Y.connectionId)throw Error("Connection context required for database access");let J=rb6(Y.connectionId),G=ob6(Y.connectionId);return{result:[{results:(await eb6(Y.db,J,G,Q)).rows,success:!0}]}}})});var w51,Yf6,M51;var oW=p(()=>{a0();Ob();w51=U.object({connectionId:U.string().optional().describe("Filter subscriptions by connection ID (optional)")}),Yf6=U.object({id:U.string().describe("Subscription ID"),connectionId:U.string().describe("Subscriber connection ID"),eventType:U.string().describe("Event type pattern"),publisher:U.string().nullable().describe("Publisher connection filter (null = all publishers)"),filter:U.string().nullable().describe("JSONPath filter expression"),enabled:U.boolean().describe("Whether subscription is enabled"),createdAt:U.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:U.string().datetime().describe("Updated timestamp (ISO 8601)")}),M51=U.object({subscriptions:U.array(Yf6).describe("List of subscriptions")})});var JX0;var P51=p(()=>{Z6();oW();JX0=t0({name:"EVENT_PUBLISH",description:"Publish an event to the event bus. Supports immediate, scheduled (deliverAt), and recurring (cron) delivery. The source is automatically set to the caller's connection ID.",inputSchema:_P,outputSchema:yP,handler:async(X,Y)=>{U1(Y);let Q=_1(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to publish events. Use a connection-scoped token.");let G=await Y.eventBus.publish(Q.id,J,{type:X.type,subject:X.subject,data:X.data,deliverAt:X.deliverAt,cron:X.cron});return{id:G.id,type:G.type,source:G.source,time:G.time}}})});var GX0;var A51=p(()=>{Z6();oW();GX0=t0({name:"EVENT_SUBSCRIBE",description:"Subscribe to events of a specific type. The subscriber is automatically set to the caller's connection.",inputSchema:bP,outputSchema:fP,handler:async(X,Y)=>{U1(Y);let Q=_1(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to subscribe. Use a connection-scoped token.");let G=await Y.eventBus.subscribe(Q.id,{connectionId:J,eventType:X.eventType,publisher:X.publisher,filter:X.filter});return{subscription:{id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}}}})});var WX0;var T51=p(()=>{Z6();oW();WX0=t0({name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events by removing a subscription.",inputSchema:gP,outputSchema:uP,handler:async(X,Y)=>{U1(Y);let Q=_1(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to unsubscribe. Use a connection-scoped token.");let G=await Y.eventBus.getSubscription(Q.id,X.subscriptionId);if(!G)throw Error(`Subscription not found: ${X.subscriptionId}`);if(G.connectionId!==J)throw Error("Cannot unsubscribe from a subscription owned by another connection");return{success:(await Y.eventBus.unsubscribe(Q.id,X.subscriptionId)).success,subscriptionId:X.subscriptionId}}})});var ZX0;var E51=p(()=>{Z6();oW();ZX0=t0({name:"EVENT_CANCEL",description:"Cancel a recurring event to stop future deliveries. Only the publisher can cancel their own events.",inputSchema:mP,outputSchema:lP,handler:async(X,Y)=>{U1(Y);let Q=_1(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to cancel events. Use a connection-scoped token.");if(!await Y.eventBus.getEvent(Q.id,X.eventId))throw Error(`Event not found: ${X.eventId}`);if(!(await Y.eventBus.cancelEvent(Q.id,X.eventId,J)).success)throw Error("Failed to cancel event. Either the event is already completed/failed, or you are not the publisher.");return{success:!0,eventId:X.eventId}}})});var $X0;var j51=p(()=>{Z6();oW();$X0=t0({name:"EVENT_ACK",description:"Acknowledge delivery of an event. Call after successfully processing an event received via ON_EVENTS with retryAfter.",inputSchema:dP,outputSchema:pP,handler:async(X,Y)=>{U1(Y);let Q=_1(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to acknowledge events. Use a connection-scoped token.");if(!(await Y.eventBus.ackEvent(Q.id,X.eventId,J)).success)throw Error("Failed to acknowledge event. Either the event was not found, already delivered, or you are not a subscriber.");return{success:!0,eventId:X.eventId}}})});var KX0;var C51=p(()=>{Z6();oW();KX0=t0({name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions, optionally filtered by connection ID.",inputSchema:w51,outputSchema:M51,handler:async(X,Y)=>{U1(Y);let Q=_1(Y);return await Y.access.check(),{subscriptions:(await Y.eventBus.listSubscriptions(Q.id,X.connectionId)).map((G)=>({id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}))}}})});var HX0;var I51=p(()=>{Z6();oW();HX0=t0({name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state. Creates new, deletes removed, updates changed filters. Subscriptions are identified by (eventType, publisher).",inputSchema:hP,outputSchema:xP,handler:async(X,Y)=>{U1(Y);let Q=_1(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to sync subscriptions. Use a connection-scoped token.");let G=await Y.eventBus.syncSubscriptions(Q.id,{connectionId:J,subscriptions:X.subscriptions});return{created:G.created,updated:G.updated,deleted:G.deleted,unchanged:G.unchanged,subscriptions:G.subscriptions.map((W)=>({id:W.id,connectionId:W.connectionId,eventType:W.eventType,publisher:W.publisher,filter:W.filter,enabled:W.enabled,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt,updatedAt:W.updatedAt instanceof Date?W.updatedAt.toISOString():W.updatedAt}))}}})});var R51=p(()=>{P51();A51();T51();E51();j51();C51();I51();oW()});var FX0,Jf6,U7,S51,k51;var WB=p(()=>{a0();FX0=U.enum(["inclusion","exclusion"]).describe("Tool selection mode: 'inclusion' = include selected (default), 'exclusion' = exclude selected"),Jf6=U.object({connection_id:U.string().describe("Connection ID"),selected_tools:U.array(U.string()).nullable().describe("Selected tool names. With 'inclusion' mode: null = all tools included. With 'exclusion' mode: null = entire connection excluded"),selected_resources:U.array(U.string()).nullable().describe("Selected resource URIs or patterns. Supports * and ** wildcards for pattern matching. With 'inclusion' mode: null = all resources included."),selected_prompts:U.array(U.string()).nullable().describe("Selected prompt names. With 'inclusion' mode: null = all prompts included. With 'exclusion' mode: null = entire connection excluded.")}),U7=U.object({id:U.string().describe("Unique identifier for the virtual MCP"),title:U.string().describe("Human-readable name for the virtual MCP"),description:U.string().nullable().describe("Description of the virtual MCP"),icon:U.string().nullable().optional().describe("Icon URL for the virtual MCP"),created_at:U.string().describe("When the virtual MCP was created"),updated_at:U.string().describe("When the virtual MCP was last updated"),created_by:U.string().describe("User ID who created the virtual MCP"),updated_by:U.string().optional().describe("User ID who last updated the virtual MCP"),organization_id:U.string().describe("Organization ID this virtual MCP belongs to"),tool_selection_mode:FX0.describe("Tool selection mode: 'inclusion' = include selected, 'exclusion' = exclude selected"),status:U.enum(["active","inactive"]).describe("Current status"),metadata:U.object({instructions:U.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:U.array(Jf6).describe("Connections with their selected tools (behavior depends on tool_selection_mode)")}),S51=U.object({title:U.string().min(1).max(255).describe("Name for the virtual MCP"),description:U.string().nullable().optional().describe("Optional description"),tool_selection_mode:FX0.optional().default("inclusion").describe("Tool selection mode (defaults to 'inclusion')"),icon:U.string().nullable().optional().describe("Optional icon URL"),status:U.enum(["active","inactive"]).optional().default("active").describe("Initial status"),metadata:U.object({instructions:U.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:U.array(U.object({connection_id:U.string().describe("Connection ID"),selected_tools:U.array(U.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:U.array(U.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:U.array(U.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).describe("Connections to include/exclude (can be empty for exclusion mode)")}),k51=U.object({title:U.string().min(1).max(255).optional().describe("New name"),description:U.string().nullable().optional().describe("New description (null to clear)"),tool_selection_mode:FX0.optional().describe("New tool selection mode"),icon:U.string().nullable().optional().describe("New icon URL (null to clear)"),status:U.enum(["active","inactive"]).optional().describe("New status"),metadata:U.object({instructions:U.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:U.array(U.object({connection_id:U.string().describe("Connection ID"),selected_tools:U.array(U.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:U.array(U.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:U.array(U.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).optional().describe("New connections (replaces existing)")})});var Gf6,Wf6,VX0;var v51=p(()=>{a0();Z6();WB();Gf6=U.object({data:S51.describe("Data for the new virtual MCP")}),Wf6=U.object({item:U7.describe("The created virtual MCP entity")}),VX0=t0({name:"COLLECTION_VIRTUAL_MCP_CREATE",description:"Create a new MCP virtual MCP in the organization",inputSchema:Gf6,outputSchema:Wf6,handler:async(X,Y)=>{U1(Y);let Q=_1(Y);await Y.access.check();let J=f8(Y);if(!J)throw Error("User ID required to create virtual MCP");return{item:await Y.storage.virtualMcps.create(Q.id,J,X.data)}}})});function Zf6(X){let Y=[],Q=0;while(Q<X.length){let J=X[Q];if(J==="%")Y.push(".*");else if(J==="_")Y.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))Y.push("\\"+J);else Y.push(J);Q++}return Y.join("")}function qK(X){return typeof X==="string"||typeof X==="number"}function qX0(X,Y){let Q=Y.split("."),J=X;for(let G of Q){if(J==null||typeof J!=="object")return;J=J[G]}return J}function $f6(X,Y){return X.connections.some((Q)=>Q.connection_id===Y)}function Tb(X,Y){if("conditions"in Y){let{operator:$,conditions:K}=Y;switch($){case"and":return K.every((H)=>Tb(X,H));case"or":return K.some((H)=>Tb(X,H));case"not":return!K.every((H)=>Tb(X,H));default:return!0}}let{field:Q,operator:J,value:G}=Y,W=Q.join(".");if(W==="connection_id"){if(J!=="eq"||typeof G!=="string")return!1;return $f6(X,G)}let Z=qX0(X,W);switch(J){case"eq":return Z===G;case"gt":return qK(Z)&&qK(G)&&Z>G;case"gte":return qK(Z)&&qK(G)&&Z>=G;case"lt":return qK(Z)&&qK(G)&&Z<G;case"lte":return qK(Z)&&qK(G)&&Z<=G;case"in":return Array.isArray(G)&&G.includes(Z);case"like":if(typeof Z!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let $=Zf6(G);return new RegExp(`^${$}$`,"i").test(Z);case"contains":if(typeof Z!=="string"||typeof G!=="string")return!1;return Z.toLowerCase().includes(G.toLowerCase());default:return!0}}function Kf6(X,Y){return[...X].sort((Q,J)=>{for(let G of Y){let W=G.field.join("."),Z=qX0(Q,W),$=qX0(J,W),K=0;if(Z==null&&$==null)continue;if(Z==null)K=G.nulls==="first"?-1:1;else if($==null)K=G.nulls==="first"?1:-1;else if(typeof Z==="string"&&typeof $==="string")K=Z.localeCompare($);else if(typeof Z==="number"&&typeof $==="number")K=Z-$;else K=String(Z).localeCompare(String($));if(K!==0)return G.direction==="desc"?-K:K}return 0})}var Hf6,Ff6,UX0;var _51=p(()=>{x5();Z6();WB();Hf6=OF,Ff6=LF(U7),UX0=t0({name:"COLLECTION_VIRTUAL_MCP_LIST",description:"List all MCP virtual MCPs in the organization",inputSchema:Hf6,outputSchema:Ff6,handler:async(X,Y)=>{await Y.access.check();let Q=_1(Y),J=X.where&&!("conditions"in X.where)&&X.where.field.join(".")==="connection_id"&&X.where.operator==="eq"&&typeof X.where.value==="string"?X.where.value:void 0,W=J?await Y.storage.virtualMcps.listByConnectionId(Q.id,J):await Y.storage.virtualMcps.list(Q.id);if(X.where)W=W.filter((V)=>Tb(V,X.where));if(X.orderBy&&X.orderBy.length>0)W=Kf6(W,X.orderBy);let Z=W.length,$=X.offset??0,K=X.limit??100,H=W.slice($,$+K),F=$+K<Z;return{items:H,totalCount:Z,hasMore:F}}})});var Vf6,qf6,zX0;var y51=p(()=>{a0();Z6();WB();Vf6=U.object({id:U.string().describe("ID of the virtual MCP to retrieve")}),qf6=U.object({item:U7.nullable().describe("The retrieved virtual MCP, or null if not found")}),zX0=t0({name:"COLLECTION_VIRTUAL_MCP_GET",description:"Get an MCP virtual MCP by ID",inputSchema:Vf6,outputSchema:qf6,handler:async(X,Y)=>{U1(Y);let Q=_1(Y);await Y.access.check();let J=await Y.storage.virtualMcps.findById(X.id);if(J&&J.organization_id!==Q.id)return{item:null};if(!J)return{item:null};return{item:J}}})});var Uf6,zf6,BX0;var b51=p(()=>{a0();Z6();WB();Uf6=U.object({id:U.string().describe("ID of the virtual MCP to update"),data:k51.describe("Partial virtual MCP data to update")}),zf6=U.object({item:U7.describe("The updated virtual MCP entity")}),BX0=t0({name:"COLLECTION_VIRTUAL_MCP_UPDATE",description:"Update an MCP virtual MCP",inputSchema:Uf6,outputSchema:zf6,handler:async(X,Y)=>{U1(Y);let Q=_1(Y);await Y.access.check();let J=f8(Y);if(!J)throw Error("User ID required to update virtual MCP");let G=await Y.storage.virtualMcps.findById(X.id);if(!G)throw Error(`Virtual MCP not found: ${X.id}`);if(G.organization_id!==Q.id)throw Error(`Virtual MCP not found: ${X.id}`);return{item:await Y.storage.virtualMcps.update(X.id,J,X.data)}}})});var Bf6,Df6,DX0;var f51=p(()=>{a0();Z6();WB();Bf6=U.object({id:U.string().describe("ID of the virtual MCP to delete")}),Df6=U.object({item:U7.describe("The deleted virtual MCP entity")}),DX0=t0({name:"COLLECTION_VIRTUAL_MCP_DELETE",description:"Delete an MCP virtual MCP",inputSchema:Bf6,outputSchema:Df6,handler:async(X,Y)=>{U1(Y);let Q=_1(Y);await Y.access.check();let J=await Y.storage.virtualMcps.findById(X.id);if(!J)throw Error(`Virtual MCP not found: ${X.id}`);if(J.organization_id!==Q.id)throw Error(`Virtual MCP not found: ${X.id}`);return await Y.storage.virtualMcps.delete(X.id),{item:J}}})});var h51=p(()=>{v51();_51();y51();b51();f51()});var Of6,NX0;var x51=p(()=>{Z6();a0();Of6=U.object({id:U.string().optional().describe("Unique log identifier"),organizationId:U.string().describe("Organization ID"),connectionId:U.string().describe("Connection ID"),connectionTitle:U.string().describe("Connection display name"),toolName:U.string().describe("Name of the tool that was called"),input:U.record(U.string(),U.unknown()).describe("Redacted tool input"),output:U.record(U.string(),U.unknown()).describe("Redacted tool output"),isError:U.boolean().describe("Whether the call resulted in an error"),errorMessage:U.string().nullish().describe("Error message if applicable"),durationMs:U.number().describe("Call duration in milliseconds"),timestamp:U.string().describe("ISO 8601 timestamp of the call"),userId:U.string().nullish().describe("User who triggered the call"),requestId:U.string().describe("Unique request identifier"),userAgent:U.string().nullish().describe("Client identifier (x-mesh-client header)"),virtualMcpId:U.string().nullish().describe("Virtual MCP (Agent) ID if routed through an agent"),properties:U.record(U.string(),U.string()).nullish().describe("Custom key-value metadata attached to the log")}),NX0=t0({name:"MONITORING_LOGS_LIST",description:"List monitoring logs for tool calls in the organization",inputSchema:U.object({connectionId:U.string().optional().describe("Filter by connection ID"),virtualMcpId:U.string().optional().describe("Filter by Virtual MCP (Agent) ID"),toolName:U.string().optional().describe("Filter by tool name"),isError:U.boolean().optional().describe("Filter by error status"),startDate:U.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:U.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)"),limit:U.number().default(100).describe("Maximum number of results"),offset:U.number().default(0).describe("Offset for pagination"),properties:U.record(U.string(),U.string()).optional().describe("Filter by exact property key=value matches"),propertyKeys:U.array(U.string()).optional().describe("Filter by logs that have these property keys"),propertyPatterns:U.record(U.string(),U.string()).optional().describe("Filter by property value patterns (SQL LIKE, use % as wildcard)")}),outputSchema:U.object({logs:U.array(Of6).describe("Array of monitoring logs"),total:U.number().describe("Total number of logs matching filters"),offset:U.number().describe("Current offset for pagination"),limit:U.number().describe("Current limit for pagination")}),handler:async(X,Y)=>{let Q=_1(Y),G=X.properties||X.propertyKeys||X.propertyPatterns?{properties:X.properties,propertyKeys:X.propertyKeys,propertyPatterns:X.propertyPatterns}:void 0,W={organizationId:Q.id,connectionId:X.connectionId,virtualMcpId:X.virtualMcpId,toolName:X.toolName,isError:X.isError,startDate:X.startDate?new Date(X.startDate):void 0,endDate:X.endDate?new Date(X.endDate):void 0,limit:X.limit,offset:X.offset,propertyFilters:G},Z=await Y.storage.monitoring.query(W);return{logs:Z.logs.map(($)=>({...$,timestamp:$.timestamp instanceof Date?$.timestamp.toISOString():$.timestamp})),total:Z.total,offset:X.offset,limit:X.limit}}})});var OX0;var g51=p(()=>{Z6();a0();OX0=t0({name:"MONITORING_STATS",description:"Get aggregated statistics for tool call monitoring",inputSchema:U.object({startDate:U.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:U.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)")}),outputSchema:U.object({totalCalls:U.number().describe("Total number of tool calls"),errorRate:U.number().describe("Error rate as a decimal (0 to 1)"),avgDurationMs:U.number().describe("Average call duration in milliseconds"),errorRatePercent:U.string().describe("Error rate as a percentage string")}),handler:async(X,Y)=>{let J={organizationId:_1(Y).id,startDate:X.startDate?new Date(X.startDate):void 0,endDate:X.endDate?new Date(X.endDate):void 0},G=await Y.storage.monitoring.getStats(J);return{...G,errorRatePercent:(G.errorRate*100).toFixed(2)}}})});var u51=p(()=>{x51();g51()});var LX0;var m51=p(()=>{a0();Z6();LX0=t0({name:"ORGANIZATION_CREATE",description:"Create a new organization",inputSchema:U.object({slug:U.string().min(1).max(50).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens"),name:U.string().min(1).max(255),description:U.string().optional()}),outputSchema:U.object({id:U.string(),name:U.string(),slug:U.string(),logo:U.string().nullable().optional(),metadata:U.any().optional(),createdAt:U.string().datetime().describe("ISO 8601 timestamp"),members:U.array(U.any()).optional()}),handler:async(X,Y)=>{U1(Y),await Y.access.check();let Q=f8(Y);if(!Q)throw Error("User ID required to create organization");let J=await Y.boundAuth.organization.create({name:X.name,slug:X.slug,metadata:X.description?{description:X.description}:void 0,userId:Q});if(!J)throw Error("Failed to create organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var wX0;var l51=p(()=>{a0();Z6();wX0=t0({name:"ORGANIZATION_LIST",description:"List all organizations user has access to",inputSchema:U.object({userId:U.string().optional()}),outputSchema:U.object({organizations:U.array(U.object({id:U.string(),name:U.string(),slug:U.string(),logo:U.string().nullable().optional(),metadata:U.any().optional(),createdAt:U.string().datetime().describe("ISO 8601 timestamp")}))}),handler:async(X,Y)=>{U1(Y),await Y.access.check();let Q=f8(Y),J=X.userId||Q;if(!J)throw Error("User ID required to list organizations");return{organizations:(await Y.boundAuth.organization.list(J)).map((W)=>({...W,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt}))}}})});var MX0;var d51=p(()=>{a0();Z6();MX0=t0({name:"ORGANIZATION_GET",description:"Get organization details by slug or ID",inputSchema:U.object({}),outputSchema:U.object({id:U.string(),name:U.string(),slug:U.string(),logo:U.string().nullable().optional(),metadata:U.any().optional(),createdAt:U.string().datetime().describe("ISO 8601 timestamp"),members:U.array(U.any()).optional(),invitations:U.array(U.any()).optional()}),handler:async(X,Y)=>{U1(Y),await Y.access.check();let Q=await Y.boundAuth.organization.get();if(!Q)throw Error("No active organization found");let J=new Date,G=Q.invitations?.filter((W)=>new Date(W.expiresAt)>J);return{...Q,invitations:G,createdAt:Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt}}})});var PX0;var p51=p(()=>{a0();Z6();PX0=t0({name:"ORGANIZATION_UPDATE",description:"Update an existing organization",inputSchema:U.object({id:U.string(),slug:U.string().min(1).max(50).regex(/^[a-z0-9-]+$/).optional(),name:U.string().min(1).max(255).optional(),description:U.string().optional()}),outputSchema:U.object({id:U.string(),name:U.string(),slug:U.string(),logo:U.string().nullable().optional(),metadata:U.any().optional(),createdAt:U.string().datetime().describe("ISO 8601 timestamp")}),handler:async(X,Y)=>{U1(Y),await Y.access.check();let Q={};if(X.name)Q.name=X.name;if(X.slug)Q.slug=X.slug;if(X.description)Q.metadata={description:X.description};let J=await Y.boundAuth.organization.update({organizationId:X.id,data:Q});if(!J)throw Error("Failed to update organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var AX0;var c51=p(()=>{a0();Z6();AX0=t0({name:"ORGANIZATION_DELETE",description:"Delete an organization",inputSchema:U.object({id:U.string()}),outputSchema:U.object({success:U.boolean(),id:U.string()}),handler:async(X,Y)=>{return U1(Y),await Y.access.check(),await Y.boundAuth.organization.delete(X.id),{success:!0,id:X.id}}})});var nP;var TX0=p(()=>{a0();nP=U.object({title:U.string(),url:U.string(),icon:U.string()})});var EX0;var n51=p(()=>{a0();Z6();TX0();EX0=t0({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings",inputSchema:U.object({}),outputSchema:U.object({organizationId:U.string(),sidebar_items:U.array(nP).nullable().optional(),enabled_plugins:U.array(U.string()).nullable().optional(),createdAt:U.string().datetime().optional().describe("ISO 8601 timestamp"),updatedAt:U.string().datetime().optional().describe("ISO 8601 timestamp")}),handler:async(X,Y)=>{U1(Y),await Y.access.check();let Q=Y.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await Y.storage.organizationSettings.get(Q);if(!J)return{organizationId:Q};return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt,updatedAt:J.updatedAt instanceof Date?J.updatedAt.toISOString():J.updatedAt}}})});var jX0;var i51=p(()=>{a0();Z6();TX0();jX0=t0({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings",inputSchema:U.object({organizationId:U.string(),sidebar_items:U.array(nP).optional(),enabled_plugins:U.array(U.string()).optional()}),outputSchema:U.object({organizationId:U.string(),sidebar_items:U.array(nP).nullable().optional(),enabled_plugins:U.array(U.string()).nullable().optional(),createdAt:U.string().datetime().describe("ISO 8601 timestamp"),updatedAt:U.string().datetime().describe("ISO 8601 timestamp")}),handler:async(X,Y)=>{if(U1(Y),await Y.access.check(),Y.organization&&Y.organization.id!==X.organizationId)throw Error("Cannot update settings for a different organization");let Q=await Y.storage.organizationSettings.upsert(X.organizationId,{sidebar_items:X.sidebar_items,enabled_plugins:X.enabled_plugins});return{...Q,createdAt:Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt,updatedAt:Q.updatedAt instanceof Date?Q.updatedAt.toISOString():Q.updatedAt}}})});var CX0;var a51=p(()=>{a0();Z6();CX0=t0({name:"ORGANIZATION_MEMBER_ADD",description:"Add a member to an organization",inputSchema:U.object({organizationId:U.string().optional(),userId:U.string(),role:U.array(U.string())}),outputSchema:U.object({id:U.string(),organizationId:U.string(),userId:U.string(),role:U.union([U.string(),U.array(U.string())]),createdAt:U.string().datetime().describe("ISO 8601 timestamp")}),handler:async(X,Y)=>{U1(Y),await Y.access.check();let Q=X.organizationId||Y.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await Y.boundAuth.organization.addMember({organizationId:Q,userId:X.userId,role:X.role});if(!J)throw Error("Failed to add member");return{...J,role:J.role,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var IX0;var r51=p(()=>{a0();Z6();IX0=t0({name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove a member from an organization",inputSchema:U.object({organizationId:U.string().optional(),memberIdOrEmail:U.string()}),outputSchema:U.object({success:U.boolean(),memberIdOrEmail:U.string()}),handler:async(X,Y)=>{U1(Y),await Y.access.check();let Q=X.organizationId||Y.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");return await Y.boundAuth.organization.removeMember({organizationId:Q,memberIdOrEmail:X.memberIdOrEmail}),{success:!0,memberIdOrEmail:X.memberIdOrEmail}}})});var RX0;var o51=p(()=>{a0();Z6();RX0=t0({name:"ORGANIZATION_MEMBER_LIST",description:"List all members in an organization",inputSchema:U.object({limit:U.number().optional(),offset:U.number().optional()}),outputSchema:U.object({members:U.array(U.object({id:U.string(),organizationId:U.string(),userId:U.string(),role:U.string(),createdAt:U.string().datetime().describe("ISO 8601 timestamp"),user:U.object({id:U.string(),name:U.string(),email:U.string(),image:U.string().optional()}).optional()}))}),handler:async(X,Y)=>{U1(Y),await Y.access.check();let Q=Y.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await Y.boundAuth.organization.listMembers({organizationId:Q,limit:X.limit,offset:X.offset});return{members:(Array.isArray(J)?J:[]).map((W)=>({...W,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt}))}}})});var SX0;var s51=p(()=>{a0();Z6();SX0=t0({name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update a member's role in an organization",inputSchema:U.object({organizationId:U.string().optional(),memberId:U.string(),role:U.array(U.string())}),outputSchema:U.object({id:U.string(),organizationId:U.string(),userId:U.string(),role:U.union([U.literal("admin"),U.literal("member"),U.literal("owner")]),createdAt:U.string().datetime().describe("ISO 8601 timestamp"),user:U.object({email:U.string(),name:U.string(),image:U.string().optional()})}),handler:async(X,Y)=>{U1(Y),await Y.access.check();let Q=X.organizationId||Y.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await Y.boundAuth.organization.updateMemberRole({organizationId:Q,memberId:X.memberId,role:X.role});if(!J)throw Error("Failed to update member role");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var t51=p(()=>{m51();l51();d51();p51();c51();n51();i51();a51();r51();o51();s51()});var e51,z7,XG1,YG1;var wF=p(()=>{a0();e51=U.object({id:U.string().describe("Unique message ID"),threadId:U.string().describe("ID of the parent thread"),metadata:U.unknown().optional().describe("Optional message metadata"),parts:U.array(U.record(U.string(),U.unknown())).describe("Message content parts (AI SDK UIMessagePart format)"),role:U.enum(["user","assistant","system"]).describe("Message role"),createdAt:U.string().datetime().describe("Timestamp of creation"),updatedAt:U.string().datetime().describe("Timestamp of last update")}),z7=U.object({id:U.string().describe("Unique thread ID"),organizationId:U.string().describe("Organization this thread belongs to"),title:U.string().describe("Thread title"),description:U.string().nullable().describe("Thread description"),createdAt:U.string().datetime().describe("Timestamp of creation"),updatedAt:U.string().datetime().describe("Timestamp of last update"),hidden:U.boolean().optional().describe("Whether the thread is hidden"),createdBy:U.string().describe("User ID who created the thread"),updatedBy:U.string().nullable().describe("User ID who last updated the thread")}),XG1=U.object({id:U.string().optional().describe("Optional custom ID for the thread"),title:U.string().describe("Thread title"),description:U.string().nullish().describe("Thread description")}),YG1=U.object({title:U.string().optional().describe("New thread title"),description:U.string().nullish().describe("New thread description"),hidden:U.boolean().optional().describe("Whether the thread is hidden")})});var Mf6,Pf6,kX0;var QG1=p(()=>{a0();Z6();wF();cW();Mf6=U.object({data:XG1.describe("Data for the new thread (id is auto-generated if not provided)")}),Pf6=U.object({item:z7.describe("The created thread entity")}),kX0=t0({name:"COLLECTION_THREADS_CREATE",description:"Create a new thread in the organization",inputSchema:Mf6,outputSchema:Pf6,handler:async(X,Y)=>{U1(Y);let Q=_1(Y);await Y.access.check();let J=f8(Y);if(!J)throw Error("User ID required to create thread");let G=X.data.id??t8("thrd"),W=await Y.storage.threads.create({id:G,organizationId:Q.id,title:X.data.title,description:X.data.description,createdBy:J});return{item:{...W,hidden:W.hidden??!1}}}})});var Af6,Tf6,vX0;var JG1=p(()=>{x5();Z6();wF();a0();Af6=OF.extend({where:U.object({created_by:U.string().optional()}).optional()}),Tf6=LF(z7),vX0=t0({name:"COLLECTION_THREADS_LIST",description:"List all threads in the organization with filtering, sorting, and pagination",inputSchema:Af6,outputSchema:Tf6,handler:async(X,Y)=>{await Y.access.check();let Q=Y.auth.user?.id;if(!Q)throw Error("User ID required to list threads");let J=_1(Y),G=X.offset??0,W=X.limit??100,{threads:Z,total:$}=await Y.storage.threads.list(J.id,Q,{limit:W,offset:G}),K=G+W<$;return{items:Z.map((H)=>({...H,hidden:H.hidden??!1})),totalCount:$,hasMore:K}}})});var Ef6,_X0;var GG1=p(()=>{x5();Z6();wF();Ef6=SP(z7),_X0=t0({name:"COLLECTION_THREADS_GET",description:"Get thread details by ID",inputSchema:RP,outputSchema:Ef6,handler:async(X,Y)=>{U1(Y);let Q=_1(Y);await Y.access.check();let J=await Y.storage.threads.get(X.id);if(!J||J.organizationId!==Q.id)return{item:null};return{item:{...J,hidden:J.hidden??!1}}}})});var jf6,Cf6,yX0;var WG1=p(()=>{a0();Z6();wF();jf6=U.object({id:U.string().describe("ID of the thread to update"),data:YG1.describe("Partial thread data to update")}),Cf6=U.object({item:z7.describe("The updated thread entity")}),yX0=t0({name:"COLLECTION_THREADS_UPDATE",description:"Update an existing thread in the organization",inputSchema:jf6,outputSchema:Cf6,handler:async(X,Y)=>{U1(Y);let Q=_1(Y);await Y.access.check();let J=f8(Y);if(!J)throw Error("User ID required to update thread");let{id:G,data:W}=X,Z=await Y.storage.threads.get(G);if(!Z||Z.organizationId!==Q.id)throw Error("Thread not found in organization");let $=await Y.storage.threads.update(G,{title:W.title,description:W.description,hidden:W.hidden,updatedBy:J});return{item:{...$,hidden:$.hidden??!1}}}})});var bX0;var ZG1=p(()=>{x5();Z6();wF();bX0=t0({name:"COLLECTION_THREADS_DELETE",description:"Delete a thread",inputSchema:kP,outputSchema:vP(z7),handler:async(X,Y)=>{U1(Y);let Q=_1(Y);await Y.access.check();let J=await Y.storage.threads.get(X.id);if(!J)throw Error(`Thread not found: ${X.id}`);if(J.organizationId!==Q.id)throw Error(`Thread not found: ${X.id}`);return await Y.storage.threads.delete(X.id),{item:{...J,hidden:J.hidden??!1}}}})});var If6,Rf6,fX0;var $G1=p(()=>{a0();Z6();wF();If6=U.object({threadId:U.string().describe("ID of the thread to list messages for"),limit:U.number().optional().describe("Maximum number of messages to return"),offset:U.number().optional().describe("Number of messages to skip")}),Rf6=U.object({items:U.array(e51).describe("List of thread messages"),totalCount:U.number().describe("Total number of messages in the thread"),hasMore:U.boolean().describe("Whether there are more messages available")}),fX0=t0({name:"COLLECTION_THREAD_MESSAGES_LIST",description:"List all messages for a specific thread",inputSchema:If6,outputSchema:Rf6,handler:async(X,Y)=>{let Q=_1(Y);await Y.access.check();let J=await Y.storage.threads.get(X.threadId);if(!J||J.organizationId!==Q.id)throw Error("Thread not found in organization");let G=X.offset??0,W=X.limit??100,{messages:Z,total:$}=await Y.storage.threads.listMessages(X.threadId,{limit:W,offset:G}),K=G+W<$;return{items:Z,totalCount:$,hasMore:K}}})});var KG1=p(()=>{QG1();JG1();GG1();WG1();ZG1();$G1()});var kf6,vf6,hX0;var HG1=p(()=>{a0();Z6();kf6=U.object({id:U.string().min(1)}),vf6=U.object({user:U.object({id:U.string(),name:U.string(),email:U.string(),image:U.string().nullable()}).nullable()}),hX0=t0({name:"USER_GET",description:"Get a user by id (restricted to shared organizations)",inputSchema:kf6,outputSchema:vf6,handler:async(X,Y)=>{await Y.access.check(),U1(Y);let Q=f8(Y);if(!Q)throw Error("Authentication required");let J=await Y.storage.users.findById(X.id,Q);if(!J)return{user:null};return{user:{id:J.id,name:J.name,email:J.email,image:J.image??null}}}})});var FG1=p(()=>{HG1()});var qG1={};A8(qG1,{managementMCP:()=>xX0,ALL_TOOLS:()=>VG1});var VG1,xX0=(X)=>{let Y=VG1.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema,outputSchema:J.outputSchema,handler:async(G)=>{return X.access.setToolName(J.name),await J.execute(G,X)}}));return AQ1({name:"mcp-mesh-management",version:"1.0.0"}).withTools(Y).build()};var gX0=p(()=>{TQ1();xQ1();RJ1();B51();L51();R51();h51();u51();t51();KG1();FG1();VG1=[LX0,wX0,MX0,PX0,AX0,EX0,jX0,CX0,IX0,RX0,SX0,d80,o80,s80,XX0,YX0,QX0,VX0,UX0,zX0,BX0,DX0,O51,NX0,OX0,N80,L80,w80,O80,JX0,GX0,WX0,ZX0,$X0,KX0,HX0,hX0,u80,m80,l80,kX0,vX0,_X0,yX0,bX0,fX0]});var zY0=I((Os4,aW1)=>{var{defineProperty:UY0,getOwnPropertyDescriptor:nx6,getOwnPropertyNames:ix6}=Object,ax6=Object.prototype.hasOwnProperty,rx6=(X,Y)=>{for(var Q in Y)UY0(X,Q,{get:Y[Q],enumerable:!0})},ox6=(X,Y,Q,J)=>{if(Y&&typeof Y==="object"||typeof Y==="function"){for(let G of ix6(Y))if(!ax6.call(X,G)&&G!==Q)UY0(X,G,{get:()=>Y[G],enumerable:!(J=nx6(Y,G))||J.enumerable})}return X},sx6=(X)=>ox6(UY0({},"__esModule",{value:!0}),X),nW1={};rx6(nW1,{SYMBOL_FOR_REQ_CONTEXT:()=>iW1,getContext:()=>tx6});aW1.exports=sx6(nW1);var iW1=Symbol.for("@vercel/request-context");function tx6(){return globalThis[iW1]?.get?.()??{}}});var YA=I((Ls4,sW1)=>{var{defineProperty:BY0,getOwnPropertyDescriptor:ex6,getOwnPropertyNames:Xg6}=Object,Yg6=Object.prototype.hasOwnProperty,Qg6=(X,Y)=>{for(var Q in Y)BY0(X,Q,{get:Y[Q],enumerable:!0})},Jg6=(X,Y,Q,J)=>{if(Y&&typeof Y==="object"||typeof Y==="function"){for(let G of Xg6(Y))if(!Yg6.call(X,G)&&G!==Q)BY0(X,G,{get:()=>Y[G],enumerable:!(J=ex6(Y,G))||J.enumerable})}return X},Gg6=(X)=>Jg6(BY0({},"__esModule",{value:!0}),X),rW1={};Qg6(rW1,{VercelOidcTokenError:()=>oW1});sW1.exports=Gg6(rW1);class oW1 extends Error{constructor(X,Y){super(X);this.name="VercelOidcTokenError",this.cause=Y}toString(){if(this.cause)return`${this.name}: ${this.message}: ${this.cause}`;return`${this.name}: ${this.message}`}}});var YZ1=I((ws4,XZ1)=>{var{create:Wg6,defineProperty:xb,getOwnPropertyDescriptor:Zg6,getOwnPropertyNames:$g6,getPrototypeOf:Kg6}=Object,Hg6=Object.prototype.hasOwnProperty,Fg6=(X,Y)=>{for(var Q in Y)xb(X,Q,{get:Y[Q],enumerable:!0})},tW1=(X,Y,Q,J)=>{if(Y&&typeof Y==="object"||typeof Y==="function"){for(let G of $g6(Y))if(!Hg6.call(X,G)&&G!==Q)xb(X,G,{get:()=>Y[G],enumerable:!(J=Zg6(Y,G))||J.enumerable})}return X},NY0=(X,Y,Q)=>(Q=X!=null?Wg6(Kg6(X)):{},tW1(Y||!X||!X.__esModule?xb(Q,"default",{value:X,enumerable:!0}):Q,X)),Vg6=(X)=>tW1(xb({},"__esModule",{value:!0}),X),eW1={};Fg6(eW1,{findRootDir:()=>zg6,getUserDataDir:()=>Bg6});XZ1.exports=Vg6(eW1);var QA=NY0(z0("path")),qg6=NY0(z0("fs")),DY0=NY0(z0("os")),Ug6=YA();function zg6(){try{let X=process.cwd();while(X!==QA.default.dirname(X)){let Y=QA.default.join(X,".vercel");if(qg6.default.existsSync(Y))return X;X=QA.default.dirname(X)}}catch(X){throw new Ug6.VercelOidcTokenError("Token refresh only supported in node server environments")}return null}function Bg6(){if(process.env.XDG_DATA_HOME)return process.env.XDG_DATA_HOME;switch(DY0.default.platform()){case"darwin":return QA.default.join(DY0.default.homedir(),"Library/Application Support");case"linux":return QA.default.join(DY0.default.homedir(),".local/share");case"win32":if(process.env.LOCALAPPDATA)return process.env.LOCALAPPDATA;return null;default:return null}}});var KZ1=I((Ms4,$Z1)=>{var{create:Dg6,defineProperty:gb,getOwnPropertyDescriptor:Ng6,getOwnPropertyNames:Og6,getPrototypeOf:Lg6}=Object,wg6=Object.prototype.hasOwnProperty,Mg6=(X,Y)=>{for(var Q in Y)gb(X,Q,{get:Y[Q],enumerable:!0})},QZ1=(X,Y,Q,J)=>{if(Y&&typeof Y==="object"||typeof Y==="function"){for(let G of Og6(Y))if(!wg6.call(X,G)&&G!==Q)gb(X,G,{get:()=>Y[G],enumerable:!(J=Ng6(Y,G))||J.enumerable})}return X},JZ1=(X,Y,Q)=>(Q=X!=null?Dg6(Lg6(X)):{},QZ1(Y||!X||!X.__esModule?gb(Q,"default",{value:X,enumerable:!0}):Q,X)),Pg6=(X)=>QZ1(gb({},"__esModule",{value:!0}),X),GZ1={};Mg6(GZ1,{isValidAccessToken:()=>jg6,readAuthConfig:()=>Tg6,writeAuthConfig:()=>Eg6});$Z1.exports=Pg6(GZ1);var JA=JZ1(z0("fs")),WZ1=JZ1(z0("path")),Ag6=ub();function ZZ1(){let X=(0,Ag6.getVercelDataDir)();if(!X)throw Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);return WZ1.join(X,"auth.json")}function Tg6(){try{let X=ZZ1();if(!JA.existsSync(X))return null;let Y=JA.readFileSync(X,"utf8");if(!Y)return null;return JSON.parse(Y)}catch(X){return null}}function Eg6(X){let Y=ZZ1(),Q=WZ1.dirname(Y);if(!JA.existsSync(Q))JA.mkdirSync(Q,{mode:504,recursive:!0});JA.writeFileSync(Y,JSON.stringify(X,null,2),{mode:384})}function jg6(X){if(!X.token)return!1;if(typeof X.expiresAt!=="number")return!0;let Y=Math.floor(Date.now()/1000);return X.expiresAt>=Y}});var qZ1=I((Ps4,VZ1)=>{var{defineProperty:wY0,getOwnPropertyDescriptor:Cg6,getOwnPropertyNames:Ig6}=Object,Rg6=Object.prototype.hasOwnProperty,Sg6=(X,Y)=>{for(var Q in Y)wY0(X,Q,{get:Y[Q],enumerable:!0})},kg6=(X,Y,Q,J)=>{if(Y&&typeof Y==="object"||typeof Y==="function"){for(let G of Ig6(Y))if(!Rg6.call(X,G)&&G!==Q)wY0(X,G,{get:()=>Y[G],enumerable:!(J=Cg6(Y,G))||J.enumerable})}return X},vg6=(X)=>kg6(wY0({},"__esModule",{value:!0}),X),HZ1={};Sg6(HZ1,{processTokenResponse:()=>hg6,refreshTokenRequest:()=>fg6});VZ1.exports=vg6(HZ1);var OY0=z0("os"),_g6="https://vercel.com",yg6="cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp",FZ1=`@vercel/oidc node-${process.version} ${(0,OY0.platform)()} (${(0,OY0.arch)()}) ${(0,OY0.hostname)()}`,LY0=null;async function bg6(){if(LY0)return LY0;let X=`${_g6}/.well-known/openid-configuration`,Y=await fetch(X,{headers:{"user-agent":FZ1}});if(!Y.ok)throw Error("Failed to discover OAuth endpoints");let Q=await Y.json();if(!Q||typeof Q.token_endpoint!=="string")throw Error("Invalid OAuth discovery response");let J=Q.token_endpoint;return LY0=J,J}async function fg6(X){let Y=await bg6();return await fetch(Y,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":FZ1},body:new URLSearchParams({client_id:yg6,grant_type:"refresh_token",...X})})}async function hg6(X){let Y=await X.json();if(!X.ok){let Q=typeof Y==="object"&&Y&&"error"in Y?String(Y.error):"Token refresh failed";return[Error(Q)]}if(typeof Y!=="object"||Y===null)return[Error("Invalid token response")];if(typeof Y.access_token!=="string")return[Error("Missing access_token in response")];if(Y.token_type!=="Bearer")return[Error("Invalid token_type in response")];if(typeof Y.expires_in!=="number")return[Error("Missing expires_in in response")];return[null,Y]}});var ub=I((As4,NZ1)=>{var{create:xg6,defineProperty:mb,getOwnPropertyDescriptor:gg6,getOwnPropertyNames:ug6,getPrototypeOf:mg6}=Object,lg6=Object.prototype.hasOwnProperty,dg6=(X,Y)=>{for(var Q in Y)mb(X,Q,{get:Y[Q],enumerable:!0})},zZ1=(X,Y,Q,J)=>{if(Y&&typeof Y==="object"||typeof Y==="function"){for(let G of ug6(Y))if(!lg6.call(X,G)&&G!==Q)mb(X,G,{get:()=>Y[G],enumerable:!(J=gg6(Y,G))||J.enumerable})}return X},BZ1=(X,Y,Q)=>(Q=X!=null?xg6(mg6(X)):{},zZ1(Y||!X||!X.__esModule?mb(Q,"default",{value:X,enumerable:!0}):Q,X)),pg6=(X)=>zZ1(mb({},"__esModule",{value:!0}),X),DZ1={};dg6(DZ1,{assertVercelOidcTokenResponse:()=>MY0,findProjectInfo:()=>ag6,getTokenPayload:()=>sg6,getVercelCliToken:()=>ng6,getVercelDataDir:()=>cg6,getVercelOidcToken:()=>ig6,isExpired:()=>tg6,loadToken:()=>og6,saveToken:()=>rg6});NZ1.exports=pg6(DZ1);var GA=BZ1(z0("path")),IF=BZ1(z0("fs")),VB=YA(),lb=YZ1(),FB=KZ1(),UZ1=qZ1();function cg6(){let Y=(0,lb.getUserDataDir)();if(!Y)return null;return GA.join(Y,"com.vercel.cli")}async function ng6(){let X=(0,FB.readAuthConfig)();if(!X)return null;if((0,FB.isValidAccessToken)(X))return X.token||null;if(!X.refreshToken)return(0,FB.writeAuthConfig)({}),null;try{let Y=await(0,UZ1.refreshTokenRequest)({refresh_token:X.refreshToken}),[Q,J]=await(0,UZ1.processTokenResponse)(Y);if(Q||!J)return(0,FB.writeAuthConfig)({}),null;let G={token:J.access_token,expiresAt:Math.floor(Date.now()/1000)+J.expires_in};if(J.refresh_token)G.refreshToken=J.refresh_token;return(0,FB.writeAuthConfig)(G),G.token??null}catch(Y){return(0,FB.writeAuthConfig)({}),null}}async function ig6(X,Y,Q){let J=`https://api.vercel.com/v1/projects/${Y}/token?source=vercel-oidc-refresh${Q?`&teamId=${Q}`:""}`,G=await fetch(J,{method:"POST",headers:{Authorization:`Bearer ${X}`}});if(!G.ok)throw new VB.VercelOidcTokenError(`Failed to refresh OIDC token: ${G.statusText}`);let W=await G.json();return MY0(W),W}function MY0(X){if(!X||typeof X!=="object")throw TypeError("Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again");if(!("token"in X)||typeof X.token!=="string")throw TypeError("Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again")}function ag6(){let X=(0,lb.findRootDir)();if(!X)throw new VB.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");let Y=GA.join(X,".vercel","project.json");if(!IF.existsSync(Y))throw new VB.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");let Q=JSON.parse(IF.readFileSync(Y,"utf8"));if(typeof Q.projectId!=="string"&&typeof Q.orgId!=="string")throw TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");return{projectId:Q.projectId,teamId:Q.orgId}}function rg6(X,Y){let Q=(0,lb.getUserDataDir)();if(!Q)throw new VB.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let J=GA.join(Q,"com.vercel.token",`${Y}.json`),G=JSON.stringify(X);IF.mkdirSync(GA.dirname(J),{mode:504,recursive:!0}),IF.writeFileSync(J,G),IF.chmodSync(J,432);return}function og6(X){let Y=(0,lb.getUserDataDir)();if(!Y)throw new VB.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let Q=GA.join(Y,"com.vercel.token",`${X}.json`);if(!IF.existsSync(Q))return null;let J=JSON.parse(IF.readFileSync(Q,"utf8"));return MY0(J),J}function sg6(X){let Y=X.split(".");if(Y.length!==3)throw new VB.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again");let Q=Y[1].replace(/-/g,"+").replace(/_/g,"/"),J=Q.padEnd(Q.length+(4-Q.length%4)%4,"=");return JSON.parse(Buffer.from(J,"base64").toString("utf8"))}function tg6(X){return X.exp*1000<Date.now()}});var wZ1=I((Ts4,LZ1)=>{var{defineProperty:AY0,getOwnPropertyDescriptor:eg6,getOwnPropertyNames:Xu6}=Object,Yu6=Object.prototype.hasOwnProperty,Qu6=(X,Y)=>{for(var Q in Y)AY0(X,Q,{get:Y[Q],enumerable:!0})},Ju6=(X,Y,Q,J)=>{if(Y&&typeof Y==="object"||typeof Y==="function"){for(let G of Xu6(Y))if(!Yu6.call(X,G)&&G!==Q)AY0(X,G,{get:()=>Y[G],enumerable:!(J=eg6(Y,G))||J.enumerable})}return X},Gu6=(X)=>Ju6(AY0({},"__esModule",{value:!0}),X),OZ1={};Qu6(OZ1,{refreshToken:()=>Wu6});LZ1.exports=Gu6(OZ1);var PY0=YA(),RF=ub();async function Wu6(){let{projectId:X,teamId:Y}=(0,RF.findProjectInfo)(),Q=(0,RF.loadToken)(X);if(!Q||(0,RF.isExpired)((0,RF.getTokenPayload)(Q.token))){let J=await(0,RF.getVercelCliToken)();if(!J)throw new PY0.VercelOidcTokenError("Failed to refresh OIDC token: Log in to Vercel CLI and link your project with `vc link`");if(!X)throw new PY0.VercelOidcTokenError("Failed to refresh OIDC token: Try re-linking your project with `vc link`");if(Q=await(0,RF.getVercelOidcToken)(J,X,Y),!Q)throw new PY0.VercelOidcTokenError("Failed to refresh OIDC token");(0,RF.saveToken)(Q,X)}process.env.VERCEL_OIDC_TOKEN=Q.token;return}});var AZ1=I((Es4,PZ1)=>{var{defineProperty:EY0,getOwnPropertyDescriptor:Zu6,getOwnPropertyNames:$u6}=Object,Ku6=Object.prototype.hasOwnProperty,Hu6=(X,Y)=>{for(var Q in Y)EY0(X,Q,{get:Y[Q],enumerable:!0})},Fu6=(X,Y,Q,J)=>{if(Y&&typeof Y==="object"||typeof Y==="function"){for(let G of $u6(Y))if(!Ku6.call(X,G)&&G!==Q)EY0(X,G,{get:()=>Y[G],enumerable:!(J=Zu6(Y,G))||J.enumerable})}return X},Vu6=(X)=>Fu6(EY0({},"__esModule",{value:!0}),X),MZ1={};Hu6(MZ1,{getVercelOidcToken:()=>zu6,getVercelOidcTokenSync:()=>TY0});PZ1.exports=Vu6(MZ1);var qu6=zY0(),Uu6=YA();async function zu6(){let X="",Y;try{X=TY0()}catch(Q){Y=Q}try{let[{getTokenPayload:Q,isExpired:J},{refreshToken:G}]=await Promise.all([await Promise.resolve().then(() => E6(ub())),await Promise.resolve().then(() => E6(wZ1()))]);if(!X||J(Q(X)))await G(),X=TY0()}catch(Q){let J=Y instanceof Error?Y.message:"";if(Q instanceof Error)J=`${J}
273
- ${Q.message}`;if(J)throw new Uu6.VercelOidcTokenError(J);throw Q}return X}function TY0(){let X=(0,qu6.getContext)().headers?.["x-vercel-oidc-token"]??process.env.VERCEL_OIDC_TOKEN;if(!X)throw Error("The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?");return X}});var CY0=I((js4,jZ1)=>{var{defineProperty:jY0,getOwnPropertyDescriptor:Bu6,getOwnPropertyNames:Du6}=Object,Nu6=Object.prototype.hasOwnProperty,Ou6=(X,Y)=>{for(var Q in Y)jY0(X,Q,{get:Y[Q],enumerable:!0})},Lu6=(X,Y,Q,J)=>{if(Y&&typeof Y==="object"||typeof Y==="function"){for(let G of Du6(Y))if(!Nu6.call(X,G)&&G!==Q)jY0(X,G,{get:()=>Y[G],enumerable:!(J=Bu6(Y,G))||J.enumerable})}return X},wu6=(X)=>Lu6(jY0({},"__esModule",{value:!0}),X),EZ1={};Ou6(EZ1,{getContext:()=>Mu6.getContext,getVercelOidcToken:()=>TZ1.getVercelOidcToken,getVercelOidcTokenSync:()=>TZ1.getVercelOidcTokenSync});jZ1.exports=wu6(EZ1);var TZ1=AZ1(),Mu6=zY0()});var Pj=E6(K1(),1),Yy0=E6(n_0(),1),Qy0=E6(Ud(),1),Jy0=E6(ml(),1),zd=new Qy0.PrometheusExporter({preventServerStart:!0}),As1=new Yy0.NodeSDK({serviceName:"mcp-mesh",traceExporter:new Jy0.OTLPTraceExporter({url:process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT||process.env.OTEL_EXPORTER_OTLP_ENDPOINT||"http://localhost:4318/v1/traces"}),metricReader:zd});As1.start();var HN=Pj.trace.getTracer("mcp-mesh","1.0.0"),Aj=Pj.metrics.getMeter("mcp-mesh","1.0.0");var CZ=class extends Error{res;status;constructor(X=500,Y){super(Y?.message,{cause:Y?.cause});this.res=Y?.res,this.status=X}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}};var Gy0=["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"],Ts1=/^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/,Es1=(X,Y)=>{if(!X)return{};let Q=new Headers(X.headers);if(Y){let J=Q.get("connection");if(J){let G=J.split(",").map((Z)=>Z.trim()),W=G.filter((Z)=>!Ts1.test(Z));if(W.length>0)throw new CZ(400,{message:`Invalid Connection header value: ${W.join(", ")}`});G.forEach((Z)=>{Q.delete(Z)})}}return Gy0.forEach((J)=>{Q.delete(J)}),{method:X.method,body:X.body,duplex:X.body?"half":void 0,headers:Q,signal:X.signal}},js1=(X)=>{if(!X.headers||Array.isArray(X.headers)||X.headers instanceof Headers)return X;let Y=new Headers;for(let[Q,J]of Object.entries(X.headers))if(J==null)Y.delete(Q);else Y.set(Q,J);return X.headers=Y,X},Wy0=async(X,Y)=>{let{raw:Q,customFetch:J,strictConnectionProcessing:G=!1,...W}=Y instanceof Request?{raw:Y}:Y??{},Z=new Request(X,{...Es1(Q,G),...js1(W)});Z.headers.delete("accept-encoding");let $=await(J||fetch)(Z),K=new Headers($.headers);if(Gy0.forEach((H)=>{K.delete(H)}),K.has("content-encoding"))K.delete("content-encoding"),K.delete("content-length");return new Response($.body,{status:$.status,statusText:$.statusText,headers:K})};var Zy0=(X)=>(Y)=>{let Q=new URL(Y.req.raw.url),J=new URL(X);return J.pathname=Q.pathname,J.search=Q.search,Wy0(J,{raw:Y.req.raw,headers:{...Y.req.raw.headers}})};import{resolve as FN,dirname as Cs1,join as Is1,extname as Rs1}from"path";var Ss1="http://localhost:4000",ks1="./dist/client";function vs1(X,Y){let Q=FN(Y),J=FN(X);return J===Q||J.startsWith(Q+"/")}function _s1({requestPath:X,clientDir:Y}){let Q=X.startsWith("/")?X.slice(1):X,J=FN(Y,Q);if(!vs1(J,Y))return null;return J}function $y0(X,Y="../client"){let Q=new URL(X),J=Cs1(Q.pathname);return FN(J,Y)}function Ky0(X={}){let{env:Y="production",devServerUrl:Q=Ss1,clientDir:J=ks1,isServerPath:G=()=>!1}=X;if(Y==="development"){let W=Zy0(Q);return async function($){let K=new URL($.url);if(G(K.pathname))return null;let H={req:{raw:$,url:$.url}};return W(H)}}return async function(Z){if(Z.method!=="GET")return null;let $=new URL(Z.url),K;try{K=decodeURIComponent($.pathname)}catch{return null}if(G(K))return null;let H=_s1({requestPath:K,clientDir:J});if(!H)return null;let F=Is1(H,"index.html"),V=FN(J,"index.html"),q=Z.headers.get("accept"),D=q?.includes("text/html")||q?.includes("*/*")&&["",".html"].includes(Rs1(H))?[F,V]:[];for(let N of[H,...D])try{let L=Bun.file(N);if(await L.exists())return new Response(L)}catch{}return null}}var Hy0="https://api.decocms.com/mcp/registry";function Fy0(X){if(!X)return!1;try{return new URL(X).host==="api.decocms.com"&&X!=="https://api.decocms.com/mcp/registry"}catch{return!1}}gL();var DH1=E6(Ud(),1);var ko=(X,Y,Q)=>{return(J,G)=>{let W=-1;return Z(0);async function Z($){if($<=W)throw Error("next() called multiple times");W=$;let K,H=!1,F;if(X[$])F=X[$][0][0],J.req.routeIndex=$;else F=$===X.length&&G||void 0;if(F)try{K=await F(J,()=>Z($+1))}catch(V){if(V instanceof Error&&Y)J.error=V,K=await Y(V,J),H=!0;else throw V}else if(J.finalized===!1&&Q)K=await Q(J);if(K&&(J.finalized===!1||H))J.res=K;return J}}};var qd0=Symbol();var Ud0=async(X,Y=Object.create(null))=>{let{all:Q=!1,dot:J=!1}=Y,W=(X instanceof IS?X.raw.headers:X.headers).get("Content-Type");if(W?.startsWith("multipart/form-data")||W?.startsWith("application/x-www-form-urlencoded"))return b76(X,{all:Q,dot:J});return{}};async function b76(X,Y){let Q=await X.formData();if(Q)return f76(Q,Y);return{}}function f76(X,Y){let Q=Object.create(null);if(X.forEach((J,G)=>{if(!(Y.all||G.endsWith("[]")))Q[G]=J;else h76(Q,G,J)}),Y.dot)Object.entries(Q).forEach(([J,G])=>{if(J.includes("."))x76(Q,J,G),delete Q[J]});return Q}var h76=(X,Y,Q)=>{if(X[Y]!==void 0)if(Array.isArray(X[Y]))X[Y].push(Q);else X[Y]=[X[Y],Q];else if(!Y.endsWith("[]"))X[Y]=Q;else X[Y]=[Q]},x76=(X,Y,Q)=>{let J=X,G=Y.split(".");G.forEach((W,Z)=>{if(Z===G.length-1)J[W]=Q;else{if(!J[W]||typeof J[W]!=="object"||Array.isArray(J[W])||J[W]instanceof File)J[W]=Object.create(null);J=J[W]}})};var _o=(X)=>{let Y=X.split("/");if(Y[0]==="")Y.shift();return Y},zd0=(X)=>{let{groups:Y,path:Q}=g76(X),J=_o(Q);return u76(J,Y)},g76=(X)=>{let Y=[];return X=X.replace(/\{[^}]+\}/g,(Q,J)=>{let G=`@${J}`;return Y.push([G,Q]),G}),{groups:Y,path:X}},u76=(X,Y)=>{for(let Q=Y.length-1;Q>=0;Q--){let[J]=Y[Q];for(let G=X.length-1;G>=0;G--)if(X[G].includes(J)){X[G]=X[G].replace(J,Y[Q][1]);break}}return X},RS={},Bd0=(X,Y)=>{if(X==="*")return"*";let Q=X.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(Q){let J=`${X}#${Y}`;if(!RS[J])if(Q[2])RS[J]=Y&&Y[0]!==":"&&Y[0]!=="*"?[J,Q[1],new RegExp(`^${Q[2]}(?=/${Y})`)]:[X,Q[1],new RegExp(`^${Q[2]}$`)];else RS[J]=[X,Q[1],!0];return RS[J]}return null},sq=(X,Y)=>{try{return Y(X)}catch{return X.replace(/(?:%[0-9A-Fa-f]{2})+/g,(Q)=>{try{return Y(Q)}catch{return Q}})}},m76=(X)=>sq(X,decodeURI),yo=(X)=>{let Y=X.url,Q=Y.indexOf("/",Y.indexOf(":")+4),J=Q;for(;J<Y.length;J++){let G=Y.charCodeAt(J);if(G===37){let W=Y.indexOf("?",J),Z=Y.slice(Q,W===-1?void 0:W);return m76(Z.includes("%25")?Z.replace(/%25/g,"%2525"):Z)}else if(G===63)break}return Y.slice(Q,J)};var Dd0=(X)=>{let Y=yo(X);return Y.length>1&&Y.at(-1)==="/"?Y.slice(0,-1):Y},Y3=(X,Y,...Q)=>{if(Q.length)Y=Y3(Y,...Q);return`${X?.[0]==="/"?"":"/"}${X}${Y==="/"?"":`${X?.at(-1)==="/"?"":"/"}${Y?.[0]==="/"?Y.slice(1):Y}`}`},SS=(X)=>{if(X.charCodeAt(X.length-1)!==63||!X.includes(":"))return null;let Y=X.split("/"),Q=[],J="";return Y.forEach((G)=>{if(G!==""&&!/\:/.test(G))J+="/"+G;else if(/\:/.test(G))if(/\?/.test(G)){if(Q.length===0&&J==="")Q.push("/");else Q.push(J);let W=G.replace("?","");J+="/"+W,Q.push(J)}else J+="/"+G}),Q.filter((G,W,Z)=>Z.indexOf(G)===W)},vo=(X)=>{if(!/[%+]/.test(X))return X;if(X.indexOf("+")!==-1)X=X.replace(/\+/g," ");return X.indexOf("%")!==-1?sq(X,uL):X},Nd0=(X,Y,Q)=>{let J;if(!Q&&Y&&!/[%+]/.test(Y)){let Z=X.indexOf("?",8);if(Z===-1)return;if(!X.startsWith(Y,Z+1))Z=X.indexOf(`&${Y}`,Z+1);while(Z!==-1){let $=X.charCodeAt(Z+Y.length+1);if($===61){let K=Z+Y.length+2,H=X.indexOf("&",K);return vo(X.slice(K,H===-1?void 0:H))}else if($==38||isNaN($))return"";Z=X.indexOf(`&${Y}`,Z+1)}if(J=/[%+]/.test(X),!J)return}let G={};J??=/[%+]/.test(X);let W=X.indexOf("?",8);while(W!==-1){let Z=X.indexOf("&",W+1),$=X.indexOf("=",W);if($>Z&&Z!==-1)$=-1;let K=X.slice(W+1,$===-1?Z===-1?void 0:Z:$);if(J)K=vo(K);if(W=Z,K==="")continue;let H;if($===-1)H="";else if(H=X.slice($+1,Z===-1?void 0:Z),J)H=vo(H);if(Q){if(!(G[K]&&Array.isArray(G[K])))G[K]=[];G[K].push(H)}else G[K]??=H}return Y?G[Y]:G},Od0=Nd0,Ld0=(X,Y)=>{return Nd0(X,Y,!0)},uL=decodeURIComponent;var wd0=(X)=>sq(X,uL),IS=class{raw;#X;#Y;routeIndex=0;path;bodyCache={};constructor(X,Y="/",Q=[[]]){this.raw=X,this.path=Y,this.#Y=Q,this.#X={}}param(X){return X?this.#Q(X):this.#J()}#Q(X){let Y=this.#Y[0][this.routeIndex][1][X],Q=this.#W(Y);return Q&&/\%/.test(Q)?wd0(Q):Q}#J(){let X={},Y=Object.keys(this.#Y[0][this.routeIndex][1]);for(let Q of Y){let J=this.#W(this.#Y[0][this.routeIndex][1][Q]);if(J!==void 0)X[Q]=/\%/.test(J)?wd0(J):J}return X}#W(X){return this.#Y[1]?this.#Y[1][X]:X}query(X){return Od0(this.url,X)}queries(X){return Ld0(this.url,X)}header(X){if(X)return this.raw.headers.get(X)??void 0;let Y={};return this.raw.headers.forEach((Q,J)=>{Y[J]=Q}),Y}async parseBody(X){return this.bodyCache.parsedBody??=await Ud0(this,X)}#G=(X)=>{let{bodyCache:Y,raw:Q}=this,J=Y[X];if(J)return J;let G=Object.keys(Y)[0];if(G)return Y[G].then((W)=>{if(G==="json")W=JSON.stringify(W);return new Response(W)[X]()});return Y[X]=Q[X]()};json(){return this.#G("text").then((X)=>JSON.parse(X))}text(){return this.#G("text")}arrayBuffer(){return this.#G("arrayBuffer")}blob(){return this.#G("blob")}formData(){return this.#G("formData")}addValidatedData(X,Y){this.#X[X]=Y}valid(X){return this.#X[X]}get url(){return this.raw.url}get method(){return this.raw.method}get[qd0](){return this.#Y}get matchedRoutes(){return this.#Y[0].map(([[,X]])=>X)}get routePath(){return this.#Y[0].map(([[,X]])=>X)[this.routeIndex].path}};var kS={Stringify:1,BeforeStream:2,Stream:3},l76=(X,Y)=>{let Q=new String(X);return Q.isEscaped=!0,Q.callbacks=Y,Q};var mL=async(X,Y,Q,J,G)=>{if(typeof X==="object"&&!(X instanceof String)){if(!(X instanceof Promise))X=X.toString();if(X instanceof Promise)X=await X}let W=X.callbacks;if(!W?.length)return Promise.resolve(X);if(G)G[0]+=X;else G=[X];let Z=Promise.all(W.map(($)=>$({phase:Y,buffer:G,context:J}))).then(($)=>Promise.all($.filter(Boolean).map((K)=>mL(K,Y,!1,J,G))).then(()=>G[0]));if(Q)return l76(await Z,W);else return Z};var Md0="text/plain; charset=UTF-8",bo=(X,Y)=>{return{"Content-Type":X,...Y}},Pd0=class{#X;#Y;env={};#Q;finalized=!1;error;#J;#W;#G;#$;#Z;#H;#K;#V;#q;constructor(X,Y){if(this.#X=X,Y)this.#W=Y.executionCtx,this.env=Y.env,this.#H=Y.notFoundHandler,this.#q=Y.path,this.#V=Y.matchResult}get req(){return this.#Y??=new IS(this.#X,this.#q,this.#V),this.#Y}get event(){if(this.#W&&"respondWith"in this.#W)return this.#W;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#W)return this.#W;else throw Error("This context has no ExecutionContext")}get res(){return this.#G||=new Response(null,{headers:this.#K??=new Headers})}set res(X){if(this.#G&&X){X=new Response(X.body,X);for(let[Y,Q]of this.#G.headers.entries()){if(Y==="content-type")continue;if(Y==="set-cookie"){let J=this.#G.headers.getSetCookie();X.headers.delete("set-cookie");for(let G of J)X.headers.append("set-cookie",G)}else X.headers.set(Y,Q)}}this.#G=X,this.finalized=!0}render=(...X)=>{return this.#Z??=(Y)=>this.html(Y),this.#Z(...X)};setLayout=(X)=>this.#$=X;getLayout=()=>this.#$;setRenderer=(X)=>{this.#Z=X};header=(X,Y,Q)=>{if(this.finalized)this.#G=new Response(this.#G.body,this.#G);let J=this.#G?this.#G.headers:this.#K??=new Headers;if(Y===void 0)J.delete(X);else if(Q?.append)J.append(X,Y);else J.set(X,Y)};status=(X)=>{this.#J=X};set=(X,Y)=>{this.#Q??=new Map,this.#Q.set(X,Y)};get=(X)=>{return this.#Q?this.#Q.get(X):void 0};get var(){if(!this.#Q)return{};return Object.fromEntries(this.#Q)}#F(X,Y,Q){let J=this.#G?new Headers(this.#G.headers):this.#K??new Headers;if(typeof Y==="object"&&"headers"in Y){let W=Y.headers instanceof Headers?Y.headers:new Headers(Y.headers);for(let[Z,$]of W)if(Z.toLowerCase()==="set-cookie")J.append(Z,$);else J.set(Z,$)}if(Q)for(let[W,Z]of Object.entries(Q))if(typeof Z==="string")J.set(W,Z);else{J.delete(W);for(let $ of Z)J.append(W,$)}let G=typeof Y==="number"?Y:Y?.status??this.#J;return new Response(X,{status:G,headers:J})}newResponse=(...X)=>this.#F(...X);body=(X,Y,Q)=>this.#F(X,Y,Q);text=(X,Y,Q)=>{return!this.#K&&!this.#J&&!Y&&!Q&&!this.finalized?new Response(X):this.#F(X,Y,bo(Md0,Q))};json=(X,Y,Q)=>{return this.#F(JSON.stringify(X),Y,bo("application/json",Q))};html=(X,Y,Q)=>{let J=(G)=>this.#F(G,Y,bo("text/html; charset=UTF-8",Q));return typeof X==="object"?mL(X,kS.Stringify,!1,{}).then(J):J(X)};redirect=(X,Y)=>{let Q=String(X);return this.header("Location",!/[^\x00-\xFF]/.test(Q)?Q:encodeURI(Q)),this.newResponse(null,Y??302)};notFound=()=>{return this.#H??=()=>new Response,this.#H(this)}};var n4="ALL",Ad0="all",Td0=["get","post","put","delete","options","patch"],vS="Can not add a route since the matcher is already built.",_S=class extends Error{};var Ed0="__COMPOSED_HANDLER";var d76=(X)=>{return X.text("404 Not Found",404)},jd0=(X,Y)=>{if("getResponse"in X){let Q=X.getResponse();return Y.newResponse(Q.body,Q)}return console.error(X),Y.text("Internal Server Error",500)},Cd0=class X{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#X="/";routes=[];constructor(Y={}){[...Td0,Ad0].forEach((W)=>{this[W]=(Z,...$)=>{if(typeof Z==="string")this.#X=Z;else this.#J(W,this.#X,Z);return $.forEach((K)=>{this.#J(W,this.#X,K)}),this}}),this.on=(W,Z,...$)=>{for(let K of[Z].flat()){this.#X=K;for(let H of[W].flat())$.map((F)=>{this.#J(H.toUpperCase(),this.#X,F)})}return this},this.use=(W,...Z)=>{if(typeof W==="string")this.#X=W;else this.#X="*",Z.unshift(W);return Z.forEach(($)=>{this.#J(n4,this.#X,$)}),this};let{strict:J,...G}=Y;Object.assign(this,G),this.getPath=J??!0?Y.getPath??yo:Dd0}#Y(){let Y=new X({router:this.router,getPath:this.getPath});return Y.errorHandler=this.errorHandler,Y.#Q=this.#Q,Y.routes=this.routes,Y}#Q=d76;errorHandler=jd0;route(Y,Q){let J=this.basePath(Y);return Q.routes.map((G)=>{let W;if(Q.errorHandler===jd0)W=G.handler;else W=async(Z,$)=>(await ko([],Q.errorHandler)(Z,()=>G.handler(Z,$))).res,W[Ed0]=G.handler;J.#J(G.method,G.path,W)}),this}basePath(Y){let Q=this.#Y();return Q._basePath=Y3(this._basePath,Y),Q}onError=(Y)=>{return this.errorHandler=Y,this};notFound=(Y)=>{return this.#Q=Y,this};mount(Y,Q,J){let G,W;if(J)if(typeof J==="function")W=J;else if(W=J.optionHandler,J.replaceRequest===!1)G=(K)=>K;else G=J.replaceRequest;let Z=W?(K)=>{let H=W(K);return Array.isArray(H)?H:[H]}:(K)=>{let H=void 0;try{H=K.executionCtx}catch{}return[K.env,H]};G||=(()=>{let K=Y3(this._basePath,Y),H=K==="/"?0:K.length;return(F)=>{let V=new URL(F.url);return V.pathname=V.pathname.slice(H)||"/",new Request(V,F)}})();let $=async(K,H)=>{let F=await Q(G(K.req.raw),...Z(K));if(F)return F;await H()};return this.#J(n4,Y3(Y,"*"),$),this}#J(Y,Q,J){Y=Y.toUpperCase(),Q=Y3(this._basePath,Q);let G={basePath:this._basePath,path:Q,method:Y,handler:J};this.router.add(Y,Q,[J,G]),this.routes.push(G)}#W(Y,Q){if(Y instanceof Error)return this.errorHandler(Y,Q);throw Y}#G(Y,Q,J,G){if(G==="HEAD")return(async()=>new Response(null,await this.#G(Y,Q,J,"GET")))();let W=this.getPath(Y,{env:J}),Z=this.router.match(G,W),$=new Pd0(Y,{path:W,matchResult:Z,env:J,executionCtx:Q,notFoundHandler:this.#Q});if(Z[0].length===1){let H;try{H=Z[0][0][0][0]($,async()=>{$.res=await this.#Q($)})}catch(F){return this.#W(F,$)}return H instanceof Promise?H.then((F)=>F||($.finalized?$.res:this.#Q($))).catch((F)=>this.#W(F,$)):H??this.#Q($)}let K=ko(Z[0],this.errorHandler,this.#Q);return(async()=>{try{let H=await K($);if(!H.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return H.res}catch(H){return this.#W(H,$)}})()}fetch=(Y,...Q)=>{return this.#G(Y,Q[1],Q[0],Y.method)};request=(Y,Q,J,G)=>{if(Y instanceof Request)return this.fetch(Q?new Request(Y,Q):Y,J,G);return Y=Y.toString(),this.fetch(new Request(/^https?:\/\//.test(Y)?Y:`http://localhost${Y3("/",Y)}`,Q),J,G)};fire=()=>{addEventListener("fetch",(Y)=>{Y.respondWith(this.#G(Y.request,Y,void 0,Y.request.method))})}};var lL=[];function yS(X,Y){let Q=this.buildAllMatchers(),J=(G,W)=>{let Z=Q[G]||Q[n4],$=Z[2][W];if($)return $;let K=W.match(Z[0]);if(!K)return[[],lL];let H=K.indexOf("",1);return[Z[1][H],K]};return this.match=J,J(X,Y)}var bS="[^/]+",dL=".*",pL="(?:|/.*)",Q3=Symbol(),p76=new Set(".\\+*[^]$()");function c76(X,Y){if(X.length===1)return Y.length===1?X<Y?-1:1:-1;if(Y.length===1)return 1;if(X===dL||X===pL)return 1;else if(Y===dL||Y===pL)return-1;if(X===bS)return 1;else if(Y===bS)return-1;return X.length===Y.length?X<Y?-1:1:Y.length-X.length}var Id0=class X{#X;#Y;#Q=Object.create(null);insert(Y,Q,J,G,W){if(Y.length===0){if(this.#X!==void 0)throw Q3;if(W)return;this.#X=Q;return}let[Z,...$]=Y,K=Z==="*"?$.length===0?["","",dL]:["","",bS]:Z==="/*"?["","",pL]:Z.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),H;if(K){let F=K[1],V=K[2]||bS;if(F&&K[2]){if(V===".*")throw Q3;if(V=V.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(V))throw Q3}if(H=this.#Q[V],!H){if(Object.keys(this.#Q).some((q)=>q!==dL&&q!==pL))throw Q3;if(W)return;if(H=this.#Q[V]=new X,F!=="")H.#Y=G.varIndex++}if(!W&&F!=="")J.push([F,H.#Y])}else if(H=this.#Q[Z],!H){if(Object.keys(this.#Q).some((F)=>F.length>1&&F!==dL&&F!==pL))throw Q3;if(W)return;H=this.#Q[Z]=new X}H.insert($,Q,J,G,W)}buildRegExpStr(){let Q=Object.keys(this.#Q).sort(c76).map((J)=>{let G=this.#Q[J];return(typeof G.#Y==="number"?`(${J})@${G.#Y}`:p76.has(J)?`\\${J}`:J)+G.buildRegExpStr()});if(typeof this.#X==="number")Q.unshift(`#${this.#X}`);if(Q.length===0)return"";if(Q.length===1)return Q[0];return"(?:"+Q.join("|")+")"}};var Rd0=class{#X={varIndex:0};#Y=new Id0;insert(X,Y,Q){let J=[],G=[];for(let Z=0;;){let $=!1;if(X=X.replace(/\{[^}]+\}/g,(K)=>{let H=`@\\${Z}`;return G[Z]=[H,K],Z++,$=!0,H}),!$)break}let W=X.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let Z=G.length-1;Z>=0;Z--){let[$]=G[Z];for(let K=W.length-1;K>=0;K--)if(W[K].indexOf($)!==-1){W[K]=W[K].replace($,G[Z][1]);break}}return this.#Y.insert(W,Y,J,this.#X,Q),J}buildRegExp(){let X=this.#Y.buildRegExpStr();if(X==="")return[/^$/,[],[]];let Y=0,Q=[],J=[];return X=X.replace(/#(\d+)|@(\d+)|\.\*\$/g,(G,W,Z)=>{if(W!==void 0)return Q[++Y]=Number(W),"$()";if(Z!==void 0)return J[Number(Z)]=++Y,"";return""}),[new RegExp(`^${X}`),Q,J]}};var n76=[/^$/,[],Object.create(null)],Sd0=Object.create(null);function kd0(X){return Sd0[X]??=new RegExp(X==="*"?"":`^${X.replace(/\/\*$|([.\\+*[^\]$()])/g,(Y,Q)=>Q?`\\${Q}`:"(?:|/.*)")}$`)}function i76(){Sd0=Object.create(null)}function a76(X){let Y=new Rd0,Q=[];if(X.length===0)return n76;let J=X.map((H)=>[!/\*|\/:/.test(H[0]),...H]).sort(([H,F],[V,q])=>H?1:V?-1:F.length-q.length),G=Object.create(null);for(let H=0,F=-1,V=J.length;H<V;H++){let[q,z,D]=J[H];if(q)G[z]=[D.map(([L])=>[L,Object.create(null)]),lL];else F++;let N;try{N=Y.insert(z,F,q)}catch(L){throw L===Q3?new _S(z):L}if(q)continue;Q[F]=D.map(([L,w])=>{let C=Object.create(null);w-=1;for(;w>=0;w--){let[T,A]=N[w];C[T]=A}return[L,C]})}let[W,Z,$]=Y.buildRegExp();for(let H=0,F=Q.length;H<F;H++)for(let V=0,q=Q[H].length;V<q;V++){let z=Q[H][V]?.[1];if(!z)continue;let D=Object.keys(z);for(let N=0,L=D.length;N<L;N++)z[D[N]]=$[z[D[N]]]}let K=[];for(let H in Z)K[H]=Q[Z[H]];return[W,K,G]}function tq(X,Y){if(!X)return;for(let Q of Object.keys(X).sort((J,G)=>G.length-J.length))if(kd0(Q).test(Y))return[...X[Q]];return}var fS=class{name="RegExpRouter";#X;#Y;constructor(){this.#X={[n4]:Object.create(null)},this.#Y={[n4]:Object.create(null)}}add(X,Y,Q){let J=this.#X,G=this.#Y;if(!J||!G)throw Error(vS);if(!J[X])[J,G].forEach(($)=>{$[X]=Object.create(null),Object.keys($[n4]).forEach((K)=>{$[X][K]=[...$[n4][K]]})});if(Y==="/*")Y="*";let W=(Y.match(/\/:/g)||[]).length;if(/\*$/.test(Y)){let $=kd0(Y);if(X===n4)Object.keys(J).forEach((K)=>{J[K][Y]||=tq(J[K],Y)||tq(J[n4],Y)||[]});else J[X][Y]||=tq(J[X],Y)||tq(J[n4],Y)||[];Object.keys(J).forEach((K)=>{if(X===n4||X===K)Object.keys(J[K]).forEach((H)=>{$.test(H)&&J[K][H].push([Q,W])})}),Object.keys(G).forEach((K)=>{if(X===n4||X===K)Object.keys(G[K]).forEach((H)=>$.test(H)&&G[K][H].push([Q,W]))});return}let Z=SS(Y)||[Y];for(let $=0,K=Z.length;$<K;$++){let H=Z[$];Object.keys(G).forEach((F)=>{if(X===n4||X===F)G[F][H]||=[...tq(J[F],H)||tq(J[n4],H)||[]],G[F][H].push([Q,W-K+$+1])})}}match=yS;buildAllMatchers(){let X=Object.create(null);return Object.keys(this.#Y).concat(Object.keys(this.#X)).forEach((Y)=>{X[Y]||=this.#Q(Y)}),this.#X=this.#Y=void 0,i76(),X}#Q(X){let Y=[],Q=X===n4;if([this.#X,this.#Y].forEach((J)=>{let G=J[X]?Object.keys(J[X]).map((W)=>[W,J[X][W]]):[];if(G.length!==0)Q||=!0,Y.push(...G);else if(X!==n4)Y.push(...Object.keys(J[n4]).map((W)=>[W,J[n4][W]]))}),!Q)return null;else return a76(Y)}};var r76=class{name="PreparedRegExpRouter";#X;#Y;constructor(X,Y){this.#X=X,this.#Y=Y}#Q(X,Y){let Q=this.#X[X];Q[1].forEach((J)=>J&&J.push(Y)),Object.values(Q[2]).forEach((J)=>J[0].push(Y))}#J(X,Y,Q,J,G){let W=this.#X[X];if(!G)W[2][Y][0].push([Q,{}]);else J.forEach((Z)=>{if(typeof Z==="number")W[1][Z].push([Q,G]);else W[2][Z||Y][0].push([Q,G])})}add(X,Y,Q){if(!this.#X[X]){let G=this.#X[n4],W={};for(let Z in G[2])W[Z]=[G[2][Z][0].slice(),lL];this.#X[X]=[G[0],G[1].map((Z)=>Array.isArray(Z)?Z.slice():0),W]}if(Y==="/*"||Y==="*"){let G=[Q,{}];if(X===n4)for(let W in this.#X)this.#Q(W,G);else this.#Q(X,G);return}let J=this.#Y[Y];if(!J)throw Error(`Path ${Y} is not registered`);for(let[G,W]of J)if(X===n4)for(let Z in this.#X)this.#J(Z,Y,Q,G,W);else this.#J(X,Y,Q,G,W)}buildAllMatchers(){return this.#X}match=yS};var fo=class{name="SmartRouter";#X=[];#Y=[];constructor(X){this.#X=X.routers}add(X,Y,Q){if(!this.#Y)throw Error(vS);this.#Y.push([X,Y,Q])}match(X,Y){if(!this.#Y)throw Error("Fatal error");let Q=this.#X,J=this.#Y,G=Q.length,W=0,Z;for(;W<G;W++){let $=Q[W];try{for(let K=0,H=J.length;K<H;K++)$.add(...J[K]);Z=$.match(X,Y)}catch(K){if(K instanceof _S)continue;throw K}this.match=$.match.bind($),this.#X=[$],this.#Y=void 0;break}if(W===G)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,Z}get activeRouter(){if(this.#Y||this.#X.length!==1)throw Error("No active router has been determined yet.");return this.#X[0]}};var cL=Object.create(null),vd0=class X{#X;#Y;#Q;#J=0;#W=cL;constructor(Y,Q,J){if(this.#Y=J||Object.create(null),this.#X=[],Y&&Q){let G=Object.create(null);G[Y]={handler:Q,possibleKeys:[],score:0},this.#X=[G]}this.#Q=[]}insert(Y,Q,J){this.#J=++this.#J;let G=this,W=zd0(Q),Z=[];for(let $=0,K=W.length;$<K;$++){let H=W[$],F=W[$+1],V=Bd0(H,F),q=Array.isArray(V)?V[0]:H;if(q in G.#Y){if(G=G.#Y[q],V)Z.push(V[1]);continue}if(G.#Y[q]=new X,V)G.#Q.push(V),Z.push(V[1]);G=G.#Y[q]}return G.#X.push({[Y]:{handler:J,possibleKeys:Z.filter(($,K,H)=>H.indexOf($)===K),score:this.#J}}),G}#G(Y,Q,J,G){let W=[];for(let Z=0,$=Y.#X.length;Z<$;Z++){let K=Y.#X[Z],H=K[Q]||K[n4],F={};if(H!==void 0){if(H.params=Object.create(null),W.push(H),J!==cL||G&&G!==cL)for(let V=0,q=H.possibleKeys.length;V<q;V++){let z=H.possibleKeys[V],D=F[H.score];H.params[z]=G?.[z]&&!D?G[z]:J[z]??G?.[z],F[H.score]=!0}}}return W}search(Y,Q){let J=[];this.#W=cL;let W=[this],Z=_o(Q),$=[];for(let K=0,H=Z.length;K<H;K++){let F=Z[K],V=K===H-1,q=[];for(let z=0,D=W.length;z<D;z++){let N=W[z],L=N.#Y[F];if(L)if(L.#W=N.#W,V){if(L.#Y["*"])J.push(...this.#G(L.#Y["*"],Y,N.#W));J.push(...this.#G(L,Y,N.#W))}else q.push(L);for(let w=0,C=N.#Q.length;w<C;w++){let T=N.#Q[w],A=N.#W===cL?{}:{...N.#W};if(T==="*"){let y=N.#Y["*"];if(y)J.push(...this.#G(y,Y,N.#W)),y.#W=A,q.push(y);continue}let[P,j,R]=T;if(!F&&!(R instanceof RegExp))continue;let k=N.#Y[P],_=Z.slice(K).join("/");if(R instanceof RegExp){let y=R.exec(_);if(y){if(A[j]=y[0],J.push(...this.#G(k,Y,N.#W,A)),Object.keys(k.#Y).length){k.#W=A;let b=y[0].match(/\//)?.length??0;($[b]||=[]).push(k)}continue}}if(R===!0||R.test(F))if(A[j]=F,V){if(J.push(...this.#G(k,Y,A,N.#W)),k.#Y["*"])J.push(...this.#G(k.#Y["*"],Y,A,N.#W))}else k.#W=A,q.push(k)}}W=q.concat($.shift()??[])}if(J.length>1)J.sort((K,H)=>{return K.score-H.score});return[J.map(({handler:K,params:H})=>[K,H])]}};var ho=class{name="TrieRouter";#X;constructor(){this.#X=new vd0}add(X,Y,Q){let J=SS(Y);if(J){for(let G=0,W=J.length;G<W;G++)this.#X.insert(X,J[G],Q);return}this.#X.insert(X,Y,Q)}match(X,Y){return this.#X.search(X,Y)}};var p8=class extends Cd0{constructor(X={}){super(X);this.router=X.router??new fo({routers:[new fS,new ho]})}};var o76=/^[\w!#$%&'*.^`|~+-]+$/,s76=/^[ !#-:<-[\]-~]*$/,xo=(X,Y)=>{if(Y&&X.indexOf(Y)===-1)return{};let Q=X.trim().split(";"),J={};for(let G of Q){G=G.trim();let W=G.indexOf("=");if(W===-1)continue;let Z=G.substring(0,W).trim();if(Y&&Y!==Z||!o76.test(Z))continue;let $=G.substring(W+1).trim();if($.startsWith('"')&&$.endsWith('"'))$=$.slice(1,-1);if(s76.test($)){if(J[Z]=$.indexOf("%")!==-1?sq($,uL):$,Y)break}}return J};var _d0=(X,Y,Q)=>{let J=X.req.raw.headers.get("Cookie");if(typeof Y==="string"){if(!J)return;let W=Y;if(Q==="secure")W="__Secure-"+Y;else if(Q==="host")W="__Host-"+Y;return xo(J,W)[W]}if(!J)return{};return xo(J)};var yd0=(X)=>{let Q={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...X},J=((W)=>{if(typeof W==="string")if(W==="*")return()=>W;else return(Z)=>W===Z?Z:null;else if(typeof W==="function")return W;else return(Z)=>W.includes(Z)?Z:null})(Q.origin),G=((W)=>{if(typeof W==="function")return W;else if(Array.isArray(W))return()=>W;else return()=>[]})(Q.allowMethods);return async function(Z,$){function K(F,V){Z.res.headers.set(F,V)}let H=await J(Z.req.header("origin")||"",Z);if(H)K("Access-Control-Allow-Origin",H);if(Q.credentials)K("Access-Control-Allow-Credentials","true");if(Q.exposeHeaders?.length)K("Access-Control-Expose-Headers",Q.exposeHeaders.join(","));if(Z.req.method==="OPTIONS"){if(Q.origin!=="*")K("Vary","Origin");if(Q.maxAge!=null)K("Access-Control-Max-Age",Q.maxAge.toString());let F=await G(Z.req.header("origin")||"",Z);if(F.length)K("Access-Control-Allow-Methods",F.join(","));let V=Q.allowHeaders;if(!V?.length){let q=Z.req.header("Access-Control-Request-Headers");if(q)V=q.split(/\s*,\s*/)}if(V?.length)K("Access-Control-Allow-Headers",V.join(",")),Z.res.headers.append("Vary","Access-Control-Request-Headers");return Z.res.headers.delete("Content-Length"),Z.res.headers.delete("Content-Type"),new Response(null,{headers:Z.res.headers,status:204,statusText:"No Content"})}if(await $(),Q.origin!=="*")Z.header("Vary","Origin",{append:!0})}};function t76(){let{process:X,Deno:Y}=globalThis;return!(typeof Y?.noColor==="boolean"?Y.noColor:X!==void 0?"NO_COLOR"in X?.env:!1)}async function bd0(){let{navigator:X}=globalThis,Y="cloudflare:workers";return!(X!==void 0&&X.userAgent==="Cloudflare-Workers"?await(async()=>{try{return"NO_COLOR"in((await import("cloudflare:workers")).env??{})}catch{return!1}})():!t76())}var e76=(X)=>{let[Y,Q]=[",","."];return X.map((G)=>G.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+Y)).join(Q)},XW6=(X)=>{let Y=Date.now()-X;return e76([Y<1000?Y+"ms":Math.round(Y/1000)+"s"])},YW6=async(X)=>{if(await bd0())switch(X/100|0){case 5:return`\x1B[31m${X}\x1B[0m`;case 4:return`\x1B[33m${X}\x1B[0m`;case 3:return`\x1B[36m${X}\x1B[0m`;case 2:return`\x1B[32m${X}\x1B[0m`}return`${X}`};async function fd0(X,Y,Q,J,G=0,W){let Z=Y==="<--"?`${Y} ${Q} ${J}`:`${Y} ${Q} ${J} ${await YW6(G)} ${W}`;X(Z)}var hd0=(X=console.log)=>{return async function(Q,J){let{method:G,url:W}=Q.req,Z=W.slice(W.indexOf("/",8));await fd0(X,"<--",G,Z);let $=Date.now();await J(),await fd0(X,"-->",G,Z,Q.res.status,XW6($))}};var xd0=()=>{try{return performance.now()}catch{}return Date.now()},go=(X)=>{let Y={total:!0,enabled:!0,totalDescription:"Total Response Time",autoEnd:!0,crossOrigin:!1,...X};return async function(J,G){let W=[],Z=new Map;if(J.get("metric"))return await G();if(J.set("metric",{headers:W,timers:Z}),Y.total)eq(J,"total",Y.totalDescription);if(await G(),Y.total)J3(J,"total");if(Y.autoEnd)Z.forEach((K,H)=>J3(J,H));if(typeof Y.enabled==="function"?Y.enabled(J):Y.enabled){J.res.headers.append("Server-Timing",W.join(","));let K=typeof Y.crossOrigin==="function"?Y.crossOrigin(J):Y.crossOrigin;if(K)J.res.headers.append("Timing-Allow-Origin",typeof K==="string"?K:"*")}}},gd0=(X,Y,Q,J,G)=>{let W=X.get("metric");if(!W){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}if(typeof Q==="number"){let Z=Q.toFixed(G||1),$=J?`${Y};dur=${Z};desc="${J}"`:`${Y};dur=${Z}`;W.headers.push($)}else{let Z=Q?`${Y};desc="${Q}"`:`${Y}`;W.headers.push(Z)}},eq=(X,Y,Q)=>{let J=X.get("metric");if(!J){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}J.timers.set(Y,{description:Q,start:xd0()})},J3=(X,Y,Q)=>{let J=X.get("metric");if(!J){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}let G=J.timers.get(Y);if(!G){console.warn(`Timer "${Y}" does not exist!`);return}let{description:W,start:Z}=G,$=xd0()-Z;gd0(X,Y,$,W,Q),J.timers.delete(Y)};var uo=[{name:"ORGANIZATION_CREATE",description:"Create a new organization",category:"Organizations"},{name:"ORGANIZATION_LIST",description:"List organizations",category:"Organizations"},{name:"ORGANIZATION_GET",description:"View organization details",category:"Organizations"},{name:"ORGANIZATION_UPDATE",description:"Update organization",category:"Organizations"},{name:"ORGANIZATION_DELETE",description:"Delete organization",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_SETTINGS_GET",description:"View organization settings",category:"Organizations"},{name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization settings",category:"Organizations"},{name:"ORGANIZATION_MEMBER_ADD",description:"Add members",category:"Organizations"},{name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove members",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_MEMBER_LIST",description:"List members",category:"Organizations"},{name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update member roles",category:"Organizations"},{name:"COLLECTION_CONNECTIONS_CREATE",description:"Create connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_LIST",description:"List connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_GET",description:"View connection details",category:"Connections"},{name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete connections",category:"Connections",dangerous:!0},{name:"CONNECTION_TEST",description:"Test connections",category:"Connections"},{name:"DATABASES_RUN_SQL",description:"Run SQL queries",category:"Connections",dangerous:!0},{name:"COLLECTION_VIRTUAL_MCP_CREATE",description:"Create virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_LIST",description:"List virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_GET",description:"View virtual MCP details",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_UPDATE",description:"Update virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_DELETE",description:"Delete virtual MCPs",category:"Virtual MCPs",dangerous:!0},{name:"MONITORING_LOGS_LIST",description:"List monitoring logs",category:"Monitoring"},{name:"MONITORING_STATS",description:"View monitoring statistics",category:"Monitoring"},{name:"API_KEY_CREATE",description:"Create API key",category:"API Keys"},{name:"API_KEY_LIST",description:"List API keys",category:"API Keys"},{name:"API_KEY_UPDATE",description:"Update API key",category:"API Keys"},{name:"API_KEY_DELETE",description:"Delete API key",category:"API Keys",dangerous:!0},{name:"EVENT_PUBLISH",description:"Publish events",category:"Event Bus"},{name:"EVENT_SUBSCRIBE",description:"Subscribe to events",category:"Event Bus"},{name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events",category:"Event Bus"},{name:"EVENT_CANCEL",description:"Cancel recurring events",category:"Event Bus"},{name:"EVENT_ACK",description:"Acknowledge event delivery",category:"Event Bus"},{name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions",category:"Event Bus"},{name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state",category:"Event Bus"},{name:"USER_GET",description:"Get a user by id",category:"Users"},{name:"CODE_EXECUTION_SEARCH_TOOLS",description:"Search available tools by name or description",category:"Code Execution"},{name:"CODE_EXECUTION_DESCRIBE_TOOLS",description:"Get detailed schemas for specific tools",category:"Code Execution"},{name:"CODE_EXECUTION_RUN_CODE",description:"Run JavaScript code in a sandbox with tool access",category:"Code Execution",dangerous:!0},{name:"COLLECTION_THREADS_CREATE",description:"Create threads",category:"Threads"},{name:"COLLECTION_THREADS_LIST",description:"List threads",category:"Threads"},{name:"COLLECTION_THREADS_GET",description:"View thread details",category:"Threads"},{name:"COLLECTION_THREADS_UPDATE",description:"Update threads",category:"Threads"},{name:"COLLECTION_THREADS_DELETE",description:"Delete threads",category:"Threads",dangerous:!0},{name:"COLLECTION_THREAD_MESSAGES_LIST",description:"List thread messages",category:"Threads"}];function nL(){let X={Organizations:[],Connections:[],"Virtual MCPs":[],Threads:[],Monitoring:[],Users:[],"API Keys":[],"Event Bus":[],"Code Execution":[]};for(let Y of uo)X[Y.category]?.push(Y);return X}var QW6=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",JW6="[:A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]["+QW6+"]*",GW6=new RegExp("^"+JW6+"$");function ud0(X,Y){let Q=[],J=Y.exec(X);while(J){let G=[];G.startIndex=Y.lastIndex-J[0].length;let W=J.length;for(let Z=0;Z<W;Z++)G.push(J[Z]);Q.push(G),J=Y.exec(X)}return Q}var mo=function(X){let Y=GW6.exec(X);return!(Y===null||typeof Y>"u")};var WW6={allowBooleanAttributes:!1,unpairedTags:[]};function cd0(X,Y){Y=Object.assign({},WW6,Y);let Q=[],J=!1,G=!1;if(X[0]==="\uFEFF")X=X.substr(1);for(let W=0;W<X.length;W++)if(X[W]==="<"&&X[W+1]==="?"){if(W+=2,W=ld0(X,W),W.err)return W}else if(X[W]==="<"){let Z=W;if(W++,X[W]==="!"){W=dd0(X,W);continue}else{let $=!1;if(X[W]==="/")$=!0,W++;let K="";for(;W<X.length&&X[W]!==">"&&X[W]!==" "&&X[W]!=="\t"&&X[W]!==`
272
+ `.execute(X)).rows[0]?.exists)await e6`CREATE ROLE ${e6.id(Q)} NOLOGIN`.execute(X);await e6`GRANT ${e6.id(Q)} TO CURRENT_USER`.execute(X),await e6`GRANT USAGE, CREATE ON SCHEMA ${e6.id(Y)} TO ${e6.id(Q)}`.execute(X),await e6`GRANT ALL ON ALL TABLES IN SCHEMA ${e6.id(Y)} TO ${e6.id(Q)}`.execute(X),await e6`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${e6.id(Y)} TO ${e6.id(Q)}`.execute(X),await e6`ALTER DEFAULT PRIVILEGES IN SCHEMA ${e6.id(Y)} GRANT ALL ON TABLES TO ${e6.id(Q)}`.execute(X),await e6`ALTER DEFAULT PRIVILEGES IN SCHEMA ${e6.id(Y)} GRANT ALL ON SEQUENCES TO ${e6.id(Q)}`.execute(X),await e6`REVOKE ALL ON SCHEMA public FROM ${e6.id(Q)}`.execute(X)}async function eb6(X,Y,Q,J){try{return await X.transaction().execute(async(G)=>{return await e6`SET LOCAL ROLE ${e6.id(Q)}`.execute(G),await e6`SET LOCAL search_path TO ${e6.id(Y)}`.execute(G),await e6.raw(J).execute(G)})}catch(G){if(sb6(G))return await tb6(X,Y,Q),await X.transaction().execute(async(W)=>{return await e6`SET LOCAL ROLE ${e6.id(Q)}`.execute(W),await e6`SET LOCAL search_path TO ${e6.id(Y)}`.execute(W),await e6.raw(J).execute(W)});throw G}}var nb6,ab6,O51;var L51=p(()=>{a0();Z6();nb6=U.object({results:U.array(U.unknown()).optional(),success:U.boolean().optional()});ab6=U.object({sql:U.string().describe("The SQL query to run"),params:U.array(U.any()).describe("The parameters to pass to the SQL query").optional()});O51=t0({name:"DATABASES_RUN_SQL",description:"Run a SQL query against the database",inputSchema:ab6,outputSchema:U.object({result:U.array(nb6)}),handler:async(X,Y)=>{U1(Y),await Y.access.check();let Q=ib6(X.sql,X.params||[]);if(!Y.connectionId)throw Error("Connection context required for database access");let J=rb6(Y.connectionId),G=ob6(Y.connectionId);return{result:[{results:(await eb6(Y.db,J,G,Q)).rows,success:!0}]}}})});var w51,Yf6,M51;var oW=p(()=>{a0();Ob();w51=U.object({connectionId:U.string().optional().describe("Filter subscriptions by connection ID (optional)")}),Yf6=U.object({id:U.string().describe("Subscription ID"),connectionId:U.string().describe("Subscriber connection ID"),eventType:U.string().describe("Event type pattern"),publisher:U.string().nullable().describe("Publisher connection filter (null = all publishers)"),filter:U.string().nullable().describe("JSONPath filter expression"),enabled:U.boolean().describe("Whether subscription is enabled"),createdAt:U.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:U.string().datetime().describe("Updated timestamp (ISO 8601)")}),M51=U.object({subscriptions:U.array(Yf6).describe("List of subscriptions")})});var JX0;var P51=p(()=>{Z6();oW();JX0=t0({name:"EVENT_PUBLISH",description:"Publish an event to the event bus. Supports immediate, scheduled (deliverAt), and recurring (cron) delivery. The source is automatically set to the caller's connection ID.",inputSchema:_P,outputSchema:yP,handler:async(X,Y)=>{U1(Y);let Q=_1(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to publish events. Use a connection-scoped token.");let G=await Y.eventBus.publish(Q.id,J,{type:X.type,subject:X.subject,data:X.data,deliverAt:X.deliverAt,cron:X.cron});return{id:G.id,type:G.type,source:G.source,time:G.time}}})});var GX0;var A51=p(()=>{Z6();oW();GX0=t0({name:"EVENT_SUBSCRIBE",description:"Subscribe to events of a specific type. The subscriber is automatically set to the caller's connection.",inputSchema:bP,outputSchema:fP,handler:async(X,Y)=>{U1(Y);let Q=_1(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to subscribe. Use a connection-scoped token.");let G=await Y.eventBus.subscribe(Q.id,{connectionId:J,eventType:X.eventType,publisher:X.publisher,filter:X.filter});return{subscription:{id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}}}})});var WX0;var T51=p(()=>{Z6();oW();WX0=t0({name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events by removing a subscription.",inputSchema:gP,outputSchema:uP,handler:async(X,Y)=>{U1(Y);let Q=_1(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to unsubscribe. Use a connection-scoped token.");let G=await Y.eventBus.getSubscription(Q.id,X.subscriptionId);if(!G)throw Error(`Subscription not found: ${X.subscriptionId}`);if(G.connectionId!==J)throw Error("Cannot unsubscribe from a subscription owned by another connection");return{success:(await Y.eventBus.unsubscribe(Q.id,X.subscriptionId)).success,subscriptionId:X.subscriptionId}}})});var ZX0;var E51=p(()=>{Z6();oW();ZX0=t0({name:"EVENT_CANCEL",description:"Cancel a recurring event to stop future deliveries. Only the publisher can cancel their own events.",inputSchema:mP,outputSchema:lP,handler:async(X,Y)=>{U1(Y);let Q=_1(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to cancel events. Use a connection-scoped token.");if(!await Y.eventBus.getEvent(Q.id,X.eventId))throw Error(`Event not found: ${X.eventId}`);if(!(await Y.eventBus.cancelEvent(Q.id,X.eventId,J)).success)throw Error("Failed to cancel event. Either the event is already completed/failed, or you are not the publisher.");return{success:!0,eventId:X.eventId}}})});var $X0;var j51=p(()=>{Z6();oW();$X0=t0({name:"EVENT_ACK",description:"Acknowledge delivery of an event. Call after successfully processing an event received via ON_EVENTS with retryAfter.",inputSchema:dP,outputSchema:pP,handler:async(X,Y)=>{U1(Y);let Q=_1(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to acknowledge events. Use a connection-scoped token.");if(!(await Y.eventBus.ackEvent(Q.id,X.eventId,J)).success)throw Error("Failed to acknowledge event. Either the event was not found, already delivered, or you are not a subscriber.");return{success:!0,eventId:X.eventId}}})});var KX0;var C51=p(()=>{Z6();oW();KX0=t0({name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions, optionally filtered by connection ID.",inputSchema:w51,outputSchema:M51,handler:async(X,Y)=>{U1(Y);let Q=_1(Y);return await Y.access.check(),{subscriptions:(await Y.eventBus.listSubscriptions(Q.id,X.connectionId)).map((G)=>({id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}))}}})});var HX0;var I51=p(()=>{Z6();oW();HX0=t0({name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state. Creates new, deletes removed, updates changed filters. Subscriptions are identified by (eventType, publisher).",inputSchema:hP,outputSchema:xP,handler:async(X,Y)=>{U1(Y);let Q=_1(Y);await Y.access.check();let J=Y.connectionId;if(!J)throw Error("Connection ID required to sync subscriptions. Use a connection-scoped token.");let G=await Y.eventBus.syncSubscriptions(Q.id,{connectionId:J,subscriptions:X.subscriptions});return{created:G.created,updated:G.updated,deleted:G.deleted,unchanged:G.unchanged,subscriptions:G.subscriptions.map((W)=>({id:W.id,connectionId:W.connectionId,eventType:W.eventType,publisher:W.publisher,filter:W.filter,enabled:W.enabled,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt,updatedAt:W.updatedAt instanceof Date?W.updatedAt.toISOString():W.updatedAt}))}}})});var R51=p(()=>{P51();A51();T51();E51();j51();C51();I51();oW()});var FX0,Jf6,U7,S51,k51;var WB=p(()=>{a0();FX0=U.enum(["inclusion","exclusion"]).describe("Tool selection mode: 'inclusion' = include selected (default), 'exclusion' = exclude selected"),Jf6=U.object({connection_id:U.string().describe("Connection ID"),selected_tools:U.array(U.string()).nullable().describe("Selected tool names. With 'inclusion' mode: null = all tools included. With 'exclusion' mode: null = entire connection excluded"),selected_resources:U.array(U.string()).nullable().describe("Selected resource URIs or patterns. Supports * and ** wildcards for pattern matching. With 'inclusion' mode: null = all resources included."),selected_prompts:U.array(U.string()).nullable().describe("Selected prompt names. With 'inclusion' mode: null = all prompts included. With 'exclusion' mode: null = entire connection excluded.")}),U7=U.object({id:U.string().describe("Unique identifier for the virtual MCP"),title:U.string().describe("Human-readable name for the virtual MCP"),description:U.string().nullable().describe("Description of the virtual MCP"),icon:U.string().nullable().optional().describe("Icon URL for the virtual MCP"),created_at:U.string().describe("When the virtual MCP was created"),updated_at:U.string().describe("When the virtual MCP was last updated"),created_by:U.string().describe("User ID who created the virtual MCP"),updated_by:U.string().optional().describe("User ID who last updated the virtual MCP"),organization_id:U.string().describe("Organization ID this virtual MCP belongs to"),tool_selection_mode:FX0.describe("Tool selection mode: 'inclusion' = include selected, 'exclusion' = exclude selected"),status:U.enum(["active","inactive"]).describe("Current status"),metadata:U.object({instructions:U.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:U.array(Jf6).describe("Connections with their selected tools (behavior depends on tool_selection_mode)")}),S51=U.object({title:U.string().min(1).max(255).describe("Name for the virtual MCP"),description:U.string().nullable().optional().describe("Optional description"),tool_selection_mode:FX0.optional().default("inclusion").describe("Tool selection mode (defaults to 'inclusion')"),icon:U.string().nullable().optional().describe("Optional icon URL"),status:U.enum(["active","inactive"]).optional().default("active").describe("Initial status"),metadata:U.object({instructions:U.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:U.array(U.object({connection_id:U.string().describe("Connection ID"),selected_tools:U.array(U.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:U.array(U.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:U.array(U.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).describe("Connections to include/exclude (can be empty for exclusion mode)")}),k51=U.object({title:U.string().min(1).max(255).optional().describe("New name"),description:U.string().nullable().optional().describe("New description (null to clear)"),tool_selection_mode:FX0.optional().describe("New tool selection mode"),icon:U.string().nullable().optional().describe("New icon URL (null to clear)"),status:U.enum(["active","inactive"]).optional().describe("New status"),metadata:U.object({instructions:U.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:U.array(U.object({connection_id:U.string().describe("Connection ID"),selected_tools:U.array(U.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:U.array(U.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:U.array(U.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).optional().describe("New connections (replaces existing)")})});var Gf6,Wf6,VX0;var v51=p(()=>{a0();Z6();WB();Gf6=U.object({data:S51.describe("Data for the new virtual MCP")}),Wf6=U.object({item:U7.describe("The created virtual MCP entity")}),VX0=t0({name:"COLLECTION_VIRTUAL_MCP_CREATE",description:"Create a new MCP virtual MCP in the organization",inputSchema:Gf6,outputSchema:Wf6,handler:async(X,Y)=>{U1(Y);let Q=_1(Y);await Y.access.check();let J=f8(Y);if(!J)throw Error("User ID required to create virtual MCP");return{item:await Y.storage.virtualMcps.create(Q.id,J,X.data)}}})});function Zf6(X){let Y=[],Q=0;while(Q<X.length){let J=X[Q];if(J==="%")Y.push(".*");else if(J==="_")Y.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))Y.push("\\"+J);else Y.push(J);Q++}return Y.join("")}function qK(X){return typeof X==="string"||typeof X==="number"}function qX0(X,Y){let Q=Y.split("."),J=X;for(let G of Q){if(J==null||typeof J!=="object")return;J=J[G]}return J}function $f6(X,Y){return X.connections.some((Q)=>Q.connection_id===Y)}function Tb(X,Y){if("conditions"in Y){let{operator:$,conditions:K}=Y;switch($){case"and":return K.every((H)=>Tb(X,H));case"or":return K.some((H)=>Tb(X,H));case"not":return!K.every((H)=>Tb(X,H));default:return!0}}let{field:Q,operator:J,value:G}=Y,W=Q.join(".");if(W==="connection_id"){if(J!=="eq"||typeof G!=="string")return!1;return $f6(X,G)}let Z=qX0(X,W);switch(J){case"eq":return Z===G;case"gt":return qK(Z)&&qK(G)&&Z>G;case"gte":return qK(Z)&&qK(G)&&Z>=G;case"lt":return qK(Z)&&qK(G)&&Z<G;case"lte":return qK(Z)&&qK(G)&&Z<=G;case"in":return Array.isArray(G)&&G.includes(Z);case"like":if(typeof Z!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let $=Zf6(G);return new RegExp(`^${$}$`,"i").test(Z);case"contains":if(typeof Z!=="string"||typeof G!=="string")return!1;return Z.toLowerCase().includes(G.toLowerCase());default:return!0}}function Kf6(X,Y){return[...X].sort((Q,J)=>{for(let G of Y){let W=G.field.join("."),Z=qX0(Q,W),$=qX0(J,W),K=0;if(Z==null&&$==null)continue;if(Z==null)K=G.nulls==="first"?-1:1;else if($==null)K=G.nulls==="first"?1:-1;else if(typeof Z==="string"&&typeof $==="string")K=Z.localeCompare($);else if(typeof Z==="number"&&typeof $==="number")K=Z-$;else K=String(Z).localeCompare(String($));if(K!==0)return G.direction==="desc"?-K:K}return 0})}var Hf6,Ff6,UX0;var _51=p(()=>{x5();Z6();WB();Hf6=OF,Ff6=LF(U7),UX0=t0({name:"COLLECTION_VIRTUAL_MCP_LIST",description:"List all MCP virtual MCPs in the organization",inputSchema:Hf6,outputSchema:Ff6,handler:async(X,Y)=>{await Y.access.check();let Q=_1(Y),J=X.where&&!("conditions"in X.where)&&X.where.field.join(".")==="connection_id"&&X.where.operator==="eq"&&typeof X.where.value==="string"?X.where.value:void 0,W=J?await Y.storage.virtualMcps.listByConnectionId(Q.id,J):await Y.storage.virtualMcps.list(Q.id);if(X.where)W=W.filter((V)=>Tb(V,X.where));if(X.orderBy&&X.orderBy.length>0)W=Kf6(W,X.orderBy);let Z=W.length,$=X.offset??0,K=X.limit??100,H=W.slice($,$+K),F=$+K<Z;return{items:H,totalCount:Z,hasMore:F}}})});var Vf6,qf6,zX0;var y51=p(()=>{a0();Z6();WB();Vf6=U.object({id:U.string().describe("ID of the virtual MCP to retrieve")}),qf6=U.object({item:U7.nullable().describe("The retrieved virtual MCP, or null if not found")}),zX0=t0({name:"COLLECTION_VIRTUAL_MCP_GET",description:"Get an MCP virtual MCP by ID",inputSchema:Vf6,outputSchema:qf6,handler:async(X,Y)=>{U1(Y);let Q=_1(Y);await Y.access.check();let J=await Y.storage.virtualMcps.findById(X.id);if(J&&J.organization_id!==Q.id)return{item:null};if(!J)return{item:null};return{item:J}}})});var Uf6,zf6,BX0;var b51=p(()=>{a0();Z6();WB();Uf6=U.object({id:U.string().describe("ID of the virtual MCP to update"),data:k51.describe("Partial virtual MCP data to update")}),zf6=U.object({item:U7.describe("The updated virtual MCP entity")}),BX0=t0({name:"COLLECTION_VIRTUAL_MCP_UPDATE",description:"Update an MCP virtual MCP",inputSchema:Uf6,outputSchema:zf6,handler:async(X,Y)=>{U1(Y);let Q=_1(Y);await Y.access.check();let J=f8(Y);if(!J)throw Error("User ID required to update virtual MCP");let G=await Y.storage.virtualMcps.findById(X.id);if(!G)throw Error(`Virtual MCP not found: ${X.id}`);if(G.organization_id!==Q.id)throw Error(`Virtual MCP not found: ${X.id}`);return{item:await Y.storage.virtualMcps.update(X.id,J,X.data)}}})});var Bf6,Df6,DX0;var f51=p(()=>{a0();Z6();WB();Bf6=U.object({id:U.string().describe("ID of the virtual MCP to delete")}),Df6=U.object({item:U7.describe("The deleted virtual MCP entity")}),DX0=t0({name:"COLLECTION_VIRTUAL_MCP_DELETE",description:"Delete an MCP virtual MCP",inputSchema:Bf6,outputSchema:Df6,handler:async(X,Y)=>{U1(Y);let Q=_1(Y);await Y.access.check();let J=await Y.storage.virtualMcps.findById(X.id);if(!J)throw Error(`Virtual MCP not found: ${X.id}`);if(J.organization_id!==Q.id)throw Error(`Virtual MCP not found: ${X.id}`);return await Y.storage.virtualMcps.delete(X.id),{item:J}}})});var h51=p(()=>{v51();_51();y51();b51();f51()});var Of6,NX0;var x51=p(()=>{Z6();a0();Of6=U.object({id:U.string().optional().describe("Unique log identifier"),organizationId:U.string().describe("Organization ID"),connectionId:U.string().describe("Connection ID"),connectionTitle:U.string().describe("Connection display name"),toolName:U.string().describe("Name of the tool that was called"),input:U.record(U.string(),U.unknown()).describe("Redacted tool input"),output:U.record(U.string(),U.unknown()).describe("Redacted tool output"),isError:U.boolean().describe("Whether the call resulted in an error"),errorMessage:U.string().nullish().describe("Error message if applicable"),durationMs:U.number().describe("Call duration in milliseconds"),timestamp:U.string().describe("ISO 8601 timestamp of the call"),userId:U.string().nullish().describe("User who triggered the call"),requestId:U.string().describe("Unique request identifier"),userAgent:U.string().nullish().describe("Client identifier (x-mesh-client header)"),virtualMcpId:U.string().nullish().describe("Virtual MCP (Agent) ID if routed through an agent"),properties:U.record(U.string(),U.string()).nullish().describe("Custom key-value metadata attached to the log")}),NX0=t0({name:"MONITORING_LOGS_LIST",description:"List monitoring logs for tool calls in the organization",inputSchema:U.object({connectionId:U.string().optional().describe("Filter by connection ID"),virtualMcpId:U.string().optional().describe("Filter by Virtual MCP (Agent) ID"),toolName:U.string().optional().describe("Filter by tool name"),isError:U.boolean().optional().describe("Filter by error status"),startDate:U.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:U.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)"),limit:U.number().default(100).describe("Maximum number of results"),offset:U.number().default(0).describe("Offset for pagination"),properties:U.record(U.string(),U.string()).optional().describe("Filter by exact property key=value matches"),propertyKeys:U.array(U.string()).optional().describe("Filter by logs that have these property keys"),propertyPatterns:U.record(U.string(),U.string()).optional().describe("Filter by property value patterns (SQL LIKE, use % as wildcard)")}),outputSchema:U.object({logs:U.array(Of6).describe("Array of monitoring logs"),total:U.number().describe("Total number of logs matching filters"),offset:U.number().describe("Current offset for pagination"),limit:U.number().describe("Current limit for pagination")}),handler:async(X,Y)=>{let Q=_1(Y),G=X.properties||X.propertyKeys||X.propertyPatterns?{properties:X.properties,propertyKeys:X.propertyKeys,propertyPatterns:X.propertyPatterns}:void 0,W={organizationId:Q.id,connectionId:X.connectionId,virtualMcpId:X.virtualMcpId,toolName:X.toolName,isError:X.isError,startDate:X.startDate?new Date(X.startDate):void 0,endDate:X.endDate?new Date(X.endDate):void 0,limit:X.limit,offset:X.offset,propertyFilters:G},Z=await Y.storage.monitoring.query(W);return{logs:Z.logs.map(($)=>({...$,timestamp:$.timestamp instanceof Date?$.timestamp.toISOString():$.timestamp})),total:Z.total,offset:X.offset,limit:X.limit}}})});var OX0;var g51=p(()=>{Z6();a0();OX0=t0({name:"MONITORING_STATS",description:"Get aggregated statistics for tool call monitoring",inputSchema:U.object({startDate:U.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:U.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)")}),outputSchema:U.object({totalCalls:U.number().describe("Total number of tool calls"),errorRate:U.number().describe("Error rate as a decimal (0 to 1)"),avgDurationMs:U.number().describe("Average call duration in milliseconds"),errorRatePercent:U.string().describe("Error rate as a percentage string")}),handler:async(X,Y)=>{let J={organizationId:_1(Y).id,startDate:X.startDate?new Date(X.startDate):void 0,endDate:X.endDate?new Date(X.endDate):void 0},G=await Y.storage.monitoring.getStats(J);return{...G,errorRatePercent:(G.errorRate*100).toFixed(2)}}})});var u51=p(()=>{x51();g51()});var LX0;var m51=p(()=>{a0();Z6();LX0=t0({name:"ORGANIZATION_CREATE",description:"Create a new organization",inputSchema:U.object({slug:U.string().min(1).max(50).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens"),name:U.string().min(1).max(255),description:U.string().optional()}),outputSchema:U.object({id:U.string(),name:U.string(),slug:U.string(),logo:U.string().nullable().optional(),metadata:U.any().optional(),createdAt:U.string().datetime().describe("ISO 8601 timestamp"),members:U.array(U.any()).optional()}),handler:async(X,Y)=>{U1(Y),await Y.access.check();let Q=f8(Y);if(!Q)throw Error("User ID required to create organization");let J=await Y.boundAuth.organization.create({name:X.name,slug:X.slug,metadata:X.description?{description:X.description}:void 0,userId:Q});if(!J)throw Error("Failed to create organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var wX0;var l51=p(()=>{a0();Z6();wX0=t0({name:"ORGANIZATION_LIST",description:"List all organizations user has access to",inputSchema:U.object({userId:U.string().optional()}),outputSchema:U.object({organizations:U.array(U.object({id:U.string(),name:U.string(),slug:U.string(),logo:U.string().nullable().optional(),metadata:U.any().optional(),createdAt:U.string().datetime().describe("ISO 8601 timestamp")}))}),handler:async(X,Y)=>{U1(Y),await Y.access.check();let Q=f8(Y),J=X.userId||Q;if(!J)throw Error("User ID required to list organizations");return{organizations:(await Y.boundAuth.organization.list(J)).map((W)=>({...W,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt}))}}})});var MX0;var d51=p(()=>{a0();Z6();MX0=t0({name:"ORGANIZATION_GET",description:"Get organization details by slug or ID",inputSchema:U.object({}),outputSchema:U.object({id:U.string(),name:U.string(),slug:U.string(),logo:U.string().nullable().optional(),metadata:U.any().optional(),createdAt:U.string().datetime().describe("ISO 8601 timestamp"),members:U.array(U.any()).optional(),invitations:U.array(U.any()).optional()}),handler:async(X,Y)=>{U1(Y),await Y.access.check();let Q=await Y.boundAuth.organization.get();if(!Q)throw Error("No active organization found");let J=new Date,G=Q.invitations?.filter((W)=>new Date(W.expiresAt)>J);return{...Q,invitations:G,createdAt:Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt}}})});var PX0;var p51=p(()=>{a0();Z6();PX0=t0({name:"ORGANIZATION_UPDATE",description:"Update an existing organization",inputSchema:U.object({id:U.string(),slug:U.string().min(1).max(50).regex(/^[a-z0-9-]+$/).optional(),name:U.string().min(1).max(255).optional(),description:U.string().optional()}),outputSchema:U.object({id:U.string(),name:U.string(),slug:U.string(),logo:U.string().nullable().optional(),metadata:U.any().optional(),createdAt:U.string().datetime().describe("ISO 8601 timestamp")}),handler:async(X,Y)=>{U1(Y),await Y.access.check();let Q={};if(X.name)Q.name=X.name;if(X.slug)Q.slug=X.slug;if(X.description)Q.metadata={description:X.description};let J=await Y.boundAuth.organization.update({organizationId:X.id,data:Q});if(!J)throw Error("Failed to update organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var AX0;var c51=p(()=>{a0();Z6();AX0=t0({name:"ORGANIZATION_DELETE",description:"Delete an organization",inputSchema:U.object({id:U.string()}),outputSchema:U.object({success:U.boolean(),id:U.string()}),handler:async(X,Y)=>{return U1(Y),await Y.access.check(),await Y.boundAuth.organization.delete(X.id),{success:!0,id:X.id}}})});var nP;var TX0=p(()=>{a0();nP=U.object({title:U.string(),url:U.string(),icon:U.string()})});var EX0;var n51=p(()=>{a0();Z6();TX0();EX0=t0({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings",inputSchema:U.object({}),outputSchema:U.object({organizationId:U.string(),sidebar_items:U.array(nP).nullable().optional(),enabled_plugins:U.array(U.string()).nullable().optional(),createdAt:U.string().datetime().optional().describe("ISO 8601 timestamp"),updatedAt:U.string().datetime().optional().describe("ISO 8601 timestamp")}),handler:async(X,Y)=>{U1(Y),await Y.access.check();let Q=Y.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await Y.storage.organizationSettings.get(Q);if(!J)return{organizationId:Q};return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt,updatedAt:J.updatedAt instanceof Date?J.updatedAt.toISOString():J.updatedAt}}})});var jX0;var i51=p(()=>{a0();Z6();TX0();jX0=t0({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings",inputSchema:U.object({organizationId:U.string(),sidebar_items:U.array(nP).optional(),enabled_plugins:U.array(U.string()).optional()}),outputSchema:U.object({organizationId:U.string(),sidebar_items:U.array(nP).nullable().optional(),enabled_plugins:U.array(U.string()).nullable().optional(),createdAt:U.string().datetime().describe("ISO 8601 timestamp"),updatedAt:U.string().datetime().describe("ISO 8601 timestamp")}),handler:async(X,Y)=>{if(U1(Y),await Y.access.check(),Y.organization&&Y.organization.id!==X.organizationId)throw Error("Cannot update settings for a different organization");let Q=await Y.storage.organizationSettings.upsert(X.organizationId,{sidebar_items:X.sidebar_items,enabled_plugins:X.enabled_plugins});return{...Q,createdAt:Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt,updatedAt:Q.updatedAt instanceof Date?Q.updatedAt.toISOString():Q.updatedAt}}})});var CX0;var a51=p(()=>{a0();Z6();CX0=t0({name:"ORGANIZATION_MEMBER_ADD",description:"Add a member to an organization",inputSchema:U.object({organizationId:U.string().optional(),userId:U.string(),role:U.array(U.string())}),outputSchema:U.object({id:U.string(),organizationId:U.string(),userId:U.string(),role:U.union([U.string(),U.array(U.string())]),createdAt:U.string().datetime().describe("ISO 8601 timestamp")}),handler:async(X,Y)=>{U1(Y),await Y.access.check();let Q=X.organizationId||Y.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await Y.boundAuth.organization.addMember({organizationId:Q,userId:X.userId,role:X.role});if(!J)throw Error("Failed to add member");return{...J,role:J.role,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var IX0;var r51=p(()=>{a0();Z6();IX0=t0({name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove a member from an organization",inputSchema:U.object({organizationId:U.string().optional(),memberIdOrEmail:U.string()}),outputSchema:U.object({success:U.boolean(),memberIdOrEmail:U.string()}),handler:async(X,Y)=>{U1(Y),await Y.access.check();let Q=X.organizationId||Y.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");return await Y.boundAuth.organization.removeMember({organizationId:Q,memberIdOrEmail:X.memberIdOrEmail}),{success:!0,memberIdOrEmail:X.memberIdOrEmail}}})});var RX0;var o51=p(()=>{a0();Z6();RX0=t0({name:"ORGANIZATION_MEMBER_LIST",description:"List all members in an organization",inputSchema:U.object({limit:U.number().optional(),offset:U.number().optional()}),outputSchema:U.object({members:U.array(U.object({id:U.string(),organizationId:U.string(),userId:U.string(),role:U.string(),createdAt:U.string().datetime().describe("ISO 8601 timestamp"),user:U.object({id:U.string(),name:U.string(),email:U.string(),image:U.string().optional()}).optional()}))}),handler:async(X,Y)=>{U1(Y),await Y.access.check();let Q=Y.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await Y.boundAuth.organization.listMembers({organizationId:Q,limit:X.limit,offset:X.offset});return{members:(Array.isArray(J)?J:[]).map((W)=>({...W,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt}))}}})});var SX0;var s51=p(()=>{a0();Z6();SX0=t0({name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update a member's role in an organization",inputSchema:U.object({organizationId:U.string().optional(),memberId:U.string(),role:U.array(U.string())}),outputSchema:U.object({id:U.string(),organizationId:U.string(),userId:U.string(),role:U.union([U.literal("admin"),U.literal("member"),U.literal("owner")]),createdAt:U.string().datetime().describe("ISO 8601 timestamp"),user:U.object({email:U.string(),name:U.string(),image:U.string().optional()})}),handler:async(X,Y)=>{U1(Y),await Y.access.check();let Q=X.organizationId||Y.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await Y.boundAuth.organization.updateMemberRole({organizationId:Q,memberId:X.memberId,role:X.role});if(!J)throw Error("Failed to update member role");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var t51=p(()=>{m51();l51();d51();p51();c51();n51();i51();a51();r51();o51();s51()});var e51,z7,XG1,YG1;var wF=p(()=>{a0();e51=U.object({id:U.string().describe("Unique message ID"),threadId:U.string().describe("ID of the parent thread"),metadata:U.unknown().optional().describe("Optional message metadata"),parts:U.array(U.record(U.string(),U.unknown())).describe("Message content parts (AI SDK UIMessagePart format)"),role:U.enum(["user","assistant","system"]).describe("Message role"),createdAt:U.string().datetime().describe("Timestamp of creation"),updatedAt:U.string().datetime().describe("Timestamp of last update")}),z7=U.object({id:U.string().describe("Unique thread ID"),organizationId:U.string().describe("Organization this thread belongs to"),title:U.string().describe("Thread title"),description:U.string().nullable().describe("Thread description"),createdAt:U.string().datetime().describe("Timestamp of creation"),updatedAt:U.string().datetime().describe("Timestamp of last update"),hidden:U.boolean().optional().describe("Whether the thread is hidden"),createdBy:U.string().describe("User ID who created the thread"),updatedBy:U.string().nullable().describe("User ID who last updated the thread")}),XG1=U.object({id:U.string().optional().describe("Optional custom ID for the thread"),title:U.string().describe("Thread title"),description:U.string().nullish().describe("Thread description")}),YG1=U.object({title:U.string().optional().describe("New thread title"),description:U.string().nullish().describe("New thread description"),hidden:U.boolean().optional().describe("Whether the thread is hidden")})});var Mf6,Pf6,kX0;var QG1=p(()=>{a0();Z6();wF();cW();Mf6=U.object({data:XG1.describe("Data for the new thread (id is auto-generated if not provided)")}),Pf6=U.object({item:z7.describe("The created thread entity")}),kX0=t0({name:"COLLECTION_THREADS_CREATE",description:"Create a new thread in the organization",inputSchema:Mf6,outputSchema:Pf6,handler:async(X,Y)=>{U1(Y);let Q=_1(Y);await Y.access.check();let J=f8(Y);if(!J)throw Error("User ID required to create thread");let G=X.data.id??t8("thrd"),W=await Y.storage.threads.create({id:G,organizationId:Q.id,title:X.data.title,description:X.data.description,createdBy:J});return{item:{...W,hidden:W.hidden??!1}}}})});var Af6,Tf6,vX0;var JG1=p(()=>{x5();Z6();wF();a0();Af6=OF.extend({where:U.object({created_by:U.string().optional()}).optional()}),Tf6=LF(z7),vX0=t0({name:"COLLECTION_THREADS_LIST",description:"List all threads in the organization with filtering, sorting, and pagination",inputSchema:Af6,outputSchema:Tf6,handler:async(X,Y)=>{await Y.access.check();let Q=Y.auth.user?.id;if(!Q)throw Error("User ID required to list threads");let J=_1(Y),G=X.offset??0,W=X.limit??100,{threads:Z,total:$}=await Y.storage.threads.list(J.id,Q,{limit:W,offset:G}),K=G+W<$;return{items:Z.map((H)=>({...H,hidden:H.hidden??!1})),totalCount:$,hasMore:K}}})});var Ef6,_X0;var GG1=p(()=>{x5();Z6();wF();Ef6=SP(z7),_X0=t0({name:"COLLECTION_THREADS_GET",description:"Get thread details by ID",inputSchema:RP,outputSchema:Ef6,handler:async(X,Y)=>{U1(Y);let Q=_1(Y);await Y.access.check();let J=await Y.storage.threads.get(X.id);if(!J||J.organizationId!==Q.id)return{item:null};return{item:{...J,hidden:J.hidden??!1}}}})});var jf6,Cf6,yX0;var WG1=p(()=>{a0();Z6();wF();jf6=U.object({id:U.string().describe("ID of the thread to update"),data:YG1.describe("Partial thread data to update")}),Cf6=U.object({item:z7.describe("The updated thread entity")}),yX0=t0({name:"COLLECTION_THREADS_UPDATE",description:"Update an existing thread in the organization",inputSchema:jf6,outputSchema:Cf6,handler:async(X,Y)=>{U1(Y);let Q=_1(Y);await Y.access.check();let J=f8(Y);if(!J)throw Error("User ID required to update thread");let{id:G,data:W}=X,Z=await Y.storage.threads.get(G);if(!Z||Z.organizationId!==Q.id)throw Error("Thread not found in organization");let $=await Y.storage.threads.update(G,{title:W.title,description:W.description,hidden:W.hidden,updatedBy:J});return{item:{...$,hidden:$.hidden??!1}}}})});var bX0;var ZG1=p(()=>{x5();Z6();wF();bX0=t0({name:"COLLECTION_THREADS_DELETE",description:"Delete a thread",inputSchema:kP,outputSchema:vP(z7),handler:async(X,Y)=>{U1(Y);let Q=_1(Y);await Y.access.check();let J=await Y.storage.threads.get(X.id);if(!J)throw Error(`Thread not found: ${X.id}`);if(J.organizationId!==Q.id)throw Error(`Thread not found: ${X.id}`);return await Y.storage.threads.delete(X.id),{item:{...J,hidden:J.hidden??!1}}}})});var If6,Rf6,fX0;var $G1=p(()=>{a0();Z6();wF();If6=U.object({threadId:U.string().describe("ID of the thread to list messages for"),limit:U.number().optional().describe("Maximum number of messages to return"),offset:U.number().optional().describe("Number of messages to skip")}),Rf6=U.object({items:U.array(e51).describe("List of thread messages"),totalCount:U.number().describe("Total number of messages in the thread"),hasMore:U.boolean().describe("Whether there are more messages available")}),fX0=t0({name:"COLLECTION_THREAD_MESSAGES_LIST",description:"List all messages for a specific thread",inputSchema:If6,outputSchema:Rf6,handler:async(X,Y)=>{let Q=_1(Y);await Y.access.check();let J=await Y.storage.threads.get(X.threadId);if(!J||J.organizationId!==Q.id)throw Error("Thread not found in organization");let G=X.offset??0,W=X.limit??100,{messages:Z,total:$}=await Y.storage.threads.listMessages(X.threadId,{limit:W,offset:G}),K=G+W<$;return{items:Z,totalCount:$,hasMore:K}}})});var KG1=p(()=>{QG1();JG1();GG1();WG1();ZG1();$G1()});var kf6,vf6,hX0;var HG1=p(()=>{a0();Z6();kf6=U.object({id:U.string().min(1)}),vf6=U.object({user:U.object({id:U.string(),name:U.string(),email:U.string(),image:U.string().nullable()}).nullable()}),hX0=t0({name:"USER_GET",description:"Get a user by id (restricted to shared organizations)",inputSchema:kf6,outputSchema:vf6,handler:async(X,Y)=>{await Y.access.check(),U1(Y);let Q=f8(Y);if(!Q)throw Error("Authentication required");let J=await Y.storage.users.findById(X.id,Q);if(!J)return{user:null};return{user:{id:J.id,name:J.name,email:J.email,image:J.image??null}}}})});var FG1=p(()=>{HG1()});var qG1={};A8(qG1,{managementMCP:()=>xX0,ALL_TOOLS:()=>VG1});var VG1,xX0=(X)=>{let Y=VG1.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema,outputSchema:J.outputSchema,handler:async(G)=>{return X.access.setToolName(J.name),await J.execute(G,X)}}));return AQ1({name:"mcp-mesh-management",version:"1.0.0"}).withTools(Y).build()};var gX0=p(()=>{TQ1();xQ1();RJ1();B51();L51();R51();h51();u51();t51();KG1();FG1();VG1=[LX0,wX0,MX0,PX0,AX0,EX0,jX0,CX0,IX0,RX0,SX0,d80,o80,s80,XX0,YX0,QX0,VX0,UX0,zX0,BX0,DX0,O51,NX0,OX0,N80,L80,w80,O80,JX0,GX0,WX0,ZX0,$X0,KX0,HX0,hX0,u80,m80,l80,kX0,vX0,_X0,yX0,bX0,fX0]});var zY0=I((Ns4,aW1)=>{var{defineProperty:UY0,getOwnPropertyDescriptor:nx6,getOwnPropertyNames:ix6}=Object,ax6=Object.prototype.hasOwnProperty,rx6=(X,Y)=>{for(var Q in Y)UY0(X,Q,{get:Y[Q],enumerable:!0})},ox6=(X,Y,Q,J)=>{if(Y&&typeof Y==="object"||typeof Y==="function"){for(let G of ix6(Y))if(!ax6.call(X,G)&&G!==Q)UY0(X,G,{get:()=>Y[G],enumerable:!(J=nx6(Y,G))||J.enumerable})}return X},sx6=(X)=>ox6(UY0({},"__esModule",{value:!0}),X),nW1={};rx6(nW1,{SYMBOL_FOR_REQ_CONTEXT:()=>iW1,getContext:()=>tx6});aW1.exports=sx6(nW1);var iW1=Symbol.for("@vercel/request-context");function tx6(){return globalThis[iW1]?.get?.()??{}}});var YA=I((Os4,sW1)=>{var{defineProperty:BY0,getOwnPropertyDescriptor:ex6,getOwnPropertyNames:Xg6}=Object,Yg6=Object.prototype.hasOwnProperty,Qg6=(X,Y)=>{for(var Q in Y)BY0(X,Q,{get:Y[Q],enumerable:!0})},Jg6=(X,Y,Q,J)=>{if(Y&&typeof Y==="object"||typeof Y==="function"){for(let G of Xg6(Y))if(!Yg6.call(X,G)&&G!==Q)BY0(X,G,{get:()=>Y[G],enumerable:!(J=ex6(Y,G))||J.enumerable})}return X},Gg6=(X)=>Jg6(BY0({},"__esModule",{value:!0}),X),rW1={};Qg6(rW1,{VercelOidcTokenError:()=>oW1});sW1.exports=Gg6(rW1);class oW1 extends Error{constructor(X,Y){super(X);this.name="VercelOidcTokenError",this.cause=Y}toString(){if(this.cause)return`${this.name}: ${this.message}: ${this.cause}`;return`${this.name}: ${this.message}`}}});var YZ1=I((Ls4,XZ1)=>{var{create:Wg6,defineProperty:xb,getOwnPropertyDescriptor:Zg6,getOwnPropertyNames:$g6,getPrototypeOf:Kg6}=Object,Hg6=Object.prototype.hasOwnProperty,Fg6=(X,Y)=>{for(var Q in Y)xb(X,Q,{get:Y[Q],enumerable:!0})},tW1=(X,Y,Q,J)=>{if(Y&&typeof Y==="object"||typeof Y==="function"){for(let G of $g6(Y))if(!Hg6.call(X,G)&&G!==Q)xb(X,G,{get:()=>Y[G],enumerable:!(J=Zg6(Y,G))||J.enumerable})}return X},NY0=(X,Y,Q)=>(Q=X!=null?Wg6(Kg6(X)):{},tW1(Y||!X||!X.__esModule?xb(Q,"default",{value:X,enumerable:!0}):Q,X)),Vg6=(X)=>tW1(xb({},"__esModule",{value:!0}),X),eW1={};Fg6(eW1,{findRootDir:()=>zg6,getUserDataDir:()=>Bg6});XZ1.exports=Vg6(eW1);var QA=NY0(z0("path")),qg6=NY0(z0("fs")),DY0=NY0(z0("os")),Ug6=YA();function zg6(){try{let X=process.cwd();while(X!==QA.default.dirname(X)){let Y=QA.default.join(X,".vercel");if(qg6.default.existsSync(Y))return X;X=QA.default.dirname(X)}}catch(X){throw new Ug6.VercelOidcTokenError("Token refresh only supported in node server environments")}return null}function Bg6(){if(process.env.XDG_DATA_HOME)return process.env.XDG_DATA_HOME;switch(DY0.default.platform()){case"darwin":return QA.default.join(DY0.default.homedir(),"Library/Application Support");case"linux":return QA.default.join(DY0.default.homedir(),".local/share");case"win32":if(process.env.LOCALAPPDATA)return process.env.LOCALAPPDATA;return null;default:return null}}});var KZ1=I((ws4,$Z1)=>{var{create:Dg6,defineProperty:gb,getOwnPropertyDescriptor:Ng6,getOwnPropertyNames:Og6,getPrototypeOf:Lg6}=Object,wg6=Object.prototype.hasOwnProperty,Mg6=(X,Y)=>{for(var Q in Y)gb(X,Q,{get:Y[Q],enumerable:!0})},QZ1=(X,Y,Q,J)=>{if(Y&&typeof Y==="object"||typeof Y==="function"){for(let G of Og6(Y))if(!wg6.call(X,G)&&G!==Q)gb(X,G,{get:()=>Y[G],enumerable:!(J=Ng6(Y,G))||J.enumerable})}return X},JZ1=(X,Y,Q)=>(Q=X!=null?Dg6(Lg6(X)):{},QZ1(Y||!X||!X.__esModule?gb(Q,"default",{value:X,enumerable:!0}):Q,X)),Pg6=(X)=>QZ1(gb({},"__esModule",{value:!0}),X),GZ1={};Mg6(GZ1,{isValidAccessToken:()=>jg6,readAuthConfig:()=>Tg6,writeAuthConfig:()=>Eg6});$Z1.exports=Pg6(GZ1);var JA=JZ1(z0("fs")),WZ1=JZ1(z0("path")),Ag6=ub();function ZZ1(){let X=(0,Ag6.getVercelDataDir)();if(!X)throw Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);return WZ1.join(X,"auth.json")}function Tg6(){try{let X=ZZ1();if(!JA.existsSync(X))return null;let Y=JA.readFileSync(X,"utf8");if(!Y)return null;return JSON.parse(Y)}catch(X){return null}}function Eg6(X){let Y=ZZ1(),Q=WZ1.dirname(Y);if(!JA.existsSync(Q))JA.mkdirSync(Q,{mode:504,recursive:!0});JA.writeFileSync(Y,JSON.stringify(X,null,2),{mode:384})}function jg6(X){if(!X.token)return!1;if(typeof X.expiresAt!=="number")return!0;let Y=Math.floor(Date.now()/1000);return X.expiresAt>=Y}});var qZ1=I((Ms4,VZ1)=>{var{defineProperty:wY0,getOwnPropertyDescriptor:Cg6,getOwnPropertyNames:Ig6}=Object,Rg6=Object.prototype.hasOwnProperty,Sg6=(X,Y)=>{for(var Q in Y)wY0(X,Q,{get:Y[Q],enumerable:!0})},kg6=(X,Y,Q,J)=>{if(Y&&typeof Y==="object"||typeof Y==="function"){for(let G of Ig6(Y))if(!Rg6.call(X,G)&&G!==Q)wY0(X,G,{get:()=>Y[G],enumerable:!(J=Cg6(Y,G))||J.enumerable})}return X},vg6=(X)=>kg6(wY0({},"__esModule",{value:!0}),X),HZ1={};Sg6(HZ1,{processTokenResponse:()=>hg6,refreshTokenRequest:()=>fg6});VZ1.exports=vg6(HZ1);var OY0=z0("os"),_g6="https://vercel.com",yg6="cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp",FZ1=`@vercel/oidc node-${process.version} ${(0,OY0.platform)()} (${(0,OY0.arch)()}) ${(0,OY0.hostname)()}`,LY0=null;async function bg6(){if(LY0)return LY0;let X=`${_g6}/.well-known/openid-configuration`,Y=await fetch(X,{headers:{"user-agent":FZ1}});if(!Y.ok)throw Error("Failed to discover OAuth endpoints");let Q=await Y.json();if(!Q||typeof Q.token_endpoint!=="string")throw Error("Invalid OAuth discovery response");let J=Q.token_endpoint;return LY0=J,J}async function fg6(X){let Y=await bg6();return await fetch(Y,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":FZ1},body:new URLSearchParams({client_id:yg6,grant_type:"refresh_token",...X})})}async function hg6(X){let Y=await X.json();if(!X.ok){let Q=typeof Y==="object"&&Y&&"error"in Y?String(Y.error):"Token refresh failed";return[Error(Q)]}if(typeof Y!=="object"||Y===null)return[Error("Invalid token response")];if(typeof Y.access_token!=="string")return[Error("Missing access_token in response")];if(Y.token_type!=="Bearer")return[Error("Invalid token_type in response")];if(typeof Y.expires_in!=="number")return[Error("Missing expires_in in response")];return[null,Y]}});var ub=I((Ps4,NZ1)=>{var{create:xg6,defineProperty:mb,getOwnPropertyDescriptor:gg6,getOwnPropertyNames:ug6,getPrototypeOf:mg6}=Object,lg6=Object.prototype.hasOwnProperty,dg6=(X,Y)=>{for(var Q in Y)mb(X,Q,{get:Y[Q],enumerable:!0})},zZ1=(X,Y,Q,J)=>{if(Y&&typeof Y==="object"||typeof Y==="function"){for(let G of ug6(Y))if(!lg6.call(X,G)&&G!==Q)mb(X,G,{get:()=>Y[G],enumerable:!(J=gg6(Y,G))||J.enumerable})}return X},BZ1=(X,Y,Q)=>(Q=X!=null?xg6(mg6(X)):{},zZ1(Y||!X||!X.__esModule?mb(Q,"default",{value:X,enumerable:!0}):Q,X)),pg6=(X)=>zZ1(mb({},"__esModule",{value:!0}),X),DZ1={};dg6(DZ1,{assertVercelOidcTokenResponse:()=>MY0,findProjectInfo:()=>ag6,getTokenPayload:()=>sg6,getVercelCliToken:()=>ng6,getVercelDataDir:()=>cg6,getVercelOidcToken:()=>ig6,isExpired:()=>tg6,loadToken:()=>og6,saveToken:()=>rg6});NZ1.exports=pg6(DZ1);var GA=BZ1(z0("path")),IF=BZ1(z0("fs")),VB=YA(),lb=YZ1(),FB=KZ1(),UZ1=qZ1();function cg6(){let Y=(0,lb.getUserDataDir)();if(!Y)return null;return GA.join(Y,"com.vercel.cli")}async function ng6(){let X=(0,FB.readAuthConfig)();if(!X)return null;if((0,FB.isValidAccessToken)(X))return X.token||null;if(!X.refreshToken)return(0,FB.writeAuthConfig)({}),null;try{let Y=await(0,UZ1.refreshTokenRequest)({refresh_token:X.refreshToken}),[Q,J]=await(0,UZ1.processTokenResponse)(Y);if(Q||!J)return(0,FB.writeAuthConfig)({}),null;let G={token:J.access_token,expiresAt:Math.floor(Date.now()/1000)+J.expires_in};if(J.refresh_token)G.refreshToken=J.refresh_token;return(0,FB.writeAuthConfig)(G),G.token??null}catch(Y){return(0,FB.writeAuthConfig)({}),null}}async function ig6(X,Y,Q){let J=`https://api.vercel.com/v1/projects/${Y}/token?source=vercel-oidc-refresh${Q?`&teamId=${Q}`:""}`,G=await fetch(J,{method:"POST",headers:{Authorization:`Bearer ${X}`}});if(!G.ok)throw new VB.VercelOidcTokenError(`Failed to refresh OIDC token: ${G.statusText}`);let W=await G.json();return MY0(W),W}function MY0(X){if(!X||typeof X!=="object")throw TypeError("Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again");if(!("token"in X)||typeof X.token!=="string")throw TypeError("Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again")}function ag6(){let X=(0,lb.findRootDir)();if(!X)throw new VB.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");let Y=GA.join(X,".vercel","project.json");if(!IF.existsSync(Y))throw new VB.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");let Q=JSON.parse(IF.readFileSync(Y,"utf8"));if(typeof Q.projectId!=="string"&&typeof Q.orgId!=="string")throw TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");return{projectId:Q.projectId,teamId:Q.orgId}}function rg6(X,Y){let Q=(0,lb.getUserDataDir)();if(!Q)throw new VB.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let J=GA.join(Q,"com.vercel.token",`${Y}.json`),G=JSON.stringify(X);IF.mkdirSync(GA.dirname(J),{mode:504,recursive:!0}),IF.writeFileSync(J,G),IF.chmodSync(J,432);return}function og6(X){let Y=(0,lb.getUserDataDir)();if(!Y)throw new VB.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let Q=GA.join(Y,"com.vercel.token",`${X}.json`);if(!IF.existsSync(Q))return null;let J=JSON.parse(IF.readFileSync(Q,"utf8"));return MY0(J),J}function sg6(X){let Y=X.split(".");if(Y.length!==3)throw new VB.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again");let Q=Y[1].replace(/-/g,"+").replace(/_/g,"/"),J=Q.padEnd(Q.length+(4-Q.length%4)%4,"=");return JSON.parse(Buffer.from(J,"base64").toString("utf8"))}function tg6(X){return X.exp*1000<Date.now()}});var wZ1=I((As4,LZ1)=>{var{defineProperty:AY0,getOwnPropertyDescriptor:eg6,getOwnPropertyNames:Xu6}=Object,Yu6=Object.prototype.hasOwnProperty,Qu6=(X,Y)=>{for(var Q in Y)AY0(X,Q,{get:Y[Q],enumerable:!0})},Ju6=(X,Y,Q,J)=>{if(Y&&typeof Y==="object"||typeof Y==="function"){for(let G of Xu6(Y))if(!Yu6.call(X,G)&&G!==Q)AY0(X,G,{get:()=>Y[G],enumerable:!(J=eg6(Y,G))||J.enumerable})}return X},Gu6=(X)=>Ju6(AY0({},"__esModule",{value:!0}),X),OZ1={};Qu6(OZ1,{refreshToken:()=>Wu6});LZ1.exports=Gu6(OZ1);var PY0=YA(),RF=ub();async function Wu6(){let{projectId:X,teamId:Y}=(0,RF.findProjectInfo)(),Q=(0,RF.loadToken)(X);if(!Q||(0,RF.isExpired)((0,RF.getTokenPayload)(Q.token))){let J=await(0,RF.getVercelCliToken)();if(!J)throw new PY0.VercelOidcTokenError("Failed to refresh OIDC token: Log in to Vercel CLI and link your project with `vc link`");if(!X)throw new PY0.VercelOidcTokenError("Failed to refresh OIDC token: Try re-linking your project with `vc link`");if(Q=await(0,RF.getVercelOidcToken)(J,X,Y),!Q)throw new PY0.VercelOidcTokenError("Failed to refresh OIDC token");(0,RF.saveToken)(Q,X)}process.env.VERCEL_OIDC_TOKEN=Q.token;return}});var AZ1=I((Ts4,PZ1)=>{var{defineProperty:EY0,getOwnPropertyDescriptor:Zu6,getOwnPropertyNames:$u6}=Object,Ku6=Object.prototype.hasOwnProperty,Hu6=(X,Y)=>{for(var Q in Y)EY0(X,Q,{get:Y[Q],enumerable:!0})},Fu6=(X,Y,Q,J)=>{if(Y&&typeof Y==="object"||typeof Y==="function"){for(let G of $u6(Y))if(!Ku6.call(X,G)&&G!==Q)EY0(X,G,{get:()=>Y[G],enumerable:!(J=Zu6(Y,G))||J.enumerable})}return X},Vu6=(X)=>Fu6(EY0({},"__esModule",{value:!0}),X),MZ1={};Hu6(MZ1,{getVercelOidcToken:()=>zu6,getVercelOidcTokenSync:()=>TY0});PZ1.exports=Vu6(MZ1);var qu6=zY0(),Uu6=YA();async function zu6(){let X="",Y;try{X=TY0()}catch(Q){Y=Q}try{let[{getTokenPayload:Q,isExpired:J},{refreshToken:G}]=await Promise.all([await Promise.resolve().then(() => E6(ub())),await Promise.resolve().then(() => E6(wZ1()))]);if(!X||J(Q(X)))await G(),X=TY0()}catch(Q){let J=Y instanceof Error?Y.message:"";if(Q instanceof Error)J=`${J}
273
+ ${Q.message}`;if(J)throw new Uu6.VercelOidcTokenError(J);throw Q}return X}function TY0(){let X=(0,qu6.getContext)().headers?.["x-vercel-oidc-token"]??process.env.VERCEL_OIDC_TOKEN;if(!X)throw Error("The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?");return X}});var CY0=I((Es4,jZ1)=>{var{defineProperty:jY0,getOwnPropertyDescriptor:Bu6,getOwnPropertyNames:Du6}=Object,Nu6=Object.prototype.hasOwnProperty,Ou6=(X,Y)=>{for(var Q in Y)jY0(X,Q,{get:Y[Q],enumerable:!0})},Lu6=(X,Y,Q,J)=>{if(Y&&typeof Y==="object"||typeof Y==="function"){for(let G of Du6(Y))if(!Nu6.call(X,G)&&G!==Q)jY0(X,G,{get:()=>Y[G],enumerable:!(J=Bu6(Y,G))||J.enumerable})}return X},wu6=(X)=>Lu6(jY0({},"__esModule",{value:!0}),X),EZ1={};Ou6(EZ1,{getContext:()=>Mu6.getContext,getVercelOidcToken:()=>TZ1.getVercelOidcToken,getVercelOidcTokenSync:()=>TZ1.getVercelOidcTokenSync});jZ1.exports=wu6(EZ1);var TZ1=AZ1(),Mu6=zY0()});var Pj=E6(K1(),1),Yy0=E6(n_0(),1),Qy0=E6(Ud(),1),Jy0=E6(ml(),1),zd=new Qy0.PrometheusExporter({preventServerStart:!0}),As1=new Yy0.NodeSDK({serviceName:"mcp-mesh",traceExporter:new Jy0.OTLPTraceExporter({url:process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT||process.env.OTEL_EXPORTER_OTLP_ENDPOINT||"http://localhost:4318/v1/traces"}),metricReader:zd});As1.start();var HN=Pj.trace.getTracer("mcp-mesh","1.0.0"),Aj=Pj.metrics.getMeter("mcp-mesh","1.0.0");var CZ=class extends Error{res;status;constructor(X=500,Y){super(Y?.message,{cause:Y?.cause});this.res=Y?.res,this.status=X}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}};var Gy0=["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"],Ts1=/^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/,Es1=(X,Y)=>{if(!X)return{};let Q=new Headers(X.headers);if(Y){let J=Q.get("connection");if(J){let G=J.split(",").map((Z)=>Z.trim()),W=G.filter((Z)=>!Ts1.test(Z));if(W.length>0)throw new CZ(400,{message:`Invalid Connection header value: ${W.join(", ")}`});G.forEach((Z)=>{Q.delete(Z)})}}return Gy0.forEach((J)=>{Q.delete(J)}),{method:X.method,body:X.body,duplex:X.body?"half":void 0,headers:Q,signal:X.signal}},js1=(X)=>{if(!X.headers||Array.isArray(X.headers)||X.headers instanceof Headers)return X;let Y=new Headers;for(let[Q,J]of Object.entries(X.headers))if(J==null)Y.delete(Q);else Y.set(Q,J);return X.headers=Y,X},Wy0=async(X,Y)=>{let{raw:Q,customFetch:J,strictConnectionProcessing:G=!1,...W}=Y instanceof Request?{raw:Y}:Y??{},Z=new Request(X,{...Es1(Q,G),...js1(W)});Z.headers.delete("accept-encoding");let $=await(J||fetch)(Z),K=new Headers($.headers);if(Gy0.forEach((H)=>{K.delete(H)}),K.has("content-encoding"))K.delete("content-encoding"),K.delete("content-length");return new Response($.body,{status:$.status,statusText:$.statusText,headers:K})};var Zy0=(X)=>(Y)=>{let Q=new URL(Y.req.raw.url),J=new URL(X);return J.pathname=Q.pathname,J.search=Q.search,Wy0(J,{raw:Y.req.raw,headers:{...Y.req.raw.headers}})};import{resolve as FN,dirname as Cs1,join as Is1,extname as Rs1}from"path";var Ss1="http://localhost:4000",ks1="./dist/client";function vs1(X,Y){let Q=FN(Y),J=FN(X);return J===Q||J.startsWith(Q+"/")}function _s1({requestPath:X,clientDir:Y}){let Q=X.startsWith("/")?X.slice(1):X,J=FN(Y,Q);if(!vs1(J,Y))return null;return J}function $y0(X,Y="../client"){let Q=new URL(X),J=Cs1(Q.pathname);return FN(J,Y)}function Ky0(X={}){let{env:Y="production",devServerUrl:Q=Ss1,clientDir:J=ks1,isServerPath:G=()=>!1}=X;if(Y==="development"){let W=Zy0(Q);return async function($){let K=new URL($.url);if(G(K.pathname))return null;let H={req:{raw:$,url:$.url}};return W(H)}}return async function(Z){if(Z.method!=="GET")return null;let $=new URL(Z.url),K;try{K=decodeURIComponent($.pathname)}catch{return null}if(G(K))return null;let H=_s1({requestPath:K,clientDir:J});if(!H)return null;let F=Is1(H,"index.html"),V=FN(J,"index.html"),q=Z.headers.get("accept"),D=q?.includes("text/html")||q?.includes("*/*")&&["",".html"].includes(Rs1(H))?[F,V]:[];for(let N of[H,...D])try{let L=Bun.file(N);if(await L.exists())return new Response(L)}catch{}return null}}var Hy0="https://api.decocms.com/mcp/registry";function Fy0(X){if(!X)return!1;try{return new URL(X).host==="api.decocms.com"&&X!=="https://api.decocms.com/mcp/registry"}catch{return!1}}gL();var DH1=E6(Ud(),1);var ko=(X,Y,Q)=>{return(J,G)=>{let W=-1;return Z(0);async function Z($){if($<=W)throw Error("next() called multiple times");W=$;let K,H=!1,F;if(X[$])F=X[$][0][0],J.req.routeIndex=$;else F=$===X.length&&G||void 0;if(F)try{K=await F(J,()=>Z($+1))}catch(V){if(V instanceof Error&&Y)J.error=V,K=await Y(V,J),H=!0;else throw V}else if(J.finalized===!1&&Q)K=await Q(J);if(K&&(J.finalized===!1||H))J.res=K;return J}}};var qd0=Symbol();var Ud0=async(X,Y=Object.create(null))=>{let{all:Q=!1,dot:J=!1}=Y,W=(X instanceof IS?X.raw.headers:X.headers).get("Content-Type");if(W?.startsWith("multipart/form-data")||W?.startsWith("application/x-www-form-urlencoded"))return b76(X,{all:Q,dot:J});return{}};async function b76(X,Y){let Q=await X.formData();if(Q)return f76(Q,Y);return{}}function f76(X,Y){let Q=Object.create(null);if(X.forEach((J,G)=>{if(!(Y.all||G.endsWith("[]")))Q[G]=J;else h76(Q,G,J)}),Y.dot)Object.entries(Q).forEach(([J,G])=>{if(J.includes("."))x76(Q,J,G),delete Q[J]});return Q}var h76=(X,Y,Q)=>{if(X[Y]!==void 0)if(Array.isArray(X[Y]))X[Y].push(Q);else X[Y]=[X[Y],Q];else if(!Y.endsWith("[]"))X[Y]=Q;else X[Y]=[Q]},x76=(X,Y,Q)=>{let J=X,G=Y.split(".");G.forEach((W,Z)=>{if(Z===G.length-1)J[W]=Q;else{if(!J[W]||typeof J[W]!=="object"||Array.isArray(J[W])||J[W]instanceof File)J[W]=Object.create(null);J=J[W]}})};var _o=(X)=>{let Y=X.split("/");if(Y[0]==="")Y.shift();return Y},zd0=(X)=>{let{groups:Y,path:Q}=g76(X),J=_o(Q);return u76(J,Y)},g76=(X)=>{let Y=[];return X=X.replace(/\{[^}]+\}/g,(Q,J)=>{let G=`@${J}`;return Y.push([G,Q]),G}),{groups:Y,path:X}},u76=(X,Y)=>{for(let Q=Y.length-1;Q>=0;Q--){let[J]=Y[Q];for(let G=X.length-1;G>=0;G--)if(X[G].includes(J)){X[G]=X[G].replace(J,Y[Q][1]);break}}return X},RS={},Bd0=(X,Y)=>{if(X==="*")return"*";let Q=X.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(Q){let J=`${X}#${Y}`;if(!RS[J])if(Q[2])RS[J]=Y&&Y[0]!==":"&&Y[0]!=="*"?[J,Q[1],new RegExp(`^${Q[2]}(?=/${Y})`)]:[X,Q[1],new RegExp(`^${Q[2]}$`)];else RS[J]=[X,Q[1],!0];return RS[J]}return null},sq=(X,Y)=>{try{return Y(X)}catch{return X.replace(/(?:%[0-9A-Fa-f]{2})+/g,(Q)=>{try{return Y(Q)}catch{return Q}})}},m76=(X)=>sq(X,decodeURI),yo=(X)=>{let Y=X.url,Q=Y.indexOf("/",Y.indexOf(":")+4),J=Q;for(;J<Y.length;J++){let G=Y.charCodeAt(J);if(G===37){let W=Y.indexOf("?",J),Z=Y.slice(Q,W===-1?void 0:W);return m76(Z.includes("%25")?Z.replace(/%25/g,"%2525"):Z)}else if(G===63)break}return Y.slice(Q,J)};var Dd0=(X)=>{let Y=yo(X);return Y.length>1&&Y.at(-1)==="/"?Y.slice(0,-1):Y},Y3=(X,Y,...Q)=>{if(Q.length)Y=Y3(Y,...Q);return`${X?.[0]==="/"?"":"/"}${X}${Y==="/"?"":`${X?.at(-1)==="/"?"":"/"}${Y?.[0]==="/"?Y.slice(1):Y}`}`},SS=(X)=>{if(X.charCodeAt(X.length-1)!==63||!X.includes(":"))return null;let Y=X.split("/"),Q=[],J="";return Y.forEach((G)=>{if(G!==""&&!/\:/.test(G))J+="/"+G;else if(/\:/.test(G))if(/\?/.test(G)){if(Q.length===0&&J==="")Q.push("/");else Q.push(J);let W=G.replace("?","");J+="/"+W,Q.push(J)}else J+="/"+G}),Q.filter((G,W,Z)=>Z.indexOf(G)===W)},vo=(X)=>{if(!/[%+]/.test(X))return X;if(X.indexOf("+")!==-1)X=X.replace(/\+/g," ");return X.indexOf("%")!==-1?sq(X,uL):X},Nd0=(X,Y,Q)=>{let J;if(!Q&&Y&&!/[%+]/.test(Y)){let Z=X.indexOf("?",8);if(Z===-1)return;if(!X.startsWith(Y,Z+1))Z=X.indexOf(`&${Y}`,Z+1);while(Z!==-1){let $=X.charCodeAt(Z+Y.length+1);if($===61){let K=Z+Y.length+2,H=X.indexOf("&",K);return vo(X.slice(K,H===-1?void 0:H))}else if($==38||isNaN($))return"";Z=X.indexOf(`&${Y}`,Z+1)}if(J=/[%+]/.test(X),!J)return}let G={};J??=/[%+]/.test(X);let W=X.indexOf("?",8);while(W!==-1){let Z=X.indexOf("&",W+1),$=X.indexOf("=",W);if($>Z&&Z!==-1)$=-1;let K=X.slice(W+1,$===-1?Z===-1?void 0:Z:$);if(J)K=vo(K);if(W=Z,K==="")continue;let H;if($===-1)H="";else if(H=X.slice($+1,Z===-1?void 0:Z),J)H=vo(H);if(Q){if(!(G[K]&&Array.isArray(G[K])))G[K]=[];G[K].push(H)}else G[K]??=H}return Y?G[Y]:G},Od0=Nd0,Ld0=(X,Y)=>{return Nd0(X,Y,!0)},uL=decodeURIComponent;var wd0=(X)=>sq(X,uL),IS=class{raw;#X;#Y;routeIndex=0;path;bodyCache={};constructor(X,Y="/",Q=[[]]){this.raw=X,this.path=Y,this.#Y=Q,this.#X={}}param(X){return X?this.#Q(X):this.#J()}#Q(X){let Y=this.#Y[0][this.routeIndex][1][X],Q=this.#W(Y);return Q&&/\%/.test(Q)?wd0(Q):Q}#J(){let X={},Y=Object.keys(this.#Y[0][this.routeIndex][1]);for(let Q of Y){let J=this.#W(this.#Y[0][this.routeIndex][1][Q]);if(J!==void 0)X[Q]=/\%/.test(J)?wd0(J):J}return X}#W(X){return this.#Y[1]?this.#Y[1][X]:X}query(X){return Od0(this.url,X)}queries(X){return Ld0(this.url,X)}header(X){if(X)return this.raw.headers.get(X)??void 0;let Y={};return this.raw.headers.forEach((Q,J)=>{Y[J]=Q}),Y}async parseBody(X){return this.bodyCache.parsedBody??=await Ud0(this,X)}#G=(X)=>{let{bodyCache:Y,raw:Q}=this,J=Y[X];if(J)return J;let G=Object.keys(Y)[0];if(G)return Y[G].then((W)=>{if(G==="json")W=JSON.stringify(W);return new Response(W)[X]()});return Y[X]=Q[X]()};json(){return this.#G("text").then((X)=>JSON.parse(X))}text(){return this.#G("text")}arrayBuffer(){return this.#G("arrayBuffer")}blob(){return this.#G("blob")}formData(){return this.#G("formData")}addValidatedData(X,Y){this.#X[X]=Y}valid(X){return this.#X[X]}get url(){return this.raw.url}get method(){return this.raw.method}get[qd0](){return this.#Y}get matchedRoutes(){return this.#Y[0].map(([[,X]])=>X)}get routePath(){return this.#Y[0].map(([[,X]])=>X)[this.routeIndex].path}};var kS={Stringify:1,BeforeStream:2,Stream:3},l76=(X,Y)=>{let Q=new String(X);return Q.isEscaped=!0,Q.callbacks=Y,Q};var mL=async(X,Y,Q,J,G)=>{if(typeof X==="object"&&!(X instanceof String)){if(!(X instanceof Promise))X=X.toString();if(X instanceof Promise)X=await X}let W=X.callbacks;if(!W?.length)return Promise.resolve(X);if(G)G[0]+=X;else G=[X];let Z=Promise.all(W.map(($)=>$({phase:Y,buffer:G,context:J}))).then(($)=>Promise.all($.filter(Boolean).map((K)=>mL(K,Y,!1,J,G))).then(()=>G[0]));if(Q)return l76(await Z,W);else return Z};var Md0="text/plain; charset=UTF-8",bo=(X,Y)=>{return{"Content-Type":X,...Y}},Pd0=class{#X;#Y;env={};#Q;finalized=!1;error;#J;#W;#G;#$;#Z;#H;#K;#V;#q;constructor(X,Y){if(this.#X=X,Y)this.#W=Y.executionCtx,this.env=Y.env,this.#H=Y.notFoundHandler,this.#q=Y.path,this.#V=Y.matchResult}get req(){return this.#Y??=new IS(this.#X,this.#q,this.#V),this.#Y}get event(){if(this.#W&&"respondWith"in this.#W)return this.#W;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#W)return this.#W;else throw Error("This context has no ExecutionContext")}get res(){return this.#G||=new Response(null,{headers:this.#K??=new Headers})}set res(X){if(this.#G&&X){X=new Response(X.body,X);for(let[Y,Q]of this.#G.headers.entries()){if(Y==="content-type")continue;if(Y==="set-cookie"){let J=this.#G.headers.getSetCookie();X.headers.delete("set-cookie");for(let G of J)X.headers.append("set-cookie",G)}else X.headers.set(Y,Q)}}this.#G=X,this.finalized=!0}render=(...X)=>{return this.#Z??=(Y)=>this.html(Y),this.#Z(...X)};setLayout=(X)=>this.#$=X;getLayout=()=>this.#$;setRenderer=(X)=>{this.#Z=X};header=(X,Y,Q)=>{if(this.finalized)this.#G=new Response(this.#G.body,this.#G);let J=this.#G?this.#G.headers:this.#K??=new Headers;if(Y===void 0)J.delete(X);else if(Q?.append)J.append(X,Y);else J.set(X,Y)};status=(X)=>{this.#J=X};set=(X,Y)=>{this.#Q??=new Map,this.#Q.set(X,Y)};get=(X)=>{return this.#Q?this.#Q.get(X):void 0};get var(){if(!this.#Q)return{};return Object.fromEntries(this.#Q)}#F(X,Y,Q){let J=this.#G?new Headers(this.#G.headers):this.#K??new Headers;if(typeof Y==="object"&&"headers"in Y){let W=Y.headers instanceof Headers?Y.headers:new Headers(Y.headers);for(let[Z,$]of W)if(Z.toLowerCase()==="set-cookie")J.append(Z,$);else J.set(Z,$)}if(Q)for(let[W,Z]of Object.entries(Q))if(typeof Z==="string")J.set(W,Z);else{J.delete(W);for(let $ of Z)J.append(W,$)}let G=typeof Y==="number"?Y:Y?.status??this.#J;return new Response(X,{status:G,headers:J})}newResponse=(...X)=>this.#F(...X);body=(X,Y,Q)=>this.#F(X,Y,Q);text=(X,Y,Q)=>{return!this.#K&&!this.#J&&!Y&&!Q&&!this.finalized?new Response(X):this.#F(X,Y,bo(Md0,Q))};json=(X,Y,Q)=>{return this.#F(JSON.stringify(X),Y,bo("application/json",Q))};html=(X,Y,Q)=>{let J=(G)=>this.#F(G,Y,bo("text/html; charset=UTF-8",Q));return typeof X==="object"?mL(X,kS.Stringify,!1,{}).then(J):J(X)};redirect=(X,Y)=>{let Q=String(X);return this.header("Location",!/[^\x00-\xFF]/.test(Q)?Q:encodeURI(Q)),this.newResponse(null,Y??302)};notFound=()=>{return this.#H??=()=>new Response,this.#H(this)}};var n4="ALL",Ad0="all",Td0=["get","post","put","delete","options","patch"],vS="Can not add a route since the matcher is already built.",_S=class extends Error{};var Ed0="__COMPOSED_HANDLER";var d76=(X)=>{return X.text("404 Not Found",404)},jd0=(X,Y)=>{if("getResponse"in X){let Q=X.getResponse();return Y.newResponse(Q.body,Q)}return console.error(X),Y.text("Internal Server Error",500)},Cd0=class X{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#X="/";routes=[];constructor(Y={}){[...Td0,Ad0].forEach((W)=>{this[W]=(Z,...$)=>{if(typeof Z==="string")this.#X=Z;else this.#J(W,this.#X,Z);return $.forEach((K)=>{this.#J(W,this.#X,K)}),this}}),this.on=(W,Z,...$)=>{for(let K of[Z].flat()){this.#X=K;for(let H of[W].flat())$.map((F)=>{this.#J(H.toUpperCase(),this.#X,F)})}return this},this.use=(W,...Z)=>{if(typeof W==="string")this.#X=W;else this.#X="*",Z.unshift(W);return Z.forEach(($)=>{this.#J(n4,this.#X,$)}),this};let{strict:J,...G}=Y;Object.assign(this,G),this.getPath=J??!0?Y.getPath??yo:Dd0}#Y(){let Y=new X({router:this.router,getPath:this.getPath});return Y.errorHandler=this.errorHandler,Y.#Q=this.#Q,Y.routes=this.routes,Y}#Q=d76;errorHandler=jd0;route(Y,Q){let J=this.basePath(Y);return Q.routes.map((G)=>{let W;if(Q.errorHandler===jd0)W=G.handler;else W=async(Z,$)=>(await ko([],Q.errorHandler)(Z,()=>G.handler(Z,$))).res,W[Ed0]=G.handler;J.#J(G.method,G.path,W)}),this}basePath(Y){let Q=this.#Y();return Q._basePath=Y3(this._basePath,Y),Q}onError=(Y)=>{return this.errorHandler=Y,this};notFound=(Y)=>{return this.#Q=Y,this};mount(Y,Q,J){let G,W;if(J)if(typeof J==="function")W=J;else if(W=J.optionHandler,J.replaceRequest===!1)G=(K)=>K;else G=J.replaceRequest;let Z=W?(K)=>{let H=W(K);return Array.isArray(H)?H:[H]}:(K)=>{let H=void 0;try{H=K.executionCtx}catch{}return[K.env,H]};G||=(()=>{let K=Y3(this._basePath,Y),H=K==="/"?0:K.length;return(F)=>{let V=new URL(F.url);return V.pathname=V.pathname.slice(H)||"/",new Request(V,F)}})();let $=async(K,H)=>{let F=await Q(G(K.req.raw),...Z(K));if(F)return F;await H()};return this.#J(n4,Y3(Y,"*"),$),this}#J(Y,Q,J){Y=Y.toUpperCase(),Q=Y3(this._basePath,Q);let G={basePath:this._basePath,path:Q,method:Y,handler:J};this.router.add(Y,Q,[J,G]),this.routes.push(G)}#W(Y,Q){if(Y instanceof Error)return this.errorHandler(Y,Q);throw Y}#G(Y,Q,J,G){if(G==="HEAD")return(async()=>new Response(null,await this.#G(Y,Q,J,"GET")))();let W=this.getPath(Y,{env:J}),Z=this.router.match(G,W),$=new Pd0(Y,{path:W,matchResult:Z,env:J,executionCtx:Q,notFoundHandler:this.#Q});if(Z[0].length===1){let H;try{H=Z[0][0][0][0]($,async()=>{$.res=await this.#Q($)})}catch(F){return this.#W(F,$)}return H instanceof Promise?H.then((F)=>F||($.finalized?$.res:this.#Q($))).catch((F)=>this.#W(F,$)):H??this.#Q($)}let K=ko(Z[0],this.errorHandler,this.#Q);return(async()=>{try{let H=await K($);if(!H.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return H.res}catch(H){return this.#W(H,$)}})()}fetch=(Y,...Q)=>{return this.#G(Y,Q[1],Q[0],Y.method)};request=(Y,Q,J,G)=>{if(Y instanceof Request)return this.fetch(Q?new Request(Y,Q):Y,J,G);return Y=Y.toString(),this.fetch(new Request(/^https?:\/\//.test(Y)?Y:`http://localhost${Y3("/",Y)}`,Q),J,G)};fire=()=>{addEventListener("fetch",(Y)=>{Y.respondWith(this.#G(Y.request,Y,void 0,Y.request.method))})}};var lL=[];function yS(X,Y){let Q=this.buildAllMatchers(),J=(G,W)=>{let Z=Q[G]||Q[n4],$=Z[2][W];if($)return $;let K=W.match(Z[0]);if(!K)return[[],lL];let H=K.indexOf("",1);return[Z[1][H],K]};return this.match=J,J(X,Y)}var bS="[^/]+",dL=".*",pL="(?:|/.*)",Q3=Symbol(),p76=new Set(".\\+*[^]$()");function c76(X,Y){if(X.length===1)return Y.length===1?X<Y?-1:1:-1;if(Y.length===1)return 1;if(X===dL||X===pL)return 1;else if(Y===dL||Y===pL)return-1;if(X===bS)return 1;else if(Y===bS)return-1;return X.length===Y.length?X<Y?-1:1:Y.length-X.length}var Id0=class X{#X;#Y;#Q=Object.create(null);insert(Y,Q,J,G,W){if(Y.length===0){if(this.#X!==void 0)throw Q3;if(W)return;this.#X=Q;return}let[Z,...$]=Y,K=Z==="*"?$.length===0?["","",dL]:["","",bS]:Z==="/*"?["","",pL]:Z.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),H;if(K){let F=K[1],V=K[2]||bS;if(F&&K[2]){if(V===".*")throw Q3;if(V=V.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(V))throw Q3}if(H=this.#Q[V],!H){if(Object.keys(this.#Q).some((q)=>q!==dL&&q!==pL))throw Q3;if(W)return;if(H=this.#Q[V]=new X,F!=="")H.#Y=G.varIndex++}if(!W&&F!=="")J.push([F,H.#Y])}else if(H=this.#Q[Z],!H){if(Object.keys(this.#Q).some((F)=>F.length>1&&F!==dL&&F!==pL))throw Q3;if(W)return;H=this.#Q[Z]=new X}H.insert($,Q,J,G,W)}buildRegExpStr(){let Q=Object.keys(this.#Q).sort(c76).map((J)=>{let G=this.#Q[J];return(typeof G.#Y==="number"?`(${J})@${G.#Y}`:p76.has(J)?`\\${J}`:J)+G.buildRegExpStr()});if(typeof this.#X==="number")Q.unshift(`#${this.#X}`);if(Q.length===0)return"";if(Q.length===1)return Q[0];return"(?:"+Q.join("|")+")"}};var Rd0=class{#X={varIndex:0};#Y=new Id0;insert(X,Y,Q){let J=[],G=[];for(let Z=0;;){let $=!1;if(X=X.replace(/\{[^}]+\}/g,(K)=>{let H=`@\\${Z}`;return G[Z]=[H,K],Z++,$=!0,H}),!$)break}let W=X.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let Z=G.length-1;Z>=0;Z--){let[$]=G[Z];for(let K=W.length-1;K>=0;K--)if(W[K].indexOf($)!==-1){W[K]=W[K].replace($,G[Z][1]);break}}return this.#Y.insert(W,Y,J,this.#X,Q),J}buildRegExp(){let X=this.#Y.buildRegExpStr();if(X==="")return[/^$/,[],[]];let Y=0,Q=[],J=[];return X=X.replace(/#(\d+)|@(\d+)|\.\*\$/g,(G,W,Z)=>{if(W!==void 0)return Q[++Y]=Number(W),"$()";if(Z!==void 0)return J[Number(Z)]=++Y,"";return""}),[new RegExp(`^${X}`),Q,J]}};var n76=[/^$/,[],Object.create(null)],Sd0=Object.create(null);function kd0(X){return Sd0[X]??=new RegExp(X==="*"?"":`^${X.replace(/\/\*$|([.\\+*[^\]$()])/g,(Y,Q)=>Q?`\\${Q}`:"(?:|/.*)")}$`)}function i76(){Sd0=Object.create(null)}function a76(X){let Y=new Rd0,Q=[];if(X.length===0)return n76;let J=X.map((H)=>[!/\*|\/:/.test(H[0]),...H]).sort(([H,F],[V,q])=>H?1:V?-1:F.length-q.length),G=Object.create(null);for(let H=0,F=-1,V=J.length;H<V;H++){let[q,z,D]=J[H];if(q)G[z]=[D.map(([L])=>[L,Object.create(null)]),lL];else F++;let N;try{N=Y.insert(z,F,q)}catch(L){throw L===Q3?new _S(z):L}if(q)continue;Q[F]=D.map(([L,w])=>{let C=Object.create(null);w-=1;for(;w>=0;w--){let[T,A]=N[w];C[T]=A}return[L,C]})}let[W,Z,$]=Y.buildRegExp();for(let H=0,F=Q.length;H<F;H++)for(let V=0,q=Q[H].length;V<q;V++){let z=Q[H][V]?.[1];if(!z)continue;let D=Object.keys(z);for(let N=0,L=D.length;N<L;N++)z[D[N]]=$[z[D[N]]]}let K=[];for(let H in Z)K[H]=Q[Z[H]];return[W,K,G]}function tq(X,Y){if(!X)return;for(let Q of Object.keys(X).sort((J,G)=>G.length-J.length))if(kd0(Q).test(Y))return[...X[Q]];return}var fS=class{name="RegExpRouter";#X;#Y;constructor(){this.#X={[n4]:Object.create(null)},this.#Y={[n4]:Object.create(null)}}add(X,Y,Q){let J=this.#X,G=this.#Y;if(!J||!G)throw Error(vS);if(!J[X])[J,G].forEach(($)=>{$[X]=Object.create(null),Object.keys($[n4]).forEach((K)=>{$[X][K]=[...$[n4][K]]})});if(Y==="/*")Y="*";let W=(Y.match(/\/:/g)||[]).length;if(/\*$/.test(Y)){let $=kd0(Y);if(X===n4)Object.keys(J).forEach((K)=>{J[K][Y]||=tq(J[K],Y)||tq(J[n4],Y)||[]});else J[X][Y]||=tq(J[X],Y)||tq(J[n4],Y)||[];Object.keys(J).forEach((K)=>{if(X===n4||X===K)Object.keys(J[K]).forEach((H)=>{$.test(H)&&J[K][H].push([Q,W])})}),Object.keys(G).forEach((K)=>{if(X===n4||X===K)Object.keys(G[K]).forEach((H)=>$.test(H)&&G[K][H].push([Q,W]))});return}let Z=SS(Y)||[Y];for(let $=0,K=Z.length;$<K;$++){let H=Z[$];Object.keys(G).forEach((F)=>{if(X===n4||X===F)G[F][H]||=[...tq(J[F],H)||tq(J[n4],H)||[]],G[F][H].push([Q,W-K+$+1])})}}match=yS;buildAllMatchers(){let X=Object.create(null);return Object.keys(this.#Y).concat(Object.keys(this.#X)).forEach((Y)=>{X[Y]||=this.#Q(Y)}),this.#X=this.#Y=void 0,i76(),X}#Q(X){let Y=[],Q=X===n4;if([this.#X,this.#Y].forEach((J)=>{let G=J[X]?Object.keys(J[X]).map((W)=>[W,J[X][W]]):[];if(G.length!==0)Q||=!0,Y.push(...G);else if(X!==n4)Y.push(...Object.keys(J[n4]).map((W)=>[W,J[n4][W]]))}),!Q)return null;else return a76(Y)}};var r76=class{name="PreparedRegExpRouter";#X;#Y;constructor(X,Y){this.#X=X,this.#Y=Y}#Q(X,Y){let Q=this.#X[X];Q[1].forEach((J)=>J&&J.push(Y)),Object.values(Q[2]).forEach((J)=>J[0].push(Y))}#J(X,Y,Q,J,G){let W=this.#X[X];if(!G)W[2][Y][0].push([Q,{}]);else J.forEach((Z)=>{if(typeof Z==="number")W[1][Z].push([Q,G]);else W[2][Z||Y][0].push([Q,G])})}add(X,Y,Q){if(!this.#X[X]){let G=this.#X[n4],W={};for(let Z in G[2])W[Z]=[G[2][Z][0].slice(),lL];this.#X[X]=[G[0],G[1].map((Z)=>Array.isArray(Z)?Z.slice():0),W]}if(Y==="/*"||Y==="*"){let G=[Q,{}];if(X===n4)for(let W in this.#X)this.#Q(W,G);else this.#Q(X,G);return}let J=this.#Y[Y];if(!J)throw Error(`Path ${Y} is not registered`);for(let[G,W]of J)if(X===n4)for(let Z in this.#X)this.#J(Z,Y,Q,G,W);else this.#J(X,Y,Q,G,W)}buildAllMatchers(){return this.#X}match=yS};var fo=class{name="SmartRouter";#X=[];#Y=[];constructor(X){this.#X=X.routers}add(X,Y,Q){if(!this.#Y)throw Error(vS);this.#Y.push([X,Y,Q])}match(X,Y){if(!this.#Y)throw Error("Fatal error");let Q=this.#X,J=this.#Y,G=Q.length,W=0,Z;for(;W<G;W++){let $=Q[W];try{for(let K=0,H=J.length;K<H;K++)$.add(...J[K]);Z=$.match(X,Y)}catch(K){if(K instanceof _S)continue;throw K}this.match=$.match.bind($),this.#X=[$],this.#Y=void 0;break}if(W===G)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,Z}get activeRouter(){if(this.#Y||this.#X.length!==1)throw Error("No active router has been determined yet.");return this.#X[0]}};var cL=Object.create(null),vd0=class X{#X;#Y;#Q;#J=0;#W=cL;constructor(Y,Q,J){if(this.#Y=J||Object.create(null),this.#X=[],Y&&Q){let G=Object.create(null);G[Y]={handler:Q,possibleKeys:[],score:0},this.#X=[G]}this.#Q=[]}insert(Y,Q,J){this.#J=++this.#J;let G=this,W=zd0(Q),Z=[];for(let $=0,K=W.length;$<K;$++){let H=W[$],F=W[$+1],V=Bd0(H,F),q=Array.isArray(V)?V[0]:H;if(q in G.#Y){if(G=G.#Y[q],V)Z.push(V[1]);continue}if(G.#Y[q]=new X,V)G.#Q.push(V),Z.push(V[1]);G=G.#Y[q]}return G.#X.push({[Y]:{handler:J,possibleKeys:Z.filter(($,K,H)=>H.indexOf($)===K),score:this.#J}}),G}#G(Y,Q,J,G){let W=[];for(let Z=0,$=Y.#X.length;Z<$;Z++){let K=Y.#X[Z],H=K[Q]||K[n4],F={};if(H!==void 0){if(H.params=Object.create(null),W.push(H),J!==cL||G&&G!==cL)for(let V=0,q=H.possibleKeys.length;V<q;V++){let z=H.possibleKeys[V],D=F[H.score];H.params[z]=G?.[z]&&!D?G[z]:J[z]??G?.[z],F[H.score]=!0}}}return W}search(Y,Q){let J=[];this.#W=cL;let W=[this],Z=_o(Q),$=[];for(let K=0,H=Z.length;K<H;K++){let F=Z[K],V=K===H-1,q=[];for(let z=0,D=W.length;z<D;z++){let N=W[z],L=N.#Y[F];if(L)if(L.#W=N.#W,V){if(L.#Y["*"])J.push(...this.#G(L.#Y["*"],Y,N.#W));J.push(...this.#G(L,Y,N.#W))}else q.push(L);for(let w=0,C=N.#Q.length;w<C;w++){let T=N.#Q[w],A=N.#W===cL?{}:{...N.#W};if(T==="*"){let y=N.#Y["*"];if(y)J.push(...this.#G(y,Y,N.#W)),y.#W=A,q.push(y);continue}let[P,j,R]=T;if(!F&&!(R instanceof RegExp))continue;let k=N.#Y[P],_=Z.slice(K).join("/");if(R instanceof RegExp){let y=R.exec(_);if(y){if(A[j]=y[0],J.push(...this.#G(k,Y,N.#W,A)),Object.keys(k.#Y).length){k.#W=A;let b=y[0].match(/\//)?.length??0;($[b]||=[]).push(k)}continue}}if(R===!0||R.test(F))if(A[j]=F,V){if(J.push(...this.#G(k,Y,A,N.#W)),k.#Y["*"])J.push(...this.#G(k.#Y["*"],Y,A,N.#W))}else k.#W=A,q.push(k)}}W=q.concat($.shift()??[])}if(J.length>1)J.sort((K,H)=>{return K.score-H.score});return[J.map(({handler:K,params:H})=>[K,H])]}};var ho=class{name="TrieRouter";#X;constructor(){this.#X=new vd0}add(X,Y,Q){let J=SS(Y);if(J){for(let G=0,W=J.length;G<W;G++)this.#X.insert(X,J[G],Q);return}this.#X.insert(X,Y,Q)}match(X,Y){return this.#X.search(X,Y)}};var p8=class extends Cd0{constructor(X={}){super(X);this.router=X.router??new fo({routers:[new fS,new ho]})}};var o76=/^[\w!#$%&'*.^`|~+-]+$/,s76=/^[ !#-:<-[\]-~]*$/,xo=(X,Y)=>{if(Y&&X.indexOf(Y)===-1)return{};let Q=X.trim().split(";"),J={};for(let G of Q){G=G.trim();let W=G.indexOf("=");if(W===-1)continue;let Z=G.substring(0,W).trim();if(Y&&Y!==Z||!o76.test(Z))continue;let $=G.substring(W+1).trim();if($.startsWith('"')&&$.endsWith('"'))$=$.slice(1,-1);if(s76.test($)){if(J[Z]=$.indexOf("%")!==-1?sq($,uL):$,Y)break}}return J};var _d0=(X,Y,Q)=>{let J=X.req.raw.headers.get("Cookie");if(typeof Y==="string"){if(!J)return;let W=Y;if(Q==="secure")W="__Secure-"+Y;else if(Q==="host")W="__Host-"+Y;return xo(J,W)[W]}if(!J)return{};return xo(J)};var yd0=(X)=>{let Q={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...X},J=((W)=>{if(typeof W==="string")if(W==="*")return()=>W;else return(Z)=>W===Z?Z:null;else if(typeof W==="function")return W;else return(Z)=>W.includes(Z)?Z:null})(Q.origin),G=((W)=>{if(typeof W==="function")return W;else if(Array.isArray(W))return()=>W;else return()=>[]})(Q.allowMethods);return async function(Z,$){function K(F,V){Z.res.headers.set(F,V)}let H=await J(Z.req.header("origin")||"",Z);if(H)K("Access-Control-Allow-Origin",H);if(Q.credentials)K("Access-Control-Allow-Credentials","true");if(Q.exposeHeaders?.length)K("Access-Control-Expose-Headers",Q.exposeHeaders.join(","));if(Z.req.method==="OPTIONS"){if(Q.origin!=="*")K("Vary","Origin");if(Q.maxAge!=null)K("Access-Control-Max-Age",Q.maxAge.toString());let F=await G(Z.req.header("origin")||"",Z);if(F.length)K("Access-Control-Allow-Methods",F.join(","));let V=Q.allowHeaders;if(!V?.length){let q=Z.req.header("Access-Control-Request-Headers");if(q)V=q.split(/\s*,\s*/)}if(V?.length)K("Access-Control-Allow-Headers",V.join(",")),Z.res.headers.append("Vary","Access-Control-Request-Headers");return Z.res.headers.delete("Content-Length"),Z.res.headers.delete("Content-Type"),new Response(null,{headers:Z.res.headers,status:204,statusText:"No Content"})}if(await $(),Q.origin!=="*")Z.header("Vary","Origin",{append:!0})}};function t76(){let{process:X,Deno:Y}=globalThis;return!(typeof Y?.noColor==="boolean"?Y.noColor:X!==void 0?"NO_COLOR"in X?.env:!1)}async function bd0(){let{navigator:X}=globalThis,Y="cloudflare:workers";return!(X!==void 0&&X.userAgent==="Cloudflare-Workers"?await(async()=>{try{return"NO_COLOR"in((await import("cloudflare:workers")).env??{})}catch{return!1}})():!t76())}var e76=(X)=>{let[Y,Q]=[",","."];return X.map((G)=>G.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+Y)).join(Q)},XW6=(X)=>{let Y=Date.now()-X;return e76([Y<1000?Y+"ms":Math.round(Y/1000)+"s"])},YW6=async(X)=>{if(await bd0())switch(X/100|0){case 5:return`\x1B[31m${X}\x1B[0m`;case 4:return`\x1B[33m${X}\x1B[0m`;case 3:return`\x1B[36m${X}\x1B[0m`;case 2:return`\x1B[32m${X}\x1B[0m`}return`${X}`};async function fd0(X,Y,Q,J,G=0,W){let Z=Y==="<--"?`${Y} ${Q} ${J}`:`${Y} ${Q} ${J} ${await YW6(G)} ${W}`;X(Z)}var hd0=(X=console.log)=>{return async function(Q,J){let{method:G,url:W}=Q.req,Z=W.slice(W.indexOf("/",8));await fd0(X,"<--",G,Z);let $=Date.now();await J(),await fd0(X,"-->",G,Z,Q.res.status,XW6($))}};var xd0=()=>{try{return performance.now()}catch{}return Date.now()},go=(X)=>{let Y={total:!0,enabled:!0,totalDescription:"Total Response Time",autoEnd:!0,crossOrigin:!1,...X};return async function(J,G){let W=[],Z=new Map;if(J.get("metric"))return await G();if(J.set("metric",{headers:W,timers:Z}),Y.total)eq(J,"total",Y.totalDescription);if(await G(),Y.total)J3(J,"total");if(Y.autoEnd)Z.forEach((K,H)=>J3(J,H));if(typeof Y.enabled==="function"?Y.enabled(J):Y.enabled){J.res.headers.append("Server-Timing",W.join(","));let K=typeof Y.crossOrigin==="function"?Y.crossOrigin(J):Y.crossOrigin;if(K)J.res.headers.append("Timing-Allow-Origin",typeof K==="string"?K:"*")}}},gd0=(X,Y,Q,J,G)=>{let W=X.get("metric");if(!W){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}if(typeof Q==="number"){let Z=Q.toFixed(G||1),$=J?`${Y};dur=${Z};desc="${J}"`:`${Y};dur=${Z}`;W.headers.push($)}else{let Z=Q?`${Y};desc="${Q}"`:`${Y}`;W.headers.push(Z)}},eq=(X,Y,Q)=>{let J=X.get("metric");if(!J){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}J.timers.set(Y,{description:Q,start:xd0()})},J3=(X,Y,Q)=>{let J=X.get("metric");if(!J){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}let G=J.timers.get(Y);if(!G){console.warn(`Timer "${Y}" does not exist!`);return}let{description:W,start:Z}=G,$=xd0()-Z;gd0(X,Y,$,W,Q),J.timers.delete(Y)};var uo=[{name:"ORGANIZATION_CREATE",description:"Create a new organization",category:"Organizations"},{name:"ORGANIZATION_LIST",description:"List organizations",category:"Organizations"},{name:"ORGANIZATION_GET",description:"View organization details",category:"Organizations"},{name:"ORGANIZATION_UPDATE",description:"Update organization",category:"Organizations"},{name:"ORGANIZATION_DELETE",description:"Delete organization",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_SETTINGS_GET",description:"View organization settings",category:"Organizations"},{name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization settings",category:"Organizations"},{name:"ORGANIZATION_MEMBER_ADD",description:"Add members",category:"Organizations"},{name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove members",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_MEMBER_LIST",description:"List members",category:"Organizations"},{name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update member roles",category:"Organizations"},{name:"COLLECTION_CONNECTIONS_CREATE",description:"Create connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_LIST",description:"List connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_GET",description:"View connection details",category:"Connections"},{name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete connections",category:"Connections",dangerous:!0},{name:"CONNECTION_TEST",description:"Test connections",category:"Connections"},{name:"DATABASES_RUN_SQL",description:"Run SQL queries",category:"Connections",dangerous:!0},{name:"COLLECTION_VIRTUAL_MCP_CREATE",description:"Create virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_LIST",description:"List virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_GET",description:"View virtual MCP details",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_UPDATE",description:"Update virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_DELETE",description:"Delete virtual MCPs",category:"Virtual MCPs",dangerous:!0},{name:"MONITORING_LOGS_LIST",description:"List monitoring logs",category:"Monitoring"},{name:"MONITORING_STATS",description:"View monitoring statistics",category:"Monitoring"},{name:"API_KEY_CREATE",description:"Create API key",category:"API Keys"},{name:"API_KEY_LIST",description:"List API keys",category:"API Keys"},{name:"API_KEY_UPDATE",description:"Update API key",category:"API Keys"},{name:"API_KEY_DELETE",description:"Delete API key",category:"API Keys",dangerous:!0},{name:"EVENT_PUBLISH",description:"Publish events",category:"Event Bus"},{name:"EVENT_SUBSCRIBE",description:"Subscribe to events",category:"Event Bus"},{name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events",category:"Event Bus"},{name:"EVENT_CANCEL",description:"Cancel recurring events",category:"Event Bus"},{name:"EVENT_ACK",description:"Acknowledge event delivery",category:"Event Bus"},{name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions",category:"Event Bus"},{name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state",category:"Event Bus"},{name:"USER_GET",description:"Get a user by id",category:"Users"},{name:"CODE_EXECUTION_SEARCH_TOOLS",description:"Search available tools by name or description",category:"Code Execution"},{name:"CODE_EXECUTION_DESCRIBE_TOOLS",description:"Get detailed schemas for specific tools",category:"Code Execution"},{name:"CODE_EXECUTION_RUN_CODE",description:"Run JavaScript code in a sandbox with tool access",category:"Code Execution",dangerous:!0},{name:"COLLECTION_THREADS_CREATE",description:"Create threads",category:"Threads"},{name:"COLLECTION_THREADS_LIST",description:"List threads",category:"Threads"},{name:"COLLECTION_THREADS_GET",description:"View thread details",category:"Threads"},{name:"COLLECTION_THREADS_UPDATE",description:"Update threads",category:"Threads"},{name:"COLLECTION_THREADS_DELETE",description:"Delete threads",category:"Threads",dangerous:!0},{name:"COLLECTION_THREAD_MESSAGES_LIST",description:"List thread messages",category:"Threads"}];function nL(){let X={Organizations:[],Connections:[],"Virtual MCPs":[],Threads:[],Monitoring:[],Users:[],"API Keys":[],"Event Bus":[],"Code Execution":[]};for(let Y of uo)X[Y.category]?.push(Y);return X}var QW6=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",JW6="[:A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]["+QW6+"]*",GW6=new RegExp("^"+JW6+"$");function ud0(X,Y){let Q=[],J=Y.exec(X);while(J){let G=[];G.startIndex=Y.lastIndex-J[0].length;let W=J.length;for(let Z=0;Z<W;Z++)G.push(J[Z]);Q.push(G),J=Y.exec(X)}return Q}var mo=function(X){let Y=GW6.exec(X);return!(Y===null||typeof Y>"u")};var WW6={allowBooleanAttributes:!1,unpairedTags:[]};function cd0(X,Y){Y=Object.assign({},WW6,Y);let Q=[],J=!1,G=!1;if(X[0]==="\uFEFF")X=X.substr(1);for(let W=0;W<X.length;W++)if(X[W]==="<"&&X[W+1]==="?"){if(W+=2,W=ld0(X,W),W.err)return W}else if(X[W]==="<"){let Z=W;if(W++,X[W]==="!"){W=dd0(X,W);continue}else{let $=!1;if(X[W]==="/")$=!0,W++;let K="";for(;W<X.length&&X[W]!==">"&&X[W]!==" "&&X[W]!=="\t"&&X[W]!==`
274
274
  `&&X[W]!=="\r";W++)K+=X[W];if(K=K.trim(),K[K.length-1]==="/")K=K.substring(0,K.length-1),W--;if(!UW6(K)){let V;if(K.trim().length===0)V="Invalid space after '<'.";else V="Tag '"+K+"' is an invalid name.";return c8("InvalidTag",V,W9(X,W))}let H=KW6(X,W);if(H===!1)return c8("InvalidAttr","Attributes for '"+K+"' have open quote.",W9(X,W));let F=H.value;if(W=H.index,F[F.length-1]==="/"){let V=W-F.length;F=F.substring(0,F.length-1);let q=pd0(F,Y);if(q===!0)J=!0;else return c8(q.err.code,q.err.msg,W9(X,V+q.err.line))}else if($)if(!H.tagClosed)return c8("InvalidTag","Closing tag '"+K+"' doesn't have proper closing.",W9(X,W));else if(F.trim().length>0)return c8("InvalidTag","Closing tag '"+K+"' can't have attributes or invalid starting.",W9(X,Z));else if(Q.length===0)return c8("InvalidTag","Closing tag '"+K+"' has not been opened.",W9(X,Z));else{let V=Q.pop();if(K!==V.tagName){let q=W9(X,V.tagStartPos);return c8("InvalidTag","Expected closing tag '"+V.tagName+"' (opened in line "+q.line+", col "+q.col+") instead of closing tag '"+K+"'.",W9(X,Z))}if(Q.length==0)G=!0}else{let V=pd0(F,Y);if(V!==!0)return c8(V.err.code,V.err.msg,W9(X,W-F.length+V.err.line));if(G===!0)return c8("InvalidXml","Multiple possible root nodes found.",W9(X,W));else if(Y.unpairedTags.indexOf(K)!==-1);else Q.push({tagName:K,tagStartPos:Z});J=!0}for(W++;W<X.length;W++)if(X[W]==="<")if(X[W+1]==="!"){W++,W=dd0(X,W);continue}else if(X[W+1]==="?"){if(W=ld0(X,++W),W.err)return W}else break;else if(X[W]==="&"){let V=VW6(X,W);if(V==-1)return c8("InvalidChar","char '&' is not expected.",W9(X,W));W=V}else if(G===!0&&!md0(X[W]))return c8("InvalidXml","Extra text at the end",W9(X,W));if(X[W]==="<")W--}}else{if(md0(X[W]))continue;return c8("InvalidChar","char '"+X[W]+"' is not expected.",W9(X,W))}if(!J)return c8("InvalidXml","Start tag expected.",1);else if(Q.length==1)return c8("InvalidTag","Unclosed tag '"+Q[0].tagName+"'.",W9(X,Q[0].tagStartPos));else if(Q.length>0)return c8("InvalidXml","Invalid '"+JSON.stringify(Q.map((W)=>W.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1});return!0}function md0(X){return X===" "||X==="\t"||X===`
275
275
  `||X==="\r"}function ld0(X,Y){let Q=Y;for(;Y<X.length;Y++)if(X[Y]=="?"||X[Y]==" "){let J=X.substr(Q,Y-Q);if(Y>5&&J==="xml")return c8("InvalidXml","XML declaration allowed only at the start of the document.",W9(X,Y));else if(X[Y]=="?"&&X[Y+1]==">"){Y++;break}else continue}return Y}function dd0(X,Y){if(X.length>Y+5&&X[Y+1]==="-"&&X[Y+2]==="-"){for(Y+=3;Y<X.length;Y++)if(X[Y]==="-"&&X[Y+1]==="-"&&X[Y+2]===">"){Y+=2;break}}else if(X.length>Y+8&&X[Y+1]==="D"&&X[Y+2]==="O"&&X[Y+3]==="C"&&X[Y+4]==="T"&&X[Y+5]==="Y"&&X[Y+6]==="P"&&X[Y+7]==="E"){let Q=1;for(Y+=8;Y<X.length;Y++)if(X[Y]==="<")Q++;else if(X[Y]===">"){if(Q--,Q===0)break}}else if(X.length>Y+9&&X[Y+1]==="["&&X[Y+2]==="C"&&X[Y+3]==="D"&&X[Y+4]==="A"&&X[Y+5]==="T"&&X[Y+6]==="A"&&X[Y+7]==="["){for(Y+=8;Y<X.length;Y++)if(X[Y]==="]"&&X[Y+1]==="]"&&X[Y+2]===">"){Y+=2;break}}return Y}var ZW6='"',$W6="'";function KW6(X,Y){let Q="",J="",G=!1;for(;Y<X.length;Y++){if(X[Y]===ZW6||X[Y]===$W6)if(J==="")J=X[Y];else if(J!==X[Y]);else J="";else if(X[Y]===">"){if(J===""){G=!0;break}}Q+=X[Y]}if(J!=="")return!1;return{value:Q,index:Y,tagClosed:G}}var HW6=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function pd0(X,Y){let Q=ud0(X,HW6),J={};for(let G=0;G<Q.length;G++){if(Q[G][1].length===0)return c8("InvalidAttr","Attribute '"+Q[G][2]+"' has no space in starting.",iL(Q[G]));else if(Q[G][3]!==void 0&&Q[G][4]===void 0)return c8("InvalidAttr","Attribute '"+Q[G][2]+"' is without value.",iL(Q[G]));else if(Q[G][3]===void 0&&!Y.allowBooleanAttributes)return c8("InvalidAttr","boolean attribute '"+Q[G][2]+"' is not allowed.",iL(Q[G]));let W=Q[G][2];if(!qW6(W))return c8("InvalidAttr","Attribute '"+W+"' is an invalid name.",iL(Q[G]));if(!J.hasOwnProperty(W))J[W]=1;else return c8("InvalidAttr","Attribute '"+W+"' is repeated.",iL(Q[G]))}return!0}function FW6(X,Y){let Q=/\d/;if(X[Y]==="x")Y++,Q=/[\da-fA-F]/;for(;Y<X.length;Y++){if(X[Y]===";")return Y;if(!X[Y].match(Q))break}return-1}function VW6(X,Y){if(Y++,X[Y]===";")return-1;if(X[Y]==="#")return Y++,FW6(X,Y);let Q=0;for(;Y<X.length;Y++,Q++){if(X[Y].match(/\w/)&&Q<20)continue;if(X[Y]===";")break;return-1}return Y}function c8(X,Y,Q){return{err:{code:X,msg:Y,line:Q.line||Q,col:Q.col}}}function qW6(X){return mo(X)}function UW6(X){return mo(X)}function W9(X,Y){let Q=X.substring(0,Y).split(/\r?\n/);return{line:Q.length,col:Q[Q.length-1].length+1}}function iL(X){return X.startIndex+X[1].length}var nd0={validate:cd0};var uY=E6(nt0(),1);h$();_5();h$();_5();w9();lX();var T8=(X,Y="ms")=>{return new Date(Date.now()+(Y==="sec"?X*1000:X))},I_=new WeakMap;function E11(X,Y){let Q=Y.fields,J={};for(let G in X){let W=Q[G];if(!W){J[G]=X[G];continue}if(W.returned===!1)continue;J[G]=X[G]}return J}function R_(X,Y){if(!I_.has(X))I_.set(X,new Map);let Q=I_.get(X);if(Q.has(Y))return Q.get(Y);let J={...Y==="user"?X.user?.additionalFields:{},...Y==="session"?X.session?.additionalFields:{}};for(let G of X.plugins||[])if(G.schema&&G.schema[Y])J={...J,...G.schema[Y].fields};return I_.get(X).set(Y,J),J}function LY(X,Y){return{...E11(Y,{fields:R_(X,"user")}),id:Y.id}}function vW(X,Y){return E11(Y,{fields:R_(X,"session")})}function j11(X,Y){let Q=Y.action||"create",J=Y.fields,G=Object.assign(Object.create(null),null);for(let W in J){if(W in X){if(J[W].input===!1){if(J[W].defaultValue!==void 0){if(Q!=="update"){G[W]=J[W].defaultValue;continue}}if(X[W])throw new i("BAD_REQUEST",{message:`${W} is not allowed to be set`});continue}if(J[W].validator?.input&&X[W]!==void 0){G[W]=J[W].validator.input["~standard"].validate(X[W]);continue}if(J[W].transform?.input&&X[W]!==void 0){G[W]=J[W].transform?.input(X[W]);continue}G[W]=X[W];continue}if(J[W].defaultValue!==void 0&&Q==="create"){if(typeof J[W].defaultValue==="function"){G[W]=J[W].defaultValue();continue}G[W]=J[W].defaultValue;continue}if(J[W].required&&Q==="create")throw new i("BAD_REQUEST",{message:`${W} is required`})}return G}function q10(X,Y={},Q){return j11(Y,{fields:R_(X,"user"),action:Q})}function C11(X,Y){return j11(Y,{fields:R_(X,"session")})}function QQ(X,Y){if(!Y)return X;for(let Q in Y){let J=Y[Q]?.modelName;if(J)X[Q].modelName=J;for(let G in X[Q].fields){let W=Y[Q]?.fields?.[G];if(!W)continue;X[Q].fields[G].fieldName=W}}return X}JQ();a0();var oM6="127.0.0.1";function t$(X,Y){if(Y.advanced?.ipAddress?.disableIpTracking)return null;if(yW()||Oz())return oM6;let Q="headers"in X?X.headers:X,J=Y.advanced?.ipAddress?.ipAddressHeaders||["x-forwarded-for"];for(let G of J){let W="get"in Q?Q.get(G):Q[G];if(typeof W==="string"){let Z=W.split(",")[0].trim();if(sM6(Z))return Z}}return null}function sM6(X){if(xH().safeParse(X).success)return!0;if(gH().safeParse(X).success)return!0;return!1}M9();X7();JQ();a8();import{sql as J7}from"kysely";async function JP6(X,Y){let Q;if(!X.database){let J=_J(X),G=Object.keys(J).reduce((Z,$)=>{return Z[$]=[],Z},{}),{memoryAdapter:W}=await Promise.resolve().then(() => (k11(),S11));Q=W(G)(X)}else if(typeof X.database==="function")Q=X.database(X);else Q=await Y(X);if(!Q.transaction)d1.warn("Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation."),Q.transaction=async(J)=>{return J(Q)};return Q}async function v11(X){return JP6(X,async(Y)=>{let{createKyselyAdapter:Q}=await Promise.resolve().then(() => (N10(),D10)),{kysely:J,databaseType:G,transaction:W}=await Q(Y);if(!J)throw new S1("Failed to initialize database adapter");let{kyselyAdapter:Z}=await Promise.resolve().then(() => (N10(),D10));return Z(J,{type:G||"sqlite",debugLogs:Y.database&&"debugLogs"in Y.database?Y.database.debugLogs:!1,transaction:W})(Y)})}function GP6(X,Y){let Q=Y.hooks;async function J(K,H,F){let V=await _Q(),q=K;for(let N of Q||[]){let L=N[H]?.create?.before;if(L){let w=await L(q,V);if(w===!1)return null;if(typeof w==="object"&&"data"in w)q={...q,...w.data}}}let z=F?await F.fn(q):null,D=!F||F.executeMainFn?await(await N4(X)).create({model:H,data:q,forceAllowId:!0}):z;for(let N of Q||[]){let L=N[H]?.create?.after;if(L)await L(D,V)}return D}async function G(K,H,F,V){let q=await _Q(),z=K;for(let L of Q||[]){let w=L[F]?.update?.before;if(w){let C=await w(K,q);if(C===!1)return null;if(typeof C==="object"&&"data"in C)z={...z,...C.data}}}let D=V?await V.fn(z):null,N=!V||V.executeMainFn?await(await N4(X)).update({model:F,update:z,where:H}):D;for(let L of Q||[]){let w=L[F]?.update?.after;if(w)await w(N,q)}return N}async function W(K,H,F,V){let q=await _Q(),z=K;for(let L of Q||[]){let w=L[F]?.update?.before;if(w){let C=await w(K,q);if(C===!1)return null;if(typeof C==="object"&&"data"in C)z={...z,...C.data}}}let D=V?await V.fn(z):null,N=!V||V.executeMainFn?await(await N4(X)).updateMany({model:F,update:z,where:H}):D;for(let L of Q||[]){let w=L[F]?.update?.after;if(w)await w(N,q)}return N}async function Z(K,H,F){let V=await _Q(),q=null;try{q=(await(await N4(X)).findMany({model:H,where:K,limit:1}))[0]||null}catch(N){}if(q)for(let N of Q||[]){let L=N[H]?.delete?.before;if(L){if(await L(q,V)===!1)return null}}let z=F?await F.fn(K):null,D=!F||F.executeMainFn?await(await N4(X)).delete({model:H,where:K}):z;if(q)for(let N of Q||[]){let L=N[H]?.delete?.after;if(L)await L(q,V)}return D}async function $(K,H,F){let V=await _Q(),q=[];try{q=await(await N4(X)).findMany({model:H,where:K})}catch(N){}for(let N of q)for(let L of Q||[]){let w=L[H]?.delete?.before;if(w){if(await w(N,V)===!1)return null}}let z=F?await F.fn(K):null,D=!F||F.executeMainFn?await(await N4(X)).deleteMany({model:H,where:K}):z;for(let N of q)for(let L of Q||[]){let w=L[H]?.delete?.after;if(w)await w(N,V)}return D}return{createWithHooks:J,updateWithHooks:G,updateManyWithHooks:W,deleteWithHooks:Z,deleteManyWithHooks:$}}var O10=(X,Y)=>{let{logger:Q,options:J}=Y,G=J.secondaryStorage,W=J.session?.expiresIn||604800,{createWithHooks:Z,updateWithHooks:$,updateManyWithHooks:K,deleteWithHooks:H,deleteManyWithHooks:F}=GP6(X,Y);async function V(q){if(!G)return;let z=await G.get(`active-sessions-${q.id}`);if(!z)return;let D=Date.now(),N=(E4(z)||[]).filter((L)=>L.expiresAt>D);await Promise.all(N.map(async({token:L})=>{let w=await G.get(L);if(!w)return;let C=E4(w);if(!C)return;let T=Math.max(Math.floor(new Date(C.session.expiresAt).getTime()-D)/1000,0);await G.set(L,JSON.stringify({session:C.session,user:q}),Math.floor(T))}))}return{createOAuthUser:async(q,z)=>{return AM(X,async()=>{let D=await Z({createdAt:new Date,updatedAt:new Date,...q},"user",void 0);return{user:D,account:await Z({...z,userId:D.id,createdAt:new Date,updatedAt:new Date},"account",void 0)}})},createUser:async(q)=>{return await Z({createdAt:new Date,updatedAt:new Date,...q,email:q.email?.toLowerCase()},"user",void 0)},createAccount:async(q)=>{return await Z({createdAt:new Date,updatedAt:new Date,...q},"account",void 0)},listSessions:async(q)=>{if(G){let z=await G.get(`active-sessions-${q}`);if(!z)return[];let D=E4(z)||[],N=Date.now(),L=D.filter((C)=>C.expiresAt>N),w=[];for(let C of L){let T=await G.get(C.token);if(T){let A=E4(T);if(!A)return[];let P=vW(Y.options,{...A.session,expiresAt:new Date(A.session.expiresAt)});w.push(P)}}return w}return await(await N4(X)).findMany({model:"session",where:[{field:"userId",value:q}]})},listUsers:async(q,z,D,N)=>{return await(await N4(X)).findMany({model:"user",limit:q,offset:z,sortBy:D,where:N})},countTotalUsers:async(q)=>{let z=await(await N4(X)).count({model:"user",where:q});if(typeof z==="string")return parseInt(z);return z},deleteUser:async(q)=>{if(G)await G.delete(`active-sessions-${q}`);if(!G||J.session?.storeSessionInDatabase)await F([{field:"userId",value:q}],"session",void 0);await F([{field:"userId",value:q}],"account",void 0),await H([{field:"id",value:q}],"user",void 0)},createSession:async(q,z,D,N)=>{let L=await _Q().catch(()=>null),w=L?.headers||L?.request?.headers,{id:C,...T}=D||{},A=C11(L?.context.options??J,{}),P={ipAddress:L?.request||L?.headers?t$(L?.request||L?.headers,L?.context.options)||"":"",userAgent:w?.get("user-agent")||"",...T,expiresAt:z?T8(86400,"sec"):T8(W,"sec"),userId:q,token:$X(32),createdAt:new Date,updatedAt:new Date,...A,...N?T:{}};return await Z(P,"session",G?{fn:async(j)=>{let R=await G.get(`active-sessions-${q}`),k=[],_=Date.now();if(R)k=E4(R)||[],k=k.filter((f)=>f.expiresAt>_);let y=k.sort((f,t)=>f.expiresAt-t.expiresAt),b=y.at(-1)?.expiresAt;if(y.push({token:P.token,expiresAt:P.expiresAt.getTime()}),!b||b<P.expiresAt.getTime())b=P.expiresAt.getTime();let r=Math.max(Math.floor((b-_)/1000),0);if(r>0)await G.set(`active-sessions-${q}`,JSON.stringify(y),r);let x=await X.findOne({model:"user",where:[{field:"id",value:q}]}),S=Math.max(Math.floor((P.expiresAt.getTime()-_)/1000),0);if(S>0)await G.set(P.token,JSON.stringify({session:j,user:x}),S);return j},executeMainFn:J.session?.storeSessionInDatabase}:void 0)},findSession:async(q)=>{if(G){let L=await G.get(q);if(!L&&!J.session?.storeSessionInDatabase)return null;if(L){let w=E4(L);if(!w)return null;return{session:vW(Y.options,{...w.session,expiresAt:new Date(w.session.expiresAt),createdAt:new Date(w.session.createdAt),updatedAt:new Date(w.session.updatedAt)}),user:LY(Y.options,{...w.user,createdAt:new Date(w.user.createdAt),updatedAt:new Date(w.user.updatedAt)})}}}let z=await(await N4(X)).findOne({model:"session",where:[{value:q,field:"token"}],join:{user:!0}});if(!z)return null;let{user:D,...N}=z;if(!D)return null;return{session:vW(Y.options,N),user:LY(Y.options,D)}},findSessions:async(q)=>{if(G){let D=[];for(let N of q){let L=await G.get(N);if(L){let w=E4(L);if(!w)return[];let C={session:{...w.session,expiresAt:new Date(w.session.expiresAt)},user:{...w.user,createdAt:new Date(w.user.createdAt),updatedAt:new Date(w.user.updatedAt)}};D.push(C)}}return D}let z=await(await N4(X)).findMany({model:"session",where:[{field:"token",value:q,operator:"in"}],join:{user:!0}});if(!z.length)return[];if(z.some((D)=>!D.user))return[];return z.map((D)=>{let{user:N,...L}=D;return{session:L,user:N}})},updateSession:async(q,z)=>{return await $(z,[{field:"token",value:q}],"session",G?{async fn(D){let N=await G.get(q),L=null;if(N){let w=E4(N);if(!w)return null;return L={...w.session,...D},L}else return null},executeMainFn:J.session?.storeSessionInDatabase}:void 0)},deleteSession:async(q)=>{if(G){let z=await G.get(q);if(z){let{session:D}=E4(z)??{};if(!D){Q.error("Session not found in secondary storage");return}let N=D.userId,L=await G.get(`active-sessions-${N}`);if(L){let w=E4(L)||[],C=Date.now(),T=w.filter((P)=>P.expiresAt>C&&P.token!==q),A=T.sort((P,j)=>P.expiresAt-j.expiresAt).at(-1)?.expiresAt;if(T.length>0&&A&&A>Date.now())await G.set(`active-sessions-${N}`,JSON.stringify(T),Math.floor((A-C)/1000));else await G.delete(`active-sessions-${N}`)}else Q.error("Active sessions list not found in secondary storage")}if(await G.delete(q),!J.session?.storeSessionInDatabase||Y.options.session?.preserveSessionInDatabase)return}await(await N4(X)).delete({model:"session",where:[{field:"token",value:q}]})},deleteAccounts:async(q)=>{await F([{field:"userId",value:q}],"account",void 0)},deleteAccount:async(q)=>{await H([{field:"id",value:q}],"account",void 0)},deleteSessions:async(q)=>{if(G){if(typeof q==="string"){let z=await G.get(`active-sessions-${q}`),D=z?E4(z):[];if(!D)return;for(let N of D)await G.delete(N.token)}else for(let z of q)if(await G.get(z))await G.delete(z);if(!J.session?.storeSessionInDatabase||Y.options.session?.preserveSessionInDatabase)return}await F([{field:Array.isArray(q)?"token":"userId",value:q,operator:Array.isArray(q)?"in":void 0}],"session",void 0)},findOAuthUser:async(q,z,D)=>{let N=await(await N4(X)).findMany({model:"account",where:[{value:z,field:"accountId"}],join:{user:!0}}).then((L)=>{return L.find((w)=>w.providerId===D)});if(N)if(N.user)return{user:N.user,accounts:[N]};else{let L=await(await N4(X)).findOne({model:"user",where:[{value:q.toLowerCase(),field:"email"}]});if(L)return{user:L,accounts:[N]};return null}else{let L=await(await N4(X)).findOne({model:"user",where:[{value:q.toLowerCase(),field:"email"}]});if(L)return{user:L,accounts:await(await N4(X)).findMany({model:"account",where:[{value:L.id,field:"userId"}]})||[]};else return null}},findUserByEmail:async(q,z)=>{let D=await(await N4(X)).findOne({model:"user",where:[{value:q.toLowerCase(),field:"email"}],join:{...z?.includeAccounts?{account:!0}:{}}});if(!D)return null;let{account:N,...L}=D;return{user:L,accounts:N??[]}},findUserById:async(q)=>{if(!q)return null;return await(await N4(X)).findOne({model:"user",where:[{field:"id",value:q}]})},linkAccount:async(q)=>{return await Z({createdAt:new Date,updatedAt:new Date,...q},"account",void 0)},updateUser:async(q,z)=>{let D=await $(z,[{field:"id",value:q}],"user",void 0);return await V(D),await V(D),D},updateUserByEmail:async(q,z)=>{let D=await $(z,[{field:"email",value:q.toLowerCase()}],"user",void 0);return await V(D),await V(D),D},updatePassword:async(q,z)=>{await K({password:z},[{field:"userId",value:q},{field:"providerId",value:"credential"}],"account",void 0)},findAccounts:async(q)=>{return await(await N4(X)).findMany({model:"account",where:[{field:"userId",value:q}]})},findAccount:async(q)=>{return await(await N4(X)).findOne({model:"account",where:[{field:"accountId",value:q}]})},findAccountByProviderId:async(q,z)=>{return await(await N4(X)).findOne({model:"account",where:[{field:"accountId",value:q},{field:"providerId",value:z}]})},findAccountByUserId:async(q)=>{return await(await N4(X)).findMany({model:"account",where:[{field:"userId",value:q}]})},updateAccount:async(q,z)=>{return await $(z,[{field:"id",value:q}],"account",void 0)},createVerificationValue:async(q)=>{return await Z({createdAt:new Date,updatedAt:new Date,...q},"verification",void 0)},findVerificationValue:async(q)=>{let z=await(await N4(X)).findMany({model:"verification",where:[{field:"identifier",value:q}],sortBy:{field:"createdAt",direction:"desc"},limit:1});if(!J.verification?.disableCleanup)await(await N4(X)).deleteMany({model:"verification",where:[{field:"expiresAt",value:new Date,operator:"lt"}]});return z[0]},deleteVerificationValue:async(q)=>{await(await N4(X)).delete({model:"verification",where:[{field:"id",value:q}]})},deleteVerificationByIdentifier:async(q)=>{await(await N4(X)).delete({model:"verification",where:[{field:"identifier",value:q}]})},updateVerificationValue:async(q,z)=>{return await $(z,[{field:"id",value:q}],"verification",void 0)}}};function WP6(X){let Y=_J(X),Q={};for(let J in Y){let G=Y[J],W=G.fields,Z={};if(Object.entries(W).forEach(([$,K])=>{if(Z[K.fieldName||$]=K,K.references){let H=Y[K.references.model];if(H)Z[K.fieldName||$].references={...K.references,model:H.modelName,field:K.references.field}}}),Q[G.modelName]){Q[G.modelName].fields={...Q[G.modelName].fields,...Z};continue}Q[G.modelName]={fields:Z,order:G.order||1/0}}return Q}var ZP6={postgres:{string:["character varying","varchar","text","uuid"],number:["int4","integer","bigint","smallint","numeric","real","double precision"],boolean:["bool","boolean"],date:["timestamptz","timestamp","date"],json:["json","jsonb"]},mysql:{string:["varchar","text","uuid"],number:["integer","int","bigint","smallint","decimal","float","double"],boolean:["boolean","tinyint"],date:["timestamp","datetime","date"],json:["json"]},sqlite:{string:["TEXT"],number:["INTEGER","REAL"],boolean:["INTEGER","BOOLEAN"],date:["DATE","INTEGER"],json:["TEXT"]},mssql:{string:["varchar","nvarchar","uniqueidentifier"],number:["int","bigint","smallint","decimal","float","double"],boolean:["bit","smallint"],date:["datetime2","date","datetime"],json:["varchar","nvarchar"]}};function $P6(X,Y,Q){function J(W){return W.toLowerCase().split("(")[0].trim()}if(Y==="string[]"||Y==="number[]")return X.toLowerCase().includes("json");let G=ZP6[Q];return(Array.isArray(Y)?G.string.map((W)=>W.toLowerCase()):G[Y].map((W)=>W.toLowerCase())).includes(J(X))}async function KP6(X){try{let Y=await J7`SHOW search_path`.execute(X);if(Y.rows[0]?.search_path)return Y.rows[0].search_path.split(",").map((Q)=>Q.trim()).map((Q)=>Q.replace(/^["']|["']$/g,"")).filter((Q)=>!Q.startsWith("$"))[0]||"public"}catch(Y){}return"public"}async function _11(X){let Y=WP6(X),Q=wz(X.logger),{kysely:J,databaseType:G}=await mv(X);if(!G)Q.warn("Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this."),G="sqlite";if(!J)Q.error("Only kysely adapter is supported for migrations. You can use `generate` command to generate the schema, if you're using a different adapter."),process.exit(1);let W="public";if(G==="postgres"){W=await KP6(J),Q.debug(`PostgreSQL migration: Using schema '${W}' (from search_path)`);try{if(!(await J7`
276
276
  SELECT schema_name
@@ -1048,8 +1048,8 @@ Please refer to the documentation here: https://better-auth.com/docs/plugins/org
1048
1048
  <h2>You've been invited!</h2>
1049
1049
  <p>${J} has invited you to join <strong>${Q.organization.name}</strong>.</p>
1050
1050
  <p><a href="${G}">Click here to accept the invitation</a></p>
1051
- `})}}}var df6=[f60({organizationCreation:{afterCreate:async(X)=>{await UG1(X.organization.id,X.member.userId)}},ac:Eb,creatorRole:"owner",allowUserToCreateOrganization:!0,dynamicAccessControl:{enabled:!0,maximumRolesPerOrganization:500,enableCustomResources:!0,allowedRolesToCreateResources:zG1,resourceNameValidation:(X)=>{return{valid:/^[a-zA-Z0-9-_]+$/.test(X)}}},roles:{user:uf6,admin:mf6,owner:lf6},sendInvitationEmail:LG1}),s60({loginPage:"/login",oidcConfig:{scopes:OG1,metadata:{scopes_supported:OG1},loginPage:"/login"}}),o60({enableMetadata:!0,maximumNameLength:64,keyExpiration:{minExpiresIn:0.003472222222222222},enableSessionForAPIKeys:!0,customAPIKeyGetter:(X)=>{if(X.headers?.get("X-MCP-Session-Auth")==="true")return null;let Q=X.headers?.get("Authorization");if(Q?.startsWith("Bearer "))return Q.replace("Bearer ","").trim();return null},permissions:{defaultPermissions:{self:["ORGANIZATION_LIST","ORGANIZATION_GET","ORGANIZATION_MEMBER_LIST","COLLECTION_CONNECTIONS_LIST","COLLECTION_CONNECTIONS_GET","API_KEY_CREATE","API_KEY_LIST"]}},rateLimit:{enabled:!1}}),g60({defaultRole:"user",adminRoles:["admin","owner"]}),Y40(),l60({jwt:{expirationTime:"5m"}}),h61(e8.ssoConfig?BG1(e8.ssoConfig):void 0),...e8.magicLinkConfig&&e8.emailProviders&&e8.emailProviders.length>0?[X40(Z91(e8.magicLinkConfig,e8.emailProviders))]:[]],pf6=u40(),cf6=W91(pf6),sW=i10({baseURL:process.env.BASE_URL||"http://localhost:3000",database:cf6,emailAndPassword:{enabled:!0},...e8,rateLimit:{enabled:process.env.DISABLE_RATE_LIMIT!=="true",window:60,max:1e4},plugins:df6,databaseHooks:{user:{create:{after:async(X)=>{if(JP.autoCreateOrganizationOnSignup===!1)return;let Y=X.name?X.name.split(" ")[0]:X.email.split("@")[0],Q=3;for(let J=0;J<Q;J++){let G=`${Y} ${hf6()}`,W=ff6(G);try{await sW.api.createOrganization({body:{name:G,slug:W,userId:X.id}});return}catch(Z){if(!(Z instanceof Error&&("body"in Z)&&Z.body?.code==="ORGANIZATION_ALREADY_EXISTS")||J===Q-1){console.error("Failed to create default organization:",Z);return}}}}}}}});vQ();import{randomBytes as nf6}from"crypto";var iP=null;function wG1(){if(iP)return iP;let X=process.env.MESH_JWT_SECRET??e8.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(X)iP=new TextEncoder().encode(X);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),iP=new Uint8Array(nf6(32));return iP}async function MG1(X,Y="5m"){let Q=wG1();return await new YQ(X).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Y).sign(Q)}async function PG1(X){try{let Y=wG1(),{payload:Q}=await K8(X,Y);return Q}catch{return}}cW();class mX0{db;constructor(X){this.db=X}async create(X,Y,Q){let J=t8("vir"),G=new Date().toISOString();if(await this.db.insertInto("connections").values({id:J,organization_id:X,created_by:Y,title:Q.title,description:Q.description??null,icon:Q.icon??null,app_name:null,app_id:null,connection_type:"VIRTUAL",connection_url:`virtual://${J}`,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:Q.metadata?JSON.stringify(Q.metadata):null,tools:null,bindings:null,status:Q.status??"active",created_at:G,updated_at:G}).execute(),Q.connections.length>0)await this.db.insertInto("connection_aggregations").values(Q.connections.map((Z)=>({id:t8("agg"),parent_connection_id:J,child_connection_id:Z.connection_id,selected_tools:Z.selected_tools?JSON.stringify(Z.selected_tools):null,selected_resources:Z.selected_resources?JSON.stringify(Z.selected_resources):null,selected_prompts:Z.selected_prompts?JSON.stringify(Z.selected_prompts):null,created_at:G}))).execute();let W=await this.findById(J);if(!W)throw Error(`Failed to create virtual MCP with id: ${J}`);return W}async findById(X){return this.findByIdInternal(this.db,X)}async findByIdInternal(X,Y){let Q=await X.selectFrom("connections").selectAll().where("id","=",Y).where("connection_type","=","VIRTUAL").executeTakeFirst();if(!Q)return null;let J=await X.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","=",Y).execute();return this.deserializeVirtualMCPEntity(Q,J)}async list(X){let Y=await this.db.selectFrom("connections").selectAll().where("organization_id","=",X).where("connection_type","=","VIRTUAL").execute(),Q=Y.map((W)=>W.id);if(Q.length===0)return[];let J=await this.db.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","in",Q).execute(),G=new Map;for(let W of J){let Z=G.get(W.parent_connection_id)??[];Z.push(W),G.set(W.parent_connection_id,Z)}return Y.map((W)=>this.deserializeVirtualMCPEntity(W,G.get(W.id)??[]))}async listByConnectionId(X,Y){let J=(await this.db.selectFrom("connection_aggregations").select("parent_connection_id").where("child_connection_id","=",Y).execute()).map((K)=>K.parent_connection_id);if(J.length===0)return[];let G=await this.db.selectFrom("connections").selectAll().where("id","in",J).where("organization_id","=",X).where("connection_type","=","VIRTUAL").execute();if(G.length===0)return[];let W=G.map((K)=>K.id),Z=await this.db.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","in",W).execute(),$=new Map;for(let K of Z){let H=$.get(K.parent_connection_id)??[];H.push(K),$.set(K.parent_connection_id,H)}return G.map((K)=>this.deserializeVirtualMCPEntity(K,$.get(K.id)??[]))}async update(X,Y,Q){let J=new Date().toISOString(),G={updated_at:J};if(Q.title!==void 0)G.title=Q.title;if(Q.description!==void 0)G.description=Q.description;if(Q.icon!==void 0)G.icon=Q.icon;if(Q.status!==void 0)G.status=Q.status;if(Q.metadata!==void 0)G.metadata=Q.metadata?JSON.stringify(Q.metadata):null;if(await this.db.updateTable("connections").set(G).where("id","=",X).where("connection_type","=","VIRTUAL").execute(),Q.connections!==void 0){if(await this.db.deleteFrom("connection_aggregations").where("parent_connection_id","=",X).execute(),Q.connections.length>0)await this.db.insertInto("connection_aggregations").values(Q.connections.map((Z)=>({id:t8("agg"),parent_connection_id:X,child_connection_id:Z.connection_id,selected_tools:Z.selected_tools?JSON.stringify(Z.selected_tools):null,selected_resources:Z.selected_resources?JSON.stringify(Z.selected_resources):null,selected_prompts:Z.selected_prompts?JSON.stringify(Z.selected_prompts):null,created_at:J}))).execute()}let W=await this.findById(X);if(!W)throw Error("Virtual MCP not found after update");return W}async delete(X){await this.db.deleteFrom("connection_aggregations").where("parent_connection_id","=",X).execute(),await this.db.deleteFrom("connections").where("id","=",X).where("connection_type","=","VIRTUAL").execute()}deserializeVirtualMCPEntity(X,Y){let Q=X.created_at instanceof Date?X.created_at.toISOString():X.created_at,J=X.updated_at instanceof Date?X.updated_at.toISOString():X.updated_at,G=X.status==="active"?"active":"inactive";return{id:X.id,organization_id:X.organization_id,title:X.title,description:X.description,tool_selection_mode:"inclusion",icon:X.icon,status:G,created_at:Q,updated_at:J,created_by:X.created_by,updated_by:void 0,metadata:this.parseJson(X.metadata),connections:Y.map((W)=>({connection_id:W.child_connection_id,selected_tools:this.parseJson(W.selected_tools),selected_resources:this.parseJson(W.selected_resources),selected_prompts:this.parseJson(W.selected_prompts)}))}}parseJson(X){if(X===null)return null;if(typeof X==="string")try{return JSON.parse(X)}catch{return null}return X}}import{sql as jb}from"kysely";class lX0{patterns=[{type:"email",regex:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g},{type:"api_key",regex:/(?:api[_-]?key|token|secret|password|bearer)\s*[:=]\s*['"]?[\w-]{16,}['"]?/gi},{type:"jwt",regex:/eyJ[A-Za-z0-9-_]+\.eyJ[A-Za-z0-9-_]+\.[A-Za-z0-9-_.+/=]*/g},{type:"credit_card",regex:/\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b/g},{type:"ssn",regex:/\b\d{3}-\d{2}-\d{4}\b/g}];redact(X){return HN.startActiveSpan("redactor.redact",(Y)=>{try{if(X===null||X===void 0)return X;if(typeof X==="string")return Y.setAttribute("data.type","string"),this.redactString(X);if(Array.isArray(X))return Y.setAttribute("data.type","array"),Y.setAttribute("data.length",X.length),X.map((Q)=>this.redact(Q));if(typeof X==="object"){Y.setAttribute("data.type","object");let Q={};for(let[J,G]of Object.entries(X)){let W=this.redactString(J);Q[W]=this.redact(G)}return Q}return Y.setAttribute("data.type",typeof X),X}finally{Y.end()}})}redactString(X){return HN.startActiveSpan("redactor.redactString",(Y)=>{try{Y.setAttribute("text.length",X.length);let Q=X,J=0;for(let G of this.patterns){let W=X.match(G.regex);if(W)J+=W.length,Y.setAttribute(`redaction.${G.type}.count`,W.length);Q=Q.replace(G.regex,`[REDACTED:${G.type}]`)}return Y.setAttribute("redaction.total_count",J),Q}finally{Y.end()}})}}cW();class dX0{db;redactor;databaseType;constructor(X,Y="sqlite"){this.db=X;this.redactor=new lX0,this.databaseType=Y}jsonExtract(X,Y){if(this.databaseType==="postgres")return jb`(${jb.ref(X)}::jsonb)->>${Y}`;let Q=`$.${Y}`;return jb`json_extract(${jb.ref(X)}, ${Q})`}async log(X){await this.logBatch([X])}async logBatch(X){if(X.length===0)return;let Y=X.map((Q)=>({...Q,input:this.redactor.redact(Q.input),output:this.redactor.redact(Q.output)}));await this.db.transaction().execute(async(Q)=>{await Q.insertInto("monitoring_logs").values(Y.map((J)=>this.toDbRow(J))).execute()})}async query(X){let Y=this.db.selectFrom("monitoring_logs").selectAll(),Q=this.db.selectFrom("monitoring_logs").select(($)=>$.fn.count("id").as("count"));if(X.organizationId)Y=Y.where("organization_id","=",X.organizationId),Q=Q.where("organization_id","=",X.organizationId);if(X.connectionId)Y=Y.where("connection_id","=",X.connectionId),Q=Q.where("connection_id","=",X.connectionId);if(X.virtualMcpId)Y=Y.where("virtual_mcp_id","=",X.virtualMcpId),Q=Q.where("virtual_mcp_id","=",X.virtualMcpId);if(X.toolName)Y=Y.where("tool_name","=",X.toolName),Q=Q.where("tool_name","=",X.toolName);if(X.isError!==void 0)Y=Y.where("is_error","=",X.isError?1:0),Q=Q.where("is_error","=",X.isError?1:0);if(X.startDate)Y=Y.where("timestamp",">=",X.startDate.toISOString()),Q=Q.where("timestamp",">=",X.startDate.toISOString());if(X.endDate)Y=Y.where("timestamp","<=",X.endDate.toISOString()),Q=Q.where("timestamp","<=",X.endDate.toISOString());if(X.propertyFilters){let{properties:$,propertyKeys:K,propertyPatterns:H}=X.propertyFilters;if($)for(let[F,V]of Object.entries($)){let q=this.jsonExtract("properties",F);Y=Y.where(q,"=",V),Q=Q.where(q,"=",V)}if(K&&K.length>0)for(let F of K){let V=this.jsonExtract("properties",F);Y=Y.where(V,"is not",null),Q=Q.where(V,"is not",null)}if(H)for(let[F,V]of Object.entries(H)){let q=this.jsonExtract("properties",F),z=this.databaseType==="postgres"?"ilike":"like";Y=Y.where(q,z,V),Q=Q.where(q,z,V)}}if(Y=Y.orderBy("timestamp","desc"),X.limit)Y=Y.limit(X.limit);if(X.offset)Y=Y.offset(X.offset);let[J,G]=await Promise.all([Y.execute(),Q.executeTakeFirst()]),W=Number(G?.count||0);return{logs:J.map(($)=>this.fromDbRow($)),total:W}}async getStats(X){let Y=this.db.selectFrom("monitoring_logs").where("organization_id","=",X.organizationId);if(X.startDate)Y=Y.where("timestamp",">=",X.startDate.toISOString());if(X.endDate)Y=Y.where("timestamp","<=",X.endDate.toISOString());let Q=await Y.select([(Z)=>Z.fn.count("id").as("total_count"),(Z)=>Z.fn.sum(Z.ref("is_error")).as("error_count"),(Z)=>Z.fn.avg("duration_ms").as("avg_duration")]).executeTakeFirst(),J=Number(Q?.total_count||0),G=Number(Q?.error_count||0),W=Number(Q?.avg_duration||0);return{totalCalls:J,errorRate:J>0?G/J:0,avgDurationMs:W}}toDbRow(X){return{id:X.id||t8("log"),organization_id:X.organizationId,connection_id:X.connectionId,connection_title:X.connectionTitle,tool_name:X.toolName,input:JSON.stringify(X.input),output:JSON.stringify(X.output),is_error:X.isError?1:0,error_message:X.errorMessage||null,duration_ms:X.durationMs,timestamp:X.timestamp instanceof Date?X.timestamp.toISOString():X.timestamp,user_id:X.userId||null,request_id:X.requestId,user_agent:X.userAgent||null,virtual_mcp_id:X.virtualMcpId||null,properties:X.properties?JSON.stringify(X.properties):null}}fromDbRow(X){let Y=typeof X.input==="string"?JSON.parse(X.input):X.input,Q=typeof X.output==="string"?JSON.parse(X.output):X.output,J=typeof X.timestamp==="string"?new Date(X.timestamp):X.timestamp,G=X.properties?typeof X.properties==="string"?JSON.parse(X.properties):X.properties:null;return{id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,connectionTitle:X.connection_title,toolName:X.tool_name,input:Y,output:Q,isError:X.is_error===1,errorMessage:X.error_message,durationMs:X.duration_ms,timestamp:J,userId:X.user_id,requestId:X.request_id,userAgent:X.user_agent,virtualMcpId:X.virtual_mcp_id,properties:G}}}class pX0{db;constructor(X){this.db=X}async get(X){let Y=await this.db.selectFrom("organization_settings").selectAll().where("organizationId","=",X).executeTakeFirst();if(!Y)return null;return{organizationId:Y.organizationId,sidebar_items:Y.sidebar_items?typeof Y.sidebar_items==="string"?JSON.parse(Y.sidebar_items):Y.sidebar_items:null,enabled_plugins:Y.enabled_plugins?typeof Y.enabled_plugins==="string"?JSON.parse(Y.enabled_plugins):Y.enabled_plugins:null,createdAt:Y.createdAt,updatedAt:Y.updatedAt}}async upsert(X,Y){let Q=new Date().toISOString(),J=Y?.sidebar_items?JSON.stringify(Y.sidebar_items):null,G=Y?.enabled_plugins?JSON.stringify(Y.enabled_plugins):null;await this.db.insertInto("organization_settings").values({organizationId:X,sidebar_items:J,enabled_plugins:G,createdAt:Q,updatedAt:Q}).onConflict((Z)=>Z.column("organizationId").doUpdateSet({sidebar_items:J?J:void 0,enabled_plugins:G?G:void 0,updatedAt:Q})).execute();let W=await this.get(X);if(!W)return{organizationId:X,sidebar_items:Y?.sidebar_items??null,enabled_plugins:Y?.enabled_plugins??null,createdAt:Q,updatedAt:Q};return W}}class cX0{db;constructor(X){this.db=X}async findById(X,Y){let Q=await this.db.selectFrom("user").select(["user.id","user.name","user.email","user.image","user.createdAt","user.updatedAt"]).where("user.id","=",X).where((J)=>J.exists(J.selectFrom("member as m1").innerJoin("member as m2","m1.organizationId","m2.organizationId").select("m1.id").where("m1.userId","=",X).where("m2.userId","=",Y))).executeTakeFirst();if(!Q)return null;return{id:Q.id,name:Q.name,email:Q.email,role:"",createdAt:Q.createdAt,updatedAt:Q.updatedAt,image:Q.image??void 0}}}var AG1="mcp.mesh";class TG1 extends Error{constructor(X){super(X);this.name="UnauthorizedError"}}class nX0 extends Error{constructor(X){super(X);this.name="ForbiddenError"}}class UK{userId;toolName;boundAuth;role;connectionId;getToolMeta;_granted=!1;constructor(X,Y,Q,J,G,W="self",Z){this.userId=Y;this.toolName=Q;this.boundAuth=J;this.role=G;this.connectionId=W;this.getToolMeta=Z}[Symbol.dispose](){this._granted=!1}setToolName(X){this.toolName=X}grant(){return this._granted=!0,{[Symbol.dispose]:()=>{this._granted=!1}}}async check(...X){if(this._granted)return;if(!this.userId&&!this.boundAuth){if(this.getToolMeta&&await this.isToolPublic()){this.grant();return}throw new TG1("Authentication required. Please provide a valid OAuth token or API key.")}let Y=X.length>0?X:this.toolName?[this.toolName]:[];if(Y.length===0)throw new nX0("No resources specified for access check");for(let Q of Y)if(await this.checkResource(Q)){this.grant();return}throw new nX0(`Access denied to: ${Y.join(", ")}`)}async checkResource(X){if(!this.userId&&!this.boundAuth)return!1;if(this.role==="admin"||this.role==="owner")return!0;if(!this.boundAuth)return!1;let Y={};if(this.connectionId)Y[this.connectionId]=[X];return this.boundAuth.hasPermission(Y)}async isToolPublic(){if(!this.getToolMeta)return!1;try{let X=await this.getToolMeta();if(!X)return!1;let Q=X[AG1]?.public_tool;return Q===!0||Q==="true"}catch{return!1}}granted(){return this._granted}}q7();function EG1(X){let Y=null;return()=>{if(Y)return Y;return Y=X().catch((Q)=>{throw Y=null,Q}),Y}}class jG1{factory;promise=null;constructor(X){this.factory=X}getOrCreatePromise(){if(!this.promise)this.promise=this.factory();return this.promise}then(X,Y){return this.getOrCreatePromise().then(X,Y)}catch(X){return this.getOrCreatePromise().catch(X)}finally(X){return this.getOrCreatePromise().finally(X)}}function B7(X){return new jG1(X)}class iX0{proxies;options;cache;constructor(X,Y){this.proxies=X;this.options=Y;this.cache=B7(()=>this.loadPrompts())}async loadPrompts(){let X=await this.proxies.mapSettled(async(G,W)=>{try{let $=(await G.proxy.client.listPrompts()).prompts;if(this.options.selectionMode==="exclusion"){if(G.selectedPrompts&&G.selectedPrompts.length>0){let K=new Set(G.selectedPrompts);$=$.filter((H)=>!K.has(H.name))}}else if(!G.selectedPrompts||G.selectedPrompts.length===0)$=[];else{let K=new Set(G.selectedPrompts);$=$.filter((H)=>K.has(H.name))}return{connectionId:W,prompts:$}}catch(Z){return console.error(`[PromptAggregator] Failed to list prompts for connection ${W}:`,Z),{connectionId:W,prompts:[]}}}),Y=new Set,Q=[],J=new Map;for(let G of X){if(G.status!=="fulfilled")continue;let{connectionId:W,prompts:Z}=G.value;for(let $ of Z){if(Y.has($.name))continue;Y.add($.name),Q.push($),J.set($.name,W)}}return{prompts:Q,mappings:J}}async list(){return{prompts:(await this.cache).prompts}}async get(X){let Q=(await this.cache).mappings.get(X.name);if(!Q)throw Error(`Prompt not found: ${X.name}`);let J=this.proxies.get(Q);if(!J)throw Error(`Connection not found for prompt: ${X.name}`);return await J.proxy.client.getPrompt(X)}}qX();function if6(X,Y){if(X===Y)return!0;if(!Y.includes("*"))return!1;let Q=Y.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"<<<DOUBLE_STAR>>>").replace(/\*/g,"[^/]*").replace(/<<<DOUBLE_STAR>>>/g,".*");Q=`^${Q}$`;try{return new RegExp(Q).test(X)}catch{return!1}}function CG1(X,Y){return Y.some((Q)=>if6(X,Q))}class aX0{proxies;options;cache;constructor(X,Y){this.proxies=X;this.options=Y;this.cache=B7(()=>this.loadResources())}async loadResources(){let X=await this.proxies.mapSettled(async(G,W)=>{try{let $=(await G.proxy.client.listResources()).resources;if(this.options.selectionMode==="exclusion"){if(G.selectedResources&&G.selectedResources.length>0)$=$.filter((K)=>!CG1(K.uri,G.selectedResources))}else if(!G.selectedResources||G.selectedResources.length===0)$=[];else $=$.filter((K)=>CG1(K.uri,G.selectedResources));return{connectionId:W,resources:$}}catch(Z){if(!(Z instanceof Q1)||Z.code!==$1.MethodNotFound)console.error(`[aggregator] Failed to list resources for connection ${W}: (defaulting to empty array)`,Z);return{connectionId:W,resources:[]}}}),Y=new Set,Q=[],J=new Map;for(let G of X){if(G.status!=="fulfilled")continue;let{connectionId:W,resources:Z}=G.value;for(let $ of Z){if(Y.has($.uri))continue;Y.add($.uri),Q.push($),J.set($.uri,W)}}return{resources:Q,mappings:J}}async list(){return{resources:(await this.cache).resources}}async read(X){let Q=(await this.cache).mappings.get(X.uri);if(!Q)throw Error(`Resource not found: ${X.uri}`);let J=this.proxies.get(Q);if(!J)throw Error(`Connection not found for resource: ${X.uri}`);return await J.proxy.client.readResource(X)}}qX();class rX0{proxies;cache;constructor(X){this.proxies=X;this.cache=B7(()=>this.loadResourceTemplates())}async loadResourceTemplates(){let X=await this.proxies.mapSettled(async(Q,J)=>{try{let G=await Q.proxy.client.listResourceTemplates();return{connectionId:J,templates:G.resourceTemplates}}catch(G){if(!(G instanceof Q1)||G.code!==$1.MethodNotFound)console.error(`[aggregator] Failed to list resource templates for connection ${J}: (defaulting to empty array)`,G);return{connectionId:J,templates:[]}}}),Y=[];for(let Q of X){if(Q.status!=="fulfilled")continue;let{templates:J}=Q.value;for(let G of J)Y.push(G)}return{templates:Y}}async list(){return{resourceTemplates:(await this.cache).templates}}}qX();a0();jP();var RG1=U.object({query:U.string().min(1).describe("Search query to find tools by name or description"),limit:U.number().default(10).describe("Maximum number of results to return")}),af6=U.toJSONSchema(RG1),SG1=U.object({tools:U.array(U.string()).min(1).describe("Array of tool names to get detailed schemas for")}),rf6=U.toJSONSchema(SG1),kG1=U.object({code:U.string().min(1).describe("JavaScript code to execute. It runs as an async function body; you can use top-level `return` and `await`."),timeoutMs:U.number().default(3000).describe("Max execution time in milliseconds (default: 3000).")}),of6=U.toJSONSchema(kG1),IG1=new Map;function sf6(X){let Y=X.slice().sort().join(","),Q=IG1.get(Y);if(!Q){let J=U.object({name:(X.length>0?U.enum(X):U.string()).describe("The name of the tool to execute"),arguments:U.record(U.string(),U.unknown()).default({}).describe("Arguments to pass to the tool")});Q={schema:J,jsonSchema:U.toJSONSchema(J)},IG1.set(Y,Q)}return Q}function vG1(X){let Y=EP(X.tools);return{tool:{name:"GATEWAY_SEARCH_TOOLS",description:`Search for available tools by name or description. Returns tool names and brief descriptions without full schemas. Use this to discover tools before calling GATEWAY_DESCRIBE_TOOLS for detailed schemas.${X.categories.length>0?` Available categories: ${X.categories.join(", ")}.`:""} Total tools: ${Y.length}.`,inputSchema:af6},handler:async(J)=>{let G=RG1.safeParse(J);if(!G.success)return QB({error:G.error.flatten()});let W=Fb(G.data.query,Y,G.data.limit);return Ub({query:G.data.query,results:W.map((Z)=>({name:Z.name,description:Z.description,connection:Z._meta.connectionTitle})),totalAvailable:Y.length})}}}function _G1(X){let Y=EP(X.tools);return{tool:{name:"GATEWAY_DESCRIBE_TOOLS",description:"Get detailed schemas for specific tools. Call after GATEWAY_SEARCH_TOOLS to get full input/output schemas.",inputSchema:rf6},handler:async(Q)=>{let J=SG1.safeParse(Q);if(!J.success)return QB({error:J.error.flatten()});let G=Vb(J.data.tools,Y);return Ub({tools:G.tools,notFound:G.notFound})}}}function tf6(X){let Y=EP(X.tools),Q=Y.map((Z)=>Z.name),J=new Map(Y.map((Z)=>[Z.name,Z])),{schema:G,jsonSchema:W}=sf6(Q);return{tool:{name:"GATEWAY_CALL_TOOL",description:"Execute a tool by name. Use GATEWAY_DESCRIBE_TOOLS first to understand the input schema.",inputSchema:W},handler:async(Z)=>{let $=G.safeParse(Z);if(!$.success)return QB({error:$.error.flatten()});let{name:K,arguments:H}=$.data;if(!J.has(K))return{content:[{type:"text",text:`Tool not found: ${K}. Use GATEWAY_SEARCH_TOOLS to find available tools.`}],isError:!0};return X.callTool(K,H)}}}function ef6(X){let Y=EP(X.tools);return{tool:{name:"GATEWAY_RUN_CODE",description:'Run JavaScript code in a sandbox. Code must be an ES module that `export default`s an async function that receives (tools) as its first parameter. Use GATEWAY_DESCRIBE_TOOLS to understand the input/output schemas for a tool before calling it. Use `await tools.toolName(args)` or `await tools["tool-name"](args)` to call tools.',inputSchema:of6},handler:async(Q)=>{let J=kG1.safeParse(Q);if(!J.success)return QB({error:J.error.flatten()});let G={...X,tools:Y},W=await qb(J.data.code,G,J.data.timeoutMs);if(W.error)return QB(W);return Ub(W)}}}function yG1(X){let Y=new Map(X.map((J)=>[J.tool.name,J.handler])),Q=X.map((J)=>J.tool.name);return{tools:X.map((J)=>J.tool),callTool:async(J,G)=>{let W=Y.get(J);if(!W)return{content:[{type:"text",text:`Unknown meta-tool: ${J}. Available: ${Q.join(", ")}`}],isError:!0};return W(G)}}}var Xh6=(X)=>({tools:X.tools,callTool:(Y,Q)=>X.callTool(Y,Q)}),Yh6=(X)=>yG1([vG1(X),_G1(X),ef6(X)]),Qh6=(X)=>yG1([vG1(X),_G1(X),tf6(X)]);function bG1(X){switch(X){case"smart_tool_selection":return Qh6;case"code_execution":return Yh6;case"passthrough":default:return Xh6}}function fG1(X){switch(X){case"smart_tool_selection":return"smart_tool_selection";case"code_execution":return"code_execution";case"passthrough":default:return"passthrough"}}class oX0{proxies;options;cache;constructor(X,Y){this.proxies=X;this.options=Y;this.cache=B7(()=>this.loadTools())}async loadTools(){let X=await this.proxies.mapSettled(async(K,H)=>{try{let V=(await K.proxy.client.listTools()).tools;if(this.options.selectionMode==="exclusion"){if(K.selectedTools&&K.selectedTools.length>0){let q=new Set(K.selectedTools);V=V.filter((z)=>!q.has(z.name))}}else if(K.selectedTools&&K.selectedTools.length>0){let q=new Set(K.selectedTools);V=V.filter((z)=>q.has(z.name))}return{connectionId:H,connectionTitle:K.connection.title,tools:V}}catch(F){if(!(F instanceof Q1)||F.code!==$1.MethodNotFound)console.error(`[aggregator] Failed to list tools ${H}: (defaulting to null)`,F);return null}}),Y=new Set,Q=[],J=new Map,G=new Set;for(let K of X){if(K.status!=="fulfilled"||!K.value)continue;let{connectionId:H,connectionTitle:F,tools:V}=K.value;G.add(F);for(let q of V){if(Y.has(q.name))continue;Y.add(q.name),Q.push({...q,_meta:{connectionId:H,connectionTitle:F}}),J.set(q.name,{connectionId:H,originalName:q.name})}}let W=async(K,H)=>{let F=J.get(K);if(!F)return{content:[{type:"text",text:`Tool not found: ${K}`}],isError:!0};let V=this.proxies.get(F.connectionId);if(!V)return{content:[{type:"text",text:`Connection not found for tool: ${K}`}],isError:!0};return await V.proxy.client.callTool({name:F.originalName,arguments:H})},$=bG1(this.options.strategy)({tools:Q,callTool:W,categories:Array.from(G).sort()});return{tools:Q,mappings:J,strategyResult:$}}async list(){return{tools:(await this.cache).strategyResult.tools}}async call(X){return(await this.cache).strategyResult.callTool(X.name,X.arguments??{})}async callStreamable(X,Y){let Q=await this.cache,J=Q.mappings.get(X);if(J){let W=this.proxies.get(J.connectionId);if(W)return W.proxy.callStreamableTool(J.originalName,Y)}let G=await Q.strategyResult.callTool(X,Y);return new Response(JSON.stringify(G),{headers:{"Content-Type":"application/json"}})}}function hG1(X,Y){if(X.connection_type!=="VIRTUAL")return!1;return $K(X.connection_url)===Y}async function Jh6(X,Y){let Q=await sz.create(X.connections,Y),J=new oX0(Q,{selectionMode:X.toolSelectionMode,strategy:X.toolSelectionStrategy}),G=new aX0(Q,{selectionMode:X.toolSelectionMode}),W=new rX0(Q),Z=new iX0(Q,{selectionMode:X.toolSelectionMode});return{client:{listTools:J.list.bind(J),callTool:J.call.bind(J),listResources:G.list.bind(G),readResource:G.read.bind(G),listResourceTemplates:W.list.bind(W),listPrompts:Z.list.bind(Z),getPrompt:Z.get.bind(Z)},callStreamableTool:J.callStreamable.bind(J)}}async function aP(X,Y,Q){let J;if(X.tool_selection_mode==="exclusion"){let Z=(await Y.storage.connections.list(X.organization_id)).filter((K)=>K.status==="active"&&!hG1(K,X.id)),$=new Map;for(let K of X.connections)$.set(K.connection_id,{selectedTools:K.selected_tools,selectedResources:K.selected_resources,selectedPrompts:K.selected_prompts});J=[];for(let K of Z){let H=$.get(K.id);if(H===void 0)J.push({connection:K,selectedTools:null,selectedResources:null,selectedPrompts:null});else if((H.selectedTools===null||H.selectedTools.length===0)&&(H.selectedResources===null||H.selectedResources.length===0)&&(H.selectedPrompts===null||H.selectedPrompts.length===0));else J.push({connection:K,selectedTools:H.selectedTools,selectedResources:H.selectedResources,selectedPrompts:H.selectedPrompts})}}else{let W=X.connections.map(($)=>$.connection_id),Z=[];for(let $ of W){let K=await Y.storage.connections.findById($);if(K&&K.status==="active"&&!hG1(K,X.id))Z.push(K)}J=Z.map(($)=>{let K=X.connections.find((H)=>H.connection_id===$.id);return{connection:$,selectedTools:K?.selected_tools??null,selectedResources:K?.selected_resources??null,selectedPrompts:K?.selected_prompts??null}})}let G={connections:J,toolSelectionMode:X.tool_selection_mode,toolSelectionStrategy:Q};return Jh6(G,Y)}e80();async function xG1(X){if(!X.refreshToken)return{success:!1,error:"No refresh token available"};if(!X.tokenEndpoint)return{success:!1,error:"No token endpoint available"};if(!X.clientId)return{success:!1,error:"No client ID available"};try{let Y=new URLSearchParams({grant_type:"refresh_token",refresh_token:X.refreshToken,client_id:X.clientId});if(X.clientSecret)Y.set("client_secret",X.clientSecret);if(X.scope)Y.set("scope",X.scope);let Q=await fetch(X.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Y.toString()});if(!Q.ok){let G=await Q.text();console.error(`[TokenRefresh] Failed to refresh token: ${Q.status}`,G);try{let W=JSON.parse(G);return{success:!1,error:W.error_description||W.error||`Token refresh failed: ${Q.status}`}}catch{return{success:!1,error:`Token refresh failed: ${Q.status}`}}}let J=await Q.json();return{success:!0,accessToken:J.access_token,refreshToken:J.refresh_token||X.refreshToken,expiresIn:J.expires_in,scope:J.scope}}catch(Y){return console.error("[TokenRefresh] Error refreshing token:",Y),{success:!1,error:Y instanceof Error?Y.message:"Token refresh failed"}}}eH();H80();function Gh6(X){return new Proxy(X,{get(Q,J,G){if(J==="close")return async()=>{};if(J==="__actualClient")return Q;return Reflect.get(Q,J,G)}})}var gG1="__mesh_stable_stdio_pool__",MF=globalThis[gG1]??(globalThis[gG1]=new Map);async function mG1(X,Y){let Q=MF.get(X.id);if(Q?.status==="connected"&&Q.stableClient)return Q.stableClient;if(Q?.connectPromise&&(Q.status==="connecting"||Q.status==="reconnecting"))return Q.connectPromise;let J=Q?.status==="failed",G=Q??{transport:null,client:null,stableClient:null,config:X,status:"connecting",connectPromise:null};if(!Q)MF.set(X.id,G);return G.status=J?"reconnecting":"connecting",G.connectPromise=(async()=>{try{console.log(`[StableStdio] ${J?"Respawning":"Spawning"}: ${X.id} (${X.command} ${X.args?.join(" ")??""})`);let W=new wP({command:X.command,args:X.args,env:X.env,cwd:X.cwd,stderr:"pipe"});G.transport=W;let Z=Y??new l9({name:`mesh-stdio-${X.id}`,version:"1.0.0"});G.client=Z,G.stableClient=Gh6(Z),Z.onclose=()=>{console.log(`[StableStdio] Connection closed unexpectedly: ${X.id}`),G.status="failed",G.connectPromise=null};let $=X.name||X.id,K="\x1B[2m",H="\x1B[0m";W.stderr?.on("data",(q)=>{let z=q.toString().trimEnd();if(z)console.error(`${z} ${K}[${$}]${H}`)});let F=new AbortController,V=setTimeout(()=>F.abort(),30000);try{await Promise.race([Z.connect(W),new Promise((q,z)=>{F.signal.addEventListener("abort",()=>{z(Error("Stdio connection timeout after 30s"))})})])}finally{clearTimeout(V)}return G.status="connected",console.log(`[StableStdio] Connected: ${X.id}`),G.stableClient}catch(W){console.error(`[StableStdio] Failed to connect ${X.id}:`,W),G.status="failed",G.connectPromise=null;try{await G.transport?.close()}catch{}throw W}})(),G.connectPromise}async function Wh6(X){let Y=MF.get(X);if(!Y)return;console.log(`[StableStdio] Force closing: ${X}`);try{if(Y.client)Y.client.onclose=void 0;await Y.client?.close()}catch{}MF.delete(X)}async function Zh6(){console.log(`[StableStdio] Closing all connections (${MF.size})`);let X=Array.from(MF.keys()).map((Y)=>Wh6(Y));await Promise.allSettled(X),MF.clear()}var uG1="__mesh_stable_stdio_shutdown_registered__";if(!globalThis[uG1]){globalThis[uG1]=!0;let X=async(Y)=>{await Zh6(),process.exit(Y==="SIGINT"?130:143)};process.on("SIGINT",()=>X("SIGINT")),process.on("SIGTERM",()=>X("SIGTERM"))}Ab();q7();eH();Xb();oq();Gb();Wb();qX();Gb();Wb();qX();gL();var sX0=new p8;async function Cb(X,Y){let Q=X.get("meshContext");try{let J=X.req.header("x-org-id"),G=X.req.header("x-org-slug"),W=J?J:G?await Q.db.selectFrom("organization").select("id").where("slug","=",G).executeTakeFirst().then((z)=>z?.id):null,Z=Y?await Q.storage.virtualMcps.findById(Y):W?Eo(W):null;if(!Z)return X.json({error:"Agent not found"},404);if(W&&Z.organization_id!==W)return X.json({error:"Agent not found"},404);if(Z.status!=="active")return X.json({error:`Agent is inactive: ${Z.id}`},503);Q.connectionId=Z.id;let $=await Q.db.selectFrom("organization").select(["id","slug","name"]).where("id","=",Z.organization_id).executeTakeFirst();if($)Q.organization={id:$.id,slug:$.slug,name:$.name};let K=X.req.query("mode"),H=fG1(K),F=await aP(Z,Q,H),V=new qF({name:`mcp-virtual-mcp-${Z.title}`,version:"1.0.0"},{capabilities:{tools:{},resources:{},prompts:{}},instructions:Z.metadata?.instructions??void 0}),q=new UF({enableJsonResponse:X.req.header("Accept")?.includes("application/json")??!1});await V.connect(q),V.server.setRequestHandler(eZ,async(z)=>{return F.client.listTools()}),V.server.setRequestHandler(TG,async(z)=>{return await F.client.callTool(z.params)}),V.server.setRequestHandler(aZ,async()=>{return F.client.listResources()}),V.server.setRequestHandler(oZ,async(z)=>{return F.client.readResource(z.params)}),V.server.setRequestHandler(rZ,async()=>{return F.client.listResourceTemplates()}),V.server.setRequestHandler(sZ,async()=>{return F.client.listPrompts()}),V.server.setRequestHandler(tZ,async(z)=>{return F.client.getPrompt(z.params)});try{return await q.handleRequest(X.req.raw)}finally{try{await q.close?.()}catch{}}}catch(J){let G=J;return console.error("[virtual-mcp] Error handling virtual MCP request:",G),X.json({error:"Internal server error",message:G.message},500)}}sX0.all("/gateway/:virtualMcpId?",async(X)=>{let Y=X.req.param("virtualMcpId");return Cb(X,Y)});sX0.all("/virtual-mcp/:virtualMcpId?",async(X)=>{let Y=X.req.param("virtualMcpId");return Cb(X,Y)});var lG1=sX0;var Ib=new p8,tX0=[404,401,406];async function dG1(X,Y){return(await Y.storage.connections.findById(X))?.connection_url??null}function $h6(X){let Y=X.toLowerCase();return Y.includes("resource_metadata=")||Y.includes("invalid_token")||Y.includes("oauth")}async function pG1(X,Y={}){try{let Q=await fetch(X,{method:"POST",headers:{...Y,"Content-Type":"application/json",Accept:"application/json, text/event-stream"},body:JSON.stringify({jsonrpc:"2.0",id:0,method:"initialize",params:{protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"mcp-mesh-proxy",version:"1.0.0"}}})});if(Q.status===401){let J=Q.headers.get("WWW-Authenticate");if(J){if($h6(J))return J}}return null}catch{return null}}async function Rb(X){let Q=new URL(X).pathname;if(Q.endsWith("/"))Q=Q.slice(0,-1);let J=new URL(X);J.pathname=`${Q}/.well-known/oauth-protected-resource`;let G=await fetch(J.toString(),{method:"GET",headers:{Accept:"application/json"}});if(G.ok)return G;if(!tX0.includes(G.status))return G;let W=new URL(X);if(W.pathname=`/.well-known/oauth-protected-resource${Q}`,G=await fetch(W.toString(),{method:"GET",headers:{Accept:"application/json"}}),!tX0.includes(G.status))return G;let Z=new URL(X);return Z.pathname="/.well-known/oauth-protected-resource",G=await fetch(Z.toString(),{method:"GET",headers:{Accept:"application/json"}}),G}async function Kh6(X,Y){let Q=await dG1(X,Y);if(!Q)return null;let J;try{J=new URL(Q).origin}catch{return null}try{let G=await Rb(Q);if(G.ok){let W=await G.json();if(W.authorization_servers?.[0])return W.authorization_servers[0]}}catch{}return J}async function cG1(X){let Y=X.get("meshContext");if(!Y)Y=await zK.create(X.req.raw),X.set("meshContext",Y);return Y}async function nG1({error:X,reqUrl:Y,connectionId:Q,connectionUrl:J,headers:G}){let W=X.message?.toLowerCase()??"";if(!(X.status===401||X.code===401||X.message?.includes("401")||W.includes("unauthorized")||W.includes("invalid_token")||W.includes("api key required")||W.includes("api-key required")))return null;if(Boolean(await pG1(J,G)))return new Response(null,{status:401,headers:{"WWW-Authenticate":`Bearer realm="mcp",resource_metadata="${Y.origin}/mcp/${Q}/.well-known/oauth-protected-resource"`}});return new Response(JSON.stringify({error:"unauthorized",message:"Authentication required but server does not support OAuth"}),{status:401,headers:{"Content-Type":"application/json"}})}var Sb=(X)=>{if(!(X.hostname==="localhost"||X.hostname==="127.0.0.1"))X.protocol="https:";return X},iG1=async(X)=>{let Y=X.req.param("connectionId"),Q=await cG1(X),J=await dG1(Y,Q);if(!J)return X.json({error:"Connection not found"},404);let G=Sb(new URL(X.req.url)),W=`${G.origin}/mcp/${Y}`,Z=`${G.origin}/oauth-proxy/${Y}`;try{let $=await Rb(J);if(!$.ok&&tX0.includes($.status)){if(await pG1(J))return new Response(JSON.stringify({resource:W,authorization_servers:[Z],bearer_methods_supported:["header"],scopes_supported:["*"]}),{status:200,headers:{"Content-Type":"application/json"}});return new Response($.body,{status:$.status,statusText:$.statusText,headers:{"Content-Type":"application/json"}})}if(!$.ok)return new Response($.body,{status:$.status,statusText:$.statusText,headers:{"Content-Type":"application/json"}});let H={...await $.json(),resource:W,authorization_servers:[Z]};return new Response(JSON.stringify(H),{status:$.status,statusText:$.statusText,headers:{"Content-Type":"application/json"}})}catch($){let K=$;return console.error("[oauth-proxy] Failed to proxy OAuth protected resource metadata:",K),X.json({error:"Failed to proxy OAuth metadata",message:K.message},502)}};Ib.get("/.well-known/oauth-protected-resource/mcp/:connectionId",(X)=>iG1(X));Ib.get("/mcp/:connectionId/.well-known/oauth-protected-resource",(X)=>iG1(X));async function eX0(X){let Q=new URL(X).pathname;if(Q.endsWith("/"))Q=Q.slice(0,-1);let J=Q!==""&&Q!=="/",G=[];if(J){let Z=new URL(X);Z.pathname=`/.well-known/oauth-authorization-server${Q}`,G.push(Z);let $=new URL(X);$.pathname=`/.well-known/openid-configuration${Q}`,G.push($);let K=new URL(X);K.pathname=`${Q}/.well-known/openid-configuration`,G.push(K)}else{let Z=new URL(X);Z.pathname="/.well-known/oauth-authorization-server",G.push(Z);let $=new URL(X);$.pathname="/.well-known/openid-configuration",G.push($)}let W=null;for(let Z of G){if(W=await fetch(Z.toString(),{method:"GET",headers:{Accept:"application/json"}}),W.ok)return W;if(W.status!==404&&W.status!==401)return W}return W}Ib.get("/.well-known/oauth-authorization-server/oauth-proxy/:connectionId",async(X)=>{let Y=X.req.param("connectionId"),Q=await cG1(X),J=await Kh6(Y,Q);if(!J)return X.json({error:"Connection not found or no auth server"},404);try{let G=await eX0(J);if(!G.ok)return new Response(G.body,{status:G.status,statusText:G.statusText,headers:{"Content-Type":"application/json"}});let W=await G.json(),$=`${Sb(new URL(X.req.url)).origin}/oauth-proxy/${Y}`,K={...W,authorization_endpoint:W.authorization_endpoint?`${$}/authorize`:void 0,token_endpoint:W.token_endpoint?`${$}/token`:void 0,registration_endpoint:W.registration_endpoint?`${$}/register`:void 0};return new Response(JSON.stringify(K),{status:200,headers:{"Content-Type":"application/json"}})}catch(G){let W=G;return console.error("[oauth-proxy] Failed to proxy auth server metadata:",W),X.json({error:"Failed to proxy auth server metadata",message:W.message},502)}});var aG1=Ib;function Hh6(X){if(!X.isError)return;let Y=X.content;if(!Array.isArray(Y))return;for(let Q of Y)if(Q&&typeof Q==="object"&&"type"in Q&&Q.type==="text"&&"text"in Q&&typeof Q.text==="string")return Q.text;return}function Fh6(X){if(!X)return;let Y=X._meta;if(!Y||typeof Y!=="object"||Array.isArray(Y))return;let Q=Y.properties;if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let J={};for(let[G,W]of Object.entries(Q))if(typeof W==="string")J[G]=W;return Object.keys(J).length>0?J:void 0}function Vh6(X,Y){if(!X&&!Y)return;if(!X)return Y;if(!Y)return X;return{...Y,...X}}function rG1(X){if(X&&typeof X==="object"&&!Array.isArray(X)){let Y=X,Q=Y.structuredContent;if(Q&&typeof Q==="object"&&!Array.isArray(Q))return Q;return Y}return{value:X}}async function qh6(X,Y){let Q=X.body;if(!Q)return{text:"",truncated:!1};let J=Q.getReader(),G=new TextDecoder,W=!1,Z=0,$=[];try{while(!0){let{value:K,done:H}=await J.read();if(H)break;if(K){if(Z+=K.byteLength,Z>Y){W=!0;let F=Y-(Z-K.byteLength);if(F>0)$.push(G.decode(K.slice(0,F),{stream:!0}));break}$.push(G.decode(K,{stream:!0}))}}}finally{J.releaseLock()}return $.push(G.decode()),{text:$.join(""),truncated:W}}async function rP(X){let{ctx:Y,enabled:Q}=X,J=X.organizationId??Y.organization?.id;if(!Q||!J)return;let G=Fh6(X.request.params.arguments),W=Vh6(Y.metadata.properties,G);await Y.storage.monitoring.log({organizationId:J,connectionId:X.connectionId,connectionTitle:X.connectionTitle,toolName:X.request.params.name,input:X.request.params.arguments??{},output:X.output,isError:X.isError,errorMessage:X.errorMessage,durationMs:X.durationMs,timestamp:new Date,userId:Y.auth.user?.id||Y.auth.apiKey?.userId||null,requestId:Y.metadata.requestId,userAgent:Y.metadata.userAgent,virtualMcpId:X.virtualMcpId,properties:W})}function oG1(X){let{ctx:Y,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:W}=X;return async(Z,$)=>{let K=Date.now();try{let H=await $(),F=Date.now()-K;return await rP({ctx:Y,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:W,request:Z,output:rG1(H),isError:Boolean(H.isError),errorMessage:Hh6(H),durationMs:F}),H}catch(H){let F=H,V=Date.now()-K;throw await rP({ctx:Y,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:W,request:Z,output:{},isError:!0,errorMessage:F.message,durationMs:V}),H}}}function sG1(X){let{ctx:Y,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:W}=X;return async(Z,$)=>{let K=Date.now();try{let H=await $(),F=Y.organization?.id;if(Q&&F){let V=H.clone();(async()=>{try{let{text:q,truncated:z}=await qh6(V,262144),D=Date.now()-K,N=V.headers.get("content-type")??"",L=q;if(N.includes("application/json"))try{L=q.length?JSON.parse(q):null}catch{L=q}let w=H.status>=400,C=w&&L&&typeof L==="object"&&"error"in L?L.error:void 0,T=typeof C==="string"&&C?C:w&&typeof L==="string"&&L.trim()?L.slice(0,500):w?`HTTP ${H.status} ${H.statusText}`.trim():z?"Response body truncated to 262144 bytes":void 0;await rP({ctx:Y,enabled:Q,organizationId:F,connectionId:J,connectionTitle:G,virtualMcpId:W,request:Z,output:rG1(L),isError:w,errorMessage:T,durationMs:D})}catch(q){let z=Date.now()-K;await rP({ctx:Y,enabled:Q,organizationId:F,connectionId:J,connectionTitle:G,virtualMcpId:W,request:Z,output:{},isError:!0,errorMessage:`Failed to read streamable response body: ${q.message}`,durationMs:z})}})()}return H}catch(H){let F=H,V=Date.now()-K;throw await rP({ctx:Y,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:W,request:Z,output:{},isError:!0,errorMessage:F.message,durationMs:V}),H}}}var kb=new p8,XY0=300000;function Uh6(X,Y,Q){return async(J,G)=>{try{let W=J.params.name,Z=async()=>{let{tools:K}=await Q();return K.find((F)=>F.name===W)?._meta};return await new UK(X.authInstance,X.auth.user?.id??X.auth.apiKey?.userId,W,X.boundAuth,X.auth.user?.role,Y,Z).check(W),await G()}catch(W){return{content:[{type:"text",text:`Authorization failed: ${W.message}`}],isError:!0}}}}function zh6(X,Y,Q){return async(J,G)=>{try{let W=J.params.name,Z=async()=>{let{tools:K}=await Q();return K.find((F)=>F.name===W)?._meta};return await new UK(X.authInstance,X.auth.user?.id??X.auth.apiKey?.userId,W,X.boundAuth,X.auth.user?.role,Y,Z).check(W),await G()}catch(W){return new Response(JSON.stringify({error:`Authorization failed: ${W.message}`}),{status:403,headers:{"Content-Type":"application/json"}})}}}async function tG1(X,Y,{superUser:Q}){let J=typeof X==="string"?await Y.storage.connections.findById(X,Y.organization?.id):X;if(!J)throw Error("Connection not found");let G=J?.id;if(Y.organization&&J.organization_id!==Y.organization.id)throw Error("Connection does not belong to the active organization");if(Y.organization??={id:J.organization_id},J.status!=="active")throw Error(`Connection inactive: ${J.status}`);let W,Z=Y.auth.user?.connectionId,$=EG1(async()=>{let S=t80(J.configuration_state,J.configuration_scopes),f=Y.auth.user?.id??Y.auth.apiKey?.userId;if(!f){console.error("User ID required to issue configuration token");return}try{W=await MG1({sub:f,user:{id:f},metadata:{state:J.configuration_state??void 0,meshUrl:process.env.MESH_URL??Y.baseUrl,connectionId:G,organizationId:Y.organization?.id},permissions:S})}catch(t){console.error("Failed to issue configuration token:",t)}}),K=async()=>{await $();let S={...Z?{"x-caller-id":Z}:{},...Y.metadata.wellKnownForwardableHeaders??{}},f=null,t=new rW(Y.db,Y.vault),m=await t.get(G);if(m){let J0=!!m.refreshToken&&!!m.tokenEndpoint;if(t.isExpired(m,J0?300000:0))if(J0){console.log(`[Proxy] Token expired for ${G}, attempting refresh`);let Y0=await xG1(m);if(Y0.success&&Y0.accessToken)await t.upsert({connectionId:G,accessToken:Y0.accessToken,refreshToken:Y0.refreshToken??m.refreshToken,scope:Y0.scope??m.scope,expiresAt:Y0.expiresIn?new Date(Date.now()+Y0.expiresIn*1000):null,clientId:m.clientId,clientSecret:m.clientSecret,tokenEndpoint:m.tokenEndpoint}),f=Y0.accessToken,console.log(`[Proxy] Token refreshed for ${G}`);else await t.delete(G),console.error(`[Proxy] Token refresh failed for ${G}: ${Y0.error}`)}else await t.delete(G),console.log(`[Proxy] Token expired without refresh capability for ${G}`);else f=m.accessToken}if(!f&&J.connection_token)f=J.connection_token;if(f)S.Authorization=`Bearer ${f}`;if(W)S["x-mesh-token"]=W;return S},H=J.connection_type==="STDIO",F=KF(J.connection_headers)?J.connection_headers:null,V=!H?J.connection_headers:null,q=async()=>{let S=new l9({name:"mcp-mesh-proxy",version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});switch(J.connection_type){case"STDIO":{if(process.env.UNSAFE_ALLOW_STDIO_TRANSPORT!=="true")throw Error("STDIO connections are disabled in production. Set UNSAFE_ALLOW_STDIO_TRANSPORT=true to enable.");if(!F)throw Error("STDIO connection missing parameters");return mG1({id:G,name:J.title,command:F.command,args:F.args,env:F.envVars,cwd:F.cwd},S)}case"HTTP":case"Websocket":{if(!J.connection_url)throw Error(`${J.connection_type} connection missing URL`);let f=await K();if(V?.headers)Object.assign(f,V.headers);let t=new IG(new URL(J.connection_url),{requestInit:{headers:f}});return await S.connect(t),S}case"SSE":{if(!J.connection_url)throw Error("SSE connection missing URL");let f=await K();if(V?.headers)Object.assign(f,V.headers);let t=new VF(new URL(J.connection_url),{requestInit:{headers:f}});return await S.connect(t),S}case"VIRTUAL":{let f=$K(J.connection_url);if(!f)throw Error("VIRTUAL connection missing virtual MCP ID in connection_url");let t=await Y.storage.virtualMcps.findById(f);if(!t)throw Error(`Virtual MCP not found: ${f}`);let m=await aP(t,Y,"passthrough");return{callTool:(J0)=>m.client.callTool(J0),listTools:()=>m.client.listTools(),listResources:()=>m.client.listResources(),readResource:(J0)=>m.client.readResource(J0),listResourceTemplates:()=>m.client.listResourceTemplates(),listPrompts:()=>m.client.listPrompts(),getPrompt:(J0)=>m.client.getPrompt(J0),close:async()=>{},getServerCapabilities:()=>({tools:{},resources:{},prompts:{}}),getInstructions:()=>t.metadata?.instructions??void 0}}default:throw Error(`Unknown connection type: ${J.connection_type}`)}},z=async()=>{if(J.tools&&J.tools.length>0)return{tools:J.tools.map((f)=>({name:f.name,description:f.description,inputSchema:f.inputSchema,outputSchema:f.outputSchema,annotations:f.annotations,_meta:f._meta}))};let S;try{return S=await q(),await S.listTools()}finally{S?.close().catch(console.error)}},D=Q?async(S,f)=>await f():Uh6(Y,G,z),N=Q?async(S,f)=>await f():zh6(Y,G,z),L=Y.connectionId&&Y.connectionId!==G?Y.connectionId:void 0,w={enabled:A81().enabled,connectionId:G,connectionTitle:J.title,virtualMcpId:L,ctx:Y},C=oG1(w),T=sG1(w),A=PP(C,D),P=PP(T,N),j=async(S)=>{return A(S,async()=>{let f=await q(),t=Date.now(),m={...S.params};if(m.arguments&&"_meta"in m.arguments){let{_meta:J0,...V0}=m.arguments;m.arguments=V0}return await Y.tracer.startActiveSpan("mcp.proxy.callTool",{attributes:{"connection.id":G,"tool.name":S.params.name}},async(J0)=>{try{let V0=await f.callTool(m,void 0,{timeout:XY0}),Y0=Date.now()-t;return Y.meter.createHistogram("connection.proxy.duration").record(Y0,{"connection.id":G,"tool.name":S.params.name,status:"success"}),Y.meter.createCounter("connection.proxy.requests").add(1,{"connection.id":G,"tool.name":S.params.name,status:"success"}),J0.end(),V0}catch(V0){let Y0=V0,U0=Date.now()-t;throw Y.meter.createHistogram("connection.proxy.duration").record(U0,{"connection.id":G,"tool.name":S.params.name,status:"error"}),Y.meter.createCounter("connection.proxy.errors").add(1,{"connection.id":G,"tool.name":S.params.name,error:Y0.message}),J0.recordException(Y0),J0.end(),V0}finally{f.close().catch(console.error)}})})};return{fetch:async(S)=>{let f=new URL(S.url),t;try{t=await q()}catch(P0){let v0=J.connection_url?await nG1({error:P0,reqUrl:f,connectionId:G,connectionUrl:J.connection_url,headers:await K()}):null;if(v0)return v0;throw P0}let m=t.getServerCapabilities(),J0=t.getInstructions(),V0=m??{tools:{},resources:{},prompts:{}},Y0=new qF({name:"mcp-mesh",version:"1.0.0"},{capabilities:V0,instructions:J0}),U0=new UF({enableJsonResponse:S.headers.get("Accept")?.includes("application/json")??!1});if(await Y0.connect(U0),Y0.server.setRequestHandler(eZ,()=>t.listTools()),Y0.server.setRequestHandler(TG,j),V0.resources)Y0.server.setRequestHandler(aZ,()=>t.listResources()),Y0.server.setRequestHandler(oZ,(P0)=>t.readResource(P0.params)),Y0.server.setRequestHandler(rZ,()=>t.listResourceTemplates());if(V0.prompts)Y0.server.setRequestHandler(sZ,()=>t.listPrompts()),Y0.server.setRequestHandler(tZ,(P0)=>t.getPrompt(P0.params));try{return await U0.handleRequest(S)}finally{try{await t.close()}catch{}try{await U0.close?.()}catch{}}},client:{callTool:(S)=>{return j({method:"tools/call",params:S})},listTools:z,listResources:async()=>{let S;try{return S=await q(),await S.listResources()}catch(f){if(f instanceof Q1&&f.code===$1.MethodNotFound)return{resources:[]};throw f}finally{S?.close().catch(console.error)}},readResource:async(S)=>{let f;try{return f=await q(),await f.readResource(S)}finally{f?.close().catch(console.error)}},listResourceTemplates:async()=>{let S;try{return S=await q(),await S.listResourceTemplates()}catch(f){if(f instanceof Q1&&f.code===$1.MethodNotFound)return{resourceTemplates:[]};throw f}finally{S?.close().catch(console.error)}},listPrompts:async()=>{let S;try{return S=await q(),await S.listPrompts()}catch(f){if(f instanceof Q1&&f.code===$1.MethodNotFound)return{prompts:[]};throw f}finally{S?.close().catch(console.error)}},getPrompt:async(S)=>{let f;try{return f=await q(),await f.getPrompt(S)}finally{f?.close().catch(console.error)}}},callStreamableTool:async(S,f)=>{if(J.connection_type==="VIRTUAL"){let J0=await j({method:"tools/call",params:{name:S,arguments:f}});return new Response(JSON.stringify(J0),{headers:{"Content-Type":"application/json"}})}if(!J.connection_url)throw Error("Streamable tools require HTTP connection with URL");let t=J.connection_url,m={method:"tools/call",params:{name:S,arguments:f}};return P(m,async()=>{let J0=await K();if(V?.headers)Object.assign(J0,V.headers);let V0=new URL(t);return V0.pathname=V0.pathname.replace(/\/$/,"")+`/call-tool/${m.params.name}`,await Y.tracer.startActiveSpan("mcp.proxy.callStreamableTool",{attributes:{"connection.id":G,"tool.name":m.params.name}},async(Y0)=>{let U0=Date.now();try{let P0=await fetch(V0.toString(),{method:"POST",redirect:"manual",body:JSON.stringify(m.params.arguments),headers:{...J0,"Content-Type":"application/json"}}),v0=Date.now()-U0;return Y.meter.createHistogram("connection.proxy.streamable.duration").record(v0,{"connection.id":G,"tool.name":m.params.name,status:P0.ok?"success":"error"}),Y.meter.createCounter("connection.proxy.streamable.requests").add(1,{"connection.id":G,"tool.name":m.params.name,status:P0.ok?"success":"error"}),Y0.end(),P0}catch(P0){let v0=P0,G1=Date.now()-U0;throw Y.meter.createHistogram("connection.proxy.streamable.duration").record(G1,{"connection.id":G,"tool.name":m.params.name,status:"error"}),Y.meter.createCounter("connection.proxy.streamable.errors").add(1,{"connection.id":G,"tool.name":m.params.name,error:v0.message}),Y0.recordException(v0),Y0.end(),P0}})})}}}async function eG1(X,Y){return tG1(X,Y,{superUser:!1})}async function X71(X,Y){return tG1(X,Y,{superUser:!0})}kb.all("/",async(X)=>{return Cb(X,void 0)});kb.all("/:connectionId",async(X)=>{let Y=X.req.param("connectionId"),Q=X.get("meshContext");try{return await(await Q.createMCPProxy(Y)).fetch(X.req.raw)}catch(J){return Y71(J,X)}});var Y71=(X,Y)=>{if(X.message.includes("not found"))return Y.json({error:X.message},404);if(X.message.includes("does not belong to the active organization"))return Y.json({error:"Connection not found"},404);if(X.message.includes("inactive"))return Y.json({error:X.message},503);return Y.json({error:"Internal server error",message:X.message},500)};kb.all("/:connectionId/call-tool/:toolName",async(X)=>{let Y=X.req.param("connectionId"),Q=X.req.param("toolName"),J=X.get("meshContext");try{let W=await(await J.createMCPProxy(Y)).client.callTool({name:Q,arguments:await X.req.json()});if(W instanceof Response)return W;if(W.isError)return new Response(JSON.stringify(W.content),{headers:{"Content-Type":"application/json"},status:500});return new Response(JSON.stringify(W.structuredContent??W.content),{headers:{"Content-Type":"application/json"}})}catch(G){return Y71(G,X)}});var Q71=kb;cW();class YY0{db;constructor(X){this.db=X}async create(X){let Y=X.id??t8("thrd"),Q=new Date().toISOString();if(!X.organizationId)throw Error("organizationId is required");if(!X.createdBy)throw Error("createdBy is required");if(!X.title)X.title="New Thread - "+Q;let J={id:Y,organization_id:X.organizationId,title:X.title,description:X.description??null,created_at:Q,updated_at:Q,created_by:X.createdBy,updated_by:X.updatedBy??null},G=await this.db.insertInto("threads").values(J).returningAll().executeTakeFirstOrThrow();return this.threadFromDbRow(G)}async get(X){let Y=await this.db.selectFrom("threads").selectAll().where("id","=",X).executeTakeFirst();return Y?this.threadFromDbRow(Y):null}async update(X,Y){let J={updated_at:new Date().toISOString()};if(Y.title!==void 0)J.title=Y.title;if(Y.description!==void 0)J.description=Y.description;if(Y.updatedBy!==void 0)J.updated_by=Y.updatedBy;if(Y.hidden!==void 0)J.hidden=Y.hidden;await this.db.updateTable("threads").set(J).where("id","=",X).execute();let G=await this.get(X);if(!G)throw Error("Thread not found after update");return G}async delete(X){await this.db.deleteFrom("threads").where("id","=",X).execute()}async list(X,Y,Q){let J=this.db.selectFrom("threads").selectAll().where("organization_id","=",X).where("hidden","=",!1).orderBy("updated_at","desc");if(Y)J=J.where("created_by","=",Y);let G=this.db.selectFrom("threads").select(($)=>$.fn.count("id").as("count")).where("organization_id","=",X).where("hidden","=",!1);if(Y)G=G.where("created_by","=",Y);if(Q?.limit)J=J.limit(Q.limit);if(Q?.offset)J=J.offset(Q.offset);let[W,Z]=await Promise.all([J.execute(),G.executeTakeFirst()]);return{threads:W.map(($)=>this.threadFromDbRow($)),total:Number(Z?.count||0)}}async saveMessages(X){let Y=new Date().toISOString(),Q=X[0]?.threadId;if(!Q)throw Error("threadId is required when creating multiple messages");let J=X.find((W)=>W.threadId!==Q);if(J)throw Error(`All messages must target the same thread. Expected threadId "${Q}", but message "${J.id}" has threadId "${J.threadId}"`);let G=X.map((W)=>({id:W.id,thread_id:Q,metadata:W.metadata?JSON.stringify(W.metadata):null,parts:JSON.stringify(W.parts),role:W.role,created_at:W.createdAt??Y,updated_at:Y}));await this.db.transaction().execute(async(W)=>{await W.insertInto("thread_messages").values(G).execute(),await W.updateTable("threads").set({updated_at:Y}).where("id","=",Q).execute()})}async listMessages(X,Y){let Q=this.db.selectFrom("thread_messages").selectAll().where("thread_id","=",X).orderBy("created_at","asc").orderBy("id","asc"),J=this.db.selectFrom("thread_messages").select((Z)=>Z.fn.count("id").as("count")).where("thread_id","=",X);if(Y?.limit)Q=Q.limit(Y.limit);if(Y?.offset)Q=Q.offset(Y.offset);let[G,W]=await Promise.all([Q.execute(),J.executeTakeFirst()]);return{messages:G.map((Z)=>this.messageFromDbRow(Z)),total:Number(W?.count||0)}}threadFromDbRow(X){return{id:X.id,organizationId:X.organization_id,title:X.title,description:X.description,createdAt:typeof X.created_at==="string"?X.created_at:X.created_at.toISOString(),updatedAt:typeof X.updated_at==="string"?X.updated_at:X.updated_at.toISOString(),createdBy:X.created_by,updatedBy:X.updated_by,hidden:X.hidden}}messageFromDbRow(X){let Y,Q;try{Y=X.metadata?JSON.parse(X.metadata):void 0}catch(J){console.error(`Failed to parse metadata for message ${X.id}:`,X.metadata,J),Y=void 0}try{Q=typeof X.parts==="string"?JSON.parse(X.parts):X.parts}catch(J){console.error(`Failed to parse parts for message ${X.id}:`,X.parts,J),Q=[]}return{id:X.id,threadId:X.thread_id,metadata:Y,parts:Q,role:X.role,createdAt:typeof X.created_at==="string"?X.created_at:X.created_at.toISOString(),updatedAt:typeof X.updated_at==="string"?X.updated_at:X.updated_at.toISOString()}}}function Bh6(X){if(!X)return;try{let Y=JSON.parse(X);if(typeof Y!=="object"||Y===null||Array.isArray(Y))return;let Q={};for(let[J,G]of Object.entries(Y))if(typeof G==="string")Q[J]=G;return Object.keys(Q).length>0?Q:void 0}catch{return}}function Dh6(X,Y){for(let[Q,J]of Object.entries(Y)){let G=X[Q];if(!G||G.length===0){let W=X["*"];if(!W||W.length===0)return!1;if(W.includes("*"))continue;for(let Z of J)if(!W.includes(Z))return!1;continue}if(G.includes("*"))continue;for(let W of J)if(!G.includes(W))return!1}return!0}function Nh6(X){let{auth:Y,headers:Q,role:J,permissions:G,userId:W}=X,Z=Y.api.hasPermission;return{hasPermission:async($)=>{if(J&&uX0.includes(J))return!0;if(G)return Dh6(G,$);if(!Z)return console.error("[Auth] hasPermission API not available"),!1;try{if((await Z({headers:Q,body:{permission:$}}))?.success===!0)return!0;let H={};for(let V of Object.keys($))H[V]=["*"];return(await Z({headers:Q,body:{permission:H}}))?.success===!0}catch(K){return console.error("[Auth] Permission check failed:",K),!1}},organization:{create:async($)=>{return Y.api.createOrganization({headers:Q,body:$})},update:async($)=>{return Y.api.updateOrganization({headers:Q,body:$})},delete:async($)=>{await Y.api.deleteOrganization({headers:Q,body:{organizationId:$}})},get:async($)=>{return Y.api.getFullOrganization({headers:Q,query:$?{organizationId:$}:void 0})},list:async($)=>{return Y.api.listOrganizations({headers:Q,query:$?{userId:$}:void 0})},addMember:async($)=>{return Y.api.addMember({headers:Q,body:$})},removeMember:async($)=>{await Y.api.removeMember({headers:Q,body:$})},listMembers:async($)=>{return Y.api.listMembers({headers:Q,query:$?{organizationId:$.organizationId,limit:$.limit,offset:$.offset}:void 0})},updateMemberRole:async($)=>{return Y.api.updateMemberRole({headers:Q,body:$})}},apiKey:{create:async($)=>{return Y.api.createApiKey({body:{...$,userId:W}})},list:async()=>{return Y.api.listApiKeys({headers:Q})},update:async($)=>{return Y.api.updateApiKey({body:{...$,userId:W}})},delete:async($)=>{await Y.api.deleteApiKey({headers:Q,body:{keyId:$}})}}}}async function Oh6(X,Y,Q){if(uX0.includes(Q))return;let J=await X.selectFrom("organizationRole").select(["permission"]).where("organizationId","=",Y).where("role","=",Q).executeTakeFirst();if(!J?.permission)return;try{return JSON.parse(J.permission)}catch{console.error(`[Auth] Failed to parse permissions for role: ${Q}`);return}}async function Lh6(X,Y,Q,J=G71){let G=X.headers.get("Authorization");try{let W=new Headers(X.headers);W.set("X-MCP-Session-Auth","true");let Z=await J.measure("auth_get_mcp_session",()=>Y.api.getMcpSession({headers:W}));if(Z){let $=Z.userId,K=await J.measure("auth_query_membership",()=>Q.selectFrom("member").innerJoin("organization","organization.id","member.organizationId").select(["member.role","member.organizationId","organization.id as orgId","organization.slug as orgSlug","organization.name as orgName"]).where("member.userId","=",$).executeTakeFirst()),H=K?.role,F=K?{id:K.orgId,slug:K.orgSlug,name:K.orgName}:void 0,V;if(K&&H)V=await J.measure("auth_fetch_role_permissions",()=>Oh6(Q,K.organizationId,H));return{user:{id:$,role:H},role:H,permissions:V,organization:F}}}catch(W){console.error("[Auth] OAuth session check failed:",W)}if(G?.startsWith("Bearer ")){let W=G.replace("Bearer ","").trim();try{let Z=await J.measure("auth_verify_mesh_jwt",()=>PG1(W));if(Z){let $,K=Z.metadata?.organizationId;if(Z.sub&&K)$=(await J.measure("auth_query_membership",()=>Q.selectFrom("member").select(["member.role"]).where("member.userId","=",Z.sub).where("member.organizationId","=",K).executeTakeFirst()))?.role;return{user:{id:Z.sub,connectionId:Z.metadata?.connectionId,role:$},role:$,permissions:Z.permissions,organization:Z.metadata?.organizationId?{id:Z.metadata?.organizationId}:void 0}}}catch{}try{let Z=await J.measure("auth_verify_api_key",()=>Y.api.verifyApiKey({body:{key:W}}));if(Z?.valid&&Z.key){let $=Z.key.metadata?.organization,K=Z.key.permissions,H,F=Z.key.userId;if(F&&$?.id)H=(await J.measure("auth_query_membership",()=>Q.selectFrom("member").select(["member.role"]).where("member.userId","=",F).where("member.organizationId","=",$.id).executeTakeFirst()))?.role;return{apiKeyId:Z.key.id,user:{id:Z.key.userId,role:H},role:H,permissions:K,organization:$?{id:$.id,slug:$.slug,name:$.name}:void 0}}}catch(Z){console.error("[Auth] API key check failed:",Z)}}try{let W=await J.measure("auth_get_session",()=>Y.api.getSession({headers:X.headers}));if(W){let Z,$;if(W.session.activeOrganizationId){let K=await J.measure("auth_get_full_organization",()=>Y.api.getFullOrganization({headers:X.headers}).catch(()=>null));if(K)Z={id:K.id,slug:K.slug,name:K.name},$=K.members?.find((F)=>F.userId===W.user.id)?.role;else Z={id:W.session.activeOrganizationId,slug:"",name:""}}return{user:{id:W.user.id,email:W.user.email,role:$},role:$,organization:Z}}}catch(W){let Z=W;console.error("[Auth] Session check failed:",JSON.stringify({message:Z.message,body:Z.body,stack:Z.stack},null,2))}return{user:void 0}}var J71,zK={set:(X)=>{J71=X},create:async(X,Y)=>{return await J71(X,Y)}},G71={measure:async(X,Y)=>{return await Y()}},wh6=["x-hub-signature-256"];function W71(X){let Y=new zP(X.encryption.key),Q={connections:new BP(X.db,Y),organizationSettings:new pX0(X.db),monitoring:new dX0(X.db,X.databaseType),virtualMcps:new mX0(X.db),users:new cX0(X.db),threads:new YY0(X.db)};return async(J,G)=>{let W=G?.timings??G71,Z=J?.headers.get("x-caller-id")??void 0,$=J?await Lh6(J,X.auth,X.db,W):{user:void 0},K=Nh6({auth:X.auth,headers:J?.headers??new Headers,role:$.role,permissions:$.permissions,userId:$.user?.id}),H={user:$.user};if($.apiKeyId)H.apiKey={id:$.apiKeyId,name:"",userId:""};let F=$.organization,V=J?new URL(J.url):new URL("http://localhost:3000"),q=process.env.BASE_URL??`${V.protocol}//${V.host}`,z=new UK(X.auth,H.user?.id,void 0,K,$.role,"self"),D={timings:W,auth:H,connectionId:Z,organization:F,storage:Q,vault:Y,authInstance:X.auth,boundAuth:K,access:z,db:X.db,tracer:X.observability.tracer,meter:X.observability.meter,baseUrl:q,metadata:{requestId:crypto.randomUUID(),timestamp:new Date,wellKnownForwardableHeaders:Object.fromEntries(wh6.map((N)=>[N,J?.headers.get(N)??null]).filter(([N,L])=>L!==null)),userAgent:J?.headers.get("x-mesh-client")||J?.headers.get("User-Agent")||void 0,ipAddress:(J?.headers.get("CF-Connecting-IP")||J?.headers.get("X-Forwarded-For"))??void 0,properties:Bh6(J?.headers.get("x-mesh-properties"))},eventBus:X.eventBus,createMCPProxy:async(N)=>{return await eG1(N,D)}};return D}}class Z71{db;constructor(X){this.db=X}async publishEvent(X){let Y=new Date().toISOString();return await this.db.insertInto("events").values({id:X.id,organization_id:X.organizationId,type:X.type,source:X.source,specversion:"1.0",subject:X.subject??null,time:X.time,datacontenttype:X.datacontenttype??"application/json",dataschema:X.dataschema??null,data:X.data?JSON.stringify(X.data):null,cron:X.cron??null,status:"pending",attempts:0,last_error:null,next_retry_at:null,created_at:Y,updated_at:Y}).execute(),{id:X.id,organizationId:X.organizationId,type:X.type,source:X.source,specversion:"1.0",subject:X.subject??null,time:X.time,datacontenttype:X.datacontenttype??"application/json",dataschema:X.dataschema??null,data:X.data??null,cron:X.cron??null,status:"pending",attempts:0,lastError:null,nextRetryAt:null,createdAt:Y,updatedAt:Y}}async subscribe(X){let Y=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",X.organizationId).where("connection_id","=",X.connectionId).where("event_type","=",X.eventType);if(X.publisher)Y=Y.where("publisher","=",X.publisher);else Y=Y.where("publisher","is",null);if(X.filter)Y=Y.where("filter","=",X.filter);else Y=Y.where("filter","is",null);let Q=await Y.executeTakeFirst();if(Q)return{id:Q.id,organizationId:Q.organization_id,connectionId:Q.connection_id,publisher:Q.publisher,eventType:Q.event_type,filter:Q.filter,enabled:Q.enabled===1,createdAt:Q.created_at,updatedAt:Q.updated_at};let J=new Date().toISOString();return await this.db.insertInto("event_subscriptions").values({id:X.id,organization_id:X.organizationId,connection_id:X.connectionId,publisher:X.publisher??null,event_type:X.eventType,filter:X.filter??null,enabled:1,created_at:J,updated_at:J}).execute(),{id:X.id,organizationId:X.organizationId,connectionId:X.connectionId,publisher:X.publisher??null,eventType:X.eventType,filter:X.filter??null,enabled:!0,createdAt:J,updatedAt:J}}async unsubscribe(X,Y){return{success:((await this.db.deleteFrom("event_subscriptions").where("id","=",X).where("organization_id","=",Y).executeTakeFirst()).numDeletedRows??0n)>0n}}async listSubscriptions(X,Y){let Q=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",X);if(Y)Q=Q.where("connection_id","=",Y);return(await Q.execute()).map((G)=>({id:G.id,organizationId:G.organization_id,connectionId:G.connection_id,publisher:G.publisher,eventType:G.event_type,filter:G.filter,enabled:G.enabled===1,createdAt:G.created_at,updatedAt:G.updated_at}))}async getSubscription(X,Y){let Q=await this.db.selectFrom("event_subscriptions").selectAll().where("id","=",X).where("organization_id","=",Y).executeTakeFirst();if(!Q)return null;return{id:Q.id,organizationId:Q.organization_id,connectionId:Q.connection_id,publisher:Q.publisher,eventType:Q.event_type,filter:Q.filter,enabled:Q.enabled===1,createdAt:Q.created_at,updatedAt:Q.updated_at}}async getMatchingSubscriptions(X){return(await this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",X.organizationId).where("enabled","=",1).where("event_type","=",X.type).where((Q)=>Q.or([Q("publisher","is",null),Q("publisher","=",X.source)])).execute()).map((Q)=>({id:Q.id,organizationId:Q.organization_id,connectionId:Q.connection_id,publisher:Q.publisher,eventType:Q.event_type,filter:Q.filter,enabled:Q.enabled===1,createdAt:Q.created_at,updatedAt:Q.updated_at}))}async createDeliveries(X,Y,Q){if(Y.length===0)return;let J=new Date().toISOString(),G=Q??null,W=Y.map((Z)=>({id:crypto.randomUUID(),event_id:X,subscription_id:Z,status:"pending",attempts:0,last_error:null,delivered_at:null,next_retry_at:G,created_at:J}));await this.db.insertInto("event_deliveries").values(W).execute()}async claimPendingDeliveries(X){let Y=new Date().toISOString(),Q;try{Q=(await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",(W)=>W.selectFrom("event_deliveries as d").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select("d.id").where("d.status","=","pending").where("s.enabled","=",1).where((Z)=>Z.or([Z("d.next_retry_at","is",null),Z("d.next_retry_at","<=",Y)])).orderBy("d.created_at","asc").limit(X)).where("status","=","pending").returning(["id"]).execute()).map((W)=>W.id)}catch{let G=await this.db.selectFrom("event_deliveries as d").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select(["d.id"]).where("d.status","=","pending").where("s.enabled","=",1).where((W)=>W.or([W("d.next_retry_at","is",null),W("d.next_retry_at","<=",Y)])).orderBy("d.created_at","asc").limit(X).execute();if(G.length===0)return[];Q=G.map((W)=>W.id),await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",Q).where("status","=","pending").execute()}if(Q.length===0)return[];return(await this.db.selectFrom("event_deliveries as d").innerJoin("events as e","e.id","d.event_id").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select(["d.id as delivery_id","d.event_id","d.subscription_id","d.status as delivery_status","d.attempts as delivery_attempts","d.last_error as delivery_last_error","d.delivered_at","d.next_retry_at as delivery_next_retry_at","d.created_at as delivery_created_at","e.organization_id","e.type","e.source","e.specversion","e.subject","e.time","e.datacontenttype","e.dataschema","e.data","e.cron","e.status as event_status","e.attempts as event_attempts","e.last_error as event_last_error","e.next_retry_at","e.created_at as event_created_at","e.updated_at as event_updated_at","s.connection_id","s.publisher","s.event_type","s.filter","s.enabled","s.created_at as subscription_created_at","s.updated_at as subscription_updated_at"]).where("d.id","in",Q).where("d.status","=","processing").execute()).map((G)=>({delivery:{id:G.delivery_id,eventId:G.event_id,subscriptionId:G.subscription_id,status:G.delivery_status,attempts:G.delivery_attempts,lastError:G.delivery_last_error,deliveredAt:G.delivered_at,nextRetryAt:G.delivery_next_retry_at,createdAt:G.delivery_created_at},event:{id:G.event_id,organizationId:G.organization_id,type:G.type,source:G.source,specversion:G.specversion,subject:G.subject,time:G.time,datacontenttype:G.datacontenttype,dataschema:G.dataschema,data:G.data?JSON.parse(G.data):null,cron:G.cron,status:G.event_status,attempts:G.event_attempts,lastError:G.event_last_error,nextRetryAt:G.next_retry_at,createdAt:G.event_created_at,updatedAt:G.event_updated_at},subscription:{id:G.subscription_id,organizationId:G.organization_id,connectionId:G.connection_id,publisher:G.publisher,eventType:G.event_type,filter:G.filter,enabled:G.enabled===1,createdAt:G.subscription_created_at,updatedAt:G.subscription_updated_at}}))}async markDeliveriesDelivered(X){if(X.length===0)return;let Y=new Date().toISOString();await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:Y}).where("id","in",X).execute()}async markDeliveriesFailed(X,Y,Q=20,J=1000,G=3600000){if(X.length===0)return;for(let W of X){let Z=await this.db.selectFrom("event_deliveries").select(["attempts"]).where("id","=",W).executeTakeFirst();if(!Z)continue;let $=Z.attempts+1;if($>=Q)await this.db.updateTable("event_deliveries").set({attempts:$,last_error:Y,status:"failed",next_retry_at:null}).where("id","=",W).execute();else{let K=Math.min(J*Math.pow(2,$-1),G),H=new Date(Date.now()+K).toISOString();await this.db.updateTable("event_deliveries").set({attempts:$,last_error:Y,status:"pending",next_retry_at:H}).where("id","=",W).execute()}}}async updateEventStatus(X){let Y=await this.db.selectFrom("event_deliveries").select(["status"]).where("event_id","=",X).execute();if(Y.length===0)return;let Q=Y.every((W)=>W.status==="delivered"),J=Y.some((W)=>W.status==="failed"),G=Y.some((W)=>W.status==="pending"||W.status==="processing");if(Q)await this.db.updateTable("events").set({status:"delivered",updated_at:new Date().toISOString()}).where("id","=",X).execute();else if(J&&!G)await this.db.updateTable("events").set({status:"failed",updated_at:new Date().toISOString()}).where("id","=",X).execute()}async resetStuckDeliveries(){let X=await this.db.updateTable("event_deliveries").set({status:"pending"}).where("status","=","processing").executeTakeFirst();return Number(X.numUpdatedRows??0)}async getEvent(X,Y){let Q=await this.db.selectFrom("events").selectAll().where("id","=",X).where("organization_id","=",Y).executeTakeFirst();if(!Q)return null;return{id:Q.id,organizationId:Q.organization_id,type:Q.type,source:Q.source,specversion:Q.specversion,subject:Q.subject,time:Q.time,datacontenttype:Q.datacontenttype,dataschema:Q.dataschema,data:Q.data?JSON.parse(Q.data):null,cron:Q.cron,status:Q.status,attempts:Q.attempts,lastError:Q.last_error,nextRetryAt:Q.next_retry_at,createdAt:Q.created_at,updatedAt:Q.updated_at}}async findActiveCronEvent(X,Y,Q,J){let G=await this.db.selectFrom("events").selectAll().where("organization_id","=",X).where("type","=",Y).where("source","=",Q).where("cron","=",J).where("status","in",["pending","processing","delivered"]).orderBy("created_at","desc").executeTakeFirst();if(!G)return null;return{id:G.id,organizationId:G.organization_id,type:G.type,source:G.source,specversion:G.specversion,subject:G.subject,time:G.time,datacontenttype:G.datacontenttype,dataschema:G.dataschema,data:G.data?JSON.parse(G.data):null,cron:G.cron,status:G.status,attempts:G.attempts,lastError:G.last_error,nextRetryAt:G.next_retry_at,createdAt:G.created_at,updatedAt:G.updated_at}}async cancelEvent(X,Y,Q){let J=await this.db.updateTable("events").set({status:"failed",last_error:"Cancelled by publisher",updated_at:new Date().toISOString()}).where("id","=",X).where("organization_id","=",Y).where("source","=",Q).where("status","in",["pending","processing"]).executeTakeFirst();if((J.numUpdatedRows??0n)>0n)await this.db.updateTable("event_deliveries").set({status:"failed",last_error:"Event cancelled by publisher"}).where("event_id","=",X).where("status","in",["pending","processing"]).execute();return{success:(J.numUpdatedRows??0n)>0n}}async scheduleRetryWithoutAttemptIncrement(X,Y){if(X.length===0)return;let Q=new Date(Date.now()+Y).toISOString();await this.db.updateTable("event_deliveries").set({status:"pending",next_retry_at:Q}).where("id","in",X).execute()}async ackDelivery(X,Y,Q){if(!await this.db.selectFrom("events").select(["id"]).where("id","=",X).where("organization_id","=",Y).executeTakeFirst())return{success:!1};let W=((await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:new Date().toISOString()}).where("event_id","=",X).where("status","in",["pending","processing"]).where((Z)=>Z.exists(Z.selectFrom("event_subscriptions").select("id").whereRef("event_subscriptions.id","=","event_deliveries.subscription_id").where("event_subscriptions.connection_id","=",Q).where("event_subscriptions.organization_id","=",Y))).executeTakeFirst()).numUpdatedRows??0n)>0n;if(W)await this.updateEventStatus(X);return{success:W}}async syncSubscriptions(X){let{organizationId:Y,connectionId:Q,subscriptions:J}=X,G=(w,C)=>{return`${w}::${C??""}`},W=await this.listSubscriptions(Y,Q),Z=new Map;for(let w of W)Z.set(G(w.eventType,w.publisher),w);let $=new Map;for(let w of J)$.set(G(w.eventType,w.publisher),w);let K=new Date().toISOString(),H=[],F=[],V=[],q=0;for(let[w,C]of $){let T=Z.get(w);if(!T)H.push({id:crypto.randomUUID(),organization_id:Y,connection_id:Q,event_type:C.eventType,publisher:C.publisher??null,filter:C.filter??null,enabled:1,created_at:K,updated_at:K});else{let A=T.filter??null,P=C.filter??null;if(A!==P)F.push({id:T.id,filter:P});else q++}}for(let[w,C]of Z)if(!$.has(w))V.push(C.id);if(H.length>0)await this.db.insertInto("event_subscriptions").values(H).execute();if(F.length>0)await Promise.all(F.map((w)=>this.db.updateTable("event_subscriptions").set({filter:w.filter,updated_at:K}).where("id","=",w.id).execute()));if(V.length>0)await this.db.deleteFrom("event_subscriptions").where("id","in",V).execute();let z=H.length,D=F.length,N=V.length,L=await this.listSubscriptions(Y,Q);return{created:z,updated:D,deleted:N,unchanged:q,subscriptions:L}}}function $71(X){return new Z71(X)}function pY(X,Y,Q,J,G,W,Z,$){return pY.fromTZ(pY.tp(X,Y,Q,J,G,W,Z),$)}pY.fromTZISO=(X,Y,Q)=>pY.fromTZ(Mh6(X,Y),Q);pY.fromTZ=function(X,Y){let Q=new Date(Date.UTC(X.y,X.m-1,X.d,X.h,X.i,X.s)),J=QY0(X.tz,Q),G=new Date(Q.getTime()-J),W=QY0(X.tz,G);if(W-J===0)return G;{let Z=new Date(Q.getTime()-W),$=QY0(X.tz,Z);if($-W===0)return Z;if(!Y&&$-W>0)return Z;if(Y)throw Error("Invalid date passed to fromTZ()");return G}};pY.toTZ=function(X,Y){let Q=X.toLocaleString("en-US",{timeZone:Y}).replace(/[\u202f]/," "),J=new Date(Q);return{y:J.getFullYear(),m:J.getMonth()+1,d:J.getDate(),h:J.getHours(),i:J.getMinutes(),s:J.getSeconds(),tz:Y}};pY.tp=(X,Y,Q,J,G,W,Z)=>({y:X,m:Y,d:Q,h:J,i:G,s:W,tz:Z});function QY0(X,Y=new Date){let Q=Y.toLocaleString("en-US",{timeZone:X,timeZoneName:"shortOffset"}).split(" ").slice(-1)[0],J=Y.toLocaleString("en-US").replace(/[\u202f]/," ");return Date.parse(`${J} GMT`)-Date.parse(`${J} ${Q}`)}function Mh6(X,Y){let Q=new Date(Date.parse(X));if(isNaN(Q))throw Error("minitz: Invalid ISO8601 passed to parser.");let J=X.substring(9);return X.includes("Z")||J.includes("-")||J.includes("+")?pY.tp(Q.getUTCFullYear(),Q.getUTCMonth()+1,Q.getUTCDate(),Q.getUTCHours(),Q.getUTCMinutes(),Q.getUTCSeconds(),"Etc/UTC"):pY.tp(Q.getFullYear(),Q.getMonth()+1,Q.getDate(),Q.getHours(),Q.getMinutes(),Q.getSeconds(),Y)}pY.minitz=pY;var JY0=32,sP=31|JY0,V71=[1,2,4,8,16],K71=class{pattern;timezone;second;minute;hour;day;month;dayOfWeek;lastDayOfMonth;starDOM;starDOW;constructor(X,Y){this.pattern=X,this.timezone=Y,this.second=Array(60).fill(0),this.minute=Array(60).fill(0),this.hour=Array(24).fill(0),this.day=Array(31).fill(0),this.month=Array(12).fill(0),this.dayOfWeek=Array(7).fill(0),this.lastDayOfMonth=!1,this.starDOM=!1,this.starDOW=!1,this.parse()}parse(){if(!(typeof this.pattern=="string"||this.pattern instanceof String))throw TypeError("CronPattern: Pattern has to be of type string.");this.pattern.indexOf("@")>=0&&(this.pattern=this.handleNicknames(this.pattern).trim());let X=this.pattern.replace(/\s+/g," ").split(" ");if(X.length<5||X.length>6)throw TypeError("CronPattern: invalid configuration format ('"+this.pattern+"'), exactly five or six space separated parts are required.");if(X.length===5&&X.unshift("0"),X[3].indexOf("L")>=0&&(X[3]=X[3].replace("L",""),this.lastDayOfMonth=!0),X[3]=="*"&&(this.starDOM=!0),X[4].length>=3&&(X[4]=this.replaceAlphaMonths(X[4])),X[5].length>=3&&(X[5]=this.replaceAlphaDays(X[5])),X[5]=="*"&&(this.starDOW=!0),this.pattern.indexOf("?")>=0){let Y=new pJ(new Date,this.timezone).getDate(!0);X[0]=X[0].replace("?",Y.getSeconds().toString()),X[1]=X[1].replace("?",Y.getMinutes().toString()),X[2]=X[2].replace("?",Y.getHours().toString()),this.starDOM||(X[3]=X[3].replace("?",Y.getDate().toString())),X[4]=X[4].replace("?",(Y.getMonth()+1).toString()),this.starDOW||(X[5]=X[5].replace("?",Y.getDay().toString()))}this.throwAtIllegalCharacters(X),this.partToArray("second",X[0],0,1),this.partToArray("minute",X[1],0,1),this.partToArray("hour",X[2],0,1),this.partToArray("day",X[3],-1,1),this.partToArray("month",X[4],-1,1),this.partToArray("dayOfWeek",X[5],0,sP),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(X,Y,Q,J){let G=this[X],W=X==="day"&&this.lastDayOfMonth;if(Y===""&&!W)throw TypeError("CronPattern: configuration entry "+X+" ("+Y+") is empty, check for trailing spaces.");if(Y==="*")return G.fill(J);let Z=Y.split(",");if(Z.length>1)for(let $=0;$<Z.length;$++)this.partToArray(X,Z[$],Q,J);else Y.indexOf("-")!==-1&&Y.indexOf("/")!==-1?this.handleRangeWithStepping(Y,X,Q,J):Y.indexOf("-")!==-1?this.handleRange(Y,X,Q,J):Y.indexOf("/")!==-1?this.handleStepping(Y,X,Q,J):Y!==""&&this.handleNumber(Y,X,Q,J)}throwAtIllegalCharacters(X){for(let Y=0;Y<X.length;Y++)if((Y===5?/[^/*0-9,\-#L]+/:/[^/*0-9,-]+/).test(X[Y]))throw TypeError("CronPattern: configuration entry "+Y+" ("+X[Y]+") contains illegal characters.")}handleNumber(X,Y,Q,J){let G=this.extractNth(X,Y),W=parseInt(G[0],10)+Q;if(isNaN(W))throw TypeError("CronPattern: "+Y+" is not a number: '"+X+"'");this.setPart(Y,W,G[1]||J)}setPart(X,Y,Q){if(!Object.prototype.hasOwnProperty.call(this,X))throw TypeError("CronPattern: Invalid part specified: "+X);if(X==="dayOfWeek"){if(Y===7&&(Y=0),Y<0||Y>6)throw RangeError("CronPattern: Invalid value for dayOfWeek: "+Y);this.setNthWeekdayOfMonth(Y,Q);return}if(X==="second"||X==="minute"){if(Y<0||Y>=60)throw RangeError("CronPattern: Invalid value for "+X+": "+Y)}else if(X==="hour"){if(Y<0||Y>=24)throw RangeError("CronPattern: Invalid value for "+X+": "+Y)}else if(X==="day"){if(Y<0||Y>=31)throw RangeError("CronPattern: Invalid value for "+X+": "+Y)}else if(X==="month"&&(Y<0||Y>=12))throw RangeError("CronPattern: Invalid value for "+X+": "+Y);this[X][Y]=Q}handleRangeWithStepping(X,Y,Q,J){let G=this.extractNth(X,Y),W=G[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(W===null)throw TypeError("CronPattern: Syntax error, illegal range with stepping: '"+X+"'");let[,Z,$,K]=W,H=parseInt(Z,10)+Q,F=parseInt($,10)+Q,V=parseInt(K,10);if(isNaN(H))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(F))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN(V))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(V===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(V>this[Y].length)throw TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[Y].length+")");if(H>F)throw TypeError("CronPattern: From value is larger than to value: '"+X+"'");for(let q=H;q<=F;q+=V)this.setPart(Y,q,G[1]||J)}extractNth(X,Y){let Q=X,J;if(Q.includes("#")){if(Y!=="dayOfWeek")throw Error("CronPattern: nth (#) only allowed in day-of-week field");J=Q.split("#")[1],Q=Q.split("#")[0]}return[Q,J]}handleRange(X,Y,Q,J){let G=this.extractNth(X,Y),W=G[0].split("-");if(W.length!==2)throw TypeError("CronPattern: Syntax error, illegal range: '"+X+"'");let Z=parseInt(W[0],10)+Q,$=parseInt(W[1],10)+Q;if(isNaN(Z))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN($))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(Z>$)throw TypeError("CronPattern: From value is larger than to value: '"+X+"'");for(let K=Z;K<=$;K++)this.setPart(Y,K,G[1]||J)}handleStepping(X,Y,Q,J){let G=this.extractNth(X,Y),W=G[0].split("/");if(W.length!==2)throw TypeError("CronPattern: Syntax error, illegal stepping: '"+X+"'");W[0]===""&&(W[0]="*");let Z=0;W[0]!=="*"&&(Z=parseInt(W[0],10)+Q);let $=parseInt(W[1],10);if(isNaN($))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if($===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if($>this[Y].length)throw TypeError("CronPattern: Syntax error, max steps for part is ("+this[Y].length+")");for(let K=Z;K<this[Y].length;K+=$)this.setPart(Y,K,G[1]||J)}replaceAlphaDays(X){return X.replace(/-sun/gi,"-7").replace(/sun/gi,"0").replace(/mon/gi,"1").replace(/tue/gi,"2").replace(/wed/gi,"3").replace(/thu/gi,"4").replace(/fri/gi,"5").replace(/sat/gi,"6")}replaceAlphaMonths(X){return X.replace(/jan/gi,"1").replace(/feb/gi,"2").replace(/mar/gi,"3").replace(/apr/gi,"4").replace(/may/gi,"5").replace(/jun/gi,"6").replace(/jul/gi,"7").replace(/aug/gi,"8").replace(/sep/gi,"9").replace(/oct/gi,"10").replace(/nov/gi,"11").replace(/dec/gi,"12")}handleNicknames(X){let Y=X.trim().toLowerCase();return Y==="@yearly"||Y==="@annually"?"0 0 1 1 *":Y==="@monthly"?"0 0 1 * *":Y==="@weekly"?"0 0 * * 0":Y==="@daily"?"0 0 * * *":Y==="@hourly"?"0 * * * *":X}setNthWeekdayOfMonth(X,Y){if(typeof Y!="number"&&Y==="L")this.dayOfWeek[X]=this.dayOfWeek[X]|JY0;else if(Y===sP)this.dayOfWeek[X]=sP;else if(Y<6&&Y>0)this.dayOfWeek[X]=this.dayOfWeek[X]|V71[Y-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${Y}, Type: ${typeof Y}`)}},H71=[31,28,31,30,31,30,31,31,30,31,30,31],tW=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]],pJ=class X{tz;ms;second;minute;hour;day;month;year;constructor(Y,Q){if(this.tz=Q,Y&&Y instanceof Date)if(!isNaN(Y))this.fromDate(Y);else throw TypeError("CronDate: Invalid date passed to CronDate constructor");else if(Y===void 0)this.fromDate(new Date);else if(Y&&typeof Y=="string")this.fromString(Y);else if(Y instanceof X)this.fromCronDate(Y);else throw TypeError("CronDate: Invalid type ("+typeof Y+") passed to CronDate constructor")}isNthWeekdayOfMonth(Y,Q,J,G){let W=new Date(Date.UTC(Y,Q,J)).getUTCDay(),Z=0;for(let $=1;$<=J;$++)new Date(Date.UTC(Y,Q,$)).getUTCDay()===W&&Z++;if(G&sP&&V71[Z-1]&G)return!0;if(G&JY0){let $=new Date(Date.UTC(Y,Q+1,0)).getUTCDate();for(let K=J+1;K<=$;K++)if(new Date(Date.UTC(Y,Q,K)).getUTCDay()===W)return!1;return!0}return!1}fromDate(Y){if(this.tz!==void 0)if(typeof this.tz=="number")this.ms=Y.getUTCMilliseconds(),this.second=Y.getUTCSeconds(),this.minute=Y.getUTCMinutes()+this.tz,this.hour=Y.getUTCHours(),this.day=Y.getUTCDate(),this.month=Y.getUTCMonth(),this.year=Y.getUTCFullYear(),this.apply();else{let Q=pY.toTZ(Y,this.tz);this.ms=Y.getMilliseconds(),this.second=Q.s,this.minute=Q.i,this.hour=Q.h,this.day=Q.d,this.month=Q.m-1,this.year=Q.y}else this.ms=Y.getMilliseconds(),this.second=Y.getSeconds(),this.minute=Y.getMinutes(),this.hour=Y.getHours(),this.day=Y.getDate(),this.month=Y.getMonth(),this.year=Y.getFullYear()}fromCronDate(Y){this.tz=Y.tz,this.year=Y.year,this.month=Y.month,this.day=Y.day,this.hour=Y.hour,this.minute=Y.minute,this.second=Y.second,this.ms=Y.ms}apply(){if(this.month>11||this.day>H71[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let Y=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=Y.getUTCMilliseconds(),this.second=Y.getUTCSeconds(),this.minute=Y.getUTCMinutes(),this.hour=Y.getUTCHours(),this.day=Y.getUTCDate(),this.month=Y.getUTCMonth(),this.year=Y.getUTCFullYear(),!0}else return!1}fromString(Y){if(typeof this.tz=="number"){let Q=pY.fromTZISO(Y);this.ms=Q.getUTCMilliseconds(),this.second=Q.getUTCSeconds(),this.minute=Q.getUTCMinutes(),this.hour=Q.getUTCHours(),this.day=Q.getUTCDate(),this.month=Q.getUTCMonth(),this.year=Q.getUTCFullYear(),this.apply()}else return this.fromDate(pY.fromTZISO(Y,this.tz))}findNext(Y,Q,J,G){let W=this[Q],Z;J.lastDayOfMonth&&(this.month!==1?Z=H71[this.month]:Z=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate());let $=!J.starDOW&&Q=="day"?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let K=this[Q]+G;K<J[Q].length;K++){let H=J[Q][K];if(Q==="day"&&J.lastDayOfMonth&&K-G==Z&&(H=1),Q==="day"&&!J.starDOW){let F=J.dayOfWeek[($+(K-G-1))%7];if(F&&F&sP)F=this.isNthWeekdayOfMonth(this.year,this.month,K-G,F)?1:0;else if(F)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${F}`);Y.legacyMode&&!J.starDOM?H=H||F:H=H&&F}if(H)return this[Q]=K-G,W!==this[Q]?2:1}return 3}recurse(Y,Q,J){let G=this.findNext(Q,tW[J][0],Y,tW[J][2]);if(G>1){let W=J+1;for(;W<tW.length;)this[tW[W][0]]=-tW[W][2],W++;if(G===3)return this[tW[J][1]]++,this[tW[J][0]]=-tW[J][2],this.apply(),this.recurse(Y,Q,0);if(this.apply())return this.recurse(Y,Q,J-1)}return J+=1,J>=tW.length?this:this.year>=3000?null:this.recurse(Y,Q,J)}increment(Y,Q,J){return this.second+=Q.interval!==void 0&&Q.interval>1&&J?Q.interval:1,this.ms=0,this.apply(),this.recurse(Y,Q,0)}getDate(Y){return Y||this.tz===void 0?new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms):typeof this.tz=="number"?new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms)):pY.fromTZ(pY.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function Ph6(X){if(X===void 0&&(X={}),delete X.name,X.legacyMode=X.legacyMode===void 0?!0:X.legacyMode,X.paused=X.paused===void 0?!1:X.paused,X.maxRuns=X.maxRuns===void 0?1/0:X.maxRuns,X.catch=X.catch===void 0?!1:X.catch,X.interval=X.interval===void 0?0:parseInt(X.interval.toString(),10),X.utcOffset=X.utcOffset===void 0?void 0:parseInt(X.utcOffset.toString(),10),X.unref=X.unref===void 0?!1:X.unref,X.startAt&&(X.startAt=new pJ(X.startAt,X.timezone)),X.stopAt&&(X.stopAt=new pJ(X.stopAt,X.timezone)),X.interval!==null){if(isNaN(X.interval))throw Error("CronOptions: Supplied value for interval is not a number");if(X.interval<0)throw Error("CronOptions: Supplied value for interval can not be negative")}if(X.utcOffset!==void 0){if(isNaN(X.utcOffset))throw Error("CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.");if(X.utcOffset<-870||X.utcOffset>870)throw Error("CronOptions: utcOffset out of bounds.");if(X.utcOffset!==void 0&&X.timezone)throw Error("CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.")}if(X.unref!==!0&&X.unref!==!1)throw Error("CronOptions: Unref should be either true, false or undefined(false).");return X}function oP(X){return Object.prototype.toString.call(X)==="[object Function]"||typeof X=="function"||X instanceof Function}function Ah6(X){return oP(X)}function Th6(X){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer(X):X&&typeof X.unref<"u"&&X.unref()}var F71=30000,vb=[],_b=class{name;options;_states;fn;constructor(X,Y,Q){let J,G;if(oP(Y))G=Y;else if(typeof Y=="object")J=Y;else if(Y!==void 0)throw Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");if(oP(Q))G=Q;else if(typeof Q=="object")J=Q;else if(Q!==void 0)throw Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");if(this.name=J?.name,this.options=Ph6(J),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:J?J.maxRuns:void 0,paused:J?J.paused:!1,pattern:new K71("* * * * *")},X&&(X instanceof Date||typeof X=="string"&&X.indexOf(":")>0)?this._states.once=new pJ(X,this.options.timezone||this.options.utcOffset):this._states.pattern=new K71(X,this.options.timezone),this.name){if(vb.find((W)=>W.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");vb.push(this)}return G!==void 0&&Ah6(G)&&(this.fn=G,this.schedule()),this}nextRun(X){let Y=this._next(X);return Y?Y.getDate(!1):null}nextRuns(X,Y){this._states.maxRuns!==void 0&&X>this._states.maxRuns&&(X=this._states.maxRuns);let Q=[],J=Y||this._states.currentRun||void 0;for(;X--&&(J=this.nextRun(J));)Q.push(J);return Q}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let X=this.nextRun(this._states.currentRun),Y=!this._states.paused,Q=this.fn!==void 0,J=!this._states.kill;return Y&&Q&&J&&X!==null}isStopped(){return this._states.kill}isBusy(){return this._states.blocking}currentRun(){return this._states.currentRun?this._states.currentRun.getDate():null}previousRun(){return this._states.previousRun?this._states.previousRun.getDate():null}msToNext(X){let Y=this._next(X);return Y?X instanceof pJ||X instanceof Date?Y.getTime()-X.getTime():Y.getTime()-new pJ(X).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let X=vb.indexOf(this);X>=0&&vb.splice(X,1)}pause(){return this._states.paused=!0,!this._states.kill}resume(){return this._states.paused=!1,!this._states.kill}schedule(X){if(X&&this.fn)throw Error("Cron: It is not allowed to schedule two functions using the same Croner instance.");X&&(this.fn=X);let Y=this.msToNext(),Q=this.nextRun(this._states.currentRun);return Y==null||isNaN(Y)||Q===null?this:(Y>F71&&(Y=F71),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(Q),Y),this._states.currentTimeout&&this.options.unref&&Th6(this._states.currentTimeout),this)}async _trigger(X){if(this._states.blocking=!0,this._states.currentRun=new pJ(void 0,this.options.timezone||this.options.utcOffset),this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(Y){oP(this.options.catch)&&this.options.catch(Y,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new pJ(X,this.options.timezone||this.options.utcOffset),this._states.blocking=!1}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger(X){let Y=new Date,Q=!this._states.paused&&Y.getTime()>=X.getTime(),J=this._states.blocking&&this.options.protect;Q&&!J?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):Q&&J&&oP(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next(X){let Y=!!(X||this._states.currentRun),Q=!1;!X&&this.options.startAt&&this.options.interval&&([X,Y]=this._calculatePreviousRun(X,Y),Q=!X),X=new pJ(X,this.options.timezone||this.options.utcOffset),this.options.startAt&&X&&X.getTime()<this.options.startAt.getTime()&&(X=this.options.startAt);let J=this._states.once||new pJ(X,this.options.timezone||this.options.utcOffset);return!Q&&J!==this._states.once&&(J=J.increment(this._states.pattern,this.options,Y)),this._states.once&&this._states.once.getTime()<=X.getTime()||J===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&J.getTime()>=this.options.stopAt.getTime()?null:J}_calculatePreviousRun(X,Y){let Q=new pJ(void 0,this.options.timezone||this.options.utcOffset),J=X;if(this.options.startAt.getTime()<=Q.getTime()){J=this.options.startAt;let G=J.getTime()+this.options.interval*1000;for(;G<=Q.getTime();)J=new pJ(J,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),G=J.getTime()+this.options.interval*1000;Y=!0}return J===null&&(J=void 0),[J,Y]}};var yb={pollIntervalMs:5000,batchSize:100,maxAttempts:20,retryDelayMs:1000,maxDelayMs:3600000};Ob();function q71(){return async(X,Y)=>{try{let Q=await zK.create(),J=await X71(X,{...Q,auth:{...Q.auth,user:{id:"notify-worker"}}}),W=await i80.forClient(J).ON_EVENTS({events:Y});return{success:W.success,error:W.error,retryAfter:W.retryAfter,results:W.results}}catch(Q){let J=Q instanceof Error?Q.message:String(Q);return console.error(`[EventBus] Failed to notify connection ${X}:`,J),{success:!1,error:J}}}}function U71(X){return{specversion:"1.0",id:X.id,source:X.source,type:X.type,time:X.time,subject:X.subject??void 0,datacontenttype:X.datacontenttype,dataschema:X.dataschema??void 0,data:X.data??void 0}}function Eh6(X){let Y=new Map;for(let J of X){let G=J.subscription.connectionId,W=Y.get(G);if(W){if(W.deliveryIds.push(J.delivery.id),!W.seenEventIds.has(J.event.id))W.seenEventIds.add(J.event.id),W.events.push(U71(J.event))}else Y.set(G,{connectionId:J.subscription.connectionId,deliveryIds:[J.delivery.id],events:[U71(J.event)],seenEventIds:new Set([J.event.id])})}let Q=new Map;for(let[J,G]of Y)Q.set(J,{connectionId:G.connectionId,deliveryIds:G.deliveryIds,events:G.events});return Q}class GY0{storage;notifySubscriber;running=!1;processing=!1;config;constructor(X,Y){this.storage=X;this.notifySubscriber=q71(),this.config={...yb,...Y}}async start(){if(this.running)return;let X=await this.storage.resetStuckDeliveries();if(X>0)console.log(`[EventBus] Reset ${X} stuck deliveries from previous shutdown`);this.running=!0}stop(){this.running=!1,console.log("[EventBus] Worker stopped")}isRunning(){return this.running}async processNow(){if(!this.running)return;if(this.processing)return;this.processing=!0;try{await this.processEvents()}catch(X){console.error("[EventBus] Error processing events:",X)}finally{this.processing=!1}}async processEvents(){let X=await this.storage.claimPendingDeliveries(this.config.batchSize);if(X.length===0)return;let Y=Eh6(X),Q=new Set;for(let[J,G]of Y){try{let W=await this.notifySubscriber(G.connectionId,G.events);if(W.results&&Object.keys(W.results).length>0)await this.processPerEventResults(G,W);else if(W.success)await this.storage.markDeliveriesDelivered(G.deliveryIds);else if(W.retryAfter&&W.retryAfter>0)await this.storage.scheduleRetryWithoutAttemptIncrement(G.deliveryIds,W.retryAfter);else await this.storage.markDeliveriesFailed(G.deliveryIds,W.error||"Subscriber returned success=false",this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}catch(W){let Z=W instanceof Error?W.message:String(W);console.error(`[EventBus] Failed to notify subscription ${J}:`,Z),await this.storage.markDeliveriesFailed(G.deliveryIds,Z,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}for(let W of X)if(G.deliveryIds.includes(W.delivery.id))Q.add(W.event.id)}for(let J of Q)try{await this.storage.updateEventStatus(J);let G=X.find((W)=>W.event.id===J)?.event;if(G?.cron)await this.scheduleNextCronDelivery(G)}catch(G){console.error(`[EventBus] Failed to update event status ${J}:`,G)}}async processPerEventResults(X,Y){let Q=[],J=new Map,G=[],W=new Map;for(let Z=0;Z<X.events.length;Z++){let $=X.events?.[Z];if(!$)continue;let K=X.deliveryIds?.[Z];if(!K)continue;W.set($.id,K)}for(let Z of X.events){let $=W.get(Z.id);if(!$)continue;let K=Y.results?.[Z.id];if(K)if(K.success)Q.push($);else if(K.retryAfter&&K.retryAfter>0){let H=J.get(K.retryAfter)||[];H.push($),J.set(K.retryAfter,H)}else G.push({deliveryId:$,error:K.error||"Event processing failed"});else if(Y.success)Q.push($);else if(Y.retryAfter&&Y.retryAfter>0){let H=J.get(Y.retryAfter)||[];H.push($),J.set(Y.retryAfter,H)}else G.push({deliveryId:$,error:Y.error||"Batch processing failed"})}if(Q.length>0)await this.storage.markDeliveriesDelivered(Q);for(let[Z,$]of J)await this.storage.scheduleRetryWithoutAttemptIncrement($,Z);if(G.length>0){let Z=new Map;for(let{deliveryId:$,error:K}of G){let H=Z.get(K)||[];H.push($),Z.set(K,H)}for(let[$,K]of Z)await this.storage.markDeliveriesFailed(K,$,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}}async scheduleNextCronDelivery(X){if(!X.cron)return;try{let Q=new _b(X.cron).nextRun();if(!Q){console.log(`[EventBus] Cron expression for event ${X.id} has no more runs`);return}let J=Q.toISOString(),G=await this.storage.getMatchingSubscriptions(X);if(G.length===0){console.log(`[EventBus] No subscriptions for cron event ${X.id}, skipping next delivery`);return}await this.storage.createDeliveries(X.id,G.map((W)=>W.id),J),console.log(`[EventBus] Scheduled next cron delivery for event ${X.id} at ${J}`)}catch(Y){console.error(`[EventBus] Failed to schedule next cron delivery for event ${X.id}:`,Y)}}}class WY0{storage;worker;notifyStrategy;running=!1;constructor(X){this.storage=X.storage,this.notifyStrategy=X.notifyStrategy,this.worker=new GY0(this.storage,X.config)}async publish(X,Y,Q){if(Q.deliverAt&&Q.cron)throw Error("Cannot set both deliverAt and cron. Use one or the other.");let J;if(Q.cron){try{let F=new _b(Q.cron).nextRun();if(!F)throw Error("Cron expression does not produce a next run time");J=F.toISOString()}catch(H){throw Error(`Invalid cron expression: ${H instanceof Error?H.message:String(H)}`)}let K=await this.storage.findActiveCronEvent(X,Q.type,Y,Q.cron);if(K)return K}let G=crypto.randomUUID(),W=new Date().toISOString(),Z=await this.storage.publishEvent({id:G,organizationId:X,type:Q.type,source:Y,subject:Q.subject,time:W,data:Q.data,cron:Q.cron}),$=await this.storage.getMatchingSubscriptions(Z);if($.length>0){let K=Q.deliverAt??J;if(await this.storage.createDeliveries(G,$.map((H)=>H.id),K),this.notifyStrategy&&!K)await this.notifyStrategy.notify(G).catch((H)=>{console.warn("[EventBus] Notify failed (non-critical):",H)})}return Z}async subscribe(X,Y){return this.storage.subscribe({id:crypto.randomUUID(),organizationId:X,connectionId:Y.connectionId,publisher:Y.publisher,eventType:Y.eventType,filter:Y.filter})}async unsubscribe(X,Y){return this.storage.unsubscribe(Y,X)}async listSubscriptions(X,Y){return this.storage.listSubscriptions(X,Y)}async getSubscription(X,Y){return this.storage.getSubscription(Y,X)}async getEvent(X,Y){return this.storage.getEvent(Y,X)}async cancelEvent(X,Y,Q){return this.storage.cancelEvent(Y,X,Q)}async ackEvent(X,Y,Q){return this.storage.ackDelivery(Y,X,Q)}async syncSubscriptions(X,Y){return this.storage.syncSubscriptions({organizationId:X,...Y})}async start(){if(this.running)return;if(this.running=!0,await this.worker.start(),this.notifyStrategy)await this.notifyStrategy.start(()=>{this.worker.processNow().catch((X)=>{console.error("[EventBus] Error processing after notify:",X)})});await this.worker.processNow().catch((X)=>{console.error("[EventBus] Error processing pending events on startup:",X)})}async stop(){if(!this.running)return;if(this.running=!1,this.worker.stop(),this.notifyStrategy)try{await this.notifyStrategy.stop()}catch(X){console.error("[EventBus] Error stopping notify strategy:",X)}console.log("[EventBus] Stopped")}isRunning(){return this.running}}function z71(...X){return{async start(Y){await Promise.all(X.map((Q)=>Q.start(Y)))},async stop(){await Promise.all(X.map((Y)=>Y.stop().catch((Q)=>{console.error("[NotifyStrategy] Error stopping strategy:",Q)})))},async notify(Y){await Promise.all(X.map((Q)=>Q.notify(Y).catch((J)=>{console.warn("[NotifyStrategy] Notify failed (non-critical):",J)})))}}}class bb{intervalMs;timer=null;onNotify=null;constructor(X){this.intervalMs=X}async start(X){if(this.timer)return;this.onNotify=X,this.scheduleNext(),console.log(`[Polling] Started polling every ${this.intervalMs}ms`)}async stop(){if(this.timer)clearTimeout(this.timer),this.timer=null,console.log("[Polling] Stopped polling");this.onNotify=null}async notify(X){if(this.onNotify)this.onNotify()}scheduleNext(){this.timer=setTimeout(()=>{if(this.onNotify)this.onNotify();if(this.timer)this.scheduleNext()},this.intervalMs)}}import{sql as jh6}from"kysely";var ZB="mesh_events";class ZY0{db;pool;listenClient=null;onNotify=null;constructor(X,Y){this.db=X;this.pool=Y}async start(X){if(this.listenClient)return;this.onNotify=X;try{this.listenClient=await this.pool.connect(),this.listenClient.on("notification",(Y)=>{if(Y.channel===ZB&&this.onNotify)this.onNotify()}),this.listenClient.on("error",(Y)=>{console.error("[PostgresNotify] Connection error:",Y),this.cleanup()}),await this.listenClient.query(`LISTEN ${ZB}`),console.log("[PostgresNotify] Started LISTEN on",ZB)}catch(Y){console.error("[PostgresNotify] Failed to start LISTEN:",Y),this.cleanup()}}async stop(){if(this.listenClient){try{await this.listenClient.query(`UNLISTEN ${ZB}`),console.log("[PostgresNotify] Stopped LISTEN on",ZB)}catch{}this.cleanup()}}async notify(X){try{await jh6`SELECT pg_notify(${ZB}, ${X})`.execute(this.db)}catch(Y){console.warn("[PostgresNotify] Failed to send NOTIFY:",Y)}}cleanup(){if(this.listenClient)this.listenClient.release(),this.listenClient=null;this.onNotify=null}}function B71(X,Y){let Q=$71(X.db),J=Y?.pollIntervalMs??yb.pollIntervalMs,G=X.type==="postgres"?z71(new bb(J),new ZY0(X.db,X.pool)):new bb(J);return new WY0({storage:Q,config:Y,notifyStrategy:G})}var D71={google:{name:"Google",icon:"https://assets.decocache.com/webdraw/eb7480aa-a68b-4ce4-98ff-36aa121762a7/google.svg"},github:{name:"GitHub",icon:"https://assets.decocache.com/webdraw/5f999dcb-c8a6-4572-948c-9996ef1d502f/github.svg"},microsoft:{name:"Microsoft",icon:"https://assets.decocache.com/mcp/aa6f6e1a-6526-4bca-99cc-82e2ec38b0e4/microsoft.png"}};var N71=new p8;N71.get("/config",async(X)=>{try{let Y=Object.keys(e8.socialProviders??{}),Q=Y.length>0,J=Y.map((Z)=>({name:Z,icon:D71[Z].icon})),G=process.env.UNSAFE_ALLOW_STDIO_TRANSPORT==="true",W={emailAndPassword:{enabled:e8.emailAndPassword?.enabled??!1},magicLink:{enabled:e8.magicLinkConfig?.enabled??!1},socialProviders:{enabled:Q,providers:J},sso:e8.ssoConfig?{enabled:!0,providerId:e8.ssoConfig.providerId}:{enabled:!1},stdioEnabled:G};return X.json({success:!0,config:W})}catch(Y){let Q=Y instanceof Error?Y.message:"Failed to load auth config";return X.json({success:!1,error:Q},500)}});var O71=N71;eH();var i71="vercel.ai.error",Ch6=Symbol.for(i71),L71,w71,N1=class X extends(w71=Error,L71=Ch6,w71){constructor({name:Y,message:Q,cause:J}){super(Q);this[L71]=!0,this.name=Y,this.cause=J}static isInstance(Y){return X.hasMarker(Y,i71)}static hasMarker(Y,Q){let J=Symbol.for(Q);return Y!=null&&typeof Y==="object"&&J in Y&&typeof Y[J]==="boolean"&&Y[J]===!0}},a71="AI_APICallError",r71=`vercel.ai.error.${a71}`,Ih6=Symbol.for(r71),M71,P71,XX=class extends(P71=N1,M71=Ih6,P71){constructor({message:X,url:Y,requestBodyValues:Q,statusCode:J,responseHeaders:G,responseBody:W,cause:Z,isRetryable:$=J!=null&&(J===408||J===409||J===429||J>=500),data:K}){super({name:a71,message:X,cause:Z});this[M71]=!0,this.url=Y,this.requestBodyValues=Q,this.statusCode=J,this.responseHeaders=G,this.responseBody=W,this.isRetryable=$,this.data=K}static isInstance(X){return N1.hasMarker(X,r71)}},o71="AI_EmptyResponseBodyError",s71=`vercel.ai.error.${o71}`,Rh6=Symbol.for(s71),A71,T71,t71=class extends(T71=N1,A71=Rh6,T71){constructor({message:X="Empty response body"}={}){super({name:o71,message:X});this[A71]=!0}static isInstance(X){return N1.hasMarker(X,s71)}};function g5(X){if(X==null)return"unknown error";if(typeof X==="string")return X;if(X instanceof Error)return X.message;return JSON.stringify(X)}var e71="AI_InvalidArgumentError",XW1=`vercel.ai.error.${e71}`,Sh6=Symbol.for(XW1),E71,j71,YW1=class extends(j71=N1,E71=Sh6,j71){constructor({message:X,cause:Y,argument:Q}){super({name:e71,message:X,cause:Y});this[E71]=!0,this.argument=Q}static isInstance(X){return N1.hasMarker(X,XW1)}},QW1="AI_InvalidPromptError",JW1=`vercel.ai.error.${QW1}`,kh6=Symbol.for(JW1),C71,I71,PF=class extends(I71=N1,C71=kh6,I71){constructor({prompt:X,message:Y,cause:Q}){super({name:QW1,message:`Invalid prompt: ${Y}`,cause:Q});this[C71]=!0,this.prompt=X}static isInstance(X){return N1.hasMarker(X,JW1)}},GW1="AI_InvalidResponseDataError",WW1=`vercel.ai.error.${GW1}`,vh6=Symbol.for(WW1),R71,S71,fo4=class extends(S71=N1,R71=vh6,S71){constructor({data:X,message:Y=`Invalid response data: ${JSON.stringify(X)}.`}){super({name:GW1,message:Y});this[R71]=!0,this.data=X}static isInstance(X){return N1.hasMarker(X,WW1)}},ZW1="AI_JSONParseError",$W1=`vercel.ai.error.${ZW1}`,_h6=Symbol.for($W1),k71,v71,tP=class extends(v71=N1,k71=_h6,v71){constructor({text:X,cause:Y}){super({name:ZW1,message:`JSON parsing failed: Text: ${X}.
1052
- Error message: ${g5(Y)}`,cause:Y});this[k71]=!0,this.text=X}static isInstance(X){return N1.hasMarker(X,$W1)}},KW1="AI_LoadAPIKeyError",HW1=`vercel.ai.error.${KW1}`,yh6=Symbol.for(HW1),_71,y71,ho4=class extends(y71=N1,_71=yh6,y71){constructor({message:X}){super({name:KW1,message:X});this[_71]=!0}static isInstance(X){return N1.hasMarker(X,HW1)}},FW1="AI_LoadSettingError",VW1=`vercel.ai.error.${FW1}`,bh6=Symbol.for(VW1),b71,f71,xo4=class extends(f71=N1,b71=bh6,f71){constructor({message:X}){super({name:FW1,message:X});this[b71]=!0}static isInstance(X){return N1.hasMarker(X,VW1)}},qW1="AI_NoContentGeneratedError",UW1=`vercel.ai.error.${qW1}`,fh6=Symbol.for(UW1),h71,x71,go4=class extends(x71=N1,h71=fh6,x71){constructor({message:X="No content generated."}={}){super({name:qW1,message:X});this[h71]=!0}static isInstance(X){return N1.hasMarker(X,UW1)}},zW1="AI_NoSuchModelError",BW1=`vercel.ai.error.${zW1}`,hh6=Symbol.for(BW1),g71,u71,uo4=class extends(u71=N1,g71=hh6,u71){constructor({errorName:X=zW1,modelId:Y,modelType:Q,message:J=`No such ${Q}: ${Y}`}){super({name:X,message:J});this[g71]=!0,this.modelId=Y,this.modelType=Q}static isInstance(X){return N1.hasMarker(X,BW1)}},DW1="AI_TooManyEmbeddingValuesForCallError",NW1=`vercel.ai.error.${DW1}`,xh6=Symbol.for(NW1),m71,l71,mo4=class extends(l71=N1,m71=xh6,l71){constructor(X){super({name:DW1,message:`Too many values for a single embedding call. The ${X.provider} model "${X.modelId}" can only embed up to ${X.maxEmbeddingsPerCall} values per call, but ${X.values.length} values were provided.`});this[m71]=!0,this.provider=X.provider,this.modelId=X.modelId,this.maxEmbeddingsPerCall=X.maxEmbeddingsPerCall,this.values=X.values}static isInstance(X){return N1.hasMarker(X,NW1)}},OW1="AI_TypeValidationError",LW1=`vercel.ai.error.${OW1}`,gh6=Symbol.for(LW1),d71,p71,KQ=class X extends(p71=N1,d71=gh6,p71){constructor({value:Y,cause:Q}){super({name:OW1,message:`Type validation failed: Value: ${JSON.stringify(Y)}.
1051
+ `})}}}var df6=[f60({organizationCreation:{afterCreate:async(X)=>{await UG1(X.organization.id,X.member.userId)}},ac:Eb,creatorRole:"owner",allowUserToCreateOrganization:!0,dynamicAccessControl:{enabled:!0,maximumRolesPerOrganization:500,enableCustomResources:!0,allowedRolesToCreateResources:zG1,resourceNameValidation:(X)=>{return{valid:/^[a-zA-Z0-9-_]+$/.test(X)}}},roles:{user:uf6,admin:mf6,owner:lf6},sendInvitationEmail:LG1}),s60({loginPage:"/login",oidcConfig:{scopes:OG1,metadata:{scopes_supported:OG1},loginPage:"/login"}}),o60({enableMetadata:!0,maximumNameLength:64,keyExpiration:{minExpiresIn:0.003472222222222222},enableSessionForAPIKeys:!0,customAPIKeyGetter:(X)=>{if(X.headers?.get("X-MCP-Session-Auth")==="true")return null;let Q=X.headers?.get("Authorization");if(Q?.startsWith("Bearer "))return Q.replace("Bearer ","").trim();return null},permissions:{defaultPermissions:{self:["ORGANIZATION_LIST","ORGANIZATION_GET","ORGANIZATION_MEMBER_LIST","COLLECTION_CONNECTIONS_LIST","COLLECTION_CONNECTIONS_GET","API_KEY_CREATE","API_KEY_LIST"]}},rateLimit:{enabled:!1}}),g60({defaultRole:"user",adminRoles:["admin","owner"]}),Y40(),l60({jwt:{expirationTime:"5m"}}),h61(e8.ssoConfig?BG1(e8.ssoConfig):void 0),...e8.magicLinkConfig&&e8.emailProviders&&e8.emailProviders.length>0?[X40(Z91(e8.magicLinkConfig,e8.emailProviders))]:[]],pf6=u40(),cf6=W91(pf6),sW=i10({baseURL:process.env.BASE_URL||"http://localhost:3000",database:cf6,emailAndPassword:{enabled:!0},...e8,rateLimit:{enabled:process.env.DISABLE_RATE_LIMIT!=="true",window:60,max:1e4},plugins:df6,databaseHooks:{user:{create:{after:async(X)=>{if(JP.autoCreateOrganizationOnSignup===!1)return;let Y=X.name?X.name.split(" ")[0]:X.email.split("@")[0],Q=3;for(let J=0;J<Q;J++){let G=`${Y} ${hf6()}`,W=ff6(G);try{await sW.api.createOrganization({body:{name:G,slug:W,userId:X.id}});return}catch(Z){if(!(Z instanceof Error&&("body"in Z)&&Z.body?.code==="ORGANIZATION_ALREADY_EXISTS")||J===Q-1){console.error("Failed to create default organization:",Z);return}}}}}}}});vQ();import{randomBytes as nf6}from"crypto";var iP=null;function wG1(){if(iP)return iP;let X=process.env.MESH_JWT_SECRET??e8.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(X)iP=new TextEncoder().encode(X);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),iP=new Uint8Array(nf6(32));return iP}async function MG1(X,Y="5m"){let Q=wG1();return await new YQ(X).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Y).sign(Q)}async function PG1(X){try{let Y=wG1(),{payload:Q}=await K8(X,Y);return Q}catch{return}}cW();class mX0{db;constructor(X){this.db=X}async create(X,Y,Q){let J=t8("vir"),G=new Date().toISOString();if(await this.db.insertInto("connections").values({id:J,organization_id:X,created_by:Y,title:Q.title,description:Q.description??null,icon:Q.icon??null,app_name:null,app_id:null,connection_type:"VIRTUAL",connection_url:`virtual://${J}`,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:Q.metadata?JSON.stringify(Q.metadata):null,tools:null,bindings:null,status:Q.status??"active",created_at:G,updated_at:G}).execute(),Q.connections.length>0)await this.db.insertInto("connection_aggregations").values(Q.connections.map((Z)=>({id:t8("agg"),parent_connection_id:J,child_connection_id:Z.connection_id,selected_tools:Z.selected_tools?JSON.stringify(Z.selected_tools):null,selected_resources:Z.selected_resources?JSON.stringify(Z.selected_resources):null,selected_prompts:Z.selected_prompts?JSON.stringify(Z.selected_prompts):null,created_at:G}))).execute();let W=await this.findById(J);if(!W)throw Error(`Failed to create virtual MCP with id: ${J}`);return W}async findById(X){return this.findByIdInternal(this.db,X)}async findByIdInternal(X,Y){let Q=await X.selectFrom("connections").selectAll().where("id","=",Y).where("connection_type","=","VIRTUAL").executeTakeFirst();if(!Q)return null;let J=await X.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","=",Y).execute();return this.deserializeVirtualMCPEntity(Q,J)}async list(X){let Y=await this.db.selectFrom("connections").selectAll().where("organization_id","=",X).where("connection_type","=","VIRTUAL").execute(),Q=Y.map((W)=>W.id);if(Q.length===0)return[];let J=await this.db.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","in",Q).execute(),G=new Map;for(let W of J){let Z=G.get(W.parent_connection_id)??[];Z.push(W),G.set(W.parent_connection_id,Z)}return Y.map((W)=>this.deserializeVirtualMCPEntity(W,G.get(W.id)??[]))}async listByConnectionId(X,Y){let J=(await this.db.selectFrom("connection_aggregations").select("parent_connection_id").where("child_connection_id","=",Y).execute()).map((K)=>K.parent_connection_id);if(J.length===0)return[];let G=await this.db.selectFrom("connections").selectAll().where("id","in",J).where("organization_id","=",X).where("connection_type","=","VIRTUAL").execute();if(G.length===0)return[];let W=G.map((K)=>K.id),Z=await this.db.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","in",W).execute(),$=new Map;for(let K of Z){let H=$.get(K.parent_connection_id)??[];H.push(K),$.set(K.parent_connection_id,H)}return G.map((K)=>this.deserializeVirtualMCPEntity(K,$.get(K.id)??[]))}async update(X,Y,Q){let J=new Date().toISOString(),G={updated_at:J};if(Q.title!==void 0)G.title=Q.title;if(Q.description!==void 0)G.description=Q.description;if(Q.icon!==void 0)G.icon=Q.icon;if(Q.status!==void 0)G.status=Q.status;if(Q.metadata!==void 0)G.metadata=Q.metadata?JSON.stringify(Q.metadata):null;if(await this.db.updateTable("connections").set(G).where("id","=",X).where("connection_type","=","VIRTUAL").execute(),Q.connections!==void 0){if(await this.db.deleteFrom("connection_aggregations").where("parent_connection_id","=",X).execute(),Q.connections.length>0)await this.db.insertInto("connection_aggregations").values(Q.connections.map((Z)=>({id:t8("agg"),parent_connection_id:X,child_connection_id:Z.connection_id,selected_tools:Z.selected_tools?JSON.stringify(Z.selected_tools):null,selected_resources:Z.selected_resources?JSON.stringify(Z.selected_resources):null,selected_prompts:Z.selected_prompts?JSON.stringify(Z.selected_prompts):null,created_at:J}))).execute()}let W=await this.findById(X);if(!W)throw Error("Virtual MCP not found after update");return W}async delete(X){await this.db.deleteFrom("connection_aggregations").where("parent_connection_id","=",X).execute(),await this.db.deleteFrom("connections").where("id","=",X).where("connection_type","=","VIRTUAL").execute()}deserializeVirtualMCPEntity(X,Y){let Q=X.created_at instanceof Date?X.created_at.toISOString():X.created_at,J=X.updated_at instanceof Date?X.updated_at.toISOString():X.updated_at,G=X.status==="active"?"active":"inactive";return{id:X.id,organization_id:X.organization_id,title:X.title,description:X.description,tool_selection_mode:"inclusion",icon:X.icon,status:G,created_at:Q,updated_at:J,created_by:X.created_by,updated_by:void 0,metadata:this.parseJson(X.metadata),connections:Y.map((W)=>({connection_id:W.child_connection_id,selected_tools:this.parseJson(W.selected_tools),selected_resources:this.parseJson(W.selected_resources),selected_prompts:this.parseJson(W.selected_prompts)}))}}parseJson(X){if(X===null)return null;if(typeof X==="string")try{return JSON.parse(X)}catch{return null}return X}}import{sql as jb}from"kysely";class lX0{patterns=[{type:"email",regex:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g},{type:"api_key",regex:/(?:api[_-]?key|token|secret|password|bearer)\s*[:=]\s*['"]?[\w-]{16,}['"]?/gi},{type:"jwt",regex:/eyJ[A-Za-z0-9-_]+\.eyJ[A-Za-z0-9-_]+\.[A-Za-z0-9-_.+/=]*/g},{type:"credit_card",regex:/\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b/g},{type:"ssn",regex:/\b\d{3}-\d{2}-\d{4}\b/g}];redact(X){return HN.startActiveSpan("redactor.redact",(Y)=>{try{if(X===null||X===void 0)return X;if(typeof X==="string")return Y.setAttribute("data.type","string"),this.redactString(X);if(Array.isArray(X))return Y.setAttribute("data.type","array"),Y.setAttribute("data.length",X.length),X.map((Q)=>this.redact(Q));if(typeof X==="object"){Y.setAttribute("data.type","object");let Q={};for(let[J,G]of Object.entries(X)){let W=this.redactString(J);Q[W]=this.redact(G)}return Q}return Y.setAttribute("data.type",typeof X),X}finally{Y.end()}})}redactString(X){return HN.startActiveSpan("redactor.redactString",(Y)=>{try{Y.setAttribute("text.length",X.length);let Q=X,J=0;for(let G of this.patterns){let W=X.match(G.regex);if(W)J+=W.length,Y.setAttribute(`redaction.${G.type}.count`,W.length);Q=Q.replace(G.regex,`[REDACTED:${G.type}]`)}return Y.setAttribute("redaction.total_count",J),Q}finally{Y.end()}})}}cW();class dX0{db;redactor;databaseType;constructor(X,Y="sqlite"){this.db=X;this.redactor=new lX0,this.databaseType=Y}jsonExtract(X,Y){if(this.databaseType==="postgres")return jb`(${jb.ref(X)}::jsonb)->>${Y}`;let Q=`$.${Y}`;return jb`json_extract(${jb.ref(X)}, ${Q})`}async log(X){await this.logBatch([X])}async logBatch(X){if(X.length===0)return;let Y=X.map((Q)=>({...Q,input:this.redactor.redact(Q.input),output:this.redactor.redact(Q.output)}));await this.db.transaction().execute(async(Q)=>{await Q.insertInto("monitoring_logs").values(Y.map((J)=>this.toDbRow(J))).execute()})}async query(X){let Y=this.db.selectFrom("monitoring_logs").selectAll(),Q=this.db.selectFrom("monitoring_logs").select(($)=>$.fn.count("id").as("count"));if(X.organizationId)Y=Y.where("organization_id","=",X.organizationId),Q=Q.where("organization_id","=",X.organizationId);if(X.connectionId)Y=Y.where("connection_id","=",X.connectionId),Q=Q.where("connection_id","=",X.connectionId);if(X.virtualMcpId)Y=Y.where("virtual_mcp_id","=",X.virtualMcpId),Q=Q.where("virtual_mcp_id","=",X.virtualMcpId);if(X.toolName)Y=Y.where("tool_name","=",X.toolName),Q=Q.where("tool_name","=",X.toolName);if(X.isError!==void 0)Y=Y.where("is_error","=",X.isError?1:0),Q=Q.where("is_error","=",X.isError?1:0);if(X.startDate)Y=Y.where("timestamp",">=",X.startDate.toISOString()),Q=Q.where("timestamp",">=",X.startDate.toISOString());if(X.endDate)Y=Y.where("timestamp","<=",X.endDate.toISOString()),Q=Q.where("timestamp","<=",X.endDate.toISOString());if(X.propertyFilters){let{properties:$,propertyKeys:K,propertyPatterns:H}=X.propertyFilters;if($)for(let[F,V]of Object.entries($)){let q=this.jsonExtract("properties",F);Y=Y.where(q,"=",V),Q=Q.where(q,"=",V)}if(K&&K.length>0)for(let F of K){let V=this.jsonExtract("properties",F);Y=Y.where(V,"is not",null),Q=Q.where(V,"is not",null)}if(H)for(let[F,V]of Object.entries(H)){let q=this.jsonExtract("properties",F),z=this.databaseType==="postgres"?"ilike":"like";Y=Y.where(q,z,V),Q=Q.where(q,z,V)}}if(Y=Y.orderBy("timestamp","desc"),X.limit)Y=Y.limit(X.limit);if(X.offset)Y=Y.offset(X.offset);let[J,G]=await Promise.all([Y.execute(),Q.executeTakeFirst()]),W=Number(G?.count||0);return{logs:J.map(($)=>this.fromDbRow($)),total:W}}async getStats(X){let Y=this.db.selectFrom("monitoring_logs").where("organization_id","=",X.organizationId);if(X.startDate)Y=Y.where("timestamp",">=",X.startDate.toISOString());if(X.endDate)Y=Y.where("timestamp","<=",X.endDate.toISOString());let Q=await Y.select([(Z)=>Z.fn.count("id").as("total_count"),(Z)=>Z.fn.sum(Z.ref("is_error")).as("error_count"),(Z)=>Z.fn.avg("duration_ms").as("avg_duration")]).executeTakeFirst(),J=Number(Q?.total_count||0),G=Number(Q?.error_count||0),W=Number(Q?.avg_duration||0);return{totalCalls:J,errorRate:J>0?G/J:0,avgDurationMs:W}}toDbRow(X){return{id:X.id||t8("log"),organization_id:X.organizationId,connection_id:X.connectionId,connection_title:X.connectionTitle,tool_name:X.toolName,input:JSON.stringify(X.input),output:JSON.stringify(X.output),is_error:X.isError?1:0,error_message:X.errorMessage||null,duration_ms:X.durationMs,timestamp:X.timestamp instanceof Date?X.timestamp.toISOString():X.timestamp,user_id:X.userId||null,request_id:X.requestId,user_agent:X.userAgent||null,virtual_mcp_id:X.virtualMcpId||null,properties:X.properties?JSON.stringify(X.properties):null}}fromDbRow(X){let Y=typeof X.input==="string"?JSON.parse(X.input):X.input,Q=typeof X.output==="string"?JSON.parse(X.output):X.output,J=typeof X.timestamp==="string"?new Date(X.timestamp):X.timestamp,G=X.properties?typeof X.properties==="string"?JSON.parse(X.properties):X.properties:null;return{id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,connectionTitle:X.connection_title,toolName:X.tool_name,input:Y,output:Q,isError:X.is_error===1,errorMessage:X.error_message,durationMs:X.duration_ms,timestamp:J,userId:X.user_id,requestId:X.request_id,userAgent:X.user_agent,virtualMcpId:X.virtual_mcp_id,properties:G}}}class pX0{db;constructor(X){this.db=X}async get(X){let Y=await this.db.selectFrom("organization_settings").selectAll().where("organizationId","=",X).executeTakeFirst();if(!Y)return null;return{organizationId:Y.organizationId,sidebar_items:Y.sidebar_items?typeof Y.sidebar_items==="string"?JSON.parse(Y.sidebar_items):Y.sidebar_items:null,enabled_plugins:Y.enabled_plugins?typeof Y.enabled_plugins==="string"?JSON.parse(Y.enabled_plugins):Y.enabled_plugins:null,createdAt:Y.createdAt,updatedAt:Y.updatedAt}}async upsert(X,Y){let Q=new Date().toISOString(),J=Y?.sidebar_items?JSON.stringify(Y.sidebar_items):null,G=Y?.enabled_plugins?JSON.stringify(Y.enabled_plugins):null;await this.db.insertInto("organization_settings").values({organizationId:X,sidebar_items:J,enabled_plugins:G,createdAt:Q,updatedAt:Q}).onConflict((Z)=>Z.column("organizationId").doUpdateSet({sidebar_items:J?J:void 0,enabled_plugins:G?G:void 0,updatedAt:Q})).execute();let W=await this.get(X);if(!W)return{organizationId:X,sidebar_items:Y?.sidebar_items??null,enabled_plugins:Y?.enabled_plugins??null,createdAt:Q,updatedAt:Q};return W}}class cX0{db;constructor(X){this.db=X}async findById(X,Y){let Q=await this.db.selectFrom("user").select(["user.id","user.name","user.email","user.image","user.createdAt","user.updatedAt"]).where("user.id","=",X).where((J)=>J.exists(J.selectFrom("member as m1").innerJoin("member as m2","m1.organizationId","m2.organizationId").select("m1.id").where("m1.userId","=",X).where("m2.userId","=",Y))).executeTakeFirst();if(!Q)return null;return{id:Q.id,name:Q.name,email:Q.email,role:"",createdAt:Q.createdAt,updatedAt:Q.updatedAt,image:Q.image??void 0}}}var AG1="mcp.mesh";class TG1 extends Error{constructor(X){super(X);this.name="UnauthorizedError"}}class nX0 extends Error{constructor(X){super(X);this.name="ForbiddenError"}}class UK{userId;toolName;boundAuth;role;connectionId;getToolMeta;_granted=!1;constructor(X,Y,Q,J,G,W="self",Z){this.userId=Y;this.toolName=Q;this.boundAuth=J;this.role=G;this.connectionId=W;this.getToolMeta=Z}[Symbol.dispose](){this._granted=!1}setToolName(X){this.toolName=X}grant(){return this._granted=!0,{[Symbol.dispose]:()=>{this._granted=!1}}}async check(...X){if(this._granted)return;if(!this.userId&&!this.boundAuth){if(this.getToolMeta&&await this.isToolPublic()){this.grant();return}throw new TG1("Authentication required. Please provide a valid OAuth token or API key.")}let Y=X.length>0?X:this.toolName?[this.toolName]:[];if(Y.length===0)throw new nX0("No resources specified for access check");for(let Q of Y)if(await this.checkResource(Q)){this.grant();return}throw new nX0(`Access denied to: ${Y.join(", ")}`)}async checkResource(X){if(!this.userId&&!this.boundAuth)return!1;if(this.role==="admin"||this.role==="owner")return!0;if(!this.boundAuth)return!1;let Y={};if(this.connectionId)Y[this.connectionId]=[X];return this.boundAuth.hasPermission(Y)}async isToolPublic(){if(!this.getToolMeta)return!1;try{let X=await this.getToolMeta();if(!X)return!1;let Q=X[AG1]?.public_tool;return Q===!0||Q==="true"}catch{return!1}}granted(){return this._granted}}q7();function EG1(X){let Y=null;return()=>{if(Y)return Y;return Y=X().catch((Q)=>{throw Y=null,Q}),Y}}class jG1{factory;promise=null;constructor(X){this.factory=X}getOrCreatePromise(){if(!this.promise)this.promise=this.factory();return this.promise}then(X,Y){return this.getOrCreatePromise().then(X,Y)}catch(X){return this.getOrCreatePromise().catch(X)}finally(X){return this.getOrCreatePromise().finally(X)}}function B7(X){return new jG1(X)}class iX0{proxies;options;cache;constructor(X,Y){this.proxies=X;this.options=Y;this.cache=B7(()=>this.loadPrompts())}async loadPrompts(){let X=await this.proxies.mapSettled(async(G,W)=>{try{let $=(await G.proxy.client.listPrompts()).prompts;if(this.options.selectionMode==="exclusion"){if(G.selectedPrompts&&G.selectedPrompts.length>0){let K=new Set(G.selectedPrompts);$=$.filter((H)=>!K.has(H.name))}}else if(!G.selectedPrompts||G.selectedPrompts.length===0)$=[];else{let K=new Set(G.selectedPrompts);$=$.filter((H)=>K.has(H.name))}return{connectionId:W,prompts:$}}catch(Z){return console.error(`[PromptAggregator] Failed to list prompts for connection ${W}:`,Z),{connectionId:W,prompts:[]}}}),Y=new Set,Q=[],J=new Map;for(let G of X){if(G.status!=="fulfilled")continue;let{connectionId:W,prompts:Z}=G.value;for(let $ of Z){if(Y.has($.name))continue;Y.add($.name),Q.push($),J.set($.name,W)}}return{prompts:Q,mappings:J}}async list(){return{prompts:(await this.cache).prompts}}async get(X){let Q=(await this.cache).mappings.get(X.name);if(!Q)throw Error(`Prompt not found: ${X.name}`);let J=this.proxies.get(Q);if(!J)throw Error(`Connection not found for prompt: ${X.name}`);return await J.proxy.client.getPrompt(X)}}qX();function if6(X,Y){if(X===Y)return!0;if(!Y.includes("*"))return!1;let Q=Y.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"<<<DOUBLE_STAR>>>").replace(/\*/g,"[^/]*").replace(/<<<DOUBLE_STAR>>>/g,".*");Q=`^${Q}$`;try{return new RegExp(Q).test(X)}catch{return!1}}function CG1(X,Y){return Y.some((Q)=>if6(X,Q))}class aX0{proxies;options;cache;constructor(X,Y){this.proxies=X;this.options=Y;this.cache=B7(()=>this.loadResources())}async loadResources(){let X=await this.proxies.mapSettled(async(G,W)=>{try{let $=(await G.proxy.client.listResources()).resources;if(this.options.selectionMode==="exclusion"){if(G.selectedResources&&G.selectedResources.length>0)$=$.filter((K)=>!CG1(K.uri,G.selectedResources))}else if(!G.selectedResources||G.selectedResources.length===0)$=[];else $=$.filter((K)=>CG1(K.uri,G.selectedResources));return{connectionId:W,resources:$}}catch(Z){if(!(Z instanceof Q1)||Z.code!==$1.MethodNotFound)console.error(`[aggregator] Failed to list resources for connection ${W}: (defaulting to empty array)`,Z);return{connectionId:W,resources:[]}}}),Y=new Set,Q=[],J=new Map;for(let G of X){if(G.status!=="fulfilled")continue;let{connectionId:W,resources:Z}=G.value;for(let $ of Z){if(Y.has($.uri))continue;Y.add($.uri),Q.push($),J.set($.uri,W)}}return{resources:Q,mappings:J}}async list(){return{resources:(await this.cache).resources}}async read(X){let Q=(await this.cache).mappings.get(X.uri);if(!Q)throw Error(`Resource not found: ${X.uri}`);let J=this.proxies.get(Q);if(!J)throw Error(`Connection not found for resource: ${X.uri}`);return await J.proxy.client.readResource(X)}}qX();class rX0{proxies;cache;constructor(X){this.proxies=X;this.cache=B7(()=>this.loadResourceTemplates())}async loadResourceTemplates(){let X=await this.proxies.mapSettled(async(Q,J)=>{try{let G=await Q.proxy.client.listResourceTemplates();return{connectionId:J,templates:G.resourceTemplates}}catch(G){if(!(G instanceof Q1)||G.code!==$1.MethodNotFound)console.error(`[aggregator] Failed to list resource templates for connection ${J}: (defaulting to empty array)`,G);return{connectionId:J,templates:[]}}}),Y=[];for(let Q of X){if(Q.status!=="fulfilled")continue;let{templates:J}=Q.value;for(let G of J)Y.push(G)}return{templates:Y}}async list(){return{resourceTemplates:(await this.cache).templates}}}qX();a0();jP();var RG1=U.object({query:U.string().min(1).describe("Search query to find tools by name or description"),limit:U.number().default(10).describe("Maximum number of results to return")}),af6=U.toJSONSchema(RG1),SG1=U.object({tools:U.array(U.string()).min(1).describe("Array of tool names to get detailed schemas for")}),rf6=U.toJSONSchema(SG1),kG1=U.object({code:U.string().min(1).describe("JavaScript code to execute. It runs as an async function body; you can use top-level `return` and `await`."),timeoutMs:U.number().default(3000).describe("Max execution time in milliseconds (default: 3000).")}),of6=U.toJSONSchema(kG1),IG1=new Map;function sf6(X){let Y=X.slice().sort().join(","),Q=IG1.get(Y);if(!Q){let J=U.object({name:(X.length>0?U.enum(X):U.string()).describe("The name of the tool to execute"),arguments:U.record(U.string(),U.unknown()).default({}).describe("Arguments to pass to the tool")});Q={schema:J,jsonSchema:U.toJSONSchema(J)},IG1.set(Y,Q)}return Q}function vG1(X){let Y=EP(X.tools);return{tool:{name:"GATEWAY_SEARCH_TOOLS",description:`Search for available tools by name or description. Returns tool names and brief descriptions without full schemas. Use this to discover tools before calling GATEWAY_DESCRIBE_TOOLS for detailed schemas.${X.categories.length>0?` Available categories: ${X.categories.join(", ")}.`:""} Total tools: ${Y.length}.`,inputSchema:af6},handler:async(J)=>{let G=RG1.safeParse(J);if(!G.success)return QB({error:G.error.flatten()});let W=Fb(G.data.query,Y,G.data.limit);return Ub({query:G.data.query,results:W.map((Z)=>({name:Z.name,description:Z.description,connection:Z._meta.connectionTitle})),totalAvailable:Y.length})}}}function _G1(X){let Y=EP(X.tools);return{tool:{name:"GATEWAY_DESCRIBE_TOOLS",description:"Get detailed schemas for specific tools. Call after GATEWAY_SEARCH_TOOLS to get full input/output schemas.",inputSchema:rf6},handler:async(Q)=>{let J=SG1.safeParse(Q);if(!J.success)return QB({error:J.error.flatten()});let G=Vb(J.data.tools,Y);return Ub({tools:G.tools,notFound:G.notFound})}}}function tf6(X){let Y=EP(X.tools),Q=Y.map((Z)=>Z.name),J=new Map(Y.map((Z)=>[Z.name,Z])),{schema:G,jsonSchema:W}=sf6(Q);return{tool:{name:"GATEWAY_CALL_TOOL",description:"Execute a tool by name. Use GATEWAY_DESCRIBE_TOOLS first to understand the input schema.",inputSchema:W},handler:async(Z)=>{let $=G.safeParse(Z);if(!$.success)return QB({error:$.error.flatten()});let{name:K,arguments:H}=$.data;if(!J.has(K))return{content:[{type:"text",text:`Tool not found: ${K}. Use GATEWAY_SEARCH_TOOLS to find available tools.`}],isError:!0};return X.callTool(K,H)}}}function ef6(X){let Y=EP(X.tools);return{tool:{name:"GATEWAY_RUN_CODE",description:'Run JavaScript code in a sandbox. Code must be an ES module that `export default`s an async function that receives (tools) as its first parameter. Use GATEWAY_DESCRIBE_TOOLS to understand the input/output schemas for a tool before calling it. Use `await tools.toolName(args)` or `await tools["tool-name"](args)` to call tools.',inputSchema:of6},handler:async(Q)=>{let J=kG1.safeParse(Q);if(!J.success)return QB({error:J.error.flatten()});let G={...X,tools:Y},W=await qb(J.data.code,G,J.data.timeoutMs);if(W.error)return QB(W);return Ub(W)}}}function yG1(X){let Y=new Map(X.map((J)=>[J.tool.name,J.handler])),Q=X.map((J)=>J.tool.name);return{tools:X.map((J)=>J.tool),callTool:async(J,G)=>{let W=Y.get(J);if(!W)return{content:[{type:"text",text:`Unknown meta-tool: ${J}. Available: ${Q.join(", ")}`}],isError:!0};return W(G)}}}var Xh6=(X)=>({tools:X.tools,callTool:(Y,Q)=>X.callTool(Y,Q)}),Yh6=(X)=>yG1([vG1(X),_G1(X),ef6(X)]),Qh6=(X)=>yG1([vG1(X),_G1(X),tf6(X)]);function bG1(X){switch(X){case"smart_tool_selection":return Qh6;case"code_execution":return Yh6;case"passthrough":default:return Xh6}}function fG1(X){switch(X){case"smart_tool_selection":return"smart_tool_selection";case"code_execution":return"code_execution";case"passthrough":default:return"passthrough"}}class oX0{proxies;options;cache;constructor(X,Y){this.proxies=X;this.options=Y;this.cache=B7(()=>this.loadTools())}async loadTools(){let X=await this.proxies.mapSettled(async(K,H)=>{try{let V=(await K.proxy.client.listTools()).tools;if(this.options.selectionMode==="exclusion"){if(K.selectedTools&&K.selectedTools.length>0){let q=new Set(K.selectedTools);V=V.filter((z)=>!q.has(z.name))}}else if(K.selectedTools&&K.selectedTools.length>0){let q=new Set(K.selectedTools);V=V.filter((z)=>q.has(z.name))}return{connectionId:H,connectionTitle:K.connection.title,tools:V}}catch(F){if(!(F instanceof Q1)||F.code!==$1.MethodNotFound)console.error(`[aggregator] Failed to list tools ${H}: (defaulting to null)`,F);return null}}),Y=new Set,Q=[],J=new Map,G=new Set;for(let K of X){if(K.status!=="fulfilled"||!K.value)continue;let{connectionId:H,connectionTitle:F,tools:V}=K.value;G.add(F);for(let q of V){if(Y.has(q.name))continue;Y.add(q.name),Q.push({...q,_meta:{connectionId:H,connectionTitle:F}}),J.set(q.name,{connectionId:H,originalName:q.name})}}let W=async(K,H)=>{let F=J.get(K);if(!F)return{content:[{type:"text",text:`Tool not found: ${K}`}],isError:!0};let V=this.proxies.get(F.connectionId);if(!V)return{content:[{type:"text",text:`Connection not found for tool: ${K}`}],isError:!0};return await V.proxy.client.callTool({name:F.originalName,arguments:H})},$=bG1(this.options.strategy)({tools:Q,callTool:W,categories:Array.from(G).sort()});return{tools:Q,mappings:J,strategyResult:$}}async list(){return{tools:(await this.cache).strategyResult.tools}}async call(X){return(await this.cache).strategyResult.callTool(X.name,X.arguments??{})}async callStreamable(X,Y){let Q=await this.cache,J=Q.mappings.get(X);if(J){let W=this.proxies.get(J.connectionId);if(W)return W.proxy.callStreamableTool(J.originalName,Y)}let G=await Q.strategyResult.callTool(X,Y);return new Response(JSON.stringify(G),{headers:{"Content-Type":"application/json"}})}}function hG1(X,Y){if(X.connection_type!=="VIRTUAL")return!1;return $K(X.connection_url)===Y}async function Jh6(X,Y){let Q=await sz.create(X.connections,Y),J=new oX0(Q,{selectionMode:X.toolSelectionMode,strategy:X.toolSelectionStrategy}),G=new aX0(Q,{selectionMode:X.toolSelectionMode}),W=new rX0(Q),Z=new iX0(Q,{selectionMode:X.toolSelectionMode});return{client:{listTools:J.list.bind(J),callTool:J.call.bind(J),listResources:G.list.bind(G),readResource:G.read.bind(G),listResourceTemplates:W.list.bind(W),listPrompts:Z.list.bind(Z),getPrompt:Z.get.bind(Z)},callStreamableTool:J.callStreamable.bind(J)}}async function aP(X,Y,Q){let J;if(X.tool_selection_mode==="exclusion"){let Z=(await Y.storage.connections.list(X.organization_id)).filter((K)=>K.status==="active"&&!hG1(K,X.id)),$=new Map;for(let K of X.connections)$.set(K.connection_id,{selectedTools:K.selected_tools,selectedResources:K.selected_resources,selectedPrompts:K.selected_prompts});J=[];for(let K of Z){let H=$.get(K.id);if(H===void 0)J.push({connection:K,selectedTools:null,selectedResources:null,selectedPrompts:null});else if((H.selectedTools===null||H.selectedTools.length===0)&&(H.selectedResources===null||H.selectedResources.length===0)&&(H.selectedPrompts===null||H.selectedPrompts.length===0));else J.push({connection:K,selectedTools:H.selectedTools,selectedResources:H.selectedResources,selectedPrompts:H.selectedPrompts})}}else{let W=X.connections.map(($)=>$.connection_id),Z=[];for(let $ of W){let K=await Y.storage.connections.findById($);if(K&&K.status==="active"&&!hG1(K,X.id))Z.push(K)}J=Z.map(($)=>{let K=X.connections.find((H)=>H.connection_id===$.id);return{connection:$,selectedTools:K?.selected_tools??null,selectedResources:K?.selected_resources??null,selectedPrompts:K?.selected_prompts??null}})}let G={connections:J,toolSelectionMode:X.tool_selection_mode,toolSelectionStrategy:Q};return Jh6(G,Y)}e80();async function xG1(X){if(!X.refreshToken)return{success:!1,error:"No refresh token available"};if(!X.tokenEndpoint)return{success:!1,error:"No token endpoint available"};if(!X.clientId)return{success:!1,error:"No client ID available"};try{let Y=new URLSearchParams({grant_type:"refresh_token",refresh_token:X.refreshToken,client_id:X.clientId});if(X.clientSecret)Y.set("client_secret",X.clientSecret);if(X.scope)Y.set("scope",X.scope);let Q=await fetch(X.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Y.toString()});if(!Q.ok){let G=await Q.text();console.error(`[TokenRefresh] Failed to refresh token: ${Q.status}`,G);try{let W=JSON.parse(G);return{success:!1,error:W.error_description||W.error||`Token refresh failed: ${Q.status}`}}catch{return{success:!1,error:`Token refresh failed: ${Q.status}`}}}let J=await Q.json();return{success:!0,accessToken:J.access_token,refreshToken:J.refresh_token||X.refreshToken,expiresIn:J.expires_in,scope:J.scope}}catch(Y){return console.error("[TokenRefresh] Error refreshing token:",Y),{success:!1,error:Y instanceof Error?Y.message:"Token refresh failed"}}}eH();H80();function Gh6(X){return new Proxy(X,{get(Q,J,G){if(J==="close")return async()=>{};if(J==="__actualClient")return Q;return Reflect.get(Q,J,G)}})}var gG1="__mesh_stable_stdio_pool__",MF=globalThis[gG1]??(globalThis[gG1]=new Map);async function mG1(X,Y){let Q=MF.get(X.id);if(Q?.status==="connected"&&Q.stableClient)return Q.stableClient;if(Q?.connectPromise&&(Q.status==="connecting"||Q.status==="reconnecting"))return Q.connectPromise;let J=Q?.status==="failed",G=Q??{transport:null,client:null,stableClient:null,config:X,status:"connecting",connectPromise:null};if(!Q)MF.set(X.id,G);return G.status=J?"reconnecting":"connecting",G.connectPromise=(async()=>{try{console.log(`[StableStdio] ${J?"Respawning":"Spawning"}: ${X.id} (${X.command} ${X.args?.join(" ")??""})`);let W=new wP({command:X.command,args:X.args,env:X.env,cwd:X.cwd,stderr:"pipe"});G.transport=W;let Z=Y??new l9({name:`mesh-stdio-${X.id}`,version:"1.0.0"});G.client=Z,G.stableClient=Gh6(Z),Z.onclose=()=>{console.log(`[StableStdio] Connection closed unexpectedly: ${X.id}`),G.status="failed",G.connectPromise=null};let $=X.name||X.id,K="\x1B[2m",H="\x1B[0m";W.stderr?.on("data",(q)=>{let z=q.toString().trimEnd();if(z)console.error(`${z} ${K}[${$}]${H}`)});let F=new AbortController,V=setTimeout(()=>F.abort(),30000);try{await Promise.race([Z.connect(W),new Promise((q,z)=>{F.signal.addEventListener("abort",()=>{z(Error("Stdio connection timeout after 30s"))})})])}finally{clearTimeout(V)}return G.status="connected",console.log(`[StableStdio] Connected: ${X.id}`),G.stableClient}catch(W){console.error(`[StableStdio] Failed to connect ${X.id}:`,W),G.status="failed",G.connectPromise=null;try{await G.transport?.close()}catch{}throw W}})(),G.connectPromise}async function Wh6(X){let Y=MF.get(X);if(!Y)return;console.log(`[StableStdio] Force closing: ${X}`);try{if(Y.client)Y.client.onclose=void 0;await Y.client?.close()}catch{}MF.delete(X)}async function Zh6(){console.log(`[StableStdio] Closing all connections (${MF.size})`);let X=Array.from(MF.keys()).map((Y)=>Wh6(Y));await Promise.allSettled(X),MF.clear()}var uG1="__mesh_stable_stdio_shutdown_registered__";if(!globalThis[uG1]){globalThis[uG1]=!0;let X=async(Y)=>{await Zh6(),process.exit(Y==="SIGINT"?130:143)};process.on("SIGINT",()=>X("SIGINT")),process.on("SIGTERM",()=>X("SIGTERM"))}Ab();q7();eH();Xb();oq();Gb();Wb();qX();Gb();Wb();qX();gL();var sX0=new p8;async function Cb(X,Y){let Q=X.get("meshContext");try{let J=X.req.header("x-org-id"),G=X.req.header("x-org-slug"),W=J?J:G?await Q.db.selectFrom("organization").select("id").where("slug","=",G).executeTakeFirst().then((z)=>z?.id):null,Z=Y?await Q.storage.virtualMcps.findById(Y):W?Eo(W):null;if(!Z)return X.json({error:"Agent not found"},404);if(W&&Z.organization_id!==W)return X.json({error:"Agent not found"},404);if(Z.status!=="active")return X.json({error:`Agent is inactive: ${Z.id}`},503);Q.connectionId=Z.id;let $=await Q.db.selectFrom("organization").select(["id","slug","name"]).where("id","=",Z.organization_id).executeTakeFirst();if($)Q.organization={id:$.id,slug:$.slug,name:$.name};let K=X.req.query("mode"),H=fG1(K),F=await aP(Z,Q,H),V=new qF({name:`mcp-virtual-mcp-${Z.title}`,version:"1.0.0"},{capabilities:{tools:{},resources:{},prompts:{}},instructions:Z.metadata?.instructions??void 0}),q=new UF({enableJsonResponse:X.req.header("Accept")?.includes("application/json")??!1});await V.connect(q),V.server.setRequestHandler(eZ,async(z)=>{return F.client.listTools()}),V.server.setRequestHandler(TG,async(z)=>{return await F.client.callTool(z.params)}),V.server.setRequestHandler(aZ,async()=>{return F.client.listResources()}),V.server.setRequestHandler(oZ,async(z)=>{return F.client.readResource(z.params)}),V.server.setRequestHandler(rZ,async()=>{return F.client.listResourceTemplates()}),V.server.setRequestHandler(sZ,async()=>{return F.client.listPrompts()}),V.server.setRequestHandler(tZ,async(z)=>{return F.client.getPrompt(z.params)});try{return await q.handleRequest(X.req.raw)}finally{try{await q.close?.()}catch{}}}catch(J){let G=J;return console.error("[virtual-mcp] Error handling virtual MCP request:",G),X.json({error:"Internal server error",message:G.message},500)}}sX0.all("/gateway/:virtualMcpId?",async(X)=>{let Y=X.req.param("virtualMcpId");return Cb(X,Y)});sX0.all("/virtual-mcp/:virtualMcpId?",async(X)=>{let Y=X.req.param("virtualMcpId");return Cb(X,Y)});var lG1=sX0;var Ib=new p8,tX0=[404,401,406];async function dG1(X,Y){return(await Y.storage.connections.findById(X))?.connection_url??null}function $h6(X){let Y=X.toLowerCase();return Y.includes("resource_metadata=")||Y.includes("invalid_token")||Y.includes("oauth")}async function pG1(X,Y={}){try{let Q=await fetch(X,{method:"POST",headers:{...Y,"Content-Type":"application/json",Accept:"application/json, text/event-stream"},body:JSON.stringify({jsonrpc:"2.0",id:0,method:"initialize",params:{protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"mcp-mesh-proxy",version:"1.0.0"}}})});if(Q.status===401){let J=Q.headers.get("WWW-Authenticate");if(J){if($h6(J))return J}}return null}catch{return null}}async function Rb(X){let Q=new URL(X).pathname;if(Q.endsWith("/"))Q=Q.slice(0,-1);let J=new URL(X);J.pathname=`${Q}/.well-known/oauth-protected-resource`;let G=await fetch(J.toString(),{method:"GET",headers:{Accept:"application/json"}});if(G.ok)return G;if(!tX0.includes(G.status))return G;let W=new URL(X);if(W.pathname=`/.well-known/oauth-protected-resource${Q}`,G=await fetch(W.toString(),{method:"GET",headers:{Accept:"application/json"}}),!tX0.includes(G.status))return G;let Z=new URL(X);return Z.pathname="/.well-known/oauth-protected-resource",G=await fetch(Z.toString(),{method:"GET",headers:{Accept:"application/json"}}),G}async function Kh6(X,Y){let Q=await dG1(X,Y);if(!Q)return null;let J;try{J=new URL(Q).origin}catch{return null}try{let G=await Rb(Q);if(G.ok){let W=await G.json();if(W.authorization_servers?.[0])return W.authorization_servers[0]}}catch{}return J}async function cG1(X){let Y=X.get("meshContext");if(!Y)Y=await zK.create(X.req.raw),X.set("meshContext",Y);return Y}async function nG1({error:X,reqUrl:Y,connectionId:Q,connectionUrl:J,headers:G}){let W=X.message?.toLowerCase()??"";if(!(X.status===401||X.code===401||X.message?.includes("401")||W.includes("unauthorized")||W.includes("invalid_token")||W.includes("api key required")||W.includes("api-key required")))return null;if(Boolean(await pG1(J,G)))return new Response(null,{status:401,headers:{"WWW-Authenticate":`Bearer realm="mcp",resource_metadata="${Y.origin}/mcp/${Q}/.well-known/oauth-protected-resource"`}});return new Response(JSON.stringify({error:"unauthorized",message:"Authentication required but server does not support OAuth"}),{status:401,headers:{"Content-Type":"application/json"}})}var Sb=(X)=>{if(!(X.hostname==="localhost"||X.hostname==="127.0.0.1"))X.protocol="https:";return X},iG1=async(X)=>{let Y=X.req.param("connectionId"),Q=await cG1(X),J=await dG1(Y,Q);if(!J)return X.json({error:"Connection not found"},404);let G=Sb(new URL(X.req.url)),W=`${G.origin}/mcp/${Y}`,Z=`${G.origin}/oauth-proxy/${Y}`;try{let $=await Rb(J);if(!$.ok&&tX0.includes($.status)){if(await pG1(J))return new Response(JSON.stringify({resource:W,authorization_servers:[Z],bearer_methods_supported:["header"],scopes_supported:["*"]}),{status:200,headers:{"Content-Type":"application/json"}});return new Response($.body,{status:$.status,statusText:$.statusText,headers:{"Content-Type":"application/json"}})}if(!$.ok)return new Response($.body,{status:$.status,statusText:$.statusText,headers:{"Content-Type":"application/json"}});let H={...await $.json(),resource:W,authorization_servers:[Z]};return new Response(JSON.stringify(H),{status:$.status,statusText:$.statusText,headers:{"Content-Type":"application/json"}})}catch($){let K=$;return console.error("[oauth-proxy] Failed to proxy OAuth protected resource metadata:",K),X.json({error:"Failed to proxy OAuth metadata",message:K.message},502)}};Ib.get("/.well-known/oauth-protected-resource/mcp/:connectionId",(X)=>iG1(X));Ib.get("/mcp/:connectionId/.well-known/oauth-protected-resource",(X)=>iG1(X));async function eX0(X){let Q=new URL(X).pathname;if(Q.endsWith("/"))Q=Q.slice(0,-1);let J=Q!==""&&Q!=="/",G=[];if(J){let Z=new URL(X);Z.pathname=`/.well-known/oauth-authorization-server${Q}`,G.push(Z);let $=new URL(X);$.pathname=`/.well-known/openid-configuration${Q}`,G.push($);let K=new URL(X);K.pathname=`${Q}/.well-known/openid-configuration`,G.push(K)}else{let Z=new URL(X);Z.pathname="/.well-known/oauth-authorization-server",G.push(Z);let $=new URL(X);$.pathname="/.well-known/openid-configuration",G.push($)}let W=null;for(let Z of G){if(W=await fetch(Z.toString(),{method:"GET",headers:{Accept:"application/json"}}),W.ok)return W;if(W.status!==404&&W.status!==401)return W}return W}Ib.get("/.well-known/oauth-authorization-server/oauth-proxy/:connectionId",async(X)=>{let Y=X.req.param("connectionId"),Q=await cG1(X),J=await Kh6(Y,Q);if(!J)return X.json({error:"Connection not found or no auth server"},404);try{let G=await eX0(J);if(!G.ok)return new Response(G.body,{status:G.status,statusText:G.statusText,headers:{"Content-Type":"application/json"}});let W=await G.json(),$=`${Sb(new URL(X.req.url)).origin}/oauth-proxy/${Y}`,K={...W,authorization_endpoint:W.authorization_endpoint?`${$}/authorize`:void 0,token_endpoint:W.token_endpoint?`${$}/token`:void 0,registration_endpoint:W.registration_endpoint?`${$}/register`:void 0};return new Response(JSON.stringify(K),{status:200,headers:{"Content-Type":"application/json"}})}catch(G){let W=G;return console.error("[oauth-proxy] Failed to proxy auth server metadata:",W),X.json({error:"Failed to proxy auth server metadata",message:W.message},502)}});var aG1=Ib;function Hh6(X){if(!X.isError)return;let Y=X.content;if(!Array.isArray(Y))return;for(let Q of Y)if(Q&&typeof Q==="object"&&"type"in Q&&Q.type==="text"&&"text"in Q&&typeof Q.text==="string")return Q.text;return}function Fh6(X){if(!X)return;let Y=X._meta;if(!Y||typeof Y!=="object"||Array.isArray(Y))return;let Q=Y.properties;if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let J={};for(let[G,W]of Object.entries(Q))if(typeof W==="string")J[G]=W;return Object.keys(J).length>0?J:void 0}function Vh6(X,Y){if(!X&&!Y)return;if(!X)return Y;if(!Y)return X;return{...Y,...X}}function rG1(X){if(X&&typeof X==="object"&&!Array.isArray(X)){let Y=X,Q=Y.structuredContent;if(Q&&typeof Q==="object"&&!Array.isArray(Q))return Q;return Y}return{value:X}}async function qh6(X,Y){let Q=X.body;if(!Q)return{text:"",truncated:!1};let J=Q.getReader(),G=new TextDecoder,W=!1,Z=0,$=[];try{while(!0){let{value:K,done:H}=await J.read();if(H)break;if(K){if(Z+=K.byteLength,Z>Y){W=!0;let F=Y-(Z-K.byteLength);if(F>0)$.push(G.decode(K.slice(0,F),{stream:!0}));break}$.push(G.decode(K,{stream:!0}))}}}finally{J.releaseLock()}return $.push(G.decode()),{text:$.join(""),truncated:W}}async function rP(X){let{ctx:Y,enabled:Q}=X,J=X.organizationId??Y.organization?.id;if(!Q||!J)return;let G=Fh6(X.request.params.arguments),W=Vh6(Y.metadata.properties,G);await Y.storage.monitoring.log({organizationId:J,connectionId:X.connectionId,connectionTitle:X.connectionTitle,toolName:X.request.params.name,input:X.request.params.arguments??{},output:X.output,isError:X.isError,errorMessage:X.errorMessage,durationMs:X.durationMs,timestamp:new Date,userId:Y.auth.user?.id||Y.auth.apiKey?.userId||null,requestId:Y.metadata.requestId,userAgent:Y.metadata.userAgent,virtualMcpId:X.virtualMcpId,properties:W})}function oG1(X){let{ctx:Y,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:W}=X;return async(Z,$)=>{let K=Date.now();try{let H=await $(),F=Date.now()-K;return await rP({ctx:Y,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:W,request:Z,output:rG1(H),isError:Boolean(H.isError),errorMessage:Hh6(H),durationMs:F}),H}catch(H){let F=H,V=Date.now()-K;throw await rP({ctx:Y,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:W,request:Z,output:{},isError:!0,errorMessage:F.message,durationMs:V}),H}}}function sG1(X){let{ctx:Y,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:W}=X;return async(Z,$)=>{let K=Date.now();try{let H=await $(),F=Y.organization?.id;if(Q&&F){let V=H.clone();(async()=>{try{let{text:q,truncated:z}=await qh6(V,262144),D=Date.now()-K,N=V.headers.get("content-type")??"",L=q;if(N.includes("application/json"))try{L=q.length?JSON.parse(q):null}catch{L=q}let w=H.status>=400,C=w&&L&&typeof L==="object"&&"error"in L?L.error:void 0,T=typeof C==="string"&&C?C:w&&typeof L==="string"&&L.trim()?L.slice(0,500):w?`HTTP ${H.status} ${H.statusText}`.trim():z?"Response body truncated to 262144 bytes":void 0;await rP({ctx:Y,enabled:Q,organizationId:F,connectionId:J,connectionTitle:G,virtualMcpId:W,request:Z,output:rG1(L),isError:w,errorMessage:T,durationMs:D})}catch(q){let z=Date.now()-K;await rP({ctx:Y,enabled:Q,organizationId:F,connectionId:J,connectionTitle:G,virtualMcpId:W,request:Z,output:{},isError:!0,errorMessage:`Failed to read streamable response body: ${q.message}`,durationMs:z})}})()}return H}catch(H){let F=H,V=Date.now()-K;throw await rP({ctx:Y,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:W,request:Z,output:{},isError:!0,errorMessage:F.message,durationMs:V}),H}}}var kb=new p8,XY0=300000;function Uh6(X,Y,Q){return async(J,G)=>{try{let W=J.params.name,Z=async()=>{let{tools:K}=await Q();return K.find((F)=>F.name===W)?._meta};return await new UK(X.authInstance,X.auth.user?.id??X.auth.apiKey?.userId,W,X.boundAuth,X.auth.user?.role,Y,Z).check(W),await G()}catch(W){return{content:[{type:"text",text:`Authorization failed: ${W.message}`}],isError:!0}}}}function zh6(X,Y,Q){return async(J,G)=>{try{let W=J.params.name,Z=async()=>{let{tools:K}=await Q();return K.find((F)=>F.name===W)?._meta};return await new UK(X.authInstance,X.auth.user?.id??X.auth.apiKey?.userId,W,X.boundAuth,X.auth.user?.role,Y,Z).check(W),await G()}catch(W){return new Response(JSON.stringify({error:`Authorization failed: ${W.message}`}),{status:403,headers:{"Content-Type":"application/json"}})}}}async function tG1(X,Y,{superUser:Q}){let J=typeof X==="string"?await Y.storage.connections.findById(X,Y.organization?.id):X;if(!J)throw Error("Connection not found");let G=J?.id;if(Y.organization&&J.organization_id!==Y.organization.id)throw Error("Connection does not belong to the active organization");if(Y.organization??={id:J.organization_id},J.status!=="active")throw Error(`Connection inactive: ${J.status}`);let W,Z=Y.auth.user?.connectionId,$=EG1(async()=>{let S=t80(J.configuration_state,J.configuration_scopes),f=Y.auth.user?.id??Y.auth.apiKey?.userId;if(!f){console.error("User ID required to issue configuration token");return}try{W=await MG1({sub:f,user:{id:f},metadata:{state:J.configuration_state??void 0,meshUrl:process.env.MESH_URL??Y.baseUrl,connectionId:G,organizationId:Y.organization?.id},permissions:S})}catch(t){console.error("Failed to issue configuration token:",t)}}),K=async()=>{await $();let S={...Z?{"x-caller-id":Z}:{},...Y.metadata.wellKnownForwardableHeaders??{},"x-request-id":Y.metadata.requestId},f=null,t=new rW(Y.db,Y.vault),m=await t.get(G);if(m){let J0=!!m.refreshToken&&!!m.tokenEndpoint;if(t.isExpired(m,J0?300000:0))if(J0){console.log(`[Proxy] Token expired for ${G}, attempting refresh`);let Y0=await xG1(m);if(Y0.success&&Y0.accessToken)await t.upsert({connectionId:G,accessToken:Y0.accessToken,refreshToken:Y0.refreshToken??m.refreshToken,scope:Y0.scope??m.scope,expiresAt:Y0.expiresIn?new Date(Date.now()+Y0.expiresIn*1000):null,clientId:m.clientId,clientSecret:m.clientSecret,tokenEndpoint:m.tokenEndpoint}),f=Y0.accessToken,console.log(`[Proxy] Token refreshed for ${G}`);else await t.delete(G),console.error(`[Proxy] Token refresh failed for ${G}: ${Y0.error}`)}else await t.delete(G),console.log(`[Proxy] Token expired without refresh capability for ${G}`);else f=m.accessToken}if(!f&&J.connection_token)f=J.connection_token;if(f)S.Authorization=`Bearer ${f}`;if(W)S["x-mesh-token"]=W;return S},H=J.connection_type==="STDIO",F=KF(J.connection_headers)?J.connection_headers:null,V=!H?J.connection_headers:null,q=async()=>{let S=new l9({name:"mcp-mesh-proxy",version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});switch(J.connection_type){case"STDIO":{if(process.env.UNSAFE_ALLOW_STDIO_TRANSPORT!=="true")throw Error("STDIO connections are disabled in production. Set UNSAFE_ALLOW_STDIO_TRANSPORT=true to enable.");if(!F)throw Error("STDIO connection missing parameters");return mG1({id:G,name:J.title,command:F.command,args:F.args,env:F.envVars,cwd:F.cwd},S)}case"HTTP":case"Websocket":{if(!J.connection_url)throw Error(`${J.connection_type} connection missing URL`);let f=await K();if(V?.headers)Object.assign(f,V.headers);let t=new IG(new URL(J.connection_url),{requestInit:{headers:f}});return await S.connect(t),S}case"SSE":{if(!J.connection_url)throw Error("SSE connection missing URL");let f=await K();if(V?.headers)Object.assign(f,V.headers);let t=new VF(new URL(J.connection_url),{requestInit:{headers:f}});return await S.connect(t),S}case"VIRTUAL":{let f=$K(J.connection_url);if(!f)throw Error("VIRTUAL connection missing virtual MCP ID in connection_url");let t=await Y.storage.virtualMcps.findById(f);if(!t)throw Error(`Virtual MCP not found: ${f}`);let m=await aP(t,Y,"passthrough");return{callTool:(J0)=>m.client.callTool(J0),listTools:()=>m.client.listTools(),listResources:()=>m.client.listResources(),readResource:(J0)=>m.client.readResource(J0),listResourceTemplates:()=>m.client.listResourceTemplates(),listPrompts:()=>m.client.listPrompts(),getPrompt:(J0)=>m.client.getPrompt(J0),close:async()=>{},getServerCapabilities:()=>({tools:{},resources:{},prompts:{}}),getInstructions:()=>t.metadata?.instructions??void 0}}default:throw Error(`Unknown connection type: ${J.connection_type}`)}},z=async()=>{if(J.tools&&J.tools.length>0)return{tools:J.tools.map((f)=>({name:f.name,description:f.description,inputSchema:f.inputSchema,outputSchema:f.outputSchema,annotations:f.annotations,_meta:f._meta}))};let S;try{return S=await q(),await S.listTools()}finally{S?.close().catch(console.error)}},D=Q?async(S,f)=>await f():Uh6(Y,G,z),N=Q?async(S,f)=>await f():zh6(Y,G,z),L=Y.connectionId&&Y.connectionId!==G?Y.connectionId:void 0,w={enabled:A81().enabled,connectionId:G,connectionTitle:J.title,virtualMcpId:L,ctx:Y},C=oG1(w),T=sG1(w),A=PP(C,D),P=PP(T,N),j=async(S)=>{return A(S,async()=>{let f=await q(),t=Date.now(),m={...S.params};if(m.arguments&&"_meta"in m.arguments){let{_meta:J0,...V0}=m.arguments;m.arguments=V0}return await Y.tracer.startActiveSpan("mcp.proxy.callTool",{attributes:{"connection.id":G,"tool.name":S.params.name,"request.id":Y.metadata.requestId}},async(J0)=>{try{let V0=await f.callTool(m,void 0,{timeout:XY0}),Y0=Date.now()-t;return Y.meter.createHistogram("connection.proxy.duration").record(Y0,{"connection.id":G,"tool.name":S.params.name,status:"success"}),Y.meter.createCounter("connection.proxy.requests").add(1,{"connection.id":G,"tool.name":S.params.name,status:"success"}),J0.end(),V0}catch(V0){let Y0=V0,U0=Date.now()-t;throw Y.meter.createHistogram("connection.proxy.duration").record(U0,{"connection.id":G,"tool.name":S.params.name,status:"error"}),Y.meter.createCounter("connection.proxy.errors").add(1,{"connection.id":G,"tool.name":S.params.name,error:Y0.message}),J0.recordException(Y0),J0.end(),V0}finally{f.close().catch(console.error)}})})};return{fetch:async(S)=>{let f=new URL(S.url),t;try{t=await q()}catch(P0){let v0=J.connection_url?await nG1({error:P0,reqUrl:f,connectionId:G,connectionUrl:J.connection_url,headers:await K()}):null;if(v0)return v0;throw P0}let m=t.getServerCapabilities(),J0=t.getInstructions(),V0=m??{tools:{},resources:{},prompts:{}},Y0=new qF({name:"mcp-mesh",version:"1.0.0"},{capabilities:V0,instructions:J0}),U0=new UF({enableJsonResponse:S.headers.get("Accept")?.includes("application/json")??!1});if(await Y0.connect(U0),Y0.server.setRequestHandler(eZ,()=>t.listTools()),Y0.server.setRequestHandler(TG,j),V0.resources)Y0.server.setRequestHandler(aZ,()=>t.listResources()),Y0.server.setRequestHandler(oZ,(P0)=>t.readResource(P0.params)),Y0.server.setRequestHandler(rZ,()=>t.listResourceTemplates());if(V0.prompts)Y0.server.setRequestHandler(sZ,()=>t.listPrompts()),Y0.server.setRequestHandler(tZ,(P0)=>t.getPrompt(P0.params));try{return await U0.handleRequest(S)}finally{try{await t.close()}catch{}try{await U0.close?.()}catch{}}},client:{callTool:(S)=>{return j({method:"tools/call",params:S})},listTools:z,listResources:async()=>{let S;try{return S=await q(),await S.listResources()}catch(f){if(f instanceof Q1&&f.code===$1.MethodNotFound)return{resources:[]};throw f}finally{S?.close().catch(console.error)}},readResource:async(S)=>{let f;try{return f=await q(),await f.readResource(S)}finally{f?.close().catch(console.error)}},listResourceTemplates:async()=>{let S;try{return S=await q(),await S.listResourceTemplates()}catch(f){if(f instanceof Q1&&f.code===$1.MethodNotFound)return{resourceTemplates:[]};throw f}finally{S?.close().catch(console.error)}},listPrompts:async()=>{let S;try{return S=await q(),await S.listPrompts()}catch(f){if(f instanceof Q1&&f.code===$1.MethodNotFound)return{prompts:[]};throw f}finally{S?.close().catch(console.error)}},getPrompt:async(S)=>{let f;try{return f=await q(),await f.getPrompt(S)}finally{f?.close().catch(console.error)}}},callStreamableTool:async(S,f)=>{if(J.connection_type==="VIRTUAL"){let J0=await j({method:"tools/call",params:{name:S,arguments:f}});return new Response(JSON.stringify(J0),{headers:{"Content-Type":"application/json"}})}if(!J.connection_url)throw Error("Streamable tools require HTTP connection with URL");let t=J.connection_url,m={method:"tools/call",params:{name:S,arguments:f}};return P(m,async()=>{let J0=await K();if(V?.headers)Object.assign(J0,V.headers);let V0=new URL(t);return V0.pathname=V0.pathname.replace(/\/$/,"")+`/call-tool/${m.params.name}`,await Y.tracer.startActiveSpan("mcp.proxy.callStreamableTool",{attributes:{"connection.id":G,"tool.name":m.params.name,"request.id":Y.metadata.requestId}},async(Y0)=>{let U0=Date.now();try{let P0=await fetch(V0.toString(),{method:"POST",redirect:"manual",body:JSON.stringify(m.params.arguments),headers:{...J0,"Content-Type":"application/json"}}),v0=Date.now()-U0;return Y.meter.createHistogram("connection.proxy.streamable.duration").record(v0,{"connection.id":G,"tool.name":m.params.name,status:P0.ok?"success":"error"}),Y.meter.createCounter("connection.proxy.streamable.requests").add(1,{"connection.id":G,"tool.name":m.params.name,status:P0.ok?"success":"error"}),Y0.end(),P0}catch(P0){let v0=P0,G1=Date.now()-U0;throw Y.meter.createHistogram("connection.proxy.streamable.duration").record(G1,{"connection.id":G,"tool.name":m.params.name,status:"error"}),Y.meter.createCounter("connection.proxy.streamable.errors").add(1,{"connection.id":G,"tool.name":m.params.name,error:v0.message}),Y0.recordException(v0),Y0.end(),P0}})})}}}async function eG1(X,Y){return tG1(X,Y,{superUser:!1})}async function X71(X,Y){return tG1(X,Y,{superUser:!0})}kb.all("/",async(X)=>{return Cb(X,void 0)});kb.all("/:connectionId",async(X)=>{let Y=X.req.param("connectionId"),Q=X.get("meshContext");try{return await(await Q.createMCPProxy(Y)).fetch(X.req.raw)}catch(J){return Y71(J,X)}});var Y71=(X,Y)=>{if(X.message.includes("not found"))return Y.json({error:X.message},404);if(X.message.includes("does not belong to the active organization"))return Y.json({error:"Connection not found"},404);if(X.message.includes("inactive"))return Y.json({error:X.message},503);return Y.json({error:"Internal server error",message:X.message},500)};kb.all("/:connectionId/call-tool/:toolName",async(X)=>{let Y=X.req.param("connectionId"),Q=X.req.param("toolName"),J=X.get("meshContext");try{let W=await(await J.createMCPProxy(Y)).client.callTool({name:Q,arguments:await X.req.json()});if(W instanceof Response)return W;if(W.isError)return new Response(JSON.stringify(W.content),{headers:{"Content-Type":"application/json"},status:500});return new Response(JSON.stringify(W.structuredContent??W.content),{headers:{"Content-Type":"application/json"}})}catch(G){return Y71(G,X)}});var Q71=kb;cW();class YY0{db;constructor(X){this.db=X}async create(X){let Y=X.id??t8("thrd"),Q=new Date().toISOString();if(!X.organizationId)throw Error("organizationId is required");if(!X.createdBy)throw Error("createdBy is required");if(!X.title)X.title="New Thread - "+Q;let J={id:Y,organization_id:X.organizationId,title:X.title,description:X.description??null,created_at:Q,updated_at:Q,created_by:X.createdBy,updated_by:X.updatedBy??null},G=await this.db.insertInto("threads").values(J).returningAll().executeTakeFirstOrThrow();return this.threadFromDbRow(G)}async get(X){let Y=await this.db.selectFrom("threads").selectAll().where("id","=",X).executeTakeFirst();return Y?this.threadFromDbRow(Y):null}async update(X,Y){let J={updated_at:new Date().toISOString()};if(Y.title!==void 0)J.title=Y.title;if(Y.description!==void 0)J.description=Y.description;if(Y.updatedBy!==void 0)J.updated_by=Y.updatedBy;if(Y.hidden!==void 0)J.hidden=Y.hidden;await this.db.updateTable("threads").set(J).where("id","=",X).execute();let G=await this.get(X);if(!G)throw Error("Thread not found after update");return G}async delete(X){await this.db.deleteFrom("threads").where("id","=",X).execute()}async list(X,Y,Q){let J=this.db.selectFrom("threads").selectAll().where("organization_id","=",X).where("hidden","=",!1).orderBy("updated_at","desc");if(Y)J=J.where("created_by","=",Y);let G=this.db.selectFrom("threads").select(($)=>$.fn.count("id").as("count")).where("organization_id","=",X).where("hidden","=",!1);if(Y)G=G.where("created_by","=",Y);if(Q?.limit)J=J.limit(Q.limit);if(Q?.offset)J=J.offset(Q.offset);let[W,Z]=await Promise.all([J.execute(),G.executeTakeFirst()]);return{threads:W.map(($)=>this.threadFromDbRow($)),total:Number(Z?.count||0)}}async saveMessages(X){let Y=new Date().toISOString(),Q=X[0]?.threadId;if(!Q)throw Error("threadId is required when creating multiple messages");let J=X.find((W)=>W.threadId!==Q);if(J)throw Error(`All messages must target the same thread. Expected threadId "${Q}", but message "${J.id}" has threadId "${J.threadId}"`);let G=X.map((W)=>({id:W.id,thread_id:Q,metadata:W.metadata?JSON.stringify(W.metadata):null,parts:JSON.stringify(W.parts),role:W.role,created_at:W.createdAt??Y,updated_at:Y}));await this.db.transaction().execute(async(W)=>{await W.insertInto("thread_messages").values(G).execute(),await W.updateTable("threads").set({updated_at:Y}).where("id","=",Q).execute()})}async listMessages(X,Y){let Q=this.db.selectFrom("thread_messages").selectAll().where("thread_id","=",X).orderBy("created_at","asc").orderBy("id","asc"),J=this.db.selectFrom("thread_messages").select((Z)=>Z.fn.count("id").as("count")).where("thread_id","=",X);if(Y?.limit)Q=Q.limit(Y.limit);if(Y?.offset)Q=Q.offset(Y.offset);let[G,W]=await Promise.all([Q.execute(),J.executeTakeFirst()]);return{messages:G.map((Z)=>this.messageFromDbRow(Z)),total:Number(W?.count||0)}}threadFromDbRow(X){return{id:X.id,organizationId:X.organization_id,title:X.title,description:X.description,createdAt:typeof X.created_at==="string"?X.created_at:X.created_at.toISOString(),updatedAt:typeof X.updated_at==="string"?X.updated_at:X.updated_at.toISOString(),createdBy:X.created_by,updatedBy:X.updated_by,hidden:X.hidden}}messageFromDbRow(X){let Y,Q;try{Y=X.metadata?JSON.parse(X.metadata):void 0}catch(J){console.error(`Failed to parse metadata for message ${X.id}:`,X.metadata,J),Y=void 0}try{Q=typeof X.parts==="string"?JSON.parse(X.parts):X.parts}catch(J){console.error(`Failed to parse parts for message ${X.id}:`,X.parts,J),Q=[]}return{id:X.id,threadId:X.thread_id,metadata:Y,parts:Q,role:X.role,createdAt:typeof X.created_at==="string"?X.created_at:X.created_at.toISOString(),updatedAt:typeof X.updated_at==="string"?X.updated_at:X.updated_at.toISOString()}}}function Bh6(X){if(!X)return;try{let Y=JSON.parse(X);if(typeof Y!=="object"||Y===null||Array.isArray(Y))return;let Q={};for(let[J,G]of Object.entries(Y))if(typeof G==="string")Q[J]=G;return Object.keys(Q).length>0?Q:void 0}catch{return}}function Dh6(X,Y){for(let[Q,J]of Object.entries(Y)){let G=X[Q];if(!G||G.length===0){let W=X["*"];if(!W||W.length===0)return!1;if(W.includes("*"))continue;for(let Z of J)if(!W.includes(Z))return!1;continue}if(G.includes("*"))continue;for(let W of J)if(!G.includes(W))return!1}return!0}function Nh6(X){let{auth:Y,headers:Q,role:J,permissions:G,userId:W}=X,Z=Y.api.hasPermission;return{hasPermission:async($)=>{if(J&&uX0.includes(J))return!0;if(G)return Dh6(G,$);if(!Z)return console.error("[Auth] hasPermission API not available"),!1;try{if((await Z({headers:Q,body:{permission:$}}))?.success===!0)return!0;let H={};for(let V of Object.keys($))H[V]=["*"];return(await Z({headers:Q,body:{permission:H}}))?.success===!0}catch(K){return console.error("[Auth] Permission check failed:",K),!1}},organization:{create:async($)=>{return Y.api.createOrganization({headers:Q,body:$})},update:async($)=>{return Y.api.updateOrganization({headers:Q,body:$})},delete:async($)=>{await Y.api.deleteOrganization({headers:Q,body:{organizationId:$}})},get:async($)=>{return Y.api.getFullOrganization({headers:Q,query:$?{organizationId:$}:void 0})},list:async($)=>{return Y.api.listOrganizations({headers:Q,query:$?{userId:$}:void 0})},addMember:async($)=>{return Y.api.addMember({headers:Q,body:$})},removeMember:async($)=>{await Y.api.removeMember({headers:Q,body:$})},listMembers:async($)=>{return Y.api.listMembers({headers:Q,query:$?{organizationId:$.organizationId,limit:$.limit,offset:$.offset}:void 0})},updateMemberRole:async($)=>{return Y.api.updateMemberRole({headers:Q,body:$})}},apiKey:{create:async($)=>{return Y.api.createApiKey({body:{...$,userId:W}})},list:async()=>{return Y.api.listApiKeys({headers:Q})},update:async($)=>{return Y.api.updateApiKey({body:{...$,userId:W}})},delete:async($)=>{await Y.api.deleteApiKey({headers:Q,body:{keyId:$}})}}}}async function Oh6(X,Y,Q){if(uX0.includes(Q))return;let J=await X.selectFrom("organizationRole").select(["permission"]).where("organizationId","=",Y).where("role","=",Q).executeTakeFirst();if(!J?.permission)return;try{return JSON.parse(J.permission)}catch{console.error(`[Auth] Failed to parse permissions for role: ${Q}`);return}}async function Lh6(X,Y,Q,J=G71){let G=X.headers.get("Authorization");try{let W=new Headers(X.headers);W.set("X-MCP-Session-Auth","true");let Z=await J.measure("auth_get_mcp_session",()=>Y.api.getMcpSession({headers:W}));if(Z){let $=Z.userId,K=await J.measure("auth_query_membership",()=>Q.selectFrom("member").innerJoin("organization","organization.id","member.organizationId").select(["member.role","member.organizationId","organization.id as orgId","organization.slug as orgSlug","organization.name as orgName"]).where("member.userId","=",$).executeTakeFirst()),H=K?.role,F=K?{id:K.orgId,slug:K.orgSlug,name:K.orgName}:void 0,V;if(K&&H)V=await J.measure("auth_fetch_role_permissions",()=>Oh6(Q,K.organizationId,H));return{user:{id:$,role:H},role:H,permissions:V,organization:F}}}catch(W){console.error("[Auth] OAuth session check failed:",W)}if(G?.startsWith("Bearer ")){let W=G.replace("Bearer ","").trim();try{let Z=await J.measure("auth_verify_mesh_jwt",()=>PG1(W));if(Z){let $,K=Z.metadata?.organizationId;if(Z.sub&&K)$=(await J.measure("auth_query_membership",()=>Q.selectFrom("member").select(["member.role"]).where("member.userId","=",Z.sub).where("member.organizationId","=",K).executeTakeFirst()))?.role;return{user:{id:Z.sub,connectionId:Z.metadata?.connectionId,role:$},role:$,permissions:Z.permissions,organization:Z.metadata?.organizationId?{id:Z.metadata?.organizationId}:void 0}}}catch{}try{let Z=await J.measure("auth_verify_api_key",()=>Y.api.verifyApiKey({body:{key:W}}));if(Z?.valid&&Z.key){let $=Z.key.metadata?.organization,K=Z.key.permissions,H,F=Z.key.userId;if(F&&$?.id)H=(await J.measure("auth_query_membership",()=>Q.selectFrom("member").select(["member.role"]).where("member.userId","=",F).where("member.organizationId","=",$.id).executeTakeFirst()))?.role;return{apiKeyId:Z.key.id,user:{id:Z.key.userId,role:H},role:H,permissions:K,organization:$?{id:$.id,slug:$.slug,name:$.name}:void 0}}}catch(Z){console.error("[Auth] API key check failed:",Z)}}try{let W=await J.measure("auth_get_session",()=>Y.api.getSession({headers:X.headers}));if(W){let Z,$;if(W.session.activeOrganizationId){let K=await J.measure("auth_get_full_organization",()=>Y.api.getFullOrganization({headers:X.headers}).catch(()=>null));if(K)Z={id:K.id,slug:K.slug,name:K.name},$=K.members?.find((F)=>F.userId===W.user.id)?.role;else Z={id:W.session.activeOrganizationId,slug:"",name:""}}return{user:{id:W.user.id,email:W.user.email,role:$},role:$,organization:Z}}}catch(W){let Z=W;console.error("[Auth] Session check failed:",JSON.stringify({message:Z.message,body:Z.body,stack:Z.stack},null,2))}return{user:void 0}}var J71,zK={set:(X)=>{J71=X},create:async(X,Y)=>{return await J71(X,Y)}},G71={measure:async(X,Y)=>{return await Y()}},wh6=["x-hub-signature-256"];function W71(X){let Y=new zP(X.encryption.key),Q={connections:new BP(X.db,Y),organizationSettings:new pX0(X.db),monitoring:new dX0(X.db,X.databaseType),virtualMcps:new mX0(X.db),users:new cX0(X.db),threads:new YY0(X.db)};return async(J,G)=>{let W=G?.timings??G71,Z=J?.headers.get("x-caller-id")??void 0,$=J?await Lh6(J,X.auth,X.db,W):{user:void 0},K=Nh6({auth:X.auth,headers:J?.headers??new Headers,role:$.role,permissions:$.permissions,userId:$.user?.id}),H={user:$.user};if($.apiKeyId)H.apiKey={id:$.apiKeyId,name:"",userId:""};let F=$.organization,V=J?new URL(J.url):new URL("http://localhost:3000"),q=process.env.BASE_URL??`${V.protocol}//${V.host}`,z=new UK(X.auth,H.user?.id,void 0,K,$.role,"self"),D={timings:W,auth:H,connectionId:Z,organization:F,storage:Q,vault:Y,authInstance:X.auth,boundAuth:K,access:z,db:X.db,tracer:X.observability.tracer,meter:X.observability.meter,baseUrl:q,metadata:{requestId:crypto.randomUUID(),timestamp:new Date,wellKnownForwardableHeaders:Object.fromEntries(wh6.map((N)=>[N,J?.headers.get(N)??null]).filter(([N,L])=>L!==null)),userAgent:J?.headers.get("x-mesh-client")||J?.headers.get("User-Agent")||void 0,ipAddress:(J?.headers.get("CF-Connecting-IP")||J?.headers.get("X-Forwarded-For"))??void 0,properties:Bh6(J?.headers.get("x-mesh-properties"))},eventBus:X.eventBus,createMCPProxy:async(N)=>{return await eG1(N,D)}};return D}}class Z71{db;constructor(X){this.db=X}async publishEvent(X){let Y=new Date().toISOString();return await this.db.insertInto("events").values({id:X.id,organization_id:X.organizationId,type:X.type,source:X.source,specversion:"1.0",subject:X.subject??null,time:X.time,datacontenttype:X.datacontenttype??"application/json",dataschema:X.dataschema??null,data:X.data?JSON.stringify(X.data):null,cron:X.cron??null,status:"pending",attempts:0,last_error:null,next_retry_at:null,created_at:Y,updated_at:Y}).execute(),{id:X.id,organizationId:X.organizationId,type:X.type,source:X.source,specversion:"1.0",subject:X.subject??null,time:X.time,datacontenttype:X.datacontenttype??"application/json",dataschema:X.dataschema??null,data:X.data??null,cron:X.cron??null,status:"pending",attempts:0,lastError:null,nextRetryAt:null,createdAt:Y,updatedAt:Y}}async subscribe(X){let Y=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",X.organizationId).where("connection_id","=",X.connectionId).where("event_type","=",X.eventType);if(X.publisher)Y=Y.where("publisher","=",X.publisher);else Y=Y.where("publisher","is",null);if(X.filter)Y=Y.where("filter","=",X.filter);else Y=Y.where("filter","is",null);let Q=await Y.executeTakeFirst();if(Q)return{id:Q.id,organizationId:Q.organization_id,connectionId:Q.connection_id,publisher:Q.publisher,eventType:Q.event_type,filter:Q.filter,enabled:Q.enabled===1,createdAt:Q.created_at,updatedAt:Q.updated_at};let J=new Date().toISOString();return await this.db.insertInto("event_subscriptions").values({id:X.id,organization_id:X.organizationId,connection_id:X.connectionId,publisher:X.publisher??null,event_type:X.eventType,filter:X.filter??null,enabled:1,created_at:J,updated_at:J}).execute(),{id:X.id,organizationId:X.organizationId,connectionId:X.connectionId,publisher:X.publisher??null,eventType:X.eventType,filter:X.filter??null,enabled:!0,createdAt:J,updatedAt:J}}async unsubscribe(X,Y){return{success:((await this.db.deleteFrom("event_subscriptions").where("id","=",X).where("organization_id","=",Y).executeTakeFirst()).numDeletedRows??0n)>0n}}async listSubscriptions(X,Y){let Q=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",X);if(Y)Q=Q.where("connection_id","=",Y);return(await Q.execute()).map((G)=>({id:G.id,organizationId:G.organization_id,connectionId:G.connection_id,publisher:G.publisher,eventType:G.event_type,filter:G.filter,enabled:G.enabled===1,createdAt:G.created_at,updatedAt:G.updated_at}))}async getSubscription(X,Y){let Q=await this.db.selectFrom("event_subscriptions").selectAll().where("id","=",X).where("organization_id","=",Y).executeTakeFirst();if(!Q)return null;return{id:Q.id,organizationId:Q.organization_id,connectionId:Q.connection_id,publisher:Q.publisher,eventType:Q.event_type,filter:Q.filter,enabled:Q.enabled===1,createdAt:Q.created_at,updatedAt:Q.updated_at}}async getMatchingSubscriptions(X){return(await this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",X.organizationId).where("enabled","=",1).where("event_type","=",X.type).where((Q)=>Q.or([Q("publisher","is",null),Q("publisher","=",X.source)])).execute()).map((Q)=>({id:Q.id,organizationId:Q.organization_id,connectionId:Q.connection_id,publisher:Q.publisher,eventType:Q.event_type,filter:Q.filter,enabled:Q.enabled===1,createdAt:Q.created_at,updatedAt:Q.updated_at}))}async createDeliveries(X,Y,Q){if(Y.length===0)return;let J=new Date().toISOString(),G=Q??null,W=Y.map((Z)=>({id:crypto.randomUUID(),event_id:X,subscription_id:Z,status:"pending",attempts:0,last_error:null,delivered_at:null,next_retry_at:G,created_at:J}));await this.db.insertInto("event_deliveries").values(W).execute()}async claimPendingDeliveries(X){let Y=new Date().toISOString(),Q;try{Q=(await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",(W)=>W.selectFrom("event_deliveries as d").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select("d.id").where("d.status","=","pending").where("s.enabled","=",1).where((Z)=>Z.or([Z("d.next_retry_at","is",null),Z("d.next_retry_at","<=",Y)])).orderBy("d.created_at","asc").limit(X)).where("status","=","pending").returning(["id"]).execute()).map((W)=>W.id)}catch{let G=await this.db.selectFrom("event_deliveries as d").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select(["d.id"]).where("d.status","=","pending").where("s.enabled","=",1).where((W)=>W.or([W("d.next_retry_at","is",null),W("d.next_retry_at","<=",Y)])).orderBy("d.created_at","asc").limit(X).execute();if(G.length===0)return[];Q=G.map((W)=>W.id),await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",Q).where("status","=","pending").execute()}if(Q.length===0)return[];return(await this.db.selectFrom("event_deliveries as d").innerJoin("events as e","e.id","d.event_id").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select(["d.id as delivery_id","d.event_id","d.subscription_id","d.status as delivery_status","d.attempts as delivery_attempts","d.last_error as delivery_last_error","d.delivered_at","d.next_retry_at as delivery_next_retry_at","d.created_at as delivery_created_at","e.organization_id","e.type","e.source","e.specversion","e.subject","e.time","e.datacontenttype","e.dataschema","e.data","e.cron","e.status as event_status","e.attempts as event_attempts","e.last_error as event_last_error","e.next_retry_at","e.created_at as event_created_at","e.updated_at as event_updated_at","s.connection_id","s.publisher","s.event_type","s.filter","s.enabled","s.created_at as subscription_created_at","s.updated_at as subscription_updated_at"]).where("d.id","in",Q).where("d.status","=","processing").execute()).map((G)=>({delivery:{id:G.delivery_id,eventId:G.event_id,subscriptionId:G.subscription_id,status:G.delivery_status,attempts:G.delivery_attempts,lastError:G.delivery_last_error,deliveredAt:G.delivered_at,nextRetryAt:G.delivery_next_retry_at,createdAt:G.delivery_created_at},event:{id:G.event_id,organizationId:G.organization_id,type:G.type,source:G.source,specversion:G.specversion,subject:G.subject,time:G.time,datacontenttype:G.datacontenttype,dataschema:G.dataschema,data:G.data?JSON.parse(G.data):null,cron:G.cron,status:G.event_status,attempts:G.event_attempts,lastError:G.event_last_error,nextRetryAt:G.next_retry_at,createdAt:G.event_created_at,updatedAt:G.event_updated_at},subscription:{id:G.subscription_id,organizationId:G.organization_id,connectionId:G.connection_id,publisher:G.publisher,eventType:G.event_type,filter:G.filter,enabled:G.enabled===1,createdAt:G.subscription_created_at,updatedAt:G.subscription_updated_at}}))}async markDeliveriesDelivered(X){if(X.length===0)return;let Y=new Date().toISOString();await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:Y}).where("id","in",X).execute()}async markDeliveriesFailed(X,Y,Q=20,J=1000,G=3600000){if(X.length===0)return;for(let W of X){let Z=await this.db.selectFrom("event_deliveries").select(["attempts"]).where("id","=",W).executeTakeFirst();if(!Z)continue;let $=Z.attempts+1;if($>=Q)await this.db.updateTable("event_deliveries").set({attempts:$,last_error:Y,status:"failed",next_retry_at:null}).where("id","=",W).execute();else{let K=Math.min(J*Math.pow(2,$-1),G),H=new Date(Date.now()+K).toISOString();await this.db.updateTable("event_deliveries").set({attempts:$,last_error:Y,status:"pending",next_retry_at:H}).where("id","=",W).execute()}}}async updateEventStatus(X){let Y=await this.db.selectFrom("event_deliveries").select(["status"]).where("event_id","=",X).execute();if(Y.length===0)return;let Q=Y.every((W)=>W.status==="delivered"),J=Y.some((W)=>W.status==="failed"),G=Y.some((W)=>W.status==="pending"||W.status==="processing");if(Q)await this.db.updateTable("events").set({status:"delivered",updated_at:new Date().toISOString()}).where("id","=",X).execute();else if(J&&!G)await this.db.updateTable("events").set({status:"failed",updated_at:new Date().toISOString()}).where("id","=",X).execute()}async resetStuckDeliveries(){let X=await this.db.updateTable("event_deliveries").set({status:"pending"}).where("status","=","processing").executeTakeFirst();return Number(X.numUpdatedRows??0)}async getEvent(X,Y){let Q=await this.db.selectFrom("events").selectAll().where("id","=",X).where("organization_id","=",Y).executeTakeFirst();if(!Q)return null;return{id:Q.id,organizationId:Q.organization_id,type:Q.type,source:Q.source,specversion:Q.specversion,subject:Q.subject,time:Q.time,datacontenttype:Q.datacontenttype,dataschema:Q.dataschema,data:Q.data?JSON.parse(Q.data):null,cron:Q.cron,status:Q.status,attempts:Q.attempts,lastError:Q.last_error,nextRetryAt:Q.next_retry_at,createdAt:Q.created_at,updatedAt:Q.updated_at}}async findActiveCronEvent(X,Y,Q,J){let G=await this.db.selectFrom("events").selectAll().where("organization_id","=",X).where("type","=",Y).where("source","=",Q).where("cron","=",J).where("status","in",["pending","processing","delivered"]).orderBy("created_at","desc").executeTakeFirst();if(!G)return null;return{id:G.id,organizationId:G.organization_id,type:G.type,source:G.source,specversion:G.specversion,subject:G.subject,time:G.time,datacontenttype:G.datacontenttype,dataschema:G.dataschema,data:G.data?JSON.parse(G.data):null,cron:G.cron,status:G.status,attempts:G.attempts,lastError:G.last_error,nextRetryAt:G.next_retry_at,createdAt:G.created_at,updatedAt:G.updated_at}}async cancelEvent(X,Y,Q){let J=await this.db.updateTable("events").set({status:"failed",last_error:"Cancelled by publisher",updated_at:new Date().toISOString()}).where("id","=",X).where("organization_id","=",Y).where("source","=",Q).where("status","in",["pending","processing"]).executeTakeFirst();if((J.numUpdatedRows??0n)>0n)await this.db.updateTable("event_deliveries").set({status:"failed",last_error:"Event cancelled by publisher"}).where("event_id","=",X).where("status","in",["pending","processing"]).execute();return{success:(J.numUpdatedRows??0n)>0n}}async scheduleRetryWithoutAttemptIncrement(X,Y){if(X.length===0)return;let Q=new Date(Date.now()+Y).toISOString();await this.db.updateTable("event_deliveries").set({status:"pending",next_retry_at:Q}).where("id","in",X).execute()}async ackDelivery(X,Y,Q){if(!await this.db.selectFrom("events").select(["id"]).where("id","=",X).where("organization_id","=",Y).executeTakeFirst())return{success:!1};let W=((await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:new Date().toISOString()}).where("event_id","=",X).where("status","in",["pending","processing"]).where((Z)=>Z.exists(Z.selectFrom("event_subscriptions").select("id").whereRef("event_subscriptions.id","=","event_deliveries.subscription_id").where("event_subscriptions.connection_id","=",Q).where("event_subscriptions.organization_id","=",Y))).executeTakeFirst()).numUpdatedRows??0n)>0n;if(W)await this.updateEventStatus(X);return{success:W}}async syncSubscriptions(X){let{organizationId:Y,connectionId:Q,subscriptions:J}=X,G=(w,C)=>{return`${w}::${C??""}`},W=await this.listSubscriptions(Y,Q),Z=new Map;for(let w of W)Z.set(G(w.eventType,w.publisher),w);let $=new Map;for(let w of J)$.set(G(w.eventType,w.publisher),w);let K=new Date().toISOString(),H=[],F=[],V=[],q=0;for(let[w,C]of $){let T=Z.get(w);if(!T)H.push({id:crypto.randomUUID(),organization_id:Y,connection_id:Q,event_type:C.eventType,publisher:C.publisher??null,filter:C.filter??null,enabled:1,created_at:K,updated_at:K});else{let A=T.filter??null,P=C.filter??null;if(A!==P)F.push({id:T.id,filter:P});else q++}}for(let[w,C]of Z)if(!$.has(w))V.push(C.id);if(H.length>0)await this.db.insertInto("event_subscriptions").values(H).execute();if(F.length>0)await Promise.all(F.map((w)=>this.db.updateTable("event_subscriptions").set({filter:w.filter,updated_at:K}).where("id","=",w.id).execute()));if(V.length>0)await this.db.deleteFrom("event_subscriptions").where("id","in",V).execute();let z=H.length,D=F.length,N=V.length,L=await this.listSubscriptions(Y,Q);return{created:z,updated:D,deleted:N,unchanged:q,subscriptions:L}}}function $71(X){return new Z71(X)}function pY(X,Y,Q,J,G,W,Z,$){return pY.fromTZ(pY.tp(X,Y,Q,J,G,W,Z),$)}pY.fromTZISO=(X,Y,Q)=>pY.fromTZ(Mh6(X,Y),Q);pY.fromTZ=function(X,Y){let Q=new Date(Date.UTC(X.y,X.m-1,X.d,X.h,X.i,X.s)),J=QY0(X.tz,Q),G=new Date(Q.getTime()-J),W=QY0(X.tz,G);if(W-J===0)return G;{let Z=new Date(Q.getTime()-W),$=QY0(X.tz,Z);if($-W===0)return Z;if(!Y&&$-W>0)return Z;if(Y)throw Error("Invalid date passed to fromTZ()");return G}};pY.toTZ=function(X,Y){let Q=X.toLocaleString("en-US",{timeZone:Y}).replace(/[\u202f]/," "),J=new Date(Q);return{y:J.getFullYear(),m:J.getMonth()+1,d:J.getDate(),h:J.getHours(),i:J.getMinutes(),s:J.getSeconds(),tz:Y}};pY.tp=(X,Y,Q,J,G,W,Z)=>({y:X,m:Y,d:Q,h:J,i:G,s:W,tz:Z});function QY0(X,Y=new Date){let Q=Y.toLocaleString("en-US",{timeZone:X,timeZoneName:"shortOffset"}).split(" ").slice(-1)[0],J=Y.toLocaleString("en-US").replace(/[\u202f]/," ");return Date.parse(`${J} GMT`)-Date.parse(`${J} ${Q}`)}function Mh6(X,Y){let Q=new Date(Date.parse(X));if(isNaN(Q))throw Error("minitz: Invalid ISO8601 passed to parser.");let J=X.substring(9);return X.includes("Z")||J.includes("-")||J.includes("+")?pY.tp(Q.getUTCFullYear(),Q.getUTCMonth()+1,Q.getUTCDate(),Q.getUTCHours(),Q.getUTCMinutes(),Q.getUTCSeconds(),"Etc/UTC"):pY.tp(Q.getFullYear(),Q.getMonth()+1,Q.getDate(),Q.getHours(),Q.getMinutes(),Q.getSeconds(),Y)}pY.minitz=pY;var JY0=32,sP=31|JY0,V71=[1,2,4,8,16],K71=class{pattern;timezone;second;minute;hour;day;month;dayOfWeek;lastDayOfMonth;starDOM;starDOW;constructor(X,Y){this.pattern=X,this.timezone=Y,this.second=Array(60).fill(0),this.minute=Array(60).fill(0),this.hour=Array(24).fill(0),this.day=Array(31).fill(0),this.month=Array(12).fill(0),this.dayOfWeek=Array(7).fill(0),this.lastDayOfMonth=!1,this.starDOM=!1,this.starDOW=!1,this.parse()}parse(){if(!(typeof this.pattern=="string"||this.pattern instanceof String))throw TypeError("CronPattern: Pattern has to be of type string.");this.pattern.indexOf("@")>=0&&(this.pattern=this.handleNicknames(this.pattern).trim());let X=this.pattern.replace(/\s+/g," ").split(" ");if(X.length<5||X.length>6)throw TypeError("CronPattern: invalid configuration format ('"+this.pattern+"'), exactly five or six space separated parts are required.");if(X.length===5&&X.unshift("0"),X[3].indexOf("L")>=0&&(X[3]=X[3].replace("L",""),this.lastDayOfMonth=!0),X[3]=="*"&&(this.starDOM=!0),X[4].length>=3&&(X[4]=this.replaceAlphaMonths(X[4])),X[5].length>=3&&(X[5]=this.replaceAlphaDays(X[5])),X[5]=="*"&&(this.starDOW=!0),this.pattern.indexOf("?")>=0){let Y=new pJ(new Date,this.timezone).getDate(!0);X[0]=X[0].replace("?",Y.getSeconds().toString()),X[1]=X[1].replace("?",Y.getMinutes().toString()),X[2]=X[2].replace("?",Y.getHours().toString()),this.starDOM||(X[3]=X[3].replace("?",Y.getDate().toString())),X[4]=X[4].replace("?",(Y.getMonth()+1).toString()),this.starDOW||(X[5]=X[5].replace("?",Y.getDay().toString()))}this.throwAtIllegalCharacters(X),this.partToArray("second",X[0],0,1),this.partToArray("minute",X[1],0,1),this.partToArray("hour",X[2],0,1),this.partToArray("day",X[3],-1,1),this.partToArray("month",X[4],-1,1),this.partToArray("dayOfWeek",X[5],0,sP),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(X,Y,Q,J){let G=this[X],W=X==="day"&&this.lastDayOfMonth;if(Y===""&&!W)throw TypeError("CronPattern: configuration entry "+X+" ("+Y+") is empty, check for trailing spaces.");if(Y==="*")return G.fill(J);let Z=Y.split(",");if(Z.length>1)for(let $=0;$<Z.length;$++)this.partToArray(X,Z[$],Q,J);else Y.indexOf("-")!==-1&&Y.indexOf("/")!==-1?this.handleRangeWithStepping(Y,X,Q,J):Y.indexOf("-")!==-1?this.handleRange(Y,X,Q,J):Y.indexOf("/")!==-1?this.handleStepping(Y,X,Q,J):Y!==""&&this.handleNumber(Y,X,Q,J)}throwAtIllegalCharacters(X){for(let Y=0;Y<X.length;Y++)if((Y===5?/[^/*0-9,\-#L]+/:/[^/*0-9,-]+/).test(X[Y]))throw TypeError("CronPattern: configuration entry "+Y+" ("+X[Y]+") contains illegal characters.")}handleNumber(X,Y,Q,J){let G=this.extractNth(X,Y),W=parseInt(G[0],10)+Q;if(isNaN(W))throw TypeError("CronPattern: "+Y+" is not a number: '"+X+"'");this.setPart(Y,W,G[1]||J)}setPart(X,Y,Q){if(!Object.prototype.hasOwnProperty.call(this,X))throw TypeError("CronPattern: Invalid part specified: "+X);if(X==="dayOfWeek"){if(Y===7&&(Y=0),Y<0||Y>6)throw RangeError("CronPattern: Invalid value for dayOfWeek: "+Y);this.setNthWeekdayOfMonth(Y,Q);return}if(X==="second"||X==="minute"){if(Y<0||Y>=60)throw RangeError("CronPattern: Invalid value for "+X+": "+Y)}else if(X==="hour"){if(Y<0||Y>=24)throw RangeError("CronPattern: Invalid value for "+X+": "+Y)}else if(X==="day"){if(Y<0||Y>=31)throw RangeError("CronPattern: Invalid value for "+X+": "+Y)}else if(X==="month"&&(Y<0||Y>=12))throw RangeError("CronPattern: Invalid value for "+X+": "+Y);this[X][Y]=Q}handleRangeWithStepping(X,Y,Q,J){let G=this.extractNth(X,Y),W=G[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(W===null)throw TypeError("CronPattern: Syntax error, illegal range with stepping: '"+X+"'");let[,Z,$,K]=W,H=parseInt(Z,10)+Q,F=parseInt($,10)+Q,V=parseInt(K,10);if(isNaN(H))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(F))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN(V))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(V===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(V>this[Y].length)throw TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[Y].length+")");if(H>F)throw TypeError("CronPattern: From value is larger than to value: '"+X+"'");for(let q=H;q<=F;q+=V)this.setPart(Y,q,G[1]||J)}extractNth(X,Y){let Q=X,J;if(Q.includes("#")){if(Y!=="dayOfWeek")throw Error("CronPattern: nth (#) only allowed in day-of-week field");J=Q.split("#")[1],Q=Q.split("#")[0]}return[Q,J]}handleRange(X,Y,Q,J){let G=this.extractNth(X,Y),W=G[0].split("-");if(W.length!==2)throw TypeError("CronPattern: Syntax error, illegal range: '"+X+"'");let Z=parseInt(W[0],10)+Q,$=parseInt(W[1],10)+Q;if(isNaN(Z))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN($))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(Z>$)throw TypeError("CronPattern: From value is larger than to value: '"+X+"'");for(let K=Z;K<=$;K++)this.setPart(Y,K,G[1]||J)}handleStepping(X,Y,Q,J){let G=this.extractNth(X,Y),W=G[0].split("/");if(W.length!==2)throw TypeError("CronPattern: Syntax error, illegal stepping: '"+X+"'");W[0]===""&&(W[0]="*");let Z=0;W[0]!=="*"&&(Z=parseInt(W[0],10)+Q);let $=parseInt(W[1],10);if(isNaN($))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if($===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if($>this[Y].length)throw TypeError("CronPattern: Syntax error, max steps for part is ("+this[Y].length+")");for(let K=Z;K<this[Y].length;K+=$)this.setPart(Y,K,G[1]||J)}replaceAlphaDays(X){return X.replace(/-sun/gi,"-7").replace(/sun/gi,"0").replace(/mon/gi,"1").replace(/tue/gi,"2").replace(/wed/gi,"3").replace(/thu/gi,"4").replace(/fri/gi,"5").replace(/sat/gi,"6")}replaceAlphaMonths(X){return X.replace(/jan/gi,"1").replace(/feb/gi,"2").replace(/mar/gi,"3").replace(/apr/gi,"4").replace(/may/gi,"5").replace(/jun/gi,"6").replace(/jul/gi,"7").replace(/aug/gi,"8").replace(/sep/gi,"9").replace(/oct/gi,"10").replace(/nov/gi,"11").replace(/dec/gi,"12")}handleNicknames(X){let Y=X.trim().toLowerCase();return Y==="@yearly"||Y==="@annually"?"0 0 1 1 *":Y==="@monthly"?"0 0 1 * *":Y==="@weekly"?"0 0 * * 0":Y==="@daily"?"0 0 * * *":Y==="@hourly"?"0 * * * *":X}setNthWeekdayOfMonth(X,Y){if(typeof Y!="number"&&Y==="L")this.dayOfWeek[X]=this.dayOfWeek[X]|JY0;else if(Y===sP)this.dayOfWeek[X]=sP;else if(Y<6&&Y>0)this.dayOfWeek[X]=this.dayOfWeek[X]|V71[Y-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${Y}, Type: ${typeof Y}`)}},H71=[31,28,31,30,31,30,31,31,30,31,30,31],tW=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]],pJ=class X{tz;ms;second;minute;hour;day;month;year;constructor(Y,Q){if(this.tz=Q,Y&&Y instanceof Date)if(!isNaN(Y))this.fromDate(Y);else throw TypeError("CronDate: Invalid date passed to CronDate constructor");else if(Y===void 0)this.fromDate(new Date);else if(Y&&typeof Y=="string")this.fromString(Y);else if(Y instanceof X)this.fromCronDate(Y);else throw TypeError("CronDate: Invalid type ("+typeof Y+") passed to CronDate constructor")}isNthWeekdayOfMonth(Y,Q,J,G){let W=new Date(Date.UTC(Y,Q,J)).getUTCDay(),Z=0;for(let $=1;$<=J;$++)new Date(Date.UTC(Y,Q,$)).getUTCDay()===W&&Z++;if(G&sP&&V71[Z-1]&G)return!0;if(G&JY0){let $=new Date(Date.UTC(Y,Q+1,0)).getUTCDate();for(let K=J+1;K<=$;K++)if(new Date(Date.UTC(Y,Q,K)).getUTCDay()===W)return!1;return!0}return!1}fromDate(Y){if(this.tz!==void 0)if(typeof this.tz=="number")this.ms=Y.getUTCMilliseconds(),this.second=Y.getUTCSeconds(),this.minute=Y.getUTCMinutes()+this.tz,this.hour=Y.getUTCHours(),this.day=Y.getUTCDate(),this.month=Y.getUTCMonth(),this.year=Y.getUTCFullYear(),this.apply();else{let Q=pY.toTZ(Y,this.tz);this.ms=Y.getMilliseconds(),this.second=Q.s,this.minute=Q.i,this.hour=Q.h,this.day=Q.d,this.month=Q.m-1,this.year=Q.y}else this.ms=Y.getMilliseconds(),this.second=Y.getSeconds(),this.minute=Y.getMinutes(),this.hour=Y.getHours(),this.day=Y.getDate(),this.month=Y.getMonth(),this.year=Y.getFullYear()}fromCronDate(Y){this.tz=Y.tz,this.year=Y.year,this.month=Y.month,this.day=Y.day,this.hour=Y.hour,this.minute=Y.minute,this.second=Y.second,this.ms=Y.ms}apply(){if(this.month>11||this.day>H71[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let Y=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=Y.getUTCMilliseconds(),this.second=Y.getUTCSeconds(),this.minute=Y.getUTCMinutes(),this.hour=Y.getUTCHours(),this.day=Y.getUTCDate(),this.month=Y.getUTCMonth(),this.year=Y.getUTCFullYear(),!0}else return!1}fromString(Y){if(typeof this.tz=="number"){let Q=pY.fromTZISO(Y);this.ms=Q.getUTCMilliseconds(),this.second=Q.getUTCSeconds(),this.minute=Q.getUTCMinutes(),this.hour=Q.getUTCHours(),this.day=Q.getUTCDate(),this.month=Q.getUTCMonth(),this.year=Q.getUTCFullYear(),this.apply()}else return this.fromDate(pY.fromTZISO(Y,this.tz))}findNext(Y,Q,J,G){let W=this[Q],Z;J.lastDayOfMonth&&(this.month!==1?Z=H71[this.month]:Z=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate());let $=!J.starDOW&&Q=="day"?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let K=this[Q]+G;K<J[Q].length;K++){let H=J[Q][K];if(Q==="day"&&J.lastDayOfMonth&&K-G==Z&&(H=1),Q==="day"&&!J.starDOW){let F=J.dayOfWeek[($+(K-G-1))%7];if(F&&F&sP)F=this.isNthWeekdayOfMonth(this.year,this.month,K-G,F)?1:0;else if(F)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${F}`);Y.legacyMode&&!J.starDOM?H=H||F:H=H&&F}if(H)return this[Q]=K-G,W!==this[Q]?2:1}return 3}recurse(Y,Q,J){let G=this.findNext(Q,tW[J][0],Y,tW[J][2]);if(G>1){let W=J+1;for(;W<tW.length;)this[tW[W][0]]=-tW[W][2],W++;if(G===3)return this[tW[J][1]]++,this[tW[J][0]]=-tW[J][2],this.apply(),this.recurse(Y,Q,0);if(this.apply())return this.recurse(Y,Q,J-1)}return J+=1,J>=tW.length?this:this.year>=3000?null:this.recurse(Y,Q,J)}increment(Y,Q,J){return this.second+=Q.interval!==void 0&&Q.interval>1&&J?Q.interval:1,this.ms=0,this.apply(),this.recurse(Y,Q,0)}getDate(Y){return Y||this.tz===void 0?new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms):typeof this.tz=="number"?new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms)):pY.fromTZ(pY.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function Ph6(X){if(X===void 0&&(X={}),delete X.name,X.legacyMode=X.legacyMode===void 0?!0:X.legacyMode,X.paused=X.paused===void 0?!1:X.paused,X.maxRuns=X.maxRuns===void 0?1/0:X.maxRuns,X.catch=X.catch===void 0?!1:X.catch,X.interval=X.interval===void 0?0:parseInt(X.interval.toString(),10),X.utcOffset=X.utcOffset===void 0?void 0:parseInt(X.utcOffset.toString(),10),X.unref=X.unref===void 0?!1:X.unref,X.startAt&&(X.startAt=new pJ(X.startAt,X.timezone)),X.stopAt&&(X.stopAt=new pJ(X.stopAt,X.timezone)),X.interval!==null){if(isNaN(X.interval))throw Error("CronOptions: Supplied value for interval is not a number");if(X.interval<0)throw Error("CronOptions: Supplied value for interval can not be negative")}if(X.utcOffset!==void 0){if(isNaN(X.utcOffset))throw Error("CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.");if(X.utcOffset<-870||X.utcOffset>870)throw Error("CronOptions: utcOffset out of bounds.");if(X.utcOffset!==void 0&&X.timezone)throw Error("CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.")}if(X.unref!==!0&&X.unref!==!1)throw Error("CronOptions: Unref should be either true, false or undefined(false).");return X}function oP(X){return Object.prototype.toString.call(X)==="[object Function]"||typeof X=="function"||X instanceof Function}function Ah6(X){return oP(X)}function Th6(X){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer(X):X&&typeof X.unref<"u"&&X.unref()}var F71=30000,vb=[],_b=class{name;options;_states;fn;constructor(X,Y,Q){let J,G;if(oP(Y))G=Y;else if(typeof Y=="object")J=Y;else if(Y!==void 0)throw Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");if(oP(Q))G=Q;else if(typeof Q=="object")J=Q;else if(Q!==void 0)throw Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");if(this.name=J?.name,this.options=Ph6(J),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:J?J.maxRuns:void 0,paused:J?J.paused:!1,pattern:new K71("* * * * *")},X&&(X instanceof Date||typeof X=="string"&&X.indexOf(":")>0)?this._states.once=new pJ(X,this.options.timezone||this.options.utcOffset):this._states.pattern=new K71(X,this.options.timezone),this.name){if(vb.find((W)=>W.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");vb.push(this)}return G!==void 0&&Ah6(G)&&(this.fn=G,this.schedule()),this}nextRun(X){let Y=this._next(X);return Y?Y.getDate(!1):null}nextRuns(X,Y){this._states.maxRuns!==void 0&&X>this._states.maxRuns&&(X=this._states.maxRuns);let Q=[],J=Y||this._states.currentRun||void 0;for(;X--&&(J=this.nextRun(J));)Q.push(J);return Q}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let X=this.nextRun(this._states.currentRun),Y=!this._states.paused,Q=this.fn!==void 0,J=!this._states.kill;return Y&&Q&&J&&X!==null}isStopped(){return this._states.kill}isBusy(){return this._states.blocking}currentRun(){return this._states.currentRun?this._states.currentRun.getDate():null}previousRun(){return this._states.previousRun?this._states.previousRun.getDate():null}msToNext(X){let Y=this._next(X);return Y?X instanceof pJ||X instanceof Date?Y.getTime()-X.getTime():Y.getTime()-new pJ(X).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let X=vb.indexOf(this);X>=0&&vb.splice(X,1)}pause(){return this._states.paused=!0,!this._states.kill}resume(){return this._states.paused=!1,!this._states.kill}schedule(X){if(X&&this.fn)throw Error("Cron: It is not allowed to schedule two functions using the same Croner instance.");X&&(this.fn=X);let Y=this.msToNext(),Q=this.nextRun(this._states.currentRun);return Y==null||isNaN(Y)||Q===null?this:(Y>F71&&(Y=F71),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(Q),Y),this._states.currentTimeout&&this.options.unref&&Th6(this._states.currentTimeout),this)}async _trigger(X){if(this._states.blocking=!0,this._states.currentRun=new pJ(void 0,this.options.timezone||this.options.utcOffset),this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(Y){oP(this.options.catch)&&this.options.catch(Y,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new pJ(X,this.options.timezone||this.options.utcOffset),this._states.blocking=!1}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger(X){let Y=new Date,Q=!this._states.paused&&Y.getTime()>=X.getTime(),J=this._states.blocking&&this.options.protect;Q&&!J?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):Q&&J&&oP(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next(X){let Y=!!(X||this._states.currentRun),Q=!1;!X&&this.options.startAt&&this.options.interval&&([X,Y]=this._calculatePreviousRun(X,Y),Q=!X),X=new pJ(X,this.options.timezone||this.options.utcOffset),this.options.startAt&&X&&X.getTime()<this.options.startAt.getTime()&&(X=this.options.startAt);let J=this._states.once||new pJ(X,this.options.timezone||this.options.utcOffset);return!Q&&J!==this._states.once&&(J=J.increment(this._states.pattern,this.options,Y)),this._states.once&&this._states.once.getTime()<=X.getTime()||J===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&J.getTime()>=this.options.stopAt.getTime()?null:J}_calculatePreviousRun(X,Y){let Q=new pJ(void 0,this.options.timezone||this.options.utcOffset),J=X;if(this.options.startAt.getTime()<=Q.getTime()){J=this.options.startAt;let G=J.getTime()+this.options.interval*1000;for(;G<=Q.getTime();)J=new pJ(J,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),G=J.getTime()+this.options.interval*1000;Y=!0}return J===null&&(J=void 0),[J,Y]}};var yb={pollIntervalMs:5000,batchSize:100,maxAttempts:20,retryDelayMs:1000,maxDelayMs:3600000};Ob();function q71(){return async(X,Y)=>{try{let Q=await zK.create(),J=await X71(X,{...Q,auth:{...Q.auth,user:{id:"notify-worker"}}}),W=await i80.forClient(J).ON_EVENTS({events:Y});return{success:W.success,error:W.error,retryAfter:W.retryAfter,results:W.results}}catch(Q){let J=Q instanceof Error?Q.message:String(Q);return console.error(`[EventBus] Failed to notify connection ${X}:`,J),{success:!1,error:J}}}}function U71(X){return{specversion:"1.0",id:X.id,source:X.source,type:X.type,time:X.time,subject:X.subject??void 0,datacontenttype:X.datacontenttype,dataschema:X.dataschema??void 0,data:X.data??void 0}}function Eh6(X){let Y=new Map;for(let J of X){let G=J.subscription.connectionId,W=Y.get(G);if(W){if(W.deliveryIds.push(J.delivery.id),!W.seenEventIds.has(J.event.id))W.seenEventIds.add(J.event.id),W.events.push(U71(J.event))}else Y.set(G,{connectionId:J.subscription.connectionId,deliveryIds:[J.delivery.id],events:[U71(J.event)],seenEventIds:new Set([J.event.id])})}let Q=new Map;for(let[J,G]of Y)Q.set(J,{connectionId:G.connectionId,deliveryIds:G.deliveryIds,events:G.events});return Q}class GY0{storage;notifySubscriber;running=!1;processing=!1;config;constructor(X,Y){this.storage=X;this.notifySubscriber=q71(),this.config={...yb,...Y}}async start(){if(this.running)return;let X=await this.storage.resetStuckDeliveries();if(X>0)console.log(`[EventBus] Reset ${X} stuck deliveries from previous shutdown`);this.running=!0}stop(){this.running=!1,console.log("[EventBus] Worker stopped")}isRunning(){return this.running}async processNow(){if(!this.running)return;if(this.processing)return;this.processing=!0;try{await this.processEvents()}catch(X){console.error("[EventBus] Error processing events:",X)}finally{this.processing=!1}}async processEvents(){let X=await this.storage.claimPendingDeliveries(this.config.batchSize);if(X.length===0)return;let Y=Eh6(X),Q=new Set;for(let[J,G]of Y){try{let W=await this.notifySubscriber(G.connectionId,G.events);if(W.results&&Object.keys(W.results).length>0)await this.processPerEventResults(G,W);else if(W.success)await this.storage.markDeliveriesDelivered(G.deliveryIds);else if(W.retryAfter&&W.retryAfter>0)await this.storage.scheduleRetryWithoutAttemptIncrement(G.deliveryIds,W.retryAfter);else await this.storage.markDeliveriesFailed(G.deliveryIds,W.error||"Subscriber returned success=false",this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}catch(W){let Z=W instanceof Error?W.message:String(W);console.error(`[EventBus] Failed to notify subscription ${J}:`,Z),await this.storage.markDeliveriesFailed(G.deliveryIds,Z,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}for(let W of X)if(G.deliveryIds.includes(W.delivery.id))Q.add(W.event.id)}for(let J of Q)try{await this.storage.updateEventStatus(J);let G=X.find((W)=>W.event.id===J)?.event;if(G?.cron)await this.scheduleNextCronDelivery(G)}catch(G){console.error(`[EventBus] Failed to update event status ${J}:`,G)}}async processPerEventResults(X,Y){let Q=[],J=new Map,G=[],W=new Map;for(let Z=0;Z<X.events.length;Z++){let $=X.events?.[Z];if(!$)continue;let K=X.deliveryIds?.[Z];if(!K)continue;W.set($.id,K)}for(let Z of X.events){let $=W.get(Z.id);if(!$)continue;let K=Y.results?.[Z.id];if(K)if(K.success)Q.push($);else if(K.retryAfter&&K.retryAfter>0){let H=J.get(K.retryAfter)||[];H.push($),J.set(K.retryAfter,H)}else G.push({deliveryId:$,error:K.error||"Event processing failed"});else if(Y.success)Q.push($);else if(Y.retryAfter&&Y.retryAfter>0){let H=J.get(Y.retryAfter)||[];H.push($),J.set(Y.retryAfter,H)}else G.push({deliveryId:$,error:Y.error||"Batch processing failed"})}if(Q.length>0)await this.storage.markDeliveriesDelivered(Q);for(let[Z,$]of J)await this.storage.scheduleRetryWithoutAttemptIncrement($,Z);if(G.length>0){let Z=new Map;for(let{deliveryId:$,error:K}of G){let H=Z.get(K)||[];H.push($),Z.set(K,H)}for(let[$,K]of Z)await this.storage.markDeliveriesFailed(K,$,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}}async scheduleNextCronDelivery(X){if(!X.cron)return;try{let Q=new _b(X.cron).nextRun();if(!Q){console.log(`[EventBus] Cron expression for event ${X.id} has no more runs`);return}let J=Q.toISOString(),G=await this.storage.getMatchingSubscriptions(X);if(G.length===0){console.log(`[EventBus] No subscriptions for cron event ${X.id}, skipping next delivery`);return}await this.storage.createDeliveries(X.id,G.map((W)=>W.id),J),console.log(`[EventBus] Scheduled next cron delivery for event ${X.id} at ${J}`)}catch(Y){console.error(`[EventBus] Failed to schedule next cron delivery for event ${X.id}:`,Y)}}}class WY0{storage;worker;notifyStrategy;running=!1;constructor(X){this.storage=X.storage,this.notifyStrategy=X.notifyStrategy,this.worker=new GY0(this.storage,X.config)}async publish(X,Y,Q){if(Q.deliverAt&&Q.cron)throw Error("Cannot set both deliverAt and cron. Use one or the other.");let J;if(Q.cron){try{let F=new _b(Q.cron).nextRun();if(!F)throw Error("Cron expression does not produce a next run time");J=F.toISOString()}catch(H){throw Error(`Invalid cron expression: ${H instanceof Error?H.message:String(H)}`)}let K=await this.storage.findActiveCronEvent(X,Q.type,Y,Q.cron);if(K)return K}let G=crypto.randomUUID(),W=new Date().toISOString(),Z=await this.storage.publishEvent({id:G,organizationId:X,type:Q.type,source:Y,subject:Q.subject,time:W,data:Q.data,cron:Q.cron}),$=await this.storage.getMatchingSubscriptions(Z);if($.length>0){let K=Q.deliverAt??J;if(await this.storage.createDeliveries(G,$.map((H)=>H.id),K),this.notifyStrategy&&!K)await this.notifyStrategy.notify(G).catch((H)=>{console.warn("[EventBus] Notify failed (non-critical):",H)})}return Z}async subscribe(X,Y){return this.storage.subscribe({id:crypto.randomUUID(),organizationId:X,connectionId:Y.connectionId,publisher:Y.publisher,eventType:Y.eventType,filter:Y.filter})}async unsubscribe(X,Y){return this.storage.unsubscribe(Y,X)}async listSubscriptions(X,Y){return this.storage.listSubscriptions(X,Y)}async getSubscription(X,Y){return this.storage.getSubscription(Y,X)}async getEvent(X,Y){return this.storage.getEvent(Y,X)}async cancelEvent(X,Y,Q){return this.storage.cancelEvent(Y,X,Q)}async ackEvent(X,Y,Q){return this.storage.ackDelivery(Y,X,Q)}async syncSubscriptions(X,Y){return this.storage.syncSubscriptions({organizationId:X,...Y})}async start(){if(this.running)return;if(this.running=!0,await this.worker.start(),this.notifyStrategy)await this.notifyStrategy.start(()=>{this.worker.processNow().catch((X)=>{console.error("[EventBus] Error processing after notify:",X)})});await this.worker.processNow().catch((X)=>{console.error("[EventBus] Error processing pending events on startup:",X)})}async stop(){if(!this.running)return;if(this.running=!1,this.worker.stop(),this.notifyStrategy)try{await this.notifyStrategy.stop()}catch(X){console.error("[EventBus] Error stopping notify strategy:",X)}console.log("[EventBus] Stopped")}isRunning(){return this.running}}function z71(...X){return{async start(Y){await Promise.all(X.map((Q)=>Q.start(Y)))},async stop(){await Promise.all(X.map((Y)=>Y.stop().catch((Q)=>{console.error("[NotifyStrategy] Error stopping strategy:",Q)})))},async notify(Y){await Promise.all(X.map((Q)=>Q.notify(Y).catch((J)=>{console.warn("[NotifyStrategy] Notify failed (non-critical):",J)})))}}}class bb{intervalMs;timer=null;onNotify=null;constructor(X){this.intervalMs=X}async start(X){if(this.timer)return;this.onNotify=X,this.scheduleNext(),console.log(`[Polling] Started polling every ${this.intervalMs}ms`)}async stop(){if(this.timer)clearTimeout(this.timer),this.timer=null,console.log("[Polling] Stopped polling");this.onNotify=null}async notify(X){if(this.onNotify)this.onNotify()}scheduleNext(){this.timer=setTimeout(()=>{if(this.onNotify)this.onNotify();if(this.timer)this.scheduleNext()},this.intervalMs)}}import{sql as jh6}from"kysely";var ZB="mesh_events";class ZY0{db;pool;listenClient=null;onNotify=null;constructor(X,Y){this.db=X;this.pool=Y}async start(X){if(this.listenClient)return;this.onNotify=X;try{this.listenClient=await this.pool.connect(),this.listenClient.on("notification",(Y)=>{if(Y.channel===ZB&&this.onNotify)this.onNotify()}),this.listenClient.on("error",(Y)=>{console.error("[PostgresNotify] Connection error:",Y),this.cleanup()}),await this.listenClient.query(`LISTEN ${ZB}`),console.log("[PostgresNotify] Started LISTEN on",ZB)}catch(Y){console.error("[PostgresNotify] Failed to start LISTEN:",Y),this.cleanup()}}async stop(){if(this.listenClient){try{await this.listenClient.query(`UNLISTEN ${ZB}`),console.log("[PostgresNotify] Stopped LISTEN on",ZB)}catch{}this.cleanup()}}async notify(X){try{await jh6`SELECT pg_notify(${ZB}, ${X})`.execute(this.db)}catch(Y){console.warn("[PostgresNotify] Failed to send NOTIFY:",Y)}}cleanup(){if(this.listenClient)this.listenClient.release(),this.listenClient=null;this.onNotify=null}}function B71(X,Y){let Q=$71(X.db),J=Y?.pollIntervalMs??yb.pollIntervalMs,G=X.type==="postgres"?z71(new bb(J),new ZY0(X.db,X.pool)):new bb(J);return new WY0({storage:Q,config:Y,notifyStrategy:G})}var D71={google:{name:"Google",icon:"https://assets.decocache.com/webdraw/eb7480aa-a68b-4ce4-98ff-36aa121762a7/google.svg"},github:{name:"GitHub",icon:"https://assets.decocache.com/webdraw/5f999dcb-c8a6-4572-948c-9996ef1d502f/github.svg"},microsoft:{name:"Microsoft",icon:"https://assets.decocache.com/mcp/aa6f6e1a-6526-4bca-99cc-82e2ec38b0e4/microsoft.png"}};var N71=new p8;N71.get("/config",async(X)=>{try{let Y=Object.keys(e8.socialProviders??{}),Q=Y.length>0,J=Y.map((Z)=>({name:Z,icon:D71[Z].icon})),G=process.env.UNSAFE_ALLOW_STDIO_TRANSPORT==="true",W={emailAndPassword:{enabled:e8.emailAndPassword?.enabled??!1},magicLink:{enabled:e8.magicLinkConfig?.enabled??!1},socialProviders:{enabled:Q,providers:J},sso:e8.ssoConfig?{enabled:!0,providerId:e8.ssoConfig.providerId}:{enabled:!1},stdioEnabled:G};return X.json({success:!0,config:W})}catch(Y){let Q=Y instanceof Error?Y.message:"Failed to load auth config";return X.json({success:!1,error:Q},500)}});var O71=N71;eH();var i71="vercel.ai.error",Ch6=Symbol.for(i71),L71,w71,N1=class X extends(w71=Error,L71=Ch6,w71){constructor({name:Y,message:Q,cause:J}){super(Q);this[L71]=!0,this.name=Y,this.cause=J}static isInstance(Y){return X.hasMarker(Y,i71)}static hasMarker(Y,Q){let J=Symbol.for(Q);return Y!=null&&typeof Y==="object"&&J in Y&&typeof Y[J]==="boolean"&&Y[J]===!0}},a71="AI_APICallError",r71=`vercel.ai.error.${a71}`,Ih6=Symbol.for(r71),M71,P71,XX=class extends(P71=N1,M71=Ih6,P71){constructor({message:X,url:Y,requestBodyValues:Q,statusCode:J,responseHeaders:G,responseBody:W,cause:Z,isRetryable:$=J!=null&&(J===408||J===409||J===429||J>=500),data:K}){super({name:a71,message:X,cause:Z});this[M71]=!0,this.url=Y,this.requestBodyValues=Q,this.statusCode=J,this.responseHeaders=G,this.responseBody=W,this.isRetryable=$,this.data=K}static isInstance(X){return N1.hasMarker(X,r71)}},o71="AI_EmptyResponseBodyError",s71=`vercel.ai.error.${o71}`,Rh6=Symbol.for(s71),A71,T71,t71=class extends(T71=N1,A71=Rh6,T71){constructor({message:X="Empty response body"}={}){super({name:o71,message:X});this[A71]=!0}static isInstance(X){return N1.hasMarker(X,s71)}};function g5(X){if(X==null)return"unknown error";if(typeof X==="string")return X;if(X instanceof Error)return X.message;return JSON.stringify(X)}var e71="AI_InvalidArgumentError",XW1=`vercel.ai.error.${e71}`,Sh6=Symbol.for(XW1),E71,j71,YW1=class extends(j71=N1,E71=Sh6,j71){constructor({message:X,cause:Y,argument:Q}){super({name:e71,message:X,cause:Y});this[E71]=!0,this.argument=Q}static isInstance(X){return N1.hasMarker(X,XW1)}},QW1="AI_InvalidPromptError",JW1=`vercel.ai.error.${QW1}`,kh6=Symbol.for(JW1),C71,I71,PF=class extends(I71=N1,C71=kh6,I71){constructor({prompt:X,message:Y,cause:Q}){super({name:QW1,message:`Invalid prompt: ${Y}`,cause:Q});this[C71]=!0,this.prompt=X}static isInstance(X){return N1.hasMarker(X,JW1)}},GW1="AI_InvalidResponseDataError",WW1=`vercel.ai.error.${GW1}`,vh6=Symbol.for(WW1),R71,S71,bo4=class extends(S71=N1,R71=vh6,S71){constructor({data:X,message:Y=`Invalid response data: ${JSON.stringify(X)}.`}){super({name:GW1,message:Y});this[R71]=!0,this.data=X}static isInstance(X){return N1.hasMarker(X,WW1)}},ZW1="AI_JSONParseError",$W1=`vercel.ai.error.${ZW1}`,_h6=Symbol.for($W1),k71,v71,tP=class extends(v71=N1,k71=_h6,v71){constructor({text:X,cause:Y}){super({name:ZW1,message:`JSON parsing failed: Text: ${X}.
1052
+ Error message: ${g5(Y)}`,cause:Y});this[k71]=!0,this.text=X}static isInstance(X){return N1.hasMarker(X,$W1)}},KW1="AI_LoadAPIKeyError",HW1=`vercel.ai.error.${KW1}`,yh6=Symbol.for(HW1),_71,y71,fo4=class extends(y71=N1,_71=yh6,y71){constructor({message:X}){super({name:KW1,message:X});this[_71]=!0}static isInstance(X){return N1.hasMarker(X,HW1)}},FW1="AI_LoadSettingError",VW1=`vercel.ai.error.${FW1}`,bh6=Symbol.for(VW1),b71,f71,ho4=class extends(f71=N1,b71=bh6,f71){constructor({message:X}){super({name:FW1,message:X});this[b71]=!0}static isInstance(X){return N1.hasMarker(X,VW1)}},qW1="AI_NoContentGeneratedError",UW1=`vercel.ai.error.${qW1}`,fh6=Symbol.for(UW1),h71,x71,xo4=class extends(x71=N1,h71=fh6,x71){constructor({message:X="No content generated."}={}){super({name:qW1,message:X});this[h71]=!0}static isInstance(X){return N1.hasMarker(X,UW1)}},zW1="AI_NoSuchModelError",BW1=`vercel.ai.error.${zW1}`,hh6=Symbol.for(BW1),g71,u71,go4=class extends(u71=N1,g71=hh6,u71){constructor({errorName:X=zW1,modelId:Y,modelType:Q,message:J=`No such ${Q}: ${Y}`}){super({name:X,message:J});this[g71]=!0,this.modelId=Y,this.modelType=Q}static isInstance(X){return N1.hasMarker(X,BW1)}},DW1="AI_TooManyEmbeddingValuesForCallError",NW1=`vercel.ai.error.${DW1}`,xh6=Symbol.for(NW1),m71,l71,uo4=class extends(l71=N1,m71=xh6,l71){constructor(X){super({name:DW1,message:`Too many values for a single embedding call. The ${X.provider} model "${X.modelId}" can only embed up to ${X.maxEmbeddingsPerCall} values per call, but ${X.values.length} values were provided.`});this[m71]=!0,this.provider=X.provider,this.modelId=X.modelId,this.maxEmbeddingsPerCall=X.maxEmbeddingsPerCall,this.values=X.values}static isInstance(X){return N1.hasMarker(X,NW1)}},OW1="AI_TypeValidationError",LW1=`vercel.ai.error.${OW1}`,gh6=Symbol.for(LW1),d71,p71,KQ=class X extends(p71=N1,d71=gh6,p71){constructor({value:Y,cause:Q}){super({name:OW1,message:`Type validation failed: Value: ${JSON.stringify(Y)}.
1053
1053
  Error message: ${g5(Q)}`,cause:Q});this[d71]=!0,this.value=Y}static isInstance(Y){return N1.hasMarker(Y,LW1)}static wrap({value:Y,cause:Q}){return X.isInstance(Q)&&Q.value===Y?Q:new X({value:Y,cause:Q})}},wW1="AI_UnsupportedFunctionalityError",MW1=`vercel.ai.error.${wW1}`,uh6=Symbol.for(MW1),c71,n71,PW1=class extends(n71=N1,c71=uh6,n71){constructor({functionality:X,message:Y=`'${X}' functionality not supported.`}){super({name:wW1,message:Y});this[c71]=!0,this.functionality=X}static isInstance(X){return N1.hasMarker(X,MW1)}};c6();kZ();kZ();kZ();wo();function TF(...X){return X.reduce((Y,Q)=>({...Y,...Q!=null?Q:{}}),{})}async function RW1(X,Y){if(X==null)return Promise.resolve();let Q=Y==null?void 0:Y.abortSignal;return new Promise((J,G)=>{if(Q==null?void 0:Q.aborted){G(AW1());return}let W=setTimeout(()=>{Z(),J()},X),Z=()=>{clearTimeout(W),Q==null||Q.removeEventListener("abort",$)},$=()=>{Z(),G(AW1())};Q==null||Q.addEventListener("abort",$)})}function AW1(){return new DOMException("Delay was aborted","AbortError")}var EF=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){if(this._promise)return this._promise;return this._promise=new Promise((X,Y)=>{if(this.status.type==="resolved")X(this.status.value);else if(this.status.type==="rejected")Y(this.status.error);this._resolve=X,this._reject=Y}),this._promise}resolve(X){var Y;if(this.status={type:"resolved",value:X},this._promise)(Y=this._resolve)==null||Y.call(this,X)}reject(X){var Y;if(this.status={type:"rejected",error:X},this._promise)(Y=this._reject)==null||Y.call(this,X)}isResolved(){return this.status.type==="resolved"}isRejected(){return this.status.type==="rejected"}isPending(){return this.status.type==="pending"}};function eP(X){return Object.fromEntries([...X.headers])}var{btoa:mh6,atob:lh6}=globalThis;function $B(X){let Y=X.replace(/-/g,"+").replace(/_/g,"/"),Q=lh6(Y);return Uint8Array.from(Q,(J)=>J.codePointAt(0))}function jF(X){let Y="";for(let Q=0;Q<X.length;Q++)Y+=String.fromCodePoint(X[Q]);return mh6(Y)}var SW1="AI_DownloadError",kW1=`vercel.ai.error.${SW1}`,dh6=Symbol.for(kW1),TW1,EW1,fb=class extends(EW1=N1,TW1=dh6,EW1){constructor({url:X,statusCode:Y,statusText:Q,cause:J,message:G=J==null?`Failed to download ${X}: ${Y} ${Q}`:`Failed to download ${X}: ${J}`}){super({name:SW1,message:G,cause:J});this[TW1]=!0,this.url=X,this.statusCode=Y,this.statusText=Q}static isInstance(X){return N1.hasMarker(X,kW1)}};var D7=({prefix:X,size:Y=16,alphabet:Q="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:J="-"}={})=>{let G=()=>{let W=Q.length,Z=Array(Y);for(let $=0;$<Y;$++)Z[$]=Q[Math.random()*W|0];return Z.join("")};if(X==null)return G;if(Q.includes(J))throw new YW1({argument:"separator",message:`The separator "${J}" must not be part of the alphabet "${Q}".`});return()=>`${X}${J}${G()}`},ph6=D7();function KB(X){if(X==null)return"unknown error";if(typeof X==="string")return X;if(X instanceof Error)return X.message;return JSON.stringify(X)}function eW(X){return(X instanceof Error||X instanceof DOMException)&&(X.name==="AbortError"||X.name==="ResponseAborted"||X.name==="TimeoutError")}var ch6=["fetch failed","failed to fetch"];function vW1({error:X,url:Y,requestBodyValues:Q}){if(eW(X))return X;if(X instanceof TypeError&&ch6.includes(X.message.toLowerCase())){let J=X.cause;if(J!=null)return new XX({message:`Cannot connect to API: ${J.message}`,cause:J,url:Y,requestBodyValues:Q,isRetryable:!0})}return X}function hb(X=globalThis){var Y,Q,J;if(X.window)return"runtime/browser";if((Y=X.navigator)==null?void 0:Y.userAgent)return`runtime/${X.navigator.userAgent.toLowerCase()}`;if((J=(Q=X.process)==null?void 0:Q.versions)==null?void 0:J.node)return`runtime/node.js/${X.process.version.substring(0)}`;if(X.EdgeRuntime)return"runtime/vercel-edge";return"runtime/unknown"}function nh6(X){if(X==null)return{};let Y={};if(X instanceof Headers)X.forEach((Q,J)=>{Y[J.toLowerCase()]=Q});else{if(!Array.isArray(X))X=Object.entries(X);for(let[Q,J]of X)if(J!=null)Y[Q.toLowerCase()]=J}return Y}function XZ(X,...Y){let Q=new Headers(nh6(X)),J=Q.get("user-agent")||"";return Q.set("user-agent",[J,...Y].filter(Boolean).join(" ")),Object.fromEntries(Q.entries())}var _W1="4.0.9",ih6=()=>globalThis.fetch,VY0=async({url:X,headers:Y={},successfulResponseHandler:Q,failedResponseHandler:J,abortSignal:G,fetch:W=ih6()})=>{try{let Z=await W(X,{method:"GET",headers:XZ(Y,`ai-sdk/provider-utils/${_W1}`,hb()),signal:G}),$=eP(Z);if(!Z.ok){let K;try{K=await J({response:Z,url:X,requestBodyValues:{}})}catch(H){if(eW(H)||XX.isInstance(H))throw H;throw new XX({message:"Failed to process error response",cause:H,statusCode:Z.status,url:X,responseHeaders:$,requestBodyValues:{}})}throw K.value}try{return await Q({response:Z,url:X,requestBodyValues:{}})}catch(K){if(K instanceof Error){if(eW(K)||XX.isInstance(K))throw K}throw new XX({message:"Failed to process successful response",cause:K,statusCode:Z.status,url:X,responseHeaders:$,requestBodyValues:{}})}}catch(Z){throw vW1({error:Z,url:X,requestBodyValues:{}})}};function yW1(X){return X!=null}function bW1({mediaType:X,url:Y,supportedUrls:Q}){return Y=Y.toLowerCase(),X=X.toLowerCase(),Object.entries(Q).map(([J,G])=>{let W=J.toLowerCase();return W==="*"||W==="*/*"?{mediaTypePrefix:"",regexes:G}:{mediaTypePrefix:W.replace(/\*/,""),regexes:G}}).filter(({mediaTypePrefix:J})=>X.startsWith(J)).flatMap(({regexes:J})=>J).some((J)=>J.test(Y))}function XA({settingValue:X,environmentVariableName:Y}){if(typeof X==="string")return X;if(X!=null||typeof process>"u")return;if(X=process.env[Y],X==null||typeof X!=="string")return;return X}var ah6=/"__proto__"\s*:/,rh6=/"constructor"\s*:/;function jW1(X){let Y=JSON.parse(X);if(Y===null||typeof Y!=="object")return Y;if(ah6.test(X)===!1&&rh6.test(X)===!1)return Y;return oh6(Y)}function oh6(X){let Y=[X];while(Y.length){let Q=Y;Y=[];for(let J of Q){if(Object.prototype.hasOwnProperty.call(J,"__proto__"))throw SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(J,"constructor")&&Object.prototype.hasOwnProperty.call(J.constructor,"prototype"))throw SyntaxError("Object contains forbidden prototype property");for(let G in J){let W=J[G];if(W&&typeof W==="object")Y.push(W)}}}return X}function fW1(X){let{stackTraceLimit:Y}=Error;try{Error.stackTraceLimit=0}catch(Q){return jW1(X)}try{return jW1(X)}finally{Error.stackTraceLimit=Y}}function qY0(X){if(X.type==="object"||Array.isArray(X.type)&&X.type.includes("object")){X.additionalProperties=!1;let{properties:Q}=X;if(Q!=null)for(let J of Object.keys(Q))Q[J]=AF(Q[J])}if(X.items!=null)X.items=Array.isArray(X.items)?X.items.map(AF):AF(X.items);if(X.anyOf!=null)X.anyOf=X.anyOf.map(AF);if(X.allOf!=null)X.allOf=X.allOf.map(AF);if(X.oneOf!=null)X.oneOf=X.oneOf.map(AF);let{definitions:Y}=X;if(Y!=null)for(let Q of Object.keys(Y))Y[Q]=AF(Y[Q]);return X}function AF(X){if(typeof X==="boolean")return X;return qY0(X)}var sh6=Symbol("Let zodToJsonSchema decide on which parser to use"),CW1={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},th6=(X)=>typeof X==="string"?{...CW1,name:X}:{...CW1,...X};function lQ(){return{}}function eh6(X,Y){var Q,J,G;let W={type:"array"};if(((Q=X.type)==null?void 0:Q._def)&&((G=(J=X.type)==null?void 0:J._def)==null?void 0:G.typeName)!==j0.ZodAny)W.items=f4(X.type._def,{...Y,currentPath:[...Y.currentPath,"items"]});if(X.minLength)W.minItems=X.minLength.value;if(X.maxLength)W.maxItems=X.maxLength.value;if(X.exactLength)W.minItems=X.exactLength.value,W.maxItems=X.exactLength.value;return W}function Xx6(X){let Y={type:"integer",format:"int64"};if(!X.checks)return Y;for(let Q of X.checks)switch(Q.kind){case"min":if(Q.inclusive)Y.minimum=Q.value;else Y.exclusiveMinimum=Q.value;break;case"max":if(Q.inclusive)Y.maximum=Q.value;else Y.exclusiveMaximum=Q.value;break;case"multipleOf":Y.multipleOf=Q.value;break}return Y}function Yx6(){return{type:"boolean"}}function hW1(X,Y){return f4(X.type._def,Y)}var Qx6=(X,Y)=>{return f4(X.innerType._def,Y)};function xW1(X,Y,Q){let J=Q!=null?Q:Y.dateStrategy;if(Array.isArray(J))return{anyOf:J.map((G,W)=>xW1(X,Y,G))};switch(J){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Jx6(X)}}var Jx6=(X)=>{let Y={type:"integer",format:"unix-time"};for(let Q of X.checks)switch(Q.kind){case"min":Y.minimum=Q.value;break;case"max":Y.maximum=Q.value;break}return Y};function Gx6(X,Y){return{...f4(X.innerType._def,Y),default:X.defaultValue()}}function Wx6(X,Y){return Y.effectStrategy==="input"?f4(X.schema._def,Y):lQ()}function Zx6(X){return{type:"string",enum:Array.from(X.values)}}var $x6=(X)=>{if("type"in X&&X.type==="string")return!1;return"allOf"in X};function Kx6(X,Y){let Q=[f4(X.left._def,{...Y,currentPath:[...Y.currentPath,"allOf","0"]}),f4(X.right._def,{...Y,currentPath:[...Y.currentPath,"allOf","1"]})].filter((G)=>!!G),J=[];return Q.forEach((G)=>{if($x6(G))J.push(...G.allOf);else{let W=G;if("additionalProperties"in G&&G.additionalProperties===!1){let{additionalProperties:Z,...$}=G;W=$}J.push(W)}}),J.length?{allOf:J}:void 0}function Hx6(X){let Y=typeof X.value;if(Y!=="bigint"&&Y!=="number"&&Y!=="boolean"&&Y!=="string")return{type:Array.isArray(X.value)?"array":"object"};return{type:Y==="bigint"?"integer":Y,const:X.value}}var $Y0=void 0,u5={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:()=>{if($Y0===void 0)$Y0=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return $Y0},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function gW1(X,Y){let Q={type:"string"};if(X.checks)for(let J of X.checks)switch(J.kind){case"min":Q.minLength=typeof Q.minLength==="number"?Math.max(Q.minLength,J.value):J.value;break;case"max":Q.maxLength=typeof Q.maxLength==="number"?Math.min(Q.maxLength,J.value):J.value;break;case"email":switch(Y.emailStrategy){case"format:email":m5(Q,"email",J.message,Y);break;case"format:idn-email":m5(Q,"idn-email",J.message,Y);break;case"pattern:zod":T9(Q,u5.email,J.message,Y);break}break;case"url":m5(Q,"uri",J.message,Y);break;case"uuid":m5(Q,"uuid",J.message,Y);break;case"regex":T9(Q,J.regex,J.message,Y);break;case"cuid":T9(Q,u5.cuid,J.message,Y);break;case"cuid2":T9(Q,u5.cuid2,J.message,Y);break;case"startsWith":T9(Q,RegExp(`^${KY0(J.value,Y)}`),J.message,Y);break;case"endsWith":T9(Q,RegExp(`${KY0(J.value,Y)}$`),J.message,Y);break;case"datetime":m5(Q,"date-time",J.message,Y);break;case"date":m5(Q,"date",J.message,Y);break;case"time":m5(Q,"time",J.message,Y);break;case"duration":m5(Q,"duration",J.message,Y);break;case"length":Q.minLength=typeof Q.minLength==="number"?Math.max(Q.minLength,J.value):J.value,Q.maxLength=typeof Q.maxLength==="number"?Math.min(Q.maxLength,J.value):J.value;break;case"includes":{T9(Q,RegExp(KY0(J.value,Y)),J.message,Y);break}case"ip":{if(J.version!=="v6")m5(Q,"ipv4",J.message,Y);if(J.version!=="v4")m5(Q,"ipv6",J.message,Y);break}case"base64url":T9(Q,u5.base64url,J.message,Y);break;case"jwt":T9(Q,u5.jwt,J.message,Y);break;case"cidr":{if(J.version!=="v6")T9(Q,u5.ipv4Cidr,J.message,Y);if(J.version!=="v4")T9(Q,u5.ipv6Cidr,J.message,Y);break}case"emoji":T9(Q,u5.emoji(),J.message,Y);break;case"ulid":{T9(Q,u5.ulid,J.message,Y);break}case"base64":{switch(Y.base64Strategy){case"format:binary":{m5(Q,"binary",J.message,Y);break}case"contentEncoding:base64":{Q.contentEncoding="base64";break}case"pattern:zod":{T9(Q,u5.base64,J.message,Y);break}}break}case"nanoid":T9(Q,u5.nanoid,J.message,Y);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return Q}function KY0(X,Y){return Y.patternStrategy==="escape"?Vx6(X):X}var Fx6=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Vx6(X){let Y="";for(let Q=0;Q<X.length;Q++){if(!Fx6.has(X[Q]))Y+="\\";Y+=X[Q]}return Y}function m5(X,Y,Q,J){var G;if(X.format||((G=X.anyOf)==null?void 0:G.some((W)=>W.format))){if(!X.anyOf)X.anyOf=[];if(X.format)X.anyOf.push({format:X.format}),delete X.format;X.anyOf.push({format:Y,...Q&&J.errorMessages&&{errorMessage:{format:Q}}})}else X.format=Y}function T9(X,Y,Q,J){var G;if(X.pattern||((G=X.allOf)==null?void 0:G.some((W)=>W.pattern))){if(!X.allOf)X.allOf=[];if(X.pattern)X.allOf.push({pattern:X.pattern}),delete X.pattern;X.allOf.push({pattern:IW1(Y,J),...Q&&J.errorMessages&&{errorMessage:{pattern:Q}}})}else X.pattern=IW1(Y,J)}function IW1(X,Y){var Q;if(!Y.applyRegexFlags||!X.flags)return X.source;let J={i:X.flags.includes("i"),m:X.flags.includes("m"),s:X.flags.includes("s")},G=J.i?X.source.toLowerCase():X.source,W="",Z=!1,$=!1,K=!1;for(let H=0;H<G.length;H++){if(Z){W+=G[H],Z=!1;continue}if(J.i){if($){if(G[H].match(/[a-z]/)){if(K)W+=G[H],W+=`${G[H-2]}-${G[H]}`.toUpperCase(),K=!1;else if(G[H+1]==="-"&&((Q=G[H+2])==null?void 0:Q.match(/[a-z]/)))W+=G[H],K=!0;else W+=`${G[H]}${G[H].toUpperCase()}`;continue}}else if(G[H].match(/[a-z]/)){W+=`[${G[H]}${G[H].toUpperCase()}]`;continue}}if(J.m){if(G[H]==="^"){W+=`(^|(?<=[\r
1054
1054
  ]))`;continue}else if(G[H]==="$"){W+=`($|(?=[\r
1055
1055
  ]))`;continue}}if(J.s&&G[H]==="."){W+=$?`${G[H]}\r
@@ -1081,7 +1081,7 @@ Learn more: \x1B[34m${Q}\x1B[0m
1081
1081
 
1082
1082
  `)},flush(X){X.enqueue(`data: [DONE]
1083
1083
 
1084
- `)}})}},fK1={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function El6({status:X,statusText:Y,headers:Q,stream:J,consumeSseStream:G}){let W=J.pipeThrough(new bK1);if(G){let[Z,$]=W.tee();W=Z,G({stream:$})}return new Response(W.pipeThrough(new TextEncoderStream),{status:X,statusText:Y,headers:ob(Q,fK1)})}function jl6({originalMessages:X,responseMessageId:Y}){if(X==null)return;let Q=X[X.length-1];return(Q==null?void 0:Q.role)==="assistant"?Q.id:typeof Y==="function"?Y():Y}var st4=iX(()=>KX(U.union([U.strictObject({type:U.literal("text-start"),id:U.string(),providerMetadata:p1.optional()}),U.strictObject({type:U.literal("text-delta"),id:U.string(),delta:U.string(),providerMetadata:p1.optional()}),U.strictObject({type:U.literal("text-end"),id:U.string(),providerMetadata:p1.optional()}),U.strictObject({type:U.literal("error"),errorText:U.string()}),U.strictObject({type:U.literal("tool-input-start"),toolCallId:U.string(),toolName:U.string(),providerExecuted:U.boolean().optional(),providerMetadata:p1.optional(),dynamic:U.boolean().optional(),title:U.string().optional()}),U.strictObject({type:U.literal("tool-input-delta"),toolCallId:U.string(),inputTextDelta:U.string()}),U.strictObject({type:U.literal("tool-input-available"),toolCallId:U.string(),toolName:U.string(),input:U.unknown(),providerExecuted:U.boolean().optional(),providerMetadata:p1.optional(),dynamic:U.boolean().optional(),title:U.string().optional()}),U.strictObject({type:U.literal("tool-input-error"),toolCallId:U.string(),toolName:U.string(),input:U.unknown(),providerExecuted:U.boolean().optional(),providerMetadata:p1.optional(),dynamic:U.boolean().optional(),errorText:U.string(),title:U.string().optional()}),U.strictObject({type:U.literal("tool-approval-request"),approvalId:U.string(),toolCallId:U.string()}),U.strictObject({type:U.literal("tool-output-available"),toolCallId:U.string(),output:U.unknown(),providerExecuted:U.boolean().optional(),dynamic:U.boolean().optional(),preliminary:U.boolean().optional()}),U.strictObject({type:U.literal("tool-output-error"),toolCallId:U.string(),errorText:U.string(),providerExecuted:U.boolean().optional(),dynamic:U.boolean().optional()}),U.strictObject({type:U.literal("tool-output-denied"),toolCallId:U.string()}),U.strictObject({type:U.literal("reasoning-start"),id:U.string(),providerMetadata:p1.optional()}),U.strictObject({type:U.literal("reasoning-delta"),id:U.string(),delta:U.string(),providerMetadata:p1.optional()}),U.strictObject({type:U.literal("reasoning-end"),id:U.string(),providerMetadata:p1.optional()}),U.strictObject({type:U.literal("source-url"),sourceId:U.string(),url:U.string(),title:U.string().optional(),providerMetadata:p1.optional()}),U.strictObject({type:U.literal("source-document"),sourceId:U.string(),mediaType:U.string(),title:U.string(),filename:U.string().optional(),providerMetadata:p1.optional()}),U.strictObject({type:U.literal("file"),url:U.string(),mediaType:U.string(),providerMetadata:p1.optional()}),U.strictObject({type:U.custom((X)=>typeof X==="string"&&X.startsWith("data-"),{message:'Type must start with "data-"'}),id:U.string().optional(),data:U.unknown(),transient:U.boolean().optional()}),U.strictObject({type:U.literal("start-step")}),U.strictObject({type:U.literal("finish-step")}),U.strictObject({type:U.literal("start"),messageId:U.string().optional(),messageMetadata:U.unknown().optional()}),U.strictObject({type:U.literal("finish"),finishReason:U.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:U.unknown().optional()}),U.strictObject({type:U.literal("abort"),reason:U.string().optional()}),U.strictObject({type:U.literal("message-metadata"),messageMetadata:U.unknown()})])));function Cl6(X){return X.type.startsWith("data-")}function SY0(X){return X.type.startsWith("data-")}function kY0(X){return X.type==="text"}function vY0(X){return X.type==="file"}function D$1(X){return X.type==="reasoning"}function hY0(X){return X.type.startsWith("tool-")}function hK1(X){return X.type==="dynamic-tool"}function ZA(X){return hY0(X)||hK1(X)}function xY0(X){return X.type.split("-").slice(1).join("-")}function _Y0(X){return hK1(X)?X.toolName:xY0(X)}function Il6({lastMessage:X,messageId:Y}){return{message:(X==null?void 0:X.role)==="assistant"?X:{id:Y,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function Rl6({stream:X,messageMetadataSchema:Y,dataPartSchemas:Q,runUpdateMessageJob:J,onError:G,onToolCall:W,onData:Z}){return X.pipeThrough(new TransformStream({async transform($,K){await J(async({state:H,write:F})=>{var V,q,z,D;function N(T){let P=H.message.parts.filter(ZA).find((j)=>j.toolCallId===T);if(P==null)throw new UB({chunkType:"tool-invocation",chunkId:T,message:`No tool invocation found for tool call ID "${T}".`});return P}function L(T){var A;let P=H.message.parts.find((k)=>hY0(k)&&k.toolCallId===T.toolCallId),j=T,R=P;if(P!=null){if(P.state=T.state,R.input=j.input,R.output=j.output,R.errorText=j.errorText,R.rawInput=j.rawInput,R.preliminary=j.preliminary,T.title!==void 0)R.title=T.title;if(R.providerExecuted=(A=j.providerExecuted)!=null?A:P.providerExecuted,j.providerMetadata!=null)P.callProviderMetadata=j.providerMetadata}else H.message.parts.push({type:`tool-${T.toolName}`,toolCallId:T.toolCallId,state:T.state,title:T.title,input:j.input,output:j.output,rawInput:j.rawInput,errorText:j.errorText,providerExecuted:j.providerExecuted,preliminary:j.preliminary,...j.providerMetadata!=null?{callProviderMetadata:j.providerMetadata}:{}})}function w(T){var A,P;let j=H.message.parts.find((_)=>_.type==="dynamic-tool"&&_.toolCallId===T.toolCallId),R=T,k=j;if(j!=null){if(j.state=T.state,k.toolName=T.toolName,k.input=R.input,k.output=R.output,k.errorText=R.errorText,k.rawInput=(A=R.rawInput)!=null?A:k.rawInput,k.preliminary=R.preliminary,T.title!==void 0)k.title=T.title;if(k.providerExecuted=(P=R.providerExecuted)!=null?P:j.providerExecuted,R.providerMetadata!=null)j.callProviderMetadata=R.providerMetadata}else H.message.parts.push({type:"dynamic-tool",toolName:T.toolName,toolCallId:T.toolCallId,state:T.state,input:R.input,output:R.output,errorText:R.errorText,preliminary:R.preliminary,providerExecuted:R.providerExecuted,title:T.title,...R.providerMetadata!=null?{callProviderMetadata:R.providerMetadata}:{}})}async function C(T){if(T!=null){let A=H.message.metadata!=null?ib(H.message.metadata,T):T;if(Y!=null)await O7({value:A,schema:Y});H.message.metadata=A}}switch($.type){case"text-start":{let T={type:"text",text:"",providerMetadata:$.providerMetadata,state:"streaming"};H.activeTextParts[$.id]=T,H.message.parts.push(T),F();break}case"text-delta":{let T=H.activeTextParts[$.id];if(T==null)throw new UB({chunkType:"text-delta",chunkId:$.id,message:`Received text-delta for missing text part with ID "${$.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});T.text+=$.delta,T.providerMetadata=(V=$.providerMetadata)!=null?V:T.providerMetadata,F();break}case"text-end":{let T=H.activeTextParts[$.id];if(T==null)throw new UB({chunkType:"text-end",chunkId:$.id,message:`Received text-end for missing text part with ID "${$.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});T.state="done",T.providerMetadata=(q=$.providerMetadata)!=null?q:T.providerMetadata,delete H.activeTextParts[$.id],F();break}case"reasoning-start":{let T={type:"reasoning",text:"",providerMetadata:$.providerMetadata,state:"streaming"};H.activeReasoningParts[$.id]=T,H.message.parts.push(T),F();break}case"reasoning-delta":{let T=H.activeReasoningParts[$.id];if(T==null)throw new UB({chunkType:"reasoning-delta",chunkId:$.id,message:`Received reasoning-delta for missing reasoning part with ID "${$.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});T.text+=$.delta,T.providerMetadata=(z=$.providerMetadata)!=null?z:T.providerMetadata,F();break}case"reasoning-end":{let T=H.activeReasoningParts[$.id];if(T==null)throw new UB({chunkType:"reasoning-end",chunkId:$.id,message:`Received reasoning-end for missing reasoning part with ID "${$.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});T.providerMetadata=(D=$.providerMetadata)!=null?D:T.providerMetadata,T.state="done",delete H.activeReasoningParts[$.id],F();break}case"file":{H.message.parts.push({type:"file",mediaType:$.mediaType,url:$.url}),F();break}case"source-url":{H.message.parts.push({type:"source-url",sourceId:$.sourceId,url:$.url,title:$.title,providerMetadata:$.providerMetadata}),F();break}case"source-document":{H.message.parts.push({type:"source-document",sourceId:$.sourceId,mediaType:$.mediaType,title:$.title,filename:$.filename,providerMetadata:$.providerMetadata}),F();break}case"tool-input-start":{let T=H.message.parts.filter(hY0);if(H.partialToolCalls[$.toolCallId]={text:"",toolName:$.toolName,index:T.length,dynamic:$.dynamic,title:$.title},$.dynamic)w({toolCallId:$.toolCallId,toolName:$.toolName,state:"input-streaming",input:void 0,providerExecuted:$.providerExecuted,title:$.title,providerMetadata:$.providerMetadata});else L({toolCallId:$.toolCallId,toolName:$.toolName,state:"input-streaming",input:void 0,providerExecuted:$.providerExecuted,title:$.title,providerMetadata:$.providerMetadata});F();break}case"tool-input-delta":{let T=H.partialToolCalls[$.toolCallId];if(T==null)throw new UB({chunkType:"tool-input-delta",chunkId:$.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${$.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});T.text+=$.inputTextDelta;let{value:A}=await VA(T.text);if(T.dynamic)w({toolCallId:$.toolCallId,toolName:T.toolName,state:"input-streaming",input:A,title:T.title});else L({toolCallId:$.toolCallId,toolName:T.toolName,state:"input-streaming",input:A,title:T.title});F();break}case"tool-input-available":{if($.dynamic)w({toolCallId:$.toolCallId,toolName:$.toolName,state:"input-available",input:$.input,providerExecuted:$.providerExecuted,providerMetadata:$.providerMetadata,title:$.title});else L({toolCallId:$.toolCallId,toolName:$.toolName,state:"input-available",input:$.input,providerExecuted:$.providerExecuted,providerMetadata:$.providerMetadata,title:$.title});if(F(),W&&!$.providerExecuted)await W({toolCall:$});break}case"tool-input-error":{if($.dynamic)w({toolCallId:$.toolCallId,toolName:$.toolName,state:"output-error",input:$.input,errorText:$.errorText,providerExecuted:$.providerExecuted,providerMetadata:$.providerMetadata});else L({toolCallId:$.toolCallId,toolName:$.toolName,state:"output-error",input:void 0,rawInput:$.input,errorText:$.errorText,providerExecuted:$.providerExecuted,providerMetadata:$.providerMetadata});F();break}case"tool-approval-request":{let T=N($.toolCallId);T.state="approval-requested",T.approval={id:$.approvalId},F();break}case"tool-output-denied":{let T=N($.toolCallId);T.state="output-denied",F();break}case"tool-output-available":{let T=N($.toolCallId);if(T.type==="dynamic-tool")w({toolCallId:$.toolCallId,toolName:T.toolName,state:"output-available",input:T.input,output:$.output,preliminary:$.preliminary,providerExecuted:$.providerExecuted,title:T.title});else L({toolCallId:$.toolCallId,toolName:xY0(T),state:"output-available",input:T.input,output:$.output,providerExecuted:$.providerExecuted,preliminary:$.preliminary,title:T.title});F();break}case"tool-output-error":{let T=N($.toolCallId);if(T.type==="dynamic-tool")w({toolCallId:$.toolCallId,toolName:T.toolName,state:"output-error",input:T.input,errorText:$.errorText,providerExecuted:$.providerExecuted,title:T.title});else L({toolCallId:$.toolCallId,toolName:xY0(T),state:"output-error",input:T.input,rawInput:T.rawInput,errorText:$.errorText,providerExecuted:$.providerExecuted,title:T.title});F();break}case"start-step":{H.message.parts.push({type:"step-start"});break}case"finish-step":{H.activeTextParts={},H.activeReasoningParts={};break}case"start":{if($.messageId!=null)H.message.id=$.messageId;if(await C($.messageMetadata),$.messageId!=null||$.messageMetadata!=null)F();break}case"finish":{if($.finishReason!=null)H.finishReason=$.finishReason;if(await C($.messageMetadata),$.messageMetadata!=null)F();break}case"message-metadata":{if(await C($.messageMetadata),$.messageMetadata!=null)F();break}case"error":{G==null||G(Error($.errorText));break}default:if(Cl6($)){if((Q==null?void 0:Q[$.type])!=null)await O7({value:$.data,schema:Q[$.type]});let T=$;if(T.transient){Z==null||Z(T);break}let A=T.id!=null?H.message.parts.find((P)=>T.type===P.type&&T.id===P.id):void 0;if(A!=null)A.data=T.data;else H.message.parts.push(T);Z==null||Z(T),F()}}K.enqueue($)})}}))}function Sl6({messageId:X,originalMessages:Y=[],onFinish:Q,onError:J,stream:G}){let W=Y==null?void 0:Y[Y.length-1];if((W==null?void 0:W.role)!=="assistant")W=void 0;else X=W.id;let Z=!1,$=G.pipeThrough(new TransformStream({transform(q,z){if(q.type==="start"){let D=q;if(D.messageId==null&&X!=null)D.messageId=X}if(q.type==="abort")Z=!0;z.enqueue(q)}}));if(Q==null)return $;let K=Il6({lastMessage:W?structuredClone(W):void 0,messageId:X!=null?X:""}),H=async(q)=>{await q({state:K,write:()=>{}})},F=!1,V=async()=>{if(F||!Q)return;F=!0;let q=K.message.id===(W==null?void 0:W.id);await Q({isAborted:Z,isContinuation:q,responseMessage:K.message,messages:[...q?Y.slice(0,-1):Y,K.message],finishReason:K.finishReason})};return Rl6({stream:$,runUpdateMessageJob:H,onError:J}).pipeThrough(new TransformStream({transform(q,z){z.enqueue(q)},async cancel(){await V()},async flush(){await V()}}))}function kl6({response:X,status:Y,statusText:Q,headers:J,stream:G,consumeSseStream:W}){let Z=G.pipeThrough(new bK1);if(W){let[$,K]=Z.tee();Z=$,W({stream:K})}yK1({response:X,status:Y,statusText:Q,headers:Object.fromEntries(ob(J,fK1).entries()),stream:Z.pipeThrough(new TextEncoderStream)})}function WA(X){let Y=X.pipeThrough(new TransformStream);return Y[Symbol.asyncIterator]=function(){let Q=this.getReader(),J=!1;async function G(W){var Z;if(J)return;J=!0;try{if(W)await((Z=Q.cancel)==null?void 0:Z.call(Q))}finally{try{Q.releaseLock()}catch($){}}}return{async next(){if(J)return{done:!0,value:void 0};let{done:W,value:Z}=await Q.read();if(W)return await G(!0),{done:!0,value:void 0};return{done:!1,value:Z}},async return(){return await G(!0),{done:!0,value:void 0}},async throw(W){throw await G(!0),W}}},Y}async function pY0({stream:X,onError:Y}){let Q=X.getReader();try{while(!0){let{done:J}=await Q.read();if(J)break}}catch(J){Y==null||Y(J)}finally{Q.releaseLock()}}function N$1(){let X,Y;return{promise:new Promise((J,G)=>{X=J,Y=G}),resolve:X,reject:Y}}function vl6(){let X=[],Y=null,Q=!1,J=N$1(),G=()=>{Q=!0,J.resolve(),X.forEach((Z)=>Z.cancel()),X=[],Y==null||Y.close()},W=async()=>{if(Q&&X.length===0){Y==null||Y.close();return}if(X.length===0)return J=N$1(),await J.promise,W();try{let{value:Z,done:$}=await X[0].read();if($)if(X.shift(),X.length===0&&Q)Y==null||Y.close();else await W();else Y==null||Y.enqueue(Z)}catch(Z){Y==null||Y.error(Z),X.shift(),G()}};return{stream:new ReadableStream({start(Z){Y=Z},pull:W,async cancel(){for(let Z of X)await Z.cancel();X=[],Q=!0}}),addStream:(Z)=>{if(Q)throw Error("Cannot add inner stream: outer stream is closed");X.push(Z.getReader()),J.resolve()},close:()=>{if(Q=!0,J.resolve(),X.length===0)Y==null||Y.close()},terminate:G}}function _l6(){var X,Y;return(Y=(X=globalThis==null?void 0:globalThis.performance)==null?void 0:X.now())!=null?Y:Date.now()}function yl6({tools:X,generatorStream:Y,tracer:Q,telemetry:J,system:G,messages:W,abortSignal:Z,repairToolCall:$,experimental_context:K,generateId:H}){let F=null,V=new ReadableStream({start(T){F=T}}),q=new Set,z=new Map,D=new Map,N=!1,L=void 0;function w(){if(N&&q.size===0){if(L!=null)F.enqueue(L);F.close()}}let C=new TransformStream({async transform(T,A){let P=T.type;switch(P){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":{A.enqueue(T);break}case"file":{A.enqueue({type:"file",file:new Ul6({data:T.data,mediaType:T.mediaType})});break}case"finish":{L={type:"finish",finishReason:T.finishReason.unified,rawFinishReason:T.finishReason.raw,usage:PK1(T.usage),providerMetadata:T.providerMetadata};break}case"tool-approval-request":{let j=D.get(T.toolCallId);if(j==null){F.enqueue({type:"error",error:new uY0({toolCallId:T.toolCallId,approvalId:T.approvalId})});break}A.enqueue({type:"tool-approval-request",approvalId:T.approvalId,toolCall:j});break}case"tool-call":{try{let j=await RK1({toolCall:T,tools:X,repairToolCall:$,system:G,messages:W});if(D.set(j.toolCallId,j),A.enqueue(j),j.invalid){F.enqueue({type:"tool-error",toolCallId:j.toolCallId,toolName:j.toolName,input:j.input,error:KB(j.error),dynamic:!0,title:j.title});break}let R=X==null?void 0:X[j.toolName];if(R==null)break;if(R.onInputAvailable!=null)await R.onInputAvailable({input:j.input,toolCallId:j.toolCallId,messages:W,abortSignal:Z,experimental_context:K});if(await IK1({tool:R,toolCall:j,messages:W,experimental_context:K})){F.enqueue({type:"tool-approval-request",approvalId:H(),toolCall:j});break}if(z.set(j.toolCallId,j.input),R.execute!=null&&j.providerExecuted!==!0){let k=H();q.add(k),dY0({toolCall:j,tools:X,tracer:Q,telemetry:J,messages:W,abortSignal:Z,experimental_context:K,onPreliminaryToolResult:(_)=>{F.enqueue(_)}}).then((_)=>{F.enqueue(_)}).catch((_)=>{F.enqueue({type:"error",error:_})}).finally(()=>{q.delete(k),w()})}}catch(j){F.enqueue({type:"error",error:j})}break}case"tool-result":{let j=T.toolName;if(T.isError)F.enqueue({type:"tool-error",toolCallId:T.toolCallId,toolName:j,input:z.get(T.toolCallId),providerExecuted:!0,error:T.result,dynamic:T.dynamic});else A.enqueue({type:"tool-result",toolCallId:T.toolCallId,toolName:j,input:z.get(T.toolCallId),output:T.result,providerExecuted:!0,dynamic:T.dynamic});break}default:throw Error(`Unhandled chunk type: ${P}`)}},flush(){N=!0,w()}});return new ReadableStream({async start(T){return Promise.all([Y.pipeThrough(C).pipeTo(new WritableStream({write(A){T.enqueue(A)},close(){}})),V.pipeTo(new WritableStream({write(A){T.enqueue(A)},close(){T.close()}}))])}})}var bl6=D7({prefix:"aitxt",size:24});function sb({model:X,tools:Y,toolChoice:Q,system:J,prompt:G,messages:W,maxRetries:Z,abortSignal:$,timeout:K,headers:H,stopWhen:F=ab(1),experimental_output:V,output:q=V,experimental_telemetry:z,prepareStep:D,providerOptions:N,experimental_activeTools:L,activeTools:w=L,experimental_repairToolCall:C,experimental_transform:T,experimental_download:A,includeRawChunks:P=!1,onChunk:j,onError:R=({error:f})=>{console.error(f)},onFinish:k,onAbort:_,onStepFinish:y,experimental_context:b,_internal:{now:r=_l6,generateId:x=bl6}={},...S}){let f=lY0(K),t=ZK1(K),m=gm6(K),J0=t!=null?new AbortController:void 0,V0=m!=null?new AbortController:void 0;return new hl6({model:cb(X),telemetry:z,headers:H,settings:S,maxRetries:Z,abortSignal:_K1($,f!=null?AbortSignal.timeout(f):void 0,J0==null?void 0:J0.signal,V0==null?void 0:V0.signal),stepTimeoutMs:t,stepAbortController:J0,chunkTimeoutMs:m,chunkAbortController:V0,system:J,prompt:G,messages:W,tools:Y,toolChoice:Q,transforms:$A(T),activeTools:w,repairToolCall:C,stopConditions:$A(F),output:q,providerOptions:N,prepareStep:D,includeRawChunks:P,onChunk:j,onError:R,onFinish:k,onAbort:_,onStepFinish:y,now:r,generateId:x,experimental_context:b,download:A})}function fl6(X){let Y=void 0,Q="",J="",G=void 0,W="";function Z({controller:$,partialOutput:K=void 0}){$.enqueue({part:{type:"text-delta",id:Y,text:J,providerMetadata:G},partialOutput:K}),J=""}return new TransformStream({async transform($,K){var H;if($.type==="finish-step"&&J.length>0)Z({controller:K});if($.type!=="text-delta"&&$.type!=="text-start"&&$.type!=="text-end"){K.enqueue({part:$,partialOutput:void 0});return}if(Y==null)Y=$.id;else if($.id!==Y){K.enqueue({part:$,partialOutput:void 0});return}if($.type==="text-start"){K.enqueue({part:$,partialOutput:void 0});return}if($.type==="text-end"){if(J.length>0)Z({controller:K});K.enqueue({part:$,partialOutput:void 0});return}Q+=$.text,J+=$.text,G=(H=$.providerMetadata)!=null?H:G;let F=await X.parsePartialOutput({text:Q});if(F!==void 0){let V=JSON.stringify(F.partial);if(V!==W)Z({controller:K,partialOutput:F.partial}),W=V}}})}var hl6=class{constructor({model:X,telemetry:Y,headers:Q,settings:J,maxRetries:G,abortSignal:W,stepTimeoutMs:Z,stepAbortController:$,chunkTimeoutMs:K,chunkAbortController:H,system:F,prompt:V,messages:q,tools:z,toolChoice:D,transforms:N,activeTools:L,repairToolCall:w,stopConditions:C,output:T,providerOptions:A,prepareStep:P,includeRawChunks:j,now:R,generateId:k,onChunk:_,onError:y,onFinish:b,onAbort:r,onStepFinish:x,experimental_context:S,download:f}){this._totalUsage=new EF,this._finishReason=new EF,this._rawFinishReason=new EF,this._steps=new EF,this.outputSpecification=T,this.includeRawChunks=j,this.tools=z;let t,m=[],J0=[],V0=void 0,Y0=void 0,U0=void 0,P0={},v0=[],G1=[],N0=new Map,W0,I0={},f1={},x1=new TransformStream({async transform(H1,k1){var c1,M1,Y1,w0;k1.enqueue(H1);let{part:A0}=H1;if(A0.type==="text-delta"||A0.type==="reasoning-delta"||A0.type==="source"||A0.type==="tool-call"||A0.type==="tool-result"||A0.type==="tool-input-start"||A0.type==="tool-input-delta"||A0.type==="raw")await(_==null?void 0:_({chunk:A0}));if(A0.type==="error")await y({error:DK1(A0.error)});if(A0.type==="text-start")I0[A0.id]={type:"text",text:"",providerMetadata:A0.providerMetadata},m.push(I0[A0.id]);if(A0.type==="text-delta"){let i1=I0[A0.id];if(i1==null){k1.enqueue({part:{type:"error",error:`text part ${A0.id} not found`},partialOutput:void 0});return}i1.text+=A0.text,i1.providerMetadata=(c1=A0.providerMetadata)!=null?c1:i1.providerMetadata}if(A0.type==="text-end"){let i1=I0[A0.id];if(i1==null){k1.enqueue({part:{type:"error",error:`text part ${A0.id} not found`},partialOutput:void 0});return}i1.providerMetadata=(M1=A0.providerMetadata)!=null?M1:i1.providerMetadata,delete I0[A0.id]}if(A0.type==="reasoning-start")f1[A0.id]={type:"reasoning",text:"",providerMetadata:A0.providerMetadata},m.push(f1[A0.id]);if(A0.type==="reasoning-delta"){let i1=f1[A0.id];if(i1==null){k1.enqueue({part:{type:"error",error:`reasoning part ${A0.id} not found`},partialOutput:void 0});return}i1.text+=A0.text,i1.providerMetadata=(Y1=A0.providerMetadata)!=null?Y1:i1.providerMetadata}if(A0.type==="reasoning-end"){let i1=f1[A0.id];if(i1==null){k1.enqueue({part:{type:"error",error:`reasoning part ${A0.id} not found`},partialOutput:void 0});return}i1.providerMetadata=(w0=A0.providerMetadata)!=null?w0:i1.providerMetadata,delete f1[A0.id]}if(A0.type==="file")m.push({type:"file",file:A0.file});if(A0.type==="source")m.push(A0);if(A0.type==="tool-call")m.push(A0);if(A0.type==="tool-result"&&!A0.preliminary)m.push(A0);if(A0.type==="tool-approval-request")m.push(A0);if(A0.type==="tool-error")m.push(A0);if(A0.type==="start-step")m=[],f1={},I0={},P0=A0.request,v0=A0.warnings;if(A0.type==="finish-step"){let i1=await fY0({content:m,tools:z}),$6=new kK1({content:m,finishReason:A0.finishReason,rawFinishReason:A0.rawFinishReason,usage:A0.usage,warnings:v0,request:P0,response:{...A0.response,messages:[...J0,...i1]},providerMetadata:A0.providerMetadata});await(x==null?void 0:x($6)),mY0({warnings:v0,provider:X.provider,model:X.modelId}),G1.push($6),J0.push(...i1),t.resolve()}if(A0.type==="finish")U0=A0.totalUsage,V0=A0.finishReason,Y0=A0.rawFinishReason},async flush(H1){try{if(G1.length===0){let Y1=(W==null?void 0:W.aborted)?W.reason:new g$1({message:"No output generated. Check the stream for errors."});S0._finishReason.reject(Y1),S0._rawFinishReason.reject(Y1),S0._totalUsage.reject(Y1),S0._steps.reject(Y1);return}let k1=V0!=null?V0:"other",c1=U0!=null?U0:RY0();S0._finishReason.resolve(k1),S0._rawFinishReason.resolve(Y0),S0._totalUsage.resolve(c1),S0._steps.resolve(G1);let M1=G1[G1.length-1];await(b==null?void 0:b({finishReason:M1.finishReason,rawFinishReason:M1.rawFinishReason,totalUsage:c1,usage:M1.usage,content:M1.content,text:M1.text,reasoningText:M1.reasoningText,reasoning:M1.reasoning,files:M1.files,sources:M1.sources,toolCalls:M1.toolCalls,staticToolCalls:M1.staticToolCalls,dynamicToolCalls:M1.dynamicToolCalls,toolResults:M1.toolResults,staticToolResults:M1.staticToolResults,dynamicToolResults:M1.dynamicToolResults,request:M1.request,response:M1.response,warnings:M1.warnings,providerMetadata:M1.providerMetadata,steps:G1,experimental_context:S})),W0.setAttributes(await w7({telemetry:Y,attributes:{"ai.response.finishReason":k1,"ai.response.text":{output:()=>M1.text},"ai.response.toolCalls":{output:()=>{var Y1;return((Y1=M1.toolCalls)==null?void 0:Y1.length)?JSON.stringify(M1.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(M1.providerMetadata),"ai.usage.inputTokens":c1.inputTokens,"ai.usage.outputTokens":c1.outputTokens,"ai.usage.totalTokens":c1.totalTokens,"ai.usage.reasoningTokens":c1.reasoningTokens,"ai.usage.cachedInputTokens":c1.cachedInputTokens}}))}catch(k1){H1.error(k1)}finally{W0.end()}}}),_0=vl6();this.addStream=_0.addStream,this.closeStream=_0.close;let L0=_0.stream.getReader(),$0=new ReadableStream({async start(H1){H1.enqueue({type:"start"})},async pull(H1){function k1(){r==null||r({steps:G1}),H1.enqueue({type:"abort",...(W==null?void 0:W.reason)!==void 0?{reason:g5(W.reason)}:{}}),H1.close()}try{let{done:c1,value:M1}=await L0.read();if(c1){H1.close();return}if(W==null?void 0:W.aborted){k1();return}H1.enqueue(M1)}catch(c1){if(eW(c1)&&(W==null?void 0:W.aborted))k1();else H1.error(c1)}},cancel(H1){return _0.stream.cancel(H1)}});for(let H1 of N)$0=$0.pipeThrough(H1({tools:z,stopStream(){_0.terminate()}}));this.baseStream=$0.pipeThrough(fl6(T!=null?T:nb())).pipeThrough(x1);let{maxRetries:E0,retry:H0}=EK1({maxRetries:G,abortSignal:W}),D0=LK1(Y),r0=bY0(J),k0=NK1({model:X,telemetry:Y,headers:Q,settings:{...r0,maxRetries:E0}}),S0=this;FA({name:"ai.streamText",attributes:w7({telemetry:Y,attributes:{...HA({operationId:"ai.streamText",telemetry:Y}),...k0,"ai.prompt":{input:()=>JSON.stringify({system:F,prompt:V,messages:q})}}}),tracer:D0,endWhenDone:!1,fn:async(H1)=>{W0=H1;let k1=await BK1({system:F,prompt:V,messages:q}),c1=k1.messages,M1=[],{approvedToolApprovals:Y1,deniedToolApprovals:w0}=jK1({messages:c1});if(w0.length>0||Y1.length>0){let i1=[...Y1,...w0].filter((O)=>O.toolCall.providerExecuted),$6=Y1.filter((O)=>!O.toolCall.providerExecuted),F4=w0.filter((O)=>!O.toolCall.providerExecuted),J1=w0.filter((O)=>O.toolCall.providerExecuted),w1,FQ=new ReadableStream({start(O){w1=O}});S0.addStream(FQ);try{for(let v of[...F4,...J1])w1==null||w1.enqueue({type:"tool-output-denied",toolCallId:v.toolCall.toolCallId,toolName:v.toolCall.toolName});let O=[];if(await Promise.all($6.map(async(v)=>{let o=await dY0({toolCall:v.toolCall,tools:z,tracer:D0,telemetry:Y,messages:c1,abortSignal:W,experimental_context:S,onPreliminaryToolResult:(G0)=>{w1==null||w1.enqueue(G0)}});if(o!=null)w1==null||w1.enqueue(o),O.push(o)})),i1.length>0)M1.push({role:"tool",content:i1.map((v)=>({type:"tool-approval-response",approvalId:v.approvalResponse.approvalId,approved:v.approvalResponse.approved,reason:v.approvalResponse.reason,providerExecuted:!0}))});if(O.length>0||F4.length>0){let v=[];for(let o of O)v.push({type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:await SF({toolCallId:o.toolCallId,input:o.input,tool:z==null?void 0:z[o.toolName],output:o.type==="tool-result"?o.output:o.error,errorMode:o.type==="tool-error"?"json":"none"})});for(let o of F4)v.push({type:"tool-result",toolCallId:o.toolCall.toolCallId,toolName:o.toolCall.toolName,output:{type:"execution-denied",reason:o.approvalResponse.reason}});M1.push({role:"tool",content:v})}}finally{w1==null||w1.close()}}J0.push(...M1);async function A0({currentStep:i1,responseMessages:$6,usage:F4}){var J1,w1,FQ,O,v,o;let G0=S0.includeRawChunks,B=Z!=null?setTimeout(()=>$.abort(),Z):void 0,E=void 0;function c(){if(K!=null){if(E!=null)clearTimeout(E);E=setTimeout(()=>H.abort(),K)}}function e(){if(E!=null)clearTimeout(E),E=void 0}function X0(){if(B!=null)clearTimeout(B)}t=new EF;let n=[...c1,...$6],C0=await(P==null?void 0:P({model:X,steps:G1,stepNumber:G1.length,messages:n,experimental_context:S})),P1=cb((J1=C0==null?void 0:C0.model)!=null?J1:X),n1=await FK1({prompt:{system:(w1=C0==null?void 0:C0.system)!=null?w1:k1.system,messages:(FQ=C0==null?void 0:C0.messages)!=null?FQ:n},supportedUrls:await P1.supportedUrls,download:f}),{toolChoice:b0,tools:y1}=await VK1({tools:z,toolChoice:(O=C0==null?void 0:C0.toolChoice)!=null?O:D,activeTools:(v=C0==null?void 0:C0.activeTools)!=null?v:L});S=(o=C0==null?void 0:C0.experimental_context)!=null?o:S;let I8=ib(A,C0==null?void 0:C0.providerOptions),{result:{stream:MX,response:_6,request:R4},doStreamSpan:aX,startTimestampMs:c5}=await H0(()=>FA({name:"ai.streamText.doStream",attributes:w7({telemetry:Y,attributes:{...HA({operationId:"ai.streamText.doStream",telemetry:Y}),...k0,"ai.model.provider":P1.provider,"ai.model.id":P1.modelId,"ai.prompt.messages":{input:()=>MK1(n1)},"ai.prompt.tools":{input:()=>y1==null?void 0:y1.map((a1)=>JSON.stringify(a1))},"ai.prompt.toolChoice":{input:()=>b0!=null?JSON.stringify(b0):void 0},"gen_ai.system":P1.provider,"gen_ai.request.model":P1.modelId,"gen_ai.request.frequency_penalty":r0.frequencyPenalty,"gen_ai.request.max_tokens":r0.maxOutputTokens,"gen_ai.request.presence_penalty":r0.presencePenalty,"gen_ai.request.stop_sequences":r0.stopSequences,"gen_ai.request.temperature":r0.temperature,"gen_ai.request.top_k":r0.topK,"gen_ai.request.top_p":r0.topP}}),tracer:D0,endWhenDone:!1,fn:async(a1)=>({startTimestampMs:R(),doStreamSpan:a1,result:await P1.doStream({...r0,tools:y1,toolChoice:b0,responseFormat:await(T==null?void 0:T.responseFormat),prompt:n1,providerOptions:I8,abortSignal:W,headers:Q,includeRawChunks:G0})})})),X1=yl6({tools:z,generatorStream:MX,tracer:D0,telemetry:Y,system:F,messages:n,repairToolCall:w,abortSignal:W,experimental_context:S,generateId:k}),A6=R4!=null?R4:{},R8=[],AY=[],e0,T6={},h8="other",pQ=void 0,VQ=RY0(),Qf,aY0=!0,n5={id:k(),timestamp:new Date,modelId:X.modelId},rY0="";S0.addStream(X1.pipeThrough(new TransformStream({async transform(a1,rX){var NB,OB,UA,PX,kF;if(c(),a1.type==="stream-start"){e0=a1.warnings;return}if(aY0){let HX=R()-c5;aY0=!1,aX.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":HX}),aX.setAttributes({"ai.response.msToFirstChunk":HX}),rX.enqueue({type:"start-step",request:A6,warnings:e0!=null?e0:[]})}let Jf=a1.type;switch(Jf){case"tool-approval-request":case"text-start":case"text-end":{rX.enqueue(a1);break}case"text-delta":{if(a1.delta.length>0)rX.enqueue({type:"text-delta",id:a1.id,text:a1.delta,providerMetadata:a1.providerMetadata}),rY0+=a1.delta;break}case"reasoning-start":case"reasoning-end":{rX.enqueue(a1);break}case"reasoning-delta":{rX.enqueue({type:"reasoning-delta",id:a1.id,text:a1.delta,providerMetadata:a1.providerMetadata});break}case"tool-call":{rX.enqueue(a1),R8.push(a1);break}case"tool-result":{if(rX.enqueue(a1),!a1.preliminary)AY.push(a1);break}case"tool-error":{rX.enqueue(a1),AY.push(a1);break}case"response-metadata":{n5={id:(NB=a1.id)!=null?NB:n5.id,timestamp:(OB=a1.timestamp)!=null?OB:n5.timestamp,modelId:(UA=a1.modelId)!=null?UA:n5.modelId};break}case"finish":{VQ=a1.usage,h8=a1.finishReason,pQ=a1.rawFinishReason,Qf=a1.providerMetadata;let HX=R()-c5;aX.addEvent("ai.stream.finish"),aX.setAttributes({"ai.response.msToFinish":HX,"ai.response.avgOutputTokensPerSecond":1000*((PX=VQ.outputTokens)!=null?PX:0)/HX});break}case"file":{rX.enqueue(a1);break}case"source":{rX.enqueue(a1);break}case"tool-input-start":{T6[a1.id]=a1.toolName;let HX=z==null?void 0:z[a1.toolName];if((HX==null?void 0:HX.onInputStart)!=null)await HX.onInputStart({toolCallId:a1.id,messages:n,abortSignal:W,experimental_context:S});rX.enqueue({...a1,dynamic:(kF=a1.dynamic)!=null?kF:(HX==null?void 0:HX.type)==="dynamic",title:HX==null?void 0:HX.title});break}case"tool-input-end":{delete T6[a1.id],rX.enqueue(a1);break}case"tool-input-delta":{let HX=T6[a1.id],Gf=z==null?void 0:z[HX];if((Gf==null?void 0:Gf.onInputDelta)!=null)await Gf.onInputDelta({inputTextDelta:a1.delta,toolCallId:a1.id,messages:n,abortSignal:W,experimental_context:S});rX.enqueue(a1);break}case"error":{rX.enqueue(a1),h8="error";break}case"raw":{if(G0)rX.enqueue(a1);break}default:throw Error(`Unknown chunk type: ${Jf}`)}},async flush(a1){let rX=R8.length>0?JSON.stringify(R8):void 0;try{aX.setAttributes(await w7({telemetry:Y,attributes:{"ai.response.finishReason":h8,"ai.response.text":{output:()=>rY0},"ai.response.toolCalls":{output:()=>rX},"ai.response.id":n5.id,"ai.response.model":n5.modelId,"ai.response.timestamp":n5.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Qf),"ai.usage.inputTokens":VQ.inputTokens,"ai.usage.outputTokens":VQ.outputTokens,"ai.usage.totalTokens":VQ.totalTokens,"ai.usage.reasoningTokens":VQ.reasoningTokens,"ai.usage.cachedInputTokens":VQ.cachedInputTokens,"gen_ai.response.finish_reasons":[h8],"gen_ai.response.id":n5.id,"gen_ai.response.model":n5.modelId,"gen_ai.usage.input_tokens":VQ.inputTokens,"gen_ai.usage.output_tokens":VQ.outputTokens}}))}catch(PX){}finally{aX.end()}a1.enqueue({type:"finish-step",finishReason:h8,rawFinishReason:pQ,usage:VQ,providerMetadata:Qf,response:{...n5,headers:_6==null?void 0:_6.headers}});let NB=AK1(F4,VQ);await t.promise;let OB=R8.filter((PX)=>PX.providerExecuted!==!0),UA=AY.filter((PX)=>PX.providerExecuted!==!0);for(let PX of R8){if(PX.providerExecuted!==!0)continue;let kF=z==null?void 0:z[PX.toolName];if((kF==null?void 0:kF.type)==="provider"&&kF.supportsDeferredResults){if(!AY.some((HX)=>HX.type==="tool-result"&&HX.toolCallId===PX.toolCallId))N0.set(PX.toolCallId,{toolName:PX.toolName})}}for(let PX of AY)if(PX.type==="tool-result")N0.delete(PX.toolCallId);if(X0(),e(),(OB.length>0&&UA.length===OB.length||N0.size>0)&&!await vK1({stopConditions:C,steps:G1})){$6.push(...await fY0({content:G1[G1.length-1].content,tools:z}));try{await A0({currentStep:i1+1,responseMessages:$6,usage:NB})}catch(PX){a1.enqueue({type:"error",error:PX}),S0.closeStream()}}else a1.enqueue({type:"finish",finishReason:h8,rawFinishReason:pQ,totalUsage:NB}),S0.closeStream()}})))}await A0({currentStep:0,responseMessages:M1,usage:RY0()})}}).catch((H1)=>{S0.addStream(new ReadableStream({start(k1){k1.enqueue({type:"error",error:H1}),k1.close()}})),S0.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then((X)=>X[X.length-1])}get content(){return this.finalStep.then((X)=>X.content)}get warnings(){return this.finalStep.then((X)=>X.warnings)}get providerMetadata(){return this.finalStep.then((X)=>X.providerMetadata)}get text(){return this.finalStep.then((X)=>X.text)}get reasoningText(){return this.finalStep.then((X)=>X.reasoningText)}get reasoning(){return this.finalStep.then((X)=>X.reasoning)}get sources(){return this.finalStep.then((X)=>X.sources)}get files(){return this.finalStep.then((X)=>X.files)}get toolCalls(){return this.finalStep.then((X)=>X.toolCalls)}get staticToolCalls(){return this.finalStep.then((X)=>X.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then((X)=>X.dynamicToolCalls)}get toolResults(){return this.finalStep.then((X)=>X.toolResults)}get staticToolResults(){return this.finalStep.then((X)=>X.staticToolResults)}get dynamicToolResults(){return this.finalStep.then((X)=>X.dynamicToolResults)}get usage(){return this.finalStep.then((X)=>X.usage)}get request(){return this.finalStep.then((X)=>X.request)}get response(){return this.finalStep.then((X)=>X.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}get rawFinishReason(){return this.consumeStream(),this._rawFinishReason.promise}teeStream(){let[X,Y]=this.baseStream.tee();return this.baseStream=Y,X}get textStream(){return WA(this.teeStream().pipeThrough(new TransformStream({transform({part:X},Y){if(X.type==="text-delta")Y.enqueue(X.text)}})))}get fullStream(){return WA(this.teeStream().pipeThrough(new TransformStream({transform({part:X},Y){Y.enqueue(X)}})))}async consumeStream(X){var Y;try{await pY0({stream:this.fullStream,onError:X==null?void 0:X.onError})}catch(Q){(Y=X==null?void 0:X.onError)==null||Y.call(X,Q)}}get experimental_partialOutputStream(){return this.partialOutputStream}get partialOutputStream(){return WA(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:X},Y){if(X!=null)Y.enqueue(X)}})))}get elementStream(){var X,Y,Q;let J=(X=this.outputSpecification)==null?void 0:X.createElementStreamTransform();if(J==null)throw new PW1({functionality:`element streams in ${(Q=(Y=this.outputSpecification)==null?void 0:Y.name)!=null?Q:"text"} mode`});return WA(this.teeStream().pipeThrough(J))}get output(){return this.finalStep.then((X)=>{var Y;return((Y=this.outputSpecification)!=null?Y:nb()).parseCompleteOutput({text:X.text},{response:X.response,usage:X.usage,finishReason:X.finishReason})})}toUIMessageStream({originalMessages:X,generateMessageId:Y,onFinish:Q,messageMetadata:J,sendReasoning:G=!0,sendSources:W=!1,sendStart:Z=!0,sendFinish:$=!0,onError:K=g5}={}){let H=Y!=null?jl6({originalMessages:X,responseMessageId:Y}):void 0,F=(q)=>{var z;let D=(z=this.tools)==null?void 0:z[q.toolName];if(D==null)return q.dynamic;return(D==null?void 0:D.type)==="dynamic"?!0:void 0},V=this.fullStream.pipeThrough(new TransformStream({transform:async(q,z)=>{let D=J==null?void 0:J({part:q}),N=q.type;switch(N){case"text-start":{z.enqueue({type:"text-start",id:q.id,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"text-delta":{z.enqueue({type:"text-delta",id:q.id,delta:q.text,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"text-end":{z.enqueue({type:"text-end",id:q.id,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"reasoning-start":{z.enqueue({type:"reasoning-start",id:q.id,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"reasoning-delta":{if(G)z.enqueue({type:"reasoning-delta",id:q.id,delta:q.text,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"reasoning-end":{z.enqueue({type:"reasoning-end",id:q.id,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"file":{z.enqueue({type:"file",mediaType:q.file.mediaType,url:`data:${q.file.mediaType};base64,${q.file.base64}`});break}case"source":{if(W&&q.sourceType==="url")z.enqueue({type:"source-url",sourceId:q.id,url:q.url,title:q.title,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});if(W&&q.sourceType==="document")z.enqueue({type:"source-document",sourceId:q.id,mediaType:q.mediaType,title:q.title,filename:q.filename,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"tool-input-start":{let L=F(q);z.enqueue({type:"tool-input-start",toolCallId:q.id,toolName:q.toolName,...q.providerExecuted!=null?{providerExecuted:q.providerExecuted}:{},...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{},...L!=null?{dynamic:L}:{},...q.title!=null?{title:q.title}:{}});break}case"tool-input-delta":{z.enqueue({type:"tool-input-delta",toolCallId:q.id,inputTextDelta:q.delta});break}case"tool-call":{let L=F(q);if(q.invalid)z.enqueue({type:"tool-input-error",toolCallId:q.toolCallId,toolName:q.toolName,input:q.input,...q.providerExecuted!=null?{providerExecuted:q.providerExecuted}:{},...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{},...L!=null?{dynamic:L}:{},errorText:K(q.error),...q.title!=null?{title:q.title}:{}});else z.enqueue({type:"tool-input-available",toolCallId:q.toolCallId,toolName:q.toolName,input:q.input,...q.providerExecuted!=null?{providerExecuted:q.providerExecuted}:{},...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{},...L!=null?{dynamic:L}:{},...q.title!=null?{title:q.title}:{}});break}case"tool-approval-request":{z.enqueue({type:"tool-approval-request",approvalId:q.approvalId,toolCallId:q.toolCall.toolCallId});break}case"tool-result":{let L=F(q);z.enqueue({type:"tool-output-available",toolCallId:q.toolCallId,output:q.output,...q.providerExecuted!=null?{providerExecuted:q.providerExecuted}:{},...q.preliminary!=null?{preliminary:q.preliminary}:{},...L!=null?{dynamic:L}:{}});break}case"tool-error":{let L=F(q);z.enqueue({type:"tool-output-error",toolCallId:q.toolCallId,errorText:K(q.error),...q.providerExecuted!=null?{providerExecuted:q.providerExecuted}:{},...L!=null?{dynamic:L}:{}});break}case"tool-output-denied":{z.enqueue({type:"tool-output-denied",toolCallId:q.toolCallId});break}case"error":{z.enqueue({type:"error",errorText:K(q.error)});break}case"start-step":{z.enqueue({type:"start-step"});break}case"finish-step":{z.enqueue({type:"finish-step"});break}case"start":{if(Z)z.enqueue({type:"start",...D!=null?{messageMetadata:D}:{},...H!=null?{messageId:H}:{}});break}case"finish":{if($)z.enqueue({type:"finish",finishReason:q.finishReason,...D!=null?{messageMetadata:D}:{}});break}case"abort":{z.enqueue(q);break}case"tool-input-end":break;case"raw":break;default:throw Error(`Unknown chunk type: ${N}`)}if(D!=null&&N!=="start"&&N!=="finish")z.enqueue({type:"message-metadata",messageMetadata:D})}}));return WA(Sl6({stream:V,messageId:H!=null?H:Y==null?void 0:Y(),originalMessages:X,onFinish:Q,onError:K}))}pipeUIMessageStreamToResponse(X,{originalMessages:Y,generateMessageId:Q,onFinish:J,messageMetadata:G,sendReasoning:W,sendSources:Z,sendFinish:$,sendStart:K,onError:H,...F}={}){kl6({response:X,stream:this.toUIMessageStream({originalMessages:Y,generateMessageId:Q,onFinish:J,messageMetadata:G,sendReasoning:W,sendSources:Z,sendFinish:$,sendStart:K,onError:H}),...F})}pipeTextStreamToResponse(X,Y){Tl6({response:X,textStream:this.textStream,...Y})}toUIMessageStreamResponse({originalMessages:X,generateMessageId:Y,onFinish:Q,messageMetadata:J,sendReasoning:G,sendSources:W,sendFinish:Z,sendStart:$,onError:K,...H}={}){return El6({stream:this.toUIMessageStream({originalMessages:X,generateMessageId:Y,onFinish:Q,messageMetadata:J,sendReasoning:G,sendSources:W,sendFinish:Z,sendStart:$,onError:K}),...H})}toTextStreamResponse(X){return Al6({textStream:this.textStream,...X})}};async function xK1(X,Y){let Q=[];if(Y==null?void 0:Y.ignoreIncompleteToolCalls)X=X.map((J)=>({...J,parts:J.parts.filter((G)=>!ZA(G)||G.state!=="input-streaming"&&G.state!=="input-available")}));for(let J of X)switch(J.role){case"system":{let G=J.parts.filter((Z)=>Z.type==="text"),W=G.reduce((Z,$)=>{if($.providerMetadata!=null)return{...Z,...$.providerMetadata};return Z},{});Q.push({role:"system",content:G.map((Z)=>Z.text).join(""),...Object.keys(W).length>0?{providerOptions:W}:{}});break}case"user":{Q.push({role:"user",content:J.parts.map((G)=>{var W;if(kY0(G))return{type:"text",text:G.text,...G.providerMetadata!=null?{providerOptions:G.providerMetadata}:{}};if(vY0(G))return{type:"file",mediaType:G.mediaType,filename:G.filename,data:G.url,...G.providerMetadata!=null?{providerOptions:G.providerMetadata}:{}};if(SY0(G))return(W=Y==null?void 0:Y.convertDataPart)==null?void 0:W.call(Y,G)}).filter(yW1)});break}case"assistant":{if(J.parts!=null){let G=[];async function W(){var Z,$,K,H,F,V;if(G.length===0)return;let q=[];for(let D of G)if(kY0(D))q.push({type:"text",text:D.text,...D.providerMetadata!=null?{providerOptions:D.providerMetadata}:{}});else if(vY0(D))q.push({type:"file",mediaType:D.mediaType,filename:D.filename,data:D.url});else if(D$1(D))q.push({type:"reasoning",text:D.text,providerOptions:D.providerMetadata});else if(ZA(D)){let N=_Y0(D);if(D.state!=="input-streaming"){if(q.push({type:"tool-call",toolCallId:D.toolCallId,toolName:N,input:D.state==="output-error"?(Z=D.input)!=null?Z:("rawInput"in D)?D.rawInput:void 0:D.input,providerExecuted:D.providerExecuted,...D.callProviderMetadata!=null?{providerOptions:D.callProviderMetadata}:{}}),D.approval!=null)q.push({type:"tool-approval-request",approvalId:D.approval.id,toolCallId:D.toolCallId});if(D.providerExecuted===!0&&D.state!=="approval-responded"&&(D.state==="output-available"||D.state==="output-error"))q.push({type:"tool-result",toolCallId:D.toolCallId,toolName:N,output:await SF({toolCallId:D.toolCallId,input:D.input,output:D.state==="output-error"?D.errorText:D.output,tool:($=Y==null?void 0:Y.tools)==null?void 0:$[N],errorMode:D.state==="output-error"?"json":"none"}),...D.callProviderMetadata!=null?{providerOptions:D.callProviderMetadata}:{}})}}else if(SY0(D)){let N=(K=Y==null?void 0:Y.convertDataPart)==null?void 0:K.call(Y,D);if(N!=null)q.push(N)}else throw Error(`Unsupported part: ${D}`);Q.push({role:"assistant",content:q});let z=G.filter((D)=>{var N;return ZA(D)&&(D.providerExecuted!==!0||((N=D.approval)==null?void 0:N.approved)!=null)});if(z.length>0){let D=[];for(let N of z){if(((H=N.approval)==null?void 0:H.approved)!=null)D.push({type:"tool-approval-response",approvalId:N.approval.id,approved:N.approval.approved,reason:N.approval.reason,providerExecuted:N.providerExecuted});if(N.providerExecuted===!0)continue;switch(N.state){case"output-denied":{D.push({type:"tool-result",toolCallId:N.toolCallId,toolName:_Y0(N),output:{type:"error-text",value:(F=N.approval.reason)!=null?F:"Tool execution denied."},...N.callProviderMetadata!=null?{providerOptions:N.callProviderMetadata}:{}});break}case"output-error":case"output-available":{let L=_Y0(N);D.push({type:"tool-result",toolCallId:N.toolCallId,toolName:L,output:await SF({toolCallId:N.toolCallId,input:N.input,output:N.state==="output-error"?N.errorText:N.output,tool:(V=Y==null?void 0:Y.tools)==null?void 0:V[L],errorMode:N.state==="output-error"?"text":"none"}),...N.callProviderMetadata!=null?{providerOptions:N.callProviderMetadata}:{}});break}}}if(D.length>0)Q.push({role:"tool",content:D})}G=[]}for(let Z of J.parts)if(kY0(Z)||D$1(Z)||vY0(Z)||ZA(Z)||SY0(Z))G.push(Z);else if(Z.type==="step-start")await W();await W();break}break}default:{let G=J.role;throw new km6({originalMessage:J,message:`Unsupported role: ${G}`})}}return Q}var xl6=iX(()=>KX(U.array(U.object({id:U.string(),role:U.enum(["system","user","assistant"]),metadata:U.unknown().optional(),parts:U.array(U.union([U.object({type:U.literal("text"),text:U.string(),state:U.enum(["streaming","done"]).optional(),providerMetadata:p1.optional()}),U.object({type:U.literal("reasoning"),text:U.string(),state:U.enum(["streaming","done"]).optional(),providerMetadata:p1.optional()}),U.object({type:U.literal("source-url"),sourceId:U.string(),url:U.string(),title:U.string().optional(),providerMetadata:p1.optional()}),U.object({type:U.literal("source-document"),sourceId:U.string(),mediaType:U.string(),title:U.string(),filename:U.string().optional(),providerMetadata:p1.optional()}),U.object({type:U.literal("file"),mediaType:U.string(),filename:U.string().optional(),url:U.string(),providerMetadata:p1.optional()}),U.object({type:U.literal("step-start")}),U.object({type:U.string().startsWith("data-"),id:U.string().optional(),data:U.unknown()}),U.object({type:U.literal("dynamic-tool"),toolName:U.string(),toolCallId:U.string(),state:U.literal("input-streaming"),input:U.unknown().optional(),providerExecuted:U.boolean().optional(),callProviderMetadata:p1.optional(),output:U.never().optional(),errorText:U.never().optional(),approval:U.never().optional()}),U.object({type:U.literal("dynamic-tool"),toolName:U.string(),toolCallId:U.string(),state:U.literal("input-available"),input:U.unknown(),providerExecuted:U.boolean().optional(),output:U.never().optional(),errorText:U.never().optional(),callProviderMetadata:p1.optional(),approval:U.never().optional()}),U.object({type:U.literal("dynamic-tool"),toolName:U.string(),toolCallId:U.string(),state:U.literal("approval-requested"),input:U.unknown(),providerExecuted:U.boolean().optional(),output:U.never().optional(),errorText:U.never().optional(),callProviderMetadata:p1.optional(),approval:U.object({id:U.string(),approved:U.never().optional(),reason:U.never().optional()})}),U.object({type:U.literal("dynamic-tool"),toolName:U.string(),toolCallId:U.string(),state:U.literal("approval-responded"),input:U.unknown(),providerExecuted:U.boolean().optional(),output:U.never().optional(),errorText:U.never().optional(),callProviderMetadata:p1.optional(),approval:U.object({id:U.string(),approved:U.boolean(),reason:U.string().optional()})}),U.object({type:U.literal("dynamic-tool"),toolName:U.string(),toolCallId:U.string(),state:U.literal("output-available"),input:U.unknown(),providerExecuted:U.boolean().optional(),output:U.unknown(),errorText:U.never().optional(),callProviderMetadata:p1.optional(),preliminary:U.boolean().optional(),approval:U.object({id:U.string(),approved:U.literal(!0),reason:U.string().optional()}).optional()}),U.object({type:U.literal("dynamic-tool"),toolName:U.string(),toolCallId:U.string(),state:U.literal("output-error"),input:U.unknown(),rawInput:U.unknown().optional(),providerExecuted:U.boolean().optional(),output:U.never().optional(),errorText:U.string(),callProviderMetadata:p1.optional(),approval:U.object({id:U.string(),approved:U.literal(!0),reason:U.string().optional()}).optional()}),U.object({type:U.literal("dynamic-tool"),toolName:U.string(),toolCallId:U.string(),state:U.literal("output-denied"),input:U.unknown(),providerExecuted:U.boolean().optional(),output:U.never().optional(),errorText:U.never().optional(),callProviderMetadata:p1.optional(),approval:U.object({id:U.string(),approved:U.literal(!1),reason:U.string().optional()})}),U.object({type:U.string().startsWith("tool-"),toolCallId:U.string(),state:U.literal("input-streaming"),providerExecuted:U.boolean().optional(),callProviderMetadata:p1.optional(),input:U.unknown().optional(),output:U.never().optional(),errorText:U.never().optional(),approval:U.never().optional()}),U.object({type:U.string().startsWith("tool-"),toolCallId:U.string(),state:U.literal("input-available"),providerExecuted:U.boolean().optional(),input:U.unknown(),output:U.never().optional(),errorText:U.never().optional(),callProviderMetadata:p1.optional(),approval:U.never().optional()}),U.object({type:U.string().startsWith("tool-"),toolCallId:U.string(),state:U.literal("approval-requested"),input:U.unknown(),providerExecuted:U.boolean().optional(),output:U.never().optional(),errorText:U.never().optional(),callProviderMetadata:p1.optional(),approval:U.object({id:U.string(),approved:U.never().optional(),reason:U.never().optional()})}),U.object({type:U.string().startsWith("tool-"),toolCallId:U.string(),state:U.literal("approval-responded"),input:U.unknown(),providerExecuted:U.boolean().optional(),output:U.never().optional(),errorText:U.never().optional(),callProviderMetadata:p1.optional(),approval:U.object({id:U.string(),approved:U.boolean(),reason:U.string().optional()})}),U.object({type:U.string().startsWith("tool-"),toolCallId:U.string(),state:U.literal("output-available"),providerExecuted:U.boolean().optional(),input:U.unknown(),output:U.unknown(),errorText:U.never().optional(),callProviderMetadata:p1.optional(),preliminary:U.boolean().optional(),approval:U.object({id:U.string(),approved:U.literal(!0),reason:U.string().optional()}).optional()}),U.object({type:U.string().startsWith("tool-"),toolCallId:U.string(),state:U.literal("output-error"),providerExecuted:U.boolean().optional(),input:U.unknown(),rawInput:U.unknown().optional(),output:U.never().optional(),errorText:U.string(),callProviderMetadata:p1.optional(),approval:U.object({id:U.string(),approved:U.literal(!0),reason:U.string().optional()}).optional()}),U.object({type:U.string().startsWith("tool-"),toolCallId:U.string(),state:U.literal("output-denied"),providerExecuted:U.boolean().optional(),input:U.unknown(),output:U.never().optional(),errorText:U.never().optional(),callProviderMetadata:p1.optional(),approval:U.object({id:U.string(),approved:U.literal(!1),reason:U.string().optional()})})])).nonempty("Message must contain at least one part")})).nonempty("Messages array must not be empty")));async function gl6({messages:X,metadataSchema:Y,dataSchemas:Q,tools:J}){try{if(X==null)return{success:!1,error:new p5({parameter:"messages",value:X,message:"messages parameter must be provided"})};let G=await O7({value:X,schema:xl6});if(Y)for(let W of G)await O7({value:W.metadata,schema:Y});if(Q)for(let W of G){let Z=W.parts.filter(($)=>$.type.startsWith("data-"));for(let $ of Z){let K=$.type.slice(5),H=Q[K];if(!H)return{success:!1,error:new KQ({value:$.data,cause:`No data schema found for data part ${K}`})};await O7({value:$.data,schema:H})}}if(J)for(let W of G){let Z=W.parts.filter(($)=>$.type.startsWith("tool-"));for(let $ of Z){let K=$.type.slice(5),H=J[K];if(!H)return{success:!1,error:new KQ({value:$.input,cause:`No tool schema found for tool part ${K}`})};if($.state==="input-available"||$.state==="output-available"||$.state==="output-error"&&$.input!==void 0)await O7({value:$.input,schema:H.inputSchema});if($.state==="output-available"&&H.outputSchema)await O7({value:$.output,schema:H.outputSchema})}}return{success:!0,data:G}}catch(G){return{success:!1,error:G}}}async function gK1({messages:X,metadataSchema:Y,dataSchemas:Q,tools:J}){let G=await gl6({messages:X,metadataSchema:Y,dataSchemas:Q,tools:J});if(!G.success)throw G.error;return G.data}var Ge4=D7({prefix:"aiobj",size:24});var Ze4=D7({prefix:"aiobj",size:24});function uK1({messages:X,reasoning:Y="none",toolCalls:Q=[],emptyMessages:J="remove"}){if(Y==="all"||Y==="before-last-message")X=X.map((G,W)=>{if(G.role!=="assistant"||typeof G.content==="string"||Y==="before-last-message"&&W===X.length-1)return G;return{...G,content:G.content.filter((Z)=>Z.type!=="reasoning")}});if(Q==="none")Q=[];else if(Q==="all")Q=[{type:"all"}];else if(Q==="before-last-message")Q=[{type:"before-last-message"}];else if(typeof Q==="string")Q=[{type:Q}];for(let G of Q){let W=G.type==="all"?void 0:G.type==="before-last-message"?1:Number(G.type.slice(12).slice(0,-9)),Z=new Set,$=new Set;if(W!=null){for(let K of X.slice(-W))if((K.role==="assistant"||K.role==="tool")&&typeof K.content!=="string"){for(let H of K.content)if(H.type==="tool-call"||H.type==="tool-result")Z.add(H.toolCallId);else if(H.type==="tool-approval-request"||H.type==="tool-approval-response")$.add(H.approvalId)}}X=X.map((K,H)=>{if(K.role!=="assistant"&&K.role!=="tool"||typeof K.content==="string"||W&&H>=X.length-W)return K;let F={},V={};return{...K,content:K.content.filter((q)=>{if(q.type!=="tool-call"&&q.type!=="tool-result"&&q.type!=="tool-approval-request"&&q.type!=="tool-approval-response")return!0;if(q.type==="tool-call")F[q.toolCallId]=q.toolName;else if(q.type==="tool-approval-request")V[q.approvalId]=F[q.toolCallId];if((q.type==="tool-call"||q.type==="tool-result")&&Z.has(q.toolCallId)||(q.type==="tool-approval-request"||q.type==="tool-approval-response")&&$.has(q.approvalId))return!0;return G.tools!=null&&!G.tools.includes(q.type==="tool-call"||q.type==="tool-result"?q.toolName:V[q.approvalId])})}})}if(J==="remove")X=X.filter((G)=>G.content.length>0);return X}var ul6="AI_NoSuchProviderError",ml6=`vercel.ai.error.${ul6}`,ll6=Symbol.for(ml6),dl6;dl6=ll6;cW();var mK1=32768,lK1=50;function dK1(X){if(!X?.trim())return`You are an AI assistant running in an MCP Mesh environment.
1084
+ `)}})}},fK1={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function El6({status:X,statusText:Y,headers:Q,stream:J,consumeSseStream:G}){let W=J.pipeThrough(new bK1);if(G){let[Z,$]=W.tee();W=Z,G({stream:$})}return new Response(W.pipeThrough(new TextEncoderStream),{status:X,statusText:Y,headers:ob(Q,fK1)})}function jl6({originalMessages:X,responseMessageId:Y}){if(X==null)return;let Q=X[X.length-1];return(Q==null?void 0:Q.role)==="assistant"?Q.id:typeof Y==="function"?Y():Y}var ot4=iX(()=>KX(U.union([U.strictObject({type:U.literal("text-start"),id:U.string(),providerMetadata:p1.optional()}),U.strictObject({type:U.literal("text-delta"),id:U.string(),delta:U.string(),providerMetadata:p1.optional()}),U.strictObject({type:U.literal("text-end"),id:U.string(),providerMetadata:p1.optional()}),U.strictObject({type:U.literal("error"),errorText:U.string()}),U.strictObject({type:U.literal("tool-input-start"),toolCallId:U.string(),toolName:U.string(),providerExecuted:U.boolean().optional(),providerMetadata:p1.optional(),dynamic:U.boolean().optional(),title:U.string().optional()}),U.strictObject({type:U.literal("tool-input-delta"),toolCallId:U.string(),inputTextDelta:U.string()}),U.strictObject({type:U.literal("tool-input-available"),toolCallId:U.string(),toolName:U.string(),input:U.unknown(),providerExecuted:U.boolean().optional(),providerMetadata:p1.optional(),dynamic:U.boolean().optional(),title:U.string().optional()}),U.strictObject({type:U.literal("tool-input-error"),toolCallId:U.string(),toolName:U.string(),input:U.unknown(),providerExecuted:U.boolean().optional(),providerMetadata:p1.optional(),dynamic:U.boolean().optional(),errorText:U.string(),title:U.string().optional()}),U.strictObject({type:U.literal("tool-approval-request"),approvalId:U.string(),toolCallId:U.string()}),U.strictObject({type:U.literal("tool-output-available"),toolCallId:U.string(),output:U.unknown(),providerExecuted:U.boolean().optional(),dynamic:U.boolean().optional(),preliminary:U.boolean().optional()}),U.strictObject({type:U.literal("tool-output-error"),toolCallId:U.string(),errorText:U.string(),providerExecuted:U.boolean().optional(),dynamic:U.boolean().optional()}),U.strictObject({type:U.literal("tool-output-denied"),toolCallId:U.string()}),U.strictObject({type:U.literal("reasoning-start"),id:U.string(),providerMetadata:p1.optional()}),U.strictObject({type:U.literal("reasoning-delta"),id:U.string(),delta:U.string(),providerMetadata:p1.optional()}),U.strictObject({type:U.literal("reasoning-end"),id:U.string(),providerMetadata:p1.optional()}),U.strictObject({type:U.literal("source-url"),sourceId:U.string(),url:U.string(),title:U.string().optional(),providerMetadata:p1.optional()}),U.strictObject({type:U.literal("source-document"),sourceId:U.string(),mediaType:U.string(),title:U.string(),filename:U.string().optional(),providerMetadata:p1.optional()}),U.strictObject({type:U.literal("file"),url:U.string(),mediaType:U.string(),providerMetadata:p1.optional()}),U.strictObject({type:U.custom((X)=>typeof X==="string"&&X.startsWith("data-"),{message:'Type must start with "data-"'}),id:U.string().optional(),data:U.unknown(),transient:U.boolean().optional()}),U.strictObject({type:U.literal("start-step")}),U.strictObject({type:U.literal("finish-step")}),U.strictObject({type:U.literal("start"),messageId:U.string().optional(),messageMetadata:U.unknown().optional()}),U.strictObject({type:U.literal("finish"),finishReason:U.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:U.unknown().optional()}),U.strictObject({type:U.literal("abort"),reason:U.string().optional()}),U.strictObject({type:U.literal("message-metadata"),messageMetadata:U.unknown()})])));function Cl6(X){return X.type.startsWith("data-")}function SY0(X){return X.type.startsWith("data-")}function kY0(X){return X.type==="text"}function vY0(X){return X.type==="file"}function D$1(X){return X.type==="reasoning"}function hY0(X){return X.type.startsWith("tool-")}function hK1(X){return X.type==="dynamic-tool"}function ZA(X){return hY0(X)||hK1(X)}function xY0(X){return X.type.split("-").slice(1).join("-")}function _Y0(X){return hK1(X)?X.toolName:xY0(X)}function Il6({lastMessage:X,messageId:Y}){return{message:(X==null?void 0:X.role)==="assistant"?X:{id:Y,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function Rl6({stream:X,messageMetadataSchema:Y,dataPartSchemas:Q,runUpdateMessageJob:J,onError:G,onToolCall:W,onData:Z}){return X.pipeThrough(new TransformStream({async transform($,K){await J(async({state:H,write:F})=>{var V,q,z,D;function N(T){let P=H.message.parts.filter(ZA).find((j)=>j.toolCallId===T);if(P==null)throw new UB({chunkType:"tool-invocation",chunkId:T,message:`No tool invocation found for tool call ID "${T}".`});return P}function L(T){var A;let P=H.message.parts.find((k)=>hY0(k)&&k.toolCallId===T.toolCallId),j=T,R=P;if(P!=null){if(P.state=T.state,R.input=j.input,R.output=j.output,R.errorText=j.errorText,R.rawInput=j.rawInput,R.preliminary=j.preliminary,T.title!==void 0)R.title=T.title;if(R.providerExecuted=(A=j.providerExecuted)!=null?A:P.providerExecuted,j.providerMetadata!=null)P.callProviderMetadata=j.providerMetadata}else H.message.parts.push({type:`tool-${T.toolName}`,toolCallId:T.toolCallId,state:T.state,title:T.title,input:j.input,output:j.output,rawInput:j.rawInput,errorText:j.errorText,providerExecuted:j.providerExecuted,preliminary:j.preliminary,...j.providerMetadata!=null?{callProviderMetadata:j.providerMetadata}:{}})}function w(T){var A,P;let j=H.message.parts.find((_)=>_.type==="dynamic-tool"&&_.toolCallId===T.toolCallId),R=T,k=j;if(j!=null){if(j.state=T.state,k.toolName=T.toolName,k.input=R.input,k.output=R.output,k.errorText=R.errorText,k.rawInput=(A=R.rawInput)!=null?A:k.rawInput,k.preliminary=R.preliminary,T.title!==void 0)k.title=T.title;if(k.providerExecuted=(P=R.providerExecuted)!=null?P:j.providerExecuted,R.providerMetadata!=null)j.callProviderMetadata=R.providerMetadata}else H.message.parts.push({type:"dynamic-tool",toolName:T.toolName,toolCallId:T.toolCallId,state:T.state,input:R.input,output:R.output,errorText:R.errorText,preliminary:R.preliminary,providerExecuted:R.providerExecuted,title:T.title,...R.providerMetadata!=null?{callProviderMetadata:R.providerMetadata}:{}})}async function C(T){if(T!=null){let A=H.message.metadata!=null?ib(H.message.metadata,T):T;if(Y!=null)await O7({value:A,schema:Y});H.message.metadata=A}}switch($.type){case"text-start":{let T={type:"text",text:"",providerMetadata:$.providerMetadata,state:"streaming"};H.activeTextParts[$.id]=T,H.message.parts.push(T),F();break}case"text-delta":{let T=H.activeTextParts[$.id];if(T==null)throw new UB({chunkType:"text-delta",chunkId:$.id,message:`Received text-delta for missing text part with ID "${$.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});T.text+=$.delta,T.providerMetadata=(V=$.providerMetadata)!=null?V:T.providerMetadata,F();break}case"text-end":{let T=H.activeTextParts[$.id];if(T==null)throw new UB({chunkType:"text-end",chunkId:$.id,message:`Received text-end for missing text part with ID "${$.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});T.state="done",T.providerMetadata=(q=$.providerMetadata)!=null?q:T.providerMetadata,delete H.activeTextParts[$.id],F();break}case"reasoning-start":{let T={type:"reasoning",text:"",providerMetadata:$.providerMetadata,state:"streaming"};H.activeReasoningParts[$.id]=T,H.message.parts.push(T),F();break}case"reasoning-delta":{let T=H.activeReasoningParts[$.id];if(T==null)throw new UB({chunkType:"reasoning-delta",chunkId:$.id,message:`Received reasoning-delta for missing reasoning part with ID "${$.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});T.text+=$.delta,T.providerMetadata=(z=$.providerMetadata)!=null?z:T.providerMetadata,F();break}case"reasoning-end":{let T=H.activeReasoningParts[$.id];if(T==null)throw new UB({chunkType:"reasoning-end",chunkId:$.id,message:`Received reasoning-end for missing reasoning part with ID "${$.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});T.providerMetadata=(D=$.providerMetadata)!=null?D:T.providerMetadata,T.state="done",delete H.activeReasoningParts[$.id],F();break}case"file":{H.message.parts.push({type:"file",mediaType:$.mediaType,url:$.url}),F();break}case"source-url":{H.message.parts.push({type:"source-url",sourceId:$.sourceId,url:$.url,title:$.title,providerMetadata:$.providerMetadata}),F();break}case"source-document":{H.message.parts.push({type:"source-document",sourceId:$.sourceId,mediaType:$.mediaType,title:$.title,filename:$.filename,providerMetadata:$.providerMetadata}),F();break}case"tool-input-start":{let T=H.message.parts.filter(hY0);if(H.partialToolCalls[$.toolCallId]={text:"",toolName:$.toolName,index:T.length,dynamic:$.dynamic,title:$.title},$.dynamic)w({toolCallId:$.toolCallId,toolName:$.toolName,state:"input-streaming",input:void 0,providerExecuted:$.providerExecuted,title:$.title,providerMetadata:$.providerMetadata});else L({toolCallId:$.toolCallId,toolName:$.toolName,state:"input-streaming",input:void 0,providerExecuted:$.providerExecuted,title:$.title,providerMetadata:$.providerMetadata});F();break}case"tool-input-delta":{let T=H.partialToolCalls[$.toolCallId];if(T==null)throw new UB({chunkType:"tool-input-delta",chunkId:$.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${$.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});T.text+=$.inputTextDelta;let{value:A}=await VA(T.text);if(T.dynamic)w({toolCallId:$.toolCallId,toolName:T.toolName,state:"input-streaming",input:A,title:T.title});else L({toolCallId:$.toolCallId,toolName:T.toolName,state:"input-streaming",input:A,title:T.title});F();break}case"tool-input-available":{if($.dynamic)w({toolCallId:$.toolCallId,toolName:$.toolName,state:"input-available",input:$.input,providerExecuted:$.providerExecuted,providerMetadata:$.providerMetadata,title:$.title});else L({toolCallId:$.toolCallId,toolName:$.toolName,state:"input-available",input:$.input,providerExecuted:$.providerExecuted,providerMetadata:$.providerMetadata,title:$.title});if(F(),W&&!$.providerExecuted)await W({toolCall:$});break}case"tool-input-error":{if($.dynamic)w({toolCallId:$.toolCallId,toolName:$.toolName,state:"output-error",input:$.input,errorText:$.errorText,providerExecuted:$.providerExecuted,providerMetadata:$.providerMetadata});else L({toolCallId:$.toolCallId,toolName:$.toolName,state:"output-error",input:void 0,rawInput:$.input,errorText:$.errorText,providerExecuted:$.providerExecuted,providerMetadata:$.providerMetadata});F();break}case"tool-approval-request":{let T=N($.toolCallId);T.state="approval-requested",T.approval={id:$.approvalId},F();break}case"tool-output-denied":{let T=N($.toolCallId);T.state="output-denied",F();break}case"tool-output-available":{let T=N($.toolCallId);if(T.type==="dynamic-tool")w({toolCallId:$.toolCallId,toolName:T.toolName,state:"output-available",input:T.input,output:$.output,preliminary:$.preliminary,providerExecuted:$.providerExecuted,title:T.title});else L({toolCallId:$.toolCallId,toolName:xY0(T),state:"output-available",input:T.input,output:$.output,providerExecuted:$.providerExecuted,preliminary:$.preliminary,title:T.title});F();break}case"tool-output-error":{let T=N($.toolCallId);if(T.type==="dynamic-tool")w({toolCallId:$.toolCallId,toolName:T.toolName,state:"output-error",input:T.input,errorText:$.errorText,providerExecuted:$.providerExecuted,title:T.title});else L({toolCallId:$.toolCallId,toolName:xY0(T),state:"output-error",input:T.input,rawInput:T.rawInput,errorText:$.errorText,providerExecuted:$.providerExecuted,title:T.title});F();break}case"start-step":{H.message.parts.push({type:"step-start"});break}case"finish-step":{H.activeTextParts={},H.activeReasoningParts={};break}case"start":{if($.messageId!=null)H.message.id=$.messageId;if(await C($.messageMetadata),$.messageId!=null||$.messageMetadata!=null)F();break}case"finish":{if($.finishReason!=null)H.finishReason=$.finishReason;if(await C($.messageMetadata),$.messageMetadata!=null)F();break}case"message-metadata":{if(await C($.messageMetadata),$.messageMetadata!=null)F();break}case"error":{G==null||G(Error($.errorText));break}default:if(Cl6($)){if((Q==null?void 0:Q[$.type])!=null)await O7({value:$.data,schema:Q[$.type]});let T=$;if(T.transient){Z==null||Z(T);break}let A=T.id!=null?H.message.parts.find((P)=>T.type===P.type&&T.id===P.id):void 0;if(A!=null)A.data=T.data;else H.message.parts.push(T);Z==null||Z(T),F()}}K.enqueue($)})}}))}function Sl6({messageId:X,originalMessages:Y=[],onFinish:Q,onError:J,stream:G}){let W=Y==null?void 0:Y[Y.length-1];if((W==null?void 0:W.role)!=="assistant")W=void 0;else X=W.id;let Z=!1,$=G.pipeThrough(new TransformStream({transform(q,z){if(q.type==="start"){let D=q;if(D.messageId==null&&X!=null)D.messageId=X}if(q.type==="abort")Z=!0;z.enqueue(q)}}));if(Q==null)return $;let K=Il6({lastMessage:W?structuredClone(W):void 0,messageId:X!=null?X:""}),H=async(q)=>{await q({state:K,write:()=>{}})},F=!1,V=async()=>{if(F||!Q)return;F=!0;let q=K.message.id===(W==null?void 0:W.id);await Q({isAborted:Z,isContinuation:q,responseMessage:K.message,messages:[...q?Y.slice(0,-1):Y,K.message],finishReason:K.finishReason})};return Rl6({stream:$,runUpdateMessageJob:H,onError:J}).pipeThrough(new TransformStream({transform(q,z){z.enqueue(q)},async cancel(){await V()},async flush(){await V()}}))}function kl6({response:X,status:Y,statusText:Q,headers:J,stream:G,consumeSseStream:W}){let Z=G.pipeThrough(new bK1);if(W){let[$,K]=Z.tee();Z=$,W({stream:K})}yK1({response:X,status:Y,statusText:Q,headers:Object.fromEntries(ob(J,fK1).entries()),stream:Z.pipeThrough(new TextEncoderStream)})}function WA(X){let Y=X.pipeThrough(new TransformStream);return Y[Symbol.asyncIterator]=function(){let Q=this.getReader(),J=!1;async function G(W){var Z;if(J)return;J=!0;try{if(W)await((Z=Q.cancel)==null?void 0:Z.call(Q))}finally{try{Q.releaseLock()}catch($){}}}return{async next(){if(J)return{done:!0,value:void 0};let{done:W,value:Z}=await Q.read();if(W)return await G(!0),{done:!0,value:void 0};return{done:!1,value:Z}},async return(){return await G(!0),{done:!0,value:void 0}},async throw(W){throw await G(!0),W}}},Y}async function pY0({stream:X,onError:Y}){let Q=X.getReader();try{while(!0){let{done:J}=await Q.read();if(J)break}}catch(J){Y==null||Y(J)}finally{Q.releaseLock()}}function N$1(){let X,Y;return{promise:new Promise((J,G)=>{X=J,Y=G}),resolve:X,reject:Y}}function vl6(){let X=[],Y=null,Q=!1,J=N$1(),G=()=>{Q=!0,J.resolve(),X.forEach((Z)=>Z.cancel()),X=[],Y==null||Y.close()},W=async()=>{if(Q&&X.length===0){Y==null||Y.close();return}if(X.length===0)return J=N$1(),await J.promise,W();try{let{value:Z,done:$}=await X[0].read();if($)if(X.shift(),X.length===0&&Q)Y==null||Y.close();else await W();else Y==null||Y.enqueue(Z)}catch(Z){Y==null||Y.error(Z),X.shift(),G()}};return{stream:new ReadableStream({start(Z){Y=Z},pull:W,async cancel(){for(let Z of X)await Z.cancel();X=[],Q=!0}}),addStream:(Z)=>{if(Q)throw Error("Cannot add inner stream: outer stream is closed");X.push(Z.getReader()),J.resolve()},close:()=>{if(Q=!0,J.resolve(),X.length===0)Y==null||Y.close()},terminate:G}}function _l6(){var X,Y;return(Y=(X=globalThis==null?void 0:globalThis.performance)==null?void 0:X.now())!=null?Y:Date.now()}function yl6({tools:X,generatorStream:Y,tracer:Q,telemetry:J,system:G,messages:W,abortSignal:Z,repairToolCall:$,experimental_context:K,generateId:H}){let F=null,V=new ReadableStream({start(T){F=T}}),q=new Set,z=new Map,D=new Map,N=!1,L=void 0;function w(){if(N&&q.size===0){if(L!=null)F.enqueue(L);F.close()}}let C=new TransformStream({async transform(T,A){let P=T.type;switch(P){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":{A.enqueue(T);break}case"file":{A.enqueue({type:"file",file:new Ul6({data:T.data,mediaType:T.mediaType})});break}case"finish":{L={type:"finish",finishReason:T.finishReason.unified,rawFinishReason:T.finishReason.raw,usage:PK1(T.usage),providerMetadata:T.providerMetadata};break}case"tool-approval-request":{let j=D.get(T.toolCallId);if(j==null){F.enqueue({type:"error",error:new uY0({toolCallId:T.toolCallId,approvalId:T.approvalId})});break}A.enqueue({type:"tool-approval-request",approvalId:T.approvalId,toolCall:j});break}case"tool-call":{try{let j=await RK1({toolCall:T,tools:X,repairToolCall:$,system:G,messages:W});if(D.set(j.toolCallId,j),A.enqueue(j),j.invalid){F.enqueue({type:"tool-error",toolCallId:j.toolCallId,toolName:j.toolName,input:j.input,error:KB(j.error),dynamic:!0,title:j.title});break}let R=X==null?void 0:X[j.toolName];if(R==null)break;if(R.onInputAvailable!=null)await R.onInputAvailable({input:j.input,toolCallId:j.toolCallId,messages:W,abortSignal:Z,experimental_context:K});if(await IK1({tool:R,toolCall:j,messages:W,experimental_context:K})){F.enqueue({type:"tool-approval-request",approvalId:H(),toolCall:j});break}if(z.set(j.toolCallId,j.input),R.execute!=null&&j.providerExecuted!==!0){let k=H();q.add(k),dY0({toolCall:j,tools:X,tracer:Q,telemetry:J,messages:W,abortSignal:Z,experimental_context:K,onPreliminaryToolResult:(_)=>{F.enqueue(_)}}).then((_)=>{F.enqueue(_)}).catch((_)=>{F.enqueue({type:"error",error:_})}).finally(()=>{q.delete(k),w()})}}catch(j){F.enqueue({type:"error",error:j})}break}case"tool-result":{let j=T.toolName;if(T.isError)F.enqueue({type:"tool-error",toolCallId:T.toolCallId,toolName:j,input:z.get(T.toolCallId),providerExecuted:!0,error:T.result,dynamic:T.dynamic});else A.enqueue({type:"tool-result",toolCallId:T.toolCallId,toolName:j,input:z.get(T.toolCallId),output:T.result,providerExecuted:!0,dynamic:T.dynamic});break}default:throw Error(`Unhandled chunk type: ${P}`)}},flush(){N=!0,w()}});return new ReadableStream({async start(T){return Promise.all([Y.pipeThrough(C).pipeTo(new WritableStream({write(A){T.enqueue(A)},close(){}})),V.pipeTo(new WritableStream({write(A){T.enqueue(A)},close(){T.close()}}))])}})}var bl6=D7({prefix:"aitxt",size:24});function sb({model:X,tools:Y,toolChoice:Q,system:J,prompt:G,messages:W,maxRetries:Z,abortSignal:$,timeout:K,headers:H,stopWhen:F=ab(1),experimental_output:V,output:q=V,experimental_telemetry:z,prepareStep:D,providerOptions:N,experimental_activeTools:L,activeTools:w=L,experimental_repairToolCall:C,experimental_transform:T,experimental_download:A,includeRawChunks:P=!1,onChunk:j,onError:R=({error:f})=>{console.error(f)},onFinish:k,onAbort:_,onStepFinish:y,experimental_context:b,_internal:{now:r=_l6,generateId:x=bl6}={},...S}){let f=lY0(K),t=ZK1(K),m=gm6(K),J0=t!=null?new AbortController:void 0,V0=m!=null?new AbortController:void 0;return new hl6({model:cb(X),telemetry:z,headers:H,settings:S,maxRetries:Z,abortSignal:_K1($,f!=null?AbortSignal.timeout(f):void 0,J0==null?void 0:J0.signal,V0==null?void 0:V0.signal),stepTimeoutMs:t,stepAbortController:J0,chunkTimeoutMs:m,chunkAbortController:V0,system:J,prompt:G,messages:W,tools:Y,toolChoice:Q,transforms:$A(T),activeTools:w,repairToolCall:C,stopConditions:$A(F),output:q,providerOptions:N,prepareStep:D,includeRawChunks:P,onChunk:j,onError:R,onFinish:k,onAbort:_,onStepFinish:y,now:r,generateId:x,experimental_context:b,download:A})}function fl6(X){let Y=void 0,Q="",J="",G=void 0,W="";function Z({controller:$,partialOutput:K=void 0}){$.enqueue({part:{type:"text-delta",id:Y,text:J,providerMetadata:G},partialOutput:K}),J=""}return new TransformStream({async transform($,K){var H;if($.type==="finish-step"&&J.length>0)Z({controller:K});if($.type!=="text-delta"&&$.type!=="text-start"&&$.type!=="text-end"){K.enqueue({part:$,partialOutput:void 0});return}if(Y==null)Y=$.id;else if($.id!==Y){K.enqueue({part:$,partialOutput:void 0});return}if($.type==="text-start"){K.enqueue({part:$,partialOutput:void 0});return}if($.type==="text-end"){if(J.length>0)Z({controller:K});K.enqueue({part:$,partialOutput:void 0});return}Q+=$.text,J+=$.text,G=(H=$.providerMetadata)!=null?H:G;let F=await X.parsePartialOutput({text:Q});if(F!==void 0){let V=JSON.stringify(F.partial);if(V!==W)Z({controller:K,partialOutput:F.partial}),W=V}}})}var hl6=class{constructor({model:X,telemetry:Y,headers:Q,settings:J,maxRetries:G,abortSignal:W,stepTimeoutMs:Z,stepAbortController:$,chunkTimeoutMs:K,chunkAbortController:H,system:F,prompt:V,messages:q,tools:z,toolChoice:D,transforms:N,activeTools:L,repairToolCall:w,stopConditions:C,output:T,providerOptions:A,prepareStep:P,includeRawChunks:j,now:R,generateId:k,onChunk:_,onError:y,onFinish:b,onAbort:r,onStepFinish:x,experimental_context:S,download:f}){this._totalUsage=new EF,this._finishReason=new EF,this._rawFinishReason=new EF,this._steps=new EF,this.outputSpecification=T,this.includeRawChunks=j,this.tools=z;let t,m=[],J0=[],V0=void 0,Y0=void 0,U0=void 0,P0={},v0=[],G1=[],N0=new Map,W0,I0={},f1={},x1=new TransformStream({async transform(H1,k1){var c1,M1,Y1,w0;k1.enqueue(H1);let{part:A0}=H1;if(A0.type==="text-delta"||A0.type==="reasoning-delta"||A0.type==="source"||A0.type==="tool-call"||A0.type==="tool-result"||A0.type==="tool-input-start"||A0.type==="tool-input-delta"||A0.type==="raw")await(_==null?void 0:_({chunk:A0}));if(A0.type==="error")await y({error:DK1(A0.error)});if(A0.type==="text-start")I0[A0.id]={type:"text",text:"",providerMetadata:A0.providerMetadata},m.push(I0[A0.id]);if(A0.type==="text-delta"){let i1=I0[A0.id];if(i1==null){k1.enqueue({part:{type:"error",error:`text part ${A0.id} not found`},partialOutput:void 0});return}i1.text+=A0.text,i1.providerMetadata=(c1=A0.providerMetadata)!=null?c1:i1.providerMetadata}if(A0.type==="text-end"){let i1=I0[A0.id];if(i1==null){k1.enqueue({part:{type:"error",error:`text part ${A0.id} not found`},partialOutput:void 0});return}i1.providerMetadata=(M1=A0.providerMetadata)!=null?M1:i1.providerMetadata,delete I0[A0.id]}if(A0.type==="reasoning-start")f1[A0.id]={type:"reasoning",text:"",providerMetadata:A0.providerMetadata},m.push(f1[A0.id]);if(A0.type==="reasoning-delta"){let i1=f1[A0.id];if(i1==null){k1.enqueue({part:{type:"error",error:`reasoning part ${A0.id} not found`},partialOutput:void 0});return}i1.text+=A0.text,i1.providerMetadata=(Y1=A0.providerMetadata)!=null?Y1:i1.providerMetadata}if(A0.type==="reasoning-end"){let i1=f1[A0.id];if(i1==null){k1.enqueue({part:{type:"error",error:`reasoning part ${A0.id} not found`},partialOutput:void 0});return}i1.providerMetadata=(w0=A0.providerMetadata)!=null?w0:i1.providerMetadata,delete f1[A0.id]}if(A0.type==="file")m.push({type:"file",file:A0.file});if(A0.type==="source")m.push(A0);if(A0.type==="tool-call")m.push(A0);if(A0.type==="tool-result"&&!A0.preliminary)m.push(A0);if(A0.type==="tool-approval-request")m.push(A0);if(A0.type==="tool-error")m.push(A0);if(A0.type==="start-step")m=[],f1={},I0={},P0=A0.request,v0=A0.warnings;if(A0.type==="finish-step"){let i1=await fY0({content:m,tools:z}),$6=new kK1({content:m,finishReason:A0.finishReason,rawFinishReason:A0.rawFinishReason,usage:A0.usage,warnings:v0,request:P0,response:{...A0.response,messages:[...J0,...i1]},providerMetadata:A0.providerMetadata});await(x==null?void 0:x($6)),mY0({warnings:v0,provider:X.provider,model:X.modelId}),G1.push($6),J0.push(...i1),t.resolve()}if(A0.type==="finish")U0=A0.totalUsage,V0=A0.finishReason,Y0=A0.rawFinishReason},async flush(H1){try{if(G1.length===0){let Y1=(W==null?void 0:W.aborted)?W.reason:new g$1({message:"No output generated. Check the stream for errors."});S0._finishReason.reject(Y1),S0._rawFinishReason.reject(Y1),S0._totalUsage.reject(Y1),S0._steps.reject(Y1);return}let k1=V0!=null?V0:"other",c1=U0!=null?U0:RY0();S0._finishReason.resolve(k1),S0._rawFinishReason.resolve(Y0),S0._totalUsage.resolve(c1),S0._steps.resolve(G1);let M1=G1[G1.length-1];await(b==null?void 0:b({finishReason:M1.finishReason,rawFinishReason:M1.rawFinishReason,totalUsage:c1,usage:M1.usage,content:M1.content,text:M1.text,reasoningText:M1.reasoningText,reasoning:M1.reasoning,files:M1.files,sources:M1.sources,toolCalls:M1.toolCalls,staticToolCalls:M1.staticToolCalls,dynamicToolCalls:M1.dynamicToolCalls,toolResults:M1.toolResults,staticToolResults:M1.staticToolResults,dynamicToolResults:M1.dynamicToolResults,request:M1.request,response:M1.response,warnings:M1.warnings,providerMetadata:M1.providerMetadata,steps:G1,experimental_context:S})),W0.setAttributes(await w7({telemetry:Y,attributes:{"ai.response.finishReason":k1,"ai.response.text":{output:()=>M1.text},"ai.response.toolCalls":{output:()=>{var Y1;return((Y1=M1.toolCalls)==null?void 0:Y1.length)?JSON.stringify(M1.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(M1.providerMetadata),"ai.usage.inputTokens":c1.inputTokens,"ai.usage.outputTokens":c1.outputTokens,"ai.usage.totalTokens":c1.totalTokens,"ai.usage.reasoningTokens":c1.reasoningTokens,"ai.usage.cachedInputTokens":c1.cachedInputTokens}}))}catch(k1){H1.error(k1)}finally{W0.end()}}}),_0=vl6();this.addStream=_0.addStream,this.closeStream=_0.close;let L0=_0.stream.getReader(),$0=new ReadableStream({async start(H1){H1.enqueue({type:"start"})},async pull(H1){function k1(){r==null||r({steps:G1}),H1.enqueue({type:"abort",...(W==null?void 0:W.reason)!==void 0?{reason:g5(W.reason)}:{}}),H1.close()}try{let{done:c1,value:M1}=await L0.read();if(c1){H1.close();return}if(W==null?void 0:W.aborted){k1();return}H1.enqueue(M1)}catch(c1){if(eW(c1)&&(W==null?void 0:W.aborted))k1();else H1.error(c1)}},cancel(H1){return _0.stream.cancel(H1)}});for(let H1 of N)$0=$0.pipeThrough(H1({tools:z,stopStream(){_0.terminate()}}));this.baseStream=$0.pipeThrough(fl6(T!=null?T:nb())).pipeThrough(x1);let{maxRetries:E0,retry:H0}=EK1({maxRetries:G,abortSignal:W}),D0=LK1(Y),r0=bY0(J),k0=NK1({model:X,telemetry:Y,headers:Q,settings:{...r0,maxRetries:E0}}),S0=this;FA({name:"ai.streamText",attributes:w7({telemetry:Y,attributes:{...HA({operationId:"ai.streamText",telemetry:Y}),...k0,"ai.prompt":{input:()=>JSON.stringify({system:F,prompt:V,messages:q})}}}),tracer:D0,endWhenDone:!1,fn:async(H1)=>{W0=H1;let k1=await BK1({system:F,prompt:V,messages:q}),c1=k1.messages,M1=[],{approvedToolApprovals:Y1,deniedToolApprovals:w0}=jK1({messages:c1});if(w0.length>0||Y1.length>0){let i1=[...Y1,...w0].filter((O)=>O.toolCall.providerExecuted),$6=Y1.filter((O)=>!O.toolCall.providerExecuted),F4=w0.filter((O)=>!O.toolCall.providerExecuted),J1=w0.filter((O)=>O.toolCall.providerExecuted),w1,FQ=new ReadableStream({start(O){w1=O}});S0.addStream(FQ);try{for(let v of[...F4,...J1])w1==null||w1.enqueue({type:"tool-output-denied",toolCallId:v.toolCall.toolCallId,toolName:v.toolCall.toolName});let O=[];if(await Promise.all($6.map(async(v)=>{let o=await dY0({toolCall:v.toolCall,tools:z,tracer:D0,telemetry:Y,messages:c1,abortSignal:W,experimental_context:S,onPreliminaryToolResult:(G0)=>{w1==null||w1.enqueue(G0)}});if(o!=null)w1==null||w1.enqueue(o),O.push(o)})),i1.length>0)M1.push({role:"tool",content:i1.map((v)=>({type:"tool-approval-response",approvalId:v.approvalResponse.approvalId,approved:v.approvalResponse.approved,reason:v.approvalResponse.reason,providerExecuted:!0}))});if(O.length>0||F4.length>0){let v=[];for(let o of O)v.push({type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:await SF({toolCallId:o.toolCallId,input:o.input,tool:z==null?void 0:z[o.toolName],output:o.type==="tool-result"?o.output:o.error,errorMode:o.type==="tool-error"?"json":"none"})});for(let o of F4)v.push({type:"tool-result",toolCallId:o.toolCall.toolCallId,toolName:o.toolCall.toolName,output:{type:"execution-denied",reason:o.approvalResponse.reason}});M1.push({role:"tool",content:v})}}finally{w1==null||w1.close()}}J0.push(...M1);async function A0({currentStep:i1,responseMessages:$6,usage:F4}){var J1,w1,FQ,O,v,o;let G0=S0.includeRawChunks,B=Z!=null?setTimeout(()=>$.abort(),Z):void 0,E=void 0;function c(){if(K!=null){if(E!=null)clearTimeout(E);E=setTimeout(()=>H.abort(),K)}}function e(){if(E!=null)clearTimeout(E),E=void 0}function X0(){if(B!=null)clearTimeout(B)}t=new EF;let n=[...c1,...$6],C0=await(P==null?void 0:P({model:X,steps:G1,stepNumber:G1.length,messages:n,experimental_context:S})),P1=cb((J1=C0==null?void 0:C0.model)!=null?J1:X),n1=await FK1({prompt:{system:(w1=C0==null?void 0:C0.system)!=null?w1:k1.system,messages:(FQ=C0==null?void 0:C0.messages)!=null?FQ:n},supportedUrls:await P1.supportedUrls,download:f}),{toolChoice:b0,tools:y1}=await VK1({tools:z,toolChoice:(O=C0==null?void 0:C0.toolChoice)!=null?O:D,activeTools:(v=C0==null?void 0:C0.activeTools)!=null?v:L});S=(o=C0==null?void 0:C0.experimental_context)!=null?o:S;let I8=ib(A,C0==null?void 0:C0.providerOptions),{result:{stream:MX,response:_6,request:R4},doStreamSpan:aX,startTimestampMs:c5}=await H0(()=>FA({name:"ai.streamText.doStream",attributes:w7({telemetry:Y,attributes:{...HA({operationId:"ai.streamText.doStream",telemetry:Y}),...k0,"ai.model.provider":P1.provider,"ai.model.id":P1.modelId,"ai.prompt.messages":{input:()=>MK1(n1)},"ai.prompt.tools":{input:()=>y1==null?void 0:y1.map((a1)=>JSON.stringify(a1))},"ai.prompt.toolChoice":{input:()=>b0!=null?JSON.stringify(b0):void 0},"gen_ai.system":P1.provider,"gen_ai.request.model":P1.modelId,"gen_ai.request.frequency_penalty":r0.frequencyPenalty,"gen_ai.request.max_tokens":r0.maxOutputTokens,"gen_ai.request.presence_penalty":r0.presencePenalty,"gen_ai.request.stop_sequences":r0.stopSequences,"gen_ai.request.temperature":r0.temperature,"gen_ai.request.top_k":r0.topK,"gen_ai.request.top_p":r0.topP}}),tracer:D0,endWhenDone:!1,fn:async(a1)=>({startTimestampMs:R(),doStreamSpan:a1,result:await P1.doStream({...r0,tools:y1,toolChoice:b0,responseFormat:await(T==null?void 0:T.responseFormat),prompt:n1,providerOptions:I8,abortSignal:W,headers:Q,includeRawChunks:G0})})})),X1=yl6({tools:z,generatorStream:MX,tracer:D0,telemetry:Y,system:F,messages:n,repairToolCall:w,abortSignal:W,experimental_context:S,generateId:k}),A6=R4!=null?R4:{},R8=[],AY=[],e0,T6={},h8="other",pQ=void 0,VQ=RY0(),Qf,aY0=!0,n5={id:k(),timestamp:new Date,modelId:X.modelId},rY0="";S0.addStream(X1.pipeThrough(new TransformStream({async transform(a1,rX){var NB,OB,UA,PX,kF;if(c(),a1.type==="stream-start"){e0=a1.warnings;return}if(aY0){let HX=R()-c5;aY0=!1,aX.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":HX}),aX.setAttributes({"ai.response.msToFirstChunk":HX}),rX.enqueue({type:"start-step",request:A6,warnings:e0!=null?e0:[]})}let Jf=a1.type;switch(Jf){case"tool-approval-request":case"text-start":case"text-end":{rX.enqueue(a1);break}case"text-delta":{if(a1.delta.length>0)rX.enqueue({type:"text-delta",id:a1.id,text:a1.delta,providerMetadata:a1.providerMetadata}),rY0+=a1.delta;break}case"reasoning-start":case"reasoning-end":{rX.enqueue(a1);break}case"reasoning-delta":{rX.enqueue({type:"reasoning-delta",id:a1.id,text:a1.delta,providerMetadata:a1.providerMetadata});break}case"tool-call":{rX.enqueue(a1),R8.push(a1);break}case"tool-result":{if(rX.enqueue(a1),!a1.preliminary)AY.push(a1);break}case"tool-error":{rX.enqueue(a1),AY.push(a1);break}case"response-metadata":{n5={id:(NB=a1.id)!=null?NB:n5.id,timestamp:(OB=a1.timestamp)!=null?OB:n5.timestamp,modelId:(UA=a1.modelId)!=null?UA:n5.modelId};break}case"finish":{VQ=a1.usage,h8=a1.finishReason,pQ=a1.rawFinishReason,Qf=a1.providerMetadata;let HX=R()-c5;aX.addEvent("ai.stream.finish"),aX.setAttributes({"ai.response.msToFinish":HX,"ai.response.avgOutputTokensPerSecond":1000*((PX=VQ.outputTokens)!=null?PX:0)/HX});break}case"file":{rX.enqueue(a1);break}case"source":{rX.enqueue(a1);break}case"tool-input-start":{T6[a1.id]=a1.toolName;let HX=z==null?void 0:z[a1.toolName];if((HX==null?void 0:HX.onInputStart)!=null)await HX.onInputStart({toolCallId:a1.id,messages:n,abortSignal:W,experimental_context:S});rX.enqueue({...a1,dynamic:(kF=a1.dynamic)!=null?kF:(HX==null?void 0:HX.type)==="dynamic",title:HX==null?void 0:HX.title});break}case"tool-input-end":{delete T6[a1.id],rX.enqueue(a1);break}case"tool-input-delta":{let HX=T6[a1.id],Gf=z==null?void 0:z[HX];if((Gf==null?void 0:Gf.onInputDelta)!=null)await Gf.onInputDelta({inputTextDelta:a1.delta,toolCallId:a1.id,messages:n,abortSignal:W,experimental_context:S});rX.enqueue(a1);break}case"error":{rX.enqueue(a1),h8="error";break}case"raw":{if(G0)rX.enqueue(a1);break}default:throw Error(`Unknown chunk type: ${Jf}`)}},async flush(a1){let rX=R8.length>0?JSON.stringify(R8):void 0;try{aX.setAttributes(await w7({telemetry:Y,attributes:{"ai.response.finishReason":h8,"ai.response.text":{output:()=>rY0},"ai.response.toolCalls":{output:()=>rX},"ai.response.id":n5.id,"ai.response.model":n5.modelId,"ai.response.timestamp":n5.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Qf),"ai.usage.inputTokens":VQ.inputTokens,"ai.usage.outputTokens":VQ.outputTokens,"ai.usage.totalTokens":VQ.totalTokens,"ai.usage.reasoningTokens":VQ.reasoningTokens,"ai.usage.cachedInputTokens":VQ.cachedInputTokens,"gen_ai.response.finish_reasons":[h8],"gen_ai.response.id":n5.id,"gen_ai.response.model":n5.modelId,"gen_ai.usage.input_tokens":VQ.inputTokens,"gen_ai.usage.output_tokens":VQ.outputTokens}}))}catch(PX){}finally{aX.end()}a1.enqueue({type:"finish-step",finishReason:h8,rawFinishReason:pQ,usage:VQ,providerMetadata:Qf,response:{...n5,headers:_6==null?void 0:_6.headers}});let NB=AK1(F4,VQ);await t.promise;let OB=R8.filter((PX)=>PX.providerExecuted!==!0),UA=AY.filter((PX)=>PX.providerExecuted!==!0);for(let PX of R8){if(PX.providerExecuted!==!0)continue;let kF=z==null?void 0:z[PX.toolName];if((kF==null?void 0:kF.type)==="provider"&&kF.supportsDeferredResults){if(!AY.some((HX)=>HX.type==="tool-result"&&HX.toolCallId===PX.toolCallId))N0.set(PX.toolCallId,{toolName:PX.toolName})}}for(let PX of AY)if(PX.type==="tool-result")N0.delete(PX.toolCallId);if(X0(),e(),(OB.length>0&&UA.length===OB.length||N0.size>0)&&!await vK1({stopConditions:C,steps:G1})){$6.push(...await fY0({content:G1[G1.length-1].content,tools:z}));try{await A0({currentStep:i1+1,responseMessages:$6,usage:NB})}catch(PX){a1.enqueue({type:"error",error:PX}),S0.closeStream()}}else a1.enqueue({type:"finish",finishReason:h8,rawFinishReason:pQ,totalUsage:NB}),S0.closeStream()}})))}await A0({currentStep:0,responseMessages:M1,usage:RY0()})}}).catch((H1)=>{S0.addStream(new ReadableStream({start(k1){k1.enqueue({type:"error",error:H1}),k1.close()}})),S0.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then((X)=>X[X.length-1])}get content(){return this.finalStep.then((X)=>X.content)}get warnings(){return this.finalStep.then((X)=>X.warnings)}get providerMetadata(){return this.finalStep.then((X)=>X.providerMetadata)}get text(){return this.finalStep.then((X)=>X.text)}get reasoningText(){return this.finalStep.then((X)=>X.reasoningText)}get reasoning(){return this.finalStep.then((X)=>X.reasoning)}get sources(){return this.finalStep.then((X)=>X.sources)}get files(){return this.finalStep.then((X)=>X.files)}get toolCalls(){return this.finalStep.then((X)=>X.toolCalls)}get staticToolCalls(){return this.finalStep.then((X)=>X.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then((X)=>X.dynamicToolCalls)}get toolResults(){return this.finalStep.then((X)=>X.toolResults)}get staticToolResults(){return this.finalStep.then((X)=>X.staticToolResults)}get dynamicToolResults(){return this.finalStep.then((X)=>X.dynamicToolResults)}get usage(){return this.finalStep.then((X)=>X.usage)}get request(){return this.finalStep.then((X)=>X.request)}get response(){return this.finalStep.then((X)=>X.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}get rawFinishReason(){return this.consumeStream(),this._rawFinishReason.promise}teeStream(){let[X,Y]=this.baseStream.tee();return this.baseStream=Y,X}get textStream(){return WA(this.teeStream().pipeThrough(new TransformStream({transform({part:X},Y){if(X.type==="text-delta")Y.enqueue(X.text)}})))}get fullStream(){return WA(this.teeStream().pipeThrough(new TransformStream({transform({part:X},Y){Y.enqueue(X)}})))}async consumeStream(X){var Y;try{await pY0({stream:this.fullStream,onError:X==null?void 0:X.onError})}catch(Q){(Y=X==null?void 0:X.onError)==null||Y.call(X,Q)}}get experimental_partialOutputStream(){return this.partialOutputStream}get partialOutputStream(){return WA(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:X},Y){if(X!=null)Y.enqueue(X)}})))}get elementStream(){var X,Y,Q;let J=(X=this.outputSpecification)==null?void 0:X.createElementStreamTransform();if(J==null)throw new PW1({functionality:`element streams in ${(Q=(Y=this.outputSpecification)==null?void 0:Y.name)!=null?Q:"text"} mode`});return WA(this.teeStream().pipeThrough(J))}get output(){return this.finalStep.then((X)=>{var Y;return((Y=this.outputSpecification)!=null?Y:nb()).parseCompleteOutput({text:X.text},{response:X.response,usage:X.usage,finishReason:X.finishReason})})}toUIMessageStream({originalMessages:X,generateMessageId:Y,onFinish:Q,messageMetadata:J,sendReasoning:G=!0,sendSources:W=!1,sendStart:Z=!0,sendFinish:$=!0,onError:K=g5}={}){let H=Y!=null?jl6({originalMessages:X,responseMessageId:Y}):void 0,F=(q)=>{var z;let D=(z=this.tools)==null?void 0:z[q.toolName];if(D==null)return q.dynamic;return(D==null?void 0:D.type)==="dynamic"?!0:void 0},V=this.fullStream.pipeThrough(new TransformStream({transform:async(q,z)=>{let D=J==null?void 0:J({part:q}),N=q.type;switch(N){case"text-start":{z.enqueue({type:"text-start",id:q.id,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"text-delta":{z.enqueue({type:"text-delta",id:q.id,delta:q.text,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"text-end":{z.enqueue({type:"text-end",id:q.id,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"reasoning-start":{z.enqueue({type:"reasoning-start",id:q.id,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"reasoning-delta":{if(G)z.enqueue({type:"reasoning-delta",id:q.id,delta:q.text,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"reasoning-end":{z.enqueue({type:"reasoning-end",id:q.id,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"file":{z.enqueue({type:"file",mediaType:q.file.mediaType,url:`data:${q.file.mediaType};base64,${q.file.base64}`});break}case"source":{if(W&&q.sourceType==="url")z.enqueue({type:"source-url",sourceId:q.id,url:q.url,title:q.title,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});if(W&&q.sourceType==="document")z.enqueue({type:"source-document",sourceId:q.id,mediaType:q.mediaType,title:q.title,filename:q.filename,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"tool-input-start":{let L=F(q);z.enqueue({type:"tool-input-start",toolCallId:q.id,toolName:q.toolName,...q.providerExecuted!=null?{providerExecuted:q.providerExecuted}:{},...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{},...L!=null?{dynamic:L}:{},...q.title!=null?{title:q.title}:{}});break}case"tool-input-delta":{z.enqueue({type:"tool-input-delta",toolCallId:q.id,inputTextDelta:q.delta});break}case"tool-call":{let L=F(q);if(q.invalid)z.enqueue({type:"tool-input-error",toolCallId:q.toolCallId,toolName:q.toolName,input:q.input,...q.providerExecuted!=null?{providerExecuted:q.providerExecuted}:{},...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{},...L!=null?{dynamic:L}:{},errorText:K(q.error),...q.title!=null?{title:q.title}:{}});else z.enqueue({type:"tool-input-available",toolCallId:q.toolCallId,toolName:q.toolName,input:q.input,...q.providerExecuted!=null?{providerExecuted:q.providerExecuted}:{},...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{},...L!=null?{dynamic:L}:{},...q.title!=null?{title:q.title}:{}});break}case"tool-approval-request":{z.enqueue({type:"tool-approval-request",approvalId:q.approvalId,toolCallId:q.toolCall.toolCallId});break}case"tool-result":{let L=F(q);z.enqueue({type:"tool-output-available",toolCallId:q.toolCallId,output:q.output,...q.providerExecuted!=null?{providerExecuted:q.providerExecuted}:{},...q.preliminary!=null?{preliminary:q.preliminary}:{},...L!=null?{dynamic:L}:{}});break}case"tool-error":{let L=F(q);z.enqueue({type:"tool-output-error",toolCallId:q.toolCallId,errorText:K(q.error),...q.providerExecuted!=null?{providerExecuted:q.providerExecuted}:{},...L!=null?{dynamic:L}:{}});break}case"tool-output-denied":{z.enqueue({type:"tool-output-denied",toolCallId:q.toolCallId});break}case"error":{z.enqueue({type:"error",errorText:K(q.error)});break}case"start-step":{z.enqueue({type:"start-step"});break}case"finish-step":{z.enqueue({type:"finish-step"});break}case"start":{if(Z)z.enqueue({type:"start",...D!=null?{messageMetadata:D}:{},...H!=null?{messageId:H}:{}});break}case"finish":{if($)z.enqueue({type:"finish",finishReason:q.finishReason,...D!=null?{messageMetadata:D}:{}});break}case"abort":{z.enqueue(q);break}case"tool-input-end":break;case"raw":break;default:throw Error(`Unknown chunk type: ${N}`)}if(D!=null&&N!=="start"&&N!=="finish")z.enqueue({type:"message-metadata",messageMetadata:D})}}));return WA(Sl6({stream:V,messageId:H!=null?H:Y==null?void 0:Y(),originalMessages:X,onFinish:Q,onError:K}))}pipeUIMessageStreamToResponse(X,{originalMessages:Y,generateMessageId:Q,onFinish:J,messageMetadata:G,sendReasoning:W,sendSources:Z,sendFinish:$,sendStart:K,onError:H,...F}={}){kl6({response:X,stream:this.toUIMessageStream({originalMessages:Y,generateMessageId:Q,onFinish:J,messageMetadata:G,sendReasoning:W,sendSources:Z,sendFinish:$,sendStart:K,onError:H}),...F})}pipeTextStreamToResponse(X,Y){Tl6({response:X,textStream:this.textStream,...Y})}toUIMessageStreamResponse({originalMessages:X,generateMessageId:Y,onFinish:Q,messageMetadata:J,sendReasoning:G,sendSources:W,sendFinish:Z,sendStart:$,onError:K,...H}={}){return El6({stream:this.toUIMessageStream({originalMessages:X,generateMessageId:Y,onFinish:Q,messageMetadata:J,sendReasoning:G,sendSources:W,sendFinish:Z,sendStart:$,onError:K}),...H})}toTextStreamResponse(X){return Al6({textStream:this.textStream,...X})}};async function xK1(X,Y){let Q=[];if(Y==null?void 0:Y.ignoreIncompleteToolCalls)X=X.map((J)=>({...J,parts:J.parts.filter((G)=>!ZA(G)||G.state!=="input-streaming"&&G.state!=="input-available")}));for(let J of X)switch(J.role){case"system":{let G=J.parts.filter((Z)=>Z.type==="text"),W=G.reduce((Z,$)=>{if($.providerMetadata!=null)return{...Z,...$.providerMetadata};return Z},{});Q.push({role:"system",content:G.map((Z)=>Z.text).join(""),...Object.keys(W).length>0?{providerOptions:W}:{}});break}case"user":{Q.push({role:"user",content:J.parts.map((G)=>{var W;if(kY0(G))return{type:"text",text:G.text,...G.providerMetadata!=null?{providerOptions:G.providerMetadata}:{}};if(vY0(G))return{type:"file",mediaType:G.mediaType,filename:G.filename,data:G.url,...G.providerMetadata!=null?{providerOptions:G.providerMetadata}:{}};if(SY0(G))return(W=Y==null?void 0:Y.convertDataPart)==null?void 0:W.call(Y,G)}).filter(yW1)});break}case"assistant":{if(J.parts!=null){let G=[];async function W(){var Z,$,K,H,F,V;if(G.length===0)return;let q=[];for(let D of G)if(kY0(D))q.push({type:"text",text:D.text,...D.providerMetadata!=null?{providerOptions:D.providerMetadata}:{}});else if(vY0(D))q.push({type:"file",mediaType:D.mediaType,filename:D.filename,data:D.url});else if(D$1(D))q.push({type:"reasoning",text:D.text,providerOptions:D.providerMetadata});else if(ZA(D)){let N=_Y0(D);if(D.state!=="input-streaming"){if(q.push({type:"tool-call",toolCallId:D.toolCallId,toolName:N,input:D.state==="output-error"?(Z=D.input)!=null?Z:("rawInput"in D)?D.rawInput:void 0:D.input,providerExecuted:D.providerExecuted,...D.callProviderMetadata!=null?{providerOptions:D.callProviderMetadata}:{}}),D.approval!=null)q.push({type:"tool-approval-request",approvalId:D.approval.id,toolCallId:D.toolCallId});if(D.providerExecuted===!0&&D.state!=="approval-responded"&&(D.state==="output-available"||D.state==="output-error"))q.push({type:"tool-result",toolCallId:D.toolCallId,toolName:N,output:await SF({toolCallId:D.toolCallId,input:D.input,output:D.state==="output-error"?D.errorText:D.output,tool:($=Y==null?void 0:Y.tools)==null?void 0:$[N],errorMode:D.state==="output-error"?"json":"none"}),...D.callProviderMetadata!=null?{providerOptions:D.callProviderMetadata}:{}})}}else if(SY0(D)){let N=(K=Y==null?void 0:Y.convertDataPart)==null?void 0:K.call(Y,D);if(N!=null)q.push(N)}else throw Error(`Unsupported part: ${D}`);Q.push({role:"assistant",content:q});let z=G.filter((D)=>{var N;return ZA(D)&&(D.providerExecuted!==!0||((N=D.approval)==null?void 0:N.approved)!=null)});if(z.length>0){let D=[];for(let N of z){if(((H=N.approval)==null?void 0:H.approved)!=null)D.push({type:"tool-approval-response",approvalId:N.approval.id,approved:N.approval.approved,reason:N.approval.reason,providerExecuted:N.providerExecuted});if(N.providerExecuted===!0)continue;switch(N.state){case"output-denied":{D.push({type:"tool-result",toolCallId:N.toolCallId,toolName:_Y0(N),output:{type:"error-text",value:(F=N.approval.reason)!=null?F:"Tool execution denied."},...N.callProviderMetadata!=null?{providerOptions:N.callProviderMetadata}:{}});break}case"output-error":case"output-available":{let L=_Y0(N);D.push({type:"tool-result",toolCallId:N.toolCallId,toolName:L,output:await SF({toolCallId:N.toolCallId,input:N.input,output:N.state==="output-error"?N.errorText:N.output,tool:(V=Y==null?void 0:Y.tools)==null?void 0:V[L],errorMode:N.state==="output-error"?"text":"none"}),...N.callProviderMetadata!=null?{providerOptions:N.callProviderMetadata}:{}});break}}}if(D.length>0)Q.push({role:"tool",content:D})}G=[]}for(let Z of J.parts)if(kY0(Z)||D$1(Z)||vY0(Z)||ZA(Z)||SY0(Z))G.push(Z);else if(Z.type==="step-start")await W();await W();break}break}default:{let G=J.role;throw new km6({originalMessage:J,message:`Unsupported role: ${G}`})}}return Q}var xl6=iX(()=>KX(U.array(U.object({id:U.string(),role:U.enum(["system","user","assistant"]),metadata:U.unknown().optional(),parts:U.array(U.union([U.object({type:U.literal("text"),text:U.string(),state:U.enum(["streaming","done"]).optional(),providerMetadata:p1.optional()}),U.object({type:U.literal("reasoning"),text:U.string(),state:U.enum(["streaming","done"]).optional(),providerMetadata:p1.optional()}),U.object({type:U.literal("source-url"),sourceId:U.string(),url:U.string(),title:U.string().optional(),providerMetadata:p1.optional()}),U.object({type:U.literal("source-document"),sourceId:U.string(),mediaType:U.string(),title:U.string(),filename:U.string().optional(),providerMetadata:p1.optional()}),U.object({type:U.literal("file"),mediaType:U.string(),filename:U.string().optional(),url:U.string(),providerMetadata:p1.optional()}),U.object({type:U.literal("step-start")}),U.object({type:U.string().startsWith("data-"),id:U.string().optional(),data:U.unknown()}),U.object({type:U.literal("dynamic-tool"),toolName:U.string(),toolCallId:U.string(),state:U.literal("input-streaming"),input:U.unknown().optional(),providerExecuted:U.boolean().optional(),callProviderMetadata:p1.optional(),output:U.never().optional(),errorText:U.never().optional(),approval:U.never().optional()}),U.object({type:U.literal("dynamic-tool"),toolName:U.string(),toolCallId:U.string(),state:U.literal("input-available"),input:U.unknown(),providerExecuted:U.boolean().optional(),output:U.never().optional(),errorText:U.never().optional(),callProviderMetadata:p1.optional(),approval:U.never().optional()}),U.object({type:U.literal("dynamic-tool"),toolName:U.string(),toolCallId:U.string(),state:U.literal("approval-requested"),input:U.unknown(),providerExecuted:U.boolean().optional(),output:U.never().optional(),errorText:U.never().optional(),callProviderMetadata:p1.optional(),approval:U.object({id:U.string(),approved:U.never().optional(),reason:U.never().optional()})}),U.object({type:U.literal("dynamic-tool"),toolName:U.string(),toolCallId:U.string(),state:U.literal("approval-responded"),input:U.unknown(),providerExecuted:U.boolean().optional(),output:U.never().optional(),errorText:U.never().optional(),callProviderMetadata:p1.optional(),approval:U.object({id:U.string(),approved:U.boolean(),reason:U.string().optional()})}),U.object({type:U.literal("dynamic-tool"),toolName:U.string(),toolCallId:U.string(),state:U.literal("output-available"),input:U.unknown(),providerExecuted:U.boolean().optional(),output:U.unknown(),errorText:U.never().optional(),callProviderMetadata:p1.optional(),preliminary:U.boolean().optional(),approval:U.object({id:U.string(),approved:U.literal(!0),reason:U.string().optional()}).optional()}),U.object({type:U.literal("dynamic-tool"),toolName:U.string(),toolCallId:U.string(),state:U.literal("output-error"),input:U.unknown(),rawInput:U.unknown().optional(),providerExecuted:U.boolean().optional(),output:U.never().optional(),errorText:U.string(),callProviderMetadata:p1.optional(),approval:U.object({id:U.string(),approved:U.literal(!0),reason:U.string().optional()}).optional()}),U.object({type:U.literal("dynamic-tool"),toolName:U.string(),toolCallId:U.string(),state:U.literal("output-denied"),input:U.unknown(),providerExecuted:U.boolean().optional(),output:U.never().optional(),errorText:U.never().optional(),callProviderMetadata:p1.optional(),approval:U.object({id:U.string(),approved:U.literal(!1),reason:U.string().optional()})}),U.object({type:U.string().startsWith("tool-"),toolCallId:U.string(),state:U.literal("input-streaming"),providerExecuted:U.boolean().optional(),callProviderMetadata:p1.optional(),input:U.unknown().optional(),output:U.never().optional(),errorText:U.never().optional(),approval:U.never().optional()}),U.object({type:U.string().startsWith("tool-"),toolCallId:U.string(),state:U.literal("input-available"),providerExecuted:U.boolean().optional(),input:U.unknown(),output:U.never().optional(),errorText:U.never().optional(),callProviderMetadata:p1.optional(),approval:U.never().optional()}),U.object({type:U.string().startsWith("tool-"),toolCallId:U.string(),state:U.literal("approval-requested"),input:U.unknown(),providerExecuted:U.boolean().optional(),output:U.never().optional(),errorText:U.never().optional(),callProviderMetadata:p1.optional(),approval:U.object({id:U.string(),approved:U.never().optional(),reason:U.never().optional()})}),U.object({type:U.string().startsWith("tool-"),toolCallId:U.string(),state:U.literal("approval-responded"),input:U.unknown(),providerExecuted:U.boolean().optional(),output:U.never().optional(),errorText:U.never().optional(),callProviderMetadata:p1.optional(),approval:U.object({id:U.string(),approved:U.boolean(),reason:U.string().optional()})}),U.object({type:U.string().startsWith("tool-"),toolCallId:U.string(),state:U.literal("output-available"),providerExecuted:U.boolean().optional(),input:U.unknown(),output:U.unknown(),errorText:U.never().optional(),callProviderMetadata:p1.optional(),preliminary:U.boolean().optional(),approval:U.object({id:U.string(),approved:U.literal(!0),reason:U.string().optional()}).optional()}),U.object({type:U.string().startsWith("tool-"),toolCallId:U.string(),state:U.literal("output-error"),providerExecuted:U.boolean().optional(),input:U.unknown(),rawInput:U.unknown().optional(),output:U.never().optional(),errorText:U.string(),callProviderMetadata:p1.optional(),approval:U.object({id:U.string(),approved:U.literal(!0),reason:U.string().optional()}).optional()}),U.object({type:U.string().startsWith("tool-"),toolCallId:U.string(),state:U.literal("output-denied"),providerExecuted:U.boolean().optional(),input:U.unknown(),output:U.never().optional(),errorText:U.never().optional(),callProviderMetadata:p1.optional(),approval:U.object({id:U.string(),approved:U.literal(!1),reason:U.string().optional()})})])).nonempty("Message must contain at least one part")})).nonempty("Messages array must not be empty")));async function gl6({messages:X,metadataSchema:Y,dataSchemas:Q,tools:J}){try{if(X==null)return{success:!1,error:new p5({parameter:"messages",value:X,message:"messages parameter must be provided"})};let G=await O7({value:X,schema:xl6});if(Y)for(let W of G)await O7({value:W.metadata,schema:Y});if(Q)for(let W of G){let Z=W.parts.filter(($)=>$.type.startsWith("data-"));for(let $ of Z){let K=$.type.slice(5),H=Q[K];if(!H)return{success:!1,error:new KQ({value:$.data,cause:`No data schema found for data part ${K}`})};await O7({value:$.data,schema:H})}}if(J)for(let W of G){let Z=W.parts.filter(($)=>$.type.startsWith("tool-"));for(let $ of Z){let K=$.type.slice(5),H=J[K];if(!H)return{success:!1,error:new KQ({value:$.input,cause:`No tool schema found for tool part ${K}`})};if($.state==="input-available"||$.state==="output-available"||$.state==="output-error"&&$.input!==void 0)await O7({value:$.input,schema:H.inputSchema});if($.state==="output-available"&&H.outputSchema)await O7({value:$.output,schema:H.outputSchema})}}return{success:!0,data:G}}catch(G){return{success:!1,error:G}}}async function gK1({messages:X,metadataSchema:Y,dataSchemas:Q,tools:J}){let G=await gl6({messages:X,metadataSchema:Y,dataSchemas:Q,tools:J});if(!G.success)throw G.error;return G.data}var Je4=D7({prefix:"aiobj",size:24});var We4=D7({prefix:"aiobj",size:24});function uK1({messages:X,reasoning:Y="none",toolCalls:Q=[],emptyMessages:J="remove"}){if(Y==="all"||Y==="before-last-message")X=X.map((G,W)=>{if(G.role!=="assistant"||typeof G.content==="string"||Y==="before-last-message"&&W===X.length-1)return G;return{...G,content:G.content.filter((Z)=>Z.type!=="reasoning")}});if(Q==="none")Q=[];else if(Q==="all")Q=[{type:"all"}];else if(Q==="before-last-message")Q=[{type:"before-last-message"}];else if(typeof Q==="string")Q=[{type:Q}];for(let G of Q){let W=G.type==="all"?void 0:G.type==="before-last-message"?1:Number(G.type.slice(12).slice(0,-9)),Z=new Set,$=new Set;if(W!=null){for(let K of X.slice(-W))if((K.role==="assistant"||K.role==="tool")&&typeof K.content!=="string"){for(let H of K.content)if(H.type==="tool-call"||H.type==="tool-result")Z.add(H.toolCallId);else if(H.type==="tool-approval-request"||H.type==="tool-approval-response")$.add(H.approvalId)}}X=X.map((K,H)=>{if(K.role!=="assistant"&&K.role!=="tool"||typeof K.content==="string"||W&&H>=X.length-W)return K;let F={},V={};return{...K,content:K.content.filter((q)=>{if(q.type!=="tool-call"&&q.type!=="tool-result"&&q.type!=="tool-approval-request"&&q.type!=="tool-approval-response")return!0;if(q.type==="tool-call")F[q.toolCallId]=q.toolName;else if(q.type==="tool-approval-request")V[q.approvalId]=F[q.toolCallId];if((q.type==="tool-call"||q.type==="tool-result")&&Z.has(q.toolCallId)||(q.type==="tool-approval-request"||q.type==="tool-approval-response")&&$.has(q.approvalId))return!0;return G.tools!=null&&!G.tools.includes(q.type==="tool-call"||q.type==="tool-result"?q.toolName:V[q.approvalId])})}})}if(J==="remove")X=X.filter((G)=>G.content.length>0);return X}var ul6="AI_NoSuchProviderError",ml6=`vercel.ai.error.${ul6}`,ll6=Symbol.for(ml6),dl6;dl6=ll6;cW();var mK1=32768,lK1=50;function dK1(X){if(!X?.trim())return`You are an AI assistant running in an MCP Mesh environment.
1085
1085
 
1086
1086
  ## About MCP Mesh
1087
1087