@decocms/mesh 2.90.0 → 2.91.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 (156) hide show
  1. package/dist/client/assets/{AlertCircle-C7tRYAkQ.js → AlertCircle-D3uMaIep.js} +1 -1
  2. package/dist/client/assets/{AlertOctagon-D28THNQG.js → AlertOctagon-D8xrBki-.js} +1 -1
  3. package/dist/client/assets/{ArrowLeft-ClBGgo4l.js → ArrowLeft-BjqYsLvO.js} +1 -1
  4. package/dist/client/assets/{ArrowUp-BpGy_9ab.js → ArrowUp-BZmoIrId.js} +1 -1
  5. package/dist/client/assets/{Check-BlM4FeFk.js → Check-BezMXh3m.js} +1 -1
  6. package/dist/client/assets/{CheckCircle-D3DqVSof.js → CheckCircle-BJs6jTra.js} +1 -1
  7. package/dist/client/assets/{CheckDone01-BfRwhIAp.js → CheckDone01-B8_tfP98.js} +1 -1
  8. package/dist/client/assets/{ChevronDown-n5N_Lrv1.js → ChevronDown-Cvn22peU.js} +1 -1
  9. package/dist/client/assets/{ChevronRight-lgE9DrmA.js → ChevronRight-CTxl6bgR.js} +1 -1
  10. package/dist/client/assets/{Clock-3uBZYEa5.js → Clock-0kD4NxnQ.js} +1 -1
  11. package/dist/client/assets/{Code01-cW71Rk7W.js → Code01-BQDW5YjG.js} +1 -1
  12. package/dist/client/assets/{Copy01-DXqcDIlB.js → Copy01---hH64QW.js} +1 -1
  13. package/dist/client/assets/{Dataflow03-BjBcE8LM.js → Dataflow03-Ewf19tYQ.js} +1 -1
  14. package/dist/client/assets/{DotsHorizontal-RsDeFGvO.js → DotsHorizontal-KHWDbLx3.js} +1 -1
  15. package/dist/client/assets/{DotsVertical-Co7jTcE3.js → DotsVertical-CMwmj3Es.js} +1 -1
  16. package/dist/client/assets/{Download01-Bmf0yTxv.js → Download01-D2v6tnjT.js} +1 -1
  17. package/dist/client/assets/{Edit01-N_wE51Ji.js → Edit01-DLX_Q0on.js} +1 -1
  18. package/dist/client/assets/{Eye-Cjx3gmL-.js → Eye-DRhYa9c6.js} +1 -1
  19. package/dist/client/assets/{File02-B0_YpZ9K.js → File02-CJp6EwHF.js} +1 -1
  20. package/dist/client/assets/{File06-D5WlkKz7.js → File06-DVtDhdE5.js} +1 -1
  21. package/dist/client/assets/{FilterLines-ByV6YQqf.js → FilterLines-BcYSGfMN.js} +1 -1
  22. package/dist/client/assets/{Grid01-g5UbnnWY.js → Grid01-CgGHrqe5.js} +1 -1
  23. package/dist/client/assets/{Home02-6R9rPjal.js → Home02-uUB8Atfq.js} +1 -1
  24. package/dist/client/assets/{Image01-BoBW5lkf.js → Image01-C2cIbm7r.js} +1 -1
  25. package/dist/client/assets/{Inbox01-V2c_v8Vp.js → Inbox01-De5dzagw.js} +1 -1
  26. package/dist/client/assets/{InfoCircle-DbRe7m5X.js → InfoCircle-CWs-zdhv.js} +1 -1
  27. package/dist/client/assets/{LinkExternal01-B46QCd1_.js → LinkExternal01-7UvZi8_7.js} +1 -1
  28. package/dist/client/assets/{List-CnnFCaa_.js → List-B1anaj6z.js} +1 -1
  29. package/dist/client/assets/{Loading01-Ccnn8_nz.js → Loading01-CLaVZz2q.js} +1 -1
  30. package/dist/client/assets/{Lock01-CVg2TqaU.js → Lock01-DQZtigfQ.js} +1 -1
  31. package/dist/client/assets/{Pin01-CF5MBNG_.js → Pin01-DbMTghLG.js} +1 -1
  32. package/dist/client/assets/{Play-C_QZtdLh.js → Play-DifJQu9t.js} +1 -1
  33. package/dist/client/assets/{Plus-CvcYPEKD.js → Plus-BSoD06T5.js} +1 -1
  34. package/dist/client/assets/{RefreshCcw01-BhE8Z0sx.js → RefreshCcw01-vEyX2U13.js} +1 -1
  35. package/dist/client/assets/{SearchMd-B9p0bq1M.js → SearchMd-C3imEkj_.js} +1 -1
  36. package/dist/client/assets/{Settings01-BhBPpX3P.js → Settings01-D8Z_Og0d.js} +1 -1
  37. package/dist/client/assets/{Settings02-C75jbNRo.js → Settings02-DgNG_ojd.js} +1 -1
  38. package/dist/client/assets/{Share07-CA-_juFF.js → Share07-hI7-H_19.js} +1 -1
  39. package/dist/client/assets/{Terminal-D42HfJTr.js → Terminal-DY1lkBQp.js} +1 -1
  40. package/dist/client/assets/{Tool01-KjU2GsJW.js → Tool01-0C3r9eV1.js} +1 -1
  41. package/dist/client/assets/{Trash01-D_mSmFpX.js → Trash01-DMOrN3jw.js} +1 -1
  42. package/dist/client/assets/{Upload01-CYF85wnV.js → Upload01-BexbsGa1.js} +1 -1
  43. package/dist/client/assets/{Users03-DnAc5DRq.js → Users03-BwVADaNJ.js} +1 -1
  44. package/dist/client/assets/{X-CTTAOdP5.js → X-Bl4EbJn_.js} +1 -1
  45. package/dist/client/assets/{XClose-BDwJzgQF.js → XClose-9BHLBZyJ.js} +1 -1
  46. package/dist/client/assets/{agent-connections-preview-WthQDsUW.js → agent-connections-preview-bfNWF9f4.js} +1 -1
  47. package/dist/client/assets/{agent-detail-BqH9cJNR.js → agent-detail-C0LVwYuk.js} +1 -1
  48. package/dist/client/assets/{agents-BKnANQQN.js → agents-Da7CoTZX.js} +1 -1
  49. package/dist/client/assets/{alert-dialog-BJDYLAWS.js → alert-dialog-COW9KsrJ.js} +1 -1
  50. package/dist/client/assets/{auth-catchall-CuG4SMT1.js → auth-catchall-Cx74TIV5.js} +1 -1
  51. package/dist/client/assets/{avatar-hfcMVnoj.js → avatar-B3_biBMx.js} +1 -1
  52. package/dist/client/assets/{badge-CIAJTYZ7.js → badge-BdBlFaz2.js} +1 -1
  53. package/dist/client/assets/{binder--fFRikp7.js → binder-C_nJEmPU.js} +1 -1
  54. package/dist/client/assets/{breadcrumb-D1rwM2Yk.js → breadcrumb-CFvRp0LA.js} +1 -1
  55. package/dist/client/assets/{button-BnN5ws1J.js → button-DjRH1lB9.js} +1 -1
  56. package/dist/client/assets/{card-BX6VrB48.js → card-Crky3Dgs.js} +1 -1
  57. package/dist/client/assets/{checkbox-DOeM5BVC.js → checkbox-Buxpr0H5.js} +1 -1
  58. package/dist/client/assets/{circle-alert-CanUFwMg.js → circle-alert-B1x_VZv1.js} +1 -1
  59. package/dist/client/assets/{collection-detail-BfT9tQOH.js → collection-detail-hSjhUQb2.js} +1 -1
  60. package/dist/client/assets/{collection-search-Bg9cWleV.js → collection-search-Bznozec1.js} +1 -1
  61. package/dist/client/assets/{collection-tab-CMls2aRz.js → collection-tab-ETUYU_1h.js} +1 -1
  62. package/dist/client/assets/{collection-table-wrapper-IH3SFlYc.js → collection-table-wrapper-vIBxhjD_.js} +1 -1
  63. package/dist/client/assets/{collection-tabs-HtJ4lBOg.js → collection-tabs-Bsw5t_Dk.js} +1 -1
  64. package/dist/client/assets/{command-DKX4YOs7.js → command-BAunXmp4.js} +1 -1
  65. package/dist/client/assets/{connect-CScXrMiF.js → connect-r9AFxBWi.js} +1 -1
  66. package/dist/client/assets/{connection-card-8FtaUNQo.js → connection-card-BDRzJeyM.js} +1 -1
  67. package/dist/client/assets/{connection-detail-Bth-DhCL.js → connection-detail-BdzqkQsY.js} +1 -1
  68. package/dist/client/assets/{connections-CdtHndVF.js → connections-Ba704Ay2.js} +1 -1
  69. package/dist/client/assets/constants-B-3MHVrP.js +1 -0
  70. package/dist/client/assets/{constants-C28hHydK.js → constants-BbV5_Gvn.js} +1 -1
  71. package/dist/client/assets/{create-organization-dialog-ACj0lCMg.js → create-organization-dialog-CjDiPAzO.js} +1 -1
  72. package/dist/client/assets/{create-project-dialog-CG1IAO6H.js → create-project-dialog-BdjSvU61.js} +1 -1
  73. package/dist/client/assets/{dialog-DeXMCOEf.js → dialog-Ci90OZB_.js} +1 -1
  74. package/dist/client/assets/{dropdown-menu-DPxrC0cn.js → dropdown-menu-D0d6DveS.js} +1 -1
  75. package/dist/client/assets/{dynamic-plugin-layout-RLjAjaM3.js → dynamic-plugin-layout-Cde8Zw72.js} +1 -1
  76. package/dist/client/assets/{empty-state-DXwHwR9N.js → empty-state-B1u2cnEd.js} +1 -1
  77. package/dist/client/assets/{empty-state-C7dCfthv.js → empty-state-Db26F2g6.js} +1 -1
  78. package/dist/client/assets/{env-vars-editor-CLkN05wk.js → env-vars-editor-CCksRmt4.js} +1 -1
  79. package/dist/client/assets/{error-boundary-D93CFTiZ.js → error-boundary-DAtnvYEv.js} +1 -1
  80. package/dist/client/assets/{extract-connection-data-BXN_EDIw.js → extract-connection-data-C1ap4UAi.js} +1 -1
  81. package/dist/client/assets/{file-browser-BS2NyUbN.js → file-browser-vsIHIoyy.js} +2 -2
  82. package/dist/client/assets/{form-BCLb-UZ8.js → form-DwpSVrp-.js} +1 -1
  83. package/dist/client/assets/{grid-view-ooajsBAE.js → grid-view-B0rAMSSu.js} +1 -1
  84. package/dist/client/assets/{home-DxR7zQcl.js → home-BvOOt5Jz.js} +1 -1
  85. package/dist/client/assets/{index-sPSrSvLX.js → index-B6v49bFc.js} +1 -1
  86. package/dist/client/assets/{index-COa_SM9b.js → index-BWt7IZ6Z.js} +1 -1
  87. package/dist/client/assets/{index-Ddnu0nh3.js → index-Bs-0nDVT.js} +1 -1
  88. package/dist/client/assets/{index-CIh8Wxq9.js → index-C0Cm9UFB.js} +1 -1
  89. package/dist/client/assets/{index-BKKW7mU3.js → index-CGRyA9w8.js} +2 -2
  90. package/dist/client/assets/{index-BeRVkHG-.js → index-CnWGXAB7.js} +1 -1
  91. package/dist/client/assets/{index-Yaa_q04V.js → index-DA6l4j1R.js} +1 -1
  92. package/dist/client/assets/{index-Cm60R_4-.js → index-DF5Pmq_t.js} +1 -1
  93. package/dist/client/assets/{index-DH-kjK80.js → index-DirGeY-G.js} +1 -1
  94. package/dist/client/assets/{infiniteQueryObserver-C--Cp687.js → infiniteQueryObserver-Bz2qGnnL.js} +1 -1
  95. package/dist/client/assets/{input-U8YSaKi9.js → input-BN8tWROr.js} +1 -1
  96. package/dist/client/assets/{integration-icon-CAACzZ59.js → integration-icon-C_JseQQS.js} +1 -1
  97. package/dist/client/assets/{label-DSCjug1q.js → label-DgY9ov9i.js} +1 -1
  98. package/dist/client/assets/{layout-D93kgkkB.js → layout-CBw836gt.js} +1 -1
  99. package/dist/client/assets/{localstorage-keys-B_Uu7Ngj.js → localstorage-keys-nexyeweP.js} +1 -1
  100. package/dist/client/assets/{login-mt0PAQTm.js → login-CiVf3zef.js} +1 -1
  101. package/dist/client/assets/{mcp-oauth-BmANfNMA.js → mcp-oauth-B6wyAMx4.js} +1 -1
  102. package/dist/client/assets/{mcp-server-card-DOw4tptS.js → mcp-server-card-OYdKEPTN.js} +1 -1
  103. package/dist/client/assets/{mcp-server-detail-HN9d-4zv.js → mcp-server-detail-CuJRzZD8.js} +2 -2
  104. package/dist/client/assets/{members-o9UHewte.js → members-DkeJcxqi.js} +1 -1
  105. package/dist/client/assets/{monitoring-DeMCxpp8.js → monitoring-egwPLjp0.js} +1 -1
  106. package/dist/client/assets/{oauth-callback-OXPIh8UO.js → oauth-callback-CiwqJVg6.js} +1 -1
  107. package/dist/client/assets/{page-D8ANTJRr.js → page-BmoxBndy.js} +1 -1
  108. package/dist/client/assets/{page-D1jCMFVy.js → page-YgKzJWRP.js} +1 -1
  109. package/dist/client/assets/{plugin-empty-state-CseSTXo8.js → plugin-empty-state-Bm8j6Yah.js} +1 -1
  110. package/dist/client/assets/{plugin-empty-state-BztjA2Hv.js → plugin-empty-state-Cg6QQuTW.js} +1 -1
  111. package/dist/client/assets/{plugin-header-CYOR-GLV.js → plugin-header-BiBPfNm9.js} +1 -1
  112. package/dist/client/assets/{plugin-header-CJXqQw-8.js → plugin-header-Za0zOP8_.js} +1 -1
  113. package/dist/client/assets/{popover-Z8clS3LN.js → popover-DBISvNt-.js} +1 -1
  114. package/dist/client/assets/{project-layout-CToIFtP6.js → project-layout-wSllqfdZ.js} +1 -1
  115. package/dist/client/assets/{project-settings-BjPBm7hi.js → project-settings-B34SlsnE.js} +1 -1
  116. package/dist/client/assets/{projects-list-B8b521eA.js → projects-list-KQgHFl7X.js} +1 -1
  117. package/dist/client/assets/{registry-utils-CCgmzWkr.js → registry-utils-D9WTBcQy.js} +1 -1
  118. package/dist/client/assets/{resizable-CcAX-qs1.js → resizable-J8Aer48-.js} +1 -1
  119. package/dist/client/assets/{scroll-area-F4PB57Kk.js → scroll-area-DMcUXGPI.js} +1 -1
  120. package/dist/client/assets/{select-CPhIWiJc.js → select-CMUKnHD5.js} +1 -1
  121. package/dist/client/assets/{shell-layout-D9dQPkQK.js → shell-layout-CSqxCJ3A.js} +3 -3
  122. package/dist/client/assets/{spinner-BJo9JKPd.js → spinner-BWmTCne_.js} +1 -1
  123. package/dist/client/assets/{store-invite-BEQkmcfX.js → store-invite-DQVzahJ1.js} +1 -1
  124. package/dist/client/assets/{switch-C7RggtH3.js → switch-C-ipB4wM.js} +1 -1
  125. package/dist/client/assets/{table-GcQdAqoi.js → table-CTqJjnnx.js} +1 -1
  126. package/dist/client/assets/{tasks-B82Xf5C5.js → tasks-DQVfyRle.js} +1 -1
  127. package/dist/client/assets/{textarea-DWFHG2PH.js → textarea-BqR62h0i.js} +1 -1
  128. package/dist/client/assets/{tools-list-BziYrhBQ.js → tools-list-1sYuTCQT.js} +1 -1
  129. package/dist/client/assets/{topbar-portal-DGJkq20l.js → topbar-portal-uY9HhOr1.js} +1 -1
  130. package/dist/client/assets/{typewriter-title-BBGN8eX7.js → typewriter-title-rlX4QtWe.js} +1 -1
  131. package/dist/client/assets/{use-binding-C4vpH74C.js → use-binding-CBFm-KJH.js} +1 -1
  132. package/dist/client/assets/{use-connection-BWi2Db6r.js → use-connection-TBbvY88o.js} +1 -1
  133. package/dist/client/assets/{use-create-virtual-mcp-CccQ7wjf.js → use-create-virtual-mcp-DkEEEEVB.js} +1 -1
  134. package/dist/client/assets/{use-deco-chat-open-B9pKJybL.js → use-deco-chat-open-B3MDOzNO.js} +1 -1
  135. package/dist/client/assets/{use-install-from-registry-CNEIPsot.js → use-install-from-registry-CanzeI6m.js} +1 -1
  136. package/dist/client/assets/{use-list-state-D5f0NwUO.js → use-list-state-CB60FBzS.js} +1 -1
  137. package/dist/client/assets/{use-llm-DYhOWhPI.js → use-llm-D5XtsGft.js} +1 -1
  138. package/dist/client/assets/{use-mcp-prompts-CH0-e-U1.js → use-mcp-prompts-DdiPSE2K.js} +1 -1
  139. package/dist/client/assets/{use-mcp-tools-Yi0eODm2.js → use-mcp-tools-DreUeH6b.js} +1 -1
  140. package/dist/client/assets/{use-mobile-mUe1k1NH.js → use-mobile-C8iqPQJB.js} +1 -1
  141. package/dist/client/assets/{use-organization-settings-ZMMNYlgW.js → use-organization-settings-BjgTdt4t.js} +1 -1
  142. package/dist/client/assets/{use-project-C8eld6R6.js → use-project-kGpYxwPL.js} +1 -1
  143. package/dist/client/assets/{use-virtual-mcp-C7qHxpwx.js → use-virtual-mcp-C7Kk1mBJ.js} +1 -1
  144. package/dist/client/assets/useInfiniteQuery-XNPJlDVU.js +1 -0
  145. package/dist/client/assets/{useMutation-Bmfdf_Yk.js → useMutation-Bm-DrAfF.js} +1 -1
  146. package/dist/client/assets/useQuery-DM_qidpz.js +1 -0
  147. package/dist/client/assets/{view-mode-toggle-BseoteE9.js → view-mode-toggle-a-_OzLvE.js} +1 -1
  148. package/dist/client/assets/{workflow-DK9VwlEt.js → workflow-Q7ys8Pux.js} +1 -1
  149. package/dist/client/index.html +1 -1
  150. package/dist/server/cli.js +1 -1
  151. package/dist/server/migrate.js +1 -1
  152. package/dist/server/server.js +1 -1
  153. package/package.json +1 -1
  154. package/dist/client/assets/constants-9Txgq7Bp.js +0 -1
  155. package/dist/client/assets/useInfiniteQuery-B1egfGHi.js +0 -1
  156. package/dist/client/assets/useQuery-DoLjDGJT.js +0 -1
