@lobu/runtime-server 20.0.1 → 20.1.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 (157) hide show
  1. package/dist/catalogs/connectors.json +98 -1
  2. package/dist/component.json +1 -1
  3. package/dist/connectors/chat-user-identity.ts +45 -0
  4. package/dist/connectors/google-identity.ts +107 -0
  5. package/dist/connectors/google_drive.ts +36 -151
  6. package/dist/connectors/google_gmail.ts +149 -0
  7. package/dist/connectors/microsoft_outlook.ts +193 -0
  8. package/dist/connectors/slack-identity.ts +20 -0
  9. package/dist/dependencies.bun.lock +42 -42
  10. package/dist/owletto/dist/assets/_-CfcfHJO8.js +1 -0
  11. package/dist/owletto/dist/assets/{_-BTmsEMQo.js → _-DdvHIadV.js} +2 -2
  12. package/dist/owletto/dist/assets/_agentId-BTmFhpb6.js +1 -0
  13. package/dist/owletto/dist/assets/{_agentId-DON3NuNk.js → _agentId-DbTBU4KZ.js} +1 -1
  14. package/dist/owletto/dist/assets/{_automationId-Bprfhhg8.js → _automationId-C7dZzg6X.js} +1 -1
  15. package/dist/owletto/dist/assets/{_connectorKey._connectionId-75LMK1pB.js → _connectorKey._connectionId-NQf43Ew3.js} +1 -1
  16. package/dist/owletto/dist/assets/{_connectorKey.index-N0fJPz8N.js → _connectorKey.index-D-0ZNsgM.js} +1 -1
  17. package/dist/owletto/dist/assets/{_conversationId-BY5q9MHG.js → _conversationId-F5YmyLV9.js} +1 -1
  18. package/dist/owletto/dist/assets/{_deploymentId-DFh2d5Pm.js → _deploymentId-3LTMi0ZT.js} +1 -1
  19. package/dist/owletto/dist/assets/_name-BKeZbc-h.js +1 -0
  20. package/dist/owletto/dist/assets/{_owner-B92z-CVu.js → _owner-DglbbDEx.js} +1 -1
  21. package/dist/owletto/dist/assets/_skillKey-DhiGYYFq.js +1 -0
  22. package/dist/owletto/dist/assets/{_slug-CvHxtUEf.js → _slug-CnQDfsCE.js} +1 -1
  23. package/dist/owletto/dist/assets/{accept-invitation-CXSrxBJN.js → accept-invitation-Dgoyublh.js} +1 -1
  24. package/dist/owletto/dist/assets/{activity-route-view-C9W2Ipni.js → activity-route-view-BNzKO6aD.js} +1 -1
  25. package/dist/owletto/dist/assets/{agent-card-controls-CLupkefQ.js → agent-card-controls-VJgcB5-0.js} +1 -1
  26. package/dist/owletto/dist/assets/{agent-client-setup-list-DgFv4h0W.js → agent-client-setup-list-C5KRNRw3.js} +1 -1
  27. package/dist/owletto/dist/assets/{agent-connect-pages-DT8R_qnj.js → agent-connect-pages-BFSb6vmW.js} +1 -1
  28. package/dist/owletto/dist/assets/{agent-editor-form-ayUg3Ws1.js → agent-editor-form-CajEehVn.js} +1 -1
  29. package/dist/owletto/dist/assets/{agent-guardrails-route-D-b6CIt2.js → agent-guardrails-route-CZ_rXj-3.js} +1 -1
  30. package/dist/owletto/dist/assets/{agent-loading-shells-DjMpSoub.js → agent-loading-shells-Dczhk067.js} +1 -1
  31. package/dist/owletto/dist/assets/{agent-permissions-matrix-BuGatiEq.js → agent-permissions-matrix-DIVHvpZG.js} +1 -1
  32. package/dist/owletto/dist/assets/{agent-skill-context-DKpIFmCh.js → agent-skill-context-CxglCznW.js} +1 -1
  33. package/dist/owletto/dist/assets/{agent-skills-route-DqIMttMK.js → agent-skills-route-CatU8soC.js} +1 -1
  34. package/dist/owletto/dist/assets/{agent-subpage-shell-Bojgj1uq.js → agent-subpage-shell-DVSUdIBn.js} +1 -1
  35. package/dist/owletto/dist/assets/agent-thread-DnLUOzXk.js +134 -0
  36. package/dist/owletto/dist/assets/agents-OLmcj-qM.js +1 -0
  37. package/dist/owletto/dist/assets/{agents-workbench-BojDv6gX.js → agents-workbench-BOKifKIO.js} +1 -1
  38. package/dist/owletto/dist/assets/{app._appId-DNNB5FaI.js → app._appId-BXmITXO7.js} +1 -1
  39. package/dist/owletto/dist/assets/{automation-detail-content-CzqrHc4P.js → automation-detail-content-wJC9hhmA.js} +1 -1
  40. package/dist/owletto/dist/assets/automations-OLmcj-qM.js +1 -0
  41. package/dist/owletto/dist/assets/{calendar-VAaxHxss.js → calendar-taCoBmAh.js} +1 -1
  42. package/dist/owletto/dist/assets/{callback-0VB9tUCF.js → callback-CJxC8u_x.js} +1 -1
  43. package/dist/owletto/dist/assets/{card-HMQT7vU5.js → card-kpw3EaKC.js} +1 -1
  44. package/dist/owletto/dist/assets/{claim-C2-YTMw-.js → claim-DLHRN0bA.js} +1 -1
  45. package/dist/owletto/dist/assets/{clients-C0I3V7XE.js → clients-R4JsT_Fz.js} +1 -1
  46. package/dist/owletto/dist/assets/{code-editor-hOZHdlxM.js → code-editor-D3X0yQdI.js} +1 -1
  47. package/dist/owletto/dist/assets/connect-1ysEq9l0.js +1 -0
  48. package/dist/owletto/dist/assets/connect._clientId-BbMPs6l3.js +1 -0
  49. package/dist/owletto/dist/assets/{connected._clientId-BFuU4-8j.js → connected._clientId-ByH4etku.js} +1 -1
  50. package/dist/owletto/dist/assets/{connection-De_2AD46.js → connection-DdBkXNbX.js} +1 -1
  51. package/dist/owletto/dist/assets/{connection-feed-detail-Cbn85fG9.js → connection-feed-detail-DF93zx0A.js} +1 -1
  52. package/dist/owletto/dist/assets/{connector-provenance-B17-ze5S.js → connector-provenance-N3sc0nbo.js} +1 -1
  53. package/dist/owletto/dist/assets/{connectors-KnNED_-4.js → connectors-Ckn_aoNE.js} +1 -1
  54. package/dist/owletto/dist/assets/{consent-BOYb4pNu.js → consent-Bi6KCVtT.js} +1 -1
  55. package/dist/owletto/dist/assets/{core.esm-COW6Pfy6.js → core.esm-CFYXLQXH.js} +1 -1
  56. package/dist/owletto/dist/assets/{create-BFpUZ_mU.js → create-BiHpu2f4.js} +1 -1
  57. package/dist/owletto/dist/assets/create-C37QtjbJ.js +1 -0
  58. package/dist/owletto/dist/assets/{create-automation-form-CRenA7Ix.js → create-automation-form-Cv2RHsQ6.js} +1 -1
  59. package/dist/owletto/dist/assets/create-kAQa5_Q7.js +1 -0
  60. package/dist/owletto/dist/assets/{create._connectorKey-D4dIDQIQ.js → create._connectorKey-Qynix_hA.js} +1 -1
  61. package/dist/owletto/dist/assets/{cronstrue-BrlFh5Jy.js → cronstrue-D7xlYtGk.js} +1 -1
  62. package/dist/owletto/dist/assets/deployments-C5kSeowq.js +1 -0
  63. package/dist/owletto/dist/assets/{deployments-body-CXqfjLqj.js → deployments-body-BPCALbQe.js} +1 -1
  64. package/dist/owletto/dist/assets/{device-B0BBIdVx.js → device-DToHXxDM.js} +1 -1
  65. package/dist/owletto/dist/assets/{device-pin-tombstone-BBYes4en.js → device-pin-tombstone-DrTJYNKG.js} +1 -1
  66. package/dist/owletto/dist/assets/{device-rows-E63OZ9Cp.js → device-rows-fVm-zAiU.js} +1 -1
  67. package/dist/owletto/dist/assets/{device._deviceId-JN0cUCGe.js → device._deviceId-CIe7taim.js} +1 -1
  68. package/dist/owletto/dist/assets/{entity-options-qan9-Ycm.js → entity-options-DOGD_EyZ.js} +1 -1
  69. package/dist/owletto/dist/assets/{entity-page-CozUOlVP.js → entity-page-C8oDszRY.js} +1 -1
  70. package/dist/owletto/dist/assets/{entity-type-page-xISySjVW.js → entity-type-page-BfxIgJLq.js} +1 -1
  71. package/dist/owletto/dist/assets/{events-feed-DmZ3Ig3X.js → events-feed-B9OqmSBy.js} +1 -1
  72. package/dist/owletto/dist/assets/{full-page-spinner-Q_J5Wcop.js → full-page-spinner-DTSqneUO.js} +1 -1
  73. package/dist/owletto/dist/assets/guardrails-9Mr6avxk.js +1 -0
  74. package/dist/owletto/dist/assets/identity-DMfCjdBz.js +1 -0
  75. package/dist/owletto/dist/assets/{index-BKZMzuMS.js → index-Bfux0kHb.js} +34 -34
  76. package/dist/owletto/dist/assets/{index-pKfsEvLt.js → index-Bq4m-sK0.js} +1 -1
  77. package/dist/owletto/dist/assets/{index-CGx4og7r.js → index-CK2-iHcz.js} +1 -1
  78. package/dist/owletto/dist/assets/{index-C78ucWDF.js → index-CMOHHdFH.js} +1 -1
  79. package/dist/owletto/dist/assets/{index-BwVojwkg.js → index-COgBJ_ab.js} +1 -1
  80. package/dist/owletto/dist/assets/index-CkwwaMrx.js +1 -0
  81. package/dist/owletto/dist/assets/index-D0lZrXrY.js +1 -0
  82. package/dist/owletto/dist/assets/{index-DmB-3GhU.js → index-DYe_DVHa.js} +1 -1
  83. package/dist/owletto/dist/assets/index-DZadnZpq.js +1 -0
  84. package/dist/owletto/dist/assets/{index-DLZbFRSM.js → index-DcWyuLQS.js} +1 -1
  85. package/dist/owletto/dist/assets/{index-BwN9pHNs.js → index-DkKALC2l.js} +1 -1
  86. package/dist/owletto/dist/assets/index-DlqjyZKQ.js +1 -0
  87. package/dist/owletto/dist/assets/index-Dv0huHrO.js +1 -0
  88. package/dist/owletto/dist/assets/index-DxIDxgPJ.js +1 -0
  89. package/dist/owletto/dist/assets/index-bKUccXCc.js +1 -0
  90. package/dist/owletto/dist/assets/{index-C9Dtjaoi.js → index-jGZeANLE.js} +1 -1
  91. package/dist/owletto/dist/assets/{json-diff-1FNS_wGA.js → json-diff-CANZD4MQ.js} +1 -1
  92. package/dist/owletto/dist/assets/{list-skeleton-B6gjzr8t.js → list-skeleton-DZTUxpBx.js} +1 -1
  93. package/dist/owletto/dist/assets/{login-S9EGV_EA.js → login-D53geSP7.js} +1 -1
  94. package/dist/owletto/dist/assets/{logout-BOXPSr57.js → logout-DKQS25qd.js} +1 -1
  95. package/dist/owletto/dist/assets/{member-scope-gate-yGr4lrGD.js → member-scope-gate-C4QyRm2Q.js} +1 -1
  96. package/dist/owletto/dist/assets/{memory-browse-page-5n3MvqdS.js → memory-browse-page-DOpV3vht.js} +1 -1
  97. package/dist/owletto/dist/assets/{model-selector-9ZRlR7Sa.js → model-selector-CvU3VP90.js} +1 -1
  98. package/dist/owletto/dist/assets/models-ooBIWFuB.js +1 -0
  99. package/dist/owletto/dist/assets/new-B8_sRMYD.js +1 -0
  100. package/dist/owletto/dist/assets/{new-D4wlbvAZ.js → new-DIjOVXrQ.js} +1 -1
  101. package/dist/owletto/dist/assets/{new-BeZJOJgR.js → new-Df1q7GEj.js} +1 -1
  102. package/dist/owletto/dist/assets/{oauth-workspace-access-DoE-9F42.js → oauth-workspace-access-DWfiekRz.js} +1 -1
  103. package/dist/owletto/dist/assets/{organization-BezNEJK7.js → organization-DHEC7kDq.js} +1 -1
  104. package/dist/owletto/dist/assets/{permissions-GkKtC6a5.js → permissions-i7iwnE1a.js} +1 -1
  105. package/dist/owletto/dist/assets/{proposal-review-shell-Bk9D_9YN.js → proposal-review-shell-C_LcyUEF.js} +1 -1
  106. package/dist/owletto/dist/assets/{recent-BVvscz1V.js → recent-By19_Buq.js} +1 -1
  107. package/dist/owletto/dist/assets/{renderer-CAyr3B3s.js → renderer-B1UThnk2.js} +1 -1
  108. package/dist/owletto/dist/assets/{reset-password-atCMI5uQ.js → reset-password-Dsz5-Xeo.js} +1 -1
  109. package/dist/owletto/dist/assets/{runs-CftQDTkq.js → runs-BQ11PAQT.js} +1 -1
  110. package/dist/owletto/dist/assets/{runs-panel-BkRtr_C4.js → runs-panel-wkV1aGD9.js} +1 -1
  111. package/dist/owletto/dist/assets/{runs-table-CWCl38L5.js → runs-table-DzSWYkaf.js} +1 -1
  112. package/dist/owletto/dist/assets/{schema-value-normalization-C9Lm83-q.js → schema-value-normalization--DhnhJNf.js} +1 -1
  113. package/dist/owletto/dist/assets/{settings-CgTgofgd.js → settings-Bu239SXe.js} +1 -1
  114. package/dist/owletto/dist/assets/settings-FxbIvOhH.js +1 -0
  115. package/dist/owletto/dist/assets/skills-MBZ5ilDK.js +1 -0
  116. package/dist/owletto/dist/assets/{switch-BOGbkDQb.js → switch-CCKllS7w.js} +1 -1
  117. package/dist/owletto/dist/assets/{use-mention-search-C9ckRw0s.js → use-mention-search-CldNZTiT.js} +1 -1
  118. package/dist/owletto/dist/index.html +1 -1
  119. package/dist/server-main.bundle.mjs +3950 -3509
  120. package/npm-shrinkwrap.json +164 -160
  121. package/package.json +1 -1
  122. package/vendor/connector-sdk/dist/file-output.d.ts +97 -0
  123. package/vendor/connector-sdk/dist/file-output.js +176 -0
  124. package/vendor/connector-sdk/dist/index.d.ts +2 -0
  125. package/vendor/connector-sdk/dist/index.js +1 -0
  126. package/vendor/connector-sdk/package.json +1 -1
  127. package/vendor/core/dist/classify-error.js +50 -2
  128. package/vendor/core/dist/constants.d.ts +13 -6
  129. package/vendor/core/dist/constants.js +22 -8
  130. package/vendor/core/dist/errors.d.ts +20 -0
  131. package/vendor/core/dist/errors.js +21 -1
  132. package/vendor/core/package.json +1 -1
  133. package/dist/owletto/dist/assets/_-ea0K1u_g.js +0 -1
  134. package/dist/owletto/dist/assets/_agentId-qF8hi8Cf.js +0 -1
  135. package/dist/owletto/dist/assets/_name-OY_X_Zm-.js +0 -1
  136. package/dist/owletto/dist/assets/_skillKey-CeEE23_w.js +0 -1
  137. package/dist/owletto/dist/assets/agent-thread-R8Pego9t.js +0 -134
  138. package/dist/owletto/dist/assets/agents-C9x76gSX.js +0 -1
  139. package/dist/owletto/dist/assets/automations-C9x76gSX.js +0 -1
  140. package/dist/owletto/dist/assets/connect-DSr_gD8x.js +0 -1
  141. package/dist/owletto/dist/assets/connect._clientId-CTamwGrw.js +0 -1
  142. package/dist/owletto/dist/assets/create-CblXKFGZ.js +0 -1
  143. package/dist/owletto/dist/assets/create-ChUbSYvl.js +0 -1
  144. package/dist/owletto/dist/assets/deployments-DTFrUY7p.js +0 -1
  145. package/dist/owletto/dist/assets/guardrails-BB9iOxE3.js +0 -1
  146. package/dist/owletto/dist/assets/identity-DYbfG4hU.js +0 -1
  147. package/dist/owletto/dist/assets/index-7d9B918E.js +0 -1
  148. package/dist/owletto/dist/assets/index-BsDA0XzK.js +0 -1
  149. package/dist/owletto/dist/assets/index-C4Lz_gB-.js +0 -1
  150. package/dist/owletto/dist/assets/index-CO65Rkad.js +0 -1
  151. package/dist/owletto/dist/assets/index-CT_kxGkR.js +0 -1
  152. package/dist/owletto/dist/assets/index-CrKgNtiq.js +0 -1
  153. package/dist/owletto/dist/assets/index-DUIbfL6x.js +0 -1
  154. package/dist/owletto/dist/assets/models-LOhfJ0sb.js +0 -1
  155. package/dist/owletto/dist/assets/new-Dxn1qrmS.js +0 -1
  156. package/dist/owletto/dist/assets/settings-BKMOjfYf.js +0 -1
  157. package/dist/owletto/dist/assets/skills-DWr8qR3U.js +0 -1
