@decocms/mesh 2.67.0 → 2.69.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/dist/client/assets/{AlertCircle-B2fkM138.js → AlertCircle-CrLCfZT0.js} +1 -1
  2. package/dist/client/assets/{ArrowUp-D1AvEfzg.js → ArrowUp-deTSI0E8.js} +1 -1
  3. package/dist/client/assets/{Calendar-BVWxw6KN.js → Calendar-BaFebt3t.js} +1 -1
  4. package/dist/client/assets/{Check-G0Uo7MV1.js → Check-DTUUSvp-.js} +1 -1
  5. package/dist/client/assets/{CheckCircle-Brh6alH0.js → CheckCircle-BoFrCz54.js} +1 -1
  6. package/dist/client/assets/{ChevronDown-CVB8bXEV.js → ChevronDown-DeD12W57.js} +1 -1
  7. package/dist/client/assets/{ChevronRight-c4NlNF9A.js → ChevronRight-8Yl-zCCi.js} +1 -1
  8. package/dist/client/assets/{Code01-BVAq1cya.js → Code01-C2qL6p3f.js} +1 -1
  9. package/dist/client/assets/{Copy01-C07m3ESL.js → Copy01-CqWuZ9K-.js} +1 -1
  10. package/dist/client/assets/{DotsHorizontal-AVoj4qko.js → DotsHorizontal-4eEmoKn5.js} +1 -1
  11. package/dist/client/assets/{DotsVertical-BgAR-Qt1.js → DotsVertical-BYXFslta.js} +1 -1
  12. package/dist/client/assets/{Download01-BaWv-MPX.js → Download01-DDoxVok6.js} +1 -1
  13. package/dist/client/assets/{Edit01-abEeaaHN.js → Edit01-BD2PlTCM.js} +1 -1
  14. package/dist/client/assets/{File02-Cxg7VGhK.js → File02-D_ZJmgQJ.js} +1 -1
  15. package/dist/client/assets/{File06-B-BJJgbp.js → File06-iSPwdYi1.js} +1 -1
  16. package/dist/client/assets/{FilterLines-CpavrtRH.js → FilterLines-uGkpVOX8.js} +1 -1
  17. package/dist/client/assets/{Globe02-DjAe4vbB.js → Globe02-BhcJ1ruM.js} +1 -1
  18. package/dist/client/assets/{Grid01-DkGwMObb.js → Grid01-B9LzvODL.js} +1 -1
  19. package/dist/client/assets/{Home02-C1aheEOO.js → Home02-DCnIiCxj.js} +1 -1
  20. package/dist/client/assets/{Image01-BnPQLh0E.js → Image01-BYZhOfgB.js} +1 -1
  21. package/dist/client/assets/{Inbox01-TnJNmMxq.js → Inbox01-CUvjj3IH.js} +1 -1
  22. package/dist/client/assets/{InfoCircle-CPCf05Up.js → InfoCircle-DzQgROgs.js} +1 -1
  23. package/dist/client/assets/{LinkExternal01-4WgHKQsl.js → LinkExternal01-D33uvRa3.js} +1 -1
  24. package/dist/client/assets/{List-_b-aWM0n.js → List-C1dM-VCr.js} +1 -1
  25. package/dist/client/assets/{Loading01-DJg-4sIh.js → Loading01-3CQcIIbt.js} +1 -1
  26. package/dist/client/assets/{Lock01-bcOvI0Ko.js → Lock01-aFdw7wqo.js} +1 -1
  27. package/dist/client/assets/{Pin01-BmWi3GT3.js → Pin01-ChRD6YtE.js} +1 -1
  28. package/dist/client/assets/{Play-DmKqcTBT.js → Play-B5QcYkt5.js} +1 -1
  29. package/dist/client/assets/{Plus-BfhQyaT2.js → Plus-CP35U6Iv.js} +1 -1
  30. package/dist/client/assets/{SearchMd-vzH73w2C.js → SearchMd-DTs0TtNF.js} +1 -1
  31. package/dist/client/assets/{Share07-BebYFAZG.js → Share07-DGflfftp.js} +1 -1
  32. package/dist/client/assets/{Terminal-cm5IHqjb.js → Terminal-Djd_0g5K.js} +1 -1
  33. package/dist/client/assets/{Tool01-8pfwvGVO.js → Tool01-A-03PfQ_.js} +1 -1
  34. package/dist/client/assets/{Trash01-uXqVqZ4v.js → Trash01-Ck6jzVhZ.js} +1 -1
  35. package/dist/client/assets/{Upload01-D8CqJSKT.js → Upload01-CsBiVkrb.js} +1 -1
  36. package/dist/client/assets/{Users03-BKCrYRx-.js → Users03-B-DO1n7F.js} +1 -1
  37. package/dist/client/assets/{X-BW6YCcKc.js → X-BnxI_xD6.js} +1 -1
  38. package/dist/client/assets/{XClose-C2NXNxvY.js → XClose-DvgsYIZw.js} +1 -1
  39. package/dist/client/assets/{agent-connections-preview-CGKlKFHn.js → agent-connections-preview-CYQwMlB4.js} +1 -1
  40. package/dist/client/assets/{agent-detail-M33WpTr5.js → agent-detail-tHoRcKR8.js} +1 -1
  41. package/dist/client/assets/{agents-BjHugWl0.js → agents-CNdtweuU.js} +1 -1
  42. package/dist/client/assets/{alert-dialog-fJOs6NlL.js → alert-dialog-DN6po1tq.js} +1 -1
  43. package/dist/client/assets/{auth-catchall-D-r62wiG.js → auth-catchall-Bt6aq6Tb.js} +1 -1
  44. package/dist/client/assets/{badge-BB7crk7y.js → badge-DIFY1rsD.js} +1 -1
  45. package/dist/client/assets/{binder-CbZhSXdv.js → binder-Dg2rfYkp.js} +1 -1
  46. package/dist/client/assets/{breadcrumb-niivPcbv.js → breadcrumb-CJBikxW8.js} +1 -1
  47. package/dist/client/assets/{button-CjH_jeJQ.js → button-CKIyuXIq.js} +1 -1
  48. package/dist/client/assets/{card-BuSwLKUe.js → card-MU9VbmJ4.js} +1 -1
  49. package/dist/client/assets/{checkbox-jehQHPHA.js → checkbox-BomYVgbH.js} +1 -1
  50. package/dist/client/assets/{circle-alert-B-boz6lj.js → circle-alert-BcHAU0vN.js} +1 -1
  51. package/dist/client/assets/{collection-detail-1T0ecY8Q.js → collection-detail-CZFVa2Zq.js} +1 -1
  52. package/dist/client/assets/{collection-search-CEX16zDI.js → collection-search-CECpIAiD.js} +1 -1
  53. package/dist/client/assets/{collection-tab-CN84ifuT.js → collection-tab-D12suO7P.js} +1 -1
  54. package/dist/client/assets/{collection-table-wrapper-Cf-srhsL.js → collection-table-wrapper-CzqGMTIb.js} +1 -1
  55. package/dist/client/assets/{collection-tabs-BHUXhrq0.js → collection-tabs-Dd6S7hPE.js} +1 -1
  56. package/dist/client/assets/{command-CI8tLx1q.js → command-BLAC1NoH.js} +1 -1
  57. package/dist/client/assets/{connect-DnxowUrB.js → connect-VopSOjzi.js} +1 -1
  58. package/dist/client/assets/{connection-card-BMgz1e9v.js → connection-card-C7cdqtZc.js} +1 -1
  59. package/dist/client/assets/{connection-detail-DJfMln3d.js → connection-detail-Cm-idmqc.js} +1 -1
  60. package/dist/client/assets/{connections-D9cfv_7-.js → connections-DqIiaOoJ.js} +1 -1
  61. package/dist/client/assets/constants-DBJOqOcW.js +1 -0
  62. package/dist/client/assets/{constants-CeDPLV3j.js → constants-DwkB1age.js} +1 -1
  63. package/dist/client/assets/{create-organization-dialog-DEJZtz9m.js → create-organization-dialog-QVwT9MeU.js} +1 -1
  64. package/dist/client/assets/{dialog-BjAQMOK4.js → dialog-CjI8rs-6.js} +1 -1
  65. package/dist/client/assets/{dropdown-menu-vCMq_394.js → dropdown-menu-CoO02CsY.js} +1 -1
  66. package/dist/client/assets/{dynamic-plugin-layout-DkBPIXG_.js → dynamic-plugin-layout-DxUJHFK2.js} +1 -1
  67. package/dist/client/assets/{empty-state-Gbw_otIT.js → empty-state-CQab9dR0.js} +1 -1
  68. package/dist/client/assets/{empty-state-BvjoZw7e.js → empty-state-VwVcPCE1.js} +1 -1
  69. package/dist/client/assets/{env-vars-editor-B1PughxC.js → env-vars-editor-BMhfk7Zf.js} +1 -1
  70. package/dist/client/assets/{error-boundary-CfjGe8GJ.js → error-boundary-C8CO11ML.js} +1 -1
  71. package/dist/client/assets/{extract-connection-data-CF78Ki23.js → extract-connection-data-DwTMOpOf.js} +1 -1
  72. package/dist/client/assets/{file-browser-nwtZ6onU.js → file-browser-BqPRsorK.js} +2 -2
  73. package/dist/client/assets/{form-CHBB34OT.js → form-CO4xV9gA.js} +1 -1
  74. package/dist/client/assets/{grid-view-DL05Fujd.js → grid-view-CDgwvRTT.js} +1 -1
  75. package/dist/client/assets/{home-CLtjbN9e.js → home-Bgf631v9.js} +1 -1
  76. package/dist/client/assets/{index-D0blI3XW.js → index-810mvVLg.js} +1 -1
  77. package/dist/client/assets/{index-BsfqdgCF.js → index-Bc7QzOnC.js} +1 -1
  78. package/dist/client/assets/{index-OwZGmo7I.js → index-BdSNJxPZ.js} +1 -1
  79. package/dist/client/assets/{index-BMLEzHeY.js → index-CHQ9-Q-G.js} +36 -36
  80. package/dist/client/assets/{index-Ctm-JrdL.js → index-CNwEt7K8.js} +1 -1
  81. package/dist/client/assets/{index-8kTnOBNx.js → index-CrNYs5dK.js} +77 -77
  82. package/dist/client/assets/{index-CnGxfk10.js → index-CvZXtRPz.js} +12 -12
  83. package/dist/client/assets/{index-Bmf5NCxB.js → index-aWpPBjkT.js} +1 -1
  84. package/dist/client/assets/{infiniteQueryObserver-eQjHgw7d.js → infiniteQueryObserver-CKMx30vn.js} +1 -1
  85. package/dist/client/assets/{input-BlxXRmnq.js → input-BrgRsDcE.js} +1 -1
  86. package/dist/client/assets/{layout-DF2Vd6dD.js → layout-D8nQ7DGi.js} +1 -1
  87. package/dist/client/assets/{localstorage-keys-CYYT4Okl.js → localstorage-keys-BiLB-Ybm.js} +1 -1
  88. package/dist/client/assets/{login-rMJme3Jv.js → login-COXBU4ri.js} +1 -1
  89. package/dist/client/assets/{mcp-oauth-CPPdR_so.js → mcp-oauth-i2Um3a9A.js} +1 -1
  90. package/dist/client/assets/{mcp-server-card-Dz6OItSH.js → mcp-server-card-B_tcMycX.js} +1 -1
  91. package/dist/client/assets/{mcp-server-detail-CKCgTImi.js → mcp-server-detail-CCPdSS0H.js} +2 -2
  92. package/dist/client/assets/{members-2hnMfIOo.js → members-DNx_w5eC.js} +1 -1
  93. package/dist/client/assets/{monaco-editor-DYG-izQC.js → monaco-editor-qYykGrlT.js} +1 -1
  94. package/dist/client/assets/{monitoring-45wfQEuI.js → monitoring-BuIkRBxN.js} +1 -1
  95. package/dist/client/assets/{oauth-callback-DrWbOmjU.js → oauth-callback-B24XRb9Q.js} +1 -1
  96. package/dist/client/assets/{page-Dig-kXzy.js → page-Buen7bnX.js} +1 -1
  97. package/dist/client/assets/{page-CqA3sqGx.js → page-NaxcVK27.js} +1 -1
  98. package/dist/client/assets/{plugin-empty-state-D_A0ZR3o.js → plugin-empty-state-CNA6ghy_.js} +1 -1
  99. package/dist/client/assets/{plugin-header-CICDX7I-.js → plugin-header-ColWGLS5.js} +1 -1
  100. package/dist/client/assets/{plugins-Cj62SDQ2.js → plugins-Bwp1vQes.js} +1 -1
  101. package/dist/client/assets/{popover-JdYFp74u.js → popover-CjUGVjON.js} +1 -1
  102. package/dist/client/assets/{registry-utils-BwCYxc2h.js → registry-utils-TFnNkGPj.js} +1 -1
  103. package/dist/client/assets/{resizable-CRqJtbE0.js → resizable-DQA2LWqr.js} +1 -1
  104. package/dist/client/assets/{select-Br1I42DX.js → select-JdRjOrBE.js} +1 -1
  105. package/dist/client/assets/{settings-Csz6dsxM.js → settings-C5BA4Ik8.js} +1 -1
  106. package/dist/client/assets/{shell-layout-CLklIdz9.js → shell-layout-Dz2AUt47.js} +1 -1
  107. package/dist/client/assets/{spinner-BmgAJqAH.js → spinner-CEhxpPPn.js} +1 -1
  108. package/dist/client/assets/{store-invite-DoSHlGQN.js → store-invite-2RTGhZRS.js} +1 -1
  109. package/dist/client/assets/{switch-CMXpi8bR.js → switch-DKkhDe7l.js} +1 -1
  110. package/dist/client/assets/{table-CGj3hOxZ.js → table-CBtv9zrT.js} +1 -1
  111. package/dist/client/assets/{textarea-Dg4rxulg.js → textarea-BBk7k5wE.js} +1 -1
  112. package/dist/client/assets/{tools-list-BVu0EauP.js → tools-list-DGAPFCDO.js} +1 -1
  113. package/dist/client/assets/tools-list-DWnTz46N.css +1 -0
  114. package/dist/client/assets/{typewriter-title-bodc21io.js → typewriter-title-XDUo1EGk.js} +1 -1
  115. package/dist/client/assets/{use-binding-D3U0XVop.js → use-binding-HsWp1jWu.js} +1 -1
  116. package/dist/client/assets/use-connection-UwIAiUmR.js +1 -0
  117. package/dist/client/assets/{use-create-virtual-mcp-D7NmkZa5.js → use-create-virtual-mcp-CG-Wp4A9.js} +1 -1
  118. package/dist/client/assets/{use-deco-chat-open-cI1K_3H4.js → use-deco-chat-open-Da_cfFLg.js} +2 -2
  119. package/dist/client/assets/{use-list-state-BAGJ3irz.js → use-list-state-Dxbvm2sV.js} +1 -1
  120. package/dist/client/assets/{use-mcp-prompts-vgmIJb9h.js → use-mcp-prompts-DDPkiTOB.js} +1 -1
  121. package/dist/client/assets/{use-mcp-tools-X7PZhTof.js → use-mcp-tools-BKgKiBFS.js} +1 -1
  122. package/dist/client/assets/{use-mobile-r7mBIBEK.js → use-mobile-CtC8_4UP.js} +1 -1
  123. package/dist/client/assets/{use-organization-settings-CdospZv2.js → use-organization-settings-TImCLEbo.js} +1 -1
  124. package/dist/client/assets/{use-virtual-mcp-DrasHs63.js → use-virtual-mcp-BIZk_q3v.js} +1 -1
  125. package/dist/client/assets/useInfiniteQuery-wjoMRbc3.js +1 -0
  126. package/dist/client/assets/{useMutation-CUbpcpQz.js → useMutation-C8K1KoTI.js} +1 -1
  127. package/dist/client/assets/useQuery-CImYAWdS.js +1 -0
  128. package/dist/client/assets/{view-mode-toggle-C6XvJAEJ.js → view-mode-toggle-BiRjYen1.js} +1 -1
  129. package/dist/client/assets/{workflow-BSVWLVOc.js → workflow-TGPdc23k.js} +1 -1
  130. package/dist/client/index.html +1 -1
  131. package/dist/server/cli.js +122 -122
  132. package/dist/server/migrate.js +1 -1
  133. package/dist/server/server.js +105 -105
  134. package/package.json +1 -1
  135. package/dist/client/assets/constants-CW07-qnN.js +0 -1
  136. package/dist/client/assets/tools-list-CSRUKxnt.css +0 -1
  137. package/dist/client/assets/use-connection-D8sP6Sf6.js +0 -1
  138. package/dist/client/assets/useInfiniteQuery-CmVm1W19.js +0 -1
  139. package/dist/client/assets/useQuery-CyQI_ufp.js +0 -1