@@ -1349,7 +1349,7 @@ ${Y.stack}`;return Q}if(typeof Y==="object"&&Y!==null){let Q=Y,X="";if(typeof Q.
1349
1349
  ${Q.stack}`;return X}try{let G=JSON.stringify(Q,null,2);if(G!=="{}"&&G.length<1000){if(typeof Q.stack==="string"&&Q.stack&&Q.stack.length<2000)return`${G}
1350
1350
 
1351
1351
  Stack trace:
1352
- ${Q.stack}`;return G}}catch{}if(typeof Q.toString==="function")try{let G=Q.toString();if(G!=="[object Object]")return G}catch{}let J=Object.keys(Q);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 CO(Y,Q){switch(typeof Q){case"string":return Y.newString(Q);case"number":return Y.newNumber(Q);case"boolean":return Q?Y.true:Y.false;case"undefined":return Y.undefined;case"object":{if(Q===null)return Y.null;if(Array.isArray(Q)){let J=Y.newArray();return Q.forEach((G,K)=>{let W=CO(Y,G);try{Y.setProp(J,String(K),W)}finally{W.dispose?.()}}),J}let X=Y.newObject();for(let[J,G]of Object.entries(Q)){let K=CO(Y,G);try{Y.setProp(X,J,K)}finally{K.dispose?.()}}return X}case"function":{let X=`__hostFn_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return Y.newFunction(X,(...G)=>{try{let K=G.map((Z)=>Y.dump(Z)),W=Q(...K);if(W&&typeof W.then==="function"){let Z=Y.newPromise();return W.then((H)=>{try{let F=CO(Y,H);Z.resolve(F),F.dispose()}catch(F){let q=TO(F),V=Y.newString(`Promise resolution error: ${q}`);Z.reject(V),V.dispose()}finally{Y.runtime.executePendingJobs()}}).catch((H)=>{let F=TO(H),q=Y.newString(`Promise rejection: ${F}`);Z.reject(q),q.dispose(),Y.runtime.executePendingJobs()}),Z.handle}return CO(Y,W)}catch(K){let W=TO(K);return Y.newString(`HostFunctionError: ${W}`)}finally{G.forEach((K)=>K.dispose())}})}case"bigint":return Y.newString(Q.toString());case"symbol":return Y.newString(Q.toString());default:try{return Y.newString(String(Q))}catch{return Y.undefined}}}var Sw0=()=>{};function kw0(Y){let Q=Y.runtime.executePendingJobs(100);try{if("unwrap"in Q&&typeof Q.unwrap==="function")Q.unwrap()}finally{if("dispose"in Q&&typeof Q.dispose==="function")Q.dispose()}}async function vw0(Y,Q,X){let J=Date.now(),G=Y.resolvePromise(Q);while(!0){kw0(Y);let K=await Promise.race([G,yX4(0).then(()=>null)]);if(K!==null)return K;if(Date.now()-J>X)throw Error(`Timed out after ${X}ms while awaiting a QuickJS promise`)}}async function tE({tools:Y,code:Q,timeoutMs:X}){let W=[];try{const J=wT(W,await Rw0({memoryLimitBytes:33554432,stackSizeBytes:524288}),0);const G=wT(W,J.newContext({interruptAfterMs:X}),0);const K=wT(W,Ew0(G),0);try{let q=G.evalCode(Q,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(q),$=CO(G,Y);G.setProp(G.global,"tools",$);let z=G.runtime.hasPendingJob()?G.unwrapResult(await vw0(G,V,X)):V;if(z!==V)V.dispose();let O=G.getProp(z,"default"),L=G.typeof(O);if(L!=="function")return O.dispose(),z.dispose(),$.dispose(),{error:`Code must export default a function (tools). Got ${L}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:K.logs};let M=G.callFunction(O,G.undefined,$);$.dispose(),O.dispose(),z.dispose();let w=G.unwrapResult(M),I=await vw0(G,w,X);w.dispose();let j=G.unwrapResult(I);if(G.runtime.hasPendingJob())kw0(G);let C=G.dump(j);return j.dispose(),{returnValue:C,consoleLogs:K.logs}}catch(q){return console.log(q),{error:TO(q),consoleLogs:K.logs}}}catch(Z){var H=Z,F=1}finally{vZ1(W,H,F)}}var yX4=(Y)=>new Promise((Q)=>setTimeout(Q,Y));var _w0=v(()=>{jw0();Sw0()});var ZW1=v(()=>{_w0()});async function fX4(Y,Q){let X=Y.connections.map((K)=>K.connection_id),J=[];for(let K of X){let W=await Q.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 yw0(Y,Q){return(await Q.storage.connections.list(Y)).filter((J)=>J.status==="active").map((J)=>({connection:J,selectedTools:null,selectedResources:null,selectedPrompts:null}))}async function hX4(Y,Q){let X=new Map;for(let $ of Y)X.set($.connection.id,$);let J=Y.map(($)=>$.connection),G=new Map,K=await Promise.allSettled(J.map(async($)=>{try{let z=await Q.createMCPProxy($);return{connection:$,proxy:z}}catch(z){return console.warn(`[code-execution] Failed to create proxy for connection ${$.id}:`,z),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([$,z])=>{try{let L=(await z.proxy.listTools()).tools,M=X.get($);if(M?.selectedTools&&M.selectedTools.length>0){let w=new Set(M.selectedTools);L=L.filter((I)=>w.has(I.name))}return{connectionId:$,connectionTitle:z.connection.title,tools:L}}catch(O){return console.error(`[code-execution] Failed to list tools for connection ${$}:`,O),null}})),Z=new Set,H=[],F=new Map;for(let $ of W){if($.status!=="fulfilled"||!$.value)continue;let{connectionId:z,connectionTitle:O,tools:L}=$.value;for(let M of L){if(Z.has(M.name))continue;Z.add(M.name),H.push({...M,_meta:{connectionId:z,connectionTitle:O}}),F.set(M.name,z)}}let q=async($,z)=>{let O=F.get($);if(!O)return{content:[{type:"text",text:`Tool not found: ${$}`}],isError:!0};let L=G.get(O);if(!L)return{content:[{type:"text",text:`Connection not found for tool: ${$}`}],isError:!0};return await L.proxy.callTool({name:$,arguments:z})},V=[];for(let[,$]of G)V.push($.proxy.close().catch(()=>{}));return await Promise.all(V),{tools:H,callTool:q}}async function IO(Y){let Q=N0(Y),X;if(Y.connectionId){let J=await Y.storage.virtualMcps.findById(Y.connectionId,Y.organization?.id);if(J)X=await fX4(J,Y);else X=await yw0(Q.id,Y)}else X=await yw0(Q.id,Y);return hX4(X,Y)}function bX4(Y){return Y.toLowerCase().split(/[\s_\-./]+/).filter((Q)=>Q.length>=2)}function xX4(Y,Q){let X=0,J=Q.name.toLowerCase(),G=(Q.description??"").toLowerCase(),K=(Q._meta?.connectionTitle??"").toLowerCase();for(let W of Y){if(J===W)X+=10;else if(J.includes(W))X+=3;if(G.includes(W))X+=2;if(K.includes(W))X+=1}return X}function Wg(Y,Q,X){let J=bX4(Y);if(J.length===0)return Q.slice(0,X);return Q.map((G)=>({tool:G,score:xX4(J,G)})).filter((G)=>G.score>0).sort((G,K)=>K.score-G.score).slice(0,X).map((G)=>G.tool)}function Zg(Y,Q){let X=new Map(Q.map((G)=>[G.name,G]));return{tools:Y.map((G)=>X.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)=>!X.has(G))}}async function Kg(Y,Q,X){let J=Object.fromEntries(Q.tools.map((G)=>[G.name,async(K)=>Q.callTool(G.name,K??{})]));return tE({code:Y,tools:J,timeoutMs:X})}function eE(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}]}}function QF(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}],isError:!0}}function S3(Y){let Q=new Set(uX4);return Y.filter((X)=>!Q.has(X.name))}var uX4;var P$=v(()=>{ZW1();uX4=["CODE_EXECUTION_SEARCH_TOOLS","CODE_EXECUTION_DESCRIBE_TOOLS","CODE_EXECUTION_RUN_CODE"]});var KW1;var fw0=v(()=>{x0();sE();P$();KW1=u1({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:Lw0,outputSchema:Nw0,handler:async(Y,Q)=>{d1(Q),N0(Q),await Q.access.check();let X=await IO(Q),J=Wg(Y.query,X.tools,Y.limit);return{query:Y.query,results:J.map((G)=>({name:G.name,description:G.description,connection:G._meta?.connectionTitle??""})),totalAvailable:X.tools.length}}})});var HW1;var hw0=v(()=>{x0();sE();P$();HW1=u1({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:Mw0,outputSchema:ww0,handler:async(Y,Q)=>{d1(Q),N0(Q),await Q.access.check();let X=await IO(Q);return Zg(Y.tools,X.tools)}})});var FW1;var bw0=v(()=>{x0();sE();P$();FW1=u1({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:Pw0,outputSchema:Aw0,handler:async(Y,Q)=>{d1(Q),N0(Q),await Q.access.check();let X=await IO(Q);return await Kg(Y.code,X,Y.timeoutMs)}})});var xw0=v(()=>{fw0();hw0();bw0();sE()});var mX4,lX4,qW1;var uw0=v(()=>{x5();l1();x0();ex();z3();mX4=D.object({data:OM.describe("Data for the new connection (id is auto-generated if not provided)")}),lX4=D.object({item:rQ.describe("The created connection entity")}),qW1=u1({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",inputSchema:mX4,outputSchema:lX4,handler:async(Y,Q)=>{d1(Q);let X=N0(Q);await Q.access.check();let J=X9(Q);if(!J)throw Error("User ID required to create connection");let G={...Y.data,organization_id:X.id,created_by:J};if(G.connection_type==="VIRTUAL"){let H=sF(G.connection_url);if(!H)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let F=await Q.storage.virtualMcps.findById(H);if(!F)throw Error(`Virtual MCP not found: ${H}`);if(F.organization_id!==X.id)throw Error("Virtual MCP does not belong to the current organization");G.connection_url=tF(H)}let K=await XO({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 Q.storage.connections.create({...G,tools:W});return await Q.eventBus.publish(X.id,OX.SELF(X.id),{type:"connection.created",data:Z}),{item:Z}}})});var dX4,gw0,iz8;var mw0=v(()=>{l1();nX();dX4=D.object({id:D.string(),name:D.string(),description:D.string().optional(),inputSchema:D.record(D.string(),D.unknown()),outputSchema:D.record(D.string(),D.unknown()).optional()}),gw0=yW.extend({_meta:D.object({"io.decocms":D.object({id:D.string(),verified:D.boolean(),scopeName:D.string(),appName:D.string(),friendlyName:D.string().nullable().optional(),metadata:D.record(D.string(),D.unknown()).nullable().optional(),publishedAt:D.string().datetime().optional(),updatedAt:D.string().datetime().optional(),tools:D.array(dX4).nullable().optional().describe("Available tools exposed by this app")}).optional()}).optional(),server:D.object({$schema:D.string().optional(),_meta:D.record(D.string(),D.unknown()).optional(),name:D.string().describe("The server name (scope/app)"),title:D.string().optional().describe("User-friendly title"),description:D.string().optional().describe("Server description"),icons:D.array(D.object({src:D.string(),mimeType:D.string().optional(),sizes:D.array(D.string()).optional(),theme:D.enum(["light","dark"]).optional()})).optional(),remotes:D.array(D.object({type:D.enum(["http","stdio","sse"]),url:D.string().optional(),headers:D.array(D.unknown()).optional()})).optional(),packages:D.array(D.unknown()).optional(),repository:D.object({url:D.string(),source:D.string().optional(),subfolder:D.string().optional()}).optional(),version:D.string().optional(),websiteUrl:D.string().optional()})}),iz8=fW("registry_app",gw0,{readOnly:!0})});var lw0,dw0,pw0,cw0,nw0,pX4;var iw0=v(()=>{l1();JO();lw0=D.object({specversion:D.literal("1.0").describe("CloudEvents specification version"),id:D.string().describe("Unique identifier for this event (UUID recommended)"),source:D.string().describe("Connection ID of the event publisher"),type:D.string().describe("Event type (e.g., 'order.created', 'user.signup')"),time:D.string().datetime().optional().describe("Timestamp of when the event occurred (ISO 8601)"),subject:D.string().optional().describe("Subject/resource identifier (e.g., order ID, user ID)"),datacontenttype:D.string().optional().default("application/json").describe("Content type of the data attribute"),dataschema:D.string().url().optional().describe("URI to the schema for the data attribute"),data:D.unknown().optional().describe("Event payload (any JSON value)")}),dw0=D.object({events:D.array(lw0).min(1).describe("Batch of CloudEvents to process")}),pw0=D.object({success:D.boolean().optional().describe("Whether this event was processed successfully"),error:D.string().optional().describe("Error message for this event"),retryAfter:D.number().int().positive().optional().describe("Re-deliver this event after this many ms")}),cw0=D.object({success:D.boolean().optional().describe("Batch success - applies to events not in results"),error:D.string().optional().describe("Batch error message - applies to events not in results"),processedCount:D.number().int().min(0).optional().describe("Number of events successfully processed"),retryAfter:D.number().int().positive().optional().describe("Batch retryAfter - applies to events not in results"),results:D.record(D.string(),pw0).optional().describe("Per-event results keyed by event ID")}),nw0=[{name:"ON_EVENTS",inputSchema:dw0,outputSchema:cw0}],pX4=D3(nw0)});var YT,QT,XT,JT,aw0,rw0,GT,WT,ZT,KT,HT,FT,qT,VT,ow0,cX4;var sw0=v(()=>{l1();JO();YT=D.object({type:D.string().min(1).max(255).describe("Event type identifier"),subject:D.string().max(255).optional().describe("Subject/resource identifier (e.g., order ID)"),data:D.unknown().optional().describe("Event payload"),deliverAt:D.string().datetime().optional().describe("Scheduled delivery time (ISO 8601). Omit for immediate delivery."),cron:D.string().max(100).optional().describe("Cron expression for recurring delivery. Use EVENT_CANCEL to stop.")}),QT=D.object({id:D.string().describe("Unique event ID"),type:D.string().describe("Event type"),source:D.string().describe("Source connection ID"),time:D.string().describe("Event timestamp")}),XT=D.object({eventType:D.string().min(1).max(255).describe("Event type to subscribe to"),publisher:D.string().optional().describe("Filter events by publisher connection ID"),filter:D.string().max(1000).optional().describe("JSONPath filter expression on event data")}),JT=D.object({subscription:D.object({id:D.string().describe("Subscription ID"),connectionId:D.string().describe("Subscriber connection ID"),eventType:D.string().describe("Event type pattern"),publisher:D.string().nullable().describe("Publisher connection filter"),filter:D.string().nullable().describe("JSONPath filter expression"),enabled:D.boolean().describe("Whether subscription is enabled"),createdAt:D.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:D.string().datetime().describe("Updated timestamp (ISO 8601)")})}),aw0=D.object({eventType:D.string().min(1).max(255).describe("Event type to subscribe to"),publisher:D.string().optional().describe("Filter events by publisher connection ID"),filter:D.string().max(1000).optional().describe("JSONPath filter expression on event data")}),rw0=D.object({id:D.string().describe("Subscription ID"),connectionId:D.string().describe("Subscriber connection ID"),eventType:D.string().describe("Event type pattern"),publisher:D.string().nullable().describe("Publisher connection filter"),filter:D.string().nullable().describe("JSONPath filter expression"),enabled:D.boolean().describe("Whether subscription is enabled"),createdAt:D.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:D.string().datetime().describe("Updated timestamp (ISO 8601)")}),GT=D.object({subscriptions:D.array(aw0).describe("Desired subscriptions - system will create/update/delete to match")}),WT=D.object({created:D.number().int().min(0).describe("Number of subscriptions created"),updated:D.number().int().min(0).describe("Number of subscriptions with filter updated"),deleted:D.number().int().min(0).describe("Number of subscriptions removed"),unchanged:D.number().int().min(0).describe("Number of subscriptions unchanged"),subscriptions:D.array(rw0).describe("Current subscriptions after sync")}),ZT=D.object({subscriptionId:D.string().describe("Subscription ID to remove")}),KT=D.object({success:D.boolean().describe("Whether unsubscribe was successful"),subscriptionId:D.string().describe("Subscription ID that was removed")}),HT=D.object({eventId:D.string().describe("Event ID to cancel")}),FT=D.object({success:D.boolean().describe("Whether cancellation was successful"),eventId:D.string().describe("Event ID that was cancelled")}),qT=D.object({eventId:D.string().describe("Event ID to acknowledge")}),VT=D.object({success:D.boolean().describe("Whether ACK was successful"),eventId:D.string().describe("Event ID that was acknowledged")}),ow0=[{name:"EVENT_PUBLISH",inputSchema:YT,outputSchema:QT},{name:"EVENT_SUBSCRIBE",inputSchema:XT,outputSchema:JT},{name:"EVENT_UNSUBSCRIBE",inputSchema:ZT,outputSchema:KT},{name:"EVENT_CANCEL",inputSchema:HT,outputSchema:FT},{name:"EVENT_ACK",inputSchema:qT,outputSchema:VT},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:GT,outputSchema:WT}],cX4=D3(ow0)});var nX4,iX4,aX4,rX4,oX4,sX4,tX4,eX4,YJ4,QJ4,XJ4,JJ4,$T;var Hg=v(()=>{l1();nX4=D.object({prefix:D.string().optional().describe("Filter objects by prefix (e.g., 'folder/' for folder contents)"),maxKeys:D.number().optional().default(1000).describe("Maximum number of keys to return (default: 1000)"),continuationToken:D.string().optional().describe("Token for pagination from previous response"),delimiter:D.string().optional().describe("Delimiter for grouping keys (typically '/'). When set, commonPrefixes returns folder paths.")}),iX4=D.object({objects:D.array(D.object({key:D.string().describe("Object key/path"),size:D.number().describe("Object size in bytes"),lastModified:D.string().describe("Last modified timestamp"),etag:D.string().describe("Entity tag for the object")})),nextContinuationToken:D.string().optional().describe("Token for fetching next page of results"),isTruncated:D.boolean().describe("Whether there are more results available"),commonPrefixes:D.array(D.string()).optional().describe("Folder paths when delimiter is used (e.g., ['photos/2024/', 'photos/2025/'])")}),aX4=D.object({key:D.string().describe("Object key/path to get metadata for")}),rX4=D.object({contentType:D.string().optional().describe("MIME type of the object"),contentLength:D.number().describe("Size of the object in bytes"),lastModified:D.string().describe("Last modified timestamp"),etag:D.string().describe("Entity tag for the object"),metadata:D.record(D.string(),D.string()).optional().describe("Custom metadata key-value pairs")}),oX4=D.object({key:D.string().describe("Object key/path to generate URL for"),expiresIn:D.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)")}),sX4=D.object({url:D.string().describe("Presigned URL for downloading the object"),expiresIn:D.number().describe("Expiration time in seconds that was used")}),tX4=D.object({key:D.string().describe("Object key/path for the upload"),expiresIn:D.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)"),contentType:D.string().optional().describe("MIME type for the object being uploaded")}),eX4=D.object({url:D.string().describe("Presigned URL for uploading the object"),expiresIn:D.number().describe("Expiration time in seconds that was used")}),YJ4=D.object({key:D.string().describe("Object key/path to delete")}),QJ4=D.object({success:D.boolean().describe("Whether the deletion was successful"),key:D.string().describe("The key that was deleted")}),XJ4=D.object({keys:D.array(D.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),JJ4=D.object({deleted:D.array(D.string()).describe("Array of successfully deleted keys"),errors:D.array(D.object({key:D.string(),message:D.string()})).describe("Array of errors for failed deletions")}),$T=[{name:"LIST_OBJECTS",inputSchema:nX4,outputSchema:iX4},{name:"GET_OBJECT_METADATA",inputSchema:aX4,outputSchema:rX4},{name:"GET_PRESIGNED_URL",inputSchema:oX4,outputSchema:sX4},{name:"PUT_PRESIGNED_URL",inputSchema:tX4,outputSchema:eX4},{name:"DELETE_OBJECT",inputSchema:YJ4,outputSchema:QJ4},{name:"DELETE_OBJECTS",inputSchema:XJ4,outputSchema:JJ4}]});var VW1=v(()=>{JO();mw0();iw0();sw0();Hg();GO()});var GJ4,WJ4,tw0;var ew0=v(()=>{l1();nX();GJ4=yW.extend({avatar:D.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:D.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:D.string().describe("Virtual MCP ID to use for this assistant"),model:D.object({id:D.string().describe("Model ID"),connectionId:D.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),WJ4=fW("assistant",GJ4),tw0=[...WJ4]});var zT,v3,QP0,ZJ4,KJ4,XP0,HJ4,FJ4,qJ4,VJ4,$J4,zJ4,JP0,BJ4,UJ4,DJ4,OJ4,LJ4,NJ4,MJ4,wJ4,PJ4,AJ4,LB8,EJ4,NB8,YP0,TJ4,CJ4,$W1,MB8;var GP0=v(()=>{l1();JO();nX();zT=D.lazy(()=>D.union([D.null(),D.string(),D.number(),D.boolean(),D.record(D.string(),zT),D.array(zT)])),v3=D.record(D.string(),D.record(D.string(),zT)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),QP0=D.object({type:D.literal("text"),text:D.string().describe("The text content"),providerOptions:v3}),ZJ4=D.object({type:D.literal("text"),text:D.string().describe("The text content"),providerMetadata:D.any().optional().describe("Additional provider-specific metadata")}),KJ4=D.string().describe("File data as URL string"),XP0=D.object({type:D.literal("file"),filename:D.string().optional().describe("Optional filename of the file"),data:KJ4,mediaType:D.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:v3}),HJ4=D.object({type:D.literal("file"),mediaType:D.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:D.string().describe("Generated file data as base64 encoded string")}),FJ4=D.object({type:D.literal("reasoning"),text:D.string().describe("The reasoning text"),providerOptions:v3}),qJ4=D.object({type:D.literal("reasoning"),text:D.string().describe("The reasoning text"),providerMetadata:D.any().optional().describe("Additional provider-specific metadata")}),VJ4=D.object({type:D.literal("tool-call"),toolCallId:D.string().describe("ID of the tool call, used to match with tool result"),toolName:D.string().describe("Name of the tool being called"),input:D.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:D.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:v3}),$J4=D.object({type:D.literal("tool-call"),toolCallId:D.string().describe("ID of the tool call"),toolName:D.string().describe("Name of the tool being called"),input:D.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:D.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:D.any().optional().describe("Additional provider-specific metadata")}),zJ4=D.union([D.object({type:D.literal("text"),value:D.string()}),D.object({type:D.literal("json"),value:zT}),D.object({type:D.literal("error-text"),value:D.string()}),D.object({type:D.literal("error-json"),value:zT}),D.object({type:D.literal("content"),value:D.array(D.union([D.object({type:D.literal("text"),text:D.string().describe("Text content")}),D.object({type:D.literal("media"),data:D.string().describe("Base-64 encoded media data"),mediaType:D.string().describe("IANA media type")})]))})]),JP0=D.object({type:D.literal("tool-result"),toolCallId:D.string().describe("ID of the tool call that this result is associated with"),toolName:D.string().describe("Name of the tool that generated this result"),output:zJ4.describe("Result of the tool call"),result:D.unknown().describe("Unknown result of the tool call"),providerOptions:v3}),BJ4=D.object({type:D.literal("tool-result"),toolCallId:D.string().describe("ID of the tool call that this result is associated with"),toolName:D.string().describe("Name of the tool that generated this result"),result:D.any().describe("Result of the tool call (JSON-serializable)"),isError:D.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:D.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:D.any().optional().describe("Additional provider-specific metadata")}),UJ4=D.union([D.object({type:D.literal("source"),sourceType:D.literal("url"),id:D.string().describe("The ID of the source"),url:D.string().describe("The URL of the source"),title:D.string().optional().describe("The title of the source"),providerMetadata:D.any().optional().describe("Additional provider-specific metadata")}),D.object({type:D.literal("source"),sourceType:D.literal("document"),id:D.string().describe("The ID of the source"),mediaType:D.string().describe("IANA media type of the document (e.g., application/pdf)"),title:D.string().describe("The title of the document"),filename:D.string().optional().describe("Optional filename of the document"),providerMetadata:D.any().optional().describe("Additional provider-specific metadata")})]),DJ4=D.object({role:D.literal("system"),content:D.string().describe("System message content"),providerOptions:v3}),OJ4=D.object({role:D.literal("user"),content:D.array(D.union([QP0,XP0])).describe("User message content parts (text or file)"),providerOptions:v3}),LJ4=D.object({role:D.literal("assistant"),content:D.array(D.union([QP0,XP0,FJ4,VJ4,JP0])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:v3}),NJ4=D.object({role:D.literal("tool"),content:D.array(JP0).describe("Tool message content (tool results)"),providerOptions:v3}),MJ4=D.union([DJ4,OJ4,LJ4,NJ4]),wJ4=D.array(MJ4).describe("A list of messages forming the prompt"),PJ4=D.object({prompt:wJ4.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:D.number().optional().describe("Maximum number of tokens to generate"),temperature:D.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:D.number().optional().describe("Nucleus sampling parameter"),topK:D.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:D.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:D.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:D.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:D.array(D.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:D.union([D.object({type:D.literal("text")}),D.object({type:D.literal("json"),schema:D.any().optional().describe("JSON schema that the generated output should conform to"),name:D.string().optional().describe("Name of output that should be generated"),description:D.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:D.array(D.any()).optional().describe("The tools that are available for the model"),toolChoice:D.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:D.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:D.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:D.any().optional().describe("Additional provider-specific options")}),AJ4=D.object({content:D.array(D.union([ZJ4,HJ4,qJ4,$J4,BJ4,UJ4])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:D.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:D.looseObject({inputTokens:D.number().optional(),outputTokens:D.number().optional(),totalTokens:D.number().optional(),reasoningTokens:D.number().optional()}).describe("Usage information for the language model call"),providerMetadata:D.any().optional().describe("Additional provider-specific metadata"),request:D.object({body:D.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:D.object({id:D.string().optional().describe("ID for the generated response"),timestamp:D.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:D.string().optional().describe("The ID of the response model that was used"),headers:D.record(D.string(),D.string()).optional().describe("Response headers"),body:D.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:D.array(D.any()).describe("Warnings for the call, e.g. unsupported settings")}),LB8=D.object({stream:D.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:D.object({body:D.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:D.object({headers:D.record(D.string(),D.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),EJ4=D.object({supportedUrls:D.record(D.string(),D.array(D.string())).describe("Supported URL patterns by media type for the provider")}),NB8=D.object({modelId:D.string().describe("The ID of the model"),logo:D.string().nullable(),description:D.string().nullable(),capabilities:D.array(D.string()),limits:D.object({contextWindow:D.number(),maxOutputTokens:D.number()}).nullable(),costs:D.object({input:D.number(),output:D.number()}).nullable(),provider:D.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),YP0=D.object({modelId:D.string().describe("The ID of the model"),callOptions:PJ4}),TJ4=yW.extend({logo:D.string().nullable(),description:D.string().nullable(),capabilities:D.array(D.string()),limits:D.object({contextWindow:D.number(),maxOutputTokens:D.number()}).nullable(),costs:D.object({input:D.number(),output:D.number()}).nullable(),provider:D.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),CJ4=fW("llm",TJ4,{readOnly:!0}),$W1=[{name:"LLM_METADATA",inputSchema:D.object({modelId:D.string().describe("The ID of the model")}),outputSchema:EJ4},{name:"LLM_DO_STREAM",inputSchema:YP0,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:YP0,outputSchema:AJ4},...CJ4],MB8=D3($W1)});function RO(){return!1}function Fg(Y,Q){return Y===OX.DEV_ASSETS(Q)}function jO(Y,Q){let X=Na(Q,Y),J=new Date().toISOString();return{id:X.id??OX.DEV_ASSETS(Y),title:X.title,description:X.description??null,icon:X.icon??null,app_name:X.app_name??null,app_id:X.app_id??null,organization_id:Y,created_by:"system",created_at:J,updated_at:J,connection_type:X.connection_type,connection_url:X.connection_url??null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:X.metadata??null,tools:IJ4,bindings:["OBJECT_STORAGE"],status:"active"}}var IJ4;var qg=v(()=>{Hg();x5();l1();IJ4=$T.map((Y)=>({name:Y.name,description:`${Y.name} operation for local file storage`,inputSchema:D.toJSONSchema(Y.inputSchema),outputSchema:D.toJSONSchema(Y.outputSchema)}))});function jJ4(Y){let Q=[],X=0;while(X<Y.length){let J=Y[X];if(J==="%")Q.push(".*");else if(J==="_")Q.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))Q.push("\\"+J);else Q.push(J);X++}return Q.join("")}function XF(Y){return typeof Y==="string"||typeof Y==="number"}function Vg(Y,Q){if("conditions"in Q){let{operator:Z,conditions:H}=Q;switch(Z){case"and":return H.every((F)=>Vg(Y,F));case"or":return H.some((F)=>Vg(Y,F));case"not":return!H.every((F)=>Vg(Y,F));default:return!0}}let{field:X,operator:J,value:G}=Q,K=X.join("."),W=zW1(Y,K);switch(J){case"eq":return W===G;case"gt":return XF(W)&&XF(G)&&W>G;case"gte":return XF(W)&&XF(G)&&W>=G;case"lt":return XF(W)&&XF(G)&&W<G;case"lte":return XF(W)&&XF(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=jJ4(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 zW1(Y,Q){let X=Q.split("."),J=Y;for(let G of X){if(J==null||typeof J!=="object")return;J=J[G]}return J}function SJ4(Y,Q){return[...Y].sort((X,J)=>{for(let G of Q){let K=G.field.join("."),W=zW1(X,K),Z=zW1(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 RJ4,vJ4,kJ4,BW1;var WP0=v(()=>{VW1();ew0();nX();GP0();Hg();x5();l1();x0();qg();z3();RJ4={LLM:$W1,ASSISTANTS:tw0,OBJECT_STORAGE:$T};vJ4=O3.extend({binding:D.union([D.object({}).passthrough(),D.string()]).optional(),include_virtual:D.boolean().optional().describe("Whether to include VIRTUAL connections in the results. Defaults to false.")}),kJ4=L3(rQ),BW1=u1({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",inputSchema:vJ4,outputSchema:kJ4,handler:async(Y,Q)=>{await Q.access.check();let X=N0(Q),J=Y.binding?typeof Y.binding==="string"?(()=>{let $=RJ4[Y.binding.toUpperCase()];if(!$)throw Error(`Unknown binding: ${Y.binding}`);return $})():Y.binding:void 0,G=J?Zu(J):void 0,K=await Q.storage.connections.list(X.id,{includeVirtual:Y.include_virtual??!1});if(RO()){let $=h7(),z=OX.DEV_ASSETS(X.id);if(!K.some((O)=>O.id===z)){let O=jO(X.id,$);K.unshift(O)}}let W=G?await Promise.all(K.map(async($)=>{if(!$.tools||$.tools.length===0)return null;return G.isImplementedBy($.tools.map((O)=>({name:O.name,inputSchema:O.inputSchema,outputSchema:O.outputSchema})))?$:null})).then(($)=>$.filter((z)=>z!==null)):K;if(Y.where)W=W.filter(($)=>Vg($,Y.where));if(Y.orderBy&&Y.orderBy.length>0)W=SJ4(W,Y.orderBy);let Z=W.length,H=Y.offset??0,F=Y.limit??100,q=W.slice(H,H+F),V=H+F<Z;return{items:q,totalCount:Z,hasMore:V}}})});var _J4,UW1;var ZP0=v(()=>{nX();x0();qg();z3();_J4=OE(rQ),UW1=u1({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",inputSchema:DE,outputSchema:_J4,handler:async(Y,Q)=>{let X=N0(Q);if(await Q.access.check(),RO()&&Fg(Y.id,X.id))return{item:jO(X.id,h7())};let J=await Q.storage.connections.findById(Y.id);if(!J||J.organization_id!==X.id)return{item:null};return{item:J}}})});var $g=(Y,Q)=>{if(Q===null||Q===void 0)return;let X=Y.replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),J=Q;for(let G of X){if(J===null||J===void 0||typeof J!=="object")return;J=J[G]}return J};function KP0(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])throw Error(`Invalid scope format: ${Y}. Expected format: "KEY::SCOPE"`);return Q}function yJ4(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])return null;return Q}function fJ4(Y){if(typeof Y==="object"&&Y!==null&&"value"in Y){let Q=Y.value;if(typeof Q==="string")return Q}return null}function DW1(Y,Q){let X={};if(!Y||!Q)return X;for(let J of Q){if(J==="*"){X["*"]=["*"];continue}let G=yJ4(J);if(!G)continue;let[K,W]=G,Z=$g(K,Y),H=fJ4(Z);if(H){if(!X[H])X[H]=[];X[H].push(W)}}return X}function HP0(Y,Q){let X=DW1(Y,Q);return new Set(Object.keys(X).filter((J)=>J!=="*"))}var OW1=()=>{};import{randomBytes as hJ4}from"crypto";function bJ4(){if(BT)return BT;let Y=process.env.MESH_JWT_SECRET??T5.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(Y)BT=new TextEncoder().encode(Y);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),BT=new Uint8Array(hJ4(32));return BT}async function FP0(Y,Q="5m"){let X=bJ4();return await new m5(Y).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Q).sign(X)}var BT=null;var qP0=v(()=>{MX();zg()});async function VP0(Y){if(!Y.refreshToken)return{success:!1,error:"No refresh token available"};if(!Y.tokenEndpoint)return{success:!1,error:"No token endpoint available"};if(!Y.clientId)return{success:!1,error:"No client ID available"};try{let Q=new URLSearchParams({grant_type:"refresh_token",refresh_token:Y.refreshToken,client_id:Y.clientId});if(Y.clientSecret)Q.set("client_secret",Y.clientSecret);if(Y.scope)Q.set("scope",Y.scope);let X=await fetch(Y.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Q.toString()});if(!X.ok){let G=await X.text();console.error(`[TokenRefresh] Failed to refresh token: ${X.status}`,G);try{let K=JSON.parse(G);return{success:!1,error:K.error_description||K.error||`Token refresh failed: ${X.status}`}}catch{return{success:!1,error:`Token refresh failed: ${X.status}`}}}let J=await X.json();return{success:!0,accessToken:J.access_token,refreshToken:J.refresh_token||Y.refreshToken,expiresIn:J.expires_in,scope:J.scope}}catch(Q){return console.error("[TokenRefresh] Error refreshing token:",Q),{success:!1,error:Q instanceof Error?Q.message:"Token refresh failed"}}}class UT{db;vault;constructor(Y,Q){this.db=Y;this.vault=Q}async get(Y){let Q=await this.db.selectFrom("downstream_tokens").selectAll().where("connectionId","=",Y).executeTakeFirst();if(!Q)return null;return this.decryptToken(Q)}async upsert(Y){let Q=new Date().toISOString(),X=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:X,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,updatedAt:Q}).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:Q,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint};let Z=pH("dtok");return await K.insertInto("downstream_tokens").values({id:Z,connectionId:Y.connectionId,accessToken:X,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,createdAt:Q,updatedAt:Q}).execute(),{id:Z,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Q,updatedAt:Q,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint}})}async delete(Y){await this.db.deleteFrom("downstream_tokens").where("connectionId","=",Y).execute()}isExpired(Y,Q=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-Q<Date.now()}async decryptToken(Y){let Q=await this.vault.decrypt(Y.accessToken),X=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:Q,refreshToken:X,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Y.createdAt,updatedAt:Y.updatedAt,clientId:Y.clientId,clientSecret:J,tokenEndpoint:Y.tokenEndpoint}}}var LW1=v(()=>{GE()});async function Bg(Y,Q,X){let J=Y.id,G=DW1(Y.configuration_state,Y.configuration_scopes),K=Q.auth.user?.id??Q.auth.apiKey?.userId??(X?Y.created_by:void 0),[W,Z]=K?await FP0({sub:K,user:{id:K},metadata:{state:Y.configuration_state??void 0,meshUrl:process.env.MESH_URL??Q.baseUrl,connectionId:J,organizationId:Q.organization?.id},permissions:G}).then((z)=>[z,null]).catch((z)=>[null,z]):[null,Error("User ID required to issue configuration token")];if(Z)console.error("Failed to issue configuration token:",W);let H=Q.auth.user?.connectionId,F={...H?{"x-caller-id":H}:{},...Q.metadata.wellKnownForwardableHeaders??{},"x-request-id":Q.metadata.requestId},q=null,V=new UT(Q.db,Q.vault),$=await V.get(J);if($){let z=!!$.refreshToken&&!!$.tokenEndpoint;if(V.isExpired($,z?300000:0))if(z){console.log(`[Proxy] Token expired for ${J}, attempting refresh`);let L=await VP0($);if(L.success&&L.accessToken)await V.upsert({connectionId:J,accessToken:L.accessToken,refreshToken:L.refreshToken??$.refreshToken,scope:L.scope??$.scope,expiresAt:L.expiresIn?new Date(Date.now()+L.expiresIn*1000):null,clientId:$.clientId,clientSecret:$.clientSecret,tokenEndpoint:$.tokenEndpoint}),q=L.accessToken,console.log(`[Proxy] Token refreshed for ${J}`);else await V.delete(J),console.error(`[Proxy] Token refresh failed for ${J}: ${L.error}`)}else await V.delete(J),console.log(`[Proxy] Token expired without refresh capability for ${J}`);else q=$.accessToken}if(!q&&Y.connection_token)q=Y.connection_token;if(q)F.Authorization=`Bearer ${q}`;if(W)F["x-mesh-token"]=W;return F}var NW1=v(()=>{OW1();qP0();LW1()});function $P0(){let Y=new Map;function Q(J,G){let K=Y.get(G);if(K)return console.log(`[ClientPool] Reusing cached client for ${G}`),K;console.log(`[ClientPool] Creating new client for ${G}`);let W=new qJ({name:`outbound-client-${G}`,version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});W.onclose=()=>{Y.delete(G)};let Z=W.connect(J,{timeout:30000}).then(()=>W).catch((H)=>{throw Y.delete(G),H});return Y.set(G,Z),Z}return Object.assign(Q,{[Symbol.asyncDispose]:async()=>{let J=[];for(let[G,K]of Y)J.push(K.then((W)=>W.close()).catch((W)=>console.error(`[ClientPool] Error closing client ${G}:`,W)));await Promise.all(J),Y.clear()}})}var zP0=v(()=>{kz()});function BP0(Y){let Q=new FE({command:Y.command,args:Y.args,env:Y.env,cwd:Y.cwd,stderr:"pipe"}),X=Y.name||Y.id,J="\x1B[2m",G="\x1B[0m";return Q.stderr?.on("data",(K)=>{let W=K.toString().trimEnd();if(W)console.error(`${W} \x1B[2m[${X}]\x1B[0m`)}),Q}var UP0=v(()=>{nJ1()});class DT{innerTransport;constructor(Y){this.innerTransport=Y}async start(){return this.innerTransport.onmessage=(Y)=>{this.handleIncomingMessage(Y)},this.innerTransport.onerror=(Y)=>{this.onerror?.(Y)},this.innerTransport.onclose=()=>{this.onclose?.()},this.innerTransport.start()}async send(Y){return this.handleOutgoingMessage(Y)}async close(){return this.innerTransport.close()}async handleOutgoingMessage(Y){return this.innerTransport.send(Y)}handleIncomingMessage(Y){this.onmessage?.(Y)}isRequest(Y){return"method"in Y&&Y.method!==void 0}isResponse(Y){return"result"in Y||"error"in Y&&!("method"in Y)}onmessage;onerror;onclose}function OT(Y,...Q){return Q.reduce((X,J)=>J(X),Y)}var DP0="mcp.mesh";var OP0,MW1,Ug;var wW1=v(()=>{OP0=class OP0 extends Error{constructor(Y){super(Y);this.name="UnauthorizedError"}};MW1=class MW1 extends Error{constructor(Y){super(Y);this.name="ForbiddenError"}};Ug=class Ug{userId;toolName;boundAuth;role;connectionId;getToolMeta;_granted=!1;constructor(Y,Q,X,J,G,K="self",W){this.userId=Q;this.toolName=X;this.boundAuth=J;this.role=G;this.connectionId=K;this.getToolMeta=W}[Symbol.dispose](){this._granted=!1}setToolName(Y){this.toolName=Y}grant(){return this._granted=!0,{[Symbol.dispose]:()=>{this._granted=!1}}}async check(...Y){if(this._granted)return;if(this.toolName?.startsWith("MESH_PUBLIC_")){this.grant();return}if(!this.userId&&!this.boundAuth){if(this.getToolMeta&&await this.isToolPublic()){this.grant();return}throw new OP0("Authentication required. Please provide a valid OAuth token or API key.")}let Q=Y.length>0?Y:this.toolName?[this.toolName]:[];if(Q.length===0)throw new MW1("No resources specified for access check");for(let X of Q)if(await this.checkResource(X)){this.grant();return}throw new MW1(`Access denied to: ${Q.join(", ")}`)}async checkResource(Y){if(!this.userId&&!this.boundAuth)return!1;if(this.role==="admin"||this.role==="owner")return!0;if(!this.boundAuth)return!1;let Q={};if(this.connectionId)Q[this.connectionId]=[Y];return this.boundAuth.hasPermission(Q)}async isToolPublic(){if(this.toolName?.startsWith("MESH_PUBLIC_"))return!0;if(!this.getToolMeta)return!1;try{let Y=await this.getToolMeta();if(!Y)return!1;let X=Y[DP0]?.public_tool;return X===!0||X==="true"}catch{return!1}}granted(){return this._granted}}});var xJ4="mcp.mesh",SO;var LP0=v(()=>{wW1();SO=class SO extends DT{options;cachedToolsMap=null;constructor(Y,Q){super(Y);this.options=Q;if(Q.connection.tools)this.cachedToolsMap=new Map(Q.connection.tools.map((X)=>[X.name,X]))}async handleOutgoingMessage(Y){if(!this.isRequest(Y))return this.innerTransport.send(Y);let Q=Y;if(Q.method==="tools/call")await this.authorizeToolCall(Q),this.stripMetaFromArguments(Q);return this.innerTransport.send(Y)}async authorizeToolCall(Y){if(this.options.superUser)return;let X=Y.params.name,{ctx:J,connection:G}=this.options;if(this.isPublicTool(X))return;if(!J.auth.user?.id&&!J.auth.apiKey?.id)throw Error("Authentication required. Please provide a valid OAuth token or API key.");let K=async()=>{return this.cachedToolsMap?.get(X)?._meta};await new Ug(J.authInstance,J.auth.user?.id??J.auth.apiKey?.userId,X,J.boundAuth,J.auth.user?.role,G.id,K).check(X)}isPublicTool(Y){if(Y.startsWith("MESH_PUBLIC_"))return!0;if(!this.cachedToolsMap)return!1;let Q=this.cachedToolsMap.get(Y);if(!Q?._meta)return!1;return Q._meta[xJ4]?.public_tool===!0}stripMetaFromArguments(Y){let Q=Y.params;if(Q.arguments&&"_meta"in Q.arguments){let{_meta:X,...J}=Q.arguments;Q.arguments=J}}}});function NP0(Y){if(!Y.isError)return;let Q=Y.content;if(!Array.isArray(Q))return;for(let X of Q)if(X&&typeof X==="object"&&"type"in X&&X.type==="text"&&"text"in X&&typeof X.text==="string")return X.text;return}function MP0(Y){if(!Y)return;let Q=Y._meta;if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let X=Q.properties;if(!X||typeof X!=="object"||Array.isArray(X))return;let J={};for(let[G,K]of Object.entries(X))if(typeof K==="string")J[G]=K;return Object.keys(J).length>0?J:void 0}function wP0(Y,Q){if(!Y&&!Q)return;if(!Y)return Q;if(!Q)return Y;return{...Q,...Y}}function PP0(Y){if(Y&&typeof Y==="object"&&!Array.isArray(Y)){let Q=Y,X=Q.structuredContent;if(X&&typeof X==="object"&&!Array.isArray(X))return X;return Q}return{value:Y}}var PW1=v(()=>{x5()});var vO;var AP0=v(()=>{py();PW1();vO=class vO extends DT{options;inflightRequests=new Map;constructor(Y,Q){super(Y);this.options=Q}async handleOutgoingMessage(Y){if(this.isRequest(Y)){let Q=Y;this.onRequestStart(Q)}return this.innerTransport.send(Y)}handleIncomingMessage(Y){if(this.isResponse(Y)){let Q=Y;this.onResponseEnd(Q)}this.onmessage?.(Y)}onRequestStart(Y){let{ctx:Q,connectionId:X}=this.options,J,G;if(Y.method==="tools/call"&&Y.params){let W=Y.params;J=W.name,G=W.arguments}let K;if(Y.method==="tools/call"&&J)K=Q.tracer.startSpan("mcp.proxy.callTool",{attributes:{"connection.id":X,"tool.name":J,"request.id":Q.metadata.requestId,"jsonrpc.id":Y.id,"jsonrpc.method":Y.method}});if(Y.id!==null&&Y.id!==void 0)this.inflightRequests.set(Y.id,{startTime:Date.now(),method:Y.method,toolName:J,toolArguments:G,span:K})}onResponseEnd(Y){if(Y.id===null||Y.id===void 0)return;let Q=this.inflightRequests.get(Y.id);if(!Q)return;let{ctx:X,connectionId:J}=this.options,{startTime:G,method:K,toolName:W,toolArguments:Z,span:H}=Q,F=Date.now()-G;if(this.inflightRequests.delete(Y.id),K!=="tools/call"||!W)return;let q="error"in Y,V=q?Y.error:Y.result,$=q?{content:[{type:"text",text:Y.error?.message||"Unknown error"}],isError:!0}:V;if(X.meter.createHistogram("connection.proxy.duration").record(F,{"connection.id":J,"tool.name":W,status:q?"error":"success"}),q)X.meter.createCounter("connection.proxy.errors").add(1,{"connection.id":J,"tool.name":W,error:Y.error?.message});else X.meter.createCounter("connection.proxy.requests").add(1,{"connection.id":J,"tool.name":W,status:"success"});if(H){if(q&&Y.error)H.recordException(Error(Y.error.message)),H.setAttributes({error:!0,"error.code":Y.error.code,"error.message":Y.error.message});H.end()}this.logToDatabase({toolName:W,toolArguments:Z,result:$,duration:F,isError:Boolean(q)})}async logToDatabase(Y){let{ctx:Q,connectionId:X,connectionTitle:J,virtualMcpId:G}=this.options,{toolName:K,toolArguments:W,result:Z,duration:H,isError:F}=Y;if(!D01().enabled)return;let V=Q.organization?.id;if(!V)return;let $=NP0(Z),z=PP0(Z),O=MP0(W),L=wP0(Q.metadata.properties,O);try{await Q.storage.monitoring.log({organizationId:V,connectionId:X,connectionTitle:J,toolName:K,input:W??{},output:z,isError:F,errorMessage:$,durationMs:H,timestamp:new Date,userId:Q.auth.user?.id||Q.auth.apiKey?.userId||null,requestId:Q.metadata.requestId,userAgent:Q.metadata.userAgent,virtualMcpId:G,properties:L})}catch(M){console.error("[MonitoringTransport] Failed to log to database:",M)}}async close(){for(let Y of this.inflightRequests.values())if(Y.span)Y.span.setAttributes({"transport.closed":!0}),Y.span.end();return this.inflightRequests.clear(),super.close()}}});var EP0=v(()=>{LP0();AP0()});async function TP0(Y,Q,X=!1){let J=Y.id,G=Q.connectionId&&Q.connectionId!==J?Q.connectionId:void 0;switch(Y.connection_type){case"STDIO":{if(process.env.UNSAFE_ALLOW_STDIO_TRANSPORT!=="true")throw Error("STDIO connections are disabled in production. Set UNSAFE_ALLOW_STDIO_TRANSPORT=true to enable.");let K=Y.connection_headers;if(!wG(K))throw Error("STDIO connection missing parameters");let W=BP0({id:J,name:Y.title,command:K.command,args:K.args,env:K.envVars,cwd:K.cwd});return W=OT(W,(Z)=>new SO(Z,{ctx:Q,connection:Y,superUser:X}),(Z)=>new vO(Z,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),uJ4(W,J)}case"HTTP":case"Websocket":{if(!Y.connection_url)throw Error(`${Y.connection_type} connection missing URL`);let K=await Bg(Y,Q,X),W=Y.connection_headers;if(W&&"headers"in W)Object.assign(K,W.headers);let Z=new VK(new URL(Y.connection_url),{requestInit:{headers:K}});return Z=OT(Z,(H)=>new SO(H,{ctx:Q,connection:Y,superUser:X}),(H)=>new vO(H,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),Q.getOrCreateClient(Z,J)}case"SSE":{if(!Y.connection_url)throw Error("SSE connection missing URL");let K=await Bg(Y,Q,X),W=Y.connection_headers;if(W&&"headers"in W)Object.assign(K,W.headers);let Z=new H$(new URL(Y.connection_url),{requestInit:{headers:K}});return Z=OT(Z,(H)=>new SO(H,{ctx:Q,connection:Y,superUser:X}),(H)=>new vO(H,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),Q.getOrCreateClient(Z,J)}default:throw Error(`Unknown connection type: ${Y.connection_type}`)}}var uJ4;var CP0=v(()=>{z3();ox();DM();NW1();zP0();UP0();EP0();uJ4=$P0()});function jP0(Y){if(!Y?._meta)return!1;return typeof Y._meta["mcp.mesh"]?.["tool.fn"]==="string"}function SP0(Y){return Y._meta["mcp.mesh"]["tool.fn"]}var AW1,bU8,gW,IP0,RP0;var JF=v(()=>{l1();AW1=D.object({title:D.string().optional(),readOnlyHint:D.boolean().optional(),destructiveHint:D.boolean().optional(),idempotentHint:D.boolean().optional(),openWorldHint:D.boolean().optional()}),bU8=D.object({"tool.fn":D.string().describe("JavaScript ES module code that exports a default async function")}),gW=D.object({id:D.string().describe("Unique identifier for the virtual tool (auto-generated)"),name:D.string().min(1).max(255).describe("Tool name (must be unique within the Virtual MCP)"),description:D.string().optional().describe("Human-readable description of what the tool does"),inputSchema:D.record(D.string(),D.unknown()).describe("JSON Schema defining the tool's input parameters"),outputSchema:D.record(D.string(),D.unknown()).optional().describe("JSON Schema defining the tool's output (optional)"),annotations:AW1.optional().describe("MCP tool annotations"),code:D.string().describe("JavaScript ES module code. Must export default an async function: export default async (tools, args) => { ... }"),connection_dependencies:D.array(D.string()).describe("Connection IDs that this tool depends on (specified by the creator)"),created_at:D.string().describe("When the virtual tool was created"),updated_at:D.string().describe("When the virtual tool was last updated")}),IP0=D.object({name:D.string().min(1).max(255).describe("Tool name (must be unique within the Virtual MCP)"),description:D.string().optional().describe("Human-readable description"),inputSchema:D.record(D.string(),D.unknown()).describe("JSON Schema defining the tool's input parameters"),outputSchema:D.record(D.string(),D.unknown()).optional().describe("JSON Schema for output"),annotations:AW1.optional().describe("MCP tool annotations"),code:D.string().describe("JavaScript ES module code. Must export default an async function: export default async (tools, args) => { ... }"),connection_dependencies:D.array(D.string()).optional().describe("Connection IDs that this tool depends on. Creates indirect aggregations to prevent deletion of referenced connections.")}),RP0=D.object({name:D.string().min(1).max(255).optional().describe("New tool name"),description:D.string().nullable().optional().describe("New description (null to clear)"),inputSchema:D.record(D.string(),D.unknown()).optional().describe("New input schema"),outputSchema:D.record(D.string(),D.unknown()).nullable().optional().describe("New output schema (null to clear)"),annotations:AW1.nullable().optional().describe("New annotations (null to clear)"),code:D.string().optional().describe("New JavaScript code"),connection_dependencies:D.array(D.string()).optional().describe("Connection IDs that this tool depends on. Replaces existing dependencies if provided.")})});function Dg(Y){return(Q)=>{if(Q instanceof O0&&Q.code===P0.MethodNotFound)return Y;throw Q}}var EW1=v(()=>{lY()});class vP0{factory;promise=null;constructor(Y){this.factory=Y}getOrCreatePromise(){if(!this.promise)this.promise=this.factory();return this.promise}then(Y,Q){return this.getOrCreatePromise().then(Y,Q)}catch(Y){return this.getOrCreatePromise().catch(Y)}finally(Y){return this.getOrCreatePromise().finally(Y)}}function LT(Y){return new vP0(Y)}async function gJ4(Y,Q,X=!1){let J=await Promise.all(Y.map(async(G)=>{try{let K=await _O(G,Q,X);return[G.id,K]}catch(K){return console.warn(`[aggregator] Failed to create client for connection ${G.id}:`,K),null}}));return new Map(J.filter((G)=>!!G))}async function kP0(Y){let Q=[];for(let[,X]of Y)Q.push(X.close().catch(()=>{}));await Promise.all(Q)}var kO;var TW1=v(()=>{CW1();EW1();kz();ZW1();JF();kO=class kO extends qJ{options;ctx;_cachedTools;_cachedResources;_cachedPrompts;_clients;_connections;_selectionMap;constructor(Y,Q){super({name:"virtual-mcp-passthrough",version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});this.options=Y;this.ctx=Q;this._selectionMap=new Map;for(let X of Y.virtualMcp.connections)this._selectionMap.set(X.connection_id,X);this._connections=new Map;for(let X of Y.connections)this._connections.set(X.id,X);this._clients=LT(()=>gJ4(this.options.connections,this.ctx,this.options.superUser)),this._cachedTools=LT(()=>this.loadToolsCache()),this._cachedResources=LT(()=>this.loadCache("resources")),this._cachedPrompts=LT(()=>this.loadCache("prompts"))}async loadToolsCache(){let Y=await this._clients,Q=await Promise.all(Array.from(Y.entries()).map(async([W,Z])=>{try{let H=await Z.listTools().then((q)=>q.tools),F=this._selectionMap.get(W);if(F?.selected_tools?.length){let q=new Set(F.selected_tools);H=H.filter((V)=>q.has(V.name))}return{connectionId:W,data:H}}catch(H){return console.error(`[PassthroughClient] Failed to load tools for connection ${W}:`,H),null}})),X=[],J=new Map,G=new Map,K=this.options.virtualTools??[];for(let W of K){if(J.has(W.name))continue;let Z={name:W.name,description:W.description,inputSchema:W.inputSchema,outputSchema:W.outputSchema,annotations:W.annotations,_meta:{connectionId:this.options.virtualMcp.id??"__VIRTUAL__",connectionTitle:this.options.virtualMcp.title}};X.push(Z),J.set(W.name,"__VIRTUAL__"),G.set(W.name,W)}for(let W of Q){if(!W)continue;let{connectionId:Z,data:H}=W,q=this._connections.get(Z)?.title??"";for(let V of H){let $=V.name;if(J.has($))continue;let z={...V,_meta:{connectionId:Z,connectionTitle:q,...V?._meta}};X.push(z),J.set($,Z)}}return{data:X,mappings:J,virtualTools:G}}async loadCache(Y){let Q=await this._clients,X=await Promise.all(Array.from(Q.entries()).map(async([K,W])=>{try{let Z=Y==="resources"?await W.listResources().catch(Dg({resources:[]})).then((q)=>q.resources):await W.listPrompts().catch(Dg({prompts:[]})).then((q)=>q.prompts),H=this._selectionMap.get(K),F=Y==="resources"?"selected_resources":"selected_prompts";if(H?.[F]?.length){let q=new Set(H[F]);return{connectionId:K,data:Z.filter((V)=>q.has(V.name))}}return{connectionId:K,data:Z}}catch(Z){return console.error(`[PassthroughClient] Failed to load cache for connection ${K}:`,Z),null}})),J=[],G=new Map;for(let K of X){if(!K)continue;let{connectionId:W,data:Z}=K,F=this._connections.get(W)?.title??"";for(let q of Z){let V=q.name??q.uri;if(G.has(V))continue;let $={...q,_meta:{connectionId:W,connectionTitle:F,...q?._meta}};J.push($),G.set(V,W)}}return{data:J,mappings:G}}async listTools(){return{tools:(await this._cachedTools).data}}async callTool(Y){let[Q,X]=await Promise.all([this._cachedTools,this._clients]),J=Q.mappings.get(Y.name);if(!J)return{content:[{type:"text",text:`Tool not found: ${Y.name}`}],isError:!0};if(J==="__VIRTUAL__")return this.executeVirtualTool(Y.name,Y.arguments??{},Q,X);let G=X.get(J);if(!G)return{content:[{type:"text",text:`Connection not found for tool: ${Y.name}`}],isError:!0};return await G.callTool({name:Y.name,arguments:Y.arguments??{}})}async executeVirtualTool(Y,Q,X,J){let G=X.virtualTools.get(Y);if(!G)return{content:[{type:"text",text:`Virtual tool not found: ${Y}`}],isError:!0};let K=SP0(G),W={};for(let[Z,H]of X.mappings){if(H==="__VIRTUAL__")continue;let F=J.get(H);if(!F)continue;W[Z]=async(q)=>{let V=await F.callTool({name:Z,arguments:q}),$=V.content;if($?.[0]?.type==="text"&&$[0].text)try{return JSON.parse($[0].text)}catch{return $[0].text}return V}}try{let H=`
1352
+ ${Q.stack}`;return G}}catch{}if(typeof Q.toString==="function")try{let G=Q.toString();if(G!=="[object Object]")return G}catch{}let J=Object.keys(Q);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 CO(Y,Q){switch(typeof Q){case"string":return Y.newString(Q);case"number":return Y.newNumber(Q);case"boolean":return Q?Y.true:Y.false;case"undefined":return Y.undefined;case"object":{if(Q===null)return Y.null;if(Array.isArray(Q)){let J=Y.newArray();return Q.forEach((G,K)=>{let W=CO(Y,G);try{Y.setProp(J,String(K),W)}finally{W.dispose?.()}}),J}let X=Y.newObject();for(let[J,G]of Object.entries(Q)){let K=CO(Y,G);try{Y.setProp(X,J,K)}finally{K.dispose?.()}}return X}case"function":{let X=`__hostFn_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return Y.newFunction(X,(...G)=>{try{let K=G.map((Z)=>Y.dump(Z)),W=Q(...K);if(W&&typeof W.then==="function"){let Z=Y.newPromise();return W.then((H)=>{try{let F=CO(Y,H);Z.resolve(F),F.dispose()}catch(F){let q=TO(F),V=Y.newString(`Promise resolution error: ${q}`);Z.reject(V),V.dispose()}finally{Y.runtime.executePendingJobs()}}).catch((H)=>{let F=TO(H),q=Y.newString(`Promise rejection: ${F}`);Z.reject(q),q.dispose(),Y.runtime.executePendingJobs()}),Z.handle}return CO(Y,W)}catch(K){let W=TO(K);return Y.newString(`HostFunctionError: ${W}`)}finally{G.forEach((K)=>K.dispose())}})}case"bigint":return Y.newString(Q.toString());case"symbol":return Y.newString(Q.toString());default:try{return Y.newString(String(Q))}catch{return Y.undefined}}}var Sw0=()=>{};function kw0(Y){let Q=Y.runtime.executePendingJobs(100);try{if("unwrap"in Q&&typeof Q.unwrap==="function")Q.unwrap()}finally{if("dispose"in Q&&typeof Q.dispose==="function")Q.dispose()}}async function vw0(Y,Q,X){let J=Date.now(),G=Y.resolvePromise(Q);while(!0){kw0(Y);let K=await Promise.race([G,yX4(0).then(()=>null)]);if(K!==null)return K;if(Date.now()-J>X)throw Error(`Timed out after ${X}ms while awaiting a QuickJS promise`)}}async function tE({tools:Y,code:Q,timeoutMs:X}){let W=[];try{const J=wT(W,await Rw0({memoryLimitBytes:33554432,stackSizeBytes:524288}),0);const G=wT(W,J.newContext({interruptAfterMs:X}),0);const K=wT(W,Ew0(G),0);try{let q=G.evalCode(Q,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(q),$=CO(G,Y);G.setProp(G.global,"tools",$);let z=G.runtime.hasPendingJob()?G.unwrapResult(await vw0(G,V,X)):V;if(z!==V)V.dispose();let O=G.getProp(z,"default"),L=G.typeof(O);if(L!=="function")return O.dispose(),z.dispose(),$.dispose(),{error:`Code must export default a function (tools). Got ${L}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:K.logs};let M=G.callFunction(O,G.undefined,$);$.dispose(),O.dispose(),z.dispose();let w=G.unwrapResult(M),I=await vw0(G,w,X);w.dispose();let j=G.unwrapResult(I);if(G.runtime.hasPendingJob())kw0(G);let C=G.dump(j);return j.dispose(),{returnValue:C,consoleLogs:K.logs}}catch(q){return console.log(q),{error:TO(q),consoleLogs:K.logs}}}catch(Z){var H=Z,F=1}finally{vZ1(W,H,F)}}var yX4=(Y)=>new Promise((Q)=>setTimeout(Q,Y));var _w0=v(()=>{jw0();Sw0()});var ZW1=v(()=>{_w0()});async function fX4(Y,Q){let X=Y.connections.map((K)=>K.connection_id),J=[];for(let K of X){let W=await Q.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 yw0(Y,Q){return(await Q.storage.connections.list(Y)).filter((J)=>J.status==="active").map((J)=>({connection:J,selectedTools:null,selectedResources:null,selectedPrompts:null}))}async function hX4(Y,Q){let X=new Map;for(let $ of Y)X.set($.connection.id,$);let J=Y.map(($)=>$.connection),G=new Map,K=await Promise.allSettled(J.map(async($)=>{try{let z=await Q.createMCPProxy($);return{connection:$,proxy:z}}catch(z){return console.warn(`[code-execution] Failed to create proxy for connection ${$.id}:`,z),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([$,z])=>{try{let L=(await z.proxy.listTools()).tools,M=X.get($);if(M?.selectedTools&&M.selectedTools.length>0){let w=new Set(M.selectedTools);L=L.filter((I)=>w.has(I.name))}return{connectionId:$,connectionTitle:z.connection.title,tools:L}}catch(O){return console.error(`[code-execution] Failed to list tools for connection ${$}:`,O),null}})),Z=new Set,H=[],F=new Map;for(let $ of W){if($.status!=="fulfilled"||!$.value)continue;let{connectionId:z,connectionTitle:O,tools:L}=$.value;for(let M of L){if(Z.has(M.name))continue;Z.add(M.name),H.push({...M,_meta:{connectionId:z,connectionTitle:O}}),F.set(M.name,z)}}let q=async($,z)=>{let O=F.get($);if(!O)return{content:[{type:"text",text:`Tool not found: ${$}`}],isError:!0};let L=G.get(O);if(!L)return{content:[{type:"text",text:`Connection not found for tool: ${$}`}],isError:!0};return await L.proxy.callTool({name:$,arguments:z})},V=[];for(let[,$]of G)V.push($.proxy.close().catch(()=>{}));return await Promise.all(V),{tools:H,callTool:q}}async function IO(Y){let Q=N0(Y),X;if(Y.connectionId){let J=await Y.storage.virtualMcps.findById(Y.connectionId,Y.organization?.id);if(J)X=await fX4(J,Y);else X=await yw0(Q.id,Y)}else X=await yw0(Q.id,Y);return hX4(X,Y)}function bX4(Y){return Y.toLowerCase().split(/[\s_\-./]+/).filter((Q)=>Q.length>=2)}function xX4(Y,Q){let X=0,J=Q.name.toLowerCase(),G=(Q.description??"").toLowerCase(),K=(Q._meta?.connectionTitle??"").toLowerCase();for(let W of Y){if(J===W)X+=10;else if(J.includes(W))X+=3;if(G.includes(W))X+=2;if(K.includes(W))X+=1}return X}function Wg(Y,Q,X){let J=bX4(Y);if(J.length===0)return Q.slice(0,X);return Q.map((G)=>({tool:G,score:xX4(J,G)})).filter((G)=>G.score>0).sort((G,K)=>K.score-G.score).slice(0,X).map((G)=>G.tool)}function Zg(Y,Q){let X=new Map(Q.map((G)=>[G.name,G]));return{tools:Y.map((G)=>X.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)=>!X.has(G))}}async function Kg(Y,Q,X){let J=Object.fromEntries(Q.tools.map((G)=>[G.name,async(K)=>{let W=await Q.callTool(G.name,K??{});if(W.structuredContent&&typeof W.structuredContent==="object")return W.structuredContent;let Z=W.content;if(Z?.[0]?.type==="text"&&Z[0].text)try{return JSON.parse(Z[0].text)}catch{return Z[0].text}return W}]));return tE({code:Y,tools:J,timeoutMs:X})}function eE(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}]}}function QF(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}],isError:!0}}function S3(Y){let Q=new Set(uX4);return Y.filter((X)=>!Q.has(X.name))}var uX4;var P$=v(()=>{ZW1();uX4=["CODE_EXECUTION_SEARCH_TOOLS","CODE_EXECUTION_DESCRIBE_TOOLS","CODE_EXECUTION_RUN_CODE"]});var KW1;var fw0=v(()=>{x0();sE();P$();KW1=u1({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:Lw0,outputSchema:Nw0,handler:async(Y,Q)=>{d1(Q),N0(Q),await Q.access.check();let X=await IO(Q),J=Wg(Y.query,X.tools,Y.limit);return{query:Y.query,results:J.map((G)=>({name:G.name,description:G.description,connection:G._meta?.connectionTitle??""})),totalAvailable:X.tools.length}}})});var HW1;var hw0=v(()=>{x0();sE();P$();HW1=u1({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:Mw0,outputSchema:ww0,handler:async(Y,Q)=>{d1(Q),N0(Q),await Q.access.check();let X=await IO(Q);return Zg(Y.tools,X.tools)}})});var FW1;var bw0=v(()=>{x0();sE();P$();FW1=u1({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:Pw0,outputSchema:Aw0,handler:async(Y,Q)=>{d1(Q),N0(Q),await Q.access.check();let X=await IO(Q);return await Kg(Y.code,X,Y.timeoutMs)}})});var xw0=v(()=>{fw0();hw0();bw0();sE()});var mX4,lX4,qW1;var uw0=v(()=>{x5();l1();x0();ex();z3();mX4=D.object({data:OM.describe("Data for the new connection (id is auto-generated if not provided)")}),lX4=D.object({item:rQ.describe("The created connection entity")}),qW1=u1({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",inputSchema:mX4,outputSchema:lX4,handler:async(Y,Q)=>{d1(Q);let X=N0(Q);await Q.access.check();let J=X9(Q);if(!J)throw Error("User ID required to create connection");let G={...Y.data,organization_id:X.id,created_by:J};if(G.connection_type==="VIRTUAL"){let H=sF(G.connection_url);if(!H)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let F=await Q.storage.virtualMcps.findById(H);if(!F)throw Error(`Virtual MCP not found: ${H}`);if(F.organization_id!==X.id)throw Error("Virtual MCP does not belong to the current organization");G.connection_url=tF(H)}let K=await XO({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 Q.storage.connections.create({...G,tools:W});return await Q.eventBus.publish(X.id,OX.SELF(X.id),{type:"connection.created",data:Z}),{item:Z}}})});var dX4,gw0,iz8;var mw0=v(()=>{l1();nX();dX4=D.object({id:D.string(),name:D.string(),description:D.string().optional(),inputSchema:D.record(D.string(),D.unknown()),outputSchema:D.record(D.string(),D.unknown()).optional()}),gw0=yW.extend({_meta:D.object({"io.decocms":D.object({id:D.string(),verified:D.boolean(),scopeName:D.string(),appName:D.string(),friendlyName:D.string().nullable().optional(),metadata:D.record(D.string(),D.unknown()).nullable().optional(),publishedAt:D.string().datetime().optional(),updatedAt:D.string().datetime().optional(),tools:D.array(dX4).nullable().optional().describe("Available tools exposed by this app")}).optional()}).optional(),server:D.object({$schema:D.string().optional(),_meta:D.record(D.string(),D.unknown()).optional(),name:D.string().describe("The server name (scope/app)"),title:D.string().optional().describe("User-friendly title"),description:D.string().optional().describe("Server description"),icons:D.array(D.object({src:D.string(),mimeType:D.string().optional(),sizes:D.array(D.string()).optional(),theme:D.enum(["light","dark"]).optional()})).optional(),remotes:D.array(D.object({type:D.enum(["http","stdio","sse"]),url:D.string().optional(),headers:D.array(D.unknown()).optional()})).optional(),packages:D.array(D.unknown()).optional(),repository:D.object({url:D.string(),source:D.string().optional(),subfolder:D.string().optional()}).optional(),version:D.string().optional(),websiteUrl:D.string().optional()})}),iz8=fW("registry_app",gw0,{readOnly:!0})});var lw0,dw0,pw0,cw0,nw0,pX4;var iw0=v(()=>{l1();JO();lw0=D.object({specversion:D.literal("1.0").describe("CloudEvents specification version"),id:D.string().describe("Unique identifier for this event (UUID recommended)"),source:D.string().describe("Connection ID of the event publisher"),type:D.string().describe("Event type (e.g., 'order.created', 'user.signup')"),time:D.string().datetime().optional().describe("Timestamp of when the event occurred (ISO 8601)"),subject:D.string().optional().describe("Subject/resource identifier (e.g., order ID, user ID)"),datacontenttype:D.string().optional().default("application/json").describe("Content type of the data attribute"),dataschema:D.string().url().optional().describe("URI to the schema for the data attribute"),data:D.unknown().optional().describe("Event payload (any JSON value)")}),dw0=D.object({events:D.array(lw0).min(1).describe("Batch of CloudEvents to process")}),pw0=D.object({success:D.boolean().optional().describe("Whether this event was processed successfully"),error:D.string().optional().describe("Error message for this event"),retryAfter:D.number().int().positive().optional().describe("Re-deliver this event after this many ms")}),cw0=D.object({success:D.boolean().optional().describe("Batch success - applies to events not in results"),error:D.string().optional().describe("Batch error message - applies to events not in results"),processedCount:D.number().int().min(0).optional().describe("Number of events successfully processed"),retryAfter:D.number().int().positive().optional().describe("Batch retryAfter - applies to events not in results"),results:D.record(D.string(),pw0).optional().describe("Per-event results keyed by event ID")}),nw0=[{name:"ON_EVENTS",inputSchema:dw0,outputSchema:cw0}],pX4=D3(nw0)});var YT,QT,XT,JT,aw0,rw0,GT,WT,ZT,KT,HT,FT,qT,VT,ow0,cX4;var sw0=v(()=>{l1();JO();YT=D.object({type:D.string().min(1).max(255).describe("Event type identifier"),subject:D.string().max(255).optional().describe("Subject/resource identifier (e.g., order ID)"),data:D.unknown().optional().describe("Event payload"),deliverAt:D.string().datetime().optional().describe("Scheduled delivery time (ISO 8601). Omit for immediate delivery."),cron:D.string().max(100).optional().describe("Cron expression for recurring delivery. Use EVENT_CANCEL to stop.")}),QT=D.object({id:D.string().describe("Unique event ID"),type:D.string().describe("Event type"),source:D.string().describe("Source connection ID"),time:D.string().describe("Event timestamp")}),XT=D.object({eventType:D.string().min(1).max(255).describe("Event type to subscribe to"),publisher:D.string().optional().describe("Filter events by publisher connection ID"),filter:D.string().max(1000).optional().describe("JSONPath filter expression on event data")}),JT=D.object({subscription:D.object({id:D.string().describe("Subscription ID"),connectionId:D.string().describe("Subscriber connection ID"),eventType:D.string().describe("Event type pattern"),publisher:D.string().nullable().describe("Publisher connection filter"),filter:D.string().nullable().describe("JSONPath filter expression"),enabled:D.boolean().describe("Whether subscription is enabled"),createdAt:D.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:D.string().datetime().describe("Updated timestamp (ISO 8601)")})}),aw0=D.object({eventType:D.string().min(1).max(255).describe("Event type to subscribe to"),publisher:D.string().optional().describe("Filter events by publisher connection ID"),filter:D.string().max(1000).optional().describe("JSONPath filter expression on event data")}),rw0=D.object({id:D.string().describe("Subscription ID"),connectionId:D.string().describe("Subscriber connection ID"),eventType:D.string().describe("Event type pattern"),publisher:D.string().nullable().describe("Publisher connection filter"),filter:D.string().nullable().describe("JSONPath filter expression"),enabled:D.boolean().describe("Whether subscription is enabled"),createdAt:D.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:D.string().datetime().describe("Updated timestamp (ISO 8601)")}),GT=D.object({subscriptions:D.array(aw0).describe("Desired subscriptions - system will create/update/delete to match")}),WT=D.object({created:D.number().int().min(0).describe("Number of subscriptions created"),updated:D.number().int().min(0).describe("Number of subscriptions with filter updated"),deleted:D.number().int().min(0).describe("Number of subscriptions removed"),unchanged:D.number().int().min(0).describe("Number of subscriptions unchanged"),subscriptions:D.array(rw0).describe("Current subscriptions after sync")}),ZT=D.object({subscriptionId:D.string().describe("Subscription ID to remove")}),KT=D.object({success:D.boolean().describe("Whether unsubscribe was successful"),subscriptionId:D.string().describe("Subscription ID that was removed")}),HT=D.object({eventId:D.string().describe("Event ID to cancel")}),FT=D.object({success:D.boolean().describe("Whether cancellation was successful"),eventId:D.string().describe("Event ID that was cancelled")}),qT=D.object({eventId:D.string().describe("Event ID to acknowledge")}),VT=D.object({success:D.boolean().describe("Whether ACK was successful"),eventId:D.string().describe("Event ID that was acknowledged")}),ow0=[{name:"EVENT_PUBLISH",inputSchema:YT,outputSchema:QT},{name:"EVENT_SUBSCRIBE",inputSchema:XT,outputSchema:JT},{name:"EVENT_UNSUBSCRIBE",inputSchema:ZT,outputSchema:KT},{name:"EVENT_CANCEL",inputSchema:HT,outputSchema:FT},{name:"EVENT_ACK",inputSchema:qT,outputSchema:VT},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:GT,outputSchema:WT}],cX4=D3(ow0)});var nX4,iX4,aX4,rX4,oX4,sX4,tX4,eX4,YJ4,QJ4,XJ4,JJ4,$T;var Hg=v(()=>{l1();nX4=D.object({prefix:D.string().optional().describe("Filter objects by prefix (e.g., 'folder/' for folder contents)"),maxKeys:D.number().optional().default(1000).describe("Maximum number of keys to return (default: 1000)"),continuationToken:D.string().optional().describe("Token for pagination from previous response"),delimiter:D.string().optional().describe("Delimiter for grouping keys (typically '/'). When set, commonPrefixes returns folder paths.")}),iX4=D.object({objects:D.array(D.object({key:D.string().describe("Object key/path"),size:D.number().describe("Object size in bytes"),lastModified:D.string().describe("Last modified timestamp"),etag:D.string().describe("Entity tag for the object")})),nextContinuationToken:D.string().optional().describe("Token for fetching next page of results"),isTruncated:D.boolean().describe("Whether there are more results available"),commonPrefixes:D.array(D.string()).optional().describe("Folder paths when delimiter is used (e.g., ['photos/2024/', 'photos/2025/'])")}),aX4=D.object({key:D.string().describe("Object key/path to get metadata for")}),rX4=D.object({contentType:D.string().optional().describe("MIME type of the object"),contentLength:D.number().describe("Size of the object in bytes"),lastModified:D.string().describe("Last modified timestamp"),etag:D.string().describe("Entity tag for the object"),metadata:D.record(D.string(),D.string()).optional().describe("Custom metadata key-value pairs")}),oX4=D.object({key:D.string().describe("Object key/path to generate URL for"),expiresIn:D.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)")}),sX4=D.object({url:D.string().describe("Presigned URL for downloading the object"),expiresIn:D.number().describe("Expiration time in seconds that was used")}),tX4=D.object({key:D.string().describe("Object key/path for the upload"),expiresIn:D.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)"),contentType:D.string().optional().describe("MIME type for the object being uploaded")}),eX4=D.object({url:D.string().describe("Presigned URL for uploading the object"),expiresIn:D.number().describe("Expiration time in seconds that was used")}),YJ4=D.object({key:D.string().describe("Object key/path to delete")}),QJ4=D.object({success:D.boolean().describe("Whether the deletion was successful"),key:D.string().describe("The key that was deleted")}),XJ4=D.object({keys:D.array(D.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),JJ4=D.object({deleted:D.array(D.string()).describe("Array of successfully deleted keys"),errors:D.array(D.object({key:D.string(),message:D.string()})).describe("Array of errors for failed deletions")}),$T=[{name:"LIST_OBJECTS",inputSchema:nX4,outputSchema:iX4},{name:"GET_OBJECT_METADATA",inputSchema:aX4,outputSchema:rX4},{name:"GET_PRESIGNED_URL",inputSchema:oX4,outputSchema:sX4},{name:"PUT_PRESIGNED_URL",inputSchema:tX4,outputSchema:eX4},{name:"DELETE_OBJECT",inputSchema:YJ4,outputSchema:QJ4},{name:"DELETE_OBJECTS",inputSchema:XJ4,outputSchema:JJ4}]});var VW1=v(()=>{JO();mw0();iw0();sw0();Hg();GO()});var GJ4,WJ4,tw0;var ew0=v(()=>{l1();nX();GJ4=yW.extend({avatar:D.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:D.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:D.string().describe("Virtual MCP ID to use for this assistant"),model:D.object({id:D.string().describe("Model ID"),connectionId:D.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),WJ4=fW("assistant",GJ4),tw0=[...WJ4]});var zT,v3,QP0,ZJ4,KJ4,XP0,HJ4,FJ4,qJ4,VJ4,$J4,zJ4,JP0,BJ4,UJ4,DJ4,OJ4,LJ4,NJ4,MJ4,wJ4,PJ4,AJ4,LB8,EJ4,NB8,YP0,TJ4,CJ4,$W1,MB8;var GP0=v(()=>{l1();JO();nX();zT=D.lazy(()=>D.union([D.null(),D.string(),D.number(),D.boolean(),D.record(D.string(),zT),D.array(zT)])),v3=D.record(D.string(),D.record(D.string(),zT)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),QP0=D.object({type:D.literal("text"),text:D.string().describe("The text content"),providerOptions:v3}),ZJ4=D.object({type:D.literal("text"),text:D.string().describe("The text content"),providerMetadata:D.any().optional().describe("Additional provider-specific metadata")}),KJ4=D.string().describe("File data as URL string"),XP0=D.object({type:D.literal("file"),filename:D.string().optional().describe("Optional filename of the file"),data:KJ4,mediaType:D.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:v3}),HJ4=D.object({type:D.literal("file"),mediaType:D.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:D.string().describe("Generated file data as base64 encoded string")}),FJ4=D.object({type:D.literal("reasoning"),text:D.string().describe("The reasoning text"),providerOptions:v3}),qJ4=D.object({type:D.literal("reasoning"),text:D.string().describe("The reasoning text"),providerMetadata:D.any().optional().describe("Additional provider-specific metadata")}),VJ4=D.object({type:D.literal("tool-call"),toolCallId:D.string().describe("ID of the tool call, used to match with tool result"),toolName:D.string().describe("Name of the tool being called"),input:D.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:D.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:v3}),$J4=D.object({type:D.literal("tool-call"),toolCallId:D.string().describe("ID of the tool call"),toolName:D.string().describe("Name of the tool being called"),input:D.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:D.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:D.any().optional().describe("Additional provider-specific metadata")}),zJ4=D.union([D.object({type:D.literal("text"),value:D.string()}),D.object({type:D.literal("json"),value:zT}),D.object({type:D.literal("error-text"),value:D.string()}),D.object({type:D.literal("error-json"),value:zT}),D.object({type:D.literal("content"),value:D.array(D.union([D.object({type:D.literal("text"),text:D.string().describe("Text content")}),D.object({type:D.literal("media"),data:D.string().describe("Base-64 encoded media data"),mediaType:D.string().describe("IANA media type")})]))})]),JP0=D.object({type:D.literal("tool-result"),toolCallId:D.string().describe("ID of the tool call that this result is associated with"),toolName:D.string().describe("Name of the tool that generated this result"),output:zJ4.describe("Result of the tool call"),result:D.unknown().describe("Unknown result of the tool call"),providerOptions:v3}),BJ4=D.object({type:D.literal("tool-result"),toolCallId:D.string().describe("ID of the tool call that this result is associated with"),toolName:D.string().describe("Name of the tool that generated this result"),result:D.any().describe("Result of the tool call (JSON-serializable)"),isError:D.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:D.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:D.any().optional().describe("Additional provider-specific metadata")}),UJ4=D.union([D.object({type:D.literal("source"),sourceType:D.literal("url"),id:D.string().describe("The ID of the source"),url:D.string().describe("The URL of the source"),title:D.string().optional().describe("The title of the source"),providerMetadata:D.any().optional().describe("Additional provider-specific metadata")}),D.object({type:D.literal("source"),sourceType:D.literal("document"),id:D.string().describe("The ID of the source"),mediaType:D.string().describe("IANA media type of the document (e.g., application/pdf)"),title:D.string().describe("The title of the document"),filename:D.string().optional().describe("Optional filename of the document"),providerMetadata:D.any().optional().describe("Additional provider-specific metadata")})]),DJ4=D.object({role:D.literal("system"),content:D.string().describe("System message content"),providerOptions:v3}),OJ4=D.object({role:D.literal("user"),content:D.array(D.union([QP0,XP0])).describe("User message content parts (text or file)"),providerOptions:v3}),LJ4=D.object({role:D.literal("assistant"),content:D.array(D.union([QP0,XP0,FJ4,VJ4,JP0])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:v3}),NJ4=D.object({role:D.literal("tool"),content:D.array(JP0).describe("Tool message content (tool results)"),providerOptions:v3}),MJ4=D.union([DJ4,OJ4,LJ4,NJ4]),wJ4=D.array(MJ4).describe("A list of messages forming the prompt"),PJ4=D.object({prompt:wJ4.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:D.number().optional().describe("Maximum number of tokens to generate"),temperature:D.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:D.number().optional().describe("Nucleus sampling parameter"),topK:D.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:D.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:D.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:D.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:D.array(D.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:D.union([D.object({type:D.literal("text")}),D.object({type:D.literal("json"),schema:D.any().optional().describe("JSON schema that the generated output should conform to"),name:D.string().optional().describe("Name of output that should be generated"),description:D.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:D.array(D.any()).optional().describe("The tools that are available for the model"),toolChoice:D.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:D.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:D.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:D.any().optional().describe("Additional provider-specific options")}),AJ4=D.object({content:D.array(D.union([ZJ4,HJ4,qJ4,$J4,BJ4,UJ4])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:D.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:D.looseObject({inputTokens:D.number().optional(),outputTokens:D.number().optional(),totalTokens:D.number().optional(),reasoningTokens:D.number().optional()}).describe("Usage information for the language model call"),providerMetadata:D.any().optional().describe("Additional provider-specific metadata"),request:D.object({body:D.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:D.object({id:D.string().optional().describe("ID for the generated response"),timestamp:D.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:D.string().optional().describe("The ID of the response model that was used"),headers:D.record(D.string(),D.string()).optional().describe("Response headers"),body:D.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:D.array(D.any()).describe("Warnings for the call, e.g. unsupported settings")}),LB8=D.object({stream:D.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:D.object({body:D.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:D.object({headers:D.record(D.string(),D.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),EJ4=D.object({supportedUrls:D.record(D.string(),D.array(D.string())).describe("Supported URL patterns by media type for the provider")}),NB8=D.object({modelId:D.string().describe("The ID of the model"),logo:D.string().nullable(),description:D.string().nullable(),capabilities:D.array(D.string()),limits:D.object({contextWindow:D.number(),maxOutputTokens:D.number()}).nullable(),costs:D.object({input:D.number(),output:D.number()}).nullable(),provider:D.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),YP0=D.object({modelId:D.string().describe("The ID of the model"),callOptions:PJ4}),TJ4=yW.extend({logo:D.string().nullable(),description:D.string().nullable(),capabilities:D.array(D.string()),limits:D.object({contextWindow:D.number(),maxOutputTokens:D.number()}).nullable(),costs:D.object({input:D.number(),output:D.number()}).nullable(),provider:D.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),CJ4=fW("llm",TJ4,{readOnly:!0}),$W1=[{name:"LLM_METADATA",inputSchema:D.object({modelId:D.string().describe("The ID of the model")}),outputSchema:EJ4},{name:"LLM_DO_STREAM",inputSchema:YP0,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:YP0,outputSchema:AJ4},...CJ4],MB8=D3($W1)});function RO(){return!1}function Fg(Y,Q){return Y===OX.DEV_ASSETS(Q)}function jO(Y,Q){let X=Na(Q,Y),J=new Date().toISOString();return{id:X.id??OX.DEV_ASSETS(Y),title:X.title,description:X.description??null,icon:X.icon??null,app_name:X.app_name??null,app_id:X.app_id??null,organization_id:Y,created_by:"system",created_at:J,updated_at:J,connection_type:X.connection_type,connection_url:X.connection_url??null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:X.metadata??null,tools:IJ4,bindings:["OBJECT_STORAGE"],status:"active"}}var IJ4;var qg=v(()=>{Hg();x5();l1();IJ4=$T.map((Y)=>({name:Y.name,description:`${Y.name} operation for local file storage`,inputSchema:D.toJSONSchema(Y.inputSchema),outputSchema:D.toJSONSchema(Y.outputSchema)}))});function jJ4(Y){let Q=[],X=0;while(X<Y.length){let J=Y[X];if(J==="%")Q.push(".*");else if(J==="_")Q.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))Q.push("\\"+J);else Q.push(J);X++}return Q.join("")}function XF(Y){return typeof Y==="string"||typeof Y==="number"}function Vg(Y,Q){if("conditions"in Q){let{operator:Z,conditions:H}=Q;switch(Z){case"and":return H.every((F)=>Vg(Y,F));case"or":return H.some((F)=>Vg(Y,F));case"not":return!H.every((F)=>Vg(Y,F));default:return!0}}let{field:X,operator:J,value:G}=Q,K=X.join("."),W=zW1(Y,K);switch(J){case"eq":return W===G;case"gt":return XF(W)&&XF(G)&&W>G;case"gte":return XF(W)&&XF(G)&&W>=G;case"lt":return XF(W)&&XF(G)&&W<G;case"lte":return XF(W)&&XF(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=jJ4(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 zW1(Y,Q){let X=Q.split("."),J=Y;for(let G of X){if(J==null||typeof J!=="object")return;J=J[G]}return J}function SJ4(Y,Q){return[...Y].sort((X,J)=>{for(let G of Q){let K=G.field.join("."),W=zW1(X,K),Z=zW1(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 RJ4,vJ4,kJ4,BW1;var WP0=v(()=>{VW1();ew0();nX();GP0();Hg();x5();l1();x0();qg();z3();RJ4={LLM:$W1,ASSISTANTS:tw0,OBJECT_STORAGE:$T};vJ4=O3.extend({binding:D.union([D.object({}).passthrough(),D.string()]).optional(),include_virtual:D.boolean().optional().describe("Whether to include VIRTUAL connections in the results. Defaults to false.")}),kJ4=L3(rQ),BW1=u1({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",inputSchema:vJ4,outputSchema:kJ4,handler:async(Y,Q)=>{await Q.access.check();let X=N0(Q),J=Y.binding?typeof Y.binding==="string"?(()=>{let $=RJ4[Y.binding.toUpperCase()];if(!$)throw Error(`Unknown binding: ${Y.binding}`);return $})():Y.binding:void 0,G=J?Zu(J):void 0,K=await Q.storage.connections.list(X.id,{includeVirtual:Y.include_virtual??!1});if(RO()){let $=h7(),z=OX.DEV_ASSETS(X.id);if(!K.some((O)=>O.id===z)){let O=jO(X.id,$);K.unshift(O)}}let W=G?await Promise.all(K.map(async($)=>{if(!$.tools||$.tools.length===0)return null;return G.isImplementedBy($.tools.map((O)=>({name:O.name,inputSchema:O.inputSchema,outputSchema:O.outputSchema})))?$:null})).then(($)=>$.filter((z)=>z!==null)):K;if(Y.where)W=W.filter(($)=>Vg($,Y.where));if(Y.orderBy&&Y.orderBy.length>0)W=SJ4(W,Y.orderBy);let Z=W.length,H=Y.offset??0,F=Y.limit??100,q=W.slice(H,H+F),V=H+F<Z;return{items:q,totalCount:Z,hasMore:V}}})});var _J4,UW1;var ZP0=v(()=>{nX();x0();qg();z3();_J4=OE(rQ),UW1=u1({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",inputSchema:DE,outputSchema:_J4,handler:async(Y,Q)=>{let X=N0(Q);if(await Q.access.check(),RO()&&Fg(Y.id,X.id))return{item:jO(X.id,h7())};let J=await Q.storage.connections.findById(Y.id);if(!J||J.organization_id!==X.id)return{item:null};return{item:J}}})});var $g=(Y,Q)=>{if(Q===null||Q===void 0)return;let X=Y.replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),J=Q;for(let G of X){if(J===null||J===void 0||typeof J!=="object")return;J=J[G]}return J};function KP0(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])throw Error(`Invalid scope format: ${Y}. Expected format: "KEY::SCOPE"`);return Q}function yJ4(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])return null;return Q}function fJ4(Y){if(typeof Y==="object"&&Y!==null&&"value"in Y){let Q=Y.value;if(typeof Q==="string")return Q}return null}function DW1(Y,Q){let X={};if(!Y||!Q)return X;for(let J of Q){if(J==="*"){X["*"]=["*"];continue}let G=yJ4(J);if(!G)continue;let[K,W]=G,Z=$g(K,Y),H=fJ4(Z);if(H){if(!X[H])X[H]=[];X[H].push(W)}}return X}function HP0(Y,Q){let X=DW1(Y,Q);return new Set(Object.keys(X).filter((J)=>J!=="*"))}var OW1=()=>{};import{randomBytes as hJ4}from"crypto";function bJ4(){if(BT)return BT;let Y=process.env.MESH_JWT_SECRET??T5.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(Y)BT=new TextEncoder().encode(Y);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),BT=new Uint8Array(hJ4(32));return BT}async function FP0(Y,Q="5m"){let X=bJ4();return await new m5(Y).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Q).sign(X)}var BT=null;var qP0=v(()=>{MX();zg()});async function VP0(Y){if(!Y.refreshToken)return{success:!1,error:"No refresh token available"};if(!Y.tokenEndpoint)return{success:!1,error:"No token endpoint available"};if(!Y.clientId)return{success:!1,error:"No client ID available"};try{let Q=new URLSearchParams({grant_type:"refresh_token",refresh_token:Y.refreshToken,client_id:Y.clientId});if(Y.clientSecret)Q.set("client_secret",Y.clientSecret);if(Y.scope)Q.set("scope",Y.scope);let X=await fetch(Y.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Q.toString()});if(!X.ok){let G=await X.text();console.error(`[TokenRefresh] Failed to refresh token: ${X.status}`,G);try{let K=JSON.parse(G);return{success:!1,error:K.error_description||K.error||`Token refresh failed: ${X.status}`}}catch{return{success:!1,error:`Token refresh failed: ${X.status}`}}}let J=await X.json();return{success:!0,accessToken:J.access_token,refreshToken:J.refresh_token||Y.refreshToken,expiresIn:J.expires_in,scope:J.scope}}catch(Q){return console.error("[TokenRefresh] Error refreshing token:",Q),{success:!1,error:Q instanceof Error?Q.message:"Token refresh failed"}}}class UT{db;vault;constructor(Y,Q){this.db=Y;this.vault=Q}async get(Y){let Q=await this.db.selectFrom("downstream_tokens").selectAll().where("connectionId","=",Y).executeTakeFirst();if(!Q)return null;return this.decryptToken(Q)}async upsert(Y){let Q=new Date().toISOString(),X=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:X,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,updatedAt:Q}).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:Q,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint};let Z=pH("dtok");return await K.insertInto("downstream_tokens").values({id:Z,connectionId:Y.connectionId,accessToken:X,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,createdAt:Q,updatedAt:Q}).execute(),{id:Z,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Q,updatedAt:Q,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint}})}async delete(Y){await this.db.deleteFrom("downstream_tokens").where("connectionId","=",Y).execute()}isExpired(Y,Q=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-Q<Date.now()}async decryptToken(Y){let Q=await this.vault.decrypt(Y.accessToken),X=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:Q,refreshToken:X,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Y.createdAt,updatedAt:Y.updatedAt,clientId:Y.clientId,clientSecret:J,tokenEndpoint:Y.tokenEndpoint}}}var LW1=v(()=>{GE()});async function Bg(Y,Q,X){let J=Y.id,G=DW1(Y.configuration_state,Y.configuration_scopes),K=Q.auth.user?.id??Q.auth.apiKey?.userId??(X?Y.created_by:void 0),[W,Z]=K?await FP0({sub:K,user:{id:K},metadata:{state:Y.configuration_state??void 0,meshUrl:process.env.MESH_URL??Q.baseUrl,connectionId:J,organizationId:Q.organization?.id},permissions:G}).then((z)=>[z,null]).catch((z)=>[null,z]):[null,Error("User ID required to issue configuration token")];if(Z)console.error("Failed to issue configuration token:",W);let H=Q.auth.user?.connectionId,F={...H?{"x-caller-id":H}:{},...Q.metadata.wellKnownForwardableHeaders??{},"x-request-id":Q.metadata.requestId},q=null,V=new UT(Q.db,Q.vault),$=await V.get(J);if($){let z=!!$.refreshToken&&!!$.tokenEndpoint;if(V.isExpired($,z?300000:0))if(z){console.log(`[Proxy] Token expired for ${J}, attempting refresh`);let L=await VP0($);if(L.success&&L.accessToken)await V.upsert({connectionId:J,accessToken:L.accessToken,refreshToken:L.refreshToken??$.refreshToken,scope:L.scope??$.scope,expiresAt:L.expiresIn?new Date(Date.now()+L.expiresIn*1000):null,clientId:$.clientId,clientSecret:$.clientSecret,tokenEndpoint:$.tokenEndpoint}),q=L.accessToken,console.log(`[Proxy] Token refreshed for ${J}`);else await V.delete(J),console.error(`[Proxy] Token refresh failed for ${J}: ${L.error}`)}else await V.delete(J),console.log(`[Proxy] Token expired without refresh capability for ${J}`);else q=$.accessToken}if(!q&&Y.connection_token)q=Y.connection_token;if(q)F.Authorization=`Bearer ${q}`;if(W)F["x-mesh-token"]=W;return F}var NW1=v(()=>{OW1();qP0();LW1()});function $P0(){let Y=new Map;function Q(J,G){let K=Y.get(G);if(K)return console.log(`[ClientPool] Reusing cached client for ${G}`),K;console.log(`[ClientPool] Creating new client for ${G}`);let W=new qJ({name:`outbound-client-${G}`,version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});W.onclose=()=>{Y.delete(G)};let Z=W.connect(J,{timeout:30000}).then(()=>W).catch((H)=>{throw Y.delete(G),H});return Y.set(G,Z),Z}return Object.assign(Q,{[Symbol.asyncDispose]:async()=>{let J=[];for(let[G,K]of Y)J.push(K.then((W)=>W.close()).catch((W)=>console.error(`[ClientPool] Error closing client ${G}:`,W)));await Promise.all(J),Y.clear()}})}var zP0=v(()=>{kz()});function BP0(Y){let Q=new FE({command:Y.command,args:Y.args,env:Y.env,cwd:Y.cwd,stderr:"pipe"}),X=Y.name||Y.id,J="\x1B[2m",G="\x1B[0m";return Q.stderr?.on("data",(K)=>{let W=K.toString().trimEnd();if(W)console.error(`${W} \x1B[2m[${X}]\x1B[0m`)}),Q}var UP0=v(()=>{nJ1()});class DT{innerTransport;constructor(Y){this.innerTransport=Y}async start(){return this.innerTransport.onmessage=(Y)=>{this.handleIncomingMessage(Y)},this.innerTransport.onerror=(Y)=>{this.onerror?.(Y)},this.innerTransport.onclose=()=>{this.onclose?.()},this.innerTransport.start()}async send(Y){return this.handleOutgoingMessage(Y)}async close(){return this.innerTransport.close()}async handleOutgoingMessage(Y){return this.innerTransport.send(Y)}handleIncomingMessage(Y){this.onmessage?.(Y)}isRequest(Y){return"method"in Y&&Y.method!==void 0}isResponse(Y){return"result"in Y||"error"in Y&&!("method"in Y)}onmessage;onerror;onclose}function OT(Y,...Q){return Q.reduce((X,J)=>J(X),Y)}var DP0="mcp.mesh";var OP0,MW1,Ug;var wW1=v(()=>{OP0=class OP0 extends Error{constructor(Y){super(Y);this.name="UnauthorizedError"}};MW1=class MW1 extends Error{constructor(Y){super(Y);this.name="ForbiddenError"}};Ug=class Ug{userId;toolName;boundAuth;role;connectionId;getToolMeta;_granted=!1;constructor(Y,Q,X,J,G,K="self",W){this.userId=Q;this.toolName=X;this.boundAuth=J;this.role=G;this.connectionId=K;this.getToolMeta=W}[Symbol.dispose](){this._granted=!1}setToolName(Y){this.toolName=Y}grant(){return this._granted=!0,{[Symbol.dispose]:()=>{this._granted=!1}}}async check(...Y){if(this._granted)return;if(this.toolName?.startsWith("MESH_PUBLIC_")){this.grant();return}if(!this.userId&&!this.boundAuth){if(this.getToolMeta&&await this.isToolPublic()){this.grant();return}throw new OP0("Authentication required. Please provide a valid OAuth token or API key.")}let Q=Y.length>0?Y:this.toolName?[this.toolName]:[];if(Q.length===0)throw new MW1("No resources specified for access check");for(let X of Q)if(await this.checkResource(X)){this.grant();return}throw new MW1(`Access denied to: ${Q.join(", ")}`)}async checkResource(Y){if(!this.userId&&!this.boundAuth)return!1;if(this.role==="admin"||this.role==="owner")return!0;if(!this.boundAuth)return!1;let Q={};if(this.connectionId)Q[this.connectionId]=[Y];return this.boundAuth.hasPermission(Q)}async isToolPublic(){if(this.toolName?.startsWith("MESH_PUBLIC_"))return!0;if(!this.getToolMeta)return!1;try{let Y=await this.getToolMeta();if(!Y)return!1;let X=Y[DP0]?.public_tool;return X===!0||X==="true"}catch{return!1}}granted(){return this._granted}}});var xJ4="mcp.mesh",SO;var LP0=v(()=>{wW1();SO=class SO extends DT{options;cachedToolsMap=null;constructor(Y,Q){super(Y);this.options=Q;if(Q.connection.tools)this.cachedToolsMap=new Map(Q.connection.tools.map((X)=>[X.name,X]))}async handleOutgoingMessage(Y){if(!this.isRequest(Y))return this.innerTransport.send(Y);let Q=Y;if(Q.method==="tools/call")await this.authorizeToolCall(Q),this.stripMetaFromArguments(Q);return this.innerTransport.send(Y)}async authorizeToolCall(Y){if(this.options.superUser)return;let X=Y.params.name,{ctx:J,connection:G}=this.options;if(this.isPublicTool(X))return;if(!J.auth.user?.id&&!J.auth.apiKey?.id)throw Error("Authentication required. Please provide a valid OAuth token or API key.");let K=async()=>{return this.cachedToolsMap?.get(X)?._meta};await new Ug(J.authInstance,J.auth.user?.id??J.auth.apiKey?.userId,X,J.boundAuth,J.auth.user?.role,G.id,K).check(X)}isPublicTool(Y){if(Y.startsWith("MESH_PUBLIC_"))return!0;if(!this.cachedToolsMap)return!1;let Q=this.cachedToolsMap.get(Y);if(!Q?._meta)return!1;return Q._meta[xJ4]?.public_tool===!0}stripMetaFromArguments(Y){let Q=Y.params;if(Q.arguments&&"_meta"in Q.arguments){let{_meta:X,...J}=Q.arguments;Q.arguments=J}}}});function NP0(Y){if(!Y.isError)return;let Q=Y.content;if(!Array.isArray(Q))return;for(let X of Q)if(X&&typeof X==="object"&&"type"in X&&X.type==="text"&&"text"in X&&typeof X.text==="string")return X.text;return}function MP0(Y){if(!Y)return;let Q=Y._meta;if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let X=Q.properties;if(!X||typeof X!=="object"||Array.isArray(X))return;let J={};for(let[G,K]of Object.entries(X))if(typeof K==="string")J[G]=K;return Object.keys(J).length>0?J:void 0}function wP0(Y,Q){if(!Y&&!Q)return;if(!Y)return Q;if(!Q)return Y;return{...Q,...Y}}function PP0(Y){if(Y&&typeof Y==="object"&&!Array.isArray(Y)){let Q=Y,X=Q.structuredContent;if(X&&typeof X==="object"&&!Array.isArray(X))return X;return Q}return{value:Y}}var PW1=v(()=>{x5()});var vO;var AP0=v(()=>{py();PW1();vO=class vO extends DT{options;inflightRequests=new Map;constructor(Y,Q){super(Y);this.options=Q}async handleOutgoingMessage(Y){if(this.isRequest(Y)){let Q=Y;this.onRequestStart(Q)}return this.innerTransport.send(Y)}handleIncomingMessage(Y){if(this.isResponse(Y)){let Q=Y;this.onResponseEnd(Q)}this.onmessage?.(Y)}onRequestStart(Y){let{ctx:Q,connectionId:X}=this.options,J,G;if(Y.method==="tools/call"&&Y.params){let W=Y.params;J=W.name,G=W.arguments}let K;if(Y.method==="tools/call"&&J)K=Q.tracer.startSpan("mcp.proxy.callTool",{attributes:{"connection.id":X,"tool.name":J,"request.id":Q.metadata.requestId,"jsonrpc.id":Y.id,"jsonrpc.method":Y.method}});if(Y.id!==null&&Y.id!==void 0)this.inflightRequests.set(Y.id,{startTime:Date.now(),method:Y.method,toolName:J,toolArguments:G,span:K})}onResponseEnd(Y){if(Y.id===null||Y.id===void 0)return;let Q=this.inflightRequests.get(Y.id);if(!Q)return;let{ctx:X,connectionId:J}=this.options,{startTime:G,method:K,toolName:W,toolArguments:Z,span:H}=Q,F=Date.now()-G;if(this.inflightRequests.delete(Y.id),K!=="tools/call"||!W)return;let q="error"in Y,V=q?Y.error:Y.result,$=q?{content:[{type:"text",text:Y.error?.message||"Unknown error"}],isError:!0}:V;if(X.meter.createHistogram("connection.proxy.duration").record(F,{"connection.id":J,"tool.name":W,status:q?"error":"success"}),q)X.meter.createCounter("connection.proxy.errors").add(1,{"connection.id":J,"tool.name":W,error:Y.error?.message});else X.meter.createCounter("connection.proxy.requests").add(1,{"connection.id":J,"tool.name":W,status:"success"});if(H){if(q&&Y.error)H.recordException(Error(Y.error.message)),H.setAttributes({error:!0,"error.code":Y.error.code,"error.message":Y.error.message});H.end()}this.logToDatabase({toolName:W,toolArguments:Z,result:$,duration:F,isError:Boolean(q)})}async logToDatabase(Y){let{ctx:Q,connectionId:X,connectionTitle:J,virtualMcpId:G}=this.options,{toolName:K,toolArguments:W,result:Z,duration:H,isError:F}=Y;if(!D01().enabled)return;let V=Q.organization?.id;if(!V)return;let $=NP0(Z),z=PP0(Z),O=MP0(W),L=wP0(Q.metadata.properties,O);try{await Q.storage.monitoring.log({organizationId:V,connectionId:X,connectionTitle:J,toolName:K,input:W??{},output:z,isError:F,errorMessage:$,durationMs:H,timestamp:new Date,userId:Q.auth.user?.id||Q.auth.apiKey?.userId||null,requestId:Q.metadata.requestId,userAgent:Q.metadata.userAgent,virtualMcpId:G,properties:L})}catch(M){console.error("[MonitoringTransport] Failed to log to database:",M)}}async close(){for(let Y of this.inflightRequests.values())if(Y.span)Y.span.setAttributes({"transport.closed":!0}),Y.span.end();return this.inflightRequests.clear(),super.close()}}});var EP0=v(()=>{LP0();AP0()});async function TP0(Y,Q,X=!1){let J=Y.id,G=Q.connectionId&&Q.connectionId!==J?Q.connectionId:void 0;switch(Y.connection_type){case"STDIO":{if(process.env.UNSAFE_ALLOW_STDIO_TRANSPORT!=="true")throw Error("STDIO connections are disabled in production. Set UNSAFE_ALLOW_STDIO_TRANSPORT=true to enable.");let K=Y.connection_headers;if(!wG(K))throw Error("STDIO connection missing parameters");let W=BP0({id:J,name:Y.title,command:K.command,args:K.args,env:K.envVars,cwd:K.cwd});return W=OT(W,(Z)=>new SO(Z,{ctx:Q,connection:Y,superUser:X}),(Z)=>new vO(Z,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),uJ4(W,J)}case"HTTP":case"Websocket":{if(!Y.connection_url)throw Error(`${Y.connection_type} connection missing URL`);let K=await Bg(Y,Q,X),W=Y.connection_headers;if(W&&"headers"in W)Object.assign(K,W.headers);let Z=new VK(new URL(Y.connection_url),{requestInit:{headers:K}});return Z=OT(Z,(H)=>new SO(H,{ctx:Q,connection:Y,superUser:X}),(H)=>new vO(H,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),Q.getOrCreateClient(Z,J)}case"SSE":{if(!Y.connection_url)throw Error("SSE connection missing URL");let K=await Bg(Y,Q,X),W=Y.connection_headers;if(W&&"headers"in W)Object.assign(K,W.headers);let Z=new H$(new URL(Y.connection_url),{requestInit:{headers:K}});return Z=OT(Z,(H)=>new SO(H,{ctx:Q,connection:Y,superUser:X}),(H)=>new vO(H,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),Q.getOrCreateClient(Z,J)}default:throw Error(`Unknown connection type: ${Y.connection_type}`)}}var uJ4;var CP0=v(()=>{z3();ox();DM();NW1();zP0();UP0();EP0();uJ4=$P0()});function jP0(Y){if(!Y?._meta)return!1;return typeof Y._meta["mcp.mesh"]?.["tool.fn"]==="string"}function SP0(Y){return Y._meta["mcp.mesh"]["tool.fn"]}var AW1,bU8,gW,IP0,RP0;var JF=v(()=>{l1();AW1=D.object({title:D.string().optional(),readOnlyHint:D.boolean().optional(),destructiveHint:D.boolean().optional(),idempotentHint:D.boolean().optional(),openWorldHint:D.boolean().optional()}),bU8=D.object({"tool.fn":D.string().describe("JavaScript ES module code that exports a default async function")}),gW=D.object({id:D.string().describe("Unique identifier for the virtual tool (auto-generated)"),name:D.string().min(1).max(255).describe("Tool name (must be unique within the Virtual MCP)"),description:D.string().optional().describe("Human-readable description of what the tool does"),inputSchema:D.record(D.string(),D.unknown()).describe("JSON Schema defining the tool's input parameters"),outputSchema:D.record(D.string(),D.unknown()).optional().describe("JSON Schema defining the tool's output (optional)"),annotations:AW1.optional().describe("MCP tool annotations"),code:D.string().describe("JavaScript ES module code. Must export default an async function: export default async (tools, args) => { ... }"),connection_dependencies:D.array(D.string()).describe("Connection IDs that this tool depends on (specified by the creator)"),created_at:D.string().describe("When the virtual tool was created"),updated_at:D.string().describe("When the virtual tool was last updated")}),IP0=D.object({name:D.string().min(1).max(255).describe("Tool name (must be unique within the Virtual MCP)"),description:D.string().optional().describe("Human-readable description"),inputSchema:D.record(D.string(),D.unknown()).describe("JSON Schema defining the tool's input parameters"),outputSchema:D.record(D.string(),D.unknown()).optional().describe("JSON Schema for output"),annotations:AW1.optional().describe("MCP tool annotations"),code:D.string().describe("JavaScript ES module code. Must export default an async function: export default async (tools, args) => { ... }"),connection_dependencies:D.array(D.string()).optional().describe("Connection IDs that this tool depends on. Creates indirect aggregations to prevent deletion of referenced connections.")}),RP0=D.object({name:D.string().min(1).max(255).optional().describe("New tool name"),description:D.string().nullable().optional().describe("New description (null to clear)"),inputSchema:D.record(D.string(),D.unknown()).optional().describe("New input schema"),outputSchema:D.record(D.string(),D.unknown()).nullable().optional().describe("New output schema (null to clear)"),annotations:AW1.nullable().optional().describe("New annotations (null to clear)"),code:D.string().optional().describe("New JavaScript code"),connection_dependencies:D.array(D.string()).optional().describe("Connection IDs that this tool depends on. Replaces existing dependencies if provided.")})});function Dg(Y){return(Q)=>{if(Q instanceof O0&&Q.code===P0.MethodNotFound)return Y;throw Q}}var EW1=v(()=>{lY()});class vP0{factory;promise=null;constructor(Y){this.factory=Y}getOrCreatePromise(){if(!this.promise)this.promise=this.factory();return this.promise}then(Y,Q){return this.getOrCreatePromise().then(Y,Q)}catch(Y){return this.getOrCreatePromise().catch(Y)}finally(Y){return this.getOrCreatePromise().finally(Y)}}function LT(Y){return new vP0(Y)}async function gJ4(Y,Q,X=!1){let J=await Promise.all(Y.map(async(G)=>{try{let K=await _O(G,Q,X);return[G.id,K]}catch(K){return console.warn(`[aggregator] Failed to create client for connection ${G.id}:`,K),null}}));return new Map(J.filter((G)=>!!G))}async function kP0(Y){let Q=[];for(let[,X]of Y)Q.push(X.close().catch(()=>{}));await Promise.all(Q)}var kO;var TW1=v(()=>{CW1();EW1();kz();ZW1();JF();kO=class kO extends qJ{options;ctx;_cachedTools;_cachedResources;_cachedPrompts;_clients;_connections;_selectionMap;constructor(Y,Q){super({name:"virtual-mcp-passthrough",version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});this.options=Y;this.ctx=Q;this._selectionMap=new Map;for(let X of Y.virtualMcp.connections)this._selectionMap.set(X.connection_id,X);this._connections=new Map;for(let X of Y.connections)this._connections.set(X.id,X);this._clients=LT(()=>gJ4(this.options.connections,this.ctx,this.options.superUser)),this._cachedTools=LT(()=>this.loadToolsCache()),this._cachedResources=LT(()=>this.loadCache("resources")),this._cachedPrompts=LT(()=>this.loadCache("prompts"))}async loadToolsCache(){let Y=await this._clients,Q=await Promise.all(Array.from(Y.entries()).map(async([W,Z])=>{try{let H=await Z.listTools().then((q)=>q.tools),F=this._selectionMap.get(W);if(F?.selected_tools?.length){let q=new Set(F.selected_tools);H=H.filter((V)=>q.has(V.name))}return{connectionId:W,data:H}}catch(H){return console.error(`[PassthroughClient] Failed to load tools for connection ${W}:`,H),null}})),X=[],J=new Map,G=new Map,K=this.options.virtualTools??[];for(let W of K){if(J.has(W.name))continue;let Z={name:W.name,description:W.description,inputSchema:W.inputSchema,outputSchema:W.outputSchema,annotations:W.annotations,_meta:{connectionId:this.options.virtualMcp.id??"__VIRTUAL__",connectionTitle:this.options.virtualMcp.title}};X.push(Z),J.set(W.name,"__VIRTUAL__"),G.set(W.name,W)}for(let W of Q){if(!W)continue;let{connectionId:Z,data:H}=W,q=this._connections.get(Z)?.title??"";for(let V of H){let $=V.name;if(J.has($))continue;let z={...V,_meta:{connectionId:Z,connectionTitle:q,...V?._meta}};X.push(z),J.set($,Z)}}return{data:X,mappings:J,virtualTools:G}}async loadCache(Y){let Q=await this._clients,X=await Promise.all(Array.from(Q.entries()).map(async([K,W])=>{try{let Z=Y==="resources"?await W.listResources().catch(Dg({resources:[]})).then((q)=>q.resources):await W.listPrompts().catch(Dg({prompts:[]})).then((q)=>q.prompts),H=this._selectionMap.get(K),F=Y==="resources"?"selected_resources":"selected_prompts";if(H?.[F]?.length){let q=new Set(H[F]);return{connectionId:K,data:Z.filter((V)=>q.has(V.name))}}return{connectionId:K,data:Z}}catch(Z){return console.error(`[PassthroughClient] Failed to load cache for connection ${K}:`,Z),null}})),J=[],G=new Map;for(let K of X){if(!K)continue;let{connectionId:W,data:Z}=K,F=this._connections.get(W)?.title??"";for(let q of Z){let V=q.name??q.uri;if(G.has(V))continue;let $={...q,_meta:{connectionId:W,connectionTitle:F,...q?._meta}};J.push($),G.set(V,W)}}return{data:J,mappings:G}}async listTools(){return{tools:(await this._cachedTools).data}}async callTool(Y){let[Q,X]=await Promise.all([this._cachedTools,this._clients]),J=Q.mappings.get(Y.name);if(!J)return{content:[{type:"text",text:`Tool not found: ${Y.name}`}],isError:!0};if(J==="__VIRTUAL__")return this.executeVirtualTool(Y.name,Y.arguments??{},Q,X);let G=X.get(J);if(!G)return{content:[{type:"text",text:`Connection not found for tool: ${Y.name}`}],isError:!0};return await G.callTool({name:Y.name,arguments:Y.arguments??{}})}async executeVirtualTool(Y,Q,X,J){let G=X.virtualTools.get(Y);if(!G)return{content:[{type:"text",text:`Virtual tool not found: ${Y}`}],isError:!0};let K=SP0(G),W={};for(let[Z,H]of X.mappings){if(H==="__VIRTUAL__")continue;let F=J.get(H);if(!F)continue;W[Z]=async(q)=>{let V=await F.callTool({name:Z,arguments:q});if(V.structuredContent&&typeof V.structuredContent==="object")return V.structuredContent;let $=V.content;if($?.[0]?.type==="text"&&$[0].text)try{return JSON.parse($[0].text)}catch{return $[0].text}return V}}try{let H=`
1353
1353
  const __virtualToolFn = ${K.replace(/^\s*export\s+default\s+/,"").trim()};
1354
1354
  export default async (tools) => {
1355
1355
  const args = ${JSON.stringify(Q)};