@@ -1,134 +0,0 @@
1
- import{j as d,r as m,eY as _a,cU as ba,eZ as ya,ex as wa,an as Yn,ag as Hn,ao as eo,d2 as ka,e_ as $a,e$ as Sa,L as as,aj as fe,dr as xa,dz as cs,dB as Ra,f0 as za,cP as Ta,dC as Ia,f1 as Ea,B as it,f2 as Ca,f3 as Pa,f4 as Qn,X as Na,s as Za,dA as Oa,aS as Kt,f5 as Aa,ci as ja,cj as Ma,f6 as La,ck as Da,bI as Ua,f7 as qa,f8 as Fa,eM as Ha,bF as Va,ef as Ba,eg as Ja}from"./index-BKZMzuMS.js";import{A as Wa,a as Ka,b as Ga,c as hr,d as us,e as Ya}from"./agent-loading-shells-DjMpSoub.js";import{t as Qa}from"./pending-seed-CPbfgnLX.js";import{h as Xa,t as ec,R as tc,i as nc,u as rc,b as oc,f as sc}from"./use-mention-search-C9ckRw0s.js";var to;function v(e,t,n){function r(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:i,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,c);const u=i.prototype,l=Object.keys(u);for(let p=0;p<l.length;p++){const h=l[p];h in a||(a[h]=u[h].bind(a))}}const o=n?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:e});function i(a){var c;const u=n?.Parent?new s:this;r(u,a),(c=u._zod).deferred??(c.deferred=[]);for(const l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}let xt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};class ls extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(to=globalThis).__zod_globalConfig??(to.__zod_globalConfig={});const fr=globalThis.__zod_globalConfig;function et(e){return fr}function ds(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,o])=>t.indexOf(+r)===-1).map(([r,o])=>o)}function Xn(e,t){return typeof t=="bigint"?t.toString():t}function Zn(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function mr(e){return e==null}function gr(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function ic(e,t){const n=e/t,r=Math.round(n),o=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-r)<o?0:n-r}const no=Symbol("evaluating");function J(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==no)return r===void 0&&(r=no,r=n()),r},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function vt(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function ut(...e){const t={};for(const n of e){const r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function ro(e){return JSON.stringify(e)}function ac(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const ps="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Ut(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const cc=Zn(()=>{if(fr.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Rt(e){if(Ut(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Ut(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function hs(e){return Rt(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const uc=new Set(["string","number","symbol"]);function zt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function lt(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function z(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function lc(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const dc={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function pc(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const s=ut(e._zod.def,{get shape(){const i={};for(const a in t){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&(i[a]=n.shape[a])}return vt(this,"shape",i),i},checks:[]});return lt(e,s)}function hc(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const s=ut(e._zod.def,{get shape(){const i={...e._zod.def.shape};for(const a in t){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&delete i[a]}return vt(this,"shape",i),i},checks:[]});return lt(e,s)}function fc(e,t){if(!Rt(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const s=e._zod.def.shape;for(const i in t)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const o=ut(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t};return vt(this,"shape",s),s}});return lt(e,o)}function mc(e,t){if(!Rt(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=ut(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return vt(this,"shape",r),r}});return lt(e,n)}function gc(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n=ut(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return vt(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return lt(e,n)}function vc(e,t,n){const o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const i=ut(t._zod.def,{get shape(){const a=t._zod.def.shape,c={...a};if(n)for(const u in n){if(!(u in a))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(c[u]=e?new e({type:"optional",innerType:a[u]}):a[u])}else for(const u in a)c[u]=e?new e({type:"optional",innerType:a[u]}):a[u];return vt(this,"shape",c),c},checks:[]});return lt(t,i)}function _c(e,t,n){const r=ut(t._zod.def,{get shape(){const o=t._zod.def.shape,s={...o};if(n)for(const i in n){if(!(i in s))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(s[i]=new e({type:"nonoptional",innerType:o[i]}))}else for(const i in o)s[i]=new e({type:"nonoptional",innerType:o[i]});return vt(this,"shape",s),s}});return lt(t,r)}function $t(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function bc(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function St(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function fn(e){return typeof e=="string"?e:e?.message}function tt(e,t,n){const r=e.message?e.message:fn(e.inst?._zod.def?.error?.(e))??fn(t?.error?.(e))??fn(n.customError?.(e))??fn(n.localeError?.(e))??"Invalid input",{inst:o,continue:s,input:i,...a}=e;return a.path??(a.path=[]),a.message=r,t?.reportInput&&(a.input=i),a}function vr(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function qt(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const fs=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Xn,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ms=v("$ZodError",fs),gs=v("$ZodError",fs,{Parent:Error});function yc(e,t=n=>n.message){const n={},r=[];for(const o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}function wc(e,t=n=>n.message){const n={_errors:[]},r=(o,s=[])=>{for(const i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>r({issues:a},[...s,...i.path]));else if(i.code==="invalid_key")r({issues:i.issues},[...s,...i.path]);else if(i.code==="invalid_element")r({issues:i.issues},[...s,...i.path]);else{const a=[...s,...i.path];if(a.length===0)n._errors.push(t(i));else{let c=n,u=0;for(;u<a.length;){const l=a[u];u===a.length-1?(c[l]=c[l]||{_errors:[]},c[l]._errors.push(t(i))):c[l]=c[l]||{_errors:[]},c=c[l],u++}}}};return r(e),n}const _r=e=>(t,n,r,o)=>{const s=r?{...r,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},s);if(i instanceof Promise)throw new xt;if(i.issues.length){const a=new(o?.Err??e)(i.issues.map(c=>tt(c,s,et())));throw ps(a,o?.callee),a}return i.value},br=e=>async(t,n,r,o)=>{const s=r?{...r,async:!0}:{async:!0};let i=t._zod.run({value:n,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){const a=new(o?.Err??e)(i.issues.map(c=>tt(c,s,et())));throw ps(a,o?.callee),a}return i.value},On=e=>(t,n,r)=>{const o=r?{...r,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new xt;return s.issues.length?{success:!1,error:new(e??ms)(s.issues.map(i=>tt(i,o,et())))}:{success:!0,data:s.value}},vs=On(gs),An=e=>async(t,n,r)=>{const o=r?{...r,async:!0}:{async:!0};let s=t._zod.run({value:n,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(i=>tt(i,o,et())))}:{success:!0,data:s.value}},kc=An(gs),$c=e=>(t,n,r)=>{const o=r?{...r,direction:"backward"}:{direction:"backward"};return _r(e)(t,n,o)},Sc=e=>(t,n,r)=>_r(e)(t,n,r),xc=e=>async(t,n,r)=>{const o=r?{...r,direction:"backward"}:{direction:"backward"};return br(e)(t,n,o)},Rc=e=>async(t,n,r)=>br(e)(t,n,r),zc=e=>(t,n,r)=>{const o=r?{...r,direction:"backward"}:{direction:"backward"};return On(e)(t,n,o)},Tc=e=>(t,n,r)=>On(e)(t,n,r),Ic=e=>async(t,n,r)=>{const o=r?{...r,direction:"backward"}:{direction:"backward"};return An(e)(t,n,o)},Ec=e=>async(t,n,r)=>An(e)(t,n,r),Cc=/^[cC][0-9a-z]{6,}$/,Pc=/^[0-9a-z]+$/,Nc=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Zc=/^[0-9a-vA-V]{20}$/,Oc=/^[A-Za-z0-9]{27}$/,Ac=/^[a-zA-Z0-9_-]{21}$/,jc=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Mc=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,oo=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Lc=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Dc="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Uc(){return new RegExp(Dc,"u")}const qc=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Fc=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Hc=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Vc=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Bc=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,_s=/^[A-Za-z0-9_-]*$/,Jc=/^https?$/,Wc=/^\+[1-9]\d{6,14}$/,bs="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Kc=new RegExp(`^${bs}$`);function ys(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Gc(e){return new RegExp(`^${ys(e)}$`)}function Yc(e){const t=ys({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${bs}T(?:${r})$`)}const Qc=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Xc=/^-?\d+$/,ws=/^-?\d+(?:\.\d+)?$/,eu=/^(?:true|false)$/i,tu=/^null$/i,nu=/^[^A-Z]*$/,ru=/^[^a-z]*$/,Ae=v("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),ks={number:"number",bigint:"bigint",object:"date"},$s=v("$ZodCheckLessThan",(e,t)=>{Ae.init(e,t);const n=ks[typeof t.value];e._zod.onattach.push(r=>{const o=r._zod.bag,s=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ss=v("$ZodCheckGreaterThan",(e,t)=>{Ae.init(e,t);const n=ks[typeof t.value];e._zod.onattach.push(r=>{const o=r._zod.bag,s=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ou=v("$ZodCheckMultipleOf",(e,t)=>{Ae.init(e,t),e._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):ic(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),su=v("$ZodCheckNumberFormat",(e,t)=>{Ae.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[o,s]=dc[t.format];e._zod.onattach.push(i=>{const a=i._zod.bag;a.format=t.format,a.minimum=o,a.maximum=s,n&&(a.pattern=Xc)}),e._zod.check=i=>{const a=i.value;if(n){if(!Number.isInteger(a)){i.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}}),iu=v("$ZodCheckMaxLength",(e,t)=>{var n;Ae.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!mr(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const o=r.value;if(o.length<=t.maximum)return;const i=vr(o);r.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),au=v("$ZodCheckMinLength",(e,t)=>{var n;Ae.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!mr(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const o=r.value;if(o.length>=t.minimum)return;const i=vr(o);r.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),cu=v("$ZodCheckLengthEquals",(e,t)=>{var n;Ae.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!mr(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=r=>{const o=r.value,s=o.length;if(s===t.length)return;const i=vr(o),a=s>t.length;r.issues.push({origin:i,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),jn=v("$ZodCheckStringFormat",(e,t)=>{var n,r;Ae.init(e,t),e._zod.onattach.push(o=>{const s=o._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),uu=v("$ZodCheckRegex",(e,t)=>{jn.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),lu=v("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=nu),jn.init(e,t)}),du=v("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=ru),jn.init(e,t)}),pu=v("$ZodCheckIncludes",(e,t)=>{Ae.init(e,t);const n=zt(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(o=>{const s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),hu=v("$ZodCheckStartsWith",(e,t)=>{Ae.init(e,t);const n=new RegExp(`^${zt(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),fu=v("$ZodCheckEndsWith",(e,t)=>{Ae.init(e,t);const n=new RegExp(`.*${zt(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),mu=v("$ZodCheckOverwrite",(e,t)=>{Ae.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});let gu=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(`
2
- `).filter(i=>i),o=Math.min(...r.map(i=>i.length-i.trimStart().length)),s=r.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(const i of s)this.content.push(i)}compile(){const t=Function,n=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new t(...n,o.join(`
3
- `))}};const vu={major:4,minor:4,patch:3},re=v("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=vu;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const o of r)for(const s of o._zod.onattach)s(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=(i,a,c)=>{let u=$t(i),l;for(const p of a){if(p._zod.def.when){if(bc(i)||!p._zod.def.when(i))continue}else if(u)continue;const h=i.issues.length,f=p._zod.check(i);if(f instanceof Promise&&c?.async===!1)throw new xt;if(l||f instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await f,i.issues.length!==h&&(u||(u=$t(i,h)))});else{if(i.issues.length===h)continue;u||(u=$t(i,h))}}return l?l.then(()=>i):i},s=(i,a,c)=>{if($t(i))return i.aborted=!0,i;const u=o(a,r,c);if(u instanceof Promise){if(c.async===!1)throw new xt;return u.then(l=>e._zod.parse(l,c))}return e._zod.parse(u,c)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction==="backward"){const u=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return u instanceof Promise?u.then(l=>s(l,i,a)):s(u,i,a)}const c=e._zod.parse(i,a);if(c instanceof Promise){if(a.async===!1)throw new xt;return c.then(u=>o(u,r,a))}return o(c,r,a)}}J(e,"~standard",()=>({validate:o=>{try{const s=vs(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return kc(e,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),yr=v("$ZodString",(e,t)=>{re.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Qc(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),oe=v("$ZodStringFormat",(e,t)=>{jn.init(e,t),yr.init(e,t)}),_u=v("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Mc),oe.init(e,t)}),bu=v("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=oo(r))}else t.pattern??(t.pattern=oo());oe.init(e,t)}),yu=v("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Lc),oe.init(e,t)}),wu=v("$ZodURL",(e,t)=>{oe.init(e,t),e._zod.check=n=>{try{const r=n.value.trim();if(!t.normalize&&t.protocol?.source===Jc.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}const o=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=o.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),ku=v("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Uc()),oe.init(e,t)}),$u=v("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Ac),oe.init(e,t)}),Su=v("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Cc),oe.init(e,t)}),xu=v("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Pc),oe.init(e,t)}),Ru=v("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Nc),oe.init(e,t)}),zu=v("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Zc),oe.init(e,t)}),Tu=v("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Oc),oe.init(e,t)}),Iu=v("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Yc(t)),oe.init(e,t)}),Eu=v("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Kc),oe.init(e,t)}),Cu=v("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Gc(t)),oe.init(e,t)}),Pu=v("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=jc),oe.init(e,t)}),Nu=v("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=qc),oe.init(e,t),e._zod.bag.format="ipv4"}),Zu=v("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Fc),oe.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),Ou=v("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Hc),oe.init(e,t)}),Au=v("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Vc),oe.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[o,s]=r;if(!s)throw new Error;const i=Number(s);if(`${i}`!==s)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${o}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function xs(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const ju=v("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Bc),oe.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{xs(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function Mu(e){if(!_s.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return xs(n)}const Lu=v("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=_s),oe.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{Mu(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Du=v("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Wc),oe.init(e,t)});function Uu(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const o=JSON.parse(atob(r));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const qu=v("$ZodJWT",(e,t)=>{oe.init(e,t),e._zod.check=n=>{Uu(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Rs=v("$ZodNumber",(e,t)=>{re.init(e,t),e._zod.pattern=e._zod.bag.pattern??ws,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;const s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),n}}),Fu=v("$ZodNumberFormat",(e,t)=>{su.init(e,t),Rs.init(e,t)}),Hu=v("$ZodBoolean",(e,t)=>{re.init(e,t),e._zod.pattern=eu,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}}),Vu=v("$ZodNull",(e,t)=>{re.init(e,t),e._zod.pattern=tu,e._zod.values=new Set([null]),e._zod.parse=(n,r)=>{const o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),n}}),Bu=v("$ZodUnknown",(e,t)=>{re.init(e,t),e._zod.parse=n=>n}),Ju=v("$ZodNever",(e,t)=>{re.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function so(e,t,n){e.issues.length&&t.issues.push(...St(n,e.issues)),t.value[n]=e.value}const Wu=v("$ZodArray",(e,t)=>{re.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);const s=[];for(let i=0;i<o.length;i++){const a=o[i],c=t.element._zod.run({value:a,issues:[]},r);c instanceof Promise?s.push(c.then(u=>so(u,n,i))):so(c,n,i)}return s.length?Promise.all(s).then(()=>n):n}});function $n(e,t,n,r,o,s){const i=n in r;if(e.issues.length){if(o&&s&&!i)return;t.issues.push(...St(n,e.issues))}if(!i&&!o){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?i&&(t.value[n]=void 0):t.value[n]=e.value}function zs(e){const t=Object.keys(e.shape);for(const r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const n=lc(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Ts(e,t,n,r,o,s){const i=[],a=o.keySet,c=o.catchall._zod,u=c.def.type,l=c.optin==="optional",p=c.optout==="optional";for(const h in t){if(h==="__proto__"||a.has(h))continue;if(u==="never"){i.push(h);continue}const f=c.run({value:t[h],issues:[]},r);f instanceof Promise?e.push(f.then(y=>$n(y,n,h,t,l,p))):$n(f,n,h,t,l,p)}return i.length&&n.issues.push({code:"unrecognized_keys",keys:i,input:t,inst:s}),e.length?Promise.all(e).then(()=>n):n}const Ku=v("$ZodObject",(e,t)=>{if(re.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const a=t.shape;Object.defineProperty(t,"shape",{get:()=>{const c={...a};return Object.defineProperty(t,"shape",{value:c}),c}})}const r=Zn(()=>zs(t));J(e._zod,"propValues",()=>{const a=t.shape,c={};for(const u in a){const l=a[u]._zod;if(l.values){c[u]??(c[u]=new Set);for(const p of l.values)c[u].add(p)}}return c});const o=Ut,s=t.catchall;let i;e._zod.parse=(a,c)=>{i??(i=r.value);const u=a.value;if(!o(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),a;a.value={};const l=[],p=i.shape;for(const h of i.keys){const f=p[h],y=f._zod.optin==="optional",P=f._zod.optout==="optional",S=f._zod.run({value:u[h],issues:[]},c);S instanceof Promise?l.push(S.then(j=>$n(j,a,h,u,y,P))):$n(S,a,h,u,y,P)}return s?Ts(l,u,a,c,r.value,e):l.length?Promise.all(l).then(()=>a):a}}),Gu=v("$ZodObjectJIT",(e,t)=>{Ku.init(e,t);const n=e._zod.parse,r=Zn(()=>zs(t)),o=h=>{const f=new gu(["shape","payload","ctx"]),y=r.value,P=w=>{const k=ro(w);return`shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`};f.write("const input = payload.value;");const S=Object.create(null);let j=0;for(const w of y.keys)S[w]=`key_${j++}`;f.write("const newResult = {};");for(const w of y.keys){const k=S[w],O=ro(w),M=h[w],K=M?._zod?.optin==="optional",Se=M?._zod?.optout==="optional";f.write(`const ${k} = ${P(w)};`),K&&Se?f.write(`
4
- if (${k}.issues.length) {
5
- if (${O} in input) {
6
- payload.issues = payload.issues.concat(${k}.issues.map(iss => ({
7
- ...iss,
8
- path: iss.path ? [${O}, ...iss.path] : [${O}]
9
- })));
10
- }
11
- }
12
-
13
- if (${k}.value === undefined) {
14
- if (${O} in input) {
15
- newResult[${O}] = undefined;
16
- }
17
- } else {
18
- newResult[${O}] = ${k}.value;
19
- }
20
-
21
- `):K?f.write(`
22
- if (${k}.issues.length) {
23
- payload.issues = payload.issues.concat(${k}.issues.map(iss => ({
24
- ...iss,
25
- path: iss.path ? [${O}, ...iss.path] : [${O}]
26
- })));
27
- }
28
-
29
- if (${k}.value === undefined) {
30
- if (${O} in input) {
31
- newResult[${O}] = undefined;
32
- }
33
- } else {
34
- newResult[${O}] = ${k}.value;
35
- }
36
-
37
- `):f.write(`
38
- const ${k}_present = ${O} in input;
39
- if (${k}.issues.length) {
40
- payload.issues = payload.issues.concat(${k}.issues.map(iss => ({
41
- ...iss,
42
- path: iss.path ? [${O}, ...iss.path] : [${O}]
43
- })));
44
- }
45
- if (!${k}_present && !${k}.issues.length) {
46
- payload.issues.push({
47
- code: "invalid_type",
48
- expected: "nonoptional",
49
- input: undefined,
50
- path: [${O}]
51
- });
52
- }
53
-
54
- if (${k}_present) {
55
- if (${k}.value === undefined) {
56
- newResult[${O}] = undefined;
57
- } else {
58
- newResult[${O}] = ${k}.value;
59
- }
60
- }
61
-
62
- `)}f.write("payload.value = newResult;"),f.write("return payload;");const R=f.compile();return(w,k)=>R(h,w,k)};let s;const i=Ut,a=!fr.jitless,u=a&&cc.value,l=t.catchall;let p;e._zod.parse=(h,f)=>{p??(p=r.value);const y=h.value;return i(y)?a&&u&&f?.async===!1&&f.jitless!==!0?(s||(s=o(t.shape)),h=s(h,f),l?Ts([],y,h,f,p,e):h):n(h,f):(h.issues.push({expected:"object",code:"invalid_type",input:y,inst:e}),h)}});function io(e,t,n,r){for(const s of e)if(s.issues.length===0)return t.value=s.value,t;const o=e.filter(s=>!$t(s));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(s=>s.issues.map(i=>tt(i,r,et())))}),t)}const Is=v("$ZodUnion",(e,t)=>{re.init(e,t),J(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),J(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),J(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),J(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(o=>o._zod.pattern);return new RegExp(`^(${r.map(o=>gr(o.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,o)=>{if(n)return n(r,o);let s=!1;const i=[];for(const a of t.options){const c=a._zod.run({value:r.value,issues:[]},o);if(c instanceof Promise)i.push(c),s=!0;else{if(c.issues.length===0)return c;i.push(c)}}return s?Promise.all(i).then(a=>io(a,r,e,o)):io(i,r,e,o)}}),Yu=v("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Is.init(e,t);const n=e._zod.parse;J(e._zod,"propValues",()=>{const o={};for(const s of t.options){const i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(const u of c)o[a].add(u)}}return o});const r=Zn(()=>{const o=t.options,s=new Map;for(const i of o){const a=i._zod.propValues?.[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(const c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});e._zod.parse=(o,s)=>{const i=o.value;if(!Ut(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),o;const a=r.value.get(i?.[t.discriminator]);return a?a._zod.run(o,s):t.unionFallback||s.direction==="backward"?n(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(r.value.keys()),input:i,path:[t.discriminator],inst:e}),o)}}),Qu=v("$ZodIntersection",(e,t)=>{re.init(e,t),e._zod.parse=(n,r)=>{const o=n.value,s=t.left._zod.run({value:o,issues:[]},r),i=t.right._zod.run({value:o,issues:[]},r);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>ao(n,c,u)):ao(n,s,i)}});function er(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Rt(e)&&Rt(t)){const n=Object.keys(t),r=Object.keys(e).filter(s=>n.indexOf(s)!==-1),o={...e,...t};for(const s of r){const i=er(e[s],t[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const o=e[r],s=t[r],i=er(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function ao(e,t,n){const r=new Map;let o;for(const a of t.issues)if(a.code==="unrecognized_keys"){o??(o=a);for(const c of a.keys)r.has(c)||r.set(c,{}),r.get(c).l=!0}else e.issues.push(a);for(const a of n.issues)if(a.code==="unrecognized_keys")for(const c of a.keys)r.has(c)||r.set(c,{}),r.get(c).r=!0;else e.issues.push(a);const s=[...r].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(s.length&&o&&e.issues.push({...o,keys:s}),$t(e))return e;const i=er(t.value,n.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return e.value=i.data,e}const Xu=v("$ZodRecord",(e,t)=>{re.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!Rt(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;const s=[],i=t.keyType._zod.values;if(i){n.value={};const a=new Set;for(const u of i)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){a.add(typeof u=="number"?u.toString():u);const l=t.keyType._zod.run({value:u,issues:[]},r);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(l.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(f=>tt(f,r,et())),input:u,path:[u],inst:e});continue}const p=l.value,h=t.valueType._zod.run({value:o[u],issues:[]},r);h instanceof Promise?s.push(h.then(f=>{f.issues.length&&n.issues.push(...St(u,f.issues)),n.value[p]=f.value})):(h.issues.length&&n.issues.push(...St(u,h.issues)),n.value[p]=h.value)}let c;for(const u in o)a.has(u)||(c=c??[],c.push(u));c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:c})}else{n.value={};for(const a of Reflect.ownKeys(o)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,a))continue;let c=t.keyType._zod.run({value:a,issues:[]},r);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&ws.test(a)&&c.issues.length){const p=t.keyType._zod.run({value:Number(a),issues:[]},r);if(p instanceof Promise)throw new Error("Async schemas not supported in object keys currently");p.issues.length===0&&(c=p)}if(c.issues.length){t.mode==="loose"?n.value[a]=o[a]:n.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(p=>tt(p,r,et())),input:a,path:[a],inst:e});continue}const l=t.valueType._zod.run({value:o[a],issues:[]},r);l instanceof Promise?s.push(l.then(p=>{p.issues.length&&n.issues.push(...St(a,p.issues)),n.value[c.value]=p.value})):(l.issues.length&&n.issues.push(...St(a,l.issues)),n.value[c.value]=l.value)}}return s.length?Promise.all(s).then(()=>n):n}}),el=v("$ZodEnum",(e,t)=>{re.init(e,t);const n=ds(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(o=>uc.has(typeof o)).map(o=>typeof o=="string"?zt(o):o.toString()).join("|")})$`),e._zod.parse=(o,s)=>{const i=o.value;return r.has(i)||o.issues.push({code:"invalid_value",values:n,input:i,inst:e}),o}}),tl=v("$ZodLiteral",(e,t)=>{if(re.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?zt(r):r?zt(r.toString()):String(r)).join("|")})$`),e._zod.parse=(r,o)=>{const s=r.value;return n.has(s)||r.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),r}}),nl=v("$ZodTransform",(e,t)=>{re.init(e,t),e._zod.optin="optional",e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new ls(e.constructor.name);const o=t.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(n.value=i,n.fallback=!0,n));if(o instanceof Promise)throw new xt;return n.value=o,n.fallback=!0,n}});function co(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const Es=v("$ZodOptional",(e,t)=>{re.init(e,t),e._zod.optin="optional",e._zod.optout="optional",J(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),J(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${gr(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){const o=n.value,s=t.innerType._zod.run(n,r);return s instanceof Promise?s.then(i=>co(i,o)):co(s,o)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),rl=v("$ZodExactOptional",(e,t)=>{Es.init(e,t),J(e._zod,"values",()=>t.innerType._zod.values),J(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),ol=v("$ZodNullable",(e,t)=>{re.init(e,t),J(e._zod,"optin",()=>t.innerType._zod.optin),J(e._zod,"optout",()=>t.innerType._zod.optout),J(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${gr(n.source)}|null)$`):void 0}),J(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),sl=v("$ZodDefault",(e,t)=>{re.init(e,t),e._zod.optin="optional",J(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>uo(s,t)):uo(o,t)}});function uo(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const il=v("$ZodPrefault",(e,t)=>{re.init(e,t),e._zod.optin="optional",J(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),al=v("$ZodNonOptional",(e,t)=>{re.init(e,t),J(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>lo(s,e)):lo(o,e)}});function lo(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const cl=v("$ZodCatch",(e,t)=>{re.init(e,t),e._zod.optin="optional",J(e._zod,"optout",()=>t.innerType._zod.optout),J(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>(n.value=s.value,s.issues.length&&(n.value=t.catchValue({...n,error:{issues:s.issues.map(i=>tt(i,r,et()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(s=>tt(s,r,et()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),Cs=v("$ZodPipe",(e,t)=>{re.init(e,t),J(e._zod,"values",()=>t.in._zod.values),J(e._zod,"optin",()=>t.in._zod.optin),J(e._zod,"optout",()=>t.out._zod.optout),J(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){const s=t.out._zod.run(n,r);return s instanceof Promise?s.then(i=>mn(i,t.in,r)):mn(s,t.in,r)}const o=t.in._zod.run(n,r);return o instanceof Promise?o.then(s=>mn(s,t.out,r)):mn(o,t.out,r)}});function mn(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}const ul=v("$ZodPreprocess",(e,t)=>{Cs.init(e,t)}),ll=v("$ZodReadonly",(e,t)=>{re.init(e,t),J(e._zod,"propValues",()=>t.innerType._zod.propValues),J(e._zod,"values",()=>t.innerType._zod.values),J(e._zod,"optin",()=>t.innerType?._zod?.optin),J(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(po):po(o)}});function po(e){return e.value=Object.freeze(e.value),e}const dl=v("$ZodCustom",(e,t)=>{Ae.init(e,t),re.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then(s=>ho(s,n,r,e));ho(o,n,r,e)}});function ho(e,t,n,r){if(!e){const o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),t.issues.push(qt(o))}}var fo;let pl=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};delete r.id;const o={...r,...this._map.get(t)};return Object.keys(o).length?o:void 0}return this._map.get(t)}has(t){return this._map.has(t)}};function hl(){return new pl}(fo=globalThis).__zod_globalRegistry??(fo.__zod_globalRegistry=hl());const Lt=globalThis.__zod_globalRegistry;function fl(e,t){return new e({type:"string",...z(t)})}function ml(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...z(t)})}function mo(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...z(t)})}function gl(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...z(t)})}function vl(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...z(t)})}function _l(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...z(t)})}function bl(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...z(t)})}function yl(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...z(t)})}function wl(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...z(t)})}function kl(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...z(t)})}function $l(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...z(t)})}function Sl(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...z(t)})}function xl(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...z(t)})}function Rl(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...z(t)})}function zl(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...z(t)})}function Tl(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...z(t)})}function Il(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...z(t)})}function El(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...z(t)})}function Cl(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...z(t)})}function Pl(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...z(t)})}function Nl(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...z(t)})}function Zl(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...z(t)})}function Ol(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...z(t)})}function Al(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...z(t)})}function jl(e,t){return new e({type:"string",format:"date",check:"string_format",...z(t)})}function Ml(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...z(t)})}function Ll(e,t){return new e({type:"string",format:"duration",check:"string_format",...z(t)})}function Dl(e,t){return new e({type:"number",checks:[],...z(t)})}function Ul(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...z(t)})}function ql(e,t){return new e({type:"boolean",...z(t)})}function Fl(e,t){return new e({type:"null",...z(t)})}function Hl(e){return new e({type:"unknown"})}function Vl(e,t){return new e({type:"never",...z(t)})}function go(e,t){return new $s({check:"less_than",...z(t),value:e,inclusive:!1})}function Vn(e,t){return new $s({check:"less_than",...z(t),value:e,inclusive:!0})}function vo(e,t){return new Ss({check:"greater_than",...z(t),value:e,inclusive:!1})}function Bn(e,t){return new Ss({check:"greater_than",...z(t),value:e,inclusive:!0})}function _o(e,t){return new ou({check:"multiple_of",...z(t),value:e})}function Ps(e,t){return new iu({check:"max_length",...z(t),maximum:e})}function Sn(e,t){return new au({check:"min_length",...z(t),minimum:e})}function Ns(e,t){return new cu({check:"length_equals",...z(t),length:e})}function Bl(e,t){return new uu({check:"string_format",format:"regex",...z(t),pattern:e})}function Jl(e){return new lu({check:"string_format",format:"lowercase",...z(e)})}function Wl(e){return new du({check:"string_format",format:"uppercase",...z(e)})}function Kl(e,t){return new pu({check:"string_format",format:"includes",...z(t),includes:e})}function Gl(e,t){return new hu({check:"string_format",format:"starts_with",...z(t),prefix:e})}function Yl(e,t){return new fu({check:"string_format",format:"ends_with",...z(t),suffix:e})}function Et(e){return new mu({check:"overwrite",tx:e})}function Ql(e){return Et(t=>t.normalize(e))}function Xl(){return Et(e=>e.trim())}function ed(){return Et(e=>e.toLowerCase())}function td(){return Et(e=>e.toUpperCase())}function nd(){return Et(e=>ac(e))}function rd(e,t,n){return new e({type:"array",element:t,...z(n)})}function od(e,t,n){const r=z(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}function sd(e,t,n){return new e({type:"custom",check:"custom",fn:t,...z(n)})}function id(e,t){const n=ad(r=>(r.addIssue=o=>{if(typeof o=="string")r.issues.push(qt(o,r.value,n._zod.def));else{const s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=n),s.continue??(s.continue=!n._zod.def.abort),r.issues.push(qt(s))}},e(r.value,r)),t);return n}function ad(e,t){const n=new Ae({check:"custom",...z(t)});return n._zod.check=e,n}function Zs(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Lt,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function _e(e,t,n={path:[],schemaPath:[]}){var r;const o=e._zod.def,s=t.seen.get(e);if(s)return s.count++,n.schemaPath.includes(e)&&(s.cycle=n.path),s.schema;const i={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,i);const a=e._zod.toJSONSchema?.();if(a)i.schema=a;else{const l={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,l);else{const h=i.schema,f=t.processors[o.type];if(!f)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);f(e,t,h,l)}const p=e._zod.parent;p&&(i.ref||(i.ref=p),_e(p,t,l),t.seen.get(p).isParent=!0)}const c=t.metadataRegistry.get(e);return c&&Object.assign(i.schema,c),t.io==="input"&&Pe(e)&&(delete i.schema.examples,delete i.schema.default),t.io==="input"&&"_prefault"in i.schema&&((r=i.schema).default??(r.default=i.schema._prefault)),delete i.schema._prefault,t.seen.get(e).schema}function Os(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const i of e.seen.entries()){const a=e.metadataRegistry.get(i[0])?.id;if(a){const c=r.get(a);if(c&&c!==i[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(a,i[0])}}const o=i=>{const a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const p=e.external.registry.get(i[0])?.id,h=e.external.uri??(y=>y);if(p)return{ref:h(p)};const f=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=f,{defId:f,ref:`${h("__shared")}#/${a}/${f}`}}if(i[1]===n)return{ref:"#"};const u=`#/${a}/`,l=i[1].schema.id??`__schema${e.counter++}`;return{defId:l,ref:u+l}},s=i=>{if(i[1].schema.$ref)return;const a=i[1],{ref:c,defId:u}=o(i);a.def={...a.schema},u&&(a.defId=u);const l=a.schema;for(const p in l)delete l[p];l.$ref=c};if(e.cycles==="throw")for(const i of e.seen.entries()){const a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
63
-
64
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const i of e.seen.entries()){const a=i[1];if(t===i[0]){s(i);continue}if(e.external){const u=e.external.registry.get(i[0])?.id;if(t!==i[0]&&u){s(i);continue}}if(e.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1&&e.reused==="ref"){s(i);continue}}}function As(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=a=>{const c=e.seen.get(a);if(c.ref===null)return;const u=c.def??c.schema,l={...u},p=c.ref;if(c.ref=null,p){r(p);const f=e.seen.get(p),y=f.schema;if(y.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(y)):Object.assign(u,y),Object.assign(u,l),a._zod.parent===p)for(const S in u)S==="$ref"||S==="allOf"||S in l||delete u[S];if(y.$ref&&f.def)for(const S in u)S==="$ref"||S==="allOf"||S in f.def&&JSON.stringify(u[S])===JSON.stringify(f.def[S])&&delete u[S]}const h=a._zod.parent;if(h&&h!==p){r(h);const f=e.seen.get(h);if(f?.schema.$ref&&(u.$ref=f.schema.$ref,f.def))for(const y in u)y==="$ref"||y==="allOf"||y in f.def&&JSON.stringify(u[y])===JSON.stringify(f.def[y])&&delete u[y]}e.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};for(const a of[...e.seen.entries()].reverse())r(a[0]);const o={};if(e.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(a)}Object.assign(o,n.def??n.schema);const s=e.metadataRegistry.get(t)?.id;s!==void 0&&o.id===s&&delete o.id;const i=e.external?.defs??{};for(const a of e.seen.entries()){const c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,i[c.defId]=c.def)}e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{const a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:xn(t,"input",e.processors),output:xn(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Pe(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return Pe(r.element,n);if(r.type==="set")return Pe(r.valueType,n);if(r.type==="lazy")return Pe(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return Pe(r.innerType,n);if(r.type==="intersection")return Pe(r.left,n)||Pe(r.right,n);if(r.type==="record"||r.type==="map")return Pe(r.keyType,n)||Pe(r.valueType,n);if(r.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:Pe(r.in,n)||Pe(r.out,n);if(r.type==="object"){for(const o in r.shape)if(Pe(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(const o of r.options)if(Pe(o,n))return!0;return!1}if(r.type==="tuple"){for(const o of r.items)if(Pe(o,n))return!0;return!!(r.rest&&Pe(r.rest,n))}return!1}const cd=(e,t={})=>n=>{const r=Zs({...n,processors:t});return _e(e,r),Os(r,e),As(r,e)},xn=(e,t,n={})=>r=>{const{libraryOptions:o,target:s}=r??{},i=Zs({...o??{},target:s,io:t,processors:n});return _e(e,i),Os(i,e),As(i,e)},ud={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},ld=(e,t,n,r)=>{const o=n;o.type="string";const{minimum:s,maximum:i,format:a,patterns:c,contentEncoding:u}=e._zod.bag;if(typeof s=="number"&&(o.minLength=s),typeof i=="number"&&(o.maxLength=i),a&&(o.format=ud[a]??a,o.format===""&&delete o.format,a==="time"&&delete o.format),u&&(o.contentEncoding=u),c&&c.size>0){const l=[...c];l.length===1?o.pattern=l[0].source:l.length>1&&(o.allOf=[...l.map(p=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},dd=(e,t,n,r)=>{const o=n,{minimum:s,maximum:i,format:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:l}=e._zod.bag;typeof a=="string"&&a.includes("int")?o.type="integer":o.type="number";const p=typeof l=="number"&&l>=(s??Number.NEGATIVE_INFINITY),h=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),f=t.target==="draft-04"||t.target==="openapi-3.0";p?f?(o.minimum=l,o.exclusiveMinimum=!0):o.exclusiveMinimum=l:typeof s=="number"&&(o.minimum=s),h?f?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u:typeof i=="number"&&(o.maximum=i),typeof c=="number"&&(o.multipleOf=c)},pd=(e,t,n,r)=>{n.type="boolean"},hd=(e,t,n,r)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},fd=(e,t,n,r)=>{n.not={}},md=(e,t,n,r)=>{},gd=(e,t,n,r)=>{const o=e._zod.def,s=ds(o.entries);s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),n.enum=s},vd=(e,t,n,r)=>{const o=e._zod.def,s=[];for(const i of o.values)if(i===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(i))}else s.push(i);if(s.length!==0)if(s.length===1){const i=s[0];n.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[i]:n.const=i}else s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),s.every(i=>typeof i=="boolean")&&(n.type="boolean"),s.every(i=>i===null)&&(n.type="null"),n.enum=s},_d=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},bd=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},yd=(e,t,n,r)=>{const o=n,s=e._zod.def,{minimum:i,maximum:a}=e._zod.bag;typeof i=="number"&&(o.minItems=i),typeof a=="number"&&(o.maxItems=a),o.type="array",o.items=_e(s.element,t,{...r,path:[...r.path,"items"]})},wd=(e,t,n,r)=>{const o=n,s=e._zod.def;o.type="object",o.properties={};const i=s.shape;for(const u in i)o.properties[u]=_e(i[u],t,{...r,path:[...r.path,"properties",u]});const a=new Set(Object.keys(i)),c=new Set([...a].filter(u=>{const l=s.shape[u]._zod;return t.io==="input"?l.optin===void 0:l.optout===void 0}));c.size>0&&(o.required=Array.from(c)),s.catchall?._zod.def.type==="never"?o.additionalProperties=!1:s.catchall?s.catchall&&(o.additionalProperties=_e(s.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},kd=(e,t,n,r)=>{const o=e._zod.def,s=o.inclusive===!1,i=o.options.map((a,c)=>_e(a,t,{...r,path:[...r.path,s?"oneOf":"anyOf",c]}));s?n.oneOf=i:n.anyOf=i},$d=(e,t,n,r)=>{const o=e._zod.def,s=_e(o.left,t,{...r,path:[...r.path,"allOf",0]}),i=_e(o.right,t,{...r,path:[...r.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];n.allOf=c},Sd=(e,t,n,r)=>{const o=n,s=e._zod.def;o.type="object";const i=s.keyType,c=i._zod.bag?.patterns;if(s.mode==="loose"&&c&&c.size>0){const l=_e(s.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});o.patternProperties={};for(const p of c)o.patternProperties[p.source]=l}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(o.propertyNames=_e(s.keyType,t,{...r,path:[...r.path,"propertyNames"]})),o.additionalProperties=_e(s.valueType,t,{...r,path:[...r.path,"additionalProperties"]});const u=i._zod.values;if(u){const l=[...u].filter(p=>typeof p=="string"||typeof p=="number");l.length>0&&(o.required=l)}},xd=(e,t,n,r)=>{const o=e._zod.def,s=_e(o.innerType,t,r),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=o.innerType,n.nullable=!0):n.anyOf=[s,{type:"null"}]},Rd=(e,t,n,r)=>{const o=e._zod.def;_e(o.innerType,t,r);const s=t.seen.get(e);s.ref=o.innerType},zd=(e,t,n,r)=>{const o=e._zod.def;_e(o.innerType,t,r);const s=t.seen.get(e);s.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},Td=(e,t,n,r)=>{const o=e._zod.def;_e(o.innerType,t,r);const s=t.seen.get(e);s.ref=o.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},Id=(e,t,n,r)=>{const o=e._zod.def;_e(o.innerType,t,r);const s=t.seen.get(e);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=i},Ed=(e,t,n,r)=>{const o=e._zod.def,s=o.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?s?o.out:o.in:o.out;_e(i,t,r);const a=t.seen.get(e);a.ref=i},Cd=(e,t,n,r)=>{const o=e._zod.def;_e(o.innerType,t,r);const s=t.seen.get(e);s.ref=o.innerType,n.readOnly=!0},js=(e,t,n,r)=>{const o=e._zod.def;_e(o.innerType,t,r);const s=t.seen.get(e);s.ref=o.innerType},Pd=v("ZodISODateTime",(e,t)=>{Iu.init(e,t),de.init(e,t)});function Ms(e){return Al(Pd,e)}const Nd=v("ZodISODate",(e,t)=>{Eu.init(e,t),de.init(e,t)});function Zd(e){return jl(Nd,e)}const Od=v("ZodISOTime",(e,t)=>{Cu.init(e,t),de.init(e,t)});function Ad(e){return Ml(Od,e)}const jd=v("ZodISODuration",(e,t)=>{Pu.init(e,t),de.init(e,t)});function Md(e){return Ll(jd,e)}const Ld=(e,t)=>{ms.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>wc(e,n)},flatten:{value:n=>yc(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,Xn,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,Xn,2)}},isEmpty:{get(){return e.issues.length===0}}})},Be=v("ZodError",Ld,{Parent:Error}),Dd=_r(Be),Ud=br(Be),qd=On(Be),Fd=An(Be),Hd=$c(Be),Vd=Sc(Be),Bd=xc(Be),Jd=Rc(Be),Wd=zc(Be),Kd=Tc(Be),Gd=Ic(Be),Yd=Ec(Be),bo=new WeakMap;function Gt(e,t,n){const r=Object.getPrototypeOf(e);let o=bo.get(r);if(o||(o=new Set,bo.set(r,o)),!o.has(t)){o.add(t);for(const s in n){const i=n[s];Object.defineProperty(r,s,{configurable:!0,enumerable:!1,get(){const a=i.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}const se=v("ZodType",(e,t)=>(re.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:xn(e,"input"),output:xn(e,"output")}}),e.toJSONSchema=cd(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,r)=>Dd(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>qd(e,n,r),e.parseAsync=async(n,r)=>Ud(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>Fd(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>Hd(e,n,r),e.decode=(n,r)=>Vd(e,n,r),e.encodeAsync=async(n,r)=>Bd(e,n,r),e.decodeAsync=async(n,r)=>Jd(e,n,r),e.safeEncode=(n,r)=>Wd(e,n,r),e.safeDecode=(n,r)=>Kd(e,n,r),e.safeEncodeAsync=async(n,r)=>Gd(e,n,r),e.safeDecodeAsync=async(n,r)=>Yd(e,n,r),Gt(e,"ZodType",{check(...n){const r=this.def;return this.clone(ut(r,{checks:[...r.checks??[],...n.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return lt(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(qp(n,r))},superRefine(n,r){return this.check(Fp(n,r))},overwrite(n){return this.check(Et(n))},optional(){return ue(this)},exactOptional(){return Ip(this)},nullable(){return $o(this)},nullish(){return ue($o(this))},nonoptional(n){return Op(this,n)},array(){return U(this)},or(n){return ie([this,n])},and(n){return wr(this,n)},transform(n){return So(this,Hs(n))},default(n){return Pp(this,n)},prefault(n){return Zp(this,n)},catch(n){return jp(this,n)},pipe(n){return So(this,n)},readonly(){return Dp(this)},describe(n){const r=this.clone();return Lt.add(r,{description:n}),r},meta(...n){if(n.length===0)return Lt.get(this);const r=this.clone();return Lt.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return Lt.get(e)?.description},configurable:!0}),e)),Ls=v("_ZodString",(e,t)=>{yr.init(e,t),se.init(e,t),e._zod.processJSONSchema=(r,o,s)=>ld(e,r,o);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Gt(e,"_ZodString",{regex(...r){return this.check(Bl(...r))},includes(...r){return this.check(Kl(...r))},startsWith(...r){return this.check(Gl(...r))},endsWith(...r){return this.check(Yl(...r))},min(...r){return this.check(Sn(...r))},max(...r){return this.check(Ps(...r))},length(...r){return this.check(Ns(...r))},nonempty(...r){return this.check(Sn(1,...r))},lowercase(r){return this.check(Jl(r))},uppercase(r){return this.check(Wl(r))},trim(){return this.check(Xl())},normalize(...r){return this.check(Ql(...r))},toLowerCase(){return this.check(ed())},toUpperCase(){return this.check(td())},slugify(){return this.check(nd())}})}),Qd=v("ZodString",(e,t)=>{yr.init(e,t),Ls.init(e,t),e.email=n=>e.check(ml(Xd,n)),e.url=n=>e.check(yl(ep,n)),e.jwt=n=>e.check(Ol(mp,n)),e.emoji=n=>e.check(wl(tp,n)),e.guid=n=>e.check(mo(yo,n)),e.uuid=n=>e.check(gl(gn,n)),e.uuidv4=n=>e.check(vl(gn,n)),e.uuidv6=n=>e.check(_l(gn,n)),e.uuidv7=n=>e.check(bl(gn,n)),e.nanoid=n=>e.check(kl(np,n)),e.guid=n=>e.check(mo(yo,n)),e.cuid=n=>e.check($l(rp,n)),e.cuid2=n=>e.check(Sl(op,n)),e.ulid=n=>e.check(xl(sp,n)),e.base64=n=>e.check(Pl(pp,n)),e.base64url=n=>e.check(Nl(hp,n)),e.xid=n=>e.check(Rl(ip,n)),e.ksuid=n=>e.check(zl(ap,n)),e.ipv4=n=>e.check(Tl(cp,n)),e.ipv6=n=>e.check(Il(up,n)),e.cidrv4=n=>e.check(El(lp,n)),e.cidrv6=n=>e.check(Cl(dp,n)),e.e164=n=>e.check(Zl(fp,n)),e.datetime=n=>e.check(Ms(n)),e.date=n=>e.check(Zd(n)),e.time=n=>e.check(Ad(n)),e.duration=n=>e.check(Md(n))});function g(e){return fl(Qd,e)}const de=v("ZodStringFormat",(e,t)=>{oe.init(e,t),Ls.init(e,t)}),Xd=v("ZodEmail",(e,t)=>{yu.init(e,t),de.init(e,t)}),yo=v("ZodGUID",(e,t)=>{_u.init(e,t),de.init(e,t)}),gn=v("ZodUUID",(e,t)=>{bu.init(e,t),de.init(e,t)}),ep=v("ZodURL",(e,t)=>{wu.init(e,t),de.init(e,t)}),tp=v("ZodEmoji",(e,t)=>{ku.init(e,t),de.init(e,t)}),np=v("ZodNanoID",(e,t)=>{$u.init(e,t),de.init(e,t)}),rp=v("ZodCUID",(e,t)=>{Su.init(e,t),de.init(e,t)}),op=v("ZodCUID2",(e,t)=>{xu.init(e,t),de.init(e,t)}),sp=v("ZodULID",(e,t)=>{Ru.init(e,t),de.init(e,t)}),ip=v("ZodXID",(e,t)=>{zu.init(e,t),de.init(e,t)}),ap=v("ZodKSUID",(e,t)=>{Tu.init(e,t),de.init(e,t)}),cp=v("ZodIPv4",(e,t)=>{Nu.init(e,t),de.init(e,t)}),up=v("ZodIPv6",(e,t)=>{Zu.init(e,t),de.init(e,t)}),lp=v("ZodCIDRv4",(e,t)=>{Ou.init(e,t),de.init(e,t)}),dp=v("ZodCIDRv6",(e,t)=>{Au.init(e,t),de.init(e,t)}),pp=v("ZodBase64",(e,t)=>{ju.init(e,t),de.init(e,t)}),hp=v("ZodBase64URL",(e,t)=>{Lu.init(e,t),de.init(e,t)}),fp=v("ZodE164",(e,t)=>{Du.init(e,t),de.init(e,t)}),mp=v("ZodJWT",(e,t)=>{qu.init(e,t),de.init(e,t)}),Ds=v("ZodNumber",(e,t)=>{Rs.init(e,t),se.init(e,t),e._zod.processJSONSchema=(r,o,s)=>dd(e,r,o),Gt(e,"ZodNumber",{gt(r,o){return this.check(vo(r,o))},gte(r,o){return this.check(Bn(r,o))},min(r,o){return this.check(Bn(r,o))},lt(r,o){return this.check(go(r,o))},lte(r,o){return this.check(Vn(r,o))},max(r,o){return this.check(Vn(r,o))},int(r){return this.check(wo(r))},safe(r){return this.check(wo(r))},positive(r){return this.check(vo(0,r))},nonnegative(r){return this.check(Bn(0,r))},negative(r){return this.check(go(0,r))},nonpositive(r){return this.check(Vn(0,r))},multipleOf(r,o){return this.check(_o(r,o))},step(r,o){return this.check(_o(r,o))},finite(){return this}});const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function W(e){return Dl(Ds,e)}const gp=v("ZodNumberFormat",(e,t)=>{Fu.init(e,t),Ds.init(e,t)});function wo(e){return Ul(gp,e)}const vp=v("ZodBoolean",(e,t)=>{Hu.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,o)=>pd(e,n,r)});function xe(e){return ql(vp,e)}const _p=v("ZodNull",(e,t)=>{Vu.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,o)=>hd(e,n,r)});function bp(e){return Fl(_p,e)}const yp=v("ZodUnknown",(e,t)=>{Bu.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,o)=>md()});function le(){return Hl(yp)}const wp=v("ZodNever",(e,t)=>{Ju.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,o)=>fd(e,n,r)});function kp(e){return Vl(wp,e)}const $p=v("ZodArray",(e,t)=>{Wu.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,o)=>yd(e,n,r,o),e.element=t.element,Gt(e,"ZodArray",{min(n,r){return this.check(Sn(n,r))},nonempty(n){return this.check(Sn(1,n))},max(n,r){return this.check(Ps(n,r))},length(n,r){return this.check(Ns(n,r))},unwrap(){return this.element}})});function U(e,t){return rd($p,e,t)}const Us=v("ZodObject",(e,t)=>{Gu.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,o)=>wd(e,n,r,o),J(e,"shape",()=>t.shape),Gt(e,"ZodObject",{keyof(){return De(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:le()})},loose(){return this.clone({...this._zod.def,catchall:le()})},strict(){return this.clone({...this._zod.def,catchall:kp()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return fc(this,n)},safeExtend(n){return mc(this,n)},merge(n){return gc(this,n)},pick(n){return pc(this,n)},omit(n){return hc(this,n)},partial(...n){return vc(Vs,this,n[0])},required(...n){return _c(Bs,this,n[0])}})});function x(e,t){const n={type:"object",shape:e??{},...z(t)};return new Us(n)}function Oe(e,t){return new Us({type:"object",shape:e,catchall:le(),...z(t)})}const qs=v("ZodUnion",(e,t)=>{Is.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,o)=>kd(e,n,r,o),e.options=t.options});function ie(e,t){return new qs({type:"union",options:e,...z(t)})}const Sp=v("ZodDiscriminatedUnion",(e,t)=>{qs.init(e,t),Yu.init(e,t)});function Fs(e,t,n){return new Sp({type:"union",options:t,discriminator:e,...z(n)})}const xp=v("ZodIntersection",(e,t)=>{Qu.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,o)=>$d(e,n,r,o)});function wr(e,t){return new xp({type:"intersection",left:e,right:t})}const ko=v("ZodRecord",(e,t)=>{Xu.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Sd(e,n,r,o),e.keyType=t.keyType,e.valueType=t.valueType});function ee(e,t,n){return!t||!t._zod?new ko({type:"record",keyType:g(),valueType:e,...z(t)}):new ko({type:"record",keyType:e,valueType:t,...z(n)})}const tr=v("ZodEnum",(e,t)=>{el.init(e,t),se.init(e,t),e._zod.processJSONSchema=(r,o,s)=>gd(e,r,o),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,o)=>{const s={};for(const i of r)if(n.has(i))s[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new tr({...t,checks:[],...z(o),entries:s})},e.exclude=(r,o)=>{const s={...t.entries};for(const i of r)if(n.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new tr({...t,checks:[],...z(o),entries:s})}});function De(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new tr({type:"enum",entries:n,...z(t)})}const Rp=v("ZodLiteral",(e,t)=>{tl.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,o)=>vd(e,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function T(e,t){return new Rp({type:"literal",values:Array.isArray(e)?e:[e],...z(t)})}const zp=v("ZodTransform",(e,t)=>{nl.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,o)=>bd(e,n),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new ls(e.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(qt(s,n.value,t));else{const i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=e),n.issues.push(qt(i))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n.fallback=!0,n)):(n.value=o,n.fallback=!0,n)}});function Hs(e){return new zp({type:"transform",transform:e})}const Vs=v("ZodOptional",(e,t)=>{Es.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,o)=>js(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function ue(e){return new Vs({type:"optional",innerType:e})}const Tp=v("ZodExactOptional",(e,t)=>{rl.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,o)=>js(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function Ip(e){return new Tp({type:"optional",innerType:e})}const Ep=v("ZodNullable",(e,t)=>{ol.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,o)=>xd(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function $o(e){return new Ep({type:"nullable",innerType:e})}const Cp=v("ZodDefault",(e,t)=>{sl.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,o)=>zd(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Pp(e,t){return new Cp({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():hs(t)}})}const Np=v("ZodPrefault",(e,t)=>{il.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Td(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function Zp(e,t){return new Np({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():hs(t)}})}const Bs=v("ZodNonOptional",(e,t)=>{al.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Rd(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function Op(e,t){return new Bs({type:"nonoptional",innerType:e,...z(t)})}const Ap=v("ZodCatch",(e,t)=>{cl.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Id(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function jp(e,t){return new Ap({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const Js=v("ZodPipe",(e,t)=>{Cs.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ed(e,n,r,o),e.in=t.in,e.out=t.out});function So(e,t){return new Js({type:"pipe",in:e,out:t})}const Mp=v("ZodPreprocess",(e,t)=>{Js.init(e,t),ul.init(e,t)}),Lp=v("ZodReadonly",(e,t)=>{ll.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Cd(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function Dp(e){return new Lp({type:"readonly",innerType:e})}const Ws=v("ZodCustom",(e,t)=>{dl.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,o)=>_d(e,n)});function Up(e,t){return od(Ws,e??(()=>!0),t)}function qp(e,t={}){return sd(Ws,e,t)}function Fp(e,t){return id(e,t)}function Ks(e,t){return new Mp({type:"pipe",in:Hs(e),out:t})}const mt="io.modelcontextprotocol/related-task",Mn="2.0",ye=Up(e=>e!==null&&(typeof e=="object"||typeof e=="function")),Gs=ie([g(),W().int()]),Ys=g();Oe({ttl:W().optional(),pollInterval:W().optional()});const Hp=x({ttl:W().optional()}),Vp=x({taskId:g()}),kr=Oe({progressToken:Gs.optional(),[mt]:Vp.optional()}),Ue=x({_meta:kr.optional()}),Yt=Ue.extend({task:Hp.optional()}),Bp=e=>Yt.safeParse(e).success,Re=x({method:g(),params:Ue.loose().optional()}),Je=x({_meta:kr.optional()}),We=x({method:g(),params:Je.loose().optional()}),ze=Oe({_meta:kr.optional()}),Qt=ie([g(),W().int()]),Qs=x({jsonrpc:T(Mn),id:Qt,...Re.shape}).strict(),xo=e=>Qs.safeParse(e).success,Xs=x({jsonrpc:T(Mn),...We.shape}).strict(),Jp=e=>Xs.safeParse(e).success,$r=x({jsonrpc:T(Mn),id:Qt,result:ze}).strict(),vn=e=>$r.safeParse(e).success;var B;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(B||(B={}));const Sr=x({jsonrpc:T(Mn),id:Qt.optional(),error:x({code:W().int(),message:g(),data:le().optional()})}).strict(),Wp=e=>Sr.safeParse(e).success,Kp=ie([Qs,Xs,$r,Sr]);ie([$r,Sr]);const ei=ze.strict(),Gp=Je.extend({requestId:Qt.optional(),reason:g().optional()}),xr=We.extend({method:T("notifications/cancelled"),params:Gp}),Yp=x({src:g(),mimeType:g().optional(),sizes:U(g()).optional(),theme:De(["light","dark"]).optional()}),Xt=x({icons:U(Yp).optional()}),Tt=x({name:g(),title:g().optional()}),Ln=Tt.extend({...Tt.shape,...Xt.shape,version:g(),websiteUrl:g().optional(),description:g().optional()}),Qp=wr(x({applyDefaults:xe().optional()}),ee(g(),le())),Xp=Ks(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,wr(x({form:Qp.optional(),url:ye.optional()}),ee(g(),le()).optional())),eh=Oe({list:ye.optional(),cancel:ye.optional(),requests:Oe({sampling:Oe({createMessage:ye.optional()}).optional(),elicitation:Oe({create:ye.optional()}).optional()}).optional()}),th=Oe({list:ye.optional(),cancel:ye.optional(),requests:Oe({tools:Oe({call:ye.optional()}).optional()}).optional()}),nh=x({experimental:ee(g(),ye).optional(),sampling:x({context:ye.optional(),tools:ye.optional()}).optional(),elicitation:Xp.optional(),roots:x({listChanged:xe().optional()}).optional(),tasks:eh.optional(),extensions:ee(g(),ye).optional()}),rh=Ue.extend({protocolVersion:g(),capabilities:nh,clientInfo:Ln}),oh=Re.extend({method:T("initialize"),params:rh}),sh=x({experimental:ee(g(),ye).optional(),logging:ye.optional(),completions:ye.optional(),prompts:x({listChanged:xe().optional()}).optional(),resources:x({subscribe:xe().optional(),listChanged:xe().optional()}).optional(),tools:x({listChanged:xe().optional()}).optional(),tasks:th.optional(),extensions:ee(g(),ye).optional()}),ih=ze.extend({protocolVersion:g(),capabilities:sh,serverInfo:Ln,instructions:g().optional()}),ah=We.extend({method:T("notifications/initialized"),params:Je.optional()}),Dn=Re.extend({method:T("ping"),params:Ue.optional()}),ch=x({progress:W(),total:ue(W()),message:ue(g())}),uh=x({...Je.shape,...ch.shape,progressToken:Gs}),Rr=We.extend({method:T("notifications/progress"),params:uh}),lh=Ue.extend({cursor:Ys.optional()}),en=Re.extend({params:lh.optional()}),tn=ze.extend({nextCursor:Ys.optional()}),dh=De(["working","input_required","completed","failed","cancelled"]),nn=x({taskId:g(),status:dh,ttl:ie([W(),bp()]),createdAt:g(),lastUpdatedAt:g(),pollInterval:ue(W()),statusMessage:ue(g())}),zr=ze.extend({task:nn}),ph=Je.merge(nn),Rn=We.extend({method:T("notifications/tasks/status"),params:ph}),Tr=Re.extend({method:T("tasks/get"),params:Ue.extend({taskId:g()})}),Ir=ze.merge(nn),Er=Re.extend({method:T("tasks/result"),params:Ue.extend({taskId:g()})});ze.loose();const Cr=en.extend({method:T("tasks/list")}),Pr=tn.extend({tasks:U(nn)}),Nr=Re.extend({method:T("tasks/cancel"),params:Ue.extend({taskId:g()})}),hh=ze.merge(nn),ti=x({uri:g(),mimeType:ue(g()),_meta:ee(g(),le()).optional()}),ni=ti.extend({text:g()}),Zr=g().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),ri=ti.extend({blob:Zr}),rn=De(["user","assistant"]),Ct=x({audience:U(rn).optional(),priority:W().min(0).max(1).optional(),lastModified:Ms({offset:!0}).optional()}),oi=x({...Tt.shape,...Xt.shape,uri:g(),description:ue(g()),mimeType:ue(g()),size:ue(W()),annotations:Ct.optional(),_meta:ue(Oe({}))}),fh=x({...Tt.shape,...Xt.shape,uriTemplate:g(),description:ue(g()),mimeType:ue(g()),annotations:Ct.optional(),_meta:ue(Oe({}))}),si=en.extend({method:T("resources/list")}),ii=tn.extend({resources:U(oi)}),ai=en.extend({method:T("resources/templates/list")}),ci=tn.extend({resourceTemplates:U(fh)}),Or=Ue.extend({uri:g()}),mh=Or,ui=Re.extend({method:T("resources/read"),params:mh}),li=ze.extend({contents:U(ie([ni,ri]))}),di=We.extend({method:T("notifications/resources/list_changed"),params:Je.optional()}),gh=Or,vh=Re.extend({method:T("resources/subscribe"),params:gh}),_h=Or,bh=Re.extend({method:T("resources/unsubscribe"),params:_h}),yh=Je.extend({uri:g()}),wh=We.extend({method:T("notifications/resources/updated"),params:yh}),kh=x({name:g(),description:ue(g()),required:ue(xe())}),$h=x({...Tt.shape,...Xt.shape,description:ue(g()),arguments:ue(U(kh)),_meta:ue(Oe({}))}),pi=en.extend({method:T("prompts/list")}),hi=tn.extend({prompts:U($h)}),Sh=Ue.extend({name:g(),arguments:ee(g(),g()).optional()}),xh=Re.extend({method:T("prompts/get"),params:Sh}),Ar=x({type:T("text"),text:g(),annotations:Ct.optional(),_meta:ee(g(),le()).optional()}),jr=x({type:T("image"),data:Zr,mimeType:g(),annotations:Ct.optional(),_meta:ee(g(),le()).optional()}),Mr=x({type:T("audio"),data:Zr,mimeType:g(),annotations:Ct.optional(),_meta:ee(g(),le()).optional()}),Rh=x({type:T("tool_use"),name:g(),id:g(),input:ee(g(),le()),_meta:ee(g(),le()).optional()}),fi=x({type:T("resource"),resource:ie([ni,ri]),annotations:Ct.optional(),_meta:ee(g(),le()).optional()}),mi=oi.extend({type:T("resource_link")}),on=ie([Ar,jr,Mr,mi,fi]),zh=x({role:rn,content:on}),Th=ze.extend({description:g().optional(),messages:U(zh)}),gi=We.extend({method:T("notifications/prompts/list_changed"),params:Je.optional()}),Ih=x({title:g().optional(),readOnlyHint:xe().optional(),destructiveHint:xe().optional(),idempotentHint:xe().optional(),openWorldHint:xe().optional()}),Eh=x({taskSupport:De(["required","optional","forbidden"]).optional()}),Lr=x({...Tt.shape,...Xt.shape,description:g().optional(),inputSchema:x({type:T("object"),properties:ee(g(),ye).optional(),required:U(g()).optional()}).catchall(le()),outputSchema:x({type:T("object"),properties:ee(g(),ye).optional(),required:U(g()).optional()}).catchall(le()).optional(),annotations:Ih.optional(),execution:Eh.optional(),_meta:ee(g(),le()).optional()}),Ch=en.extend({method:T("tools/list")}),vi=tn.extend({tools:U(Lr)}),Ft=ze.extend({content:U(on).default([]),structuredContent:ee(g(),le()).optional(),isError:xe().optional()});Ft.or(ze.extend({toolResult:le()}));const Ph=Yt.extend({name:g(),arguments:ee(g(),le()).optional()}),_i=Re.extend({method:T("tools/call"),params:Ph}),bi=We.extend({method:T("notifications/tools/list_changed"),params:Je.optional()});x({autoRefresh:xe().default(!0),debounceMs:W().int().nonnegative().default(300)});const yi=De(["debug","info","notice","warning","error","critical","alert","emergency"]),Nh=Ue.extend({level:yi}),Zh=Re.extend({method:T("logging/setLevel"),params:Nh}),Oh=Je.extend({level:yi,logger:g().optional(),data:le()}),wi=We.extend({method:T("notifications/message"),params:Oh}),Ah=x({name:g().optional()}),jh=x({hints:U(Ah).optional(),costPriority:W().min(0).max(1).optional(),speedPriority:W().min(0).max(1).optional(),intelligencePriority:W().min(0).max(1).optional()}),Mh=x({mode:De(["auto","required","none"]).optional()}),Lh=x({type:T("tool_result"),toolUseId:g().describe("The unique identifier for the corresponding tool call."),content:U(on).default([]),structuredContent:x({}).loose().optional(),isError:xe().optional(),_meta:ee(g(),le()).optional()}),Dh=Fs("type",[Ar,jr,Mr]),zn=Fs("type",[Ar,jr,Mr,Rh,Lh]),Uh=x({role:rn,content:ie([zn,U(zn)]),_meta:ee(g(),le()).optional()}),qh=Yt.extend({messages:U(Uh),modelPreferences:jh.optional(),systemPrompt:g().optional(),includeContext:De(["none","thisServer","allServers"]).optional(),temperature:W().optional(),maxTokens:W().int(),stopSequences:U(g()).optional(),metadata:ye.optional(),tools:U(Lr).optional(),toolChoice:Mh.optional()}),ki=Re.extend({method:T("sampling/createMessage"),params:qh}),Fh=ze.extend({model:g(),stopReason:ue(De(["endTurn","stopSequence","maxTokens"]).or(g())),role:rn,content:Dh}),Hh=ze.extend({model:g(),stopReason:ue(De(["endTurn","stopSequence","maxTokens","toolUse"]).or(g())),role:rn,content:ie([zn,U(zn)])}),Vh=x({type:T("boolean"),title:g().optional(),description:g().optional(),default:xe().optional()}),Bh=x({type:T("string"),title:g().optional(),description:g().optional(),minLength:W().optional(),maxLength:W().optional(),format:De(["email","uri","date","date-time"]).optional(),default:g().optional()}),Jh=x({type:De(["number","integer"]),title:g().optional(),description:g().optional(),minimum:W().optional(),maximum:W().optional(),default:W().optional()}),Wh=x({type:T("string"),title:g().optional(),description:g().optional(),enum:U(g()),default:g().optional()}),Kh=x({type:T("string"),title:g().optional(),description:g().optional(),oneOf:U(x({const:g(),title:g()})),default:g().optional()}),Gh=x({type:T("string"),title:g().optional(),description:g().optional(),enum:U(g()),enumNames:U(g()).optional(),default:g().optional()}),Yh=ie([Wh,Kh]),Qh=x({type:T("array"),title:g().optional(),description:g().optional(),minItems:W().optional(),maxItems:W().optional(),items:x({type:T("string"),enum:U(g())}),default:U(g()).optional()}),Xh=x({type:T("array"),title:g().optional(),description:g().optional(),minItems:W().optional(),maxItems:W().optional(),items:x({anyOf:U(x({const:g(),title:g()}))}),default:U(g()).optional()}),ef=ie([Qh,Xh]),tf=ie([Gh,Yh,ef]),nf=ie([tf,Vh,Bh,Jh]),rf=Yt.extend({mode:T("form").optional(),message:g(),requestedSchema:x({type:T("object"),properties:ee(g(),nf),required:U(g()).optional()})}),of=Yt.extend({mode:T("url"),message:g(),elicitationId:g(),url:g().url()}),sf=ie([rf,of]),af=Re.extend({method:T("elicitation/create"),params:sf}),cf=Je.extend({elicitationId:g()}),uf=We.extend({method:T("notifications/elicitation/complete"),params:cf}),lf=ze.extend({action:De(["accept","decline","cancel"]),content:Ks(e=>e===null?void 0:e,ee(g(),ie([g(),W(),xe(),U(g())])).optional())}),df=x({type:T("ref/resource"),uri:g()}),pf=x({type:T("ref/prompt"),name:g()}),hf=Ue.extend({ref:ie([pf,df]),argument:x({name:g(),value:g()}),context:x({arguments:ee(g(),g()).optional()}).optional()}),ff=Re.extend({method:T("completion/complete"),params:hf}),mf=ze.extend({completion:Oe({values:U(g()).max(100),total:ue(W().int()),hasMore:ue(xe())})}),gf=x({uri:g().startsWith("file://"),name:g().optional(),_meta:ee(g(),le()).optional()}),vf=Re.extend({method:T("roots/list"),params:Ue.optional()}),_f=ze.extend({roots:U(gf)}),bf=We.extend({method:T("notifications/roots/list_changed"),params:Je.optional()});ie([Dn,oh,ff,Zh,xh,pi,si,ai,ui,vh,bh,_i,Ch,Tr,Er,Cr,Nr]);ie([xr,Rr,ah,bf,Rn]);ie([ei,Fh,Hh,lf,_f,Ir,Pr,zr]);ie([Dn,ki,af,vf,Tr,Er,Cr,Nr]);ie([xr,Rr,wi,wh,di,bi,gi,Rn,uf]);ie([ei,ih,mf,Th,hi,ii,ci,li,Ft,vi,Ir,Pr,zr]);class F extends Error{constructor(t,n,r){super(`MCP error ${t}: ${n}`),this.code=t,this.data=r,this.name="McpError"}static fromError(t,n,r){if(t===B.UrlElicitationRequired&&r){const o=r;if(o.elicitations)return new yf(o.elicitations,n)}return new F(t,n,r)}}class yf extends F{constructor(t,n=`URL elicitation${t.length>1?"s":""} required`){super(B.UrlElicitationRequired,n,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}}function Dr(e){return!!e._zod}function $i(e,t){return Dr(e)?vs(e,t):e.safeParse(t)}function wf(e){if(!e)return;let t;if(Dr(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function kf(e){if(Dr(e)){const s=e._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}const n=e._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}const r=e.value;if(r!==void 0)return r}function ht(e){return e==="completed"||e==="failed"||e==="cancelled"}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Ro(e){const n=wf(e)?.method;if(!n)throw new Error("Schema is missing a method literal");const r=kf(n);if(typeof r!="string")throw new Error("Schema method literal must be a string");return r}function zo(e,t){const n=$i(e,t);if(!n.success)throw n.error;return n.data}const $f=6e4;class Sf{constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(xr,n=>{this._oncancel(n)}),this.setNotificationHandler(Rr,n=>{this._onprogress(n)}),this.setRequestHandler(Dn,n=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Tr,async(n,r)=>{const o=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!o)throw new F(B.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Er,async(n,r)=>{const o=async()=>{const s=n.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,r.sessionId);){if(a.type==="response"||a.type==="error"){const c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{const p=c,h=new F(p.error.code,p.error.message,p.error.data);l(h)}else{const p=a.type==="response"?"Response":"Error";this._onerror(new Error(`${p} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:r.requestId})}}const i=await this._taskStore.getTask(s,r.sessionId);if(!i)throw new F(B.InvalidParams,`Task not found: ${s}`);if(!ht(i.status))return await this._waitForTaskUpdate(s,r.signal),await o();if(ht(i.status)){const a=await this._taskStore.getTaskResult(s,r.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[mt]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Cr,async(n,r)=>{try{const{tasks:o,nextCursor:s}=await this._taskStore.listTasks(n.params?.cursor,r.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new F(B.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Nr,async(n,r)=>{try{const o=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!o)throw new F(B.InvalidParams,`Task not found: ${n.params.taskId}`);if(ht(o.status))throw new F(B.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(n.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(n.params.taskId);const s=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!s)throw new F(B.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof F?o:new F(B.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,n,r,o,s=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,n),startTime:Date.now(),timeout:n,maxTotalTimeout:r,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(t){const n=this._timeoutInfo.get(t);if(!n)return!1;const r=Date.now()-n.startTime;if(n.maxTotalTimeout&&r>=n.maxTotalTimeout)throw this._timeoutInfo.delete(t),F.fromError(B.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:r});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(t){const n=this._timeoutInfo.get(t);n&&(clearTimeout(n.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;const n=this.transport?.onclose;this._transport.onclose=()=>{n?.(),this._onclose()};const r=this.transport?.onerror;this._transport.onerror=s=>{r?.(s),this._onerror(s)};const o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),vn(s)||Wp(s)?this._onresponse(s):xo(s)?this._onrequest(s,i):Jp(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(const r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();const n=F.fromError(B.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const r of t.values())r(n)}_onerror(t){this.onerror?.(t)}_onnotification(t){const n=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(t)).catch(r=>this._onerror(new Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(t,n){const r=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,o=this._transport,s=t.params?._meta?.[mt]?.taskId;if(r===void 0){const l={jsonrpc:"2.0",id:t.id,error:{code:B.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):o?.send(l).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}const i=new AbortController;this._requestHandlerAbortControllers.set(t.id,i);const a=Bp(t.params)?t.params.task:void 0,c=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async l=>{if(i.signal.aborted)return;const p={relatedRequestId:t.id};s&&(p.relatedTask={taskId:s}),await this.notification(l,p)},sendRequest:async(l,p,h)=>{if(i.signal.aborted)throw new F(B.ConnectionClosed,"Request was cancelled");const f={...h,relatedRequestId:t.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});const y=f.relatedTask?.taskId??s;return y&&c&&await c.updateTaskStatus(y,"input_required"),await this.request(l,p,f)},authInfo:n?.authInfo,requestId:t.id,requestInfo:n?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:n?.closeSSEStream,closeStandaloneSSEStream:n?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(t.method)}).then(()=>r(t,u)).then(async l=>{if(i.signal.aborted)return;const p={result:l,jsonrpc:"2.0",id:t.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)},async l=>{if(i.signal.aborted)return;const p={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(l.code)?l.code:B.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===i&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){const{progressToken:n,...r}=t.params,o=Number(n),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}const i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(r)}_onresponse(t){const n=Number(t.id),r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),vn(t))r(t);else{const i=new F(t.error.code,t.error.message,t.error.data);r(i)}return}const o=this._responseHandlers.get(n);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(n),this._cleanupTimeout(n);let s=!1;if(vn(t)&&t.result&&typeof t.result=="object"){const i=t.result;if(i.task&&typeof i.task=="object"){const a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,n))}}if(s||this._progressHandlers.delete(n),vn(t))o(t);else{const i=F.fromError(t.error.code,t.error.message,t.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,n,r){const{task:o}=r??{};if(!o){try{yield{type:"result",result:await this.request(t,n,r)}}catch(i){yield{type:"error",error:i instanceof F?i:new F(B.InternalError,String(i))}}return}let s;try{const i=await this.request(t,zr,r);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new F(B.InternalError,"Task creation did not return a task");for(;;){const a=await this.getTask({taskId:s},r);if(yield{type:"taskStatus",task:a},ht(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},n,r)}:a.status==="failed"?yield{type:"error",error:new F(B.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new F(B.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},n,r)};return}const c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),r?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof F?i:new F(B.InternalError,String(i))}}}request(t,n,r){const{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=r??{};return new Promise((u,l)=>{const p=R=>{l(R)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),a&&this.assertTaskCapability(t.method)}catch(R){p(R);return}r?.signal?.throwIfAborted();const h=this._requestMessageId++,f={...t,jsonrpc:"2.0",id:h};r?.onprogress&&(this._progressHandlers.set(h,r.onprogress),f.params={...t.params,_meta:{...t.params?._meta||{},progressToken:h}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[mt]:c}});const y=R=>{this._responseHandlers.delete(h),this._progressHandlers.delete(h),this._cleanupTimeout(h),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:h,reason:String(R)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(k=>this._onerror(new Error(`Failed to send cancellation: ${k}`)));const w=R instanceof F?R:new F(B.RequestTimeout,String(R));l(w)};this._responseHandlers.set(h,R=>{if(!r?.signal?.aborted){if(R instanceof Error)return l(R);try{const w=$i(n,R.result);w.success?u(w.data):l(w.error)}catch(w){l(w)}}}),r?.signal?.addEventListener("abort",()=>{y(r?.signal?.reason)});const P=r?.timeout??$f,S=()=>y(F.fromError(B.RequestTimeout,"Request timed out",{timeout:P}));this._setupTimeout(h,P,r?.maxTotalTimeout,S,r?.resetTimeoutOnProgress??!1);const j=c?.taskId;if(j){const R=w=>{const k=this._responseHandlers.get(h);k?k(w):this._onerror(new Error(`Response handler missing for side-channeled request ${h}`))};this._requestResolvers.set(h,R),this._enqueueTaskMessage(j,{type:"request",message:f,timestamp:Date.now()}).catch(w=>{this._cleanupTimeout(h),l(w)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(R=>{this._cleanupTimeout(h),l(R)})})}async getTask(t,n){return this.request({method:"tasks/get",params:t},Ir,n)}async getTaskResult(t,n,r){return this.request({method:"tasks/result",params:t},n,r)}async listTasks(t,n){return this.request({method:"tasks/list",params:t},Pr,n)}async cancelTask(t,n){return this.request({method:"tasks/cancel",params:t},hh,n)}async notification(t,n){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);const r=n?.relatedTask?.taskId;if(r){const a={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[mt]:n.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!n?.relatedRequestId&&!n?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let a={...t,jsonrpc:"2.0"};n?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[mt]:n.relatedTask}}}),this._transport?.send(a,n).catch(c=>this._onerror(c))});return}let i={...t,jsonrpc:"2.0"};n?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[mt]:n.relatedTask}}}),await this._transport.send(i,n)}setRequestHandler(t,n){const r=Ro(t);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(o,s)=>{const i=zo(t,o);return Promise.resolve(n(i,s))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,n){const r=Ro(t);this._notificationHandlers.set(r,o=>{const s=zo(t,o);return Promise.resolve(n(s))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){const n=this._taskProgressTokens.get(t);n!==void 0&&(this._progressHandlers.delete(n),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,n,r){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,n,r,o)}async _clearTaskQueue(t,n){if(this._taskMessageQueue){const r=await this._taskMessageQueue.dequeueAll(t,n);for(const o of r)if(o.type==="request"&&xo(o.message)){const s=o.message.id,i=this._requestResolvers.get(s);i?(i(new F(B.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,n){let r=this._options?.defaultTaskPollInterval??1e3;try{const o=await this._taskStore?.getTask(t);o?.pollInterval&&(r=o.pollInterval)}catch{}return new Promise((o,s)=>{if(n.aborted){s(new F(B.InvalidRequest,"Request cancelled"));return}const i=setTimeout(o,r);n.addEventListener("abort",()=>{clearTimeout(i),s(new F(B.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,n){const r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async o=>{if(!t)throw new Error("No request provided");return await r.createTask(o,t.id,{method:t.method,params:t.params},n)},getTask:async o=>{const s=await r.getTask(o,n);if(!s)throw new F(B.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await r.storeTaskResult(o,s,i,n);const a=await r.getTask(o,n);if(a){const c=Rn.parse({method:"notifications/tasks/status",params:a});await this.notification(c),ht(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>r.getTaskResult(o,n),updateTaskStatus:async(o,s,i)=>{const a=await r.getTask(o,n);if(!a)throw new F(B.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(ht(a.status))throw new F(B.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(o,s,i,n);const c=await r.getTask(o,n);if(c){const u=Rn.parse({method:"notifications/tasks/status",params:c});await this.notification(u),ht(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>r.listTasks(o,n)}}}function _(e,t,n){function r(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(e),t(a,c);for(const l in i.prototype)l in a||Object.defineProperty(a,l,{value:i.prototype[l].bind(a)});a._zod.constr=i,a._zod.def=c}const o=n?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:e});function i(a){var c;const u=n?.Parent?new s:this;r(u,a),(c=u._zod).deferred??(c.deferred=[]);for(const l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}class Ht extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Si={};function at(e){return Si}function xf(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,o])=>t.indexOf(+r)===-1).map(([r,o])=>o)}function Rf(e,t){return typeof t=="bigint"?t.toString():t}function xi(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Ur(e){return e==null}function qr(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function zf(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(e.toFixed(o).replace(".","")),i=Number.parseInt(t.toFixed(o).replace(".",""));return s%i/10**o}function ne(e,t,n){Object.defineProperty(e,t,{get(){{const r=n();return e[t]=r,r}},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function Fr(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Mt(e){return JSON.stringify(e)}const Ri=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function nr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Tf=xi(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Tn(e){if(nr(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(nr(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}const If=new Set(["string","number","symbol"]);function sn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _t(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function E(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Ef(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const Cf={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Pf(e,t){const n={},r=e._zod.def;for(const o in t){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(n[o]=r.shape[o])}return _t(e,{...e._zod.def,shape:n,checks:[]})}function Nf(e,t){const n={...e._zod.def.shape},r=e._zod.def;for(const o in t){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete n[o]}return _t(e,{...e._zod.def,shape:n,checks:[]})}function Zf(e,t){if(!Tn(t))throw new Error("Invalid input to extend: expected a plain object");const n={...e._zod.def,get shape(){const r={...e._zod.def.shape,...t};return Fr(this,"shape",r),r},checks:[]};return _t(e,n)}function Of(e,t){return _t(e,{...e._zod.def,get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return Fr(this,"shape",n),n},catchall:t._zod.def.catchall,checks:[]})}function Af(e,t,n){const r=t._zod.def.shape,o={...r};if(n)for(const s in n){if(!(s in r))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=e?new e({type:"optional",innerType:r[s]}):r[s])}else for(const s in r)o[s]=e?new e({type:"optional",innerType:r[s]}):r[s];return _t(t,{...t._zod.def,shape:o,checks:[]})}function jf(e,t,n){const r=t._zod.def.shape,o={...r};if(n)for(const s in n){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=new e({type:"nonoptional",innerType:r[s]}))}else for(const s in r)o[s]=new e({type:"nonoptional",innerType:r[s]});return _t(t,{...t._zod.def,shape:o,checks:[]})}function Dt(e,t=0){for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function gt(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function _n(e){return typeof e=="string"?e:e?.message}function ct(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const o=_n(e.inst?._zod.def?.error?.(e))??_n(t?.error?.(e))??_n(n.customError?.(e))??_n(n.localeError?.(e))??"Invalid input";r.message=o}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function Hr(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Vt(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const zi=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,Rf,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Ti=_("$ZodError",zi),Ii=_("$ZodError",zi,{Parent:Error});function Mf(e,t=n=>n.message){const n={},r=[];for(const o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}function Lf(e,t){const n=t||function(s){return s.message},r={_errors:[]},o=s=>{for(const i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)r._errors.push(n(i));else{let a=r,c=0;for(;c<i.path.length;){const u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(n(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(e),r}const Df=e=>(t,n,r,o)=>{const s=r?Object.assign(r,{async:!1}):{async:!1},i=t._zod.run({value:n,issues:[]},s);if(i instanceof Promise)throw new Ht;if(i.issues.length){const a=new(o?.Err??e)(i.issues.map(c=>ct(c,s,at())));throw Ri(a,o?.callee),a}return i.value},Uf=e=>async(t,n,r,o)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let i=t._zod.run({value:n,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){const a=new(o?.Err??e)(i.issues.map(c=>ct(c,s,at())));throw Ri(a,o?.callee),a}return i.value},Ei=e=>(t,n,r)=>{const o=r?{...r,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new Ht;return s.issues.length?{success:!1,error:new(e??Ti)(s.issues.map(i=>ct(i,o,at())))}:{success:!0,data:s.value}},qf=Ei(Ii),Ci=e=>async(t,n,r)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let s=t._zod.run({value:n,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(i=>ct(i,o,at())))}:{success:!0,data:s.value}},Ff=Ci(Ii),Hf=/^[cC][^\s-]{8,}$/,Vf=/^[0-9a-z]+$/,Bf=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Jf=/^[0-9a-vA-V]{20}$/,Wf=/^[A-Za-z0-9]{27}$/,Kf=/^[a-zA-Z0-9_-]{21}$/,Gf=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Yf=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,To=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,Qf=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Xf="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function em(){return new RegExp(Xf,"u")}const tm=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,nm=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,rm=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,om=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,sm=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Pi=/^[A-Za-z0-9_-]*$/,im=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,am=/^\+(?:[0-9]){6,14}[0-9]$/,Ni="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",cm=new RegExp(`^${Ni}$`);function Zi(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function um(e){return new RegExp(`^${Zi(e)}$`)}function lm(e){const t=Zi({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-]\\d{2}:\\d{2})");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${Ni}T(?:${r})$`)}const dm=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},pm=/^\d+$/,hm=/^-?\d+(?:\.\d+)?/i,fm=/true|false/i,mm=/undefined/i,gm=/^[^A-Z]*$/,vm=/^[^a-z]*$/,je=_("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Oi={number:"number",bigint:"bigint",object:"date"},Ai=_("$ZodCheckLessThan",(e,t)=>{je.init(e,t);const n=Oi[typeof t.value];e._zod.onattach.push(r=>{const o=r._zod.bag,s=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ji=_("$ZodCheckGreaterThan",(e,t)=>{je.init(e,t);const n=Oi[typeof t.value];e._zod.onattach.push(r=>{const o=r._zod.bag,s=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),_m=_("$ZodCheckMultipleOf",(e,t)=>{je.init(e,t),e._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):zf(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),bm=_("$ZodCheckNumberFormat",(e,t)=>{je.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[o,s]=Cf[t.format];e._zod.onattach.push(i=>{const a=i._zod.bag;a.format=t.format,a.minimum=o,a.maximum=s,n&&(a.pattern=pm)}),e._zod.check=i=>{const a=i.value;if(n){if(!Number.isInteger(a)){i.issues.push({expected:r,format:t.format,code:"invalid_type",input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:e})}}),ym=_("$ZodCheckMaxLength",(e,t)=>{var n;je.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!Ur(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const o=r.value;if(o.length<=t.maximum)return;const i=Hr(o);r.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),wm=_("$ZodCheckMinLength",(e,t)=>{var n;je.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!Ur(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const o=r.value;if(o.length>=t.minimum)return;const i=Hr(o);r.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),km=_("$ZodCheckLengthEquals",(e,t)=>{var n;je.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!Ur(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=r=>{const o=r.value,s=o.length;if(s===t.length)return;const i=Hr(o),a=s>t.length;r.issues.push({origin:i,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),Un=_("$ZodCheckStringFormat",(e,t)=>{var n,r;je.init(e,t),e._zod.onattach.push(o=>{const s=o._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),$m=_("$ZodCheckRegex",(e,t)=>{Un.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Sm=_("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=gm),Un.init(e,t)}),xm=_("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=vm),Un.init(e,t)}),Rm=_("$ZodCheckIncludes",(e,t)=>{je.init(e,t);const n=sn(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(o=>{const s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),zm=_("$ZodCheckStartsWith",(e,t)=>{je.init(e,t);const n=new RegExp(`^${sn(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),Tm=_("$ZodCheckEndsWith",(e,t)=>{je.init(e,t);const n=new RegExp(`.*${sn(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),Im=_("$ZodCheckOverwrite",(e,t)=>{je.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class Em{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(`
65
- `).filter(i=>i),o=Math.min(...r.map(i=>i.length-i.trimStart().length)),s=r.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(const i of s)this.content.push(i)}compile(){const t=Function,n=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new t(...n,o.join(`
66
- `))}}const Cm={major:4,minor:0,patch:0},Q=_("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Cm;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const o of r)for(const s of o._zod.onattach)s(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=(s,i,a)=>{let c=Dt(s),u;for(const l of i){if(l._zod.def.when){if(!l._zod.def.when(s))continue}else if(c)continue;const p=s.issues.length,h=l._zod.check(s);if(h instanceof Promise&&a?.async===!1)throw new Ht;if(u||h instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await h,s.issues.length!==p&&(c||(c=Dt(s,p)))});else{if(s.issues.length===p)continue;c||(c=Dt(s,p))}}return u?u.then(()=>s):s};e._zod.run=(s,i)=>{const a=e._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new Ht;return a.then(c=>o(c,r,i))}return o(a,r,i)}}e["~standard"]={validate:o=>{try{const s=qf(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Ff(e,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Vr=_("$ZodString",(e,t)=>{Q.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??dm(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),ae=_("$ZodStringFormat",(e,t)=>{Un.init(e,t),Vr.init(e,t)}),Pm=_("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Yf),ae.init(e,t)}),Nm=_("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=To(r))}else t.pattern??(t.pattern=To());ae.init(e,t)}),Zm=_("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Qf),ae.init(e,t)}),Om=_("$ZodURL",(e,t)=>{ae.init(e,t),e._zod.check=n=>{try{const r=n.value,o=new URL(r),s=o.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:im.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),!r.endsWith("/")&&s.endsWith("/")?n.value=s.slice(0,-1):n.value=s;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Am=_("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=em()),ae.init(e,t)}),jm=_("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Kf),ae.init(e,t)}),Mm=_("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Hf),ae.init(e,t)}),Lm=_("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Vf),ae.init(e,t)}),Dm=_("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Bf),ae.init(e,t)}),Um=_("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Jf),ae.init(e,t)}),qm=_("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Wf),ae.init(e,t)}),Fm=_("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=lm(t)),ae.init(e,t)}),Hm=_("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=cm),ae.init(e,t)}),Vm=_("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=um(t)),ae.init(e,t)}),Bm=_("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Gf),ae.init(e,t)}),Jm=_("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=tm),ae.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),Wm=_("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=nm),ae.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv6"}),e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),Km=_("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=rm),ae.init(e,t)}),Gm=_("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=om),ae.init(e,t),e._zod.check=n=>{const[r,o]=n.value.split("/");try{if(!o)throw new Error;const s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function Mi(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const Ym=_("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=sm),ae.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),e._zod.check=n=>{Mi(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function Qm(e){if(!Pi.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return Mi(n)}const Xm=_("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Pi),ae.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),e._zod.check=n=>{Qm(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),eg=_("$ZodE164",(e,t)=>{t.pattern??(t.pattern=am),ae.init(e,t)});function tg(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const o=JSON.parse(atob(r));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const ng=_("$ZodJWT",(e,t)=>{ae.init(e,t),e._zod.check=n=>{tg(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Li=_("$ZodNumber",(e,t)=>{Q.init(e,t),e._zod.pattern=e._zod.bag.pattern??hm,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;const s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),n}}),rg=_("$ZodNumber",(e,t)=>{bm.init(e,t),Li.init(e,t)}),og=_("$ZodBoolean",(e,t)=>{Q.init(e,t),e._zod.pattern=fm,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}}),sg=_("$ZodUndefined",(e,t)=>{Q.init(e,t),e._zod.pattern=mm,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(n,r)=>{const o=n.value;return typeof o>"u"||n.issues.push({expected:"undefined",code:"invalid_type",input:o,inst:e}),n}}),ig=_("$ZodAny",(e,t)=>{Q.init(e,t),e._zod.parse=n=>n}),ag=_("$ZodUnknown",(e,t)=>{Q.init(e,t),e._zod.parse=n=>n}),cg=_("$ZodNever",(e,t)=>{Q.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Io(e,t,n){e.issues.length&&t.issues.push(...gt(n,e.issues)),t.value[n]=e.value}const ug=_("$ZodArray",(e,t)=>{Q.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);const s=[];for(let i=0;i<o.length;i++){const a=o[i],c=t.element._zod.run({value:a,issues:[]},r);c instanceof Promise?s.push(c.then(u=>Io(u,n,i))):Io(c,n,i)}return s.length?Promise.all(s).then(()=>n):n}});function bn(e,t,n){e.issues.length&&t.issues.push(...gt(n,e.issues)),t.value[n]=e.value}function Eo(e,t,n,r){e.issues.length?r[n]===void 0?n in r?t.value[n]=void 0:t.value[n]=e.value:t.issues.push(...gt(n,e.issues)):e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}const lg=_("$ZodObject",(e,t)=>{Q.init(e,t);const n=xi(()=>{const p=Object.keys(t.shape);for(const f of p)if(!(t.shape[f]instanceof Q))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);const h=Ef(t.shape);return{shape:t.shape,keys:p,keySet:new Set(p),numKeys:p.length,optionalKeys:new Set(h)}});ne(e._zod,"propValues",()=>{const p=t.shape,h={};for(const f in p){const y=p[f]._zod;if(y.values){h[f]??(h[f]=new Set);for(const P of y.values)h[f].add(P)}}return h});const r=p=>{const h=new Em(["shape","payload","ctx"]),f=n.value,y=R=>{const w=Mt(R);return`shape[${w}]._zod.run({ value: input[${w}], issues: [] }, ctx)`};h.write("const input = payload.value;");const P=Object.create(null);let S=0;for(const R of f.keys)P[R]=`key_${S++}`;h.write("const newResult = {}");for(const R of f.keys)if(f.optionalKeys.has(R)){const w=P[R];h.write(`const ${w} = ${y(R)};`);const k=Mt(R);h.write(`
67
- if (${w}.issues.length) {
68
- if (input[${k}] === undefined) {
69
- if (${k} in input) {
70
- newResult[${k}] = undefined;
71
- }
72
- } else {
73
- payload.issues = payload.issues.concat(
74
- ${w}.issues.map((iss) => ({
75
- ...iss,
76
- path: iss.path ? [${k}, ...iss.path] : [${k}],
77
- }))
78
- );
79
- }
80
- } else if (${w}.value === undefined) {
81
- if (${k} in input) newResult[${k}] = undefined;
82
- } else {
83
- newResult[${k}] = ${w}.value;
84
- }
85
- `)}else{const w=P[R];h.write(`const ${w} = ${y(R)};`),h.write(`
86
- if (${w}.issues.length) payload.issues = payload.issues.concat(${w}.issues.map(iss => ({
87
- ...iss,
88
- path: iss.path ? [${Mt(R)}, ...iss.path] : [${Mt(R)}]
89
- })));`),h.write(`newResult[${Mt(R)}] = ${w}.value`)}h.write("payload.value = newResult;"),h.write("return payload;");const j=h.compile();return(R,w)=>j(p,R,w)};let o;const s=nr,i=!Si.jitless,c=i&&Tf.value,u=t.catchall;let l;e._zod.parse=(p,h)=>{l??(l=n.value);const f=p.value;if(!s(f))return p.issues.push({expected:"object",code:"invalid_type",input:f,inst:e}),p;const y=[];if(i&&c&&h?.async===!1&&h.jitless!==!0)o||(o=r(t.shape)),p=o(p,h);else{p.value={};const w=l.shape;for(const k of l.keys){const O=w[k],M=O._zod.run({value:f[k],issues:[]},h),K=O._zod.optin==="optional"&&O._zod.optout==="optional";M instanceof Promise?y.push(M.then(Se=>K?Eo(Se,p,k,f):bn(Se,p,k))):K?Eo(M,p,k,f):bn(M,p,k)}}if(!u)return y.length?Promise.all(y).then(()=>p):p;const P=[],S=l.keySet,j=u._zod,R=j.def.type;for(const w of Object.keys(f)){if(S.has(w))continue;if(R==="never"){P.push(w);continue}const k=j.run({value:f[w],issues:[]},h);k instanceof Promise?y.push(k.then(O=>bn(O,p,w))):bn(k,p,w)}return P.length&&p.issues.push({code:"unrecognized_keys",keys:P,input:f,inst:e}),y.length?Promise.all(y).then(()=>p):p}});function Co(e,t,n,r){for(const o of e)if(o.issues.length===0)return t.value=o.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(o=>o.issues.map(s=>ct(s,r,at())))}),t}const dg=_("$ZodUnion",(e,t)=>{Q.init(e,t),ne(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),ne(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),ne(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),ne(e._zod,"pattern",()=>{if(t.options.every(n=>n._zod.pattern)){const n=t.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>qr(r.source)).join("|")})$`)}}),e._zod.parse=(n,r)=>{let o=!1;const s=[];for(const i of t.options){const a=i._zod.run({value:n.value,issues:[]},r);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>Co(i,n,e,r)):Co(s,n,e,r)}}),pg=_("$ZodIntersection",(e,t)=>{Q.init(e,t),e._zod.parse=(n,r)=>{const o=n.value,s=t.left._zod.run({value:o,issues:[]},r),i=t.right._zod.run({value:o,issues:[]},r);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>Po(n,c,u)):Po(n,s,i)}});function rr(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Tn(e)&&Tn(t)){const n=Object.keys(t),r=Object.keys(e).filter(s=>n.indexOf(s)!==-1),o={...e,...t};for(const s of r){const i=rr(e[s],t[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const o=e[r],s=t[r],i=rr(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Po(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),Dt(e))return e;const r=rr(t.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}const hg=_("$ZodRecord",(e,t)=>{Q.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!Tn(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;const s=[];if(t.keyType._zod.values){const i=t.keyType._zod.values;n.value={};for(const c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){const u=t.valueType._zod.run({value:o[c],issues:[]},r);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&n.issues.push(...gt(c,l.issues)),n.value[c]=l.value})):(u.issues.length&&n.issues.push(...gt(c,u.issues)),n.value[c]=u.value)}let a;for(const c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:a})}else{n.value={};for(const i of Reflect.ownKeys(o)){if(i==="__proto__")continue;const a=t.keyType._zod.run({value:i,issues:[]},r);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>ct(u,r,at())),input:i,path:[i],inst:e}),n.value[a.value]=a.value;continue}const c=t.valueType._zod.run({value:o[i],issues:[]},r);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&n.issues.push(...gt(i,u.issues)),n.value[a.value]=u.value})):(c.issues.length&&n.issues.push(...gt(i,c.issues)),n.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>n):n}}),fg=_("$ZodEnum",(e,t)=>{Q.init(e,t);const n=xf(t.entries);e._zod.values=new Set(n),e._zod.pattern=new RegExp(`^(${n.filter(r=>If.has(typeof r)).map(r=>typeof r=="string"?sn(r):r.toString()).join("|")})$`),e._zod.parse=(r,o)=>{const s=r.value;return e._zod.values.has(s)||r.issues.push({code:"invalid_value",values:n,input:s,inst:e}),r}}),mg=_("$ZodLiteral",(e,t)=>{Q.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?sn(n):n?n.toString():String(n)).join("|")})$`),e._zod.parse=(n,r)=>{const o=n.value;return e._zod.values.has(o)||n.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),n}}),gg=_("$ZodTransform",(e,t)=>{Q.init(e,t),e._zod.parse=(n,r)=>{const o=t.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(n.value=i,n));if(o instanceof Promise)throw new Ht;return n.value=o,n}}),vg=_("$ZodOptional",(e,t)=>{Q.init(e,t),e._zod.optin="optional",e._zod.optout="optional",ne(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),ne(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${qr(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(n,r):n.value===void 0?n:t.innerType._zod.run(n,r)}),_g=_("$ZodNullable",(e,t)=>{Q.init(e,t),ne(e._zod,"optin",()=>t.innerType._zod.optin),ne(e._zod,"optout",()=>t.innerType._zod.optout),ne(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${qr(n.source)}|null)$`):void 0}),ne(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),bg=_("$ZodDefault",(e,t)=>{Q.init(e,t),e._zod.optin="optional",ne(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=t.defaultValue,n;const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>No(s,t)):No(o,t)}});function No(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const yg=_("$ZodPrefault",(e,t)=>{Q.init(e,t),e._zod.optin="optional",ne(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),wg=_("$ZodNonOptional",(e,t)=>{Q.init(e,t),ne(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>Zo(s,e)):Zo(o,e)}});function Zo(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const kg=_("$ZodCatch",(e,t)=>{Q.init(e,t),e._zod.optin="optional",ne(e._zod,"optout",()=>t.innerType._zod.optout),ne(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>(n.value=s.value,s.issues.length&&(n.value=t.catchValue({...n,error:{issues:s.issues.map(i=>ct(i,r,at()))},input:n.value}),n.issues=[]),n)):(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(s=>ct(s,r,at()))},input:n.value}),n.issues=[]),n)}}),$g=_("$ZodPipe",(e,t)=>{Q.init(e,t),ne(e._zod,"values",()=>t.in._zod.values),ne(e._zod,"optin",()=>t.in._zod.optin),ne(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(n,r)=>{const o=t.in._zod.run(n,r);return o instanceof Promise?o.then(s=>Oo(s,t,r)):Oo(o,t,r)}});function Oo(e,t,n){return Dt(e)?e:t.out._zod.run({value:e.value,issues:e.issues},n)}const Sg=_("$ZodReadonly",(e,t)=>{Q.init(e,t),ne(e._zod,"propValues",()=>t.innerType._zod.propValues),ne(e._zod,"values",()=>t.innerType._zod.values),ne(e._zod,"optin",()=>t.innerType._zod.optin),ne(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(Ao):Ao(o)}});function Ao(e){return e.value=Object.freeze(e.value),e}const xg=_("$ZodCustom",(e,t)=>{je.init(e,t),Q.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then(s=>jo(s,n,r,e));jo(o,n,r,e)}});function jo(e,t,n,r){if(!e){const o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),t.issues.push(Vt(o))}}class Rg{constructor(){this._map=new Map,this._idmap=new Map}add(t,...n){const r=n[0];if(this._map.set(t,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};return delete r.id,{...r,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}}function zg(){return new Rg}const yn=zg();function Tg(e,t){return new e({type:"string",...E(t)})}function Ig(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...E(t)})}function Mo(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...E(t)})}function Eg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...E(t)})}function Cg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...E(t)})}function Pg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...E(t)})}function Ng(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...E(t)})}function Zg(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...E(t)})}function Og(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...E(t)})}function Ag(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...E(t)})}function jg(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...E(t)})}function Mg(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...E(t)})}function Lg(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...E(t)})}function Dg(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...E(t)})}function Ug(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...E(t)})}function qg(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...E(t)})}function Fg(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...E(t)})}function Hg(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...E(t)})}function Vg(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...E(t)})}function Bg(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...E(t)})}function Jg(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...E(t)})}function Wg(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...E(t)})}function Kg(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...E(t)})}function Gg(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...E(t)})}function Yg(e,t){return new e({type:"string",format:"date",check:"string_format",...E(t)})}function Qg(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...E(t)})}function Xg(e,t){return new e({type:"string",format:"duration",check:"string_format",...E(t)})}function ev(e,t){return new e({type:"number",checks:[],...E(t)})}function tv(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...E(t)})}function nv(e,t){return new e({type:"boolean",...E(t)})}function rv(e,t){return new e({type:"undefined",...E(t)})}function ov(e){return new e({type:"any"})}function sv(e){return new e({type:"unknown"})}function iv(e,t){return new e({type:"never",...E(t)})}function Lo(e,t){return new Ai({check:"less_than",...E(t),value:e,inclusive:!1})}function Jn(e,t){return new Ai({check:"less_than",...E(t),value:e,inclusive:!0})}function Do(e,t){return new ji({check:"greater_than",...E(t),value:e,inclusive:!1})}function Wn(e,t){return new ji({check:"greater_than",...E(t),value:e,inclusive:!0})}function Uo(e,t){return new _m({check:"multiple_of",...E(t),value:e})}function Di(e,t){return new ym({check:"max_length",...E(t),maximum:e})}function In(e,t){return new wm({check:"min_length",...E(t),minimum:e})}function Ui(e,t){return new km({check:"length_equals",...E(t),length:e})}function av(e,t){return new $m({check:"string_format",format:"regex",...E(t),pattern:e})}function cv(e){return new Sm({check:"string_format",format:"lowercase",...E(e)})}function uv(e){return new xm({check:"string_format",format:"uppercase",...E(e)})}function lv(e,t){return new Rm({check:"string_format",format:"includes",...E(t),includes:e})}function dv(e,t){return new zm({check:"string_format",format:"starts_with",...E(t),prefix:e})}function pv(e,t){return new Tm({check:"string_format",format:"ends_with",...E(t),suffix:e})}function an(e){return new Im({check:"overwrite",tx:e})}function hv(e){return an(t=>t.normalize(e))}function fv(){return an(e=>e.trim())}function mv(){return an(e=>e.toLowerCase())}function gv(){return an(e=>e.toUpperCase())}function vv(e,t,n){return new e({type:"array",element:t,...E(n)})}function _v(e,t,n){return new e({type:"custom",check:"custom",fn:t,...E(n)})}const bv=_("ZodISODateTime",(e,t)=>{Fm.init(e,t),pe.init(e,t)});function yv(e){return Gg(bv,e)}const wv=_("ZodISODate",(e,t)=>{Hm.init(e,t),pe.init(e,t)});function kv(e){return Yg(wv,e)}const $v=_("ZodISOTime",(e,t)=>{Vm.init(e,t),pe.init(e,t)});function Sv(e){return Qg($v,e)}const xv=_("ZodISODuration",(e,t)=>{Bm.init(e,t),pe.init(e,t)});function Rv(e){return Xg(xv,e)}const zv=(e,t)=>{Ti.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>Lf(e,n)},flatten:{value:n=>Mf(e,n)},addIssue:{value:n=>e.issues.push(n)},addIssues:{value:n=>e.issues.push(...n)},isEmpty:{get(){return e.issues.length===0}}})},qn=_("ZodError",zv,{Parent:Error}),Tv=Df(qn),Iv=Uf(qn),Ev=Ei(qn),Cv=Ci(qn),ce=_("ZodType",(e,t)=>(Q.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),e.clone=(n,r)=>_t(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.parse=(n,r)=>Tv(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>Ev(e,n,r),e.parseAsync=async(n,r)=>Iv(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>Cv(e,n,r),e.spa=e.safeParseAsync,e.refine=(n,r)=>e.check(x_(n,r)),e.superRefine=n=>e.check(R_(n)),e.overwrite=n=>e.check(an(n)),e.optional=()=>Ho(e),e.nullable=()=>Vo(e),e.nullish=()=>Ho(Vo(e)),e.nonoptional=n=>v_(e,n),e.array=()=>Ve(e),e.or=n=>He([e,n]),e.and=n=>i_(e,n),e.transform=n=>Bo(e,d_(n)),e.default=n=>f_(e,n),e.prefault=n=>g_(e,n),e.catch=n=>b_(e,n),e.pipe=n=>Bo(e,n),e.readonly=()=>k_(e),e.describe=n=>{const r=e.clone();return yn.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){return yn.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return yn.get(e);const r=e.clone();return yn.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),qi=_("_ZodString",(e,t)=>{Vr.init(e,t),ce.init(e,t);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...r)=>e.check(av(...r)),e.includes=(...r)=>e.check(lv(...r)),e.startsWith=(...r)=>e.check(dv(...r)),e.endsWith=(...r)=>e.check(pv(...r)),e.min=(...r)=>e.check(In(...r)),e.max=(...r)=>e.check(Di(...r)),e.length=(...r)=>e.check(Ui(...r)),e.nonempty=(...r)=>e.check(In(1,...r)),e.lowercase=r=>e.check(cv(r)),e.uppercase=r=>e.check(uv(r)),e.trim=()=>e.check(fv()),e.normalize=(...r)=>e.check(hv(...r)),e.toLowerCase=()=>e.check(mv()),e.toUpperCase=()=>e.check(gv())}),Pv=_("ZodString",(e,t)=>{Vr.init(e,t),qi.init(e,t),e.email=n=>e.check(Ig(Nv,n)),e.url=n=>e.check(Zg(Zv,n)),e.jwt=n=>e.check(Kg(Kv,n)),e.emoji=n=>e.check(Og(Ov,n)),e.guid=n=>e.check(Mo(qo,n)),e.uuid=n=>e.check(Eg(wn,n)),e.uuidv4=n=>e.check(Cg(wn,n)),e.uuidv6=n=>e.check(Pg(wn,n)),e.uuidv7=n=>e.check(Ng(wn,n)),e.nanoid=n=>e.check(Ag(Av,n)),e.guid=n=>e.check(Mo(qo,n)),e.cuid=n=>e.check(jg(jv,n)),e.cuid2=n=>e.check(Mg(Mv,n)),e.ulid=n=>e.check(Lg(Lv,n)),e.base64=n=>e.check(Bg(Bv,n)),e.base64url=n=>e.check(Jg(Jv,n)),e.xid=n=>e.check(Dg(Dv,n)),e.ksuid=n=>e.check(Ug(Uv,n)),e.ipv4=n=>e.check(qg(qv,n)),e.ipv6=n=>e.check(Fg(Fv,n)),e.cidrv4=n=>e.check(Hg(Hv,n)),e.cidrv6=n=>e.check(Vg(Vv,n)),e.e164=n=>e.check(Wg(Wv,n)),e.datetime=n=>e.check(yv(n)),e.date=n=>e.check(kv(n)),e.time=n=>e.check(Sv(n)),e.duration=n=>e.check(Rv(n))});function Y(e){return Tg(Pv,e)}const pe=_("ZodStringFormat",(e,t)=>{ae.init(e,t),qi.init(e,t)}),Nv=_("ZodEmail",(e,t)=>{Zm.init(e,t),pe.init(e,t)}),qo=_("ZodGUID",(e,t)=>{Pm.init(e,t),pe.init(e,t)}),wn=_("ZodUUID",(e,t)=>{Nm.init(e,t),pe.init(e,t)}),Zv=_("ZodURL",(e,t)=>{Om.init(e,t),pe.init(e,t)}),Ov=_("ZodEmoji",(e,t)=>{Am.init(e,t),pe.init(e,t)}),Av=_("ZodNanoID",(e,t)=>{jm.init(e,t),pe.init(e,t)}),jv=_("ZodCUID",(e,t)=>{Mm.init(e,t),pe.init(e,t)}),Mv=_("ZodCUID2",(e,t)=>{Lm.init(e,t),pe.init(e,t)}),Lv=_("ZodULID",(e,t)=>{Dm.init(e,t),pe.init(e,t)}),Dv=_("ZodXID",(e,t)=>{Um.init(e,t),pe.init(e,t)}),Uv=_("ZodKSUID",(e,t)=>{qm.init(e,t),pe.init(e,t)}),qv=_("ZodIPv4",(e,t)=>{Jm.init(e,t),pe.init(e,t)}),Fv=_("ZodIPv6",(e,t)=>{Wm.init(e,t),pe.init(e,t)}),Hv=_("ZodCIDRv4",(e,t)=>{Km.init(e,t),pe.init(e,t)}),Vv=_("ZodCIDRv6",(e,t)=>{Gm.init(e,t),pe.init(e,t)}),Bv=_("ZodBase64",(e,t)=>{Ym.init(e,t),pe.init(e,t)}),Jv=_("ZodBase64URL",(e,t)=>{Xm.init(e,t),pe.init(e,t)}),Wv=_("ZodE164",(e,t)=>{eg.init(e,t),pe.init(e,t)}),Kv=_("ZodJWT",(e,t)=>{ng.init(e,t),pe.init(e,t)}),Fi=_("ZodNumber",(e,t)=>{Li.init(e,t),ce.init(e,t),e.gt=(r,o)=>e.check(Do(r,o)),e.gte=(r,o)=>e.check(Wn(r,o)),e.min=(r,o)=>e.check(Wn(r,o)),e.lt=(r,o)=>e.check(Lo(r,o)),e.lte=(r,o)=>e.check(Jn(r,o)),e.max=(r,o)=>e.check(Jn(r,o)),e.int=r=>e.check(Fo(r)),e.safe=r=>e.check(Fo(r)),e.positive=r=>e.check(Do(0,r)),e.nonnegative=r=>e.check(Wn(0,r)),e.negative=r=>e.check(Lo(0,r)),e.nonpositive=r=>e.check(Jn(0,r)),e.multipleOf=(r,o)=>e.check(Uo(r,o)),e.step=(r,o)=>e.check(Uo(r,o)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function Ye(e){return ev(Fi,e)}const Gv=_("ZodNumberFormat",(e,t)=>{rg.init(e,t),Fi.init(e,t)});function Fo(e){return tv(Gv,e)}const Yv=_("ZodBoolean",(e,t)=>{og.init(e,t),ce.init(e,t)});function nt(e){return nv(Yv,e)}const Qv=_("ZodUndefined",(e,t)=>{sg.init(e,t),ce.init(e,t)});function or(e){return rv(Qv,e)}const Xv=_("ZodAny",(e,t)=>{ig.init(e,t),ce.init(e,t)});function Hi(){return ov(Xv)}const e_=_("ZodUnknown",(e,t)=>{ag.init(e,t),ce.init(e,t)});function It(){return sv(e_)}const t_=_("ZodNever",(e,t)=>{cg.init(e,t),ce.init(e,t)});function sr(e){return iv(t_,e)}const n_=_("ZodArray",(e,t)=>{ug.init(e,t),ce.init(e,t),e.element=t.element,e.min=(n,r)=>e.check(In(n,r)),e.nonempty=n=>e.check(In(1,n)),e.max=(n,r)=>e.check(Di(n,r)),e.length=(n,r)=>e.check(Ui(n,r)),e.unwrap=()=>e.element});function Ve(e,t){return vv(n_,e,t)}const r_=_("ZodObject",(e,t)=>{lg.init(e,t),ce.init(e,t),ne(e,"shape",()=>t.shape),e.keyof=()=>c_(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:It()}),e.loose=()=>e.clone({...e._zod.def,catchall:It()}),e.strict=()=>e.clone({...e._zod.def,catchall:sr()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>Zf(e,n),e.merge=n=>Of(e,n),e.pick=n=>Pf(e,n),e.omit=n=>Nf(e,n),e.partial=(...n)=>Af(Vi,e,n[0]),e.required=(...n)=>jf(Bi,e,n[0])});function $(e,t){const n={type:"object",get shape(){return Fr(this,"shape",{...e}),this.shape},...E(t)};return new r_(n)}const o_=_("ZodUnion",(e,t)=>{dg.init(e,t),ce.init(e,t),e.options=t.options});function He(e,t){return new o_({type:"union",options:e,...E(t)})}const s_=_("ZodIntersection",(e,t)=>{pg.init(e,t),ce.init(e,t)});function i_(e,t){return new s_({type:"intersection",left:e,right:t})}const a_=_("ZodRecord",(e,t)=>{hg.init(e,t),ce.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function rt(e,t,n){return new a_({type:"record",keyType:e,valueType:t,...E(n)})}const ir=_("ZodEnum",(e,t)=>{fg.init(e,t),ce.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,o)=>{const s={};for(const i of r)if(n.has(i))s[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new ir({...t,checks:[],...E(o),entries:s})},e.exclude=(r,o)=>{const s={...t.entries};for(const i of r)if(n.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new ir({...t,checks:[],...E(o),entries:s})}});function c_(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new ir({type:"enum",entries:n,...E(t)})}const u_=_("ZodLiteral",(e,t)=>{mg.init(e,t),ce.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function b(e,t){return new u_({type:"literal",values:Array.isArray(e)?e:[e],...E(t)})}const l_=_("ZodTransform",(e,t)=>{gg.init(e,t),ce.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=s=>{if(typeof s=="string")n.issues.push(Vt(s,n.value,t));else{const i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=e),i.continue??(i.continue=!0),n.issues.push(Vt(i))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n)):(n.value=o,n)}});function d_(e){return new l_({type:"transform",transform:e})}const Vi=_("ZodOptional",(e,t)=>{vg.init(e,t),ce.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Ho(e){return new Vi({type:"optional",innerType:e})}const p_=_("ZodNullable",(e,t)=>{_g.init(e,t),ce.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Vo(e){return new p_({type:"nullable",innerType:e})}const h_=_("ZodDefault",(e,t)=>{bg.init(e,t),ce.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function f_(e,t){return new h_({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const m_=_("ZodPrefault",(e,t)=>{yg.init(e,t),ce.init(e,t),e.unwrap=()=>e._zod.def.innerType});function g_(e,t){return new m_({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const Bi=_("ZodNonOptional",(e,t)=>{wg.init(e,t),ce.init(e,t),e.unwrap=()=>e._zod.def.innerType});function v_(e,t){return new Bi({type:"nonoptional",innerType:e,...E(t)})}const __=_("ZodCatch",(e,t)=>{kg.init(e,t),ce.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function b_(e,t){return new __({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const y_=_("ZodPipe",(e,t)=>{$g.init(e,t),ce.init(e,t),e.in=t.in,e.out=t.out});function Bo(e,t){return new y_({type:"pipe",in:e,out:t})}const w_=_("ZodReadonly",(e,t)=>{Sg.init(e,t),ce.init(e,t)});function k_(e){return new w_({type:"readonly",innerType:e})}const $_=_("ZodCustom",(e,t)=>{xg.init(e,t),ce.init(e,t)});function S_(e){const t=new je({check:"custom"});return t._zod.check=e,t}function x_(e,t={}){return _v($_,e,t)}function R_(e){const t=S_(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(Vt(r,n.value,t._zod.def));else{const o=r;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),n.issues.push(Vt(o))}},e(n.value,n)));return t}(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});class z_ extends Sf{_registeredMethods=new Set;_eventSlots=new Map;onEventDispatch(t,n){}_ensureEventSlot(t){let n=this._eventSlots.get(t);if(!n){let r=this.eventSchemas[t];if(!r)throw Error(`Unknown event: ${String(t)}`);n={listeners:[]},this._eventSlots.set(t,n);let o=r.shape.method.value;this._registeredMethods.add(o);let s=n;super.setNotificationHandler(r,i=>{let a=i.params;this.onEventDispatch(t,a),s.onHandler?.(a);for(let c of[...s.listeners])c(a)})}return n}setEventHandler(t,n){let r=this._ensureEventSlot(t);r.onHandler&&n&&console.warn(`[MCP Apps] on${String(t)} handler replaced. Use addEventListener("${String(t)}", …) to add multiple listeners without replacing.`),r.onHandler=n}getEventHandler(t){return this._eventSlots.get(t)?.onHandler}addEventListener(t,n){this._ensureEventSlot(t).listeners.push(n)}removeEventListener(t,n){let r=this._eventSlots.get(t);if(!r)return;let o=r.listeners.indexOf(n);o!==-1&&r.listeners.splice(o,1)}setRequestHandler=(t,n)=>{this._assertMethodNotRegistered(t,"setRequestHandler"),super.setRequestHandler(t,n)};setNotificationHandler=(t,n)=>{this._assertMethodNotRegistered(t,"setNotificationHandler"),super.setNotificationHandler(t,n)};warnIfRequestHandlerReplaced(t,n,r){n&&r&&console.warn(`[MCP Apps] ${t} handler replaced. Previous handler will no longer be called.`)}replaceRequestHandler=(t,n)=>{let r=t.shape.method.value;this._registeredMethods.add(r),super.setRequestHandler(t,n)};_assertMethodNotRegistered(t,n){let r=t.shape.method.value;if(this._registeredMethods.has(r))throw Error(`Handler for "${r}" already registered (via ${n}). Use addEventListener() to attach multiple listeners, or the on* setter for replace semantics.`);this._registeredMethods.add(r)}}var Ji="2026-01-26",T_="ui/notifications/tool-input-partial",I_=He([b("light"),b("dark")]).describe("Color theme preference for the host environment."),Bt=He([b("inline"),b("fullscreen"),b("pip")]).describe("Display mode for UI presentation."),E_=He([b("--color-background-primary"),b("--color-background-secondary"),b("--color-background-tertiary"),b("--color-background-inverse"),b("--color-background-ghost"),b("--color-background-info"),b("--color-background-danger"),b("--color-background-success"),b("--color-background-warning"),b("--color-background-disabled"),b("--color-text-primary"),b("--color-text-secondary"),b("--color-text-tertiary"),b("--color-text-inverse"),b("--color-text-ghost"),b("--color-text-info"),b("--color-text-danger"),b("--color-text-success"),b("--color-text-warning"),b("--color-text-disabled"),b("--color-border-primary"),b("--color-border-secondary"),b("--color-border-tertiary"),b("--color-border-inverse"),b("--color-border-ghost"),b("--color-border-info"),b("--color-border-danger"),b("--color-border-success"),b("--color-border-warning"),b("--color-border-disabled"),b("--color-ring-primary"),b("--color-ring-secondary"),b("--color-ring-inverse"),b("--color-ring-info"),b("--color-ring-danger"),b("--color-ring-success"),b("--color-ring-warning"),b("--font-sans"),b("--font-mono"),b("--font-weight-normal"),b("--font-weight-medium"),b("--font-weight-semibold"),b("--font-weight-bold"),b("--font-text-xs-size"),b("--font-text-sm-size"),b("--font-text-md-size"),b("--font-text-lg-size"),b("--font-heading-xs-size"),b("--font-heading-sm-size"),b("--font-heading-md-size"),b("--font-heading-lg-size"),b("--font-heading-xl-size"),b("--font-heading-2xl-size"),b("--font-heading-3xl-size"),b("--font-text-xs-line-height"),b("--font-text-sm-line-height"),b("--font-text-md-line-height"),b("--font-text-lg-line-height"),b("--font-heading-xs-line-height"),b("--font-heading-sm-line-height"),b("--font-heading-md-line-height"),b("--font-heading-lg-line-height"),b("--font-heading-xl-line-height"),b("--font-heading-2xl-line-height"),b("--font-heading-3xl-line-height"),b("--border-radius-xs"),b("--border-radius-sm"),b("--border-radius-md"),b("--border-radius-lg"),b("--border-radius-xl"),b("--border-radius-full"),b("--border-width-regular"),b("--shadow-hairline"),b("--shadow-sm"),b("--shadow-md"),b("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),C_=rt(E_.describe(`Style variables for theming MCP apps.
90
-
91
- Individual style keys are optional - hosts may provide any subset of these values.
92
- Values are strings containing CSS values (colors, sizes, font stacks, etc.).
93
-
94
- Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
95
- for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),He([Y(),or()]).describe(`Style variables for theming MCP apps.
96
-
97
- Individual style keys are optional - hosts may provide any subset of these values.
98
- Values are strings containing CSS values (colors, sizes, font stacks, etc.).
99
-
100
- Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
101
- for compatibility with Zod schema generation. Both are functionally equivalent for validation.`)).describe(`Style variables for theming MCP apps.
102
-
103
- Individual style keys are optional - hosts may provide any subset of these values.
104
- Values are strings containing CSS values (colors, sizes, font stacks, etc.).
105
-
106
- Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
107
- for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),P_=$({method:b("ui/open-link"),params:$({url:Y().describe("URL to open in the host's browser")})});$({isError:nt().optional().describe("True if the host failed to open the URL (e.g., due to security policy).")}).passthrough();$({isError:nt().optional().describe("True if the download failed (e.g., user cancelled or host denied).")}).passthrough();$({isError:nt().optional().describe("True if the host rejected or failed to deliver the message.")}).passthrough();var N_=$({method:b("ui/notifications/sandbox-proxy-ready"),params:$({})}),Br=$({connectDomains:Ve(Y()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).
108
-
109
- - Maps to CSP \`connect-src\` directive
110
- - Empty or omitted → no network connections (secure default)`),resourceDomains:Ve(Y()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted → no network resources (secure default)"),frameDomains:Ve(Y()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted → no nested iframes allowed (`frame-src 'none'`)"),baseUriDomains:Ve(Y()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted → only same origin allowed (`base-uri 'self'`)")}),Jr=$({camera:$({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."),microphone:$({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."),geolocation:$({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."),clipboardWrite:$({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.")}),Z_=$({method:b("ui/notifications/size-changed"),params:$({width:Ye().optional().describe("New width in pixels."),height:Ye().optional().describe("New height in pixels.")})});$({method:b("ui/notifications/tool-input"),params:$({arguments:rt(Y(),It().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.")})});$({method:b("ui/notifications/tool-input-partial"),params:$({arguments:rt(Y(),It().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).")})});$({method:b("ui/notifications/tool-cancelled"),params:$({reason:Y().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").')})});var O_=$({fonts:Y().optional()}),A_=$({variables:C_.optional().describe("CSS variables for theming the app."),css:O_.optional().describe("CSS blocks that apps can inject.")});$({method:b("ui/resource-teardown"),params:$({})});var j_=rt(Y(),It()),Jo=$({text:$({}).optional().describe("Host supports text content blocks."),image:$({}).optional().describe("Host supports image content blocks."),audio:$({}).optional().describe("Host supports audio content blocks."),resource:$({}).optional().describe("Host supports resource content blocks."),resourceLink:$({}).optional().describe("Host supports resource link content blocks."),structuredContent:$({}).optional().describe("Host supports structured content.")}),M_=$({method:b("ui/notifications/request-teardown"),params:$({}).optional()}),L_=$({experimental:rt(Y(),rt(Y(),Hi()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),openLinks:$({}).optional().describe("Host supports opening external URLs."),downloadFile:$({}).optional().describe("Host supports file downloads via ui/download-file."),serverTools:$({listChanged:nt().optional().describe("Host supports tools/list_changed notifications.")}).optional().describe("Host can proxy tool calls to the MCP server."),serverResources:$({listChanged:nt().optional().describe("Host supports resources/list_changed notifications.")}).optional().describe("Host can proxy resource reads to the MCP server."),logging:$({}).optional().describe("Host accepts log messages."),sandbox:$({permissions:Jr.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."),csp:Br.optional().describe("CSP domains approved by the host.")}).optional().describe("Sandbox configuration applied by the host."),updateModelContext:Jo.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),message:Jo.optional().describe("Host supports receiving content messages (ui/message) from the view."),sampling:$({tools:$({}).optional().describe("Host supports tool use via `tools` and `toolChoice` parameters.")}).optional().describe("Host supports LLM sampling (sampling/createMessage) from the view.\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.")}),D_=$({experimental:rt(Y(),rt(Y(),Hi()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),tools:$({listChanged:nt().optional().describe("App supports tools/list_changed notifications.")}).optional().describe("App exposes MCP-style tools that the host can call."),availableDisplayModes:Ve(Bt).optional().describe("Display modes the app supports.")}),U_=$({method:b("ui/notifications/initialized"),params:$({}).optional()});$({csp:Br.optional().describe("Content Security Policy configuration for UI resources."),permissions:Jr.optional().describe("Sandbox permissions requested by the UI resource."),domain:Y().optional().describe(`Dedicated origin for view sandbox.
111
-
112
- Useful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists.
113
-
114
- **Host-dependent:** The format and validation rules for this field are determined by each host. Servers MUST consult host-specific documentation for the expected domain format. Common patterns include:
115
- - Hash-based subdomains (e.g., \`{hash}.claudemcpcontent.com\`)
116
- - URL-derived subdomains (e.g., \`www-example-com.oaiusercontent.com\`)
117
-
118
- If omitted, host uses default sandbox origin (typically per-conversation).`),prefersBorder:nt().optional().describe(`Visual boundary preference - true if view prefers a visible border.
119
-
120
- Boolean requesting whether a visible border and background is provided by the host. Specifying an explicit value for this is recommended because hosts' defaults may vary.
121
-
122
- - \`true\`: request visible border + background
123
- - \`false\`: request no visible border + background
124
- - omitted: host decides border`)});var Wo=$({method:b("ui/request-display-mode"),params:$({mode:Bt.describe("The display mode being requested.")})});$({mode:Bt.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough();var q_=He([b("model"),b("app")]).describe("Tool visibility scope - who can access the tool.");$({resourceUri:Y().optional(),visibility:Ve(q_).optional().describe(`Who can access this tool. Default: ["model", "app"]
125
- - "model": Tool visible to and callable by the agent
126
- - "app": Tool callable by the app from this server only`),csp:sr().optional(),permissions:sr().optional()});$({mimeTypes:Ve(Y()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')});var F_=$({method:b("ui/download-file"),params:$({contents:Ve(He([fi,mi])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),H_=$({method:b("ui/message"),params:$({role:b("user").describe('Message role, currently only "user" is supported.'),content:Ve(on).describe("Message content blocks (text, image, etc.).")})});$({method:b("ui/notifications/sandbox-resource-ready"),params:$({html:Y().describe("HTML content to load into the inner iframe."),sandbox:Y().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:Br.optional().describe("CSP configuration from resource metadata."),permissions:Jr.optional().describe("Sandbox permissions from resource metadata.")})});$({method:b("ui/notifications/tool-result"),params:Ft.describe("Standard MCP tool execution result.")});var Wi=$({toolInfo:$({id:Qt.optional().describe("JSON-RPC id of the tools/call request."),tool:Lr.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:I_.optional().describe("Current color theme preference."),styles:A_.optional().describe("Style configuration for theming the app."),displayMode:Bt.optional().describe("How the UI is currently displayed."),availableDisplayModes:Ve(Bt).optional().describe("Display modes the host supports."),containerDimensions:He([$({height:Ye().describe("Fixed container height in pixels.")}),$({maxHeight:He([Ye(),or()]).optional().describe("Maximum container height in pixels.")})]).and(He([$({width:Ye().describe("Fixed container width in pixels.")}),$({maxWidth:He([Ye(),or()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
127
- container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:Y().optional().describe("User's language and region preference in BCP 47 format."),timeZone:Y().optional().describe("User's timezone in IANA format."),userAgent:Y().optional().describe("Host application identifier."),platform:He([b("web"),b("desktop"),b("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:$({touch:nt().optional().describe("Whether the device supports touch input."),hover:nt().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:$({top:Ye().describe("Top safe area inset in pixels."),right:Ye().describe("Right safe area inset in pixels."),bottom:Ye().describe("Bottom safe area inset in pixels."),left:Ye().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough();$({method:b("ui/notifications/host-context-changed"),params:Wi.describe("Partial context update containing only changed fields.")});var V_=$({method:b("ui/update-model-context"),params:$({content:Ve(on).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:rt(Y(),It().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),B_=$({method:b("ui/initialize"),params:$({appInfo:Ln.describe("App identification (name and version)."),appCapabilities:D_.describe("Features and capabilities this app provides."),protocolVersion:Y().describe("Protocol version this app supports.")})});$({protocolVersion:Y().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Ln.describe("Host application identification and version."),hostCapabilities:L_.describe("Features and capabilities provided by the host."),hostContext:Wi.describe("Rich context about the host environment.")}).passthrough();class J_{eventTarget;eventSource;messageListener;constructor(t=window.parent,n){this.eventTarget=t,this.eventSource=n,this.messageListener=r=>{if(n&&r.source!==this.eventSource){console.debug("Ignoring message from unknown source",r);return}let o=Kp.safeParse(r.data);o.success?(console.debug("Parsed message",o.data),this.onmessage?.(o.data)):r.data?.jsonrpc!=="2.0"?console.debug("Ignoring non-JSON-RPC message",o.error.message,r):(console.error("Failed to parse message",o.error.message,r),this.onerror?.(Error("Invalid JSON-RPC message received: "+o.error.message)))}}async start(){window.addEventListener("message",this.messageListener)}async send(t,n){t.method!==T_&&console.debug("Sending message",t),this.eventTarget.postMessage(t,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion}var W_=[Ji];class K_ extends z_{_client;_hostInfo;_capabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_baseReplaceRequestHandler=this.replaceRequestHandler;replaceRequestHandler=(t,n)=>{this._baseReplaceRequestHandler(t,(r,o)=>(this._initializedReceived||console.warn(`[ext-apps] AppBridge received '${r.method}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`),n(r,o)))};eventSchemas={sizechange:Z_,sandboxready:N_,initialized:U_,requestteardown:M_,loggingmessage:wi};constructor(t,n,r,o){super(o),this._client=t,this._hostInfo=n,this._capabilities=r,this.addEventListener("initialized",()=>{this._initializedReceived=!0}),this._hostContext=o?.hostContext||{},this.setRequestHandler(B_,s=>this._oninitialize(s)),this.setRequestHandler(Dn,(s,i)=>(this.onping?.(s.params,i),{})),this.replaceRequestHandler(Wo,s=>({mode:this._hostContext.displayMode??"inline"}))}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;get onsizechange(){return this.getEventHandler("sizechange")}set onsizechange(t){this.setEventHandler("sizechange",t)}get onsandboxready(){return this.getEventHandler("sandboxready")}set onsandboxready(t){this.setEventHandler("sandboxready",t)}get oninitialized(){return this.getEventHandler("initialized")}set oninitialized(t){this.setEventHandler("initialized",t)}_onmessage;get onmessage(){return this._onmessage}set onmessage(t){this.warnIfRequestHandlerReplaced("onmessage",this._onmessage,t),this._onmessage=t,this.replaceRequestHandler(H_,async(n,r)=>{if(!this._onmessage)throw Error("No onmessage handler set");return this._onmessage(n.params,r)})}_onopenlink;get onopenlink(){return this._onopenlink}set onopenlink(t){this.warnIfRequestHandlerReplaced("onopenlink",this._onopenlink,t),this._onopenlink=t,this.replaceRequestHandler(P_,async(n,r)=>{if(!this._onopenlink)throw Error("No onopenlink handler set");return this._onopenlink(n.params,r)})}_ondownloadfile;get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(t){this.warnIfRequestHandlerReplaced("ondownloadfile",this._ondownloadfile,t),this._ondownloadfile=t,this.replaceRequestHandler(F_,async(n,r)=>{if(!this._ondownloadfile)throw Error("No ondownloadfile handler set");return this._ondownloadfile(n.params,r)})}get onrequestteardown(){return this.getEventHandler("requestteardown")}set onrequestteardown(t){this.setEventHandler("requestteardown",t)}_onrequestdisplaymode;get onrequestdisplaymode(){return this._onrequestdisplaymode}set onrequestdisplaymode(t){this.warnIfRequestHandlerReplaced("onrequestdisplaymode",this._onrequestdisplaymode,t),this._onrequestdisplaymode=t,this.replaceRequestHandler(Wo,async(n,r)=>{if(!this._onrequestdisplaymode)throw Error("No onrequestdisplaymode handler set");return this._onrequestdisplaymode(n.params,r)})}get onloggingmessage(){return this.getEventHandler("loggingmessage")}set onloggingmessage(t){this.setEventHandler("loggingmessage",t)}_onupdatemodelcontext;get onupdatemodelcontext(){return this._onupdatemodelcontext}set onupdatemodelcontext(t){this.warnIfRequestHandlerReplaced("onupdatemodelcontext",this._onupdatemodelcontext,t),this._onupdatemodelcontext=t,this.replaceRequestHandler(V_,async(n,r)=>{if(!this._onupdatemodelcontext)throw Error("No onupdatemodelcontext handler set");return this._onupdatemodelcontext(n.params,r)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(t){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,t),this._oncalltool=t,this.replaceRequestHandler(_i,async(n,r)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(n.params,r)})}set oncreatesamplingmessage(t){this.setRequestHandler(ki,async(n,r)=>t(n.params,r))}sendToolListChanged(t={}){return this.notification({method:"notifications/tools/list_changed",params:t})}_onlistresources;get onlistresources(){return this._onlistresources}set onlistresources(t){this.warnIfRequestHandlerReplaced("onlistresources",this._onlistresources,t),this._onlistresources=t,this.replaceRequestHandler(si,async(n,r)=>{if(!this._onlistresources)throw Error("No onlistresources handler set");return this._onlistresources(n.params,r)})}_onlistresourcetemplates;get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(t){this.warnIfRequestHandlerReplaced("onlistresourcetemplates",this._onlistresourcetemplates,t),this._onlistresourcetemplates=t,this.replaceRequestHandler(ai,async(n,r)=>{if(!this._onlistresourcetemplates)throw Error("No onlistresourcetemplates handler set");return this._onlistresourcetemplates(n.params,r)})}_onreadresource;get onreadresource(){return this._onreadresource}set onreadresource(t){this.warnIfRequestHandlerReplaced("onreadresource",this._onreadresource,t),this._onreadresource=t,this.replaceRequestHandler(ui,async(n,r)=>{if(!this._onreadresource)throw Error("No onreadresource handler set");return this._onreadresource(n.params,r)})}sendResourceListChanged(t={}){return this.notification({method:"notifications/resources/list_changed",params:t})}_onlistprompts;get onlistprompts(){return this._onlistprompts}set onlistprompts(t){this.warnIfRequestHandlerReplaced("onlistprompts",this._onlistprompts,t),this._onlistprompts=t,this.replaceRequestHandler(pi,async(n,r)=>{if(!this._onlistprompts)throw Error("No onlistprompts handler set");return this._onlistprompts(n.params,r)})}sendPromptListChanged(t={}){return this.notification({method:"notifications/prompts/list_changed",params:t})}assertCapabilityForMethod(t){}assertRequestHandlerCapability(t){}assertNotificationCapability(t){}assertTaskCapability(t){throw Error("Tasks are not supported in MCP Apps")}assertTaskHandlerCapability(t){throw Error("Task handlers are not supported in MCP Apps")}getCapabilities(){return this._capabilities}async _oninitialize(t){let n=t.params.protocolVersion;return this._appInfo!==void 0&&console.warn("[ext-apps] AppBridge received a second ui/initialize. The View may be double-mounting (e.g. React StrictMode in dev) without closing the previous App instance. Responding normally; the latest appInfo/appCapabilities replace the previous values."),this._appCapabilities=t.params.appCapabilities,this._appInfo=t.params.appInfo,{protocolVersion:W_.includes(n)?n:Ji,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(t){let n={},r=!1;for(let o of Object.keys(t)){let s=this._hostContext[o],i=t[o];G_(s,i)||(n[o]=i,r=!0)}r&&(this._hostContext=t,this.sendHostContextChange(n))}sendHostContextChange(t){return this.notification({method:"ui/notifications/host-context-changed",params:t})}sendToolInput(t){return this.notification({method:"ui/notifications/tool-input",params:t})}sendToolInputPartial(t){return this.notification({method:"ui/notifications/tool-input-partial",params:t})}sendToolResult(t){return this.notification({method:"ui/notifications/tool-result",params:t})}sendToolCancelled(t){return this.notification({method:"ui/notifications/tool-cancelled",params:t})}sendSandboxResourceReady(t){return this.notification({method:"ui/notifications/sandbox-resource-ready",params:t})}teardownResource(t,n){return this.request({method:"ui/resource-teardown",params:t},j_,n)}sendResourceTeardown=this.teardownResource;callTool(t,n){return this.request({method:"tools/call",params:t},Ft,n)}listTools(t,n){return this.request({method:"tools/list",params:t},vi,n)}async connect(t){if(this.transport)throw Error("AppBridge is already connected. Call close() before connecting again.");if(this._initializedReceived=!1,this._client){let n=this._client.getServerCapabilities();if(!n)throw Error("Client server capabilities not available");n.tools&&(this.oncalltool=async(r,o)=>this._client.request({method:"tools/call",params:r},Ft,{signal:o.signal}),n.tools.listChanged&&this._client.setNotificationHandler(bi,r=>this.sendToolListChanged(r.params))),n.resources&&(this.onlistresources=async(r,o)=>this._client.request({method:"resources/list",params:r},ii,{signal:o.signal}),this.onlistresourcetemplates=async(r,o)=>this._client.request({method:"resources/templates/list",params:r},ci,{signal:o.signal}),this.onreadresource=async(r,o)=>this._client.request({method:"resources/read",params:r},li,{signal:o.signal}),n.resources.listChanged&&this._client.setNotificationHandler(di,r=>this.sendResourceListChanged(r.params))),n.prompts&&(this.onlistprompts=async(r,o)=>this._client.request({method:"prompts/list",params:r},hi,{signal:o.signal}),n.prompts.listChanged&&this._client.setNotificationHandler(gi,r=>this.sendPromptListChanged(r.params)))}return super.connect(t)}}function G_(e,t){return JSON.stringify(e)===JSON.stringify(t)}const Ki=m.createContext(null);function Y_({extension:e,children:t}){return d.jsx(Ki.Provider,{value:e??null,children:t})}function Wr(){return m.useContext(Ki)}var Kr=(e=>(e.PROVIDER_QUOTA_EXHAUSTED="PROVIDER_QUOTA_EXHAUSTED",e.PROVIDER_AUTH="PROVIDER_AUTH",e.PROVIDER_UNKNOWN_MODEL="PROVIDER_UNKNOWN_MODEL",e.PROVIDER_BASE_URL_UNRESOLVED="PROVIDER_BASE_URL_UNRESOLVED",e.NO_MODEL_CONFIGURED="NO_MODEL_CONFIGURED",e.WORKER_UNRESPONSIVE="WORKER_UNRESPONSIVE",e.WORKER_DIED="WORKER_DIED",e.WORKER_STARTUP_FAILED="WORKER_STARTUP_FAILED",e.PROVIDER_TOOL_CALL_FAILED="PROVIDER_TOOL_CALL_FAILED",e.SESSION_TIMEOUT="SESSION_TIMEOUT",e))(Kr||{});const Q_={PROVIDER_QUOTA_EXHAUSTED:{cta:"provider-management",ctaLabel:"Manage provider"},PROVIDER_AUTH:{cta:"provider-management",ctaLabel:"Reconnect provider"},PROVIDER_UNKNOWN_MODEL:{cta:"agent-settings",ctaLabel:"Choose model"},PROVIDER_BASE_URL_UNRESOLVED:{cta:"provider-management",ctaLabel:"Manage provider"},PROVIDER_TOOL_CALL_FAILED:{message:"The model provider rejected its own tool call and ended the turn. This is usually temporary — please try again.",cta:"none"},NO_MODEL_CONFIGURED:{message:"No model is configured for this agent. Choose a model in agent settings.",cta:"agent-settings",ctaLabel:"Choose a model"},WORKER_UNRESPONSIVE:{message:"The agent didn't finish responding in time. This is usually temporary — please try again.",cta:"none"},WORKER_DIED:{message:"The agent stopped unexpectedly before it could reply. This is usually temporary — please try again.",cta:"none"},WORKER_STARTUP_FAILED:{message:"The agent couldn't start, so your request wasn't processed. Please try again in a moment.",cta:"none"},SESSION_TIMEOUT:{cta:"none",silent:!0}};function X_(e){if(typeof e=="string")return Object.values(Kr).includes(e)?e:void 0}const eb=Object.freeze(Object.defineProperty({__proto__:null,AGENT_ERRORS:Q_,AgentErrorCode:Kr,toAgentErrorCode:X_},Symbol.toStringTag,{value:"Module"})),{AGENT_ERRORS:tb,toAgentErrorCode:nb}=eb;function Ko(e,t){if(!t)return null;try{const n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?null:new URL(e,`${n.origin}/`).toString()}catch{return null}}function Gi(e,t){const n=nb(e);if(!n)return null;const r=tb[n];if(r.cta==="none"||!t.workspaceSlug)return null;const o=encodeURIComponent(t.workspaceSlug);if(r.cta==="provider-connect"||r.cta==="provider-management"){const i=t.provider?`/${o}/connectors/${encodeURIComponent(`${_a}${t.provider}`)}`:`/${o}/connectors`,a=Ko(i,t.webOrigin);if(!a)return null;const c=new URL(a);return t.provider&&t.model&&c.searchParams.set("model",t.model),{label:r.ctaLabel??"Connect a provider",href:c.toString()}}if(!t.agentId)return null;const s=Ko(`/${o}/agents/${encodeURIComponent(t.agentId)}/settings`,t.webOrigin);return s?{label:r.ctaLabel??"Open settings",href:s}:null}function Yi(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e.subscribable;if(!t||typeof t!="object"||Array.isArray(t))return null;const n=t;if(typeof n.connector_key!="string"||!n.connector_key||typeof n.resource_type!="string"||!n.resource_type||typeof n.resource_ref!="string"||!n.resource_ref||typeof n.label!="string"||!n.label)return null;const r=Array.isArray(n.suggested_event_keys)?n.suggested_event_keys.filter(o=>typeof o=="string"&&!!o):void 0;return{connector_key:n.connector_key,resource_type:n.resource_type,resource_ref:n.resource_ref,label:n.label,...r?.length?{suggested_event_keys:r}:{}}}const Go=new Set(["localhost","127.0.0.1","::1","[::1]"]);function rb(e){return e?.trim().toLowerCase().replace(/^\.+|\.+$/g,"")||null}function Yo(e,t){const n=rb(t);if(!n)return!1;const r=e.toLowerCase().replace(/\.$/,"");return r===n||r.endsWith(`.${n}`)}function Qo(e,t,n){try{const r=new URL(t),o=new URL(e,t),s=Go.has(o.hostname)&&Go.has(r.hostname),i=o.protocol===r.protocol&&(o.protocol==="https:"||o.protocol==="http:")&&Yo(o.hostname,n)&&Yo(r.hostname,n);return o.origin!==r.origin&&(s||i)&&(o.protocol=r.protocol,o.host=r.host),o.origin===r.origin&&o.pathname.startsWith("/api/v1/agents")&&(o.pathname=`/lobu${o.pathname}`),o.toString()}catch{return e}}const ob=/\.(png|jpe?g|gif|webp|avif|bmp|svg)$/i,Qi=new Set(["suggest_actions"]),ar="Thinking…";function sb(e){const{textOut:t,statusLine:n,errorText:r,toolCalls:o}=e,s=[];n===ar&&s.push({type:"reasoning"}),r&&s.push({type:"error",text:r});let i=t;return n&&n!==ar&&(i=t?`${t}
128
-
129
- ${n}`:n),i&&s.push({type:"text",text:i}),s.push(...o),s}const Gr=m.createContext(null);function cn(){const e=m.useContext(Gr);if(!e)throw new Error("useLobuChat must be used within <LobuChatProvider>");return e}function Gy({messages:e,children:t}){const n=m.useMemo(()=>({messages:e,running:!1,append:()=>{},cancel:()=>{},pendingAttachments:[],addAttachments:()=>{},removeAttachment:()=>{},agentId:null,conversationId:"",workspaceSlug:null,currentSuggestions:null}),[e]);return d.jsx(Gr.Provider,{value:n,children:t})}const Xi=/\[([^\]]*)\]\((\S*?\/api\/v1\/files\/[^)\s]+)\)/g;function Xo(e){return e.replace(/<lobu_internal_context>[\s\S]*?<\/lobu_internal_context>\n*/g,"").replace(Xi,"").replace(/\n{3,}/g,`
130
-
131
- `).trim()}function ib(e){const t=[];for(const n of e.matchAll(Xi)){const r=n[1]?.trim()||"file",o=n[2];o&&t.push({name:r,url:o})}return t}function ab(e,t={}){if(typeof e=="string"){const r=Xo(e);return r?[{type:"text",text:r}]:[]}if(!Array.isArray(e))return[];const n=[];for(const r of e){if(!r||typeof r!="object")continue;const o=r;if(o.type==="text"&&typeof o.text=="string"){const s=Xo(o.text);s&&n.push({type:"text",text:s})}else t.showToolCalls&&o.type==="toolCall"&&typeof o.name=="string"&&!Qi.has(o.name)&&n.push({type:"tool-call",toolCallId:o.id??`tc-${n.length}`,toolName:o.name,args:o.arguments??{}})}return n}function cb(e){const t=[],n=r=>{for(const{name:o,url:s}of ib(r))t.push({id:`file-${t.length}`,name:o,url:s,isImage:ob.test(o)})};if(typeof e=="string")return n(e),t.length>0?t:void 0;if(Array.isArray(e)){for(const r of e){if(!r||typeof r!="object")continue;const o=r;if(o.type==="image"&&typeof o.data=="string"){const s=o.mimeType||"image/png";t.push({id:`img-${t.length}`,name:`image-${t.length+1}`,imageDataUrl:`data:${s};base64,${o.data}`,isImage:!0})}else o.type==="text"&&typeof o.text=="string"&&n(o.text)}return t.length>0?t:void 0}}function ub(e,t){if(e.type==="bashExecution"){const r=e.content??{},o=e.timestamp?new Date(e.timestamp).getTime():void 0;return{id:e.id,role:"user",parts:[{type:"bash",command:r.command??"",output:r.output??"",exitCode:r.exitCode,cancelled:r.cancelled??!1}],createdAt:o&&!Number.isNaN(o)?o:void 0}}if(e.type!=="message"||e.isVerbose||e.role!=="assistant"&&e.role!=="user"&&e.role!=="system")return null;const n=e.timestamp?new Date(e.timestamp).getTime():void 0;return{id:e.id,role:e.role,parts:ab(e.content,t),attachments:cb(e.content),createdAt:n&&!Number.isNaN(n)?n:void 0}}const lb=[],db=[];function pb(e){let t=null;for(const n of e)n.type==="suggestion"&&(t=n.prompts.length>0?n.prompts:null);return t}function hb(e,t){if(e.length===0)return null;const n=[];for(const r of e)if(r.type!=="suggestion"){if(r.type==="agent-error"){n.push({type:"error",text:String(r.error??"Agent reported an error.")});const o=Gi(r.errorCode,{...t,provider:r.errorContext?.provider,model:r.errorContext?.model});o&&n.push({type:"tool-call",toolCallId:`error-run-${r.runId}`,toolName:"link-button",args:{label:o.label,url:o.href}});continue}n.push({type:"tool-call",toolCallId:`approval-event-${r.eventId}`,toolName:"tool-approval",args:{runId:r.runId,action:r.action,proposal:r.proposal,current:r.current,fields:r.fields??null,attribution:r.attribution??null,resourceKind:r.resourceKind??null,reason:r.reason??null,status:r.status??"pending",reviewedByName:r.reviewedByName??null,requestId:null}})}return n.length===0?null:{id:"history-interactions",role:"assistant",parts:n}}function Kn(e){try{return JSON.parse(e.data)}catch{return{content:e.data}}}const ft=e=>`${e}-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;function es(e){const t=[],n=new Set;for(const r of e){if(!r||typeof r!="object")continue;const{title:o,message:s}=r;if(typeof o!="string"||typeof s!="string")continue;const i=o.trim(),a=s.trim();if(i.length===0||a.length===0)continue;const c=`${i}\0${a}`;n.has(c)||(n.add(c),t.push({title:i,message:a}))}return t.length>0?t:null}function Yy({agentId:e,workspaceSlug:t,thread:n="agent-panel",loadHistory:r=!0,ephemeralContext:o,onFirstUserMessage:s,children:i,initialDraft:a}){const c=ba(),u=m.useRef(null),l=m.useRef(null),p=m.useRef(!1),h=m.useRef(o),f=m.useRef(void 0),[y,P]=m.useState(void 0),S=m.useRef(!1),j=m.useRef(null);h.current=o;const{data:R,isLoading:w}=ya(e,n,{orgSlug:t,enabled:r&&!!e&&!!n}),k=R?.messages??lb,O=R?.interactions??db,{data:M}=wa(e,{enabled:!!e}),K=!!(M?.showToolCalls??M?.settings?.showToolCalls),[Se,Ke]=m.useState([]),[we,Ne]=m.useState(!1),[Te,N]=m.useState([]);m.useEffect(()=>{y&&N([])},[y]);const[L,H]=m.useState(null),X=m.useRef(!1);X.current=we;const G=m.useMemo(()=>k.map(V=>ub(V,{showToolCalls:K})).filter(V=>V!==null),[k,K]),qe=m.useRef(!1);m.useEffect(()=>{if(qe.current||w||X.current)return;qe.current=!0;const V=hb(O,{workspaceSlug:t,agentId:e,webOrigin:typeof window>"u"?null:window.location.origin});Ke(V?[...G,V]:G),H(pb(O))},[e,w,G,O,t]);const Ze=m.useCallback(()=>{c.invalidateQueries({queryKey:["agent-thread-messages",t,e,n]}),c.invalidateQueries({queryKey:["agent-threads",t,e]})},[c,t,e,n]),Ge=m.useCallback(async()=>{if(u.current)return u.current;if(l.current)return l.current;if(!e)throw new Error("No agent selected");const V=(async()=>{const D=await Yn(`${Hn}/lobu/api/v1/agents`,{method:"POST",headers:{"Content-Type":"application/json",...t?{"x-lobu-org":t}:{}},credentials:"include",body:JSON.stringify({agentId:e,thread:n,...f.current?{executionTarget:f.current}:{}}),timeoutMs:2e4});if(!D.ok)throw await eo(D);const be=await D.json(),ke=ka(),ve={sessionId:be.agentId,sseUrl:Qo(be.sseUrl,Hn,ke),messagesUrl:Qo(be.messagesUrl,Hn,ke),executionTarget:be.executionTarget};return f.current=be.executionTarget,P(be.executionTarget),u.current=ve,ve})();l.current=V;try{return await V}catch(D){throw u.current=null,D}finally{l.current=null}},[e,t,n]),Xe=m.useCallback(async(V,D,be)=>{const ke=new AbortController;j.current=ke;const ve=q=>{Ke($e=>$e.map(Ee=>Ee.id===be?{...Ee,parts:q}:Ee))};let Le;try{Le=await Ge()}catch(q){ve([{type:"text",text:`Error: ${q instanceof Error?q.message:"Could not start a session."}`}]);return}const me=await $a(Le.sseUrl,{throwOnFailure:!0}),st=[];let bt=null;const Zt=()=>{const q=bt;bt=null,q?.()},yt=q=>{st.push(q),Zt()};let wt=!1,Ot=null,kt=null;const dn=new Promise(q=>{Ot=q});me.addEventListener("open",()=>{wt=!0,Ot?.()}),me.addEventListener("connected",q=>{wt||(wt=!0,Ot?.());const $e=q;if(typeof $e.data=="string"&&$e.data){const Ee=Kn($e).timestamp;typeof Ee=="number"&&(kt=Ee)}});const pn=q=>$e=>{const Ee=$e;typeof Ee.data=="string"&&yt({kind:q,payload:Kn(Ee)})},hn=["output","status","complete","closed","agent-error","question","suggestion","link-button","tool-approval","tool_use"];for(const q of hn)me.addEventListener(q,pn(q));me.addEventListener("error",q=>{const $e=q;if(typeof $e.data=="string"&&$e.data){yt({kind:"error",payload:Kn($e)});return}me.readyState===EventSource.CLOSED&&yt({kind:"error",payload:{error:"Connection closed"}})}),await Promise.race([dn,new Promise(q=>setTimeout(q,1500))]);const At=()=>{me.close(),Zt()};ke.signal.addEventListener("abort",At,{once:!0});try{const q=h.current?.trim(),$e=!!q&&!S.current;$e&&(S.current=!0);let Ee;if(D.length>0){const I=new FormData;I.set("content",V),$e&&q&&I.set("ephemeralContext",q);for(const jt of D)I.append("files",jt,jt.name);Ee={method:"POST",credentials:"include",body:I,timeoutMs:12e4}}else{const I={content:V};$e&&q&&(I.ephemeralContext=q),Ee={method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(I),timeoutMs:2e4}}const C=await Yn(Le.messagesUrl,Ee);if(!C.ok)throw u.current=null,await eo(C);let Z="",A=ar,Ie=null;const Fe=[],he=()=>sb({textOut:Z,statusLine:A,errorText:Ie,toolCalls:Fe});for(ve(he());!ke.signal.aborted;){if(st.length===0){let te;const Ce=await Promise.race([new Promise(Fn=>{bt=()=>Fn(!0)}),new Promise(Fn=>{te=setTimeout(()=>Fn(!1),12e4)})]);if(te&&clearTimeout(te),!Ce){A="No response yet — the agent may be handling this elsewhere (e.g. a connected platform).",Ze(),ve(he()),me.close();return}continue}const I=st.shift();if(!I)continue;const jt=I.payload.timestamp;if(!(kt!=null&&typeof jt=="number"&&jt<kt)){if(I.kind==="output")A=null,Z+=String(I.payload.content??"");else if(I.kind==="status")A=String(I.payload.status??"Working");else if(I.kind==="complete"){A=null;const te=I.payload.finalText;typeof te=="string"&&te.length>0&&(Z=te);const Ce=I.payload.suggestions;Ce!==void 0&&H(Array.isArray(Ce)?es(Ce):null),Ze(),ve(he());return}else if(I.kind==="closed"){u.current=null;const te=I.payload.reason;A=`Session ended${te?`: ${te}`:""}.`,Ze(),ve(he());return}else if(I.kind==="error"||I.kind==="agent-error"){A=null,Ie=typeof I.payload.error=="string"&&I.payload.error?I.payload.error:"Agent reported an error.";const te=I.payload.errorContext&&typeof I.payload.errorContext=="object"?I.payload.errorContext:void 0,Ce=Gi(I.payload.errorCode,{workspaceSlug:t,agentId:e,webOrigin:typeof window>"u"?null:window.location.origin,provider:typeof te?.provider=="string"?te.provider:void 0,model:typeof te?.model=="string"?te.model:void 0});Ce&&Fe.push({type:"tool-call",toolCallId:ft("l"),toolName:"link-button",args:{label:Ce.label,url:Ce.href}}),Ze(),ve(he());return}else if(I.kind==="question")Fe.push({type:"tool-call",toolCallId:ft("q"),toolName:"question",args:{question:I.payload.question??"",options:I.payload.options??[]}});else if(I.kind==="tool_use"){if(A=null,Qi.has(I.payload.name??"")){ve(he());continue}const te=I.payload.result_summary,Ce=Yi(te);if(!K&&!Ce){ve(he());continue}Fe.push({type:"tool-call",toolCallId:I.payload.toolCallId??ft("t"),toolName:K?I.payload.name??"tool":"subscription-candidate",args:K?I.payload.input??{}:null,result:te,isError:I.payload.isError})}else if(I.kind==="suggestion"){const te=I.payload.prompts;te!==void 0&&(H(Array.isArray(te)?es(te):null),ve(he()))}else if(I.kind==="link-button")Fe.push({type:"tool-call",toolCallId:ft("l"),toolName:"link-button",args:{label:I.payload.label??"Open link",url:I.payload.url??""}});else if(I.kind==="tool-approval"){const te=Le.messagesUrl.replace(/\/agents\/[^/]+\/messages$/,"/agents/approve"),Ce=I.payload.runId;Fe.push({type:"tool-call",toolCallId:I.payload.requestId??(Ce!=null?`run-${Ce}`:ft("a")),toolName:"tool-approval",args:{requestId:I.payload.requestId??null,tool:I.payload.toolName??"a tool",args:I.payload.args??null,durationOptions:I.payload.durationOptions??["1h","24h","always"],approveUrl:te,orgSlug:t??null,runId:Ce??null,action:I.payload.action??null,proposal:I.payload.proposal??null,current:I.payload.current??null,fields:I.payload.fields??null,attribution:I.payload.attribution??null,resourceKind:I.payload.resourceKind??null}})}ve(he())}}}catch(q){ve([{type:"text",text:`Error: ${q instanceof Error?q.message:"Send failed."}`}])}finally{ke.signal.removeEventListener("abort",At),me.close()}},[e,Ge,Ze,K,t]),dt=m.useCallback(V=>{const D=V.trim(),be=Te.map(me=>me.file);if(!D&&be.length===0||X.current||!e)return;p.current||(p.current=!0,s?.(D||be[0]?.name||""));const ke={id:ft("u"),role:"user",parts:D?[{type:"text",text:D}]:[],attachments:Te.map(me=>({id:me.id,name:me.name,isImage:me.isImage,imageDataUrl:me.isImage?URL.createObjectURL(me.file):void 0})),createdAt:Date.now()},ve=ft("asst"),Le={id:ve,role:"assistant",parts:[{type:"reasoning"}],createdAt:Date.now()};Ke(me=>[...me,ke,Le]),N([]),Ne(!0),X.current=!0,Xe(D,be,ve).finally(()=>{Ne(!1),X.current=!1,j.current=null})},[e,s,Te,Xe]),Me=m.useCallback(()=>{j.current?.abort()},[]),ot=m.useCallback(V=>{const D=Array.from(V);N(be=>[...be,...D.map(ke=>({id:crypto.randomUUID(),name:ke.name,file:ke,isImage:ke.type.startsWith("image/")}))])},[]),ge=m.useCallback(V=>{N(D=>D.filter(be=>be.id!==V))},[]),pt=m.useRef(!1);m.useEffect(()=>{if(pt.current)return;const V=Qa(n);V&&(pt.current=!0,f.current=V.executionTarget,P(V.executionTarget),dt(V.text))},[n,dt]),m.useEffect(()=>{w||G.length===0||Ge().catch(()=>{})},[Ge,G.length,w]);const ln=m.useMemo(()=>({messages:Se,running:we,append:dt,cancel:Me,pendingAttachments:Te,addAttachments:ot,removeAttachment:ge,initialDraft:a,agentId:e,conversationId:n,workspaceSlug:t,currentSuggestions:L,executionTarget:y}),[Se,we,dt,Me,Te,ot,ge,a,e,n,t,L,y]);return r&&w?d.jsx(Wa,{}):d.jsx(Gr.Provider,{value:ln,children:i})}const ts="mx-0.5 inline-flex items-center gap-1 rounded-md bg-accent px-1.5 py-0.5 align-baseline font-medium text-[0.9em] text-accent-foreground no-underline";function fb({refItem:e}){const t=tc[e.kind]??Sa;return nc(e.path)?d.jsxs("span",{className:ts,children:[d.jsx(t,{className:"h-3 w-3 shrink-0 opacity-70"}),e.label]}):d.jsxs(as,{to:e.path,className:fe(ts,"hover:bg-accent/80"),children:[d.jsx(t,{className:"h-3 w-3 shrink-0 opacity-70"}),e.label]})}const Yr=({text:e,renderText:t})=>Xa(e)?d.jsx(d.Fragment,{children:ec(e).map((n,r)=>n.type==="ref"?d.jsx(fb,{refItem:n.ref},`r${r}`):d.jsx("span",{children:t(n.text)},`t${r}`))}):d.jsx(d.Fragment,{children:t(e)}),mb=({label:e="Thinking"})=>d.jsx("span",{className:"aui-thinking-shimmer inline-block text-sm","aria-live":"polite","aria-busy":"true",children:e}),ea=m.createContext(null),ta=()=>{const e=m.useContext(ea);if(!e)throw new Error("ChainOfThought components must be used within ChainOfThought");return e},na=m.memo(({className:e,open:t,defaultOpen:n=!1,onOpenChange:r,children:o,...s})=>{const[i,a]=xa({prop:t,defaultProp:n,onChange:r}),c=m.useMemo(()=>({isOpen:i,setIsOpen:a}),[i,a]);return d.jsx(ea.Provider,{value:c,children:d.jsx("div",{className:fe("not-prose max-w-prose space-y-4",e),...s,children:o})})}),ra=m.memo(({className:e,children:t,...n})=>{const{isOpen:r,setIsOpen:o}=ta();return d.jsx(cs,{onOpenChange:o,open:r,children:d.jsxs(Ra,{className:fe("flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",e),...n,children:[d.jsx(za,{className:"size-4"}),d.jsx("span",{className:"flex-1 text-left",children:t??"Chain of Thought"}),d.jsx(Ta,{className:fe("size-4 transition-transform",r?"rotate-180":"rotate-0")})]})})}),oa=m.memo(({className:e,icon:t=Ea,label:n,description:r,status:o="complete",children:s,...i})=>{const a={complete:"text-muted-foreground",active:"text-foreground",pending:"text-muted-foreground/50"};return d.jsxs("div",{className:fe("flex gap-2 text-sm",a[o],"fade-in-0 slide-in-from-top-2 animate-in",e),...i,children:[d.jsxs("div",{className:"relative mt-0.5",children:[d.jsx(t,{className:"size-4"}),d.jsx("div",{className:"-mx-px absolute top-7 bottom-0 left-1/2 w-px bg-border"})]}),d.jsxs("div",{className:"flex-1 space-y-2 overflow-hidden",children:[d.jsx("div",{children:n}),r&&d.jsx("div",{className:"text-muted-foreground text-xs",children:r}),s]})]})}),sa=m.memo(({className:e,children:t,...n})=>{const{isOpen:r}=ta();return d.jsx(cs,{open:r,children:d.jsx(Ia,{className:fe("mt-2 space-y-3","data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-popover-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in",e),...n,children:t})})});na.displayName="ChainOfThought";ra.displayName="ChainOfThoughtHeader";oa.displayName="ChainOfThoughtStep";sa.displayName="ChainOfThoughtContent";function gb(e){const t=e.current?.loser??{};return{duplicates:Array.isArray(e.current?.duplicates)?e.current.duplicates:[t],winner:e.current?.winner??{}}}function ia(e,t){if(e.length===0)return"No deterministic identity match details are available for these records.";if(e.length===1&&t===2){const[n]=e;return`Both records have the same ${String(n?.kind??"identity")}: ${String(n?.identifier??"")}.`}return`Recorded match evidence:
132
- ${e.map(n=>`• ${String(n.kind??"Identity")}: ${String(n.identifier??"")}`).join(`
133
- `)}`}function En(e,t,n){const r=String(t.id??e.toLowerCase());let o;const s=[],i=new Set;typeof t.href=="string"&&(n.add(t.href),o={id:`entity-${r}`,label:"Open record",variant:"ghost",icon:"external",terminal:!1,tool:"open_review_link",args:{url:t.href}});const a=new Set;for(const c of Array.isArray(t.identities)?t.identities:[]){const u=String(c.connection_name??c.source_connector??"Unknown source");a.add(`${u} · ${String(c.namespace??"identity")}: ${String(c.identifier??"")}`),!(typeof c.connection_href!="string"||i.has(c.connection_href))&&(i.add(c.connection_href),n.add(c.connection_href),s.push({id:`connection-${String(c.id??c.connection_href)}`,label:`Open source: ${u}`,variant:"ghost",icon:"external",terminal:!1,tool:"open_review_link",args:{url:c.connection_href}}))}return{type:"entity",id:r,label:e,name:String(t.name??`Entity ${r}`),details:[...a],recordLink:o,sourceLinks:s}}function Qr(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&!Array.isArray(t)):[]}function ns(e){return`${String(e.kind??"Identity")}: ${String(e.identifier??"")}`}function rs(e){if(!Array.isArray(e))return null;const t=Qr(e);return t.length===e.length&&t.every(n=>typeof n.kind=="string"&&n.kind.trim().length>0&&typeof n.identifier=="string"&&n.identifier.trim().length>0)?t:null}function vb(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,n=rs(t.dropped),r=rs(t.gained);if(!n||!r)return null;const o=[];for(const s of n)o.push(`− No longer proven — ${ns(s)}`);for(const s of r)o.push(`+ Newly proven — ${ns(s)}`);return{weakened:n.length>0,block:{type:"text",label:n.length>0?"What changed since you reviewed this":r.length>0?"What the re-check newly found":"What changed since you reviewed this",value:o.length>0?o.join(`
134
- `):"The recorded match evidence did not change."}}}function _b(e){const{duplicates:t,winner:n}=gb(e),r=Qr(e.proposal?.evidence),o=new Set,s=typeof e.status=="string"?e.status:"pending",i=s==="pending",a=s==="rejected"?"Kept separate":s==="failed"?"Failed":"Approved",c=typeof e.reason=="string"?e.reason:typeof e.proposal?.reason=="string"?e.proposal.reason:null,u=[{type:"text",label:"Why Lobu thinks they match",value:ia(r,t.length+1)}];c&&u.push({type:"text",label:"Why this needs review",value:c,muted:!0});const l=vb(e.proposal?.evidence_change);l&&u.push(l.block),u.push(...t.map(h=>En("Duplicate",h,o)),En("Canonical",n,o),{type:"text",value:i?`If approved, ${t.length===1?"the":"each"} duplicate's relationships and aliases will move to the canonical record.`:typeof e.reviewedByName=="string"?`${a} by ${e.reviewedByName}.`:`${a}.`,muted:!0});const p=i?[{id:"approve",label:l?"Approve again to apply":"Approve merge",variant:"primary",icon:"check",...l?.weakened?{confirm:!0,confirmPrompt:"The evidence for this merge no longer holds. Merge these records anyway?"}:{},tool:"manage_operations",args:{action:"approve"},resolvedLabel:"Merge approved and is being applied."},{id:"reject",label:"Keep separate",variant:"outline",icon:"x",confirm:!0,confirmPrompt:"Keep these entities separate?",tool:"manage_operations",args:{action:"reject"},resolvedLabel:"The entities were kept separate."}]:[];return{view:{title:`Merge ${t.length} duplicate ${t.length===1?"record":"records"}${i?"":` · ${a}`}`,icon:"entity",impact:i?{level:"high",reason:"This combines duplicate records into the selected winner."}:{level:"normal"},tone:i||s==="failed"?"warning":"default",blocks:u,actions:p},reviewUrls:o}}function Qy(e){const t=e.loser&&typeof e.loser=="object"&&!Array.isArray(e.loser)?{...e.loser}:{},n=e.winner&&typeof e.winner=="object"&&!Array.isArray(e.winner)?{...e.winner}:{};typeof e.loserHref=="string"&&(t.href=e.loserHref),typeof e.winnerHref=="string"&&(n.href=e.winnerHref);const r=Qr(e.evidence),o=new Set,s=e.status==="active",a=s&&e.canUndo===!0?[{id:"undo",label:"Undo merge",variant:"outline",icon:"x",confirm:!0,confirmPrompt:"Undo this automatic merge?",tool:"manage_entity",args:{action:"unmerge"},resolvedLabel:"Merge undone."}]:[];return{view:{title:s?"Merged automatically":"Automatic merge undone",icon:"entity",impact:{level:"normal"},tone:s?"default":"warning",blocks:[{type:"text",label:"Why Lobu merged them",value:ia(r,2)},En("Duplicate",t,o),En("Canonical",n,o),{type:"text",value:s?"The entity type's deterministic identity rule applied this merge without human review.":"This automatic merge was undone.",muted:!0}],actions:a},reviewUrls:o}}function bb({defaultTagName:e,props:t,render:n,state:r={},stateAttributesMapping:o}){let s=cr(yb(r,o),t);if(!n)return m.createElement(e,s);if(typeof n=="function")return n(s,r);if(!m.isValidElement(n))return null;let i=n.props,a={...cr(s,i),ref:un(s.ref,i.ref)};return m.cloneElement(n,a)}function cr(...e){let t={};for(let n of e){if(!n)continue;let r=n;for(let o of Object.keys(r)){let s=r[o];if(s===void 0)continue;let i=t[o];o==="className"?t[o]=[i,s].filter(Boolean).join(" "):o==="style"?t[o]={...i,...s}:o==="ref"?t[o]=un(i,s):kb(o)&&typeof i=="function"&&typeof s=="function"?t[o]=wb(s,i):t[o]=s}}return t}function yb(e,t){let n={};for(let r of Object.keys(e)){let o=e[r],s=t?.[r]?.(o);if(s){Object.assign(n,s);continue}if(r==="slot"){n["data-slot"]=o;continue}let i=`data-${String(r).replace(/[A-Z]/g,a=>`-${a.toLowerCase()}`)}`;typeof o=="boolean"?n[i]=o?"":void 0:o!=null&&(n[i]=String(o))}return n}function wb(e,t){return function(n){e(n),n.defaultPrevented||t(n)}}function kb(e){return/^on[A-Z]/.test(e)}function un(...e){let t=e.filter(Boolean);if(t.length!==0)return n=>{for(let r of t)typeof r=="function"?r(n):r&&(r.current=n)}}var $b=8,Sb=64,xb=0,Cn=.5,Rb=180,zb=new Set(["ArrowDown","ArrowUp","End","Home","PageDown","PageUp"," "]),aa={start:!1,end:!1},Tb=[],Pn={currentAnchorId:null,visibleMessageIds:Tb};function Ib({content:e,scrollEdgeThreshold:t,spacer:n,viewport:r}){if(!r||!e)return aa;let o=Xr({content:e,spacer:n,viewport:r});return{start:r.scrollTop>t,end:o-r.scrollTop-r.clientHeight>t}}function Eb({content:e,scrollMargin:t,scrollPreviousItemPeek:n,spacer:r,viewport:o,visibleMessageIds:s}){if(!e||!o)return Pn;let i=o.getBoundingClientRect(),a=i.top+t+n,c=typeof IntersectionObserver>"u",u=[],l=null;for(let p of Jt(e,r)){let h=p.dataset.messageId;if(!h)continue;let f=p.dataset.scrollAnchor==="true",y=f||c?p.getBoundingClientRect():null;(c&&y?y.bottom>a&&y.top<i.bottom:s.has(h))&&u.push(h),f&&y&&y.top<=a+Cn&&(l=h)}return u.length===0&&l===null?Pn:{currentAnchorId:l,visibleMessageIds:u}}function Jt(e,t){return Array.from(e.children).filter(n=>n instanceof HTMLElement&&n!==t)}function Cb(e,t){for(let n=t;n<e.length;n++){let r=e[n];if(r?.dataset.scrollAnchor==="true")return r}return null}function Pb(e,t){for(let n of e)if(n.dataset.scrollAnchor==="true"&&!t.has(n))return n;return null}function Nb(e,t){let n=0;for(let r=t;r<e.length;r++)if(e[r]?.dataset.scrollAnchor==="true"&&(n+=1,n>1))return!0;return!1}function Zb(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n?.dataset.scrollAnchor==="true")return n}return null}function Ob({content:e,spacer:t,viewport:n}){let r=n.getBoundingClientRect();for(let o of Jt(e,t)){if(!o.dataset.messageId)continue;let s=o.getBoundingClientRect();if(s.bottom>r.top&&s.top<r.bottom)return o}return null}function Ab({align:e,element:t,scrollMargin:n,spacer:r,viewport:o}){let s=ca(t,o),i=t.getBoundingClientRect().height,a=Lb(r);if(e==="center"){let c=Math.max(0,o.clientHeight-a.start-a.end);return s-a.start-(c-i)/2-n}if(e==="end")return s-o.clientHeight+i+a.end+n;if(e==="nearest"){let c=s+i,u=o.scrollTop+a.start,l=o.scrollTop+o.clientHeight-a.end;return s>=u&&c<=l?o.scrollTop:s<u?s-a.start-n:c-o.clientHeight+a.end+n}return s-a.start-n}function ca(e,t){let n=e.getBoundingClientRect(),r=t.getBoundingClientRect();return n.top-r.top+t.scrollTop}function kn(e,t){return e.getBoundingClientRect().top-t.getBoundingClientRect().top}function jb({content:e,scrollTop:t,spacer:n,viewport:r}){let o=Xr({content:e,spacer:n,viewport:r});return t+r.clientHeight-o}function Xr({content:e,spacer:t,viewport:n}){let r=Jt(e,t),o=ua(e),s=n.getBoundingClientRect(),i=n.scrollTop,a=o.start+o.end;for(let c of r){let u=c.getBoundingClientRect();a=Math.max(a,u.bottom-s.top+i+o.end)}return a}function Mb(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function ua(e){let t=window.getComputedStyle(e);return{end:ur(t.paddingBlockEnd||t.paddingBottom),start:ur(t.paddingBlockStart||t.paddingTop)}}function Lb(e){let t=e?.parentElement;return t?ua(t):{end:0,start:0}}function Db(e){if(!e)return 0;let t=window.getComputedStyle(e),n=t.rowGap==="normal"?t.gap:t.rowGap;return ur(n)}function ur(e){if(!e)return 0;let t=Number.parseFloat(e);return Number.isFinite(t)?t:0}function Ub({refs:e,commitScrollState:t,scheduleStateCommit:n,scheduleVisibilitySync:r}){let{streamingTurnRef:o,autoScrollRef:s,autoscrollingRef:i,autoscrollingTimeoutRef:a,contentRef:c,defaultScrollPositionAppliedRef:u,itemCountRef:l,messageElementsRef:p,modeRef:h,pendingScrollToMessageRef:f,prependRestoreRef:y,scrollMarginRef:P,scrollPreviousItemPeekRef:S,spacerGapRef:j,spacerHeightRef:R,spacerRef:w,viewportRef:k}=e,O=m.useCallback(N=>{a.current!==null&&(window.clearTimeout(a.current),a.current=null),i.current!==N&&(i.current=N,t()),N&&(a.current=window.setTimeout(()=>{a.current=null,i.current=!1,t()},Rb))},[t]),M=m.useCallback(N=>{let L=w.current;if(!L)return;let H=Math.max(0,Math.ceil(N));R.current!==H&&(R.current=H,L.hidden=H===0,L.style.height=`${H}px`,L.style.marginTop=H>0?`${-j.current}px`:"")},[]),K=m.useCallback((N,{behavior:L="auto",autoscrolling:H=!1}={})=>{let X=k.current;if(!X)return;let G=Math.max(0,N);if(Math.abs(X.scrollTop-G)<=Cn){X.scrollTop=G,t();return}H&&O(!0),X.scrollTo({top:G,behavior:L}),n()},[t,n,O]),Se=m.useCallback(({behavior:N="auto"}={})=>k.current?(M(0),o.current=null,h.current="free-scrolling",K(0,{behavior:N}),r(),!0):!1,[r,K,M]),Ke=m.useCallback(({behavior:N="auto"}={})=>{let L=k.current;return L?(M(0),o.current=null,h.current=s.current?"following-bottom":"free-scrolling",K(Mb(L),{autoscrolling:!0,behavior:N}),r(),!0):!1},[r,K,M]),we=m.useCallback((N,{align:L="start",behavior:H="auto",scrollMargin:X=P.current}={},{keepPreviousPeek:G=!1}={})=>{let qe=c.current,Ze=k.current;if(!qe||!Ze||!qe.contains(N))return!1;let Ge=Ab({align:L,element:N,scrollMargin:G?X+S.current:X,spacer:w.current,viewport:Ze}),Xe=jb({content:qe,scrollTop:Ge,spacer:w.current,viewport:Ze});return M(Xe),y.current={element:N,viewportTop:kn(N,Ze)},h.current=G?"anchored-to-message":"settling-jump",o.current=G?N:null,K(Ge,{behavior:H}),r(),!0},[r,K,M]),Ne=m.useCallback(()=>{let N=o.current;return!N||!N.isConnected||h.current!=="anchored-to-message"?!1:we(N,{align:"start"},{keepPreviousPeek:!0})},[we]),Te=m.useCallback((N,L)=>{let H=p.current.get(N);return H?(u.current=!0,we(H,L)?(f.current=null,!0):(f.current={messageId:N,options:L},!0)):l.current===0?(f.current={messageId:N,options:L},u.current=!0,!0):!1},[we]);return{flushPendingScrollToMessage:m.useCallback(()=>{let N=f.current;if(!N)return!1;let L=p.current.get(N.messageId);return!L||!we(L,N.options)?!1:(f.current=null,u.current=!0,!0)},[we]),reanchorToAnchoredMessage:Ne,scrollToElement:we,scrollToEnd:Ke,scrollToMessage:Te,scrollToStart:Se}}function la(e,t){let n=e,r=new Set;return{getSnapshot:()=>n,hasListeners:()=>r.size>0,setSnapshot:o=>{t(n,o)||(n=o,r.forEach(s=>s()))},subscribe:(o,s,i)=>{let a=r.size===0;return r.add(o),a&&s?.(),()=>{r.delete(o),r.size===0&&i?.()}}}}function qb(e,t){return la(e,t)}function Fb(){return la(Pn,Vb)}function Hb(e,t){return e.start===t.start&&e.end===t.end}function Vb(e,t){return e.currentAnchorId!==t.currentAnchorId||e.visibleMessageIds.length!==t.visibleMessageIds.length?!1:e.visibleMessageIds.every((n,r)=>n===t.visibleMessageIds[r])}function Bb({autoScroll:e,scrollEdgeThreshold:t,scrollMargin:n,scrollPreviousItemPeek:r}){let o=m.useRef(e),s=m.useRef(!1),i=m.useRef(null),a=m.useRef(!1),c=m.useRef(t),u=m.useRef(0),l=m.useRef(null),p=m.useRef(0),h=m.useRef(e?"following-bottom":"free-scrolling"),f=m.useRef(new Map),y=m.useRef(null),P=m.useRef(null),S=m.useRef(null),j=m.useRef(r),R=m.useRef(!0),w=m.useRef(null),k=m.useRef(n),O=m.useRef(null),M=m.useRef(0),K=m.useRef(0),Se=m.useRef(null),Ke=m.useRef(null),we=m.useRef(null),Ne=m.useRef(null),Te=m.useRef(null),N=m.useRef(null),L=m.useRef(null),H=m.useRef(null),X=m.useRef(new Set),G=m.useRef(new WeakSet);return we.current===null&&(we.current=qb(aa,Hb)),H.current===null&&(H.current=Fb()),o.current=e,c.current=t,k.current=n,j.current=r,{autoScrollRef:o,autoscrollingRef:s,autoscrollingTimeoutRef:Ne,streamingTurnRef:S,contentRef:i,defaultScrollPositionAppliedRef:a,firstItemRef:l,itemCountRef:u,lastScrollTopRef:p,messageElementsRef:f,modeRef:h,pendingScrollFrameRef:O,pendingScrollToMessageRef:y,prependRestoreRef:P,preserveScrollOnPrependRef:R,rootRef:w,scrollEdgeThresholdRef:c,scrollMarginRef:k,scrollPreviousItemPeekRef:j,spacerGapRef:M,spacerHeightRef:K,spacerRef:Se,stateFrameRef:Ke,stateStore:we.current,viewportRef:Te,visibilityFrameRef:N,visibilityObserverRef:L,visibilityStore:H.current,visibleMessageIdsRef:X,handledScrollAnchorsRef:G}}function os(e,t){return m.useCallback(n=>{e.current=n,n&&t()},[e,t])}function Jb({autoScroll:e=!1,defaultScrollPosition:t="end",scrollEdgeThreshold:n=$b,scrollPreviousItemPeek:r=Sb,scrollMargin:o=xb}){let s=Bb({autoScroll:e,scrollEdgeThreshold:n,scrollMargin:o,scrollPreviousItemPeek:r}),{streamingTurnRef:i,autoScrollRef:a,autoscrollingRef:c,autoscrollingTimeoutRef:u,contentRef:l,defaultScrollPositionAppliedRef:p,firstItemRef:h,itemCountRef:f,lastScrollTopRef:y,messageElementsRef:P,modeRef:S,pendingScrollFrameRef:j,pendingScrollToMessageRef:R,prependRestoreRef:w,preserveScrollOnPrependRef:k,rootRef:O,scrollEdgeThresholdRef:M,scrollMarginRef:K,scrollPreviousItemPeekRef:Se,spacerGapRef:Ke,spacerHeightRef:we,spacerRef:Ne,stateFrameRef:Te,stateStore:N,viewportRef:L,visibilityFrameRef:H,visibilityObserverRef:X,visibilityStore:G,visibleMessageIdsRef:qe,handledScrollAnchorsRef:Ze}=s,Ge=m.useRef(t);Ge.current!==t&&(Ge.current=t,p.current=!1);let Xe=m.useCallback(C=>{let Z=O.current,A=L.current,Ie=[C.start&&"start",C.end&&"end"].filter(Boolean).join(" "),Fe=c.current;for(let he of[Z,A])he&&(Ie?he.setAttribute("data-scrollable",Ie):he.removeAttribute("data-scrollable"),he.toggleAttribute("data-autoscrolling",Fe))},[]),dt=m.useCallback(C=>{let Z=L.current?.scrollTop??0,A=Z<y.current-Cn;y.current=Z,a.current&&!C.end&&S.current!=="settling-jump"&&S.current!=="anchored-to-message"?S.current="following-bottom":S.current==="following-bottom"&&C.end&&A&&!c.current&&(S.current="free-scrolling")},[]),Me=m.useCallback(()=>{let C=Ib({content:l.current,scrollEdgeThreshold:M.current,spacer:Ne.current,viewport:L.current});dt(C);let Z=S.current==="following-bottom"?{...C,end:!1}:C;Xe(Z),N.setSnapshot(Z)},[dt,N,Xe]),ot=m.useCallback(()=>{Te.current===null&&(Te.current=window.requestAnimationFrame(()=>{Te.current=null,Me()}))},[Me]),ge=m.useCallback(()=>{G.hasListeners()&&H.current===null&&(H.current=window.requestAnimationFrame(()=>{H.current=null,G.hasListeners()&&G.setSnapshot(Eb({content:l.current,scrollMargin:K.current,scrollPreviousItemPeek:Se.current,spacer:Ne.current,viewport:L.current,visibleMessageIds:qe.current}))}))},[G]),{flushPendingScrollToMessage:pt,reanchorToAnchoredMessage:ln,scrollToElement:V,scrollToEnd:D,scrollToMessage:be,scrollToStart:ke}=Ub({refs:s,commitScrollState:Me,scheduleStateCommit:ot,scheduleVisibilitySync:ge}),ve=m.useCallback(()=>{let C=w.current,Z=L.current;if(!C||!Z||!C.element.isConnected)return!1;let A=kn(C.element,Z)-C.viewportTop;return Math.abs(A)<=Cn?!1:(Z.scrollTop+=A,C.viewportTop=kn(C.element,Z),ot(),ge(),!0)},[ot,ge]),Le=m.useCallback(()=>{let C=l.current,Z=L.current;if(!C||!Z){w.current=null;return}let A=Ob({content:C,spacer:Ne.current,viewport:Z});w.current=A?{element:A,viewportTop:kn(A,Z)}:null},[]),me=m.useCallback(()=>{j.current===null&&(j.current=window.requestAnimationFrame(()=>{j.current=null,pt()&&Le()}))},[Le,pt]),st=m.useCallback(()=>{if(!t||p.current||f.current===0)return!1;let C=!1;if(t==="last-anchor"){let Z=l.current,A=L.current,Ie=Z&&A?Zb(Jt(Z,Ne.current)):null;if(!Z||!A||!Ie)C=D({behavior:"auto"});else{let Fe=ca(Ie,A);C=Xr({content:Z,spacer:Ne.current,viewport:A})-Fe<=A.clientHeight?D({behavior:"auto"}):V(Ie,{align:"start"},{keepPreviousPeek:!0})}}else C=t==="end"?D({behavior:"auto"}):ke({behavior:"auto"});return C?(p.current=!0,!0):!1},[t,V,D,ke]),bt=m.useCallback(()=>{let C=l.current;if(!C)return;let Z=Jt(C,Ne.current),A=f.current,Ie=h.current;f.current=Z.length,h.current=Z[0]??null,(()=>{if(pt())return;if(A===0){if(st()||Z.length>0&&a.current&&D({behavior:"auto"}))return;Me(),ge();return}let Fe=Ie?Z.indexOf(Ie):-1;if(k.current&&Fe>0){ve();return}if(Z.length>A){let he=Cb(Z,A);if(he){if(a.current&&S.current==="following-bottom"&&Nb(Z,A)){D({behavior:"auto"});return}V(he,{align:"start"},{keepPreviousPeek:!0}),Ze.current.add(he);return}}if(Z.length===A){let he=Pb(Z,Ze.current);if(he){V(he,{align:"start"},{keepPreviousPeek:!0}),Ze.current.add(he);return}}S.current==="following-bottom"&&a.current?D({behavior:"auto"}):(Me(),ge())})(),Le()},[st,Le,Me,pt,ve,ge,V,D]),Zt=m.useCallback(()=>{if(S.current==="following-bottom"&&a.current){D({behavior:"auto"});return}let C=we.current;if(ln()){a.current&&C>0&&we.current===0&&D({behavior:"auto"});return}ot(),ge()},[ln,ot,ge,D]),yt=m.useCallback(()=>{let C=L.current;if(!(!C||!G.hasListeners())){if(typeof IntersectionObserver>"u"){ge();return}X.current||(X.current=new IntersectionObserver(Z=>{for(let A of Z){let Ie=A.target.dataset.messageId;Ie&&(A.isIntersecting?qe.current.add(Ie):qe.current.delete(Ie))}ge()},{root:C,rootMargin:`${-(K.current+Se.current)}px 0px 0px 0px`,threshold:[0,.01,.5,1]})),P.current.forEach(Z=>{X.current?.observe(Z)}),ge()}},[ge,G]),wt=m.useCallback(()=>{H.current!==null&&(window.cancelAnimationFrame(H.current),H.current=null),X.current?.disconnect(),X.current=null,qe.current.clear(),G.setSnapshot(Pn)},[G]),Ot=m.useCallback((C,Z,A)=>{if(Z){P.current.set(C,Z),X.current?.observe(Z),ge(),R.current?.messageId===C&&me();return}A&&P.current.get(C)===A&&(P.current.delete(C),qe.current.delete(C),X.current?.unobserve(A),ge())},[me,ge]),kt=m.useCallback(()=>{(S.current==="following-bottom"||S.current==="anchored-to-message"||S.current==="settling-jump")&&(i.current=null,S.current="free-scrolling")},[]),dn=m.useCallback(()=>Xe(N.getSnapshot()),[N,Xe]),pn=os(O,dn),hn=os(L,dn),At=m.useCallback(C=>{l.current=C},[]),q=m.useCallback(C=>{Ne.current=C,Ke.current=Db(C?.parentElement??null)},[]),$e=m.useCallback(()=>{Me(),ge(),Le()},[Le,Me,ge]),Ee=m.useMemo(()=>({handleContentChange:bt,handleResize:Zt,observeVisibility:yt,preserveScrollOnPrependRef:k,scrollToEnd:D,scrollToMessage:be,scrollToStart:ke,setContentElement:At,setRootElement:pn,setSpacerElement:q,setViewportElement:hn,stateStore:N,syncAfterScroll:$e,unobserveVisibility:wt,userScrollIntent:kt,viewportRef:L,visibilityStore:G}),[bt,Zt,yt,D,be,ke,At,pn,q,hn,N,$e,wt,kt,G]);return m.useLayoutEffect(()=>{st()},[st]),m.useEffect(()=>()=>{Te.current!==null&&(window.cancelAnimationFrame(Te.current),Te.current=null),H.current!==null&&(window.cancelAnimationFrame(H.current),H.current=null),u.current!==null&&(window.clearTimeout(u.current),u.current=null),j.current!==null&&(window.cancelAnimationFrame(j.current),j.current=null),X.current?.disconnect(),X.current=null},[]),m.useLayoutEffect(()=>{if(e&&S.current==="following-bottom"&&f.current>0){D({behavior:"auto"});return}Me()},[e,Me,D]),{context:Ee,registerMessage:Ot}}function Wb(e){let t=m.useRef(e);return t.current=e,t}var da=m.createContext(null),pa=m.createContext(null);function Pt(){let e=m.useContext(da);if(!e)throw new Error("useMessageScroller must be used within a MessageScroller.");return e}function Kb(){let e=m.useContext(pa);if(!e)throw new Error("MessageScrollerItem must be used within a MessageScroller.");return e}function ha(){let{scrollToEnd:e,scrollToMessage:t,scrollToStart:n}=Pt();return m.useMemo(()=>({scrollToEnd:e,scrollToMessage:t,scrollToStart:n}),[e,t,n])}function fa(){let{observeVisibility:e,unobserveVisibility:t,visibilityStore:n}=Pt(),r=m.useCallback(o=>n.subscribe(o,e,t),[e,t,n]);return m.useSyncExternalStore(r,n.getSnapshot,n.getSnapshot)}function Gb({autoScroll:e=!1,children:t,defaultScrollPosition:n="end",scrollEdgeThreshold:r,scrollPreviousItemPeek:o,scrollMargin:s}){let{context:i,registerMessage:a}=Jb({autoScroll:e,defaultScrollPosition:n,scrollEdgeThreshold:r,scrollPreviousItemPeek:o,scrollMargin:s});return d.jsx(da.Provider,{value:i,children:d.jsx(pa.Provider,{value:a,children:t})})}function Yb({children:e,...t}){let{setRootElement:n}=Pt();return d.jsx("div",{ref:n,...t,children:e})}function Qb({"aria-label":e,children:t,onKeyDown:n,onScroll:r,onTouchMove:o,onWheel:s,preserveScrollOnPrepend:i=!0,ref:a,role:c,tabIndex:u,...l}){let{handleResize:p,preserveScrollOnPrependRef:h,setViewportElement:f,syncAfterScroll:y,userScrollIntent:P,viewportRef:S}=Pt();h.current=i;let j=m.useCallback(M=>{f(M),un(a)?.(M)},[a,f]);function R(M){y(),r?.(M)}function w(M){P(),s?.(M)}function k(M){P(),o?.(M)}function O(M){zb.has(M.key)&&P(),n?.(M)}return m.useEffect(()=>{let M=S.current;if(!M||typeof ResizeObserver>"u")return;let K=0,Se=new ResizeObserver(()=>{window.cancelAnimationFrame(K),K=window.requestAnimationFrame(p)});return Se.observe(M),()=>{window.cancelAnimationFrame(K),Se.disconnect()}},[p,S]),d.jsx("div",{ref:j,role:c??"region","aria-label":e??"Messages",tabIndex:u??0,onKeyDown:O,onScroll:R,onTouchMove:k,onWheel:w,...l,children:t})}function Xb({"aria-relevant":e,children:t,ref:n,role:r,spacerClassName:o,...s}){let{handleContentChange:i,handleResize:a,setContentElement:c,setSpacerElement:u}=Pt(),l=m.useRef(null),p=m.useCallback(h=>{l.current=h,c(h),un(n)?.(h)},[n,c]);return m.useLayoutEffect(()=>{let h=l.current;if(!h||(i(),typeof MutationObserver>"u"))return;let f=new MutationObserver(()=>{i()});return f.observe(h,{childList:!0}),()=>f.disconnect()},[i]),m.useEffect(()=>{let h=l.current;if(!h||typeof ResizeObserver>"u")return;let f=0,y=new ResizeObserver(()=>{window.cancelAnimationFrame(f),f=window.requestAnimationFrame(a)});return y.observe(h),()=>{window.cancelAnimationFrame(f),y.disconnect()}},[a]),d.jsxs("div",{ref:p,role:r??"log","aria-relevant":e??"additions",...s,children:[t,d.jsx("div",{ref:u,"aria-hidden":"true","data-message-scroller-spacer":"",hidden:!0,className:o})]})}function ey({messageId:e,ref:t,scrollAnchor:n=!1,...r}){let o=Kb(),s=m.useRef(null),i=m.useCallback(a=>{let c=s.current;s.current=a,e&&o(e,a,c),un(t)?.(a)},[e,t,o]);return d.jsx("div",{ref:i,"data-message-id":e,"data-scroll-anchor":n?"true":"false",...r})}function ty({behavior:e="smooth",children:t,direction:n="end",onClick:r,render:o,tabIndex:s,type:i="button",...a}){let{scrollToEnd:c,scrollToStart:u,stateStore:l}=Pt(),p=Wb(r),h=m.useCallback(S=>l.subscribe(S),[l]),f=m.useCallback(()=>{let S=l.getSnapshot();return n==="start"?S.start:S.end},[n,l]),y=m.useSyncExternalStore(h,f,f),P=m.useCallback(S=>{y&&(p.current?.(S),S.defaultPrevented||(S.currentTarget.blur(),n==="start"?u({behavior:e}):c({behavior:e})))},[e,n,y,p,c,u]);return bb({defaultTagName:"button",props:cr({type:i,inert:!y,tabIndex:y?s:-1,children:t??d.jsxs("span",{children:["Scroll to ",n]}),onClick:P},a),render:o,state:{active:y,direction:n},stateAttributesMapping:{active:S=>({"data-active":S?"true":"false"})}})}var Nt={Provider:Gb,Root:Yb,Viewport:Qb,Content:Xb,Item:ey,Button:ty};const ny=Nt.Provider;function ry({className:e,...t}){return d.jsx(Nt.Root,{className:fe("relative flex size-full min-h-0 flex-col overflow-hidden",e),...t})}function oy({className:e,...t}){return d.jsx(Nt.Viewport,{className:fe("size-full min-h-0 overflow-y-auto overscroll-contain [scrollbar-gutter:stable]",e),...t})}function sy({className:e,...t}){return d.jsx(Nt.Content,{className:fe("flex h-max min-h-full flex-col",e),...t})}function iy({className:e,...t}){return d.jsx(Nt.Item,{className:fe("min-w-0 shrink-0",e),...t})}function ay({className:e,...t}){return d.jsx(Nt.Button,{direction:"end",behavior:"smooth",render:({active:n,...r})=>n?d.jsx(it,{...r,type:"button",variant:"outline",size:"icon",className:fe("absolute right-4 bottom-4 z-20 rounded-full bg-background ",e),"aria-label":"Scroll to latest message",children:d.jsx(Ca,{})}):null,...t})}function cy(e){if(!e)return"";const t=e.startsWith("?")?e.slice(1):e,n=new URLSearchParams(t);return n.get("message_id")?.trim()||n.get("message")?.trim()||""}function uy(e){const t=e.scrollTarget.trim();return t?e.alreadyScrolledTo===t?{scroll:!1}:e.messageIds.includes(t)?{scroll:!0,id:t}:{scroll:!1}:{scroll:!1}}const ly="lobu-spa";function Gn(e){return typeof e=="string"&&/^https?:\/\//i.test(e.trim())}function Nn(e,t){return t.type==="tool-call"?`tc-${t.toolCallId}`:t.type==="reasoning"?`${e.id}-reasoning`:t.type==="bash"?`${e.id}-bash-${t.command.slice(0,24)}`:t.type==="error"?`${e.id}-error`:`${e.id}-text-${t.text.slice(0,24)}`}const Xy=({afterMessagesContent:e,readOnly:t=!1,readerPositionMode:n="messages",interactionExtension:r,onRunSelect:o})=>{const{messages:s,agentId:i,conversationId:a}=cn(),{data:c=[]}=Pa(i,{conversationId:a});return d.jsx(Y_,{extension:r,children:d.jsxs("div",{"data-agent-thread":!0,className:"flex min-h-0 flex-1 flex-col",children:[d.jsx(dy,{messages:s,trips:c,mode:n,afterMessagesContent:e,onRunSelect:o}),t?null:d.jsx("div",{className:Ka,children:d.jsx(Uy,{})})]})})},dy=({messages:e,trips:t,mode:n,afterMessagesContent:r,onRunSelect:o})=>d.jsx(ny,{autoScroll:!0,defaultScrollPosition:n==="runs"?"last-anchor":"end",scrollPreviousItemPeek:48,children:d.jsx(hy,{messages:e,trips:t,mode:n,afterMessagesContent:r,onRunSelect:o})});function py(e){if(!e.startsWith("sep:"))return null;const t=Number(e.slice(4));return Number.isFinite(t)&&t>0?t:null}const hy=({messages:e,trips:t,mode:n,afterMessagesContent:r,onRunSelect:o})=>{const{currentAnchorId:s}=fa(),{scrollToMessage:i}=ha(),a=m.useRef(null);m.useEffect(()=>{if(e.length===0||typeof window>"u")return;const u=uy({messageIds:e.map(l=>l.id),scrollTarget:cy(window.location.search),alreadyScrolledTo:a.current});u.scroll&&(a.current=u.id,i(u.id,{align:"start",behavior:"smooth"}))},[e,i]);const c=u=>n==="runs"?u.id.startsWith("sep:"):u.role==="user";return d.jsxs(ry,{children:[d.jsx(oy,{"aria-label":n==="runs"?"Automation run history":"Conversation",children:d.jsxs(sy,{className:fe(hr,Ga),children:[e.map(u=>{const l=n==="runs"&&o?py(u.id):null;return d.jsx(iy,{messageId:u.id,scrollAnchor:c(u),"aria-current":u.id===s?"location":void 0,className:fe("flex flex-col",n==="runs"&&c(u)&&"border-l-2 border-transparent pl-2 transition-colors",n==="runs"&&u.id===s&&"border-primary"),children:l!=null?d.jsx(zy,{message:u,onClick:()=>o?.(l)}):d.jsx(_y,{message:u})},u.id)}),t.map(u=>d.jsx(my,{trip:u},u.id)),d.jsx(vy,{}),r?d.jsx("div",{className:"mt-auto shrink-0 py-2",children:r}):null]})}),e.length>0?d.jsx(fy,{messages:e,mode:n}):null,d.jsx(ay,{})]})},fy=({messages:e,mode:t})=>{const{scrollToMessage:n}=ha(),{currentAnchorId:r,visibleMessageIds:o}=fa(),s=t==="runs"?e.flatMap(a=>a.parts).filter(a=>a.type==="tool-call"&&a.toolName==="tool-approval"&&a.args!==null&&typeof a.args=="object"&&a.args.status==="pending").length:0,i=e.flatMap(a=>{if(!(t==="runs"?a.id.startsWith("sep:"):a.role==="user"))return[];const u=a.parts.find(l=>l.type==="text");return[{id:a.id,label:u?.type==="text"?u.text:"Automation run"}]});return i.length===0?null:d.jsxs(ja,{children:[d.jsx(Ma,{asChild:!0,children:d.jsxs(it,{type:"button",variant:"outline",size:"icon",className:fe("absolute top-1/2 right-4 z-20 -translate-y-1/2 rounded-full bg-background/95 ",s>0&&"w-auto px-3"),"aria-label":s>0?`Open transcript outline, ${s} ${s===1?"approval":"approvals"} waiting`:"Open transcript outline",children:[d.jsx(La,{}),s>0?d.jsxs("span",{className:"text-xs tabular-nums",children:[s," waiting"]}):null]})}),d.jsxs(Da,{side:"left",align:"center",className:"w-80 space-y-3 p-3",children:[d.jsxs("div",{className:"px-1",children:[d.jsx("p",{className:"text-sm font-medium",children:"Transcript outline"}),d.jsx("p",{className:"text-xs text-muted-foreground",children:t==="runs"?"Track and jump between Automation runs.":"Track and jump between your messages."})]}),d.jsx("div",{className:"max-h-80 space-y-1 overflow-y-auto",children:i.map(a=>{const c=a.id===r,u=o.includes(a.id);return d.jsxs(it,{type:"button",variant:c?"secondary":"ghost",className:"h-auto w-full justify-start gap-2 px-2 py-2 text-left text-xs font-normal","aria-current":c?"location":void 0,onClick:()=>n(a.id,{align:"start",behavior:"smooth"}),children:[d.jsx("span",{className:fe("size-1.5 shrink-0 rounded-full bg-muted-foreground/30",u&&"bg-primary/60",c&&"bg-primary")}),d.jsx("span",{className:"line-clamp-2",children:a.label})]},a.id)})})]})]})},my=({trip:e})=>d.jsxs("div",{className:fe(hr,"flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive"),children:[d.jsx(Aa,{className:"mt-0.5 size-4 shrink-0"}),d.jsxs("div",{className:"min-w-0",children:[d.jsxs("div",{className:"font-medium",children:["Guardrail blocked: ",e.guardrailName," ",d.jsxs("span",{className:"font-normal opacity-70",children:["(",e.stage,")"]})]}),e.reason?d.jsx("div",{className:"mt-0.5 break-words opacity-80",children:e.reason}):null]})]}),gy=({prompts:e,onPick:t,className:n})=>e.length===0?null:d.jsx("div",{className:fe("flex flex-wrap gap-2",n),children:e.map(r=>d.jsx(it,{type:"button",variant:"outline",size:"sm",className:"h-auto rounded-full whitespace-normal text-left",title:r.message,"aria-label":`${r.title}: ${r.message}`,onClick:()=>t(r.message),children:r.title},`${r.title}\0${r.message}`))}),vy=()=>{const{currentSuggestions:e,running:t,append:n}=cn();return t||!e||e.length===0?null:d.jsx(gy,{prompts:e,className:hr,onPick:r=>n(r)})},_y=({message:e})=>e.role==="user"?d.jsx(by,{message:e}):e.role==="system"?d.jsx(Ty,{message:e}):d.jsx(ky,{message:e}),ma=({attachment:e})=>{const t=e.isImage?e.imageDataUrl??e.url:void 0;if(t)return d.jsx("a",{href:e.url??t,target:"_blank",rel:"noreferrer",children:d.jsx("img",{src:t,alt:e.name,className:"max-h-64 rounded-lg border object-contain"})});const n=d.jsxs(d.Fragment,{children:[d.jsx(Qn,{className:"h-3 w-3 shrink-0"}),d.jsx("span",{className:"max-w-[14rem] truncate",children:e.name})]});return d.jsx("div",{className:"flex items-center gap-1.5 rounded-md border bg-background px-2 py-1 text-xs",children:e.url?d.jsx("a",{href:e.url,target:"_blank",rel:"noreferrer",className:"flex items-center gap-1.5 hover:underline",children:n}):n})},by=({message:e})=>{const t=e.parts.filter(n=>n.type==="bash");return t.length>0?d.jsx("div",{className:us,children:d.jsx("div",{className:"space-y-2",children:t.map(n=>d.jsx(yy,{part:n},Nn(e,n)))})}):d.jsx("div",{className:Ya,children:d.jsxs("div",{className:fe(Kt,"px-3 py-2 text-sm"),children:[e.attachments&&e.attachments.length>0?d.jsx("div",{className:"mb-1.5 flex flex-wrap gap-1.5",children:e.attachments.map(n=>d.jsx(ma,{attachment:n},n.id))}):null,e.parts.map(n=>n.type==="text"?d.jsx("div",{className:"whitespace-pre-wrap break-words",children:d.jsx(Yr,{text:n.text,renderText:r=>r})},Nn(e,n)):null)]})})},yy=({part:e})=>{const t=e.cancelled||e.exitCode!==void 0&&e.exitCode!==0;return d.jsxs("div",{className:fe(Kt,"overflow-hidden text-xs"),children:[d.jsxs("div",{className:"flex items-center gap-1.5 border-border/60 border-b px-3 py-1.5",children:[d.jsx(Ua,{className:"size-3.5 shrink-0 text-muted-foreground"}),d.jsx("code",{className:"min-w-0 flex-1 truncate font-mono text-foreground/90",children:e.command}),e.cancelled?d.jsx("span",{className:"rounded bg-muted px-1.5 py-0.5 font-medium text-[10px] text-muted-foreground",children:"cancelled"}):t?d.jsxs("span",{className:"rounded bg-destructive/15 px-1.5 py-0.5 font-medium text-[10px] text-destructive",children:["exit ",e.exitCode]}):null]}),e.output.trim()?d.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap break-words px-3 py-2 font-mono text-foreground/80",children:e.output}):null]})},ga=new Set(["question","link-button","tool-approval"]),wy="subscription-candidate",ky=({message:e})=>{const t=Wr(),{agentId:n,workspaceSlug:r}=cn(),o=c=>c.type==="tool-call"&&(ga.has(c.toolName)||t?.toolNames.has(c.toolName)),s=e.parts.filter(c=>c.type==="tool-call"&&!o(c)&&c.toolName!==wy),i=e.parts.filter(c=>c.type!=="tool-call"||o(c)),a=e.parts.flatMap(c=>{if(c.type!=="tool-call")return[];const u=Yi(c.result);return u?[u]:[]});return d.jsx("div",{className:us,children:d.jsxs("div",{className:"space-y-2 text-sm",children:[s.length>0?d.jsx(Sy,{tools:s}):null,n&&r?a.map(c=>d.jsx($y,{candidate:c,agentId:n,workspaceSlug:r},`${c.connector_key}:${c.resource_ref}`)):null,i.map(c=>d.jsx(Ry,{part:c},Nn(e,c))),e.attachments&&e.attachments.length>0?d.jsx("div",{className:"flex flex-wrap gap-2",children:e.attachments.map(c=>d.jsx(ma,{attachment:c},c.id))}):null]})})},$y=({candidate:e,agentId:t,workspaceSlug:n})=>d.jsxs("div",{className:fe(Kt,"flex items-center justify-between gap-3 p-3"),children:[d.jsxs("div",{className:"min-w-0",children:[d.jsx("p",{className:"truncate text-sm font-medium",children:e.label}),d.jsx("p",{className:"text-xs text-muted-foreground",children:"Run this agent when the resource changes."})]}),d.jsx(it,{asChild:!0,size:"sm",variant:"outline",className:"shrink-0",children:d.jsxs(as,{to:"/$owner/automations/new",params:{owner:n},search:{agent:t,platform:e.connector_key,resource_type:e.resource_type,resource:e.resource_ref,events:e.suggested_event_keys?.join(","),label:e.label},children:[d.jsx(Fa,{className:"mr-1.5 h-4 w-4"}),"Add automation"]})})]}),Sy=({tools:e})=>d.jsxs(na,{defaultOpen:!1,children:[d.jsx(ra,{children:e.length===1?e[0].toolName:`${e.length} tool calls`}),d.jsx(sa,{children:e.map(t=>{const n=t.args!==void 0&&t.args!==null,r=t.result!==void 0&&t.result!==null;return d.jsxs(oa,{icon:qa,label:d.jsxs("span",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:"font-medium",children:t.toolName}),t.isError?d.jsx("span",{className:"rounded bg-destructive/15 px-1.5 py-0.5 font-medium text-[10px] text-destructive",children:"error"}):null]}),status:t.isError?"active":"complete",children:[n?d.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap break-words text-foreground/80 text-xs",children:Wt(t.args)}):null,r?d.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap break-words text-foreground/80 text-xs",children:Wt(t.result)}):null]},t.toolCallId)})})]}),xy=({text:e})=>{let t=e,n=null;const r=e.match(/\{[\s\S]*\}/);if(r)try{const s=JSON.parse(r[0])?.error?.message;typeof s=="string"&&s.trim()&&(t=s,n=e)}catch{}return d.jsxs("div",{className:"flex gap-2 rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2.5 text-sm",children:[d.jsx(Va,{className:"mt-0.5 size-4 shrink-0 text-destructive"}),d.jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[d.jsx("p",{className:"text-foreground/80",children:t}),n&&d.jsxs("details",{className:"text-xs text-muted-foreground",children:[d.jsx("summary",{className:"cursor-pointer select-none hover:text-foreground",children:"Technical details"}),d.jsx("pre",{className:"mt-1 overflow-x-auto whitespace-pre-wrap break-all font-mono",children:n})]})]})]})},Ry=({part:e})=>{const t=Wr();return e.type==="reasoning"?d.jsx(mb,{}):e.type==="error"?d.jsx(xy,{text:e.text}):e.type==="text"?e.text.trim()?d.jsx(Yr,{text:e.text,renderText:n=>d.jsx(Ha,{text:n})}):null:e.type!=="tool-call"?null:ga.has(e.toolName)||t?.toolNames.has(e.toolName)?d.jsx(Dy,{toolName:e.toolName,args:e.args}):null},zy=({message:e,onClick:t})=>{const n=e.parts.find(r=>r.type==="text");return d.jsx("button",{type:"button",onClick:t,className:fe(Kt,"block w-full cursor-pointer whitespace-pre-wrap break-words px-3 py-2 text-left text-xs text-muted-foreground transition-colors hover:bg-muted/50"),children:n?.type==="text"?n.text:"Automation run"})},Ty=({message:e})=>d.jsx("div",{className:"self-stretch",children:d.jsx("div",{className:fe(Kt,"px-3 py-2 text-xs text-muted-foreground"),children:e.parts.map(t=>t.type==="text"?d.jsx("div",{className:"whitespace-pre-wrap break-words",children:d.jsx(Yr,{text:t.text,renderText:n=>n})},Nn(e,t)):null)})}),Iy="/mcp-apps/interaction/index.html";function ss(e){return new Promise(t=>{e({onSettled:(n,r)=>t(!!r)})})}const Ey=({src:e,title:t,renderPayload:n,onToolCall:r,onOpenLink:o})=>{const s=m.useRef(null),[i,a]=m.useState(48),c=m.useRef({renderPayload:n,onToolCall:r,onOpenLink:o});return c.current={renderPayload:n,onToolCall:r,onOpenLink:o},m.useEffect(()=>{const u=s.current;if(!u?.contentWindow)return;const l=new K_(null,{name:"Lobu",version:"1.0.0"},{openLinks:{},serverTools:{}},{hostContext:{theme:document.documentElement.classList.contains("dark")?"dark":"light",displayMode:"inline",platform:"web"}});l.addEventListener("sizechange",({height:f})=>{typeof f=="number"&&a(Math.max(32,Math.ceil(f)))}),l.oncalltool=async({name:f,arguments:y})=>({content:[],isError:await c.current.onToolCall(f,y??{})}),l.onopenlink=async({url:f})=>({isError:await c.current.onOpenLink(f)}),l.addEventListener("initialized",()=>{(async()=>(await l.sendToolInput({arguments:{}}),await l.sendToolResult({content:[],structuredContent:{...c.current.renderPayload,version:1,source:ly}})))()});const p=new J_(u.contentWindow,u.contentWindow);l.connect(p).catch(f=>{console.error("[mcp-app-host] failed to initialize",f)});const h=new MutationObserver(()=>{l.setHostContext({theme:document.documentElement.classList.contains("dark")?"dark":"light",displayMode:"inline",platform:"web"})});return h.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),()=>{h.disconnect(),p.close()}},[]),d.jsx("iframe",{ref:s,title:t,src:e,sandbox:"allow-scripts",style:{width:"100%",height:i,border:"none",display:"block"}})},Cy=new Set(["action"]),Py=["name","description","identity_md"];function Qe(e){return e==null||e===""?"":typeof e=="string"?e:Wt(e)}function is(e){return e===null?"(cleared)":e===void 0?"":typeof e=="string"?e===""?"":e:Wt(e)}function lr(e){return e.length>0?e[0].toUpperCase()+e.slice(1):e}const va=new Set(["delete","disconnect","merge","remove","remove_rule","reset","revoke"]);function dr(e){return e&&va.has(e)?"warning":"default"}function pr(e,t){return e&&va.has(e)?{level:"high",reason:t}:{level:"normal"}}function Ny(e,t){const n=e.attribution==="automation"?"An Automation":"An agent",r=Object.keys(t),o=r.map(s=>({label:s,before:Qe(e.current?.[s]),after:Qe(t[s])}));return{title:`${n} proposes a change`,icon:"entity",impact:{level:"normal"},tone:"default",blocks:o.length>0?[{type:"diff",fields:o}]:[{type:"text",value:"No field changes.",muted:!0}],actions:[{id:"approve",label:"Approve",variant:"primary",icon:"check",tool:"manage_operations",args:{action:"approve"},resolvedLabel:`Approved — ${r.join(", ")} is being applied.`},{id:"reject",label:"Reject",variant:"outline",icon:"x",confirm:!0,confirmPrompt:"Reject this change?",tool:"manage_operations",args:{action:"reject"},resolvedLabel:`Rejected — ${r.join(", ")} was not applied.`}]}}function Zy(e){const t=e.action??"change",n=e.proposal?.slug??e.proposal?.name??(e.proposal?.automation_id!=null?String(e.proposal.automation_id):void 0)??e.current?.slug??e.current?.name??"automation",r=[];e.action==="delete"&&r.push({type:"text",value:"This will archive the Automation.",muted:!0});const o=e.proposal??{},s=Object.keys(o).filter(i=>!Cy.has(i)&&o[i]!==void 0).map(i=>({label:i,...e.action==="update"&&e.current?.[i]!==void 0?{before:is(e.current?.[i])}:{},after:is(o[i])}));return r.push(s.length>0?{type:"diff",fields:s}:{type:"text",value:"No field changes.",muted:!0}),{title:`${lr(t)} Automation ${n}`,icon:"automation",impact:pr(e.action,"This archives the Automation and stops future runs."),tone:dr(e.action),blocks:r,actions:[{id:"approve",label:"Approve",variant:"primary",icon:"check",tool:"manage_operations",args:{action:"approve"},resolvedLabel:`Approved — ${t} ${n} is being applied.`},{id:"reject",label:"Reject",variant:"outline",icon:"x",confirm:!0,confirmPrompt:"Reject this change?",tool:"manage_operations",args:{action:"reject"},resolvedLabel:`Rejected — ${t} ${n} was not applied.`}]}}function Oy(e){return e.action==="merge"&&(e.resourceKind==="entity"||e.proposal?.entity_id!==void 0||e.proposal?.winner_entity_id!==void 0||e.current?.winner!==void 0)}function Ay(e){if(e.resourceKind==="automation")return Zy(e);if(e.fields&&Object.keys(e.fields).length>0)return Ny(e,e.fields);if(e.resourceKind==="entity"||e.proposal?.entity_id!==void 0||e.current?.entity_type!==void 0||e.proposal?.entity_type!==void 0){const s=e.proposal?.name??e.current?.name??e.proposal?.entity_id??e.current?.id??"entity",i=e.action??"change",a=[];if(e.action==="delete")a.push({type:"text",value:"This will delete the entity.",muted:!0});else{const c=Object.keys(e.proposal??{}).filter(u=>!["entity_id","id"].includes(u)&&e.proposal?.[u]!==void 0&&Qe(e.proposal?.[u])!==Qe(e.current?.[u])).map(u=>({label:u,...e.action==="update"?{before:Qe(e.current?.[u])}:{},after:Qe(e.proposal?.[u])}));a.push(c.length>0?{type:"diff",fields:c}:{type:"text",value:"No field changes.",muted:!0})}return{title:`${lr(i)} entity ${s}`,icon:"entity",impact:pr(e.action,e.action==="merge"?"This combines duplicate records into the selected winner.":"This deletes the entity."),tone:dr(e.action),blocks:a,actions:[{id:"approve",label:"Approve",variant:"primary",icon:"check",tool:"manage_operations",args:{action:"approve"},resolvedLabel:`Approved — ${i} ${s} is being applied.`},{id:"reject",label:"Reject",variant:"outline",icon:"x",confirm:!0,confirmPrompt:"Reject this change?",tool:"manage_operations",args:{action:"reject"},resolvedLabel:`Rejected — ${i} ${s} was not applied.`}]}}const n=e.proposal?.agent_id??e.current?.id??"agent",r=e.action??"change",o=[];if(e.action==="delete")o.push({type:"text",value:"This will permanently delete the agent.",muted:!0});else{const s=Py.filter(i=>e.proposal?.[i]!==void 0&&Qe(e.proposal?.[i])!==Qe(e.current?.[i])).map(i=>({label:i,...e.action==="update"?{before:Qe(e.current?.[i])}:{},after:Qe(e.proposal?.[i])}));o.push(s.length>0?{type:"diff",fields:s}:{type:"text",value:"No field changes.",muted:!0})}return{title:`${lr(r)} agent ${n}`,icon:"agent",impact:pr(e.action,"This permanently deletes the agent and its configuration."),tone:dr(e.action),blocks:o,actions:[{id:"approve",label:"Approve",variant:"primary",icon:"check",tool:"manage_operations",args:{action:"approve"},resolvedLabel:`Approved — ${r} ${n} is being applied.`},{id:"reject",label:"Reject",variant:"outline",icon:"x",confirm:!0,confirmPrompt:"Reject this change?",tool:"manage_operations",args:{action:"reject"},resolvedLabel:`Rejected — ${r} ${n} was not applied.`}]}}function jy(e,t){const n=[];e.args!==void 0&&e.args!==null&&n.push({type:"code",value:Wt(e.args)});const r=t.map(o=>({id:o,label:o==="always"?"Always allow":`Approve ${o}`,variant:"outline",tool:"approve_tool_request",args:{decision:o},resolvedLabel:o==="always"?"Approved — always allowed.":`Approved for ${o}.`}));return r.push({id:"deny",label:"Deny",variant:"ghost",tool:"approve_tool_request",args:{decision:"deny"},resolvedLabel:"Denied."}),{title:`Wants to run ${e.tool??"a tool"}`,icon:"tool",impact:{level:"high",reason:"This grants the agent permission to use a tool."},tone:"warning",blocks:n,actions:r}}function My(e){const t=Array.isArray(e.options)?e.options.filter(o=>typeof o=="string"):[],n=[{type:"text",value:e.question||"The agent has a question."}];t.length===0&&n.push({type:"text",value:"Reply below to answer.",muted:!0});const r=t.map(o=>({id:o,label:o,variant:"outline",tool:"answer_question",args:{answer:o},resolvedLabel:`Answered: ${o}`}));return{title:"Input needed",icon:"question",tone:"default",blocks:n,actions:r}}function Ly(e,t){return{tone:"bare",actions:[{id:"open",label:e.label??"Open link",variant:"outline",icon:"external",terminal:!1,href:t}]}}const Dy=({toolName:e,args:t})=>{const n=Ba(),r=Ja(),{append:o}=cn(),s=Wr(),i=t??{},a=s?.resolve(e,t)??null;let c=a?.view??null;const u={...a?.handlers??{}},l=new Set;if(!a){if(e==="tool-approval"&&typeof i.runId=="number"){const p=i.runId,h=typeof i.status=="string"?i.status:"pending",f=h==="pending",y=Oy(i),P=y?_b(i):null,S=P?.view??Ay(i),j=h==="rejected"?i.action==="merge"?"Kept separate":"Rejected":h==="failed"?"Failed":"Approved";c=f||y?S:{...S,title:`${S.title??"Approval"} · ${j}`,tone:h==="failed"?"warning":"default",blocks:[...S.blocks??[],{type:"text",value:typeof i.reviewedByName=="string"?`${j} by ${i.reviewedByName}.`:`${j}.`,muted:!0}],actions:(S.actions??[]).filter(w=>w.terminal===!1)},f&&(u.manage_operations=w=>{if(w.action==="approve")return ss(k=>n.mutate({run_id:p},k));if(w.action==="reject"){const k=typeof w.reason=="string"?w.reason:void 0;return ss(O=>r.mutate({run_id:p,...k?{reason:k}:{}},O))}return Promise.resolve(!0)});const R=P?.reviewUrls??new Set;for(const w of R)l.add(w);u.open_review_link=w=>{const k=typeof w.url=="string"?w.url:"";return!R.has(k)||!Gn(k)?Promise.resolve(!0):(window.open(k,"_blank","noopener,noreferrer"),Promise.resolve(!1))}}else if(e==="tool-approval"){const p=Array.isArray(i.durationOptions)&&i.durationOptions.every(f=>typeof f=="string")&&i.durationOptions.length>0?i.durationOptions:["1h","24h","always"],h=new Set([...p,"deny"]);c=jy(i,p),u.approve_tool_request=async f=>{const y=typeof f.decision=="string"?f.decision:"";if(!i.requestId||!i.approveUrl||!h.has(y))return!0;try{return!(await Yn(i.approveUrl,{method:"POST",headers:{"Content-Type":"application/json",...i.orgSlug?{"x-lobu-org":i.orgSlug}:{}},credentials:"include",body:JSON.stringify({requestId:i.requestId,decision:y}),timeoutMs:2e4})).ok}catch{return!0}}}else if(e==="question"){const p=Array.isArray(i.options)?i.options.filter(h=>typeof h=="string"):[];c=My(i),u.answer_question=h=>{const f=typeof h.answer=="string"?h.answer:"";return p.includes(f)?(o(f),Promise.resolve(!1)):Promise.resolve(!0)}}else if(e==="link-button"){if(!Gn(i.url))return null;const p=i.url;l.add(p),c=Ly(i,p)}}return c?d.jsx(Ey,{src:Iy,title:c.title??"Interaction",renderPayload:c,onToolCall:(p,h)=>u[p]?u[p](h):Promise.resolve(!0),onOpenLink:p=>!l.has(p)||!Gn(p)?Promise.resolve(!0):(window.open(p,"_blank","noopener,noreferrer"),Promise.resolve(!1))}):null};function Wt(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}const Uy=()=>{const{running:e,append:t,cancel:n,pendingAttachments:r,addAttachments:o,removeAttachment:s,initialDraft:i,currentSuggestions:a,executionTarget:c}=cn(),u=qy({suggestions:e?null:a}),[l,p]=m.useState(i??""),h=m.useRef(null),f=m.useRef(null),y=rc(sc),P=m.useRef(i??"");m.useEffect(()=>{const R=i??"";if(R===P.current)return;const w=P.current;P.current=R,R!==""&&p(k=>k===""||k===w?R:k)},[i]);const S=m.useRef(l);S.current=l;const j=()=>{e||(t(S.current),p(""),f.current?.clear())};return d.jsxs("div",{className:"rounded-2xl border bg-background transition-colors focus-within:ring-1 focus-within:ring-ring",children:[!c&&r.length>0?d.jsx("div",{className:"flex flex-wrap gap-1.5 px-3 pt-3",children:r.map(R=>d.jsxs("div",{className:"flex items-center gap-1.5 rounded-lg border bg-muted/50 px-2 py-1 text-xs",children:[d.jsx(Qn,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),d.jsx("span",{className:"max-w-[12rem] truncate",children:R.name}),d.jsx("button",{type:"button",className:"text-muted-foreground transition-colors hover:text-foreground","aria-label":"Remove attachment",onClick:()=>s(R.id),children:d.jsx(Na,{className:"h-3 w-3"})})]},R.id))}):null,d.jsx(oc,{value:l,onChange:p,onSubmit:j,searchRefs:y,handleRef:f,placeholder:u,className:"max-h-48 overflow-y-auto"}),d.jsxs("div",{className:"flex items-center justify-between px-3 pb-2",children:[c?d.jsx("span",{className:"px-2 text-xs text-muted-foreground",children:"Running on your device"}):d.jsxs(d.Fragment,{children:[d.jsx("input",{ref:h,type:"file",multiple:!0,className:"hidden",onChange:R=>{R.target.files&&o(R.target.files),R.target.value=""}}),d.jsxs(it,{type:"button",size:"icon",variant:"ghost",className:"h-8 w-8 rounded-full text-muted-foreground hover:text-foreground",onClick:()=>h.current?.click(),children:[d.jsx(Qn,{className:"h-4 w-4"}),d.jsx("span",{className:"sr-only",children:"Attach files"})]})]}),e?d.jsxs(it,{type:"button",size:"icon",variant:"secondary",className:"h-8 w-8 rounded-full",onClick:n,children:[d.jsx(Za,{size:"lg"}),d.jsx("span",{className:"sr-only",children:"Cancel"})]}):d.jsxs(it,{type:"button",size:"icon",className:"h-8 w-8 rounded-full",onClick:j,children:[d.jsx(Oa,{className:"h-4 w-4"}),d.jsx("span",{className:"sr-only",children:"Send message"})]})]})]})};function qy({suggestions:e}){const t=e?.find(n=>n.message.trim().length>0)?.message;return t?`Recommended: ${t.trim()}`:"Chat… (@ to mention, / for commands)"}export{Xy as A,Yy as L,Gy as R,Qy as a,_b as b,hb as h,ub as s};