@decocms/mesh 2.53.0 → 2.55.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 (145) hide show
  1. package/dist/client/assets/{AlertCircle-CUosFGNd.js → AlertCircle-DnrpASG2.js} +1 -1
  2. package/dist/client/assets/{ArrowLeft-CW6UTxaz.js → ArrowLeft-CkGaUN6o.js} +1 -1
  3. package/dist/client/assets/{ArrowUp-DQViolGS.js → ArrowUp-Cc09RZY4.js} +1 -1
  4. package/dist/client/assets/{Check-D2dSwOsr.js → Check-BYHlfTQr.js} +1 -1
  5. package/dist/client/assets/{ChevronDown-BQcg3GVd.js → ChevronDown-Cyh9WMp0.js} +1 -1
  6. package/dist/client/assets/{Code01-BE_3ESgc.js → Code01-B62YyryF.js} +1 -1
  7. package/dist/client/assets/{Copy01-DXECPSKT.js → Copy01-GHFquEvX.js} +1 -1
  8. package/dist/client/assets/{DotsHorizontal-C-G5ckUS.js → DotsHorizontal-C6El5T66.js} +1 -1
  9. package/dist/client/assets/{DotsVertical-BKPYeNIt.js → DotsVertical-DtC1yLil.js} +1 -1
  10. package/dist/client/assets/{Download01-DfSyYiGh.js → Download01-C5tBRZHe.js} +1 -1
  11. package/dist/client/assets/{Edit01-B1Z5KLbC.js → Edit01-CCTivbEj.js} +1 -1
  12. package/dist/client/assets/{File06-2DGjt4hs.js → File06-CDFdF5Nr.js} +1 -1
  13. package/dist/client/assets/{FilterLines-BnzY_lhi.js → FilterLines-4yPP_gAU.js} +1 -1
  14. package/dist/client/assets/{FlipBackward-D4CXw7be.js → FlipBackward-Bb3ib1Bh.js} +1 -1
  15. package/dist/client/assets/{Grid01-BjSv11LN.js → Grid01-C4O4Aknh.js} +1 -1
  16. package/dist/client/assets/{Home02-BZwvtXxZ.js → Home02-D2riSlnv.js} +1 -1
  17. package/dist/client/assets/{Image01-BphOjsIM.js → Image01-CYRE6pGN.js} +1 -1
  18. package/dist/client/assets/{Inbox01-DY3Scgnu.js → Inbox01-CV_5S91p.js} +1 -1
  19. package/dist/client/assets/{InfoCircle-D9eFDDch.js → InfoCircle-DnMMetUy.js} +1 -1
  20. package/dist/client/assets/{Key01-6wOTm5ju.js → Key01-CLADbyO4.js} +1 -1
  21. package/dist/client/assets/{LinkExternal01-OR0e2Yfm.js → LinkExternal01-DgcGDmdL.js} +1 -1
  22. package/dist/client/assets/{List-COpk5CVa.js → List-Cai2-K9Z.js} +1 -1
  23. package/dist/client/assets/{Loading01-BwwKYDtF.js → Loading01-B-TyaLAR.js} +1 -1
  24. package/dist/client/assets/{Lock01-CbN_GdeR.js → Lock01-Blk8_ONM.js} +1 -1
  25. package/dist/client/assets/{Pin01-BizQ6g3R.js → Pin01-GbJJn2vw.js} +1 -1
  26. package/dist/client/assets/{Play-BaS-lFep.js → Play-Bw-s0SW4.js} +1 -1
  27. package/dist/client/assets/{Plus-DFo2GFot.js → Plus-Cxc7BtkQ.js} +1 -1
  28. package/dist/client/assets/{SearchMd-Bh0QJjEM.js → SearchMd-CpKLo2Zn.js} +1 -1
  29. package/dist/client/assets/{Share07-BYXU7wNl.js → Share07-BB-7HQgT.js} +1 -1
  30. package/dist/client/assets/{Terminal-Fv-TNTFR.js → Terminal-DF70HZ2S.js} +1 -1
  31. package/dist/client/assets/{Trash01-CccVd7Bh.js → Trash01-BvwhK6Vg.js} +1 -1
  32. package/dist/client/assets/{Upload01-C2bCUV2p.js → Upload01-B6Wi4Y6P.js} +1 -1
  33. package/dist/client/assets/{Users03-CDcB69PL.js → Users03-Ba_1xVKB.js} +1 -1
  34. package/dist/client/assets/{X-DJomJuB1.js → X-CODbfs2H.js} +1 -1
  35. package/dist/client/assets/{XClose-DZXz07Zp.js → XClose-BaVIBBzB.js} +1 -1
  36. package/dist/client/assets/{agent-detail-tCJwYCyF.js → agent-detail-BwU_iOlG.js} +1 -1
  37. package/dist/client/assets/{agents-BwpkbOHR.js → agents-BIH6gREs.js} +1 -1
  38. package/dist/client/assets/{alert-dialog-BRa6_KDy.js → alert-dialog-C_OXD-MA.js} +2 -2
  39. package/dist/client/assets/{auth-catchall-N0na9_20.js → auth-catchall-BCQx1ruw.js} +1 -1
  40. package/dist/client/assets/{avatar-Ck8-q6HY.js → avatar-D8AIxV6P.js} +1 -1
  41. package/dist/client/assets/{badge-CZbH2WMS.js → badge-CpVCYFMG.js} +1 -1
  42. package/dist/client/assets/{binder-CQcXwjVp.js → binder-BEyDSNRs.js} +1 -1
  43. package/dist/client/assets/{button-B00_ydX0.js → button-B2KLvXEr.js} +1 -1
  44. package/dist/client/assets/{card-BMvxppEq.js → card-DlXZ7U9Z.js} +1 -1
  45. package/dist/client/assets/{checkbox-ImunmI7r.js → checkbox-DaoCFuj8.js} +1 -1
  46. package/dist/client/assets/{circle-alert-CpXy4Hr8.js → circle-alert-Bm5Q_veV.js} +1 -1
  47. package/dist/client/assets/{collection-detail-CYuIcnnl.js → collection-detail-C1oHfNP9.js} +1 -1
  48. package/dist/client/assets/{collection-display-button-BPtWZQEo.js → collection-display-button-BTGoT8ci.js} +1 -1
  49. package/dist/client/assets/{collection-header-BNcRdMLH.js → collection-header-Be7RY6CQ.js} +1 -1
  50. package/dist/client/assets/{collection-page-B7oO2n23.js → collection-page-RrsDnv83.js} +1 -1
  51. package/dist/client/assets/{collection-search-Dckk_Ikz.js → collection-search-DD9gszSV.js} +1 -1
  52. package/dist/client/assets/{collection-tab-DVvZlyTy.js → collection-tab-3ZZSVcZ8.js} +1 -1
  53. package/dist/client/assets/{collection-table-wrapper-BF9XEwHD.js → collection-table-wrapper-BSy03JYc.js} +1 -1
  54. package/dist/client/assets/connect-BXWPEVv8.js +1 -0
  55. package/dist/client/assets/{connection-card-CgRN8Ayh.js → connection-card-BJ8nkB6q.js} +1 -1
  56. package/dist/client/assets/{connection-detail-uKqWBtPH.js → connection-detail-DVHoUY1Q.js} +1 -1
  57. package/dist/client/assets/{connections-y7jRQMEz.js → connections-B5_ch0b8.js} +1 -1
  58. package/dist/client/assets/{constants-WkW0waEP.js → constants-BecaK2Q7.js} +1 -1
  59. package/dist/client/assets/constants-lBJFsDYc.js +1 -0
  60. package/dist/client/assets/create-organization-dialog-kmOZjs4K.js +1 -0
  61. package/dist/client/assets/{dialog-qhbGhbZx.js → dialog-cWpa0tjW.js} +1 -1
  62. package/dist/client/assets/{dropdown-menu-42ftE2oK.js → dropdown-menu-DDACOXnG.js} +1 -1
  63. package/dist/client/assets/{dynamic-plugin-layout-DKOCLn6K.js → dynamic-plugin-layout-nceYO9tV.js} +1 -1
  64. package/dist/client/assets/{empty-state-CS9-P6od.js → empty-state-BRRevprM.js} +1 -1
  65. package/dist/client/assets/{empty-state-BUcEAoKI.js → empty-state-CysqrplM.js} +1 -1
  66. package/dist/client/assets/env-vars-editor-CyAPCgjC.js +1 -0
  67. package/dist/client/assets/{error-boundary-B15bMSig.js → error-boundary-D2FqiSoM.js} +1 -1
  68. package/dist/client/assets/{extract-connection-data-BDL-TEv2.js → extract-connection-data-DG_diqa3.js} +1 -1
  69. package/dist/client/assets/{file-browser-B7pbZypi.js → file-browser-BbtVlE62.js} +2 -2
  70. package/dist/client/assets/{form-BtpD-Mg0.js → form-ChHRavtv.js} +1 -1
  71. package/dist/client/assets/{grid-view-DvOSXag8.js → grid-view-BPn6qgmX.js} +1 -1
  72. package/dist/client/assets/{home-C_lsZqgH.js → home-hstgKRny.js} +1 -1
  73. package/dist/client/assets/index-B5YD-rJR.js +1 -0
  74. package/dist/client/assets/{index-DirwRnbJ.js → index-CKyh6XBg.js} +1 -1
  75. package/dist/client/assets/{index-AUAYH-kQ.js → index-DIxYn0kb.js} +64 -64
  76. package/dist/client/assets/{index-DL0E9kqQ.js → index-DhY2K4tp.js} +12 -12
  77. package/dist/client/assets/index-mQwl56Q0.js +1 -0
  78. package/dist/client/assets/{index-Czllqz-2.js → index-rms_W4V6.js} +33 -33
  79. package/dist/client/assets/infiniteQueryObserver-C_cEPa52.js +1 -0
  80. package/dist/client/assets/{input-CCqm-6CK.js → input-BkeUe06e.js} +1 -1
  81. package/dist/client/assets/{layout-BFy9cXIQ.js → layout-CdihDKq7.js} +1 -1
  82. package/dist/client/assets/{localstorage-keys-KyET-T_h.js → localstorage-keys-BkUFqNvo.js} +1 -1
  83. package/dist/client/assets/login-B4do1VXN.js +1 -0
  84. package/dist/client/assets/mcp-oauth-Z4D16Uoq.js +1 -0
  85. package/dist/client/assets/{mcp-server-card-m9JuE0nb.js → mcp-server-card-ZLodfuxh.js} +1 -1
  86. package/dist/client/assets/{mcp-server-detail-BsBLG9_9.js → mcp-server-detail-ChazypwB.js} +2 -2
  87. package/dist/client/assets/{members-xwUNGYDi.js → members-DIUQDq49.js} +1 -1
  88. package/dist/client/assets/{monaco-editor-Q_er1L0I.js → monaco-editor-CF8xOd0f.js} +4 -4
  89. package/dist/client/assets/{monitoring-_VT5f5Bq.js → monitoring-BXGU01Kc.js} +3 -3
  90. package/dist/client/assets/{oauth-callback-DWkO610z.js → oauth-callback-CqnMpdvf.js} +1 -1
  91. package/dist/client/assets/{page-DFJw1vc5.js → page-CLam7tfm.js} +1 -1
  92. package/dist/client/assets/{page-0dLxS1h-.js → page-DcHPZKZc.js} +1 -1
  93. package/dist/client/assets/{pin-to-sidebar-button-FlRaE5CN.js → pin-to-sidebar-button-xde8P8_T.js} +1 -1
  94. package/dist/client/assets/{plugin-empty-state-rUw49Sla.js → plugin-empty-state-DBQd886H.js} +1 -1
  95. package/dist/client/assets/{plugin-header-DBOF23Sq.js → plugin-header-BzN93bFk.js} +1 -1
  96. package/dist/client/assets/{plugins-BN-3RFdx.js → plugins-DTGBld4c.js} +1 -1
  97. package/dist/client/assets/{popover-DB55iMbc.js → popover-BQ4fAaba.js} +1 -1
  98. package/dist/client/assets/{registry-utils-C6h9Gx0x.js → registry-utils-CubAr1ep.js} +1 -1
  99. package/dist/client/assets/{resizable-CJYOs9td.js → resizable-CBbQ2mtO.js} +1 -1
  100. package/dist/client/assets/{resource-tabs-CwoGib18.js → resource-tabs-PgIUUqJg.js} +1 -1
  101. package/dist/client/assets/{select-BQyV0pOn.js → select-DtbOgYEp.js} +1 -1
  102. package/dist/client/assets/{settings-DJgCVswE.js → settings-Bpg3bFrL.js} +1 -1
  103. package/dist/client/assets/shell-layout-OPZoFrI9.js +3 -0
  104. package/dist/client/assets/spinner-BtXJc_eZ.js +1 -0
  105. package/dist/client/assets/store-invite-BEl6VykZ.js +1 -0
  106. package/dist/client/assets/{switch-RY18eFtF.js → switch-DsnDxQXG.js} +1 -1
  107. package/dist/client/assets/{textarea-CMLduiYq.js → textarea-BANZCPie.js} +1 -1
  108. package/dist/client/assets/{tool-set-selector-pswCeL17.js → tool-set-selector-CqX9WN4g.js} +1 -1
  109. package/dist/client/assets/{tools-list-CaIW22pA.js → tools-list-BRzmSp1i.js} +1 -1
  110. package/dist/client/assets/{tooltip-Dpvr0rXq.js → tooltip-Dwcc1k71.js} +1 -1
  111. package/dist/client/assets/{typewriter-title-DonUWsRZ.js → typewriter-title-Bay0uuB9.js} +2 -2
  112. package/dist/client/assets/{use-binding-DETlsMC2.js → use-binding--VZ7Y5Ef.js} +1 -1
  113. package/dist/client/assets/{use-collections-DGIB8J28.js → use-collections-8Kj36wYP.js} +1 -1
  114. package/dist/client/assets/{use-connection-B5trZtD3.js → use-connection-DfqjO6nz.js} +1 -1
  115. package/dist/client/assets/{use-create-virtual-mcp-C1gVg8Cb.js → use-create-virtual-mcp-lWx9_XWS.js} +1 -1
  116. package/dist/client/assets/{use-list-state-DmUxkG5Z.js → use-list-state-vBhSzyur.js} +1 -1
  117. package/dist/client/assets/{use-mcp-prompts-Dj17zuNr.js → use-mcp-prompts-DioGpWDr.js} +1 -1
  118. package/dist/client/assets/use-members-E4uqx9v1.js +1 -0
  119. package/dist/client/assets/{use-mobile-8fEdz_YY.js → use-mobile-C29nHXu6.js} +1 -1
  120. package/dist/client/assets/{use-organization-settings-U0agG2h9.js → use-organization-settings-BSUJceGn.js} +1 -1
  121. package/dist/client/assets/{use-virtual-mcp-Bi5F5F6f.js → use-virtual-mcp-BsVUpxvH.js} +1 -1
  122. package/dist/client/assets/useInfiniteQuery-BTaBTa8y.js +1 -0
  123. package/dist/client/assets/{useMutation-C9EFCZz_.js → useMutation-5hMjZ_Ks.js} +1 -1
  124. package/dist/client/assets/useQuery-D0z2lKje.js +1 -0
  125. package/dist/client/assets/{view-mode-toggle-KIDFLeEj.js → view-mode-toggle-CLtTg2VY.js} +1 -1
  126. package/dist/client/assets/{workflow-daJYPL0_.js → workflow-Iz076qQ_.js} +1 -1
  127. package/dist/client/index.html +1 -1
  128. package/dist/server/cli.js +112 -112
  129. package/dist/server/migrate.js +5 -5
  130. package/dist/server/server.js +109 -109
  131. package/package.json +1 -1
  132. package/dist/client/assets/connect-DJyguwtd.js +0 -1
  133. package/dist/client/assets/constants-CApA9LvW.js +0 -1
  134. package/dist/client/assets/create-organization-dialog-Dt_N2MMJ.js +0 -1
  135. package/dist/client/assets/env-vars-editor-B9AW86vg.js +0 -1
  136. package/dist/client/assets/index-3bBDO_0b.js +0 -1
  137. package/dist/client/assets/index-CxWk7Fwg.js +0 -1
  138. package/dist/client/assets/infiniteQueryObserver-cVAe_2FL.js +0 -1
  139. package/dist/client/assets/login-YfQaRXOk.js +0 -1
  140. package/dist/client/assets/mcp-oauth-A6Csj-pc.js +0 -1
  141. package/dist/client/assets/shell-layout-BafaBoHC.js +0 -3
  142. package/dist/client/assets/spinner-BndxvZpI.js +0 -1
  143. package/dist/client/assets/use-members-D9yKU0hW.js +0 -1
  144. package/dist/client/assets/useInfiniteQuery-Cl5a5iyP.js +0 -1
  145. package/dist/client/assets/useQuery-Gixvofai.js +0 -1
@@ -381,7 +381,7 @@ ${G}
381
381
  `;break;case"id":Z=L.includes("\x00")?void 0:L;break;case"retry":/^\d+$/.test(L)?J(parseInt(L,10)):Q(new z90(`Invalid \`retry\` value: "${L}"`,{type:"invalid-retry",value:L,line:M}));break;default:Q(new z90(`Unknown field "${D.length>20?`${D.slice(0,20)}\u2026`:D}"`,{type:"unknown-field",field:D,value:L,line:M}));break}}function B(){H.length>0&&X({id:Z,event:F||void 0,data:H.endsWith(`
382
382
  `)?H.slice(0,-1):H}),Z=void 0,H="",F=""}function U(D={}){K&&D.consume&&q(K),W=!0,Z=void 0,H="",F="",K=""}return{feed:V,reset:U}}function Bp4(Y){let X=[],Q="",J=0;for(;J<Y.length;){let G=Y.indexOf("\r",J),K=Y.indexOf(`
383
383
  `,J),W=-1;if(G!==-1&&K!==-1?W=Math.min(G,K):G!==-1?G===Y.length-1?W=-1:W=G:K!==-1&&(W=K),W===-1){Q=Y.slice(J);break}else{let Z=Y.slice(J,W);X.push(Z),J=W+1,Y[J-1]==="\r"&&Y[J]===`
384
- `&&J++}}return[X,Q]}var z90;var B90=m(()=>{z90=class z90 extends Error{constructor(Y,X){super(Y),this.name="ParseError",this.type=X.type,this.field=X.field,this.value=X.value,this.line=X.line}}});var U90;var cK6=m(()=>{B90();U90=class U90 extends TransformStream{constructor({onError:Y,onRetry:X,onComment:Q}={}){let J;super({start(G){J=$f({onEvent:(K)=>{G.enqueue(K)},onError(K){Y==="terminate"?G.error(K):typeof Y=="function"&&Y(K)},onRetry:X,onComment:Q})},transform(G){J.feed(G)}})}}});class jB{constructor(Y,X){this._hasCompletedAuthFlow=!1,this._url=Y,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=X?.requestInit,this._authProvider=X?.authProvider,this._fetch=X?.fetch,this._fetchWithInit=ty(X?.fetch,X?.requestInit),this._sessionId=X?.sessionId,this._reconnectionOptions=X?.reconnectionOptions??Up4}async _authThenStart(){if(!this._authProvider)throw new GQ("No auth provider");let Y;try{Y=await D7(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(X){throw this.onerror?.(X),X}if(Y!=="AUTHORIZED")throw new GQ;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let Y={};if(this._authProvider){let Q=await this._authProvider.tokens();if(Q)Y.Authorization=`Bearer ${Q.access_token}`}if(this._sessionId)Y["mcp-session-id"]=this._sessionId;if(this._protocolVersion)Y["mcp-protocol-version"]=this._protocolVersion;let X=TB(this._requestInit?.headers);return new Headers({...Y,...X})}async _startOrAuthSse(Y){let{resumptionToken:X}=Y;try{let Q=await this._commonHeaders();if(Q.set("Accept","text/event-stream"),X)Q.set("last-event-id",X);let J=await(this._fetch??fetch)(this._url,{method:"GET",headers:Q,signal:this._abortController?.signal});if(!J.ok){if(await J.body?.cancel(),J.status===401&&this._authProvider)return await this._authThenStart();if(J.status===405)return;throw new KV(J.status,`Failed to open SSE stream: ${J.statusText}`)}this._handleSseStream(J.body,Y,!0)}catch(Q){throw this.onerror?.(Q),Q}}_getNextReconnectionDelay(Y){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let X=this._reconnectionOptions.initialReconnectionDelay,Q=this._reconnectionOptions.reconnectionDelayGrowFactor,J=this._reconnectionOptions.maxReconnectionDelay;return Math.min(X*Math.pow(Q,Y),J)}_scheduleReconnection(Y,X=0){let Q=this._reconnectionOptions.maxRetries;if(X>=Q){this.onerror?.(Error(`Maximum reconnection attempts (${Q}) exceeded.`));return}let J=this._getNextReconnectionDelay(X);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(Y).catch((G)=>{this.onerror?.(Error(`Failed to reconnect SSE stream: ${G instanceof Error?G.message:String(G)}`)),this._scheduleReconnection(Y,X+1)})},J)}_handleSseStream(Y,X,Q){if(!Y)return;let{onresumptiontoken:J,replayMessageId:G}=X,K,W=!1,Z=!1;(async()=>{try{let F=Y.pipeThrough(new TextDecoderStream).pipeThrough(new U90({onRetry:($)=>{this._serverRetryMs=$}})).getReader();while(!0){let{value:$,done:B}=await F.read();if(B)break;if($.id)K=$.id,W=!0,J?.($.id);if(!$.data)continue;if(!$.event||$.event==="message")try{let U=bQ.parse(JSON.parse($.data));if(y5(U)){if(Z=!0,G!==void 0)U.id=G}this.onmessage?.(U)}catch(U){this.onerror?.(U)}}if((Q||W)&&!Z&&this._abortController&&!this._abortController.signal.aborted)this._scheduleReconnection({resumptionToken:K,onresumptiontoken:J,replayMessageId:G},0)}catch(F){if(this.onerror?.(Error(`SSE stream disconnected: ${F}`)),(Q||W)&&!Z&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:K,onresumptiontoken:J,replayMessageId:G},0)}catch($){this.onerror?.(Error(`Failed to reconnect: ${$ instanceof Error?$.message:String($)}`))}}})()}async start(){if(this._abortController)throw Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(Y){if(!this._authProvider)throw new GQ("No auth provider");if(await D7(this._authProvider,{serverUrl:this._url,authorizationCode:Y,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new GQ("Failed to authorize")}async close(){if(this._reconnectionTimeout)clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0;this._abortController?.abort(),this.onclose?.()}async send(Y,X){try{let{resumptionToken:Q,onresumptiontoken:J}=X||{};if(Q){this._startOrAuthSse({resumptionToken:Q,replayMessageId:$7(Y)?Y.id:void 0}).catch((q)=>this.onerror?.(q));return}let G=await this._commonHeaders();G.set("content-type","application/json"),G.set("accept","application/json, text/event-stream");let K={...this._requestInit,method:"POST",headers:G,body:JSON.stringify(Y),signal:this._abortController?.signal},W=await(this._fetch??fetch)(this._url,K),Z=W.headers.get("mcp-session-id");if(Z)this._sessionId=Z;if(!W.ok){let q=await W.text().catch(()=>null);if(W.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new KV(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:$,scope:B}=SB(W);if(this._resourceMetadataUrl=$,this._scope=B,await D7(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new GQ;return this._hasCompletedAuthFlow=!0,this.send(Y)}if(W.status===403&&this._authProvider){let{resourceMetadataUrl:$,scope:B,error:U}=SB(W);if(U==="insufficient_scope"){let D=W.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===D)throw new KV(403,"Server returned 403 after trying upscoping");if(B)this._scope=B;if($)this._resourceMetadataUrl=$;if(this._lastUpscopingHeader=D??void 0,await D7(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new GQ;return this.send(Y)}}throw new KV(W.status,`Error POSTing to endpoint: ${q}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,W.status===202){if(await W.body?.cancel(),G56(Y))this._startOrAuthSse({resumptionToken:void 0}).catch((q)=>this.onerror?.(q));return}let F=(Array.isArray(Y)?Y:[Y]).filter((q)=>("method"in q)&&("id"in q)&&q.id!==void 0).length>0,V=W.headers.get("content-type");if(F)if(V?.includes("text/event-stream"))this._handleSseStream(W.body,{onresumptiontoken:J},!1);else if(V?.includes("application/json")){let q=await W.json(),$=Array.isArray(q)?q.map((B)=>bQ.parse(B)):[bQ.parse(q)];for(let B of $)this.onmessage?.(B)}else throw await W.body?.cancel(),new KV(-1,`Unexpected content type: ${V}`);else await W.body?.cancel()}catch(Q){throw this.onerror?.(Q),Q}}get sessionId(){return this._sessionId}async terminateSession(){if(!this._sessionId)return;try{let Y=await this._commonHeaders(),X={...this._requestInit,method:"DELETE",headers:Y,signal:this._abortController?.signal},Q=await(this._fetch??fetch)(this._url,X);if(await Q.body?.cancel(),!Q.ok&&Q.status!==405)throw new KV(Q.status,`Failed to terminate session: ${Q.statusText}`);this._sessionId=void 0}catch(Y){throw this.onerror?.(Y),Y}}setProtocolVersion(Y){this._protocolVersion=Y}get protocolVersion(){return this._protocolVersion}async resumeStream(Y,X){await this._startOrAuthSse({resumptionToken:Y,onresumptiontoken:X?.onresumptiontoken})}}var Up4,KV;var zf=m(()=>{xQ();qf();cK6();Up4={initialReconnectionDelay:1000,maxReconnectionDelay:30000,reconnectionDelayGrowFactor:1.5,maxRetries:2};KV=class KV extends Error{constructor(Y,X){super(`Streamable HTTP error: ${X}`);this.code=Y}}});var D90=m(()=>{zf()});var Bf=m(()=>{sy();rF();D90()});function O90(Y){return{id:FP.REGISTRY(Y),title:"Deco Store",description:"Official deco MCP registry with curated integrations",connection_type:"HTTP",connection_url:"https://api.decocms.com/mcp/registry",icon:"https://assets.decocache.com/decocms/00ccf6c3-9e13-4517-83b0-75ab84554bb9/596364c63320075ca58483660156b6d9de9b526e.png",app_name:"deco-registry",app_id:null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!0,type:"registry"}}}function N90(){return{id:"community-registry",title:"MCP Registry",description:"Community MCP registry with thousands of handy MCPs",connection_type:"HTTP",connection_url:"https://sites-registry.decocache.com/mcp",icon:"https://assets.decocache.com/decocms/cd7ca472-0f72-463a-b0de-6e44bdd0f9b4/mcp.png",app_name:"mcp-registry",app_id:null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!0,type:"registry"}}}function L90(Y,X){return{id:FP.SELF(X),title:"Mesh MCP",description:"The MCP for the mesh API",connection_type:"HTTP",connection_url:`${Y}/mcp/self`,icon:"https://assets.decocache.com/mcp/09e44283-f47d-4046-955f-816d227c626f/app.png",app_name:"@deco/management-mcp",connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!0,type:"self"}}}var FP;var Uf=m(()=>{FP={SELF:(Y)=>`${Y}_self`,REGISTRY:(Y)=>`${Y}_registry`,COMMUNITY_REGISTRY:(Y)=>`${Y}_community-registry`}});var iK6=m(()=>{k40();N_();Bf();Uf()});var aK6=m(()=>{rF()});var rK6=m(()=>{rF()});var oK6=m(()=>{_40();N_();Bf();Uf()});var sK6=m(()=>{N_();iK6();Bf();h40();aK6();rK6();oK6()});var xp4,up4,gp4,mp4,Df,tK6,eK6;var Y36=m(()=>{Y6();xp4=N.object({authorizationEndpoint:N.string().url(),tokenEndpoint:N.string().url(),introspectionEndpoint:N.string().url().optional(),clientId:N.string(),clientSecret:N.string().optional(),scopes:N.array(N.string()),grantType:N.enum(["authorization_code","client_credentials"])}),up4=N.object({name:N.string(),description:N.string().optional(),inputSchema:N.record(N.string(),N.unknown()),outputSchema:N.record(N.string(),N.unknown()).optional()}),gp4=N.object({headers:N.record(N.string(),N.string()).optional()}),mp4=N.object({command:N.string().describe("Command to run (e.g., 'npx', 'node')"),args:N.array(N.string()).optional().describe("Command arguments"),cwd:N.string().optional().describe("Working directory"),envVars:N.record(N.string(),N.string()).optional().describe("Environment variables (encrypted in storage)")}),Df=N.object({id:N.string().describe("Unique identifier for the connection"),title:N.string().describe("Human-readable name for the connection"),created_at:N.string().describe("When the connection was created"),updated_at:N.string().describe("When the connection was last updated"),created_by:N.string().describe("User ID who created the connection"),updated_by:N.string().optional().describe("User ID who last updated the connection"),organization_id:N.string().describe("Organization ID this connection belongs to"),description:N.string().nullable().describe("Description of the connection"),icon:N.string().nullable().describe("Icon URL for the connection"),app_name:N.string().nullable().describe("Associated app name"),app_id:N.string().nullable().describe("Associated app ID"),connection_type:N.enum(["HTTP","SSE","Websocket","STDIO","VIRTUAL"]).describe("Type of connection"),connection_url:N.string().nullable().describe("URL for HTTP/SSE/WebSocket connections. virtual://$id for VIRTUAL. Null for STDIO."),connection_token:N.string().nullable().describe("Authentication token (for HTTP connections)"),connection_headers:N.union([mp4,gp4]).nullable().describe("Connection parameters. HTTP: { headers }. STDIO: { command, args, cwd, envVars }"),oauth_config:xp4.nullable().describe("OAuth configuration"),configuration_state:N.record(N.string(),N.unknown()).nullable().describe("Configuration state (decrypted)"),configuration_scopes:N.array(N.string()).nullable().optional().describe("Configuration scopes"),metadata:N.record(N.string(),N.unknown()).nullable().describe("Additional metadata (includes repository info)"),tools:N.array(up4).nullable().describe("Discovered tools from MCP"),bindings:N.array(N.string()).nullable().describe("Detected bindings"),status:N.enum(["active","inactive","error"]).describe("Current status")}),tK6=Df.omit({created_at:!0,updated_at:!0,created_by:!0,updated_by:!0,organization_id:!0,tools:!0,bindings:!0,status:!0}).partial({id:!0,description:!0,icon:!0,app_name:!0,app_id:!0,connection_url:!0,connection_token:!0,connection_headers:!0,oauth_config:!0,configuration_state:!0,configuration_scopes:!0,metadata:!0}),eK6=Df.partial()});var T90,lp4,X36,Q36,J36;var G36=m(()=>{Y6();T90=N.enum(["inclusion","exclusion"]).describe("Tool selection mode: 'inclusion' = include selected (default), 'exclusion' = exclude selected"),lp4=N.object({connection_id:N.string().describe("Connection ID"),selected_tools:N.array(N.string()).nullable().describe("Selected tool names. With 'inclusion' mode: null = all tools included. With 'exclusion' mode: null = entire connection excluded"),selected_resources:N.array(N.string()).nullable().describe("Selected resource URIs or patterns. Supports * and ** wildcards for pattern matching. With 'inclusion' mode: null = all resources included."),selected_prompts:N.array(N.string()).nullable().describe("Selected prompt names. With 'inclusion' mode: null = all prompts included. With 'exclusion' mode: null = entire connection excluded.")}),X36=N.object({id:N.string().describe("Unique identifier for the virtual MCP"),title:N.string().describe("Human-readable name for the virtual MCP"),description:N.string().nullable().describe("Description of the virtual MCP"),icon:N.string().nullable().optional().describe("Icon URL for the virtual MCP"),created_at:N.string().describe("When the virtual MCP was created"),updated_at:N.string().describe("When the virtual MCP was last updated"),created_by:N.string().describe("User ID who created the virtual MCP"),updated_by:N.string().optional().describe("User ID who last updated the virtual MCP"),organization_id:N.string().describe("Organization ID this virtual MCP belongs to"),tool_selection_mode:T90.describe("Tool selection mode: 'inclusion' = include selected, 'exclusion' = exclude selected"),status:N.enum(["active","inactive"]).describe("Current status"),metadata:N.object({instructions:N.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:N.array(lp4).describe("Connections with their selected tools (behavior depends on tool_selection_mode)")}),Q36=N.object({title:N.string().min(1).max(255).describe("Name for the virtual MCP"),description:N.string().nullable().optional().describe("Optional description"),tool_selection_mode:T90.optional().default("inclusion").describe("Tool selection mode (defaults to 'inclusion')"),icon:N.string().nullable().optional().describe("Optional icon URL"),status:N.enum(["active","inactive"]).optional().default("active").describe("Initial status"),metadata:N.object({instructions:N.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:N.array(N.object({connection_id:N.string().describe("Connection ID"),selected_tools:N.array(N.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:N.array(N.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:N.array(N.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).describe("Connections to include/exclude (can be empty for exclusion mode)")}),J36=N.object({title:N.string().min(1).max(255).optional().describe("New name"),description:N.string().nullable().optional().describe("New description (null to clear)"),tool_selection_mode:T90.optional().describe("New tool selection mode"),icon:N.string().nullable().optional().describe("New icon URL (null to clear)"),status:N.enum(["active","inactive"]).optional().describe("New status"),metadata:N.object({instructions:N.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:N.array(N.object({connection_id:N.string().describe("Connection ID"),selected_tools:N.array(N.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:N.array(N.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:N.array(N.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).optional().describe("New connections (replaces existing)")})});var W36=m(()=>{Y36();G36()});var Z36=m(()=>{qf()});var E90=m(()=>{_40();sK6();W36();D90();rF();Z36();Uf()});function qP(Y){return Y!==null&&Y!==void 0&&"command"in Y}function Of(Y){if(!Y||!Y.startsWith("virtual://"))return null;return Y.replace("virtual://","")}function Nf(Y){return`virtual://${Y}`}var ap4,rp4,op4,sp4,tp4,cJ,q36,$36;var Z3=m(()=>{Y6();ap4=N.object({authorizationEndpoint:N.string().url(),tokenEndpoint:N.string().url(),introspectionEndpoint:N.string().url().optional(),clientId:N.string(),clientSecret:N.string().optional(),scopes:N.array(N.string()),grantType:N.enum(["authorization_code","client_credentials"])}),rp4=N.object({title:N.string().optional(),readOnlyHint:N.boolean().optional(),destructiveHint:N.boolean().optional(),idempotentHint:N.boolean().optional(),openWorldHint:N.boolean().optional()}),op4=N.object({name:N.string(),description:N.string().optional(),inputSchema:N.record(N.string(),N.unknown()),outputSchema:N.record(N.string(),N.unknown()).optional(),annotations:rp4.optional(),_meta:N.record(N.string(),N.unknown()).optional()}),sp4=N.object({headers:N.record(N.string(),N.string()).optional()}),tp4=N.object({command:N.string().describe("Command to run (e.g., 'npx', 'node')"),args:N.array(N.string()).optional().describe("Command arguments"),cwd:N.string().optional().describe("Working directory"),envVars:N.record(N.string(),N.string()).optional().describe("Environment variables (encrypted in storage)")}),cJ=N.object({id:N.string().describe("Unique identifier for the connection"),title:N.string().describe("Human-readable name for the connection"),created_at:N.string().describe("When the connection was created"),updated_at:N.string().describe("When the connection was last updated"),created_by:N.string().describe("User ID who created the connection"),updated_by:N.string().optional().describe("User ID who last updated the connection"),organization_id:N.string().describe("Organization ID this connection belongs to"),description:N.string().nullable().describe("Description of the connection"),icon:N.string().nullable().describe("Icon URL for the connection"),app_name:N.string().nullable().describe("Associated app name"),app_id:N.string().nullable().describe("Associated app ID"),connection_type:N.enum(["HTTP","SSE","Websocket","STDIO","VIRTUAL"]).describe("Type of connection"),connection_url:N.string().nullable().describe("URL for HTTP/SSE/WebSocket connections. virtual://$id for VIRTUAL. Null for STDIO."),connection_token:N.string().nullable().describe("Authentication token (for HTTP connections)"),connection_headers:N.union([tp4,sp4]).nullable().describe("Connection parameters. HTTP: { headers }. STDIO: { command, args, cwd, envVars }"),oauth_config:ap4.nullable().describe("OAuth configuration"),configuration_state:N.record(N.string(),N.unknown()).nullable().describe("Configuration state (decrypted)"),configuration_scopes:N.array(N.string()).nullable().optional().describe("Configuration scopes"),metadata:N.record(N.string(),N.unknown()).nullable().describe("Additional metadata (includes repository info)"),tools:N.array(op4).nullable().describe("Discovered tools from MCP"),bindings:N.array(N.string()).nullable().describe("Detected bindings"),status:N.enum(["active","inactive","error"]).describe("Current status")}),q36=cJ.omit({created_at:!0,updated_at:!0,created_by:!0,updated_by:!0,organization_id:!0,tools:!0,bindings:!0,status:!0}).partial({id:!0,description:!0,icon:!0,app_name:!0,app_id:!0,connection_url:!0,connection_token:!0,connection_headers:!0,oauth_config:!0,configuration_state:!0,configuration_scopes:!0,metadata:!0}),$36=cJ.partial()});var z36="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";import{webcrypto as B36}from"crypto";function Yc4(Y){if(!HV||HV.length<Y)HV=Buffer.allocUnsafe(Y*ep4),B36.getRandomValues(HV),kB=0;else if(kB+Y>HV.length)B36.getRandomValues(HV),kB=0;kB+=Y}function U36(Y=21){Yc4(Y|=0);let X="";for(let Q=kB-Y;Q<kB;Q++)X+=z36[HV[Q]&63];return X}var ep4=128,HV,kB;var D36=()=>{};function vB(Y){return`${Y}_${U36()}`}var Lf=m(()=>{D36()});function Qc4(Y){let X=globalThis.DOMException;return typeof X=="function"?new X(Y,"SyntaxError"):SyntaxError(Y)}function S90(Y){return Y instanceof Error?"errors"in Y&&Array.isArray(Y.errors)?Y.errors.map(S90).join(", "):("cause"in Y)&&Y.cause instanceof Error?`${Y}: ${S90(Y.cause)}`:Y.message:`${Y}`}function O36(Y){return{type:Y.type,message:Y.message,code:Y.code,defaultPrevented:Y.defaultPrevented,cancelable:Y.cancelable,timeStamp:Y.timeStamp}}function Jc4(){let Y="document"in globalThis?globalThis.document:void 0;return Y&&typeof Y=="object"&&"baseURI"in Y&&typeof Y.baseURI=="string"?Y.baseURI:void 0}var R90,L36=(Y)=>{throw TypeError(Y)},b90=(Y,X,Q)=>X.has(Y)||L36("Cannot "+Q),j4=(Y,X,Q)=>(b90(Y,X,"read from private field"),Q?Q.call(Y):X.get(Y)),D9=(Y,X,Q)=>X.has(Y)?L36("Cannot add the same private member more than once"):X instanceof WeakSet?X.add(Y):X.set(Y,Q),M8=(Y,X,Q,J)=>(b90(Y,X,"write to private field"),X.set(Y,Q),Q),dW=(Y,X,Q)=>(b90(Y,X,"access private method"),Q),WQ,FV,_B,Mf,wf,BP,hB,UP,K3,yB,bB,fB,$P,d5,j90,k90,v90,N36,_90,y90,zP,f90,h90,xB;var M36=m(()=>{B90();R90=class R90 extends Event{constructor(Y,X){var Q,J;super(Y),this.code=(Q=X==null?void 0:X.code)!=null?Q:void 0,this.message=(J=X==null?void 0:X.message)!=null?J:void 0}[Symbol.for("nodejs.util.inspect.custom")](Y,X,Q){return Q(O36(this),X)}[Symbol.for("Deno.customInspect")](Y,X){return Y(O36(this),X)}};xB=class xB extends EventTarget{constructor(Y,X){var Q,J;super(),D9(this,d5),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,D9(this,WQ),D9(this,FV),D9(this,_B),D9(this,Mf),D9(this,wf),D9(this,BP),D9(this,hB),D9(this,UP,null),D9(this,K3),D9(this,yB),D9(this,bB,null),D9(this,fB,null),D9(this,$P,null),D9(this,k90,async(G)=>{var K;j4(this,yB).reset();let{body:W,redirected:Z,status:H,headers:F}=G;if(H===204){dW(this,d5,zP).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(Z?M8(this,_B,new URL(G.url)):M8(this,_B,void 0),H!==200){dW(this,d5,zP).call(this,`Non-200 status code (${H})`,H);return}if(!(F.get("content-type")||"").startsWith("text/event-stream")){dW(this,d5,zP).call(this,'Invalid content type, expected "text/event-stream"',H);return}if(j4(this,WQ)===this.CLOSED)return;M8(this,WQ,this.OPEN);let V=new Event("open");if((K=j4(this,$P))==null||K.call(this,V),this.dispatchEvent(V),typeof W!="object"||!W||!("getReader"in W)){dW(this,d5,zP).call(this,"Invalid response body, expected a web ReadableStream",H),this.close();return}let q=new TextDecoder,$=W.getReader(),B=!0;do{let{done:U,value:D}=await $.read();D&&j4(this,yB).feed(q.decode(D,{stream:!U})),U&&(B=!1,j4(this,yB).reset(),dW(this,d5,f90).call(this))}while(B)}),D9(this,v90,(G)=>{M8(this,K3,void 0),!(G.name==="AbortError"||G.type==="aborted")&&dW(this,d5,f90).call(this,S90(G))}),D9(this,_90,(G)=>{typeof G.id=="string"&&M8(this,UP,G.id);let K=new MessageEvent(G.event||"message",{data:G.data,origin:j4(this,_B)?j4(this,_B).origin:j4(this,FV).origin,lastEventId:G.id||""});j4(this,fB)&&(!G.event||G.event==="message")&&j4(this,fB).call(this,K),this.dispatchEvent(K)}),D9(this,y90,(G)=>{M8(this,BP,G)}),D9(this,h90,()=>{M8(this,hB,void 0),j4(this,WQ)===this.CONNECTING&&dW(this,d5,j90).call(this)});try{if(Y instanceof URL)M8(this,FV,Y);else if(typeof Y=="string")M8(this,FV,new URL(Y,Jc4()));else throw Error("Invalid URL")}catch{throw Qc4("An invalid or illegal string was specified")}M8(this,yB,$f({onEvent:j4(this,_90),onRetry:j4(this,y90)})),M8(this,WQ,this.CONNECTING),M8(this,BP,3000),M8(this,wf,(Q=X==null?void 0:X.fetch)!=null?Q:globalThis.fetch),M8(this,Mf,(J=X==null?void 0:X.withCredentials)!=null?J:!1),dW(this,d5,j90).call(this)}get readyState(){return j4(this,WQ)}get url(){return j4(this,FV).href}get withCredentials(){return j4(this,Mf)}get onerror(){return j4(this,bB)}set onerror(Y){M8(this,bB,Y)}get onmessage(){return j4(this,fB)}set onmessage(Y){M8(this,fB,Y)}get onopen(){return j4(this,$P)}set onopen(Y){M8(this,$P,Y)}addEventListener(Y,X,Q){let J=X;super.addEventListener(Y,J,Q)}removeEventListener(Y,X,Q){let J=X;super.removeEventListener(Y,J,Q)}close(){j4(this,hB)&&clearTimeout(j4(this,hB)),j4(this,WQ)!==this.CLOSED&&(j4(this,K3)&&j4(this,K3).abort(),M8(this,WQ,this.CLOSED),M8(this,K3,void 0))}};WQ=new WeakMap,FV=new WeakMap,_B=new WeakMap,Mf=new WeakMap,wf=new WeakMap,BP=new WeakMap,hB=new WeakMap,UP=new WeakMap,K3=new WeakMap,yB=new WeakMap,bB=new WeakMap,fB=new WeakMap,$P=new WeakMap,d5=new WeakSet,j90=function(){M8(this,WQ,this.CONNECTING),M8(this,K3,new AbortController),j4(this,wf)(j4(this,FV),dW(this,d5,N36).call(this)).then(j4(this,k90)).catch(j4(this,v90))},k90=new WeakMap,v90=new WeakMap,N36=function(){var Y;let X={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...j4(this,UP)?{"Last-Event-ID":j4(this,UP)}:void 0},cache:"no-store",signal:(Y=j4(this,K3))==null?void 0:Y.signal};return"window"in globalThis&&(X.credentials=this.withCredentials?"include":"same-origin"),X},_90=new WeakMap,y90=new WeakMap,zP=function(Y,X){var Q;j4(this,WQ)!==this.CLOSED&&M8(this,WQ,this.CLOSED);let J=new R90("error",{code:X,message:Y});(Q=j4(this,bB))==null||Q.call(this,J),this.dispatchEvent(J)},f90=function(Y,X){var Q;if(j4(this,WQ)===this.CLOSED)return;M8(this,WQ,this.CONNECTING);let J=new R90("error",{code:X,message:Y});(Q=j4(this,bB))==null||Q.call(this,J),this.dispatchEvent(J),M8(this,hB,setTimeout(j4(this,h90),j4(this,BP)))},h90=new WeakMap,xB.CONNECTING=0,xB.OPEN=1,xB.CLOSED=2});class DP{constructor(Y,X){this._url=Y,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=X?.eventSourceInit,this._requestInit=X?.requestInit,this._authProvider=X?.authProvider,this._fetch=X?.fetch,this._fetchWithInit=ty(X?.fetch,X?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new GQ("No auth provider");let Y;try{Y=await D7(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(X){throw this.onerror?.(X),X}if(Y!=="AUTHORIZED")throw new GQ;return await this._startOrAuth()}async _commonHeaders(){let Y={};if(this._authProvider){let Q=await this._authProvider.tokens();if(Q)Y.Authorization=`Bearer ${Q.access_token}`}if(this._protocolVersion)Y["mcp-protocol-version"]=this._protocolVersion;let X=TB(this._requestInit?.headers);return new Headers({...Y,...X})}_startOrAuth(){let Y=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((X,Q)=>{this._eventSource=new xB(this._url.href,{...this._eventSourceInit,fetch:async(J,G)=>{let K=await this._commonHeaders();K.set("Accept","text/event-stream");let W=await Y(J,{...G,headers:K});if(W.status===401&&W.headers.has("www-authenticate")){let{resourceMetadataUrl:Z,scope:H}=SB(W);this._resourceMetadataUrl=Z,this._scope=H}return W}}),this._abortController=new AbortController,this._eventSource.onerror=(J)=>{if(J.code===401&&this._authProvider){this._authThenStart().then(X,Q);return}let G=new w36(J.code,J.message,J);Q(G),this.onerror?.(G)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",(J)=>{let G=J;try{if(this._endpoint=new URL(G.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(K){Q(K),this.onerror?.(K),this.close();return}X()}),this._eventSource.onmessage=(J)=>{let G=J,K;try{K=bQ.parse(JSON.parse(G.data))}catch(W){this.onerror?.(W);return}this.onmessage?.(K)}})}async start(){if(this._eventSource)throw Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(Y){if(!this._authProvider)throw new GQ("No auth provider");if(await D7(this._authProvider,{serverUrl:this._url,authorizationCode:Y,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new GQ("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(Y){if(!this._endpoint)throw Error("Not connected");try{let X=await this._commonHeaders();X.set("content-type","application/json");let Q={...this._requestInit,method:"POST",headers:X,body:JSON.stringify(Y),signal:this._abortController?.signal},J=await(this._fetch??fetch)(this._endpoint,Q);if(!J.ok){let G=await J.text().catch(()=>null);if(J.status===401&&this._authProvider){let{resourceMetadataUrl:K,scope:W}=SB(J);if(this._resourceMetadataUrl=K,this._scope=W,await D7(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new GQ;return this.send(Y)}throw Error(`Error POSTing to endpoint (HTTP ${J.status}): ${G}`)}await J.body?.cancel()}catch(X){throw this.onerror?.(X),X}}setProtocolVersion(Y){this._protocolVersion=Y}}var w36;var x90=m(()=>{M36();xQ();qf();w36=class w36 extends Error{constructor(Y,X,Q){super(`SSE error: ${X}`);this.code=Y,this.event=Q}}});var I36=P((ta1,E36)=>{E36.exports=T36;T36.sync=Wc4;var P36=q0("fs");function Gc4(Y,X){var Q=X.pathExt!==void 0?X.pathExt:process.env.PATHEXT;if(!Q)return!0;if(Q=Q.split(";"),Q.indexOf("")!==-1)return!0;for(var J=0;J<Q.length;J++){var G=Q[J].toLowerCase();if(G&&Y.substr(-G.length).toLowerCase()===G)return!0}return!1}function A36(Y,X,Q){if(!Y.isSymbolicLink()&&!Y.isFile())return!1;return Gc4(X,Q)}function T36(Y,X,Q){P36.stat(Y,function(J,G){Q(J,J?!1:A36(G,Y,X))})}function Wc4(Y,X){return A36(P36.statSync(Y),Y,X)}});var k36=P((ea1,j36)=>{j36.exports=R36;R36.sync=Zc4;var C36=q0("fs");function R36(Y,X,Q){C36.stat(Y,function(J,G){Q(J,J?!1:S36(G,X))})}function Zc4(Y,X){return S36(C36.statSync(Y),X)}function S36(Y,X){return Y.isFile()&&Kc4(Y,X)}function Kc4(Y,X){var{mode:Q,uid:J,gid:G}=Y,K=X.uid!==void 0?X.uid:process.getuid&&process.getuid(),W=X.gid!==void 0?X.gid:process.getgid&&process.getgid(),Z=parseInt("100",8),H=parseInt("010",8),F=parseInt("001",8),V=Z|H,q=Q&F||Q&H&&G===W||Q&Z&&J===K||Q&V&&K===0;return q}});var _36=P((Xr1,v36)=>{var Yr1=q0("fs"),Pf;if(process.platform==="win32"||global.TESTING_WINDOWS)Pf=I36();else Pf=k36();v36.exports=u90;u90.sync=Hc4;function u90(Y,X,Q){if(typeof X==="function")Q=X,X={};if(!Q){if(typeof Promise!=="function")throw TypeError("callback not provided");return new Promise(function(J,G){u90(Y,X||{},function(K,W){if(K)G(K);else J(W)})})}Pf(Y,X||{},function(J,G){if(J){if(J.code==="EACCES"||X&&X.ignoreErrors)J=null,G=!1}Q(J,G)})}function Hc4(Y,X){try{return Pf.sync(Y,X||{})}catch(Q){if(X&&X.ignoreErrors||Q.code==="EACCES")return!1;else throw Q}}});var g36=P((Qr1,u36)=>{var uB=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",y36=q0("path"),Fc4=uB?";":":",f36=_36(),h36=(Y)=>Object.assign(Error(`not found: ${Y}`),{code:"ENOENT"}),b36=(Y,X)=>{let Q=X.colon||Fc4,J=Y.match(/\//)||uB&&Y.match(/\\/)?[""]:[...uB?[process.cwd()]:[],...(X.path||process.env.PATH||"").split(Q)],G=uB?X.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",K=uB?G.split(Q):[""];if(uB){if(Y.indexOf(".")!==-1&&K[0]!=="")K.unshift("")}return{pathEnv:J,pathExt:K,pathExtExe:G}},x36=(Y,X,Q)=>{if(typeof X==="function")Q=X,X={};if(!X)X={};let{pathEnv:J,pathExt:G,pathExtExe:K}=b36(Y,X),W=[],Z=(F)=>new Promise((V,q)=>{if(F===J.length)return X.all&&W.length?V(W):q(h36(Y));let $=J[F],B=/^".*"$/.test($)?$.slice(1,-1):$,U=y36.join(B,Y),D=!B&&/^\.[\\\/]/.test(Y)?Y.slice(0,2)+U:U;V(H(D,F,0))}),H=(F,V,q)=>new Promise(($,B)=>{if(q===G.length)return $(Z(V+1));let U=G[q];f36(F+U,{pathExt:K},(D,L)=>{if(!D&&L)if(X.all)W.push(F+U);else return $(F+U);return $(H(F,V,q+1))})});return Q?Z(0).then((F)=>Q(null,F),Q):Z(0)},Vc4=(Y,X)=>{X=X||{};let{pathEnv:Q,pathExt:J,pathExtExe:G}=b36(Y,X),K=[];for(let W=0;W<Q.length;W++){let Z=Q[W],H=/^".*"$/.test(Z)?Z.slice(1,-1):Z,F=y36.join(H,Y),V=!H&&/^\.[\\\/]/.test(Y)?Y.slice(0,2)+F:F;for(let q=0;q<J.length;q++){let $=V+J[q];try{if(f36.sync($,{pathExt:G}))if(X.all)K.push($);else return $}catch(B){}}}if(X.all&&K.length)return K;if(X.nothrow)return null;throw h36(Y)};u36.exports=x36;x36.sync=Vc4});var l36=P((Jr1,g90)=>{var m36=(Y={})=>{let X=Y.env||process.env;if((Y.platform||process.platform)!=="win32")return"PATH";return Object.keys(X).reverse().find((J)=>J.toUpperCase()==="PATH")||"Path"};g90.exports=m36;g90.exports.default=m36});var n36=P((Gr1,c36)=>{var d36=q0("path"),qc4=g36(),$c4=l36();function p36(Y,X){let Q=Y.options.env||process.env,J=process.cwd(),G=Y.options.cwd!=null,K=G&&process.chdir!==void 0&&!process.chdir.disabled;if(K)try{process.chdir(Y.options.cwd)}catch(Z){}let W;try{W=qc4.sync(Y.command,{path:Q[$c4({env:Q})],pathExt:X?d36.delimiter:void 0})}catch(Z){}finally{if(K)process.chdir(J)}if(W)W=d36.resolve(G?Y.options.cwd:"",W);return W}function zc4(Y){return p36(Y)||p36(Y,!0)}c36.exports=zc4});var i36=P((Dc4,l90)=>{var m90=/([()\][%!^"`<>&|;, *?])/g;function Bc4(Y){return Y=Y.replace(m90,"^$1"),Y}function Uc4(Y,X){if(Y=`${Y}`,Y=Y.replace(/(?=(\\+?)?)\1"/g,"$1$1\\\""),Y=Y.replace(/(?=(\\+?)?)\1$/,"$1$1"),Y=`"${Y}"`,Y=Y.replace(m90,"^$1"),X)Y=Y.replace(m90,"^$1");return Y}Dc4.command=Bc4;Dc4.argument=Uc4});var r36=P((Wr1,a36)=>{a36.exports=/^#!(.*)/});var s36=P((Zr1,o36)=>{var Lc4=r36();o36.exports=(Y="")=>{let X=Y.match(Lc4);if(!X)return null;let[Q,J]=X[0].replace(/#! ?/,"").split(" "),G=Q.split("/").pop();if(G==="env")return J;return J?`${G} ${J}`:G}});var e36=P((Kr1,t36)=>{var d90=q0("fs"),Mc4=s36();function wc4(Y){let Q=Buffer.alloc(150),J;try{J=d90.openSync(Y,"r"),d90.readSync(J,Q,0,150,0),d90.closeSync(J)}catch(G){}return Mc4(Q.toString())}t36.exports=wc4});var JH6=P((Hr1,QH6)=>{var Pc4=q0("path"),YH6=n36(),XH6=i36(),Ac4=e36(),Tc4=process.platform==="win32",Ec4=/\.(?:com|exe)$/i,Ic4=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function Cc4(Y){Y.file=YH6(Y);let X=Y.file&&Ac4(Y.file);if(X)return Y.args.unshift(Y.file),Y.command=X,YH6(Y);return Y.file}function Rc4(Y){if(!Tc4)return Y;let X=Cc4(Y),Q=!Ec4.test(X);if(Y.options.forceShell||Q){let J=Ic4.test(X);Y.command=Pc4.normalize(Y.command),Y.command=XH6.command(Y.command),Y.args=Y.args.map((K)=>XH6.argument(K,J));let G=[Y.command].concat(Y.args).join(" ");Y.args=["/d","/s","/c",`"${G}"`],Y.command=process.env.comspec||"cmd.exe",Y.options.windowsVerbatimArguments=!0}return Y}function Sc4(Y,X,Q){if(X&&!Array.isArray(X))Q=X,X=null;X=X?X.slice(0):[],Q=Object.assign({},Q);let J={command:Y,args:X,options:Q,file:void 0,original:{command:Y,args:X}};return Q.shell?J:Rc4(J)}QH6.exports=Sc4});var ZH6=P((Fr1,WH6)=>{var p90=process.platform==="win32";function c90(Y,X){return Object.assign(Error(`${X} ${Y.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${X} ${Y.command}`,path:Y.command,spawnargs:Y.args})}function jc4(Y,X){if(!p90)return;let Q=Y.emit;Y.emit=function(J,G){if(J==="exit"){let K=GH6(G,X);if(K)return Q.call(Y,"error",K)}return Q.apply(Y,arguments)}}function GH6(Y,X){if(p90&&Y===1&&!X.file)return c90(X.original,"spawn");return null}function kc4(Y,X){if(p90&&Y===1&&!X.file)return c90(X.original,"spawnSync");return null}WH6.exports={hookChildProcess:jc4,verifyENOENT:GH6,verifyENOENTSync:kc4,notFoundError:c90}});var FH6=P((Vr1,gB)=>{var KH6=q0("child_process"),n90=JH6(),i90=ZH6();function HH6(Y,X,Q){let J=n90(Y,X,Q),G=KH6.spawn(J.command,J.args,J.options);return i90.hookChildProcess(G,J),G}function vc4(Y,X,Q){let J=n90(Y,X,Q),G=KH6.spawnSync(J.command,J.args,J.options);return G.error=G.error||i90.verifyENOENTSync(G.status,J),G}gB.exports=HH6;gB.exports.spawn=HH6;gB.exports.sync=vc4;gB.exports._parse=n90;gB.exports._enoent=i90});class a90{append(Y){this._buffer=this._buffer?Buffer.concat([this._buffer,Y]):Y}readMessage(){if(!this._buffer)return null;let Y=this._buffer.indexOf(`
384
+ `&&J++}}return[X,Q]}var z90;var B90=m(()=>{z90=class z90 extends Error{constructor(Y,X){super(Y),this.name="ParseError",this.type=X.type,this.field=X.field,this.value=X.value,this.line=X.line}}});var U90;var cK6=m(()=>{B90();U90=class U90 extends TransformStream{constructor({onError:Y,onRetry:X,onComment:Q}={}){let J;super({start(G){J=$f({onEvent:(K)=>{G.enqueue(K)},onError(K){Y==="terminate"?G.error(K):typeof Y=="function"&&Y(K)},onRetry:X,onComment:Q})},transform(G){J.feed(G)}})}}});class jB{constructor(Y,X){this._hasCompletedAuthFlow=!1,this._url=Y,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=X?.requestInit,this._authProvider=X?.authProvider,this._fetch=X?.fetch,this._fetchWithInit=ty(X?.fetch,X?.requestInit),this._sessionId=X?.sessionId,this._reconnectionOptions=X?.reconnectionOptions??Up4}async _authThenStart(){if(!this._authProvider)throw new GQ("No auth provider");let Y;try{Y=await D7(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(X){throw this.onerror?.(X),X}if(Y!=="AUTHORIZED")throw new GQ;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let Y={};if(this._authProvider){let Q=await this._authProvider.tokens();if(Q)Y.Authorization=`Bearer ${Q.access_token}`}if(this._sessionId)Y["mcp-session-id"]=this._sessionId;if(this._protocolVersion)Y["mcp-protocol-version"]=this._protocolVersion;let X=TB(this._requestInit?.headers);return new Headers({...Y,...X})}async _startOrAuthSse(Y){let{resumptionToken:X}=Y;try{let Q=await this._commonHeaders();if(Q.set("Accept","text/event-stream"),X)Q.set("last-event-id",X);let J=await(this._fetch??fetch)(this._url,{method:"GET",headers:Q,signal:this._abortController?.signal});if(!J.ok){if(await J.body?.cancel(),J.status===401&&this._authProvider)return await this._authThenStart();if(J.status===405)return;throw new KV(J.status,`Failed to open SSE stream: ${J.statusText}`)}this._handleSseStream(J.body,Y,!0)}catch(Q){throw this.onerror?.(Q),Q}}_getNextReconnectionDelay(Y){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let X=this._reconnectionOptions.initialReconnectionDelay,Q=this._reconnectionOptions.reconnectionDelayGrowFactor,J=this._reconnectionOptions.maxReconnectionDelay;return Math.min(X*Math.pow(Q,Y),J)}_scheduleReconnection(Y,X=0){let Q=this._reconnectionOptions.maxRetries;if(X>=Q){this.onerror?.(Error(`Maximum reconnection attempts (${Q}) exceeded.`));return}let J=this._getNextReconnectionDelay(X);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(Y).catch((G)=>{this.onerror?.(Error(`Failed to reconnect SSE stream: ${G instanceof Error?G.message:String(G)}`)),this._scheduleReconnection(Y,X+1)})},J)}_handleSseStream(Y,X,Q){if(!Y)return;let{onresumptiontoken:J,replayMessageId:G}=X,K,W=!1,Z=!1;(async()=>{try{let F=Y.pipeThrough(new TextDecoderStream).pipeThrough(new U90({onRetry:($)=>{this._serverRetryMs=$}})).getReader();while(!0){let{value:$,done:B}=await F.read();if(B)break;if($.id)K=$.id,W=!0,J?.($.id);if(!$.data)continue;if(!$.event||$.event==="message")try{let U=bQ.parse(JSON.parse($.data));if(y5(U)){if(Z=!0,G!==void 0)U.id=G}this.onmessage?.(U)}catch(U){this.onerror?.(U)}}if((Q||W)&&!Z&&this._abortController&&!this._abortController.signal.aborted)this._scheduleReconnection({resumptionToken:K,onresumptiontoken:J,replayMessageId:G},0)}catch(F){if(this.onerror?.(Error(`SSE stream disconnected: ${F}`)),(Q||W)&&!Z&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:K,onresumptiontoken:J,replayMessageId:G},0)}catch($){this.onerror?.(Error(`Failed to reconnect: ${$ instanceof Error?$.message:String($)}`))}}})()}async start(){if(this._abortController)throw Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(Y){if(!this._authProvider)throw new GQ("No auth provider");if(await D7(this._authProvider,{serverUrl:this._url,authorizationCode:Y,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new GQ("Failed to authorize")}async close(){if(this._reconnectionTimeout)clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0;this._abortController?.abort(),this.onclose?.()}async send(Y,X){try{let{resumptionToken:Q,onresumptiontoken:J}=X||{};if(Q){this._startOrAuthSse({resumptionToken:Q,replayMessageId:$7(Y)?Y.id:void 0}).catch((q)=>this.onerror?.(q));return}let G=await this._commonHeaders();G.set("content-type","application/json"),G.set("accept","application/json, text/event-stream");let K={...this._requestInit,method:"POST",headers:G,body:JSON.stringify(Y),signal:this._abortController?.signal},W=await(this._fetch??fetch)(this._url,K),Z=W.headers.get("mcp-session-id");if(Z)this._sessionId=Z;if(!W.ok){let q=await W.text().catch(()=>null);if(W.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new KV(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:$,scope:B}=SB(W);if(this._resourceMetadataUrl=$,this._scope=B,await D7(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new GQ;return this._hasCompletedAuthFlow=!0,this.send(Y)}if(W.status===403&&this._authProvider){let{resourceMetadataUrl:$,scope:B,error:U}=SB(W);if(U==="insufficient_scope"){let D=W.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===D)throw new KV(403,"Server returned 403 after trying upscoping");if(B)this._scope=B;if($)this._resourceMetadataUrl=$;if(this._lastUpscopingHeader=D??void 0,await D7(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new GQ;return this.send(Y)}}throw new KV(W.status,`Error POSTing to endpoint: ${q}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,W.status===202){if(await W.body?.cancel(),G56(Y))this._startOrAuthSse({resumptionToken:void 0}).catch((q)=>this.onerror?.(q));return}let F=(Array.isArray(Y)?Y:[Y]).filter((q)=>("method"in q)&&("id"in q)&&q.id!==void 0).length>0,V=W.headers.get("content-type");if(F)if(V?.includes("text/event-stream"))this._handleSseStream(W.body,{onresumptiontoken:J},!1);else if(V?.includes("application/json")){let q=await W.json(),$=Array.isArray(q)?q.map((B)=>bQ.parse(B)):[bQ.parse(q)];for(let B of $)this.onmessage?.(B)}else throw await W.body?.cancel(),new KV(-1,`Unexpected content type: ${V}`);else await W.body?.cancel()}catch(Q){throw this.onerror?.(Q),Q}}get sessionId(){return this._sessionId}async terminateSession(){if(!this._sessionId)return;try{let Y=await this._commonHeaders(),X={...this._requestInit,method:"DELETE",headers:Y,signal:this._abortController?.signal},Q=await(this._fetch??fetch)(this._url,X);if(await Q.body?.cancel(),!Q.ok&&Q.status!==405)throw new KV(Q.status,`Failed to terminate session: ${Q.statusText}`);this._sessionId=void 0}catch(Y){throw this.onerror?.(Y),Y}}setProtocolVersion(Y){this._protocolVersion=Y}get protocolVersion(){return this._protocolVersion}async resumeStream(Y,X){await this._startOrAuthSse({resumptionToken:Y,onresumptiontoken:X?.onresumptiontoken})}}var Up4,KV;var zf=m(()=>{xQ();qf();cK6();Up4={initialReconnectionDelay:1000,maxReconnectionDelay:30000,reconnectionDelayGrowFactor:1.5,maxRetries:2};KV=class KV extends Error{constructor(Y,X){super(`Streamable HTTP error: ${X}`);this.code=Y}}});var D90=m(()=>{zf()});var Bf=m(()=>{sy();rF();D90()});function O90(Y){return{id:FP.REGISTRY(Y),title:"Deco Store",description:"Official deco MCP registry with curated integrations",connection_type:"HTTP",connection_url:"https://api.decocms.com/mcp/registry",icon:"https://assets.decocache.com/decocms/00ccf6c3-9e13-4517-83b0-75ab84554bb9/596364c63320075ca58483660156b6d9de9b526e.png",app_name:"deco-registry",app_id:null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!0,type:"registry"}}}function N90(){return{id:"community-registry",title:"MCP Registry",description:"Community MCP registry with thousands of handy MCPs",connection_type:"HTTP",connection_url:"https://sites-registry.decocache.com/mcp",icon:"https://assets.decocache.com/decocms/cd7ca472-0f72-463a-b0de-6e44bdd0f9b4/mcp.png",app_name:"mcp-registry",app_id:null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!0,type:"registry"}}}function L90(Y,X){return{id:FP.SELF(X),title:"Mesh MCP",description:"The MCP for the mesh API",connection_type:"HTTP",connection_url:`${Y}/mcp/self`,icon:"https://assets.decocache.com/mcp/09e44283-f47d-4046-955f-816d227c626f/app.png",app_name:"@deco/management-mcp",connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!0,type:"self"}}}var FP;var Uf=m(()=>{FP={SELF:(Y)=>`${Y}_self`,REGISTRY:(Y)=>`${Y}_registry`,COMMUNITY_REGISTRY:(Y)=>`${Y}_community-registry`}});var iK6=m(()=>{k40();N_();Bf();Uf()});var aK6=m(()=>{rF()});var rK6=m(()=>{rF()});var oK6=m(()=>{_40();N_();Bf();Uf()});var sK6=m(()=>{N_();iK6();Bf();h40();aK6();rK6();oK6()});var xp4,up4,gp4,mp4,Df,tK6,eK6;var Y36=m(()=>{Y6();xp4=N.object({authorizationEndpoint:N.string().url(),tokenEndpoint:N.string().url(),introspectionEndpoint:N.string().url().optional(),clientId:N.string(),clientSecret:N.string().optional(),scopes:N.array(N.string()),grantType:N.enum(["authorization_code","client_credentials"])}),up4=N.object({name:N.string(),description:N.string().optional(),inputSchema:N.record(N.string(),N.unknown()),outputSchema:N.record(N.string(),N.unknown()).optional()}),gp4=N.object({headers:N.record(N.string(),N.string()).optional()}),mp4=N.object({command:N.string().describe("Command to run (e.g., 'npx', 'node')"),args:N.array(N.string()).optional().describe("Command arguments"),cwd:N.string().optional().describe("Working directory"),envVars:N.record(N.string(),N.string()).optional().describe("Environment variables (encrypted in storage)")}),Df=N.object({id:N.string().describe("Unique identifier for the connection"),title:N.string().describe("Human-readable name for the connection"),created_at:N.string().describe("When the connection was created"),updated_at:N.string().describe("When the connection was last updated"),created_by:N.string().describe("User ID who created the connection"),updated_by:N.string().optional().describe("User ID who last updated the connection"),organization_id:N.string().describe("Organization ID this connection belongs to"),description:N.string().nullable().describe("Description of the connection"),icon:N.string().nullable().describe("Icon URL for the connection"),app_name:N.string().nullable().describe("Associated app name"),app_id:N.string().nullable().describe("Associated app ID"),connection_type:N.enum(["HTTP","SSE","Websocket","STDIO","VIRTUAL"]).describe("Type of connection"),connection_url:N.string().nullable().describe("URL for HTTP/SSE/WebSocket connections. virtual://$id for VIRTUAL. Null for STDIO."),connection_token:N.string().nullable().describe("Authentication token (for HTTP connections)"),connection_headers:N.union([mp4,gp4]).nullable().describe("Connection parameters. HTTP: { headers }. STDIO: { command, args, cwd, envVars }"),oauth_config:xp4.nullable().describe("OAuth configuration"),configuration_state:N.record(N.string(),N.unknown()).nullable().describe("Configuration state (decrypted)"),configuration_scopes:N.array(N.string()).nullable().optional().describe("Configuration scopes"),metadata:N.record(N.string(),N.unknown()).nullable().describe("Additional metadata (includes repository info)"),tools:N.array(up4).nullable().describe("Discovered tools from MCP"),bindings:N.array(N.string()).nullable().describe("Detected bindings"),status:N.enum(["active","inactive","error"]).describe("Current status")}),tK6=Df.omit({created_at:!0,updated_at:!0,created_by:!0,updated_by:!0,organization_id:!0,tools:!0,bindings:!0,status:!0}).partial({id:!0,description:!0,icon:!0,app_name:!0,app_id:!0,connection_url:!0,connection_token:!0,connection_headers:!0,oauth_config:!0,configuration_state:!0,configuration_scopes:!0,metadata:!0}),eK6=Df.partial()});var T90,lp4,X36,Q36,J36;var G36=m(()=>{Y6();T90=N.enum(["inclusion","exclusion"]).describe("Tool selection mode: 'inclusion' = include selected (default), 'exclusion' = exclude selected"),lp4=N.object({connection_id:N.string().describe("Connection ID"),selected_tools:N.array(N.string()).nullable().describe("Selected tool names. With 'inclusion' mode: null = all tools included. With 'exclusion' mode: null = entire connection excluded"),selected_resources:N.array(N.string()).nullable().describe("Selected resource URIs or patterns. Supports * and ** wildcards for pattern matching. With 'inclusion' mode: null = all resources included."),selected_prompts:N.array(N.string()).nullable().describe("Selected prompt names. With 'inclusion' mode: null = all prompts included. With 'exclusion' mode: null = entire connection excluded.")}),X36=N.object({id:N.string().describe("Unique identifier for the virtual MCP"),title:N.string().describe("Human-readable name for the virtual MCP"),description:N.string().nullable().describe("Description of the virtual MCP"),icon:N.string().nullable().optional().describe("Icon URL for the virtual MCP"),created_at:N.string().describe("When the virtual MCP was created"),updated_at:N.string().describe("When the virtual MCP was last updated"),created_by:N.string().describe("User ID who created the virtual MCP"),updated_by:N.string().optional().describe("User ID who last updated the virtual MCP"),organization_id:N.string().describe("Organization ID this virtual MCP belongs to"),tool_selection_mode:T90.describe("Tool selection mode: 'inclusion' = include selected, 'exclusion' = exclude selected"),status:N.enum(["active","inactive"]).describe("Current status"),metadata:N.object({instructions:N.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:N.array(lp4).describe("Connections with their selected tools (behavior depends on tool_selection_mode)")}),Q36=N.object({title:N.string().min(1).max(255).describe("Name for the virtual MCP"),description:N.string().nullable().optional().describe("Optional description"),tool_selection_mode:T90.optional().default("inclusion").describe("Tool selection mode (defaults to 'inclusion')"),icon:N.string().nullable().optional().describe("Optional icon URL"),status:N.enum(["active","inactive"]).optional().default("active").describe("Initial status"),metadata:N.object({instructions:N.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:N.array(N.object({connection_id:N.string().describe("Connection ID"),selected_tools:N.array(N.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:N.array(N.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:N.array(N.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).describe("Connections to include/exclude (can be empty for exclusion mode)")}),J36=N.object({title:N.string().min(1).max(255).optional().describe("New name"),description:N.string().nullable().optional().describe("New description (null to clear)"),tool_selection_mode:T90.optional().describe("New tool selection mode"),icon:N.string().nullable().optional().describe("New icon URL (null to clear)"),status:N.enum(["active","inactive"]).optional().describe("New status"),metadata:N.object({instructions:N.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:N.array(N.object({connection_id:N.string().describe("Connection ID"),selected_tools:N.array(N.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:N.array(N.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:N.array(N.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).optional().describe("New connections (replaces existing)")})});var W36=m(()=>{Y36();G36()});var Z36=m(()=>{qf()});var E90=m(()=>{_40();sK6();W36();D90();rF();Z36();Uf()});function qP(Y){return Y!==null&&Y!==void 0&&"command"in Y}function Of(Y){if(!Y||!Y.startsWith("virtual://"))return null;return Y.replace("virtual://","")}function Nf(Y){return`virtual://${Y}`}var ap4,rp4,op4,sp4,tp4,cJ,q36,$36;var Z3=m(()=>{Y6();ap4=N.object({authorizationEndpoint:N.string().url(),tokenEndpoint:N.string().url(),introspectionEndpoint:N.string().url().optional(),clientId:N.string(),clientSecret:N.string().optional(),scopes:N.array(N.string()),grantType:N.enum(["authorization_code","client_credentials"])}),rp4=N.object({title:N.string().optional(),readOnlyHint:N.boolean().optional(),destructiveHint:N.boolean().optional(),idempotentHint:N.boolean().optional(),openWorldHint:N.boolean().optional()}),op4=N.object({name:N.string(),description:N.string().optional(),inputSchema:N.record(N.string(),N.unknown()),outputSchema:N.record(N.string(),N.unknown()).optional(),annotations:rp4.optional(),_meta:N.record(N.string(),N.unknown()).optional()}),sp4=N.object({headers:N.record(N.string(),N.string()).optional()}),tp4=N.object({command:N.string().describe("Command to run (e.g., 'npx', 'node')"),args:N.array(N.string()).optional().describe("Command arguments"),cwd:N.string().optional().describe("Working directory"),envVars:N.record(N.string(),N.string()).optional().describe("Environment variables (encrypted in storage)")}),cJ=N.object({id:N.string().describe("Unique identifier for the connection"),title:N.string().describe("Human-readable name for the connection"),created_at:N.string().describe("When the connection was created"),updated_at:N.string().describe("When the connection was last updated"),created_by:N.string().describe("User ID who created the connection"),updated_by:N.string().optional().describe("User ID who last updated the connection"),organization_id:N.string().describe("Organization ID this connection belongs to"),description:N.string().nullable().describe("Description of the connection"),icon:N.string().nullable().describe("Icon URL for the connection"),app_name:N.string().nullable().describe("Associated app name"),app_id:N.string().nullable().describe("Associated app ID"),connection_type:N.enum(["HTTP","SSE","Websocket","STDIO","VIRTUAL"]).describe("Type of connection"),connection_url:N.string().nullable().describe("URL for HTTP/SSE/WebSocket connections. virtual://$id for VIRTUAL. Null for STDIO."),connection_token:N.string().nullable().describe("Authentication token (for HTTP connections)"),connection_headers:N.union([tp4,sp4]).nullable().describe("Connection parameters. HTTP: { headers }. STDIO: { command, args, cwd, envVars }"),oauth_config:ap4.nullable().describe("OAuth configuration"),configuration_state:N.record(N.string(),N.unknown()).nullable().describe("Configuration state (decrypted)"),configuration_scopes:N.array(N.string()).nullable().optional().describe("Configuration scopes"),metadata:N.record(N.string(),N.unknown()).nullable().describe("Additional metadata (includes repository info)"),tools:N.array(op4).nullable().describe("Discovered tools from MCP"),bindings:N.array(N.string()).nullable().describe("Detected bindings"),status:N.enum(["active","inactive","error"]).describe("Current status")}),q36=cJ.omit({created_at:!0,updated_at:!0,created_by:!0,updated_by:!0,organization_id:!0,tools:!0,bindings:!0,status:!0}).partial({id:!0,description:!0,icon:!0,app_name:!0,app_id:!0,connection_url:!0,connection_token:!0,connection_headers:!0,oauth_config:!0,configuration_state:!0,configuration_scopes:!0,metadata:!0}),$36=cJ.partial()});var z36="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";import{webcrypto as B36}from"crypto";function Yc4(Y){if(!HV||HV.length<Y)HV=Buffer.allocUnsafe(Y*ep4),B36.getRandomValues(HV),kB=0;else if(kB+Y>HV.length)B36.getRandomValues(HV),kB=0;kB+=Y}function U36(Y=21){Yc4(Y|=0);let X="";for(let Q=kB-Y;Q<kB;Q++)X+=z36[HV[Q]&63];return X}var ep4=128,HV,kB;var D36=()=>{};function vB(Y){return`${Y}_${U36()}`}var Lf=m(()=>{D36()});function Qc4(Y){let X=globalThis.DOMException;return typeof X=="function"?new X(Y,"SyntaxError"):SyntaxError(Y)}function S90(Y){return Y instanceof Error?"errors"in Y&&Array.isArray(Y.errors)?Y.errors.map(S90).join(", "):("cause"in Y)&&Y.cause instanceof Error?`${Y}: ${S90(Y.cause)}`:Y.message:`${Y}`}function O36(Y){return{type:Y.type,message:Y.message,code:Y.code,defaultPrevented:Y.defaultPrevented,cancelable:Y.cancelable,timeStamp:Y.timeStamp}}function Jc4(){let Y="document"in globalThis?globalThis.document:void 0;return Y&&typeof Y=="object"&&"baseURI"in Y&&typeof Y.baseURI=="string"?Y.baseURI:void 0}var R90,L36=(Y)=>{throw TypeError(Y)},b90=(Y,X,Q)=>X.has(Y)||L36("Cannot "+Q),j4=(Y,X,Q)=>(b90(Y,X,"read from private field"),Q?Q.call(Y):X.get(Y)),D9=(Y,X,Q)=>X.has(Y)?L36("Cannot add the same private member more than once"):X instanceof WeakSet?X.add(Y):X.set(Y,Q),M8=(Y,X,Q,J)=>(b90(Y,X,"write to private field"),X.set(Y,Q),Q),dW=(Y,X,Q)=>(b90(Y,X,"access private method"),Q),WQ,FV,_B,Mf,wf,BP,hB,UP,K3,yB,bB,fB,$P,d5,j90,k90,v90,N36,_90,y90,zP,f90,h90,xB;var M36=m(()=>{B90();R90=class R90 extends Event{constructor(Y,X){var Q,J;super(Y),this.code=(Q=X==null?void 0:X.code)!=null?Q:void 0,this.message=(J=X==null?void 0:X.message)!=null?J:void 0}[Symbol.for("nodejs.util.inspect.custom")](Y,X,Q){return Q(O36(this),X)}[Symbol.for("Deno.customInspect")](Y,X){return Y(O36(this),X)}};xB=class xB extends EventTarget{constructor(Y,X){var Q,J;super(),D9(this,d5),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,D9(this,WQ),D9(this,FV),D9(this,_B),D9(this,Mf),D9(this,wf),D9(this,BP),D9(this,hB),D9(this,UP,null),D9(this,K3),D9(this,yB),D9(this,bB,null),D9(this,fB,null),D9(this,$P,null),D9(this,k90,async(G)=>{var K;j4(this,yB).reset();let{body:W,redirected:Z,status:H,headers:F}=G;if(H===204){dW(this,d5,zP).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(Z?M8(this,_B,new URL(G.url)):M8(this,_B,void 0),H!==200){dW(this,d5,zP).call(this,`Non-200 status code (${H})`,H);return}if(!(F.get("content-type")||"").startsWith("text/event-stream")){dW(this,d5,zP).call(this,'Invalid content type, expected "text/event-stream"',H);return}if(j4(this,WQ)===this.CLOSED)return;M8(this,WQ,this.OPEN);let V=new Event("open");if((K=j4(this,$P))==null||K.call(this,V),this.dispatchEvent(V),typeof W!="object"||!W||!("getReader"in W)){dW(this,d5,zP).call(this,"Invalid response body, expected a web ReadableStream",H),this.close();return}let q=new TextDecoder,$=W.getReader(),B=!0;do{let{done:U,value:D}=await $.read();D&&j4(this,yB).feed(q.decode(D,{stream:!U})),U&&(B=!1,j4(this,yB).reset(),dW(this,d5,f90).call(this))}while(B)}),D9(this,v90,(G)=>{M8(this,K3,void 0),!(G.name==="AbortError"||G.type==="aborted")&&dW(this,d5,f90).call(this,S90(G))}),D9(this,_90,(G)=>{typeof G.id=="string"&&M8(this,UP,G.id);let K=new MessageEvent(G.event||"message",{data:G.data,origin:j4(this,_B)?j4(this,_B).origin:j4(this,FV).origin,lastEventId:G.id||""});j4(this,fB)&&(!G.event||G.event==="message")&&j4(this,fB).call(this,K),this.dispatchEvent(K)}),D9(this,y90,(G)=>{M8(this,BP,G)}),D9(this,h90,()=>{M8(this,hB,void 0),j4(this,WQ)===this.CONNECTING&&dW(this,d5,j90).call(this)});try{if(Y instanceof URL)M8(this,FV,Y);else if(typeof Y=="string")M8(this,FV,new URL(Y,Jc4()));else throw Error("Invalid URL")}catch{throw Qc4("An invalid or illegal string was specified")}M8(this,yB,$f({onEvent:j4(this,_90),onRetry:j4(this,y90)})),M8(this,WQ,this.CONNECTING),M8(this,BP,3000),M8(this,wf,(Q=X==null?void 0:X.fetch)!=null?Q:globalThis.fetch),M8(this,Mf,(J=X==null?void 0:X.withCredentials)!=null?J:!1),dW(this,d5,j90).call(this)}get readyState(){return j4(this,WQ)}get url(){return j4(this,FV).href}get withCredentials(){return j4(this,Mf)}get onerror(){return j4(this,bB)}set onerror(Y){M8(this,bB,Y)}get onmessage(){return j4(this,fB)}set onmessage(Y){M8(this,fB,Y)}get onopen(){return j4(this,$P)}set onopen(Y){M8(this,$P,Y)}addEventListener(Y,X,Q){let J=X;super.addEventListener(Y,J,Q)}removeEventListener(Y,X,Q){let J=X;super.removeEventListener(Y,J,Q)}close(){j4(this,hB)&&clearTimeout(j4(this,hB)),j4(this,WQ)!==this.CLOSED&&(j4(this,K3)&&j4(this,K3).abort(),M8(this,WQ,this.CLOSED),M8(this,K3,void 0))}};WQ=new WeakMap,FV=new WeakMap,_B=new WeakMap,Mf=new WeakMap,wf=new WeakMap,BP=new WeakMap,hB=new WeakMap,UP=new WeakMap,K3=new WeakMap,yB=new WeakMap,bB=new WeakMap,fB=new WeakMap,$P=new WeakMap,d5=new WeakSet,j90=function(){M8(this,WQ,this.CONNECTING),M8(this,K3,new AbortController),j4(this,wf)(j4(this,FV),dW(this,d5,N36).call(this)).then(j4(this,k90)).catch(j4(this,v90))},k90=new WeakMap,v90=new WeakMap,N36=function(){var Y;let X={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...j4(this,UP)?{"Last-Event-ID":j4(this,UP)}:void 0},cache:"no-store",signal:(Y=j4(this,K3))==null?void 0:Y.signal};return"window"in globalThis&&(X.credentials=this.withCredentials?"include":"same-origin"),X},_90=new WeakMap,y90=new WeakMap,zP=function(Y,X){var Q;j4(this,WQ)!==this.CLOSED&&M8(this,WQ,this.CLOSED);let J=new R90("error",{code:X,message:Y});(Q=j4(this,bB))==null||Q.call(this,J),this.dispatchEvent(J)},f90=function(Y,X){var Q;if(j4(this,WQ)===this.CLOSED)return;M8(this,WQ,this.CONNECTING);let J=new R90("error",{code:X,message:Y});(Q=j4(this,bB))==null||Q.call(this,J),this.dispatchEvent(J),M8(this,hB,setTimeout(j4(this,h90),j4(this,BP)))},h90=new WeakMap,xB.CONNECTING=0,xB.OPEN=1,xB.CLOSED=2});class DP{constructor(Y,X){this._url=Y,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=X?.eventSourceInit,this._requestInit=X?.requestInit,this._authProvider=X?.authProvider,this._fetch=X?.fetch,this._fetchWithInit=ty(X?.fetch,X?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new GQ("No auth provider");let Y;try{Y=await D7(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(X){throw this.onerror?.(X),X}if(Y!=="AUTHORIZED")throw new GQ;return await this._startOrAuth()}async _commonHeaders(){let Y={};if(this._authProvider){let Q=await this._authProvider.tokens();if(Q)Y.Authorization=`Bearer ${Q.access_token}`}if(this._protocolVersion)Y["mcp-protocol-version"]=this._protocolVersion;let X=TB(this._requestInit?.headers);return new Headers({...Y,...X})}_startOrAuth(){let Y=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((X,Q)=>{this._eventSource=new xB(this._url.href,{...this._eventSourceInit,fetch:async(J,G)=>{let K=await this._commonHeaders();K.set("Accept","text/event-stream");let W=await Y(J,{...G,headers:K});if(W.status===401&&W.headers.has("www-authenticate")){let{resourceMetadataUrl:Z,scope:H}=SB(W);this._resourceMetadataUrl=Z,this._scope=H}return W}}),this._abortController=new AbortController,this._eventSource.onerror=(J)=>{if(J.code===401&&this._authProvider){this._authThenStart().then(X,Q);return}let G=new w36(J.code,J.message,J);Q(G),this.onerror?.(G)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",(J)=>{let G=J;try{if(this._endpoint=new URL(G.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(K){Q(K),this.onerror?.(K),this.close();return}X()}),this._eventSource.onmessage=(J)=>{let G=J,K;try{K=bQ.parse(JSON.parse(G.data))}catch(W){this.onerror?.(W);return}this.onmessage?.(K)}})}async start(){if(this._eventSource)throw Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(Y){if(!this._authProvider)throw new GQ("No auth provider");if(await D7(this._authProvider,{serverUrl:this._url,authorizationCode:Y,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new GQ("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(Y){if(!this._endpoint)throw Error("Not connected");try{let X=await this._commonHeaders();X.set("content-type","application/json");let Q={...this._requestInit,method:"POST",headers:X,body:JSON.stringify(Y),signal:this._abortController?.signal},J=await(this._fetch??fetch)(this._endpoint,Q);if(!J.ok){let G=await J.text().catch(()=>null);if(J.status===401&&this._authProvider){let{resourceMetadataUrl:K,scope:W}=SB(J);if(this._resourceMetadataUrl=K,this._scope=W,await D7(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new GQ;return this.send(Y)}throw Error(`Error POSTing to endpoint (HTTP ${J.status}): ${G}`)}await J.body?.cancel()}catch(X){throw this.onerror?.(X),X}}setProtocolVersion(Y){this._protocolVersion=Y}}var w36;var x90=m(()=>{M36();xQ();qf();w36=class w36 extends Error{constructor(Y,X,Q){super(`SSE error: ${X}`);this.code=Y,this.event=Q}}});var I36=P((ea1,E36)=>{E36.exports=T36;T36.sync=Wc4;var P36=q0("fs");function Gc4(Y,X){var Q=X.pathExt!==void 0?X.pathExt:process.env.PATHEXT;if(!Q)return!0;if(Q=Q.split(";"),Q.indexOf("")!==-1)return!0;for(var J=0;J<Q.length;J++){var G=Q[J].toLowerCase();if(G&&Y.substr(-G.length).toLowerCase()===G)return!0}return!1}function A36(Y,X,Q){if(!Y.isSymbolicLink()&&!Y.isFile())return!1;return Gc4(X,Q)}function T36(Y,X,Q){P36.stat(Y,function(J,G){Q(J,J?!1:A36(G,Y,X))})}function Wc4(Y,X){return A36(P36.statSync(Y),Y,X)}});var k36=P((Yr1,j36)=>{j36.exports=R36;R36.sync=Zc4;var C36=q0("fs");function R36(Y,X,Q){C36.stat(Y,function(J,G){Q(J,J?!1:S36(G,X))})}function Zc4(Y,X){return S36(C36.statSync(Y),X)}function S36(Y,X){return Y.isFile()&&Kc4(Y,X)}function Kc4(Y,X){var{mode:Q,uid:J,gid:G}=Y,K=X.uid!==void 0?X.uid:process.getuid&&process.getuid(),W=X.gid!==void 0?X.gid:process.getgid&&process.getgid(),Z=parseInt("100",8),H=parseInt("010",8),F=parseInt("001",8),V=Z|H,q=Q&F||Q&H&&G===W||Q&Z&&J===K||Q&V&&K===0;return q}});var _36=P((Qr1,v36)=>{var Xr1=q0("fs"),Pf;if(process.platform==="win32"||global.TESTING_WINDOWS)Pf=I36();else Pf=k36();v36.exports=u90;u90.sync=Hc4;function u90(Y,X,Q){if(typeof X==="function")Q=X,X={};if(!Q){if(typeof Promise!=="function")throw TypeError("callback not provided");return new Promise(function(J,G){u90(Y,X||{},function(K,W){if(K)G(K);else J(W)})})}Pf(Y,X||{},function(J,G){if(J){if(J.code==="EACCES"||X&&X.ignoreErrors)J=null,G=!1}Q(J,G)})}function Hc4(Y,X){try{return Pf.sync(Y,X||{})}catch(Q){if(X&&X.ignoreErrors||Q.code==="EACCES")return!1;else throw Q}}});var g36=P((Jr1,u36)=>{var uB=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",y36=q0("path"),Fc4=uB?";":":",f36=_36(),h36=(Y)=>Object.assign(Error(`not found: ${Y}`),{code:"ENOENT"}),b36=(Y,X)=>{let Q=X.colon||Fc4,J=Y.match(/\//)||uB&&Y.match(/\\/)?[""]:[...uB?[process.cwd()]:[],...(X.path||process.env.PATH||"").split(Q)],G=uB?X.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",K=uB?G.split(Q):[""];if(uB){if(Y.indexOf(".")!==-1&&K[0]!=="")K.unshift("")}return{pathEnv:J,pathExt:K,pathExtExe:G}},x36=(Y,X,Q)=>{if(typeof X==="function")Q=X,X={};if(!X)X={};let{pathEnv:J,pathExt:G,pathExtExe:K}=b36(Y,X),W=[],Z=(F)=>new Promise((V,q)=>{if(F===J.length)return X.all&&W.length?V(W):q(h36(Y));let $=J[F],B=/^".*"$/.test($)?$.slice(1,-1):$,U=y36.join(B,Y),D=!B&&/^\.[\\\/]/.test(Y)?Y.slice(0,2)+U:U;V(H(D,F,0))}),H=(F,V,q)=>new Promise(($,B)=>{if(q===G.length)return $(Z(V+1));let U=G[q];f36(F+U,{pathExt:K},(D,L)=>{if(!D&&L)if(X.all)W.push(F+U);else return $(F+U);return $(H(F,V,q+1))})});return Q?Z(0).then((F)=>Q(null,F),Q):Z(0)},Vc4=(Y,X)=>{X=X||{};let{pathEnv:Q,pathExt:J,pathExtExe:G}=b36(Y,X),K=[];for(let W=0;W<Q.length;W++){let Z=Q[W],H=/^".*"$/.test(Z)?Z.slice(1,-1):Z,F=y36.join(H,Y),V=!H&&/^\.[\\\/]/.test(Y)?Y.slice(0,2)+F:F;for(let q=0;q<J.length;q++){let $=V+J[q];try{if(f36.sync($,{pathExt:G}))if(X.all)K.push($);else return $}catch(B){}}}if(X.all&&K.length)return K;if(X.nothrow)return null;throw h36(Y)};u36.exports=x36;x36.sync=Vc4});var l36=P((Gr1,g90)=>{var m36=(Y={})=>{let X=Y.env||process.env;if((Y.platform||process.platform)!=="win32")return"PATH";return Object.keys(X).reverse().find((J)=>J.toUpperCase()==="PATH")||"Path"};g90.exports=m36;g90.exports.default=m36});var n36=P((Wr1,c36)=>{var d36=q0("path"),qc4=g36(),$c4=l36();function p36(Y,X){let Q=Y.options.env||process.env,J=process.cwd(),G=Y.options.cwd!=null,K=G&&process.chdir!==void 0&&!process.chdir.disabled;if(K)try{process.chdir(Y.options.cwd)}catch(Z){}let W;try{W=qc4.sync(Y.command,{path:Q[$c4({env:Q})],pathExt:X?d36.delimiter:void 0})}catch(Z){}finally{if(K)process.chdir(J)}if(W)W=d36.resolve(G?Y.options.cwd:"",W);return W}function zc4(Y){return p36(Y)||p36(Y,!0)}c36.exports=zc4});var i36=P((Dc4,l90)=>{var m90=/([()\][%!^"`<>&|;, *?])/g;function Bc4(Y){return Y=Y.replace(m90,"^$1"),Y}function Uc4(Y,X){if(Y=`${Y}`,Y=Y.replace(/(?=(\\+?)?)\1"/g,"$1$1\\\""),Y=Y.replace(/(?=(\\+?)?)\1$/,"$1$1"),Y=`"${Y}"`,Y=Y.replace(m90,"^$1"),X)Y=Y.replace(m90,"^$1");return Y}Dc4.command=Bc4;Dc4.argument=Uc4});var r36=P((Zr1,a36)=>{a36.exports=/^#!(.*)/});var s36=P((Kr1,o36)=>{var Lc4=r36();o36.exports=(Y="")=>{let X=Y.match(Lc4);if(!X)return null;let[Q,J]=X[0].replace(/#! ?/,"").split(" "),G=Q.split("/").pop();if(G==="env")return J;return J?`${G} ${J}`:G}});var e36=P((Hr1,t36)=>{var d90=q0("fs"),Mc4=s36();function wc4(Y){let Q=Buffer.alloc(150),J;try{J=d90.openSync(Y,"r"),d90.readSync(J,Q,0,150,0),d90.closeSync(J)}catch(G){}return Mc4(Q.toString())}t36.exports=wc4});var JH6=P((Fr1,QH6)=>{var Pc4=q0("path"),YH6=n36(),XH6=i36(),Ac4=e36(),Tc4=process.platform==="win32",Ec4=/\.(?:com|exe)$/i,Ic4=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function Cc4(Y){Y.file=YH6(Y);let X=Y.file&&Ac4(Y.file);if(X)return Y.args.unshift(Y.file),Y.command=X,YH6(Y);return Y.file}function Rc4(Y){if(!Tc4)return Y;let X=Cc4(Y),Q=!Ec4.test(X);if(Y.options.forceShell||Q){let J=Ic4.test(X);Y.command=Pc4.normalize(Y.command),Y.command=XH6.command(Y.command),Y.args=Y.args.map((K)=>XH6.argument(K,J));let G=[Y.command].concat(Y.args).join(" ");Y.args=["/d","/s","/c",`"${G}"`],Y.command=process.env.comspec||"cmd.exe",Y.options.windowsVerbatimArguments=!0}return Y}function Sc4(Y,X,Q){if(X&&!Array.isArray(X))Q=X,X=null;X=X?X.slice(0):[],Q=Object.assign({},Q);let J={command:Y,args:X,options:Q,file:void 0,original:{command:Y,args:X}};return Q.shell?J:Rc4(J)}QH6.exports=Sc4});var ZH6=P((Vr1,WH6)=>{var p90=process.platform==="win32";function c90(Y,X){return Object.assign(Error(`${X} ${Y.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${X} ${Y.command}`,path:Y.command,spawnargs:Y.args})}function jc4(Y,X){if(!p90)return;let Q=Y.emit;Y.emit=function(J,G){if(J==="exit"){let K=GH6(G,X);if(K)return Q.call(Y,"error",K)}return Q.apply(Y,arguments)}}function GH6(Y,X){if(p90&&Y===1&&!X.file)return c90(X.original,"spawn");return null}function kc4(Y,X){if(p90&&Y===1&&!X.file)return c90(X.original,"spawnSync");return null}WH6.exports={hookChildProcess:jc4,verifyENOENT:GH6,verifyENOENTSync:kc4,notFoundError:c90}});var FH6=P((qr1,gB)=>{var KH6=q0("child_process"),n90=JH6(),i90=ZH6();function HH6(Y,X,Q){let J=n90(Y,X,Q),G=KH6.spawn(J.command,J.args,J.options);return i90.hookChildProcess(G,J),G}function vc4(Y,X,Q){let J=n90(Y,X,Q),G=KH6.spawnSync(J.command,J.args,J.options);return G.error=G.error||i90.verifyENOENTSync(G.status,J),G}gB.exports=HH6;gB.exports.spawn=HH6;gB.exports.sync=vc4;gB.exports._parse=n90;gB.exports._enoent=i90});class a90{append(Y){this._buffer=this._buffer?Buffer.concat([this._buffer,Y]):Y}readMessage(){if(!this._buffer)return null;let Y=this._buffer.indexOf(`
385
385
  `);if(Y===-1)return null;let X=this._buffer.toString("utf8",0,Y).replace(/\r$/,"");return this._buffer=this._buffer.subarray(Y+1),_c4(X)}clear(){this._buffer=void 0}}function _c4(Y){return bQ.parse(JSON.parse(Y))}function VH6(Y){return JSON.stringify(Y)+`
386
386
  `}var qH6=m(()=>{xQ()});import Af from"process";import{PassThrough as yc4}from"stream";function hc4(){let Y={};for(let X of fc4){let Q=Af.env[X];if(Q===void 0)continue;if(Q.startsWith("()"))continue;Y[X]=Q}return Y}class r90{constructor(Y){if(this._readBuffer=new a90,this._stderrStream=null,this._serverParams=Y,Y.stderr==="pipe"||Y.stderr==="overlapped")this._stderrStream=new yc4}async start(){if(this._process)throw Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((Y,X)=>{if(this._process=$H6.default(this._serverParams.command,this._serverParams.args??[],{env:{...hc4(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:Af.platform==="win32"&&bc4(),cwd:this._serverParams.cwd}),this._process.on("error",(Q)=>{X(Q),this.onerror?.(Q)}),this._process.on("spawn",()=>{Y()}),this._process.on("close",(Q)=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",(Q)=>{this.onerror?.(Q)}),this._process.stdout?.on("data",(Q)=>{this._readBuffer.append(Q),this.processReadBuffer()}),this._process.stdout?.on("error",(Q)=>{this.onerror?.(Q)}),this._stderrStream&&this._process.stderr)this._process.stderr.pipe(this._stderrStream)})}get stderr(){if(this._stderrStream)return this._stderrStream;return this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){while(!0)try{let Y=this._readBuffer.readMessage();if(Y===null)break;this.onmessage?.(Y)}catch(Y){this.onerror?.(Y)}}async close(){if(this._process){let Y=this._process;this._process=void 0;let X=new Promise((Q)=>{Y.once("close",()=>{Q()})});try{Y.stdin?.end()}catch{}if(await Promise.race([X,new Promise((Q)=>setTimeout(Q,2000).unref())]),Y.exitCode===null){try{Y.kill("SIGTERM")}catch{}await Promise.race([X,new Promise((Q)=>setTimeout(Q,2000).unref())])}if(Y.exitCode===null)try{Y.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(Y){return new Promise((X)=>{if(!this._process?.stdin)throw Error("Not connected");let Q=VH6(Y);if(this._process.stdin.write(Q))X();else this._process.stdin.once("drain",X)})}}function bc4(){return"type"in Af}var $H6,fc4;var zH6=m(()=>{qH6();$H6=E4(FH6(),1),fc4=Af.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"]});async function mB(Y){switch(Y.connection_type){case"STDIO":return gc4(Y);case"HTTP":case"Websocket":return xc4(Y);case"SSE":return uc4(Y);case"VIRTUAL":return null;default:return null}}async function xc4(Y){if(!Y.connection_url)return console.error(`HTTP connection ${Y.id} missing URL`),null;let X=null;try{let Q={"Content-Type":"application/json"};if(Y.connection_token)Q.Authorization=`Bearer ${Y.connection_token}`;let J=Y.connection_headers;if(J?.headers)Object.assign(Q,J.headers);let G=new jB(new URL(Y.connection_url),{requestInit:{headers:Q}});X=new G3({name:"mcp-mesh-tool-fetcher",version:"1.0.0"});let K=new Promise((Z,H)=>{setTimeout(()=>H(Error("Connection timeout")),1e4)});await Promise.race([X.connect(G),K]);let W=await Promise.race([X.listTools(),K]);if(!W.tools||W.tools.length===0)return null;return W.tools.map((Z)=>({name:Z.name,description:Z.description??void 0,inputSchema:Z.inputSchema??{},outputSchema:Z.outputSchema?{...Z.outputSchema,additionalProperties:!0}:void 0,annotations:Z.annotations??void 0,_meta:Z._meta??void 0}))}catch(Q){return console.error(`Failed to fetch tools from HTTP connection ${Y.id}:`,Q),null}finally{try{if(X&&typeof X.close==="function")await X.close()}catch(Q){console.warn(`Failed to close HTTP client for ${Y.id}:`,Q)}}}async function uc4(Y){if(!Y.connection_url)return console.error(`SSE connection ${Y.id} missing URL`),null;let X=null;try{let Q={"Content-Type":"application/json"};if(Y.connection_token)Q.Authorization=`Bearer ${Y.connection_token}`;let J=Y.connection_headers;if(J?.headers)Object.assign(Q,J.headers);let G=new DP(new URL(Y.connection_url),{requestInit:{headers:Q}});X=new G3({name:"mcp-mesh-tool-fetcher",version:"1.0.0"});let K=new Promise((Z,H)=>{setTimeout(()=>H(Error("SSE connection timeout")),15000)});await Promise.race([X.connect(G),K]);let W=await Promise.race([X.listTools(),K]);if(!W.tools||W.tools.length===0)return null;return W.tools.map((Z)=>({name:Z.name,description:Z.description??void 0,inputSchema:Z.inputSchema??{},outputSchema:Z.outputSchema?{...Z.outputSchema,additionalProperties:!0}:void 0,annotations:Z.annotations??void 0,_meta:Z._meta??void 0}))}catch(Q){return console.error(`Failed to fetch tools from SSE connection ${Y.id}:`,Q),null}finally{try{await X?.close()}catch(Q){console.warn(`Failed to close SSE client for ${Y.id}:`,Q)}}}async function gc4(Y){let X=qP(Y.connection_headers)?Y.connection_headers:null;if(!X)return console.error(`STDIO connection ${Y.id} missing parameters`),null;let Q=null;try{let J=new r90({command:X.command,args:X.args,env:X.envVars,cwd:X.cwd});Q=new G3({name:"mcp-mesh-tool-fetcher",version:"1.0.0"});let G=new Promise((W,Z)=>{setTimeout(()=>Z(Error("Tool fetch timeout")),1e4)});await Promise.race([Q.connect(J),G]);let K=await Promise.race([Q.listTools(),G]);if(!K.tools||K.tools.length===0)return null;return K.tools.map((W)=>({name:W.name,description:W.description??void 0,inputSchema:W.inputSchema??{},outputSchema:W.outputSchema??void 0,annotations:W.annotations??void 0,_meta:W._meta??void 0}))}catch(J){return console.error(`Failed to fetch tools from STDIO connection ${Y.id}:`,J),null}finally{try{if(Q&&typeof Q.close==="function")await Q.close()}catch(J){console.warn(`Failed to close STDIO client for ${Y.id}:`,J)}}}var Tf=m(()=>{sy();x90();zH6();zf();Z3()});class o90{constructor(Y){this._server=Y}requestStream(Y,X,Q){return this._server.requestStream(Y,X,Q)}async getTask(Y,X){return this._server.getTask({taskId:Y},X)}async getTaskResult(Y,X,Q){return this._server.getTaskResult({taskId:Y},X,Q)}async listTasks(Y,X){return this._server.listTasks(Y?{cursor:Y}:void 0,X)}async cancelTask(Y,X){return this._server.cancelTask({taskId:Y},X)}}var s90;var BH6=m(()=>{s10();xQ();X90();KB();s90=class s90 extends xw{constructor(Y,X){super(X);if(this._serverInfo=Y,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(fw.options.map((Q,J)=>[Q,J])),this.isMessageIgnored=(Q,J)=>{let G=this._loggingLevels.get(J);return G?this.LOG_LEVEL_SEVERITY.get(Q)<this.LOG_LEVEL_SEVERITY.get(G):!1},this._capabilities=X?.capabilities??{},this._instructions=X?.instructions,this._jsonSchemaValidator=X?.jsonSchemaValidator??new HP,this.setRequestHandler(b_,(Q)=>this._oninitialize(Q)),this.setNotificationHandler(x_,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(z10,async(Q,J)=>{let G=J.sessionId||J.requestInfo?.headers["mcp-session-id"]||void 0,{level:K}=Q.params,W=fw.safeParse(K);if(W.success)this._loggingLevels.set(G,W.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new o90(this)};return this._experimental}registerCapabilities(Y){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=Fy(this._capabilities,Y)}setRequestHandler(Y,X){let J=q7(Y)?.method;if(!J)throw Error("Schema is missing a method literal");let G;if(eX(J)){let W=J;G=W._zod?.def?.value??W.value}else{let W=J;G=W._def?.value??W.value}if(typeof G!=="string")throw Error("Schema method literal must be a string");if(G==="tools/call"){let W=async(Z,H)=>{let F=MX(qB,Z);if(!F.success){let B=F.error instanceof Error?F.error.message:String(F.error);throw new H6(O6.InvalidParams,`Invalid tools/call request: ${B}`)}let{params:V}=F.data,q=await Promise.resolve(X(Z,H));if(V.task){let B=MX(bW,q);if(!B.success){let U=B.error instanceof Error?B.error.message:String(B.error);throw new H6(O6.InvalidParams,`Invalid task creation result: ${U}`)}return B.data}let $=MX(rK,q);if(!$.success){let B=$.error instanceof Error?$.error.message:String($.error);throw new H6(O6.InvalidParams,`Invalid tools/call result: ${B}`)}return $.data};return super.setRequestHandler(Y,W)}return super.setRequestHandler(Y,X)}assertCapabilityForMethod(Y){switch(Y){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${Y})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${Y})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${Y})`);break;case"ping":break}}assertNotificationCapability(Y){switch(Y){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Y})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${Y})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${Y})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${Y})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${Y})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(Y){if(!this._capabilities)return;switch(Y){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${Y})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Y})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${Y})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${Y})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${Y})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${Y})`);break;case"ping":case"initialize":break}}assertTaskCapability(Y){ry(this._clientCapabilities?.tasks?.requests,Y,"Client")}assertTaskHandlerCapability(Y){if(!this._capabilities)return;ay(this._capabilities.tasks?.requests,Y,"Server")}async _oninitialize(Y){let X=Y.params.protocolVersion;return this._clientCapabilities=Y.params.capabilities,this._clientVersion=Y.params.clientInfo,{protocolVersion:YV.includes(X)?X:iK,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},hW)}async createMessage(Y,X){if(Y.tools||Y.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(Y.messages.length>0){let Q=Y.messages[Y.messages.length-1],J=Array.isArray(Q.content)?Q.content:[Q.content],G=J.some((H)=>H.type==="tool_result"),K=Y.messages.length>1?Y.messages[Y.messages.length-2]:void 0,W=K?Array.isArray(K.content)?K.content:[K.content]:[],Z=W.some((H)=>H.type==="tool_use");if(G){if(J.some((H)=>H.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!Z)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(Z){let H=new Set(W.filter((V)=>V.type==="tool_use").map((V)=>V.id)),F=new Set(J.filter((V)=>V.type==="tool_result").map((V)=>V.toolUseId));if(H.size!==F.size||![...H].every((V)=>F.has(V)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(Y.tools)return this.request({method:"sampling/createMessage",params:Y},U10,X);return this.request({method:"sampling/createMessage",params:Y},hw,X)}async elicitInput(Y,X){switch(Y.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let J=Y;return this.request({method:"elicitation/create",params:J},$B,X)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let J=Y.mode==="form"?Y:{...Y,mode:"form"},G=await this.request({method:"elicitation/create",params:J},$B,X);if(G.action==="accept"&&G.content&&J.requestedSchema)try{let W=this._jsonSchemaValidator.getValidator(J.requestedSchema)(G.content);if(!W.valid)throw new H6(O6.InvalidParams,`Elicitation response content does not match requested schema: ${W.errorMessage}`)}catch(K){if(K instanceof H6)throw K;throw new H6(O6.InternalError,`Error validating elicitation response: ${K instanceof Error?K.message:String(K)}`)}return G}}}createElicitationCompletionNotifier(Y,X){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:Y}},X)}async listRoots(Y,X){return this.request({method:"roots/list",params:Y},N10,X)}async sendLoggingMessage(Y,X){if(this._capabilities.logging){if(!this.isMessageIgnored(Y.level,X))return this.notification({method:"notifications/message",params:Y})}}async sendResourceUpdated(Y){return this.notification({method:"notifications/resources/updated",params:Y})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}});function t90(Y){return!!Y&&typeof Y==="object"&&DH6 in Y}function OH6(Y){return Y[DH6]?.complete}var DH6,UH6;var NH6=m(()=>{DH6=Symbol.for("mcp.completable");(function(Y){Y.Completable="McpCompletable"})(UH6||(UH6={}))});function lc4(Y){let X=[];if(Y.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(Y.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${Y.length})`]};if(Y.includes(" "))X.push("Tool name contains spaces, which may cause parsing issues");if(Y.includes(","))X.push("Tool name contains commas, which may cause parsing issues");if(Y.startsWith("-")||Y.endsWith("-"))X.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");if(Y.startsWith(".")||Y.endsWith("."))X.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");if(!mc4.test(Y)){let Q=Y.split("").filter((J)=>!/[A-Za-z0-9._-]/.test(J)).filter((J,G,K)=>K.indexOf(J)===G);return X.push(`Tool name contains invalid characters: ${Q.map((J)=>`"${J}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:X}}return{isValid:!0,warnings:X}}function dc4(Y,X){if(X.length>0){console.warn(`Tool name validation warning for "${Y}":`);for(let Q of X)console.warn(` - ${Q}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function e90(Y){let X=lc4(Y);return dc4(Y,X.warnings),X.isValid}var mc4;var LH6=m(()=>{mc4=/^[A-Za-z0-9._-]{1,128}$/});class YY0{constructor(Y){this._mcpServer=Y}registerToolTask(Y,X,Q){let J={taskSupport:"required",...X.execution};if(J.taskSupport==="forbidden")throw Error(`Cannot register task-based tool '${Y}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(Y,X.title,X.description,X.inputSchema,X.outputSchema,X.annotations,J,X._meta,Q)}}class QY0{constructor(Y,X){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new s90(Y,X)}get experimental(){if(!this._experimental)this._experimental={tasks:new YY0(this)};return this._experimental}async connect(Y){return await this.server.connect(Y)}async close(){await this.server.close()}setToolRequestHandlers(){if(this._toolHandlersInitialized)return;this.server.assertCanSetRequestHandler(H3(t_)),this.server.assertCanSetRequestHandler(H3(qB)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(t_,()=>({tools:Object.entries(this._registeredTools).filter(([,Y])=>Y.enabled).map(([Y,X])=>{let Q={name:Y,title:X.title,description:X.description,inputSchema:(()=>{let J=ZB(X.inputSchema);return J?i10(J,{strictUnions:!0,pipeStrategy:"input"}):pc4})(),annotations:X.annotations,execution:X.execution,_meta:X._meta};if(X.outputSchema){let J=ZB(X.outputSchema);if(J)Q.outputSchema=i10(J,{strictUnions:!0,pipeStrategy:"output"})}return Q})})),this.server.setRequestHandler(qB,async(Y,X)=>{try{let Q=this._registeredTools[Y.params.name];if(!Q)throw new H6(O6.InvalidParams,`Tool ${Y.params.name} not found`);if(!Q.enabled)throw new H6(O6.InvalidParams,`Tool ${Y.params.name} disabled`);let J=!!Y.params.task,G=Q.execution?.taskSupport,K="createTask"in Q.handler;if((G==="required"||G==="optional")&&!K)throw new H6(O6.InternalError,`Tool ${Y.params.name} has taskSupport '${G}' but was not registered with registerToolTask`);if(G==="required"&&!J)throw new H6(O6.MethodNotFound,`Tool ${Y.params.name} requires task augmentation (taskSupport: 'required')`);if(G==="optional"&&!J&&K)return await this.handleAutomaticTaskPolling(Q,Y,X);let W=await this.validateToolInput(Q,Y.params.arguments,Y.params.name),Z=await this.executeToolHandler(Q,W,X);if(J)return Z;return await this.validateToolOutput(Q,Z,Y.params.name),Z}catch(Q){if(Q instanceof H6){if(Q.code===O6.UrlElicitationRequired)throw Q}return this.createToolError(Q instanceof Error?Q.message:String(Q))}}),this._toolHandlersInitialized=!0}createToolError(Y){return{content:[{type:"text",text:Y}],isError:!0}}async validateToolInput(Y,X,Q){if(!Y.inputSchema)return;let G=ZB(Y.inputSchema)??Y.inputSchema,K=await j_(G,X);if(!K.success){let W="error"in K?K.error:"Unknown error",Z=k_(W);throw new H6(O6.InvalidParams,`Input validation error: Invalid arguments for tool ${Q}: ${Z}`)}return K.data}async validateToolOutput(Y,X,Q){if(!Y.outputSchema)return;if(!("content"in X))return;if(X.isError)return;if(!X.structuredContent)throw new H6(O6.InvalidParams,`Output validation error: Tool ${Q} has an output schema but no structured content was provided`);let J=ZB(Y.outputSchema),G=await j_(J,X.structuredContent);if(!G.success){let K="error"in G?G.error:"Unknown error",W=k_(K);throw new H6(O6.InvalidParams,`Output validation error: Invalid structured content for tool ${Q}: ${W}`)}}async executeToolHandler(Y,X,Q){let J=Y.handler;if("createTask"in J){if(!Q.taskStore)throw Error("No task store provided.");let K={...Q,taskStore:Q.taskStore};if(Y.inputSchema)return await Promise.resolve(J.createTask(X,K));else return await Promise.resolve(J.createTask(K))}if(Y.inputSchema)return await Promise.resolve(J(X,Q));else return await Promise.resolve(J(Q))}async handleAutomaticTaskPolling(Y,X,Q){if(!Q.taskStore)throw Error("No task store provided for task-capable tool.");let J=await this.validateToolInput(Y,X.params.arguments,X.params.name),G=Y.handler,K={...Q,taskStore:Q.taskStore},W=J?await Promise.resolve(G.createTask(J,K)):await Promise.resolve(G.createTask(K)),Z=W.task.taskId,H=W.task,F=H.pollInterval??5000;while(H.status!=="completed"&&H.status!=="failed"&&H.status!=="cancelled"){await new Promise((q)=>setTimeout(q,F));let V=await Q.taskStore.getTask(Z);if(!V)throw new H6(O6.InternalError,`Task ${Z} not found during polling`);H=V}return await Q.taskStore.getTaskResult(Z)}setCompletionRequestHandler(){if(this._completionHandlerInitialized)return;this.server.assertCanSetRequestHandler(H3(e_)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(e_,async(Y)=>{switch(Y.params.ref.type){case"ref/prompt":return $56(Y),this.handlePromptCompletion(Y,Y.params.ref);case"ref/resource":return z56(Y),this.handleResourceCompletion(Y,Y.params.ref);default:throw new H6(O6.InvalidParams,`Invalid completion reference: ${Y.params.ref}`)}}),this._completionHandlerInitialized=!0}async handlePromptCompletion(Y,X){let Q=this._registeredPrompts[X.name];if(!Q)throw new H6(O6.InvalidParams,`Prompt ${X.name} not found`);if(!Q.enabled)throw new H6(O6.InvalidParams,`Prompt ${X.name} disabled`);if(!Q.argsSchema)return OP;let G=q7(Q.argsSchema)?.[Y.params.argument.name];if(!t90(G))return OP;let K=OH6(G);if(!K)return OP;let W=await K(Y.params.argument.value,Y.params.context);return wH6(W)}async handleResourceCompletion(Y,X){let Q=Object.values(this._registeredResourceTemplates).find((K)=>K.resourceTemplate.uriTemplate.toString()===X.uri);if(!Q){if(this._registeredResources[X.uri])return OP;throw new H6(O6.InvalidParams,`Resource template ${Y.params.ref.uri} not found`)}let J=Q.resourceTemplate.completeCallback(Y.params.argument.name);if(!J)return OP;let G=await J(Y.params.argument.value,Y.params.context);return wH6(G)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(H3(i_)),this.server.assertCanSetRequestHandler(H3(a_)),this.server.assertCanSetRequestHandler(H3(r_)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(i_,async(Y,X)=>{let Q=Object.entries(this._registeredResources).filter(([G,K])=>K.enabled).map(([G,K])=>({uri:G,name:K.name,...K.metadata})),J=[];for(let G of Object.values(this._registeredResourceTemplates)){if(!G.resourceTemplate.listCallback)continue;let K=await G.resourceTemplate.listCallback(X);for(let W of K.resources)J.push({...G.metadata,...W})}return{resources:[...Q,...J]}}),this.server.setRequestHandler(a_,async()=>{return{resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([X,Q])=>({name:X,uriTemplate:Q.resourceTemplate.uriTemplate.toString(),...Q.metadata}))}}),this.server.setRequestHandler(r_,async(Y,X)=>{let Q=new URL(Y.params.uri),J=this._registeredResources[Q.toString()];if(J){if(!J.enabled)throw new H6(O6.InvalidParams,`Resource ${Q} disabled`);return J.readCallback(Q,X)}for(let G of Object.values(this._registeredResourceTemplates)){let K=G.resourceTemplate.uriTemplate.match(Q.toString());if(K)return G.readCallback(Q,K,X)}throw new H6(O6.InvalidParams,`Resource ${Q} not found`)}),this._resourceHandlersInitialized=!0}setPromptRequestHandlers(){if(this._promptHandlersInitialized)return;this.server.assertCanSetRequestHandler(H3(o_)),this.server.assertCanSetRequestHandler(H3(s_)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(o_,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,Y])=>Y.enabled).map(([Y,X])=>{return{name:Y,title:X.title,description:X.description,arguments:X.argsSchema?nc4(X.argsSchema):void 0}})})),this.server.setRequestHandler(s_,async(Y,X)=>{let Q=this._registeredPrompts[Y.params.name];if(!Q)throw new H6(O6.InvalidParams,`Prompt ${Y.params.name} not found`);if(!Q.enabled)throw new H6(O6.InvalidParams,`Prompt ${Y.params.name} disabled`);if(Q.argsSchema){let J=ZB(Q.argsSchema),G=await j_(J,Y.params.arguments);if(!G.success){let Z="error"in G?G.error:"Unknown error",H=k_(Z);throw new H6(O6.InvalidParams,`Invalid arguments for prompt ${Y.params.name}: ${H}`)}let K=G.data,W=Q.callback;return await Promise.resolve(W(K,X))}else{let J=Q.callback;return await Promise.resolve(J(X))}}),this._promptHandlersInitialized=!0}resource(Y,X,...Q){let J;if(typeof Q[0]==="object")J=Q.shift();let G=Q[0];if(typeof X==="string"){if(this._registeredResources[X])throw Error(`Resource ${X} is already registered`);let K=this._createRegisteredResource(Y,void 0,X,J,G);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),K}else{if(this._registeredResourceTemplates[Y])throw Error(`Resource template ${Y} is already registered`);let K=this._createRegisteredResourceTemplate(Y,void 0,X,J,G);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),K}}registerResource(Y,X,Q,J){if(typeof X==="string"){if(this._registeredResources[X])throw Error(`Resource ${X} is already registered`);let G=this._createRegisteredResource(Y,Q.title,X,Q,J);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),G}else{if(this._registeredResourceTemplates[Y])throw Error(`Resource template ${Y} is already registered`);let G=this._createRegisteredResourceTemplate(Y,Q.title,X,Q,J);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),G}}_createRegisteredResource(Y,X,Q,J,G){let K={name:Y,title:X,metadata:J,readCallback:G,enabled:!0,disable:()=>K.update({enabled:!1}),enable:()=>K.update({enabled:!0}),remove:()=>K.update({uri:null}),update:(W)=>{if(typeof W.uri<"u"&&W.uri!==Q){if(delete this._registeredResources[Q],W.uri)this._registeredResources[W.uri]=K}if(typeof W.name<"u")K.name=W.name;if(typeof W.title<"u")K.title=W.title;if(typeof W.metadata<"u")K.metadata=W.metadata;if(typeof W.callback<"u")K.readCallback=W.callback;if(typeof W.enabled<"u")K.enabled=W.enabled;this.sendResourceListChanged()}};return this._registeredResources[Q]=K,K}_createRegisteredResourceTemplate(Y,X,Q,J,G){let K={resourceTemplate:Q,title:X,metadata:J,readCallback:G,enabled:!0,disable:()=>K.update({enabled:!1}),enable:()=>K.update({enabled:!0}),remove:()=>K.update({name:null}),update:(H)=>{if(typeof H.name<"u"&&H.name!==Y){if(delete this._registeredResourceTemplates[Y],H.name)this._registeredResourceTemplates[H.name]=K}if(typeof H.title<"u")K.title=H.title;if(typeof H.template<"u")K.resourceTemplate=H.template;if(typeof H.metadata<"u")K.metadata=H.metadata;if(typeof H.callback<"u")K.readCallback=H.callback;if(typeof H.enabled<"u")K.enabled=H.enabled;this.sendResourceListChanged()}};this._registeredResourceTemplates[Y]=K;let W=Q.uriTemplate.variableNames;if(Array.isArray(W)&&W.some((H)=>!!Q.completeCallback(H)))this.setCompletionRequestHandler();return K}_createRegisteredPrompt(Y,X,Q,J,G){let K={title:X,description:Q,argsSchema:J===void 0?void 0:eF(J),callback:G,enabled:!0,disable:()=>K.update({enabled:!1}),enable:()=>K.update({enabled:!0}),remove:()=>K.update({name:null}),update:(W)=>{if(typeof W.name<"u"&&W.name!==Y){if(delete this._registeredPrompts[Y],W.name)this._registeredPrompts[W.name]=K}if(typeof W.title<"u")K.title=W.title;if(typeof W.description<"u")K.description=W.description;if(typeof W.argsSchema<"u")K.argsSchema=eF(W.argsSchema);if(typeof W.callback<"u")K.callback=W.callback;if(typeof W.enabled<"u")K.enabled=W.enabled;this.sendPromptListChanged()}};if(this._registeredPrompts[Y]=K,J){if(Object.values(J).some((Z)=>{let H=Z instanceof i9?Z._def?.innerType:Z;return t90(H)}))this.setCompletionRequestHandler()}return K}_createRegisteredTool(Y,X,Q,J,G,K,W,Z,H){e90(Y);let F={title:X,description:Q,inputSchema:MH6(J),outputSchema:MH6(G),annotations:K,execution:W,_meta:Z,handler:H,enabled:!0,disable:()=>F.update({enabled:!1}),enable:()=>F.update({enabled:!0}),remove:()=>F.update({name:null}),update:(V)=>{if(typeof V.name<"u"&&V.name!==Y){if(typeof V.name==="string")e90(V.name);if(delete this._registeredTools[Y],V.name)this._registeredTools[V.name]=F}if(typeof V.title<"u")F.title=V.title;if(typeof V.description<"u")F.description=V.description;if(typeof V.paramsSchema<"u")F.inputSchema=eF(V.paramsSchema);if(typeof V.outputSchema<"u")F.outputSchema=eF(V.outputSchema);if(typeof V.callback<"u")F.handler=V.callback;if(typeof V.annotations<"u")F.annotations=V.annotations;if(typeof V._meta<"u")F._meta=V._meta;if(typeof V.enabled<"u")F.enabled=V.enabled;this.sendToolListChanged()}};return this._registeredTools[Y]=F,this.setToolRequestHandlers(),this.sendToolListChanged(),F}tool(Y,...X){if(this._registeredTools[Y])throw Error(`Tool ${Y} is already registered`);let Q,J,G,K;if(typeof X[0]==="string")Q=X.shift();if(X.length>1){let Z=X[0];if(XY0(Z)){if(J=X.shift(),X.length>1&&typeof X[0]==="object"&&X[0]!==null&&!XY0(X[0]))K=X.shift()}else if(typeof Z==="object"&&Z!==null)K=X.shift()}let W=X[0];return this._createRegisteredTool(Y,void 0,Q,J,G,K,{taskSupport:"forbidden"},void 0,W)}registerTool(Y,X,Q){if(this._registeredTools[Y])throw Error(`Tool ${Y} is already registered`);let{title:J,description:G,inputSchema:K,outputSchema:W,annotations:Z,_meta:H}=X;return this._createRegisteredTool(Y,J,G,K,W,Z,{taskSupport:"forbidden"},H,Q)}prompt(Y,...X){if(this._registeredPrompts[Y])throw Error(`Prompt ${Y} is already registered`);let Q;if(typeof X[0]==="string")Q=X.shift();let J;if(X.length>1)J=X.shift();let G=X[0],K=this._createRegisteredPrompt(Y,void 0,Q,J,G);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),K}registerPrompt(Y,X,Q){if(this._registeredPrompts[Y])throw Error(`Prompt ${Y} is already registered`);let{title:J,description:G,argsSchema:K}=X,W=this._createRegisteredPrompt(Y,J,G,K,Q);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),W}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(Y,X){return this.server.sendLoggingMessage(Y,X)}sendResourceListChanged(){if(this.isConnected())this.server.sendResourceListChanged()}sendToolListChanged(){if(this.isConnected())this.server.sendToolListChanged()}sendPromptListChanged(){if(this.isConnected())this.server.sendPromptListChanged()}}function PH6(Y){return Y!==null&&typeof Y==="object"&&"parse"in Y&&typeof Y.parse==="function"&&"safeParse"in Y&&typeof Y.safeParse==="function"}function cc4(Y){return"_def"in Y||"_zod"in Y||PH6(Y)}function XY0(Y){if(typeof Y!=="object"||Y===null)return!1;if(cc4(Y))return!1;if(Object.keys(Y).length===0)return!0;return Object.values(Y).some(PH6)}function MH6(Y){if(!Y)return;if(XY0(Y))return eF(Y);return Y}function nc4(Y){let X=q7(Y);if(!X)return[];return Object.entries(X).map(([Q,J])=>{let G=aJ6(J),K=rJ6(J);return{name:Q,description:G,required:!K}})}function H3(Y){let Q=q7(Y)?.method;if(!Q)throw Error("Schema is missing a method literal");let J=v_(Q);if(typeof J==="string")return J;throw Error("Schema method literal must be a string")}function wH6(Y){return{completion:{values:Y.slice(0,100),total:Y.length,hasMore:Y.length>100}}}var pc4,OP;var AH6=m(()=>{BH6();KB();o10();xQ();NH6();LH6();Y6();pc4={type:"object",properties:{}};OP={completion:{values:[],hasMore:!1}}});class JY0{constructor(Y={}){this._started=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId="_GET_stream",this.sessionIdGenerator=Y.sessionIdGenerator,this._enableJsonResponse=Y.enableJsonResponse??!1,this._eventStore=Y.eventStore,this._onsessioninitialized=Y.onsessioninitialized,this._onsessionclosed=Y.onsessionclosed,this._allowedHosts=Y.allowedHosts,this._allowedOrigins=Y.allowedOrigins,this._enableDnsRebindingProtection=Y.enableDnsRebindingProtection??!1,this._retryInterval=Y.retryInterval}async start(){if(this._started)throw Error("Transport already started");this._started=!0}createJsonErrorResponse(Y,X,Q,J){let G={code:X,message:Q};if(J?.data!==void 0)G.data=J.data;return new Response(JSON.stringify({jsonrpc:"2.0",error:G,id:null}),{status:Y,headers:{"Content-Type":"application/json",...J?.headers}})}validateRequestHeaders(Y){if(!this._enableDnsRebindingProtection)return;if(this._allowedHosts&&this._allowedHosts.length>0){let X=Y.headers.get("host");if(!X||!this._allowedHosts.includes(X)){let Q=`Invalid Host header: ${X}`;return this.onerror?.(Error(Q)),this.createJsonErrorResponse(403,-32000,Q)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let X=Y.headers.get("origin");if(X&&!this._allowedOrigins.includes(X)){let Q=`Invalid Origin header: ${X}`;return this.onerror?.(Error(Q)),this.createJsonErrorResponse(403,-32000,Q)}}return}async handleRequest(Y,X){let Q=this.validateRequestHeaders(Y);if(Q)return Q;switch(Y.method){case"POST":return this.handlePostRequest(Y,X);case"GET":return this.handleGetRequest(Y);case"DELETE":return this.handleDeleteRequest(Y);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(Y,X,Q,J){if(!this._eventStore)return;if(J<"2025-11-25")return;let G=await this._eventStore.storeEvent(Q,{}),K=`id: ${G}
387
387
  data:
@@ -395,16 +395,16 @@ data:
395
395
  `;return G+=`data: ${JSON.stringify(Q)}
396
396
 
397
397
  `,Y.enqueue(X.encode(G)),!0}catch{return!1}}handleUnsupportedRequest(){return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32000,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(Y,X){try{let Q=Y.headers.get("accept");if(!Q?.includes("application/json")||!Q.includes("text/event-stream"))return this.createJsonErrorResponse(406,-32000,"Not Acceptable: Client must accept both application/json and text/event-stream");let J=Y.headers.get("content-type");if(!J||!J.includes("application/json"))return this.createJsonErrorResponse(415,-32000,"Unsupported Media Type: Content-Type must be application/json");let G={headers:Object.fromEntries(Y.headers.entries())},K;if(X?.parsedBody!==void 0)K=X.parsedBody;else try{K=await Y.json()}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}let W;try{if(Array.isArray(K))W=K.map((L)=>bQ.parse(L));else W=[bQ.parse(K)]}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let Z=W.some(s40);if(Z){if(this._initialized&&this.sessionId!==void 0)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(W.length>1)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");if(this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized)await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!Z){let L=this.validateSession(Y);if(L)return L;let M=this.validateProtocolVersion(Y);if(M)return M}if(!W.some($7)){for(let L of W)this.onmessage?.(L,{authInfo:X?.authInfo,requestInfo:G});return new Response(null,{status:202})}let F=crypto.randomUUID(),V=W.find((L)=>s40(L)),q=V?V.params.protocolVersion:Y.headers.get("mcp-protocol-version")??oJ6;if(this._enableJsonResponse)return new Promise((L)=>{this._streamMapping.set(F,{resolveJson:L,cleanup:()=>{this._streamMapping.delete(F)}});for(let M of W)if($7(M))this._requestToStreamMapping.set(M.id,F);for(let M of W)this.onmessage?.(M,{authInfo:X?.authInfo,requestInfo:G})});let $=new TextEncoder,B,U=new ReadableStream({start:(L)=>{B=L},cancel:()=>{this._streamMapping.delete(F)}}),D={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};if(this.sessionId!==void 0)D["mcp-session-id"]=this.sessionId;for(let L of W)if($7(L))this._streamMapping.set(F,{controller:B,encoder:$,cleanup:()=>{this._streamMapping.delete(F);try{B.close()}catch{}}}),this._requestToStreamMapping.set(L.id,F);await this.writePrimingEvent(B,$,F,q);for(let L of W){let M,I;if($7(L)&&this._eventStore&&q>="2025-11-25")M=()=>{this.closeSSEStream(L.id)},I=()=>{this.closeStandaloneSSEStream()};this.onmessage?.(L,{authInfo:X?.authInfo,requestInfo:G,closeSSEStream:M,closeStandaloneSSEStream:I})}return new Response(U,{status:200,headers:D})}catch(Q){return this.onerror?.(Q),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(Q)})}}async handleDeleteRequest(Y){let X=this.validateSession(Y);if(X)return X;let Q=this.validateProtocolVersion(Y);if(Q)return Q;return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200})}validateSession(Y){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.createJsonErrorResponse(400,-32000,"Bad Request: Server not initialized");let X=Y.headers.get("mcp-session-id");if(!X)return this.createJsonErrorResponse(400,-32000,"Bad Request: Mcp-Session-Id header is required");if(X!==this.sessionId)return this.createJsonErrorResponse(404,-32001,"Session not found");return}validateProtocolVersion(Y){let X=Y.headers.get("mcp-protocol-version");if(X!==null&&!YV.includes(X))return this.createJsonErrorResponse(400,-32000,`Bad Request: Unsupported protocol version: ${X} (supported versions: ${YV.join(", ")})`);return}async close(){this._streamMapping.forEach(({cleanup:Y})=>{Y()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(Y){let X=this._requestToStreamMapping.get(Y);if(!X)return;let Q=this._streamMapping.get(X);if(Q)Q.cleanup()}closeStandaloneSSEStream(){let Y=this._streamMapping.get(this._standaloneSseStreamId);if(Y)Y.cleanup()}async send(Y,X){let Q=X?.relatedRequestId;if(y5(Y)||FB(Y))Q=Y.id;if(Q===void 0){if(y5(Y)||FB(Y))throw Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let K;if(this._eventStore)K=await this._eventStore.storeEvent(this._standaloneSseStreamId,Y);let W=this._streamMapping.get(this._standaloneSseStreamId);if(W===void 0)return;if(W.controller&&W.encoder)this.writeSSEEvent(W.controller,W.encoder,Y,K);return}let J=this._requestToStreamMapping.get(Q);if(!J)throw Error(`No connection established for request ID: ${String(Q)}`);let G=this._streamMapping.get(J);if(!this._enableJsonResponse&&G?.controller&&G?.encoder){let K;if(this._eventStore)K=await this._eventStore.storeEvent(J,Y);this.writeSSEEvent(G.controller,G.encoder,Y,K)}if(y5(Y)||FB(Y)){this._requestResponseMap.set(Q,Y);let K=Array.from(this._requestToStreamMapping.entries()).filter(([Z,H])=>H===J).map(([Z])=>Z);if(K.every((Z)=>this._requestResponseMap.has(Z))){if(!G)throw Error(`No connection established for request ID: ${String(Q)}`);if(this._enableJsonResponse&&G.resolveJson){let Z={"Content-Type":"application/json"};if(this.sessionId!==void 0)Z["mcp-session-id"]=this.sessionId;let H=K.map((F)=>this._requestResponseMap.get(F));if(H.length===1)G.resolveJson(new Response(JSON.stringify(H[0]),{status:200,headers:Z}));else G.resolveJson(new Response(JSON.stringify(H),{status:200,headers:Z}))}else G.cleanup();for(let Z of K)this._requestResponseMap.delete(Z),this._requestToStreamMapping.delete(Z)}}}}var TH6=m(()=>{xQ()});var EH6=(...Y)=>{return function(Q,J){let G=(K)=>{let W=Y[K];if(!W)return J();return W(Q,()=>G(K+1))};return G(0)}};class IH6{config;tools=[];callToolMiddlewares=[];jsonSchemaCache=new Map;constructor(Y){this.config={...Y,capabilities:Y.capabilities??{tools:{}}}}getCachedJsonSchema(Y){let X=this.jsonSchemaCache.get(Y);if(!X)X=N.toJSONSchema(Y),this.jsonSchemaCache.set(Y,X);return X}withTool(Y){return this.tools.push(Y),this}withTools(Y){return this.tools.push(...Y),this}callToolMiddleware(...Y){return this.callToolMiddlewares.push(...Y),this}build(){let Y=this.callToolMiddlewares.length>0?EH6(...this.callToolMiddlewares):null,X=()=>{let Q=new QY0({name:this.config.name,version:this.config.version},{capabilities:this.config.capabilities});for(let J of this.tools){let G=async(H)=>{try{let F=await J.handler(H);return{content:[{type:"text",text:JSON.stringify(F)}],structuredContent:F}}catch(F){return{content:[{type:"text",text:`Error: ${F.message}`}],isError:!0}}},K=Y?async(H)=>{let F={method:"tools/call",params:{name:J.name,arguments:H}};return await Y(F,()=>G(H))}:G,W="shape"in J.inputSchema?J.inputSchema.shape:N.object({}).shape,Z=J.outputSchema&&"shape"in J.outputSchema?J.outputSchema.shape:N.object({}).shape;Q.registerTool(J.name,{annotations:J.annotations,description:J.description??"",inputSchema:W,outputSchema:Z},K)}return Q};return{callStreamableTool:async(Q,J)=>{let G=this.tools.find((W)=>W.name===Q);if(!G)throw Error(`Tool ${Q} not found`);let K=await G.handler(J);if(!(K instanceof Response))throw Error(`Tool ${Q} returned a non-response`);return K},client:{listTools:async()=>{return{tools:this.tools.map((Q)=>({name:Q.name,description:Q.description??"",inputSchema:this.getCachedJsonSchema(Q.inputSchema),outputSchema:Q.outputSchema?this.getCachedJsonSchema(Q.outputSchema):void 0}))}},callTool:async(Q)=>{let J=this.tools.find((G)=>G.name===Q.name);if(!J)return{content:[{type:"text",text:"Tool not found"}]};try{let G=await J?.handler(Q.arguments??{});return{content:[{type:"text",text:JSON.stringify(G)}],structuredContent:G}}catch(G){return{content:[{type:"text",text:`Error: ${G.message}`}]}}}},fetch:async(Q)=>{let J=new JY0({enableJsonResponse:Q.headers.get("Accept")?.includes("application/json")??!1});await X().connect(J);try{return await J.handleRequest(Q)}finally{try{await J.close?.()}catch{}}}}}}function CH6(Y){return new IH6(Y)}var RH6=m(()=>{AH6();TH6();Y6()});function X6(Y){return{...Y,execute:async(X,Q)=>{let J=Date.now();return await Q.timings.measure(`tool.${Y.name}`,async()=>Q.tracer.startActiveSpan(`tool.${Y.name}`,{attributes:{"tool.name":Y.name,"organization.id":Q.organization?.id??"system","user.id":Q.auth.user?.id??Q.auth.apiKey?.userId??"anonymous"}},async(G)=>{try{Q.toolName=Y.name,Q.access.setToolName?.(Y.name);let K=await Y.handler(X,Q),W=Date.now()-J;return Q.meter.createHistogram("tool.execution.duration",{description:"Duration of tool executions in milliseconds",unit:"ms"}).record(W,{"tool.name":Y.name,"organization.id":Q.organization?.id??"system",status:"success"}),Q.meter.createCounter("tool.execution.count",{description:"Number of tool executions"}).add(1,{"tool.name":Y.name,status:"success"}),G.setStatus({code:GY0.SpanStatusCode.OK}),K}catch(K){throw Q.meter.createCounter("tool.execution.errors",{description:"Number of tool execution errors"}).add(1,{"tool.name":Y.name,"error.type":K.constructor.name}),G.setStatus({code:GY0.SpanStatusCode.ERROR,message:K.message}),G.recordException(K),K}finally{G.end()}}))}}}var GY0;var J4=m(()=>{GY0=E4(_0(),1)});function S6(Y){if(!Y.organization)throw Error("This operation requires organization scope");return Y.organization}function x8(Y){return Y.auth.user?.id??Y.auth.apiKey?.userId}function ic4(Y){return!!(Y.auth.user||Y.auth.apiKey)}function $6(Y){if(!ic4(Y))throw Error("Authentication required")}var Ef,SH6,jH6,kH6,vH6,_H6,yH6,fH6,hH6,bH6;var lB=m(()=>{Y6();Ef=N.record(N.string(),N.array(N.string())),SH6=N.object({id:N.string().describe("Unique identifier for the API key"),name:N.string().describe("Human-readable name for the API key"),userId:N.string().describe("ID of the user who owns this API key"),permissions:Ef.describe('Permissions granted to this API key. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Example: { "self": ["API_KEY_CREATE"], "conn_abc123": ["SEND_MESSAGE"] }'),expiresAt:N.string().datetime().nullable().optional().describe("Expiration date of the API key (ISO 8601)"),createdAt:N.string().datetime().describe("When the API key was created (ISO 8601)")}),jH6=N.object({name:N.string().min(1).max(64).describe("Human-readable name for the API key"),permissions:Ef.optional().describe('Permissions to grant. Format: { resource: [actions] }. Resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Actions are tool names (e.g., ["API_KEY_CREATE"]) or ["*"] for all. Example: { "self": ["API_KEY_CREATE", "COLLECTION_CONNECTIONS_LIST"] }. Defaults to read-only permissions.'),expiresIn:N.number().positive().optional().describe("Expiration time in seconds. If not provided, key never expires."),metadata:N.record(N.string(),N.unknown()).optional().describe("Additional metadata to store with the API key")}),kH6=N.object({id:N.string().describe("Unique identifier for the API key"),name:N.string().describe("Human-readable name for the API key"),key:N.string().describe("The actual API key value. STORE THIS SECURELY - it will not be shown again!"),permissions:Ef.describe('Permissions granted to this API key. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools'),expiresAt:N.string().datetime().nullable().optional().describe("Expiration date of the API key (ISO 8601)"),createdAt:N.string().datetime().describe("When the API key was created (ISO 8601)")}),vH6=N.object({}),_H6=N.object({items:N.array(SH6).describe("List of API keys (without key values)")}),yH6=N.object({keyId:N.string().describe("ID of the API key to update"),name:N.string().min(1).max(64).optional().describe("New name for the API key"),permissions:Ef.optional().describe('New permissions. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Actions are tool names or "*" for all. Example: { "self": ["API_KEY_CREATE"] }. Replaces existing permissions.'),metadata:N.record(N.string(),N.unknown()).optional().describe("New metadata. Replaces existing metadata.")}),fH6=N.object({item:SH6.describe("The updated API key (without key value)")}),hH6=N.object({keyId:N.string().describe("ID of the API key to delete")}),bH6=N.object({success:N.boolean().describe("Whether the deletion was successful"),keyId:N.string().describe("ID of the deleted API key")})});var WY0;var xH6=m(()=>{J4();lB();WY0=X6({name:"API_KEY_CREATE",description:"Create a new API key with specified permissions. The key value is only returned once - store it securely!",inputSchema:jH6,outputSchema:kH6,handler:async(Y,X)=>{$6(X),await X.access.check();let Q=await X.boundAuth.apiKey.create({name:Y.name,permissions:Y.permissions,expiresIn:Y.expiresIn,metadata:{...Y.metadata,organization:X.organization}}),J=Q.expiresAt?Q.expiresAt instanceof Date?Q.expiresAt.toISOString():Q.expiresAt:null,G=Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt;return{id:Q.id,name:Q.name??Y.name,key:Q.key,permissions:Q.permissions??{},expiresAt:J,createdAt:G}}})});var ZY0;var uH6=m(()=>{J4();lB();ZY0=X6({name:"API_KEY_DELETE",description:"Delete an API key. This instantly revokes the key - it can no longer be used for authentication.",inputSchema:hH6,outputSchema:bH6,handler:async(Y,X)=>{if($6(X),await X.access.check(),!x8(X))throw Error("User ID required to delete API key");let G=(await X.boundAuth.apiKey.list())?.find((H)=>H.id===Y.keyId);if(!G)throw Error("API key not found");let W=G.metadata?.organization?.id,Z=X.organization?.id;if(W!==Z)throw Error("Cannot delete API key from another organization");return await X.boundAuth.apiKey.delete(Y.keyId),{success:!0,keyId:Y.keyId}}})});var KY0;var gH6=m(()=>{J4();lB();KY0=X6({name:"API_KEY_LIST",description:"List all API keys for the current user in the current organization. Returns metadata only - key values are never shown after creation.",inputSchema:vH6,outputSchema:_H6,handler:async(Y,X)=>{$6(X),await X.access.check();let Q=await X.boundAuth.apiKey.list(),J=X.organization?.id;return{items:(Q??[]).filter((K)=>{return K.metadata?.organization?.id===J}).map((K)=>({id:K.id,name:K.name??"Unnamed Key",userId:K.userId,permissions:K.permissions??{},expiresAt:K.expiresAt?K.expiresAt instanceof Date?K.expiresAt.toISOString():K.expiresAt:null,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt}))}}})});var HY0;var mH6=m(()=>{J4();lB();HY0=X6({name:"API_KEY_UPDATE",description:"Update an existing API key's name, permissions, or metadata. Note: Key value cannot be changed or retrieved.",inputSchema:yH6,outputSchema:fH6,handler:async(Y,X)=>{if($6(X),await X.access.check(),!x8(X))throw Error("User ID required to update API key");let G=(await X.boundAuth.apiKey.list())?.find((F)=>F.id===Y.keyId);if(!G)throw Error(`API key not found: ${Y.keyId}`);let W=G.metadata?.organization?.id,Z=X.organization?.id;if(W!==Z)throw Error("Cannot update API key from another organization");let H=await X.boundAuth.apiKey.update({keyId:Y.keyId,name:Y.name,permissions:Y.permissions,metadata:{...Y.metadata,organization:X.organization}});if(!H)throw Error(`Failed to update API key: ${Y.keyId}`);return{item:{id:H.id,name:H.name??Y.name??"Unnamed Key",userId:H.userId,permissions:H.permissions??{},expiresAt:H.expiresAt?H.expiresAt instanceof Date?H.expiresAt.toISOString():H.expiresAt:null,createdAt:H.createdAt instanceof Date?H.createdAt.toISOString():H.createdAt}}}})});var lH6=m(()=>{xH6();uH6();gH6();mH6();lB()});var dH6,pH6,cH6,nH6,iH6,aH6;var NP=m(()=>{Y6();dH6=N.object({query:N.string().describe("Natural language search query (e.g., 'send email', 'create order')"),limit:N.number().default(10).describe("Maximum results to return (default: 10)")}),pH6=N.object({query:N.string(),results:N.array(N.object({name:N.string(),description:N.string().optional(),connection:N.string()})),totalAvailable:N.number()}),cH6=N.object({tools:N.array(N.string()).min(1).describe("Array of tool names to get detailed schemas for")}),nH6=N.object({tools:N.array(N.object({name:N.string(),description:N.string().optional(),connection:N.string(),inputSchema:N.unknown(),outputSchema:N.unknown().optional()})),notFound:N.array(N.string())}),iH6=N.object({code:N.string().min(1).describe("JavaScript code to execute. It runs as an async function body; you can use top-level `return` and `await`."),timeoutMs:N.number().default(3000).describe("Max execution time in milliseconds (default: 3000).")}),aH6=N.object({returnValue:N.unknown().optional(),error:N.string().optional(),consoleLogs:N.array(N.object({type:N.enum(["log","warn","error"]),content:N.string()}))})});class If{proxies=new Map;constructor(){}static async create(Y,X){let Q=new If,J=await Promise.allSettled(Y.map(async({connection:G,selectedTools:K,selectedResources:W,selectedPrompts:Z})=>{try{let H=await X.createMCPProxy(G);return{connection:G,proxy:H,selectedTools:K,selectedResources:W,selectedPrompts:Z}}catch(H){return console.error(`[aggregator] Failed to create proxy for connection ${G.id}:`,H),null}}));for(let G of J)if(G.status==="fulfilled"&&G.value)Q.proxies.set(G.value.connection.id,G.value);return Q}get(Y){return this.proxies.get(Y)}entries(){return this.proxies.entries()}forEach(Y){this.proxies.forEach((X,Q)=>Y(X,Q))}async mapAsync(Y){let X=[];for(let[Q,J]of this.proxies.entries())X.push(Y(J,Q));return await Promise.all(X)}async mapSettled(Y){return Promise.allSettled(Array.from(this.proxies.entries()).map(([X,Q])=>Y(Q,X)))}get size(){return this.proxies.size}}function rH6(Y){let X=[],Q=[],J=(H)=>{let F=Y.newFunction(H,(...V)=>{try{let q=V.map(($)=>Y.dump($));X.push({type:H??"log",content:q.map(String).join(" ")})}finally{V.forEach((q)=>q.dispose())}return Y.undefined});return Q.push(F),F},G=Y.newObject();Q.push(G);let K=J("log"),W=J("warn"),Z=J("error");return Y.setProp(G,"log",K),Y.setProp(G,"warn",W),Y.setProp(G,"error",Z),Y.setProp(Y.global,"console",G),{logs:X,[Symbol.dispose](){Q.forEach((H)=>H.dispose())}}}var VV,FY0,Cf,qV,LP;var Rf=m(()=>{VV={JS_EVAL_TYPE_GLOBAL:0,JS_EVAL_TYPE_MODULE:1,JS_EVAL_TYPE_DIRECT:2,JS_EVAL_TYPE_INDIRECT:3,JS_EVAL_TYPE_MASK:3,JS_EVAL_FLAG_STRICT:8,JS_EVAL_FLAG_STRIP:16,JS_EVAL_FLAG_COMPILE_ONLY:32,JS_EVAL_FLAG_BACKTRACE_BARRIER:64},FY0={BaseObjects:1,Date:2,Eval:4,StringNormalize:8,RegExp:16,RegExpCompiler:32,JSON:64,Proxy:128,MapSet:256,TypedArrays:512,Promise:1024,BigInt:2048,BigFloat:4096,BigDecimal:8192,OperatorOverloading:16384,BignumExt:32768},Cf={Pending:0,Fulfilled:1,Rejected:2},qV={JS_GPN_STRING_MASK:1,JS_GPN_SYMBOL_MASK:2,JS_GPN_PRIVATE_MASK:4,JS_GPN_ENUM_ONLY:16,JS_GPN_SET_ENUM:32,QTS_GPN_NUMBER_MASK:64,QTS_STANDARD_COMPLIANT_NUMBER:128},LP={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2}});function dB(...Y){UY0&&console.log("quickjs-emscripten:",...Y)}function*HF6(Y){return yield Y}function sc4(Y){return HF6(OY0(Y))}function oH6(Y,X){return(...Q)=>{let J=X.call(Y,DY0,...Q);return OY0(J)}}function tc4(Y,X){let Q=X.call(Y,DY0);return OY0(Q)}function OY0(Y){function X(Q){return Q.done?Q.value:Q.value instanceof Promise?Q.value.then((J)=>X(Y.next(J)),(J)=>X(Y.throw(J))):X(Y.next(Q.value))}return X(Y.next())}function VY0(Y,X){let Q;try{Y.dispose()}catch(J){Q=J}if(X&&Q)throw Object.assign(X,{message:`${X.message}
398
- Then, failed to dispose scope: ${Q.message}`,disposeError:Q}),X;if(X||Q)throw X||Q}function FF6(Y){let X=Y?Array.from(Y):[];function Q(){return X.forEach((G)=>G.alive?G.dispose():void 0)}function J(){return X.some((G)=>G.alive)}return Object.defineProperty(X,zY0,{configurable:!0,enumerable:!1,value:Q}),Object.defineProperty(X,"dispose",{configurable:!0,enumerable:!1,value:Q}),Object.defineProperty(X,"alive",{configurable:!0,enumerable:!1,get:J}),X}function Sf(Y){return!!(Y&&(typeof Y=="object"||typeof Y=="function")&&("alive"in Y)&&typeof Y.alive=="boolean"&&("dispose"in Y)&&typeof Y.dispose=="function")}function ec4(Y){if(!Y)return 0;let X=0;for(let[Q,J]of Object.entries(Y)){if(!(Q in FY0))throw new WF6(Q);J&&(X|=FY0[Q])}return X}function Yn4(Y){if(typeof Y=="number")return Y;if(Y===void 0)return 0;let{type:X,strict:Q,strip:J,compileOnly:G,backtraceBarrier:K}=Y,W=0;return X==="global"&&(W|=VV.JS_EVAL_TYPE_GLOBAL),X==="module"&&(W|=VV.JS_EVAL_TYPE_MODULE),Q&&(W|=VV.JS_EVAL_FLAG_STRICT),J&&(W|=VV.JS_EVAL_FLAG_STRIP),G&&(W|=VV.JS_EVAL_FLAG_COMPILE_ONLY),K&&(W|=VV.JS_EVAL_FLAG_BACKTRACE_BARRIER),W}function Xn4(Y){if(typeof Y=="number")return Y;if(Y===void 0)return 0;let{strings:X,symbols:Q,quickjsPrivate:J,onlyEnumerable:G,numbers:K,numbersAsStrings:W}=Y,Z=0;return X&&(Z|=qV.JS_GPN_STRING_MASK),Q&&(Z|=qV.JS_GPN_SYMBOL_MASK),J&&(Z|=qV.JS_GPN_PRIVATE_MASK),G&&(Z|=qV.JS_GPN_ENUM_ONLY),K&&(Z|=qV.QTS_GPN_NUMBER_MASK),W&&(Z|=qV.QTS_STANDARD_COMPLIANT_NUMBER),Z}function Qn4(...Y){let X=[];for(let Q of Y)Q!==void 0&&(X=X.concat(Q));return X}function wY0(Y,X){X.interruptHandler&&Y.setInterruptHandler(X.interruptHandler),X.maxStackSizeBytes!==void 0&&Y.setMaxStackSize(X.maxStackSizeBytes),X.memoryLimitBytes!==void 0&&Y.setMemoryLimit(X.memoryLimitBytes)}function PY0(Y,X){X.moduleLoader&&Y.setModuleLoader(X.moduleLoader),X.shouldInterrupt&&Y.setInterruptHandler(X.shouldInterrupt),X.memoryLimitBytes!==void 0&&Y.setMemoryLimit(X.memoryLimitBytes),X.maxStackSizeBytes!==void 0&&Y.setMaxStackSize(X.maxStackSizeBytes)}var rc4,oc4=(Y,X)=>{for(var Q in X)rc4(Y,Q,{get:X[Q],enumerable:!0})},UY0=!1,tH6,qY0,eH6,$Y0,YF6,XF6,QF6,JF6,GF6,WF6,ZF6,KF6,DY0,pW,zY0,sH6,lY,F3,BY0,p5,NY0,VF6,qF6,$V,$F6,zF6=class{constructor(Y){this.module=Y}toPointerArray(Y){let X=new Int32Array(Y.map((G)=>G.value)),Q=X.length*X.BYTES_PER_ELEMENT,J=this.module._malloc(Q);return new Uint8Array(this.module.HEAPU8.buffer,J,Q).set(new Uint8Array(X.buffer)),new lY(J,void 0,(G)=>this.module._free(G))}newTypedArray(Y,X){let Q=new Y(Array(X).fill(0)),J=Q.length*Q.BYTES_PER_ELEMENT,G=this.module._malloc(J),K=new Y(this.module.HEAPU8.buffer,G,X);return K.set(Q),new lY({typedArray:K,ptr:G},void 0,(W)=>this.module._free(W.ptr))}newMutablePointerArray(Y){return this.newTypedArray(Int32Array,Y)}newHeapCharPointer(Y){let X=this.module.lengthBytesUTF8(Y),Q=X+1,J=this.module._malloc(Q);return this.module.stringToUTF8(Y,J,Q),new lY({ptr:J,strlen:X},void 0,(G)=>this.module._free(G.ptr))}newHeapBufferPointer(Y){let X=Y.byteLength,Q=this.module._malloc(X);return this.module.HEAPU8.set(Y,Q),new lY({pointer:Q,numBytes:X},void 0,(J)=>this.module._free(J.pointer))}consumeHeapCharPointer(Y){let X=this.module.UTF8ToString(Y);return this.module._free(Y),X}},vo1,LY0,Jn4,Gn4,BF6,UF6,Wn4=class{constructor(Y){this.callFunction=Y.callFunction,this.shouldInterrupt=Y.shouldInterrupt,this.loadModuleSource=Y.loadModuleSource,this.normalizeModule=Y.normalizeModule}},MY0=class{constructor(Y){this.contextCallbacks=new Map,this.runtimeCallbacks=new Map,this.suspendedCount=0,this.cToHostCallbacks=new Wn4({callFunction:(X,Q,J,G,K,W)=>this.handleAsyncify(X,()=>{try{let Z=this.contextCallbacks.get(Q);if(!Z)throw Error(`QuickJSContext(ctx = ${Q}) not found for C function call "${W}"`);return Z.callFunction(Q,J,G,K,W)}catch(Z){return console.error("[C to host error: returning null]",Z),0}}),shouldInterrupt:(X,Q)=>this.handleAsyncify(X,()=>{try{let J=this.runtimeCallbacks.get(Q);if(!J)throw Error(`QuickJSRuntime(rt = ${Q}) not found for C interrupt`);return J.shouldInterrupt(Q)}catch(J){return console.error("[C to host interrupt: returning error]",J),1}}),loadModuleSource:(X,Q,J,G)=>this.handleAsyncify(X,()=>{try{let K=this.runtimeCallbacks.get(Q);if(!K)throw Error(`QuickJSRuntime(rt = ${Q}) not found for C module loader`);let W=K.loadModuleSource;if(!W)throw Error(`QuickJSRuntime(rt = ${Q}) does not support module loading`);return W(Q,J,G)}catch(K){return console.error("[C to host module loader error: returning null]",K),0}}),normalizeModule:(X,Q,J,G,K)=>this.handleAsyncify(X,()=>{try{let W=this.runtimeCallbacks.get(Q);if(!W)throw Error(`QuickJSRuntime(rt = ${Q}) not found for C module loader`);let Z=W.normalizeModule;if(!Z)throw Error(`QuickJSRuntime(rt = ${Q}) does not support module loading`);return Z(Q,J,G,K)}catch(W){return console.error("[C to host module loader error: returning null]",W),0}})}),this.module=Y,this.module.callbacks=this.cToHostCallbacks}setRuntimeCallbacks(Y,X){this.runtimeCallbacks.set(Y,X)}deleteRuntime(Y){this.runtimeCallbacks.delete(Y)}setContextCallbacks(Y,X){this.contextCallbacks.set(Y,X)}deleteContext(Y){this.contextCallbacks.delete(Y)}handleAsyncify(Y,X){if(Y)return Y.handleSleep((J)=>{try{let G=X();if(!(G instanceof Promise)){dB("asyncify.handleSleep: not suspending:",G),J(G);return}if(this.suspended)throw new XF6(`Already suspended at: ${this.suspended.stack}
398
+ Then, failed to dispose scope: ${Q.message}`,disposeError:Q}),X;if(X||Q)throw X||Q}function FF6(Y){let X=Y?Array.from(Y):[];function Q(){return X.forEach((G)=>G.alive?G.dispose():void 0)}function J(){return X.some((G)=>G.alive)}return Object.defineProperty(X,zY0,{configurable:!0,enumerable:!1,value:Q}),Object.defineProperty(X,"dispose",{configurable:!0,enumerable:!1,value:Q}),Object.defineProperty(X,"alive",{configurable:!0,enumerable:!1,get:J}),X}function Sf(Y){return!!(Y&&(typeof Y=="object"||typeof Y=="function")&&("alive"in Y)&&typeof Y.alive=="boolean"&&("dispose"in Y)&&typeof Y.dispose=="function")}function ec4(Y){if(!Y)return 0;let X=0;for(let[Q,J]of Object.entries(Y)){if(!(Q in FY0))throw new WF6(Q);J&&(X|=FY0[Q])}return X}function Yn4(Y){if(typeof Y=="number")return Y;if(Y===void 0)return 0;let{type:X,strict:Q,strip:J,compileOnly:G,backtraceBarrier:K}=Y,W=0;return X==="global"&&(W|=VV.JS_EVAL_TYPE_GLOBAL),X==="module"&&(W|=VV.JS_EVAL_TYPE_MODULE),Q&&(W|=VV.JS_EVAL_FLAG_STRICT),J&&(W|=VV.JS_EVAL_FLAG_STRIP),G&&(W|=VV.JS_EVAL_FLAG_COMPILE_ONLY),K&&(W|=VV.JS_EVAL_FLAG_BACKTRACE_BARRIER),W}function Xn4(Y){if(typeof Y=="number")return Y;if(Y===void 0)return 0;let{strings:X,symbols:Q,quickjsPrivate:J,onlyEnumerable:G,numbers:K,numbersAsStrings:W}=Y,Z=0;return X&&(Z|=qV.JS_GPN_STRING_MASK),Q&&(Z|=qV.JS_GPN_SYMBOL_MASK),J&&(Z|=qV.JS_GPN_PRIVATE_MASK),G&&(Z|=qV.JS_GPN_ENUM_ONLY),K&&(Z|=qV.QTS_GPN_NUMBER_MASK),W&&(Z|=qV.QTS_STANDARD_COMPLIANT_NUMBER),Z}function Qn4(...Y){let X=[];for(let Q of Y)Q!==void 0&&(X=X.concat(Q));return X}function wY0(Y,X){X.interruptHandler&&Y.setInterruptHandler(X.interruptHandler),X.maxStackSizeBytes!==void 0&&Y.setMaxStackSize(X.maxStackSizeBytes),X.memoryLimitBytes!==void 0&&Y.setMemoryLimit(X.memoryLimitBytes)}function PY0(Y,X){X.moduleLoader&&Y.setModuleLoader(X.moduleLoader),X.shouldInterrupt&&Y.setInterruptHandler(X.shouldInterrupt),X.memoryLimitBytes!==void 0&&Y.setMemoryLimit(X.memoryLimitBytes),X.maxStackSizeBytes!==void 0&&Y.setMaxStackSize(X.maxStackSizeBytes)}var rc4,oc4=(Y,X)=>{for(var Q in X)rc4(Y,Q,{get:X[Q],enumerable:!0})},UY0=!1,tH6,qY0,eH6,$Y0,YF6,XF6,QF6,JF6,GF6,WF6,ZF6,KF6,DY0,pW,zY0,sH6,lY,F3,BY0,p5,NY0,VF6,qF6,$V,$F6,zF6=class{constructor(Y){this.module=Y}toPointerArray(Y){let X=new Int32Array(Y.map((G)=>G.value)),Q=X.length*X.BYTES_PER_ELEMENT,J=this.module._malloc(Q);return new Uint8Array(this.module.HEAPU8.buffer,J,Q).set(new Uint8Array(X.buffer)),new lY(J,void 0,(G)=>this.module._free(G))}newTypedArray(Y,X){let Q=new Y(Array(X).fill(0)),J=Q.length*Q.BYTES_PER_ELEMENT,G=this.module._malloc(J),K=new Y(this.module.HEAPU8.buffer,G,X);return K.set(Q),new lY({typedArray:K,ptr:G},void 0,(W)=>this.module._free(W.ptr))}newMutablePointerArray(Y){return this.newTypedArray(Int32Array,Y)}newHeapCharPointer(Y){let X=this.module.lengthBytesUTF8(Y),Q=X+1,J=this.module._malloc(Q);return this.module.stringToUTF8(Y,J,Q),new lY({ptr:J,strlen:X},void 0,(G)=>this.module._free(G.ptr))}newHeapBufferPointer(Y){let X=Y.byteLength,Q=this.module._malloc(X);return this.module.HEAPU8.set(Y,Q),new lY({pointer:Q,numBytes:X},void 0,(J)=>this.module._free(J.pointer))}consumeHeapCharPointer(Y){let X=this.module.UTF8ToString(Y);return this.module._free(Y),X}},_o1,LY0,Jn4,Gn4,BF6,UF6,Wn4=class{constructor(Y){this.callFunction=Y.callFunction,this.shouldInterrupt=Y.shouldInterrupt,this.loadModuleSource=Y.loadModuleSource,this.normalizeModule=Y.normalizeModule}},MY0=class{constructor(Y){this.contextCallbacks=new Map,this.runtimeCallbacks=new Map,this.suspendedCount=0,this.cToHostCallbacks=new Wn4({callFunction:(X,Q,J,G,K,W)=>this.handleAsyncify(X,()=>{try{let Z=this.contextCallbacks.get(Q);if(!Z)throw Error(`QuickJSContext(ctx = ${Q}) not found for C function call "${W}"`);return Z.callFunction(Q,J,G,K,W)}catch(Z){return console.error("[C to host error: returning null]",Z),0}}),shouldInterrupt:(X,Q)=>this.handleAsyncify(X,()=>{try{let J=this.runtimeCallbacks.get(Q);if(!J)throw Error(`QuickJSRuntime(rt = ${Q}) not found for C interrupt`);return J.shouldInterrupt(Q)}catch(J){return console.error("[C to host interrupt: returning error]",J),1}}),loadModuleSource:(X,Q,J,G)=>this.handleAsyncify(X,()=>{try{let K=this.runtimeCallbacks.get(Q);if(!K)throw Error(`QuickJSRuntime(rt = ${Q}) not found for C module loader`);let W=K.loadModuleSource;if(!W)throw Error(`QuickJSRuntime(rt = ${Q}) does not support module loading`);return W(Q,J,G)}catch(K){return console.error("[C to host module loader error: returning null]",K),0}}),normalizeModule:(X,Q,J,G,K)=>this.handleAsyncify(X,()=>{try{let W=this.runtimeCallbacks.get(Q);if(!W)throw Error(`QuickJSRuntime(rt = ${Q}) not found for C module loader`);let Z=W.normalizeModule;if(!Z)throw Error(`QuickJSRuntime(rt = ${Q}) does not support module loading`);return Z(Q,J,G,K)}catch(W){return console.error("[C to host module loader error: returning null]",W),0}})}),this.module=Y,this.module.callbacks=this.cToHostCallbacks}setRuntimeCallbacks(Y,X){this.runtimeCallbacks.set(Y,X)}deleteRuntime(Y){this.runtimeCallbacks.delete(Y)}setContextCallbacks(Y,X){this.contextCallbacks.set(Y,X)}deleteContext(Y){this.contextCallbacks.delete(Y)}handleAsyncify(Y,X){if(Y)return Y.handleSleep((J)=>{try{let G=X();if(!(G instanceof Promise)){dB("asyncify.handleSleep: not suspending:",G),J(G);return}if(this.suspended)throw new XF6(`Already suspended at: ${this.suspended.stack}
399
399
  Attempted to suspend at:`);this.suspended=new QF6(`(${this.suspendedCount++})`),dB("asyncify.handleSleep: suspending:",this.suspended),G.then((K)=>{this.suspended=void 0,dB("asyncify.handleSleep: resolved:",K),J(K)},(K)=>{dB("asyncify.handleSleep: rejected:",K),console.error("QuickJS: cannot handle error in suspended function",K),this.suspended=void 0})}catch(G){throw dB("asyncify.handleSleep: error:",G),this.suspended=void 0,G}});let Q=X();if(Q instanceof Promise)throw Error("Promise return value not supported in non-asyncify context.");return Q}},AY0=class{constructor(Y,X){this.module=Y,this.ffi=X,this.callbacks=new MY0(Y)}newRuntime(Y={}){let X=new lY(this.ffi.QTS_NewRuntime(),void 0,(J)=>{this.callbacks.deleteRuntime(J),this.ffi.QTS_FreeRuntime(J)}),Q=new UF6({module:this.module,callbacks:this.callbacks,ffi:this.ffi,rt:X});return wY0(Q,Y),Y.moduleLoader&&Q.setModuleLoader(Y.moduleLoader),Q}newContext(Y={}){let X=this.newRuntime(),Q=X.newContext({...Y,ownedLifetimes:Qn4(X,Y.ownedLifetimes)});return X.context=Q,Q}evalCode(Y,X={}){return p5.withScope((Q)=>{let J=Q.manage(this.newContext());PY0(J.runtime,X);let G=J.evalCode(Y,"eval.js");if(X.memoryLimitBytes!==void 0&&J.runtime.setMemoryLimit(-1),G.error)throw J.dump(Q.manage(G.error));return J.dump(Q.manage(G.value))})}getWasmMemory(){let Y=this.module.quickjsEmscriptenInit?.(()=>{})?.getWasmMemory?.();if(!Y)throw Error("Variant does not support getting WebAssembly.Memory");return Y}getFFI(){return this.ffi}};var TY0=m(()=>{Rf();Rf();rc4=Object.defineProperty;tH6={};oc4(tH6,{QuickJSAsyncifyError:()=>XF6,QuickJSAsyncifySuspended:()=>QF6,QuickJSEmptyGetOwnPropertyNames:()=>KF6,QuickJSEmscriptenModuleError:()=>GF6,QuickJSMemoryLeakDetected:()=>JF6,QuickJSNotImplemented:()=>YF6,QuickJSPromisePending:()=>ZF6,QuickJSUnknownIntrinsic:()=>WF6,QuickJSUnwrapError:()=>qY0,QuickJSUseAfterFree:()=>$Y0,QuickJSWrongOwner:()=>eH6});qY0=class extends Error{constructor(Y,X){let Q=typeof Y=="object"&&Y&&"message"in Y?String(Y.message):String(Y);super(Q);this.cause=Y,this.context=X,this.name="QuickJSUnwrapError"}},eH6=class extends Error{constructor(){super(...arguments);this.name="QuickJSWrongOwner"}},$Y0=class extends Error{constructor(){super(...arguments);this.name="QuickJSUseAfterFree"}},YF6=class extends Error{constructor(){super(...arguments);this.name="QuickJSNotImplemented"}},XF6=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifyError"}},QF6=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifySuspended"}},JF6=class extends Error{constructor(){super(...arguments);this.name="QuickJSMemoryLeakDetected"}},GF6=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmscriptenModuleError"}},WF6=class extends TypeError{constructor(){super(...arguments);this.name="QuickJSUnknownIntrinsic"}},ZF6=class extends Error{constructor(){super(...arguments);this.name="QuickJSPromisePending"}},KF6=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmptyGetOwnPropertyNames"}};DY0=HF6;DY0.of=sc4;pW=class{[Symbol.dispose](){return this.dispose()}},zY0=Symbol.dispose??Symbol.for("Symbol.dispose"),sH6=pW.prototype;sH6[zY0]||(sH6[zY0]=function(){return this.dispose()});lY=class Y extends pW{constructor(X,Q,J,G){super();this._value=X,this.copier=Q,this.disposer=J,this._owner=G,this._alive=!0,this._constructorStack=UY0?Error("Lifetime constructed").stack:void 0}get alive(){return this._alive}get value(){return this.assertAlive(),this._value}get owner(){return this._owner}get dupable(){return!!this.copier}dup(){if(this.assertAlive(),!this.copier)throw Error("Non-dupable lifetime");return new Y(this.copier(this._value),this.copier,this.disposer,this._owner)}consume(X){this.assertAlive();let Q=X(this);return this.dispose(),Q}map(X){return this.assertAlive(),X(this)}tap(X){return X(this),this}dispose(){this.assertAlive(),this.disposer&&this.disposer(this._value),this._alive=!1}assertAlive(){if(!this.alive)throw this._constructorStack?new $Y0(`Lifetime not alive
400
400
  ${this._constructorStack}
401
- Lifetime used`):new $Y0("Lifetime not alive")}},F3=class extends lY{constructor(Y,X){super(Y,void 0,void 0,X)}get dupable(){return!0}dup(){return this}dispose(){}},BY0=class extends lY{constructor(Y,X,Q,J){super(Y,X,Q,J)}dispose(){this._alive=!1}};p5=class Y extends pW{constructor(){super(...arguments);this._disposables=new lY(new Set),this.manage=(X)=>(this._disposables.value.add(X),X)}static withScope(X){let Q=new Y,J;try{return X(Q)}catch(G){throw J=G,G}finally{VY0(Q,J)}}static withScopeMaybeAsync(X,Q){return tc4(void 0,function*(J){let G=new Y,K;try{return yield*J.of(Q.call(X,J,G))}catch(W){throw K=W,W}finally{VY0(G,K)}})}static async withScopeAsync(X){let Q=new Y,J;try{return await X(Q)}catch(G){throw J=G,G}finally{VY0(Q,J)}}get alive(){return this._disposables.alive}dispose(){let X=Array.from(this._disposables.value.values()).reverse();for(let Q of X)Q.alive&&Q.dispose();this._disposables.dispose()}};NY0=class Y extends pW{static success(X){return new VF6(X)}static fail(X,Q){return new qF6(X,Q)}static is(X){return X instanceof Y}},VF6=class extends NY0{constructor(Y){super();this.value=Y}get alive(){return Sf(this.value)?this.value.alive:!0}dispose(){Sf(this.value)&&this.value.dispose()}unwrap(){return this.value}unwrapOr(Y){return this.value}},qF6=class extends NY0{constructor(Y,X){super();this.error=Y,this.onUnwrap=X}get alive(){return Sf(this.error)?this.error.alive:!0}dispose(){Sf(this.error)&&this.error.dispose()}unwrap(){throw this.onUnwrap(this),this.error}unwrapOr(Y){return Y}},$V=NY0,$F6=class extends pW{constructor(Y){super();this.resolve=(X)=>{this.resolveHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.resolveHandle,this.context.undefined,X||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled())},this.reject=(X)=>{this.rejectHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.rejectHandle,this.context.undefined,X||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled())},this.dispose=()=>{this.handle.alive&&this.handle.dispose(),this.disposeResolvers()},this.context=Y.context,this.owner=Y.context.runtime,this.handle=Y.promiseHandle,this.settled=new Promise((X)=>{this.onSettled=X}),this.resolveHandle=Y.resolveHandle,this.rejectHandle=Y.rejectHandle}get alive(){return this.handle.alive||this.resolveHandle.alive||this.rejectHandle.alive}disposeResolvers(){this.resolveHandle.alive&&this.resolveHandle.dispose(),this.rejectHandle.alive&&this.rejectHandle.dispose()}},vo1=Symbol("Unstable"),LY0=Object.freeze({BaseObjects:!0,Date:!0,Eval:!0,StringNormalize:!0,RegExp:!0,JSON:!0,Proxy:!0,MapSet:!0,TypedArrays:!0,Promise:!0});Jn4=class extends pW{constructor(Y,X){super();this.handle=Y,this.context=X,this._isDone=!1,this.owner=X.runtime}[Symbol.iterator](){return this}next(Y){if(!this.alive||this._isDone)return{done:!0,value:void 0};let X=this._next??(this._next=this.context.getProp(this.handle,"next"));return this.callIteratorMethod(X,Y)}return(Y){if(!this.alive)return{done:!0,value:void 0};let X=this.context.getProp(this.handle,"return");if(X===this.context.undefined&&Y===void 0)return this.dispose(),{done:!0,value:void 0};let Q=this.callIteratorMethod(X,Y);return X.dispose(),this.dispose(),Q}throw(Y){if(!this.alive)return{done:!0,value:void 0};let X=Y instanceof lY?Y:this.context.newError(Y),Q=this.context.getProp(this.handle,"throw"),J=this.callIteratorMethod(Q,Y);return X.alive&&X.dispose(),Q.dispose(),this.dispose(),J}get alive(){return this.handle.alive}dispose(){this._isDone=!0,this.handle.dispose(),this._next?.dispose()}callIteratorMethod(Y,X){let Q=X?this.context.callFunction(Y,this.handle,X):this.context.callFunction(Y,this.handle);if(Q.error)return this.dispose(),{value:Q};let J=this.context.getProp(Q.value,"done").consume((K)=>this.context.dump(K));if(J)return Q.value.dispose(),this.dispose(),{done:J,value:void 0};let G=this.context.getProp(Q.value,"value");return Q.value.dispose(),{value:$V.success(G),done:J}}},Gn4=class extends zF6{constructor(Y){super(Y.module);this.scope=new p5,this.copyJSValue=(X)=>this.ffi.QTS_DupValuePointer(this.ctx.value,X),this.freeJSValue=(X)=>{this.ffi.QTS_FreeValuePointer(this.ctx.value,X)},Y.ownedLifetimes?.forEach((X)=>this.scope.manage(X)),this.owner=Y.owner,this.module=Y.module,this.ffi=Y.ffi,this.rt=Y.rt,this.ctx=this.scope.manage(Y.ctx)}get alive(){return this.scope.alive}dispose(){return this.scope.dispose()}[Symbol.dispose](){return this.dispose()}manage(Y){return this.scope.manage(Y)}consumeJSCharPointer(Y){let X=this.module.UTF8ToString(Y);return this.ffi.QTS_FreeCString(this.ctx.value,Y),X}heapValueHandle(Y){return new lY(Y,this.copyJSValue,this.freeJSValue,this.owner)}staticHeapValueHandle(Y){return this.manage(this.heapValueHandle(Y)),new F3(Y,this.owner)}},BF6=class extends pW{constructor(Y){super();this._undefined=void 0,this._null=void 0,this._false=void 0,this._true=void 0,this._global=void 0,this._BigInt=void 0,this._Symbol=void 0,this._SymbolIterator=void 0,this._SymbolAsyncIterator=void 0,this.fnNextId=-32768,this.fnMaps=new Map,this.cToHostCallbacks={callFunction:(X,Q,J,G,K)=>{if(X!==this.ctx.value)throw Error("QuickJSContext instance received C -> JS call with mismatched ctx");let W=this.getFunction(K);if(!W)throw Error(`QuickJSContext had no callback with id ${K}`);return p5.withScopeMaybeAsync(this,function*(Z,H){let F=H.manage(new BY0(Q,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime)),V=Array(J);for(let q=0;q<J;q++){let $=this.ffi.QTS_ArgvGetJSValueConstPointer(G,q);V[q]=H.manage(new BY0($,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime))}try{let q=yield*Z(W.apply(F,V));if(q){if("error"in q&&q.error)throw this.runtime.debugLog("throw error",q.error),q.error;let $=H.manage(q instanceof lY?q:q.value);return this.ffi.QTS_DupValuePointer(this.ctx.value,$.value)}return 0}catch(q){return this.errorToHandle(q).consume(($)=>this.ffi.QTS_Throw(this.ctx.value,$.value))}})}},this.runtime=Y.runtime,this.module=Y.module,this.ffi=Y.ffi,this.rt=Y.rt,this.ctx=Y.ctx,this.memory=new Gn4({...Y,owner:this.runtime}),Y.callbacks.setContextCallbacks(this.ctx.value,this.cToHostCallbacks),this.dump=this.dump.bind(this),this.getString=this.getString.bind(this),this.getNumber=this.getNumber.bind(this),this.resolvePromise=this.resolvePromise.bind(this),this.uint32Out=this.memory.manage(this.memory.newTypedArray(Uint32Array,1))}get alive(){return this.memory.alive}dispose(){this.memory.dispose()}get undefined(){if(this._undefined)return this._undefined;let Y=this.ffi.QTS_GetUndefined();return this._undefined=new F3(Y)}get null(){if(this._null)return this._null;let Y=this.ffi.QTS_GetNull();return this._null=new F3(Y)}get true(){if(this._true)return this._true;let Y=this.ffi.QTS_GetTrue();return this._true=new F3(Y)}get false(){if(this._false)return this._false;let Y=this.ffi.QTS_GetFalse();return this._false=new F3(Y)}get global(){if(this._global)return this._global;let Y=this.ffi.QTS_GetGlobalObject(this.ctx.value);return this._global=this.memory.staticHeapValueHandle(Y),this._global}newNumber(Y){return this.memory.heapValueHandle(this.ffi.QTS_NewFloat64(this.ctx.value,Y))}newString(Y){let X=this.memory.newHeapCharPointer(Y).consume((Q)=>this.ffi.QTS_NewString(this.ctx.value,Q.value.ptr));return this.memory.heapValueHandle(X)}newUniqueSymbol(Y){let X=(typeof Y=="symbol"?Y.description:Y)??"",Q=this.memory.newHeapCharPointer(X).consume((J)=>this.ffi.QTS_NewSymbol(this.ctx.value,J.value.ptr,0));return this.memory.heapValueHandle(Q)}newSymbolFor(Y){let X=(typeof Y=="symbol"?Y.description:Y)??"",Q=this.memory.newHeapCharPointer(X).consume((J)=>this.ffi.QTS_NewSymbol(this.ctx.value,J.value.ptr,1));return this.memory.heapValueHandle(Q)}getWellKnownSymbol(Y){return this._Symbol??(this._Symbol=this.memory.manage(this.getProp(this.global,"Symbol"))),this.getProp(this._Symbol,Y)}newBigInt(Y){if(!this._BigInt){let J=this.getProp(this.global,"BigInt");this.memory.manage(J),this._BigInt=new F3(J.value,this.runtime)}let X=this._BigInt,Q=String(Y);return this.newString(Q).consume((J)=>this.unwrapResult(this.callFunction(X,this.undefined,J)))}newObject(Y){Y&&this.runtime.assertOwned(Y);let X=Y?this.ffi.QTS_NewObjectProto(this.ctx.value,Y.value):this.ffi.QTS_NewObject(this.ctx.value);return this.memory.heapValueHandle(X)}newArray(){let Y=this.ffi.QTS_NewArray(this.ctx.value);return this.memory.heapValueHandle(Y)}newArrayBuffer(Y){let X=new Uint8Array(Y),Q=this.memory.newHeapBufferPointer(X),J=this.ffi.QTS_NewArrayBuffer(this.ctx.value,Q.value.pointer,X.length);return this.memory.heapValueHandle(J)}newPromise(Y){let X=p5.withScope((Q)=>{let J=Q.manage(this.memory.newMutablePointerArray(2)),G=this.ffi.QTS_NewPromiseCapability(this.ctx.value,J.value.ptr),K=this.memory.heapValueHandle(G),[W,Z]=Array.from(J.value.typedArray).map((H)=>this.memory.heapValueHandle(H));return new $F6({context:this,promiseHandle:K,resolveHandle:W,rejectHandle:Z})});return Y&&typeof Y=="function"&&(Y=new Promise(Y)),Y&&Promise.resolve(Y).then(X.resolve,(Q)=>Q instanceof lY?X.reject(Q):this.newError(Q).consume(X.reject)),X}newFunction(Y,X){let Q=++this.fnNextId;return this.setFunction(Q,X),this.memory.heapValueHandle(this.ffi.QTS_NewFunction(this.ctx.value,Q,Y))}newError(Y){let X=this.memory.heapValueHandle(this.ffi.QTS_NewError(this.ctx.value));return Y&&typeof Y=="object"?(Y.name!==void 0&&this.newString(Y.name).consume((Q)=>this.setProp(X,"name",Q)),Y.message!==void 0&&this.newString(Y.message).consume((Q)=>this.setProp(X,"message",Q))):typeof Y=="string"?this.newString(Y).consume((Q)=>this.setProp(X,"message",Q)):Y!==void 0&&this.newString(String(Y)).consume((Q)=>this.setProp(X,"message",Q)),X}typeof(Y){return this.runtime.assertOwned(Y),this.memory.consumeHeapCharPointer(this.ffi.QTS_Typeof(this.ctx.value,Y.value))}getNumber(Y){return this.runtime.assertOwned(Y),this.ffi.QTS_GetFloat64(this.ctx.value,Y.value)}getString(Y){return this.runtime.assertOwned(Y),this.memory.consumeJSCharPointer(this.ffi.QTS_GetString(this.ctx.value,Y.value))}getSymbol(Y){this.runtime.assertOwned(Y);let X=this.memory.consumeJSCharPointer(this.ffi.QTS_GetSymbolDescriptionOrKey(this.ctx.value,Y.value));return this.ffi.QTS_IsGlobalSymbol(this.ctx.value,Y.value)?Symbol.for(X):Symbol(X)}getBigInt(Y){this.runtime.assertOwned(Y);let X=this.getString(Y);return BigInt(X)}getArrayBuffer(Y){this.runtime.assertOwned(Y);let X=this.ffi.QTS_GetArrayBufferLength(this.ctx.value,Y.value),Q=this.ffi.QTS_GetArrayBuffer(this.ctx.value,Y.value);if(!Q)throw Error("Couldn't allocate memory to get ArrayBuffer");return new lY(this.module.HEAPU8.subarray(Q,Q+X),void 0,()=>this.module._free(Q))}getPromiseState(Y){this.runtime.assertOwned(Y);let X=this.ffi.QTS_PromiseState(this.ctx.value,Y.value);if(X<0)return{type:"fulfilled",value:Y,notAPromise:!0};if(X===Cf.Pending)return{type:"pending",get error(){return new ZF6("Cannot unwrap a pending promise")}};let Q=this.ffi.QTS_PromiseResult(this.ctx.value,Y.value),J=this.memory.heapValueHandle(Q);if(X===Cf.Fulfilled)return{type:"fulfilled",value:J};if(X===Cf.Rejected)return{type:"rejected",error:J};throw J.dispose(),Error(`Unknown JSPromiseStateEnum: ${X}`)}resolvePromise(Y){this.runtime.assertOwned(Y);let X=p5.withScope((Q)=>{let J=Q.manage(this.getProp(this.global,"Promise")),G=Q.manage(this.getProp(J,"resolve"));return this.callFunction(G,J,Y)});return X.error?Promise.resolve(X):new Promise((Q)=>{p5.withScope((J)=>{let G=J.manage(this.newFunction("resolve",(H)=>{Q(this.success(H&&H.dup()))})),K=J.manage(this.newFunction("reject",(H)=>{Q(this.fail(H&&H.dup()))})),W=J.manage(X.value),Z=J.manage(this.getProp(W,"then"));this.callFunction(Z,W,G,K).unwrap().dispose()})})}isEqual(Y,X,Q=LP.IsStrictlyEqual){if(Y===X)return!0;this.runtime.assertOwned(Y),this.runtime.assertOwned(X);let J=this.ffi.QTS_IsEqual(this.ctx.value,Y.value,X.value,Q);if(J===-1)throw new YF6("WASM variant does not expose equality");return!!J}eq(Y,X){return this.isEqual(Y,X,LP.IsStrictlyEqual)}sameValue(Y,X){return this.isEqual(Y,X,LP.IsSameValue)}sameValueZero(Y,X){return this.isEqual(Y,X,LP.IsSameValueZero)}getProp(Y,X){this.runtime.assertOwned(Y);let Q;return typeof X=="number"&&X>=0?Q=this.ffi.QTS_GetPropNumber(this.ctx.value,Y.value,X):Q=this.borrowPropertyKey(X).consume((J)=>this.ffi.QTS_GetProp(this.ctx.value,Y.value,J.value)),this.memory.heapValueHandle(Q)}getLength(Y){if(this.runtime.assertOwned(Y),!(this.ffi.QTS_GetLength(this.ctx.value,this.uint32Out.value.ptr,Y.value)<0))return this.uint32Out.value.typedArray[0]}getOwnPropertyNames(Y,X={strings:!0,numbersAsStrings:!0}){this.runtime.assertOwned(Y),Y.value;let Q=Xn4(X);if(Q===0)throw new KF6("No options set, will return an empty array");return p5.withScope((J)=>{let G=J.manage(this.memory.newMutablePointerArray(1)),K=this.ffi.QTS_GetOwnPropertyNames(this.ctx.value,G.value.ptr,this.uint32Out.value.ptr,Y.value,Q);if(K)return this.fail(this.memory.heapValueHandle(K));let W=this.uint32Out.value.typedArray[0],Z=G.value.typedArray[0],H=new Uint32Array(this.module.HEAP8.buffer,Z,W),F=Array.from(H).map((V)=>this.memory.heapValueHandle(V));return this.ffi.QTS_FreeVoidPointer(this.ctx.value,Z),this.success(FF6(F))})}getIterator(Y){let X=this._SymbolIterator??(this._SymbolIterator=this.memory.manage(this.getWellKnownSymbol("iterator")));return p5.withScope((Q)=>{let J=Q.manage(this.getProp(Y,X)),G=this.callFunction(J,Y);return G.error?G:this.success(new Jn4(G.value,this))})}setProp(Y,X,Q){this.runtime.assertOwned(Y),this.borrowPropertyKey(X).consume((J)=>this.ffi.QTS_SetProp(this.ctx.value,Y.value,J.value,Q.value))}defineProp(Y,X,Q){this.runtime.assertOwned(Y),p5.withScope((J)=>{let G=J.manage(this.borrowPropertyKey(X)),K=Q.value||this.undefined,W=!!Q.configurable,Z=!!Q.enumerable,H=!!Q.value,F=Q.get?J.manage(this.newFunction(Q.get.name,Q.get)):this.undefined,V=Q.set?J.manage(this.newFunction(Q.set.name,Q.set)):this.undefined;this.ffi.QTS_DefineProp(this.ctx.value,Y.value,G.value,K.value,F.value,V.value,W,Z,H)})}callFunction(Y,X,...Q){this.runtime.assertOwned(Y);let J,G=Q[0];G===void 0||Array.isArray(G)?J=G??[]:J=Q;let K=this.memory.toPointerArray(J).consume((Z)=>this.ffi.QTS_Call(this.ctx.value,Y.value,X.value,J.length,Z.value)),W=this.ffi.QTS_ResolveException(this.ctx.value,K);return W?(this.ffi.QTS_FreeValuePointer(this.ctx.value,K),this.fail(this.memory.heapValueHandle(W))):this.success(this.memory.heapValueHandle(K))}callMethod(Y,X,Q=[]){return this.getProp(Y,X).consume((J)=>this.callFunction(J,Y,Q))}evalCode(Y,X="eval.js",Q){let J=Q===void 0?1:0,G=Yn4(Q),K=this.memory.newHeapCharPointer(Y).consume((Z)=>this.ffi.QTS_Eval(this.ctx.value,Z.value.ptr,Z.value.strlen,X,J,G)),W=this.ffi.QTS_ResolveException(this.ctx.value,K);return W?(this.ffi.QTS_FreeValuePointer(this.ctx.value,K),this.fail(this.memory.heapValueHandle(W))):this.success(this.memory.heapValueHandle(K))}throw(Y){return this.errorToHandle(Y).consume((X)=>this.ffi.QTS_Throw(this.ctx.value,X.value))}borrowPropertyKey(Y){return typeof Y=="number"?this.newNumber(Y):typeof Y=="string"?this.newString(Y):new F3(Y.value,this.runtime)}getMemory(Y){if(Y===this.rt.value)return this.memory;throw Error("Private API. Cannot get memory from a different runtime")}dump(Y){this.runtime.assertOwned(Y);let X=this.typeof(Y);if(X==="string")return this.getString(Y);if(X==="number")return this.getNumber(Y);if(X==="bigint")return this.getBigInt(Y);if(X==="undefined")return;if(X==="symbol")return this.getSymbol(Y);let Q=this.getPromiseState(Y);if(Q.type==="fulfilled"&&!Q.notAPromise)return Y.dispose(),{type:Q.type,value:Q.value.consume(this.dump)};if(Q.type==="pending")return Y.dispose(),{type:Q.type};if(Q.type==="rejected")return Y.dispose(),{type:Q.type,error:Q.error.consume(this.dump)};let J=this.memory.consumeJSCharPointer(this.ffi.QTS_Dump(this.ctx.value,Y.value));try{return JSON.parse(J)}catch{return J}}unwrapResult(Y){if(Y.error){let X="context"in Y.error?Y.error.context:this,Q=Y.error.consume((J)=>this.dump(J));if(Q&&typeof Q=="object"&&typeof Q.message=="string"){let{message:J,name:G,stack:K,...W}=Q,Z=new qY0(Q,X);typeof G=="string"&&(Z.name=Q.name),Z.message=J;let H=Z.stack;throw typeof K=="string"&&(Z.stack=`${G}: ${J}
401
+ Lifetime used`):new $Y0("Lifetime not alive")}},F3=class extends lY{constructor(Y,X){super(Y,void 0,void 0,X)}get dupable(){return!0}dup(){return this}dispose(){}},BY0=class extends lY{constructor(Y,X,Q,J){super(Y,X,Q,J)}dispose(){this._alive=!1}};p5=class Y extends pW{constructor(){super(...arguments);this._disposables=new lY(new Set),this.manage=(X)=>(this._disposables.value.add(X),X)}static withScope(X){let Q=new Y,J;try{return X(Q)}catch(G){throw J=G,G}finally{VY0(Q,J)}}static withScopeMaybeAsync(X,Q){return tc4(void 0,function*(J){let G=new Y,K;try{return yield*J.of(Q.call(X,J,G))}catch(W){throw K=W,W}finally{VY0(G,K)}})}static async withScopeAsync(X){let Q=new Y,J;try{return await X(Q)}catch(G){throw J=G,G}finally{VY0(Q,J)}}get alive(){return this._disposables.alive}dispose(){let X=Array.from(this._disposables.value.values()).reverse();for(let Q of X)Q.alive&&Q.dispose();this._disposables.dispose()}};NY0=class Y extends pW{static success(X){return new VF6(X)}static fail(X,Q){return new qF6(X,Q)}static is(X){return X instanceof Y}},VF6=class extends NY0{constructor(Y){super();this.value=Y}get alive(){return Sf(this.value)?this.value.alive:!0}dispose(){Sf(this.value)&&this.value.dispose()}unwrap(){return this.value}unwrapOr(Y){return this.value}},qF6=class extends NY0{constructor(Y,X){super();this.error=Y,this.onUnwrap=X}get alive(){return Sf(this.error)?this.error.alive:!0}dispose(){Sf(this.error)&&this.error.dispose()}unwrap(){throw this.onUnwrap(this),this.error}unwrapOr(Y){return Y}},$V=NY0,$F6=class extends pW{constructor(Y){super();this.resolve=(X)=>{this.resolveHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.resolveHandle,this.context.undefined,X||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled())},this.reject=(X)=>{this.rejectHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.rejectHandle,this.context.undefined,X||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled())},this.dispose=()=>{this.handle.alive&&this.handle.dispose(),this.disposeResolvers()},this.context=Y.context,this.owner=Y.context.runtime,this.handle=Y.promiseHandle,this.settled=new Promise((X)=>{this.onSettled=X}),this.resolveHandle=Y.resolveHandle,this.rejectHandle=Y.rejectHandle}get alive(){return this.handle.alive||this.resolveHandle.alive||this.rejectHandle.alive}disposeResolvers(){this.resolveHandle.alive&&this.resolveHandle.dispose(),this.rejectHandle.alive&&this.rejectHandle.dispose()}},_o1=Symbol("Unstable"),LY0=Object.freeze({BaseObjects:!0,Date:!0,Eval:!0,StringNormalize:!0,RegExp:!0,JSON:!0,Proxy:!0,MapSet:!0,TypedArrays:!0,Promise:!0});Jn4=class extends pW{constructor(Y,X){super();this.handle=Y,this.context=X,this._isDone=!1,this.owner=X.runtime}[Symbol.iterator](){return this}next(Y){if(!this.alive||this._isDone)return{done:!0,value:void 0};let X=this._next??(this._next=this.context.getProp(this.handle,"next"));return this.callIteratorMethod(X,Y)}return(Y){if(!this.alive)return{done:!0,value:void 0};let X=this.context.getProp(this.handle,"return");if(X===this.context.undefined&&Y===void 0)return this.dispose(),{done:!0,value:void 0};let Q=this.callIteratorMethod(X,Y);return X.dispose(),this.dispose(),Q}throw(Y){if(!this.alive)return{done:!0,value:void 0};let X=Y instanceof lY?Y:this.context.newError(Y),Q=this.context.getProp(this.handle,"throw"),J=this.callIteratorMethod(Q,Y);return X.alive&&X.dispose(),Q.dispose(),this.dispose(),J}get alive(){return this.handle.alive}dispose(){this._isDone=!0,this.handle.dispose(),this._next?.dispose()}callIteratorMethod(Y,X){let Q=X?this.context.callFunction(Y,this.handle,X):this.context.callFunction(Y,this.handle);if(Q.error)return this.dispose(),{value:Q};let J=this.context.getProp(Q.value,"done").consume((K)=>this.context.dump(K));if(J)return Q.value.dispose(),this.dispose(),{done:J,value:void 0};let G=this.context.getProp(Q.value,"value");return Q.value.dispose(),{value:$V.success(G),done:J}}},Gn4=class extends zF6{constructor(Y){super(Y.module);this.scope=new p5,this.copyJSValue=(X)=>this.ffi.QTS_DupValuePointer(this.ctx.value,X),this.freeJSValue=(X)=>{this.ffi.QTS_FreeValuePointer(this.ctx.value,X)},Y.ownedLifetimes?.forEach((X)=>this.scope.manage(X)),this.owner=Y.owner,this.module=Y.module,this.ffi=Y.ffi,this.rt=Y.rt,this.ctx=this.scope.manage(Y.ctx)}get alive(){return this.scope.alive}dispose(){return this.scope.dispose()}[Symbol.dispose](){return this.dispose()}manage(Y){return this.scope.manage(Y)}consumeJSCharPointer(Y){let X=this.module.UTF8ToString(Y);return this.ffi.QTS_FreeCString(this.ctx.value,Y),X}heapValueHandle(Y){return new lY(Y,this.copyJSValue,this.freeJSValue,this.owner)}staticHeapValueHandle(Y){return this.manage(this.heapValueHandle(Y)),new F3(Y,this.owner)}},BF6=class extends pW{constructor(Y){super();this._undefined=void 0,this._null=void 0,this._false=void 0,this._true=void 0,this._global=void 0,this._BigInt=void 0,this._Symbol=void 0,this._SymbolIterator=void 0,this._SymbolAsyncIterator=void 0,this.fnNextId=-32768,this.fnMaps=new Map,this.cToHostCallbacks={callFunction:(X,Q,J,G,K)=>{if(X!==this.ctx.value)throw Error("QuickJSContext instance received C -> JS call with mismatched ctx");let W=this.getFunction(K);if(!W)throw Error(`QuickJSContext had no callback with id ${K}`);return p5.withScopeMaybeAsync(this,function*(Z,H){let F=H.manage(new BY0(Q,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime)),V=Array(J);for(let q=0;q<J;q++){let $=this.ffi.QTS_ArgvGetJSValueConstPointer(G,q);V[q]=H.manage(new BY0($,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime))}try{let q=yield*Z(W.apply(F,V));if(q){if("error"in q&&q.error)throw this.runtime.debugLog("throw error",q.error),q.error;let $=H.manage(q instanceof lY?q:q.value);return this.ffi.QTS_DupValuePointer(this.ctx.value,$.value)}return 0}catch(q){return this.errorToHandle(q).consume(($)=>this.ffi.QTS_Throw(this.ctx.value,$.value))}})}},this.runtime=Y.runtime,this.module=Y.module,this.ffi=Y.ffi,this.rt=Y.rt,this.ctx=Y.ctx,this.memory=new Gn4({...Y,owner:this.runtime}),Y.callbacks.setContextCallbacks(this.ctx.value,this.cToHostCallbacks),this.dump=this.dump.bind(this),this.getString=this.getString.bind(this),this.getNumber=this.getNumber.bind(this),this.resolvePromise=this.resolvePromise.bind(this),this.uint32Out=this.memory.manage(this.memory.newTypedArray(Uint32Array,1))}get alive(){return this.memory.alive}dispose(){this.memory.dispose()}get undefined(){if(this._undefined)return this._undefined;let Y=this.ffi.QTS_GetUndefined();return this._undefined=new F3(Y)}get null(){if(this._null)return this._null;let Y=this.ffi.QTS_GetNull();return this._null=new F3(Y)}get true(){if(this._true)return this._true;let Y=this.ffi.QTS_GetTrue();return this._true=new F3(Y)}get false(){if(this._false)return this._false;let Y=this.ffi.QTS_GetFalse();return this._false=new F3(Y)}get global(){if(this._global)return this._global;let Y=this.ffi.QTS_GetGlobalObject(this.ctx.value);return this._global=this.memory.staticHeapValueHandle(Y),this._global}newNumber(Y){return this.memory.heapValueHandle(this.ffi.QTS_NewFloat64(this.ctx.value,Y))}newString(Y){let X=this.memory.newHeapCharPointer(Y).consume((Q)=>this.ffi.QTS_NewString(this.ctx.value,Q.value.ptr));return this.memory.heapValueHandle(X)}newUniqueSymbol(Y){let X=(typeof Y=="symbol"?Y.description:Y)??"",Q=this.memory.newHeapCharPointer(X).consume((J)=>this.ffi.QTS_NewSymbol(this.ctx.value,J.value.ptr,0));return this.memory.heapValueHandle(Q)}newSymbolFor(Y){let X=(typeof Y=="symbol"?Y.description:Y)??"",Q=this.memory.newHeapCharPointer(X).consume((J)=>this.ffi.QTS_NewSymbol(this.ctx.value,J.value.ptr,1));return this.memory.heapValueHandle(Q)}getWellKnownSymbol(Y){return this._Symbol??(this._Symbol=this.memory.manage(this.getProp(this.global,"Symbol"))),this.getProp(this._Symbol,Y)}newBigInt(Y){if(!this._BigInt){let J=this.getProp(this.global,"BigInt");this.memory.manage(J),this._BigInt=new F3(J.value,this.runtime)}let X=this._BigInt,Q=String(Y);return this.newString(Q).consume((J)=>this.unwrapResult(this.callFunction(X,this.undefined,J)))}newObject(Y){Y&&this.runtime.assertOwned(Y);let X=Y?this.ffi.QTS_NewObjectProto(this.ctx.value,Y.value):this.ffi.QTS_NewObject(this.ctx.value);return this.memory.heapValueHandle(X)}newArray(){let Y=this.ffi.QTS_NewArray(this.ctx.value);return this.memory.heapValueHandle(Y)}newArrayBuffer(Y){let X=new Uint8Array(Y),Q=this.memory.newHeapBufferPointer(X),J=this.ffi.QTS_NewArrayBuffer(this.ctx.value,Q.value.pointer,X.length);return this.memory.heapValueHandle(J)}newPromise(Y){let X=p5.withScope((Q)=>{let J=Q.manage(this.memory.newMutablePointerArray(2)),G=this.ffi.QTS_NewPromiseCapability(this.ctx.value,J.value.ptr),K=this.memory.heapValueHandle(G),[W,Z]=Array.from(J.value.typedArray).map((H)=>this.memory.heapValueHandle(H));return new $F6({context:this,promiseHandle:K,resolveHandle:W,rejectHandle:Z})});return Y&&typeof Y=="function"&&(Y=new Promise(Y)),Y&&Promise.resolve(Y).then(X.resolve,(Q)=>Q instanceof lY?X.reject(Q):this.newError(Q).consume(X.reject)),X}newFunction(Y,X){let Q=++this.fnNextId;return this.setFunction(Q,X),this.memory.heapValueHandle(this.ffi.QTS_NewFunction(this.ctx.value,Q,Y))}newError(Y){let X=this.memory.heapValueHandle(this.ffi.QTS_NewError(this.ctx.value));return Y&&typeof Y=="object"?(Y.name!==void 0&&this.newString(Y.name).consume((Q)=>this.setProp(X,"name",Q)),Y.message!==void 0&&this.newString(Y.message).consume((Q)=>this.setProp(X,"message",Q))):typeof Y=="string"?this.newString(Y).consume((Q)=>this.setProp(X,"message",Q)):Y!==void 0&&this.newString(String(Y)).consume((Q)=>this.setProp(X,"message",Q)),X}typeof(Y){return this.runtime.assertOwned(Y),this.memory.consumeHeapCharPointer(this.ffi.QTS_Typeof(this.ctx.value,Y.value))}getNumber(Y){return this.runtime.assertOwned(Y),this.ffi.QTS_GetFloat64(this.ctx.value,Y.value)}getString(Y){return this.runtime.assertOwned(Y),this.memory.consumeJSCharPointer(this.ffi.QTS_GetString(this.ctx.value,Y.value))}getSymbol(Y){this.runtime.assertOwned(Y);let X=this.memory.consumeJSCharPointer(this.ffi.QTS_GetSymbolDescriptionOrKey(this.ctx.value,Y.value));return this.ffi.QTS_IsGlobalSymbol(this.ctx.value,Y.value)?Symbol.for(X):Symbol(X)}getBigInt(Y){this.runtime.assertOwned(Y);let X=this.getString(Y);return BigInt(X)}getArrayBuffer(Y){this.runtime.assertOwned(Y);let X=this.ffi.QTS_GetArrayBufferLength(this.ctx.value,Y.value),Q=this.ffi.QTS_GetArrayBuffer(this.ctx.value,Y.value);if(!Q)throw Error("Couldn't allocate memory to get ArrayBuffer");return new lY(this.module.HEAPU8.subarray(Q,Q+X),void 0,()=>this.module._free(Q))}getPromiseState(Y){this.runtime.assertOwned(Y);let X=this.ffi.QTS_PromiseState(this.ctx.value,Y.value);if(X<0)return{type:"fulfilled",value:Y,notAPromise:!0};if(X===Cf.Pending)return{type:"pending",get error(){return new ZF6("Cannot unwrap a pending promise")}};let Q=this.ffi.QTS_PromiseResult(this.ctx.value,Y.value),J=this.memory.heapValueHandle(Q);if(X===Cf.Fulfilled)return{type:"fulfilled",value:J};if(X===Cf.Rejected)return{type:"rejected",error:J};throw J.dispose(),Error(`Unknown JSPromiseStateEnum: ${X}`)}resolvePromise(Y){this.runtime.assertOwned(Y);let X=p5.withScope((Q)=>{let J=Q.manage(this.getProp(this.global,"Promise")),G=Q.manage(this.getProp(J,"resolve"));return this.callFunction(G,J,Y)});return X.error?Promise.resolve(X):new Promise((Q)=>{p5.withScope((J)=>{let G=J.manage(this.newFunction("resolve",(H)=>{Q(this.success(H&&H.dup()))})),K=J.manage(this.newFunction("reject",(H)=>{Q(this.fail(H&&H.dup()))})),W=J.manage(X.value),Z=J.manage(this.getProp(W,"then"));this.callFunction(Z,W,G,K).unwrap().dispose()})})}isEqual(Y,X,Q=LP.IsStrictlyEqual){if(Y===X)return!0;this.runtime.assertOwned(Y),this.runtime.assertOwned(X);let J=this.ffi.QTS_IsEqual(this.ctx.value,Y.value,X.value,Q);if(J===-1)throw new YF6("WASM variant does not expose equality");return!!J}eq(Y,X){return this.isEqual(Y,X,LP.IsStrictlyEqual)}sameValue(Y,X){return this.isEqual(Y,X,LP.IsSameValue)}sameValueZero(Y,X){return this.isEqual(Y,X,LP.IsSameValueZero)}getProp(Y,X){this.runtime.assertOwned(Y);let Q;return typeof X=="number"&&X>=0?Q=this.ffi.QTS_GetPropNumber(this.ctx.value,Y.value,X):Q=this.borrowPropertyKey(X).consume((J)=>this.ffi.QTS_GetProp(this.ctx.value,Y.value,J.value)),this.memory.heapValueHandle(Q)}getLength(Y){if(this.runtime.assertOwned(Y),!(this.ffi.QTS_GetLength(this.ctx.value,this.uint32Out.value.ptr,Y.value)<0))return this.uint32Out.value.typedArray[0]}getOwnPropertyNames(Y,X={strings:!0,numbersAsStrings:!0}){this.runtime.assertOwned(Y),Y.value;let Q=Xn4(X);if(Q===0)throw new KF6("No options set, will return an empty array");return p5.withScope((J)=>{let G=J.manage(this.memory.newMutablePointerArray(1)),K=this.ffi.QTS_GetOwnPropertyNames(this.ctx.value,G.value.ptr,this.uint32Out.value.ptr,Y.value,Q);if(K)return this.fail(this.memory.heapValueHandle(K));let W=this.uint32Out.value.typedArray[0],Z=G.value.typedArray[0],H=new Uint32Array(this.module.HEAP8.buffer,Z,W),F=Array.from(H).map((V)=>this.memory.heapValueHandle(V));return this.ffi.QTS_FreeVoidPointer(this.ctx.value,Z),this.success(FF6(F))})}getIterator(Y){let X=this._SymbolIterator??(this._SymbolIterator=this.memory.manage(this.getWellKnownSymbol("iterator")));return p5.withScope((Q)=>{let J=Q.manage(this.getProp(Y,X)),G=this.callFunction(J,Y);return G.error?G:this.success(new Jn4(G.value,this))})}setProp(Y,X,Q){this.runtime.assertOwned(Y),this.borrowPropertyKey(X).consume((J)=>this.ffi.QTS_SetProp(this.ctx.value,Y.value,J.value,Q.value))}defineProp(Y,X,Q){this.runtime.assertOwned(Y),p5.withScope((J)=>{let G=J.manage(this.borrowPropertyKey(X)),K=Q.value||this.undefined,W=!!Q.configurable,Z=!!Q.enumerable,H=!!Q.value,F=Q.get?J.manage(this.newFunction(Q.get.name,Q.get)):this.undefined,V=Q.set?J.manage(this.newFunction(Q.set.name,Q.set)):this.undefined;this.ffi.QTS_DefineProp(this.ctx.value,Y.value,G.value,K.value,F.value,V.value,W,Z,H)})}callFunction(Y,X,...Q){this.runtime.assertOwned(Y);let J,G=Q[0];G===void 0||Array.isArray(G)?J=G??[]:J=Q;let K=this.memory.toPointerArray(J).consume((Z)=>this.ffi.QTS_Call(this.ctx.value,Y.value,X.value,J.length,Z.value)),W=this.ffi.QTS_ResolveException(this.ctx.value,K);return W?(this.ffi.QTS_FreeValuePointer(this.ctx.value,K),this.fail(this.memory.heapValueHandle(W))):this.success(this.memory.heapValueHandle(K))}callMethod(Y,X,Q=[]){return this.getProp(Y,X).consume((J)=>this.callFunction(J,Y,Q))}evalCode(Y,X="eval.js",Q){let J=Q===void 0?1:0,G=Yn4(Q),K=this.memory.newHeapCharPointer(Y).consume((Z)=>this.ffi.QTS_Eval(this.ctx.value,Z.value.ptr,Z.value.strlen,X,J,G)),W=this.ffi.QTS_ResolveException(this.ctx.value,K);return W?(this.ffi.QTS_FreeValuePointer(this.ctx.value,K),this.fail(this.memory.heapValueHandle(W))):this.success(this.memory.heapValueHandle(K))}throw(Y){return this.errorToHandle(Y).consume((X)=>this.ffi.QTS_Throw(this.ctx.value,X.value))}borrowPropertyKey(Y){return typeof Y=="number"?this.newNumber(Y):typeof Y=="string"?this.newString(Y):new F3(Y.value,this.runtime)}getMemory(Y){if(Y===this.rt.value)return this.memory;throw Error("Private API. Cannot get memory from a different runtime")}dump(Y){this.runtime.assertOwned(Y);let X=this.typeof(Y);if(X==="string")return this.getString(Y);if(X==="number")return this.getNumber(Y);if(X==="bigint")return this.getBigInt(Y);if(X==="undefined")return;if(X==="symbol")return this.getSymbol(Y);let Q=this.getPromiseState(Y);if(Q.type==="fulfilled"&&!Q.notAPromise)return Y.dispose(),{type:Q.type,value:Q.value.consume(this.dump)};if(Q.type==="pending")return Y.dispose(),{type:Q.type};if(Q.type==="rejected")return Y.dispose(),{type:Q.type,error:Q.error.consume(this.dump)};let J=this.memory.consumeJSCharPointer(this.ffi.QTS_Dump(this.ctx.value,Y.value));try{return JSON.parse(J)}catch{return J}}unwrapResult(Y){if(Y.error){let X="context"in Y.error?Y.error.context:this,Q=Y.error.consume((J)=>this.dump(J));if(Q&&typeof Q=="object"&&typeof Q.message=="string"){let{message:J,name:G,stack:K,...W}=Q,Z=new qY0(Q,X);typeof G=="string"&&(Z.name=Q.name),Z.message=J;let H=Z.stack;throw typeof K=="string"&&(Z.stack=`${G}: ${J}
402
402
  ${Q.stack}Host: ${H}`),Object.assign(Z,W),Z}throw new qY0(Q)}return Y.value}[Symbol.for("nodejs.util.inspect.custom")](){return this.alive?`${this.constructor.name} { ctx: ${this.ctx.value} rt: ${this.rt.value} }`:`${this.constructor.name} { disposed }`}getFunction(Y){let X=Y>>8,Q=this.fnMaps.get(X);if(Q)return Q.get(Y)}setFunction(Y,X){let Q=Y>>8,J=this.fnMaps.get(Q);return J||(J=new Map,this.fnMaps.set(Q,J)),J.set(Y,X)}errorToHandle(Y){return Y instanceof lY?Y:this.newError(Y)}encodeBinaryJSON(Y){let X=this.ffi.QTS_bjson_encode(this.ctx.value,Y.value);return this.memory.heapValueHandle(X)}decodeBinaryJSON(Y){let X=this.ffi.QTS_bjson_decode(this.ctx.value,Y.value);return this.memory.heapValueHandle(X)}success(Y){return $V.success(Y)}fail(Y){return $V.fail(Y,(X)=>this.unwrapResult(X))}},UF6=class extends pW{constructor(Y){super();this.scope=new p5,this.contextMap=new Map,this._debugMode=!1,this.cToHostCallbacks={shouldInterrupt:(X)=>{if(X!==this.rt.value)throw Error("QuickJSContext instance received C -> JS interrupt with mismatched rt");let Q=this.interruptHandler;if(!Q)throw Error("QuickJSContext had no interrupt handler");return Q(this)?1:0},loadModuleSource:oH6(this,function*(X,Q,J,G){let K=this.moduleLoader;if(!K)throw Error("Runtime has no module loader");if(Q!==this.rt.value)throw Error("Runtime pointer mismatch");let W=this.contextMap.get(J)??this.newContext({contextPointer:J});try{let Z=yield*X(K(G,W));if(typeof Z=="object"&&"error"in Z&&Z.error)throw this.debugLog("cToHostLoadModule: loader returned error",Z.error),Z.error;let H=typeof Z=="string"?Z:("value"in Z)?Z.value:Z;return this.memory.newHeapCharPointer(H).value.ptr}catch(Z){return this.debugLog("cToHostLoadModule: caught error",Z),W.throw(Z),0}}),normalizeModule:oH6(this,function*(X,Q,J,G,K){let W=this.moduleNormalizer;if(!W)throw Error("Runtime has no module normalizer");if(Q!==this.rt.value)throw Error("Runtime pointer mismatch");let Z=this.contextMap.get(J)??this.newContext({contextPointer:J});try{let H=yield*X(W(G,K,Z));if(typeof H=="object"&&"error"in H&&H.error)throw this.debugLog("cToHostNormalizeModule: normalizer returned error",H.error),H.error;let F=typeof H=="string"?H:H.value;return Z.getMemory(this.rt.value).newHeapCharPointer(F).value.ptr}catch(H){return this.debugLog("normalizeModule: caught error",H),Z.throw(H),0}})},Y.ownedLifetimes?.forEach((X)=>this.scope.manage(X)),this.module=Y.module,this.memory=new zF6(this.module),this.ffi=Y.ffi,this.rt=Y.rt,this.callbacks=Y.callbacks,this.scope.manage(this.rt),this.callbacks.setRuntimeCallbacks(this.rt.value,this.cToHostCallbacks),this.executePendingJobs=this.executePendingJobs.bind(this),UY0&&this.setDebugMode(!0)}get alive(){return this.scope.alive}dispose(){return this.scope.dispose()}newContext(Y={}){let X=ec4(Y.intrinsics),Q=new lY(Y.contextPointer||this.ffi.QTS_NewContext(this.rt.value,X),void 0,(G)=>{this.contextMap.delete(G),this.callbacks.deleteContext(G),this.ffi.QTS_FreeContext(G)}),J=new BF6({module:this.module,ctx:Q,ffi:this.ffi,rt:this.rt,ownedLifetimes:Y.ownedLifetimes,runtime:this,callbacks:this.callbacks});return this.contextMap.set(Q.value,J),J}setModuleLoader(Y,X){this.moduleLoader=Y,this.moduleNormalizer=X,this.ffi.QTS_RuntimeEnableModuleLoader(this.rt.value,this.moduleNormalizer?1:0)}removeModuleLoader(){this.moduleLoader=void 0,this.ffi.QTS_RuntimeDisableModuleLoader(this.rt.value)}hasPendingJob(){return!!this.ffi.QTS_IsJobPending(this.rt.value)}setInterruptHandler(Y){let X=this.interruptHandler;this.interruptHandler=Y,X||this.ffi.QTS_RuntimeEnableInterruptHandler(this.rt.value)}removeInterruptHandler(){this.interruptHandler&&(this.ffi.QTS_RuntimeDisableInterruptHandler(this.rt.value),this.interruptHandler=void 0)}executePendingJobs(Y=-1){let X=this.memory.newMutablePointerArray(1),Q=this.ffi.QTS_ExecutePendingJob(this.rt.value,Y??-1,X.value.ptr),J=X.value.typedArray[0];if(X.dispose(),J===0)return this.ffi.QTS_FreeValuePointerRuntime(this.rt.value,Q),$V.success(0);let G=this.contextMap.get(J)??this.newContext({contextPointer:J}),K=G.getMemory(this.rt.value).heapValueHandle(Q);if(G.typeof(K)==="number"){let W=G.getNumber(K);return K.dispose(),$V.success(W)}else{let W=Object.assign(K,{context:G});return $V.fail(W,(Z)=>G.unwrapResult(Z))}}setMemoryLimit(Y){if(Y<0&&Y!==-1)throw Error("Cannot set memory limit to negative number. To unset, pass -1");this.ffi.QTS_RuntimeSetMemoryLimit(this.rt.value,Y)}computeMemoryUsage(){let Y=this.getSystemContext().getMemory(this.rt.value);return Y.heapValueHandle(this.ffi.QTS_RuntimeComputeMemoryUsage(this.rt.value,Y.ctx.value))}dumpMemoryUsage(){return this.memory.consumeHeapCharPointer(this.ffi.QTS_RuntimeDumpMemoryUsage(this.rt.value))}setMaxStackSize(Y){if(Y<0)throw Error("Cannot set memory limit to negative number. To unset, pass 0.");this.ffi.QTS_RuntimeSetMaxStackSize(this.rt.value,Y)}assertOwned(Y){if(Y.owner&&Y.owner.rt!==this.rt)throw new eH6(`Handle is not owned by this runtime: ${Y.owner.rt.value} != ${this.rt.value}`)}setDebugMode(Y){this._debugMode=Y,this.ffi.DEBUG&&this.rt.alive&&this.ffi.QTS_SetDebugLogEnabled(this.rt.value,Y?1:0)}isDebugMode(){return this._debugMode}debugLog(...Y){this._debugMode&&console.log("quickjs-emscripten:",...Y)}[Symbol.for("nodejs.util.inspect.custom")](){return this.alive?`${this.constructor.name} { rt: ${this.rt.value} }`:`${this.constructor.name} { disposed }`}getSystemContext(){return this.context||(this.context=this.scope.manage(this.newContext())),this.context}}});var DF6={};d6(DF6,{applyModuleEvalRuntimeOptions:()=>PY0,applyBaseRuntimeOptions:()=>wY0,QuickJSWASMModule:()=>AY0,QuickJSModuleCallbacks:()=>MY0});var OF6=m(()=>{TY0()});async function NF6(Y){let X=EY0(await Y),[Q,J,{QuickJSWASMModule:G}]=await Promise.all([X.importModuleLoader().then(EY0),X.importFFI(),Promise.resolve().then(() => (OF6(),DF6)).then(EY0)]),K=await Q();K.type="sync";let W=new J(K);return new G(K,W)}function EY0(Y){return Y&&"default"in Y&&Y.default?Y.default&&"default"in Y.default&&Y.default.default?Y.default.default:Y.default:Y}var IY0=m(()=>{TY0();Rf()});import Zn4 from"@jitl/quickjs-wasmfile-release-sync";function MF6(){return LF6??=NF6(Zn4),LF6}var LF6;var wF6=m(()=>{IY0()});async function PF6(Y={}){let Q=(await MF6()).newRuntime({maxStackSizeBytes:Y.stackSizeBytes,memoryLimitBytes:Y.memoryLimitBytes});return{newContext:({interruptAfterMs:G,...K}={})=>{let W=Q.newContext({intrinsics:{...LY0,...K}}),Z=0,H=(F)=>{Z=F?Date.now()+F:0};if(Q.setInterruptHandler(()=>{let F=Date.now(),V=Z>0&&F>Z;return V}),G)H(G);return W},dispose:()=>{Q.dispose()},[Symbol.dispose](){Q.dispose()}}}var AF6=m(()=>{IY0();wF6()});function pB(Y){if(Y===null)return"null";if(Y===void 0)return"undefined";if(Y instanceof Error){let X=Y.message||Y.name||"Error";if(Y.stack&&Y.stack.length<2000)return`${X}
403
403
  ${Y.stack}`;return X}if(typeof Y==="object"&&Y!==null){let X=Y,Q="";if(typeof X.message==="string"&&X.message)Q=X.message;else if(typeof X.error==="string"&&X.error)Q=X.error;else if(typeof X.description==="string"&&X.description)Q=X.description;else if(typeof X.reason==="string"&&X.reason)Q=X.reason;if(Q){if(typeof X.stack==="string"&&X.stack&&X.stack.length<2000)return`${Q}
404
404
  ${X.stack}`;return Q}try{let G=JSON.stringify(X,null,2);if(G!=="{}"&&G.length<1000){if(typeof X.stack==="string"&&X.stack&&X.stack.length<2000)return`${G}
405
405
 
406
406
  Stack trace:
407
- ${X.stack}`;return G}}catch{}if(typeof X.toString==="function")try{let G=X.toString();if(G!=="[object Object]")return G}catch{}let J=Object.keys(X);if(J.length>0)return`Object with keys: ${J.join(", ")}`;return"[object Object]"}if(typeof Y==="string")return Y;if(typeof Y==="number"||typeof Y==="boolean")return String(Y);if(typeof Y==="function")return`[Function: ${Y.name||"anon"}]`;if(typeof Y==="symbol")return Y.toString();if(typeof Y==="bigint")return Y.toString();try{return String(Y)}catch{return"Unknown value (could not convert to string)"}}function cB(Y,X){switch(typeof X){case"string":return Y.newString(X);case"number":return Y.newNumber(X);case"boolean":return X?Y.true:Y.false;case"undefined":return Y.undefined;case"object":{if(X===null)return Y.null;if(Array.isArray(X)){let J=Y.newArray();return X.forEach((G,K)=>{let W=cB(Y,G);try{Y.setProp(J,String(K),W)}finally{W.dispose?.()}}),J}let Q=Y.newObject();for(let[J,G]of Object.entries(X)){let K=cB(Y,G);try{Y.setProp(Q,J,K)}finally{K.dispose?.()}}return Q}case"function":{let Q=`__hostFn_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return Y.newFunction(Q,(...G)=>{try{let K=G.map((Z)=>Y.dump(Z)),W=X(...K);if(W&&typeof W.then==="function"){let Z=Y.newPromise();return W.then((H)=>{try{let F=cB(Y,H);Z.resolve(F),F.dispose(),Y.runtime.executePendingJobs()}catch(F){let V=pB(F),q=Y.newString(`Promise resolution error: ${V}`);Z.reject(q),q.dispose(),Y.runtime.executePendingJobs()}}).catch((H)=>{let F=pB(H),V=Y.newString(`Promise rejection: ${F}`);Z.reject(V),V.dispose(),Y.runtime.executePendingJobs()}),Z.handle}return cB(Y,W)}catch(K){let W=pB(K);return Y.newString(`HostFunctionError: ${W}`)}finally{G.forEach((K)=>K.dispose())}})}case"bigint":return Y.newString(X.toString());case"symbol":return Y.newString(X.toString());default:try{return Y.newString(String(X))}catch{return Y.undefined}}}var TF6=()=>{};function IF6(Y){let X=Y.runtime.executePendingJobs(100);try{if("unwrap"in X&&typeof X.unwrap==="function")X.unwrap()}finally{if("dispose"in X&&typeof X.dispose==="function")X.dispose()}}async function EF6(Y,X,Q){let J=Date.now(),G=Y.resolvePromise(X);while(!0){IF6(Y);let K=await Promise.race([G,Kn4(0).then(()=>null)]);if(K!==null)return K;if(Date.now()-J>Q)throw Error(`Timed out after ${Q}ms while awaiting a QuickJS promise`)}}async function CY0({tools:Y,code:X,timeoutMs:Q}){let W=[];try{let J=await PF6({memoryLimitBytes:33554432,stackSizeBytes:524288});const G=mf(W,J.newContext({interruptAfterMs:Q}),0);const K=mf(W,rH6(G),0);try{let V=G.evalCode(X,"index.mjs",{strip:!0,strict:!0,type:"module"}),q=G.unwrapResult(V),$=cB(G,Y);G.setProp(G.global,"tools",$);let B=G.runtime.hasPendingJob()?G.unwrapResult(await EF6(G,q,Q)):q;if(B!==q)q.dispose();let U=G.getProp(B,"default"),D=G.typeof(U);if(D!=="function")return{error:`Code must export default a function (tools). Got ${D}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:K.logs};let L=G.callFunction(U,G.undefined,$),M=G.unwrapResult(L),I=await EF6(G,M,Q),R=G.unwrapResult(I);if(G.runtime.hasPendingJob())IF6(G);return{returnValue:G.dump(R),consoleLogs:K.logs}}catch(V){return console.log(V),{error:pB(V),consoleLogs:K.logs}}}catch(Z){var H=Z,F=1}finally{EX0(W,H,F)}}var Kn4=(Y)=>new Promise((X)=>setTimeout(X,Y));var CF6=m(()=>{AF6();TF6()});var RF6=m(()=>{CF6()});async function Hn4(Y,X){let Q;if(Y.tool_selection_mode==="exclusion"){let G=(await X.storage.connections.list(Y.organization_id)).filter((W)=>W.status==="active"),K=new Map;for(let W of Y.connections)K.set(W.connection_id,{selectedTools:W.selected_tools,selectedResources:W.selected_resources,selectedPrompts:W.selected_prompts});Q=[];for(let W of G){let Z=K.get(W.id);if(Z===void 0)Q.push({connection:W,selectedTools:null,selectedResources:null,selectedPrompts:null});else if((Z.selectedTools===null||Z.selectedTools.length===0)&&(Z.selectedResources===null||Z.selectedResources.length===0)&&(Z.selectedPrompts===null||Z.selectedPrompts.length===0));else Q.push({connection:W,selectedTools:Z.selectedTools,selectedResources:Z.selectedResources,selectedPrompts:Z.selectedPrompts})}}else{let J=Y.connections.map((K)=>K.connection_id),G=[];for(let K of J){let W=await X.storage.connections.findById(K);if(W&&W.status==="active")G.push(W)}Q=G.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}})}return Q}async function SF6(Y,X){return(await X.storage.connections.list(Y)).filter((J)=>J.status==="active").map((J)=>({connection:J,selectedTools:null,selectedResources:null,selectedPrompts:null}))}async function Fn4(Y,X,Q){let J=await If.create(Y,Q),G=await J.mapSettled(async(V,q)=>{try{let B=(await V.proxy.client.listTools()).tools;if(X==="exclusion"){if(V.selectedTools&&V.selectedTools.length>0){let U=new Set(V.selectedTools);B=B.filter((D)=>!U.has(D.name))}}else if(V.selectedTools&&V.selectedTools.length>0){let U=new Set(V.selectedTools);B=B.filter((D)=>U.has(D.name))}return{connectionId:q,connectionTitle:V.connection.title,tools:B}}catch($){return console.error(`[code-execution] Failed to list tools for connection ${q}:`,$),null}}),K=new Set,W=[],Z=new Map,H=new Set;for(let V of G){if(V.status!=="fulfilled"||!V.value)continue;let{connectionId:q,connectionTitle:$,tools:B}=V.value;H.add($);for(let U of B){if(K.has(U.name))continue;K.add(U.name),W.push({...U,_meta:{connectionId:q,connectionTitle:$}}),Z.set(U.name,{connectionId:q,originalName:U.name})}}return{tools:W,callTool:async(V,q)=>{let $=Z.get(V);if(!$)return{content:[{type:"text",text:`Tool not found: ${V}`}],isError:!0};let B=J.get($.connectionId);if(!B)return{content:[{type:"text",text:`Connection not found for tool: ${V}`}],isError:!0};return await B.proxy.client.callTool({name:$.originalName,arguments:q})},categories:Array.from(H).sort()}}async function nB(Y){let X=S6(Y),Q,J="inclusion";if(Y.connectionId){let G=await Y.storage.virtualMcps.findById(Y.connectionId);if(G)Q=await Hn4(G,Y),J=G.tool_selection_mode;else Q=await SF6(X.id,Y)}else Q=await SF6(X.id,Y);return Fn4(Q,J,Y)}function Vn4(Y){return Y.toLowerCase().split(/[\s_\-./]+/).filter((X)=>X.length>=2)}function qn4(Y,X){let Q=0,J=X.name.toLowerCase(),G=(X.description??"").toLowerCase(),K=X._meta.connectionTitle.toLowerCase();for(let W of Y){if(J===W)Q+=10;else if(J.includes(W))Q+=3;if(G.includes(W))Q+=2;if(K.includes(W))Q+=1}return Q}function jF6(Y,X,Q){let J=Vn4(Y);if(J.length===0)return X.slice(0,Q);return X.map((G)=>({tool:G,score:qn4(J,G)})).filter((G)=>G.score>0).sort((G,K)=>K.score-G.score).slice(0,Q).map((G)=>G.tool)}function kF6(Y,X){let Q=new Map(X.map((G)=>[G.name,G]));return{tools:Y.map((G)=>Q.get(G)).filter((G)=>G!==void 0).map((G)=>({name:G.name,description:G.description,connection:G._meta.connectionTitle,inputSchema:G.inputSchema,outputSchema:G.outputSchema})),notFound:Y.filter((G)=>!Q.has(G))}}async function vF6(Y,X,Q){let J=Object.fromEntries(X.tools.map((G)=>[G.name,async(K)=>X.callTool(G.name,K??{})]));return CY0({code:Y,tools:J,timeoutMs:Q})}var jf=m(()=>{RF6()});var RY0;var _F6=m(()=>{J4();NP();jf();RY0=X6({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:dH6,outputSchema:pH6,handler:async(Y,X)=>{$6(X),S6(X),await X.access.check();let Q=await nB(X),J=jF6(Y.query,Q.tools,Y.limit);return{query:Y.query,results:J.map((G)=>({name:G.name,description:G.description,connection:G._meta.connectionTitle})),totalAvailable:Q.tools.length}}})});var SY0;var yF6=m(()=>{J4();NP();jf();SY0=X6({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:cH6,outputSchema:nH6,handler:async(Y,X)=>{$6(X),S6(X),await X.access.check();let Q=await nB(X);return kF6(Y.tools,Q.tools)}})});var jY0;var fF6=m(()=>{J4();NP();jf();jY0=X6({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:iH6,outputSchema:aH6,handler:async(Y,X)=>{$6(X),S6(X),await X.access.check();let Q=await nB(X);return await vF6(Y.code,Q,Y.timeoutMs)}})});var hF6=m(()=>{_F6();yF6();fF6();NP()});var zn4,Bn4,kY0;var bF6=m(()=>{E90();Y6();J4();Tf();Z3();zn4=N.object({data:q36.describe("Data for the new connection (id is auto-generated if not provided)")}),Bn4=N.object({item:cJ.describe("The created connection entity")}),kY0=X6({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",inputSchema:zn4,outputSchema:Bn4,handler:async(Y,X)=>{$6(X);let Q=S6(X);await X.access.check();let J=x8(X);if(!J)throw Error("User ID required to create connection");let G={...Y.data,organization_id:Q.id,created_by:J};if(G.connection_type==="VIRTUAL"){let H=Of(G.connection_url);if(!H)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let F=await X.storage.virtualMcps.findById(H);if(!F)throw Error(`Virtual MCP not found: ${H}`);if(F.organization_id!==Q.id)throw Error("Virtual MCP does not belong to the current organization");G.connection_url=Nf(H)}let K=await mB({id:`pending-${Date.now()}`,title:G.title,connection_type:G.connection_type,connection_url:G.connection_url,connection_token:G.connection_token,connection_headers:G.connection_headers}).catch(()=>null),W=K?.length?K:null,Z=await X.storage.connections.create({...G,tools:W});return await X.eventBus.publish(Q.id,FP.SELF(Q.id),{type:"connection.created",data:Z}),{item:Z}}})});function MP(Y,X){if(Y===X)return!0;if(Y==null||X==null)return Y===X;if(typeof Y!==typeof X)return!1;if(Array.isArray(Y)&&Array.isArray(X)){if(Y.length!==X.length)return!1;return Y.every((Q,J)=>MP(Q,X[J]))}if(typeof Y==="object"&&typeof X==="object"){let Q=Object.keys(Y),J=Object.keys(X);if(Q.length!==J.length)return!1;return Q.every((G)=>J.includes(G)&&MP(Y[G],X[G]))}return!1}function bn4(){return(Y)=>{if(!Array.isArray(Y))return!0;let X=[];return Y.every((Q)=>{if(X.some((G)=>MP(Q,G)))return!1;return X.push(Q),!0})}}function kf(Y,X){return Y.safeParse(X).success}function NY(Y){if(typeof Y==="boolean")return Y?N.any():N.never();let X={};for(let G of sn4)G.apply(X,Y);let Q=[];if(X.string!==!1)Q.push(X.string||N.string());if(X.number!==!1)Q.push(X.number||N.number());if(X.boolean!==!1)Q.push(X.boolean||N.boolean());if(X.null!==!1)Q.push(X.null||N.null());if(X.array!==!1)Q.push(X.array||N.array(N.any()));if(X.tuple!==!1&&X.tuple!==void 0)Q.push(X.tuple);if(X.object!==!1)if(X.object)Q.push(X.object);else{let G=N.custom((K)=>{return typeof K==="object"&&K!==null&&!Array.isArray(K)},"Must be an object, not an array");Q.push(G)}if(X.file!==!1&&X.file!==void 0)Q.push(X.file);let J;if(Q.length===0)J=N.never();else if(Q.length===1)J=Q[0];else if(!Object.keys(Y).some((K)=>K!=="$schema"&&K!=="title"&&K!=="description"))J=N.any();else J=N.union(Q);for(let G of tn4)J=G.apply(J,Y);return J}var Un4=class{apply(Y,X){if(!X.type)return;let Q=Array.isArray(X.type)?X.type:[X.type],J=new Set(Q);if(!J.has("string"))Y.string=!1;if(!J.has("number")&&!J.has("integer"))Y.number=!1;if(!J.has("boolean"))Y.boolean=!1;if(!J.has("null"))Y.null=!1;if(!J.has("array"))Y.array=!1;if(!J.has("object"))Y.object=!1;if(J.has("integer")&&Y.number!==!1){let G=Y.number||N.number();if(G instanceof N.ZodNumber)Y.number=G.int()}}},Dn4=class{apply(Y,X){if(X.const===void 0)return;let Q=X.const;if(Y.string=!1,Y.number=!1,Y.boolean=!1,Y.null=!1,Y.array=!1,Y.object=!1,typeof Q==="string")Y.string=N.literal(Q);else if(typeof Q==="number")Y.number=N.literal(Q);else if(typeof Q==="boolean")Y.boolean=N.literal(Q);else if(Q===null)Y.null=N.null();else if(Array.isArray(Q))Y.array=void 0;else if(typeof Q==="object")Y.object=void 0}},On4=class{apply(Y,X){if(!X.enum)return;if(X.enum.length===0){if(!X.type)Y.string=!1,Y.number=!1,Y.boolean=!1,Y.null=!1,Y.array=!1,Y.object=!1;return}let Q={string:X.enum.filter((J)=>typeof J==="string"),number:X.enum.filter((J)=>typeof J==="number"),boolean:X.enum.filter((J)=>typeof J==="boolean"),null:X.enum.filter((J)=>J===null),array:X.enum.filter((J)=>Array.isArray(J)),object:X.enum.filter((J)=>typeof J==="object"&&J!==null&&!Array.isArray(J))};Y.string=this.createTypeSchema(Q.string,"string"),Y.number=this.createTypeSchema(Q.number,"number"),Y.boolean=this.createTypeSchema(Q.boolean,"boolean"),Y.null=Q.null.length>0?N.null():!1,Y.array=Q.array.length>0?void 0:!1,Y.object=Q.object.length>0?void 0:!1}createTypeSchema(Y,X){if(Y.length===0)return!1;if(Y.length===1)return N.literal(Y[0]);if(X==="string")return N.enum(Y);if(X==="number"){let[Q,J,...G]=Y;return N.union([N.literal(Q),N.literal(J),...G.map((K)=>N.literal(K))])}if(X==="boolean")return N.union([N.literal(!0),N.literal(!1)]);return!1}},Nn4=class{apply(Y,X){let Q=X;if(Q.type==="string"&&Q.format==="binary"&&Q.contentEncoding==="binary"){let J=N.file();if(Q.minLength!==void 0)J=J.min(Q.minLength);if(Q.maxLength!==void 0)J=J.max(Q.maxLength);if(Q.contentMediaType!==void 0)J=J.mime(Q.contentMediaType);Y.file=J,Y.string=!1}}},Ln4=class{apply(Y,X){let Q=X;if(X.type===void 0&&(Q.minLength!==void 0||Q.maxLength!==void 0||Q.pattern!==void 0)){if(Y.string===void 0)Y.string=N.string()}}},Mn4=class{apply(Y,X){let Q=X;if(Q.minLength===void 0)return;if(Y.string!==!1){let J=Y.string||N.string();if(J instanceof N.ZodString)Y.string=J.refine((G)=>{return Array.from(G).length>=Q.minLength},{message:`String must be at least ${Q.minLength} characters long`})}}},wn4=class{apply(Y,X){let Q=X;if(Q.maxLength===void 0)return;if(Y.string!==!1){let J=Y.string||N.string();if(J instanceof N.ZodString)Y.string=J.refine((G)=>{return Array.from(G).length<=Q.maxLength},{message:`String must be at most ${Q.maxLength} characters long`})}}},Pn4=class{apply(Y,X){let Q=X;if(!Q.pattern)return;if(Y.string!==!1){let J=Y.string||N.string();if(J instanceof N.ZodString){let G=new RegExp(Q.pattern);Y.string=J.regex(G)}}}},An4=class{apply(Y,X){let Q=X;if(Q.minimum===void 0)return;if(Y.number!==!1){let J=Y.number||N.number();if(J instanceof N.ZodNumber)Y.number=J.min(Q.minimum)}}},Tn4=class{apply(Y,X){let Q=X;if(Q.maximum===void 0)return;if(Y.number!==!1){let J=Y.number||N.number();if(J instanceof N.ZodNumber)Y.number=J.max(Q.maximum)}}},En4=class{apply(Y,X){let Q=X;if(Q.exclusiveMinimum===void 0)return;if(Y.number!==!1){let J=Y.number||N.number();if(J instanceof N.ZodNumber)if(typeof Q.exclusiveMinimum==="number")Y.number=J.gt(Q.exclusiveMinimum);else Y.number=!1}}},In4=class{apply(Y,X){let Q=X;if(Q.exclusiveMaximum===void 0)return;if(Y.number!==!1){let J=Y.number||N.number();if(J instanceof N.ZodNumber)if(typeof Q.exclusiveMaximum==="number")Y.number=J.lt(Q.exclusiveMaximum);else Y.number=!1}}},Cn4=class{apply(Y,X){let Q=X;if(Q.multipleOf===void 0)return;if(Y.number!==!1){let J=Y.number||N.number();if(J instanceof N.ZodNumber)Y.number=J.refine((G)=>{if(Q.multipleOf===0)return!1;let K=G/Q.multipleOf,W=Math.round(K),Z=Math.min(Math.abs(G)*Number.EPSILON*10,Math.abs(Q.multipleOf)*Number.EPSILON*10);return Math.abs(K-W)<=Z/Math.abs(Q.multipleOf)},{message:`Must be a multiple of ${Q.multipleOf}`})}}},Rn4=class{apply(Y,X){let Q=X;if(X.type===void 0&&(Q.minItems!==void 0||Q.maxItems!==void 0||Q.items!==void 0||Q.prefixItems!==void 0)){if(Y.array===void 0)Y.array=N.array(N.any())}}},Sn4=class{apply(Y,X){let Q=X;if(Q.minItems===void 0)return;if(Y.array!==!1)Y.array=(Y.array||N.array(N.any())).min(Q.minItems)}},jn4=class{apply(Y,X){let Q=X;if(Q.maxItems===void 0)return;if(Y.array!==!1)Y.array=(Y.array||N.array(N.any())).max(Q.maxItems)}},kn4=class{apply(Y,X){let Q=X;if(Y.array===!1)return;if(Array.isArray(Q.items))Y.array=Y.array||N.array(N.any());else if(Q.items&&typeof Q.items!=="boolean"&&!Q.prefixItems){let J=NY(Q.items),G=N.array(J);if(Y.array&&Y.array instanceof N.ZodArray){let K=Y.array._def;if(K.checks)K.checks.forEach((W)=>{if(W._zod&&W._zod.def){let Z=W._zod.def;if(Z.check==="min_length"&&Z.minimum!==void 0)G=G.min(Z.minimum);else if(Z.check==="max_length"&&Z.maximum!==void 0)G=G.max(Z.maximum)}})}Y.array=G}else if(typeof Q.items==="boolean"&&Q.items===!1)if(!Q.prefixItems)Y.array=N.array(N.any()).max(0);else Y.array=Y.array||N.array(N.any());else if(typeof Q.items==="boolean"&&Q.items===!0)Y.array=Y.array||N.array(N.any());else if(Q.prefixItems)Y.array=Y.array||N.array(N.any())}},vn4=class{apply(Y,X){if(X.type!=="array")return;let Q=X;if(!Array.isArray(Q.items))return;if(Y.array===!1)return;let J=Q.items.map((K)=>NY(K)),G;if(J.length===0)G=N.tuple([]);else G=N.tuple(J);if(Q.minItems!==void 0&&Q.minItems>J.length)G=!1;if(Q.maxItems!==void 0&&Q.maxItems<J.length)G=!1;Y.tuple=G,Y.array=!1}},_n4=class{apply(Y,X){let Q=X;if(Y.object===!1)return;if(Q.properties||Q.required||Q.additionalProperties!==void 0)Y.object=Y.object||N.object({}).passthrough()}},yn4=class{apply(Y,X){let Q=X;if(X.type===void 0&&(Q.maxProperties!==void 0||Q.minProperties!==void 0)){if(Y.object===void 0)Y.object=N.object({}).passthrough()}}},fn4=class{apply(Y,X){let Q=X;if(Q.maxProperties===void 0)return;if(Y.object!==!1){let J=Y.object||N.object({}).passthrough();Y.object=J.refine((G)=>Object.keys(G).length<=Q.maxProperties,{message:`Object must have at most ${Q.maxProperties} properties`})}}},hn4=class{apply(Y,X){let Q=X;if(Q.minProperties===void 0)return;if(Y.object!==!1){let J=Y.object||N.object({}).passthrough();Y.object=J.refine((G)=>Object.keys(G).length>=Q.minProperties,{message:`Object must have at least ${Q.minProperties} properties`})}}},xn4=class{apply(Y,X){if(!X.not)return Y;let Q=NY(X.not);return Y.refine((J)=>!kf(Q,J),{message:"Value must not match the 'not' schema"})}},un4=class{apply(Y,X){if(X.uniqueItems!==!0)return Y;return Y.refine(bn4(),{message:"Array items must be unique"})}},gn4=class{apply(Y,X){if(!X.allOf||X.allOf.length===0)return Y;return X.allOf.map((J)=>NY(J)).reduce((J,G)=>N.intersection(J,G),Y)}},mn4=class{apply(Y,X){if(!X.anyOf||X.anyOf.length===0)return Y;let Q=X.anyOf.length===1?NY(X.anyOf[0]):N.union([NY(X.anyOf[0]),NY(X.anyOf[1]),...X.anyOf.slice(2).map((J)=>NY(J))]);return N.intersection(Y,Q)}},ln4=class{apply(Y,X){if(!X.oneOf||X.oneOf.length===0)return Y;let Q=X.oneOf.map((J)=>NY(J));return Y.refine((J)=>{let G=0;for(let K of Q)if(K.safeParse(J).success){if(G++,G>1)return!1}return G===1},{message:"Value must match exactly one of the oneOf schemas"})}},dn4=class{apply(Y,X){let Q=X;if(Q.prefixItems&&Array.isArray(Q.prefixItems)){let G=Q.prefixItems.map((K)=>NY(K));return Y.refine((K)=>{if(!Array.isArray(K))return!0;for(let W=0;W<Math.min(K.length,G.length);W++)if(!kf(G[W],K[W]))return!1;if(K.length>G.length){if(typeof Q.items==="boolean"&&Q.items===!1)return!1;else if(Q.items&&typeof Q.items==="object"&&!Array.isArray(Q.items)){let W=NY(Q.items);for(let Z=G.length;Z<K.length;Z++)if(!kf(W,K[Z]))return!1}}return!0},{message:"Array does not match prefixItems schema"})}return Y}},pn4=class{apply(Y,X){let Q=X;if(!Q.properties&&!Q.required&&Q.additionalProperties!==!1)return Y;if(Y instanceof N.ZodObject||Y instanceof N.ZodRecord){let J={};if(Q.properties){for(let[G,K]of Object.entries(Q.properties))if(K!==void 0)J[G]=NY(K)}if(Q.required&&Array.isArray(Q.required)){let G=new Set(Q.required);for(let K of Object.keys(J))if(!G.has(K))J[K]=J[K].optional()}else for(let G of Object.keys(J))J[G]=J[G].optional();if(Q.additionalProperties===!1)return N.object(J);else return N.object(J).passthrough()}return Y.refine((J)=>{if(typeof J!=="object"||J===null||Array.isArray(J))return!0;if(Q.properties){for(let[G,K]of Object.entries(Q.properties))if(K!==void 0){if(Object.getOwnPropertyDescriptor(J,G)!==void 0){if(!NY(K).safeParse(J[G]).success)return!1}}}if(Q.required&&Array.isArray(Q.required)){for(let G of Q.required)if(Object.getOwnPropertyDescriptor(J,G)===void 0)return!1}if(Q.additionalProperties===!1&&Q.properties){let G=new Set(Object.keys(Q.properties));for(let K in J)if(!G.has(K))return!1}return!0},{message:"Object constraints validation failed"})}},cn4=class{apply(Y,X){if(!X.enum||X.enum.length===0)return Y;let Q=X.enum.filter((J)=>Array.isArray(J)||typeof J==="object"&&J!==null);if(Q.length===0)return Y;return Y.refine((J)=>{if(typeof J!=="object"||J===null)return!0;return Q.some((G)=>MP(J,G))},{message:"Value must match one of the enum values"})}},nn4=class{apply(Y,X){if(X.const===void 0)return Y;let Q=X.const;if(typeof Q!=="object"||Q===null)return Y;return Y.refine((J)=>MP(J,Q),{message:"Value must equal the const value"})}},in4=class{apply(Y,X){if(X.description)Y=Y.describe(X.description);return Y}},an4=class{apply(Y,X){var Q;let J=X;if(!((Q=J.required)==null?void 0:Q.includes("__proto__"))||X.type!==void 0)return Y;return N.any().refine((G)=>this.validateRequired(G,J.required),{message:"Missing required properties"})}validateRequired(Y,X){if(typeof Y!=="object"||Y===null||Array.isArray(Y))return!0;return X.every((Q)=>Object.prototype.hasOwnProperty.call(Y,Q))}},rn4=class{apply(Y,X){var Q;let J=X;if(J.contains===void 0)return Y;let G=NY(J.contains),K=(Q=J.minContains)!=null?Q:1,W=J.maxContains;return Y.refine((Z)=>{if(!Array.isArray(Z))return!0;let H=0;for(let F of Z)if(kf(G,F))H++;if(H<K)return!1;if(W!==void 0&&H>W)return!1;return!0},{message:"Array must contain required items matching the schema"})}},on4=class{apply(Y,X){let{default:Q}=X;if(Q===void 0)return Y;if(!Y.safeParse(Q).success)return Y;return Y.default(Q)}},sn4,tn4;var xF6=m(()=>{_9();_9();_9();_9();_9();_9();_9();_9();_9();_9();_9();_9();_9();_9();sn4=[new Dn4,new On4,new Un4,new Nn4,new Ln4,new Rn4,new yn4,new Mn4,new wn4,new Pn4,new An4,new Tn4,new En4,new In4,new Cn4,new vn4,new Sn4,new jn4,new kn4,new fn4,new hn4,new _n4],tn4=[new an4,new cn4,new nn4,new gn4,new mn4,new ln4,new dn4,new pn4,new rn4,new xn4,new un4,new on4,new in4]});class vY0{constructor(Y){this._url=Y}start(){if(this._socket)throw Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((Y,X)=>{this._socket=new WebSocket(this._url,en4),this._socket.onerror=(Q)=>{let J="error"in Q?Q.error:Error(`WebSocket error: ${JSON.stringify(Q)}`);X(J),this.onerror?.(J)},this._socket.onopen=()=>{Y()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=(Q)=>{let J;try{J=bQ.parse(JSON.parse(Q.data))}catch(G){this.onerror?.(G);return}this.onmessage?.(J)}})}async close(){this._socket?.close()}send(Y){return new Promise((X,Q)=>{if(!this._socket){Q(Error("Not connected"));return}this._socket?.send(JSON.stringify(Y)),X()})}}var en4="mcp";var uF6=m(()=>{xQ()});function Yi4(Y){let X=Y;if(!X||typeof X!=="object"||!("method"in X))return null;switch(X.method){case"initialize":{let Q=X?.params?.protocolVersion;if(!Q)return null;return{type:"emit",message:{result:{protocolVersion:Q,capabilities:{tools:{}},serverInfo:{name:"deco-chat-server",version:"1.0.0"}},jsonrpc:X.jsonrpc??"2.0",id:X.id}}}case"notifications/roots/list_changed":case"notifications/initialized":case"notifications/cancelled":case"notifications/progress":return{type:"suppress"};default:return null}}var _Y0;var gF6=m(()=>{zf();_Y0=class _Y0 extends jB{constructor(Y,X){super(Y,X)}send(Y,X){let Q=Yi4(Y);if(Q?.type==="emit")return this.onmessage?.(Q.message),Promise.resolve();if(Q?.type==="suppress")return Promise.resolve();return super.send(Y,X)}}});var mF6,lF6=async(Y,X,Q)=>{let J=Xi4(Y.connection,X,Q);if(!J)throw Error("Unknown MCP connection type");let G=new mF6({name:Y?.name??"MCP Client",version:"1.0.0"});return await G.connect(J),{client:G,callStreamableTool:(K,W,Z)=>{if(Y.connection.type!=="HTTP")throw Error("HTTP connection required");let H=new Headers(Q);if(!H.has("Authorization"))H.set("Authorization",`Bearer ${Y.connection.token}`);for(let[q,$]of Object.entries(Y.connection.headers??{}))H.set(q,$);let F=new URL(Y.connection.url),V=F.pathname.replace(/\/+$/,"")||"/";return F.pathname=`${V}/call-tool/${encodeURIComponent(K)}`,fetch(F.href,{method:"POST",redirect:"manual",body:JSON.stringify(W),headers:H,signal:Z})}}},Xi4=(Y,X,Q)=>{if(Y.type==="Websocket")return new vY0(new URL(Y.url));if(Y.type!=="SSE"&&Y.type!=="HTTP")return null;let G={...Y.token?{authorization:`Bearer ${Y.token}`}:{},...Q??{},..."headers"in Y?Y.headers||{}:{}};if(Y.type==="SSE"){let K={requestInit:{headers:G,signal:X}};if(Y.token)K.eventSourceInit={fetch:(W,Z)=>{return fetch(W,{...Z,headers:{...G,Accept:"text/event-stream"},signal:X})}};return new DP(new URL(Y.url),K)}return new _Y0(new URL(Y.url),{requestInit:{headers:G,signal:X,credentials:"include"}})};var dF6=m(()=>{sy();x90();uF6();xQ();gF6();mF6=class mF6 extends G3{constructor(Y,X){super(Y,X)}async listTools(Y,X){return await this.request({method:"tools/list",params:Y},yw,X)}}});function cF6(Y){let X=(Q)=>{if("connection"in Y)return lF6({connection:Y.connection},void 0,Q);return Y.client};return new Proxy({},{get(Q,J){if(J==="toJSON")return null;if(typeof J!=="string")throw Error("Name must be a string");if(J==="listTools")return Z;async function G(H,F=J){let V=Y?.debugId?.(),q=V?{"x-trace-debug-id":V}:void 0,{client:$,callStreamableTool:B}=await X(q);if(Y?.streamable?.[String(F)])return B(String(F),H);let{structuredContent:U,isError:D,content:L}=await $.callTool({name:String(F),arguments:H});if(D){let M=L?.[0]?.text,I=typeof M==="string"?Qi4(M):null,R=I?.code&&typeof Y?.getErrorByStatusCode==="function"?Y.getErrorByStatusCode(I.code,I.message,I.traceId):null;if(R)throw R;throw Error(`Tool ${String(F)} returned an error: ${JSON.stringify(U??L)}`)}return U}async function K(){let{client:H}=await X(),{tools:F}=await H.listTools();return F}async function W(){if(!("connection"in Y))return K();let H=Y.connection,F=JSON.stringify(H);try{if(!vf.has(F))vf.set(F,K());return await vf.get(F)}catch(V){console.error("Failed to list tools",V),vf.delete(F);return}}async function Z(){return(await W()??[]).map((F)=>pF6(F,G))}return G.asTool=async()=>{let F=(await W()??[]).find((V)=>V.name===J);if(!F)throw Error(`Tool ${J} not found`);return pF6(F,G)},G}})}var Qi4=(Y)=>{try{return JSON.parse(Y)}catch{return Y}},vf,pF6=(Y,X)=>{return{...Y,id:Y.name,inputSchema:Y.inputSchema?NY(Y.inputSchema):void 0,outputSchema:Y.outputSchema?NY(Y.outputSchema):void 0,execute:(Q)=>{return X(Q.context,Y.name)}}};var nF6=m(()=>{xF6();dF6();vf=new Map});function _f(Y){return cF6(Y)}var Ne1;var iF6=m(()=>{nF6();Ne1=new Proxy({},{get(Y,X){if(X==="toJSON")return null;if(X==="forConnection")return(Q)=>_f({connection:Q});return global[X]}})});function yf(Y){return{isImplementedBy:(X)=>{for(let Q of Y){let J=typeof Q.name==="string"?new RegExp(`^${Q.name}$`):Q.name,G=X.find((K)=>J.test(K.name));if(!G&&Q.opt)continue;if(!G)return!1}return!0}}}var zV=(Y)=>{return{...yf(Y),forClient:(X)=>{return _f({client:X,streamable:Y.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})},forConnection:(X)=>{return _f({connection:X,streamable:Y.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})}}};var wP=m(()=>{iF6()});var yY0,Ae1;var aF6=m(()=>{Hw();yY0=E4(Kw(),1),Ae1=yY0.createContext(null)});function nW(Y){return N.object({items:N.array(Y).describe("Array of collection items"),totalCount:N.number().int().min(0).optional().describe("Total number of matching items (if available)"),hasMore:N.boolean().optional().describe("Whether there are more items available")})}function AP(Y){return N.object({item:Y.nullable().describe("The retrieved item, or null if not found")})}function Wi4(Y){return N.object({data:Y.partial().describe("Data for the new entity (id may be auto-generated)")})}function Zi4(Y){return N.object({item:Y.describe("The created entity with generated id")})}function Ki4(Y){return N.object({id:N.string().describe("ID of the entity to update"),data:Y.partial().describe("Partial entity data to update")})}function Hi4(Y){return N.object({item:Y.describe("The updated entity")})}function EP(Y){return N.object({item:Y.describe("The deleted entity")})}function aB(Y,X,Q){let J=Y.toUpperCase(),G=Q?.readOnly??!1,K=[{name:`COLLECTION_${J}_LIST`,inputSchema:cW,outputSchema:nW(X)},{name:`COLLECTION_${J}_GET`,inputSchema:PP,outputSchema:AP(X)}];if(!G)K.push({name:`COLLECTION_${J}_CREATE`,inputSchema:Wi4(X),outputSchema:Zi4(X),opt:!0},{name:`COLLECTION_${J}_UPDATE`,inputSchema:Ki4(X),outputSchema:Hi4(X),opt:!0},{name:`COLLECTION_${J}_DELETE`,inputSchema:TP,outputSchema:EP(X),opt:!0});return K}var iB,Ji4,rF6,Gi4,cW,PP,TP;var nJ=m(()=>{Y6();iB=N.object({id:N.string().describe("Unique identifier for the entity"),title:N.string().describe("Human-readable title for the entity"),description:N.string().nullish().describe("Description of the entity"),created_at:N.string().datetime(),updated_at:N.string().datetime(),created_by:N.string().optional(),updated_by:N.string().optional()}),Ji4=N.object({field:N.array(N.string()),operator:N.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:N.unknown()}),rF6=N.lazy(()=>N.union([Ji4,N.object({operator:N.enum(["and","or","not"]),conditions:N.array(rF6)})])),Gi4=N.object({field:N.array(N.string()),direction:N.enum(["asc","desc"]),nulls:N.enum(["first","last"]).optional()}),cW=N.object({where:rF6.optional().describe("Filter expression"),orderBy:N.array(Gi4).optional().describe("Sort expressions"),limit:N.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:N.number().int().min(0).optional().describe("Number of items to skip")});PP=N.object({id:N.string().describe("ID of the entity to retrieve")});TP=N.object({id:N.string().describe("ID of the entity to delete")})});var Fi4,oF6,je1;var sF6=m(()=>{Y6();nJ();Fi4=N.object({id:N.string(),name:N.string(),description:N.string().optional(),inputSchema:N.record(N.string(),N.unknown()),outputSchema:N.record(N.string(),N.unknown()).optional()}),oF6=iB.extend({_meta:N.object({"io.decocms":N.object({id:N.string(),verified:N.boolean(),scopeName:N.string(),appName:N.string(),friendlyName:N.string().nullable().optional(),metadata:N.record(N.string(),N.unknown()).nullable().optional(),publishedAt:N.string().datetime().optional(),updatedAt:N.string().datetime().optional(),tools:N.array(Fi4).nullable().optional().describe("Available tools exposed by this app")}).optional()}).optional(),server:N.object({$schema:N.string().optional(),_meta:N.record(N.string(),N.unknown()).optional(),name:N.string().describe("The server name (scope/app)"),title:N.string().optional().describe("User-friendly title"),description:N.string().optional().describe("Server description"),icons:N.array(N.object({src:N.string(),mimeType:N.string().optional(),sizes:N.array(N.string()).optional(),theme:N.enum(["light","dark"]).optional()})).optional(),remotes:N.array(N.object({type:N.enum(["http","stdio","sse"]),url:N.string().optional(),headers:N.array(N.unknown()).optional()})).optional(),packages:N.array(N.unknown()).optional(),repository:N.object({url:N.string(),source:N.string().optional(),subfolder:N.string().optional()}).optional(),version:N.string().optional(),websiteUrl:N.string().optional()})}),je1=aB("registry_app",oF6,{readOnly:!0})});var tF6,eF6,YV6,XV6,QV6,Vi4;var JV6=m(()=>{Y6();wP();tF6=N.object({specversion:N.literal("1.0").describe("CloudEvents specification version"),id:N.string().describe("Unique identifier for this event (UUID recommended)"),source:N.string().describe("Connection ID of the event publisher"),type:N.string().describe("Event type (e.g., 'order.created', 'user.signup')"),time:N.string().datetime().optional().describe("Timestamp of when the event occurred (ISO 8601)"),subject:N.string().optional().describe("Subject/resource identifier (e.g., order ID, user ID)"),datacontenttype:N.string().optional().default("application/json").describe("Content type of the data attribute"),dataschema:N.string().url().optional().describe("URI to the schema for the data attribute"),data:N.unknown().optional().describe("Event payload (any JSON value)")}),eF6=N.object({events:N.array(tF6).min(1).describe("Batch of CloudEvents to process")}),YV6=N.object({success:N.boolean().optional().describe("Whether this event was processed successfully"),error:N.string().optional().describe("Error message for this event"),retryAfter:N.number().int().positive().optional().describe("Re-deliver this event after this many ms")}),XV6=N.object({success:N.boolean().optional().describe("Batch success - applies to events not in results"),error:N.string().optional().describe("Batch error message - applies to events not in results"),processedCount:N.number().int().min(0).optional().describe("Number of events successfully processed"),retryAfter:N.number().int().positive().optional().describe("Batch retryAfter - applies to events not in results"),results:N.record(N.string(),YV6).optional().describe("Per-event results keyed by event ID")}),QV6=[{name:"ON_EVENTS",inputSchema:eF6,outputSchema:XV6}],Vi4=zV(QV6)});var IP,CP,RP,SP,GV6,WV6,jP,kP,vP,_P,yP,fP,hP,bP,ZV6,qi4;var KV6=m(()=>{Y6();wP();IP=N.object({type:N.string().min(1).max(255).describe("Event type identifier"),subject:N.string().max(255).optional().describe("Subject/resource identifier (e.g., order ID)"),data:N.unknown().optional().describe("Event payload"),deliverAt:N.string().datetime().optional().describe("Scheduled delivery time (ISO 8601). Omit for immediate delivery."),cron:N.string().max(100).optional().describe("Cron expression for recurring delivery. Use EVENT_CANCEL to stop.")}),CP=N.object({id:N.string().describe("Unique event ID"),type:N.string().describe("Event type"),source:N.string().describe("Source connection ID"),time:N.string().describe("Event timestamp")}),RP=N.object({eventType:N.string().min(1).max(255).describe("Event type to subscribe to"),publisher:N.string().optional().describe("Filter events by publisher connection ID"),filter:N.string().max(1000).optional().describe("JSONPath filter expression on event data")}),SP=N.object({subscription:N.object({id:N.string().describe("Subscription ID"),connectionId:N.string().describe("Subscriber connection ID"),eventType:N.string().describe("Event type pattern"),publisher:N.string().nullable().describe("Publisher connection filter"),filter:N.string().nullable().describe("JSONPath filter expression"),enabled:N.boolean().describe("Whether subscription is enabled"),createdAt:N.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:N.string().datetime().describe("Updated timestamp (ISO 8601)")})}),GV6=N.object({eventType:N.string().min(1).max(255).describe("Event type to subscribe to"),publisher:N.string().optional().describe("Filter events by publisher connection ID"),filter:N.string().max(1000).optional().describe("JSONPath filter expression on event data")}),WV6=N.object({id:N.string().describe("Subscription ID"),connectionId:N.string().describe("Subscriber connection ID"),eventType:N.string().describe("Event type pattern"),publisher:N.string().nullable().describe("Publisher connection filter"),filter:N.string().nullable().describe("JSONPath filter expression"),enabled:N.boolean().describe("Whether subscription is enabled"),createdAt:N.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:N.string().datetime().describe("Updated timestamp (ISO 8601)")}),jP=N.object({subscriptions:N.array(GV6).describe("Desired subscriptions - system will create/update/delete to match")}),kP=N.object({created:N.number().int().min(0).describe("Number of subscriptions created"),updated:N.number().int().min(0).describe("Number of subscriptions with filter updated"),deleted:N.number().int().min(0).describe("Number of subscriptions removed"),unchanged:N.number().int().min(0).describe("Number of subscriptions unchanged"),subscriptions:N.array(WV6).describe("Current subscriptions after sync")}),vP=N.object({subscriptionId:N.string().describe("Subscription ID to remove")}),_P=N.object({success:N.boolean().describe("Whether unsubscribe was successful"),subscriptionId:N.string().describe("Subscription ID that was removed")}),yP=N.object({eventId:N.string().describe("Event ID to cancel")}),fP=N.object({success:N.boolean().describe("Whether cancellation was successful"),eventId:N.string().describe("Event ID that was cancelled")}),hP=N.object({eventId:N.string().describe("Event ID to acknowledge")}),bP=N.object({success:N.boolean().describe("Whether ACK was successful"),eventId:N.string().describe("Event ID that was acknowledged")}),ZV6=[{name:"EVENT_PUBLISH",inputSchema:IP,outputSchema:CP},{name:"EVENT_SUBSCRIBE",inputSchema:RP,outputSchema:SP},{name:"EVENT_UNSUBSCRIBE",inputSchema:vP,outputSchema:_P},{name:"EVENT_CANCEL",inputSchema:yP,outputSchema:fP},{name:"EVENT_ACK",inputSchema:hP,outputSchema:bP},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:jP,outputSchema:kP}],qi4=zV(ZV6)});var ue1,ge1,me1,le1,de1,pe1,ce1,ne1,ie1,ae1,re1,oe1;var HV6=m(()=>{Y6();ue1=N.object({prefix:N.string().optional().describe("Filter objects by prefix (e.g., 'folder/' for folder contents)"),maxKeys:N.number().optional().default(1000).describe("Maximum number of keys to return (default: 1000)"),continuationToken:N.string().optional().describe("Token for pagination from previous response"),delimiter:N.string().optional().describe("Delimiter for grouping keys (typically '/'). When set, commonPrefixes returns folder paths.")}),ge1=N.object({objects:N.array(N.object({key:N.string().describe("Object key/path"),size:N.number().describe("Object size in bytes"),lastModified:N.string().describe("Last modified timestamp"),etag:N.string().describe("Entity tag for the object")})),nextContinuationToken:N.string().optional().describe("Token for fetching next page of results"),isTruncated:N.boolean().describe("Whether there are more results available"),commonPrefixes:N.array(N.string()).optional().describe("Folder paths when delimiter is used (e.g., ['photos/2024/', 'photos/2025/'])")}),me1=N.object({key:N.string().describe("Object key/path to get metadata for")}),le1=N.object({contentType:N.string().optional().describe("MIME type of the object"),contentLength:N.number().describe("Size of the object in bytes"),lastModified:N.string().describe("Last modified timestamp"),etag:N.string().describe("Entity tag for the object"),metadata:N.record(N.string(),N.string()).optional().describe("Custom metadata key-value pairs")}),de1=N.object({key:N.string().describe("Object key/path to generate URL for"),expiresIn:N.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)")}),pe1=N.object({url:N.string().describe("Presigned URL for downloading the object"),expiresIn:N.number().describe("Expiration time in seconds that was used")}),ce1=N.object({key:N.string().describe("Object key/path for the upload"),expiresIn:N.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)"),contentType:N.string().optional().describe("MIME type for the object being uploaded")}),ne1=N.object({url:N.string().describe("Presigned URL for uploading the object"),expiresIn:N.number().describe("Expiration time in seconds that was used")}),ie1=N.object({key:N.string().describe("Object key/path to delete")}),ae1=N.object({success:N.boolean().describe("Whether the deletion was successful"),key:N.string().describe("The key that was deleted")}),re1=N.object({keys:N.array(N.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),oe1=N.object({deleted:N.array(N.string()).describe("Array of successfully deleted keys"),errors:N.array(N.object({key:N.string(),message:N.string()})).describe("Array of errors for failed deletions")})});var fY0=m(()=>{wP();aF6();sF6();JV6();KV6();HV6()});var $i4,zi4,FV6;var VV6=m(()=>{Y6();nJ();$i4=iB.extend({avatar:N.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:N.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:N.string().describe("Virtual MCP ID to use for this assistant"),model:N.object({id:N.string().describe("Model ID"),connectionId:N.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),zi4=aB("assistant",$i4),FV6=[...zi4]});var xP,iW,$V6,Bi4,Ui4,zV6,Di4,Oi4,Ni4,Li4,Mi4,wi4,BV6,Pi4,Ai4,Ti4,Ei4,Ii4,Ci4,Ri4,Si4,ji4,ki4,D08,vi4,O08,qV6,_i4,yi4,hY0,N08;var UV6=m(()=>{Y6();wP();nJ();xP=N.lazy(()=>N.union([N.null(),N.string(),N.number(),N.boolean(),N.record(N.string(),xP),N.array(xP)])),iW=N.record(N.string(),N.record(N.string(),xP)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),$V6=N.object({type:N.literal("text"),text:N.string().describe("The text content"),providerOptions:iW}),Bi4=N.object({type:N.literal("text"),text:N.string().describe("The text content"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),Ui4=N.string().describe("File data as URL string"),zV6=N.object({type:N.literal("file"),filename:N.string().optional().describe("Optional filename of the file"),data:Ui4,mediaType:N.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:iW}),Di4=N.object({type:N.literal("file"),mediaType:N.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:N.string().describe("Generated file data as base64 encoded string")}),Oi4=N.object({type:N.literal("reasoning"),text:N.string().describe("The reasoning text"),providerOptions:iW}),Ni4=N.object({type:N.literal("reasoning"),text:N.string().describe("The reasoning text"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),Li4=N.object({type:N.literal("tool-call"),toolCallId:N.string().describe("ID of the tool call, used to match with tool result"),toolName:N.string().describe("Name of the tool being called"),input:N.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:N.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:iW}),Mi4=N.object({type:N.literal("tool-call"),toolCallId:N.string().describe("ID of the tool call"),toolName:N.string().describe("Name of the tool being called"),input:N.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:N.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),wi4=N.union([N.object({type:N.literal("text"),value:N.string()}),N.object({type:N.literal("json"),value:xP}),N.object({type:N.literal("error-text"),value:N.string()}),N.object({type:N.literal("error-json"),value:xP}),N.object({type:N.literal("content"),value:N.array(N.union([N.object({type:N.literal("text"),text:N.string().describe("Text content")}),N.object({type:N.literal("media"),data:N.string().describe("Base-64 encoded media data"),mediaType:N.string().describe("IANA media type")})]))})]),BV6=N.object({type:N.literal("tool-result"),toolCallId:N.string().describe("ID of the tool call that this result is associated with"),toolName:N.string().describe("Name of the tool that generated this result"),output:wi4.describe("Result of the tool call"),result:N.unknown().describe("Unknown result of the tool call"),providerOptions:iW}),Pi4=N.object({type:N.literal("tool-result"),toolCallId:N.string().describe("ID of the tool call that this result is associated with"),toolName:N.string().describe("Name of the tool that generated this result"),result:N.any().describe("Result of the tool call (JSON-serializable)"),isError:N.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:N.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),Ai4=N.union([N.object({type:N.literal("source"),sourceType:N.literal("url"),id:N.string().describe("The ID of the source"),url:N.string().describe("The URL of the source"),title:N.string().optional().describe("The title of the source"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),N.object({type:N.literal("source"),sourceType:N.literal("document"),id:N.string().describe("The ID of the source"),mediaType:N.string().describe("IANA media type of the document (e.g., application/pdf)"),title:N.string().describe("The title of the document"),filename:N.string().optional().describe("Optional filename of the document"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")})]),Ti4=N.object({role:N.literal("system"),content:N.string().describe("System message content"),providerOptions:iW}),Ei4=N.object({role:N.literal("user"),content:N.array(N.union([$V6,zV6])).describe("User message content parts (text or file)"),providerOptions:iW}),Ii4=N.object({role:N.literal("assistant"),content:N.array(N.union([$V6,zV6,Oi4,Li4,BV6])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:iW}),Ci4=N.object({role:N.literal("tool"),content:N.array(BV6).describe("Tool message content (tool results)"),providerOptions:iW}),Ri4=N.union([Ti4,Ei4,Ii4,Ci4]),Si4=N.array(Ri4).describe("A list of messages forming the prompt"),ji4=N.object({prompt:Si4.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:N.number().optional().describe("Maximum number of tokens to generate"),temperature:N.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:N.number().optional().describe("Nucleus sampling parameter"),topK:N.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:N.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:N.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:N.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:N.array(N.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:N.union([N.object({type:N.literal("text")}),N.object({type:N.literal("json"),schema:N.any().optional().describe("JSON schema that the generated output should conform to"),name:N.string().optional().describe("Name of output that should be generated"),description:N.string().optional().describe("Description of the output that should be generated")})]).optional().describe("Response format. The output can either be text or JSON. Default is text"),tools:N.array(N.any()).optional().describe("The tools that are available for the model"),toolChoice:N.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:N.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:N.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:N.any().optional().describe("Additional provider-specific options")}),ki4=N.object({content:N.array(N.union([Bi4,Di4,Ni4,Mi4,Pi4,Ai4])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:N.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:N.looseObject({inputTokens:N.number().optional(),outputTokens:N.number().optional(),totalTokens:N.number().optional(),reasoningTokens:N.number().optional()}).describe("Usage information for the language model call"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata"),request:N.object({body:N.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:N.object({id:N.string().optional().describe("ID for the generated response"),timestamp:N.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:N.string().optional().describe("The ID of the response model that was used"),headers:N.record(N.string(),N.string()).optional().describe("Response headers"),body:N.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:N.array(N.any()).describe("Warnings for the call, e.g. unsupported settings")}),D08=N.object({stream:N.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:N.object({body:N.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:N.object({headers:N.record(N.string(),N.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),vi4=N.object({supportedUrls:N.record(N.string(),N.array(N.string())).describe("Supported URL patterns by media type for the provider")}),O08=N.object({modelId:N.string().describe("The ID of the model"),logo:N.string().nullable(),description:N.string().nullable(),capabilities:N.array(N.string()),limits:N.object({contextWindow:N.number(),maxOutputTokens:N.number()}).nullable(),costs:N.object({input:N.number(),output:N.number()}).nullable(),provider:N.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),qV6=N.object({modelId:N.string().describe("The ID of the model"),callOptions:ji4}),_i4=iB.extend({logo:N.string().nullable(),description:N.string().nullable(),capabilities:N.array(N.string()),limits:N.object({contextWindow:N.number(),maxOutputTokens:N.number()}).nullable(),costs:N.object({input:N.number(),output:N.number()}).nullable(),provider:N.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),yi4=aB("llm",_i4,{readOnly:!0}),hY0=[{name:"LLM_METADATA",inputSchema:N.object({modelId:N.string().describe("The ID of the model")}),outputSchema:vi4},{name:"LLM_DO_STREAM",inputSchema:qV6,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:qV6,outputSchema:ki4},...yi4],N08=zV(hY0)});function hi4(Y){let X=[],Q=0;while(Q<Y.length){let J=Y[Q];if(J==="%")X.push(".*");else if(J==="_")X.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))X.push("\\"+J);else X.push(J);Q++}return X.join("")}function V3(Y){return typeof Y==="string"||typeof Y==="number"}function ff(Y,X){if("conditions"in X){let{operator:Z,conditions:H}=X;switch(Z){case"and":return H.every((F)=>ff(Y,F));case"or":return H.some((F)=>ff(Y,F));case"not":return!H.every((F)=>ff(Y,F));default:return!0}}let{field:Q,operator:J,value:G}=X,K=Q.join("."),W=bY0(Y,K);switch(J){case"eq":return W===G;case"gt":return V3(W)&&V3(G)&&W>G;case"gte":return V3(W)&&V3(G)&&W>=G;case"lt":return V3(W)&&V3(G)&&W<G;case"lte":return V3(W)&&V3(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=hi4(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 bY0(Y,X){let Q=X.split("."),J=Y;for(let G of Q){if(J==null||typeof J!=="object")return;J=J[G]}return J}function bi4(Y,X){return[...Y].sort((Q,J)=>{for(let G of X){let K=G.field.join("."),W=bY0(Q,K),Z=bY0(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 fi4,xi4,ui4,xY0;var DV6=m(()=>{fY0();VV6();nJ();UV6();Y6();J4();Z3();fi4={LLM:hY0,ASSISTANTS:FV6};xi4=cW.extend({binding:N.union([N.object({}).passthrough(),N.string()]).optional()}),ui4=nW(cJ),xY0=X6({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",inputSchema:xi4,outputSchema:ui4,handler:async(Y,X)=>{await X.access.check();let Q=S6(X),J=Y.binding?typeof Y.binding==="string"?(()=>{let B=fi4[Y.binding.toUpperCase()];if(!B)throw Error(`Unknown binding: ${Y.binding}`);return B})():Y.binding:void 0,G=J?yf(J):void 0,W=(await X.storage.connections.list(Q.id)).filter((B)=>B.connection_type!=="VIRTUAL"),Z=G?await Promise.all(W.map(async(B)=>{if(!B.tools||B.tools.length===0)return null;return G.isImplementedBy(B.tools.map((D)=>({name:D.name,inputSchema:D.inputSchema,outputSchema:D.outputSchema})))?B:null})).then((B)=>B.filter((U)=>U!==null)):W;if(Y.where)Z=Z.filter((B)=>ff(B,Y.where));if(Y.orderBy&&Y.orderBy.length>0)Z=bi4(Z,Y.orderBy);let H=Z.length,F=Y.offset??0,V=Y.limit??100,q=Z.slice(F,F+V),$=F+V<H;return{items:q,totalCount:H,hasMore:$}}})});var gi4,uY0;var OV6=m(()=>{nJ();J4();Z3();gi4=AP(cJ),uY0=X6({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",inputSchema:PP,outputSchema:gi4,handler:async(Y,X)=>{let Q=S6(X);await X.access.check();let J=await X.storage.connections.findById(Y.id);if(!J||J.organization_id!==Q.id)return{item:null};return{item:J}}})});var hf=(Y,X)=>{if(X===null||X===void 0)return;let Q=Y.replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),J=X;for(let G of Q){if(J===null||J===void 0||typeof J!=="object")return;J=J[G]}return J};function NV6(Y){let X=Y.split("::");if(X.length!==2||!X[0]||!X[1])throw Error(`Invalid scope format: ${Y}. Expected format: "KEY::SCOPE"`);return X}function mi4(Y){let X=Y.split("::");if(X.length!==2||!X[0]||!X[1])return null;return X}function li4(Y){if(typeof Y==="object"&&Y!==null&&"value"in Y){let X=Y.value;if(typeof X==="string")return X}return null}function di4(Y,X){let Q={};if(!Y||!X)return Q;for(let J of X){if(J==="*"){Q["*"]=["*"];continue}let G=mi4(J);if(!G)continue;let[K,W]=G,Z=hf(K,Y),H=li4(Z);if(H){if(!Q[H])Q[H]=[];Q[H].push(W)}}return Q}function LV6(Y,X){let Q=di4(Y,X);return new Set(Object.keys(Q).filter((J)=>J!=="*"))}var MV6=()=>{};class gY0{db;vault;constructor(Y,X){this.db=Y;this.vault=X}async get(Y){let X=await this.db.selectFrom("downstream_tokens").selectAll().where("connectionId","=",Y).executeTakeFirst();if(!X)return null;return this.decryptToken(X)}async upsert(Y){let X=new Date().toISOString(),Q=await this.vault.encrypt(Y.accessToken),J=Y.refreshToken?await this.vault.encrypt(Y.refreshToken):null,G=Y.clientSecret?await this.vault.encrypt(Y.clientSecret):null;return await this.db.transaction().execute(async(K)=>{let W=await K.selectFrom("downstream_tokens").select(["id","createdAt"]).where("connectionId","=",Y.connectionId).executeTakeFirst();if(W)return await K.updateTable("downstream_tokens").set({accessToken:Q,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,updatedAt:X}).where("id","=",W.id).execute(),{id:W.id,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:W.createdAt,updatedAt:X,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint};let Z=vB("dtok");return await K.insertInto("downstream_tokens").values({id:Z,connectionId:Y.connectionId,accessToken:Q,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,createdAt:X,updatedAt:X}).execute(),{id:Z,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:X,updatedAt:X,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint}})}async delete(Y){await this.db.deleteFrom("downstream_tokens").where("connectionId","=",Y).execute()}isExpired(Y,X=0){if(!Y.expiresAt)return!1;let J=(Y.expiresAt instanceof Date?Y.expiresAt:new Date(Y.expiresAt)).getTime();if(Number.isNaN(J))return!0;return J-X<Date.now()}async decryptToken(Y){let X=await this.vault.decrypt(Y.accessToken),Q=Y.refreshToken?await this.vault.decrypt(Y.refreshToken):null,J=Y.clientSecret?await this.vault.decrypt(Y.clientSecret):null;return{id:Y.id,connectionId:Y.connectionId,accessToken:X,refreshToken:Q,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Y.createdAt,updatedAt:Y.updatedAt,clientId:Y.clientId,clientSecret:J,tokenEndpoint:Y.tokenEndpoint}}}var wV6=m(()=>{Lf()});async function ni4(Y,X,Q,J){for(let K of X){if(K==="*")continue;let[W]=NV6(K),Z=hf(W,Y);if(Z===void 0||Z===null)throw Error(`Scope references key "${W}" but it's not present in state`)}let G=LV6(Y,X);for(let K of G){if(K.endsWith("_self"))continue;let W=await J.storage.connections.findById(K);if(!W||W.organization_id!==Q)throw Error(`Referenced connection not found: ${K}`);try{await J.access.check(K)}catch(Z){throw Error(`Access denied to referenced connection: ${K}. ${Z.message}`)}}}var pi4,ci4,mY0;var PV6=m(()=>{MV6();wV6();Y6();J4();Tf();Z3();pi4=N.object({id:N.string().describe("ID of the connection to update"),data:$36.describe("Partial connection data to update")}),ci4=N.object({item:cJ.describe("The updated connection entity")});mY0=X6({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update an existing MCP connection in the organization",inputSchema:pi4,outputSchema:ci4,handler:async(Y,X)=>{$6(X);let Q=S6(X);if(await X.access.check(),!x8(X))throw Error("User ID required to update connection");let{id:G,data:K}=Y,W=await X.storage.connections.findById(G);if(!W||W.organization_id!==Q.id)throw Error("Connection not found in organization");let Z=K.connection_type??W.connection_type,H=K.connection_url??W.connection_url;if(Z==="VIRTUAL"){let L=Of(H);if(!L)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let M=await X.storage.virtualMcps.findById(L);if(!M)throw Error(`Virtual MCP not found: ${L}`);if(M.organization_id!==Q.id)throw Error("Virtual MCP does not belong to the current organization");H=Nf(L)}let F=K.configuration_state??W.configuration_state,V=K.configuration_scopes??W.configuration_scopes??[];if(K.configuration_state!==void 0||K.configuration_scopes!==void 0){if(K.configuration_state!==void 0)F=K.configuration_state;else if(F===null)F={};if(K.configuration_scopes!==void 0)V=K.configuration_scopes??[];if(V.length>0&&F)await ni4(F,V,Q.id,X)}let q=K.connection_token??W.connection_token;if(!q)try{let M=await new gY0(X.db,X.vault).get(G);if(M?.accessToken)q=M.accessToken}catch{}let $=await mB({id:W.id,title:K.title??W.title,connection_type:Z,connection_url:H,connection_token:q,connection_headers:K.connection_headers??W.connection_headers}).catch(()=>null),B=$?.length?$:null,U={...K,connection_url:H,tools:B,configuration_state:F,configuration_scopes:V},D=await X.storage.connections.update(G,U);if((K.configuration_state!==void 0||K.configuration_scopes!==void 0)&&F&&V.length>0)try{await(await X.createMCPProxy(G)).client.callTool({name:"ON_MCP_CONFIGURATION",arguments:{state:F,scopes:V}})}catch(L){console.error("Failed to invoke ON_MCP_CONFIGURATION callback",L)}return{item:D}}})});var lY0;var AV6=m(()=>{nJ();J4();Z3();lY0=X6({name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete a connection",inputSchema:TP,outputSchema:EP(cJ),handler:async(Y,X)=>{$6(X);let Q=S6(X);await X.access.check();let J=await X.storage.connections.findById(Y.id);if(!J)throw Error(`Connection not found: ${Y.id}`);if(J.organization_id!==Q.id)throw Error("Connection not found in organization");return await X.storage.connections.delete(Y.id),{item:J}}})});var dY0;var TV6=m(()=>{Y6();J4();dY0=X6({name:"CONNECTION_TEST",description:"Test connection health and latency",inputSchema:N.object({id:N.string()}),outputSchema:N.object({id:N.string(),healthy:N.boolean(),latencyMs:N.number()}),handler:async(Y,X)=>{let Q=S6(X);await X.access.check();let J=await X.storage.connections.findById(Y.id);if(!J||J.organization_id!==Q.id)throw Error("Connection not found");let G=await X.storage.connections.testConnection(Y.id);return{id:Y.id,...G}}})});var EV6=m(()=>{bF6();DV6();OV6();PV6();AV6();TV6()});import{sql as t4}from"kysely";function IV6(Y){if(Y===null||Y===void 0)return"NULL";if(typeof Y==="number")return String(Y);if(typeof Y==="boolean")return Y?"TRUE":"FALSE";if(typeof Y==="string")return`'${Y.replace(/'/g,"''")}'`;if(Y instanceof Date)return`'${Y.toISOString()}'`;return`'${JSON.stringify(Y).replace(/'/g,"''")}'`}function ri4(Y,X){let Q=Y;for(let G=X.length;G>=1;G--){let K=`$${G}`;if(Q.includes(K))Q=Q.replaceAll(K,IV6(X[G-1]))}let J=[];for(let G=0;G<Q.length;G++)if(Q[G]==="?")J.push(G);for(let G=Math.min(J.length,X.length)-1;G>=0;G--){let K=J[G],W=IV6(X[G]);Q=Q.slice(0,K)+W+Q.slice(K+1)}return Q}function CV6(Y){return Y.replace(/-/g,"_")}function si4(Y){return`app_${CV6(Y)}`}function ti4(Y){return`app_role_${CV6(Y)}`}function ei4(Y){if(Y instanceof Error){let X=Y.message.toLowerCase(),Q=Y.code;return Q==="3F000"||Q==="42704"||X.includes("schema")&&X.includes("does not exist")||X.includes("role")&&X.includes("does not exist")}return!1}async function Ya4(Y,X,Q){if(await t4`CREATE SCHEMA IF NOT EXISTS ${t4.id(X)}`.execute(Y),!(await t4`
407
+ ${X.stack}`;return G}}catch{}if(typeof X.toString==="function")try{let G=X.toString();if(G!=="[object Object]")return G}catch{}let J=Object.keys(X);if(J.length>0)return`Object with keys: ${J.join(", ")}`;return"[object Object]"}if(typeof Y==="string")return Y;if(typeof Y==="number"||typeof Y==="boolean")return String(Y);if(typeof Y==="function")return`[Function: ${Y.name||"anon"}]`;if(typeof Y==="symbol")return Y.toString();if(typeof Y==="bigint")return Y.toString();try{return String(Y)}catch{return"Unknown value (could not convert to string)"}}function cB(Y,X){switch(typeof X){case"string":return Y.newString(X);case"number":return Y.newNumber(X);case"boolean":return X?Y.true:Y.false;case"undefined":return Y.undefined;case"object":{if(X===null)return Y.null;if(Array.isArray(X)){let J=Y.newArray();return X.forEach((G,K)=>{let W=cB(Y,G);try{Y.setProp(J,String(K),W)}finally{W.dispose?.()}}),J}let Q=Y.newObject();for(let[J,G]of Object.entries(X)){let K=cB(Y,G);try{Y.setProp(Q,J,K)}finally{K.dispose?.()}}return Q}case"function":{let Q=`__hostFn_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return Y.newFunction(Q,(...G)=>{try{let K=G.map((Z)=>Y.dump(Z)),W=X(...K);if(W&&typeof W.then==="function"){let Z=Y.newPromise();return W.then((H)=>{try{let F=cB(Y,H);Z.resolve(F),F.dispose(),Y.runtime.executePendingJobs()}catch(F){let V=pB(F),q=Y.newString(`Promise resolution error: ${V}`);Z.reject(q),q.dispose(),Y.runtime.executePendingJobs()}}).catch((H)=>{let F=pB(H),V=Y.newString(`Promise rejection: ${F}`);Z.reject(V),V.dispose(),Y.runtime.executePendingJobs()}),Z.handle}return cB(Y,W)}catch(K){let W=pB(K);return Y.newString(`HostFunctionError: ${W}`)}finally{G.forEach((K)=>K.dispose())}})}case"bigint":return Y.newString(X.toString());case"symbol":return Y.newString(X.toString());default:try{return Y.newString(String(X))}catch{return Y.undefined}}}var TF6=()=>{};function IF6(Y){let X=Y.runtime.executePendingJobs(100);try{if("unwrap"in X&&typeof X.unwrap==="function")X.unwrap()}finally{if("dispose"in X&&typeof X.dispose==="function")X.dispose()}}async function EF6(Y,X,Q){let J=Date.now(),G=Y.resolvePromise(X);while(!0){IF6(Y);let K=await Promise.race([G,Kn4(0).then(()=>null)]);if(K!==null)return K;if(Date.now()-J>Q)throw Error(`Timed out after ${Q}ms while awaiting a QuickJS promise`)}}async function CY0({tools:Y,code:X,timeoutMs:Q}){let W=[];try{let J=await PF6({memoryLimitBytes:33554432,stackSizeBytes:524288});const G=mf(W,J.newContext({interruptAfterMs:Q}),0);const K=mf(W,rH6(G),0);try{let V=G.evalCode(X,"index.mjs",{strip:!0,strict:!0,type:"module"}),q=G.unwrapResult(V),$=cB(G,Y);G.setProp(G.global,"tools",$);let B=G.runtime.hasPendingJob()?G.unwrapResult(await EF6(G,q,Q)):q;if(B!==q)q.dispose();let U=G.getProp(B,"default"),D=G.typeof(U);if(D!=="function")return{error:`Code must export default a function (tools). Got ${D}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:K.logs};let L=G.callFunction(U,G.undefined,$),M=G.unwrapResult(L),I=await EF6(G,M,Q),R=G.unwrapResult(I);if(G.runtime.hasPendingJob())IF6(G);return{returnValue:G.dump(R),consoleLogs:K.logs}}catch(V){return console.log(V),{error:pB(V),consoleLogs:K.logs}}}catch(Z){var H=Z,F=1}finally{EX0(W,H,F)}}var Kn4=(Y)=>new Promise((X)=>setTimeout(X,Y));var CF6=m(()=>{AF6();TF6()});var RF6=m(()=>{CF6()});async function Hn4(Y,X){let Q;if(Y.tool_selection_mode==="exclusion"){let G=(await X.storage.connections.list(Y.organization_id)).filter((W)=>W.status==="active"),K=new Map;for(let W of Y.connections)K.set(W.connection_id,{selectedTools:W.selected_tools,selectedResources:W.selected_resources,selectedPrompts:W.selected_prompts});Q=[];for(let W of G){let Z=K.get(W.id);if(Z===void 0)Q.push({connection:W,selectedTools:null,selectedResources:null,selectedPrompts:null});else if((Z.selectedTools===null||Z.selectedTools.length===0)&&(Z.selectedResources===null||Z.selectedResources.length===0)&&(Z.selectedPrompts===null||Z.selectedPrompts.length===0));else Q.push({connection:W,selectedTools:Z.selectedTools,selectedResources:Z.selectedResources,selectedPrompts:Z.selectedPrompts})}}else{let J=Y.connections.map((K)=>K.connection_id),G=[];for(let K of J){let W=await X.storage.connections.findById(K);if(W&&W.status==="active")G.push(W)}Q=G.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}})}return Q}async function SF6(Y,X){return(await X.storage.connections.list(Y)).filter((J)=>J.status==="active").map((J)=>({connection:J,selectedTools:null,selectedResources:null,selectedPrompts:null}))}async function Fn4(Y,X,Q){let J=await If.create(Y,Q),G=await J.mapSettled(async(V,q)=>{try{let B=(await V.proxy.client.listTools()).tools;if(X==="exclusion"){if(V.selectedTools&&V.selectedTools.length>0){let U=new Set(V.selectedTools);B=B.filter((D)=>!U.has(D.name))}}else if(V.selectedTools&&V.selectedTools.length>0){let U=new Set(V.selectedTools);B=B.filter((D)=>U.has(D.name))}return{connectionId:q,connectionTitle:V.connection.title,tools:B}}catch($){return console.error(`[code-execution] Failed to list tools for connection ${q}:`,$),null}}),K=new Set,W=[],Z=new Map,H=new Set;for(let V of G){if(V.status!=="fulfilled"||!V.value)continue;let{connectionId:q,connectionTitle:$,tools:B}=V.value;H.add($);for(let U of B){if(K.has(U.name))continue;K.add(U.name),W.push({...U,_meta:{connectionId:q,connectionTitle:$}}),Z.set(U.name,{connectionId:q,originalName:U.name})}}return{tools:W,callTool:async(V,q)=>{let $=Z.get(V);if(!$)return{content:[{type:"text",text:`Tool not found: ${V}`}],isError:!0};let B=J.get($.connectionId);if(!B)return{content:[{type:"text",text:`Connection not found for tool: ${V}`}],isError:!0};return await B.proxy.client.callTool({name:$.originalName,arguments:q})},categories:Array.from(H).sort()}}async function nB(Y){let X=S6(Y),Q,J="inclusion";if(Y.connectionId){let G=await Y.storage.virtualMcps.findById(Y.connectionId);if(G)Q=await Hn4(G,Y),J=G.tool_selection_mode;else Q=await SF6(X.id,Y)}else Q=await SF6(X.id,Y);return Fn4(Q,J,Y)}function Vn4(Y){return Y.toLowerCase().split(/[\s_\-./]+/).filter((X)=>X.length>=2)}function qn4(Y,X){let Q=0,J=X.name.toLowerCase(),G=(X.description??"").toLowerCase(),K=X._meta.connectionTitle.toLowerCase();for(let W of Y){if(J===W)Q+=10;else if(J.includes(W))Q+=3;if(G.includes(W))Q+=2;if(K.includes(W))Q+=1}return Q}function jF6(Y,X,Q){let J=Vn4(Y);if(J.length===0)return X.slice(0,Q);return X.map((G)=>({tool:G,score:qn4(J,G)})).filter((G)=>G.score>0).sort((G,K)=>K.score-G.score).slice(0,Q).map((G)=>G.tool)}function kF6(Y,X){let Q=new Map(X.map((G)=>[G.name,G]));return{tools:Y.map((G)=>Q.get(G)).filter((G)=>G!==void 0).map((G)=>({name:G.name,description:G.description,connection:G._meta.connectionTitle,inputSchema:G.inputSchema,outputSchema:G.outputSchema})),notFound:Y.filter((G)=>!Q.has(G))}}async function vF6(Y,X,Q){let J=Object.fromEntries(X.tools.map((G)=>[G.name,async(K)=>X.callTool(G.name,K??{})]));return CY0({code:Y,tools:J,timeoutMs:Q})}var jf=m(()=>{RF6()});var RY0;var _F6=m(()=>{J4();NP();jf();RY0=X6({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:dH6,outputSchema:pH6,handler:async(Y,X)=>{$6(X),S6(X),await X.access.check();let Q=await nB(X),J=jF6(Y.query,Q.tools,Y.limit);return{query:Y.query,results:J.map((G)=>({name:G.name,description:G.description,connection:G._meta.connectionTitle})),totalAvailable:Q.tools.length}}})});var SY0;var yF6=m(()=>{J4();NP();jf();SY0=X6({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:cH6,outputSchema:nH6,handler:async(Y,X)=>{$6(X),S6(X),await X.access.check();let Q=await nB(X);return kF6(Y.tools,Q.tools)}})});var jY0;var fF6=m(()=>{J4();NP();jf();jY0=X6({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:iH6,outputSchema:aH6,handler:async(Y,X)=>{$6(X),S6(X),await X.access.check();let Q=await nB(X);return await vF6(Y.code,Q,Y.timeoutMs)}})});var hF6=m(()=>{_F6();yF6();fF6();NP()});var zn4,Bn4,kY0;var bF6=m(()=>{E90();Y6();J4();Tf();Z3();zn4=N.object({data:q36.describe("Data for the new connection (id is auto-generated if not provided)")}),Bn4=N.object({item:cJ.describe("The created connection entity")}),kY0=X6({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",inputSchema:zn4,outputSchema:Bn4,handler:async(Y,X)=>{$6(X);let Q=S6(X);await X.access.check();let J=x8(X);if(!J)throw Error("User ID required to create connection");let G={...Y.data,organization_id:Q.id,created_by:J};if(G.connection_type==="VIRTUAL"){let H=Of(G.connection_url);if(!H)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let F=await X.storage.virtualMcps.findById(H);if(!F)throw Error(`Virtual MCP not found: ${H}`);if(F.organization_id!==Q.id)throw Error("Virtual MCP does not belong to the current organization");G.connection_url=Nf(H)}let K=await mB({id:`pending-${Date.now()}`,title:G.title,connection_type:G.connection_type,connection_url:G.connection_url,connection_token:G.connection_token,connection_headers:G.connection_headers}).catch(()=>null),W=K?.length?K:null,Z=await X.storage.connections.create({...G,tools:W});return await X.eventBus.publish(Q.id,FP.SELF(Q.id),{type:"connection.created",data:Z}),{item:Z}}})});function MP(Y,X){if(Y===X)return!0;if(Y==null||X==null)return Y===X;if(typeof Y!==typeof X)return!1;if(Array.isArray(Y)&&Array.isArray(X)){if(Y.length!==X.length)return!1;return Y.every((Q,J)=>MP(Q,X[J]))}if(typeof Y==="object"&&typeof X==="object"){let Q=Object.keys(Y),J=Object.keys(X);if(Q.length!==J.length)return!1;return Q.every((G)=>J.includes(G)&&MP(Y[G],X[G]))}return!1}function bn4(){return(Y)=>{if(!Array.isArray(Y))return!0;let X=[];return Y.every((Q)=>{if(X.some((G)=>MP(Q,G)))return!1;return X.push(Q),!0})}}function kf(Y,X){return Y.safeParse(X).success}function NY(Y){if(typeof Y==="boolean")return Y?N.any():N.never();let X={};for(let G of sn4)G.apply(X,Y);let Q=[];if(X.string!==!1)Q.push(X.string||N.string());if(X.number!==!1)Q.push(X.number||N.number());if(X.boolean!==!1)Q.push(X.boolean||N.boolean());if(X.null!==!1)Q.push(X.null||N.null());if(X.array!==!1)Q.push(X.array||N.array(N.any()));if(X.tuple!==!1&&X.tuple!==void 0)Q.push(X.tuple);if(X.object!==!1)if(X.object)Q.push(X.object);else{let G=N.custom((K)=>{return typeof K==="object"&&K!==null&&!Array.isArray(K)},"Must be an object, not an array");Q.push(G)}if(X.file!==!1&&X.file!==void 0)Q.push(X.file);let J;if(Q.length===0)J=N.never();else if(Q.length===1)J=Q[0];else if(!Object.keys(Y).some((K)=>K!=="$schema"&&K!=="title"&&K!=="description"))J=N.any();else J=N.union(Q);for(let G of tn4)J=G.apply(J,Y);return J}var Un4=class{apply(Y,X){if(!X.type)return;let Q=Array.isArray(X.type)?X.type:[X.type],J=new Set(Q);if(!J.has("string"))Y.string=!1;if(!J.has("number")&&!J.has("integer"))Y.number=!1;if(!J.has("boolean"))Y.boolean=!1;if(!J.has("null"))Y.null=!1;if(!J.has("array"))Y.array=!1;if(!J.has("object"))Y.object=!1;if(J.has("integer")&&Y.number!==!1){let G=Y.number||N.number();if(G instanceof N.ZodNumber)Y.number=G.int()}}},Dn4=class{apply(Y,X){if(X.const===void 0)return;let Q=X.const;if(Y.string=!1,Y.number=!1,Y.boolean=!1,Y.null=!1,Y.array=!1,Y.object=!1,typeof Q==="string")Y.string=N.literal(Q);else if(typeof Q==="number")Y.number=N.literal(Q);else if(typeof Q==="boolean")Y.boolean=N.literal(Q);else if(Q===null)Y.null=N.null();else if(Array.isArray(Q))Y.array=void 0;else if(typeof Q==="object")Y.object=void 0}},On4=class{apply(Y,X){if(!X.enum)return;if(X.enum.length===0){if(!X.type)Y.string=!1,Y.number=!1,Y.boolean=!1,Y.null=!1,Y.array=!1,Y.object=!1;return}let Q={string:X.enum.filter((J)=>typeof J==="string"),number:X.enum.filter((J)=>typeof J==="number"),boolean:X.enum.filter((J)=>typeof J==="boolean"),null:X.enum.filter((J)=>J===null),array:X.enum.filter((J)=>Array.isArray(J)),object:X.enum.filter((J)=>typeof J==="object"&&J!==null&&!Array.isArray(J))};Y.string=this.createTypeSchema(Q.string,"string"),Y.number=this.createTypeSchema(Q.number,"number"),Y.boolean=this.createTypeSchema(Q.boolean,"boolean"),Y.null=Q.null.length>0?N.null():!1,Y.array=Q.array.length>0?void 0:!1,Y.object=Q.object.length>0?void 0:!1}createTypeSchema(Y,X){if(Y.length===0)return!1;if(Y.length===1)return N.literal(Y[0]);if(X==="string")return N.enum(Y);if(X==="number"){let[Q,J,...G]=Y;return N.union([N.literal(Q),N.literal(J),...G.map((K)=>N.literal(K))])}if(X==="boolean")return N.union([N.literal(!0),N.literal(!1)]);return!1}},Nn4=class{apply(Y,X){let Q=X;if(Q.type==="string"&&Q.format==="binary"&&Q.contentEncoding==="binary"){let J=N.file();if(Q.minLength!==void 0)J=J.min(Q.minLength);if(Q.maxLength!==void 0)J=J.max(Q.maxLength);if(Q.contentMediaType!==void 0)J=J.mime(Q.contentMediaType);Y.file=J,Y.string=!1}}},Ln4=class{apply(Y,X){let Q=X;if(X.type===void 0&&(Q.minLength!==void 0||Q.maxLength!==void 0||Q.pattern!==void 0)){if(Y.string===void 0)Y.string=N.string()}}},Mn4=class{apply(Y,X){let Q=X;if(Q.minLength===void 0)return;if(Y.string!==!1){let J=Y.string||N.string();if(J instanceof N.ZodString)Y.string=J.refine((G)=>{return Array.from(G).length>=Q.minLength},{message:`String must be at least ${Q.minLength} characters long`})}}},wn4=class{apply(Y,X){let Q=X;if(Q.maxLength===void 0)return;if(Y.string!==!1){let J=Y.string||N.string();if(J instanceof N.ZodString)Y.string=J.refine((G)=>{return Array.from(G).length<=Q.maxLength},{message:`String must be at most ${Q.maxLength} characters long`})}}},Pn4=class{apply(Y,X){let Q=X;if(!Q.pattern)return;if(Y.string!==!1){let J=Y.string||N.string();if(J instanceof N.ZodString){let G=new RegExp(Q.pattern);Y.string=J.regex(G)}}}},An4=class{apply(Y,X){let Q=X;if(Q.minimum===void 0)return;if(Y.number!==!1){let J=Y.number||N.number();if(J instanceof N.ZodNumber)Y.number=J.min(Q.minimum)}}},Tn4=class{apply(Y,X){let Q=X;if(Q.maximum===void 0)return;if(Y.number!==!1){let J=Y.number||N.number();if(J instanceof N.ZodNumber)Y.number=J.max(Q.maximum)}}},En4=class{apply(Y,X){let Q=X;if(Q.exclusiveMinimum===void 0)return;if(Y.number!==!1){let J=Y.number||N.number();if(J instanceof N.ZodNumber)if(typeof Q.exclusiveMinimum==="number")Y.number=J.gt(Q.exclusiveMinimum);else Y.number=!1}}},In4=class{apply(Y,X){let Q=X;if(Q.exclusiveMaximum===void 0)return;if(Y.number!==!1){let J=Y.number||N.number();if(J instanceof N.ZodNumber)if(typeof Q.exclusiveMaximum==="number")Y.number=J.lt(Q.exclusiveMaximum);else Y.number=!1}}},Cn4=class{apply(Y,X){let Q=X;if(Q.multipleOf===void 0)return;if(Y.number!==!1){let J=Y.number||N.number();if(J instanceof N.ZodNumber)Y.number=J.refine((G)=>{if(Q.multipleOf===0)return!1;let K=G/Q.multipleOf,W=Math.round(K),Z=Math.min(Math.abs(G)*Number.EPSILON*10,Math.abs(Q.multipleOf)*Number.EPSILON*10);return Math.abs(K-W)<=Z/Math.abs(Q.multipleOf)},{message:`Must be a multiple of ${Q.multipleOf}`})}}},Rn4=class{apply(Y,X){let Q=X;if(X.type===void 0&&(Q.minItems!==void 0||Q.maxItems!==void 0||Q.items!==void 0||Q.prefixItems!==void 0)){if(Y.array===void 0)Y.array=N.array(N.any())}}},Sn4=class{apply(Y,X){let Q=X;if(Q.minItems===void 0)return;if(Y.array!==!1)Y.array=(Y.array||N.array(N.any())).min(Q.minItems)}},jn4=class{apply(Y,X){let Q=X;if(Q.maxItems===void 0)return;if(Y.array!==!1)Y.array=(Y.array||N.array(N.any())).max(Q.maxItems)}},kn4=class{apply(Y,X){let Q=X;if(Y.array===!1)return;if(Array.isArray(Q.items))Y.array=Y.array||N.array(N.any());else if(Q.items&&typeof Q.items!=="boolean"&&!Q.prefixItems){let J=NY(Q.items),G=N.array(J);if(Y.array&&Y.array instanceof N.ZodArray){let K=Y.array._def;if(K.checks)K.checks.forEach((W)=>{if(W._zod&&W._zod.def){let Z=W._zod.def;if(Z.check==="min_length"&&Z.minimum!==void 0)G=G.min(Z.minimum);else if(Z.check==="max_length"&&Z.maximum!==void 0)G=G.max(Z.maximum)}})}Y.array=G}else if(typeof Q.items==="boolean"&&Q.items===!1)if(!Q.prefixItems)Y.array=N.array(N.any()).max(0);else Y.array=Y.array||N.array(N.any());else if(typeof Q.items==="boolean"&&Q.items===!0)Y.array=Y.array||N.array(N.any());else if(Q.prefixItems)Y.array=Y.array||N.array(N.any())}},vn4=class{apply(Y,X){if(X.type!=="array")return;let Q=X;if(!Array.isArray(Q.items))return;if(Y.array===!1)return;let J=Q.items.map((K)=>NY(K)),G;if(J.length===0)G=N.tuple([]);else G=N.tuple(J);if(Q.minItems!==void 0&&Q.minItems>J.length)G=!1;if(Q.maxItems!==void 0&&Q.maxItems<J.length)G=!1;Y.tuple=G,Y.array=!1}},_n4=class{apply(Y,X){let Q=X;if(Y.object===!1)return;if(Q.properties||Q.required||Q.additionalProperties!==void 0)Y.object=Y.object||N.object({}).passthrough()}},yn4=class{apply(Y,X){let Q=X;if(X.type===void 0&&(Q.maxProperties!==void 0||Q.minProperties!==void 0)){if(Y.object===void 0)Y.object=N.object({}).passthrough()}}},fn4=class{apply(Y,X){let Q=X;if(Q.maxProperties===void 0)return;if(Y.object!==!1){let J=Y.object||N.object({}).passthrough();Y.object=J.refine((G)=>Object.keys(G).length<=Q.maxProperties,{message:`Object must have at most ${Q.maxProperties} properties`})}}},hn4=class{apply(Y,X){let Q=X;if(Q.minProperties===void 0)return;if(Y.object!==!1){let J=Y.object||N.object({}).passthrough();Y.object=J.refine((G)=>Object.keys(G).length>=Q.minProperties,{message:`Object must have at least ${Q.minProperties} properties`})}}},xn4=class{apply(Y,X){if(!X.not)return Y;let Q=NY(X.not);return Y.refine((J)=>!kf(Q,J),{message:"Value must not match the 'not' schema"})}},un4=class{apply(Y,X){if(X.uniqueItems!==!0)return Y;return Y.refine(bn4(),{message:"Array items must be unique"})}},gn4=class{apply(Y,X){if(!X.allOf||X.allOf.length===0)return Y;return X.allOf.map((J)=>NY(J)).reduce((J,G)=>N.intersection(J,G),Y)}},mn4=class{apply(Y,X){if(!X.anyOf||X.anyOf.length===0)return Y;let Q=X.anyOf.length===1?NY(X.anyOf[0]):N.union([NY(X.anyOf[0]),NY(X.anyOf[1]),...X.anyOf.slice(2).map((J)=>NY(J))]);return N.intersection(Y,Q)}},ln4=class{apply(Y,X){if(!X.oneOf||X.oneOf.length===0)return Y;let Q=X.oneOf.map((J)=>NY(J));return Y.refine((J)=>{let G=0;for(let K of Q)if(K.safeParse(J).success){if(G++,G>1)return!1}return G===1},{message:"Value must match exactly one of the oneOf schemas"})}},dn4=class{apply(Y,X){let Q=X;if(Q.prefixItems&&Array.isArray(Q.prefixItems)){let G=Q.prefixItems.map((K)=>NY(K));return Y.refine((K)=>{if(!Array.isArray(K))return!0;for(let W=0;W<Math.min(K.length,G.length);W++)if(!kf(G[W],K[W]))return!1;if(K.length>G.length){if(typeof Q.items==="boolean"&&Q.items===!1)return!1;else if(Q.items&&typeof Q.items==="object"&&!Array.isArray(Q.items)){let W=NY(Q.items);for(let Z=G.length;Z<K.length;Z++)if(!kf(W,K[Z]))return!1}}return!0},{message:"Array does not match prefixItems schema"})}return Y}},pn4=class{apply(Y,X){let Q=X;if(!Q.properties&&!Q.required&&Q.additionalProperties!==!1)return Y;if(Y instanceof N.ZodObject||Y instanceof N.ZodRecord){let J={};if(Q.properties){for(let[G,K]of Object.entries(Q.properties))if(K!==void 0)J[G]=NY(K)}if(Q.required&&Array.isArray(Q.required)){let G=new Set(Q.required);for(let K of Object.keys(J))if(!G.has(K))J[K]=J[K].optional()}else for(let G of Object.keys(J))J[G]=J[G].optional();if(Q.additionalProperties===!1)return N.object(J);else return N.object(J).passthrough()}return Y.refine((J)=>{if(typeof J!=="object"||J===null||Array.isArray(J))return!0;if(Q.properties){for(let[G,K]of Object.entries(Q.properties))if(K!==void 0){if(Object.getOwnPropertyDescriptor(J,G)!==void 0){if(!NY(K).safeParse(J[G]).success)return!1}}}if(Q.required&&Array.isArray(Q.required)){for(let G of Q.required)if(Object.getOwnPropertyDescriptor(J,G)===void 0)return!1}if(Q.additionalProperties===!1&&Q.properties){let G=new Set(Object.keys(Q.properties));for(let K in J)if(!G.has(K))return!1}return!0},{message:"Object constraints validation failed"})}},cn4=class{apply(Y,X){if(!X.enum||X.enum.length===0)return Y;let Q=X.enum.filter((J)=>Array.isArray(J)||typeof J==="object"&&J!==null);if(Q.length===0)return Y;return Y.refine((J)=>{if(typeof J!=="object"||J===null)return!0;return Q.some((G)=>MP(J,G))},{message:"Value must match one of the enum values"})}},nn4=class{apply(Y,X){if(X.const===void 0)return Y;let Q=X.const;if(typeof Q!=="object"||Q===null)return Y;return Y.refine((J)=>MP(J,Q),{message:"Value must equal the const value"})}},in4=class{apply(Y,X){if(X.description)Y=Y.describe(X.description);return Y}},an4=class{apply(Y,X){var Q;let J=X;if(!((Q=J.required)==null?void 0:Q.includes("__proto__"))||X.type!==void 0)return Y;return N.any().refine((G)=>this.validateRequired(G,J.required),{message:"Missing required properties"})}validateRequired(Y,X){if(typeof Y!=="object"||Y===null||Array.isArray(Y))return!0;return X.every((Q)=>Object.prototype.hasOwnProperty.call(Y,Q))}},rn4=class{apply(Y,X){var Q;let J=X;if(J.contains===void 0)return Y;let G=NY(J.contains),K=(Q=J.minContains)!=null?Q:1,W=J.maxContains;return Y.refine((Z)=>{if(!Array.isArray(Z))return!0;let H=0;for(let F of Z)if(kf(G,F))H++;if(H<K)return!1;if(W!==void 0&&H>W)return!1;return!0},{message:"Array must contain required items matching the schema"})}},on4=class{apply(Y,X){let{default:Q}=X;if(Q===void 0)return Y;if(!Y.safeParse(Q).success)return Y;return Y.default(Q)}},sn4,tn4;var xF6=m(()=>{_9();_9();_9();_9();_9();_9();_9();_9();_9();_9();_9();_9();_9();_9();sn4=[new Dn4,new On4,new Un4,new Nn4,new Ln4,new Rn4,new yn4,new Mn4,new wn4,new Pn4,new An4,new Tn4,new En4,new In4,new Cn4,new vn4,new Sn4,new jn4,new kn4,new fn4,new hn4,new _n4],tn4=[new an4,new cn4,new nn4,new gn4,new mn4,new ln4,new dn4,new pn4,new rn4,new xn4,new un4,new on4,new in4]});class vY0{constructor(Y){this._url=Y}start(){if(this._socket)throw Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((Y,X)=>{this._socket=new WebSocket(this._url,en4),this._socket.onerror=(Q)=>{let J="error"in Q?Q.error:Error(`WebSocket error: ${JSON.stringify(Q)}`);X(J),this.onerror?.(J)},this._socket.onopen=()=>{Y()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=(Q)=>{let J;try{J=bQ.parse(JSON.parse(Q.data))}catch(G){this.onerror?.(G);return}this.onmessage?.(J)}})}async close(){this._socket?.close()}send(Y){return new Promise((X,Q)=>{if(!this._socket){Q(Error("Not connected"));return}this._socket?.send(JSON.stringify(Y)),X()})}}var en4="mcp";var uF6=m(()=>{xQ()});function Yi4(Y){let X=Y;if(!X||typeof X!=="object"||!("method"in X))return null;switch(X.method){case"initialize":{let Q=X?.params?.protocolVersion;if(!Q)return null;return{type:"emit",message:{result:{protocolVersion:Q,capabilities:{tools:{}},serverInfo:{name:"deco-chat-server",version:"1.0.0"}},jsonrpc:X.jsonrpc??"2.0",id:X.id}}}case"notifications/roots/list_changed":case"notifications/initialized":case"notifications/cancelled":case"notifications/progress":return{type:"suppress"};default:return null}}var _Y0;var gF6=m(()=>{zf();_Y0=class _Y0 extends jB{constructor(Y,X){super(Y,X)}send(Y,X){let Q=Yi4(Y);if(Q?.type==="emit")return this.onmessage?.(Q.message),Promise.resolve();if(Q?.type==="suppress")return Promise.resolve();return super.send(Y,X)}}});var mF6,lF6=async(Y,X,Q)=>{let J=Xi4(Y.connection,X,Q);if(!J)throw Error("Unknown MCP connection type");let G=new mF6({name:Y?.name??"MCP Client",version:"1.0.0"});return await G.connect(J),{client:G,callStreamableTool:(K,W,Z)=>{if(Y.connection.type!=="HTTP")throw Error("HTTP connection required");let H=new Headers(Q);if(!H.has("Authorization"))H.set("Authorization",`Bearer ${Y.connection.token}`);for(let[q,$]of Object.entries(Y.connection.headers??{}))H.set(q,$);let F=new URL(Y.connection.url),V=F.pathname.replace(/\/+$/,"")||"/";return F.pathname=`${V}/call-tool/${encodeURIComponent(K)}`,fetch(F.href,{method:"POST",redirect:"manual",body:JSON.stringify(W),headers:H,signal:Z})}}},Xi4=(Y,X,Q)=>{if(Y.type==="Websocket")return new vY0(new URL(Y.url));if(Y.type!=="SSE"&&Y.type!=="HTTP")return null;let G={...Y.token?{authorization:`Bearer ${Y.token}`}:{},...Q??{},..."headers"in Y?Y.headers||{}:{}};if(Y.type==="SSE"){let K={requestInit:{headers:G,signal:X}};if(Y.token)K.eventSourceInit={fetch:(W,Z)=>{return fetch(W,{...Z,headers:{...G,Accept:"text/event-stream"},signal:X})}};return new DP(new URL(Y.url),K)}return new _Y0(new URL(Y.url),{requestInit:{headers:G,signal:X,credentials:"include"}})};var dF6=m(()=>{sy();x90();uF6();xQ();gF6();mF6=class mF6 extends G3{constructor(Y,X){super(Y,X)}async listTools(Y,X){return await this.request({method:"tools/list",params:Y},yw,X)}}});function cF6(Y){let X=(Q)=>{if("connection"in Y)return lF6({connection:Y.connection},void 0,Q);return Y.client};return new Proxy({},{get(Q,J){if(J==="toJSON")return null;if(typeof J!=="string")throw Error("Name must be a string");if(J==="listTools")return Z;async function G(H,F=J){let V=Y?.debugId?.(),q=V?{"x-trace-debug-id":V}:void 0,{client:$,callStreamableTool:B}=await X(q);if(Y?.streamable?.[String(F)])return B(String(F),H);let{structuredContent:U,isError:D,content:L}=await $.callTool({name:String(F),arguments:H});if(D){let M=L?.[0]?.text,I=typeof M==="string"?Qi4(M):null,R=I?.code&&typeof Y?.getErrorByStatusCode==="function"?Y.getErrorByStatusCode(I.code,I.message,I.traceId):null;if(R)throw R;throw Error(`Tool ${String(F)} returned an error: ${JSON.stringify(U??L)}`)}return U}async function K(){let{client:H}=await X(),{tools:F}=await H.listTools();return F}async function W(){if(!("connection"in Y))return K();let H=Y.connection,F=JSON.stringify(H);try{if(!vf.has(F))vf.set(F,K());return await vf.get(F)}catch(V){console.error("Failed to list tools",V),vf.delete(F);return}}async function Z(){return(await W()??[]).map((F)=>pF6(F,G))}return G.asTool=async()=>{let F=(await W()??[]).find((V)=>V.name===J);if(!F)throw Error(`Tool ${J} not found`);return pF6(F,G)},G}})}var Qi4=(Y)=>{try{return JSON.parse(Y)}catch{return Y}},vf,pF6=(Y,X)=>{return{...Y,id:Y.name,inputSchema:Y.inputSchema?NY(Y.inputSchema):void 0,outputSchema:Y.outputSchema?NY(Y.outputSchema):void 0,execute:(Q)=>{return X(Q.context,Y.name)}}};var nF6=m(()=>{xF6();dF6();vf=new Map});function _f(Y){return cF6(Y)}var Le1;var iF6=m(()=>{nF6();Le1=new Proxy({},{get(Y,X){if(X==="toJSON")return null;if(X==="forConnection")return(Q)=>_f({connection:Q});return global[X]}})});function yf(Y){return{isImplementedBy:(X)=>{for(let Q of Y){let J=typeof Q.name==="string"?new RegExp(`^${Q.name}$`):Q.name,G=X.find((K)=>J.test(K.name));if(!G&&Q.opt)continue;if(!G)return!1}return!0}}}var zV=(Y)=>{return{...yf(Y),forClient:(X)=>{return _f({client:X,streamable:Y.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})},forConnection:(X)=>{return _f({connection:X,streamable:Y.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})}}};var wP=m(()=>{iF6()});var yY0,Te1;var aF6=m(()=>{Hw();yY0=E4(Kw(),1),Te1=yY0.createContext(null)});function nW(Y){return N.object({items:N.array(Y).describe("Array of collection items"),totalCount:N.number().int().min(0).optional().describe("Total number of matching items (if available)"),hasMore:N.boolean().optional().describe("Whether there are more items available")})}function AP(Y){return N.object({item:Y.nullable().describe("The retrieved item, or null if not found")})}function Wi4(Y){return N.object({data:Y.partial().describe("Data for the new entity (id may be auto-generated)")})}function Zi4(Y){return N.object({item:Y.describe("The created entity with generated id")})}function Ki4(Y){return N.object({id:N.string().describe("ID of the entity to update"),data:Y.partial().describe("Partial entity data to update")})}function Hi4(Y){return N.object({item:Y.describe("The updated entity")})}function EP(Y){return N.object({item:Y.describe("The deleted entity")})}function aB(Y,X,Q){let J=Y.toUpperCase(),G=Q?.readOnly??!1,K=[{name:`COLLECTION_${J}_LIST`,inputSchema:cW,outputSchema:nW(X)},{name:`COLLECTION_${J}_GET`,inputSchema:PP,outputSchema:AP(X)}];if(!G)K.push({name:`COLLECTION_${J}_CREATE`,inputSchema:Wi4(X),outputSchema:Zi4(X),opt:!0},{name:`COLLECTION_${J}_UPDATE`,inputSchema:Ki4(X),outputSchema:Hi4(X),opt:!0},{name:`COLLECTION_${J}_DELETE`,inputSchema:TP,outputSchema:EP(X),opt:!0});return K}var iB,Ji4,rF6,Gi4,cW,PP,TP;var nJ=m(()=>{Y6();iB=N.object({id:N.string().describe("Unique identifier for the entity"),title:N.string().describe("Human-readable title for the entity"),description:N.string().nullish().describe("Description of the entity"),created_at:N.string().datetime(),updated_at:N.string().datetime(),created_by:N.string().optional(),updated_by:N.string().optional()}),Ji4=N.object({field:N.array(N.string()),operator:N.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:N.unknown()}),rF6=N.lazy(()=>N.union([Ji4,N.object({operator:N.enum(["and","or","not"]),conditions:N.array(rF6)})])),Gi4=N.object({field:N.array(N.string()),direction:N.enum(["asc","desc"]),nulls:N.enum(["first","last"]).optional()}),cW=N.object({where:rF6.optional().describe("Filter expression"),orderBy:N.array(Gi4).optional().describe("Sort expressions"),limit:N.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:N.number().int().min(0).optional().describe("Number of items to skip")});PP=N.object({id:N.string().describe("ID of the entity to retrieve")});TP=N.object({id:N.string().describe("ID of the entity to delete")})});var Fi4,oF6,ke1;var sF6=m(()=>{Y6();nJ();Fi4=N.object({id:N.string(),name:N.string(),description:N.string().optional(),inputSchema:N.record(N.string(),N.unknown()),outputSchema:N.record(N.string(),N.unknown()).optional()}),oF6=iB.extend({_meta:N.object({"io.decocms":N.object({id:N.string(),verified:N.boolean(),scopeName:N.string(),appName:N.string(),friendlyName:N.string().nullable().optional(),metadata:N.record(N.string(),N.unknown()).nullable().optional(),publishedAt:N.string().datetime().optional(),updatedAt:N.string().datetime().optional(),tools:N.array(Fi4).nullable().optional().describe("Available tools exposed by this app")}).optional()}).optional(),server:N.object({$schema:N.string().optional(),_meta:N.record(N.string(),N.unknown()).optional(),name:N.string().describe("The server name (scope/app)"),title:N.string().optional().describe("User-friendly title"),description:N.string().optional().describe("Server description"),icons:N.array(N.object({src:N.string(),mimeType:N.string().optional(),sizes:N.array(N.string()).optional(),theme:N.enum(["light","dark"]).optional()})).optional(),remotes:N.array(N.object({type:N.enum(["http","stdio","sse"]),url:N.string().optional(),headers:N.array(N.unknown()).optional()})).optional(),packages:N.array(N.unknown()).optional(),repository:N.object({url:N.string(),source:N.string().optional(),subfolder:N.string().optional()}).optional(),version:N.string().optional(),websiteUrl:N.string().optional()})}),ke1=aB("registry_app",oF6,{readOnly:!0})});var tF6,eF6,YV6,XV6,QV6,Vi4;var JV6=m(()=>{Y6();wP();tF6=N.object({specversion:N.literal("1.0").describe("CloudEvents specification version"),id:N.string().describe("Unique identifier for this event (UUID recommended)"),source:N.string().describe("Connection ID of the event publisher"),type:N.string().describe("Event type (e.g., 'order.created', 'user.signup')"),time:N.string().datetime().optional().describe("Timestamp of when the event occurred (ISO 8601)"),subject:N.string().optional().describe("Subject/resource identifier (e.g., order ID, user ID)"),datacontenttype:N.string().optional().default("application/json").describe("Content type of the data attribute"),dataschema:N.string().url().optional().describe("URI to the schema for the data attribute"),data:N.unknown().optional().describe("Event payload (any JSON value)")}),eF6=N.object({events:N.array(tF6).min(1).describe("Batch of CloudEvents to process")}),YV6=N.object({success:N.boolean().optional().describe("Whether this event was processed successfully"),error:N.string().optional().describe("Error message for this event"),retryAfter:N.number().int().positive().optional().describe("Re-deliver this event after this many ms")}),XV6=N.object({success:N.boolean().optional().describe("Batch success - applies to events not in results"),error:N.string().optional().describe("Batch error message - applies to events not in results"),processedCount:N.number().int().min(0).optional().describe("Number of events successfully processed"),retryAfter:N.number().int().positive().optional().describe("Batch retryAfter - applies to events not in results"),results:N.record(N.string(),YV6).optional().describe("Per-event results keyed by event ID")}),QV6=[{name:"ON_EVENTS",inputSchema:eF6,outputSchema:XV6}],Vi4=zV(QV6)});var IP,CP,RP,SP,GV6,WV6,jP,kP,vP,_P,yP,fP,hP,bP,ZV6,qi4;var KV6=m(()=>{Y6();wP();IP=N.object({type:N.string().min(1).max(255).describe("Event type identifier"),subject:N.string().max(255).optional().describe("Subject/resource identifier (e.g., order ID)"),data:N.unknown().optional().describe("Event payload"),deliverAt:N.string().datetime().optional().describe("Scheduled delivery time (ISO 8601). Omit for immediate delivery."),cron:N.string().max(100).optional().describe("Cron expression for recurring delivery. Use EVENT_CANCEL to stop.")}),CP=N.object({id:N.string().describe("Unique event ID"),type:N.string().describe("Event type"),source:N.string().describe("Source connection ID"),time:N.string().describe("Event timestamp")}),RP=N.object({eventType:N.string().min(1).max(255).describe("Event type to subscribe to"),publisher:N.string().optional().describe("Filter events by publisher connection ID"),filter:N.string().max(1000).optional().describe("JSONPath filter expression on event data")}),SP=N.object({subscription:N.object({id:N.string().describe("Subscription ID"),connectionId:N.string().describe("Subscriber connection ID"),eventType:N.string().describe("Event type pattern"),publisher:N.string().nullable().describe("Publisher connection filter"),filter:N.string().nullable().describe("JSONPath filter expression"),enabled:N.boolean().describe("Whether subscription is enabled"),createdAt:N.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:N.string().datetime().describe("Updated timestamp (ISO 8601)")})}),GV6=N.object({eventType:N.string().min(1).max(255).describe("Event type to subscribe to"),publisher:N.string().optional().describe("Filter events by publisher connection ID"),filter:N.string().max(1000).optional().describe("JSONPath filter expression on event data")}),WV6=N.object({id:N.string().describe("Subscription ID"),connectionId:N.string().describe("Subscriber connection ID"),eventType:N.string().describe("Event type pattern"),publisher:N.string().nullable().describe("Publisher connection filter"),filter:N.string().nullable().describe("JSONPath filter expression"),enabled:N.boolean().describe("Whether subscription is enabled"),createdAt:N.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:N.string().datetime().describe("Updated timestamp (ISO 8601)")}),jP=N.object({subscriptions:N.array(GV6).describe("Desired subscriptions - system will create/update/delete to match")}),kP=N.object({created:N.number().int().min(0).describe("Number of subscriptions created"),updated:N.number().int().min(0).describe("Number of subscriptions with filter updated"),deleted:N.number().int().min(0).describe("Number of subscriptions removed"),unchanged:N.number().int().min(0).describe("Number of subscriptions unchanged"),subscriptions:N.array(WV6).describe("Current subscriptions after sync")}),vP=N.object({subscriptionId:N.string().describe("Subscription ID to remove")}),_P=N.object({success:N.boolean().describe("Whether unsubscribe was successful"),subscriptionId:N.string().describe("Subscription ID that was removed")}),yP=N.object({eventId:N.string().describe("Event ID to cancel")}),fP=N.object({success:N.boolean().describe("Whether cancellation was successful"),eventId:N.string().describe("Event ID that was cancelled")}),hP=N.object({eventId:N.string().describe("Event ID to acknowledge")}),bP=N.object({success:N.boolean().describe("Whether ACK was successful"),eventId:N.string().describe("Event ID that was acknowledged")}),ZV6=[{name:"EVENT_PUBLISH",inputSchema:IP,outputSchema:CP},{name:"EVENT_SUBSCRIBE",inputSchema:RP,outputSchema:SP},{name:"EVENT_UNSUBSCRIBE",inputSchema:vP,outputSchema:_P},{name:"EVENT_CANCEL",inputSchema:yP,outputSchema:fP},{name:"EVENT_ACK",inputSchema:hP,outputSchema:bP},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:jP,outputSchema:kP}],qi4=zV(ZV6)});var ge1,me1,le1,de1,pe1,ce1,ne1,ie1,ae1,re1,oe1,se1;var HV6=m(()=>{Y6();ge1=N.object({prefix:N.string().optional().describe("Filter objects by prefix (e.g., 'folder/' for folder contents)"),maxKeys:N.number().optional().default(1000).describe("Maximum number of keys to return (default: 1000)"),continuationToken:N.string().optional().describe("Token for pagination from previous response"),delimiter:N.string().optional().describe("Delimiter for grouping keys (typically '/'). When set, commonPrefixes returns folder paths.")}),me1=N.object({objects:N.array(N.object({key:N.string().describe("Object key/path"),size:N.number().describe("Object size in bytes"),lastModified:N.string().describe("Last modified timestamp"),etag:N.string().describe("Entity tag for the object")})),nextContinuationToken:N.string().optional().describe("Token for fetching next page of results"),isTruncated:N.boolean().describe("Whether there are more results available"),commonPrefixes:N.array(N.string()).optional().describe("Folder paths when delimiter is used (e.g., ['photos/2024/', 'photos/2025/'])")}),le1=N.object({key:N.string().describe("Object key/path to get metadata for")}),de1=N.object({contentType:N.string().optional().describe("MIME type of the object"),contentLength:N.number().describe("Size of the object in bytes"),lastModified:N.string().describe("Last modified timestamp"),etag:N.string().describe("Entity tag for the object"),metadata:N.record(N.string(),N.string()).optional().describe("Custom metadata key-value pairs")}),pe1=N.object({key:N.string().describe("Object key/path to generate URL for"),expiresIn:N.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)")}),ce1=N.object({url:N.string().describe("Presigned URL for downloading the object"),expiresIn:N.number().describe("Expiration time in seconds that was used")}),ne1=N.object({key:N.string().describe("Object key/path for the upload"),expiresIn:N.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)"),contentType:N.string().optional().describe("MIME type for the object being uploaded")}),ie1=N.object({url:N.string().describe("Presigned URL for uploading the object"),expiresIn:N.number().describe("Expiration time in seconds that was used")}),ae1=N.object({key:N.string().describe("Object key/path to delete")}),re1=N.object({success:N.boolean().describe("Whether the deletion was successful"),key:N.string().describe("The key that was deleted")}),oe1=N.object({keys:N.array(N.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),se1=N.object({deleted:N.array(N.string()).describe("Array of successfully deleted keys"),errors:N.array(N.object({key:N.string(),message:N.string()})).describe("Array of errors for failed deletions")})});var fY0=m(()=>{wP();aF6();sF6();JV6();KV6();HV6()});var $i4,zi4,FV6;var VV6=m(()=>{Y6();nJ();$i4=iB.extend({avatar:N.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:N.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:N.string().describe("Virtual MCP ID to use for this assistant"),model:N.object({id:N.string().describe("Model ID"),connectionId:N.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),zi4=aB("assistant",$i4),FV6=[...zi4]});var xP,iW,$V6,Bi4,Ui4,zV6,Di4,Oi4,Ni4,Li4,Mi4,wi4,BV6,Pi4,Ai4,Ti4,Ei4,Ii4,Ci4,Ri4,Si4,ji4,ki4,O08,vi4,N08,qV6,_i4,yi4,hY0,L08;var UV6=m(()=>{Y6();wP();nJ();xP=N.lazy(()=>N.union([N.null(),N.string(),N.number(),N.boolean(),N.record(N.string(),xP),N.array(xP)])),iW=N.record(N.string(),N.record(N.string(),xP)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),$V6=N.object({type:N.literal("text"),text:N.string().describe("The text content"),providerOptions:iW}),Bi4=N.object({type:N.literal("text"),text:N.string().describe("The text content"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),Ui4=N.string().describe("File data as URL string"),zV6=N.object({type:N.literal("file"),filename:N.string().optional().describe("Optional filename of the file"),data:Ui4,mediaType:N.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:iW}),Di4=N.object({type:N.literal("file"),mediaType:N.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:N.string().describe("Generated file data as base64 encoded string")}),Oi4=N.object({type:N.literal("reasoning"),text:N.string().describe("The reasoning text"),providerOptions:iW}),Ni4=N.object({type:N.literal("reasoning"),text:N.string().describe("The reasoning text"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),Li4=N.object({type:N.literal("tool-call"),toolCallId:N.string().describe("ID of the tool call, used to match with tool result"),toolName:N.string().describe("Name of the tool being called"),input:N.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:N.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:iW}),Mi4=N.object({type:N.literal("tool-call"),toolCallId:N.string().describe("ID of the tool call"),toolName:N.string().describe("Name of the tool being called"),input:N.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:N.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),wi4=N.union([N.object({type:N.literal("text"),value:N.string()}),N.object({type:N.literal("json"),value:xP}),N.object({type:N.literal("error-text"),value:N.string()}),N.object({type:N.literal("error-json"),value:xP}),N.object({type:N.literal("content"),value:N.array(N.union([N.object({type:N.literal("text"),text:N.string().describe("Text content")}),N.object({type:N.literal("media"),data:N.string().describe("Base-64 encoded media data"),mediaType:N.string().describe("IANA media type")})]))})]),BV6=N.object({type:N.literal("tool-result"),toolCallId:N.string().describe("ID of the tool call that this result is associated with"),toolName:N.string().describe("Name of the tool that generated this result"),output:wi4.describe("Result of the tool call"),result:N.unknown().describe("Unknown result of the tool call"),providerOptions:iW}),Pi4=N.object({type:N.literal("tool-result"),toolCallId:N.string().describe("ID of the tool call that this result is associated with"),toolName:N.string().describe("Name of the tool that generated this result"),result:N.any().describe("Result of the tool call (JSON-serializable)"),isError:N.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:N.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),Ai4=N.union([N.object({type:N.literal("source"),sourceType:N.literal("url"),id:N.string().describe("The ID of the source"),url:N.string().describe("The URL of the source"),title:N.string().optional().describe("The title of the source"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),N.object({type:N.literal("source"),sourceType:N.literal("document"),id:N.string().describe("The ID of the source"),mediaType:N.string().describe("IANA media type of the document (e.g., application/pdf)"),title:N.string().describe("The title of the document"),filename:N.string().optional().describe("Optional filename of the document"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")})]),Ti4=N.object({role:N.literal("system"),content:N.string().describe("System message content"),providerOptions:iW}),Ei4=N.object({role:N.literal("user"),content:N.array(N.union([$V6,zV6])).describe("User message content parts (text or file)"),providerOptions:iW}),Ii4=N.object({role:N.literal("assistant"),content:N.array(N.union([$V6,zV6,Oi4,Li4,BV6])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:iW}),Ci4=N.object({role:N.literal("tool"),content:N.array(BV6).describe("Tool message content (tool results)"),providerOptions:iW}),Ri4=N.union([Ti4,Ei4,Ii4,Ci4]),Si4=N.array(Ri4).describe("A list of messages forming the prompt"),ji4=N.object({prompt:Si4.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:N.number().optional().describe("Maximum number of tokens to generate"),temperature:N.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:N.number().optional().describe("Nucleus sampling parameter"),topK:N.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:N.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:N.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:N.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:N.array(N.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:N.union([N.object({type:N.literal("text")}),N.object({type:N.literal("json"),schema:N.any().optional().describe("JSON schema that the generated output should conform to"),name:N.string().optional().describe("Name of output that should be generated"),description:N.string().optional().describe("Description of the output that should be generated")})]).optional().describe("Response format. The output can either be text or JSON. Default is text"),tools:N.array(N.any()).optional().describe("The tools that are available for the model"),toolChoice:N.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:N.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:N.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:N.any().optional().describe("Additional provider-specific options")}),ki4=N.object({content:N.array(N.union([Bi4,Di4,Ni4,Mi4,Pi4,Ai4])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:N.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:N.looseObject({inputTokens:N.number().optional(),outputTokens:N.number().optional(),totalTokens:N.number().optional(),reasoningTokens:N.number().optional()}).describe("Usage information for the language model call"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata"),request:N.object({body:N.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:N.object({id:N.string().optional().describe("ID for the generated response"),timestamp:N.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:N.string().optional().describe("The ID of the response model that was used"),headers:N.record(N.string(),N.string()).optional().describe("Response headers"),body:N.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:N.array(N.any()).describe("Warnings for the call, e.g. unsupported settings")}),O08=N.object({stream:N.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:N.object({body:N.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:N.object({headers:N.record(N.string(),N.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),vi4=N.object({supportedUrls:N.record(N.string(),N.array(N.string())).describe("Supported URL patterns by media type for the provider")}),N08=N.object({modelId:N.string().describe("The ID of the model"),logo:N.string().nullable(),description:N.string().nullable(),capabilities:N.array(N.string()),limits:N.object({contextWindow:N.number(),maxOutputTokens:N.number()}).nullable(),costs:N.object({input:N.number(),output:N.number()}).nullable(),provider:N.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),qV6=N.object({modelId:N.string().describe("The ID of the model"),callOptions:ji4}),_i4=iB.extend({logo:N.string().nullable(),description:N.string().nullable(),capabilities:N.array(N.string()),limits:N.object({contextWindow:N.number(),maxOutputTokens:N.number()}).nullable(),costs:N.object({input:N.number(),output:N.number()}).nullable(),provider:N.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),yi4=aB("llm",_i4,{readOnly:!0}),hY0=[{name:"LLM_METADATA",inputSchema:N.object({modelId:N.string().describe("The ID of the model")}),outputSchema:vi4},{name:"LLM_DO_STREAM",inputSchema:qV6,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:qV6,outputSchema:ki4},...yi4],L08=zV(hY0)});function hi4(Y){let X=[],Q=0;while(Q<Y.length){let J=Y[Q];if(J==="%")X.push(".*");else if(J==="_")X.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))X.push("\\"+J);else X.push(J);Q++}return X.join("")}function V3(Y){return typeof Y==="string"||typeof Y==="number"}function ff(Y,X){if("conditions"in X){let{operator:Z,conditions:H}=X;switch(Z){case"and":return H.every((F)=>ff(Y,F));case"or":return H.some((F)=>ff(Y,F));case"not":return!H.every((F)=>ff(Y,F));default:return!0}}let{field:Q,operator:J,value:G}=X,K=Q.join("."),W=bY0(Y,K);switch(J){case"eq":return W===G;case"gt":return V3(W)&&V3(G)&&W>G;case"gte":return V3(W)&&V3(G)&&W>=G;case"lt":return V3(W)&&V3(G)&&W<G;case"lte":return V3(W)&&V3(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=hi4(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 bY0(Y,X){let Q=X.split("."),J=Y;for(let G of Q){if(J==null||typeof J!=="object")return;J=J[G]}return J}function bi4(Y,X){return[...Y].sort((Q,J)=>{for(let G of X){let K=G.field.join("."),W=bY0(Q,K),Z=bY0(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 fi4,xi4,ui4,xY0;var DV6=m(()=>{fY0();VV6();nJ();UV6();Y6();J4();Z3();fi4={LLM:hY0,ASSISTANTS:FV6};xi4=cW.extend({binding:N.union([N.object({}).passthrough(),N.string()]).optional()}),ui4=nW(cJ),xY0=X6({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",inputSchema:xi4,outputSchema:ui4,handler:async(Y,X)=>{await X.access.check();let Q=S6(X),J=Y.binding?typeof Y.binding==="string"?(()=>{let B=fi4[Y.binding.toUpperCase()];if(!B)throw Error(`Unknown binding: ${Y.binding}`);return B})():Y.binding:void 0,G=J?yf(J):void 0,W=(await X.storage.connections.list(Q.id)).filter((B)=>B.connection_type!=="VIRTUAL"),Z=G?await Promise.all(W.map(async(B)=>{if(!B.tools||B.tools.length===0)return null;return G.isImplementedBy(B.tools.map((D)=>({name:D.name,inputSchema:D.inputSchema,outputSchema:D.outputSchema})))?B:null})).then((B)=>B.filter((U)=>U!==null)):W;if(Y.where)Z=Z.filter((B)=>ff(B,Y.where));if(Y.orderBy&&Y.orderBy.length>0)Z=bi4(Z,Y.orderBy);let H=Z.length,F=Y.offset??0,V=Y.limit??100,q=Z.slice(F,F+V),$=F+V<H;return{items:q,totalCount:H,hasMore:$}}})});var gi4,uY0;var OV6=m(()=>{nJ();J4();Z3();gi4=AP(cJ),uY0=X6({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",inputSchema:PP,outputSchema:gi4,handler:async(Y,X)=>{let Q=S6(X);await X.access.check();let J=await X.storage.connections.findById(Y.id);if(!J||J.organization_id!==Q.id)return{item:null};return{item:J}}})});var hf=(Y,X)=>{if(X===null||X===void 0)return;let Q=Y.replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),J=X;for(let G of Q){if(J===null||J===void 0||typeof J!=="object")return;J=J[G]}return J};function NV6(Y){let X=Y.split("::");if(X.length!==2||!X[0]||!X[1])throw Error(`Invalid scope format: ${Y}. Expected format: "KEY::SCOPE"`);return X}function mi4(Y){let X=Y.split("::");if(X.length!==2||!X[0]||!X[1])return null;return X}function li4(Y){if(typeof Y==="object"&&Y!==null&&"value"in Y){let X=Y.value;if(typeof X==="string")return X}return null}function di4(Y,X){let Q={};if(!Y||!X)return Q;for(let J of X){if(J==="*"){Q["*"]=["*"];continue}let G=mi4(J);if(!G)continue;let[K,W]=G,Z=hf(K,Y),H=li4(Z);if(H){if(!Q[H])Q[H]=[];Q[H].push(W)}}return Q}function LV6(Y,X){let Q=di4(Y,X);return new Set(Object.keys(Q).filter((J)=>J!=="*"))}var MV6=()=>{};class gY0{db;vault;constructor(Y,X){this.db=Y;this.vault=X}async get(Y){let X=await this.db.selectFrom("downstream_tokens").selectAll().where("connectionId","=",Y).executeTakeFirst();if(!X)return null;return this.decryptToken(X)}async upsert(Y){let X=new Date().toISOString(),Q=await this.vault.encrypt(Y.accessToken),J=Y.refreshToken?await this.vault.encrypt(Y.refreshToken):null,G=Y.clientSecret?await this.vault.encrypt(Y.clientSecret):null;return await this.db.transaction().execute(async(K)=>{let W=await K.selectFrom("downstream_tokens").select(["id","createdAt"]).where("connectionId","=",Y.connectionId).executeTakeFirst();if(W)return await K.updateTable("downstream_tokens").set({accessToken:Q,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,updatedAt:X}).where("id","=",W.id).execute(),{id:W.id,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:W.createdAt,updatedAt:X,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint};let Z=vB("dtok");return await K.insertInto("downstream_tokens").values({id:Z,connectionId:Y.connectionId,accessToken:Q,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,createdAt:X,updatedAt:X}).execute(),{id:Z,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:X,updatedAt:X,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint}})}async delete(Y){await this.db.deleteFrom("downstream_tokens").where("connectionId","=",Y).execute()}isExpired(Y,X=0){if(!Y.expiresAt)return!1;let J=(Y.expiresAt instanceof Date?Y.expiresAt:new Date(Y.expiresAt)).getTime();if(Number.isNaN(J))return!0;return J-X<Date.now()}async decryptToken(Y){let X=await this.vault.decrypt(Y.accessToken),Q=Y.refreshToken?await this.vault.decrypt(Y.refreshToken):null,J=Y.clientSecret?await this.vault.decrypt(Y.clientSecret):null;return{id:Y.id,connectionId:Y.connectionId,accessToken:X,refreshToken:Q,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Y.createdAt,updatedAt:Y.updatedAt,clientId:Y.clientId,clientSecret:J,tokenEndpoint:Y.tokenEndpoint}}}var wV6=m(()=>{Lf()});async function ni4(Y,X,Q,J){for(let K of X){if(K==="*")continue;let[W]=NV6(K),Z=hf(W,Y);if(Z===void 0||Z===null)throw Error(`Scope references key "${W}" but it's not present in state`)}let G=LV6(Y,X);for(let K of G){if(K.endsWith("_self"))continue;let W=await J.storage.connections.findById(K);if(!W||W.organization_id!==Q)throw Error(`Referenced connection not found: ${K}`);try{await J.access.check(K)}catch(Z){throw Error(`Access denied to referenced connection: ${K}. ${Z.message}`)}}}var pi4,ci4,mY0;var PV6=m(()=>{MV6();wV6();Y6();J4();Tf();Z3();pi4=N.object({id:N.string().describe("ID of the connection to update"),data:$36.describe("Partial connection data to update")}),ci4=N.object({item:cJ.describe("The updated connection entity")});mY0=X6({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update an existing MCP connection in the organization",inputSchema:pi4,outputSchema:ci4,handler:async(Y,X)=>{$6(X);let Q=S6(X);if(await X.access.check(),!x8(X))throw Error("User ID required to update connection");let{id:G,data:K}=Y,W=await X.storage.connections.findById(G);if(!W||W.organization_id!==Q.id)throw Error("Connection not found in organization");let Z=K.connection_type??W.connection_type,H=K.connection_url??W.connection_url;if(Z==="VIRTUAL"){let L=Of(H);if(!L)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let M=await X.storage.virtualMcps.findById(L);if(!M)throw Error(`Virtual MCP not found: ${L}`);if(M.organization_id!==Q.id)throw Error("Virtual MCP does not belong to the current organization");H=Nf(L)}let F=K.configuration_state??W.configuration_state,V=K.configuration_scopes??W.configuration_scopes??[];if(K.configuration_state!==void 0||K.configuration_scopes!==void 0){if(K.configuration_state!==void 0)F=K.configuration_state;else if(F===null)F={};if(K.configuration_scopes!==void 0)V=K.configuration_scopes??[];if(V.length>0&&F)await ni4(F,V,Q.id,X)}let q=K.connection_token??W.connection_token;if(!q)try{let M=await new gY0(X.db,X.vault).get(G);if(M?.accessToken)q=M.accessToken}catch{}let $=await mB({id:W.id,title:K.title??W.title,connection_type:Z,connection_url:H,connection_token:q,connection_headers:K.connection_headers??W.connection_headers}).catch(()=>null),B=$?.length?$:null,U={...K,connection_url:H,tools:B,configuration_state:F,configuration_scopes:V},D=await X.storage.connections.update(G,U);if((K.configuration_state!==void 0||K.configuration_scopes!==void 0)&&F&&V.length>0)try{await(await X.createMCPProxy(G)).client.callTool({name:"ON_MCP_CONFIGURATION",arguments:{state:F,scopes:V}})}catch(L){console.error("Failed to invoke ON_MCP_CONFIGURATION callback",L)}return{item:D}}})});var lY0;var AV6=m(()=>{nJ();J4();Z3();lY0=X6({name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete a connection",inputSchema:TP,outputSchema:EP(cJ),handler:async(Y,X)=>{$6(X);let Q=S6(X);await X.access.check();let J=await X.storage.connections.findById(Y.id);if(!J)throw Error(`Connection not found: ${Y.id}`);if(J.organization_id!==Q.id)throw Error("Connection not found in organization");return await X.storage.connections.delete(Y.id),{item:J}}})});var dY0;var TV6=m(()=>{Y6();J4();dY0=X6({name:"CONNECTION_TEST",description:"Test connection health and latency",inputSchema:N.object({id:N.string()}),outputSchema:N.object({id:N.string(),healthy:N.boolean(),latencyMs:N.number()}),handler:async(Y,X)=>{let Q=S6(X);await X.access.check();let J=await X.storage.connections.findById(Y.id);if(!J||J.organization_id!==Q.id)throw Error("Connection not found");let G=await X.storage.connections.testConnection(Y.id);return{id:Y.id,...G}}})});var EV6=m(()=>{bF6();DV6();OV6();PV6();AV6();TV6()});import{sql as t4}from"kysely";function IV6(Y){if(Y===null||Y===void 0)return"NULL";if(typeof Y==="number")return String(Y);if(typeof Y==="boolean")return Y?"TRUE":"FALSE";if(typeof Y==="string")return`'${Y.replace(/'/g,"''")}'`;if(Y instanceof Date)return`'${Y.toISOString()}'`;return`'${JSON.stringify(Y).replace(/'/g,"''")}'`}function ri4(Y,X){let Q=Y;for(let G=X.length;G>=1;G--){let K=`$${G}`;if(Q.includes(K))Q=Q.replaceAll(K,IV6(X[G-1]))}let J=[];for(let G=0;G<Q.length;G++)if(Q[G]==="?")J.push(G);for(let G=Math.min(J.length,X.length)-1;G>=0;G--){let K=J[G],W=IV6(X[G]);Q=Q.slice(0,K)+W+Q.slice(K+1)}return Q}function CV6(Y){return Y.replace(/-/g,"_")}function si4(Y){return`app_${CV6(Y)}`}function ti4(Y){return`app_role_${CV6(Y)}`}function ei4(Y){if(Y instanceof Error){let X=Y.message.toLowerCase(),Q=Y.code;return Q==="3F000"||Q==="42704"||X.includes("schema")&&X.includes("does not exist")||X.includes("role")&&X.includes("does not exist")}return!1}async function Ya4(Y,X,Q){if(await t4`CREATE SCHEMA IF NOT EXISTS ${t4.id(X)}`.execute(Y),!(await t4`
408
408
  SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${Q}) as exists
409
409
  `.execute(Y)).rows[0]?.exists)await t4`CREATE ROLE ${t4.id(Q)} NOLOGIN`.execute(Y);await t4`GRANT ${t4.id(Q)} TO CURRENT_USER`.execute(Y),await t4`GRANT USAGE, CREATE ON SCHEMA ${t4.id(X)} TO ${t4.id(Q)}`.execute(Y),await t4`GRANT ALL ON ALL TABLES IN SCHEMA ${t4.id(X)} TO ${t4.id(Q)}`.execute(Y),await t4`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${t4.id(X)} TO ${t4.id(Q)}`.execute(Y),await t4`ALTER DEFAULT PRIVILEGES IN SCHEMA ${t4.id(X)} GRANT ALL ON TABLES TO ${t4.id(Q)}`.execute(Y),await t4`ALTER DEFAULT PRIVILEGES IN SCHEMA ${t4.id(X)} GRANT ALL ON SEQUENCES TO ${t4.id(Q)}`.execute(Y),await t4`REVOKE ALL ON SCHEMA public FROM ${t4.id(Q)}`.execute(Y)}async function Xa4(Y,X,Q,J){try{return await Y.transaction().execute(async(G)=>{return await t4`SET LOCAL ROLE ${t4.id(Q)}`.execute(G),await t4`SET LOCAL search_path TO ${t4.id(X)}`.execute(G),await t4.raw(J).execute(G)})}catch(G){if(ei4(G))return await Ya4(Y,X,Q),await Y.transaction().execute(async(K)=>{return await t4`SET LOCAL ROLE ${t4.id(Q)}`.execute(K),await t4`SET LOCAL search_path TO ${t4.id(X)}`.execute(K),await t4.raw(J).execute(K)});throw G}}var ai4,oi4,RV6;var SV6=m(()=>{Y6();J4();ai4=N.object({results:N.array(N.unknown()).optional(),success:N.boolean().optional()});oi4=N.object({sql:N.string().describe("The SQL query to run"),params:N.array(N.any()).describe("The parameters to pass to the SQL query").optional()});RV6=X6({name:"DATABASES_RUN_SQL",description:"Run a SQL query against the database",inputSchema:oi4,outputSchema:N.object({result:N.array(ai4)}),handler:async(Y,X)=>{$6(X),await X.access.check();let Q=ri4(Y.sql,Y.params||[]);if(!X.connectionId)throw Error("Connection context required for database access");let J=si4(X.connectionId),G=ti4(X.connectionId);return{result:[{results:(await Xa4(X.db,J,G,Q)).rows,success:!0}]}}})});var jV6,Ja4,kV6;var aW=m(()=>{Y6();fY0();jV6=N.object({connectionId:N.string().optional().describe("Filter subscriptions by connection ID (optional)")}),Ja4=N.object({id:N.string().describe("Subscription ID"),connectionId:N.string().describe("Subscriber connection ID"),eventType:N.string().describe("Event type pattern"),publisher:N.string().nullable().describe("Publisher connection filter (null = all publishers)"),filter:N.string().nullable().describe("JSONPath filter expression"),enabled:N.boolean().describe("Whether subscription is enabled"),createdAt:N.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:N.string().datetime().describe("Updated timestamp (ISO 8601)")}),kV6=N.object({subscriptions:N.array(Ja4).describe("List of subscriptions")})});var pY0;var vV6=m(()=>{J4();aW();pY0=X6({name:"EVENT_PUBLISH",description:"Publish an event to the event bus. Supports immediate, scheduled (deliverAt), and recurring (cron) delivery. The source is automatically set to the caller's connection ID.",inputSchema:IP,outputSchema:CP,handler:async(Y,X)=>{$6(X);let Q=S6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to publish events. Use a connection-scoped token.");let G=await X.eventBus.publish(Q.id,J,{type:Y.type,subject:Y.subject,data:Y.data,deliverAt:Y.deliverAt,cron:Y.cron});return{id:G.id,type:G.type,source:G.source,time:G.time}}})});var cY0;var _V6=m(()=>{J4();aW();cY0=X6({name:"EVENT_SUBSCRIBE",description:"Subscribe to events of a specific type. The subscriber is automatically set to the caller's connection.",inputSchema:RP,outputSchema:SP,handler:async(Y,X)=>{$6(X);let Q=S6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to subscribe. Use a connection-scoped token.");let G=await X.eventBus.subscribe(Q.id,{connectionId:J,eventType:Y.eventType,publisher:Y.publisher,filter:Y.filter});return{subscription:{id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}}}})});var nY0;var yV6=m(()=>{J4();aW();nY0=X6({name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events by removing a subscription.",inputSchema:vP,outputSchema:_P,handler:async(Y,X)=>{$6(X);let Q=S6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to unsubscribe. Use a connection-scoped token.");let G=await X.eventBus.getSubscription(Q.id,Y.subscriptionId);if(!G)throw Error(`Subscription not found: ${Y.subscriptionId}`);if(G.connectionId!==J)throw Error("Cannot unsubscribe from a subscription owned by another connection");return{success:(await X.eventBus.unsubscribe(Q.id,Y.subscriptionId)).success,subscriptionId:Y.subscriptionId}}})});var iY0;var fV6=m(()=>{J4();aW();iY0=X6({name:"EVENT_CANCEL",description:"Cancel a recurring event to stop future deliveries. Only the publisher can cancel their own events.",inputSchema:yP,outputSchema:fP,handler:async(Y,X)=>{$6(X);let Q=S6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to cancel events. Use a connection-scoped token.");if(!await X.eventBus.getEvent(Q.id,Y.eventId))throw Error(`Event not found: ${Y.eventId}`);if(!(await X.eventBus.cancelEvent(Q.id,Y.eventId,J)).success)throw Error("Failed to cancel event. Either the event is already completed/failed, or you are not the publisher.");return{success:!0,eventId:Y.eventId}}})});var aY0;var hV6=m(()=>{J4();aW();aY0=X6({name:"EVENT_ACK",description:"Acknowledge delivery of an event. Call after successfully processing an event received via ON_EVENTS with retryAfter.",inputSchema:hP,outputSchema:bP,handler:async(Y,X)=>{$6(X);let Q=S6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to acknowledge events. Use a connection-scoped token.");if(!(await X.eventBus.ackEvent(Q.id,Y.eventId,J)).success)throw Error("Failed to acknowledge event. Either the event was not found, already delivered, or you are not a subscriber.");return{success:!0,eventId:Y.eventId}}})});var rY0;var bV6=m(()=>{J4();aW();rY0=X6({name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions, optionally filtered by connection ID.",inputSchema:jV6,outputSchema:kV6,handler:async(Y,X)=>{$6(X);let Q=S6(X);return await X.access.check(),{subscriptions:(await X.eventBus.listSubscriptions(Q.id,Y.connectionId)).map((G)=>({id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}))}}})});var oY0;var xV6=m(()=>{J4();aW();oY0=X6({name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state. Creates new, deletes removed, updates changed filters. Subscriptions are identified by (eventType, publisher).",inputSchema:jP,outputSchema:kP,handler:async(Y,X)=>{$6(X);let Q=S6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to sync subscriptions. Use a connection-scoped token.");let G=await X.eventBus.syncSubscriptions(Q.id,{connectionId:J,subscriptions:Y.subscriptions});return{created:G.created,updated:G.updated,deleted:G.deleted,unchanged:G.unchanged,subscriptions:G.subscriptions.map((K)=>({id:K.id,connectionId:K.connectionId,eventType:K.eventType,publisher:K.publisher,filter:K.filter,enabled:K.enabled,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt,updatedAt:K.updatedAt instanceof Date?K.updatedAt.toISOString():K.updatedAt}))}}})});var uV6=m(()=>{vV6();_V6();yV6();fV6();hV6();bV6();xV6();aW()});var sY0,Wa4,O7,gV6,mV6;var rB=m(()=>{Y6();sY0=N.enum(["inclusion","exclusion"]).describe("Tool selection mode: 'inclusion' = include selected (default), 'exclusion' = exclude selected"),Wa4=N.object({connection_id:N.string().describe("Connection ID"),selected_tools:N.array(N.string()).nullable().describe("Selected tool names. With 'inclusion' mode: null = all tools included. With 'exclusion' mode: null = entire connection excluded"),selected_resources:N.array(N.string()).nullable().describe("Selected resource URIs or patterns. Supports * and ** wildcards for pattern matching. With 'inclusion' mode: null = all resources included."),selected_prompts:N.array(N.string()).nullable().describe("Selected prompt names. With 'inclusion' mode: null = all prompts included. With 'exclusion' mode: null = entire connection excluded.")}),O7=N.object({id:N.string().describe("Unique identifier for the virtual MCP"),title:N.string().describe("Human-readable name for the virtual MCP"),description:N.string().nullable().describe("Description of the virtual MCP"),icon:N.string().nullable().optional().describe("Icon URL for the virtual MCP"),created_at:N.string().describe("When the virtual MCP was created"),updated_at:N.string().describe("When the virtual MCP was last updated"),created_by:N.string().describe("User ID who created the virtual MCP"),updated_by:N.string().optional().describe("User ID who last updated the virtual MCP"),organization_id:N.string().describe("Organization ID this virtual MCP belongs to"),tool_selection_mode:sY0.describe("Tool selection mode: 'inclusion' = include selected, 'exclusion' = exclude selected"),status:N.enum(["active","inactive"]).describe("Current status"),metadata:N.object({instructions:N.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:N.array(Wa4).describe("Connections with their selected tools (behavior depends on tool_selection_mode)")}),gV6=N.object({title:N.string().min(1).max(255).describe("Name for the virtual MCP"),description:N.string().nullable().optional().describe("Optional description"),tool_selection_mode:sY0.optional().default("inclusion").describe("Tool selection mode (defaults to 'inclusion')"),icon:N.string().nullable().optional().describe("Optional icon URL"),status:N.enum(["active","inactive"]).optional().default("active").describe("Initial status"),metadata:N.object({instructions:N.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:N.array(N.object({connection_id:N.string().describe("Connection ID"),selected_tools:N.array(N.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:N.array(N.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:N.array(N.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).describe("Connections to include/exclude (can be empty for exclusion mode)")}),mV6=N.object({title:N.string().min(1).max(255).optional().describe("New name"),description:N.string().nullable().optional().describe("New description (null to clear)"),tool_selection_mode:sY0.optional().describe("New tool selection mode"),icon:N.string().nullable().optional().describe("New icon URL (null to clear)"),status:N.enum(["active","inactive"]).optional().describe("New status"),metadata:N.object({instructions:N.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:N.array(N.object({connection_id:N.string().describe("Connection ID"),selected_tools:N.array(N.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:N.array(N.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:N.array(N.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).optional().describe("New connections (replaces existing)")})});var Za4,Ka4,tY0;var lV6=m(()=>{Y6();J4();rB();Za4=N.object({data:gV6.describe("Data for the new virtual MCP")}),Ka4=N.object({item:O7.describe("The created virtual MCP entity")}),tY0=X6({name:"COLLECTION_VIRTUAL_MCP_CREATE",description:"Create a new MCP virtual MCP in the organization",inputSchema:Za4,outputSchema:Ka4,handler:async(Y,X)=>{$6(X);let Q=S6(X);await X.access.check();let J=x8(X);if(!J)throw Error("User ID required to create virtual MCP");return{item:await X.storage.virtualMcps.create(Q.id,J,Y.data)}}})});function Ha4(Y){let X=[],Q=0;while(Q<Y.length){let J=Y[Q];if(J==="%")X.push(".*");else if(J==="_")X.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))X.push("\\"+J);else X.push(J);Q++}return X.join("")}function q3(Y){return typeof Y==="string"||typeof Y==="number"}function eY0(Y,X){let Q=X.split("."),J=Y;for(let G of Q){if(J==null||typeof J!=="object")return;J=J[G]}return J}function Fa4(Y,X){return Y.connections.some((Q)=>Q.connection_id===X)}function bf(Y,X){if("conditions"in X){let{operator:Z,conditions:H}=X;switch(Z){case"and":return H.every((F)=>bf(Y,F));case"or":return H.some((F)=>bf(Y,F));case"not":return!H.every((F)=>bf(Y,F));default:return!0}}let{field:Q,operator:J,value:G}=X,K=Q.join(".");if(K==="connection_id"){if(J!=="eq"||typeof G!=="string")return!1;return Fa4(Y,G)}let W=eY0(Y,K);switch(J){case"eq":return W===G;case"gt":return q3(W)&&q3(G)&&W>G;case"gte":return q3(W)&&q3(G)&&W>=G;case"lt":return q3(W)&&q3(G)&&W<G;case"lte":return q3(W)&&q3(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=Ha4(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 Va4(Y,X){return[...Y].sort((Q,J)=>{for(let G of X){let K=G.field.join("."),W=eY0(Q,K),Z=eY0(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 qa4,$a4,YX0;var dV6=m(()=>{nJ();J4();rB();qa4=cW,$a4=nW(O7),YX0=X6({name:"COLLECTION_VIRTUAL_MCP_LIST",description:"List all MCP virtual MCPs in the organization",inputSchema:qa4,outputSchema:$a4,handler:async(Y,X)=>{await X.access.check();let Q=S6(X),J=Y.where&&!("conditions"in Y.where)&&Y.where.field.join(".")==="connection_id"&&Y.where.operator==="eq"&&typeof Y.where.value==="string"?Y.where.value:void 0,K=J?await X.storage.virtualMcps.listByConnectionId(Q.id,J):await X.storage.virtualMcps.list(Q.id);if(Y.where)K=K.filter((q)=>bf(q,Y.where));if(Y.orderBy&&Y.orderBy.length>0)K=Va4(K,Y.orderBy);let W=K.length,Z=Y.offset??0,H=Y.limit??100,F=K.slice(Z,Z+H),V=Z+H<W;return{items:F,totalCount:W,hasMore:V}}})});var za4,Ba4,XX0;var pV6=m(()=>{Y6();J4();rB();za4=N.object({id:N.string().describe("ID of the virtual MCP to retrieve")}),Ba4=N.object({item:O7.nullable().describe("The retrieved virtual MCP, or null if not found")}),XX0=X6({name:"COLLECTION_VIRTUAL_MCP_GET",description:"Get an MCP virtual MCP by ID",inputSchema:za4,outputSchema:Ba4,handler:async(Y,X)=>{$6(X);let Q=S6(X);await X.access.check();let J=await X.storage.virtualMcps.findById(Y.id);if(J&&J.organization_id!==Q.id)return{item:null};if(!J)return{item:null};return{item:J}}})});var Ua4,Da4,QX0;var cV6=m(()=>{Y6();J4();rB();Ua4=N.object({id:N.string().describe("ID of the virtual MCP to update"),data:mV6.describe("Partial virtual MCP data to update")}),Da4=N.object({item:O7.describe("The updated virtual MCP entity")}),QX0=X6({name:"COLLECTION_VIRTUAL_MCP_UPDATE",description:"Update an MCP virtual MCP",inputSchema:Ua4,outputSchema:Da4,handler:async(Y,X)=>{$6(X);let Q=S6(X);await X.access.check();let J=x8(X);if(!J)throw Error("User ID required to update virtual MCP");let G=await X.storage.virtualMcps.findById(Y.id);if(!G)throw Error(`Virtual MCP not found: ${Y.id}`);if(G.organization_id!==Q.id)throw Error(`Virtual MCP not found: ${Y.id}`);return{item:await X.storage.virtualMcps.update(Y.id,J,Y.data)}}})});var Oa4,Na4,JX0;var nV6=m(()=>{Y6();J4();rB();Oa4=N.object({id:N.string().describe("ID of the virtual MCP to delete")}),Na4=N.object({item:O7.describe("The deleted virtual MCP entity")}),JX0=X6({name:"COLLECTION_VIRTUAL_MCP_DELETE",description:"Delete an MCP virtual MCP",inputSchema:Oa4,outputSchema:Na4,handler:async(Y,X)=>{$6(X);let Q=S6(X);await X.access.check();let J=await X.storage.virtualMcps.findById(Y.id);if(!J)throw Error(`Virtual MCP not found: ${Y.id}`);if(J.organization_id!==Q.id)throw Error(`Virtual MCP not found: ${Y.id}`);return await X.storage.virtualMcps.delete(Y.id),{item:J}}})});var iV6=m(()=>{lV6();dV6();pV6();cV6();nV6()});var Ma4,GX0;var aV6=m(()=>{J4();Y6();Ma4=N.object({id:N.string().optional().describe("Unique log identifier"),organizationId:N.string().describe("Organization ID"),connectionId:N.string().describe("Connection ID"),connectionTitle:N.string().describe("Connection display name"),toolName:N.string().describe("Name of the tool that was called"),input:N.record(N.string(),N.unknown()).describe("Redacted tool input"),output:N.record(N.string(),N.unknown()).describe("Redacted tool output"),isError:N.boolean().describe("Whether the call resulted in an error"),errorMessage:N.string().nullish().describe("Error message if applicable"),durationMs:N.number().describe("Call duration in milliseconds"),timestamp:N.string().describe("ISO 8601 timestamp of the call"),userId:N.string().nullish().describe("User who triggered the call"),requestId:N.string().describe("Unique request identifier"),userAgent:N.string().nullish().describe("Client identifier (x-mesh-client header)"),virtualMcpId:N.string().nullish().describe("Virtual MCP (Agent) ID if routed through an agent"),properties:N.record(N.string(),N.string()).nullish().describe("Custom key-value metadata attached to the log")}),GX0=X6({name:"MONITORING_LOGS_LIST",description:"List monitoring logs for tool calls in the organization",inputSchema:N.object({connectionId:N.string().optional().describe("Filter by connection ID"),virtualMcpId:N.string().optional().describe("Filter by Virtual MCP (Agent) ID"),toolName:N.string().optional().describe("Filter by tool name"),isError:N.boolean().optional().describe("Filter by error status"),startDate:N.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:N.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)"),limit:N.number().default(10).describe("Maximum number of results"),offset:N.number().default(0).describe("Offset for pagination"),properties:N.record(N.string(),N.string()).optional().describe("Filter by exact property key=value matches"),propertyKeys:N.array(N.string()).optional().describe("Filter by logs that have these property keys"),propertyPatterns:N.record(N.string(),N.string()).optional().describe("Filter by property value patterns (SQL LIKE, use % as wildcard)")}),outputSchema:N.object({logs:N.array(Ma4).describe("Array of monitoring logs"),total:N.number().describe("Total number of logs matching filters"),offset:N.number().describe("Current offset for pagination"),limit:N.number().describe("Current limit for pagination")}),handler:async(Y,X)=>{let Q=S6(X),G=Y.properties||Y.propertyKeys||Y.propertyPatterns?{properties:Y.properties,propertyKeys:Y.propertyKeys,propertyPatterns:Y.propertyPatterns}:void 0,K={organizationId:Q.id,connectionId:Y.connectionId,virtualMcpId:Y.virtualMcpId,toolName:Y.toolName,isError:Y.isError,startDate:Y.startDate?new Date(Y.startDate):void 0,endDate:Y.endDate?new Date(Y.endDate):void 0,limit:Y.limit,offset:Y.offset,propertyFilters:G},W=await X.storage.monitoring.query(K);return{logs:W.logs.map((Z)=>({...Z,timestamp:Z.timestamp instanceof Date?Z.timestamp.toISOString():Z.timestamp})),total:W.total,offset:Y.offset,limit:Y.limit}}})});var WX0;var rV6=m(()=>{J4();Y6();WX0=X6({name:"MONITORING_STATS",description:"Get aggregated statistics for tool call monitoring",inputSchema:N.object({startDate:N.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:N.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)")}),outputSchema:N.object({totalCalls:N.number().describe("Total number of tool calls"),errorRate:N.number().describe("Error rate as a decimal (0 to 1)"),avgDurationMs:N.number().describe("Average call duration in milliseconds"),errorRatePercent:N.string().describe("Error rate as a percentage string")}),handler:async(Y,X)=>{let J={organizationId:S6(X).id,startDate:Y.startDate?new Date(Y.startDate):void 0,endDate:Y.endDate?new Date(Y.endDate):void 0},G=await X.storage.monitoring.getStats(J);return{...G,errorRatePercent:(G.errorRate*100).toFixed(2)}}})});var oV6=m(()=>{aV6();rV6()});var ZX0;var sV6=m(()=>{Y6();J4();ZX0=X6({name:"ORGANIZATION_CREATE",description:"Create a new organization",inputSchema:N.object({slug:N.string().min(1).max(50).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens"),name:N.string().min(1).max(255),description:N.string().optional()}),outputSchema:N.object({id:N.string(),name:N.string(),slug:N.string(),logo:N.string().nullable().optional(),metadata:N.any().optional(),createdAt:N.string().datetime().describe("ISO 8601 timestamp"),members:N.array(N.any()).optional()}),handler:async(Y,X)=>{$6(X),await X.access.check();let Q=x8(X);if(!Q)throw Error("User ID required to create organization");let J=await X.boundAuth.organization.create({name:Y.name,slug:Y.slug,metadata:Y.description?{description:Y.description}:void 0,userId:Q});if(!J)throw Error("Failed to create organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var KX0;var tV6=m(()=>{Y6();J4();KX0=X6({name:"ORGANIZATION_LIST",description:"List all organizations user has access to",inputSchema:N.object({userId:N.string().optional()}),outputSchema:N.object({organizations:N.array(N.object({id:N.string(),name:N.string(),slug:N.string(),logo:N.string().nullable().optional(),metadata:N.any().optional(),createdAt:N.string().datetime().describe("ISO 8601 timestamp")}))}),handler:async(Y,X)=>{$6(X),await X.access.check();let Q=x8(X),J=Y.userId||Q;if(!J)throw Error("User ID required to list organizations");return{organizations:(await X.boundAuth.organization.list(J)).map((K)=>({...K,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt}))}}})});var HX0;var eV6=m(()=>{Y6();J4();HX0=X6({name:"ORGANIZATION_GET",description:"Get organization details by slug or ID",inputSchema:N.object({}),outputSchema:N.object({id:N.string(),name:N.string(),slug:N.string(),logo:N.string().nullable().optional(),metadata:N.any().optional(),createdAt:N.string().datetime().describe("ISO 8601 timestamp"),members:N.array(N.any()).optional(),invitations:N.array(N.any()).optional()}),handler:async(Y,X)=>{$6(X),await X.access.check();let Q=await X.boundAuth.organization.get();if(!Q)throw Error("No active organization found");let J=new Date,G=Q.invitations?.filter((K)=>new Date(K.expiresAt)>J);return{...Q,invitations:G,createdAt:Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt}}})});var FX0;var Yq6=m(()=>{Y6();J4();FX0=X6({name:"ORGANIZATION_UPDATE",description:"Update an existing organization",inputSchema:N.object({id:N.string(),slug:N.string().min(1).max(50).regex(/^[a-z0-9-]+$/).optional(),name:N.string().min(1).max(255).optional(),description:N.string().optional()}),outputSchema:N.object({id:N.string(),name:N.string(),slug:N.string(),logo:N.string().nullable().optional(),metadata:N.any().optional(),createdAt:N.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Y,X)=>{$6(X),await X.access.check();let Q={};if(Y.name)Q.name=Y.name;if(Y.slug)Q.slug=Y.slug;if(Y.description)Q.metadata={description:Y.description};let J=await X.boundAuth.organization.update({organizationId:Y.id,data:Q});if(!J)throw Error("Failed to update organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var VX0;var Xq6=m(()=>{Y6();J4();VX0=X6({name:"ORGANIZATION_DELETE",description:"Delete an organization",inputSchema:N.object({id:N.string()}),outputSchema:N.object({success:N.boolean(),id:N.string()}),handler:async(Y,X)=>{return $6(X),await X.access.check(),await X.boundAuth.organization.delete(Y.id),{success:!0,id:Y.id}}})});var uP;var qX0=m(()=>{Y6();uP=N.object({title:N.string(),url:N.string(),icon:N.string()})});var $X0;var Qq6=m(()=>{Y6();J4();qX0();$X0=X6({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings",inputSchema:N.object({}),outputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(uP).nullable().optional(),enabled_plugins:N.array(N.string()).nullable().optional(),createdAt:N.string().datetime().optional().describe("ISO 8601 timestamp"),updatedAt:N.string().datetime().optional().describe("ISO 8601 timestamp")}),handler:async(Y,X)=>{$6(X),await X.access.check();let Q=X.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await X.storage.organizationSettings.get(Q);if(!J)return{organizationId:Q};return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt,updatedAt:J.updatedAt instanceof Date?J.updatedAt.toISOString():J.updatedAt}}})});var zX0;var Jq6=m(()=>{Y6();J4();qX0();zX0=X6({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings",inputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(uP).optional(),enabled_plugins:N.array(N.string()).optional()}),outputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(uP).nullable().optional(),enabled_plugins:N.array(N.string()).nullable().optional(),createdAt:N.string().datetime().describe("ISO 8601 timestamp"),updatedAt:N.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Y,X)=>{if($6(X),await X.access.check(),X.organization&&X.organization.id!==Y.organizationId)throw Error("Cannot update settings for a different organization");let Q=await X.storage.organizationSettings.upsert(Y.organizationId,{sidebar_items:Y.sidebar_items,enabled_plugins:Y.enabled_plugins});return{...Q,createdAt:Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt,updatedAt:Q.updatedAt instanceof Date?Q.updatedAt.toISOString():Q.updatedAt}}})});var BX0;var Gq6=m(()=>{Y6();J4();BX0=X6({name:"ORGANIZATION_MEMBER_ADD",description:"Add a member to an organization",inputSchema:N.object({organizationId:N.string().optional(),userId:N.string(),role:N.array(N.string())}),outputSchema:N.object({id:N.string(),organizationId:N.string(),userId:N.string(),role:N.union([N.string(),N.array(N.string())]),createdAt:N.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Y,X)=>{$6(X),await X.access.check();let Q=Y.organizationId||X.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await X.boundAuth.organization.addMember({organizationId:Q,userId:Y.userId,role:Y.role});if(!J)throw Error("Failed to add member");return{...J,role:J.role,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var UX0;var Wq6=m(()=>{Y6();J4();UX0=X6({name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove a member from an organization",inputSchema:N.object({organizationId:N.string().optional(),memberIdOrEmail:N.string()}),outputSchema:N.object({success:N.boolean(),memberIdOrEmail:N.string()}),handler:async(Y,X)=>{$6(X),await X.access.check();let Q=Y.organizationId||X.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");return await X.boundAuth.organization.removeMember({organizationId:Q,memberIdOrEmail:Y.memberIdOrEmail}),{success:!0,memberIdOrEmail:Y.memberIdOrEmail}}})});var DX0;var Zq6=m(()=>{Y6();J4();DX0=X6({name:"ORGANIZATION_MEMBER_LIST",description:"List all members in an organization",inputSchema:N.object({limit:N.number().optional(),offset:N.number().optional()}),outputSchema:N.object({members:N.array(N.object({id:N.string(),organizationId:N.string(),userId:N.string(),role:N.string(),createdAt:N.string().datetime().describe("ISO 8601 timestamp"),user:N.object({id:N.string(),name:N.string(),email:N.string(),image:N.string().optional()}).optional()}))}),handler:async(Y,X)=>{$6(X),await X.access.check();let Q=X.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await X.boundAuth.organization.listMembers({organizationId:Q,limit:Y.limit,offset:Y.offset});return{members:(Array.isArray(J)?J:[]).map((K)=>({...K,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt}))}}})});var OX0;var Kq6=m(()=>{Y6();J4();OX0=X6({name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update a member's role in an organization",inputSchema:N.object({organizationId:N.string().optional(),memberId:N.string(),role:N.array(N.string())}),outputSchema:N.object({id:N.string(),organizationId:N.string(),userId:N.string(),role:N.union([N.literal("admin"),N.literal("member"),N.literal("owner")]),createdAt:N.string().datetime().describe("ISO 8601 timestamp"),user:N.object({email:N.string(),name:N.string(),image:N.string().optional()})}),handler:async(Y,X)=>{$6(X),await X.access.check();let Q=Y.organizationId||X.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await X.boundAuth.organization.updateMemberRole({organizationId:Q,memberId:Y.memberId,role:Y.role});if(!J)throw Error("Failed to update member role");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var Hq6=m(()=>{sV6();tV6();eV6();Yq6();Xq6();Qq6();Jq6();Gq6();Wq6();Zq6();Kq6()});var Fq6,N7,Vq6,qq6;var BV=m(()=>{Y6();Fq6=N.object({id:N.string().describe("Unique message ID"),threadId:N.string().describe("ID of the parent thread"),metadata:N.unknown().optional().describe("Optional message metadata"),parts:N.array(N.record(N.string(),N.unknown())).describe("Message content parts (AI SDK UIMessagePart format)"),role:N.enum(["user","assistant","system"]).describe("Message role"),createdAt:N.string().datetime().describe("Timestamp of creation"),updatedAt:N.string().datetime().describe("Timestamp of last update")}),N7=N.object({id:N.string().describe("Unique thread ID"),organizationId:N.string().describe("Organization this thread belongs to"),title:N.string().describe("Thread title"),description:N.string().nullable().describe("Thread description"),createdAt:N.string().datetime().describe("Timestamp of creation"),updatedAt:N.string().datetime().describe("Timestamp of last update"),hidden:N.boolean().optional().describe("Whether the thread is hidden"),createdBy:N.string().describe("User ID who created the thread"),updatedBy:N.string().nullable().describe("User ID who last updated the thread")}),Vq6=N.object({id:N.string().optional().describe("Optional custom ID for the thread"),title:N.string().describe("Thread title"),description:N.string().nullish().describe("Thread description")}),qq6=N.object({title:N.string().optional().describe("New thread title"),description:N.string().nullish().describe("New thread description"),hidden:N.boolean().optional().describe("Whether the thread is hidden")})});var Aa4,Ta4,NX0;var $q6=m(()=>{Y6();J4();BV();Lf();Aa4=N.object({data:Vq6.describe("Data for the new thread (id is auto-generated if not provided)")}),Ta4=N.object({item:N7.describe("The created thread entity")}),NX0=X6({name:"COLLECTION_THREADS_CREATE",description:"Create a new thread in the organization",inputSchema:Aa4,outputSchema:Ta4,handler:async(Y,X)=>{$6(X);let Q=S6(X);await X.access.check();let J=x8(X);if(!J)throw Error("User ID required to create thread");let G=Y.data.id??vB("thrd"),K=await X.storage.threads.create({id:G,organizationId:Q.id,title:Y.data.title,description:Y.data.description,createdBy:J});return{item:{...K,hidden:K.hidden??!1}}}})});var Ea4,Ia4,LX0;var zq6=m(()=>{nJ();J4();BV();Y6();Ea4=cW.extend({where:N.object({created_by:N.string().optional()}).optional()}),Ia4=nW(N7),LX0=X6({name:"COLLECTION_THREADS_LIST",description:"List all threads in the organization with filtering, sorting, and pagination",inputSchema:Ea4,outputSchema:Ia4,handler:async(Y,X)=>{await X.access.check();let Q=X.auth.user?.id;if(!Q)throw Error("User ID required to list threads");let J=S6(X),G=Y.offset??0,K=Y.limit??100,{threads:W,total:Z}=await X.storage.threads.list(J.id,Q,{limit:K,offset:G}),H=G+K<Z;return{items:W.map((F)=>({...F,hidden:F.hidden??!1})),totalCount:Z,hasMore:H}}})});var Ca4,MX0;var Bq6=m(()=>{nJ();J4();BV();Ca4=AP(N7),MX0=X6({name:"COLLECTION_THREADS_GET",description:"Get thread details by ID",inputSchema:PP,outputSchema:Ca4,handler:async(Y,X)=>{$6(X);let Q=S6(X);await X.access.check();let J=await X.storage.threads.get(Y.id);if(!J||J.organizationId!==Q.id)return{item:null};return{item:{...J,hidden:J.hidden??!1}}}})});var Ra4,Sa4,wX0;var Uq6=m(()=>{Y6();J4();BV();Ra4=N.object({id:N.string().describe("ID of the thread to update"),data:qq6.describe("Partial thread data to update")}),Sa4=N.object({item:N7.describe("The updated thread entity")}),wX0=X6({name:"COLLECTION_THREADS_UPDATE",description:"Update an existing thread in the organization",inputSchema:Ra4,outputSchema:Sa4,handler:async(Y,X)=>{$6(X);let Q=S6(X);await X.access.check();let J=x8(X);if(!J)throw Error("User ID required to update thread");let{id:G,data:K}=Y,W=await X.storage.threads.get(G);if(!W||W.organizationId!==Q.id)throw Error("Thread not found in organization");let Z=await X.storage.threads.update(G,{title:K.title,description:K.description,hidden:K.hidden,updatedBy:J});return{item:{...Z,hidden:Z.hidden??!1}}}})});var PX0;var Dq6=m(()=>{nJ();J4();BV();PX0=X6({name:"COLLECTION_THREADS_DELETE",description:"Delete a thread",inputSchema:TP,outputSchema:EP(N7),handler:async(Y,X)=>{$6(X);let Q=S6(X);await X.access.check();let J=await X.storage.threads.get(Y.id);if(!J)throw Error(`Thread not found: ${Y.id}`);if(J.organizationId!==Q.id)throw Error(`Thread not found: ${Y.id}`);return await X.storage.threads.delete(Y.id),{item:{...J,hidden:J.hidden??!1}}}})});function Oq6(Y){if(!Y)return null;if("field"in Y&&Y.field[0]==="threadId"&&Y.operator==="eq")return String(Y.value);if("conditions"in Y)for(let X of Y.conditions){let Q=Oq6(X);if(Q)return Q}return null}var ja4,AX0;var Nq6=m(()=>{nJ();J4();BV();ja4=nW(Fq6),AX0=X6({name:"COLLECTION_THREAD_MESSAGES_LIST",description:"List all messages for a specific thread",inputSchema:cW,outputSchema:ja4,handler:async(Y,X)=>{let Q=S6(X);await X.access.check();let J=Oq6(Y.where);if(!J)throw Error("threadId filter is required in where clause");let G=await X.storage.threads.get(J);if(!G||G.organizationId!==Q.id)throw Error("Thread not found in organization");let K=Y.offset??0,W=Y.limit??100,{messages:Z,total:H}=await X.storage.threads.listMessages(J,{limit:W,offset:K}),F=K+W<H;return{items:Z,totalCount:H,hasMore:F}}})});var Lq6=m(()=>{$q6();zq6();Bq6();Uq6();Dq6();Nq6()});var va4,_a4,TX0;var Mq6=m(()=>{Y6();J4();va4=N.object({id:N.string().min(1)}),_a4=N.object({user:N.object({id:N.string(),name:N.string(),email:N.string(),image:N.string().nullable()}).nullable()}),TX0=X6({name:"USER_GET",description:"Get a user by id (restricted to shared organizations)",inputSchema:va4,outputSchema:_a4,handler:async(Y,X)=>{await X.access.check(),$6(X);let Q=x8(X);if(!Q)throw Error("Authentication required");let J=await X.storage.users.findById(Y.id,Q);if(!J)return{user:null};return{user:{id:J.id,name:J.name,email:J.email,image:J.image??null}}}})});var wq6=m(()=>{Mq6()});var Aq6={};d6(Aq6,{managementMCP:()=>ba4,ALL_TOOLS:()=>Pq6});var fa4,ha4,Pq6,ba4=async(Y)=>{let X=null;if(Y.organization)X=(await Y.storage.organizationSettings.get(Y.organization.id))?.enabled_plugins??null;let J=L50(Pq6,X).map((K)=>({name:K.name,description:K.description,inputSchema:K.inputSchema,outputSchema:K.outputSchema,handler:async(W)=>{return Y.access.setToolName(K.name),await K.execute(W,Y)}}));return CH6({name:"mcp-mesh-management",version:"1.0.0"}).withTools(J).build()};var Tq6=m(()=>{RH6();Vg();lH6();hF6();EV6();SV6();uV6();iV6();oV6();Hq6();Lq6();wq6();fa4=[ZX0,KX0,HX0,FX0,VX0,$X0,zX0,BX0,UX0,DX0,OX0,kY0,xY0,uY0,mY0,lY0,dY0,tY0,YX0,XX0,QX0,JX0,RV6,GX0,WX0,WY0,KY0,HY0,ZY0,pY0,cY0,nY0,iY0,aY0,rY0,oY0,TX0,RY0,SY0,jY0,NX0,LX0,MX0,wX0,PX0,AX0],ha4=M50(),Pq6=[...fa4,...ha4]});mg();import{Migrator as _q6}from"kysely";var d50={benchmark:()=>Promise.resolve().then(() => (l50(),m50)).then((Y)=>Y.seed)};async function p50(Y,X){let Q=d50[X];if(!Q)throw Error(`Unknown seed: ${X}. Available: ${Object.keys(d50).join(", ")}`);let J=await Q();console.log(`\uD83C\uDF31 Running seed: ${X}`);let G=await J(Y);return console.log(`\u2705 Seed "${X}" completed`),G}T7();pQ();T7();pQ();SY();T9();var T8=(Y,X="ms")=>{return new Date(Date.now()+(X==="sec"?Y*1000:Y))},aI=new WeakMap;function AW0(Y,X){let Q=X.fields,J={};for(let G in Y){let K=Q[G];if(!K){J[G]=Y[G];continue}if(K.returned===!1)continue;J[G]=Y[G]}return J}function rI(Y,X){if(!aI.has(Y))aI.set(Y,new Map);let Q=aI.get(Y);if(Q.has(X))return Q.get(X);let J={...X==="user"?Y.user?.additionalFields:{},...X==="session"?Y.session?.additionalFields:{}};for(let G of Y.plugins||[])if(G.schema&&G.schema[X])J={...J,...G.schema[X].fields};return aI.get(Y).set(X,J),J}function E9(Y,X){return{...AW0(X,{fields:rI(Y,"user")}),id:X.id}}function KG(Y,X){return AW0(X,{fields:rI(Y,"session")})}function Wl(Y,X){let Q=X.action||"create",J=X.fields,G=Object.assign(Object.create(null),null);for(let K in J){if(K in Y){if(J[K].input===!1){if(J[K].defaultValue!==void 0){if(Q!=="update"){G[K]=J[K].defaultValue;continue}}if(Y[K])throw new i("BAD_REQUEST",{message:`${K} is not allowed to be set`});continue}if(J[K].validator?.input&&Y[K]!==void 0){G[K]=J[K].validator.input["~standard"].validate(Y[K]);continue}if(J[K].transform?.input&&Y[K]!==void 0){G[K]=J[K].transform?.input(Y[K]);continue}G[K]=Y[K];continue}if(J[K].defaultValue!==void 0&&Q==="create"){if(typeof J[K].defaultValue==="function"){G[K]=J[K].defaultValue();continue}G[K]=J[K].defaultValue;continue}if(J[K].required&&Q==="create")throw new i("BAD_REQUEST",{message:`${K} is required`})}return G}function oI(Y,X={},Q){return Wl(X,{fields:rI(Y,"user"),action:Q})}function Zl(Y,X){return Wl(X,{fields:rI(Y,"session")})}function rY(Y,X){if(!X)return Y;for(let Q in X){let J=X[Q]?.modelName;if(J)Y[Q].modelName=J;for(let G in Y[Q].fields){let K=X[Q]?.fields?.[G];if(!K)continue;Y[Q].fields[G].fieldName=K}}return Y}kX();Y6();var tO6="127.0.0.1";function CZ(Y,X){if(X.advanced?.ipAddress?.disableIpTracking)return null;if(y7()||$q())return tO6;let Q="headers"in Y?Y.headers:Y,J=X.advanced?.ipAddress?.ipAddressHeaders||["x-forwarded-for"];for(let G of J){let K="get"in Q?Q.get(G):Q[G];if(typeof K==="string"){let W=K.split(",")[0].trim();if(eO6(W))return W}}return null}function eO6(Y){if(_3().safeParse(Y).success)return!0;if(y3().safeParse(Y).success)return!0;return!1}jY();WG();kX();u8();import{sql as FG}from"kysely";async function RW0(Y,X){let Q;if(!Y.database){let J=VQ(Y),G=Object.keys(J).reduce((W,Z)=>{return W[Z]=[],W},{}),{memoryAdapter:K}=await Promise.resolve().then(() => (CW0(),IW0));Q=K(G)(Y)}else if(typeof Y.database==="function")Q=Y.database(Y);else Q=await X(Y);if(!Q.transaction)f6.warn("Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation."),Q.transaction=async(J)=>{return J(Q)};return Q}async function $l(Y){return RW0(Y,async(X)=>{let{createKyselyAdapter:Q}=await Promise.resolve().then(() => (ql(),Vl)),{kysely:J,databaseType:G,transaction:K}=await Q(X);if(!J)throw new I6("Failed to initialize database adapter");let{kyselyAdapter:W}=await Promise.resolve().then(() => (ql(),Vl));return W(J,{type:G||"sqlite",debugLogs:X.database&&"debugLogs"in X.database?X.database.debugLogs:!1,transaction:K})(X)})}function SW0(Y,X){let Q=X.hooks;async function J(H,F,V){let q=await qQ(),$=H;for(let D of Q||[]){let L=D[F]?.create?.before;if(L){let M=await L($,q);if(M===!1)return null;if(typeof M==="object"&&"data"in M)$={...$,...M.data}}}let B=V?await V.fn($):null,U=!V||V.executeMainFn?await(await D1(Y)).create({model:F,data:$,forceAllowId:!0}):B;for(let D of Q||[]){let L=D[F]?.create?.after;if(L)await L(U,q)}return U}async function G(H,F,V,q){let $=await qQ(),B=H;for(let L of Q||[]){let M=L[V]?.update?.before;if(M){let I=await M(H,$);if(I===!1)return null;if(typeof I==="object"&&"data"in I)B={...B,...I.data}}}let U=q?await q.fn(B):null,D=!q||q.executeMainFn?await(await D1(Y)).update({model:V,update:B,where:F}):U;for(let L of Q||[]){let M=L[V]?.update?.after;if(M)await M(D,$)}return D}async function K(H,F,V,q){let $=await qQ(),B=H;for(let L of Q||[]){let M=L[V]?.update?.before;if(M){let I=await M(H,$);if(I===!1)return null;if(typeof I==="object"&&"data"in I)B={...B,...I.data}}}let U=q?await q.fn(B):null,D=!q||q.executeMainFn?await(await D1(Y)).updateMany({model:V,update:B,where:F}):U;for(let L of Q||[]){let M=L[V]?.update?.after;if(M)await M(D,$)}return D}async function W(H,F,V){let q=await qQ(),$=null;try{$=(await(await D1(Y)).findMany({model:F,where:H,limit:1}))[0]||null}catch(D){}if($)for(let D of Q||[]){let L=D[F]?.delete?.before;if(L){if(await L($,q)===!1)return null}}let B=V?await V.fn(H):null,U=!V||V.executeMainFn?await(await D1(Y)).delete({model:F,where:H}):B;if($)for(let D of Q||[]){let L=D[F]?.delete?.after;if(L)await L($,q)}return U}async function Z(H,F,V){let q=await qQ(),$=[];try{$=await(await D1(Y)).findMany({model:F,where:H})}catch(D){}for(let D of $)for(let L of Q||[]){let M=L[F]?.delete?.before;if(M){if(await M(D,q)===!1)return null}}let B=V?await V.fn(H):null,U=!V||V.executeMainFn?await(await D1(Y)).deleteMany({model:F,where:H}):B;for(let D of $)for(let L of Q||[]){let M=L[F]?.delete?.after;if(M)await M(D,q)}return U}return{createWithHooks:J,updateWithHooks:G,updateManyWithHooks:K,deleteWithHooks:W,deleteManyWithHooks:Z}}var JC=(Y,X)=>{let{logger:Q,options:J}=X,G=J.secondaryStorage,K=J.session?.expiresIn||604800,{createWithHooks:W,updateWithHooks:Z,updateManyWithHooks:H,deleteWithHooks:F,deleteManyWithHooks:V}=SW0(Y,X);async function q($){if(!G)return;let B=await G.get(`active-sessions-${$.id}`);if(!B)return;let U=Date.now(),D=(T1(B)||[]).filter((L)=>L.expiresAt>U);await Promise.all(D.map(async({token:L})=>{let M=await G.get(L);if(!M)return;let I=T1(M);if(!I)return;let R=Math.max(Math.floor(new Date(I.session.expiresAt).getTime()-U)/1000,0);await G.set(L,JSON.stringify({session:I.session,user:$}),Math.floor(R))}))}return{createOAuthUser:async($,B)=>{return YO(Y,async()=>{let U=await W({createdAt:new Date,updatedAt:new Date,...$},"user",void 0);return{user:U,account:await W({...B,userId:U.id,createdAt:new Date,updatedAt:new Date},"account",void 0)}})},createUser:async($)=>{return await W({createdAt:new Date,updatedAt:new Date,...$,email:$.email?.toLowerCase()},"user",void 0)},createAccount:async($)=>{return await W({createdAt:new Date,updatedAt:new Date,...$},"account",void 0)},listSessions:async($)=>{if(G){let B=await G.get(`active-sessions-${$}`);if(!B)return[];let U=T1(B)||[],D=Date.now(),L=U.filter((I)=>I.expiresAt>D),M=[];for(let I of L){let R=await G.get(I.token);if(R){let E=T1(R);if(!E)return[];let T=KG(X.options,{...E.session,expiresAt:new Date(E.session.expiresAt)});M.push(T)}}return M}return await(await D1(Y)).findMany({model:"session",where:[{field:"userId",value:$}]})},listUsers:async($,B,U,D)=>{return await(await D1(Y)).findMany({model:"user",limit:$,offset:B,sortBy:U,where:D})},countTotalUsers:async($)=>{let B=await(await D1(Y)).count({model:"user",where:$});if(typeof B==="string")return parseInt(B);return B},deleteUser:async($)=>{if(G)await G.delete(`active-sessions-${$}`);if(!G||J.session?.storeSessionInDatabase)await V([{field:"userId",value:$}],"session",void 0);await V([{field:"userId",value:$}],"account",void 0),await F([{field:"id",value:$}],"user",void 0)},createSession:async($,B,U,D)=>{let L=await qQ().catch(()=>null),M=L?.headers||L?.request?.headers,{id:I,...R}=U||{},E=Zl(L?.context.options??J,{}),T={ipAddress:L?.request||L?.headers?CZ(L?.request||L?.headers,L?.context.options)||"":"",userAgent:M?.get("user-agent")||"",...R,expiresAt:B?T8(86400,"sec"):T8(K,"sec"),userId:$,token:e8(32),createdAt:new Date,updatedAt:new Date,...E,...D?R:{}};return await W(T,"session",G?{fn:async(C)=>{let S=await G.get(`active-sessions-${$}`),k=[],_=Date.now();if(S)k=T1(S)||[],k=k.filter((d)=>d.expiresAt>_);let y=k.sort((d,Y0)=>d.expiresAt-Y0.expiresAt),f=y.at(-1)?.expiresAt;if(y.push({token:T.token,expiresAt:T.expiresAt.getTime()}),!f||f<T.expiresAt.getTime())f=T.expiresAt.getTime();let o=Math.max(Math.floor((f-_)/1000),0);if(o>0)await G.set(`active-sessions-${$}`,JSON.stringify(y),o);let g=await Y.findOne({model:"user",where:[{field:"id",value:$}]}),v=Math.max(Math.floor((T.expiresAt.getTime()-_)/1000),0);if(v>0)await G.set(T.token,JSON.stringify({session:C,user:g}),v);return C},executeMainFn:J.session?.storeSessionInDatabase}:void 0)},findSession:async($)=>{if(G){let L=await G.get($);if(!L&&!J.session?.storeSessionInDatabase)return null;if(L){let M=T1(L);if(!M)return null;return{session:KG(X.options,{...M.session,expiresAt:new Date(M.session.expiresAt),createdAt:new Date(M.session.createdAt),updatedAt:new Date(M.session.updatedAt)}),user:E9(X.options,{...M.user,createdAt:new Date(M.user.createdAt),updatedAt:new Date(M.user.updatedAt)})}}}let B=await(await D1(Y)).findOne({model:"session",where:[{value:$,field:"token"}],join:{user:!0}});if(!B)return null;let{user:U,...D}=B;if(!U)return null;return{session:KG(X.options,D),user:E9(X.options,U)}},findSessions:async($)=>{if(G){let U=[];for(let D of $){let L=await G.get(D);if(L){let M=T1(L);if(!M)return[];let I={session:{...M.session,expiresAt:new Date(M.session.expiresAt)},user:{...M.user,createdAt:new Date(M.user.createdAt),updatedAt:new Date(M.user.updatedAt)}};U.push(I)}}return U}let B=await(await D1(Y)).findMany({model:"session",where:[{field:"token",value:$,operator:"in"}],join:{user:!0}});if(!B.length)return[];if(B.some((U)=>!U.user))return[];return B.map((U)=>{let{user:D,...L}=U;return{session:L,user:D}})},updateSession:async($,B)=>{return await Z(B,[{field:"token",value:$}],"session",G?{async fn(U){let D=await G.get($),L=null;if(D){let M=T1(D);if(!M)return null;return L={...M.session,...U},L}else return null},executeMainFn:J.session?.storeSessionInDatabase}:void 0)},deleteSession:async($)=>{if(G){let B=await G.get($);if(B){let{session:U}=T1(B)??{};if(!U){Q.error("Session not found in secondary storage");return}let D=U.userId,L=await G.get(`active-sessions-${D}`);if(L){let M=T1(L)||[],I=Date.now(),R=M.filter((T)=>T.expiresAt>I&&T.token!==$),E=R.sort((T,C)=>T.expiresAt-C.expiresAt).at(-1)?.expiresAt;if(R.length>0&&E&&E>Date.now())await G.set(`active-sessions-${D}`,JSON.stringify(R),Math.floor((E-I)/1000));else await G.delete(`active-sessions-${D}`)}else Q.error("Active sessions list not found in secondary storage")}if(await G.delete($),!J.session?.storeSessionInDatabase||X.options.session?.preserveSessionInDatabase)return}await(await D1(Y)).delete({model:"session",where:[{field:"token",value:$}]})},deleteAccounts:async($)=>{await V([{field:"userId",value:$}],"account",void 0)},deleteAccount:async($)=>{await F([{field:"id",value:$}],"account",void 0)},deleteSessions:async($)=>{if(G){if(typeof $==="string"){let B=await G.get(`active-sessions-${$}`),U=B?T1(B):[];if(!U)return;for(let D of U)await G.delete(D.token)}else for(let B of $)if(await G.get(B))await G.delete(B);if(!J.session?.storeSessionInDatabase||X.options.session?.preserveSessionInDatabase)return}await V([{field:Array.isArray($)?"token":"userId",value:$,operator:Array.isArray($)?"in":void 0}],"session",void 0)},findOAuthUser:async($,B,U)=>{let D=await(await D1(Y)).findMany({model:"account",where:[{value:B,field:"accountId"}],join:{user:!0}}).then((L)=>{return L.find((M)=>M.providerId===U)});if(D)if(D.user)return{user:D.user,accounts:[D]};else{let L=await(await D1(Y)).findOne({model:"user",where:[{value:$.toLowerCase(),field:"email"}]});if(L)return{user:L,accounts:[D]};return null}else{let L=await(await D1(Y)).findOne({model:"user",where:[{value:$.toLowerCase(),field:"email"}]});if(L)return{user:L,accounts:await(await D1(Y)).findMany({model:"account",where:[{value:L.id,field:"userId"}]})||[]};else return null}},findUserByEmail:async($,B)=>{let U=await(await D1(Y)).findOne({model:"user",where:[{value:$.toLowerCase(),field:"email"}],join:{...B?.includeAccounts?{account:!0}:{}}});if(!U)return null;let{account:D,...L}=U;return{user:L,accounts:D??[]}},findUserById:async($)=>{if(!$)return null;return await(await D1(Y)).findOne({model:"user",where:[{field:"id",value:$}]})},linkAccount:async($)=>{return await W({createdAt:new Date,updatedAt:new Date,...$},"account",void 0)},updateUser:async($,B)=>{let U=await Z(B,[{field:"id",value:$}],"user",void 0);return await q(U),await q(U),U},updateUserByEmail:async($,B)=>{let U=await Z(B,[{field:"email",value:$.toLowerCase()}],"user",void 0);return await q(U),await q(U),U},updatePassword:async($,B)=>{await H({password:B},[{field:"userId",value:$},{field:"providerId",value:"credential"}],"account",void 0)},findAccounts:async($)=>{return await(await D1(Y)).findMany({model:"account",where:[{field:"userId",value:$}]})},findAccount:async($)=>{return await(await D1(Y)).findOne({model:"account",where:[{field:"accountId",value:$}]})},findAccountByProviderId:async($,B)=>{return await(await D1(Y)).findOne({model:"account",where:[{field:"accountId",value:$},{field:"providerId",value:B}]})},findAccountByUserId:async($)=>{return await(await D1(Y)).findMany({model:"account",where:[{field:"userId",value:$}]})},updateAccount:async($,B)=>{return await Z(B,[{field:"id",value:$}],"account",void 0)},createVerificationValue:async($)=>{return await W({createdAt:new Date,updatedAt:new Date,...$},"verification",void 0)},findVerificationValue:async($)=>{let B=await(await D1(Y)).findMany({model:"verification",where:[{field:"identifier",value:$}],sortBy:{field:"createdAt",direction:"desc"},limit:1});if(!J.verification?.disableCleanup)await(await D1(Y)).deleteMany({model:"verification",where:[{field:"expiresAt",value:new Date,operator:"lt"}]});return B[0]},deleteVerificationValue:async($)=>{await(await D1(Y)).delete({model:"verification",where:[{field:"id",value:$}]})},deleteVerificationByIdentifier:async($)=>{await(await D1(Y)).delete({model:"verification",where:[{field:"identifier",value:$}]})},updateVerificationValue:async($,B)=>{return await Z(B,[{field:"id",value:$}],"verification",void 0)}}};function jW0(Y){let X=VQ(Y),Q={};for(let J in X){let G=X[J],K=G.fields,W={};if(Object.entries(K).forEach(([Z,H])=>{if(W[H.fieldName||Z]=H,H.references){let F=X[H.references.model];if(F)W[H.fieldName||Z].references={...H.references,model:F.modelName,field:H.references.field}}}),Q[G.modelName]){Q[G.modelName].fields={...Q[G.modelName].fields,...W};continue}Q[G.modelName]={fields:W,order:G.order||1/0}}return Q}var WN6={postgres:{string:["character varying","varchar","text","uuid"],number:["int4","integer","bigint","smallint","numeric","real","double precision"],boolean:["bool","boolean"],date:["timestamptz","timestamp","date"],json:["json","jsonb"]},mysql:{string:["varchar","text","uuid"],number:["integer","int","bigint","smallint","decimal","float","double"],boolean:["boolean","tinyint"],date:["timestamp","datetime","date"],json:["json"]},sqlite:{string:["TEXT"],number:["INTEGER","REAL"],boolean:["INTEGER","BOOLEAN"],date:["DATE","INTEGER"],json:["TEXT"]},mssql:{string:["varchar","nvarchar","uniqueidentifier"],number:["int","bigint","smallint","decimal","float","double"],boolean:["bit","smallint"],date:["datetime2","date","datetime"],json:["varchar","nvarchar"]}};function kW0(Y,X,Q){function J(K){return K.toLowerCase().split("(")[0].trim()}if(X==="string[]"||X==="number[]")return Y.toLowerCase().includes("json");let G=WN6[Q];return(Array.isArray(X)?G.string.map((K)=>K.toLowerCase()):G[X].map((K)=>K.toLowerCase())).includes(J(Y))}async function ZN6(Y){try{let X=await FG`SHOW search_path`.execute(Y);if(X.rows[0]?.search_path)return X.rows[0].search_path.split(",").map((Q)=>Q.trim()).map((Q)=>Q.replace(/^["']|["']$/g,"")).filter((Q)=>!Q.startsWith("$"))[0]||"public"}catch(X){}return"public"}async function ZO(Y){let X=jW0(Y),Q=Bq(Y.logger),{kysely:J,databaseType:G}=await KI(Y);if(!G)Q.warn("Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this."),G="sqlite";if(!J)Q.error("Only kysely adapter is supported for migrations. You can use `generate` command to generate the schema, if you're using a different adapter."),process.exit(1);let K="public";if(G==="postgres"){K=await ZN6(J),Q.debug(`PostgreSQL migration: Using schema '${K}' (from search_path)`);try{if(!(await FG`
410
410
  SELECT schema_name
@@ -1184,4 +1184,4 @@ Please refer to the documentation here: https://better-auth.com/docs/plugins/org
1184
1184
  <h2>You've been invited!</h2>
1185
1185
  <p>${J} has invited you to join <strong>${Q.organization.name}</strong>.</p>
1186
1186
  <p><a href="${G}">Click here to accept the invitation</a></p>
1187
- `})}}}var ia4=[gn({organizationCreation:{afterCreate:async(Y)=>{await Eq6(Y.organization.id,Y.member.userId)}},ac:xf,creatorRole:"owner",allowUserToCreateOrganization:!0,dynamicAccessControl:{enabled:!0,maximumRolesPerOrganization:500,enableCustomResources:!0,allowedRolesToCreateResources:Iq6,resourceNameValidation:(Y)=>{return{valid:/^[a-zA-Z0-9-_]+$/.test(Y)}}},roles:{user:pa4,admin:ca4,owner:na4},sendInvitationEmail:kq6}),Qi({loginPage:"/login",oidcConfig:{scopes:jq6,metadata:{scopes_supported:jq6},loginPage:"/login"}}),Xi({enableMetadata:!0,maximumNameLength:64,keyExpiration:{minExpiresIn:0.003472222222222222},enableSessionForAPIKeys:!0,customAPIKeyGetter:(Y)=>{if(Y.headers?.get("X-MCP-Session-Auth")==="true")return null;let Q=Y.headers?.get("Authorization");if(Q?.startsWith("Bearer "))return Q.replace("Bearer ","").trim();return null},permissions:{defaultPermissions:{self:["ORGANIZATION_LIST","ORGANIZATION_GET","ORGANIZATION_MEMBER_LIST","COLLECTION_CONNECTIONS_LIST","COLLECTION_CONNECTIONS_GET","API_KEY_CREATE","API_KEY_LIST"]}},rateLimit:{enabled:!1}}),dn({defaultRole:"user",adminRoles:["admin","owner"]}),Gi(),nn({jwt:{expirationTime:"5m"}}),dB0(uQ.ssoConfig?Cq6(uQ.ssoConfig):void 0),...uQ.magicLinkConfig&&uQ.emailProviders&&uQ.emailProviders.length>0?[Ji(tQ6(uQ.magicLinkConfig,uQ.emailProviders))]:[]],aa4=M40(),ra4=oQ6(aa4),oB=oc({baseURL:process.env.BASE_URL||"http://localhost:3000",database:ra4,emailAndPassword:{enabled:!0},...uQ,rateLimit:{enabled:process.env.DISABLE_RATE_LIMIT!=="true",window:60,max:1e4},plugins:ia4,databaseHooks:{user:{create:{after:async(Y)=>{if(Wi.autoCreateOrganizationOnSignup===!1)return;let X=Y.name?Y.name.split(" ")[0]:Y.email.split("@")[0],Q=3;for(let J=0;J<Q;J++){let G=`${X} ${ma4()}`,K=ga4(G);try{await oB.api.createOrganization({body:{name:G,slug:K,userId:Y.id}});return}catch(W){if(!(W instanceof Error&&("body"in W)&&W.body?.code==="ORGANIZATION_ALREADY_EXISTS")||J===Q-1){console.error("Failed to create default organization:",W);return}}}}}}}});async function vq6(){console.log("\uD83D\uDD10 Running Better Auth migrations...");try{let{toBeAdded:Y,toBeCreated:X,runMigrations:Q}=await ZO(oB.options);if(!Y.length&&!X.length){console.log("\u2705 Better Auth schema is up to date (no migrations needed)");return}console.log("\uD83D\uDCCB Better Auth will create/update the following tables:");for(let J of[...X,...Y])console.log(` - ${J.table}`);await Q(),console.log("\u2705 Better Auth migrations completed successfully")}catch(Y){console.warn("\u26A0\uFE0F Better Auth migration failed (tables may be created on first use):",Y)}}async function oa4(Y){let X=new _q6({db:Y,provider:{getMigrations:()=>Promise.resolve(WI)}}),{error:Q,results:J}=await X.migrateToLatest();if(J?.forEach((G)=>{if(G.status==="Success")console.log(`\u2705 Migration "${G.migrationName}" executed successfully`);else if(G.status==="Error")console.error(`\u274C Failed to execute migration "${G.migrationName}"`)}),Q)throw console.error("Failed to migrate"),console.error(Q),Q}async function sa4(Y){let{keepOpen:X=!1,database:Q,skipBetterAuth:J=!1,seed:G}=Y??{};if(!J&&!Q)await vq6();let K=Q??Zw(),W=async()=>{if(!X&&!Q)console.log("\uD83D\uDD12 Closing database connection..."),await sQ6(K).catch((Z)=>{console.warn("Warning: Error closing database:",Z)})};try{console.log("\uD83D\uDCCA Running Kysely migrations..."),await oa4(K.db),console.log("\uD83C\uDF89 All Kysely migrations completed successfully");let Z;if(G)Z=await p50(K.db,G);return await W(),{seedResult:Z}}catch(Z){throw await W(),Z}}async function L98(){let Y=Zw(),X=new _q6({db:Y.db,provider:{getMigrations:()=>Promise.resolve(WI)}}),{error:Q,results:J}=await X.migrateDown();if(J?.forEach((G)=>{if(G.status==="Success")console.log(`\u2705 Migration "${G.migrationName}" rolled back successfully`);else if(G.status==="Error")console.error(`\u274C Failed to rollback migration "${G.migrationName}"`)}),Q)throw console.error("Failed to rollback migration"),console.error(Q),Q}if(import.meta.main)console.log("\uD83D\uDE80 Migration script starting..."),console.log("\uD83D\uDCE6 Imported migrateToLatest function"),(async()=>{console.log("\uD83C\uDFC3 Executing migration function...");try{await sa4(),console.log("\u2705 All migrations completed. Exiting..."),process.exit(0)}catch(Y){console.error("\u274C Migration failed:",Y),process.exit(1)}})();export{p50 as runSeed,oa4 as runKyselyMigrations,sa4 as migrateToLatest,L98 as migrateDown};
1187
+ `})}}}var ia4=[gn({organizationCreation:{afterCreate:async(Y)=>{await Eq6(Y.organization.id,Y.member.userId)}},ac:xf,creatorRole:"owner",allowUserToCreateOrganization:!0,dynamicAccessControl:{enabled:!0,maximumRolesPerOrganization:500,enableCustomResources:!0,allowedRolesToCreateResources:Iq6,resourceNameValidation:(Y)=>{return{valid:/^[a-zA-Z0-9-_]+$/.test(Y)}}},roles:{user:pa4,admin:ca4,owner:na4},sendInvitationEmail:kq6}),Qi({loginPage:"/login",oidcConfig:{scopes:jq6,metadata:{scopes_supported:jq6},loginPage:"/login"}}),Xi({enableMetadata:!0,maximumNameLength:64,keyExpiration:{minExpiresIn:0.003472222222222222},enableSessionForAPIKeys:!0,customAPIKeyGetter:(Y)=>{if(Y.headers?.get("X-MCP-Session-Auth")==="true")return null;let Q=Y.headers?.get("Authorization");if(Q?.startsWith("Bearer "))return Q.replace("Bearer ","").trim();return null},permissions:{defaultPermissions:{self:["ORGANIZATION_LIST","ORGANIZATION_GET","ORGANIZATION_MEMBER_LIST","COLLECTION_CONNECTIONS_LIST","COLLECTION_CONNECTIONS_GET","API_KEY_CREATE","API_KEY_LIST"]}},rateLimit:{enabled:!1}}),dn({defaultRole:"user",adminRoles:["admin","owner"]}),Gi(),nn({jwt:{expirationTime:"5m"}}),dB0(uQ.ssoConfig?Cq6(uQ.ssoConfig):void 0),...uQ.magicLinkConfig&&uQ.emailProviders&&uQ.emailProviders.length>0?[Ji(tQ6(uQ.magicLinkConfig,uQ.emailProviders))]:[]],aa4=M40(),ra4=oQ6(aa4),oB=oc({baseURL:process.env.BASE_URL||"http://localhost:3000",database:ra4,emailAndPassword:{enabled:!0},...uQ,rateLimit:{enabled:process.env.DISABLE_RATE_LIMIT!=="true",window:60,max:1e4},plugins:ia4,databaseHooks:{user:{create:{after:async(Y)=>{if(Wi.autoCreateOrganizationOnSignup===!1)return;let X=Y.name?Y.name.split(" ")[0]:Y.email.split("@")[0],Q=3;for(let J=0;J<Q;J++){let G=`${X} ${ma4()}`,K=ga4(G);try{await oB.api.createOrganization({body:{name:G,slug:K,userId:Y.id}});return}catch(W){if(!(W instanceof Error&&("body"in W)&&W.body?.code==="ORGANIZATION_ALREADY_EXISTS")||J===Q-1){console.error("Failed to create default organization:",W);return}}}}}}}});async function vq6(){console.log("\uD83D\uDD10 Running Better Auth migrations...");try{let{toBeAdded:Y,toBeCreated:X,runMigrations:Q}=await ZO(oB.options);if(!Y.length&&!X.length){console.log("\u2705 Better Auth schema is up to date (no migrations needed)");return}console.log("\uD83D\uDCCB Better Auth will create/update the following tables:");for(let J of[...X,...Y])console.log(` - ${J.table}`);await Q(),console.log("\u2705 Better Auth migrations completed successfully")}catch(Y){console.warn("\u26A0\uFE0F Better Auth migration failed (tables may be created on first use):",Y)}}async function oa4(Y){let X=new _q6({db:Y,provider:{getMigrations:()=>Promise.resolve(WI)}}),{error:Q,results:J}=await X.migrateToLatest();if(J?.forEach((G)=>{if(G.status==="Success")console.log(`\u2705 Migration "${G.migrationName}" executed successfully`);else if(G.status==="Error")console.error(`\u274C Failed to execute migration "${G.migrationName}"`)}),Q)throw console.error("Failed to migrate"),console.error(Q),Q}async function sa4(Y){let{keepOpen:X=!1,database:Q,skipBetterAuth:J=!1,seed:G}=Y??{};if(!J&&!Q)await vq6();let K=Q??Zw(),W=async()=>{if(!X&&!Q)console.log("\uD83D\uDD12 Closing database connection..."),await sQ6(K).catch((Z)=>{console.warn("Warning: Error closing database:",Z)})};try{console.log("\uD83D\uDCCA Running Kysely migrations..."),await oa4(K.db),console.log("\uD83C\uDF89 All Kysely migrations completed successfully");let Z;if(G)Z=await p50(K.db,G);return await W(),{seedResult:Z}}catch(Z){throw await W(),Z}}async function M98(){let Y=Zw(),X=new _q6({db:Y.db,provider:{getMigrations:()=>Promise.resolve(WI)}}),{error:Q,results:J}=await X.migrateDown();if(J?.forEach((G)=>{if(G.status==="Success")console.log(`\u2705 Migration "${G.migrationName}" rolled back successfully`);else if(G.status==="Error")console.error(`\u274C Failed to rollback migration "${G.migrationName}"`)}),Q)throw console.error("Failed to rollback migration"),console.error(Q),Q}if(import.meta.main)console.log("\uD83D\uDE80 Migration script starting..."),console.log("\uD83D\uDCE6 Imported migrateToLatest function"),(async()=>{console.log("\uD83C\uDFC3 Executing migration function...");try{await sa4(),console.log("\u2705 All migrations completed. Exiting..."),process.exit(0)}catch(Y){console.error("\u274C Migration failed:",Y),process.exit(1)}})();export{p50 as runSeed,oa4 as runKyselyMigrations,sa4 as migrateToLatest,M98 as migrateDown};