@@ -416,7 +416,7 @@ ${Y.stack}`;return X}if(typeof Y==="object"&&Y!==null){let X=Y,Q="";if(typeof X.
416
416
  ${X.stack}`;return Q}try{let G=JSON.stringify(X,null,2);if(G!=="{}"&&G.length<1000){if(typeof X.stack==="string"&&X.stack&&X.stack.length<2000)return`${G}
417
417
 
418
418
  Stack trace:
419
- ${X.stack}`;return G}}catch{}if(typeof X.toString==="function")try{let G=X.toString();if(G!=="[object Object]")return G}catch{}let J=Object.keys(X);if(J.length>0)return`Object with keys: ${J.join(", ")}`;return"[object Object]"}if(typeof Y==="string")return Y;if(typeof Y==="number"||typeof Y==="boolean")return String(Y);if(typeof Y==="function")return`[Function: ${Y.name||"anon"}]`;if(typeof Y==="symbol")return Y.toString();if(typeof Y==="bigint")return Y.toString();try{return String(Y)}catch{return"Unknown value (could not convert to string)"}}function xB(Y,X){switch(typeof X){case"string":return Y.newString(X);case"number":return Y.newNumber(X);case"boolean":return X?Y.true:Y.false;case"undefined":return Y.undefined;case"object":{if(X===null)return Y.null;if(Array.isArray(X)){let J=Y.newArray();return X.forEach((G,K)=>{let W=xB(Y,G);try{Y.setProp(J,String(K),W)}finally{W.dispose?.()}}),J}let Q=Y.newObject();for(let[J,G]of Object.entries(X)){let K=xB(Y,G);try{Y.setProp(Q,J,K)}finally{K.dispose?.()}}return Q}case"function":{let Q=`__hostFn_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return Y.newFunction(Q,(...G)=>{try{let K=G.map((Z)=>Y.dump(Z)),W=X(...K);if(W&&typeof W.then==="function"){let Z=Y.newPromise();return W.then((H)=>{try{let F=xB(Y,H);Z.resolve(F),F.dispose(),Y.runtime.executePendingJobs()}catch(F){let V=bB(F),q=Y.newString(`Promise resolution error: ${V}`);Z.reject(q),q.dispose(),Y.runtime.executePendingJobs()}}).catch((H)=>{let F=bB(H),V=Y.newString(`Promise rejection: ${F}`);Z.reject(V),V.dispose(),Y.runtime.executePendingJobs()}),Z.handle}return xB(Y,W)}catch(K){let W=bB(K);return Y.newString(`HostFunctionError: ${W}`)}finally{G.forEach((K)=>K.dispose())}})}case"bigint":return Y.newString(X.toString());case"symbol":return Y.newString(X.toString());default:try{return Y.newString(String(X))}catch{return Y.undefined}}}var BH6=()=>{};function DH6(Y){let X=Y.runtime.executePendingJobs(100);try{if("unwrap"in X&&typeof X.unwrap==="function")X.unwrap()}finally{if("dispose"in X&&typeof X.dispose==="function")X.dispose()}}async function UH6(Y,X,Q){let J=Date.now(),G=Y.resolvePromise(X);while(!0){DH6(Y);let K=await Promise.race([G,td4(0).then(()=>null)]);if(K!==null)return K;if(Date.now()-J>Q)throw Error(`Timed out after ${Q}ms while awaiting a QuickJS promise`)}}async function FY0({tools:Y,code:X,timeoutMs:Q}){let W=[];try{let J=await $H6({memoryLimitBytes:33554432,stackSizeBytes:524288});const G=nB(W,J.newContext({interruptAfterMs:Q}),0);const K=nB(W,uK6(G),0);try{let V=G.evalCode(X,"index.mjs",{strip:!0,strict:!0,type:"module"}),q=G.unwrapResult(V),$=xB(G,Y);G.setProp(G.global,"tools",$);let B=G.runtime.hasPendingJob()?G.unwrapResult(await UH6(G,q,Q)):q;if(B!==q)q.dispose();let U=G.getProp(B,"default"),O=G.typeof(U);if(O!=="function")return{error:`Code must export default a function (tools). Got ${O}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:K.logs};let L=G.callFunction(U,G.undefined,$),M=G.unwrapResult(L),C=await UH6(G,M,Q),R=G.unwrapResult(C);if(G.runtime.hasPendingJob())DH6(G);return{returnValue:G.dump(R),consoleLogs:K.logs}}catch(V){return console.log(V),{error:bB(V),consoleLogs:K.logs}}}catch(Z){var H=Z,F=1}finally{dP(W,H,F)}}var td4=(Y)=>new Promise((X)=>setTimeout(X,Y));var OH6=x(()=>{zH6();BH6()});var NH6=x(()=>{OH6()});async function ed4(Y,X){let Q=Y.connections.map((K)=>K.connection_id),J=[];for(let K of Q){let W=await X.storage.connections.findById(K);if(W&&W.status==="active")J.push(W)}return J.map((K)=>{let W=Y.connections.find((Z)=>Z.connection_id===K.id);return{connection:K,selectedTools:W?.selected_tools??null,selectedResources:W?.selected_resources??null,selectedPrompts:W?.selected_prompts??null}})}async function LH6(Y,X){return(await X.storage.connections.list(Y)).filter((J)=>J.status==="active").map((J)=>({connection:J,selectedTools:null,selectedResources:null,selectedPrompts:null}))}async function Yp4(Y,X){let Q=new Map;for(let $ of Y)Q.set($.connection.id,$);let J=Y.map(($)=>$.connection),G=new Map,K=await Promise.allSettled(J.map(async($)=>{try{let B=await X.createMCPProxy($);return{connection:$,proxy:B}}catch(B){return console.warn(`[code-execution] Failed to create proxy for connection ${$.id}:`,B),null}}));for(let $ of K)if($.status==="fulfilled"&&$.value)G.set($.value.connection.id,$.value);let W=await Promise.allSettled(Array.from(G.entries()).map(async([$,B])=>{try{let O=(await B.proxy.listTools()).tools,L=Q.get($);if(L?.selectedTools&&L.selectedTools.length>0){let M=new Set(L.selectedTools);O=O.filter((C)=>M.has(C.name))}return{connectionId:$,connectionTitle:B.connection.title,tools:O}}catch(U){return console.error(`[code-execution] Failed to list tools for connection ${$}:`,U),null}})),Z=new Set,H=[],F=new Map;for(let $ of W){if($.status!=="fulfilled"||!$.value)continue;let{connectionId:B,connectionTitle:U,tools:O}=$.value;for(let L of O){if(Z.has(L.name))continue;Z.add(L.name),H.push({...L,_meta:{connectionId:B,connectionTitle:U}}),F.set(L.name,B)}}let V=async($,B)=>{let U=F.get($);if(!U)return{content:[{type:"text",text:`Tool not found: ${$}`}],isError:!0};let O=G.get(U);if(!O)return{content:[{type:"text",text:`Connection not found for tool: ${$}`}],isError:!0};return await O.proxy.callTool({name:$,arguments:B})},q=[];for(let[,$]of G)q.push($.proxy.close().catch(()=>{}));return await Promise.all(q),{tools:H,callTool:V}}async function uB(Y){let X=H6(Y),Q;if(Y.connectionId){let J=await Y.storage.virtualMcps.findById(Y.connectionId,Y.organization?.id);if(J)Q=await ed4(J,Y);else Q=await LH6(X.id,Y)}else Q=await LH6(X.id,Y);return Yp4(Q,Y)}function Xp4(Y){return Y.toLowerCase().split(/[\s_\-./]+/).filter((X)=>X.length>=2)}function Qp4(Y,X){let Q=0,J=X.name.toLowerCase(),G=(X.description??"").toLowerCase(),K=(X._meta?.connectionTitle??"").toLowerCase();for(let W of Y){if(J===W)Q+=10;else if(J.includes(W))Q+=3;if(G.includes(W))Q+=2;if(K.includes(W))Q+=1}return Q}function MH6(Y,X,Q){let J=Xp4(Y);if(J.length===0)return X.slice(0,Q);return X.map((G)=>({tool:G,score:Qp4(J,G)})).filter((G)=>G.score>0).sort((G,K)=>K.score-G.score).slice(0,Q).map((G)=>G.tool)}function wH6(Y,X){let Q=new Map(X.map((G)=>[G.name,G]));return{tools:Y.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:Y.filter((G)=>!Q.has(G))}}async function PH6(Y,X,Q){let J=Object.fromEntries(X.tools.map((G)=>[G.name,async(K)=>X.callTool(G.name,K??{})]));return FY0({code:Y,tools:J,timeoutMs:Q})}var Of=x(()=>{NH6()});var VY0;var TH6=x(()=>{f6();LP();Of();VY0=v0({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:_K6,outputSchema:yK6,handler:async(Y,X)=>{t0(X),H6(X),await X.access.check();let Q=await uB(X),J=MH6(Y.query,Q.tools,Y.limit);return{query:Y.query,results:J.map((G)=>({name:G.name,description:G.description,connection:G._meta?.connectionTitle??""})),totalAvailable:Q.tools.length}}})});var qY0;var AH6=x(()=>{f6();LP();Of();qY0=v0({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:fK6,outputSchema:hK6,handler:async(Y,X)=>{t0(X),H6(X),await X.access.check();let Q=await uB(X);return wH6(Y.tools,Q.tools)}})});var $Y0;var EH6=x(()=>{f6();LP();Of();$Y0=v0({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:bK6,outputSchema:xK6,handler:async(Y,X)=>{t0(X),H6(X),await X.access.check();let Q=await uB(X);return await PH6(Y.code,Q,Y.timeoutMs)}})});var CH6=x(()=>{TH6();AH6();EH6();LP()});var Gp4,Wp4,zY0;var IH6=x(()=>{TB();g0();f6();Ff();s3();Gp4=N.object({data:QP.describe("Data for the new connection (id is auto-generated if not provided)")}),Wp4=N.object({item:DX.describe("The created connection entity")}),zY0=v0({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",inputSchema:Gp4,outputSchema:Wp4,handler:async(Y,X)=>{t0(X);let Q=H6(X);await X.access.check();let J=_8(X);if(!J)throw Error("User ID required to create connection");let G={...Y.data,organization_id:Q.id,created_by:J};if(G.connection_type==="VIRTUAL"){let H=tF(G.connection_url);if(!H)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let F=await X.storage.virtualMcps.findById(H);if(!F)throw Error(`Virtual MCP not found: ${H}`);if(F.organization_id!==Q.id)throw Error("Virtual MCP does not belong to the current organization");G.connection_url=eF(H)}let K=await yB({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),W=K?.length?K:null,Z=await X.storage.connections.create({...G,tools:W});return await X.eventBus.publish(Q.id,k5.SELF(Q.id),{type:"connection.created",data:Z}),{item:Z}}})});function wP(Y,X){if(Y===X)return!0;if(Y==null||X==null)return Y===X;if(typeof Y!==typeof X)return!1;if(Array.isArray(Y)&&Array.isArray(X)){if(Y.length!==X.length)return!1;return Y.every((Q,J)=>wP(Q,X[J]))}if(typeof Y==="object"&&typeof X==="object"){let Q=Object.keys(Y),J=Object.keys(X);if(Q.length!==J.length)return!1;return Q.every((G)=>J.includes(G)&&wP(Y[G],X[G]))}return!1}function Rp4(){return(Y)=>{if(!Array.isArray(Y))return!0;let X=[];return Y.every((Q)=>{if(X.some((G)=>wP(Q,G)))return!1;return X.push(Q),!0})}}function Nf(Y,X){return Y.safeParse(X).success}function qY(Y){if(typeof Y==="boolean")return Y?N.any():N.never();let X={};for(let G of lp4)G.apply(X,Y);let Q=[];if(X.string!==!1)Q.push(X.string||N.string());if(X.number!==!1)Q.push(X.number||N.number());if(X.boolean!==!1)Q.push(X.boolean||N.boolean());if(X.null!==!1)Q.push(X.null||N.null());if(X.array!==!1)Q.push(X.array||N.array(N.any()));if(X.tuple!==!1&&X.tuple!==void 0)Q.push(X.tuple);if(X.object!==!1)if(X.object)Q.push(X.object);else{let G=N.custom((K)=>{return typeof K==="object"&&K!==null&&!Array.isArray(K)},"Must be an object, not an array");Q.push(G)}if(X.file!==!1&&X.file!==void 0)Q.push(X.file);let J;if(Q.length===0)J=N.never();else if(Q.length===1)J=Q[0];else if(!Object.keys(Y).some((K)=>K!=="$schema"&&K!=="title"&&K!=="description"))J=N.any();else J=N.union(Q);for(let G of dp4)J=G.apply(J,Y);return J}var Zp4=class{apply(Y,X){if(!X.type)return;let Q=Array.isArray(X.type)?X.type:[X.type],J=new Set(Q);if(!J.has("string"))Y.string=!1;if(!J.has("number")&&!J.has("integer"))Y.number=!1;if(!J.has("boolean"))Y.boolean=!1;if(!J.has("null"))Y.null=!1;if(!J.has("array"))Y.array=!1;if(!J.has("object"))Y.object=!1;if(J.has("integer")&&Y.number!==!1){let G=Y.number||N.number();if(G instanceof N.ZodNumber)Y.number=G.int()}}},Kp4=class{apply(Y,X){if(X.const===void 0)return;let Q=X.const;if(Y.string=!1,Y.number=!1,Y.boolean=!1,Y.null=!1,Y.array=!1,Y.object=!1,typeof Q==="string")Y.string=N.literal(Q);else if(typeof Q==="number")Y.number=N.literal(Q);else if(typeof Q==="boolean")Y.boolean=N.literal(Q);else if(Q===null)Y.null=N.null();else if(Array.isArray(Q))Y.array=void 0;else if(typeof Q==="object")Y.object=void 0}},Hp4=class{apply(Y,X){if(!X.enum)return;if(X.enum.length===0){if(!X.type)Y.string=!1,Y.number=!1,Y.boolean=!1,Y.null=!1,Y.array=!1,Y.object=!1;return}let Q={string:X.enum.filter((J)=>typeof J==="string"),number:X.enum.filter((J)=>typeof J==="number"),boolean:X.enum.filter((J)=>typeof J==="boolean"),null:X.enum.filter((J)=>J===null),array:X.enum.filter((J)=>Array.isArray(J)),object:X.enum.filter((J)=>typeof J==="object"&&J!==null&&!Array.isArray(J))};Y.string=this.createTypeSchema(Q.string,"string"),Y.number=this.createTypeSchema(Q.number,"number"),Y.boolean=this.createTypeSchema(Q.boolean,"boolean"),Y.null=Q.null.length>0?N.null():!1,Y.array=Q.array.length>0?void 0:!1,Y.object=Q.object.length>0?void 0:!1}createTypeSchema(Y,X){if(Y.length===0)return!1;if(Y.length===1)return N.literal(Y[0]);if(X==="string")return N.enum(Y);if(X==="number"){let[Q,J,...G]=Y;return N.union([N.literal(Q),N.literal(J),...G.map((K)=>N.literal(K))])}if(X==="boolean")return N.union([N.literal(!0),N.literal(!1)]);return!1}},Fp4=class{apply(Y,X){let Q=X;if(Q.type==="string"&&Q.format==="binary"&&Q.contentEncoding==="binary"){let J=N.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);Y.file=J,Y.string=!1}}},Vp4=class{apply(Y,X){let Q=X;if(X.type===void 0&&(Q.minLength!==void 0||Q.maxLength!==void 0||Q.pattern!==void 0)){if(Y.string===void 0)Y.string=N.string()}}},qp4=class{apply(Y,X){let Q=X;if(Q.minLength===void 0)return;if(Y.string!==!1){let J=Y.string||N.string();if(J instanceof N.ZodString)Y.string=J.refine((G)=>{return Array.from(G).length>=Q.minLength},{message:`String must be at least ${Q.minLength} characters long`})}}},$p4=class{apply(Y,X){let Q=X;if(Q.maxLength===void 0)return;if(Y.string!==!1){let J=Y.string||N.string();if(J instanceof N.ZodString)Y.string=J.refine((G)=>{return Array.from(G).length<=Q.maxLength},{message:`String must be at most ${Q.maxLength} characters long`})}}},zp4=class{apply(Y,X){let Q=X;if(!Q.pattern)return;if(Y.string!==!1){let J=Y.string||N.string();if(J instanceof N.ZodString){let G=new RegExp(Q.pattern);Y.string=J.regex(G)}}}},Bp4=class{apply(Y,X){let Q=X;if(Q.minimum===void 0)return;if(Y.number!==!1){let J=Y.number||N.number();if(J instanceof N.ZodNumber)Y.number=J.min(Q.minimum)}}},Up4=class{apply(Y,X){let Q=X;if(Q.maximum===void 0)return;if(Y.number!==!1){let J=Y.number||N.number();if(J instanceof N.ZodNumber)Y.number=J.max(Q.maximum)}}},Dp4=class{apply(Y,X){let Q=X;if(Q.exclusiveMinimum===void 0)return;if(Y.number!==!1){let J=Y.number||N.number();if(J instanceof N.ZodNumber)if(typeof Q.exclusiveMinimum==="number")Y.number=J.gt(Q.exclusiveMinimum);else Y.number=!1}}},Op4=class{apply(Y,X){let Q=X;if(Q.exclusiveMaximum===void 0)return;if(Y.number!==!1){let J=Y.number||N.number();if(J instanceof N.ZodNumber)if(typeof Q.exclusiveMaximum==="number")Y.number=J.lt(Q.exclusiveMaximum);else Y.number=!1}}},Np4=class{apply(Y,X){let Q=X;if(Q.multipleOf===void 0)return;if(Y.number!==!1){let J=Y.number||N.number();if(J instanceof N.ZodNumber)Y.number=J.refine((G)=>{if(Q.multipleOf===0)return!1;let K=G/Q.multipleOf,W=Math.round(K),Z=Math.min(Math.abs(G)*Number.EPSILON*10,Math.abs(Q.multipleOf)*Number.EPSILON*10);return Math.abs(K-W)<=Z/Math.abs(Q.multipleOf)},{message:`Must be a multiple of ${Q.multipleOf}`})}}},Lp4=class{apply(Y,X){let Q=X;if(X.type===void 0&&(Q.minItems!==void 0||Q.maxItems!==void 0||Q.items!==void 0||Q.prefixItems!==void 0)){if(Y.array===void 0)Y.array=N.array(N.any())}}},Mp4=class{apply(Y,X){let Q=X;if(Q.minItems===void 0)return;if(Y.array!==!1)Y.array=(Y.array||N.array(N.any())).min(Q.minItems)}},wp4=class{apply(Y,X){let Q=X;if(Q.maxItems===void 0)return;if(Y.array!==!1)Y.array=(Y.array||N.array(N.any())).max(Q.maxItems)}},Pp4=class{apply(Y,X){let Q=X;if(Y.array===!1)return;if(Array.isArray(Q.items))Y.array=Y.array||N.array(N.any());else if(Q.items&&typeof Q.items!=="boolean"&&!Q.prefixItems){let J=qY(Q.items),G=N.array(J);if(Y.array&&Y.array instanceof N.ZodArray){let K=Y.array._def;if(K.checks)K.checks.forEach((W)=>{if(W._zod&&W._zod.def){let Z=W._zod.def;if(Z.check==="min_length"&&Z.minimum!==void 0)G=G.min(Z.minimum);else if(Z.check==="max_length"&&Z.maximum!==void 0)G=G.max(Z.maximum)}})}Y.array=G}else if(typeof Q.items==="boolean"&&Q.items===!1)if(!Q.prefixItems)Y.array=N.array(N.any()).max(0);else Y.array=Y.array||N.array(N.any());else if(typeof Q.items==="boolean"&&Q.items===!0)Y.array=Y.array||N.array(N.any());else if(Q.prefixItems)Y.array=Y.array||N.array(N.any())}},Tp4=class{apply(Y,X){if(X.type!=="array")return;let Q=X;if(!Array.isArray(Q.items))return;if(Y.array===!1)return;let J=Q.items.map((K)=>qY(K)),G;if(J.length===0)G=N.tuple([]);else G=N.tuple(J);if(Q.minItems!==void 0&&Q.minItems>J.length)G=!1;if(Q.maxItems!==void 0&&Q.maxItems<J.length)G=!1;Y.tuple=G,Y.array=!1}},Ap4=class{apply(Y,X){let Q=X;if(Y.object===!1)return;if(Q.properties||Q.required||Q.additionalProperties!==void 0)Y.object=Y.object||N.object({}).passthrough()}},Ep4=class{apply(Y,X){let Q=X;if(X.type===void 0&&(Q.maxProperties!==void 0||Q.minProperties!==void 0)){if(Y.object===void 0)Y.object=N.object({}).passthrough()}}},Cp4=class{apply(Y,X){let Q=X;if(Q.maxProperties===void 0)return;if(Y.object!==!1){let J=Y.object||N.object({}).passthrough();Y.object=J.refine((G)=>Object.keys(G).length<=Q.maxProperties,{message:`Object must have at most ${Q.maxProperties} properties`})}}},Ip4=class{apply(Y,X){let Q=X;if(Q.minProperties===void 0)return;if(Y.object!==!1){let J=Y.object||N.object({}).passthrough();Y.object=J.refine((G)=>Object.keys(G).length>=Q.minProperties,{message:`Object must have at least ${Q.minProperties} properties`})}}},Sp4=class{apply(Y,X){if(!X.not)return Y;let Q=qY(X.not);return Y.refine((J)=>!Nf(Q,J),{message:"Value must not match the 'not' schema"})}},jp4=class{apply(Y,X){if(X.uniqueItems!==!0)return Y;return Y.refine(Rp4(),{message:"Array items must be unique"})}},kp4=class{apply(Y,X){if(!X.allOf||X.allOf.length===0)return Y;return X.allOf.map((J)=>qY(J)).reduce((J,G)=>N.intersection(J,G),Y)}},vp4=class{apply(Y,X){if(!X.anyOf||X.anyOf.length===0)return Y;let Q=X.anyOf.length===1?qY(X.anyOf[0]):N.union([qY(X.anyOf[0]),qY(X.anyOf[1]),...X.anyOf.slice(2).map((J)=>qY(J))]);return N.intersection(Y,Q)}},_p4=class{apply(Y,X){if(!X.oneOf||X.oneOf.length===0)return Y;let Q=X.oneOf.map((J)=>qY(J));return Y.refine((J)=>{let G=0;for(let K of Q)if(K.safeParse(J).success){if(G++,G>1)return!1}return G===1},{message:"Value must match exactly one of the oneOf schemas"})}},yp4=class{apply(Y,X){let Q=X;if(Q.prefixItems&&Array.isArray(Q.prefixItems)){let G=Q.prefixItems.map((K)=>qY(K));return Y.refine((K)=>{if(!Array.isArray(K))return!0;for(let W=0;W<Math.min(K.length,G.length);W++)if(!Nf(G[W],K[W]))return!1;if(K.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 W=qY(Q.items);for(let Z=G.length;Z<K.length;Z++)if(!Nf(W,K[Z]))return!1}}return!0},{message:"Array does not match prefixItems schema"})}return Y}},fp4=class{apply(Y,X){let Q=X;if(!Q.properties&&!Q.required&&Q.additionalProperties!==!1)return Y;if(Y instanceof N.ZodObject||Y instanceof N.ZodRecord){let J={};if(Q.properties){for(let[G,K]of Object.entries(Q.properties))if(K!==void 0)J[G]=qY(K)}if(Q.required&&Array.isArray(Q.required)){let G=new Set(Q.required);for(let K of Object.keys(J))if(!G.has(K))J[K]=J[K].optional()}else for(let G of Object.keys(J))J[G]=J[G].optional();if(Q.additionalProperties===!1)return N.object(J);else return N.object(J).passthrough()}return Y.refine((J)=>{if(typeof J!=="object"||J===null||Array.isArray(J))return!0;if(Q.properties){for(let[G,K]of Object.entries(Q.properties))if(K!==void 0){if(Object.getOwnPropertyDescriptor(J,G)!==void 0){if(!qY(K).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 K in J)if(!G.has(K))return!1}return!0},{message:"Object constraints validation failed"})}},hp4=class{apply(Y,X){if(!X.enum||X.enum.length===0)return Y;let Q=X.enum.filter((J)=>Array.isArray(J)||typeof J==="object"&&J!==null);if(Q.length===0)return Y;return Y.refine((J)=>{if(typeof J!=="object"||J===null)return!0;return Q.some((G)=>wP(J,G))},{message:"Value must match one of the enum values"})}},bp4=class{apply(Y,X){if(X.const===void 0)return Y;let Q=X.const;if(typeof Q!=="object"||Q===null)return Y;return Y.refine((J)=>wP(J,Q),{message:"Value must equal the const value"})}},xp4=class{apply(Y,X){if(X.description)Y=Y.describe(X.description);return Y}},up4=class{apply(Y,X){var Q;let J=X;if(!((Q=J.required)==null?void 0:Q.includes("__proto__"))||X.type!==void 0)return Y;return N.any().refine((G)=>this.validateRequired(G,J.required),{message:"Missing required properties"})}validateRequired(Y,X){if(typeof Y!=="object"||Y===null||Array.isArray(Y))return!0;return X.every((Q)=>Object.prototype.hasOwnProperty.call(Y,Q))}},gp4=class{apply(Y,X){var Q;let J=X;if(J.contains===void 0)return Y;let G=qY(J.contains),K=(Q=J.minContains)!=null?Q:1,W=J.maxContains;return Y.refine((Z)=>{if(!Array.isArray(Z))return!0;let H=0;for(let F of Z)if(Nf(G,F))H++;if(H<K)return!1;if(W!==void 0&&H>W)return!1;return!0},{message:"Array must contain required items matching the schema"})}},mp4=class{apply(Y,X){let{default:Q}=X;if(Q===void 0)return Y;if(!Y.safeParse(Q).success)return Y;return Y.default(Q)}},lp4,dp4;var RH6=x(()=>{I9();I9();I9();I9();I9();I9();I9();I9();I9();I9();I9();I9();I9();I9();lp4=[new Kp4,new Hp4,new Zp4,new Fp4,new Vp4,new Lp4,new Ep4,new qp4,new $p4,new zp4,new Bp4,new Up4,new Dp4,new Op4,new Np4,new Tp4,new Mp4,new wp4,new Pp4,new Cp4,new Ip4,new Ap4],dp4=[new up4,new hp4,new bp4,new kp4,new vp4,new _p4,new yp4,new fp4,new gp4,new Sp4,new jp4,new mp4,new xp4]});class BY0{constructor(Y){this._url=Y}start(){if(this._socket)throw Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((Y,X)=>{this._socket=new WebSocket(this._url,pp4),this._socket.onerror=(Q)=>{let J="error"in Q?Q.error:Error(`WebSocket error: ${JSON.stringify(Q)}`);X(J),this.onerror?.(J)},this._socket.onopen=()=>{Y()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=(Q)=>{let J;try{J=jQ.parse(JSON.parse(Q.data))}catch(G){this.onerror?.(G);return}this.onmessage?.(J)}})}async close(){this._socket?.close()}send(Y){return new Promise((X,Q)=>{if(!this._socket){Q(Error("Not connected"));return}this._socket?.send(JSON.stringify(Y)),X()})}}var pp4="mcp";var SH6=x(()=>{nX()});function cp4(Y){let X=Y;if(!X||typeof X!=="object"||!("method"in X))return null;switch(X.method){case"initialize":{let Q=X?.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:X.jsonrpc??"2.0",id:X.id}}}case"notifications/roots/list_changed":case"notifications/initialized":case"notifications/cancelled":case"notifications/progress":return{type:"suppress"};default:return null}}var UY0;var jH6=x(()=>{ey();UY0=class UY0 extends PB{constructor(Y,X){super(Y,X)}send(Y,X){let Q=cp4(Y);if(Q?.type==="emit")return this.onmessage?.(Q.message),Promise.resolve();if(Q?.type==="suppress")return Promise.resolve();return super.send(Y,X)}}});var kH6,vH6=async(Y,X,Q)=>{let J=np4(Y.connection,X,Q);if(!J)throw Error("Unknown MCP connection type");let G=new kH6({name:Y?.name??"MCP Client",version:"1.0.0"});return await G.connect(J),{client:G,callStreamableTool:(K,W,Z)=>{if(Y.connection.type!=="HTTP")throw Error("HTTP connection required");let H=new Headers(Q);if(!H.has("Authorization"))H.set("Authorization",`Bearer ${Y.connection.token}`);for(let[q,$]of Object.entries(Y.connection.headers??{}))H.set(q,$);let F=new URL(Y.connection.url),V=F.pathname.replace(/\/+$/,"")||"/";return F.pathname=`${V}/call-tool/${encodeURIComponent(K)}`,fetch(F.href,{method:"POST",redirect:"manual",body:JSON.stringify(W),headers:H,signal:Z})}}},np4=(Y,X,Q)=>{if(Y.type==="Websocket")return new BY0(new URL(Y.url));if(Y.type!=="SSE"&&Y.type!=="HTTP")return null;let G={...Y.token?{authorization:`Bearer ${Y.token}`}:{},...Q??{},..."headers"in Y?Y.headers||{}:{}};if(Y.type==="SSE"){let K={requestInit:{headers:G,signal:X}};if(Y.token)K.eventSourceInit={fetch:(W,Z)=>{return fetch(W,{...Z,headers:{...G,Accept:"text/event-stream"},signal:X})}};return new zP(new URL(Y.url),K)}return new UY0(new URL(Y.url),{requestInit:{headers:G,signal:X,credentials:"include"}})};var _H6=x(()=>{by();U90();SH6();nX();jH6();kH6=class kH6 extends i3{constructor(Y,X){super(Y,X)}async listTools(Y,X){return await this.request({method:"tools/list",params:Y},Cw,X)}}});function fH6(Y){let X=(Q)=>{if("connection"in Y)return vH6({connection:Y.connection},void 0,Q);return Y.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 Z;async function G(H,F=J){let V=Y?.debugId?.(),q=V?{"x-trace-debug-id":V}:void 0,{client:$,callStreamableTool:B}=await X(q);if(Y?.streamable?.[String(F)])return B(String(F),H);let{structuredContent:U,isError:O,content:L}=await $.callTool({name:String(F),arguments:H});if(O){let M=L?.[0]?.text,C=typeof M==="string"?ip4(M):null,R=C?.code&&typeof Y?.getErrorByStatusCode==="function"?Y.getErrorByStatusCode(C.code,C.message,C.traceId):null;if(R)throw R;throw Error(`Tool ${String(F)} returned an error: ${JSON.stringify(U??L)}`)}return U}async function K(){let{client:H}=await X(),{tools:F}=await H.listTools();return F}async function W(){if(!("connection"in Y))return K();let H=Y.connection,F=JSON.stringify(H);try{if(!Lf.has(F))Lf.set(F,K());return await Lf.get(F)}catch(V){console.error("Failed to list tools",V),Lf.delete(F);return}}async function Z(){return(await W()??[]).map((F)=>yH6(F,G))}return G.asTool=async()=>{let F=(await W()??[]).find((V)=>V.name===J);if(!F)throw Error(`Tool ${J} not found`);return yH6(F,G)},G}})}var ip4=(Y)=>{try{return JSON.parse(Y)}catch{return Y}},Lf,yH6=(Y,X)=>{return{...Y,id:Y.name,inputSchema:Y.inputSchema?qY(Y.inputSchema):void 0,outputSchema:Y.outputSchema?qY(Y.outputSchema):void 0,execute:(Q)=>{return X(Q.context,Y.name)}}};var hH6=x(()=>{RH6();_H6();Lf=new Map});function Mf(Y){return fH6(Y)}var Ms1;var bH6=x(()=>{hH6();Ms1=new Proxy({},{get(Y,X){if(X==="toJSON")return null;if(X==="forConnection")return(Q)=>Mf({connection:Q});return global[X]}})});function wf(Y){return{isImplementedBy:(X)=>{for(let Q of Y){let J=typeof Q.name==="string"?new RegExp(`^${Q.name}$`):Q.name,G=X.find((K)=>J.test(K.name));if(!G&&Q.opt)continue;if(!G)return!1}return!0}}}var ZV=(Y)=>{return{...wf(Y),forClient:(X)=>{return Mf({client:X,streamable:Y.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})},forConnection:(X)=>{return Mf({connection:X,streamable:Y.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})}}};var PP=x(()=>{bH6()});function bW(Y){return N.object({items:N.array(Y).describe("Array of collection items"),totalCount:N.number().int().min(0).optional().describe("Total number of matching items (if available)"),hasMore:N.boolean().optional().describe("Whether there are more items available")})}function AP(Y){return N.object({item:Y.nullable().describe("The retrieved item, or null if not found")})}function op4(Y){return N.object({data:Y.partial().describe("Data for the new entity (id may be auto-generated)")})}function sp4(Y){return N.object({item:Y.describe("The created entity with generated id")})}function tp4(Y){return N.object({id:N.string().describe("ID of the entity to update"),data:Y.partial().describe("Partial entity data to update")})}function ep4(Y){return N.object({item:Y.describe("The updated entity")})}function CP(Y){return N.object({item:Y.describe("The deleted entity")})}function mB(Y,X,Q){let J=Y.toUpperCase(),G=Q?.readOnly??!1,K=[{name:`COLLECTION_${J}_LIST`,inputSchema:hW,outputSchema:bW(X)},{name:`COLLECTION_${J}_GET`,inputSchema:TP,outputSchema:AP(X)}];if(!G)K.push({name:`COLLECTION_${J}_CREATE`,inputSchema:op4(X),outputSchema:sp4(X),opt:!0},{name:`COLLECTION_${J}_UPDATE`,inputSchema:tp4(X),outputSchema:ep4(X),opt:!0},{name:`COLLECTION_${J}_DELETE`,inputSchema:EP,outputSchema:CP(X),opt:!0});return K}var gB,ap4,xH6,rp4,hW,TP,EP;var bJ=x(()=>{g0();gB=N.object({id:N.string().describe("Unique identifier for the entity"),title:N.string().describe("Human-readable title for the entity"),description:N.string().nullish().describe("Description of the entity"),created_at:N.string().datetime(),updated_at:N.string().datetime(),created_by:N.string().optional(),updated_by:N.string().optional()}),ap4=N.object({field:N.array(N.string()),operator:N.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:N.unknown()}),xH6=N.lazy(()=>N.union([ap4,N.object({operator:N.enum(["and","or","not"]),conditions:N.array(xH6)})])),rp4=N.object({field:N.array(N.string()),direction:N.enum(["asc","desc"]),nulls:N.enum(["first","last"]).optional()}),hW=N.object({where:xH6.optional().describe("Filter expression"),orderBy:N.array(rp4).optional().describe("Sort expressions"),limit:N.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:N.number().int().min(0).optional().describe("Number of items to skip")});TP=N.object({id:N.string().describe("ID of the entity to retrieve")});EP=N.object({id:N.string().describe("ID of the entity to delete")})});var Yc4,uH6,Ss1;var gH6=x(()=>{g0();bJ();Yc4=N.object({id:N.string(),name:N.string(),description:N.string().optional(),inputSchema:N.record(N.string(),N.unknown()),outputSchema:N.record(N.string(),N.unknown()).optional()}),uH6=gB.extend({_meta:N.object({"io.decocms":N.object({id:N.string(),verified:N.boolean(),scopeName:N.string(),appName:N.string(),friendlyName:N.string().nullable().optional(),metadata:N.record(N.string(),N.unknown()).nullable().optional(),publishedAt:N.string().datetime().optional(),updatedAt:N.string().datetime().optional(),tools:N.array(Yc4).nullable().optional().describe("Available tools exposed by this app")}).optional()}).optional(),server:N.object({$schema:N.string().optional(),_meta:N.record(N.string(),N.unknown()).optional(),name:N.string().describe("The server name (scope/app)"),title:N.string().optional().describe("User-friendly title"),description:N.string().optional().describe("Server description"),icons:N.array(N.object({src:N.string(),mimeType:N.string().optional(),sizes:N.array(N.string()).optional(),theme:N.enum(["light","dark"]).optional()})).optional(),remotes:N.array(N.object({type:N.enum(["http","stdio","sse"]),url:N.string().optional(),headers:N.array(N.unknown()).optional()})).optional(),packages:N.array(N.unknown()).optional(),repository:N.object({url:N.string(),source:N.string().optional(),subfolder:N.string().optional()}).optional(),version:N.string().optional(),websiteUrl:N.string().optional()})}),Ss1=mB("registry_app",uH6,{readOnly:!0})});var mH6,lH6,dH6,pH6,cH6,Xc4;var nH6=x(()=>{g0();PP();mH6=N.object({specversion:N.literal("1.0").describe("CloudEvents specification version"),id:N.string().describe("Unique identifier for this event (UUID recommended)"),source:N.string().describe("Connection ID of the event publisher"),type:N.string().describe("Event type (e.g., 'order.created', 'user.signup')"),time:N.string().datetime().optional().describe("Timestamp of when the event occurred (ISO 8601)"),subject:N.string().optional().describe("Subject/resource identifier (e.g., order ID, user ID)"),datacontenttype:N.string().optional().default("application/json").describe("Content type of the data attribute"),dataschema:N.string().url().optional().describe("URI to the schema for the data attribute"),data:N.unknown().optional().describe("Event payload (any JSON value)")}),lH6=N.object({events:N.array(mH6).min(1).describe("Batch of CloudEvents to process")}),dH6=N.object({success:N.boolean().optional().describe("Whether this event was processed successfully"),error:N.string().optional().describe("Error message for this event"),retryAfter:N.number().int().positive().optional().describe("Re-deliver this event after this many ms")}),pH6=N.object({success:N.boolean().optional().describe("Batch success - applies to events not in results"),error:N.string().optional().describe("Batch error message - applies to events not in results"),processedCount:N.number().int().min(0).optional().describe("Number of events successfully processed"),retryAfter:N.number().int().positive().optional().describe("Batch retryAfter - applies to events not in results"),results:N.record(N.string(),dH6).optional().describe("Per-event results keyed by event ID")}),cH6=[{name:"ON_EVENTS",inputSchema:lH6,outputSchema:pH6}],Xc4=ZV(cH6)});var IP,RP,SP,jP,iH6,aH6,kP,vP,_P,yP,fP,hP,bP,xP,rH6,Qc4;var oH6=x(()=>{g0();PP();IP=N.object({type:N.string().min(1).max(255).describe("Event type identifier"),subject:N.string().max(255).optional().describe("Subject/resource identifier (e.g., order ID)"),data:N.unknown().optional().describe("Event payload"),deliverAt:N.string().datetime().optional().describe("Scheduled delivery time (ISO 8601). Omit for immediate delivery."),cron:N.string().max(100).optional().describe("Cron expression for recurring delivery. Use EVENT_CANCEL to stop.")}),RP=N.object({id:N.string().describe("Unique event ID"),type:N.string().describe("Event type"),source:N.string().describe("Source connection ID"),time:N.string().describe("Event timestamp")}),SP=N.object({eventType:N.string().min(1).max(255).describe("Event type to subscribe to"),publisher:N.string().optional().describe("Filter events by publisher connection ID"),filter:N.string().max(1000).optional().describe("JSONPath filter expression on event data")}),jP=N.object({subscription:N.object({id:N.string().describe("Subscription ID"),connectionId:N.string().describe("Subscriber connection ID"),eventType:N.string().describe("Event type pattern"),publisher:N.string().nullable().describe("Publisher connection filter"),filter:N.string().nullable().describe("JSONPath filter expression"),enabled:N.boolean().describe("Whether subscription is enabled"),createdAt:N.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:N.string().datetime().describe("Updated timestamp (ISO 8601)")})}),iH6=N.object({eventType:N.string().min(1).max(255).describe("Event type to subscribe to"),publisher:N.string().optional().describe("Filter events by publisher connection ID"),filter:N.string().max(1000).optional().describe("JSONPath filter expression on event data")}),aH6=N.object({id:N.string().describe("Subscription ID"),connectionId:N.string().describe("Subscriber connection ID"),eventType:N.string().describe("Event type pattern"),publisher:N.string().nullable().describe("Publisher connection filter"),filter:N.string().nullable().describe("JSONPath filter expression"),enabled:N.boolean().describe("Whether subscription is enabled"),createdAt:N.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:N.string().datetime().describe("Updated timestamp (ISO 8601)")}),kP=N.object({subscriptions:N.array(iH6).describe("Desired subscriptions - system will create/update/delete to match")}),vP=N.object({created:N.number().int().min(0).describe("Number of subscriptions created"),updated:N.number().int().min(0).describe("Number of subscriptions with filter updated"),deleted:N.number().int().min(0).describe("Number of subscriptions removed"),unchanged:N.number().int().min(0).describe("Number of subscriptions unchanged"),subscriptions:N.array(aH6).describe("Current subscriptions after sync")}),_P=N.object({subscriptionId:N.string().describe("Subscription ID to remove")}),yP=N.object({success:N.boolean().describe("Whether unsubscribe was successful"),subscriptionId:N.string().describe("Subscription ID that was removed")}),fP=N.object({eventId:N.string().describe("Event ID to cancel")}),hP=N.object({success:N.boolean().describe("Whether cancellation was successful"),eventId:N.string().describe("Event ID that was cancelled")}),bP=N.object({eventId:N.string().describe("Event ID to acknowledge")}),xP=N.object({success:N.boolean().describe("Whether ACK was successful"),eventId:N.string().describe("Event ID that was acknowledged")}),rH6=[{name:"EVENT_PUBLISH",inputSchema:IP,outputSchema:RP},{name:"EVENT_SUBSCRIBE",inputSchema:SP,outputSchema:jP},{name:"EVENT_UNSUBSCRIBE",inputSchema:_P,outputSchema:yP},{name:"EVENT_CANCEL",inputSchema:fP,outputSchema:hP},{name:"EVENT_ACK",inputSchema:bP,outputSchema:xP},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:kP,outputSchema:vP}],Qc4=ZV(rH6)});var Jc4,Gc4,Wc4,Zc4,Kc4,Hc4,Fc4,Vc4,qc4,$c4,zc4,Bc4,uP;var Pf=x(()=>{g0();Jc4=N.object({prefix:N.string().optional().describe("Filter objects by prefix (e.g., 'folder/' for folder contents)"),maxKeys:N.number().optional().default(1000).describe("Maximum number of keys to return (default: 1000)"),continuationToken:N.string().optional().describe("Token for pagination from previous response"),delimiter:N.string().optional().describe("Delimiter for grouping keys (typically '/'). When set, commonPrefixes returns folder paths.")}),Gc4=N.object({objects:N.array(N.object({key:N.string().describe("Object key/path"),size:N.number().describe("Object size in bytes"),lastModified:N.string().describe("Last modified timestamp"),etag:N.string().describe("Entity tag for the object")})),nextContinuationToken:N.string().optional().describe("Token for fetching next page of results"),isTruncated:N.boolean().describe("Whether there are more results available"),commonPrefixes:N.array(N.string()).optional().describe("Folder paths when delimiter is used (e.g., ['photos/2024/', 'photos/2025/'])")}),Wc4=N.object({key:N.string().describe("Object key/path to get metadata for")}),Zc4=N.object({contentType:N.string().optional().describe("MIME type of the object"),contentLength:N.number().describe("Size of the object in bytes"),lastModified:N.string().describe("Last modified timestamp"),etag:N.string().describe("Entity tag for the object"),metadata:N.record(N.string(),N.string()).optional().describe("Custom metadata key-value pairs")}),Kc4=N.object({key:N.string().describe("Object key/path to generate URL for"),expiresIn:N.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)")}),Hc4=N.object({url:N.string().describe("Presigned URL for downloading the object"),expiresIn:N.number().describe("Expiration time in seconds that was used")}),Fc4=N.object({key:N.string().describe("Object key/path for the upload"),expiresIn:N.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)"),contentType:N.string().optional().describe("MIME type for the object being uploaded")}),Vc4=N.object({url:N.string().describe("Presigned URL for uploading the object"),expiresIn:N.number().describe("Expiration time in seconds that was used")}),qc4=N.object({key:N.string().describe("Object key/path to delete")}),$c4=N.object({success:N.boolean().describe("Whether the deletion was successful"),key:N.string().describe("The key that was deleted")}),zc4=N.object({keys:N.array(N.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),Bc4=N.object({deleted:N.array(N.string()).describe("Array of successfully deleted keys"),errors:N.array(N.object({key:N.string(),message:N.string()})).describe("Array of errors for failed deletions")}),uP=[{name:"LIST_OBJECTS",inputSchema:Jc4,outputSchema:Gc4},{name:"GET_OBJECT_METADATA",inputSchema:Wc4,outputSchema:Zc4},{name:"GET_PRESIGNED_URL",inputSchema:Kc4,outputSchema:Hc4},{name:"PUT_PRESIGNED_URL",inputSchema:Fc4,outputSchema:Vc4},{name:"DELETE_OBJECT",inputSchema:qc4,outputSchema:$c4},{name:"DELETE_OBJECTS",inputSchema:zc4,outputSchema:Bc4}]});var DY0=x(()=>{PP();gH6();nH6();oH6();Pf()});var Uc4,Dc4,sH6;var tH6=x(()=>{g0();bJ();Uc4=gB.extend({avatar:N.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:N.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:N.string().describe("Virtual MCP ID to use for this assistant"),model:N.object({id:N.string().describe("Model ID"),connectionId:N.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),Dc4=mB("assistant",Uc4),sH6=[...Dc4]});var gP,xW,YF6,Oc4,Nc4,XF6,Lc4,Mc4,wc4,Pc4,Tc4,Ac4,QF6,Ec4,Cc4,Ic4,Rc4,Sc4,jc4,kc4,vc4,_c4,yc4,es1,fc4,Yt1,eH6,hc4,bc4,OY0,Xt1;var JF6=x(()=>{g0();PP();bJ();gP=N.lazy(()=>N.union([N.null(),N.string(),N.number(),N.boolean(),N.record(N.string(),gP),N.array(gP)])),xW=N.record(N.string(),N.record(N.string(),gP)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),YF6=N.object({type:N.literal("text"),text:N.string().describe("The text content"),providerOptions:xW}),Oc4=N.object({type:N.literal("text"),text:N.string().describe("The text content"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),Nc4=N.string().describe("File data as URL string"),XF6=N.object({type:N.literal("file"),filename:N.string().optional().describe("Optional filename of the file"),data:Nc4,mediaType:N.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:xW}),Lc4=N.object({type:N.literal("file"),mediaType:N.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:N.string().describe("Generated file data as base64 encoded string")}),Mc4=N.object({type:N.literal("reasoning"),text:N.string().describe("The reasoning text"),providerOptions:xW}),wc4=N.object({type:N.literal("reasoning"),text:N.string().describe("The reasoning text"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),Pc4=N.object({type:N.literal("tool-call"),toolCallId:N.string().describe("ID of the tool call, used to match with tool result"),toolName:N.string().describe("Name of the tool being called"),input:N.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:N.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:xW}),Tc4=N.object({type:N.literal("tool-call"),toolCallId:N.string().describe("ID of the tool call"),toolName:N.string().describe("Name of the tool being called"),input:N.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:N.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),Ac4=N.union([N.object({type:N.literal("text"),value:N.string()}),N.object({type:N.literal("json"),value:gP}),N.object({type:N.literal("error-text"),value:N.string()}),N.object({type:N.literal("error-json"),value:gP}),N.object({type:N.literal("content"),value:N.array(N.union([N.object({type:N.literal("text"),text:N.string().describe("Text content")}),N.object({type:N.literal("media"),data:N.string().describe("Base-64 encoded media data"),mediaType:N.string().describe("IANA media type")})]))})]),QF6=N.object({type:N.literal("tool-result"),toolCallId:N.string().describe("ID of the tool call that this result is associated with"),toolName:N.string().describe("Name of the tool that generated this result"),output:Ac4.describe("Result of the tool call"),result:N.unknown().describe("Unknown result of the tool call"),providerOptions:xW}),Ec4=N.object({type:N.literal("tool-result"),toolCallId:N.string().describe("ID of the tool call that this result is associated with"),toolName:N.string().describe("Name of the tool that generated this result"),result:N.any().describe("Result of the tool call (JSON-serializable)"),isError:N.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:N.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),Cc4=N.union([N.object({type:N.literal("source"),sourceType:N.literal("url"),id:N.string().describe("The ID of the source"),url:N.string().describe("The URL of the source"),title:N.string().optional().describe("The title of the source"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),N.object({type:N.literal("source"),sourceType:N.literal("document"),id:N.string().describe("The ID of the source"),mediaType:N.string().describe("IANA media type of the document (e.g., application/pdf)"),title:N.string().describe("The title of the document"),filename:N.string().optional().describe("Optional filename of the document"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")})]),Ic4=N.object({role:N.literal("system"),content:N.string().describe("System message content"),providerOptions:xW}),Rc4=N.object({role:N.literal("user"),content:N.array(N.union([YF6,XF6])).describe("User message content parts (text or file)"),providerOptions:xW}),Sc4=N.object({role:N.literal("assistant"),content:N.array(N.union([YF6,XF6,Mc4,Pc4,QF6])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:xW}),jc4=N.object({role:N.literal("tool"),content:N.array(QF6).describe("Tool message content (tool results)"),providerOptions:xW}),kc4=N.union([Ic4,Rc4,Sc4,jc4]),vc4=N.array(kc4).describe("A list of messages forming the prompt"),_c4=N.object({prompt:vc4.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:N.number().optional().describe("Maximum number of tokens to generate"),temperature:N.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:N.number().optional().describe("Nucleus sampling parameter"),topK:N.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:N.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:N.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:N.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:N.array(N.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:N.union([N.object({type:N.literal("text")}),N.object({type:N.literal("json"),schema:N.any().optional().describe("JSON schema that the generated output should conform to"),name:N.string().optional().describe("Name of output that should be generated"),description:N.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:N.array(N.any()).optional().describe("The tools that are available for the model"),toolChoice:N.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:N.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:N.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:N.any().optional().describe("Additional provider-specific options")}),yc4=N.object({content:N.array(N.union([Oc4,Lc4,wc4,Tc4,Ec4,Cc4])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:N.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:N.looseObject({inputTokens:N.number().optional(),outputTokens:N.number().optional(),totalTokens:N.number().optional(),reasoningTokens:N.number().optional()}).describe("Usage information for the language model call"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata"),request:N.object({body:N.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:N.object({id:N.string().optional().describe("ID for the generated response"),timestamp:N.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:N.string().optional().describe("The ID of the response model that was used"),headers:N.record(N.string(),N.string()).optional().describe("Response headers"),body:N.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:N.array(N.any()).describe("Warnings for the call, e.g. unsupported settings")}),es1=N.object({stream:N.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:N.object({body:N.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:N.object({headers:N.record(N.string(),N.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),fc4=N.object({supportedUrls:N.record(N.string(),N.array(N.string())).describe("Supported URL patterns by media type for the provider")}),Yt1=N.object({modelId:N.string().describe("The ID of the model"),logo:N.string().nullable(),description:N.string().nullable(),capabilities:N.array(N.string()),limits:N.object({contextWindow:N.number(),maxOutputTokens:N.number()}).nullable(),costs:N.object({input:N.number(),output:N.number()}).nullable(),provider:N.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),eH6=N.object({modelId:N.string().describe("The ID of the model"),callOptions:_c4}),hc4=gB.extend({logo:N.string().nullable(),description:N.string().nullable(),capabilities:N.array(N.string()),limits:N.object({contextWindow:N.number(),maxOutputTokens:N.number()}).nullable(),costs:N.object({input:N.number(),output:N.number()}).nullable(),provider:N.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),bc4=mB("llm",hc4,{readOnly:!0}),OY0=[{name:"LLM_METADATA",inputSchema:N.object({modelId:N.string().describe("The ID of the model")}),outputSchema:fc4},{name:"LLM_DO_STREAM",inputSchema:eH6,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:eH6,outputSchema:yc4},...bc4],Xt1=ZV(OY0)});function Tf(){return!1}function GF6(Y,X){return Y===k5.DEV_ASSETS(X)}function Af(Y,X){let Q=d80(X,Y),J=new Date().toISOString();return{id:Q.id??k5.DEV_ASSETS(Y),title:Q.title,description:Q.description??null,icon:Q.icon??null,app_name:Q.app_name??null,app_id:Q.app_id??null,organization_id:Y,created_by:"system",created_at:J,updated_at:J,connection_type:Q.connection_type,connection_url:Q.connection_url??null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:Q.metadata??null,tools:xc4,bindings:["OBJECT_STORAGE"],status:"active"}}var xc4;var NY0=x(()=>{Pf();TB();g0();xc4=uP.map((Y)=>({name:Y.name,description:`${Y.name} operation for local file storage`,inputSchema:N.toJSONSchema(Y.inputSchema),outputSchema:N.toJSONSchema(Y.outputSchema)}))});function gc4(Y){let X=[],Q=0;while(Q<Y.length){let J=Y[Q];if(J==="%")X.push(".*");else if(J==="_")X.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))X.push("\\"+J);else X.push(J);Q++}return X.join("")}function QK(Y){return typeof Y==="string"||typeof Y==="number"}function Ef(Y,X){if("conditions"in X){let{operator:Z,conditions:H}=X;switch(Z){case"and":return H.every((F)=>Ef(Y,F));case"or":return H.some((F)=>Ef(Y,F));case"not":return!H.every((F)=>Ef(Y,F));default:return!0}}let{field:Q,operator:J,value:G}=X,K=Q.join("."),W=LY0(Y,K);switch(J){case"eq":return W===G;case"gt":return QK(W)&&QK(G)&&W>G;case"gte":return QK(W)&&QK(G)&&W>=G;case"lt":return QK(W)&&QK(G)&&W<G;case"lte":return QK(W)&&QK(G)&&W<=G;case"in":return Array.isArray(G)&&G.includes(W);case"like":if(typeof W!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let Z=gc4(G);return new RegExp(`^${Z}$`,"i").test(W);case"contains":if(typeof W!=="string"||typeof G!=="string")return!1;return W.toLowerCase().includes(G.toLowerCase());default:return!0}}function LY0(Y,X){let Q=X.split("."),J=Y;for(let G of Q){if(J==null||typeof J!=="object")return;J=J[G]}return J}function mc4(Y,X){return[...Y].sort((Q,J)=>{for(let G of X){let K=G.field.join("."),W=LY0(Q,K),Z=LY0(J,K),H=0;if(W==null&&Z==null)continue;if(W==null)H=G.nulls==="first"?-1:1;else if(Z==null)H=G.nulls==="first"?1:-1;else if(typeof W==="string"&&typeof Z==="string")H=W.localeCompare(Z);else if(typeof W==="number"&&typeof Z==="number")H=W-Z;else H=String(W).localeCompare(String(Z));if(H!==0)return G.direction==="desc"?-H:H}return 0})}var uc4,lc4,dc4,MY0;var WF6=x(()=>{DY0();tH6();bJ();JF6();Pf();TB();g0();f6();NY0();s3();uc4={LLM:OY0,ASSISTANTS:sH6,OBJECT_STORAGE:uP};lc4=hW.extend({binding:N.union([N.object({}).passthrough(),N.string()]).optional(),include_virtual:N.boolean().optional().describe("Whether to include VIRTUAL connections in the results. Defaults to false.")}),dc4=bW(DX),MY0=v0({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",inputSchema:lc4,outputSchema:dc4,handler:async(Y,X)=>{await X.access.check();let Q=H6(X),J=Y.binding?typeof Y.binding==="string"?(()=>{let $=uc4[Y.binding.toUpperCase()];if(!$)throw Error(`Unknown binding: ${Y.binding}`);return $})():Y.binding:void 0,G=J?wf(J):void 0,K=await X.storage.connections.list(Q.id,{includeVirtual:Y.include_virtual??!1});if(Tf()){let $=o7(),B=k5.DEV_ASSETS(Q.id);if(!K.some((U)=>U.id===B)){let U=Af(Q.id,$);K.unshift(U)}}let W=G?await Promise.all(K.map(async($)=>{if(!$.tools||$.tools.length===0)return null;return G.isImplementedBy($.tools.map((U)=>({name:U.name,inputSchema:U.inputSchema,outputSchema:U.outputSchema})))?$:null})).then(($)=>$.filter((B)=>B!==null)):K;if(Y.where)W=W.filter(($)=>Ef($,Y.where));if(Y.orderBy&&Y.orderBy.length>0)W=mc4(W,Y.orderBy);let Z=W.length,H=Y.offset??0,F=Y.limit??100,V=W.slice(H,H+F),q=H+F<Z;return{items:V,totalCount:Z,hasMore:q}}})});var pc4,wY0;var ZF6=x(()=>{bJ();f6();NY0();s3();pc4=AP(DX),wY0=v0({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",inputSchema:TP,outputSchema:pc4,handler:async(Y,X)=>{let Q=H6(X);if(await X.access.check(),Tf()&&GF6(Y.id,Q.id))return{item:Af(Q.id,o7())};let J=await X.storage.connections.findById(Y.id);if(!J||J.organization_id!==Q.id)return{item:null};return{item:J}}})});var Cf=(Y,X)=>{if(X===null||X===void 0)return;let Q=Y.replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),J=X;for(let G of Q){if(J===null||J===void 0||typeof J!=="object")return;J=J[G]}return J};function KF6(Y){let X=Y.split("::");if(X.length!==2||!X[0]||!X[1])throw Error(`Invalid scope format: ${Y}. Expected format: "KEY::SCOPE"`);return X}function cc4(Y){let X=Y.split("::");if(X.length!==2||!X[0]||!X[1])return null;return X}function nc4(Y){if(typeof Y==="object"&&Y!==null&&"value"in Y){let X=Y.value;if(typeof X==="string")return X}return null}function ic4(Y,X){let Q={};if(!Y||!X)return Q;for(let J of X){if(J==="*"){Q["*"]=["*"];continue}let G=cc4(J);if(!G)continue;let[K,W]=G,Z=Cf(K,Y),H=nc4(Z);if(H){if(!Q[H])Q[H]=[];Q[H].push(W)}}return Q}function HF6(Y,X){let Q=ic4(Y,X);return new Set(Object.keys(Q).filter((J)=>J!=="*"))}var FF6=()=>{};class PY0{db;vault;constructor(Y,X){this.db=Y;this.vault=X}async get(Y){let X=await this.db.selectFrom("downstream_tokens").selectAll().where("connectionId","=",Y).executeTakeFirst();if(!X)return null;return this.decryptToken(X)}async upsert(Y){let X=new Date().toISOString(),Q=await this.vault.encrypt(Y.accessToken),J=Y.refreshToken?await this.vault.encrypt(Y.refreshToken):null,G=Y.clientSecret?await this.vault.encrypt(Y.clientSecret):null;return await this.db.transaction().execute(async(K)=>{let W=await K.selectFrom("downstream_tokens").select(["id","createdAt"]).where("connectionId","=",Y.connectionId).executeTakeFirst();if(W)return await K.updateTable("downstream_tokens").set({accessToken:Q,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,updatedAt:X}).where("id","=",W.id).execute(),{id:W.id,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:W.createdAt,updatedAt:X,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint};let Z=EB("dtok");return await K.insertInto("downstream_tokens").values({id:Z,connectionId:Y.connectionId,accessToken:Q,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,createdAt:X,updatedAt:X}).execute(),{id:Z,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:X,updatedAt:X,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint}})}async delete(Y){await this.db.deleteFrom("downstream_tokens").where("connectionId","=",Y).execute()}isExpired(Y,X=0){if(!Y.expiresAt)return!1;let J=(Y.expiresAt instanceof Date?Y.expiresAt:new Date(Y.expiresAt)).getTime();if(Number.isNaN(J))return!0;return J-X<Date.now()}async decryptToken(Y){let X=await this.vault.decrypt(Y.accessToken),Q=Y.refreshToken?await this.vault.decrypt(Y.refreshToken):null,J=Y.clientSecret?await this.vault.decrypt(Y.clientSecret):null;return{id:Y.id,connectionId:Y.connectionId,accessToken:X,refreshToken:Q,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Y.createdAt,updatedAt:Y.updatedAt,clientId:Y.clientId,clientSecret:J,tokenEndpoint:Y.tokenEndpoint}}}var VF6=x(()=>{Gf()});async function oc4(Y,X,Q,J){for(let K of X){if(K==="*")continue;let[W]=KF6(K),Z=Cf(W,Y);if(Z===void 0||Z===null)throw Error(`Scope references key "${W}" but it's not present in state`)}let G=HF6(Y,X);for(let K of G){if(K.endsWith("_self"))continue;let W=await J.storage.connections.findById(K);if(!W||W.organization_id!==Q)throw Error(`Referenced connection not found: ${K}`);try{await J.access.check(K)}catch(Z){throw Error(`Access denied to referenced connection: ${K}. ${Z.message}`)}}}var ac4,rc4,TY0;var qF6=x(()=>{FF6();VF6();g0();f6();Ff();s3();ac4=N.object({id:N.string().describe("ID of the connection to update"),data:JP.describe("Partial connection data to update")}),rc4=N.object({item:DX.describe("The updated connection entity")});TY0=v0({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update an existing MCP connection in the organization",inputSchema:ac4,outputSchema:rc4,handler:async(Y,X)=>{t0(X);let Q=H6(X);await X.access.check();let J=_8(X);if(!J)throw Error("User ID required to update connection");let{id:G,data:K}=Y,W=await X.storage.connections.findById(G);if(!W||W.organization_id!==Q.id)throw Error("Connection not found in organization");let Z=K.connection_type??W.connection_type,H=K.connection_url??W.connection_url;if(Z==="VIRTUAL"){let T=tF(H);if(!T)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let I=await X.storage.virtualMcps.findById(T);if(!I)throw Error(`Virtual MCP not found: ${T}`);if(I.organization_id!==Q.id)throw Error("Virtual MCP does not belong to the current organization");H=eF(T)}let F=K.configuration_state??W.configuration_state,V=K.configuration_scopes??W.configuration_scopes??[];if(K.configuration_state!==void 0||K.configuration_scopes!==void 0){if(K.configuration_state!==void 0)F=K.configuration_state;else if(F===null)F={};if(K.configuration_scopes!==void 0)V=K.configuration_scopes??[];if(V.length>0&&F)await oc4(F,V,Q.id,X)}let q=K.connection_token??W.connection_token;if(!q)try{let I=await new PY0(X.db,X.vault).get(G);if(I?.accessToken)q=I.accessToken}catch{}let $=await yB({id:W.id,title:K.title??W.title,connection_type:Z,connection_url:H,connection_token:q,connection_headers:K.connection_headers??W.connection_headers}).catch(()=>null),B=$?.length?$:null,U={...K,connection_url:H,tools:B,configuration_state:F,configuration_scopes:V,updated_by:J},O=await X.storage.connections.update(G,U);if((K.configuration_state!==void 0||K.configuration_scopes!==void 0)&&F&&V.length>0)try{let L=[];try{const T=nB(L,await X.createMCPProxy(G),1);await T.callTool({name:"ON_MCP_CONFIGURATION",arguments:{state:F,scopes:V}});await T.close().catch(console.error)}catch(M){var C=M,R=1}finally{var E=dP(L,C,R);E&&await E}}catch(T){console.error("Failed to invoke ON_MCP_CONFIGURATION callback",T)}return{item:O}}})});var AY0;var $F6=x(()=>{bJ();f6();s3();AY0=v0({name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete a connection",inputSchema:EP,outputSchema:CP(DX),handler:async(Y,X)=>{t0(X);let Q=H6(X);await X.access.check();let J=await X.storage.connections.findById(Y.id);if(!J)throw Error(`Connection not found: ${Y.id}`);if(J.organization_id!==Q.id)throw Error("Connection not found in organization");if(J.metadata?.isFixed===!0)throw Error("This connection is a fixed system connection and cannot be deleted");return await X.storage.connections.delete(Y.id),{item:J}}})});var EY0;var zF6=x(()=>{g0();f6();EY0=v0({name:"CONNECTION_TEST",description:"Test connection health and latency",inputSchema:N.object({id:N.string()}),outputSchema:N.object({id:N.string(),healthy:N.boolean(),latencyMs:N.number()}),handler:async(Y,X)=>{let Q=H6(X);await X.access.check();let J=await X.storage.connections.findById(Y.id);if(!J||J.organization_id!==Q.id)throw Error("Connection not found");let G=await X.storage.connections.testConnection(Y.id);return{id:Y.id,...G}}})});var BF6=x(()=>{IH6();WF6();ZF6();qF6();$F6();zF6()});import{sql as s4}from"kysely";function UF6(Y){if(Y===null||Y===void 0)return"NULL";if(typeof Y==="number")return String(Y);if(typeof Y==="boolean")return Y?"TRUE":"FALSE";if(typeof Y==="string")return`'${Y.replace(/'/g,"''")}'`;if(Y instanceof Date)return`'${Y.toISOString()}'`;return`'${JSON.stringify(Y).replace(/'/g,"''")}'`}function ec4(Y,X){let Q=Y;for(let G=X.length;G>=1;G--){let K=`$${G}`;if(Q.includes(K))Q=Q.replaceAll(K,UF6(X[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,X.length)-1;G>=0;G--){let K=J[G],W=UF6(X[G]);Q=Q.slice(0,K)+W+Q.slice(K+1)}return Q}function DF6(Y){return Y.replace(/-/g,"_")}function Xn4(Y){return`app_${DF6(Y)}`}function Qn4(Y){return`app_role_${DF6(Y)}`}function Jn4(Y){if(Y instanceof Error){let X=Y.message.toLowerCase(),Q=Y.code;return Q==="3F000"||Q==="42704"||X.includes("schema")&&X.includes("does not exist")||X.includes("role")&&X.includes("does not exist")}return!1}async function Gn4(Y,X,Q){if(await s4`CREATE SCHEMA IF NOT EXISTS ${s4.id(X)}`.execute(Y),!(await s4`
419
+ ${X.stack}`;return G}}catch{}if(typeof X.toString==="function")try{let G=X.toString();if(G!=="[object Object]")return G}catch{}let J=Object.keys(X);if(J.length>0)return`Object with keys: ${J.join(", ")}`;return"[object Object]"}if(typeof Y==="string")return Y;if(typeof Y==="number"||typeof Y==="boolean")return String(Y);if(typeof Y==="function")return`[Function: ${Y.name||"anon"}]`;if(typeof Y==="symbol")return Y.toString();if(typeof Y==="bigint")return Y.toString();try{return String(Y)}catch{return"Unknown value (could not convert to string)"}}function xB(Y,X){switch(typeof X){case"string":return Y.newString(X);case"number":return Y.newNumber(X);case"boolean":return X?Y.true:Y.false;case"undefined":return Y.undefined;case"object":{if(X===null)return Y.null;if(Array.isArray(X)){let J=Y.newArray();return X.forEach((G,K)=>{let W=xB(Y,G);try{Y.setProp(J,String(K),W)}finally{W.dispose?.()}}),J}let Q=Y.newObject();for(let[J,G]of Object.entries(X)){let K=xB(Y,G);try{Y.setProp(Q,J,K)}finally{K.dispose?.()}}return Q}case"function":{let Q=`__hostFn_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return Y.newFunction(Q,(...G)=>{try{let K=G.map((Z)=>Y.dump(Z)),W=X(...K);if(W&&typeof W.then==="function"){let Z=Y.newPromise();return W.then((H)=>{try{let F=xB(Y,H);Z.resolve(F),F.dispose(),Y.runtime.executePendingJobs()}catch(F){let V=bB(F),q=Y.newString(`Promise resolution error: ${V}`);Z.reject(q),q.dispose(),Y.runtime.executePendingJobs()}}).catch((H)=>{let F=bB(H),V=Y.newString(`Promise rejection: ${F}`);Z.reject(V),V.dispose(),Y.runtime.executePendingJobs()}),Z.handle}return xB(Y,W)}catch(K){let W=bB(K);return Y.newString(`HostFunctionError: ${W}`)}finally{G.forEach((K)=>K.dispose())}})}case"bigint":return Y.newString(X.toString());case"symbol":return Y.newString(X.toString());default:try{return Y.newString(String(X))}catch{return Y.undefined}}}var BH6=()=>{};function DH6(Y){let X=Y.runtime.executePendingJobs(100);try{if("unwrap"in X&&typeof X.unwrap==="function")X.unwrap()}finally{if("dispose"in X&&typeof X.dispose==="function")X.dispose()}}async function UH6(Y,X,Q){let J=Date.now(),G=Y.resolvePromise(X);while(!0){DH6(Y);let K=await Promise.race([G,td4(0).then(()=>null)]);if(K!==null)return K;if(Date.now()-J>Q)throw Error(`Timed out after ${Q}ms while awaiting a QuickJS promise`)}}async function FY0({tools:Y,code:X,timeoutMs:Q}){let W=[];try{let J=await $H6({memoryLimitBytes:33554432,stackSizeBytes:524288});const G=nB(W,J.newContext({interruptAfterMs:Q}),0);const K=nB(W,uK6(G),0);try{let V=G.evalCode(X,"index.mjs",{strip:!0,strict:!0,type:"module"}),q=G.unwrapResult(V),$=xB(G,Y);G.setProp(G.global,"tools",$);let B=G.runtime.hasPendingJob()?G.unwrapResult(await UH6(G,q,Q)):q;if(B!==q)q.dispose();let U=G.getProp(B,"default"),O=G.typeof(U);if(O!=="function")return{error:`Code must export default a function (tools). Got ${O}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:K.logs};let L=G.callFunction(U,G.undefined,$),M=G.unwrapResult(L),C=await UH6(G,M,Q),R=G.unwrapResult(C);if(G.runtime.hasPendingJob())DH6(G);return{returnValue:G.dump(R),consoleLogs:K.logs}}catch(V){return console.log(V),{error:bB(V),consoleLogs:K.logs}}}catch(Z){var H=Z,F=1}finally{dP(W,H,F)}}var td4=(Y)=>new Promise((X)=>setTimeout(X,Y));var OH6=x(()=>{zH6();BH6()});var NH6=x(()=>{OH6()});async function ed4(Y,X){let Q=Y.connections.map((K)=>K.connection_id),J=[];for(let K of Q){let W=await X.storage.connections.findById(K);if(W&&W.status==="active")J.push(W)}return J.map((K)=>{let W=Y.connections.find((Z)=>Z.connection_id===K.id);return{connection:K,selectedTools:W?.selected_tools??null,selectedResources:W?.selected_resources??null,selectedPrompts:W?.selected_prompts??null}})}async function LH6(Y,X){return(await X.storage.connections.list(Y)).filter((J)=>J.status==="active").map((J)=>({connection:J,selectedTools:null,selectedResources:null,selectedPrompts:null}))}async function Yp4(Y,X){let Q=new Map;for(let $ of Y)Q.set($.connection.id,$);let J=Y.map(($)=>$.connection),G=new Map,K=await Promise.allSettled(J.map(async($)=>{try{let B=await X.createMCPProxy($);return{connection:$,proxy:B}}catch(B){return console.warn(`[code-execution] Failed to create proxy for connection ${$.id}:`,B),null}}));for(let $ of K)if($.status==="fulfilled"&&$.value)G.set($.value.connection.id,$.value);let W=await Promise.allSettled(Array.from(G.entries()).map(async([$,B])=>{try{let O=(await B.proxy.listTools()).tools,L=Q.get($);if(L?.selectedTools&&L.selectedTools.length>0){let M=new Set(L.selectedTools);O=O.filter((C)=>M.has(C.name))}return{connectionId:$,connectionTitle:B.connection.title,tools:O}}catch(U){return console.error(`[code-execution] Failed to list tools for connection ${$}:`,U),null}})),Z=new Set,H=[],F=new Map;for(let $ of W){if($.status!=="fulfilled"||!$.value)continue;let{connectionId:B,connectionTitle:U,tools:O}=$.value;for(let L of O){if(Z.has(L.name))continue;Z.add(L.name),H.push({...L,_meta:{connectionId:B,connectionTitle:U}}),F.set(L.name,B)}}let V=async($,B)=>{let U=F.get($);if(!U)return{content:[{type:"text",text:`Tool not found: ${$}`}],isError:!0};let O=G.get(U);if(!O)return{content:[{type:"text",text:`Connection not found for tool: ${$}`}],isError:!0};return await O.proxy.callTool({name:$,arguments:B})},q=[];for(let[,$]of G)q.push($.proxy.close().catch(()=>{}));return await Promise.all(q),{tools:H,callTool:V}}async function uB(Y){let X=H6(Y),Q;if(Y.connectionId){let J=await Y.storage.virtualMcps.findById(Y.connectionId,Y.organization?.id);if(J)Q=await ed4(J,Y);else Q=await LH6(X.id,Y)}else Q=await LH6(X.id,Y);return Yp4(Q,Y)}function Xp4(Y){return Y.toLowerCase().split(/[\s_\-./]+/).filter((X)=>X.length>=2)}function Qp4(Y,X){let Q=0,J=X.name.toLowerCase(),G=(X.description??"").toLowerCase(),K=(X._meta?.connectionTitle??"").toLowerCase();for(let W of Y){if(J===W)Q+=10;else if(J.includes(W))Q+=3;if(G.includes(W))Q+=2;if(K.includes(W))Q+=1}return Q}function MH6(Y,X,Q){let J=Xp4(Y);if(J.length===0)return X.slice(0,Q);return X.map((G)=>({tool:G,score:Qp4(J,G)})).filter((G)=>G.score>0).sort((G,K)=>K.score-G.score).slice(0,Q).map((G)=>G.tool)}function wH6(Y,X){let Q=new Map(X.map((G)=>[G.name,G]));return{tools:Y.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:Y.filter((G)=>!Q.has(G))}}async function PH6(Y,X,Q){let J=Object.fromEntries(X.tools.map((G)=>[G.name,async(K)=>X.callTool(G.name,K??{})]));return FY0({code:Y,tools:J,timeoutMs:Q})}var Of=x(()=>{NH6()});var VY0;var TH6=x(()=>{f6();LP();Of();VY0=v0({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:_K6,outputSchema:yK6,handler:async(Y,X)=>{t0(X),H6(X),await X.access.check();let Q=await uB(X),J=MH6(Y.query,Q.tools,Y.limit);return{query:Y.query,results:J.map((G)=>({name:G.name,description:G.description,connection:G._meta?.connectionTitle??""})),totalAvailable:Q.tools.length}}})});var qY0;var AH6=x(()=>{f6();LP();Of();qY0=v0({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:fK6,outputSchema:hK6,handler:async(Y,X)=>{t0(X),H6(X),await X.access.check();let Q=await uB(X);return wH6(Y.tools,Q.tools)}})});var $Y0;var EH6=x(()=>{f6();LP();Of();$Y0=v0({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:bK6,outputSchema:xK6,handler:async(Y,X)=>{t0(X),H6(X),await X.access.check();let Q=await uB(X);return await PH6(Y.code,Q,Y.timeoutMs)}})});var CH6=x(()=>{TH6();AH6();EH6();LP()});var Gp4,Wp4,zY0;var IH6=x(()=>{TB();g0();f6();Ff();s3();Gp4=N.object({data:QP.describe("Data for the new connection (id is auto-generated if not provided)")}),Wp4=N.object({item:DX.describe("The created connection entity")}),zY0=v0({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",inputSchema:Gp4,outputSchema:Wp4,handler:async(Y,X)=>{t0(X);let Q=H6(X);await X.access.check();let J=_8(X);if(!J)throw Error("User ID required to create connection");let G={...Y.data,organization_id:Q.id,created_by:J};if(G.connection_type==="VIRTUAL"){let H=tF(G.connection_url);if(!H)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let F=await X.storage.virtualMcps.findById(H);if(!F)throw Error(`Virtual MCP not found: ${H}`);if(F.organization_id!==Q.id)throw Error("Virtual MCP does not belong to the current organization");G.connection_url=eF(H)}let K=await yB({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),W=K?.length?K:null,Z=await X.storage.connections.create({...G,tools:W});return await X.eventBus.publish(Q.id,k5.SELF(Q.id),{type:"connection.created",data:Z}),{item:Z}}})});function wP(Y,X){if(Y===X)return!0;if(Y==null||X==null)return Y===X;if(typeof Y!==typeof X)return!1;if(Array.isArray(Y)&&Array.isArray(X)){if(Y.length!==X.length)return!1;return Y.every((Q,J)=>wP(Q,X[J]))}if(typeof Y==="object"&&typeof X==="object"){let Q=Object.keys(Y),J=Object.keys(X);if(Q.length!==J.length)return!1;return Q.every((G)=>J.includes(G)&&wP(Y[G],X[G]))}return!1}function Rp4(){return(Y)=>{if(!Array.isArray(Y))return!0;let X=[];return Y.every((Q)=>{if(X.some((G)=>wP(Q,G)))return!1;return X.push(Q),!0})}}function Nf(Y,X){return Y.safeParse(X).success}function qY(Y){if(typeof Y==="boolean")return Y?N.any():N.never();let X={};for(let G of lp4)G.apply(X,Y);let Q=[];if(X.string!==!1)Q.push(X.string||N.string());if(X.number!==!1)Q.push(X.number||N.number());if(X.boolean!==!1)Q.push(X.boolean||N.boolean());if(X.null!==!1)Q.push(X.null||N.null());if(X.array!==!1)Q.push(X.array||N.array(N.any()));if(X.tuple!==!1&&X.tuple!==void 0)Q.push(X.tuple);if(X.object!==!1)if(X.object)Q.push(X.object);else{let G=N.custom((K)=>{return typeof K==="object"&&K!==null&&!Array.isArray(K)},"Must be an object, not an array");Q.push(G)}if(X.file!==!1&&X.file!==void 0)Q.push(X.file);let J;if(Q.length===0)J=N.never();else if(Q.length===1)J=Q[0];else if(!Object.keys(Y).some((K)=>K!=="$schema"&&K!=="title"&&K!=="description"))J=N.any();else J=N.union(Q);for(let G of dp4)J=G.apply(J,Y);return J}var Zp4=class{apply(Y,X){if(!X.type)return;let Q=Array.isArray(X.type)?X.type:[X.type],J=new Set(Q);if(!J.has("string"))Y.string=!1;if(!J.has("number")&&!J.has("integer"))Y.number=!1;if(!J.has("boolean"))Y.boolean=!1;if(!J.has("null"))Y.null=!1;if(!J.has("array"))Y.array=!1;if(!J.has("object"))Y.object=!1;if(J.has("integer")&&Y.number!==!1){let G=Y.number||N.number();if(G instanceof N.ZodNumber)Y.number=G.int()}}},Kp4=class{apply(Y,X){if(X.const===void 0)return;let Q=X.const;if(Y.string=!1,Y.number=!1,Y.boolean=!1,Y.null=!1,Y.array=!1,Y.object=!1,typeof Q==="string")Y.string=N.literal(Q);else if(typeof Q==="number")Y.number=N.literal(Q);else if(typeof Q==="boolean")Y.boolean=N.literal(Q);else if(Q===null)Y.null=N.null();else if(Array.isArray(Q))Y.array=void 0;else if(typeof Q==="object")Y.object=void 0}},Hp4=class{apply(Y,X){if(!X.enum)return;if(X.enum.length===0){if(!X.type)Y.string=!1,Y.number=!1,Y.boolean=!1,Y.null=!1,Y.array=!1,Y.object=!1;return}let Q={string:X.enum.filter((J)=>typeof J==="string"),number:X.enum.filter((J)=>typeof J==="number"),boolean:X.enum.filter((J)=>typeof J==="boolean"),null:X.enum.filter((J)=>J===null),array:X.enum.filter((J)=>Array.isArray(J)),object:X.enum.filter((J)=>typeof J==="object"&&J!==null&&!Array.isArray(J))};Y.string=this.createTypeSchema(Q.string,"string"),Y.number=this.createTypeSchema(Q.number,"number"),Y.boolean=this.createTypeSchema(Q.boolean,"boolean"),Y.null=Q.null.length>0?N.null():!1,Y.array=Q.array.length>0?void 0:!1,Y.object=Q.object.length>0?void 0:!1}createTypeSchema(Y,X){if(Y.length===0)return!1;if(Y.length===1)return N.literal(Y[0]);if(X==="string")return N.enum(Y);if(X==="number"){let[Q,J,...G]=Y;return N.union([N.literal(Q),N.literal(J),...G.map((K)=>N.literal(K))])}if(X==="boolean")return N.union([N.literal(!0),N.literal(!1)]);return!1}},Fp4=class{apply(Y,X){let Q=X;if(Q.type==="string"&&Q.format==="binary"&&Q.contentEncoding==="binary"){let J=N.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);Y.file=J,Y.string=!1}}},Vp4=class{apply(Y,X){let Q=X;if(X.type===void 0&&(Q.minLength!==void 0||Q.maxLength!==void 0||Q.pattern!==void 0)){if(Y.string===void 0)Y.string=N.string()}}},qp4=class{apply(Y,X){let Q=X;if(Q.minLength===void 0)return;if(Y.string!==!1){let J=Y.string||N.string();if(J instanceof N.ZodString)Y.string=J.refine((G)=>{return Array.from(G).length>=Q.minLength},{message:`String must be at least ${Q.minLength} characters long`})}}},$p4=class{apply(Y,X){let Q=X;if(Q.maxLength===void 0)return;if(Y.string!==!1){let J=Y.string||N.string();if(J instanceof N.ZodString)Y.string=J.refine((G)=>{return Array.from(G).length<=Q.maxLength},{message:`String must be at most ${Q.maxLength} characters long`})}}},zp4=class{apply(Y,X){let Q=X;if(!Q.pattern)return;if(Y.string!==!1){let J=Y.string||N.string();if(J instanceof N.ZodString){let G=new RegExp(Q.pattern);Y.string=J.regex(G)}}}},Bp4=class{apply(Y,X){let Q=X;if(Q.minimum===void 0)return;if(Y.number!==!1){let J=Y.number||N.number();if(J instanceof N.ZodNumber)Y.number=J.min(Q.minimum)}}},Up4=class{apply(Y,X){let Q=X;if(Q.maximum===void 0)return;if(Y.number!==!1){let J=Y.number||N.number();if(J instanceof N.ZodNumber)Y.number=J.max(Q.maximum)}}},Dp4=class{apply(Y,X){let Q=X;if(Q.exclusiveMinimum===void 0)return;if(Y.number!==!1){let J=Y.number||N.number();if(J instanceof N.ZodNumber)if(typeof Q.exclusiveMinimum==="number")Y.number=J.gt(Q.exclusiveMinimum);else Y.number=!1}}},Op4=class{apply(Y,X){let Q=X;if(Q.exclusiveMaximum===void 0)return;if(Y.number!==!1){let J=Y.number||N.number();if(J instanceof N.ZodNumber)if(typeof Q.exclusiveMaximum==="number")Y.number=J.lt(Q.exclusiveMaximum);else Y.number=!1}}},Np4=class{apply(Y,X){let Q=X;if(Q.multipleOf===void 0)return;if(Y.number!==!1){let J=Y.number||N.number();if(J instanceof N.ZodNumber)Y.number=J.refine((G)=>{if(Q.multipleOf===0)return!1;let K=G/Q.multipleOf,W=Math.round(K),Z=Math.min(Math.abs(G)*Number.EPSILON*10,Math.abs(Q.multipleOf)*Number.EPSILON*10);return Math.abs(K-W)<=Z/Math.abs(Q.multipleOf)},{message:`Must be a multiple of ${Q.multipleOf}`})}}},Lp4=class{apply(Y,X){let Q=X;if(X.type===void 0&&(Q.minItems!==void 0||Q.maxItems!==void 0||Q.items!==void 0||Q.prefixItems!==void 0)){if(Y.array===void 0)Y.array=N.array(N.any())}}},Mp4=class{apply(Y,X){let Q=X;if(Q.minItems===void 0)return;if(Y.array!==!1)Y.array=(Y.array||N.array(N.any())).min(Q.minItems)}},wp4=class{apply(Y,X){let Q=X;if(Q.maxItems===void 0)return;if(Y.array!==!1)Y.array=(Y.array||N.array(N.any())).max(Q.maxItems)}},Pp4=class{apply(Y,X){let Q=X;if(Y.array===!1)return;if(Array.isArray(Q.items))Y.array=Y.array||N.array(N.any());else if(Q.items&&typeof Q.items!=="boolean"&&!Q.prefixItems){let J=qY(Q.items),G=N.array(J);if(Y.array&&Y.array instanceof N.ZodArray){let K=Y.array._def;if(K.checks)K.checks.forEach((W)=>{if(W._zod&&W._zod.def){let Z=W._zod.def;if(Z.check==="min_length"&&Z.minimum!==void 0)G=G.min(Z.minimum);else if(Z.check==="max_length"&&Z.maximum!==void 0)G=G.max(Z.maximum)}})}Y.array=G}else if(typeof Q.items==="boolean"&&Q.items===!1)if(!Q.prefixItems)Y.array=N.array(N.any()).max(0);else Y.array=Y.array||N.array(N.any());else if(typeof Q.items==="boolean"&&Q.items===!0)Y.array=Y.array||N.array(N.any());else if(Q.prefixItems)Y.array=Y.array||N.array(N.any())}},Tp4=class{apply(Y,X){if(X.type!=="array")return;let Q=X;if(!Array.isArray(Q.items))return;if(Y.array===!1)return;let J=Q.items.map((K)=>qY(K)),G;if(J.length===0)G=N.tuple([]);else G=N.tuple(J);if(Q.minItems!==void 0&&Q.minItems>J.length)G=!1;if(Q.maxItems!==void 0&&Q.maxItems<J.length)G=!1;Y.tuple=G,Y.array=!1}},Ap4=class{apply(Y,X){let Q=X;if(Y.object===!1)return;if(Q.properties||Q.required||Q.additionalProperties!==void 0)Y.object=Y.object||N.object({}).passthrough()}},Ep4=class{apply(Y,X){let Q=X;if(X.type===void 0&&(Q.maxProperties!==void 0||Q.minProperties!==void 0)){if(Y.object===void 0)Y.object=N.object({}).passthrough()}}},Cp4=class{apply(Y,X){let Q=X;if(Q.maxProperties===void 0)return;if(Y.object!==!1){let J=Y.object||N.object({}).passthrough();Y.object=J.refine((G)=>Object.keys(G).length<=Q.maxProperties,{message:`Object must have at most ${Q.maxProperties} properties`})}}},Ip4=class{apply(Y,X){let Q=X;if(Q.minProperties===void 0)return;if(Y.object!==!1){let J=Y.object||N.object({}).passthrough();Y.object=J.refine((G)=>Object.keys(G).length>=Q.minProperties,{message:`Object must have at least ${Q.minProperties} properties`})}}},Sp4=class{apply(Y,X){if(!X.not)return Y;let Q=qY(X.not);return Y.refine((J)=>!Nf(Q,J),{message:"Value must not match the 'not' schema"})}},jp4=class{apply(Y,X){if(X.uniqueItems!==!0)return Y;return Y.refine(Rp4(),{message:"Array items must be unique"})}},kp4=class{apply(Y,X){if(!X.allOf||X.allOf.length===0)return Y;return X.allOf.map((J)=>qY(J)).reduce((J,G)=>N.intersection(J,G),Y)}},vp4=class{apply(Y,X){if(!X.anyOf||X.anyOf.length===0)return Y;let Q=X.anyOf.length===1?qY(X.anyOf[0]):N.union([qY(X.anyOf[0]),qY(X.anyOf[1]),...X.anyOf.slice(2).map((J)=>qY(J))]);return N.intersection(Y,Q)}},_p4=class{apply(Y,X){if(!X.oneOf||X.oneOf.length===0)return Y;let Q=X.oneOf.map((J)=>qY(J));return Y.refine((J)=>{let G=0;for(let K of Q)if(K.safeParse(J).success){if(G++,G>1)return!1}return G===1},{message:"Value must match exactly one of the oneOf schemas"})}},yp4=class{apply(Y,X){let Q=X;if(Q.prefixItems&&Array.isArray(Q.prefixItems)){let G=Q.prefixItems.map((K)=>qY(K));return Y.refine((K)=>{if(!Array.isArray(K))return!0;for(let W=0;W<Math.min(K.length,G.length);W++)if(!Nf(G[W],K[W]))return!1;if(K.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 W=qY(Q.items);for(let Z=G.length;Z<K.length;Z++)if(!Nf(W,K[Z]))return!1}}return!0},{message:"Array does not match prefixItems schema"})}return Y}},fp4=class{apply(Y,X){let Q=X;if(!Q.properties&&!Q.required&&Q.additionalProperties!==!1)return Y;if(Y instanceof N.ZodObject||Y instanceof N.ZodRecord){let J={};if(Q.properties){for(let[G,K]of Object.entries(Q.properties))if(K!==void 0)J[G]=qY(K)}if(Q.required&&Array.isArray(Q.required)){let G=new Set(Q.required);for(let K of Object.keys(J))if(!G.has(K))J[K]=J[K].optional()}else for(let G of Object.keys(J))J[G]=J[G].optional();if(Q.additionalProperties===!1)return N.object(J);else return N.object(J).passthrough()}return Y.refine((J)=>{if(typeof J!=="object"||J===null||Array.isArray(J))return!0;if(Q.properties){for(let[G,K]of Object.entries(Q.properties))if(K!==void 0){if(Object.getOwnPropertyDescriptor(J,G)!==void 0){if(!qY(K).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 K in J)if(!G.has(K))return!1}return!0},{message:"Object constraints validation failed"})}},hp4=class{apply(Y,X){if(!X.enum||X.enum.length===0)return Y;let Q=X.enum.filter((J)=>Array.isArray(J)||typeof J==="object"&&J!==null);if(Q.length===0)return Y;return Y.refine((J)=>{if(typeof J!=="object"||J===null)return!0;return Q.some((G)=>wP(J,G))},{message:"Value must match one of the enum values"})}},bp4=class{apply(Y,X){if(X.const===void 0)return Y;let Q=X.const;if(typeof Q!=="object"||Q===null)return Y;return Y.refine((J)=>wP(J,Q),{message:"Value must equal the const value"})}},xp4=class{apply(Y,X){if(X.description)Y=Y.describe(X.description);return Y}},up4=class{apply(Y,X){var Q;let J=X;if(!((Q=J.required)==null?void 0:Q.includes("__proto__"))||X.type!==void 0)return Y;return N.any().refine((G)=>this.validateRequired(G,J.required),{message:"Missing required properties"})}validateRequired(Y,X){if(typeof Y!=="object"||Y===null||Array.isArray(Y))return!0;return X.every((Q)=>Object.prototype.hasOwnProperty.call(Y,Q))}},gp4=class{apply(Y,X){var Q;let J=X;if(J.contains===void 0)return Y;let G=qY(J.contains),K=(Q=J.minContains)!=null?Q:1,W=J.maxContains;return Y.refine((Z)=>{if(!Array.isArray(Z))return!0;let H=0;for(let F of Z)if(Nf(G,F))H++;if(H<K)return!1;if(W!==void 0&&H>W)return!1;return!0},{message:"Array must contain required items matching the schema"})}},mp4=class{apply(Y,X){let{default:Q}=X;if(Q===void 0)return Y;if(!Y.safeParse(Q).success)return Y;return Y.default(Q)}},lp4,dp4;var RH6=x(()=>{I9();I9();I9();I9();I9();I9();I9();I9();I9();I9();I9();I9();I9();I9();lp4=[new Kp4,new Hp4,new Zp4,new Fp4,new Vp4,new Lp4,new Ep4,new qp4,new $p4,new zp4,new Bp4,new Up4,new Dp4,new Op4,new Np4,new Tp4,new Mp4,new wp4,new Pp4,new Cp4,new Ip4,new Ap4],dp4=[new up4,new hp4,new bp4,new kp4,new vp4,new _p4,new yp4,new fp4,new gp4,new Sp4,new jp4,new mp4,new xp4]});class BY0{constructor(Y){this._url=Y}start(){if(this._socket)throw Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((Y,X)=>{this._socket=new WebSocket(this._url,pp4),this._socket.onerror=(Q)=>{let J="error"in Q?Q.error:Error(`WebSocket error: ${JSON.stringify(Q)}`);X(J),this.onerror?.(J)},this._socket.onopen=()=>{Y()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=(Q)=>{let J;try{J=jQ.parse(JSON.parse(Q.data))}catch(G){this.onerror?.(G);return}this.onmessage?.(J)}})}async close(){this._socket?.close()}send(Y){return new Promise((X,Q)=>{if(!this._socket){Q(Error("Not connected"));return}this._socket?.send(JSON.stringify(Y)),X()})}}var pp4="mcp";var SH6=x(()=>{nX()});function cp4(Y){let X=Y;if(!X||typeof X!=="object"||!("method"in X))return null;switch(X.method){case"initialize":{let Q=X?.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:X.jsonrpc??"2.0",id:X.id}}}case"notifications/roots/list_changed":case"notifications/initialized":case"notifications/cancelled":case"notifications/progress":return{type:"suppress"};default:return null}}var UY0;var jH6=x(()=>{ey();UY0=class UY0 extends PB{constructor(Y,X){super(Y,X)}send(Y,X){let Q=cp4(Y);if(Q?.type==="emit")return this.onmessage?.(Q.message),Promise.resolve();if(Q?.type==="suppress")return Promise.resolve();return super.send(Y,X)}}});var kH6,vH6=async(Y,X,Q)=>{let J=np4(Y.connection,X,Q);if(!J)throw Error("Unknown MCP connection type");let G=new kH6({name:Y?.name??"MCP Client",version:"1.0.0"});return await G.connect(J),{client:G,callStreamableTool:(K,W,Z)=>{if(Y.connection.type!=="HTTP")throw Error("HTTP connection required");let H=new Headers(Q);if(!H.has("Authorization"))H.set("Authorization",`Bearer ${Y.connection.token}`);for(let[q,$]of Object.entries(Y.connection.headers??{}))H.set(q,$);let F=new URL(Y.connection.url),V=F.pathname.replace(/\/+$/,"")||"/";return F.pathname=`${V}/call-tool/${encodeURIComponent(K)}`,fetch(F.href,{method:"POST",redirect:"manual",body:JSON.stringify(W),headers:H,signal:Z})}}},np4=(Y,X,Q)=>{if(Y.type==="Websocket")return new BY0(new URL(Y.url));if(Y.type!=="SSE"&&Y.type!=="HTTP")return null;let G={...Y.token?{authorization:`Bearer ${Y.token}`}:{},...Q??{},..."headers"in Y?Y.headers||{}:{}};if(Y.type==="SSE"){let K={requestInit:{headers:G,signal:X}};if(Y.token)K.eventSourceInit={fetch:(W,Z)=>{return fetch(W,{...Z,headers:{...G,Accept:"text/event-stream"},signal:X})}};return new zP(new URL(Y.url),K)}return new UY0(new URL(Y.url),{requestInit:{headers:G,signal:X,credentials:"include"}})};var _H6=x(()=>{by();U90();SH6();nX();jH6();kH6=class kH6 extends i3{constructor(Y,X){super(Y,X)}async listTools(Y,X){return await this.request({method:"tools/list",params:Y},Cw,X)}}});function fH6(Y){let X=(Q)=>{if("connection"in Y)return vH6({connection:Y.connection},void 0,Q);return Y.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 Z;async function G(H,F=J){let V=Y?.debugId?.(),q=V?{"x-trace-debug-id":V}:void 0,{client:$,callStreamableTool:B}=await X(q);if(Y?.streamable?.[String(F)])return B(String(F),H);let{structuredContent:U,isError:O,content:L}=await $.callTool({name:String(F),arguments:H});if(O){let M=L?.[0]?.text,C=typeof M==="string"?ip4(M):null,R=C?.code&&typeof Y?.getErrorByStatusCode==="function"?Y.getErrorByStatusCode(C.code,C.message,C.traceId):null;if(R)throw R;throw Error(`Tool ${String(F)} returned an error: ${JSON.stringify(U??L)}`)}return U}async function K(){let{client:H}=await X(),{tools:F}=await H.listTools();return F}async function W(){if(!("connection"in Y))return K();let H=Y.connection,F=JSON.stringify(H);try{if(!Lf.has(F))Lf.set(F,K());return await Lf.get(F)}catch(V){console.error("Failed to list tools",V),Lf.delete(F);return}}async function Z(){return(await W()??[]).map((F)=>yH6(F,G))}return G.asTool=async()=>{let F=(await W()??[]).find((V)=>V.name===J);if(!F)throw Error(`Tool ${J} not found`);return yH6(F,G)},G}})}var ip4=(Y)=>{try{return JSON.parse(Y)}catch{return Y}},Lf,yH6=(Y,X)=>{return{...Y,id:Y.name,inputSchema:Y.inputSchema?qY(Y.inputSchema):void 0,outputSchema:Y.outputSchema?qY(Y.outputSchema):void 0,execute:(Q)=>{return X(Q.context,Y.name)}}};var hH6=x(()=>{RH6();_H6();Lf=new Map});function Mf(Y){return fH6(Y)}var Ms1;var bH6=x(()=>{hH6();Ms1=new Proxy({},{get(Y,X){if(X==="toJSON")return null;if(X==="forConnection")return(Q)=>Mf({connection:Q});return global[X]}})});function wf(Y){return{isImplementedBy:(X)=>{for(let Q of Y){let J=typeof Q.name==="string"?new RegExp(`^${Q.name}$`):Q.name,G=X.find((K)=>J.test(K.name));if(!G&&Q.opt)continue;if(!G)return!1}return!0}}}var ZV=(Y)=>{return{...wf(Y),forClient:(X)=>{return Mf({client:X,streamable:Y.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})},forConnection:(X)=>{return Mf({connection:X,streamable:Y.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})}}};var PP=x(()=>{bH6()});function bW(Y){return N.object({items:N.array(Y).describe("Array of collection items"),totalCount:N.number().int().min(0).optional().describe("Total number of matching items (if available)"),hasMore:N.boolean().optional().describe("Whether there are more items available")})}function AP(Y){return N.object({item:Y.nullable().describe("The retrieved item, or null if not found")})}function op4(Y){return N.object({data:Y.partial().describe("Data for the new entity (id may be auto-generated)")})}function sp4(Y){return N.object({item:Y.describe("The created entity with generated id")})}function tp4(Y){return N.object({id:N.string().describe("ID of the entity to update"),data:Y.partial().describe("Partial entity data to update")})}function ep4(Y){return N.object({item:Y.describe("The updated entity")})}function CP(Y){return N.object({item:Y.describe("The deleted entity")})}function mB(Y,X,Q){let J=Y.toUpperCase(),G=Q?.readOnly??!1,K=[{name:`COLLECTION_${J}_LIST`,inputSchema:hW,outputSchema:bW(X)},{name:`COLLECTION_${J}_GET`,inputSchema:TP,outputSchema:AP(X)}];if(!G)K.push({name:`COLLECTION_${J}_CREATE`,inputSchema:op4(X),outputSchema:sp4(X),opt:!0},{name:`COLLECTION_${J}_UPDATE`,inputSchema:tp4(X),outputSchema:ep4(X),opt:!0},{name:`COLLECTION_${J}_DELETE`,inputSchema:EP,outputSchema:CP(X),opt:!0});return K}var gB,ap4,xH6,rp4,hW,TP,EP;var bJ=x(()=>{g0();gB=N.object({id:N.string().describe("Unique identifier for the entity"),title:N.string().describe("Human-readable title for the entity"),description:N.string().nullish().describe("Description of the entity"),created_at:N.string().datetime(),updated_at:N.string().datetime(),created_by:N.string().optional(),updated_by:N.string().optional()}),ap4=N.object({field:N.array(N.string()),operator:N.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:N.unknown()}),xH6=N.lazy(()=>N.union([ap4,N.object({operator:N.enum(["and","or","not"]),conditions:N.array(xH6)})])),rp4=N.object({field:N.array(N.string()),direction:N.enum(["asc","desc"]),nulls:N.enum(["first","last"]).optional()}),hW=N.object({where:xH6.optional().describe("Filter expression"),orderBy:N.array(rp4).optional().describe("Sort expressions"),limit:N.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:N.number().int().min(0).optional().describe("Number of items to skip")});TP=N.object({id:N.string().describe("ID of the entity to retrieve")});EP=N.object({id:N.string().describe("ID of the entity to delete")})});var Yc4,uH6,Ss1;var gH6=x(()=>{g0();bJ();Yc4=N.object({id:N.string(),name:N.string(),description:N.string().optional(),inputSchema:N.record(N.string(),N.unknown()),outputSchema:N.record(N.string(),N.unknown()).optional()}),uH6=gB.extend({_meta:N.object({"io.decocms":N.object({id:N.string(),verified:N.boolean(),scopeName:N.string(),appName:N.string(),friendlyName:N.string().nullable().optional(),metadata:N.record(N.string(),N.unknown()).nullable().optional(),publishedAt:N.string().datetime().optional(),updatedAt:N.string().datetime().optional(),tools:N.array(Yc4).nullable().optional().describe("Available tools exposed by this app")}).optional()}).optional(),server:N.object({$schema:N.string().optional(),_meta:N.record(N.string(),N.unknown()).optional(),name:N.string().describe("The server name (scope/app)"),title:N.string().optional().describe("User-friendly title"),description:N.string().optional().describe("Server description"),icons:N.array(N.object({src:N.string(),mimeType:N.string().optional(),sizes:N.array(N.string()).optional(),theme:N.enum(["light","dark"]).optional()})).optional(),remotes:N.array(N.object({type:N.enum(["http","stdio","sse"]),url:N.string().optional(),headers:N.array(N.unknown()).optional()})).optional(),packages:N.array(N.unknown()).optional(),repository:N.object({url:N.string(),source:N.string().optional(),subfolder:N.string().optional()}).optional(),version:N.string().optional(),websiteUrl:N.string().optional()})}),Ss1=mB("registry_app",uH6,{readOnly:!0})});var mH6,lH6,dH6,pH6,cH6,Xc4;var nH6=x(()=>{g0();PP();mH6=N.object({specversion:N.literal("1.0").describe("CloudEvents specification version"),id:N.string().describe("Unique identifier for this event (UUID recommended)"),source:N.string().describe("Connection ID of the event publisher"),type:N.string().describe("Event type (e.g., 'order.created', 'user.signup')"),time:N.string().datetime().optional().describe("Timestamp of when the event occurred (ISO 8601)"),subject:N.string().optional().describe("Subject/resource identifier (e.g., order ID, user ID)"),datacontenttype:N.string().optional().default("application/json").describe("Content type of the data attribute"),dataschema:N.string().url().optional().describe("URI to the schema for the data attribute"),data:N.unknown().optional().describe("Event payload (any JSON value)")}),lH6=N.object({events:N.array(mH6).min(1).describe("Batch of CloudEvents to process")}),dH6=N.object({success:N.boolean().optional().describe("Whether this event was processed successfully"),error:N.string().optional().describe("Error message for this event"),retryAfter:N.number().int().positive().optional().describe("Re-deliver this event after this many ms")}),pH6=N.object({success:N.boolean().optional().describe("Batch success - applies to events not in results"),error:N.string().optional().describe("Batch error message - applies to events not in results"),processedCount:N.number().int().min(0).optional().describe("Number of events successfully processed"),retryAfter:N.number().int().positive().optional().describe("Batch retryAfter - applies to events not in results"),results:N.record(N.string(),dH6).optional().describe("Per-event results keyed by event ID")}),cH6=[{name:"ON_EVENTS",inputSchema:lH6,outputSchema:pH6}],Xc4=ZV(cH6)});var IP,RP,SP,jP,iH6,aH6,kP,vP,_P,yP,fP,hP,bP,xP,rH6,Qc4;var oH6=x(()=>{g0();PP();IP=N.object({type:N.string().min(1).max(255).describe("Event type identifier"),subject:N.string().max(255).optional().describe("Subject/resource identifier (e.g., order ID)"),data:N.unknown().optional().describe("Event payload"),deliverAt:N.string().datetime().optional().describe("Scheduled delivery time (ISO 8601). Omit for immediate delivery."),cron:N.string().max(100).optional().describe("Cron expression for recurring delivery. Use EVENT_CANCEL to stop.")}),RP=N.object({id:N.string().describe("Unique event ID"),type:N.string().describe("Event type"),source:N.string().describe("Source connection ID"),time:N.string().describe("Event timestamp")}),SP=N.object({eventType:N.string().min(1).max(255).describe("Event type to subscribe to"),publisher:N.string().optional().describe("Filter events by publisher connection ID"),filter:N.string().max(1000).optional().describe("JSONPath filter expression on event data")}),jP=N.object({subscription:N.object({id:N.string().describe("Subscription ID"),connectionId:N.string().describe("Subscriber connection ID"),eventType:N.string().describe("Event type pattern"),publisher:N.string().nullable().describe("Publisher connection filter"),filter:N.string().nullable().describe("JSONPath filter expression"),enabled:N.boolean().describe("Whether subscription is enabled"),createdAt:N.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:N.string().datetime().describe("Updated timestamp (ISO 8601)")})}),iH6=N.object({eventType:N.string().min(1).max(255).describe("Event type to subscribe to"),publisher:N.string().optional().describe("Filter events by publisher connection ID"),filter:N.string().max(1000).optional().describe("JSONPath filter expression on event data")}),aH6=N.object({id:N.string().describe("Subscription ID"),connectionId:N.string().describe("Subscriber connection ID"),eventType:N.string().describe("Event type pattern"),publisher:N.string().nullable().describe("Publisher connection filter"),filter:N.string().nullable().describe("JSONPath filter expression"),enabled:N.boolean().describe("Whether subscription is enabled"),createdAt:N.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:N.string().datetime().describe("Updated timestamp (ISO 8601)")}),kP=N.object({subscriptions:N.array(iH6).describe("Desired subscriptions - system will create/update/delete to match")}),vP=N.object({created:N.number().int().min(0).describe("Number of subscriptions created"),updated:N.number().int().min(0).describe("Number of subscriptions with filter updated"),deleted:N.number().int().min(0).describe("Number of subscriptions removed"),unchanged:N.number().int().min(0).describe("Number of subscriptions unchanged"),subscriptions:N.array(aH6).describe("Current subscriptions after sync")}),_P=N.object({subscriptionId:N.string().describe("Subscription ID to remove")}),yP=N.object({success:N.boolean().describe("Whether unsubscribe was successful"),subscriptionId:N.string().describe("Subscription ID that was removed")}),fP=N.object({eventId:N.string().describe("Event ID to cancel")}),hP=N.object({success:N.boolean().describe("Whether cancellation was successful"),eventId:N.string().describe("Event ID that was cancelled")}),bP=N.object({eventId:N.string().describe("Event ID to acknowledge")}),xP=N.object({success:N.boolean().describe("Whether ACK was successful"),eventId:N.string().describe("Event ID that was acknowledged")}),rH6=[{name:"EVENT_PUBLISH",inputSchema:IP,outputSchema:RP},{name:"EVENT_SUBSCRIBE",inputSchema:SP,outputSchema:jP},{name:"EVENT_UNSUBSCRIBE",inputSchema:_P,outputSchema:yP},{name:"EVENT_CANCEL",inputSchema:fP,outputSchema:hP},{name:"EVENT_ACK",inputSchema:bP,outputSchema:xP},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:kP,outputSchema:vP}],Qc4=ZV(rH6)});var Jc4,Gc4,Wc4,Zc4,Kc4,Hc4,Fc4,Vc4,qc4,$c4,zc4,Bc4,uP;var Pf=x(()=>{g0();Jc4=N.object({prefix:N.string().optional().describe("Filter objects by prefix (e.g., 'folder/' for folder contents)"),maxKeys:N.number().optional().default(1000).describe("Maximum number of keys to return (default: 1000)"),continuationToken:N.string().optional().describe("Token for pagination from previous response"),delimiter:N.string().optional().describe("Delimiter for grouping keys (typically '/'). When set, commonPrefixes returns folder paths.")}),Gc4=N.object({objects:N.array(N.object({key:N.string().describe("Object key/path"),size:N.number().describe("Object size in bytes"),lastModified:N.string().describe("Last modified timestamp"),etag:N.string().describe("Entity tag for the object")})),nextContinuationToken:N.string().optional().describe("Token for fetching next page of results"),isTruncated:N.boolean().describe("Whether there are more results available"),commonPrefixes:N.array(N.string()).optional().describe("Folder paths when delimiter is used (e.g., ['photos/2024/', 'photos/2025/'])")}),Wc4=N.object({key:N.string().describe("Object key/path to get metadata for")}),Zc4=N.object({contentType:N.string().optional().describe("MIME type of the object"),contentLength:N.number().describe("Size of the object in bytes"),lastModified:N.string().describe("Last modified timestamp"),etag:N.string().describe("Entity tag for the object"),metadata:N.record(N.string(),N.string()).optional().describe("Custom metadata key-value pairs")}),Kc4=N.object({key:N.string().describe("Object key/path to generate URL for"),expiresIn:N.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)")}),Hc4=N.object({url:N.string().describe("Presigned URL for downloading the object"),expiresIn:N.number().describe("Expiration time in seconds that was used")}),Fc4=N.object({key:N.string().describe("Object key/path for the upload"),expiresIn:N.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)"),contentType:N.string().optional().describe("MIME type for the object being uploaded")}),Vc4=N.object({url:N.string().describe("Presigned URL for uploading the object"),expiresIn:N.number().describe("Expiration time in seconds that was used")}),qc4=N.object({key:N.string().describe("Object key/path to delete")}),$c4=N.object({success:N.boolean().describe("Whether the deletion was successful"),key:N.string().describe("The key that was deleted")}),zc4=N.object({keys:N.array(N.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),Bc4=N.object({deleted:N.array(N.string()).describe("Array of successfully deleted keys"),errors:N.array(N.object({key:N.string(),message:N.string()})).describe("Array of errors for failed deletions")}),uP=[{name:"LIST_OBJECTS",inputSchema:Jc4,outputSchema:Gc4},{name:"GET_OBJECT_METADATA",inputSchema:Wc4,outputSchema:Zc4},{name:"GET_PRESIGNED_URL",inputSchema:Kc4,outputSchema:Hc4},{name:"PUT_PRESIGNED_URL",inputSchema:Fc4,outputSchema:Vc4},{name:"DELETE_OBJECT",inputSchema:qc4,outputSchema:$c4},{name:"DELETE_OBJECTS",inputSchema:zc4,outputSchema:Bc4}]});var DY0=x(()=>{PP();gH6();nH6();oH6();Pf()});var Uc4,Dc4,sH6;var tH6=x(()=>{g0();bJ();Uc4=gB.extend({avatar:N.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:N.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:N.string().describe("Virtual MCP ID to use for this assistant"),model:N.object({id:N.string().describe("Model ID"),connectionId:N.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),Dc4=mB("assistant",Uc4),sH6=[...Dc4]});var gP,xW,YF6,Oc4,Nc4,XF6,Lc4,Mc4,wc4,Pc4,Tc4,Ac4,QF6,Ec4,Cc4,Ic4,Rc4,Sc4,jc4,kc4,vc4,_c4,yc4,es1,fc4,Yt1,eH6,hc4,bc4,OY0,Xt1;var JF6=x(()=>{g0();PP();bJ();gP=N.lazy(()=>N.union([N.null(),N.string(),N.number(),N.boolean(),N.record(N.string(),gP),N.array(gP)])),xW=N.record(N.string(),N.record(N.string(),gP)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),YF6=N.object({type:N.literal("text"),text:N.string().describe("The text content"),providerOptions:xW}),Oc4=N.object({type:N.literal("text"),text:N.string().describe("The text content"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),Nc4=N.string().describe("File data as URL string"),XF6=N.object({type:N.literal("file"),filename:N.string().optional().describe("Optional filename of the file"),data:Nc4,mediaType:N.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:xW}),Lc4=N.object({type:N.literal("file"),mediaType:N.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:N.string().describe("Generated file data as base64 encoded string")}),Mc4=N.object({type:N.literal("reasoning"),text:N.string().describe("The reasoning text"),providerOptions:xW}),wc4=N.object({type:N.literal("reasoning"),text:N.string().describe("The reasoning text"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),Pc4=N.object({type:N.literal("tool-call"),toolCallId:N.string().describe("ID of the tool call, used to match with tool result"),toolName:N.string().describe("Name of the tool being called"),input:N.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:N.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:xW}),Tc4=N.object({type:N.literal("tool-call"),toolCallId:N.string().describe("ID of the tool call"),toolName:N.string().describe("Name of the tool being called"),input:N.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:N.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),Ac4=N.union([N.object({type:N.literal("text"),value:N.string()}),N.object({type:N.literal("json"),value:gP}),N.object({type:N.literal("error-text"),value:N.string()}),N.object({type:N.literal("error-json"),value:gP}),N.object({type:N.literal("content"),value:N.array(N.union([N.object({type:N.literal("text"),text:N.string().describe("Text content")}),N.object({type:N.literal("media"),data:N.string().describe("Base-64 encoded media data"),mediaType:N.string().describe("IANA media type")})]))})]),QF6=N.object({type:N.literal("tool-result"),toolCallId:N.string().describe("ID of the tool call that this result is associated with"),toolName:N.string().describe("Name of the tool that generated this result"),output:Ac4.describe("Result of the tool call"),result:N.unknown().describe("Unknown result of the tool call"),providerOptions:xW}),Ec4=N.object({type:N.literal("tool-result"),toolCallId:N.string().describe("ID of the tool call that this result is associated with"),toolName:N.string().describe("Name of the tool that generated this result"),result:N.any().describe("Result of the tool call (JSON-serializable)"),isError:N.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:N.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),Cc4=N.union([N.object({type:N.literal("source"),sourceType:N.literal("url"),id:N.string().describe("The ID of the source"),url:N.string().describe("The URL of the source"),title:N.string().optional().describe("The title of the source"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),N.object({type:N.literal("source"),sourceType:N.literal("document"),id:N.string().describe("The ID of the source"),mediaType:N.string().describe("IANA media type of the document (e.g., application/pdf)"),title:N.string().describe("The title of the document"),filename:N.string().optional().describe("Optional filename of the document"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")})]),Ic4=N.object({role:N.literal("system"),content:N.string().describe("System message content"),providerOptions:xW}),Rc4=N.object({role:N.literal("user"),content:N.array(N.union([YF6,XF6])).describe("User message content parts (text or file)"),providerOptions:xW}),Sc4=N.object({role:N.literal("assistant"),content:N.array(N.union([YF6,XF6,Mc4,Pc4,QF6])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:xW}),jc4=N.object({role:N.literal("tool"),content:N.array(QF6).describe("Tool message content (tool results)"),providerOptions:xW}),kc4=N.union([Ic4,Rc4,Sc4,jc4]),vc4=N.array(kc4).describe("A list of messages forming the prompt"),_c4=N.object({prompt:vc4.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:N.number().optional().describe("Maximum number of tokens to generate"),temperature:N.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:N.number().optional().describe("Nucleus sampling parameter"),topK:N.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:N.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:N.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:N.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:N.array(N.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:N.union([N.object({type:N.literal("text")}),N.object({type:N.literal("json"),schema:N.any().optional().describe("JSON schema that the generated output should conform to"),name:N.string().optional().describe("Name of output that should be generated"),description:N.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:N.array(N.any()).optional().describe("The tools that are available for the model"),toolChoice:N.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:N.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:N.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:N.any().optional().describe("Additional provider-specific options")}),yc4=N.object({content:N.array(N.union([Oc4,Lc4,wc4,Tc4,Ec4,Cc4])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:N.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:N.looseObject({inputTokens:N.number().optional(),outputTokens:N.number().optional(),totalTokens:N.number().optional(),reasoningTokens:N.number().optional()}).describe("Usage information for the language model call"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata"),request:N.object({body:N.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:N.object({id:N.string().optional().describe("ID for the generated response"),timestamp:N.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:N.string().optional().describe("The ID of the response model that was used"),headers:N.record(N.string(),N.string()).optional().describe("Response headers"),body:N.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:N.array(N.any()).describe("Warnings for the call, e.g. unsupported settings")}),es1=N.object({stream:N.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:N.object({body:N.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:N.object({headers:N.record(N.string(),N.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),fc4=N.object({supportedUrls:N.record(N.string(),N.array(N.string())).describe("Supported URL patterns by media type for the provider")}),Yt1=N.object({modelId:N.string().describe("The ID of the model"),logo:N.string().nullable(),description:N.string().nullable(),capabilities:N.array(N.string()),limits:N.object({contextWindow:N.number(),maxOutputTokens:N.number()}).nullable(),costs:N.object({input:N.number(),output:N.number()}).nullable(),provider:N.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),eH6=N.object({modelId:N.string().describe("The ID of the model"),callOptions:_c4}),hc4=gB.extend({logo:N.string().nullable(),description:N.string().nullable(),capabilities:N.array(N.string()),limits:N.object({contextWindow:N.number(),maxOutputTokens:N.number()}).nullable(),costs:N.object({input:N.number(),output:N.number()}).nullable(),provider:N.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),bc4=mB("llm",hc4,{readOnly:!0}),OY0=[{name:"LLM_METADATA",inputSchema:N.object({modelId:N.string().describe("The ID of the model")}),outputSchema:fc4},{name:"LLM_DO_STREAM",inputSchema:eH6,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:eH6,outputSchema:yc4},...bc4],Xt1=ZV(OY0)});function Tf(){return!1}function GF6(Y,X){return Y===k5.DEV_ASSETS(X)}function Af(Y,X){let Q=d80(X,Y),J=new Date().toISOString();return{id:Q.id??k5.DEV_ASSETS(Y),title:Q.title,description:Q.description??null,icon:Q.icon??null,app_name:Q.app_name??null,app_id:Q.app_id??null,organization_id:Y,created_by:"system",created_at:J,updated_at:J,connection_type:Q.connection_type,connection_url:Q.connection_url??null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:Q.metadata??null,tools:xc4,bindings:["OBJECT_STORAGE"],status:"active"}}var xc4;var NY0=x(()=>{Pf();TB();g0();xc4=uP.map((Y)=>({name:Y.name,description:`${Y.name} operation for local file storage`,inputSchema:N.toJSONSchema(Y.inputSchema),outputSchema:N.toJSONSchema(Y.outputSchema)}))});function gc4(Y){let X=[],Q=0;while(Q<Y.length){let J=Y[Q];if(J==="%")X.push(".*");else if(J==="_")X.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))X.push("\\"+J);else X.push(J);Q++}return X.join("")}function QK(Y){return typeof Y==="string"||typeof Y==="number"}function Ef(Y,X){if("conditions"in X){let{operator:Z,conditions:H}=X;switch(Z){case"and":return H.every((F)=>Ef(Y,F));case"or":return H.some((F)=>Ef(Y,F));case"not":return!H.every((F)=>Ef(Y,F));default:return!0}}let{field:Q,operator:J,value:G}=X,K=Q.join("."),W=LY0(Y,K);switch(J){case"eq":return W===G;case"gt":return QK(W)&&QK(G)&&W>G;case"gte":return QK(W)&&QK(G)&&W>=G;case"lt":return QK(W)&&QK(G)&&W<G;case"lte":return QK(W)&&QK(G)&&W<=G;case"in":return Array.isArray(G)&&G.includes(W);case"like":if(typeof W!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let Z=gc4(G);return new RegExp(`^${Z}$`,"i").test(W);case"contains":if(typeof W!=="string"||typeof G!=="string")return!1;return W.toLowerCase().includes(G.toLowerCase());default:return!0}}function LY0(Y,X){let Q=X.split("."),J=Y;for(let G of Q){if(J==null||typeof J!=="object")return;J=J[G]}return J}function mc4(Y,X){return[...Y].sort((Q,J)=>{for(let G of X){let K=G.field.join("."),W=LY0(Q,K),Z=LY0(J,K),H=0;if(W==null&&Z==null)continue;if(W==null)H=G.nulls==="first"?-1:1;else if(Z==null)H=G.nulls==="first"?1:-1;else if(typeof W==="string"&&typeof Z==="string")H=W.localeCompare(Z);else if(typeof W==="number"&&typeof Z==="number")H=W-Z;else H=String(W).localeCompare(String(Z));if(H!==0)return G.direction==="desc"?-H:H}return 0})}var uc4,lc4,dc4,MY0;var WF6=x(()=>{DY0();tH6();bJ();JF6();Pf();TB();g0();f6();NY0();s3();uc4={LLM:OY0,ASSISTANTS:sH6,OBJECT_STORAGE:uP};lc4=hW.extend({binding:N.union([N.object({}).passthrough(),N.string()]).optional(),include_virtual:N.boolean().optional().describe("Whether to include VIRTUAL connections in the results. Defaults to false.")}),dc4=bW(DX),MY0=v0({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",inputSchema:lc4,outputSchema:dc4,handler:async(Y,X)=>{await X.access.check();let Q=H6(X),J=Y.binding?typeof Y.binding==="string"?(()=>{let $=uc4[Y.binding.toUpperCase()];if(!$)throw Error(`Unknown binding: ${Y.binding}`);return $})():Y.binding:void 0,G=J?wf(J):void 0,K=await X.storage.connections.list(Q.id,{includeVirtual:Y.include_virtual??!1});if(Tf()){let $=o7(),B=k5.DEV_ASSETS(Q.id);if(!K.some((U)=>U.id===B)){let U=Af(Q.id,$);K.unshift(U)}}let W=G?await Promise.all(K.map(async($)=>{if(!$.tools||$.tools.length===0)return null;return G.isImplementedBy($.tools.map((U)=>({name:U.name,inputSchema:U.inputSchema,outputSchema:U.outputSchema})))?$:null})).then(($)=>$.filter((B)=>B!==null)):K;if(Y.where)W=W.filter(($)=>Ef($,Y.where));if(Y.orderBy&&Y.orderBy.length>0)W=mc4(W,Y.orderBy);let Z=W.length,H=Y.offset??0,F=Y.limit??100,V=W.slice(H,H+F),q=H+F<Z;return{items:V,totalCount:Z,hasMore:q}}})});var pc4,wY0;var ZF6=x(()=>{bJ();f6();NY0();s3();pc4=AP(DX),wY0=v0({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",inputSchema:TP,outputSchema:pc4,handler:async(Y,X)=>{let Q=H6(X);if(await X.access.check(),Tf()&&GF6(Y.id,Q.id))return{item:Af(Q.id,o7())};let J=await X.storage.connections.findById(Y.id);if(!J||J.organization_id!==Q.id)return{item:null};return{item:J}}})});var Cf=(Y,X)=>{if(X===null||X===void 0)return;let Q=Y.replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),J=X;for(let G of Q){if(J===null||J===void 0||typeof J!=="object")return;J=J[G]}return J};function KF6(Y){let X=Y.split("::");if(X.length!==2||!X[0]||!X[1])throw Error(`Invalid scope format: ${Y}. Expected format: "KEY::SCOPE"`);return X}function cc4(Y){let X=Y.split("::");if(X.length!==2||!X[0]||!X[1])return null;return X}function nc4(Y){if(typeof Y==="object"&&Y!==null&&"value"in Y){let X=Y.value;if(typeof X==="string")return X}return null}function ic4(Y,X){let Q={};if(!Y||!X)return Q;for(let J of X){if(J==="*"){Q["*"]=["*"];continue}let G=cc4(J);if(!G)continue;let[K,W]=G,Z=Cf(K,Y),H=nc4(Z);if(H){if(!Q[H])Q[H]=[];Q[H].push(W)}}return Q}function HF6(Y,X){let Q=ic4(Y,X);return new Set(Object.keys(Q).filter((J)=>J!=="*"))}var FF6=()=>{};class PY0{db;vault;constructor(Y,X){this.db=Y;this.vault=X}async get(Y){let X=await this.db.selectFrom("downstream_tokens").selectAll().where("connectionId","=",Y).executeTakeFirst();if(!X)return null;return this.decryptToken(X)}async upsert(Y){let X=new Date().toISOString(),Q=await this.vault.encrypt(Y.accessToken),J=Y.refreshToken?await this.vault.encrypt(Y.refreshToken):null,G=Y.clientSecret?await this.vault.encrypt(Y.clientSecret):null;return await this.db.transaction().execute(async(K)=>{let W=await K.selectFrom("downstream_tokens").select(["id","createdAt"]).where("connectionId","=",Y.connectionId).executeTakeFirst();if(W)return await K.updateTable("downstream_tokens").set({accessToken:Q,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,updatedAt:X}).where("id","=",W.id).execute(),{id:W.id,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:W.createdAt,updatedAt:X,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint};let Z=EB("dtok");return await K.insertInto("downstream_tokens").values({id:Z,connectionId:Y.connectionId,accessToken:Q,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,createdAt:X,updatedAt:X}).execute(),{id:Z,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:X,updatedAt:X,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint}})}async delete(Y){await this.db.deleteFrom("downstream_tokens").where("connectionId","=",Y).execute()}isExpired(Y,X=0){if(!Y.expiresAt)return!1;let J=(Y.expiresAt instanceof Date?Y.expiresAt:new Date(Y.expiresAt)).getTime();if(Number.isNaN(J))return!0;return J-X<Date.now()}async decryptToken(Y){let X=await this.vault.decrypt(Y.accessToken),Q=Y.refreshToken?await this.vault.decrypt(Y.refreshToken):null,J=Y.clientSecret?await this.vault.decrypt(Y.clientSecret):null;return{id:Y.id,connectionId:Y.connectionId,accessToken:X,refreshToken:Q,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Y.createdAt,updatedAt:Y.updatedAt,clientId:Y.clientId,clientSecret:J,tokenEndpoint:Y.tokenEndpoint}}}var VF6=x(()=>{Gf()});async function oc4(Y,X,Q,J){for(let K of X){if(K==="*")continue;let[W]=KF6(K),Z=Cf(W,Y);if(Z===void 0||Z===null)throw Error(`Scope references key "${W}" but it's not present in state`)}let G=HF6(Y,X);for(let K of G){if(K.endsWith("_self"))continue;let W=await J.storage.connections.findById(K);if(!W||W.organization_id!==Q)throw Error(`Referenced connection not found: ${K}`);try{await J.access.check(K)}catch(Z){throw Error(`Access denied to referenced connection: ${K}. ${Z.message}`)}}}var ac4,rc4,TY0;var qF6=x(()=>{FF6();VF6();g0();f6();Ff();s3();ac4=N.object({id:N.string().describe("ID of the connection to update"),data:JP.describe("Partial connection data to update")}),rc4=N.object({item:DX.describe("The updated connection entity")});TY0=v0({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update an existing MCP connection in the organization",inputSchema:ac4,outputSchema:rc4,handler:async(Y,X)=>{t0(X);let Q=H6(X);await X.access.check();let J=_8(X);if(!J)throw Error("User ID required to update connection");let{id:G,data:K}=Y,W=await X.storage.connections.findById(G);if(!W||W.organization_id!==Q.id)throw Error("Connection not found in organization");let Z=K.connection_type??W.connection_type,H=K.connection_url??W.connection_url;if(Z==="VIRTUAL"){let T=tF(H);if(!T)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let I=await X.storage.virtualMcps.findById(T);if(!I)throw Error(`Virtual MCP not found: ${T}`);if(I.organization_id!==Q.id)throw Error("Virtual MCP does not belong to the current organization");H=eF(T)}let F=K.configuration_state??W.configuration_state??{},V=K.configuration_scopes??W.configuration_scopes??[];if(K.configuration_state!==void 0||K.configuration_scopes!==void 0){if(K.configuration_state!==void 0)F=K.configuration_state??{};else if(F===null||F===void 0)F={};if(K.configuration_scopes!==void 0)V=K.configuration_scopes??[];if(V.length>0)await oc4(F,V,Q.id,X)}let q=K.connection_token??W.connection_token;if(!q)try{let I=await new PY0(X.db,X.vault).get(G);if(I?.accessToken)q=I.accessToken}catch{}let $=await yB({id:W.id,title:K.title??W.title,connection_type:Z,connection_url:H,connection_token:q,connection_headers:K.connection_headers??W.connection_headers}).catch(()=>null),B=$?.length?$:null,U={...K,connection_url:H,tools:B,configuration_state:F,configuration_scopes:V,updated_by:J},O=await X.storage.connections.update(G,U);if((K.configuration_state!==void 0||K.configuration_scopes!==void 0)&&F&&V)try{let L=[];try{const T=nB(L,await X.createMCPProxy(G),1);await T.callTool({name:"ON_MCP_CONFIGURATION",arguments:{state:F,scopes:V}});await T.close().catch(console.error)}catch(M){var C=M,R=1}finally{var E=dP(L,C,R);E&&await E}}catch(T){console.error("Failed to invoke ON_MCP_CONFIGURATION callback",T)}return{item:O}}})});var AY0;var $F6=x(()=>{bJ();f6();s3();AY0=v0({name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete a connection",inputSchema:EP,outputSchema:CP(DX),handler:async(Y,X)=>{t0(X);let Q=H6(X);await X.access.check();let J=await X.storage.connections.findById(Y.id);if(!J)throw Error(`Connection not found: ${Y.id}`);if(J.organization_id!==Q.id)throw Error("Connection not found in organization");if(J.metadata?.isFixed===!0)throw Error("This connection is a fixed system connection and cannot be deleted");return await X.storage.connections.delete(Y.id),{item:J}}})});var EY0;var zF6=x(()=>{g0();f6();EY0=v0({name:"CONNECTION_TEST",description:"Test connection health and latency",inputSchema:N.object({id:N.string()}),outputSchema:N.object({id:N.string(),healthy:N.boolean(),latencyMs:N.number()}),handler:async(Y,X)=>{let Q=H6(X);await X.access.check();let J=await X.storage.connections.findById(Y.id);if(!J||J.organization_id!==Q.id)throw Error("Connection not found");let G=await X.storage.connections.testConnection(Y.id);return{id:Y.id,...G}}})});var BF6=x(()=>{IH6();WF6();ZF6();qF6();$F6();zF6()});import{sql as s4}from"kysely";function UF6(Y){if(Y===null||Y===void 0)return"NULL";if(typeof Y==="number")return String(Y);if(typeof Y==="boolean")return Y?"TRUE":"FALSE";if(typeof Y==="string")return`'${Y.replace(/'/g,"''")}'`;if(Y instanceof Date)return`'${Y.toISOString()}'`;return`'${JSON.stringify(Y).replace(/'/g,"''")}'`}function ec4(Y,X){let Q=Y;for(let G=X.length;G>=1;G--){let K=`$${G}`;if(Q.includes(K))Q=Q.replaceAll(K,UF6(X[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,X.length)-1;G>=0;G--){let K=J[G],W=UF6(X[G]);Q=Q.slice(0,K)+W+Q.slice(K+1)}return Q}function DF6(Y){return Y.replace(/-/g,"_")}function Xn4(Y){return`app_${DF6(Y)}`}function Qn4(Y){return`app_role_${DF6(Y)}`}function Jn4(Y){if(Y instanceof Error){let X=Y.message.toLowerCase(),Q=Y.code;return Q==="3F000"||Q==="42704"||X.includes("schema")&&X.includes("does not exist")||X.includes("role")&&X.includes("does not exist")}return!1}async function Gn4(Y,X,Q){if(await s4`CREATE SCHEMA IF NOT EXISTS ${s4.id(X)}`.execute(Y),!(await s4`
420
420
  SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${Q}) as exists
421
421
  `.execute(Y)).rows[0]?.exists)await s4`CREATE ROLE ${s4.id(Q)} NOLOGIN`.execute(Y);await s4`GRANT ${s4.id(Q)} TO CURRENT_USER`.execute(Y),await s4`GRANT USAGE, CREATE ON SCHEMA ${s4.id(X)} TO ${s4.id(Q)}`.execute(Y),await s4`GRANT ALL ON ALL TABLES IN SCHEMA ${s4.id(X)} TO ${s4.id(Q)}`.execute(Y),await s4`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${s4.id(X)} TO ${s4.id(Q)}`.execute(Y),await s4`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s4.id(X)} GRANT ALL ON TABLES TO ${s4.id(Q)}`.execute(Y),await s4`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s4.id(X)} GRANT ALL ON SEQUENCES TO ${s4.id(Q)}`.execute(Y),await s4`REVOKE ALL ON SCHEMA public FROM ${s4.id(Q)}`.execute(Y)}async function Wn4(Y,X,Q,J){try{return await Y.transaction().execute(async(G)=>{return await s4`SET LOCAL ROLE ${s4.id(Q)}`.execute(G),await s4`SET LOCAL search_path TO ${s4.id(X)}`.execute(G),await s4.raw(J).execute(G)})}catch(G){if(Jn4(G))return await Gn4(Y,X,Q),await Y.transaction().execute(async(K)=>{return await s4`SET LOCAL ROLE ${s4.id(Q)}`.execute(K),await s4`SET LOCAL search_path TO ${s4.id(X)}`.execute(K),await s4.raw(J).execute(K)});throw G}}var tc4,Yn4,OF6;var NF6=x(()=>{g0();f6();tc4=N.object({results:N.array(N.unknown()).optional(),success:N.boolean().optional()});Yn4=N.object({sql:N.string().describe("The SQL query to run"),params:N.array(N.any()).describe("The parameters to pass to the SQL query").optional()});OF6=v0({name:"DATABASES_RUN_SQL",description:"Run a SQL query against the database",inputSchema:Yn4,outputSchema:N.object({result:N.array(tc4)}),handler:async(Y,X)=>{t0(X),await X.access.check();let Q=ec4(Y.sql,Y.params||[]);if(!X.connectionId)throw Error("Connection context required for database access");let J=Xn4(X.connectionId),G=Qn4(X.connectionId);return{result:[{results:(await Wn4(X.db,J,G,Q)).rows,success:!0}]}}})});var LF6,Kn4,MF6;var uW=x(()=>{g0();DY0();LF6=N.object({connectionId:N.string().optional().describe("Filter subscriptions by connection ID (optional)")}),Kn4=N.object({id:N.string().describe("Subscription ID"),connectionId:N.string().describe("Subscriber connection ID"),eventType:N.string().describe("Event type pattern"),publisher:N.string().nullable().describe("Publisher connection filter (null = all publishers)"),filter:N.string().nullable().describe("JSONPath filter expression"),enabled:N.boolean().describe("Whether subscription is enabled"),createdAt:N.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:N.string().datetime().describe("Updated timestamp (ISO 8601)")}),MF6=N.object({subscriptions:N.array(Kn4).describe("List of subscriptions")})});var CY0;var wF6=x(()=>{f6();uW();CY0=v0({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:IP,outputSchema:RP,handler:async(Y,X)=>{t0(X);let Q=H6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to publish events. Use a connection-scoped token.");let G=await X.eventBus.publish(Q.id,J,{type:Y.type,subject:Y.subject,data:Y.data,deliverAt:Y.deliverAt,cron:Y.cron});return{id:G.id,type:G.type,source:G.source,time:G.time}}})});var IY0;var PF6=x(()=>{f6();uW();IY0=v0({name:"EVENT_SUBSCRIBE",description:"Subscribe to events of a specific type. The subscriber is automatically set to the caller's connection.",inputSchema:SP,outputSchema:jP,handler:async(Y,X)=>{t0(X);let Q=H6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to subscribe. Use a connection-scoped token.");let G=await X.eventBus.subscribe(Q.id,{connectionId:J,eventType:Y.eventType,publisher:Y.publisher,filter:Y.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 RY0;var TF6=x(()=>{f6();uW();RY0=v0({name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events by removing a subscription.",inputSchema:_P,outputSchema:yP,handler:async(Y,X)=>{t0(X);let Q=H6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to unsubscribe. Use a connection-scoped token.");let G=await X.eventBus.getSubscription(Q.id,Y.subscriptionId);if(!G)throw Error(`Subscription not found: ${Y.subscriptionId}`);if(G.connectionId!==J)throw Error("Cannot unsubscribe from a subscription owned by another connection");return{success:(await X.eventBus.unsubscribe(Q.id,Y.subscriptionId)).success,subscriptionId:Y.subscriptionId}}})});var SY0;var AF6=x(()=>{f6();uW();SY0=v0({name:"EVENT_CANCEL",description:"Cancel a recurring event to stop future deliveries. Only the publisher can cancel their own events.",inputSchema:fP,outputSchema:hP,handler:async(Y,X)=>{t0(X);let Q=H6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to cancel events. Use a connection-scoped token.");if(!await X.eventBus.getEvent(Q.id,Y.eventId))throw Error(`Event not found: ${Y.eventId}`);if(!(await X.eventBus.cancelEvent(Q.id,Y.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:Y.eventId}}})});var jY0;var EF6=x(()=>{f6();uW();jY0=v0({name:"EVENT_ACK",description:"Acknowledge delivery of an event. Call after successfully processing an event received via ON_EVENTS with retryAfter.",inputSchema:bP,outputSchema:xP,handler:async(Y,X)=>{t0(X);let Q=H6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to acknowledge events. Use a connection-scoped token.");if(!(await X.eventBus.ackEvent(Q.id,Y.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:Y.eventId}}})});var kY0;var CF6=x(()=>{f6();uW();kY0=v0({name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions, optionally filtered by connection ID.",inputSchema:LF6,outputSchema:MF6,handler:async(Y,X)=>{t0(X);let Q=H6(X);return await X.access.check(),{subscriptions:(await X.eventBus.listSubscriptions(Q.id,Y.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 vY0;var IF6=x(()=>{f6();uW();vY0=v0({name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state. Creates new, deletes removed, updates changed filters. Subscriptions are identified by (eventType, publisher).",inputSchema:kP,outputSchema:vP,handler:async(Y,X)=>{t0(X);let Q=H6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to sync subscriptions. Use a connection-scoped token.");let G=await X.eventBus.syncSubscriptions(Q.id,{connectionId:J,subscriptions:Y.subscriptions});return{created:G.created,updated:G.updated,deleted:G.deleted,unchanged:G.unchanged,subscriptions:G.subscriptions.map((K)=>({id:K.id,connectionId:K.connectionId,eventType:K.eventType,publisher:K.publisher,filter:K.filter,enabled:K.enabled,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt,updatedAt:K.updatedAt instanceof Date?K.updatedAt.toISOString():K.updatedAt}))}}})});var RF6=x(()=>{wF6();PF6();TF6();AF6();EF6();CF6();IF6();uW()});var lB=x(()=>{Qf()});var Fn4,Vn4,_Y0;var SF6=x(()=>{g0();f6();lB();Fn4=N.object({data:WP.describe("Data for the new virtual MCP")}),Vn4=N.object({item:kQ.describe("The created virtual MCP entity")}),_Y0=v0({name:"COLLECTION_VIRTUAL_MCP_CREATE",description:"Create a new MCP virtual MCP in the organization",inputSchema:Fn4,outputSchema:Vn4,handler:async(Y,X)=>{t0(X);let Q=H6(X);await X.access.check();let J=_8(X);if(!J)throw Error("User ID required to create virtual MCP");return{item:await X.storage.virtualMcps.create(Q.id,J,Y.data)}}})});function qn4(Y){let X=[],Q=0;while(Q<Y.length){let J=Y[Q];if(J==="%")X.push(".*");else if(J==="_")X.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))X.push("\\"+J);else X.push(J);Q++}return X.join("")}function JK(Y){return typeof Y==="string"||typeof Y==="number"}function yY0(Y,X){let Q=X.split("."),J=Y;for(let G of Q){if(J==null||typeof J!=="object")return;J=J[G]}return J}function $n4(Y,X){return Y.connections.some((Q)=>Q.connection_id===X)}function If(Y,X){if("conditions"in X){let{operator:Z,conditions:H}=X;switch(Z){case"and":return H.every((F)=>If(Y,F));case"or":return H.some((F)=>If(Y,F));case"not":return!H.every((F)=>If(Y,F));default:return!0}}let{field:Q,operator:J,value:G}=X,K=Q.join(".");if(K==="connection_id"){if(J!=="eq"||typeof G!=="string")return!1;return $n4(Y,G)}let W=yY0(Y,K);switch(J){case"eq":return W===G;case"gt":return JK(W)&&JK(G)&&W>G;case"gte":return JK(W)&&JK(G)&&W>=G;case"lt":return JK(W)&&JK(G)&&W<G;case"lte":return JK(W)&&JK(G)&&W<=G;case"in":return Array.isArray(G)&&G.includes(W);case"like":if(typeof W!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let Z=qn4(G);return new RegExp(`^${Z}$`,"i").test(W);case"contains":if(typeof W!=="string"||typeof G!=="string")return!1;return W.toLowerCase().includes(G.toLowerCase());default:return!0}}function zn4(Y,X){return[...Y].sort((Q,J)=>{for(let G of X){let K=G.field.join("."),W=yY0(Q,K),Z=yY0(J,K),H=0;if(W==null&&Z==null)continue;if(W==null)H=G.nulls==="first"?-1:1;else if(Z==null)H=G.nulls==="first"?1:-1;else if(typeof W==="string"&&typeof Z==="string")H=W.localeCompare(Z);else if(typeof W==="number"&&typeof Z==="number")H=W-Z;else H=String(W).localeCompare(String(Z));if(H!==0)return G.direction==="desc"?-H:H}return 0})}var Bn4,Un4,fY0;var jF6=x(()=>{bJ();f6();lB();Bn4=hW,Un4=bW(kQ),fY0=v0({name:"COLLECTION_VIRTUAL_MCP_LIST",description:"List all MCP virtual MCPs in the organization",inputSchema:Bn4,outputSchema:Un4,handler:async(Y,X)=>{await X.access.check();let Q=H6(X),J=Y.where&&!("conditions"in Y.where)&&Y.where.field.join(".")==="connection_id"&&Y.where.operator==="eq"&&typeof Y.where.value==="string"?Y.where.value:void 0,K=J?await X.storage.virtualMcps.listByConnectionId(Q.id,J):await X.storage.virtualMcps.list(Q.id);if(Y.where)K=K.filter((q)=>If(q,Y.where));if(Y.orderBy&&Y.orderBy.length>0)K=zn4(K,Y.orderBy);let W=K.length,Z=Y.offset??0,H=Y.limit??100,F=K.slice(Z,Z+H),V=Z+H<W;return{items:F,totalCount:W,hasMore:V}}})});var Dn4,On4,hY0;var kF6=x(()=>{g0();f6();lB();Dn4=N.object({id:N.string().describe("ID of the virtual MCP to retrieve")}),On4=N.object({item:kQ.nullable().describe("The retrieved virtual MCP, or null if not found")}),hY0=v0({name:"COLLECTION_VIRTUAL_MCP_GET",description:"Get an MCP virtual MCP by ID",inputSchema:Dn4,outputSchema:On4,handler:async(Y,X)=>{t0(X);let Q=H6(X);await X.access.check();let J=await X.storage.virtualMcps.findById(Y.id);if(J&&J.organization_id!==Q.id)return{item:null};if(!J)return{item:null};return{item:J}}})});var Nn4,Ln4,bY0;var vF6=x(()=>{g0();f6();lB();Nn4=N.object({id:N.string().describe("ID of the virtual MCP to update"),data:ZP.describe("Partial virtual MCP data to update")}),Ln4=N.object({item:kQ.describe("The updated virtual MCP entity")}),bY0=v0({name:"COLLECTION_VIRTUAL_MCP_UPDATE",description:"Update an MCP virtual MCP",inputSchema:Nn4,outputSchema:Ln4,handler:async(Y,X)=>{t0(X);let Q=H6(X);await X.access.check();let J=_8(X);if(!J)throw Error("User ID required to update virtual MCP");let G=await X.storage.virtualMcps.findById(Y.id);if(!G)throw Error(`Virtual MCP not found: ${Y.id}`);if(G.organization_id!==Q.id)throw Error(`Virtual MCP not found: ${Y.id}`);return{item:await X.storage.virtualMcps.update(Y.id,J,Y.data)}}})});var Mn4,wn4,xY0;var _F6=x(()=>{g0();f6();lB();Mn4=N.object({id:N.string().describe("ID of the virtual MCP to delete")}),wn4=N.object({item:kQ.describe("The deleted virtual MCP entity")}),xY0=v0({name:"COLLECTION_VIRTUAL_MCP_DELETE",description:"Delete an MCP virtual MCP",inputSchema:Mn4,outputSchema:wn4,handler:async(Y,X)=>{t0(X);let Q=H6(X);await X.access.check();let J=await X.storage.virtualMcps.findById(Y.id);if(!J)throw Error(`Virtual MCP not found: ${Y.id}`);if(J.organization_id!==Q.id)throw Error(`Virtual MCP not found: ${Y.id}`);return await X.storage.virtualMcps.delete(Y.id),{item:J}}})});var yF6=x(()=>{SF6();jF6();kF6();vF6();_F6()});var uY0,E08,K7,fF6,hF6;var dB=x(()=>{g0();uY0=N.object({title:N.string().optional(),readOnlyHint:N.boolean().optional(),destructiveHint:N.boolean().optional(),idempotentHint:N.boolean().optional(),openWorldHint:N.boolean().optional()}),E08=N.object({"tool.fn":N.string().describe("JavaScript ES module code that exports a default async function")}),K7=N.object({id:N.string().describe("Unique identifier for the virtual tool (auto-generated)"),name:N.string().min(1).max(255).describe("Tool name (must be unique within the Virtual MCP)"),description:N.string().optional().describe("Human-readable description of what the tool does"),inputSchema:N.record(N.string(),N.unknown()).describe("JSON Schema defining the tool's input parameters"),outputSchema:N.record(N.string(),N.unknown()).optional().describe("JSON Schema defining the tool's output (optional)"),annotations:uY0.optional().describe("MCP tool annotations"),code:N.string().describe("JavaScript ES module code. Must export default an async function: export default async (tools, args) => { ... }"),connection_dependencies:N.array(N.string()).describe("Connection IDs that this tool depends on (specified by the creator)"),created_at:N.string().describe("When the virtual tool was created"),updated_at:N.string().describe("When the virtual tool was last updated")}),fF6=N.object({name:N.string().min(1).max(255).describe("Tool name (must be unique within the Virtual MCP)"),description:N.string().optional().describe("Human-readable description"),inputSchema:N.record(N.string(),N.unknown()).describe("JSON Schema defining the tool's input parameters"),outputSchema:N.record(N.string(),N.unknown()).optional().describe("JSON Schema for output"),annotations:uY0.optional().describe("MCP tool annotations"),code:N.string().describe("JavaScript ES module code. Must export default an async function: export default async (tools, args) => { ... }"),connection_dependencies:N.array(N.string()).optional().describe("Connection IDs that this tool depends on. Creates indirect aggregations to prevent deletion of referenced connections.")}),hF6=N.object({name:N.string().min(1).max(255).optional().describe("New tool name"),description:N.string().nullable().optional().describe("New description (null to clear)"),inputSchema:N.record(N.string(),N.unknown()).optional().describe("New input schema"),outputSchema:N.record(N.string(),N.unknown()).nullable().optional().describe("New output schema (null to clear)"),annotations:uY0.nullable().optional().describe("New annotations (null to clear)"),code:N.string().optional().describe("New JavaScript code"),connection_dependencies:N.array(N.string()).optional().describe("Connection IDs that this tool depends on. Replaces existing dependencies if provided.")})});var Tn4,An4,gY0;var bF6=x(()=>{g0();f6();dB();Tn4=N.object({virtual_mcp_id:N.string().describe("ID of the Virtual MCP to add the tool to"),data:fF6.describe("Virtual tool data")}),An4=N.object({item:K7.describe("The created virtual tool")}),gY0=v0({name:"COLLECTION_VIRTUAL_TOOLS_CREATE",description:"Create a new virtual tool on a Virtual MCP. The tool code should be a JavaScript ES module that exports a default async function: export default async (tools, args) => { ... }. Specify connection_dependencies to indicate which connections this tool uses.",inputSchema:Tn4,outputSchema:An4,handler:async(Y,X)=>{t0(X);let Q=H6(X);await X.access.check();let J=await X.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==Q.id)throw Error(`Virtual MCP not found: ${Y.virtual_mcp_id}`);let G=Y.data.connection_dependencies??[];return{item:await X.storage.virtualMcps.createVirtualTool(Y.virtual_mcp_id,Y.data,G)}}})});var En4,Cn4,mY0;var xF6=x(()=>{g0();f6();dB();En4=N.object({virtual_mcp_id:N.string().describe("ID of the Virtual MCP to list tools for"),limit:N.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:N.number().int().min(0).optional().describe("Number of items to skip")}),Cn4=N.object({items:N.array(K7).describe("Array of virtual tools"),totalCount:N.number().int().min(0).optional().describe("Total number of virtual tools"),hasMore:N.boolean().optional().describe("Whether there are more items available")}),mY0=v0({name:"COLLECTION_VIRTUAL_TOOLS_LIST",description:"List all virtual tools for a Virtual MCP",inputSchema:En4,outputSchema:Cn4,handler:async(Y,X)=>{t0(X);let Q=H6(X);await X.access.check();let J=await X.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==Q.id)return{items:[],totalCount:0,hasMore:!1};let G=await X.storage.virtualMcps.listVirtualTools(Y.virtual_mcp_id),K=G.length,W=Y.offset??0,Z=Y.limit??100,H=G.slice(W,W+Z),F=W+Z<K;return{items:H,totalCount:K,hasMore:F}}})});var In4,Rn4,lY0;var uF6=x(()=>{g0();f6();dB();In4=N.object({virtual_mcp_id:N.string().describe("ID of the Virtual MCP"),name:N.string().describe("Name of the virtual tool to retrieve")}),Rn4=N.object({item:K7.nullable().describe("The retrieved virtual tool, or null if not found")}),lY0=v0({name:"COLLECTION_VIRTUAL_TOOLS_GET",description:"Get a virtual tool by name from a Virtual MCP",inputSchema:In4,outputSchema:Rn4,handler:async(Y,X)=>{t0(X);let Q=H6(X);await X.access.check();let J=await X.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==Q.id)return{item:null};return{item:await X.storage.virtualMcps.getVirtualTool(Y.virtual_mcp_id,Y.name)}}})});var Sn4,jn4,dY0;var gF6=x(()=>{g0();f6();dB();Sn4=N.object({virtual_mcp_id:N.string().describe("ID of the Virtual MCP"),name:N.string().describe("Current name of the virtual tool to update"),data:hF6.describe("Partial virtual tool data to update")}),jn4=N.object({item:K7.describe("The updated virtual tool")}),dY0=v0({name:"COLLECTION_VIRTUAL_TOOLS_UPDATE",description:"Update an existing virtual tool on a Virtual MCP. Specify connection_dependencies to update which connections this tool uses.",inputSchema:Sn4,outputSchema:jn4,handler:async(Y,X)=>{t0(X);let Q=H6(X);await X.access.check();let J=await X.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==Q.id)throw Error(`Virtual MCP not found: ${Y.virtual_mcp_id}`);if(!await X.storage.virtualMcps.getVirtualTool(Y.virtual_mcp_id,Y.name))throw Error(`Virtual tool not found: ${Y.name}`);let K=Y.data.connection_dependencies;return{item:await X.storage.virtualMcps.updateVirtualTool(Y.virtual_mcp_id,Y.name,Y.data,K)}}})});var kn4,vn4,pY0;var mF6=x(()=>{g0();f6();dB();kn4=N.object({virtual_mcp_id:N.string().describe("ID of the Virtual MCP"),name:N.string().describe("Name of the virtual tool to delete")}),vn4=N.object({item:K7.describe("The deleted virtual tool")}),pY0=v0({name:"COLLECTION_VIRTUAL_TOOLS_DELETE",description:"Delete a virtual tool from a Virtual MCP",inputSchema:kn4,outputSchema:vn4,handler:async(Y,X)=>{t0(X);let Q=H6(X);await X.access.check();let J=await X.storage.virtualMcps.findById(Y.virtual_mcp_id);if(!J||J.organization_id!==Q.id)throw Error(`Virtual MCP not found: ${Y.virtual_mcp_id}`);let G=await X.storage.virtualMcps.getVirtualTool(Y.virtual_mcp_id,Y.name);if(!G)throw Error(`Virtual tool not found: ${Y.name}`);return await X.storage.virtualMcps.deleteVirtualTool(Y.virtual_mcp_id,Y.name),{item:G}}})});var lF6=x(()=>{bF6();xF6();uF6();gF6();mF6()});var yn4,cY0;var dF6=x(()=>{f6();g0();yn4=N.object({id:N.string().optional().describe("Unique log identifier"),organizationId:N.string().describe("Organization ID"),connectionId:N.string().describe("Connection ID"),connectionTitle:N.string().describe("Connection display name"),toolName:N.string().describe("Name of the tool that was called"),input:N.record(N.string(),N.unknown()).describe("Redacted tool input"),output:N.record(N.string(),N.unknown()).describe("Redacted tool output"),isError:N.boolean().describe("Whether the call resulted in an error"),errorMessage:N.string().nullish().describe("Error message if applicable"),durationMs:N.number().describe("Call duration in milliseconds"),timestamp:N.string().describe("ISO 8601 timestamp of the call"),userId:N.string().nullish().describe("User who triggered the call"),requestId:N.string().describe("Unique request identifier"),userAgent:N.string().nullish().describe("Client identifier (x-mesh-client header)"),virtualMcpId:N.string().nullish().describe("Virtual MCP (Agent) ID if routed through an agent"),properties:N.record(N.string(),N.string()).nullish().describe("Custom key-value metadata attached to the log")}),cY0=v0({name:"MONITORING_LOGS_LIST",description:"List monitoring logs for tool calls in the organization",inputSchema:N.object({connectionId:N.string().optional().describe("Filter by connection ID"),virtualMcpId:N.string().optional().describe("Filter by Virtual MCP (Agent) ID"),toolName:N.string().optional().describe("Filter by tool name"),isError:N.boolean().optional().describe("Filter by error status"),startDate:N.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:N.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)"),limit:N.number().default(20).describe("Maximum number of results"),offset:N.number().default(0).describe("Offset for pagination"),properties:N.record(N.string(),N.string()).optional().describe("Filter by exact property key=value matches"),propertyKeys:N.array(N.string()).optional().describe("Filter by logs that have these property keys"),propertyPatterns:N.record(N.string(),N.string()).optional().describe("Filter by property value patterns (SQL LIKE, use % as wildcard)"),propertyInValues:N.record(N.string(),N.string()).optional().describe("Filter by exact match within comma-separated values (e.g., user_tags in 'Engineering')")}),outputSchema:N.object({logs:N.array(yn4).describe("Array of monitoring logs"),total:N.number().describe("Total number of logs matching filters"),offset:N.number().describe("Current offset for pagination"),limit:N.number().describe("Current limit for pagination")}),handler:async(Y,X)=>{let Q=H6(X),G=Y.properties||Y.propertyKeys||Y.propertyPatterns||Y.propertyInValues?{properties:Y.properties,propertyKeys:Y.propertyKeys,propertyPatterns:Y.propertyPatterns,propertyInValues:Y.propertyInValues}:void 0,K={organizationId:Q.id,connectionId:Y.connectionId,virtualMcpId:Y.virtualMcpId,toolName:Y.toolName,isError:Y.isError,startDate:Y.startDate?new Date(Y.startDate):void 0,endDate:Y.endDate?new Date(Y.endDate):void 0,limit:Y.limit,offset:Y.offset,propertyFilters:G},W=await X.storage.monitoring.query(K);return{logs:W.logs.map((Z)=>({...Z,timestamp:Z.timestamp instanceof Date?Z.timestamp.toISOString():Z.timestamp})),total:W.total,offset:Y.offset,limit:Y.limit}}})});var nY0;var pF6=x(()=>{f6();g0();nY0=v0({name:"MONITORING_STATS",description:"Get aggregated statistics for tool call monitoring",inputSchema:N.object({startDate:N.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:N.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)")}),outputSchema:N.object({totalCalls:N.number().describe("Total number of tool calls"),errorRate:N.number().describe("Error rate as a decimal (0 to 1)"),avgDurationMs:N.number().describe("Average call duration in milliseconds"),errorRatePercent:N.string().describe("Error rate as a percentage string")}),handler:async(Y,X)=>{let J={organizationId:H6(X).id,startDate:Y.startDate?new Date(Y.startDate):void 0,endDate:Y.endDate?new Date(Y.endDate):void 0},G=await X.storage.monitoring.getStats(J);return{...G,errorRatePercent:(G.errorRate*100).toFixed(2)}}})});var cF6=x(()=>{dF6();pF6()});var iY0;var nF6=x(()=>{g0();f6();iY0=v0({name:"ORGANIZATION_CREATE",description:"Create a new organization",inputSchema:N.object({slug:N.string().min(1).max(50).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens"),name:N.string().min(1).max(255),description:N.string().optional()}),outputSchema:N.object({id:N.string(),name:N.string(),slug:N.string(),logo:N.string().nullable().optional(),metadata:N.any().optional(),createdAt:N.string().datetime().describe("ISO 8601 timestamp"),members:N.array(N.any()).optional()}),handler:async(Y,X)=>{t0(X),await X.access.check();let Q=_8(X);if(!Q)throw Error("User ID required to create organization");let J=await X.boundAuth.organization.create({name:Y.name,slug:Y.slug,metadata:Y.description?{description:Y.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 aY0;var iF6=x(()=>{g0();f6();aY0=v0({name:"ORGANIZATION_LIST",description:"List all organizations user has access to",inputSchema:N.object({userId:N.string().optional()}),outputSchema:N.object({organizations:N.array(N.object({id:N.string(),name:N.string(),slug:N.string(),logo:N.string().nullable().optional(),metadata:N.any().optional(),createdAt:N.string().datetime().describe("ISO 8601 timestamp")}))}),handler:async(Y,X)=>{t0(X),await X.access.check();let Q=_8(X),J=Y.userId||Q;if(!J)throw Error("User ID required to list organizations");return{organizations:(await X.boundAuth.organization.list(J)).map((K)=>({...K,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt}))}}})});var rY0;var aF6=x(()=>{g0();f6();rY0=v0({name:"ORGANIZATION_GET",description:"Get organization details by slug or ID",inputSchema:N.object({}),outputSchema:N.object({id:N.string(),name:N.string(),slug:N.string(),logo:N.string().nullable().optional(),metadata:N.any().optional(),createdAt:N.string().datetime().describe("ISO 8601 timestamp"),members:N.array(N.any()).optional(),invitations:N.array(N.any()).optional()}),handler:async(Y,X)=>{t0(X),await X.access.check();let Q=await X.boundAuth.organization.get();if(!Q)throw Error("No active organization found");let J=new Date,G=Q.invitations?.filter((K)=>new Date(K.expiresAt)>J);return{...Q,invitations:G,createdAt:Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt}}})});var oY0;var rF6=x(()=>{g0();f6();oY0=v0({name:"ORGANIZATION_UPDATE",description:"Update an existing organization",inputSchema:N.object({id:N.string(),slug:N.string().min(1).max(50).regex(/^[a-z0-9-]+$/).optional(),name:N.string().min(1).max(255).optional(),description:N.string().optional()}),outputSchema:N.object({id:N.string(),name:N.string(),slug:N.string(),logo:N.string().nullable().optional(),metadata:N.any().optional(),createdAt:N.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Y,X)=>{t0(X),await X.access.check();let Q={};if(Y.name)Q.name=Y.name;if(Y.slug)Q.slug=Y.slug;if(Y.description)Q.metadata={description:Y.description};let J=await X.boundAuth.organization.update({organizationId:Y.id,data:Q});if(!J)throw Error("Failed to update organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var sY0;var oF6=x(()=>{g0();f6();sY0=v0({name:"ORGANIZATION_DELETE",description:"Delete an organization",inputSchema:N.object({id:N.string()}),outputSchema:N.object({success:N.boolean(),id:N.string()}),handler:async(Y,X)=>{return t0(X),await X.access.check(),await X.boundAuth.organization.delete(Y.id),{success:!0,id:Y.id}}})});var mP;var tY0=x(()=>{g0();mP=N.object({title:N.string(),url:N.string(),icon:N.string()})});var eY0;var sF6=x(()=>{g0();f6();tY0();eY0=v0({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings",inputSchema:N.object({}),outputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(mP).nullable().optional(),enabled_plugins:N.array(N.string()).nullable().optional(),createdAt:N.string().datetime().optional().describe("ISO 8601 timestamp"),updatedAt:N.string().datetime().optional().describe("ISO 8601 timestamp")}),handler:async(Y,X)=>{t0(X),await X.access.check();let Q=X.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await X.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 YX0;var tF6=x(()=>{g0();f6();tY0();YX0=v0({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings",inputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(mP).optional(),enabled_plugins:N.array(N.string()).optional()}),outputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(mP).nullable().optional(),enabled_plugins:N.array(N.string()).nullable().optional(),createdAt:N.string().datetime().describe("ISO 8601 timestamp"),updatedAt:N.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Y,X)=>{if(t0(X),await X.access.check(),X.organization&&X.organization.id!==Y.organizationId)throw Error("Cannot update settings for a different organization");let Q=await X.storage.organizationSettings.upsert(Y.organizationId,{sidebar_items:Y.sidebar_items,enabled_plugins:Y.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 XX0;var eF6=x(()=>{g0();f6();XX0=v0({name:"ORGANIZATION_MEMBER_ADD",description:"Add a member to an organization",inputSchema:N.object({organizationId:N.string().optional(),userId:N.string(),role:N.array(N.string())}),outputSchema:N.object({id:N.string(),organizationId:N.string(),userId:N.string(),role:N.union([N.string(),N.array(N.string())]),createdAt:N.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Y,X)=>{t0(X),await X.access.check();let Q=Y.organizationId||X.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await X.boundAuth.organization.addMember({organizationId:Q,userId:Y.userId,role:Y.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 QX0;var YV6=x(()=>{g0();f6();QX0=v0({name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove a member from an organization",inputSchema:N.object({organizationId:N.string().optional(),memberIdOrEmail:N.string()}),outputSchema:N.object({success:N.boolean(),memberIdOrEmail:N.string()}),handler:async(Y,X)=>{t0(X),await X.access.check();let Q=Y.organizationId||X.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");return await X.boundAuth.organization.removeMember({organizationId:Q,memberIdOrEmail:Y.memberIdOrEmail}),{success:!0,memberIdOrEmail:Y.memberIdOrEmail}}})});var JX0;var XV6=x(()=>{g0();f6();JX0=v0({name:"ORGANIZATION_MEMBER_LIST",description:"List all members in an organization",inputSchema:N.object({limit:N.number().optional(),offset:N.number().optional()}),outputSchema:N.object({members:N.array(N.object({id:N.string(),organizationId:N.string(),userId:N.string(),role:N.string(),createdAt:N.string().datetime().describe("ISO 8601 timestamp"),user:N.object({id:N.string(),name:N.string(),email:N.string(),image:N.string().optional()}).optional()}))}),handler:async(Y,X)=>{t0(X),await X.access.check();let Q=X.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await X.boundAuth.organization.listMembers({organizationId:Q,limit:Y.limit,offset:Y.offset});return{members:(Array.isArray(J)?J:[]).map((K)=>({...K,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt}))}}})});var GX0;var QV6=x(()=>{g0();f6();GX0=v0({name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update a member's role in an organization",inputSchema:N.object({organizationId:N.string().optional(),memberId:N.string(),role:N.array(N.string())}),outputSchema:N.object({id:N.string(),organizationId:N.string(),userId:N.string(),role:N.union([N.literal("admin"),N.literal("member"),N.literal("owner")]),createdAt:N.string().datetime().describe("ISO 8601 timestamp"),user:N.object({email:N.string(),name:N.string(),image:N.string().optional()})}),handler:async(Y,X)=>{t0(X),await X.access.check();let Q=Y.organizationId||X.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await X.boundAuth.organization.updateMemberRole({organizationId:Q,memberId:Y.memberId,role:Y.role});if(!J)throw Error("Failed to update member role");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var JV6=x(()=>{nF6();iF6();aF6();rF6();oF6();sF6();tF6();eF6();YV6();XV6();QV6()});var WX0;var GV6=x(()=>{g0();f6();WX0=v0({name:"TAGS_LIST",description:"List all tags in an organization",inputSchema:N.object({}),outputSchema:N.object({tags:N.array(N.object({id:N.string(),organizationId:N.string(),name:N.string(),createdAt:N.string().describe("ISO 8601 timestamp")}))}),handler:async(Y,X)=>{t0(X),await X.access.check();let Q=H6(X);return{tags:(await X.storage.tags.listOrgTags(Q.id)).map((G)=>({...G,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():String(G.createdAt)}))}}})});var ZX0;var WV6=x(()=>{g0();f6();ZX0=v0({name:"TAGS_CREATE",description:"Create a new tag in an organization",inputSchema:N.object({name:N.string().min(1).max(50).describe("Tag name")}),outputSchema:N.object({tag:N.object({id:N.string(),organizationId:N.string(),name:N.string(),createdAt:N.string().describe("ISO 8601 timestamp")})}),handler:async(Y,X)=>{t0(X),await X.access.check();let Q=H6(X),J=await X.storage.tags.createTag(Q.id,Y.name);return{tag:{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():String(J.createdAt)}}}})});var KX0;var ZV6=x(()=>{g0();f6();KX0=v0({name:"TAGS_DELETE",description:"Delete a tag from an organization (removes from all members)",inputSchema:N.object({tagId:N.string().describe("Tag ID to delete")}),outputSchema:N.object({success:N.boolean()}),handler:async(Y,X)=>{t0(X),await X.access.check();let Q=H6(X),J=await X.storage.tags.getTag(Y.tagId);if(!J)throw Error("Tag not found");if(J.organizationId!==Q.id)throw Error("Tag does not belong to this organization");return await X.storage.tags.deleteTag(Y.tagId),{success:!0}}})});var HX0;var KV6=x(()=>{g0();f6();HX0=v0({name:"MEMBER_TAGS_GET",description:"Get tags assigned to a member",inputSchema:N.object({memberId:N.string().describe("Member ID")}),outputSchema:N.object({tags:N.array(N.object({id:N.string(),organizationId:N.string(),name:N.string(),createdAt:N.string().describe("ISO 8601 timestamp")}))}),handler:async(Y,X)=>{t0(X),await X.access.check();let Q=H6(X);if(!await X.storage.tags.verifyMemberOrg(Y.memberId,Q.id))throw Error(`Member not found in this organization: ${Y.memberId}`);return{tags:(await X.storage.tags.getMemberTags(Y.memberId)).map((K)=>({...K,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():String(K.createdAt)}))}}})});var FX0;var HV6=x(()=>{g0();f6();FX0=v0({name:"MEMBER_TAGS_SET",description:"Set tags for a member (replaces all existing tags)",inputSchema:N.object({memberId:N.string().describe("Member ID"),tagIds:N.array(N.string()).describe("Array of tag IDs to assign")}),outputSchema:N.object({success:N.boolean(),tags:N.array(N.object({id:N.string(),organizationId:N.string(),name:N.string(),createdAt:N.string().describe("ISO 8601 timestamp")}))}),handler:async(Y,X)=>{t0(X),await X.access.check();let Q=H6(X);if(!await X.storage.tags.verifyMemberOrg(Y.memberId,Q.id))throw Error(`Member not found in this organization: ${Y.memberId}`);for(let K of Y.tagIds){let W=await X.storage.tags.getTag(K);if(!W)throw Error(`Tag not found: ${K}`);if(W.organizationId!==Q.id)throw Error(`Tag does not belong to this organization: ${K}`)}return await X.storage.tags.setMemberTags(Y.memberId,Y.tagIds),{success:!0,tags:(await X.storage.tags.getMemberTags(Y.memberId)).map((K)=>({...K,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():String(K.createdAt)}))}}})});var FV6=x(()=>{GV6();WV6();ZV6();KV6();HV6()});var VV6,H7,qV6,$V6;var KV=x(()=>{g0();VV6=N.object({id:N.string().describe("Unique message ID"),threadId:N.string().describe("ID of the parent thread"),metadata:N.unknown().optional().describe("Optional message metadata"),parts:N.array(N.record(N.string(),N.unknown())).describe("Message content parts (AI SDK UIMessagePart format)"),role:N.enum(["user","assistant","system"]).describe("Message role"),createdAt:N.string().datetime().describe("Timestamp of creation"),updatedAt:N.string().datetime().describe("Timestamp of last update")}),H7=N.object({id:N.string().describe("Unique thread ID"),organizationId:N.string().describe("Organization this thread belongs to"),title:N.string().describe("Thread title"),description:N.string().nullable().describe("Thread description"),createdAt:N.string().datetime().describe("Timestamp of creation"),updatedAt:N.string().datetime().describe("Timestamp of last update"),hidden:N.boolean().optional().describe("Whether the thread is hidden"),createdBy:N.string().describe("User ID who created the thread"),updatedBy:N.string().nullable().describe("User ID who last updated the thread")}),qV6=N.object({id:N.string().optional().describe("Optional custom ID for the thread"),title:N.string().describe("Thread title"),description:N.string().nullish().describe("Thread description")}),$V6=N.object({title:N.string().optional().describe("New thread title"),description:N.string().nullish().describe("New thread description"),hidden:N.boolean().optional().describe("Whether the thread is hidden")})});var xn4,un4,VX0;var zV6=x(()=>{g0();f6();KV();Gf();xn4=N.object({data:qV6.describe("Data for the new thread (id is auto-generated if not provided)")}),un4=N.object({item:H7.describe("The created thread entity")}),VX0=v0({name:"COLLECTION_THREADS_CREATE",description:"Create a new thread in the organization",inputSchema:xn4,outputSchema:un4,handler:async(Y,X)=>{t0(X);let Q=H6(X);await X.access.check();let J=_8(X);if(!J)throw Error("User ID required to create thread");let G=Y.data.id??EB("thrd"),K=await X.storage.threads.create({id:G,organizationId:Q.id,title:Y.data.title,description:Y.data.description,createdBy:J});return{item:{...K,hidden:K.hidden??!1}}}})});var gn4,mn4,qX0;var BV6=x(()=>{bJ();f6();KV();g0();gn4=hW.extend({where:N.object({created_by:N.string().optional()}).optional()}),mn4=bW(H7),qX0=v0({name:"COLLECTION_THREADS_LIST",description:"List all threads in the organization with filtering, sorting, and pagination",inputSchema:gn4,outputSchema:mn4,handler:async(Y,X)=>{await X.access.check();let Q=X.auth.user?.id;if(!Q)throw Error("User ID required to list threads");let J=H6(X),G=Y.offset??0,K=Y.limit??100,{threads:W,total:Z}=await X.storage.threads.list(J.id,Q,{limit:K,offset:G}),H=G+K<Z;return{items:W.map((F)=>({...F,hidden:F.hidden??!1})),totalCount:Z,hasMore:H}}})});var ln4,$X0;var UV6=x(()=>{bJ();f6();KV();ln4=AP(H7),$X0=v0({name:"COLLECTION_THREADS_GET",description:"Get thread details by ID",inputSchema:TP,outputSchema:ln4,handler:async(Y,X)=>{t0(X);let Q=H6(X);await X.access.check();let J=await X.storage.threads.get(Y.id);if(!J||J.organizationId!==Q.id)return{item:null};return{item:{...J,hidden:J.hidden??!1}}}})});var dn4,pn4,zX0;var DV6=x(()=>{g0();f6();KV();dn4=N.object({id:N.string().describe("ID of the thread to update"),data:$V6.describe("Partial thread data to update")}),pn4=N.object({item:H7.describe("The updated thread entity")}),zX0=v0({name:"COLLECTION_THREADS_UPDATE",description:"Update an existing thread in the organization",inputSchema:dn4,outputSchema:pn4,handler:async(Y,X)=>{t0(X);let Q=H6(X);await X.access.check();let J=_8(X);if(!J)throw Error("User ID required to update thread");let{id:G,data:K}=Y,W=await X.storage.threads.get(G);if(!W||W.organizationId!==Q.id)throw Error("Thread not found in organization");let Z=await X.storage.threads.update(G,{title:K.title,description:K.description,hidden:K.hidden,updatedBy:J});return{item:{...Z,hidden:Z.hidden??!1}}}})});var BX0;var OV6=x(()=>{bJ();f6();KV();BX0=v0({name:"COLLECTION_THREADS_DELETE",description:"Delete a thread",inputSchema:EP,outputSchema:CP(H7),handler:async(Y,X)=>{t0(X);let Q=H6(X);await X.access.check();let J=await X.storage.threads.get(Y.id);if(!J)throw Error(`Thread not found: ${Y.id}`);if(J.organizationId!==Q.id)throw Error(`Thread not found: ${Y.id}`);return await X.storage.threads.delete(Y.id),{item:{...J,hidden:J.hidden??!1}}}})});function NV6(Y){if(!Y)return null;if("field"in Y&&Y.field[0]==="threadId"&&Y.operator==="eq")return String(Y.value);if("conditions"in Y)for(let X of Y.conditions){let Q=NV6(X);if(Q)return Q}return null}var cn4,UX0;var LV6=x(()=>{bJ();f6();KV();cn4=bW(VV6),UX0=v0({name:"COLLECTION_THREAD_MESSAGES_LIST",description:"List all messages for a specific thread",inputSchema:hW,outputSchema:cn4,handler:async(Y,X)=>{let Q=H6(X);await X.access.check();let J=NV6(Y.where);if(!J)throw Error("threadId filter is required in where clause");let G=await X.storage.threads.get(J);if(!G||G.organizationId!==Q.id)return{items:[],totalCount:0,hasMore:!1};let K=Y.offset??0,W=Y.limit??100,{messages:Z,total:H}=await X.storage.threads.listMessages(J,{limit:W,offset:K}),F=K+W<H;return{items:Z,totalCount:H,hasMore:F}}})});var MV6=x(()=>{zV6();BV6();UV6();DV6();OV6();LV6()});var in4,an4,DX0;var wV6=x(()=>{g0();f6();in4=N.object({id:N.string().min(1)}),an4=N.object({user:N.object({id:N.string(),name:N.string(),email:N.string(),image:N.string().nullable()}).nullable()}),DX0=v0({name:"USER_GET",description:"Get a user by id (restricted to shared organizations)",inputSchema:in4,outputSchema:an4,handler:async(Y,X)=>{await X.access.check(),t0(X);let Q=_8(X);if(!Q)throw Error("Authentication required");let J=await X.storage.users.findById(Y.id,Q);if(!J)return{user:null};return{user:{id:J.id,name:J.name,email:J.email,image:J.image??null}}}})});var PV6=x(()=>{wV6()});var AV6={};h6(AV6,{managementMCP:()=>tn4,ALL_TOOLS:()=>TV6});var on4,sn4,TV6,tn4=async(Y)=>{let X=null;if(Y.organization)X=(await Y.storage.organizationSettings.get(Y.organization.id))?.enabled_plugins??null;let J=DK6(TV6,X).map((K)=>({name:K.name,description:K.description,inputSchema:K.inputSchema,outputSchema:K.outputSchema,handler:async(W)=>{return Y.access.setToolName(K.name),await K.execute(W,Y)}}));return N36({name:"mcp-mesh-management",version:"1.0.0"}).withTools(J).build()};var EV6=x(()=>{L36();u90();vK6();CH6();BF6();NF6();RF6();yF6();lF6();cF6();JV6();FV6();MV6();PV6();on4=[iY0,aY0,rY0,oY0,sY0,eY0,YX0,XX0,QX0,JX0,GX0,zY0,MY0,wY0,TY0,AY0,EY0,_Y0,fY0,hY0,bY0,xY0,gY0,mY0,lY0,dY0,pY0,OF6,cY0,nY0,m90,d90,p90,l90,CY0,IY0,RY0,SY0,jY0,kY0,vY0,DX0,VY0,qY0,$Y0,VX0,qX0,$X0,zX0,BX0,UX0,WX0,ZX0,KX0,HX0,FX0],sn4=OK6(),TV6=[...on4,...sn4]});qh();import{Migrator as yV6,sql as gW}from"kysely";var gX0={benchmark:()=>Promise.resolve().then(() => (uX0(),xX0)).then((Y)=>Y.seed)};async function mX0(Y,X){let Q=gX0[X];if(!Q)throw Error(`Unknown seed: ${X}. Available: ${Object.keys(gX0).join(", ")}`);let J=await Q();console.log(`\uD83C\uDF31 Running seed: ${X}`);let G=await J(Y);return console.log(`\u2705 Seed "${X}" completed`),G}F7();yQ();F7();yQ();wY();N9();var P8=(Y,X="ms")=>{return new Date(Date.now()+(X==="sec"?Y*1000:Y))},aC=new WeakMap;function O70(Y,X){let Q=X.fields,J={};for(let G in Y){let K=Q[G];if(!K){J[G]=Y[G];continue}if(K.returned===!1)continue;J[G]=Y[G]}return J}function rC(Y,X){if(!aC.has(Y))aC.set(Y,new Map);let Q=aC.get(Y);if(Q.has(X))return Q.get(X);let J={...X==="user"?Y.user?.additionalFields:{},...X==="session"?Y.session?.additionalFields:{}};for(let G of Y.plugins||[])if(G.schema&&G.schema[X])J={...J,...G.schema[X].fields};return aC.get(Y).set(X,J),J}function L9(Y,X){return{...O70(X,{fields:rC(Y,"user")}),id:X.id}}function o5(Y,X){return O70(X,{fields:rC(Y,"session")})}function um(Y,X){let Q=X.action||"create",J=X.fields,G=Object.assign(Object.create(null),null);for(let K in J){if(K in Y){if(J[K].input===!1){if(J[K].defaultValue!==void 0){if(Q!=="update"){G[K]=J[K].defaultValue;continue}}if(Y[K])throw new i("BAD_REQUEST",{message:`${K} is not allowed to be set`});continue}if(J[K].validator?.input&&Y[K]!==void 0){G[K]=J[K].validator.input["~standard"].validate(Y[K]);continue}if(J[K].transform?.input&&Y[K]!==void 0){G[K]=J[K].transform?.input(Y[K]);continue}G[K]=Y[K];continue}if(J[K].defaultValue!==void 0&&Q==="create"){if(typeof J[K].defaultValue==="function"){G[K]=J[K].defaultValue();continue}G[K]=J[K].defaultValue;continue}if(J[K].required&&Q==="create")throw new i("BAD_REQUEST",{message:`${K} is required`})}return G}function oC(Y,X={},Q){return um(X,{fields:rC(Y,"user"),action:Q})}function gm(Y,X){return um(X,{fields:rC(Y,"session")})}function lY(Y,X){if(!X)return Y;for(let Q in X){let J=X[Q]?.modelName;if(J)Y[Q].modelName=J;for(let G in Y[Q].fields){let K=X[Q]?.fields?.[G];if(!K)continue;Y[Q].fields[G].fieldName=K}}return Y}AX();g0();var yD6="127.0.0.1";function OZ(Y,X){if(X.advanced?.ipAddress?.disableIpTracking)return null;if(T7()||Wq())return yD6;let Q="headers"in Y?Y.headers:Y,J=X.advanced?.ipAddress?.ipAddressHeaders||["x-forwarded-for"];for(let G of J){let K="get"in Q?Q.get(G):Q[G];if(typeof K==="string"){let W=K.split(",")[0].trim();if(fD6(W))return W}}return null}function fD6(Y){if(bK().safeParse(Y).success)return!0;if(xK().safeParse(Y).success)return!0;return!1}PY();n5();AX();y8();import{sql as t5}from"kysely";async function P70(Y,X){let Q;if(!Y.database){let J=XQ(Y),G=Object.keys(J).reduce((W,Z)=>{return W[Z]=[],W},{}),{memoryAdapter:K}=await Promise.resolve().then(() => (w70(),M70));Q=K(G)(Y)}else if(typeof Y.database==="function")Q=Y.database(Y);else Q=await X(Y);if(!Q.transaction)b6.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 nm(Y){return P70(Y,async(X)=>{let{createKyselyAdapter:Q}=await Promise.resolve().then(() => (cm(),pm)),{kysely:J,databaseType:G,transaction:K}=await Q(X);if(!J)throw new I6("Failed to initialize database adapter");let{kyselyAdapter:W}=await Promise.resolve().then(() => (cm(),pm));return W(J,{type:G||"sqlite",debugLogs:X.database&&"debugLogs"in X.database?X.database.debugLogs:!1,transaction:K})(X)})}function T70(Y,X){let Q=X.hooks;async function J(H,F,V){let q=await QQ(),$=H;for(let O of Q||[]){let L=O[F]?.create?.before;if(L){let M=await L($,q);if(M===!1)return null;if(typeof M==="object"&&"data"in M)$={...$,...M.data}}}let B=V?await V.fn($):null,U=!V||V.executeMainFn?await(await U1(Y)).create({model:F,data:$,forceAllowId:!0}):B;for(let O of Q||[]){let L=O[F]?.create?.after;if(L)await L(U,q)}return U}async function G(H,F,V,q){let $=await QQ(),B=H;for(let L of Q||[]){let M=L[V]?.update?.before;if(M){let C=await M(H,$);if(C===!1)return null;if(typeof C==="object"&&"data"in C)B={...B,...C.data}}}let U=q?await q.fn(B):null,O=!q||q.executeMainFn?await(await U1(Y)).update({model:V,update:B,where:F}):U;for(let L of Q||[]){let M=L[V]?.update?.after;if(M)await M(O,$)}return O}async function K(H,F,V,q){let $=await QQ(),B=H;for(let L of Q||[]){let M=L[V]?.update?.before;if(M){let C=await M(H,$);if(C===!1)return null;if(typeof C==="object"&&"data"in C)B={...B,...C.data}}}let U=q?await q.fn(B):null,O=!q||q.executeMainFn?await(await U1(Y)).updateMany({model:V,update:B,where:F}):U;for(let L of Q||[]){let M=L[V]?.update?.after;if(M)await M(O,$)}return O}async function W(H,F,V){let q=await QQ(),$=null;try{$=(await(await U1(Y)).findMany({model:F,where:H,limit:1}))[0]||null}catch(O){}if($)for(let O of Q||[]){let L=O[F]?.delete?.before;if(L){if(await L($,q)===!1)return null}}let B=V?await V.fn(H):null,U=!V||V.executeMainFn?await(await U1(Y)).delete({model:F,where:H}):B;if($)for(let O of Q||[]){let L=O[F]?.delete?.after;if(L)await L($,q)}return U}async function Z(H,F,V){let q=await QQ(),$=[];try{$=await(await U1(Y)).findMany({model:F,where:H})}catch(O){}for(let O of $)for(let L of Q||[]){let M=L[F]?.delete?.before;if(M){if(await M(O,q)===!1)return null}}let B=V?await V.fn(H):null,U=!V||V.executeMainFn?await(await U1(Y)).deleteMany({model:F,where:H}):B;for(let O of $)for(let L of Q||[]){let M=L[F]?.delete?.after;if(M)await M(O,q)}return U}return{createWithHooks:J,updateWithHooks:G,updateManyWithHooks:K,deleteWithHooks:W,deleteManyWithHooks:Z}}var J2=(Y,X)=>{let{logger:Q,options:J}=X,G=J.secondaryStorage,K=J.session?.expiresIn||604800,{createWithHooks:W,updateWithHooks:Z,updateManyWithHooks:H,deleteWithHooks:F,deleteManyWithHooks:V}=T70(Y,X);async function q($){if(!G)return;let B=await G.get(`active-sessions-${$.id}`);if(!B)return;let U=Date.now(),O=(T1(B)||[]).filter((L)=>L.expiresAt>U);await Promise.all(O.map(async({token:L})=>{let M=await G.get(L);if(!M)return;let C=T1(M);if(!C)return;let R=Math.max(Math.floor(new Date(C.session.expiresAt).getTime()-U)/1000,0);await G.set(L,JSON.stringify({session:C.session,user:$}),Math.floor(R))}))}return{createOAuthUser:async($,B)=>{return LU(Y,async()=>{let U=await W({createdAt:new Date,updatedAt:new Date,...$},"user",void 0);return{user:U,account:await W({...B,userId:U.id,createdAt:new Date,updatedAt:new Date},"account",void 0)}})},createUser:async($)=>{return await W({createdAt:new Date,updatedAt:new Date,...$,email:$.email?.toLowerCase()},"user",void 0)},createAccount:async($)=>{return await W({createdAt:new Date,updatedAt:new Date,...$},"account",void 0)},listSessions:async($)=>{if(G){let B=await G.get(`active-sessions-${$}`);if(!B)return[];let U=T1(B)||[],O=Date.now(),L=U.filter((C)=>C.expiresAt>O),M=[];for(let C of L){let R=await G.get(C.token);if(R){let E=T1(R);if(!E)return[];let T=o5(X.options,{...E.session,expiresAt:new Date(E.session.expiresAt)});M.push(T)}}return M}return await(await U1(Y)).findMany({model:"session",where:[{field:"userId",value:$}]})},listUsers:async($,B,U,O)=>{return await(await U1(Y)).findMany({model:"user",limit:$,offset:B,sortBy:U,where:O})},countTotalUsers:async($)=>{let B=await(await U1(Y)).count({model:"user",where:$});if(typeof B==="string")return parseInt(B);return B},deleteUser:async($)=>{if(G)await G.delete(`active-sessions-${$}`);if(!G||J.session?.storeSessionInDatabase)await V([{field:"userId",value:$}],"session",void 0);await V([{field:"userId",value:$}],"account",void 0),await F([{field:"id",value:$}],"user",void 0)},createSession:async($,B,U,O)=>{let L=await QQ().catch(()=>null),M=L?.headers||L?.request?.headers,{id:C,...R}=U||{},E=gm(L?.context.options??J,{}),T={ipAddress:L?.request||L?.headers?OZ(L?.request||L?.headers,L?.context.options)||"":"",userAgent:M?.get("user-agent")||"",...R,expiresAt:B?P8(86400,"sec"):P8(K,"sec"),userId:$,token:a8(32),createdAt:new Date,updatedAt:new Date,...E,...O?R:{}};return await W(T,"session",G?{fn:async(I)=>{let S=await G.get(`active-sessions-${$}`),k=[],_=Date.now();if(S)k=T1(S)||[],k=k.filter((d)=>d.expiresAt>_);let y=k.sort((d,Y0)=>d.expiresAt-Y0.expiresAt),f=y.at(-1)?.expiresAt;if(y.push({token:T.token,expiresAt:T.expiresAt.getTime()}),!f||f<T.expiresAt.getTime())f=T.expiresAt.getTime();let o=Math.max(Math.floor((f-_)/1000),0);if(o>0)await G.set(`active-sessions-${$}`,JSON.stringify(y),o);let m=await Y.findOne({model:"user",where:[{field:"id",value:$}]}),v=Math.max(Math.floor((T.expiresAt.getTime()-_)/1000),0);if(v>0)await G.set(T.token,JSON.stringify({session:I,user:m}),v);return I},executeMainFn:J.session?.storeSessionInDatabase}:void 0)},findSession:async($)=>{if(G){let L=await G.get($);if(!L&&!J.session?.storeSessionInDatabase)return null;if(L){let M=T1(L);if(!M)return null;return{session:o5(X.options,{...M.session,expiresAt:new Date(M.session.expiresAt),createdAt:new Date(M.session.createdAt),updatedAt:new Date(M.session.updatedAt)}),user:L9(X.options,{...M.user,createdAt:new Date(M.user.createdAt),updatedAt:new Date(M.user.updatedAt)})}}}let B=await(await U1(Y)).findOne({model:"session",where:[{value:$,field:"token"}],join:{user:!0}});if(!B)return null;let{user:U,...O}=B;if(!U)return null;return{session:o5(X.options,O),user:L9(X.options,U)}},findSessions:async($)=>{if(G){let U=[];for(let O of $){let L=await G.get(O);if(L){let M=T1(L);if(!M)return[];let C={session:{...M.session,expiresAt:new Date(M.session.expiresAt)},user:{...M.user,createdAt:new Date(M.user.createdAt),updatedAt:new Date(M.user.updatedAt)}};U.push(C)}}return U}let B=await(await U1(Y)).findMany({model:"session",where:[{field:"token",value:$,operator:"in"}],join:{user:!0}});if(!B.length)return[];if(B.some((U)=>!U.user))return[];return B.map((U)=>{let{user:O,...L}=U;return{session:L,user:O}})},updateSession:async($,B)=>{return await Z(B,[{field:"token",value:$}],"session",G?{async fn(U){let O=await G.get($),L=null;if(O){let M=T1(O);if(!M)return null;return L={...M.session,...U},L}else return null},executeMainFn:J.session?.storeSessionInDatabase}:void 0)},deleteSession:async($)=>{if(G){let B=await G.get($);if(B){let{session:U}=T1(B)??{};if(!U){Q.error("Session not found in secondary storage");return}let O=U.userId,L=await G.get(`active-sessions-${O}`);if(L){let M=T1(L)||[],C=Date.now(),R=M.filter((T)=>T.expiresAt>C&&T.token!==$),E=R.sort((T,I)=>T.expiresAt-I.expiresAt).at(-1)?.expiresAt;if(R.length>0&&E&&E>Date.now())await G.set(`active-sessions-${O}`,JSON.stringify(R),Math.floor((E-C)/1000));else await G.delete(`active-sessions-${O}`)}else Q.error("Active sessions list not found in secondary storage")}if(await G.delete($),!J.session?.storeSessionInDatabase||X.options.session?.preserveSessionInDatabase)return}await(await U1(Y)).delete({model:"session",where:[{field:"token",value:$}]})},deleteAccounts:async($)=>{await V([{field:"userId",value:$}],"account",void 0)},deleteAccount:async($)=>{await F([{field:"id",value:$}],"account",void 0)},deleteSessions:async($)=>{if(G){if(typeof $==="string"){let B=await G.get(`active-sessions-${$}`),U=B?T1(B):[];if(!U)return;for(let O of U)await G.delete(O.token)}else for(let B of $)if(await G.get(B))await G.delete(B);if(!J.session?.storeSessionInDatabase||X.options.session?.preserveSessionInDatabase)return}await V([{field:Array.isArray($)?"token":"userId",value:$,operator:Array.isArray($)?"in":void 0}],"session",void 0)},findOAuthUser:async($,B,U)=>{let O=await(await U1(Y)).findMany({model:"account",where:[{value:B,field:"accountId"}],join:{user:!0}}).then((L)=>{return L.find((M)=>M.providerId===U)});if(O)if(O.user)return{user:O.user,accounts:[O]};else{let L=await(await U1(Y)).findOne({model:"user",where:[{value:$.toLowerCase(),field:"email"}]});if(L)return{user:L,accounts:[O]};return null}else{let L=await(await U1(Y)).findOne({model:"user",where:[{value:$.toLowerCase(),field:"email"}]});if(L)return{user:L,accounts:await(await U1(Y)).findMany({model:"account",where:[{value:L.id,field:"userId"}]})||[]};else return null}},findUserByEmail:async($,B)=>{let U=await(await U1(Y)).findOne({model:"user",where:[{value:$.toLowerCase(),field:"email"}],join:{...B?.includeAccounts?{account:!0}:{}}});if(!U)return null;let{account:O,...L}=U;return{user:L,accounts:O??[]}},findUserById:async($)=>{if(!$)return null;return await(await U1(Y)).findOne({model:"user",where:[{field:"id",value:$}]})},linkAccount:async($)=>{return await W({createdAt:new Date,updatedAt:new Date,...$},"account",void 0)},updateUser:async($,B)=>{let U=await Z(B,[{field:"id",value:$}],"user",void 0);return await q(U),await q(U),U},updateUserByEmail:async($,B)=>{let U=await Z(B,[{field:"email",value:$.toLowerCase()}],"user",void 0);return await q(U),await q(U),U},updatePassword:async($,B)=>{await H({password:B},[{field:"userId",value:$},{field:"providerId",value:"credential"}],"account",void 0)},findAccounts:async($)=>{return await(await U1(Y)).findMany({model:"account",where:[{field:"userId",value:$}]})},findAccount:async($)=>{return await(await U1(Y)).findOne({model:"account",where:[{field:"accountId",value:$}]})},findAccountByProviderId:async($,B)=>{return await(await U1(Y)).findOne({model:"account",where:[{field:"accountId",value:$},{field:"providerId",value:B}]})},findAccountByUserId:async($)=>{return await(await U1(Y)).findMany({model:"account",where:[{field:"userId",value:$}]})},updateAccount:async($,B)=>{return await Z(B,[{field:"id",value:$}],"account",void 0)},createVerificationValue:async($)=>{return await W({createdAt:new Date,updatedAt:new Date,...$},"verification",void 0)},findVerificationValue:async($)=>{let B=await(await U1(Y)).findMany({model:"verification",where:[{field:"identifier",value:$}],sortBy:{field:"createdAt",direction:"desc"},limit:1});if(!J.verification?.disableCleanup)await(await U1(Y)).deleteMany({model:"verification",where:[{field:"expiresAt",value:new Date,operator:"lt"}]});return B[0]},deleteVerificationValue:async($)=>{await(await U1(Y)).delete({model:"verification",where:[{field:"id",value:$}]})},deleteVerificationByIdentifier:async($)=>{await(await U1(Y)).delete({model:"verification",where:[{field:"identifier",value:$}]})},updateVerificationValue:async($,B)=>{return await Z(B,[{field:"id",value:$}],"verification",void 0)}}};function A70(Y){let X=XQ(Y),Q={};for(let J in X){let G=X[J],K=G.fields,W={};if(Object.entries(K).forEach(([Z,H])=>{if(W[H.fieldName||Z]=H,H.references){let F=X[H.references.model];if(F)W[H.fieldName||Z].references={...H.references,model:F.modelName,field:H.references.field}}}),Q[G.modelName]){Q[G.modelName].fields={...Q[G.modelName].fields,...W};continue}Q[G.modelName]={fields:W,order:G.order||1/0}}return Q}var mD6={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 E70(Y,X,Q){function J(K){return K.toLowerCase().split("(")[0].trim()}if(X==="string[]"||X==="number[]")return Y.toLowerCase().includes("json");let G=mD6[Q];return(Array.isArray(X)?G.string.map((K)=>K.toLowerCase()):G[X].map((K)=>K.toLowerCase())).includes(J(Y))}async function lD6(Y){try{let X=await t5`SHOW search_path`.execute(Y);if(X.rows[0]?.search_path)return X.rows[0].search_path.split(",").map((Q)=>Q.trim()).map((Q)=>Q.replace(/^["']|["']$/g,"")).filter((Q)=>!Q.startsWith("$"))[0]||"public"}catch(X){}return"public"}async function sD(Y){let X=A70(Y),Q=Kq(Y.logger),{kysely:J,databaseType:G}=await rP(Y);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 K="public";if(G==="postgres"){K=await lD6(J),Q.debug(`PostgreSQL migration: Using schema '${K}' (from search_path)`);try{if(!(await t5`
422
422
  SELECT schema_name