@datalayer/agent-runtimes 1.5.23 → 1.5.24

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 (115) hide show
  1. package/dist-embed/chunks/{CellSidebarExtension-CDnzN9Cb.js → CellSidebarExtension-B-73cmcQ.js} +1 -1
  2. package/dist-embed/chunks/{ChatView-BjZ993Ch.js → ChatView-CUWE6I5M.js} +3 -3
  3. package/dist-embed/chunks/{DeckComponent-Cb4_dZpN.js → DeckComponent-ymp4My5d.js} +1 -1
  4. package/dist-embed/chunks/{DocumentView-Caxb2xz-.js → DocumentView-i99p_Qzt.js} +1 -1
  5. package/dist-embed/chunks/{EphemeralDocument-DIHjR5l8.js → EphemeralDocument--pV47gPl.js} +1 -1
  6. package/dist-embed/chunks/{EphemeralNotebook-1Rwa3anx.js → EphemeralNotebook-BqccUXGd.js} +1 -1
  7. package/dist-embed/chunks/{ExcalidrawComponent-vJQwgcUt.js → ExcalidrawComponent-DgSMy796.js} +1 -1
  8. package/dist-embed/chunks/{ExcalidrawModal-BDgjdSz2.js → ExcalidrawModal-DFJW9pQh.js} +1 -1
  9. package/dist-embed/chunks/{JupyterLexicalExtension-_7FM5Om8.js → JupyterLexicalExtension-CqDatsgf.js} +5 -5
  10. package/dist-embed/chunks/{KernelVariables-CKIqy599.js → KernelVariables-CS6h5HyK.js} +1 -1
  11. package/dist-embed/chunks/{NotebookToolSurfaces-YAM1bvZS.js → NotebookToolSurfaces-CTLbTvsS.js} +1 -1
  12. package/dist-embed/chunks/{NotebookView-C8RCvsR1.js → NotebookView-BJpTApeL.js} +1 -1
  13. package/dist-embed/chunks/{Output-BWClePP-.js → Output-no9rnFJ7.js} +1 -1
  14. package/dist-embed/chunks/{SandboxDetailsDialog-CDSxIC0-.js → SandboxDetailsDialog-BAv6RMed.js} +1 -1
  15. package/dist-embed/chunks/{SchemaForm-CO_2yGg2.js → SchemaForm-CE5NfpBU.js} +1 -1
  16. package/dist-embed/chunks/{WidgetVariableView--osoOLv8.js → WidgetVariableView-V4DsgfIK.js} +1 -1
  17. package/dist-embed/chunks/{YouTubePlugin-BB7Z7INn.js → YouTubePlugin-CpgyVTwG.js} +1 -1
  18. package/dist-embed/chunks/{ar-SA-G6X2FPQ2-D6Ko4I2x.js → ar-SA-G6X2FPQ2-DwUjDWHp.js} +1 -1
  19. package/dist-embed/chunks/{az-AZ-76LH7QW2-B3UhxnSz.js → az-AZ-76LH7QW2-DROX4pJc.js} +1 -1
  20. package/dist-embed/chunks/{bg-BG-XCXSNQG7-BS-QRZjB.js → bg-BG-XCXSNQG7-DPLzP9Bm.js} +1 -1
  21. package/dist-embed/chunks/{bn-BD-2XOGV67Q-DNg0uIV0.js → bn-BD-2XOGV67Q-CCOU2J2j.js} +1 -1
  22. package/dist-embed/chunks/{ca-ES-6MX7JW3Y-Bn4yHfTY.js → ca-ES-6MX7JW3Y-3RgFapBd.js} +1 -1
  23. package/dist-embed/chunks/{cs-CZ-2BRQDIVT-DUGnyonZ.js → cs-CZ-2BRQDIVT-BJS7ofhJ.js} +1 -1
  24. package/dist-embed/chunks/{da-DK-5WZEPLOC-Is8nybqO.js → da-DK-5WZEPLOC-BHDT0zzh.js} +1 -1
  25. package/dist-embed/chunks/{de-DE-XR44H4JA-D54sMa4L.js → de-DE-XR44H4JA-CWVJKc9t.js} +1 -1
  26. package/dist-embed/chunks/{el-GR-BZB4AONW-CvM3SWat.js → el-GR-BZB4AONW-2z8DB9lI.js} +1 -1
  27. package/dist-embed/chunks/{es-ES-U4NZUMDT-BZDRRuRf.js → es-ES-U4NZUMDT-DzXGWPd4.js} +1 -1
  28. package/dist-embed/chunks/{eu-ES-A7QVB2H4-DAmknI9y.js → eu-ES-A7QVB2H4-CslHE4iE.js} +1 -1
  29. package/dist-embed/chunks/{fa-IR-HGAKTJCU-CQhKri4O.js → fa-IR-HGAKTJCU-CBWUHs2r.js} +1 -1
  30. package/dist-embed/chunks/{fi-FI-Z5N7JZ37-DzEDoP64.js → fi-FI-Z5N7JZ37-MAr8kZMI.js} +1 -1
  31. package/dist-embed/chunks/{fr-FR-RHASNOE6-DiSkyvEB.js → fr-FR-RHASNOE6-BUz3aHQJ.js} +1 -1
  32. package/dist-embed/chunks/{gl-ES-HMX3MZ6V-3AJMzY-I.js → gl-ES-HMX3MZ6V-DvzQmDYv.js} +1 -1
  33. package/dist-embed/chunks/{he-IL-6SHJWFNN-Cuh5an4X.js → he-IL-6SHJWFNN-DKR3cKyQ.js} +1 -1
  34. package/dist-embed/chunks/{hi-IN-IWLTKZ5I-BbeuFB83.js → hi-IN-IWLTKZ5I-C4tyBNwa.js} +1 -1
  35. package/dist-embed/chunks/{hu-HU-A5ZG7DT2-C1OMfhob.js → hu-HU-A5ZG7DT2-C8BnBgH5.js} +1 -1
  36. package/dist-embed/chunks/{id-ID-SAP4L64H-BzKILJTZ.js → id-ID-SAP4L64H-Bn1hY5OS.js} +1 -1
  37. package/dist-embed/chunks/{index-CPpm1tqJ.js → index-5N0EOEHV.js} +1 -1
  38. package/dist-embed/chunks/{index-f418CYn7.js → index-BKB97UwL.js} +1 -1
  39. package/dist-embed/chunks/{index-CyQgE_Es.js → index-BN8Bbau-.js} +2 -2
  40. package/dist-embed/chunks/{index-CKFrz1es.js → index-BTdq_niO.js} +1 -1
  41. package/dist-embed/chunks/{index-D4QM3qbA.js → index-Bhzj1Pnv.js} +1 -1
  42. package/dist-embed/chunks/{index-BMandbJB.js → index-BzMt3uYX.js} +1 -1
  43. package/dist-embed/chunks/{index-DLimRfHQ.js → index-CCRwowMu.js} +1 -1
  44. package/dist-embed/chunks/{index-BFdE0KFI.js → index-CEbnhuIo.js} +1 -1
  45. package/dist-embed/chunks/{index-CAd5YQQl.js → index-CZB8DyUw.js} +1 -1
  46. package/dist-embed/chunks/{index-BO6VQLH6.js → index-Cd5CgKFr.js} +1 -1
  47. package/dist-embed/chunks/{index-D64QvG43.js → index-CkQ6IAoY.js} +1 -1
  48. package/dist-embed/chunks/{index-BktUM85c.js → index-Coj9opLJ.js} +1 -1
  49. package/dist-embed/chunks/{index-dYwQAVs_.js → index-D9_026K2.js} +1 -1
  50. package/dist-embed/chunks/{index-SbFvdBPQ.js → index-DVaPKQyL.js} +1 -1
  51. package/dist-embed/chunks/{index-f9WZsG2n.js → index-DWfzdTZo.js} +1 -1
  52. package/dist-embed/chunks/{index-DY8mjz1l.js → index-DdBQBN76.js} +1 -1
  53. package/dist-embed/chunks/{index-DEjLPUAD.js → index-Di3aBGLV.js} +1 -1
  54. package/dist-embed/chunks/{index-Cu0bp_EI.js → index-Gngo0bXi.js} +1 -1
  55. package/dist-embed/chunks/{index-DyVR0igi.js → index-S4sn4R3i.js} +1 -1
  56. package/dist-embed/chunks/{index-noRoZrq5.js → index-Z2pxzg3H.js} +1 -1
  57. package/dist-embed/chunks/{index-PqsSImlj.js → index-_H5U6gal.js} +1 -1
  58. package/dist-embed/chunks/{index-x45cMPwN.js → index-_nsBY26B.js} +1 -1
  59. package/dist-embed/chunks/{index-CM7xo08K.js → index-b6e3y1R-.js} +1 -1
  60. package/dist-embed/chunks/{index-wk9vl2uW.js → index-szXn1pzS.js} +1 -1
  61. package/dist-embed/chunks/{index.esm-p0OnSU9h.js → index.esm-nZym6gpK.js} +1 -1
  62. package/dist-embed/chunks/isEqual-g-jK7vY0.js +1 -0
  63. package/dist-embed/chunks/{it-IT-JPQ66NNP-DuG05fUR.js → it-IT-JPQ66NNP-DEiaanA7.js} +1 -1
  64. package/dist-embed/chunks/{ja-JP-DBVTYXUO-DeDfL3Bk.js → ja-JP-DBVTYXUO-Bb0GBZrQ.js} +1 -1
  65. package/dist-embed/chunks/{kaa-6HZHGXH3-BRKFVG6s.js → kaa-6HZHGXH3-DxqTv9uN.js} +1 -1
  66. package/dist-embed/chunks/{kab-KAB-ZGHBKWFO-Uqakmhz5.js → kab-KAB-ZGHBKWFO-D0V0yQgV.js} +1 -1
  67. package/dist-embed/chunks/{kk-KZ-P5N5QNE5-DWMXMIAK.js → kk-KZ-P5N5QNE5-CYyEyHXW.js} +1 -1
  68. package/dist-embed/chunks/{km-KH-HSX4SM5Z-BXNl9QnV.js → km-KH-HSX4SM5Z-CCTEGikY.js} +1 -1
  69. package/dist-embed/chunks/{ko-KR-MTYHY66A-BZgIqTuN.js → ko-KR-MTYHY66A-C-QDut19.js} +1 -1
  70. package/dist-embed/chunks/{ku-TR-6OUDTVRD-CQNa5i5U.js → ku-TR-6OUDTVRD-CIqn8p2Y.js} +1 -1
  71. package/dist-embed/chunks/{lt-LT-XHIRWOB4-BQW2k7iv.js → lt-LT-XHIRWOB4-BDLUWFPH.js} +1 -1
  72. package/dist-embed/chunks/{lv-LV-5QDEKY6T-B0HRRCC4.js → lv-LV-5QDEKY6T-BItabIJP.js} +1 -1
  73. package/dist-embed/chunks/{mr-IN-CRQNXWMA-DXR6sWSH.js → mr-IN-CRQNXWMA-DXXb8N2w.js} +1 -1
  74. package/dist-embed/chunks/{my-MM-5M5IBNSE-BZ5_9oCm.js → my-MM-5M5IBNSE-TidIfjqS.js} +1 -1
  75. package/dist-embed/chunks/{nb-NO-T6EIAALU-CBtv36wZ.js → nb-NO-T6EIAALU-DEINynK7.js} +1 -1
  76. package/dist-embed/chunks/{nl-NL-IS3SIHDZ-CcqE3cY8.js → nl-NL-IS3SIHDZ-D04rJzNe.js} +1 -1
  77. package/dist-embed/chunks/{nn-NO-6E72VCQL-Cl9wPgpU.js → nn-NO-6E72VCQL-oWFzCtpf.js} +1 -1
  78. package/dist-embed/chunks/{oc-FR-POXYY2M6-CQEkV2p1.js → oc-FR-POXYY2M6-BmFfP6hk.js} +1 -1
  79. package/dist-embed/chunks/{pa-IN-N4M65BXN-CaE6yG0U.js → pa-IN-N4M65BXN-RkXrgKXw.js} +1 -1
  80. package/dist-embed/chunks/{percentages-BXMCSKIN-Bk5xifLL.js → percentages-BXMCSKIN-BL_DuU3S.js} +3 -3
  81. package/dist-embed/chunks/{pl-PL-T2D74RX3-M1pQcF2j.js → pl-PL-T2D74RX3-DqxkHzTj.js} +1 -1
  82. package/dist-embed/chunks/{pt-BR-5N22H2LF-BFDHu72z.js → pt-BR-5N22H2LF-DFA-wWC5.js} +1 -1
  83. package/dist-embed/chunks/{pt-PT-UZXXM6DQ-DFcZY1Gz.js → pt-PT-UZXXM6DQ-Z5jw_7aw.js} +1 -1
  84. package/dist-embed/chunks/{renderer-Dy4lZ1KZ.js → renderer-DKKfWkWv.js} +1 -1
  85. package/dist-embed/chunks/{ro-RO-JPDTUUEW-BGm_Xwik.js → ro-RO-JPDTUUEW-DjC09bHq.js} +1 -1
  86. package/dist-embed/chunks/{ru-RU-B4JR7IUQ-BsrZ_x8p.js → ru-RU-B4JR7IUQ-CqwD7Yik.js} +1 -1
  87. package/dist-embed/chunks/{si-LK-N5RQ5JYF-BfaYS44g.js → si-LK-N5RQ5JYF-OVf4k6G3.js} +1 -1
  88. package/dist-embed/chunks/{sk-SK-C5VTKIMK-D-K9yMTN.js → sk-SK-C5VTKIMK-BG__kjLT.js} +1 -1
  89. package/dist-embed/chunks/{sl-SI-NN7IZMDC-B48XvZUw.js → sl-SI-NN7IZMDC-CIgxidVH.js} +1 -1
  90. package/dist-embed/chunks/{subset-shared.chunk-DzA7mJjZ.js → subset-shared.chunk-BR0LJHtQ.js} +1 -1
  91. package/dist-embed/chunks/{subset-worker.chunk-CsTEdHAt.js → subset-worker.chunk-52aAcjvz.js} +1 -1
  92. package/dist-embed/chunks/{sv-SE-XGPEYMSR-DfhLO_Vt.js → sv-SE-XGPEYMSR-CYHz3xCa.js} +1 -1
  93. package/dist-embed/chunks/{ta-IN-2NMHFXQM-EZA_oxSt.js → ta-IN-2NMHFXQM-BphRr9QY.js} +1 -1
  94. package/dist-embed/chunks/{th-TH-HPSO5L25-G9vy_zQH.js → th-TH-HPSO5L25-Ba2-2Bo0.js} +1 -1
  95. package/dist-embed/chunks/{tr-TR-DEFEU3FU-DBj_G5CD.js → tr-TR-DEFEU3FU-CRKE7Roy.js} +1 -1
  96. package/dist-embed/chunks/{uk-UA-QMV73CPH-DN7lMu5H.js → uk-UA-QMV73CPH-DlNE5CAT.js} +1 -1
  97. package/dist-embed/chunks/{vi-VN-M7AON7JQ-LoT02qgd.js → vi-VN-M7AON7JQ-Cp44PRXY.js} +1 -1
  98. package/dist-embed/chunks/{zh-CN-LNUGB5OW-CjexwOqT.js → zh-CN-LNUGB5OW-JHqqwp0j.js} +1 -1
  99. package/dist-embed/chunks/{zh-HK-E62DVLB3-B0ys_HV6.js → zh-HK-E62DVLB3-YEs97mA8.js} +1 -1
  100. package/dist-embed/chunks/{zh-TW-RAJ6MFWO-tQJWLJuU.js → zh-TW-RAJ6MFWO-CgmeTbuy.js} +1 -1
  101. package/dist-embed/datalayer-app-main.js +12 -12
  102. package/lib/chat/presence/Presence.d.ts +4 -4
  103. package/lib/chat/presence/Presence.js +3 -2
  104. package/lib/chat/presence/presenceStatus.d.ts +3 -34
  105. package/lib/chat/presence/presenceStatus.js +4 -46
  106. package/lib/portable/fixtures.d.ts +11 -0
  107. package/lib/portable/fixtures.js +70 -0
  108. package/lib/portable/index.d.ts +3 -0
  109. package/lib/portable/index.js +5 -0
  110. package/lib/portable/presence.d.ts +47 -0
  111. package/lib/portable/presence.js +71 -0
  112. package/lib/portable/views.d.ts +125 -0
  113. package/lib/portable/views.js +52 -0
  114. package/package.json +1 -1
  115. package/dist-embed/chunks/isEqual-Cwjr2skl.js +0 -1
@@ -2091,7 +2091,7 @@ Execution failed: ${Du}`,diff:Pu}}}catch(Pu){const Ou=Pu instanceof Error?Pu.mes
2091
2091
  `)}function decode$4(Au,lo){return decodeFromLines(Au.split(`
2092
2092
  `))}function encodeLines(Au,lo){return encodeJsonValue(normalizeValue(Au),resolveOptions(),0)}function decodeFromLines(Au,lo){const $u=resolveDecodeOptions();return buildValueFromEvents(decodeStreamSync$1(Au,{indent:$u.indent,strict:$u.strict}))}function resolveOptions(Au){return{indent:2,delimiter:DEFAULT_DELIMITER,keyFolding:"off",flattenDepth:Number.POSITIVE_INFINITY}}function resolveDecodeOptions(Au){return{indent:2,strict:!0,expandPaths:"off"}}function formatResponse(Au,lo){return lo==="json"?Au:encode$3(Au)}class DefaultExecutor{documentId;store;constructor(lo,$u){this.documentId=lo,this.store=$u}async execute(lo,$u){const Ru=this.store[lo];if(typeof Ru!="function")throw new Error(`Store method '${lo}' not found or not a function`);const Iu=typeof $u=="object"&&$u!==null?{id:this.documentId,...$u}:{id:this.documentId};return await Ru.call(this.store,Iu)}}class OperationRunner{async execute(lo,$u,Ru){const Iu=await lo.execute($u,Ru);return formatResponse(Iu,Ru.format)}}const notebookToolDefinitions=[insertCellTool,deleteCellsTool,updateCellTool,readCellTool,readAllCellsTool,runCellTool,executeCodeTool],notebookToolOperations={insertCell:insertCellOperation,deleteCells:deleteCellsOperation,updateCell:updateCellOperation,readCell:readCellOperation,readAllCells:readAllCellsOperation,runCell:runCellOperation,executeCodeInNotebook:executeCodeOperation,executeCode:executeCodeOperation},notebookTools={definitions:notebookToolDefinitions,operations:notebookToolOperations},SPACE_CONTEXT_COOKIE="datalayer-space-context",SPACE_CONTEXT_COOKIE_MAX_AGE=3600*24*365,readSpaceContextCookie=()=>{if(typeof document>"u")return;const Au=SPACE_CONTEXT_COOKIE.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),lo=document.cookie.match(new RegExp(`(?:^|;\\s*)${Au}=([^;]*)`));if(lo?.[1])try{const $u=JSON.parse(decodeURIComponent(lo[1]));return!$u||typeof $u!="object"||typeof $u.id!="string"?void 0:{id:$u.id,handle:typeof $u.handle=="string"?$u.handle:void 0,name:typeof $u.name=="string"?$u.name:void 0}}catch{return}},writeSpaceContextCookie=Au=>{if(typeof document>"u")return;if(!Au?.id){document.cookie=`${SPACE_CONTEXT_COOKIE}=; path=/; max-age=0; SameSite=Lax`;return}const lo=encodeURIComponent(JSON.stringify({id:Au.id,handle:Au.handle,name:Au.name}));document.cookie=`${SPACE_CONTEXT_COOKIE}=${lo}; path=/; max-age=${SPACE_CONTEXT_COOKIE_MAX_AGE}; SameSite=Lax`},initialSpaceContext=readSpaceContextCookie(),layoutStore=createStore$1((Au,lo)=>({backdrop:void 0,banner:void 0,bootstrapped:!1,item:void 0,itemsRefreshCount:0,leftPortal:void 0,leftSidebarVariant:"empty",organization:void 0,rightPortal:void 0,screenCapture:void 0,space:initialSpaceContext,team:void 0,hideBackdrop:()=>Au($u=>({backdrop:{open:!1,message:void 0}})),hideScreencapture:()=>Au($u=>({screenshot:{open:!1,message:void 0}})),setBootstrapped:$u=>Au(Ru=>({bootstrapped:$u})),showBackdrop:$u=>Au(Ru=>({backdrop:{open:!0,message:$u}})),showScreencapture:$u=>Au(Ru=>({screenshot:{open:!0,message:$u}})),setBanner:$u=>Au(Ru=>({banner:{timestamp:new Date,message:$u.message,variant:$u.variant}})),setLeftPortal:$u=>Au(Ru=>({leftPortal:$u})),setRightPortal:$u=>Au(Ru=>({rightPortal:$u})),resetLeftPortal:()=>Au($u=>({leftPortal:$u.leftPortal?.pinned?$u.leftPortal:void 0})),resetRightPortal:()=>Au($u=>({rightPortal:$u.rightPortal?.pinned?$u.rightPortal:void 0})),resetForcedLeftPortal:()=>Au($u=>({leftPortal:void 0})),resetForcedRightPortal:()=>Au($u=>({rightPortal:void 0})),setLeftSidebarVariant:$u=>Au(Ru=>({leftSidebarVariant:$u})),updateLayoutOrganization:$u=>Au(Ru=>({organization:$u?{...Ru.organization,...$u}:void 0})),updateLayoutTeam:$u=>Au(Ru=>({team:$u?{...Ru.team,...$u}:void 0})),updateLayoutSpace:$u=>Au(Ru=>{const Iu=$u?{...Ru.space,...$u}:void 0;return writeSpaceContextCookie(Iu),{space:Iu}}),setItem:$u=>Au(Ru=>({item:$u})),triggerItemsRefresh:()=>Au($u=>({itemsRefreshCount:$u.itemsRefreshCount+1})),setScreencapture:$u=>Au(Ru=>({screenCapture:$u})),reset:()=>Au($u=>({bootstrapped:!1}))}));registerSessionState({forget:()=>{const Au=layoutStore.getState();Au.updateLayoutSpace(void 0),Au.updateLayoutOrganization(void 0),Au.updateLayoutTeam(void 0),Au.setItem(void 0)}});function useLayoutStore(Au){return useStore$1(layoutStore,Au)}var ABSOLUTE_URL_REGEX=/^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i,PROTOCOL_RELATIVE_URL_REGEX=/^[\\/]{2}/;function normalizeProtocolRelativeUrl(Au,lo){return lo+Au.replace(/\\/g,"/")}function invariant(Au,lo){if(Au===!1||Au===null||typeof Au>"u")throw new Error(lo)}function warning(Au,lo){if(!Au){typeof console<"u"&&console.warn(lo);try{throw new Error(lo)}catch{}}}function createPath({pathname:Au="/",search:lo="",hash:$u=""}){return lo&&lo!=="?"&&(Au+=lo.charAt(0)==="?"?lo:"?"+lo),$u&&$u!=="#"&&(Au+=$u.charAt(0)==="#"?$u:"#"+$u),Au}function parsePath(Au){let lo={};if(Au){let $u=Au.indexOf("#");$u>=0&&(lo.hash=Au.substring($u),Au=Au.substring(0,$u));let Ru=Au.indexOf("?");Ru>=0&&(lo.search=Au.substring(Ru),Au=Au.substring(0,Ru)),Au&&(lo.pathname=Au)}return lo}function matchRoutes(Au,lo,$u="/"){return matchRoutesImpl(Au,lo,$u,!1)}function matchRoutesImpl(Au,lo,$u,Ru,Iu){let Pu=typeof lo=="string"?parsePath(lo):lo,Ou=stripBasename(Pu.pathname||"/",$u);if(Ou==null)return null;let Mu=flattenAndRankRoutes(Au),Du=null,Lu=decodePath(Ou);for(let Bu=0;Du==null&&Bu<Mu.length;++Bu)Du=matchRouteBranch(Mu[Bu],Lu,Ru);return Du}function flattenAndRankRoutes(Au){let lo=flattenRoutes(Au);return rankRouteBranches(lo),lo}function flattenRoutes(Au,lo=[],$u=[],Ru="",Iu=!1){let Pu=(Ou,Mu,Du=Iu,Lu)=>{let Bu={relativePath:Lu===void 0?Ou.path||"":Lu,caseSensitive:Ou.caseSensitive===!0,childrenIndex:Mu,route:Ou};if(Bu.relativePath.startsWith("/")){if(!Bu.relativePath.startsWith(Ru)&&Du)return;invariant(Bu.relativePath.startsWith(Ru),`Absolute route path "${Bu.relativePath}" nested under path "${Ru}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),Bu.relativePath=Bu.relativePath.slice(Ru.length)}let ju=joinPaths([Ru,Bu.relativePath]),Fu=$u.concat(Bu);Ou.children&&Ou.children.length>0&&(invariant(Ou.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${ju}".`),flattenRoutes(Ou.children,lo,Fu,ju,Du)),!(Ou.path==null&&!Ou.index)&&lo.push({path:ju,score:computeScore(ju,Ou.index),routesMeta:Fu.map((zu,Uu)=>{let[Hu,Vu]=compilePath(zu.relativePath,zu.caseSensitive,Uu===Fu.length-1);return{...zu,matcher:Hu,compiledParams:Vu}})})};return Au.forEach((Ou,Mu)=>{if(Ou.path===""||!Ou.path?.includes("?"))Pu(Ou,Mu);else for(let Du of explodeOptionalSegments(Ou.path))Pu(Ou,Mu,!0,Du)}),lo}function explodeOptionalSegments(Au){let lo=Au.split("/");if(lo.length===0)return[];let[$u,...Ru]=lo,Iu=$u.endsWith("?"),Pu=$u.replace(/\?$/,"");if(Ru.length===0)return Iu?[Pu,""]:[Pu];let Ou=explodeOptionalSegments(Ru.join("/")),Mu=[];return Mu.push(...Ou.map(Du=>Du===""?Pu:[Pu,Du].join("/"))),Iu&&Mu.push(...Ou),Mu.map(Du=>Au.startsWith("/")&&Du===""?"/":Du)}function rankRouteBranches(Au){Au.sort((lo,$u)=>lo.score!==$u.score?$u.score-lo.score:compareIndexes(lo.routesMeta.map(Ru=>Ru.childrenIndex),$u.routesMeta.map(Ru=>Ru.childrenIndex)))}var paramRe=/^:[\w-]+$/,dynamicSegmentValue=3,indexRouteValue=2,emptySegmentValue=1,staticSegmentValue=10,splatPenalty=-2,isSplat=Au=>Au==="*";function computeScore(Au,lo){let $u=Au.split("/"),Ru=$u.length;return $u.some(isSplat)&&(Ru+=splatPenalty),lo&&(Ru+=indexRouteValue),$u.filter(Iu=>!isSplat(Iu)).reduce((Iu,Pu)=>Iu+(paramRe.test(Pu)?dynamicSegmentValue:Pu===""?emptySegmentValue:staticSegmentValue),Ru)}function compareIndexes(Au,lo){return Au.length===lo.length&&Au.slice(0,-1).every((Ru,Iu)=>Ru===lo[Iu])?Au[Au.length-1]-lo[lo.length-1]:0}function matchRouteBranch(Au,lo,$u=!1){let{routesMeta:Ru}=Au,Iu={},Pu="/",Ou=[];for(let Mu=0;Mu<Ru.length;++Mu){let Du=Ru[Mu],Lu=Mu===Ru.length-1,Bu=Pu==="/"?lo:lo.slice(Pu.length)||"/",ju={path:Du.relativePath,caseSensitive:Du.caseSensitive,end:Lu},Fu=Du.matcher&&Du.compiledParams?matchPathImpl(ju,Bu,Du.matcher,Du.compiledParams):matchPath(ju,Bu),zu=Du.route;if(!Fu&&Lu&&$u&&!Ru[Ru.length-1].route.index&&(Fu=matchPath({path:Du.relativePath,caseSensitive:Du.caseSensitive,end:!1},Bu)),!Fu)return null;Object.assign(Iu,Fu.params),Ou.push({params:Iu,pathname:joinPaths([Pu,Fu.pathname]),pathnameBase:normalizePathname$1(joinPaths([Pu,Fu.pathnameBase])),route:zu}),Fu.pathnameBase!=="/"&&(Pu=joinPaths([Pu,Fu.pathnameBase]))}return Ou}function matchPath(Au,lo){typeof Au=="string"&&(Au={path:Au,caseSensitive:!1,end:!0});let[$u,Ru]=compilePath(Au.path,Au.caseSensitive,Au.end);return matchPathImpl(Au,lo,$u,Ru)}function matchPathImpl(Au,lo,$u,Ru){let Iu=lo.match($u);if(!Iu)return null;let Pu=Iu[0],Ou=removeTrailingSlash(Pu,1),Mu=Iu.slice(1);return{params:Ru.reduce((Lu,{paramName:Bu,isOptional:ju},Fu)=>{if(Bu==="*"){let Uu=Mu[Fu]||"";Ou=removeTrailingSlash(Pu.slice(0,Pu.length-Uu.length),1)}const zu=Mu[Fu];return ju&&!zu?Lu[Bu]=void 0:Lu[Bu]=(zu||"").replace(/%2F/g,"/"),Lu},{}),pathname:Pu,pathnameBase:Ou,pattern:Au}}function compilePath(Au,lo=!1,$u=!0){warning(Au==="*"||!Au.endsWith("*")||Au.endsWith("/*"),`Route path "${Au}" will be treated as if it were "${Au.replace(/\*$/,"/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${Au.replace(/\*$/,"/*")}".`);let Ru=[],Iu="^"+Au.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(Ou,Mu,Du,Lu,Bu)=>{if(Ru.push({paramName:Mu,isOptional:Du!=null}),Du){let ju=Bu.charAt(Lu+Ou.length);return ju&&ju!=="/"?"/([^\\/]*)":"(?:/([^\\/]*))?"}return"/([^\\/]+)"}).replace(/\/([\w-]+)\?(\/|$)/g,"(/$1)?$2");return Au.endsWith("*")?(Ru.push({paramName:"*"}),Iu+=Au==="*"||Au==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):$u?Iu+="\\/*$":Au!==""&&Au!=="/"&&(Iu+="(?:(?=\\/|$))"),[new RegExp(Iu,lo?void 0:"i"),Ru]}function decodePath(Au){try{return Au.split("/").map(lo=>decodeURIComponent(lo).replace(/\//g,"%2F")).join("/")}catch(lo){return warning(!1,`The URL path "${Au}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${lo}).`),Au}}function stripBasename(Au,lo){if(lo==="/")return Au;if(!Au.toLowerCase().startsWith(lo.toLowerCase()))return null;let $u=lo.endsWith("/")?lo.length-1:lo.length,Ru=Au.charAt($u);return Ru&&Ru!=="/"?null:Au.slice($u)||"/"}function resolvePath(Au,lo="/"){let{pathname:$u,search:Ru="",hash:Iu=""}=typeof Au=="string"?parsePath(Au):Au,Pu;return $u?($u=removeDoubleSlashes($u),$u.startsWith("/")||$u.startsWith("\\")?Pu=resolvePathname($u.substring(1),"/"):Pu=resolvePathname($u,lo)):Pu=lo,{pathname:Pu,search:normalizeSearch(Ru),hash:normalizeHash(Iu)}}function resolvePathname(Au,lo){let $u=removeTrailingSlash(lo).split("/");return Au.split("/").forEach(Iu=>{Iu===".."?$u.length>1&&$u.pop():Iu!=="."&&$u.push(Iu)}),$u.length>1?$u.join("/"):"/"}function getInvalidPathError(Au,lo,$u,Ru){return`Cannot include a '${Au}' character in a manually specified \`to.${lo}\` field [${JSON.stringify(Ru)}]. Please separate it out to the \`to.${$u}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function getPathContributingMatches(Au){return Au.filter((lo,$u)=>$u===0||lo.route.path&&lo.route.path.length>0)}function getResolveToMatches(Au){let lo=getPathContributingMatches(Au);return lo.map(($u,Ru)=>Ru===lo.length-1?$u.pathname:$u.pathnameBase)}function resolveTo(Au,lo,$u,Ru=!1){let Iu;typeof Au=="string"?Iu=parsePath(Au):(Iu={...Au},invariant(!Iu.pathname||!Iu.pathname.includes("?"),getInvalidPathError("?","pathname","search",Iu)),invariant(!Iu.pathname||!Iu.pathname.includes("#"),getInvalidPathError("#","pathname","hash",Iu)),invariant(!Iu.search||!Iu.search.includes("#"),getInvalidPathError("#","search","hash",Iu)));let Pu=Au===""||Iu.pathname==="",Ou=Pu?"/":Iu.pathname,Mu;if(Ou==null)Mu=$u;else{let ju=lo.length-1;if(!Ru&&Ou.startsWith("..")){let Fu=Ou.split("/");for(;Fu[0]==="..";)Fu.shift(),ju-=1;Iu.pathname=Fu.join("/")}Mu=ju>=0?lo[ju]:"/"}let Du=resolvePath(Iu,Mu),Lu=Ou&&Ou!=="/"&&Ou.endsWith("/"),Bu=(Pu||Ou===".")&&$u.endsWith("/");return!Du.pathname.endsWith("/")&&(Lu||Bu)&&(Du.pathname+="/"),Du}var removeDoubleSlashes=Au=>Au.replace(/[\\/]{2,}/g,"/"),joinPaths=Au=>removeDoubleSlashes(Au.join("/"));function removeTrailingSlash(Au,lo=0){let $u=Au.length;for(;$u>lo&&Au.charCodeAt($u-1)===47;)$u--;return $u===Au.length?Au:Au.slice(0,$u)}var normalizePathname$1=Au=>removeTrailingSlash(Au).replace(/^\/*/,"/"),normalizeSearch=Au=>!Au||Au==="?"?"":Au.startsWith("?")?Au:"?"+Au,normalizeHash=Au=>!Au||Au==="#"?"":Au.startsWith("#")?Au:"#"+Au,ErrorResponseImpl=class{constructor(Au,lo,$u,Ru=!1){this.status=Au,this.statusText=lo||"",this.internal=Ru,$u instanceof Error?(this.data=$u.toString(),this.error=$u):this.data=$u}};function isRouteErrorResponse(Au){return Au!=null&&typeof Au.status=="number"&&typeof Au.statusText=="string"&&typeof Au.internal=="boolean"&&"data"in Au}function getRoutePattern(Au){let lo=Au.map($u=>$u.route.path).filter(Boolean);return joinPaths(lo)||"/"}var isBrowser=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function parseToInfo(Au,lo){let $u=Au;if(typeof $u!="string"||!ABSOLUTE_URL_REGEX.test($u))return{absoluteURL:void 0,isExternal:!1,to:$u};let Ru=$u,Iu=!1;if(isBrowser)try{let Pu=new URL(window.location.href),Ou=PROTOCOL_RELATIVE_URL_REGEX.test($u)?new URL(normalizeProtocolRelativeUrl($u,Pu.protocol)):new URL($u),Mu=stripBasename(Ou.pathname,lo);Ou.origin===Pu.origin&&Mu!=null?$u=Mu+Ou.search+Ou.hash:Iu=!0}catch{warning(!1,`<Link to="${$u}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:Ru,isExternal:Iu,to:$u}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");var DEFAULT_NAVIGATION_URL=new URL("http://localhost");function getNavigatorCurrentUrl(Au){if(Au.createURL)return Au.createURL("/");try{return new URL(Au.createHref("/"),DEFAULT_NAVIGATION_URL)}catch{return DEFAULT_NAVIGATION_URL}}function isSameOrigin$3(Au,lo){return Au.origin===lo.origin&&(Au.origin!=="null"||Au.protocol===lo.protocol&&Au.host===lo.host)}function isExplicitUrl(Au,lo){if(Au.startsWith("//"))return!0;let $u=lo.protocol.toLowerCase();return Au.toLowerCase().startsWith($u)?lo.host===""||Au.slice($u.length).startsWith("//"):!1}function validateNavigationTarget(Au,lo,$u,Ru){let Iu=null;try{Iu=Au==null?null:new URL(Au,$u)}catch{}let Pu=new URL(lo,$u),Ou=Iu!=null&&!isSameOrigin$3(Iu,$u),Mu=!isSameOrigin$3(Pu,$u);if(Ru==="reject"){if(Ou||Mu)throw new Error("External navigation is not allowed")}else if(Mu&&(Iu==null||!isExplicitUrl(Au,Iu)||!isSameOrigin$3(Iu,Pu)))throw new Error("External navigation is not allowed")}var validMutationMethodsArr=["POST","PUT","PATCH","DELETE"];new Set(validMutationMethodsArr);var validRequestMethodsArr=["GET",...validMutationMethodsArr];new Set(validRequestMethodsArr);var invalidProtocols=["about:","blob:","chrome:","chrome-untrusted:","content:","data:","devtools:","file:","filesystem:","javascript:"];function hasInvalidProtocol(Au){try{return invalidProtocols.includes(new URL(Au).protocol)}catch{return!1}}var DataRouterContext=reactExports.createContext(null);DataRouterContext.displayName="DataRouter";var DataRouterStateContext=reactExports.createContext(null);DataRouterStateContext.displayName="DataRouterState";var RSCRouterContext=reactExports.createContext(!1);function useIsRSCRouterContext(){return reactExports.useContext(RSCRouterContext)}var ViewTransitionContext=reactExports.createContext({isTransitioning:!1});ViewTransitionContext.displayName="ViewTransition";var FetchersContext=reactExports.createContext(new Map);FetchersContext.displayName="Fetchers";var AwaitContext=reactExports.createContext(null);AwaitContext.displayName="Await";var NavigationContext=reactExports.createContext(null);NavigationContext.displayName="Navigation";var LocationContext=reactExports.createContext(null);LocationContext.displayName="Location";var RouteContext=reactExports.createContext({outlet:null,matches:[],isDataRoute:!1});RouteContext.displayName="Route";var RouteErrorContext=reactExports.createContext(null);RouteErrorContext.displayName="RouteError";var ERROR_DIGEST_BASE="REACT_ROUTER_ERROR",ERROR_DIGEST_REDIRECT="REDIRECT",ERROR_DIGEST_ROUTE_ERROR_RESPONSE="ROUTE_ERROR_RESPONSE";function decodeRedirectErrorDigest(Au){if(Au.startsWith(`${ERROR_DIGEST_BASE}:${ERROR_DIGEST_REDIRECT}:{`))try{let lo=JSON.parse(Au.slice(28));if(typeof lo=="object"&&lo&&typeof lo.status=="number"&&typeof lo.statusText=="string"&&typeof lo.location=="string"&&typeof lo.reloadDocument=="boolean"&&typeof lo.replace=="boolean")return lo}catch{}}function decodeRouteErrorResponseDigest(Au){if(Au.startsWith(`${ERROR_DIGEST_BASE}:${ERROR_DIGEST_ROUTE_ERROR_RESPONSE}:{`))try{let lo=JSON.parse(Au.slice(40));if(typeof lo=="object"&&lo&&typeof lo.status=="number"&&typeof lo.statusText=="string")return new ErrorResponseImpl(lo.status,lo.statusText,lo.data)}catch{}}function useHref(Au,{relative:lo}={}){invariant(useInRouterContext(),"useHref() may be used only in the context of a <Router> component.");let{basename:$u,navigator:Ru}=reactExports.useContext(NavigationContext),{hash:Iu,pathname:Pu,search:Ou}=useResolvedPath(Au,{relative:lo}),Mu=Pu;return $u!=="/"&&(Mu=Pu==="/"?$u:joinPaths([$u,Pu])),Ru.createHref({pathname:Mu,search:Ou,hash:Iu})}function useInRouterContext(){return reactExports.useContext(LocationContext)!=null}function useLocation$1(){return invariant(useInRouterContext(),"useLocation() may be used only in the context of a <Router> component."),reactExports.useContext(LocationContext).location}var navigateEffectWarning="You should call navigate() in a React.useEffect(), not when your component is first rendered.";function useIsomorphicLayoutEffect(Au){reactExports.useContext(NavigationContext).static||reactExports.useLayoutEffect(Au)}function useNavigate$1(){let{isDataRoute:Au}=reactExports.useContext(RouteContext);return Au?useNavigateStable():useNavigateUnstable()}function useNavigateUnstable(){invariant(useInRouterContext(),"useNavigate() may be used only in the context of a <Router> component.");let Au=reactExports.useContext(DataRouterContext),{basename:lo,navigator:$u}=reactExports.useContext(NavigationContext),{matches:Ru}=reactExports.useContext(RouteContext),{pathname:Iu}=useLocation$1(),Pu=JSON.stringify(getResolveToMatches(Ru)),Ou=reactExports.useRef(!1);return useIsomorphicLayoutEffect(()=>{Ou.current=!0}),reactExports.useCallback((Du,Lu={})=>{if(warning(Ou.current,navigateEffectWarning),!Ou.current)return;if(typeof Du=="number"){$u.go(Du);return}let Bu=resolveTo(Du,JSON.parse(Pu),Iu,Lu.relative==="path");Au==null&&lo!=="/"&&(Bu.pathname=Bu.pathname==="/"?lo:joinPaths([lo,Bu.pathname])),validateNavigationTarget(typeof Du=="string"?Du:createPath(Du),$u.createHref(Bu),getNavigatorCurrentUrl($u),"reject"),(Lu.replace?$u.replace:$u.push)(Bu,Lu.state,Lu)},[lo,$u,Pu,Iu,Au])}reactExports.createContext(null);function useResolvedPath(Au,{relative:lo}={}){let{matches:$u}=reactExports.useContext(RouteContext),{pathname:Ru}=useLocation$1(),Iu=JSON.stringify(getResolveToMatches($u));return reactExports.useMemo(()=>resolveTo(Au,JSON.parse(Iu),Ru,lo==="path"),[Au,Iu,Ru,lo])}function useRoutesImpl(Au,lo,$u){invariant(useInRouterContext(),"useRoutes() may be used only in the context of a <Router> component.");let{navigator:Ru}=reactExports.useContext(NavigationContext),{matches:Iu}=reactExports.useContext(RouteContext),Pu=Iu[Iu.length-1],Ou=Pu?Pu.params:{},Mu=Pu?Pu.pathname:"/",Du=Pu?Pu.pathnameBase:"/",Lu=Pu&&Pu.route;{let Vu=Lu&&Lu.path||"";warningOnce(Mu,!Lu||Vu.endsWith("*")||Vu.endsWith("*?"),`You rendered descendant <Routes> (or called \`useRoutes()\`) at "${Mu}" (under <Route path="${Vu}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.
2093
2093
 
2094
- Please change the parent <Route path="${Vu}"> to <Route path="${Vu==="/"?"*":`${Vu}/*`}">.`)}let Bu=useLocation$1(),ju;ju=Bu;let Fu=ju.pathname||"/",zu=Fu;if(Du!=="/"){let Vu=Du.replace(/^\//,"").split("/");zu="/"+Fu.replace(/^\//,"").split("/").slice(Vu.length).join("/")}let Uu=$u&&$u.state.matches.length?$u.state.matches.map(Vu=>Object.assign(Vu,{route:$u.manifest[Vu.route.id]||Vu.route})):matchRoutes(Au,{pathname:zu});return warning(Lu||Uu!=null,`No routes matched location "${ju.pathname}${ju.search}${ju.hash}" `),warning(Uu==null||Uu[Uu.length-1].route.element!==void 0||Uu[Uu.length-1].route.Component!==void 0||Uu[Uu.length-1].route.lazy!==void 0,`Matched leaf route at location "${ju.pathname}${ju.search}${ju.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`),_renderMatches(Uu&&Uu.map(Vu=>Object.assign({},Vu,{params:Object.assign({},Ou,Vu.params),pathname:joinPaths([Du,Ru.encodeLocation?Ru.encodeLocation(Vu.pathname.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:Vu.pathname]),pathnameBase:Vu.pathnameBase==="/"?Du:joinPaths([Du,Ru.encodeLocation?Ru.encodeLocation(Vu.pathnameBase.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:Vu.pathnameBase])})),Iu,$u)}function DefaultErrorComponent(){let Au=useRouteError(),lo=isRouteErrorResponse(Au)?`${Au.status} ${Au.statusText}`:Au instanceof Error?Au.message:JSON.stringify(Au),$u=Au instanceof Error?Au.stack:null,Ru="rgba(200,200,200, 0.5)",Iu={padding:"0.5rem",backgroundColor:Ru},Pu={padding:"2px 4px",backgroundColor:Ru},Ou=null;return console.error("Error handled by React Router default ErrorBoundary:",Au),Ou=reactExports.createElement(reactExports.Fragment,null,reactExports.createElement("p",null,"💿 Hey developer 👋"),reactExports.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",reactExports.createElement("code",{style:Pu},"ErrorBoundary")," or"," ",reactExports.createElement("code",{style:Pu},"errorElement")," prop on your route.")),reactExports.createElement(reactExports.Fragment,null,reactExports.createElement("h2",null,"Unexpected Application Error!"),reactExports.createElement("h3",{style:{fontStyle:"italic"}},lo),$u?reactExports.createElement("pre",{style:Iu},$u):null,Ou)}var defaultErrorElement=reactExports.createElement(DefaultErrorComponent,null),RenderErrorBoundary=class extends reactExports.Component{constructor(Au){super(Au),this.state={location:Au.location,revalidation:Au.revalidation,error:Au.error}}static getDerivedStateFromError(Au){return{error:Au}}static getDerivedStateFromProps(Au,lo){return lo.location!==Au.location||lo.revalidation!=="idle"&&Au.revalidation==="idle"?{error:Au.error,location:Au.location,revalidation:Au.revalidation}:{error:Au.error!==void 0?Au.error:lo.error,location:lo.location,revalidation:Au.revalidation||lo.revalidation}}componentDidCatch(Au,lo){this.props.onError?this.props.onError(Au,lo):console.error("React Router caught the following error during render",Au)}render(){let Au=this.state.error;if(this.context&&typeof Au=="object"&&Au&&"digest"in Au&&typeof Au.digest=="string"){const $u=decodeRouteErrorResponseDigest(Au.digest);$u&&(Au=$u)}let lo=Au!==void 0?reactExports.createElement(RouteContext.Provider,{value:this.props.routeContext},reactExports.createElement(RouteErrorContext.Provider,{value:Au,children:this.props.component})):this.props.children;return this.context?reactExports.createElement(RSCErrorHandler,{error:Au},lo):lo}};RenderErrorBoundary.contextType=RSCRouterContext;var errorRedirectHandledMap=new WeakMap;function RSCErrorHandler({children:Au,error:lo}){let{basename:$u,navigator:Ru}=reactExports.useContext(NavigationContext);if(typeof lo=="object"&&lo&&"digest"in lo&&typeof lo.digest=="string"){let Iu=decodeRedirectErrorDigest(lo.digest);if(Iu){let Pu=errorRedirectHandledMap.get(lo);if(Pu)throw Pu;let Ou=parseToInfo(Iu.location,$u),Mu=Ou.absoluteURL||Ou.to;if(validateNavigationTarget(Iu.location,Mu,getNavigatorCurrentUrl(Ru),"allow-explicit"),hasInvalidProtocol(Mu))throw new Error("Invalid redirect location");if(isBrowser&&!errorRedirectHandledMap.get(lo))if(Ou.isExternal||Iu.reloadDocument)window.location.href=Mu;else{const Du=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(Ou.to,{replace:Iu.replace}));throw errorRedirectHandledMap.set(lo,Du),Du}return reactExports.createElement("meta",{httpEquiv:"refresh",content:`0;url=${Mu}`})}}return Au}function RenderedRoute({routeContext:Au,match:lo,children:$u}){let Ru=reactExports.useContext(DataRouterContext);return Ru&&Ru.static&&Ru.staticContext&&(lo.route.errorElement||lo.route.ErrorBoundary)&&(Ru.staticContext._deepestRenderedBoundaryId=lo.route.id),reactExports.createElement(RouteContext.Provider,{value:Au},$u)}function _renderMatches(Au,lo=[],$u){let Ru=$u?.state;if(Au==null){if(!Ru)return null;if(Ru.errors)Au=Ru.matches;else if(lo.length===0&&!Ru.initialized&&Ru.matches.length>0)Au=Ru.matches;else return null}let Iu=Au,Pu=Ru?.errors;if(Pu!=null){let Bu=Iu.findIndex(ju=>ju.route.id&&Pu?.[ju.route.id]!==void 0);invariant(Bu>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(Pu).join(",")}`),Iu=Iu.slice(0,Math.min(Iu.length,Bu+1))}let Ou=!1,Mu=-1;if($u&&Ru){Ou=Ru.renderFallback;for(let Bu=0;Bu<Iu.length;Bu++){let ju=Iu[Bu];if((ju.route.HydrateFallback||ju.route.hydrateFallbackElement)&&(Mu=Bu),ju.route.id){let{loaderData:Fu,errors:zu}=Ru,Uu=ju.route.loader&&!Fu.hasOwnProperty(ju.route.id)&&(!zu||zu[ju.route.id]===void 0);if(ju.route.lazy||Uu){$u.isStatic&&(Ou=!0),Mu>=0?Iu=Iu.slice(0,Mu+1):Iu=[Iu[0]];break}}}}let Du=$u?.onError,Lu=Ru&&Du?(Bu,ju)=>{Du(Bu,{location:Ru.location,params:Ru.matches?.[0]?.params??{},pattern:getRoutePattern(Ru.matches),errorInfo:ju})}:void 0;return Iu.reduceRight((Bu,ju,Fu)=>{let zu,Uu=!1,Hu=null,Vu=null;Ru&&(zu=Pu&&ju.route.id?Pu[ju.route.id]:void 0,Hu=ju.route.errorElement||defaultErrorElement,Ou&&(Mu<0&&Fu===0?(warningOnce("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),Uu=!0,Vu=null):Mu===Fu&&(Uu=!0,Vu=ju.route.hydrateFallbackElement||null)));let Gu=lo.concat(Iu.slice(0,Fu+1)),Wu=()=>{let Ku;return zu?Ku=Hu:Uu?Ku=Vu:ju.route.Component?Ku=reactExports.createElement(ju.route.Component,null):ju.route.element?Ku=ju.route.element:Ku=Bu,reactExports.createElement(RenderedRoute,{match:ju,routeContext:{outlet:Bu,matches:Gu,isDataRoute:Ru!=null},children:Ku})};return Ru&&(ju.route.ErrorBoundary||ju.route.errorElement||Fu===0)?reactExports.createElement(RenderErrorBoundary,{location:Ru.location,revalidation:Ru.revalidation,component:Hu,error:zu,children:Wu(),routeContext:{outlet:null,matches:Gu,isDataRoute:!0},onError:Lu}):Wu()},null)}function getDataRouterConsoleError(Au){return`${Au} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function useDataRouterContext(Au){let lo=reactExports.useContext(DataRouterContext);return invariant(lo,getDataRouterConsoleError(Au)),lo}function useDataRouterState(Au){let lo=reactExports.useContext(DataRouterStateContext);return invariant(lo,getDataRouterConsoleError(Au)),lo}function useRouteContext(Au){let lo=reactExports.useContext(RouteContext);return invariant(lo,getDataRouterConsoleError(Au)),lo}function useCurrentRouteId(Au){let lo=useRouteContext(Au),$u=lo.matches[lo.matches.length-1];return invariant($u.route.id,`${Au} can only be used on routes that contain a unique "id"`),$u.route.id}function useRouteId(){return useCurrentRouteId("useRouteId")}function useRouteError(){let Au=reactExports.useContext(RouteErrorContext),lo=useDataRouterState("useRouteError"),$u=useCurrentRouteId("useRouteError");return Au!==void 0?Au:lo.errors?.[$u]}function useNavigateStable(){let{router:Au}=useDataRouterContext("useNavigate"),lo=useCurrentRouteId("useNavigate"),$u=reactExports.useRef(!1);return useIsomorphicLayoutEffect(()=>{$u.current=!0}),reactExports.useCallback(async(Iu,Pu={})=>{warning($u.current,navigateEffectWarning),$u.current&&(typeof Iu=="number"?await Au.navigate(Iu):await Au.navigate(Iu,{fromRouteId:lo,...Pu}))},[Au,lo])}var alreadyWarned={};function warningOnce(Au,lo,$u){!lo&&!alreadyWarned[Au]&&(alreadyWarned[Au]=!0,warning(!1,$u))}reactExports.memo(DataRoutes2);function DataRoutes2({routes:Au,manifest:lo,future:$u,state:Ru,isStatic:Iu,onError:Pu}){return useRoutesImpl(Au,void 0,{manifest:lo,state:Ru,isStatic:Iu,onError:Pu})}var defaultMethod="get",defaultEncType="application/x-www-form-urlencoded";function isHtmlElement(Au){return typeof HTMLElement<"u"&&Au instanceof HTMLElement}function isButtonElement(Au){return isHtmlElement(Au)&&Au.tagName.toLowerCase()==="button"}function isFormElement(Au){return isHtmlElement(Au)&&Au.tagName.toLowerCase()==="form"}function isInputElement(Au){return isHtmlElement(Au)&&Au.tagName.toLowerCase()==="input"}function isModifiedEvent(Au){return!!(Au.metaKey||Au.altKey||Au.ctrlKey||Au.shiftKey)}function shouldProcessLinkClick(Au,lo){return Au.button===0&&(!lo||lo==="_self")&&!isModifiedEvent(Au)}var _formDataSupportsSubmitter=null;function isFormDataSubmitterSupported(){if(_formDataSupportsSubmitter===null)try{new FormData(document.createElement("form"),0),_formDataSupportsSubmitter=!1}catch{_formDataSupportsSubmitter=!0}return _formDataSupportsSubmitter}var supportedFormEncTypes=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function getFormEncType(Au){return Au!=null&&!supportedFormEncTypes.has(Au)?(warning(!1,`"${Au}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${defaultEncType}"`),null):Au}function getFormSubmissionInfo(Au,lo){let $u,Ru,Iu,Pu,Ou;if(isFormElement(Au)){let Mu=Au.getAttribute("action");Ru=Mu?stripBasename(Mu,lo):null,$u=Au.getAttribute("method")||defaultMethod,Iu=getFormEncType(Au.getAttribute("enctype"))||defaultEncType,Pu=new FormData(Au)}else if(isButtonElement(Au)||isInputElement(Au)&&(Au.type==="submit"||Au.type==="image")){let Mu=Au.form;if(Mu==null)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let Du=Au.getAttribute("formaction")||Mu.getAttribute("action");if(Ru=Du?stripBasename(Du,lo):null,$u=Au.getAttribute("formmethod")||Mu.getAttribute("method")||defaultMethod,Iu=getFormEncType(Au.getAttribute("formenctype"))||getFormEncType(Mu.getAttribute("enctype"))||defaultEncType,Pu=new FormData(Mu,Au),!isFormDataSubmitterSupported()){let{name:Lu,type:Bu,value:ju}=Au;if(Bu==="image"){let Fu=Lu?`${Lu}.`:"";Pu.append(`${Fu}x`,"0"),Pu.append(`${Fu}y`,"0")}else Lu&&Pu.append(Lu,ju)}}else{if(isHtmlElement(Au))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');$u=defaultMethod,Ru=null,Iu=defaultEncType,Ou=Au}return Pu&&Iu==="text/plain"&&(Ou=Pu,Pu=void 0),{action:Ru,method:$u.toLowerCase(),encType:Iu,formData:Pu,body:Ou}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");function invariant2(Au,lo){if(Au===!1||Au===null||typeof Au>"u")throw new Error(lo)}function singleFetchUrl(Au,lo,$u,Ru){let Iu=typeof Au=="string"?new URL(Au,typeof window>"u"?"server://singlefetch/":window.location.origin):Au;return $u?Iu.pathname.endsWith("/")?Iu.pathname=`${Iu.pathname}_.${Ru}`:Iu.pathname=`${Iu.pathname}.${Ru}`:Iu.pathname==="/"?Iu.pathname=`_root.${Ru}`:lo&&stripBasename(Iu.pathname,lo)==="/"?Iu.pathname=`${removeTrailingSlash(lo)}/_root.${Ru}`:Iu.pathname=`${removeTrailingSlash(Iu.pathname)}.${Ru}`,Iu}async function loadRouteModule(Au,lo){if(Au.id in lo)return lo[Au.id];try{let $u=await import(Au.module);return lo[Au.id]=$u,$u}catch($u){return console.error(`Error loading route module \`${Au.module}\`, reloading page...`),console.error($u),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function isHtmlLinkDescriptor(Au){return Au==null?!1:Au.href==null?Au.rel==="preload"&&typeof Au.imageSrcSet=="string"&&typeof Au.imageSizes=="string":typeof Au.rel=="string"&&typeof Au.href=="string"}async function getKeyedPrefetchLinks(Au,lo,$u){let Ru=await Promise.all(Au.map(async Iu=>{let Pu=lo.routes[Iu.route.id];if(Pu){let Ou=await loadRouteModule(Pu,$u);return Ou.links?Ou.links():[]}return[]}));return dedupeLinkDescriptors(Ru.flat(1).filter(isHtmlLinkDescriptor).filter(Iu=>Iu.rel==="stylesheet"||Iu.rel==="preload").map(Iu=>Iu.rel==="stylesheet"?{...Iu,rel:"prefetch",as:"style"}:{...Iu,rel:"prefetch"}))}function getNewMatchesForLinks(Au,lo,$u,Ru,Iu,Pu){let Ou=(Du,Lu)=>$u[Lu]?Du.route.id!==$u[Lu].route.id:!0,Mu=(Du,Lu)=>$u[Lu].pathname!==Du.pathname||$u[Lu].route.path?.endsWith("*")&&$u[Lu].params["*"]!==Du.params["*"];return Pu==="assets"?lo.filter((Du,Lu)=>Ou(Du,Lu)||Mu(Du,Lu)):Pu==="data"?lo.filter((Du,Lu)=>{let Bu=Ru.routes[Du.route.id];if(!Bu||!Bu.hasLoader)return!1;if(Ou(Du,Lu)||Mu(Du,Lu))return!0;if(Du.route.shouldRevalidate){let ju=Du.route.shouldRevalidate({currentUrl:new URL(Iu.pathname+Iu.search+Iu.hash,window.origin),currentParams:$u[0]?.params||{},nextUrl:new URL(Au,window.origin),nextParams:Du.params,defaultShouldRevalidate:!0});if(typeof ju=="boolean")return ju}return!0}):[]}function getModuleLinkHrefs(Au,lo,{includeHydrateFallback:$u}={}){return dedupeHrefs(Au.map(Ru=>{let Iu=lo.routes[Ru.route.id];if(!Iu)return[];let Pu=[Iu.module];return Iu.clientActionModule&&(Pu=Pu.concat(Iu.clientActionModule)),Iu.clientLoaderModule&&(Pu=Pu.concat(Iu.clientLoaderModule)),$u&&Iu.hydrateFallbackModule&&(Pu=Pu.concat(Iu.hydrateFallbackModule)),Iu.imports&&(Pu=Pu.concat(Iu.imports)),Pu}).flat(1))}function dedupeHrefs(Au){return[...new Set(Au)]}function sortKeys(Au){let lo={},$u=Object.keys(Au).sort();for(let Ru of $u)lo[Ru]=Au[Ru];return lo}function dedupeLinkDescriptors(Au,lo){let $u=new Set;return new Set(lo),Au.reduce((Ru,Iu)=>{let Pu=JSON.stringify(sortKeys(Iu));return $u.has(Pu)||($u.add(Pu),Ru.push({key:Pu,link:Iu})),Ru},[])}function useDataRouterContext2(){let Au=reactExports.useContext(DataRouterContext);return invariant2(Au,"You must render this element inside a <DataRouterContext.Provider> element"),Au}function useDataRouterStateContext(){let Au=reactExports.useContext(DataRouterStateContext);return invariant2(Au,"You must render this element inside a <DataRouterStateContext.Provider> element"),Au}var FrameworkContext=reactExports.createContext(void 0);FrameworkContext.displayName="FrameworkContext";function useFrameworkContext(){let Au=reactExports.useContext(FrameworkContext);return invariant2(Au,"You must render this element inside a <HydratedRouter> element"),Au}function usePrefetchBehavior(Au,lo){let $u=reactExports.useContext(FrameworkContext),[Ru,Iu]=reactExports.useState(!1),[Pu,Ou]=reactExports.useState(!1),{onFocus:Mu,onBlur:Du,onMouseEnter:Lu,onMouseLeave:Bu,onTouchStart:ju}=lo,Fu=reactExports.useRef(null);reactExports.useEffect(()=>{if(Au==="render"&&Ou(!0),Au==="viewport"){let Hu=Gu=>{Gu.forEach(Wu=>{Ou(Wu.isIntersecting)})},Vu=new IntersectionObserver(Hu,{threshold:.5});return Fu.current&&Vu.observe(Fu.current),()=>{Vu.disconnect()}}},[Au]),reactExports.useEffect(()=>{if(Ru){let Hu=setTimeout(()=>{Ou(!0)},100);return()=>{clearTimeout(Hu)}}},[Ru]);let zu=()=>{Iu(!0)},Uu=()=>{Iu(!1),Ou(!1)};return $u?Au!=="intent"?[Pu,Fu,{}]:[Pu,Fu,{onFocus:composeEventHandlers(Mu,zu),onBlur:composeEventHandlers(Du,Uu),onMouseEnter:composeEventHandlers(Lu,zu),onMouseLeave:composeEventHandlers(Bu,Uu),onTouchStart:composeEventHandlers(ju,zu)}]:[!1,Fu,{}]}function composeEventHandlers(Au,lo){return $u=>{Au&&Au($u),$u.defaultPrevented||lo($u)}}function PrefetchPageLinks({page:Au,...lo}){let $u=useIsRSCRouterContext(),{nonce:Ru}=useFrameworkContext(),{router:Iu}=useDataRouterContext2(),Pu=reactExports.useMemo(()=>matchRoutes(Iu.routes,Au,Iu.basename),[Iu.routes,Au,Iu.basename]);return Pu?(lo.nonce==null&&Ru&&(lo={...lo,nonce:Ru}),$u?reactExports.createElement(RSCPrefetchPageLinksImpl,{page:Au,matches:Pu,...lo}):reactExports.createElement(PrefetchPageLinksImpl,{page:Au,matches:Pu,...lo})):null}function useKeyedPrefetchLinks(Au){let{manifest:lo,routeModules:$u}=useFrameworkContext(),[Ru,Iu]=reactExports.useState([]);return reactExports.useEffect(()=>{let Pu=!1;return getKeyedPrefetchLinks(Au,lo,$u).then(Ou=>{Pu||Iu(Ou)}),()=>{Pu=!0}},[Au,lo,$u]),Ru}function RSCPrefetchPageLinksImpl({page:Au,matches:lo,...$u}){let Ru=useLocation$1(),{future:Iu}=useFrameworkContext(),{basename:Pu}=useDataRouterContext2(),Ou=reactExports.useMemo(()=>{if(Au===Ru.pathname+Ru.search+Ru.hash)return[];let Mu=singleFetchUrl(Au,Pu,Iu.v8_trailingSlashAwareDataRequests,"rsc"),Du=!1,Lu=[];for(let Bu of lo)typeof Bu.route.shouldRevalidate=="function"?Du=!0:Lu.push(Bu.route.id);return Du&&Lu.length>0&&Mu.searchParams.set("_routes",Lu.join(",")),[Mu.pathname+Mu.search]},[Pu,Iu.v8_trailingSlashAwareDataRequests,Au,Ru,lo]);return reactExports.createElement(reactExports.Fragment,null,Ou.map(Mu=>reactExports.createElement("link",{key:Mu,rel:"prefetch",as:"fetch",href:Mu,...$u})))}function PrefetchPageLinksImpl({page:Au,matches:lo,...$u}){let Ru=useLocation$1(),{future:Iu,manifest:Pu,routeModules:Ou}=useFrameworkContext(),{basename:Mu}=useDataRouterContext2(),{loaderData:Du,matches:Lu}=useDataRouterStateContext(),Bu=reactExports.useMemo(()=>getNewMatchesForLinks(Au,lo,Lu,Pu,Ru,"data"),[Au,lo,Lu,Pu,Ru]),ju=reactExports.useMemo(()=>getNewMatchesForLinks(Au,lo,Lu,Pu,Ru,"assets"),[Au,lo,Lu,Pu,Ru]),Fu=reactExports.useMemo(()=>{if(Au===Ru.pathname+Ru.search+Ru.hash)return[];let Hu=new Set,Vu=!1;if(lo.forEach(Wu=>{let Ku=Pu.routes[Wu.route.id];!Ku||!Ku.hasLoader||(!Bu.some(Ju=>Ju.route.id===Wu.route.id)&&Wu.route.id in Du&&Ou[Wu.route.id]?.shouldRevalidate||Ku.hasClientLoader?Vu=!0:Hu.add(Wu.route.id))}),Hu.size===0)return[];let Gu=singleFetchUrl(Au,Mu,Iu.v8_trailingSlashAwareDataRequests,"data");return Vu&&Hu.size>0&&Gu.searchParams.set("_routes",lo.filter(Wu=>Hu.has(Wu.route.id)).map(Wu=>Wu.route.id).join(",")),[Gu.pathname+Gu.search]},[Mu,Iu.v8_trailingSlashAwareDataRequests,Du,Ru,Pu,Bu,lo,Au,Ou]),zu=reactExports.useMemo(()=>getModuleLinkHrefs(ju,Pu),[ju,Pu]),Uu=useKeyedPrefetchLinks(ju);return reactExports.createElement(reactExports.Fragment,null,Fu.map(Hu=>reactExports.createElement("link",{key:Hu,rel:"prefetch",as:"fetch",href:Hu,...$u})),zu.map(Hu=>reactExports.createElement("link",{key:Hu,rel:"modulepreload",href:Hu,...$u})),Uu.map(({key:Hu,link:Vu})=>reactExports.createElement("link",{key:Hu,nonce:$u.nonce,...Vu,crossOrigin:Vu.crossOrigin??$u.crossOrigin})))}function mergeRefs(...Au){return lo=>{Au.forEach($u=>{typeof $u=="function"?$u(lo):$u!=null&&($u.current=lo)})}}var isBrowser2=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{isBrowser2&&(window.__reactRouterVersion="7.18.3")}catch(Au){}var Link=reactExports.forwardRef(function Au({onClick:lo,discover:$u="render",prefetch:Ru="none",relative:Iu,reloadDocument:Pu,replace:Ou,mask:Mu,state:Du,target:Lu,to:Bu,preventScrollReset:ju,viewTransition:Fu,defaultShouldRevalidate:zu,...Uu},Hu){let{basename:Vu,navigator:Gu,useTransitions:Wu}=reactExports.useContext(NavigationContext),Ku=typeof Bu=="string"&&ABSOLUTE_URL_REGEX.test(Bu),Ju=parseToInfo(Bu,Vu);Bu=Ju.to;let Yu=useHref(Bu,{relative:Iu}),Xu=useLocation$1(),ed=null;if(Mu){let xd=resolveTo(Mu,[],Xu.mask?Xu.mask.pathname:"/",!0);Vu!=="/"&&(xd.pathname=xd.pathname==="/"?Vu:joinPaths([Vu,xd.pathname])),ed=Gu.createHref(xd)}let[td,nd,od]=usePrefetchBehavior(Ru,Uu),sd=useLinkClickHandler(Bu,{replace:Ou,mask:Mu,state:Du,target:Lu,preventScrollReset:ju,relative:Iu,viewTransition:Fu,defaultShouldRevalidate:zu,useTransitions:Wu});function ad(xd){lo&&lo(xd),xd.defaultPrevented||sd(xd)}let pd=!(Ju.isExternal||Pu),gd=reactExports.createElement("a",{...Uu,...od,href:(pd?ed:void 0)||Ju.absoluteURL||Yu,onClick:pd?ad:lo,ref:mergeRefs(Hu,nd),target:Lu,"data-discover":!Ku&&$u==="render"?"true":void 0});return td&&!Ku?reactExports.createElement(reactExports.Fragment,null,gd,reactExports.createElement(PrefetchPageLinks,{page:Yu})):gd});Link.displayName="Link";var NavLink=reactExports.forwardRef(function Au({"aria-current":lo="page",caseSensitive:$u=!1,className:Ru="",end:Iu=!1,style:Pu,to:Ou,viewTransition:Mu,children:Du,...Lu},Bu){let ju=useResolvedPath(Ou,{relative:Lu.relative}),Fu=useLocation$1(),zu=reactExports.useContext(DataRouterStateContext),{navigator:Uu,basename:Hu}=reactExports.useContext(NavigationContext),Vu=zu!=null&&useViewTransitionState(ju)&&Mu===!0,Gu=Uu.encodeLocation?Uu.encodeLocation(ju).pathname:ju.pathname,Wu=Fu.pathname,Ku=zu&&zu.navigation&&zu.navigation.location?zu.navigation.location.pathname:null;$u||(Wu=Wu.toLowerCase(),Ku=Ku?Ku.toLowerCase():null,Gu=Gu.toLowerCase()),Ku&&Hu&&(Ku=stripBasename(Ku,Hu)||Ku);const Ju=Gu!=="/"&&Gu.endsWith("/")?Gu.length-1:Gu.length;let Yu=Wu===Gu||!Iu&&Wu.startsWith(Gu)&&Wu.charAt(Ju)==="/",Xu=Ku!=null&&(Ku===Gu||!Iu&&Ku.startsWith(Gu)&&Ku.charAt(Gu.length)==="/"),ed={isActive:Yu,isPending:Xu,isTransitioning:Vu},td=Yu?lo:void 0,nd;typeof Ru=="function"?nd=Ru(ed):nd=[Ru,Yu?"active":null,Xu?"pending":null,Vu?"transitioning":null].filter(Boolean).join(" ");let od=typeof Pu=="function"?Pu(ed):Pu;return reactExports.createElement(Link,{...Lu,"aria-current":td,className:nd,ref:Bu,style:od,to:Ou,viewTransition:Mu},typeof Du=="function"?Du(ed):Du)});NavLink.displayName="NavLink";var Form$1=reactExports.forwardRef(({discover:Au="render",fetcherKey:lo,navigate:$u,reloadDocument:Ru,replace:Iu,state:Pu,method:Ou=defaultMethod,action:Mu,onSubmit:Du,relative:Lu,preventScrollReset:Bu,viewTransition:ju,defaultShouldRevalidate:Fu,...zu},Uu)=>{let{useTransitions:Hu}=reactExports.useContext(NavigationContext),Vu=useSubmit(),Gu=useFormAction(Mu,{relative:Lu}),Wu=Ou.toLowerCase()==="get"?"get":"post",Ku=typeof Mu=="string"&&ABSOLUTE_URL_REGEX.test(Mu),Ju=Yu=>{if(Du&&Du(Yu),Yu.defaultPrevented)return;Yu.preventDefault();let Xu=Yu.nativeEvent.submitter,ed=Xu?.getAttribute("formmethod")||Ou,td=()=>Vu(Xu||Yu.currentTarget,{fetcherKey:lo,method:ed,navigate:$u,replace:Iu,state:Pu,relative:Lu,preventScrollReset:Bu,viewTransition:ju,defaultShouldRevalidate:Fu});Hu&&$u!==!1?reactExports.startTransition(()=>td()):td()};return reactExports.createElement("form",{ref:Uu,method:Wu,action:Gu,onSubmit:Ru?Du:Ju,...zu,"data-discover":!Ku&&Au==="render"?"true":void 0})});Form$1.displayName="Form";function getDataRouterConsoleError2(Au){return`${Au} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function useDataRouterContext3(Au){let lo=reactExports.useContext(DataRouterContext);return invariant(lo,getDataRouterConsoleError2(Au)),lo}function useLinkClickHandler(Au,{target:lo,replace:$u,mask:Ru,state:Iu,preventScrollReset:Pu,relative:Ou,viewTransition:Mu,defaultShouldRevalidate:Du,useTransitions:Lu}={}){let Bu=useNavigate$1(),ju=useLocation$1(),Fu=useResolvedPath(Au,{relative:Ou});return reactExports.useCallback(zu=>{if(shouldProcessLinkClick(zu,lo)){zu.preventDefault();let Uu=$u!==void 0?$u:createPath(ju)===createPath(Fu),Hu=()=>Bu(Au,{replace:Uu,mask:Ru,state:Iu,preventScrollReset:Pu,relative:Ou,viewTransition:Mu,defaultShouldRevalidate:Du});Lu?reactExports.startTransition(()=>Hu()):Hu()}},[ju,Bu,Fu,$u,Ru,Iu,lo,Au,Pu,Ou,Mu,Du,Lu])}var fetcherId=0,getUniqueFetcherId=()=>`__${String(++fetcherId)}__`;function useSubmit(){let{router:Au}=useDataRouterContext3("useSubmit"),{basename:lo}=reactExports.useContext(NavigationContext),$u=useRouteId(),Ru=Au.fetch,Iu=Au.navigate;return reactExports.useCallback(async(Pu,Ou={})=>{let{action:Mu,method:Du,encType:Lu,formData:Bu,body:ju}=getFormSubmissionInfo(Pu,lo);if(Ou.navigate===!1){let Fu=Ou.fetcherKey||getUniqueFetcherId();await Ru(Fu,$u,Ou.action||Mu,{defaultShouldRevalidate:Ou.defaultShouldRevalidate,preventScrollReset:Ou.preventScrollReset,formData:Bu,body:ju,formMethod:Ou.method||Du,formEncType:Ou.encType||Lu,flushSync:Ou.flushSync})}else await Iu(Ou.action||Mu,{defaultShouldRevalidate:Ou.defaultShouldRevalidate,preventScrollReset:Ou.preventScrollReset,formData:Bu,body:ju,formMethod:Ou.method||Du,formEncType:Ou.encType||Lu,replace:Ou.replace,state:Ou.state,fromRouteId:$u,flushSync:Ou.flushSync,viewTransition:Ou.viewTransition})},[Ru,Iu,lo,$u])}function useFormAction(Au,{relative:lo}={}){let{basename:$u}=reactExports.useContext(NavigationContext),Ru=reactExports.useContext(RouteContext);invariant(Ru,"useFormAction must be used inside a RouteContext");let[Iu]=Ru.matches.slice(-1),Pu={...useResolvedPath(Au||".",{relative:lo})},Ou=useLocation$1();if(Au==null){Pu.search=Ou.search;let Mu=new URLSearchParams(Pu.search),Du=Mu.getAll("index");if(Du.some(Bu=>Bu==="")){Mu.delete("index"),Du.filter(ju=>ju).forEach(ju=>Mu.append("index",ju));let Bu=Mu.toString();Pu.search=Bu?`?${Bu}`:""}}return(!Au||Au===".")&&Iu.route.index&&(Pu.search=Pu.search?Pu.search.replace(/^\?/,"?index&"):"?index"),$u!=="/"&&(Pu.pathname=Pu.pathname==="/"?$u:joinPaths([$u,Pu.pathname])),createPath(Pu)}function useViewTransitionState(Au,{relative:lo}={}){let $u=reactExports.useContext(ViewTransitionContext);invariant($u!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:Ru}=useDataRouterContext3("useViewTransitionState"),Iu=useResolvedPath(Au,{relative:lo});if(!$u.isTransitioning)return!1;let Pu=stripBasename($u.currentLocation.pathname,Ru)||$u.currentLocation.pathname,Ou=stripBasename($u.nextLocation.pathname,Ru)||$u.nextLocation.pathname;return matchPath(Iu.pathname,Ou)!=null||matchPath(Iu.pathname,Pu)!=null}const useLocationRR=useLocation$1,useNavigateRR=useNavigate$1,useLocation=()=>{const[Au,lo]=reactExports.useState(()=>typeof window>"u"?{pathname:"/",search:"",hash:"",state:null,key:"default"}:{pathname:window.location.pathname,search:window.location.search,hash:window.location.hash,state:window.history.state,key:"default"}),$u=typeof window<"u"&&!!window.__NEXT_DATA__,Ru=typeof window<"u";let Iu=null,Pu=!1;try{!$u&&useLocationRR&&Ru&&(Iu=useLocationRR(),Pu=!!Iu)}catch{}return reactExports.useEffect(()=>{if(Pu)return;const Ou=()=>{lo({pathname:window.location.pathname,search:window.location.search,hash:window.location.hash,state:window.history.state,key:"native-"+Date.now()})};return window.addEventListener("popstate",Ou),window.addEventListener("pushstate",Ou),window.addEventListener("replacestate",Ou),()=>{window.removeEventListener("popstate",Ou),window.removeEventListener("pushstate",Ou),window.removeEventListener("replacestate",Ou)}},[Pu]),Pu&&Iu?Iu:Au},NAVIGATION_VIEW_HOMES={studio:"/studio",home:"/power",agentify:"/agentify",admin:"/admin",apps:"/apps/apps"},LIBRARY_VIEW="library",AGENTS_VIEW="agents",SETTINGS_VIEW="settings",DATALAYER_VIEW="datalayer",CONTENTS_VIEW="contents",TUTOR_VIEW="tutor",STORAGE_KEY="datalayer-navigation",SHELL_COOKIE="datalayer-signed-in-view",FORMER_TABS_KEY="datalayer_view_tabs",COOKIE_MAX_AGE_DAYS=365,isView=Au=>Au==="studio"||Au==="home"||Au==="agentify"||Au==="admin"||Au==="apps";function readCookie(Au){if(typeof document>"u")return;const lo=document.cookie.split("; ").find($u=>$u.startsWith(`${Au}=`));return lo?decodeURIComponent(lo.slice(Au.length+1)):void 0}function writeCookie(Au,lo){if(typeof document>"u")return;const $u=COOKIE_MAX_AGE_DAYS*24*60*60;document.cookie=`${Au}=${encodeURIComponent(lo)}; path=/; max-age=${$u}; SameSite=Lax`}function readLocal(Au){try{return globalThis.localStorage?.getItem(Au)??null}catch{return null}}function restore(){let Au={};const lo=readLocal(STORAGE_KEY);if(lo)try{const Ru=JSON.parse(lo),Iu=Ru?.state??Ru;Au=Iu&&typeof Iu=="object"?Iu:{}}catch{Au={}}else{const Ru=readLocal(FORMER_TABS_KEY);if(Ru)try{const{state:Iu}=JSON.parse(Ru);Au={tabsByView:Iu?.tabsByView??{}}}catch{Au={}}}const $u=readCookie(SHELL_COOKIE);return isView($u)&&(Au.view=$u),Au.lastRouteByView=restoredRoutes(Au.lastRouteByView),Au}function restoredRoutes(Au){const lo={};if(!Au||typeof Au!="object")return lo;for(const[$u,Ru]of Object.entries(Au))isView($u)&&isRouteOfView(Ru,$u)&&(lo[$u]=Ru);return lo}function persist$1(Au){const lo={view:Au.view,lastRouteByView:Au.lastRouteByView,tabsByView:Au.tabsByView};try{globalThis.localStorage?.setItem(STORAGE_KEY,JSON.stringify(lo))}catch{}writeCookie(SHELL_COOKIE,Au.view)}function pathOf(Au){const lo=Au.search(/[?#]/);return lo===-1?Au:Au.slice(0,lo)}function isRememberableRoute(Au){if(!Au.startsWith("/"))return!1;const lo=pathOf(Au);return!["/signin","/signup","/login","/logout","/oauth2","/oauth","/join"].some($u=>lo===$u||lo.startsWith(`${$u}/`))&&!isShellNeutralRoute(Au)}function isShellNeutralRoute(Au){const lo=pathOf(Au);return["/settings","/docs","/decks"].some($u=>lo===$u||lo.startsWith(`${$u}/`))}function viewForRoute(Au,lo){const $u=pathOf(Au);return lo&&isShellNeutralRoute(Au)?lo:$u==="/"||$u==="/studio"||$u.startsWith("/studio/")||$u==="/settings"||$u.startsWith("/settings/")||$u==="/agentspecs"||$u.startsWith("/agentspecs/")?"studio":$u==="/agentify"||$u.startsWith("/agentify/")?"agentify":$u==="/admin"||$u.startsWith("/admin/")?"admin":$u==="/apps"||$u.startsWith("/apps/")?"apps":"home"}function isRouteOfView(Au,lo){return typeof Au=="string"&&isRememberableRoute(Au)&&viewForRoute(Au)===lo}const initial=restore(),navigationStore=createStore$1((Au,lo)=>({view:initial.view??"studio",lastRouteByView:initial.lastRouteByView??{},tabsByView:initial.tabsByView??{},requestedRoute:void 0,docsOrigin:void 0,setView:$u=>{Au({view:$u}),persist$1(lo())},toggleView:()=>{Au($u=>({view:$u.view==="home"?"agentify":"home"})),persist$1(lo())},rememberRoute:($u,Ru)=>{if(!isRememberableRoute($u))return;const Iu=Ru??viewForRoute($u),Pu=Ru===void 0,Ou=lo();Ou.lastRouteByView[Iu]===$u&&(!Pu||Ou.view===Iu)||(Au(Mu=>({view:Pu?Iu:Mu.view,lastRouteByView:{...Mu.lastRouteByView,[Iu]:$u}})),persist$1(lo()))},routeForView:$u=>{const Ru=lo().lastRouteByView[$u];return isRouteOfView(Ru,$u)?Ru:NAVIGATION_VIEW_HOMES[$u]},setViewTab:($u,Ru)=>{lo().tabsByView[$u]!==Ru&&(Au(Iu=>({tabsByView:{...Iu.tabsByView,[$u]:Ru}})),persist$1(lo()))},getViewTab:$u=>lo().tabsByView[$u],setRequestedRoute:$u=>Au({requestedRoute:$u}),clearRequestedRoute:()=>Au({requestedRoute:void 0}),setDocsOrigin:$u=>Au({docsOrigin:$u})}));registerSessionState({forget:()=>{navigationStore.setState({lastRouteByView:{},tabsByView:{},requestedRoute:void 0,docsOrigin:void 0}),persist$1(navigationStore.getState())},localStorageKeys:[FORMER_TABS_KEY]});function useNavigationState(Au){return useStore$1(navigationStore,Au??(lo=>lo))}const useNavigationStore=Object.assign(useNavigationState,{getState:navigationStore.getState,setState:navigationStore.setState,subscribe:navigationStore.subscribe}),navigationListeners=new Set,notifyNavigationChange=()=>{navigationListeners.forEach(Au=>Au())},createNativeNavigate=()=>(Au,lo)=>{if(typeof window>"u")return;const $u=new URL(Au,window.location.href),Ru=lo||{},Iu=Ru.state||null;Ru.replace?(window.history.replaceState(Iu,"",$u.href),window.dispatchEvent(new Event("replacestate"))):(window.history.pushState(Iu,"",$u.href),window.dispatchEvent(new Event("pushstate"))),notifyNavigationChange(),Ru.scroll!==!1&&window.scrollTo(0,0)};function isNewTabClick(Au){return!!Au.metaKey||!!Au.ctrlKey||!!Au.shiftKey||!!Au.altKey||Au.button===1}const resolveUrl$1=Au=>new URL(Au,window.location.href).href;function openInNewTab(Au){window.open(resolveUrl$1(Au),"_blank","noopener,noreferrer")}function isLinkTo(Au,lo){const $u=Au.currentTarget??Au.target,Ru=$u&&typeof $u.closest=="function"?$u.closest("a[href]"):null;if(!Ru)return!1;try{return resolveUrl$1(Ru.getAttribute("href")??"")===resolveUrl$1(lo)}catch{return!1}}const isEvent=Au=>!!Au&&typeof Au.preventDefault=="function";function parseCall(Au,lo,$u){if(isEvent(Au)){const Ru=typeof lo=="boolean"?{resetPortals:lo,...$u??{}}:{...lo??{},...$u??{}};return{event:Au,options:Ru}}return typeof Au=="boolean"?{options:{resetPortals:Au,...typeof lo=="object"?lo:{},...$u??{}}}:{options:{...Au??{}}}}const useNavigate=()=>{const Au=useLayoutStore(),lo=typeof window<"u"&&!!window.__NEXT_DATA__,$u=typeof window<"u";let Ru=null;if(!lo&&useNavigateRR&&$u)try{Ru=useNavigateRR()}catch{}const Iu=reactExports.useMemo(()=>createNativeNavigate(),[]);return reactExports.useCallback((Pu,Ou,Mu,Du)=>{if(typeof window>"u")return;const{event:Lu,options:Bu}=parseCall(Ou,Mu,Du);if(typeof Pu=="number"){Lu?.preventDefault(),Ru?Ru(Pu):window.history.go(Pu);return}if(Lu&&isNewTabClick(Lu)){isLinkTo(Lu,Pu)||(Lu.preventDefault(),openInNewTab(Pu));return}if(Bu.newTab){Lu?.preventDefault(),openInNewTab(Pu);return}if(Lu?.preventDefault(),Bu.scroll!==!1&&(window.scrollTo(0,0),document.body.scrollTop=0),navigationStore.getState().rememberRoute(Pu),Ru){Ru(Pu,{replace:Bu.replace,state:Bu.state});return}Bu.resetPortals!==!1&&(Au.resetLeftPortal(),Au.resetRightPortal()),Iu(Pu,{replace:Bu.replace,state:Bu.state,scroll:Bu.scroll})},[Ru,Iu,Au])};var propTypes$2={exports:{}},ReactPropTypesSecret_1,hasRequiredReactPropTypesSecret;function requireReactPropTypesSecret(){if(hasRequiredReactPropTypesSecret)return ReactPropTypesSecret_1;hasRequiredReactPropTypesSecret=1;var Au="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";return ReactPropTypesSecret_1=Au,ReactPropTypesSecret_1}var factoryWithThrowingShims,hasRequiredFactoryWithThrowingShims;function requireFactoryWithThrowingShims(){if(hasRequiredFactoryWithThrowingShims)return factoryWithThrowingShims;hasRequiredFactoryWithThrowingShims=1;var Au=requireReactPropTypesSecret();function lo(){}function $u(){}return $u.resetWarningCache=lo,factoryWithThrowingShims=function(){function Ru(Ou,Mu,Du,Lu,Bu,ju){if(ju!==Au){var Fu=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw Fu.name="Invariant Violation",Fu}}Ru.isRequired=Ru;function Iu(){return Ru}var Pu={array:Ru,bigint:Ru,bool:Ru,func:Ru,number:Ru,object:Ru,string:Ru,symbol:Ru,any:Ru,arrayOf:Iu,element:Ru,elementType:Ru,instanceOf:Iu,node:Ru,objectOf:Iu,oneOf:Iu,oneOfType:Iu,shape:Iu,exact:Iu,checkPropTypes:$u,resetWarningCache:lo};return Pu.PropTypes=Pu,Pu},factoryWithThrowingShims}var hasRequiredPropTypes;function requirePropTypes(){return hasRequiredPropTypes||(hasRequiredPropTypes=1,propTypes$2.exports=requireFactoryWithThrowingShims()()),propTypes$2.exports}var propTypesExports=requirePropTypes();const s$5=getDefaultExportFromCjs(propTypesExports);var L$4=Au=>typeof Au=="number"&&!isNaN(Au),N$3=Au=>typeof Au=="string",P$5=Au=>typeof Au=="function",ut$5=Au=>N$3(Au)||L$4(Au),F$4=Au=>reactExports.isValidElement(Au)||N$3(Au)||P$5(Au)||L$4(Au),Qt$3=1,st$5=()=>`${Qt$3++}`,I$3=new Map,U$5=[],rt$5=new Set,ht$4=()=>I$3.size>0,Ct$5=(Au,{containerId:lo})=>{var $u;return($u=I$3.get(lo||1))==null?void 0:$u.toasts.get(Au)};function X$5(Au,lo){var $u;if(lo)return!!(($u=I$3.get(lo))!=null&&$u.isToastActive(Au));let Ru=!1;return I$3.forEach(Iu=>{Iu.isToastActive(Au)&&(Ru=!0)}),Ru}function xt$4(Au){if(!ht$4()){U$5=U$5.filter(lo=>Au!=null&&lo.options.toastId!==Au);return}if(Au==null||ut$5(Au))I$3.forEach(lo=>{lo.removeToast(Au)});else if(Au&&("containerId"in Au||"id"in Au)){let lo=I$3.get(Au.containerId);lo?lo.removeToast(Au.id):I$3.forEach($u=>{$u.removeToast(Au.id)})}}var Et$4=(Au={})=>{I$3.forEach(lo=>{lo.props.limit&&(!Au.containerId||lo.id===Au.containerId)&&lo.clearQueue()})};function nt$5(Au,lo){F$4(Au)&&(ht$4()||U$5.push({content:Au,options:lo}),I$3.forEach($u=>{$u.buildToast(Au,lo)}))}function it$5(Au,lo){I$3.forEach($u=>{(lo==null||!(lo!=null&&lo.containerId)||lo?.containerId===$u.id)&&$u.toggle(Au,lo?.id)})}function St$4(Au){return rt$5.add(Au),()=>{rt$5.delete(Au)}}function qt$3(Au){return Au&&(N$3(Au.toastId)||L$4(Au.toastId))?Au.toastId:st$5()}function H$4(Au,lo){return nt$5(Au,lo),lo.toastId}function Q$4(Au,lo){return{...lo,type:lo&&lo.type||Au,toastId:qt$3(lo)}}function W$4(Au){return(lo,$u)=>H$4(lo,Q$4(Au,$u))}function y$6(Au,lo){return H$4(Au,Q$4("default",lo))}y$6.loading=(Au,lo)=>H$4(Au,Q$4("default",{isLoading:!0,autoClose:!1,closeOnClick:!1,closeButton:!1,draggable:!1,...lo}));function Kt$4(Au,{pending:lo,error:$u,success:Ru},Iu){let Pu;lo&&(Pu=N$3(lo)?y$6.loading(lo,Iu):y$6.loading(lo.render,{...Iu,...lo}));let Ou={isLoading:null,autoClose:null,closeOnClick:null,closeButton:null,draggable:null},Mu=(Lu,Bu,ju)=>{if(Bu==null){y$6.dismiss(Pu);return}let Fu={type:Lu,...Ou,...Iu,data:ju},zu=N$3(Bu)?{render:Bu}:Bu;return Pu?y$6.update(Pu,{...Fu,...zu}):y$6(zu.render,{...Fu,...zu}),ju},Du=P$5(Au)?Au():Au;return Du.then(Lu=>Mu("success",Ru,Lu)).catch(Lu=>Mu("error",$u,Lu)),Du}y$6.promise=Kt$4;y$6.success=W$4("success");y$6.info=W$4("info");y$6.error=W$4("error");y$6.warning=W$4("warning");y$6.warn=y$6.warning;y$6.dark=(Au,lo)=>H$4(Au,Q$4("default",{theme:"dark",...lo}));function Yt$3(Au){xt$4(Au)}y$6.dismiss=Yt$3;y$6.clearWaitingQueue=Et$4;y$6.isActive=X$5;y$6.update=(Au,lo={})=>{let $u=Ct$5(Au,lo);if($u){let{props:Ru,content:Iu}=$u,Pu={delay:100,...Ru,...lo,toastId:lo.toastId||Au,updateId:st$5()};Pu.toastId!==Au&&(Pu.staleId=Au);let Ou=Pu.render||Iu;delete Pu.render,H$4(Ou,Pu)}};y$6.done=Au=>{y$6.update(Au,{progress:1})};y$6.onChange=St$4;y$6.play=Au=>it$5(!0,Au);y$6.pause=Au=>it$5(!1,Au);const JupyterReactTheme=vM.lazy(()=>__vitePreload(()=>import("./chunks/index-CyQgE_Es.js").then(Au=>Au.r),[],import.meta.url).then(Au=>({default:Au.JupyterReactTheme})));let NotificationApi;isInsideJupyterLab()&&__vitePreload(()=>import("./chunks/index-CFP9psRB.js").then(Au=>Au.q),[],import.meta.url).then(Au=>{NotificationApi=Au.Notification});const TOAST_POSITION="bottom-right",THEME_STORAGE_KEY="datalayer-theme";function resolveToastTheme(){if(typeof window>"u")return"dark";let Au;try{const $u=window.localStorage.getItem(THEME_STORAGE_KEY);$u&&(Au=JSON.parse($u)?.state?.colorMode)}catch{}return Au==="light"?"light":Au==="dark"||window.matchMedia?.("(prefers-color-scheme: dark)")?.matches?"dark":"light"}const displayType2Class={accent:"primary",link:"invisible",warn:"danger",default:"default"};function ToastButton({action:Au,closeToast:lo}){const $u=Ru=>{Au.callback(Ru),Ru.defaultPrevented||lo()};return jsxRuntimeExports.jsx(ButtonComponent,{title:Au.caption??Au.label,onClick:$u,variant:displayType2Class[Au.displayType??"default"],size:"small",children:Au.label})}function createContent(Au,lo,$u){return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("div",{className:"jp-toast-message",children:Au.split(`
2094
+ Please change the parent <Route path="${Vu}"> to <Route path="${Vu==="/"?"*":`${Vu}/*`}">.`)}let Bu=useLocation$1(),ju;ju=Bu;let Fu=ju.pathname||"/",zu=Fu;if(Du!=="/"){let Vu=Du.replace(/^\//,"").split("/");zu="/"+Fu.replace(/^\//,"").split("/").slice(Vu.length).join("/")}let Uu=$u&&$u.state.matches.length?$u.state.matches.map(Vu=>Object.assign(Vu,{route:$u.manifest[Vu.route.id]||Vu.route})):matchRoutes(Au,{pathname:zu});return warning(Lu||Uu!=null,`No routes matched location "${ju.pathname}${ju.search}${ju.hash}" `),warning(Uu==null||Uu[Uu.length-1].route.element!==void 0||Uu[Uu.length-1].route.Component!==void 0||Uu[Uu.length-1].route.lazy!==void 0,`Matched leaf route at location "${ju.pathname}${ju.search}${ju.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`),_renderMatches(Uu&&Uu.map(Vu=>Object.assign({},Vu,{params:Object.assign({},Ou,Vu.params),pathname:joinPaths([Du,Ru.encodeLocation?Ru.encodeLocation(Vu.pathname.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:Vu.pathname]),pathnameBase:Vu.pathnameBase==="/"?Du:joinPaths([Du,Ru.encodeLocation?Ru.encodeLocation(Vu.pathnameBase.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:Vu.pathnameBase])})),Iu,$u)}function DefaultErrorComponent(){let Au=useRouteError(),lo=isRouteErrorResponse(Au)?`${Au.status} ${Au.statusText}`:Au instanceof Error?Au.message:JSON.stringify(Au),$u=Au instanceof Error?Au.stack:null,Ru="rgba(200,200,200, 0.5)",Iu={padding:"0.5rem",backgroundColor:Ru},Pu={padding:"2px 4px",backgroundColor:Ru},Ou=null;return console.error("Error handled by React Router default ErrorBoundary:",Au),Ou=reactExports.createElement(reactExports.Fragment,null,reactExports.createElement("p",null,"💿 Hey developer 👋"),reactExports.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",reactExports.createElement("code",{style:Pu},"ErrorBoundary")," or"," ",reactExports.createElement("code",{style:Pu},"errorElement")," prop on your route.")),reactExports.createElement(reactExports.Fragment,null,reactExports.createElement("h2",null,"Unexpected Application Error!"),reactExports.createElement("h3",{style:{fontStyle:"italic"}},lo),$u?reactExports.createElement("pre",{style:Iu},$u):null,Ou)}var defaultErrorElement=reactExports.createElement(DefaultErrorComponent,null),RenderErrorBoundary=class extends reactExports.Component{constructor(Au){super(Au),this.state={location:Au.location,revalidation:Au.revalidation,error:Au.error}}static getDerivedStateFromError(Au){return{error:Au}}static getDerivedStateFromProps(Au,lo){return lo.location!==Au.location||lo.revalidation!=="idle"&&Au.revalidation==="idle"?{error:Au.error,location:Au.location,revalidation:Au.revalidation}:{error:Au.error!==void 0?Au.error:lo.error,location:lo.location,revalidation:Au.revalidation||lo.revalidation}}componentDidCatch(Au,lo){this.props.onError?this.props.onError(Au,lo):console.error("React Router caught the following error during render",Au)}render(){let Au=this.state.error;if(this.context&&typeof Au=="object"&&Au&&"digest"in Au&&typeof Au.digest=="string"){const $u=decodeRouteErrorResponseDigest(Au.digest);$u&&(Au=$u)}let lo=Au!==void 0?reactExports.createElement(RouteContext.Provider,{value:this.props.routeContext},reactExports.createElement(RouteErrorContext.Provider,{value:Au,children:this.props.component})):this.props.children;return this.context?reactExports.createElement(RSCErrorHandler,{error:Au},lo):lo}};RenderErrorBoundary.contextType=RSCRouterContext;var errorRedirectHandledMap=new WeakMap;function RSCErrorHandler({children:Au,error:lo}){let{basename:$u,navigator:Ru}=reactExports.useContext(NavigationContext);if(typeof lo=="object"&&lo&&"digest"in lo&&typeof lo.digest=="string"){let Iu=decodeRedirectErrorDigest(lo.digest);if(Iu){let Pu=errorRedirectHandledMap.get(lo);if(Pu)throw Pu;let Ou=parseToInfo(Iu.location,$u),Mu=Ou.absoluteURL||Ou.to;if(validateNavigationTarget(Iu.location,Mu,getNavigatorCurrentUrl(Ru),"allow-explicit"),hasInvalidProtocol(Mu))throw new Error("Invalid redirect location");if(isBrowser&&!errorRedirectHandledMap.get(lo))if(Ou.isExternal||Iu.reloadDocument)window.location.href=Mu;else{const Du=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(Ou.to,{replace:Iu.replace}));throw errorRedirectHandledMap.set(lo,Du),Du}return reactExports.createElement("meta",{httpEquiv:"refresh",content:`0;url=${Mu}`})}}return Au}function RenderedRoute({routeContext:Au,match:lo,children:$u}){let Ru=reactExports.useContext(DataRouterContext);return Ru&&Ru.static&&Ru.staticContext&&(lo.route.errorElement||lo.route.ErrorBoundary)&&(Ru.staticContext._deepestRenderedBoundaryId=lo.route.id),reactExports.createElement(RouteContext.Provider,{value:Au},$u)}function _renderMatches(Au,lo=[],$u){let Ru=$u?.state;if(Au==null){if(!Ru)return null;if(Ru.errors)Au=Ru.matches;else if(lo.length===0&&!Ru.initialized&&Ru.matches.length>0)Au=Ru.matches;else return null}let Iu=Au,Pu=Ru?.errors;if(Pu!=null){let Bu=Iu.findIndex(ju=>ju.route.id&&Pu?.[ju.route.id]!==void 0);invariant(Bu>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(Pu).join(",")}`),Iu=Iu.slice(0,Math.min(Iu.length,Bu+1))}let Ou=!1,Mu=-1;if($u&&Ru){Ou=Ru.renderFallback;for(let Bu=0;Bu<Iu.length;Bu++){let ju=Iu[Bu];if((ju.route.HydrateFallback||ju.route.hydrateFallbackElement)&&(Mu=Bu),ju.route.id){let{loaderData:Fu,errors:zu}=Ru,Uu=ju.route.loader&&!Fu.hasOwnProperty(ju.route.id)&&(!zu||zu[ju.route.id]===void 0);if(ju.route.lazy||Uu){$u.isStatic&&(Ou=!0),Mu>=0?Iu=Iu.slice(0,Mu+1):Iu=[Iu[0]];break}}}}let Du=$u?.onError,Lu=Ru&&Du?(Bu,ju)=>{Du(Bu,{location:Ru.location,params:Ru.matches?.[0]?.params??{},pattern:getRoutePattern(Ru.matches),errorInfo:ju})}:void 0;return Iu.reduceRight((Bu,ju,Fu)=>{let zu,Uu=!1,Hu=null,Vu=null;Ru&&(zu=Pu&&ju.route.id?Pu[ju.route.id]:void 0,Hu=ju.route.errorElement||defaultErrorElement,Ou&&(Mu<0&&Fu===0?(warningOnce("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),Uu=!0,Vu=null):Mu===Fu&&(Uu=!0,Vu=ju.route.hydrateFallbackElement||null)));let Gu=lo.concat(Iu.slice(0,Fu+1)),Wu=()=>{let Ku;return zu?Ku=Hu:Uu?Ku=Vu:ju.route.Component?Ku=reactExports.createElement(ju.route.Component,null):ju.route.element?Ku=ju.route.element:Ku=Bu,reactExports.createElement(RenderedRoute,{match:ju,routeContext:{outlet:Bu,matches:Gu,isDataRoute:Ru!=null},children:Ku})};return Ru&&(ju.route.ErrorBoundary||ju.route.errorElement||Fu===0)?reactExports.createElement(RenderErrorBoundary,{location:Ru.location,revalidation:Ru.revalidation,component:Hu,error:zu,children:Wu(),routeContext:{outlet:null,matches:Gu,isDataRoute:!0},onError:Lu}):Wu()},null)}function getDataRouterConsoleError(Au){return`${Au} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function useDataRouterContext(Au){let lo=reactExports.useContext(DataRouterContext);return invariant(lo,getDataRouterConsoleError(Au)),lo}function useDataRouterState(Au){let lo=reactExports.useContext(DataRouterStateContext);return invariant(lo,getDataRouterConsoleError(Au)),lo}function useRouteContext(Au){let lo=reactExports.useContext(RouteContext);return invariant(lo,getDataRouterConsoleError(Au)),lo}function useCurrentRouteId(Au){let lo=useRouteContext(Au),$u=lo.matches[lo.matches.length-1];return invariant($u.route.id,`${Au} can only be used on routes that contain a unique "id"`),$u.route.id}function useRouteId(){return useCurrentRouteId("useRouteId")}function useRouteError(){let Au=reactExports.useContext(RouteErrorContext),lo=useDataRouterState("useRouteError"),$u=useCurrentRouteId("useRouteError");return Au!==void 0?Au:lo.errors?.[$u]}function useNavigateStable(){let{router:Au}=useDataRouterContext("useNavigate"),lo=useCurrentRouteId("useNavigate"),$u=reactExports.useRef(!1);return useIsomorphicLayoutEffect(()=>{$u.current=!0}),reactExports.useCallback(async(Iu,Pu={})=>{warning($u.current,navigateEffectWarning),$u.current&&(typeof Iu=="number"?await Au.navigate(Iu):await Au.navigate(Iu,{fromRouteId:lo,...Pu}))},[Au,lo])}var alreadyWarned={};function warningOnce(Au,lo,$u){!lo&&!alreadyWarned[Au]&&(alreadyWarned[Au]=!0,warning(!1,$u))}reactExports.memo(DataRoutes2);function DataRoutes2({routes:Au,manifest:lo,future:$u,state:Ru,isStatic:Iu,onError:Pu}){return useRoutesImpl(Au,void 0,{manifest:lo,state:Ru,isStatic:Iu,onError:Pu})}var defaultMethod="get",defaultEncType="application/x-www-form-urlencoded";function isHtmlElement(Au){return typeof HTMLElement<"u"&&Au instanceof HTMLElement}function isButtonElement(Au){return isHtmlElement(Au)&&Au.tagName.toLowerCase()==="button"}function isFormElement(Au){return isHtmlElement(Au)&&Au.tagName.toLowerCase()==="form"}function isInputElement(Au){return isHtmlElement(Au)&&Au.tagName.toLowerCase()==="input"}function isModifiedEvent(Au){return!!(Au.metaKey||Au.altKey||Au.ctrlKey||Au.shiftKey)}function shouldProcessLinkClick(Au,lo){return Au.button===0&&(!lo||lo==="_self")&&!isModifiedEvent(Au)}var _formDataSupportsSubmitter=null;function isFormDataSubmitterSupported(){if(_formDataSupportsSubmitter===null)try{new FormData(document.createElement("form"),0),_formDataSupportsSubmitter=!1}catch{_formDataSupportsSubmitter=!0}return _formDataSupportsSubmitter}var supportedFormEncTypes=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function getFormEncType(Au){return Au!=null&&!supportedFormEncTypes.has(Au)?(warning(!1,`"${Au}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${defaultEncType}"`),null):Au}function getFormSubmissionInfo(Au,lo){let $u,Ru,Iu,Pu,Ou;if(isFormElement(Au)){let Mu=Au.getAttribute("action");Ru=Mu?stripBasename(Mu,lo):null,$u=Au.getAttribute("method")||defaultMethod,Iu=getFormEncType(Au.getAttribute("enctype"))||defaultEncType,Pu=new FormData(Au)}else if(isButtonElement(Au)||isInputElement(Au)&&(Au.type==="submit"||Au.type==="image")){let Mu=Au.form;if(Mu==null)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let Du=Au.getAttribute("formaction")||Mu.getAttribute("action");if(Ru=Du?stripBasename(Du,lo):null,$u=Au.getAttribute("formmethod")||Mu.getAttribute("method")||defaultMethod,Iu=getFormEncType(Au.getAttribute("formenctype"))||getFormEncType(Mu.getAttribute("enctype"))||defaultEncType,Pu=new FormData(Mu,Au),!isFormDataSubmitterSupported()){let{name:Lu,type:Bu,value:ju}=Au;if(Bu==="image"){let Fu=Lu?`${Lu}.`:"";Pu.append(`${Fu}x`,"0"),Pu.append(`${Fu}y`,"0")}else Lu&&Pu.append(Lu,ju)}}else{if(isHtmlElement(Au))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');$u=defaultMethod,Ru=null,Iu=defaultEncType,Ou=Au}return Pu&&Iu==="text/plain"&&(Ou=Pu,Pu=void 0),{action:Ru,method:$u.toLowerCase(),encType:Iu,formData:Pu,body:Ou}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");function invariant2(Au,lo){if(Au===!1||Au===null||typeof Au>"u")throw new Error(lo)}function singleFetchUrl(Au,lo,$u,Ru){let Iu=typeof Au=="string"?new URL(Au,typeof window>"u"?"server://singlefetch/":window.location.origin):Au;return $u?Iu.pathname.endsWith("/")?Iu.pathname=`${Iu.pathname}_.${Ru}`:Iu.pathname=`${Iu.pathname}.${Ru}`:Iu.pathname==="/"?Iu.pathname=`_root.${Ru}`:lo&&stripBasename(Iu.pathname,lo)==="/"?Iu.pathname=`${removeTrailingSlash(lo)}/_root.${Ru}`:Iu.pathname=`${removeTrailingSlash(Iu.pathname)}.${Ru}`,Iu}async function loadRouteModule(Au,lo){if(Au.id in lo)return lo[Au.id];try{let $u=await import(Au.module);return lo[Au.id]=$u,$u}catch($u){return console.error(`Error loading route module \`${Au.module}\`, reloading page...`),console.error($u),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function isHtmlLinkDescriptor(Au){return Au==null?!1:Au.href==null?Au.rel==="preload"&&typeof Au.imageSrcSet=="string"&&typeof Au.imageSizes=="string":typeof Au.rel=="string"&&typeof Au.href=="string"}async function getKeyedPrefetchLinks(Au,lo,$u){let Ru=await Promise.all(Au.map(async Iu=>{let Pu=lo.routes[Iu.route.id];if(Pu){let Ou=await loadRouteModule(Pu,$u);return Ou.links?Ou.links():[]}return[]}));return dedupeLinkDescriptors(Ru.flat(1).filter(isHtmlLinkDescriptor).filter(Iu=>Iu.rel==="stylesheet"||Iu.rel==="preload").map(Iu=>Iu.rel==="stylesheet"?{...Iu,rel:"prefetch",as:"style"}:{...Iu,rel:"prefetch"}))}function getNewMatchesForLinks(Au,lo,$u,Ru,Iu,Pu){let Ou=(Du,Lu)=>$u[Lu]?Du.route.id!==$u[Lu].route.id:!0,Mu=(Du,Lu)=>$u[Lu].pathname!==Du.pathname||$u[Lu].route.path?.endsWith("*")&&$u[Lu].params["*"]!==Du.params["*"];return Pu==="assets"?lo.filter((Du,Lu)=>Ou(Du,Lu)||Mu(Du,Lu)):Pu==="data"?lo.filter((Du,Lu)=>{let Bu=Ru.routes[Du.route.id];if(!Bu||!Bu.hasLoader)return!1;if(Ou(Du,Lu)||Mu(Du,Lu))return!0;if(Du.route.shouldRevalidate){let ju=Du.route.shouldRevalidate({currentUrl:new URL(Iu.pathname+Iu.search+Iu.hash,window.origin),currentParams:$u[0]?.params||{},nextUrl:new URL(Au,window.origin),nextParams:Du.params,defaultShouldRevalidate:!0});if(typeof ju=="boolean")return ju}return!0}):[]}function getModuleLinkHrefs(Au,lo,{includeHydrateFallback:$u}={}){return dedupeHrefs(Au.map(Ru=>{let Iu=lo.routes[Ru.route.id];if(!Iu)return[];let Pu=[Iu.module];return Iu.clientActionModule&&(Pu=Pu.concat(Iu.clientActionModule)),Iu.clientLoaderModule&&(Pu=Pu.concat(Iu.clientLoaderModule)),$u&&Iu.hydrateFallbackModule&&(Pu=Pu.concat(Iu.hydrateFallbackModule)),Iu.imports&&(Pu=Pu.concat(Iu.imports)),Pu}).flat(1))}function dedupeHrefs(Au){return[...new Set(Au)]}function sortKeys(Au){let lo={},$u=Object.keys(Au).sort();for(let Ru of $u)lo[Ru]=Au[Ru];return lo}function dedupeLinkDescriptors(Au,lo){let $u=new Set;return new Set(lo),Au.reduce((Ru,Iu)=>{let Pu=JSON.stringify(sortKeys(Iu));return $u.has(Pu)||($u.add(Pu),Ru.push({key:Pu,link:Iu})),Ru},[])}function useDataRouterContext2(){let Au=reactExports.useContext(DataRouterContext);return invariant2(Au,"You must render this element inside a <DataRouterContext.Provider> element"),Au}function useDataRouterStateContext(){let Au=reactExports.useContext(DataRouterStateContext);return invariant2(Au,"You must render this element inside a <DataRouterStateContext.Provider> element"),Au}var FrameworkContext=reactExports.createContext(void 0);FrameworkContext.displayName="FrameworkContext";function useFrameworkContext(){let Au=reactExports.useContext(FrameworkContext);return invariant2(Au,"You must render this element inside a <HydratedRouter> element"),Au}function usePrefetchBehavior(Au,lo){let $u=reactExports.useContext(FrameworkContext),[Ru,Iu]=reactExports.useState(!1),[Pu,Ou]=reactExports.useState(!1),{onFocus:Mu,onBlur:Du,onMouseEnter:Lu,onMouseLeave:Bu,onTouchStart:ju}=lo,Fu=reactExports.useRef(null);reactExports.useEffect(()=>{if(Au==="render"&&Ou(!0),Au==="viewport"){let Hu=Gu=>{Gu.forEach(Wu=>{Ou(Wu.isIntersecting)})},Vu=new IntersectionObserver(Hu,{threshold:.5});return Fu.current&&Vu.observe(Fu.current),()=>{Vu.disconnect()}}},[Au]),reactExports.useEffect(()=>{if(Ru){let Hu=setTimeout(()=>{Ou(!0)},100);return()=>{clearTimeout(Hu)}}},[Ru]);let zu=()=>{Iu(!0)},Uu=()=>{Iu(!1),Ou(!1)};return $u?Au!=="intent"?[Pu,Fu,{}]:[Pu,Fu,{onFocus:composeEventHandlers(Mu,zu),onBlur:composeEventHandlers(Du,Uu),onMouseEnter:composeEventHandlers(Lu,zu),onMouseLeave:composeEventHandlers(Bu,Uu),onTouchStart:composeEventHandlers(ju,zu)}]:[!1,Fu,{}]}function composeEventHandlers(Au,lo){return $u=>{Au&&Au($u),$u.defaultPrevented||lo($u)}}function PrefetchPageLinks({page:Au,...lo}){let $u=useIsRSCRouterContext(),{nonce:Ru}=useFrameworkContext(),{router:Iu}=useDataRouterContext2(),Pu=reactExports.useMemo(()=>matchRoutes(Iu.routes,Au,Iu.basename),[Iu.routes,Au,Iu.basename]);return Pu?(lo.nonce==null&&Ru&&(lo={...lo,nonce:Ru}),$u?reactExports.createElement(RSCPrefetchPageLinksImpl,{page:Au,matches:Pu,...lo}):reactExports.createElement(PrefetchPageLinksImpl,{page:Au,matches:Pu,...lo})):null}function useKeyedPrefetchLinks(Au){let{manifest:lo,routeModules:$u}=useFrameworkContext(),[Ru,Iu]=reactExports.useState([]);return reactExports.useEffect(()=>{let Pu=!1;return getKeyedPrefetchLinks(Au,lo,$u).then(Ou=>{Pu||Iu(Ou)}),()=>{Pu=!0}},[Au,lo,$u]),Ru}function RSCPrefetchPageLinksImpl({page:Au,matches:lo,...$u}){let Ru=useLocation$1(),{future:Iu}=useFrameworkContext(),{basename:Pu}=useDataRouterContext2(),Ou=reactExports.useMemo(()=>{if(Au===Ru.pathname+Ru.search+Ru.hash)return[];let Mu=singleFetchUrl(Au,Pu,Iu.v8_trailingSlashAwareDataRequests,"rsc"),Du=!1,Lu=[];for(let Bu of lo)typeof Bu.route.shouldRevalidate=="function"?Du=!0:Lu.push(Bu.route.id);return Du&&Lu.length>0&&Mu.searchParams.set("_routes",Lu.join(",")),[Mu.pathname+Mu.search]},[Pu,Iu.v8_trailingSlashAwareDataRequests,Au,Ru,lo]);return reactExports.createElement(reactExports.Fragment,null,Ou.map(Mu=>reactExports.createElement("link",{key:Mu,rel:"prefetch",as:"fetch",href:Mu,...$u})))}function PrefetchPageLinksImpl({page:Au,matches:lo,...$u}){let Ru=useLocation$1(),{future:Iu,manifest:Pu,routeModules:Ou}=useFrameworkContext(),{basename:Mu}=useDataRouterContext2(),{loaderData:Du,matches:Lu}=useDataRouterStateContext(),Bu=reactExports.useMemo(()=>getNewMatchesForLinks(Au,lo,Lu,Pu,Ru,"data"),[Au,lo,Lu,Pu,Ru]),ju=reactExports.useMemo(()=>getNewMatchesForLinks(Au,lo,Lu,Pu,Ru,"assets"),[Au,lo,Lu,Pu,Ru]),Fu=reactExports.useMemo(()=>{if(Au===Ru.pathname+Ru.search+Ru.hash)return[];let Hu=new Set,Vu=!1;if(lo.forEach(Wu=>{let Ku=Pu.routes[Wu.route.id];!Ku||!Ku.hasLoader||(!Bu.some(Ju=>Ju.route.id===Wu.route.id)&&Wu.route.id in Du&&Ou[Wu.route.id]?.shouldRevalidate||Ku.hasClientLoader?Vu=!0:Hu.add(Wu.route.id))}),Hu.size===0)return[];let Gu=singleFetchUrl(Au,Mu,Iu.v8_trailingSlashAwareDataRequests,"data");return Vu&&Hu.size>0&&Gu.searchParams.set("_routes",lo.filter(Wu=>Hu.has(Wu.route.id)).map(Wu=>Wu.route.id).join(",")),[Gu.pathname+Gu.search]},[Mu,Iu.v8_trailingSlashAwareDataRequests,Du,Ru,Pu,Bu,lo,Au,Ou]),zu=reactExports.useMemo(()=>getModuleLinkHrefs(ju,Pu),[ju,Pu]),Uu=useKeyedPrefetchLinks(ju);return reactExports.createElement(reactExports.Fragment,null,Fu.map(Hu=>reactExports.createElement("link",{key:Hu,rel:"prefetch",as:"fetch",href:Hu,...$u})),zu.map(Hu=>reactExports.createElement("link",{key:Hu,rel:"modulepreload",href:Hu,...$u})),Uu.map(({key:Hu,link:Vu})=>reactExports.createElement("link",{key:Hu,nonce:$u.nonce,...Vu,crossOrigin:Vu.crossOrigin??$u.crossOrigin})))}function mergeRefs(...Au){return lo=>{Au.forEach($u=>{typeof $u=="function"?$u(lo):$u!=null&&($u.current=lo)})}}var isBrowser2=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{isBrowser2&&(window.__reactRouterVersion="7.18.3")}catch(Au){}var Link=reactExports.forwardRef(function Au({onClick:lo,discover:$u="render",prefetch:Ru="none",relative:Iu,reloadDocument:Pu,replace:Ou,mask:Mu,state:Du,target:Lu,to:Bu,preventScrollReset:ju,viewTransition:Fu,defaultShouldRevalidate:zu,...Uu},Hu){let{basename:Vu,navigator:Gu,useTransitions:Wu}=reactExports.useContext(NavigationContext),Ku=typeof Bu=="string"&&ABSOLUTE_URL_REGEX.test(Bu),Ju=parseToInfo(Bu,Vu);Bu=Ju.to;let Yu=useHref(Bu,{relative:Iu}),Xu=useLocation$1(),ed=null;if(Mu){let xd=resolveTo(Mu,[],Xu.mask?Xu.mask.pathname:"/",!0);Vu!=="/"&&(xd.pathname=xd.pathname==="/"?Vu:joinPaths([Vu,xd.pathname])),ed=Gu.createHref(xd)}let[td,nd,od]=usePrefetchBehavior(Ru,Uu),sd=useLinkClickHandler(Bu,{replace:Ou,mask:Mu,state:Du,target:Lu,preventScrollReset:ju,relative:Iu,viewTransition:Fu,defaultShouldRevalidate:zu,useTransitions:Wu});function ad(xd){lo&&lo(xd),xd.defaultPrevented||sd(xd)}let pd=!(Ju.isExternal||Pu),gd=reactExports.createElement("a",{...Uu,...od,href:(pd?ed:void 0)||Ju.absoluteURL||Yu,onClick:pd?ad:lo,ref:mergeRefs(Hu,nd),target:Lu,"data-discover":!Ku&&$u==="render"?"true":void 0});return td&&!Ku?reactExports.createElement(reactExports.Fragment,null,gd,reactExports.createElement(PrefetchPageLinks,{page:Yu})):gd});Link.displayName="Link";var NavLink=reactExports.forwardRef(function Au({"aria-current":lo="page",caseSensitive:$u=!1,className:Ru="",end:Iu=!1,style:Pu,to:Ou,viewTransition:Mu,children:Du,...Lu},Bu){let ju=useResolvedPath(Ou,{relative:Lu.relative}),Fu=useLocation$1(),zu=reactExports.useContext(DataRouterStateContext),{navigator:Uu,basename:Hu}=reactExports.useContext(NavigationContext),Vu=zu!=null&&useViewTransitionState(ju)&&Mu===!0,Gu=Uu.encodeLocation?Uu.encodeLocation(ju).pathname:ju.pathname,Wu=Fu.pathname,Ku=zu&&zu.navigation&&zu.navigation.location?zu.navigation.location.pathname:null;$u||(Wu=Wu.toLowerCase(),Ku=Ku?Ku.toLowerCase():null,Gu=Gu.toLowerCase()),Ku&&Hu&&(Ku=stripBasename(Ku,Hu)||Ku);const Ju=Gu!=="/"&&Gu.endsWith("/")?Gu.length-1:Gu.length;let Yu=Wu===Gu||!Iu&&Wu.startsWith(Gu)&&Wu.charAt(Ju)==="/",Xu=Ku!=null&&(Ku===Gu||!Iu&&Ku.startsWith(Gu)&&Ku.charAt(Gu.length)==="/"),ed={isActive:Yu,isPending:Xu,isTransitioning:Vu},td=Yu?lo:void 0,nd;typeof Ru=="function"?nd=Ru(ed):nd=[Ru,Yu?"active":null,Xu?"pending":null,Vu?"transitioning":null].filter(Boolean).join(" ");let od=typeof Pu=="function"?Pu(ed):Pu;return reactExports.createElement(Link,{...Lu,"aria-current":td,className:nd,ref:Bu,style:od,to:Ou,viewTransition:Mu},typeof Du=="function"?Du(ed):Du)});NavLink.displayName="NavLink";var Form$1=reactExports.forwardRef(({discover:Au="render",fetcherKey:lo,navigate:$u,reloadDocument:Ru,replace:Iu,state:Pu,method:Ou=defaultMethod,action:Mu,onSubmit:Du,relative:Lu,preventScrollReset:Bu,viewTransition:ju,defaultShouldRevalidate:Fu,...zu},Uu)=>{let{useTransitions:Hu}=reactExports.useContext(NavigationContext),Vu=useSubmit(),Gu=useFormAction(Mu,{relative:Lu}),Wu=Ou.toLowerCase()==="get"?"get":"post",Ku=typeof Mu=="string"&&ABSOLUTE_URL_REGEX.test(Mu),Ju=Yu=>{if(Du&&Du(Yu),Yu.defaultPrevented)return;Yu.preventDefault();let Xu=Yu.nativeEvent.submitter,ed=Xu?.getAttribute("formmethod")||Ou,td=()=>Vu(Xu||Yu.currentTarget,{fetcherKey:lo,method:ed,navigate:$u,replace:Iu,state:Pu,relative:Lu,preventScrollReset:Bu,viewTransition:ju,defaultShouldRevalidate:Fu});Hu&&$u!==!1?reactExports.startTransition(()=>td()):td()};return reactExports.createElement("form",{ref:Uu,method:Wu,action:Gu,onSubmit:Ru?Du:Ju,...zu,"data-discover":!Ku&&Au==="render"?"true":void 0})});Form$1.displayName="Form";function getDataRouterConsoleError2(Au){return`${Au} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function useDataRouterContext3(Au){let lo=reactExports.useContext(DataRouterContext);return invariant(lo,getDataRouterConsoleError2(Au)),lo}function useLinkClickHandler(Au,{target:lo,replace:$u,mask:Ru,state:Iu,preventScrollReset:Pu,relative:Ou,viewTransition:Mu,defaultShouldRevalidate:Du,useTransitions:Lu}={}){let Bu=useNavigate$1(),ju=useLocation$1(),Fu=useResolvedPath(Au,{relative:Ou});return reactExports.useCallback(zu=>{if(shouldProcessLinkClick(zu,lo)){zu.preventDefault();let Uu=$u!==void 0?$u:createPath(ju)===createPath(Fu),Hu=()=>Bu(Au,{replace:Uu,mask:Ru,state:Iu,preventScrollReset:Pu,relative:Ou,viewTransition:Mu,defaultShouldRevalidate:Du});Lu?reactExports.startTransition(()=>Hu()):Hu()}},[ju,Bu,Fu,$u,Ru,Iu,lo,Au,Pu,Ou,Mu,Du,Lu])}var fetcherId=0,getUniqueFetcherId=()=>`__${String(++fetcherId)}__`;function useSubmit(){let{router:Au}=useDataRouterContext3("useSubmit"),{basename:lo}=reactExports.useContext(NavigationContext),$u=useRouteId(),Ru=Au.fetch,Iu=Au.navigate;return reactExports.useCallback(async(Pu,Ou={})=>{let{action:Mu,method:Du,encType:Lu,formData:Bu,body:ju}=getFormSubmissionInfo(Pu,lo);if(Ou.navigate===!1){let Fu=Ou.fetcherKey||getUniqueFetcherId();await Ru(Fu,$u,Ou.action||Mu,{defaultShouldRevalidate:Ou.defaultShouldRevalidate,preventScrollReset:Ou.preventScrollReset,formData:Bu,body:ju,formMethod:Ou.method||Du,formEncType:Ou.encType||Lu,flushSync:Ou.flushSync})}else await Iu(Ou.action||Mu,{defaultShouldRevalidate:Ou.defaultShouldRevalidate,preventScrollReset:Ou.preventScrollReset,formData:Bu,body:ju,formMethod:Ou.method||Du,formEncType:Ou.encType||Lu,replace:Ou.replace,state:Ou.state,fromRouteId:$u,flushSync:Ou.flushSync,viewTransition:Ou.viewTransition})},[Ru,Iu,lo,$u])}function useFormAction(Au,{relative:lo}={}){let{basename:$u}=reactExports.useContext(NavigationContext),Ru=reactExports.useContext(RouteContext);invariant(Ru,"useFormAction must be used inside a RouteContext");let[Iu]=Ru.matches.slice(-1),Pu={...useResolvedPath(Au||".",{relative:lo})},Ou=useLocation$1();if(Au==null){Pu.search=Ou.search;let Mu=new URLSearchParams(Pu.search),Du=Mu.getAll("index");if(Du.some(Bu=>Bu==="")){Mu.delete("index"),Du.filter(ju=>ju).forEach(ju=>Mu.append("index",ju));let Bu=Mu.toString();Pu.search=Bu?`?${Bu}`:""}}return(!Au||Au===".")&&Iu.route.index&&(Pu.search=Pu.search?Pu.search.replace(/^\?/,"?index&"):"?index"),$u!=="/"&&(Pu.pathname=Pu.pathname==="/"?$u:joinPaths([$u,Pu.pathname])),createPath(Pu)}function useViewTransitionState(Au,{relative:lo}={}){let $u=reactExports.useContext(ViewTransitionContext);invariant($u!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:Ru}=useDataRouterContext3("useViewTransitionState"),Iu=useResolvedPath(Au,{relative:lo});if(!$u.isTransitioning)return!1;let Pu=stripBasename($u.currentLocation.pathname,Ru)||$u.currentLocation.pathname,Ou=stripBasename($u.nextLocation.pathname,Ru)||$u.nextLocation.pathname;return matchPath(Iu.pathname,Ou)!=null||matchPath(Iu.pathname,Pu)!=null}const useLocationRR=useLocation$1,useNavigateRR=useNavigate$1,useLocation=()=>{const[Au,lo]=reactExports.useState(()=>typeof window>"u"?{pathname:"/",search:"",hash:"",state:null,key:"default"}:{pathname:window.location.pathname,search:window.location.search,hash:window.location.hash,state:window.history.state,key:"default"}),$u=typeof window<"u"&&!!window.__NEXT_DATA__,Ru=typeof window<"u";let Iu=null,Pu=!1;try{!$u&&useLocationRR&&Ru&&(Iu=useLocationRR(),Pu=!!Iu)}catch{}return reactExports.useEffect(()=>{if(Pu)return;const Ou=()=>{lo({pathname:window.location.pathname,search:window.location.search,hash:window.location.hash,state:window.history.state,key:"native-"+Date.now()})};return window.addEventListener("popstate",Ou),window.addEventListener("pushstate",Ou),window.addEventListener("replacestate",Ou),()=>{window.removeEventListener("popstate",Ou),window.removeEventListener("pushstate",Ou),window.removeEventListener("replacestate",Ou)}},[Pu]),Pu&&Iu?Iu:Au},NAVIGATION_VIEW_HOMES={studio:"/studio",home:"/power",agentify:"/agentify",admin:"/admin",apps:"/apps/apps"},LIBRARY_VIEW="library",AGENTS_VIEW="agents",SETTINGS_VIEW="settings",DATALAYER_VIEW="datalayer",CONTENTS_VIEW="contents",TUTOR_VIEW="tutor",STORAGE_KEY="datalayer-navigation",SHELL_COOKIE="datalayer-signed-in-view",FORMER_TABS_KEY="datalayer_view_tabs",COOKIE_MAX_AGE_DAYS=365,isView=Au=>Au==="studio"||Au==="home"||Au==="agentify"||Au==="admin"||Au==="apps";function readCookie(Au){if(typeof document>"u")return;const lo=document.cookie.split("; ").find($u=>$u.startsWith(`${Au}=`));return lo?decodeURIComponent(lo.slice(Au.length+1)):void 0}function writeCookie(Au,lo){if(typeof document>"u")return;const $u=COOKIE_MAX_AGE_DAYS*24*60*60;document.cookie=`${Au}=${encodeURIComponent(lo)}; path=/; max-age=${$u}; SameSite=Lax`}function readLocal(Au){try{return globalThis.localStorage?.getItem(Au)??null}catch{return null}}function restore(){let Au={};const lo=readLocal(STORAGE_KEY);if(lo)try{const Ru=JSON.parse(lo),Iu=Ru?.state??Ru;Au=Iu&&typeof Iu=="object"?Iu:{}}catch{Au={}}else{const Ru=readLocal(FORMER_TABS_KEY);if(Ru)try{const{state:Iu}=JSON.parse(Ru);Au={tabsByView:Iu?.tabsByView??{}}}catch{Au={}}}const $u=readCookie(SHELL_COOKIE);return isView($u)&&(Au.view=$u),Au.lastRouteByView=restoredRoutes(Au.lastRouteByView),Au}function restoredRoutes(Au){const lo={};if(!Au||typeof Au!="object")return lo;for(const[$u,Ru]of Object.entries(Au))isView($u)&&isRouteOfView(Ru,$u)&&(lo[$u]=Ru);return lo}function persist$1(Au){const lo={view:Au.view,lastRouteByView:Au.lastRouteByView,tabsByView:Au.tabsByView};try{globalThis.localStorage?.setItem(STORAGE_KEY,JSON.stringify(lo))}catch{}writeCookie(SHELL_COOKIE,Au.view)}function pathOf(Au){const lo=Au.search(/[?#]/);return lo===-1?Au:Au.slice(0,lo)}function isRememberableRoute(Au){if(!Au.startsWith("/"))return!1;const lo=pathOf(Au);return!["/signin","/signup","/login","/logout","/oauth2","/oauth","/join"].some($u=>lo===$u||lo.startsWith(`${$u}/`))&&!isShellNeutralRoute(Au)}function isShellNeutralRoute(Au){const lo=pathOf(Au);return["/settings","/docs","/decks"].some($u=>lo===$u||lo.startsWith(`${$u}/`))}function viewForRoute(Au,lo){const $u=pathOf(Au);return lo&&isShellNeutralRoute(Au)?lo:$u==="/"||$u==="/studio"||$u.startsWith("/studio/")||$u==="/settings"||$u.startsWith("/settings/")||$u==="/agentspecs"||$u.startsWith("/agentspecs/")?"studio":$u==="/agentify"||$u.startsWith("/agentify/")?"agentify":$u==="/admin"||$u.startsWith("/admin/")?"admin":$u==="/apps"||$u.startsWith("/apps/")?"apps":"home"}function isRouteOfView(Au,lo){return typeof Au=="string"&&isRememberableRoute(Au)&&viewForRoute(Au)===lo}const initial=restore(),navigationStore=createStore$1((Au,lo)=>({view:initial.view??"studio",lastRouteByView:initial.lastRouteByView??{},tabsByView:initial.tabsByView??{},requestedRoute:void 0,docsOrigin:void 0,setView:$u=>{Au({view:$u}),persist$1(lo())},toggleView:()=>{Au($u=>({view:$u.view==="home"?"agentify":"home"})),persist$1(lo())},rememberRoute:($u,Ru)=>{if(!isRememberableRoute($u))return;const Iu=Ru??viewForRoute($u),Pu=Ru===void 0,Ou=lo();Ou.lastRouteByView[Iu]===$u&&(!Pu||Ou.view===Iu)||(Au(Mu=>({view:Pu?Iu:Mu.view,lastRouteByView:{...Mu.lastRouteByView,[Iu]:$u}})),persist$1(lo()))},routeForView:$u=>{const Ru=lo().lastRouteByView[$u];return isRouteOfView(Ru,$u)?Ru:NAVIGATION_VIEW_HOMES[$u]},setViewTab:($u,Ru)=>{lo().tabsByView[$u]!==Ru&&(Au(Iu=>({tabsByView:{...Iu.tabsByView,[$u]:Ru}})),persist$1(lo()))},getViewTab:$u=>lo().tabsByView[$u],setRequestedRoute:$u=>Au({requestedRoute:$u}),clearRequestedRoute:()=>Au({requestedRoute:void 0}),setDocsOrigin:$u=>Au({docsOrigin:$u})}));registerSessionState({forget:()=>{navigationStore.setState({lastRouteByView:{},tabsByView:{},requestedRoute:void 0,docsOrigin:void 0}),persist$1(navigationStore.getState())},localStorageKeys:[FORMER_TABS_KEY]});function useNavigationState(Au){return useStore$1(navigationStore,Au??(lo=>lo))}const useNavigationStore=Object.assign(useNavigationState,{getState:navigationStore.getState,setState:navigationStore.setState,subscribe:navigationStore.subscribe}),navigationListeners=new Set,notifyNavigationChange=()=>{navigationListeners.forEach(Au=>Au())},createNativeNavigate=()=>(Au,lo)=>{if(typeof window>"u")return;const $u=new URL(Au,window.location.href),Ru=lo||{},Iu=Ru.state||null;Ru.replace?(window.history.replaceState(Iu,"",$u.href),window.dispatchEvent(new Event("replacestate"))):(window.history.pushState(Iu,"",$u.href),window.dispatchEvent(new Event("pushstate"))),notifyNavigationChange(),Ru.scroll!==!1&&window.scrollTo(0,0)};function isNewTabClick(Au){return!!Au.metaKey||!!Au.ctrlKey||!!Au.shiftKey||!!Au.altKey||Au.button===1}const resolveUrl$1=Au=>new URL(Au,window.location.href).href;function openInNewTab(Au){window.open(resolveUrl$1(Au),"_blank","noopener,noreferrer")}function isLinkTo(Au,lo){const $u=Au.currentTarget??Au.target,Ru=$u&&typeof $u.closest=="function"?$u.closest("a[href]"):null;if(!Ru)return!1;try{return resolveUrl$1(Ru.getAttribute("href")??"")===resolveUrl$1(lo)}catch{return!1}}const isEvent=Au=>!!Au&&typeof Au.preventDefault=="function";function parseCall(Au,lo,$u){if(isEvent(Au)){const Ru=typeof lo=="boolean"?{resetPortals:lo,...$u??{}}:{...lo??{},...$u??{}};return{event:Au,options:Ru}}return typeof Au=="boolean"?{options:{resetPortals:Au,...typeof lo=="object"?lo:{},...$u??{}}}:{options:{...Au??{}}}}const useNavigate=()=>{const Au=useLayoutStore(),lo=typeof window<"u"&&!!window.__NEXT_DATA__,$u=typeof window<"u";let Ru=null;if(!lo&&useNavigateRR&&$u)try{Ru=useNavigateRR()}catch{}const Iu=reactExports.useMemo(()=>createNativeNavigate(),[]);return reactExports.useCallback((Pu,Ou,Mu,Du)=>{if(typeof window>"u")return;const{event:Lu,options:Bu}=parseCall(Ou,Mu,Du);if(typeof Pu=="number"){Lu?.preventDefault(),Ru?Ru(Pu):window.history.go(Pu);return}if(Lu&&isNewTabClick(Lu)){isLinkTo(Lu,Pu)||(Lu.preventDefault(),openInNewTab(Pu));return}if(Bu.newTab){Lu?.preventDefault(),openInNewTab(Pu);return}if(Lu?.preventDefault(),Bu.scroll!==!1&&(window.scrollTo(0,0),document.body.scrollTop=0),navigationStore.getState().rememberRoute(Pu),Ru){Ru(Pu,{replace:Bu.replace,state:Bu.state});return}Bu.resetPortals!==!1&&(Au.resetLeftPortal(),Au.resetRightPortal()),Iu(Pu,{replace:Bu.replace,state:Bu.state,scroll:Bu.scroll})},[Ru,Iu,Au])};var propTypes$2={exports:{}},ReactPropTypesSecret_1,hasRequiredReactPropTypesSecret;function requireReactPropTypesSecret(){if(hasRequiredReactPropTypesSecret)return ReactPropTypesSecret_1;hasRequiredReactPropTypesSecret=1;var Au="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";return ReactPropTypesSecret_1=Au,ReactPropTypesSecret_1}var factoryWithThrowingShims,hasRequiredFactoryWithThrowingShims;function requireFactoryWithThrowingShims(){if(hasRequiredFactoryWithThrowingShims)return factoryWithThrowingShims;hasRequiredFactoryWithThrowingShims=1;var Au=requireReactPropTypesSecret();function lo(){}function $u(){}return $u.resetWarningCache=lo,factoryWithThrowingShims=function(){function Ru(Ou,Mu,Du,Lu,Bu,ju){if(ju!==Au){var Fu=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw Fu.name="Invariant Violation",Fu}}Ru.isRequired=Ru;function Iu(){return Ru}var Pu={array:Ru,bigint:Ru,bool:Ru,func:Ru,number:Ru,object:Ru,string:Ru,symbol:Ru,any:Ru,arrayOf:Iu,element:Ru,elementType:Ru,instanceOf:Iu,node:Ru,objectOf:Iu,oneOf:Iu,oneOfType:Iu,shape:Iu,exact:Iu,checkPropTypes:$u,resetWarningCache:lo};return Pu.PropTypes=Pu,Pu},factoryWithThrowingShims}var hasRequiredPropTypes;function requirePropTypes(){return hasRequiredPropTypes||(hasRequiredPropTypes=1,propTypes$2.exports=requireFactoryWithThrowingShims()()),propTypes$2.exports}var propTypesExports=requirePropTypes();const s$5=getDefaultExportFromCjs(propTypesExports);var L$4=Au=>typeof Au=="number"&&!isNaN(Au),N$3=Au=>typeof Au=="string",P$5=Au=>typeof Au=="function",ut$5=Au=>N$3(Au)||L$4(Au),F$4=Au=>reactExports.isValidElement(Au)||N$3(Au)||P$5(Au)||L$4(Au),Qt$3=1,st$5=()=>`${Qt$3++}`,I$3=new Map,U$5=[],rt$5=new Set,ht$4=()=>I$3.size>0,Ct$5=(Au,{containerId:lo})=>{var $u;return($u=I$3.get(lo||1))==null?void 0:$u.toasts.get(Au)};function X$5(Au,lo){var $u;if(lo)return!!(($u=I$3.get(lo))!=null&&$u.isToastActive(Au));let Ru=!1;return I$3.forEach(Iu=>{Iu.isToastActive(Au)&&(Ru=!0)}),Ru}function xt$4(Au){if(!ht$4()){U$5=U$5.filter(lo=>Au!=null&&lo.options.toastId!==Au);return}if(Au==null||ut$5(Au))I$3.forEach(lo=>{lo.removeToast(Au)});else if(Au&&("containerId"in Au||"id"in Au)){let lo=I$3.get(Au.containerId);lo?lo.removeToast(Au.id):I$3.forEach($u=>{$u.removeToast(Au.id)})}}var Et$4=(Au={})=>{I$3.forEach(lo=>{lo.props.limit&&(!Au.containerId||lo.id===Au.containerId)&&lo.clearQueue()})};function nt$5(Au,lo){F$4(Au)&&(ht$4()||U$5.push({content:Au,options:lo}),I$3.forEach($u=>{$u.buildToast(Au,lo)}))}function it$5(Au,lo){I$3.forEach($u=>{(lo==null||!(lo!=null&&lo.containerId)||lo?.containerId===$u.id)&&$u.toggle(Au,lo?.id)})}function St$4(Au){return rt$5.add(Au),()=>{rt$5.delete(Au)}}function qt$3(Au){return Au&&(N$3(Au.toastId)||L$4(Au.toastId))?Au.toastId:st$5()}function H$4(Au,lo){return nt$5(Au,lo),lo.toastId}function Q$4(Au,lo){return{...lo,type:lo&&lo.type||Au,toastId:qt$3(lo)}}function W$4(Au){return(lo,$u)=>H$4(lo,Q$4(Au,$u))}function y$6(Au,lo){return H$4(Au,Q$4("default",lo))}y$6.loading=(Au,lo)=>H$4(Au,Q$4("default",{isLoading:!0,autoClose:!1,closeOnClick:!1,closeButton:!1,draggable:!1,...lo}));function Kt$4(Au,{pending:lo,error:$u,success:Ru},Iu){let Pu;lo&&(Pu=N$3(lo)?y$6.loading(lo,Iu):y$6.loading(lo.render,{...Iu,...lo}));let Ou={isLoading:null,autoClose:null,closeOnClick:null,closeButton:null,draggable:null},Mu=(Lu,Bu,ju)=>{if(Bu==null){y$6.dismiss(Pu);return}let Fu={type:Lu,...Ou,...Iu,data:ju},zu=N$3(Bu)?{render:Bu}:Bu;return Pu?y$6.update(Pu,{...Fu,...zu}):y$6(zu.render,{...Fu,...zu}),ju},Du=P$5(Au)?Au():Au;return Du.then(Lu=>Mu("success",Ru,Lu)).catch(Lu=>Mu("error",$u,Lu)),Du}y$6.promise=Kt$4;y$6.success=W$4("success");y$6.info=W$4("info");y$6.error=W$4("error");y$6.warning=W$4("warning");y$6.warn=y$6.warning;y$6.dark=(Au,lo)=>H$4(Au,Q$4("default",{theme:"dark",...lo}));function Yt$3(Au){xt$4(Au)}y$6.dismiss=Yt$3;y$6.clearWaitingQueue=Et$4;y$6.isActive=X$5;y$6.update=(Au,lo={})=>{let $u=Ct$5(Au,lo);if($u){let{props:Ru,content:Iu}=$u,Pu={delay:100,...Ru,...lo,toastId:lo.toastId||Au,updateId:st$5()};Pu.toastId!==Au&&(Pu.staleId=Au);let Ou=Pu.render||Iu;delete Pu.render,H$4(Ou,Pu)}};y$6.done=Au=>{y$6.update(Au,{progress:1})};y$6.onChange=St$4;y$6.play=Au=>it$5(!0,Au);y$6.pause=Au=>it$5(!1,Au);const JupyterReactTheme=vM.lazy(()=>__vitePreload(()=>import("./chunks/index-BN8Bbau-.js").then(Au=>Au.r),[],import.meta.url).then(Au=>({default:Au.JupyterReactTheme})));let NotificationApi;isInsideJupyterLab()&&__vitePreload(()=>import("./chunks/index-CFP9psRB.js").then(Au=>Au.q),[],import.meta.url).then(Au=>{NotificationApi=Au.Notification});const TOAST_POSITION="bottom-right",THEME_STORAGE_KEY="datalayer-theme";function resolveToastTheme(){if(typeof window>"u")return"dark";let Au;try{const $u=window.localStorage.getItem(THEME_STORAGE_KEY);$u&&(Au=JSON.parse($u)?.state?.colorMode)}catch{}return Au==="light"?"light":Au==="dark"||window.matchMedia?.("(prefers-color-scheme: dark)")?.matches?"dark":"light"}const displayType2Class={accent:"primary",link:"invisible",warn:"danger",default:"default"};function ToastButton({action:Au,closeToast:lo}){const $u=Ru=>{Au.callback(Ru),Ru.defaultPrevented||lo()};return jsxRuntimeExports.jsx(ButtonComponent,{title:Au.caption??Au.label,onClick:$u,variant:displayType2Class[Au.displayType??"default"],size:"small",children:Au.label})}function createContent(Au,lo,$u){return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("div",{className:"jp-toast-message",children:Au.split(`
2095
2095
  `).map((Ru,Iu)=>jsxRuntimeExports.jsxs(vM.Fragment,{children:[Iu>0?jsxRuntimeExports.jsx("br",{}):null,Ru]},`part-${Iu}`))}),($u?.length??0)>0&&jsxRuntimeExports.jsxs("div",{className:"jp-toast-buttonBar",children:[jsxRuntimeExports.jsx("div",{className:"jp-toast-spacer"}),$u.map((Ru,Iu)=>jsxRuntimeExports.jsx(vM.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(JupyterReactTheme,{children:jsxRuntimeExports.jsx(ToastButton,{action:Ru,closeToast:lo})})},"button-"+Iu))]})]})}const useToast=()=>{const Au=isInsideJupyterLab();return Object.freeze({enqueueToast:(Ru,Iu={variant:"info"})=>{const{actions:Pu,autoClose:Ou}=Iu,Mu=resolveToastTheme();switch(Iu.variant){case"info":return Au&&NotificationApi?NotificationApi.info(Ru,{autoClose:Ou??5e3,actions:Pu}):y$6.info(({closeToast:Du})=>createContent(Ru,()=>{Du&&Du()},Pu),{autoClose:Ou,position:TOAST_POSITION,theme:Mu});case"success":return Au&&NotificationApi?NotificationApi.success(Ru,{autoClose:Ou??5e3,actions:Pu}):y$6.success(({closeToast:Du})=>createContent(Ru,()=>{Du&&Du()},Pu),{autoClose:Ou,position:TOAST_POSITION,theme:Mu});case"warning":return Au&&NotificationApi?NotificationApi.warning(Ru,{autoClose:Ou??!1,actions:Pu}):y$6.warning(({closeToast:Du})=>createContent(Ru,()=>{Du&&Du()},Pu),{autoClose:Ou??!1,position:TOAST_POSITION,theme:Mu});case"error":return Au&&NotificationApi?NotificationApi.error(Ru,{autoClose:Ou??!1,actions:Pu}):y$6.error(({closeToast:Du})=>createContent(Ru,()=>{Du&&Du()},Pu),{autoClose:Ou??!1,position:TOAST_POSITION,theme:Mu})}},dismiss:Ru=>{Au&&NotificationApi?NotificationApi.dismiss(Ru):y$6.dismiss(Ru)},trackAsyncTask:(Ru,Iu)=>{const Pu=resolveToastTheme();return Au&&NotificationApi?NotificationApi.promise(Ru,Iu):y$6.promise(Ru,{error:{render:Iu.error.message,...Iu.error.options},pending:Iu.pending.message,success:{render:Iu.success.message,...Iu.success.options}},{position:TOAST_POSITION,theme:Pu,...Iu.pending.options})}})},PUBLIC_PATH_PREFIXES=["/about","/agents","/agentspecs","/aws/marketplace","/blog","/careers","/community","/compare","/connect","/contact","/dataliens","/docs","/events","/features","/gallery","/integrations","/join/confirm/user","/library","/outbounds/contacts/unsubscribe","/outbounds/invites/pages","/outbounds/invites/unsubscribe","/outbounds/users/unsubscribe","/partners","/password","/pricing","/privacy","/public","/releases","/reports","/research","/search","/settings/agentspecs","/signup/confirm/user","/support","/team","/terms","/testimonials","/trust","/tutorials","/usecases","/use-cases"],normalizePathname=Au=>((Au||"").split("?")[0]?.split("#")[0]||"/").trim().toLowerCase().replace(/\/+$/,"")||"/",isPublicPath=Au=>{const lo=normalizePathname(Au);return PUBLIC_PATH_PREFIXES.some($u=>lo===$u||lo.startsWith(`${$u}/`))};function useDatalayer(Au={}){const{loginRoute:lo="/login",notifyOnError:$u=!0}=Au,Ru=useLocation(),Iu=Lu=>{if(Lu!=="/login")return Lu;const Bu=Ru.pathname||"",ju="/jupyter/kernels",Fu="/jupyter/iam";if(Bu.includes(ju)){const[zu]=Bu.split(ju);return`${zu}${ju}/login`}if(Bu.includes(Fu)){const[zu]=Bu.split(Fu);return`${zu}${Fu}/login`}return Lu},{enqueueToast:Pu}=useToast(),Ou=useIAMStore(),Mu=useNavigate();return{requestDatalayer:async Lu=>{const{loginRoute:Bu=lo,notifyOnError:ju=$u,...Fu}=Lu,zu=Fu.token??Ou.token;return requestDatalayerAPI({...Fu,token:zu}).then(Uu=>Uu).catch(Uu=>{if(Uu.name==="RunResponseError"){const Hu=Uu,Vu=Hu.response.status===403;if(Hu.response.status===401){console.log("Datalayer sent a 401 return code.");const Wu=Iu(Bu),Ku=isPublicPath(Ru.pathname||"");!(Ru.pathname===Wu||Ru.pathname.endsWith("/login"))&&!Ku&&(Ou.logout(),Mu(Wu))}else ju&&!Vu&&(Hu.warnings&&Hu.warnings.forEach(Wu=>Pu(`${Wu}`,{variant:"warning"})),Hu.errors&&Hu.errors.forEach(Wu=>Pu(`${Wu}`,{variant:"error"})),Hu.message?Pu(`${Hu.message}`,{variant:"error"}):Pu("API Error",{variant:"error"}),Hu.exceptionMessage&&Pu(`${Hu.exceptionMessage}`,{variant:"error"}));return{success:!1,sucess:!1,message:Hu.message,errors:Hu.errors,warnings:Hu.warnings,detail:Hu.detail,status:Hu.response.status,code:Hu.response.status===403?"FORBIDDEN":`HTTP_${Hu.response.status}`}}throw console.log("Error",Uu),ju&&Pu(`${Uu.message}`,{variant:"error"}),Uu})}}}const API_BASE_PATHS={AI_AGENTS:"/api/ai-agents/v1",CONTENTS:"/api/contents/v1",IAM:"/api/iam/v1",MCP:"/api/mcp/v1",OTEL:"/api/otel/v1",RUNTIMES:"/api/runtimes/v1",SCHEDULER:"/api/scheduler/v1",SPACER:"/api/spacer/v1"},DEFAULT_SERVICE_URLS={AI_AGENTS:"https://r1.datalayer.run",RUNTIMES:"https://r1.datalayer.run"};function isMacOS(){return typeof navigator>"u"?!1:/Mac|iPod|iPhone|iPad/.test(navigator.platform)}function useKeyboardShortcuts({enabled:Au=!0,shortcuts:lo}){const $u=reactExports.useCallback(Ru=>{if(!Au)return;const Iu=Ru.target,Pu=Iu.tagName==="INPUT"||Iu.tagName==="SELECT"||Iu.tagName==="TEXTAREA"||Iu.isContentEditable;for(const Ou of lo){if(Pu&&!Ou.allowInInput&&Ou.key!=="Escape"||Ru.key.toLowerCase()!==Ou.key.toLowerCase())continue;const Mu=isMacOS()?Ru.metaKey:Ru.ctrlKey;if(!(Ou.ctrlOrCmd&&!Mu)&&!(!Ou.ctrlOrCmd&&Mu&&Ou.key!=="Escape")&&!(Ou.shift&&!Ru.shiftKey)&&!(Ou.alt&&!Ru.altKey)){Ru.preventDefault(),Ru.stopPropagation(),Ou.handler();break}}},[Au,lo]);reactExports.useEffect(()=>{if(Au)return document.addEventListener("keydown",$u),()=>{document.removeEventListener("keydown",$u)}},[Au,$u])}function useChatKeyboardShortcuts({onToggle:Au,onNewChat:lo,onClear:$u,onFocusInput:Ru,enabled:Iu=!0}){const Pu=[];Au&&Pu.push({key:"k",ctrlOrCmd:!0,handler:Au,description:"Toggle chat sidebar"}),lo&&Pu.push({key:"n",ctrlOrCmd:!0,shift:!0,handler:lo,description:"Start new chat"}),$u&&Pu.push({key:"Backspace",ctrlOrCmd:!0,shift:!0,handler:$u,description:"Clear chat messages"}),Ru&&Pu.push({key:"/",handler:Ru,description:"Focus chat input"}),Au&&Pu.push({key:"Escape",handler:Au,description:"Close chat sidebar",allowInInput:!0}),useKeyboardShortcuts({enabled:Iu,shortcuts:Pu})}function getShortcutDisplay(Au){const lo=[],$u=isMacOS();lo.push($u?"⌘":"Ctrl"),Au.shift&&lo.push($u?"⇧":"Shift"),Au.alt&&lo.push($u?"⌥":"Alt");let Ru=Au.key.toUpperCase();return Au.key==="Escape"&&(Ru="Esc"),Au.key==="Backspace"&&(Ru=$u?"⌫":"Del"),lo.push(Ru),lo.join($u?"":"+")}const __vite_import_meta_env__={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1},trackedConnections=new Map,getTrackedConnectionState=Au=>{const lo=trackedConnections.get(Au);return lo?Object.fromEntries(Object.entries(lo.stores).map(([$u,Ru])=>[$u,Ru.getState()])):{}},extractConnectionInformation=(Au,lo,$u)=>{if(Au===void 0)return{type:"untracked",connection:lo.connect($u)};const Ru=trackedConnections.get($u.name);if(Ru)return{type:"tracked",store:Au,...Ru};const Iu={connection:lo.connect($u),stores:{}};return trackedConnections.set($u.name,Iu),{type:"tracked",store:Au,...Iu}},devtoolsImpl=(Au,lo={})=>($u,Ru,Iu)=>{const{enabled:Pu,anonymousActionType:Ou,store:Mu,...Du}=lo;let Lu;try{Lu=(Pu??(__vite_import_meta_env__?"production":void 0)!=="production")&&window.__REDUX_DEVTOOLS_EXTENSION__}catch{}if(!Lu)return(__vite_import_meta_env__?"production":void 0)!=="production"&&Pu&&console.warn("[zustand devtools middleware] Please install/enable Redux devtools extension"),Au($u,Ru,Iu);const{connection:Bu,...ju}=extractConnectionInformation(Mu,Lu,Du);let Fu=!0;Iu.setState=(Hu,Vu,Gu)=>{const Wu=$u(Hu,Vu);if(!Fu)return Wu;const Ku=Gu===void 0?{type:Ou||"anonymous"}:typeof Gu=="string"?{type:Gu}:Gu;return Mu===void 0?(Bu?.send(Ku,Ru()),Wu):(Bu?.send({...Ku,type:`${Mu}/${Ku.type}`},{...getTrackedConnectionState(Du.name),[Mu]:Iu.getState()}),Wu)};const zu=(...Hu)=>{const Vu=Fu;Fu=!1,$u(...Hu),Fu=Vu},Uu=Au(Iu.setState,Ru,Iu);if(ju.type==="untracked"?Bu?.init(Uu):(ju.stores[ju.store]=Iu,Bu?.init(Object.fromEntries(Object.entries(ju.stores).map(([Hu,Vu])=>[Hu,Hu===ju.store?Uu:Vu.getState()])))),Iu.dispatchFromDevtools&&typeof Iu.dispatch=="function"){let Hu=!1;const Vu=Iu.dispatch;Iu.dispatch=(...Gu)=>{(__vite_import_meta_env__?"production":void 0)!=="production"&&Gu[0].type==="__setState"&&!Hu&&(console.warn('[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'),Hu=!0),Vu(...Gu)}}return Bu.subscribe(Hu=>{var Vu;switch(Hu.type){case"ACTION":if(typeof Hu.payload!="string"){console.error("[zustand devtools middleware] Unsupported action format");return}return parseJsonThen(Hu.payload,Gu=>{if(Gu.type==="__setState"){if(Mu===void 0){zu(Gu.state);return}Object.keys(Gu.state).length!==1&&console.error(`
2096
2096
  [zustand devtools middleware] Unsupported __setState action format.
2097
2097
  When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),
@@ -3634,10 +3634,10 @@ ${expandCompactMarkdownTableBody(Iu.trim())}
3634
3634
  ${Pu.trim()}
3635
3635
 
3636
3636
  `:`\`\`\`${Ru}
3637
- ${Pu}\`\`\``}),lo}function ChatMarkdown({text:Au,density:lo="comfortable"}){return jsxRuntimeExports.jsx(Box,{"data-chat-markdown":"",sx:{...streamdownMarkdownStyles,...lo==="compact"?{lineHeight:1.4,"& p":{marginTop:0,marginBottom:"0.4em"},"& p:last-child":{marginBottom:0}}:{}},children:jsxRuntimeExports.jsx(_o$1,{rehypePlugins:REHYPE_PLUGINS_WITHOUT_HTML,children:normalizeAssistantMarkdown(Au)})})}const ICON_PACKAGES=["@datalayer/icons-react","@primer/octicons-react"],ICON_REF=/^(@datalayer\/icons-react|@primer\/octicons-react):([a-z0-9]+(?:-[a-z0-9]+)*)$/;function exportNameOf(Au){return Au.split("-").map(lo=>lo.charAt(0).toUpperCase()+lo.slice(1)).join("")+"Icon"}function parseIconRef(Au){const lo=ICON_REF.exec(Au);if(!lo)throw new Error(`The icon ${JSON.stringify(Au)} is not <package>:<name>, the package one of ${ICON_PACKAGES.join(", ")} and the name in kebab case`);const[,$u,Ru]=lo;return{pkg:$u,name:Ru,exportName:exportNameOf(Ru)}}const LOADERS={"@datalayer/icons-react":()=>__vitePreload(()=>import("./chunks/index.esm-z-R1Ypx2.js"),[],import.meta.url),"@primer/octicons-react":()=>__vitePreload(()=>import("./chunks/index.esm-p0OnSU9h.js"),[],import.meta.url)},loaded=new Map,loading=new Map;function loadIconPackage(Au){const lo=loading.get(Au)??LOADERS[Au]().then($u=>(loaded.set(Au,$u),$u));return loading.set(Au,lo),lo}function iconOf(Au,lo){const $u=lo[Au.exportName];if(!$u)throw new Error(`${Au.pkg} has no icon ${Au.name} (${Au.exportName}): name one it has`);return $u}function useMarkIcon(Au){const lo=Au?parseIconRef(Au):void 0,$u=lo?.pkg,Ru=$u?loaded.get($u):void 0,[,Iu]=reactExports.useState(0),[Pu,Ou]=reactExports.useState(null);if(reactExports.useEffect(()=>{if(!$u||Ru)return;let Mu=!0;return loadIconPackage($u).then(()=>Mu&&Iu(Du=>Du+1),Du=>Mu&&Ou(Du)),()=>{Mu=!1}},[$u,Ru]),Pu)throw Pu;return lo&&Ru?iconOf(lo,Ru):void 0}function SpecMark({icon:Au,emoji:lo,size:$u=16}){const Ru=useMarkIcon(Au);return Au?Ru?jsxRuntimeExports.jsx("span",{"data-mark":Au,style:{display:"inline-flex",flexShrink:0,lineHeight:0},children:jsxRuntimeExports.jsx(Ru,{size:$u,"aria-hidden":"true",...Au.startsWith("@datalayer/icons-react:")?{colored:!0}:{}})}):jsxRuntimeExports.jsx("span",{"data-mark":Au,"aria-hidden":"true",style:{display:"inline-block",width:$u,height:$u}}):lo?jsxRuntimeExports.jsx("span",{"data-mark":"emoji","aria-hidden":"true",style:{display:"inline-flex",flexShrink:0,fontSize:Math.round($u*.9),lineHeight:1},children:lo}):null}function hasMark(Au){return!!(Au?.icon||Au?.emoji)}const SKILL_TOOLS=new Set(["run_skill_script","load_skill","read_skill_resource"]);function marksOf(Au){return{icon:Au?.icon,emoji:Au?.emoji}}function skillIdOfCall(Au,lo){if(!SKILL_TOOLS.has(Au))return null;const $u=lo?.skill_name??lo?.skill??lo?.name;return typeof $u!="string"||$u.length===0?null:$u.split(":",1)[0]||$u}let frontendIndex=null,runtimeIndex=null;function frontendTools(){if(!frontendIndex){frontendIndex=new Map;for(const Au of Object.values(FRONTEND_TOOL_CATALOG))for(const lo of Au.toolset??[])frontendIndex.has(lo)||frontendIndex.set(lo,{id:Au.id,...marksOf(Au)})}return frontendIndex}function runtimeTools(){if(!runtimeIndex){runtimeIndex=new Map;for(const Au of Object.values(BACKEND_TOOL_CATALOG)){const lo=Au.runtime?.method;lo&&!runtimeIndex.has(lo)&&runtimeIndex.set(lo,{id:Au.id,...marksOf(Au)})}}return runtimeIndex}function marksOfMcpServer(Au){return Au.icon||Au.emoji?marksOf(Au):marksOf(MCP_SERVER_LIBRARY[Au.id])}function marksOfSkill(Au){return marksOf(SKILLS_CATALOG[Au.split(":",1)[0]||Au])}function marksOfFrontendTool(Au){return marksOf(frontendTools().get(Au))}function marksOfRuntimeTool(Au){return marksOf(runtimeTools().get(Au))}function marksOfToolCall(Au,lo,$u=[]){const Ru=skillIdOfCall(Au,lo);if(Ru)return{kind:"skill",ownerId:Ru,...marksOfSkill(Ru)};const Iu=$u.find(Mu=>Mu.tools.some(Du=>Du.name===Au));if(Iu)return{kind:"mcp",ownerId:Iu.id,...marksOfMcpServer(Iu)};const Pu=frontendTools().get(Au);if(Pu)return{kind:"frontend",ownerId:Pu.id,...marksOf(Pu)};const Ou=runtimeTools().get(Au);return Ou?{kind:"runtime",ownerId:Ou.id,...marksOf(Ou)}:null}function getStatusDisplay(Au,lo,$u){switch(Au){case"inProgress":return{icon:jsxRuntimeExports.jsx(ClockIcon,{size:14}),color:"attention.fg",label:$u.toolPreparing,bgColor:"attention.subtle"};case"executing":return{icon:jsxRuntimeExports.jsx(ClockIcon,{size:14}),color:"attention.fg",label:$u.toolExecuting,bgColor:"attention.subtle"};case"complete":return{icon:jsxRuntimeExports.jsx(CheckCircleIcon,{size:14}),color:"success.fg",label:$u.toolComplete,bgColor:"success.subtle"};case"error":return lo==="execution"?{icon:jsxRuntimeExports.jsx(AlertIcon,{size:14}),color:"danger.fg",label:$u.toolExecutionFailed,bgColor:"danger.subtle"}:lo==="code"?{icon:jsxRuntimeExports.jsx(XCircleIcon,{size:14}),color:"severe.fg",label:$u.toolCodeError,bgColor:"severe.subtle"}:lo==="exit"?{icon:jsxRuntimeExports.jsx(AlertIcon,{size:14}),color:"attention.fg",label:$u.toolExited,bgColor:"attention.subtle"}:{icon:jsxRuntimeExports.jsx(XCircleIcon,{size:14}),color:"danger.fg",label:$u.toolFailed,bgColor:"danger.subtle"};default:return{icon:jsxRuntimeExports.jsx(ToolsIcon,{size:14}),color:"fg.muted",label:Au,bgColor:"neutral.subtle"}}}function formatToolName(Au){return Au.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").split(" ").map(lo=>lo.charAt(0).toUpperCase()+lo.slice(1).toLowerCase()).join(" ")}function getArgsSummary(Au,lo){const $u=Object.entries(Au);if($u.length===0)return lo.noParameters;const Ru=$u.slice(0,2).map(([Iu,Pu])=>{const Ou=typeof Pu=="string"?Pu.slice(0,30)+(Pu.length>30?"...":""):typeof Pu=="object"?JSON.stringify(Pu).slice(0,30)+"...":String(Pu);return`${Iu}: ${Ou}`}).join(", ");return $u.length>2?`${Ru} ${lo.moreArguments($u.length-2)}`:Ru}function ToolCallDisplay({toolCallId:Au,toolName:lo,args:$u,result:Ru,status:Iu,error:Pu,executionResult:Ou,codeError:Mu,exitCode:Du,executionError:Lu,approvalRequired:Bu=!1,approvalState:ju,approvalDecisionSource:Fu,onApprove:zu,onDeny:Uu,approvalLoading:Hu=!1,marks:Vu,summary:Gu,density:Wu="comfortable"}){const Ku=useChatWords(),Ju=Wu==="compact",[Yu,Xu]=reactExports.useState(!1),ed=Du??Ou?.exit_code,td=ed!=null&&ed!==0,nd=Iu==="error"?Lu||Ou?.execution_error?"execution":Mu||Ou?.code_error?"code":td?"exit":"unknown":void 0,od=getStatusDisplay(Iu,nd,Ku),sd=formatToolName(lo),ad=Gu||getArgsSummary($u,Ku),gd=ju==="pending"||Iu==="inProgress"&&(Ru&&typeof Ru=="object"?Ru:void 0)?.pending_approval===!0;reactExports.useEffect(()=>{gd&&Xu(!0)},[gd]);const xd=Mu||Ou?.code_error||void 0,yd=Lu||Ou?.execution_error||void 0,vd=Pu||Ou?.error||yd||void 0,Td=Ou?.output??(typeof Ru=="string"?Ru:Ru!=null&&typeof Ru=="object"?Ru.output??Ru.stdout??Ru.stderr??void 0:void 0);return jsxRuntimeExports.jsxs(Box,{"data-tool-call":lo,"data-tool-call-status":Iu,width:"100%",border:"1px solid",borderColor:"border.default",borderRadius:Ju?"8px":"12px",overflow:"hidden",backgroundColor:"canvas.default",children:[jsxRuntimeExports.jsxs(Box,{as:"button",onClick:()=>Xu(!Yu),width:"100%",display:"flex",alignItems:"center",gap:Ju?1:2,padding:Ju?1:2,backgroundColor:"canvas.subtle",border:"none",borderBottom:Yu?"1px solid":"none",borderColor:"border.default",cursor:"pointer",textAlign:"left",hover:{backgroundColor:"neutral.muted"},children:[jsxRuntimeExports.jsx(Box,{color:"fg.muted",flexShrink:0,children:Yu?jsxRuntimeExports.jsx(ChevronDownIcon,{size:16}):jsxRuntimeExports.jsx(ChevronRightIcon,{size:16})}),hasMark(Vu)&&jsxRuntimeExports.jsx(Box,{color:"fg.muted",flexShrink:0,display:"flex",children:jsxRuntimeExports.jsx(SpecMark,{icon:Vu?.icon,emoji:Vu?.emoji,size:16})}),jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold",fontSize:Ju?0:1,color:"fg.default",flexShrink:0},children:sd}),jsxRuntimeExports.jsxs(Box,{display:"inline-flex",alignItems:"center",gap:1,px:2,py:"2px",borderRadius:2,backgroundColor:od.bgColor,flexShrink:0,children:[jsxRuntimeExports.jsx(Box,{color:od.color,display:"flex",children:od.icon}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,fontWeight:"medium",color:od.color},children:gd?Ku.awaitingApproval:od.label})]}),!Yu&&jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:ad})]}),Yu&&jsxRuntimeExports.jsxs(Box,{p:3,children:[jsxRuntimeExports.jsxs(Box,{mb:Ru!==void 0||Pu?3:0,children:[jsxRuntimeExports.jsx(Text$3,{sx:{display:"block",fontSize:0,fontWeight:"semibold",color:"fg.muted",textTransform:"uppercase",letterSpacing:"0.05em",mb:2},children:Ku.parameters}),jsxRuntimeExports.jsx(Box,{backgroundColor:"canvas.inset",borderRadius:2,border:"1px solid",borderColor:"border.default",overflow:"auto",maxHeight:"200px",children:jsxRuntimeExports.jsx("pre",{style:{margin:0,padding:"12px",fontSize:"12px",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:Object.keys($u).length>0?JSON.stringify($u,null,2):`(${Ku.noParameters})`})})]}),(Iu==="complete"||Iu==="executing")&&Ru!==void 0&&jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{display:"block",fontSize:0,fontWeight:"semibold",color:"success.fg",textTransform:"uppercase",letterSpacing:"0.05em",mb:2},children:Ku.result}),jsxRuntimeExports.jsx(Box,{backgroundColor:"success.subtle",borderRadius:2,border:"1px solid",borderColor:"success.muted",overflow:"auto",maxHeight:"300px",children:jsxRuntimeExports.jsx("pre",{style:{margin:0,padding:"12px",fontSize:"12px",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:typeof Ru=="string"?Ru:JSON.stringify(Ru,null,2)})})]}),Bu&&jsxRuntimeExports.jsx(Box,{mt:Iu==="complete"&&Ru!==void 0?3:0,children:ju==="approved"?jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{color:"success.fg",fontSize:1,display:"block"},children:Ku.approvedRunning}),Fu==="external"&&jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontSize:0,display:"block"},children:Ku.approvedElsewhere})]}):ju==="denied"?jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{color:"danger.fg",fontSize:1,display:"block"},children:Ku.deniedWontRun}),Fu==="external"&&jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontSize:0,display:"block"},children:Ku.decidedElsewhere})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,color:"fg.default"},children:Ku.approvalNeeded}),jsxRuntimeExports.jsxs(Box,{mt:2,display:"flex",gap:2,children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",onClick:zu,disabled:Hu||!zu,children:Ku.approve}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"danger",onClick:Uu,disabled:Hu||!Uu,children:Ku.deny})]})]})}),Iu==="error"&&yd&&jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsxs(Text$3,{sx:{display:"block",fontSize:0,fontWeight:"semibold",color:"danger.fg",textTransform:"uppercase",letterSpacing:"0.05em",mb:2},children:[jsxRuntimeExports.jsx(AlertIcon,{size:12})," ",Ku.executionError]}),jsxRuntimeExports.jsxs(Box,{backgroundColor:"danger.subtle",borderRadius:2,border:"1px solid",borderColor:"danger.muted",p:2,children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,color:"danger.fg"},children:yd}),jsxRuntimeExports.jsx(Text$3,{sx:{display:"block",fontSize:0,color:"fg.muted",mt:1},children:Ku.executionErrorWhy})]})]}),Iu==="error"&&xd&&jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsxs(Text$3,{sx:{display:"block",fontSize:0,fontWeight:"semibold",color:"severe.fg",textTransform:"uppercase",letterSpacing:"0.05em",mb:2},children:[Ku.toolCodeError,": ",xd.name]}),jsxRuntimeExports.jsxs(Box,{backgroundColor:"severe.subtle",borderRadius:2,border:"1px solid",borderColor:"severe.muted",overflow:"hidden",children:[jsxRuntimeExports.jsx(Box,{p:2,children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,color:"severe.fg"},children:xd.value})}),xd.traceback&&jsxRuntimeExports.jsx(Box,{borderTop:"1px solid",borderColor:"severe.muted",backgroundColor:"canvas.inset",children:jsxRuntimeExports.jsx("pre",{style:{margin:0,padding:"8px 12px",fontSize:"11px",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',lineHeight:1.4,whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:"200px",overflow:"auto"},children:xd.traceback})})]})]}),Iu==="error"&&vd&&!yd&&!xd&&!td&&jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{display:"block",fontSize:0,fontWeight:"semibold",color:"danger.fg",textTransform:"uppercase",letterSpacing:"0.05em",mb:2},children:Ku.errorHeading}),jsxRuntimeExports.jsx(Box,{backgroundColor:"danger.subtle",borderRadius:2,border:"1px solid",borderColor:"danger.muted",p:2,children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,color:"danger.fg"},children:vd})})]}),td&&!yd&&!xd&&jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsxs(Text$3,{sx:{display:"block",fontSize:0,fontWeight:"semibold",color:"attention.fg",textTransform:"uppercase",letterSpacing:"0.05em",mb:2},children:[jsxRuntimeExports.jsx(AlertIcon,{size:12})," ",Ku.processExited]}),jsxRuntimeExports.jsxs(Box,{backgroundColor:"attention.subtle",borderRadius:2,border:"1px solid",borderColor:"attention.muted",p:2,children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,color:"attention.fg"},children:Ku.exitedWithCode(String(ed))}),jsxRuntimeExports.jsx(Text$3,{sx:{display:"block",fontSize:0,color:"fg.muted",mt:1},children:Ku.nonZeroExit})]}),Td&&jsxRuntimeExports.jsx(Box,{mt:2,backgroundColor:"canvas.inset",borderRadius:2,border:"1px solid",borderColor:"attention.muted",overflow:"auto",children:jsxRuntimeExports.jsx("pre",{style:{margin:0,padding:"10px 12px",fontSize:"12px",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',lineHeight:1.4,whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:"200px"},children:Td})})]}),jsxRuntimeExports.jsx(Box,{mt:3,pt:2,borderTop:"1px solid",borderColor:"border.muted",children:jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"fg.subtle",fontFamily:"monospace"},children:["ID: ",Au]})})]})]})}function TypingDots({size:Au=8}){return jsxRuntimeExports.jsx(Box,{"aria-hidden":"true","data-typing-dots":"",display:"inline-flex",alignItems:"center",gap:"4px",children:[0,.2,.4].map((lo,$u)=>jsxRuntimeExports.jsx(Box,{width:Au,height:Au,borderRadius:"50%",bg:"fg.muted",animation:"typingPulse 1.4s ease-in-out infinite",animationDelay:`${lo}s`,reducedMotion:{animation:"none",opacity:.7},sx:{"@keyframes typingPulse":{"0%, 60%, 100%":{transform:"scale(0.6)",opacity:.4},"30%":{transform:"scale(1)",opacity:1}}}},$u))})}function TurnFooter({usage:Au,live:lo,latest:$u,padding:Ru,onCopy:Iu,onRemove:Pu}){const Ou=useChatWords(),[Mu,Du]=reactExports.useState(!1),Lu=reactExports.useRef(null);reactExports.useEffect(()=>()=>{Lu.current!==null&&window.clearTimeout(Lu.current)},[]);const Bu=Au?{contextTokens:Au.totalTokens,contextWindow:Au.contextWindow,inputTokens:Au.turnUsage?.inputTokens??0,outputTokens:Au.turnUsage?.outputTokens??0}:null,ju=reactExports.useRef(null),[Fu,zu]=reactExports.useState(null);reactExports.useEffect(()=>{(lo||$u)&&Bu?ju.current=Bu:!lo&&!$u&&!Fu&&ju.current&&zu(ju.current)});const Uu=lo||$u?Bu:Fu;if(!Uu&&lo)return null;const Hu=async()=>{await Iu(),Du(!0),Lu.current!==null&&window.clearTimeout(Lu.current),Lu.current=window.setTimeout(()=>Du(!1),1500)};return jsxRuntimeExports.jsxs(Box,{"data-turn-footer":"",display:"flex",alignItems:"center",gap:1,px:Ru,mt:-1,pb:1,minHeight:24,sx:{opacity:.55,transition:"opacity 0.15s ease","&:hover, &:focus-within":{opacity:1},"& [data-turn-actions]":{opacity:0,transition:"opacity 0.15s ease"},"&:hover [data-turn-actions], &:focus-within [data-turn-actions]":{opacity:1}},children:[Uu&&jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"fg.muted",flexShrink:0},children:[jsxRuntimeExports.jsx(Text$3,{as:"span",sx:{fontWeight:"semibold",color:"fg.default",fontSize:0},children:formatTokenCount(Uu.contextTokens)})," / ",formatTokenCount(Uu.contextWindow)," ctx · turn ",formatTokenCount(Uu.inputTokens),jsxRuntimeExports.jsx(Text$3,{as:"span",sx:{color:"success.fg",fontSize:0},children:"▲"})," ",formatTokenCount(Uu.outputTokens),jsxRuntimeExports.jsx(Text$3,{as:"span",sx:{color:"attention.fg",fontSize:0},children:"▼"})]}),!lo&&jsxRuntimeExports.jsxs(Box,{"data-turn-actions":"",display:"flex",alignItems:"center",children:[jsxRuntimeExports.jsx(IconButton,{"data-turn-copy":"",icon:Mu?CheckIcon:CopyIcon,"aria-label":Ou.copyTurn,size:"small",variant:"invisible",onClick:()=>{Hu()}}),jsxRuntimeExports.jsx(IconButton,{"data-turn-remove":"",icon:TrashIcon,"aria-label":Ou.removeTurn,size:"small",variant:"invisible",onClick:Pu})]})]})}const FORM_SUBMISSION_LANGUAGE="a2ui-submission",FENCE=new RegExp("```"+FORM_SUBMISSION_LANGUAGE+"\\s*\\n([\\s\\S]*?)\\n```");function encodeFormSubmission(Au){const lo=JSON.stringify(Au,null,2);return`I just submitted "${Au.title}".
3637
+ ${Pu}\`\`\``}),lo}function ChatMarkdown({text:Au,density:lo="comfortable"}){return jsxRuntimeExports.jsx(Box,{"data-chat-markdown":"",sx:{...streamdownMarkdownStyles,...lo==="compact"?{lineHeight:1.4,"& p":{marginTop:0,marginBottom:"0.4em"},"& p:last-child":{marginBottom:0}}:{}},children:jsxRuntimeExports.jsx(_o$1,{rehypePlugins:REHYPE_PLUGINS_WITHOUT_HTML,children:normalizeAssistantMarkdown(Au)})})}const ICON_PACKAGES=["@datalayer/icons-react","@primer/octicons-react"],ICON_REF=/^(@datalayer\/icons-react|@primer\/octicons-react):([a-z0-9]+(?:-[a-z0-9]+)*)$/;function exportNameOf(Au){return Au.split("-").map(lo=>lo.charAt(0).toUpperCase()+lo.slice(1)).join("")+"Icon"}function parseIconRef(Au){const lo=ICON_REF.exec(Au);if(!lo)throw new Error(`The icon ${JSON.stringify(Au)} is not <package>:<name>, the package one of ${ICON_PACKAGES.join(", ")} and the name in kebab case`);const[,$u,Ru]=lo;return{pkg:$u,name:Ru,exportName:exportNameOf(Ru)}}const LOADERS={"@datalayer/icons-react":()=>__vitePreload(()=>import("./chunks/index.esm-z-R1Ypx2.js"),[],import.meta.url),"@primer/octicons-react":()=>__vitePreload(()=>import("./chunks/index.esm-nZym6gpK.js"),[],import.meta.url)},loaded=new Map,loading=new Map;function loadIconPackage(Au){const lo=loading.get(Au)??LOADERS[Au]().then($u=>(loaded.set(Au,$u),$u));return loading.set(Au,lo),lo}function iconOf(Au,lo){const $u=lo[Au.exportName];if(!$u)throw new Error(`${Au.pkg} has no icon ${Au.name} (${Au.exportName}): name one it has`);return $u}function useMarkIcon(Au){const lo=Au?parseIconRef(Au):void 0,$u=lo?.pkg,Ru=$u?loaded.get($u):void 0,[,Iu]=reactExports.useState(0),[Pu,Ou]=reactExports.useState(null);if(reactExports.useEffect(()=>{if(!$u||Ru)return;let Mu=!0;return loadIconPackage($u).then(()=>Mu&&Iu(Du=>Du+1),Du=>Mu&&Ou(Du)),()=>{Mu=!1}},[$u,Ru]),Pu)throw Pu;return lo&&Ru?iconOf(lo,Ru):void 0}function SpecMark({icon:Au,emoji:lo,size:$u=16}){const Ru=useMarkIcon(Au);return Au?Ru?jsxRuntimeExports.jsx("span",{"data-mark":Au,style:{display:"inline-flex",flexShrink:0,lineHeight:0},children:jsxRuntimeExports.jsx(Ru,{size:$u,"aria-hidden":"true",...Au.startsWith("@datalayer/icons-react:")?{colored:!0}:{}})}):jsxRuntimeExports.jsx("span",{"data-mark":Au,"aria-hidden":"true",style:{display:"inline-block",width:$u,height:$u}}):lo?jsxRuntimeExports.jsx("span",{"data-mark":"emoji","aria-hidden":"true",style:{display:"inline-flex",flexShrink:0,fontSize:Math.round($u*.9),lineHeight:1},children:lo}):null}function hasMark(Au){return!!(Au?.icon||Au?.emoji)}const SKILL_TOOLS=new Set(["run_skill_script","load_skill","read_skill_resource"]);function marksOf(Au){return{icon:Au?.icon,emoji:Au?.emoji}}function skillIdOfCall(Au,lo){if(!SKILL_TOOLS.has(Au))return null;const $u=lo?.skill_name??lo?.skill??lo?.name;return typeof $u!="string"||$u.length===0?null:$u.split(":",1)[0]||$u}let frontendIndex=null,runtimeIndex=null;function frontendTools(){if(!frontendIndex){frontendIndex=new Map;for(const Au of Object.values(FRONTEND_TOOL_CATALOG))for(const lo of Au.toolset??[])frontendIndex.has(lo)||frontendIndex.set(lo,{id:Au.id,...marksOf(Au)})}return frontendIndex}function runtimeTools(){if(!runtimeIndex){runtimeIndex=new Map;for(const Au of Object.values(BACKEND_TOOL_CATALOG)){const lo=Au.runtime?.method;lo&&!runtimeIndex.has(lo)&&runtimeIndex.set(lo,{id:Au.id,...marksOf(Au)})}}return runtimeIndex}function marksOfMcpServer(Au){return Au.icon||Au.emoji?marksOf(Au):marksOf(MCP_SERVER_LIBRARY[Au.id])}function marksOfSkill(Au){return marksOf(SKILLS_CATALOG[Au.split(":",1)[0]||Au])}function marksOfFrontendTool(Au){return marksOf(frontendTools().get(Au))}function marksOfRuntimeTool(Au){return marksOf(runtimeTools().get(Au))}function marksOfToolCall(Au,lo,$u=[]){const Ru=skillIdOfCall(Au,lo);if(Ru)return{kind:"skill",ownerId:Ru,...marksOfSkill(Ru)};const Iu=$u.find(Mu=>Mu.tools.some(Du=>Du.name===Au));if(Iu)return{kind:"mcp",ownerId:Iu.id,...marksOfMcpServer(Iu)};const Pu=frontendTools().get(Au);if(Pu)return{kind:"frontend",ownerId:Pu.id,...marksOf(Pu)};const Ou=runtimeTools().get(Au);return Ou?{kind:"runtime",ownerId:Ou.id,...marksOf(Ou)}:null}function getStatusDisplay(Au,lo,$u){switch(Au){case"inProgress":return{icon:jsxRuntimeExports.jsx(ClockIcon,{size:14}),color:"attention.fg",label:$u.toolPreparing,bgColor:"attention.subtle"};case"executing":return{icon:jsxRuntimeExports.jsx(ClockIcon,{size:14}),color:"attention.fg",label:$u.toolExecuting,bgColor:"attention.subtle"};case"complete":return{icon:jsxRuntimeExports.jsx(CheckCircleIcon,{size:14}),color:"success.fg",label:$u.toolComplete,bgColor:"success.subtle"};case"error":return lo==="execution"?{icon:jsxRuntimeExports.jsx(AlertIcon,{size:14}),color:"danger.fg",label:$u.toolExecutionFailed,bgColor:"danger.subtle"}:lo==="code"?{icon:jsxRuntimeExports.jsx(XCircleIcon,{size:14}),color:"severe.fg",label:$u.toolCodeError,bgColor:"severe.subtle"}:lo==="exit"?{icon:jsxRuntimeExports.jsx(AlertIcon,{size:14}),color:"attention.fg",label:$u.toolExited,bgColor:"attention.subtle"}:{icon:jsxRuntimeExports.jsx(XCircleIcon,{size:14}),color:"danger.fg",label:$u.toolFailed,bgColor:"danger.subtle"};default:return{icon:jsxRuntimeExports.jsx(ToolsIcon,{size:14}),color:"fg.muted",label:Au,bgColor:"neutral.subtle"}}}function formatToolName(Au){return Au.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").split(" ").map(lo=>lo.charAt(0).toUpperCase()+lo.slice(1).toLowerCase()).join(" ")}function getArgsSummary(Au,lo){const $u=Object.entries(Au);if($u.length===0)return lo.noParameters;const Ru=$u.slice(0,2).map(([Iu,Pu])=>{const Ou=typeof Pu=="string"?Pu.slice(0,30)+(Pu.length>30?"...":""):typeof Pu=="object"?JSON.stringify(Pu).slice(0,30)+"...":String(Pu);return`${Iu}: ${Ou}`}).join(", ");return $u.length>2?`${Ru} ${lo.moreArguments($u.length-2)}`:Ru}function ToolCallDisplay({toolCallId:Au,toolName:lo,args:$u,result:Ru,status:Iu,error:Pu,executionResult:Ou,codeError:Mu,exitCode:Du,executionError:Lu,approvalRequired:Bu=!1,approvalState:ju,approvalDecisionSource:Fu,onApprove:zu,onDeny:Uu,approvalLoading:Hu=!1,marks:Vu,summary:Gu,density:Wu="comfortable"}){const Ku=useChatWords(),Ju=Wu==="compact",[Yu,Xu]=reactExports.useState(!1),ed=Du??Ou?.exit_code,td=ed!=null&&ed!==0,nd=Iu==="error"?Lu||Ou?.execution_error?"execution":Mu||Ou?.code_error?"code":td?"exit":"unknown":void 0,od=getStatusDisplay(Iu,nd,Ku),sd=formatToolName(lo),ad=Gu||getArgsSummary($u,Ku),gd=ju==="pending"||Iu==="inProgress"&&(Ru&&typeof Ru=="object"?Ru:void 0)?.pending_approval===!0;reactExports.useEffect(()=>{gd&&Xu(!0)},[gd]);const xd=Mu||Ou?.code_error||void 0,yd=Lu||Ou?.execution_error||void 0,vd=Pu||Ou?.error||yd||void 0,Td=Ou?.output??(typeof Ru=="string"?Ru:Ru!=null&&typeof Ru=="object"?Ru.output??Ru.stdout??Ru.stderr??void 0:void 0);return jsxRuntimeExports.jsxs(Box,{"data-tool-call":lo,"data-tool-call-status":Iu,width:"100%",border:"1px solid",borderColor:"border.default",borderRadius:Ju?"8px":"12px",overflow:"hidden",backgroundColor:"canvas.default",children:[jsxRuntimeExports.jsxs(Box,{as:"button",onClick:()=>Xu(!Yu),width:"100%",display:"flex",alignItems:"center",gap:Ju?1:2,padding:Ju?1:2,backgroundColor:"canvas.subtle",border:"none",borderBottom:Yu?"1px solid":"none",borderColor:"border.default",cursor:"pointer",textAlign:"left",hover:{backgroundColor:"neutral.muted"},children:[jsxRuntimeExports.jsx(Box,{color:"fg.muted",flexShrink:0,children:Yu?jsxRuntimeExports.jsx(ChevronDownIcon,{size:16}):jsxRuntimeExports.jsx(ChevronRightIcon,{size:16})}),hasMark(Vu)&&jsxRuntimeExports.jsx(Box,{color:"fg.muted",flexShrink:0,display:"flex",children:jsxRuntimeExports.jsx(SpecMark,{icon:Vu?.icon,emoji:Vu?.emoji,size:16})}),jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold",fontSize:Ju?0:1,color:"fg.default",flexShrink:0},children:sd}),jsxRuntimeExports.jsxs(Box,{display:"inline-flex",alignItems:"center",gap:1,px:2,py:"2px",borderRadius:2,backgroundColor:od.bgColor,flexShrink:0,children:[jsxRuntimeExports.jsx(Box,{color:od.color,display:"flex",children:od.icon}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,fontWeight:"medium",color:od.color},children:gd?Ku.awaitingApproval:od.label})]}),!Yu&&jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:ad})]}),Yu&&jsxRuntimeExports.jsxs(Box,{p:3,children:[jsxRuntimeExports.jsxs(Box,{mb:Ru!==void 0||Pu?3:0,children:[jsxRuntimeExports.jsx(Text$3,{sx:{display:"block",fontSize:0,fontWeight:"semibold",color:"fg.muted",textTransform:"uppercase",letterSpacing:"0.05em",mb:2},children:Ku.parameters}),jsxRuntimeExports.jsx(Box,{backgroundColor:"canvas.inset",borderRadius:2,border:"1px solid",borderColor:"border.default",overflow:"auto",maxHeight:"200px",children:jsxRuntimeExports.jsx("pre",{style:{margin:0,padding:"12px",fontSize:"12px",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:Object.keys($u).length>0?JSON.stringify($u,null,2):`(${Ku.noParameters})`})})]}),(Iu==="complete"||Iu==="executing")&&Ru!==void 0&&jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{display:"block",fontSize:0,fontWeight:"semibold",color:"success.fg",textTransform:"uppercase",letterSpacing:"0.05em",mb:2},children:Ku.result}),jsxRuntimeExports.jsx(Box,{backgroundColor:"success.subtle",borderRadius:2,border:"1px solid",borderColor:"success.muted",overflow:"auto",maxHeight:"300px",children:jsxRuntimeExports.jsx("pre",{style:{margin:0,padding:"12px",fontSize:"12px",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:typeof Ru=="string"?Ru:JSON.stringify(Ru,null,2)})})]}),Bu&&jsxRuntimeExports.jsx(Box,{mt:Iu==="complete"&&Ru!==void 0?3:0,children:ju==="approved"?jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{color:"success.fg",fontSize:1,display:"block"},children:Ku.approvedRunning}),Fu==="external"&&jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontSize:0,display:"block"},children:Ku.approvedElsewhere})]}):ju==="denied"?jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{color:"danger.fg",fontSize:1,display:"block"},children:Ku.deniedWontRun}),Fu==="external"&&jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontSize:0,display:"block"},children:Ku.decidedElsewhere})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,color:"fg.default"},children:Ku.approvalNeeded}),jsxRuntimeExports.jsxs(Box,{mt:2,display:"flex",gap:2,children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",onClick:zu,disabled:Hu||!zu,children:Ku.approve}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"danger",onClick:Uu,disabled:Hu||!Uu,children:Ku.deny})]})]})}),Iu==="error"&&yd&&jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsxs(Text$3,{sx:{display:"block",fontSize:0,fontWeight:"semibold",color:"danger.fg",textTransform:"uppercase",letterSpacing:"0.05em",mb:2},children:[jsxRuntimeExports.jsx(AlertIcon,{size:12})," ",Ku.executionError]}),jsxRuntimeExports.jsxs(Box,{backgroundColor:"danger.subtle",borderRadius:2,border:"1px solid",borderColor:"danger.muted",p:2,children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,color:"danger.fg"},children:yd}),jsxRuntimeExports.jsx(Text$3,{sx:{display:"block",fontSize:0,color:"fg.muted",mt:1},children:Ku.executionErrorWhy})]})]}),Iu==="error"&&xd&&jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsxs(Text$3,{sx:{display:"block",fontSize:0,fontWeight:"semibold",color:"severe.fg",textTransform:"uppercase",letterSpacing:"0.05em",mb:2},children:[Ku.toolCodeError,": ",xd.name]}),jsxRuntimeExports.jsxs(Box,{backgroundColor:"severe.subtle",borderRadius:2,border:"1px solid",borderColor:"severe.muted",overflow:"hidden",children:[jsxRuntimeExports.jsx(Box,{p:2,children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,color:"severe.fg"},children:xd.value})}),xd.traceback&&jsxRuntimeExports.jsx(Box,{borderTop:"1px solid",borderColor:"severe.muted",backgroundColor:"canvas.inset",children:jsxRuntimeExports.jsx("pre",{style:{margin:0,padding:"8px 12px",fontSize:"11px",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',lineHeight:1.4,whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:"200px",overflow:"auto"},children:xd.traceback})})]})]}),Iu==="error"&&vd&&!yd&&!xd&&!td&&jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{display:"block",fontSize:0,fontWeight:"semibold",color:"danger.fg",textTransform:"uppercase",letterSpacing:"0.05em",mb:2},children:Ku.errorHeading}),jsxRuntimeExports.jsx(Box,{backgroundColor:"danger.subtle",borderRadius:2,border:"1px solid",borderColor:"danger.muted",p:2,children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,color:"danger.fg"},children:vd})})]}),td&&!yd&&!xd&&jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsxs(Text$3,{sx:{display:"block",fontSize:0,fontWeight:"semibold",color:"attention.fg",textTransform:"uppercase",letterSpacing:"0.05em",mb:2},children:[jsxRuntimeExports.jsx(AlertIcon,{size:12})," ",Ku.processExited]}),jsxRuntimeExports.jsxs(Box,{backgroundColor:"attention.subtle",borderRadius:2,border:"1px solid",borderColor:"attention.muted",p:2,children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,color:"attention.fg"},children:Ku.exitedWithCode(String(ed))}),jsxRuntimeExports.jsx(Text$3,{sx:{display:"block",fontSize:0,color:"fg.muted",mt:1},children:Ku.nonZeroExit})]}),Td&&jsxRuntimeExports.jsx(Box,{mt:2,backgroundColor:"canvas.inset",borderRadius:2,border:"1px solid",borderColor:"attention.muted",overflow:"auto",children:jsxRuntimeExports.jsx("pre",{style:{margin:0,padding:"10px 12px",fontSize:"12px",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',lineHeight:1.4,whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:"200px"},children:Td})})]}),jsxRuntimeExports.jsx(Box,{mt:3,pt:2,borderTop:"1px solid",borderColor:"border.muted",children:jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"fg.subtle",fontFamily:"monospace"},children:["ID: ",Au]})})]})]})}function TypingDots({size:Au=8}){return jsxRuntimeExports.jsx(Box,{"aria-hidden":"true","data-typing-dots":"",display:"inline-flex",alignItems:"center",gap:"4px",children:[0,.2,.4].map((lo,$u)=>jsxRuntimeExports.jsx(Box,{width:Au,height:Au,borderRadius:"50%",bg:"fg.muted",animation:"typingPulse 1.4s ease-in-out infinite",animationDelay:`${lo}s`,reducedMotion:{animation:"none",opacity:.7},sx:{"@keyframes typingPulse":{"0%, 60%, 100%":{transform:"scale(0.6)",opacity:.4},"30%":{transform:"scale(1)",opacity:1}}}},$u))})}function TurnFooter({usage:Au,live:lo,latest:$u,padding:Ru,onCopy:Iu,onRemove:Pu}){const Ou=useChatWords(),[Mu,Du]=reactExports.useState(!1),Lu=reactExports.useRef(null);reactExports.useEffect(()=>()=>{Lu.current!==null&&window.clearTimeout(Lu.current)},[]);const Bu=Au?{contextTokens:Au.totalTokens,contextWindow:Au.contextWindow,inputTokens:Au.turnUsage?.inputTokens??0,outputTokens:Au.turnUsage?.outputTokens??0}:null,ju=reactExports.useRef(null),[Fu,zu]=reactExports.useState(null);reactExports.useEffect(()=>{(lo||$u)&&Bu?ju.current=Bu:!lo&&!$u&&!Fu&&ju.current&&zu(ju.current)});const Uu=lo||$u?Bu:Fu;if(!Uu&&lo)return null;const Hu=async()=>{await Iu(),Du(!0),Lu.current!==null&&window.clearTimeout(Lu.current),Lu.current=window.setTimeout(()=>Du(!1),1500)};return jsxRuntimeExports.jsxs(Box,{"data-turn-footer":"",display:"flex",alignItems:"center",gap:1,px:Ru,mt:-1,pb:1,minHeight:24,sx:{opacity:.55,transition:"opacity 0.15s ease","&:hover, &:focus-within":{opacity:1},"& [data-turn-actions]":{opacity:0,transition:"opacity 0.15s ease"},"&:hover [data-turn-actions], &:focus-within [data-turn-actions]":{opacity:1}},children:[Uu&&jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"fg.muted",flexShrink:0},children:[jsxRuntimeExports.jsx(Text$3,{as:"span",sx:{fontWeight:"semibold",color:"fg.default",fontSize:0},children:formatTokenCount(Uu.contextTokens)})," / ",formatTokenCount(Uu.contextWindow)," ctx · turn ",formatTokenCount(Uu.inputTokens),jsxRuntimeExports.jsx(Text$3,{as:"span",sx:{color:"success.fg",fontSize:0},children:"▲"})," ",formatTokenCount(Uu.outputTokens),jsxRuntimeExports.jsx(Text$3,{as:"span",sx:{color:"attention.fg",fontSize:0},children:"▼"})]}),!lo&&jsxRuntimeExports.jsxs(Box,{"data-turn-actions":"",display:"flex",alignItems:"center",children:[jsxRuntimeExports.jsx(IconButton,{"data-turn-copy":"",icon:Mu?CheckIcon:CopyIcon,"aria-label":Ou.copyTurn,size:"small",variant:"invisible",onClick:()=>{Hu()}}),jsxRuntimeExports.jsx(IconButton,{"data-turn-remove":"",icon:TrashIcon,"aria-label":Ou.removeTurn,size:"small",variant:"invisible",onClick:Pu})]})]})}const FORM_SUBMISSION_LANGUAGE="a2ui-submission",FENCE=new RegExp("```"+FORM_SUBMISSION_LANGUAGE+"\\s*\\n([\\s\\S]*?)\\n```");function encodeFormSubmission(Au){const lo=JSON.stringify(Au,null,2);return`I just submitted "${Au.title}".
3638
3638
 
3639
3639
  \`\`\``+FORM_SUBMISSION_LANGUAGE+`
3640
- `+lo+"\n```\n\nPlease confirm you received it and briefly say what happens next."}function parseFormSubmission(Au){const lo=FENCE.exec(Au);if(!lo)return null;try{const $u=JSON.parse(lo[1]);return!$u||typeof $u!="object"||typeof $u.title!="string"||!$u.values||typeof $u.values!="object"?null:{title:$u.title,...$u.surfaceId?{surfaceId:String($u.surfaceId)}:{},values:$u.values}}catch{return null}}function labelOfFieldId(Au){const lo=Au.replace(/[-_]+/g," ").trim();return lo?lo[0].toUpperCase()+lo.slice(1):Au}function displayValue(Au){return Au==null?"—":typeof Au=="string"?Au.trim()===""?"—":Au:Array.isArray(Au)?Au.length===0?"—":Au.map(displayValue).join(", "):typeof Au=="boolean"?Au?"Yes":"No":typeof Au=="number"?String(Au):JSON.stringify(Au)}function FormSubmissionMessage({submission:Au}){const[lo,$u]=reactExports.useState(!0),Ru=Object.entries(Au.values),Iu=Ru.length;return jsxRuntimeExports.jsxs(Box,{width:"100%",minWidth:280,border:"1px solid",borderColor:"border.default",borderRadius:"12px",overflow:"hidden",backgroundColor:"canvas.default",color:"fg.default",children:[jsxRuntimeExports.jsxs(Box,{as:"button",type:"button","aria-expanded":lo,onClick:()=>$u(Pu=>!Pu),width:"100%",display:"flex",alignItems:"center",gap:2,padding:2,backgroundColor:"canvas.subtle",border:"none",borderBottom:lo?"1px solid":"none",borderColor:"border.default",cursor:"pointer",textAlign:"left",color:"fg.default",hover:{backgroundColor:"neutral.muted"},children:[jsxRuntimeExports.jsx(Box,{color:"fg.muted",flexShrink:0,children:lo?jsxRuntimeExports.jsx(ChevronDownIcon,{size:16}):jsxRuntimeExports.jsx(ChevronRightIcon,{size:16})}),jsxRuntimeExports.jsx(Box,{color:"fg.muted",flexShrink:0,children:jsxRuntimeExports.jsx(ChecklistIcon,{size:16})}),jsxRuntimeExports.jsxs(Text$3,{sx:{fontWeight:"semibold",fontSize:1},children:["Submitted ",Au.title]}),jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"fg.muted",ml:"auto"},children:[Iu," field",Iu===1?"":"s"]})]}),lo?jsxRuntimeExports.jsx(Box,{as:"table",width:"100%",borderCollapse:"collapse",children:jsxRuntimeExports.jsx(Box,{as:"tbody",children:Ru.map(([Pu,Ou])=>jsxRuntimeExports.jsxs(Box,{as:"tr",sx:{"& + tr td":{borderTop:"1px solid",borderColor:"border.muted"}},children:[jsxRuntimeExports.jsx(Box,{as:"td",px:3,py:1,fontSize:0,color:"fg.muted",whiteSpace:"nowrap",verticalAlign:"top",width:"40%",children:labelOfFieldId(Pu)}),jsxRuntimeExports.jsx(Box,{as:"td",px:3,py:1,fontSize:1,wordBreak:"break-word",children:displayValue(Ou)})]},Pu))})}):null]})}function a2aAgentDetails(Au,lo){if(!Au.some(Ru=>Ru.transport==="a2a"))return null;const $u={name:Au[0]?.subagentName??lo??"agent"};for(const Ru of Au)Ru.url&&($u.url=Ru.url),Ru.launch&&Ru.launch!=="auto"&&($u.launch=Ru.launch),Ru.phase==="status"&&Ru.state&&($u.state=Ru.state),Ru.taskId&&($u.taskId=Ru.taskId),Ru.runtimeUid&&($u.runtimeUid=Ru.runtimeUid),Ru.agentCard&&($u.card=Ru.agentCard);return $u}function agentCardUrl(Au){return`${Au.replace(/\/+$/,"")}/.well-known/agent-card.json`}function useAgentCard(Au){const[lo,$u]=reactExports.useState({status:Au?"loading":"idle"});return reactExports.useEffect(()=>{if(!Au){$u({status:"idle"});return}const Ru=new AbortController;return $u({status:"loading"}),fetch(agentCardUrl(Au),{signal:Ru.signal,headers:{Accept:"application/json"}}).then(async Iu=>{if(!Iu.ok)throw new Error(`${Iu.status} ${Iu.statusText}`.trim());const Pu=await Iu.json();if(!Pu||typeof Pu!="object"||Array.isArray(Pu))throw new Error("The agent card is not a JSON object");$u({status:"loaded",card:Pu})}).catch(Iu=>{Ru.signal.aborted||$u({status:"error",error:Iu instanceof Error?Iu.message:String(Iu)})}),()=>Ru.abort()},[Au]),lo}const record=Au=>Au&&typeof Au=="object"&&!Array.isArray(Au)?Au:void 0,items=Au=>Array.isArray(Au)?Au.map(record).filter(lo=>!!lo):[],text$4=Au=>typeof Au=="string"&&Au?Au:void 0,strings=Au=>Array.isArray(Au)?Au.filter(lo=>typeof lo=="string"):[];function Section({title:Au,children:lo}){return jsxRuntimeExports.jsxs(Box,{display:"flex",flexDirection:"column",gap:2,children:[jsxRuntimeExports.jsx(Heading$2,{as:"h4",sx:{fontSize:1,m:0},children:Au}),lo]})}function Row$1({label:Au,children:lo}){return jsxRuntimeExports.jsxs(Box,{display:"grid",gridTemplateColumns:"112px 1fr",gap:2,alignItems:"baseline",fontSize:0,children:[jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontSize:0},children:Au}),jsxRuntimeExports.jsx(Box,{minWidth:0,wordBreak:"break-all",children:lo})]})}function External({href:Au,children:lo}){return jsxRuntimeExports.jsxs(Link$1,{href:Au,target:"_blank",rel:"noreferrer",sx:{fontSize:0,fontFamily:"mono",display:"inline-flex",alignItems:"center",gap:1},children:[lo??Au,jsxRuntimeExports.jsx(LinkExternalIcon,{size:12})]})}function Mono({children:Au}){return jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,fontFamily:"mono"},children:Au})}function humanize(Au){const lo=Au.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").toLowerCase();return lo.charAt(0).toUpperCase()+lo.slice(1)}const isUrl=Au=>/^https?:\/\//.test(Au),None=({word:Au="none"})=>jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:Au});function ValueView({value:Au,depth:lo=0}){if(Au==null)return jsxRuntimeExports.jsx(None,{word:"—"});if(typeof Au=="boolean")return jsxRuntimeExports.jsx(Label,{size:"small",variant:Au?"success":"secondary",children:Au?"yes":"no"});if(typeof Au=="number")return jsxRuntimeExports.jsx(Mono,{children:String(Au)});if(typeof Au=="string")return isUrl(Au)?jsxRuntimeExports.jsx(External,{href:Au}):jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0},children:Au});if(lo>=3)return jsxRuntimeExports.jsx(Mono,{children:JSON.stringify(Au)});if(Array.isArray(Au))return Au.length===0?jsxRuntimeExports.jsx(None,{}):Au.every(Ru=>typeof Ru!="object"||Ru===null)?jsxRuntimeExports.jsx(Box,{display:"flex",gap:2,flexWrap:"wrap",children:Au.map((Ru,Iu)=>jsxRuntimeExports.jsx(ValueView,{value:Ru,depth:lo+1},Iu))}):jsxRuntimeExports.jsx(Box,{display:"flex",flexDirection:"column",gap:2,children:Au.map((Ru,Iu)=>jsxRuntimeExports.jsx(Box,{pl:2,borderLeft:"2px solid",borderColor:"border.muted",children:jsxRuntimeExports.jsx(ValueView,{value:Ru,depth:lo+1})},Iu))});const $u=Object.entries(Au);return $u.length===0?jsxRuntimeExports.jsx(None,{word:"empty"}):jsxRuntimeExports.jsx(Box,{display:"grid",gridTemplateColumns:"max-content 1fr",columnGap:2,rowGap:1,alignItems:"baseline",children:$u.map(([Ru,Iu])=>jsxRuntimeExports.jsxs(vM.Fragment,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:humanize(Ru)}),jsxRuntimeExports.jsx(Box,{minWidth:0,wordBreak:"break-all",children:jsxRuntimeExports.jsx(ValueView,{value:Iu,depth:lo+1})})]},Ru))})}const HANDLED_KEYS=new Set(["name","description","version","protocolVersion","url","documentationUrl","iconUrl","provider","supportedInterfaces","capabilities","skills","defaultInputModes","defaultOutputModes"]);function CardFields({card:Au}){const lo=record(Au.provider),$u=record(Au.capabilities),Ru=Object.entries($u??{}),Iu=items($u?.extensions),Pu=items(Au.supportedInterfaces),Ou=items(Au.skills),Mu=strings(Au.defaultInputModes),Du=strings(Au.defaultOutputModes),Lu=Object.entries(Au).filter(([Bu])=>!HANDLED_KEYS.has(Bu));return jsxRuntimeExports.jsxs(Box,{display:"flex",flexDirection:"column",gap:2,children:[jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,fontWeight:"bold"},children:text$4(Au.name)??"Unnamed agent"}),text$4(Au.version)?jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"fg.muted",ml:2},children:["v",text$4(Au.version)]}):null,text$4(Au.protocolVersion)?jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"fg.muted",ml:2},children:["A2A ",text$4(Au.protocolVersion)]}):null,text$4(Au.description)?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",mt:1,mb:0},children:text$4(Au.description)}):null]}),text$4(Au.url)?jsxRuntimeExports.jsx(Row$1,{label:"Endpoint",children:jsxRuntimeExports.jsx(External,{href:text$4(Au.url)})}):null,text$4(Au.documentationUrl)?jsxRuntimeExports.jsx(Row$1,{label:"Documentation",children:jsxRuntimeExports.jsx(External,{href:text$4(Au.documentationUrl)})}):null,text$4(Au.iconUrl)?jsxRuntimeExports.jsx(Row$1,{label:"Icon",children:jsxRuntimeExports.jsx(External,{href:text$4(Au.iconUrl)})}):null,lo?jsxRuntimeExports.jsx(Row$1,{label:"Provider",children:jsxRuntimeExports.jsx(ValueView,{value:lo,depth:1})}):null,Au.supportedInterfaces!==void 0?jsxRuntimeExports.jsx(Row$1,{label:"Interfaces",children:Pu.length===0?jsxRuntimeExports.jsx(None,{}):jsxRuntimeExports.jsx(Box,{display:"flex",flexDirection:"column",gap:1,children:Pu.map((Bu,ju)=>jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,alignItems:"center",flexWrap:"wrap",children:[jsxRuntimeExports.jsx(Label,{size:"small",children:text$4(Bu.protocolBinding)??"binding"}),text$4(Bu.url)?jsxRuntimeExports.jsx(Mono,{children:text$4(Bu.url)}):null,text$4(Bu.protocolVersion)?jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:["v",text$4(Bu.protocolVersion)]}):null]},ju))})}):null,$u!==void 0?jsxRuntimeExports.jsx(Row$1,{label:"Capabilities",children:Ru.length===0?jsxRuntimeExports.jsx(None,{}):jsxRuntimeExports.jsxs(Box,{display:"flex",flexDirection:"column",gap:1,children:[jsxRuntimeExports.jsx(Box,{display:"flex",gap:1,flexWrap:"wrap",children:Ru.filter(([,Bu])=>typeof Bu=="boolean").map(([Bu,ju])=>jsxRuntimeExports.jsxs(Label,{size:"small",variant:ju?"success":"secondary",children:[Bu,": ",ju?"yes":"no"]},Bu))}),Iu.map((Bu,ju)=>jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,alignItems:"baseline",flexWrap:"wrap",children:[jsxRuntimeExports.jsx(Mono,{children:text$4(Bu.uri)??"extension"}),Bu.required===!0?jsxRuntimeExports.jsx(Label,{size:"small",variant:"attention",children:"required"}):null,text$4(Bu.description)?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:text$4(Bu.description)}):null]},ju)),Ru.filter(([Bu,ju])=>typeof ju!="boolean"&&Bu!=="extensions").map(([Bu,ju])=>jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:humanize(Bu)}),jsxRuntimeExports.jsx(ValueView,{value:ju,depth:1})]},Bu))]})}):null,Au.skills!==void 0?jsxRuntimeExports.jsx(Row$1,{label:"Skills",children:Ou.length===0?jsxRuntimeExports.jsx(None,{}):jsxRuntimeExports.jsx(Box,{display:"flex",flexDirection:"column",gap:1,children:Ou.map((Bu,ju)=>jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,fontWeight:"bold"},children:text$4(Bu.name)??text$4(Bu.id)??"skill"}),text$4(Bu.description)?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted",ml:2},children:text$4(Bu.description)}):null,strings(Bu.tags).length>0?jsxRuntimeExports.jsx(Box,{display:"inline-flex",gap:1,ml:2,children:strings(Bu.tags).map(Fu=>jsxRuntimeExports.jsx(Label,{size:"small",children:Fu},Fu))}):null]},ju))})}):null,Au.defaultInputModes!==void 0?jsxRuntimeExports.jsx(Row$1,{label:"Input modes",children:Mu.length?jsxRuntimeExports.jsx(Mono,{children:Mu.join(", ")}):jsxRuntimeExports.jsx(None,{})}):null,Au.defaultOutputModes!==void 0?jsxRuntimeExports.jsx(Row$1,{label:"Output modes",children:Du.length?jsxRuntimeExports.jsx(Mono,{children:Du.join(", ")}):jsxRuntimeExports.jsx(None,{})}):null,Lu.map(([Bu,ju])=>jsxRuntimeExports.jsx(Row$1,{label:humanize(Bu),children:jsxRuntimeExports.jsx(ValueView,{value:ju})},Bu))]})}const LAUNCH_LABEL={local:"launched on the local agent-runtimes server",cloud:"launched on a Datalayer runtime",remote:"reached at a URL the spec named",auto:"launch not decided yet"};function A2AAgentDialog({details:Au,onClose:lo}){const $u=useAgentCard(Au.url),Ru=Au.url?agentCardUrl(Au.url):void 0,Iu=()=>{Ru&&window.open(Ru,"_blank","noopener,noreferrer")};return jsxRuntimeExports.jsx(Dialog$1,{onClose:lo,title:`A2A agent · ${Au.name}`,subtitle:"A separate agent, reached over the A2A protocol",width:"large",footerButtons:[...Ru?[{content:"Open agent card",onClick:Iu}]:[],{content:"Close",onClick:lo,buttonType:"primary"}],children:jsxRuntimeExports.jsxs(Box,{"data-a2a-agent-dialog":Au.name,"data-a2a-card-status":$u.status,display:"flex",flexDirection:"column",gap:3,children:[jsxRuntimeExports.jsxs(Section,{title:"This run",children:[Au.description?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",m:0},children:Au.description}):null,jsxRuntimeExports.jsx(Row$1,{label:"Launch",children:jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0},children:[Au.launch??"auto",jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:[" ","— ",LAUNCH_LABEL[Au.launch??"auto"]??""]})]})}),Au.ref?jsxRuntimeExports.jsx(Row$1,{label:"Agentspec",children:jsxRuntimeExports.jsx(Mono,{children:Au.ref})}):null,jsxRuntimeExports.jsx(Row$1,{label:"State",children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0},children:Au.state??"unknown"})}),Au.taskId?jsxRuntimeExports.jsx(Row$1,{label:"Task",children:jsxRuntimeExports.jsx(Mono,{children:Au.taskId})}):null,Au.runtimeUid?jsxRuntimeExports.jsx(Row$1,{label:"Runtime",children:jsxRuntimeExports.jsx(Mono,{children:Au.runtimeUid})}):null,Au.url?jsxRuntimeExports.jsx(Row$1,{label:"Endpoint",children:jsxRuntimeExports.jsx(External,{href:Au.url})}):null,Ru?jsxRuntimeExports.jsx(Row$1,{label:"Agent card",children:jsxRuntimeExports.jsx(External,{href:Ru})}):null]}),jsxRuntimeExports.jsxs(Section,{title:"Agent card",children:[$u.status==="idle"?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:"No endpoint known yet: the card can be fetched once the agent is launched."}):null,$u.status==="loading"?jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,children:[jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}),jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:["Fetching ",Ru,"…"]})]}):null,$u.status==="error"?jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"danger.fg"},children:["The card could not be fetched from here (",$u.error,"). It may still open in a tab through the link above."]}):null,$u.status==="loaded"?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(CardFields,{card:$u.card}),jsxRuntimeExports.jsxs(Box,{as:"details",fontSize:0,children:[jsxRuntimeExports.jsx(Box,{as:"summary",cursor:"pointer",color:"fg.muted",children:"Raw JSON"}),jsxRuntimeExports.jsx(Box,{as:"pre","data-a2a-card-json":!0,mt:2,p:2,bg:"canvas.subtle",border:"1px solid",borderColor:"border.default",borderRadius:2,overflow:"auto",maxHeight:280,fontSize:0,m:0,children:JSON.stringify($u.card,null,2)})]})]}):null]}),Au.card&&$u.status!=="loaded"?jsxRuntimeExports.jsxs(Section,{title:"Card, as the server saw it at launch",children:[jsxRuntimeExports.jsx(Row$1,{label:"Name",children:jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0},children:[Au.card.name??"—",Au.card.version?` v${Au.card.version}`:""]})}),Au.card.description?jsxRuntimeExports.jsx(Row$1,{label:"Description",children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0},children:Au.card.description})}):null,Au.card.skills&&Au.card.skills.length>0?jsxRuntimeExports.jsx(Row$1,{label:"Skills",children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0},children:Au.card.skills.join(", ")})}):null]}):null]})})}const NO_SUBSCRIPTION=()=>()=>{},NotebookToolSurfaces=reactExports.lazy(()=>__vitePreload(()=>import("./chunks/NotebookToolSurfaces-YAM1bvZS.js"),[],import.meta.url));function normalizeName(Au){return Au.replace(/:[0-9]+\.[0-9]+\.[0-9]+.*$/,"").replace(/[-_]/g,"").toLowerCase()}function toneColorsOf(Au){return!Au||Au==="neutral"?{emphasis:"neutral.emphasis",subtle:"canvas.subtle",muted:"border.default",fg:"fg.default"}:{emphasis:`${Au}.emphasis`,subtle:`${Au}.subtle`,muted:`${Au}.muted`,fg:`${Au}.fg`}}const SUBAGENT_AVATAR_CONFIG={userAvatar:jsxRuntimeExports.jsx(PersonIcon,{size:14}),assistantAvatar:jsxRuntimeExports.jsx(DependabotIcon,{size:14}),showAvatars:!0,avatarSize:24,userAvatarBg:"neutral.muted",assistantAvatarBg:"accent.emphasis"};function buildSubagentDisplayItems(Au,lo){const $u=[],Ru=new Map;let Iu="",Pu=0;const Ou=()=>{Iu.trim()&&$u.push({id:`${lo}:msg:${Pu++}`,role:"assistant",content:Iu,createdAt:new Date(0)}),Iu=""};for(const Mu of Au)switch(Mu.phase){case"text":Iu+=Mu.text??"";break;case"tool_call":{Ou();const Du=`${lo}:tool:${Pu++}`,Lu={id:Du,type:"tool-call",toolCallId:Du,toolName:Mu.toolName??"tool",args:Mu.toolArgs??{},status:"inProgress"};$u.push(Lu),Mu.toolName&&Ru.set(Mu.toolName,Lu);break}case"tool_result":{Ou();const Du=Mu.toolName?Ru.get(Mu.toolName):void 0;if(Du)Du.result=Mu.result,Du.status="complete",Mu.toolName&&Ru.delete(Mu.toolName);else{const Lu=`${lo}:tool:${Pu++}`;$u.push({id:Lu,type:"tool-call",toolCallId:Lu,toolName:Mu.toolName??"tool",args:{},result:Mu.result,status:"complete"})}break}case"error":Ou(),$u.push({id:`${lo}:msg:${Pu++}`,role:"assistant",content:`**⚠️ ${Mu.error??"Subagent failed"}**`,createdAt:new Date(0)});break}return Ou(),$u}function SubagentChatPanel({toolCallId:Au,subagentName:lo,height:$u=280,avatarConfig:Ru=SUBAGENT_AVATAR_CONFIG}){const Iu=useAgentRuntimeSubagentActivityByToolCall(Au,lo),Pu=reactExports.useMemo(()=>buildSubagentDisplayItems(Iu,Au),[Iu,Au]),Ou=reactExports.useRef(null),Mu=reactExports.useMemo(()=>{for(const Wu of Iu)if(Wu.subagentName)return Wu.subagentName;return lo??"subagent"},[Iu,lo]),Du=reactExports.useMemo(()=>Iu.some(Wu=>Wu.phase==="end"||Wu.phase==="error"),[Iu]),Lu=reactExports.useMemo(()=>Iu.some(Wu=>Wu.phase==="error"),[Iu]),Bu=reactExports.useMemo(()=>Iu.some(Wu=>Wu.phase==="error"&&Wu.error===SUBAGENT_STOPPED),[Iu]),ju=reactExports.useMemo(()=>a2aAgentDetails(Iu,lo),[Iu,lo]),Fu=ju!==null,[zu,Uu]=reactExports.useState(!1),Hu=reactExports.useCallback(async(Wu,Ku)=>{if(Ku&&typeof Ku=="object"){const Ju=Ku;Ju.type==="tool-approval-decision"&&typeof Ju.approved=="boolean"&&typeof Ju.approvalId=="string"&&agentRuntimeStore.getState().sendDecision(Ju.approvalId,Ju.approved)}},[]);if(reactExports.useEffect(()=>{Ou.current?.scrollIntoView?.({block:"end"})},[Pu]),Iu.length===0)return null;const Vu=Lu?Bu?"attention":"danger":Du?"success":"accent",Gu=Lu?Bu?"stopped":"failed":Du?"done":Fu&&ju?.state==="launching"?"launching…":"working…";return jsxRuntimeExports.jsxs(Box,{"data-subagent-panel":Mu,"data-subagent-transport":Fu?"a2a":"in-process",mt:2,display:"flex",flexDirection:"column",height:$u,width:"100%",border:"1px solid",borderColor:`${Vu}.emphasis`,borderRadius:2,overflow:"hidden",bg:"canvas.default",children:[jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:1,px:2,py:1,borderBottom:"1px solid",borderColor:`${Vu}.muted`,bg:`${Vu}.subtle`,flexShrink:0,children:[jsxRuntimeExports.jsx(Box,{display:"flex",color:`${Vu}.fg`,children:Fu?jsxRuntimeExports.jsx(BroadcastIcon,{size:14}):jsxRuntimeExports.jsx(DependabotIcon,{size:14})}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:`${Vu}.fg`},children:Fu?"A2A agent":"Subagent"}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,fontWeight:"bold",color:`${Vu}.fg`},children:Mu}),ju?.launch?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:`${Vu}.fg`,opacity:.8},children:ju.launch}):null,ju?jsxRuntimeExports.jsx(Link$1,{as:"button",type:"button","data-a2a-card-button":!0,onClick:()=>Uu(!0),sx:{fontSize:0,ml:1},children:"card"}):null,jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:`${Vu}.fg`,ml:"auto"},children:Gu})]}),zu&&ju?jsxRuntimeExports.jsx(A2AAgentDialog,{details:ju,onClose:()=>Uu(!1)}):null,jsxRuntimeExports.jsx(Box,{flex:1,minHeight:0,overflowY:"auto",children:jsxRuntimeExports.jsx(ChatMessageList,{displayItems:Pu,isLoading:!Du,isStreaming:!Du,showLoadingIndicator:!Du,hideMessagesAfterToolUI:!1,avatarConfig:Ru,padding:2,onRespond:Hu,messagesEndRef:Ou,emptyContent:jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:1,color:"fg.muted",p:2,children:[jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0},children:"Starting…"})]})})})]})}function DefaultToolCallRenderer({item:Au,onRespond:lo,mcpServers:$u,density:Ru}){const Iu=Au.result&&typeof Au.result=="object"?Au.result:void 0,Pu=Au.status==="inProgress"&&Iu?.pending_approval===!0,Ou=typeof Iu?.approval_id=="string"?Iu.approval_id:void 0,Mu=Au.status==="executing",[Du,Lu]=reactExports.useState(),Bu=reactExports.useMemo(()=>normalizeName(Au.toolName),[Au.toolName]),ju=reactExports.useMemo(()=>{const sd=skillIdOfCall(Au.toolName,Au.args);return sd?`skill:${sd}`.toLowerCase():null},[Au.toolName,Au.args]),Fu=reactExports.useMemo(()=>marksOfToolCall(Au.toolName,Au.args,$u),[Au.toolName,Au.args,$u]),zu=useAgentRuntimeStore(sd=>sd.approvals),Uu=reactExports.useMemo(()=>Ou?zu.find(sd=>sd.id===Ou)??null:null,[zu,Ou]),Hu=reactExports.useMemo(()=>ju?zu.find(sd=>sd.tool_name?.toLowerCase()===ju)??null:null,[zu,ju]),Vu=reactExports.useMemo(()=>!Pu&&!Mu?null:zu.find(sd=>normalizeName(sd.tool_name)===Bu)??null,[zu,Bu,Pu,Mu]),Gu=Uu??Hu??Vu,Wu=Gu?.id??Ou??null,Ku=Gu?.status==="approved"?"approved":Gu?.status==="rejected"?"denied":void 0,Ju=reactExports.useCallback(sd=>{if(!Wu)return;const ad=sd==="approve";Lu(ad?"approved":"denied"),lo({type:"tool-approval-decision",approved:ad,approvalId:Wu,toolName:Au.toolName})},[Wu,lo,Au.toolName]),Yu=Pu||!!Wu||!!Ku,Xu=Du||Ku||(Yu?"pending":void 0),ed=Du?"inline":Ku?"external":void 0,td=useAgentRuntimeSubagentActivity(Au.toolCallId),nd=Bu==="delegatetask"||td.length>0,od=typeof Au.args?.subagent_name=="string"?Au.args.subagent_name:typeof Au.args?.subagent=="string"?Au.args.subagent:Bu==="delegatetask"?void 0:Au.toolName;return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(ToolCallDisplay,{toolCallId:Au.toolCallId,toolName:Au.toolName,args:Au.args,result:Au.result,status:Au.status,error:Au.error,executionError:Au.executionError,codeError:Au.codeError,exitCode:Au.exitCode,approvalRequired:Yu,approvalState:Xu,approvalDecisionSource:ed,onApprove:Wu&&!Du&&!Ku?()=>Ju("approve"):void 0,onDeny:Wu&&!Du&&!Ku?()=>Ju("reject"):void 0,approvalLoading:!1,marks:Fu,summary:Au.summary,density:Ru}),nd&&jsxRuntimeExports.jsx(SubagentChatPanel,{toolCallId:Au.toolCallId,subagentName:od})]})}function ChatMessageList({displayItems:Au,actOn:lo,upload:$u,isLoading:Ru,isStreaming:Iu,showLoadingIndicator:Pu,hideMessagesAfterToolUI:Ou,avatarConfig:Mu,padding:Du,notebookToolSurfacesId:Lu,emptyContent:Bu,messagesEndRef:ju,onRespond:Fu,approvalConfig:zu,showTurnFooters:Uu=!1,agentUsage:Hu,onRemoveItems:Vu,renderMessageFooter:Gu,mcpServers:Wu,density:Ku="comfortable"}){const Ju=useOptionalReactorPlatform();reactExports.useSyncExternalStore(Ju?.subscribe??NO_SUBSCRIPTION,()=>Ju?.getRevision()??0);const Yu=Ku==="compact";if(Yu&&(Mu={...Mu,showAvatars:!1},Uu=!1),Au.length===0)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Bu});const Xu=ad=>pd=>{Fu(ad,pd)},ed=Au.some(isToolCallMessage),td=new Map;if(Uu){let ad=-1;Au.forEach((pd,gd)=>{!isToolCallMessage(pd)&&pd.role==="user"&&(ad>=0&&td.set(gd-1,ad),ad=gd)}),ad>=0&&td.set(Au.length-1,ad)}const nd=(ad,pd)=>{const gd=[];for(let xd=ad;xd<=pd;xd+=1){const yd=Au[xd];if(isToolCallMessage(yd))gd.push(`[tool · ${yd.toolName}]`);else{const vd=yd,wd=getMessageText(vd);wd&&gd.push(vd.role==="user"?`You: ${wd}`:wd)}}return navigator.clipboard?.writeText(gd.join(`
3640
+ `+lo+"\n```\n\nPlease confirm you received it and briefly say what happens next."}function parseFormSubmission(Au){const lo=FENCE.exec(Au);if(!lo)return null;try{const $u=JSON.parse(lo[1]);return!$u||typeof $u!="object"||typeof $u.title!="string"||!$u.values||typeof $u.values!="object"?null:{title:$u.title,...$u.surfaceId?{surfaceId:String($u.surfaceId)}:{},values:$u.values}}catch{return null}}function labelOfFieldId(Au){const lo=Au.replace(/[-_]+/g," ").trim();return lo?lo[0].toUpperCase()+lo.slice(1):Au}function displayValue(Au){return Au==null?"—":typeof Au=="string"?Au.trim()===""?"—":Au:Array.isArray(Au)?Au.length===0?"—":Au.map(displayValue).join(", "):typeof Au=="boolean"?Au?"Yes":"No":typeof Au=="number"?String(Au):JSON.stringify(Au)}function FormSubmissionMessage({submission:Au}){const[lo,$u]=reactExports.useState(!0),Ru=Object.entries(Au.values),Iu=Ru.length;return jsxRuntimeExports.jsxs(Box,{width:"100%",minWidth:280,border:"1px solid",borderColor:"border.default",borderRadius:"12px",overflow:"hidden",backgroundColor:"canvas.default",color:"fg.default",children:[jsxRuntimeExports.jsxs(Box,{as:"button",type:"button","aria-expanded":lo,onClick:()=>$u(Pu=>!Pu),width:"100%",display:"flex",alignItems:"center",gap:2,padding:2,backgroundColor:"canvas.subtle",border:"none",borderBottom:lo?"1px solid":"none",borderColor:"border.default",cursor:"pointer",textAlign:"left",color:"fg.default",hover:{backgroundColor:"neutral.muted"},children:[jsxRuntimeExports.jsx(Box,{color:"fg.muted",flexShrink:0,children:lo?jsxRuntimeExports.jsx(ChevronDownIcon,{size:16}):jsxRuntimeExports.jsx(ChevronRightIcon,{size:16})}),jsxRuntimeExports.jsx(Box,{color:"fg.muted",flexShrink:0,children:jsxRuntimeExports.jsx(ChecklistIcon,{size:16})}),jsxRuntimeExports.jsxs(Text$3,{sx:{fontWeight:"semibold",fontSize:1},children:["Submitted ",Au.title]}),jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"fg.muted",ml:"auto"},children:[Iu," field",Iu===1?"":"s"]})]}),lo?jsxRuntimeExports.jsx(Box,{as:"table",width:"100%",borderCollapse:"collapse",children:jsxRuntimeExports.jsx(Box,{as:"tbody",children:Ru.map(([Pu,Ou])=>jsxRuntimeExports.jsxs(Box,{as:"tr",sx:{"& + tr td":{borderTop:"1px solid",borderColor:"border.muted"}},children:[jsxRuntimeExports.jsx(Box,{as:"td",px:3,py:1,fontSize:0,color:"fg.muted",whiteSpace:"nowrap",verticalAlign:"top",width:"40%",children:labelOfFieldId(Pu)}),jsxRuntimeExports.jsx(Box,{as:"td",px:3,py:1,fontSize:1,wordBreak:"break-word",children:displayValue(Ou)})]},Pu))})}):null]})}function a2aAgentDetails(Au,lo){if(!Au.some(Ru=>Ru.transport==="a2a"))return null;const $u={name:Au[0]?.subagentName??lo??"agent"};for(const Ru of Au)Ru.url&&($u.url=Ru.url),Ru.launch&&Ru.launch!=="auto"&&($u.launch=Ru.launch),Ru.phase==="status"&&Ru.state&&($u.state=Ru.state),Ru.taskId&&($u.taskId=Ru.taskId),Ru.runtimeUid&&($u.runtimeUid=Ru.runtimeUid),Ru.agentCard&&($u.card=Ru.agentCard);return $u}function agentCardUrl(Au){return`${Au.replace(/\/+$/,"")}/.well-known/agent-card.json`}function useAgentCard(Au){const[lo,$u]=reactExports.useState({status:Au?"loading":"idle"});return reactExports.useEffect(()=>{if(!Au){$u({status:"idle"});return}const Ru=new AbortController;return $u({status:"loading"}),fetch(agentCardUrl(Au),{signal:Ru.signal,headers:{Accept:"application/json"}}).then(async Iu=>{if(!Iu.ok)throw new Error(`${Iu.status} ${Iu.statusText}`.trim());const Pu=await Iu.json();if(!Pu||typeof Pu!="object"||Array.isArray(Pu))throw new Error("The agent card is not a JSON object");$u({status:"loaded",card:Pu})}).catch(Iu=>{Ru.signal.aborted||$u({status:"error",error:Iu instanceof Error?Iu.message:String(Iu)})}),()=>Ru.abort()},[Au]),lo}const record=Au=>Au&&typeof Au=="object"&&!Array.isArray(Au)?Au:void 0,items=Au=>Array.isArray(Au)?Au.map(record).filter(lo=>!!lo):[],text$4=Au=>typeof Au=="string"&&Au?Au:void 0,strings=Au=>Array.isArray(Au)?Au.filter(lo=>typeof lo=="string"):[];function Section({title:Au,children:lo}){return jsxRuntimeExports.jsxs(Box,{display:"flex",flexDirection:"column",gap:2,children:[jsxRuntimeExports.jsx(Heading$2,{as:"h4",sx:{fontSize:1,m:0},children:Au}),lo]})}function Row$1({label:Au,children:lo}){return jsxRuntimeExports.jsxs(Box,{display:"grid",gridTemplateColumns:"112px 1fr",gap:2,alignItems:"baseline",fontSize:0,children:[jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontSize:0},children:Au}),jsxRuntimeExports.jsx(Box,{minWidth:0,wordBreak:"break-all",children:lo})]})}function External({href:Au,children:lo}){return jsxRuntimeExports.jsxs(Link$1,{href:Au,target:"_blank",rel:"noreferrer",sx:{fontSize:0,fontFamily:"mono",display:"inline-flex",alignItems:"center",gap:1},children:[lo??Au,jsxRuntimeExports.jsx(LinkExternalIcon,{size:12})]})}function Mono({children:Au}){return jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,fontFamily:"mono"},children:Au})}function humanize(Au){const lo=Au.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").toLowerCase();return lo.charAt(0).toUpperCase()+lo.slice(1)}const isUrl=Au=>/^https?:\/\//.test(Au),None=({word:Au="none"})=>jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:Au});function ValueView({value:Au,depth:lo=0}){if(Au==null)return jsxRuntimeExports.jsx(None,{word:"—"});if(typeof Au=="boolean")return jsxRuntimeExports.jsx(Label,{size:"small",variant:Au?"success":"secondary",children:Au?"yes":"no"});if(typeof Au=="number")return jsxRuntimeExports.jsx(Mono,{children:String(Au)});if(typeof Au=="string")return isUrl(Au)?jsxRuntimeExports.jsx(External,{href:Au}):jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0},children:Au});if(lo>=3)return jsxRuntimeExports.jsx(Mono,{children:JSON.stringify(Au)});if(Array.isArray(Au))return Au.length===0?jsxRuntimeExports.jsx(None,{}):Au.every(Ru=>typeof Ru!="object"||Ru===null)?jsxRuntimeExports.jsx(Box,{display:"flex",gap:2,flexWrap:"wrap",children:Au.map((Ru,Iu)=>jsxRuntimeExports.jsx(ValueView,{value:Ru,depth:lo+1},Iu))}):jsxRuntimeExports.jsx(Box,{display:"flex",flexDirection:"column",gap:2,children:Au.map((Ru,Iu)=>jsxRuntimeExports.jsx(Box,{pl:2,borderLeft:"2px solid",borderColor:"border.muted",children:jsxRuntimeExports.jsx(ValueView,{value:Ru,depth:lo+1})},Iu))});const $u=Object.entries(Au);return $u.length===0?jsxRuntimeExports.jsx(None,{word:"empty"}):jsxRuntimeExports.jsx(Box,{display:"grid",gridTemplateColumns:"max-content 1fr",columnGap:2,rowGap:1,alignItems:"baseline",children:$u.map(([Ru,Iu])=>jsxRuntimeExports.jsxs(vM.Fragment,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:humanize(Ru)}),jsxRuntimeExports.jsx(Box,{minWidth:0,wordBreak:"break-all",children:jsxRuntimeExports.jsx(ValueView,{value:Iu,depth:lo+1})})]},Ru))})}const HANDLED_KEYS=new Set(["name","description","version","protocolVersion","url","documentationUrl","iconUrl","provider","supportedInterfaces","capabilities","skills","defaultInputModes","defaultOutputModes"]);function CardFields({card:Au}){const lo=record(Au.provider),$u=record(Au.capabilities),Ru=Object.entries($u??{}),Iu=items($u?.extensions),Pu=items(Au.supportedInterfaces),Ou=items(Au.skills),Mu=strings(Au.defaultInputModes),Du=strings(Au.defaultOutputModes),Lu=Object.entries(Au).filter(([Bu])=>!HANDLED_KEYS.has(Bu));return jsxRuntimeExports.jsxs(Box,{display:"flex",flexDirection:"column",gap:2,children:[jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,fontWeight:"bold"},children:text$4(Au.name)??"Unnamed agent"}),text$4(Au.version)?jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"fg.muted",ml:2},children:["v",text$4(Au.version)]}):null,text$4(Au.protocolVersion)?jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"fg.muted",ml:2},children:["A2A ",text$4(Au.protocolVersion)]}):null,text$4(Au.description)?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",mt:1,mb:0},children:text$4(Au.description)}):null]}),text$4(Au.url)?jsxRuntimeExports.jsx(Row$1,{label:"Endpoint",children:jsxRuntimeExports.jsx(External,{href:text$4(Au.url)})}):null,text$4(Au.documentationUrl)?jsxRuntimeExports.jsx(Row$1,{label:"Documentation",children:jsxRuntimeExports.jsx(External,{href:text$4(Au.documentationUrl)})}):null,text$4(Au.iconUrl)?jsxRuntimeExports.jsx(Row$1,{label:"Icon",children:jsxRuntimeExports.jsx(External,{href:text$4(Au.iconUrl)})}):null,lo?jsxRuntimeExports.jsx(Row$1,{label:"Provider",children:jsxRuntimeExports.jsx(ValueView,{value:lo,depth:1})}):null,Au.supportedInterfaces!==void 0?jsxRuntimeExports.jsx(Row$1,{label:"Interfaces",children:Pu.length===0?jsxRuntimeExports.jsx(None,{}):jsxRuntimeExports.jsx(Box,{display:"flex",flexDirection:"column",gap:1,children:Pu.map((Bu,ju)=>jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,alignItems:"center",flexWrap:"wrap",children:[jsxRuntimeExports.jsx(Label,{size:"small",children:text$4(Bu.protocolBinding)??"binding"}),text$4(Bu.url)?jsxRuntimeExports.jsx(Mono,{children:text$4(Bu.url)}):null,text$4(Bu.protocolVersion)?jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:["v",text$4(Bu.protocolVersion)]}):null]},ju))})}):null,$u!==void 0?jsxRuntimeExports.jsx(Row$1,{label:"Capabilities",children:Ru.length===0?jsxRuntimeExports.jsx(None,{}):jsxRuntimeExports.jsxs(Box,{display:"flex",flexDirection:"column",gap:1,children:[jsxRuntimeExports.jsx(Box,{display:"flex",gap:1,flexWrap:"wrap",children:Ru.filter(([,Bu])=>typeof Bu=="boolean").map(([Bu,ju])=>jsxRuntimeExports.jsxs(Label,{size:"small",variant:ju?"success":"secondary",children:[Bu,": ",ju?"yes":"no"]},Bu))}),Iu.map((Bu,ju)=>jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,alignItems:"baseline",flexWrap:"wrap",children:[jsxRuntimeExports.jsx(Mono,{children:text$4(Bu.uri)??"extension"}),Bu.required===!0?jsxRuntimeExports.jsx(Label,{size:"small",variant:"attention",children:"required"}):null,text$4(Bu.description)?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:text$4(Bu.description)}):null]},ju)),Ru.filter(([Bu,ju])=>typeof ju!="boolean"&&Bu!=="extensions").map(([Bu,ju])=>jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:humanize(Bu)}),jsxRuntimeExports.jsx(ValueView,{value:ju,depth:1})]},Bu))]})}):null,Au.skills!==void 0?jsxRuntimeExports.jsx(Row$1,{label:"Skills",children:Ou.length===0?jsxRuntimeExports.jsx(None,{}):jsxRuntimeExports.jsx(Box,{display:"flex",flexDirection:"column",gap:1,children:Ou.map((Bu,ju)=>jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,fontWeight:"bold"},children:text$4(Bu.name)??text$4(Bu.id)??"skill"}),text$4(Bu.description)?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted",ml:2},children:text$4(Bu.description)}):null,strings(Bu.tags).length>0?jsxRuntimeExports.jsx(Box,{display:"inline-flex",gap:1,ml:2,children:strings(Bu.tags).map(Fu=>jsxRuntimeExports.jsx(Label,{size:"small",children:Fu},Fu))}):null]},ju))})}):null,Au.defaultInputModes!==void 0?jsxRuntimeExports.jsx(Row$1,{label:"Input modes",children:Mu.length?jsxRuntimeExports.jsx(Mono,{children:Mu.join(", ")}):jsxRuntimeExports.jsx(None,{})}):null,Au.defaultOutputModes!==void 0?jsxRuntimeExports.jsx(Row$1,{label:"Output modes",children:Du.length?jsxRuntimeExports.jsx(Mono,{children:Du.join(", ")}):jsxRuntimeExports.jsx(None,{})}):null,Lu.map(([Bu,ju])=>jsxRuntimeExports.jsx(Row$1,{label:humanize(Bu),children:jsxRuntimeExports.jsx(ValueView,{value:ju})},Bu))]})}const LAUNCH_LABEL={local:"launched on the local agent-runtimes server",cloud:"launched on a Datalayer runtime",remote:"reached at a URL the spec named",auto:"launch not decided yet"};function A2AAgentDialog({details:Au,onClose:lo}){const $u=useAgentCard(Au.url),Ru=Au.url?agentCardUrl(Au.url):void 0,Iu=()=>{Ru&&window.open(Ru,"_blank","noopener,noreferrer")};return jsxRuntimeExports.jsx(Dialog$1,{onClose:lo,title:`A2A agent · ${Au.name}`,subtitle:"A separate agent, reached over the A2A protocol",width:"large",footerButtons:[...Ru?[{content:"Open agent card",onClick:Iu}]:[],{content:"Close",onClick:lo,buttonType:"primary"}],children:jsxRuntimeExports.jsxs(Box,{"data-a2a-agent-dialog":Au.name,"data-a2a-card-status":$u.status,display:"flex",flexDirection:"column",gap:3,children:[jsxRuntimeExports.jsxs(Section,{title:"This run",children:[Au.description?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",m:0},children:Au.description}):null,jsxRuntimeExports.jsx(Row$1,{label:"Launch",children:jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0},children:[Au.launch??"auto",jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:[" ","— ",LAUNCH_LABEL[Au.launch??"auto"]??""]})]})}),Au.ref?jsxRuntimeExports.jsx(Row$1,{label:"Agentspec",children:jsxRuntimeExports.jsx(Mono,{children:Au.ref})}):null,jsxRuntimeExports.jsx(Row$1,{label:"State",children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0},children:Au.state??"unknown"})}),Au.taskId?jsxRuntimeExports.jsx(Row$1,{label:"Task",children:jsxRuntimeExports.jsx(Mono,{children:Au.taskId})}):null,Au.runtimeUid?jsxRuntimeExports.jsx(Row$1,{label:"Runtime",children:jsxRuntimeExports.jsx(Mono,{children:Au.runtimeUid})}):null,Au.url?jsxRuntimeExports.jsx(Row$1,{label:"Endpoint",children:jsxRuntimeExports.jsx(External,{href:Au.url})}):null,Ru?jsxRuntimeExports.jsx(Row$1,{label:"Agent card",children:jsxRuntimeExports.jsx(External,{href:Ru})}):null]}),jsxRuntimeExports.jsxs(Section,{title:"Agent card",children:[$u.status==="idle"?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:"No endpoint known yet: the card can be fetched once the agent is launched."}):null,$u.status==="loading"?jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,children:[jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}),jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:["Fetching ",Ru,"…"]})]}):null,$u.status==="error"?jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"danger.fg"},children:["The card could not be fetched from here (",$u.error,"). It may still open in a tab through the link above."]}):null,$u.status==="loaded"?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(CardFields,{card:$u.card}),jsxRuntimeExports.jsxs(Box,{as:"details",fontSize:0,children:[jsxRuntimeExports.jsx(Box,{as:"summary",cursor:"pointer",color:"fg.muted",children:"Raw JSON"}),jsxRuntimeExports.jsx(Box,{as:"pre","data-a2a-card-json":!0,mt:2,p:2,bg:"canvas.subtle",border:"1px solid",borderColor:"border.default",borderRadius:2,overflow:"auto",maxHeight:280,fontSize:0,m:0,children:JSON.stringify($u.card,null,2)})]})]}):null]}),Au.card&&$u.status!=="loaded"?jsxRuntimeExports.jsxs(Section,{title:"Card, as the server saw it at launch",children:[jsxRuntimeExports.jsx(Row$1,{label:"Name",children:jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0},children:[Au.card.name??"—",Au.card.version?` v${Au.card.version}`:""]})}),Au.card.description?jsxRuntimeExports.jsx(Row$1,{label:"Description",children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0},children:Au.card.description})}):null,Au.card.skills&&Au.card.skills.length>0?jsxRuntimeExports.jsx(Row$1,{label:"Skills",children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0},children:Au.card.skills.join(", ")})}):null]}):null]})})}const NO_SUBSCRIPTION=()=>()=>{},NotebookToolSurfaces=reactExports.lazy(()=>__vitePreload(()=>import("./chunks/NotebookToolSurfaces-CTLbTvsS.js"),[],import.meta.url));function normalizeName(Au){return Au.replace(/:[0-9]+\.[0-9]+\.[0-9]+.*$/,"").replace(/[-_]/g,"").toLowerCase()}function toneColorsOf(Au){return!Au||Au==="neutral"?{emphasis:"neutral.emphasis",subtle:"canvas.subtle",muted:"border.default",fg:"fg.default"}:{emphasis:`${Au}.emphasis`,subtle:`${Au}.subtle`,muted:`${Au}.muted`,fg:`${Au}.fg`}}const SUBAGENT_AVATAR_CONFIG={userAvatar:jsxRuntimeExports.jsx(PersonIcon,{size:14}),assistantAvatar:jsxRuntimeExports.jsx(DependabotIcon,{size:14}),showAvatars:!0,avatarSize:24,userAvatarBg:"neutral.muted",assistantAvatarBg:"accent.emphasis"};function buildSubagentDisplayItems(Au,lo){const $u=[],Ru=new Map;let Iu="",Pu=0;const Ou=()=>{Iu.trim()&&$u.push({id:`${lo}:msg:${Pu++}`,role:"assistant",content:Iu,createdAt:new Date(0)}),Iu=""};for(const Mu of Au)switch(Mu.phase){case"text":Iu+=Mu.text??"";break;case"tool_call":{Ou();const Du=`${lo}:tool:${Pu++}`,Lu={id:Du,type:"tool-call",toolCallId:Du,toolName:Mu.toolName??"tool",args:Mu.toolArgs??{},status:"inProgress"};$u.push(Lu),Mu.toolName&&Ru.set(Mu.toolName,Lu);break}case"tool_result":{Ou();const Du=Mu.toolName?Ru.get(Mu.toolName):void 0;if(Du)Du.result=Mu.result,Du.status="complete",Mu.toolName&&Ru.delete(Mu.toolName);else{const Lu=`${lo}:tool:${Pu++}`;$u.push({id:Lu,type:"tool-call",toolCallId:Lu,toolName:Mu.toolName??"tool",args:{},result:Mu.result,status:"complete"})}break}case"error":Ou(),$u.push({id:`${lo}:msg:${Pu++}`,role:"assistant",content:`**⚠️ ${Mu.error??"Subagent failed"}**`,createdAt:new Date(0)});break}return Ou(),$u}function SubagentChatPanel({toolCallId:Au,subagentName:lo,height:$u=280,avatarConfig:Ru=SUBAGENT_AVATAR_CONFIG}){const Iu=useAgentRuntimeSubagentActivityByToolCall(Au,lo),Pu=reactExports.useMemo(()=>buildSubagentDisplayItems(Iu,Au),[Iu,Au]),Ou=reactExports.useRef(null),Mu=reactExports.useMemo(()=>{for(const Wu of Iu)if(Wu.subagentName)return Wu.subagentName;return lo??"subagent"},[Iu,lo]),Du=reactExports.useMemo(()=>Iu.some(Wu=>Wu.phase==="end"||Wu.phase==="error"),[Iu]),Lu=reactExports.useMemo(()=>Iu.some(Wu=>Wu.phase==="error"),[Iu]),Bu=reactExports.useMemo(()=>Iu.some(Wu=>Wu.phase==="error"&&Wu.error===SUBAGENT_STOPPED),[Iu]),ju=reactExports.useMemo(()=>a2aAgentDetails(Iu,lo),[Iu,lo]),Fu=ju!==null,[zu,Uu]=reactExports.useState(!1),Hu=reactExports.useCallback(async(Wu,Ku)=>{if(Ku&&typeof Ku=="object"){const Ju=Ku;Ju.type==="tool-approval-decision"&&typeof Ju.approved=="boolean"&&typeof Ju.approvalId=="string"&&agentRuntimeStore.getState().sendDecision(Ju.approvalId,Ju.approved)}},[]);if(reactExports.useEffect(()=>{Ou.current?.scrollIntoView?.({block:"end"})},[Pu]),Iu.length===0)return null;const Vu=Lu?Bu?"attention":"danger":Du?"success":"accent",Gu=Lu?Bu?"stopped":"failed":Du?"done":Fu&&ju?.state==="launching"?"launching…":"working…";return jsxRuntimeExports.jsxs(Box,{"data-subagent-panel":Mu,"data-subagent-transport":Fu?"a2a":"in-process",mt:2,display:"flex",flexDirection:"column",height:$u,width:"100%",border:"1px solid",borderColor:`${Vu}.emphasis`,borderRadius:2,overflow:"hidden",bg:"canvas.default",children:[jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:1,px:2,py:1,borderBottom:"1px solid",borderColor:`${Vu}.muted`,bg:`${Vu}.subtle`,flexShrink:0,children:[jsxRuntimeExports.jsx(Box,{display:"flex",color:`${Vu}.fg`,children:Fu?jsxRuntimeExports.jsx(BroadcastIcon,{size:14}):jsxRuntimeExports.jsx(DependabotIcon,{size:14})}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:`${Vu}.fg`},children:Fu?"A2A agent":"Subagent"}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,fontWeight:"bold",color:`${Vu}.fg`},children:Mu}),ju?.launch?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:`${Vu}.fg`,opacity:.8},children:ju.launch}):null,ju?jsxRuntimeExports.jsx(Link$1,{as:"button",type:"button","data-a2a-card-button":!0,onClick:()=>Uu(!0),sx:{fontSize:0,ml:1},children:"card"}):null,jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:`${Vu}.fg`,ml:"auto"},children:Gu})]}),zu&&ju?jsxRuntimeExports.jsx(A2AAgentDialog,{details:ju,onClose:()=>Uu(!1)}):null,jsxRuntimeExports.jsx(Box,{flex:1,minHeight:0,overflowY:"auto",children:jsxRuntimeExports.jsx(ChatMessageList,{displayItems:Pu,isLoading:!Du,isStreaming:!Du,showLoadingIndicator:!Du,hideMessagesAfterToolUI:!1,avatarConfig:Ru,padding:2,onRespond:Hu,messagesEndRef:Ou,emptyContent:jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:1,color:"fg.muted",p:2,children:[jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0},children:"Starting…"})]})})})]})}function DefaultToolCallRenderer({item:Au,onRespond:lo,mcpServers:$u,density:Ru}){const Iu=Au.result&&typeof Au.result=="object"?Au.result:void 0,Pu=Au.status==="inProgress"&&Iu?.pending_approval===!0,Ou=typeof Iu?.approval_id=="string"?Iu.approval_id:void 0,Mu=Au.status==="executing",[Du,Lu]=reactExports.useState(),Bu=reactExports.useMemo(()=>normalizeName(Au.toolName),[Au.toolName]),ju=reactExports.useMemo(()=>{const sd=skillIdOfCall(Au.toolName,Au.args);return sd?`skill:${sd}`.toLowerCase():null},[Au.toolName,Au.args]),Fu=reactExports.useMemo(()=>marksOfToolCall(Au.toolName,Au.args,$u),[Au.toolName,Au.args,$u]),zu=useAgentRuntimeStore(sd=>sd.approvals),Uu=reactExports.useMemo(()=>Ou?zu.find(sd=>sd.id===Ou)??null:null,[zu,Ou]),Hu=reactExports.useMemo(()=>ju?zu.find(sd=>sd.tool_name?.toLowerCase()===ju)??null:null,[zu,ju]),Vu=reactExports.useMemo(()=>!Pu&&!Mu?null:zu.find(sd=>normalizeName(sd.tool_name)===Bu)??null,[zu,Bu,Pu,Mu]),Gu=Uu??Hu??Vu,Wu=Gu?.id??Ou??null,Ku=Gu?.status==="approved"?"approved":Gu?.status==="rejected"?"denied":void 0,Ju=reactExports.useCallback(sd=>{if(!Wu)return;const ad=sd==="approve";Lu(ad?"approved":"denied"),lo({type:"tool-approval-decision",approved:ad,approvalId:Wu,toolName:Au.toolName})},[Wu,lo,Au.toolName]),Yu=Pu||!!Wu||!!Ku,Xu=Du||Ku||(Yu?"pending":void 0),ed=Du?"inline":Ku?"external":void 0,td=useAgentRuntimeSubagentActivity(Au.toolCallId),nd=Bu==="delegatetask"||td.length>0,od=typeof Au.args?.subagent_name=="string"?Au.args.subagent_name:typeof Au.args?.subagent=="string"?Au.args.subagent:Bu==="delegatetask"?void 0:Au.toolName;return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(ToolCallDisplay,{toolCallId:Au.toolCallId,toolName:Au.toolName,args:Au.args,result:Au.result,status:Au.status,error:Au.error,executionError:Au.executionError,codeError:Au.codeError,exitCode:Au.exitCode,approvalRequired:Yu,approvalState:Xu,approvalDecisionSource:ed,onApprove:Wu&&!Du&&!Ku?()=>Ju("approve"):void 0,onDeny:Wu&&!Du&&!Ku?()=>Ju("reject"):void 0,approvalLoading:!1,marks:Fu,summary:Au.summary,density:Ru}),nd&&jsxRuntimeExports.jsx(SubagentChatPanel,{toolCallId:Au.toolCallId,subagentName:od})]})}function ChatMessageList({displayItems:Au,actOn:lo,upload:$u,isLoading:Ru,isStreaming:Iu,showLoadingIndicator:Pu,hideMessagesAfterToolUI:Ou,avatarConfig:Mu,padding:Du,notebookToolSurfacesId:Lu,emptyContent:Bu,messagesEndRef:ju,onRespond:Fu,approvalConfig:zu,showTurnFooters:Uu=!1,agentUsage:Hu,onRemoveItems:Vu,renderMessageFooter:Gu,mcpServers:Wu,density:Ku="comfortable"}){const Ju=useOptionalReactorPlatform();reactExports.useSyncExternalStore(Ju?.subscribe??NO_SUBSCRIPTION,()=>Ju?.getRevision()??0);const Yu=Ku==="compact";if(Yu&&(Mu={...Mu,showAvatars:!1},Uu=!1),Au.length===0)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Bu});const Xu=ad=>pd=>{Fu(ad,pd)},ed=Au.some(isToolCallMessage),td=new Map;if(Uu){let ad=-1;Au.forEach((pd,gd)=>{!isToolCallMessage(pd)&&pd.role==="user"&&(ad>=0&&td.set(gd-1,ad),ad=gd)}),ad>=0&&td.set(Au.length-1,ad)}const nd=(ad,pd)=>{const gd=[];for(let xd=ad;xd<=pd;xd+=1){const yd=Au[xd];if(isToolCallMessage(yd))gd.push(`[tool · ${yd.toolName}]`);else{const vd=yd,wd=getMessageText(vd);wd&&gd.push(vd.role==="user"?`You: ${wd}`:wd)}}return navigator.clipboard?.writeText(gd.join(`
3641
3641
 
3642
3642
  `))??Promise.resolve()},od=ad=>{const pd=td.get(ad);if(pd===void 0)return null;const gd=ad===Au.length-1,xd=Ru||Iu;return jsxRuntimeExports.jsx(TurnFooter,{usage:Hu,live:gd&&xd,latest:gd&&!xd,padding:Du,onCopy:()=>nd(pd,ad),onRemove:()=>Vu?.(Au.slice(pd,ad+1).map(yd=>yd.id))})},sd=(ad,pd)=>{if(isToolCallMessage(ad)){const vd=ad.status==="executing"||ad.status==="inProgress"?Xu(ad.toolCallId):void 0,wd=jsxRuntimeExports.jsx(DefaultToolCallRenderer,{item:ad,approvalConfig:zu,onRespond:Xu(ad.toolCallId),mcpServers:Wu,density:Ku}),Td={toolCallId:ad.toolCallId,toolName:ad.toolName,name:ad.toolName,args:ad.args,result:ad.result,status:ad.status,error:ad.error,respond:vd,defaultUI:wd},cd=Lu?jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:wd,children:jsxRuntimeExports.jsx(NotebookToolSurfaces,{documentId:Lu,context:Td})}):wd,dd=Ju?resolveToolResult(Ju,{toolName:ad.toolName,result:ad.result,toolCallId:ad.toolCallId}):void 0,md=dd?jsxRuntimeExports.jsx(ReactorDisplay,{display:dd,context:{...Td,defaultUI:cd},fallback:cd}):cd;return jsxRuntimeExports.jsx(Box,{"data-chat-tool-row":ad.toolName,display:"flex",flexDirection:"column",alignItems:"flex-start",width:"100%",px:Du,py:Yu?"2px":1,children:md},ad.id)}const gd=ad,xd=gd.role==="user",yd=gd.speaker;if(gd.note){const vd=gd.note==="failed"?"danger.fg":gd.note==="waiting"?"attention.fg":"fg.muted",wd=gd.note==="failed"?XCircleFillIcon:gd.note==="waiting"?ClockIcon:SkipIcon;return jsxRuntimeExports.jsx(Box,{display:"flex",justifyContent:"center",px:Du,py:1,children:jsxRuntimeExports.jsxs(Box,{display:"inline-flex",gap:2,alignItems:"center",px:3,py:1,borderRadius:999,bg:"canvas.subtle",border:"1px solid",borderColor:"border.muted",color:vd,fontSize:0,maxWidth:"90%",children:[jsxRuntimeExports.jsx(wd,{size:14}),yd?jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold"},children:yd.name}):null,jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted"},children:getMessageText(gd)}),gd.createdAt?jsxRuntimeExports.jsx(RelativeTime,{datetime:gd.createdAt.toISOString(),sx:{color:"fg.muted"}}):null]})},gd.id)}if(!xd&&Ou&&ed){const vd=getMessageText(gd),wd=pd-1;if(wd>=0){const cd=Au[wd];if(isToolCallMessage(cd))return null}const Td=Au.find(cd=>isToolCallMessage(cd)&&cd.args&&"steps"in cd.args&&Array.isArray(cd.args.steps));if(Td&&vd&&(Td.args.steps.some(md=>md.description&&vd.toLowerCase().includes(md.description.toLowerCase().slice(0,20)))||/^\s*(\d+\.\s|[-*]\s|\*\*)/.test(vd)||vd.includes("**Enabled**")||vd.includes("steps below")))return null}return jsxRuntimeExports.jsx(Box,{"data-chat-message":gd.role,display:"flex",flexDirection:"column",alignItems:xd?"flex-end":"flex-start",px:Du,py:Yu?"2px":1,children:jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,flexDirection:xd?"row-reverse":"row",alignItems:"flex-start",width:"100%",children:[Mu.showAvatars&&jsxRuntimeExports.jsx(Box,{width:Mu.avatarSize,height:Mu.avatarSize,borderRadius:"50%",bg:yd?toneColorsOf(yd.tone).emphasis:xd?Mu.userAvatarBg:Mu.assistantAvatarBg,color:yd?"fg.onEmphasis":xd?"fg.default":"var(--button-primary-fgColor-rest, var(--fgColor-onEmphasis))",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontSize:yd?0:void 0,fontWeight:yd?"bold":void 0,children:yd?yd.initials||"?":xd?Mu.userAvatar:Mu.assistantAvatar}),jsxRuntimeExports.jsxs(Box,{maxWidth:Yu?"92%":"85%",minWidth:0,children:[yd?jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,alignItems:"baseline",flexWrap:"wrap",flexDirection:xd?"row-reverse":"row",mb:1,children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold",fontSize:1,color:toneColorsOf(yd.tone).fg},children:yd.name}),gd.directedTo?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs(Text$3,{sx:{color:"fg.muted",fontSize:0,display:"inline-flex",alignItems:"center",gap:1},children:[gd.steer?"steers":"asks"," ",jsxRuntimeExports.jsx(ArrowRightIcon,{size:12})]}),jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold",fontSize:1,color:toneColorsOf(gd.directedTo.tone).fg},children:gd.directedTo.name})]}):yd.role?jsxRuntimeExports.jsx(Label,{size:"small",children:yd.role}):null,gd.createdAt?jsxRuntimeExports.jsx(RelativeTime,{datetime:gd.createdAt.toISOString(),sx:{fontSize:0,color:"fg.muted"}}):null]}):null,jsxRuntimeExports.jsxs(Box,{p:Yu?1:2,px:2,overflowX:"auto",borderRadius:"bubble",animation:"chatMessageArrive var(--theme-motion-message) var(--theme-motion-easing) both",reducedMotion:{animation:"none"},backgroundColor:xd?"accent.emphasis":yd?toneColorsOf(yd.tone).subtle:"canvas.subtle",border:!xd&&yd?"1px solid":void 0,borderColor:!xd&&yd?toneColorsOf(yd.tone).muted:void 0,color:xd?"var(--button-primary-fgColor-rest, var(--fgColor-onEmphasis))":"fg.default",sx:{"@keyframes chatMessageArrive":{from:{opacity:0,transform:"translateY(4px)"},to:{opacity:1,transform:"none"}},...streamdownCodeBlockStyles},children:[gd.toolChips?.length?jsxRuntimeExports.jsx(Box,{display:"flex",gap:1,flexWrap:"wrap",mb:2,children:gd.toolChips.map((vd,wd)=>jsxRuntimeExports.jsx(Label,{variant:"secondary",size:"small",children:jsxRuntimeExports.jsxs(Box,{as:"span",display:"inline-flex",gap:1,alignItems:"center",children:[jsxRuntimeExports.jsx(ToolsIcon,{size:10})," ",vd]})},`${vd}-${wd}`))}):null,xd?(()=>{const vd=getMessageText(gd),wd=parseFormSubmission(vd);return wd?jsxRuntimeExports.jsx(FormSubmissionMessage,{submission:wd}):jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:Yu?0:1,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:[gd.metadata?.input==="voice"?jsxRuntimeExports.jsx(Box,{as:"span","data-spoken":"",title:"Said aloud","aria-label":"Said aloud:",display:"inline-flex",verticalAlign:"text-bottom",mr:1,opacity:.85,children:jsxRuntimeExports.jsx(ForwardRef$1,{size:14,"aria-hidden":"true"})}):null,vd]})})():gd.live&&!getMessageText(gd)?jsxRuntimeExports.jsx(TypingDots,{size:6}):jsxRuntimeExports.jsx(ChatMarkdown,{density:Ku,text:getMessageText(gd)||(Iu?"...":"")})]}),gd.displays?.length?jsxRuntimeExports.jsx(Box,{"data-chat-displays":"",display:"flex",flexDirection:"column",gap:2,mt:2,width:"100%",children:gd.displays.map(vd=>Ju?jsxRuntimeExports.jsx(ReactorDisplay,{display:vd,act:lo?.(vd),upload:$u},vd.id):jsxRuntimeExports.jsx(DisplayText,{display:vd},vd.id))}):null,Gu?.(gd)?jsxRuntimeExports.jsx(Box,{display:"flex",gap:2,alignItems:"center",mt:1,flexWrap:"wrap",flexDirection:xd?"row-reverse":"row",children:Gu(gd)}):null]})]})},gd.id)};return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Au.map((ad,pd)=>{const gd=sd(ad,pd),xd=od(pd);return gd===null&&xd===null?null:jsxRuntimeExports.jsxs(reactExports.Fragment,{children:[gd,xd]},ad.id)}),Pu&&(Ru||Iu)&&jsxRuntimeExports.jsx(Box,{"data-chat-typing":"",display:"flex",alignItems:"flex-start",px:Du,py:1,children:jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,alignItems:"flex-start",children:[Mu.showAvatars&&jsxRuntimeExports.jsx(Box,{width:Mu.avatarSize,height:Mu.avatarSize,borderRadius:"50%",bg:Mu.assistantAvatarBg,color:"var(--button-primary-fgColor-rest, var(--fgColor-onEmphasis))",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,children:Mu.assistantAvatar}),jsxRuntimeExports.jsx(Box,{display:"flex",alignItems:"center",p:Yu?1:2,borderRadius:"var(--theme-radius-bubble, 6px)",bg:"canvas.subtle",minHeight:Yu?"20px":"32px",children:jsxRuntimeExports.jsx(TypingDots,{})})]})}),jsxRuntimeExports.jsx("div",{ref:ju})]})}const TYPE_MS=45,HOLD_MS=1600,ERASE_MS=14,GAP_MS=2e3,TYPING_START={index:0,shown:1,erasing:!1};function nextTypingStep(Au,lo){const $u=lo[Au.index%lo.length]??"";return Au.erasing?Au.shown>0?{delayMs:ERASE_MS,state:{...Au,shown:Au.shown-1}}:{delayMs:GAP_MS,state:{index:(Au.index+1)%lo.length,shown:TYPING_START.shown,erasing:!1}}:Au.shown<$u.length?{delayMs:TYPE_MS,state:{...Au,shown:Au.shown+1}}:{delayMs:HOLD_MS,state:{...Au,erasing:!0}}}function typedText(Au,lo){return(lo[Au.index%lo.length]??"").slice(0,Au.shown)}function prefersReducedMotion(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function useTypingPlaceholder({phrases:Au,enabled:lo,idle:$u}){const Ru=Au.join(" "),Iu=reactExports.useRef(Au);Iu.current=Au;const[Pu,Ou]=reactExports.useState(TYPING_START),[Mu]=reactExports.useState(prefersReducedMotion),Du=lo&&!Mu&&Au.length>0;return reactExports.useEffect(()=>{Ou(TYPING_START)},[Ru]),reactExports.useEffect(()=>{Du||Ou(Lu=>({...Lu,shown:TYPING_START.shown,erasing:!1}))},[Du]),reactExports.useEffect(()=>{if(!Du)return;const Lu=nextTypingStep(Pu,Iu.current),Bu=setTimeout(()=>Ou(Lu.state),Lu.delayMs);return()=>clearTimeout(Bu)},[Du,Pu]),Du&&typedText(Pu,Au)||$u}function isRendered(Au){return!!Au.content||!!Au.minHeight}function PromptStacks({stacks:Au,disabled:lo=!1}){const $u=Au.filter(isRendered);return $u.length===0?null:jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:$u.map(Ru=>{const Iu=lo||Ru.disabled;return jsxRuntimeExports.jsx(Box,{"data-prompt-stack":Ru.id,"aria-disabled":Iu||void 0,px:Ru.px??2,py:Ru.py??1,minHeight:Ru.minHeight,display:Ru.layout==="block"?void 0:"flex",alignItems:Ru.layout==="block"?void 0:"center",gap:Ru.layout==="block"?void 0:Ru.gap??2,pt:Ru.pt===void 0?void 0:Ru.pt,pb:Ru.pb===void 0?void 0:Ru.pb,borderTop:Ru.bordered?"1px solid":void 0,borderColor:Ru.bordered?"border.default":void 0,bg:Ru.subtle?"canvas.subtle":void 0,opacity:Iu?.5:void 0,pointerEvents:Iu?"none":void 0,children:Ru.content},Ru.id)})})}function InPromptHeader({stacks:Au,children:lo,disabled:$u}){const Ru=[...lo?[{id:"default",content:lo}]:[],...Au??[]];return jsxRuntimeExports.jsx(PromptStacks,{stacks:Ru.map(Iu=>({pt:2,pb:1,...Iu})),disabled:$u})}function BelowPromptHeader({stacks:Au,children:lo,disabled:$u}){const Ru=[...lo?[{id:"default",content:lo}]:[],...Au??[]];return jsxRuntimeExports.jsx(PromptStacks,{stacks:Ru,disabled:$u})}function InPromptFooter({stacks:Au,children:lo,rightContent:$u,isLoading:Ru=!1,sendDisabled:Iu=!1,isKernelBusy:Pu=!1,onSend:Ou,onStop:Mu}){const Du=useChatWords();return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Au&&Au.length>0?jsxRuntimeExports.jsx(PromptStacks,{stacks:Au}):null,jsxRuntimeExports.jsxs(Box,{"data-prompt-stack":"controls",display:"flex",alignItems:"center",gap:2,px:2,pt:1,pb:2,children:[jsxRuntimeExports.jsx(Box,{display:"flex",alignItems:"center",gap:2,flex:1,children:lo}),jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:1,children:[$u,Ru?jsxRuntimeExports.jsx(IconButton,{icon:SquareCircleIcon,"aria-label":Du.stop,"data-prompt-action":"stop",onClick:Mu,size:"small",variant:"invisible"}):Pu?jsxRuntimeExports.jsx(IconButton,{icon:PauseIcon,"aria-label":Du.pauseKernelBusy,onClick:Mu,size:"small",variant:"invisible",disabled:!Mu}):jsxRuntimeExports.jsx(IconButton,{icon:PaperAirplaneIcon,"aria-label":Du.send,onClick:Ou,disabled:Iu,size:"small",variant:"invisible"})]})]})]})}function BelowPromptFooter({stacks:Au,children:lo,disabled:$u}){const Ru=[...lo?[{id:"default",content:lo}]:[],...Au??[]];return jsxRuntimeExports.jsx(PromptStacks,{stacks:Ru,disabled:$u})}function InputPromptText({value:Au,onChange:lo,placeholder:$u="Ask anything…",disabled:Ru=!1,readOnly:Iu=!1,onSubmit:Pu,onHistory:Ou,inputRef:Mu}){const Du=reactExports.useCallback(()=>{const Bu=Mu&&"current"in Mu?Mu.current:null;if(Bu){Bu.style.height="auto";const ju=120,zu=Math.min(Math.max(Bu.scrollHeight,40),ju);Bu.style.height=`${zu}px`,Bu.style.overflowY=Bu.scrollHeight>ju?"auto":"hidden"}},[Mu]);reactExports.useEffect(()=>{Du()},[Au,Du]),reactExports.useEffect(()=>{const Bu=setTimeout(Du,0);return()=>clearTimeout(Bu)},[Du]);const Lu=reactExports.useCallback(Bu=>{if(Bu.key==="Enter"&&!Bu.shiftKey){Bu.preventDefault(),Pu?.();return}if((Bu.key==="ArrowUp"||Bu.key==="ArrowDown")&&Ou&&!Bu.shiftKey&&!Bu.altKey&&!Bu.metaKey&&!Bu.ctrlKey){const ju=Bu.currentTarget,Fu=Bu.key==="ArrowUp"?"up":"down";(Fu==="up"?!ju.value.slice(0,ju.selectionStart).includes(`
3643
3643
  `):!ju.value.slice(ju.selectionEnd).includes(`
@@ -3670,13 +3670,13 @@ ${Pu}\`\`\``}),lo}function ChatMarkdown({text:Au,density:lo="comfortable"}){retu
3670
3670
  `).replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm,"").replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/`([^`]*)`/g,"$1").replace(/^\s{0,3}#{1,6}\s+(.*)$/gm,"$1.").replace(/^\s*(?:[-*+]|\d+[.)])\s+/gm,"").replace(/^\s*>\s?/gm,"").replace(/[*_~]+/g,"").replace(/\.\s*\./g,".").replace(/\s+/g," ").trim()}const END=/[.!?…:;](?=["'»)\]]*(\s|$))/g,SHORTEST=12;class SentenceCutter{said=0;feed(lo){const $u=plainWords(lo),Ru=[];END.lastIndex=this.said;let Iu;for(;(Iu=END.exec($u))!==null;){const Pu=Iu.index+Iu[0].length;if(Pu>=$u.length)break;const Ou=$u.slice(this.said,Pu).trim();Ou.length>=SHORTEST&&(Ru.push(Ou),this.said=Pu)}return Ru}end(lo){const $u=plainWords(lo).slice(this.said).trim();return this.said=plainWords(lo).length,$u?[$u]:[]}}function readAloud(Au,lo){Au.unlock?.(),Au.stop();const $u=new SentenceCutter,Ru=[...$u.feed(lo),...$u.end(lo)];return Ru.forEach(Iu=>Au.say(Iu)),Ru}function readsAloud(Au,lo,$u){return Au.role==="assistant"&&!Au.live&&!Au.note&&Au.id!==$u&&lo.trim().length>0}function ReadAloud({onRead:Au}){return jsxRuntimeExports.jsx(Tooltip,{text:"Read aloud",direction:"n",children:jsxRuntimeExports.jsx(IconButton,{"data-read-aloud":"",icon:UnmuteIcon,"aria-label":"Read aloud",size:"small",variant:"invisible",onClick:Au})})}const DATALAYER_SPEECH_MODELS_URL="https://models-speech.datalayer.tech",DATALAYER_VOICE_ENGINES={transformers:()=>__vitePreload(()=>import("./chunks/transformers.web-CLaqP_Vm.js"),[],import.meta.url),vad:()=>__vitePreload(()=>import("./chunks/index-BSG9WA6E.js").then(Au=>Au.i),[],import.meta.url)};function chatVoiceOf(Au,lo){if(!Au?.enabled||Au.input==="off"&&Au.output==="off")return;if(Au.output!=="off"&&!lo.speechUrl)throw new Error("Its answers are said by Datalayer’s speech service, and its host gave no address for it.");const $u=Au.language||lo.language||"en-US";return{language:$u,input:Au.input==="off"?"off":"push_to_talk",output:Au.output,voice:Au.voice||voiceFor($u)?.id||"",modelsUrl:lo.modelsUrl||DATALAYER_SPEECH_MODELS_URL,engines:DATALAYER_VOICE_ENGINES,speechUrl:lo.speechUrl,token:lo.token,consentKey:lo.consentKey}}function voiceAskedAs(Au,lo,$u){if(!Au)return;const Ru=Au.token||lo,Iu=Au.deployment||$u;return{...Au,...Ru?{token:Ru}:{},...Iu?{deployment:Iu}:{}}}const SILENCE_MS=1500;function settledVoice(Au,lo=heldVoiceSettings()){const $u=voiceForPerson(Au,lo),Ru=$u.output??"off";if(Ru!=="off"&&!$u.speechUrl)throw new Error(`A chat whose answers are heard (${Ru}) names the speech service: its speechUrl is missing.`);return{...$u,output:Ru,voice:$u.voice||voiceFor($u.language)?.id||"",modelsUrl:$u.modelsUrl||DATALAYER_SPEECH_MODELS_URL,engines:$u.engines??DATALAYER_VOICE_ENGINES,silenceMs:$u.silenceMs??SILENCE_MS}}const SYNTHESES_PATH="/api/ai-agents/v1/speech/syntheses",SENTENCES_AHEAD=2;class ServerSpeaker{constructor(lo){this.options=lo}options;context;analyser;gain;buffer;queue=[];playing;running=!1;generation=0;state={speaking:!1};update(lo){this.options={...this.options,...lo}}unlock(){this.audio(),this.context?.resume()}audio(){return this.context||(this.context=new AudioContext,this.analyser=this.context.createAnalyser(),this.analyser.fftSize=512,this.gain=this.context.createGain(),this.analyser.connect(this.gain),this.gain.connect(this.context.destination),this.buffer=new Float32Array(this.analyser.fftSize)),this.context}level(){if(!this.analyser||!this.buffer||!this.state.speaking)return 0;this.analyser.getFloatTimeDomainData(this.buffer);let lo=0;for(const $u of this.buffer)lo+=$u*$u;return Math.min(1,Math.sqrt(lo/this.buffer.length)*6)}speed(){const lo=this.options.rate;return typeof lo=="number"&&Number.isFinite(lo)?Math.min(2,Math.max(.5,lo)):1}loudness(){const lo=this.options.volume;return typeof lo=="number"&&Number.isFinite(lo)?Math.min(1,Math.max(0,lo)):1}set(lo){this.state={...this.state,...lo},this.options.onState?.(this.state)}say(lo){const $u=lo.trim();$u&&(this.queue.push({text:$u,asked:performance.now()}),this.askAhead(),this.running||this.run(this.generation))}askAhead(){for(const lo of this.queue.slice(0,SENTENCES_AHEAD))lo.audio||(lo.audio=this.fetch(lo.text))}async fetch(lo){const{speechUrl:$u,voice:Ru,language:Iu,token:Pu,deployment:Ou,fetcher:Mu=fetch}=this.options;try{const Du=await Mu(`${$u.replace(/\/+$/,"")}${SYNTHESES_PATH}`,{method:"POST",headers:{"Content-Type":"application/json",...Pu?{Authorization:`Bearer ${Pu}`}:{}},body:JSON.stringify({text:lo,voice:Ru,language:Iu,format:"opus",...Ou?{deployment:Ou}:{}})});if(!Du.ok){const Lu=await Du.json().catch(()=>({}));return typeof Lu?.detail=="string"?Lu.detail:`The answer could not be spoken (${Du.status}).`}return await Du.arrayBuffer()}catch{return"Datalayer’s speech service could not be reached: the answer is still written here."}}async run(lo){this.running=!0;try{for(;this.queue.length&&lo===this.generation;){this.askAhead();const $u=this.queue[0],Ru=await $u.audio;if(lo!==this.generation)return;if(typeof Ru=="string"){this.queue=[],this.set({speaking:!1,sentence:void 0,refused:Ru});return}this.queue.shift(),this.askAhead();const Iu=this.audio(),Pu=await Iu.decodeAudioData(Ru);if(lo!==this.generation)return;await new Promise(Ou=>{const Mu=Iu.createBufferSource();Mu.buffer=Pu,Mu.playbackRate.value=this.speed(),this.gain&&(this.gain.gain.value=this.loudness()),Mu.connect(this.analyser),Mu.onended=()=>Ou(),this.playing=Mu,this.set({speaking:!0,sentence:$u.text,refused:void 0}),this.options.onFirstSound?.(Math.round(performance.now()-$u.asked)),Mu.start()}),this.playing=void 0}}finally{lo===this.generation&&(this.running=!1,this.state.speaking&&this.set({speaking:!1,sentence:void 0}))}}stop(){this.generation+=1,this.queue=[],this.running=!1;try{this.playing?.stop()}catch{}this.playing=void 0,this.set({speaking:!1,sentence:void 0})}close(){this.stop(),this.context?.close(),this.context=void 0}}function useVoiceSpeaker(Au,lo=!0){const[$u,Ru]=reactExports.useState({speaking:!1}),Iu=lo&&!!Au&&Au.output!=="off"&&!!Au.speechUrl,Pu=reactExports.useMemo(()=>Iu&&Au?.speechUrl?new ServerSpeaker({speechUrl:Au.speechUrl,voice:Au.voice,language:Au.language,token:Au.token,deployment:Au.deployment,rate:Au.rate,volume:Au.volume,onState:Ru}):void 0,[Iu,Au?.speechUrl]);reactExports.useEffect(()=>{Pu?.update({voice:Au?.voice,language:Au?.language,token:Au?.token,deployment:Au?.deployment,rate:Au?.rate,volume:Au?.volume})},[Pu,Au?.voice,Au?.language,Au?.token,Au?.deployment,Au?.rate,Au?.volume]),reactExports.useEffect(()=>()=>Pu?.close(),[Pu]),reactExports.useEffect(()=>{if(!Pu)return;const Lu=()=>Pu.unlock();return window.addEventListener("pointerdown",Lu,{once:!0}),window.addEventListener("keydown",Lu,{once:!0}),()=>{window.removeEventListener("pointerdown",Lu),window.removeEventListener("keydown",Lu)}},[Pu]);const Ou=reactExports.useCallback(()=>Pu?.stop(),[Pu]),Mu=reactExports.useCallback(Lu=>{Pu&&readAloud(Pu,Lu)},[Pu]),Du=reactExports.useMemo(()=>Pu?()=>Pu.level():void 0,[Pu]);return{speaker:Pu,state:$u,stop:Ou,read:Mu,level:Du}}function answerText(Au){const lo=Au;if(!(!lo||lo.role!=="assistant"||typeof lo.toolName=="string")){if(typeof lo.content=="string")return lo.content;if(Array.isArray(lo.content))return lo.content.map($u=>$u&&typeof $u=="object"&&$u.type==="text"?String($u.text??""):"").join(" ")}}function useSpokenAnswers(Au,lo,$u,Ru){const Iu=reactExports.useRef(new Set),Pu=reactExports.useRef(void 0),Ou=reactExports.useRef(!1);reactExports.useEffect(()=>{if(!$u||!Ru){Ou.current=!1,Pu.current=void 0;return}const Mu=Au.map((Bu,ju)=>({id:String(Bu?.id??ju),text:answerText(Bu)})).filter(Bu=>Bu.text!==void 0);if(!Ou.current){Ou.current=!0,Mu.forEach(Bu=>Iu.current.add(Bu.id));return}const Du=Mu[Mu.length-1];if(!Du||Iu.current.has(Du.id)&&Pu.current?.id!==Du.id)return;Pu.current?.id!==Du.id&&(Iu.current.add(Du.id),Pu.current={id:Du.id,cutter:new SentenceCutter,ended:!1});const Lu=Pu.current;if(!Lu.ended){for(const Bu of Lu.cutter.feed(Du.text??""))Ru.say(Bu);if(!lo){for(const Bu of Lu.cutter.end(Du.text??""))Ru.say(Bu);Lu.ended=!0}}},[Au,lo,$u,Ru])}function ToolApprovalBanner({pendingApprovals:Au,onReview:lo,onApproveAll:$u,onDismiss:Ru,collapsible:Iu=!0}){const Pu=useChatWords(),[Ou,Mu]=reactExports.useState(!1);return Au.length===0?null:Ou?jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,px:3,py:2,bg:"attention.subtle",borderBottom:"1px solid",borderColor:"attention.muted",cursor:"pointer",onClick:()=>Mu(!1),children:[jsxRuntimeExports.jsx(ShieldCheckIcon,{size:16}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,fontWeight:"semibold"},children:Pu.toolApprovalsPending}),jsxRuntimeExports.jsx(CounterLabel,{children:Au.length})]}):jsxRuntimeExports.jsxs(Box,{borderBottom:"1px solid",borderColor:"attention.muted",bg:"attention.subtle",children:[jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",justifyContent:"space-between",px:3,py:2,children:[jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,children:[jsxRuntimeExports.jsx(AlertIcon,{size:16}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,fontWeight:"semibold"},children:Pu.approvalsPending(Au.length)})]}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:1,children:[$u&&Au.length>=1&&jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"primary",leadingVisual:CheckIcon,onClick:$u,children:Pu.approveAll}),Iu&&jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"invisible",onClick:()=>Mu(!0),children:Pu.collapse}),Ru&&jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"invisible",leadingVisual:XIcon,onClick:Ru,"aria-label":Pu.dismiss})]})]}),jsxRuntimeExports.jsx(Box,{px:3,pb:2,children:Au.map(Du=>jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",justifyContent:"space-between",py:1,px:2,mb:1,bg:"canvas.default",borderRadius:2,border:"1px solid",borderColor:"border.default",children:[jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold",fontSize:1},children:Du.toolName}),Du.toolDescription&&jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontSize:0,ml:2},children:Du.toolDescription})]}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"default",onClick:()=>lo(Du),children:Pu.review})]},Du.id))})]})}function ToolApprovalDialog({isOpen:Au,toolName:lo,toolDescription:$u,args:Ru,onApprove:Iu,onDeny:Pu,onClose:Ou,showRememberChoice:Mu=!0}){const Du=useChatWords(),[Lu,Bu]=reactExports.useState(!1),ju=reactExports.useCallback(()=>{Iu(Lu)},[Iu,Lu]),Fu=reactExports.useCallback(()=>{Pu(Lu)},[Pu,Lu]);return Au?jsxRuntimeExports.jsxs(Dialog$1,{onClose:Ou,"aria-labelledby":"tool-approval-title",children:[jsxRuntimeExports.jsx(Dialog$1.Header,{children:jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,children:[jsxRuntimeExports.jsx(AlertIcon,{size:16}),Du.approvalTitle]})}),jsxRuntimeExports.jsxs(Box,{p:3,children:[jsxRuntimeExports.jsxs(Box,{mb:3,children:[jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,mb:2,children:[jsxRuntimeExports.jsx(ToolsIcon,{size:20}),jsxRuntimeExports.jsx(Heading$2,{as:"h4",sx:{fontSize:2},children:lo})]}),$u&&jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontSize:1},children:$u})]}),jsxRuntimeExports.jsxs(Box,{mb:3,children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold",fontSize:1,mb:2,display:"block"},children:Du.arguments}),jsxRuntimeExports.jsx(Box,{as:"pre",p:3,bg:"canvas.subtle",borderRadius:2,border:"1px solid",borderColor:"border.default",overflow:"auto",maxHeight:200,fontSize:0,children:JSON.stringify(Ru,null,2)})]}),jsxRuntimeExports.jsx(Box,{p:3,bg:"attention.subtle",borderRadius:2,border:"1px solid",borderColor:"attention.muted",mb:3,children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1},children:Du.approvalWarning})}),Mu&&jsxRuntimeExports.jsxs(FormControl$1,{sx:{mb:3},children:[jsxRuntimeExports.jsx(Checkbox,{checked:Lu,onChange:zu=>Bu(zu.target.checked)}),jsxRuntimeExports.jsx(FormControl$1.Label,{children:Du.rememberChoice})]}),jsxRuntimeExports.jsxs(Box,{display:"flex",justifyContent:"flex-end",gap:2,children:[jsxRuntimeExports.jsx(ButtonComponent,{variant:"danger",onClick:Fu,leadingVisual:XIcon,children:Du.deny}),jsxRuntimeExports.jsx(ButtonComponent,{variant:"primary",onClick:ju,leadingVisual:CheckIcon,children:Du.approve})]})]})]}):null}const isUsable=Au=>Au.isAvailable!==!1;function usableModels(Au){const lo=Au.filter(isUsable);return lo.length>0?lo:Au}function offeredModels(Au,lo){return usableModels(Au??lo())}const isOffered=(Au,lo)=>!!lo&&Au.some($u=>$u.id===lo&&isUsable($u));function initialModelId(Au,lo){return Au.some(Ru=>Ru.id===lo&&isUsable(Ru))?lo:(Au.find(isUsable)??Au[0])?.id}function readServerCatalogue(Au){return(Au?.models??[]).map(readServerModel)}function readServerDecisions(Au){return{models:Au.decision_models.map(readServerModel),note:Au.decisions_note}}function readServerModel(Au){const lo=Au.missing_env_vars??[],$u=Au.reason??(lo.length>0?`Set ${lo.join(", ")}`:void 0)??Au.warning??void 0;return{id:Au.id,name:Au.name??Au.id,isAvailable:Au.available!==!1,...$u&&Au.available===!1?{unavailableReason:$u}:{}}}const executionCache=new Map,CACHE_TTL_MS=2e3;function getOperationSignature(Au,lo){return`${Au}:${JSON.stringify(lo)}`}function isRecentDuplicate(Au,lo){const $u=getOperationSignature(Au,lo),Ru=executionCache.get($u);if(Ru&&Date.now()-Ru<CACHE_TTL_MS)return!0;for(const[Iu,Pu]of executionCache.entries())Date.now()-Pu>CACHE_TTL_MS*2&&executionCache.delete(Iu);return executionCache.set($u,Date.now()),!1}function processParameters(Au){if(!Au||typeof Au!="object"||Array.isArray(Au))return Au;const lo={};for(const[$u,Ru]of Object.entries(Au))if(typeof Ru=="string"&&(Ru.startsWith("{")||Ru.startsWith("[")))try{lo[$u]=JSON.parse(Ru)}catch{lo[$u]=Ru}else lo[$u]=Ru;return lo}function createAgentRuntimesTool(Au,lo,$u){const Ru=new OperationRunner;return{name:Au.toolReferenceName||Au.name,description:Au.description,parameters:Au.parameters,handler:async Iu=>{if(isRecentDuplicate(Au.name,Iu))return{success:!1,message:"Operation already executed recently (duplicate detected)"};try{const Pu=processParameters(Iu);return await Ru.execute(lo,Pu,{...$u,format:"toon"})}catch(Pu){return console.error("[agent-runtimes] ❌ ERROR in handler:",Pu),{success:!1,error:Pu instanceof Error?Pu.message:String(Pu)}}}}}function createAllAgentRuntimesTools(Au,lo,$u){const Ru=[];for(const Iu of Au){const Pu=lo[Iu.operation];if(!Pu){console.warn(`[agent-runtimes Tools] No operation found for ${Iu.name} (operation: ${Iu.operation})`);continue}const Ou=createAgentRuntimesTool(Iu,Pu,$u);Ru.push(Ou)}return Ru}const useNotebookStore=()=>notebookStore.getState();function createNotebookTools(Au,lo){const $u=new DefaultExecutor(Au,notebookStore.getState());return createAllAgentRuntimesTools(notebookToolDefinitions,notebookToolOperations,{documentId:Au,executor:$u,format:"toon",...lo})}function useNotebookTools(Au,lo){const $u=useNotebookStore(),Ru=reactExports.useMemo(()=>new DefaultExecutor(Au,$u),[Au]),Iu=reactExports.useMemo(()=>({documentId:Au,executor:Ru,format:"toon",...lo}),[Au,Ru,lo]);return reactExports.useMemo(()=>createAllAgentRuntimesTools(notebookToolDefinitions,notebookToolOperations,Iu),[Iu])}const notebookHooks=Object.freeze(Object.defineProperty({__proto__:null,createNotebookTools,useNotebookTools},Symbol.toStringTag,{value:"Module"})),AGENT_SPAN_ATTRIBUTES={operation:"gen_ai.operation.name",agentName:"gen_ai.agent.name",conversationId:"gen_ai.conversation.id",requestModel:"gen_ai.request.model",inputMessages:"gen_ai.input.messages",outputMessages:"gen_ai.output.messages",inputTokens:"gen_ai.usage.input_tokens",outputTokens:"gen_ai.usage.output_tokens",toolName:"gen_ai.tool.name",toolCallId:"gen_ai.tool.call.id",toolArguments:"gen_ai.tool.call.arguments",toolResult:"gen_ai.tool.call.result",toolType:"gen_ai.tool.type",toolKind:"datalayer.tool.kind",markIcon:"datalayer.mark.icon",markEmoji:"datalayer.mark.emoji",origin:"datalayer.span.origin",errorType:"error.type"},A=AGENT_SPAN_ATTRIBUTES;function jsonAttribute(Au){if(Au!==void 0)try{return JSON.stringify(Au)}catch{return String(Au)}}function shortLine(Au,lo=160){const $u=Au.replace(/\s+/g," ").trim();return $u.length>lo?`${$u.slice(0,lo-1)}…`:$u}function argumentsLine(Au,lo=100){if(!Au||typeof Au!="object")return Au===void 0?"":shortLine(String(Au),lo);const $u=Object.entries(Au).map(([Ru,Iu])=>`${Ru}=${typeof Iu=="string"?Iu:JSON.stringify(Iu)}`);return shortLine($u.join(", "),lo)}function messages(Au,lo){return JSON.stringify([{role:Au,parts:[{type:"text",content:lo}]}])}function startAgentTurn(Au,lo){return Au.startSpan(`invoke_agent ${lo.agent}`,{serviceName:lo.agent,parent:null,attributes:{[A.operation]:"invoke_agent",[A.agentName]:lo.agent,[A.requestModel]:lo.model||void 0,[A.conversationId]:lo.conversationId,[A.inputMessages]:messages("user",lo.prompt)}})}function endAgentTurn(Au,lo){const $u=lo.usage;Au.setAttributes({[A.outputMessages]:lo.text?messages("assistant",lo.text):void 0,[A.inputTokens]:$u?.inputTokens??$u?.promptTokens,[A.outputTokens]:$u?.outputTokens??$u?.completionTokens}),lo.error?(Au.setAttribute(A.errorType,"error"),Au.recordException(new Error(lo.error))):Au.setStatus("OK"),Au.end()}function toolType(Au){return Au==="mcp"?"extension":"function"}function startToolCall(Au,lo){return Au.startSpan(`execute_tool ${lo.name}`,{serviceName:lo.agent,...lo.parent?{parent:lo.parent}:{},attributes:{[A.operation]:"execute_tool",[A.agentName]:lo.agent,[A.toolName]:lo.name,[A.toolCallId]:lo.id,[A.toolArguments]:jsonAttribute(lo.args??{}),[A.toolType]:toolType(lo.tool.kind),[A.toolKind]:lo.tool.kind,[A.markIcon]:lo.tool.icon,[A.markEmoji]:lo.tool.emoji,[A.origin]:lo.origin}})}function endToolCall(Au,lo){Au.setAttribute(A.toolResult,jsonAttribute(lo.result)),lo.error?(Au.setAttribute(A.errorType,"tool_error"),Au.recordException(new Error(lo.error))):Au.setStatus("OK"),Au.end()}function sourceOfSpan(Au){const lo=Au.attributes??{};if(lo[A.toolKind])return String(lo[A.toolKind]);if(lo["rpc.service"]==="a2a"||Au.span_name.startsWith("a2a "))return"a2a";if(lo[A.operation]==="invoke_agent")return"model"}const SPAN_SOURCE_LABELS={a2a:"A2A",mcp:"MCP",frontend:"Frontend tool",skill:"Skill",codemode:"Codemode",runtime:"Runtime tool",model:"Model"};function messageText$1(Au){if(typeof Au!="string")return"";try{return(JSON.parse(Au)[0]?.parts??[]).map($u=>typeof $u.content=="string"?$u.content:"").join("")}catch{return""}}function describeAgentSpan(Au){const lo=Au.attributes??{},$u=lo[A.operation];if($u==="execute_tool"){let Mu;try{Mu=JSON.parse(String(lo[A.toolArguments]??"{}"))}catch{Mu=lo[A.toolArguments]}return argumentsLine(Mu)||void 0}if($u==="invoke_agent"){const Mu=messageText$1(lo[A.inputMessages]),Du=messageText$1(lo[A.outputMessages]),Lu=Number(lo[A.inputTokens]??0),Bu=Number(lo[A.outputTokens]??0),ju=Lu+Bu?` · ${Lu+Bu} tokens`:"";return shortLine(Du?`${shortLine(Mu,60)} → ${Du}`:Mu)+ju}const Ru=lo["a2a.message.text"],Iu=lo["a2a.task.state"],Pu=[typeof Iu=="string"?stateWord(Iu):"",typeof Ru=="string"?shortLine(Ru):""].filter(Boolean);if(Pu.length)return Pu.join(" · ");const Ou=lo["a2a.agent.skills"];return Array.isArray(Ou)?Ou.join(", "):void 0}function stateWord(Au){return typeof Au=="string"?Au.replace(/^TASK_STATE_/,"").toLowerCase().replace(/_/g," "):""}const AgentInspectorContext=reactExports.createContext(null);function useAgentInspectorTracer(){return reactExports.useContext(AgentInspectorContext)}const CODEMODE_TOOLS=new Set(["list_servers","list_tool_names","search_tools","get_tool_details","execute_code"]);function classifyToolCall(Au,lo,$u={}){const Ru=marksOfToolCall(Au,lo,$u.mcpServers);return{kind:$u.frontendTools?.includes(Au)?"frontend":Ru?.kind?Ru.kind:CODEMODE_TOOLS.has(Au)?"codemode":$u.fallback??"runtime",...Ru?.icon?{icon:Ru.icon}:{},...Ru?.emoji?{emoji:Ru.emoji}:{}}}function chatSpanRecorder(Au,lo,$u={}){let Ru;const Iu=new Map;return{turnStarted(Pu,Ou){Ru=startAgentTurn(Au,{agent:lo(),prompt:Pu,model:Ou})},turnEnded(Pu){Ru&&(endAgentTurn(Ru,Pu),Ru=void 0)},toolStarted({id:Pu,name:Ou,args:Mu}){const Du=Iu.get(Pu);if(Du){Du.setAttribute("gen_ai.tool.call.arguments",JSON.stringify(Mu??{}));return}Iu.set(Pu,startToolCall(Au,{agent:lo(),name:Ou,id:Pu,args:Mu,tool:classifyToolCall(Ou,Mu,{frontendTools:$u.frontendTools?.(),mcpServers:$u.mcpServers?.()}),...Ru?{parent:Ru.context}:{}}))},toolEnded(Pu,Ou){const Mu=Iu.get(Pu);Mu&&(Iu.delete(Pu),endToolCall(Mu,Ou))}}}const STEP_DISPLAY_TYPE="application/vnd.datalayer.loop.step+json",isStepDisplay=Au=>Au.type===STEP_DISPLAY_TYPE;function stepOfDisplay(Au){const lo=Au.data??{};if(!isStepDisplay(Au)||typeof lo.name!="string")throw new Error(`Display ${Au.id} is not a step`);return{id:Au.id,name:lo.name,kind:typeof lo.kind=="string"?lo.kind:"run",parentId:typeof lo.parent_id=="string"&&lo.parent_id?lo.parent_id:null,input:lo.input??null,output:lo.output??null,error:typeof lo.error=="string"?lo.error:"",ended:typeof lo.ended_at=="string"&&lo.ended_at!==""}}const stepCallId=Au=>`step-${Au}`;function stepItem(Au,lo){const $u=stepCallId(Au.id),Ru=`${Au.kind} step`;return{id:$u,type:"tool-call",toolCallId:$u,toolName:Au.name,args:{kind:Au.kind,...Au.input!==null?{input:Au.input}:{}},...!Au.error&&Au.output!==null?{result:Au.output}:{},status:Au.ended?Au.error?"error":"complete":"executing",...Au.error?{error:Au.error}:{},summary:lo?`${Ru}, inside ${lo}`:Ru}}function withLoopStep(Au,lo){const $u=lo.parentId?Au.find(Ou=>"toolCallId"in Ou&&Ou.toolCallId===stepCallId(lo.parentId)):void 0,Ru=stepItem(lo,$u&&"toolName"in $u?$u.toolName:void 0);let Iu=!1;const Pu=Au.map(Ou=>"toolCallId"in Ou&&Ou.toolCallId===Ru.toolCallId?(Iu=!0,Ru):Ou);return Iu?Pu:[...Au,Ru]}function elementOfDisplay(Au){const lo=Au.data?.where;if(lo!=="panel"&&lo!=="page")return null;const $u=Au.data?.title;return{id:Au.id,where:lo,title:typeof $u=="string"?$u:"",shows:Au}}function withLoopElement(Au,lo){if("closed"in lo)return Au.filter(Ru=>Ru.id!==lo.id);const $u=Au.findIndex(Ru=>Ru.id===lo.id);return $u<0?[...Au,lo]:Au.map((Ru,Iu)=>Iu===$u?lo:Ru)}let opened=[];const listeners$4=new Set,openLoopElements=()=>opened;function applyLoopElement(Au){opened=withLoopElement(opened,Au);for(const lo of[...listeners$4])lo(opened)}const closeLoopElement=Au=>applyLoopElement({id:Au,closed:!0});function clearLoopElements(){opened=[];for(const Au of[...listeners$4])Au(opened)}function onLoopElements(Au){return listeners$4.add(Au),()=>{listeners$4.delete(Au)}}const WINDOW_MESSAGE="message";function windowMessageOf(Au){if(Au.body.name!==WINDOW_MESSAGE)throw new Error(`A window op named ${Au.body.name} is not one this page acts on`);const lo=Au.body.args;if(!lo||!("data"in lo))throw new Error("A window message says no data");return lo.data}const listeners$3=new Set;function tellLoopWindow(Au){for(const lo of[...listeners$3])lo(Au)}function onLoopWindowMessage(Au){return listeners$3.add(Au),()=>{listeners$3.delete(Au)}}function windowTurnErrorOf(Au){let lo=null;for(const $u of Au.split(`
3671
3671
 
3672
3672
  `)){const Ru=$u.split(`
3673
- `).filter(Pu=>Pu.startsWith("data:")).map(Pu=>Pu.slice(5).trim()).join("");if(!Ru)continue;let Iu;try{Iu=JSON.parse(Ru)}catch{continue}if(Iu.type==="RUN_ERROR")lo=String(Iu.message??"The turn failed.");else if(Iu.type==="CUSTOM"&&Iu.name===AGUI_NAME)throw new Error("A reactor.ui op came on the run stream: it comes over the ui socket.")}return lo}function messageOfDisplay(Au){const lo=Au.data?.message_id;if(typeof lo!="string"||!lo)throw new Error(`Display ${Au.id} says no message it is under`);return lo}function speakerOf(Au){return{id:`author:${Au}`,name:Au}}function changed(Au,lo,$u){const Ru=Au.findIndex(Iu=>(Iu.displays??[]).some(Pu=>Pu.id===lo));if(Ru<0)throw new Error(`Display ${lo} is shown under no message here`);return Au.map((Iu,Pu)=>{if(Pu!==Ru)return Iu;const Ou=[];for(const Mu of Iu.displays??[]){if(Mu.id!==lo){Ou.push(Mu);continue}const Du=$u(Mu);Du&&Ou.push({...Du,id:lo})}return{...Iu,displays:Ou}})}function replaced(Au,lo){const $u=Au.findIndex(Ru=>Ru.id===lo.id);return $u<0?[...Au,lo]:Au.map((Ru,Iu)=>Iu===$u?lo:Ru)}function withUiOp(Au,lo){switch(lo.op){case"show":case"ask":{const $u=lo.body,Ru=messageOfDisplay($u);if(!Au.some(Iu=>Iu.id===Ru))throw new Error(`Display ${$u.id} is under message ${Ru}, which is not here`);return Au.map(Iu=>Iu.id===Ru?{...Iu,displays:replaced(Iu.displays??[],$u)}:Iu)}case"remove":{if(Au.some(Ru=>(Ru.displays??[]).some(Iu=>Iu.id===lo.id)))return changed(Au,lo.id,()=>{});if(!Au.some(Ru=>Ru.id===lo.id))throw new Error(`Nothing here is ${lo.id}: it cannot be removed`);return Au.filter(Ru=>Ru.id!==lo.id)}case"patch":{const $u=lo.body;return changed(Au,lo.id,Ru=>applyPatch$1(Ru,$u))}case"append":{const{path:$u,value:Ru}=lo.body;return changed(Au,lo.id,Iu=>applyPatch$1(Iu,[{op:"add",path:`${$u}/-`,value:Ru}]))}case"meta":{const $u=lo.body.author,Ru=Object.keys(lo.body);if(!lo.id||Ru.length!==1||typeof $u!="string"||!$u.trim())throw new Error(`A meta op says ${JSON.stringify(lo.body)}: only a message's author is read`);if(!Au.some(Iu=>Iu.id===lo.id))throw new Error(`Message ${lo.id} is not here: it has no author to say`);return Au.map(Iu=>Iu.id===lo.id?{...Iu,speaker:speakerOf($u.trim())}:Iu)}case"window":throw new Error("A window op is for the page, not the messages");default:return Au}}function routeUiOp(Au,lo,$u){switch(Au.op){case"window":return{routed:{to:"window",data:windowMessageOf(Au)},steps:lo};case"show":case"ask":{if(isStepDisplay(Au.body)){const Iu=applyUiOp(lo,Au);return{routed:{to:"step",step:stepOfDisplay(Au.body)},steps:Iu}}const Ru=elementOfDisplay(Au.body);return Ru?{routed:{to:"element",change:Ru},steps:lo}:{routed:{to:"messages",op:Au},steps:lo}}case"patch":case"append":{if(Au.id in lo.displays){const Ru=applyUiOp(lo,Au);return{routed:{to:"step",step:stepOfDisplay(Ru.displays[Au.id])},steps:Ru}}return{routed:{to:"messages",op:Au},steps:lo}}case"remove":{if(Au.id in lo.displays)throw new Error(`Step ${Au.id} is never removed: it ends`);return $u.has(Au.id)?{routed:{to:"element",change:{id:Au.id,closed:!0}},steps:lo}:{routed:{to:"messages",op:Au},steps:lo}}default:return{routed:{to:"messages",op:Au},steps:lo}}}function placeable(Au,lo){const $u=Iu=>!!Iu&&Au.some(Pu=>Pu.id===Iu),Ru=Iu=>!!Iu&&Au.some(Pu=>(Pu.displays??[]).some(Ou=>Ou.id===Iu));switch(lo.op){case"show":case"ask":{const Iu=lo.body.data?.message_id;return typeof Iu=="string"&&$u(Iu)}case"meta":return $u(lo.id);case"patch":case"append":return Ru(lo.id);case"remove":return Ru(lo.id)||$u(lo.id);default:return!0}}function displayPressOf(Au){const $u=Au?.loop?.action;if(!$u||typeof $u.display_id!="string")return null;if(typeof $u.name!="string"||typeof $u.token!="string")throw new Error("A press of a display says its action and its token");return{action:$u.name,display_id:$u.display_id,token:$u.token,payload:$u.payload??{}}}function withPress(Au,lo){const $u=lo?.press;if(typeof $u!="string"||!$u)throw new Error("The runtime checked the press but named none");const Ru={...Au.loop};return delete Ru.action,{...Au,loop:{...Ru,press:$u}}}function blobOfDataUrl(Au,lo,$u){const[Ru,Iu]=[Au.slice(0,Au.indexOf(",")),Au.slice(Au.indexOf(",")+1)];if(!Ru.startsWith("data:")||Au.indexOf(",")<0)throw new Error(`${lo} could not be read: it is not a data URL.`);const Pu=$u||Ru.slice(5).split(";")[0];let Ou;if(Ru.endsWith(";base64")){const Mu=atob(Iu);Ou=new Uint8Array(Mu.length);for(let Du=0;Du<Mu.length;Du+=1)Ou[Du]=Mu.charCodeAt(Du)}else Ou=new TextEncoder().encode(decodeURIComponent(Iu));return Object.assign(new Blob([Ou],{type:Pu}),{name:lo})}function namesFiles(Au){const lo=Au?.loop?.files;return Array.isArray(lo)&&lo.length>0}async function withUploadedFiles(Au,lo){const $u=Au.loop,Ru=$u.files,Iu=[];for(const Pu of Ru){if(isFileRef(Pu)){Iu.push(Pu);continue}const Ou=Pu;if(typeof Ou.name!="string"||typeof Ou.data_url!="string")throw new Error("A file given is neither the page’s nor a ref.");Iu.push(await lo(blobOfDataUrl(Ou.data_url,Ou.name,typeof Ou.type=="string"?Ou.type:void 0)))}return{...Au,loop:{...$u,files:Iu}}}const EphemeralDocument=vM.lazy(()=>__vitePreload(()=>import("./chunks/EphemeralDocument-DIHjR5l8.js"),[],import.meta.url).then(Au=>({default:Au.EphemeralDocument}))),loadAgentDetails=()=>__vitePreload(()=>import("./chunks/AgentDetails-Xvq2IvHg.js"),[],import.meta.url).then(Au=>({default:Au.AgentDetails})),loadEphemeralNotebook=()=>__vitePreload(()=>import("./chunks/EphemeralNotebook-1Rwa3anx.js"),[],import.meta.url).then(Au=>({default:Au.EphemeralNotebook})),lazyViewRefused=Au=>lo=>jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{p:3,color:"danger.fg"},children:`The ${Au} could not be loaded: ${lo.message}`}),agentDetailsRefused=lazyViewRefused("agent details"),ephemeralNotebookRefused=lazyViewRefused("notebook"),sentPendingPromptKeys=new Set;function frontendToolExpectsArgs(Au){const lo=Au?.parameters;if(!lo)return!1;if(Array.isArray(lo))return lo.length>0;const $u=lo.properties;return $u&&typeof $u=="object"?Object.keys($u).length>0:Object.keys(lo).length>0}function CompanionSurfaceSkeleton({mode:Au}){return jsxRuntimeExports.jsx(Box,{"aria-label":Au==="notebook"?"Preparing notebook…":"Preparing document…",flex:1,minHeight:0,overflow:"hidden",display:"flex",flexDirection:"column",gap:3,p:4,children:Au==="notebook"?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:[0,1,2].map(lo=>jsxRuntimeExports.jsxs(Box,{p:3,border:"1px solid",borderColor:"border.muted",borderRadius:2,bg:"canvas.subtle",display:"flex",flexDirection:"column",gap:2,children:[jsxRuntimeExports.jsx(SkeletonText,{lines:1}),jsxRuntimeExports.jsx(SkeletonText,{lines:lo===0?2:3})]},lo))}):jsxRuntimeExports.jsxs(Box,{maxWidth:860,width:"100%",mx:"auto",display:"flex",flexDirection:"column",gap:3,children:[jsxRuntimeExports.jsx(SkeletonText,{lines:1}),jsxRuntimeExports.jsx(SkeletonText,{lines:4}),jsxRuntimeExports.jsx(SkeletonText,{lines:3}),jsxRuntimeExports.jsx(SkeletonText,{lines:5})]})})}const ThemedJupyterReactTheme=JupyterReactTheme$1;function ThemedChatBoundary({children:Au,themeVariant:lo,colorMode:$u,themeOverrides:Ru}){const Iu=useThemeStore(zu=>zu.colorMode),Pu=useThemeStore(zu=>zu.theme),Ou=$u??Iu,Mu=lo??Pu,Du=useSystemColorMode(),Lu=getThemeConfig(Mu),Bu=Ou==="auto"?Du:Ou,ju={...Bu==="dark"?Lu.themeStyles.dark:Lu.themeStyles.light,...Ru?.[Bu]},Fu=ju.backgroundColor??"";return jsxRuntimeExports.jsx(ThemedJupyterReactTheme,{colormode:Bu,theme:Lu.primerTheme,backgroundColor:Fu,loadJupyterLabCss:!1,style:{...ju,color:"var(--fgColor-default)",fontSize:"var(--text-body-size-medium)",display:"contents"},children:Au})}const AI_AGENTS_API_PREFIX="/api/ai-agents/v1",isDevTraceEnabled=()=>{try{return!1}catch{return!1}},logApprovalTrace=(Au,lo)=>{isDevTraceEnabled()&&console.debug(`[approval-trace] ${Au}`,lo)},normalizeAgentId=Au=>(Au??"").trim().toLowerCase(),normalizeToolName=Au=>Au.replace(/[-_]/g,"").toLowerCase(),normalizeSkillApprovalId=Au=>{const lo=Au.indexOf(":");return lo<=0?Au:Au.slice(0,lo)},stableStringify=Au=>Au===null||typeof Au!="object"?JSON.stringify(Au):Array.isArray(Au)?`[${Au.map($u=>stableStringify($u)).join(",")}]`:`{${Object.entries(Au).sort(([$u],[Ru])=>$u.localeCompare(Ru)).map(([$u,Ru])=>`${JSON.stringify($u)}:${stableStringify(Ru)}`).join(",")}}`,approvalSignature=(Au,lo)=>`${normalizeToolName(Au)}::${stableStringify(lo??{})}`,normalizeAiAgentsBaseUrl=Au=>{const lo=Au.replace(/\/$/,"");return lo.endsWith(AI_AGENTS_API_PREFIX)?lo.slice(0,-AI_AGENTS_API_PREFIX.length):lo},toWsUrl=(Au,lo,$u)=>{try{const Ru=new URL(Au);return Ru.protocol=Ru.protocol==="https:"?"wss:":"ws:",Ru.pathname=lo,$u?Ru.searchParams.set("token",$u):Ru.search="",Ru.toString()}catch{return null}},normalizeApprovalPayload=Au=>{const lo=typeof Au.id=="string"&&Au.id||typeof Au.approval_id=="string"&&Au.approval_id||typeof Au.approvalId=="string"&&Au.approvalId||"",$u=typeof Au.tool_name=="string"&&Au.tool_name||typeof Au.toolName=="string"&&Au.toolName||"";if(!lo||!$u)return null;const Ru=(Au.tool_args&&typeof Au.tool_args=="object"?Au.tool_args:Au.toolArgs&&typeof Au.toolArgs=="object"?Au.toolArgs:void 0)??{};return{id:lo,tool_name:$u,tool_args:Ru,tool_call_id:typeof Au.tool_call_id=="string"&&Au.tool_call_id||typeof Au.toolCallId=="string"&&Au.toolCallId||void 0,note:typeof Au.note=="string"&&Au.note||typeof Au.message=="string"&&Au.message||void 0,status:typeof Au.status=="string"&&Au.status||"pending",agent_id:typeof Au.agent_id=="string"&&Au.agent_id||typeof Au.agentId=="string"&&Au.agentId||void 0,created_at:typeof Au.created_at=="string"&&Au.created_at||typeof Au.createdAt=="string"&&Au.createdAt||void 0,updated_at:typeof Au.updated_at=="string"&&Au.updated_at||typeof Au.updatedAt=="string"&&Au.updatedAt||void 0}},statusFromApprovalEvent=Au=>{if(Au==="tool_approval_created")return"pending";if(Au==="tool_approval_approved")return"approved";if(Au==="tool_approval_rejected")return"rejected";if(Au==="tool_approval_deleted")return"deleted"},RESOLVED_TOOL_CALL_SUPPRESSION_MS=15e3,isApprovalForAgent=(Au,lo)=>{if(!lo)return!0;if(!Au.agent_id)return!1;if(Au.agent_id===lo)return!0;const $u=normalizeAgentId(Au.agent_id),Ru=normalizeAgentId(lo);return $u.includes(Ru)||Ru.includes($u)};function isToolCallOnlyPrompt(Au){const lo=Au.toLowerCase();return/tool\s*call\s*only/.test(lo)||/use\s+(?:a\s+)?tool\s+call\s+only/.test(lo)}function formatToolResultFallback(Au){if(typeof Au=="string")return Au;if(typeof Au=="number"||typeof Au=="boolean"||Au===null)return String(Au);try{const lo=JSON.stringify(Au,null,2);return lo.length>2e3?`${lo.slice(0,2e3)}
3673
+ `).filter(Pu=>Pu.startsWith("data:")).map(Pu=>Pu.slice(5).trim()).join("");if(!Ru)continue;let Iu;try{Iu=JSON.parse(Ru)}catch{continue}if(Iu.type==="RUN_ERROR")lo=String(Iu.message??"The turn failed.");else if(Iu.type==="CUSTOM"&&Iu.name===AGUI_NAME)throw new Error("A reactor.ui op came on the run stream: it comes over the ui socket.")}return lo}function messageOfDisplay(Au){const lo=Au.data?.message_id;if(typeof lo!="string"||!lo)throw new Error(`Display ${Au.id} says no message it is under`);return lo}function speakerOf(Au){return{id:`author:${Au}`,name:Au}}function changed(Au,lo,$u){const Ru=Au.findIndex(Iu=>(Iu.displays??[]).some(Pu=>Pu.id===lo));if(Ru<0)throw new Error(`Display ${lo} is shown under no message here`);return Au.map((Iu,Pu)=>{if(Pu!==Ru)return Iu;const Ou=[];for(const Mu of Iu.displays??[]){if(Mu.id!==lo){Ou.push(Mu);continue}const Du=$u(Mu);Du&&Ou.push({...Du,id:lo})}return{...Iu,displays:Ou}})}function replaced(Au,lo){const $u=Au.findIndex(Ru=>Ru.id===lo.id);return $u<0?[...Au,lo]:Au.map((Ru,Iu)=>Iu===$u?lo:Ru)}function withUiOp(Au,lo){switch(lo.op){case"show":case"ask":{const $u=lo.body,Ru=messageOfDisplay($u);if(!Au.some(Iu=>Iu.id===Ru))throw new Error(`Display ${$u.id} is under message ${Ru}, which is not here`);return Au.map(Iu=>Iu.id===Ru?{...Iu,displays:replaced(Iu.displays??[],$u)}:Iu)}case"remove":{if(Au.some(Ru=>(Ru.displays??[]).some(Iu=>Iu.id===lo.id)))return changed(Au,lo.id,()=>{});if(!Au.some(Ru=>Ru.id===lo.id))throw new Error(`Nothing here is ${lo.id}: it cannot be removed`);return Au.filter(Ru=>Ru.id!==lo.id)}case"patch":{const $u=lo.body;return changed(Au,lo.id,Ru=>applyPatch$1(Ru,$u))}case"append":{const{path:$u,value:Ru}=lo.body;return changed(Au,lo.id,Iu=>applyPatch$1(Iu,[{op:"add",path:`${$u}/-`,value:Ru}]))}case"meta":{const $u=lo.body.author,Ru=Object.keys(lo.body);if(!lo.id||Ru.length!==1||typeof $u!="string"||!$u.trim())throw new Error(`A meta op says ${JSON.stringify(lo.body)}: only a message's author is read`);if(!Au.some(Iu=>Iu.id===lo.id))throw new Error(`Message ${lo.id} is not here: it has no author to say`);return Au.map(Iu=>Iu.id===lo.id?{...Iu,speaker:speakerOf($u.trim())}:Iu)}case"window":throw new Error("A window op is for the page, not the messages");default:return Au}}function routeUiOp(Au,lo,$u){switch(Au.op){case"window":return{routed:{to:"window",data:windowMessageOf(Au)},steps:lo};case"show":case"ask":{if(isStepDisplay(Au.body)){const Iu=applyUiOp(lo,Au);return{routed:{to:"step",step:stepOfDisplay(Au.body)},steps:Iu}}const Ru=elementOfDisplay(Au.body);return Ru?{routed:{to:"element",change:Ru},steps:lo}:{routed:{to:"messages",op:Au},steps:lo}}case"patch":case"append":{if(Au.id in lo.displays){const Ru=applyUiOp(lo,Au);return{routed:{to:"step",step:stepOfDisplay(Ru.displays[Au.id])},steps:Ru}}return{routed:{to:"messages",op:Au},steps:lo}}case"remove":{if(Au.id in lo.displays)throw new Error(`Step ${Au.id} is never removed: it ends`);return $u.has(Au.id)?{routed:{to:"element",change:{id:Au.id,closed:!0}},steps:lo}:{routed:{to:"messages",op:Au},steps:lo}}default:return{routed:{to:"messages",op:Au},steps:lo}}}function placeable(Au,lo){const $u=Iu=>!!Iu&&Au.some(Pu=>Pu.id===Iu),Ru=Iu=>!!Iu&&Au.some(Pu=>(Pu.displays??[]).some(Ou=>Ou.id===Iu));switch(lo.op){case"show":case"ask":{const Iu=lo.body.data?.message_id;return typeof Iu=="string"&&$u(Iu)}case"meta":return $u(lo.id);case"patch":case"append":return Ru(lo.id);case"remove":return Ru(lo.id)||$u(lo.id);default:return!0}}function displayPressOf(Au){const $u=Au?.loop?.action;if(!$u||typeof $u.display_id!="string")return null;if(typeof $u.name!="string"||typeof $u.token!="string")throw new Error("A press of a display says its action and its token");return{action:$u.name,display_id:$u.display_id,token:$u.token,payload:$u.payload??{}}}function withPress(Au,lo){const $u=lo?.press;if(typeof $u!="string"||!$u)throw new Error("The runtime checked the press but named none");const Ru={...Au.loop};return delete Ru.action,{...Au,loop:{...Ru,press:$u}}}function blobOfDataUrl(Au,lo,$u){const[Ru,Iu]=[Au.slice(0,Au.indexOf(",")),Au.slice(Au.indexOf(",")+1)];if(!Ru.startsWith("data:")||Au.indexOf(",")<0)throw new Error(`${lo} could not be read: it is not a data URL.`);const Pu=$u||Ru.slice(5).split(";")[0];let Ou;if(Ru.endsWith(";base64")){const Mu=atob(Iu);Ou=new Uint8Array(Mu.length);for(let Du=0;Du<Mu.length;Du+=1)Ou[Du]=Mu.charCodeAt(Du)}else Ou=new TextEncoder().encode(decodeURIComponent(Iu));return Object.assign(new Blob([Ou],{type:Pu}),{name:lo})}function namesFiles(Au){const lo=Au?.loop?.files;return Array.isArray(lo)&&lo.length>0}async function withUploadedFiles(Au,lo){const $u=Au.loop,Ru=$u.files,Iu=[];for(const Pu of Ru){if(isFileRef(Pu)){Iu.push(Pu);continue}const Ou=Pu;if(typeof Ou.name!="string"||typeof Ou.data_url!="string")throw new Error("A file given is neither the page’s nor a ref.");Iu.push(await lo(blobOfDataUrl(Ou.data_url,Ou.name,typeof Ou.type=="string"?Ou.type:void 0)))}return{...Au,loop:{...$u,files:Iu}}}const EphemeralDocument=vM.lazy(()=>__vitePreload(()=>import("./chunks/EphemeralDocument--pV47gPl.js"),[],import.meta.url).then(Au=>({default:Au.EphemeralDocument}))),loadAgentDetails=()=>__vitePreload(()=>import("./chunks/AgentDetails-Xvq2IvHg.js"),[],import.meta.url).then(Au=>({default:Au.AgentDetails})),loadEphemeralNotebook=()=>__vitePreload(()=>import("./chunks/EphemeralNotebook-BqccUXGd.js"),[],import.meta.url).then(Au=>({default:Au.EphemeralNotebook})),lazyViewRefused=Au=>lo=>jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{p:3,color:"danger.fg"},children:`The ${Au} could not be loaded: ${lo.message}`}),agentDetailsRefused=lazyViewRefused("agent details"),ephemeralNotebookRefused=lazyViewRefused("notebook"),sentPendingPromptKeys=new Set;function frontendToolExpectsArgs(Au){const lo=Au?.parameters;if(!lo)return!1;if(Array.isArray(lo))return lo.length>0;const $u=lo.properties;return $u&&typeof $u=="object"?Object.keys($u).length>0:Object.keys(lo).length>0}function CompanionSurfaceSkeleton({mode:Au}){return jsxRuntimeExports.jsx(Box,{"aria-label":Au==="notebook"?"Preparing notebook…":"Preparing document…",flex:1,minHeight:0,overflow:"hidden",display:"flex",flexDirection:"column",gap:3,p:4,children:Au==="notebook"?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:[0,1,2].map(lo=>jsxRuntimeExports.jsxs(Box,{p:3,border:"1px solid",borderColor:"border.muted",borderRadius:2,bg:"canvas.subtle",display:"flex",flexDirection:"column",gap:2,children:[jsxRuntimeExports.jsx(SkeletonText,{lines:1}),jsxRuntimeExports.jsx(SkeletonText,{lines:lo===0?2:3})]},lo))}):jsxRuntimeExports.jsxs(Box,{maxWidth:860,width:"100%",mx:"auto",display:"flex",flexDirection:"column",gap:3,children:[jsxRuntimeExports.jsx(SkeletonText,{lines:1}),jsxRuntimeExports.jsx(SkeletonText,{lines:4}),jsxRuntimeExports.jsx(SkeletonText,{lines:3}),jsxRuntimeExports.jsx(SkeletonText,{lines:5})]})})}const ThemedJupyterReactTheme=JupyterReactTheme$1;function ThemedChatBoundary({children:Au,themeVariant:lo,colorMode:$u,themeOverrides:Ru}){const Iu=useThemeStore(zu=>zu.colorMode),Pu=useThemeStore(zu=>zu.theme),Ou=$u??Iu,Mu=lo??Pu,Du=useSystemColorMode(),Lu=getThemeConfig(Mu),Bu=Ou==="auto"?Du:Ou,ju={...Bu==="dark"?Lu.themeStyles.dark:Lu.themeStyles.light,...Ru?.[Bu]},Fu=ju.backgroundColor??"";return jsxRuntimeExports.jsx(ThemedJupyterReactTheme,{colormode:Bu,theme:Lu.primerTheme,backgroundColor:Fu,loadJupyterLabCss:!1,style:{...ju,color:"var(--fgColor-default)",fontSize:"var(--text-body-size-medium)",display:"contents"},children:Au})}const AI_AGENTS_API_PREFIX="/api/ai-agents/v1",isDevTraceEnabled=()=>{try{return!1}catch{return!1}},logApprovalTrace=(Au,lo)=>{isDevTraceEnabled()&&console.debug(`[approval-trace] ${Au}`,lo)},normalizeAgentId=Au=>(Au??"").trim().toLowerCase(),normalizeToolName=Au=>Au.replace(/[-_]/g,"").toLowerCase(),normalizeSkillApprovalId=Au=>{const lo=Au.indexOf(":");return lo<=0?Au:Au.slice(0,lo)},stableStringify=Au=>Au===null||typeof Au!="object"?JSON.stringify(Au):Array.isArray(Au)?`[${Au.map($u=>stableStringify($u)).join(",")}]`:`{${Object.entries(Au).sort(([$u],[Ru])=>$u.localeCompare(Ru)).map(([$u,Ru])=>`${JSON.stringify($u)}:${stableStringify(Ru)}`).join(",")}}`,approvalSignature=(Au,lo)=>`${normalizeToolName(Au)}::${stableStringify(lo??{})}`,normalizeAiAgentsBaseUrl=Au=>{const lo=Au.replace(/\/$/,"");return lo.endsWith(AI_AGENTS_API_PREFIX)?lo.slice(0,-AI_AGENTS_API_PREFIX.length):lo},toWsUrl=(Au,lo,$u)=>{try{const Ru=new URL(Au);return Ru.protocol=Ru.protocol==="https:"?"wss:":"ws:",Ru.pathname=lo,$u?Ru.searchParams.set("token",$u):Ru.search="",Ru.toString()}catch{return null}},normalizeApprovalPayload=Au=>{const lo=typeof Au.id=="string"&&Au.id||typeof Au.approval_id=="string"&&Au.approval_id||typeof Au.approvalId=="string"&&Au.approvalId||"",$u=typeof Au.tool_name=="string"&&Au.tool_name||typeof Au.toolName=="string"&&Au.toolName||"";if(!lo||!$u)return null;const Ru=(Au.tool_args&&typeof Au.tool_args=="object"?Au.tool_args:Au.toolArgs&&typeof Au.toolArgs=="object"?Au.toolArgs:void 0)??{};return{id:lo,tool_name:$u,tool_args:Ru,tool_call_id:typeof Au.tool_call_id=="string"&&Au.tool_call_id||typeof Au.toolCallId=="string"&&Au.toolCallId||void 0,note:typeof Au.note=="string"&&Au.note||typeof Au.message=="string"&&Au.message||void 0,status:typeof Au.status=="string"&&Au.status||"pending",agent_id:typeof Au.agent_id=="string"&&Au.agent_id||typeof Au.agentId=="string"&&Au.agentId||void 0,created_at:typeof Au.created_at=="string"&&Au.created_at||typeof Au.createdAt=="string"&&Au.createdAt||void 0,updated_at:typeof Au.updated_at=="string"&&Au.updated_at||typeof Au.updatedAt=="string"&&Au.updatedAt||void 0}},statusFromApprovalEvent=Au=>{if(Au==="tool_approval_created")return"pending";if(Au==="tool_approval_approved")return"approved";if(Au==="tool_approval_rejected")return"rejected";if(Au==="tool_approval_deleted")return"deleted"},RESOLVED_TOOL_CALL_SUPPRESSION_MS=15e3,isApprovalForAgent=(Au,lo)=>{if(!lo)return!0;if(!Au.agent_id)return!1;if(Au.agent_id===lo)return!0;const $u=normalizeAgentId(Au.agent_id),Ru=normalizeAgentId(lo);return $u.includes(Ru)||Ru.includes($u)};function isToolCallOnlyPrompt(Au){const lo=Au.toLowerCase();return/tool\s*call\s*only/.test(lo)||/use\s+(?:a\s+)?tool\s+call\s+only/.test(lo)}function formatToolResultFallback(Au){if(typeof Au=="string")return Au;if(typeof Au=="number"||typeof Au=="boolean"||Au===null)return String(Au);try{const lo=JSON.stringify(Au,null,2);return lo.length>2e3?`${lo.slice(0,2e3)}
3674
3674
  ...`:lo}catch{return"Tool completed successfully."}}function parseEnabledMcpToolsByServer(Au){if(!Au||typeof Au!="object")return null;const lo=Au.enabled_tools_by_server;if(lo==null)return new Map;if(typeof lo!="object")return new Map;const $u=new Map;for(const[Ru,Iu]of Object.entries(lo)){if(!Array.isArray(Iu))continue;const Ou=Iu.filter(Mu=>typeof Mu=="string"&&Mu.length>0).map(Mu=>{const Du=Mu.indexOf("__");return Du>=0?Mu.slice(Du+2):Mu});$u.set(Ru,new Set(Ou))}return $u}function parseApprovedMcpToolsByServer(Au){if(!Au||typeof Au!="object")return null;const lo=Au.approved_tools_by_server;if(lo==null)return new Map;if(typeof lo!="object")return new Map;const $u=new Map;for(const[Ru,Iu]of Object.entries(lo)){if(!Array.isArray(Iu))continue;const Ou=Iu.filter(Mu=>typeof Mu=="string"&&Mu.length>0).map(Mu=>{const Du=Mu.indexOf("__");return Du>=0?Mu.slice(Du+2):Mu});$u.set(Ru,new Set(Ou))}return $u}const WELCOME_AT=new Date(0);function ChatBase(Au){const{agentRuntimeConfig:lo,protocol:$u,useStore:Ru=!0,disableInternalJupyterTheme:Iu=!1,themeVariant:Pu,colorMode:Ou,themeOverrides:Mu}=Au,Bu=lo?{type:(typeof $u=="string"?$u:void 0)||lo.protocol||"vercel-ai",endpoint:lo.url,authToken:lo.authToken,agentId:lo.agentId,enableConfigQuery:!0,configEndpoint:`${lo.url}/api/v1/config`}:typeof $u=="object"?$u:void 0,ju=lo?!1:Ru,Fu=reactExports.useContext(QueryClientContext),zu={...Au,protocol:Bu,useStore:ju},Uu=jsxRuntimeExports.jsx(ChatBaseInner,{...zu}),Hu=Iu?Uu:jsxRuntimeExports.jsx(ThemedChatBoundary,{themeVariant:Pu,colorMode:Ou,themeOverrides:Mu,children:Uu});return Fu?Hu:jsxRuntimeExports.jsx(QueryClientProvider,{client:internalQueryClient,children:Hu})}function ChatBaseInner({title:Au,subtitle:lo,showHeader:$u=!1,showTokenUsage:Ru=!0,showContextRing:Iu=!1,showLoadingIndicator:Pu=!0,showErrors:Ou=!0,showInput:Mu=!0,showModelSelector:Du=!0,showToolsMenu:Lu=!0,showSkillsMenu:Bu=!0,disableInputPrompt:ju=!1,promptVariant:Fu,mentionableAgents:zu,promptCommands:Uu,showAgentsMenu:Hu=!0,agents:Vu,selectedAgentId:Gu,onSelectAgent:Wu,disabled:Ku,disableReason:Ju,overlay:Yu,launching:Xu=!1,launchingMessage:ed,autoConnect:td=!0,codemodeEnabled:nd=!1,onToggleCodemode:od,initialModel:sd,availableModels:ad,mcpServers:pd,initialSkills:gd,className:xd,loadingState:yd,headerActions:vd,kernelIndicatorState:wd,kernelIndicatorPlacement:Td="left",kernel:cd,kernelEnvironmentName:dd,kernelCpu:md,kernelMemory:ld,kernelGpu:hd,themeVariant:bd,colorMode:Sd,chatViewMode:kd,onChatViewModeChange:Rd,disabledViewModes:Od,useStore:Bd=!0,protocol:Ed,onSendMessage:Ad,onSendReady:$d,onLoadingChange:qd,onSpeakingChange:Dd,onContextSnapshot:Hd,enableStreaming:nh=!1,brandIcon:Xd,avatarConfig:vh,headerButtons:ih,showPoweredBy:xh=!1,poweredByProps:bh,emptyState:eh,renderHeader:rh,showTurnFooter:ah=!0,notebookToolSurfacesId:Dh,footerContent:Gd,welcome:zd,trailingContent:Id,voice:Pd,voiceSpeaking:Wd=!1,onStopSpeaking:Nd,onReadAloud:Kd,showInformation:Qd=!1,onInformationClick:fh,headerContent:_h,children:Sh,borderRadius:Wh,backgroundColor:Md,border:_d,boxShadow:Vd,compact:Fd=!1,placeholder:uh,description:wh="Start a conversation with the AI agent.",onStateUpdate:Eh,onNewChat:kh,onClear:Ph,onMessagesChange:Fh,onItemsChange:Uh,onDisplayItemsChange:Jh,autoFocus:Oh=!1,suggestions:np,submitOnSuggestionClick:ap=!0,hideMessagesAfterToolUI:hp=!1,focusTrigger:bp,frontendTools:Qh,enableEphemeralNotebook:_p=!1,initialEphemeralNotebookOpen:lp=!0,onEphemeralNotebookOpenChange:up,enableEphemeralDocument:Hh=!1,initialEphemeralSurfaceMode:zh,onEphemeralSurfaceModeChange:Xh,collapsed:Uf=!1,onExpandFromCollapsed:$p,ephemeralNotebookToolbar:Rh,ephemeralNotebookToolbarExtraItems:jh,ephemeralDocumentToolbarExtraItems:af,ephemeralNotebookCollaborationProvider:qp,ephemeralNotebookCollaborationDocumentId:lf,ephemeralDocumentCollaboration:Xp,ephemeralRuntimeOverride:tp,onToolCallStart:Vp,onToolCallComplete:$f,inspector:cm,onAuthorizationRequired:Hf,connectedIdentities:qf,runtimeId:Qp,thread:fp,historyEndpoint:jp,historyAuthToken:Sp,pendingPrompt:Bp,contextSnapshot:Of,mcpStatusData:ef,sandboxStatusData:cf,showToolApprovalBanner:yp=!0,pendingApprovals:Jf,onApproveApproval:vf,onRejectApproval:vm}){const Mf=useChatWords();reactExports.useEffect(()=>{setupPrimerPortals()},[]);const Fm=useChatAvailability(),uf=Ku??Fm.disabled,Am=Ju??Fm.disableReason,{theme:Cm}=useThemeStore(),Vf=getColorPalette(Cm,"dark").textLight,Lh=useAgentRuntimeStore(jd=>jd.approvals),Ud=useAgentRuntimeStore(jd=>jd.historyVersion),lh=useAgentRuntimeStore(jd=>jd.mcpStatus),Mh=ef??lh,Nh=typeof Ed=="object"?Ed:void 0,mp=useCoreStore(jd=>jd.configuration?.aiAgentsUrl),$h=Nh?.agentId||Qp,ep=Qp||$h,Fp=Nh?.authToken,Sf=reactExports.useRef(`ephemeral-notebook-${Math.random().toString(36).slice(2,10)}`),Ip=Qp||Nh?.agentId||$h,zp=lf||(Ip?`ephemeral-notebook-${Ip}`:Sf.current),Yp=useAgentRuntimeStore(jd=>jd.getEphemeralNotebookModel(zp)),um=useAgentRuntimeStore(jd=>jd.setEphemeralNotebookModel),nm=reactExports.useCallback(jd=>{um(zp,jd)},[zp,um]),bf=Xp?.roomId||(Ip?`ephemeral-document-${Ip}`:`ephemeral-document-${Sf.current}`),$m=useAgentRuntimeStore(jd=>jd.getEphemeralDocumentModel(bf)),Rm=useAgentRuntimeStore(jd=>jd.setEphemeralDocumentModel),r0=reactExports.useCallback(jd=>{Rm(bf,jd)},[bf,Rm]),bm=zh??(_p&&lp?"notebook":"none"),[Cf,dm]=reactExports.useState(bm),Df=reactExports.useCallback(jd=>{dm(jd),Xh?.(jd),up?.(jd==="notebook")},[Xh,up]),Kp=_p&&Cf==="notebook",Rf=Hh&&Cf==="document",xp=Kp||Rf,If=xp&&Uf,Nf=If?{key:"ephemeral-surface",type:"custom",order:900,render:()=>jsxRuntimeExports.jsx(EphemeralSurfaceControl,{mode:Cf,onChange:Df,enableNotebook:_p,enableDocument:Hh,enableChatOnly:!1})}:null,Vh=Nf?[...jh??[],Nf]:jh,Up=Nf?[...af??[],Nf]:af,[tf,Tf]=reactExports.useState(null);reactExports.useEffect(()=>{if(!Kp){Tf(null);return}const jd=()=>notebookStore.getState().selectNotebook(zp)?.adapter?.kernel??null,Zd=()=>{const sh=jd();Tf(gh=>gh?.id===sh?.id?gh:sh)};Zd();const Yd=window.setInterval(Zd,750),dh=notebookStore.subscribe(Zd);return()=>{window.clearInterval(Yd),dh()}},[Kp,zp]);const[Lf,hm]=reactExports.useState(null),Xf=reactExports.useCallback(jd=>{hm(Zd=>Zd?.id===jd?.id?Zd:jd)},[]);reactExports.useEffect(()=>{Rf||hm(null)},[Rf]);const kp=xp&&isFloatingChatViewMode(kd),Gf=kd==="floating-small"||kd==="floating-draggable",Tm=useNotebookTools(zp),[df,Zh]=reactExports.useState([]),Hp=reactExports.useCallback(jd=>{Zh(jd)},[]),Pf=reactExports.useMemo(()=>Kp?[...Qh||[],...Tm]:Rf?[...Qh||[],...df]:Qh,[Kp,Rf,Qh,Tm,df]),rf=reactExports.useMemo(()=>normalizeAiAgentsBaseUrl(mp||DEFAULT_SERVICE_URLS.AI_AGENTS),[mp]),hf=reactExports.useRef(null),x0=reactExports.useRef(new Map),zm=reactExports.useCallback((jd,Zd,Yd)=>{const dh=hf.current;if(!dh||dh.readyState!==WebSocket.OPEN)return logApprovalTrace("send_decision_skipped_ws_not_ready",{approvalId:jd,approved:Zd,wsReadyState:dh?.readyState}),!1;try{return logApprovalTrace("send_decision",{approvalId:jd,approved:Zd,hasNote:!!Yd}),dh.send(JSON.stringify({type:"tool_approval_decision",approvalId:jd,approved:Zd,...Yd?{note:Yd}:{}})),!0}catch{return logApprovalTrace("send_decision_failed",{approvalId:jd,approved:Zd}),!1}},[]),Um=reactExports.useCallback(()=>{const jd=hf.current;if(!jd||jd.readyState!==WebSocket.OPEN)return!1;try{return jd.send(JSON.stringify({type:"tool-approvals-history"})),logApprovalTrace("request_history",{}),!0}catch{return!1}},[]),pm=reactExports.useCallback(jd=>{jd&&(x0.current.set(jd,Date.now()+RESOLVED_TOOL_CALL_SUPPRESSION_MS),logApprovalTrace("suppress_pending_for_tool_call",{toolCallId:jd,windowMs:RESOLVED_TOOL_CALL_SUPPRESSION_MS}))},[]),kg=reactExports.useCallback(jd=>{if(!jd)return!1;const Zd=x0.current.get(jd);return Zd?Zd<Date.now()?(x0.current.delete(jd),!1):!0:!1},[]),Q0=reactExports.useCallback((jd,Zd,Yd)=>{window.setTimeout(()=>{if(!agentRuntimeStore.getState().approvals.some(gh=>gh.id===jd&&gh.status==="pending"))return;const sh=zm(jd,Zd,Yd);logApprovalTrace("retry_send_decision",{approvalId:jd,approved:Zd,sent:sh}),sh&&Um()},500)},[Um,zm]),Qg=reactExports.useMemo(()=>Jf||Lh.filter(jd=>jd.status==="pending"&&isApprovalForAgent(jd,$h)).map(jd=>({id:jd.id,toolName:jd.tool_name,toolDescription:jd.note??void 0,args:jd.tool_args??{},agentId:jd.agent_id??"",requestedAt:jd.created_at??new Date().toISOString()})),[Jf,Lh,$h]),e1=reactExports.useCallback((jd,Zd)=>{const Yd=agentRuntimeStore.getState().approvals.find(Kh=>Kh.id===jd),dh=Yd?.tool_name;if(!dh)return;const gh=(()=>{if(dh.startsWith("skill:")){const qh=dh.slice(6);return qh?normalizeSkillApprovalId(qh):null}if(!new Set(["run_skill_script","load_skill","read_skill_resource"]).has(dh))return null;const cp=Yd?.tool_args??{},Gh=cp.skill_name??cp.skill??cp.name;return typeof Gh!="string"||!Gh?null:normalizeSkillApprovalId(Gh)})();if(gh){T0(cp=>{const Gh=new Map(cp);return Gh.set(gh,Zd),Gh}),agentRuntimeStore.getState().sendRawMessage({type:Zd?"skill_approve":"skill_unapprove",skillId:gh},$h)||console.warn("[ChatBase] skill_approve persistence dropped: websocket not ready");return}const Th=dh.indexOf("__");if(Th!==-1){const Kh=dh.slice(0,Th),cp=dh.slice(Th+2);agentRuntimeStore.getState().sendRawMessage({type:"mcp_server_tool_approve",serverId:Kh,toolName:cp,approved:Zd},$h)||console.warn("[ChatBase] mcp_server_tool_approve persistence dropped: websocket not ready")}},[$h]),eg=reactExports.useCallback(async(jd,Zd,Yd)=>{const sh=agentRuntimeStore.getState().approvals.find(Kh=>Kh.id===jd)?.tool_call_id??Yd;pm(sh);const gh=zm(jd,!0,Zd);gh||console.warn("[ChatBase] ai-agents tool_approval_decision not sent: websocket not ready");const Th=agentRuntimeStore.getState().sendDecision(jd,!0,Zd,sh,$h);Th?e1(jd,!0):console.warn("[ChatBase] tool_approval_decision dropped: websocket not ready"),(gh||Th)&&agentRuntimeStore.getState().removeApproval(jd),Um(),Q0(jd,!0,Zd),await vf?.(jd,Zd)},[$h,pm,vf,e1,Q0,Um,zm]),h0=reactExports.useCallback(async(jd,Zd,Yd)=>{const sh=agentRuntimeStore.getState().approvals.find(Kh=>Kh.id===jd)?.tool_call_id??Yd;pm(sh);const gh=zm(jd,!1,Zd);gh||console.warn("[ChatBase] ai-agents tool_approval_decision not sent: websocket not ready");const Th=agentRuntimeStore.getState().sendDecision(jd,!1,Zd,sh,$h);Th||console.warn("[ChatBase] tool_approval_decision dropped: websocket not ready"),(gh||Th)&&agentRuntimeStore.getState().removeApproval(jd),Um(),Q0(jd,!1,Zd),await vm?.(jd,Zd)},[$h,pm,vm,Q0,Um,zm]),t1=reactExports.useRef(null),r1=reactExports.useCallback(jd=>{const Zd=agentRuntimeStore.getState(),Yd=new Set([jd.id]),sh=!!jd.tool_name?approvalSignature(jd.tool_name,jd.tool_args??{}):null;for(const gh of Zd.approvals){if(gh.status!=="pending"||!isApprovalForAgent(gh,$h))continue;if(gh.id===jd.id){Yd.add(gh.id);continue}if(jd.tool_call_id&&gh.tool_call_id&&gh.tool_call_id===jd.tool_call_id){Yd.add(gh.id);continue}if(!sh||!gh.tool_name)continue;approvalSignature(gh.tool_name,gh.tool_args??{})===sh&&Yd.add(gh.id)}for(const gh of Yd)Zd.removeApproval(gh)},[$h]);reactExports.useEffect(()=>{if(!yp||Jf||!Fp)return;const jd=toWsUrl(rf,`${AI_AGENTS_API_PREFIX}/ws`,Fp);if(!jd)return;let Zd=!1;const Yd=new WebSocket(jd);return hf.current=Yd,Yd.onopen=()=>{logApprovalTrace("ws_open_request_history",{activeAgentId:$h}),Yd.send(JSON.stringify({type:"tool-approvals-history"}))},Yd.onmessage=dh=>{try{const sh=JSON.parse(String(dh.data)),gh=[],Th=typeof sh.type=="string"?sh.type:void 0,Kh=typeof sh.event=="string"?sh.event:void 0;if(Th==="tool-approvals-history"){const qh=(sh.data&&typeof sh.data=="object"?sh.data:{}).approvals;if(Array.isArray(qh))for(const Yh of qh)Yh&&typeof Yh=="object"&&gh.push(Yh)}else if(Kh?.startsWith("tool_approval_")){const Gh=sh.data&&typeof sh.data=="object"?sh.data:sh.payload&&typeof sh.payload=="object"?sh.payload:null;if(Gh){const qh=statusFromApprovalEvent(Kh);logApprovalTrace("recv_tool_approval_event",{event:Kh,approvalId:typeof Gh.id=="string"?Gh.id:typeof Gh.approval_id=="string"?Gh.approval_id:void 0,status:typeof Gh.status=="string"?Gh.status:qh}),gh.push(qh&&typeof Gh.status!="string"?{...Gh,status:qh}:Gh)}}if(gh.length===0)return;const cp=agentRuntimeStore.getState();for(const Gh of gh){let qh=normalizeApprovalPayload(Gh);if(!qh){const gp=typeof Gh.id=="string"&&Gh.id||typeof Gh.approval_id=="string"&&Gh.approval_id||typeof Gh.approvalId=="string"&&Gh.approvalId||"",dp=typeof Gh.status=="string"&&Gh.status||"";if(gp&&dp&&dp!=="pending"){const Dp=cp.approvals.find(xf=>xf.id===gp);Dp&&(qh={...Dp,status:dp})}}if(!qh)continue;const Yh=qh.agent_id||!$h?qh:{...qh,agent_id:$h};if(isApprovalForAgent(Yh,$h)){if(Yh.status==="pending"&&kg(Yh.tool_call_id)){logApprovalTrace("drop_transient_pending",{approvalId:Yh.id,toolCallId:Yh.tool_call_id,status:Yh.status});continue}logApprovalTrace("apply_tool_approval_update",{approvalId:Yh.id,status:Yh.status,agentId:Yh.agent_id,activeAgentId:$h}),Yh.status==="pending"?cp.upsertApproval(Yh):(r1(Yh),t1.current?.(Yh,Yh.status==="approved",Yh.note??void 0))}}}catch{}},Yd.onclose=()=>{Zd||(hf.current=null)},Yd.onerror=()=>{hf.current=null},()=>{Zd=!0,hf.current=null,Yd.close()}},[yp,Jf,rf,Fp,$h,kg,r1]);const ip=typeof Ed=="object"?Ed:void 0,C1=ip?JSON.stringify(ip):"",Ag="agent-runtimes",ym=useChatStore(jd=>jd.clearMessages),j0=ip?.type==="a2a",[wf,Rp]=reactExports.useState([]),[p0,om]=reactExports.useState(null),[sv,tg]=reactExports.useState(!1),[im,Im]=reactExports.useState(!1),[n1,rg]=reactExports.useState(),[o1,Hm]=reactExports.useState(!1),[ng,Pm]=reactExports.useState(null),[sm,og]=reactExports.useState("");reactExports.useEffect(()=>{if(!cd){rg(void 0);return}rg(cd.status);const jd=(Zd,Yd)=>{rg(Yd)};return cd.statusChanged.connect(jd),()=>{cd.statusChanged.disconnect(jd)}},[cd]);const[i1,_f]=reactExports.useState(!ep),[qm,S0]=reactExports.useState(0),n0=reactExports.useRef(new Map),f0=reactExports.useRef(emptyUiModel()),s1=reactExports.useRef(new Set),[m0,a1]=reactExports.useState(!1),Bh=reactExports.useRef(null),wp=Bp&&[Qp||jp||ip?.endpoint||ip?.agentId,Bp].filter(Boolean).join("::"),[pf,_m]=reactExports.useState(""),[Jp,Om]=reactExports.useState(new Map),[w0,fm]=reactExports.useState(new Map),[E0,T1]=reactExports.useState([]),Vm=useAgentRuntimeWsState(),Wf=!!ip?.enableConfigQuery&&td,Cp=useConfig(Wf,ip?.configEndpoint,ip?.authToken,ip?.agentId),Gm=useSkills(Wf&&Bu,ip?.configEndpoint,ip?.authToken),{enableSkill:C0,disableSkill:F0,approveSkill:av,unapproveSkill:k1}=useSkillActions($h),[Kv,T0]=reactExports.useState(new Map);reactExports.useEffect(()=>{T0(new Map)},[$h]);const ig=reactExports.useMemo(()=>{const jd=new Set;for(const Zd of Gm.data?.skills??[])(Zd.status==="enabled"||Zd.status==="loaded")&&jd.add(Zd.id);return jd},[Gm.data]);reactExports.useEffect(()=>{if(!$h||Ig.current.has($h))return;const jd=Gm.data?.skills??[];if(jd.length===0)return;if(jd.some(sh=>sh.status==="enabled"||sh.status==="loaded")){Ig.current.add($h);return}const Yd=jd.filter(sh=>sh.status==="available").map(sh=>sh.id).filter(Boolean);if(Yd.length===0){Ig.current.add($h);return}Yd.every(sh=>C0(sh))&&Ig.current.add($h)},[$h,Gm.data,C0]);const sg=reactExports.useMemo(()=>{const jd=new Set;for(const Zd of Gm.data?.skills??[])Zd.approved===!0&&jd.add(Zd.id);return Kv.forEach((Zd,Yd)=>{Zd?jd.add(Yd):jd.delete(Yd)}),jd},[Kv,Gm.data]),A1=reactExports.useMemo(()=>{const jd=Cp.data?.builtinTools??[],Zd=ip?.options?.frontendTools??[],Yd=new Set(jd.map(sh=>sh.name)),dh=[...Pf??[],...Zd].filter(sh=>Yd.has(sh.name)?!1:(Yd.add(sh.name),!0)).map(sh=>({id:sh.name,name:sh.name}));return{runtime:jd,frontend:dh}},[Cp.data?.builtinTools,Pf,ip?.options]),$g=reactExports.useMemo(()=>Vu??($h?[{id:$h,name:Au||$h,description:lo||wh}]:[]),[Vu,$h,Au,lo,wh]),g0=typeof ip?.options?.model=="string"?(ip?.options).model:void 0,Wm=reactExports.useMemo(()=>{const jd=ad||Cp.data?.models||(Cp.isError?[]:void 0);return offeredModels(jd,()=>{const Zd=Object.values(AI_MODEL_CATALOGUE).filter(Yd=>Yd.available&&isChatModel(Yd)).map(Yd=>({id:Yd.id,name:Yd.name,provider:Yd.provider}));return Zd.length>0?Zd:g0?[{id:g0,name:g0,provider:"inference"}]:[]})},[ad,Cp.data?.models,Cp.isError,g0]),lv=reactExports.useMemo(()=>zu??$g.map(jd=>({name:jd.name,description:jd.description,icon:jd.icon,disabled:jd.id===(Gu??$g[0]?.id),disabledReason:`You are already talking to ${jd.name}`})),[zu,$g,Gu]),Zv=useContextSnapshot(Wf&&Ru,ip?.configEndpoint,ip?.agentId,ip?.authToken),ag=reactExports.useMemo(()=>ip?.enableConfigQuery?void 0:{totalTokens:p0?.totalTokens??0,contextWindow:2e5,sumResponseInputTokens:p0?.sessionInput??0,sumResponseOutputTokens:p0?.sessionOutput??0,systemPromptTokens:0,userMessageTokens:0,assistantMessageTokens:0,toolTokens:0,toolCallTokens:0,toolReturnTokens:0,historyToolCallTokens:0,historyToolReturnTokens:0,currentToolCallTokens:0,currentToolReturnTokens:0,turnUsage:{inputTokens:p0?.turnInput??0,outputTokens:p0?.turnOutput??0,requests:0,toolCalls:0,toolNames:[],durationSeconds:0},sessionUsage:{inputTokens:p0?.sessionInput??0,outputTokens:p0?.sessionOutput??0,requests:0,toolCalls:0,turns:0,durationSeconds:0}},[p0,ip?.enableConfigQuery]),cv=reactExports.useRef($h),uv=reactExports.useRef(null),Rg=Zv.data,Yv=reactExports.useRef(Rg);Yv.current=Rg,reactExports.useEffect(()=>{cv.current!==$h&&(cv.current=$h,om(null),uv.current=Yv.current??null)},[$h]);const Xb=Rg&&Rg!==uv.current?Rg:void 0,$1=Of??Xb??ag;reactExports.useEffect(()=>{Hd?.($1)},[$1,Hd]);const dv=useSandbox(Wf&&$u&&!ip?.ownRoutesOnly,ip?.configEndpoint,ip?.authToken,ip?.agentId),km=reactExports.useRef(null),R1=reactExports.useRef(null),Pp=reactExports.useRef(new Map),xm=reactExports.useRef(0),Kf=reactExports.useRef(null),lg=reactExports.useRef(new Set),Ig=reactExports.useRef(new Set),l1=reactExports.useRef(new Set),v0=reactExports.useRef(!1),c1=reactExports.useRef(hp);c1.current=hp;const Mm=reactExports.useRef(fp?.id||generateMessageId()),hv=reactExports.useRef(fp),u1=reactExports.useRef(fp?.messages.length?fp.id:null),cg=reactExports.useCallback(()=>{const jd=Mm.current;u1.current!==jd&&(u1.current=jd,hv.current?.onStarted?.(jd))},[]),d1=reactExports.useRef(null),am=reactExports.useRef([]),h1=reactExports.useRef(new Set),Km=reactExports.useRef([]),I1=ip?.uiSocket,Pg=reactExports.useRef(ip?.authToken);Pg.current=ip?.authToken;const k0=ip?.uiFiles,p1=reactExports.useCallback(jd=>k0?uploadFile(jd,{url:k0,scope:Mm.current,token:Pg.current}):Promise.reject(new Error("This conversation takes no file.")),[k0]),Og=reactExports.useCallback(jd=>{const Zd=Yd=>{try{return withUiOp(Yd,jd)}catch(dh){return console.error("[ChatBase] reactor.ui op not applied:",dh),Yd}};if(Rp(Yd=>Zd(Yd)),Bd){const Yd=useChatStore.getState();Yd.setMessages(Zd(Yd.messages))}},[Bd]),P1=reactExports.useCallback((jd,Zd)=>{if(Zd){if(jd.op==="window")return;if((jd.op==="show"||jd.op==="ask")&&isStepDisplay(jd.body)){h1.current.add(jd.body.id);return}if((jd.op==="patch"||jd.op==="append")&&h1.current.has(jd.id))return}let Yd;try{Yd=routeUiOp(jd,f0.current,s1.current)}catch(sh){console.error("[ChatBase] reactor.ui op not applied:",sh);return}f0.current=Yd.steps;const dh=Yd.routed;if(dh.to==="window")tellLoopWindow(dh.data);else if(dh.to==="step"){const sh=dh.step;Rp(gh=>withLoopStep(gh,sh))}else if(dh.to==="element")s1.current.add(dh.change.id),applyLoopElement(dh.change);else if(placeable(Km.current,dh.op))Og(dh.op);else{const sh=dh.op.op==="show"||dh.op.op==="ask"?dh.op.body.data?.message_id:void 0;if(Zd&&typeof sh=="string"){const gh={id:sh,role:"assistant",content:"",createdAt:new Date};Km.current=[...Km.current,gh],Rp(Th=>Th.some(Kh=>Kh.id===sh)?Th:[...Th,gh]),Bd&&useChatStore.getState().addMessage(gh),Og(dh.op)}else am.current.push(dh.op)}},[Og,Bd]),pv=reactExports.useRef(P1);pv.current=P1,reactExports.useEffect(()=>{if(Km.current=wf,am.current.length===0)return;const jd=am.current.splice(0);let Zd=wf;for(const Yd of jd){if(!placeable(Zd,Yd)){am.current.push(Yd);continue}try{Zd=withUiOp(Zd,Yd)}catch{}Og(Yd)}},[wf,Og]);const Dm=reactExports.useCallback(()=>{if(!I1)return null;const jd=Mm.current,Zd=d1.current;if(Zd&&Zd.scope===jd)return Zd.socket;Zd?.socket.close(),f0.current=emptyUiModel(),s1.current=new Set,am.current=[],h1.current=new Set;const Yd=new UiSocket({url:I1,scope:jd,token:()=>Pg.current??"",onOp:(dh,sh,gh)=>pv.current(dh,gh),onStatus:(dh,sh)=>{(dh==="refused"||dh==="gone")&&console.error(`[ChatBase] ui socket ${dh}: ${sh??""}`)}});return d1.current={socket:Yd,scope:jd},Yd.connect(),Yd},[I1]),z0=reactExports.useRef(Dm);z0.current=Dm,reactExports.useEffect(()=>(fp?.messages.length&&z0.current(),()=>{d1.current?.socket.close(),d1.current=null}),[]);const U0=reactExports.useRef(null),f1=reactExports.useRef(null),Zm=reactExports.useRef(null),Sm=reactExports.useRef(null),mm=reactExports.useRef(!1),A0=reactExports.useRef(qf);A0.current=qf;const Nm=reactExports.useRef(Pf);Nm.current=Pf;const o0=reactExports.useRef(Vp);o0.current=Vp;const b0=reactExports.useRef($f);b0.current=$f;const Jv=useAgentInspectorTracer(),ug=cm??Jv,O1=reactExports.useRef("Agent");O1.current=typeof Au=="string"&&Au||$h||"Agent";const i0=reactExports.useRef(null);ug&&i0.current?.tracer!==ug?i0.current={tracer:ug,recorder:chatSpanRecorder(ug,()=>O1.current,{frontendTools:()=>(Nm.current??[]).map(jd=>jd.name)})}:ug||(i0.current=null);const Bf=reactExports.useRef(""),nf=reactExports.useRef(null);reactExports.useEffect(()=>{let jd=agentRuntimeStore.getState().toolDecisionRequest?.seq??0;return agentRuntimeStore.subscribe(Zd=>Zd.toolDecisionRequest,Zd=>{if(!Zd||Zd.seq===jd)return;jd=Zd.seq;const Yd=nf.current;if(!Yd)return;const dh=Th=>(Th??"").toLowerCase().replace(/[-_]/g,""),sh=Array.from(Pp.current.values()),gh=sh.find(Th=>Th.result?.approvalId===Zd.approvalId)??sh.find(Th=>dh(Th.toolName)===dh(Zd.toolName)&&(Th.status==="executing"||Th.status==="inProgress"));gh&&Yd(gh.toolCallId,{type:"tool-approval-decision",approved:Zd.approved,approvalId:Zd.approvalId,toolName:gh.toolName})})},[]);const Ap=reactExports.useCallback((jd,Zd,Yd)=>{if(!jd?.id||lg.current.has(jd.id))return!1;let dh=jd.tool_call_id;if(!dh)for(const[gh,Th]of Pp.current.entries()){if(Th.status!=="inProgress"&&Th.status!=="executing")continue;const Kh=approvalSignature(Th.toolName,Th.args??{}),cp=approvalSignature(jd.tool_name,jd.tool_args??{});if(Kh===cp){dh=gh;break}}if(!dh)return!1;const sh=Pp.current.get(dh);return!sh||sh.status!=="inProgress"&&sh.status!=="executing"?!1:(lg.current.add(jd.id),nf.current?.(dh,{type:"tool-approval-decision",approved:Zd,approvalId:jd.id,toolName:jd.tool_name||sh.toolName,_fromServerEcho:!0,_alreadyDispatched:!0,...Yd?{message:Yd}:{}}),!0)},[$h]);t1.current=Ap;const H0=!!(ip?.endpoint&&/\/api\/runtimes\/v1\/agent-nodes\/[^/]+\/ag-ui\/?$/.test(ip.endpoint)),Lm=ip?.configEndpoint?ip.configEndpoint.replace(/\/api\/v1\/(config|configure)\/?$/,""):ip?.endpoint?.replace(/\/api\/v1\/.*$/,"")??"";useAgentRuntimeWebSocket({enabled:!!ip&&!!Lm&&!H0&&!ip.ownRoutesOnly,baseUrl:Lm,authToken:ip?.authToken,agentId:ip?.agentId,onMessage:jd=>{if(jd.type!=="tool_approval_created"&&jd.type!=="tool_approval_approved"&&jd.type!=="tool_approval_rejected")return;const Zd=jd.payload;if(Zd){if(jd.type==="tool_approval_created"){isApprovalForAgent(Zd,$h)&&agentRuntimeStore.getState().upsertApproval(Zd);return}r1(Zd),Ap(Zd,jd.type==="tool_approval_approved",Zd.note??void 0)}}});const q0=reactExports.useCallback(jd=>{if(!pd)return!0;const Zd=jd.isConfig===!1?"catalog":"config";return pd.some(Yd=>Yd.id===jd.id&&Yd.origin===Zd)},[pd]);reactExports.useEffect(()=>{if(Oh&&Zm.current){const jd=setTimeout(()=>Zm.current?.focus(),100);return()=>clearTimeout(jd)}},[Oh]),reactExports.useEffect(()=>{if(bp!==void 0&&bp>0&&Zm.current){const jd=setTimeout(()=>Zm.current?.focus(),150);return()=>clearTimeout(jd)}},[bp]);const $0=reactExports.useRef(!1);reactExports.useEffect(()=>{if($0.current&&!im&&Zm.current){const jd=setTimeout(()=>Zm.current?.focus(),50);return()=>clearTimeout(jd)}$0.current=im},[im]);const m1=reactExports.useCallback(()=>{const jd=Zm.current;if(jd){jd.style.height="auto";const Zd=120,dh=Math.min(Math.max(jd.scrollHeight,40),Zd);jd.style.height=`${dh}px`,jd.style.overflowY=jd.scrollHeight>Zd?"auto":"hidden"}},[]);reactExports.useEffect(()=>{m1()},[sm,m1]),reactExports.useEffect(()=>{const jd=setTimeout(m1,0);return()=>clearTimeout(jd)},[m1]),reactExports.useEffect(()=>{if(Wm.length===0||isOffered(Wm,pf))return;const jd=initialModelId(Wm,sd||Cp.data?.defaultModel||DEFAULT_MODEL);jd&&jd!==pf&&_m(jd)},[Wm,pf,sd,Cp.data?.defaultModel]);const fv=reactExports.useRef(!1);reactExports.useEffect(()=>{if(Wm.length>0&&!fv.current){fv.current=!0;const jd=Cp.data?.builtinTools?.map(Zd=>Zd.id)||[];if(T1(jd),Cp.data?.mcpServers){const Zd=new Map;for(const Yd of Cp.data.mcpServers)if(Yd.isAvailable&&Yd.enabled&&q0(Yd)){const sh=new Set(Yd.tools.map(gh=>gh.name).filter(gh=>!!gh));Zd.set(Yd.id,sh)}Om(Zd)}}},[Cp.data,Wm,pf,sd,ad,pd,q0]),reactExports.useEffect(()=>{!Cp.data?.mcpServers||!pd||Om(jd=>{const Zd=new Map;for(const Yd of Cp.data?.mcpServers??[])if(q0(Yd)&&jd.has(Yd.id)){const dh=jd.get(Yd.id);dh&&Zd.set(Yd.id,dh)}else if(q0(Yd)&&Yd.isAvailable&&Yd.enabled){const dh=new Set(Yd.tools.map(sh=>sh.name).filter(sh=>!!sh));Zd.set(Yd.id,dh)}return Zd})},[pd,Cp.data?.mcpServers,q0]);const Ym=reactExports.useRef(pd);Ym.current=pd,reactExports.useEffect(()=>{const jd=parseEnabledMcpToolsByServer(Mh);if(!jd)return;const Zd=$h||"__global__",Yd=!l1.current.has(Zd)&&Vm==="connected";Om(dh=>{const sh=new Map(dh);if(jd.forEach((gh,Th)=>{(!Ym.current||Ym.current.some(cp=>cp.id===Th))&&gh.size!==0&&sh.set(Th,new Set(gh))}),Yd){const gh=[];for(const Kh of Cp.data?.mcpServers??[]){if(!(!Ym.current||Ym.current.some(Yh=>Yh.id===Kh.id))||!Kh.isAvailable||!Kh.enabled)continue;const Gh=Kh.tools.map(Yh=>Yh.name).filter(Yh=>!!Yh);if(Gh.length===0)continue;const qh=sh.get(Kh.id);(!qh||qh.size===0)&&(sh.set(Kh.id,new Set(Gh)),gh.push({serverId:Kh.id,enabledToolNames:Gh}))}let Th=!0;for(const Kh of gh)agentRuntimeStore.getState().sendRawMessage({type:"mcp_server_tools_set",serverId:Kh.serverId,enabledToolNames:Kh.enabledToolNames},$h)||(Th=!1,console.warn("[ChatBase] initial mcp_server_tools_set dropped: websocket not ready"));Th&&l1.current.add(Zd)}return sh})},[Mh,$h,Cp.data?.mcpServers,Vm]),reactExports.useEffect(()=>{const jd=parseApprovedMcpToolsByServer(Mh);jd&&fm(()=>{const Zd=new Map;return jd.forEach((Yd,dh)=>{(!Ym.current||Ym.current.some(gh=>gh.id===dh))&&Zd.set(dh,new Set(Yd))}),Zd})},[Mh]);const V0=reactExports.useRef("");reactExports.useEffect(()=>{const jd=Mh?.servers;if(!jd||jd.length===0)return;const Zd=jd.filter(gh=>gh.status==="started").map(gh=>gh.id).sort();if(Zd.length===0)return;const Yd=Cp.data?.mcpServers||[],dh=Zd.some(gh=>{const Th=Yd.find(Kh=>Kh.id===gh);return!Th||Th.tools.length===0}),sh=Zd.join(",");dh&&sh!==V0.current&&Cp.refetch&&(V0.current=sh,Cp.refetch())},[Mh,Cp]);const mv=reactExports.useCallback((jd,Zd)=>{Om(Yd=>{const dh=new Map(Yd),sh=new Set(Yd.get(jd)||[]);return sh.has(Zd)?sh.delete(Zd):sh.add(Zd),dh.set(jd,sh),agentRuntimeStore.getState().sendRawMessage({type:"mcp_server_tools_set",serverId:jd,enabledToolNames:Array.from(sh)},$h)||console.warn("[ChatBase] mcp_server_tools_set dropped: websocket not ready"),dh})},[$h]),g1=reactExports.useCallback((jd,Zd,Yd)=>{Om(dh=>{const sh=new Map(dh),gh=Yd?new Set(Zd):new Set;return sh.set(jd,gh),agentRuntimeStore.getState().sendRawMessage({type:"mcp_server_tools_set",serverId:jd,enabledToolNames:Array.from(gh)},$h)||console.warn("[ChatBase] mcp_server_tools_set dropped: websocket not ready"),sh})},[$h]),gv=reactExports.useCallback(jd=>{ig.has(jd)?F0(jd):C0(jd)},[ig,C0,F0]),dg=reactExports.useCallback((jd,Zd)=>{for(const Yd of jd)Zd?C0(Yd):F0(Yd)},[C0,F0]),R0=reactExports.useCallback((jd,Zd)=>{fm(Yd=>{const dh=new Map(Yd),sh=new Set(Yd.get(jd)??[]),gh=sh.has(Zd);return gh?sh.delete(Zd):sh.add(Zd),dh.set(jd,sh),agentRuntimeStore.getState().sendRawMessage({type:"mcp_server_tool_approve",serverId:jd,toolName:Zd,approved:!gh},$h)||console.warn("[ChatBase] mcp_server_tool_approve dropped: websocket not ready"),dh})},[$h]),G0=reactExports.useCallback(jd=>{sg.has(jd)?(T0(Zd=>{const Yd=new Map(Zd);return Yd.set(jd,!1),Yd}),k1(jd)):(T0(Zd=>{const Yd=new Map(Zd);return Yd.set(jd,!0),Yd}),av(jd))},[sg,av,k1]),s0=reactExports.useCallback(()=>{const jd=[];return Jp.forEach((Zd,Yd)=>{(!pd||pd.some(dh=>dh.id===Yd))&&Zd.forEach(dh=>jd.push(dh))}),jd},[Jp,pd]),M1=reactExports.useCallback(()=>Array.from(ig),[ig]);reactExports.useEffect(()=>{if(Bd&&!Qp){const jd=useChatStore.getState().messages;jd.length>0&&Rp(jd)}},[Bd,Qp]);const D1=reactExports.useRef(void 0),hg=reactExports.useRef(0),Mg=reactExports.useRef(!1),W0=reactExports.useRef(null);reactExports.useEffect(()=>{if(ep!==D1.current&&(ep&&n0.current.set(ep,0),D1.current=ep,Rp([]),Pp.current.clear(),!ep)||!ep)return;const jd=hv.current;if(jd){W0.current!==jd.id&&(W0.current=jd.id,useConversationStore.getState().setMessages(ep,jd.messages),Rp(convertHistoryToDisplayItems(jd.messages)),useConversationStore.getState().markFetched(ep),_f(!0));return}Ud!==hg.current&&(hg.current=Ud,Ud>0&&(useConversationStore.getState().clearMessages(ep),Rp([]),Pp.current.clear(),n0.current.set(ep,0),Mg.current=!0));const Zd=useConversationStore.getState(),Yd=Zd.isFetching(ep),dh=Zd.getMessages(ep);if(dh.length>0&&(Rp(dp=>dp.length>0?dp:dh),_f(!0)),Yd)return;if(Vm!=="connected"){dh.length===0&&_f(!1);return}Zd.setFetching(ep,!0);const sh=()=>extractChatMessagesFromFullContext(agentRuntimeStore.getState().fullContext),gh=dp=>{Zd.setMessages(ep,dp),Rp(convertHistoryToDisplayItems(dp)),n0.current.set(ep,0),Zd.markFetched(ep),_f(!0)},Th=Mg.current?[]:sh();if(Mg.current=!1,Th.length>0){gh(Th);return}const Kh=()=>{const dp=[$h,Nh?.agentId,Qp,ep,"default",void 0],Dp=new Set;for(const xf of dp){const fg=typeof xf=="string"?xf.trim():void 0,jg=fg||"__global__";if(Dp.has(jg))continue;if(Dp.add(jg),agentRuntimeStore.getState().requestRefresh(fg))return!0}return!1};if(!Kh()){Zd.setFetching(ep,!1),dh.length===0&&_f(!1);return}let Gh=!1;const qh=window.setTimeout(()=>{Gh||Kh()},500),Yh=agentRuntimeStore.subscribe(dp=>dp.fullContext,dp=>{if(Gh||!dp)return;const Dp=extractChatMessagesFromFullContext(dp);Gh=!0,Yh(),gh(Dp)}),gp=window.setTimeout(()=>{if(Gh)return;Gh=!0,Yh(),Zd.setFetching(ep,!1),_f(dh.length>0);const dp=n0.current.get(ep)??0;Vm==="connected"&&dp<3?(n0.current.set(ep,dp+1),Kh(),S0(xf=>xf+1)):_f(!0)},2e3);return()=>{window.clearTimeout(qh),window.clearTimeout(gp),Yh()}},[ep,jp,ip?.agentId,Vm,$h,qm,Ud]),reactExports.useEffect(()=>{if(ep&&wf.length>0){const jd=wf.filter(Zd=>!isToolCallMessage(Zd));jd.length>0&&useConversationStore.getState().setMessages(ep,jd)}},[ep,wf]);const jf=wf.filter(jd=>!isToolCallMessage(jd)),v1=reactExports.useRef(0);reactExports.useEffect(()=>{const jd=jf.length;jd!==v1.current&&(v1.current=jd,Fh?.(jf))},[wf,jf,Fh]),reactExports.useEffect(()=>{Uh?.(wf.filter(jd=>!isToolCallMessage(jd)))},[wf,Uh]),reactExports.useEffect(()=>{Jh?.(wf)},[wf,Jh]);const b1=Fd?2:3,Qb=reactExports.useMemo(()=>{if(ip?.configEndpoint)return{apiBaseUrl:getApiBaseFromConfig(ip.configEndpoint),authToken:ip.authToken}},[ip?.configEndpoint,ip?.authToken]),ey={userAvatar:jsxRuntimeExports.jsx(PersonIcon,{size:16}),assistantAvatar:jsxRuntimeExports.jsx(ForwardRef$2,{size:16,color:Vf}),showAvatars:!0,avatarSize:32,userAvatarBg:"neutral.muted",assistantAvatarBg:"accent.emphasis",...vh};reactExports.useEffect(()=>{if(!ip||!td||uf)return;const jd=createProtocolAdapter(ip);if(jd)return km.current=jd,a1(!0),R1.current=jd.subscribe(Zd=>{if(z0.current(),!(mm.current&&Zd.type!=="state-update"&&Zd.type!=="error"&&Zd.type!=="done"))switch(Zd.type){case"message":if(Zd.usage){const Yd=Zd.timestamp instanceof Date?Zd.timestamp.getTime():Date.now(),dh=Math.max(0,Zd.usage.promptTokens??0),sh=Math.max(0,Zd.usage.completionTokens??0),gh=Math.max(dh+sh,Zd.usage.totalTokens??0),Th=agentRuntimeStore.getState();Th.appendLocalTokenTurn({serviceName:Ag,agentId:ip?.agentId,timestampMs:Yd,promptTokens:dh,completionTokens:sh,totalTokens:gh});const Kh=Th.costUsage?.cumulativeCostUsd;typeof Kh=="number"&&Number.isFinite(Kh)&&Th.upsertLocalCostPoint({serviceName:Ag,agentId:ip?.agentId,timestampMs:Yd,cumulativeUsd:Math.max(0,Kh)})}if(v0.current){const Yd=Kf.current?.id;Yd&&(Rp(dh=>dh.filter(sh=>isToolCallMessage(sh)||sh.id!==Yd)),Bd&&useChatStore.getState().deleteMessage(Yd),Kf.current=null);break}if(Zd.message){const Yd=Zd.message.id,dh=Kf.current?.id;if(dh&&!(!dh||Yd&&Yd!==dh)){const gh=Zd.message.content,Th=typeof gh=="string"?sanitizeAssistantContent(gh):gh??"";typeof Th=="string"&&Th&&(Bf.current=Th),Rp(Kh=>{const cp=[...Kh],Gh=cp.findIndex(qh=>!isToolCallMessage(qh)&&qh.id===dh);return Gh>=0&&!isToolCallMessage(cp[Gh])&&(cp[Gh]={...cp[Gh],content:Th}),cp}),Bd&&useChatStore.getState().updateMessage(dh,{content:Th})}else{const gh=Zd.message.content,Th=typeof gh=="string"?gh:gh??"",Kh=typeof Th=="string"?sanitizeAssistantContent(Th):"",cp=createAssistantMessage(Kh);cp.id=Zd.message.id||cp.id,Kf.current=cp,Rp(Gh=>{const qh=Gh.findIndex(Yh=>!isToolCallMessage(Yh)&&Yh.id===cp.id);if(qh>=0){const Yh=[...Gh];return Yh[qh]={...Yh[qh],content:Kh},Yh}return[...Gh,cp]}),Bd&&(useChatStore.getState().messages.find(qh=>qh.id===cp.id)?useChatStore.getState().updateMessage(cp.id,{content:Kh}):useChatStore.getState().addMessage(cp))}}break;case"tool-call":if(Zd.toolCall&&!mm.current){const Yd=Zd.toolCall.toolCallId||generateMessageId(),dh=Zd.toolCall.toolName,sh=Zd.toolCall.args||{},gh=Zd.toolCall.argsComplete;if(Pp.current.has(Yd)){const Th=Pp.current.get(Yd);if(Th){const Kh={...Th,args:{...Th.args,...sh}};Pp.current.set(Yd,Kh),Rp(qh=>qh.map(Yh=>isToolCallMessage(Yh)&&Yh.toolCallId===Yd?Kh:Yh));const Gh=Nm.current?.find(qh=>qh.name===dh)?.handler;Gh&&Th.status==="executing"&&(gh??Object.keys(sh).length>0)&&(xm.current++,Xv(Gh,Kh,Yd))}}else{const Th={id:`tool-${Yd}`,type:"tool-call",toolCallId:Yd,toolName:dh,args:sh,status:"executing"};Pp.current.set(Yd,Th),Rp(Gh=>[...Gh,Th]),o0.current?.({toolName:dh,toolCallId:Yd,args:sh}),i0.current?.recorder.toolStarted({id:Yd,name:dh,args:sh});const Kh=Nm.current?.find(Gh=>Gh.name===dh),cp=Kh?.handler;cp&&(gh??(Object.keys(sh).length>0||!frontendToolExpectsArgs(Kh)))&&(xm.current++,Xv(cp,Th,Yd))}}break;case"tool-result":if(Zd.toolResult){const Yd=Zd.toolResult.toolCallId;if(Yd&&Pp.current.has(Yd)){const dh=Pp.current.get(Yd);if(dh){const sh=dh.args&&"steps"in dh.args&&Array.isArray(dh.args.steps),gh=Zd.toolResult.result;let Th,Kh,cp,Gh=!1,qh=!!Zd.toolResult.error;if(gh&&typeof gh=="object"){if("pending_approval"in gh&&gh.pending_approval===!0&&(Gh=!0),gh.execution_error&&typeof gh.execution_error=="string"&&(Th=gh.execution_error,qh=!0),gh.code_error&&typeof gh.code_error=="object"){const gp=gh.code_error;Kh={name:gp.name||"Error",value:gp.value||"Unknown error",traceback:gp.traceback},qh=!0}if("exit_code"in gh){const gp=gh.exit_code;cp=typeof gp=="number"?gp:null,cp!=null&&cp!==0&&(qh=!0)}"execution_ok"in gh&&gh.execution_ok===!1&&(qh=!0)}const Yh={...dh,result:Zd.toolResult.result,status:qh?"error":Gh?"inProgress":sh?"executing":"complete",error:Zd.toolResult.error,executionError:Th,codeError:Kh,exitCode:cp};Pp.current.set(Yd,Yh),Rp(gp=>gp.map(dp=>isToolCallMessage(dp)&&dp.toolCallId===Yd?Yh:dp)),i0.current?.recorder.toolEnded(Yd,{result:Zd.toolResult.result,error:Zd.toolResult.error??(Yh.status==="error"?Th??"failed":void 0)}),b0.current?.({toolName:dh.toolName,toolCallId:Yd,args:dh.args,result:Zd.toolResult.result,status:Yh.status,error:Zd.toolResult.error})}}}break;case"state-update":if(Eh?.(Zd.data),Zd.data){const Yd=Array.from(Pp.current.entries()).filter(([dh,sh])=>sh.status==="executing");if(Yd.length>0){const[dh,sh]=Yd[Yd.length-1];if(!(sh.args&&"steps"in sh.args&&Array.isArray(sh.args.steps))){const Th=Zd.data,Kh=Th.weather??Th.result??Th.toolResult??Th,cp={...sh,result:Kh,status:"complete"};Pp.current.set(dh,cp),Rp(Gh=>Gh.map(qh=>isToolCallMessage(qh)&&qh.toolCallId===dh?cp:qh))}}}break;case"activity":break;case"done":{i0.current?.recorder.turnEnded({text:Bf.current||void 0,usage:Zd.usage}),Bf.current="";const Yd=Zd.usage?.promptTokens??0,dh=Zd.usage?.completionTokens??0,sh=Zd.usage?.totalTokens??Yd+dh;sh>0&&om(gh=>({turnInput:Yd,turnOutput:dh,sessionInput:(gh?.sessionInput??0)+Yd,sessionOutput:(gh?.sessionOutput??0)+dh,totalTokens:sh}))}v0.current&&c1.current&&Rp(Yd=>{if(Yd.some(Th=>!isToolCallMessage(Th)&&Th.role==="assistant"&&String(Th.content||"").trim().length>0))return Yd;const sh=[...Yd].reverse().find(Th=>isToolCallMessage(Th)&&Th.status==="complete"&&Th.result!==void 0);if(!sh||!isToolCallMessage(sh))return Yd;const gh=createAssistantMessage(formatToolResultFallback(sh.result));return Bd&&useChatStore.getState().addMessage(gh),[...Yd,gh]}),v0.current=!1,xm.current=0,Im(!1),Hm(!1),agentRuntimeStore.getState().requestRefresh($h);break;case"error":console.error("[ChatBase] Protocol error:",Zd.error),i0.current?.recorder.turnEnded({error:Zd.error?.message??"error"}),Zd.error?.message&&/exceeded maximum retries/i.test(Zd.error.message)&&c1.current&&Rp(Yd=>{if(Yd.some(Th=>!isToolCallMessage(Th)&&Th.role==="assistant"&&String(Th.content||"").trim().length>0))return Yd;const sh=[...Yd].reverse().find(Th=>isToolCallMessage(Th)&&Th.status==="complete"&&Th.result!==void 0);if(!sh||!isToolCallMessage(sh))return Yd;const gh=createAssistantMessage(formatToolResultFallback(sh.result));return Bd&&useChatStore.getState().addMessage(gh),[...Yd,gh]}),v0.current=!1,Pm(Zd.error||new Error("Unknown error")),xm.current=0,Im(!1),Hm(!1),agentRuntimeStore.getState().requestRefresh($h);break}}),jd.connect().catch(console.error),()=>{R1.current?.(),km.current?.disconnect()}},[C1,Eh,Bd,td]);function Xv(jd,Zd,Yd){(async()=>{if(mm.current){xm.current--,xm.current<0&&(xm.current=0);return}try{const dh=await jd(Zd.args);km.current&&await km.current.sendToolResult(Yd,{toolCallId:Yd,success:!0,result:dh});const sh={...Zd,result:dh,status:"complete"};i0.current?.recorder.toolEnded(Yd,{result:dh}),Pp.current.set(Yd,sh),Rp(gh=>gh.map(Th=>isToolCallMessage(Th)&&Th.toolCallId===Yd?sh:Th))}catch(dh){console.error("[ChatBase] Frontend tool execution error:",dh);const sh={...Zd,status:"error",error:dh.message};i0.current?.recorder.toolEnded(Yd,{error:dh.message}),Pp.current.set(Yd,sh),Rp(gh=>gh.map(Th=>isToolCallMessage(Th)&&Th.toolCallId===Yd?sh:Th))}finally{xm.current--,xm.current<0&&(xm.current=0)}})()}reactExports.useEffect(()=>{const jd=U0.current;if(jd){jd.scrollTo({top:jd.scrollHeight,behavior:"smooth"});return}f1.current?.scrollIntoView({behavior:"smooth"})},[wf]);const kf=reactExports.useRef(void 0),[N1]=useVoiceSettings(),I0=reactExports.useMemo(()=>Pd?settledVoice(Pd,N1):void 0,[Pd,N1]),[y1,vv]=reactExports.useState(!1),K0=!!(Kd||Nd),Bm=useVoiceSpeaker(I0,!K0);useSpokenAnswers(wf,im,!K0&&I0?.output==="always",Bm.speaker);const bv=Wd||Bm.state.speaking,L1=Nd??(Bm.speaker?Bm.stop:void 0),Qv=Kd??(Bm.speaker?Bm.read:void 0),a0=reactExports.useCallback(async(jd,Zd,Yd)=>{const dh=(jd??sm).trim();if(!dh||im||!km.current&&!Ad)return;if(Zd&&namesFiles(Zd))try{Zd=await withUploadedFiles(Zd,p1)}catch(qh){Pm(qh instanceof Error?qh:new Error(String(qh)));return}const sh=displayPressOf(Zd);if(sh&&Zd){const qh=d1.current?.socket;if(!qh){Pm(new Error("This conversation’s ui channel is not open."));return}try{const Yh=await qh.act(sh);if(!Yh.ok){Pm(new Error(Yh.detail||`The press was refused (${Yh.status}).`));return}Zd=withPress(Zd,Yh.value)}catch(Yh){Pm(Yh instanceof Error?Yh:new Error(String(Yh)));return}}mm.current=!1,Bf.current="",i0.current?.recorder.turnStarted(dh,pf||void 0),v0.current=isToolCallOnlyPrompt(dh);const gh=Yd??spokenOf(Zd?.voice)??(jd===void 0?kf.current:void 0);kf.current=void 0;const Th=gh?{...Zd??{},voice:gh}:Zd,Kh=createUserMessage(dh,gh?{...gh}:void 0),Gh=[...wf.filter(qh=>!isToolCallMessage(qh)),Kh];Rp(qh=>[...qh,Kh]),og(""),Im(!0),Hm(!0),Pm(null),Kf.current=null,Bd&&useChatStore.getState().addMessage(Kh);try{if(Ad)if(nh){const qh=generateMessageId(),Yh=createAssistantMessage("");Yh.id=qh,Rp(gp=>[...gp,Yh]),Kf.current=Yh,Bd&&(useChatStore.getState().addMessage(Yh),useChatStore.getState().startStreaming(qh)),Sm.current=new AbortController,await Ad(dh,Gh,{onChunk:gp=>{Rp(dp=>dp.map(Dp=>Dp.id===qh?{...Dp,content:Dp.content+gp}:Dp)),Bd&&useChatStore.getState().appendToStream(qh,gp)},onComplete:gp=>{Rp(dp=>dp.map(Dp=>Dp.id===qh?{...Dp,content:gp}:Dp)),Bd&&(useChatStore.getState().updateMessage(qh,{content:gp}),useChatStore.getState().stopStreaming())},onError:gp=>{const dp=Mf.error(gp.message);Rp(Dp=>Dp.map(xf=>xf.id===qh?{...xf,content:dp}:xf)),Bd&&(useChatStore.getState().updateMessage(qh,{content:dp}),useChatStore.getState().stopStreaming()),Pm(gp)},signal:Sm.current.signal})}else{const qh=await Ad(dh,Gh);if(qh){const Yh=createAssistantMessage(qh);Rp(gp=>[...gp,Yh]),Bd&&useChatStore.getState().addMessage(Yh)}}else if(km.current){const qh=(Pf||[]).map(dp=>({name:dp.name,description:dp.description,parameters:dp.parameters||{type:"object",properties:{}}}));console.warn("[ChatBase] frontendTools count:",Pf?.length??0,"toolsForRequest:",qh.map(dp=>dp.name));const Yh=s0(),gp=M1();cg(),await km.current.sendMessage(Kh,{threadId:Mm.current,messages:Gh,...pf&&{model:pf},tools:qh,builtinTools:Yh,skills:gp,identities:A0.current,...Th?{forwardedProps:Th}:{}})}}catch(qh){if(qh.name!=="AbortError"){console.error("[ChatBase] Send error:",qh);const Yh=createAssistantMessage(Mf.error(qh.message));Rp(gp=>[...gp,Yh]),Pm(qh)}}finally{km.current||(Im(!1),Hm(!1),agentRuntimeStore.getState().requestRefresh($h)),v0.current=!1,Kf.current=null,Sm.current=null}},[sm,im,wf,pf,Pf,Bd,Ad,$h,nh,s0,M1,cg,Mf,p1]);reactExports.useEffect(()=>{if(!Bp||wp&&Bh.current===wp)return;if(wp&&sentPendingPromptKeys.has(wp)){Bh.current=wp;return}!i1&&!(!ep||Vm!=="connected")||!m0&&!Ad||(Bh.current=wp??null,wp&&sentPendingPromptKeys.add(wp),queueMicrotask(()=>a0(Bp)))},[Bp,wp,i1,ep,Vm,m0,a0,Ad,Ap]);const P0=reactExports.useCallback(()=>{mm.current=!0,Sm.current?.abort();const jd=km.current;jd&&(typeof jd.stopGeneration=="function"&&jd.stopGeneration(),typeof jd.terminateSession=="function"?jd.terminateSession().catch(()=>{}):typeof jd.terminateAgent=="function"?jd.terminateAgent().catch(()=>{}):typeof jd.terminateTask=="function"?jd.terminateTask().catch(()=>{}):typeof jd.terminateRequest=="function"&&jd.terminateRequest().catch(()=>{}));for(const[Zd,Yd]of Pp.current.entries())(Yd.status==="executing"||Yd.status==="inProgress")&&Pp.current.set(Zd,{...Yd,status:"error",error:"Interrupted by user"});Rp(Zd=>Zd.map(Yd=>!isToolCallMessage(Yd)||Yd.status!=="executing"&&Yd.status!=="inProgress"?Yd:{...Yd,status:"error",error:"Interrupted by user"})),Bd&&useChatStore.getState().stopStreaming(),xm.current=0,Im(!1),Hm(!1),agentRuntimeStore.getState().requestRefresh($h),agentRuntimeStore.getState().stopSubagentActivity(),v0.current=!1,Kf.current=null,dv.interrupt(),cd&&cd.interrupt().catch(()=>{})},[cd,Bd,$h,ip?.configEndpoint,ip?.authToken,ip?.agentId]),yv=reactExports.useCallback(jd=>async Zd=>{const Yd=jd.actions?.find(gh=>gh.name===Zd.action);if(!Yd)throw new Error(`“${Zd.action}” was not offered here.`);const dh=Zd.payload?.value,sh=Zd.action===ANSWER_ACTION?typeof dh=="string"?dh:isFileRef(dh)?dh.name:"Answered.":Zd.action;await a0(sh,{loop:{action:{name:Zd.action,display_id:jd.id,token:Yd.token,payload:Zd.payload??{}}}})},[a0]),Dg=reactExports.useCallback(()=>{Rp([]),Pp.current.clear(),xm.current=0,og(""),Mm.current=generateMessageId(),Bd&&ym(),ep&&useConversationStore.getState().clearMessages(ep),kh?.(),ih?.onNewChat?.()},[ym,kh,ih,Bd,Qp]);reactExports.useEffect(()=>{if($d){if(!m0&&!Ad){$d(null);return}return $d({send:(jd,Zd)=>{a0(jd,Zd)},stop:P0,newChat:Dg,thread:()=>Mm.current,stopSpeaking:L1}),()=>{$d(null)}}},[$d,m0,Ad,a0,P0,Dg,L1]),reactExports.useEffect(()=>{qd?.(im)},[qd,im]),reactExports.useEffect(()=>{Dd?.(bv)},[Dd,bv]);const eb=reactExports.useCallback(()=>{window.confirm("Clear all messages?")&&(Rp([]),Pp.current.clear(),Bd&&ym(),ep&&useConversationStore.getState().clearMessages(ep),Ph?.(),ih?.onClear?.())},[ym,Ph,ih,Bd,Qp]),Ng=reactExports.useCallback(jd=>{const Zd=new Set(jd);Rp(Yd=>Yd.filter(dh=>!Zd.has(dh.id)));for(const[Yd,dh]of Pp.current.entries())Zd.has(dh.id)&&Pp.current.delete(Yd)},[]),B1=reactExports.useCallback(async(jd,Zd)=>{const Yd=Pp.current.get(jd);if(Yd&&(Yd.status==="executing"||Yd.status==="inProgress")){if(!!Zd&&typeof Zd=="object"&&Zd.type==="tool-approval-decision"&&typeof Zd.approved=="boolean"&&km.current){const gh=Zd,Th=!!gh.approved,Kh=gh._fromServerEcho===!0,cp=gh._alreadyDispatched===!0,Gh=Yd.status==="inProgress",qh=typeof gh.toolName=="string"?gh.toolName:Yd.toolName,Yh=qh.includes("__");if(Th){const gp=qh.indexOf("__");if(gp!==-1){const dp=qh.slice(0,gp),Dp=qh.slice(gp+2);fm(xf=>{const fg=new Map(xf),jg=new Set(xf.get(dp)??[]);return jg.add(Dp),fg.set(dp,jg),fg})}}try{const gp=typeof Zd=="object"&&Zd!==null&&typeof Zd.approvalId=="string"?Zd.approvalId:void 0;if(!Kh&&!Gh){gp&&(Th?await eg?.(gp,void 0,jd):await h0?.(gp,void 0,jd));return}if(gp&&!cp&&(Th?await eg?.(gp,void 0,jd):await h0?.(gp,void 0,jd)),Yh&&!Gh)return;const dp={...Yd,result:Zd,status:Th?"complete":"error",error:Th?void 0:"Tool approval rejected by user"};Pp.current.set(jd,dp),Rp(Dp=>Dp.map(xf=>isToolCallMessage(xf)&&xf.toolCallId===jd?dp:xf)),Im(!0),Hm(!0),await km.current.sendToolResult(jd,{toolCallId:jd,success:Th,result:Th?{approved:!0,message:"Tool call approved by user.",...gp?{approvalId:gp}:{}}:{approved:!1,message:"Tool call rejected by user.",...gp?{approvalId:gp}:{}},...Th?{}:{error:"Tool approval rejected by user"}})}catch(gp){console.error("[ChatBase] Approval continuation error:",gp),Pm(gp)}return}const sh={...Yd,result:Zd,status:"complete"};if(Pp.current.set(jd,sh),Rp(gh=>gh.map(Th=>isToolCallMessage(Th)&&Th.toolCallId===jd?sh:Th)),km.current){let gh;if(typeof Zd=="string")gh=Zd;else if(Zd&&typeof Zd=="object"&&"accepted"in Zd){const Kh=Zd;if(Kh.accepted){const cp=Kh.steps?.map(Gh=>Gh.description).join(", ")||"";gh=cp?`I confirm and approve the following steps: ${cp}`:"I confirm and approve the plan."}else gh="I reject this plan. Please suggest something else."}else gh=JSON.stringify(Zd,null,2);const Th={id:generateMessageId(),role:"user",content:gh,createdAt:new Date};Im(!0),Hm(!0);try{const Kh=wf.filter(cp=>!isToolCallMessage(cp));await km.current.sendMessage(Th,{threadId:Mm.current,messages:[...Kh,Th]})}catch(Kh){console.error("[ChatBase] HITL respond error:",Kh)}}}},[wf,eg,h0]);nf.current=B1;const j1=reactExports.useCallback(jd=>{a0(jd.message)},[a0]),F1=reactExports.useCallback(jd=>{og(jd),setTimeout(()=>Zm.current?.focus(),0)},[]),tb=reactExports.useCallback(async(jd,Zd)=>{await eg?.(jd,Zd)},[eg]),rb=reactExports.useCallback(async(jd,Zd)=>{await h0?.(jd,Zd)},[h0]),O0=(Cp.data?.mcpServers||[]).filter(jd=>!pd||q0(jd)),Z0=reactExports.useMemo(()=>{const jd=O0.map(Yd=>{const dh=Mh?.servers?.find(sh=>sh.id===Yd.id);if(dh&&dh.status==="started"){const sh={};if(Yd.isAvailable||(sh.isAvailable=!0),dh.tools&&dh.tools.length>0&&(sh.tools=dh.tools.map(gh=>({name:gh.name,description:gh.description||"",enabled:gh.enabled??!0}))),Object.keys(sh).length>0)return{...Yd,...sh}}return Yd}),Zd=new Set(O0.map(Yd=>Yd.id));for(const Yd of Mh?.servers??[])Yd.status==="started"&&!Zd.has(Yd.id)&&Yd.tools&&Yd.tools.length>0&&(!pd||pd.some(sh=>sh.id===Yd.id))&&jd.push({id:Yd.id,name:Yd.id,description:"",url:"",enabled:!0,tools:Yd.tools.map(sh=>({name:sh.name,description:sh.description||"",enabled:sh.enabled??!0})),args:[],requiredEnvVars:[],isAvailable:!0,transport:"stdio",isConfig:!1,isRunning:!0});return jd},[O0,Mh,pd]),nb=ip?.configEndpoint?ip.configEndpoint.replace(/\/api\/v1\/(config|configure)\/?$/,""):void 0,ob=!ip||!ip.enableConfigQuery||!!Cp.data||!!Gm.data,Lg=wh||Cp.data?.welcomeMessage||"",pg=Cp.data?.suggestions,_1=np&&np.length>0?np:Array.isArray(pg)&&pg.length>0?pg.map(jd=>{if(typeof jd=="string"){const dh=jd.trim();return{title:dh,message:dh}}const Zd=(jd?.text??"").trim();return{title:(jd?.summary??"").trim()||Zd,message:Zd}}).filter(jd=>jd.message):void 0,Bg=zd?[{id:"__welcome__",role:"assistant",content:zd,createdAt:WELCOME_AT},...wf]:wf,z1=im||o1?[...Bg].reverse().find(jd=>!isToolCallMessage(jd)&&jd.role==="assistant")?.id:void 0,ib=Qv?jd=>{const Zd=getMessageText(jd);return readsAloud(jd,Zd,z1)?jsxRuntimeExports.jsx(ReadAloud,{onRead:()=>Qv(Zd)}):null}:void 0,Y0=Sh||jsxRuntimeExports.jsxs(Box,{display:"flex",flexDirection:"column",minHeight:0,width:"100%",maxWidth:920,mx:"auto",bg:"canvas.default",children:[jsxRuntimeExports.jsx(ChatMessageList,{displayItems:Bg,actOn:ip?.uiSocket?yv:void 0,upload:ip?.uiFiles?p1:void 0,isLoading:im,isStreaming:o1,showLoadingIndicator:Pu,hideMessagesAfterToolUI:hp,avatarConfig:ey,padding:b1,notebookToolSurfacesId:Dh,approvalConfig:Qb,messagesEndRef:f1,onRespond:B1,showTurnFooters:ah,renderMessageFooter:ib,agentUsage:$1,onRemoveItems:Ng,mcpServers:Z0,emptyContent:Xu?null:jsxRuntimeExports.jsx(ChatEmptyState,{emptyState:eh,brandIcon:Xd,description:Lg,suggestions:_1,submitOnSuggestionClick:ap,onSuggestionSubmit:j1,onSuggestionFill:F1})}),Id]}),_v=I0&&I0.input!=="off"?jsxRuntimeExports.jsx(ComposerVoice,{voice:I0,input:sm,setInput:og,disabled:uf||Xu,speaking:bv,onStopSpeaking:L1,onInterimChange:vv,answers:!!(Pd?.output&&Pd.output!=="off"&&Pd.speechUrl),onSpoken:jd=>{kf.current=jd},send:(jd,Zd)=>{a0(jd,void 0,Zd)}}):void 0,M0=!K0&&Bm.state.refused?jsxRuntimeExports.jsx(Text$3,{role:"alert",sx:{fontSize:0,color:"danger.fg",maxWidth:260},"data-voice-refused":"",children:Bm.state.refused}):null,U1=Mu?jsxRuntimeExports.jsx(InputPrompt,{footerExtras:M0?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[M0,_v]}):_v,interim:y1,input:sm,setInput:og,isLoading:im,kernelStatus:n1,connectionConfirmed:ob,placeholder:uh,typingSuggestions:_1?.map(jd=>jd.message||jd.title),autoFocus:Oh,focusTrigger:bp,padding:b1,onSend:()=>a0(),onStop:P0,disableInputPrompt:ju||uf||!!Yu||Xu,promptVariant:Fu,mentionableAgents:lv,promptCommands:Uu,promptHistory:Cp.data?.promptHistory?.map(askedOf),showTokenUsage:Ru,showContextRing:Iu,agentUsage:$1,showModelSelector:Du,showToolsMenu:Lu,showSkillsMenu:Bu,codemodeEnabled:nd,onToggleCodemode:od,isA2AProtocol:j0,showAgentsMenu:Hu,agents:$g,selectedAgentId:Gu??$g[0]?.id,onSelectAgent:Wu,hasConfigData:!!Cp.data,hasSkillsData:!!Gm.data,configLoading:Cp.isLoading,models:Wm,decisions:Cp.data?{models:Cp.data.decisionModels,note:Cp.data.decisionsNote}:void 0,selectedModel:pf,onModelSelect:_m,availableTools:A1.runtime,availableFrontendTools:A1.frontend,mcpServers:Z0,enabledMcpTools:Jp,enabledMcpToolCount:s0().length,onToggleMcpTool:mv,onToggleAllMcpServerTools:g1,approvedMcpTools:w0,onToggleMcpToolApproval:R0,skills:Gm.data?.skills||[],skillsLoading:!1,enabledSkills:ig,onToggleSkill:gv,onToggleAllSkills:dg,approvedSkills:sg,onToggleSkillApproval:G0,apiBase:nb,authToken:ip?.authToken,mcpStatusData:Mh}):null,H1={title:Au,subtitle:lo,disableReason:uf?Am:void 0,brandIcon:Xd,headerContent:_h,headerActions:vd,showInformation:Qd,onInformationClick:fh??(()=>tg(!0)),padding:b1,kernelIndicatorState:wd,kernelIndicatorPlacement:Td,runtimeStatus:cf??dv.data,kernel:Kp?tf??cd:Rf?Lf??cd:cd,kernelEnvironmentName:dd,kernelCpu:md,kernelMemory:ld,kernelGpu:hd,headerButtons:ih,messageCount:jf.length,onNewChat:Dg,onClear:eb,chatViewMode:kd,onChatViewModeChange:Rd,disabledViewModes:Od,showEphemeralSurfaceControl:_p||Hh,enableEphemeralNotebookOption:_p,enableEphemeralDocumentOption:Hh,ephemeralSurfaceMode:Cf,onEphemeralSurfaceModeChange:Df},D0=$u?rh?rh(H1):jsxRuntimeExports.jsx(ChatBaseHeader,{...H1}):null;return jsxRuntimeExports.jsxs(Box,{className:xd,position:"relative",display:"flex",flexDirection:"column",height:"100%",maxHeight:"100%",minHeight:0,flex:"1 1 auto",width:"100%",minWidth:0,bg:Md||"canvas.default",borderRadius:Wh,border:_d,boxShadow:Vd,overflow:"hidden",children:[!xp&&D0,sv&&jsxRuntimeExports.jsx(Box,{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column",children:jsxRuntimeExports.jsx(ReactorLazy,{load:loadAgentDetails,errorFallback:agentDetailsRefused,props:{name:Au||"AI Agent",icon:Xd,protocol:ip?.type??"unknown",url:ip?.endpoint||"",messageCount:wf.length,agentId:$h,apiBase:ip?.configEndpoint,onBack:()=>tg(!1)}})}),yp&&Qg&&Qg.length>0&&jsxRuntimeExports.jsx(ToolApprovalBannerSection,{pendingApprovals:Qg,onApprove:tb,onReject:rb}),Ou&&ng&&jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,p:b1,bg:"danger.subtle",borderBottom:"1px solid",borderColor:"danger.muted",children:[jsxRuntimeExports.jsx(AlertIcon,{size:16}),jsxRuntimeExports.jsx(Text$3,{sx:{color:"danger.fg",fontSize:1},children:ng.message})]}),xp?jsxRuntimeExports.jsxs(Box,{flex:1,minHeight:0,display:"flex",overflow:"hidden",position:"relative",children:[jsxRuntimeExports.jsx(Box,{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden",sx:kp||If?null:{borderRight:"1px solid",borderColor:"border.default"},children:Xu||Yu?jsxRuntimeExports.jsx(CompanionSurfaceSkeleton,{mode:Kp?"notebook":"document"}):Kp?jsxRuntimeExports.jsx(ReactorLazy,{load:loadEphemeralNotebook,errorFallback:ephemeralNotebookRefused,fallback:jsxRuntimeExports.jsx(CompanionSurfaceSkeleton,{mode:"notebook"}),props:{notebookId:zp,runtimeName:Qp||$h,runtimeOverride:tp,themeVariant:bd,colorMode:Sd,nbformat:Yp??void 0,onNbformatChange:nm,toolbarComponent:Rh,toolbarExtraItems:Vh,collaborationProvider:qp}}):jsxRuntimeExports.jsx(vM.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(EphemeralDocument,{documentId:bf,runtimeName:Qp||$h,runtimeOverride:tp,themeVariant:bd,colorMode:Sd,content:$m??void 0,onContentChange:r0,onToolsReady:Hp,onKernelChange:Xf,collaboration:Xp,toolbarExtraItems:Up})})}),!If&&jsxRuntimeExports.jsxs(Box,{sx:kp?{position:"absolute",right:16,width:Gf?360:440,maxWidth:"calc(100% - 32px)",...Gf?{bottom:16,height:"62%"}:{top:16,bottom:16},display:"flex",flexDirection:"column",minHeight:0,overflow:"hidden",bg:"canvas.default",border:"1px solid",borderColor:"border.default",borderRadius:2,boxShadow:"shadow.large",zIndex:5}:{flexShrink:0,width:440,minWidth:320,maxWidth:"48%",minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden",bg:"canvas.default"},children:[D0,jsxRuntimeExports.jsx(Box,{ref:U0,flex:1,minHeight:0,overflow:"auto",bg:"canvas.default",children:Y0}),Gd,U1]}),If&&$p&&(kd==="sidebar"?jsxRuntimeExports.jsx(Box,{position:"absolute",top:8,right:8,zIndex:6,children:jsxRuntimeExports.jsx(IconButton,{icon:SidebarExpandIcon,"aria-label":"Open chat",onClick:$p,variant:"default",size:"small"})}):jsxRuntimeExports.jsx(FloatingBrandButton,{isOpen:!1,onToggle:$p,position:"bottom-right",tooltip:"Open chat"}))]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Box,{ref:U0,"data-chat-history":"",flex:1,flexGrow:1,minHeight:0,overflow:"auto",bg:"canvas.default",children:Y0}),Gd,U1]}),xh&&jsxRuntimeExports.jsx(PoweredByTag,{...bh}),Yu&&jsxRuntimeExports.jsxs(Box,{position:"absolute",inset:0,zIndex:20,display:"flex",alignItems:"center",justifyContent:"center",p:3,overflow:"auto",children:[jsxRuntimeExports.jsx(Box,{"aria-hidden":!0,position:"absolute",inset:0,bg:"canvas.default",opacity:.4,backdropFilter:"blur(1px)"}),jsxRuntimeExports.jsx(Box,{position:"relative",zIndex:1,maxWidth:"100%",children:Yu})]}),Xu&&!Yu&&jsxRuntimeExports.jsxs(Box,{position:"absolute",inset:0,zIndex:15,display:"flex",alignItems:"center",justifyContent:"center",p:3,children:[jsxRuntimeExports.jsx(Box,{"aria-hidden":!0,position:"absolute",inset:0,bg:"canvas.default",opacity:.35,backdropFilter:"blur(1px)"}),jsxRuntimeExports.jsxs(Box,{position:"relative",zIndex:1,display:"flex",flexDirection:"column",alignItems:"center",gap:3,children:[jsxRuntimeExports.jsx(StyledSpinner,{size:"large"}),jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted"},children:ed||"Launching your agent…"})]})]})]})}function ToolApprovalBannerSection({pendingApprovals:Au,onApprove:lo,onReject:$u}){const[Ru,Iu]=reactExports.useState(null);return reactExports.useEffect(()=>{Ru&&(Au.some(Pu=>Pu.id===Ru.id)||Iu(null))},[Au,Ru]),jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(ToolApprovalBanner,{pendingApprovals:Au,onReview:Pu=>Iu(Pu),onApproveAll:async()=>{if(lo)for(const Pu of Au)await lo(Pu.id)}}),jsxRuntimeExports.jsx(ToolApprovalDialog,{isOpen:!!Ru,toolName:Ru?.toolName??"",toolDescription:Ru?.toolDescription,args:Ru?.args??{},onApprove:async()=>{if(!Ru||!lo){Iu(null);return}await lo(Ru.id)!==!1&&Iu(null)},onDeny:async()=>{if(!Ru||!$u){Iu(null);return}await $u(Ru.id,"Rejected from tool approval dialog")!==!1&&Iu(null)},onClose:()=>Iu(null)})]})}const halo=Au=>({position:"absolute",inset:0,borderRadius:"50%",bg:Au||"accent.emphasis",zIndex:-1,pointerEvents:"none",willChange:"transform, opacity"});function ButtonGlow({color:Au}){return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Box,{"aria-hidden":!0,"data-button-glow":"breath",sx:{...halo(Au),filter:"blur(10px)",animation:"agentRuntimesGlowBreath 3.4s ease-in-out infinite","@keyframes agentRuntimesGlowBreath":{"0%, 100%":{transform:"scale(0.9)",opacity:.35},"50%":{transform:"scale(1.25)",opacity:.7}},"@media (prefers-reduced-motion: reduce)":{animation:"none",transform:"scale(1.1)",opacity:.4}}}),jsxRuntimeExports.jsx(Box,{"aria-hidden":!0,"data-button-glow":"aura",sx:{...halo(Au),filter:"blur(18px)",animation:"agentRuntimesGlowAura 5.3s ease-in-out infinite","@keyframes agentRuntimesGlowAura":{"0%, 100%":{transform:"scale(1)",opacity:.15},"40%":{transform:"scale(1.55)",opacity:.4},"70%":{transform:"scale(1.3)",opacity:.25}},"@media (prefers-reduced-motion: reduce)":{animation:"none",transform:"scale(1.3)",opacity:.2}}})]})}const MARGIN=24;function useViewportDrag(Au,{whole:lo=!1}={}){const[$u,Ru]=reactExports.useState(null),Iu=reactExports.useRef(null),Pu=reactExports.useCallback(Mu=>{const Du=Au.current;if(!Du)return;const Lu=Du.getBoundingClientRect();Iu.current={dx:Mu.clientX-Lu.left,dy:Mu.clientY-Lu.top};const Bu=Mu.currentTarget;Bu.setPointerCapture?.(Mu.pointerId);const ju=zu=>{if(!Iu.current)return;const Uu=Math.min(Math.max(zu.clientX-Iu.current.dx,lo?0:MARGIN-Lu.width),window.innerWidth-(lo?Lu.width:MARGIN)),Hu=Math.min(Math.max(zu.clientY-Iu.current.dy,0),window.innerHeight-(lo?Lu.height:MARGIN));Ru({left:Uu,top:Hu})},Fu=()=>{Iu.current=null,Bu.removeEventListener("pointermove",ju),Bu.removeEventListener("pointerup",Fu),Bu.removeEventListener("pointercancel",Fu)};Bu.addEventListener("pointermove",ju),Bu.addEventListener("pointerup",Fu),Bu.addEventListener("pointercancel",Fu),Mu.preventDefault()},[Au,lo]),Ou=reactExports.useCallback(()=>Ru(null),[]);return{position:$u,onHandlePointerDown:Pu,reset:Ou}}const INK=loopColors.ink,INK_DARK=loopColors.inkDark;function Eyes({cx:Au,cy:lo,gap:$u,r:Ru,colours:Iu}){const Pu=Au-$u/2,Ou=Au+$u/2;return jsxRuntimeExports.jsxs("g",{children:[jsxRuntimeExports.jsx("circle",{cx:Pu,cy:lo,r:Ru,fill:Iu.white,stroke:Iu.ring,strokeWidth:1.5}),jsxRuntimeExports.jsx("circle",{cx:Ou,cy:lo,r:Ru,fill:Iu.white,stroke:Iu.ring,strokeWidth:1.5}),jsxRuntimeExports.jsxs("g",{className:"assistant-pupils",children:[jsxRuntimeExports.jsx("circle",{cx:Pu+Ru*.15,cy:lo+Ru*.1,r:Ru*.45,fill:Iu.pupil}),jsxRuntimeExports.jsx("circle",{cx:Ou+Ru*.15,cy:lo+Ru*.1,r:Ru*.45,fill:Iu.pupil}),jsxRuntimeExports.jsx("circle",{cx:Pu+Ru*.3,cy:lo-Ru*.1,r:Ru*.14,fill:Iu.white}),jsxRuntimeExports.jsx("circle",{cx:Ou+Ru*.3,cy:lo-Ru*.1,r:Ru*.14,fill:Iu.white})]}),jsxRuntimeExports.jsxs("g",{className:"assistant-lids",children:[jsxRuntimeExports.jsx("ellipse",{cx:Pu,cy:lo,rx:Ru+.5,ry:Ru+.5,fill:Iu.lid}),jsxRuntimeExports.jsx("ellipse",{cx:Ou,cy:lo,rx:Ru+.5,ry:Ru+.5,fill:Iu.lid})]})]})}const PAPER_CLIP={light:{wire:"#7A808A",shine:"#E3E6EB",line:INK,eye:{white:loopColors.white,ring:INK,pupil:INK,lid:"#B8BDC6"}},dark:{wire:"#C9CED6",shine:"#8D93A0",line:INK_DARK,eye:{white:INK_DARK,ring:loopColors.grayDark,pupil:INK,lid:"#8D93A0"}}},WIZARD={light:{hat:"#6E5CD6",brim:"#4A3C9E",robe:"#5B4BB7",face:"#F2D3B3",beard:"#F4F4F6",beardEdge:"#7A808A",star:"#F8D469",eye:{white:loopColors.white,ring:INK,pupil:INK,lid:"#F2D3B3"}},dark:{hat:"#9C88F0",brim:"#7B67DB",robe:"#8F7CE8",face:"#E8C4A0",beard:"#E4E4EA",beardEdge:loopColors.grayDark,star:"#F8D469",eye:{white:INK_DARK,ring:INK,pupil:INK,lid:"#E8C4A0"}}},CAT={light:{fur:"#F4A261",edge:"#B4571A",tail:"#E08A45",ear:"#F6A5C1",nose:"#B83A6B",whiskers:INK,eye:{white:loopColors.white,ring:INK,pupil:INK,lid:"#F4A261"}},dark:{fur:"#F4A261",edge:"#F4A261",tail:"#E08A45",ear:"#F6A5C1",nose:"#B83A6B",whiskers:INK_DARK,eye:{white:INK_DARK,ring:INK,pupil:INK,lid:"#F4A261"}}},LOOP_EYES={light:{eye:{white:loopColors.white,ring:INK,pupil:INK,lid:"#E3E6EB"}},dark:{eye:{white:INK_DARK,ring:INK_DARK,pupil:loopColors.black,lid:loopColors.grayDark}}};function PaperClip({size:Au,mode:lo="light"}){const $u=PAPER_CLIP[lo],Ru="M40 86 L40 30 Q40 14 52 14 Q64 14 64 30 L64 74 Q64 82 56 82 Q48 82 48 74 L48 36";return jsxRuntimeExports.jsx("svg",{width:Au,height:Au,viewBox:"0 0 96 96",role:"img","aria-label":"Paper clip","data-assistant-mode":lo,children:jsxRuntimeExports.jsxs("g",{className:"assistant-body",children:[jsxRuntimeExports.jsx("path",{d:Ru,fill:"none",stroke:$u.wire,strokeWidth:6,strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:Ru,fill:"none",stroke:$u.shine,strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M36 22 Q42 18 47 21",stroke:$u.line,strokeWidth:2,fill:"none",strokeLinecap:"round"}),jsxRuntimeExports.jsx("path",{d:"M57 21 Q62 18 68 22",stroke:$u.line,strokeWidth:2,fill:"none",strokeLinecap:"round"}),jsxRuntimeExports.jsx(Eyes,{cx:52,cy:30,gap:16,r:6.5,colours:$u.eye}),jsxRuntimeExports.jsx("path",{className:"assistant-mouth",d:"M48 44 Q52 47 56 44",stroke:$u.line,strokeWidth:2,fill:"none",strokeLinecap:"round"})]})})}function Wizard({size:Au,mode:lo="light"}){const $u=WIZARD[lo];return jsxRuntimeExports.jsx("svg",{width:Au,height:Au,viewBox:"0 0 96 96",role:"img","aria-label":"Wizard","data-assistant-mode":lo,children:jsxRuntimeExports.jsxs("g",{className:"assistant-body",children:[jsxRuntimeExports.jsx("path",{d:"M34 58 Q48 52 62 58 Q70 74 76 92 Q48 98 20 92 Q26 74 34 58 Z",fill:$u.robe}),jsxRuntimeExports.jsx("path",{d:"M21 90 Q48 96 75 90 L76 92 Q48 98 20 92 Z",fill:$u.brim}),jsxRuntimeExports.jsx("circle",{cx:30,cy:82,r:1.6,fill:$u.star}),jsxRuntimeExports.jsx("circle",{cx:67,cy:78,r:1.3,fill:$u.star}),jsxRuntimeExports.jsx("ellipse",{cx:48,cy:46,rx:13,ry:12,fill:$u.face}),jsxRuntimeExports.jsx("path",{d:"M33 38 Q31 66 40 77 Q48 89 56 77 Q65 66 63 38 Q61 50 56 53 Q48 58 40 53 Q35 50 33 38 Z",fill:$u.beard,stroke:$u.beardEdge,strokeWidth:1,strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{className:"assistant-mouth",d:"M44 59 Q48 62 52 59",stroke:INK,strokeWidth:1.8,fill:"none",strokeLinecap:"round"}),jsxRuntimeExports.jsx("path",{d:"M39 55 Q44 51 48 54 Q52 51 57 55 Q52 57 48 56 Q44 57 39 55 Z",fill:$u.beard,stroke:$u.beardEdge,strokeWidth:.8}),jsxRuntimeExports.jsx("path",{d:"M25 36 Q35 26 39 14 Q43 2 58 3 Q50 8 53 18 Q58 30 71 36 Q48 30 25 36 Z",fill:$u.hat}),jsxRuntimeExports.jsx("path",{d:"M18 37 Q48 27 78 37 Q48 45 18 37 Z",fill:$u.brim}),jsxRuntimeExports.jsx("path",{d:"M47 17 l1.8 3.6 4 .6 -2.9 2.8 .7 4 -3.6 -1.9 -3.6 1.9 .7 -4 -2.9 -2.8 4 -.6 Z",fill:$u.star}),jsxRuntimeExports.jsx("circle",{cx:56,cy:28,r:1.4,fill:$u.star}),jsxRuntimeExports.jsx(Eyes,{cx:48,cy:46,gap:11,r:4,colours:$u.eye})]})})}function Cat({size:Au,mode:lo="light"}){const $u=CAT[lo],Ru="M70 84 Q90 78 84 58";return jsxRuntimeExports.jsx("svg",{width:Au,height:Au,viewBox:"0 0 96 96",role:"img","aria-label":"Cat","data-assistant-mode":lo,children:jsxRuntimeExports.jsxs("g",{className:"assistant-body",children:[jsxRuntimeExports.jsx("path",{d:Ru,stroke:$u.edge,strokeWidth:8,fill:"none",strokeLinecap:"round"}),jsxRuntimeExports.jsx("path",{d:Ru,stroke:$u.tail,strokeWidth:5,fill:"none",strokeLinecap:"round"}),jsxRuntimeExports.jsx("ellipse",{cx:48,cy:78,rx:24,ry:14,fill:$u.fur,stroke:$u.edge,strokeWidth:1.5}),jsxRuntimeExports.jsx("path",{d:"M24 30 L28 8 L42 22 Z",fill:$u.fur,stroke:$u.edge,strokeWidth:1.5,strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M72 30 L68 8 L54 22 Z",fill:$u.fur,stroke:$u.edge,strokeWidth:1.5,strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M28 26 L30 14 L38 22 Z",fill:$u.ear}),jsxRuntimeExports.jsx("path",{d:"M68 26 L66 14 L58 22 Z",fill:$u.ear}),jsxRuntimeExports.jsx("circle",{cx:48,cy:42,r:24,fill:$u.fur,stroke:$u.edge,strokeWidth:1.5}),jsxRuntimeExports.jsx(Eyes,{cx:48,cy:38,gap:18,r:6.5,colours:$u.eye}),jsxRuntimeExports.jsx("path",{d:"M45 48 L51 48 L48 52 Z",fill:$u.nose}),jsxRuntimeExports.jsx("path",{className:"assistant-mouth",d:"M43 55 Q48 58 53 55",stroke:INK,strokeWidth:2,fill:"none",strokeLinecap:"round"}),jsxRuntimeExports.jsx("path",{d:"M30 48 L18 46 M30 52 L18 54 M66 48 L78 46 M66 52 L78 54",stroke:$u.whiskers,strokeWidth:1.2,strokeLinecap:"round"})]})})}function LoopEyes({size:Au,mode:lo="light"}){const $u=LOOP_EYES[lo];return jsxRuntimeExports.jsx("svg",{width:Au,height:Au,viewBox:"0 0 96 96",role:"img","aria-label":"L👀P eyes","data-assistant-mode":lo,children:jsxRuntimeExports.jsxs("g",{className:"assistant-body",children:[jsxRuntimeExports.jsx(Eyes,{cx:48,cy:50,gap:40,r:18,colours:$u.eye}),jsxRuntimeExports.jsx("path",{className:"assistant-mouth",d:"M42 80 Q48 84 54 80",stroke:lo==="dark"?INK_DARK:INK,strokeWidth:2.5,fill:"none",strokeLinecap:"round",opacity:0})]})})}const eyeOf=(Au,lo)=>({white:Au.white,ring:Au.ring,pupil:Au.pupil,on:lo}),ASSISTANT_CHARACTERS=[{id:"paperclip",name:"Paper clip",Drawing:PaperClip,keyColours:{light:{edges:[PAPER_CLIP.light.wire,PAPER_CLIP.light.line],eye:eyeOf(PAPER_CLIP.light.eye,"page")},dark:{edges:[PAPER_CLIP.dark.wire,PAPER_CLIP.dark.line],eye:eyeOf(PAPER_CLIP.dark.eye,"page")}}},{id:"wizard",name:"Wizard",Drawing:Wizard,keyColours:{light:{edges:[WIZARD.light.hat,WIZARD.light.brim,WIZARD.light.robe,WIZARD.light.beardEdge],eye:eyeOf(WIZARD.light.eye,WIZARD.light.face)},dark:{edges:[WIZARD.dark.hat,WIZARD.dark.brim,WIZARD.dark.robe,WIZARD.dark.beardEdge],eye:eyeOf(WIZARD.dark.eye,WIZARD.dark.face)}}},{id:"cat",name:"Cat",Drawing:Cat,keyColours:{light:{edges:[CAT.light.edge,CAT.light.whiskers],eye:eyeOf(CAT.light.eye,CAT.light.fur)},dark:{edges:[CAT.dark.edge,CAT.dark.whiskers],eye:eyeOf(CAT.dark.eye,CAT.dark.fur)}}},{id:"eyes",name:"L👀P eyes",Drawing:LoopEyes,keyColours:{light:{edges:[LOOP_EYES.light.eye.ring],eye:eyeOf(LOOP_EYES.light.eye,"page")},dark:{edges:[LOOP_EYES.dark.eye.white],eye:eyeOf(LOOP_EYES.dark.eye,"page")}}}],DEFAULT_ASSISTANT_CHARACTER="paperclip";function assistantCharacter(Au){const lo=ASSISTANT_CHARACTERS.find($u=>$u.id===Au);if(!lo)throw new Error(`There is no assistant character "${Au}"; the characters are ${ASSISTANT_CHARACTERS.map($u=>$u.id).join(", ")}.`);return lo}const DEFAULT_DECISION_NAME="Answer",DEFAULT_SCORE_RANGE={from:1,to:5},MAX_SCORE_STEPS=11;function scoreSteps(Au){const lo=[];for(let $u=Au.from;$u<=Au.to;$u+=1)lo.push(String($u));return lo}function decisionAskProblem(Au){if(!Au.situation.trim())return"Say the situation the question is about.";if(!Au.question.trim())return"Ask a question.";if(Au.type==="choice"){const lo=(Au.options??[]).filter($u=>$u.trim());if(lo.length<2)return"A choice needs at least two options.";if(new Set(lo.map($u=>$u.trim())).size!==lo.length)return"Two options are the same."}if(Au.type==="score"){const lo=Au.range??DEFAULT_SCORE_RANGE;if(!Number.isInteger(lo.from)||!Number.isInteger(lo.to))return"A score goes from a whole number to another.";if(lo.to<=lo.from)return"A score goes from a lower number to a higher one.";if(lo.to-lo.from+1>MAX_SCORE_STEPS)return`A score has at most ${MAX_SCORE_STEPS} steps.`}}function decisionRequest(Au){const lo=Au.type==="choice"?(Au.options??[]).map($u=>$u.trim()).filter(Boolean):Au.type==="score"?scoreSteps(Au.range??DEFAULT_SCORE_RANGE):[];return{state:Au.situation.trim(),questions:[{name:Au.name?.trim()||DEFAULT_DECISION_NAME,type:Au.type,instructions:Au.question.trim(),options:lo}]}}function confidenceWords(Au){return String(Number(Au.toFixed(2)))}function decisionAnswerWords(Au,lo,$u=[]){if(typeof lo.probability=="number"&&lo.choice===void 0){const Iu=lo.probability>=.5;return`${Au}: ${Iu?"yes":"no"} (${confidenceWords(Iu?lo.probability:1-lo.probability)})`}const Ru=typeof lo.confidence=="number"?` (${confidenceWords(lo.confidence)})`:"";if(typeof lo.score=="number"){const Iu=$u.length?$u:Object.keys(lo.legend??{}).sort((Du,Lu)=>Number(Du)-Number(Lu)).map(Du=>lo.legend?.[Du]??Du),Pu=lo.legend?.[String(lo.score)]??Iu[lo.score],Ou=Iu[Iu.length-1],Mu=Iu.length>0&&Iu.every(Du=>/^-?\d+$/.test(Du.trim()));return`${Au}: ${Pu??lo.score+1}${Mu&&Ou!==void 0?` of ${Ou}`:""}${Ru}`}return typeof lo.choice=="string"?`${Au}: ${lo.choice}${Ru}`:`${Au}: no answer`}function decisionResponseWords(Au,lo){if(lo.refusal)return lo.refusal;const[$u]=Au.questions,Ru=lo.answers?.[$u.name];return Ru?decisionAnswerWords($u.name,Ru,$u.options):"Nothing was decided: the answer did not come back."}function decisionsAskerAt(Au,lo){const $u=Au.replace(/\/+$/,"");return async Ru=>{let Iu;try{Iu=await fetch(`${$u}/api/v1/configure/inference/decisions`,{method:"POST",headers:{"Content-Type":"application/json",...lo?{Authorization:`Bearer ${lo}`}:{}},body:JSON.stringify(Ru)})}catch{return{refusal:"Nothing was decided: the runtime could not be reached."}}if(!Iu.ok){let Pu="";try{const Ou=await Iu.json();Pu=typeof Ou.detail=="string"?Ou.detail:""}catch{}return{refusal:`Nothing was decided: the runtime refused it (${Iu.status})${Pu?`: ${Pu}`:"."}`}}return await Iu.json()}}const DECISION_WORDS={ask:"Ask a decision",asking:"Asking…",submit:"Ask",cancel:"Cancel",again:"Ask another",types:{noul:"Yes or no",choice:"A choice",score:"A score"}},LINK_SX={mt:1,p:0,border:0,bg:"transparent",color:"accent.fg",textDecoration:"underline",cursor:"pointer",fontSize:1};function DecisionAsk({ask:Au,onActiveChange:lo}){const[$u,Ru]=reactExports.useState(!1),[Iu,Pu]=reactExports.useState(""),[Ou,Mu]=reactExports.useState(""),[Du,Lu]=reactExports.useState(""),[Bu,ju]=reactExports.useState("noul"),[Fu,zu]=reactExports.useState(""),[Uu,Hu]=reactExports.useState(String(DEFAULT_SCORE_RANGE.from)),[Vu,Gu]=reactExports.useState(String(DEFAULT_SCORE_RANGE.to)),[Wu,Ku]=reactExports.useState(),[Ju,Yu]=reactExports.useState(!1),[Xu,ed]=reactExports.useState(),td=reactExports.useRef(lo);td.current=lo,reactExports.useEffect(()=>()=>td.current?.(!1),[]);const nd=ad=>{Ru(ad),lo?.(ad)},od=()=>{ed(void 0),Ku(void 0),nd(!1)};if(!$u)return jsxRuntimeExports.jsx(Box,{as:"button",type:"button","data-balloon-ask-decision":"",onClick:()=>nd(!0),...LINK_SX,display:"block",children:DECISION_WORDS.ask});if(Xu!==void 0)return jsxRuntimeExports.jsxs(Box,{"data-balloon-decision":"answered",mt:2,children:[jsxRuntimeExports.jsx(Text$3,{as:"p","data-decision-answer":"",sx:{m:0,fontWeight:"semibold"},children:Xu}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,mt:2,children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",onClick:()=>ed(void 0),children:DECISION_WORDS.again}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"invisible",onClick:od,children:DECISION_WORDS.cancel})]})]});const sd=async()=>{const ad={situation:Iu,question:Ou,type:Bu,name:Du,options:Fu.split(`
3675
3675
  `),range:{from:Number(Uu),to:Number(Vu)}},pd=decisionAskProblem(ad);if(Ku(pd),pd)return;const gd=decisionRequest(ad);Yu(!0);try{ed(decisionResponseWords(gd,await Au(gd)))}catch(xd){ed(`Nothing was decided: ${xd instanceof Error?xd.message:String(xd)}`)}finally{Yu(!1)}};return jsxRuntimeExports.jsxs(Box,{as:"form","data-balloon-decision":"asking","aria-label":DECISION_WORDS.ask,onSubmit:ad=>{ad.preventDefault(),sd()},onKeyDown:ad=>{ad.key==="Escape"&&od()},mt:2,display:"flex",flexDirection:"column",gap:2,children:[jsxRuntimeExports.jsxs(FormControl$1,{children:[jsxRuntimeExports.jsx(FormControl$1.Label,{children:"Situation"}),jsxRuntimeExports.jsx(Textarea,{block:!0,rows:3,resize:"vertical",name:"situation",placeholder:"Help! My payouts have been failing for 3 days.",value:Iu,onChange:ad=>Pu(ad.target.value)})]}),jsxRuntimeExports.jsxs(FormControl$1,{children:[jsxRuntimeExports.jsx(FormControl$1.Label,{children:"Question"}),jsxRuntimeExports.jsx(TextInput$1,{block:!0,size:"small",name:"question",placeholder:"Is it urgent?",value:Ou,onChange:ad=>Mu(ad.target.value)})]}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,children:[jsxRuntimeExports.jsxs(FormControl$1,{sx:{flex:1},children:[jsxRuntimeExports.jsx(FormControl$1.Label,{children:"Type"}),jsxRuntimeExports.jsx(Select$1,{block:!0,size:"small",name:"type",value:Bu,onChange:ad=>ju(ad.target.value),children:Object.keys(DECISION_WORDS.types).map(ad=>jsxRuntimeExports.jsx(Select$1.Option,{value:ad,children:DECISION_WORDS.types[ad]},ad))})]}),jsxRuntimeExports.jsxs(FormControl$1,{sx:{flex:1},children:[jsxRuntimeExports.jsx(FormControl$1.Label,{children:"Name"}),jsxRuntimeExports.jsx(TextInput$1,{block:!0,size:"small",name:"name",placeholder:"Answer",value:Du,onChange:ad=>Lu(ad.target.value)})]})]}),Bu==="choice"&&jsxRuntimeExports.jsxs(FormControl$1,{children:[jsxRuntimeExports.jsx(FormControl$1.Label,{children:"Options, one per line"}),jsxRuntimeExports.jsx(Textarea,{block:!0,rows:3,resize:"vertical",name:"options",placeholder:`Billing
3676
3676
  Tech
3677
3677
  Sales`,value:Fu,onChange:ad=>zu(ad.target.value)})]}),Bu==="score"&&jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,children:[jsxRuntimeExports.jsxs(FormControl$1,{sx:{flex:1},children:[jsxRuntimeExports.jsx(FormControl$1.Label,{children:"From"}),jsxRuntimeExports.jsx(TextInput$1,{block:!0,size:"small",type:"number",name:"from",value:Uu,onChange:ad=>Hu(ad.target.value)})]}),jsxRuntimeExports.jsxs(FormControl$1,{sx:{flex:1},children:[jsxRuntimeExports.jsx(FormControl$1.Label,{children:"To"}),jsxRuntimeExports.jsx(TextInput$1,{block:!0,size:"small",type:"number",name:"to",value:Vu,onChange:ad=>Gu(ad.target.value)})]})]}),Wu?jsxRuntimeExports.jsx(Text$3,{as:"p",role:"alert",sx:{m:0,color:"danger.fg",fontSize:0},children:Wu}):null,jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"primary",type:"submit",disabled:Ju,children:Ju?DECISION_WORDS.asking:DECISION_WORDS.submit}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",type:"button",onClick:od,disabled:Ju,children:DECISION_WORDS.cancel})]})]})}const DEFAULT_BALLOON_DISPLAY="history";let displayNames=null;function toolDisplayName(Au){if(!displayNames){displayNames=new Map;for(const Ru of Object.values(BACKEND_TOOL_CATALOG)){const Iu=Ru.runtime?.method;Iu&&Ru.name&&!displayNames.has(Iu)&&displayNames.set(Iu,Ru.name)}}const lo=displayNames.get(Au);if(lo)return lo;const $u=Au.indexOf("__");return $u>0?Au.slice($u+2):Au}function toolLineParts(Au,lo=ENGLISH_CHAT_WORDS){if(Au.phase==="running"&&Au.words)return{before:"",name:"",after:Au.words};switch(Au.phase){case"running":return{...lo.toolRunning,name:Au.name};case"done":return{...lo.toolDone,name:Au.name};case"failed":return{...lo.toolFailedLine,name:Au.name}}}function toolLineText(Au,lo=ENGLISH_CHAT_WORDS){const{before:$u,name:Ru,after:Iu}=toolLineParts(Au,lo);return`${$u}${Ru}${Iu}`}function newestToolLine(Au){const lo=Au[Au.length-1];if(!lo||typeof lo.toolName!="string"||!lo.toolName)return;const $u=lo.status==="error"||typeof lo.error=="string"&&lo.error?"failed":lo.status==="complete"?"done":"running";return{id:String(lo.toolCallId??lo.id??lo.toolName),tool:lo.toolName,name:toolDisplayName(lo.toolName),phase:$u}}function toolAnnouncement(Au,lo,$u=ENGLISH_CHAT_WORDS){if(Au&&!(lo&&lo.id===Au.id&&lo.phase===Au.phase))return toolLineText(Au,$u)}function conversationCount(Au){return Au.filter(lo=>{const $u=lo;return($u.role==="user"||$u.role==="assistant")&&typeof $u.toolName!="string"}).length}function displayItemOfLine(Au){return!Au.tool&&!Au.name?{id:`balloon-activity:${Au.id}`,role:"assistant",content:Au.words??"",createdAt:new Date(0)}:toolCallOfLine(Au)}function toolCallOfLine(Au){return{id:`balloon-tool:${Au.id}`,type:"tool-call",toolCallId:Au.id,toolName:Au.tool||Au.name,args:{},status:Au.phase==="failed"?"error":Au.phase==="done"?"complete":"executing",...Au.words?{summary:Au.words}:{}}}function withToolCall(Au,lo){return!lo||Au.some($u=>$u.toolCallId===lo.id||$u.id===lo.id)?Au:[...Au,displayItemOfLine(lo)]}const VISUALLY_HIDDEN={position:"absolute",width:1,height:1,overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap"},BALLOON_AVATARS={userAvatar:null,assistantAvatar:null,showAvatars:!1,avatarSize:0,userAvatarBg:"neutral.muted",assistantAvatarBg:"accent.emphasis"};async function respondInBalloon(Au,lo){if(lo&&typeof lo=="object"){const $u=lo;$u.type==="tool-approval-decision"&&typeof $u.approved=="boolean"&&typeof $u.approvalId=="string"&&agentRuntimeStore.getState().sendDecision($u.approvalId,$u.approved)}}function BalloonChatItems({items:Au,density:lo="compact",waiting:$u=!1}){const Ru=reactExports.useRef(null);return jsxRuntimeExports.jsx(Box,{"data-balloon-chat-items":"",minWidth:0,children:jsxRuntimeExports.jsx(ChatMessageList,{displayItems:Au,isLoading:$u,isStreaming:!1,showLoadingIndicator:$u,hideMessagesAfterToolUI:!1,avatarConfig:BALLOON_AVATARS,padding:0,onRespond:respondInBalloon,messagesEndRef:Ru,emptyContent:$u?jsxRuntimeExports.jsx(TypingDots,{size:6}):null,density:lo})})}function BalloonToolCall({line:Au,waiting:lo=!1}){return jsxRuntimeExports.jsx(Box,{"aria-hidden":"true","data-balloon-tool":Au.phase,"data-balloon-tool-name":Au.tool||void 0,minWidth:0,width:"100%",children:jsxRuntimeExports.jsx(BalloonChatItems,{items:[displayItemOfLine(Au)],waiting:lo})})}function ToolLineAnnouncer({line:Au}){const lo=useChatWords(),$u=reactExports.useRef(void 0),[Ru,Iu]=reactExports.useState("");return reactExports.useEffect(()=>{const Pu=toolAnnouncement(Au,$u.current,lo);Au&&Pu&&($u.current={id:Au.id,phase:Au.phase},Iu(Pu))},[Au?.id,Au?.phase]),jsxRuntimeExports.jsx(Box,{as:"span",role:"status","aria-live":"polite","data-balloon-announce":"",...VISUALLY_HIDDEN,children:Ru})}function WordsAnnouncer({text:Au,speaking:lo=!1}){const $u=reactExports.useRef(void 0),[Ru,Iu]=reactExports.useState("");return reactExports.useEffect(()=>{lo||!Au||Au===$u.current||($u.current=Au,Iu(plainWords(Au)))},[Au,lo]),jsxRuntimeExports.jsx(Box,{as:"span",role:"status","aria-live":"polite","data-balloon-words-announce":"",...VISUALLY_HIDDEN,children:Ru})}function BalloonNow({busy:Au=!1}){const lo=useChatWords();return jsxRuntimeExports.jsxs(Box,{as:"span","data-balloon-now":Au?"busy":"",display:"inline-flex",alignItems:"center",gap:"6px",fontSize:0,fontWeight:"semibold",color:"accent.fg",textTransform:"uppercase",letterSpacing:"0.04em",sx:{"@keyframes balloonNowBreathe":{"0%, 100%":{opacity:1,transform:"scale(1)"},"50%":{opacity:.35,transform:"scale(0.7)"}},"& [data-balloon-now-dot]":{width:6,height:6,borderRadius:"50%",bg:"accent.emphasis",animation:Au?"balloonNowBreathe 1.2s ease-in-out infinite":"none"},"@media (prefers-reduced-motion: reduce)":{"& [data-balloon-now-dot]":{animation:"none"}}},children:[jsxRuntimeExports.jsx(Box,{as:"span","data-balloon-now-dot":"","aria-hidden":"true"}),lo.now]})}function conversationHeaderText(Au,lo=ENGLISH_CHAT_WORDS){return Au>0?`${lo.conversation} · ${Au}`:lo.conversation}function ConversationBalloonHeader({count:Au}){const lo=useChatWords();return jsxRuntimeExports.jsx(Box,{"data-balloon-header":"",flexShrink:0,display:"flex",alignItems:"center",gap:2,pl:3,pr:6,py:2,borderBottom:"1px solid",borderColor:"border.muted",bg:"canvas.default",borderTopLeftRadius:"var(--theme-radius-bubble, 16px)",borderTopRightRadius:"var(--theme-radius-bubble, 16px)",children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,fontWeight:"semibold",color:"fg.muted"},children:conversationHeaderText(Au,lo)})})}function CurrentBalloonBody({text:Au,tool:lo,busy:$u=!1,speaking:Ru=!1,attachment:Iu,waiting:Pu=!1,whole:Ou=!1,fullText:Mu,onOverflow:Du}){const Lu=reactExports.useRef(null),Bu=!Ou&&!!Au&&!!Mu&&Mu!==Au;return reactExports.useLayoutEffect(()=>{const ju=Lu.current;!ju||Ou||!Du||Du(ju.scrollHeight>ju.clientHeight+1)},[Au,Ou,Du]),jsxRuntimeExports.jsxs(Box,{"data-balloon-current":"",display:"flex",flexDirection:"column",gap:1,minWidth:0,children:[jsxRuntimeExports.jsx(BalloonNow,{busy:$u}),lo?jsxRuntimeExports.jsx(BalloonToolCall,{line:lo,waiting:Pu}):Au?jsxRuntimeExports.jsxs(Box,{"aria-busy":Ru,ref:Lu,"data-balloon-current-text":Ou?"whole":"",maxHeight:Ou?240:"5.6em",overflowY:Ou?"auto":void 0,overflowWrap:"anywhere",pr:Ou?1:void 0,overflow:Ou?void 0:"hidden",children:[Bu?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Box,{"aria-hidden":"true",children:jsxRuntimeExports.jsx(ChatMarkdown,{density:"compact",text:Au})}),jsxRuntimeExports.jsx(Box,{as:"span","data-balloon-words-whole":"",...VISUALLY_HIDDEN,children:plainWords(Mu??"")})]}):jsxRuntimeExports.jsx(ChatMarkdown,{density:"compact",text:Ou?Mu??Au:Au}),Pu&&jsxRuntimeExports.jsx(Box,{as:"span",ml:2,display:"inline-flex",children:jsxRuntimeExports.jsx(TypingDots,{size:5})})]}):Pu?jsxRuntimeExports.jsx(TypingDots,{size:6}):null,Iu,jsxRuntimeExports.jsx(WordsAnnouncer,{text:lo?void 0:Mu??Au,speaking:Ru}),jsxRuntimeExports.jsx(ToolLineAnnouncer,{line:lo})]})}const BalloonExpandContext=reactExports.createContext(null);function BalloonExpandButton({title:Au,onExpand:lo}){const $u=useChatWords();return jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"invisible",leadingVisual:ScreenFullIcon,"aria-label":$u.expandWhat(Au),"data-balloon-expand":"",onClick:lo,sx:{alignSelf:"flex-start",px:1},children:$u.expand})}const EXPANDED_DIALOG_SIZE={width:"80vw",height:"80vh"};function ExpandedVisual({visual:Au,target:lo,onClose:$u}){const Ru=lo?.current;return lo?Ru?reactDomExports.createPortal(jsxRuntimeExports.jsxs(Box,{"data-balloon-expanded":"target","data-balloon-visual":Au.id,position:"relative",minWidth:0,children:[jsxRuntimeExports.jsx(Box,{position:"absolute",top:0,right:0,zIndex:1,children:jsxRuntimeExports.jsx(IconButton,{icon:Au.shrink?ScreenNormalIcon:XIcon,size:"small",variant:"invisible","aria-label":`${Au.shrink?"Shrink":"Close"} ${Au.title}`,"data-balloon-expanded-close":"",...Au.shrink?{"data-balloon-shrink":""}:{},onClick:$u})}),Au.render("target")]}),Ru):null:jsxRuntimeExports.jsx(Dialog$1,{title:Au.title,onClose:$u,sx:{width:EXPANDED_DIALOG_SIZE.width,maxWidth:EXPANDED_DIALOG_SIZE.width,height:EXPANDED_DIALOG_SIZE.height,maxHeight:EXPANDED_DIALOG_SIZE.height},children:jsxRuntimeExports.jsx(Box,{"data-balloon-expanded":"overlay","data-balloon-visual":Au.id,minWidth:0,children:Au.render("overlay")})})}function focusExpanded(Au){const lo=Au?.current;if(!lo)return;const $u=typeof window<"u"&&!!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;lo.scrollIntoView?.({behavior:$u?"auto":"smooth",block:"start"}),(lo.querySelector('[tabindex="-1"]')??lo).focus?.({preventScroll:!0})}function BalloonSuggestions({suggestions:Au,onSuggestion:lo}){const $u=useChatWords();return jsxRuntimeExports.jsx(Box,{role:"group","aria-label":$u.suggestions,"data-balloon-suggestions":"",display:"flex",flexWrap:"wrap",gap:1,mt:2,children:Au.map(Ru=>jsxRuntimeExports.jsx(ButtonComponent,{size:"small","data-balloon-suggestion":Ru.label,"aria-label":`Ask: ${Ru.prompt}`,title:Ru.prompt,onClick:()=>lo(Ru),sx:{borderRadius:999},children:Ru.label},Ru.label))})}const BALLOON_HISTORY_MAX_HEIGHT=220,BALLOON_HISTORY_WITH_ATTACHMENT_MAX_HEIGHT=120;function BalloonHistoryLarge({history:Au,tool:lo,attachment:$u}){const Ru=useChatWords();return jsxRuntimeExports.jsxs(Box,{role:"log","aria-label":Ru.conversation,"data-balloon-history-large":"",display:"flex",flexDirection:"column",gap:2,children:[jsxRuntimeExports.jsx(BalloonChatItems,{items:withToolCall(Au,lo),density:"comfortable"}),$u?jsxRuntimeExports.jsx(Box,{children:$u}):null]})}function BalloonHistory({history:Au,onOpen:lo,maxHeight:$u=BALLOON_HISTORY_MAX_HEIGHT,onExpand:Ru,tool:Iu,waiting:Pu=!1}){const Ou=useChatWords(),Mu=reactExports.useRef(null),Du=Au[Au.length-1]?.id;return reactExports.useEffect(()=>{const Lu=Mu.current;Lu&&(Lu.scrollTop=Lu.scrollHeight)},[Au.length,Du,Pu,Iu?.id,Iu?.phase]),reactExports.useEffect(()=>{const Lu=Mu.current,Bu=Lu?.firstElementChild;if(!Lu||!Bu||typeof ResizeObserver>"u")return;const ju=new ResizeObserver(()=>{Lu.scrollTop=Lu.scrollHeight});return ju.observe(Bu),()=>ju.disconnect()},[]),jsxRuntimeExports.jsxs(Box,{"data-balloon-history":"",flex:1,minWidth:0,display:"flex",flexDirection:"column",children:[jsxRuntimeExports.jsx(Box,{as:"button",type:"button","data-balloon-peek":"","data-balloon-header":"",onClick:lo,m:0,p:0,pb:1,border:0,bg:"transparent",font:"inherit",textAlign:"left",cursor:"pointer",fontSize:0,fontWeight:"semibold",color:"fg.muted",hover:{textDecoration:"underline"},children:conversationHeaderText(conversationCount(Au),Ou)}),Ru?jsxRuntimeExports.jsx(IconButton,{icon:ScreenFullIcon,size:"small",variant:"invisible","aria-label":Ou.expandConversation,"data-balloon-history-expand":"",onClick:Ru,sx:{position:"absolute",top:"4px",right:"28px"}}):null,jsxRuntimeExports.jsx(Box,{ref:Mu,role:"log","aria-label":Ou.conversation,"data-balloon-history-list":"",maxHeight:$u,overflowY:"auto",display:"flex",flexDirection:"column",pr:1,children:jsxRuntimeExports.jsx(BalloonChatItems,{items:withToolCall(Au,Iu),waiting:Pu})})]})}function SpeechBalloon({text:Au,more:lo=!1,onOpen:$u,above:Ru,side:Iu="above",align:Pu,tailAt:Ou,approval:Mu,decide:Du,onDecisionActive:Lu,wide:Bu=!1,onDismissPeek:ju,display:Fu="history",tool:zu,speaking:Uu=!1,busy:Hu=!1,attachment:Vu,history:Gu,onExpand:Wu,expandTitle:Ku,suggestions:Ju,onSuggestion:Yu,waiting:Xu=!1,fullText:ed,onExpandHistory:td}){const nd=useChatWords(),[od,sd]=reactExports.useState(!1),[ad,pd]=reactExports.useState(!1),gd=!!ed&&ed!==Au||!!lo&&Au.endsWith("…"),xd=ed??Au;reactExports.useEffect(()=>{sd(!1)},[xd.slice(0,40)]);const yd=Ju&&Ju.length>0&&Yu&&!Mu?Ju:null,vd=Fu==="current",wd=!vd&&Gu&&Gu.length>0?Gu:null;return jsxRuntimeExports.jsxs(Box,{"data-speech-balloon":"","data-balloon-display":Fu,maxWidth:Bu||wd||yd||od||vd&&Vu?300:vd?260:280,px:3,py:2,color:"fg.default",border:"1px solid",borderRadius:"bubble",boxShadow:"shadow.medium",fontSize:1,textAlign:"left",bottom:Iu==="above"?`${Ru}px`:void 0,top:Iu==="above"?void 0:`${Ru}px`,sx:{position:"absolute",[Pu]:0,width:Bu||wd||yd||od||vd&&Vu?300:"max-content",bg:"canvas.default",borderColor:vd?"accent.muted":"border.default","&::after":{content:'""',position:"absolute",...Iu==="above"?{bottom:"-7px"}:{top:"-7px"},[Pu]:`${Ou-6}px`,width:12,height:12,bg:"canvas.default",borderRight:"1px solid",borderBottom:"1px solid",borderColor:vd?"accent.muted":"border.default",transform:Iu==="above"?"rotate(45deg)":"rotate(225deg)"}},children:[jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"flex-start",gap:1,children:[vd&&!Mu?jsxRuntimeExports.jsx(Box,{role:"button",tabIndex:0,"data-balloon-peek":"",onClick:Td=>{const cd=Td.target.closest("button");cd&&Td.currentTarget.contains(cd)||$u()},onKeyDown:Td=>{Td.target===Td.currentTarget&&(Td.key==="Enter"||Td.key===" ")&&(Td.preventDefault(),$u())},flex:1,minWidth:0,m:0,p:0,border:0,bg:"transparent",color:"inherit",font:"inherit",textAlign:"left",cursor:"pointer",children:jsxRuntimeExports.jsx(CurrentBalloonBody,{text:Au,tool:zu,busy:Hu,speaking:Uu,waiting:Xu,whole:od,fullText:xd,onOverflow:pd})}):wd?jsxRuntimeExports.jsx(BalloonHistory,{history:wd,onOpen:$u,onExpand:td,tool:zu,waiting:Xu,maxHeight:Vu?BALLOON_HISTORY_WITH_ATTACHMENT_MAX_HEIGHT:BALLOON_HISTORY_MAX_HEIGHT}):zu?jsxRuntimeExports.jsx(Box,{flex:1,minWidth:0,children:jsxRuntimeExports.jsx(BalloonToolCall,{line:zu})}):jsxRuntimeExports.jsx(Box,{as:"button",type:"button","data-balloon-peek":"","data-balloon-more":lo?"":void 0,onClick:$u,flex:1,minWidth:0,m:0,p:0,border:0,bg:"transparent",color:"inherit",font:"inherit",textAlign:"left",cursor:"pointer",hover:{textDecoration:"underline"},children:jsxRuntimeExports.jsx(Box,{as:"span",role:"status","aria-live":"polite",children:Au})}),ju&&!Mu?jsxRuntimeExports.jsx(IconButton,{icon:XIcon,size:"small",variant:"invisible","aria-label":nd.dismiss,"data-balloon-dismiss":"",onClick:ju,sx:{mt:"-4px",mr:"-8px",flexShrink:0}}):null]}),vd&&!Mu&&!zu&&(gd||ad||od)?jsxRuntimeExports.jsx(Box,{as:"button",type:"button","aria-expanded":od,"data-balloon-whole":od?"less":"more",onClick:()=>sd(!od),m:0,mt:1,p:0,border:0,bg:"transparent",color:"accent.fg",font:"inherit",fontSize:0,cursor:"pointer",hover:{textDecoration:"underline"},children:od?nd.showLess:nd.showMore}):null,!vd&&!wd&&Xu?jsxRuntimeExports.jsx(Box,{"data-balloon-waiting":"",mt:1,children:jsxRuntimeExports.jsx(BalloonChatItems,{items:[],waiting:!0})}):null,Mu&&jsxRuntimeExports.jsxs(Box,{"data-balloon-approval":Mu.id,mt:1,children:[jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,fontWeight:"semibold"},children:Mu.asks}),Mu.why?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,color:"fg.muted",fontSize:0},children:Mu.why}):null,jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,mt:2,children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"primary",disabled:Mu.deciding,onClick:Mu.onApprove,children:nd.approve}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:Mu.deciding,onClick:Mu.onDeny,children:nd.deny})]}),Mu.others>0?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,mt:1,color:"fg.muted",fontSize:0},children:nd.moreWaiting(Mu.others)}):null]}),yd&&Yu?jsxRuntimeExports.jsx(BalloonSuggestions,{suggestions:yd,onSuggestion:Yu}):null,Vu?jsxRuntimeExports.jsxs(Box,{"data-balloon-attachment":"",mt:2,display:"flex",flexDirection:"column",gap:1,children:[Vu,Wu?jsxRuntimeExports.jsx(BalloonExpandButton,{title:Ku??nd.theVisual,onExpand:Wu}):null]}):null,vd?null:jsxRuntimeExports.jsx(ToolLineAnnouncer,{line:zu}),Du&&jsxRuntimeExports.jsx(DecisionAsk,{ask:Du,onActiveChange:Lu})]})}const MENU_DESCRIPTION_MAX=60;function shortDescription(Au){const lo=Au.replace(/\s+/g," ").trim();if(lo.length<=MENU_DESCRIPTION_MAX)return lo;const $u=lo.slice(0,MENU_DESCRIPTION_MAX),Ru=$u.lastIndexOf(" ");return`${(Ru>MENU_DESCRIPTION_MAX/2?$u.slice(0,Ru):$u).replace(/[\s,.;:!?—-]+$/,"")}…`}function menuGroups(Au){const lo=[];for(const $u of Au){const Ru=lo.find(Iu=>Iu.group===$u.group);Ru?Ru.items.push($u):lo.push({group:$u.group,items:[$u]})}return[...lo.filter($u=>$u.group===void 0),...lo.filter($u=>$u.group!==void 0)]}function opensContextMenu(Au){return Au.key==="ContextMenu"||Au.key==="F10"&&Au.shiftKey}const LONG_PRESS_MS=550;function AssistantContextMenu({at:Au,items:lo,onClose:$u,returnFocusRef:Ru,label:Iu}){const Pu=reactExports.useRef(null),Ou=Au!==null;if(reactExports.useEffect(()=>{if(!Ou)return;const Du=()=>$u();return window.addEventListener("scroll",Du,!0),()=>window.removeEventListener("scroll",Du,!0)},[Ou,$u]),!Au||typeof document>"u")return null;const Mu=menuGroups(lo);return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[reactDomExports.createPortal(jsxRuntimeExports.jsx("div",{ref:Pu,"aria-hidden":"true","data-assistant-menu-anchor":"",style:{position:"fixed",left:Au.x,top:Au.y,width:1,height:1,pointerEvents:"none"}}),document.body),jsxRuntimeExports.jsx(ActionMenu,{open:!0,anchorRef:Pu,onOpenChange:Du=>{Du||($u(),requestAnimationFrame(()=>Ru?.current?.focus()))},children:jsxRuntimeExports.jsx(ActionMenu.Overlay,{width:"auto","data-assistant-menu":"",children:jsxRuntimeExports.jsx(ActionList,{"aria-label":Iu,children:Mu.map(({group:Du,items:Lu},Bu)=>{const ju=Lu.some(zu=>zu.checked!==void 0),Fu=Lu.map(zu=>jsxRuntimeExports.jsxs(ActionList.Item,{"data-assistant-menu-item":zu.id,disabled:zu.disabled,variant:zu.danger?"danger":"default",...ju?{selected:!!zu.checked}:{},onSelect:()=>{zu.onSelect(),$u(),requestAnimationFrame(()=>Ru?.current?.focus())},children:[zu.icon&&jsxRuntimeExports.jsx(ActionList.LeadingVisual,{children:jsxRuntimeExports.jsx(zu.icon,{})}),zu.label,zu.description&&jsxRuntimeExports.jsx(ActionList.Description,{variant:"block",children:jsxRuntimeExports.jsx("span",{title:zu.description,children:shortDescription(zu.description)})})]},zu.id));return jsxRuntimeExports.jsxs(ActionList.Group,{...ju?{selectionVariant:"single"}:{},children:[Du&&jsxRuntimeExports.jsx(ActionList.GroupHeading,{children:Du}),Fu]},Du??`ungrouped-${Bu}`)})})})})]})}const NAMES={idle:[],thinking:["Thinking","Think","CheckingSomething","Searching","Search","Uncertain"],working:["Processing","Working","Writing","Write","Searching","Search","GetTechy","CheckingSomething","Read","Reading"],waiting:["GetAttention","Alert","Suggest","LookDown","GestureDown","Acknowledge"],paused:["IdleSnooze","Sleep","Sleeping","Snooze","Rest","RestPose"],greeting:["Greeting","Greet","Show","Wave"],speaking:["Explain","Speak","Speaking","Announce","GestureRight","GestureLeft"],goodbye:["GoodBye","Goodbye","Hide","Wave"]},AUTHORED={idle:["IdlingLevel1","IdlingLevel2","IdlingLevel3"],thinking:[],working:[],waiting:["Listening"],paused:[],greeting:["Showing"],speaking:["Speaking"],goodbye:["Hiding"]},IDLE$1=/^(idle|rest ?pose)/i,STATES=["idle","thinking","working","waiting","paused","greeting","speaking","goodbye"];function stateAnimations(Au){const lo=Object.keys(Au.animations);if(lo.length===0)throw new Error(`The character ${Au.name} has no animations.`);const $u=new Map;for(const Bu of lo)$u.has(Bu.toLowerCase())||$u.set(Bu.toLowerCase(),Bu);const Ru=new Map;for(const[Bu,ju]of Object.entries(Au.authoredStates??{}))Ru.set(Bu.toLowerCase().replace(/\s+/g,""),ju);const Iu=Bu=>{const ju=[];for(const Fu of Bu){const zu=$u.get(Fu.toLowerCase());zu&&!ju.includes(zu)&&ju.push(zu)}return ju},Pu=lo.filter(Bu=>IDLE$1.test(Bu)),Ou=Iu(AUTHORED.idle.flatMap(Bu=>Ru.get(Bu.toLowerCase())??[])),Mu=[...new Set([...Pu,...Ou])],Du=Mu.length>0?Mu:[lo[0]],Lu={};for(const Bu of STATES){if(Bu==="idle"){Lu.idle=Du;continue}const ju=[...new Set([...Iu(NAMES[Bu]),...Iu(AUTHORED[Bu].flatMap(Fu=>Ru.get(Fu.toLowerCase())??[]))])];Lu[Bu]=ju.length>0?ju:Du}return Lu}function assistantStateOf(Au,lo={}){return lo.leaving?"goodbye":Au==="paused"?"paused":lo.arriving?"greeting":Au==="waiting"?"waiting":lo.speaking&&Au!=="idle"||lo.voicing?"speaking":Au}function newestIsAnswer(Au){const lo=Au[Au.length-1];return!!lo&&lo.role==="assistant"&&typeof lo.toolName!="string"}const SAYING_LIMIT=220;function plainWordsOf(Au){return(typeof Au=="string"?Au:Array.isArray(Au)?Au.map($u=>$u&&typeof $u=="object"&&$u.type==="text"?String($u.text??""):"").join(" "):"").replace(/```[\s\S]*?```/g," ").replace(/!?\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/[*_`#>]+/g,"").replace(/\s+/g," ").trim()}function markdownOf(Au){return typeof Au=="string"?Au:Array.isArray(Au)?Au.map(lo=>lo&&typeof lo=="object"&&lo.type==="text"?String(lo.text??""):"").join(`
3678
3678
 
3679
- `):""}function latestSaying(Au){for(let lo=Au.length-1;lo>=0;lo-=1){const $u=Au[lo];if($u.role!=="assistant"||typeof $u.toolName=="string")continue;const Ru=plainWordsOf($u.content);if(!Ru)continue;const Iu=markdownOf($u.content);if(Ru.length<=SAYING_LIMIT)return{id:String($u.id??lo),text:Ru,more:!1,markdown:Iu};const Pu=Ru.slice(0,SAYING_LIMIT),Ou=Pu.slice(0,Math.max(Pu.lastIndexOf(" "),SAYING_LIMIT*.6));return{id:String($u.id??lo),text:`${Ou.trimEnd()}…`,more:!0,markdown:Iu}}}function mouthOpening(Au){return Au<.08?0:Au<.3?1:Au<.6?2:3}const ASSISTANT_AWAY_KEY="datalayer-assistant-away";function keptAway(){try{if(window.localStorage.getItem(ASSISTANT_AWAY_KEY)==="always")return"always";if(window.sessionStorage.getItem(ASSISTANT_AWAY_KEY)==="session")return"session"}catch{}return"none"}function keepAway(Au){try{window.localStorage.removeItem(ASSISTANT_AWAY_KEY),window.sessionStorage.removeItem(ASSISTANT_AWAY_KEY),Au==="always"?window.localStorage.setItem(ASSISTANT_AWAY_KEY,"always"):Au==="session"&&window.sessionStorage.setItem(ASSISTANT_AWAY_KEY,"session")}catch{}}const ASSISTANT_OBSTACLES=['[role="dialog"]','[role="alertdialog"]',"dialog[open]",'[class*="prc-Overlay-Overlay"]',"[data-chat-composer]"].join(", "),POINTER_ROOM=24,POINTER_CALM_MS=1500;function boxesMeet(Au,lo,$u=0){return Au.left-$u<lo.right&&lo.left<Au.right+$u&&Au.top-$u<lo.bottom&&lo.top<Au.bottom+$u}function pointerNear(Au,lo,$u=POINTER_ROOM){return boxesMeet(Au,{left:lo.x,top:lo.y,right:lo.x,bottom:lo.y},$u)}const MOUTH_STEP_MS=110,WIDE=["wide1","wide2","wide3","wide4"],BY_OPENING={0:["closed","narrow"],1:["narrow","medium","closed"],2:["medium","narrow",...WIDE],3:[...WIDE,"medium"]};function mouthFor(Au,lo,$u=Math.random()){const Ru=Object.keys(Au?.mouths??{});if(Ru.length===0)return;if(lo===void 0)return Ru[Math.min(Ru.length-1,Math.floor($u*Ru.length))];const Iu=BY_OPENING[mouthOpening(lo)],Pu=WIDE.filter(Ou=>Ru.includes(Ou));return mouthOpening(lo)===3&&Pu.length>0?Pu[Math.min(Pu.length-1,Math.floor($u*Pu.length))]:Iu.find(Ou=>Ru.includes(Ou))??Ru[0]}function playCharacterSound(Au){const lo=new Audio(Au);Promise.resolve(lo.play()).catch($u=>{console.warn(`A sound of the character was not played: ${String($u)}`)})}function nextFrameIndex(Au,lo,$u=Math.random()){const Ru=Au.frames[lo];let Iu=$u*100;for(const Pu of Ru?.branching??[]){if(Iu<Pu.weight)return Pu.frameIndex;Iu-=Pu.weight}return lo+1<Au.frames.length?lo+1:void 0}function animationFor(Au,lo,$u=Math.random()){const Ru=stateAnimations(Au)[lo];return Ru[Math.min(Ru.length-1,Math.floor($u*Ru.length))]}const reducedMotion=()=>typeof window<"u"&&!!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;function SpriteCharacter({character:Au,state:lo,size:$u,sounds:Ru=!1,mouthLevel:Iu,playSound:Pu=playCharacterSound}){const[Ou,Mu]=reactExports.useState(()=>({name:animationFor(Au,lo),index:0}));reactExports.useEffect(()=>{Mu({name:animationFor(Au,lo),index:0})},[Au,lo]);const Du=Au.animations[Ou.name],Lu=Du?.frames[Ou.index],Bu=reactExports.useMemo(reducedMotion,[]);reactExports.useEffect(()=>{if(!Du||!Lu||Bu)return;const Ju=setTimeout(()=>{const Yu=nextFrameIndex(Du,Ou.index);Mu(Yu===void 0?{name:animationFor(Au,lo),index:0}:{name:Ou.name,index:Yu})},Math.max(Lu.duration,16));return()=>clearTimeout(Ju)},[Du,Lu,Ou,Au,lo,Bu]);const ju=Ru&&Lu?.sound!==void 0?Au.sounds?.[Lu.sound]:void 0;reactExports.useEffect(()=>{ju&&Pu(ju)},[ju,Ou,Pu]);const Fu=lo==="speaking"&&!Bu&&!!Lu?.mouths,[zu,Uu]=reactExports.useState();reactExports.useEffect(()=>{if(!Fu){Uu(void 0);return}const Ju=()=>Uu(mouthFor(Lu,Iu?.()));Ju();const Yu=setInterval(Ju,MOUTH_STEP_MS);return()=>clearInterval(Yu)},[Fu,Lu,Iu]);const Hu=Fu&&zu?Lu?.mouths?.[zu]:void 0,Vu=Hu?[Hu]:Lu?.images??[],{width:Gu,height:Wu}=Au.frameSize,Ku=$u/Math.max(Gu,Wu);return jsxRuntimeExports.jsx("span",{className:"assistant-sprite",role:"img","aria-label":Au.name,"data-sprite-animation":Ou.name,...Hu?{"data-sprite-mouth":zu}:{},style:{position:"relative",display:"block",width:$u,height:$u},children:Vu.map((Ju,Yu)=>jsxRuntimeExports.jsx("span",{"aria-hidden":!0,style:{position:"absolute",left:($u-Gu*Ku)/2,top:($u-Wu*Ku)/2,width:Gu,height:Wu,transform:`scale(${Ku})`,transformOrigin:"top left",backgroundImage:`url(${Au.sprite})`,backgroundPosition:`-${Ju.x}px -${Ju.y}px`,backgroundRepeat:"no-repeat",imageRendering:"pixelated"}},Yu))})}const MOTIONS={"@keyframes assistantFloat":{"0%, 100%":{transform:"translateY(0)"},"50%":{transform:"translateY(-3px)"}},"@keyframes assistantBlink":{"0%, 94%, 100%":{transform:"scaleY(0)"},"97%":{transform:"scaleY(1)"}},"@keyframes assistantTilt":{"0%, 100%":{transform:"rotate(-5deg)"},"50%":{transform:"rotate(-8deg) translateY(-2px)"}},"@keyframes assistantWork":{"0%, 100%":{transform:"rotate(-3deg) translateY(0)"},"50%":{transform:"rotate(3deg) translateY(-4px)"}},"@keyframes assistantAttention":{"0%, 100%":{transform:"scale(1) rotate(0)"},"20%":{transform:"scale(1.08) rotate(-6deg)"},"40%":{transform:"scale(1.08) rotate(6deg)"},"60%":{transform:"scale(1)"}},"@keyframes assistantHop":{"0%, 100%":{transform:"translateY(0)"},"30%":{transform:"translateY(-14px)"},"55%":{transform:"translateY(0)"},"75%":{transform:"translateY(-6px)"}},"@keyframes assistantTalk":{"0%, 100%":{transform:"scaleY(1)"},"50%":{transform:"scaleY(2.2)"}},"@keyframes assistantDoze":{"0%, 100%":{transform:"translateY(2px) scale(1, 0.97)"},"50%":{transform:"translateY(3px) scale(1.02, 0.95)"}},"@keyframes assistantLeave":{from:{transform:"scale(1)",opacity:1},to:{transform:"scale(0.2) translateY(20px)",opacity:0}}},BODY="& .assistant-body",AWAY_CHOICES=[{away:"page",label:"Hide for now"},{away:"session",label:"Hide for this session"},{away:"always",label:"Don’t show again"}],AgentInspectorDialog=reactExports.lazy(()=>__vitePreload(()=>import("./chunks/AgentInspectorDialog-3fbLXnLP.js"),[],import.meta.url)),AgentDetailsDialog=reactExports.lazy(()=>__vitePreload(()=>import("./chunks/AgentDetailsDialog-DmtKB_5z.js"),[],import.meta.url)),SandboxDetailsDialog=reactExports.lazy(()=>__vitePreload(()=>import("./chunks/SandboxDetailsDialog-CDSxIC0-.js"),[],import.meta.url));function assistantMenuItems(Au){const lo=[];if(Au.inspect&&lo.push({id:"inspect",label:"Inspect the agent…",icon:PulseIcon,onSelect:Au.inspect}),Au.agentDetails&&lo.push({id:"agent-details",label:"Agent Details…",icon:DependabotIcon,onSelect:Au.agentDetails}),Au.sandboxDetails&&lo.push({id:"sandbox-details",label:"Code Sandbox Details…",icon:CodeIcon,onSelect:Au.sandboxDetails}),Au.conversationLabel!==!1&&lo.push({id:"conversation",label:Au.conversationLabel??(Au.open?"Close the conversation":"Open the conversation"),icon:CommentDiscussionIcon,onSelect:Au.onToggle}),Au.busy&&Au.onStop&&lo.push({id:"stop",label:"Stop the turn",icon:SquareFillIcon,onSelect:Au.onStop}),Au.onNewChat&&lo.push({id:"new-chat",label:"New conversation",icon:PlusIcon,onSelect:Au.onNewChat}),Au.onClear&&lo.push({id:"clear",label:"Clear the conversation",icon:TrashIcon,onSelect:Au.onClear}),Au.suggestions?.length&&Au.onSuggestion){const $u=Au.onSuggestion;for(const Ru of Au.suggestions)lo.push({id:`suggestion:${Ru.label}`,label:Ru.label,description:Ru.prompt,group:"Suggestions",disabled:Au.busy,onSelect:()=>$u(Ru)})}if(Au.onBalloonDisplayChange){const $u=Au.onBalloonDisplayChange;lo.push({id:"balloon-history",label:"History",group:"Balloon",checked:Au.balloonDisplay!=="current",onSelect:()=>$u("history")},{id:"balloon-current",label:"Current",group:"Balloon",checked:Au.balloonDisplay==="current",onSelect:()=>$u("current")})}Au.onChangeCharacter&&lo.push({id:"character",label:"Change character…",icon:PencilIcon,onSelect:Au.onChangeCharacter}),Au.speech&&lo.push({id:"speech",label:Au.speech.muted?"Unmute speech":"Mute speech",icon:Au.speech.muted?UnmuteIcon:MuteIcon,onSelect:Au.speech.onToggle}),Au.characterSounds&&lo.push({id:"character-sounds",label:Au.characterSounds.on?"Mute its sounds":"Play its sounds",icon:Au.characterSounds.on?MuteIcon:UnmuteIcon,onSelect:Au.characterSounds.onToggle}),Au.onResetPosition&&lo.push({id:"reset-position",label:"Reset position",icon:ScreenNormalIcon,onSelect:Au.onResetPosition}),Au.about&&lo.push({id:"about",label:`About ${Au.name}`,icon:InfoIcon,onSelect:Au.about}),lo.push(...Au.extra??[]);for(const $u of AWAY_CHOICES)lo.push({id:`away:${$u.away}`,label:$u.label,group:"Send away",icon:XIcon,onSelect:()=>Au.onDismiss($u.away)});return lo}const BALLOON_ROOM=200;function pixels(Au){if(typeof Au=="number")return Au;const lo=typeof Au=="string"?/^(-?\d+(?:\.\d+)?)px$/.exec(Au):null;return lo?Number(lo[1]):void 0}function balloonSide(Au,lo={width:typeof window>"u"?1280:window.innerWidth,height:typeof window>"u"?800:window.innerHeight}){const $u=pixels(Au.left),Ru=pixels(Au.top),Iu=$u!==void 0?$u<lo.width/2?"left":"right":Au.left!==void 0&&Au.right===void 0?"left":"right";return{side:Ru!==void 0?Ru<BALLOON_ROOM?"below":"above":Au.top!==void 0&&Au.bottom===void 0?"below":"above",align:Iu}}const CLEAR_CHECK_MS=400;function useKeepClear(Au,lo,$u){const[Ru,Iu]=reactExports.useState(!1),[Pu,Ou]=reactExports.useState(!1);return reactExports.useEffect(()=>{if($u){Iu(!1);return}const Mu=()=>{const Lu=Au.current;if(!Lu)return;const Bu=Lu.getBoundingClientRect(),ju=lo?.current,Fu=Array.from(document.querySelectorAll(ASSISTANT_OBSTACLES)).some(zu=>{if(Lu.contains(zu)||zu.contains(Lu)||ju?.contains(zu))return!1;const Uu=zu.getBoundingClientRect();return Uu.width>0&&Uu.height>0&&boxesMeet(Bu,Uu)});Iu(Fu)};Mu();const Du=window.setInterval(Mu,CLEAR_CHECK_MS);return()=>window.clearInterval(Du)},[Au,lo,$u]),reactExports.useEffect(()=>{if($u){Ou(!1);return}let Mu,Du=!1;const Lu=Bu=>{const ju=Au.current,Fu=Bu.target;!ju||Fu&&(ju.contains(Fu)||lo?.current?.contains(Fu))||Bu.type==="pointermove"&&Bu.buttons===0&&!Du||pointerNear(ju.getBoundingClientRect(),{x:Bu.clientX,y:Bu.clientY})&&(Du=!0,Ou(!0),clearTimeout(Mu),Mu=setTimeout(()=>{Du=!1,Ou(!1)},POINTER_CALM_MS))};return document.addEventListener("pointerdown",Lu,!0),document.addEventListener("pointermove",Lu,!0),()=>{clearTimeout(Mu),document.removeEventListener("pointerdown",Lu,!0),document.removeEventListener("pointermove",Lu,!0)}},[Au,lo,$u]),Ru?"obstacle":Pu?"pointer":void 0}function useMouth(Au,lo,$u){reactExports.useEffect(()=>{const Ru=Au.current,Iu=typeof window<"u"&&!!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;if(!Ru||!lo||!$u||Iu){Ru?.removeAttribute("data-assistant-mouth");return}let Pu=0;const Ou=()=>{Ru.setAttribute("data-assistant-mouth",String(mouthOpening(lo()))),Pu=requestAnimationFrame(Ou)};return Pu=requestAnimationFrame(Ou),()=>{cancelAnimationFrame(Pu),Ru.removeAttribute("data-assistant-mouth")}},[Au,lo,$u])}function AssistantStage({character:Au,state:lo,size:$u=88,place:Ru,stageRef:Iu,onDragStart:Pu,open:Ou,onToggle:Mu,onCharacterClick:Du,onCharacterKeyDown:Lu,balloon:Bu,insist:ju=!1,onDismiss:Fu,ownRef:zu,decide:Uu,mouthLevel:Hu,stayPut:Vu=!1,balloonDisplay:Gu="history",expandTarget:Wu,expandOnArrival:Ku=!1,suggestions:Ju,onSuggestion:Yu,inspector:Xu,inspectAgent:ed,conversationLabel:td,onBalloonDisplayChange:nd,onStop:od,onNewChat:sd,onClear:ad,onChangeCharacter:pd,speech:gd,onResetPosition:xd,about:yd,sandbox:vd,contextMenu:wd,agentName:Td,label:cd}){const dd=useChatWords(),md=typeof Au=="string"?assistantCharacter(Au):"Drawing"in Au?Au:void 0,ld=md?md.name:Au.name,hd=Td??ld,bd=reactExports.useId(),Sd=!!(Td||cd),{colorScheme:kd}=useTheme(),Rd=kd?.startsWith("dark")?"dark":"light",[Od,Bd]=reactExports.useState(!1),[Ed,Ad]=reactExports.useState(!1),[$d,qd]=reactExports.useState(null),[Dd,Hd]=reactExports.useState(!1),[nh,Xd]=reactExports.useState(!1),[vh,ih]=reactExports.useState(null),xh=reactExports.useRef(null),bh=reactExports.useRef(void 0),eh=reactExports.useCallback(()=>qd(null),[]),[rh,ah]=reactExports.useState(!1),Dh=!md&&Object.keys(Au.sounds??{}).length>0;reactExports.useEffect(()=>()=>clearTimeout(bh.current),[]);const Gd=reactExports.useRef(null),zd=useKeepClear(Iu,zu,Ed||$d!==null||Dd||nh||vh!==null||Vu);useMouth(Iu,Hu,lo==="speaking");const[Id,Pd]=reactExports.useState(!1),Wd=!zd&&!Ou&&!!Bu&&(Od||ju||Id),Nd=(lo==="idle"||lo==="greeting")&&!Bu?.tool&&!Bu?.approval&&!Bu?.busy,Qd=assistantMenuItems({name:hd,open:Ou,onToggle:Mu,onDismiss:Fu,conversationLabel:td,inspect:Xu?()=>Hd(!0):void 0,agentDetails:yd?()=>ih("agent"):void 0,sandboxDetails:vd?()=>ih("sandbox"):void 0,balloonDisplay:Gu,onBalloonDisplayChange:nd,suggestions:Ju,onSuggestion:Yu,busy:lo==="thinking"||lo==="working"||lo==="speaking",onStop:od,onNewChat:sd,onClear:ad,onChangeCharacter:pd,speech:gd,characterSounds:Dh?{on:rh,onToggle:()=>ah(Fd=>!Fd)}:void 0,onResetPosition:xd,about:yd?()=>Xd(!0):void 0,extra:wd}),fh=Bu?.visual,[_h,Sh]=reactExports.useState(null),Wh=fh?()=>{Sh(fh),Wu&&requestAnimationFrame(()=>focusExpanded(Wu))}:null,Md=Bu?.history,_d=Gu!=="current"&&Md&&Md.length>0?{id:"balloon-history",title:conversationHeaderText(conversationCount(Md),dd),shrink:!0,render:()=>jsxRuntimeExports.jsx(BalloonHistoryLarge,{history:Md,tool:Bu?.tool,attachment:Bu?.attachment})}:null,Vd=_h?.id==="balloon-history"?_d:_h;return reactExports.useEffect(()=>{fh&&Ku&&Wu&&Sh(fh)},[fh?.id,Ku,!!Wu]),jsxRuntimeExports.jsxs(Box,{ref:Iu,"data-assistant-state":lo,"data-assistant-aside":zd,"data-assistant-balloon":Gu,sx:{position:"fixed",zIndex:1002,...Ru,width:$u,height:$u,opacity:zd?0:1,visibility:zd?"hidden":"visible",pointerEvents:zd?"none":void 0,transition:zd?"opacity 150ms ease, visibility 0s linear 150ms":"opacity 150ms ease",...MOTIONS,"& .assistant-lids ellipse":{transformBox:"fill-box",transformOrigin:"top",transform:"scaleY(0)",animation:"assistantBlink 5.2s ease-in-out infinite"},[BODY]:{transformBox:"fill-box",transformOrigin:"50% 100%"},"& .assistant-pupils":{transition:"transform var(--theme-motion-status, 120ms) var(--theme-motion-easing, ease)"},"& .assistant-mouth":{transformBox:"fill-box",transformOrigin:"center"},'&[data-assistant-state="idle"] .assistant-body':{animation:"assistantFloat 3.2s ease-in-out infinite"},'&[data-assistant-state="thinking"] .assistant-body':{animation:"assistantTilt 2.4s ease-in-out infinite"},'&[data-assistant-state="thinking"] .assistant-pupils':{transform:"translate(-1px, -3px)"},'&[data-assistant-state="working"] .assistant-body':{animation:"assistantWork 0.7s ease-in-out infinite"},'&[data-assistant-state="working"] .assistant-pupils':{transform:"translate(2px, 2px)"},'&[data-assistant-state="waiting"] .assistant-body':{animation:"assistantAttention 1.4s ease-in-out infinite"},'&[data-assistant-state="greeting"] .assistant-body':{animation:"assistantHop 0.9s ease-out 2"},'&[data-assistant-state="speaking"] .assistant-mouth':{animation:"assistantTalk 0.24s ease-in-out infinite"},'&[data-assistant-state="speaking"] .assistant-body':{animation:"assistantFloat 1.6s ease-in-out infinite"},"&[data-assistant-mouth] .assistant-mouth":{animation:"none",transition:"transform 60ms linear"},'&[data-assistant-mouth="0"] .assistant-mouth':{transform:"scaleY(1)"},'&[data-assistant-mouth="1"] .assistant-mouth':{transform:"scaleY(1.5)"},'&[data-assistant-mouth="2"] .assistant-mouth':{transform:"scaleY(2.1)"},'&[data-assistant-mouth="3"] .assistant-mouth':{transform:"scaleY(2.8)"},'&[data-assistant-state="paused"] .assistant-body':{animation:"assistantDoze 4.8s ease-in-out infinite",filter:"grayscale(0.5)",opacity:.8},'&[data-assistant-state="paused"] .assistant-lids ellipse':{animation:"none",transform:"scaleY(1)"},'&[data-assistant-state="goodbye"] .assistant-body':{animation:"assistantLeave 0.6s ease-in forwards"},'&[data-assistant-state="goodbye"] .assistant-sprite':{animation:"assistantLeave 0.6s ease-in forwards"},"@media (prefers-reduced-motion: reduce)":{"& *":{animation:"none !important"}}},onMouseEnter:()=>Bd(!0),onMouseLeave:()=>Bd(!1),children:[Vd&&jsxRuntimeExports.jsx(ExpandedVisual,{visual:Vd,target:Wu,onClose:()=>Sh(null)}),Wd&&Bu&&jsxRuntimeExports.jsx(BalloonExpandContext.Provider,{value:Wh,children:jsxRuntimeExports.jsx(SpeechBalloon,{text:Bu.text,more:Bu.more,approval:Bu.approval,onDismissPeek:Bu.onDismiss,display:Gu,tool:Bu.tool,speaking:Bu.speaking,busy:Bu.busy,attachment:Bu.attachment,history:Bu.history,onExpand:Wh??void 0,expandTitle:fh?.title,onExpandHistory:_d?()=>{Sh(_d),Wu&&requestAnimationFrame(()=>focusExpanded(Wu))}:void 0,suggestions:Nd?Ju:void 0,fullText:Bu.fullText,waiting:(lo==="thinking"||lo==="working"||lo==="waiting")&&!Bu.speaking,onSuggestion:Yu,decide:Uu,onDecisionActive:Pd,wide:Id,onOpen:Mu,above:$u+8,side:balloonSide(Ru).side,align:balloonSide(Ru).align,tailAt:$u/2})}),jsxRuntimeExports.jsxs(Box,{as:"button",type:"button","aria-label":cd??(Ou?`Close the conversation with ${hd}`:`Talk to ${hd}`),"aria-describedby":Sd?bd:void 0,"aria-expanded":Ou,"aria-haspopup":"menu",ref:xh,"data-assistant-figure":"",onContextMenu:Fd=>{Fd.preventDefault(),clearTimeout(bh.current),qd({x:Fd.clientX,y:Fd.clientY})},onKeyDown:Fd=>{if(opensContextMenu(Fd)){Fd.preventDefault();const uh=Fd.currentTarget.getBoundingClientRect();qd({x:uh.left+uh.width/2,y:uh.bottom});return}Lu?.(Fd)},onPointerUp:()=>clearTimeout(bh.current),onPointerCancel:()=>clearTimeout(bh.current),onPointerMove:Fd=>{const uh=Gd.current;uh&&Math.hypot(Fd.clientX-uh.x,Fd.clientY-uh.y)>8&&clearTimeout(bh.current)},onPointerDown:Fd=>{if(Gd.current={x:Fd.clientX,y:Fd.clientY},Fd.pointerType==="touch"){const uh={x:Fd.clientX,y:Fd.clientY};clearTimeout(bh.current),bh.current=setTimeout(()=>{Gd.current={x:-1e6,y:-1e6},qd(uh)},LONG_PRESS_MS)}Pu(Fd)},onClick:Fd=>{const uh=Gd.current;Gd.current=null,!(uh&&Math.hypot(Fd.clientX-uh.x,Fd.clientY-uh.y)>4)&&(Du??Mu)()},display:"block",width:$u,height:$u,p:0,border:0,bg:"transparent",cursor:"grab",filter:"drop-shadow(0 6px 10px rgba(0, 0, 0, 0.18))",active:{cursor:"grabbing"},focusVisible:{outline:"2px solid",outlineColor:"var(--focus-outlineColor, var(--fgColor-accent))",outlineOffset:2,borderRadius:"50%"},touchAction:"none",children:[Sd&&jsxRuntimeExports.jsx(Box,{as:"span",id:bd,position:"absolute",width:1,height:1,overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap",children:`Its character: ${ld}`}),md?jsxRuntimeExports.jsx(md.Drawing,{size:$u,mode:Rd}):jsxRuntimeExports.jsx(SpriteCharacter,{character:Au,state:lo,size:$u,sounds:rh,mouthLevel:Hu})]}),(Od||Ed)&&!zd&&lo!=="goodbye"&&jsxRuntimeExports.jsx(Box,{position:"absolute",top:"-6px",right:"-6px",children:jsxRuntimeExports.jsxs(ActionMenu,{open:Ed,onOpenChange:Ad,children:[jsxRuntimeExports.jsx(ActionMenu.Anchor,{children:jsxRuntimeExports.jsx(IconButton,{icon:XIcon,"aria-label":`Send ${hd} away`,size:"small",variant:"invisible","data-assistant-dismiss":"",sx:{bg:"canvas.default",borderRadius:"50%",boxShadow:"shadow.small"}})}),jsxRuntimeExports.jsx(ActionMenu.Overlay,{width:"auto",children:jsxRuntimeExports.jsx(ActionList,{children:AWAY_CHOICES.map(Fd=>jsxRuntimeExports.jsx(ActionList.Item,{"data-assistant-away":Fd.away,onSelect:()=>Fu(Fd.away),children:Fd.label},Fd.away))})})]})}),jsxRuntimeExports.jsx(AssistantContextMenu,{at:$d,items:Qd,onClose:eh,returnFocusRef:xh,label:`${hd}’s menu`}),Dd&&jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(AgentInspectorDialog,{tracer:Xu??null,agent:ed,title:`${yd?.name??hd} · Agent Inspector`,onClose:()=>{Hd(!1),xh.current?.focus()}})}),vh==="agent"&&yd&&jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(AgentDetailsDialog,{about:yd,name:hd,onClose:()=>{ih(null),xh.current?.focus()}})}),vh==="sandbox"&&vd&&jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(SandboxDetailsDialog,{sandbox:vd,name:yd?.name??hd,onClose:()=>{ih(null),xh.current?.focus()}})}),nh&&yd&&jsxRuntimeExports.jsx(Dialog$1,{title:`About ${yd.name??hd}`,onClose:()=>{Xd(!1),xh.current?.focus()},"data-assistant-about":"",children:[["Agent",yd.name],["Spec",yd.spec],["Model",yd.model],["Runs",yd.where],["Character",ld]].filter(([,Fd])=>Fd).map(([Fd,uh])=>jsxRuntimeExports.jsxs(Text$3,{as:"p",sx:{m:0,mb:1},children:[jsxRuntimeExports.jsxs(Text$3,{sx:{color:"fg.muted"},children:[Fd,": "]}),uh]},Fd))})]})}const CONVERSATION_BALLOON_WIDTH=380,CONVERSATION_BALLOON_MAX_HEIGHT=560,CONVERSATION_BALLOON_VIEWPORT_SHARE=.6,CURRENT_BALLOON_HEIGHT=230;function conversationBalloonHeight(Au){return Math.max(240,Math.min(CONVERSATION_BALLOON_MAX_HEIGHT,Math.round(Au*CONVERSATION_BALLOON_VIEWPORT_SHARE)))}const TAIL=7;function balloonTailAt(Au,lo,$u=CONVERSATION_BALLOON_WIDTH){return Math.min($u-24-TAIL,Math.max(24,Au-lo-TAIL))}function conversationBalloonSx(Au,lo="canvas.default"){return{borderRadius:"var(--theme-radius-bubble, 16px)",overflow:"visible",...Au.edge==="none"?{}:{"&::after":{content:'""',position:"absolute",...Au.edge==="bottom"?{bottom:`-${TAIL}px`}:{top:`-${TAIL}px`},left:`${Au.at}px`,width:`${TAIL*2}px`,height:`${TAIL*2}px`,bg:lo,borderRight:"1px solid",borderBottom:"1px solid",borderColor:"border.default",transform:Au.edge==="bottom"?"rotate(45deg)":"rotate(225deg)",pointerEvents:"none"}}}}function ConversationBalloonClose({name:Au,onClose:lo}){return jsxRuntimeExports.jsx(Box,{"data-conversation-balloon-close":"",position:"absolute",top:"6px",right:"6px",zIndex:30,children:jsxRuntimeExports.jsx(IconButton,{icon:XIcon,size:"small",variant:"invisible","aria-label":Au?`Close the conversation with ${Au}`:"Close the conversation",onClick:lo,sx:{bg:"canvas.default",borderRadius:"50%"}})})}function BalloonApprovalMessage({approval:Au}){const lo=useChatWords(),$u=reactExports.useRef(null);return reactExports.useEffect(()=>{$u.current?.scrollIntoView?.({block:"nearest"})},[Au.id]),jsxRuntimeExports.jsx(Box,{ref:$u,"data-balloon-approval":Au.id,px:3,py:2,display:"flex",children:jsxRuntimeExports.jsxs(Box,{maxWidth:"90%",px:3,py:2,bg:"attention.subtle",border:"1px solid",borderColor:"attention.muted",borderRadius:"var(--theme-radius-bubble, 16px)",fontSize:1,children:[jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,color:"fg.muted",fontSize:0},children:lo.waitingForYou}),jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,fontWeight:"semibold"},children:Au.asks}),Au.why?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,color:"fg.muted",fontSize:0},children:Au.why}):null,jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,mt:2,alignItems:"center",children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"primary",disabled:Au.deciding,onClick:Au.onApprove,children:lo.approve}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:Au.deciding,onClick:Au.onDeny,children:lo.deny}),Au.others>0?jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontSize:0},children:lo.moreWaiting(Au.others)}):null]})]})})}const PEEK_LIMIT=60;function peekLine(Au,lo=PEEK_LIMIT){const $u=Au.replace(/\s+/g," ").trim();if($u.length<=lo)return{text:$u,more:!1};const Ru=$u.slice(0,lo);return{text:`${Ru.slice(0,Math.max(Ru.lastIndexOf(" "),lo*.6)).trimEnd()}…`,more:!0}}const PRESENCE_LINES={idle:"Ready",thinking:"Thinking…",working:"Working…",waiting:"Waiting for you",paused:"Paused"};function presenceState(Au,lo,$u=!1){return $u?"paused":lo?.open&&lo.pendingApproval?"waiting":Au?lo?.open?"working":"thinking":"idle"}function presenceToolOf(Au){for(let lo=Au.length-1;lo>=0;lo-=1){const $u=Au[lo];if(typeof $u.toolName=="string"&&$u.toolCallId){const Ru=$u.status!=="complete"&&$u.status!=="error",Iu=Ru&&$u.result?.pending_approval===!0;return{open:Ru,pendingApproval:Iu}}}return{open:!1,pendingApproval:!1}}const LIVE=new Set(["running","idle","busy","starting"]);function sandboxIsLive(Au){return Au.status===void 0||LIVE.has(Au.status)}const NO_SANDBOX_YET="No sandbox is running yet: run a cell or ask the agent to execute code.",SANDBOX_KIND_LABELS={browser:"Python in your browser (Pyodide)",local:"Local Jupyter server",jupyter:"Jupyter server",cloud:"Datalayer cloud runtime",runtime:"In the agent runtime"};function isLocalUrl(Au){if(!Au)return!1;try{const lo=new URL(Au).hostname;return lo==="localhost"||lo==="127.0.0.1"||lo==="::1"||lo==="[::1]"||lo.endsWith(".localhost")}catch{return!1}}const SECRET_PARAMS=/^(token|access_token|api_key|apikey|key|auth|password|secret|signature|sig|jwt)$/i;function displayUrl(Au){if(Au)try{const lo=new URL(Au);lo.username="",lo.password="";for(const $u of[...lo.searchParams.keys()])SECRET_PARAMS.test($u)&&lo.searchParams.delete($u);return lo.toString()}catch{return Au.split("?")[0]}}const text$3=Au=>typeof Au=="string"&&Au?Au:void 0;function assistantSandboxOf(Au,lo={}){if(!Au)return;const $u=text$3(Au.variant),Ru=text$3(Au.jupyter_url)??text$3(Au.agent_base_url),Iu=Au.sandbox_running===!0||Au.jupyter_connected===!0;return!$u&&!Iu?void 0:{kind:$u==="datalayer"?"cloud":$u==="jupyter-server"||$u==="jupyter"?isLocalUrl(text$3(Au.jupyter_url))?"local":"jupyter":"runtime",status:lo.state??(Iu?"running":"stopped"),variant:$u,url:Ru,token:text$3(Au.jupyter_token),kernelId:text$3(Au.kernel_id),agentId:lo.agentId,environment:text$3(Au.environment_name),serverUrl:lo.serverUrl}}function sandboxExecuteOverHttp(Au,lo){const $u=Au.replace(/\/+$/,"").replace(/\/api\/v1$/,"");return async Ru=>{const Iu=await fetch(`${$u}/api/v1/sandbox/execute`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:Ru,agent_id:lo})});if(!Iu.ok)return{stdout:"",error:`The sandbox did not run the code (HTTP ${Iu.status}).`};const Pu=await Iu.json();return{stdout:Pu.stdout??"",error:Pu.error??void 0}}}function timeLeft(Au,lo=Date.now()){if(Au===null)return"never";if(Au===void 0||Au==="")return;const $u=typeof Au=="number"?Au<1e12?Au*1e3:Au:Date.parse(Au);if(!Number.isFinite($u))return;const Ru=Math.round(($u-lo)/6e4);if(Ru<=0)return"ended";const Iu=Math.floor(Ru/60);return Iu?`${Iu} h ${Ru%60} min`:`${Ru} min`}function useIsMobile(Au=640){const[lo,$u]=reactExports.useState(!1);return reactExports.useEffect(()=>{const Ru=()=>{$u(window.innerWidth<Au)};return Ru(),window.addEventListener("resize",Ru),()=>window.removeEventListener("resize",Ru)},[Au]),lo}const px=Au=>`${Math.round(Au)}px`,clamp=(Au,lo)=>Math.max(8,Math.min(Au,Math.max(8,lo)));function ChatFloating({endpoint:Au,protocol:lo,useStore:$u=!0,title:Ru="Chat",description:Iu="Start a conversation with the AI agent.",position:Pu="bottom-right",defaultOpen:Ou=!1,width:Mu=400,height:Du=550,showHeader:Lu=!0,showButton:Bu=!0,showNewChatButton:ju=!0,showClearButton:Fu=!0,showSettingsButton:zu=!1,enableKeyboardShortcuts:Uu=!0,toggleShortcut:Hu="/",showPoweredBy:Vu=!0,promptVariant:Gu,mentionableAgents:Wu,poweredByProps:Ku,clickOutsideToClose:Ju=!1,escapeToClose:Yu=!0,className:Xu,onSettingsClick:ed,onNewChat:td,onOpen:nd,onClose:od,onStateUpdate:sd,children:ad,brandIcon:pd,buttonIcon:gd,buttonTooltip:xd="Chat with AI",brandColor:yd,buttonGlow:vd=!0,offset:wd=20,animationDuration:Td=200,frontendTools:cd,initialState:dd,suggestions:md,submitOnSuggestionClick:ld=!0,hideMessagesAfterToolUI:hd=!1,defaultViewMode:bd="floating",onViewModeChange:Sd,sidebarMountPoint:kd=null,showPanelBackdrop:Rd=!1,availableModels:Od,showModelSelector:Bd=!1,showToolsMenu:Ed=!1,showSkillsMenu:Ad=!1,showTokenUsage:$d=!0,showContextRing:qd=!1,themeVariant:Dd,themeOverrides:Hd,colorMode:nh,runtimeId:Xd,historyEndpoint:vh,authToken:ih,historyAuthToken:xh,pendingPrompt:bh,showInformation:eh=!1,onInformationClick:rh,onToolCallStart:ah,onToolCallComplete:Dh,showToolApprovalBanner:Gd,pendingApprovals:zd,onApproveApproval:Id,onRejectApproval:Pd,panelProps:Wd,launching:Nd=!1,launchingMessage:Kd,assistantCharacter:Qd=DEFAULT_ASSISTANT_CHARACTER,balloonDisplay:fh=DEFAULT_BALLOON_DISPLAY,expandTarget:_h,conversation:Sh,decisions:Wh,voice:Md,inspector:_d,onBalloonDisplayChange:Vd,onChangeCharacter:Fd,about:uh,sandbox:wh,contextMenu:Eh}){const kh=useChatWords(),Ph=reactExports.useRef(null),[Fh,Uh]=reactExports.useState(),[Jh,Oh]=reactExports.useState(!1),[np,ap]=reactExports.useState();reactExports.useEffect(()=>ap(void 0),[fh]);const hp=np??fh,bp=reactExports.useCallback(Bh=>{ap(Bh),Vd?.(Bh)},[Vd]),Qh=useChatOpen(),_p=useChatMessages(),lp=useChatStore(Bh=>Bh.setOpen),up=useChatStore(Bh=>Bh.clearMessages),[Hh,zh]=reactExports.useState(Ou),Xh=$u?Qh:Hh,Uf=$u?lp:zh,$p=_p,Rh=reactExports.useRef(null),jh=useIsMobile(),[af,qp]=reactExports.useState(!1),[lf,Xp]=reactExports.useState(!1),[tp,Vp]=reactExports.useState(bd),[$f,cm]=reactExports.useState(0),[Hf,qf]=reactExports.useState(!1),[Qp,fp]=reactExports.useState(null),jp=tp==="panel"?"sidebar":tp,[Sp,Bp]=reactExports.useState(null);reactExports.useLayoutEffect(()=>{Bp(resolveMountPoint(kd))},[kd,Xh,tp]);const Of=disabledChatViewModes({sidebarMountPoint:Sp,viewMode:jp}),ef=Of.includes("sidebar"),cf=tp==="panel"&&!jh&&!!Sp,yp=useViewportDrag(Rh),Jf=yp.reset;reactExports.useEffect(()=>{tp!=="floating-draggable"&&Jf()},[tp,Jf]);const vf=88,vm=tp==="assistant"&&!jh,[Mf,Fm]=reactExports.useState(!1),[uf,Am]=reactExports.useState({open:!1,pendingApproval:!1}),[Cm,Vf]=reactExports.useState(!1),[Lh,Ud]=reactExports.useState(),[lh,Mh]=reactExports.useState(0),[Nh,mp]=reactExports.useState([]),[$h,ep]=reactExports.useState([]),[Fp]=useVoiceSettings(),Sf=reactExports.useMemo(()=>Md?settledVoice(Md,Fp):void 0,[Md,Fp]),{speaker:Ip,state:zp,stop:Yp,read:um,level:nm}=useVoiceSpeaker(Sf);useSpokenAnswers($h,Mf,!!Ip&&Sf?.output==="always"&&!Jh,Ip);const[bf,$m]=reactExports.useState(!1),[Rm,r0]=reactExports.useState(!1),[bm,Cf]=reactExports.useState(keptAway),dm=vm&&bm==="none",Df=reactExports.useCallback(()=>{keepAway("none"),Cf("none")},[]),[Kp,Rf]=reactExports.useState(),xp=Sh?Sh.saying:Kp,If=Sh?Sh.answering:Cm,Nf=Sh?Sh.tool:Lh,Vh=hp==="current",[Up,tf]=reactExports.useState(),[Tf,Lf]=reactExports.useState(!1);reactExports.useEffect(()=>{if(!xp||Xh)return;Lf(!0);const Bh=setTimeout(()=>Lf(!1),12e3);return()=>clearTimeout(Bh)},[xp?.id,xp?.text,Xh]),reactExports.useEffect(()=>{Xh&&xp&&tf(xp.id)},[Xh,xp?.id]);const hm=reactExports.useRef(null),Xf=useViewportDrag(hm,{whole:!0});reactExports.useEffect(()=>{if(!dm)return;$m(!0);const Bh=setTimeout(()=>$m(!1),1800);return()=>clearTimeout(Bh)},[dm]);const kp=assistantStateOf(Sh?Sh.presence:presenceState(Mf,uf),{arriving:bf,leaving:Rm,speaking:If,voicing:zp.speaking}),Gf=!!xp&&xp.id!==Up,[Tm,df]=reactExports.useState(!1),Zh=zd?.[0],Hp=Zh&&Id&&Pd?{id:Zh.id,asks:Zh.toolDescription||Zh.toolName,others:(zd?.length??1)-1,deciding:Tm,onApprove:()=>{df(!0),Promise.resolve(Id(Zh.id)).finally(()=>df(!1))},onDeny:()=>{df(!0),Promise.resolve(Pd(Zh.id)).finally(()=>df(!1))}}:void 0,Pf=reactExports.useMemo(()=>Wh?.serverUrl?decisionsAskerAt(Wh.serverUrl,Wh.token):void 0,[Wh?.serverUrl,Wh?.token]),rf=kp==="thinking"||kp==="working"||kp==="speaking",hf=Nf&&(Nf.phase==="running"||rf)?Nf:void 0,x0=rf&&!If?kh.thinking:(xp?.more?xp.text:xp?.markdown)||void 0,zm=rf&&!If?void 0:xp?.more?xp.markdown:void 0,Um=!Vh&&!Sh&&Nh.length>0?Nh:void 0,pm=Bh=>Um?{...Bh,history:Um}:Bh,kg=kp==="paused"?{text:kh.paused}:zp.sentence?{text:zp.sentence}:zp.refused?{text:zp.refused}:Hp?pm({text:kh.waitingForYou,approval:Hp}):kp==="waiting"?{text:kh.waitingOpen}:hf?pm({text:toolLineText(hf,kh),tool:hf,busy:rf}):Vh&&(Gf||rf)?{text:x0??Iu,fullText:zm,more:xp?.more,speaking:If&&rf,busy:rf,onDismiss:xp?()=>{tf(xp.id),Lf(!1)}:void 0}:pm(Gf&&xp?{...peekLine(xp.text),onDismiss:()=>{tf(xp.id),Lf(!1)}}:{text:Iu}),Q0=!!zp.sentence||kp==="greeting"||kp==="waiting"||!!Hp||!!hf||Vh&&rf||Gf&&(kp==="speaking"||Tf),Wv=reactExports.useMemo(()=>Sh||!md?.length?void 0:md.map(Bh=>({label:Bh.title,prompt:Bh.message})),[Sh,md]),Qg=reactExports.useCallback(Bh=>{Ph.current?Ph.current.send(Bh.prompt):Uh(Bh.prompt)},[]),e1=Wd?.onSendReady,eg=reactExports.useCallback(Bh=>{Ph.current=Bh,e1?.(Bh)},[e1]),h0=Wd?.onLoadingChange,t1=Wd?.onDisplayItemsChange,r1=reactExports.useCallback(Bh=>{Fm(Bh),h0?.(Bh)},[h0]),ip=reactExports.useCallback(Bh=>{const wp=presenceToolOf(Bh);Am(Jp=>Jp.open===wp.open&&Jp.pendingApproval===wp.pendingApproval?Jp:wp),Vf(newestIsAnswer(Bh));const pf=newestToolLine(Bh);Ud(Jp=>Jp?.id===pf?.id&&Jp?.phase===pf?.phase?Jp:pf),Mh(conversationCount(Bh)),mp(Bh),ep(Bh);const _m=latestSaying(Bh);Rf(Jp=>Jp?.id===_m?.id&&Jp?.text===_m?.text?Jp:_m),t1?.(Bh)},[t1]),C1=reactExports.useCallback(Bh=>{if(!(Bh==="sidebar"&&ef))if(Bh==="sidebar"){if(Sd){Sd(Bh);return}Vp("panel"),cm(wp=>wp+1)}else Bh==="assistant"&&Df(),Vp(Bh),cm(wp=>wp+1),Sd?.(Bh)},[Sd,ef,Df]);reactExports.useLayoutEffect(()=>{if(tp!=="panel"||jh){qf(!1);return}if(Sp){qf(!0);return}const Bh=Rh.current?.parentElement;if(!Bh){qf(!1);return}const wp=window.getComputedStyle(Bh),pf=wp.display.includes("flex")&&(wp.flexDirection==="row"||wp.flexDirection==="row-reverse"),_m=wp.display.includes("grid");qf(pf||_m)},[tp,jh,Xh,Sp]);const Ag=typeof Mu=="number"?Mu:typeof Mu=="string"&&Number.parseInt(Mu,10)||420;reactExports.useLayoutEffect(()=>{if(jh||tp!=="panel"||Hf||!Xh){fp(null);return}const Bh=Rh.current?.parentElement;if(!Bh){fp(null);return}const wp=Bh.style.paddingRight,pf=Bh.style.boxSizing,_m=window.getComputedStyle(Bh).paddingRight;Bh.style.boxSizing="border-box",Bh.style.paddingRight=`calc(${_m} + ${Ag}px)`;const Jp=()=>{const w0=Bh.getBoundingClientRect();fp(fm=>{const E0=w0.height<1?{top:0,height:window.innerHeight,right:0}:{top:w0.top,height:w0.height,right:Math.max(0,window.innerWidth-w0.right)};return fm&&Math.abs(fm.top-E0.top)<1&&Math.abs(fm.height-E0.height)<1&&Math.abs(fm.right-E0.right)<1?fm:E0})};Jp(),window.addEventListener("resize",Jp),window.addEventListener("scroll",Jp,!0);const Om=new ResizeObserver(Jp);return Om.observe(Bh),()=>{window.removeEventListener("resize",Jp),window.removeEventListener("scroll",Jp,!0),Om.disconnect(),Bh.style.paddingRight=wp,Bh.style.boxSizing=pf}},[jh,tp,Hf,Xh,Ag]);const ym=reactExports.useMemo(()=>{if(lo&&typeof lo=="object")return lo;if(!Au)return;const Bh=typeof lo=="string"?lo:void 0,wp=Au.match(/^(.*?)\/api\/v1\//)?.[1]||Au.match(/^(https?:\/\/[^/]+)/)?.[1]||"",pf=Au.match(/\/api\/v1\/(ag-ui|vercel-ai|a2a|acp)\//),_m=Bh??pf?.[1]??"vercel-ai",Jp=Au.match(/\/api\/v1\/(?:ag-ui|vercel-ai|a2a\/agents|acp\/ws)\/([^/]+)/),Om=Jp?Jp[1]:void 0;return{type:_m,endpoint:Au,agentId:Om,authToken:ih,enableConfigQuery:Bd||Ed||Ad||$d,configEndpoint:Bd||Ed||Ad||$d?`${wp}/api/v1/configure`:void 0}},[lo,Au,ih,Bd,Ed,Ad,$d]),j0=Au?.match(/^(.*?)\/api\/v1\//)?.[1],wf=reactExports.useMemo(()=>uh||ym?.agentId?{name:Ru,protocol:ym?.type,url:ym?.endpoint,agentId:ym?.agentId,apiBase:j0,...uh}:void 0,[uh,ym,Ru,j0]),Rp=useAgentRuntimeCodemodeStatus(),p0=reactExports.useMemo(()=>wh??assistantSandboxOf(Rp?.sandbox,{agentId:ym?.agentId,serverUrl:j0})??(ym?.agentId&&j0?{kind:"runtime",status:"not running",agentId:ym.agentId,serverUrl:j0}:void 0),[wh,Rp,ym?.agentId,j0]);reactExports.useEffect(()=>{up()},[Au,lo]),reactExports.useEffect(()=>{Uf(Ou)},[]);const om=reactExports.useCallback(()=>{const Bh=!Xh;qp(!0),Bh?(Uf(Bh),nd?.()):setTimeout(()=>{Uf(Bh),od?.(),qp(!1)},Td),setTimeout(()=>qp(!1),Td)},[Xh,Uf,nd,od,Td]),sv=reactExports.useCallback(Bh=>{Xh&&om(),keepAway(Bh),r0(!0),setTimeout(()=>{r0(!1),Cf(Bh)},600)},[Xh,om]),tg=typeof window>"u"?1280:window.innerWidth,im=typeof window>"u"?800:window.innerHeight,Im=conversationBalloonHeight(im),n1=Vh&&!Sh,rg=n1?CURRENT_BALLOON_HEIGHT:Im,o1=()=>{const Bh=CONVERSATION_BALLOON_WIDTH,wp=rg;if(Xf.position){const{left:fm,top:E0}=Xf.position,T1=fm+vf/2<tg/2,Vm=E0-wp-16,Wf=E0+vf+16,Cp=Vm<8&&Wf+wp>im-8,Gm=Cp?T1?fm+vf+16:fm-Bh-16:T1?fm:fm+vf-Bh,C0=Cp?E0+vf-wp:Vm>=8?Vm:Wf,F0=clamp(Gm,tg-Bh-8);return{place:{left:px(F0),top:px(clamp(C0,im-wp-8)),right:"auto",bottom:"auto"},tail:Cp?{edge:"none"}:{edge:Vm>=8?"bottom":"top",at:balloonTailAt(fm+vf/2,F0)}}}const pf=Pu.endsWith("right"),_m=pf?tg-wd-vf/2:wd+vf/2,Jp=pf?tg-wd-Bh:wd,Om={edge:Pu.startsWith("bottom")?"bottom":"top",at:balloonTailAt(_m,Jp)},w0=sm();return{place:Pu.startsWith("bottom")?{...w0,bottom:px(wd+vf+16)}:{...w0,top:px(wd+vf+16)},tail:Om}},Hm=reactExports.useCallback(()=>{$u&&up(),td?.()},[$u,up,td]),ng=reactExports.useCallback(()=>{window.confirm("Clear all messages?")&&$u&&up()},[$u,up]);useChatKeyboardShortcuts({onToggle:Uu?om:void 0,onNewChat:Uu?Hm:void 0,onClear:Uu&&$p.length>0?ng:void 0,enabled:Uu}),reactExports.useEffect(()=>{if(!Yu||!Xh)return;const Bh=wp=>{wp.key==="Escape"&&om()};return document.addEventListener("keydown",Bh),()=>document.removeEventListener("keydown",Bh)},[Yu,Xh,om]);const Pm=!!Sh;reactExports.useEffect(()=>{if(!Pm||!Xh)return;const Bh=setTimeout(()=>{Rh.current?.querySelector('[data-chat-composer] textarea, [data-chat-composer] [contenteditable="true"], textarea')?.focus()},Td);return()=>clearTimeout(Bh)},[Pm,Xh,Td,$f]),reactExports.useEffect(()=>{if(!dm||!Xh)return;const Bh=setTimeout(()=>{const wp=Rh.current?.querySelector("[data-chat-history]");wp?.scrollTo?.({top:wp.scrollHeight})},Td);return()=>clearTimeout(Bh)},[dm,Xh,Td]),reactExports.useEffect(()=>{if(!Ju||!Xh)return;const Bh=pf=>{Rh.current&&!Rh.current.contains(pf.target)&&om()},wp=setTimeout(()=>{document.addEventListener("mousedown",Bh)},100);return()=>{clearTimeout(wp),document.removeEventListener("mousedown",Bh)}},[Ju,Xh,om]),reactExports.useEffect(()=>{if(jh&&Xh)return document.body.style.overflow="hidden",document.body.style.position="fixed",document.body.style.width="100%",document.body.style.touchAction="none",()=>{document.body.style.overflow="",document.body.style.position="",document.body.style.width="",document.body.style.touchAction=""}},[jh,Xh]);const sm=()=>{const Bh={position:"fixed",zIndex:1e3};switch(Pu){case"bottom-right":Bh.bottom=wd,Bh.right=wd;break;case"bottom-left":Bh.bottom=wd,Bh.left=wd;break;case"top-right":Bh.top=wd,Bh.right=wd;break;case"top-left":Bh.top=wd,Bh.left=wd;break}return Bh},og=Bh=>{if(Bh)return"scale(1) translateY(0)";switch(Pu){case"bottom-right":case"bottom-left":return"scale(0.95) translateY(20px)";case"top-right":case"top-left":return"scale(0.95) translateY(-20px)";default:return"scale(0.95)"}},i1=Uu?getShortcutDisplay({key:Hu}):void 0,_f=dm?o1():void 0,qm=jh?"100%":_f?CONVERSATION_BALLOON_WIDTH:Mu,S0=jh?"100%":_f?rg:Du,n0=jh?{position:"fixed",top:0,left:0,right:0,bottom:0,width:"100%",height:"100%",borderRadius:0}:{},f0=jsxRuntimeExports.jsx(Tooltip,{text:`Close${Yu?" (Esc)":""}`,direction:"s",children:jsxRuntimeExports.jsx(IconButton,{icon:XIcon,"aria-label":"Close",onClick:om,variant:"invisible",size:"small"})}),s1=_f?{showHeader:!1,showPoweredBy:!1,promptVariant:"lexical",showModelSelector:!1,showToolsMenu:!1,showSkillsMenu:!1,showTokenUsage:!1,showContextRing:!1,showInformation:!1,showToolApprovalBanner:!1,showAgentsMenu:!1,showTurnFooter:!1,compact:!0,welcome:Iu,backgroundColor:"canvas.default",borderRadius:"var(--theme-radius-bubble, 16px)",trailingContent:Hp?jsxRuntimeExports.jsx(BalloonApprovalMessage,{approval:Hp}):void 0,footerContent:Pf?jsxRuntimeExports.jsx(Box,{"data-balloon-decisions":"",px:3,pb:1,display:"flex",flexDirection:"column",alignItems:"flex-end",fontSize:0,sx:{"& form":{alignSelf:"stretch"},'& [data-balloon-decision="answered"]':{alignSelf:"stretch"}},children:jsxRuntimeExports.jsx(DecisionAsk,{ask:Pf})}):void 0}:void 0,m0=jsxRuntimeExports.jsxs(Box,{ref:Rh,className:Xu,sx:{position:tp==="panel"&&!jh&&(Hf||cf)?"relative":"fixed",...tp==="floating"&&!jh?{top:0,right:0,bottom:0,left:"auto"}:{},...tp==="floating-small"&&!jh?sm():{},...tp==="floating-draggable"&&!jh?yp.position?{left:px(yp.position.left),top:px(yp.position.top),right:"auto",bottom:"auto"}:sm():{},..._f?_f.place:vm&&!jh?sm():{},...tp==="panel"&&!jh?{...Hf||cf?{top:"auto",right:"auto",bottom:"auto",left:"auto",marginLeft:"auto",alignSelf:"stretch"}:{top:Qp?`${Qp.top}px`:0,right:Qp?`${Qp.right}px`:0,bottom:Qp?"auto":0,left:"auto"}}:{},width:tp==="panel"&&!jh?Xh||af?`${Ag}px`:"0px":tp==="floating"&&!jh?typeof qm=="number"?`${qm}px`:qm:(tp==="floating-small"||tp==="floating-draggable"||tp==="assistant")&&!jh?typeof qm=="number"?`${qm}px`:qm:jh?"100%":typeof qm=="number"?`${qm}px`:qm,height:tp==="panel"&&!jh?Hf||cf?"100%":Qp?`${Qp.height}px`:"100%":tp==="floating"&&!jh?"100%":(tp==="floating-small"||tp==="floating-draggable"||tp==="assistant")&&!jh?typeof S0=="number"?`${S0}px`:S0:jh?"100%":typeof S0=="number"?`${S0}px`:S0,display:"flex",flexDirection:"column",bg:"canvas.default",border:"1px solid",borderColor:"border.default",borderRadius:tp==="panel"||jh?0:vm?"var(--theme-radius-bubble, 16px)":"12px",boxShadow:tp==="panel"?"shadow.none":"shadow.extra-large",overflow:"hidden",transform:tp==="panel"?Xh?"translateX(0)":"translateX(100%)":og(Xh),opacity:tp==="panel"||Xh?1:0,transition:`transform ${Td}ms ease, opacity ${Td}ms ease, width ${Td}ms ease`,zIndex:tp==="panel"&&!jh&&(Hf||cf)?"auto":1001,visibility:Xh||af?"visible":"hidden",pointerEvents:Xh?"auto":"none",...n0,..._f?conversationBalloonSx(_f.tail,_f.tail.edge==="bottom"?"canvas.subtle":"canvas.default"):{}},"data-conversation-balloon":_f?"":void 0,"data-balloon-display":_f?hp:void 0,children:[_f?jsxRuntimeExports.jsx(ConversationBalloonClose,{onClose:om}):null,_f&&!n1?jsxRuntimeExports.jsx(ConversationBalloonHeader,{count:lh}):null,tp==="floating-draggable"&&!jh&&jsxRuntimeExports.jsx(Box,{onPointerDown:yp.onHandlePointerDown,"aria-label":"Move the chat",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,height:18,cursor:"grab",color:"fg.subtle",bg:"canvas.subtle",borderBottom:"1px solid",borderColor:"border.muted",active:{cursor:"grabbing"},touchAction:"none",children:jsxRuntimeExports.jsx(GrabberIcon,{size:16})}),Sh?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Lu&&!_f?jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,flexShrink:0,px:3,py:2,borderBottom:"1px solid",borderColor:"border.default",children:[pd||jsxRuntimeExports.jsx(ForwardRef$2,{colored:!0,size:20}),jsxRuntimeExports.jsx(Text$3,{sx:{flex:1,minWidth:0,fontWeight:"semibold",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Ru}),f0]}):null,jsxRuntimeExports.jsx(Box,{"data-floating-conversation":!0,flex:"1 1 auto",minHeight:0,display:"flex",borderRadius:_f?"bubble":void 0,overflow:_f?"hidden":void 0,children:Sh.body})]}):jsxRuntimeExports.jsx(ChatBase,{title:Ru,showHeader:Lu,useStore:$u,protocol:ym,themeVariant:Dd,themeOverrides:Hd,colorMode:nh,autoFocus:Xh,focusTrigger:$f,launching:Nd,launchingMessage:Kd,brandIcon:pd||jsxRuntimeExports.jsx(ForwardRef$2,{colored:!0,size:20}),headerButtons:{showNewChat:ju,showClear:Fu&&$p.length>0,showSettings:zu&&!!ed,onNewChat:Hm,onClear:ng,onSettings:ed},headerActions:jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:f0}),chatViewMode:jp,onChatViewModeChange:C1,disabledViewModes:Of,showPoweredBy:Vu,promptVariant:Gu,mentionableAgents:Wu,poweredByProps:{brandName:"Datalayer",brandUrl:"https://datalayer.ai",...Ku},description:Iu,onStateUpdate:sd,onNewChat:td,suggestions:md,submitOnSuggestionClick:ld,hideMessagesAfterToolUI:hd,avatarConfig:{showAvatars:!0},placeholder:"Type a message...",backgroundColor:"canvas.subtle",frontendTools:cd,showModelSelector:Bd,availableModels:Od,showToolsMenu:Ed,showSkillsMenu:Ad,showTokenUsage:$d,showContextRing:qd,runtimeId:Xd,historyEndpoint:vh,historyAuthToken:xh,pendingPrompt:bh??Fh,inspector:_d,showInformation:eh,onInformationClick:rh,onToolCallStart:ah,onToolCallComplete:Dh,showToolApprovalBanner:Gd,pendingApprovals:zd,onApproveApproval:Id,onRejectApproval:Pd,voice:Md,voiceSpeaking:zp.speaking,onStopSpeaking:Ip?Yp:void 0,onReadAloud:Ip?um:void 0,...Wd,...s1,onLoadingChange:r1,onDisplayItemsChange:ip,onSendReady:eg,children:_f&&n1?jsxRuntimeExports.jsx(Box,{px:3,pt:3,pb:2,overflow:"hidden",children:jsxRuntimeExports.jsx(CurrentBalloonBody,{text:hf?void 0:x0??Iu,fullText:hf?void 0:zm,tool:hf,busy:rf,speaking:If&&rf,waiting:rf&&!If})}):ad})]}),a1=jsxRuntimeExports.jsx(IconButton,{icon:gd||CommentDiscussionIcon,"aria-label":xd,unsafeDisableTooltip:!!xp,onClick:vm&&bm==="page"?Df:om,size:"large",sx:{width:56,height:56,borderRadius:"50%",bg:yd||"accent.emphasis",color:"fg.onEmphasis",boxShadow:"shadow.large",transition:"transform 0.2s ease, box-shadow 0.2s ease",transform:lf?"scale(1.1)":"scale(1)",...Gf?{animation:"chatFloatingBlink 1.1s ease-in-out infinite","@keyframes chatFloatingBlink":{"0%, 100%":{filter:"brightness(1)",boxShadow:"0 0 0 0 rgba(0,0,0,0)"},"50%":{filter:"brightness(1.25)",boxShadow:"0 0 0 6px var(--bgColor-accent-muted, rgba(84,174,255,0.4))"}},"@media (prefers-reduced-motion: reduce)":{animation:"none"}}:{},"&:hover":{bg:yd||"accent.emphasis",boxShadow:"shadow.extra-large"}}});return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[dm&&jsxRuntimeExports.jsx(AssistantStage,{character:Qd,state:kp,size:vf,place:Xf.position?{left:px(Xf.position.left),top:px(Xf.position.top)}:sm(),stageRef:hm,onDragStart:Xf.onHandlePointerDown,open:Xh,onToggle:om,balloon:kg,balloonDisplay:hp,expandTarget:_h,insist:Q0,onDismiss:sv,ownRef:Rh,mouthLevel:nm,suggestions:Wv,onSuggestion:Qg,inspector:_d,onBalloonDisplayChange:bp,onStop:Mf&&Ph.current?()=>Ph.current?.stop():void 0,onNewChat:!Sh&&ju?Hm:void 0,onClear:!Sh&&$u?ng:void 0,onChangeCharacter:Fd,speech:Ip&&Sf?.output==="always"?{muted:Jh,onToggle:()=>{Jh||Ip.stop(),Oh(!Jh)}}:void 0,onResetPosition:Xf.position?Xf.reset:void 0,about:wf,sandbox:p0,contextMenu:Eh}),Bu&&!Xh&&!dm&&jsxRuntimeExports.jsx(Box,{sx:{...sm()},children:jsxRuntimeExports.jsxs(Box,{position:"relative",display:"inline-flex",isolation:"isolate",onMouseEnter:()=>Xp(!0),onMouseLeave:()=>Xp(!1),children:[vd&&jsxRuntimeExports.jsx(ButtonGlow,{color:yd}),lf&&xp?jsxRuntimeExports.jsx(SpeechBalloon,{text:xp.text,more:xp.more,onOpen:om,above:64,side:Pu.startsWith("bottom")?"above":"below",align:Pu.includes("right")?"right":"left",tailAt:28}):null,xp?a1:jsxRuntimeExports.jsx(Tooltip,{text:`${xd}${i1?` (${i1})`:""}`,direction:Pu.includes("right")?"w":"e",children:a1}),$p.length>0&&jsxRuntimeExports.jsx(Box,{position:"absolute",top:0,right:0,minWidth:18,height:18,px:1,display:"flex",alignItems:"center",justifyContent:"center",bg:"danger.emphasis",color:"fg.onEmphasis",borderRadius:"50%",fontSize:0,fontWeight:"bold",pointerEvents:"none",children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0},children:$p.length>99?"99+":$p.length})}),Gf&&jsxRuntimeExports.jsx(Box,{position:"absolute",top:0,left:0,right:0,bottom:0,borderRadius:"50%",border:"2px solid",borderColor:yd||"accent.emphasis",animation:"pulse 2s infinite",pointerEvents:"none",reducedMotion:{animation:"none",transform:"scale(1.15)",opacity:.6},sx:{"@keyframes pulse":{"0%":{transform:"scale(1)",opacity:1},"100%":{transform:"scale(1.5)",opacity:0}}}})]})}),jh&&Xh&&jsxRuntimeExports.jsx(Box,{position:"fixed",top:0,left:0,right:0,bottom:0,bg:"neutral.muted",opacity:.5,zIndex:999,onClick:om}),Rd&&tp==="panel"&&Xh&&!jh&&jsxRuntimeExports.jsx(Box,{position:"fixed",top:0,left:0,right:0,bottom:0,bg:"neutral.muted",opacity:.3,zIndex:1e3,onClick:om}),cf&&Sp?reactDomExports.createPortal(m0,Sp):m0]})}const LoopCanvasBlock=defineContributionPoint("loop.canvas.block"),LoopA2uiComponent=defineContributionPoint("loop.a2ui.component"),LoopAppFiles=defineContributionPoint("loop.app.files"),listeners$2=new Set;function requestSurface(Au){if(listeners$2.size===0)return!1;for(const lo of[...listeners$2])lo(Au);return!0}function onSurfaceRequest(Au){return listeners$2.add(Au),()=>{listeners$2.delete(Au)}}const listeners$1=new Set;function focusPrompt(){if(listeners$1.size===0)return!1;for(const Au of[...listeners$1])Au();return!0}function onPromptFocusRequest(Au){return listeners$1.add(Au),()=>{listeners$1.delete(Au)}}function agentServerOf(Au,lo){return Au.target==="datalayer"?Au.agentBaseUrl||void 0:Au.agentBaseUrl||lo}function noRuntimeSaid(Au,lo){return Au.state==="error"?lo.noRuntime(Au.errorReason??""):lo.runtimeStarting}const IDLE_SANDBOX_SNAPSHOT=Object.freeze({state:"idle"}),IDLE_SANDBOX_SNAPSHOT_SIGNAL={value:IDLE_SANDBOX_SNAPSHOT,peek:()=>IDLE_SANDBOX_SNAPSHOT},IDLE_SANDBOX_TARGET_SIGNAL={value:void 0,peek:()=>{}};function loopSurfaceId(Au){return`loop-${Au||"default"}`}function createPromptChannel(){const Au=new Set,lo=[];return{submit($u){if(Au.size===0)return lo.push($u),!0;for(const Ru of[...Au])Ru($u);return!0},subscribe($u){if(Au.add($u),lo.length>0){const Ru=lo.splice(0,lo.length);queueMicrotask(()=>{for(const Iu of Ru)$u(Iu)})}return()=>{Au.delete($u)}}}}const LoopViewType=defineContributionPoint("loop.viewType"),LoopEditorView=defineContributionPoint("loop.chat.surface"),LoopChatSurface=LoopEditorView,LoopFrontendTool=defineContributionPoint("loop.frontendTool"),LoopChatComposer=defineContributionPoint("loop.chat.composer"),LoopChatHeader=defineContributionPoint("loop.chat.header"),LoopAgentBlueprint=defineContributionPoint("loop.agent.blueprint"),LoopChatSuggestion=defineContributionPoint("loop.chat.suggestion"),LoopAssistantCharacter=defineContributionPoint("loop.assistant.character");defineContributionPoint("loop.assistant.menu");async function sendInstead(Au,lo){if(!Au.sendInstead)return null;try{return await Au.sendInstead.send(lo),{sent:!0}}catch($u){return{sent:!1,refused:$u instanceof Error?$u.message:String($u)}}}const LoopChatExtras=defineContributionPoint("loop.chat.extras"),LoopOpeningNotebook=defineContributionPoint("loop.notebook.opening"),LoopOpeningDocument=defineContributionPoint("loop.document.opening"),LoopAgentGate=defineGate("loop.agent.available"),LoopNotebookToolbar=defineContributionPoint("loop.notebook.toolbar"),LoopNotebookToolbarItem=defineContributionPoint("loop.notebook.toolbar.item"),LoopDocumentToolbar=defineContributionPoint("loop.document.toolbar"),LoopDocumentToolbarItem=defineContributionPoint("loop.document.toolbar.item"),LoopCommand=defineContributionPoint("loop.command"),LoopRunProps=defineContributionPoint("loop.runProps");function runForwardedProps(Au,lo){let $u;for(const Ru of[...Au.map(Iu=>Iu.props()),lo]){if(!Ru)continue;const Iu={...$u?.loop??{},...Ru.loop??{}};$u={...$u,...Ru},Object.keys(Iu).length>0&&($u.loop=Iu)}return $u}defineContributionPoint("loop.mention");const LoopSlots={header:"loop.header",chatHeader:"loop.chatHeader",promptAction:"loop.promptAction",inpromptMenu:"loop.inpromptMenu",footer:"loop.footer",status:"loop.status",root:"root",sidebar:"loop.sidebar"};function sandboxIndicatorState(Au,lo,$u){return Au==="error"?"connected-dead":Au==="starting"?"connected-starting":Au==="stopping"?"disconnecting":Au!=="running"?"disconnected":lo==="busy"||$u?"connected-busy":"connected-idle"}function canOpenView(Au,lo){return Au.canOpen?Au.canOpen(lo):!0}function parseCommand(Au){const lo=Au.trimStart();if(!lo.startsWith("/"))return;const[$u,...Ru]=lo.slice(1).split(/\s+/);if($u)return{name:$u.toLowerCase(),argv:Ru.join(" ").trim()}}const LoopChatLayout=defineContributionPoint("loop.chat.layout"),LoopPromptPanel=defineContributionPoint("loop.prompt.panel"),LoopChatTurn=defineContributionPoint("loop.chat.turn");function defineAgentCapacityPlugin(Au){const{key:lo,displayName:$u,description:Ru,specId:Iu,octicon:Pu,emoji:Ou,codemode:Mu,createPayload:Du,suggestions:Lu,instructions:Bu,model:ju,modeEffect:Fu,name:zu,requiredBackendPlugins:Uu}=Au;return{name:zu??`@datalayer/loop-plugin-agent-${lo}`,...Uu?{requiredBackendPlugins:Uu}:{},displayName:$u,description:Ru,octicon:Pu??"dependabot",emoji:Ou,contributes:[contribution(LoopAgentBlueprint,{id:lo,specId:Iu,createPayload:{description:Ru,agent_library:"pydantic-ai",enable_codemode:Mu??!1,...Du},...Bu?{instructions:Bu}:{},...ju?{model:ju}:{},...Fu?{modeEffect:Fu}:{}},{id:lo}),...Lu&&Lu.length>0?[contribution(LoopChatSuggestion,{id:lo,suggestions:Lu},{id:lo})]:[]]}}var util;(function(Au){Au.assertEqual=Iu=>{};function lo(Iu){}Au.assertIs=lo;function $u(Iu){throw new Error}Au.assertNever=$u,Au.arrayToEnum=Iu=>{const Pu={};for(const Ou of Iu)Pu[Ou]=Ou;return Pu},Au.getValidEnumValues=Iu=>{const Pu=Au.objectKeys(Iu).filter(Mu=>typeof Iu[Iu[Mu]]!="number"),Ou={};for(const Mu of Pu)Ou[Mu]=Iu[Mu];return Au.objectValues(Ou)},Au.objectValues=Iu=>Au.objectKeys(Iu).map(function(Pu){return Iu[Pu]}),Au.objectKeys=typeof Object.keys=="function"?Iu=>Object.keys(Iu):Iu=>{const Pu=[];for(const Ou in Iu)Object.prototype.hasOwnProperty.call(Iu,Ou)&&Pu.push(Ou);return Pu},Au.find=(Iu,Pu)=>{for(const Ou of Iu)if(Pu(Ou))return Ou},Au.isInteger=typeof Number.isInteger=="function"?Iu=>Number.isInteger(Iu):Iu=>typeof Iu=="number"&&Number.isFinite(Iu)&&Math.floor(Iu)===Iu;function Ru(Iu,Pu=" | "){return Iu.map(Ou=>typeof Ou=="string"?`'${Ou}'`:Ou).join(Pu)}Au.joinValues=Ru,Au.jsonStringifyReplacer=(Iu,Pu)=>typeof Pu=="bigint"?Pu.toString():Pu})(util||(util={}));var objectUtil;(function(Au){Au.mergeShapes=(lo,$u)=>({...lo,...$u})})(objectUtil||(objectUtil={}));const ZodParsedType=util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),getParsedType=Au=>{switch(typeof Au){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return Number.isNaN(Au)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":return Array.isArray(Au)?ZodParsedType.array:Au===null?ZodParsedType.null:Au.then&&typeof Au.then=="function"&&Au.catch&&typeof Au.catch=="function"?ZodParsedType.promise:typeof Map<"u"&&Au instanceof Map?ZodParsedType.map:typeof Set<"u"&&Au instanceof Set?ZodParsedType.set:typeof Date<"u"&&Au instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ZodError extends Error{get errors(){return this.issues}constructor(lo){super(),this.issues=[],this.addIssue=Ru=>{this.issues=[...this.issues,Ru]},this.addIssues=(Ru=[])=>{this.issues=[...this.issues,...Ru]};const $u=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,$u):this.__proto__=$u,this.name="ZodError",this.issues=lo}format(lo){const $u=lo||function(Pu){return Pu.message},Ru={_errors:[]},Iu=Pu=>{for(const Ou of Pu.issues)if(Ou.code==="invalid_union")Ou.unionErrors.map(Iu);else if(Ou.code==="invalid_return_type")Iu(Ou.returnTypeError);else if(Ou.code==="invalid_arguments")Iu(Ou.argumentsError);else if(Ou.path.length===0)Ru._errors.push($u(Ou));else{let Mu=Ru,Du=0;for(;Du<Ou.path.length;){const Lu=Ou.path[Du];Du===Ou.path.length-1?(Mu[Lu]=Mu[Lu]||{_errors:[]},Mu[Lu]._errors.push($u(Ou))):Mu[Lu]=Mu[Lu]||{_errors:[]},Mu=Mu[Lu],Du++}}};return Iu(this),Ru}static assert(lo){if(!(lo instanceof ZodError))throw new Error(`Not a ZodError: ${lo}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(lo=$u=>$u.message){const $u={},Ru=[];for(const Iu of this.issues)if(Iu.path.length>0){const Pu=Iu.path[0];$u[Pu]=$u[Pu]||[],$u[Pu].push(lo(Iu))}else Ru.push(lo(Iu));return{formErrors:Ru,fieldErrors:$u}}get formErrors(){return this.flatten()}}ZodError.create=Au=>new ZodError(Au);const errorMap=(Au,lo)=>{let $u;switch(Au.code){case ZodIssueCode.invalid_type:Au.received===ZodParsedType.undefined?$u="Required":$u=`Expected ${Au.expected}, received ${Au.received}`;break;case ZodIssueCode.invalid_literal:$u=`Invalid literal value, expected ${JSON.stringify(Au.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:$u=`Unrecognized key(s) in object: ${util.joinValues(Au.keys,", ")}`;break;case ZodIssueCode.invalid_union:$u="Invalid input";break;case ZodIssueCode.invalid_union_discriminator:$u=`Invalid discriminator value. Expected ${util.joinValues(Au.options)}`;break;case ZodIssueCode.invalid_enum_value:$u=`Invalid enum value. Expected ${util.joinValues(Au.options)}, received '${Au.received}'`;break;case ZodIssueCode.invalid_arguments:$u="Invalid function arguments";break;case ZodIssueCode.invalid_return_type:$u="Invalid function return type";break;case ZodIssueCode.invalid_date:$u="Invalid date";break;case ZodIssueCode.invalid_string:typeof Au.validation=="object"?"includes"in Au.validation?($u=`Invalid input: must include "${Au.validation.includes}"`,typeof Au.validation.position=="number"&&($u=`${$u} at one or more positions greater than or equal to ${Au.validation.position}`)):"startsWith"in Au.validation?$u=`Invalid input: must start with "${Au.validation.startsWith}"`:"endsWith"in Au.validation?$u=`Invalid input: must end with "${Au.validation.endsWith}"`:util.assertNever(Au.validation):Au.validation!=="regex"?$u=`Invalid ${Au.validation}`:$u="Invalid";break;case ZodIssueCode.too_small:Au.type==="array"?$u=`Array must contain ${Au.exact?"exactly":Au.inclusive?"at least":"more than"} ${Au.minimum} element(s)`:Au.type==="string"?$u=`String must contain ${Au.exact?"exactly":Au.inclusive?"at least":"over"} ${Au.minimum} character(s)`:Au.type==="number"?$u=`Number must be ${Au.exact?"exactly equal to ":Au.inclusive?"greater than or equal to ":"greater than "}${Au.minimum}`:Au.type==="bigint"?$u=`Number must be ${Au.exact?"exactly equal to ":Au.inclusive?"greater than or equal to ":"greater than "}${Au.minimum}`:Au.type==="date"?$u=`Date must be ${Au.exact?"exactly equal to ":Au.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(Au.minimum))}`:$u="Invalid input";break;case ZodIssueCode.too_big:Au.type==="array"?$u=`Array must contain ${Au.exact?"exactly":Au.inclusive?"at most":"less than"} ${Au.maximum} element(s)`:Au.type==="string"?$u=`String must contain ${Au.exact?"exactly":Au.inclusive?"at most":"under"} ${Au.maximum} character(s)`:Au.type==="number"?$u=`Number must be ${Au.exact?"exactly":Au.inclusive?"less than or equal to":"less than"} ${Au.maximum}`:Au.type==="bigint"?$u=`BigInt must be ${Au.exact?"exactly":Au.inclusive?"less than or equal to":"less than"} ${Au.maximum}`:Au.type==="date"?$u=`Date must be ${Au.exact?"exactly":Au.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(Au.maximum))}`:$u="Invalid input";break;case ZodIssueCode.custom:$u="Invalid input";break;case ZodIssueCode.invalid_intersection_types:$u="Intersection results could not be merged";break;case ZodIssueCode.not_multiple_of:$u=`Number must be a multiple of ${Au.multipleOf}`;break;case ZodIssueCode.not_finite:$u="Number must be finite";break;default:$u=lo.defaultError,util.assertNever(Au)}return{message:$u}};let overrideErrorMap=errorMap;function getErrorMap(){return overrideErrorMap}const makeIssue=Au=>{const{data:lo,path:$u,errorMaps:Ru,issueData:Iu}=Au,Pu=[...$u,...Iu.path||[]],Ou={...Iu,path:Pu};if(Iu.message!==void 0)return{...Iu,path:Pu,message:Iu.message};let Mu="";const Du=Ru.filter(Lu=>!!Lu).slice().reverse();for(const Lu of Du)Mu=Lu(Ou,{data:lo,defaultError:Mu}).message;return{...Iu,path:Pu,message:Mu}};function addIssueToContext(Au,lo){const $u=getErrorMap(),Ru=makeIssue({issueData:lo,data:Au.data,path:Au.path,errorMaps:[Au.common.contextualErrorMap,Au.schemaErrorMap,$u,$u===errorMap?void 0:errorMap].filter(Iu=>!!Iu)});Au.common.issues.push(Ru)}class ParseStatus{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(lo,$u){const Ru=[];for(const Iu of $u){if(Iu.status==="aborted")return INVALID;Iu.status==="dirty"&&lo.dirty(),Ru.push(Iu.value)}return{status:lo.value,value:Ru}}static async mergeObjectAsync(lo,$u){const Ru=[];for(const Iu of $u){const Pu=await Iu.key,Ou=await Iu.value;Ru.push({key:Pu,value:Ou})}return ParseStatus.mergeObjectSync(lo,Ru)}static mergeObjectSync(lo,$u){const Ru={};for(const Iu of $u){const{key:Pu,value:Ou}=Iu;if(Pu.status==="aborted"||Ou.status==="aborted")return INVALID;Pu.status==="dirty"&&lo.dirty(),Ou.status==="dirty"&&lo.dirty(),Pu.value!=="__proto__"&&(typeof Ou.value<"u"||Iu.alwaysSet)&&(Ru[Pu.value]=Ou.value)}return{status:lo.value,value:Ru}}}const INVALID=Object.freeze({status:"aborted"}),DIRTY=Au=>({status:"dirty",value:Au}),OK=Au=>({status:"valid",value:Au}),isAborted=Au=>Au.status==="aborted",isDirty=Au=>Au.status==="dirty",isValid=Au=>Au.status==="valid",isAsync=Au=>typeof Promise<"u"&&Au instanceof Promise;var errorUtil;(function(Au){Au.errToObj=lo=>typeof lo=="string"?{message:lo}:lo||{},Au.toString=lo=>typeof lo=="string"?lo:lo?.message})(errorUtil||(errorUtil={}));class ParseInputLazyPath{constructor(lo,$u,Ru,Iu){this._cachedPath=[],this.parent=lo,this.data=$u,this._path=Ru,this._key=Iu}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const handleResult=(Au,lo)=>{if(isValid(lo))return{success:!0,data:lo.value};if(!Au.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const $u=new ZodError(Au.common.issues);return this._error=$u,this._error}}};function processCreateParams(Au){if(!Au)return{};const{errorMap:lo,invalid_type_error:$u,required_error:Ru,description:Iu}=Au;if(lo&&($u||Ru))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return lo?{errorMap:lo,description:Iu}:{errorMap:(Ou,Mu)=>{const{message:Du}=Au;return Ou.code==="invalid_enum_value"?{message:Du??Mu.defaultError}:typeof Mu.data>"u"?{message:Du??Ru??Mu.defaultError}:Ou.code!=="invalid_type"?{message:Mu.defaultError}:{message:Du??$u??Mu.defaultError}},description:Iu}}class ZodType{get description(){return this._def.description}_getType(lo){return getParsedType(lo.data)}_getOrReturnCtx(lo,$u){return $u||{common:lo.parent.common,data:lo.data,parsedType:getParsedType(lo.data),schemaErrorMap:this._def.errorMap,path:lo.path,parent:lo.parent}}_processInputParams(lo){return{status:new ParseStatus,ctx:{common:lo.parent.common,data:lo.data,parsedType:getParsedType(lo.data),schemaErrorMap:this._def.errorMap,path:lo.path,parent:lo.parent}}}_parseSync(lo){const $u=this._parse(lo);if(isAsync($u))throw new Error("Synchronous parse encountered promise.");return $u}_parseAsync(lo){const $u=this._parse(lo);return Promise.resolve($u)}parse(lo,$u){const Ru=this.safeParse(lo,$u);if(Ru.success)return Ru.data;throw Ru.error}safeParse(lo,$u){const Ru={common:{issues:[],async:$u?.async??!1,contextualErrorMap:$u?.errorMap},path:$u?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:lo,parsedType:getParsedType(lo)},Iu=this._parseSync({data:lo,path:Ru.path,parent:Ru});return handleResult(Ru,Iu)}"~validate"(lo){const $u={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:lo,parsedType:getParsedType(lo)};if(!this["~standard"].async)try{const Ru=this._parseSync({data:lo,path:[],parent:$u});return isValid(Ru)?{value:Ru.value}:{issues:$u.common.issues}}catch(Ru){Ru?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),$u.common={issues:[],async:!0}}return this._parseAsync({data:lo,path:[],parent:$u}).then(Ru=>isValid(Ru)?{value:Ru.value}:{issues:$u.common.issues})}async parseAsync(lo,$u){const Ru=await this.safeParseAsync(lo,$u);if(Ru.success)return Ru.data;throw Ru.error}async safeParseAsync(lo,$u){const Ru={common:{issues:[],contextualErrorMap:$u?.errorMap,async:!0},path:$u?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:lo,parsedType:getParsedType(lo)},Iu=this._parse({data:lo,path:Ru.path,parent:Ru}),Pu=await(isAsync(Iu)?Iu:Promise.resolve(Iu));return handleResult(Ru,Pu)}refine(lo,$u){const Ru=Iu=>typeof $u=="string"||typeof $u>"u"?{message:$u}:typeof $u=="function"?$u(Iu):$u;return this._refinement((Iu,Pu)=>{const Ou=lo(Iu),Mu=()=>Pu.addIssue({code:ZodIssueCode.custom,...Ru(Iu)});return typeof Promise<"u"&&Ou instanceof Promise?Ou.then(Du=>Du?!0:(Mu(),!1)):Ou?!0:(Mu(),!1)})}refinement(lo,$u){return this._refinement((Ru,Iu)=>lo(Ru)?!0:(Iu.addIssue(typeof $u=="function"?$u(Ru,Iu):$u),!1))}_refinement(lo){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"refinement",refinement:lo}})}superRefine(lo){return this._refinement(lo)}constructor(lo){this.spa=this.safeParseAsync,this._def=lo,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:$u=>this["~validate"]($u)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(lo){return ZodUnion.create([this,lo],this._def)}and(lo){return ZodIntersection.create(this,lo,this._def)}transform(lo){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform:lo}})}default(lo){const $u=typeof lo=="function"?lo:()=>lo;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:$u,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(lo){const $u=typeof lo=="function"?lo:()=>lo;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:$u,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(lo){const $u=this.constructor;return new $u({...this._def,description:lo})}pipe(lo){return ZodPipeline.create(this,lo)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let emojiRegex;const ipv4Regex=/^(?:(?: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])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource="((\\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])))",dateRegex=new RegExp(`^${dateRegexSource}$`);function timeRegexSource(Au){let lo="[0-5]\\d";Au.precision?lo=`${lo}\\.\\d{${Au.precision}}`:Au.precision==null&&(lo=`${lo}(\\.\\d+)?`);const $u=Au.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${lo})${$u}`}function timeRegex(Au){return new RegExp(`^${timeRegexSource(Au)}$`)}function datetimeRegex(Au){let lo=`${dateRegexSource}T${timeRegexSource(Au)}`;const $u=[];return $u.push(Au.local?"Z?":"Z"),Au.offset&&$u.push("([+-]\\d{2}:?\\d{2})"),lo=`${lo}(${$u.join("|")})`,new RegExp(`^${lo}$`)}function isValidIP(Au,lo){return!!((lo==="v4"||!lo)&&ipv4Regex.test(Au)||(lo==="v6"||!lo)&&ipv6Regex.test(Au))}function isValidJWT(Au,lo){if(!jwtRegex.test(Au))return!1;try{const[$u]=Au.split(".");if(!$u)return!1;const Ru=$u.replace(/-/g,"+").replace(/_/g,"/").padEnd($u.length+(4-$u.length%4)%4,"="),Iu=JSON.parse(atob(Ru));return!(typeof Iu!="object"||Iu===null||"typ"in Iu&&Iu?.typ!=="JWT"||!Iu.alg||lo&&Iu.alg!==lo)}catch{return!1}}function isValidCidr(Au,lo){return!!((lo==="v4"||!lo)&&ipv4CidrRegex.test(Au)||(lo==="v6"||!lo)&&ipv6CidrRegex.test(Au))}class ZodString extends ZodType{_parse(lo){if(this._def.coerce&&(lo.data=String(lo.data)),this._getType(lo)!==ZodParsedType.string){const Pu=this._getOrReturnCtx(lo);return addIssueToContext(Pu,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:Pu.parsedType}),INVALID}const Ru=new ParseStatus;let Iu;for(const Pu of this._def.checks)if(Pu.kind==="min")lo.data.length<Pu.value&&(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.too_small,minimum:Pu.value,type:"string",inclusive:!0,exact:!1,message:Pu.message}),Ru.dirty());else if(Pu.kind==="max")lo.data.length>Pu.value&&(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.too_big,maximum:Pu.value,type:"string",inclusive:!0,exact:!1,message:Pu.message}),Ru.dirty());else if(Pu.kind==="length"){const Ou=lo.data.length>Pu.value,Mu=lo.data.length<Pu.value;(Ou||Mu)&&(Iu=this._getOrReturnCtx(lo,Iu),Ou?addIssueToContext(Iu,{code:ZodIssueCode.too_big,maximum:Pu.value,type:"string",inclusive:!0,exact:!0,message:Pu.message}):Mu&&addIssueToContext(Iu,{code:ZodIssueCode.too_small,minimum:Pu.value,type:"string",inclusive:!0,exact:!0,message:Pu.message}),Ru.dirty())}else if(Pu.kind==="email")emailRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"email",code:ZodIssueCode.invalid_string,message:Pu.message}),Ru.dirty());else if(Pu.kind==="emoji")emojiRegex||(emojiRegex=new RegExp(_emojiRegex,"u")),emojiRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"emoji",code:ZodIssueCode.invalid_string,message:Pu.message}),Ru.dirty());else if(Pu.kind==="uuid")uuidRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"uuid",code:ZodIssueCode.invalid_string,message:Pu.message}),Ru.dirty());else if(Pu.kind==="nanoid")nanoidRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:Pu.message}),Ru.dirty());else if(Pu.kind==="cuid")cuidRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"cuid",code:ZodIssueCode.invalid_string,message:Pu.message}),Ru.dirty());else if(Pu.kind==="cuid2")cuid2Regex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:Pu.message}),Ru.dirty());else if(Pu.kind==="ulid")ulidRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"ulid",code:ZodIssueCode.invalid_string,message:Pu.message}),Ru.dirty());else if(Pu.kind==="url")try{new URL(lo.data)}catch{Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"url",code:ZodIssueCode.invalid_string,message:Pu.message}),Ru.dirty()}else Pu.kind==="regex"?(Pu.regex.lastIndex=0,Pu.regex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"regex",code:ZodIssueCode.invalid_string,message:Pu.message}),Ru.dirty())):Pu.kind==="trim"?lo.data=lo.data.trim():Pu.kind==="includes"?lo.data.includes(Pu.value,Pu.position)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.invalid_string,validation:{includes:Pu.value,position:Pu.position},message:Pu.message}),Ru.dirty()):Pu.kind==="toLowerCase"?lo.data=lo.data.toLowerCase():Pu.kind==="toUpperCase"?lo.data=lo.data.toUpperCase():Pu.kind==="startsWith"?lo.data.startsWith(Pu.value)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.invalid_string,validation:{startsWith:Pu.value},message:Pu.message}),Ru.dirty()):Pu.kind==="endsWith"?lo.data.endsWith(Pu.value)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.invalid_string,validation:{endsWith:Pu.value},message:Pu.message}),Ru.dirty()):Pu.kind==="datetime"?datetimeRegex(Pu).test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.invalid_string,validation:"datetime",message:Pu.message}),Ru.dirty()):Pu.kind==="date"?dateRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.invalid_string,validation:"date",message:Pu.message}),Ru.dirty()):Pu.kind==="time"?timeRegex(Pu).test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.invalid_string,validation:"time",message:Pu.message}),Ru.dirty()):Pu.kind==="duration"?durationRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"duration",code:ZodIssueCode.invalid_string,message:Pu.message}),Ru.dirty()):Pu.kind==="ip"?isValidIP(lo.data,Pu.version)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"ip",code:ZodIssueCode.invalid_string,message:Pu.message}),Ru.dirty()):Pu.kind==="jwt"?isValidJWT(lo.data,Pu.alg)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"jwt",code:ZodIssueCode.invalid_string,message:Pu.message}),Ru.dirty()):Pu.kind==="cidr"?isValidCidr(lo.data,Pu.version)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"cidr",code:ZodIssueCode.invalid_string,message:Pu.message}),Ru.dirty()):Pu.kind==="base64"?base64Regex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"base64",code:ZodIssueCode.invalid_string,message:Pu.message}),Ru.dirty()):Pu.kind==="base64url"?base64urlRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"base64url",code:ZodIssueCode.invalid_string,message:Pu.message}),Ru.dirty()):util.assertNever(Pu);return{status:Ru.value,value:lo.data}}_regex(lo,$u,Ru){return this.refinement(Iu=>lo.test(Iu),{validation:$u,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(Ru)})}_addCheck(lo){return new ZodString({...this._def,checks:[...this._def.checks,lo]})}email(lo){return this._addCheck({kind:"email",...errorUtil.errToObj(lo)})}url(lo){return this._addCheck({kind:"url",...errorUtil.errToObj(lo)})}emoji(lo){return this._addCheck({kind:"emoji",...errorUtil.errToObj(lo)})}uuid(lo){return this._addCheck({kind:"uuid",...errorUtil.errToObj(lo)})}nanoid(lo){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(lo)})}cuid(lo){return this._addCheck({kind:"cuid",...errorUtil.errToObj(lo)})}cuid2(lo){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(lo)})}ulid(lo){return this._addCheck({kind:"ulid",...errorUtil.errToObj(lo)})}base64(lo){return this._addCheck({kind:"base64",...errorUtil.errToObj(lo)})}base64url(lo){return this._addCheck({kind:"base64url",...errorUtil.errToObj(lo)})}jwt(lo){return this._addCheck({kind:"jwt",...errorUtil.errToObj(lo)})}ip(lo){return this._addCheck({kind:"ip",...errorUtil.errToObj(lo)})}cidr(lo){return this._addCheck({kind:"cidr",...errorUtil.errToObj(lo)})}datetime(lo){return typeof lo=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:lo}):this._addCheck({kind:"datetime",precision:typeof lo?.precision>"u"?null:lo?.precision,offset:lo?.offset??!1,local:lo?.local??!1,...errorUtil.errToObj(lo?.message)})}date(lo){return this._addCheck({kind:"date",message:lo})}time(lo){return typeof lo=="string"?this._addCheck({kind:"time",precision:null,message:lo}):this._addCheck({kind:"time",precision:typeof lo?.precision>"u"?null:lo?.precision,...errorUtil.errToObj(lo?.message)})}duration(lo){return this._addCheck({kind:"duration",...errorUtil.errToObj(lo)})}regex(lo,$u){return this._addCheck({kind:"regex",regex:lo,...errorUtil.errToObj($u)})}includes(lo,$u){return this._addCheck({kind:"includes",value:lo,position:$u?.position,...errorUtil.errToObj($u?.message)})}startsWith(lo,$u){return this._addCheck({kind:"startsWith",value:lo,...errorUtil.errToObj($u)})}endsWith(lo,$u){return this._addCheck({kind:"endsWith",value:lo,...errorUtil.errToObj($u)})}min(lo,$u){return this._addCheck({kind:"min",value:lo,...errorUtil.errToObj($u)})}max(lo,$u){return this._addCheck({kind:"max",value:lo,...errorUtil.errToObj($u)})}length(lo,$u){return this._addCheck({kind:"length",value:lo,...errorUtil.errToObj($u)})}nonempty(lo){return this.min(1,errorUtil.errToObj(lo))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(lo=>lo.kind==="datetime")}get isDate(){return!!this._def.checks.find(lo=>lo.kind==="date")}get isTime(){return!!this._def.checks.find(lo=>lo.kind==="time")}get isDuration(){return!!this._def.checks.find(lo=>lo.kind==="duration")}get isEmail(){return!!this._def.checks.find(lo=>lo.kind==="email")}get isURL(){return!!this._def.checks.find(lo=>lo.kind==="url")}get isEmoji(){return!!this._def.checks.find(lo=>lo.kind==="emoji")}get isUUID(){return!!this._def.checks.find(lo=>lo.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(lo=>lo.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(lo=>lo.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(lo=>lo.kind==="cuid2")}get isULID(){return!!this._def.checks.find(lo=>lo.kind==="ulid")}get isIP(){return!!this._def.checks.find(lo=>lo.kind==="ip")}get isCIDR(){return!!this._def.checks.find(lo=>lo.kind==="cidr")}get isBase64(){return!!this._def.checks.find(lo=>lo.kind==="base64")}get isBase64url(){return!!this._def.checks.find(lo=>lo.kind==="base64url")}get minLength(){let lo=null;for(const $u of this._def.checks)$u.kind==="min"&&(lo===null||$u.value>lo)&&(lo=$u.value);return lo}get maxLength(){let lo=null;for(const $u of this._def.checks)$u.kind==="max"&&(lo===null||$u.value<lo)&&(lo=$u.value);return lo}}ZodString.create=Au=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:Au?.coerce??!1,...processCreateParams(Au)});function floatSafeRemainder(Au,lo){const $u=(Au.toString().split(".")[1]||"").length,Ru=(lo.toString().split(".")[1]||"").length,Iu=$u>Ru?$u:Ru,Pu=Number.parseInt(Au.toFixed(Iu).replace(".","")),Ou=Number.parseInt(lo.toFixed(Iu).replace(".",""));return Pu%Ou/10**Iu}class ZodNumber extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(lo){if(this._def.coerce&&(lo.data=Number(lo.data)),this._getType(lo)!==ZodParsedType.number){const Pu=this._getOrReturnCtx(lo);return addIssueToContext(Pu,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:Pu.parsedType}),INVALID}let Ru;const Iu=new ParseStatus;for(const Pu of this._def.checks)Pu.kind==="int"?util.isInteger(lo.data)||(Ru=this._getOrReturnCtx(lo,Ru),addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:Pu.message}),Iu.dirty()):Pu.kind==="min"?(Pu.inclusive?lo.data<Pu.value:lo.data<=Pu.value)&&(Ru=this._getOrReturnCtx(lo,Ru),addIssueToContext(Ru,{code:ZodIssueCode.too_small,minimum:Pu.value,type:"number",inclusive:Pu.inclusive,exact:!1,message:Pu.message}),Iu.dirty()):Pu.kind==="max"?(Pu.inclusive?lo.data>Pu.value:lo.data>=Pu.value)&&(Ru=this._getOrReturnCtx(lo,Ru),addIssueToContext(Ru,{code:ZodIssueCode.too_big,maximum:Pu.value,type:"number",inclusive:Pu.inclusive,exact:!1,message:Pu.message}),Iu.dirty()):Pu.kind==="multipleOf"?floatSafeRemainder(lo.data,Pu.value)!==0&&(Ru=this._getOrReturnCtx(lo,Ru),addIssueToContext(Ru,{code:ZodIssueCode.not_multiple_of,multipleOf:Pu.value,message:Pu.message}),Iu.dirty()):Pu.kind==="finite"?Number.isFinite(lo.data)||(Ru=this._getOrReturnCtx(lo,Ru),addIssueToContext(Ru,{code:ZodIssueCode.not_finite,message:Pu.message}),Iu.dirty()):util.assertNever(Pu);return{status:Iu.value,value:lo.data}}gte(lo,$u){return this.setLimit("min",lo,!0,errorUtil.toString($u))}gt(lo,$u){return this.setLimit("min",lo,!1,errorUtil.toString($u))}lte(lo,$u){return this.setLimit("max",lo,!0,errorUtil.toString($u))}lt(lo,$u){return this.setLimit("max",lo,!1,errorUtil.toString($u))}setLimit(lo,$u,Ru,Iu){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind:lo,value:$u,inclusive:Ru,message:errorUtil.toString(Iu)}]})}_addCheck(lo){return new ZodNumber({...this._def,checks:[...this._def.checks,lo]})}int(lo){return this._addCheck({kind:"int",message:errorUtil.toString(lo)})}positive(lo){return this._addCheck({kind:"min",value:0,inclusive:!1,message:errorUtil.toString(lo)})}negative(lo){return this._addCheck({kind:"max",value:0,inclusive:!1,message:errorUtil.toString(lo)})}nonpositive(lo){return this._addCheck({kind:"max",value:0,inclusive:!0,message:errorUtil.toString(lo)})}nonnegative(lo){return this._addCheck({kind:"min",value:0,inclusive:!0,message:errorUtil.toString(lo)})}multipleOf(lo,$u){return this._addCheck({kind:"multipleOf",value:lo,message:errorUtil.toString($u)})}finite(lo){return this._addCheck({kind:"finite",message:errorUtil.toString(lo)})}safe(lo){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString(lo)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil.toString(lo)})}get minValue(){let lo=null;for(const $u of this._def.checks)$u.kind==="min"&&(lo===null||$u.value>lo)&&(lo=$u.value);return lo}get maxValue(){let lo=null;for(const $u of this._def.checks)$u.kind==="max"&&(lo===null||$u.value<lo)&&(lo=$u.value);return lo}get isInt(){return!!this._def.checks.find(lo=>lo.kind==="int"||lo.kind==="multipleOf"&&util.isInteger(lo.value))}get isFinite(){let lo=null,$u=null;for(const Ru of this._def.checks){if(Ru.kind==="finite"||Ru.kind==="int"||Ru.kind==="multipleOf")return!0;Ru.kind==="min"?($u===null||Ru.value>$u)&&($u=Ru.value):Ru.kind==="max"&&(lo===null||Ru.value<lo)&&(lo=Ru.value)}return Number.isFinite($u)&&Number.isFinite(lo)}}ZodNumber.create=Au=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:Au?.coerce||!1,...processCreateParams(Au)});class ZodBigInt extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(lo){if(this._def.coerce)try{lo.data=BigInt(lo.data)}catch{return this._getInvalidInput(lo)}if(this._getType(lo)!==ZodParsedType.bigint)return this._getInvalidInput(lo);let Ru;const Iu=new ParseStatus;for(const Pu of this._def.checks)Pu.kind==="min"?(Pu.inclusive?lo.data<Pu.value:lo.data<=Pu.value)&&(Ru=this._getOrReturnCtx(lo,Ru),addIssueToContext(Ru,{code:ZodIssueCode.too_small,type:"bigint",minimum:Pu.value,inclusive:Pu.inclusive,message:Pu.message}),Iu.dirty()):Pu.kind==="max"?(Pu.inclusive?lo.data>Pu.value:lo.data>=Pu.value)&&(Ru=this._getOrReturnCtx(lo,Ru),addIssueToContext(Ru,{code:ZodIssueCode.too_big,type:"bigint",maximum:Pu.value,inclusive:Pu.inclusive,message:Pu.message}),Iu.dirty()):Pu.kind==="multipleOf"?lo.data%Pu.value!==BigInt(0)&&(Ru=this._getOrReturnCtx(lo,Ru),addIssueToContext(Ru,{code:ZodIssueCode.not_multiple_of,multipleOf:Pu.value,message:Pu.message}),Iu.dirty()):util.assertNever(Pu);return{status:Iu.value,value:lo.data}}_getInvalidInput(lo){const $u=this._getOrReturnCtx(lo);return addIssueToContext($u,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:$u.parsedType}),INVALID}gte(lo,$u){return this.setLimit("min",lo,!0,errorUtil.toString($u))}gt(lo,$u){return this.setLimit("min",lo,!1,errorUtil.toString($u))}lte(lo,$u){return this.setLimit("max",lo,!0,errorUtil.toString($u))}lt(lo,$u){return this.setLimit("max",lo,!1,errorUtil.toString($u))}setLimit(lo,$u,Ru,Iu){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:lo,value:$u,inclusive:Ru,message:errorUtil.toString(Iu)}]})}_addCheck(lo){return new ZodBigInt({...this._def,checks:[...this._def.checks,lo]})}positive(lo){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString(lo)})}negative(lo){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString(lo)})}nonpositive(lo){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString(lo)})}nonnegative(lo){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString(lo)})}multipleOf(lo,$u){return this._addCheck({kind:"multipleOf",value:lo,message:errorUtil.toString($u)})}get minValue(){let lo=null;for(const $u of this._def.checks)$u.kind==="min"&&(lo===null||$u.value>lo)&&(lo=$u.value);return lo}get maxValue(){let lo=null;for(const $u of this._def.checks)$u.kind==="max"&&(lo===null||$u.value<lo)&&(lo=$u.value);return lo}}ZodBigInt.create=Au=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:Au?.coerce??!1,...processCreateParams(Au)});class ZodBoolean extends ZodType{_parse(lo){if(this._def.coerce&&(lo.data=!!lo.data),this._getType(lo)!==ZodParsedType.boolean){const Ru=this._getOrReturnCtx(lo);return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:Ru.parsedType}),INVALID}return OK(lo.data)}}ZodBoolean.create=Au=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:Au?.coerce||!1,...processCreateParams(Au)});class ZodDate extends ZodType{_parse(lo){if(this._def.coerce&&(lo.data=new Date(lo.data)),this._getType(lo)!==ZodParsedType.date){const Pu=this._getOrReturnCtx(lo);return addIssueToContext(Pu,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:Pu.parsedType}),INVALID}if(Number.isNaN(lo.data.getTime())){const Pu=this._getOrReturnCtx(lo);return addIssueToContext(Pu,{code:ZodIssueCode.invalid_date}),INVALID}const Ru=new ParseStatus;let Iu;for(const Pu of this._def.checks)Pu.kind==="min"?lo.data.getTime()<Pu.value&&(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.too_small,message:Pu.message,inclusive:!0,exact:!1,minimum:Pu.value,type:"date"}),Ru.dirty()):Pu.kind==="max"?lo.data.getTime()>Pu.value&&(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.too_big,message:Pu.message,inclusive:!0,exact:!1,maximum:Pu.value,type:"date"}),Ru.dirty()):util.assertNever(Pu);return{status:Ru.value,value:new Date(lo.data.getTime())}}_addCheck(lo){return new ZodDate({...this._def,checks:[...this._def.checks,lo]})}min(lo,$u){return this._addCheck({kind:"min",value:lo.getTime(),message:errorUtil.toString($u)})}max(lo,$u){return this._addCheck({kind:"max",value:lo.getTime(),message:errorUtil.toString($u)})}get minDate(){let lo=null;for(const $u of this._def.checks)$u.kind==="min"&&(lo===null||$u.value>lo)&&(lo=$u.value);return lo!=null?new Date(lo):null}get maxDate(){let lo=null;for(const $u of this._def.checks)$u.kind==="max"&&(lo===null||$u.value<lo)&&(lo=$u.value);return lo!=null?new Date(lo):null}}ZodDate.create=Au=>new ZodDate({checks:[],coerce:Au?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(Au)});class ZodSymbol extends ZodType{_parse(lo){if(this._getType(lo)!==ZodParsedType.symbol){const Ru=this._getOrReturnCtx(lo);return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:Ru.parsedType}),INVALID}return OK(lo.data)}}ZodSymbol.create=Au=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(Au)});class ZodUndefined extends ZodType{_parse(lo){if(this._getType(lo)!==ZodParsedType.undefined){const Ru=this._getOrReturnCtx(lo);return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:Ru.parsedType}),INVALID}return OK(lo.data)}}ZodUndefined.create=Au=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(Au)});class ZodNull extends ZodType{_parse(lo){if(this._getType(lo)!==ZodParsedType.null){const Ru=this._getOrReturnCtx(lo);return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:Ru.parsedType}),INVALID}return OK(lo.data)}}ZodNull.create=Au=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(Au)});class ZodAny extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(lo){return OK(lo.data)}}ZodAny.create=Au=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(Au)});class ZodUnknown extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(lo){return OK(lo.data)}}ZodUnknown.create=Au=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(Au)});class ZodNever extends ZodType{_parse(lo){const $u=this._getOrReturnCtx(lo);return addIssueToContext($u,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:$u.parsedType}),INVALID}}ZodNever.create=Au=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(Au)});class ZodVoid extends ZodType{_parse(lo){if(this._getType(lo)!==ZodParsedType.undefined){const Ru=this._getOrReturnCtx(lo);return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:Ru.parsedType}),INVALID}return OK(lo.data)}}ZodVoid.create=Au=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(Au)});class ZodArray extends ZodType{_parse(lo){const{ctx:$u,status:Ru}=this._processInputParams(lo),Iu=this._def;if($u.parsedType!==ZodParsedType.array)return addIssueToContext($u,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:$u.parsedType}),INVALID;if(Iu.exactLength!==null){const Ou=$u.data.length>Iu.exactLength.value,Mu=$u.data.length<Iu.exactLength.value;(Ou||Mu)&&(addIssueToContext($u,{code:Ou?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:Mu?Iu.exactLength.value:void 0,maximum:Ou?Iu.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:Iu.exactLength.message}),Ru.dirty())}if(Iu.minLength!==null&&$u.data.length<Iu.minLength.value&&(addIssueToContext($u,{code:ZodIssueCode.too_small,minimum:Iu.minLength.value,type:"array",inclusive:!0,exact:!1,message:Iu.minLength.message}),Ru.dirty()),Iu.maxLength!==null&&$u.data.length>Iu.maxLength.value&&(addIssueToContext($u,{code:ZodIssueCode.too_big,maximum:Iu.maxLength.value,type:"array",inclusive:!0,exact:!1,message:Iu.maxLength.message}),Ru.dirty()),$u.common.async)return Promise.all([...$u.data].map((Ou,Mu)=>Iu.type._parseAsync(new ParseInputLazyPath($u,Ou,$u.path,Mu)))).then(Ou=>ParseStatus.mergeArray(Ru,Ou));const Pu=[...$u.data].map((Ou,Mu)=>Iu.type._parseSync(new ParseInputLazyPath($u,Ou,$u.path,Mu)));return ParseStatus.mergeArray(Ru,Pu)}get element(){return this._def.type}min(lo,$u){return new ZodArray({...this._def,minLength:{value:lo,message:errorUtil.toString($u)}})}max(lo,$u){return new ZodArray({...this._def,maxLength:{value:lo,message:errorUtil.toString($u)}})}length(lo,$u){return new ZodArray({...this._def,exactLength:{value:lo,message:errorUtil.toString($u)}})}nonempty(lo){return this.min(1,lo)}}ZodArray.create=(Au,lo)=>new ZodArray({type:Au,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(lo)});function deepPartialify(Au){if(Au instanceof ZodObject){const lo={};for(const $u in Au.shape){const Ru=Au.shape[$u];lo[$u]=ZodOptional.create(deepPartialify(Ru))}return new ZodObject({...Au._def,shape:()=>lo})}else return Au instanceof ZodArray?new ZodArray({...Au._def,type:deepPartialify(Au.element)}):Au instanceof ZodOptional?ZodOptional.create(deepPartialify(Au.unwrap())):Au instanceof ZodNullable?ZodNullable.create(deepPartialify(Au.unwrap())):Au instanceof ZodTuple?ZodTuple.create(Au.items.map(lo=>deepPartialify(lo))):Au}class ZodObject extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const lo=this._def.shape(),$u=util.objectKeys(lo);return this._cached={shape:lo,keys:$u},this._cached}_parse(lo){if(this._getType(lo)!==ZodParsedType.object){const Lu=this._getOrReturnCtx(lo);return addIssueToContext(Lu,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:Lu.parsedType}),INVALID}const{status:Ru,ctx:Iu}=this._processInputParams(lo),{shape:Pu,keys:Ou}=this._getCached(),Mu=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys==="strip"))for(const Lu in Iu.data)Ou.includes(Lu)||Mu.push(Lu);const Du=[];for(const Lu of Ou){const Bu=Pu[Lu],ju=Iu.data[Lu];Du.push({key:{status:"valid",value:Lu},value:Bu._parse(new ParseInputLazyPath(Iu,ju,Iu.path,Lu)),alwaysSet:Lu in Iu.data})}if(this._def.catchall instanceof ZodNever){const Lu=this._def.unknownKeys;if(Lu==="passthrough")for(const Bu of Mu)Du.push({key:{status:"valid",value:Bu},value:{status:"valid",value:Iu.data[Bu]}});else if(Lu==="strict")Mu.length>0&&(addIssueToContext(Iu,{code:ZodIssueCode.unrecognized_keys,keys:Mu}),Ru.dirty());else if(Lu!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const Lu=this._def.catchall;for(const Bu of Mu){const ju=Iu.data[Bu];Du.push({key:{status:"valid",value:Bu},value:Lu._parse(new ParseInputLazyPath(Iu,ju,Iu.path,Bu)),alwaysSet:Bu in Iu.data})}}return Iu.common.async?Promise.resolve().then(async()=>{const Lu=[];for(const Bu of Du){const ju=await Bu.key,Fu=await Bu.value;Lu.push({key:ju,value:Fu,alwaysSet:Bu.alwaysSet})}return Lu}).then(Lu=>ParseStatus.mergeObjectSync(Ru,Lu)):ParseStatus.mergeObjectSync(Ru,Du)}get shape(){return this._def.shape()}strict(lo){return errorUtil.errToObj,new ZodObject({...this._def,unknownKeys:"strict",...lo!==void 0?{errorMap:($u,Ru)=>{const Iu=this._def.errorMap?.($u,Ru).message??Ru.defaultError;return $u.code==="unrecognized_keys"?{message:errorUtil.errToObj(lo).message??Iu}:{message:Iu}}}:{}})}strip(){return new ZodObject({...this._def,unknownKeys:"strip"})}passthrough(){return new ZodObject({...this._def,unknownKeys:"passthrough"})}extend(lo){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...lo})})}merge(lo){return new ZodObject({unknownKeys:lo._def.unknownKeys,catchall:lo._def.catchall,shape:()=>({...this._def.shape(),...lo._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(lo,$u){return this.augment({[lo]:$u})}catchall(lo){return new ZodObject({...this._def,catchall:lo})}pick(lo){const $u={};for(const Ru of util.objectKeys(lo))lo[Ru]&&this.shape[Ru]&&($u[Ru]=this.shape[Ru]);return new ZodObject({...this._def,shape:()=>$u})}omit(lo){const $u={};for(const Ru of util.objectKeys(this.shape))lo[Ru]||($u[Ru]=this.shape[Ru]);return new ZodObject({...this._def,shape:()=>$u})}deepPartial(){return deepPartialify(this)}partial(lo){const $u={};for(const Ru of util.objectKeys(this.shape)){const Iu=this.shape[Ru];lo&&!lo[Ru]?$u[Ru]=Iu:$u[Ru]=Iu.optional()}return new ZodObject({...this._def,shape:()=>$u})}required(lo){const $u={};for(const Ru of util.objectKeys(this.shape))if(lo&&!lo[Ru])$u[Ru]=this.shape[Ru];else{let Pu=this.shape[Ru];for(;Pu instanceof ZodOptional;)Pu=Pu._def.innerType;$u[Ru]=Pu}return new ZodObject({...this._def,shape:()=>$u})}keyof(){return createZodEnum(util.objectKeys(this.shape))}}ZodObject.create=(Au,lo)=>new ZodObject({shape:()=>Au,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(lo)});ZodObject.strictCreate=(Au,lo)=>new ZodObject({shape:()=>Au,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(lo)});ZodObject.lazycreate=(Au,lo)=>new ZodObject({shape:Au,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(lo)});class ZodUnion extends ZodType{_parse(lo){const{ctx:$u}=this._processInputParams(lo),Ru=this._def.options;function Iu(Pu){for(const Mu of Pu)if(Mu.result.status==="valid")return Mu.result;for(const Mu of Pu)if(Mu.result.status==="dirty")return $u.common.issues.push(...Mu.ctx.common.issues),Mu.result;const Ou=Pu.map(Mu=>new ZodError(Mu.ctx.common.issues));return addIssueToContext($u,{code:ZodIssueCode.invalid_union,unionErrors:Ou}),INVALID}if($u.common.async)return Promise.all(Ru.map(async Pu=>{const Ou={...$u,common:{...$u.common,issues:[]},parent:null};return{result:await Pu._parseAsync({data:$u.data,path:$u.path,parent:Ou}),ctx:Ou}})).then(Iu);{let Pu;const Ou=[];for(const Du of Ru){const Lu={...$u,common:{...$u.common,issues:[]},parent:null},Bu=Du._parseSync({data:$u.data,path:$u.path,parent:Lu});if(Bu.status==="valid")return Bu;Bu.status==="dirty"&&!Pu&&(Pu={result:Bu,ctx:Lu}),Lu.common.issues.length&&Ou.push(Lu.common.issues)}if(Pu)return $u.common.issues.push(...Pu.ctx.common.issues),Pu.result;const Mu=Ou.map(Du=>new ZodError(Du));return addIssueToContext($u,{code:ZodIssueCode.invalid_union,unionErrors:Mu}),INVALID}}get options(){return this._def.options}}ZodUnion.create=(Au,lo)=>new ZodUnion({options:Au,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(lo)});function mergeValues(Au,lo){const $u=getParsedType(Au),Ru=getParsedType(lo);if(Au===lo)return{valid:!0,data:Au};if($u===ZodParsedType.object&&Ru===ZodParsedType.object){const Iu=util.objectKeys(lo),Pu=util.objectKeys(Au).filter(Mu=>Iu.indexOf(Mu)!==-1),Ou={...Au,...lo};for(const Mu of Pu){const Du=mergeValues(Au[Mu],lo[Mu]);if(!Du.valid)return{valid:!1};Ou[Mu]=Du.data}return{valid:!0,data:Ou}}else if($u===ZodParsedType.array&&Ru===ZodParsedType.array){if(Au.length!==lo.length)return{valid:!1};const Iu=[];for(let Pu=0;Pu<Au.length;Pu++){const Ou=Au[Pu],Mu=lo[Pu],Du=mergeValues(Ou,Mu);if(!Du.valid)return{valid:!1};Iu.push(Du.data)}return{valid:!0,data:Iu}}else return $u===ZodParsedType.date&&Ru===ZodParsedType.date&&+Au==+lo?{valid:!0,data:Au}:{valid:!1}}class ZodIntersection extends ZodType{_parse(lo){const{status:$u,ctx:Ru}=this._processInputParams(lo),Iu=(Pu,Ou)=>{if(isAborted(Pu)||isAborted(Ou))return INVALID;const Mu=mergeValues(Pu.value,Ou.value);return Mu.valid?((isDirty(Pu)||isDirty(Ou))&&$u.dirty(),{status:$u.value,value:Mu.data}):(addIssueToContext(Ru,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return Ru.common.async?Promise.all([this._def.left._parseAsync({data:Ru.data,path:Ru.path,parent:Ru}),this._def.right._parseAsync({data:Ru.data,path:Ru.path,parent:Ru})]).then(([Pu,Ou])=>Iu(Pu,Ou)):Iu(this._def.left._parseSync({data:Ru.data,path:Ru.path,parent:Ru}),this._def.right._parseSync({data:Ru.data,path:Ru.path,parent:Ru}))}}ZodIntersection.create=(Au,lo,$u)=>new ZodIntersection({left:Au,right:lo,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams($u)});class ZodTuple extends ZodType{_parse(lo){const{status:$u,ctx:Ru}=this._processInputParams(lo);if(Ru.parsedType!==ZodParsedType.array)return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:Ru.parsedType}),INVALID;if(Ru.data.length<this._def.items.length)return addIssueToContext(Ru,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;!this._def.rest&&Ru.data.length>this._def.items.length&&(addIssueToContext(Ru,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),$u.dirty());const Pu=[...Ru.data].map((Ou,Mu)=>{const Du=this._def.items[Mu]||this._def.rest;return Du?Du._parse(new ParseInputLazyPath(Ru,Ou,Ru.path,Mu)):null}).filter(Ou=>!!Ou);return Ru.common.async?Promise.all(Pu).then(Ou=>ParseStatus.mergeArray($u,Ou)):ParseStatus.mergeArray($u,Pu)}get items(){return this._def.items}rest(lo){return new ZodTuple({...this._def,rest:lo})}}ZodTuple.create=(Au,lo)=>{if(!Array.isArray(Au))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:Au,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(lo)})};class ZodRecord extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(lo){const{status:$u,ctx:Ru}=this._processInputParams(lo);if(Ru.parsedType!==ZodParsedType.object)return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:Ru.parsedType}),INVALID;const Iu=[],Pu=this._def.keyType,Ou=this._def.valueType;for(const Mu in Ru.data)Iu.push({key:Pu._parse(new ParseInputLazyPath(Ru,Mu,Ru.path,Mu)),value:Ou._parse(new ParseInputLazyPath(Ru,Ru.data[Mu],Ru.path,Mu)),alwaysSet:Mu in Ru.data});return Ru.common.async?ParseStatus.mergeObjectAsync($u,Iu):ParseStatus.mergeObjectSync($u,Iu)}get element(){return this._def.valueType}static create(lo,$u,Ru){return $u instanceof ZodType?new ZodRecord({keyType:lo,valueType:$u,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(Ru)}):new ZodRecord({keyType:ZodString.create(),valueType:lo,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams($u)})}}class ZodMap extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(lo){const{status:$u,ctx:Ru}=this._processInputParams(lo);if(Ru.parsedType!==ZodParsedType.map)return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:Ru.parsedType}),INVALID;const Iu=this._def.keyType,Pu=this._def.valueType,Ou=[...Ru.data.entries()].map(([Mu,Du],Lu)=>({key:Iu._parse(new ParseInputLazyPath(Ru,Mu,Ru.path,[Lu,"key"])),value:Pu._parse(new ParseInputLazyPath(Ru,Du,Ru.path,[Lu,"value"]))}));if(Ru.common.async){const Mu=new Map;return Promise.resolve().then(async()=>{for(const Du of Ou){const Lu=await Du.key,Bu=await Du.value;if(Lu.status==="aborted"||Bu.status==="aborted")return INVALID;(Lu.status==="dirty"||Bu.status==="dirty")&&$u.dirty(),Mu.set(Lu.value,Bu.value)}return{status:$u.value,value:Mu}})}else{const Mu=new Map;for(const Du of Ou){const Lu=Du.key,Bu=Du.value;if(Lu.status==="aborted"||Bu.status==="aborted")return INVALID;(Lu.status==="dirty"||Bu.status==="dirty")&&$u.dirty(),Mu.set(Lu.value,Bu.value)}return{status:$u.value,value:Mu}}}}ZodMap.create=(Au,lo,$u)=>new ZodMap({valueType:lo,keyType:Au,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams($u)});class ZodSet extends ZodType{_parse(lo){const{status:$u,ctx:Ru}=this._processInputParams(lo);if(Ru.parsedType!==ZodParsedType.set)return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:Ru.parsedType}),INVALID;const Iu=this._def;Iu.minSize!==null&&Ru.data.size<Iu.minSize.value&&(addIssueToContext(Ru,{code:ZodIssueCode.too_small,minimum:Iu.minSize.value,type:"set",inclusive:!0,exact:!1,message:Iu.minSize.message}),$u.dirty()),Iu.maxSize!==null&&Ru.data.size>Iu.maxSize.value&&(addIssueToContext(Ru,{code:ZodIssueCode.too_big,maximum:Iu.maxSize.value,type:"set",inclusive:!0,exact:!1,message:Iu.maxSize.message}),$u.dirty());const Pu=this._def.valueType;function Ou(Du){const Lu=new Set;for(const Bu of Du){if(Bu.status==="aborted")return INVALID;Bu.status==="dirty"&&$u.dirty(),Lu.add(Bu.value)}return{status:$u.value,value:Lu}}const Mu=[...Ru.data.values()].map((Du,Lu)=>Pu._parse(new ParseInputLazyPath(Ru,Du,Ru.path,Lu)));return Ru.common.async?Promise.all(Mu).then(Du=>Ou(Du)):Ou(Mu)}min(lo,$u){return new ZodSet({...this._def,minSize:{value:lo,message:errorUtil.toString($u)}})}max(lo,$u){return new ZodSet({...this._def,maxSize:{value:lo,message:errorUtil.toString($u)}})}size(lo,$u){return this.min(lo,$u).max(lo,$u)}nonempty(lo){return this.min(1,lo)}}ZodSet.create=(Au,lo)=>new ZodSet({valueType:Au,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(lo)});class ZodLazy extends ZodType{get schema(){return this._def.getter()}_parse(lo){const{ctx:$u}=this._processInputParams(lo);return this._def.getter()._parse({data:$u.data,path:$u.path,parent:$u})}}ZodLazy.create=(Au,lo)=>new ZodLazy({getter:Au,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(lo)});class ZodLiteral extends ZodType{_parse(lo){if(lo.data!==this._def.value){const $u=this._getOrReturnCtx(lo);return addIssueToContext($u,{received:$u.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:lo.data}}get value(){return this._def.value}}ZodLiteral.create=(Au,lo)=>new ZodLiteral({value:Au,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(lo)});function createZodEnum(Au,lo){return new ZodEnum({values:Au,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(lo)})}class ZodEnum extends ZodType{_parse(lo){if(typeof lo.data!="string"){const $u=this._getOrReturnCtx(lo),Ru=this._def.values;return addIssueToContext($u,{expected:util.joinValues(Ru),received:$u.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(lo.data)){const $u=this._getOrReturnCtx(lo),Ru=this._def.values;return addIssueToContext($u,{received:$u.data,code:ZodIssueCode.invalid_enum_value,options:Ru}),INVALID}return OK(lo.data)}get options(){return this._def.values}get enum(){const lo={};for(const $u of this._def.values)lo[$u]=$u;return lo}get Values(){const lo={};for(const $u of this._def.values)lo[$u]=$u;return lo}get Enum(){const lo={};for(const $u of this._def.values)lo[$u]=$u;return lo}extract(lo,$u=this._def){return ZodEnum.create(lo,{...this._def,...$u})}exclude(lo,$u=this._def){return ZodEnum.create(this.options.filter(Ru=>!lo.includes(Ru)),{...this._def,...$u})}}ZodEnum.create=createZodEnum;class ZodNativeEnum extends ZodType{_parse(lo){const $u=util.getValidEnumValues(this._def.values),Ru=this._getOrReturnCtx(lo);if(Ru.parsedType!==ZodParsedType.string&&Ru.parsedType!==ZodParsedType.number){const Iu=util.objectValues($u);return addIssueToContext(Ru,{expected:util.joinValues(Iu),received:Ru.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(util.getValidEnumValues(this._def.values))),!this._cache.has(lo.data)){const Iu=util.objectValues($u);return addIssueToContext(Ru,{received:Ru.data,code:ZodIssueCode.invalid_enum_value,options:Iu}),INVALID}return OK(lo.data)}get enum(){return this._def.values}}ZodNativeEnum.create=(Au,lo)=>new ZodNativeEnum({values:Au,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(lo)});class ZodPromise extends ZodType{unwrap(){return this._def.type}_parse(lo){const{ctx:$u}=this._processInputParams(lo);if($u.parsedType!==ZodParsedType.promise&&$u.common.async===!1)return addIssueToContext($u,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:$u.parsedType}),INVALID;const Ru=$u.parsedType===ZodParsedType.promise?$u.data:Promise.resolve($u.data);return OK(Ru.then(Iu=>this._def.type.parseAsync(Iu,{path:$u.path,errorMap:$u.common.contextualErrorMap})))}}ZodPromise.create=(Au,lo)=>new ZodPromise({type:Au,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(lo)});class ZodEffects extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(lo){const{status:$u,ctx:Ru}=this._processInputParams(lo),Iu=this._def.effect||null,Pu={addIssue:Ou=>{addIssueToContext(Ru,Ou),Ou.fatal?$u.abort():$u.dirty()},get path(){return Ru.path}};if(Pu.addIssue=Pu.addIssue.bind(Pu),Iu.type==="preprocess"){const Ou=Iu.transform(Ru.data,Pu);if(Ru.common.async)return Promise.resolve(Ou).then(async Mu=>{if($u.value==="aborted")return INVALID;const Du=await this._def.schema._parseAsync({data:Mu,path:Ru.path,parent:Ru});return Du.status==="aborted"?INVALID:Du.status==="dirty"||$u.value==="dirty"?DIRTY(Du.value):Du});{if($u.value==="aborted")return INVALID;const Mu=this._def.schema._parseSync({data:Ou,path:Ru.path,parent:Ru});return Mu.status==="aborted"?INVALID:Mu.status==="dirty"||$u.value==="dirty"?DIRTY(Mu.value):Mu}}if(Iu.type==="refinement"){const Ou=Mu=>{const Du=Iu.refinement(Mu,Pu);if(Ru.common.async)return Promise.resolve(Du);if(Du instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return Mu};if(Ru.common.async===!1){const Mu=this._def.schema._parseSync({data:Ru.data,path:Ru.path,parent:Ru});return Mu.status==="aborted"?INVALID:(Mu.status==="dirty"&&$u.dirty(),Ou(Mu.value),{status:$u.value,value:Mu.value})}else return this._def.schema._parseAsync({data:Ru.data,path:Ru.path,parent:Ru}).then(Mu=>Mu.status==="aborted"?INVALID:(Mu.status==="dirty"&&$u.dirty(),Ou(Mu.value).then(()=>({status:$u.value,value:Mu.value}))))}if(Iu.type==="transform")if(Ru.common.async===!1){const Ou=this._def.schema._parseSync({data:Ru.data,path:Ru.path,parent:Ru});if(!isValid(Ou))return INVALID;const Mu=Iu.transform(Ou.value,Pu);if(Mu instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:$u.value,value:Mu}}else return this._def.schema._parseAsync({data:Ru.data,path:Ru.path,parent:Ru}).then(Ou=>isValid(Ou)?Promise.resolve(Iu.transform(Ou.value,Pu)).then(Mu=>({status:$u.value,value:Mu})):INVALID);util.assertNever(Iu)}}ZodEffects.create=(Au,lo,$u)=>new ZodEffects({schema:Au,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:lo,...processCreateParams($u)});ZodEffects.createWithPreprocess=(Au,lo,$u)=>new ZodEffects({schema:lo,effect:{type:"preprocess",transform:Au},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams($u)});class ZodOptional extends ZodType{_parse(lo){return this._getType(lo)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(lo)}unwrap(){return this._def.innerType}}ZodOptional.create=(Au,lo)=>new ZodOptional({innerType:Au,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(lo)});class ZodNullable extends ZodType{_parse(lo){return this._getType(lo)===ZodParsedType.null?OK(null):this._def.innerType._parse(lo)}unwrap(){return this._def.innerType}}ZodNullable.create=(Au,lo)=>new ZodNullable({innerType:Au,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(lo)});class ZodDefault extends ZodType{_parse(lo){const{ctx:$u}=this._processInputParams(lo);let Ru=$u.data;return $u.parsedType===ZodParsedType.undefined&&(Ru=this._def.defaultValue()),this._def.innerType._parse({data:Ru,path:$u.path,parent:$u})}removeDefault(){return this._def.innerType}}ZodDefault.create=(Au,lo)=>new ZodDefault({innerType:Au,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof lo.default=="function"?lo.default:()=>lo.default,...processCreateParams(lo)});class ZodCatch extends ZodType{_parse(lo){const{ctx:$u}=this._processInputParams(lo),Ru={...$u,common:{...$u.common,issues:[]}},Iu=this._def.innerType._parse({data:Ru.data,path:Ru.path,parent:{...Ru}});return isAsync(Iu)?Iu.then(Pu=>({status:"valid",value:Pu.status==="valid"?Pu.value:this._def.catchValue({get error(){return new ZodError(Ru.common.issues)},input:Ru.data})})):{status:"valid",value:Iu.status==="valid"?Iu.value:this._def.catchValue({get error(){return new ZodError(Ru.common.issues)},input:Ru.data})}}removeCatch(){return this._def.innerType}}ZodCatch.create=(Au,lo)=>new ZodCatch({innerType:Au,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof lo.catch=="function"?lo.catch:()=>lo.catch,...processCreateParams(lo)});class ZodNaN extends ZodType{_parse(lo){if(this._getType(lo)!==ZodParsedType.nan){const Ru=this._getOrReturnCtx(lo);return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:Ru.parsedType}),INVALID}return{status:"valid",value:lo.data}}}ZodNaN.create=Au=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(Au)});class ZodBranded extends ZodType{_parse(lo){const{ctx:$u}=this._processInputParams(lo),Ru=$u.data;return this._def.type._parse({data:Ru,path:$u.path,parent:$u})}unwrap(){return this._def.type}}class ZodPipeline extends ZodType{_parse(lo){const{status:$u,ctx:Ru}=this._processInputParams(lo);if(Ru.common.async)return(async()=>{const Pu=await this._def.in._parseAsync({data:Ru.data,path:Ru.path,parent:Ru});return Pu.status==="aborted"?INVALID:Pu.status==="dirty"?($u.dirty(),DIRTY(Pu.value)):this._def.out._parseAsync({data:Pu.value,path:Ru.path,parent:Ru})})();{const Iu=this._def.in._parseSync({data:Ru.data,path:Ru.path,parent:Ru});return Iu.status==="aborted"?INVALID:Iu.status==="dirty"?($u.dirty(),{status:"dirty",value:Iu.value}):this._def.out._parseSync({data:Iu.value,path:Ru.path,parent:Ru})}}static create(lo,$u){return new ZodPipeline({in:lo,out:$u,typeName:ZodFirstPartyTypeKind.ZodPipeline})}}class ZodReadonly extends ZodType{_parse(lo){const $u=this._def.innerType._parse(lo),Ru=Iu=>(isValid(Iu)&&(Iu.value=Object.freeze(Iu.value)),Iu);return isAsync($u)?$u.then(Iu=>Ru(Iu)):Ru($u)}unwrap(){return this._def.innerType}}ZodReadonly.create=(Au,lo)=>new ZodReadonly({innerType:Au,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(lo)});var ZodFirstPartyTypeKind;(function(Au){Au.ZodString="ZodString",Au.ZodNumber="ZodNumber",Au.ZodNaN="ZodNaN",Au.ZodBigInt="ZodBigInt",Au.ZodBoolean="ZodBoolean",Au.ZodDate="ZodDate",Au.ZodSymbol="ZodSymbol",Au.ZodUndefined="ZodUndefined",Au.ZodNull="ZodNull",Au.ZodAny="ZodAny",Au.ZodUnknown="ZodUnknown",Au.ZodNever="ZodNever",Au.ZodVoid="ZodVoid",Au.ZodArray="ZodArray",Au.ZodObject="ZodObject",Au.ZodUnion="ZodUnion",Au.ZodDiscriminatedUnion="ZodDiscriminatedUnion",Au.ZodIntersection="ZodIntersection",Au.ZodTuple="ZodTuple",Au.ZodRecord="ZodRecord",Au.ZodMap="ZodMap",Au.ZodSet="ZodSet",Au.ZodFunction="ZodFunction",Au.ZodLazy="ZodLazy",Au.ZodLiteral="ZodLiteral",Au.ZodEnum="ZodEnum",Au.ZodEffects="ZodEffects",Au.ZodNativeEnum="ZodNativeEnum",Au.ZodOptional="ZodOptional",Au.ZodNullable="ZodNullable",Au.ZodDefault="ZodDefault",Au.ZodCatch="ZodCatch",Au.ZodPromise="ZodPromise",Au.ZodBranded="ZodBranded",Au.ZodPipeline="ZodPipeline",Au.ZodReadonly="ZodReadonly"})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));const stringType=ZodString.create,numberType=ZodNumber.create;ZodBigInt.create;const booleanType=ZodBoolean.create;ZodDate.create;const anyType=ZodAny.create,unknownType=ZodUnknown.create;ZodNever.create;const arrayType=ZodArray.create,objectType=ZodObject.create,unionType=ZodUnion.create,intersectionType=ZodIntersection.create;ZodTuple.create;const recordType=ZodRecord.create,lazyType=ZodLazy.create,literalType=ZodLiteral.create,enumType=ZodEnum.create;ZodPromise.create;ZodOptional.create;ZodNullable.create;const coerce={string:(Au=>ZodString.create({...Au,coerce:!0})),number:(Au=>ZodNumber.create({...Au,coerce:!0})),boolean:(Au=>ZodBoolean.create({...Au,coerce:!0})),bigint:(Au=>ZodBigInt.create({...Au,coerce:!0})),date:(Au=>ZodDate.create({...Au,coerce:!0}))};class A2uiError extends Error{constructor(lo,$u="UNKNOWN_ERROR"){super(lo),this.name=this.constructor.name,this.code=$u,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}class A2uiValidationError extends A2uiError{constructor(lo,$u,Ru="VALIDATION_ERROR"){super(lo,Ru),this.details=$u}}class A2uiDataError extends A2uiError{constructor(lo,$u){super(lo,"DATA_ERROR"),this.path=$u}}class A2uiExpressionError extends A2uiError{constructor(lo,$u,Ru){super(lo,"EXPRESSION_ERROR"),this.expression=$u,this.details=Ru}}class A2uiStateError extends A2uiError{constructor(lo){super(lo,"STATE_ERROR")}}class A2uiCatalogError extends A2uiError{constructor(lo,$u="CATALOG_ERROR"){super(lo,$u)}}class A2uiIntegrityError extends A2uiValidationError{constructor(lo,$u,Ru="INTEGRITY_ERROR"){super(lo,$u,Ru),this.name="A2uiIntegrityError"}}class A2uiRecursionError extends A2uiValidationError{constructor(lo,$u,Ru="RECURSION_ERROR"){super(lo,$u,Ru),this.name="A2uiRecursionError"}}var RpcErrorCode;(function(Au){Au.INVALID_FUNCTION_CALL="INVALID_FUNCTION_CALL",Au.EXECUTION_ERROR="EXECUTION_ERROR",Au.UNKNOWN_FUNCTION="UNKNOWN_FUNCTION",Au.UNKNOWN_ERROR="UNKNOWN_ERROR",Au.TIMEOUT="TIMEOUT",Au.CANCELLED="CANCELLED",Au.DISPOSED="DISPOSED",Au.DUPLICATE="DUPLICATE",Au.NO_LISTENER="NO_LISTENER"})(RpcErrorCode||(RpcErrorCode={}));class A2uiRpcError extends A2uiError{constructor(lo,$u=RpcErrorCode.UNKNOWN_ERROR,Ru,Iu){const Pu=$u||RpcErrorCode.UNKNOWN_ERROR;super(`[${Pu}] ${lo}`,Pu),this.functionCallId=Ru,this.details=Iu,this.name="A2uiRpcError"}}function markChildRef(Au,lo){return Au._def.a2uiChildRef=lo,Au}function childRefKindOf(Au){return Au?._def?.a2uiChildRef}const MAX_FUNCTION_CALL_ARGS=1e3;objectType({component:stringType().describe("The type name of the component."),id:lazyType(()=>ComponentIdSchema$2).optional(),weight:numberType().optional()}).passthrough().describe("A generic A2UI component definition.");const ComponentIdSchema$2=markChildRef(stringType().describe("REF:common_types.json#/$defs/ComponentId|The unique identifier for a component, used for both definitions and references within the same surface."),"component-id"),DataBindingSchema$2=objectType({path:stringType().describe("A JSON Pointer path to a value in the data model.")}).describe("REF:common_types.json#/$defs/DataBinding"),FunctionCallSchema$2=objectType({call:stringType().describe("The name of the function to call."),args:recordType(stringType(),unknownType()).describe("Arguments passed to the function.").optional(),returnType:enumType(["string","number","boolean","array","object","any","void"]).describe("The expected return type of the function call.").optional(),catalogId:stringType().describe("The catalog ID for this function, overriding any surface-level default catalogId.").optional()}).describe("REF:common_types.json#/$defs/FunctionCall|Invokes a named function, combining common function properties with the catalog function definition."),DynamicStringSchema$2=unionType([stringType(),DataBindingSchema$2,FunctionCallSchema$2]).describe("REF:common_types.json#/$defs/DynamicString|Represents a string"),DynamicBooleanSchema$2=unionType([booleanType(),DataBindingSchema$2,FunctionCallSchema$2]).describe("REF:common_types.json#/$defs/DynamicBoolean|A boolean value that can be a literal, a path, or a function call returning a boolean."),AccessibilityAttributesSchema$2=objectType({label:DynamicStringSchema$2.optional(),description:DynamicStringSchema$2.optional(),live:enumType(["off","polite","assertive"]).default("off").describe("Controls screen reader announcements for dynamic updates (WAI-ARIA aria-live). 'polite' waits for user pause; 'assertive' interrupts immediately for alerts.").optional(),hidden:DynamicBooleanSchema$2.optional()}).describe("REF:common_types.json#/$defs/AccessibilityAttributes|Attributes to enhance accessibility when using assistive technologies like screen readers or model understanding."),ExtensionsSchema$1=recordType(stringType(),unknownType()).superRefine((Au,lo)=>{for(const $u in Au)$u.match(/^[\p{XID_Start}_][\p{XID_Continue}]*$/u)||lo.addIssue({path:[$u],code:ZodIssueCode.custom,message:`Invalid extension key "${$u}": Keys MUST be Unicode identifiers (UAX #31).`})}).describe("REF:#/$defs/Extensions|Optional extension metadata. Keys MUST be Unicode identifiers (UAX #31). Keys starting with 'a2ui_' are reserved for official extensions.");objectType({id:ComponentIdSchema$2,accessibility:AccessibilityAttributesSchema$2.optional(),catalogId:stringType().describe("The catalog ID for this component, overriding any surface-level default catalogId.").optional(),metadata:objectType({extensions:ExtensionsSchema$1.optional()}).strict().describe("Optional component-level metadata for vendor extensions.").optional()}).describe("REF:common_types.json#/$defs/ComponentCommon");const ChildListSchema$1=markChildRef(unionType([arrayType(ComponentIdSchema$2).describe("A static list of child component IDs."),objectType({componentId:ComponentIdSchema$2,path:stringType().describe("The path to the list of component property objects in the data model.")}).describe("A template for generating a dynamic list of children.")]).describe("REF:common_types.json#/$defs/ChildList"),"child-list"),DynamicValueSchema$2=unionType([stringType(),numberType(),booleanType(),arrayType(unknownType()),DataBindingSchema$2,FunctionCallSchema$2,recordType(stringType(),unknownType()).refine(Au=>!Au||!("path"in Au)&&!("call"in Au))]).describe("REF:common_types.json#/$defs/DynamicValue|A value that can be a literal, a path, or a function call returning any type."),DynamicNumberSchema$2=unionType([numberType(),DataBindingSchema$2,FunctionCallSchema$2]).describe("REF:common_types.json#/$defs/DynamicNumber|Represents a value that can be either a literal number, a path to a number in the data model, or a function call returning a number."),DynamicStringListSchema$1=unionType([arrayType(stringType()),DataBindingSchema$2,FunctionCallSchema$2]).describe("REF:common_types.json#/$defs/DynamicStringList|Represents a value that can be either a literal array of strings, a path to a string array in the data model, or a function call returning a string array."),CheckRuleSchema$2=objectType({condition:unionType([DynamicBooleanSchema$2,DataBindingSchema$2,FunctionCallSchema$2]).describe("Path or function call evaluating to a structured validation result object."),message:stringType().describe("Optional fallback error message.").optional()}).describe("REF:common_types.json#/$defs/CheckRule|A single validation check rule applied to an input component. The condition function or path evaluates to a structured validation result object."),CheckableSchema=objectType({checks:arrayType(CheckRuleSchema$2).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional()}).describe("REF:common_types.json#/$defs/Checkable|Properties for components that support renderer-side checks."),ActionSchema$2=unionType([objectType({event:objectType({name:stringType().describe("The name of the action to be dispatched to the server."),context:recordType(stringType(),unknownType()).describe("A JSON object containing the key-value pairs for the action context. Values can be literals or paths. Use literal values unless the value must be dynamically bound to the data model. Do NOT use paths for static IDs.").optional()}).strict().describe("The event to dispatch to the server.")}).strict().describe("Triggers a server-side event."),objectType({functionCall:FunctionCallSchema$2}).strict().describe("Executes a local client-side function."),objectType({event:objectType({name:stringType().describe("The name of the action to be dispatched to the agent."),userMessage:DynamicStringSchema$2.optional(),context:recordType(stringType(),unknownType()).describe("A JSON object containing the key-value pairs for the action context. Values can be literals or paths. Use literal values unless the value must be dynamically bound to the data model. Do NOT use paths for static IDs.").optional()}).strict().describe("The event to dispatch to the agent.")}).strict().describe("Triggers an agent-side event."),objectType({functionCall:FunctionCallSchema$2}).strict().describe("Executes a renderer or agent-side function.")]).describe("REF:common_types.json#/$defs/Action|Defines an interaction handler that can either trigger an agent-side event or execute a local renderer-side function."),CallIdSchema$1=stringType().describe("REF:common_types.json#/$defs/CallId|The unique identifier for a function call.");objectType({call:stringType().describe("The name of the function to call."),catalogId:stringType().describe("The catalog ID for this function, overriding any surface-level default catalogId.").optional()}).describe("REF:common_types.json#/$defs/FunctionCommon|Baseline envelope properties common to all function calls. Function-specific argument schemas (\\'args\\') are defined individually by each function in the active catalog.");objectType({call:literalType("@index"),args:objectType({offset:DynamicNumberSchema$2.optional()}).strict().optional()}).strict().describe("REF:common_types.json#/$defs/IndexSystemFunction|Returns the 0-based index of the current item when rendering a dynamic list from a template. This function MUST ONLY be available when evaluating template items within a list context.");objectType({component:literalType("Surface").optional(),child:literalType("root").optional()}).strict().describe("REF:common_types.json#/$defs/Surface|The reserved canonical container component representing an A2UI surface. The Surface component is immutable and always has \\'child\\': \\'root\\'.");objectType({functionCallId:CallIdSchema$1,value:unknownType().describe("The return value of the function.").optional(),error:objectType({code:stringType(),message:stringType()}).strict().describe("An error object indicating failure of the function execution.").optional()}).strict().describe("REF:common_types.json#/$defs/FunctionResponse|The return response matching a callAgentFunction or callRendererFunction invocation.");const SEMVER_REGEX=/^[vV]?(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*))?(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;function normalizeVersionString(Au){if(!Au||typeof Au!="string")return"";const lo=Au.trim().replace(/^[vV]/,""),$u=lo.indexOf("-"),Ru=lo.indexOf("+");let Iu=lo.length;return $u!==-1&&Ru!==-1?Iu=Math.min($u,Ru):$u!==-1?Iu=$u:Ru!==-1&&(Iu=Ru),`${lo.slice(0,Iu).replace(/_/g,".")}${lo.slice(Iu)}`}function parseSemVer(Au){if(!Au||typeof Au!="string")return null;const lo=Au.trim().match(SEMVER_REGEX);return lo?{major:parseInt(lo[1],10),minor:parseInt(lo[2],10),patch:lo[3]!==void 0?parseInt(lo[3],10):0,prerelease:lo[4]?lo[4].split("."):[],build:lo[5]?lo[5].split("."):[]}:null}function toSemVer(Au){if(!Au)return null;if(typeof Au=="object"){const lo=Au;return typeof lo.major!="number"||!Number.isInteger(lo.major)||lo.major<0||typeof lo.minor=="number"&&(!Number.isInteger(lo.minor)||lo.minor<0)||typeof lo.patch=="number"&&(!Number.isInteger(lo.patch)||lo.patch<0)?null:{major:lo.major,minor:typeof lo.minor=="number"?lo.minor:0,patch:typeof lo.patch=="number"?lo.patch:0,prerelease:Array.isArray(lo.prerelease)?lo.prerelease:[],build:Array.isArray(lo.build)?lo.build:[]}}return parseSemVer(normalizeVersionString(Au))}function toCanonicalVersion(Au){if(!Au)return null;const lo=toSemVer(Au);if(!lo)return null;if(lo.patch===0&&lo.prerelease.length===0&&lo.build.length===0)return`${lo.major}.${lo.minor}`;const $u=lo.prerelease.length>0?`-${lo.prerelease.join(".")}`:"",Ru=lo.build.length>0?`+${lo.build.join(".")}`:"";return`${lo.major}.${lo.minor}.${lo.patch}${$u}${Ru}`}function comparePrereleaseId(Au,lo){const $u=/^\d+$/.test(Au),Ru=/^\d+$/.test(lo);return $u&&Ru?Au.length!==lo.length?Au.length-lo.length:Au<lo?-1:Au>lo?1:0:$u?-1:Ru?1:Au<lo?-1:Au>lo?1:0}function comparePrereleaseLists(Au,lo){if(Au.length===0&&lo.length===0)return 0;if(Au.length===0)return 1;if(lo.length===0)return-1;const $u=Math.min(Au.length,lo.length);for(let Ru=0;Ru<$u;Ru++){const Iu=comparePrereleaseId(Au[Ru],lo[Ru]);if(Iu!==0)return Iu}return Au.length-lo.length}function compareSemVer(Au,lo){const $u=toSemVer(Au),Ru=toSemVer(lo);return!$u&&!Ru?0:$u?Ru?$u.major!==Ru.major?$u.major-Ru.major:$u.minor!==Ru.minor?$u.minor-Ru.minor:$u.patch!==Ru.patch?$u.patch-Ru.patch:comparePrereleaseLists($u.prerelease,Ru.prerelease):1:-1}function isAtLeastVersion(Au,lo){if(!Au)return!1;const $u=toSemVer(Au),Ru=toSemVer(lo);return!$u||!Ru?!1:compareSemVer($u,Ru)>=0}const UAX31_IDENTIFIER=/^[\p{XID_Start}_][\p{XID_Continue}]*$/u;function isValidUax31Identifier(Au){if(!Au)return!1;const lo=Au.startsWith("@")?Au.slice(1):Au;return UAX31_IDENTIFIER.test(lo)}function assertUax31Identifier(Au,lo){if(!isValidUax31Identifier(Au))throw new A2uiCatalogError(`Invalid UAX #31 ${lo}`)}const DEFAULT_PROTOCOL_VERSION="0.9",COMMON_TYPE_SCHEMAS={DynamicString:DynamicStringSchema$2,DynamicNumber:DynamicNumberSchema$2,DynamicBoolean:DynamicBooleanSchema$2,DynamicStringList:DynamicStringListSchema$1,DynamicValue:DynamicValueSchema$2,ComponentId:ComponentIdSchema$2,ChildList:ChildListSchema$1,Action:ActionSchema$2,CheckRule:CheckRuleSchema$2,Checkable:CheckableSchema,AccessibilityAttributes:AccessibilityAttributesSchema$2,DataBinding:DataBindingSchema$2,FunctionCall:FunctionCallSchema$2};function resolveJsonPointer(Au,lo){if(!lo.startsWith("#/"))return;const $u=lo.slice(2).split("/").map(Iu=>Iu.replace(/~1/g,"/").replace(/~0/g,"~"));let Ru=Au;for(const Iu of $u)if(Ru&&typeof Ru=="object"&&Iu in Ru)Ru=Ru[Iu];else return;return typeof Ru=="object"&&Ru!==null?Ru:void 0}function resolveProtocolRef(Au){const lo=Au.split(/#\/(?:\$defs|definitions)\//)[1];return lo?COMMON_TYPE_SCHEMAS[lo]:void 0}function convertEnumToZod(Au){return Au.length===0?unknownType():Au.every(lo=>typeof lo=="string")?enumType(Au):Au.length===1?literalType(Au[0]):unionType(Au.map(lo=>literalType(lo)))}function canonicalJsonStringify(Au){return Au===null||typeof Au!="object"?JSON.stringify(Au):Array.isArray(Au)?`[${Au.map(canonicalJsonStringify).join(",")}]`:`{${Object.keys(Au).sort().map(Ru=>`${JSON.stringify(Ru)}:${canonicalJsonStringify(Au[Ru])}`).join(",")}}`}function finalizePropertyZod(Au,lo,$u,Ru,Iu){let Pu=Au;if(lo.not&&typeof lo.not=="object"){const Ou=convertPropertyToZod(lo.not,$u,new Set(Ru),Iu);Pu=Pu.refine(Mu=>!Ou.safeParse(Mu).success,{message:'Value matched prohibited "not" schema'})}return lo.default!==void 0&&(Pu=Pu.default(lo.default)),typeof lo.description=="string"&&(Pu=Pu.describe(lo.description)),Pu}function convertRefToZod(Au,lo,$u,Ru,Iu){const Pu=resolveProtocolRef(Au);if(Pu){const Ou=Au.split(/#\/(?:\$defs|definitions)\//)[1],Mu=typeof lo.description=="string"?`REF:common_types.json#/$defs/${Ou}|${lo.description}`:Pu.description;return Mu?Pu.describe(Mu):Pu}if($u&&Au.startsWith("#/")){const Ou=resolveJsonPointer($u,Au);if(!Ou)return unknownType().superRefine((Du,Lu)=>{Lu.addIssue({code:ZodIssueCode.custom,message:`Unresolvable schema reference: '${Au}'`})});if(Ru.has(Au)){let Du=Iu.get(Au);return lazyType(()=>(Du||(Du=Iu.get(Au)??convertPropertyToZod(Ou,$u,new Set([Au]),Iu),Iu.set(Au,Du)),Du))}let Mu=Iu.get(Au);if(!Mu){const Du=new Set(Ru);Du.add(Au),Mu=convertPropertyToZod(Ou,$u,Du,Iu),Iu.set(Au,Mu)}return typeof lo.description=="string"&&(Mu=Mu.describe(lo.description)),Mu}}function convertUnionToZod(Au,lo,$u,Ru){const Iu=Array.isArray(Au.oneOf),Ou=(Au.oneOf||Au.anyOf).filter(Fu=>typeof Fu=="object"&&Fu!==null);if(Ou.length===0)return;const Mu=Ou.find(Fu=>Array.isArray(Fu.enum)),Du=Ou.some(Fu=>typeof Fu.$ref=="string"&&Fu.$ref.includes("DataBinding")),Lu=Ou.map(Fu=>convertPropertyToZod(Fu,lo,new Set($u),Ru));let Bu;if(Lu.length===1)Bu=Lu[0];else{const Fu=unionType([Lu[0],Lu[1],...Lu.slice(2)]);Bu=Iu?anyType().superRefine((zu,Uu)=>{let Hu=0;for(const Vu of Lu)if(Vu.safeParse(zu).success&&++Hu>1){Uu.addIssue({code:ZodIssueCode.custom,message:"Value matched more than one schema in oneOf"});return}}).pipe(Fu):Fu}Au.default!==void 0&&(Bu=Bu.default(Au.default));const ju=(typeof Au.description=="string"?Au.description:void 0)||(Mu&&Du?"REF:common_types.json#/$defs/DynamicString":void 0);return ju?Bu.describe(ju):Bu}function convertPropertyToZod(Au,lo,$u=new Set,Ru=new Map){if(!Au||typeof Au!="object")return unknownType();if(Au.$ref&&typeof Au.$ref=="string"){const Iu=convertRefToZod(Au.$ref,Au,lo,$u,Ru);if(Iu)return Iu}if(Array.isArray(Au.oneOf)||Array.isArray(Au.anyOf)){const Iu=convertUnionToZod(Au,lo,$u,Ru);if(Iu)return Iu}if(Au.const!==void 0){const Iu=literalType(Au.const);return finalizePropertyZod(Iu,Au,lo,$u,Ru)}if(Array.isArray(Au.enum)&&Au.enum.length>0){const Iu=convertEnumToZod(Au.enum);return finalizePropertyZod(Iu,Au,lo,$u,Ru)}if(Au.type==="array"){const Iu=Au.items&&typeof Au.items=="object"?convertPropertyToZod(Au.items,lo,new Set($u),Ru):unknownType();let Pu=arrayType(Iu);return typeof Au.minItems=="number"&&(Pu=Pu.min(Au.minItems)),typeof Au.maxItems=="number"&&(Pu=Pu.max(Au.maxItems)),Au.uniqueItems===!0&&(Pu=Pu.refine(Ou=>new Set(Ou.map(canonicalJsonStringify)).size===Ou.length,{message:"Array items must be unique"})),finalizePropertyZod(Pu,Au,lo,$u,Ru)}switch(Au.type){case"string":{let Iu=stringType();if(typeof Au.minLength=="number"&&(Iu=Iu.min(Au.minLength)),typeof Au.maxLength=="number"&&(Iu=Iu.max(Au.maxLength)),typeof Au.pattern=="string")try{Iu=Iu.regex(new RegExp(Au.pattern,"u"))}catch{}return finalizePropertyZod(Iu,Au,lo,$u,Ru)}case"integer":case"number":{let Iu=Au.type==="integer"?numberType().int():numberType();return typeof Au.minimum=="number"&&(Iu=Iu.min(Au.minimum)),typeof Au.maximum=="number"&&(Iu=Iu.max(Au.maximum)),typeof Au.exclusiveMinimum=="number"&&(Iu=Iu.gt(Au.exclusiveMinimum)),typeof Au.exclusiveMaximum=="number"&&(Iu=Iu.lt(Au.exclusiveMaximum)),typeof Au.multipleOf=="number"&&(Iu=Iu.multipleOf(Au.multipleOf)),finalizePropertyZod(Iu,Au,lo,$u,Ru)}case"boolean":return finalizePropertyZod(booleanType(),Au,lo,$u,Ru);case"object":{const Iu=Au.properties;let Pu;if(typeof Iu=="object"&&Iu!==null){const Ou=Array.isArray(Au.required)?new Set(Au.required.filter(Lu=>typeof Lu=="string")):new Set,Mu=objectType(convertPropertiesToShape(Iu,Ou,!1,lo,$u,Ru));Pu=Au.additionalProperties===!1||Au.unevaluatedProperties===!1?Mu.strict():Mu.passthrough()}else Pu=recordType(unknownType());return finalizePropertyZod(Pu,Au,lo,$u,Ru)}default:return finalizePropertyZod(unknownType(),Au,lo,$u,Ru)}}function convertPropertiesToShape(Au,lo,$u=!1,Ru,Iu,Pu=new Map){const Ou={};for(const[Mu,Du]of Object.entries(Au)){if($u&&(Mu==="component"||Mu==="id"))continue;const Lu=convertPropertyToZod(typeof Du=="object"&&Du!==null?Du:{},Ru,Iu?new Set(Iu):new Set,Pu);Ou[Mu]=lo.has(Mu)?Lu:Lu.optional()}return Ou}function collectComponentSubSchemas(Au,lo,$u=new Set){const Ru=[];if(!Au||typeof Au!="object")return Ru;if(Array.isArray(Au.allOf)){for(const Iu of Au.allOf)if(!(!Iu||typeof Iu!="object"))if(typeof Iu.$ref=="string"){const Pu=Iu.$ref;if(Pu.includes("common_types.json")&&Pu.includes("ComponentCommon"))Ru.push({properties:{accessibility:AccessibilityAttributesSchema$2.optional()}});else if(Pu.startsWith("#/")&&!$u.has(Pu)){$u.add(Pu);const Ou=resolveJsonPointer(lo,Pu);Ou&&Ru.push(...collectComponentSubSchemas(Ou,lo,$u))}}else Ru.push(...collectComponentSubSchemas(Iu,lo,$u))}return Au.properties&&Ru.push(Au),Ru}function convertComponentJsonSchemaToZod(Au,lo,$u=!0,Ru=new Map){const Iu={},Pu=collectComponentSubSchemas(Au,lo),Ou=new Set;for(const Lu of Pu)Array.isArray(Lu.required)&&Lu.required.forEach(Bu=>{typeof Bu=="string"&&Ou.add(Bu)});for(const Lu of Pu){const Bu=convertPropertiesToShape(Lu.properties||{},Ou,$u,lo,void 0,Ru);Object.assign(Iu,Bu)}const Mu=objectType(Iu);return Au.unevaluatedProperties===!0||typeof Au.unevaluatedProperties=="object"&&Au.unevaluatedProperties!==null||Au.additionalProperties===!0||typeof Au.additionalProperties=="object"&&Au.additionalProperties!==null?Mu.passthrough():Mu.strict()}function convertFunctionArgsJsonSchemaToZod(Au,lo,$u=new Map){const Ru=new Set(Array.isArray(Au.required)?Au.required.filter(Mu=>typeof Mu=="string"):[]),Iu=convertPropertiesToShape(Au.properties||{},Ru,!1,lo,void 0,$u),Pu=objectType(Iu);return Au.unevaluatedProperties===!0||typeof Au.unevaluatedProperties=="object"&&Au.unevaluatedProperties!==null||Au.additionalProperties===!0||typeof Au.additionalProperties=="object"&&Au.additionalProperties!==null?Pu.passthrough():Pu.strict()}function parseFunctionDefinitions(Au,lo,$u,Ru=!1){const Iu=[];if(!Au)return Iu;const Pu=new Map,Ou=(Mu,Du)=>{if(Ru&&(assertUax31Identifier(Mu,`function identifier: '${Mu}'`),Du&&typeof Du=="object"))for(const Lu of Object.keys(Du))assertUax31Identifier(Lu,`argument identifier: '${Lu}' in function '${Mu}'`)};if(Array.isArray(Au)){for(const Mu of Au)if(Mu&&typeof Mu=="object"&&typeof Mu.name=="string"){if(Ou(Mu.name,Mu.parameters),$u&&!$u.has(Mu.name))continue;const Du=Mu.parameters&&typeof Mu.parameters=="object"?convertFunctionArgsJsonSchemaToZod(Mu.parameters,lo,Pu):recordType(unknownType());Iu.push({name:Mu.name,description:typeof Mu.description=="string"?Mu.description:void 0,returnType:typeof Mu.returnType=="string"?Mu.returnType:"any",allowedCallers:Mu.allowedCallers,requiresUserActivation:Mu.requiresUserActivation,schema:Du})}return Iu}if(typeof Au=="object"&&Au!==null)for(const[Mu,Du]of Object.entries(Au)){const Lu=Du&&typeof Du=="object"?Du:{};if(Ou(Mu,Lu.properties&&typeof Lu.properties=="object"?Lu.properties:Lu.parameters),$u&&!$u.has(Mu)||!Du||typeof Du!="object")continue;const Bu=Du,ju=Bu.properties;let Fu=ju?.args??Bu.args??Bu.parameters;!Fu&&ju&&!("call"in ju)&&!("function"in ju)?Fu=Bu:Fu&&typeof Fu=="object"&&!("properties"in Fu)&&!("type"in Fu)&&(Fu={type:"object",properties:Fu,required:Bu.required,additionalProperties:Bu.additionalProperties});const zu=Fu&&typeof Fu=="object"?convertFunctionArgsJsonSchemaToZod(Fu,lo,Pu):recordType(unknownType()),Uu=(typeof Bu.returnType=="string"?Bu.returnType:void 0)??(typeof ju?.returnType?.const=="string"?(ju?.returnType).const:"any"),Hu=Bu.allowedCallers??ju?.allowedCallers?.const,Vu=Bu.requiresUserActivation??ju?.requiresUserActivation?.const;Iu.push({name:Mu,description:typeof Bu.description=="string"?Bu.description:void 0,returnType:Uu,allowedCallers:Hu,requiresUserActivation:Vu,schema:zu})}return Iu}function extractPermittedNames(Au,lo){if(!Array.isArray(Au))return;const $u=new Set;for(const Ru of Au)if(typeof Ru?.$ref=="string"&&Ru.$ref.startsWith(lo)){const Pu=Ru.$ref.slice(lo.length).replace(/~([01])/g,(Ou,Mu)=>Mu==="1"?"/":"~");$u.add(Pu)}return $u}function parseCatalogComponents(Au,lo,$u,Ru){const Iu=[],Pu=new Map;for(const[Ou,Mu]of Object.entries(Au)){const Du=Mu||{};if($u){assertUax31Identifier(Ou,`component identifier: '${Ou}'`);const Bu=Du.properties;if(Bu&&typeof Bu=="object")for(const ju of Object.keys(Bu))assertUax31Identifier(ju,`property identifier: '${ju}' in component '${Ou}'`)}if(Ru&&!Ru.has(Ou))continue;const Lu=convertComponentJsonSchemaToZod(Du,lo,!0,Pu);Iu.push({name:Ou,schema:Lu,allowedParents:Array.isArray(Du.allowedParents)?Du.allowedParents.filter(Bu=>typeof Bu=="string"):void 0,allowedChildren:Array.isArray(Du.allowedChildren)?Du.allowedChildren.filter(Bu=>typeof Bu=="string"):void 0})}return Iu}function parseThemeSchema(Au,lo){const $u=Au.theme??Au.themeSchema??Au.styles??lo?.theme;if($u&&typeof $u=="object")return convertComponentJsonSchemaToZod($u,Au,!1)}function loadCatalogFromSchema(Au,lo){const $u=Au.catalogId??Au.$id??Au.id;if(!$u||typeof $u!="string")throw new Error("Catalog ID must be specified via catalog metadata ('catalogId' or '$id').");const Ru=Au.$defs,Iu=Ru?.anyComponent,Pu=extractPermittedNames(Iu?.oneOf,"#/components/"),Ou=lo??Au.protocolVersion??DEFAULT_PROTOCOL_VERSION,Mu=isAtLeastVersion(Ou,"1.0"),Du=Au.components??{},Lu=parseCatalogComponents(Du,Au,Mu,Pu),Bu=Ru?.anyFunction,ju=extractPermittedNames(Bu?.oneOf,"#/functions/"),Fu=parseFunctionDefinitions(Au.functions,Au,ju,Mu),zu=parseThemeSchema(Au,Ru),Uu=typeof Au.instructions=="string"?Au.instructions:void 0;return new Catalog($u,Ou,Lu,Fu,zu,Uu)}const V08_STANDARD_DEFS={ComponentId:{description:"The unique identifier for a component, used for both definitions and references within the same surface.",type:"string"},TextItem:{additionalProperties:!1,description:"The value of the text field. This can be a literal string or a reference to a value in the data model ('path', e.g. '/user/name').",properties:{literalString:{type:"string"},path:{type:"string"}},type:"object"},UrlItem:{additionalProperties:!1,description:"The URL of the audio to be played. This can be a literal string ('literal') or a reference to a value in the data model ('path', e.g. '/song/url').",properties:{literalString:{type:"string"},path:{type:"string"}},type:"object"},AltTextItem:{additionalProperties:!1,description:"The alt text for the image. This can be a literal string ('literal') or a reference to a value in the data model ('path', e.g. '/thumbnail/altText').",properties:{literalString:{type:"string"},path:{type:"string"}},type:"object"},NameItem:{additionalProperties:!1,description:"The name of the icon to display. This can be a literal string or a reference to a value in the data model ('path', e.g. '/form/submit').",properties:{literalString:{enum:["accountCircle","add","arrowBack","arrowForward","attachFile","calendarToday","call","camera","check","close","delete","download","edit","event","error","favorite","favoriteOff","folder","help","home","info","locationOn","lock","lockOpen","mail","menu","moreVert","moreHoriz","notificationsOff","notifications","payment","person","phone","photo","print","refresh","search","send","settings","share","shoppingCart","star","starHalf","starOff","upload","visibility","visibilityOff","warning"],type:"string"},path:{type:"string"}},type:"object"},DescriptionItem:{additionalProperties:!1,description:"A description of the audio, such as a title or summary. This can be a literal string or a reference to a value in the data model ('path', e.g. '/song/title').",properties:{literalString:{type:"string"},path:{type:"string"}},type:"object"},ChildrenItem:{additionalProperties:!1,description:"Defines the children. Use 'explicitList' for a fixed set of children, or 'template' to generate children from a data list.",properties:{explicitList:{items:{type:"string"},type:"array"},template:{$ref:"#/$defs/TemplateItem",description:"A template for generating a dynamic list of children from a data model list. `componentId` is the component to use as a template, and `dataBinding` is the path to the map of components in the data model. Values in the map will define the list of children."}},type:"object"},TemplateItem:{additionalProperties:!1,description:"A template for generating a dynamic list of children from a data model list. `componentId` is the component to use as a template, and `dataBinding` is the path to the map of components in the data model. Values in the map will define the list of children.",properties:{componentId:{type:"string"},dataBinding:{type:"string"}},required:["componentId","dataBinding"],type:"object"},TabItemItem:{additionalProperties:!1,properties:{child:{type:"string"},title:{$ref:"#/$defs/TitleItem"}},required:["title","child"],type:"object"},TitleItem:{additionalProperties:!1,description:"The tab title. Defines the value as either a literal value or a path to data model value (e.g. '/options/title').",properties:{literalString:{type:"string"},path:{type:"string"}},type:"object"},ActionItem:{additionalProperties:!1,description:"The client-side action to be dispatched when the button is clicked. It includes the action's name and an optional context payload.",properties:{context:{items:{$ref:"#/$defs/ContextItem"},type:"array"},name:{type:"string"}},required:["name"],type:"object"},ContextItem:{additionalProperties:!1,properties:{key:{type:"string"},value:{$ref:"#/$defs/ValueItem",description:"Defines the value to be included in the context as either a literal value or a path to a data model value (e.g. '/user/name')."}},required:["key","value"],type:"object"},ValueItem:{additionalProperties:!1,description:"The current value of the slider. This can be a literal number ('literalNumber') or a reference to a value in the data model ('path', e.g. '/restaurant/cost').",properties:{literalNumber:{type:"number"},path:{type:"string"}},type:"object"},LabelItem:{additionalProperties:!1,description:"The label for the slider. This can be a literal string or a reference to a value in the data model ('path').",properties:{literalString:{type:"string"},path:{type:"string"}},type:"object"},OptionItem:{additionalProperties:!1,properties:{label:{$ref:"#/$defs/LabelItem",description:"The text to display for this option. This can be a literal string or a reference to a value in the data model (e.g. '/option/label')."},value:{description:"The value to be associated with this option when selected.",type:"string"}},required:["label","value"],type:"object"},SelectionItem:{additionalProperties:!1,description:"The currently selected values for the component. This can be a literal array of strings or a path to an array in the data model('path', e.g. '/hotel/options').",properties:{literalArray:{items:{type:"string"},type:"array"},path:{type:"string"}},type:"object"}},V09_CHILD_REF_OPTIONS={childRefNames:new Set(["ComponentId","Child","ChildComponentId"]),childListRefNames:new Set(["ChildList","TemplateChildList","ChildrenItem","TemplateItem"])},V09_STANDARD_DEFS={ComponentId:{type:"string",description:"The unique identifier for a component, used for both definitions and references within the same surface."},AccessibilityAttributes:{type:"object",description:"Attributes to enhance accessibility when using assistive technologies like screen readers.",properties:{label:{$ref:"#/$defs/DynamicString",description:"A short string, typically 1 to 3 words, used by assistive technologies to convey the purpose or intent of an element. For example, an input field might have an accessible label of 'User ID' or a button might be labeled 'Submit'."},description:{$ref:"#/$defs/DynamicString",description:"Additional information provided by assistive technologies about an element such as instructions, format requirements, or result of an action. For example, a mute button might have a label of 'Mute' and a description of 'Silences notifications about this conversation'."}}},ComponentCommon:{type:"object",properties:{id:{$ref:"#/$defs/ComponentId"},accessibility:{$ref:"#/$defs/AccessibilityAttributes"}},required:["id"]},ChildList:{oneOf:[{type:"array",items:{$ref:"#/$defs/ComponentId"},description:"A static list of child component IDs."},{type:"object",description:"A template for generating a dynamic list of children from a data model list. The `componentId` is the component to use as a template.",properties:{componentId:{$ref:"#/$defs/ComponentId"},path:{type:"string",description:"The path to the list of component property objects in the data model."}},required:["componentId","path"],additionalProperties:!1}]},DataBinding:{type:"object",properties:{path:{type:"string",description:"A JSON Pointer path to a value in the data model."}},required:["path"],additionalProperties:!1},DynamicValue:{description:"A value that can be a literal, a path, or a function call returning any type.",oneOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"array"},{$ref:"#/$defs/DataBinding"},{$ref:"#/$defs/FunctionCall"}]},DynamicString:{description:"Represents a string",oneOf:[{type:"string"},{$ref:"#/$defs/DataBinding"},{allOf:[{$ref:"#/$defs/FunctionCall"},{properties:{returnType:{const:"string"}}}]}]},DynamicNumber:{description:"Represents a value that can be either a literal number, a path to a number in the data model, or a function call returning a number.",oneOf:[{type:"number"},{$ref:"#/$defs/DataBinding"},{allOf:[{$ref:"#/$defs/FunctionCall"},{properties:{returnType:{const:"number"}}}]}]},DynamicBoolean:{description:"A boolean value that can be a literal, a path, or a function call returning a boolean.",oneOf:[{type:"boolean"},{$ref:"#/$defs/DataBinding"},{allOf:[{$ref:"#/$defs/FunctionCall"},{properties:{returnType:{const:"boolean"}}}]}]},DynamicStringList:{description:"Represents a value that can be either a literal array of strings, a path to a string array in the data model, or a function call returning a string array.",oneOf:[{type:"array",items:{type:"string"}},{$ref:"#/$defs/DataBinding"},{allOf:[{$ref:"#/$defs/FunctionCall"},{properties:{returnType:{const:"array"}}}]}]},FunctionCall:{type:"object",description:"Invokes a named function on the client.",properties:{call:{type:"string",description:"The name of the function to call."},args:{type:"object",description:"Arguments passed to the function.",additionalProperties:{anyOf:[{$ref:"#/$defs/DynamicValue"},{type:"object",description:"A literal object argument (e.g. configuration)."}]}},returnType:{type:"string",description:"The expected return type of the function call.",enum:["string","number","boolean","array","object","any","void"],default:"boolean"}},required:["call"],oneOf:[{$ref:"catalog.json#/$defs/anyFunction"}]},CheckRule:{type:"object",description:"A single validation rule applied to an input component.",properties:{condition:{$ref:"#/$defs/DynamicBoolean"},message:{type:"string",description:"The error message to display if the check fails."}},required:["condition","message"],additionalProperties:!1},Checkable:{description:"Properties for components that support client-side checks.",type:"object",properties:{checks:{type:"array",description:"A list of checks to perform. These are function calls that must return a boolean indicating validity.",items:{$ref:"#/$defs/CheckRule"}}}},Action:{description:"Defines an interaction handler that can either trigger a server-side event or execute a local client-side function.",oneOf:[{type:"object",description:"Triggers a server-side event.",properties:{event:{type:"object",description:"The event to dispatch to the server.",properties:{name:{type:"string",description:"The name of the action to be dispatched to the server."},context:{type:"object",description:"A JSON object containing the key-value pairs for the action context. Values can be literals or paths. Use literal values unless the value must be dynamically bound to the data model. Do NOT use paths for static IDs.",additionalProperties:{$ref:"#/$defs/DynamicValue"}}},required:["name"],additionalProperties:!1}},required:["event"],additionalProperties:!1},{type:"object",description:"Executes a local client-side function.",properties:{functionCall:{$ref:"#/$defs/FunctionCall"}},required:["functionCall"],additionalProperties:!1}]}},V10_STANDARD_DEFS={ComponentId:{type:"string",description:"The unique identifier for a component, used for both definitions and references within the same surface."},CallId:{type:"string",description:"The unique identifier for a function call."},AccessibilityAttributes:{type:"object",description:"Attributes to enhance accessibility when using assistive technologies like screen readers or model understanding.",properties:{label:{$ref:"#/$defs/DynamicString",description:"A short string, typically 1 to 3 words, used by assistive technologies to convey the purpose or intent of an element. For example, an input field might have an accessible label of 'User ID' or a button might be labeled 'Submit'."},description:{$ref:"#/$defs/DynamicString",description:"Additional information provided by assistive technologies about an element such as instructions, format requirements, or result of an action. For example, a mute button might have a label of 'Mute' and a description of 'Silences notifications about this conversation'."},live:{type:"string",enum:["off","polite","assertive"],default:"off",description:"Controls screen reader announcements for dynamic updates (WAI-ARIA aria-live). 'polite' waits for user pause; 'assertive' interrupts immediately for alerts."},hidden:{$ref:"#/$defs/DynamicBoolean",description:"Hides the element and its children from assistive technologies when true. Default is false."}},additionalProperties:!1},Extensions:{type:"object",description:"Optional extension metadata. Keys MUST be Unicode identifiers (UAX #31). Keys starting with 'a2ui_' are reserved for official extensions.",patternProperties:{"^[\\p{XID_Start}_][\\p{XID_Continue}]*$":{}},additionalProperties:!1},ComponentCommon:{type:"object",properties:{id:{$ref:"#/$defs/ComponentId"},catalogId:{type:"string",description:"The catalog ID for this component, overriding any surface-level default catalogId."},accessibility:{$ref:"#/$defs/AccessibilityAttributes"},metadata:{type:"object",description:"Optional component-level metadata for vendor extensions.",properties:{extensions:{$ref:"#/$defs/Extensions"}},additionalProperties:!1}},required:["id"]},Child:{$ref:"#/$defs/ComponentId",description:"A reference to a single child component ID."},ChildList:{oneOf:[{type:"array",items:{$ref:"#/$defs/ComponentId"},description:"A static list of child component IDs."},{type:"object",description:"A template for generating a dynamic list of children from a data model list. The `componentId` is the component to use as a template.",properties:{componentId:{$ref:"#/$defs/ComponentId"},path:{type:"string",description:"The path to the list of component property objects in the data model."}},required:["componentId","path"],additionalProperties:!1}]},DataBinding:{type:"object",properties:{path:{type:"string",description:"A JSON Pointer path to a value in the data model."}},required:["path"],additionalProperties:!1},DynamicValue:{description:"A value that can be a literal, a path, or a function call returning any type.",oneOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"array"},{type:"object",not:{anyOf:[{required:["path"]},{required:["call"]}]}},{$ref:"#/$defs/DataBinding"},{$ref:"#/$defs/FunctionCall"}]},DynamicString:{description:"Represents a string",oneOf:[{type:"string"},{$ref:"#/$defs/DataBinding"},{$ref:"#/$defs/FunctionCall"}]},DynamicNumber:{description:"Represents a value that can be either a literal number, a path to a number in the data model, or a function call returning a number.",oneOf:[{type:"number"},{$ref:"#/$defs/DataBinding"},{$ref:"#/$defs/FunctionCall"}]},DynamicBoolean:{description:"A boolean value that can be a literal, a path, or a function call returning a boolean.",oneOf:[{type:"boolean"},{$ref:"#/$defs/DataBinding"},{$ref:"#/$defs/FunctionCall"}]},DynamicStringList:{description:"Represents a value that can be either a literal array of strings, a path to a string array in the data model, or a function call returning a string array.",oneOf:[{type:"array",items:{type:"string"}},{$ref:"#/$defs/DataBinding"},{$ref:"#/$defs/FunctionCall"}]},FunctionCommon:{type:"object",description:"Baseline envelope properties common to all function calls. Function-specific argument schemas ('args') are defined individually by each function in the active catalog.",properties:{call:{type:"string",description:"The name of the function to call."},catalogId:{type:"string",description:"The catalog ID for this function, overriding any surface-level default catalogId."}},required:["call"]},IndexSystemFunction:{type:"object",description:"Returns the 0-based index of the current item when rendering a dynamic list from a template. This function MUST ONLY be available when evaluating template items within a list context.",returnType:"number",properties:{call:{const:"@index"},args:{type:"object",properties:{offset:{$ref:"#/$defs/DynamicNumber",description:"Optional. An offset to add to the 0-based index (e.g., 1 for 1-based indexing). Defaults to 0.",default:0}},unevaluatedProperties:!1}},required:["call"],unevaluatedProperties:!1},FunctionCall:{type:"object",description:"Invokes a named function, combining common function properties with the catalog function definition.",allOf:[{$ref:"#/$defs/FunctionCommon"},{oneOf:[{$ref:"catalog.json#/$defs/anyFunction"},{$ref:"#/$defs/IndexSystemFunction"}]}],unevaluatedProperties:!1},CheckRule:{type:"object",description:"A single validation check rule applied to an input component. The condition function or path evaluates to a structured validation result object.",properties:{condition:{oneOf:[{$ref:"#/$defs/DataBinding"},{$ref:"#/$defs/FunctionCall"}],description:"Path or function call evaluating to a structured validation result object."},message:{type:"string",description:"Optional fallback error message."}},required:["condition"],additionalProperties:!1},Checkable:{description:"Properties for components that support renderer-side checks.",type:"object",properties:{checks:{type:"array",description:"A list of checks to perform. These are function calls that must return a boolean indicating validity.",items:{$ref:"#/$defs/CheckRule"}}}},Action:{description:"Defines an interaction handler that can either trigger an agent-side event or execute a local renderer-side function.",oneOf:[{type:"object",description:"Triggers an agent-side event.",properties:{event:{type:"object",description:"The event to dispatch to the agent.",properties:{name:{type:"string",description:"The name of the action to be dispatched to the agent."},userMessage:{$ref:"#/$defs/DynamicString",description:"An optional human-readable message describing the action performed by the user, to present in conversation history or user feedback."},context:{type:"object",description:"A JSON object containing the key-value pairs for the action context. Values can be literals or paths. Use literal values unless the value must be dynamically bound to the data model. Do NOT use paths for static IDs.",additionalProperties:{$ref:"#/$defs/DynamicValue"}}},required:["name"],additionalProperties:!1}},required:["event"],additionalProperties:!1},{type:"object",description:"Executes a renderer or agent-side function.",properties:{functionCall:{$ref:"#/$defs/FunctionCall"}},required:["functionCall"],additionalProperties:!1}]},Surface:{title:"Surface Container Component",description:"The reserved canonical container component representing an A2UI surface. The Surface component is immutable and always has 'child': 'root'.",type:"object",allowedParents:[],properties:{component:{const:"Surface"},child:{const:"root"}},additionalProperties:!1},FunctionResponse:{type:"object",description:"The return response matching a callAgentFunction or callRendererFunction invocation.",properties:{functionCallId:{$ref:"#/$defs/CallId",description:"The unique ID matching the initiating function call."},value:{description:"The return value of the function."},error:{type:"object",description:"An error object indicating failure of the function execution.",properties:{code:{type:"string"},message:{type:"string"}},required:["code","message"],additionalProperties:!1}},required:["functionCallId"],oneOf:[{required:["value"]},{required:["error"]}],additionalProperties:!1}};const STANDARD_DEFS_BY_VERSION={"0.8":V08_STANDARD_DEFS,"0.9":V09_STANDARD_DEFS,"0.9.1":V09_STANDARD_DEFS,"1.0":V10_STANDARD_DEFS};function getStandardDefsForCatalog(Au,lo){if(lo?.standardDefs)return lo.standardDefs;if(lo?.protocolVersion){const $u=toCanonicalVersion(lo.protocolVersion)??normalizeVersionString(lo.protocolVersion);if($u in STANDARD_DEFS_BY_VERSION)return STANDARD_DEFS_BY_VERSION[$u]}return V09_STANDARD_DEFS}function transformRefDescriptionNode(Au){if(typeof Au.description!="string"||!Au.description.startsWith("REF:"))return!1;const lo=Au.description.substring(4),$u=lo.indexOf("|"),Ru=$u===-1?lo:lo.substring(0,$u),Iu=$u===-1?"":lo.substring($u+1),Pu=Au.default;for(const Ou of Object.keys(Au))delete Au[Ou];return Au.$ref=Ru.startsWith("#")?Ru:`#/$defs/${Ru.split("/").pop()}`,Pu!==void 0&&(Au.default=Pu),Iu&&(Au.description=Iu),!0}function cleanSchemaProperties(Au){Array.isArray(Au.anyOf)&&(Au.oneOf=Au.anyOf,delete Au.anyOf),Au.additionalProperties&&typeof Au.additionalProperties=="object"&&Object.keys(Au.additionalProperties).length===0&&(Au.additionalProperties=!0),Au.unevaluatedProperties&&typeof Au.unevaluatedProperties=="object"&&Object.keys(Au.unevaluatedProperties).length===0&&(Au.unevaluatedProperties=!0),"$schema"in Au&&delete Au.$schema}function cleanSchemaNode(Au,lo=new Set){if(typeof Au!="object"||Au===null||lo.has(Au))return;if(lo.add(Au),Array.isArray(Au)){for(const Ru of Au)cleanSchemaNode(Ru,lo);return}const $u=Au;if(!transformRefDescriptionNode($u)){cleanSchemaProperties($u);for(const Ru of Object.keys($u))cleanSchemaNode($u[Ru],lo)}}function processTheme(Au,lo){if(!Au.themeSchema)return;const $u=zodToJsonSchema(Au.themeSchema,{target:"jsonSchema2019-09",$refStrategy:"none"});cleanSchemaNode($u),$u.definitions&&typeof $u.definitions=="object"?(Object.assign(lo,$u.definitions),delete $u.definitions):$u.$defs&&typeof $u.$defs=="object"&&(Object.assign(lo,$u.$defs),delete $u.$defs);const Ru=Au.id.includes("v0_8")||Au.id.includes("v0.8"),Iu={type:"object",properties:$u.properties||{},...Array.isArray($u.required)&&$u.required.length>0?{required:$u.required}:{},...Ru?{}:{additionalProperties:$u.additionalProperties!==void 0?$u.additionalProperties:!0}};lo.theme=Iu}function extractZodComponentSchema(Au,lo){if(!Au.schema||typeof Au.schema!="object"||!("safeParse"in Au.schema))return{props:{},reqList:[],additionalProps:void 0};const $u=zodToJsonSchema(Au.schema,{target:"jsonSchema2019-09",$refStrategy:"none"});cleanSchemaNode($u),$u.definitions&&typeof $u.definitions=="object"?Object.assign(lo,$u.definitions):$u.$defs&&typeof $u.$defs=="object"&&Object.assign(lo,$u.$defs);const Ru=$u.properties||{},Iu=Array.isArray($u.required)?$u.required.filter(Mu=>Mu!=="component"&&Mu!=="id"):[],Pu=$u.unevaluatedProperties??$u.additionalProperties;return{props:Ru,reqList:Iu,additionalProps:typeof Pu=="boolean"||typeof Pu=="object"&&Pu!==null?Pu:void 0}}function processSingleComponent(Au,lo,$u,Ru,Iu){const{props:Pu,reqList:Ou,additionalProps:Mu}=extractZodComponentSchema(lo,$u),{component:Du,id:Lu,...Bu}=Pu,ju={id:{$ref:"#/$defs/ComponentId"},...Bu,component:{const:Au}},Fu=["id",...Ou,"component"];let zu;return Iu?.componentEnvelopeRef?zu={allOf:[{$ref:Iu.componentEnvelopeRef},{type:"object",properties:ju,required:Fu}],unevaluatedProperties:Mu!==void 0?Mu:!1}:zu={type:"object",properties:ju,required:Fu,unevaluatedProperties:Mu!==void 0?Mu:!1},lo.allowedParents&&lo.allowedParents.length>0&&(zu.allowedParents=lo.allowedParents),lo.allowedChildren&&lo.allowedChildren.length>0&&(zu.allowedChildren=lo.allowedChildren),zu}function processComponents(Au,lo,$u,Ru){if(Au.components.size===0){lo.components={};return}const Iu={};for(const[Pu,Ou]of Au.components.entries())Iu[Pu]=processSingleComponent(Pu,Ou,$u,Au,Ru);lo.components=Iu,$u.anyComponent={oneOf:Array.from(Au.components.keys()).map(Pu=>({$ref:`#/components/${Pu}`})),discriminator:{propertyName:"component"}}}function processSingleFunction(Au,lo,$u){let Ru;if(lo.schema&&typeof lo.schema=="object"&&"safeParse"in lo.schema){const Iu=zodToJsonSchema(lo.schema,{target:"jsonSchema2019-09",$refStrategy:"none"});cleanSchemaNode(Iu),Iu.definitions&&typeof Iu.definitions=="object"?(Object.assign($u,Iu.definitions),delete Iu.definitions):Iu.$defs&&typeof Iu.$defs=="object"&&(Object.assign($u,Iu.$defs),delete Iu.$defs),Ru=Iu}else Ru={type:"object",properties:{}};if(lo.description&&Ru.description===void 0&&(Ru.description=lo.description),Ru.type==="object"){const Iu=Ru.unevaluatedProperties??Ru.additionalProperties,Pu=typeof Iu=="boolean"||typeof Iu=="object"&&Iu!==null?Iu:void 0;Ru.additionalProperties!==void 0&&delete Ru.additionalProperties,Ru.unevaluatedProperties=Pu!==void 0?Pu:!1}return Ru}function processFunctions(Au,lo,$u){if(Au.functions.size===0)return;const Ru={};for(const[Iu,Pu]of Au.functions.entries())Ru[Iu]=processSingleFunction(Iu,Pu,$u);lo.functions=Ru,$u.anyFunction={oneOf:Array.from(Au.functions.keys()).map(Iu=>({$ref:`#/functions/${Iu}`}))}}function collectReferencedDefs(Au,lo,$u=new Set){if(!(typeof Au!="object"||Au===null)&&!$u.has(Au)){if($u.add(Au),typeof Au.$ref=="string"){const Ru=Au.$ref;Ru.startsWith("#/$defs/")&&lo.add(Ru.substring(8))}if(Array.isArray(Au))for(const Ru of Au)collectReferencedDefs(Ru,lo,$u);else for(const Ru of Object.values(Au))collectReferencedDefs(Ru,lo,$u)}}function generateCatalogSchema(Au,lo){const $u={$schema:"https://json-schema.org/draft/2020-12/schema",catalogId:Au.id};Au.instructions&&($u.instructions=Au.instructions);const Ru={};processTheme(Au,Ru),processComponents(Au,$u,Ru,lo),processFunctions(Au,$u,Ru);const Iu=getStandardDefsForCatalog(Au,lo);let Pu;do{Pu=Object.keys(Ru).length;const Ou=new Set;collectReferencedDefs($u,Ou),collectReferencedDefs(Ru,Ou),(Ou.has("DynamicString")||Ou.has("DynamicNumber")||Ou.has("DynamicBoolean")||Ou.has("DynamicValue"))&&(Ou.add("DataBinding"),Ou.add("FunctionCall"));for(const Mu of Ou)Mu in Iu&&!(Mu in Ru)&&(Ru[Mu]=Iu[Mu])}while(Object.keys(Ru).length>Pu);return Object.keys(Ru).length>0&&($u.$defs=Ru),$u}function extractRefDefName(Au){if(!Au)return"";const lo=Au.lastIndexOf("#");return(lo!==-1?Au.slice(lo+1):Au).split("/").filter(Boolean).pop()??""}function unwrapNextZodLayer(Au,lo){if(!Au?._def)return null;if(lo){if(lo.has(Au))return null;lo.add(Au)}switch(Au._def.typeName){case"ZodOptional":case"ZodNullable":case"ZodDefault":case"ZodReadonly":return Au._def.innerType;case"ZodBranded":return Au._def.type;case"ZodEffects":return Au._def.schema;case"ZodLazy":return Au._def.getter();default:return null}}function getDescriptions(Au){const lo=[],$u=new Set;let Ru=Au;for(;Ru;){Ru.description&&lo.push(Ru.description),Ru._def?.description&&lo.push(Ru._def.description);const Iu=unwrapNextZodLayer(Ru,$u);if(!Iu)break;Ru=Iu}return lo}function unwrapZodType(Au){const lo=new Set;let $u=Au;for(;$u;){const Ru=unwrapNextZodLayer($u,lo);if(!Ru)break;$u=Ru}return $u}function checkDirectJsonRef(Au,lo){if(!Au)return null;const $u=extractRefDefName(Au),Ru=lo.childListRefNames,Iu=lo.childRefNames;return Ru.has($u)?{isChild:!1,isChildList:!0}:Iu.has($u)?{isChild:!0,isChildList:!1}:null}function checkCombinerList(Au,lo){let $u=!1;for(const Ru of Au){if(typeof Ru!="object"||Ru===null)continue;const Iu=checkJsonSchemaRef(Ru,lo);if(Iu.isChildList)return{isChild:!1,isChildList:!0};Iu.isChild&&($u=!0)}return $u?{isChild:!0,isChildList:!1}:null}function checkCombinerRefs(Au,lo){let $u=!1;for(const Ru of["oneOf","anyOf","allOf"]){const Iu=Au[Ru];if(!Array.isArray(Iu))continue;const Pu=checkCombinerList(Iu,lo);if(Pu?.isChildList)return Pu;Pu?.isChild&&($u=!0)}return $u?{isChild:!0,isChildList:!1}:null}function checkJsonSchemaRef(Au,lo){const $u=typeof Au.$ref=="string"?Au.$ref:"",Ru=checkDirectJsonRef($u,lo);if(Ru)return Ru;if(Au.type==="array"&&Au.items){const Pu=checkJsonSchemaRef(Au.items,lo);if(Pu.isChild||Pu.isChildList)return{isChild:!1,isChildList:!0}}const Iu=checkCombinerRefs(Au,lo);return Iu||(Au.type==="object"&&Au.properties&&("componentId"in Au.properties&&("path"in Au.properties||"dataBinding"in Au.properties)||"explicitList"in Au.properties||"template"in Au.properties)?{isChild:!1,isChildList:!0}:{isChild:!1,isChildList:!1})}function isTemplateShape(Au){if(Au?._def?.typeName==="ZodObject"&&typeof Au._def.shape=="function"){const lo=Au._def.shape();return!!(lo.componentId&&(lo.path||lo.dataBinding)||lo.explicitList||lo.template)}return!1}function isArrayOfChild(Au,lo){if(Au?._def?.typeName==="ZodArray"){const $u=unwrapZodType(Au._def.type);return analyzeChildRefSchema($u,lo).isChild}return!1}function analyzeUnionOptions(Au,lo){let $u=!1,Ru=!1,Iu=!1;for(const Pu of Au){const Ou=unwrapZodType(Pu);isTemplateShape(Ou)&&($u=!0),isArrayOfChild(Ou,lo)&&(Ru=!0);const Mu=analyzeChildRefSchema(Ou,lo);if(Mu.isChildList)return{isChild:!1,isChildList:!0};Mu.isChild&&(Iu=!0)}return $u||Ru?{isChild:!1,isChildList:!0}:Iu?{isChild:!0,isChildList:!1}:{isChild:!1,isChildList:!1}}function isChildListDescription(Au,lo){if(!Au)return!1;if(Au.startsWith("REF:")){const Iu=extractRefDefName(Au.substring(4).split("|")[0]);if(lo.has(Iu))return!0}const $u=extractRefDefName(Au.split("|")[0]);if($u&&lo.has($u))return!0;const Ru=Au.trim();return!!lo.has(Ru)}function isChildDescription(Au,lo){if(!Au)return!1;if(Au.startsWith("REF:")){const Iu=extractRefDefName(Au.substring(4).split("|")[0]);if(lo.has(Iu))return!0}const $u=extractRefDefName(Au.split("|")[0]);if($u&&lo.has($u))return!0;const Ru=Au.trim();return!!lo.has(Ru)}function checkDescriptionChildRef(Au,lo){const $u=lo.childListRefNames,Ru=lo.childRefNames;for(const Iu of Au){if(isChildListDescription(Iu,$u))return{isChild:!1,isChildList:!0};if(isChildDescription(Iu,Ru))return{isChild:!0,isChildList:!1}}return null}function analyzeZodArray(Au,lo){const $u=analyzeChildRefSchema(Au,lo);return $u.isChild||$u.isChildList?{isChild:!1,isChildList:!0}:{isChild:!1,isChildList:!1}}function analyzeChildRefSchema(Au,lo){if(!Au||typeof Au!="object")return{isChild:!1,isChildList:!1};const $u=childRefKindOf(Au);if($u==="component-id")return{isChild:!0,isChildList:!1};if($u==="child-list")return{isChild:!1,isChildList:!0};const Ru=checkDescriptionChildRef(getDescriptions(Au),lo);if(Ru)return Ru;const Iu=unwrapZodType(Au);if(!Iu?._def)return checkJsonSchemaRef(Au,lo);const Pu=childRefKindOf(Iu);if(Pu==="component-id")return{isChild:!0,isChildList:!1};if(Pu==="child-list")return{isChild:!1,isChildList:!0};const Ou=Iu._def.typeName;if(Ou==="ZodArray"){const Mu=unwrapZodType(Iu._def.type);return analyzeZodArray(Mu,lo)}if(Ou==="ZodUnion"){const Mu=Iu._def.options??[];return analyzeUnionOptions(Mu,lo)}if(Ou==="ZodObject"&&typeof Iu._def.shape=="function"){const Mu=Iu._def.shape();if(Mu.componentId&&(Mu.path||Mu.dataBinding)||Mu.explicitList||Mu.template)return{isChild:!1,isChildList:!0}}return{isChild:!1,isChildList:!1}}function addNestedRef(Au,lo,$u){const Ru=Au.nestedRefs[lo];if(Ru){Ru.add($u);return}Au.nestedRefs[lo]=new Set([$u])}function inspectShapeField(Au,lo,$u,Ru){const Iu=analyzeChildRefSchema(lo,Ru);if(Iu.isChildList){$u.listRefs.add(Au);return}if(Iu.isChild){$u.singleRefs.add(Au);return}const Pu=unwrapZodType(lo);if(Pu?._def?.typeName!=="ZodArray")return;const Ou=unwrapZodType(Pu._def.type);if(Ou?._def?.typeName!=="ZodObject"||typeof Ou._def.shape!="function")return;const Mu=Ou._def.shape();for(const[Du,Lu]of Object.entries(Mu)){const Bu=analyzeChildRefSchema(Lu,Ru);(Bu.isChild||Bu.isChildList)&&($u.listRefs.add(Au),addNestedRef($u,Au,Du))}}function rawArrayItemProperties(Au){if(typeof Au!="object"||Au===null)return null;const lo=Au;if(lo.type!=="array"&&!("items"in lo))return null;const $u=lo.items;if(typeof $u!="object"||$u===null)return null;const Ru=$u.properties;return typeof Ru!="object"||Ru===null?null:Ru}function inspectRawProperties(Au,lo,$u){for(const[Ru,Iu]of Object.entries(Au)){const Pu=analyzeChildRefSchema(Iu,$u);if(Pu.isChildList){lo.listRefs.add(Ru);continue}if(Pu.isChild){lo.singleRefs.add(Ru);continue}const Ou=rawArrayItemProperties(Iu);if(Ou)for(const[Mu,Du]of Object.entries(Ou)){const Lu=analyzeChildRefSchema(Du,$u);(Lu.isChild||Lu.isChildList)&&(lo.listRefs.add(Ru),addNestedRef(lo,Ru,Mu))}}}function inspectComponentSchema(Au,lo,$u){if(!Au)return;const Ru=unwrapZodType(Au);if(Ru?._def?.typeName==="ZodObject"&&typeof Ru._def.shape=="function"){const Iu=Ru._def.shape();for(const[Pu,Ou]of Object.entries(Iu))inspectShapeField(Pu,Ou,lo,$u);return}if(typeof Au=="object"&&Au!==null&&"properties"in Au){const Iu=Au.properties;typeof Iu=="object"&&Iu!==null&&inspectRawProperties(Iu,lo,$u)}}function buildComponentRefMap(Au,lo){const $u={},Ru=typeof Au?.components?.values=="function"?Array.from(Au.components.values()):Array.isArray(Au)?Au:Array.from(Au.values());for(const Iu of Ru){const Pu={singleRefs:new Set,listRefs:new Set,nestedRefs:{}};inspectComponentSchema(Iu.schema,Pu,lo),$u[Iu.name]={singleRefs:Pu.singleRefs,listRefs:Pu.listRefs,nestedRefs:Pu.nestedRefs}}return $u}function createFunctionImplementation(Au,lo){return{name:Au.name,returnType:Au.returnType,schema:Au.schema,allowedCallers:Au.allowedCallers,requiresUserActivation:Au.requiresUserActivation,description:Au.description,execute:lo}}class Catalog{get catalogSchema(){return this.cachedCatalogSchema||(this.cachedCatalogSchema=generateCatalogSchema(this)),this.cachedCatalogSchema}get componentRefMap(){return this._componentRefMap||(this._componentRefMap=buildComponentRefMap(this,V09_CHILD_REF_OPTIONS)),this._componentRefMap}constructor(lo,$u,Ru=[],Iu=[],Pu,Ou){if(!$u)throw new A2uiCatalogError("protocolVersion must be provided.");this.id=lo,this.protocolVersion=$u;const Mu=new Map;for(const Lu of Ru)Mu.set(Lu.name,Lu);this.components=Mu;const Du=new Map;for(const Lu of Iu)Du.set(Lu.name,Lu);this.functions=Du,this.themeSchema=Pu,this.instructions=Ou,this.invoker=(Lu,Bu,ju,Fu)=>{const zu=this.functions.get(Lu);if(!zu)throw new A2uiExpressionError(`Function not found in catalog '${this.id}': ${Lu}`,Lu);const Uu=zu.execute;if(typeof Uu!="function")throw new A2uiExpressionError(`Function '${Lu}' in catalog '${this.id}' is schema-only and has no implementation.`,Lu);try{const Hu=zu.schema.parse(Bu);return Uu.call(zu,Hu,ju,Fu)}catch(Hu){throw Hu?.name==="ZodError"||Hu instanceof ZodError?new A2uiExpressionError(`Validation failed for function '${Lu}': ${Hu.message}`,Lu,Hu.errors??Hu.issues):Hu}}}static fromSchema(lo,$u){return loadCatalogFromSchema(lo,$u)}}class EventEmitter{constructor(){this.listeners=new Set}subscribe(lo){return this.listeners.add(lo),{unsubscribe:()=>this.listeners.delete(lo)}}async emit(lo){for(const $u of this.listeners)try{await $u(lo)}catch(Ru){console.error("EventEmitter error:",Ru)}}dispose(){this.listeners.clear()}}var i=Symbol.for("preact-signals");function t(){if(v>1)v--;else{var Au,lo=!1;for((function(){var Iu=c;for(c=void 0;Iu!==void 0;){var Pu=Iu.S;if(Pu.v===Iu.v)for(var Ou=Pu.t;Ou!==void 0;Ou=Ou.x)Ou.i===Iu.i&&(Ou.i=Pu.i);Iu=Iu.o}})();h!==void 0;){var $u=h;for(h=void 0,s++;$u!==void 0;){var Ru=$u.u;if($u.u=void 0,$u.f&=-3,!(8&$u.f)&&w($u))try{$u.c()}catch(Iu){lo||(Au=Iu,lo=!0)}$u=Ru}}if(s=0,v--,lo)throw Au}}function n(Au){if(v>0)return Au();e=++u,v++;try{return Au()}finally{t()}}var r,o=void 0;function f(Au){var lo=o,$u=r;o=void 0,r=void 0;try{return Au()}finally{o=lo,r=$u}}var h=void 0,v=0,s=0,u=0,e=0,c=void 0,d=0;function a(Au){if(o!==void 0){var lo=Au.n;if(lo===void 0||lo.t!==o)return lo={i:0,S:Au,p:o.s,n:void 0,t:o,e:void 0,x:void 0,r:lo},o.s!==void 0&&(o.s.n=lo),o.s=lo,Au.n=lo,32&o.f&&Au.S(lo),lo;if(lo.i===-1)return lo.i=0,lo.n!==void 0&&(lo.n.p=lo.p,lo.p!==void 0&&(lo.p.n=lo.n),lo.p=o.s,lo.n=void 0,o.s.n=lo,o.s=lo),lo}}function l(Au,lo){this.v=Au,this.i=0,this.n=void 0,this.t=void 0,this.l=0,this.W=lo?.watched,this.Z=lo?.unwatched,this.name=lo?.name}l.prototype.brand=i;l.prototype.h=function(){return!0};l.prototype.S=function(Au){var lo=this,$u=this.t;$u!==Au&&Au.e===void 0&&(Au.x=$u,this.t=Au,$u!==void 0?$u.e=Au:f(function(){var Ru;(Ru=lo.W)==null||Ru.call(lo)}))};l.prototype.U=function(Au){var lo=this;if(this.t!==void 0){var $u=Au.e,Ru=Au.x;$u!==void 0&&($u.x=Ru,Au.e=void 0),Ru!==void 0&&(Ru.e=$u,Au.x=void 0),Au===this.t&&(this.t=Ru,Ru===void 0&&f(function(){var Iu;(Iu=lo.Z)==null||Iu.call(lo)}))}};l.prototype.subscribe=function(Au){var lo=this;return j(function(){var $u=lo.value;f(function(){return Au($u)})},{name:"sub"})};l.prototype.valueOf=function(){return this.value};l.prototype.toString=function(){return this.value+""};l.prototype.toJSON=function(){return this.value};l.prototype.peek=function(){var Au=this;return f(function(){return Au.value})};Object.defineProperty(l.prototype,"value",{get:function(){var Au=a(this);return Au!==void 0&&(Au.i=this.i),this.v},set:function(Au){if(Au!==this.v){if(s>100)throw new Error("Cycle detected");(function($u){v!==0&&s===0&&$u.l!==e&&($u.l=e,c={S:$u,v:$u.v,i:$u.i,o:c})})(this),this.v=Au,this.i++,d++,v++;try{for(var lo=this.t;lo!==void 0;lo=lo.x)lo.t.N()}finally{t()}}}});function y(Au,lo){return new l(Au,lo)}function w(Au){for(var lo=Au.s;lo!==void 0;lo=lo.n)if(lo.S.i!==lo.i||!lo.S.h()||lo.S.i!==lo.i)return!0;return!1}function _(Au){for(var lo=Au.s;lo!==void 0;lo=lo.n){var $u=lo.S.n;if($u!==void 0&&(lo.r=$u),lo.S.n=lo,lo.i=-1,lo.n===void 0){Au.s=lo;break}}}function b(Au){for(var lo=Au.s,$u=void 0;lo!==void 0;){var Ru=lo.p;lo.i===-1?(lo.S.U(lo),Ru!==void 0&&(Ru.n=lo.n),lo.n!==void 0&&(lo.n.p=Ru)):$u=lo,lo.S.n=lo.r,lo.r!==void 0&&(lo.r=void 0),lo=Ru}Au.s=$u}function p(Au,lo){l.call(this,void 0,lo),this.x=Au,this.s=void 0,this.g=d-1,this.f=4}p.prototype=new l;p.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===d))return!0;if(this.g=d,this.f|=1,this.i>0&&!w(this))return this.f&=-2,!0;var Au=o;try{_(this),o=this;var lo=this.x();(16&this.f||this.v!==lo||this.i===0)&&(this.v=lo,this.f&=-17,this.i++)}catch($u){this.v=$u,this.f|=16,this.i++}return o=Au,b(this),this.f&=-2,!0};p.prototype.S=function(Au){if(this.t===void 0){this.f|=36;for(var lo=this.s;lo!==void 0;lo=lo.n)lo.S.S(lo)}l.prototype.S.call(this,Au)};p.prototype.U=function(Au){if(this.t!==void 0&&(l.prototype.U.call(this,Au),this.t===void 0)){this.f&=-33;for(var lo=this.s;lo!==void 0;lo=lo.n)lo.S.U(lo)}};p.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var Au=this.t;Au!==void 0;Au=Au.x)Au.t.N()}};Object.defineProperty(p.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var Au=a(this);if(this.h(),Au!==void 0&&(Au.i=this.i),16&this.f)throw this.v;return this.v}});function g(Au,lo){return new p(Au,lo)}function S(Au){var lo=Au.m;if(Au.m=void 0,typeof lo=="function"){v++;var $u=o;o=void 0;try{lo()}catch(Ru){throw Au.f&=-2,Au.f|=8,m(Au),Ru}finally{o=$u,t()}}}function m(Au){for(var lo=Au.s;lo!==void 0;lo=lo.n)lo.S.U(lo);Au.x=void 0,Au.s=void 0,S(Au)}function x(Au){if(o!==this)throw new Error("Out-of-order effect");b(this),o=Au,this.f&=-2,8&this.f&&m(this),t()}function E(Au,lo){this.x=Au,this.m=void 0,this.s=void 0,this.u=void 0,this.f=32,this.name=lo?.name,r&&r.push(this)}E.prototype.c=function(){var Au=this.S();try{if(8&this.f||this.x===void 0)return;var lo=this.x();typeof lo=="function"&&(this.m=lo)}finally{Au()}};E.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,S(this),_(this),v++;var Au=o;return o=this,x.bind(this,Au)};E.prototype.N=function(){2&this.f||(this.f|=2,this.u=h,h=this)};E.prototype.d=function(){this.f|=8,1&this.f||m(this)};E.prototype.dispose=function(){this.d()};function j(Au,lo){var $u=new E(Au,lo);try{$u.c()}catch(Iu){throw $u.d(),Iu}var Ru=$u.d.bind($u);return Ru[Symbol.dispose]=Ru,Ru}let signalImpl,computedImpl,effectImpl,batchWriteImpl,isSignalImpl,getValueImpl,setValueImpl,peekValueImpl;const _PRIVATE_DEFAULT_SIGNAL_IMPLEMENTATION={signal:y,computed:g,effect:j,batchWrite:n,isSignal:Au=>!!Au&&typeof Au=="object"&&"value"in Au&&"peek"in Au,getValue:Au=>Au.value,setValue:(Au,lo)=>{Au instanceof p||(Au.value=lo)},peekValue:Au=>Au.peek()};setSignalImplementation(_PRIVATE_DEFAULT_SIGNAL_IMPLEMENTATION);function setSignalImplementation(Au){signalImpl=Au.signal,computedImpl=Au.computed,effectImpl=Au.effect,batchWriteImpl=Au.batchWrite,isSignalImpl=Au.isSignal,getValueImpl=Au.getValue,setValueImpl=Au.setValue,peekValueImpl=Au.peekValue}function signal(Au){return signalImpl(Au)}function computed(Au){return computedImpl(Au)}function effect(Au){return effectImpl(Au)}function batchWrite(Au){return batchWriteImpl(Au)}function isSignal(Au){return isSignalImpl(Au)}function getValue(Au){return getValueImpl(Au)}function setValue(Au,lo){setValueImpl(Au,lo)}function peekValue(Au){return peekValueImpl(Au)}function isNumeric(Au){return/^(0|[1-9]\d*)$/.test(Au)}const MAX_ARRAY_INDEX=1e4,FORBIDDEN_KEYS=new Set(["__proto__","constructor","prototype"]);class DataModel{constructor(lo={}){this.data={},this.signals=new Map,this.subscriptions=new Set,this.data=lo}getSignal(lo){const $u=this.normalizePath(lo);return this.signals.has($u)||this.signals.set($u,signal(this.get($u))),this.signals.get($u)}set(lo,$u){if(lo==null)throw new A2uiDataError("Path cannot be null or undefined.");if(lo==="/"||lo==="")return this.data=$u??{},this.notifyAllSignals(),this;const Ru=this.parsePath(lo),Iu=Ru.pop();if($u==null&&this.get(lo)===void 0)return this;if(this.data===void 0||this.data===null)this.data={};else if(typeof this.data!="object")throw new A2uiDataError(`Cannot set path '${lo}': the data model root is a primitive value.`,lo);let Pu=this.data;for(let Ou=0;Ou<Ru.length;Ou++){const Mu=Ru[Ou];if(Array.isArray(Pu)){if(!isNumeric(Mu))throw new A2uiDataError(`Cannot use non-numeric segment '${Mu}' on an array in path '${lo}'.`,lo);const Du=parseInt(Mu,10);if(Du>MAX_ARRAY_INDEX)throw new A2uiDataError(`Cannot set path '${lo}': array index '${Mu}' exceeds maximum supported index (${MAX_ARRAY_INDEX}).`,lo);const Lu=Pu[Du];if(Lu!=null&&typeof Lu!="object")throw new A2uiDataError(`Cannot set path '${lo}': segment '${Mu}' is a primitive value.`,lo);if(Lu==null){const Bu=Ou<Ru.length-1?Ru[Ou+1]:Iu;if(isNumeric(Bu)){if(parseInt(Bu,10)>MAX_ARRAY_INDEX)throw new A2uiDataError(`Cannot set path '${lo}': array index '${Bu}' exceeds maximum supported index (${MAX_ARRAY_INDEX}).`,lo);Pu[Du]=[]}else Pu[Du]={}}}else{const Du=Object.prototype.hasOwnProperty.call(Pu,Mu);if(Du){const Lu=Pu[Mu];if(Lu!=null&&typeof Lu!="object")throw new A2uiDataError(`Cannot set path '${lo}': segment '${Mu}' is a primitive value.`,lo)}if(!Du||Pu[Mu]===void 0||Pu[Mu]===null){const Lu=Ou<Ru.length-1?Ru[Ou+1]:Iu;if(isNumeric(Lu)){if(parseInt(Lu,10)>MAX_ARRAY_INDEX)throw new A2uiDataError(`Cannot set path '${lo}': array index '${Lu}' exceeds maximum supported index (${MAX_ARRAY_INDEX}).`,lo);Pu[Mu]=[]}else Pu[Mu]={}}}Pu=Pu[Mu]}if(Array.isArray(Pu)){if(!isNumeric(Iu))throw new A2uiDataError(`Cannot use non-numeric segment '${Iu}' on an array in path '${lo}'.`,lo);if(parseInt(Iu,10)>MAX_ARRAY_INDEX)throw new A2uiDataError(`Cannot set path '${lo}': array index '${Iu}' exceeds maximum supported index (${MAX_ARRAY_INDEX}).`,lo)}if($u==null)if(Array.isArray(Pu)){const Ou=parseInt(Iu,10);Ou<Pu.length&&(Pu[Ou]=void 0)}else delete Pu[Iu];else Pu[Iu]=$u;return this.notifySignals(lo),this}delete(lo){return this.set(lo,void 0)}static resolvePath(lo,$u){return lo.startsWith("/")?lo:$u?`${$u.endsWith("/")?$u:`${$u}/`}${lo}`:`/${lo}`}get(lo){if(lo==null)throw new A2uiDataError("Path cannot be null or undefined.");if(lo==="/"||lo==="")return this.data;const $u=this.parsePath(lo);let Ru=this.data;for(const Iu of $u){if(Ru==null||typeof Ru!="object")return;if(Array.isArray(Ru)){if(!isNumeric(Iu))return;const Pu=parseInt(Iu,10);if(Pu<0||Pu>=Ru.length)return;Ru=Ru[Pu]}else{if(!Object.prototype.hasOwnProperty.call(Ru,Iu))return;Ru=Ru[Iu]}}return Ru}hasPath(lo){return lo==null?!1:this.get(lo)!==void 0}subscribe(lo,$u){const Ru=this.getSignal(lo);let Iu=!0,Pu=peekValue(Ru);const Ou=effect(()=>{const Mu=getValue(Ru);Pu=Mu,Iu||$u(Mu)});return Iu=!1,this.subscriptions.add(Ou),{get value(){return Pu},unsubscribe:()=>{Ou(),this.subscriptions.delete(Ou)}}}dispose(){for(const lo of this.subscriptions)lo();this.subscriptions.clear(),this.signals.clear()}normalizePath(lo){return lo.length>1&&lo.endsWith("/")?lo.slice(0,-1):lo||"/"}parsePath(lo){return lo.split("/").filter($u=>$u.length>0).map($u=>{const Ru=$u.replace(/~([01])/g,(Iu,Pu)=>Pu==="1"?"/":"~");if(FORBIDDEN_KEYS.has(Ru))throw new A2uiDataError(`Forbidden path segment '${Ru}' in path '${lo}'.`,lo);return Ru})}notifySignals(lo){const $u=this.normalizePath(lo);batchWrite(()=>{this.updateSignal($u);let Ru=$u;for(;Ru!=="/"&&Ru!=="";)Ru=Ru.substring(0,Ru.lastIndexOf("/"))||"/",this.updateSignal(Ru);for(const Iu of this.signals.keys())this.isDescendant(Iu,$u)&&this.updateSignal(Iu)})}updateSignal(lo){const $u=this.signals.get(lo);if($u){const Ru=this.get(lo);Array.isArray(Ru)?setValue($u,Ru.slice()):typeof Ru=="object"&&Ru!==null?setValue($u,{...Ru}):setValue($u,Ru)}}notifyAllSignals(){batchWrite(()=>{for(const lo of this.signals.keys())this.updateSignal(lo)})}isDescendant(lo,$u){return $u==="/"||$u===""?lo!=="/":lo.startsWith($u+"/")}}const MAX_GLOBAL_DEPTH=50,MAX_FUNC_CALL_DEPTH=5,RELAXED_PATH_PATTERN=/^(?:(?:\/(?:[^~/]|~[01])*)*|(?:[^~/]|~[01])+(?:\/(?:[^~/]|~[01])*)*)$/;function*extractPointers(Au,lo,$u){if(typeof Au=="string")yield[Au,lo];else if(Array.isArray(Au))for(let Ru=0;Ru<Au.length;Ru++){const Iu=Au[Ru],Pu=`${lo}[${Ru}]`;yield*extractPointers(Iu,Pu,$u)}else if(typeof Au=="object"&&Au!==null){const Ru=Au;if("componentId"in Ru&&typeof Ru.componentId=="string"&&("path"in Ru||"dataBinding"in Ru))yield[Ru.componentId,`${lo}.componentId`];else if($u?.size)for(const Iu of $u)Iu in Ru&&(yield*extractPointers(Ru[Iu],`${lo}.${Iu}`));else for(const[Iu,Pu]of Object.entries(Ru))yield*extractPointers(Pu,`${lo}.${Iu}`)}}function getOrCreateRefMap(Au){return Au.componentRefMap}function*getComponentReferences(Au,lo){if(!Au||typeof Au!="object")return;const $u=lo instanceof Catalog?getOrCreateRefMap(lo):lo,Ru=Au.component;let Iu="",Pu=Au;if(typeof Ru=="string")Iu=Ru;else if(typeof Ru=="object"&&Ru!==null){const Bu=Ru;Iu=Object.keys(Bu)[0]??"",Pu=Bu[Iu]??{}}if(!Iu||typeof Pu!="object"||Pu===null)return;const Ou=$u[Iu],Mu=Ou?Ou.singleRefs:new Set,Du=Ou?Ou.listRefs:new Set,Lu=Ou?.nestedRefs;for(const[Bu,ju]of Object.entries(Pu))(Mu.has(Bu)||Du.has(Bu))&&(yield*extractPointers(ju,Bu,Lu?.[Bu]))}function traverseRecursionAndPaths(Au,lo,$u){if(lo>MAX_GLOBAL_DEPTH)throw new A2uiRecursionError(`Global recursion limit exceeded: Depth > ${MAX_GLOBAL_DEPTH}`);if(Array.isArray(Au)){for(const Ru of Au)traverseRecursionAndPaths(Ru,lo+1,$u);return}if(typeof Au=="object"&&Au!==null){const Ru=Au;if("path"in Ru&&typeof Ru.path=="string"){const Ou=Ru.path;if(!RELAXED_PATH_PATTERN.test(Ou))throw new A2uiValidationError(`Invalid path syntax: '${Ou}'`)}const Iu="functionCall"in Ru&&typeof Ru.functionCall=="object"&&Ru.functionCall!==null,Pu="call"in Ru&&"args"in Ru;if(Iu){if($u>=MAX_FUNC_CALL_DEPTH)throw new A2uiRecursionError(`Recursion limit exceeded: functionCall depth > ${MAX_FUNC_CALL_DEPTH}`);for(const[Ou,Mu]of Object.entries(Ru))Ou==="functionCall"?traverseRecursionAndPaths(Mu,lo+1,$u+1):traverseRecursionAndPaths(Mu,lo+1,$u)}else if(Pu){if($u>=MAX_FUNC_CALL_DEPTH)throw new A2uiRecursionError(`Recursion limit exceeded: functionCall depth > ${MAX_FUNC_CALL_DEPTH}`);for(const[Ou,Mu]of Object.entries(Ru))Ou==="args"?traverseRecursionAndPaths(Mu,lo+1,$u+1):traverseRecursionAndPaths(Mu,lo+1,$u)}else for(const Ou of Object.values(Ru))traverseRecursionAndPaths(Ou,lo+1,$u)}}function validateRecursionAndPaths(Au){traverseRecursionAndPaths(Au,0,0)}class SurfaceComponentsModel{constructor(lo){this.components=new Map,this._onCreated=new EventEmitter,this._onDeleted=new EventEmitter,this.onCreated=this._onCreated,this.onDeleted=this._onDeleted,lo&&this.setCatalog(lo)}setCatalog(lo){this.refMap=lo instanceof Catalog?lo.componentRefMap:lo}get(lo){return this.components.get(lo)}getAll(){return new Map(this.components)}has(lo){return this.components.has(lo)}get entries(){return this.components.entries()}get keys(){return this.components.keys()}get values(){return this.components.values()}get size(){return this.components.size}get componentsMap(){return this.components}addComponent(lo){if(this.components.has(lo.id))throw new A2uiStateError(`Component with id '${lo.id}' already exists.`);this.components.set(lo.id,lo),this._onCreated.emit(lo)}removeComponent(lo){const $u=this.components.get(lo);$u&&(this.components.delete(lo),$u.dispose(),this._onDeleted.emit(lo))}getChildReferences(lo){const $u=this.components.get(lo);if(!$u)return[];const Ru=$u.catalog?.components.size?$u.catalog.componentRefMap:this.refMap??$u.catalog?.componentRefMap??{};return Array.from(getComponentReferences({id:$u.id,component:$u.type,...$u.properties},Ru))}getChildIds(lo){return this.getChildReferences(lo).map(([$u])=>$u)}detectCycles(lo={}){const $u=lo.rootId??"root",Ru=lo.maxDepth??MAX_GLOBAL_DEPTH,Iu=lo.allowMissingRoot??!1;for(const Du of this.components.values())for(const[Lu,Bu]of this.getChildReferences(Du.id))if(Lu===Du.id)throw new A2uiRecursionError(`Circular reference detected: Component '${Du.id}' references itself in field '${Bu}' (Self-reference detected)`);const Pu=new Set,Ou=new Set,Mu=(Du,Lu)=>{if(Lu>Ru)throw new A2uiRecursionError(`Global recursion limit exceeded: logical depth > ${Ru}`);Pu.add(Du),Ou.add(Du);const Bu=this.getChildIds(Du);for(const ju of Bu)if(this.components.has(ju)){if(!Pu.has(ju))Mu(ju,Lu+1);else if(Ou.has(ju))throw new A2uiRecursionError(`Circular reference detected involving component '${ju}'`)}Ou.delete(Du)};if(Iu){const Du=Array.from(this.components.keys()).sort();for(const Lu of Du)Pu.has(Lu)||Mu(Lu,0)}else this.components.has($u)&&Mu($u,0);return Pu}validateTopology(lo={}){if(this.components.size===0)return;const $u=lo.rootId??"root",Ru=lo.allowMissingRoot??!1,Iu=lo.allowDanglingReferences??!1,Pu=lo.allowOrphanComponents??!1;if(!Ru&&!this.components.has($u))throw new A2uiIntegrityError(`Missing root component: No component has id='${$u}'`);if(!Iu){for(const Mu of this.components.values())for(const[Du,Lu]of this.getChildReferences(Mu.id))if(!this.components.has(Du))throw new A2uiIntegrityError(`Component '${Mu.id}' references non-existent component '${Du}' in field '${Lu}' (Dangling reference '${Du}' in component '${Mu.id}')`)}const Ou=this.detectCycles({rootId:$u,allowMissingRoot:Ru,maxDepth:lo.maxDepth});if(!Pu&&!Ru&&Ou.size<this.components.size){const Mu=Array.from(this.components.keys()).filter(Du=>!Ou.has(Du)).sort();if(Mu.length>0)throw new A2uiIntegrityError(`Component '${Mu[0]}' is not reachable from '${$u}' (Orphaned component '${Mu[0]}' is not reachable from root)`)}}validateReferences(lo={}){const $u=[];try{this.validateTopology(lo)}catch(Ru){Ru instanceof A2uiValidationError?$u.push(Ru):Ru instanceof Error&&$u.push(new A2uiValidationError(Ru.message))}return $u}dispose(){for(const lo of this.components.values())lo.dispose();this.components.clear(),this._onCreated.dispose(),this._onDeleted.dispose()}}class SurfaceModel{constructor(lo,$u,Ru=new Map,Iu={},Pu=!1,Ou,Mu="root"){if(this.id=lo,this.defaultCatalog=$u,this.theme=Iu,this.sendDataModel=Pu,this.rootId=Mu,this._onAction=new EventEmitter,this._onError=new EventEmitter,this._onWarning=new EventEmitter,this.onAction=this._onAction,this.onError=this._onError,this.onWarning=this._onWarning,Ru!=null&&!(Ru instanceof Map))throw new TypeError("availableCatalogs must be a Map, or undefined/null. Note that availableCatalogs is now the 3rd argument to SurfaceModel and theme is the 4th argument.");const Du=new Map(Ru??[]);$u?.id&&!Du.has($u.id)&&Du.set($u.id,$u),this.availableCatalogs=Du,this.dataModel=Ou??new DataModel({}),this.componentsModel=new SurfaceComponentsModel($u)}get catalog(){return this.defaultCatalog}async dispatchAction(lo,$u){if(!lo||typeof lo!="object")return;const Ru=extractActionTarget(lo);if(!Ru)return;const Iu=Ru.name;if(!Iu||typeof Iu!="string")return;const Pu=Ru.context,Ou=Pu&&typeof Pu=="object"&&!Array.isArray(Pu)?Pu:{},Mu={name:Iu,surfaceId:this.id,sourceComponentId:$u,timestamp:new Date().toISOString(),context:Ou},Du=Ru.catalogId??lo.catalogId;typeof Du=="string"&&Du&&(Mu.catalogId=Du),typeof Ru.userMessage=="string"&&Ru.userMessage.length>0&&(Mu.userMessage=Ru.userMessage),await this._onAction.emit(Mu)}async dispatchError(lo){await this._onError.emit({...lo,surfaceId:this.id})}async dispatchWarning(lo){await this._onWarning.emit({...lo,surfaceId:this.id})}dispose(){this.dataModel.dispose(),this.componentsModel.dispose(),this._onAction.dispose(),this._onError.dispose(),this._onWarning.dispose()}}function extractActionTarget(Au){return"event"in Au&&Au.event&&typeof Au.event=="object"?Au.event:"name"in Au&&typeof Au.name=="string"?Au:null}class SurfaceGroupModel{constructor(){this.surfaces=new Map,this.surfaceUnsubscribers=new Map,this._onSurfaceCreated=new EventEmitter,this._onSurfaceDeleted=new EventEmitter,this._onAction=new EventEmitter,this.onSurfaceCreated=this._onSurfaceCreated,this.onSurfaceDeleted=this._onSurfaceDeleted,this.onAction=this._onAction}addSurface(lo){if(this.surfaces.has(lo.id)){console.warn(`Surface ${lo.id} already exists. Ignoring.`);return}this.surfaces.set(lo.id,lo);const $u=lo.onAction.subscribe(Ru=>this._onAction.emit(Ru));this.surfaceUnsubscribers.set(lo.id,$u),this._onSurfaceCreated.emit(lo)}deleteSurface(lo){const $u=this.surfaces.get(lo);if($u){const Ru=this.surfaceUnsubscribers.get(lo);Ru&&(Ru.unsubscribe(),this.surfaceUnsubscribers.delete(lo)),this.surfaces.delete(lo),$u.dispose(),this._onSurfaceDeleted.emit(lo)}}getSurface(lo){return this.surfaces.get(lo)}get surfacesMap(){return this.surfaces}dispose(){for(const lo of Array.from(this.surfaces.keys()))this.deleteSurface(lo);this._onSurfaceCreated.dispose(),this._onSurfaceDeleted.dispose(),this._onAction.dispose()}}class ComponentModel{constructor(lo,$u,Ru,Iu){this.id=lo,this.type=$u,this.catalog=Iu,this._onUpdated=new EventEmitter,this.onUpdated=this._onUpdated,this._properties=Ru}get properties(){return this._properties}set properties(lo){this._properties=lo,this._onUpdated.emit(this)}dispose(){this._onUpdated.dispose()}get componentTree(){return{id:this.id,type:this.type,...this._properties}}}function formatZodIssue(Au){const lo=Au.path.join(".")||"root";switch(Au.code){case ZodIssueCode.invalid_union:{const $u=Au.unionErrors?.flatMap(Ru=>Ru.issues);return $u&&$u.length>0?$u.map(formatZodIssue).join("; "):`${lo}: Invalid union`}case ZodIssueCode.unrecognized_keys:{const $u=Au.keys.map(Ru=>`'${Ru}'`).join(", ");return`${lo}: Unrecognized key(s) in object: ${$u}`}case ZodIssueCode.invalid_enum_value:{const $u=Au,Ru=$u.options.map(Iu=>String(Iu)).join(" | ");return`${lo}: Invalid enum value. Expected ${Ru}, received '${String($u.received)}'`}case ZodIssueCode.invalid_type:{const $u=Au;return`${lo}: Expected ${$u.expected}, received ${$u.received}`}case ZodIssueCode.custom:return`${lo}: ${Au.message}`;default:return Au.message?`${lo}: ${Au.message}`:`${lo}: Validation error (${Au.code})`}}const DEFAULT_CATALOG_COMPATIBILITY={"0.8":new Set(["0.8"]),"0.9":new Set(["0.9","0.9.1"]),"0.9.1":new Set(["0.9.1","0.9"]),"1.0":new Set(["1.0"])};function isCatalogVersionCompatible(Au,lo,$u=DEFAULT_CATALOG_COMPATIBILITY){if(!Au||!lo)return!1;const Ru=toCanonicalVersion(Au),Iu=toCanonicalVersion(lo);if(Ru&&Iu){if(Ru===Iu)return!0;const Mu=$u[Iu];if(Mu&&Mu.has(Ru))return!0;const Du=toSemVer(Au),Lu=toSemVer(lo);return!!(Du&&Lu&&Du.major>=1&&Du.major===Lu.major)}if(typeof Au!="string"||typeof lo!="string")return!1;const Pu=normalizeVersionString(Au),Ou=normalizeVersionString(lo);return Pu.length>0&&Pu===Ou}let globalKnownActionsProvider;function registerKnownActionsProvider(Au){globalKnownActionsProvider=Au}function validateActionSurfaceIds(Au,lo){for(const $u of lo){const Ru=Au[$u];if(Ru&&typeof Ru=="object"){const Iu=Ru;if("surfaceId"in Iu&&Iu.surfaceId!==void 0&&typeof Iu.surfaceId!="string")throw new A2uiValidationError("surfaceId must be a string")}}}class BaseVersionAdapter{get compatibleCatalogVersions(){const lo=toCanonicalVersion(this.version);return lo?new Set([lo]):new Set}get validActions(){return new Set(this.getNativeActionKeys())}isCatalogCompatible(lo){return lo?isCatalogVersionCompatible(lo,this.version):!1}extractOperations(lo){if(!lo||typeof lo!="object")return[];if(Array.isArray(lo))return lo.flatMap(Mu=>this.extractOperations(Mu));const $u=lo;if(Array.isArray($u.messages))return this.extractOperations($u.messages);const Ru=this.getNativeActionKeys();validateActionSurfaceIds($u,Ru);const Iu=Ru.filter(Mu=>Mu in $u).sort();if(Iu.length>1)throw new A2uiValidationError(`Message contains multiple conflicting update actions: ${Iu.join(", ")}.`);if(Iu.length===0){const Mu=globalKnownActionsProvider?globalKnownActionsProvider():new Set(Ru),Du=Object.keys($u).find(Bu=>Mu.has(Bu)&&!Ru.includes(Bu)),Lu=Ru.slice().sort().join(", ");throw Du?new A2uiValidationError(`Invalid ${this.version} message: action '${Du}' is not supported in protocol version ${this.version}. Allowed actions: ${Lu}.`):new A2uiValidationError(`Invalid ${this.version} message: message must contain exactly one update action: ${Lu}.`)}const Pu=this.preparePayloadForValidation($u),Ou=this.schema.safeParse(Pu);if(!Ou.success){const Mu=Ou.error.errors.map(formatZodIssue).join("; ");throw new A2uiValidationError(`Invalid ${this.version} message: ${Mu}`,Ou.error)}return this.extractOperationsFromObject($u)}preparePayloadForValidation(lo){return"version"in lo?lo:{version:this.version,...lo}}}const exactlyOneKey=(Au,lo)=>{const $u=Object.keys(Au).filter(Ru=>Au[Ru]!==void 0);$u.length!==1&&lo.addIssue({code:ZodIssueCode.custom,message:`Must define exactly one property, found ${$u.length} (${$u.join(", ")}).`})},StringValueSchema=objectType({path:stringType().optional(),literalString:stringType().optional(),literal:stringType().optional()}).strict().superRefine(exactlyOneKey),DataValueMapItemSchema=lazyType(()=>objectType({key:stringType(),valueString:stringType().optional(),valueNumber:numberType().optional(),valueBoolean:booleanType().optional(),valueMap:arrayType(DataValueMapItemSchema).optional()}).strict().superRefine((Au,lo)=>{let $u=0;Au.valueString!==void 0&&$u++,Au.valueNumber!==void 0&&$u++,Au.valueBoolean!==void 0&&$u++,Au.valueMap!==void 0&&$u++,$u!==1&&lo.addIssue({code:ZodIssueCode.custom,message:`Value map item must have exactly one value property (valueString, valueNumber, valueBoolean, valueMap), found ${$u}.`})}));function createDataValueSchema(Au={}){const lo=Au.maxDepth??5;return DataValueMapItemSchema.superRefine(($u,Ru)=>{const Iu=(Pu,Ou)=>{if(Ou>lo){Ru.addIssue({code:ZodIssueCode.custom,message:`valueMap recursion exceeded maximum depth of ${lo}.`});return}if(Pu.valueMap&&Array.isArray(Pu.valueMap))for(const Mu of Pu.valueMap)Iu(Mu,Ou+1)};Iu($u,1)})}const DataValueSchema=createDataValueSchema();objectType({path:stringType().optional(),literalNumber:numberType().optional(),literal:numberType().optional()}).strict().superRefine(exactlyOneKey);objectType({path:stringType().optional(),literalBoolean:booleanType().optional(),literal:booleanType().optional()}).strict().superRefine(exactlyOneKey);const ActionSchema$1=objectType({name:stringType().describe("A unique name identifying the action (e.g., 'submitForm')."),context:arrayType(objectType({key:stringType(),value:objectType({path:stringType().describe("A data binding reference to a location in the data model (e.g., '/user/name').").optional(),literalString:stringType().describe("A fixed, hardcoded string value.").optional(),literalNumber:numberType().optional(),literalBoolean:booleanType().optional()}).describe("The dynamic value. Define EXACTLY ONE of the nested properties.").strict().superRefine(exactlyOneKey)})).describe("A key-value map of data bindings to be resolved when the action is triggered.").optional()});objectType({text:StringValueSchema,usageHint:enumType(["h1","h2","h3","h4","h5","caption","body"]).optional()});objectType({url:StringValueSchema,usageHint:enumType(["icon","avatar","smallFeature","mediumFeature","largeFeature","header"]).optional(),fit:enumType(["contain","cover","fill","none","scale-down"]).optional(),altText:StringValueSchema.optional()});objectType({name:StringValueSchema});objectType({url:StringValueSchema});objectType({url:StringValueSchema,description:StringValueSchema.optional().describe("A label, title, or placeholder text.")});objectType({tabItems:arrayType(objectType({title:objectType({path:stringType().describe("A data binding reference to a location in the data model (e.g., '/user/name').").optional(),literalString:stringType().describe("A fixed, hardcoded string value.").optional()}),child:stringType().describe("A reference to a component instance by its unique ID.")}).strict().superRefine((Au,lo)=>{Au.title||lo.addIssue({code:ZodIssueCode.custom,message:"Tab item is missing 'title'."}),Au.child||lo.addIssue({code:ZodIssueCode.custom,message:"Tab item is missing 'child'."}),Au.title&&exactlyOneKey(Au.title,lo)})).describe("A list of tabs, each with a title and a child component ID.")});objectType({axis:enumType(["horizontal","vertical"]).optional().describe("The orientation."),color:stringType().optional().describe("The color of the divider (e.g., hex code or semantic name)."),thickness:numberType().optional().describe("The thickness of the divider.")});objectType({entryPointChild:stringType().describe("The ID of the component (e.g., a button) that triggers the modal."),contentChild:stringType().describe("The ID of the component to display as the modal's content.")});objectType({child:stringType().describe("The ID of the component to display as the button's content."),action:ActionSchema$1.describe("Represents a user-initiated action."),primary:booleanType().optional().describe("Indicates if this button should be styled as the primary action.")});objectType({label:StringValueSchema,value:objectType({path:stringType().describe("A data binding reference to a location in the data model (e.g., '/user/name').").optional(),literalBoolean:booleanType().optional()}).strict().superRefine(exactlyOneKey)});objectType({text:StringValueSchema.optional(),label:StringValueSchema.describe("A label, title, or placeholder text."),textFieldType:enumType(["shortText","number","date","longText","obscured"]).optional(),validationRegexp:stringType().optional().describe("A regex string to validate the input.")});objectType({value:StringValueSchema,enableDate:booleanType().optional(),enableTime:booleanType().optional(),outputFormat:stringType().optional().describe("The string format for the output (e.g., 'YYYY-MM-DD').")});objectType({selections:objectType({path:stringType().describe("A data binding reference to a location in the data model (e.g., '/user/name').").optional(),literalArray:arrayType(stringType()).optional()}).strict().superRefine(exactlyOneKey),options:arrayType(objectType({label:objectType({path:stringType().describe("A data binding reference to a location in the data model (e.g., '/user/name').").optional(),literalString:stringType().describe("A fixed, hardcoded string value.").optional()}).strict().superRefine(exactlyOneKey),value:stringType()})).optional(),maxAllowedSelections:numberType().optional(),type:enumType(["checkbox","chips"]).optional(),filterable:booleanType().optional()});objectType({value:objectType({path:stringType().describe("A data binding reference to a location in the data model (e.g., '/user/name').").optional(),literalNumber:numberType().optional()}).strict().superRefine(exactlyOneKey),minValue:numberType().optional(),maxValue:numberType().optional(),label:StringValueSchema.optional()});const ComponentArrayTemplateSchema=objectType({componentId:stringType(),dataBinding:stringType()}),ComponentArrayReferenceSchema=objectType({explicitList:arrayType(stringType()).optional(),template:ComponentArrayTemplateSchema.describe("A template for generating a dynamic list of children from a data model list. `componentId` is the component to use as a template, and `dataBinding` is the path to the map of components in the data model. Values in the map will define the list of children.").optional()}).strict().superRefine(exactlyOneKey);objectType({children:ComponentArrayReferenceSchema,distribution:enumType(["start","center","end","spaceBetween","spaceAround","spaceEvenly"]).optional(),alignment:enumType(["start","center","end","stretch"]).optional()});objectType({children:ComponentArrayReferenceSchema,distribution:enumType(["start","center","end","spaceBetween","spaceAround","spaceEvenly"]).optional(),alignment:enumType(["start","center","end","stretch"]).optional()});objectType({children:ComponentArrayReferenceSchema,direction:enumType(["vertical","horizontal"]).optional(),alignment:enumType(["start","center","end","stretch"]).optional()});objectType({child:stringType().describe("The ID of the component to be rendered inside the card.")});const ValueMapSchema=DataValueSchema.describe("A single data entry. Exactly one 'value*' property should be provided alongside the key."),ComponentPropertiesSchema=recordType(anyType()).refine(Au=>Object.keys(Au).length===1,"A wrapper object that MUST contain exactly one key, which is the name of the component type (e.g., 'Heading')."),ComponentInstanceSchema=objectType({id:stringType().describe("The unique identifier for this component."),weight:numberType().optional().describe("The relative weight of this component within a Row or Column. This corresponds to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column."),component:ComponentPropertiesSchema.describe("A wrapper object that MUST contain exactly one key, which is the name of the component type (e.g., 'Heading'). The value is an object containing the properties for that specific component.")}).strict().describe("Represents a *single* component in a UI widget tree. This component could be one of many supported types."),BeginRenderingMessageSchema=objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be rendered."),catalogId:stringType().optional().describe("The identifier of the component catalog to use for this surface. If omitted, the client MUST default to the standard catalog for this A2UI version (https://a2ui.org/specification/v0_8/standard_catalog_definition.json)."),root:stringType().describe("The ID of the root component to render."),styles:objectType({font:stringType().optional().describe("The primary font for the UI."),primaryColor:stringType().regex(/^#[0-9a-fA-F]{6}$/).optional().describe("The primary UI color as a hexadecimal code (e.g., '#00BFFF').")}).strict().optional().describe("Styling information for the UI.")}).strict().describe("Signals the client to begin rendering a surface with a root component and specific styles."),SurfaceUpdateMessageSchema=objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be updated. If you are adding a new surface this *must* be a new, unique identified that has never been used for any existing surfaces shown."),components:arrayType(ComponentInstanceSchema).min(1).describe("A list containing all UI components for the surface.")}).strict().superRefine((Au,lo)=>{const $u=new Set;for(const Iu of Au.components)Iu.id&&($u.has(Iu.id)&&lo.addIssue({code:ZodIssueCode.custom,message:`Duplicate component ID found: ${Iu.id}`,path:["components"]}),$u.add(Iu.id));const Ru=(Iu,Pu)=>{for(const Ou of Iu)Ou&&!$u.has(Ou)&&lo.addIssue({code:ZodIssueCode.custom,message:`Component '${Pu}' references non-existent component ID '${Ou}'.`,path:["components"]})};for(const Iu of Au.components){if(!Iu.id||!Iu.component)continue;const Pu=Object.keys(Iu.component);if(Pu.length!==1)continue;const Ou=Pu[0],Mu=Iu.component[Ou];switch(Ou){case"Row":case"Column":case"List":if(Mu.children&&!Array.isArray(Mu.children)){const Du=!!Mu.children.explicitList,Lu=!!Mu.children.template;(Du&&Lu||!Du&&!Lu)&&lo.addIssue({code:ZodIssueCode.custom,message:`Component '${Iu.id}' must have either 'explicitList' or 'template' in children, but not both or neither.`}),Du&&Ru(Mu.children.explicitList,Iu.id),Lu&&Ru([Mu.children.template?.componentId],Iu.id)}break;case"Card":Mu.child&&Ru([Mu.child],Iu.id);break;case"Tabs":Mu.tabItems&&Array.isArray(Mu.tabItems)&&Mu.tabItems.forEach(Du=>{Du.child&&Ru([Du.child],Iu.id)});break;case"Modal":Ru([Mu.entryPointChild,Mu.contentChild],Iu.id);break;case"Button":Mu.child&&Ru([Mu.child],Iu.id);break}}}).describe("Updates a surface with a new set of components."),DataModelUpdateMessageSchema=objectType({surfaceId:stringType().describe("The unique identifier for the UI surface this data model update applies to."),path:stringType().optional().describe("An optional path to a location within the data model (e.g., '/user/name'). If omitted, or set to '/', the entire data model will be replaced."),contents:arrayType(ValueMapSchema).describe("An array of data entries. Each entry must contain a 'key' and exactly one corresponding typed 'value*' property.")}).strict().describe("Updates the data model for a surface."),DeleteSurfaceMessageSchema$2=objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be deleted.")}).strict().describe("Signals the client to delete the surface identified by 'surfaceId'."),A2uiMessageSchema$1=objectType({beginRendering:BeginRenderingMessageSchema.optional(),surfaceUpdate:SurfaceUpdateMessageSchema.optional(),dataModelUpdate:DataModelUpdateMessageSchema.optional(),deleteSurface:DeleteSurfaceMessageSchema$2.optional()}).strict().superRefine((Au,lo)=>{Object.keys(Au).filter(Ru=>["beginRendering","surfaceUpdate","dataModelUpdate","deleteSurface"].includes(Ru)).length!==1&&lo.addIssue({code:ZodIssueCode.custom,message:"A2UI Protocol message must have exactly one of: surfaceUpdate, dataModelUpdate, beginRendering, deleteSurface."})}).describe("Describes a JSON payload for an A2UI (Agent to UI) message, which is used to dynamically construct and update user interfaces. A message MUST contain exactly ONE of the action properties: 'beginRendering', 'surfaceUpdate', 'dataModelUpdate', or 'deleteSurface'.");function normalizeV08Component(Au){if(!Au||typeof Au!="object")return{id:"",component:""};const lo=Au;let $u=typeof lo.component=="string"?lo.component:"";const Ru={};for(const[Iu,Pu]of Object.entries(lo))Iu!=="component"&&Iu!=="id"&&(Ru[Iu]=Pu);if(lo.component&&typeof lo.component=="object"){const Iu=lo.component,Pu=Object.keys(Iu);if(Pu.length>0){$u=Pu[0];const Ou=Iu[Pu[0]];Ou&&typeof Ou=="object"&&Ou!==null&&!Array.isArray(Ou)&&Object.assign(Ru,Ou)}}return{...Ru,id:String(lo.id??""),component:$u}}class V0Point8Adapter extends BaseVersionAdapter{constructor(){super(...arguments),this.version="v0.8",this.schema=A2uiMessageSchema$1}getNativeActionKeys(){return["beginRendering","surfaceUpdate","dataModelUpdate","deleteSurface"]}preparePayloadForValidation(lo){const $u={...lo};return delete $u.version,$u}extractOperationsFromObject(lo){const $u=[];if("beginRendering"in lo){const Ru=lo.beginRendering;$u.push({type:"createSurface",surfaceId:String(Ru?.surfaceId??""),catalogId:typeof Ru?.catalogId=="string"?Ru.catalogId:void 0,theme:Ru?.theme??Ru?.styles,sendDataModel:!!Ru?.sendDataModel,components:Array.isArray(Ru?.components)?Ru.components.map(normalizeV08Component):void 0,dataModel:Ru?.dataModel&&typeof Ru.dataModel=="object"&&!Array.isArray(Ru.dataModel)?Ru.dataModel:void 0,version:typeof lo.version=="string"?lo.version:this.version,rootId:typeof Ru?.root=="string"&&Ru.root?Ru.root:void 0})}if("surfaceUpdate"in lo){const Ru=lo.surfaceUpdate;$u.push({type:"updateComponents",surfaceId:String(Ru?.surfaceId??""),components:Array.isArray(Ru?.components)?Ru.components.map(normalizeV08Component):[]})}if("dataModelUpdate"in lo){const Ru=lo.dataModelUpdate,Iu=String(Ru?.surfaceId??"");if(Array.isArray(Ru?.contents)){for(const Pu of Ru.contents)if(Pu&&typeof Pu=="object"&&typeof Pu.key=="string"){const Ou="valueNumber"in Pu?Pu.valueNumber:"valueString"in Pu?Pu.valueString:"valueBoolean"in Pu?Pu.valueBoolean:"valueObject"in Pu?Pu.valueObject:"valueArray"in Pu?Pu.valueArray:Pu.value;$u.push({type:"updateDataModel",surfaceId:Iu,path:Pu.key,value:Ou})}}else $u.push({type:"updateDataModel",surfaceId:Iu,path:typeof Ru?.path=="string"?Ru.path:void 0,value:Ru?.value})}if("deleteSurface"in lo){const Ru=lo.deleteSurface;$u.push({type:"deleteSurface",surfaceId:String(Ru?.surfaceId??"")})}return $u}}const CreateSurfaceMessageSchema$1=objectType({version:enumType(["v0.9","v0.9.1"]),createSurface:objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be rendered."),catalogId:stringType().describe("A string that uniquely identifies this catalog. It is recommended to prefix this with an internet domain that you own, to avoid conflicts e.g. mycompany.com:somecatalog'."),theme:anyType().optional(),sendDataModel:booleanType().describe("If true, the client will send the full data model of this surface in the metadata of every A2A message sent to the server that created the surface. Defaults to false.").optional()}).strict().describe("Signals the client to create a new surface and begin rendering it. It is an error to send 'createSurface' for a surfaceId that already exists without first deleting it. When this message is sent, the client will expect 'updateComponents' and/or 'updateDataModel' messages for the same surfaceId that define the component tree.")}).strict(),UpdateComponentsMessageSchema$1=objectType({version:enumType(["v0.9","v0.9.1"]),updateComponents:objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be updated."),components:arrayType(recordType(stringType(),anyType())).min(1).describe("A list containing all UI components for the surface.")}).strict().describe("Updates a surface with a new set of components. This message can be sent multiple times to update the component tree of an existing surface. One of the components in one of the components lists MUST have an 'id' of 'root' to serve as the root of the component tree. A createSurface message MUST have been previously sent for the 'surfaceId' in this message; the surface's catalog is the one specified by that createSurface.")}).strict(),UpdateDataModelMessageSchema$1=objectType({version:enumType(["v0.9","v0.9.1"]),updateDataModel:objectType({surfaceId:stringType().describe("The unique identifier for the UI surface this data model update applies to."),path:stringType().describe("An optional path to a location within the data model (e.g., '/user/name'). If omitted, or set to '/', refers to the entire data model.").optional(),value:anyType().describe("The data to be updated in the data model. If present, the value at 'path' is replaced (or created). If omitted, the key at 'path' is removed.").optional()}).strict().describe("Updates the data model for an existing surface. This message can be sent multiple times to update the data model. A createSurface message MUST have been previously sent for the 'surfaceId' in this message; the surface's catalog is the one specified by that createSurface.")}).strict(),DeleteSurfaceMessageSchema$1=objectType({version:enumType(["v0.9","v0.9.1"]),deleteSurface:objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be deleted.")}).strict().describe("Signals the client to delete the surface identified by 'surfaceId'. A createSurface message MUST have been previously sent for the 'surfaceId' in this message; the surface's catalog is the one specified by that createSurface.")}).strict(),A2uiMessageSchema=unionType([CreateSurfaceMessageSchema$1,UpdateComponentsMessageSchema$1,UpdateDataModelMessageSchema$1,DeleteSurfaceMessageSchema$1]),A2uiMessageListSchema=arrayType(A2uiMessageSchema).describe("A list of messages.");objectType({messages:A2uiMessageListSchema}).strict().describe("An object wrapping a list of messages.");class V0Point9Adapter extends BaseVersionAdapter{constructor(){super(...arguments),this.version="v0.9",this.schema=A2uiMessageSchema}get compatibleCatalogVersions(){return new Set(["0.9","0.9.1"])}getNativeActionKeys(){return["createSurface","updateComponents","updateDataModel","deleteSurface"]}extractOperationsFromObject(lo){const $u=[];if("createSurface"in lo){const Ru=lo.createSurface;$u.push({type:"createSurface",surfaceId:String(Ru?.surfaceId||""),catalogId:typeof Ru?.catalogId=="string"?Ru.catalogId:void 0,theme:Ru?.theme,sendDataModel:!!Ru?.sendDataModel,components:Array.isArray(Ru?.components)?Ru.components:void 0,dataModel:Ru?.dataModel&&typeof Ru.dataModel=="object"&&!Array.isArray(Ru.dataModel)?Ru.dataModel:void 0,version:typeof lo.version=="string"?lo.version:this.version})}if("updateComponents"in lo){const Ru=lo.updateComponents;$u.push({type:"updateComponents",surfaceId:String(Ru?.surfaceId||""),components:Array.isArray(Ru?.components)?Ru.components:[]})}if("updateDataModel"in lo){const Ru=lo.updateDataModel;$u.push({type:"updateDataModel",surfaceId:String(Ru?.surfaceId||""),path:typeof Ru?.path=="string"?Ru.path:void 0,value:Ru?.value})}if("deleteSurface"in lo){const Ru=lo.deleteSurface;$u.push({type:"deleteSurface",surfaceId:String(Ru?.surfaceId||"")})}return $u}}const INTERNAL_OPERATION_TYPES=["createSurface","updateComponents","updateDataModel","deleteSurface","callRendererFunction","agentFunctionResponse"];function isInternalOperation(Au){return typeof Au=="object"&&Au!==null&&"type"in Au&&typeof Au.type=="string"&&INTERNAL_OPERATION_TYPES.includes(Au.type)}objectType({componentId:lazyType(()=>ComponentIdSchema$1),path:stringType().describe("The path to the list of component property objects in the data model.")}).strict().describe("REF:#/$defs/TemplateChildList|A template for generating a dynamic list of children from a data model list. The `componentId` is the component to use as a template.");const AnyComponentSchema=lazyType(()=>ComponentCommonSchema.extend({component:stringType()}).passthrough().refine(Au=>Au.component!=="Surface",{message:'Component type cannot be "Surface". "Surface" is a top-level protocol container defined in createSurface, not a child component.'})),ComponentsListSchema=arrayType(AnyComponentSchema).min(1);recordType(stringType(),anyType());const ComponentIdSchema$1=markChildRef(stringType().describe("REF:#/$defs/ComponentId|The unique identifier for a component, used for both definitions and references within the same surface."),"component-id"),CallIdSchema=stringType().describe("REF:#/$defs/CallId|The unique identifier for a function call."),DataBindingSchema$1=objectType({path:stringType().describe("A JSON Pointer path to a value in the data model.")}).strict().describe("REF:#/$defs/DataBinding"),FunctionCommonSchema=objectType({call:stringType().describe("The name of the function to call."),catalogId:stringType().describe("The catalog ID for this function, overriding any surface-level default catalogId.").optional()}).describe("REF:#/$defs/FunctionCommon|Baseline envelope properties common to all function calls. Function-specific argument schemas ('args') are defined individually by each function in the active catalog."),FunctionCallSchema$1=recordType(stringType(),anyType()).and(intersectionType(FunctionCommonSchema,anyType())).describe("REF:#/$defs/FunctionCall|Invokes a named function, combining common function properties with the catalog function definition."),DynamicStringSchema$1=unionType([stringType(),DataBindingSchema$1,FunctionCallSchema$1]).describe("REF:#/$defs/DynamicString|Represents a string"),DynamicBooleanSchema$1=unionType([booleanType(),DataBindingSchema$1,FunctionCallSchema$1]).describe("REF:#/$defs/DynamicBoolean|A boolean value that can be a literal, a path, or a function call returning a boolean."),AccessibilityAttributesSchema$1=objectType({label:DynamicStringSchema$1.optional(),description:DynamicStringSchema$1.optional(),live:enumType(["off","polite","assertive"]).describe("Controls screen reader announcements for dynamic updates (WAI-ARIA aria-live). 'polite' waits for user pause; 'assertive' interrupts immediately for alerts.").default("off"),hidden:DynamicBooleanSchema$1.optional()}).strict().describe("REF:#/$defs/AccessibilityAttributes|Attributes to enhance accessibility when using assistive technologies like screen readers or model understanding."),ExtensionsSchema=recordType(stringType(),unknownType()).superRefine((Au,lo)=>{for(const $u in Au)$u.match(/^[\p{XID_Start}_][\p{XID_Continue}:-]*$/u)||lo.addIssue({path:[$u],code:ZodIssueCode.custom,message:`Invalid extension key "${$u}": Keys MUST be Unicode identifiers (UAX #31).`})}).describe("REF:#/$defs/Extensions|Optional extension metadata. Keys MUST be Unicode identifiers (UAX #31). Keys starting with 'a2ui_' are reserved for official extensions."),ComponentCommonSchema=objectType({id:ComponentIdSchema$1,catalogId:stringType().describe("The catalog ID for this component, overriding any surface-level default catalogId.").optional(),accessibility:AccessibilityAttributesSchema$1.optional(),metadata:objectType({extensions:ExtensionsSchema.optional()}).strict().describe("Optional component-level metadata for vendor extensions.").optional()}).describe("REF:#/$defs/ComponentCommon");markChildRef(unionType([arrayType(ComponentIdSchema$1).describe("A static list of child component IDs."),objectType({componentId:ComponentIdSchema$1,path:stringType().describe("The path to the list of component property objects in the data model.")}).strict().describe("A template for generating a dynamic list of children from a data model list. The `componentId` is the component to use as a template.")]).describe("REF:#/$defs/ChildList"),"child-list");const DynamicValueSchema$1=unionType([stringType(),numberType(),booleanType(),arrayType(anyType()),recordType(stringType(),unknownType()).refine(Au=>!Au||!("path"in Au)&&!("call"in Au)),DataBindingSchema$1,FunctionCallSchema$1]).describe("REF:#/$defs/DynamicValue|A value that can be a literal, a path, or a function call returning any type."),DynamicNumberSchema$1=unionType([numberType(),DataBindingSchema$1,FunctionCallSchema$1]).describe("REF:#/$defs/DynamicNumber|Represents a value that can be either a literal number, a path to a number in the data model, or a function call returning a number.");unionType([arrayType(stringType()),DataBindingSchema$1,FunctionCallSchema$1]).describe("REF:#/$defs/DynamicStringList|Represents a value that can be either a literal array of strings, a path to a string array in the data model, or a function call returning a string array.");objectType({call:literalType("@index"),args:objectType({offset:DynamicNumberSchema$1.optional()}).optional()}).describe("REF:#/$defs/IndexSystemFunction|Returns the 0-based index of the current item when rendering a dynamic list from a template. This function MUST ONLY be available when evaluating template items within a list context.");const CheckRuleSchema$1=objectType({condition:unionType([DataBindingSchema$1,FunctionCallSchema$1]).describe("Path or function call evaluating to a structured validation result object."),message:stringType().describe("Optional fallback error message.").optional()}).strict().describe("REF:#/$defs/CheckRule|A single validation check rule applied to an input component. The condition function or path evaluates to a structured validation result object.");objectType({checks:arrayType(CheckRuleSchema$1).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional()}).describe("REF:#/$defs/Checkable|Properties for components that support renderer-side checks.");unionType([objectType({event:objectType({name:stringType().describe("The name of the action to be dispatched to the agent."),userMessage:DynamicStringSchema$1.optional(),context:recordType(stringType(),DynamicValueSchema$1).describe("A JSON object containing the key-value pairs for the action context. Values can be literals or paths. Use literal values unless the value must be dynamically bound to the data model. Do NOT use paths for static IDs.").optional()}).strict().describe("The event to dispatch to the agent.")}).strict().describe("Triggers an agent-side event."),objectType({functionCall:FunctionCallSchema$1}).strict().describe("Executes a renderer or agent-side function.")]).describe("REF:#/$defs/Action|Defines an interaction handler that can either trigger an agent-side event or execute a local renderer-side function.");objectType({component:literalType("Surface").optional(),child:literalType("root").optional()}).strict().describe("REF:#/$defs/Surface|The reserved canonical container component representing an A2UI surface. The Surface component is immutable and always has 'child': 'root'.");const FunctionResponseSchema=objectType({functionCallId:CallIdSchema,value:anyType().describe("The return value of the function.").optional(),error:objectType({code:stringType(),message:stringType()}).strict().describe("An error object indicating failure of the function execution.").optional()}).strict().superRefine((Au,lo)=>{const $u="value"in Au,Ru="error"in Au;($u&&Ru||!$u&&!Ru)&&lo.addIssue({code:ZodIssueCode.custom,message:'FunctionResponse must have either "value" or "error", but not both or neither.'})}).describe("REF:#/$defs/FunctionResponse|The return response matching a callAgentFunction or callRendererFunction invocation."),CreateSurfaceMessageSchema=objectType({version:literalType("v1.0"),createSurface:objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be rendered. It must be globally unique for the renderer's lifetime."),catalogId:stringType().describe("A string that uniquely identifies the default catalog for this surface. It is recommended to prefix this with an internet domain that you own, to avoid conflicts e.g. 'mycompany.com:somecatalog'. Components and function calls that do not explicitly specify a catalogId will use this surface-level default catalogId.").optional(),sendDataModel:booleanType().describe("If true, the renderer will send the full data model of this surface in the metadata of every A2A message sent to the agent that created the surface. Defaults to false.").optional(),components:ComponentsListSchema.optional(),dataModel:recordType(stringType(),anyType()).describe("The initial root data model object for the surface.").optional(),metadata:objectType({extensions:ExtensionsSchema.optional()}).strict().describe("Optional surface-level metadata.").optional()}).strict().describe("Signals the renderer to create a new surface and begin rendering it. Creating a surface implicitly instantiates the canonical 'Surface' container component ('common_types.json#/$defs/Surface') with 'child': 'root'. It is an error to try to create a surface with an existing ID without first deleting it; surfaceId MUST be globally unique for the renderer's lifetime. When this message is sent, the renderer expects 'updateComponents' and/or 'updateDataModel' messages for the same surfaceId to define the component tree.")}).strict(),UpdateComponentsMessageSchema=objectType({version:literalType("v1.0"),updateComponents:objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be updated. It must be globally unique for the renderer's lifetime."),components:ComponentsListSchema}).strict().describe("Updates a surface with a new set of components. This message can be sent multiple times to update the component tree of an existing surface. One of the components in one of the components lists MUST have an 'id' of 'root' to serve as the root of the component tree. The createSurface message MUST have been previously sent for this surfaceId.")}).strict(),UpdateDataModelMessageSchema=objectType({version:literalType("v1.0"),updateDataModel:objectType({surfaceId:stringType().describe("The unique identifier for the UI surface this data model update applies to. It must be globally unique for the renderer's lifetime."),path:stringType().describe("An optional path to a location within the data model (e.g., '/user/name'). If omitted, or set to '/', refers to the entire data model.").optional(),value:anyType().describe("The data to be updated in the data model. To delete the key/value at 'path', set 'value' explicitly to null.")}).strict().describe("Updates the data model for an existing surface. This message can be sent multiple times to update the data model. The createSurface message MUST have been previously sent for this surfaceId.")}).strict(),DeleteSurfaceMessageSchema=objectType({version:literalType("v1.0"),deleteSurface:objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be deleted. It must be globally unique for the renderer's lifetime.")}).strict().describe("Signals the renderer to delete the surface identified by 'surfaceId'. The createSurface message MUST have been previously sent for this surfaceId.")}).strict(),CallRendererFunctionMessageSchema=objectType({version:literalType("v1.0"),callRendererFunction:objectType({functionCallId:CallIdSchema,callFunction:intersectionType(FunctionCallSchema$1,anyType())}).strict().describe("Signals the renderer to execute a function locally on behalf of the agent.")}).strict(),AgentFunctionResponseMessageSchema=objectType({version:literalType("v1.0"),agentFunctionResponse:FunctionResponseSchema}).strict(),AgentToRendererMessageSchema=unionType([CreateSurfaceMessageSchema,UpdateComponentsMessageSchema,UpdateDataModelMessageSchema,DeleteSurfaceMessageSchema,CallRendererFunctionMessageSchema,AgentFunctionResponseMessageSchema]);class V1Point0Adapter extends BaseVersionAdapter{constructor(){super(...arguments),this.version="v1.0",this.schema=AgentToRendererMessageSchema}getNativeActionKeys(){return[...INTERNAL_OPERATION_TYPES]}extractOperationsFromObject(lo){const $u=[];if("createSurface"in lo){const Ru=lo.createSurface;$u.push({type:"createSurface",surfaceId:String(Ru?.surfaceId||""),catalogId:typeof Ru?.catalogId=="string"?Ru.catalogId:void 0,sendDataModel:!!Ru?.sendDataModel,components:Array.isArray(Ru?.components)?Ru.components:void 0,dataModel:Ru?.dataModel&&typeof Ru.dataModel=="object"&&!Array.isArray(Ru.dataModel)?Ru.dataModel:void 0,version:typeof lo.version=="string"?lo.version:this.version})}if("updateComponents"in lo){const Ru=lo.updateComponents;$u.push({type:"updateComponents",surfaceId:String(Ru?.surfaceId||""),components:Array.isArray(Ru?.components)?Ru.components:[]})}if("updateDataModel"in lo){const Ru=lo.updateDataModel;$u.push({type:"updateDataModel",surfaceId:String(Ru?.surfaceId||""),path:typeof Ru?.path=="string"?Ru.path:void 0,value:Ru?.value})}if("deleteSurface"in lo){const Ru=lo.deleteSurface;$u.push({type:"deleteSurface",surfaceId:String(Ru?.surfaceId||"")})}if("callRendererFunction"in lo){const Ru=lo.callRendererFunction,Iu=Ru?.callFunction||{};$u.push({type:"callRendererFunction",functionCallId:String(Ru?.functionCallId||""),call:String(Iu?.call||""),version:this.version,catalogId:typeof Iu?.catalogId=="string"?Iu.catalogId:void 0,args:Iu?.args&&typeof Iu.args=="object"&&!Array.isArray(Iu.args)?Iu.args:{}})}if("agentFunctionResponse"in lo){const Ru=lo.agentFunctionResponse;$u.push({type:"agentFunctionResponse",functionCallId:String(Ru?.functionCallId||""),version:this.version,value:Ru?.value,error:Ru?.error&&typeof Ru.error=="object"?Ru.error:void 0})}return $u}}class VersionAdapterFactory{constructor(){this.adapters=new Map([["0.8",new V0Point8Adapter],["0.9",new V0Point9Adapter],["0.9.1",new V0Point9Adapter],["1.0",new V1Point0Adapter]])}getAllKnownActions(){const lo=new Set;for(const $u of this.adapters.values())if($u.validActions)for(const Ru of $u.validActions)lo.add(Ru);return lo}registerAdapter(lo){const $u=toCanonicalVersion(lo.version)??normalizeVersionString(lo.version);this.adapters.set($u,lo)}getAdapter(lo){const $u=toCanonicalVersion(lo)??normalizeVersionString(lo),Ru=this.adapters.get($u);if(!Ru){const Iu=Array.from(new Set(Array.from(this.adapters.keys()).map(Pu=>Pu.startsWith("v")?Pu:`v${Pu}`))).sort().join(", ");throw new A2uiValidationError(`[VersionAdapterFactory] Unsupported protocol version '${lo}'. Supported versions: ${Iu}.`)}return Ru}resolveFromPayload(lo){const $u=Array.isArray(lo)?lo[0]:lo;if(typeof $u=="object"&&$u!==null){if("messages"in $u&&Array.isArray($u.messages))return this.resolveFromPayload($u.messages);if("version"in $u){const Ru=$u.version;if(typeof Ru!="string")throw new A2uiValidationError(`[VersionAdapterFactory] Message payload is missing a valid 'version' string: 'version' property must be a string, got ${typeof Ru}.`);return this.getAdapter(Ru)}if("beginRendering"in $u||"surfaceUpdate"in $u||"dataModelUpdate"in $u||"deleteSurface"in $u)return this.getAdapter("v0.8")}throw new A2uiValidationError("[VersionAdapterFactory] Message payload is missing a valid 'version' string.")}static registerAdapter(lo){defaultVersionAdapterFactory.registerAdapter(lo)}static getAdapter(lo){return defaultVersionAdapterFactory.getAdapter(lo)}static resolveFromPayload(lo){return defaultVersionAdapterFactory.resolveFromPayload(lo)}static getAllKnownActions(){return defaultVersionAdapterFactory.getAllKnownActions()}}const defaultVersionAdapterFactory=new VersionAdapterFactory;registerKnownActionsProvider(()=>defaultVersionAdapterFactory.getAllKnownActions());const schemaKeysCache=new WeakMap;function getKnownSchemaKeys(Au){if(schemaKeysCache.has(Au))return schemaKeysCache.get(Au);const lo=(()=>{let $u=Au;for(;$u;){if($u instanceof ZodObject||$u._def?.typeName==="ZodObject"){if($u._def?.unknownKeys==="passthrough")return null;const Ru=typeof $u.shape=="function"?$u.shape():$u.shape;return Ru&&typeof Ru=="object"?new Set(Object.keys(Ru)):null}if($u instanceof ZodEffects||$u._def?.typeName==="ZodEffects"){$u=$u._def.schema;continue}if($u instanceof ZodOptional||$u instanceof ZodNullable||$u._def?.typeName==="ZodOptional"||$u._def?.typeName==="ZodNullable"){$u=$u._def.innerType;continue}if($u instanceof ZodDefault||$u._def?.typeName==="ZodDefault"){$u=$u._def.innerType;continue}if($u instanceof ZodCatch||$u._def?.typeName==="ZodCatch"){$u=$u._def.innerType;continue}if($u instanceof ZodIntersection||$u._def?.typeName==="ZodIntersection"){const Ru=getKnownSchemaKeys($u._def.left),Iu=getKnownSchemaKeys($u._def.right);return!Ru||!Iu?null:new Set([...Ru,...Iu])}if($u instanceof ZodUnion||$u._def?.typeName==="ZodUnion"){const Ru=$u._def.options,Iu=new Set;for(const Pu of Ru){const Ou=getKnownSchemaKeys(Pu);if(!Ou)return null;for(const Mu of Ou)Iu.add(Mu)}return Iu}return null}return null})();return schemaKeysCache.set(Au,lo),lo}function validateFunctionArgs(Au,lo,$u){if(!lo||typeof lo!="object"||Array.isArray(lo))return;const Ru=Object.keys(lo);if(Ru.length>MAX_FUNCTION_CALL_ARGS)throw new A2uiExpressionError(`Function call '${Au}' exceeds maximum allowed arguments count (${MAX_FUNCTION_CALL_ARGS})`,Au);const Iu=$u?.functions?.get?.(Au);if(!Iu?.schema)return;const Pu=getKnownSchemaKeys(Iu.schema);if(Pu){for(const Ou of Ru)if(!Pu.has(Ou))throw new A2uiExpressionError(`Unknown argument '${Ou}' passed to function '${Au}'`,Au);if(Ru.length>Pu.size)throw new A2uiExpressionError(`Too many arguments for function '${Au}': expected at most ${Pu.size}, received ${Ru.length}`,Au)}}function resolveContextIndex(Au){let lo=Au;for(;lo;){if(lo.explicitIndex!==void 0&&Number.isFinite(lo.explicitIndex))return lo.explicitIndex;if(!(lo instanceof DataContext)&&typeof lo.getIndex=="function"){const $u=lo.getIndex();if($u!==void 0&&Number.isFinite($u))return $u}if(!(lo instanceof DataContext)&&typeof lo.index=="number"&&Number.isFinite(lo.index))return lo.index;if(typeof lo.path=="string"){const $u=lo.path.split("/").filter(Boolean);if($u.length>0&&/^\d+$/.test($u[$u.length-1]))return parseInt($u[$u.length-1],10)}lo=lo.parent}}const MAX_DYNAMIC_VALUE_DEPTH=1e3;class DataContext{constructor(lo,$u,Ru,Iu){this.surface=lo,this.path=$u,this.dataModel=lo.dataModel,this.functionInvoker=lo.defaultCatalog.invoker,this.explicitIndex=Ru,this.parent=Iu,this.warnedPaths=Iu?Iu.warnedPaths:new Set}getIndex(){return resolveContextIndex(this)}get index(){return this.getIndex()}set(lo,$u){const Ru=this.resolvePath(lo);this.dataModel.set(Ru,$u)}static isDataBindingObject(lo){return"path"in lo&&typeof lo.path=="string"&&!("componentId"in lo)}static isFunctionCallObject(lo){return"call"in lo&&typeof lo.call=="string"}static containsDynamicValue(lo){if(lo===null||typeof lo!="object")return!1;if(Array.isArray(lo))return lo.some(Ru=>DataContext.containsDynamicValue(Ru));const $u=lo;return DataContext.isDataBindingObject($u)||DataContext.isFunctionCallObject($u)?!0:Object.values($u).some(Ru=>DataContext.containsDynamicValue(Ru))}emitMissingDataBindingWarning(lo){typeof this.dataModel?.hasPath=="function"&&!this.dataModel.hasPath(lo)&&!this.warnedPaths.has(lo)&&(this.warnedPaths.add(lo),this.surface?.dispatchWarning?.({code:"MISSING_DATA_BINDING",path:lo,message:`Preflight DataBinding Warning: The bound JSON Pointer '${lo}' does not physically exist in the active DataModel. Evaluating to None.`}))}resolveDynamicValue(lo,$u=0){if($u>MAX_DYNAMIC_VALUE_DEPTH){const Iu=new A2uiExpressionError(`Maximum dynamic value nesting depth exceeded (${MAX_DYNAMIC_VALUE_DEPTH})`);this.dispatchExpressionError(Iu,"DynamicValue");return}if(lo===null||typeof lo!="object")return lo;if(Array.isArray(lo))return DataContext.containsDynamicValue(lo)?lo.map(Iu=>this.resolveDynamicValue(Iu,$u+1)):lo;const Ru=lo;if(DataContext.isDataBindingObject(Ru)){const Iu=this.resolvePath(lo.path),Pu=this.dataModel.get(Iu);return Pu===void 0&&this.emitMissingDataBindingWarning(Iu),Pu}return DataContext.isFunctionCallObject(Ru)?this.resolveFunctionCallValue(lo,$u):this.resolvePlainObjectValue(Ru,$u)}resolveFunctionCallValue(lo,$u=0){let Ru;try{Ru=this.resolveFunctionCatalog(lo.catalogId),validateFunctionArgs(lo.call,lo.args,Ru)}catch(Mu){this.dispatchExpressionError(Mu,lo.call);return}const Iu={};for(const[Mu,Du]of Object.entries(lo.args??{}))Iu[Mu]=this.resolveDynamicValue(Du,$u+1);const Pu=new AbortController,Ou=this.evaluateFunctionReactive(lo.call,Iu,Pu.signal,lo.catalogId,Ru.invoker);if(Ou!==void 0)return isSignal(Ou)?peekValue(Ou):Ou}resolvePlainObjectValue(lo,$u=0){if(!DataContext.containsDynamicValue(lo))return lo;const Ru={};for(const[Iu,Pu]of Object.entries(lo))Ru[Iu]=this.resolveDynamicValue(Pu,$u+1);return Ru}subscribeDynamicValue(lo,$u){const Ru=this.resolveSignal(lo);let Iu=!0,Pu=peekValue(Ru);const Ou=effect(()=>{const Mu=getValue(Ru);Pu=Mu,Iu||$u(Mu)});return Iu=!1,{get value(){return Pu},unsubscribe:()=>{Ou(),Ru.unsubscribe?.()}}}resolveSignal(lo,$u=0){if($u>MAX_DYNAMIC_VALUE_DEPTH){const Mu=new A2uiExpressionError(`Maximum dynamic value nesting depth exceeded (${MAX_DYNAMIC_VALUE_DEPTH})`);return this.dispatchExpressionError(Mu,typeof lo=="object"&&lo&&"call"in lo?lo.call:"DynamicValue"),signal(void 0)}if(typeof lo!="object"||lo===null)return signal(lo);if(Array.isArray(lo)){if(!DataContext.containsDynamicValue(lo))return signal(lo);const Mu=lo.map(Lu=>this.resolveSignal(Lu,$u+1)),Du=computed(()=>Mu.map(Lu=>getValue(Lu)));return Du.unsubscribe=()=>{for(const Lu of Mu)Lu.unsubscribe?.()},Du}const Ru=lo;if(DataContext.isDataBindingObject(Ru)){const Mu=this.resolvePath(lo.path);return this.emitMissingDataBindingWarning(Mu),this.dataModel.getSignal(Mu)}if(DataContext.isFunctionCallObject(Ru)){const Mu=lo;let Du;try{Du=this.resolveFunctionCatalog(Mu.catalogId),validateFunctionArgs(Mu.call,Mu.args,Du)}catch(Vu){return this.dispatchExpressionError(Vu,Mu.call),signal(void 0)}const Lu={};for(const[Vu,Gu]of Object.entries(Mu.args??{}))Lu[Vu]=this.resolveSignal(Gu,$u+1);if(Object.keys(Lu).length===0){const Vu=new AbortController,Gu=this.evaluateFunctionReactive(Mu.call,{},Vu.signal,Mu.catalogId,Du.invoker),Wu=isSignal(Gu)?Gu:signal(Gu);return Wu.unsubscribe=()=>Vu.abort(),Wu}const Bu=Object.keys(Lu),ju=signal(void 0);let Fu,zu;const Uu=computed(()=>{const Vu={};for(let Gu=0;Gu<Bu.length;Gu++)Vu[Bu[Gu]]=getValue(Lu[Bu[Gu]]);return Vu}),Hu=effect(()=>{try{const Vu=getValue(Uu);Fu&&Fu.abort(),zu&&(zu(),zu=void 0),Fu=new AbortController;const Gu=this.evaluateFunctionReactive(Mu.call,Vu,Fu.signal,Mu.catalogId,Du.invoker);isSignal(Gu)?zu=effect(()=>{setValue(ju,getValue(Gu))}):setValue(ju,Gu)}catch(Vu){this.dispatchExpressionError(Vu,Mu.call),setValue(ju,void 0)}});return ju.unsubscribe=()=>{Hu(),zu&&zu(),Fu&&Fu.abort();for(let Vu=0;Vu<Bu.length;Vu++)Lu[Bu[Vu]].unsubscribe?.()},ju}if(!DataContext.containsDynamicValue(Ru))return signal(lo);const Iu=Object.entries(Ru).map(([Mu,Du])=>[Mu,this.resolveSignal(Du)]),Pu=computed(()=>{const Mu={};for(const[Du,Lu]of Iu)Mu[Du]=getValue(Lu);return Mu}),Ou=Pu.unsubscribe?.bind(Pu);return Pu.unsubscribe=()=>{Ou?.();for(const[,Mu]of Iu)Mu.unsubscribe?.()},Pu}resolveAction(lo){if("event"in lo){const $u={};if(lo.event.context)for(const[Ru,Iu]of Object.entries(lo.event.context))$u[Ru]=this.resolveDynamicValue(Iu);return{event:{...lo.event,context:$u}}}return"functionCall"in lo?this.resolveDynamicValue(lo.functionCall):lo}resolveFunctionCatalog(lo){if(lo===void 0)return this.surface.defaultCatalog;const $u=this.surface.availableCatalogs?.get(lo);if(!$u)throw new A2uiCatalogError(`Catalog not found: ${lo}`);return $u}evaluateFunctionReactive(lo,$u,Ru,Iu,Pu){const Ou=Pu??(Iu===void 0?this.functionInvoker:this.resolveFunctionCatalog(Iu).invoker);try{return Ou(lo,$u,this,Ru)}catch(Mu){this.dispatchExpressionError(Mu,lo);return}}dispatchExpressionError(lo,$u){if(lo instanceof ZodError||typeof lo=="object"&&lo!==null&&lo.name==="ZodError"){const Ru=lo,Iu=new A2uiExpressionError(`Validation failed for function '${$u}': ${Ru.message}`,$u,Ru.errors??Ru.issues);this.surface.dispatchError({code:"EXPRESSION_ERROR",message:Iu.message,expression:$u,details:Iu.details})}else if(lo instanceof A2uiExpressionError)this.surface.dispatchError({code:"EXPRESSION_ERROR",message:lo.message,expression:lo.expression,details:lo.details});else{const Ru=typeof lo=="object"&&lo!==null?lo:{};this.surface.dispatchError({code:"EXPRESSION_ERROR",message:Ru.message??`An unexpected error occurred in function ${$u}.`,expression:$u})}}nested(lo,$u){const Ru=this.resolvePath(lo);return new DataContext(this.surface,Ru,$u,this)}resolvePath(lo){if(lo.startsWith("/"))return lo;if(lo===""||lo===".")return this.path;let $u=this.path;return $u.endsWith("/")&&$u.length>1&&($u=$u.slice(0,-1)),$u==="/"&&($u=""),`${$u}/${lo}`}}const IndexApi={name:"@index",returnType:"number",allowedCallers:"rendererOnly",schema:objectType({offset:coerce.number().optional()})};createFunctionImplementation(IndexApi,(Au,lo)=>{const $u=typeof Au.offset=="number"&&Number.isFinite(Au.offset)?Au.offset:0,Ru=resolveContextIndex(lo);if(Ru===void 0||!Number.isFinite(Ru))throw new A2uiValidationError("@index function can only be evaluated inside a collection template iteration scope.");return Ru+$u});const COMPONENT_ENVELOPE_KEYS=["id","component","catalogId","catalogID"];class PayloadValidator{constructor(lo,$u){this.catalog=lo,this.config=$u,this.enforceIdentifiers=isAtLeastVersion(lo.protocolVersion,"1.0")}get allowUnknown(){return this.config?this.config.allowUnknownElements??!1:!0}validateComponent(lo,$u){const Ru=lo.id;if(typeof Ru!="string"||!Ru)throw new A2uiValidationError(`Component '${lo.component}' is missing an 'id'; entries require a valid string 'id'.`);this.assertIdentifier(Ru,`Component id '${Ru}' must be a valid UAX #31 identifier`);const Iu=lo.component,Pu=typeof Iu=="string"?Iu:$u;if(!Pu)throw new A2uiValidationError(`Cannot create component ${Ru} without a type.`);const Ou=this.catalog.components.get(Pu);if(!Ou){if(!this.allowUnknown)throw new A2uiValidationError(`Unknown component type '${Pu}' not found in catalog '${this.catalog.id}'.`);return}const Mu=stripEnvelopeKeys(lo),Du=Ou.schema.safeParse(Mu);if(!Du.success){const Lu=Du.error.errors.map(formatZodIssue).join(", ");throw new A2uiValidationError(`Validation failed for component '${Pu}' (${Ru}): ${Lu}`,Du.error.issues)}this.validateNestedFunctions(Mu)}assertFunctionIdentifiers(lo,$u){if(this.assertIdentifier(lo,`Function name '${lo}' must be a valid UAX #31 identifier`),$u&&typeof $u=="object"&&!Array.isArray($u)){const Ru=Object.keys($u);if(Ru.length>MAX_FUNCTION_CALL_ARGS)throw new A2uiValidationError(`Function call '${lo}' exceeds maximum allowed arguments count (${MAX_FUNCTION_CALL_ARGS})`);for(const Iu of Ru)this.assertIdentifier(Iu,`Function argument '${Iu}' in function '${lo}' must be a valid UAX #31 identifier`)}}validateNestedFunctions(lo){if(Array.isArray(lo)){for(const Iu of lo)this.validateNestedFunctions(Iu);return}if(typeof lo!="object"||lo===null)return;const $u=lo,Ru=$u.call??$u.function;if(typeof Ru=="string"&&Ru.length>0){const Iu=$u.args,Pu=Iu!==void 0?Iu:{},Ou=typeof $u.catalogId=="string"&&$u.catalogId.length>0?$u.catalogId:void 0;Ou&&Ou!==this.catalog.id?this.assertFunctionIdentifiers(Ru,Pu):this.validateFunction(Ru,Pu)}for(const[Iu,Pu]of Object.entries($u))Iu!=="id"&&Iu!=="component"&&this.validateNestedFunctions(Pu)}validateFunction(lo,$u){this.assertFunctionIdentifiers(lo,$u);const Ru=this.catalog.functions.get(lo)??(this.enforceIdentifiers&&lo==="@index"?IndexApi:void 0);if(!Ru){if(!this.allowUnknown)throw new A2uiValidationError(`Unrecognized function '${lo}'`);return $u??{}}if(!Ru.schema){if($u!==void 0&&(typeof $u!="object"||$u===null||Array.isArray($u)))throw new A2uiValidationError(`Validation failed for function '${lo}': Expected object, received ${Array.isArray($u)?"array":typeof $u}`);return $u??{}}const Iu=Ru.schema.safeParse($u??{});if(!Iu.success){const Pu=Iu.error.errors.map(formatZodIssue).join(", ");throw new A2uiValidationError(`Validation failed for function '${lo}': ${Pu}`,Iu.error.issues)}return Iu.data}validateTheme(lo){const $u=this.catalog.themeSchema;if(!$u)return lo;const Ru=$u.safeParse(lo);if(!Ru.success){const Iu=Ru.error.errors.map(formatZodIssue).join(", ");throw new A2uiValidationError(`Validation failed for theme: ${Iu}`,Ru.error.issues)}return Ru.data}assertIdentifier(lo,$u){if(this.enforceIdentifiers&&!isValidUax31Identifier(lo))throw new A2uiValidationError($u)}}function stripEnvelopeKeys(Au){const lo={};for(const[$u,Ru]of Object.entries(Au))COMPONENT_ENVELOPE_KEYS.includes($u)||(lo[$u]=Ru);return lo}class RpcHandler{constructor(lo,$u){if(this.pendingAgentCalls=new Map,this.isDisposed=!1,Array.isArray(lo))this.catalogs=lo,this.outboundListener=$u,this.defaultTimeoutMs=3e4;else{const Ru=lo??{};this.catalogs=Ru.catalogs??[],this.outboundListener=Ru.outboundListener,this.defaultTimeoutMs=Ru.defaultTimeoutMs??3e4}}get disposed(){return this.isDisposed}async handleCallRendererFunction(lo,$u,Ru=!1){const Iu=this.validateInboundMessage(lo);if(Iu)return await this.emitOutboundResponse(Iu),Iu;const{version:Pu,callRendererFunction:Ou}=lo,{functionCallId:Mu,callFunction:Du}=Ou,{call:Lu,catalogId:Bu,args:ju}=Du,Fu=this.resolveFunctionImplementation(Bu,Lu,$u,Pu);if("error"in Fu){const Vu=this.createResponseError(Mu,RpcErrorCode.INVALID_FUNCTION_CALL,Fu.error,Pu);return await this.emitOutboundResponse(Vu),Vu}const zu=this.checkExecutionPermissions(Fu.funcImpl,Lu,Ru);if(zu){const Vu=this.createResponseError(Mu,RpcErrorCode.INVALID_FUNCTION_CALL,zu,Pu);return await this.emitOutboundResponse(Vu),Vu}const Uu=this.parseArguments(Fu.catalog,Fu.funcImpl,ju,Lu);if("error"in Uu){const Vu=this.createResponseError(Mu,RpcErrorCode.INVALID_FUNCTION_CALL,Uu.error,Pu);return await this.emitOutboundResponse(Vu),Vu}const Hu=await this.executeFunctionSafely(Fu.funcImpl,Uu.args,$u,Mu,Pu);return await this.emitOutboundResponse(Hu),Hu}handleAgentFunctionResponse(lo){if(!lo||!lo.agentFunctionResponse)return;const{functionCallId:$u,value:Ru,error:Iu}=lo.agentFunctionResponse,Pu=this.pendingAgentCalls.get($u);if(Pu)if(this.pendingAgentCalls.delete($u),Iu){const Ou=Iu.code??RpcErrorCode.UNKNOWN_ERROR,Mu=Iu.message??"Agent function execution failed";Pu.reject(new A2uiRpcError(Mu,Ou,$u,Iu))}else Pu.resolve(Ru)}callAgentFunction(lo,$u,Ru){if(this.isDisposed)return Promise.reject(new A2uiRpcError("RpcHandler has been disposed.",RpcErrorCode.DISPOSED));if(!this.outboundListener)return Promise.reject(new A2uiRpcError("Cannot call agent function without outboundListener configured.",RpcErrorCode.NO_LISTENER));if(!$u||!$u.call)return Promise.reject(new A2uiRpcError("Missing or invalid function call name.",RpcErrorCode.INVALID_FUNCTION_CALL));const Iu=Ru??{},Pu=Iu.functionCallId??this.generateFunctionCallId(),Ou=Iu.timeoutMs??this.defaultTimeoutMs;if(this.pendingAgentCalls.has(Pu))return Promise.reject(new A2uiRpcError(`A call with functionCallId '${Pu}' is already pending.`,RpcErrorCode.DUPLICATE,Pu));const Mu={functionCallId:Pu,call:$u,effectiveTimeoutMs:Ou,version:Iu.version};return this.dispatchAgentCall(lo,Mu)}dispose(){if(!this.isDisposed){this.isDisposed=!0;for(const[lo,$u]of this.pendingAgentCalls.entries())$u.reject(new A2uiRpcError(`RpcHandler disposed while call '${lo}' was pending.`,RpcErrorCode.CANCELLED,lo));this.pendingAgentCalls.clear()}}async emitOutboundResponse(lo){if(this.outboundListener)try{const $u=this.outboundListener(lo);$u&&typeof $u.catch=="function"&&await $u}catch{}}validateInboundMessage(lo){if(!lo)return this.createResponseError("unknown",RpcErrorCode.INVALID_FUNCTION_CALL,"Inbound message is null or undefined.","unknown");const $u=lo.version;return this.isDisposed?this.createResponseError(lo.callRendererFunction?.functionCallId??"unknown",RpcErrorCode.DISPOSED,"RpcHandler has been disposed.",$u):lo.callRendererFunction?.callFunction?null:this.createResponseError(lo.callRendererFunction?.functionCallId??"unknown",RpcErrorCode.INVALID_FUNCTION_CALL,"Malformed message: missing callRendererFunction or callFunction.",$u)}resolveFunctionImplementation(lo,$u,Ru,Iu){let Pu;if(lo){if(Pu=this.catalogs.find(Mu=>Mu.id===lo),!Pu)return{error:`Catalog not found: ${lo}`}}else Ru?.surface?.defaultCatalog&&(Pu=Ru.surface.defaultCatalog);if(!Pu)return{error:"No catalog available for function resolution."};if(Pu.protocolVersion&&Iu&&!isCatalogVersionCompatible(Pu.protocolVersion,Iu))return{error:`Catalog '${Pu.id}' specification version (${Pu.protocolVersion}) does not match message protocol version (${Iu}).`};const Ou=Pu.functions?.get($u);return Ou?{funcImpl:Ou,catalog:Pu}:{error:`Function not found: ${$u}`}}checkExecutionPermissions(lo,$u,Ru){const Iu=lo.allowedCallers??"rendererOnly";return Iu==="rendererOrAgent"||Iu==="agentOnly"?lo.requiresUserActivation&&!Ru?`Function '${$u}' requires user activation context to execute.`:null:`Function '${$u}' cannot be called by agent (allowedCallers is ${Iu}).`}parseArguments(lo,$u,Ru,Iu){try{return{args:new PayloadValidator(lo,{allowUnknownElements:!1}).validateFunction(Iu,Ru)}}catch(Pu){const Ou=this.extractErrorMessage(Pu);return{error:`Invalid function arguments for '${Iu}': ${Ou}`}}}async executeFunctionSafely(lo,$u,Ru,Iu,Pu){const Ou=Pu||"v1.0";try{const Mu=await Promise.resolve(lo.execute($u,Ru)),Du=isSignal(Mu)?getValue(Mu):Mu;return{version:Ou,rendererFunctionResponse:{functionCallId:Iu,value:Du!==void 0?Du:null}}}catch(Mu){const Du=this.extractErrorMessage(Mu);return{version:Ou,rendererFunctionResponse:{functionCallId:Iu,error:{code:RpcErrorCode.EXECUTION_ERROR,message:Du||"An error occurred during function execution."}}}}}generateFunctionCallId(){if(typeof globalThis.crypto?.randomUUID=="function")return globalThis.crypto.randomUUID();const lo=Math.random().toString(36).substring(2,15).padEnd(13,"0");return`call-${Date.now()}-${lo}`}dispatchAgentCall(lo,$u){const{functionCallId:Ru,call:Iu,effectiveTimeoutMs:Pu,version:Ou}=$u;return new Promise((Mu,Du)=>{let Lu;const Bu=()=>{Lu&&(clearTimeout(Lu),Lu=void 0),this.pendingAgentCalls.delete(Ru)};Lu=this.createTimeoutTimer(Ru,Iu.call,Pu,Bu,Du),this.pendingAgentCalls.set(Ru,{resolve:ju=>{Bu(),Mu(ju)},reject:ju=>{Bu(),Du(ju)}}),this.sendOutboundMessage(lo,Ru,Iu,Ou,Bu,Du)})}createTimeoutTimer(lo,$u,Ru,Iu,Pu){if(!(Ru<=0))return setTimeout(()=>{this.pendingAgentCalls.delete(lo)&&(Iu(),Pu(new A2uiRpcError(`Agent function call '${$u}' timed out after ${Ru}ms.`,RpcErrorCode.TIMEOUT,lo)))},Ru)}sendOutboundMessage(lo,$u,Ru,Iu,Pu,Ou){const Mu={version:Iu||"v1.0",callAgentFunction:{surfaceId:lo,functionCallId:$u,callFunction:Ru}};try{const Du=this.outboundListener(Mu);Du&&typeof Du.catch=="function"&&Du.catch(Lu=>{Pu(),Ou(Lu)})}catch(Du){Pu(),Ou(Du)}}extractErrorMessage(lo){return lo instanceof Error?lo.message:String(lo)}createResponseError(lo,$u,Ru,Iu){return{version:Iu||"v1.0",rendererFunctionResponse:{functionCallId:lo,error:{code:$u,message:Ru}}}}}class MessageProcessor{constructor(lo,$u,Ru){this.catalogs=lo,this.actionHandler=$u,this.model=new SurfaceGroupModel,this.adapterRegistry=Ru?.adapterRegistry??defaultVersionAdapterFactory,this.rpc=new RpcHandler({catalogs:this.catalogs,outboundListener:Ru?.outboundListener,defaultTimeoutMs:Ru?.defaultTimeoutMs}),Ru?.validationConfig?this.validationConfig={allowOrphanComponents:!1,allowDanglingReferences:!1,allowMissingRoot:!1,allowUnknownElements:!1,...Ru.validationConfig}:this.validationConfig=void 0,this.actionHandler&&this.model.onAction.subscribe(this.actionHandler)}callAgentFunction(lo,$u,Ru){return this.rpc.callAgentFunction(lo,$u,Ru)}dispose(){this.rpc.dispose()}getRendererCapabilities(lo){if(!lo?.versions||lo.versions.length===0)throw new A2uiValidationError("At least one protocol version must be provided in CapabilitiesOptions to generate renderer capabilities.");const $u=lo.versions,Ru={};for(const Iu of $u){const Pu={supportedCatalogIds:this.catalogs.map(Mu=>Mu.id)},Ou=lo?.includeInlineCatalogs?this.catalogs.map(Mu=>compareSemVer(Iu,"1.0")>=0?generateCatalogSchema(Mu,{componentEnvelopeRef:lo?.componentEnvelopeRef,protocolVersion:Iu}):this.generateLegacyInlineCatalog(Mu,lo?.componentEnvelopeRef??"common_types.json#/$defs/ComponentCommon")):void 0;Ou&&(Pu.inlineCatalogs=Ou),Ru[Iu]=Pu}return Ru}getClientCapabilities(lo){return this.getRendererCapabilities(lo)}generateLegacyInlineCatalog(lo,$u="common_types.json#/$defs/ComponentCommon"){const Ru=generateCatalogSchema(lo,{componentEnvelopeRef:$u}),Iu=Ru.components||{},Pu=Ru.functions,Ou=[];for(const Lu of lo.functions.values()){const Bu=Pu?.[Lu.name];Ou.push({name:Lu.name,description:Lu.description,returnType:Lu.returnType,parameters:Bu?.properties?.args??{type:"object",properties:{}}})}const Du=Ru.$defs?.theme?.properties;return{catalogId:lo.id,components:Iu,...Ou.length>0?{functions:Ou}:{},...Du?{theme:Du}:{}}}getRendererDataModel(lo){const $u=Array.from(this.model.surfacesMap.values()).filter(Ou=>Ou.sendDataModel);if($u.length===0)return;if(lo!==void 0){const Ou={};for(const Mu of $u){const Du=Mu.defaultCatalog?.protocolVersion;(!Du||isCatalogVersionCompatible(Du,lo))&&(Ou[Mu.id]=Mu.dataModel.get("/"))}return Object.keys(Ou).length===0?void 0:{version:lo,surfaces:Ou}}const Ru=new Set;for(const Ou of $u)if(Ou.defaultCatalog?.protocolVersion){const Mu=toCanonicalVersion(Ou.defaultCatalog.protocolVersion),Du=Mu?`v${Mu}`:Ou.defaultCatalog.protocolVersion;Ru.add(Du)}if(Ru.size>1)throw new A2uiValidationError(`Multiple protocol versions detected among active surfaces: ${Array.from(Ru).sort().join(", ")}. Specify a target protocol version in getRendererDataModel(version).`);const Iu=Ru.size===1?Ru.values().next().value:"v1.0",Pu={};for(const Ou of $u)Pu[Ou.id]=Ou.dataModel.get("/");return{version:Iu,surfaces:Pu}}getClientDataModel(lo){return this.getRendererDataModel(lo)}resolvePath(lo,$u){return DataModel.resolvePath(lo,$u)}getSurfaces(){return this.model.surfacesMap}getSurface(lo){return this.model.getSurface(lo)}onSurfaceCreated(lo){return this.model.onSurfaceCreated.subscribe(lo)}onSurfaceDeleted(lo){return this.model.onSurfaceDeleted.subscribe(lo)}processMessages(lo,$u){const Ru=this.prepareOperations(lo);for(const Iu of Ru)this.processOperation(Iu,$u)}async processMessagesAsync(lo,$u){const Ru=this.prepareOperations(lo),Iu=[];for(const Pu of Ru){const Ou=await this.processOperationAsync(Pu,$u);Ou&&Iu.push(Ou)}return Iu}prepareOperations(lo){return!lo||Array.isArray(lo)&&lo.length===0?[]:(this.validationConfig&&validateRecursionAndPaths(lo),this.validationConfig?.targetVersion&&this.validateTargetVersion(lo),isInternalOperation(lo)?[lo]:this.adapterRegistry.resolveFromPayload(lo).extractOperations(lo))}validateTargetVersion(lo){const $u=this.validationConfig?.targetVersion;if(!$u)return;const Ru=Iu=>{if(typeof Iu=="object"&&Iu!==null&&"version"in Iu){const Pu=Iu.version;if(Pu){const Ou=toCanonicalVersion(Pu)??Pu,Mu=toCanonicalVersion($u)??$u;if(Ou!==Mu)throw new A2uiValidationError(`Message version '${Pu}' does not match expected target version '${$u}'`)}}};if(Array.isArray(lo))for(const Iu of lo)Ru(Iu);else Ru(lo)}applyStateOperation(lo){if(this.validationConfig?.allowedMessages&&!this.validationConfig.allowedMessages.includes(lo.type))throw new A2uiValidationError(`Operation '${lo.type}' is not permitted by ValidationConfig.allowedMessages`);switch(lo.type){case"createSurface":this.processCreateSurfaceOp(lo);break;case"deleteSurface":this.processDeleteSurfaceOp(lo);break;case"updateComponents":this.processUpdateComponentsOp(lo);break;case"updateDataModel":this.processUpdateDataModelOp(lo);break;case"agentFunctionResponse":this.rpc.handleAgentFunctionResponse({version:lo.version??"v1.0",agentFunctionResponse:{functionCallId:lo.functionCallId,value:lo.value,error:lo.error}});break}}resolveRpcDataContext(lo){const $u=(lo.catalogId?this.catalogs.find(Ou=>Ou.id===lo.catalogId):void 0)??this.catalogs[0],Ru=(lo.catalogId?Array.from(this.model.surfacesMap.values()).find(Ou=>Ou.defaultCatalog?.id===lo.catalogId||Ou.availableCatalogs?.has(lo.catalogId)):void 0)??this.model.surfacesMap.values().next().value;if(Ru)return new DataContext(Ru,"/");const Iu=`_rpc_fallback_${lo.functionCallId||"default"}`,Pu=new Map;for(const Ou of this.catalogs)$u?.protocolVersion&&Ou.protocolVersion&&isCatalogVersionCompatible($u.protocolVersion,Ou.protocolVersion)&&Pu.set(Ou.id,Ou);return $u&&Pu.set($u.id,$u),new DataContext(new SurfaceModel(Iu,$u,Pu),"/")}processOperation(lo,$u){if(lo.type==="callRendererFunction"){const Ru=this.resolveRpcDataContext(lo),Iu=$u?.isUserActivated??lo.isUserActivated??!1,Pu={version:lo.version??"v1.0",callRendererFunction:{functionCallId:lo.functionCallId,callFunction:{call:lo.call,catalogId:lo.catalogId,args:lo.args}}};this.rpc.handleCallRendererFunction(Pu,Ru,Iu).catch(Ou=>{console.error(`Unhandled error in callRendererFunction (${lo.call}):`,Ou)});return}this.applyStateOperation(lo)}async processOperationAsync(lo,$u){if(lo.type==="callRendererFunction"){const Ru=this.resolveRpcDataContext(lo),Iu=$u?.isUserActivated??lo.isUserActivated??!1,Pu={version:lo.version??"v1.0",callRendererFunction:{functionCallId:lo.functionCallId,callFunction:{call:lo.call,catalogId:lo.catalogId,args:lo.args}}};return await this.rpc.handleCallRendererFunction(Pu,Ru,Iu)}return this.applyStateOperation(lo),null}processCreateSurfaceOp(lo){const{surfaceId:$u,catalogId:Ru,theme:Iu,sendDataModel:Pu,components:Ou,dataModel:Mu}=lo,Du=Ru!==void 0?this.catalogs.find(zu=>zu.id===Ru):this.catalogs[0];if(!Du)throw new A2uiStateError(`Catalog not found: ${Ru}`);const Lu=lo.version;if(Du.protocolVersion&&Lu&&!isCatalogVersionCompatible(Du.protocolVersion,Lu))throw new A2uiValidationError(`Surface '${$u}' catalog '${Ru??Du.id}' specification version (${Du.protocolVersion}) does not match message protocol version (${Lu}).`);if(this.model.getSurface($u))throw new A2uiStateError(`Surface ${$u} already exists.`);let Bu=Iu;if(Iu&&Du.themeSchema)try{Bu=new PayloadValidator(Du,this.validationConfig).validateTheme(Iu)}catch(zu){throw zu instanceof A2uiValidationError?new A2uiValidationError(zu.message.replace(/^Validation failed for theme:/,`Validation failed for theme on surface '${$u}':`),zu.details):zu}const ju=new Map(this.catalogs.filter(zu=>isCatalogVersionCompatible(zu.protocolVersion,Du.protocolVersion)).map(zu=>[zu.id,zu])),Fu=new SurfaceModel($u,Du,ju,Bu,Pu??!1,void 0,lo.rootId??"root");this.model.addSurface(Fu),Mu&&Fu.dataModel.set("/",Mu),Ou&&Ou.length>0&&this.processUpdateComponentsOp({type:"updateComponents",surfaceId:$u,components:Ou})}processDeleteSurfaceOp(lo){lo.surfaceId&&this.model.deleteSurface(lo.surfaceId)}validateComponentProperties(lo,$u){const{id:Ru,component:Iu}=lo,Pu=lo.catalogId??lo.catalogID;if(typeof Ru!="string"||!Ru)throw new A2uiValidationError(`Component '${Iu}' is missing an 'id'; entries require a valid string 'id'.`);let Ou=$u.defaultCatalog;if(typeof Pu=="string"&&Pu){const Du=$u.availableCatalogs.get(Pu);if(!Du){const Lu=this.catalogs.find(Bu=>Bu.id===Pu);throw Lu?new A2uiValidationError(`Component '${Ru}' catalog '${Pu}' specification version (${Lu.protocolVersion}) does not match surface default catalog version (${$u.defaultCatalog.protocolVersion}).`):new A2uiValidationError(`Unknown catalog ID '${Pu}' for component '${Ru}'. Available catalogs: ${this.catalogs.map(Bu=>Bu.id).join(", ")}`)}Ou=Du}const Mu=$u.componentsModel.get(Ru);new PayloadValidator(Ou,this.validationConfig).validateComponent(lo,Mu?.type)}applyComponentUpdate(lo,$u){const{id:Ru,component:Iu,...Pu}=lo;if(typeof Ru!="string")return;const Ou=lo.catalogId??lo.catalogID,Mu=$u.componentsModel.get(Ru);let Du=$u.defaultCatalog;if(typeof Ou=="string"&&Ou){const Lu=$u.availableCatalogs.get(Ou);Lu&&(Du=Lu)}if(Mu){const Lu=typeof Iu=="string"?Iu:Mu.type;if(Lu!==Mu.type||Ou&&Mu.catalog?.id!==Du.id){$u.componentsModel.removeComponent(Ru);const Bu=new ComponentModel(Ru,Lu,Pu,Du);$u.componentsModel.addComponent(Bu)}else Mu.properties=Pu}else{if(typeof Iu!="string"||!Iu)throw new A2uiValidationError(`Cannot create component ${Ru} without a type.`);const Lu=new ComponentModel(Ru,Iu,Pu,Du);$u.componentsModel.addComponent(Lu)}}processUpdateComponentsOp(lo){if(!lo.surfaceId)return;const $u=this.model.getSurface(lo.surfaceId);if(!$u)throw new A2uiStateError(`Surface not found for message: ${lo.surfaceId}`);for(const Ru of lo.components)this.validateComponentProperties(Ru,$u);this.validateCompositionConstraints($u,lo.components),this.validateCandidateTopology($u,lo.components);for(const Ru of lo.components)this.applyComponentUpdate(Ru,$u)}processUpdateDataModelOp(lo){if(!lo.surfaceId)return;const $u=this.model.getSurface(lo.surfaceId);if(!$u)throw new A2uiStateError(`Surface not found for message: ${lo.surfaceId}`);const Ru=lo.path||"/",Iu=lo.value;$u.dataModel.set(Ru,Iu)}validateParentConstraints(lo,$u,Ru,Iu){if(!Iu||Iu.length===0){if((lo==="root"||this.validationConfig&&this.validationConfig.allowOrphanComponents===!1)&&!Ru.includes("Surface"))throw new A2uiValidationError(`Component '${lo}' (${$u}) cannot be placed under parent 'Surface' (Surface). Allowed parents: ${JSON.stringify(Ru)}.`,void 0,"UNALLOWED_PARENT");return}for(const Pu of Iu)if(!Ru.includes(Pu.parentType))throw new A2uiValidationError(`Component '${lo}' (${$u}) cannot be placed under parent '${Pu.parentId}' (${Pu.parentType||"unknown"}). Allowed parents: ${JSON.stringify(Ru)}.`,void 0,"UNALLOWED_PARENT")}validateChildConstraints(lo,$u,Ru,Iu,Pu){for(const Ou of Iu){const Mu=Pu.get(Ou);if(Mu&&!Ru.includes(Mu))throw new A2uiValidationError(`Container '${lo}' (${$u}) cannot contain child '${Ou}' (${Mu}). Allowed children: ${JSON.stringify(Ru)}.`,void 0,"UNALLOWED_CHILD")}}buildCompositionTopology(lo,$u){const Ru=new Map,Iu=new Map,Pu=new Map;for(const[Mu,Du]of lo.componentsModel.entries){Ru.set(Mu,Du.type),Du.catalog&&Iu.set(Mu,Du.catalog);const Lu=lo.componentsModel.getChildIds(Mu);Lu.length>0&&Pu.set(Mu,Lu)}for(const Mu of $u){const{id:Du,component:Lu,...Bu}=Mu;if(typeof Du!="string")continue;let ju=lo.defaultCatalog;const Fu=Mu.catalogId??Mu.catalogID;if(typeof Fu=="string"&&Fu){const Gu=lo.availableCatalogs.get(Fu);Gu&&(ju=Gu,Iu.set(Du,Gu))}const zu=lo.componentsModel.get(Du),Uu=(typeof Lu=="string"?Lu:zu?.type)??"";Uu&&Ru.set(Du,Uu);const Hu={id:Du,component:Uu,...Bu},Vu=Array.from(getComponentReferences(Hu,ju)).map(([Gu])=>Gu);Vu.length>0?Pu.set(Du,Vu):Pu.delete(Du)}const Ou=new Map;for(const[Mu,Du]of Pu.entries()){const Lu=Ru.get(Mu)||"Unknown";for(const Bu of Du){const ju=Ou.get(Bu)??[];ju.push({parentId:Mu,parentType:Lu}),Ou.set(Bu,ju)}}return{typeMap:Ru,compCatalogMap:Iu,childMap:Pu,parentMap:Ou}}validateCompositionConstraints(lo,$u){const{typeMap:Ru,compCatalogMap:Iu,childMap:Pu,parentMap:Ou}=this.buildCompositionTopology(lo,$u);for(const[Mu,Du]of Ru.entries()){const Bu=(Iu.get(Mu)??lo.defaultCatalog).components.get(Du);Bu&&(Bu.allowedParents&&Bu.allowedParents.length>0&&this.validateParentConstraints(Mu,Du,Bu.allowedParents,Ou.get(Mu)),Bu.allowedChildren&&Bu.allowedChildren.length>0&&this.validateChildConstraints(Mu,Du,Bu.allowedChildren,Pu.get(Mu)||[],Ru))}}validateCandidateTopology(lo,$u){if(!this.validationConfig)return;const Ru=new SurfaceComponentsModel(lo.defaultCatalog);for(const[Iu,Pu]of lo.componentsModel.entries)Ru.addComponent(new ComponentModel(Iu,Pu.type,Pu.properties,Pu.catalog));for(const Iu of $u){const{id:Pu,component:Ou,...Mu}=Iu;if(typeof Pu!="string"||!Pu)continue;const Du=Iu.catalogId??Iu.catalogID;let Lu=lo.defaultCatalog;if(typeof Du=="string"&&Du){const Fu=lo.availableCatalogs.get(Du);Fu&&(Lu=Fu)}const Bu=Ru.get(Pu),ju=(typeof Ou=="string"?Ou:Bu?.type)||"";ju&&(Bu?ju!==Bu.type||Du&&Bu.catalog?.id!==Lu.id?(Ru.removeComponent(Pu),Ru.addComponent(new ComponentModel(Pu,ju,Mu,Lu))):Bu.properties=Mu:Ru.addComponent(new ComponentModel(Pu,ju,Mu,Lu)))}Ru.validateTopology({...this.validationConfig,rootId:this.validationConfig.rootId??lo.rootId})}}class ComponentContext{constructor(lo,$u,Ru="/",Iu,Pu){const Ou=lo.componentsModel.get($u);if(!Ou)throw new A2uiStateError(`Component not found: ${$u}`);this.componentModel=Ou,this.surfaceComponents=lo.componentsModel,this.theme=lo.theme,this.dataContext=new DataContext(lo,Ru,Pu,Iu),this._actionDispatcher=Mu=>lo.dispatchAction(Mu,this.componentModel.id)}dispatchAction(lo){return this._actionDispatcher(lo)}}function scrapeSchemaBehavior(Au){return getFieldBehavior(Au)}function unwrapZodSchema(Au){let lo=Au;for(;lo;){const $u=lo._def?.typeName;if($u==="ZodOptional"||$u==="ZodNullable"||$u==="ZodDefault"||$u==="ZodReadonly")lo=lo._def.innerType;else if($u==="ZodEffects")lo=lo._def.schema;else if($u==="ZodBranded")lo=lo._def.type;else if($u==="ZodLazy")lo=lo._def.getter();else break}return lo}function getRefDefName(Au){let lo=Au,$u="";for(;lo&&($u=lo.description??lo._def?.description??"",!$u);){const Iu=lo._def?.typeName;if(Iu==="ZodOptional"||Iu==="ZodNullable"||Iu==="ZodDefault"||Iu==="ZodReadonly")lo=lo._def.innerType;else if(Iu==="ZodEffects")lo=lo._def.schema;else if(Iu==="ZodBranded")lo=lo._def.type;else if(Iu==="ZodLazy")lo=lo._def.getter();else break}if(!$u||!$u.startsWith("REF:"))return"";const Ru=$u.slice(4);return extractRefDefName(Ru.split("|")[0])}function isCheckableField(Au){const lo=getRefDefName(Au);if(lo==="Checkable"||lo==="CheckRule")return!0;const $u=unwrapZodSchema(Au);if($u?._def?.typeName==="ZodArray"){const Ru=$u._def.type;if(getRefDefName(Ru)==="CheckRule")return!0}return!1}function isActionOption(Au){if(getRefDefName(Au)==="Action")return!0;const $u=unwrapZodSchema(Au)._def;return $u?.typeName==="ZodObject"&&!!$u.shape?.().event}function isDynamicOption(Au){const lo=getRefDefName(Au);if(lo==="DataBinding"||lo.startsWith("Dynamic"))return!0;const Ru=unwrapZodSchema(Au)._def;if(Ru?.typeName!=="ZodObject")return!1;const Iu=Ru.shape?.()||{},Pu=Object.values(Iu).some(Ou=>getRefDefName(Ou)==="ComponentId");return!!Iu.path&&!Pu}function isChildListOption(Au){if(childRefKindOf(Au)==="child-list"||getRefDefName(Au)==="ChildList")return!0;const $u=unwrapZodSchema(Au)._def;if($u?.typeName!=="ZodObject")return!1;const Ru=$u.shape?.()||{};return Object.values(Ru).some(Iu=>getRefDefName(Iu)==="ComponentId")}function isDynamicDef(Au,lo){return(Au==="DataBinding"||Au.startsWith("Dynamic"))&&lo!=="ZodObject"&&lo!=="ZodArray"}function matchUnionBehavior(Au){if(Au.some(isActionOption))return{type:"ACTION"};if(Au.some(isDynamicOption))return{type:"DYNAMIC"};if(Au.some(isChildListOption))return{type:"STRUCTURAL"}}function scrapeObjectShape(Au){const lo={};for(const[$u,Ru]of Object.entries(Au))lo[$u]=getFieldBehavior(Ru);return lo}function getFieldBehavior(Au){const lo=getRefDefName(Au);if(isCheckableField(Au))return{type:"CHECKABLE"};if(lo==="Action")return{type:"ACTION"};const $u=unwrapZodSchema(Au);if(childRefKindOf($u)==="child-list"||lo==="ChildList")return{type:"STRUCTURAL"};if(isDynamicDef(lo,$u._def?.typeName))return{type:"DYNAMIC"};if($u._def.typeName==="ZodUnion"){const Ru=matchUnionBehavior($u._def.options);if(Ru)return Ru}return $u._def.typeName==="ZodArray"?{type:"ARRAY",element:getFieldBehavior($u._def.type)}:$u._def.typeName==="ZodObject"?{type:"OBJECT",shape:scrapeObjectShape($u._def.shape())}:{type:"STATIC"}}const MAX_DYNAMIC_CHILD_LIST_SIZE=1e4;function getSafeChildList(Au){return Array.isArray(Au)?Au.length>MAX_DYNAMIC_CHILD_LIST_SIZE?Au.slice(0,MAX_DYNAMIC_CHILD_LIST_SIZE):Au:[]}class GenericBinder{constructor(lo,$u){this.dataListeners=[],this.propsListeners=[],this.currentProps={},this.isConnected=!1,this.actionClosures=new Map,this.context=lo,this.behaviorTree=scrapeSchemaBehavior($u),this.behaviorTree.type!=="OBJECT"&&(this.behaviorTree={type:"OBJECT",shape:{}}),this.resolveInitialProps()}resolveInitialProps(){const lo=this.context.componentModel.properties,$u=this.resolveAndBind(lo,this.behaviorTree,[],!0);this.currentProps={...this.currentProps,...$u||{}}}connect(){if(this.isConnected)return;this.isConnected=!0;const lo=this.context.componentModel.onUpdated.subscribe(()=>{this.rebuildAllBindings()});this.compUnsub=()=>lo.unsubscribe(),this.rebuildAllBindings()}rebuildAllBindings(){this.dataListeners.forEach(Ru=>Ru()),this.dataListeners=[];const lo=this.context.componentModel.properties,$u=this.resolveAndBind(lo,this.behaviorTree,[],!1);this.currentProps={...this.currentProps,...$u||{}},this.notify()}bindDynamicValue(lo,$u,Ru){const Iu=this.context.dataContext.subscribeDynamicValue(lo,Pu=>{this.updateDeepValue($u,Pu),this.notify()});return Ru?Iu.unsubscribe():this.dataListeners.push(()=>Iu.unsubscribe()),Iu.value}resolveDeepSync(lo,$u=0){if(typeof lo!="object"||lo===null)return lo;if($u>MAX_DYNAMIC_VALUE_DEPTH)return;if("path"in lo||"call"in lo)return this.context.dataContext.resolveDynamicValue(lo,$u);if(Array.isArray(lo))return lo.map(Iu=>this.resolveDeepSync(Iu,$u+1));const Ru={};for(const[Iu,Pu]of Object.entries(lo))Ru[Iu]=this.resolveDeepSync(Pu,$u+1);return Ru}resolveEventAction(lo){if(typeof lo!="object"||lo===null)return lo;const $u=lo;if("event"in $u&&typeof $u.event=="object"&&$u.event!==null){const Ru=$u.event,Iu={...Ru,context:Ru.context?this.resolveDeepSync(Ru.context,1):void 0};return Ru.userMessage!==void 0&&(Iu.userMessage=this.resolveDeepSync(Ru.userMessage,1)),{...$u,event:Iu}}if("name"in $u){const Ru={...$u,context:$u.context?this.resolveDeepSync($u.context,1):void 0};return $u.userMessage!==void 0&&(Ru.userMessage=this.resolveDeepSync($u.userMessage,1)),Ru}return this.resolveDeepSync(lo,0)}bindAction(lo,$u){const Ru=$u.join("/"),Iu=this.actionClosures.get(Ru);if(Iu&&jsonEquals(Iu.raw,lo))return Iu.closure;const Pu=()=>{if(lo&&typeof lo=="object"){const Ou=lo,Mu=Ou.functionCall&&typeof Ou.functionCall=="object"?Ou.functionCall:Ou;if(typeof Mu.call=="string"){this.context.dataContext.resolveDynamicValue(Mu);return}}this.context.dispatchAction(this.resolveEventAction(lo))};return this.actionClosures.set(Ru,{raw:lo,closure:Pu}),Pu}mapTemplateChildren(lo,$u,Ru){const Iu=getSafeChildList(lo),Pu=this.context.dataContext.nested(Ru);return Iu.map((Ou,Mu)=>({id:$u,basePath:Pu.nested(String(Mu)).path}))}bindStructuralTemplate(lo,$u,Ru){if(!lo||typeof lo!="object"||Array.isArray(lo))return lo;const Iu=lo,Pu=typeof Iu.path=="string"?Iu.path:void 0,Ou=typeof Iu.componentId=="string"?Iu.componentId:void 0;if(!Pu||!Ou)return lo;const Mu=this.context.dataContext.subscribeDynamicValue({path:Pu},Du=>{const Lu=this.mapTemplateChildren(Du,Ou,Pu);this.updateDeepValue($u,Lu),this.notify()});return Ru?Mu.unsubscribe():this.dataListeners.push(()=>Mu.unsubscribe()),this.mapTemplateChildren(Mu.value,Ou,Pu)}extractValidationResult(lo,$u){if(typeof lo=="object"&&lo!==null&&"valid"in lo){const Ru=lo.message;return{valid:!!lo.valid,message:Ru!=null?String(Ru):$u}}return{valid:!!lo,message:$u}}bindCheckable(lo,$u,Ru){const Iu=Array.isArray(lo)?lo:[],Pu=Iu.map(()=>({valid:!0,message:""})),Ou=$u.slice(0,-1),Mu=()=>{const Lu=Pu.filter(Bu=>!Bu.valid).map(Bu=>Bu.message);this.updateDeepValue([...Ou,"isValid"],Lu.length===0),this.updateDeepValue([...Ou,"validationErrors"],Lu),this.notify()};Iu.forEach((Lu,Bu)=>{const ju=typeof Lu=="object"&&Lu!==null?Lu:void 0,Fu=ju&&ju.condition!==void 0?ju.condition:Lu,zu=typeof ju?.message=="string"?ju.message:"Validation failed";Pu[Bu].message=zu;const Uu=this.context.dataContext.subscribeDynamicValue(Fu,Hu=>{Pu[Bu]=this.extractValidationResult(Hu,zu),Mu()});Ru?Uu.unsubscribe():this.dataListeners.push(()=>Uu.unsubscribe()),Pu[Bu]=this.extractValidationResult(Uu.value,zu)});const Du=Pu.filter(Lu=>!Lu.valid).map(Lu=>Lu.message);return this.updateDeepValue([...Ou,"isValid"],Du.length===0),this.updateDeepValue([...Ou,"validationErrors"],Du),lo}bindObject(lo,$u,Ru,Iu){const Pu={};for(const[Ou,Mu]of Object.entries(lo)){const Du=$u[Ou]||{type:"STATIC"};Pu[Ou]=this.resolveAndBind(Mu,Du,[...Ru,Ou],Iu)}for(const[Ou,Mu]of Object.entries($u))if(Mu.type==="DYNAMIC"){const Du=`set${Ou.charAt(0).toUpperCase()+Ou.slice(1)}`,Lu=lo[Ou];Pu[Du]=Bu=>{if(Lu&&typeof Lu=="object"&&"path"in Lu){const ju=Lu.path;typeof ju=="string"&&this.context.dataContext.set(ju,Bu)}}}return Pu}resolveAndBind(lo,$u,Ru,Iu){if(lo==null)return lo;switch($u.type){case"DYNAMIC":return this.bindDynamicValue(lo,Ru,Iu);case"ACTION":return this.bindAction(lo,Ru);case"STRUCTURAL":return this.bindStructuralTemplate(lo,Ru,Iu);case"CHECKABLE":return this.bindCheckable(lo,Ru,Iu);case"STATIC":return lo;case"ARRAY":return Array.isArray(lo)?lo.map((Pu,Ou)=>this.resolveAndBind(Pu,$u.element,[...Ru,Ou.toString()],Iu)):lo;case"OBJECT":return typeof lo!="object"?lo:this.bindObject(lo,$u.shape,Ru,Iu)}}updateDeepValue(lo,$u){this.currentProps=this.cloneAndUpdate(this.currentProps,lo,$u)}cloneAndUpdate(lo,$u,Ru){if($u.length===0)return Ru;const[Iu,...Pu]=$u;if(Array.isArray(lo)){const Ou=[...lo];return Ou[Number(Iu)]=this.cloneAndUpdate(Ou[Number(Iu)],Pu,Ru),Ou}else{const Ou=typeof lo=="object"&&lo!==null?lo:{};return{...Ou,[Iu]:this.cloneAndUpdate(Ou[Iu],Pu,Ru)}}}dispose(){this.isConnected&&(this.isConnected=!1,this.dataListeners.forEach(lo=>lo()),this.dataListeners=[],this.compUnsub&&(this.compUnsub(),this.compUnsub=void 0))}notify(){this.propsListeners.forEach(lo=>lo(this.currentProps))}subscribe(lo){return this.propsListeners.length===0&&this.connect(),this.propsListeners.push(lo),{unsubscribe:()=>{this.propsListeners=this.propsListeners.filter($u=>$u!==lo),this.propsListeners.length===0&&this.dispose()}}}get snapshot(){return this.currentProps}}function jsonEquals(Au,lo){if(Object.is(Au,lo))return!0;if(typeof Au!="object"||typeof lo!="object"||Au===null||lo===null)return!1;if(Array.isArray(Au)||Array.isArray(lo))return!Array.isArray(Au)||!Array.isArray(lo)||Au.length!==lo.length?!1:Au.every((Iu,Pu)=>jsonEquals(Iu,lo[Pu]));const $u=Object.keys(Au),Ru=Object.keys(lo);return $u.length!==Ru.length?!1:$u.every(Iu=>Object.prototype.hasOwnProperty.call(lo,Iu)&&jsonEquals(Au[Iu],lo[Iu]))}class ResolvedBinding{constructor(lo){this.value=lo}}class WritableBinding extends ResolvedBinding{constructor(lo,$u,Ru){super(lo),this.set=$u,this.path=Ru}}function isWritable(Au){return Au instanceof WritableBinding}function sameBinding(Au,lo){return isWritable(Au)!==isWritable(lo)||isWritable(Au)&&isWritable(lo)&&Au.path!==lo.path?!1:valueEquals(Au.value,lo.value)}function valueEquals(Au,lo){if(Object.is(Au,lo))return!0;if(Array.isArray(Au)&&Array.isArray(lo))return Au.length===lo.length&&Au.every(($u,Ru)=>valueEquals($u,lo[Ru]));if(isPlainObject$2(Au)&&isPlainObject$2(lo)){const $u=Object.keys(Au),Ru=Object.keys(lo);return $u.length===Ru.length&&$u.every(Iu=>Iu in lo&&valueEquals(Au[Iu],lo[Iu]))}return!1}function isPlainObject$2(Au){if(typeof Au!="object"||Au===null)return!1;const lo=Object.getPrototypeOf(Au);return lo===Object.prototype||lo===null}const PLACEHOLDER_TYPE="Placeholder";function isComponentNode(Au){return Au instanceof MutableComponentNode}class MutableComponentNode{constructor(lo,$u,Ru,Iu,Pu,Ou,Mu="resolved"){this._onDestroyed=new EventEmitter,this.onDestroyed=this._onDestroyed,this.cleanups=[],this._disposed=!1,this.instanceId=lo,this.componentId=$u,this.type=Ru,this.dataPath=Iu,this.props=signal(Pu),this.impl=Ou,this.state=Mu}get disposed(){return this._disposed}get isPlaceholder(){return this.state!=="resolved"}addCleanup(lo){this.cleanups.push(lo)}toJSON(){if(this.isPlaceholder)return{id:this.componentId,type:this.type,state:this.state};const lo={id:this.componentId,type:this.type},$u=peekValue(this.props);for(const[Ru,Iu]of Object.entries($u))lo[Ru]=serializeValue(Iu);return lo}setProps(lo){if(this._disposed)return;const $u=peekValue(this.props);shallowEqual($u,lo)||setValue(this.props,lo)}dispose(){if(!this._disposed){this._disposed=!0;for(const lo of this.cleanups)try{lo()}catch($u){console.error(`ComponentNode cleanup error (${this.instanceId}):`,$u)}this.cleanups=[],this._onDestroyed.emit(),this._onDestroyed.dispose()}}}function serializeValue(Au){if(isComponentNode(Au))return Au.toJSON();if(Au instanceof ResolvedBinding)return serializeValue(Au.value);if(typeof Au=="function")return"<Action>";if(Array.isArray(Au))return Au.map(serializeValue);if(Au&&typeof Au=="object"){const lo={};for(const[$u,Ru]of Object.entries(Au))lo[$u]=serializeValue(Ru);return lo}return Au}function shallowEqual(Au,lo){if(Object.is(Au,lo))return!0;const $u=Object.keys(Au),Ru=Object.keys(lo);if($u.length!==Ru.length)return!1;for(const Iu of $u)if(!Object.is(Au[Iu],lo[Iu]))return!1;return!0}const COMPONENT_ID_REF="REF:common_types.json#/$defs/ComponentId",CHILD_LIST_REF="REF:common_types.json#/$defs/ChildList",EMPTY_REF_FIELDS$1=new Map,refFieldsCache=new WeakMap;function extractRefFields(Au){const lo=refFieldsCache.get(Au);if(lo)return lo;const $u=unwrap(Au);if($u.schema._def.typeName!=="ZodObject")return refFieldsCache.set(Au,EMPTY_REF_FIELDS$1),EMPTY_REF_FIELDS$1;const Ru=new Map,Iu=$u.schema.shape;for(const[Ou,Mu]of Object.entries(Iu)){const Du=unwrap(Mu);if(marksChildList(Du)||isChildListUnion(Du.schema)){Ru.set(Ou,{kind:"list"});continue}if(marksComponentId(Du)){Ru.set(Ou,{kind:"single"});continue}if(Du.schema._def.typeName==="ZodArray"){const Lu=unwrap(Du.schema._def.type);if(marksComponentId(Lu)){Ru.set(Ou,{kind:"list"});continue}if(Lu.schema._def.typeName==="ZodObject"){const Bu=new Set,ju=Lu.schema.shape;for(const[Fu,zu]of Object.entries(ju))marksComponentId(unwrap(zu))&&Bu.add(Fu);Bu.size>0&&Ru.set(Ou,{kind:"nested",keys:Bu})}}}const Pu=Ru;return refFieldsCache.set(Au,Pu),Pu}function unwrap(Au){const lo=[],$u=new Set;let Ru=Au;for(;;){Ru.description&&lo.push(Ru.description);const Iu=childRefKindOf(Ru);Iu&&$u.add(Iu);const Pu=Ru._def.typeName;if(Pu==="ZodOptional"||Pu==="ZodNullable"||Pu==="ZodDefault")Ru=Ru._def.innerType;else if(Pu==="ZodEffects")Ru=Ru._def.schema;else return{schema:Ru,descriptions:lo,refs:$u}}}function marksComponentId(Au){return Au.refs.has("component-id")||hasPointer(Au.descriptions,COMPONENT_ID_REF)}function marksChildList(Au){return Au.refs.has("child-list")||hasPointer(Au.descriptions,CHILD_LIST_REF)}function hasPointer(Au,lo){return Au.some($u=>$u.startsWith(lo))}function isChildListUnion(Au){return Au._def.typeName!=="ZodUnion"?!1:Au._def.options.some($u=>{if($u._def.typeName!=="ZodObject")return!1;const Ru=$u.shape;return Ru.componentId&&Ru.path})}const ROOT_COMPONENT_ID="root",ROOT_DATA_PATH="/",EMPTY_REF_FIELDS=new Map;class NodeResolver{constructor(lo,$u){if(this.records=new Map,this.nodesByEdge=new Map,this.nodesByComponentId=new Map,this.pendingParents=new Map,this.dispatchedErrors=new Map,this.modelSubs=[],this._disposed=!1,$u!==lo.defaultCatalog)throw new A2uiStateError("NodeResolver requires the same catalog instance its surface was constructed with.");this.surface=lo,this.catalog=$u,this.rootId=lo.rootId??ROOT_COMPONENT_ID,this.rootNode=signal(void 0),this.modelSubs.push(lo.componentsModel.onCreated.subscribe(Ru=>this.onComponentCreated(Ru))),this.modelSubs.push(lo.componentsModel.onDeleted.subscribe(Ru=>this.onComponentDeleted(Ru))),lo.componentsModel.get(this.rootId)&&this.buildRoot()}dispatchOnce(lo,$u,Ru,Iu){let Pu=this.dispatchedErrors.get($u);Pu||(Pu=new Map,this.dispatchedErrors.set($u,Pu));let Ou=Pu.get(Ru);Ou||(Ou=new Set,Pu.set(Ru,Ou)),!Ou.has(lo)&&(Ou.add(lo),this.surface.dispatchError({code:lo,message:Iu}))}clearDispatched(lo,$u){const Ru=this.dispatchedErrors.get(lo);Ru?.delete($u)&&Ru.size===0&&this.dispatchedErrors.delete(lo)}get activeNodeCount(){return this.records.size}get disposed(){return this._disposed}dispose(){if(!this._disposed){this._disposed=!0;for(const lo of this.modelSubs)lo.unsubscribe();this.modelSubs.length=0;for(const lo of[...this.records.keys()])this.disposeNode(lo);this.pendingParents.clear(),this.dispatchedErrors.clear(),this.rootRecord=void 0,setValue(this.rootNode,void 0)}}buildRoot(){if(this.rootRecord)return;const lo=`>${escapeIdPart(this.rootId)}>${escapeIdPart(this.rootId)}@/`,$u=this.createNode(this.rootId,ROOT_DATA_PATH,lo,void 0);this.rootRecord=this.records.get($u),setValue(this.rootNode,$u)}onComponentCreated(lo){if(this._disposed)return;if(lo.id===this.rootId){const Ru=this.surface.componentsModel.get(this.rootId);this.rootRecord&&this.rootRecord.componentModel!==Ru&&(this.disposeNode(this.rootRecord.node),this.rootRecord=void 0,Ru||setValue(this.rootNode,void 0)),Ru&&this.buildRoot()}const $u=this.pendingParents.get(lo.id);if($u){this.pendingParents.delete(lo.id);for(const Ru of $u){const Iu=this.records.get(Ru);Iu&&!Ru.disposed&&this.materialize(Iu)}}}onComponentDeleted(lo){if(this._disposed)return;this.dispatchedErrors.delete(lo);const $u=this.surface.componentsModel.get(lo),Ru=this.nodesByComponentId.get(lo);if(!Ru)return;const Iu=new Set;let Pu=!1;for(const Ou of[...Ru]){const Mu=this.records.get(Ou);Mu&&(Mu.parent?Iu.add(Mu.parent):Pu=!0)}Pu&&this.rootRecord&&($u?this.rootRecord.componentModel!==$u&&(this.disposeNode(this.rootRecord.node),this.rootRecord=void 0,this.buildRoot()):(this.disposeNode(this.rootRecord.node),this.rootRecord=void 0,setValue(this.rootNode,void 0)));for(const Ou of Iu){const Mu=this.records.get(Ou);Mu&&!Ou.disposed&&this.materialize(Mu)}}createNode(lo,$u,Ru,Iu,Pu=1){const Ou=this.surface.componentsModel.get(lo);if(!Ou){const zu=this.registerNode(new MutableComponentNode(instanceIdFor(lo,$u,Pu),lo,PLACEHOLDER_TYPE,$u,{},void 0,"pending"),{edgeKey:Ru,parent:Iu,occurrence:Pu,refFields:EMPTY_REF_FIELDS});return Iu&&this.registerPendingParent(lo,Iu),zu.node}const Mu=(Ou.catalog?.components.size?Ou.catalog:void 0)??this.catalog,Du=Mu.components.get(Ou.type);if(!Du)return this.dispatchOnce("UNKNOWN_COMPONENT_TYPE",lo,$u,`Component '${lo}' has type '${Ou.type}', which is not in catalog '${Mu.id}'.`),this.registerNode(new MutableComponentNode(instanceIdFor(lo,$u,Pu),lo,Ou.type,$u,{},void 0,"unknown-type"),{edgeKey:Ru,parent:Iu,occurrence:Pu,refFields:EMPTY_REF_FIELDS,componentModel:Ou}).node;this.clearDispatched(lo,$u);const Lu=Iu?this.records.get(Iu)?.context?.dataContext:void 0,Bu=new ComponentContext(this.surface,lo,$u,Lu),ju=new GenericBinder(Bu,Du.schema),Fu=this.registerNode(new MutableComponentNode(instanceIdFor(lo,$u,Pu),lo,Ou.type,$u,{},Du),{edgeKey:Ru,parent:Iu,occurrence:Pu,refFields:extractRefFields(Du.schema),behavior:scrapeSchemaBehavior(Du.schema),context:Bu,componentModel:Ou,binder:ju});return Fu.binderSub=ju.subscribe(zu=>{Fu.lastBinderProps=zu,this.materialize(Fu)}),Fu.lastBinderProps=ju.snapshot,this.materialize(Fu),Fu.node}registerNode(lo,$u){const Ru={node:lo,edgeKey:$u.edgeKey,parent:$u.parent,occurrence:$u.occurrence,refFields:$u.refFields,behavior:$u.behavior,context:$u.context,componentModel:$u.componentModel,binder:$u.binder,childEdges:new Map};this.records.set(lo,Ru),this.nodesByEdge.set($u.edgeKey,lo);let Iu=this.nodesByComponentId.get(lo.componentId);return Iu||(Iu=new Set,this.nodesByComponentId.set(lo.componentId,Iu)),Iu.add(lo),Ru}childNode(lo,$u,Ru,Iu,Pu=1){const Ou=this.nodesByEdge.get(Ru);if(this.isCyclic(lo,$u,Iu))return Ou&&!Ou.disposed&&Ou.isPlaceholder&&this.records.get(Ou)?.occurrence===Pu?Ou:(Ou&&!Ou.disposed&&this.disposeNode(Ou),this.dispatchOnce("CYCLIC_REFERENCE",lo,$u,`Component '${lo}' at '${$u}' is referenced by one of its own descendants; rendering a placeholder instead.`),this.registerNode(new MutableComponentNode(instanceIdFor(lo,$u,Pu),lo,PLACEHOLDER_TYPE,$u,{},void 0,"cyclic"),{edgeKey:Ru,parent:Iu,occurrence:Pu,refFields:EMPTY_REF_FIELDS}).node);if(Ou&&!Ou.disposed){const Mu=this.surface.componentsModel.get(lo),Du=(Mu?.catalog?.components.size?Mu.catalog:void 0)??this.catalog,Lu=Mu?Du.components.get(Mu.type):void 0,Bu=this.records.get(Ou);if(Ou.componentId===lo&&Ou.dataPath===$u&&Bu?.occurrence===Pu&&(Ou.isPlaceholder?Mu===void 0&&Ou.state==="pending"||Mu!==void 0&&Lu===void 0&&Ou.state==="unknown-type"&&Bu?.componentModel===Mu:Mu!==void 0&&Ou.type===Mu.type&&Bu?.componentModel===Mu))return Ou.state==="pending"&&this.registerPendingParent(lo,Iu),Ou;this.disposeNode(Ou)}return this.createNode(lo,$u,Ru,Iu,Pu)}registerPendingParent(lo,$u){let Ru=this.pendingParents.get(lo);Ru||(Ru=new Set,this.pendingParents.set(lo,Ru)),Ru.add($u)}isCyclic(lo,$u,Ru){for(let Iu=Ru;Iu;Iu=this.records.get(Iu)?.parent)if(Iu.componentId===lo&&Iu.dataPath===$u)return!0;return!1}materialize(lo){if(lo.node.disposed)return;const Ru={...lo.lastBinderProps??lo.binder?.snapshot??{}},Iu=new Map,Pu=lo.componentModel?.properties;if(Pu)for(const Bu of lo.refFields.keys())Bu in Ru&&!(Bu in Pu)&&delete Ru[Bu];const Ou=new Map,Mu=(Bu,ju,Fu)=>{const zu=`${escapeIdPart(ju)}@${escapeIdPart(Fu)}`,Uu=(Ou.get(zu)??0)+1;Ou.set(zu,Uu);const Hu=`${lo.edgeKey}>${Bu}>${zu}`,Vu=this.childNode(ju,Fu,Hu,lo.node,Uu);return Iu.set(Hu,Vu),Vu};for(const[Bu,ju]of lo.refFields)switch(ju.kind){case"single":{const Fu=Ru[Bu];typeof Fu=="string"&&Fu&&(Ru[Bu]=Mu(escapeIdPart(Bu),Fu,lo.node.dataPath));break}case"list":{const Fu=Ru[Bu];if(!Array.isArray(Fu))break;const zu=getSafeChildList(Fu);Ru[Bu]=zu.map((Uu,Hu)=>{if(typeof Uu=="string"&&Uu)return Mu(`${escapeIdPart(Bu)}[${Hu}]`,Uu,lo.node.dataPath);if(Uu&&typeof Uu=="object"&&!Array.isArray(Uu)){const Vu=Uu;if(typeof Vu.id=="string"&&typeof Vu.basePath=="string")return Mu(`${escapeIdPart(Bu)}[${Hu}]`,Vu.id,Vu.basePath);if(typeof Vu.componentId=="string"&&Vu.componentId)return Mu(`${escapeIdPart(Bu)}[${Hu}]`,Vu.componentId,lo.node.dataPath)}return Uu});break}case"nested":{const Fu=Ru[Bu];if(!Array.isArray(Fu))break;Ru[Bu]=Fu.map((zu,Uu)=>{if(!zu||typeof zu!="object"||Array.isArray(zu))return zu;const Hu={...zu};let Vu=!1;for(const Gu of ju.keys){const Wu=Hu[Gu];typeof Wu=="string"&&Wu&&(Hu[Gu]=Mu(`${escapeIdPart(Bu)}[${Uu}].${escapeIdPart(Gu)}`,Wu,lo.node.dataPath),Vu=!0)}return Vu?Hu:zu});break}}for(const[Bu,ju]of lo.childEdges)if(!Iu.has(Bu)&&(this.disposeNode(ju),ju.isPlaceholder&&![...Iu.values()].some(zu=>zu.isPlaceholder&&zu.componentId===ju.componentId))){const zu=this.pendingParents.get(ju.componentId);zu&&(zu.delete(lo.node),zu.size===0&&this.pendingParents.delete(ju.componentId))}lo.childEdges=Iu;const Du=lo.behavior&&lo.context?wrapDynamicValues(Ru,lo.behavior,Pu??{},lo.context.dataContext):Ru,Lu=peekValue(lo.node.props);for(const Bu of Object.keys(Du))Du[Bu]=stabilize(Lu[Bu],Du[Bu]);lo.node.setProps(Du)}disposeNode(lo){if(lo.disposed)return;const $u=this.records.get(lo);if($u){for(const Iu of $u.childEdges.values())this.disposeNode(Iu);$u.childEdges.clear(),$u.binderSub?.unsubscribe(),$u.binderSub=void 0,this.nodesByEdge.get($u.edgeKey)===lo&&this.nodesByEdge.delete($u.edgeKey),this.records.delete(lo)}const Ru=this.nodesByComponentId.get(lo.componentId);Ru&&(Ru.delete(lo),Ru.size===0&&this.nodesByComponentId.delete(lo.componentId));for(const[Iu,Pu]of this.pendingParents)Pu.delete(lo),Pu.size===0&&this.pendingParents.delete(Iu);lo.state==="cyclic"&&this.clearDispatched(lo.componentId,lo.dataPath),lo.dispose()}}const ID_PART_ESCAPES={"~":"~0","#":"~1","[":"~2","]":"~3",">":"~4","@":"~5"};function escapeIdPart(Au){return Au.replace(/[~#[\]>@]/g,lo=>ID_PART_ESCAPES[lo])}function instanceIdFor(Au,lo,$u){const Ru=lo.replace(/\/+$/,"")||ROOT_DATA_PATH,Iu=lo===ROOT_DATA_PATH?escapeIdPart(Au):`${escapeIdPart(Au)}-[${escapeIdPart(Ru)}]`;return $u>1?`${Iu}#${$u}`:Iu}function wrapDynamicValues(Au,lo,$u,Ru){switch(lo.type){case"DYNAMIC":{const Iu=$u&&typeof $u=="object"&&!Array.isArray($u)&&typeof $u.path=="string"?$u.path:void 0;return Iu===void 0?new ResolvedBinding(Au):new WritableBinding(Au,Pu=>Ru.set(Iu,Pu),Iu)}case"ARRAY":{if(!Array.isArray(Au))return Au;const Iu=Array.isArray($u)?$u:[];return Au.map((Pu,Ou)=>wrapDynamicValues(Pu,lo.element,Iu[Ou],Ru))}case"OBJECT":{if(!Au||typeof Au!="object"||Array.isArray(Au))return Au;const Iu=new Set;for(const[Mu,Du]of Object.entries(lo.shape))Du.type==="DYNAMIC"&&Iu.add(`set${Mu.charAt(0).toUpperCase()}${Mu.slice(1)}`);const Pu=$u&&typeof $u=="object"&&!Array.isArray($u)?$u:{},Ou={};for(const[Mu,Du]of Object.entries(Au))Iu.has(Mu)||(Ou[Mu]=wrapDynamicValues(Du,lo.shape[Mu]??{type:"STATIC"},Pu[Mu],Ru));for(const[Mu,Du]of Object.entries(lo.shape))Du.type==="DYNAMIC"&&!(Mu in Ou)&&(Ou[Mu]=new ResolvedBinding(void 0));return Ou}default:return Au}}function stabilize(Au,lo){if(Object.is(Au,lo))return lo;if(Au instanceof ResolvedBinding&&lo instanceof ResolvedBinding)return sameBinding(Au,lo)?Au:lo;if(isComponentNode(Au)||isComponentNode(lo))return lo;if(Array.isArray(Au)&&Array.isArray(lo)&&Au.length===lo.length){let $u=!0;const Ru=lo.map((Iu,Pu)=>{const Ou=stabilize(Au[Pu],Iu);return Object.is(Ou,Au[Pu])||($u=!1),Ou});return $u?Au:Ru}if(isPlainObject$1(Au)&&isPlainObject$1(lo)){const $u=Object.keys(Au),Ru=Object.keys(lo);if($u.length===Ru.length){let Iu=!0;const Pu={};for(const Ou of Ru){const Mu=stabilize(Au[Ou],lo[Ou]);Pu[Ou]=Mu,(!(Ou in Au)||!Object.is(Mu,Au[Ou]))&&(Iu=!1)}return Iu?Au:Pu}}return lo}function isPlainObject$1(Au){if(!Au||typeof Au!="object"||Array.isArray(Au)||isComponentNode(Au))return!1;const lo=Object.getPrototypeOf(Au);return lo===Object.prototype||lo===null}const ComponentIdSchema=markChildRef(stringType().describe("REF:#/$defs/ComponentId|The unique identifier for a component, used for both definitions and references within the same surface."),"component-id"),DataBindingSchema=objectType({path:stringType().describe("A JSON Pointer path to a value in the data model.")}).strict().describe("REF:#/$defs/DataBinding"),DynamicValueSchema=unionType([stringType(),numberType(),booleanType(),arrayType(anyType()),DataBindingSchema,lazyType(()=>FunctionCallSchema)]).describe("REF:#/$defs/DynamicValue|A value that can be a literal, a path, or a function call returning any type."),FunctionCallSchema=objectType({call:stringType().describe("The name of the function to call."),args:recordType(stringType(),unionType([DynamicValueSchema,recordType(stringType(),anyType()).describe("A literal object argument (e.g. configuration).")])).describe("Arguments passed to the function.").optional(),returnType:enumType(["string","number","boolean","array","object","any","void"]).describe("The expected return type of the function call.").default("boolean")}).describe("REF:#/$defs/FunctionCall|Invokes a named function on the client."),DynamicStringSchema=unionType([stringType(),DataBindingSchema,FunctionCallSchema]).describe("REF:#/$defs/DynamicString|Represents a string"),AccessibilityAttributesSchema=objectType({label:DynamicStringSchema.optional(),description:DynamicStringSchema.optional()}).describe("REF:#/$defs/AccessibilityAttributes|Attributes to enhance accessibility when using assistive technologies like screen readers.");objectType({id:ComponentIdSchema,accessibility:AccessibilityAttributesSchema.optional()}).describe("REF:#/$defs/ComponentCommon");const ChildListSchema=markChildRef(unionType([arrayType(ComponentIdSchema).describe("A static list of child component IDs."),objectType({componentId:ComponentIdSchema,path:stringType().describe("The path to the list of component property objects in the data model.")}).strict().describe("A template for generating a dynamic list of children from a data model list. The `componentId` is the component to use as a template.")]).describe("REF:#/$defs/ChildList"),"child-list"),DynamicNumberSchema=unionType([numberType(),DataBindingSchema,FunctionCallSchema]).describe("REF:#/$defs/DynamicNumber|Represents a value that can be either a literal number, a path to a number in the data model, or a function call returning a number."),DynamicBooleanSchema=unionType([booleanType(),DataBindingSchema,FunctionCallSchema]).describe("REF:#/$defs/DynamicBoolean|A boolean value that can be a literal, a path, or a function call returning a boolean."),DynamicStringListSchema=unionType([arrayType(stringType()),DataBindingSchema,FunctionCallSchema]).describe("REF:#/$defs/DynamicStringList|Represents a value that can be either a literal array of strings, a path to a string array in the data model, or a function call returning a string array."),CheckRuleSchema=objectType({condition:DynamicBooleanSchema,message:stringType().describe("The error message to display if the check fails.")}).strict().describe("REF:#/$defs/CheckRule|A single validation rule applied to an input component.");objectType({checks:arrayType(CheckRuleSchema).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional()}).describe("REF:#/$defs/Checkable|Properties for components that support client-side checks.");const ActionSchema=unionType([objectType({event:objectType({name:stringType().describe("The name of the action to be dispatched to the server."),context:recordType(stringType(),DynamicValueSchema).describe("A JSON object containing the key-value pairs for the action context. Values can be literals or paths. Use literal values unless the value must be dynamically bound to the data model. Do NOT use paths for static IDs.").optional()}).strict().describe("The event to dispatch to the server.")}).strict().describe("Triggers a server-side event."),objectType({functionCall:FunctionCallSchema}).strict().describe("Executes a local client-side function.")]).describe("REF:#/$defs/Action|Defines an interaction handler that can either trigger a server-side event or execute a local client-side function."),TextApi={name:"Text",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),text:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The text content to display. While simple Markdown formatting is supported (i.e. without HTML, images, or links), utilizing dedicated UI components is generally preferred for a richer and more structured presentation."),variant:enumType(["h1","h2","h3","h4","h5","caption","body"]).default("body").describe("A hint for the base text style.").optional()}).strict()},ImageApi={name:"Image",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),url:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The URL of the image to display."),description:DynamicStringSchema.describe("REF:#/$defs/DynamicString|Accessibility text for the image.").optional(),fit:enumType(["contain","cover","fill","none","scaleDown"]).default("fill").describe("Specifies how the image should be resized to fit its container. This corresponds to the CSS 'object-fit' property.").optional(),variant:enumType(["icon","avatar","smallFeature","mediumFeature","largeFeature","header"]).default("mediumFeature").describe("A hint for the image size and style.").optional()}).strict()},IconApi={name:"Icon",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),name:unionType([enumType(["accountCircle","add","arrowBack","arrowForward","attachFile","calendarToday","call","camera","check","close","delete","download","edit","event","error","fastForward","favorite","favoriteOff","folder","help","home","info","locationOn","lock","lockOpen","mail","menu","moreVert","moreHoriz","notificationsOff","notifications","pause","payment","person","phone","photo","play","print","refresh","rewind","search","send","settings","share","shoppingCart","skipNext","skipPrevious","star","starHalf","starOff","stop","upload","visibility","visibilityOff","volumeDown","volumeMute","volumeOff","volumeUp","warning"]),objectType({svgPath:stringType()}),DataBindingSchema.describe("REF:#/$defs/DataBinding")]).describe("The name of the icon to display.")}).strict()},VideoApi={name:"Video",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),url:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The URL of the video to display.")}).strict()},AudioPlayerApi={name:"AudioPlayer",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),url:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The URL of the audio to be played."),description:DynamicStringSchema.describe("REF:#/$defs/DynamicString|A description of the audio, such as a title or summary.").optional()}).strict()},RowApi={name:"Row",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),children:ChildListSchema.describe("REF:#/$defs/ChildList|Defines the children. Use an array of strings for a fixed set of children, or a template object to generate children from a data list. Children cannot be defined inline, they must be referred to by ID."),justify:enumType(["center","end","spaceAround","spaceBetween","spaceEvenly","start","stretch"]).default("start").describe("Defines the arrangement of children along the main axis (horizontally). Use 'spaceBetween' to push items to the edges, or 'start'/'end'/'center' to pack them together.").optional(),align:enumType(["start","center","end","stretch"]).default("stretch").describe("Defines the alignment of children along the cross axis (vertically). This is similar to the CSS 'align-items' property, but uses camelCase values (e.g., 'start').").optional()}).strict()},ColumnApi={name:"Column",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),children:ChildListSchema.describe("REF:#/$defs/ChildList|Defines the children. Use an array of strings for a fixed set of children, or a template object to generate children from a data list. Children cannot be defined inline, they must be referred to by ID."),justify:enumType(["start","center","end","spaceBetween","spaceAround","spaceEvenly","stretch"]).default("start").describe("Defines the arrangement of children along the main axis (vertically). Use 'spaceBetween' to push items to the edges (e.g. header at top, footer at bottom), or 'start'/'end'/'center' to pack them together.").optional(),align:enumType(["center","end","start","stretch"]).default("stretch").describe("Defines the alignment of children along the cross axis (horizontally). This is similar to the CSS 'align-items' property.").optional()}).strict()},ListApi={name:"List",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),children:ChildListSchema.describe("REF:#/$defs/ChildList|Defines the children. Use an array of strings for a fixed set of children, or a template object to generate children from a data list."),direction:enumType(["vertical","horizontal"]).default("vertical").describe("The direction in which the list items are laid out.").optional(),align:enumType(["start","center","end","stretch"]).default("stretch").describe("Defines the alignment of children along the cross axis.").optional()}).strict()},CardApi={name:"Card",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),child:ComponentIdSchema.describe("REF:#/$defs/ComponentId|The ID of the single child component to be rendered inside the card. To display multiple elements, you MUST wrap them in a layout component (like Column or Row) and pass that container's ID here. Do NOT pass multiple IDs or a non-existent ID.")}).strict()},TabsApi={name:"Tabs",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),tabs:arrayType(objectType({title:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The tab title."),child:ComponentIdSchema.describe("REF:#/$defs/ComponentId|The ID of the child component.")})).min(1).describe("An array of objects, where each object defines a tab with a title and a child component.")}).strict()},ModalApi={name:"Modal",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),trigger:ComponentIdSchema.describe("REF:#/$defs/ComponentId|The ID of the component that opens the modal when interacted with (e.g., a button)."),content:ComponentIdSchema.describe("REF:#/$defs/ComponentId|The ID of the component to be displayed inside the modal.")}).strict()},DividerApi={name:"Divider",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),axis:enumType(["horizontal","vertical"]).default("horizontal").describe("The orientation of the divider.").optional()}).strict()},ButtonApi={name:"Button",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),checks:arrayType(CheckRuleSchema).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional(),child:ComponentIdSchema.describe("REF:#/$defs/ComponentId|The ID of the child component. Use a 'Text' component for a labeled button. Only use an 'Icon' if the requirements explicitly ask for an icon-only button."),variant:enumType(["default","primary","borderless"]).default("default").describe("A hint for the button style. If omitted, a default button style is used. 'primary' indicates this is the main call-to-action button. 'borderless' means the button has no visual border or background, making its child content appear like a clickable link.").optional(),action:ActionSchema.describe("REF:#/$defs/Action")}).strict()},TextFieldApi={name:"TextField",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),checks:arrayType(CheckRuleSchema).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional(),label:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The text label for the input field."),value:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The value of the text field.").optional(),variant:enumType(["longText","number","shortText","obscured"]).default("shortText").describe("The type of input field to display.").optional(),validationRegexp:stringType().describe("A regular expression used for client-side validation of the input.").optional()}).strict()},CheckBoxApi={name:"CheckBox",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),checks:arrayType(CheckRuleSchema).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional(),label:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The text to display next to the checkbox."),value:DynamicBooleanSchema.describe("REF:#/$defs/DynamicBoolean|The current state of the checkbox (true for checked, false for unchecked).")}).strict()},ChoicePickerApi={name:"ChoicePicker",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),checks:arrayType(CheckRuleSchema).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional(),label:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The label for the group of options.").optional(),variant:enumType(["multipleSelection","mutuallyExclusive"]).default("mutuallyExclusive").describe("A hint for how the choice picker should be displayed and behave.").optional(),options:arrayType(objectType({label:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The text to display for this option."),value:stringType().describe("The stable value associated with this option.")})).describe("The list of available options to choose from."),value:DynamicStringListSchema.describe("REF:#/$defs/DynamicStringList|The list of currently selected values. This should be bound to a string array in the data model."),displayStyle:enumType(["checkbox","chips"]).default("checkbox").describe("The display style of the component.").optional(),filterable:booleanType().default(!1).describe("If true, displays a search input to filter the options.").optional()}).strict()},SliderApi={name:"Slider",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),checks:arrayType(CheckRuleSchema).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional(),label:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The label for the slider.").optional(),min:numberType().default(0).describe("The minimum value of the slider.").optional(),max:numberType().describe("The maximum value of the slider."),value:DynamicNumberSchema.describe("REF:#/$defs/DynamicNumber|The current value of the slider.")}).strict()},DateTimeInputApi={name:"DateTimeInput",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),checks:arrayType(CheckRuleSchema).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional(),value:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The selected date and/or time value in ISO 8601 format. If not yet set, initialize with an empty string."),enableDate:booleanType().default(!1).describe("If true, allows the user to select a date.").optional(),enableTime:booleanType().default(!1).describe("If true, allows the user to select a time.").optional(),min:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The minimum allowed date/time in ISO 8601 format.").optional(),max:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The maximum allowed date/time in ISO 8601 format.").optional(),label:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The text label for the input field.").optional()}).strict()},DEFAULT_CSS=`
3679
+ `):""}function latestSaying(Au){for(let lo=Au.length-1;lo>=0;lo-=1){const $u=Au[lo];if($u.role!=="assistant"||typeof $u.toolName=="string")continue;const Ru=plainWordsOf($u.content);if(!Ru)continue;const Iu=markdownOf($u.content);if(Ru.length<=SAYING_LIMIT)return{id:String($u.id??lo),text:Ru,more:!1,markdown:Iu};const Pu=Ru.slice(0,SAYING_LIMIT),Ou=Pu.slice(0,Math.max(Pu.lastIndexOf(" "),SAYING_LIMIT*.6));return{id:String($u.id??lo),text:`${Ou.trimEnd()}…`,more:!0,markdown:Iu}}}function mouthOpening(Au){return Au<.08?0:Au<.3?1:Au<.6?2:3}const ASSISTANT_AWAY_KEY="datalayer-assistant-away";function keptAway(){try{if(window.localStorage.getItem(ASSISTANT_AWAY_KEY)==="always")return"always";if(window.sessionStorage.getItem(ASSISTANT_AWAY_KEY)==="session")return"session"}catch{}return"none"}function keepAway(Au){try{window.localStorage.removeItem(ASSISTANT_AWAY_KEY),window.sessionStorage.removeItem(ASSISTANT_AWAY_KEY),Au==="always"?window.localStorage.setItem(ASSISTANT_AWAY_KEY,"always"):Au==="session"&&window.sessionStorage.setItem(ASSISTANT_AWAY_KEY,"session")}catch{}}const ASSISTANT_OBSTACLES=['[role="dialog"]','[role="alertdialog"]',"dialog[open]",'[class*="prc-Overlay-Overlay"]',"[data-chat-composer]"].join(", "),POINTER_ROOM=24,POINTER_CALM_MS=1500;function boxesMeet(Au,lo,$u=0){return Au.left-$u<lo.right&&lo.left<Au.right+$u&&Au.top-$u<lo.bottom&&lo.top<Au.bottom+$u}function pointerNear(Au,lo,$u=POINTER_ROOM){return boxesMeet(Au,{left:lo.x,top:lo.y,right:lo.x,bottom:lo.y},$u)}const MOUTH_STEP_MS=110,WIDE=["wide1","wide2","wide3","wide4"],BY_OPENING={0:["closed","narrow"],1:["narrow","medium","closed"],2:["medium","narrow",...WIDE],3:[...WIDE,"medium"]};function mouthFor(Au,lo,$u=Math.random()){const Ru=Object.keys(Au?.mouths??{});if(Ru.length===0)return;if(lo===void 0)return Ru[Math.min(Ru.length-1,Math.floor($u*Ru.length))];const Iu=BY_OPENING[mouthOpening(lo)],Pu=WIDE.filter(Ou=>Ru.includes(Ou));return mouthOpening(lo)===3&&Pu.length>0?Pu[Math.min(Pu.length-1,Math.floor($u*Pu.length))]:Iu.find(Ou=>Ru.includes(Ou))??Ru[0]}function playCharacterSound(Au){const lo=new Audio(Au);Promise.resolve(lo.play()).catch($u=>{console.warn(`A sound of the character was not played: ${String($u)}`)})}function nextFrameIndex(Au,lo,$u=Math.random()){const Ru=Au.frames[lo];let Iu=$u*100;for(const Pu of Ru?.branching??[]){if(Iu<Pu.weight)return Pu.frameIndex;Iu-=Pu.weight}return lo+1<Au.frames.length?lo+1:void 0}function animationFor(Au,lo,$u=Math.random()){const Ru=stateAnimations(Au)[lo];return Ru[Math.min(Ru.length-1,Math.floor($u*Ru.length))]}const reducedMotion=()=>typeof window<"u"&&!!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;function SpriteCharacter({character:Au,state:lo,size:$u,sounds:Ru=!1,mouthLevel:Iu,playSound:Pu=playCharacterSound}){const[Ou,Mu]=reactExports.useState(()=>({name:animationFor(Au,lo),index:0}));reactExports.useEffect(()=>{Mu({name:animationFor(Au,lo),index:0})},[Au,lo]);const Du=Au.animations[Ou.name],Lu=Du?.frames[Ou.index],Bu=reactExports.useMemo(reducedMotion,[]);reactExports.useEffect(()=>{if(!Du||!Lu||Bu)return;const Ju=setTimeout(()=>{const Yu=nextFrameIndex(Du,Ou.index);Mu(Yu===void 0?{name:animationFor(Au,lo),index:0}:{name:Ou.name,index:Yu})},Math.max(Lu.duration,16));return()=>clearTimeout(Ju)},[Du,Lu,Ou,Au,lo,Bu]);const ju=Ru&&Lu?.sound!==void 0?Au.sounds?.[Lu.sound]:void 0;reactExports.useEffect(()=>{ju&&Pu(ju)},[ju,Ou,Pu]);const Fu=lo==="speaking"&&!Bu&&!!Lu?.mouths,[zu,Uu]=reactExports.useState();reactExports.useEffect(()=>{if(!Fu){Uu(void 0);return}const Ju=()=>Uu(mouthFor(Lu,Iu?.()));Ju();const Yu=setInterval(Ju,MOUTH_STEP_MS);return()=>clearInterval(Yu)},[Fu,Lu,Iu]);const Hu=Fu&&zu?Lu?.mouths?.[zu]:void 0,Vu=Hu?[Hu]:Lu?.images??[],{width:Gu,height:Wu}=Au.frameSize,Ku=$u/Math.max(Gu,Wu);return jsxRuntimeExports.jsx("span",{className:"assistant-sprite",role:"img","aria-label":Au.name,"data-sprite-animation":Ou.name,...Hu?{"data-sprite-mouth":zu}:{},style:{position:"relative",display:"block",width:$u,height:$u},children:Vu.map((Ju,Yu)=>jsxRuntimeExports.jsx("span",{"aria-hidden":!0,style:{position:"absolute",left:($u-Gu*Ku)/2,top:($u-Wu*Ku)/2,width:Gu,height:Wu,transform:`scale(${Ku})`,transformOrigin:"top left",backgroundImage:`url(${Au.sprite})`,backgroundPosition:`-${Ju.x}px -${Ju.y}px`,backgroundRepeat:"no-repeat",imageRendering:"pixelated"}},Yu))})}const MOTIONS={"@keyframes assistantFloat":{"0%, 100%":{transform:"translateY(0)"},"50%":{transform:"translateY(-3px)"}},"@keyframes assistantBlink":{"0%, 94%, 100%":{transform:"scaleY(0)"},"97%":{transform:"scaleY(1)"}},"@keyframes assistantTilt":{"0%, 100%":{transform:"rotate(-5deg)"},"50%":{transform:"rotate(-8deg) translateY(-2px)"}},"@keyframes assistantWork":{"0%, 100%":{transform:"rotate(-3deg) translateY(0)"},"50%":{transform:"rotate(3deg) translateY(-4px)"}},"@keyframes assistantAttention":{"0%, 100%":{transform:"scale(1) rotate(0)"},"20%":{transform:"scale(1.08) rotate(-6deg)"},"40%":{transform:"scale(1.08) rotate(6deg)"},"60%":{transform:"scale(1)"}},"@keyframes assistantHop":{"0%, 100%":{transform:"translateY(0)"},"30%":{transform:"translateY(-14px)"},"55%":{transform:"translateY(0)"},"75%":{transform:"translateY(-6px)"}},"@keyframes assistantTalk":{"0%, 100%":{transform:"scaleY(1)"},"50%":{transform:"scaleY(2.2)"}},"@keyframes assistantDoze":{"0%, 100%":{transform:"translateY(2px) scale(1, 0.97)"},"50%":{transform:"translateY(3px) scale(1.02, 0.95)"}},"@keyframes assistantLeave":{from:{transform:"scale(1)",opacity:1},to:{transform:"scale(0.2) translateY(20px)",opacity:0}}},BODY="& .assistant-body",AWAY_CHOICES=[{away:"page",label:"Hide for now"},{away:"session",label:"Hide for this session"},{away:"always",label:"Don’t show again"}],AgentInspectorDialog=reactExports.lazy(()=>__vitePreload(()=>import("./chunks/AgentInspectorDialog-3fbLXnLP.js"),[],import.meta.url)),AgentDetailsDialog=reactExports.lazy(()=>__vitePreload(()=>import("./chunks/AgentDetailsDialog-DmtKB_5z.js"),[],import.meta.url)),SandboxDetailsDialog=reactExports.lazy(()=>__vitePreload(()=>import("./chunks/SandboxDetailsDialog-BAv6RMed.js"),[],import.meta.url));function assistantMenuItems(Au){const lo=[];if(Au.inspect&&lo.push({id:"inspect",label:"Inspect the agent…",icon:PulseIcon,onSelect:Au.inspect}),Au.agentDetails&&lo.push({id:"agent-details",label:"Agent Details…",icon:DependabotIcon,onSelect:Au.agentDetails}),Au.sandboxDetails&&lo.push({id:"sandbox-details",label:"Code Sandbox Details…",icon:CodeIcon,onSelect:Au.sandboxDetails}),Au.conversationLabel!==!1&&lo.push({id:"conversation",label:Au.conversationLabel??(Au.open?"Close the conversation":"Open the conversation"),icon:CommentDiscussionIcon,onSelect:Au.onToggle}),Au.busy&&Au.onStop&&lo.push({id:"stop",label:"Stop the turn",icon:SquareFillIcon,onSelect:Au.onStop}),Au.onNewChat&&lo.push({id:"new-chat",label:"New conversation",icon:PlusIcon,onSelect:Au.onNewChat}),Au.onClear&&lo.push({id:"clear",label:"Clear the conversation",icon:TrashIcon,onSelect:Au.onClear}),Au.suggestions?.length&&Au.onSuggestion){const $u=Au.onSuggestion;for(const Ru of Au.suggestions)lo.push({id:`suggestion:${Ru.label}`,label:Ru.label,description:Ru.prompt,group:"Suggestions",disabled:Au.busy,onSelect:()=>$u(Ru)})}if(Au.onBalloonDisplayChange){const $u=Au.onBalloonDisplayChange;lo.push({id:"balloon-history",label:"History",group:"Balloon",checked:Au.balloonDisplay!=="current",onSelect:()=>$u("history")},{id:"balloon-current",label:"Current",group:"Balloon",checked:Au.balloonDisplay==="current",onSelect:()=>$u("current")})}Au.onChangeCharacter&&lo.push({id:"character",label:"Change character…",icon:PencilIcon,onSelect:Au.onChangeCharacter}),Au.speech&&lo.push({id:"speech",label:Au.speech.muted?"Unmute speech":"Mute speech",icon:Au.speech.muted?UnmuteIcon:MuteIcon,onSelect:Au.speech.onToggle}),Au.characterSounds&&lo.push({id:"character-sounds",label:Au.characterSounds.on?"Mute its sounds":"Play its sounds",icon:Au.characterSounds.on?MuteIcon:UnmuteIcon,onSelect:Au.characterSounds.onToggle}),Au.onResetPosition&&lo.push({id:"reset-position",label:"Reset position",icon:ScreenNormalIcon,onSelect:Au.onResetPosition}),Au.about&&lo.push({id:"about",label:`About ${Au.name}`,icon:InfoIcon,onSelect:Au.about}),lo.push(...Au.extra??[]);for(const $u of AWAY_CHOICES)lo.push({id:`away:${$u.away}`,label:$u.label,group:"Send away",icon:XIcon,onSelect:()=>Au.onDismiss($u.away)});return lo}const BALLOON_ROOM=200;function pixels(Au){if(typeof Au=="number")return Au;const lo=typeof Au=="string"?/^(-?\d+(?:\.\d+)?)px$/.exec(Au):null;return lo?Number(lo[1]):void 0}function balloonSide(Au,lo={width:typeof window>"u"?1280:window.innerWidth,height:typeof window>"u"?800:window.innerHeight}){const $u=pixels(Au.left),Ru=pixels(Au.top),Iu=$u!==void 0?$u<lo.width/2?"left":"right":Au.left!==void 0&&Au.right===void 0?"left":"right";return{side:Ru!==void 0?Ru<BALLOON_ROOM?"below":"above":Au.top!==void 0&&Au.bottom===void 0?"below":"above",align:Iu}}const CLEAR_CHECK_MS=400;function useKeepClear(Au,lo,$u){const[Ru,Iu]=reactExports.useState(!1),[Pu,Ou]=reactExports.useState(!1);return reactExports.useEffect(()=>{if($u){Iu(!1);return}const Mu=()=>{const Lu=Au.current;if(!Lu)return;const Bu=Lu.getBoundingClientRect(),ju=lo?.current,Fu=Array.from(document.querySelectorAll(ASSISTANT_OBSTACLES)).some(zu=>{if(Lu.contains(zu)||zu.contains(Lu)||ju?.contains(zu))return!1;const Uu=zu.getBoundingClientRect();return Uu.width>0&&Uu.height>0&&boxesMeet(Bu,Uu)});Iu(Fu)};Mu();const Du=window.setInterval(Mu,CLEAR_CHECK_MS);return()=>window.clearInterval(Du)},[Au,lo,$u]),reactExports.useEffect(()=>{if($u){Ou(!1);return}let Mu,Du=!1;const Lu=Bu=>{const ju=Au.current,Fu=Bu.target;!ju||Fu&&(ju.contains(Fu)||lo?.current?.contains(Fu))||Bu.type==="pointermove"&&Bu.buttons===0&&!Du||pointerNear(ju.getBoundingClientRect(),{x:Bu.clientX,y:Bu.clientY})&&(Du=!0,Ou(!0),clearTimeout(Mu),Mu=setTimeout(()=>{Du=!1,Ou(!1)},POINTER_CALM_MS))};return document.addEventListener("pointerdown",Lu,!0),document.addEventListener("pointermove",Lu,!0),()=>{clearTimeout(Mu),document.removeEventListener("pointerdown",Lu,!0),document.removeEventListener("pointermove",Lu,!0)}},[Au,lo,$u]),Ru?"obstacle":Pu?"pointer":void 0}function useMouth(Au,lo,$u){reactExports.useEffect(()=>{const Ru=Au.current,Iu=typeof window<"u"&&!!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;if(!Ru||!lo||!$u||Iu){Ru?.removeAttribute("data-assistant-mouth");return}let Pu=0;const Ou=()=>{Ru.setAttribute("data-assistant-mouth",String(mouthOpening(lo()))),Pu=requestAnimationFrame(Ou)};return Pu=requestAnimationFrame(Ou),()=>{cancelAnimationFrame(Pu),Ru.removeAttribute("data-assistant-mouth")}},[Au,lo,$u])}function AssistantStage({character:Au,state:lo,size:$u=88,place:Ru,stageRef:Iu,onDragStart:Pu,open:Ou,onToggle:Mu,onCharacterClick:Du,onCharacterKeyDown:Lu,balloon:Bu,insist:ju=!1,onDismiss:Fu,ownRef:zu,decide:Uu,mouthLevel:Hu,stayPut:Vu=!1,balloonDisplay:Gu="history",expandTarget:Wu,expandOnArrival:Ku=!1,suggestions:Ju,onSuggestion:Yu,inspector:Xu,inspectAgent:ed,conversationLabel:td,onBalloonDisplayChange:nd,onStop:od,onNewChat:sd,onClear:ad,onChangeCharacter:pd,speech:gd,onResetPosition:xd,about:yd,sandbox:vd,contextMenu:wd,agentName:Td,label:cd}){const dd=useChatWords(),md=typeof Au=="string"?assistantCharacter(Au):"Drawing"in Au?Au:void 0,ld=md?md.name:Au.name,hd=Td??ld,bd=reactExports.useId(),Sd=!!(Td||cd),{colorScheme:kd}=useTheme(),Rd=kd?.startsWith("dark")?"dark":"light",[Od,Bd]=reactExports.useState(!1),[Ed,Ad]=reactExports.useState(!1),[$d,qd]=reactExports.useState(null),[Dd,Hd]=reactExports.useState(!1),[nh,Xd]=reactExports.useState(!1),[vh,ih]=reactExports.useState(null),xh=reactExports.useRef(null),bh=reactExports.useRef(void 0),eh=reactExports.useCallback(()=>qd(null),[]),[rh,ah]=reactExports.useState(!1),Dh=!md&&Object.keys(Au.sounds??{}).length>0;reactExports.useEffect(()=>()=>clearTimeout(bh.current),[]);const Gd=reactExports.useRef(null),zd=useKeepClear(Iu,zu,Ed||$d!==null||Dd||nh||vh!==null||Vu);useMouth(Iu,Hu,lo==="speaking");const[Id,Pd]=reactExports.useState(!1),Wd=!zd&&!Ou&&!!Bu&&(Od||ju||Id),Nd=(lo==="idle"||lo==="greeting")&&!Bu?.tool&&!Bu?.approval&&!Bu?.busy,Qd=assistantMenuItems({name:hd,open:Ou,onToggle:Mu,onDismiss:Fu,conversationLabel:td,inspect:Xu?()=>Hd(!0):void 0,agentDetails:yd?()=>ih("agent"):void 0,sandboxDetails:vd?()=>ih("sandbox"):void 0,balloonDisplay:Gu,onBalloonDisplayChange:nd,suggestions:Ju,onSuggestion:Yu,busy:lo==="thinking"||lo==="working"||lo==="speaking",onStop:od,onNewChat:sd,onClear:ad,onChangeCharacter:pd,speech:gd,characterSounds:Dh?{on:rh,onToggle:()=>ah(Fd=>!Fd)}:void 0,onResetPosition:xd,about:yd?()=>Xd(!0):void 0,extra:wd}),fh=Bu?.visual,[_h,Sh]=reactExports.useState(null),Wh=fh?()=>{Sh(fh),Wu&&requestAnimationFrame(()=>focusExpanded(Wu))}:null,Md=Bu?.history,_d=Gu!=="current"&&Md&&Md.length>0?{id:"balloon-history",title:conversationHeaderText(conversationCount(Md),dd),shrink:!0,render:()=>jsxRuntimeExports.jsx(BalloonHistoryLarge,{history:Md,tool:Bu?.tool,attachment:Bu?.attachment})}:null,Vd=_h?.id==="balloon-history"?_d:_h;return reactExports.useEffect(()=>{fh&&Ku&&Wu&&Sh(fh)},[fh?.id,Ku,!!Wu]),jsxRuntimeExports.jsxs(Box,{ref:Iu,"data-assistant-state":lo,"data-assistant-aside":zd,"data-assistant-balloon":Gu,sx:{position:"fixed",zIndex:1002,...Ru,width:$u,height:$u,opacity:zd?0:1,visibility:zd?"hidden":"visible",pointerEvents:zd?"none":void 0,transition:zd?"opacity 150ms ease, visibility 0s linear 150ms":"opacity 150ms ease",...MOTIONS,"& .assistant-lids ellipse":{transformBox:"fill-box",transformOrigin:"top",transform:"scaleY(0)",animation:"assistantBlink 5.2s ease-in-out infinite"},[BODY]:{transformBox:"fill-box",transformOrigin:"50% 100%"},"& .assistant-pupils":{transition:"transform var(--theme-motion-status, 120ms) var(--theme-motion-easing, ease)"},"& .assistant-mouth":{transformBox:"fill-box",transformOrigin:"center"},'&[data-assistant-state="idle"] .assistant-body':{animation:"assistantFloat 3.2s ease-in-out infinite"},'&[data-assistant-state="thinking"] .assistant-body':{animation:"assistantTilt 2.4s ease-in-out infinite"},'&[data-assistant-state="thinking"] .assistant-pupils':{transform:"translate(-1px, -3px)"},'&[data-assistant-state="working"] .assistant-body':{animation:"assistantWork 0.7s ease-in-out infinite"},'&[data-assistant-state="working"] .assistant-pupils':{transform:"translate(2px, 2px)"},'&[data-assistant-state="waiting"] .assistant-body':{animation:"assistantAttention 1.4s ease-in-out infinite"},'&[data-assistant-state="greeting"] .assistant-body':{animation:"assistantHop 0.9s ease-out 2"},'&[data-assistant-state="speaking"] .assistant-mouth':{animation:"assistantTalk 0.24s ease-in-out infinite"},'&[data-assistant-state="speaking"] .assistant-body':{animation:"assistantFloat 1.6s ease-in-out infinite"},"&[data-assistant-mouth] .assistant-mouth":{animation:"none",transition:"transform 60ms linear"},'&[data-assistant-mouth="0"] .assistant-mouth':{transform:"scaleY(1)"},'&[data-assistant-mouth="1"] .assistant-mouth':{transform:"scaleY(1.5)"},'&[data-assistant-mouth="2"] .assistant-mouth':{transform:"scaleY(2.1)"},'&[data-assistant-mouth="3"] .assistant-mouth':{transform:"scaleY(2.8)"},'&[data-assistant-state="paused"] .assistant-body':{animation:"assistantDoze 4.8s ease-in-out infinite",filter:"grayscale(0.5)",opacity:.8},'&[data-assistant-state="paused"] .assistant-lids ellipse':{animation:"none",transform:"scaleY(1)"},'&[data-assistant-state="goodbye"] .assistant-body':{animation:"assistantLeave 0.6s ease-in forwards"},'&[data-assistant-state="goodbye"] .assistant-sprite':{animation:"assistantLeave 0.6s ease-in forwards"},"@media (prefers-reduced-motion: reduce)":{"& *":{animation:"none !important"}}},onMouseEnter:()=>Bd(!0),onMouseLeave:()=>Bd(!1),children:[Vd&&jsxRuntimeExports.jsx(ExpandedVisual,{visual:Vd,target:Wu,onClose:()=>Sh(null)}),Wd&&Bu&&jsxRuntimeExports.jsx(BalloonExpandContext.Provider,{value:Wh,children:jsxRuntimeExports.jsx(SpeechBalloon,{text:Bu.text,more:Bu.more,approval:Bu.approval,onDismissPeek:Bu.onDismiss,display:Gu,tool:Bu.tool,speaking:Bu.speaking,busy:Bu.busy,attachment:Bu.attachment,history:Bu.history,onExpand:Wh??void 0,expandTitle:fh?.title,onExpandHistory:_d?()=>{Sh(_d),Wu&&requestAnimationFrame(()=>focusExpanded(Wu))}:void 0,suggestions:Nd?Ju:void 0,fullText:Bu.fullText,waiting:(lo==="thinking"||lo==="working"||lo==="waiting")&&!Bu.speaking,onSuggestion:Yu,decide:Uu,onDecisionActive:Pd,wide:Id,onOpen:Mu,above:$u+8,side:balloonSide(Ru).side,align:balloonSide(Ru).align,tailAt:$u/2})}),jsxRuntimeExports.jsxs(Box,{as:"button",type:"button","aria-label":cd??(Ou?`Close the conversation with ${hd}`:`Talk to ${hd}`),"aria-describedby":Sd?bd:void 0,"aria-expanded":Ou,"aria-haspopup":"menu",ref:xh,"data-assistant-figure":"",onContextMenu:Fd=>{Fd.preventDefault(),clearTimeout(bh.current),qd({x:Fd.clientX,y:Fd.clientY})},onKeyDown:Fd=>{if(opensContextMenu(Fd)){Fd.preventDefault();const uh=Fd.currentTarget.getBoundingClientRect();qd({x:uh.left+uh.width/2,y:uh.bottom});return}Lu?.(Fd)},onPointerUp:()=>clearTimeout(bh.current),onPointerCancel:()=>clearTimeout(bh.current),onPointerMove:Fd=>{const uh=Gd.current;uh&&Math.hypot(Fd.clientX-uh.x,Fd.clientY-uh.y)>8&&clearTimeout(bh.current)},onPointerDown:Fd=>{if(Gd.current={x:Fd.clientX,y:Fd.clientY},Fd.pointerType==="touch"){const uh={x:Fd.clientX,y:Fd.clientY};clearTimeout(bh.current),bh.current=setTimeout(()=>{Gd.current={x:-1e6,y:-1e6},qd(uh)},LONG_PRESS_MS)}Pu(Fd)},onClick:Fd=>{const uh=Gd.current;Gd.current=null,!(uh&&Math.hypot(Fd.clientX-uh.x,Fd.clientY-uh.y)>4)&&(Du??Mu)()},display:"block",width:$u,height:$u,p:0,border:0,bg:"transparent",cursor:"grab",filter:"drop-shadow(0 6px 10px rgba(0, 0, 0, 0.18))",active:{cursor:"grabbing"},focusVisible:{outline:"2px solid",outlineColor:"var(--focus-outlineColor, var(--fgColor-accent))",outlineOffset:2,borderRadius:"50%"},touchAction:"none",children:[Sd&&jsxRuntimeExports.jsx(Box,{as:"span",id:bd,position:"absolute",width:1,height:1,overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap",children:`Its character: ${ld}`}),md?jsxRuntimeExports.jsx(md.Drawing,{size:$u,mode:Rd}):jsxRuntimeExports.jsx(SpriteCharacter,{character:Au,state:lo,size:$u,sounds:rh,mouthLevel:Hu})]}),(Od||Ed)&&!zd&&lo!=="goodbye"&&jsxRuntimeExports.jsx(Box,{position:"absolute",top:"-6px",right:"-6px",children:jsxRuntimeExports.jsxs(ActionMenu,{open:Ed,onOpenChange:Ad,children:[jsxRuntimeExports.jsx(ActionMenu.Anchor,{children:jsxRuntimeExports.jsx(IconButton,{icon:XIcon,"aria-label":`Send ${hd} away`,size:"small",variant:"invisible","data-assistant-dismiss":"",sx:{bg:"canvas.default",borderRadius:"50%",boxShadow:"shadow.small"}})}),jsxRuntimeExports.jsx(ActionMenu.Overlay,{width:"auto",children:jsxRuntimeExports.jsx(ActionList,{children:AWAY_CHOICES.map(Fd=>jsxRuntimeExports.jsx(ActionList.Item,{"data-assistant-away":Fd.away,onSelect:()=>Fu(Fd.away),children:Fd.label},Fd.away))})})]})}),jsxRuntimeExports.jsx(AssistantContextMenu,{at:$d,items:Qd,onClose:eh,returnFocusRef:xh,label:`${hd}’s menu`}),Dd&&jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(AgentInspectorDialog,{tracer:Xu??null,agent:ed,title:`${yd?.name??hd} · Agent Inspector`,onClose:()=>{Hd(!1),xh.current?.focus()}})}),vh==="agent"&&yd&&jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(AgentDetailsDialog,{about:yd,name:hd,onClose:()=>{ih(null),xh.current?.focus()}})}),vh==="sandbox"&&vd&&jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(SandboxDetailsDialog,{sandbox:vd,name:yd?.name??hd,onClose:()=>{ih(null),xh.current?.focus()}})}),nh&&yd&&jsxRuntimeExports.jsx(Dialog$1,{title:`About ${yd.name??hd}`,onClose:()=>{Xd(!1),xh.current?.focus()},"data-assistant-about":"",children:[["Agent",yd.name],["Spec",yd.spec],["Model",yd.model],["Runs",yd.where],["Character",ld]].filter(([,Fd])=>Fd).map(([Fd,uh])=>jsxRuntimeExports.jsxs(Text$3,{as:"p",sx:{m:0,mb:1},children:[jsxRuntimeExports.jsxs(Text$3,{sx:{color:"fg.muted"},children:[Fd,": "]}),uh]},Fd))})]})}const CONVERSATION_BALLOON_WIDTH=380,CONVERSATION_BALLOON_MAX_HEIGHT=560,CONVERSATION_BALLOON_VIEWPORT_SHARE=.6,CURRENT_BALLOON_HEIGHT=230;function conversationBalloonHeight(Au){return Math.max(240,Math.min(CONVERSATION_BALLOON_MAX_HEIGHT,Math.round(Au*CONVERSATION_BALLOON_VIEWPORT_SHARE)))}const TAIL=7;function balloonTailAt(Au,lo,$u=CONVERSATION_BALLOON_WIDTH){return Math.min($u-24-TAIL,Math.max(24,Au-lo-TAIL))}function conversationBalloonSx(Au,lo="canvas.default"){return{borderRadius:"var(--theme-radius-bubble, 16px)",overflow:"visible",...Au.edge==="none"?{}:{"&::after":{content:'""',position:"absolute",...Au.edge==="bottom"?{bottom:`-${TAIL}px`}:{top:`-${TAIL}px`},left:`${Au.at}px`,width:`${TAIL*2}px`,height:`${TAIL*2}px`,bg:lo,borderRight:"1px solid",borderBottom:"1px solid",borderColor:"border.default",transform:Au.edge==="bottom"?"rotate(45deg)":"rotate(225deg)",pointerEvents:"none"}}}}function ConversationBalloonClose({name:Au,onClose:lo}){return jsxRuntimeExports.jsx(Box,{"data-conversation-balloon-close":"",position:"absolute",top:"6px",right:"6px",zIndex:30,children:jsxRuntimeExports.jsx(IconButton,{icon:XIcon,size:"small",variant:"invisible","aria-label":Au?`Close the conversation with ${Au}`:"Close the conversation",onClick:lo,sx:{bg:"canvas.default",borderRadius:"50%"}})})}function BalloonApprovalMessage({approval:Au}){const lo=useChatWords(),$u=reactExports.useRef(null);return reactExports.useEffect(()=>{$u.current?.scrollIntoView?.({block:"nearest"})},[Au.id]),jsxRuntimeExports.jsx(Box,{ref:$u,"data-balloon-approval":Au.id,px:3,py:2,display:"flex",children:jsxRuntimeExports.jsxs(Box,{maxWidth:"90%",px:3,py:2,bg:"attention.subtle",border:"1px solid",borderColor:"attention.muted",borderRadius:"var(--theme-radius-bubble, 16px)",fontSize:1,children:[jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,color:"fg.muted",fontSize:0},children:lo.waitingForYou}),jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,fontWeight:"semibold"},children:Au.asks}),Au.why?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,color:"fg.muted",fontSize:0},children:Au.why}):null,jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,mt:2,alignItems:"center",children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"primary",disabled:Au.deciding,onClick:Au.onApprove,children:lo.approve}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:Au.deciding,onClick:Au.onDeny,children:lo.deny}),Au.others>0?jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontSize:0},children:lo.moreWaiting(Au.others)}):null]})]})})}const PEEK_LIMIT=60;function peekLine(Au,lo=PEEK_LIMIT){const $u=Au.replace(/\s+/g," ").trim();if($u.length<=lo)return{text:$u,more:!1};const Ru=$u.slice(0,lo);return{text:`${Ru.slice(0,Math.max(Ru.lastIndexOf(" "),lo*.6)).trimEnd()}…`,more:!0}}const PRESENCE_LINES={idle:"Ready",thinking:"Thinking…",working:"Working…",waiting:"Waiting for you",paused:"Paused"};function presenceState(Au,lo,$u=!1){return $u?"paused":lo?.open&&lo.pendingApproval?"waiting":Au?lo?.open?"working":"thinking":"idle"}function presenceToolOf(Au){for(let lo=Au.length-1;lo>=0;lo-=1){const $u=Au[lo];if(typeof $u.toolName=="string"&&$u.toolCallId){const Ru=$u.status!=="complete"&&$u.status!=="error",Iu=Ru&&$u.result?.pending_approval===!0;return{open:Ru,pendingApproval:Iu}}}return{open:!1,pendingApproval:!1}}const LIVE=new Set(["running","idle","busy","starting"]);function sandboxIsLive(Au){return Au.status===void 0||LIVE.has(Au.status)}const NO_SANDBOX_YET="No sandbox is running yet: run a cell or ask the agent to execute code.",SANDBOX_KIND_LABELS={browser:"Python in your browser (Pyodide)",local:"Local Jupyter server",jupyter:"Jupyter server",cloud:"Datalayer cloud runtime",runtime:"In the agent runtime"};function isLocalUrl(Au){if(!Au)return!1;try{const lo=new URL(Au).hostname;return lo==="localhost"||lo==="127.0.0.1"||lo==="::1"||lo==="[::1]"||lo.endsWith(".localhost")}catch{return!1}}const SECRET_PARAMS=/^(token|access_token|api_key|apikey|key|auth|password|secret|signature|sig|jwt)$/i;function displayUrl(Au){if(Au)try{const lo=new URL(Au);lo.username="",lo.password="";for(const $u of[...lo.searchParams.keys()])SECRET_PARAMS.test($u)&&lo.searchParams.delete($u);return lo.toString()}catch{return Au.split("?")[0]}}const text$3=Au=>typeof Au=="string"&&Au?Au:void 0;function assistantSandboxOf(Au,lo={}){if(!Au)return;const $u=text$3(Au.variant),Ru=text$3(Au.jupyter_url)??text$3(Au.agent_base_url),Iu=Au.sandbox_running===!0||Au.jupyter_connected===!0;return!$u&&!Iu?void 0:{kind:$u==="datalayer"?"cloud":$u==="jupyter-server"||$u==="jupyter"?isLocalUrl(text$3(Au.jupyter_url))?"local":"jupyter":"runtime",status:lo.state??(Iu?"running":"stopped"),variant:$u,url:Ru,token:text$3(Au.jupyter_token),kernelId:text$3(Au.kernel_id),agentId:lo.agentId,environment:text$3(Au.environment_name),serverUrl:lo.serverUrl}}function sandboxExecuteOverHttp(Au,lo){const $u=Au.replace(/\/+$/,"").replace(/\/api\/v1$/,"");return async Ru=>{const Iu=await fetch(`${$u}/api/v1/sandbox/execute`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:Ru,agent_id:lo})});if(!Iu.ok)return{stdout:"",error:`The sandbox did not run the code (HTTP ${Iu.status}).`};const Pu=await Iu.json();return{stdout:Pu.stdout??"",error:Pu.error??void 0}}}function timeLeft(Au,lo=Date.now()){if(Au===null)return"never";if(Au===void 0||Au==="")return;const $u=typeof Au=="number"?Au<1e12?Au*1e3:Au:Date.parse(Au);if(!Number.isFinite($u))return;const Ru=Math.round(($u-lo)/6e4);if(Ru<=0)return"ended";const Iu=Math.floor(Ru/60);return Iu?`${Iu} h ${Ru%60} min`:`${Ru} min`}function useIsMobile(Au=640){const[lo,$u]=reactExports.useState(!1);return reactExports.useEffect(()=>{const Ru=()=>{$u(window.innerWidth<Au)};return Ru(),window.addEventListener("resize",Ru),()=>window.removeEventListener("resize",Ru)},[Au]),lo}const px=Au=>`${Math.round(Au)}px`,clamp=(Au,lo)=>Math.max(8,Math.min(Au,Math.max(8,lo)));function ChatFloating({endpoint:Au,protocol:lo,useStore:$u=!0,title:Ru="Chat",description:Iu="Start a conversation with the AI agent.",position:Pu="bottom-right",defaultOpen:Ou=!1,width:Mu=400,height:Du=550,showHeader:Lu=!0,showButton:Bu=!0,showNewChatButton:ju=!0,showClearButton:Fu=!0,showSettingsButton:zu=!1,enableKeyboardShortcuts:Uu=!0,toggleShortcut:Hu="/",showPoweredBy:Vu=!0,promptVariant:Gu,mentionableAgents:Wu,poweredByProps:Ku,clickOutsideToClose:Ju=!1,escapeToClose:Yu=!0,className:Xu,onSettingsClick:ed,onNewChat:td,onOpen:nd,onClose:od,onStateUpdate:sd,children:ad,brandIcon:pd,buttonIcon:gd,buttonTooltip:xd="Chat with AI",brandColor:yd,buttonGlow:vd=!0,offset:wd=20,animationDuration:Td=200,frontendTools:cd,initialState:dd,suggestions:md,submitOnSuggestionClick:ld=!0,hideMessagesAfterToolUI:hd=!1,defaultViewMode:bd="floating",onViewModeChange:Sd,sidebarMountPoint:kd=null,showPanelBackdrop:Rd=!1,availableModels:Od,showModelSelector:Bd=!1,showToolsMenu:Ed=!1,showSkillsMenu:Ad=!1,showTokenUsage:$d=!0,showContextRing:qd=!1,themeVariant:Dd,themeOverrides:Hd,colorMode:nh,runtimeId:Xd,historyEndpoint:vh,authToken:ih,historyAuthToken:xh,pendingPrompt:bh,showInformation:eh=!1,onInformationClick:rh,onToolCallStart:ah,onToolCallComplete:Dh,showToolApprovalBanner:Gd,pendingApprovals:zd,onApproveApproval:Id,onRejectApproval:Pd,panelProps:Wd,launching:Nd=!1,launchingMessage:Kd,assistantCharacter:Qd=DEFAULT_ASSISTANT_CHARACTER,balloonDisplay:fh=DEFAULT_BALLOON_DISPLAY,expandTarget:_h,conversation:Sh,decisions:Wh,voice:Md,inspector:_d,onBalloonDisplayChange:Vd,onChangeCharacter:Fd,about:uh,sandbox:wh,contextMenu:Eh}){const kh=useChatWords(),Ph=reactExports.useRef(null),[Fh,Uh]=reactExports.useState(),[Jh,Oh]=reactExports.useState(!1),[np,ap]=reactExports.useState();reactExports.useEffect(()=>ap(void 0),[fh]);const hp=np??fh,bp=reactExports.useCallback(Bh=>{ap(Bh),Vd?.(Bh)},[Vd]),Qh=useChatOpen(),_p=useChatMessages(),lp=useChatStore(Bh=>Bh.setOpen),up=useChatStore(Bh=>Bh.clearMessages),[Hh,zh]=reactExports.useState(Ou),Xh=$u?Qh:Hh,Uf=$u?lp:zh,$p=_p,Rh=reactExports.useRef(null),jh=useIsMobile(),[af,qp]=reactExports.useState(!1),[lf,Xp]=reactExports.useState(!1),[tp,Vp]=reactExports.useState(bd),[$f,cm]=reactExports.useState(0),[Hf,qf]=reactExports.useState(!1),[Qp,fp]=reactExports.useState(null),jp=tp==="panel"?"sidebar":tp,[Sp,Bp]=reactExports.useState(null);reactExports.useLayoutEffect(()=>{Bp(resolveMountPoint(kd))},[kd,Xh,tp]);const Of=disabledChatViewModes({sidebarMountPoint:Sp,viewMode:jp}),ef=Of.includes("sidebar"),cf=tp==="panel"&&!jh&&!!Sp,yp=useViewportDrag(Rh),Jf=yp.reset;reactExports.useEffect(()=>{tp!=="floating-draggable"&&Jf()},[tp,Jf]);const vf=88,vm=tp==="assistant"&&!jh,[Mf,Fm]=reactExports.useState(!1),[uf,Am]=reactExports.useState({open:!1,pendingApproval:!1}),[Cm,Vf]=reactExports.useState(!1),[Lh,Ud]=reactExports.useState(),[lh,Mh]=reactExports.useState(0),[Nh,mp]=reactExports.useState([]),[$h,ep]=reactExports.useState([]),[Fp]=useVoiceSettings(),Sf=reactExports.useMemo(()=>Md?settledVoice(Md,Fp):void 0,[Md,Fp]),{speaker:Ip,state:zp,stop:Yp,read:um,level:nm}=useVoiceSpeaker(Sf);useSpokenAnswers($h,Mf,!!Ip&&Sf?.output==="always"&&!Jh,Ip);const[bf,$m]=reactExports.useState(!1),[Rm,r0]=reactExports.useState(!1),[bm,Cf]=reactExports.useState(keptAway),dm=vm&&bm==="none",Df=reactExports.useCallback(()=>{keepAway("none"),Cf("none")},[]),[Kp,Rf]=reactExports.useState(),xp=Sh?Sh.saying:Kp,If=Sh?Sh.answering:Cm,Nf=Sh?Sh.tool:Lh,Vh=hp==="current",[Up,tf]=reactExports.useState(),[Tf,Lf]=reactExports.useState(!1);reactExports.useEffect(()=>{if(!xp||Xh)return;Lf(!0);const Bh=setTimeout(()=>Lf(!1),12e3);return()=>clearTimeout(Bh)},[xp?.id,xp?.text,Xh]),reactExports.useEffect(()=>{Xh&&xp&&tf(xp.id)},[Xh,xp?.id]);const hm=reactExports.useRef(null),Xf=useViewportDrag(hm,{whole:!0});reactExports.useEffect(()=>{if(!dm)return;$m(!0);const Bh=setTimeout(()=>$m(!1),1800);return()=>clearTimeout(Bh)},[dm]);const kp=assistantStateOf(Sh?Sh.presence:presenceState(Mf,uf),{arriving:bf,leaving:Rm,speaking:If,voicing:zp.speaking}),Gf=!!xp&&xp.id!==Up,[Tm,df]=reactExports.useState(!1),Zh=zd?.[0],Hp=Zh&&Id&&Pd?{id:Zh.id,asks:Zh.toolDescription||Zh.toolName,others:(zd?.length??1)-1,deciding:Tm,onApprove:()=>{df(!0),Promise.resolve(Id(Zh.id)).finally(()=>df(!1))},onDeny:()=>{df(!0),Promise.resolve(Pd(Zh.id)).finally(()=>df(!1))}}:void 0,Pf=reactExports.useMemo(()=>Wh?.serverUrl?decisionsAskerAt(Wh.serverUrl,Wh.token):void 0,[Wh?.serverUrl,Wh?.token]),rf=kp==="thinking"||kp==="working"||kp==="speaking",hf=Nf&&(Nf.phase==="running"||rf)?Nf:void 0,x0=rf&&!If?kh.thinking:(xp?.more?xp.text:xp?.markdown)||void 0,zm=rf&&!If?void 0:xp?.more?xp.markdown:void 0,Um=!Vh&&!Sh&&Nh.length>0?Nh:void 0,pm=Bh=>Um?{...Bh,history:Um}:Bh,kg=kp==="paused"?{text:kh.paused}:zp.sentence?{text:zp.sentence}:zp.refused?{text:zp.refused}:Hp?pm({text:kh.waitingForYou,approval:Hp}):kp==="waiting"?{text:kh.waitingOpen}:hf?pm({text:toolLineText(hf,kh),tool:hf,busy:rf}):Vh&&(Gf||rf)?{text:x0??Iu,fullText:zm,more:xp?.more,speaking:If&&rf,busy:rf,onDismiss:xp?()=>{tf(xp.id),Lf(!1)}:void 0}:pm(Gf&&xp?{...peekLine(xp.text),onDismiss:()=>{tf(xp.id),Lf(!1)}}:{text:Iu}),Q0=!!zp.sentence||kp==="greeting"||kp==="waiting"||!!Hp||!!hf||Vh&&rf||Gf&&(kp==="speaking"||Tf),Wv=reactExports.useMemo(()=>Sh||!md?.length?void 0:md.map(Bh=>({label:Bh.title,prompt:Bh.message})),[Sh,md]),Qg=reactExports.useCallback(Bh=>{Ph.current?Ph.current.send(Bh.prompt):Uh(Bh.prompt)},[]),e1=Wd?.onSendReady,eg=reactExports.useCallback(Bh=>{Ph.current=Bh,e1?.(Bh)},[e1]),h0=Wd?.onLoadingChange,t1=Wd?.onDisplayItemsChange,r1=reactExports.useCallback(Bh=>{Fm(Bh),h0?.(Bh)},[h0]),ip=reactExports.useCallback(Bh=>{const wp=presenceToolOf(Bh);Am(Jp=>Jp.open===wp.open&&Jp.pendingApproval===wp.pendingApproval?Jp:wp),Vf(newestIsAnswer(Bh));const pf=newestToolLine(Bh);Ud(Jp=>Jp?.id===pf?.id&&Jp?.phase===pf?.phase?Jp:pf),Mh(conversationCount(Bh)),mp(Bh),ep(Bh);const _m=latestSaying(Bh);Rf(Jp=>Jp?.id===_m?.id&&Jp?.text===_m?.text?Jp:_m),t1?.(Bh)},[t1]),C1=reactExports.useCallback(Bh=>{if(!(Bh==="sidebar"&&ef))if(Bh==="sidebar"){if(Sd){Sd(Bh);return}Vp("panel"),cm(wp=>wp+1)}else Bh==="assistant"&&Df(),Vp(Bh),cm(wp=>wp+1),Sd?.(Bh)},[Sd,ef,Df]);reactExports.useLayoutEffect(()=>{if(tp!=="panel"||jh){qf(!1);return}if(Sp){qf(!0);return}const Bh=Rh.current?.parentElement;if(!Bh){qf(!1);return}const wp=window.getComputedStyle(Bh),pf=wp.display.includes("flex")&&(wp.flexDirection==="row"||wp.flexDirection==="row-reverse"),_m=wp.display.includes("grid");qf(pf||_m)},[tp,jh,Xh,Sp]);const Ag=typeof Mu=="number"?Mu:typeof Mu=="string"&&Number.parseInt(Mu,10)||420;reactExports.useLayoutEffect(()=>{if(jh||tp!=="panel"||Hf||!Xh){fp(null);return}const Bh=Rh.current?.parentElement;if(!Bh){fp(null);return}const wp=Bh.style.paddingRight,pf=Bh.style.boxSizing,_m=window.getComputedStyle(Bh).paddingRight;Bh.style.boxSizing="border-box",Bh.style.paddingRight=`calc(${_m} + ${Ag}px)`;const Jp=()=>{const w0=Bh.getBoundingClientRect();fp(fm=>{const E0=w0.height<1?{top:0,height:window.innerHeight,right:0}:{top:w0.top,height:w0.height,right:Math.max(0,window.innerWidth-w0.right)};return fm&&Math.abs(fm.top-E0.top)<1&&Math.abs(fm.height-E0.height)<1&&Math.abs(fm.right-E0.right)<1?fm:E0})};Jp(),window.addEventListener("resize",Jp),window.addEventListener("scroll",Jp,!0);const Om=new ResizeObserver(Jp);return Om.observe(Bh),()=>{window.removeEventListener("resize",Jp),window.removeEventListener("scroll",Jp,!0),Om.disconnect(),Bh.style.paddingRight=wp,Bh.style.boxSizing=pf}},[jh,tp,Hf,Xh,Ag]);const ym=reactExports.useMemo(()=>{if(lo&&typeof lo=="object")return lo;if(!Au)return;const Bh=typeof lo=="string"?lo:void 0,wp=Au.match(/^(.*?)\/api\/v1\//)?.[1]||Au.match(/^(https?:\/\/[^/]+)/)?.[1]||"",pf=Au.match(/\/api\/v1\/(ag-ui|vercel-ai|a2a|acp)\//),_m=Bh??pf?.[1]??"vercel-ai",Jp=Au.match(/\/api\/v1\/(?:ag-ui|vercel-ai|a2a\/agents|acp\/ws)\/([^/]+)/),Om=Jp?Jp[1]:void 0;return{type:_m,endpoint:Au,agentId:Om,authToken:ih,enableConfigQuery:Bd||Ed||Ad||$d,configEndpoint:Bd||Ed||Ad||$d?`${wp}/api/v1/configure`:void 0}},[lo,Au,ih,Bd,Ed,Ad,$d]),j0=Au?.match(/^(.*?)\/api\/v1\//)?.[1],wf=reactExports.useMemo(()=>uh||ym?.agentId?{name:Ru,protocol:ym?.type,url:ym?.endpoint,agentId:ym?.agentId,apiBase:j0,...uh}:void 0,[uh,ym,Ru,j0]),Rp=useAgentRuntimeCodemodeStatus(),p0=reactExports.useMemo(()=>wh??assistantSandboxOf(Rp?.sandbox,{agentId:ym?.agentId,serverUrl:j0})??(ym?.agentId&&j0?{kind:"runtime",status:"not running",agentId:ym.agentId,serverUrl:j0}:void 0),[wh,Rp,ym?.agentId,j0]);reactExports.useEffect(()=>{up()},[Au,lo]),reactExports.useEffect(()=>{Uf(Ou)},[]);const om=reactExports.useCallback(()=>{const Bh=!Xh;qp(!0),Bh?(Uf(Bh),nd?.()):setTimeout(()=>{Uf(Bh),od?.(),qp(!1)},Td),setTimeout(()=>qp(!1),Td)},[Xh,Uf,nd,od,Td]),sv=reactExports.useCallback(Bh=>{Xh&&om(),keepAway(Bh),r0(!0),setTimeout(()=>{r0(!1),Cf(Bh)},600)},[Xh,om]),tg=typeof window>"u"?1280:window.innerWidth,im=typeof window>"u"?800:window.innerHeight,Im=conversationBalloonHeight(im),n1=Vh&&!Sh,rg=n1?CURRENT_BALLOON_HEIGHT:Im,o1=()=>{const Bh=CONVERSATION_BALLOON_WIDTH,wp=rg;if(Xf.position){const{left:fm,top:E0}=Xf.position,T1=fm+vf/2<tg/2,Vm=E0-wp-16,Wf=E0+vf+16,Cp=Vm<8&&Wf+wp>im-8,Gm=Cp?T1?fm+vf+16:fm-Bh-16:T1?fm:fm+vf-Bh,C0=Cp?E0+vf-wp:Vm>=8?Vm:Wf,F0=clamp(Gm,tg-Bh-8);return{place:{left:px(F0),top:px(clamp(C0,im-wp-8)),right:"auto",bottom:"auto"},tail:Cp?{edge:"none"}:{edge:Vm>=8?"bottom":"top",at:balloonTailAt(fm+vf/2,F0)}}}const pf=Pu.endsWith("right"),_m=pf?tg-wd-vf/2:wd+vf/2,Jp=pf?tg-wd-Bh:wd,Om={edge:Pu.startsWith("bottom")?"bottom":"top",at:balloonTailAt(_m,Jp)},w0=sm();return{place:Pu.startsWith("bottom")?{...w0,bottom:px(wd+vf+16)}:{...w0,top:px(wd+vf+16)},tail:Om}},Hm=reactExports.useCallback(()=>{$u&&up(),td?.()},[$u,up,td]),ng=reactExports.useCallback(()=>{window.confirm("Clear all messages?")&&$u&&up()},[$u,up]);useChatKeyboardShortcuts({onToggle:Uu?om:void 0,onNewChat:Uu?Hm:void 0,onClear:Uu&&$p.length>0?ng:void 0,enabled:Uu}),reactExports.useEffect(()=>{if(!Yu||!Xh)return;const Bh=wp=>{wp.key==="Escape"&&om()};return document.addEventListener("keydown",Bh),()=>document.removeEventListener("keydown",Bh)},[Yu,Xh,om]);const Pm=!!Sh;reactExports.useEffect(()=>{if(!Pm||!Xh)return;const Bh=setTimeout(()=>{Rh.current?.querySelector('[data-chat-composer] textarea, [data-chat-composer] [contenteditable="true"], textarea')?.focus()},Td);return()=>clearTimeout(Bh)},[Pm,Xh,Td,$f]),reactExports.useEffect(()=>{if(!dm||!Xh)return;const Bh=setTimeout(()=>{const wp=Rh.current?.querySelector("[data-chat-history]");wp?.scrollTo?.({top:wp.scrollHeight})},Td);return()=>clearTimeout(Bh)},[dm,Xh,Td]),reactExports.useEffect(()=>{if(!Ju||!Xh)return;const Bh=pf=>{Rh.current&&!Rh.current.contains(pf.target)&&om()},wp=setTimeout(()=>{document.addEventListener("mousedown",Bh)},100);return()=>{clearTimeout(wp),document.removeEventListener("mousedown",Bh)}},[Ju,Xh,om]),reactExports.useEffect(()=>{if(jh&&Xh)return document.body.style.overflow="hidden",document.body.style.position="fixed",document.body.style.width="100%",document.body.style.touchAction="none",()=>{document.body.style.overflow="",document.body.style.position="",document.body.style.width="",document.body.style.touchAction=""}},[jh,Xh]);const sm=()=>{const Bh={position:"fixed",zIndex:1e3};switch(Pu){case"bottom-right":Bh.bottom=wd,Bh.right=wd;break;case"bottom-left":Bh.bottom=wd,Bh.left=wd;break;case"top-right":Bh.top=wd,Bh.right=wd;break;case"top-left":Bh.top=wd,Bh.left=wd;break}return Bh},og=Bh=>{if(Bh)return"scale(1) translateY(0)";switch(Pu){case"bottom-right":case"bottom-left":return"scale(0.95) translateY(20px)";case"top-right":case"top-left":return"scale(0.95) translateY(-20px)";default:return"scale(0.95)"}},i1=Uu?getShortcutDisplay({key:Hu}):void 0,_f=dm?o1():void 0,qm=jh?"100%":_f?CONVERSATION_BALLOON_WIDTH:Mu,S0=jh?"100%":_f?rg:Du,n0=jh?{position:"fixed",top:0,left:0,right:0,bottom:0,width:"100%",height:"100%",borderRadius:0}:{},f0=jsxRuntimeExports.jsx(Tooltip,{text:`Close${Yu?" (Esc)":""}`,direction:"s",children:jsxRuntimeExports.jsx(IconButton,{icon:XIcon,"aria-label":"Close",onClick:om,variant:"invisible",size:"small"})}),s1=_f?{showHeader:!1,showPoweredBy:!1,promptVariant:"lexical",showModelSelector:!1,showToolsMenu:!1,showSkillsMenu:!1,showTokenUsage:!1,showContextRing:!1,showInformation:!1,showToolApprovalBanner:!1,showAgentsMenu:!1,showTurnFooter:!1,compact:!0,welcome:Iu,backgroundColor:"canvas.default",borderRadius:"var(--theme-radius-bubble, 16px)",trailingContent:Hp?jsxRuntimeExports.jsx(BalloonApprovalMessage,{approval:Hp}):void 0,footerContent:Pf?jsxRuntimeExports.jsx(Box,{"data-balloon-decisions":"",px:3,pb:1,display:"flex",flexDirection:"column",alignItems:"flex-end",fontSize:0,sx:{"& form":{alignSelf:"stretch"},'& [data-balloon-decision="answered"]':{alignSelf:"stretch"}},children:jsxRuntimeExports.jsx(DecisionAsk,{ask:Pf})}):void 0}:void 0,m0=jsxRuntimeExports.jsxs(Box,{ref:Rh,className:Xu,sx:{position:tp==="panel"&&!jh&&(Hf||cf)?"relative":"fixed",...tp==="floating"&&!jh?{top:0,right:0,bottom:0,left:"auto"}:{},...tp==="floating-small"&&!jh?sm():{},...tp==="floating-draggable"&&!jh?yp.position?{left:px(yp.position.left),top:px(yp.position.top),right:"auto",bottom:"auto"}:sm():{},..._f?_f.place:vm&&!jh?sm():{},...tp==="panel"&&!jh?{...Hf||cf?{top:"auto",right:"auto",bottom:"auto",left:"auto",marginLeft:"auto",alignSelf:"stretch"}:{top:Qp?`${Qp.top}px`:0,right:Qp?`${Qp.right}px`:0,bottom:Qp?"auto":0,left:"auto"}}:{},width:tp==="panel"&&!jh?Xh||af?`${Ag}px`:"0px":tp==="floating"&&!jh?typeof qm=="number"?`${qm}px`:qm:(tp==="floating-small"||tp==="floating-draggable"||tp==="assistant")&&!jh?typeof qm=="number"?`${qm}px`:qm:jh?"100%":typeof qm=="number"?`${qm}px`:qm,height:tp==="panel"&&!jh?Hf||cf?"100%":Qp?`${Qp.height}px`:"100%":tp==="floating"&&!jh?"100%":(tp==="floating-small"||tp==="floating-draggable"||tp==="assistant")&&!jh?typeof S0=="number"?`${S0}px`:S0:jh?"100%":typeof S0=="number"?`${S0}px`:S0,display:"flex",flexDirection:"column",bg:"canvas.default",border:"1px solid",borderColor:"border.default",borderRadius:tp==="panel"||jh?0:vm?"var(--theme-radius-bubble, 16px)":"12px",boxShadow:tp==="panel"?"shadow.none":"shadow.extra-large",overflow:"hidden",transform:tp==="panel"?Xh?"translateX(0)":"translateX(100%)":og(Xh),opacity:tp==="panel"||Xh?1:0,transition:`transform ${Td}ms ease, opacity ${Td}ms ease, width ${Td}ms ease`,zIndex:tp==="panel"&&!jh&&(Hf||cf)?"auto":1001,visibility:Xh||af?"visible":"hidden",pointerEvents:Xh?"auto":"none",...n0,..._f?conversationBalloonSx(_f.tail,_f.tail.edge==="bottom"?"canvas.subtle":"canvas.default"):{}},"data-conversation-balloon":_f?"":void 0,"data-balloon-display":_f?hp:void 0,children:[_f?jsxRuntimeExports.jsx(ConversationBalloonClose,{onClose:om}):null,_f&&!n1?jsxRuntimeExports.jsx(ConversationBalloonHeader,{count:lh}):null,tp==="floating-draggable"&&!jh&&jsxRuntimeExports.jsx(Box,{onPointerDown:yp.onHandlePointerDown,"aria-label":"Move the chat",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,height:18,cursor:"grab",color:"fg.subtle",bg:"canvas.subtle",borderBottom:"1px solid",borderColor:"border.muted",active:{cursor:"grabbing"},touchAction:"none",children:jsxRuntimeExports.jsx(GrabberIcon,{size:16})}),Sh?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Lu&&!_f?jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,flexShrink:0,px:3,py:2,borderBottom:"1px solid",borderColor:"border.default",children:[pd||jsxRuntimeExports.jsx(ForwardRef$2,{colored:!0,size:20}),jsxRuntimeExports.jsx(Text$3,{sx:{flex:1,minWidth:0,fontWeight:"semibold",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Ru}),f0]}):null,jsxRuntimeExports.jsx(Box,{"data-floating-conversation":!0,flex:"1 1 auto",minHeight:0,display:"flex",borderRadius:_f?"bubble":void 0,overflow:_f?"hidden":void 0,children:Sh.body})]}):jsxRuntimeExports.jsx(ChatBase,{title:Ru,showHeader:Lu,useStore:$u,protocol:ym,themeVariant:Dd,themeOverrides:Hd,colorMode:nh,autoFocus:Xh,focusTrigger:$f,launching:Nd,launchingMessage:Kd,brandIcon:pd||jsxRuntimeExports.jsx(ForwardRef$2,{colored:!0,size:20}),headerButtons:{showNewChat:ju,showClear:Fu&&$p.length>0,showSettings:zu&&!!ed,onNewChat:Hm,onClear:ng,onSettings:ed},headerActions:jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:f0}),chatViewMode:jp,onChatViewModeChange:C1,disabledViewModes:Of,showPoweredBy:Vu,promptVariant:Gu,mentionableAgents:Wu,poweredByProps:{brandName:"Datalayer",brandUrl:"https://datalayer.ai",...Ku},description:Iu,onStateUpdate:sd,onNewChat:td,suggestions:md,submitOnSuggestionClick:ld,hideMessagesAfterToolUI:hd,avatarConfig:{showAvatars:!0},placeholder:"Type a message...",backgroundColor:"canvas.subtle",frontendTools:cd,showModelSelector:Bd,availableModels:Od,showToolsMenu:Ed,showSkillsMenu:Ad,showTokenUsage:$d,showContextRing:qd,runtimeId:Xd,historyEndpoint:vh,historyAuthToken:xh,pendingPrompt:bh??Fh,inspector:_d,showInformation:eh,onInformationClick:rh,onToolCallStart:ah,onToolCallComplete:Dh,showToolApprovalBanner:Gd,pendingApprovals:zd,onApproveApproval:Id,onRejectApproval:Pd,voice:Md,voiceSpeaking:zp.speaking,onStopSpeaking:Ip?Yp:void 0,onReadAloud:Ip?um:void 0,...Wd,...s1,onLoadingChange:r1,onDisplayItemsChange:ip,onSendReady:eg,children:_f&&n1?jsxRuntimeExports.jsx(Box,{px:3,pt:3,pb:2,overflow:"hidden",children:jsxRuntimeExports.jsx(CurrentBalloonBody,{text:hf?void 0:x0??Iu,fullText:hf?void 0:zm,tool:hf,busy:rf,speaking:If&&rf,waiting:rf&&!If})}):ad})]}),a1=jsxRuntimeExports.jsx(IconButton,{icon:gd||CommentDiscussionIcon,"aria-label":xd,unsafeDisableTooltip:!!xp,onClick:vm&&bm==="page"?Df:om,size:"large",sx:{width:56,height:56,borderRadius:"50%",bg:yd||"accent.emphasis",color:"fg.onEmphasis",boxShadow:"shadow.large",transition:"transform 0.2s ease, box-shadow 0.2s ease",transform:lf?"scale(1.1)":"scale(1)",...Gf?{animation:"chatFloatingBlink 1.1s ease-in-out infinite","@keyframes chatFloatingBlink":{"0%, 100%":{filter:"brightness(1)",boxShadow:"0 0 0 0 rgba(0,0,0,0)"},"50%":{filter:"brightness(1.25)",boxShadow:"0 0 0 6px var(--bgColor-accent-muted, rgba(84,174,255,0.4))"}},"@media (prefers-reduced-motion: reduce)":{animation:"none"}}:{},"&:hover":{bg:yd||"accent.emphasis",boxShadow:"shadow.extra-large"}}});return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[dm&&jsxRuntimeExports.jsx(AssistantStage,{character:Qd,state:kp,size:vf,place:Xf.position?{left:px(Xf.position.left),top:px(Xf.position.top)}:sm(),stageRef:hm,onDragStart:Xf.onHandlePointerDown,open:Xh,onToggle:om,balloon:kg,balloonDisplay:hp,expandTarget:_h,insist:Q0,onDismiss:sv,ownRef:Rh,mouthLevel:nm,suggestions:Wv,onSuggestion:Qg,inspector:_d,onBalloonDisplayChange:bp,onStop:Mf&&Ph.current?()=>Ph.current?.stop():void 0,onNewChat:!Sh&&ju?Hm:void 0,onClear:!Sh&&$u?ng:void 0,onChangeCharacter:Fd,speech:Ip&&Sf?.output==="always"?{muted:Jh,onToggle:()=>{Jh||Ip.stop(),Oh(!Jh)}}:void 0,onResetPosition:Xf.position?Xf.reset:void 0,about:wf,sandbox:p0,contextMenu:Eh}),Bu&&!Xh&&!dm&&jsxRuntimeExports.jsx(Box,{sx:{...sm()},children:jsxRuntimeExports.jsxs(Box,{position:"relative",display:"inline-flex",isolation:"isolate",onMouseEnter:()=>Xp(!0),onMouseLeave:()=>Xp(!1),children:[vd&&jsxRuntimeExports.jsx(ButtonGlow,{color:yd}),lf&&xp?jsxRuntimeExports.jsx(SpeechBalloon,{text:xp.text,more:xp.more,onOpen:om,above:64,side:Pu.startsWith("bottom")?"above":"below",align:Pu.includes("right")?"right":"left",tailAt:28}):null,xp?a1:jsxRuntimeExports.jsx(Tooltip,{text:`${xd}${i1?` (${i1})`:""}`,direction:Pu.includes("right")?"w":"e",children:a1}),$p.length>0&&jsxRuntimeExports.jsx(Box,{position:"absolute",top:0,right:0,minWidth:18,height:18,px:1,display:"flex",alignItems:"center",justifyContent:"center",bg:"danger.emphasis",color:"fg.onEmphasis",borderRadius:"50%",fontSize:0,fontWeight:"bold",pointerEvents:"none",children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0},children:$p.length>99?"99+":$p.length})}),Gf&&jsxRuntimeExports.jsx(Box,{position:"absolute",top:0,left:0,right:0,bottom:0,borderRadius:"50%",border:"2px solid",borderColor:yd||"accent.emphasis",animation:"pulse 2s infinite",pointerEvents:"none",reducedMotion:{animation:"none",transform:"scale(1.15)",opacity:.6},sx:{"@keyframes pulse":{"0%":{transform:"scale(1)",opacity:1},"100%":{transform:"scale(1.5)",opacity:0}}}})]})}),jh&&Xh&&jsxRuntimeExports.jsx(Box,{position:"fixed",top:0,left:0,right:0,bottom:0,bg:"neutral.muted",opacity:.5,zIndex:999,onClick:om}),Rd&&tp==="panel"&&Xh&&!jh&&jsxRuntimeExports.jsx(Box,{position:"fixed",top:0,left:0,right:0,bottom:0,bg:"neutral.muted",opacity:.3,zIndex:1e3,onClick:om}),cf&&Sp?reactDomExports.createPortal(m0,Sp):m0]})}const LoopCanvasBlock=defineContributionPoint("loop.canvas.block"),LoopA2uiComponent=defineContributionPoint("loop.a2ui.component"),LoopAppFiles=defineContributionPoint("loop.app.files"),listeners$2=new Set;function requestSurface(Au){if(listeners$2.size===0)return!1;for(const lo of[...listeners$2])lo(Au);return!0}function onSurfaceRequest(Au){return listeners$2.add(Au),()=>{listeners$2.delete(Au)}}const listeners$1=new Set;function focusPrompt(){if(listeners$1.size===0)return!1;for(const Au of[...listeners$1])Au();return!0}function onPromptFocusRequest(Au){return listeners$1.add(Au),()=>{listeners$1.delete(Au)}}function agentServerOf(Au,lo){return Au.target==="datalayer"?Au.agentBaseUrl||void 0:Au.agentBaseUrl||lo}function noRuntimeSaid(Au,lo){return Au.state==="error"?lo.noRuntime(Au.errorReason??""):lo.runtimeStarting}const IDLE_SANDBOX_SNAPSHOT=Object.freeze({state:"idle"}),IDLE_SANDBOX_SNAPSHOT_SIGNAL={value:IDLE_SANDBOX_SNAPSHOT,peek:()=>IDLE_SANDBOX_SNAPSHOT},IDLE_SANDBOX_TARGET_SIGNAL={value:void 0,peek:()=>{}};function loopSurfaceId(Au){return`loop-${Au||"default"}`}function createPromptChannel(){const Au=new Set,lo=[];return{submit($u){if(Au.size===0)return lo.push($u),!0;for(const Ru of[...Au])Ru($u);return!0},subscribe($u){if(Au.add($u),lo.length>0){const Ru=lo.splice(0,lo.length);queueMicrotask(()=>{for(const Iu of Ru)$u(Iu)})}return()=>{Au.delete($u)}}}}const LoopViewType=defineContributionPoint("loop.viewType"),LoopEditorView=defineContributionPoint("loop.chat.surface"),LoopChatSurface=LoopEditorView,LoopFrontendTool=defineContributionPoint("loop.frontendTool"),LoopChatComposer=defineContributionPoint("loop.chat.composer"),LoopChatHeader=defineContributionPoint("loop.chat.header"),LoopAgentBlueprint=defineContributionPoint("loop.agent.blueprint"),LoopChatSuggestion=defineContributionPoint("loop.chat.suggestion"),LoopAssistantCharacter=defineContributionPoint("loop.assistant.character");defineContributionPoint("loop.assistant.menu");async function sendInstead(Au,lo){if(!Au.sendInstead)return null;try{return await Au.sendInstead.send(lo),{sent:!0}}catch($u){return{sent:!1,refused:$u instanceof Error?$u.message:String($u)}}}const LoopChatExtras=defineContributionPoint("loop.chat.extras"),LoopOpeningNotebook=defineContributionPoint("loop.notebook.opening"),LoopOpeningDocument=defineContributionPoint("loop.document.opening"),LoopAgentGate=defineGate("loop.agent.available"),LoopNotebookToolbar=defineContributionPoint("loop.notebook.toolbar"),LoopNotebookToolbarItem=defineContributionPoint("loop.notebook.toolbar.item"),LoopDocumentToolbar=defineContributionPoint("loop.document.toolbar"),LoopDocumentToolbarItem=defineContributionPoint("loop.document.toolbar.item"),LoopCommand=defineContributionPoint("loop.command"),LoopRunProps=defineContributionPoint("loop.runProps");function runForwardedProps(Au,lo){let $u;for(const Ru of[...Au.map(Iu=>Iu.props()),lo]){if(!Ru)continue;const Iu={...$u?.loop??{},...Ru.loop??{}};$u={...$u,...Ru},Object.keys(Iu).length>0&&($u.loop=Iu)}return $u}defineContributionPoint("loop.mention");const LoopSlots={header:"loop.header",chatHeader:"loop.chatHeader",promptAction:"loop.promptAction",inpromptMenu:"loop.inpromptMenu",footer:"loop.footer",status:"loop.status",root:"root",sidebar:"loop.sidebar"};function sandboxIndicatorState(Au,lo,$u){return Au==="error"?"connected-dead":Au==="starting"?"connected-starting":Au==="stopping"?"disconnecting":Au!=="running"?"disconnected":lo==="busy"||$u?"connected-busy":"connected-idle"}function canOpenView(Au,lo){return Au.canOpen?Au.canOpen(lo):!0}function parseCommand(Au){const lo=Au.trimStart();if(!lo.startsWith("/"))return;const[$u,...Ru]=lo.slice(1).split(/\s+/);if($u)return{name:$u.toLowerCase(),argv:Ru.join(" ").trim()}}const LoopChatLayout=defineContributionPoint("loop.chat.layout"),LoopPromptPanel=defineContributionPoint("loop.prompt.panel"),LoopChatTurn=defineContributionPoint("loop.chat.turn");function defineAgentCapacityPlugin(Au){const{key:lo,displayName:$u,description:Ru,specId:Iu,octicon:Pu,emoji:Ou,codemode:Mu,createPayload:Du,suggestions:Lu,instructions:Bu,model:ju,modeEffect:Fu,name:zu,requiredBackendPlugins:Uu}=Au;return{name:zu??`@datalayer/loop-plugin-agent-${lo}`,...Uu?{requiredBackendPlugins:Uu}:{},displayName:$u,description:Ru,octicon:Pu??"dependabot",emoji:Ou,contributes:[contribution(LoopAgentBlueprint,{id:lo,specId:Iu,createPayload:{description:Ru,agent_library:"pydantic-ai",enable_codemode:Mu??!1,...Du},...Bu?{instructions:Bu}:{},...ju?{model:ju}:{},...Fu?{modeEffect:Fu}:{}},{id:lo}),...Lu&&Lu.length>0?[contribution(LoopChatSuggestion,{id:lo,suggestions:Lu},{id:lo})]:[]]}}var util;(function(Au){Au.assertEqual=Iu=>{};function lo(Iu){}Au.assertIs=lo;function $u(Iu){throw new Error}Au.assertNever=$u,Au.arrayToEnum=Iu=>{const Pu={};for(const Ou of Iu)Pu[Ou]=Ou;return Pu},Au.getValidEnumValues=Iu=>{const Pu=Au.objectKeys(Iu).filter(Mu=>typeof Iu[Iu[Mu]]!="number"),Ou={};for(const Mu of Pu)Ou[Mu]=Iu[Mu];return Au.objectValues(Ou)},Au.objectValues=Iu=>Au.objectKeys(Iu).map(function(Pu){return Iu[Pu]}),Au.objectKeys=typeof Object.keys=="function"?Iu=>Object.keys(Iu):Iu=>{const Pu=[];for(const Ou in Iu)Object.prototype.hasOwnProperty.call(Iu,Ou)&&Pu.push(Ou);return Pu},Au.find=(Iu,Pu)=>{for(const Ou of Iu)if(Pu(Ou))return Ou},Au.isInteger=typeof Number.isInteger=="function"?Iu=>Number.isInteger(Iu):Iu=>typeof Iu=="number"&&Number.isFinite(Iu)&&Math.floor(Iu)===Iu;function Ru(Iu,Pu=" | "){return Iu.map(Ou=>typeof Ou=="string"?`'${Ou}'`:Ou).join(Pu)}Au.joinValues=Ru,Au.jsonStringifyReplacer=(Iu,Pu)=>typeof Pu=="bigint"?Pu.toString():Pu})(util||(util={}));var objectUtil;(function(Au){Au.mergeShapes=(lo,$u)=>({...lo,...$u})})(objectUtil||(objectUtil={}));const ZodParsedType=util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),getParsedType=Au=>{switch(typeof Au){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return Number.isNaN(Au)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":return Array.isArray(Au)?ZodParsedType.array:Au===null?ZodParsedType.null:Au.then&&typeof Au.then=="function"&&Au.catch&&typeof Au.catch=="function"?ZodParsedType.promise:typeof Map<"u"&&Au instanceof Map?ZodParsedType.map:typeof Set<"u"&&Au instanceof Set?ZodParsedType.set:typeof Date<"u"&&Au instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ZodError extends Error{get errors(){return this.issues}constructor(lo){super(),this.issues=[],this.addIssue=Ru=>{this.issues=[...this.issues,Ru]},this.addIssues=(Ru=[])=>{this.issues=[...this.issues,...Ru]};const $u=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,$u):this.__proto__=$u,this.name="ZodError",this.issues=lo}format(lo){const $u=lo||function(Pu){return Pu.message},Ru={_errors:[]},Iu=Pu=>{for(const Ou of Pu.issues)if(Ou.code==="invalid_union")Ou.unionErrors.map(Iu);else if(Ou.code==="invalid_return_type")Iu(Ou.returnTypeError);else if(Ou.code==="invalid_arguments")Iu(Ou.argumentsError);else if(Ou.path.length===0)Ru._errors.push($u(Ou));else{let Mu=Ru,Du=0;for(;Du<Ou.path.length;){const Lu=Ou.path[Du];Du===Ou.path.length-1?(Mu[Lu]=Mu[Lu]||{_errors:[]},Mu[Lu]._errors.push($u(Ou))):Mu[Lu]=Mu[Lu]||{_errors:[]},Mu=Mu[Lu],Du++}}};return Iu(this),Ru}static assert(lo){if(!(lo instanceof ZodError))throw new Error(`Not a ZodError: ${lo}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(lo=$u=>$u.message){const $u={},Ru=[];for(const Iu of this.issues)if(Iu.path.length>0){const Pu=Iu.path[0];$u[Pu]=$u[Pu]||[],$u[Pu].push(lo(Iu))}else Ru.push(lo(Iu));return{formErrors:Ru,fieldErrors:$u}}get formErrors(){return this.flatten()}}ZodError.create=Au=>new ZodError(Au);const errorMap=(Au,lo)=>{let $u;switch(Au.code){case ZodIssueCode.invalid_type:Au.received===ZodParsedType.undefined?$u="Required":$u=`Expected ${Au.expected}, received ${Au.received}`;break;case ZodIssueCode.invalid_literal:$u=`Invalid literal value, expected ${JSON.stringify(Au.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:$u=`Unrecognized key(s) in object: ${util.joinValues(Au.keys,", ")}`;break;case ZodIssueCode.invalid_union:$u="Invalid input";break;case ZodIssueCode.invalid_union_discriminator:$u=`Invalid discriminator value. Expected ${util.joinValues(Au.options)}`;break;case ZodIssueCode.invalid_enum_value:$u=`Invalid enum value. Expected ${util.joinValues(Au.options)}, received '${Au.received}'`;break;case ZodIssueCode.invalid_arguments:$u="Invalid function arguments";break;case ZodIssueCode.invalid_return_type:$u="Invalid function return type";break;case ZodIssueCode.invalid_date:$u="Invalid date";break;case ZodIssueCode.invalid_string:typeof Au.validation=="object"?"includes"in Au.validation?($u=`Invalid input: must include "${Au.validation.includes}"`,typeof Au.validation.position=="number"&&($u=`${$u} at one or more positions greater than or equal to ${Au.validation.position}`)):"startsWith"in Au.validation?$u=`Invalid input: must start with "${Au.validation.startsWith}"`:"endsWith"in Au.validation?$u=`Invalid input: must end with "${Au.validation.endsWith}"`:util.assertNever(Au.validation):Au.validation!=="regex"?$u=`Invalid ${Au.validation}`:$u="Invalid";break;case ZodIssueCode.too_small:Au.type==="array"?$u=`Array must contain ${Au.exact?"exactly":Au.inclusive?"at least":"more than"} ${Au.minimum} element(s)`:Au.type==="string"?$u=`String must contain ${Au.exact?"exactly":Au.inclusive?"at least":"over"} ${Au.minimum} character(s)`:Au.type==="number"?$u=`Number must be ${Au.exact?"exactly equal to ":Au.inclusive?"greater than or equal to ":"greater than "}${Au.minimum}`:Au.type==="bigint"?$u=`Number must be ${Au.exact?"exactly equal to ":Au.inclusive?"greater than or equal to ":"greater than "}${Au.minimum}`:Au.type==="date"?$u=`Date must be ${Au.exact?"exactly equal to ":Au.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(Au.minimum))}`:$u="Invalid input";break;case ZodIssueCode.too_big:Au.type==="array"?$u=`Array must contain ${Au.exact?"exactly":Au.inclusive?"at most":"less than"} ${Au.maximum} element(s)`:Au.type==="string"?$u=`String must contain ${Au.exact?"exactly":Au.inclusive?"at most":"under"} ${Au.maximum} character(s)`:Au.type==="number"?$u=`Number must be ${Au.exact?"exactly":Au.inclusive?"less than or equal to":"less than"} ${Au.maximum}`:Au.type==="bigint"?$u=`BigInt must be ${Au.exact?"exactly":Au.inclusive?"less than or equal to":"less than"} ${Au.maximum}`:Au.type==="date"?$u=`Date must be ${Au.exact?"exactly":Au.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(Au.maximum))}`:$u="Invalid input";break;case ZodIssueCode.custom:$u="Invalid input";break;case ZodIssueCode.invalid_intersection_types:$u="Intersection results could not be merged";break;case ZodIssueCode.not_multiple_of:$u=`Number must be a multiple of ${Au.multipleOf}`;break;case ZodIssueCode.not_finite:$u="Number must be finite";break;default:$u=lo.defaultError,util.assertNever(Au)}return{message:$u}};let overrideErrorMap=errorMap;function getErrorMap(){return overrideErrorMap}const makeIssue=Au=>{const{data:lo,path:$u,errorMaps:Ru,issueData:Iu}=Au,Pu=[...$u,...Iu.path||[]],Ou={...Iu,path:Pu};if(Iu.message!==void 0)return{...Iu,path:Pu,message:Iu.message};let Mu="";const Du=Ru.filter(Lu=>!!Lu).slice().reverse();for(const Lu of Du)Mu=Lu(Ou,{data:lo,defaultError:Mu}).message;return{...Iu,path:Pu,message:Mu}};function addIssueToContext(Au,lo){const $u=getErrorMap(),Ru=makeIssue({issueData:lo,data:Au.data,path:Au.path,errorMaps:[Au.common.contextualErrorMap,Au.schemaErrorMap,$u,$u===errorMap?void 0:errorMap].filter(Iu=>!!Iu)});Au.common.issues.push(Ru)}class ParseStatus{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(lo,$u){const Ru=[];for(const Iu of $u){if(Iu.status==="aborted")return INVALID;Iu.status==="dirty"&&lo.dirty(),Ru.push(Iu.value)}return{status:lo.value,value:Ru}}static async mergeObjectAsync(lo,$u){const Ru=[];for(const Iu of $u){const Pu=await Iu.key,Ou=await Iu.value;Ru.push({key:Pu,value:Ou})}return ParseStatus.mergeObjectSync(lo,Ru)}static mergeObjectSync(lo,$u){const Ru={};for(const Iu of $u){const{key:Pu,value:Ou}=Iu;if(Pu.status==="aborted"||Ou.status==="aborted")return INVALID;Pu.status==="dirty"&&lo.dirty(),Ou.status==="dirty"&&lo.dirty(),Pu.value!=="__proto__"&&(typeof Ou.value<"u"||Iu.alwaysSet)&&(Ru[Pu.value]=Ou.value)}return{status:lo.value,value:Ru}}}const INVALID=Object.freeze({status:"aborted"}),DIRTY=Au=>({status:"dirty",value:Au}),OK=Au=>({status:"valid",value:Au}),isAborted=Au=>Au.status==="aborted",isDirty=Au=>Au.status==="dirty",isValid=Au=>Au.status==="valid",isAsync=Au=>typeof Promise<"u"&&Au instanceof Promise;var errorUtil;(function(Au){Au.errToObj=lo=>typeof lo=="string"?{message:lo}:lo||{},Au.toString=lo=>typeof lo=="string"?lo:lo?.message})(errorUtil||(errorUtil={}));class ParseInputLazyPath{constructor(lo,$u,Ru,Iu){this._cachedPath=[],this.parent=lo,this.data=$u,this._path=Ru,this._key=Iu}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const handleResult=(Au,lo)=>{if(isValid(lo))return{success:!0,data:lo.value};if(!Au.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const $u=new ZodError(Au.common.issues);return this._error=$u,this._error}}};function processCreateParams(Au){if(!Au)return{};const{errorMap:lo,invalid_type_error:$u,required_error:Ru,description:Iu}=Au;if(lo&&($u||Ru))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return lo?{errorMap:lo,description:Iu}:{errorMap:(Ou,Mu)=>{const{message:Du}=Au;return Ou.code==="invalid_enum_value"?{message:Du??Mu.defaultError}:typeof Mu.data>"u"?{message:Du??Ru??Mu.defaultError}:Ou.code!=="invalid_type"?{message:Mu.defaultError}:{message:Du??$u??Mu.defaultError}},description:Iu}}class ZodType{get description(){return this._def.description}_getType(lo){return getParsedType(lo.data)}_getOrReturnCtx(lo,$u){return $u||{common:lo.parent.common,data:lo.data,parsedType:getParsedType(lo.data),schemaErrorMap:this._def.errorMap,path:lo.path,parent:lo.parent}}_processInputParams(lo){return{status:new ParseStatus,ctx:{common:lo.parent.common,data:lo.data,parsedType:getParsedType(lo.data),schemaErrorMap:this._def.errorMap,path:lo.path,parent:lo.parent}}}_parseSync(lo){const $u=this._parse(lo);if(isAsync($u))throw new Error("Synchronous parse encountered promise.");return $u}_parseAsync(lo){const $u=this._parse(lo);return Promise.resolve($u)}parse(lo,$u){const Ru=this.safeParse(lo,$u);if(Ru.success)return Ru.data;throw Ru.error}safeParse(lo,$u){const Ru={common:{issues:[],async:$u?.async??!1,contextualErrorMap:$u?.errorMap},path:$u?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:lo,parsedType:getParsedType(lo)},Iu=this._parseSync({data:lo,path:Ru.path,parent:Ru});return handleResult(Ru,Iu)}"~validate"(lo){const $u={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:lo,parsedType:getParsedType(lo)};if(!this["~standard"].async)try{const Ru=this._parseSync({data:lo,path:[],parent:$u});return isValid(Ru)?{value:Ru.value}:{issues:$u.common.issues}}catch(Ru){Ru?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),$u.common={issues:[],async:!0}}return this._parseAsync({data:lo,path:[],parent:$u}).then(Ru=>isValid(Ru)?{value:Ru.value}:{issues:$u.common.issues})}async parseAsync(lo,$u){const Ru=await this.safeParseAsync(lo,$u);if(Ru.success)return Ru.data;throw Ru.error}async safeParseAsync(lo,$u){const Ru={common:{issues:[],contextualErrorMap:$u?.errorMap,async:!0},path:$u?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:lo,parsedType:getParsedType(lo)},Iu=this._parse({data:lo,path:Ru.path,parent:Ru}),Pu=await(isAsync(Iu)?Iu:Promise.resolve(Iu));return handleResult(Ru,Pu)}refine(lo,$u){const Ru=Iu=>typeof $u=="string"||typeof $u>"u"?{message:$u}:typeof $u=="function"?$u(Iu):$u;return this._refinement((Iu,Pu)=>{const Ou=lo(Iu),Mu=()=>Pu.addIssue({code:ZodIssueCode.custom,...Ru(Iu)});return typeof Promise<"u"&&Ou instanceof Promise?Ou.then(Du=>Du?!0:(Mu(),!1)):Ou?!0:(Mu(),!1)})}refinement(lo,$u){return this._refinement((Ru,Iu)=>lo(Ru)?!0:(Iu.addIssue(typeof $u=="function"?$u(Ru,Iu):$u),!1))}_refinement(lo){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"refinement",refinement:lo}})}superRefine(lo){return this._refinement(lo)}constructor(lo){this.spa=this.safeParseAsync,this._def=lo,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:$u=>this["~validate"]($u)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(lo){return ZodUnion.create([this,lo],this._def)}and(lo){return ZodIntersection.create(this,lo,this._def)}transform(lo){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform:lo}})}default(lo){const $u=typeof lo=="function"?lo:()=>lo;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:$u,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(lo){const $u=typeof lo=="function"?lo:()=>lo;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:$u,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(lo){const $u=this.constructor;return new $u({...this._def,description:lo})}pipe(lo){return ZodPipeline.create(this,lo)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let emojiRegex;const ipv4Regex=/^(?:(?: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])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource="((\\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])))",dateRegex=new RegExp(`^${dateRegexSource}$`);function timeRegexSource(Au){let lo="[0-5]\\d";Au.precision?lo=`${lo}\\.\\d{${Au.precision}}`:Au.precision==null&&(lo=`${lo}(\\.\\d+)?`);const $u=Au.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${lo})${$u}`}function timeRegex(Au){return new RegExp(`^${timeRegexSource(Au)}$`)}function datetimeRegex(Au){let lo=`${dateRegexSource}T${timeRegexSource(Au)}`;const $u=[];return $u.push(Au.local?"Z?":"Z"),Au.offset&&$u.push("([+-]\\d{2}:?\\d{2})"),lo=`${lo}(${$u.join("|")})`,new RegExp(`^${lo}$`)}function isValidIP(Au,lo){return!!((lo==="v4"||!lo)&&ipv4Regex.test(Au)||(lo==="v6"||!lo)&&ipv6Regex.test(Au))}function isValidJWT(Au,lo){if(!jwtRegex.test(Au))return!1;try{const[$u]=Au.split(".");if(!$u)return!1;const Ru=$u.replace(/-/g,"+").replace(/_/g,"/").padEnd($u.length+(4-$u.length%4)%4,"="),Iu=JSON.parse(atob(Ru));return!(typeof Iu!="object"||Iu===null||"typ"in Iu&&Iu?.typ!=="JWT"||!Iu.alg||lo&&Iu.alg!==lo)}catch{return!1}}function isValidCidr(Au,lo){return!!((lo==="v4"||!lo)&&ipv4CidrRegex.test(Au)||(lo==="v6"||!lo)&&ipv6CidrRegex.test(Au))}class ZodString extends ZodType{_parse(lo){if(this._def.coerce&&(lo.data=String(lo.data)),this._getType(lo)!==ZodParsedType.string){const Pu=this._getOrReturnCtx(lo);return addIssueToContext(Pu,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:Pu.parsedType}),INVALID}const Ru=new ParseStatus;let Iu;for(const Pu of this._def.checks)if(Pu.kind==="min")lo.data.length<Pu.value&&(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.too_small,minimum:Pu.value,type:"string",inclusive:!0,exact:!1,message:Pu.message}),Ru.dirty());else if(Pu.kind==="max")lo.data.length>Pu.value&&(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.too_big,maximum:Pu.value,type:"string",inclusive:!0,exact:!1,message:Pu.message}),Ru.dirty());else if(Pu.kind==="length"){const Ou=lo.data.length>Pu.value,Mu=lo.data.length<Pu.value;(Ou||Mu)&&(Iu=this._getOrReturnCtx(lo,Iu),Ou?addIssueToContext(Iu,{code:ZodIssueCode.too_big,maximum:Pu.value,type:"string",inclusive:!0,exact:!0,message:Pu.message}):Mu&&addIssueToContext(Iu,{code:ZodIssueCode.too_small,minimum:Pu.value,type:"string",inclusive:!0,exact:!0,message:Pu.message}),Ru.dirty())}else if(Pu.kind==="email")emailRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"email",code:ZodIssueCode.invalid_string,message:Pu.message}),Ru.dirty());else if(Pu.kind==="emoji")emojiRegex||(emojiRegex=new RegExp(_emojiRegex,"u")),emojiRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"emoji",code:ZodIssueCode.invalid_string,message:Pu.message}),Ru.dirty());else if(Pu.kind==="uuid")uuidRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"uuid",code:ZodIssueCode.invalid_string,message:Pu.message}),Ru.dirty());else if(Pu.kind==="nanoid")nanoidRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:Pu.message}),Ru.dirty());else if(Pu.kind==="cuid")cuidRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"cuid",code:ZodIssueCode.invalid_string,message:Pu.message}),Ru.dirty());else if(Pu.kind==="cuid2")cuid2Regex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:Pu.message}),Ru.dirty());else if(Pu.kind==="ulid")ulidRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"ulid",code:ZodIssueCode.invalid_string,message:Pu.message}),Ru.dirty());else if(Pu.kind==="url")try{new URL(lo.data)}catch{Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"url",code:ZodIssueCode.invalid_string,message:Pu.message}),Ru.dirty()}else Pu.kind==="regex"?(Pu.regex.lastIndex=0,Pu.regex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"regex",code:ZodIssueCode.invalid_string,message:Pu.message}),Ru.dirty())):Pu.kind==="trim"?lo.data=lo.data.trim():Pu.kind==="includes"?lo.data.includes(Pu.value,Pu.position)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.invalid_string,validation:{includes:Pu.value,position:Pu.position},message:Pu.message}),Ru.dirty()):Pu.kind==="toLowerCase"?lo.data=lo.data.toLowerCase():Pu.kind==="toUpperCase"?lo.data=lo.data.toUpperCase():Pu.kind==="startsWith"?lo.data.startsWith(Pu.value)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.invalid_string,validation:{startsWith:Pu.value},message:Pu.message}),Ru.dirty()):Pu.kind==="endsWith"?lo.data.endsWith(Pu.value)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.invalid_string,validation:{endsWith:Pu.value},message:Pu.message}),Ru.dirty()):Pu.kind==="datetime"?datetimeRegex(Pu).test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.invalid_string,validation:"datetime",message:Pu.message}),Ru.dirty()):Pu.kind==="date"?dateRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.invalid_string,validation:"date",message:Pu.message}),Ru.dirty()):Pu.kind==="time"?timeRegex(Pu).test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.invalid_string,validation:"time",message:Pu.message}),Ru.dirty()):Pu.kind==="duration"?durationRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"duration",code:ZodIssueCode.invalid_string,message:Pu.message}),Ru.dirty()):Pu.kind==="ip"?isValidIP(lo.data,Pu.version)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"ip",code:ZodIssueCode.invalid_string,message:Pu.message}),Ru.dirty()):Pu.kind==="jwt"?isValidJWT(lo.data,Pu.alg)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"jwt",code:ZodIssueCode.invalid_string,message:Pu.message}),Ru.dirty()):Pu.kind==="cidr"?isValidCidr(lo.data,Pu.version)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"cidr",code:ZodIssueCode.invalid_string,message:Pu.message}),Ru.dirty()):Pu.kind==="base64"?base64Regex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"base64",code:ZodIssueCode.invalid_string,message:Pu.message}),Ru.dirty()):Pu.kind==="base64url"?base64urlRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"base64url",code:ZodIssueCode.invalid_string,message:Pu.message}),Ru.dirty()):util.assertNever(Pu);return{status:Ru.value,value:lo.data}}_regex(lo,$u,Ru){return this.refinement(Iu=>lo.test(Iu),{validation:$u,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(Ru)})}_addCheck(lo){return new ZodString({...this._def,checks:[...this._def.checks,lo]})}email(lo){return this._addCheck({kind:"email",...errorUtil.errToObj(lo)})}url(lo){return this._addCheck({kind:"url",...errorUtil.errToObj(lo)})}emoji(lo){return this._addCheck({kind:"emoji",...errorUtil.errToObj(lo)})}uuid(lo){return this._addCheck({kind:"uuid",...errorUtil.errToObj(lo)})}nanoid(lo){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(lo)})}cuid(lo){return this._addCheck({kind:"cuid",...errorUtil.errToObj(lo)})}cuid2(lo){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(lo)})}ulid(lo){return this._addCheck({kind:"ulid",...errorUtil.errToObj(lo)})}base64(lo){return this._addCheck({kind:"base64",...errorUtil.errToObj(lo)})}base64url(lo){return this._addCheck({kind:"base64url",...errorUtil.errToObj(lo)})}jwt(lo){return this._addCheck({kind:"jwt",...errorUtil.errToObj(lo)})}ip(lo){return this._addCheck({kind:"ip",...errorUtil.errToObj(lo)})}cidr(lo){return this._addCheck({kind:"cidr",...errorUtil.errToObj(lo)})}datetime(lo){return typeof lo=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:lo}):this._addCheck({kind:"datetime",precision:typeof lo?.precision>"u"?null:lo?.precision,offset:lo?.offset??!1,local:lo?.local??!1,...errorUtil.errToObj(lo?.message)})}date(lo){return this._addCheck({kind:"date",message:lo})}time(lo){return typeof lo=="string"?this._addCheck({kind:"time",precision:null,message:lo}):this._addCheck({kind:"time",precision:typeof lo?.precision>"u"?null:lo?.precision,...errorUtil.errToObj(lo?.message)})}duration(lo){return this._addCheck({kind:"duration",...errorUtil.errToObj(lo)})}regex(lo,$u){return this._addCheck({kind:"regex",regex:lo,...errorUtil.errToObj($u)})}includes(lo,$u){return this._addCheck({kind:"includes",value:lo,position:$u?.position,...errorUtil.errToObj($u?.message)})}startsWith(lo,$u){return this._addCheck({kind:"startsWith",value:lo,...errorUtil.errToObj($u)})}endsWith(lo,$u){return this._addCheck({kind:"endsWith",value:lo,...errorUtil.errToObj($u)})}min(lo,$u){return this._addCheck({kind:"min",value:lo,...errorUtil.errToObj($u)})}max(lo,$u){return this._addCheck({kind:"max",value:lo,...errorUtil.errToObj($u)})}length(lo,$u){return this._addCheck({kind:"length",value:lo,...errorUtil.errToObj($u)})}nonempty(lo){return this.min(1,errorUtil.errToObj(lo))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(lo=>lo.kind==="datetime")}get isDate(){return!!this._def.checks.find(lo=>lo.kind==="date")}get isTime(){return!!this._def.checks.find(lo=>lo.kind==="time")}get isDuration(){return!!this._def.checks.find(lo=>lo.kind==="duration")}get isEmail(){return!!this._def.checks.find(lo=>lo.kind==="email")}get isURL(){return!!this._def.checks.find(lo=>lo.kind==="url")}get isEmoji(){return!!this._def.checks.find(lo=>lo.kind==="emoji")}get isUUID(){return!!this._def.checks.find(lo=>lo.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(lo=>lo.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(lo=>lo.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(lo=>lo.kind==="cuid2")}get isULID(){return!!this._def.checks.find(lo=>lo.kind==="ulid")}get isIP(){return!!this._def.checks.find(lo=>lo.kind==="ip")}get isCIDR(){return!!this._def.checks.find(lo=>lo.kind==="cidr")}get isBase64(){return!!this._def.checks.find(lo=>lo.kind==="base64")}get isBase64url(){return!!this._def.checks.find(lo=>lo.kind==="base64url")}get minLength(){let lo=null;for(const $u of this._def.checks)$u.kind==="min"&&(lo===null||$u.value>lo)&&(lo=$u.value);return lo}get maxLength(){let lo=null;for(const $u of this._def.checks)$u.kind==="max"&&(lo===null||$u.value<lo)&&(lo=$u.value);return lo}}ZodString.create=Au=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:Au?.coerce??!1,...processCreateParams(Au)});function floatSafeRemainder(Au,lo){const $u=(Au.toString().split(".")[1]||"").length,Ru=(lo.toString().split(".")[1]||"").length,Iu=$u>Ru?$u:Ru,Pu=Number.parseInt(Au.toFixed(Iu).replace(".","")),Ou=Number.parseInt(lo.toFixed(Iu).replace(".",""));return Pu%Ou/10**Iu}class ZodNumber extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(lo){if(this._def.coerce&&(lo.data=Number(lo.data)),this._getType(lo)!==ZodParsedType.number){const Pu=this._getOrReturnCtx(lo);return addIssueToContext(Pu,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:Pu.parsedType}),INVALID}let Ru;const Iu=new ParseStatus;for(const Pu of this._def.checks)Pu.kind==="int"?util.isInteger(lo.data)||(Ru=this._getOrReturnCtx(lo,Ru),addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:Pu.message}),Iu.dirty()):Pu.kind==="min"?(Pu.inclusive?lo.data<Pu.value:lo.data<=Pu.value)&&(Ru=this._getOrReturnCtx(lo,Ru),addIssueToContext(Ru,{code:ZodIssueCode.too_small,minimum:Pu.value,type:"number",inclusive:Pu.inclusive,exact:!1,message:Pu.message}),Iu.dirty()):Pu.kind==="max"?(Pu.inclusive?lo.data>Pu.value:lo.data>=Pu.value)&&(Ru=this._getOrReturnCtx(lo,Ru),addIssueToContext(Ru,{code:ZodIssueCode.too_big,maximum:Pu.value,type:"number",inclusive:Pu.inclusive,exact:!1,message:Pu.message}),Iu.dirty()):Pu.kind==="multipleOf"?floatSafeRemainder(lo.data,Pu.value)!==0&&(Ru=this._getOrReturnCtx(lo,Ru),addIssueToContext(Ru,{code:ZodIssueCode.not_multiple_of,multipleOf:Pu.value,message:Pu.message}),Iu.dirty()):Pu.kind==="finite"?Number.isFinite(lo.data)||(Ru=this._getOrReturnCtx(lo,Ru),addIssueToContext(Ru,{code:ZodIssueCode.not_finite,message:Pu.message}),Iu.dirty()):util.assertNever(Pu);return{status:Iu.value,value:lo.data}}gte(lo,$u){return this.setLimit("min",lo,!0,errorUtil.toString($u))}gt(lo,$u){return this.setLimit("min",lo,!1,errorUtil.toString($u))}lte(lo,$u){return this.setLimit("max",lo,!0,errorUtil.toString($u))}lt(lo,$u){return this.setLimit("max",lo,!1,errorUtil.toString($u))}setLimit(lo,$u,Ru,Iu){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind:lo,value:$u,inclusive:Ru,message:errorUtil.toString(Iu)}]})}_addCheck(lo){return new ZodNumber({...this._def,checks:[...this._def.checks,lo]})}int(lo){return this._addCheck({kind:"int",message:errorUtil.toString(lo)})}positive(lo){return this._addCheck({kind:"min",value:0,inclusive:!1,message:errorUtil.toString(lo)})}negative(lo){return this._addCheck({kind:"max",value:0,inclusive:!1,message:errorUtil.toString(lo)})}nonpositive(lo){return this._addCheck({kind:"max",value:0,inclusive:!0,message:errorUtil.toString(lo)})}nonnegative(lo){return this._addCheck({kind:"min",value:0,inclusive:!0,message:errorUtil.toString(lo)})}multipleOf(lo,$u){return this._addCheck({kind:"multipleOf",value:lo,message:errorUtil.toString($u)})}finite(lo){return this._addCheck({kind:"finite",message:errorUtil.toString(lo)})}safe(lo){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString(lo)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil.toString(lo)})}get minValue(){let lo=null;for(const $u of this._def.checks)$u.kind==="min"&&(lo===null||$u.value>lo)&&(lo=$u.value);return lo}get maxValue(){let lo=null;for(const $u of this._def.checks)$u.kind==="max"&&(lo===null||$u.value<lo)&&(lo=$u.value);return lo}get isInt(){return!!this._def.checks.find(lo=>lo.kind==="int"||lo.kind==="multipleOf"&&util.isInteger(lo.value))}get isFinite(){let lo=null,$u=null;for(const Ru of this._def.checks){if(Ru.kind==="finite"||Ru.kind==="int"||Ru.kind==="multipleOf")return!0;Ru.kind==="min"?($u===null||Ru.value>$u)&&($u=Ru.value):Ru.kind==="max"&&(lo===null||Ru.value<lo)&&(lo=Ru.value)}return Number.isFinite($u)&&Number.isFinite(lo)}}ZodNumber.create=Au=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:Au?.coerce||!1,...processCreateParams(Au)});class ZodBigInt extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(lo){if(this._def.coerce)try{lo.data=BigInt(lo.data)}catch{return this._getInvalidInput(lo)}if(this._getType(lo)!==ZodParsedType.bigint)return this._getInvalidInput(lo);let Ru;const Iu=new ParseStatus;for(const Pu of this._def.checks)Pu.kind==="min"?(Pu.inclusive?lo.data<Pu.value:lo.data<=Pu.value)&&(Ru=this._getOrReturnCtx(lo,Ru),addIssueToContext(Ru,{code:ZodIssueCode.too_small,type:"bigint",minimum:Pu.value,inclusive:Pu.inclusive,message:Pu.message}),Iu.dirty()):Pu.kind==="max"?(Pu.inclusive?lo.data>Pu.value:lo.data>=Pu.value)&&(Ru=this._getOrReturnCtx(lo,Ru),addIssueToContext(Ru,{code:ZodIssueCode.too_big,type:"bigint",maximum:Pu.value,inclusive:Pu.inclusive,message:Pu.message}),Iu.dirty()):Pu.kind==="multipleOf"?lo.data%Pu.value!==BigInt(0)&&(Ru=this._getOrReturnCtx(lo,Ru),addIssueToContext(Ru,{code:ZodIssueCode.not_multiple_of,multipleOf:Pu.value,message:Pu.message}),Iu.dirty()):util.assertNever(Pu);return{status:Iu.value,value:lo.data}}_getInvalidInput(lo){const $u=this._getOrReturnCtx(lo);return addIssueToContext($u,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:$u.parsedType}),INVALID}gte(lo,$u){return this.setLimit("min",lo,!0,errorUtil.toString($u))}gt(lo,$u){return this.setLimit("min",lo,!1,errorUtil.toString($u))}lte(lo,$u){return this.setLimit("max",lo,!0,errorUtil.toString($u))}lt(lo,$u){return this.setLimit("max",lo,!1,errorUtil.toString($u))}setLimit(lo,$u,Ru,Iu){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:lo,value:$u,inclusive:Ru,message:errorUtil.toString(Iu)}]})}_addCheck(lo){return new ZodBigInt({...this._def,checks:[...this._def.checks,lo]})}positive(lo){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString(lo)})}negative(lo){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString(lo)})}nonpositive(lo){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString(lo)})}nonnegative(lo){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString(lo)})}multipleOf(lo,$u){return this._addCheck({kind:"multipleOf",value:lo,message:errorUtil.toString($u)})}get minValue(){let lo=null;for(const $u of this._def.checks)$u.kind==="min"&&(lo===null||$u.value>lo)&&(lo=$u.value);return lo}get maxValue(){let lo=null;for(const $u of this._def.checks)$u.kind==="max"&&(lo===null||$u.value<lo)&&(lo=$u.value);return lo}}ZodBigInt.create=Au=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:Au?.coerce??!1,...processCreateParams(Au)});class ZodBoolean extends ZodType{_parse(lo){if(this._def.coerce&&(lo.data=!!lo.data),this._getType(lo)!==ZodParsedType.boolean){const Ru=this._getOrReturnCtx(lo);return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:Ru.parsedType}),INVALID}return OK(lo.data)}}ZodBoolean.create=Au=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:Au?.coerce||!1,...processCreateParams(Au)});class ZodDate extends ZodType{_parse(lo){if(this._def.coerce&&(lo.data=new Date(lo.data)),this._getType(lo)!==ZodParsedType.date){const Pu=this._getOrReturnCtx(lo);return addIssueToContext(Pu,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:Pu.parsedType}),INVALID}if(Number.isNaN(lo.data.getTime())){const Pu=this._getOrReturnCtx(lo);return addIssueToContext(Pu,{code:ZodIssueCode.invalid_date}),INVALID}const Ru=new ParseStatus;let Iu;for(const Pu of this._def.checks)Pu.kind==="min"?lo.data.getTime()<Pu.value&&(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.too_small,message:Pu.message,inclusive:!0,exact:!1,minimum:Pu.value,type:"date"}),Ru.dirty()):Pu.kind==="max"?lo.data.getTime()>Pu.value&&(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.too_big,message:Pu.message,inclusive:!0,exact:!1,maximum:Pu.value,type:"date"}),Ru.dirty()):util.assertNever(Pu);return{status:Ru.value,value:new Date(lo.data.getTime())}}_addCheck(lo){return new ZodDate({...this._def,checks:[...this._def.checks,lo]})}min(lo,$u){return this._addCheck({kind:"min",value:lo.getTime(),message:errorUtil.toString($u)})}max(lo,$u){return this._addCheck({kind:"max",value:lo.getTime(),message:errorUtil.toString($u)})}get minDate(){let lo=null;for(const $u of this._def.checks)$u.kind==="min"&&(lo===null||$u.value>lo)&&(lo=$u.value);return lo!=null?new Date(lo):null}get maxDate(){let lo=null;for(const $u of this._def.checks)$u.kind==="max"&&(lo===null||$u.value<lo)&&(lo=$u.value);return lo!=null?new Date(lo):null}}ZodDate.create=Au=>new ZodDate({checks:[],coerce:Au?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(Au)});class ZodSymbol extends ZodType{_parse(lo){if(this._getType(lo)!==ZodParsedType.symbol){const Ru=this._getOrReturnCtx(lo);return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:Ru.parsedType}),INVALID}return OK(lo.data)}}ZodSymbol.create=Au=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(Au)});class ZodUndefined extends ZodType{_parse(lo){if(this._getType(lo)!==ZodParsedType.undefined){const Ru=this._getOrReturnCtx(lo);return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:Ru.parsedType}),INVALID}return OK(lo.data)}}ZodUndefined.create=Au=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(Au)});class ZodNull extends ZodType{_parse(lo){if(this._getType(lo)!==ZodParsedType.null){const Ru=this._getOrReturnCtx(lo);return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:Ru.parsedType}),INVALID}return OK(lo.data)}}ZodNull.create=Au=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(Au)});class ZodAny extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(lo){return OK(lo.data)}}ZodAny.create=Au=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(Au)});class ZodUnknown extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(lo){return OK(lo.data)}}ZodUnknown.create=Au=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(Au)});class ZodNever extends ZodType{_parse(lo){const $u=this._getOrReturnCtx(lo);return addIssueToContext($u,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:$u.parsedType}),INVALID}}ZodNever.create=Au=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(Au)});class ZodVoid extends ZodType{_parse(lo){if(this._getType(lo)!==ZodParsedType.undefined){const Ru=this._getOrReturnCtx(lo);return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:Ru.parsedType}),INVALID}return OK(lo.data)}}ZodVoid.create=Au=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(Au)});class ZodArray extends ZodType{_parse(lo){const{ctx:$u,status:Ru}=this._processInputParams(lo),Iu=this._def;if($u.parsedType!==ZodParsedType.array)return addIssueToContext($u,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:$u.parsedType}),INVALID;if(Iu.exactLength!==null){const Ou=$u.data.length>Iu.exactLength.value,Mu=$u.data.length<Iu.exactLength.value;(Ou||Mu)&&(addIssueToContext($u,{code:Ou?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:Mu?Iu.exactLength.value:void 0,maximum:Ou?Iu.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:Iu.exactLength.message}),Ru.dirty())}if(Iu.minLength!==null&&$u.data.length<Iu.minLength.value&&(addIssueToContext($u,{code:ZodIssueCode.too_small,minimum:Iu.minLength.value,type:"array",inclusive:!0,exact:!1,message:Iu.minLength.message}),Ru.dirty()),Iu.maxLength!==null&&$u.data.length>Iu.maxLength.value&&(addIssueToContext($u,{code:ZodIssueCode.too_big,maximum:Iu.maxLength.value,type:"array",inclusive:!0,exact:!1,message:Iu.maxLength.message}),Ru.dirty()),$u.common.async)return Promise.all([...$u.data].map((Ou,Mu)=>Iu.type._parseAsync(new ParseInputLazyPath($u,Ou,$u.path,Mu)))).then(Ou=>ParseStatus.mergeArray(Ru,Ou));const Pu=[...$u.data].map((Ou,Mu)=>Iu.type._parseSync(new ParseInputLazyPath($u,Ou,$u.path,Mu)));return ParseStatus.mergeArray(Ru,Pu)}get element(){return this._def.type}min(lo,$u){return new ZodArray({...this._def,minLength:{value:lo,message:errorUtil.toString($u)}})}max(lo,$u){return new ZodArray({...this._def,maxLength:{value:lo,message:errorUtil.toString($u)}})}length(lo,$u){return new ZodArray({...this._def,exactLength:{value:lo,message:errorUtil.toString($u)}})}nonempty(lo){return this.min(1,lo)}}ZodArray.create=(Au,lo)=>new ZodArray({type:Au,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(lo)});function deepPartialify(Au){if(Au instanceof ZodObject){const lo={};for(const $u in Au.shape){const Ru=Au.shape[$u];lo[$u]=ZodOptional.create(deepPartialify(Ru))}return new ZodObject({...Au._def,shape:()=>lo})}else return Au instanceof ZodArray?new ZodArray({...Au._def,type:deepPartialify(Au.element)}):Au instanceof ZodOptional?ZodOptional.create(deepPartialify(Au.unwrap())):Au instanceof ZodNullable?ZodNullable.create(deepPartialify(Au.unwrap())):Au instanceof ZodTuple?ZodTuple.create(Au.items.map(lo=>deepPartialify(lo))):Au}class ZodObject extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const lo=this._def.shape(),$u=util.objectKeys(lo);return this._cached={shape:lo,keys:$u},this._cached}_parse(lo){if(this._getType(lo)!==ZodParsedType.object){const Lu=this._getOrReturnCtx(lo);return addIssueToContext(Lu,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:Lu.parsedType}),INVALID}const{status:Ru,ctx:Iu}=this._processInputParams(lo),{shape:Pu,keys:Ou}=this._getCached(),Mu=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys==="strip"))for(const Lu in Iu.data)Ou.includes(Lu)||Mu.push(Lu);const Du=[];for(const Lu of Ou){const Bu=Pu[Lu],ju=Iu.data[Lu];Du.push({key:{status:"valid",value:Lu},value:Bu._parse(new ParseInputLazyPath(Iu,ju,Iu.path,Lu)),alwaysSet:Lu in Iu.data})}if(this._def.catchall instanceof ZodNever){const Lu=this._def.unknownKeys;if(Lu==="passthrough")for(const Bu of Mu)Du.push({key:{status:"valid",value:Bu},value:{status:"valid",value:Iu.data[Bu]}});else if(Lu==="strict")Mu.length>0&&(addIssueToContext(Iu,{code:ZodIssueCode.unrecognized_keys,keys:Mu}),Ru.dirty());else if(Lu!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const Lu=this._def.catchall;for(const Bu of Mu){const ju=Iu.data[Bu];Du.push({key:{status:"valid",value:Bu},value:Lu._parse(new ParseInputLazyPath(Iu,ju,Iu.path,Bu)),alwaysSet:Bu in Iu.data})}}return Iu.common.async?Promise.resolve().then(async()=>{const Lu=[];for(const Bu of Du){const ju=await Bu.key,Fu=await Bu.value;Lu.push({key:ju,value:Fu,alwaysSet:Bu.alwaysSet})}return Lu}).then(Lu=>ParseStatus.mergeObjectSync(Ru,Lu)):ParseStatus.mergeObjectSync(Ru,Du)}get shape(){return this._def.shape()}strict(lo){return errorUtil.errToObj,new ZodObject({...this._def,unknownKeys:"strict",...lo!==void 0?{errorMap:($u,Ru)=>{const Iu=this._def.errorMap?.($u,Ru).message??Ru.defaultError;return $u.code==="unrecognized_keys"?{message:errorUtil.errToObj(lo).message??Iu}:{message:Iu}}}:{}})}strip(){return new ZodObject({...this._def,unknownKeys:"strip"})}passthrough(){return new ZodObject({...this._def,unknownKeys:"passthrough"})}extend(lo){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...lo})})}merge(lo){return new ZodObject({unknownKeys:lo._def.unknownKeys,catchall:lo._def.catchall,shape:()=>({...this._def.shape(),...lo._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(lo,$u){return this.augment({[lo]:$u})}catchall(lo){return new ZodObject({...this._def,catchall:lo})}pick(lo){const $u={};for(const Ru of util.objectKeys(lo))lo[Ru]&&this.shape[Ru]&&($u[Ru]=this.shape[Ru]);return new ZodObject({...this._def,shape:()=>$u})}omit(lo){const $u={};for(const Ru of util.objectKeys(this.shape))lo[Ru]||($u[Ru]=this.shape[Ru]);return new ZodObject({...this._def,shape:()=>$u})}deepPartial(){return deepPartialify(this)}partial(lo){const $u={};for(const Ru of util.objectKeys(this.shape)){const Iu=this.shape[Ru];lo&&!lo[Ru]?$u[Ru]=Iu:$u[Ru]=Iu.optional()}return new ZodObject({...this._def,shape:()=>$u})}required(lo){const $u={};for(const Ru of util.objectKeys(this.shape))if(lo&&!lo[Ru])$u[Ru]=this.shape[Ru];else{let Pu=this.shape[Ru];for(;Pu instanceof ZodOptional;)Pu=Pu._def.innerType;$u[Ru]=Pu}return new ZodObject({...this._def,shape:()=>$u})}keyof(){return createZodEnum(util.objectKeys(this.shape))}}ZodObject.create=(Au,lo)=>new ZodObject({shape:()=>Au,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(lo)});ZodObject.strictCreate=(Au,lo)=>new ZodObject({shape:()=>Au,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(lo)});ZodObject.lazycreate=(Au,lo)=>new ZodObject({shape:Au,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(lo)});class ZodUnion extends ZodType{_parse(lo){const{ctx:$u}=this._processInputParams(lo),Ru=this._def.options;function Iu(Pu){for(const Mu of Pu)if(Mu.result.status==="valid")return Mu.result;for(const Mu of Pu)if(Mu.result.status==="dirty")return $u.common.issues.push(...Mu.ctx.common.issues),Mu.result;const Ou=Pu.map(Mu=>new ZodError(Mu.ctx.common.issues));return addIssueToContext($u,{code:ZodIssueCode.invalid_union,unionErrors:Ou}),INVALID}if($u.common.async)return Promise.all(Ru.map(async Pu=>{const Ou={...$u,common:{...$u.common,issues:[]},parent:null};return{result:await Pu._parseAsync({data:$u.data,path:$u.path,parent:Ou}),ctx:Ou}})).then(Iu);{let Pu;const Ou=[];for(const Du of Ru){const Lu={...$u,common:{...$u.common,issues:[]},parent:null},Bu=Du._parseSync({data:$u.data,path:$u.path,parent:Lu});if(Bu.status==="valid")return Bu;Bu.status==="dirty"&&!Pu&&(Pu={result:Bu,ctx:Lu}),Lu.common.issues.length&&Ou.push(Lu.common.issues)}if(Pu)return $u.common.issues.push(...Pu.ctx.common.issues),Pu.result;const Mu=Ou.map(Du=>new ZodError(Du));return addIssueToContext($u,{code:ZodIssueCode.invalid_union,unionErrors:Mu}),INVALID}}get options(){return this._def.options}}ZodUnion.create=(Au,lo)=>new ZodUnion({options:Au,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(lo)});function mergeValues(Au,lo){const $u=getParsedType(Au),Ru=getParsedType(lo);if(Au===lo)return{valid:!0,data:Au};if($u===ZodParsedType.object&&Ru===ZodParsedType.object){const Iu=util.objectKeys(lo),Pu=util.objectKeys(Au).filter(Mu=>Iu.indexOf(Mu)!==-1),Ou={...Au,...lo};for(const Mu of Pu){const Du=mergeValues(Au[Mu],lo[Mu]);if(!Du.valid)return{valid:!1};Ou[Mu]=Du.data}return{valid:!0,data:Ou}}else if($u===ZodParsedType.array&&Ru===ZodParsedType.array){if(Au.length!==lo.length)return{valid:!1};const Iu=[];for(let Pu=0;Pu<Au.length;Pu++){const Ou=Au[Pu],Mu=lo[Pu],Du=mergeValues(Ou,Mu);if(!Du.valid)return{valid:!1};Iu.push(Du.data)}return{valid:!0,data:Iu}}else return $u===ZodParsedType.date&&Ru===ZodParsedType.date&&+Au==+lo?{valid:!0,data:Au}:{valid:!1}}class ZodIntersection extends ZodType{_parse(lo){const{status:$u,ctx:Ru}=this._processInputParams(lo),Iu=(Pu,Ou)=>{if(isAborted(Pu)||isAborted(Ou))return INVALID;const Mu=mergeValues(Pu.value,Ou.value);return Mu.valid?((isDirty(Pu)||isDirty(Ou))&&$u.dirty(),{status:$u.value,value:Mu.data}):(addIssueToContext(Ru,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return Ru.common.async?Promise.all([this._def.left._parseAsync({data:Ru.data,path:Ru.path,parent:Ru}),this._def.right._parseAsync({data:Ru.data,path:Ru.path,parent:Ru})]).then(([Pu,Ou])=>Iu(Pu,Ou)):Iu(this._def.left._parseSync({data:Ru.data,path:Ru.path,parent:Ru}),this._def.right._parseSync({data:Ru.data,path:Ru.path,parent:Ru}))}}ZodIntersection.create=(Au,lo,$u)=>new ZodIntersection({left:Au,right:lo,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams($u)});class ZodTuple extends ZodType{_parse(lo){const{status:$u,ctx:Ru}=this._processInputParams(lo);if(Ru.parsedType!==ZodParsedType.array)return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:Ru.parsedType}),INVALID;if(Ru.data.length<this._def.items.length)return addIssueToContext(Ru,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;!this._def.rest&&Ru.data.length>this._def.items.length&&(addIssueToContext(Ru,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),$u.dirty());const Pu=[...Ru.data].map((Ou,Mu)=>{const Du=this._def.items[Mu]||this._def.rest;return Du?Du._parse(new ParseInputLazyPath(Ru,Ou,Ru.path,Mu)):null}).filter(Ou=>!!Ou);return Ru.common.async?Promise.all(Pu).then(Ou=>ParseStatus.mergeArray($u,Ou)):ParseStatus.mergeArray($u,Pu)}get items(){return this._def.items}rest(lo){return new ZodTuple({...this._def,rest:lo})}}ZodTuple.create=(Au,lo)=>{if(!Array.isArray(Au))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:Au,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(lo)})};class ZodRecord extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(lo){const{status:$u,ctx:Ru}=this._processInputParams(lo);if(Ru.parsedType!==ZodParsedType.object)return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:Ru.parsedType}),INVALID;const Iu=[],Pu=this._def.keyType,Ou=this._def.valueType;for(const Mu in Ru.data)Iu.push({key:Pu._parse(new ParseInputLazyPath(Ru,Mu,Ru.path,Mu)),value:Ou._parse(new ParseInputLazyPath(Ru,Ru.data[Mu],Ru.path,Mu)),alwaysSet:Mu in Ru.data});return Ru.common.async?ParseStatus.mergeObjectAsync($u,Iu):ParseStatus.mergeObjectSync($u,Iu)}get element(){return this._def.valueType}static create(lo,$u,Ru){return $u instanceof ZodType?new ZodRecord({keyType:lo,valueType:$u,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(Ru)}):new ZodRecord({keyType:ZodString.create(),valueType:lo,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams($u)})}}class ZodMap extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(lo){const{status:$u,ctx:Ru}=this._processInputParams(lo);if(Ru.parsedType!==ZodParsedType.map)return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:Ru.parsedType}),INVALID;const Iu=this._def.keyType,Pu=this._def.valueType,Ou=[...Ru.data.entries()].map(([Mu,Du],Lu)=>({key:Iu._parse(new ParseInputLazyPath(Ru,Mu,Ru.path,[Lu,"key"])),value:Pu._parse(new ParseInputLazyPath(Ru,Du,Ru.path,[Lu,"value"]))}));if(Ru.common.async){const Mu=new Map;return Promise.resolve().then(async()=>{for(const Du of Ou){const Lu=await Du.key,Bu=await Du.value;if(Lu.status==="aborted"||Bu.status==="aborted")return INVALID;(Lu.status==="dirty"||Bu.status==="dirty")&&$u.dirty(),Mu.set(Lu.value,Bu.value)}return{status:$u.value,value:Mu}})}else{const Mu=new Map;for(const Du of Ou){const Lu=Du.key,Bu=Du.value;if(Lu.status==="aborted"||Bu.status==="aborted")return INVALID;(Lu.status==="dirty"||Bu.status==="dirty")&&$u.dirty(),Mu.set(Lu.value,Bu.value)}return{status:$u.value,value:Mu}}}}ZodMap.create=(Au,lo,$u)=>new ZodMap({valueType:lo,keyType:Au,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams($u)});class ZodSet extends ZodType{_parse(lo){const{status:$u,ctx:Ru}=this._processInputParams(lo);if(Ru.parsedType!==ZodParsedType.set)return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:Ru.parsedType}),INVALID;const Iu=this._def;Iu.minSize!==null&&Ru.data.size<Iu.minSize.value&&(addIssueToContext(Ru,{code:ZodIssueCode.too_small,minimum:Iu.minSize.value,type:"set",inclusive:!0,exact:!1,message:Iu.minSize.message}),$u.dirty()),Iu.maxSize!==null&&Ru.data.size>Iu.maxSize.value&&(addIssueToContext(Ru,{code:ZodIssueCode.too_big,maximum:Iu.maxSize.value,type:"set",inclusive:!0,exact:!1,message:Iu.maxSize.message}),$u.dirty());const Pu=this._def.valueType;function Ou(Du){const Lu=new Set;for(const Bu of Du){if(Bu.status==="aborted")return INVALID;Bu.status==="dirty"&&$u.dirty(),Lu.add(Bu.value)}return{status:$u.value,value:Lu}}const Mu=[...Ru.data.values()].map((Du,Lu)=>Pu._parse(new ParseInputLazyPath(Ru,Du,Ru.path,Lu)));return Ru.common.async?Promise.all(Mu).then(Du=>Ou(Du)):Ou(Mu)}min(lo,$u){return new ZodSet({...this._def,minSize:{value:lo,message:errorUtil.toString($u)}})}max(lo,$u){return new ZodSet({...this._def,maxSize:{value:lo,message:errorUtil.toString($u)}})}size(lo,$u){return this.min(lo,$u).max(lo,$u)}nonempty(lo){return this.min(1,lo)}}ZodSet.create=(Au,lo)=>new ZodSet({valueType:Au,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(lo)});class ZodLazy extends ZodType{get schema(){return this._def.getter()}_parse(lo){const{ctx:$u}=this._processInputParams(lo);return this._def.getter()._parse({data:$u.data,path:$u.path,parent:$u})}}ZodLazy.create=(Au,lo)=>new ZodLazy({getter:Au,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(lo)});class ZodLiteral extends ZodType{_parse(lo){if(lo.data!==this._def.value){const $u=this._getOrReturnCtx(lo);return addIssueToContext($u,{received:$u.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:lo.data}}get value(){return this._def.value}}ZodLiteral.create=(Au,lo)=>new ZodLiteral({value:Au,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(lo)});function createZodEnum(Au,lo){return new ZodEnum({values:Au,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(lo)})}class ZodEnum extends ZodType{_parse(lo){if(typeof lo.data!="string"){const $u=this._getOrReturnCtx(lo),Ru=this._def.values;return addIssueToContext($u,{expected:util.joinValues(Ru),received:$u.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(lo.data)){const $u=this._getOrReturnCtx(lo),Ru=this._def.values;return addIssueToContext($u,{received:$u.data,code:ZodIssueCode.invalid_enum_value,options:Ru}),INVALID}return OK(lo.data)}get options(){return this._def.values}get enum(){const lo={};for(const $u of this._def.values)lo[$u]=$u;return lo}get Values(){const lo={};for(const $u of this._def.values)lo[$u]=$u;return lo}get Enum(){const lo={};for(const $u of this._def.values)lo[$u]=$u;return lo}extract(lo,$u=this._def){return ZodEnum.create(lo,{...this._def,...$u})}exclude(lo,$u=this._def){return ZodEnum.create(this.options.filter(Ru=>!lo.includes(Ru)),{...this._def,...$u})}}ZodEnum.create=createZodEnum;class ZodNativeEnum extends ZodType{_parse(lo){const $u=util.getValidEnumValues(this._def.values),Ru=this._getOrReturnCtx(lo);if(Ru.parsedType!==ZodParsedType.string&&Ru.parsedType!==ZodParsedType.number){const Iu=util.objectValues($u);return addIssueToContext(Ru,{expected:util.joinValues(Iu),received:Ru.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(util.getValidEnumValues(this._def.values))),!this._cache.has(lo.data)){const Iu=util.objectValues($u);return addIssueToContext(Ru,{received:Ru.data,code:ZodIssueCode.invalid_enum_value,options:Iu}),INVALID}return OK(lo.data)}get enum(){return this._def.values}}ZodNativeEnum.create=(Au,lo)=>new ZodNativeEnum({values:Au,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(lo)});class ZodPromise extends ZodType{unwrap(){return this._def.type}_parse(lo){const{ctx:$u}=this._processInputParams(lo);if($u.parsedType!==ZodParsedType.promise&&$u.common.async===!1)return addIssueToContext($u,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:$u.parsedType}),INVALID;const Ru=$u.parsedType===ZodParsedType.promise?$u.data:Promise.resolve($u.data);return OK(Ru.then(Iu=>this._def.type.parseAsync(Iu,{path:$u.path,errorMap:$u.common.contextualErrorMap})))}}ZodPromise.create=(Au,lo)=>new ZodPromise({type:Au,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(lo)});class ZodEffects extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(lo){const{status:$u,ctx:Ru}=this._processInputParams(lo),Iu=this._def.effect||null,Pu={addIssue:Ou=>{addIssueToContext(Ru,Ou),Ou.fatal?$u.abort():$u.dirty()},get path(){return Ru.path}};if(Pu.addIssue=Pu.addIssue.bind(Pu),Iu.type==="preprocess"){const Ou=Iu.transform(Ru.data,Pu);if(Ru.common.async)return Promise.resolve(Ou).then(async Mu=>{if($u.value==="aborted")return INVALID;const Du=await this._def.schema._parseAsync({data:Mu,path:Ru.path,parent:Ru});return Du.status==="aborted"?INVALID:Du.status==="dirty"||$u.value==="dirty"?DIRTY(Du.value):Du});{if($u.value==="aborted")return INVALID;const Mu=this._def.schema._parseSync({data:Ou,path:Ru.path,parent:Ru});return Mu.status==="aborted"?INVALID:Mu.status==="dirty"||$u.value==="dirty"?DIRTY(Mu.value):Mu}}if(Iu.type==="refinement"){const Ou=Mu=>{const Du=Iu.refinement(Mu,Pu);if(Ru.common.async)return Promise.resolve(Du);if(Du instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return Mu};if(Ru.common.async===!1){const Mu=this._def.schema._parseSync({data:Ru.data,path:Ru.path,parent:Ru});return Mu.status==="aborted"?INVALID:(Mu.status==="dirty"&&$u.dirty(),Ou(Mu.value),{status:$u.value,value:Mu.value})}else return this._def.schema._parseAsync({data:Ru.data,path:Ru.path,parent:Ru}).then(Mu=>Mu.status==="aborted"?INVALID:(Mu.status==="dirty"&&$u.dirty(),Ou(Mu.value).then(()=>({status:$u.value,value:Mu.value}))))}if(Iu.type==="transform")if(Ru.common.async===!1){const Ou=this._def.schema._parseSync({data:Ru.data,path:Ru.path,parent:Ru});if(!isValid(Ou))return INVALID;const Mu=Iu.transform(Ou.value,Pu);if(Mu instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:$u.value,value:Mu}}else return this._def.schema._parseAsync({data:Ru.data,path:Ru.path,parent:Ru}).then(Ou=>isValid(Ou)?Promise.resolve(Iu.transform(Ou.value,Pu)).then(Mu=>({status:$u.value,value:Mu})):INVALID);util.assertNever(Iu)}}ZodEffects.create=(Au,lo,$u)=>new ZodEffects({schema:Au,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:lo,...processCreateParams($u)});ZodEffects.createWithPreprocess=(Au,lo,$u)=>new ZodEffects({schema:lo,effect:{type:"preprocess",transform:Au},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams($u)});class ZodOptional extends ZodType{_parse(lo){return this._getType(lo)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(lo)}unwrap(){return this._def.innerType}}ZodOptional.create=(Au,lo)=>new ZodOptional({innerType:Au,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(lo)});class ZodNullable extends ZodType{_parse(lo){return this._getType(lo)===ZodParsedType.null?OK(null):this._def.innerType._parse(lo)}unwrap(){return this._def.innerType}}ZodNullable.create=(Au,lo)=>new ZodNullable({innerType:Au,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(lo)});class ZodDefault extends ZodType{_parse(lo){const{ctx:$u}=this._processInputParams(lo);let Ru=$u.data;return $u.parsedType===ZodParsedType.undefined&&(Ru=this._def.defaultValue()),this._def.innerType._parse({data:Ru,path:$u.path,parent:$u})}removeDefault(){return this._def.innerType}}ZodDefault.create=(Au,lo)=>new ZodDefault({innerType:Au,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof lo.default=="function"?lo.default:()=>lo.default,...processCreateParams(lo)});class ZodCatch extends ZodType{_parse(lo){const{ctx:$u}=this._processInputParams(lo),Ru={...$u,common:{...$u.common,issues:[]}},Iu=this._def.innerType._parse({data:Ru.data,path:Ru.path,parent:{...Ru}});return isAsync(Iu)?Iu.then(Pu=>({status:"valid",value:Pu.status==="valid"?Pu.value:this._def.catchValue({get error(){return new ZodError(Ru.common.issues)},input:Ru.data})})):{status:"valid",value:Iu.status==="valid"?Iu.value:this._def.catchValue({get error(){return new ZodError(Ru.common.issues)},input:Ru.data})}}removeCatch(){return this._def.innerType}}ZodCatch.create=(Au,lo)=>new ZodCatch({innerType:Au,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof lo.catch=="function"?lo.catch:()=>lo.catch,...processCreateParams(lo)});class ZodNaN extends ZodType{_parse(lo){if(this._getType(lo)!==ZodParsedType.nan){const Ru=this._getOrReturnCtx(lo);return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:Ru.parsedType}),INVALID}return{status:"valid",value:lo.data}}}ZodNaN.create=Au=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(Au)});class ZodBranded extends ZodType{_parse(lo){const{ctx:$u}=this._processInputParams(lo),Ru=$u.data;return this._def.type._parse({data:Ru,path:$u.path,parent:$u})}unwrap(){return this._def.type}}class ZodPipeline extends ZodType{_parse(lo){const{status:$u,ctx:Ru}=this._processInputParams(lo);if(Ru.common.async)return(async()=>{const Pu=await this._def.in._parseAsync({data:Ru.data,path:Ru.path,parent:Ru});return Pu.status==="aborted"?INVALID:Pu.status==="dirty"?($u.dirty(),DIRTY(Pu.value)):this._def.out._parseAsync({data:Pu.value,path:Ru.path,parent:Ru})})();{const Iu=this._def.in._parseSync({data:Ru.data,path:Ru.path,parent:Ru});return Iu.status==="aborted"?INVALID:Iu.status==="dirty"?($u.dirty(),{status:"dirty",value:Iu.value}):this._def.out._parseSync({data:Iu.value,path:Ru.path,parent:Ru})}}static create(lo,$u){return new ZodPipeline({in:lo,out:$u,typeName:ZodFirstPartyTypeKind.ZodPipeline})}}class ZodReadonly extends ZodType{_parse(lo){const $u=this._def.innerType._parse(lo),Ru=Iu=>(isValid(Iu)&&(Iu.value=Object.freeze(Iu.value)),Iu);return isAsync($u)?$u.then(Iu=>Ru(Iu)):Ru($u)}unwrap(){return this._def.innerType}}ZodReadonly.create=(Au,lo)=>new ZodReadonly({innerType:Au,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(lo)});var ZodFirstPartyTypeKind;(function(Au){Au.ZodString="ZodString",Au.ZodNumber="ZodNumber",Au.ZodNaN="ZodNaN",Au.ZodBigInt="ZodBigInt",Au.ZodBoolean="ZodBoolean",Au.ZodDate="ZodDate",Au.ZodSymbol="ZodSymbol",Au.ZodUndefined="ZodUndefined",Au.ZodNull="ZodNull",Au.ZodAny="ZodAny",Au.ZodUnknown="ZodUnknown",Au.ZodNever="ZodNever",Au.ZodVoid="ZodVoid",Au.ZodArray="ZodArray",Au.ZodObject="ZodObject",Au.ZodUnion="ZodUnion",Au.ZodDiscriminatedUnion="ZodDiscriminatedUnion",Au.ZodIntersection="ZodIntersection",Au.ZodTuple="ZodTuple",Au.ZodRecord="ZodRecord",Au.ZodMap="ZodMap",Au.ZodSet="ZodSet",Au.ZodFunction="ZodFunction",Au.ZodLazy="ZodLazy",Au.ZodLiteral="ZodLiteral",Au.ZodEnum="ZodEnum",Au.ZodEffects="ZodEffects",Au.ZodNativeEnum="ZodNativeEnum",Au.ZodOptional="ZodOptional",Au.ZodNullable="ZodNullable",Au.ZodDefault="ZodDefault",Au.ZodCatch="ZodCatch",Au.ZodPromise="ZodPromise",Au.ZodBranded="ZodBranded",Au.ZodPipeline="ZodPipeline",Au.ZodReadonly="ZodReadonly"})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));const stringType=ZodString.create,numberType=ZodNumber.create;ZodBigInt.create;const booleanType=ZodBoolean.create;ZodDate.create;const anyType=ZodAny.create,unknownType=ZodUnknown.create;ZodNever.create;const arrayType=ZodArray.create,objectType=ZodObject.create,unionType=ZodUnion.create,intersectionType=ZodIntersection.create;ZodTuple.create;const recordType=ZodRecord.create,lazyType=ZodLazy.create,literalType=ZodLiteral.create,enumType=ZodEnum.create;ZodPromise.create;ZodOptional.create;ZodNullable.create;const coerce={string:(Au=>ZodString.create({...Au,coerce:!0})),number:(Au=>ZodNumber.create({...Au,coerce:!0})),boolean:(Au=>ZodBoolean.create({...Au,coerce:!0})),bigint:(Au=>ZodBigInt.create({...Au,coerce:!0})),date:(Au=>ZodDate.create({...Au,coerce:!0}))};class A2uiError extends Error{constructor(lo,$u="UNKNOWN_ERROR"){super(lo),this.name=this.constructor.name,this.code=$u,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}class A2uiValidationError extends A2uiError{constructor(lo,$u,Ru="VALIDATION_ERROR"){super(lo,Ru),this.details=$u}}class A2uiDataError extends A2uiError{constructor(lo,$u){super(lo,"DATA_ERROR"),this.path=$u}}class A2uiExpressionError extends A2uiError{constructor(lo,$u,Ru){super(lo,"EXPRESSION_ERROR"),this.expression=$u,this.details=Ru}}class A2uiStateError extends A2uiError{constructor(lo){super(lo,"STATE_ERROR")}}class A2uiCatalogError extends A2uiError{constructor(lo,$u="CATALOG_ERROR"){super(lo,$u)}}class A2uiIntegrityError extends A2uiValidationError{constructor(lo,$u,Ru="INTEGRITY_ERROR"){super(lo,$u,Ru),this.name="A2uiIntegrityError"}}class A2uiRecursionError extends A2uiValidationError{constructor(lo,$u,Ru="RECURSION_ERROR"){super(lo,$u,Ru),this.name="A2uiRecursionError"}}var RpcErrorCode;(function(Au){Au.INVALID_FUNCTION_CALL="INVALID_FUNCTION_CALL",Au.EXECUTION_ERROR="EXECUTION_ERROR",Au.UNKNOWN_FUNCTION="UNKNOWN_FUNCTION",Au.UNKNOWN_ERROR="UNKNOWN_ERROR",Au.TIMEOUT="TIMEOUT",Au.CANCELLED="CANCELLED",Au.DISPOSED="DISPOSED",Au.DUPLICATE="DUPLICATE",Au.NO_LISTENER="NO_LISTENER"})(RpcErrorCode||(RpcErrorCode={}));class A2uiRpcError extends A2uiError{constructor(lo,$u=RpcErrorCode.UNKNOWN_ERROR,Ru,Iu){const Pu=$u||RpcErrorCode.UNKNOWN_ERROR;super(`[${Pu}] ${lo}`,Pu),this.functionCallId=Ru,this.details=Iu,this.name="A2uiRpcError"}}function markChildRef(Au,lo){return Au._def.a2uiChildRef=lo,Au}function childRefKindOf(Au){return Au?._def?.a2uiChildRef}const MAX_FUNCTION_CALL_ARGS=1e3;objectType({component:stringType().describe("The type name of the component."),id:lazyType(()=>ComponentIdSchema$2).optional(),weight:numberType().optional()}).passthrough().describe("A generic A2UI component definition.");const ComponentIdSchema$2=markChildRef(stringType().describe("REF:common_types.json#/$defs/ComponentId|The unique identifier for a component, used for both definitions and references within the same surface."),"component-id"),DataBindingSchema$2=objectType({path:stringType().describe("A JSON Pointer path to a value in the data model.")}).describe("REF:common_types.json#/$defs/DataBinding"),FunctionCallSchema$2=objectType({call:stringType().describe("The name of the function to call."),args:recordType(stringType(),unknownType()).describe("Arguments passed to the function.").optional(),returnType:enumType(["string","number","boolean","array","object","any","void"]).describe("The expected return type of the function call.").optional(),catalogId:stringType().describe("The catalog ID for this function, overriding any surface-level default catalogId.").optional()}).describe("REF:common_types.json#/$defs/FunctionCall|Invokes a named function, combining common function properties with the catalog function definition."),DynamicStringSchema$2=unionType([stringType(),DataBindingSchema$2,FunctionCallSchema$2]).describe("REF:common_types.json#/$defs/DynamicString|Represents a string"),DynamicBooleanSchema$2=unionType([booleanType(),DataBindingSchema$2,FunctionCallSchema$2]).describe("REF:common_types.json#/$defs/DynamicBoolean|A boolean value that can be a literal, a path, or a function call returning a boolean."),AccessibilityAttributesSchema$2=objectType({label:DynamicStringSchema$2.optional(),description:DynamicStringSchema$2.optional(),live:enumType(["off","polite","assertive"]).default("off").describe("Controls screen reader announcements for dynamic updates (WAI-ARIA aria-live). 'polite' waits for user pause; 'assertive' interrupts immediately for alerts.").optional(),hidden:DynamicBooleanSchema$2.optional()}).describe("REF:common_types.json#/$defs/AccessibilityAttributes|Attributes to enhance accessibility when using assistive technologies like screen readers or model understanding."),ExtensionsSchema$1=recordType(stringType(),unknownType()).superRefine((Au,lo)=>{for(const $u in Au)$u.match(/^[\p{XID_Start}_][\p{XID_Continue}]*$/u)||lo.addIssue({path:[$u],code:ZodIssueCode.custom,message:`Invalid extension key "${$u}": Keys MUST be Unicode identifiers (UAX #31).`})}).describe("REF:#/$defs/Extensions|Optional extension metadata. Keys MUST be Unicode identifiers (UAX #31). Keys starting with 'a2ui_' are reserved for official extensions.");objectType({id:ComponentIdSchema$2,accessibility:AccessibilityAttributesSchema$2.optional(),catalogId:stringType().describe("The catalog ID for this component, overriding any surface-level default catalogId.").optional(),metadata:objectType({extensions:ExtensionsSchema$1.optional()}).strict().describe("Optional component-level metadata for vendor extensions.").optional()}).describe("REF:common_types.json#/$defs/ComponentCommon");const ChildListSchema$1=markChildRef(unionType([arrayType(ComponentIdSchema$2).describe("A static list of child component IDs."),objectType({componentId:ComponentIdSchema$2,path:stringType().describe("The path to the list of component property objects in the data model.")}).describe("A template for generating a dynamic list of children.")]).describe("REF:common_types.json#/$defs/ChildList"),"child-list"),DynamicValueSchema$2=unionType([stringType(),numberType(),booleanType(),arrayType(unknownType()),DataBindingSchema$2,FunctionCallSchema$2,recordType(stringType(),unknownType()).refine(Au=>!Au||!("path"in Au)&&!("call"in Au))]).describe("REF:common_types.json#/$defs/DynamicValue|A value that can be a literal, a path, or a function call returning any type."),DynamicNumberSchema$2=unionType([numberType(),DataBindingSchema$2,FunctionCallSchema$2]).describe("REF:common_types.json#/$defs/DynamicNumber|Represents a value that can be either a literal number, a path to a number in the data model, or a function call returning a number."),DynamicStringListSchema$1=unionType([arrayType(stringType()),DataBindingSchema$2,FunctionCallSchema$2]).describe("REF:common_types.json#/$defs/DynamicStringList|Represents a value that can be either a literal array of strings, a path to a string array in the data model, or a function call returning a string array."),CheckRuleSchema$2=objectType({condition:unionType([DynamicBooleanSchema$2,DataBindingSchema$2,FunctionCallSchema$2]).describe("Path or function call evaluating to a structured validation result object."),message:stringType().describe("Optional fallback error message.").optional()}).describe("REF:common_types.json#/$defs/CheckRule|A single validation check rule applied to an input component. The condition function or path evaluates to a structured validation result object."),CheckableSchema=objectType({checks:arrayType(CheckRuleSchema$2).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional()}).describe("REF:common_types.json#/$defs/Checkable|Properties for components that support renderer-side checks."),ActionSchema$2=unionType([objectType({event:objectType({name:stringType().describe("The name of the action to be dispatched to the server."),context:recordType(stringType(),unknownType()).describe("A JSON object containing the key-value pairs for the action context. Values can be literals or paths. Use literal values unless the value must be dynamically bound to the data model. Do NOT use paths for static IDs.").optional()}).strict().describe("The event to dispatch to the server.")}).strict().describe("Triggers a server-side event."),objectType({functionCall:FunctionCallSchema$2}).strict().describe("Executes a local client-side function."),objectType({event:objectType({name:stringType().describe("The name of the action to be dispatched to the agent."),userMessage:DynamicStringSchema$2.optional(),context:recordType(stringType(),unknownType()).describe("A JSON object containing the key-value pairs for the action context. Values can be literals or paths. Use literal values unless the value must be dynamically bound to the data model. Do NOT use paths for static IDs.").optional()}).strict().describe("The event to dispatch to the agent.")}).strict().describe("Triggers an agent-side event."),objectType({functionCall:FunctionCallSchema$2}).strict().describe("Executes a renderer or agent-side function.")]).describe("REF:common_types.json#/$defs/Action|Defines an interaction handler that can either trigger an agent-side event or execute a local renderer-side function."),CallIdSchema$1=stringType().describe("REF:common_types.json#/$defs/CallId|The unique identifier for a function call.");objectType({call:stringType().describe("The name of the function to call."),catalogId:stringType().describe("The catalog ID for this function, overriding any surface-level default catalogId.").optional()}).describe("REF:common_types.json#/$defs/FunctionCommon|Baseline envelope properties common to all function calls. Function-specific argument schemas (\\'args\\') are defined individually by each function in the active catalog.");objectType({call:literalType("@index"),args:objectType({offset:DynamicNumberSchema$2.optional()}).strict().optional()}).strict().describe("REF:common_types.json#/$defs/IndexSystemFunction|Returns the 0-based index of the current item when rendering a dynamic list from a template. This function MUST ONLY be available when evaluating template items within a list context.");objectType({component:literalType("Surface").optional(),child:literalType("root").optional()}).strict().describe("REF:common_types.json#/$defs/Surface|The reserved canonical container component representing an A2UI surface. The Surface component is immutable and always has \\'child\\': \\'root\\'.");objectType({functionCallId:CallIdSchema$1,value:unknownType().describe("The return value of the function.").optional(),error:objectType({code:stringType(),message:stringType()}).strict().describe("An error object indicating failure of the function execution.").optional()}).strict().describe("REF:common_types.json#/$defs/FunctionResponse|The return response matching a callAgentFunction or callRendererFunction invocation.");const SEMVER_REGEX=/^[vV]?(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*))?(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;function normalizeVersionString(Au){if(!Au||typeof Au!="string")return"";const lo=Au.trim().replace(/^[vV]/,""),$u=lo.indexOf("-"),Ru=lo.indexOf("+");let Iu=lo.length;return $u!==-1&&Ru!==-1?Iu=Math.min($u,Ru):$u!==-1?Iu=$u:Ru!==-1&&(Iu=Ru),`${lo.slice(0,Iu).replace(/_/g,".")}${lo.slice(Iu)}`}function parseSemVer(Au){if(!Au||typeof Au!="string")return null;const lo=Au.trim().match(SEMVER_REGEX);return lo?{major:parseInt(lo[1],10),minor:parseInt(lo[2],10),patch:lo[3]!==void 0?parseInt(lo[3],10):0,prerelease:lo[4]?lo[4].split("."):[],build:lo[5]?lo[5].split("."):[]}:null}function toSemVer(Au){if(!Au)return null;if(typeof Au=="object"){const lo=Au;return typeof lo.major!="number"||!Number.isInteger(lo.major)||lo.major<0||typeof lo.minor=="number"&&(!Number.isInteger(lo.minor)||lo.minor<0)||typeof lo.patch=="number"&&(!Number.isInteger(lo.patch)||lo.patch<0)?null:{major:lo.major,minor:typeof lo.minor=="number"?lo.minor:0,patch:typeof lo.patch=="number"?lo.patch:0,prerelease:Array.isArray(lo.prerelease)?lo.prerelease:[],build:Array.isArray(lo.build)?lo.build:[]}}return parseSemVer(normalizeVersionString(Au))}function toCanonicalVersion(Au){if(!Au)return null;const lo=toSemVer(Au);if(!lo)return null;if(lo.patch===0&&lo.prerelease.length===0&&lo.build.length===0)return`${lo.major}.${lo.minor}`;const $u=lo.prerelease.length>0?`-${lo.prerelease.join(".")}`:"",Ru=lo.build.length>0?`+${lo.build.join(".")}`:"";return`${lo.major}.${lo.minor}.${lo.patch}${$u}${Ru}`}function comparePrereleaseId(Au,lo){const $u=/^\d+$/.test(Au),Ru=/^\d+$/.test(lo);return $u&&Ru?Au.length!==lo.length?Au.length-lo.length:Au<lo?-1:Au>lo?1:0:$u?-1:Ru?1:Au<lo?-1:Au>lo?1:0}function comparePrereleaseLists(Au,lo){if(Au.length===0&&lo.length===0)return 0;if(Au.length===0)return 1;if(lo.length===0)return-1;const $u=Math.min(Au.length,lo.length);for(let Ru=0;Ru<$u;Ru++){const Iu=comparePrereleaseId(Au[Ru],lo[Ru]);if(Iu!==0)return Iu}return Au.length-lo.length}function compareSemVer(Au,lo){const $u=toSemVer(Au),Ru=toSemVer(lo);return!$u&&!Ru?0:$u?Ru?$u.major!==Ru.major?$u.major-Ru.major:$u.minor!==Ru.minor?$u.minor-Ru.minor:$u.patch!==Ru.patch?$u.patch-Ru.patch:comparePrereleaseLists($u.prerelease,Ru.prerelease):1:-1}function isAtLeastVersion(Au,lo){if(!Au)return!1;const $u=toSemVer(Au),Ru=toSemVer(lo);return!$u||!Ru?!1:compareSemVer($u,Ru)>=0}const UAX31_IDENTIFIER=/^[\p{XID_Start}_][\p{XID_Continue}]*$/u;function isValidUax31Identifier(Au){if(!Au)return!1;const lo=Au.startsWith("@")?Au.slice(1):Au;return UAX31_IDENTIFIER.test(lo)}function assertUax31Identifier(Au,lo){if(!isValidUax31Identifier(Au))throw new A2uiCatalogError(`Invalid UAX #31 ${lo}`)}const DEFAULT_PROTOCOL_VERSION="0.9",COMMON_TYPE_SCHEMAS={DynamicString:DynamicStringSchema$2,DynamicNumber:DynamicNumberSchema$2,DynamicBoolean:DynamicBooleanSchema$2,DynamicStringList:DynamicStringListSchema$1,DynamicValue:DynamicValueSchema$2,ComponentId:ComponentIdSchema$2,ChildList:ChildListSchema$1,Action:ActionSchema$2,CheckRule:CheckRuleSchema$2,Checkable:CheckableSchema,AccessibilityAttributes:AccessibilityAttributesSchema$2,DataBinding:DataBindingSchema$2,FunctionCall:FunctionCallSchema$2};function resolveJsonPointer(Au,lo){if(!lo.startsWith("#/"))return;const $u=lo.slice(2).split("/").map(Iu=>Iu.replace(/~1/g,"/").replace(/~0/g,"~"));let Ru=Au;for(const Iu of $u)if(Ru&&typeof Ru=="object"&&Iu in Ru)Ru=Ru[Iu];else return;return typeof Ru=="object"&&Ru!==null?Ru:void 0}function resolveProtocolRef(Au){const lo=Au.split(/#\/(?:\$defs|definitions)\//)[1];return lo?COMMON_TYPE_SCHEMAS[lo]:void 0}function convertEnumToZod(Au){return Au.length===0?unknownType():Au.every(lo=>typeof lo=="string")?enumType(Au):Au.length===1?literalType(Au[0]):unionType(Au.map(lo=>literalType(lo)))}function canonicalJsonStringify(Au){return Au===null||typeof Au!="object"?JSON.stringify(Au):Array.isArray(Au)?`[${Au.map(canonicalJsonStringify).join(",")}]`:`{${Object.keys(Au).sort().map(Ru=>`${JSON.stringify(Ru)}:${canonicalJsonStringify(Au[Ru])}`).join(",")}}`}function finalizePropertyZod(Au,lo,$u,Ru,Iu){let Pu=Au;if(lo.not&&typeof lo.not=="object"){const Ou=convertPropertyToZod(lo.not,$u,new Set(Ru),Iu);Pu=Pu.refine(Mu=>!Ou.safeParse(Mu).success,{message:'Value matched prohibited "not" schema'})}return lo.default!==void 0&&(Pu=Pu.default(lo.default)),typeof lo.description=="string"&&(Pu=Pu.describe(lo.description)),Pu}function convertRefToZod(Au,lo,$u,Ru,Iu){const Pu=resolveProtocolRef(Au);if(Pu){const Ou=Au.split(/#\/(?:\$defs|definitions)\//)[1],Mu=typeof lo.description=="string"?`REF:common_types.json#/$defs/${Ou}|${lo.description}`:Pu.description;return Mu?Pu.describe(Mu):Pu}if($u&&Au.startsWith("#/")){const Ou=resolveJsonPointer($u,Au);if(!Ou)return unknownType().superRefine((Du,Lu)=>{Lu.addIssue({code:ZodIssueCode.custom,message:`Unresolvable schema reference: '${Au}'`})});if(Ru.has(Au)){let Du=Iu.get(Au);return lazyType(()=>(Du||(Du=Iu.get(Au)??convertPropertyToZod(Ou,$u,new Set([Au]),Iu),Iu.set(Au,Du)),Du))}let Mu=Iu.get(Au);if(!Mu){const Du=new Set(Ru);Du.add(Au),Mu=convertPropertyToZod(Ou,$u,Du,Iu),Iu.set(Au,Mu)}return typeof lo.description=="string"&&(Mu=Mu.describe(lo.description)),Mu}}function convertUnionToZod(Au,lo,$u,Ru){const Iu=Array.isArray(Au.oneOf),Ou=(Au.oneOf||Au.anyOf).filter(Fu=>typeof Fu=="object"&&Fu!==null);if(Ou.length===0)return;const Mu=Ou.find(Fu=>Array.isArray(Fu.enum)),Du=Ou.some(Fu=>typeof Fu.$ref=="string"&&Fu.$ref.includes("DataBinding")),Lu=Ou.map(Fu=>convertPropertyToZod(Fu,lo,new Set($u),Ru));let Bu;if(Lu.length===1)Bu=Lu[0];else{const Fu=unionType([Lu[0],Lu[1],...Lu.slice(2)]);Bu=Iu?anyType().superRefine((zu,Uu)=>{let Hu=0;for(const Vu of Lu)if(Vu.safeParse(zu).success&&++Hu>1){Uu.addIssue({code:ZodIssueCode.custom,message:"Value matched more than one schema in oneOf"});return}}).pipe(Fu):Fu}Au.default!==void 0&&(Bu=Bu.default(Au.default));const ju=(typeof Au.description=="string"?Au.description:void 0)||(Mu&&Du?"REF:common_types.json#/$defs/DynamicString":void 0);return ju?Bu.describe(ju):Bu}function convertPropertyToZod(Au,lo,$u=new Set,Ru=new Map){if(!Au||typeof Au!="object")return unknownType();if(Au.$ref&&typeof Au.$ref=="string"){const Iu=convertRefToZod(Au.$ref,Au,lo,$u,Ru);if(Iu)return Iu}if(Array.isArray(Au.oneOf)||Array.isArray(Au.anyOf)){const Iu=convertUnionToZod(Au,lo,$u,Ru);if(Iu)return Iu}if(Au.const!==void 0){const Iu=literalType(Au.const);return finalizePropertyZod(Iu,Au,lo,$u,Ru)}if(Array.isArray(Au.enum)&&Au.enum.length>0){const Iu=convertEnumToZod(Au.enum);return finalizePropertyZod(Iu,Au,lo,$u,Ru)}if(Au.type==="array"){const Iu=Au.items&&typeof Au.items=="object"?convertPropertyToZod(Au.items,lo,new Set($u),Ru):unknownType();let Pu=arrayType(Iu);return typeof Au.minItems=="number"&&(Pu=Pu.min(Au.minItems)),typeof Au.maxItems=="number"&&(Pu=Pu.max(Au.maxItems)),Au.uniqueItems===!0&&(Pu=Pu.refine(Ou=>new Set(Ou.map(canonicalJsonStringify)).size===Ou.length,{message:"Array items must be unique"})),finalizePropertyZod(Pu,Au,lo,$u,Ru)}switch(Au.type){case"string":{let Iu=stringType();if(typeof Au.minLength=="number"&&(Iu=Iu.min(Au.minLength)),typeof Au.maxLength=="number"&&(Iu=Iu.max(Au.maxLength)),typeof Au.pattern=="string")try{Iu=Iu.regex(new RegExp(Au.pattern,"u"))}catch{}return finalizePropertyZod(Iu,Au,lo,$u,Ru)}case"integer":case"number":{let Iu=Au.type==="integer"?numberType().int():numberType();return typeof Au.minimum=="number"&&(Iu=Iu.min(Au.minimum)),typeof Au.maximum=="number"&&(Iu=Iu.max(Au.maximum)),typeof Au.exclusiveMinimum=="number"&&(Iu=Iu.gt(Au.exclusiveMinimum)),typeof Au.exclusiveMaximum=="number"&&(Iu=Iu.lt(Au.exclusiveMaximum)),typeof Au.multipleOf=="number"&&(Iu=Iu.multipleOf(Au.multipleOf)),finalizePropertyZod(Iu,Au,lo,$u,Ru)}case"boolean":return finalizePropertyZod(booleanType(),Au,lo,$u,Ru);case"object":{const Iu=Au.properties;let Pu;if(typeof Iu=="object"&&Iu!==null){const Ou=Array.isArray(Au.required)?new Set(Au.required.filter(Lu=>typeof Lu=="string")):new Set,Mu=objectType(convertPropertiesToShape(Iu,Ou,!1,lo,$u,Ru));Pu=Au.additionalProperties===!1||Au.unevaluatedProperties===!1?Mu.strict():Mu.passthrough()}else Pu=recordType(unknownType());return finalizePropertyZod(Pu,Au,lo,$u,Ru)}default:return finalizePropertyZod(unknownType(),Au,lo,$u,Ru)}}function convertPropertiesToShape(Au,lo,$u=!1,Ru,Iu,Pu=new Map){const Ou={};for(const[Mu,Du]of Object.entries(Au)){if($u&&(Mu==="component"||Mu==="id"))continue;const Lu=convertPropertyToZod(typeof Du=="object"&&Du!==null?Du:{},Ru,Iu?new Set(Iu):new Set,Pu);Ou[Mu]=lo.has(Mu)?Lu:Lu.optional()}return Ou}function collectComponentSubSchemas(Au,lo,$u=new Set){const Ru=[];if(!Au||typeof Au!="object")return Ru;if(Array.isArray(Au.allOf)){for(const Iu of Au.allOf)if(!(!Iu||typeof Iu!="object"))if(typeof Iu.$ref=="string"){const Pu=Iu.$ref;if(Pu.includes("common_types.json")&&Pu.includes("ComponentCommon"))Ru.push({properties:{accessibility:AccessibilityAttributesSchema$2.optional()}});else if(Pu.startsWith("#/")&&!$u.has(Pu)){$u.add(Pu);const Ou=resolveJsonPointer(lo,Pu);Ou&&Ru.push(...collectComponentSubSchemas(Ou,lo,$u))}}else Ru.push(...collectComponentSubSchemas(Iu,lo,$u))}return Au.properties&&Ru.push(Au),Ru}function convertComponentJsonSchemaToZod(Au,lo,$u=!0,Ru=new Map){const Iu={},Pu=collectComponentSubSchemas(Au,lo),Ou=new Set;for(const Lu of Pu)Array.isArray(Lu.required)&&Lu.required.forEach(Bu=>{typeof Bu=="string"&&Ou.add(Bu)});for(const Lu of Pu){const Bu=convertPropertiesToShape(Lu.properties||{},Ou,$u,lo,void 0,Ru);Object.assign(Iu,Bu)}const Mu=objectType(Iu);return Au.unevaluatedProperties===!0||typeof Au.unevaluatedProperties=="object"&&Au.unevaluatedProperties!==null||Au.additionalProperties===!0||typeof Au.additionalProperties=="object"&&Au.additionalProperties!==null?Mu.passthrough():Mu.strict()}function convertFunctionArgsJsonSchemaToZod(Au,lo,$u=new Map){const Ru=new Set(Array.isArray(Au.required)?Au.required.filter(Mu=>typeof Mu=="string"):[]),Iu=convertPropertiesToShape(Au.properties||{},Ru,!1,lo,void 0,$u),Pu=objectType(Iu);return Au.unevaluatedProperties===!0||typeof Au.unevaluatedProperties=="object"&&Au.unevaluatedProperties!==null||Au.additionalProperties===!0||typeof Au.additionalProperties=="object"&&Au.additionalProperties!==null?Pu.passthrough():Pu.strict()}function parseFunctionDefinitions(Au,lo,$u,Ru=!1){const Iu=[];if(!Au)return Iu;const Pu=new Map,Ou=(Mu,Du)=>{if(Ru&&(assertUax31Identifier(Mu,`function identifier: '${Mu}'`),Du&&typeof Du=="object"))for(const Lu of Object.keys(Du))assertUax31Identifier(Lu,`argument identifier: '${Lu}' in function '${Mu}'`)};if(Array.isArray(Au)){for(const Mu of Au)if(Mu&&typeof Mu=="object"&&typeof Mu.name=="string"){if(Ou(Mu.name,Mu.parameters),$u&&!$u.has(Mu.name))continue;const Du=Mu.parameters&&typeof Mu.parameters=="object"?convertFunctionArgsJsonSchemaToZod(Mu.parameters,lo,Pu):recordType(unknownType());Iu.push({name:Mu.name,description:typeof Mu.description=="string"?Mu.description:void 0,returnType:typeof Mu.returnType=="string"?Mu.returnType:"any",allowedCallers:Mu.allowedCallers,requiresUserActivation:Mu.requiresUserActivation,schema:Du})}return Iu}if(typeof Au=="object"&&Au!==null)for(const[Mu,Du]of Object.entries(Au)){const Lu=Du&&typeof Du=="object"?Du:{};if(Ou(Mu,Lu.properties&&typeof Lu.properties=="object"?Lu.properties:Lu.parameters),$u&&!$u.has(Mu)||!Du||typeof Du!="object")continue;const Bu=Du,ju=Bu.properties;let Fu=ju?.args??Bu.args??Bu.parameters;!Fu&&ju&&!("call"in ju)&&!("function"in ju)?Fu=Bu:Fu&&typeof Fu=="object"&&!("properties"in Fu)&&!("type"in Fu)&&(Fu={type:"object",properties:Fu,required:Bu.required,additionalProperties:Bu.additionalProperties});const zu=Fu&&typeof Fu=="object"?convertFunctionArgsJsonSchemaToZod(Fu,lo,Pu):recordType(unknownType()),Uu=(typeof Bu.returnType=="string"?Bu.returnType:void 0)??(typeof ju?.returnType?.const=="string"?(ju?.returnType).const:"any"),Hu=Bu.allowedCallers??ju?.allowedCallers?.const,Vu=Bu.requiresUserActivation??ju?.requiresUserActivation?.const;Iu.push({name:Mu,description:typeof Bu.description=="string"?Bu.description:void 0,returnType:Uu,allowedCallers:Hu,requiresUserActivation:Vu,schema:zu})}return Iu}function extractPermittedNames(Au,lo){if(!Array.isArray(Au))return;const $u=new Set;for(const Ru of Au)if(typeof Ru?.$ref=="string"&&Ru.$ref.startsWith(lo)){const Pu=Ru.$ref.slice(lo.length).replace(/~([01])/g,(Ou,Mu)=>Mu==="1"?"/":"~");$u.add(Pu)}return $u}function parseCatalogComponents(Au,lo,$u,Ru){const Iu=[],Pu=new Map;for(const[Ou,Mu]of Object.entries(Au)){const Du=Mu||{};if($u){assertUax31Identifier(Ou,`component identifier: '${Ou}'`);const Bu=Du.properties;if(Bu&&typeof Bu=="object")for(const ju of Object.keys(Bu))assertUax31Identifier(ju,`property identifier: '${ju}' in component '${Ou}'`)}if(Ru&&!Ru.has(Ou))continue;const Lu=convertComponentJsonSchemaToZod(Du,lo,!0,Pu);Iu.push({name:Ou,schema:Lu,allowedParents:Array.isArray(Du.allowedParents)?Du.allowedParents.filter(Bu=>typeof Bu=="string"):void 0,allowedChildren:Array.isArray(Du.allowedChildren)?Du.allowedChildren.filter(Bu=>typeof Bu=="string"):void 0})}return Iu}function parseThemeSchema(Au,lo){const $u=Au.theme??Au.themeSchema??Au.styles??lo?.theme;if($u&&typeof $u=="object")return convertComponentJsonSchemaToZod($u,Au,!1)}function loadCatalogFromSchema(Au,lo){const $u=Au.catalogId??Au.$id??Au.id;if(!$u||typeof $u!="string")throw new Error("Catalog ID must be specified via catalog metadata ('catalogId' or '$id').");const Ru=Au.$defs,Iu=Ru?.anyComponent,Pu=extractPermittedNames(Iu?.oneOf,"#/components/"),Ou=lo??Au.protocolVersion??DEFAULT_PROTOCOL_VERSION,Mu=isAtLeastVersion(Ou,"1.0"),Du=Au.components??{},Lu=parseCatalogComponents(Du,Au,Mu,Pu),Bu=Ru?.anyFunction,ju=extractPermittedNames(Bu?.oneOf,"#/functions/"),Fu=parseFunctionDefinitions(Au.functions,Au,ju,Mu),zu=parseThemeSchema(Au,Ru),Uu=typeof Au.instructions=="string"?Au.instructions:void 0;return new Catalog($u,Ou,Lu,Fu,zu,Uu)}const V08_STANDARD_DEFS={ComponentId:{description:"The unique identifier for a component, used for both definitions and references within the same surface.",type:"string"},TextItem:{additionalProperties:!1,description:"The value of the text field. This can be a literal string or a reference to a value in the data model ('path', e.g. '/user/name').",properties:{literalString:{type:"string"},path:{type:"string"}},type:"object"},UrlItem:{additionalProperties:!1,description:"The URL of the audio to be played. This can be a literal string ('literal') or a reference to a value in the data model ('path', e.g. '/song/url').",properties:{literalString:{type:"string"},path:{type:"string"}},type:"object"},AltTextItem:{additionalProperties:!1,description:"The alt text for the image. This can be a literal string ('literal') or a reference to a value in the data model ('path', e.g. '/thumbnail/altText').",properties:{literalString:{type:"string"},path:{type:"string"}},type:"object"},NameItem:{additionalProperties:!1,description:"The name of the icon to display. This can be a literal string or a reference to a value in the data model ('path', e.g. '/form/submit').",properties:{literalString:{enum:["accountCircle","add","arrowBack","arrowForward","attachFile","calendarToday","call","camera","check","close","delete","download","edit","event","error","favorite","favoriteOff","folder","help","home","info","locationOn","lock","lockOpen","mail","menu","moreVert","moreHoriz","notificationsOff","notifications","payment","person","phone","photo","print","refresh","search","send","settings","share","shoppingCart","star","starHalf","starOff","upload","visibility","visibilityOff","warning"],type:"string"},path:{type:"string"}},type:"object"},DescriptionItem:{additionalProperties:!1,description:"A description of the audio, such as a title or summary. This can be a literal string or a reference to a value in the data model ('path', e.g. '/song/title').",properties:{literalString:{type:"string"},path:{type:"string"}},type:"object"},ChildrenItem:{additionalProperties:!1,description:"Defines the children. Use 'explicitList' for a fixed set of children, or 'template' to generate children from a data list.",properties:{explicitList:{items:{type:"string"},type:"array"},template:{$ref:"#/$defs/TemplateItem",description:"A template for generating a dynamic list of children from a data model list. `componentId` is the component to use as a template, and `dataBinding` is the path to the map of components in the data model. Values in the map will define the list of children."}},type:"object"},TemplateItem:{additionalProperties:!1,description:"A template for generating a dynamic list of children from a data model list. `componentId` is the component to use as a template, and `dataBinding` is the path to the map of components in the data model. Values in the map will define the list of children.",properties:{componentId:{type:"string"},dataBinding:{type:"string"}},required:["componentId","dataBinding"],type:"object"},TabItemItem:{additionalProperties:!1,properties:{child:{type:"string"},title:{$ref:"#/$defs/TitleItem"}},required:["title","child"],type:"object"},TitleItem:{additionalProperties:!1,description:"The tab title. Defines the value as either a literal value or a path to data model value (e.g. '/options/title').",properties:{literalString:{type:"string"},path:{type:"string"}},type:"object"},ActionItem:{additionalProperties:!1,description:"The client-side action to be dispatched when the button is clicked. It includes the action's name and an optional context payload.",properties:{context:{items:{$ref:"#/$defs/ContextItem"},type:"array"},name:{type:"string"}},required:["name"],type:"object"},ContextItem:{additionalProperties:!1,properties:{key:{type:"string"},value:{$ref:"#/$defs/ValueItem",description:"Defines the value to be included in the context as either a literal value or a path to a data model value (e.g. '/user/name')."}},required:["key","value"],type:"object"},ValueItem:{additionalProperties:!1,description:"The current value of the slider. This can be a literal number ('literalNumber') or a reference to a value in the data model ('path', e.g. '/restaurant/cost').",properties:{literalNumber:{type:"number"},path:{type:"string"}},type:"object"},LabelItem:{additionalProperties:!1,description:"The label for the slider. This can be a literal string or a reference to a value in the data model ('path').",properties:{literalString:{type:"string"},path:{type:"string"}},type:"object"},OptionItem:{additionalProperties:!1,properties:{label:{$ref:"#/$defs/LabelItem",description:"The text to display for this option. This can be a literal string or a reference to a value in the data model (e.g. '/option/label')."},value:{description:"The value to be associated with this option when selected.",type:"string"}},required:["label","value"],type:"object"},SelectionItem:{additionalProperties:!1,description:"The currently selected values for the component. This can be a literal array of strings or a path to an array in the data model('path', e.g. '/hotel/options').",properties:{literalArray:{items:{type:"string"},type:"array"},path:{type:"string"}},type:"object"}},V09_CHILD_REF_OPTIONS={childRefNames:new Set(["ComponentId","Child","ChildComponentId"]),childListRefNames:new Set(["ChildList","TemplateChildList","ChildrenItem","TemplateItem"])},V09_STANDARD_DEFS={ComponentId:{type:"string",description:"The unique identifier for a component, used for both definitions and references within the same surface."},AccessibilityAttributes:{type:"object",description:"Attributes to enhance accessibility when using assistive technologies like screen readers.",properties:{label:{$ref:"#/$defs/DynamicString",description:"A short string, typically 1 to 3 words, used by assistive technologies to convey the purpose or intent of an element. For example, an input field might have an accessible label of 'User ID' or a button might be labeled 'Submit'."},description:{$ref:"#/$defs/DynamicString",description:"Additional information provided by assistive technologies about an element such as instructions, format requirements, or result of an action. For example, a mute button might have a label of 'Mute' and a description of 'Silences notifications about this conversation'."}}},ComponentCommon:{type:"object",properties:{id:{$ref:"#/$defs/ComponentId"},accessibility:{$ref:"#/$defs/AccessibilityAttributes"}},required:["id"]},ChildList:{oneOf:[{type:"array",items:{$ref:"#/$defs/ComponentId"},description:"A static list of child component IDs."},{type:"object",description:"A template for generating a dynamic list of children from a data model list. The `componentId` is the component to use as a template.",properties:{componentId:{$ref:"#/$defs/ComponentId"},path:{type:"string",description:"The path to the list of component property objects in the data model."}},required:["componentId","path"],additionalProperties:!1}]},DataBinding:{type:"object",properties:{path:{type:"string",description:"A JSON Pointer path to a value in the data model."}},required:["path"],additionalProperties:!1},DynamicValue:{description:"A value that can be a literal, a path, or a function call returning any type.",oneOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"array"},{$ref:"#/$defs/DataBinding"},{$ref:"#/$defs/FunctionCall"}]},DynamicString:{description:"Represents a string",oneOf:[{type:"string"},{$ref:"#/$defs/DataBinding"},{allOf:[{$ref:"#/$defs/FunctionCall"},{properties:{returnType:{const:"string"}}}]}]},DynamicNumber:{description:"Represents a value that can be either a literal number, a path to a number in the data model, or a function call returning a number.",oneOf:[{type:"number"},{$ref:"#/$defs/DataBinding"},{allOf:[{$ref:"#/$defs/FunctionCall"},{properties:{returnType:{const:"number"}}}]}]},DynamicBoolean:{description:"A boolean value that can be a literal, a path, or a function call returning a boolean.",oneOf:[{type:"boolean"},{$ref:"#/$defs/DataBinding"},{allOf:[{$ref:"#/$defs/FunctionCall"},{properties:{returnType:{const:"boolean"}}}]}]},DynamicStringList:{description:"Represents a value that can be either a literal array of strings, a path to a string array in the data model, or a function call returning a string array.",oneOf:[{type:"array",items:{type:"string"}},{$ref:"#/$defs/DataBinding"},{allOf:[{$ref:"#/$defs/FunctionCall"},{properties:{returnType:{const:"array"}}}]}]},FunctionCall:{type:"object",description:"Invokes a named function on the client.",properties:{call:{type:"string",description:"The name of the function to call."},args:{type:"object",description:"Arguments passed to the function.",additionalProperties:{anyOf:[{$ref:"#/$defs/DynamicValue"},{type:"object",description:"A literal object argument (e.g. configuration)."}]}},returnType:{type:"string",description:"The expected return type of the function call.",enum:["string","number","boolean","array","object","any","void"],default:"boolean"}},required:["call"],oneOf:[{$ref:"catalog.json#/$defs/anyFunction"}]},CheckRule:{type:"object",description:"A single validation rule applied to an input component.",properties:{condition:{$ref:"#/$defs/DynamicBoolean"},message:{type:"string",description:"The error message to display if the check fails."}},required:["condition","message"],additionalProperties:!1},Checkable:{description:"Properties for components that support client-side checks.",type:"object",properties:{checks:{type:"array",description:"A list of checks to perform. These are function calls that must return a boolean indicating validity.",items:{$ref:"#/$defs/CheckRule"}}}},Action:{description:"Defines an interaction handler that can either trigger a server-side event or execute a local client-side function.",oneOf:[{type:"object",description:"Triggers a server-side event.",properties:{event:{type:"object",description:"The event to dispatch to the server.",properties:{name:{type:"string",description:"The name of the action to be dispatched to the server."},context:{type:"object",description:"A JSON object containing the key-value pairs for the action context. Values can be literals or paths. Use literal values unless the value must be dynamically bound to the data model. Do NOT use paths for static IDs.",additionalProperties:{$ref:"#/$defs/DynamicValue"}}},required:["name"],additionalProperties:!1}},required:["event"],additionalProperties:!1},{type:"object",description:"Executes a local client-side function.",properties:{functionCall:{$ref:"#/$defs/FunctionCall"}},required:["functionCall"],additionalProperties:!1}]}},V10_STANDARD_DEFS={ComponentId:{type:"string",description:"The unique identifier for a component, used for both definitions and references within the same surface."},CallId:{type:"string",description:"The unique identifier for a function call."},AccessibilityAttributes:{type:"object",description:"Attributes to enhance accessibility when using assistive technologies like screen readers or model understanding.",properties:{label:{$ref:"#/$defs/DynamicString",description:"A short string, typically 1 to 3 words, used by assistive technologies to convey the purpose or intent of an element. For example, an input field might have an accessible label of 'User ID' or a button might be labeled 'Submit'."},description:{$ref:"#/$defs/DynamicString",description:"Additional information provided by assistive technologies about an element such as instructions, format requirements, or result of an action. For example, a mute button might have a label of 'Mute' and a description of 'Silences notifications about this conversation'."},live:{type:"string",enum:["off","polite","assertive"],default:"off",description:"Controls screen reader announcements for dynamic updates (WAI-ARIA aria-live). 'polite' waits for user pause; 'assertive' interrupts immediately for alerts."},hidden:{$ref:"#/$defs/DynamicBoolean",description:"Hides the element and its children from assistive technologies when true. Default is false."}},additionalProperties:!1},Extensions:{type:"object",description:"Optional extension metadata. Keys MUST be Unicode identifiers (UAX #31). Keys starting with 'a2ui_' are reserved for official extensions.",patternProperties:{"^[\\p{XID_Start}_][\\p{XID_Continue}]*$":{}},additionalProperties:!1},ComponentCommon:{type:"object",properties:{id:{$ref:"#/$defs/ComponentId"},catalogId:{type:"string",description:"The catalog ID for this component, overriding any surface-level default catalogId."},accessibility:{$ref:"#/$defs/AccessibilityAttributes"},metadata:{type:"object",description:"Optional component-level metadata for vendor extensions.",properties:{extensions:{$ref:"#/$defs/Extensions"}},additionalProperties:!1}},required:["id"]},Child:{$ref:"#/$defs/ComponentId",description:"A reference to a single child component ID."},ChildList:{oneOf:[{type:"array",items:{$ref:"#/$defs/ComponentId"},description:"A static list of child component IDs."},{type:"object",description:"A template for generating a dynamic list of children from a data model list. The `componentId` is the component to use as a template.",properties:{componentId:{$ref:"#/$defs/ComponentId"},path:{type:"string",description:"The path to the list of component property objects in the data model."}},required:["componentId","path"],additionalProperties:!1}]},DataBinding:{type:"object",properties:{path:{type:"string",description:"A JSON Pointer path to a value in the data model."}},required:["path"],additionalProperties:!1},DynamicValue:{description:"A value that can be a literal, a path, or a function call returning any type.",oneOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"array"},{type:"object",not:{anyOf:[{required:["path"]},{required:["call"]}]}},{$ref:"#/$defs/DataBinding"},{$ref:"#/$defs/FunctionCall"}]},DynamicString:{description:"Represents a string",oneOf:[{type:"string"},{$ref:"#/$defs/DataBinding"},{$ref:"#/$defs/FunctionCall"}]},DynamicNumber:{description:"Represents a value that can be either a literal number, a path to a number in the data model, or a function call returning a number.",oneOf:[{type:"number"},{$ref:"#/$defs/DataBinding"},{$ref:"#/$defs/FunctionCall"}]},DynamicBoolean:{description:"A boolean value that can be a literal, a path, or a function call returning a boolean.",oneOf:[{type:"boolean"},{$ref:"#/$defs/DataBinding"},{$ref:"#/$defs/FunctionCall"}]},DynamicStringList:{description:"Represents a value that can be either a literal array of strings, a path to a string array in the data model, or a function call returning a string array.",oneOf:[{type:"array",items:{type:"string"}},{$ref:"#/$defs/DataBinding"},{$ref:"#/$defs/FunctionCall"}]},FunctionCommon:{type:"object",description:"Baseline envelope properties common to all function calls. Function-specific argument schemas ('args') are defined individually by each function in the active catalog.",properties:{call:{type:"string",description:"The name of the function to call."},catalogId:{type:"string",description:"The catalog ID for this function, overriding any surface-level default catalogId."}},required:["call"]},IndexSystemFunction:{type:"object",description:"Returns the 0-based index of the current item when rendering a dynamic list from a template. This function MUST ONLY be available when evaluating template items within a list context.",returnType:"number",properties:{call:{const:"@index"},args:{type:"object",properties:{offset:{$ref:"#/$defs/DynamicNumber",description:"Optional. An offset to add to the 0-based index (e.g., 1 for 1-based indexing). Defaults to 0.",default:0}},unevaluatedProperties:!1}},required:["call"],unevaluatedProperties:!1},FunctionCall:{type:"object",description:"Invokes a named function, combining common function properties with the catalog function definition.",allOf:[{$ref:"#/$defs/FunctionCommon"},{oneOf:[{$ref:"catalog.json#/$defs/anyFunction"},{$ref:"#/$defs/IndexSystemFunction"}]}],unevaluatedProperties:!1},CheckRule:{type:"object",description:"A single validation check rule applied to an input component. The condition function or path evaluates to a structured validation result object.",properties:{condition:{oneOf:[{$ref:"#/$defs/DataBinding"},{$ref:"#/$defs/FunctionCall"}],description:"Path or function call evaluating to a structured validation result object."},message:{type:"string",description:"Optional fallback error message."}},required:["condition"],additionalProperties:!1},Checkable:{description:"Properties for components that support renderer-side checks.",type:"object",properties:{checks:{type:"array",description:"A list of checks to perform. These are function calls that must return a boolean indicating validity.",items:{$ref:"#/$defs/CheckRule"}}}},Action:{description:"Defines an interaction handler that can either trigger an agent-side event or execute a local renderer-side function.",oneOf:[{type:"object",description:"Triggers an agent-side event.",properties:{event:{type:"object",description:"The event to dispatch to the agent.",properties:{name:{type:"string",description:"The name of the action to be dispatched to the agent."},userMessage:{$ref:"#/$defs/DynamicString",description:"An optional human-readable message describing the action performed by the user, to present in conversation history or user feedback."},context:{type:"object",description:"A JSON object containing the key-value pairs for the action context. Values can be literals or paths. Use literal values unless the value must be dynamically bound to the data model. Do NOT use paths for static IDs.",additionalProperties:{$ref:"#/$defs/DynamicValue"}}},required:["name"],additionalProperties:!1}},required:["event"],additionalProperties:!1},{type:"object",description:"Executes a renderer or agent-side function.",properties:{functionCall:{$ref:"#/$defs/FunctionCall"}},required:["functionCall"],additionalProperties:!1}]},Surface:{title:"Surface Container Component",description:"The reserved canonical container component representing an A2UI surface. The Surface component is immutable and always has 'child': 'root'.",type:"object",allowedParents:[],properties:{component:{const:"Surface"},child:{const:"root"}},additionalProperties:!1},FunctionResponse:{type:"object",description:"The return response matching a callAgentFunction or callRendererFunction invocation.",properties:{functionCallId:{$ref:"#/$defs/CallId",description:"The unique ID matching the initiating function call."},value:{description:"The return value of the function."},error:{type:"object",description:"An error object indicating failure of the function execution.",properties:{code:{type:"string"},message:{type:"string"}},required:["code","message"],additionalProperties:!1}},required:["functionCallId"],oneOf:[{required:["value"]},{required:["error"]}],additionalProperties:!1}};const STANDARD_DEFS_BY_VERSION={"0.8":V08_STANDARD_DEFS,"0.9":V09_STANDARD_DEFS,"0.9.1":V09_STANDARD_DEFS,"1.0":V10_STANDARD_DEFS};function getStandardDefsForCatalog(Au,lo){if(lo?.standardDefs)return lo.standardDefs;if(lo?.protocolVersion){const $u=toCanonicalVersion(lo.protocolVersion)??normalizeVersionString(lo.protocolVersion);if($u in STANDARD_DEFS_BY_VERSION)return STANDARD_DEFS_BY_VERSION[$u]}return V09_STANDARD_DEFS}function transformRefDescriptionNode(Au){if(typeof Au.description!="string"||!Au.description.startsWith("REF:"))return!1;const lo=Au.description.substring(4),$u=lo.indexOf("|"),Ru=$u===-1?lo:lo.substring(0,$u),Iu=$u===-1?"":lo.substring($u+1),Pu=Au.default;for(const Ou of Object.keys(Au))delete Au[Ou];return Au.$ref=Ru.startsWith("#")?Ru:`#/$defs/${Ru.split("/").pop()}`,Pu!==void 0&&(Au.default=Pu),Iu&&(Au.description=Iu),!0}function cleanSchemaProperties(Au){Array.isArray(Au.anyOf)&&(Au.oneOf=Au.anyOf,delete Au.anyOf),Au.additionalProperties&&typeof Au.additionalProperties=="object"&&Object.keys(Au.additionalProperties).length===0&&(Au.additionalProperties=!0),Au.unevaluatedProperties&&typeof Au.unevaluatedProperties=="object"&&Object.keys(Au.unevaluatedProperties).length===0&&(Au.unevaluatedProperties=!0),"$schema"in Au&&delete Au.$schema}function cleanSchemaNode(Au,lo=new Set){if(typeof Au!="object"||Au===null||lo.has(Au))return;if(lo.add(Au),Array.isArray(Au)){for(const Ru of Au)cleanSchemaNode(Ru,lo);return}const $u=Au;if(!transformRefDescriptionNode($u)){cleanSchemaProperties($u);for(const Ru of Object.keys($u))cleanSchemaNode($u[Ru],lo)}}function processTheme(Au,lo){if(!Au.themeSchema)return;const $u=zodToJsonSchema(Au.themeSchema,{target:"jsonSchema2019-09",$refStrategy:"none"});cleanSchemaNode($u),$u.definitions&&typeof $u.definitions=="object"?(Object.assign(lo,$u.definitions),delete $u.definitions):$u.$defs&&typeof $u.$defs=="object"&&(Object.assign(lo,$u.$defs),delete $u.$defs);const Ru=Au.id.includes("v0_8")||Au.id.includes("v0.8"),Iu={type:"object",properties:$u.properties||{},...Array.isArray($u.required)&&$u.required.length>0?{required:$u.required}:{},...Ru?{}:{additionalProperties:$u.additionalProperties!==void 0?$u.additionalProperties:!0}};lo.theme=Iu}function extractZodComponentSchema(Au,lo){if(!Au.schema||typeof Au.schema!="object"||!("safeParse"in Au.schema))return{props:{},reqList:[],additionalProps:void 0};const $u=zodToJsonSchema(Au.schema,{target:"jsonSchema2019-09",$refStrategy:"none"});cleanSchemaNode($u),$u.definitions&&typeof $u.definitions=="object"?Object.assign(lo,$u.definitions):$u.$defs&&typeof $u.$defs=="object"&&Object.assign(lo,$u.$defs);const Ru=$u.properties||{},Iu=Array.isArray($u.required)?$u.required.filter(Mu=>Mu!=="component"&&Mu!=="id"):[],Pu=$u.unevaluatedProperties??$u.additionalProperties;return{props:Ru,reqList:Iu,additionalProps:typeof Pu=="boolean"||typeof Pu=="object"&&Pu!==null?Pu:void 0}}function processSingleComponent(Au,lo,$u,Ru,Iu){const{props:Pu,reqList:Ou,additionalProps:Mu}=extractZodComponentSchema(lo,$u),{component:Du,id:Lu,...Bu}=Pu,ju={id:{$ref:"#/$defs/ComponentId"},...Bu,component:{const:Au}},Fu=["id",...Ou,"component"];let zu;return Iu?.componentEnvelopeRef?zu={allOf:[{$ref:Iu.componentEnvelopeRef},{type:"object",properties:ju,required:Fu}],unevaluatedProperties:Mu!==void 0?Mu:!1}:zu={type:"object",properties:ju,required:Fu,unevaluatedProperties:Mu!==void 0?Mu:!1},lo.allowedParents&&lo.allowedParents.length>0&&(zu.allowedParents=lo.allowedParents),lo.allowedChildren&&lo.allowedChildren.length>0&&(zu.allowedChildren=lo.allowedChildren),zu}function processComponents(Au,lo,$u,Ru){if(Au.components.size===0){lo.components={};return}const Iu={};for(const[Pu,Ou]of Au.components.entries())Iu[Pu]=processSingleComponent(Pu,Ou,$u,Au,Ru);lo.components=Iu,$u.anyComponent={oneOf:Array.from(Au.components.keys()).map(Pu=>({$ref:`#/components/${Pu}`})),discriminator:{propertyName:"component"}}}function processSingleFunction(Au,lo,$u){let Ru;if(lo.schema&&typeof lo.schema=="object"&&"safeParse"in lo.schema){const Iu=zodToJsonSchema(lo.schema,{target:"jsonSchema2019-09",$refStrategy:"none"});cleanSchemaNode(Iu),Iu.definitions&&typeof Iu.definitions=="object"?(Object.assign($u,Iu.definitions),delete Iu.definitions):Iu.$defs&&typeof Iu.$defs=="object"&&(Object.assign($u,Iu.$defs),delete Iu.$defs),Ru=Iu}else Ru={type:"object",properties:{}};if(lo.description&&Ru.description===void 0&&(Ru.description=lo.description),Ru.type==="object"){const Iu=Ru.unevaluatedProperties??Ru.additionalProperties,Pu=typeof Iu=="boolean"||typeof Iu=="object"&&Iu!==null?Iu:void 0;Ru.additionalProperties!==void 0&&delete Ru.additionalProperties,Ru.unevaluatedProperties=Pu!==void 0?Pu:!1}return Ru}function processFunctions(Au,lo,$u){if(Au.functions.size===0)return;const Ru={};for(const[Iu,Pu]of Au.functions.entries())Ru[Iu]=processSingleFunction(Iu,Pu,$u);lo.functions=Ru,$u.anyFunction={oneOf:Array.from(Au.functions.keys()).map(Iu=>({$ref:`#/functions/${Iu}`}))}}function collectReferencedDefs(Au,lo,$u=new Set){if(!(typeof Au!="object"||Au===null)&&!$u.has(Au)){if($u.add(Au),typeof Au.$ref=="string"){const Ru=Au.$ref;Ru.startsWith("#/$defs/")&&lo.add(Ru.substring(8))}if(Array.isArray(Au))for(const Ru of Au)collectReferencedDefs(Ru,lo,$u);else for(const Ru of Object.values(Au))collectReferencedDefs(Ru,lo,$u)}}function generateCatalogSchema(Au,lo){const $u={$schema:"https://json-schema.org/draft/2020-12/schema",catalogId:Au.id};Au.instructions&&($u.instructions=Au.instructions);const Ru={};processTheme(Au,Ru),processComponents(Au,$u,Ru,lo),processFunctions(Au,$u,Ru);const Iu=getStandardDefsForCatalog(Au,lo);let Pu;do{Pu=Object.keys(Ru).length;const Ou=new Set;collectReferencedDefs($u,Ou),collectReferencedDefs(Ru,Ou),(Ou.has("DynamicString")||Ou.has("DynamicNumber")||Ou.has("DynamicBoolean")||Ou.has("DynamicValue"))&&(Ou.add("DataBinding"),Ou.add("FunctionCall"));for(const Mu of Ou)Mu in Iu&&!(Mu in Ru)&&(Ru[Mu]=Iu[Mu])}while(Object.keys(Ru).length>Pu);return Object.keys(Ru).length>0&&($u.$defs=Ru),$u}function extractRefDefName(Au){if(!Au)return"";const lo=Au.lastIndexOf("#");return(lo!==-1?Au.slice(lo+1):Au).split("/").filter(Boolean).pop()??""}function unwrapNextZodLayer(Au,lo){if(!Au?._def)return null;if(lo){if(lo.has(Au))return null;lo.add(Au)}switch(Au._def.typeName){case"ZodOptional":case"ZodNullable":case"ZodDefault":case"ZodReadonly":return Au._def.innerType;case"ZodBranded":return Au._def.type;case"ZodEffects":return Au._def.schema;case"ZodLazy":return Au._def.getter();default:return null}}function getDescriptions(Au){const lo=[],$u=new Set;let Ru=Au;for(;Ru;){Ru.description&&lo.push(Ru.description),Ru._def?.description&&lo.push(Ru._def.description);const Iu=unwrapNextZodLayer(Ru,$u);if(!Iu)break;Ru=Iu}return lo}function unwrapZodType(Au){const lo=new Set;let $u=Au;for(;$u;){const Ru=unwrapNextZodLayer($u,lo);if(!Ru)break;$u=Ru}return $u}function checkDirectJsonRef(Au,lo){if(!Au)return null;const $u=extractRefDefName(Au),Ru=lo.childListRefNames,Iu=lo.childRefNames;return Ru.has($u)?{isChild:!1,isChildList:!0}:Iu.has($u)?{isChild:!0,isChildList:!1}:null}function checkCombinerList(Au,lo){let $u=!1;for(const Ru of Au){if(typeof Ru!="object"||Ru===null)continue;const Iu=checkJsonSchemaRef(Ru,lo);if(Iu.isChildList)return{isChild:!1,isChildList:!0};Iu.isChild&&($u=!0)}return $u?{isChild:!0,isChildList:!1}:null}function checkCombinerRefs(Au,lo){let $u=!1;for(const Ru of["oneOf","anyOf","allOf"]){const Iu=Au[Ru];if(!Array.isArray(Iu))continue;const Pu=checkCombinerList(Iu,lo);if(Pu?.isChildList)return Pu;Pu?.isChild&&($u=!0)}return $u?{isChild:!0,isChildList:!1}:null}function checkJsonSchemaRef(Au,lo){const $u=typeof Au.$ref=="string"?Au.$ref:"",Ru=checkDirectJsonRef($u,lo);if(Ru)return Ru;if(Au.type==="array"&&Au.items){const Pu=checkJsonSchemaRef(Au.items,lo);if(Pu.isChild||Pu.isChildList)return{isChild:!1,isChildList:!0}}const Iu=checkCombinerRefs(Au,lo);return Iu||(Au.type==="object"&&Au.properties&&("componentId"in Au.properties&&("path"in Au.properties||"dataBinding"in Au.properties)||"explicitList"in Au.properties||"template"in Au.properties)?{isChild:!1,isChildList:!0}:{isChild:!1,isChildList:!1})}function isTemplateShape(Au){if(Au?._def?.typeName==="ZodObject"&&typeof Au._def.shape=="function"){const lo=Au._def.shape();return!!(lo.componentId&&(lo.path||lo.dataBinding)||lo.explicitList||lo.template)}return!1}function isArrayOfChild(Au,lo){if(Au?._def?.typeName==="ZodArray"){const $u=unwrapZodType(Au._def.type);return analyzeChildRefSchema($u,lo).isChild}return!1}function analyzeUnionOptions(Au,lo){let $u=!1,Ru=!1,Iu=!1;for(const Pu of Au){const Ou=unwrapZodType(Pu);isTemplateShape(Ou)&&($u=!0),isArrayOfChild(Ou,lo)&&(Ru=!0);const Mu=analyzeChildRefSchema(Ou,lo);if(Mu.isChildList)return{isChild:!1,isChildList:!0};Mu.isChild&&(Iu=!0)}return $u||Ru?{isChild:!1,isChildList:!0}:Iu?{isChild:!0,isChildList:!1}:{isChild:!1,isChildList:!1}}function isChildListDescription(Au,lo){if(!Au)return!1;if(Au.startsWith("REF:")){const Iu=extractRefDefName(Au.substring(4).split("|")[0]);if(lo.has(Iu))return!0}const $u=extractRefDefName(Au.split("|")[0]);if($u&&lo.has($u))return!0;const Ru=Au.trim();return!!lo.has(Ru)}function isChildDescription(Au,lo){if(!Au)return!1;if(Au.startsWith("REF:")){const Iu=extractRefDefName(Au.substring(4).split("|")[0]);if(lo.has(Iu))return!0}const $u=extractRefDefName(Au.split("|")[0]);if($u&&lo.has($u))return!0;const Ru=Au.trim();return!!lo.has(Ru)}function checkDescriptionChildRef(Au,lo){const $u=lo.childListRefNames,Ru=lo.childRefNames;for(const Iu of Au){if(isChildListDescription(Iu,$u))return{isChild:!1,isChildList:!0};if(isChildDescription(Iu,Ru))return{isChild:!0,isChildList:!1}}return null}function analyzeZodArray(Au,lo){const $u=analyzeChildRefSchema(Au,lo);return $u.isChild||$u.isChildList?{isChild:!1,isChildList:!0}:{isChild:!1,isChildList:!1}}function analyzeChildRefSchema(Au,lo){if(!Au||typeof Au!="object")return{isChild:!1,isChildList:!1};const $u=childRefKindOf(Au);if($u==="component-id")return{isChild:!0,isChildList:!1};if($u==="child-list")return{isChild:!1,isChildList:!0};const Ru=checkDescriptionChildRef(getDescriptions(Au),lo);if(Ru)return Ru;const Iu=unwrapZodType(Au);if(!Iu?._def)return checkJsonSchemaRef(Au,lo);const Pu=childRefKindOf(Iu);if(Pu==="component-id")return{isChild:!0,isChildList:!1};if(Pu==="child-list")return{isChild:!1,isChildList:!0};const Ou=Iu._def.typeName;if(Ou==="ZodArray"){const Mu=unwrapZodType(Iu._def.type);return analyzeZodArray(Mu,lo)}if(Ou==="ZodUnion"){const Mu=Iu._def.options??[];return analyzeUnionOptions(Mu,lo)}if(Ou==="ZodObject"&&typeof Iu._def.shape=="function"){const Mu=Iu._def.shape();if(Mu.componentId&&(Mu.path||Mu.dataBinding)||Mu.explicitList||Mu.template)return{isChild:!1,isChildList:!0}}return{isChild:!1,isChildList:!1}}function addNestedRef(Au,lo,$u){const Ru=Au.nestedRefs[lo];if(Ru){Ru.add($u);return}Au.nestedRefs[lo]=new Set([$u])}function inspectShapeField(Au,lo,$u,Ru){const Iu=analyzeChildRefSchema(lo,Ru);if(Iu.isChildList){$u.listRefs.add(Au);return}if(Iu.isChild){$u.singleRefs.add(Au);return}const Pu=unwrapZodType(lo);if(Pu?._def?.typeName!=="ZodArray")return;const Ou=unwrapZodType(Pu._def.type);if(Ou?._def?.typeName!=="ZodObject"||typeof Ou._def.shape!="function")return;const Mu=Ou._def.shape();for(const[Du,Lu]of Object.entries(Mu)){const Bu=analyzeChildRefSchema(Lu,Ru);(Bu.isChild||Bu.isChildList)&&($u.listRefs.add(Au),addNestedRef($u,Au,Du))}}function rawArrayItemProperties(Au){if(typeof Au!="object"||Au===null)return null;const lo=Au;if(lo.type!=="array"&&!("items"in lo))return null;const $u=lo.items;if(typeof $u!="object"||$u===null)return null;const Ru=$u.properties;return typeof Ru!="object"||Ru===null?null:Ru}function inspectRawProperties(Au,lo,$u){for(const[Ru,Iu]of Object.entries(Au)){const Pu=analyzeChildRefSchema(Iu,$u);if(Pu.isChildList){lo.listRefs.add(Ru);continue}if(Pu.isChild){lo.singleRefs.add(Ru);continue}const Ou=rawArrayItemProperties(Iu);if(Ou)for(const[Mu,Du]of Object.entries(Ou)){const Lu=analyzeChildRefSchema(Du,$u);(Lu.isChild||Lu.isChildList)&&(lo.listRefs.add(Ru),addNestedRef(lo,Ru,Mu))}}}function inspectComponentSchema(Au,lo,$u){if(!Au)return;const Ru=unwrapZodType(Au);if(Ru?._def?.typeName==="ZodObject"&&typeof Ru._def.shape=="function"){const Iu=Ru._def.shape();for(const[Pu,Ou]of Object.entries(Iu))inspectShapeField(Pu,Ou,lo,$u);return}if(typeof Au=="object"&&Au!==null&&"properties"in Au){const Iu=Au.properties;typeof Iu=="object"&&Iu!==null&&inspectRawProperties(Iu,lo,$u)}}function buildComponentRefMap(Au,lo){const $u={},Ru=typeof Au?.components?.values=="function"?Array.from(Au.components.values()):Array.isArray(Au)?Au:Array.from(Au.values());for(const Iu of Ru){const Pu={singleRefs:new Set,listRefs:new Set,nestedRefs:{}};inspectComponentSchema(Iu.schema,Pu,lo),$u[Iu.name]={singleRefs:Pu.singleRefs,listRefs:Pu.listRefs,nestedRefs:Pu.nestedRefs}}return $u}function createFunctionImplementation(Au,lo){return{name:Au.name,returnType:Au.returnType,schema:Au.schema,allowedCallers:Au.allowedCallers,requiresUserActivation:Au.requiresUserActivation,description:Au.description,execute:lo}}class Catalog{get catalogSchema(){return this.cachedCatalogSchema||(this.cachedCatalogSchema=generateCatalogSchema(this)),this.cachedCatalogSchema}get componentRefMap(){return this._componentRefMap||(this._componentRefMap=buildComponentRefMap(this,V09_CHILD_REF_OPTIONS)),this._componentRefMap}constructor(lo,$u,Ru=[],Iu=[],Pu,Ou){if(!$u)throw new A2uiCatalogError("protocolVersion must be provided.");this.id=lo,this.protocolVersion=$u;const Mu=new Map;for(const Lu of Ru)Mu.set(Lu.name,Lu);this.components=Mu;const Du=new Map;for(const Lu of Iu)Du.set(Lu.name,Lu);this.functions=Du,this.themeSchema=Pu,this.instructions=Ou,this.invoker=(Lu,Bu,ju,Fu)=>{const zu=this.functions.get(Lu);if(!zu)throw new A2uiExpressionError(`Function not found in catalog '${this.id}': ${Lu}`,Lu);const Uu=zu.execute;if(typeof Uu!="function")throw new A2uiExpressionError(`Function '${Lu}' in catalog '${this.id}' is schema-only and has no implementation.`,Lu);try{const Hu=zu.schema.parse(Bu);return Uu.call(zu,Hu,ju,Fu)}catch(Hu){throw Hu?.name==="ZodError"||Hu instanceof ZodError?new A2uiExpressionError(`Validation failed for function '${Lu}': ${Hu.message}`,Lu,Hu.errors??Hu.issues):Hu}}}static fromSchema(lo,$u){return loadCatalogFromSchema(lo,$u)}}class EventEmitter{constructor(){this.listeners=new Set}subscribe(lo){return this.listeners.add(lo),{unsubscribe:()=>this.listeners.delete(lo)}}async emit(lo){for(const $u of this.listeners)try{await $u(lo)}catch(Ru){console.error("EventEmitter error:",Ru)}}dispose(){this.listeners.clear()}}var i=Symbol.for("preact-signals");function t(){if(v>1)v--;else{var Au,lo=!1;for((function(){var Iu=c;for(c=void 0;Iu!==void 0;){var Pu=Iu.S;if(Pu.v===Iu.v)for(var Ou=Pu.t;Ou!==void 0;Ou=Ou.x)Ou.i===Iu.i&&(Ou.i=Pu.i);Iu=Iu.o}})();h!==void 0;){var $u=h;for(h=void 0,s++;$u!==void 0;){var Ru=$u.u;if($u.u=void 0,$u.f&=-3,!(8&$u.f)&&w($u))try{$u.c()}catch(Iu){lo||(Au=Iu,lo=!0)}$u=Ru}}if(s=0,v--,lo)throw Au}}function n(Au){if(v>0)return Au();e=++u,v++;try{return Au()}finally{t()}}var r,o=void 0;function f(Au){var lo=o,$u=r;o=void 0,r=void 0;try{return Au()}finally{o=lo,r=$u}}var h=void 0,v=0,s=0,u=0,e=0,c=void 0,d=0;function a(Au){if(o!==void 0){var lo=Au.n;if(lo===void 0||lo.t!==o)return lo={i:0,S:Au,p:o.s,n:void 0,t:o,e:void 0,x:void 0,r:lo},o.s!==void 0&&(o.s.n=lo),o.s=lo,Au.n=lo,32&o.f&&Au.S(lo),lo;if(lo.i===-1)return lo.i=0,lo.n!==void 0&&(lo.n.p=lo.p,lo.p!==void 0&&(lo.p.n=lo.n),lo.p=o.s,lo.n=void 0,o.s.n=lo,o.s=lo),lo}}function l(Au,lo){this.v=Au,this.i=0,this.n=void 0,this.t=void 0,this.l=0,this.W=lo?.watched,this.Z=lo?.unwatched,this.name=lo?.name}l.prototype.brand=i;l.prototype.h=function(){return!0};l.prototype.S=function(Au){var lo=this,$u=this.t;$u!==Au&&Au.e===void 0&&(Au.x=$u,this.t=Au,$u!==void 0?$u.e=Au:f(function(){var Ru;(Ru=lo.W)==null||Ru.call(lo)}))};l.prototype.U=function(Au){var lo=this;if(this.t!==void 0){var $u=Au.e,Ru=Au.x;$u!==void 0&&($u.x=Ru,Au.e=void 0),Ru!==void 0&&(Ru.e=$u,Au.x=void 0),Au===this.t&&(this.t=Ru,Ru===void 0&&f(function(){var Iu;(Iu=lo.Z)==null||Iu.call(lo)}))}};l.prototype.subscribe=function(Au){var lo=this;return j(function(){var $u=lo.value;f(function(){return Au($u)})},{name:"sub"})};l.prototype.valueOf=function(){return this.value};l.prototype.toString=function(){return this.value+""};l.prototype.toJSON=function(){return this.value};l.prototype.peek=function(){var Au=this;return f(function(){return Au.value})};Object.defineProperty(l.prototype,"value",{get:function(){var Au=a(this);return Au!==void 0&&(Au.i=this.i),this.v},set:function(Au){if(Au!==this.v){if(s>100)throw new Error("Cycle detected");(function($u){v!==0&&s===0&&$u.l!==e&&($u.l=e,c={S:$u,v:$u.v,i:$u.i,o:c})})(this),this.v=Au,this.i++,d++,v++;try{for(var lo=this.t;lo!==void 0;lo=lo.x)lo.t.N()}finally{t()}}}});function y(Au,lo){return new l(Au,lo)}function w(Au){for(var lo=Au.s;lo!==void 0;lo=lo.n)if(lo.S.i!==lo.i||!lo.S.h()||lo.S.i!==lo.i)return!0;return!1}function _(Au){for(var lo=Au.s;lo!==void 0;lo=lo.n){var $u=lo.S.n;if($u!==void 0&&(lo.r=$u),lo.S.n=lo,lo.i=-1,lo.n===void 0){Au.s=lo;break}}}function b(Au){for(var lo=Au.s,$u=void 0;lo!==void 0;){var Ru=lo.p;lo.i===-1?(lo.S.U(lo),Ru!==void 0&&(Ru.n=lo.n),lo.n!==void 0&&(lo.n.p=Ru)):$u=lo,lo.S.n=lo.r,lo.r!==void 0&&(lo.r=void 0),lo=Ru}Au.s=$u}function p(Au,lo){l.call(this,void 0,lo),this.x=Au,this.s=void 0,this.g=d-1,this.f=4}p.prototype=new l;p.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===d))return!0;if(this.g=d,this.f|=1,this.i>0&&!w(this))return this.f&=-2,!0;var Au=o;try{_(this),o=this;var lo=this.x();(16&this.f||this.v!==lo||this.i===0)&&(this.v=lo,this.f&=-17,this.i++)}catch($u){this.v=$u,this.f|=16,this.i++}return o=Au,b(this),this.f&=-2,!0};p.prototype.S=function(Au){if(this.t===void 0){this.f|=36;for(var lo=this.s;lo!==void 0;lo=lo.n)lo.S.S(lo)}l.prototype.S.call(this,Au)};p.prototype.U=function(Au){if(this.t!==void 0&&(l.prototype.U.call(this,Au),this.t===void 0)){this.f&=-33;for(var lo=this.s;lo!==void 0;lo=lo.n)lo.S.U(lo)}};p.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var Au=this.t;Au!==void 0;Au=Au.x)Au.t.N()}};Object.defineProperty(p.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var Au=a(this);if(this.h(),Au!==void 0&&(Au.i=this.i),16&this.f)throw this.v;return this.v}});function g(Au,lo){return new p(Au,lo)}function S(Au){var lo=Au.m;if(Au.m=void 0,typeof lo=="function"){v++;var $u=o;o=void 0;try{lo()}catch(Ru){throw Au.f&=-2,Au.f|=8,m(Au),Ru}finally{o=$u,t()}}}function m(Au){for(var lo=Au.s;lo!==void 0;lo=lo.n)lo.S.U(lo);Au.x=void 0,Au.s=void 0,S(Au)}function x(Au){if(o!==this)throw new Error("Out-of-order effect");b(this),o=Au,this.f&=-2,8&this.f&&m(this),t()}function E(Au,lo){this.x=Au,this.m=void 0,this.s=void 0,this.u=void 0,this.f=32,this.name=lo?.name,r&&r.push(this)}E.prototype.c=function(){var Au=this.S();try{if(8&this.f||this.x===void 0)return;var lo=this.x();typeof lo=="function"&&(this.m=lo)}finally{Au()}};E.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,S(this),_(this),v++;var Au=o;return o=this,x.bind(this,Au)};E.prototype.N=function(){2&this.f||(this.f|=2,this.u=h,h=this)};E.prototype.d=function(){this.f|=8,1&this.f||m(this)};E.prototype.dispose=function(){this.d()};function j(Au,lo){var $u=new E(Au,lo);try{$u.c()}catch(Iu){throw $u.d(),Iu}var Ru=$u.d.bind($u);return Ru[Symbol.dispose]=Ru,Ru}let signalImpl,computedImpl,effectImpl,batchWriteImpl,isSignalImpl,getValueImpl,setValueImpl,peekValueImpl;const _PRIVATE_DEFAULT_SIGNAL_IMPLEMENTATION={signal:y,computed:g,effect:j,batchWrite:n,isSignal:Au=>!!Au&&typeof Au=="object"&&"value"in Au&&"peek"in Au,getValue:Au=>Au.value,setValue:(Au,lo)=>{Au instanceof p||(Au.value=lo)},peekValue:Au=>Au.peek()};setSignalImplementation(_PRIVATE_DEFAULT_SIGNAL_IMPLEMENTATION);function setSignalImplementation(Au){signalImpl=Au.signal,computedImpl=Au.computed,effectImpl=Au.effect,batchWriteImpl=Au.batchWrite,isSignalImpl=Au.isSignal,getValueImpl=Au.getValue,setValueImpl=Au.setValue,peekValueImpl=Au.peekValue}function signal(Au){return signalImpl(Au)}function computed(Au){return computedImpl(Au)}function effect(Au){return effectImpl(Au)}function batchWrite(Au){return batchWriteImpl(Au)}function isSignal(Au){return isSignalImpl(Au)}function getValue(Au){return getValueImpl(Au)}function setValue(Au,lo){setValueImpl(Au,lo)}function peekValue(Au){return peekValueImpl(Au)}function isNumeric(Au){return/^(0|[1-9]\d*)$/.test(Au)}const MAX_ARRAY_INDEX=1e4,FORBIDDEN_KEYS=new Set(["__proto__","constructor","prototype"]);class DataModel{constructor(lo={}){this.data={},this.signals=new Map,this.subscriptions=new Set,this.data=lo}getSignal(lo){const $u=this.normalizePath(lo);return this.signals.has($u)||this.signals.set($u,signal(this.get($u))),this.signals.get($u)}set(lo,$u){if(lo==null)throw new A2uiDataError("Path cannot be null or undefined.");if(lo==="/"||lo==="")return this.data=$u??{},this.notifyAllSignals(),this;const Ru=this.parsePath(lo),Iu=Ru.pop();if($u==null&&this.get(lo)===void 0)return this;if(this.data===void 0||this.data===null)this.data={};else if(typeof this.data!="object")throw new A2uiDataError(`Cannot set path '${lo}': the data model root is a primitive value.`,lo);let Pu=this.data;for(let Ou=0;Ou<Ru.length;Ou++){const Mu=Ru[Ou];if(Array.isArray(Pu)){if(!isNumeric(Mu))throw new A2uiDataError(`Cannot use non-numeric segment '${Mu}' on an array in path '${lo}'.`,lo);const Du=parseInt(Mu,10);if(Du>MAX_ARRAY_INDEX)throw new A2uiDataError(`Cannot set path '${lo}': array index '${Mu}' exceeds maximum supported index (${MAX_ARRAY_INDEX}).`,lo);const Lu=Pu[Du];if(Lu!=null&&typeof Lu!="object")throw new A2uiDataError(`Cannot set path '${lo}': segment '${Mu}' is a primitive value.`,lo);if(Lu==null){const Bu=Ou<Ru.length-1?Ru[Ou+1]:Iu;if(isNumeric(Bu)){if(parseInt(Bu,10)>MAX_ARRAY_INDEX)throw new A2uiDataError(`Cannot set path '${lo}': array index '${Bu}' exceeds maximum supported index (${MAX_ARRAY_INDEX}).`,lo);Pu[Du]=[]}else Pu[Du]={}}}else{const Du=Object.prototype.hasOwnProperty.call(Pu,Mu);if(Du){const Lu=Pu[Mu];if(Lu!=null&&typeof Lu!="object")throw new A2uiDataError(`Cannot set path '${lo}': segment '${Mu}' is a primitive value.`,lo)}if(!Du||Pu[Mu]===void 0||Pu[Mu]===null){const Lu=Ou<Ru.length-1?Ru[Ou+1]:Iu;if(isNumeric(Lu)){if(parseInt(Lu,10)>MAX_ARRAY_INDEX)throw new A2uiDataError(`Cannot set path '${lo}': array index '${Lu}' exceeds maximum supported index (${MAX_ARRAY_INDEX}).`,lo);Pu[Mu]=[]}else Pu[Mu]={}}}Pu=Pu[Mu]}if(Array.isArray(Pu)){if(!isNumeric(Iu))throw new A2uiDataError(`Cannot use non-numeric segment '${Iu}' on an array in path '${lo}'.`,lo);if(parseInt(Iu,10)>MAX_ARRAY_INDEX)throw new A2uiDataError(`Cannot set path '${lo}': array index '${Iu}' exceeds maximum supported index (${MAX_ARRAY_INDEX}).`,lo)}if($u==null)if(Array.isArray(Pu)){const Ou=parseInt(Iu,10);Ou<Pu.length&&(Pu[Ou]=void 0)}else delete Pu[Iu];else Pu[Iu]=$u;return this.notifySignals(lo),this}delete(lo){return this.set(lo,void 0)}static resolvePath(lo,$u){return lo.startsWith("/")?lo:$u?`${$u.endsWith("/")?$u:`${$u}/`}${lo}`:`/${lo}`}get(lo){if(lo==null)throw new A2uiDataError("Path cannot be null or undefined.");if(lo==="/"||lo==="")return this.data;const $u=this.parsePath(lo);let Ru=this.data;for(const Iu of $u){if(Ru==null||typeof Ru!="object")return;if(Array.isArray(Ru)){if(!isNumeric(Iu))return;const Pu=parseInt(Iu,10);if(Pu<0||Pu>=Ru.length)return;Ru=Ru[Pu]}else{if(!Object.prototype.hasOwnProperty.call(Ru,Iu))return;Ru=Ru[Iu]}}return Ru}hasPath(lo){return lo==null?!1:this.get(lo)!==void 0}subscribe(lo,$u){const Ru=this.getSignal(lo);let Iu=!0,Pu=peekValue(Ru);const Ou=effect(()=>{const Mu=getValue(Ru);Pu=Mu,Iu||$u(Mu)});return Iu=!1,this.subscriptions.add(Ou),{get value(){return Pu},unsubscribe:()=>{Ou(),this.subscriptions.delete(Ou)}}}dispose(){for(const lo of this.subscriptions)lo();this.subscriptions.clear(),this.signals.clear()}normalizePath(lo){return lo.length>1&&lo.endsWith("/")?lo.slice(0,-1):lo||"/"}parsePath(lo){return lo.split("/").filter($u=>$u.length>0).map($u=>{const Ru=$u.replace(/~([01])/g,(Iu,Pu)=>Pu==="1"?"/":"~");if(FORBIDDEN_KEYS.has(Ru))throw new A2uiDataError(`Forbidden path segment '${Ru}' in path '${lo}'.`,lo);return Ru})}notifySignals(lo){const $u=this.normalizePath(lo);batchWrite(()=>{this.updateSignal($u);let Ru=$u;for(;Ru!=="/"&&Ru!=="";)Ru=Ru.substring(0,Ru.lastIndexOf("/"))||"/",this.updateSignal(Ru);for(const Iu of this.signals.keys())this.isDescendant(Iu,$u)&&this.updateSignal(Iu)})}updateSignal(lo){const $u=this.signals.get(lo);if($u){const Ru=this.get(lo);Array.isArray(Ru)?setValue($u,Ru.slice()):typeof Ru=="object"&&Ru!==null?setValue($u,{...Ru}):setValue($u,Ru)}}notifyAllSignals(){batchWrite(()=>{for(const lo of this.signals.keys())this.updateSignal(lo)})}isDescendant(lo,$u){return $u==="/"||$u===""?lo!=="/":lo.startsWith($u+"/")}}const MAX_GLOBAL_DEPTH=50,MAX_FUNC_CALL_DEPTH=5,RELAXED_PATH_PATTERN=/^(?:(?:\/(?:[^~/]|~[01])*)*|(?:[^~/]|~[01])+(?:\/(?:[^~/]|~[01])*)*)$/;function*extractPointers(Au,lo,$u){if(typeof Au=="string")yield[Au,lo];else if(Array.isArray(Au))for(let Ru=0;Ru<Au.length;Ru++){const Iu=Au[Ru],Pu=`${lo}[${Ru}]`;yield*extractPointers(Iu,Pu,$u)}else if(typeof Au=="object"&&Au!==null){const Ru=Au;if("componentId"in Ru&&typeof Ru.componentId=="string"&&("path"in Ru||"dataBinding"in Ru))yield[Ru.componentId,`${lo}.componentId`];else if($u?.size)for(const Iu of $u)Iu in Ru&&(yield*extractPointers(Ru[Iu],`${lo}.${Iu}`));else for(const[Iu,Pu]of Object.entries(Ru))yield*extractPointers(Pu,`${lo}.${Iu}`)}}function getOrCreateRefMap(Au){return Au.componentRefMap}function*getComponentReferences(Au,lo){if(!Au||typeof Au!="object")return;const $u=lo instanceof Catalog?getOrCreateRefMap(lo):lo,Ru=Au.component;let Iu="",Pu=Au;if(typeof Ru=="string")Iu=Ru;else if(typeof Ru=="object"&&Ru!==null){const Bu=Ru;Iu=Object.keys(Bu)[0]??"",Pu=Bu[Iu]??{}}if(!Iu||typeof Pu!="object"||Pu===null)return;const Ou=$u[Iu],Mu=Ou?Ou.singleRefs:new Set,Du=Ou?Ou.listRefs:new Set,Lu=Ou?.nestedRefs;for(const[Bu,ju]of Object.entries(Pu))(Mu.has(Bu)||Du.has(Bu))&&(yield*extractPointers(ju,Bu,Lu?.[Bu]))}function traverseRecursionAndPaths(Au,lo,$u){if(lo>MAX_GLOBAL_DEPTH)throw new A2uiRecursionError(`Global recursion limit exceeded: Depth > ${MAX_GLOBAL_DEPTH}`);if(Array.isArray(Au)){for(const Ru of Au)traverseRecursionAndPaths(Ru,lo+1,$u);return}if(typeof Au=="object"&&Au!==null){const Ru=Au;if("path"in Ru&&typeof Ru.path=="string"){const Ou=Ru.path;if(!RELAXED_PATH_PATTERN.test(Ou))throw new A2uiValidationError(`Invalid path syntax: '${Ou}'`)}const Iu="functionCall"in Ru&&typeof Ru.functionCall=="object"&&Ru.functionCall!==null,Pu="call"in Ru&&"args"in Ru;if(Iu){if($u>=MAX_FUNC_CALL_DEPTH)throw new A2uiRecursionError(`Recursion limit exceeded: functionCall depth > ${MAX_FUNC_CALL_DEPTH}`);for(const[Ou,Mu]of Object.entries(Ru))Ou==="functionCall"?traverseRecursionAndPaths(Mu,lo+1,$u+1):traverseRecursionAndPaths(Mu,lo+1,$u)}else if(Pu){if($u>=MAX_FUNC_CALL_DEPTH)throw new A2uiRecursionError(`Recursion limit exceeded: functionCall depth > ${MAX_FUNC_CALL_DEPTH}`);for(const[Ou,Mu]of Object.entries(Ru))Ou==="args"?traverseRecursionAndPaths(Mu,lo+1,$u+1):traverseRecursionAndPaths(Mu,lo+1,$u)}else for(const Ou of Object.values(Ru))traverseRecursionAndPaths(Ou,lo+1,$u)}}function validateRecursionAndPaths(Au){traverseRecursionAndPaths(Au,0,0)}class SurfaceComponentsModel{constructor(lo){this.components=new Map,this._onCreated=new EventEmitter,this._onDeleted=new EventEmitter,this.onCreated=this._onCreated,this.onDeleted=this._onDeleted,lo&&this.setCatalog(lo)}setCatalog(lo){this.refMap=lo instanceof Catalog?lo.componentRefMap:lo}get(lo){return this.components.get(lo)}getAll(){return new Map(this.components)}has(lo){return this.components.has(lo)}get entries(){return this.components.entries()}get keys(){return this.components.keys()}get values(){return this.components.values()}get size(){return this.components.size}get componentsMap(){return this.components}addComponent(lo){if(this.components.has(lo.id))throw new A2uiStateError(`Component with id '${lo.id}' already exists.`);this.components.set(lo.id,lo),this._onCreated.emit(lo)}removeComponent(lo){const $u=this.components.get(lo);$u&&(this.components.delete(lo),$u.dispose(),this._onDeleted.emit(lo))}getChildReferences(lo){const $u=this.components.get(lo);if(!$u)return[];const Ru=$u.catalog?.components.size?$u.catalog.componentRefMap:this.refMap??$u.catalog?.componentRefMap??{};return Array.from(getComponentReferences({id:$u.id,component:$u.type,...$u.properties},Ru))}getChildIds(lo){return this.getChildReferences(lo).map(([$u])=>$u)}detectCycles(lo={}){const $u=lo.rootId??"root",Ru=lo.maxDepth??MAX_GLOBAL_DEPTH,Iu=lo.allowMissingRoot??!1;for(const Du of this.components.values())for(const[Lu,Bu]of this.getChildReferences(Du.id))if(Lu===Du.id)throw new A2uiRecursionError(`Circular reference detected: Component '${Du.id}' references itself in field '${Bu}' (Self-reference detected)`);const Pu=new Set,Ou=new Set,Mu=(Du,Lu)=>{if(Lu>Ru)throw new A2uiRecursionError(`Global recursion limit exceeded: logical depth > ${Ru}`);Pu.add(Du),Ou.add(Du);const Bu=this.getChildIds(Du);for(const ju of Bu)if(this.components.has(ju)){if(!Pu.has(ju))Mu(ju,Lu+1);else if(Ou.has(ju))throw new A2uiRecursionError(`Circular reference detected involving component '${ju}'`)}Ou.delete(Du)};if(Iu){const Du=Array.from(this.components.keys()).sort();for(const Lu of Du)Pu.has(Lu)||Mu(Lu,0)}else this.components.has($u)&&Mu($u,0);return Pu}validateTopology(lo={}){if(this.components.size===0)return;const $u=lo.rootId??"root",Ru=lo.allowMissingRoot??!1,Iu=lo.allowDanglingReferences??!1,Pu=lo.allowOrphanComponents??!1;if(!Ru&&!this.components.has($u))throw new A2uiIntegrityError(`Missing root component: No component has id='${$u}'`);if(!Iu){for(const Mu of this.components.values())for(const[Du,Lu]of this.getChildReferences(Mu.id))if(!this.components.has(Du))throw new A2uiIntegrityError(`Component '${Mu.id}' references non-existent component '${Du}' in field '${Lu}' (Dangling reference '${Du}' in component '${Mu.id}')`)}const Ou=this.detectCycles({rootId:$u,allowMissingRoot:Ru,maxDepth:lo.maxDepth});if(!Pu&&!Ru&&Ou.size<this.components.size){const Mu=Array.from(this.components.keys()).filter(Du=>!Ou.has(Du)).sort();if(Mu.length>0)throw new A2uiIntegrityError(`Component '${Mu[0]}' is not reachable from '${$u}' (Orphaned component '${Mu[0]}' is not reachable from root)`)}}validateReferences(lo={}){const $u=[];try{this.validateTopology(lo)}catch(Ru){Ru instanceof A2uiValidationError?$u.push(Ru):Ru instanceof Error&&$u.push(new A2uiValidationError(Ru.message))}return $u}dispose(){for(const lo of this.components.values())lo.dispose();this.components.clear(),this._onCreated.dispose(),this._onDeleted.dispose()}}class SurfaceModel{constructor(lo,$u,Ru=new Map,Iu={},Pu=!1,Ou,Mu="root"){if(this.id=lo,this.defaultCatalog=$u,this.theme=Iu,this.sendDataModel=Pu,this.rootId=Mu,this._onAction=new EventEmitter,this._onError=new EventEmitter,this._onWarning=new EventEmitter,this.onAction=this._onAction,this.onError=this._onError,this.onWarning=this._onWarning,Ru!=null&&!(Ru instanceof Map))throw new TypeError("availableCatalogs must be a Map, or undefined/null. Note that availableCatalogs is now the 3rd argument to SurfaceModel and theme is the 4th argument.");const Du=new Map(Ru??[]);$u?.id&&!Du.has($u.id)&&Du.set($u.id,$u),this.availableCatalogs=Du,this.dataModel=Ou??new DataModel({}),this.componentsModel=new SurfaceComponentsModel($u)}get catalog(){return this.defaultCatalog}async dispatchAction(lo,$u){if(!lo||typeof lo!="object")return;const Ru=extractActionTarget(lo);if(!Ru)return;const Iu=Ru.name;if(!Iu||typeof Iu!="string")return;const Pu=Ru.context,Ou=Pu&&typeof Pu=="object"&&!Array.isArray(Pu)?Pu:{},Mu={name:Iu,surfaceId:this.id,sourceComponentId:$u,timestamp:new Date().toISOString(),context:Ou},Du=Ru.catalogId??lo.catalogId;typeof Du=="string"&&Du&&(Mu.catalogId=Du),typeof Ru.userMessage=="string"&&Ru.userMessage.length>0&&(Mu.userMessage=Ru.userMessage),await this._onAction.emit(Mu)}async dispatchError(lo){await this._onError.emit({...lo,surfaceId:this.id})}async dispatchWarning(lo){await this._onWarning.emit({...lo,surfaceId:this.id})}dispose(){this.dataModel.dispose(),this.componentsModel.dispose(),this._onAction.dispose(),this._onError.dispose(),this._onWarning.dispose()}}function extractActionTarget(Au){return"event"in Au&&Au.event&&typeof Au.event=="object"?Au.event:"name"in Au&&typeof Au.name=="string"?Au:null}class SurfaceGroupModel{constructor(){this.surfaces=new Map,this.surfaceUnsubscribers=new Map,this._onSurfaceCreated=new EventEmitter,this._onSurfaceDeleted=new EventEmitter,this._onAction=new EventEmitter,this.onSurfaceCreated=this._onSurfaceCreated,this.onSurfaceDeleted=this._onSurfaceDeleted,this.onAction=this._onAction}addSurface(lo){if(this.surfaces.has(lo.id)){console.warn(`Surface ${lo.id} already exists. Ignoring.`);return}this.surfaces.set(lo.id,lo);const $u=lo.onAction.subscribe(Ru=>this._onAction.emit(Ru));this.surfaceUnsubscribers.set(lo.id,$u),this._onSurfaceCreated.emit(lo)}deleteSurface(lo){const $u=this.surfaces.get(lo);if($u){const Ru=this.surfaceUnsubscribers.get(lo);Ru&&(Ru.unsubscribe(),this.surfaceUnsubscribers.delete(lo)),this.surfaces.delete(lo),$u.dispose(),this._onSurfaceDeleted.emit(lo)}}getSurface(lo){return this.surfaces.get(lo)}get surfacesMap(){return this.surfaces}dispose(){for(const lo of Array.from(this.surfaces.keys()))this.deleteSurface(lo);this._onSurfaceCreated.dispose(),this._onSurfaceDeleted.dispose(),this._onAction.dispose()}}class ComponentModel{constructor(lo,$u,Ru,Iu){this.id=lo,this.type=$u,this.catalog=Iu,this._onUpdated=new EventEmitter,this.onUpdated=this._onUpdated,this._properties=Ru}get properties(){return this._properties}set properties(lo){this._properties=lo,this._onUpdated.emit(this)}dispose(){this._onUpdated.dispose()}get componentTree(){return{id:this.id,type:this.type,...this._properties}}}function formatZodIssue(Au){const lo=Au.path.join(".")||"root";switch(Au.code){case ZodIssueCode.invalid_union:{const $u=Au.unionErrors?.flatMap(Ru=>Ru.issues);return $u&&$u.length>0?$u.map(formatZodIssue).join("; "):`${lo}: Invalid union`}case ZodIssueCode.unrecognized_keys:{const $u=Au.keys.map(Ru=>`'${Ru}'`).join(", ");return`${lo}: Unrecognized key(s) in object: ${$u}`}case ZodIssueCode.invalid_enum_value:{const $u=Au,Ru=$u.options.map(Iu=>String(Iu)).join(" | ");return`${lo}: Invalid enum value. Expected ${Ru}, received '${String($u.received)}'`}case ZodIssueCode.invalid_type:{const $u=Au;return`${lo}: Expected ${$u.expected}, received ${$u.received}`}case ZodIssueCode.custom:return`${lo}: ${Au.message}`;default:return Au.message?`${lo}: ${Au.message}`:`${lo}: Validation error (${Au.code})`}}const DEFAULT_CATALOG_COMPATIBILITY={"0.8":new Set(["0.8"]),"0.9":new Set(["0.9","0.9.1"]),"0.9.1":new Set(["0.9.1","0.9"]),"1.0":new Set(["1.0"])};function isCatalogVersionCompatible(Au,lo,$u=DEFAULT_CATALOG_COMPATIBILITY){if(!Au||!lo)return!1;const Ru=toCanonicalVersion(Au),Iu=toCanonicalVersion(lo);if(Ru&&Iu){if(Ru===Iu)return!0;const Mu=$u[Iu];if(Mu&&Mu.has(Ru))return!0;const Du=toSemVer(Au),Lu=toSemVer(lo);return!!(Du&&Lu&&Du.major>=1&&Du.major===Lu.major)}if(typeof Au!="string"||typeof lo!="string")return!1;const Pu=normalizeVersionString(Au),Ou=normalizeVersionString(lo);return Pu.length>0&&Pu===Ou}let globalKnownActionsProvider;function registerKnownActionsProvider(Au){globalKnownActionsProvider=Au}function validateActionSurfaceIds(Au,lo){for(const $u of lo){const Ru=Au[$u];if(Ru&&typeof Ru=="object"){const Iu=Ru;if("surfaceId"in Iu&&Iu.surfaceId!==void 0&&typeof Iu.surfaceId!="string")throw new A2uiValidationError("surfaceId must be a string")}}}class BaseVersionAdapter{get compatibleCatalogVersions(){const lo=toCanonicalVersion(this.version);return lo?new Set([lo]):new Set}get validActions(){return new Set(this.getNativeActionKeys())}isCatalogCompatible(lo){return lo?isCatalogVersionCompatible(lo,this.version):!1}extractOperations(lo){if(!lo||typeof lo!="object")return[];if(Array.isArray(lo))return lo.flatMap(Mu=>this.extractOperations(Mu));const $u=lo;if(Array.isArray($u.messages))return this.extractOperations($u.messages);const Ru=this.getNativeActionKeys();validateActionSurfaceIds($u,Ru);const Iu=Ru.filter(Mu=>Mu in $u).sort();if(Iu.length>1)throw new A2uiValidationError(`Message contains multiple conflicting update actions: ${Iu.join(", ")}.`);if(Iu.length===0){const Mu=globalKnownActionsProvider?globalKnownActionsProvider():new Set(Ru),Du=Object.keys($u).find(Bu=>Mu.has(Bu)&&!Ru.includes(Bu)),Lu=Ru.slice().sort().join(", ");throw Du?new A2uiValidationError(`Invalid ${this.version} message: action '${Du}' is not supported in protocol version ${this.version}. Allowed actions: ${Lu}.`):new A2uiValidationError(`Invalid ${this.version} message: message must contain exactly one update action: ${Lu}.`)}const Pu=this.preparePayloadForValidation($u),Ou=this.schema.safeParse(Pu);if(!Ou.success){const Mu=Ou.error.errors.map(formatZodIssue).join("; ");throw new A2uiValidationError(`Invalid ${this.version} message: ${Mu}`,Ou.error)}return this.extractOperationsFromObject($u)}preparePayloadForValidation(lo){return"version"in lo?lo:{version:this.version,...lo}}}const exactlyOneKey=(Au,lo)=>{const $u=Object.keys(Au).filter(Ru=>Au[Ru]!==void 0);$u.length!==1&&lo.addIssue({code:ZodIssueCode.custom,message:`Must define exactly one property, found ${$u.length} (${$u.join(", ")}).`})},StringValueSchema=objectType({path:stringType().optional(),literalString:stringType().optional(),literal:stringType().optional()}).strict().superRefine(exactlyOneKey),DataValueMapItemSchema=lazyType(()=>objectType({key:stringType(),valueString:stringType().optional(),valueNumber:numberType().optional(),valueBoolean:booleanType().optional(),valueMap:arrayType(DataValueMapItemSchema).optional()}).strict().superRefine((Au,lo)=>{let $u=0;Au.valueString!==void 0&&$u++,Au.valueNumber!==void 0&&$u++,Au.valueBoolean!==void 0&&$u++,Au.valueMap!==void 0&&$u++,$u!==1&&lo.addIssue({code:ZodIssueCode.custom,message:`Value map item must have exactly one value property (valueString, valueNumber, valueBoolean, valueMap), found ${$u}.`})}));function createDataValueSchema(Au={}){const lo=Au.maxDepth??5;return DataValueMapItemSchema.superRefine(($u,Ru)=>{const Iu=(Pu,Ou)=>{if(Ou>lo){Ru.addIssue({code:ZodIssueCode.custom,message:`valueMap recursion exceeded maximum depth of ${lo}.`});return}if(Pu.valueMap&&Array.isArray(Pu.valueMap))for(const Mu of Pu.valueMap)Iu(Mu,Ou+1)};Iu($u,1)})}const DataValueSchema=createDataValueSchema();objectType({path:stringType().optional(),literalNumber:numberType().optional(),literal:numberType().optional()}).strict().superRefine(exactlyOneKey);objectType({path:stringType().optional(),literalBoolean:booleanType().optional(),literal:booleanType().optional()}).strict().superRefine(exactlyOneKey);const ActionSchema$1=objectType({name:stringType().describe("A unique name identifying the action (e.g., 'submitForm')."),context:arrayType(objectType({key:stringType(),value:objectType({path:stringType().describe("A data binding reference to a location in the data model (e.g., '/user/name').").optional(),literalString:stringType().describe("A fixed, hardcoded string value.").optional(),literalNumber:numberType().optional(),literalBoolean:booleanType().optional()}).describe("The dynamic value. Define EXACTLY ONE of the nested properties.").strict().superRefine(exactlyOneKey)})).describe("A key-value map of data bindings to be resolved when the action is triggered.").optional()});objectType({text:StringValueSchema,usageHint:enumType(["h1","h2","h3","h4","h5","caption","body"]).optional()});objectType({url:StringValueSchema,usageHint:enumType(["icon","avatar","smallFeature","mediumFeature","largeFeature","header"]).optional(),fit:enumType(["contain","cover","fill","none","scale-down"]).optional(),altText:StringValueSchema.optional()});objectType({name:StringValueSchema});objectType({url:StringValueSchema});objectType({url:StringValueSchema,description:StringValueSchema.optional().describe("A label, title, or placeholder text.")});objectType({tabItems:arrayType(objectType({title:objectType({path:stringType().describe("A data binding reference to a location in the data model (e.g., '/user/name').").optional(),literalString:stringType().describe("A fixed, hardcoded string value.").optional()}),child:stringType().describe("A reference to a component instance by its unique ID.")}).strict().superRefine((Au,lo)=>{Au.title||lo.addIssue({code:ZodIssueCode.custom,message:"Tab item is missing 'title'."}),Au.child||lo.addIssue({code:ZodIssueCode.custom,message:"Tab item is missing 'child'."}),Au.title&&exactlyOneKey(Au.title,lo)})).describe("A list of tabs, each with a title and a child component ID.")});objectType({axis:enumType(["horizontal","vertical"]).optional().describe("The orientation."),color:stringType().optional().describe("The color of the divider (e.g., hex code or semantic name)."),thickness:numberType().optional().describe("The thickness of the divider.")});objectType({entryPointChild:stringType().describe("The ID of the component (e.g., a button) that triggers the modal."),contentChild:stringType().describe("The ID of the component to display as the modal's content.")});objectType({child:stringType().describe("The ID of the component to display as the button's content."),action:ActionSchema$1.describe("Represents a user-initiated action."),primary:booleanType().optional().describe("Indicates if this button should be styled as the primary action.")});objectType({label:StringValueSchema,value:objectType({path:stringType().describe("A data binding reference to a location in the data model (e.g., '/user/name').").optional(),literalBoolean:booleanType().optional()}).strict().superRefine(exactlyOneKey)});objectType({text:StringValueSchema.optional(),label:StringValueSchema.describe("A label, title, or placeholder text."),textFieldType:enumType(["shortText","number","date","longText","obscured"]).optional(),validationRegexp:stringType().optional().describe("A regex string to validate the input.")});objectType({value:StringValueSchema,enableDate:booleanType().optional(),enableTime:booleanType().optional(),outputFormat:stringType().optional().describe("The string format for the output (e.g., 'YYYY-MM-DD').")});objectType({selections:objectType({path:stringType().describe("A data binding reference to a location in the data model (e.g., '/user/name').").optional(),literalArray:arrayType(stringType()).optional()}).strict().superRefine(exactlyOneKey),options:arrayType(objectType({label:objectType({path:stringType().describe("A data binding reference to a location in the data model (e.g., '/user/name').").optional(),literalString:stringType().describe("A fixed, hardcoded string value.").optional()}).strict().superRefine(exactlyOneKey),value:stringType()})).optional(),maxAllowedSelections:numberType().optional(),type:enumType(["checkbox","chips"]).optional(),filterable:booleanType().optional()});objectType({value:objectType({path:stringType().describe("A data binding reference to a location in the data model (e.g., '/user/name').").optional(),literalNumber:numberType().optional()}).strict().superRefine(exactlyOneKey),minValue:numberType().optional(),maxValue:numberType().optional(),label:StringValueSchema.optional()});const ComponentArrayTemplateSchema=objectType({componentId:stringType(),dataBinding:stringType()}),ComponentArrayReferenceSchema=objectType({explicitList:arrayType(stringType()).optional(),template:ComponentArrayTemplateSchema.describe("A template for generating a dynamic list of children from a data model list. `componentId` is the component to use as a template, and `dataBinding` is the path to the map of components in the data model. Values in the map will define the list of children.").optional()}).strict().superRefine(exactlyOneKey);objectType({children:ComponentArrayReferenceSchema,distribution:enumType(["start","center","end","spaceBetween","spaceAround","spaceEvenly"]).optional(),alignment:enumType(["start","center","end","stretch"]).optional()});objectType({children:ComponentArrayReferenceSchema,distribution:enumType(["start","center","end","spaceBetween","spaceAround","spaceEvenly"]).optional(),alignment:enumType(["start","center","end","stretch"]).optional()});objectType({children:ComponentArrayReferenceSchema,direction:enumType(["vertical","horizontal"]).optional(),alignment:enumType(["start","center","end","stretch"]).optional()});objectType({child:stringType().describe("The ID of the component to be rendered inside the card.")});const ValueMapSchema=DataValueSchema.describe("A single data entry. Exactly one 'value*' property should be provided alongside the key."),ComponentPropertiesSchema=recordType(anyType()).refine(Au=>Object.keys(Au).length===1,"A wrapper object that MUST contain exactly one key, which is the name of the component type (e.g., 'Heading')."),ComponentInstanceSchema=objectType({id:stringType().describe("The unique identifier for this component."),weight:numberType().optional().describe("The relative weight of this component within a Row or Column. This corresponds to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column."),component:ComponentPropertiesSchema.describe("A wrapper object that MUST contain exactly one key, which is the name of the component type (e.g., 'Heading'). The value is an object containing the properties for that specific component.")}).strict().describe("Represents a *single* component in a UI widget tree. This component could be one of many supported types."),BeginRenderingMessageSchema=objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be rendered."),catalogId:stringType().optional().describe("The identifier of the component catalog to use for this surface. If omitted, the client MUST default to the standard catalog for this A2UI version (https://a2ui.org/specification/v0_8/standard_catalog_definition.json)."),root:stringType().describe("The ID of the root component to render."),styles:objectType({font:stringType().optional().describe("The primary font for the UI."),primaryColor:stringType().regex(/^#[0-9a-fA-F]{6}$/).optional().describe("The primary UI color as a hexadecimal code (e.g., '#00BFFF').")}).strict().optional().describe("Styling information for the UI.")}).strict().describe("Signals the client to begin rendering a surface with a root component and specific styles."),SurfaceUpdateMessageSchema=objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be updated. If you are adding a new surface this *must* be a new, unique identified that has never been used for any existing surfaces shown."),components:arrayType(ComponentInstanceSchema).min(1).describe("A list containing all UI components for the surface.")}).strict().superRefine((Au,lo)=>{const $u=new Set;for(const Iu of Au.components)Iu.id&&($u.has(Iu.id)&&lo.addIssue({code:ZodIssueCode.custom,message:`Duplicate component ID found: ${Iu.id}`,path:["components"]}),$u.add(Iu.id));const Ru=(Iu,Pu)=>{for(const Ou of Iu)Ou&&!$u.has(Ou)&&lo.addIssue({code:ZodIssueCode.custom,message:`Component '${Pu}' references non-existent component ID '${Ou}'.`,path:["components"]})};for(const Iu of Au.components){if(!Iu.id||!Iu.component)continue;const Pu=Object.keys(Iu.component);if(Pu.length!==1)continue;const Ou=Pu[0],Mu=Iu.component[Ou];switch(Ou){case"Row":case"Column":case"List":if(Mu.children&&!Array.isArray(Mu.children)){const Du=!!Mu.children.explicitList,Lu=!!Mu.children.template;(Du&&Lu||!Du&&!Lu)&&lo.addIssue({code:ZodIssueCode.custom,message:`Component '${Iu.id}' must have either 'explicitList' or 'template' in children, but not both or neither.`}),Du&&Ru(Mu.children.explicitList,Iu.id),Lu&&Ru([Mu.children.template?.componentId],Iu.id)}break;case"Card":Mu.child&&Ru([Mu.child],Iu.id);break;case"Tabs":Mu.tabItems&&Array.isArray(Mu.tabItems)&&Mu.tabItems.forEach(Du=>{Du.child&&Ru([Du.child],Iu.id)});break;case"Modal":Ru([Mu.entryPointChild,Mu.contentChild],Iu.id);break;case"Button":Mu.child&&Ru([Mu.child],Iu.id);break}}}).describe("Updates a surface with a new set of components."),DataModelUpdateMessageSchema=objectType({surfaceId:stringType().describe("The unique identifier for the UI surface this data model update applies to."),path:stringType().optional().describe("An optional path to a location within the data model (e.g., '/user/name'). If omitted, or set to '/', the entire data model will be replaced."),contents:arrayType(ValueMapSchema).describe("An array of data entries. Each entry must contain a 'key' and exactly one corresponding typed 'value*' property.")}).strict().describe("Updates the data model for a surface."),DeleteSurfaceMessageSchema$2=objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be deleted.")}).strict().describe("Signals the client to delete the surface identified by 'surfaceId'."),A2uiMessageSchema$1=objectType({beginRendering:BeginRenderingMessageSchema.optional(),surfaceUpdate:SurfaceUpdateMessageSchema.optional(),dataModelUpdate:DataModelUpdateMessageSchema.optional(),deleteSurface:DeleteSurfaceMessageSchema$2.optional()}).strict().superRefine((Au,lo)=>{Object.keys(Au).filter(Ru=>["beginRendering","surfaceUpdate","dataModelUpdate","deleteSurface"].includes(Ru)).length!==1&&lo.addIssue({code:ZodIssueCode.custom,message:"A2UI Protocol message must have exactly one of: surfaceUpdate, dataModelUpdate, beginRendering, deleteSurface."})}).describe("Describes a JSON payload for an A2UI (Agent to UI) message, which is used to dynamically construct and update user interfaces. A message MUST contain exactly ONE of the action properties: 'beginRendering', 'surfaceUpdate', 'dataModelUpdate', or 'deleteSurface'.");function normalizeV08Component(Au){if(!Au||typeof Au!="object")return{id:"",component:""};const lo=Au;let $u=typeof lo.component=="string"?lo.component:"";const Ru={};for(const[Iu,Pu]of Object.entries(lo))Iu!=="component"&&Iu!=="id"&&(Ru[Iu]=Pu);if(lo.component&&typeof lo.component=="object"){const Iu=lo.component,Pu=Object.keys(Iu);if(Pu.length>0){$u=Pu[0];const Ou=Iu[Pu[0]];Ou&&typeof Ou=="object"&&Ou!==null&&!Array.isArray(Ou)&&Object.assign(Ru,Ou)}}return{...Ru,id:String(lo.id??""),component:$u}}class V0Point8Adapter extends BaseVersionAdapter{constructor(){super(...arguments),this.version="v0.8",this.schema=A2uiMessageSchema$1}getNativeActionKeys(){return["beginRendering","surfaceUpdate","dataModelUpdate","deleteSurface"]}preparePayloadForValidation(lo){const $u={...lo};return delete $u.version,$u}extractOperationsFromObject(lo){const $u=[];if("beginRendering"in lo){const Ru=lo.beginRendering;$u.push({type:"createSurface",surfaceId:String(Ru?.surfaceId??""),catalogId:typeof Ru?.catalogId=="string"?Ru.catalogId:void 0,theme:Ru?.theme??Ru?.styles,sendDataModel:!!Ru?.sendDataModel,components:Array.isArray(Ru?.components)?Ru.components.map(normalizeV08Component):void 0,dataModel:Ru?.dataModel&&typeof Ru.dataModel=="object"&&!Array.isArray(Ru.dataModel)?Ru.dataModel:void 0,version:typeof lo.version=="string"?lo.version:this.version,rootId:typeof Ru?.root=="string"&&Ru.root?Ru.root:void 0})}if("surfaceUpdate"in lo){const Ru=lo.surfaceUpdate;$u.push({type:"updateComponents",surfaceId:String(Ru?.surfaceId??""),components:Array.isArray(Ru?.components)?Ru.components.map(normalizeV08Component):[]})}if("dataModelUpdate"in lo){const Ru=lo.dataModelUpdate,Iu=String(Ru?.surfaceId??"");if(Array.isArray(Ru?.contents)){for(const Pu of Ru.contents)if(Pu&&typeof Pu=="object"&&typeof Pu.key=="string"){const Ou="valueNumber"in Pu?Pu.valueNumber:"valueString"in Pu?Pu.valueString:"valueBoolean"in Pu?Pu.valueBoolean:"valueObject"in Pu?Pu.valueObject:"valueArray"in Pu?Pu.valueArray:Pu.value;$u.push({type:"updateDataModel",surfaceId:Iu,path:Pu.key,value:Ou})}}else $u.push({type:"updateDataModel",surfaceId:Iu,path:typeof Ru?.path=="string"?Ru.path:void 0,value:Ru?.value})}if("deleteSurface"in lo){const Ru=lo.deleteSurface;$u.push({type:"deleteSurface",surfaceId:String(Ru?.surfaceId??"")})}return $u}}const CreateSurfaceMessageSchema$1=objectType({version:enumType(["v0.9","v0.9.1"]),createSurface:objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be rendered."),catalogId:stringType().describe("A string that uniquely identifies this catalog. It is recommended to prefix this with an internet domain that you own, to avoid conflicts e.g. mycompany.com:somecatalog'."),theme:anyType().optional(),sendDataModel:booleanType().describe("If true, the client will send the full data model of this surface in the metadata of every A2A message sent to the server that created the surface. Defaults to false.").optional()}).strict().describe("Signals the client to create a new surface and begin rendering it. It is an error to send 'createSurface' for a surfaceId that already exists without first deleting it. When this message is sent, the client will expect 'updateComponents' and/or 'updateDataModel' messages for the same surfaceId that define the component tree.")}).strict(),UpdateComponentsMessageSchema$1=objectType({version:enumType(["v0.9","v0.9.1"]),updateComponents:objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be updated."),components:arrayType(recordType(stringType(),anyType())).min(1).describe("A list containing all UI components for the surface.")}).strict().describe("Updates a surface with a new set of components. This message can be sent multiple times to update the component tree of an existing surface. One of the components in one of the components lists MUST have an 'id' of 'root' to serve as the root of the component tree. A createSurface message MUST have been previously sent for the 'surfaceId' in this message; the surface's catalog is the one specified by that createSurface.")}).strict(),UpdateDataModelMessageSchema$1=objectType({version:enumType(["v0.9","v0.9.1"]),updateDataModel:objectType({surfaceId:stringType().describe("The unique identifier for the UI surface this data model update applies to."),path:stringType().describe("An optional path to a location within the data model (e.g., '/user/name'). If omitted, or set to '/', refers to the entire data model.").optional(),value:anyType().describe("The data to be updated in the data model. If present, the value at 'path' is replaced (or created). If omitted, the key at 'path' is removed.").optional()}).strict().describe("Updates the data model for an existing surface. This message can be sent multiple times to update the data model. A createSurface message MUST have been previously sent for the 'surfaceId' in this message; the surface's catalog is the one specified by that createSurface.")}).strict(),DeleteSurfaceMessageSchema$1=objectType({version:enumType(["v0.9","v0.9.1"]),deleteSurface:objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be deleted.")}).strict().describe("Signals the client to delete the surface identified by 'surfaceId'. A createSurface message MUST have been previously sent for the 'surfaceId' in this message; the surface's catalog is the one specified by that createSurface.")}).strict(),A2uiMessageSchema=unionType([CreateSurfaceMessageSchema$1,UpdateComponentsMessageSchema$1,UpdateDataModelMessageSchema$1,DeleteSurfaceMessageSchema$1]),A2uiMessageListSchema=arrayType(A2uiMessageSchema).describe("A list of messages.");objectType({messages:A2uiMessageListSchema}).strict().describe("An object wrapping a list of messages.");class V0Point9Adapter extends BaseVersionAdapter{constructor(){super(...arguments),this.version="v0.9",this.schema=A2uiMessageSchema}get compatibleCatalogVersions(){return new Set(["0.9","0.9.1"])}getNativeActionKeys(){return["createSurface","updateComponents","updateDataModel","deleteSurface"]}extractOperationsFromObject(lo){const $u=[];if("createSurface"in lo){const Ru=lo.createSurface;$u.push({type:"createSurface",surfaceId:String(Ru?.surfaceId||""),catalogId:typeof Ru?.catalogId=="string"?Ru.catalogId:void 0,theme:Ru?.theme,sendDataModel:!!Ru?.sendDataModel,components:Array.isArray(Ru?.components)?Ru.components:void 0,dataModel:Ru?.dataModel&&typeof Ru.dataModel=="object"&&!Array.isArray(Ru.dataModel)?Ru.dataModel:void 0,version:typeof lo.version=="string"?lo.version:this.version})}if("updateComponents"in lo){const Ru=lo.updateComponents;$u.push({type:"updateComponents",surfaceId:String(Ru?.surfaceId||""),components:Array.isArray(Ru?.components)?Ru.components:[]})}if("updateDataModel"in lo){const Ru=lo.updateDataModel;$u.push({type:"updateDataModel",surfaceId:String(Ru?.surfaceId||""),path:typeof Ru?.path=="string"?Ru.path:void 0,value:Ru?.value})}if("deleteSurface"in lo){const Ru=lo.deleteSurface;$u.push({type:"deleteSurface",surfaceId:String(Ru?.surfaceId||"")})}return $u}}const INTERNAL_OPERATION_TYPES=["createSurface","updateComponents","updateDataModel","deleteSurface","callRendererFunction","agentFunctionResponse"];function isInternalOperation(Au){return typeof Au=="object"&&Au!==null&&"type"in Au&&typeof Au.type=="string"&&INTERNAL_OPERATION_TYPES.includes(Au.type)}objectType({componentId:lazyType(()=>ComponentIdSchema$1),path:stringType().describe("The path to the list of component property objects in the data model.")}).strict().describe("REF:#/$defs/TemplateChildList|A template for generating a dynamic list of children from a data model list. The `componentId` is the component to use as a template.");const AnyComponentSchema=lazyType(()=>ComponentCommonSchema.extend({component:stringType()}).passthrough().refine(Au=>Au.component!=="Surface",{message:'Component type cannot be "Surface". "Surface" is a top-level protocol container defined in createSurface, not a child component.'})),ComponentsListSchema=arrayType(AnyComponentSchema).min(1);recordType(stringType(),anyType());const ComponentIdSchema$1=markChildRef(stringType().describe("REF:#/$defs/ComponentId|The unique identifier for a component, used for both definitions and references within the same surface."),"component-id"),CallIdSchema=stringType().describe("REF:#/$defs/CallId|The unique identifier for a function call."),DataBindingSchema$1=objectType({path:stringType().describe("A JSON Pointer path to a value in the data model.")}).strict().describe("REF:#/$defs/DataBinding"),FunctionCommonSchema=objectType({call:stringType().describe("The name of the function to call."),catalogId:stringType().describe("The catalog ID for this function, overriding any surface-level default catalogId.").optional()}).describe("REF:#/$defs/FunctionCommon|Baseline envelope properties common to all function calls. Function-specific argument schemas ('args') are defined individually by each function in the active catalog."),FunctionCallSchema$1=recordType(stringType(),anyType()).and(intersectionType(FunctionCommonSchema,anyType())).describe("REF:#/$defs/FunctionCall|Invokes a named function, combining common function properties with the catalog function definition."),DynamicStringSchema$1=unionType([stringType(),DataBindingSchema$1,FunctionCallSchema$1]).describe("REF:#/$defs/DynamicString|Represents a string"),DynamicBooleanSchema$1=unionType([booleanType(),DataBindingSchema$1,FunctionCallSchema$1]).describe("REF:#/$defs/DynamicBoolean|A boolean value that can be a literal, a path, or a function call returning a boolean."),AccessibilityAttributesSchema$1=objectType({label:DynamicStringSchema$1.optional(),description:DynamicStringSchema$1.optional(),live:enumType(["off","polite","assertive"]).describe("Controls screen reader announcements for dynamic updates (WAI-ARIA aria-live). 'polite' waits for user pause; 'assertive' interrupts immediately for alerts.").default("off"),hidden:DynamicBooleanSchema$1.optional()}).strict().describe("REF:#/$defs/AccessibilityAttributes|Attributes to enhance accessibility when using assistive technologies like screen readers or model understanding."),ExtensionsSchema=recordType(stringType(),unknownType()).superRefine((Au,lo)=>{for(const $u in Au)$u.match(/^[\p{XID_Start}_][\p{XID_Continue}:-]*$/u)||lo.addIssue({path:[$u],code:ZodIssueCode.custom,message:`Invalid extension key "${$u}": Keys MUST be Unicode identifiers (UAX #31).`})}).describe("REF:#/$defs/Extensions|Optional extension metadata. Keys MUST be Unicode identifiers (UAX #31). Keys starting with 'a2ui_' are reserved for official extensions."),ComponentCommonSchema=objectType({id:ComponentIdSchema$1,catalogId:stringType().describe("The catalog ID for this component, overriding any surface-level default catalogId.").optional(),accessibility:AccessibilityAttributesSchema$1.optional(),metadata:objectType({extensions:ExtensionsSchema.optional()}).strict().describe("Optional component-level metadata for vendor extensions.").optional()}).describe("REF:#/$defs/ComponentCommon");markChildRef(unionType([arrayType(ComponentIdSchema$1).describe("A static list of child component IDs."),objectType({componentId:ComponentIdSchema$1,path:stringType().describe("The path to the list of component property objects in the data model.")}).strict().describe("A template for generating a dynamic list of children from a data model list. The `componentId` is the component to use as a template.")]).describe("REF:#/$defs/ChildList"),"child-list");const DynamicValueSchema$1=unionType([stringType(),numberType(),booleanType(),arrayType(anyType()),recordType(stringType(),unknownType()).refine(Au=>!Au||!("path"in Au)&&!("call"in Au)),DataBindingSchema$1,FunctionCallSchema$1]).describe("REF:#/$defs/DynamicValue|A value that can be a literal, a path, or a function call returning any type."),DynamicNumberSchema$1=unionType([numberType(),DataBindingSchema$1,FunctionCallSchema$1]).describe("REF:#/$defs/DynamicNumber|Represents a value that can be either a literal number, a path to a number in the data model, or a function call returning a number.");unionType([arrayType(stringType()),DataBindingSchema$1,FunctionCallSchema$1]).describe("REF:#/$defs/DynamicStringList|Represents a value that can be either a literal array of strings, a path to a string array in the data model, or a function call returning a string array.");objectType({call:literalType("@index"),args:objectType({offset:DynamicNumberSchema$1.optional()}).optional()}).describe("REF:#/$defs/IndexSystemFunction|Returns the 0-based index of the current item when rendering a dynamic list from a template. This function MUST ONLY be available when evaluating template items within a list context.");const CheckRuleSchema$1=objectType({condition:unionType([DataBindingSchema$1,FunctionCallSchema$1]).describe("Path or function call evaluating to a structured validation result object."),message:stringType().describe("Optional fallback error message.").optional()}).strict().describe("REF:#/$defs/CheckRule|A single validation check rule applied to an input component. The condition function or path evaluates to a structured validation result object.");objectType({checks:arrayType(CheckRuleSchema$1).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional()}).describe("REF:#/$defs/Checkable|Properties for components that support renderer-side checks.");unionType([objectType({event:objectType({name:stringType().describe("The name of the action to be dispatched to the agent."),userMessage:DynamicStringSchema$1.optional(),context:recordType(stringType(),DynamicValueSchema$1).describe("A JSON object containing the key-value pairs for the action context. Values can be literals or paths. Use literal values unless the value must be dynamically bound to the data model. Do NOT use paths for static IDs.").optional()}).strict().describe("The event to dispatch to the agent.")}).strict().describe("Triggers an agent-side event."),objectType({functionCall:FunctionCallSchema$1}).strict().describe("Executes a renderer or agent-side function.")]).describe("REF:#/$defs/Action|Defines an interaction handler that can either trigger an agent-side event or execute a local renderer-side function.");objectType({component:literalType("Surface").optional(),child:literalType("root").optional()}).strict().describe("REF:#/$defs/Surface|The reserved canonical container component representing an A2UI surface. The Surface component is immutable and always has 'child': 'root'.");const FunctionResponseSchema=objectType({functionCallId:CallIdSchema,value:anyType().describe("The return value of the function.").optional(),error:objectType({code:stringType(),message:stringType()}).strict().describe("An error object indicating failure of the function execution.").optional()}).strict().superRefine((Au,lo)=>{const $u="value"in Au,Ru="error"in Au;($u&&Ru||!$u&&!Ru)&&lo.addIssue({code:ZodIssueCode.custom,message:'FunctionResponse must have either "value" or "error", but not both or neither.'})}).describe("REF:#/$defs/FunctionResponse|The return response matching a callAgentFunction or callRendererFunction invocation."),CreateSurfaceMessageSchema=objectType({version:literalType("v1.0"),createSurface:objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be rendered. It must be globally unique for the renderer's lifetime."),catalogId:stringType().describe("A string that uniquely identifies the default catalog for this surface. It is recommended to prefix this with an internet domain that you own, to avoid conflicts e.g. 'mycompany.com:somecatalog'. Components and function calls that do not explicitly specify a catalogId will use this surface-level default catalogId.").optional(),sendDataModel:booleanType().describe("If true, the renderer will send the full data model of this surface in the metadata of every A2A message sent to the agent that created the surface. Defaults to false.").optional(),components:ComponentsListSchema.optional(),dataModel:recordType(stringType(),anyType()).describe("The initial root data model object for the surface.").optional(),metadata:objectType({extensions:ExtensionsSchema.optional()}).strict().describe("Optional surface-level metadata.").optional()}).strict().describe("Signals the renderer to create a new surface and begin rendering it. Creating a surface implicitly instantiates the canonical 'Surface' container component ('common_types.json#/$defs/Surface') with 'child': 'root'. It is an error to try to create a surface with an existing ID without first deleting it; surfaceId MUST be globally unique for the renderer's lifetime. When this message is sent, the renderer expects 'updateComponents' and/or 'updateDataModel' messages for the same surfaceId to define the component tree.")}).strict(),UpdateComponentsMessageSchema=objectType({version:literalType("v1.0"),updateComponents:objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be updated. It must be globally unique for the renderer's lifetime."),components:ComponentsListSchema}).strict().describe("Updates a surface with a new set of components. This message can be sent multiple times to update the component tree of an existing surface. One of the components in one of the components lists MUST have an 'id' of 'root' to serve as the root of the component tree. The createSurface message MUST have been previously sent for this surfaceId.")}).strict(),UpdateDataModelMessageSchema=objectType({version:literalType("v1.0"),updateDataModel:objectType({surfaceId:stringType().describe("The unique identifier for the UI surface this data model update applies to. It must be globally unique for the renderer's lifetime."),path:stringType().describe("An optional path to a location within the data model (e.g., '/user/name'). If omitted, or set to '/', refers to the entire data model.").optional(),value:anyType().describe("The data to be updated in the data model. To delete the key/value at 'path', set 'value' explicitly to null.")}).strict().describe("Updates the data model for an existing surface. This message can be sent multiple times to update the data model. The createSurface message MUST have been previously sent for this surfaceId.")}).strict(),DeleteSurfaceMessageSchema=objectType({version:literalType("v1.0"),deleteSurface:objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be deleted. It must be globally unique for the renderer's lifetime.")}).strict().describe("Signals the renderer to delete the surface identified by 'surfaceId'. The createSurface message MUST have been previously sent for this surfaceId.")}).strict(),CallRendererFunctionMessageSchema=objectType({version:literalType("v1.0"),callRendererFunction:objectType({functionCallId:CallIdSchema,callFunction:intersectionType(FunctionCallSchema$1,anyType())}).strict().describe("Signals the renderer to execute a function locally on behalf of the agent.")}).strict(),AgentFunctionResponseMessageSchema=objectType({version:literalType("v1.0"),agentFunctionResponse:FunctionResponseSchema}).strict(),AgentToRendererMessageSchema=unionType([CreateSurfaceMessageSchema,UpdateComponentsMessageSchema,UpdateDataModelMessageSchema,DeleteSurfaceMessageSchema,CallRendererFunctionMessageSchema,AgentFunctionResponseMessageSchema]);class V1Point0Adapter extends BaseVersionAdapter{constructor(){super(...arguments),this.version="v1.0",this.schema=AgentToRendererMessageSchema}getNativeActionKeys(){return[...INTERNAL_OPERATION_TYPES]}extractOperationsFromObject(lo){const $u=[];if("createSurface"in lo){const Ru=lo.createSurface;$u.push({type:"createSurface",surfaceId:String(Ru?.surfaceId||""),catalogId:typeof Ru?.catalogId=="string"?Ru.catalogId:void 0,sendDataModel:!!Ru?.sendDataModel,components:Array.isArray(Ru?.components)?Ru.components:void 0,dataModel:Ru?.dataModel&&typeof Ru.dataModel=="object"&&!Array.isArray(Ru.dataModel)?Ru.dataModel:void 0,version:typeof lo.version=="string"?lo.version:this.version})}if("updateComponents"in lo){const Ru=lo.updateComponents;$u.push({type:"updateComponents",surfaceId:String(Ru?.surfaceId||""),components:Array.isArray(Ru?.components)?Ru.components:[]})}if("updateDataModel"in lo){const Ru=lo.updateDataModel;$u.push({type:"updateDataModel",surfaceId:String(Ru?.surfaceId||""),path:typeof Ru?.path=="string"?Ru.path:void 0,value:Ru?.value})}if("deleteSurface"in lo){const Ru=lo.deleteSurface;$u.push({type:"deleteSurface",surfaceId:String(Ru?.surfaceId||"")})}if("callRendererFunction"in lo){const Ru=lo.callRendererFunction,Iu=Ru?.callFunction||{};$u.push({type:"callRendererFunction",functionCallId:String(Ru?.functionCallId||""),call:String(Iu?.call||""),version:this.version,catalogId:typeof Iu?.catalogId=="string"?Iu.catalogId:void 0,args:Iu?.args&&typeof Iu.args=="object"&&!Array.isArray(Iu.args)?Iu.args:{}})}if("agentFunctionResponse"in lo){const Ru=lo.agentFunctionResponse;$u.push({type:"agentFunctionResponse",functionCallId:String(Ru?.functionCallId||""),version:this.version,value:Ru?.value,error:Ru?.error&&typeof Ru.error=="object"?Ru.error:void 0})}return $u}}class VersionAdapterFactory{constructor(){this.adapters=new Map([["0.8",new V0Point8Adapter],["0.9",new V0Point9Adapter],["0.9.1",new V0Point9Adapter],["1.0",new V1Point0Adapter]])}getAllKnownActions(){const lo=new Set;for(const $u of this.adapters.values())if($u.validActions)for(const Ru of $u.validActions)lo.add(Ru);return lo}registerAdapter(lo){const $u=toCanonicalVersion(lo.version)??normalizeVersionString(lo.version);this.adapters.set($u,lo)}getAdapter(lo){const $u=toCanonicalVersion(lo)??normalizeVersionString(lo),Ru=this.adapters.get($u);if(!Ru){const Iu=Array.from(new Set(Array.from(this.adapters.keys()).map(Pu=>Pu.startsWith("v")?Pu:`v${Pu}`))).sort().join(", ");throw new A2uiValidationError(`[VersionAdapterFactory] Unsupported protocol version '${lo}'. Supported versions: ${Iu}.`)}return Ru}resolveFromPayload(lo){const $u=Array.isArray(lo)?lo[0]:lo;if(typeof $u=="object"&&$u!==null){if("messages"in $u&&Array.isArray($u.messages))return this.resolveFromPayload($u.messages);if("version"in $u){const Ru=$u.version;if(typeof Ru!="string")throw new A2uiValidationError(`[VersionAdapterFactory] Message payload is missing a valid 'version' string: 'version' property must be a string, got ${typeof Ru}.`);return this.getAdapter(Ru)}if("beginRendering"in $u||"surfaceUpdate"in $u||"dataModelUpdate"in $u||"deleteSurface"in $u)return this.getAdapter("v0.8")}throw new A2uiValidationError("[VersionAdapterFactory] Message payload is missing a valid 'version' string.")}static registerAdapter(lo){defaultVersionAdapterFactory.registerAdapter(lo)}static getAdapter(lo){return defaultVersionAdapterFactory.getAdapter(lo)}static resolveFromPayload(lo){return defaultVersionAdapterFactory.resolveFromPayload(lo)}static getAllKnownActions(){return defaultVersionAdapterFactory.getAllKnownActions()}}const defaultVersionAdapterFactory=new VersionAdapterFactory;registerKnownActionsProvider(()=>defaultVersionAdapterFactory.getAllKnownActions());const schemaKeysCache=new WeakMap;function getKnownSchemaKeys(Au){if(schemaKeysCache.has(Au))return schemaKeysCache.get(Au);const lo=(()=>{let $u=Au;for(;$u;){if($u instanceof ZodObject||$u._def?.typeName==="ZodObject"){if($u._def?.unknownKeys==="passthrough")return null;const Ru=typeof $u.shape=="function"?$u.shape():$u.shape;return Ru&&typeof Ru=="object"?new Set(Object.keys(Ru)):null}if($u instanceof ZodEffects||$u._def?.typeName==="ZodEffects"){$u=$u._def.schema;continue}if($u instanceof ZodOptional||$u instanceof ZodNullable||$u._def?.typeName==="ZodOptional"||$u._def?.typeName==="ZodNullable"){$u=$u._def.innerType;continue}if($u instanceof ZodDefault||$u._def?.typeName==="ZodDefault"){$u=$u._def.innerType;continue}if($u instanceof ZodCatch||$u._def?.typeName==="ZodCatch"){$u=$u._def.innerType;continue}if($u instanceof ZodIntersection||$u._def?.typeName==="ZodIntersection"){const Ru=getKnownSchemaKeys($u._def.left),Iu=getKnownSchemaKeys($u._def.right);return!Ru||!Iu?null:new Set([...Ru,...Iu])}if($u instanceof ZodUnion||$u._def?.typeName==="ZodUnion"){const Ru=$u._def.options,Iu=new Set;for(const Pu of Ru){const Ou=getKnownSchemaKeys(Pu);if(!Ou)return null;for(const Mu of Ou)Iu.add(Mu)}return Iu}return null}return null})();return schemaKeysCache.set(Au,lo),lo}function validateFunctionArgs(Au,lo,$u){if(!lo||typeof lo!="object"||Array.isArray(lo))return;const Ru=Object.keys(lo);if(Ru.length>MAX_FUNCTION_CALL_ARGS)throw new A2uiExpressionError(`Function call '${Au}' exceeds maximum allowed arguments count (${MAX_FUNCTION_CALL_ARGS})`,Au);const Iu=$u?.functions?.get?.(Au);if(!Iu?.schema)return;const Pu=getKnownSchemaKeys(Iu.schema);if(Pu){for(const Ou of Ru)if(!Pu.has(Ou))throw new A2uiExpressionError(`Unknown argument '${Ou}' passed to function '${Au}'`,Au);if(Ru.length>Pu.size)throw new A2uiExpressionError(`Too many arguments for function '${Au}': expected at most ${Pu.size}, received ${Ru.length}`,Au)}}function resolveContextIndex(Au){let lo=Au;for(;lo;){if(lo.explicitIndex!==void 0&&Number.isFinite(lo.explicitIndex))return lo.explicitIndex;if(!(lo instanceof DataContext)&&typeof lo.getIndex=="function"){const $u=lo.getIndex();if($u!==void 0&&Number.isFinite($u))return $u}if(!(lo instanceof DataContext)&&typeof lo.index=="number"&&Number.isFinite(lo.index))return lo.index;if(typeof lo.path=="string"){const $u=lo.path.split("/").filter(Boolean);if($u.length>0&&/^\d+$/.test($u[$u.length-1]))return parseInt($u[$u.length-1],10)}lo=lo.parent}}const MAX_DYNAMIC_VALUE_DEPTH=1e3;class DataContext{constructor(lo,$u,Ru,Iu){this.surface=lo,this.path=$u,this.dataModel=lo.dataModel,this.functionInvoker=lo.defaultCatalog.invoker,this.explicitIndex=Ru,this.parent=Iu,this.warnedPaths=Iu?Iu.warnedPaths:new Set}getIndex(){return resolveContextIndex(this)}get index(){return this.getIndex()}set(lo,$u){const Ru=this.resolvePath(lo);this.dataModel.set(Ru,$u)}static isDataBindingObject(lo){return"path"in lo&&typeof lo.path=="string"&&!("componentId"in lo)}static isFunctionCallObject(lo){return"call"in lo&&typeof lo.call=="string"}static containsDynamicValue(lo){if(lo===null||typeof lo!="object")return!1;if(Array.isArray(lo))return lo.some(Ru=>DataContext.containsDynamicValue(Ru));const $u=lo;return DataContext.isDataBindingObject($u)||DataContext.isFunctionCallObject($u)?!0:Object.values($u).some(Ru=>DataContext.containsDynamicValue(Ru))}emitMissingDataBindingWarning(lo){typeof this.dataModel?.hasPath=="function"&&!this.dataModel.hasPath(lo)&&!this.warnedPaths.has(lo)&&(this.warnedPaths.add(lo),this.surface?.dispatchWarning?.({code:"MISSING_DATA_BINDING",path:lo,message:`Preflight DataBinding Warning: The bound JSON Pointer '${lo}' does not physically exist in the active DataModel. Evaluating to None.`}))}resolveDynamicValue(lo,$u=0){if($u>MAX_DYNAMIC_VALUE_DEPTH){const Iu=new A2uiExpressionError(`Maximum dynamic value nesting depth exceeded (${MAX_DYNAMIC_VALUE_DEPTH})`);this.dispatchExpressionError(Iu,"DynamicValue");return}if(lo===null||typeof lo!="object")return lo;if(Array.isArray(lo))return DataContext.containsDynamicValue(lo)?lo.map(Iu=>this.resolveDynamicValue(Iu,$u+1)):lo;const Ru=lo;if(DataContext.isDataBindingObject(Ru)){const Iu=this.resolvePath(lo.path),Pu=this.dataModel.get(Iu);return Pu===void 0&&this.emitMissingDataBindingWarning(Iu),Pu}return DataContext.isFunctionCallObject(Ru)?this.resolveFunctionCallValue(lo,$u):this.resolvePlainObjectValue(Ru,$u)}resolveFunctionCallValue(lo,$u=0){let Ru;try{Ru=this.resolveFunctionCatalog(lo.catalogId),validateFunctionArgs(lo.call,lo.args,Ru)}catch(Mu){this.dispatchExpressionError(Mu,lo.call);return}const Iu={};for(const[Mu,Du]of Object.entries(lo.args??{}))Iu[Mu]=this.resolveDynamicValue(Du,$u+1);const Pu=new AbortController,Ou=this.evaluateFunctionReactive(lo.call,Iu,Pu.signal,lo.catalogId,Ru.invoker);if(Ou!==void 0)return isSignal(Ou)?peekValue(Ou):Ou}resolvePlainObjectValue(lo,$u=0){if(!DataContext.containsDynamicValue(lo))return lo;const Ru={};for(const[Iu,Pu]of Object.entries(lo))Ru[Iu]=this.resolveDynamicValue(Pu,$u+1);return Ru}subscribeDynamicValue(lo,$u){const Ru=this.resolveSignal(lo);let Iu=!0,Pu=peekValue(Ru);const Ou=effect(()=>{const Mu=getValue(Ru);Pu=Mu,Iu||$u(Mu)});return Iu=!1,{get value(){return Pu},unsubscribe:()=>{Ou(),Ru.unsubscribe?.()}}}resolveSignal(lo,$u=0){if($u>MAX_DYNAMIC_VALUE_DEPTH){const Mu=new A2uiExpressionError(`Maximum dynamic value nesting depth exceeded (${MAX_DYNAMIC_VALUE_DEPTH})`);return this.dispatchExpressionError(Mu,typeof lo=="object"&&lo&&"call"in lo?lo.call:"DynamicValue"),signal(void 0)}if(typeof lo!="object"||lo===null)return signal(lo);if(Array.isArray(lo)){if(!DataContext.containsDynamicValue(lo))return signal(lo);const Mu=lo.map(Lu=>this.resolveSignal(Lu,$u+1)),Du=computed(()=>Mu.map(Lu=>getValue(Lu)));return Du.unsubscribe=()=>{for(const Lu of Mu)Lu.unsubscribe?.()},Du}const Ru=lo;if(DataContext.isDataBindingObject(Ru)){const Mu=this.resolvePath(lo.path);return this.emitMissingDataBindingWarning(Mu),this.dataModel.getSignal(Mu)}if(DataContext.isFunctionCallObject(Ru)){const Mu=lo;let Du;try{Du=this.resolveFunctionCatalog(Mu.catalogId),validateFunctionArgs(Mu.call,Mu.args,Du)}catch(Vu){return this.dispatchExpressionError(Vu,Mu.call),signal(void 0)}const Lu={};for(const[Vu,Gu]of Object.entries(Mu.args??{}))Lu[Vu]=this.resolveSignal(Gu,$u+1);if(Object.keys(Lu).length===0){const Vu=new AbortController,Gu=this.evaluateFunctionReactive(Mu.call,{},Vu.signal,Mu.catalogId,Du.invoker),Wu=isSignal(Gu)?Gu:signal(Gu);return Wu.unsubscribe=()=>Vu.abort(),Wu}const Bu=Object.keys(Lu),ju=signal(void 0);let Fu,zu;const Uu=computed(()=>{const Vu={};for(let Gu=0;Gu<Bu.length;Gu++)Vu[Bu[Gu]]=getValue(Lu[Bu[Gu]]);return Vu}),Hu=effect(()=>{try{const Vu=getValue(Uu);Fu&&Fu.abort(),zu&&(zu(),zu=void 0),Fu=new AbortController;const Gu=this.evaluateFunctionReactive(Mu.call,Vu,Fu.signal,Mu.catalogId,Du.invoker);isSignal(Gu)?zu=effect(()=>{setValue(ju,getValue(Gu))}):setValue(ju,Gu)}catch(Vu){this.dispatchExpressionError(Vu,Mu.call),setValue(ju,void 0)}});return ju.unsubscribe=()=>{Hu(),zu&&zu(),Fu&&Fu.abort();for(let Vu=0;Vu<Bu.length;Vu++)Lu[Bu[Vu]].unsubscribe?.()},ju}if(!DataContext.containsDynamicValue(Ru))return signal(lo);const Iu=Object.entries(Ru).map(([Mu,Du])=>[Mu,this.resolveSignal(Du)]),Pu=computed(()=>{const Mu={};for(const[Du,Lu]of Iu)Mu[Du]=getValue(Lu);return Mu}),Ou=Pu.unsubscribe?.bind(Pu);return Pu.unsubscribe=()=>{Ou?.();for(const[,Mu]of Iu)Mu.unsubscribe?.()},Pu}resolveAction(lo){if("event"in lo){const $u={};if(lo.event.context)for(const[Ru,Iu]of Object.entries(lo.event.context))$u[Ru]=this.resolveDynamicValue(Iu);return{event:{...lo.event,context:$u}}}return"functionCall"in lo?this.resolveDynamicValue(lo.functionCall):lo}resolveFunctionCatalog(lo){if(lo===void 0)return this.surface.defaultCatalog;const $u=this.surface.availableCatalogs?.get(lo);if(!$u)throw new A2uiCatalogError(`Catalog not found: ${lo}`);return $u}evaluateFunctionReactive(lo,$u,Ru,Iu,Pu){const Ou=Pu??(Iu===void 0?this.functionInvoker:this.resolveFunctionCatalog(Iu).invoker);try{return Ou(lo,$u,this,Ru)}catch(Mu){this.dispatchExpressionError(Mu,lo);return}}dispatchExpressionError(lo,$u){if(lo instanceof ZodError||typeof lo=="object"&&lo!==null&&lo.name==="ZodError"){const Ru=lo,Iu=new A2uiExpressionError(`Validation failed for function '${$u}': ${Ru.message}`,$u,Ru.errors??Ru.issues);this.surface.dispatchError({code:"EXPRESSION_ERROR",message:Iu.message,expression:$u,details:Iu.details})}else if(lo instanceof A2uiExpressionError)this.surface.dispatchError({code:"EXPRESSION_ERROR",message:lo.message,expression:lo.expression,details:lo.details});else{const Ru=typeof lo=="object"&&lo!==null?lo:{};this.surface.dispatchError({code:"EXPRESSION_ERROR",message:Ru.message??`An unexpected error occurred in function ${$u}.`,expression:$u})}}nested(lo,$u){const Ru=this.resolvePath(lo);return new DataContext(this.surface,Ru,$u,this)}resolvePath(lo){if(lo.startsWith("/"))return lo;if(lo===""||lo===".")return this.path;let $u=this.path;return $u.endsWith("/")&&$u.length>1&&($u=$u.slice(0,-1)),$u==="/"&&($u=""),`${$u}/${lo}`}}const IndexApi={name:"@index",returnType:"number",allowedCallers:"rendererOnly",schema:objectType({offset:coerce.number().optional()})};createFunctionImplementation(IndexApi,(Au,lo)=>{const $u=typeof Au.offset=="number"&&Number.isFinite(Au.offset)?Au.offset:0,Ru=resolveContextIndex(lo);if(Ru===void 0||!Number.isFinite(Ru))throw new A2uiValidationError("@index function can only be evaluated inside a collection template iteration scope.");return Ru+$u});const COMPONENT_ENVELOPE_KEYS=["id","component","catalogId","catalogID"];class PayloadValidator{constructor(lo,$u){this.catalog=lo,this.config=$u,this.enforceIdentifiers=isAtLeastVersion(lo.protocolVersion,"1.0")}get allowUnknown(){return this.config?this.config.allowUnknownElements??!1:!0}validateComponent(lo,$u){const Ru=lo.id;if(typeof Ru!="string"||!Ru)throw new A2uiValidationError(`Component '${lo.component}' is missing an 'id'; entries require a valid string 'id'.`);this.assertIdentifier(Ru,`Component id '${Ru}' must be a valid UAX #31 identifier`);const Iu=lo.component,Pu=typeof Iu=="string"?Iu:$u;if(!Pu)throw new A2uiValidationError(`Cannot create component ${Ru} without a type.`);const Ou=this.catalog.components.get(Pu);if(!Ou){if(!this.allowUnknown)throw new A2uiValidationError(`Unknown component type '${Pu}' not found in catalog '${this.catalog.id}'.`);return}const Mu=stripEnvelopeKeys(lo),Du=Ou.schema.safeParse(Mu);if(!Du.success){const Lu=Du.error.errors.map(formatZodIssue).join(", ");throw new A2uiValidationError(`Validation failed for component '${Pu}' (${Ru}): ${Lu}`,Du.error.issues)}this.validateNestedFunctions(Mu)}assertFunctionIdentifiers(lo,$u){if(this.assertIdentifier(lo,`Function name '${lo}' must be a valid UAX #31 identifier`),$u&&typeof $u=="object"&&!Array.isArray($u)){const Ru=Object.keys($u);if(Ru.length>MAX_FUNCTION_CALL_ARGS)throw new A2uiValidationError(`Function call '${lo}' exceeds maximum allowed arguments count (${MAX_FUNCTION_CALL_ARGS})`);for(const Iu of Ru)this.assertIdentifier(Iu,`Function argument '${Iu}' in function '${lo}' must be a valid UAX #31 identifier`)}}validateNestedFunctions(lo){if(Array.isArray(lo)){for(const Iu of lo)this.validateNestedFunctions(Iu);return}if(typeof lo!="object"||lo===null)return;const $u=lo,Ru=$u.call??$u.function;if(typeof Ru=="string"&&Ru.length>0){const Iu=$u.args,Pu=Iu!==void 0?Iu:{},Ou=typeof $u.catalogId=="string"&&$u.catalogId.length>0?$u.catalogId:void 0;Ou&&Ou!==this.catalog.id?this.assertFunctionIdentifiers(Ru,Pu):this.validateFunction(Ru,Pu)}for(const[Iu,Pu]of Object.entries($u))Iu!=="id"&&Iu!=="component"&&this.validateNestedFunctions(Pu)}validateFunction(lo,$u){this.assertFunctionIdentifiers(lo,$u);const Ru=this.catalog.functions.get(lo)??(this.enforceIdentifiers&&lo==="@index"?IndexApi:void 0);if(!Ru){if(!this.allowUnknown)throw new A2uiValidationError(`Unrecognized function '${lo}'`);return $u??{}}if(!Ru.schema){if($u!==void 0&&(typeof $u!="object"||$u===null||Array.isArray($u)))throw new A2uiValidationError(`Validation failed for function '${lo}': Expected object, received ${Array.isArray($u)?"array":typeof $u}`);return $u??{}}const Iu=Ru.schema.safeParse($u??{});if(!Iu.success){const Pu=Iu.error.errors.map(formatZodIssue).join(", ");throw new A2uiValidationError(`Validation failed for function '${lo}': ${Pu}`,Iu.error.issues)}return Iu.data}validateTheme(lo){const $u=this.catalog.themeSchema;if(!$u)return lo;const Ru=$u.safeParse(lo);if(!Ru.success){const Iu=Ru.error.errors.map(formatZodIssue).join(", ");throw new A2uiValidationError(`Validation failed for theme: ${Iu}`,Ru.error.issues)}return Ru.data}assertIdentifier(lo,$u){if(this.enforceIdentifiers&&!isValidUax31Identifier(lo))throw new A2uiValidationError($u)}}function stripEnvelopeKeys(Au){const lo={};for(const[$u,Ru]of Object.entries(Au))COMPONENT_ENVELOPE_KEYS.includes($u)||(lo[$u]=Ru);return lo}class RpcHandler{constructor(lo,$u){if(this.pendingAgentCalls=new Map,this.isDisposed=!1,Array.isArray(lo))this.catalogs=lo,this.outboundListener=$u,this.defaultTimeoutMs=3e4;else{const Ru=lo??{};this.catalogs=Ru.catalogs??[],this.outboundListener=Ru.outboundListener,this.defaultTimeoutMs=Ru.defaultTimeoutMs??3e4}}get disposed(){return this.isDisposed}async handleCallRendererFunction(lo,$u,Ru=!1){const Iu=this.validateInboundMessage(lo);if(Iu)return await this.emitOutboundResponse(Iu),Iu;const{version:Pu,callRendererFunction:Ou}=lo,{functionCallId:Mu,callFunction:Du}=Ou,{call:Lu,catalogId:Bu,args:ju}=Du,Fu=this.resolveFunctionImplementation(Bu,Lu,$u,Pu);if("error"in Fu){const Vu=this.createResponseError(Mu,RpcErrorCode.INVALID_FUNCTION_CALL,Fu.error,Pu);return await this.emitOutboundResponse(Vu),Vu}const zu=this.checkExecutionPermissions(Fu.funcImpl,Lu,Ru);if(zu){const Vu=this.createResponseError(Mu,RpcErrorCode.INVALID_FUNCTION_CALL,zu,Pu);return await this.emitOutboundResponse(Vu),Vu}const Uu=this.parseArguments(Fu.catalog,Fu.funcImpl,ju,Lu);if("error"in Uu){const Vu=this.createResponseError(Mu,RpcErrorCode.INVALID_FUNCTION_CALL,Uu.error,Pu);return await this.emitOutboundResponse(Vu),Vu}const Hu=await this.executeFunctionSafely(Fu.funcImpl,Uu.args,$u,Mu,Pu);return await this.emitOutboundResponse(Hu),Hu}handleAgentFunctionResponse(lo){if(!lo||!lo.agentFunctionResponse)return;const{functionCallId:$u,value:Ru,error:Iu}=lo.agentFunctionResponse,Pu=this.pendingAgentCalls.get($u);if(Pu)if(this.pendingAgentCalls.delete($u),Iu){const Ou=Iu.code??RpcErrorCode.UNKNOWN_ERROR,Mu=Iu.message??"Agent function execution failed";Pu.reject(new A2uiRpcError(Mu,Ou,$u,Iu))}else Pu.resolve(Ru)}callAgentFunction(lo,$u,Ru){if(this.isDisposed)return Promise.reject(new A2uiRpcError("RpcHandler has been disposed.",RpcErrorCode.DISPOSED));if(!this.outboundListener)return Promise.reject(new A2uiRpcError("Cannot call agent function without outboundListener configured.",RpcErrorCode.NO_LISTENER));if(!$u||!$u.call)return Promise.reject(new A2uiRpcError("Missing or invalid function call name.",RpcErrorCode.INVALID_FUNCTION_CALL));const Iu=Ru??{},Pu=Iu.functionCallId??this.generateFunctionCallId(),Ou=Iu.timeoutMs??this.defaultTimeoutMs;if(this.pendingAgentCalls.has(Pu))return Promise.reject(new A2uiRpcError(`A call with functionCallId '${Pu}' is already pending.`,RpcErrorCode.DUPLICATE,Pu));const Mu={functionCallId:Pu,call:$u,effectiveTimeoutMs:Ou,version:Iu.version};return this.dispatchAgentCall(lo,Mu)}dispose(){if(!this.isDisposed){this.isDisposed=!0;for(const[lo,$u]of this.pendingAgentCalls.entries())$u.reject(new A2uiRpcError(`RpcHandler disposed while call '${lo}' was pending.`,RpcErrorCode.CANCELLED,lo));this.pendingAgentCalls.clear()}}async emitOutboundResponse(lo){if(this.outboundListener)try{const $u=this.outboundListener(lo);$u&&typeof $u.catch=="function"&&await $u}catch{}}validateInboundMessage(lo){if(!lo)return this.createResponseError("unknown",RpcErrorCode.INVALID_FUNCTION_CALL,"Inbound message is null or undefined.","unknown");const $u=lo.version;return this.isDisposed?this.createResponseError(lo.callRendererFunction?.functionCallId??"unknown",RpcErrorCode.DISPOSED,"RpcHandler has been disposed.",$u):lo.callRendererFunction?.callFunction?null:this.createResponseError(lo.callRendererFunction?.functionCallId??"unknown",RpcErrorCode.INVALID_FUNCTION_CALL,"Malformed message: missing callRendererFunction or callFunction.",$u)}resolveFunctionImplementation(lo,$u,Ru,Iu){let Pu;if(lo){if(Pu=this.catalogs.find(Mu=>Mu.id===lo),!Pu)return{error:`Catalog not found: ${lo}`}}else Ru?.surface?.defaultCatalog&&(Pu=Ru.surface.defaultCatalog);if(!Pu)return{error:"No catalog available for function resolution."};if(Pu.protocolVersion&&Iu&&!isCatalogVersionCompatible(Pu.protocolVersion,Iu))return{error:`Catalog '${Pu.id}' specification version (${Pu.protocolVersion}) does not match message protocol version (${Iu}).`};const Ou=Pu.functions?.get($u);return Ou?{funcImpl:Ou,catalog:Pu}:{error:`Function not found: ${$u}`}}checkExecutionPermissions(lo,$u,Ru){const Iu=lo.allowedCallers??"rendererOnly";return Iu==="rendererOrAgent"||Iu==="agentOnly"?lo.requiresUserActivation&&!Ru?`Function '${$u}' requires user activation context to execute.`:null:`Function '${$u}' cannot be called by agent (allowedCallers is ${Iu}).`}parseArguments(lo,$u,Ru,Iu){try{return{args:new PayloadValidator(lo,{allowUnknownElements:!1}).validateFunction(Iu,Ru)}}catch(Pu){const Ou=this.extractErrorMessage(Pu);return{error:`Invalid function arguments for '${Iu}': ${Ou}`}}}async executeFunctionSafely(lo,$u,Ru,Iu,Pu){const Ou=Pu||"v1.0";try{const Mu=await Promise.resolve(lo.execute($u,Ru)),Du=isSignal(Mu)?getValue(Mu):Mu;return{version:Ou,rendererFunctionResponse:{functionCallId:Iu,value:Du!==void 0?Du:null}}}catch(Mu){const Du=this.extractErrorMessage(Mu);return{version:Ou,rendererFunctionResponse:{functionCallId:Iu,error:{code:RpcErrorCode.EXECUTION_ERROR,message:Du||"An error occurred during function execution."}}}}}generateFunctionCallId(){if(typeof globalThis.crypto?.randomUUID=="function")return globalThis.crypto.randomUUID();const lo=Math.random().toString(36).substring(2,15).padEnd(13,"0");return`call-${Date.now()}-${lo}`}dispatchAgentCall(lo,$u){const{functionCallId:Ru,call:Iu,effectiveTimeoutMs:Pu,version:Ou}=$u;return new Promise((Mu,Du)=>{let Lu;const Bu=()=>{Lu&&(clearTimeout(Lu),Lu=void 0),this.pendingAgentCalls.delete(Ru)};Lu=this.createTimeoutTimer(Ru,Iu.call,Pu,Bu,Du),this.pendingAgentCalls.set(Ru,{resolve:ju=>{Bu(),Mu(ju)},reject:ju=>{Bu(),Du(ju)}}),this.sendOutboundMessage(lo,Ru,Iu,Ou,Bu,Du)})}createTimeoutTimer(lo,$u,Ru,Iu,Pu){if(!(Ru<=0))return setTimeout(()=>{this.pendingAgentCalls.delete(lo)&&(Iu(),Pu(new A2uiRpcError(`Agent function call '${$u}' timed out after ${Ru}ms.`,RpcErrorCode.TIMEOUT,lo)))},Ru)}sendOutboundMessage(lo,$u,Ru,Iu,Pu,Ou){const Mu={version:Iu||"v1.0",callAgentFunction:{surfaceId:lo,functionCallId:$u,callFunction:Ru}};try{const Du=this.outboundListener(Mu);Du&&typeof Du.catch=="function"&&Du.catch(Lu=>{Pu(),Ou(Lu)})}catch(Du){Pu(),Ou(Du)}}extractErrorMessage(lo){return lo instanceof Error?lo.message:String(lo)}createResponseError(lo,$u,Ru,Iu){return{version:Iu||"v1.0",rendererFunctionResponse:{functionCallId:lo,error:{code:$u,message:Ru}}}}}class MessageProcessor{constructor(lo,$u,Ru){this.catalogs=lo,this.actionHandler=$u,this.model=new SurfaceGroupModel,this.adapterRegistry=Ru?.adapterRegistry??defaultVersionAdapterFactory,this.rpc=new RpcHandler({catalogs:this.catalogs,outboundListener:Ru?.outboundListener,defaultTimeoutMs:Ru?.defaultTimeoutMs}),Ru?.validationConfig?this.validationConfig={allowOrphanComponents:!1,allowDanglingReferences:!1,allowMissingRoot:!1,allowUnknownElements:!1,...Ru.validationConfig}:this.validationConfig=void 0,this.actionHandler&&this.model.onAction.subscribe(this.actionHandler)}callAgentFunction(lo,$u,Ru){return this.rpc.callAgentFunction(lo,$u,Ru)}dispose(){this.rpc.dispose()}getRendererCapabilities(lo){if(!lo?.versions||lo.versions.length===0)throw new A2uiValidationError("At least one protocol version must be provided in CapabilitiesOptions to generate renderer capabilities.");const $u=lo.versions,Ru={};for(const Iu of $u){const Pu={supportedCatalogIds:this.catalogs.map(Mu=>Mu.id)},Ou=lo?.includeInlineCatalogs?this.catalogs.map(Mu=>compareSemVer(Iu,"1.0")>=0?generateCatalogSchema(Mu,{componentEnvelopeRef:lo?.componentEnvelopeRef,protocolVersion:Iu}):this.generateLegacyInlineCatalog(Mu,lo?.componentEnvelopeRef??"common_types.json#/$defs/ComponentCommon")):void 0;Ou&&(Pu.inlineCatalogs=Ou),Ru[Iu]=Pu}return Ru}getClientCapabilities(lo){return this.getRendererCapabilities(lo)}generateLegacyInlineCatalog(lo,$u="common_types.json#/$defs/ComponentCommon"){const Ru=generateCatalogSchema(lo,{componentEnvelopeRef:$u}),Iu=Ru.components||{},Pu=Ru.functions,Ou=[];for(const Lu of lo.functions.values()){const Bu=Pu?.[Lu.name];Ou.push({name:Lu.name,description:Lu.description,returnType:Lu.returnType,parameters:Bu?.properties?.args??{type:"object",properties:{}}})}const Du=Ru.$defs?.theme?.properties;return{catalogId:lo.id,components:Iu,...Ou.length>0?{functions:Ou}:{},...Du?{theme:Du}:{}}}getRendererDataModel(lo){const $u=Array.from(this.model.surfacesMap.values()).filter(Ou=>Ou.sendDataModel);if($u.length===0)return;if(lo!==void 0){const Ou={};for(const Mu of $u){const Du=Mu.defaultCatalog?.protocolVersion;(!Du||isCatalogVersionCompatible(Du,lo))&&(Ou[Mu.id]=Mu.dataModel.get("/"))}return Object.keys(Ou).length===0?void 0:{version:lo,surfaces:Ou}}const Ru=new Set;for(const Ou of $u)if(Ou.defaultCatalog?.protocolVersion){const Mu=toCanonicalVersion(Ou.defaultCatalog.protocolVersion),Du=Mu?`v${Mu}`:Ou.defaultCatalog.protocolVersion;Ru.add(Du)}if(Ru.size>1)throw new A2uiValidationError(`Multiple protocol versions detected among active surfaces: ${Array.from(Ru).sort().join(", ")}. Specify a target protocol version in getRendererDataModel(version).`);const Iu=Ru.size===1?Ru.values().next().value:"v1.0",Pu={};for(const Ou of $u)Pu[Ou.id]=Ou.dataModel.get("/");return{version:Iu,surfaces:Pu}}getClientDataModel(lo){return this.getRendererDataModel(lo)}resolvePath(lo,$u){return DataModel.resolvePath(lo,$u)}getSurfaces(){return this.model.surfacesMap}getSurface(lo){return this.model.getSurface(lo)}onSurfaceCreated(lo){return this.model.onSurfaceCreated.subscribe(lo)}onSurfaceDeleted(lo){return this.model.onSurfaceDeleted.subscribe(lo)}processMessages(lo,$u){const Ru=this.prepareOperations(lo);for(const Iu of Ru)this.processOperation(Iu,$u)}async processMessagesAsync(lo,$u){const Ru=this.prepareOperations(lo),Iu=[];for(const Pu of Ru){const Ou=await this.processOperationAsync(Pu,$u);Ou&&Iu.push(Ou)}return Iu}prepareOperations(lo){return!lo||Array.isArray(lo)&&lo.length===0?[]:(this.validationConfig&&validateRecursionAndPaths(lo),this.validationConfig?.targetVersion&&this.validateTargetVersion(lo),isInternalOperation(lo)?[lo]:this.adapterRegistry.resolveFromPayload(lo).extractOperations(lo))}validateTargetVersion(lo){const $u=this.validationConfig?.targetVersion;if(!$u)return;const Ru=Iu=>{if(typeof Iu=="object"&&Iu!==null&&"version"in Iu){const Pu=Iu.version;if(Pu){const Ou=toCanonicalVersion(Pu)??Pu,Mu=toCanonicalVersion($u)??$u;if(Ou!==Mu)throw new A2uiValidationError(`Message version '${Pu}' does not match expected target version '${$u}'`)}}};if(Array.isArray(lo))for(const Iu of lo)Ru(Iu);else Ru(lo)}applyStateOperation(lo){if(this.validationConfig?.allowedMessages&&!this.validationConfig.allowedMessages.includes(lo.type))throw new A2uiValidationError(`Operation '${lo.type}' is not permitted by ValidationConfig.allowedMessages`);switch(lo.type){case"createSurface":this.processCreateSurfaceOp(lo);break;case"deleteSurface":this.processDeleteSurfaceOp(lo);break;case"updateComponents":this.processUpdateComponentsOp(lo);break;case"updateDataModel":this.processUpdateDataModelOp(lo);break;case"agentFunctionResponse":this.rpc.handleAgentFunctionResponse({version:lo.version??"v1.0",agentFunctionResponse:{functionCallId:lo.functionCallId,value:lo.value,error:lo.error}});break}}resolveRpcDataContext(lo){const $u=(lo.catalogId?this.catalogs.find(Ou=>Ou.id===lo.catalogId):void 0)??this.catalogs[0],Ru=(lo.catalogId?Array.from(this.model.surfacesMap.values()).find(Ou=>Ou.defaultCatalog?.id===lo.catalogId||Ou.availableCatalogs?.has(lo.catalogId)):void 0)??this.model.surfacesMap.values().next().value;if(Ru)return new DataContext(Ru,"/");const Iu=`_rpc_fallback_${lo.functionCallId||"default"}`,Pu=new Map;for(const Ou of this.catalogs)$u?.protocolVersion&&Ou.protocolVersion&&isCatalogVersionCompatible($u.protocolVersion,Ou.protocolVersion)&&Pu.set(Ou.id,Ou);return $u&&Pu.set($u.id,$u),new DataContext(new SurfaceModel(Iu,$u,Pu),"/")}processOperation(lo,$u){if(lo.type==="callRendererFunction"){const Ru=this.resolveRpcDataContext(lo),Iu=$u?.isUserActivated??lo.isUserActivated??!1,Pu={version:lo.version??"v1.0",callRendererFunction:{functionCallId:lo.functionCallId,callFunction:{call:lo.call,catalogId:lo.catalogId,args:lo.args}}};this.rpc.handleCallRendererFunction(Pu,Ru,Iu).catch(Ou=>{console.error(`Unhandled error in callRendererFunction (${lo.call}):`,Ou)});return}this.applyStateOperation(lo)}async processOperationAsync(lo,$u){if(lo.type==="callRendererFunction"){const Ru=this.resolveRpcDataContext(lo),Iu=$u?.isUserActivated??lo.isUserActivated??!1,Pu={version:lo.version??"v1.0",callRendererFunction:{functionCallId:lo.functionCallId,callFunction:{call:lo.call,catalogId:lo.catalogId,args:lo.args}}};return await this.rpc.handleCallRendererFunction(Pu,Ru,Iu)}return this.applyStateOperation(lo),null}processCreateSurfaceOp(lo){const{surfaceId:$u,catalogId:Ru,theme:Iu,sendDataModel:Pu,components:Ou,dataModel:Mu}=lo,Du=Ru!==void 0?this.catalogs.find(zu=>zu.id===Ru):this.catalogs[0];if(!Du)throw new A2uiStateError(`Catalog not found: ${Ru}`);const Lu=lo.version;if(Du.protocolVersion&&Lu&&!isCatalogVersionCompatible(Du.protocolVersion,Lu))throw new A2uiValidationError(`Surface '${$u}' catalog '${Ru??Du.id}' specification version (${Du.protocolVersion}) does not match message protocol version (${Lu}).`);if(this.model.getSurface($u))throw new A2uiStateError(`Surface ${$u} already exists.`);let Bu=Iu;if(Iu&&Du.themeSchema)try{Bu=new PayloadValidator(Du,this.validationConfig).validateTheme(Iu)}catch(zu){throw zu instanceof A2uiValidationError?new A2uiValidationError(zu.message.replace(/^Validation failed for theme:/,`Validation failed for theme on surface '${$u}':`),zu.details):zu}const ju=new Map(this.catalogs.filter(zu=>isCatalogVersionCompatible(zu.protocolVersion,Du.protocolVersion)).map(zu=>[zu.id,zu])),Fu=new SurfaceModel($u,Du,ju,Bu,Pu??!1,void 0,lo.rootId??"root");this.model.addSurface(Fu),Mu&&Fu.dataModel.set("/",Mu),Ou&&Ou.length>0&&this.processUpdateComponentsOp({type:"updateComponents",surfaceId:$u,components:Ou})}processDeleteSurfaceOp(lo){lo.surfaceId&&this.model.deleteSurface(lo.surfaceId)}validateComponentProperties(lo,$u){const{id:Ru,component:Iu}=lo,Pu=lo.catalogId??lo.catalogID;if(typeof Ru!="string"||!Ru)throw new A2uiValidationError(`Component '${Iu}' is missing an 'id'; entries require a valid string 'id'.`);let Ou=$u.defaultCatalog;if(typeof Pu=="string"&&Pu){const Du=$u.availableCatalogs.get(Pu);if(!Du){const Lu=this.catalogs.find(Bu=>Bu.id===Pu);throw Lu?new A2uiValidationError(`Component '${Ru}' catalog '${Pu}' specification version (${Lu.protocolVersion}) does not match surface default catalog version (${$u.defaultCatalog.protocolVersion}).`):new A2uiValidationError(`Unknown catalog ID '${Pu}' for component '${Ru}'. Available catalogs: ${this.catalogs.map(Bu=>Bu.id).join(", ")}`)}Ou=Du}const Mu=$u.componentsModel.get(Ru);new PayloadValidator(Ou,this.validationConfig).validateComponent(lo,Mu?.type)}applyComponentUpdate(lo,$u){const{id:Ru,component:Iu,...Pu}=lo;if(typeof Ru!="string")return;const Ou=lo.catalogId??lo.catalogID,Mu=$u.componentsModel.get(Ru);let Du=$u.defaultCatalog;if(typeof Ou=="string"&&Ou){const Lu=$u.availableCatalogs.get(Ou);Lu&&(Du=Lu)}if(Mu){const Lu=typeof Iu=="string"?Iu:Mu.type;if(Lu!==Mu.type||Ou&&Mu.catalog?.id!==Du.id){$u.componentsModel.removeComponent(Ru);const Bu=new ComponentModel(Ru,Lu,Pu,Du);$u.componentsModel.addComponent(Bu)}else Mu.properties=Pu}else{if(typeof Iu!="string"||!Iu)throw new A2uiValidationError(`Cannot create component ${Ru} without a type.`);const Lu=new ComponentModel(Ru,Iu,Pu,Du);$u.componentsModel.addComponent(Lu)}}processUpdateComponentsOp(lo){if(!lo.surfaceId)return;const $u=this.model.getSurface(lo.surfaceId);if(!$u)throw new A2uiStateError(`Surface not found for message: ${lo.surfaceId}`);for(const Ru of lo.components)this.validateComponentProperties(Ru,$u);this.validateCompositionConstraints($u,lo.components),this.validateCandidateTopology($u,lo.components);for(const Ru of lo.components)this.applyComponentUpdate(Ru,$u)}processUpdateDataModelOp(lo){if(!lo.surfaceId)return;const $u=this.model.getSurface(lo.surfaceId);if(!$u)throw new A2uiStateError(`Surface not found for message: ${lo.surfaceId}`);const Ru=lo.path||"/",Iu=lo.value;$u.dataModel.set(Ru,Iu)}validateParentConstraints(lo,$u,Ru,Iu){if(!Iu||Iu.length===0){if((lo==="root"||this.validationConfig&&this.validationConfig.allowOrphanComponents===!1)&&!Ru.includes("Surface"))throw new A2uiValidationError(`Component '${lo}' (${$u}) cannot be placed under parent 'Surface' (Surface). Allowed parents: ${JSON.stringify(Ru)}.`,void 0,"UNALLOWED_PARENT");return}for(const Pu of Iu)if(!Ru.includes(Pu.parentType))throw new A2uiValidationError(`Component '${lo}' (${$u}) cannot be placed under parent '${Pu.parentId}' (${Pu.parentType||"unknown"}). Allowed parents: ${JSON.stringify(Ru)}.`,void 0,"UNALLOWED_PARENT")}validateChildConstraints(lo,$u,Ru,Iu,Pu){for(const Ou of Iu){const Mu=Pu.get(Ou);if(Mu&&!Ru.includes(Mu))throw new A2uiValidationError(`Container '${lo}' (${$u}) cannot contain child '${Ou}' (${Mu}). Allowed children: ${JSON.stringify(Ru)}.`,void 0,"UNALLOWED_CHILD")}}buildCompositionTopology(lo,$u){const Ru=new Map,Iu=new Map,Pu=new Map;for(const[Mu,Du]of lo.componentsModel.entries){Ru.set(Mu,Du.type),Du.catalog&&Iu.set(Mu,Du.catalog);const Lu=lo.componentsModel.getChildIds(Mu);Lu.length>0&&Pu.set(Mu,Lu)}for(const Mu of $u){const{id:Du,component:Lu,...Bu}=Mu;if(typeof Du!="string")continue;let ju=lo.defaultCatalog;const Fu=Mu.catalogId??Mu.catalogID;if(typeof Fu=="string"&&Fu){const Gu=lo.availableCatalogs.get(Fu);Gu&&(ju=Gu,Iu.set(Du,Gu))}const zu=lo.componentsModel.get(Du),Uu=(typeof Lu=="string"?Lu:zu?.type)??"";Uu&&Ru.set(Du,Uu);const Hu={id:Du,component:Uu,...Bu},Vu=Array.from(getComponentReferences(Hu,ju)).map(([Gu])=>Gu);Vu.length>0?Pu.set(Du,Vu):Pu.delete(Du)}const Ou=new Map;for(const[Mu,Du]of Pu.entries()){const Lu=Ru.get(Mu)||"Unknown";for(const Bu of Du){const ju=Ou.get(Bu)??[];ju.push({parentId:Mu,parentType:Lu}),Ou.set(Bu,ju)}}return{typeMap:Ru,compCatalogMap:Iu,childMap:Pu,parentMap:Ou}}validateCompositionConstraints(lo,$u){const{typeMap:Ru,compCatalogMap:Iu,childMap:Pu,parentMap:Ou}=this.buildCompositionTopology(lo,$u);for(const[Mu,Du]of Ru.entries()){const Bu=(Iu.get(Mu)??lo.defaultCatalog).components.get(Du);Bu&&(Bu.allowedParents&&Bu.allowedParents.length>0&&this.validateParentConstraints(Mu,Du,Bu.allowedParents,Ou.get(Mu)),Bu.allowedChildren&&Bu.allowedChildren.length>0&&this.validateChildConstraints(Mu,Du,Bu.allowedChildren,Pu.get(Mu)||[],Ru))}}validateCandidateTopology(lo,$u){if(!this.validationConfig)return;const Ru=new SurfaceComponentsModel(lo.defaultCatalog);for(const[Iu,Pu]of lo.componentsModel.entries)Ru.addComponent(new ComponentModel(Iu,Pu.type,Pu.properties,Pu.catalog));for(const Iu of $u){const{id:Pu,component:Ou,...Mu}=Iu;if(typeof Pu!="string"||!Pu)continue;const Du=Iu.catalogId??Iu.catalogID;let Lu=lo.defaultCatalog;if(typeof Du=="string"&&Du){const Fu=lo.availableCatalogs.get(Du);Fu&&(Lu=Fu)}const Bu=Ru.get(Pu),ju=(typeof Ou=="string"?Ou:Bu?.type)||"";ju&&(Bu?ju!==Bu.type||Du&&Bu.catalog?.id!==Lu.id?(Ru.removeComponent(Pu),Ru.addComponent(new ComponentModel(Pu,ju,Mu,Lu))):Bu.properties=Mu:Ru.addComponent(new ComponentModel(Pu,ju,Mu,Lu)))}Ru.validateTopology({...this.validationConfig,rootId:this.validationConfig.rootId??lo.rootId})}}class ComponentContext{constructor(lo,$u,Ru="/",Iu,Pu){const Ou=lo.componentsModel.get($u);if(!Ou)throw new A2uiStateError(`Component not found: ${$u}`);this.componentModel=Ou,this.surfaceComponents=lo.componentsModel,this.theme=lo.theme,this.dataContext=new DataContext(lo,Ru,Pu,Iu),this._actionDispatcher=Mu=>lo.dispatchAction(Mu,this.componentModel.id)}dispatchAction(lo){return this._actionDispatcher(lo)}}function scrapeSchemaBehavior(Au){return getFieldBehavior(Au)}function unwrapZodSchema(Au){let lo=Au;for(;lo;){const $u=lo._def?.typeName;if($u==="ZodOptional"||$u==="ZodNullable"||$u==="ZodDefault"||$u==="ZodReadonly")lo=lo._def.innerType;else if($u==="ZodEffects")lo=lo._def.schema;else if($u==="ZodBranded")lo=lo._def.type;else if($u==="ZodLazy")lo=lo._def.getter();else break}return lo}function getRefDefName(Au){let lo=Au,$u="";for(;lo&&($u=lo.description??lo._def?.description??"",!$u);){const Iu=lo._def?.typeName;if(Iu==="ZodOptional"||Iu==="ZodNullable"||Iu==="ZodDefault"||Iu==="ZodReadonly")lo=lo._def.innerType;else if(Iu==="ZodEffects")lo=lo._def.schema;else if(Iu==="ZodBranded")lo=lo._def.type;else if(Iu==="ZodLazy")lo=lo._def.getter();else break}if(!$u||!$u.startsWith("REF:"))return"";const Ru=$u.slice(4);return extractRefDefName(Ru.split("|")[0])}function isCheckableField(Au){const lo=getRefDefName(Au);if(lo==="Checkable"||lo==="CheckRule")return!0;const $u=unwrapZodSchema(Au);if($u?._def?.typeName==="ZodArray"){const Ru=$u._def.type;if(getRefDefName(Ru)==="CheckRule")return!0}return!1}function isActionOption(Au){if(getRefDefName(Au)==="Action")return!0;const $u=unwrapZodSchema(Au)._def;return $u?.typeName==="ZodObject"&&!!$u.shape?.().event}function isDynamicOption(Au){const lo=getRefDefName(Au);if(lo==="DataBinding"||lo.startsWith("Dynamic"))return!0;const Ru=unwrapZodSchema(Au)._def;if(Ru?.typeName!=="ZodObject")return!1;const Iu=Ru.shape?.()||{},Pu=Object.values(Iu).some(Ou=>getRefDefName(Ou)==="ComponentId");return!!Iu.path&&!Pu}function isChildListOption(Au){if(childRefKindOf(Au)==="child-list"||getRefDefName(Au)==="ChildList")return!0;const $u=unwrapZodSchema(Au)._def;if($u?.typeName!=="ZodObject")return!1;const Ru=$u.shape?.()||{};return Object.values(Ru).some(Iu=>getRefDefName(Iu)==="ComponentId")}function isDynamicDef(Au,lo){return(Au==="DataBinding"||Au.startsWith("Dynamic"))&&lo!=="ZodObject"&&lo!=="ZodArray"}function matchUnionBehavior(Au){if(Au.some(isActionOption))return{type:"ACTION"};if(Au.some(isDynamicOption))return{type:"DYNAMIC"};if(Au.some(isChildListOption))return{type:"STRUCTURAL"}}function scrapeObjectShape(Au){const lo={};for(const[$u,Ru]of Object.entries(Au))lo[$u]=getFieldBehavior(Ru);return lo}function getFieldBehavior(Au){const lo=getRefDefName(Au);if(isCheckableField(Au))return{type:"CHECKABLE"};if(lo==="Action")return{type:"ACTION"};const $u=unwrapZodSchema(Au);if(childRefKindOf($u)==="child-list"||lo==="ChildList")return{type:"STRUCTURAL"};if(isDynamicDef(lo,$u._def?.typeName))return{type:"DYNAMIC"};if($u._def.typeName==="ZodUnion"){const Ru=matchUnionBehavior($u._def.options);if(Ru)return Ru}return $u._def.typeName==="ZodArray"?{type:"ARRAY",element:getFieldBehavior($u._def.type)}:$u._def.typeName==="ZodObject"?{type:"OBJECT",shape:scrapeObjectShape($u._def.shape())}:{type:"STATIC"}}const MAX_DYNAMIC_CHILD_LIST_SIZE=1e4;function getSafeChildList(Au){return Array.isArray(Au)?Au.length>MAX_DYNAMIC_CHILD_LIST_SIZE?Au.slice(0,MAX_DYNAMIC_CHILD_LIST_SIZE):Au:[]}class GenericBinder{constructor(lo,$u){this.dataListeners=[],this.propsListeners=[],this.currentProps={},this.isConnected=!1,this.actionClosures=new Map,this.context=lo,this.behaviorTree=scrapeSchemaBehavior($u),this.behaviorTree.type!=="OBJECT"&&(this.behaviorTree={type:"OBJECT",shape:{}}),this.resolveInitialProps()}resolveInitialProps(){const lo=this.context.componentModel.properties,$u=this.resolveAndBind(lo,this.behaviorTree,[],!0);this.currentProps={...this.currentProps,...$u||{}}}connect(){if(this.isConnected)return;this.isConnected=!0;const lo=this.context.componentModel.onUpdated.subscribe(()=>{this.rebuildAllBindings()});this.compUnsub=()=>lo.unsubscribe(),this.rebuildAllBindings()}rebuildAllBindings(){this.dataListeners.forEach(Ru=>Ru()),this.dataListeners=[];const lo=this.context.componentModel.properties,$u=this.resolveAndBind(lo,this.behaviorTree,[],!1);this.currentProps={...this.currentProps,...$u||{}},this.notify()}bindDynamicValue(lo,$u,Ru){const Iu=this.context.dataContext.subscribeDynamicValue(lo,Pu=>{this.updateDeepValue($u,Pu),this.notify()});return Ru?Iu.unsubscribe():this.dataListeners.push(()=>Iu.unsubscribe()),Iu.value}resolveDeepSync(lo,$u=0){if(typeof lo!="object"||lo===null)return lo;if($u>MAX_DYNAMIC_VALUE_DEPTH)return;if("path"in lo||"call"in lo)return this.context.dataContext.resolveDynamicValue(lo,$u);if(Array.isArray(lo))return lo.map(Iu=>this.resolveDeepSync(Iu,$u+1));const Ru={};for(const[Iu,Pu]of Object.entries(lo))Ru[Iu]=this.resolveDeepSync(Pu,$u+1);return Ru}resolveEventAction(lo){if(typeof lo!="object"||lo===null)return lo;const $u=lo;if("event"in $u&&typeof $u.event=="object"&&$u.event!==null){const Ru=$u.event,Iu={...Ru,context:Ru.context?this.resolveDeepSync(Ru.context,1):void 0};return Ru.userMessage!==void 0&&(Iu.userMessage=this.resolveDeepSync(Ru.userMessage,1)),{...$u,event:Iu}}if("name"in $u){const Ru={...$u,context:$u.context?this.resolveDeepSync($u.context,1):void 0};return $u.userMessage!==void 0&&(Ru.userMessage=this.resolveDeepSync($u.userMessage,1)),Ru}return this.resolveDeepSync(lo,0)}bindAction(lo,$u){const Ru=$u.join("/"),Iu=this.actionClosures.get(Ru);if(Iu&&jsonEquals(Iu.raw,lo))return Iu.closure;const Pu=()=>{if(lo&&typeof lo=="object"){const Ou=lo,Mu=Ou.functionCall&&typeof Ou.functionCall=="object"?Ou.functionCall:Ou;if(typeof Mu.call=="string"){this.context.dataContext.resolveDynamicValue(Mu);return}}this.context.dispatchAction(this.resolveEventAction(lo))};return this.actionClosures.set(Ru,{raw:lo,closure:Pu}),Pu}mapTemplateChildren(lo,$u,Ru){const Iu=getSafeChildList(lo),Pu=this.context.dataContext.nested(Ru);return Iu.map((Ou,Mu)=>({id:$u,basePath:Pu.nested(String(Mu)).path}))}bindStructuralTemplate(lo,$u,Ru){if(!lo||typeof lo!="object"||Array.isArray(lo))return lo;const Iu=lo,Pu=typeof Iu.path=="string"?Iu.path:void 0,Ou=typeof Iu.componentId=="string"?Iu.componentId:void 0;if(!Pu||!Ou)return lo;const Mu=this.context.dataContext.subscribeDynamicValue({path:Pu},Du=>{const Lu=this.mapTemplateChildren(Du,Ou,Pu);this.updateDeepValue($u,Lu),this.notify()});return Ru?Mu.unsubscribe():this.dataListeners.push(()=>Mu.unsubscribe()),this.mapTemplateChildren(Mu.value,Ou,Pu)}extractValidationResult(lo,$u){if(typeof lo=="object"&&lo!==null&&"valid"in lo){const Ru=lo.message;return{valid:!!lo.valid,message:Ru!=null?String(Ru):$u}}return{valid:!!lo,message:$u}}bindCheckable(lo,$u,Ru){const Iu=Array.isArray(lo)?lo:[],Pu=Iu.map(()=>({valid:!0,message:""})),Ou=$u.slice(0,-1),Mu=()=>{const Lu=Pu.filter(Bu=>!Bu.valid).map(Bu=>Bu.message);this.updateDeepValue([...Ou,"isValid"],Lu.length===0),this.updateDeepValue([...Ou,"validationErrors"],Lu),this.notify()};Iu.forEach((Lu,Bu)=>{const ju=typeof Lu=="object"&&Lu!==null?Lu:void 0,Fu=ju&&ju.condition!==void 0?ju.condition:Lu,zu=typeof ju?.message=="string"?ju.message:"Validation failed";Pu[Bu].message=zu;const Uu=this.context.dataContext.subscribeDynamicValue(Fu,Hu=>{Pu[Bu]=this.extractValidationResult(Hu,zu),Mu()});Ru?Uu.unsubscribe():this.dataListeners.push(()=>Uu.unsubscribe()),Pu[Bu]=this.extractValidationResult(Uu.value,zu)});const Du=Pu.filter(Lu=>!Lu.valid).map(Lu=>Lu.message);return this.updateDeepValue([...Ou,"isValid"],Du.length===0),this.updateDeepValue([...Ou,"validationErrors"],Du),lo}bindObject(lo,$u,Ru,Iu){const Pu={};for(const[Ou,Mu]of Object.entries(lo)){const Du=$u[Ou]||{type:"STATIC"};Pu[Ou]=this.resolveAndBind(Mu,Du,[...Ru,Ou],Iu)}for(const[Ou,Mu]of Object.entries($u))if(Mu.type==="DYNAMIC"){const Du=`set${Ou.charAt(0).toUpperCase()+Ou.slice(1)}`,Lu=lo[Ou];Pu[Du]=Bu=>{if(Lu&&typeof Lu=="object"&&"path"in Lu){const ju=Lu.path;typeof ju=="string"&&this.context.dataContext.set(ju,Bu)}}}return Pu}resolveAndBind(lo,$u,Ru,Iu){if(lo==null)return lo;switch($u.type){case"DYNAMIC":return this.bindDynamicValue(lo,Ru,Iu);case"ACTION":return this.bindAction(lo,Ru);case"STRUCTURAL":return this.bindStructuralTemplate(lo,Ru,Iu);case"CHECKABLE":return this.bindCheckable(lo,Ru,Iu);case"STATIC":return lo;case"ARRAY":return Array.isArray(lo)?lo.map((Pu,Ou)=>this.resolveAndBind(Pu,$u.element,[...Ru,Ou.toString()],Iu)):lo;case"OBJECT":return typeof lo!="object"?lo:this.bindObject(lo,$u.shape,Ru,Iu)}}updateDeepValue(lo,$u){this.currentProps=this.cloneAndUpdate(this.currentProps,lo,$u)}cloneAndUpdate(lo,$u,Ru){if($u.length===0)return Ru;const[Iu,...Pu]=$u;if(Array.isArray(lo)){const Ou=[...lo];return Ou[Number(Iu)]=this.cloneAndUpdate(Ou[Number(Iu)],Pu,Ru),Ou}else{const Ou=typeof lo=="object"&&lo!==null?lo:{};return{...Ou,[Iu]:this.cloneAndUpdate(Ou[Iu],Pu,Ru)}}}dispose(){this.isConnected&&(this.isConnected=!1,this.dataListeners.forEach(lo=>lo()),this.dataListeners=[],this.compUnsub&&(this.compUnsub(),this.compUnsub=void 0))}notify(){this.propsListeners.forEach(lo=>lo(this.currentProps))}subscribe(lo){return this.propsListeners.length===0&&this.connect(),this.propsListeners.push(lo),{unsubscribe:()=>{this.propsListeners=this.propsListeners.filter($u=>$u!==lo),this.propsListeners.length===0&&this.dispose()}}}get snapshot(){return this.currentProps}}function jsonEquals(Au,lo){if(Object.is(Au,lo))return!0;if(typeof Au!="object"||typeof lo!="object"||Au===null||lo===null)return!1;if(Array.isArray(Au)||Array.isArray(lo))return!Array.isArray(Au)||!Array.isArray(lo)||Au.length!==lo.length?!1:Au.every((Iu,Pu)=>jsonEquals(Iu,lo[Pu]));const $u=Object.keys(Au),Ru=Object.keys(lo);return $u.length!==Ru.length?!1:$u.every(Iu=>Object.prototype.hasOwnProperty.call(lo,Iu)&&jsonEquals(Au[Iu],lo[Iu]))}class ResolvedBinding{constructor(lo){this.value=lo}}class WritableBinding extends ResolvedBinding{constructor(lo,$u,Ru){super(lo),this.set=$u,this.path=Ru}}function isWritable(Au){return Au instanceof WritableBinding}function sameBinding(Au,lo){return isWritable(Au)!==isWritable(lo)||isWritable(Au)&&isWritable(lo)&&Au.path!==lo.path?!1:valueEquals(Au.value,lo.value)}function valueEquals(Au,lo){if(Object.is(Au,lo))return!0;if(Array.isArray(Au)&&Array.isArray(lo))return Au.length===lo.length&&Au.every(($u,Ru)=>valueEquals($u,lo[Ru]));if(isPlainObject$2(Au)&&isPlainObject$2(lo)){const $u=Object.keys(Au),Ru=Object.keys(lo);return $u.length===Ru.length&&$u.every(Iu=>Iu in lo&&valueEquals(Au[Iu],lo[Iu]))}return!1}function isPlainObject$2(Au){if(typeof Au!="object"||Au===null)return!1;const lo=Object.getPrototypeOf(Au);return lo===Object.prototype||lo===null}const PLACEHOLDER_TYPE="Placeholder";function isComponentNode(Au){return Au instanceof MutableComponentNode}class MutableComponentNode{constructor(lo,$u,Ru,Iu,Pu,Ou,Mu="resolved"){this._onDestroyed=new EventEmitter,this.onDestroyed=this._onDestroyed,this.cleanups=[],this._disposed=!1,this.instanceId=lo,this.componentId=$u,this.type=Ru,this.dataPath=Iu,this.props=signal(Pu),this.impl=Ou,this.state=Mu}get disposed(){return this._disposed}get isPlaceholder(){return this.state!=="resolved"}addCleanup(lo){this.cleanups.push(lo)}toJSON(){if(this.isPlaceholder)return{id:this.componentId,type:this.type,state:this.state};const lo={id:this.componentId,type:this.type},$u=peekValue(this.props);for(const[Ru,Iu]of Object.entries($u))lo[Ru]=serializeValue(Iu);return lo}setProps(lo){if(this._disposed)return;const $u=peekValue(this.props);shallowEqual($u,lo)||setValue(this.props,lo)}dispose(){if(!this._disposed){this._disposed=!0;for(const lo of this.cleanups)try{lo()}catch($u){console.error(`ComponentNode cleanup error (${this.instanceId}):`,$u)}this.cleanups=[],this._onDestroyed.emit(),this._onDestroyed.dispose()}}}function serializeValue(Au){if(isComponentNode(Au))return Au.toJSON();if(Au instanceof ResolvedBinding)return serializeValue(Au.value);if(typeof Au=="function")return"<Action>";if(Array.isArray(Au))return Au.map(serializeValue);if(Au&&typeof Au=="object"){const lo={};for(const[$u,Ru]of Object.entries(Au))lo[$u]=serializeValue(Ru);return lo}return Au}function shallowEqual(Au,lo){if(Object.is(Au,lo))return!0;const $u=Object.keys(Au),Ru=Object.keys(lo);if($u.length!==Ru.length)return!1;for(const Iu of $u)if(!Object.is(Au[Iu],lo[Iu]))return!1;return!0}const COMPONENT_ID_REF="REF:common_types.json#/$defs/ComponentId",CHILD_LIST_REF="REF:common_types.json#/$defs/ChildList",EMPTY_REF_FIELDS$1=new Map,refFieldsCache=new WeakMap;function extractRefFields(Au){const lo=refFieldsCache.get(Au);if(lo)return lo;const $u=unwrap(Au);if($u.schema._def.typeName!=="ZodObject")return refFieldsCache.set(Au,EMPTY_REF_FIELDS$1),EMPTY_REF_FIELDS$1;const Ru=new Map,Iu=$u.schema.shape;for(const[Ou,Mu]of Object.entries(Iu)){const Du=unwrap(Mu);if(marksChildList(Du)||isChildListUnion(Du.schema)){Ru.set(Ou,{kind:"list"});continue}if(marksComponentId(Du)){Ru.set(Ou,{kind:"single"});continue}if(Du.schema._def.typeName==="ZodArray"){const Lu=unwrap(Du.schema._def.type);if(marksComponentId(Lu)){Ru.set(Ou,{kind:"list"});continue}if(Lu.schema._def.typeName==="ZodObject"){const Bu=new Set,ju=Lu.schema.shape;for(const[Fu,zu]of Object.entries(ju))marksComponentId(unwrap(zu))&&Bu.add(Fu);Bu.size>0&&Ru.set(Ou,{kind:"nested",keys:Bu})}}}const Pu=Ru;return refFieldsCache.set(Au,Pu),Pu}function unwrap(Au){const lo=[],$u=new Set;let Ru=Au;for(;;){Ru.description&&lo.push(Ru.description);const Iu=childRefKindOf(Ru);Iu&&$u.add(Iu);const Pu=Ru._def.typeName;if(Pu==="ZodOptional"||Pu==="ZodNullable"||Pu==="ZodDefault")Ru=Ru._def.innerType;else if(Pu==="ZodEffects")Ru=Ru._def.schema;else return{schema:Ru,descriptions:lo,refs:$u}}}function marksComponentId(Au){return Au.refs.has("component-id")||hasPointer(Au.descriptions,COMPONENT_ID_REF)}function marksChildList(Au){return Au.refs.has("child-list")||hasPointer(Au.descriptions,CHILD_LIST_REF)}function hasPointer(Au,lo){return Au.some($u=>$u.startsWith(lo))}function isChildListUnion(Au){return Au._def.typeName!=="ZodUnion"?!1:Au._def.options.some($u=>{if($u._def.typeName!=="ZodObject")return!1;const Ru=$u.shape;return Ru.componentId&&Ru.path})}const ROOT_COMPONENT_ID="root",ROOT_DATA_PATH="/",EMPTY_REF_FIELDS=new Map;class NodeResolver{constructor(lo,$u){if(this.records=new Map,this.nodesByEdge=new Map,this.nodesByComponentId=new Map,this.pendingParents=new Map,this.dispatchedErrors=new Map,this.modelSubs=[],this._disposed=!1,$u!==lo.defaultCatalog)throw new A2uiStateError("NodeResolver requires the same catalog instance its surface was constructed with.");this.surface=lo,this.catalog=$u,this.rootId=lo.rootId??ROOT_COMPONENT_ID,this.rootNode=signal(void 0),this.modelSubs.push(lo.componentsModel.onCreated.subscribe(Ru=>this.onComponentCreated(Ru))),this.modelSubs.push(lo.componentsModel.onDeleted.subscribe(Ru=>this.onComponentDeleted(Ru))),lo.componentsModel.get(this.rootId)&&this.buildRoot()}dispatchOnce(lo,$u,Ru,Iu){let Pu=this.dispatchedErrors.get($u);Pu||(Pu=new Map,this.dispatchedErrors.set($u,Pu));let Ou=Pu.get(Ru);Ou||(Ou=new Set,Pu.set(Ru,Ou)),!Ou.has(lo)&&(Ou.add(lo),this.surface.dispatchError({code:lo,message:Iu}))}clearDispatched(lo,$u){const Ru=this.dispatchedErrors.get(lo);Ru?.delete($u)&&Ru.size===0&&this.dispatchedErrors.delete(lo)}get activeNodeCount(){return this.records.size}get disposed(){return this._disposed}dispose(){if(!this._disposed){this._disposed=!0;for(const lo of this.modelSubs)lo.unsubscribe();this.modelSubs.length=0;for(const lo of[...this.records.keys()])this.disposeNode(lo);this.pendingParents.clear(),this.dispatchedErrors.clear(),this.rootRecord=void 0,setValue(this.rootNode,void 0)}}buildRoot(){if(this.rootRecord)return;const lo=`>${escapeIdPart(this.rootId)}>${escapeIdPart(this.rootId)}@/`,$u=this.createNode(this.rootId,ROOT_DATA_PATH,lo,void 0);this.rootRecord=this.records.get($u),setValue(this.rootNode,$u)}onComponentCreated(lo){if(this._disposed)return;if(lo.id===this.rootId){const Ru=this.surface.componentsModel.get(this.rootId);this.rootRecord&&this.rootRecord.componentModel!==Ru&&(this.disposeNode(this.rootRecord.node),this.rootRecord=void 0,Ru||setValue(this.rootNode,void 0)),Ru&&this.buildRoot()}const $u=this.pendingParents.get(lo.id);if($u){this.pendingParents.delete(lo.id);for(const Ru of $u){const Iu=this.records.get(Ru);Iu&&!Ru.disposed&&this.materialize(Iu)}}}onComponentDeleted(lo){if(this._disposed)return;this.dispatchedErrors.delete(lo);const $u=this.surface.componentsModel.get(lo),Ru=this.nodesByComponentId.get(lo);if(!Ru)return;const Iu=new Set;let Pu=!1;for(const Ou of[...Ru]){const Mu=this.records.get(Ou);Mu&&(Mu.parent?Iu.add(Mu.parent):Pu=!0)}Pu&&this.rootRecord&&($u?this.rootRecord.componentModel!==$u&&(this.disposeNode(this.rootRecord.node),this.rootRecord=void 0,this.buildRoot()):(this.disposeNode(this.rootRecord.node),this.rootRecord=void 0,setValue(this.rootNode,void 0)));for(const Ou of Iu){const Mu=this.records.get(Ou);Mu&&!Ou.disposed&&this.materialize(Mu)}}createNode(lo,$u,Ru,Iu,Pu=1){const Ou=this.surface.componentsModel.get(lo);if(!Ou){const zu=this.registerNode(new MutableComponentNode(instanceIdFor(lo,$u,Pu),lo,PLACEHOLDER_TYPE,$u,{},void 0,"pending"),{edgeKey:Ru,parent:Iu,occurrence:Pu,refFields:EMPTY_REF_FIELDS});return Iu&&this.registerPendingParent(lo,Iu),zu.node}const Mu=(Ou.catalog?.components.size?Ou.catalog:void 0)??this.catalog,Du=Mu.components.get(Ou.type);if(!Du)return this.dispatchOnce("UNKNOWN_COMPONENT_TYPE",lo,$u,`Component '${lo}' has type '${Ou.type}', which is not in catalog '${Mu.id}'.`),this.registerNode(new MutableComponentNode(instanceIdFor(lo,$u,Pu),lo,Ou.type,$u,{},void 0,"unknown-type"),{edgeKey:Ru,parent:Iu,occurrence:Pu,refFields:EMPTY_REF_FIELDS,componentModel:Ou}).node;this.clearDispatched(lo,$u);const Lu=Iu?this.records.get(Iu)?.context?.dataContext:void 0,Bu=new ComponentContext(this.surface,lo,$u,Lu),ju=new GenericBinder(Bu,Du.schema),Fu=this.registerNode(new MutableComponentNode(instanceIdFor(lo,$u,Pu),lo,Ou.type,$u,{},Du),{edgeKey:Ru,parent:Iu,occurrence:Pu,refFields:extractRefFields(Du.schema),behavior:scrapeSchemaBehavior(Du.schema),context:Bu,componentModel:Ou,binder:ju});return Fu.binderSub=ju.subscribe(zu=>{Fu.lastBinderProps=zu,this.materialize(Fu)}),Fu.lastBinderProps=ju.snapshot,this.materialize(Fu),Fu.node}registerNode(lo,$u){const Ru={node:lo,edgeKey:$u.edgeKey,parent:$u.parent,occurrence:$u.occurrence,refFields:$u.refFields,behavior:$u.behavior,context:$u.context,componentModel:$u.componentModel,binder:$u.binder,childEdges:new Map};this.records.set(lo,Ru),this.nodesByEdge.set($u.edgeKey,lo);let Iu=this.nodesByComponentId.get(lo.componentId);return Iu||(Iu=new Set,this.nodesByComponentId.set(lo.componentId,Iu)),Iu.add(lo),Ru}childNode(lo,$u,Ru,Iu,Pu=1){const Ou=this.nodesByEdge.get(Ru);if(this.isCyclic(lo,$u,Iu))return Ou&&!Ou.disposed&&Ou.isPlaceholder&&this.records.get(Ou)?.occurrence===Pu?Ou:(Ou&&!Ou.disposed&&this.disposeNode(Ou),this.dispatchOnce("CYCLIC_REFERENCE",lo,$u,`Component '${lo}' at '${$u}' is referenced by one of its own descendants; rendering a placeholder instead.`),this.registerNode(new MutableComponentNode(instanceIdFor(lo,$u,Pu),lo,PLACEHOLDER_TYPE,$u,{},void 0,"cyclic"),{edgeKey:Ru,parent:Iu,occurrence:Pu,refFields:EMPTY_REF_FIELDS}).node);if(Ou&&!Ou.disposed){const Mu=this.surface.componentsModel.get(lo),Du=(Mu?.catalog?.components.size?Mu.catalog:void 0)??this.catalog,Lu=Mu?Du.components.get(Mu.type):void 0,Bu=this.records.get(Ou);if(Ou.componentId===lo&&Ou.dataPath===$u&&Bu?.occurrence===Pu&&(Ou.isPlaceholder?Mu===void 0&&Ou.state==="pending"||Mu!==void 0&&Lu===void 0&&Ou.state==="unknown-type"&&Bu?.componentModel===Mu:Mu!==void 0&&Ou.type===Mu.type&&Bu?.componentModel===Mu))return Ou.state==="pending"&&this.registerPendingParent(lo,Iu),Ou;this.disposeNode(Ou)}return this.createNode(lo,$u,Ru,Iu,Pu)}registerPendingParent(lo,$u){let Ru=this.pendingParents.get(lo);Ru||(Ru=new Set,this.pendingParents.set(lo,Ru)),Ru.add($u)}isCyclic(lo,$u,Ru){for(let Iu=Ru;Iu;Iu=this.records.get(Iu)?.parent)if(Iu.componentId===lo&&Iu.dataPath===$u)return!0;return!1}materialize(lo){if(lo.node.disposed)return;const Ru={...lo.lastBinderProps??lo.binder?.snapshot??{}},Iu=new Map,Pu=lo.componentModel?.properties;if(Pu)for(const Bu of lo.refFields.keys())Bu in Ru&&!(Bu in Pu)&&delete Ru[Bu];const Ou=new Map,Mu=(Bu,ju,Fu)=>{const zu=`${escapeIdPart(ju)}@${escapeIdPart(Fu)}`,Uu=(Ou.get(zu)??0)+1;Ou.set(zu,Uu);const Hu=`${lo.edgeKey}>${Bu}>${zu}`,Vu=this.childNode(ju,Fu,Hu,lo.node,Uu);return Iu.set(Hu,Vu),Vu};for(const[Bu,ju]of lo.refFields)switch(ju.kind){case"single":{const Fu=Ru[Bu];typeof Fu=="string"&&Fu&&(Ru[Bu]=Mu(escapeIdPart(Bu),Fu,lo.node.dataPath));break}case"list":{const Fu=Ru[Bu];if(!Array.isArray(Fu))break;const zu=getSafeChildList(Fu);Ru[Bu]=zu.map((Uu,Hu)=>{if(typeof Uu=="string"&&Uu)return Mu(`${escapeIdPart(Bu)}[${Hu}]`,Uu,lo.node.dataPath);if(Uu&&typeof Uu=="object"&&!Array.isArray(Uu)){const Vu=Uu;if(typeof Vu.id=="string"&&typeof Vu.basePath=="string")return Mu(`${escapeIdPart(Bu)}[${Hu}]`,Vu.id,Vu.basePath);if(typeof Vu.componentId=="string"&&Vu.componentId)return Mu(`${escapeIdPart(Bu)}[${Hu}]`,Vu.componentId,lo.node.dataPath)}return Uu});break}case"nested":{const Fu=Ru[Bu];if(!Array.isArray(Fu))break;Ru[Bu]=Fu.map((zu,Uu)=>{if(!zu||typeof zu!="object"||Array.isArray(zu))return zu;const Hu={...zu};let Vu=!1;for(const Gu of ju.keys){const Wu=Hu[Gu];typeof Wu=="string"&&Wu&&(Hu[Gu]=Mu(`${escapeIdPart(Bu)}[${Uu}].${escapeIdPart(Gu)}`,Wu,lo.node.dataPath),Vu=!0)}return Vu?Hu:zu});break}}for(const[Bu,ju]of lo.childEdges)if(!Iu.has(Bu)&&(this.disposeNode(ju),ju.isPlaceholder&&![...Iu.values()].some(zu=>zu.isPlaceholder&&zu.componentId===ju.componentId))){const zu=this.pendingParents.get(ju.componentId);zu&&(zu.delete(lo.node),zu.size===0&&this.pendingParents.delete(ju.componentId))}lo.childEdges=Iu;const Du=lo.behavior&&lo.context?wrapDynamicValues(Ru,lo.behavior,Pu??{},lo.context.dataContext):Ru,Lu=peekValue(lo.node.props);for(const Bu of Object.keys(Du))Du[Bu]=stabilize(Lu[Bu],Du[Bu]);lo.node.setProps(Du)}disposeNode(lo){if(lo.disposed)return;const $u=this.records.get(lo);if($u){for(const Iu of $u.childEdges.values())this.disposeNode(Iu);$u.childEdges.clear(),$u.binderSub?.unsubscribe(),$u.binderSub=void 0,this.nodesByEdge.get($u.edgeKey)===lo&&this.nodesByEdge.delete($u.edgeKey),this.records.delete(lo)}const Ru=this.nodesByComponentId.get(lo.componentId);Ru&&(Ru.delete(lo),Ru.size===0&&this.nodesByComponentId.delete(lo.componentId));for(const[Iu,Pu]of this.pendingParents)Pu.delete(lo),Pu.size===0&&this.pendingParents.delete(Iu);lo.state==="cyclic"&&this.clearDispatched(lo.componentId,lo.dataPath),lo.dispose()}}const ID_PART_ESCAPES={"~":"~0","#":"~1","[":"~2","]":"~3",">":"~4","@":"~5"};function escapeIdPart(Au){return Au.replace(/[~#[\]>@]/g,lo=>ID_PART_ESCAPES[lo])}function instanceIdFor(Au,lo,$u){const Ru=lo.replace(/\/+$/,"")||ROOT_DATA_PATH,Iu=lo===ROOT_DATA_PATH?escapeIdPart(Au):`${escapeIdPart(Au)}-[${escapeIdPart(Ru)}]`;return $u>1?`${Iu}#${$u}`:Iu}function wrapDynamicValues(Au,lo,$u,Ru){switch(lo.type){case"DYNAMIC":{const Iu=$u&&typeof $u=="object"&&!Array.isArray($u)&&typeof $u.path=="string"?$u.path:void 0;return Iu===void 0?new ResolvedBinding(Au):new WritableBinding(Au,Pu=>Ru.set(Iu,Pu),Iu)}case"ARRAY":{if(!Array.isArray(Au))return Au;const Iu=Array.isArray($u)?$u:[];return Au.map((Pu,Ou)=>wrapDynamicValues(Pu,lo.element,Iu[Ou],Ru))}case"OBJECT":{if(!Au||typeof Au!="object"||Array.isArray(Au))return Au;const Iu=new Set;for(const[Mu,Du]of Object.entries(lo.shape))Du.type==="DYNAMIC"&&Iu.add(`set${Mu.charAt(0).toUpperCase()}${Mu.slice(1)}`);const Pu=$u&&typeof $u=="object"&&!Array.isArray($u)?$u:{},Ou={};for(const[Mu,Du]of Object.entries(Au))Iu.has(Mu)||(Ou[Mu]=wrapDynamicValues(Du,lo.shape[Mu]??{type:"STATIC"},Pu[Mu],Ru));for(const[Mu,Du]of Object.entries(lo.shape))Du.type==="DYNAMIC"&&!(Mu in Ou)&&(Ou[Mu]=new ResolvedBinding(void 0));return Ou}default:return Au}}function stabilize(Au,lo){if(Object.is(Au,lo))return lo;if(Au instanceof ResolvedBinding&&lo instanceof ResolvedBinding)return sameBinding(Au,lo)?Au:lo;if(isComponentNode(Au)||isComponentNode(lo))return lo;if(Array.isArray(Au)&&Array.isArray(lo)&&Au.length===lo.length){let $u=!0;const Ru=lo.map((Iu,Pu)=>{const Ou=stabilize(Au[Pu],Iu);return Object.is(Ou,Au[Pu])||($u=!1),Ou});return $u?Au:Ru}if(isPlainObject$1(Au)&&isPlainObject$1(lo)){const $u=Object.keys(Au),Ru=Object.keys(lo);if($u.length===Ru.length){let Iu=!0;const Pu={};for(const Ou of Ru){const Mu=stabilize(Au[Ou],lo[Ou]);Pu[Ou]=Mu,(!(Ou in Au)||!Object.is(Mu,Au[Ou]))&&(Iu=!1)}return Iu?Au:Pu}}return lo}function isPlainObject$1(Au){if(!Au||typeof Au!="object"||Array.isArray(Au)||isComponentNode(Au))return!1;const lo=Object.getPrototypeOf(Au);return lo===Object.prototype||lo===null}const ComponentIdSchema=markChildRef(stringType().describe("REF:#/$defs/ComponentId|The unique identifier for a component, used for both definitions and references within the same surface."),"component-id"),DataBindingSchema=objectType({path:stringType().describe("A JSON Pointer path to a value in the data model.")}).strict().describe("REF:#/$defs/DataBinding"),DynamicValueSchema=unionType([stringType(),numberType(),booleanType(),arrayType(anyType()),DataBindingSchema,lazyType(()=>FunctionCallSchema)]).describe("REF:#/$defs/DynamicValue|A value that can be a literal, a path, or a function call returning any type."),FunctionCallSchema=objectType({call:stringType().describe("The name of the function to call."),args:recordType(stringType(),unionType([DynamicValueSchema,recordType(stringType(),anyType()).describe("A literal object argument (e.g. configuration).")])).describe("Arguments passed to the function.").optional(),returnType:enumType(["string","number","boolean","array","object","any","void"]).describe("The expected return type of the function call.").default("boolean")}).describe("REF:#/$defs/FunctionCall|Invokes a named function on the client."),DynamicStringSchema=unionType([stringType(),DataBindingSchema,FunctionCallSchema]).describe("REF:#/$defs/DynamicString|Represents a string"),AccessibilityAttributesSchema=objectType({label:DynamicStringSchema.optional(),description:DynamicStringSchema.optional()}).describe("REF:#/$defs/AccessibilityAttributes|Attributes to enhance accessibility when using assistive technologies like screen readers.");objectType({id:ComponentIdSchema,accessibility:AccessibilityAttributesSchema.optional()}).describe("REF:#/$defs/ComponentCommon");const ChildListSchema=markChildRef(unionType([arrayType(ComponentIdSchema).describe("A static list of child component IDs."),objectType({componentId:ComponentIdSchema,path:stringType().describe("The path to the list of component property objects in the data model.")}).strict().describe("A template for generating a dynamic list of children from a data model list. The `componentId` is the component to use as a template.")]).describe("REF:#/$defs/ChildList"),"child-list"),DynamicNumberSchema=unionType([numberType(),DataBindingSchema,FunctionCallSchema]).describe("REF:#/$defs/DynamicNumber|Represents a value that can be either a literal number, a path to a number in the data model, or a function call returning a number."),DynamicBooleanSchema=unionType([booleanType(),DataBindingSchema,FunctionCallSchema]).describe("REF:#/$defs/DynamicBoolean|A boolean value that can be a literal, a path, or a function call returning a boolean."),DynamicStringListSchema=unionType([arrayType(stringType()),DataBindingSchema,FunctionCallSchema]).describe("REF:#/$defs/DynamicStringList|Represents a value that can be either a literal array of strings, a path to a string array in the data model, or a function call returning a string array."),CheckRuleSchema=objectType({condition:DynamicBooleanSchema,message:stringType().describe("The error message to display if the check fails.")}).strict().describe("REF:#/$defs/CheckRule|A single validation rule applied to an input component.");objectType({checks:arrayType(CheckRuleSchema).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional()}).describe("REF:#/$defs/Checkable|Properties for components that support client-side checks.");const ActionSchema=unionType([objectType({event:objectType({name:stringType().describe("The name of the action to be dispatched to the server."),context:recordType(stringType(),DynamicValueSchema).describe("A JSON object containing the key-value pairs for the action context. Values can be literals or paths. Use literal values unless the value must be dynamically bound to the data model. Do NOT use paths for static IDs.").optional()}).strict().describe("The event to dispatch to the server.")}).strict().describe("Triggers a server-side event."),objectType({functionCall:FunctionCallSchema}).strict().describe("Executes a local client-side function.")]).describe("REF:#/$defs/Action|Defines an interaction handler that can either trigger a server-side event or execute a local client-side function."),TextApi={name:"Text",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),text:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The text content to display. While simple Markdown formatting is supported (i.e. without HTML, images, or links), utilizing dedicated UI components is generally preferred for a richer and more structured presentation."),variant:enumType(["h1","h2","h3","h4","h5","caption","body"]).default("body").describe("A hint for the base text style.").optional()}).strict()},ImageApi={name:"Image",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),url:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The URL of the image to display."),description:DynamicStringSchema.describe("REF:#/$defs/DynamicString|Accessibility text for the image.").optional(),fit:enumType(["contain","cover","fill","none","scaleDown"]).default("fill").describe("Specifies how the image should be resized to fit its container. This corresponds to the CSS 'object-fit' property.").optional(),variant:enumType(["icon","avatar","smallFeature","mediumFeature","largeFeature","header"]).default("mediumFeature").describe("A hint for the image size and style.").optional()}).strict()},IconApi={name:"Icon",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),name:unionType([enumType(["accountCircle","add","arrowBack","arrowForward","attachFile","calendarToday","call","camera","check","close","delete","download","edit","event","error","fastForward","favorite","favoriteOff","folder","help","home","info","locationOn","lock","lockOpen","mail","menu","moreVert","moreHoriz","notificationsOff","notifications","pause","payment","person","phone","photo","play","print","refresh","rewind","search","send","settings","share","shoppingCart","skipNext","skipPrevious","star","starHalf","starOff","stop","upload","visibility","visibilityOff","volumeDown","volumeMute","volumeOff","volumeUp","warning"]),objectType({svgPath:stringType()}),DataBindingSchema.describe("REF:#/$defs/DataBinding")]).describe("The name of the icon to display.")}).strict()},VideoApi={name:"Video",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),url:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The URL of the video to display.")}).strict()},AudioPlayerApi={name:"AudioPlayer",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),url:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The URL of the audio to be played."),description:DynamicStringSchema.describe("REF:#/$defs/DynamicString|A description of the audio, such as a title or summary.").optional()}).strict()},RowApi={name:"Row",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),children:ChildListSchema.describe("REF:#/$defs/ChildList|Defines the children. Use an array of strings for a fixed set of children, or a template object to generate children from a data list. Children cannot be defined inline, they must be referred to by ID."),justify:enumType(["center","end","spaceAround","spaceBetween","spaceEvenly","start","stretch"]).default("start").describe("Defines the arrangement of children along the main axis (horizontally). Use 'spaceBetween' to push items to the edges, or 'start'/'end'/'center' to pack them together.").optional(),align:enumType(["start","center","end","stretch"]).default("stretch").describe("Defines the alignment of children along the cross axis (vertically). This is similar to the CSS 'align-items' property, but uses camelCase values (e.g., 'start').").optional()}).strict()},ColumnApi={name:"Column",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),children:ChildListSchema.describe("REF:#/$defs/ChildList|Defines the children. Use an array of strings for a fixed set of children, or a template object to generate children from a data list. Children cannot be defined inline, they must be referred to by ID."),justify:enumType(["start","center","end","spaceBetween","spaceAround","spaceEvenly","stretch"]).default("start").describe("Defines the arrangement of children along the main axis (vertically). Use 'spaceBetween' to push items to the edges (e.g. header at top, footer at bottom), or 'start'/'end'/'center' to pack them together.").optional(),align:enumType(["center","end","start","stretch"]).default("stretch").describe("Defines the alignment of children along the cross axis (horizontally). This is similar to the CSS 'align-items' property.").optional()}).strict()},ListApi={name:"List",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),children:ChildListSchema.describe("REF:#/$defs/ChildList|Defines the children. Use an array of strings for a fixed set of children, or a template object to generate children from a data list."),direction:enumType(["vertical","horizontal"]).default("vertical").describe("The direction in which the list items are laid out.").optional(),align:enumType(["start","center","end","stretch"]).default("stretch").describe("Defines the alignment of children along the cross axis.").optional()}).strict()},CardApi={name:"Card",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),child:ComponentIdSchema.describe("REF:#/$defs/ComponentId|The ID of the single child component to be rendered inside the card. To display multiple elements, you MUST wrap them in a layout component (like Column or Row) and pass that container's ID here. Do NOT pass multiple IDs or a non-existent ID.")}).strict()},TabsApi={name:"Tabs",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),tabs:arrayType(objectType({title:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The tab title."),child:ComponentIdSchema.describe("REF:#/$defs/ComponentId|The ID of the child component.")})).min(1).describe("An array of objects, where each object defines a tab with a title and a child component.")}).strict()},ModalApi={name:"Modal",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),trigger:ComponentIdSchema.describe("REF:#/$defs/ComponentId|The ID of the component that opens the modal when interacted with (e.g., a button)."),content:ComponentIdSchema.describe("REF:#/$defs/ComponentId|The ID of the component to be displayed inside the modal.")}).strict()},DividerApi={name:"Divider",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),axis:enumType(["horizontal","vertical"]).default("horizontal").describe("The orientation of the divider.").optional()}).strict()},ButtonApi={name:"Button",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),checks:arrayType(CheckRuleSchema).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional(),child:ComponentIdSchema.describe("REF:#/$defs/ComponentId|The ID of the child component. Use a 'Text' component for a labeled button. Only use an 'Icon' if the requirements explicitly ask for an icon-only button."),variant:enumType(["default","primary","borderless"]).default("default").describe("A hint for the button style. If omitted, a default button style is used. 'primary' indicates this is the main call-to-action button. 'borderless' means the button has no visual border or background, making its child content appear like a clickable link.").optional(),action:ActionSchema.describe("REF:#/$defs/Action")}).strict()},TextFieldApi={name:"TextField",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),checks:arrayType(CheckRuleSchema).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional(),label:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The text label for the input field."),value:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The value of the text field.").optional(),variant:enumType(["longText","number","shortText","obscured"]).default("shortText").describe("The type of input field to display.").optional(),validationRegexp:stringType().describe("A regular expression used for client-side validation of the input.").optional()}).strict()},CheckBoxApi={name:"CheckBox",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),checks:arrayType(CheckRuleSchema).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional(),label:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The text to display next to the checkbox."),value:DynamicBooleanSchema.describe("REF:#/$defs/DynamicBoolean|The current state of the checkbox (true for checked, false for unchecked).")}).strict()},ChoicePickerApi={name:"ChoicePicker",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),checks:arrayType(CheckRuleSchema).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional(),label:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The label for the group of options.").optional(),variant:enumType(["multipleSelection","mutuallyExclusive"]).default("mutuallyExclusive").describe("A hint for how the choice picker should be displayed and behave.").optional(),options:arrayType(objectType({label:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The text to display for this option."),value:stringType().describe("The stable value associated with this option.")})).describe("The list of available options to choose from."),value:DynamicStringListSchema.describe("REF:#/$defs/DynamicStringList|The list of currently selected values. This should be bound to a string array in the data model."),displayStyle:enumType(["checkbox","chips"]).default("checkbox").describe("The display style of the component.").optional(),filterable:booleanType().default(!1).describe("If true, displays a search input to filter the options.").optional()}).strict()},SliderApi={name:"Slider",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),checks:arrayType(CheckRuleSchema).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional(),label:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The label for the slider.").optional(),min:numberType().default(0).describe("The minimum value of the slider.").optional(),max:numberType().describe("The maximum value of the slider."),value:DynamicNumberSchema.describe("REF:#/$defs/DynamicNumber|The current value of the slider.")}).strict()},DateTimeInputApi={name:"DateTimeInput",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),checks:arrayType(CheckRuleSchema).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional(),value:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The selected date and/or time value in ISO 8601 format. If not yet set, initialize with an empty string."),enableDate:booleanType().default(!1).describe("If true, allows the user to select a date.").optional(),enableTime:booleanType().default(!1).describe("If true, allows the user to select a time.").optional(),min:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The minimum allowed date/time in ISO 8601 format.").optional(),max:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The maximum allowed date/time in ISO 8601 format.").optional(),label:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The text label for the input field.").optional()}).strict()},DEFAULT_CSS=`
3680
3680
  :where(:root) {
3681
3681
  color-scheme: light dark;
3682
3682
  }
@@ -3780,7 +3780,7 @@ Examples:
3780
3780
  `),lo=lo.replace(NULL_RE,"�"),Au.src=lo}function block(Au){let lo;Au.inlineMode?(lo=new Au.Token("inline","",0),lo.content=Au.src,lo.map=[0,1],lo.children=[],Au.tokens.push(lo)):Au.md.block.parse(Au.src,Au.md,Au.env,Au.tokens)}function inline(Au){const lo=Au.tokens;for(let $u=0,Ru=lo.length;$u<Ru;$u++){const Iu=lo[$u];Iu.type==="inline"&&Au.md.inline.parse(Iu.content,Au.md,Au.env,Iu.children)}}function isLinkOpen$1(Au){return/^<a[>\s]/i.test(Au)}function isLinkClose$1(Au){return/^<\/a\s*>/i.test(Au)}function linkify$1(Au){const lo=Au.tokens;if(Au.md.options.linkify)for(let $u=0,Ru=lo.length;$u<Ru;$u++){if(lo[$u].type!=="inline"||!Au.md.linkify.pretest(lo[$u].content))continue;const Iu=lo[$u].children,Pu=[];let Ou=0;for(let Mu=Iu.length-1;Mu>=0;Mu--){const Du=Iu[Mu];if(Du.type==="link_close"){for(Mu--;Iu[Mu].level!==Du.level&&Iu[Mu].type!=="link_open";)Mu--;continue}if(Du.type==="html_inline"&&(isLinkOpen$1(Du.content)&&Ou>0&&Ou--,isLinkClose$1(Du.content)&&Ou++),!(Ou>0)&&Du.type==="text"&&Au.md.linkify.test(Du.content)){const Lu=Du.content;let Bu=Au.md.linkify.match(Lu);const ju=[];let Fu=Du.level,zu=0;Bu.length>0&&Bu[0].index===0&&Mu>0&&Iu[Mu-1].type==="text_special"&&(Bu=Bu.slice(1));for(let Uu=0;Uu<Bu.length;Uu++){const Hu=Bu[Uu].url,Vu=Au.md.normalizeLink(Hu);if(!Au.md.validateLink(Vu))continue;let Gu=Bu[Uu].text;Bu[Uu].schema?Bu[Uu].schema==="mailto:"&&!/^mailto:/i.test(Gu)?Gu=Au.md.normalizeLinkText("mailto:"+Gu).replace(/^mailto:/,""):Gu=Au.md.normalizeLinkText(Gu):Gu=Au.md.normalizeLinkText("http://"+Gu).replace(/^http:\/\//,"");const Wu=Bu[Uu].index;if(Wu>zu){const Xu=new Au.Token("text","",0);Xu.content=Lu.slice(zu,Wu),Xu.level=Fu,ju.push(Xu)}const Ku=new Au.Token("link_open","a",1);Ku.attrs=[["href",Vu]],Ku.level=Fu++,Ku.markup="linkify",Ku.info="auto",ju.push(Ku);const Ju=new Au.Token("text","",0);Ju.content=Gu,Ju.level=Fu,ju.push(Ju);const Yu=new Au.Token("link_close","a",-1);Yu.level=--Fu,Yu.markup="linkify",Yu.info="auto",ju.push(Yu),zu=Bu[Uu].lastIndex}if(zu<Lu.length){const Uu=new Au.Token("text","",0);Uu.content=Lu.slice(zu),Uu.level=Fu,ju.push(Uu)}Pu.push({index:Mu,nodes:ju})}}if(Pu.length>0){let Mu=Iu.length;for(const ju of Pu)Mu+=ju.nodes.length-1;const Du=new Array(Mu);let Lu=0,Bu=0;Pu.reverse();for(let ju=0;ju<Iu.length;ju++){const Fu=Pu[Lu];if(Fu?.index===ju){for(const zu of Fu.nodes)Du[Bu++]=zu;Lu++}else Du[Bu++]=Iu[ju]}lo[$u].children=Du}}}const RARE_RE=/\+-|\.\.|\?\?\?\?|!!!!|,,|--/,SCOPED_ABBR_TEST_RE=/\((c|tm|r)\)/i,SCOPED_ABBR_RE=/\((c|tm|r)\)/ig,SCOPED_ABBR={c:"©",r:"®",tm:"™"};function replaceFn(Au,lo){return SCOPED_ABBR[lo.toLowerCase()]}function replace_scoped(Au){let lo=0;for(let $u=Au.length-1;$u>=0;$u--){const Ru=Au[$u];Ru.type==="text"&&!lo&&(Ru.content=Ru.content.replace(SCOPED_ABBR_RE,replaceFn)),Ru.type==="link_open"&&Ru.info==="auto"&&lo--,Ru.type==="link_close"&&Ru.info==="auto"&&lo++}}function replace_rare(Au){let lo=0;for(let $u=Au.length-1;$u>=0;$u--){const Ru=Au[$u];Ru.type==="text"&&!lo&&RARE_RE.test(Ru.content)&&(Ru.content=Ru.content.replace(/\+-/g,"±").replace(/\.{2,}/g,"…").replace(/([?!])…/g,"$1..").replace(/([?!]){4,}/g,"$1$1$1").replace(/,{2,}/g,",").replace(/(^|[^-])---(?=[^-]|$)/mg,"$1—").replace(/(^|\s)--(?=\s|$)/mg,"$1–").replace(/(^|[^-\s])--(?=[^-\s]|$)/mg,"$1–")),Ru.type==="link_open"&&Ru.info==="auto"&&lo--,Ru.type==="link_close"&&Ru.info==="auto"&&lo++}}function replace(Au){let lo;if(Au.md.options.typographer)for(lo=Au.tokens.length-1;lo>=0;lo--)Au.tokens[lo].type==="inline"&&(SCOPED_ABBR_TEST_RE.test(Au.tokens[lo].content)&&replace_scoped(Au.tokens[lo].children),RARE_RE.test(Au.tokens[lo].content)&&replace_rare(Au.tokens[lo].children))}const QUOTE_TEST_RE=/['"]/,QUOTE_RE=/['"]/g,APOSTROPHE="’",MAX_OPENERS=1e3;function truncateStack(Au,lo,$u){for(;Au.length>$u;){const Ru=Au.pop();Ru.isSingleQuote?lo.single=Ru.prevSameQuoteIdx:lo.double=Ru.prevSameQuoteIdx}}function addReplacement(Au,lo,$u,Ru){Au[lo]||(Au[lo]=[]),Au[lo].push({pos:$u,ch:Ru})}function applyReplacements(Au,lo){let $u="",Ru=0;lo.sort((Iu,Pu)=>Iu.pos-Pu.pos);for(let Iu=0;Iu<lo.length;Iu++){const Pu=lo[Iu];$u+=Au.slice(Ru,Pu.pos)+Pu.ch,Ru=Pu.pos+1}return $u+Au.slice(Ru)}function process_inlines(Au,lo){let $u;const Ru=[],Iu={single:-1,double:-1},Pu={};for(let Ou=0;Ou<Au.length;Ou++){const Mu=Au[Ou],Du=Au[Ou].level;for($u=Ru.length-1;$u>=0&&!(Ru[$u].level<=Du);$u--);if(truncateStack(Ru,Iu,$u+1),Mu.type!=="text")continue;const Lu=Mu.content;let Bu=0;const ju=Lu.length;e:for(;Bu<ju;){QUOTE_RE.lastIndex=Bu;const Fu=QUOTE_RE.exec(Lu);if(!Fu)break;let zu=!0,Uu=!0;Bu=Fu.index+1;const Hu=Fu[0]==="'";let Vu=32;if(Fu.index-1>=0)Vu=Lu.charCodeAt(Fu.index-1);else for($u=Ou-1;$u>=0&&!(Au[$u].type==="softbreak"||Au[$u].type==="hardbreak");$u--)if(Au[$u].content){Vu=Au[$u].content.charCodeAt(Au[$u].content.length-1);break}let Gu=32;if(Bu<ju)Gu=Lu.charCodeAt(Bu);else for($u=Ou+1;$u<Au.length&&!(Au[$u].type==="softbreak"||Au[$u].type==="hardbreak");$u++)if(Au[$u].content){Gu=Au[$u].content.charCodeAt(0);break}const Wu=isMdAsciiPunct(Vu)||isPunctCharCode(Vu),Ku=isMdAsciiPunct(Gu)||isPunctCharCode(Gu),Ju=isWhiteSpace(Vu),Yu=isWhiteSpace(Gu);if(Yu?zu=!1:Ku&&(Ju||Wu||(zu=!1)),Ju?Uu=!1:Wu&&(Yu||Ku||(Uu=!1)),Gu===34&&Fu[0]==='"'&&Vu>=48&&Vu<=57&&(Uu=zu=!1),zu&&Uu&&(zu=Wu,Uu=Ku),!zu&&!Uu){Hu&&addReplacement(Pu,Ou,Fu.index,APOSTROPHE);continue}if(Uu&&($u=Hu?Iu.single:Iu.double,$u>=0&&Ru[$u].level===Du)){const Xu=Ru[$u];let ed,td;Hu?(ed=lo.md.options.quotes[2],td=lo.md.options.quotes[3]):(ed=lo.md.options.quotes[0],td=lo.md.options.quotes[1]),addReplacement(Pu,Ou,Fu.index,td),addReplacement(Pu,Xu.tokenIdx,Xu.contentPos,ed),truncateStack(Ru,Iu,$u);continue e}if(zu){if(Ru.length>=MAX_OPENERS)return;Ru.push({tokenIdx:Ou,contentPos:Fu.index,isSingleQuote:Hu,level:Du,prevSameQuoteIdx:Hu?Iu.single:Iu.double}),Hu?Iu.single=Ru.length-1:Iu.double=Ru.length-1}else Uu&&Hu&&addReplacement(Pu,Ou,Fu.index,APOSTROPHE)}}Object.keys(Pu).forEach(function(Ou){Au[Ou].content=applyReplacements(Au[Ou].content,Pu[Ou])})}function smartquotes(Au){if(Au.md.options.typographer)for(let lo=Au.tokens.length-1;lo>=0;lo--)Au.tokens[lo].type!=="inline"||!QUOTE_TEST_RE.test(Au.tokens[lo].content)||process_inlines(Au.tokens[lo].children,Au)}function text_join(Au){let lo,$u;const Ru=Au.tokens,Iu=Ru.length;for(let Pu=0;Pu<Iu;Pu++){if(Ru[Pu].type!=="inline")continue;const Ou=Ru[Pu].children,Mu=Ou.length;for(lo=0;lo<Mu;lo++)Ou[lo].type==="text_special"&&(Ou[lo].type="text");for(lo=$u=0;lo<Mu;lo++)Ou[lo].type==="text"&&lo+1<Mu&&Ou[lo+1].type==="text"?Ou[lo+1].content=Ou[lo].content+Ou[lo+1].content:(lo!==$u&&(Ou[$u]=Ou[lo]),$u++);lo!==$u&&(Ou.length=$u)}}const _rules$2=[["normalize",normalize],["block",block],["inline",inline],["linkify",linkify$1],["replacements",replace],["smartquotes",smartquotes],["text_join",text_join]];function Core(){this.ruler=new Ruler;for(let Au=0;Au<_rules$2.length;Au++)this.ruler.push(_rules$2[Au][0],_rules$2[Au][1])}Core.prototype.process=function(Au){const lo=this.ruler.getRules("");for(let $u=0,Ru=lo.length;$u<Ru;$u++)lo[$u](Au)};Core.prototype.State=StateCore;function StateBlock(Au,lo,$u,Ru){this.src=Au,this.md=lo,this.env=$u,this.tokens=Ru,this.bMarks=[],this.eMarks=[],this.tShift=[],this.sCount=[],this.bsCount=[],this.blkIndent=0,this.line=0,this.lineMax=0,this.tight=!1,this.ddIndent=-1,this.listIndent=-1,this.parentType="root",this.level=0;const Iu=this.src;for(let Pu=0,Ou=0,Mu=0,Du=0,Lu=Iu.length,Bu=!1;Ou<Lu;Ou++){const ju=Iu.charCodeAt(Ou);if(!Bu)if(isSpace(ju)){Mu++,ju===9?Du+=4-Du%4:Du++;continue}else Bu=!0;(ju===10||Ou===Lu-1)&&(ju!==10&&Ou++,this.bMarks.push(Pu),this.eMarks.push(Ou),this.tShift.push(Mu),this.sCount.push(Du),this.bsCount.push(0),Bu=!1,Mu=0,Du=0,Pu=Ou+1)}this.bMarks.push(Iu.length),this.eMarks.push(Iu.length),this.tShift.push(0),this.sCount.push(0),this.bsCount.push(0),this.lineMax=this.bMarks.length-1}StateBlock.prototype.push=function(Au,lo,$u){const Ru=new Token(Au,lo,$u);return Ru.block=!0,$u<0&&this.level--,Ru.level=this.level,$u>0&&this.level++,this.tokens.push(Ru),Ru};StateBlock.prototype.isEmpty=function Au(lo){return this.bMarks[lo]+this.tShift[lo]>=this.eMarks[lo]};StateBlock.prototype.skipEmptyLines=function Au(lo){for(let $u=this.lineMax;lo<$u&&!(this.bMarks[lo]+this.tShift[lo]<this.eMarks[lo]);lo++);return lo};StateBlock.prototype.skipSpaces=function Au(lo){for(let $u=this.src.length;lo<$u;lo++){const Ru=this.src.charCodeAt(lo);if(!isSpace(Ru))break}return lo};StateBlock.prototype.skipSpacesBack=function Au(lo,$u){if(lo<=$u)return lo;for(;lo>$u;)if(!isSpace(this.src.charCodeAt(--lo)))return lo+1;return lo};StateBlock.prototype.skipChars=function Au(lo,$u){for(let Ru=this.src.length;lo<Ru&&this.src.charCodeAt(lo)===$u;lo++);return lo};StateBlock.prototype.skipCharsBack=function Au(lo,$u,Ru){if(lo<=Ru)return lo;for(;lo>Ru;)if($u!==this.src.charCodeAt(--lo))return lo+1;return lo};StateBlock.prototype.getLines=function Au(lo,$u,Ru,Iu){if(lo>=$u)return"";const Pu=new Array($u-lo);for(let Ou=0,Mu=lo;Mu<$u;Mu++,Ou++){let Du=0;const Lu=this.bMarks[Mu];let Bu=Lu,ju;for(Mu+1<$u||Iu?ju=this.eMarks[Mu]+1:ju=this.eMarks[Mu];Bu<ju&&Du<Ru;){const Fu=this.src.charCodeAt(Bu);if(isSpace(Fu))Fu===9?Du+=4-(Du+this.bsCount[Mu])%4:Du++;else if(Bu-Lu<this.tShift[Mu])Du++;else break;Bu++}Du>Ru?Pu[Ou]=new Array(Du-Ru+1).join(" ")+this.src.slice(Bu,ju):Pu[Ou]=this.src.slice(Bu,ju)}return Pu.join("")};StateBlock.prototype.Token=Token;const MAX_AUTOCOMPLETED_CELLS=65536;function getLine(Au,lo){const $u=Au.bMarks[lo]+Au.tShift[lo],Ru=Au.eMarks[lo];return Au.src.slice($u,Ru)}function escapedSplit(Au){const lo=[],$u=Au.length;let Ru=0,Iu=Au.charCodeAt(Ru),Pu=!1,Ou=0,Mu="";for(;Ru<$u;)Iu===124&&(Pu?(Mu+=Au.substring(Ou,Ru-1),Ou=Ru):(lo.push(Mu+Au.substring(Ou,Ru)),Mu="",Ou=Ru+1)),Pu=Iu===92,Ru++,Iu=Au.charCodeAt(Ru);return lo.push(Mu+Au.substring(Ou)),lo}function table(Au,lo,$u,Ru){if(lo+2>$u)return!1;let Iu=lo+1;if(Au.sCount[Iu]<Au.blkIndent||Au.sCount[Iu]-Au.blkIndent>=4)return!1;let Pu=Au.bMarks[Iu]+Au.tShift[Iu];if(Pu>=Au.eMarks[Iu])return!1;const Ou=Au.src.charCodeAt(Pu++);if(Ou!==124&&Ou!==45&&Ou!==58||Pu>=Au.eMarks[Iu])return!1;const Mu=Au.src.charCodeAt(Pu++);if(Mu!==124&&Mu!==45&&Mu!==58&&!isSpace(Mu)||Ou===45&&isSpace(Mu))return!1;for(;Pu<Au.eMarks[Iu];){const Ju=Au.src.charCodeAt(Pu);if(Ju!==124&&Ju!==45&&Ju!==58&&!isSpace(Ju))return!1;Pu++}let Du=getLine(Au,lo+1),Lu=Du.split("|");const Bu=[];for(let Ju=0;Ju<Lu.length;Ju++){const Yu=Lu[Ju].trim();if(!Yu){if(Ju===0||Ju===Lu.length-1)continue;return!1}if(!/^:?-+:?$/.test(Yu))return!1;Yu.charCodeAt(Yu.length-1)===58?Bu.push(Yu.charCodeAt(0)===58?"center":"right"):Yu.charCodeAt(0)===58?Bu.push("left"):Bu.push("")}if(Du=getLine(Au,lo).trim(),Du.indexOf("|")===-1||Au.sCount[lo]-Au.blkIndent>=4)return!1;Lu=escapedSplit(Du),Lu.length&&Lu[0]===""&&Lu.shift(),Lu.length&&Lu[Lu.length-1]===""&&Lu.pop();const ju=Lu.length;if(ju===0||ju!==Bu.length)return!1;if(Ru)return!0;const Fu=Au.parentType;Au.parentType="table";const zu=Au.md.block.ruler.getRules("blockquote"),Uu=Au.push("table_open","table",1),Hu=[lo,0];Uu.map=Hu;const Vu=Au.push("thead_open","thead",1);Vu.map=[lo,lo+1];const Gu=Au.push("tr_open","tr",1);Gu.map=[lo,lo+1];for(let Ju=0;Ju<Lu.length;Ju++){const Yu=Au.push("th_open","th",1);Bu[Ju]&&(Yu.attrs=[["style","text-align:"+Bu[Ju]]]);const Xu=Au.push("inline","",0);Xu.content=Lu[Ju].trim(),Xu.children=[],Au.push("th_close","th",-1)}Au.push("tr_close","tr",-1),Au.push("thead_close","thead",-1);let Wu,Ku=0;for(Iu=lo+2;Iu<$u&&!(Au.sCount[Iu]<Au.blkIndent);Iu++){let Ju=!1;for(let Xu=0,ed=zu.length;Xu<ed;Xu++)if(zu[Xu](Au,Iu,$u,!0)){Ju=!0;break}if(Ju||(Du=getLine(Au,Iu).trim(),!Du)||Au.sCount[Iu]-Au.blkIndent>=4||(Lu=escapedSplit(Du),Lu.length&&Lu[0]===""&&Lu.shift(),Lu.length&&Lu[Lu.length-1]===""&&Lu.pop(),Ku+=ju-Lu.length,Ku>MAX_AUTOCOMPLETED_CELLS))break;if(Iu===lo+2){const Xu=Au.push("tbody_open","tbody",1);Xu.map=Wu=[lo+2,0]}const Yu=Au.push("tr_open","tr",1);Yu.map=[Iu,Iu+1];for(let Xu=0;Xu<ju;Xu++){const ed=Au.push("td_open","td",1);Bu[Xu]&&(ed.attrs=[["style","text-align:"+Bu[Xu]]]);const td=Au.push("inline","",0);td.content=Lu[Xu]?Lu[Xu].trim():"",td.children=[],Au.push("td_close","td",-1)}Au.push("tr_close","tr",-1)}return Wu&&(Au.push("tbody_close","tbody",-1),Wu[1]=Iu),Au.push("table_close","table",-1),Hu[1]=Iu,Au.parentType=Fu,Au.line=Iu,!0}function code(Au,lo,$u){if(Au.sCount[lo]-Au.blkIndent<4)return!1;let Ru=lo+1,Iu=Ru;for(;Ru<$u;){if(Au.isEmpty(Ru)){Ru++;continue}if(Au.sCount[Ru]-Au.blkIndent>=4){Ru++,Iu=Ru;continue}break}Au.line=Iu;const Pu=Au.push("code_block","code",0);return Pu.content=Au.getLines(lo,Iu,4+Au.blkIndent,!1)+`
3781
3781
  `,Pu.map=[lo,Au.line],!0}function fence(Au,lo,$u,Ru){let Iu=Au.bMarks[lo]+Au.tShift[lo],Pu=Au.eMarks[lo];if(Au.sCount[lo]-Au.blkIndent>=4||Iu+3>Pu)return!1;const Ou=Au.src.charCodeAt(Iu);if(Ou!==126&&Ou!==96)return!1;let Mu=Iu;Iu=Au.skipChars(Iu,Ou);let Du=Iu-Mu;if(Du<3)return!1;const Lu=Au.src.slice(Mu,Iu),Bu=Au.src.slice(Iu,Pu);if(Ou===96&&Bu.indexOf(String.fromCharCode(Ou))>=0)return!1;if(Ru)return!0;let ju=lo,Fu=!1;for(;ju++,!(ju>=$u||(Iu=Mu=Au.bMarks[ju]+Au.tShift[ju],Pu=Au.eMarks[ju],Iu<Pu&&Au.sCount[ju]<Au.blkIndent));)if(Au.src.charCodeAt(Iu)===Ou&&!(Au.sCount[ju]-Au.blkIndent>=4)&&(Iu=Au.skipChars(Iu,Ou),!(Iu-Mu<Du)&&(Iu=Au.skipSpaces(Iu),!(Iu<Pu)))){Fu=!0;break}Du=Au.sCount[lo],Au.line=ju+(Fu?1:0);const zu=Au.push("fence","code",0);return zu.info=Bu,zu.content=Au.getLines(lo+1,ju,Du,!0),zu.markup=Lu,zu.map=[lo,Au.line],!0}function blockquote(Au,lo,$u,Ru){let Iu=Au.bMarks[lo]+Au.tShift[lo],Pu=Au.eMarks[lo];const Ou=Au.lineMax;if(Au.sCount[lo]-Au.blkIndent>=4||Au.src.charCodeAt(Iu)!==62)return!1;if(Ru)return!0;const Mu=[],Du=[],Lu=[],Bu=[],ju=Au.md.block.ruler.getRules("blockquote"),Fu=Au.parentType;Au.parentType="blockquote";let zu=!1,Uu;for(Uu=lo;Uu<$u;Uu++){const Ku=Au.sCount[Uu]<Au.blkIndent;if(Iu=Au.bMarks[Uu]+Au.tShift[Uu],Pu=Au.eMarks[Uu],Iu>=Pu)break;if(Au.src.charCodeAt(Iu++)===62&&!Ku){let Yu=Au.sCount[Uu]+1,Xu,ed;Au.src.charCodeAt(Iu)===32?(Iu++,Yu++,ed=!1,Xu=!0):Au.src.charCodeAt(Iu)===9?(Xu=!0,(Au.bsCount[Uu]+Yu)%4===3?(Iu++,Yu++,ed=!1):ed=!0):Xu=!1;let td=Yu;for(Mu.push(Au.bMarks[Uu]),Au.bMarks[Uu]=Iu;Iu<Pu;){const nd=Au.src.charCodeAt(Iu);if(isSpace(nd))nd===9?td+=4-(td+Au.bsCount[Uu]+(ed?1:0))%4:td++;else break;Iu++}zu=Iu>=Pu,Du.push(Au.bsCount[Uu]),Au.bsCount[Uu]=Au.sCount[Uu]+1+(Xu?1:0),Lu.push(Au.sCount[Uu]),Au.sCount[Uu]=td-Yu,Bu.push(Au.tShift[Uu]),Au.tShift[Uu]=Iu-Au.bMarks[Uu];continue}if(zu)break;let Ju=!1;for(let Yu=0,Xu=ju.length;Yu<Xu;Yu++)if(ju[Yu](Au,Uu,$u,!0)){Ju=!0;break}if(Ju){Au.lineMax=Uu,Au.blkIndent!==0&&(Mu.push(Au.bMarks[Uu]),Du.push(Au.bsCount[Uu]),Bu.push(Au.tShift[Uu]),Lu.push(Au.sCount[Uu]),Au.sCount[Uu]-=Au.blkIndent);break}Mu.push(Au.bMarks[Uu]),Du.push(Au.bsCount[Uu]),Bu.push(Au.tShift[Uu]),Lu.push(Au.sCount[Uu]),Au.sCount[Uu]=-1}const Hu=Au.blkIndent;Au.blkIndent=0;const Vu=Au.push("blockquote_open","blockquote",1);Vu.markup=">";const Gu=[lo,0];Vu.map=Gu,Au.md.block.tokenize(Au,lo,Uu);const Wu=Au.push("blockquote_close","blockquote",-1);Wu.markup=">",Au.lineMax=Ou,Au.parentType=Fu,Gu[1]=Au.line;for(let Ku=0;Ku<Bu.length;Ku++)Au.bMarks[Ku+lo]=Mu[Ku],Au.tShift[Ku+lo]=Bu[Ku],Au.sCount[Ku+lo]=Lu[Ku],Au.bsCount[Ku+lo]=Du[Ku];return Au.blkIndent=Hu,!0}function hr(Au,lo,$u,Ru){const Iu=Au.eMarks[lo];if(Au.sCount[lo]-Au.blkIndent>=4)return!1;let Pu=Au.bMarks[lo]+Au.tShift[lo];const Ou=Au.src.charCodeAt(Pu++);if(Ou!==42&&Ou!==45&&Ou!==95)return!1;let Mu=1;for(;Pu<Iu;){const Lu=Au.src.charCodeAt(Pu++);if(Lu!==Ou&&!isSpace(Lu))return!1;Lu===Ou&&Mu++}if(Mu<3)return!1;if(Ru)return!0;Au.line=lo+1;const Du=Au.push("hr","hr",0);return Du.map=[lo,Au.line],Du.markup=Array(Mu+1).join(String.fromCharCode(Ou)),!0}function skipBulletListMarker(Au,lo){const $u=Au.eMarks[lo];let Ru=Au.bMarks[lo]+Au.tShift[lo];const Iu=Au.src.charCodeAt(Ru++);if(Iu!==42&&Iu!==45&&Iu!==43)return-1;if(Ru<$u){const Pu=Au.src.charCodeAt(Ru);if(!isSpace(Pu))return-1}return Ru}function skipOrderedListMarker(Au,lo){const $u=Au.bMarks[lo]+Au.tShift[lo],Ru=Au.eMarks[lo];let Iu=$u;if(Iu+1>=Ru)return-1;let Pu=Au.src.charCodeAt(Iu++);if(Pu<48||Pu>57)return-1;for(;;){if(Iu>=Ru)return-1;if(Pu=Au.src.charCodeAt(Iu++),Pu>=48&&Pu<=57){if(Iu-$u>=10)return-1;continue}if(Pu===41||Pu===46)break;return-1}return Iu<Ru&&(Pu=Au.src.charCodeAt(Iu),!isSpace(Pu))?-1:Iu}function markTightParagraphs(Au,lo){const $u=Au.level+2;for(let Ru=lo+2,Iu=Au.tokens.length-2;Ru<Iu;Ru++)Au.tokens[Ru].level===$u&&Au.tokens[Ru].type==="paragraph_open"&&(Au.tokens[Ru+2].hidden=!0,Au.tokens[Ru].hidden=!0,Ru+=2)}function list(Au,lo,$u,Ru){let Iu,Pu,Ou,Mu,Du=lo,Lu=!0;if(Au.sCount[Du]-Au.blkIndent>=4||Au.listIndent>=0&&Au.sCount[Du]-Au.listIndent>=4&&Au.sCount[Du]<Au.blkIndent)return!1;let Bu=!1;Ru&&Au.parentType==="paragraph"&&Au.sCount[Du]>=Au.blkIndent&&(Bu=!0);let ju,Fu,zu;if((zu=skipOrderedListMarker(Au,Du))>=0){if(ju=!0,Ou=Au.bMarks[Du]+Au.tShift[Du],Fu=Number(Au.src.slice(Ou,zu-1)),Bu&&Fu!==1)return!1}else if((zu=skipBulletListMarker(Au,Du))>=0)ju=!1;else return!1;if(Bu&&Au.skipSpaces(zu)>=Au.eMarks[Du])return!1;if(Ru)return!0;const Uu=Au.src.charCodeAt(zu-1),Hu=Au.tokens.length;ju?(Mu=Au.push("ordered_list_open","ol",1),Fu!==1&&(Mu.attrs=[["start",Fu]])):Mu=Au.push("bullet_list_open","ul",1);const Vu=[Du,0];Mu.map=Vu,Mu.markup=String.fromCharCode(Uu);let Gu=!1;const Wu=Au.md.block.ruler.getRules("list"),Ku=Au.parentType;for(Au.parentType="list";Du<$u;){Pu=zu,Iu=Au.eMarks[Du];const Ju=Au.sCount[Du]+zu-(Au.bMarks[Du]+Au.tShift[Du]);let Yu=Ju;for(;Pu<Iu;){const xd=Au.src.charCodeAt(Pu);if(xd===9)Yu+=4-(Yu+Au.bsCount[Du])%4;else if(xd===32)Yu++;else break;Pu++}const Xu=Pu;let ed;Xu>=Iu?ed=1:ed=Yu-Ju,ed>4&&(ed=1);const td=Ju+ed;Mu=Au.push("list_item_open","li",1),Mu.markup=String.fromCharCode(Uu);const nd=[Du,0];Mu.map=nd,ju&&(Mu.info=Au.src.slice(Ou,zu-1));const od=Au.tight,sd=Au.tShift[Du],ad=Au.sCount[Du],pd=Au.listIndent;if(Au.listIndent=Au.blkIndent,Au.blkIndent=td,Au.tight=!0,Au.tShift[Du]=Xu-Au.bMarks[Du],Au.sCount[Du]=Yu,Xu>=Iu&&Au.isEmpty(Du+1)?Au.line=Math.min(Au.line+2,$u):Au.md.block.tokenize(Au,Du,$u,!0),(!Au.tight||Gu)&&(Lu=!1),Gu=Au.line-Du>1&&Au.isEmpty(Au.line-1),Au.blkIndent=Au.listIndent,Au.listIndent=pd,Au.tShift[Du]=sd,Au.sCount[Du]=ad,Au.tight=od,Mu=Au.push("list_item_close","li",-1),Mu.markup=String.fromCharCode(Uu),Du=Au.line,nd[1]=Du,Du>=$u||Au.sCount[Du]<Au.blkIndent||Au.sCount[Du]-Au.blkIndent>=4)break;let gd=!1;for(let xd=0,yd=Wu.length;xd<yd;xd++)if(Wu[xd](Au,Du,$u,!0)){gd=!0;break}if(gd)break;if(ju){if(zu=skipOrderedListMarker(Au,Du),zu<0)break;Ou=Au.bMarks[Du]+Au.tShift[Du]}else if(zu=skipBulletListMarker(Au,Du),zu<0)break;if(Uu!==Au.src.charCodeAt(zu-1))break}return ju?Mu=Au.push("ordered_list_close","ol",-1):Mu=Au.push("bullet_list_close","ul",-1),Mu.markup=String.fromCharCode(Uu),Vu[1]=Du,Au.line=Du,Au.parentType=Ku,Lu&&markTightParagraphs(Au,Hu),!0}function reference(Au,lo,$u,Ru){let Iu=Au.bMarks[lo]+Au.tShift[lo],Pu=Au.eMarks[lo],Ou=lo+1;if(Au.sCount[lo]-Au.blkIndent>=4||Au.src.charCodeAt(Iu)!==91)return!1;function Mu(Wu){const Ku=Au.lineMax;if(Wu>=Ku||Au.isEmpty(Wu))return null;let Ju=!1;if(Au.sCount[Wu]-Au.blkIndent>3&&(Ju=!0),Au.sCount[Wu]<0&&(Ju=!0),!Ju){const ed=Au.md.block.ruler.getRules("reference"),td=Au.parentType;Au.parentType="reference";let nd=!1;for(let od=0,sd=ed.length;od<sd;od++)if(ed[od](Au,Wu,Ku,!0)){nd=!0;break}if(Au.parentType=td,nd)return null}const Yu=Au.bMarks[Wu]+Au.tShift[Wu],Xu=Au.eMarks[Wu];return Au.src.slice(Yu,Xu+1)}let Du=Au.src.slice(Iu,Pu+1);Pu=Du.length;let Lu=-1;for(Iu=1;Iu<Pu;Iu++){const Wu=Du.charCodeAt(Iu);if(Wu===91)return!1;if(Wu===93){Lu=Iu;break}else if(Wu===10){const Ku=Mu(Ou);Ku!==null&&(Du+=Ku,Pu=Du.length,Ou++)}else if(Wu===92&&(Iu++,Iu<Pu&&Du.charCodeAt(Iu)===10)){const Ku=Mu(Ou);Ku!==null&&(Du+=Ku,Pu=Du.length,Ou++)}}if(Lu<0||Du.charCodeAt(Lu+1)!==58)return!1;for(Iu=Lu+2;Iu<Pu;Iu++){const Wu=Du.charCodeAt(Iu);if(Wu===10){const Ku=Mu(Ou);Ku!==null&&(Du+=Ku,Pu=Du.length,Ou++)}else if(!isSpace(Wu))break}const Bu=Au.md.helpers.parseLinkDestination(Du,Iu,Pu);if(!Bu.ok)return!1;const ju=Au.md.normalizeLink(Bu.str);if(!Au.md.validateLink(ju))return!1;Iu=Bu.pos;const Fu=Iu,zu=Ou,Uu=Iu;for(;Iu<Pu;Iu++){const Wu=Du.charCodeAt(Iu);if(Wu===10){const Ku=Mu(Ou);Ku!==null&&(Du+=Ku,Pu=Du.length,Ou++)}else if(!isSpace(Wu))break}let Hu=Au.md.helpers.parseLinkTitle(Du,Iu,Pu);for(;Hu.can_continue;){const Wu=Mu(Ou);if(Wu===null)break;Du+=Wu,Iu=Pu,Pu=Du.length,Ou++,Hu=Au.md.helpers.parseLinkTitle(Du,Iu,Pu,Hu)}let Vu;for(Iu<Pu&&Uu!==Iu&&Hu.ok?(Vu=Hu.str,Iu=Hu.pos):(Vu="",Iu=Fu,Ou=zu);Iu<Pu;){const Wu=Du.charCodeAt(Iu);if(!isSpace(Wu))break;Iu++}if(Iu<Pu&&Du.charCodeAt(Iu)!==10&&Vu)for(Vu="",Iu=Fu,Ou=zu;Iu<Pu;){const Wu=Du.charCodeAt(Iu);if(!isSpace(Wu))break;Iu++}if(Iu<Pu&&Du.charCodeAt(Iu)!==10)return!1;const Gu=normalizeReference(Du.slice(1,Lu));return Gu?(Ru||(typeof Au.env.references>"u"&&(Au.env.references={}),typeof Au.env.references[Gu]>"u"&&(Au.env.references[Gu]={title:Vu,href:ju}),Au.line=Ou),!0):!1}const block_names=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],attr_name="[a-zA-Z_:][a-zA-Z0-9:._-]*",unquoted="[^\"'=<>`\\x00-\\x20]+",single_quoted="'[^']*'",double_quoted='"[^"]*"',attr_value="(?:"+unquoted+"|"+single_quoted+"|"+double_quoted+")",attribute="(?:\\s+"+attr_name+"(?:\\s*=\\s*"+attr_value+")?)",open_tag="<[A-Za-z][A-Za-z0-9\\-]*"+attribute+"*\\s*\\/?>",close_tag="<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>",comment="<!---?>|<!--(?:[^-]|-[^-]|--[^>])*-->",processing="<[?][\\s\\S]*?[?]>",declaration="<![A-Za-z][^>]*>",cdata="<!\\[CDATA\\[[\\s\\S]*?\\]\\]>",HTML_TAG_RE=new RegExp("^(?:"+open_tag+"|"+close_tag+"|"+comment+"|"+processing+"|"+declaration+"|"+cdata+")"),HTML_OPEN_CLOSE_TAG_RE=new RegExp("^(?:"+open_tag+"|"+close_tag+")"),HTML_SEQUENCES=[[/^<(script|pre|style|textarea)(?=(\s|>|$))/i,/<\/(script|pre|style|textarea)>/i,!0],[/^<!--/,/-->/,!0],[/^<\?/,/\?>/,!0],[/^<![A-Za-z]/,/>/,!0],[/^<!\[CDATA\[/,/\]\]>/,!0],[new RegExp("^</?("+block_names.join("|")+")(?=(\\s|/?>|$))","i"),/^$/,!0],[new RegExp(HTML_OPEN_CLOSE_TAG_RE.source+"\\s*$"),/^$/,!1]];function html_block(Au,lo,$u,Ru){let Iu=Au.bMarks[lo]+Au.tShift[lo],Pu=Au.eMarks[lo];if(Au.sCount[lo]-Au.blkIndent>=4||!Au.md.options.html||Au.src.charCodeAt(Iu)!==60)return!1;let Ou=Au.src.slice(Iu,Pu),Mu=0;for(;Mu<HTML_SEQUENCES.length&&!HTML_SEQUENCES[Mu][0].test(Ou);Mu++);if(Mu===HTML_SEQUENCES.length)return!1;if(Ru)return HTML_SEQUENCES[Mu][2];let Du=lo+1;const Lu=HTML_SEQUENCES[Mu][1].test("");if(!HTML_SEQUENCES[Mu][1].test(Ou)){for(;Du<$u&&!(Au.sCount[Du]<Au.blkIndent&&(Lu||!Au.isEmpty(Du)));Du++)if(Iu=Au.bMarks[Du]+Au.tShift[Du],Pu=Au.eMarks[Du],Ou=Au.src.slice(Iu,Pu),HTML_SEQUENCES[Mu][1].test(Ou)){Ou.length!==0&&Du++;break}}Au.line=Du;const Bu=Au.push("html_block","",0);return Bu.map=[lo,Du],Bu.content=Au.getLines(lo,Du,Au.blkIndent,!0),!0}function heading(Au,lo,$u,Ru){let Iu=Au.bMarks[lo]+Au.tShift[lo],Pu=Au.eMarks[lo];if(Au.sCount[lo]-Au.blkIndent>=4)return!1;let Ou=Au.src.charCodeAt(Iu);if(Ou!==35||Iu>=Pu)return!1;let Mu=1;for(Ou=Au.src.charCodeAt(++Iu);Ou===35&&Iu<Pu&&Mu<=6;)Mu++,Ou=Au.src.charCodeAt(++Iu);if(Mu>6||Iu<Pu&&!isSpace(Ou))return!1;if(Ru)return!0;Pu=Au.skipSpacesBack(Pu,Iu);const Du=Au.skipCharsBack(Pu,35,Iu);Du>Iu&&isSpace(Au.src.charCodeAt(Du-1))&&(Pu=Du),Au.line=lo+1;const Lu=Au.push("heading_open","h"+String(Mu),1);Lu.markup="########".slice(0,Mu),Lu.map=[lo,Au.line];const Bu=Au.push("inline","",0);Bu.content=asciiTrim(Au.src.slice(Iu,Pu)),Bu.map=[lo,Au.line],Bu.children=[];const ju=Au.push("heading_close","h"+String(Mu),-1);return ju.markup="########".slice(0,Mu),!0}function lheading(Au,lo,$u){const Ru=Au.md.block.ruler.getRules("paragraph");if(Au.sCount[lo]-Au.blkIndent>=4)return!1;const Iu=Au.parentType;Au.parentType="paragraph";let Pu=0,Ou,Mu=lo+1;for(;Mu<$u&&!Au.isEmpty(Mu);Mu++){if(Au.sCount[Mu]-Au.blkIndent>3)continue;if(Au.sCount[Mu]>=Au.blkIndent){let zu=Au.bMarks[Mu]+Au.tShift[Mu];const Uu=Au.eMarks[Mu];if(zu<Uu&&(Ou=Au.src.charCodeAt(zu),(Ou===45||Ou===61)&&(zu=Au.skipChars(zu,Ou),zu=Au.skipSpaces(zu),zu>=Uu))){Pu=Ou===61?1:2;break}}if(Au.sCount[Mu]<0)continue;let Fu=!1;for(let zu=0,Uu=Ru.length;zu<Uu;zu++)if(Ru[zu](Au,Mu,$u,!0)){Fu=!0;break}if(Fu)break}if(!Pu)return Au.parentType=Iu,!1;const Du=asciiTrim(Au.getLines(lo,Mu,Au.blkIndent,!1));Au.line=Mu+1;const Lu=Au.push("heading_open","h"+String(Pu),1);Lu.markup=String.fromCharCode(Ou),Lu.map=[lo,Au.line];const Bu=Au.push("inline","",0);Bu.content=Du,Bu.map=[lo,Au.line-1],Bu.children=[];const ju=Au.push("heading_close","h"+String(Pu),-1);return ju.markup=String.fromCharCode(Ou),Au.parentType=Iu,!0}function paragraph(Au,lo,$u){const Ru=Au.md.block.ruler.getRules("paragraph"),Iu=Au.parentType;let Pu=lo+1;for(Au.parentType="paragraph";Pu<$u&&!Au.isEmpty(Pu);Pu++){if(Au.sCount[Pu]-Au.blkIndent>3||Au.sCount[Pu]<0)continue;let Lu=!1;for(let Bu=0,ju=Ru.length;Bu<ju;Bu++)if(Ru[Bu](Au,Pu,$u,!0)){Lu=!0;break}if(Lu)break}const Ou=asciiTrim(Au.getLines(lo,Pu,Au.blkIndent,!1));Au.line=Pu;const Mu=Au.push("paragraph_open","p",1);Mu.map=[lo,Au.line];const Du=Au.push("inline","",0);return Du.content=Ou,Du.map=[lo,Au.line],Du.children=[],Au.push("paragraph_close","p",-1),Au.parentType=Iu,!0}const _rules$1=[["table",table,["paragraph","reference"]],["code",code],["fence",fence,["paragraph","reference","blockquote","list"]],["blockquote",blockquote,["paragraph","reference","blockquote","list"]],["hr",hr,["paragraph","reference","blockquote","list"]],["list",list,["paragraph","reference","blockquote"]],["reference",reference],["html_block",html_block,["paragraph","reference","blockquote"]],["heading",heading,["paragraph","reference","blockquote"]],["lheading",lheading],["paragraph",paragraph]];function ParserBlock(){this.ruler=new Ruler;for(let Au=0;Au<_rules$1.length;Au++)this.ruler.push(_rules$1[Au][0],_rules$1[Au][1],{alt:(_rules$1[Au][2]||[]).slice()})}ParserBlock.prototype.tokenize=function(Au,lo,$u){const Ru=this.ruler.getRules(""),Iu=Ru.length,Pu=Au.md.options.maxNesting;let Ou=lo,Mu=!1;for(;Ou<$u&&(Au.line=Ou=Au.skipEmptyLines(Ou),!(Ou>=$u||Au.sCount[Ou]<Au.blkIndent));){if(Au.level>=Pu){Au.line=$u;break}const Du=Au.line;let Lu=!1;for(let Bu=0;Bu<Iu;Bu++)if(Lu=Ru[Bu](Au,Ou,$u,!1),Lu){if(Du>=Au.line)throw new Error("block rule didn't increment state.line");break}if(!Lu)throw new Error("none of the block rules matched");Au.tight=!Mu,Au.isEmpty(Au.line-1)&&(Mu=!0),Ou=Au.line,Ou<$u&&Au.isEmpty(Ou)&&(Mu=!0,Ou++,Au.line=Ou)}};ParserBlock.prototype.parse=function(Au,lo,$u,Ru){if(!Au)return;const Iu=new this.State(Au,lo,$u,Ru);this.tokenize(Iu,Iu.line,Iu.lineMax)};ParserBlock.prototype.State=StateBlock;function StateInline(Au,lo,$u,Ru){this.src=Au,this.env=$u,this.md=lo,this.tokens=Ru,this.tokens_meta=Array(Ru.length),this.pos=0,this.posMax=this.src.length,this.level=0,this.pending="",this.pendingLevel=0,this.cache={},this.delimiters=[],this._prev_delimiters=[],this.backticks={},this.backticksScanned=!1,this.linkLevel=0}StateInline.prototype.pushPending=function(){const Au=new Token("text","",0);return Au.content=this.pending,Au.level=this.pendingLevel,this.tokens.push(Au),this.pending="",Au};StateInline.prototype.push=function(Au,lo,$u){this.pending&&this.pushPending();const Ru=new Token(Au,lo,$u);let Iu=null;return $u<0&&(this.level--,this.delimiters=this._prev_delimiters.pop()),Ru.level=this.level,$u>0&&(this.level++,this._prev_delimiters.push(this.delimiters),this.delimiters=[],Iu={delimiters:this.delimiters}),this.pendingLevel=this.level,this.tokens.push(Ru),this.tokens_meta.push(Iu),Ru};StateInline.prototype.scanDelims=function(Au,lo){const $u=this.posMax,Ru=this.src.charCodeAt(Au);let Iu;if(Au===0)Iu=32;else if(Au===1)Iu=this.src.charCodeAt(0),(Iu&63488)===55296&&(Iu=65533);else if(Iu=this.src.charCodeAt(Au-1),(Iu&64512)===56320){const Vu=this.src.charCodeAt(Au-2);Iu=(Vu&64512)===55296?65536+(Vu-55296<<10)+(Iu-56320):65533}else(Iu&64512)===55296&&(Iu=65533);let Pu=Au;for(;Pu<$u&&this.src.charCodeAt(Pu)===Ru;)Pu++;const Ou=Pu-Au;let Mu=Pu<$u?this.src.charCodeAt(Pu):32;if((Mu&64512)===55296){const Vu=this.src.charCodeAt(Pu+1);Mu=(Vu&64512)===56320?65536+(Mu-55296<<10)+(Vu-56320):65533}else(Mu&64512)===56320&&(Mu=65533);const Du=isMdAsciiPunct(Iu)||isPunctCharCode(Iu),Lu=isMdAsciiPunct(Mu)||isPunctCharCode(Mu),Bu=isWhiteSpace(Iu),ju=isWhiteSpace(Mu),Fu=!ju&&(!Lu||Bu||Du),zu=!Bu&&(!Du||ju||Lu);return{can_open:Fu&&(lo||!zu||Du),can_close:zu&&(lo||!Fu||Lu),length:Ou}};StateInline.prototype.Token=Token;function isTerminatorChar(Au){switch(Au){case 10:case 33:case 35:case 36:case 37:case 38:case 42:case 43:case 45:case 58:case 60:case 61:case 62:case 64:case 91:case 92:case 93:case 94:case 95:case 96:case 123:case 125:case 126:return!0;default:return!1}}function text$2(Au,lo){let $u=Au.pos;for(;$u<Au.posMax&&!isTerminatorChar(Au.src.charCodeAt($u));)$u++;return $u===Au.pos?!1:(lo||(Au.pending+=Au.src.slice(Au.pos,$u)),Au.pos=$u,!0)}function isAsciiAlpha(Au){return Au>=65&&Au<=90||Au>=97&&Au<=122}function isSchemeChar(Au){return Au>=65&&Au<=90||Au>=97&&Au<=122||Au>=48&&Au<=57||Au===43||Au===45||Au===46}function linkify(Au,lo){if(!Au.md.options.linkify||Au.linkLevel>0)return!1;const $u=Au.pos,Ru=Au.posMax;if($u+3>Ru||Au.src.charCodeAt($u)!==58||Au.src.charCodeAt($u+1)!==47||Au.src.charCodeAt($u+2)!==47)return!1;const Iu=$u-Math.min(10,Au.pending.length,$u);let Pu=$u;for(;Pu>Iu&&isSchemeChar(Au.src.charCodeAt(Pu-1));)Pu--;if(Pu===$u||!isAsciiAlpha(Au.src.charCodeAt(Pu)))return!1;const Ou=$u-Pu,Mu=Au.md.linkify.matchAtStart(Au.src.slice(Pu));if(!Mu)return!1;let Du=Mu.url;if(Du.length<=Ou)return!1;let Lu=Du.length;for(;Lu>0&&Du.charCodeAt(Lu-1)===42;)Lu--;Lu!==Du.length&&(Du=Du.slice(0,Lu));const Bu=Au.md.normalizeLink(Du);if(!Au.md.validateLink(Bu))return!1;if(!lo){Au.pending=Au.pending.slice(0,-Ou);const ju=Au.push("link_open","a",1);ju.attrs=[["href",Bu]],ju.markup="linkify",ju.info="auto";const Fu=Au.push("text","",0);Fu.content=Au.md.normalizeLinkText(Du);const zu=Au.push("link_close","a",-1);zu.markup="linkify",zu.info="auto"}return Au.pos+=Du.length-Ou,!0}function newline(Au,lo){let $u=Au.pos;if(Au.src.charCodeAt($u)!==10)return!1;const Ru=Au.pending.length-1,Iu=Au.posMax;if(!lo)if(Ru>=0&&Au.pending.charCodeAt(Ru)===32)if(Ru>=1&&Au.pending.charCodeAt(Ru-1)===32){let Pu=Ru-1;for(;Pu>=1&&Au.pending.charCodeAt(Pu-1)===32;)Pu--;Au.pending=Au.pending.slice(0,Pu),Au.push("hardbreak","br",0)}else Au.pending=Au.pending.slice(0,-1),Au.push("softbreak","br",0);else Au.push("softbreak","br",0);for($u++;$u<Iu&&isSpace(Au.src.charCodeAt($u));)$u++;return Au.pos=$u,!0}const ESCAPED=[];for(let Au=0;Au<256;Au++)ESCAPED.push(0);"\\!\"#$%&'()*+,./:;<=>?@[]^_`{|}~-".split("").forEach(function(Au){ESCAPED[Au.charCodeAt(0)]=1});function escape$1(Au,lo){let $u=Au.pos;const Ru=Au.posMax;if(Au.src.charCodeAt($u)!==92||($u++,$u>=Ru))return!1;let Iu=Au.src.charCodeAt($u);if(Iu===10){for(lo||Au.push("hardbreak","br",0),$u++;$u<Ru&&(Iu=Au.src.charCodeAt($u),!!isSpace(Iu));)$u++;return Au.pos=$u,!0}if(Iu===32){if(!lo){const Mu=Au.push("text_special","",0);Mu.content="\\",Mu.markup="\\",Mu.info="escape"}return Au.pos=$u,!0}let Pu=Au.src[$u];if(Iu>=55296&&Iu<=56319&&$u+1<Ru){const Mu=Au.src.charCodeAt($u+1);Mu>=56320&&Mu<=57343&&(Pu+=Au.src[$u+1],$u++)}const Ou="\\"+Pu;if(!lo){const Mu=Au.push("text_special","",0);Iu<256&&ESCAPED[Iu]!==0?Mu.content=Pu:Mu.content=Ou,Mu.markup=Ou,Mu.info="escape"}return Au.pos=$u+1,!0}function backtick(Au,lo){let $u=Au.pos;if(Au.src.charCodeAt($u)!==96)return!1;const Iu=$u;$u++;const Pu=Au.posMax;for(;$u<Pu&&Au.src.charCodeAt($u)===96;)$u++;const Ou=Au.src.slice(Iu,$u),Mu=Ou.length;if(Au.backticksScanned&&(Au.backticks[Mu]||0)<=Iu)return lo||(Au.pending+=Ou),Au.pos+=Mu,!0;let Du=$u,Lu;for(;(Lu=Au.src.indexOf("`",Du))!==-1;){for(Du=Lu+1;Du<Pu&&Au.src.charCodeAt(Du)===96;)Du++;const Bu=Du-Lu;if(Bu===Mu){if(!lo){const ju=Au.push("code_inline","code",0);ju.markup=Ou,ju.content=Au.src.slice($u,Lu).replace(/\n/g," ").replace(/^ (.+) $/,"$1")}return Au.pos=Du,!0}Au.backticks[Bu]=Lu}return Au.backticksScanned=!0,lo||(Au.pending+=Ou),Au.pos+=Mu,!0}function strikethrough_tokenize(Au,lo){const $u=Au.pos,Ru=Au.src.charCodeAt($u);if(lo||Ru!==126)return!1;const Iu=Au.scanDelims(Au.pos,!0);let Pu=Iu.length;const Ou=String.fromCharCode(Ru);if(Pu<2)return!1;let Mu;Pu%2&&(Mu=Au.push("text","",0),Mu.content=Ou,Pu--);for(let Du=0;Du<Pu;Du+=2)Mu=Au.push("text","",0),Mu.content=Ou+Ou,Au.delimiters.push({marker:Ru,length:0,token:Au.tokens.length-1,end:-1,open:Iu.can_open,close:Iu.can_close});return Au.pos+=Iu.length,!0}function postProcess$1(Au,lo){let $u;const Ru=[],Iu=lo.length;for(let Pu=0;Pu<Iu;Pu++){const Ou=lo[Pu];if(Ou.marker!==126||Ou.end===-1)continue;const Mu=lo[Ou.end];$u=Au.tokens[Ou.token],$u.type="s_open",$u.tag="s",$u.nesting=1,$u.markup="~~",$u.content="",$u=Au.tokens[Mu.token],$u.type="s_close",$u.tag="s",$u.nesting=-1,$u.markup="~~",$u.content="",Au.tokens[Mu.token-1].type==="text"&&Au.tokens[Mu.token-1].content==="~"&&Ru.push(Mu.token-1)}for(;Ru.length;){const Pu=Ru.pop();let Ou=Pu+1;for(;Ou<Au.tokens.length&&Au.tokens[Ou].type==="s_close";)Ou++;Ou--,Pu!==Ou&&($u=Au.tokens[Ou],Au.tokens[Ou]=Au.tokens[Pu],Au.tokens[Pu]=$u)}}function strikethrough_postProcess(Au){const lo=Au.tokens_meta,$u=Au.tokens_meta.length;postProcess$1(Au,Au.delimiters);for(let Ru=0;Ru<$u;Ru++)lo[Ru]&&lo[Ru].delimiters&&postProcess$1(Au,lo[Ru].delimiters)}const r_strikethrough={tokenize:strikethrough_tokenize,postProcess:strikethrough_postProcess};function emphasis_tokenize(Au,lo){const $u=Au.pos,Ru=Au.src.charCodeAt($u);if(lo||Ru!==95&&Ru!==42)return!1;const Iu=Au.scanDelims(Au.pos,Ru===42);for(let Pu=0;Pu<Iu.length;Pu++){const Ou=Au.push("text","",0);Ou.content=String.fromCharCode(Ru),Au.delimiters.push({marker:Ru,length:Iu.length,token:Au.tokens.length-1,end:-1,open:Iu.can_open,close:Iu.can_close})}return Au.pos+=Iu.length,!0}function postProcess(Au,lo){const $u=lo.length;for(let Ru=$u-1;Ru>=0;Ru--){const Iu=lo[Ru];if(Iu.marker!==95&&Iu.marker!==42||Iu.end===-1)continue;const Pu=lo[Iu.end],Ou=Ru>0&&lo[Ru-1].end===Iu.end+1&&lo[Ru-1].marker===Iu.marker&&lo[Ru-1].token===Iu.token-1&&lo[Iu.end+1].token===Pu.token+1,Mu=String.fromCharCode(Iu.marker),Du=Au.tokens[Iu.token];Du.type=Ou?"strong_open":"em_open",Du.tag=Ou?"strong":"em",Du.nesting=1,Du.markup=Ou?Mu+Mu:Mu,Du.content="";const Lu=Au.tokens[Pu.token];Lu.type=Ou?"strong_close":"em_close",Lu.tag=Ou?"strong":"em",Lu.nesting=-1,Lu.markup=Ou?Mu+Mu:Mu,Lu.content="",Ou&&(Au.tokens[lo[Ru-1].token].content="",Au.tokens[lo[Iu.end+1].token].content="",Ru--)}}function emphasis_post_process(Au){const lo=Au.tokens_meta,$u=Au.tokens_meta.length;postProcess(Au,Au.delimiters);for(let Ru=0;Ru<$u;Ru++)lo[Ru]&&lo[Ru].delimiters&&postProcess(Au,lo[Ru].delimiters)}const r_emphasis={tokenize:emphasis_tokenize,postProcess:emphasis_post_process};function link(Au,lo){let $u,Ru,Iu,Pu,Ou="",Mu="",Du=Au.pos,Lu=!0;if(Au.src.charCodeAt(Au.pos)!==91)return!1;const Bu=Au.pos,ju=Au.posMax,Fu=Au.pos+1,zu=Au.md.helpers.parseLinkLabel(Au,Au.pos,!0);if(zu<0)return!1;let Uu=zu+1;if(Uu<ju&&Au.src.charCodeAt(Uu)===40){for(Lu=!1,Uu++;Uu<ju&&($u=Au.src.charCodeAt(Uu),!(!isSpace($u)&&$u!==10));Uu++);if(Uu>=ju)return!1;if(Du=Uu,Iu=Au.md.helpers.parseLinkDestination(Au.src,Uu,Au.posMax),Iu.ok){for(Ou=Au.md.normalizeLink(Iu.str),Au.md.validateLink(Ou)?Uu=Iu.pos:Ou="",Du=Uu;Uu<ju&&($u=Au.src.charCodeAt(Uu),!(!isSpace($u)&&$u!==10));Uu++);if(Iu=Au.md.helpers.parseLinkTitle(Au.src,Uu,Au.posMax),Uu<ju&&Du!==Uu&&Iu.ok)for(Mu=Iu.str,Uu=Iu.pos;Uu<ju&&($u=Au.src.charCodeAt(Uu),!(!isSpace($u)&&$u!==10));Uu++);}(Uu>=ju||Au.src.charCodeAt(Uu)!==41)&&(Lu=!0),Uu++}if(Lu){if(typeof Au.env.references>"u")return!1;if(Uu<ju&&Au.src.charCodeAt(Uu)===91?(Du=Uu+1,Uu=Au.md.helpers.parseLinkLabel(Au,Uu),Uu>=0?Ru=Au.src.slice(Du,Uu++):Uu=zu+1):Uu=zu+1,Ru||(Ru=Au.src.slice(Fu,zu)),Pu=Au.env.references[normalizeReference(Ru)],!Pu)return Au.pos=Bu,!1;Ou=Pu.href,Mu=Pu.title}if(!lo){Au.pos=Fu,Au.posMax=zu;const Hu=Au.push("link_open","a",1),Vu=[["href",Ou]];Hu.attrs=Vu,Mu&&Vu.push(["title",Mu]),Au.linkLevel++,Au.md.inline.tokenize(Au),Au.linkLevel--,Au.push("link_close","a",-1)}return Au.pos=Uu,Au.posMax=ju,!0}function image(Au,lo){let $u,Ru,Iu,Pu,Ou,Mu,Du,Lu,Bu="";const ju=Au.pos,Fu=Au.posMax;if(Au.src.charCodeAt(Au.pos)!==33||Au.src.charCodeAt(Au.pos+1)!==91)return!1;const zu=Au.pos+2,Uu=Au.md.helpers.parseLinkLabel(Au,Au.pos+1,!1);if(Uu<0)return!1;if(Pu=Uu+1,Pu<Fu&&Au.src.charCodeAt(Pu)===40){for(Pu++;Pu<Fu&&($u=Au.src.charCodeAt(Pu),!(!isSpace($u)&&$u!==10));Pu++);if(Pu>=Fu)return!1;for(Lu=Pu,Mu=Au.md.helpers.parseLinkDestination(Au.src,Pu,Au.posMax),Mu.ok&&(Bu=Au.md.normalizeLink(Mu.str),Au.md.validateLink(Bu)?Pu=Mu.pos:Bu=""),Lu=Pu;Pu<Fu&&($u=Au.src.charCodeAt(Pu),!(!isSpace($u)&&$u!==10));Pu++);if(Mu=Au.md.helpers.parseLinkTitle(Au.src,Pu,Au.posMax),Pu<Fu&&Lu!==Pu&&Mu.ok)for(Du=Mu.str,Pu=Mu.pos;Pu<Fu&&($u=Au.src.charCodeAt(Pu),!(!isSpace($u)&&$u!==10));Pu++);else Du="";if(Pu>=Fu||Au.src.charCodeAt(Pu)!==41)return Au.pos=ju,!1;Pu++}else{if(typeof Au.env.references>"u")return!1;if(Pu<Fu&&Au.src.charCodeAt(Pu)===91?(Lu=Pu+1,Pu=Au.md.helpers.parseLinkLabel(Au,Pu),Pu>=0?Iu=Au.src.slice(Lu,Pu++):Pu=Uu+1):Pu=Uu+1,Iu||(Iu=Au.src.slice(zu,Uu)),Ou=Au.env.references[normalizeReference(Iu)],!Ou)return Au.pos=ju,!1;Bu=Ou.href,Du=Ou.title}if(!lo){Ru=Au.src.slice(zu,Uu);const Hu=[];Au.md.inline.parse(Ru,Au.md,Au.env,Hu);const Vu=Au.push("image","img",0),Gu=[["src",Bu],["alt",""]];Vu.attrs=Gu,Vu.children=Hu,Vu.content=Ru,Du&&Gu.push(["title",Du])}return Au.pos=Pu,Au.posMax=Fu,!0}const EMAIL_RE=/^([a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)$/,AUTOLINK_RE=/^([a-zA-Z][a-zA-Z0-9+.-]{1,31}):([^<>\x00-\x20]*)$/;function autolink(Au,lo){let $u=Au.pos;if(Au.src.charCodeAt($u)!==60)return!1;const Ru=Au.pos,Iu=Au.posMax;for(;;){if(++$u>=Iu)return!1;const Ou=Au.src.charCodeAt($u);if(Ou===60)return!1;if(Ou===62)break}const Pu=Au.src.slice(Ru+1,$u);if(AUTOLINK_RE.test(Pu)){const Ou=Au.md.normalizeLink(Pu);if(!Au.md.validateLink(Ou))return!1;if(!lo){const Mu=Au.push("link_open","a",1);Mu.attrs=[["href",Ou]],Mu.markup="autolink",Mu.info="auto";const Du=Au.push("text","",0);Du.content=Au.md.normalizeLinkText(Pu);const Lu=Au.push("link_close","a",-1);Lu.markup="autolink",Lu.info="auto"}return Au.pos+=Pu.length+2,!0}if(EMAIL_RE.test(Pu)){const Ou=Au.md.normalizeLink("mailto:"+Pu);if(!Au.md.validateLink(Ou))return!1;if(!lo){const Mu=Au.push("link_open","a",1);Mu.attrs=[["href",Ou]],Mu.markup="autolink",Mu.info="auto";const Du=Au.push("text","",0);Du.content=Au.md.normalizeLinkText(Pu);const Lu=Au.push("link_close","a",-1);Lu.markup="autolink",Lu.info="auto"}return Au.pos+=Pu.length+2,!0}return!1}function isLinkOpen(Au){return/^<a[>\s]/i.test(Au)}function isLinkClose(Au){return/^<\/a\s*>/i.test(Au)}function isLetter(Au){const lo=Au|32;return lo>=97&&lo<=122}function html_inline(Au,lo){if(!Au.md.options.html)return!1;const $u=Au.posMax,Ru=Au.pos;if(Au.src.charCodeAt(Ru)!==60||Ru+2>=$u)return!1;const Iu=Au.src.charCodeAt(Ru+1);if(Iu!==33&&Iu!==63&&Iu!==47&&!isLetter(Iu))return!1;const Pu=Au.src.slice(Ru).match(HTML_TAG_RE);if(!Pu)return!1;if(!lo){const Ou=Au.push("html_inline","",0);Ou.content=Pu[0],isLinkOpen(Ou.content)&&Au.linkLevel++,isLinkClose(Ou.content)&&Au.linkLevel--}return Au.pos+=Pu[0].length,!0}const DIGITAL_RE=/^&#((?:x[a-f0-9]{1,6}|[0-9]{1,7}));/i,NAMED_RE=/^&([a-z][a-z0-9]{1,31});/i;function entity(Au,lo){const $u=Au.pos,Ru=Au.posMax;if(Au.src.charCodeAt($u)!==38||$u+1>=Ru)return!1;if(Au.src.charCodeAt($u+1)===35){const Pu=Au.src.slice($u).match(DIGITAL_RE);if(Pu){if(!lo){const Ou=Pu[1][0].toLowerCase()==="x"?parseInt(Pu[1].slice(1),16):parseInt(Pu[1],10),Mu=Au.push("text_special","",0);Mu.content=isValidEntityCode(Ou)?fromCodePoint(Ou):fromCodePoint(65533),Mu.markup=Pu[0],Mu.info="entity"}return Au.pos+=Pu[0].length,!0}}else{const Pu=Au.src.slice($u).match(NAMED_RE);if(Pu){const Ou=decodeHTMLStrict(Pu[0]);if(Ou!==Pu[0]){if(!lo){const Mu=Au.push("text_special","",0);Mu.content=Ou,Mu.markup=Pu[0],Mu.info="entity"}return Au.pos+=Pu[0].length,!0}}}return!1}function processDelimiters(Au){const lo={},$u=Au.length;if(!$u)return;let Ru=0,Iu=-2;const Pu=[];for(let Ou=0;Ou<$u;Ou++){const Mu=Au[Ou];if(Pu.push(0),(Au[Ru].marker!==Mu.marker||Iu!==Mu.token-1)&&(Ru=Ou),Iu=Mu.token,Mu.length=Mu.length||0,!Mu.close)continue;lo.hasOwnProperty(Mu.marker)||(lo[Mu.marker]=[-1,-1,-1,-1,-1,-1]);const Du=lo[Mu.marker][(Mu.open?3:0)+Mu.length%3];let Lu=Ru-Pu[Ru]-1,Bu=Lu;for(;Lu>Du;Lu-=Pu[Lu]+1){const ju=Au[Lu];if(ju.marker===Mu.marker&&ju.open&&ju.end<0){let Fu=!1;if((ju.close||Mu.open)&&(ju.length+Mu.length)%3===0&&(ju.length%3!==0||Mu.length%3!==0)&&(Fu=!0),!Fu){const zu=Lu>0&&!Au[Lu-1].open?Pu[Lu-1]+1:0;Pu[Ou]=Ou-Lu+zu,Pu[Lu]=zu,Mu.open=!1,ju.end=Ou,ju.close=!1,Bu=-1,Iu=-2;break}}}Bu!==-1&&(lo[Mu.marker][(Mu.open?3:0)+(Mu.length||0)%3]=Bu)}}function link_pairs(Au){const lo=Au.tokens_meta,$u=Au.tokens_meta.length;processDelimiters(Au.delimiters);for(let Ru=0;Ru<$u;Ru++)lo[Ru]&&lo[Ru].delimiters&&processDelimiters(lo[Ru].delimiters)}function fragments_join(Au){let lo,$u,Ru=0;const Iu=Au.tokens,Pu=Au.tokens.length;for(lo=$u=0;lo<Pu;lo++)Iu[lo].nesting<0&&Ru--,Iu[lo].level=Ru,Iu[lo].nesting>0&&Ru++,Iu[lo].type==="text"&&lo+1<Pu&&Iu[lo+1].type==="text"?Iu[lo+1].content=Iu[lo].content+Iu[lo+1].content:(lo!==$u&&(Iu[$u]=Iu[lo]),$u++);lo!==$u&&(Iu.length=$u)}const _rules=[["text",text$2],["linkify",linkify],["newline",newline],["escape",escape$1],["backticks",backtick],["strikethrough",r_strikethrough.tokenize],["emphasis",r_emphasis.tokenize],["link",link],["image",image],["autolink",autolink],["html_inline",html_inline],["entity",entity]],_rules2=[["balance_pairs",link_pairs],["strikethrough",r_strikethrough.postProcess],["emphasis",r_emphasis.postProcess],["fragments_join",fragments_join]];function ParserInline(){this.ruler=new Ruler;for(let Au=0;Au<_rules.length;Au++)this.ruler.push(_rules[Au][0],_rules[Au][1]);this.ruler2=new Ruler;for(let Au=0;Au<_rules2.length;Au++)this.ruler2.push(_rules2[Au][0],_rules2[Au][1])}ParserInline.prototype.skipToken=function(Au){const lo=Au.pos,$u=this.ruler.getRules(""),Ru=$u.length,Iu=Au.md.options.maxNesting,Pu=Au.cache;if(typeof Pu[lo]<"u"){Au.pos=Pu[lo];return}let Ou=!1;if(Au.level<Iu){for(let Mu=0;Mu<Ru;Mu++)if(Au.level++,Ou=$u[Mu](Au,!0),Au.level--,Ou){if(lo>=Au.pos)throw new Error("inline rule didn't increment state.pos");break}}else Au.pos=Au.posMax;Ou||Au.pos++,Pu[lo]=Au.pos};ParserInline.prototype.tokenize=function(Au){const lo=this.ruler.getRules(""),$u=lo.length,Ru=Au.posMax,Iu=Au.md.options.maxNesting;for(;Au.pos<Ru;){const Pu=Au.pos;let Ou=!1;if(Au.level<Iu){for(let Mu=0;Mu<$u;Mu++)if(Ou=lo[Mu](Au,!1),Ou){if(Pu>=Au.pos)throw new Error("inline rule didn't increment state.pos");break}}if(Ou){if(Au.pos>=Ru)break;continue}Au.pending+=Au.src[Au.pos++]}Au.pending&&Au.pushPending()};ParserInline.prototype.parse=function(Au,lo,$u,Ru){const Iu=new this.State(Au,lo,$u,Ru);this.tokenize(Iu);const Pu=this.ruler2.getRules(""),Ou=Pu.length;for(let Mu=0;Mu<Ou;Mu++)Pu[Mu](Iu)};ParserInline.prototype.State=StateInline;function reFactory(Au){const lo={};Au=Au||{},lo.src_Any=Any.source,lo.src_Cc=Cc.source,lo.src_Z=Z.source,lo.src_P=P.source,lo.src_ZPCc=[lo.src_Z,lo.src_P,lo.src_Cc].join("|"),lo.src_ZCc=[lo.src_Z,lo.src_Cc].join("|");const $u="[><|]";return lo.src_pseudo_letter=`(?:(?!${$u}|${lo.src_ZPCc})${lo.src_Any})`,lo.src_ip4="(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)",lo.src_auth=`(?:(?:(?!${lo.src_ZCc}|[@/\\[\\]()]).){1,50}@)?`,lo.src_port="(?::(?:6(?:[0-4]\\d{3}|5(?:[0-4]\\d{2}|5(?:[0-2]\\d|3[0-5])))|[1-5]?\\d{1,4}))?",lo.src_host_terminator=`(?=$|${$u}|${lo.src_ZPCc})(?!${Au["---"]?"-(?!--)|":"-|"}_|:\\d|\\.-|\\.(?!$|${lo.src_ZPCc}))`,lo.src_path=`(?:[/?#](?:(?!${lo.src_ZCc}|${$u}|[()[\\]{}.,"'?!\\-;]).|\\[(?:(?!${lo.src_ZCc}|\\]).)*\\]|\\((?:(?!${lo.src_ZCc}|[)]).)*\\)|\\{(?:(?!${lo.src_ZCc}|[}]).)*\\}|\\"(?:(?!${lo.src_ZCc}|["]).)+\\"|\\'(?:(?!${lo.src_ZCc}|[']).)+\\'|\\'(?=${lo.src_pseudo_letter}|[-])|\\.{2,}[a-zA-Z0-9%/&]|\\.(?!${lo.src_ZCc}|[.]|$)|`+(Au["---"]?"\\-(?!--(?:[^-]|$))(?:-*)|":"\\-+|")+`,(?!${lo.src_ZCc}|$)|;(?!${lo.src_ZCc}|$)|\\!+(?!${lo.src_ZCc}|[!]|$)|\\?(?!${lo.src_ZCc}|[?]|$))+|\\/)?`,lo.src_email_name='[\\-;:&=\\+\\$,\\.a-zA-Z0-9_][\\-;:&=\\+\\$,\\"\\.a-zA-Z0-9_]{0,63}',lo.src_xn="xn--[a-z0-9\\-]{1,59}",lo.src_domain_root="(?:"+lo.src_xn+`|${lo.src_pseudo_letter}{1,63})`,lo.src_domain="(?:"+lo.src_xn+`|(?:${lo.src_pseudo_letter})|(?:${lo.src_pseudo_letter}(?:-|${lo.src_pseudo_letter}){0,61}${lo.src_pseudo_letter}))`,lo.src_host=`(?:(?:(?:(?:${lo.src_domain})\\.)*${lo.src_domain}))`,lo.tpl_host_fuzzy="(?:"+lo.src_ip4+`|(?:(?:(?:${lo.src_domain})\\.)+(?:%TLDS%)))`,lo.tpl_host_no_ip_fuzzy=`(?:(?:(?:${lo.src_domain})\\.)+(?:%TLDS%))`,lo.src_host_strict=lo.src_host+lo.src_host_terminator,lo.tpl_host_fuzzy_strict=lo.tpl_host_fuzzy+lo.src_host_terminator,lo.src_host_port_strict=lo.src_host+lo.src_port+lo.src_host_terminator,lo.tpl_host_port_fuzzy_strict=lo.tpl_host_fuzzy+lo.src_port+lo.src_host_terminator,lo.tpl_host_port_no_ip_fuzzy_strict=lo.tpl_host_no_ip_fuzzy+lo.src_port+lo.src_host_terminator,lo.tpl_host_fuzzy_test=`localhost|www\\.|\\.\\d{1,3}\\.|(?:\\.(?:%TLDS%)(?:${lo.src_ZPCc}|>|$))`,lo.tpl_email_fuzzy=`(^|${$u}|"|\\(|${lo.src_ZCc})(${lo.src_email_name}@${lo.tpl_host_fuzzy_strict})`,lo.tpl_link_fuzzy=`(^|(?![.:/\\-_@])(?:[$+<=>^\`||]|${lo.src_ZPCc}))((?![$+<=>^\`||])${lo.tpl_host_port_fuzzy_strict}${lo.src_path})`,lo.tpl_link_no_ip_fuzzy=`(^|(?![.:/\\-_@])(?:[$+<=>^\`||]|${lo.src_ZPCc}))((?![$+<=>^\`||])${lo.tpl_host_port_no_ip_fuzzy_strict}${lo.src_path})`,lo}function assign(Au){return Array.prototype.slice.call(arguments,1).forEach(function($u){$u&&Object.keys($u).forEach(function(Ru){Au[Ru]=$u[Ru]})}),Au}function _class(Au){return Object.prototype.toString.call(Au)}function isString(Au){return _class(Au)==="[object String]"}function isObject(Au){return _class(Au)==="[object Object]"}function isRegExp(Au){return _class(Au)==="[object RegExp]"}function isFunction(Au){return _class(Au)==="[object Function]"}function escapeRE(Au){return Au.replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}const defaultOptions={fuzzyLink:!0,fuzzyEmail:!0,fuzzyIP:!1};function isOptionsObj(Au){return Object.keys(Au||{}).reduce(function(lo,$u){return lo||defaultOptions.hasOwnProperty($u)},!1)}const defaultSchemas={"http:":{validate:function(Au,lo,$u){const Ru=Au.slice(lo);return $u.re.http||($u.re.http=new RegExp(`^\\/\\/${$u.re.src_auth}${$u.re.src_host_port_strict}${$u.re.src_path}`,"i")),$u.re.http.test(Ru)?Ru.match($u.re.http)[0].length:0}},"https:":"http:","ftp:":"http:","//":{validate:function(Au,lo,$u){const Ru=Au.slice(lo);return $u.re.no_http||($u.re.no_http=new RegExp("^"+$u.re.src_auth+`(?:localhost|(?:(?:${$u.re.src_domain})\\.)+${$u.re.src_domain_root})`+$u.re.src_port+$u.re.src_host_terminator+$u.re.src_path,"i")),$u.re.no_http.test(Ru)?lo>=3&&Au[lo-3]===":"||lo>=3&&Au[lo-3]==="/"?0:Ru.match($u.re.no_http)[0].length:0}},"mailto:":{validate:function(Au,lo,$u){const Ru=Au.slice(lo);return $u.re.mailto||($u.re.mailto=new RegExp(`^${$u.re.src_email_name}@${$u.re.src_host_strict}`,"i")),$u.re.mailto.test(Ru)?Ru.match($u.re.mailto)[0].length:0}}},tlds_2ch_src_re="a[cdefgilmnoqrstuwxz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvwxyz]|d[ejkmoz]|e[cegrstu]|f[ijkmor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdeghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eosuw]|s[abcdeghijklmnortuvxyz]|t[cdfghjklmnortvwz]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]",tlds_default="biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф".split("|");function createValidator(Au){return function(lo,$u){const Ru=lo.slice($u);return Au.test(Ru)?Ru.match(Au)[0].length:0}}function createNormalizer(){return function(Au,lo){lo.normalize(Au)}}function compile(Au){const lo=Au.re=reFactory(Au.__opts__),$u=Au.__tlds__.slice();Au.onCompile(),Au.__tlds_replaced__||$u.push(tlds_2ch_src_re),$u.push(lo.src_xn),lo.src_tlds=$u.join("|");function Ru(Mu){return Mu.replace("%TLDS%",lo.src_tlds)}lo.email_fuzzy=RegExp(Ru(lo.tpl_email_fuzzy),"i"),lo.email_fuzzy_global=RegExp(Ru(lo.tpl_email_fuzzy),"ig"),lo.link_fuzzy=RegExp(Ru(lo.tpl_link_fuzzy),"i"),lo.link_fuzzy_global=RegExp(Ru(lo.tpl_link_fuzzy),"ig"),lo.link_no_ip_fuzzy=RegExp(Ru(lo.tpl_link_no_ip_fuzzy),"i"),lo.link_no_ip_fuzzy_global=RegExp(Ru(lo.tpl_link_no_ip_fuzzy),"ig"),lo.host_fuzzy_test=RegExp(Ru(lo.tpl_host_fuzzy_test),"i");const Iu=[];Au.__compiled__={};function Pu(Mu,Du){throw new Error(`(LinkifyIt) Invalid schema "${Mu}": ${Du}`)}Object.keys(Au.__schemas__).forEach(function(Mu){const Du=Au.__schemas__[Mu];if(Du===null)return;const Lu={validate:null,link:null};if(Au.__compiled__[Mu]=Lu,isObject(Du)){isRegExp(Du.validate)?Lu.validate=createValidator(Du.validate):isFunction(Du.validate)?Lu.validate=Du.validate:Pu(Mu,Du),isFunction(Du.normalize)?Lu.normalize=Du.normalize:Du.normalize?Pu(Mu,Du):Lu.normalize=createNormalizer();return}if(isString(Du)){Iu.push(Mu);return}Pu(Mu,Du)}),Iu.forEach(function(Mu){Au.__compiled__[Au.__schemas__[Mu]]&&(Au.__compiled__[Mu].validate=Au.__compiled__[Au.__schemas__[Mu]].validate,Au.__compiled__[Mu].normalize=Au.__compiled__[Au.__schemas__[Mu]].normalize)}),Au.__compiled__[""]={validate:null,normalize:createNormalizer()};const Ou=Object.keys(Au.__compiled__).filter(function(Mu){return Mu.length>0&&Au.__compiled__[Mu]}).map(escapeRE).join("|");Au.re.schema_test=RegExp(`(^|(?!_)(?:[><|]|${lo.src_ZPCc}))(${Ou})`,"i"),Au.re.schema_search=RegExp(`(^|(?!_)(?:[><|]|${lo.src_ZPCc}))(${Ou})`,"ig"),Au.re.schema_at_start=RegExp(`^${Au.re.schema_search.source}`,"i"),Au.re.pretest=RegExp(`(${Au.re.schema_test.source})|(${Au.re.host_fuzzy_test.source})|@`,"i")}function Match(Au,lo,$u,Ru){const Iu=Au.slice($u,Ru);this.schema=lo.toLowerCase(),this.index=$u,this.lastIndex=Ru,this.raw=Iu,this.text=Iu,this.url=Iu}function LinkifyIt(Au,lo){if(!(this instanceof LinkifyIt))return new LinkifyIt(Au,lo);lo||isOptionsObj(Au)&&(lo=Au,Au={}),this.__opts__=assign({},defaultOptions,lo),this.__schemas__=assign({},defaultSchemas,Au),this.__compiled__={},this.__tlds__=tlds_default,this.__tlds_replaced__=!1,this.re={},compile(this)}LinkifyIt.prototype.add=function Au(lo,$u){return this.__schemas__[lo]=$u,compile(this),this};LinkifyIt.prototype.set=function Au(lo){return this.__opts__=assign(this.__opts__,lo),this};LinkifyIt.prototype.test=function Au(lo){if(!lo.length)return!1;let $u,Ru;if(this.re.schema_test.test(lo)){for(Ru=this.re.schema_search,Ru.lastIndex=0;($u=Ru.exec(lo))!==null;)if(this.testSchemaAt(lo,$u[2],Ru.lastIndex))return!0}return!!(this.__opts__.fuzzyLink&&this.__compiled__["http:"]&&lo.search(this.re.host_fuzzy_test)>=0&&lo.match(this.__opts__.fuzzyIP?this.re.link_fuzzy:this.re.link_no_ip_fuzzy)!==null||this.__opts__.fuzzyEmail&&this.__compiled__["mailto:"]&&lo.indexOf("@")>=0&&lo.match(this.re.email_fuzzy)!==null)};LinkifyIt.prototype.pretest=function Au(lo){return this.re.pretest.test(lo)};LinkifyIt.prototype.testSchemaAt=function Au(lo,$u,Ru){return this.__compiled__[$u.toLowerCase()]?this.__compiled__[$u.toLowerCase()].validate(lo,Ru,this):0};LinkifyIt.prototype.match=function Au(lo){const $u=[],Ru=[],Iu=[],Pu=[];let Ou,Mu,Du;function Lu(Fu,zu){return Fu?zu?Fu.index!==zu.index?Fu.index<zu.index?Fu:zu:Fu.lastIndex>=zu.lastIndex?Fu:zu:Fu:zu}if(!lo.length)return null;if(this.re.schema_test.test(lo))for(Du=this.re.schema_search,Du.lastIndex=0;(Ou=Du.exec(lo))!==null;)Mu=this.testSchemaAt(lo,Ou[2],Du.lastIndex),Mu&&Ru.push({schema:Ou[2],index:Ou.index+Ou[1].length,lastIndex:Ou.index+Ou[0].length+Mu});if(this.__opts__.fuzzyLink&&this.__compiled__["http:"])for(Du=this.__opts__.fuzzyIP?this.re.link_fuzzy_global:this.re.link_no_ip_fuzzy_global,Du.lastIndex=0;(Ou=Du.exec(lo))!==null;)Iu.push({schema:"",index:Ou.index+Ou[1].length,lastIndex:Ou.index+Ou[0].length});if(this.__opts__.fuzzyEmail&&this.__compiled__["mailto:"])for(Du=this.re.email_fuzzy_global,Du.lastIndex=0;(Ou=Du.exec(lo))!==null;)Pu.push({schema:"mailto:",index:Ou.index+Ou[1].length,lastIndex:Ou.index+Ou[0].length});const Bu=[0,0,0];let ju=0;for(;;){const Fu=[Ru[Bu[0]],Pu[Bu[1]],Iu[Bu[2]]],zu=Lu(Lu(Fu[0],Fu[1]),Fu[2]);if(!zu)break;if(zu===Fu[0]?Bu[0]++:zu===Fu[1]?Bu[1]++:Bu[2]++,zu.index<ju)continue;const Uu=new Match(lo,zu.schema,zu.index,zu.lastIndex);this.__compiled__[Uu.schema].normalize(Uu,this),$u.push(Uu),ju=zu.lastIndex}return $u.length?$u:null};LinkifyIt.prototype.matchAtStart=function Au(lo){if(!lo.length)return null;const $u=this.re.schema_at_start.exec(lo);if(!$u)return null;const Ru=this.testSchemaAt(lo,$u[2],$u[0].length);if(!Ru)return null;const Iu=new Match(lo,$u[2],$u.index+$u[1].length,$u.index+$u[0].length+Ru);return this.__compiled__[Iu.schema].normalize(Iu,this),Iu};LinkifyIt.prototype.tlds=function Au(lo,$u){return lo=Array.isArray(lo)?lo:[lo],$u?(this.__tlds__=this.__tlds__.concat(lo).sort().filter(function(Ru,Iu,Pu){return Ru!==Pu[Iu-1]}).reverse(),compile(this),this):(this.__tlds__=lo.slice(),this.__tlds_replaced__=!0,compile(this),this)};LinkifyIt.prototype.normalize=function Au(lo){lo.schema||(lo.url=`http://${lo.url}`),lo.schema==="mailto:"&&!/^mailto:/i.test(lo.url)&&(lo.url=`mailto:${lo.url}`)};LinkifyIt.prototype.onCompile=function Au(){};const maxInt=2147483647,base$1=36,tMin=1,tMax=26,skew=38,damp=700,initialBias=72,initialN=128,delimiter="-",regexPunycode=/^xn--/,regexNonASCII=/[^\0-\x7F]/,regexSeparators=/[\x2E\u3002\uFF0E\uFF61]/g,errors={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},baseMinusTMin=base$1-tMin,floor=Math.floor,stringFromCharCode=String.fromCharCode;function error(Au){throw new RangeError(errors[Au])}function map(Au,lo){const $u=[];let Ru=Au.length;for(;Ru--;)$u[Ru]=lo(Au[Ru]);return $u}function mapDomain(Au,lo){const $u=Au.split("@");let Ru="";$u.length>1&&(Ru=$u[0]+"@",Au=$u[1]),Au=Au.replace(regexSeparators,".");const Iu=Au.split("."),Pu=map(Iu,lo).join(".");return Ru+Pu}function ucs2decode(Au){const lo=[];let $u=0;const Ru=Au.length;for(;$u<Ru;){const Iu=Au.charCodeAt($u++);if(Iu>=55296&&Iu<=56319&&$u<Ru){const Pu=Au.charCodeAt($u++);(Pu&64512)==56320?lo.push(((Iu&1023)<<10)+(Pu&1023)+65536):(lo.push(Iu),$u--)}else lo.push(Iu)}return lo}const ucs2encode=Au=>String.fromCodePoint(...Au),basicToDigit=function(Au){return Au>=48&&Au<58?26+(Au-48):Au>=65&&Au<91?Au-65:Au>=97&&Au<123?Au-97:base$1},digitToBasic=function(Au,lo){return Au+22+75*(Au<26)-((lo!=0)<<5)},adapt=function(Au,lo,$u){let Ru=0;for(Au=$u?floor(Au/damp):Au>>1,Au+=floor(Au/lo);Au>baseMinusTMin*tMax>>1;Ru+=base$1)Au=floor(Au/baseMinusTMin);return floor(Ru+(baseMinusTMin+1)*Au/(Au+skew))},decode=function(Au){const lo=[],$u=Au.length;let Ru=0,Iu=initialN,Pu=initialBias,Ou=Au.lastIndexOf(delimiter);Ou<0&&(Ou=0);for(let Mu=0;Mu<Ou;++Mu)Au.charCodeAt(Mu)>=128&&error("not-basic"),lo.push(Au.charCodeAt(Mu));for(let Mu=Ou>0?Ou+1:0;Mu<$u;){const Du=Ru;for(let Bu=1,ju=base$1;;ju+=base$1){Mu>=$u&&error("invalid-input");const Fu=basicToDigit(Au.charCodeAt(Mu++));Fu>=base$1&&error("invalid-input"),Fu>floor((maxInt-Ru)/Bu)&&error("overflow"),Ru+=Fu*Bu;const zu=ju<=Pu?tMin:ju>=Pu+tMax?tMax:ju-Pu;if(Fu<zu)break;const Uu=base$1-zu;Bu>floor(maxInt/Uu)&&error("overflow"),Bu*=Uu}const Lu=lo.length+1;Pu=adapt(Ru-Du,Lu,Du==0),floor(Ru/Lu)>maxInt-Iu&&error("overflow"),Iu+=floor(Ru/Lu),Ru%=Lu,lo.splice(Ru++,0,Iu)}return String.fromCodePoint(...lo)},encode=function(Au){const lo=[];Au=ucs2decode(Au);const $u=Au.length;let Ru=initialN,Iu=0,Pu=initialBias;for(const Du of Au)Du<128&&lo.push(stringFromCharCode(Du));const Ou=lo.length;let Mu=Ou;for(Ou&&lo.push(delimiter);Mu<$u;){let Du=maxInt;for(const Bu of Au)Bu>=Ru&&Bu<Du&&(Du=Bu);const Lu=Mu+1;Du-Ru>floor((maxInt-Iu)/Lu)&&error("overflow"),Iu+=(Du-Ru)*Lu,Ru=Du;for(const Bu of Au)if(Bu<Ru&&++Iu>maxInt&&error("overflow"),Bu===Ru){let ju=Iu;for(let Fu=base$1;;Fu+=base$1){const zu=Fu<=Pu?tMin:Fu>=Pu+tMax?tMax:Fu-Pu;if(ju<zu)break;const Uu=ju-zu,Hu=base$1-zu;lo.push(stringFromCharCode(digitToBasic(zu+Uu%Hu,0))),ju=floor(Uu/Hu)}lo.push(stringFromCharCode(digitToBasic(ju,0))),Pu=adapt(Iu,Lu,Mu===Ou),Iu=0,++Mu}++Iu,++Ru}return lo.join("")},toUnicode=function(Au){return mapDomain(Au,function(lo){return regexPunycode.test(lo)?decode(lo.slice(4).toLowerCase()):lo})},toASCII=function(Au){return mapDomain(Au,function(lo){return regexNonASCII.test(lo)?"xn--"+encode(lo):lo})},punycode={version:"2.3.1",ucs2:{decode:ucs2decode,encode:ucs2encode},decode,encode,toASCII,toUnicode},cfg_default={options:{html:!1,xhtmlOut:!1,breaks:!1,langPrefix:"language-",linkify:!1,typographer:!1,quotes:"“”‘’",highlight:null,maxNesting:100},components:{core:{},block:{},inline:{}}},cfg_zero={options:{html:!1,xhtmlOut:!1,breaks:!1,langPrefix:"language-",linkify:!1,typographer:!1,quotes:"“”‘’",highlight:null,maxNesting:20},components:{core:{rules:["normalize","block","inline","text_join"]},block:{rules:["paragraph"]},inline:{rules:["text"],rules2:["balance_pairs","fragments_join"]}}},cfg_commonmark={options:{html:!0,xhtmlOut:!0,breaks:!1,langPrefix:"language-",linkify:!1,typographer:!1,quotes:"“”‘’",highlight:null,maxNesting:20},components:{core:{rules:["normalize","block","inline","text_join"]},block:{rules:["blockquote","code","fence","heading","hr","html_block","lheading","list","reference","paragraph"]},inline:{rules:["autolink","backticks","emphasis","entity","escape","html_inline","image","link","newline","text"],rules2:["balance_pairs","emphasis","fragments_join"]}}},config={default:cfg_default,zero:cfg_zero,commonmark:cfg_commonmark},BAD_PROTO_RE=/^(vbscript|javascript|file|data):/,GOOD_DATA_RE=/^data:image\/(gif|png|jpeg|webp);/;function validateLink(Au){const lo=Au.trim().toLowerCase();return BAD_PROTO_RE.test(lo)?GOOD_DATA_RE.test(lo):!0}const RECODE_HOSTNAME_FOR=["http:","https:","mailto:"];function normalizeLink(Au){const lo=urlParse(Au,!0);if(lo.hostname&&(!lo.protocol||RECODE_HOSTNAME_FOR.indexOf(lo.protocol)>=0))try{lo.hostname=punycode.toASCII(lo.hostname)}catch{}return encode$1(format$1(lo))}function normalizeLinkText(Au){const lo=urlParse(Au,!0);if(lo.hostname&&(!lo.protocol||RECODE_HOSTNAME_FOR.indexOf(lo.protocol)>=0))try{lo.hostname=punycode.toUnicode(lo.hostname)}catch{}return decode$1(format$1(lo),decode$1.defaultChars+"%")}function MarkdownIt(Au,lo){if(!(this instanceof MarkdownIt))return new MarkdownIt(Au,lo);lo||isString$1(Au)||(lo=Au||{},Au="default"),this.inline=new ParserInline,this.block=new ParserBlock,this.core=new Core,this.renderer=new Renderer,this.linkify=new LinkifyIt,this.validateLink=validateLink,this.normalizeLink=normalizeLink,this.normalizeLinkText=normalizeLinkText,this.utils=utils,this.helpers=assign$1({},helpers),this.options={},this.configure(Au),lo&&this.set(lo)}MarkdownIt.prototype.set=function(Au){return assign$1(this.options,Au),this};MarkdownIt.prototype.configure=function(Au){const lo=this;if(isString$1(Au)){const $u=Au;if(Au=config[$u],!Au)throw new Error('Wrong `markdown-it` preset "'+$u+'", check name')}if(!Au)throw new Error("Wrong `markdown-it` preset, can't be empty");return Au.options&&lo.set(Au.options),Au.components&&Object.keys(Au.components).forEach(function($u){Au.components[$u].rules&&lo[$u].ruler.enableOnly(Au.components[$u].rules),Au.components[$u].rules2&&lo[$u].ruler2.enableOnly(Au.components[$u].rules2)}),this};MarkdownIt.prototype.enable=function(Au,lo){let $u=[];Array.isArray(Au)||(Au=[Au]),["core","block","inline"].forEach(function(Iu){$u=$u.concat(this[Iu].ruler.enable(Au,!0))},this),$u=$u.concat(this.inline.ruler2.enable(Au,!0));const Ru=Au.filter(function(Iu){return $u.indexOf(Iu)<0});if(Ru.length&&!lo)throw new Error("MarkdownIt. Failed to enable unknown rule(s): "+Ru);return this};MarkdownIt.prototype.disable=function(Au,lo){let $u=[];Array.isArray(Au)||(Au=[Au]),["core","block","inline"].forEach(function(Iu){$u=$u.concat(this[Iu].ruler.disable(Au,!0))},this),$u=$u.concat(this.inline.ruler2.disable(Au,!0));const Ru=Au.filter(function(Iu){return $u.indexOf(Iu)<0});if(Ru.length&&!lo)throw new Error("MarkdownIt. Failed to disable unknown rule(s): "+Ru);return this};MarkdownIt.prototype.use=function(Au){const lo=[this].concat(Array.prototype.slice.call(arguments,1));return Au.apply(Au,lo),this};MarkdownIt.prototype.parse=function(Au,lo){if(typeof Au!="string")throw new Error("Input data should be a String");const $u=new this.core.State(Au,this,lo);return this.core.process($u),$u.tokens};MarkdownIt.prototype.render=function(Au,lo){return lo=lo||{},this.renderer.render(this.parse(Au,lo),this.options,lo)};MarkdownIt.prototype.parseInline=function(Au,lo){const $u=new this.core.State(Au,this,lo);return $u.inlineMode=!0,this.core.process($u),$u.tokens};MarkdownIt.prototype.renderInline=function(Au,lo){return lo=lo||{},this.renderer.render(this.parseInline(Au,lo),this.options,lo)};class MarkdownItRenderer{constructor(){this.markdownIt=MarkdownIt(),this.registerTagClassMapRules()}registerTagClassMapRules(){const lo=["paragraph_open","heading_open","bullet_list_open","ordered_list_open","list_item_open","link_open","strong_open","em_open"];for(const $u of lo){const Ru=this.markdownIt.renderer.rules[$u];this.markdownIt.renderer.rules[$u]=(Iu,Pu,Ou,Mu,Du)=>{const Lu=Iu[Pu],Bu=Mu?.tagClassMap;if(Bu){const ju=Bu[Lu.tag]??[];for(const Fu of ju)Lu.attrJoin("class",Fu)}return Ru?Ru(Iu,Pu,Ou,Mu,Du):Du.renderToken(Iu,Pu,Ou)}}}render(lo,$u){return this.markdownIt.render(lo,{tagClassMap:$u})}}const rawMarkdownRenderer=new MarkdownItRenderer;function _arrayLikeToArray(Au,lo){(lo==null||lo>Au.length)&&(lo=Au.length);for(var $u=0,Ru=Array(lo);$u<lo;$u++)Ru[$u]=Au[$u];return Ru}function _arrayWithHoles(Au){if(Array.isArray(Au))return Au}function _iterableToArrayLimit(Au,lo){var $u=Au==null?null:typeof Symbol<"u"&&Au[Symbol.iterator]||Au["@@iterator"];if($u!=null){var Ru,Iu,Pu,Ou,Mu=[],Du=!0,Lu=!1;try{if(Pu=($u=$u.call(Au)).next,lo!==0)for(;!(Du=(Ru=Pu.call($u)).done)&&(Mu.push(Ru.value),Mu.length!==lo);Du=!0);}catch(Bu){Lu=!0,Iu=Bu}finally{try{if(!Du&&$u.return!=null&&(Ou=$u.return(),Object(Ou)!==Ou))return}finally{if(Lu)throw Iu}}return Mu}}function _nonIterableRest(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
3782
3782
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function _slicedToArray(Au,lo){return _arrayWithHoles(Au)||_iterableToArrayLimit(Au,lo)||_unsupportedIterableToArray(Au,lo)||_nonIterableRest()}function _unsupportedIterableToArray(Au,lo){if(Au){if(typeof Au=="string")return _arrayLikeToArray(Au,lo);var $u={}.toString.call(Au).slice(8,-1);return $u==="Object"&&Au.constructor&&($u=Au.constructor.name),$u==="Map"||$u==="Set"?Array.from(Au):$u==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test($u)?_arrayLikeToArray(Au,lo):void 0}}const entries=Object.entries,setPrototypeOf=Object.setPrototypeOf,isFrozen=Object.isFrozen,getPrototypeOf=Object.getPrototypeOf,getOwnPropertyDescriptor=Object.getOwnPropertyDescriptor;let freeze=Object.freeze,seal=Object.seal,create=Object.create,_ref=typeof Reflect<"u"&&Reflect,apply=_ref.apply,construct=_ref.construct;freeze||(freeze=function(lo){return lo});seal||(seal=function(lo){return lo});apply||(apply=function(lo,$u){for(var Ru=arguments.length,Iu=new Array(Ru>2?Ru-2:0),Pu=2;Pu<Ru;Pu++)Iu[Pu-2]=arguments[Pu];return lo.apply($u,Iu)});construct||(construct=function(lo){for(var $u=arguments.length,Ru=new Array($u>1?$u-1:0),Iu=1;Iu<$u;Iu++)Ru[Iu-1]=arguments[Iu];return new lo(...Ru)});const arrayForEach=unapply(Array.prototype.forEach),arrayLastIndexOf=unapply(Array.prototype.lastIndexOf),arrayPop=unapply(Array.prototype.pop),arrayPush=unapply(Array.prototype.push),arraySplice=unapply(Array.prototype.splice),arrayIsArray=Array.isArray,stringToLowerCase=unapply(String.prototype.toLowerCase),stringToString=unapply(String.prototype.toString),stringMatch=unapply(String.prototype.match),stringReplace=unapply(String.prototype.replace),stringIndexOf=unapply(String.prototype.indexOf),stringTrim=unapply(String.prototype.trim),numberToString=unapply(Number.prototype.toString),booleanToString=unapply(Boolean.prototype.toString),bigintToString=typeof BigInt>"u"?null:unapply(BigInt.prototype.toString),symbolToString=typeof Symbol>"u"?null:unapply(Symbol.prototype.toString),objectHasOwnProperty=unapply(Object.prototype.hasOwnProperty),objectToString=unapply(Object.prototype.toString),regExpTest=unapply(RegExp.prototype.test),typeErrorCreate=unconstruct(TypeError);function unapply(Au){return function(lo){lo instanceof RegExp&&(lo.lastIndex=0);for(var $u=arguments.length,Ru=new Array($u>1?$u-1:0),Iu=1;Iu<$u;Iu++)Ru[Iu-1]=arguments[Iu];return apply(Au,lo,Ru)}}function unconstruct(Au){return function(){for(var lo=arguments.length,$u=new Array(lo),Ru=0;Ru<lo;Ru++)$u[Ru]=arguments[Ru];return construct(Au,$u)}}function addToSet(Au,lo){let $u=arguments.length>2&&arguments[2]!==void 0?arguments[2]:stringToLowerCase;if(setPrototypeOf&&setPrototypeOf(Au,null),!arrayIsArray(lo))return Au;let Ru=lo.length;for(;Ru--;){let Iu=lo[Ru];if(typeof Iu=="string"){const Pu=$u(Iu);Pu!==Iu&&(isFrozen(lo)||(lo[Ru]=Pu),Iu=Pu)}Au[Iu]=!0}return Au}function cleanArray(Au){for(let lo=0;lo<Au.length;lo++)objectHasOwnProperty(Au,lo)||(Au[lo]=null);return Au}function clone(Au){const lo=create(null);for(const Ru of entries(Au)){var $u=_slicedToArray(Ru,2);const Iu=$u[0],Pu=$u[1];objectHasOwnProperty(Au,Iu)&&(arrayIsArray(Pu)?lo[Iu]=cleanArray(Pu):Pu&&typeof Pu=="object"&&Pu.constructor===Object?lo[Iu]=clone(Pu):lo[Iu]=Pu)}return lo}function stringifyValue(Au){switch(typeof Au){case"string":return Au;case"number":return numberToString(Au);case"boolean":return booleanToString(Au);case"bigint":return bigintToString?bigintToString(Au):"0";case"symbol":return symbolToString?symbolToString(Au):"Symbol()";case"undefined":return objectToString(Au);case"function":case"object":{if(Au===null)return objectToString(Au);const lo=Au,$u=lookupGetter(lo,"toString");if(typeof $u=="function"){const Ru=$u(lo);return typeof Ru=="string"?Ru:objectToString(Ru)}return objectToString(Au)}default:return objectToString(Au)}}function lookupGetter(Au,lo){for(;Au!==null;){const Ru=getOwnPropertyDescriptor(Au,lo);if(Ru){if(Ru.get)return unapply(Ru.get);if(typeof Ru.value=="function")return unapply(Ru.value)}Au=getPrototypeOf(Au)}function $u(){return null}return $u}function isRegex(Au){try{return regExpTest(Au,""),!0}catch{return!1}}const html$1=freeze(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),svg$1=freeze(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),svgFilters=freeze(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),svgDisallowed=freeze(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),mathMl$1=freeze(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),mathMlDisallowed=freeze(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),text$1=freeze(["#text"]),html=freeze(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),svg=freeze(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),mathMl=freeze(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),xml=freeze(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),MUSTACHE_EXPR=seal(/{{[\w\W]*|^[\w\W]*}}/g),ERB_EXPR=seal(/<%[\w\W]*|^[\w\W]*%>/g),TMPLIT_EXPR=seal(/\${[\w\W]*/g),DATA_ATTR=seal(/^data-[\-\w.\u00B7-\uFFFF]+$/),ARIA_ATTR=seal(/^aria-[\-\w]+$/),IS_ALLOWED_URI=seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),IS_SCRIPT_OR_DATA=seal(/^(?:\w+script|data):/i),ATTR_WHITESPACE=seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),DOCTYPE_NAME=seal(/^html$/i),CUSTOM_ELEMENT=seal(/^[a-z][.\w]*(-[.\w]+)+$/i),ELEMENT_MARKUP_PROBE=seal(/<[/\w!]/g),COMMENT_MARKUP_PROBE=seal(/<[/\w]/g),FALLBACK_TAG_CLOSE=seal(/<\/no(script|embed|frames)/i),SELF_CLOSING_TAG=seal(/\/>/i),NODE_TYPE={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},getGlobal=function Au(){return typeof window>"u"?null:window},_createTrustedTypesPolicy=function Au(lo,$u){if(typeof lo!="object"||typeof lo.createPolicy!="function")return null;let Ru=null;const Iu="data-tt-policy-suffix";$u&&$u.hasAttribute(Iu)&&(Ru=$u.getAttribute(Iu));const Pu="dompurify"+(Ru?"#"+Ru:"");try{return lo.createPolicy(Pu,{createHTML(Ou){return Ou},createScriptURL(Ou){return Ou}})}catch{return console.warn("TrustedTypes policy "+Pu+" could not be created."),null}},_createHooksMap=function Au(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},_resolveSetOption=function Au(lo,$u,Ru,Iu){return objectHasOwnProperty(lo,$u)&&arrayIsArray(lo[$u])?addToSet(Iu.base?clone(Iu.base):{},lo[$u],Iu.transform):Ru};function createDOMPurify(){let Au=arguments.length>0&&arguments[0]!==void 0?arguments[0]:getGlobal();const lo=Lh=>createDOMPurify(Lh);if(lo.version="3.4.11",lo.removed=[],!Au||!Au.document||Au.document.nodeType!==NODE_TYPE.document||!Au.Element)return lo.isSupported=!1,lo;let $u=Au.document;const Ru=$u,Iu=Ru.currentScript;Au.DocumentFragment;const Pu=Au.HTMLTemplateElement,Ou=Au.Node,Mu=Au.Element,Du=Au.NodeFilter,Lu=Au.NamedNodeMap;Lu===void 0&&(Au.NamedNodeMap||Au.MozNamedAttrMap),Au.HTMLFormElement;const Bu=Au.DOMParser,ju=Au.trustedTypes,Fu=Mu.prototype,zu=lookupGetter(Fu,"cloneNode"),Uu=lookupGetter(Fu,"remove"),Hu=lookupGetter(Fu,"nextSibling"),Vu=lookupGetter(Fu,"childNodes"),Gu=lookupGetter(Fu,"parentNode"),Wu=lookupGetter(Fu,"shadowRoot"),Ku=lookupGetter(Fu,"attributes"),Ju=Ou&&Ou.prototype?lookupGetter(Ou.prototype,"nodeType"):null,Yu=Ou&&Ou.prototype?lookupGetter(Ou.prototype,"nodeName"):null;if(typeof Pu=="function"){const Lh=$u.createElement("template");Lh.content&&Lh.content.ownerDocument&&($u=Lh.content.ownerDocument)}let Xu,ed="",td,nd=!1,od=0;const sd=function(){if(od>0)throw typeErrorCreate('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},ad=function(Ud){sd(),od++;try{return Xu.createHTML(Ud)}finally{od--}},pd=function(Ud){sd(),od++;try{return Xu.createScriptURL(Ud)}finally{od--}},gd=function(){return nd||(td=_createTrustedTypesPolicy(ju,Iu),nd=!0),td},xd=$u,yd=xd.implementation,vd=xd.createNodeIterator,wd=xd.createDocumentFragment,Td=xd.getElementsByTagName,cd=Ru.importNode;let dd=_createHooksMap();lo.isSupported=typeof entries=="function"&&typeof Gu=="function"&&yd&&yd.createHTMLDocument!==void 0;const md=MUSTACHE_EXPR,ld=ERB_EXPR,hd=TMPLIT_EXPR,bd=DATA_ATTR,Sd=ARIA_ATTR,kd=IS_SCRIPT_OR_DATA,Rd=ATTR_WHITESPACE,Od=CUSTOM_ELEMENT;let Bd=IS_ALLOWED_URI,Ed=null;const Ad=addToSet({},[...html$1,...svg$1,...svgFilters,...mathMl$1,...text$1]);let $d=null;const qd=addToSet({},[...html,...svg,...mathMl,...xml]);let Dd=Object.seal(create(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Hd=null,nh=null;const Xd=Object.seal(create(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let vh=!0,ih=!0,xh=!1,bh=!0,eh=!1,rh=!0,ah=!1,Dh=!1,Gd=null,zd=null,Id=!1,Pd=!1,Wd=!1,Nd=!1,Kd=!0,Qd=!1;const fh="user-content-";let _h=!0,Sh=!1,Wh={},Md=null;const _d=addToSet({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]);let Vd=null;const Fd=addToSet({},["audio","video","img","source","image","track"]);let uh=null;const wh=addToSet({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Eh="http://www.w3.org/1998/Math/MathML",kh="http://www.w3.org/2000/svg",Ph="http://www.w3.org/1999/xhtml";let Fh=Ph,Uh=!1,Jh=null;const Oh=addToSet({},[Eh,kh,Ph],stringToString),np=freeze(["mi","mo","mn","ms","mtext"]);let ap=addToSet({},np);const hp=freeze(["annotation-xml"]);let bp=addToSet({},hp);const Qh=addToSet({},["title","style","font","a","script"]);let _p=null;const lp=["application/xhtml+xml","text/html"],up="text/html";let Hh=null,zh=null;const Xh=$u.createElement("form"),Uf=function(Ud){return Ud instanceof RegExp||Ud instanceof Function},$p=function(){let Ud=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(zh&&zh===Ud)return;(!Ud||typeof Ud!="object")&&(Ud={}),Ud=clone(Ud),_p=lp.indexOf(Ud.PARSER_MEDIA_TYPE)===-1?up:Ud.PARSER_MEDIA_TYPE,Hh=_p==="application/xhtml+xml"?stringToString:stringToLowerCase,Ed=_resolveSetOption(Ud,"ALLOWED_TAGS",Ad,{transform:Hh}),$d=_resolveSetOption(Ud,"ALLOWED_ATTR",qd,{transform:Hh}),Jh=_resolveSetOption(Ud,"ALLOWED_NAMESPACES",Oh,{transform:stringToString}),uh=_resolveSetOption(Ud,"ADD_URI_SAFE_ATTR",wh,{transform:Hh,base:wh}),Vd=_resolveSetOption(Ud,"ADD_DATA_URI_TAGS",Fd,{transform:Hh,base:Fd}),Md=_resolveSetOption(Ud,"FORBID_CONTENTS",_d,{transform:Hh}),Hd=_resolveSetOption(Ud,"FORBID_TAGS",clone({}),{transform:Hh}),nh=_resolveSetOption(Ud,"FORBID_ATTR",clone({}),{transform:Hh}),Wh=objectHasOwnProperty(Ud,"USE_PROFILES")?Ud.USE_PROFILES&&typeof Ud.USE_PROFILES=="object"?clone(Ud.USE_PROFILES):Ud.USE_PROFILES:!1,vh=Ud.ALLOW_ARIA_ATTR!==!1,ih=Ud.ALLOW_DATA_ATTR!==!1,xh=Ud.ALLOW_UNKNOWN_PROTOCOLS||!1,bh=Ud.ALLOW_SELF_CLOSE_IN_ATTR!==!1,eh=Ud.SAFE_FOR_TEMPLATES||!1,rh=Ud.SAFE_FOR_XML!==!1,ah=Ud.WHOLE_DOCUMENT||!1,Pd=Ud.RETURN_DOM||!1,Wd=Ud.RETURN_DOM_FRAGMENT||!1,Nd=Ud.RETURN_TRUSTED_TYPE||!1,Id=Ud.FORCE_BODY||!1,Kd=Ud.SANITIZE_DOM!==!1,Qd=Ud.SANITIZE_NAMED_PROPS||!1,_h=Ud.KEEP_CONTENT!==!1,Sh=Ud.IN_PLACE||!1,Bd=isRegex(Ud.ALLOWED_URI_REGEXP)?Ud.ALLOWED_URI_REGEXP:IS_ALLOWED_URI,Fh=typeof Ud.NAMESPACE=="string"?Ud.NAMESPACE:Ph,ap=objectHasOwnProperty(Ud,"MATHML_TEXT_INTEGRATION_POINTS")&&Ud.MATHML_TEXT_INTEGRATION_POINTS&&typeof Ud.MATHML_TEXT_INTEGRATION_POINTS=="object"?clone(Ud.MATHML_TEXT_INTEGRATION_POINTS):addToSet({},np),bp=objectHasOwnProperty(Ud,"HTML_INTEGRATION_POINTS")&&Ud.HTML_INTEGRATION_POINTS&&typeof Ud.HTML_INTEGRATION_POINTS=="object"?clone(Ud.HTML_INTEGRATION_POINTS):addToSet({},hp);const lh=objectHasOwnProperty(Ud,"CUSTOM_ELEMENT_HANDLING")&&Ud.CUSTOM_ELEMENT_HANDLING&&typeof Ud.CUSTOM_ELEMENT_HANDLING=="object"?clone(Ud.CUSTOM_ELEMENT_HANDLING):create(null);if(Dd=create(null),objectHasOwnProperty(lh,"tagNameCheck")&&Uf(lh.tagNameCheck)&&(Dd.tagNameCheck=lh.tagNameCheck),objectHasOwnProperty(lh,"attributeNameCheck")&&Uf(lh.attributeNameCheck)&&(Dd.attributeNameCheck=lh.attributeNameCheck),objectHasOwnProperty(lh,"allowCustomizedBuiltInElements")&&typeof lh.allowCustomizedBuiltInElements=="boolean"&&(Dd.allowCustomizedBuiltInElements=lh.allowCustomizedBuiltInElements),seal(Dd),eh&&(ih=!1),Wd&&(Pd=!0),Wh&&(Ed=addToSet({},text$1),$d=create(null),Wh.html===!0&&(addToSet(Ed,html$1),addToSet($d,html)),Wh.svg===!0&&(addToSet(Ed,svg$1),addToSet($d,svg),addToSet($d,xml)),Wh.svgFilters===!0&&(addToSet(Ed,svgFilters),addToSet($d,svg),addToSet($d,xml)),Wh.mathMl===!0&&(addToSet(Ed,mathMl$1),addToSet($d,mathMl),addToSet($d,xml))),Xd.tagCheck=null,Xd.attributeCheck=null,objectHasOwnProperty(Ud,"ADD_TAGS")&&(typeof Ud.ADD_TAGS=="function"?Xd.tagCheck=Ud.ADD_TAGS:arrayIsArray(Ud.ADD_TAGS)&&(Ed===Ad&&(Ed=clone(Ed)),addToSet(Ed,Ud.ADD_TAGS,Hh))),objectHasOwnProperty(Ud,"ADD_ATTR")&&(typeof Ud.ADD_ATTR=="function"?Xd.attributeCheck=Ud.ADD_ATTR:arrayIsArray(Ud.ADD_ATTR)&&($d===qd&&($d=clone($d)),addToSet($d,Ud.ADD_ATTR,Hh))),objectHasOwnProperty(Ud,"ADD_URI_SAFE_ATTR")&&arrayIsArray(Ud.ADD_URI_SAFE_ATTR)&&addToSet(uh,Ud.ADD_URI_SAFE_ATTR,Hh),objectHasOwnProperty(Ud,"FORBID_CONTENTS")&&arrayIsArray(Ud.FORBID_CONTENTS)&&(Md===_d&&(Md=clone(Md)),addToSet(Md,Ud.FORBID_CONTENTS,Hh)),objectHasOwnProperty(Ud,"ADD_FORBID_CONTENTS")&&arrayIsArray(Ud.ADD_FORBID_CONTENTS)&&(Md===_d&&(Md=clone(Md)),addToSet(Md,Ud.ADD_FORBID_CONTENTS,Hh)),_h&&(Ed["#text"]=!0),ah&&addToSet(Ed,["html","head","body"]),Ed.table&&(addToSet(Ed,["tbody"]),delete Hd.tbody),Ud.TRUSTED_TYPES_POLICY){if(typeof Ud.TRUSTED_TYPES_POLICY.createHTML!="function")throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof Ud.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const Mh=Xu;Xu=Ud.TRUSTED_TYPES_POLICY;try{ed=ad("")}catch(Nh){throw Xu=Mh,Nh}}else Ud.TRUSTED_TYPES_POLICY===null?(Xu=void 0,ed=""):(Xu===void 0&&(Xu=gd()),Xu&&typeof ed=="string"&&(ed=ad("")));freeze&&freeze(Ud),zh=Ud},Rh=addToSet({},[...svg$1,...svgFilters,...svgDisallowed]),jh=addToSet({},[...mathMl$1,...mathMlDisallowed]),af=function(Ud,lh,Mh){return lh.namespaceURI===Ph?Ud==="svg":lh.namespaceURI===Eh?Ud==="svg"&&(Mh==="annotation-xml"||ap[Mh]):!!Rh[Ud]},qp=function(Ud,lh,Mh){return lh.namespaceURI===Ph?Ud==="math":lh.namespaceURI===kh?Ud==="math"&&bp[Mh]:!!jh[Ud]},lf=function(Ud,lh,Mh){return lh.namespaceURI===kh&&!bp[Mh]||lh.namespaceURI===Eh&&!ap[Mh]?!1:!jh[Ud]&&(Qh[Ud]||!Rh[Ud])},Xp=function(Ud){let lh=Gu(Ud);(!lh||!lh.tagName)&&(lh={namespaceURI:Fh,tagName:"template"});const Mh=stringToLowerCase(Ud.tagName),Nh=stringToLowerCase(lh.tagName);return Jh[Ud.namespaceURI]?Ud.namespaceURI===kh?af(Mh,lh,Nh):Ud.namespaceURI===Eh?qp(Mh,lh,Nh):Ud.namespaceURI===Ph?lf(Mh,lh,Nh):!!(_p==="application/xhtml+xml"&&Jh[Ud.namespaceURI]):!1},tp=function(Ud){arrayPush(lo.removed,{element:Ud});try{Gu(Ud).removeChild(Ud)}catch{if(Uu(Ud),!Gu(Ud))throw typeErrorCreate("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},Vp=function(Ud){const lh=Vu(Ud);if(lh){const Nh=[];arrayForEach(lh,mp=>{arrayPush(Nh,mp)}),arrayForEach(Nh,mp=>{try{Uu(mp)}catch{}})}const Mh=Ku(Ud);if(Mh)for(let Nh=Mh.length-1;Nh>=0;--Nh){const mp=Mh[Nh],$h=mp&&mp.name;if(typeof $h=="string")try{Ud.removeAttribute($h)}catch{}}},$f=function(Ud,lh){try{arrayPush(lo.removed,{attribute:lh.getAttributeNode(Ud),from:lh})}catch{arrayPush(lo.removed,{attribute:null,from:lh})}if(lh.removeAttribute(Ud),Ud==="is")if(Pd||Wd)try{tp(lh)}catch{}else try{lh.setAttribute(Ud,"")}catch{}},cm=function(Ud){const lh=Ku(Ud);if(lh)for(let Mh=lh.length-1;Mh>=0;--Mh){const Nh=lh[Mh],mp=Nh&&Nh.name;if(!(typeof mp!="string"||$d[Hh(mp)]))try{Ud.removeAttribute(mp)}catch{}}},Hf=function(Ud){const lh=[Ud];for(;lh.length>0;){const Mh=lh.pop();(Ju?Ju(Mh):Mh.nodeType)===NODE_TYPE.element&&cm(Mh);const mp=Vu(Mh);if(mp)for(let $h=mp.length-1;$h>=0;--$h)lh.push(mp[$h])}},qf=function(Ud){let lh=null,Mh=null;if(Id)Ud="<remove></remove>"+Ud;else{const $h=stringMatch(Ud,/^[\r\n\t ]+/);Mh=$h&&$h[0]}_p==="application/xhtml+xml"&&Fh===Ph&&(Ud='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+Ud+"</body></html>");const Nh=Xu?ad(Ud):Ud;if(Fh===Ph)try{lh=new Bu().parseFromString(Nh,_p)}catch{}if(!lh||!lh.documentElement){lh=yd.createDocument(Fh,"template",null);try{lh.documentElement.innerHTML=Uh?ed:Nh}catch{}}const mp=lh.body||lh.documentElement;return Ud&&Mh&&mp.insertBefore($u.createTextNode(Mh),mp.childNodes[0]||null),Fh===Ph?Td.call(lh,ah?"html":"body")[0]:ah?lh.documentElement:mp},Qp=function(Ud){return vd.call(Ud.ownerDocument||Ud,Ud,Du.SHOW_ELEMENT|Du.SHOW_COMMENT|Du.SHOW_TEXT|Du.SHOW_PROCESSING_INSTRUCTION|Du.SHOW_CDATA_SECTION,null)},fp=function(Ud){return Ud=stringReplace(Ud,md," "),Ud=stringReplace(Ud,ld," "),Ud=stringReplace(Ud,hd," "),Ud},jp=function(Ud){var lh;Ud.normalize();const Mh=vd.call(Ud.ownerDocument||Ud,Ud,Du.SHOW_TEXT|Du.SHOW_COMMENT|Du.SHOW_CDATA_SECTION|Du.SHOW_PROCESSING_INSTRUCTION,null);let Nh=Mh.nextNode();for(;Nh;)Nh.data=fp(Nh.data),Nh=Mh.nextNode();const mp=(lh=Ud.querySelectorAll)===null||lh===void 0?void 0:lh.call(Ud,"template");mp&&arrayForEach(mp,$h=>{Bp($h.content)&&jp($h.content)})},Sp=function(Ud){const lh=Yu?Yu(Ud):null;return typeof lh!="string"||Hh(lh)!=="form"?!1:typeof Ud.nodeName!="string"||typeof Ud.textContent!="string"||typeof Ud.removeChild!="function"||Ud.attributes!==Ku(Ud)||typeof Ud.removeAttribute!="function"||typeof Ud.setAttribute!="function"||typeof Ud.namespaceURI!="string"||typeof Ud.insertBefore!="function"||typeof Ud.hasChildNodes!="function"||Ud.nodeType!==Ju(Ud)||Ud.childNodes!==Vu(Ud)},Bp=function(Ud){if(!Ju||typeof Ud!="object"||Ud===null)return!1;try{return Ju(Ud)===NODE_TYPE.documentFragment}catch{return!1}},Of=function(Ud){if(!Ju||typeof Ud!="object"||Ud===null)return!1;try{return typeof Ju(Ud)=="number"}catch{return!1}};function ef(Lh,Ud,lh){Lh.length!==0&&arrayForEach(Lh,Mh=>{Mh.call(lo,Ud,lh,zh)})}const cf=function(Ud,lh){return!!(rh&&Ud.hasChildNodes()&&!Of(Ud.firstElementChild)&&regExpTest(ELEMENT_MARKUP_PROBE,Ud.textContent)&&regExpTest(ELEMENT_MARKUP_PROBE,Ud.innerHTML)||rh&&Ud.namespaceURI===Ph&&lh==="style"&&Of(Ud.firstElementChild)||Ud.nodeType===NODE_TYPE.processingInstruction||rh&&Ud.nodeType===NODE_TYPE.comment&&regExpTest(COMMENT_MARKUP_PROBE,Ud.data))},yp=function(Ud,lh){if(!Hd[lh]&&Mf(lh)&&(Dd.tagNameCheck instanceof RegExp&&regExpTest(Dd.tagNameCheck,lh)||Dd.tagNameCheck instanceof Function&&Dd.tagNameCheck(lh)))return!1;if(_h&&!Md[lh]){const Mh=Gu(Ud),Nh=Vu(Ud);if(Nh&&Mh){const mp=Nh.length;for(let $h=mp-1;$h>=0;--$h){const ep=Sh?Nh[$h]:zu(Nh[$h],!0);Mh.insertBefore(ep,Hu(Ud))}}}return tp(Ud),!0},Jf=function(Ud){if(ef(dd.beforeSanitizeElements,Ud,null),Sp(Ud))return tp(Ud),!0;const lh=Hh(Yu?Yu(Ud):Ud.nodeName);if(ef(dd.uponSanitizeElement,Ud,{tagName:lh,allowedTags:Ed}),cf(Ud,lh))return tp(Ud),!0;if(Hd[lh]||!(Xd.tagCheck instanceof Function&&Xd.tagCheck(lh))&&!Ed[lh])return yp(Ud,lh);if((Ju?Ju(Ud):Ud.nodeType)===NODE_TYPE.element&&!Xp(Ud)||(lh==="noscript"||lh==="noembed"||lh==="noframes")&&regExpTest(FALLBACK_TAG_CLOSE,Ud.innerHTML))return tp(Ud),!0;if(eh&&Ud.nodeType===NODE_TYPE.text){const Nh=fp(Ud.textContent);Ud.textContent!==Nh&&(arrayPush(lo.removed,{element:Ud.cloneNode()}),Ud.textContent=Nh)}return ef(dd.afterSanitizeElements,Ud,null),!1},vf=function(Ud,lh,Mh){if(nh[lh]||Kd&&(lh==="id"||lh==="name")&&(Mh in $u||Mh in Xh))return!1;const Nh=$d[lh]||Xd.attributeCheck instanceof Function&&Xd.attributeCheck(lh,Ud);if(!(ih&&regExpTest(bd,lh))){if(!(vh&&regExpTest(Sd,lh))){if(Nh){if(!uh[lh]){if(!regExpTest(Bd,stringReplace(Mh,Rd,""))){if(!((lh==="src"||lh==="xlink:href"||lh==="href")&&Ud!=="script"&&stringIndexOf(Mh,"data:")===0&&Vd[Ud])){if(!(xh&&!regExpTest(kd,stringReplace(Mh,Rd,"")))){if(Mh)return!1}}}}}else if(!(Mf(Ud)&&(Dd.tagNameCheck instanceof RegExp&&regExpTest(Dd.tagNameCheck,Ud)||Dd.tagNameCheck instanceof Function&&Dd.tagNameCheck(Ud))&&(Dd.attributeNameCheck instanceof RegExp&&regExpTest(Dd.attributeNameCheck,lh)||Dd.attributeNameCheck instanceof Function&&Dd.attributeNameCheck(lh,Ud))||lh==="is"&&Dd.allowCustomizedBuiltInElements&&(Dd.tagNameCheck instanceof RegExp&&regExpTest(Dd.tagNameCheck,Mh)||Dd.tagNameCheck instanceof Function&&Dd.tagNameCheck(Mh))))return!1}}return!0},vm=addToSet({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Mf=function(Ud){return!vm[stringToLowerCase(Ud)]&&regExpTest(Od,Ud)},Fm=function(Ud,lh,Mh,Nh){if(Xu&&typeof ju=="object"&&typeof ju.getAttributeType=="function"&&!Mh)switch(ju.getAttributeType(Ud,lh)){case"TrustedHTML":return ad(Nh);case"TrustedScriptURL":return pd(Nh)}return Nh},uf=function(Ud,lh,Mh,Nh){try{Mh?Ud.setAttributeNS(Mh,lh,Nh):Ud.setAttribute(lh,Nh),Sp(Ud)?tp(Ud):arrayPop(lo.removed)}catch{$f(lh,Ud)}},Am=function(Ud){ef(dd.beforeSanitizeAttributes,Ud,null);const lh=Ud.attributes;if(!lh||Sp(Ud))return;const Mh={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:$d,forceKeepAttr:void 0};let Nh=lh.length;const mp=Hh(Ud.nodeName);for(;Nh--;){const $h=lh[Nh],ep=$h.name,Fp=$h.namespaceURI,Sf=$h.value,Ip=Hh(ep),zp=Sf;let Yp=ep==="value"?zp:stringTrim(zp);if(Mh.attrName=Ip,Mh.attrValue=Yp,Mh.keepAttr=!0,Mh.forceKeepAttr=void 0,ef(dd.uponSanitizeAttribute,Ud,Mh),Yp=Mh.attrValue,Qd&&(Ip==="id"||Ip==="name")&&stringIndexOf(Yp,fh)!==0&&($f(ep,Ud),Yp=fh+Yp),rh&&regExpTest(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Yp)){$f(ep,Ud);continue}if(Ip==="attributename"&&stringMatch(Yp,"href")){$f(ep,Ud);continue}if(!Mh.forceKeepAttr){if(!Mh.keepAttr){$f(ep,Ud);continue}if(!bh&&regExpTest(SELF_CLOSING_TAG,Yp)){$f(ep,Ud);continue}if(eh&&(Yp=fp(Yp)),!vf(mp,Ip,Yp)){$f(ep,Ud);continue}Yp=Fm(mp,Ip,Fp,Yp),Yp!==zp&&uf(Ud,ep,Fp,Yp)}}ef(dd.afterSanitizeAttributes,Ud,null)},Cm=function(Ud){let lh=null;const Mh=Qp(Ud);for(ef(dd.beforeSanitizeShadowDOM,Ud,null);lh=Mh.nextNode();)if(ef(dd.uponSanitizeShadowNode,lh,null),Jf(lh),Am(lh),Bp(lh.content)&&Cm(lh.content),(Ju?Ju(lh):lh.nodeType)===NODE_TYPE.element){const mp=Wu(lh);Bp(mp)&&(Vf(mp),Cm(mp))}ef(dd.afterSanitizeShadowDOM,Ud,null)},Vf=function(Ud){const lh=[{node:Ud,shadow:null}];for(;lh.length>0;){const Mh=lh.pop();if(Mh.shadow){Cm(Mh.shadow);continue}const Nh=Mh.node,$h=(Ju?Ju(Nh):Nh.nodeType)===NODE_TYPE.element,ep=Vu(Nh);if(ep)for(let Fp=ep.length-1;Fp>=0;--Fp)lh.push({node:ep[Fp],shadow:null});if($h){const Fp=Yu?Yu(Nh):null;if(typeof Fp=="string"&&Hh(Fp)==="template"){const Sf=Nh.content;Bp(Sf)&&lh.push({node:Sf,shadow:null})}}if($h){const Fp=Wu(Nh);Bp(Fp)&&lh.push({node:null,shadow:Fp},{node:Fp,shadow:null})}}};return lo.sanitize=function(Lh){let Ud=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},lh=null,Mh=null,Nh=null,mp=null;if(Uh=!Lh,Uh&&(Lh="<!-->"),typeof Lh!="string"&&!Of(Lh)&&(Lh=stringifyValue(Lh),typeof Lh!="string"))throw typeErrorCreate("dirty is not a string, aborting");if(!lo.isSupported)return Lh;Dh?(Ed=Gd,$d=zd):$p(Ud),(dd.uponSanitizeElement.length>0||dd.uponSanitizeAttribute.length>0)&&(Ed=clone(Ed)),dd.uponSanitizeAttribute.length>0&&($d=clone($d)),lo.removed=[];const $h=Sh&&typeof Lh!="string"&&Of(Lh);if($h){const Sf=Yu?Yu(Lh):Lh.nodeName;if(typeof Sf=="string"){const Ip=Hh(Sf);if(!Ed[Ip]||Hd[Ip])throw typeErrorCreate("root node is forbidden and cannot be sanitized in-place")}if(Sp(Lh))throw typeErrorCreate("root node is clobbered and cannot be sanitized in-place");try{Vf(Lh)}catch(Ip){throw Vp(Lh),Ip}}else if(Of(Lh))lh=qf("<!---->"),Mh=lh.ownerDocument.importNode(Lh,!0),Mh.nodeType===NODE_TYPE.element&&Mh.nodeName==="BODY"||Mh.nodeName==="HTML"?lh=Mh:lh.appendChild(Mh),Vf(Mh);else{if(!Pd&&!eh&&!ah&&Lh.indexOf("<")===-1)return Xu&&Nd?ad(Lh):Lh;if(lh=qf(Lh),!lh)return Pd?null:Nd?ed:""}lh&&Id&&tp(lh.firstChild);const ep=Qp($h?Lh:lh);try{for(;Nh=ep.nextNode();)Jf(Nh),Am(Nh),Bp(Nh.content)&&Cm(Nh.content)}catch(Sf){throw $h&&Vp(Lh),Sf}if($h)return arrayForEach(lo.removed,Sf=>{Sf.element&&Hf(Sf.element)}),eh&&jp(Lh),Lh;if(Pd){if(eh&&jp(lh),Wd)for(mp=wd.call(lh.ownerDocument);lh.firstChild;)mp.appendChild(lh.firstChild);else mp=lh;return($d.shadowroot||$d.shadowrootmode)&&(mp=cd.call(Ru,mp,!0)),mp}let Fp=ah?lh.outerHTML:lh.innerHTML;return ah&&Ed["!doctype"]&&lh.ownerDocument&&lh.ownerDocument.doctype&&lh.ownerDocument.doctype.name&&regExpTest(DOCTYPE_NAME,lh.ownerDocument.doctype.name)&&(Fp="<!DOCTYPE "+lh.ownerDocument.doctype.name+`>
3783
- `+Fp),eh&&(Fp=fp(Fp)),Xu&&Nd?ad(Fp):Fp},lo.setConfig=function(){let Lh=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};$p(Lh),Dh=!0,Gd=Ed,zd=$d},lo.clearConfig=function(){zh=null,Dh=!1,Gd=null,zd=null,Xu=td,ed=""},lo.isValidAttribute=function(Lh,Ud,lh){zh||$p({});const Mh=Hh(Lh),Nh=Hh(Ud);return vf(Mh,Nh,lh)},lo.addHook=function(Lh,Ud){typeof Ud=="function"&&objectHasOwnProperty(dd,Lh)&&arrayPush(dd[Lh],Ud)},lo.removeHook=function(Lh,Ud){if(objectHasOwnProperty(dd,Lh)){if(Ud!==void 0){const lh=arrayLastIndexOf(dd[Lh],Ud);return lh===-1?void 0:arraySplice(dd[Lh],lh,1)[0]}return arrayPop(dd[Lh])}},lo.removeHooks=function(Lh){objectHasOwnProperty(dd,Lh)&&(dd[Lh]=[])},lo.removeAllHooks=function(){dd=_createHooksMap()},lo}var purify$1=createDOMPurify();let purify;function sanitize(Au){if(!purify)if(typeof purify$1.sanitize=="function")purify=purify$1;else{const lo=globalThis.window;if(lo)purify=purify$1(lo);else throw new Error("DOMPurify requires a window object. If testing, provide a jsdom window as `globalThis`.")}return purify.sanitize(Au)}async function renderMarkdown(Au,lo){const $u=rawMarkdownRenderer.render(Au,lo?.tagClassMap);return sanitize($u)}const A2uiMarkdownProvider=({children:Au})=>jsxRuntimeExports.jsx(MarkdownContext.Provider,{value:renderMarkdown,children:Au});function applyA2uiClassFallbacks(Au){Au.querySelectorAll("button").forEach(lo=>{lo.classList.remove("undefined");const $u=lo;if($u.classList.contains("a2ui-tab-button")){$u.style.removeProperty("background"),$u.style.removeProperty("border"),$u.style.removeProperty("color"),$u.style.removeProperty("border-radius");return}if($u.classList.contains("chip")){$u.style.removeProperty("background"),$u.style.removeProperty("background-color"),$u.style.removeProperty("border"),$u.style.removeProperty("color");return}lo.classList.contains("a2ui-button")||lo.classList.add("a2ui-button"),lo.classList.contains("a2ui-button-primary")||lo.classList.add("a2ui-button-primary"),$u.style.removeProperty("background"),$u.style.removeProperty("border"),$u.style.removeProperty("color"),$u.style.removeProperty("border-radius"),$u.style.removeProperty("padding"),$u.style.removeProperty("font-weight"),$u.style.removeProperty("cursor")}),Au.querySelectorAll("input[type='text'], input[type='number'], input[type='password'], input[type='datetime-local'], textarea").forEach(lo=>{lo.classList.remove("undefined"),lo.classList.contains("a2ui-textfield-input")||lo.classList.add("a2ui-textfield-input")}),Au.querySelectorAll("label").forEach(lo=>{lo.classList.remove("undefined"),lo.classList.contains("a2ui-textfield-label")||lo.classList.add("a2ui-textfield-label")}),Au.querySelectorAll("span").forEach(lo=>{lo.textContent&&/invalid|required|error/i.test(lo.textContent)&&(lo.classList.contains("a2ui-textfield-error")||lo.classList.add("a2ui-textfield-error"))}),Au.querySelectorAll(".body, .caption").forEach(lo=>{lo.classList.remove("undefined"),lo.classList.contains("a2ui-text")||lo.classList.add("a2ui-text"),lo.classList.contains("caption")&&!lo.classList.contains("a2ui-caption")&&lo.classList.add("a2ui-caption")})}function A2uiSurfaceComposed({surface:Au}){const lo=reactExports.useRef(null);return reactExports.useEffect(()=>{const $u=lo.current;if(!$u)return;const Ru=()=>applyA2uiClassFallbacks($u);Ru();const Iu=new MutationObserver(()=>{Ru()});return Iu.observe($u,{childList:!0,subtree:!0}),()=>{Iu.disconnect()}},[Au]),jsxRuntimeExports.jsx("div",{ref:lo,children:jsxRuntimeExports.jsx(A2uiSurface,{surface:Au})})}const A2UI_INPUT_SELECTOR="& .a2ui-textfield-input",A2UI_INPUT_FOCUS_SELECTOR="& .a2ui-textfield-input:focus",A2UI_INPUT_HOVER_SELECTOR="& .a2ui-textfield-input:hover",A2UI_RENDER_SCOPE_SX={"--a2ui-icon-size":"1em","& .a2ui-card":{background:"var(--a2ui-card-background, var(--a2ui-color-surface, #f6f8fa))",border:"1px solid var(--a2ui-color-border, #d0d7de)",borderRadius:"var(--a2ui-card-border-radius, 12px)",boxShadow:"var(--a2ui-card-box-shadow, none)"},"& .a2ui-text":{color:"var(--a2ui-color-on-surface, var(--a2ui-color-on-background, #1f2328))",margin:0},"& .a2ui-caption":{color:"var(--a2ui-text-caption-color, var(--a2ui-color-on-surface, #656d76))"},"& .a2ui-button":{appearance:"none",cursor:"pointer",border:"1px solid var(--button-primary-bgColor-rest)",background:"var(--button-primary-bgColor-rest)",color:"var(--button-primary-fgColor-rest)",borderRadius:"var(--a2ui-button-border-radius, 6px)",padding:"var(--a2ui-button-padding, 5px 16px)",fontWeight:"var(--a2ui-button-font-weight, 500)",boxShadow:"var(--a2ui-button-box-shadow, none)",transition:"background-color 0.15s ease, border-color 0.15s ease"},"& .a2ui-button .a2ui-text":{color:"inherit"},"& .a2ui-button:hover":{background:"var(--button-primary-bgColor-hover)",borderColor:"var(--button-primary-bgColor-hover)"},"& .a2ui-button:disabled":{opacity:.6,cursor:"not-allowed"},"& .a2ui-tab-button":{appearance:"none",background:"transparent",border:"none",borderBottom:"2px solid transparent",borderRadius:0,marginBottom:"-1px",padding:"var(--a2ui-tab-padding, 8px 16px)",color:"var(--a2ui-tab-color, var(--a2ui-color-on-surface, #656d76))",cursor:"pointer",fontFamily:"inherit",fontSize:"var(--a2ui-font-size-sm, 14px)",fontWeight:500,boxShadow:"none",transition:"color 0.15s ease, border-color 0.15s ease, background-color 0.15s ease"},"& .a2ui-tab-button:hover":{color:"var(--a2ui-tab-color-hover, var(--a2ui-color-primary, #1f883d))",background:"var(--a2ui-tab-background-hover, var(--a2ui-color-surface, #f6f8fa))"},"& .a2ui-tab-button.active":{color:"var(--a2ui-tab-color-active, var(--a2ui-color-primary, #1f883d))",borderBottomColor:"var(--a2ui-tab-border-active, var(--a2ui-color-primary, #1f883d))",fontWeight:600},"& .chip":{appearance:"none",padding:"var(--a2ui-choicepicker-chip-padding, 4px 12px)",borderRadius:"var(--a2ui-choicepicker-chip-border-radius, 999px)",border:"1px solid var(--a2ui-color-border, #d0d7de)",background:"var(--a2ui-color-surface, #f6f8fa)",color:"var(--a2ui-color-on-surface, #1f2328)",cursor:"pointer",fontFamily:"inherit",fontSize:"var(--a2ui-font-size-sm, 14px)",fontWeight:500,boxShadow:"none",transition:"background-color 0.15s ease, border-color 0.15s ease, color 0.15s ease"},"& .chip:hover":{borderColor:"var(--a2ui-color-border-hover, var(--a2ui-color-primary, #1f883d))"},'& .chip.selected, & .chip[aria-pressed="true"]':{background:"var(--a2ui-color-primary, #1f883d)",borderColor:"var(--a2ui-color-primary, #1f883d)",color:"var(--a2ui-color-on-primary, #ffffff)"},[A2UI_INPUT_SELECTOR]:{width:"100%",minHeight:"var(--a2ui-control-height, 32px)",boxSizing:"border-box",background:"var(--a2ui-textfield-background, var(--a2ui-color-input, var(--a2ui-color-background, #ffffff)))",color:"var(--a2ui-textfield-color, var(--a2ui-color-on-input, var(--a2ui-color-on-background, #1f2328)))",border:"var(--a2ui-textfield-border, 1px solid var(--a2ui-color-border, #d0d7de))",borderRadius:"var(--a2ui-textfield-border-radius, 6px)",padding:"var(--a2ui-textfield-padding, 5px 12px)",fontSize:"var(--a2ui-font-size-sm, 14px)",lineHeight:"20px",transition:"border-color 0.15s ease, box-shadow 0.15s ease"},[A2UI_INPUT_HOVER_SELECTOR]:{borderColor:"var(--a2ui-textfield-color-border-hover, var(--a2ui-color-border-hover, #8c959f))"},[A2UI_INPUT_FOCUS_SELECTOR]:{outline:"none",borderColor:"var(--a2ui-textfield-color-border-focus, var(--a2ui-color-primary, #1f883d))",boxShadow:"0 0 0 3px color-mix(in srgb, var(--a2ui-color-primary, #1f883d) 25%, transparent)"},"& .a2ui-textfield-label":{color:"var(--a2ui-textfield-label-color, var(--a2ui-color-on-surface, var(--a2ui-color-on-background, #1f2328)))",fontWeight:600,fontSize:"var(--a2ui-font-size-xs, 12px)",marginBottom:"var(--a2ui-spacing-xxs, 4px)",display:"inline-block"},"& .a2ui-textfield-error":{color:"var(--a2ui-textfield-color-error, #d1242f)",fontSize:"var(--a2ui-font-size-xs, 12px)",marginTop:"var(--a2ui-spacing-xs, 4px)"},'& input[type="checkbox"]':{accentColor:"var(--a2ui-color-primary, #1f883d)"}},VISIBLE_WHEN="visible_when";function isShown(Au){return Array.isArray(Au)?Au.length>0:!!Au}const OWN_COMPONENT_IDS=Object.values(COMPONENT_CATALOGUE).filter(Au=>!Au.standard).map(Au=>Au.id);function ownComponent(Au){const lo=COMPONENT_CATALOGUE[Au];if(!lo)throw new Error(`The catalog has no component ${Au}.`);if(lo.standard||!lo.properties||!lo.bindings)throw new Error(`${Au} is A2UI's own: its schema is the basic catalog's, not Datalayer's.`);return lo}const BindingSchema=unionType$1([arrayType$1(anyType$1()),recordType$1(stringType$1(),unknownType$1()),stringType$1(),numberType$1(),booleanType$1(),DataBindingSchema]).describe("REF:#/$defs/DynamicValue|Datalayer: what the component shows or sends — a path the application publishes or takes, or a value given in place.");function propertySchema(Au,lo){if(lo.enum)return enumType$1(lo.enum);switch(lo.type){case"string":return stringType$1();case"integer":case"number":return numberType$1();case"boolean":return booleanType$1();case"array":return arrayType$1(anyType$1());case"object":return recordType$1(stringType$1(),unknownType$1());default:throw new Error(`${Au} is typed ${String(lo.type)}, which a component's property cannot be.`)}}function bindingNames(Au){const{shows:lo,sends:$u}=Au.bindings;return[...new Set([...lo,...$u])]}function ownComponentSchema(Au){return componentSchemaOf(ownComponent(Au))}function componentSchemaOf(Au){const lo=Au.id;if(!Au.bindings)throw new Error(`${lo} says nothing of what it shows or sends.`);const $u=Au.properties,Ru=new Set($u.required??[]),Iu={};for(const[Pu,Ou]of Object.entries($u.properties??{})){const Mu=propertySchema(Pu,Ou);Iu[Pu]=Ru.has(Pu)?Mu:Mu.optional()}for(const Pu of bindingNames(Au)){if(Pu in Iu)throw new Error(`${lo} both declares ${Pu} as a property and binds through it.`);Iu[Pu]=BindingSchema.optional()}return Iu.action=ActionSchema.describe("REF:#/$defs/Action|What it dispatches when a person acts on it.").optional(),Iu.weight=numberType$1().describe("The relative weight of this component within a Row or Column.").optional(),objectType$1(Iu).strict()}const DRAWN_OWN_COMPONENTS=["Table","Chart","FileUpload","Chat","Evidence","Form","Download"],CARD_RADIUS="var(--theme-radius-card, 6px)";function BlockFrame({title:Au,label:lo,weight:$u,children:Ru,testId:Iu}){return jsxRuntimeExports.jsxs(Box,{as:"section","aria-label":Au||lo,"data-testid":Iu,display:"flex",flexDirection:"column",gap:2,minWidth:0,boxSizing:"border-box",p:3,border:"1px solid",borderColor:"border.default",borderRadius:CARD_RADIUS,bg:"canvas.default",color:"fg.default",flex:typeof $u=="number"?`${$u}`:void 0,minHeight:typeof $u=="number"?0:void 0,children:[Au?jsxRuntimeExports.jsx(Heading$2,{as:"h3",sx:{fontSize:2,m:0},children:Au}):null,Ru]})}function Problem({children:Au}){return jsxRuntimeExports.jsx(Text$3,{as:"p",role:"status",sx:{m:0,color:"danger.fg",fontSize:1},children:Au})}function Quiet({children:Au}){return jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,color:"fg.muted",fontSize:1},children:Au})}const isRecord=Au=>typeof Au=="object"&&Au!==null&&!Array.isArray(Au);function asWords(Au){return Au==null?"":typeof Au=="object"?JSON.stringify(Au):String(Au)}function ownImplementation(Au,lo){const $u={name:Au,schema:ownComponentSchema(Au)};return createComponentImplementation($u,lo)}const PAGE_SIZE=20,sameRow=(Au,lo)=>Au!==void 0&&JSON.stringify(Au)===JSON.stringify(lo);function tableRows(Au){if(Au==null)return{rows:[]};if(!Array.isArray(Au))return{problem:"What it shows is not a list of rows."};const lo=Au.findIndex($u=>!isRecord($u));return lo>=0?{problem:`Row ${lo+1} is not a record of the columns' values.`}:{rows:Au}}function TableView({props:Au}){const{title:lo,columns:$u,selectable:Ru=!1,selected:Iu,setSelected:Pu,action:Ou}=Au,Mu=Au.page_size??PAGE_SIZE,Du=reactExports.useMemo(()=>tableRows(Au.rows),[Au.rows]),Lu="rows"in Du?Du.rows:[],Bu=Math.max(1,Math.ceil(Lu.length/Mu)),[ju,Fu]=reactExports.useState(0);reactExports.useEffect(()=>{ju>=Bu&&Fu(Bu-1)},[ju,Bu]);const zu=Lu.slice(ju*Mu,(ju+1)*Mu),[Uu,Hu]=reactExports.useState(void 0),Vu=Iu??Uu,Gu=Ku=>{Hu(Ku),Pu(Ku),Ou?.()},Wu=(Ku,Ju)=>{(Ku.key==="Enter"||Ku.key===" ")&&(Ku.preventDefault(),Gu(Ju))};return jsxRuntimeExports.jsxs(BlockFrame,{title:lo,label:"Table",weight:Au.weight,testId:"a2ui-table",children:["problem"in Du?jsxRuntimeExports.jsx(Problem,{children:Du.problem}):jsxRuntimeExports.jsxs(Box,{overflowX:"auto",children:[jsxRuntimeExports.jsxs(Box,{as:"table",role:Ru?"grid":void 0,"aria-label":lo||"Table",width:"100%",borderCollapse:"collapse",fontSize:1,sx:{"& th, & td":{textAlign:"left",px:2,py:1,borderBottom:"1px solid",borderColor:"border.muted"},"& th":{color:"fg.muted",fontWeight:"semibold"}},children:[jsxRuntimeExports.jsx("thead",{children:jsxRuntimeExports.jsx("tr",{children:$u.map(Ku=>jsxRuntimeExports.jsx("th",{scope:"col",children:Ku},Ku))})}),jsxRuntimeExports.jsx("tbody",{children:zu.map((Ku,Ju)=>{const Yu=Ru&&sameRow(Vu,Ku);return jsxRuntimeExports.jsx(Box,{as:"tr",...Ru?{tabIndex:0,"aria-selected":Yu,onClick:()=>Gu(Ku),onKeyDown:Xu=>Wu(Xu,Ku)}:null,cursor:Ru?"pointer":void 0,bg:Yu?"accent.subtle":void 0,focusVisible:{outline:"2px solid",outlineColor:"accent.fg",outlineOffset:"-2px"},hover:Ru?{bg:Yu?"accent.subtle":"canvas.subtle"}:void 0,children:$u.map(Xu=>jsxRuntimeExports.jsx("td",{children:asWords(Ku[Xu])},Xu))},ju*Mu+Ju)})})]}),Lu.length===0?jsxRuntimeExports.jsx(Quiet,{children:"No rows yet."}):null]}),Bu>1?jsxRuntimeExports.jsxs(Box,{as:"nav","aria-label":"Pages",display:"flex",alignItems:"center",gap:2,children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:ju===0,onClick:()=>Fu(ju-1),children:"Previous"}),jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:1,color:"fg.muted"},"aria-live":"polite",children:["Page ",ju+1," of ",Bu]}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:ju>=Bu-1,onClick:()=>Fu(ju+1),children:"Next"})]}):null]})}const Table=ownImplementation("Table",TableView),loadECharts=()=>__vitePreload(()=>import("./chunks/index-BTnG8qrO.js"),[],import.meta.url),chartRefused=Au=>jsxRuntimeExports.jsx(Problem,{children:`The chart could not be drawn: ${Au.message}`}),FALLBACK={series:["#0969da","#1a7f37","#9a6700","#8250df","#cf222e","#bc4c00"],text:"#1f2328",muted:"#59636e",grid:"#d1d9e0"},SERIES_VARIABLES=["--fgColor-accent","--fgColor-success","--fgColor-attention","--fgColor-done","--fgColor-danger","--fgColor-severe"];function readColours(Au){if(!Au)return FALLBACK;const lo=getComputedStyle(Au),$u=(Ru,Iu)=>lo.getPropertyValue(Ru).trim()||Iu;return{series:SERIES_VARIABLES.map((Ru,Iu)=>$u(Ru,FALLBACK.series[Iu])),text:$u("--fgColor-default",FALLBACK.text),muted:$u("--fgColor-muted",FALLBACK.muted),grid:$u("--borderColor-muted",FALLBACK.grid)}}function chartPoints(Au){return Au==null?{points:[]}:!Array.isArray(Au)||Au.some(lo=>!isRecord(lo))?{problem:"What it shows is not a list of points."}:{points:Au}}function chartSeries(Au,lo){if(!lo.series)return[{name:lo.y,points:Au}];const $u=[];for(const Ru of Au){const Iu=asWords(Ru[lo.series]);$u.includes(Iu)||$u.push(Iu)}return $u.map(Ru=>({name:Ru,points:Au.filter(Iu=>asWords(Iu[lo.series])===Ru)}))}function chartOption(Au,lo,$u){const Ru=chartSeries(Au,lo),Iu=lo.kind==="scatter",Pu=[];for(const Mu of Au){const Du=asWords(Mu[lo.x]);Pu.includes(Du)||Pu.push(Du)}const Ou={axisLine:{lineStyle:{color:$u.grid}},axisLabel:{color:$u.muted},splitLine:{lineStyle:{color:$u.grid}},nameTextStyle:{color:$u.muted}};return{aria:{enabled:!0},animation:!1,color:$u.series,textStyle:{color:$u.text},grid:{left:48,right:16,top:Ru.length>1?48:32,bottom:40},legend:Ru.length>1?{top:0,textStyle:{color:$u.text}}:void 0,tooltip:{trigger:Iu?"item":"axis"},xAxis:Iu?{type:"value",name:lo.x,nameLocation:"middle",nameGap:26,...Ou}:{type:"category",data:Pu,name:lo.x,nameLocation:"middle",nameGap:26,...Ou},yAxis:{type:"value",name:lo.y,...Ou},series:Ru.map(Mu=>({name:Mu.name,type:lo.kind==="area"?"line":lo.kind,areaStyle:lo.kind==="area"?{}:void 0,data:Iu?Mu.points.map(Du=>[Number(Du[lo.x]),Number(Du[lo.y])]):Pu.map(Du=>{const Lu=Mu.points.find(Bu=>asWords(Bu[lo.x])===Du);return Lu?Number(Lu[lo.y]):null})}))}}function ChartView({props:Au}){const{title:lo,kind:$u,x:Ru,y:Iu,series:Pu}=Au,Ou=reactExports.useMemo(()=>chartPoints(Au.points),[Au.points]),Mu=reactExports.useRef(null),[Du,Lu]=reactExports.useState(FALLBACK);reactExports.useLayoutEffect(()=>{Lu(readColours(Mu.current))},[]);const Bu="points"in Ou?Ou.points:[],ju=reactExports.useMemo(()=>chartOption(Bu,{kind:$u,x:Ru,y:Iu,series:Pu},Du),[Bu,$u,Ru,Iu,Pu,Du]),Fu=Pu?[Ru,Pu,Iu]:[Ru,Iu],zu=`${lo||"Chart"}: ${Iu} by ${Ru}, as a ${$u}`;return jsxRuntimeExports.jsx(BlockFrame,{title:lo,label:"Chart",weight:Au.weight,testId:"a2ui-chart",children:jsxRuntimeExports.jsx(Box,{ref:Mu,children:"problem"in Ou?jsxRuntimeExports.jsx(Problem,{children:Ou.problem}):Bu.length===0?jsxRuntimeExports.jsx(Quiet,{children:"No points yet."}):jsxRuntimeExports.jsxs(Box,{as:"figure","aria-label":zu,m:0,children:[jsxRuntimeExports.jsx("div",{"aria-hidden":"true",children:jsxRuntimeExports.jsx(ReactorLazy,{load:loadECharts,errorFallback:chartRefused,fallback:jsxRuntimeExports.jsx(Box,{height:240}),props:{option:ju,style:{height:240,width:"100%"},opts:{renderer:"svg"},notMerge:!0,lazyUpdate:!0}})}),jsxRuntimeExports.jsxs(Box,{as:"details",fontSize:1,children:[jsxRuntimeExports.jsx(Box,{as:"summary",cursor:"pointer",color:"fg.muted",focusVisible:{outline:"2px solid",outlineColor:"accent.fg"},children:jsxRuntimeExports.jsx(Text$3,{children:"The numbers"})}),jsxRuntimeExports.jsxs(Box,{as:"table",mt:1,borderCollapse:"collapse",sx:{"& th, & td":{textAlign:"left",pr:3,py:"2px"},"& th":{color:"fg.muted",fontWeight:"semibold"}},children:[jsxRuntimeExports.jsx("thead",{children:jsxRuntimeExports.jsx("tr",{children:Fu.map(Uu=>jsxRuntimeExports.jsx("th",{scope:"col",children:Uu},Uu))})}),jsxRuntimeExports.jsx("tbody",{children:Bu.map((Uu,Hu)=>jsxRuntimeExports.jsx("tr",{children:Fu.map(Vu=>jsxRuntimeExports.jsx("td",{children:asWords(Uu[Vu])},Vu))},Hu))})]})]})]})})})}const Chart=ownImplementation("Chart",ChartView),MAX_MB=25;function refusal(Au,lo,$u){return acceptsFile(lo,{name:Au.name,type:Au.type??""})?Au.size>$u*1024*1024?`${Au.name} is larger than ${$u} MB.`:null:`${Au.name} is not one it takes (${(lo??[]).join(", ")}).`}const readFile=Au=>new Promise((lo,$u)=>{const Ru=new FileReader;Ru.onload=()=>lo({name:Au.name,type:Au.type,size:Au.size,data_url:String(Ru.result)}),Ru.onerror=()=>$u(Ru.error),Ru.readAsDataURL(Au)});function FileUploadView({props:Au}){const{label:lo,accept:$u,multiple:Ru=!1,setFiles:Iu,action:Pu}=Au,Ou=Au.max_mb??MAX_MB,Mu=reactExports.useRef(null),Du=reactExports.useId(),[Lu,Bu]=reactExports.useState(!1),[ju,Fu]=reactExports.useState([]),zu=Array.isArray(Au.files)?Au.files.filter(isRecord).map(Gu=>String(Gu.name??"")):[],Uu=async Gu=>{const Wu=Array.from(Gu),Ku=Ru?Wu:Wu.slice(0,1),Ju=Ku.map(Yu=>refusal(Yu,$u,Ou)).filter(Yu=>Yu!==null);!Ru&&Wu.length>1&&Ju.push("It takes one file at a time."),Fu(Ju),!Ju.length&&(Iu(await Promise.all(Ku.map(readFile))),Pu?.())},Hu=Gu=>{Gu.preventDefault(),Bu(!1),Uu(Gu.dataTransfer.files)},Vu=[$u?.length?`Takes ${$u.join(", ")}`:"Takes any file",`up to ${Ou} MB`,Ru?"several at once":"one at a time"].join(", ");return jsxRuntimeExports.jsxs(BlockFrame,{label:lo,weight:Au.weight,testId:"a2ui-fileupload",children:[jsxRuntimeExports.jsxs(Box,{onDragOver:Gu=>{Gu.preventDefault(),Bu(!0)},onDragLeave:()=>Bu(!1),onDrop:Hu,"data-testid":"a2ui-fileupload-drop",display:"flex",flexDirection:"column",alignItems:"center",gap:2,p:3,border:"1px dashed",borderColor:Lu?"accent.fg":"border.default",borderRadius:CARD_RADIUS,bg:Lu?"accent.subtle":"canvas.subtle",textAlign:"center",children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold"},children:lo}),jsxRuntimeExports.jsx(ButtonComponent,{leadingVisual:UploadIcon,"aria-describedby":Du,onClick:()=>Mu.current?.click(),children:Ru?"Choose files":"Choose a file"}),jsxRuntimeExports.jsxs(Text$3,{id:Du,sx:{fontSize:0,color:"fg.muted"},children:["or drop ",Ru?"them":"it"," here. ",Vu,"."]}),jsxRuntimeExports.jsx("input",{ref:Mu,type:"file",hidden:!0,"aria-label":lo,accept:$u?.join(","),multiple:Ru,onChange:Gu=>{Gu.target.files&&Uu(Gu.target.files),Gu.target.value=""}})]}),ju.map(Gu=>jsxRuntimeExports.jsx(Problem,{children:Gu},Gu)),zu.length?jsxRuntimeExports.jsxs(Quiet,{children:["Given: ",zu.join(", ")]}):null]})}const FileUpload=ownImplementation("FileUpload",FileUploadView),PLACEHOLDER="Ask anything",AVATARS={userAvatar:jsxRuntimeExports.jsx(PersonIcon,{size:14}),assistantAvatar:jsxRuntimeExports.jsx(DependabotIcon,{size:14}),showAvatars:!0,avatarSize:24,userAvatarBg:"neutral.muted",assistantAvatarBg:"accent.emphasis"},NO_TIME=new Date(0);function chatItems(Au,lo){if(Au==null)return{items:[]};if(!Array.isArray(Au))return{problem:"What it shows is not a list of messages."};const $u=[];for(const[Ru,Iu]of Au.entries()){const Pu=`m${Ru}`;if(!isRecord(Iu))return{problem:`Message ${Ru+1} is not a message.`};if(Iu.role==="tool"){lo&&$u.push({id:Pu,type:"tool-call",toolCallId:Pu,toolName:asWords(Iu.name)||"tool",args:isRecord(Iu.args)?Iu.args:{},result:Iu.result,status:"complete"});continue}if(Iu.role!=="user"&&Iu.role!=="assistant")return{problem:`Message ${Ru+1} is from ${asWords(Iu.role)||"nobody"}: a message is the user's, the assistant's or a tool's.`};$u.push({id:Pu,role:Iu.role,content:asWords(Iu.text??Iu.content),createdAt:NO_TIME})}return{items:$u}}function ChatView({props:Au}){const{welcome:lo,starters:$u=[],setMessage:Ru,action:Iu}=Au,Pu=Au.placeholder??PLACEHOLDER,Ou=Au.show_tools??!0,Mu=reactExports.useMemo(()=>chatItems(Au.messages,Ou),[Au.messages,Ou]),[Du,Lu]=reactExports.useState(""),Bu=reactExports.useMemo(()=>reactExports.createRef(),[]),ju=reactExports.useMemo(()=>reactExports.createRef(),[]),Fu=zu=>{const Uu=zu.trim();Uu&&(Ru(Uu),Iu?.(),Lu(""))};return jsxRuntimeExports.jsxs(BlockFrame,{label:"Chat",weight:Au.weight,testId:"a2ui-chat",children:["problem"in Mu?jsxRuntimeExports.jsx(Problem,{children:Mu.problem}):jsxRuntimeExports.jsx(Box,{maxHeight:420,overflowY:"auto",borderRadius:CARD_RADIUS,children:jsxRuntimeExports.jsx(ChatMessageList,{displayItems:Mu.items,isLoading:!1,isStreaming:!1,showLoadingIndicator:!1,hideMessagesAfterToolUI:!1,avatarConfig:AVATARS,padding:2,emptyContent:jsxRuntimeExports.jsx(ChatEmptyState,{description:"",emptyState:{title:lo||"Start a conversation"},suggestions:$u.map(zu=>({title:zu,message:zu})),onSuggestionSubmit:zu=>Fu(zu.message)}),messagesEndRef:Bu,onRespond:async()=>{}})}),jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"flex-end",gap:2,children:[jsxRuntimeExports.jsx(Box,{flex:1,minWidth:0,children:jsxRuntimeExports.jsx(InputPromptText,{value:Du,onChange:Lu,placeholder:Pu,onSubmit:()=>Fu(Du),inputRef:ju})}),jsxRuntimeExports.jsx(IconButton,{icon:PaperAirplaneIcon,"aria-label":"Send",variant:"primary",disabled:!Du.trim(),onClick:()=>Fu(Du)})]})]})}const Chat=ownImplementation("Chat",ChatView),TITLE="Sources",MAX_ITEMS=5;function evidenceSources(Au){if(Au==null)return{sources:[]};if(!Array.isArray(Au))return{problem:"What it shows is not a list of sources."};const lo=[];for(const[$u,Ru]of Au.entries()){if(!isRecord(Ru)||!Ru.title&&!Ru.url)return{problem:`Source ${$u+1} has neither a title nor a link.`};lo.push({title:asWords(Ru.title)||asWords(Ru.url),url:asWords(Ru.url),passage:asWords(Ru.passage)})}return{sources:lo}}function EvidenceView({props:Au}){const{show_passages:lo=!0,action:$u}=Au,Ru=Au.title??TITLE,Iu=Au.max_items??MAX_ITEMS,Pu=reactExports.useMemo(()=>evidenceSources(Au.sources),[Au.sources]),[Ou,Mu]=reactExports.useState(!1),Du="sources"in Pu?Pu.sources:[],Lu=Ou?Du:Du.slice(0,Iu),Bu=Du.length-Lu.length;return jsxRuntimeExports.jsxs(BlockFrame,{title:Ru,label:"Evidence",weight:Au.weight,testId:"a2ui-evidence",children:["problem"in Pu?jsxRuntimeExports.jsx(Problem,{children:Pu.problem}):Du.length===0?jsxRuntimeExports.jsx(Quiet,{children:"Nothing cited yet."}):jsxRuntimeExports.jsx(Box,{as:"ol",m:0,pl:3,display:"flex",flexDirection:"column",gap:2,children:Lu.map((ju,Fu)=>jsxRuntimeExports.jsxs("li",{children:[ju.url?jsxRuntimeExports.jsxs(Link$1,{href:ju.url,target:"_blank",rel:"noreferrer noopener",onClick:()=>$u?.(),sx:{fontWeight:"semibold"},children:[ju.title," ",jsxRuntimeExports.jsx(LinkExternalIcon,{size:12,"aria-label":"opens in a new tab"})]}):jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold"},children:ju.title}),lo&&ju.passage?jsxRuntimeExports.jsx(Box,{as:"blockquote",m:0,mt:1,pl:2,borderLeft:"3px solid",borderColor:"border.default",color:"fg.muted",fontSize:1,children:ju.passage}):null]},`${ju.url}-${Fu}`))}),Bu>0?jsxRuntimeExports.jsx(Box,{children:jsxRuntimeExports.jsxs(ButtonComponent,{size:"small",variant:"invisible",onClick:()=>Mu(!0),children:[Bu," more"]})}):null]})}const Evidence=ownImplementation("Evidence",EvidenceView),loadSchemaForm=()=>__vitePreload(()=>import("./chunks/SchemaForm-CO_2yGg2.js"),[],import.meta.url),formRefused=Au=>jsxRuntimeExports.jsx(Problem,{children:`The form could not be drawn: ${Au.message}`}),SUBMIT_LABEL="Send";function FormView({props:Au}){const{title:lo,schema:$u,setValues:Ru,action:Iu}=Au,Pu=Au.submit_label??SUBMIT_LABEL,Ou=isRecord(Au.values)?Au.values:{},[Mu,Du]=reactExports.useState(Ou),[Lu,Bu]=reactExports.useState(!1),ju=JSON.stringify(Ou);reactExports.useEffect(()=>{Du(JSON.parse(ju))},[ju]);const Fu=Iu===void 0,zu=JSON.stringify(Au.ui??{}),Uu=reactExports.useMemo(()=>({...JSON.parse(zu),"ui:submitButtonOptions":Fu?{norender:!0}:{submitText:Pu}}),[zu,Fu,Pu]),Hu=$u.type!==void 0&&$u.type!=="object"?"Its fields are not an object schema: a form asks for several named values.":null;return jsxRuntimeExports.jsx(BlockFrame,{title:lo,label:"Form",weight:Au.weight,testId:"a2ui-form",children:Hu?jsxRuntimeExports.jsx(Problem,{children:Hu}):jsxRuntimeExports.jsx(ReactorLazy,{load:loadSchemaForm,errorFallback:formRefused,props:{schema:$u,uiSchema:Uu,formData:Mu,liveValidate:Lu,onBlur:()=>Bu(!0),onError:()=>Bu(!0),showErrorList:!1,onChange:Vu=>{const Gu=Vu.formData??{};Du(Gu),Fu&&Ru(Gu)},onSubmit:Vu=>{Ru(Vu.formData??{}),Iu?.()}}})})}const Form=ownImplementation("Form",FormView),SCHEMES=/^(https?:\/\/|data:)/i;function sizeInWords(Au){if(typeof Au!="number"||!Number.isFinite(Au)||Au<0)return"";if(Au<1024)return Au===1?"1 byte":`${Au} bytes`;const lo=["KB","MB","GB"];let $u=Au/1024,Ru=0;for(;$u>=1024&&Ru<lo.length-1;)$u/=1024,Ru+=1;return`${$u<10?$u.toFixed(1):Math.round($u)} ${lo[Ru]}`}function downloadOf(Au){const lo=typeof Au.name=="string"?Au.name.trim():"",$u=typeof Au.url=="string"?Au.url.trim():"";return lo?$u?SCHEMES.test($u)?{name:lo,url:$u}:{problem:`${lo} is not offered: its link is neither an http(s) link nor a data: URL.`}:{problem:`${lo} has no link.`}:{problem:"This file has no name."}}function DownloadView({props:Au}){const{action:lo}=Au,$u=reactExports.useMemo(()=>downloadOf({name:Au.name,url:Au.url}),[Au.name,Au.url]),Ru=[Au.media_type,sizeInWords(Au.size)].filter(Boolean).join(" · ");return jsxRuntimeExports.jsx(BlockFrame,{label:"File to download",weight:Au.weight,testId:"a2ui-download",children:"problem"in $u?jsxRuntimeExports.jsx(Problem,{children:$u.problem}):jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,alignItems:"flex-start",children:[jsxRuntimeExports.jsx(Box,{color:"fg.muted",pt:"2px",children:jsxRuntimeExports.jsx(DownloadIcon,{size:16,"aria-hidden":"true"})}),jsxRuntimeExports.jsxs(Box,{display:"flex",flexDirection:"column",minWidth:0,children:[jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Link$1,{href:$u.url,download:$u.name,target:"_blank",rel:"noreferrer noopener",onClick:()=>lo?.(),sx:{fontWeight:"semibold",wordBreak:"break-word"},children:$u.name}),Ru?jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontSize:1,ml:2},children:Ru}):null]}),Au.description?jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontSize:1},children:Au.description}):null]})]})})}const Download=ownImplementation("Download",DownloadView),RENDERERS={Table,Chart,FileUpload,Chat,Evidence,Form,Download},OWN_COMPONENTS=(()=>{const Au=DRAWN_OWN_COMPONENTS,lo=OWN_COMPONENT_IDS.filter(Ru=>!Au.includes(Ru));if(lo.length)throw new Error(`The catalog has ${lo.join(", ")}, which no renderer draws.`);const $u=Au.filter(Ru=>!OWN_COMPONENT_IDS.includes(Ru));if($u.length)throw new Error(`A renderer draws ${$u.join(", ")}, which the catalog does not have.`);return OWN_COMPONENT_IDS.map(Ru=>RENDERERS[Ru])})();function nodeIsShown(Au){const lo=Au[VISIBLE_WHEN];if(!(lo instanceof ResolvedBinding))throw new Error(`${VISIBLE_WHEN} resolved to ${String(lo)}, not a binding: the catalog's schema does not declare it.`);return isWritable(lo)?isShown(lo.value):lo.value===void 0||isShown(lo.value)}const VISIBLE_WHEN_SCHEMA=DynamicBooleanSchema.describe("REF:#/$defs/DynamicBoolean|Datalayer: the block is shown only while this is true or not empty — a path the application publishes.").optional();function withVisibleWhen(Au){const lo=Au.view;if(!lo)throw new Error(`${Au.name} has no node view: visible_when is read from the node, and A2uiSurface draws through it.`);const $u=Au.schema;if(!$u.shape||typeof $u.extend!="function")throw new Error(`${Au.name}'s schema is not an object: visible_when cannot be declared on it.`);if(VISIBLE_WHEN in $u.shape)throw new Error(`${Au.name} already declares ${VISIBLE_WHEN}.`);const Ru=({node:Iu,buildChild:Pu})=>{const Ou=useSignalValue(Iu.props);return nodeIsShown(Ou)?jsxRuntimeExports.jsx(lo,{node:Iu,buildChild:Pu}):null};return Ru.displayName=`${Au.name}.visibleWhen`,{...Au,schema:$u.extend({[VISIBLE_WHEN]:VISIBLE_WHEN_SCHEMA}),view:Ru}}const datalayerCatalog=new Catalog(basicCatalog.id,basicCatalog.protocolVersion,[...basicCatalog.components.values(),...OWN_COMPONENTS].map(withVisibleWhen),[...basicCatalog.functions.values()],basicCatalog.themeSchema,basicCatalog.instructions);function catalogOfBlocks(Au,lo=[]){const $u=new Map(lo.map(Pu=>[Pu.name,withVisibleWhen(Pu)])),Ru=[...$u.keys()].filter(Pu=>datalayerCatalog.components.has(Pu));if(Ru.length>0)throw new Error(`${Ru.join(", ")} ${Ru.length===1?"is a component":"are components"} of the catalog: a component of an application's own is named otherwise.`);const Iu=Au.filter(Pu=>!datalayerCatalog.components.has(Pu)&&!$u.has(Pu));if(Iu.length>0)throw new Error(`No renderer draws ${Iu.join(", ")}: a block is contributed by a plugin whose component the catalog draws.`);return new Catalog(datalayerCatalog.id,datalayerCatalog.protocolVersion,Au.map(Pu=>datalayerCatalog.components.get(Pu)??$u.get(Pu)),[...datalayerCatalog.functions.values()],datalayerCatalog.themeSchema,datalayerCatalog.instructions)}function catalogWithOwn(Au){return Au.length===0?datalayerCatalog:catalogOfBlocks([...datalayerCatalog.components.keys(),...Au.map(lo=>lo.name)],Au)}const CUSTOM_FILE=/^(?:\.\/)?(?:[A-Za-z0-9_][A-Za-z0-9_.-]*\/)*[A-Za-z0-9_][A-Za-z0-9_.-]*\.m?js$/,isFolderSource=Au=>!/^[a-z][a-z0-9+.-]*:/.test(Au)&&CUSTOM_FILE.test(Au),folderSourceUrl=(Au,lo)=>new URL(Au.replace(/^\.\//,""),lo.endsWith("/")?lo:`${lo}/`).href,hasFolderModules=Au=>(Au.interface.customComponents??[]).some(lo=>isFolderSource(lo.source));function customComponentEntry(Au,lo){return{id:Au.name,name:Au.name,description:Au.description,category:"custom",emoji:"🧩",version:lo,standard:!1,properties:Au.props,bindings:{shows:[...Au.shows],sends:[...Au.sends]},events:Au.sends.length>0?["send"]:[],...Au.example?{example:Au.example}:{}}}const CUSTOM_FRAME_SANDBOX="allow-scripts",MAX_MODULE_BYTES=2*1024*1024,FRAME_TAG="loop.component";function customFramePolicy(Au){return["default-src 'none'",`script-src 'nonce-${Au}' blob:`,"style-src 'unsafe-inline'","img-src data: blob:","font-src data:","media-src data: blob:","form-action 'none'","base-uri 'none'"].join("; ")}function frameNonce(){const Au=new Uint8Array(16);return crypto.getRandomValues(Au),Array.from(Au,lo=>lo.toString(16).padStart(2,"0")).join("")}function customFrameDocument(Au,lo){const $u=lo.replace(/[&<>"]/g,Ru=>`&#${Ru.charCodeAt(0)};`);return`<!doctype html>
3783
+ `+Fp),eh&&(Fp=fp(Fp)),Xu&&Nd?ad(Fp):Fp},lo.setConfig=function(){let Lh=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};$p(Lh),Dh=!0,Gd=Ed,zd=$d},lo.clearConfig=function(){zh=null,Dh=!1,Gd=null,zd=null,Xu=td,ed=""},lo.isValidAttribute=function(Lh,Ud,lh){zh||$p({});const Mh=Hh(Lh),Nh=Hh(Ud);return vf(Mh,Nh,lh)},lo.addHook=function(Lh,Ud){typeof Ud=="function"&&objectHasOwnProperty(dd,Lh)&&arrayPush(dd[Lh],Ud)},lo.removeHook=function(Lh,Ud){if(objectHasOwnProperty(dd,Lh)){if(Ud!==void 0){const lh=arrayLastIndexOf(dd[Lh],Ud);return lh===-1?void 0:arraySplice(dd[Lh],lh,1)[0]}return arrayPop(dd[Lh])}},lo.removeHooks=function(Lh){objectHasOwnProperty(dd,Lh)&&(dd[Lh]=[])},lo.removeAllHooks=function(){dd=_createHooksMap()},lo}var purify$1=createDOMPurify();let purify;function sanitize(Au){if(!purify)if(typeof purify$1.sanitize=="function")purify=purify$1;else{const lo=globalThis.window;if(lo)purify=purify$1(lo);else throw new Error("DOMPurify requires a window object. If testing, provide a jsdom window as `globalThis`.")}return purify.sanitize(Au)}async function renderMarkdown(Au,lo){const $u=rawMarkdownRenderer.render(Au,lo?.tagClassMap);return sanitize($u)}const A2uiMarkdownProvider=({children:Au})=>jsxRuntimeExports.jsx(MarkdownContext.Provider,{value:renderMarkdown,children:Au});function applyA2uiClassFallbacks(Au){Au.querySelectorAll("button").forEach(lo=>{lo.classList.remove("undefined");const $u=lo;if($u.classList.contains("a2ui-tab-button")){$u.style.removeProperty("background"),$u.style.removeProperty("border"),$u.style.removeProperty("color"),$u.style.removeProperty("border-radius");return}if($u.classList.contains("chip")){$u.style.removeProperty("background"),$u.style.removeProperty("background-color"),$u.style.removeProperty("border"),$u.style.removeProperty("color");return}lo.classList.contains("a2ui-button")||lo.classList.add("a2ui-button"),lo.classList.contains("a2ui-button-primary")||lo.classList.add("a2ui-button-primary"),$u.style.removeProperty("background"),$u.style.removeProperty("border"),$u.style.removeProperty("color"),$u.style.removeProperty("border-radius"),$u.style.removeProperty("padding"),$u.style.removeProperty("font-weight"),$u.style.removeProperty("cursor")}),Au.querySelectorAll("input[type='text'], input[type='number'], input[type='password'], input[type='datetime-local'], textarea").forEach(lo=>{lo.classList.remove("undefined"),lo.classList.contains("a2ui-textfield-input")||lo.classList.add("a2ui-textfield-input")}),Au.querySelectorAll("label").forEach(lo=>{lo.classList.remove("undefined"),lo.classList.contains("a2ui-textfield-label")||lo.classList.add("a2ui-textfield-label")}),Au.querySelectorAll("span").forEach(lo=>{lo.textContent&&/invalid|required|error/i.test(lo.textContent)&&(lo.classList.contains("a2ui-textfield-error")||lo.classList.add("a2ui-textfield-error"))}),Au.querySelectorAll(".body, .caption").forEach(lo=>{lo.classList.remove("undefined"),lo.classList.contains("a2ui-text")||lo.classList.add("a2ui-text"),lo.classList.contains("caption")&&!lo.classList.contains("a2ui-caption")&&lo.classList.add("a2ui-caption")})}function A2uiSurfaceComposed({surface:Au}){const lo=reactExports.useRef(null);return reactExports.useEffect(()=>{const $u=lo.current;if(!$u)return;const Ru=()=>applyA2uiClassFallbacks($u);Ru();const Iu=new MutationObserver(()=>{Ru()});return Iu.observe($u,{childList:!0,subtree:!0}),()=>{Iu.disconnect()}},[Au]),jsxRuntimeExports.jsx("div",{ref:lo,children:jsxRuntimeExports.jsx(A2uiSurface,{surface:Au})})}const A2UI_INPUT_SELECTOR="& .a2ui-textfield-input",A2UI_INPUT_FOCUS_SELECTOR="& .a2ui-textfield-input:focus",A2UI_INPUT_HOVER_SELECTOR="& .a2ui-textfield-input:hover",A2UI_RENDER_SCOPE_SX={"--a2ui-icon-size":"1em","& .a2ui-card":{background:"var(--a2ui-card-background, var(--a2ui-color-surface, #f6f8fa))",border:"1px solid var(--a2ui-color-border, #d0d7de)",borderRadius:"var(--a2ui-card-border-radius, 12px)",boxShadow:"var(--a2ui-card-box-shadow, none)"},"& .a2ui-text":{color:"var(--a2ui-color-on-surface, var(--a2ui-color-on-background, #1f2328))",margin:0},"& .a2ui-caption":{color:"var(--a2ui-text-caption-color, var(--a2ui-color-on-surface, #656d76))"},"& .a2ui-button":{appearance:"none",cursor:"pointer",border:"1px solid var(--button-primary-bgColor-rest)",background:"var(--button-primary-bgColor-rest)",color:"var(--button-primary-fgColor-rest)",borderRadius:"var(--a2ui-button-border-radius, 6px)",padding:"var(--a2ui-button-padding, 5px 16px)",fontWeight:"var(--a2ui-button-font-weight, 500)",boxShadow:"var(--a2ui-button-box-shadow, none)",transition:"background-color 0.15s ease, border-color 0.15s ease"},"& .a2ui-button .a2ui-text":{color:"inherit"},"& .a2ui-button:hover":{background:"var(--button-primary-bgColor-hover)",borderColor:"var(--button-primary-bgColor-hover)"},"& .a2ui-button:disabled":{opacity:.6,cursor:"not-allowed"},"& .a2ui-tab-button":{appearance:"none",background:"transparent",border:"none",borderBottom:"2px solid transparent",borderRadius:0,marginBottom:"-1px",padding:"var(--a2ui-tab-padding, 8px 16px)",color:"var(--a2ui-tab-color, var(--a2ui-color-on-surface, #656d76))",cursor:"pointer",fontFamily:"inherit",fontSize:"var(--a2ui-font-size-sm, 14px)",fontWeight:500,boxShadow:"none",transition:"color 0.15s ease, border-color 0.15s ease, background-color 0.15s ease"},"& .a2ui-tab-button:hover":{color:"var(--a2ui-tab-color-hover, var(--a2ui-color-primary, #1f883d))",background:"var(--a2ui-tab-background-hover, var(--a2ui-color-surface, #f6f8fa))"},"& .a2ui-tab-button.active":{color:"var(--a2ui-tab-color-active, var(--a2ui-color-primary, #1f883d))",borderBottomColor:"var(--a2ui-tab-border-active, var(--a2ui-color-primary, #1f883d))",fontWeight:600},"& .chip":{appearance:"none",padding:"var(--a2ui-choicepicker-chip-padding, 4px 12px)",borderRadius:"var(--a2ui-choicepicker-chip-border-radius, 999px)",border:"1px solid var(--a2ui-color-border, #d0d7de)",background:"var(--a2ui-color-surface, #f6f8fa)",color:"var(--a2ui-color-on-surface, #1f2328)",cursor:"pointer",fontFamily:"inherit",fontSize:"var(--a2ui-font-size-sm, 14px)",fontWeight:500,boxShadow:"none",transition:"background-color 0.15s ease, border-color 0.15s ease, color 0.15s ease"},"& .chip:hover":{borderColor:"var(--a2ui-color-border-hover, var(--a2ui-color-primary, #1f883d))"},'& .chip.selected, & .chip[aria-pressed="true"]':{background:"var(--a2ui-color-primary, #1f883d)",borderColor:"var(--a2ui-color-primary, #1f883d)",color:"var(--a2ui-color-on-primary, #ffffff)"},[A2UI_INPUT_SELECTOR]:{width:"100%",minHeight:"var(--a2ui-control-height, 32px)",boxSizing:"border-box",background:"var(--a2ui-textfield-background, var(--a2ui-color-input, var(--a2ui-color-background, #ffffff)))",color:"var(--a2ui-textfield-color, var(--a2ui-color-on-input, var(--a2ui-color-on-background, #1f2328)))",border:"var(--a2ui-textfield-border, 1px solid var(--a2ui-color-border, #d0d7de))",borderRadius:"var(--a2ui-textfield-border-radius, 6px)",padding:"var(--a2ui-textfield-padding, 5px 12px)",fontSize:"var(--a2ui-font-size-sm, 14px)",lineHeight:"20px",transition:"border-color 0.15s ease, box-shadow 0.15s ease"},[A2UI_INPUT_HOVER_SELECTOR]:{borderColor:"var(--a2ui-textfield-color-border-hover, var(--a2ui-color-border-hover, #8c959f))"},[A2UI_INPUT_FOCUS_SELECTOR]:{outline:"none",borderColor:"var(--a2ui-textfield-color-border-focus, var(--a2ui-color-primary, #1f883d))",boxShadow:"0 0 0 3px color-mix(in srgb, var(--a2ui-color-primary, #1f883d) 25%, transparent)"},"& .a2ui-textfield-label":{color:"var(--a2ui-textfield-label-color, var(--a2ui-color-on-surface, var(--a2ui-color-on-background, #1f2328)))",fontWeight:600,fontSize:"var(--a2ui-font-size-xs, 12px)",marginBottom:"var(--a2ui-spacing-xxs, 4px)",display:"inline-block"},"& .a2ui-textfield-error":{color:"var(--a2ui-textfield-color-error, #d1242f)",fontSize:"var(--a2ui-font-size-xs, 12px)",marginTop:"var(--a2ui-spacing-xs, 4px)"},'& input[type="checkbox"]':{accentColor:"var(--a2ui-color-primary, #1f883d)"}},VISIBLE_WHEN="visible_when";function isShown(Au){return Array.isArray(Au)?Au.length>0:!!Au}const OWN_COMPONENT_IDS=Object.values(COMPONENT_CATALOGUE).filter(Au=>!Au.standard).map(Au=>Au.id);function ownComponent(Au){const lo=COMPONENT_CATALOGUE[Au];if(!lo)throw new Error(`The catalog has no component ${Au}.`);if(lo.standard||!lo.properties||!lo.bindings)throw new Error(`${Au} is A2UI's own: its schema is the basic catalog's, not Datalayer's.`);return lo}const BindingSchema=unionType$1([arrayType$1(anyType$1()),recordType$1(stringType$1(),unknownType$1()),stringType$1(),numberType$1(),booleanType$1(),DataBindingSchema]).describe("REF:#/$defs/DynamicValue|Datalayer: what the component shows or sends — a path the application publishes or takes, or a value given in place.");function propertySchema(Au,lo){if(lo.enum)return enumType$1(lo.enum);switch(lo.type){case"string":return stringType$1();case"integer":case"number":return numberType$1();case"boolean":return booleanType$1();case"array":return arrayType$1(anyType$1());case"object":return recordType$1(stringType$1(),unknownType$1());default:throw new Error(`${Au} is typed ${String(lo.type)}, which a component's property cannot be.`)}}function bindingNames(Au){const{shows:lo,sends:$u}=Au.bindings;return[...new Set([...lo,...$u])]}function ownComponentSchema(Au){return componentSchemaOf(ownComponent(Au))}function componentSchemaOf(Au){const lo=Au.id;if(!Au.bindings)throw new Error(`${lo} says nothing of what it shows or sends.`);const $u=Au.properties,Ru=new Set($u.required??[]),Iu={};for(const[Pu,Ou]of Object.entries($u.properties??{})){const Mu=propertySchema(Pu,Ou);Iu[Pu]=Ru.has(Pu)?Mu:Mu.optional()}for(const Pu of bindingNames(Au)){if(Pu in Iu)throw new Error(`${lo} both declares ${Pu} as a property and binds through it.`);Iu[Pu]=BindingSchema.optional()}return Iu.action=ActionSchema.describe("REF:#/$defs/Action|What it dispatches when a person acts on it.").optional(),Iu.weight=numberType$1().describe("The relative weight of this component within a Row or Column.").optional(),objectType$1(Iu).strict()}const DRAWN_OWN_COMPONENTS=["Table","Chart","FileUpload","Chat","Evidence","Form","Download"],CARD_RADIUS="var(--theme-radius-card, 6px)";function BlockFrame({title:Au,label:lo,weight:$u,children:Ru,testId:Iu}){return jsxRuntimeExports.jsxs(Box,{as:"section","aria-label":Au||lo,"data-testid":Iu,display:"flex",flexDirection:"column",gap:2,minWidth:0,boxSizing:"border-box",p:3,border:"1px solid",borderColor:"border.default",borderRadius:CARD_RADIUS,bg:"canvas.default",color:"fg.default",flex:typeof $u=="number"?`${$u}`:void 0,minHeight:typeof $u=="number"?0:void 0,children:[Au?jsxRuntimeExports.jsx(Heading$2,{as:"h3",sx:{fontSize:2,m:0},children:Au}):null,Ru]})}function Problem({children:Au}){return jsxRuntimeExports.jsx(Text$3,{as:"p",role:"status",sx:{m:0,color:"danger.fg",fontSize:1},children:Au})}function Quiet({children:Au}){return jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,color:"fg.muted",fontSize:1},children:Au})}const isRecord=Au=>typeof Au=="object"&&Au!==null&&!Array.isArray(Au);function asWords(Au){return Au==null?"":typeof Au=="object"?JSON.stringify(Au):String(Au)}function ownImplementation(Au,lo){const $u={name:Au,schema:ownComponentSchema(Au)};return createComponentImplementation($u,lo)}const PAGE_SIZE=20,sameRow=(Au,lo)=>Au!==void 0&&JSON.stringify(Au)===JSON.stringify(lo);function tableRows(Au){if(Au==null)return{rows:[]};if(!Array.isArray(Au))return{problem:"What it shows is not a list of rows."};const lo=Au.findIndex($u=>!isRecord($u));return lo>=0?{problem:`Row ${lo+1} is not a record of the columns' values.`}:{rows:Au}}function TableView({props:Au}){const{title:lo,columns:$u,selectable:Ru=!1,selected:Iu,setSelected:Pu,action:Ou}=Au,Mu=Au.page_size??PAGE_SIZE,Du=reactExports.useMemo(()=>tableRows(Au.rows),[Au.rows]),Lu="rows"in Du?Du.rows:[],Bu=Math.max(1,Math.ceil(Lu.length/Mu)),[ju,Fu]=reactExports.useState(0);reactExports.useEffect(()=>{ju>=Bu&&Fu(Bu-1)},[ju,Bu]);const zu=Lu.slice(ju*Mu,(ju+1)*Mu),[Uu,Hu]=reactExports.useState(void 0),Vu=Iu??Uu,Gu=Ku=>{Hu(Ku),Pu(Ku),Ou?.()},Wu=(Ku,Ju)=>{(Ku.key==="Enter"||Ku.key===" ")&&(Ku.preventDefault(),Gu(Ju))};return jsxRuntimeExports.jsxs(BlockFrame,{title:lo,label:"Table",weight:Au.weight,testId:"a2ui-table",children:["problem"in Du?jsxRuntimeExports.jsx(Problem,{children:Du.problem}):jsxRuntimeExports.jsxs(Box,{overflowX:"auto",children:[jsxRuntimeExports.jsxs(Box,{as:"table",role:Ru?"grid":void 0,"aria-label":lo||"Table",width:"100%",borderCollapse:"collapse",fontSize:1,sx:{"& th, & td":{textAlign:"left",px:2,py:1,borderBottom:"1px solid",borderColor:"border.muted"},"& th":{color:"fg.muted",fontWeight:"semibold"}},children:[jsxRuntimeExports.jsx("thead",{children:jsxRuntimeExports.jsx("tr",{children:$u.map(Ku=>jsxRuntimeExports.jsx("th",{scope:"col",children:Ku},Ku))})}),jsxRuntimeExports.jsx("tbody",{children:zu.map((Ku,Ju)=>{const Yu=Ru&&sameRow(Vu,Ku);return jsxRuntimeExports.jsx(Box,{as:"tr",...Ru?{tabIndex:0,"aria-selected":Yu,onClick:()=>Gu(Ku),onKeyDown:Xu=>Wu(Xu,Ku)}:null,cursor:Ru?"pointer":void 0,bg:Yu?"accent.subtle":void 0,focusVisible:{outline:"2px solid",outlineColor:"accent.fg",outlineOffset:"-2px"},hover:Ru?{bg:Yu?"accent.subtle":"canvas.subtle"}:void 0,children:$u.map(Xu=>jsxRuntimeExports.jsx("td",{children:asWords(Ku[Xu])},Xu))},ju*Mu+Ju)})})]}),Lu.length===0?jsxRuntimeExports.jsx(Quiet,{children:"No rows yet."}):null]}),Bu>1?jsxRuntimeExports.jsxs(Box,{as:"nav","aria-label":"Pages",display:"flex",alignItems:"center",gap:2,children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:ju===0,onClick:()=>Fu(ju-1),children:"Previous"}),jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:1,color:"fg.muted"},"aria-live":"polite",children:["Page ",ju+1," of ",Bu]}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:ju>=Bu-1,onClick:()=>Fu(ju+1),children:"Next"})]}):null]})}const Table=ownImplementation("Table",TableView),loadECharts=()=>__vitePreload(()=>import("./chunks/index-BTnG8qrO.js"),[],import.meta.url),chartRefused=Au=>jsxRuntimeExports.jsx(Problem,{children:`The chart could not be drawn: ${Au.message}`}),FALLBACK={series:["#0969da","#1a7f37","#9a6700","#8250df","#cf222e","#bc4c00"],text:"#1f2328",muted:"#59636e",grid:"#d1d9e0"},SERIES_VARIABLES=["--fgColor-accent","--fgColor-success","--fgColor-attention","--fgColor-done","--fgColor-danger","--fgColor-severe"];function readColours(Au){if(!Au)return FALLBACK;const lo=getComputedStyle(Au),$u=(Ru,Iu)=>lo.getPropertyValue(Ru).trim()||Iu;return{series:SERIES_VARIABLES.map((Ru,Iu)=>$u(Ru,FALLBACK.series[Iu])),text:$u("--fgColor-default",FALLBACK.text),muted:$u("--fgColor-muted",FALLBACK.muted),grid:$u("--borderColor-muted",FALLBACK.grid)}}function chartPoints(Au){return Au==null?{points:[]}:!Array.isArray(Au)||Au.some(lo=>!isRecord(lo))?{problem:"What it shows is not a list of points."}:{points:Au}}function chartSeries(Au,lo){if(!lo.series)return[{name:lo.y,points:Au}];const $u=[];for(const Ru of Au){const Iu=asWords(Ru[lo.series]);$u.includes(Iu)||$u.push(Iu)}return $u.map(Ru=>({name:Ru,points:Au.filter(Iu=>asWords(Iu[lo.series])===Ru)}))}function chartOption(Au,lo,$u){const Ru=chartSeries(Au,lo),Iu=lo.kind==="scatter",Pu=[];for(const Mu of Au){const Du=asWords(Mu[lo.x]);Pu.includes(Du)||Pu.push(Du)}const Ou={axisLine:{lineStyle:{color:$u.grid}},axisLabel:{color:$u.muted},splitLine:{lineStyle:{color:$u.grid}},nameTextStyle:{color:$u.muted}};return{aria:{enabled:!0},animation:!1,color:$u.series,textStyle:{color:$u.text},grid:{left:48,right:16,top:Ru.length>1?48:32,bottom:40},legend:Ru.length>1?{top:0,textStyle:{color:$u.text}}:void 0,tooltip:{trigger:Iu?"item":"axis"},xAxis:Iu?{type:"value",name:lo.x,nameLocation:"middle",nameGap:26,...Ou}:{type:"category",data:Pu,name:lo.x,nameLocation:"middle",nameGap:26,...Ou},yAxis:{type:"value",name:lo.y,...Ou},series:Ru.map(Mu=>({name:Mu.name,type:lo.kind==="area"?"line":lo.kind,areaStyle:lo.kind==="area"?{}:void 0,data:Iu?Mu.points.map(Du=>[Number(Du[lo.x]),Number(Du[lo.y])]):Pu.map(Du=>{const Lu=Mu.points.find(Bu=>asWords(Bu[lo.x])===Du);return Lu?Number(Lu[lo.y]):null})}))}}function ChartView({props:Au}){const{title:lo,kind:$u,x:Ru,y:Iu,series:Pu}=Au,Ou=reactExports.useMemo(()=>chartPoints(Au.points),[Au.points]),Mu=reactExports.useRef(null),[Du,Lu]=reactExports.useState(FALLBACK);reactExports.useLayoutEffect(()=>{Lu(readColours(Mu.current))},[]);const Bu="points"in Ou?Ou.points:[],ju=reactExports.useMemo(()=>chartOption(Bu,{kind:$u,x:Ru,y:Iu,series:Pu},Du),[Bu,$u,Ru,Iu,Pu,Du]),Fu=Pu?[Ru,Pu,Iu]:[Ru,Iu],zu=`${lo||"Chart"}: ${Iu} by ${Ru}, as a ${$u}`;return jsxRuntimeExports.jsx(BlockFrame,{title:lo,label:"Chart",weight:Au.weight,testId:"a2ui-chart",children:jsxRuntimeExports.jsx(Box,{ref:Mu,children:"problem"in Ou?jsxRuntimeExports.jsx(Problem,{children:Ou.problem}):Bu.length===0?jsxRuntimeExports.jsx(Quiet,{children:"No points yet."}):jsxRuntimeExports.jsxs(Box,{as:"figure","aria-label":zu,m:0,children:[jsxRuntimeExports.jsx("div",{"aria-hidden":"true",children:jsxRuntimeExports.jsx(ReactorLazy,{load:loadECharts,errorFallback:chartRefused,fallback:jsxRuntimeExports.jsx(Box,{height:240}),props:{option:ju,style:{height:240,width:"100%"},opts:{renderer:"svg"},notMerge:!0,lazyUpdate:!0}})}),jsxRuntimeExports.jsxs(Box,{as:"details",fontSize:1,children:[jsxRuntimeExports.jsx(Box,{as:"summary",cursor:"pointer",color:"fg.muted",focusVisible:{outline:"2px solid",outlineColor:"accent.fg"},children:jsxRuntimeExports.jsx(Text$3,{children:"The numbers"})}),jsxRuntimeExports.jsxs(Box,{as:"table",mt:1,borderCollapse:"collapse",sx:{"& th, & td":{textAlign:"left",pr:3,py:"2px"},"& th":{color:"fg.muted",fontWeight:"semibold"}},children:[jsxRuntimeExports.jsx("thead",{children:jsxRuntimeExports.jsx("tr",{children:Fu.map(Uu=>jsxRuntimeExports.jsx("th",{scope:"col",children:Uu},Uu))})}),jsxRuntimeExports.jsx("tbody",{children:Bu.map((Uu,Hu)=>jsxRuntimeExports.jsx("tr",{children:Fu.map(Vu=>jsxRuntimeExports.jsx("td",{children:asWords(Uu[Vu])},Vu))},Hu))})]})]})]})})})}const Chart=ownImplementation("Chart",ChartView),MAX_MB=25;function refusal(Au,lo,$u){return acceptsFile(lo,{name:Au.name,type:Au.type??""})?Au.size>$u*1024*1024?`${Au.name} is larger than ${$u} MB.`:null:`${Au.name} is not one it takes (${(lo??[]).join(", ")}).`}const readFile=Au=>new Promise((lo,$u)=>{const Ru=new FileReader;Ru.onload=()=>lo({name:Au.name,type:Au.type,size:Au.size,data_url:String(Ru.result)}),Ru.onerror=()=>$u(Ru.error),Ru.readAsDataURL(Au)});function FileUploadView({props:Au}){const{label:lo,accept:$u,multiple:Ru=!1,setFiles:Iu,action:Pu}=Au,Ou=Au.max_mb??MAX_MB,Mu=reactExports.useRef(null),Du=reactExports.useId(),[Lu,Bu]=reactExports.useState(!1),[ju,Fu]=reactExports.useState([]),zu=Array.isArray(Au.files)?Au.files.filter(isRecord).map(Gu=>String(Gu.name??"")):[],Uu=async Gu=>{const Wu=Array.from(Gu),Ku=Ru?Wu:Wu.slice(0,1),Ju=Ku.map(Yu=>refusal(Yu,$u,Ou)).filter(Yu=>Yu!==null);!Ru&&Wu.length>1&&Ju.push("It takes one file at a time."),Fu(Ju),!Ju.length&&(Iu(await Promise.all(Ku.map(readFile))),Pu?.())},Hu=Gu=>{Gu.preventDefault(),Bu(!1),Uu(Gu.dataTransfer.files)},Vu=[$u?.length?`Takes ${$u.join(", ")}`:"Takes any file",`up to ${Ou} MB`,Ru?"several at once":"one at a time"].join(", ");return jsxRuntimeExports.jsxs(BlockFrame,{label:lo,weight:Au.weight,testId:"a2ui-fileupload",children:[jsxRuntimeExports.jsxs(Box,{onDragOver:Gu=>{Gu.preventDefault(),Bu(!0)},onDragLeave:()=>Bu(!1),onDrop:Hu,"data-testid":"a2ui-fileupload-drop",display:"flex",flexDirection:"column",alignItems:"center",gap:2,p:3,border:"1px dashed",borderColor:Lu?"accent.fg":"border.default",borderRadius:CARD_RADIUS,bg:Lu?"accent.subtle":"canvas.subtle",textAlign:"center",children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold"},children:lo}),jsxRuntimeExports.jsx(ButtonComponent,{leadingVisual:UploadIcon,"aria-describedby":Du,onClick:()=>Mu.current?.click(),children:Ru?"Choose files":"Choose a file"}),jsxRuntimeExports.jsxs(Text$3,{id:Du,sx:{fontSize:0,color:"fg.muted"},children:["or drop ",Ru?"them":"it"," here. ",Vu,"."]}),jsxRuntimeExports.jsx("input",{ref:Mu,type:"file",hidden:!0,"aria-label":lo,accept:$u?.join(","),multiple:Ru,onChange:Gu=>{Gu.target.files&&Uu(Gu.target.files),Gu.target.value=""}})]}),ju.map(Gu=>jsxRuntimeExports.jsx(Problem,{children:Gu},Gu)),zu.length?jsxRuntimeExports.jsxs(Quiet,{children:["Given: ",zu.join(", ")]}):null]})}const FileUpload=ownImplementation("FileUpload",FileUploadView),PLACEHOLDER="Ask anything",AVATARS={userAvatar:jsxRuntimeExports.jsx(PersonIcon,{size:14}),assistantAvatar:jsxRuntimeExports.jsx(DependabotIcon,{size:14}),showAvatars:!0,avatarSize:24,userAvatarBg:"neutral.muted",assistantAvatarBg:"accent.emphasis"},NO_TIME=new Date(0);function chatItems(Au,lo){if(Au==null)return{items:[]};if(!Array.isArray(Au))return{problem:"What it shows is not a list of messages."};const $u=[];for(const[Ru,Iu]of Au.entries()){const Pu=`m${Ru}`;if(!isRecord(Iu))return{problem:`Message ${Ru+1} is not a message.`};if(Iu.role==="tool"){lo&&$u.push({id:Pu,type:"tool-call",toolCallId:Pu,toolName:asWords(Iu.name)||"tool",args:isRecord(Iu.args)?Iu.args:{},result:Iu.result,status:"complete"});continue}if(Iu.role!=="user"&&Iu.role!=="assistant")return{problem:`Message ${Ru+1} is from ${asWords(Iu.role)||"nobody"}: a message is the user's, the assistant's or a tool's.`};$u.push({id:Pu,role:Iu.role,content:asWords(Iu.text??Iu.content),createdAt:NO_TIME})}return{items:$u}}function ChatView({props:Au}){const{welcome:lo,starters:$u=[],setMessage:Ru,action:Iu}=Au,Pu=Au.placeholder??PLACEHOLDER,Ou=Au.show_tools??!0,Mu=reactExports.useMemo(()=>chatItems(Au.messages,Ou),[Au.messages,Ou]),[Du,Lu]=reactExports.useState(""),Bu=reactExports.useMemo(()=>reactExports.createRef(),[]),ju=reactExports.useMemo(()=>reactExports.createRef(),[]),Fu=zu=>{const Uu=zu.trim();Uu&&(Ru(Uu),Iu?.(),Lu(""))};return jsxRuntimeExports.jsxs(BlockFrame,{label:"Chat",weight:Au.weight,testId:"a2ui-chat",children:["problem"in Mu?jsxRuntimeExports.jsx(Problem,{children:Mu.problem}):jsxRuntimeExports.jsx(Box,{maxHeight:420,overflowY:"auto",borderRadius:CARD_RADIUS,children:jsxRuntimeExports.jsx(ChatMessageList,{displayItems:Mu.items,isLoading:!1,isStreaming:!1,showLoadingIndicator:!1,hideMessagesAfterToolUI:!1,avatarConfig:AVATARS,padding:2,emptyContent:jsxRuntimeExports.jsx(ChatEmptyState,{description:"",emptyState:{title:lo||"Start a conversation"},suggestions:$u.map(zu=>({title:zu,message:zu})),onSuggestionSubmit:zu=>Fu(zu.message)}),messagesEndRef:Bu,onRespond:async()=>{}})}),jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"flex-end",gap:2,children:[jsxRuntimeExports.jsx(Box,{flex:1,minWidth:0,children:jsxRuntimeExports.jsx(InputPromptText,{value:Du,onChange:Lu,placeholder:Pu,onSubmit:()=>Fu(Du),inputRef:ju})}),jsxRuntimeExports.jsx(IconButton,{icon:PaperAirplaneIcon,"aria-label":"Send",variant:"primary",disabled:!Du.trim(),onClick:()=>Fu(Du)})]})]})}const Chat=ownImplementation("Chat",ChatView),TITLE="Sources",MAX_ITEMS=5;function evidenceSources(Au){if(Au==null)return{sources:[]};if(!Array.isArray(Au))return{problem:"What it shows is not a list of sources."};const lo=[];for(const[$u,Ru]of Au.entries()){if(!isRecord(Ru)||!Ru.title&&!Ru.url)return{problem:`Source ${$u+1} has neither a title nor a link.`};lo.push({title:asWords(Ru.title)||asWords(Ru.url),url:asWords(Ru.url),passage:asWords(Ru.passage)})}return{sources:lo}}function EvidenceView({props:Au}){const{show_passages:lo=!0,action:$u}=Au,Ru=Au.title??TITLE,Iu=Au.max_items??MAX_ITEMS,Pu=reactExports.useMemo(()=>evidenceSources(Au.sources),[Au.sources]),[Ou,Mu]=reactExports.useState(!1),Du="sources"in Pu?Pu.sources:[],Lu=Ou?Du:Du.slice(0,Iu),Bu=Du.length-Lu.length;return jsxRuntimeExports.jsxs(BlockFrame,{title:Ru,label:"Evidence",weight:Au.weight,testId:"a2ui-evidence",children:["problem"in Pu?jsxRuntimeExports.jsx(Problem,{children:Pu.problem}):Du.length===0?jsxRuntimeExports.jsx(Quiet,{children:"Nothing cited yet."}):jsxRuntimeExports.jsx(Box,{as:"ol",m:0,pl:3,display:"flex",flexDirection:"column",gap:2,children:Lu.map((ju,Fu)=>jsxRuntimeExports.jsxs("li",{children:[ju.url?jsxRuntimeExports.jsxs(Link$1,{href:ju.url,target:"_blank",rel:"noreferrer noopener",onClick:()=>$u?.(),sx:{fontWeight:"semibold"},children:[ju.title," ",jsxRuntimeExports.jsx(LinkExternalIcon,{size:12,"aria-label":"opens in a new tab"})]}):jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold"},children:ju.title}),lo&&ju.passage?jsxRuntimeExports.jsx(Box,{as:"blockquote",m:0,mt:1,pl:2,borderLeft:"3px solid",borderColor:"border.default",color:"fg.muted",fontSize:1,children:ju.passage}):null]},`${ju.url}-${Fu}`))}),Bu>0?jsxRuntimeExports.jsx(Box,{children:jsxRuntimeExports.jsxs(ButtonComponent,{size:"small",variant:"invisible",onClick:()=>Mu(!0),children:[Bu," more"]})}):null]})}const Evidence=ownImplementation("Evidence",EvidenceView),loadSchemaForm=()=>__vitePreload(()=>import("./chunks/SchemaForm-CE5NfpBU.js"),[],import.meta.url),formRefused=Au=>jsxRuntimeExports.jsx(Problem,{children:`The form could not be drawn: ${Au.message}`}),SUBMIT_LABEL="Send";function FormView({props:Au}){const{title:lo,schema:$u,setValues:Ru,action:Iu}=Au,Pu=Au.submit_label??SUBMIT_LABEL,Ou=isRecord(Au.values)?Au.values:{},[Mu,Du]=reactExports.useState(Ou),[Lu,Bu]=reactExports.useState(!1),ju=JSON.stringify(Ou);reactExports.useEffect(()=>{Du(JSON.parse(ju))},[ju]);const Fu=Iu===void 0,zu=JSON.stringify(Au.ui??{}),Uu=reactExports.useMemo(()=>({...JSON.parse(zu),"ui:submitButtonOptions":Fu?{norender:!0}:{submitText:Pu}}),[zu,Fu,Pu]),Hu=$u.type!==void 0&&$u.type!=="object"?"Its fields are not an object schema: a form asks for several named values.":null;return jsxRuntimeExports.jsx(BlockFrame,{title:lo,label:"Form",weight:Au.weight,testId:"a2ui-form",children:Hu?jsxRuntimeExports.jsx(Problem,{children:Hu}):jsxRuntimeExports.jsx(ReactorLazy,{load:loadSchemaForm,errorFallback:formRefused,props:{schema:$u,uiSchema:Uu,formData:Mu,liveValidate:Lu,onBlur:()=>Bu(!0),onError:()=>Bu(!0),showErrorList:!1,onChange:Vu=>{const Gu=Vu.formData??{};Du(Gu),Fu&&Ru(Gu)},onSubmit:Vu=>{Ru(Vu.formData??{}),Iu?.()}}})})}const Form=ownImplementation("Form",FormView),SCHEMES=/^(https?:\/\/|data:)/i;function sizeInWords(Au){if(typeof Au!="number"||!Number.isFinite(Au)||Au<0)return"";if(Au<1024)return Au===1?"1 byte":`${Au} bytes`;const lo=["KB","MB","GB"];let $u=Au/1024,Ru=0;for(;$u>=1024&&Ru<lo.length-1;)$u/=1024,Ru+=1;return`${$u<10?$u.toFixed(1):Math.round($u)} ${lo[Ru]}`}function downloadOf(Au){const lo=typeof Au.name=="string"?Au.name.trim():"",$u=typeof Au.url=="string"?Au.url.trim():"";return lo?$u?SCHEMES.test($u)?{name:lo,url:$u}:{problem:`${lo} is not offered: its link is neither an http(s) link nor a data: URL.`}:{problem:`${lo} has no link.`}:{problem:"This file has no name."}}function DownloadView({props:Au}){const{action:lo}=Au,$u=reactExports.useMemo(()=>downloadOf({name:Au.name,url:Au.url}),[Au.name,Au.url]),Ru=[Au.media_type,sizeInWords(Au.size)].filter(Boolean).join(" · ");return jsxRuntimeExports.jsx(BlockFrame,{label:"File to download",weight:Au.weight,testId:"a2ui-download",children:"problem"in $u?jsxRuntimeExports.jsx(Problem,{children:$u.problem}):jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,alignItems:"flex-start",children:[jsxRuntimeExports.jsx(Box,{color:"fg.muted",pt:"2px",children:jsxRuntimeExports.jsx(DownloadIcon,{size:16,"aria-hidden":"true"})}),jsxRuntimeExports.jsxs(Box,{display:"flex",flexDirection:"column",minWidth:0,children:[jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Link$1,{href:$u.url,download:$u.name,target:"_blank",rel:"noreferrer noopener",onClick:()=>lo?.(),sx:{fontWeight:"semibold",wordBreak:"break-word"},children:$u.name}),Ru?jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontSize:1,ml:2},children:Ru}):null]}),Au.description?jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontSize:1},children:Au.description}):null]})]})})}const Download=ownImplementation("Download",DownloadView),RENDERERS={Table,Chart,FileUpload,Chat,Evidence,Form,Download},OWN_COMPONENTS=(()=>{const Au=DRAWN_OWN_COMPONENTS,lo=OWN_COMPONENT_IDS.filter(Ru=>!Au.includes(Ru));if(lo.length)throw new Error(`The catalog has ${lo.join(", ")}, which no renderer draws.`);const $u=Au.filter(Ru=>!OWN_COMPONENT_IDS.includes(Ru));if($u.length)throw new Error(`A renderer draws ${$u.join(", ")}, which the catalog does not have.`);return OWN_COMPONENT_IDS.map(Ru=>RENDERERS[Ru])})();function nodeIsShown(Au){const lo=Au[VISIBLE_WHEN];if(!(lo instanceof ResolvedBinding))throw new Error(`${VISIBLE_WHEN} resolved to ${String(lo)}, not a binding: the catalog's schema does not declare it.`);return isWritable(lo)?isShown(lo.value):lo.value===void 0||isShown(lo.value)}const VISIBLE_WHEN_SCHEMA=DynamicBooleanSchema.describe("REF:#/$defs/DynamicBoolean|Datalayer: the block is shown only while this is true or not empty — a path the application publishes.").optional();function withVisibleWhen(Au){const lo=Au.view;if(!lo)throw new Error(`${Au.name} has no node view: visible_when is read from the node, and A2uiSurface draws through it.`);const $u=Au.schema;if(!$u.shape||typeof $u.extend!="function")throw new Error(`${Au.name}'s schema is not an object: visible_when cannot be declared on it.`);if(VISIBLE_WHEN in $u.shape)throw new Error(`${Au.name} already declares ${VISIBLE_WHEN}.`);const Ru=({node:Iu,buildChild:Pu})=>{const Ou=useSignalValue(Iu.props);return nodeIsShown(Ou)?jsxRuntimeExports.jsx(lo,{node:Iu,buildChild:Pu}):null};return Ru.displayName=`${Au.name}.visibleWhen`,{...Au,schema:$u.extend({[VISIBLE_WHEN]:VISIBLE_WHEN_SCHEMA}),view:Ru}}const datalayerCatalog=new Catalog(basicCatalog.id,basicCatalog.protocolVersion,[...basicCatalog.components.values(),...OWN_COMPONENTS].map(withVisibleWhen),[...basicCatalog.functions.values()],basicCatalog.themeSchema,basicCatalog.instructions);function catalogOfBlocks(Au,lo=[]){const $u=new Map(lo.map(Pu=>[Pu.name,withVisibleWhen(Pu)])),Ru=[...$u.keys()].filter(Pu=>datalayerCatalog.components.has(Pu));if(Ru.length>0)throw new Error(`${Ru.join(", ")} ${Ru.length===1?"is a component":"are components"} of the catalog: a component of an application's own is named otherwise.`);const Iu=Au.filter(Pu=>!datalayerCatalog.components.has(Pu)&&!$u.has(Pu));if(Iu.length>0)throw new Error(`No renderer draws ${Iu.join(", ")}: a block is contributed by a plugin whose component the catalog draws.`);return new Catalog(datalayerCatalog.id,datalayerCatalog.protocolVersion,Au.map(Pu=>datalayerCatalog.components.get(Pu)??$u.get(Pu)),[...datalayerCatalog.functions.values()],datalayerCatalog.themeSchema,datalayerCatalog.instructions)}function catalogWithOwn(Au){return Au.length===0?datalayerCatalog:catalogOfBlocks([...datalayerCatalog.components.keys(),...Au.map(lo=>lo.name)],Au)}const CUSTOM_FILE=/^(?:\.\/)?(?:[A-Za-z0-9_][A-Za-z0-9_.-]*\/)*[A-Za-z0-9_][A-Za-z0-9_.-]*\.m?js$/,isFolderSource=Au=>!/^[a-z][a-z0-9+.-]*:/.test(Au)&&CUSTOM_FILE.test(Au),folderSourceUrl=(Au,lo)=>new URL(Au.replace(/^\.\//,""),lo.endsWith("/")?lo:`${lo}/`).href,hasFolderModules=Au=>(Au.interface.customComponents??[]).some(lo=>isFolderSource(lo.source));function customComponentEntry(Au,lo){return{id:Au.name,name:Au.name,description:Au.description,category:"custom",emoji:"🧩",version:lo,standard:!1,properties:Au.props,bindings:{shows:[...Au.shows],sends:[...Au.sends]},events:Au.sends.length>0?["send"]:[],...Au.example?{example:Au.example}:{}}}const CUSTOM_FRAME_SANDBOX="allow-scripts",MAX_MODULE_BYTES=2*1024*1024,FRAME_TAG="loop.component";function customFramePolicy(Au){return["default-src 'none'",`script-src 'nonce-${Au}' blob:`,"style-src 'unsafe-inline'","img-src data: blob:","font-src data:","media-src data: blob:","form-action 'none'","base-uri 'none'"].join("; ")}function frameNonce(){const Au=new Uint8Array(16);return crypto.getRandomValues(Au),Array.from(Au,lo=>lo.toString(16).padStart(2,"0")).join("")}function customFrameDocument(Au,lo){const $u=lo.replace(/[&<>"]/g,Ru=>`&#${Ru.charCodeAt(0)};`);return`<!doctype html>
3784
3784
  <html lang="en">
3785
3785
  <head>
3786
3786
  <meta charset="utf-8">
@@ -3835,11 +3835,11 @@ ${lo}`;let Iu=MODULES.get(Ru);return Iu||(Iu=(async()=>{const Pu=await $u(Au,{cr
3835
3835
  ${Mu}`:ju,inputs:Mu,clear:Ou?[]:[DRAFT.path],loop:Lu()}:{refused:"Nothing to send: write a message first."}}}}const text=(Au,lo,$u)=>({id:Au,component:"Text",text:{path:lo},...$u?{variant:$u}:{}}),button=(Au,lo,$u,Ru=!1)=>[{id:Au,component:"Button",child:`${Au}-label`,...Ru?{variant:"primary"}:{},action:{event:{name:$u}}},{id:`${Au}-label`,component:"Text",text:lo}];function settingsForm(Au){const lo=pageOf(Au);return lo?pageForm(Au,lo):Au.interface.settings&&settingFields(Au.interface.settings).length?[{id:"settings",component:"Form",schema:Au.interface.settings,...Au.interface.settingsUi?{ui:Au.interface.settingsUi}:{},values:{path:"/inputs"}}]:[]}function pageForm(Au,lo){const $u=Au.interface.settings,Ru={...lo.inputs,type:"object",properties:{...$u?.properties,...lo.inputs.properties},required:[...$u?.required??[],...lo.inputs.required??[]]},Iu={...Au.interface.settingsUi,...lo.inputsUi},Pu=lo.outputs.flatMap(Ou=>[...Ou.title?[{id:`output-${Ou.name}-title`,component:"Text",text:Ou.title,variant:"h4"}]:[],{...Ou.props,id:`output-${Ou.name}`,component:Ou.component,[pageOutputShows(Ou.component,Au.interface.customComponents)??"text"]:{path:outputPath(Ou.name)}}]);return[{id:"inputs",component:"Form",schema:Ru,...Object.keys(Iu).length>0?{ui:Iu}:{},values:{path:"/inputs"}},...lo.live?[]:button("run-page","Run",PAGE_ACTION,!0),...Pu]}function defaultAppSurface(Au){const lo=appKindPaths(Au).inputs?settingsForm(Au):[],$u=[];switch(Au.kind){case"chat":$u.push(text("question","/question","h3"),text("answer","/answer"),text("status","/status","caption"),...lo);break;case"widget":if(pageOf(Au)){$u.push(...lo);break}$u.push(...lo,{id:"actions",component:"Row",children:["run","stop"]},...button("run","Run","run",!0),...button("stop","Stop","stop"),text("status","/status","caption"),text("output","/output"));break;case"worker":$u.push(text("goal","/goal","h3"),text("status","/status","caption"),text("activity","/activity","caption"),text("report","/report"));break}const Ru=new Set($u.flatMap(Iu=>[...Array.isArray(Iu.children)?Iu.children:[],Iu.child].filter(Pu=>typeof Pu=="string")));return[{id:"root",component:"Column",children:$u.map(Iu=>Iu.id).filter(Iu=>!Ru.has(Iu))},...$u]}function appPageMessages(Au,lo){const $u=surfaceComponents(Au);return[{version:"v0.9",createSurface:{surfaceId:APP_PAGE_SURFACE_ID,catalogId:lo}},{version:"v0.9",updateComponents:{surfaceId:APP_PAGE_SURFACE_ID,components:$u.length>0?$u:defaultAppSurface(Au)}},{version:"v0.9",updateDataModel:{surfaceId:APP_PAGE_SURFACE_ID,path:"/",value:appPageInitialData(Au)}}]}const LOOP_PAGE="loop.page";function streamEvents(Au){const lo=[];for(const $u of Au.split(`
3836
3836
 
3837
3837
  `)){const Ru=$u.split(`
3838
- `).filter(Iu=>Iu.startsWith("data:")).map(Iu=>Iu.slice(5).trim()).join("");if(Ru)try{lo.push(JSON.parse(Ru))}catch{}}return lo}function pageTurnOf(Au){let lo=null;for(const $u of streamEvents(Au)){if($u.type==="RUN_ERROR")return{refused:String($u.message??"Its page could not run.")};if($u.type==="CUSTOM"&&$u.name===LOOP_PAGE){const Ru=$u.value??{};lo={outputs:Ru.outputs??{},inputs:Ru.inputs??{}}}}return lo??{refused:"Its page showed nothing: its code answered no outputs."}}const base=Au=>`${Au.serverUrl.replace(/\/+$/,"")}/api/v1/apps/sessions`;async function posted(Au,lo,$u){const Ru=await(Au.fetcher??fetch)(lo,{method:"POST",headers:{"content-type":"application/json",...Au.token?{Authorization:`Bearer ${Au.token}`}:{}},body:JSON.stringify($u)});if(!Ru.ok){let Iu="";try{const Pu=await Ru.json();Iu=typeof Pu.detail=="string"?Pu.detail:""}catch{}throw new Error(Iu||`Its page was refused (${Ru.status}).`)}return Ru.text()}async function openPageSession(Au){const lo=await posted(Au,base(Au),{agent:Au.agentId});for(const $u of streamEvents(lo))if($u.type==="CUSTOM"&&$u.name==="loop.session"){const Ru=$u.value?.uid;if(typeof Ru=="string"&&Ru)return Ru}throw new Error("The runtime opened no session for its page.")}async function runPageIn(Au,lo,$u){try{const Ru=await posted(Au,`${base(Au)}/${encodeURIComponent(lo)}/page`,{inputs:$u});return pageTurnOf(Ru)}catch(Ru){return{refused:Ru instanceof Error?Ru.message:String(Ru)}}}function outputsData(Au){return Object.fromEntries(Object.entries(Au).map(([lo,$u])=>[`/outputs/${lo}`,$u]))}const PAGE_RUN_DELAY_MS=300,NO_TURN$6=signal$2({id:0,status:"idle"}),NO_CONVERSATION$2=signal$2([]);function componentsOnPage(Au){const lo=new Set;for(const $u of Au){const Ru=$u.updateComponents;for(const Iu of Ru?.components??[])lo.add(String(Iu.component))}return[...lo]}function blocksMissing(Au,lo){const $u=new Set(lo),Ru=Au.filter(Iu=>!$u.has(Iu));return Ru.length===0?null:`This page places ${Ru.join(", ")}, which no enabled plugin contributes: ${Ru.length===1?"it is":"they are"} drawn once the plugin that contributes ${Ru.length===1?"it":"them"} is on.`}function AppPage({app:Au,workspace:lo}){const $u=useContributions(LoopChatTurn),Ru=useSignalValue$1($u[0]?.value.turn??NO_TURN$6),Iu=useSignalValue$1($u[0]?.value.conversation??NO_CONVERSATION$2),Pu=reactExports.useMemo(()=>appPageMessages(Au,SURFACE_CATALOG_ID),[Au]),Ou=useContributions(LoopCanvasBlock),Mu=[...new Set(Ou.map(vd=>vd.value.id))].sort(),Du=Mu.join(","),Lu=useOwnComponents(),Bu=reactExports.useMemo(()=>{const vd=blocksMissing(componentsOnPage(Pu),Mu);if(vd)return{problem:vd};try{return{catalog:catalogOfBlocks(Mu,Lu)}}catch(wd){return{problem:wd instanceof Error?wd.message:String(wd)}}},[Pu,Du,Lu]),[ju,Fu]=reactExports.useState(null),zu=pageOf(Au),[Uu,Hu]=reactExports.useState({}),Vu=reactExports.useMemo(()=>({...appPageData(Au,Ru,Iu),...outputsData(Uu)}),[Au,Ru,Iu,Uu]),Gu=useIAMStore(vd=>vd.token)??"",Wu=useChatWords(),Ku=agentServerOf(lo.sandbox,lo.serverUrl),Ju=reactExports.useRef(null);Ju.current=Ku===void 0?null:{serverUrl:Ku,agentId:lo.agentId||Au.id,token:Gu||void 0};const Yu=reactExports.useRef("");Yu.current=Ku===void 0?noRuntimeSaid(lo.sandbox,Wu):"";const Xu=reactExports.useRef(null),ed=reactExports.useRef(!1),td=reactExports.useRef(null),nd=reactExports.useRef(""),od=reactExports.useRef(!0),sd=reactExports.useCallback(vd=>{td.current=vd,!ed.current&&(ed.current=!0,(async()=>{for(;td.current&&od.current;){const wd=td.current;td.current=null;const Td=Ju.current;if(!Td){Fu(Yu.current);continue}try{Xu.current??=openPageSession(Td);const cd=await runPageIn(Td,await Xu.current,wd);if(!od.current)break;"refused"in cd?Fu(cd.refused):(Fu(null),Hu(cd.outputs))}catch(cd){Xu.current=null,od.current&&Fu(cd instanceof Error?cd.message:String(cd))}}ed.current=!1})())},[]),ad=reactExports.useRef(null);reactExports.useEffect(()=>(od.current=!0,()=>{od.current=!1,ad.current?.()}),[]);const pd=reactExports.useCallback(vd=>{if(!zu?.live)return;ad.current?.();let wd;const Td=dd=>{const md=pageInputsOf(Au,dd),ld=JSON.stringify(md);ld!==nd.current&&(clearTimeout(wd),wd=setTimeout(()=>{nd.current=ld,sd(md)},PAGE_RUN_DELAY_MS))},cd=vd.dataModel.subscribe("/inputs",Td);Td(cd.value),ad.current=()=>{clearTimeout(wd),cd.unsubscribe()}},[Au,zu?.live,sd]),gd=reactExports.useRef(lo);gd.current=lo;const xd=reactExports.useRef(""),yd=reactExports.useCallback((vd,wd)=>{const Td=appPageAction(Au,{name:vd.name,context:vd.context??{}},dd=>wd?.dataModel.get(dd),xd.current),cd=gd.current.viewControls;if("refused"in Td){Fu(Td.refused);return}if(Fu(null),"runPage"in Td)sd(Td.runPage);else if("stop"in Td)cd.stop?.();else if("newChat"in Td)cd.newChat?.();else{if(cd.send){const dd=cd.send(Td.send,{loop:Td.loop});if(dd){Fu(dd);return}}else if(Td.loop.files){Fu("The conversation is not ready for a file yet: try again.");return}else gd.current.prompts.submit(Td.send);xd.current=Td.inputs;for(const dd of Td.clear)wd?.dataModel.set(dd,"")}},[Au,sd]);return jsxRuntimeExports.jsx(Box,{"data-testid":"app-page",height:"100%",minHeight:0,overflow:"auto",p:3,children:"problem"in Bu?jsxRuntimeExports.jsx(Box,{role:"status",color:"fg.muted",fontSize:1,children:Bu.problem}):jsxRuntimeExports.jsx(InlineSurface,{messages:Pu,data:Vu,onAction:yd,validationError:ju,catalog:Bu.catalog,...zu?{onSurface:pd}:{}},Du)})}const APP_PAGE_PLUGIN_NAME="@datalayer/loop-plugin-app-page";function defineAppPagePlugin(Au){function lo({workspace:Ru}){return jsxRuntimeExports.jsx(AppPage,{app:Au,workspace:Ru})}return{name:`${APP_PAGE_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: its page`,description:`The page of ${Au.name}, drawn beside its conversation.`,octicon:"browser",emoji:Au.emoji||void 0,contributes:[contribution(LoopEditorView,{surfaceId:APP_PAGE_SURFACE,title:Au.name,icon:BrowserIcon,order:-10,load:async()=>({default:lo})},{id:APP_PAGE_SURFACE,order:-10})]}}const APP_HOST_PAGE_VIEW="app-page";function defineAppHostPagePlugin(Au,lo){function $u({workspace:Iu}){return jsxRuntimeExports.jsx(lo,{app:Au,workspace:Iu})}return{name:`${APP_PAGE_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: its page`,description:`The page of ${Au.name}, drawn by its host.`,octicon:"browser",emoji:Au.emoji||void 0,contributes:[contribution(LoopViewType,{viewType:APP_HOST_PAGE_VIEW,title:Au.name,icon:BrowserIcon,order:-10,load:async()=>({default:$u})},{id:APP_HOST_PAGE_VIEW,order:-10})]}}const canvasBlocksPluginName=Au=>`@datalayer/loop-plugin-ui-${Au}`;function uiPluginBlocks(Au){return{name:canvasBlocksPluginName(Au.id),displayName:Au.name,description:`The blocks of ${Au.name} on the Canvas: ${Au.components.map(lo=>lo.name).join(", ")}.`,octicon:"apps",contributes:Au.components.map(lo=>contribution(LoopCanvasBlock,{id:lo.id,ui:Au.id,component:lo},{id:lo.id}))}}const CANVAS_BLOCK_PLUGINS=listUI().filter(Au=>Au.components.length>0).map(uiPluginBlocks),MANAGER_PLUGIN_NAME="@datalayer/reactor-manager",MANAGER_ACTIONS_SLOT="manager-actions",ManagerPluginSource=defineContributionPoint("manager.pluginSource");function usePluginRows(Au,lo){const $u=useReactorPlatform(),Ru=reactExports.useSyncExternalStore($u.subscribe,()=>$u.getRevision());return reactExports.useMemo(()=>$u.listPlugins().filter(Iu=>!lo.has(Iu)).map(Iu=>{const Pu=$u.getManifest(Iu);return{name:Iu,displayName:Pu?.displayName??Iu,description:Pu?.description,emoji:Pu?.emoji,version:Pu?.version,enabled:$u.isEnabled(Iu),disabledBy:Pu?.disabledBy,changeable:!Au.has(Iu),details:[{label:"Delivered by",values:Pu?.extension?[Pu.extension]:[]},{label:"Contributes to",values:Pu?.contributesTo??[]},{label:"Offers contribution points",values:Pu?.contributionPoints??[]},{label:"Requires backend plugins",values:Pu?.requiredBackendPlugins??[]},{label:"Uses if available",values:Pu?.optionalBackendPlugins??[]},{label:"Activates on",values:Pu?.activationEvents??[]}]}}),[$u,Ru,Au,lo])}function pluginMatches(Au,lo){if(!lo)return!0;const $u=lo.trim().toLowerCase();return[Au.name,Au.displayName,Au.description??""].join(" ").toLowerCase().includes($u)}const PluginHoverContext=reactExports.createContext(null);function usePluginHoverControl(){const[Au,lo]=reactExports.useState(null),$u=reactExports.useRef(void 0);return reactExports.useEffect(()=>()=>clearTimeout($u.current),[]),reactExports.useMemo(()=>({openName:Au,show:Ru=>{clearTimeout($u.current),lo(Ru)},hide:()=>{clearTimeout($u.current),$u.current=setTimeout(()=>lo(null),200)}}),[Au])}function useHoverControl(){const Au=reactExports.useContext(PluginHoverContext),lo=usePluginHoverControl();return Au??lo}function PluginDetails({row:Au}){const lo=(Au.details??[]).filter($u=>$u.values.length>0);return jsxRuntimeExports.jsxs(Box,{sx:{p:3,maxWidth:360,display:"grid",gap:2},children:[jsxRuntimeExports.jsxs(Box,{sx:{display:"flex",alignItems:"center",gap:2},children:[Au.emoji?jsxRuntimeExports.jsx(Text$3,{"aria-hidden":!0,children:Au.emoji}):null,jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold"},children:Au.displayName}),Au.version?jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:["v",Au.version]}):null]}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted",wordBreak:"break-all"},children:Au.name}),Au.description?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0},children:Au.description}):null,lo.map($u=>jsxRuntimeExports.jsxs(Box,{sx:{display:"grid",gap:1},children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,fontWeight:"semibold"},children:$u.label}),$u.values.map(Ru=>jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted",wordBreak:"break-all"},children:Ru},Ru))]},$u.label)),Au.disabledBy==="dependency"?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"attention.fg"},children:"Off because something it depends on is off. It comes back when that does."}):null,Au.changeable?null:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"attention.fg"},children:"This one cannot be switched off."})]})}const OVERLAY_TAKES_NO_FOCUS={preventFocusOnOpen:!0,sx:{pointerEvents:"none"},returnFocusRef:{current:null}};function PluginRowView({row:Au,size:lo,onToggle:$u}){const Ru=`plugin-name-${Au.name.replace(/[^a-zA-Z0-9]+/g,"-")}`,Iu=useHoverControl(),Pu=Iu.openName===Au.name,Ou=()=>Iu.show(Au.name),Mu=()=>Iu.hide();return jsxRuntimeExports.jsx(AnchoredOverlay,{open:Pu,onOpen:Ou,onClose:Mu,focusZoneSettings:{disabled:!0},focusTrapSettings:{disabled:!0},overlayProps:OVERLAY_TAKES_NO_FOCUS,side:"outside-right",renderAnchor:Du=>jsxRuntimeExports.jsxs(Box,{...Du,onMouseEnter:Ou,onMouseLeave:Mu,onFocus:Ou,onBlur:Mu,sx:{display:"flex",alignItems:"flex-start",gap:2,py:2,borderBottom:"1px solid",borderColor:"border.muted"},children:[jsxRuntimeExports.jsxs(Box,{sx:{minWidth:0,flex:1},children:[jsxRuntimeExports.jsxs(Box,{sx:{display:"flex",alignItems:"center",gap:1},children:[Au.emoji?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1},"aria-hidden":!0,children:Au.emoji}):null,jsxRuntimeExports.jsx(Text$3,{id:Ru,sx:{fontSize:1,fontWeight:"semibold",minWidth:0},children:jsxRuntimeExports.jsx(Truncate,{title:Au.name,maxWidth:"100%",inline:!0,children:Au.displayName})})]}),Au.description?jsxRuntimeExports.jsx(Text$3,{sx:{display:"block",fontSize:0,color:"fg.muted"},children:jsxRuntimeExports.jsx(Truncate,{title:Au.description,maxWidth:"100%",inline:!0,children:Au.description})}):null]}),jsxRuntimeExports.jsx(ToggleSwitch,{size:lo,checked:Au.enabled,disabled:!Au.changeable||Au.disabledBy==="dependency","aria-labelledby":Ru,onClick:()=>{Au.changeable&&Au.disabledBy!=="dependency"&&$u(Au.name,!Au.enabled)}})]}),children:jsxRuntimeExports.jsx(PluginDetails,{row:Au})})}function PluginList({plugins:Au,query:lo="",switchSize:$u="small",onToggle:Ru,emptyMessage:Iu}){const Pu=reactExports.useMemo(()=>Au.filter(Ou=>pluginMatches(Ou,lo)),[Au,lo]);return Pu.length===0?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:Iu??`No plugin matches “${lo}”.`}):jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Pu.map(Ou=>jsxRuntimeExports.jsx(PluginRowView,{row:Ou,size:$u,onToggle:Ru},Ou.name))})}function PluginsManagerView({protectedPlugins:Au,hiddenPlugins:lo,switchSize:$u,width:Ru,...Iu}){const Pu=useReactorPlatform(),Ou=Pu.getConfig(MANAGER_PLUGIN_NAME)??{},Mu=reactExports.useMemo(()=>new Set(Au??Ou.protected??[MANAGER_PLUGIN_NAME]),[Au,Ou.protected]),Du=reactExports.useMemo(()=>new Set(lo??Ou.hidden??[]),[lo,Ou.hidden]),Lu=usePluginHoverControl(),Bu=usePluginRows(Mu,Du),[ju,Fu]=reactExports.useState(""),zu=$u??Ou.switchSize??"small",Uu=useContributions(ManagerPluginSource),Hu=reactExports.useMemo(()=>[...Uu].map(Vu=>Vu.value).sort((Vu,Gu)=>(Vu.order??100)-(Gu.order??100)),[Uu]);return jsxRuntimeExports.jsx(PluginHoverContext.Provider,{value:Lu,children:jsxRuntimeExports.jsxs(Box,{sx:{display:"flex",flexDirection:"column",gap:3,width:Ru??Ou.width??"100%",maxWidth:"100%",minWidth:0},children:[jsxRuntimeExports.jsx(ReactorSlot,{slot:MANAGER_ACTIONS_SLOT,props:Iu}),jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{as:"h2",sx:{fontSize:1,fontWeight:"semibold",display:"block",mb:2},children:Ou.title??"Plugins"}),jsxRuntimeExports.jsx(TextInput$1,{leadingVisual:SearchIcon,value:ju,onChange:Vu=>Fu(Vu.target.value),"aria-label":"Filter plugins",placeholder:"Filter…",block:!0,size:"small"})]}),jsxRuntimeExports.jsx(Box,{children:jsxRuntimeExports.jsx(PluginList,{plugins:Bu,query:ju,switchSize:zu,onToggle:(Vu,Gu)=>Gu?Pu.enable(Vu):Pu.disable(Vu)})}),Hu.map(Vu=>jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{as:"h3",sx:{fontSize:1,fontWeight:"semibold",display:"block",mb:2},children:Vu.title}),jsxRuntimeExports.jsx(Vu.Component,{query:ju,switchSize:zu})]},Vu.title))]})})}const PLUGINS_PANEL_PLUGIN_NAME="@datalayer/loop-plugin-plugins-panel",SIDEBAR_WIDTH=420,REACTOR_GRAPH_PLUGIN_NAME="@datalayer/reactor-graph",PluginsPanelPlugin={name:PLUGINS_PANEL_PLUGIN_NAME,displayName:"Plugins panel",description:"Switch plugins on and off while the workspace runs.",octicon:"plug",emoji:"🔌",build:()=>({components:[{id:"plugins-panel",slot:LoopSlots.sidebar,order:900,Component:({workspace:Au})=>jsxRuntimeExports.jsx(PluginsManagerView,{protectedPlugins:[PLUGINS_PANEL_PLUGIN_NAME],hiddenPlugins:[REACTOR_GRAPH_PLUGIN_NAME],width:SIDEBAR_WIDTH,workspace:Au})}]})};function ViewSwitcher({views:Au,workspace:lo,compact:$u=!1}){return Au.length<2?null:jsxRuntimeExports.jsx(Box,{role:"tablist","aria-label":"Workspace views",display:"inline-flex",alignItems:"center",bg:"neutral.muted",borderRadius:"6px",p:"2px",gap:"1px",children:Au.map(Ru=>{const Iu=Ru.value,Pu=canOpenView(Iu,lo),Ou=lo.activeViewType===Iu.viewType,Mu=Iu.icon,Du=Pu?Iu.title:`${Iu.title} — ${Iu.unavailableReason?.(lo)??"unavailable"}`;return jsxRuntimeExports.jsx(Tooltip,{text:Du,direction:"n",children:jsxRuntimeExports.jsxs(Box,{as:"button",role:"tab","aria-selected":Ou,"aria-disabled":!Pu,onClick:()=>Pu&&lo.setActiveViewType(Iu.viewType),display:"inline-flex",alignItems:"center",gap:1,border:"none",borderRadius:"5px",px:2,py:"4px",fontSize:0,cursor:Pu?"pointer":"not-allowed",opacity:Pu?1:.5,bg:Ou?"canvas.default":"transparent",color:Ou?"fg.default":"fg.muted",boxShadow:Ou?"shadow.small":"none",children:[Mu?jsxRuntimeExports.jsx(Mu,{size:14}):null,$u&&Mu?null:Iu.title]})},Iu.viewType)})})}const paneOpenKeyframes=Au=>Au==="left"?"loopPaneOpenLeft":"loopPaneOpenRight",paneOpenAnimation=Au=>`${paneOpenKeyframes(Au)} var(--theme-motion-pane, 0ms) var(--theme-motion-easing, ease) both`;function paneOpening(Au){const lo="12px";return{animation:paneOpenAnimation(Au),[`@keyframes ${paneOpenKeyframes(Au)}`]:{from:{opacity:0,transform:`translateX(${lo})`},to:{opacity:1,transform:"none"}},"@media (prefers-reduced-motion: reduce)":{animation:"none"}}}function railItemsOf(Au){return Au.map(lo=>({id:lo.id,label:lo.rail?.label??lo.id,icon:lo.rail?.icon??SidebarExpandIcon}))}function railChoiceAfter(Au,lo){return Au===lo?null:lo}const RAIL_WIDTH=48;function SidebarRail({components:Au,props:lo,width:$u}){const Ru=railItemsOf(Au),[Iu,Pu]=reactExports.useState(Ru[0]?.id??null),Ou=Ru.some(Mu=>Mu.id===Iu)?Iu:null;return jsxRuntimeExports.jsxs(Box,{as:"aside","data-loop-rail-sidebar":"",flex:"0 0 auto",display:"flex",minHeight:0,children:[jsxRuntimeExports.jsx(Box,{"data-loop-rail-panel":Ou??void 0,display:Ou?"block":"none",width:`${$u}px`,minWidth:0,borderLeft:"var(--theme-hairline, 1px) solid",borderColor:"border.default",overflowY:"auto",px:3,py:3,children:Au.map(Mu=>{const{Component:Du}=Mu,Lu=Mu.id===Ou;return jsxRuntimeExports.jsx(Box,{id:`loop-rail-panel-${Mu.id}`,role:"region","aria-label":railItemsOf([Mu])[0].label,hidden:!Lu,sx:Lu?paneOpening("right"):void 0,children:jsxRuntimeExports.jsx(Du,{...lo})},Mu.id)})}),jsxRuntimeExports.jsx(Box,{as:"nav","aria-label":"Panels",width:`${RAIL_WIDTH}px`,flex:`0 0 ${RAIL_WIDTH}px`,display:"flex",flexDirection:"column",alignItems:"center",gap:1,py:2,borderLeft:"var(--theme-hairline, 1px) solid",borderColor:"border.default",children:Ru.map(Mu=>{const Du=Mu.icon,Lu=Mu.id===Ou;return jsxRuntimeExports.jsx(Box,{as:"button",type:"button","data-loop-rail-item":Mu.id,"aria-label":Mu.label,title:Mu.label,"aria-pressed":Lu,"aria-controls":`loop-rail-panel-${Mu.id}`,onClick:()=>Pu(railChoiceAfter(Ou,Mu.id)),width:32,height:32,display:"inline-flex",alignItems:"center",justifyContent:"center",p:0,border:"none",borderRadius:2,cursor:"pointer",color:Lu?"fg.default":"fg.muted",bg:Lu?"neutral.muted":"transparent",hover:{color:"fg.default",bg:"neutral.subtle"},focusVisible:{outline:"2px solid",outlineColor:"var(--focus-outlineColor, #0969da)",outlineOffset:"1px"},children:jsxRuntimeExports.jsx(Du,{size:16})},Mu.id)})})]})}function buildLoopReactor(Au){return buildReactorFromPlugins(Au)}function LoopWorkspace(Au){const{serverUrl:lo,agentId:$u,conversationId:Ru,model:Iu,sandbox:Pu={state:"idle"},extensions:Ou=[],reactor:Mu,manageReactor:Du=!0,initialViewType:Lu,onSend:Bu,layout:ju="page",showViewSelector:Fu=!0,showHeader:zu=!0,chatHeaderActions:Uu,chatViewModes:Hu,headerActions:Vu,headerContainer:Gu,sidebarRail:Wu=!1}=Au,Ku=reactExports.useMemo(()=>Mu??buildLoopReactor(Ou),[Mu]);return useReactor(Ku,{autoStart:Du}),jsxRuntimeExports.jsx(WorkspaceBody,{serverUrl:lo,agentId:$u,conversationId:Ru,model:Iu,initialSandbox:Pu,initialViewType:Lu,onSend:Bu,layout:ju,showViewSelector:Fu,showHeader:zu,chatHeaderActions:Uu,chatViewModes:Hu,headerActions:Vu,headerContainer:Gu,sidebarRail:Wu})}function WorkspaceBody({serverUrl:Au,agentId:lo,conversationId:$u,model:Ru,initialSandbox:Iu,initialViewType:Pu,onSend:Ou,layout:Mu="page",showViewSelector:Du=!0,showHeader:Lu=!0,chatHeaderActions:Bu,chatViewModes:ju,headerActions:Fu,headerContainer:zu,sidebarRail:Uu=!1}){const[Hu,Vu]=reactExports.useState(lo),Gu=reactExports.useRef(loopSurfaceId($u??`session-${Date.now().toString(36)}`));reactExports.useEffect(()=>{Vu(lo)},[lo]);const[Wu,Ku]=reactExports.useState(Pu??""),[Ju,Yu]=reactExports.useState(Iu),[Xu]=reactExports.useState(createPromptChannel),[ed,td]=reactExports.useState({}),nd=reactExports.useCallback(cd=>{td(cd??{})},[]),od=useContributions(LoopViewType),sd=useContributions(LoopCommand),ad=useSlotComponents(LoopSlots.sidebar),pd=reactExports.useRef(sd),gd=reactExports.useRef(null),xd=Mu==="panel",yd=reactExports.useCallback(async cd=>{const dd=parseCommand(cd);if(!dd)return Ou?.(cd,gd.current),Xu.submit(cd)||Ou?{handled:!0}:{handled:!1,reason:"Nothing is listening for prompts in this view yet."};const md=pd.current.find(hd=>hd.value.name===dd.name||(hd.value.aliases??[]).includes(dd.name));if(!md)return{handled:!1,command:dd.name,reason:`Unknown command: /${dd.name}. Type /help to see what there is.`};const ld=await md.value.run({workspace:gd.current,argv:dd.argv});return ld?.prompt&&(Ou?.(ld.prompt,gd.current),Xu.submit(ld.prompt)),{handled:!0,command:dd.name,result:ld??void 0}},[Ou,Xu]),vd=reactExports.useMemo(()=>({serverUrl:Au,agentId:Hu,surfaceId:Gu.current,setAgentId:Vu,conversationId:$u,model:Ru,sandbox:Ju,setSandbox:Yu,activeViewType:Wu,setActiveViewType:Ku,prompts:Xu,submit:yd,viewControls:ed,setViewControls:nd,chatHeaderActions:Bu,chatViewModes:ju}),[Au,Hu,$u,Ru,Ju,Wu,Xu,yd,ed,nd,Bu,ju]);gd.current=vd,pd.current=sd;const wd=reactExports.useMemo(()=>Wu||(od.find(dd=>canOpenView(dd.value,vd))?.value.viewType??""),[Wu,od,vd]);useReactorEvent(wd?onView(wd):void 0);const Td=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Fu,jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.header,props:{workspace:vd}}),Du?jsxRuntimeExports.jsx(ViewSwitcher,{views:od,workspace:vd,compact:xd}):null]});return jsxRuntimeExports.jsxs(Box,{"data-loop-workspace":"",display:"flex",flexDirection:"column",height:"100%",minHeight:0,position:"relative",bg:"canvas.default",color:"fg.default",children:[Lu&&zu?reactDomExports.createPortal(jsxRuntimeExports.jsx(Box,{display:"flex",alignItems:"center",flexWrap:"wrap",gap:2,children:Td}),zu):null,Lu&&zu===void 0?jsxRuntimeExports.jsx(Box,{as:"header",display:"flex",alignItems:"center",justifyContent:xd?"flex-start":"space-between",flexWrap:"wrap",gap:2,px:xd?2:3,py:2,borderBottom:"1px solid",borderColor:"border.default",flex:"0 0 auto",children:Td}):null,jsxRuntimeExports.jsxs(Box,{flex:"1 1 auto",minHeight:0,display:"flex",children:[jsxRuntimeExports.jsx(Box,{flex:"1 1 auto",minWidth:0,minHeight:0,position:"relative",children:jsxRuntimeExports.jsx(ReactorViewHost,{point:LoopViewType,active:wd,props:{viewType:wd,workspace:vd},fallback:jsxRuntimeExports.jsx(Centered,{children:"Loading…"}),empty:jsxRuntimeExports.jsx(Centered,{children:"No view is available yet."}),errorFallback:cd=>jsxRuntimeExports.jsxs(Centered,{children:["This view failed to load: ",cd.message]})})}),ad.length>0&&Uu&&!xd?jsxRuntimeExports.jsx(SidebarRail,{components:ad,props:{workspace:vd},width:SIDEBAR_WIDTH}):ad.length>0?jsxRuntimeExports.jsx(Box,{as:"aside",flex:"0 0 auto",width:xd?"100%":`${SIDEBAR_WIDTH}px`,minWidth:0,borderLeft:xd?"none":"1px solid",borderTop:xd?"1px solid":"none",borderColor:"border.default",bg:"canvas.subtle",overflowY:"auto",px:3,py:3,children:jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.sidebar,props:{workspace:vd}})}):null]}),jsxRuntimeExports.jsxs(Box,{flex:"0 0 auto",children:[jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.footer,props:{workspace:vd}}),jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.status,props:{workspace:vd}})]}),jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.root,props:{workspace:vd}})]})}function Centered({children:Au}){return jsxRuntimeExports.jsx(Box,{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"fg.muted",fontSize:1,px:3,textAlign:"center",children:Au})}function resolveTopOffset(Au){if(typeof Au=="number")return Au;if(!Au||typeof document>"u")return 0;const lo=document.querySelector(Au);return lo?Math.max(0,Math.round(lo.getBoundingClientRect().bottom)):0}function fullScreenNode(Au){return Au?.closest("[data-loop-fullscreen-root]")??Au?.closest("[data-loop-workspace]")??Au}function useWorkspaceFullScreen(Au,lo={}){const{forceOverlay:$u=!1,paintOverlay:Ru=!1,topOffset:Iu=0}=lo,[Pu,Ou]=reactExports.useState(!1),Mu=reactExports.useRef(!1);reactExports.useEffect(()=>{const ju=()=>{if(!Mu.current)return;const Fu=!!document.fullscreenElement&&!!Au.current&&document.fullscreenElement.contains(Au.current);Ou(Fu),Fu||(Mu.current=!1)};return document.addEventListener("fullscreenchange",ju),()=>document.removeEventListener("fullscreenchange",ju)},[Au]);const Du=reactExports.useCallback(()=>{const ju=fullScreenNode(Au.current);if(Pu){Mu.current&&document.fullscreenElement?document.exitFullscreen():Ou(!1);return}if($u||Ru||!ju?.requestFullscreen){Ou(!0);return}Mu.current=!0,ju.requestFullscreen().then(()=>Ou(!0),()=>{Mu.current=!1,Ou(!0)})},[Au,Pu,$u,Ru]),[Lu,Bu]=reactExports.useState(0);return reactExports.useEffect(()=>{if(!Pu||Mu.current){Bu(0);return}const ju=()=>Bu(resolveTopOffset(Iu));return ju(),window.addEventListener("resize",ju),()=>window.removeEventListener("resize",ju)},[Pu,Iu]),reactExports.useEffect(()=>{if(!Ru||!Pu||Mu.current)return;const ju=fullScreenNode(Au.current);if(!ju)return;const Fu=ju.getAttribute("style");return ju.style.position="fixed",ju.style.top=`${Lu}px`,ju.style.right="0",ju.style.bottom="0",ju.style.left="0",ju.style.height="auto",ju.style.zIndex="1000",()=>{Fu===null?ju.removeAttribute("style"):ju.setAttribute("style",Fu)}},[Ru,Pu,Au,Lu]),reactExports.useEffect(()=>{if(!Pu||Mu.current)return;const ju=Fu=>{Fu.key==="Escape"&&!Fu.defaultPrevented&&Ou(!1)};return window.addEventListener("keydown",ju),()=>window.removeEventListener("keydown",ju)},[Pu]),{fullScreen:Pu,usingApi:Mu,toggle:Du,topOffsetPx:Lu}}function messageText(Au){const lo=Au.content;return typeof lo=="string"?lo:lo.map($u=>typeof $u=="string"?$u:$u.text??"").join("")}const isToolCall=Au=>Au.type==="tool-call";function conversationOf(Au){const lo=[];for(const $u of Au){if(isToolCall($u)){lo.push({role:"tool",name:$u.toolName,args:$u.args??{},...$u.result===void 0?{}:{result:$u.result}});continue}if($u.role!=="user"&&$u.role!=="assistant")continue;const Ru=messageText($u);Ru.trim()&&lo.push({role:$u.role,text:Ru})}return lo}const sameConversation=(Au,lo)=>Au.length===lo.length&&Au.every(($u,Ru)=>JSON.stringify($u)===JSON.stringify(lo[Ru])),IDLE={id:0,status:"idle"};function createTurnFeed(){const Au=signal$2(IDLE),lo=signal$2([]),$u=signal$2("idle");return{turn:Au,conversation:lo,presence:$u,setPresence:Ru=>{$u.value!==Ru&&($u.value=Ru)},items:Ru=>{const Iu=conversationOf(Ru);sameConversation(lo.value,Iu)||(lo.value=Iu)},begin:(Ru,Iu)=>{Au.value={id:Au.value.id+1,user:Ru,...Iu?{thread:Iu}:{},status:"thinking",usage:Au.value.usage}},assistant:Ru=>{const Iu=Au.value;Iu.status==="idle"||Iu.assistant===Ru||(Au.value={...Iu,assistant:Ru,status:Iu.status==="done"||Iu.status==="error"?Iu.status:Ru?"streaming":Iu.status})},usage:Ru=>{const Iu=Au.value;Iu.usage!==Ru&&(Au.value={...Iu,usage:Ru})},activity:Ru=>{const Iu=Au.value;Iu.status==="idle"||Iu.activity===Ru||(Au.value={...Iu,activity:Ru})},end:(Ru="done")=>{const Iu=Au.value;Iu.status!=="idle"&&(Au.value={...Iu,status:Ru,activity:void 0})}}}const TURN_WRITERS=Symbol.for("loop.chat.turn.writers");function feedWriters(Au){return{[TURN_WRITERS]:Au}}function turnWritersOf(Au){return Au?.[TURN_WRITERS]}function agentAction(Au,lo){const{prompt:$u,...Ru}=lo;return{...Ru,type:"button",group:"agent",onClick:()=>Au.workspace.prompts.submit($u)}}const CHAT_PLUGIN_NAME="@datalayer/loop-plugin-chat",ChatPlugin={name:CHAT_PLUGIN_NAME,config:{placeholder:"",defaultSurface:"notebook",showSurfaceSelector:!0,hideHeader:!1,headerButtons:{newChat:!1,clear:!1},hidePrompt:!1,promptPlacement:"bottom",autoFocusPrompt:!0,suggestionLabels:!0,fullScreenTopOffset:0},displayName:"Chat",description:"The conversation, the prompt, and the point editors plug into.",octicon:"comment-discussion",emoji:"💬",contributionPoints:[LoopAgentGate,LoopFrontendTool,LoopChatComposer,LoopChatHeader,LoopChatSuggestion,LoopChatExtras,LoopChatTurn],build:Au=>{const lo=createTurnFeed();return Au.contribute(LoopChatTurn,{id:"chat-turn",turn:lo.turn,conversation:lo.conversation,presence:lo.presence,...feedWriters(lo)},{id:"chat-turn"}),{}},contributes:[contribution(LoopViewType,{viewType:"chat",title:"Chat",icon:CommentDiscussionIcon,order:0,load:()=>__vitePreload(()=>import("./chunks/ChatView-BjZ993Ch.js"),[],import.meta.url)},{id:"chat",order:0}),contribution(LoopCommand,{name:"chat",description:"Show the conversation",group:"Session",keybinding:"Mod+Alt+K",run:async({workspace:Au})=>{Au.setActiveViewType("chat")}},{id:"chat"}),contribution(LoopNotebookToolbarItem,{items:Au=>[agentAction(Au,{key:"loop-compact",ariaLabel:"Compact this notebook",title:"Ask @NotebookCompactor to shorten it without changing results",icon:FoldIcon,order:200,prompt:"@NotebookCompactor compact this notebook without changing what it computes."}),agentAction(Au,{key:"loop-reproduce",ariaLabel:"Check reproducibility",title:"Ask @NotebookReproducer to run it on a fresh sandbox",icon:SyncIcon,order:201,prompt:"@NotebookReproducer run this notebook top to bottom on a fresh sandbox and report what does not reproduce."})]},{id:"agent-actions",order:200}),contribution(LoopDocumentToolbarItem,{items:Au=>[agentAction(Au,{key:"loop-summarise",ariaLabel:"Summarise this document",title:"Ask the agent for a summary of what this document says",icon:SparkleFillIcon,order:200,prompt:"Summarise this document in a short paragraph."})]},{id:"agent-actions",order:200})]};function WorkspaceFullScreenAction(){const Au=reactExports.useRef(null),$u=useReactorPlatform().getConfig(CHAT_PLUGIN_NAME)?.fullScreenTopOffset??0,{fullScreen:Ru,toggle:Iu}=useWorkspaceFullScreen(Au,{paintOverlay:!!$u,topOffset:$u});return jsxRuntimeExports.jsx(IconButton,{ref:Au,icon:Ru?ScreenNormalIcon:ScreenFullIcon,"aria-label":Ru?"Exit full screen":"Enter full screen",variant:"invisible",size:"small",sx:{order:2},onClick:Iu})}const THEME_PLUGIN_NAME="@datalayer/primer-theme",TOGGLE_COLOR_MODE_COMMAND="theme.toggleColorMode",ThemePlugin={name:THEME_PLUGIN_NAME,displayName:"Theme",description:"Keeps Primer portals in the application’s color mode, and toggles it.",octicon:"sun",emoji:"🌗",commands:[{id:TOGGLE_COLOR_MODE_COMMAND,name:"Toggle the color mode",description:"Switch between light and dark",emoji:"🌗",category:"Appearance",keybinding:"Mod+Alt+C",execute:()=>{const Au=useThemeStore.getState(),lo=Au.colorMode==="auto"?typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light":Au.colorMode;Au.setColorMode(lo==="dark"?"light":"dark")}}],register:()=>{if(typeof document>"u")return;setupPrimerPortals(useThemeStore.getState().colorMode);const Au=useThemeStore.subscribe((Ru,Iu)=>{Ru.colorMode!==Iu.colorMode&&setupPrimerPortals(Ru.colorMode)}),lo=window.matchMedia("(prefers-color-scheme: dark)"),$u=()=>{useThemeStore.getState().colorMode==="auto"&&setupPrimerPortals("auto")};return lo.addEventListener("change",$u),()=>{Au(),lo.removeEventListener("change",$u)}}},pageLayoutPanelOpen=signal$2(!1),pageLayoutSheet=signal$2("page"),pageLayoutActivity=signal$2(void 0);function openPagePanel(){pageLayoutPanelOpen.value=!0}const PAGE_SHEET_WIDTH=920,PAGE_PANEL_WIDTH=400,PAGE_SIZE_FORMATS={letter:{width:816,height:1056},a4:{width:794,height:1123}};function resolvePageSize(Au,lo=PAGE_SHEET_WIDTH){const $u=Au?.format&&Au.format!=="free"?PAGE_SIZE_FORMATS[Au.format]:void 0;return{width:Au?.width??$u?.width??lo,height:Au?.height??$u?.height}}const CANVAS_PX=[2,3,4];function ActivityLine({label:Au}){return jsxRuntimeExports.jsxs(Box$1,{"data-page-activity":"",role:"status",sx:{position:"sticky",top:0,zIndex:2,alignSelf:"flex-start",display:"inline-flex",alignItems:"center",gap:2,px:2,py:"4px",borderRadius:"999px",border:"1px solid",borderColor:"accent.muted",bg:"accent.subtle",color:"accent.fg",fontSize:0,fontWeight:"semibold",whiteSpace:"nowrap",boxShadow:"0 4px 12px -6px rgba(0,0,0,0.3)"},children:[jsxRuntimeExports.jsx(Box$1,{as:"span","aria-hidden":"true",sx:{width:7,height:7,borderRadius:"50%",bg:"accent.fg",animation:"page-activity-dot 1.1s ease-in-out infinite","@keyframes page-activity-dot":{"0%, 100%":{opacity:1},"50%":{opacity:.3}}}}),jsxRuntimeExports.jsx(Text$3,{children:Au})]})}function panelOpening(Au){const lo=Au==="left"?"pagePanelOpenLeft":"pagePanelOpenRight";return{animation:`${lo} var(--theme-motion-pane, 0ms) var(--theme-motion-easing, ease) both`,[`@keyframes ${lo}`]:{from:{opacity:0,transform:`translateX(${Au==="left"?"-12px":"12px"})`},to:{opacity:1,transform:"none"}},"@media (prefers-reduced-motion: reduce)":{animation:"none"}}}function PageLayout({page:Au,hasPage:lo=Au!=null,panel:$u,band:Ru,chips:Iu,picker:Pu,transient:Ou,activity:Mu,bandMode:Du="docked",panelMode:Lu="docked",panelSide:Bu="right",sheetWidth:ju=PAGE_SHEET_WIDTH,pageSize:Fu,panelWidth:zu=PAGE_PANEL_WIDTH}){const Uu=Du==="panel",Hu=Ru!=null,{width:Vu,height:Gu}=resolvePageSize(Fu,ju),Ku=useSignalValue$1(pageLayoutPanelOpen)||Uu&&Hu,Ju=useSignalValue$1(pageLayoutActivity),Yu=Mu??Ju,Xu=lo?"page":"panel";return reactExports.useEffect(()=>{pageLayoutSheet.value=Xu},[Xu]),jsxRuntimeExports.jsxs(Box$1,{"data-page-layout":"",sx:{position:"relative",flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column"},children:[Pu,jsxRuntimeExports.jsxs(Box$1,{sx:{flex:"1 1 auto",minHeight:0,display:"flex",bg:"canvas.inset"},children:[jsxRuntimeExports.jsxs(Box$1,{sx:{flex:"1 1 auto",minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:[Ru&&Du==="docked"?jsxRuntimeExports.jsx(Box$1,{"data-page-band":"","data-page-prompt-dock":"",sx:{flex:"0 0 auto",display:"flex",justifyContent:"center",px:CANVAS_PX,bg:"canvas.subtle",borderBottom:"1px solid",borderColor:"border.default"},children:jsxRuntimeExports.jsx(Box$1,{sx:{width:"100%",maxWidth:Vu,minWidth:0},children:Ru})}):null,jsxRuntimeExports.jsxs(Box$1,{"data-page-canvas":"",sx:{flex:"1 1 auto",minWidth:0,minHeight:0,overflowY:lo?"auto":"hidden",overflowX:"hidden",display:"flex",flexDirection:"column",alignItems:"center",pt:3,pb:6,px:CANVAS_PX},children:[Ru&&Iu&&!Uu?jsxRuntimeExports.jsx(Box$1,{sx:{width:"100%",maxWidth:Vu,mb:3,display:"flex",justifyContent:"center","& > *":{justifyContent:"center"}},children:Iu}):null,Yu?jsxRuntimeExports.jsx(Box$1,{sx:{width:"100%",maxWidth:Vu,display:"flex",justifyContent:"flex-end",mb:2},children:jsxRuntimeExports.jsx(ActivityLine,{label:Yu})}):null,jsxRuntimeExports.jsx(Sheet,{"data-page-sheet":"",sx:{width:"100%",maxWidth:Vu,flex:lo?"1 0 auto":"1 1 auto",px:lo?[3,4,"56px"]:[2,3,4],py:lo?[3,4,4]:2,position:"relative",display:"flex",minHeight:lo?Gu??480:0,"& > *":{flex:"1 1 auto",minWidth:0}},children:lo?Au:$u}),lo||!Au?null:jsxRuntimeExports.jsx(Box$1,{"aria-hidden":"true",sx:{position:"absolute",inset:0,visibility:"hidden",pointerEvents:"none",zIndex:-1,display:"flex"},children:Au})]})]}),!lo||!$u?null:jsxRuntimeExports.jsxs(Box$1,{"data-page-panel":Ku?"":void 0,"data-page-panel-mode":Lu,"aria-hidden":Ku?void 0:"true",sx:{minWidth:0,minHeight:0,display:"flex",flexDirection:"column",bg:"canvas.default",borderColor:"border.default",...Ku?Lu==="docked"?{flex:`0 0 ${zu}px`,maxWidth:"45%",order:Bu==="left"?-1:void 0,[Bu==="left"?"borderRight":"borderLeft"]:"1px solid",zIndex:1}:Lu==="overlay"?{position:"absolute",top:0,bottom:0,[Bu]:0,width:zu,maxWidth:"85%",[Bu==="left"?"borderRight":"borderLeft"]:"1px solid",boxShadow:"shadow.large",zIndex:5}:{position:"absolute",[Bu]:16,bottom:16,width:zu,maxWidth:"calc(100% - 32px)",height:"min(70%, 560px)",border:"1px solid",borderRadius:2,boxShadow:"shadow.large",overflow:"hidden",zIndex:5}:{position:"absolute",inset:0,visibility:"hidden",pointerEvents:"none",overflow:"visible"}},children:[jsxRuntimeExports.jsx(Box$1,{sx:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column","& > *":{flex:"1 1 auto",minHeight:0},...Ku?panelOpening(Bu):null},children:$u}),Hu&&Du!=="docked"?jsxRuntimeExports.jsxs(Box$1,{"data-page-panel-band":Uu?"":void 0,sx:Uu?{flex:"0 0 auto",borderTop:"1px solid",borderColor:"border.default",visibility:"visible",pointerEvents:"auto","& > *":{justifyContent:"center"}}:{position:"absolute",inset:0,visibility:"visible",pointerEvents:"none","& > *":{pointerEvents:"auto"}},children:[Uu?Iu:null,Ru]}):null]})]}),Ou]})}function PagePanelToggle({panelName:Au="panel",icon:lo=SidebarExpandIcon,sx:$u}){const Ru=useSignalValue$1(pageLayoutPanelOpen);return useSignalValue$1(pageLayoutSheet)==="panel"?null:jsxRuntimeExports.jsx(IconButton,{icon:lo,size:"small",variant:Ru?"default":"invisible","aria-label":Ru?`Hide the ${Au}`:`Show the ${Au}`,"aria-pressed":Ru,onClick:()=>{Ru?pageLayoutPanelOpen.value=!1:openPagePanel()},sx:{color:Ru?"accent.fg":"fg.muted",...$u}})}const INPUT_PROMPT_PLUGIN_NAME="@datalayer/loop-plugin-input-prompt",LazyComposerView=reactExports.lazy(()=>__vitePreload(()=>import("./chunks/ComposerView-Wa0dy8ex.js"),[],import.meta.url));function ComposerView(Au){return jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(LazyComposerView,{...Au})})}const InputPromptPlugin={name:INPUT_PROMPT_PLUGIN_NAME,config:{},displayName:"Input Prompt",description:"The composer under (or over) the conversation.",octicon:"pencil",emoji:"✏️",contributionPoints:[LoopPromptPanel],contributes:[contribution(LoopChatComposer,{id:"input-prompt",Component:ComposerView},{id:"input-prompt"})]},AGENT_ICONS={agent:ForwardRef$2,beaker:BeakerIcon,bell:BellIcon,book:BookIcon,briefcase:BriefcaseIcon,browser:BrowserIcon,bug:BugIcon,clock:ClockIcon,code:CodeIcon,"comment-discussion":CommentDiscussionIcon,cpu:CpuIcon,"credit-card":CreditCardIcon,database:DatabaseIcon,file:FileIcon,checklist:ChecklistIcon,"code-review":CodeReviewIcon,fold:FoldIcon,"git-branch":GitBranchIcon,globe:GlobeIcon,graph:GraphIcon,heart:HeartIcon,"issue-opened":IssueOpenedIcon,lightbulb:LightBulbIcon,"light-bulb":LightBulbIcon,"list-unordered":ListUnorderedIcon,mail:MailIcon,megaphone:MegaphoneIcon,"mortar-board":MortarBoardIcon,note:NoteIcon,organization:OrganizationIcon,package:PackageIcon,pencil:PencilIcon,people:PeopleIcon,play:PlayIcon,pulse:PulseIcon,rss:RssIcon,search:SearchIcon,"share-2":ShareAndroidIcon,shield:ShieldIcon,"shield-check":ShieldCheckIcon,sliders:SlidersIcon,sun:SunIcon,sync:SyncIcon,table:TableIcon,tag:TagIcon,tasklist:TasklistIcon,telescope:TelescopeIcon,tools:ToolsIcon,"trending-up":GraphIcon,rocket:RocketIcon,zap:ZapIcon};function agentIcon(Au){return(Au?AGENT_ICONS[Au]:void 0)??ForwardRef$2}function useOptionalSandboxService(){return useReactorPlatform().getOutput(AGENTS_PLUGIN_NAME)?.sandbox}function useSandboxService(){const Au=useOptionalSandboxService();if(!Au)throw new Error(`The code sandbox plugin (${AGENTS_PLUGIN_NAME}) is not mounted. A view that needs a sandbox must declare it as a dependency.`);return Au}function SandboxStatusBridge({workspace:Au}){const lo=useOptionalSandboxService(),$u=useSignalValue$1(lo?.snapshot??IDLE_SANDBOX_SNAPSHOT_SIGNAL),Ru=useSignalValue$1(lo?.target??IDLE_SANDBOX_TARGET_SIGNAL),{setSandbox:Iu,agentId:Pu}=Au;return reactExports.useEffect(()=>lo?.connect(Pu),[lo,Pu]),reactExports.useEffect(()=>{lo&&Iu({...$u,target:Ru})},[lo,$u,Ru,Iu]),null}const DatalayerAgentBridge=reactExports.lazy(async()=>({default:(await __vitePreload(()=>import("./chunks/DatalayerAgentBridge-D54Z9BZ3.js"),[],import.meta.url)).DatalayerAgentBridge}));function DatalayerAgentMount(){return jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(DatalayerAgentBridge,{})})}const CREATING_STATUSES=new Set(["creating","starting","launching","connecting","pending","resuming"]),MAX_AGENT_NAME_LENGTH=32,toSandboxStatusUrl=Au=>{const lo=String(Au||"").trim();if(lo)try{const $u=new URL(lo);return $u.pathname=`${$u.pathname.replace(/\/$/,"")}/api`,$u.toString()}catch{const $u=lo.replace(/\/$/,"");return $u.endsWith("/api")?$u:`${$u}/api`}},OVERLAY_WIDTH=360,AgentSummary=({summary:Au,title:lo="Active Agent"})=>{const[$u,Ru]=reactExports.useState(!1),[Iu,Pu]=reactExports.useState(!1),Ou=reactExports.useRef(null),Mu=reactExports.useRef(null),Du=()=>{Mu.current!==null&&(window.clearTimeout(Mu.current),Mu.current=null)},Lu=()=>{Du();const Yu=Ou.current?.getBoundingClientRect();Pu(!!(Yu&&Yu.left+OVERLAY_WIDTH>window.innerWidth)),Ru(!0)},Bu=()=>{Du(),Mu.current=window.setTimeout(()=>{Ru(!1),Mu.current=null},300)};reactExports.useEffect(()=>()=>{Du()},[]);const ju=Au?.baseUrl?(()=>{const Yu=Au.baseUrl.replace(/\/$/,"");return Yu.endsWith("/api/v1")?Yu:`${Yu}/api/v1`})():void 0,Fu=ju?`${ju}/runtime/status`:void 0,zu=toSandboxStatusUrl(Au?.sandboxBaseUrl);if(!Au)return null;const Uu=(Au.status||"").toLowerCase(),Hu=!Au.isReady&&!Au.agentId&&CREATING_STATUSES.has(Uu),Vu=!!Au.error,Gu=!!Au.agentId||Hu,Wu=strip(Au.agentName,MAX_AGENT_NAME_LENGTH),Ku=`${Au.agentName} · ${Au.location}`,Ju=`${Wu} · ${Au.location}`;return jsxRuntimeExports.jsxs(Box,{ref:Ou,position:"relative",onMouseEnter:Lu,onMouseLeave:Bu,children:[jsxRuntimeExports.jsxs(Box,{as:"button",type:"button",title:Ku,px:2,py:"6px",maxWidth:280,minWidth:0,border:"1px solid",borderColor:Vu?"danger.emphasis":"border.default",borderRadius:2,bg:Vu?"danger.subtle":"canvas.default",color:Vu?"danger.fg":"fg.default",fontSize:0,cursor:"default",display:"flex",alignItems:"center",gap:1,children:[Hu&&jsxRuntimeExports.jsx(StyledSpinner,{size:"small",sx:{width:12,height:12}}),Vu&&jsxRuntimeExports.jsx("span",{"aria-hidden":!0,children:"⚠"}),jsxRuntimeExports.jsx(Box,{as:"span",display:"block",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",children:Ju})]}),$u&&jsxRuntimeExports.jsxs(Box,{position:"absolute",top:"calc(100% + 8px)",width:OVERLAY_WIDTH,p:2,border:"1px solid",borderColor:"border.default",borderRadius:2,bg:"canvas.overlay",boxShadow:"shadow.large",zIndex:120,fontSize:0,color:"fg.default",right:Iu?0:void 0,left:Iu?void 0:0,children:[jsxRuntimeExports.jsx(Box,{mb:1,fontWeight:600,children:lo}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Name: ",Au.agentName]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Location: ",Au.location]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Spec: ",Au.specId||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Harness: ",Au.harness||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Variant: ",Au.variant||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Status: ",Hu?"creating":Au.status||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Agent base URL: ",Au.baseUrl||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Code sandbox base URL:"," ",Au.sandboxBaseUrl?jsxRuntimeExports.jsx(Box,{as:"a",href:Au.sandboxBaseUrl,target:"_blank",rel:"noopener noreferrer",color:"accent.fg",textDecoration:"underline",children:Au.sandboxBaseUrl}):"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",display:"flex",alignItems:"center",gap:1,children:["Agent ID:"," ",Au.agentId?Au.agentId:Hu?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(StyledSpinner,{size:"small",sx:{width:12,height:12}}),"Creating…"]}):"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Agent status:"," ",Gu&&Fu?jsxRuntimeExports.jsx(Box,{as:"a",href:Fu,target:"_blank",rel:"noopener noreferrer",color:"accent.fg",textDecoration:"underline",children:Fu}):"n/a"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Code sandbox status:"," ",zu?jsxRuntimeExports.jsx(Box,{as:"a",href:zu,target:"_blank",rel:"noopener noreferrer",color:"accent.fg",textDecoration:"underline",children:zu}):"n/a"]}),Vu&&jsxRuntimeExports.jsxs(Box,{mt:1,p:1,border:"1px solid",borderColor:"danger.muted",borderRadius:2,bg:"danger.subtle",color:"danger.fg",wordBreak:"break-word",children:["Error: ",Au.error]})]})]})},insideJupyterLab=()=>loadJupyterConfig().insideJupyterLab;function collect(Au,lo){const $u=Au?.header?.msg_type,Ru=Au?.content??{};$u==="stream"?(lo.stdout.push(String(Ru.text??"")),lo.outputs.push({output_type:"stream",text:Ru.text})):$u==="execute_result"||$u==="display_data"?lo.outputs.push({output_type:$u,data:Ru.data}):$u==="error"&&(lo.error=`${Ru.ename??"Error"}: ${Ru.evalue??""}`,lo.outputs.push({output_type:"error",ename:Ru.ename,evalue:Ru.evalue,traceback:Ru.traceback}))}function browserSource(){let Au;return{variant:"pyodide",acquire:async()=>{const{createLiteServiceManager:lo,jupyterReactStore:$u,loadJupyterConfig:Ru}=await __vitePreload(async()=>{const{createLiteServiceManager:Pu,jupyterReactStore:Ou,loadJupyterConfig:Mu}=await import("./chunks/index-CyQgE_Es.js").then(Du=>Du.r);return{createLiteServiceManager:Pu,jupyterReactStore:Ou,loadJupyterConfig:Mu}},[],import.meta.url);Au=Au??{baseUrl:libExports$5.PageConfig.getOption("baseUrl"),wsUrl:libExports$5.PageConfig.getOption("wsUrl")},Ru({lite:!0});const Iu=await lo();return $u.getState().setServiceManager(Iu),Iu},release:()=>{Au&&(libExports$5.PageConfig.setOption("baseUrl",Au.baseUrl),libExports$5.PageConfig.setOption("wsUrl",Au.wsUrl),Au=void 0)},owned:!0}}function createBrowserSandboxService(Au=browserSource()){const lo=signal$2(null),$u=signal$2("idle"),Ru=signal$2(null),Iu=computed$1(()=>({state:$u.value,variant:Au.variant,kernelId:lo.value?.kernel_id})),Pu=computed$1(()=>$u.value==="running");let Ou=null,Mu=null,Du=null,Lu=null;async function Bu(){if(Mu)return;$u.value="starting",Ou=await Au.acquire();const ju=await Ou.sessions.startNew({name:"loop",path:"loop.ipynb",type:"notebook",kernel:{name:"python"}});Du=ju.kernel,Mu=ju.kernel,lo.value={variant:Au.variant,sandbox_running:!0,kernel_id:Mu?.id,kernel_name:"python"},$u.value="running"}return{kind:"browser",snapshot:Iu,status:lo,ready:Pu,lastExecution:Ru,serverUrl:"",getServiceManager:()=>Ou,getKernelConnection:()=>Du,report(ju){lo.value=ju},setState(ju){$u.value=ju},connect(){return Lu=Lu??Bu().catch(ju=>{throw $u.value="error",lo.value=null,Lu=null,ju}),()=>{Mu?.shutdown?.(),Mu=null,Du=null,Ou=Au.owned?null:Ou,Au.release?.(),Lu=null,$u.value="idle",lo.value=null}},async execute(ju){const Fu=Date.now();try{if(await(Lu??Bu()),!Mu)throw new Error("The browser kernel did not start");const zu={outputs:[],stdout:[],error:""},Uu=Mu.requestExecute({code:ju});Uu.onIOPub=Vu=>collect(Vu,zu),await Uu.done;const Hu={code:ju,success:!zu.error,stdout:zu.stdout.join(""),error:zu.error||void 0,outputs:zu.outputs,startedAt:Fu,finishedAt:Date.now()};return Ru.value=Hu,Hu}catch(zu){const Uu={code:ju,success:!1,error:zu instanceof Error?zu.message:String(zu),startedAt:Fu,finishedAt:Date.now()};return Ru.value=Uu,Uu}}}}function summarize(Au,lo){if(!Au)return{state:lo};const $u=Au.variant==="jupyter-server"||Au.variant==="datalayer";return{state:!!Au.sandbox_running||$u&&!!Au.jupyter_connected?"running":lo==="running"?"idle":lo,variant:Au.variant,kernelId:Au.kernel_id,jupyterUrl:Au.jupyter_url,jupyterToken:Au.jupyter_token,agentBaseUrl:Au.agent_base_url}}const RECONNECT_BASE_MS=1e3,RECONNECT_MAX_MS=3e4;function createServerSandboxService(Au){const lo=signal$2(null),$u=signal$2("idle"),Ru=signal$2(void 0),Iu=signal$2(null),Pu=computed$1(()=>({...summarize(lo.value,$u.value),errorReason:$u.value==="error"?Ru.value:void 0})),Ou=computed$1(()=>Pu.value.state==="running");return{kind:"server",connect(Mu){if(typeof WebSocket>"u")return()=>{};let Du=null,Lu=null,Bu=0,ju=!1;const Fu=()=>{if(ju)return;const zu=Au.replace(/^http/,"ws"),Uu=Mu?`?agent_id=${encodeURIComponent(Mu)}`:"";Du=new WebSocket(`${zu}/api/v1/configure/sandbox/ws${Uu}`),Du.onopen=()=>{Bu=0},Du.onmessage=Hu=>{try{lo.value=JSON.parse(String(Hu.data))}catch{}},Du.onclose=()=>{if(ju)return;lo.value=null,Bu+=1;const Hu=Math.min(RECONNECT_BASE_MS*2**(Bu-1),RECONNECT_MAX_MS);Lu=setTimeout(Fu,Hu)}};return Fu(),()=>{ju=!0,Lu&&clearTimeout(Lu),Du?.close(),Du=null}},snapshot:Pu,status:lo,ready:Ou,lastExecution:Iu,serverUrl:Au,report(Mu){lo.value=Mu},setState(Mu,Du){$u.value=Mu,Ru.value=Mu==="error"?Du:void 0},async execute(Mu){const Du=Date.now();try{const Lu=await fetch(`${Au}/api/v1/sandbox/execute`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:Mu})}),Bu=Lu.ok?await Lu.json():null,ju={code:Mu,success:Lu.ok&&!Bu?.error,stdout:Bu?.stdout,stderr:Bu?.stderr,error:Lu.ok?Bu?.error:`Execution failed: ${Lu.status}`,outputs:Bu?.outputs,startedAt:Du,finishedAt:Date.now()};return Iu.value=ju,ju}catch(Lu){const Bu={code:Mu,success:!1,error:Lu instanceof Error?Lu.message:String(Lu),startedAt:Du,finishedAt:Date.now()};return Iu.value=Bu,Bu}}}}const ANONYMOUS_JUPYTER_URL="https://prod1.datalayer.run/api/jupyter-server",ANONYMOUS_JUPYTER_TOKEN="60c1661cc408f978c309d04157af55c9588ff9557c9380e4fb50785750703da6",SANDBOX_TARGETS=["browser","local","jupyter","datalayer"];function heldTargetReason(Au,lo){if(Au==="local"&&!lo&&!insideJupyterLab())return"Not offered on the web for now: a local agent and the Jupyter server it starts run beside JupyterLab, not in a page."}const TARGET_SPECS={browser:{label:"Browser",hint:"Python in this page (Pyodide), with the agent loop running here too. Only the model is asked over the network.",hasAgent:!0,noAgentReason:""},local:{label:"Local",hint:"A local agent, with the Jupyter server it starts beside itself.",hasAgent:!0,noAgentReason:"",configure:{variant:"jupyter-server",jupyter_url:"",jupyter_token:""}},jupyter:{label:"Jupyter",hint:"A named Jupyter server: the anonymous one on prod1.datalayer.run.",hasAgent:!1,noAgentReason:"No agent on an anonymous Jupyter server",configure:{variant:"jupyter-server",jupyter_url:ANONYMOUS_JUPYTER_URL,jupyter_token:ANONYMOUS_JUPYTER_TOKEN}},datalayer:{label:"Datalayer",hint:"A Datalayer runtime running the agent this workspace asks for.",hasAgent:!0,noAgentReason:""}};function targetHasAgent(Au){return TARGET_SPECS[Au]?.hasAgent??!1}function targetRunsAgentInPage(Au){return Au==="browser"}function createSwitchableSandboxService({serverUrl:Au,initialTarget:lo="local",kernelSource:$u,localAgent:Ru,blueprint:Iu}){const Pu=signal$2(lo),Ou=createServerSandboxService(Au),Mu=createBrowserSandboxService($u??browserSource()),Du=computed$1(()=>Pu.value==="browser"?Mu:Ou);let Lu=null,Bu;const ju=computed$1(()=>Du.value.snapshot.value),Fu=computed$1(()=>Du.value.status.value),zu=computed$1(()=>Du.value.ready.value),Uu=computed$1(()=>Du.value.lastExecution.value);async function Hu(Wu){if(Wu==="local"){const ed=Iu?.()??Ru?.createPayload;ed&&await Vu(ed)}const Ku=TARGET_SPECS[Wu]?.configure;if(!Ku)return;const Ju=TARGET_SPECS[Wu].label;let Yu;try{Yu=await fetch(`${Au}/api/v1/agents/sandbox/configure`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Ku)})}catch(ed){throw new Error(`${Ju} needs an agent-runtimes server at ${Au}, and nothing answered there. Start one and try again. (${ed instanceof Error?ed.message:String(ed)})`,{cause:ed})}if(!Yu.ok)throw new Error(`The server could not switch to ${Ju} (${Yu.status} ${Yu.statusText}). `+await detail(Yu));const Xu=await fetch(`${Au}/api/v1/agents/sandbox/restart`,{method:"POST"});if(!Xu.ok)throw new Error(`The server could not start ${Ju} (${Xu.status} ${Xu.statusText}). `+await detail(Xu))}function Vu(Wu){return ensureServerAgent(Au,Bu,Wu)}function Gu(){if(Lu?.(),Pu.peek()==="datalayer"){Lu=null,Ou.setState("starting");return}Lu=Du.peek().connect(Bu)}return{get kind(){return Pu.peek()==="browser"?"browser":"server"},target:Pu,snapshot:ju,status:Fu,ready:zu,lastExecution:Uu,serverUrl:Au,getServiceManager:()=>Pu.peek()==="browser"?Mu.getServiceManager():null,getKernelConnection:()=>Pu.peek()==="browser"?Mu.getKernelConnection():null,report(Wu){Du.peek().report(Wu)},setState(Wu,Ku){Du.peek().setState(Wu,Ku)},execute(Wu){return Du.peek().execute(Wu)},connect(Wu){Bu=Wu;const Ku=Pu.peek()==="local"&&Wu?Iu?.()??Ru?.createPayload:void 0;if(!Ku)return Gu(),()=>{Lu?.(),Lu=null};let Ju=!1;return Ou.setState("starting"),Vu(Ku).then(()=>{Ju||Gu()},Yu=>{Ju||(Ou.setState("error"),console.error("[loop] Local agent could not be started:",Yu))}),()=>{Ju=!0,Lu?.(),Lu=null}},async setTarget(Wu){const Ku=Pu.peek();if(Wu===Ku)return;const Ju=heldTargetReason(Wu,Au);if(Ju)throw new Error(Ju);Lu?.(),Lu=null;try{await Hu(Wu)}catch(Yu){throw Gu(),Yu}Pu.value=Wu,Gu()}}}async function ensureServerAgent(Au,lo,$u){const Ru=lo?.trim();if(!Ru)throw new Error("Local needs an agent id before its runtime can start.");let Iu;try{Iu=await fetch(`${Au}/api/v1/agents/${encodeURIComponent(Ru)}`)}catch(Ou){throw new Error(`Local needs an agent-runtimes server at ${Au}, and nothing answered there. Start one and try again. (${Ou instanceof Error?Ou.message:String(Ou)})`,{cause:Ou})}if(Iu.ok){await ensureServerSandbox(Au,Ru);return}if(Iu.status!==404)throw new Error(`The server could not inspect local agent ${Ru} (${Iu.status} ${Iu.statusText}). `+await detail(Iu));const Pu=await fetch(`${Au}/api/v1/agents`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({transport:"ag-ui",sandbox_variant:"jupyter-server",...$u,name:Ru})});if(!Pu.ok&&Pu.status!==409)throw new Error(`The server could not launch local agent ${Ru} (${Pu.status} ${Pu.statusText}). `+await detail(Pu));Pu.status===409&&await ensureServerSandbox(Au,Ru)}async function ensureServerSandbox(Au,lo){const $u=await fetch(`${Au}/api/v1/agents/${encodeURIComponent(lo)}/sandbox/ensure`,{method:"POST"});if(!$u.ok)throw new Error(`The server could not start a sandbox for local agent ${lo} (${$u.status} ${$u.statusText}). `+await detail($u))}async function detail(Au){try{const lo=await Au.json();return typeof lo.detail=="string"?lo.detail:""}catch{return""}}function useOptionalTeamSelection(){return useReactorPlatform().getOutput(AGENTS_PLUGIN_NAME)?.team}const NO_TARGET={value:void 0,peek:()=>{}},NO_MEMBER={value:void 0,peek:()=>{}};function AgentSummaryPanel({workspace:Au}){const lo=useSandboxService(),$u=useSignalValue$1(lo?.target??NO_TARGET),Ru=useOptionalTeamSelection(),Iu=useSignalValue$1(Ru?.active??NO_MEMBER);if(!lo)return null;const Pu=Au.sandbox,Ou=Iu?.specId||Au.agentId,Mu=AGENTSPECS$1[Ou],Du={agentName:Iu?.name||Mu?.name||Au.agentId,location:$u?TARGET_SPECS[$u].label:"—",specId:Ou,harness:Mu?.harness,variant:Pu.variant,status:Pu.state,baseUrl:Pu.agentBaseUrl||Au.serverUrl,sandboxBaseUrl:Pu.jupyterUrl,agentId:Au.agentId,isReady:Pu.state==="running"};return jsxRuntimeExports.jsx(AgentSummary,{summary:Du})}const RING=14,STROKE=2.5,RADIUS=(RING-STROKE)/2,CIRCUMFERENCE=2*Math.PI*RADIUS,DEFAULT_WARN_AT=.25,DEFAULT_DANGER_AT=.1,DEFAULT_PULSE_AT=.05,PULSE_MS=1200;function format(Au){const lo=Math.max(0,Math.ceil(Au/1e3)),$u=Math.floor(lo/60),Ru=lo%60;return`${$u}:${String(Ru).padStart(2,"0")}`}function AnonymousKeyTimer({expiresAt:Au,grantedMs:lo,label:$u="Trial key",warnAt:Ru=DEFAULT_WARN_AT,dangerAt:Iu=DEFAULT_DANGER_AT,pulseAt:Pu=DEFAULT_PULSE_AT,onExpire:Ou}){const[Mu,Du]=reactExports.useState(()=>Date.now()),Lu=reactExports.useRef(lo??Math.max(1,Au-Date.now())),Bu=reactExports.useRef(!1);reactExports.useEffect(()=>{const Hu=window.setInterval(()=>{Du(Vu=>{const Gu=Date.now(),Wu=Ku=>Math.ceil((Au-Ku)/1e3);return Wu(Gu)===Wu(Vu)?Vu:Gu})},250);return()=>window.clearInterval(Hu)},[Au]);const ju=Math.max(0,Au-Mu);reactExports.useEffect(()=>{ju>0||Bu.current||(Bu.current=!0,Ou?.())},[ju,Ou]);const Fu=Math.min(1,Math.max(0,ju/Lu.current)),zu=Fu<=Pu,Uu=Fu<=Iu?"danger.fg":Fu<=Ru?"attention.fg":"fg.muted";return jsxRuntimeExports.jsxs(Box,{display:"inline-flex",alignItems:"center",gap:1,px:2,py:"2px",borderRadius:"999px",border:"1px solid",borderColor:"border.muted",bg:"canvas.subtle",color:Uu,fontVariantNumeric:"tabular-nums",sx:{...zu?{"@keyframes dla-key-pulse":{"0%, 100%":{opacity:1},"50%":{opacity:.45}},animation:`dla-key-pulse ${PULSE_MS}ms ease-in-out infinite`,"@media (prefers-reduced-motion: reduce)":{animation:"none"}}:null},title:`${$u}: this workspace is talking to the agent on a temporary key issued to nobody in particular. When it runs out the chat asks you to sign in. Sign in now for an account of your own.`,children:[jsxRuntimeExports.jsx(Box,{display:"flex",alignItems:"center",color:Uu,children:jsxRuntimeExports.jsx(KeyIcon,{size:12})}),jsxRuntimeExports.jsxs(Box,{as:"svg","aria-hidden":"true",focusable:"false",width:RING,height:RING,viewBox:`0 0 ${RING} ${RING}`,display:"block",flexShrink:0,children:[jsxRuntimeExports.jsx("circle",{cx:RING/2,cy:RING/2,r:RADIUS,fill:"none",stroke:"currentColor",strokeWidth:STROKE,opacity:.2}),jsxRuntimeExports.jsx("circle",{cx:RING/2,cy:RING/2,r:RADIUS,fill:"none",stroke:"currentColor",strokeWidth:STROKE,strokeLinecap:"round",strokeDasharray:CIRCUMFERENCE,strokeDashoffset:CIRCUMFERENCE*(1-Fu),transform:`rotate(-90 ${RING/2} ${RING/2})`,style:{transition:"stroke-dashoffset 0.5s linear"}})]}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:Uu,fontWeight:"semibold"},children:format(ju)})]})}function AnonymousKeyHeaderBadge({workspace:Au}){return jsxRuntimeExports.jsx(Box,{order:1,display:"inline-flex",alignItems:"center",children:jsxRuntimeExports.jsx(AnonymousKeyBadge,{workspace:Au})})}function AnonymousKeyBadge({workspace:Au}){const lo=useAnonymousSession(),$u=Au.sandbox.target??"local";return!targetRunsAgentInPage($u)||lo.status==="idle"||lo.status==="expired"?null:lo.expiresAt?jsxRuntimeExports.jsx(AnonymousKeyTimer,{expiresAt:lo.expiresAt,grantedMs:lo.grantedMs,onExpire:()=>useAnonymousSessionStore.getState().expire()}):jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:lo.error?"danger.fg":"fg.muted"},title:lo.error,children:lo.error?"No trial key":"Getting a trial key…"})}function SandboxSelector(Au){const lo=useOptionalSandboxService(),[$u,Ru]=reactExports.useState(!1),[Iu,Pu]=reactExports.useState(null),Ou=useSignalValue$1(lo?.snapshot??IDLE_SANDBOX_SNAPSHOT_SIGNAL),Mu=useSignalValue$1(lo?.status??EMPTY_STATUS),Du=useSignalValue$1(lo?.target??DEFAULT_TARGET),Lu=reactExports.useCallback(async ju=>{if(!(!lo||ju===Du)){Ru(!0),Pu(null);try{await lo.setTarget(ju)}catch(Fu){Pu(Fu instanceof Error?Fu.message:String(Fu))}finally{Ru(!1)}}},[lo,Du]);if(!lo)return null;const Bu=Math.max(0,SANDBOX_TARGETS.indexOf(Du));return jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,minWidth:0,children:[jsxRuntimeExports.jsx(Box,{width:16,flexShrink:0,display:"flex",justifyContent:"center",children:$u?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):null}),jsxRuntimeExports.jsx(KernelIndicator,{state:sandboxIndicatorState(Ou.state,Mu?.execution_state,Mu?.is_executing),kernelId:Ou.kernelId??Mu?.kernel_id,kernelName:Mu?.kernel_name,serverUrl:Ou.jupyterUrl??Mu?.jupyter_url,websocketUrl:toWebsocketUrl(Ou.jupyterUrl??Mu?.jupyter_url),environmentName:TARGET_SPECS[Du].label,overlayTitle:`${TARGET_SPECS[Du].label} Kernel`,position:"se",bordered:!1}),jsxRuntimeExports.jsx(SegmentedControl,{"aria-label":"Where code runs",size:"small",style:{listStyle:"none",margin:0,padding:0},sx:{listStyle:"none",m:0,p:0,"& > li":{listStyle:"none"},"& > li::marker":{content:"none"}},children:SANDBOX_TARGETS.map((ju,Fu)=>{const zu=heldTargetReason(ju,lo?.serverUrl??"");return jsxRuntimeExports.jsx(SegmentedControl.Button,{selected:Fu===Bu,"aria-disabled":zu?!0:void 0,"data-sandbox-target":ju,"data-sandbox-target-held":zu?"":void 0,sx:{listStyle:"none",...zu?{color:"fg.subtle",cursor:"not-allowed"}:null},title:zu??TARGET_SPECS[ju].hint,onClick:()=>zu?void 0:void Lu(ju),children:TARGET_SPECS[ju].label},ju)})}),Iu||Ou.errorReason?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"danger.fg",lineHeight:1.3,maxWidth:280,minWidth:0},title:Iu??Ou.errorReason,children:Iu??Ou.errorReason}):jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},title:TARGET_SPECS[SANDBOX_TARGETS[Bu]].hint,children:Ou.state})]})}function toWebsocketUrl(Au){return Au?.replace(/^http/,"ws")}const EMPTY_STATUS={value:null,peek:()=>null},DEFAULT_TARGET={value:"local",peek:()=>"local"};function MemberIcon({icon:Au}){const lo=agentIcon(Au);return jsxRuntimeExports.jsx(lo,{})}function TeamMemberPicker(){const Au=useOptionalTeamSelection();return!Au||Au.members.length<2?null:jsxRuntimeExports.jsx(TeamMemberMenu,{selection:Au})}function TeamMemberMenu({selection:Au}){const[lo,$u]=reactExports.useState(!1),Ru=useSignalValue$1(Au.selected),Iu=Au.members.find(Pu=>Pu.id===Ru);return jsxRuntimeExports.jsx(AnchoredOverlay,{width:"large",open:lo,onOpen:()=>$u(!0),onClose:()=>$u(!1),renderAnchor:Pu=>jsxRuntimeExports.jsx(IconButton,{...Pu,"aria-labelledby":void 0,icon:ForwardRef$2,"aria-label":Iu?`Talking to ${Iu.name}. Choose another agent.`:"Choose an agent",variant:"invisible",size:"small"}),children:jsxRuntimeExports.jsx(Box,{width:440,maxWidth:"calc(100vw - 16px)",children:jsxRuntimeExports.jsxs(ActionList,{selectionVariant:"single",role:"listbox","aria-label":`Agents in ${Au.team.name}`,children:[jsxRuntimeExports.jsx(ActionList.GroupHeading,{children:Au.team.name}),Au.members.map(Pu=>jsxRuntimeExports.jsxs(ActionList.Item,{selected:Pu.id===Ru,onSelect:()=>{Au.select(Pu.id),$u(!1)},children:[jsxRuntimeExports.jsx(ActionList.LeadingVisual,{children:jsxRuntimeExports.jsx(MemberIcon,{icon:Pu.icon})}),jsxRuntimeExports.jsxs(Box,{as:"span",display:"flex",alignItems:"center",gap:2,children:[Pu.name,Pu.isSupervisor?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:"supervisor"}):null]}),Pu.description?jsxRuntimeExports.jsx(ActionList.Description,{variant:"block",sx:{display:"block",whiteSpace:"normal",overflowWrap:"anywhere",minWidth:0},children:Pu.description}):null]},Pu.id))]})})})}function specIdOf(Au){return(Au??"").split(":")[0]??""}function teamMembers(Au){const lo=specIdOf(Au.supervisor?.ref),$u=Iu=>{const Pu=AGENTSPECS$1[Iu];return{description:Pu?.description,emoji:Pu?.emoji,icon:Pu?.icon}},Ru=(Au.agents??[]).map(Iu=>{const Pu=specIdOf(Iu.ref);return{id:Iu.id,name:Iu.name||Pu||Iu.id,specId:Pu,isSupervisor:Pu!==""&&Pu===lo,...$u(Pu)}});return[...Ru.filter(Iu=>Iu.isSupervisor),...Ru.filter(Iu=>!Iu.isSupervisor)]}function createTeamSelection(Au){const lo=TEAM_SPECS[Au];if(!lo)return;const $u=teamMembers(lo);if($u.length===0)return;const Ru=signal$2($u[0].id);return{team:lo,members:$u,selected:Ru,select:Iu=>{$u.some(Pu=>Pu.id===Iu)&&(Ru.value=Iu)},sharing:lo.context?.sharing??"shared",active:computed$1(()=>$u.find(Iu=>Iu.id===Ru.value))}}function subagentsFor(Au,lo){const $u=teamMembers(Au),Ru=$u.find(Du=>Du.id===lo);if(!Ru)return[];const Iu=(Du,Lu,Bu)=>{const ju=AGENTSPECS$1[Lu];if(ju)return{name:Du,description:Bu||ju.description||Du,instructions:ju.systemPrompt,model:ju.model,icon:ju.icon}},Pu=Ru.isSupervisor||Au.delegation?.allowPeerDelegation?$u.filter(Du=>Du.id!==lo).map(Du=>Iu(Du.name,Du.specId,Du.description)):[],Mu=((Au.agents??[]).find(Du=>Du.id===lo)?.subagents??[]).map(Du=>Iu(Du.name,(Du.ref??"").split(":")[0]??"",Du.description));return[...Pu,...Mu].filter(Boolean)}const DEFAULT_DATALAYER_AGENTSPEC="jupyter-tutor",AGENTS_PLUGIN_NAME="@datalayer/loop-plugin-agents",offeredTarget=(Au,lo)=>heldTargetReason(Au,lo)?"browser":Au,AgentsPlugin={name:AGENTS_PLUGIN_NAME,displayName:"Agents",description:"Where the agent and its code run: this page, a local server, or a Datalayer runtime.",octicon:"container",emoji:"📦",config:{serverUrl:"",target:"local"},contributionPoints:[LoopAgentBlueprint],preserveOutput:!0,build({config:Au,reactor:lo}){const $u=Au.showAgentVariants??!0,Ru=Au.teamId?createTeamSelection(Au.teamId):void 0;return{team:Ru,sandbox:createSwitchableSandboxService({serverUrl:Au.serverUrl,initialTarget:offeredTarget(($u||Au.targetFixed?Au.target:"browser")??"local",Au.serverUrl),kernelSource:Au.kernelSource,localAgent:Au.localAgent,blueprint:()=>{const Iu=lo.getContributions(LoopAgentBlueprint)[0]?.value;if(Iu)return{...Iu.specId?{agent_spec_id:Iu.specId}:null,...Iu.createPayload}}}),components:[{slot:LoopSlots.status,id:"sandbox-status",Component:SandboxStatusBridge},{slot:LoopSlots.status,id:"datalayer-agent",Component:DatalayerAgentMount},...Ru&&Au.showTeamPicker!==!1?[{slot:LoopSlots.header,id:"team-member-picker",Component:TeamMemberPicker}]:[],...$u?[{slot:LoopSlots.header,id:"sandbox-selector",Component:SandboxSelector}]:[],...Au.showAgentSummary===!1?[]:[{slot:LoopSlots.header,id:"agent-summary",Component:AgentSummaryPanel}],{slot:LoopSlots.chatHeader,id:"anonymous-key",Component:AnonymousKeyBadge},{slot:LoopSlots.header,id:"anonymous-key-header",Component:AnonymousKeyHeaderBadge}]}},register({contribute:Au,state:lo}){const $u=lo.getOutput()?.sandbox;if($u)return Au(LoopAgentGate,{check:Ru=>{const Iu=Ru.sandbox.target??$u.target.peek();return targetHasAgent(Iu)||TARGET_SPECS[Iu].noAgentReason}},{id:"sandbox-target"})},contributes:[contribution(LoopViewType,{viewType:"sandbox",title:"Sandbox",icon:ServerIcon,order:40,load:()=>__vitePreload(()=>import("./chunks/SandboxView-NqXA2LuS.js"),[],import.meta.url)},{id:"sandbox",order:40}),contribution(LoopCommand,{name:"sandbox",aliases:["code-sandbox"],description:"Show the code sandbox: variant, kernel, Jupyter server",group:"Capabilities",run:async({workspace:Au})=>{Au.setActiveViewType("sandbox")}},{id:"sandbox"})]},PULSE_ANIMATION="loop-subagent-pulse",KEYFRAMES=`@keyframes ${PULSE_ANIMATION} {
3838
+ `).filter(Iu=>Iu.startsWith("data:")).map(Iu=>Iu.slice(5).trim()).join("");if(Ru)try{lo.push(JSON.parse(Ru))}catch{}}return lo}function pageTurnOf(Au){let lo=null;for(const $u of streamEvents(Au)){if($u.type==="RUN_ERROR")return{refused:String($u.message??"Its page could not run.")};if($u.type==="CUSTOM"&&$u.name===LOOP_PAGE){const Ru=$u.value??{};lo={outputs:Ru.outputs??{},inputs:Ru.inputs??{}}}}return lo??{refused:"Its page showed nothing: its code answered no outputs."}}const base=Au=>`${Au.serverUrl.replace(/\/+$/,"")}/api/v1/apps/sessions`;async function posted(Au,lo,$u){const Ru=await(Au.fetcher??fetch)(lo,{method:"POST",headers:{"content-type":"application/json",...Au.token?{Authorization:`Bearer ${Au.token}`}:{}},body:JSON.stringify($u)});if(!Ru.ok){let Iu="";try{const Pu=await Ru.json();Iu=typeof Pu.detail=="string"?Pu.detail:""}catch{}throw new Error(Iu||`Its page was refused (${Ru.status}).`)}return Ru.text()}async function openPageSession(Au){const lo=await posted(Au,base(Au),{agent:Au.agentId});for(const $u of streamEvents(lo))if($u.type==="CUSTOM"&&$u.name==="loop.session"){const Ru=$u.value?.uid;if(typeof Ru=="string"&&Ru)return Ru}throw new Error("The runtime opened no session for its page.")}async function runPageIn(Au,lo,$u){try{const Ru=await posted(Au,`${base(Au)}/${encodeURIComponent(lo)}/page`,{inputs:$u});return pageTurnOf(Ru)}catch(Ru){return{refused:Ru instanceof Error?Ru.message:String(Ru)}}}function outputsData(Au){return Object.fromEntries(Object.entries(Au).map(([lo,$u])=>[`/outputs/${lo}`,$u]))}const PAGE_RUN_DELAY_MS=300,NO_TURN$6=signal$2({id:0,status:"idle"}),NO_CONVERSATION$2=signal$2([]);function componentsOnPage(Au){const lo=new Set;for(const $u of Au){const Ru=$u.updateComponents;for(const Iu of Ru?.components??[])lo.add(String(Iu.component))}return[...lo]}function blocksMissing(Au,lo){const $u=new Set(lo),Ru=Au.filter(Iu=>!$u.has(Iu));return Ru.length===0?null:`This page places ${Ru.join(", ")}, which no enabled plugin contributes: ${Ru.length===1?"it is":"they are"} drawn once the plugin that contributes ${Ru.length===1?"it":"them"} is on.`}function AppPage({app:Au,workspace:lo}){const $u=useContributions(LoopChatTurn),Ru=useSignalValue$1($u[0]?.value.turn??NO_TURN$6),Iu=useSignalValue$1($u[0]?.value.conversation??NO_CONVERSATION$2),Pu=reactExports.useMemo(()=>appPageMessages(Au,SURFACE_CATALOG_ID),[Au]),Ou=useContributions(LoopCanvasBlock),Mu=[...new Set(Ou.map(vd=>vd.value.id))].sort(),Du=Mu.join(","),Lu=useOwnComponents(),Bu=reactExports.useMemo(()=>{const vd=blocksMissing(componentsOnPage(Pu),Mu);if(vd)return{problem:vd};try{return{catalog:catalogOfBlocks(Mu,Lu)}}catch(wd){return{problem:wd instanceof Error?wd.message:String(wd)}}},[Pu,Du,Lu]),[ju,Fu]=reactExports.useState(null),zu=pageOf(Au),[Uu,Hu]=reactExports.useState({}),Vu=reactExports.useMemo(()=>({...appPageData(Au,Ru,Iu),...outputsData(Uu)}),[Au,Ru,Iu,Uu]),Gu=useIAMStore(vd=>vd.token)??"",Wu=useChatWords(),Ku=agentServerOf(lo.sandbox,lo.serverUrl),Ju=reactExports.useRef(null);Ju.current=Ku===void 0?null:{serverUrl:Ku,agentId:lo.agentId||Au.id,token:Gu||void 0};const Yu=reactExports.useRef("");Yu.current=Ku===void 0?noRuntimeSaid(lo.sandbox,Wu):"";const Xu=reactExports.useRef(null),ed=reactExports.useRef(!1),td=reactExports.useRef(null),nd=reactExports.useRef(""),od=reactExports.useRef(!0),sd=reactExports.useCallback(vd=>{td.current=vd,!ed.current&&(ed.current=!0,(async()=>{for(;td.current&&od.current;){const wd=td.current;td.current=null;const Td=Ju.current;if(!Td){Fu(Yu.current);continue}try{Xu.current??=openPageSession(Td);const cd=await runPageIn(Td,await Xu.current,wd);if(!od.current)break;"refused"in cd?Fu(cd.refused):(Fu(null),Hu(cd.outputs))}catch(cd){Xu.current=null,od.current&&Fu(cd instanceof Error?cd.message:String(cd))}}ed.current=!1})())},[]),ad=reactExports.useRef(null);reactExports.useEffect(()=>(od.current=!0,()=>{od.current=!1,ad.current?.()}),[]);const pd=reactExports.useCallback(vd=>{if(!zu?.live)return;ad.current?.();let wd;const Td=dd=>{const md=pageInputsOf(Au,dd),ld=JSON.stringify(md);ld!==nd.current&&(clearTimeout(wd),wd=setTimeout(()=>{nd.current=ld,sd(md)},PAGE_RUN_DELAY_MS))},cd=vd.dataModel.subscribe("/inputs",Td);Td(cd.value),ad.current=()=>{clearTimeout(wd),cd.unsubscribe()}},[Au,zu?.live,sd]),gd=reactExports.useRef(lo);gd.current=lo;const xd=reactExports.useRef(""),yd=reactExports.useCallback((vd,wd)=>{const Td=appPageAction(Au,{name:vd.name,context:vd.context??{}},dd=>wd?.dataModel.get(dd),xd.current),cd=gd.current.viewControls;if("refused"in Td){Fu(Td.refused);return}if(Fu(null),"runPage"in Td)sd(Td.runPage);else if("stop"in Td)cd.stop?.();else if("newChat"in Td)cd.newChat?.();else{if(cd.send){const dd=cd.send(Td.send,{loop:Td.loop});if(dd){Fu(dd);return}}else if(Td.loop.files){Fu("The conversation is not ready for a file yet: try again.");return}else gd.current.prompts.submit(Td.send);xd.current=Td.inputs;for(const dd of Td.clear)wd?.dataModel.set(dd,"")}},[Au,sd]);return jsxRuntimeExports.jsx(Box,{"data-testid":"app-page",height:"100%",minHeight:0,overflow:"auto",p:3,children:"problem"in Bu?jsxRuntimeExports.jsx(Box,{role:"status",color:"fg.muted",fontSize:1,children:Bu.problem}):jsxRuntimeExports.jsx(InlineSurface,{messages:Pu,data:Vu,onAction:yd,validationError:ju,catalog:Bu.catalog,...zu?{onSurface:pd}:{}},Du)})}const APP_PAGE_PLUGIN_NAME="@datalayer/loop-plugin-app-page";function defineAppPagePlugin(Au){function lo({workspace:Ru}){return jsxRuntimeExports.jsx(AppPage,{app:Au,workspace:Ru})}return{name:`${APP_PAGE_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: its page`,description:`The page of ${Au.name}, drawn beside its conversation.`,octicon:"browser",emoji:Au.emoji||void 0,contributes:[contribution(LoopEditorView,{surfaceId:APP_PAGE_SURFACE,title:Au.name,icon:BrowserIcon,order:-10,load:async()=>({default:lo})},{id:APP_PAGE_SURFACE,order:-10})]}}const APP_HOST_PAGE_VIEW="app-page";function defineAppHostPagePlugin(Au,lo){function $u({workspace:Iu}){return jsxRuntimeExports.jsx(lo,{app:Au,workspace:Iu})}return{name:`${APP_PAGE_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: its page`,description:`The page of ${Au.name}, drawn by its host.`,octicon:"browser",emoji:Au.emoji||void 0,contributes:[contribution(LoopViewType,{viewType:APP_HOST_PAGE_VIEW,title:Au.name,icon:BrowserIcon,order:-10,load:async()=>({default:$u})},{id:APP_HOST_PAGE_VIEW,order:-10})]}}const canvasBlocksPluginName=Au=>`@datalayer/loop-plugin-ui-${Au}`;function uiPluginBlocks(Au){return{name:canvasBlocksPluginName(Au.id),displayName:Au.name,description:`The blocks of ${Au.name} on the Canvas: ${Au.components.map(lo=>lo.name).join(", ")}.`,octicon:"apps",contributes:Au.components.map(lo=>contribution(LoopCanvasBlock,{id:lo.id,ui:Au.id,component:lo},{id:lo.id}))}}const CANVAS_BLOCK_PLUGINS=listUI().filter(Au=>Au.components.length>0).map(uiPluginBlocks),MANAGER_PLUGIN_NAME="@datalayer/reactor-manager",MANAGER_ACTIONS_SLOT="manager-actions",ManagerPluginSource=defineContributionPoint("manager.pluginSource");function usePluginRows(Au,lo){const $u=useReactorPlatform(),Ru=reactExports.useSyncExternalStore($u.subscribe,()=>$u.getRevision());return reactExports.useMemo(()=>$u.listPlugins().filter(Iu=>!lo.has(Iu)).map(Iu=>{const Pu=$u.getManifest(Iu);return{name:Iu,displayName:Pu?.displayName??Iu,description:Pu?.description,emoji:Pu?.emoji,version:Pu?.version,enabled:$u.isEnabled(Iu),disabledBy:Pu?.disabledBy,changeable:!Au.has(Iu),details:[{label:"Delivered by",values:Pu?.extension?[Pu.extension]:[]},{label:"Contributes to",values:Pu?.contributesTo??[]},{label:"Offers contribution points",values:Pu?.contributionPoints??[]},{label:"Requires backend plugins",values:Pu?.requiredBackendPlugins??[]},{label:"Uses if available",values:Pu?.optionalBackendPlugins??[]},{label:"Activates on",values:Pu?.activationEvents??[]}]}}),[$u,Ru,Au,lo])}function pluginMatches(Au,lo){if(!lo)return!0;const $u=lo.trim().toLowerCase();return[Au.name,Au.displayName,Au.description??""].join(" ").toLowerCase().includes($u)}const PluginHoverContext=reactExports.createContext(null);function usePluginHoverControl(){const[Au,lo]=reactExports.useState(null),$u=reactExports.useRef(void 0);return reactExports.useEffect(()=>()=>clearTimeout($u.current),[]),reactExports.useMemo(()=>({openName:Au,show:Ru=>{clearTimeout($u.current),lo(Ru)},hide:()=>{clearTimeout($u.current),$u.current=setTimeout(()=>lo(null),200)}}),[Au])}function useHoverControl(){const Au=reactExports.useContext(PluginHoverContext),lo=usePluginHoverControl();return Au??lo}function PluginDetails({row:Au}){const lo=(Au.details??[]).filter($u=>$u.values.length>0);return jsxRuntimeExports.jsxs(Box,{sx:{p:3,maxWidth:360,display:"grid",gap:2},children:[jsxRuntimeExports.jsxs(Box,{sx:{display:"flex",alignItems:"center",gap:2},children:[Au.emoji?jsxRuntimeExports.jsx(Text$3,{"aria-hidden":!0,children:Au.emoji}):null,jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold"},children:Au.displayName}),Au.version?jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:["v",Au.version]}):null]}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted",wordBreak:"break-all"},children:Au.name}),Au.description?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0},children:Au.description}):null,lo.map($u=>jsxRuntimeExports.jsxs(Box,{sx:{display:"grid",gap:1},children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,fontWeight:"semibold"},children:$u.label}),$u.values.map(Ru=>jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted",wordBreak:"break-all"},children:Ru},Ru))]},$u.label)),Au.disabledBy==="dependency"?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"attention.fg"},children:"Off because something it depends on is off. It comes back when that does."}):null,Au.changeable?null:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"attention.fg"},children:"This one cannot be switched off."})]})}const OVERLAY_TAKES_NO_FOCUS={preventFocusOnOpen:!0,sx:{pointerEvents:"none"},returnFocusRef:{current:null}};function PluginRowView({row:Au,size:lo,onToggle:$u}){const Ru=`plugin-name-${Au.name.replace(/[^a-zA-Z0-9]+/g,"-")}`,Iu=useHoverControl(),Pu=Iu.openName===Au.name,Ou=()=>Iu.show(Au.name),Mu=()=>Iu.hide();return jsxRuntimeExports.jsx(AnchoredOverlay,{open:Pu,onOpen:Ou,onClose:Mu,focusZoneSettings:{disabled:!0},focusTrapSettings:{disabled:!0},overlayProps:OVERLAY_TAKES_NO_FOCUS,side:"outside-right",renderAnchor:Du=>jsxRuntimeExports.jsxs(Box,{...Du,onMouseEnter:Ou,onMouseLeave:Mu,onFocus:Ou,onBlur:Mu,sx:{display:"flex",alignItems:"flex-start",gap:2,py:2,borderBottom:"1px solid",borderColor:"border.muted"},children:[jsxRuntimeExports.jsxs(Box,{sx:{minWidth:0,flex:1},children:[jsxRuntimeExports.jsxs(Box,{sx:{display:"flex",alignItems:"center",gap:1},children:[Au.emoji?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1},"aria-hidden":!0,children:Au.emoji}):null,jsxRuntimeExports.jsx(Text$3,{id:Ru,sx:{fontSize:1,fontWeight:"semibold",minWidth:0},children:jsxRuntimeExports.jsx(Truncate,{title:Au.name,maxWidth:"100%",inline:!0,children:Au.displayName})})]}),Au.description?jsxRuntimeExports.jsx(Text$3,{sx:{display:"block",fontSize:0,color:"fg.muted"},children:jsxRuntimeExports.jsx(Truncate,{title:Au.description,maxWidth:"100%",inline:!0,children:Au.description})}):null]}),jsxRuntimeExports.jsx(ToggleSwitch,{size:lo,checked:Au.enabled,disabled:!Au.changeable||Au.disabledBy==="dependency","aria-labelledby":Ru,onClick:()=>{Au.changeable&&Au.disabledBy!=="dependency"&&$u(Au.name,!Au.enabled)}})]}),children:jsxRuntimeExports.jsx(PluginDetails,{row:Au})})}function PluginList({plugins:Au,query:lo="",switchSize:$u="small",onToggle:Ru,emptyMessage:Iu}){const Pu=reactExports.useMemo(()=>Au.filter(Ou=>pluginMatches(Ou,lo)),[Au,lo]);return Pu.length===0?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:Iu??`No plugin matches “${lo}”.`}):jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Pu.map(Ou=>jsxRuntimeExports.jsx(PluginRowView,{row:Ou,size:$u,onToggle:Ru},Ou.name))})}function PluginsManagerView({protectedPlugins:Au,hiddenPlugins:lo,switchSize:$u,width:Ru,...Iu}){const Pu=useReactorPlatform(),Ou=Pu.getConfig(MANAGER_PLUGIN_NAME)??{},Mu=reactExports.useMemo(()=>new Set(Au??Ou.protected??[MANAGER_PLUGIN_NAME]),[Au,Ou.protected]),Du=reactExports.useMemo(()=>new Set(lo??Ou.hidden??[]),[lo,Ou.hidden]),Lu=usePluginHoverControl(),Bu=usePluginRows(Mu,Du),[ju,Fu]=reactExports.useState(""),zu=$u??Ou.switchSize??"small",Uu=useContributions(ManagerPluginSource),Hu=reactExports.useMemo(()=>[...Uu].map(Vu=>Vu.value).sort((Vu,Gu)=>(Vu.order??100)-(Gu.order??100)),[Uu]);return jsxRuntimeExports.jsx(PluginHoverContext.Provider,{value:Lu,children:jsxRuntimeExports.jsxs(Box,{sx:{display:"flex",flexDirection:"column",gap:3,width:Ru??Ou.width??"100%",maxWidth:"100%",minWidth:0},children:[jsxRuntimeExports.jsx(ReactorSlot,{slot:MANAGER_ACTIONS_SLOT,props:Iu}),jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{as:"h2",sx:{fontSize:1,fontWeight:"semibold",display:"block",mb:2},children:Ou.title??"Plugins"}),jsxRuntimeExports.jsx(TextInput$1,{leadingVisual:SearchIcon,value:ju,onChange:Vu=>Fu(Vu.target.value),"aria-label":"Filter plugins",placeholder:"Filter…",block:!0,size:"small"})]}),jsxRuntimeExports.jsx(Box,{children:jsxRuntimeExports.jsx(PluginList,{plugins:Bu,query:ju,switchSize:zu,onToggle:(Vu,Gu)=>Gu?Pu.enable(Vu):Pu.disable(Vu)})}),Hu.map(Vu=>jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{as:"h3",sx:{fontSize:1,fontWeight:"semibold",display:"block",mb:2},children:Vu.title}),jsxRuntimeExports.jsx(Vu.Component,{query:ju,switchSize:zu})]},Vu.title))]})})}const PLUGINS_PANEL_PLUGIN_NAME="@datalayer/loop-plugin-plugins-panel",SIDEBAR_WIDTH=420,REACTOR_GRAPH_PLUGIN_NAME="@datalayer/reactor-graph",PluginsPanelPlugin={name:PLUGINS_PANEL_PLUGIN_NAME,displayName:"Plugins panel",description:"Switch plugins on and off while the workspace runs.",octicon:"plug",emoji:"🔌",build:()=>({components:[{id:"plugins-panel",slot:LoopSlots.sidebar,order:900,Component:({workspace:Au})=>jsxRuntimeExports.jsx(PluginsManagerView,{protectedPlugins:[PLUGINS_PANEL_PLUGIN_NAME],hiddenPlugins:[REACTOR_GRAPH_PLUGIN_NAME],width:SIDEBAR_WIDTH,workspace:Au})}]})};function ViewSwitcher({views:Au,workspace:lo,compact:$u=!1}){return Au.length<2?null:jsxRuntimeExports.jsx(Box,{role:"tablist","aria-label":"Workspace views",display:"inline-flex",alignItems:"center",bg:"neutral.muted",borderRadius:"6px",p:"2px",gap:"1px",children:Au.map(Ru=>{const Iu=Ru.value,Pu=canOpenView(Iu,lo),Ou=lo.activeViewType===Iu.viewType,Mu=Iu.icon,Du=Pu?Iu.title:`${Iu.title} — ${Iu.unavailableReason?.(lo)??"unavailable"}`;return jsxRuntimeExports.jsx(Tooltip,{text:Du,direction:"n",children:jsxRuntimeExports.jsxs(Box,{as:"button",role:"tab","aria-selected":Ou,"aria-disabled":!Pu,onClick:()=>Pu&&lo.setActiveViewType(Iu.viewType),display:"inline-flex",alignItems:"center",gap:1,border:"none",borderRadius:"5px",px:2,py:"4px",fontSize:0,cursor:Pu?"pointer":"not-allowed",opacity:Pu?1:.5,bg:Ou?"canvas.default":"transparent",color:Ou?"fg.default":"fg.muted",boxShadow:Ou?"shadow.small":"none",children:[Mu?jsxRuntimeExports.jsx(Mu,{size:14}):null,$u&&Mu?null:Iu.title]})},Iu.viewType)})})}const paneOpenKeyframes=Au=>Au==="left"?"loopPaneOpenLeft":"loopPaneOpenRight",paneOpenAnimation=Au=>`${paneOpenKeyframes(Au)} var(--theme-motion-pane, 0ms) var(--theme-motion-easing, ease) both`;function paneOpening(Au){const lo="12px";return{animation:paneOpenAnimation(Au),[`@keyframes ${paneOpenKeyframes(Au)}`]:{from:{opacity:0,transform:`translateX(${lo})`},to:{opacity:1,transform:"none"}},"@media (prefers-reduced-motion: reduce)":{animation:"none"}}}function railItemsOf(Au){return Au.map(lo=>({id:lo.id,label:lo.rail?.label??lo.id,icon:lo.rail?.icon??SidebarExpandIcon}))}function railChoiceAfter(Au,lo){return Au===lo?null:lo}const RAIL_WIDTH=48;function SidebarRail({components:Au,props:lo,width:$u}){const Ru=railItemsOf(Au),[Iu,Pu]=reactExports.useState(Ru[0]?.id??null),Ou=Ru.some(Mu=>Mu.id===Iu)?Iu:null;return jsxRuntimeExports.jsxs(Box,{as:"aside","data-loop-rail-sidebar":"",flex:"0 0 auto",display:"flex",minHeight:0,children:[jsxRuntimeExports.jsx(Box,{"data-loop-rail-panel":Ou??void 0,display:Ou?"block":"none",width:`${$u}px`,minWidth:0,borderLeft:"var(--theme-hairline, 1px) solid",borderColor:"border.default",overflowY:"auto",px:3,py:3,children:Au.map(Mu=>{const{Component:Du}=Mu,Lu=Mu.id===Ou;return jsxRuntimeExports.jsx(Box,{id:`loop-rail-panel-${Mu.id}`,role:"region","aria-label":railItemsOf([Mu])[0].label,hidden:!Lu,sx:Lu?paneOpening("right"):void 0,children:jsxRuntimeExports.jsx(Du,{...lo})},Mu.id)})}),jsxRuntimeExports.jsx(Box,{as:"nav","aria-label":"Panels",width:`${RAIL_WIDTH}px`,flex:`0 0 ${RAIL_WIDTH}px`,display:"flex",flexDirection:"column",alignItems:"center",gap:1,py:2,borderLeft:"var(--theme-hairline, 1px) solid",borderColor:"border.default",children:Ru.map(Mu=>{const Du=Mu.icon,Lu=Mu.id===Ou;return jsxRuntimeExports.jsx(Box,{as:"button",type:"button","data-loop-rail-item":Mu.id,"aria-label":Mu.label,title:Mu.label,"aria-pressed":Lu,"aria-controls":`loop-rail-panel-${Mu.id}`,onClick:()=>Pu(railChoiceAfter(Ou,Mu.id)),width:32,height:32,display:"inline-flex",alignItems:"center",justifyContent:"center",p:0,border:"none",borderRadius:2,cursor:"pointer",color:Lu?"fg.default":"fg.muted",bg:Lu?"neutral.muted":"transparent",hover:{color:"fg.default",bg:"neutral.subtle"},focusVisible:{outline:"2px solid",outlineColor:"var(--focus-outlineColor, #0969da)",outlineOffset:"1px"},children:jsxRuntimeExports.jsx(Du,{size:16})},Mu.id)})})]})}function buildLoopReactor(Au){return buildReactorFromPlugins(Au)}function LoopWorkspace(Au){const{serverUrl:lo,agentId:$u,conversationId:Ru,model:Iu,sandbox:Pu={state:"idle"},extensions:Ou=[],reactor:Mu,manageReactor:Du=!0,initialViewType:Lu,onSend:Bu,layout:ju="page",showViewSelector:Fu=!0,showHeader:zu=!0,chatHeaderActions:Uu,chatViewModes:Hu,headerActions:Vu,headerContainer:Gu,sidebarRail:Wu=!1}=Au,Ku=reactExports.useMemo(()=>Mu??buildLoopReactor(Ou),[Mu]);return useReactor(Ku,{autoStart:Du}),jsxRuntimeExports.jsx(WorkspaceBody,{serverUrl:lo,agentId:$u,conversationId:Ru,model:Iu,initialSandbox:Pu,initialViewType:Lu,onSend:Bu,layout:ju,showViewSelector:Fu,showHeader:zu,chatHeaderActions:Uu,chatViewModes:Hu,headerActions:Vu,headerContainer:Gu,sidebarRail:Wu})}function WorkspaceBody({serverUrl:Au,agentId:lo,conversationId:$u,model:Ru,initialSandbox:Iu,initialViewType:Pu,onSend:Ou,layout:Mu="page",showViewSelector:Du=!0,showHeader:Lu=!0,chatHeaderActions:Bu,chatViewModes:ju,headerActions:Fu,headerContainer:zu,sidebarRail:Uu=!1}){const[Hu,Vu]=reactExports.useState(lo),Gu=reactExports.useRef(loopSurfaceId($u??`session-${Date.now().toString(36)}`));reactExports.useEffect(()=>{Vu(lo)},[lo]);const[Wu,Ku]=reactExports.useState(Pu??""),[Ju,Yu]=reactExports.useState(Iu),[Xu]=reactExports.useState(createPromptChannel),[ed,td]=reactExports.useState({}),nd=reactExports.useCallback(cd=>{td(cd??{})},[]),od=useContributions(LoopViewType),sd=useContributions(LoopCommand),ad=useSlotComponents(LoopSlots.sidebar),pd=reactExports.useRef(sd),gd=reactExports.useRef(null),xd=Mu==="panel",yd=reactExports.useCallback(async cd=>{const dd=parseCommand(cd);if(!dd)return Ou?.(cd,gd.current),Xu.submit(cd)||Ou?{handled:!0}:{handled:!1,reason:"Nothing is listening for prompts in this view yet."};const md=pd.current.find(hd=>hd.value.name===dd.name||(hd.value.aliases??[]).includes(dd.name));if(!md)return{handled:!1,command:dd.name,reason:`Unknown command: /${dd.name}. Type /help to see what there is.`};const ld=await md.value.run({workspace:gd.current,argv:dd.argv});return ld?.prompt&&(Ou?.(ld.prompt,gd.current),Xu.submit(ld.prompt)),{handled:!0,command:dd.name,result:ld??void 0}},[Ou,Xu]),vd=reactExports.useMemo(()=>({serverUrl:Au,agentId:Hu,surfaceId:Gu.current,setAgentId:Vu,conversationId:$u,model:Ru,sandbox:Ju,setSandbox:Yu,activeViewType:Wu,setActiveViewType:Ku,prompts:Xu,submit:yd,viewControls:ed,setViewControls:nd,chatHeaderActions:Bu,chatViewModes:ju}),[Au,Hu,$u,Ru,Ju,Wu,Xu,yd,ed,nd,Bu,ju]);gd.current=vd,pd.current=sd;const wd=reactExports.useMemo(()=>Wu||(od.find(dd=>canOpenView(dd.value,vd))?.value.viewType??""),[Wu,od,vd]);useReactorEvent(wd?onView(wd):void 0);const Td=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Fu,jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.header,props:{workspace:vd}}),Du?jsxRuntimeExports.jsx(ViewSwitcher,{views:od,workspace:vd,compact:xd}):null]});return jsxRuntimeExports.jsxs(Box,{"data-loop-workspace":"",display:"flex",flexDirection:"column",height:"100%",minHeight:0,position:"relative",bg:"canvas.default",color:"fg.default",children:[Lu&&zu?reactDomExports.createPortal(jsxRuntimeExports.jsx(Box,{display:"flex",alignItems:"center",flexWrap:"wrap",gap:2,children:Td}),zu):null,Lu&&zu===void 0?jsxRuntimeExports.jsx(Box,{as:"header",display:"flex",alignItems:"center",justifyContent:xd?"flex-start":"space-between",flexWrap:"wrap",gap:2,px:xd?2:3,py:2,borderBottom:"1px solid",borderColor:"border.default",flex:"0 0 auto",children:Td}):null,jsxRuntimeExports.jsxs(Box,{flex:"1 1 auto",minHeight:0,display:"flex",children:[jsxRuntimeExports.jsx(Box,{flex:"1 1 auto",minWidth:0,minHeight:0,position:"relative",children:jsxRuntimeExports.jsx(ReactorViewHost,{point:LoopViewType,active:wd,props:{viewType:wd,workspace:vd},fallback:jsxRuntimeExports.jsx(Centered,{children:"Loading…"}),empty:jsxRuntimeExports.jsx(Centered,{children:"No view is available yet."}),errorFallback:cd=>jsxRuntimeExports.jsxs(Centered,{children:["This view failed to load: ",cd.message]})})}),ad.length>0&&Uu&&!xd?jsxRuntimeExports.jsx(SidebarRail,{components:ad,props:{workspace:vd},width:SIDEBAR_WIDTH}):ad.length>0?jsxRuntimeExports.jsx(Box,{as:"aside",flex:"0 0 auto",width:xd?"100%":`${SIDEBAR_WIDTH}px`,minWidth:0,borderLeft:xd?"none":"1px solid",borderTop:xd?"1px solid":"none",borderColor:"border.default",bg:"canvas.subtle",overflowY:"auto",px:3,py:3,children:jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.sidebar,props:{workspace:vd}})}):null]}),jsxRuntimeExports.jsxs(Box,{flex:"0 0 auto",children:[jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.footer,props:{workspace:vd}}),jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.status,props:{workspace:vd}})]}),jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.root,props:{workspace:vd}})]})}function Centered({children:Au}){return jsxRuntimeExports.jsx(Box,{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"fg.muted",fontSize:1,px:3,textAlign:"center",children:Au})}function resolveTopOffset(Au){if(typeof Au=="number")return Au;if(!Au||typeof document>"u")return 0;const lo=document.querySelector(Au);return lo?Math.max(0,Math.round(lo.getBoundingClientRect().bottom)):0}function fullScreenNode(Au){return Au?.closest("[data-loop-fullscreen-root]")??Au?.closest("[data-loop-workspace]")??Au}function useWorkspaceFullScreen(Au,lo={}){const{forceOverlay:$u=!1,paintOverlay:Ru=!1,topOffset:Iu=0}=lo,[Pu,Ou]=reactExports.useState(!1),Mu=reactExports.useRef(!1);reactExports.useEffect(()=>{const ju=()=>{if(!Mu.current)return;const Fu=!!document.fullscreenElement&&!!Au.current&&document.fullscreenElement.contains(Au.current);Ou(Fu),Fu||(Mu.current=!1)};return document.addEventListener("fullscreenchange",ju),()=>document.removeEventListener("fullscreenchange",ju)},[Au]);const Du=reactExports.useCallback(()=>{const ju=fullScreenNode(Au.current);if(Pu){Mu.current&&document.fullscreenElement?document.exitFullscreen():Ou(!1);return}if($u||Ru||!ju?.requestFullscreen){Ou(!0);return}Mu.current=!0,ju.requestFullscreen().then(()=>Ou(!0),()=>{Mu.current=!1,Ou(!0)})},[Au,Pu,$u,Ru]),[Lu,Bu]=reactExports.useState(0);return reactExports.useEffect(()=>{if(!Pu||Mu.current){Bu(0);return}const ju=()=>Bu(resolveTopOffset(Iu));return ju(),window.addEventListener("resize",ju),()=>window.removeEventListener("resize",ju)},[Pu,Iu]),reactExports.useEffect(()=>{if(!Ru||!Pu||Mu.current)return;const ju=fullScreenNode(Au.current);if(!ju)return;const Fu=ju.getAttribute("style");return ju.style.position="fixed",ju.style.top=`${Lu}px`,ju.style.right="0",ju.style.bottom="0",ju.style.left="0",ju.style.height="auto",ju.style.zIndex="1000",()=>{Fu===null?ju.removeAttribute("style"):ju.setAttribute("style",Fu)}},[Ru,Pu,Au,Lu]),reactExports.useEffect(()=>{if(!Pu||Mu.current)return;const ju=Fu=>{Fu.key==="Escape"&&!Fu.defaultPrevented&&Ou(!1)};return window.addEventListener("keydown",ju),()=>window.removeEventListener("keydown",ju)},[Pu]),{fullScreen:Pu,usingApi:Mu,toggle:Du,topOffsetPx:Lu}}function messageText(Au){const lo=Au.content;return typeof lo=="string"?lo:lo.map($u=>typeof $u=="string"?$u:$u.text??"").join("")}const isToolCall=Au=>Au.type==="tool-call";function conversationOf(Au){const lo=[];for(const $u of Au){if(isToolCall($u)){lo.push({role:"tool",name:$u.toolName,args:$u.args??{},...$u.result===void 0?{}:{result:$u.result}});continue}if($u.role!=="user"&&$u.role!=="assistant")continue;const Ru=messageText($u);Ru.trim()&&lo.push({role:$u.role,text:Ru})}return lo}const sameConversation=(Au,lo)=>Au.length===lo.length&&Au.every(($u,Ru)=>JSON.stringify($u)===JSON.stringify(lo[Ru])),IDLE={id:0,status:"idle"};function createTurnFeed(){const Au=signal$2(IDLE),lo=signal$2([]),$u=signal$2("idle");return{turn:Au,conversation:lo,presence:$u,setPresence:Ru=>{$u.value!==Ru&&($u.value=Ru)},items:Ru=>{const Iu=conversationOf(Ru);sameConversation(lo.value,Iu)||(lo.value=Iu)},begin:(Ru,Iu)=>{Au.value={id:Au.value.id+1,user:Ru,...Iu?{thread:Iu}:{},status:"thinking",usage:Au.value.usage}},assistant:Ru=>{const Iu=Au.value;Iu.status==="idle"||Iu.assistant===Ru||(Au.value={...Iu,assistant:Ru,status:Iu.status==="done"||Iu.status==="error"?Iu.status:Ru?"streaming":Iu.status})},usage:Ru=>{const Iu=Au.value;Iu.usage!==Ru&&(Au.value={...Iu,usage:Ru})},activity:Ru=>{const Iu=Au.value;Iu.status==="idle"||Iu.activity===Ru||(Au.value={...Iu,activity:Ru})},end:(Ru="done")=>{const Iu=Au.value;Iu.status!=="idle"&&(Au.value={...Iu,status:Ru,activity:void 0})}}}const TURN_WRITERS=Symbol.for("loop.chat.turn.writers");function feedWriters(Au){return{[TURN_WRITERS]:Au}}function turnWritersOf(Au){return Au?.[TURN_WRITERS]}function agentAction(Au,lo){const{prompt:$u,...Ru}=lo;return{...Ru,type:"button",group:"agent",onClick:()=>Au.workspace.prompts.submit($u)}}const CHAT_PLUGIN_NAME="@datalayer/loop-plugin-chat",ChatPlugin={name:CHAT_PLUGIN_NAME,config:{placeholder:"",defaultSurface:"notebook",showSurfaceSelector:!0,hideHeader:!1,headerButtons:{newChat:!1,clear:!1},hidePrompt:!1,promptPlacement:"bottom",autoFocusPrompt:!0,suggestionLabels:!0,fullScreenTopOffset:0},displayName:"Chat",description:"The conversation, the prompt, and the point editors plug into.",octicon:"comment-discussion",emoji:"💬",contributionPoints:[LoopAgentGate,LoopFrontendTool,LoopChatComposer,LoopChatHeader,LoopChatSuggestion,LoopChatExtras,LoopChatTurn],build:Au=>{const lo=createTurnFeed();return Au.contribute(LoopChatTurn,{id:"chat-turn",turn:lo.turn,conversation:lo.conversation,presence:lo.presence,...feedWriters(lo)},{id:"chat-turn"}),{}},contributes:[contribution(LoopViewType,{viewType:"chat",title:"Chat",icon:CommentDiscussionIcon,order:0,load:()=>__vitePreload(()=>import("./chunks/ChatView-CUWE6I5M.js"),[],import.meta.url)},{id:"chat",order:0}),contribution(LoopCommand,{name:"chat",description:"Show the conversation",group:"Session",keybinding:"Mod+Alt+K",run:async({workspace:Au})=>{Au.setActiveViewType("chat")}},{id:"chat"}),contribution(LoopNotebookToolbarItem,{items:Au=>[agentAction(Au,{key:"loop-compact",ariaLabel:"Compact this notebook",title:"Ask @NotebookCompactor to shorten it without changing results",icon:FoldIcon,order:200,prompt:"@NotebookCompactor compact this notebook without changing what it computes."}),agentAction(Au,{key:"loop-reproduce",ariaLabel:"Check reproducibility",title:"Ask @NotebookReproducer to run it on a fresh sandbox",icon:SyncIcon,order:201,prompt:"@NotebookReproducer run this notebook top to bottom on a fresh sandbox and report what does not reproduce."})]},{id:"agent-actions",order:200}),contribution(LoopDocumentToolbarItem,{items:Au=>[agentAction(Au,{key:"loop-summarise",ariaLabel:"Summarise this document",title:"Ask the agent for a summary of what this document says",icon:SparkleFillIcon,order:200,prompt:"Summarise this document in a short paragraph."})]},{id:"agent-actions",order:200})]};function WorkspaceFullScreenAction(){const Au=reactExports.useRef(null),$u=useReactorPlatform().getConfig(CHAT_PLUGIN_NAME)?.fullScreenTopOffset??0,{fullScreen:Ru,toggle:Iu}=useWorkspaceFullScreen(Au,{paintOverlay:!!$u,topOffset:$u});return jsxRuntimeExports.jsx(IconButton,{ref:Au,icon:Ru?ScreenNormalIcon:ScreenFullIcon,"aria-label":Ru?"Exit full screen":"Enter full screen",variant:"invisible",size:"small",sx:{order:2},onClick:Iu})}const THEME_PLUGIN_NAME="@datalayer/primer-theme",TOGGLE_COLOR_MODE_COMMAND="theme.toggleColorMode",ThemePlugin={name:THEME_PLUGIN_NAME,displayName:"Theme",description:"Keeps Primer portals in the application’s color mode, and toggles it.",octicon:"sun",emoji:"🌗",commands:[{id:TOGGLE_COLOR_MODE_COMMAND,name:"Toggle the color mode",description:"Switch between light and dark",emoji:"🌗",category:"Appearance",keybinding:"Mod+Alt+C",execute:()=>{const Au=useThemeStore.getState(),lo=Au.colorMode==="auto"?typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light":Au.colorMode;Au.setColorMode(lo==="dark"?"light":"dark")}}],register:()=>{if(typeof document>"u")return;setupPrimerPortals(useThemeStore.getState().colorMode);const Au=useThemeStore.subscribe((Ru,Iu)=>{Ru.colorMode!==Iu.colorMode&&setupPrimerPortals(Ru.colorMode)}),lo=window.matchMedia("(prefers-color-scheme: dark)"),$u=()=>{useThemeStore.getState().colorMode==="auto"&&setupPrimerPortals("auto")};return lo.addEventListener("change",$u),()=>{Au(),lo.removeEventListener("change",$u)}}},pageLayoutPanelOpen=signal$2(!1),pageLayoutSheet=signal$2("page"),pageLayoutActivity=signal$2(void 0);function openPagePanel(){pageLayoutPanelOpen.value=!0}const PAGE_SHEET_WIDTH=920,PAGE_PANEL_WIDTH=400,PAGE_SIZE_FORMATS={letter:{width:816,height:1056},a4:{width:794,height:1123}};function resolvePageSize(Au,lo=PAGE_SHEET_WIDTH){const $u=Au?.format&&Au.format!=="free"?PAGE_SIZE_FORMATS[Au.format]:void 0;return{width:Au?.width??$u?.width??lo,height:Au?.height??$u?.height}}const CANVAS_PX=[2,3,4];function ActivityLine({label:Au}){return jsxRuntimeExports.jsxs(Box$1,{"data-page-activity":"",role:"status",sx:{position:"sticky",top:0,zIndex:2,alignSelf:"flex-start",display:"inline-flex",alignItems:"center",gap:2,px:2,py:"4px",borderRadius:"999px",border:"1px solid",borderColor:"accent.muted",bg:"accent.subtle",color:"accent.fg",fontSize:0,fontWeight:"semibold",whiteSpace:"nowrap",boxShadow:"0 4px 12px -6px rgba(0,0,0,0.3)"},children:[jsxRuntimeExports.jsx(Box$1,{as:"span","aria-hidden":"true",sx:{width:7,height:7,borderRadius:"50%",bg:"accent.fg",animation:"page-activity-dot 1.1s ease-in-out infinite","@keyframes page-activity-dot":{"0%, 100%":{opacity:1},"50%":{opacity:.3}}}}),jsxRuntimeExports.jsx(Text$3,{children:Au})]})}function panelOpening(Au){const lo=Au==="left"?"pagePanelOpenLeft":"pagePanelOpenRight";return{animation:`${lo} var(--theme-motion-pane, 0ms) var(--theme-motion-easing, ease) both`,[`@keyframes ${lo}`]:{from:{opacity:0,transform:`translateX(${Au==="left"?"-12px":"12px"})`},to:{opacity:1,transform:"none"}},"@media (prefers-reduced-motion: reduce)":{animation:"none"}}}function PageLayout({page:Au,hasPage:lo=Au!=null,panel:$u,band:Ru,chips:Iu,picker:Pu,transient:Ou,activity:Mu,bandMode:Du="docked",panelMode:Lu="docked",panelSide:Bu="right",sheetWidth:ju=PAGE_SHEET_WIDTH,pageSize:Fu,panelWidth:zu=PAGE_PANEL_WIDTH}){const Uu=Du==="panel",Hu=Ru!=null,{width:Vu,height:Gu}=resolvePageSize(Fu,ju),Ku=useSignalValue$1(pageLayoutPanelOpen)||Uu&&Hu,Ju=useSignalValue$1(pageLayoutActivity),Yu=Mu??Ju,Xu=lo?"page":"panel";return reactExports.useEffect(()=>{pageLayoutSheet.value=Xu},[Xu]),jsxRuntimeExports.jsxs(Box$1,{"data-page-layout":"",sx:{position:"relative",flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column"},children:[Pu,jsxRuntimeExports.jsxs(Box$1,{sx:{flex:"1 1 auto",minHeight:0,display:"flex",bg:"canvas.inset"},children:[jsxRuntimeExports.jsxs(Box$1,{sx:{flex:"1 1 auto",minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:[Ru&&Du==="docked"?jsxRuntimeExports.jsx(Box$1,{"data-page-band":"","data-page-prompt-dock":"",sx:{flex:"0 0 auto",display:"flex",justifyContent:"center",px:CANVAS_PX,bg:"canvas.subtle",borderBottom:"1px solid",borderColor:"border.default"},children:jsxRuntimeExports.jsx(Box$1,{sx:{width:"100%",maxWidth:Vu,minWidth:0},children:Ru})}):null,jsxRuntimeExports.jsxs(Box$1,{"data-page-canvas":"",sx:{flex:"1 1 auto",minWidth:0,minHeight:0,overflowY:lo?"auto":"hidden",overflowX:"hidden",display:"flex",flexDirection:"column",alignItems:"center",pt:3,pb:6,px:CANVAS_PX},children:[Ru&&Iu&&!Uu?jsxRuntimeExports.jsx(Box$1,{sx:{width:"100%",maxWidth:Vu,mb:3,display:"flex",justifyContent:"center","& > *":{justifyContent:"center"}},children:Iu}):null,Yu?jsxRuntimeExports.jsx(Box$1,{sx:{width:"100%",maxWidth:Vu,display:"flex",justifyContent:"flex-end",mb:2},children:jsxRuntimeExports.jsx(ActivityLine,{label:Yu})}):null,jsxRuntimeExports.jsx(Sheet,{"data-page-sheet":"",sx:{width:"100%",maxWidth:Vu,flex:lo?"1 0 auto":"1 1 auto",px:lo?[3,4,"56px"]:[2,3,4],py:lo?[3,4,4]:2,position:"relative",display:"flex",minHeight:lo?Gu??480:0,"& > *":{flex:"1 1 auto",minWidth:0}},children:lo?Au:$u}),lo||!Au?null:jsxRuntimeExports.jsx(Box$1,{"aria-hidden":"true",sx:{position:"absolute",inset:0,visibility:"hidden",pointerEvents:"none",zIndex:-1,display:"flex"},children:Au})]})]}),!lo||!$u?null:jsxRuntimeExports.jsxs(Box$1,{"data-page-panel":Ku?"":void 0,"data-page-panel-mode":Lu,"aria-hidden":Ku?void 0:"true",sx:{minWidth:0,minHeight:0,display:"flex",flexDirection:"column",bg:"canvas.default",borderColor:"border.default",...Ku?Lu==="docked"?{flex:`0 0 ${zu}px`,maxWidth:"45%",order:Bu==="left"?-1:void 0,[Bu==="left"?"borderRight":"borderLeft"]:"1px solid",zIndex:1}:Lu==="overlay"?{position:"absolute",top:0,bottom:0,[Bu]:0,width:zu,maxWidth:"85%",[Bu==="left"?"borderRight":"borderLeft"]:"1px solid",boxShadow:"shadow.large",zIndex:5}:{position:"absolute",[Bu]:16,bottom:16,width:zu,maxWidth:"calc(100% - 32px)",height:"min(70%, 560px)",border:"1px solid",borderRadius:2,boxShadow:"shadow.large",overflow:"hidden",zIndex:5}:{position:"absolute",inset:0,visibility:"hidden",pointerEvents:"none",overflow:"visible"}},children:[jsxRuntimeExports.jsx(Box$1,{sx:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column","& > *":{flex:"1 1 auto",minHeight:0},...Ku?panelOpening(Bu):null},children:$u}),Hu&&Du!=="docked"?jsxRuntimeExports.jsxs(Box$1,{"data-page-panel-band":Uu?"":void 0,sx:Uu?{flex:"0 0 auto",borderTop:"1px solid",borderColor:"border.default",visibility:"visible",pointerEvents:"auto","& > *":{justifyContent:"center"}}:{position:"absolute",inset:0,visibility:"visible",pointerEvents:"none","& > *":{pointerEvents:"auto"}},children:[Uu?Iu:null,Ru]}):null]})]}),Ou]})}function PagePanelToggle({panelName:Au="panel",icon:lo=SidebarExpandIcon,sx:$u}){const Ru=useSignalValue$1(pageLayoutPanelOpen);return useSignalValue$1(pageLayoutSheet)==="panel"?null:jsxRuntimeExports.jsx(IconButton,{icon:lo,size:"small",variant:Ru?"default":"invisible","aria-label":Ru?`Hide the ${Au}`:`Show the ${Au}`,"aria-pressed":Ru,onClick:()=>{Ru?pageLayoutPanelOpen.value=!1:openPagePanel()},sx:{color:Ru?"accent.fg":"fg.muted",...$u}})}const INPUT_PROMPT_PLUGIN_NAME="@datalayer/loop-plugin-input-prompt",LazyComposerView=reactExports.lazy(()=>__vitePreload(()=>import("./chunks/ComposerView-Wa0dy8ex.js"),[],import.meta.url));function ComposerView(Au){return jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(LazyComposerView,{...Au})})}const InputPromptPlugin={name:INPUT_PROMPT_PLUGIN_NAME,config:{},displayName:"Input Prompt",description:"The composer under (or over) the conversation.",octicon:"pencil",emoji:"✏️",contributionPoints:[LoopPromptPanel],contributes:[contribution(LoopChatComposer,{id:"input-prompt",Component:ComposerView},{id:"input-prompt"})]},AGENT_ICONS={agent:ForwardRef$2,beaker:BeakerIcon,bell:BellIcon,book:BookIcon,briefcase:BriefcaseIcon,browser:BrowserIcon,bug:BugIcon,clock:ClockIcon,code:CodeIcon,"comment-discussion":CommentDiscussionIcon,cpu:CpuIcon,"credit-card":CreditCardIcon,database:DatabaseIcon,file:FileIcon,checklist:ChecklistIcon,"code-review":CodeReviewIcon,fold:FoldIcon,"git-branch":GitBranchIcon,globe:GlobeIcon,graph:GraphIcon,heart:HeartIcon,"issue-opened":IssueOpenedIcon,lightbulb:LightBulbIcon,"light-bulb":LightBulbIcon,"list-unordered":ListUnorderedIcon,mail:MailIcon,megaphone:MegaphoneIcon,"mortar-board":MortarBoardIcon,note:NoteIcon,organization:OrganizationIcon,package:PackageIcon,pencil:PencilIcon,people:PeopleIcon,play:PlayIcon,pulse:PulseIcon,rss:RssIcon,search:SearchIcon,"share-2":ShareAndroidIcon,shield:ShieldIcon,"shield-check":ShieldCheckIcon,sliders:SlidersIcon,sun:SunIcon,sync:SyncIcon,table:TableIcon,tag:TagIcon,tasklist:TasklistIcon,telescope:TelescopeIcon,tools:ToolsIcon,"trending-up":GraphIcon,rocket:RocketIcon,zap:ZapIcon};function agentIcon(Au){return(Au?AGENT_ICONS[Au]:void 0)??ForwardRef$2}function useOptionalSandboxService(){return useReactorPlatform().getOutput(AGENTS_PLUGIN_NAME)?.sandbox}function useSandboxService(){const Au=useOptionalSandboxService();if(!Au)throw new Error(`The code sandbox plugin (${AGENTS_PLUGIN_NAME}) is not mounted. A view that needs a sandbox must declare it as a dependency.`);return Au}function SandboxStatusBridge({workspace:Au}){const lo=useOptionalSandboxService(),$u=useSignalValue$1(lo?.snapshot??IDLE_SANDBOX_SNAPSHOT_SIGNAL),Ru=useSignalValue$1(lo?.target??IDLE_SANDBOX_TARGET_SIGNAL),{setSandbox:Iu,agentId:Pu}=Au;return reactExports.useEffect(()=>lo?.connect(Pu),[lo,Pu]),reactExports.useEffect(()=>{lo&&Iu({...$u,target:Ru})},[lo,$u,Ru,Iu]),null}const DatalayerAgentBridge=reactExports.lazy(async()=>({default:(await __vitePreload(()=>import("./chunks/DatalayerAgentBridge-D54Z9BZ3.js"),[],import.meta.url)).DatalayerAgentBridge}));function DatalayerAgentMount(){return jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(DatalayerAgentBridge,{})})}const CREATING_STATUSES=new Set(["creating","starting","launching","connecting","pending","resuming"]),MAX_AGENT_NAME_LENGTH=32,toSandboxStatusUrl=Au=>{const lo=String(Au||"").trim();if(lo)try{const $u=new URL(lo);return $u.pathname=`${$u.pathname.replace(/\/$/,"")}/api`,$u.toString()}catch{const $u=lo.replace(/\/$/,"");return $u.endsWith("/api")?$u:`${$u}/api`}},OVERLAY_WIDTH=360,AgentSummary=({summary:Au,title:lo="Active Agent"})=>{const[$u,Ru]=reactExports.useState(!1),[Iu,Pu]=reactExports.useState(!1),Ou=reactExports.useRef(null),Mu=reactExports.useRef(null),Du=()=>{Mu.current!==null&&(window.clearTimeout(Mu.current),Mu.current=null)},Lu=()=>{Du();const Yu=Ou.current?.getBoundingClientRect();Pu(!!(Yu&&Yu.left+OVERLAY_WIDTH>window.innerWidth)),Ru(!0)},Bu=()=>{Du(),Mu.current=window.setTimeout(()=>{Ru(!1),Mu.current=null},300)};reactExports.useEffect(()=>()=>{Du()},[]);const ju=Au?.baseUrl?(()=>{const Yu=Au.baseUrl.replace(/\/$/,"");return Yu.endsWith("/api/v1")?Yu:`${Yu}/api/v1`})():void 0,Fu=ju?`${ju}/runtime/status`:void 0,zu=toSandboxStatusUrl(Au?.sandboxBaseUrl);if(!Au)return null;const Uu=(Au.status||"").toLowerCase(),Hu=!Au.isReady&&!Au.agentId&&CREATING_STATUSES.has(Uu),Vu=!!Au.error,Gu=!!Au.agentId||Hu,Wu=strip(Au.agentName,MAX_AGENT_NAME_LENGTH),Ku=`${Au.agentName} · ${Au.location}`,Ju=`${Wu} · ${Au.location}`;return jsxRuntimeExports.jsxs(Box,{ref:Ou,position:"relative",onMouseEnter:Lu,onMouseLeave:Bu,children:[jsxRuntimeExports.jsxs(Box,{as:"button",type:"button",title:Ku,px:2,py:"6px",maxWidth:280,minWidth:0,border:"1px solid",borderColor:Vu?"danger.emphasis":"border.default",borderRadius:2,bg:Vu?"danger.subtle":"canvas.default",color:Vu?"danger.fg":"fg.default",fontSize:0,cursor:"default",display:"flex",alignItems:"center",gap:1,children:[Hu&&jsxRuntimeExports.jsx(StyledSpinner,{size:"small",sx:{width:12,height:12}}),Vu&&jsxRuntimeExports.jsx("span",{"aria-hidden":!0,children:"⚠"}),jsxRuntimeExports.jsx(Box,{as:"span",display:"block",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",children:Ju})]}),$u&&jsxRuntimeExports.jsxs(Box,{position:"absolute",top:"calc(100% + 8px)",width:OVERLAY_WIDTH,p:2,border:"1px solid",borderColor:"border.default",borderRadius:2,bg:"canvas.overlay",boxShadow:"shadow.large",zIndex:120,fontSize:0,color:"fg.default",right:Iu?0:void 0,left:Iu?void 0:0,children:[jsxRuntimeExports.jsx(Box,{mb:1,fontWeight:600,children:lo}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Name: ",Au.agentName]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Location: ",Au.location]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Spec: ",Au.specId||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Harness: ",Au.harness||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Variant: ",Au.variant||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Status: ",Hu?"creating":Au.status||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Agent base URL: ",Au.baseUrl||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Code sandbox base URL:"," ",Au.sandboxBaseUrl?jsxRuntimeExports.jsx(Box,{as:"a",href:Au.sandboxBaseUrl,target:"_blank",rel:"noopener noreferrer",color:"accent.fg",textDecoration:"underline",children:Au.sandboxBaseUrl}):"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",display:"flex",alignItems:"center",gap:1,children:["Agent ID:"," ",Au.agentId?Au.agentId:Hu?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(StyledSpinner,{size:"small",sx:{width:12,height:12}}),"Creating…"]}):"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Agent status:"," ",Gu&&Fu?jsxRuntimeExports.jsx(Box,{as:"a",href:Fu,target:"_blank",rel:"noopener noreferrer",color:"accent.fg",textDecoration:"underline",children:Fu}):"n/a"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Code sandbox status:"," ",zu?jsxRuntimeExports.jsx(Box,{as:"a",href:zu,target:"_blank",rel:"noopener noreferrer",color:"accent.fg",textDecoration:"underline",children:zu}):"n/a"]}),Vu&&jsxRuntimeExports.jsxs(Box,{mt:1,p:1,border:"1px solid",borderColor:"danger.muted",borderRadius:2,bg:"danger.subtle",color:"danger.fg",wordBreak:"break-word",children:["Error: ",Au.error]})]})]})},insideJupyterLab=()=>loadJupyterConfig().insideJupyterLab;function collect(Au,lo){const $u=Au?.header?.msg_type,Ru=Au?.content??{};$u==="stream"?(lo.stdout.push(String(Ru.text??"")),lo.outputs.push({output_type:"stream",text:Ru.text})):$u==="execute_result"||$u==="display_data"?lo.outputs.push({output_type:$u,data:Ru.data}):$u==="error"&&(lo.error=`${Ru.ename??"Error"}: ${Ru.evalue??""}`,lo.outputs.push({output_type:"error",ename:Ru.ename,evalue:Ru.evalue,traceback:Ru.traceback}))}function browserSource(){let Au;return{variant:"pyodide",acquire:async()=>{const{createLiteServiceManager:lo,jupyterReactStore:$u,loadJupyterConfig:Ru}=await __vitePreload(async()=>{const{createLiteServiceManager:Pu,jupyterReactStore:Ou,loadJupyterConfig:Mu}=await import("./chunks/index-BN8Bbau-.js").then(Du=>Du.r);return{createLiteServiceManager:Pu,jupyterReactStore:Ou,loadJupyterConfig:Mu}},[],import.meta.url);Au=Au??{baseUrl:libExports$5.PageConfig.getOption("baseUrl"),wsUrl:libExports$5.PageConfig.getOption("wsUrl")},Ru({lite:!0});const Iu=await lo();return $u.getState().setServiceManager(Iu),Iu},release:()=>{Au&&(libExports$5.PageConfig.setOption("baseUrl",Au.baseUrl),libExports$5.PageConfig.setOption("wsUrl",Au.wsUrl),Au=void 0)},owned:!0}}function createBrowserSandboxService(Au=browserSource()){const lo=signal$2(null),$u=signal$2("idle"),Ru=signal$2(null),Iu=computed$1(()=>({state:$u.value,variant:Au.variant,kernelId:lo.value?.kernel_id})),Pu=computed$1(()=>$u.value==="running");let Ou=null,Mu=null,Du=null,Lu=null;async function Bu(){if(Mu)return;$u.value="starting",Ou=await Au.acquire();const ju=await Ou.sessions.startNew({name:"loop",path:"loop.ipynb",type:"notebook",kernel:{name:"python"}});Du=ju.kernel,Mu=ju.kernel,lo.value={variant:Au.variant,sandbox_running:!0,kernel_id:Mu?.id,kernel_name:"python"},$u.value="running"}return{kind:"browser",snapshot:Iu,status:lo,ready:Pu,lastExecution:Ru,serverUrl:"",getServiceManager:()=>Ou,getKernelConnection:()=>Du,report(ju){lo.value=ju},setState(ju){$u.value=ju},connect(){return Lu=Lu??Bu().catch(ju=>{throw $u.value="error",lo.value=null,Lu=null,ju}),()=>{Mu?.shutdown?.(),Mu=null,Du=null,Ou=Au.owned?null:Ou,Au.release?.(),Lu=null,$u.value="idle",lo.value=null}},async execute(ju){const Fu=Date.now();try{if(await(Lu??Bu()),!Mu)throw new Error("The browser kernel did not start");const zu={outputs:[],stdout:[],error:""},Uu=Mu.requestExecute({code:ju});Uu.onIOPub=Vu=>collect(Vu,zu),await Uu.done;const Hu={code:ju,success:!zu.error,stdout:zu.stdout.join(""),error:zu.error||void 0,outputs:zu.outputs,startedAt:Fu,finishedAt:Date.now()};return Ru.value=Hu,Hu}catch(zu){const Uu={code:ju,success:!1,error:zu instanceof Error?zu.message:String(zu),startedAt:Fu,finishedAt:Date.now()};return Ru.value=Uu,Uu}}}}function summarize(Au,lo){if(!Au)return{state:lo};const $u=Au.variant==="jupyter-server"||Au.variant==="datalayer";return{state:!!Au.sandbox_running||$u&&!!Au.jupyter_connected?"running":lo==="running"?"idle":lo,variant:Au.variant,kernelId:Au.kernel_id,jupyterUrl:Au.jupyter_url,jupyterToken:Au.jupyter_token,agentBaseUrl:Au.agent_base_url}}const RECONNECT_BASE_MS=1e3,RECONNECT_MAX_MS=3e4;function createServerSandboxService(Au){const lo=signal$2(null),$u=signal$2("idle"),Ru=signal$2(void 0),Iu=signal$2(null),Pu=computed$1(()=>({...summarize(lo.value,$u.value),errorReason:$u.value==="error"?Ru.value:void 0})),Ou=computed$1(()=>Pu.value.state==="running");return{kind:"server",connect(Mu){if(typeof WebSocket>"u")return()=>{};let Du=null,Lu=null,Bu=0,ju=!1;const Fu=()=>{if(ju)return;const zu=Au.replace(/^http/,"ws"),Uu=Mu?`?agent_id=${encodeURIComponent(Mu)}`:"";Du=new WebSocket(`${zu}/api/v1/configure/sandbox/ws${Uu}`),Du.onopen=()=>{Bu=0},Du.onmessage=Hu=>{try{lo.value=JSON.parse(String(Hu.data))}catch{}},Du.onclose=()=>{if(ju)return;lo.value=null,Bu+=1;const Hu=Math.min(RECONNECT_BASE_MS*2**(Bu-1),RECONNECT_MAX_MS);Lu=setTimeout(Fu,Hu)}};return Fu(),()=>{ju=!0,Lu&&clearTimeout(Lu),Du?.close(),Du=null}},snapshot:Pu,status:lo,ready:Ou,lastExecution:Iu,serverUrl:Au,report(Mu){lo.value=Mu},setState(Mu,Du){$u.value=Mu,Ru.value=Mu==="error"?Du:void 0},async execute(Mu){const Du=Date.now();try{const Lu=await fetch(`${Au}/api/v1/sandbox/execute`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:Mu})}),Bu=Lu.ok?await Lu.json():null,ju={code:Mu,success:Lu.ok&&!Bu?.error,stdout:Bu?.stdout,stderr:Bu?.stderr,error:Lu.ok?Bu?.error:`Execution failed: ${Lu.status}`,outputs:Bu?.outputs,startedAt:Du,finishedAt:Date.now()};return Iu.value=ju,ju}catch(Lu){const Bu={code:Mu,success:!1,error:Lu instanceof Error?Lu.message:String(Lu),startedAt:Du,finishedAt:Date.now()};return Iu.value=Bu,Bu}}}}const ANONYMOUS_JUPYTER_URL="https://prod1.datalayer.run/api/jupyter-server",ANONYMOUS_JUPYTER_TOKEN="60c1661cc408f978c309d04157af55c9588ff9557c9380e4fb50785750703da6",SANDBOX_TARGETS=["browser","local","jupyter","datalayer"];function heldTargetReason(Au,lo){if(Au==="local"&&!lo&&!insideJupyterLab())return"Not offered on the web for now: a local agent and the Jupyter server it starts run beside JupyterLab, not in a page."}const TARGET_SPECS={browser:{label:"Browser",hint:"Python in this page (Pyodide), with the agent loop running here too. Only the model is asked over the network.",hasAgent:!0,noAgentReason:""},local:{label:"Local",hint:"A local agent, with the Jupyter server it starts beside itself.",hasAgent:!0,noAgentReason:"",configure:{variant:"jupyter-server",jupyter_url:"",jupyter_token:""}},jupyter:{label:"Jupyter",hint:"A named Jupyter server: the anonymous one on prod1.datalayer.run.",hasAgent:!1,noAgentReason:"No agent on an anonymous Jupyter server",configure:{variant:"jupyter-server",jupyter_url:ANONYMOUS_JUPYTER_URL,jupyter_token:ANONYMOUS_JUPYTER_TOKEN}},datalayer:{label:"Datalayer",hint:"A Datalayer runtime running the agent this workspace asks for.",hasAgent:!0,noAgentReason:""}};function targetHasAgent(Au){return TARGET_SPECS[Au]?.hasAgent??!1}function targetRunsAgentInPage(Au){return Au==="browser"}function createSwitchableSandboxService({serverUrl:Au,initialTarget:lo="local",kernelSource:$u,localAgent:Ru,blueprint:Iu}){const Pu=signal$2(lo),Ou=createServerSandboxService(Au),Mu=createBrowserSandboxService($u??browserSource()),Du=computed$1(()=>Pu.value==="browser"?Mu:Ou);let Lu=null,Bu;const ju=computed$1(()=>Du.value.snapshot.value),Fu=computed$1(()=>Du.value.status.value),zu=computed$1(()=>Du.value.ready.value),Uu=computed$1(()=>Du.value.lastExecution.value);async function Hu(Wu){if(Wu==="local"){const ed=Iu?.()??Ru?.createPayload;ed&&await Vu(ed)}const Ku=TARGET_SPECS[Wu]?.configure;if(!Ku)return;const Ju=TARGET_SPECS[Wu].label;let Yu;try{Yu=await fetch(`${Au}/api/v1/agents/sandbox/configure`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Ku)})}catch(ed){throw new Error(`${Ju} needs an agent-runtimes server at ${Au}, and nothing answered there. Start one and try again. (${ed instanceof Error?ed.message:String(ed)})`,{cause:ed})}if(!Yu.ok)throw new Error(`The server could not switch to ${Ju} (${Yu.status} ${Yu.statusText}). `+await detail(Yu));const Xu=await fetch(`${Au}/api/v1/agents/sandbox/restart`,{method:"POST"});if(!Xu.ok)throw new Error(`The server could not start ${Ju} (${Xu.status} ${Xu.statusText}). `+await detail(Xu))}function Vu(Wu){return ensureServerAgent(Au,Bu,Wu)}function Gu(){if(Lu?.(),Pu.peek()==="datalayer"){Lu=null,Ou.setState("starting");return}Lu=Du.peek().connect(Bu)}return{get kind(){return Pu.peek()==="browser"?"browser":"server"},target:Pu,snapshot:ju,status:Fu,ready:zu,lastExecution:Uu,serverUrl:Au,getServiceManager:()=>Pu.peek()==="browser"?Mu.getServiceManager():null,getKernelConnection:()=>Pu.peek()==="browser"?Mu.getKernelConnection():null,report(Wu){Du.peek().report(Wu)},setState(Wu,Ku){Du.peek().setState(Wu,Ku)},execute(Wu){return Du.peek().execute(Wu)},connect(Wu){Bu=Wu;const Ku=Pu.peek()==="local"&&Wu?Iu?.()??Ru?.createPayload:void 0;if(!Ku)return Gu(),()=>{Lu?.(),Lu=null};let Ju=!1;return Ou.setState("starting"),Vu(Ku).then(()=>{Ju||Gu()},Yu=>{Ju||(Ou.setState("error"),console.error("[loop] Local agent could not be started:",Yu))}),()=>{Ju=!0,Lu?.(),Lu=null}},async setTarget(Wu){const Ku=Pu.peek();if(Wu===Ku)return;const Ju=heldTargetReason(Wu,Au);if(Ju)throw new Error(Ju);Lu?.(),Lu=null;try{await Hu(Wu)}catch(Yu){throw Gu(),Yu}Pu.value=Wu,Gu()}}}async function ensureServerAgent(Au,lo,$u){const Ru=lo?.trim();if(!Ru)throw new Error("Local needs an agent id before its runtime can start.");let Iu;try{Iu=await fetch(`${Au}/api/v1/agents/${encodeURIComponent(Ru)}`)}catch(Ou){throw new Error(`Local needs an agent-runtimes server at ${Au}, and nothing answered there. Start one and try again. (${Ou instanceof Error?Ou.message:String(Ou)})`,{cause:Ou})}if(Iu.ok){await ensureServerSandbox(Au,Ru);return}if(Iu.status!==404)throw new Error(`The server could not inspect local agent ${Ru} (${Iu.status} ${Iu.statusText}). `+await detail(Iu));const Pu=await fetch(`${Au}/api/v1/agents`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({transport:"ag-ui",sandbox_variant:"jupyter-server",...$u,name:Ru})});if(!Pu.ok&&Pu.status!==409)throw new Error(`The server could not launch local agent ${Ru} (${Pu.status} ${Pu.statusText}). `+await detail(Pu));Pu.status===409&&await ensureServerSandbox(Au,Ru)}async function ensureServerSandbox(Au,lo){const $u=await fetch(`${Au}/api/v1/agents/${encodeURIComponent(lo)}/sandbox/ensure`,{method:"POST"});if(!$u.ok)throw new Error(`The server could not start a sandbox for local agent ${lo} (${$u.status} ${$u.statusText}). `+await detail($u))}async function detail(Au){try{const lo=await Au.json();return typeof lo.detail=="string"?lo.detail:""}catch{return""}}function useOptionalTeamSelection(){return useReactorPlatform().getOutput(AGENTS_PLUGIN_NAME)?.team}const NO_TARGET={value:void 0,peek:()=>{}},NO_MEMBER={value:void 0,peek:()=>{}};function AgentSummaryPanel({workspace:Au}){const lo=useSandboxService(),$u=useSignalValue$1(lo?.target??NO_TARGET),Ru=useOptionalTeamSelection(),Iu=useSignalValue$1(Ru?.active??NO_MEMBER);if(!lo)return null;const Pu=Au.sandbox,Ou=Iu?.specId||Au.agentId,Mu=AGENTSPECS$1[Ou],Du={agentName:Iu?.name||Mu?.name||Au.agentId,location:$u?TARGET_SPECS[$u].label:"—",specId:Ou,harness:Mu?.harness,variant:Pu.variant,status:Pu.state,baseUrl:Pu.agentBaseUrl||Au.serverUrl,sandboxBaseUrl:Pu.jupyterUrl,agentId:Au.agentId,isReady:Pu.state==="running"};return jsxRuntimeExports.jsx(AgentSummary,{summary:Du})}const RING=14,STROKE=2.5,RADIUS=(RING-STROKE)/2,CIRCUMFERENCE=2*Math.PI*RADIUS,DEFAULT_WARN_AT=.25,DEFAULT_DANGER_AT=.1,DEFAULT_PULSE_AT=.05,PULSE_MS=1200;function format(Au){const lo=Math.max(0,Math.ceil(Au/1e3)),$u=Math.floor(lo/60),Ru=lo%60;return`${$u}:${String(Ru).padStart(2,"0")}`}function AnonymousKeyTimer({expiresAt:Au,grantedMs:lo,label:$u="Trial key",warnAt:Ru=DEFAULT_WARN_AT,dangerAt:Iu=DEFAULT_DANGER_AT,pulseAt:Pu=DEFAULT_PULSE_AT,onExpire:Ou}){const[Mu,Du]=reactExports.useState(()=>Date.now()),Lu=reactExports.useRef(lo??Math.max(1,Au-Date.now())),Bu=reactExports.useRef(!1);reactExports.useEffect(()=>{const Hu=window.setInterval(()=>{Du(Vu=>{const Gu=Date.now(),Wu=Ku=>Math.ceil((Au-Ku)/1e3);return Wu(Gu)===Wu(Vu)?Vu:Gu})},250);return()=>window.clearInterval(Hu)},[Au]);const ju=Math.max(0,Au-Mu);reactExports.useEffect(()=>{ju>0||Bu.current||(Bu.current=!0,Ou?.())},[ju,Ou]);const Fu=Math.min(1,Math.max(0,ju/Lu.current)),zu=Fu<=Pu,Uu=Fu<=Iu?"danger.fg":Fu<=Ru?"attention.fg":"fg.muted";return jsxRuntimeExports.jsxs(Box,{display:"inline-flex",alignItems:"center",gap:1,px:2,py:"2px",borderRadius:"999px",border:"1px solid",borderColor:"border.muted",bg:"canvas.subtle",color:Uu,fontVariantNumeric:"tabular-nums",sx:{...zu?{"@keyframes dla-key-pulse":{"0%, 100%":{opacity:1},"50%":{opacity:.45}},animation:`dla-key-pulse ${PULSE_MS}ms ease-in-out infinite`,"@media (prefers-reduced-motion: reduce)":{animation:"none"}}:null},title:`${$u}: this workspace is talking to the agent on a temporary key issued to nobody in particular. When it runs out the chat asks you to sign in. Sign in now for an account of your own.`,children:[jsxRuntimeExports.jsx(Box,{display:"flex",alignItems:"center",color:Uu,children:jsxRuntimeExports.jsx(KeyIcon,{size:12})}),jsxRuntimeExports.jsxs(Box,{as:"svg","aria-hidden":"true",focusable:"false",width:RING,height:RING,viewBox:`0 0 ${RING} ${RING}`,display:"block",flexShrink:0,children:[jsxRuntimeExports.jsx("circle",{cx:RING/2,cy:RING/2,r:RADIUS,fill:"none",stroke:"currentColor",strokeWidth:STROKE,opacity:.2}),jsxRuntimeExports.jsx("circle",{cx:RING/2,cy:RING/2,r:RADIUS,fill:"none",stroke:"currentColor",strokeWidth:STROKE,strokeLinecap:"round",strokeDasharray:CIRCUMFERENCE,strokeDashoffset:CIRCUMFERENCE*(1-Fu),transform:`rotate(-90 ${RING/2} ${RING/2})`,style:{transition:"stroke-dashoffset 0.5s linear"}})]}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:Uu,fontWeight:"semibold"},children:format(ju)})]})}function AnonymousKeyHeaderBadge({workspace:Au}){return jsxRuntimeExports.jsx(Box,{order:1,display:"inline-flex",alignItems:"center",children:jsxRuntimeExports.jsx(AnonymousKeyBadge,{workspace:Au})})}function AnonymousKeyBadge({workspace:Au}){const lo=useAnonymousSession(),$u=Au.sandbox.target??"local";return!targetRunsAgentInPage($u)||lo.status==="idle"||lo.status==="expired"?null:lo.expiresAt?jsxRuntimeExports.jsx(AnonymousKeyTimer,{expiresAt:lo.expiresAt,grantedMs:lo.grantedMs,onExpire:()=>useAnonymousSessionStore.getState().expire()}):jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:lo.error?"danger.fg":"fg.muted"},title:lo.error,children:lo.error?"No trial key":"Getting a trial key…"})}function SandboxSelector(Au){const lo=useOptionalSandboxService(),[$u,Ru]=reactExports.useState(!1),[Iu,Pu]=reactExports.useState(null),Ou=useSignalValue$1(lo?.snapshot??IDLE_SANDBOX_SNAPSHOT_SIGNAL),Mu=useSignalValue$1(lo?.status??EMPTY_STATUS),Du=useSignalValue$1(lo?.target??DEFAULT_TARGET),Lu=reactExports.useCallback(async ju=>{if(!(!lo||ju===Du)){Ru(!0),Pu(null);try{await lo.setTarget(ju)}catch(Fu){Pu(Fu instanceof Error?Fu.message:String(Fu))}finally{Ru(!1)}}},[lo,Du]);if(!lo)return null;const Bu=Math.max(0,SANDBOX_TARGETS.indexOf(Du));return jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,minWidth:0,children:[jsxRuntimeExports.jsx(Box,{width:16,flexShrink:0,display:"flex",justifyContent:"center",children:$u?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):null}),jsxRuntimeExports.jsx(KernelIndicator,{state:sandboxIndicatorState(Ou.state,Mu?.execution_state,Mu?.is_executing),kernelId:Ou.kernelId??Mu?.kernel_id,kernelName:Mu?.kernel_name,serverUrl:Ou.jupyterUrl??Mu?.jupyter_url,websocketUrl:toWebsocketUrl(Ou.jupyterUrl??Mu?.jupyter_url),environmentName:TARGET_SPECS[Du].label,overlayTitle:`${TARGET_SPECS[Du].label} Kernel`,position:"se",bordered:!1}),jsxRuntimeExports.jsx(SegmentedControl,{"aria-label":"Where code runs",size:"small",style:{listStyle:"none",margin:0,padding:0},sx:{listStyle:"none",m:0,p:0,"& > li":{listStyle:"none"},"& > li::marker":{content:"none"}},children:SANDBOX_TARGETS.map((ju,Fu)=>{const zu=heldTargetReason(ju,lo?.serverUrl??"");return jsxRuntimeExports.jsx(SegmentedControl.Button,{selected:Fu===Bu,"aria-disabled":zu?!0:void 0,"data-sandbox-target":ju,"data-sandbox-target-held":zu?"":void 0,sx:{listStyle:"none",...zu?{color:"fg.subtle",cursor:"not-allowed"}:null},title:zu??TARGET_SPECS[ju].hint,onClick:()=>zu?void 0:void Lu(ju),children:TARGET_SPECS[ju].label},ju)})}),Iu||Ou.errorReason?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"danger.fg",lineHeight:1.3,maxWidth:280,minWidth:0},title:Iu??Ou.errorReason,children:Iu??Ou.errorReason}):jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},title:TARGET_SPECS[SANDBOX_TARGETS[Bu]].hint,children:Ou.state})]})}function toWebsocketUrl(Au){return Au?.replace(/^http/,"ws")}const EMPTY_STATUS={value:null,peek:()=>null},DEFAULT_TARGET={value:"local",peek:()=>"local"};function MemberIcon({icon:Au}){const lo=agentIcon(Au);return jsxRuntimeExports.jsx(lo,{})}function TeamMemberPicker(){const Au=useOptionalTeamSelection();return!Au||Au.members.length<2?null:jsxRuntimeExports.jsx(TeamMemberMenu,{selection:Au})}function TeamMemberMenu({selection:Au}){const[lo,$u]=reactExports.useState(!1),Ru=useSignalValue$1(Au.selected),Iu=Au.members.find(Pu=>Pu.id===Ru);return jsxRuntimeExports.jsx(AnchoredOverlay,{width:"large",open:lo,onOpen:()=>$u(!0),onClose:()=>$u(!1),renderAnchor:Pu=>jsxRuntimeExports.jsx(IconButton,{...Pu,"aria-labelledby":void 0,icon:ForwardRef$2,"aria-label":Iu?`Talking to ${Iu.name}. Choose another agent.`:"Choose an agent",variant:"invisible",size:"small"}),children:jsxRuntimeExports.jsx(Box,{width:440,maxWidth:"calc(100vw - 16px)",children:jsxRuntimeExports.jsxs(ActionList,{selectionVariant:"single",role:"listbox","aria-label":`Agents in ${Au.team.name}`,children:[jsxRuntimeExports.jsx(ActionList.GroupHeading,{children:Au.team.name}),Au.members.map(Pu=>jsxRuntimeExports.jsxs(ActionList.Item,{selected:Pu.id===Ru,onSelect:()=>{Au.select(Pu.id),$u(!1)},children:[jsxRuntimeExports.jsx(ActionList.LeadingVisual,{children:jsxRuntimeExports.jsx(MemberIcon,{icon:Pu.icon})}),jsxRuntimeExports.jsxs(Box,{as:"span",display:"flex",alignItems:"center",gap:2,children:[Pu.name,Pu.isSupervisor?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:"supervisor"}):null]}),Pu.description?jsxRuntimeExports.jsx(ActionList.Description,{variant:"block",sx:{display:"block",whiteSpace:"normal",overflowWrap:"anywhere",minWidth:0},children:Pu.description}):null]},Pu.id))]})})})}function specIdOf(Au){return(Au??"").split(":")[0]??""}function teamMembers(Au){const lo=specIdOf(Au.supervisor?.ref),$u=Iu=>{const Pu=AGENTSPECS$1[Iu];return{description:Pu?.description,emoji:Pu?.emoji,icon:Pu?.icon}},Ru=(Au.agents??[]).map(Iu=>{const Pu=specIdOf(Iu.ref);return{id:Iu.id,name:Iu.name||Pu||Iu.id,specId:Pu,isSupervisor:Pu!==""&&Pu===lo,...$u(Pu)}});return[...Ru.filter(Iu=>Iu.isSupervisor),...Ru.filter(Iu=>!Iu.isSupervisor)]}function createTeamSelection(Au){const lo=TEAM_SPECS[Au];if(!lo)return;const $u=teamMembers(lo);if($u.length===0)return;const Ru=signal$2($u[0].id);return{team:lo,members:$u,selected:Ru,select:Iu=>{$u.some(Pu=>Pu.id===Iu)&&(Ru.value=Iu)},sharing:lo.context?.sharing??"shared",active:computed$1(()=>$u.find(Iu=>Iu.id===Ru.value))}}function subagentsFor(Au,lo){const $u=teamMembers(Au),Ru=$u.find(Du=>Du.id===lo);if(!Ru)return[];const Iu=(Du,Lu,Bu)=>{const ju=AGENTSPECS$1[Lu];if(ju)return{name:Du,description:Bu||ju.description||Du,instructions:ju.systemPrompt,model:ju.model,icon:ju.icon}},Pu=Ru.isSupervisor||Au.delegation?.allowPeerDelegation?$u.filter(Du=>Du.id!==lo).map(Du=>Iu(Du.name,Du.specId,Du.description)):[],Mu=((Au.agents??[]).find(Du=>Du.id===lo)?.subagents??[]).map(Du=>Iu(Du.name,(Du.ref??"").split(":")[0]??"",Du.description));return[...Pu,...Mu].filter(Boolean)}const DEFAULT_DATALAYER_AGENTSPEC="jupyter-tutor",AGENTS_PLUGIN_NAME="@datalayer/loop-plugin-agents",offeredTarget=(Au,lo)=>heldTargetReason(Au,lo)?"browser":Au,AgentsPlugin={name:AGENTS_PLUGIN_NAME,displayName:"Agents",description:"Where the agent and its code run: this page, a local server, or a Datalayer runtime.",octicon:"container",emoji:"📦",config:{serverUrl:"",target:"local"},contributionPoints:[LoopAgentBlueprint],preserveOutput:!0,build({config:Au,reactor:lo}){const $u=Au.showAgentVariants??!0,Ru=Au.teamId?createTeamSelection(Au.teamId):void 0;return{team:Ru,sandbox:createSwitchableSandboxService({serverUrl:Au.serverUrl,initialTarget:offeredTarget(($u||Au.targetFixed?Au.target:"browser")??"local",Au.serverUrl),kernelSource:Au.kernelSource,localAgent:Au.localAgent,blueprint:()=>{const Iu=lo.getContributions(LoopAgentBlueprint)[0]?.value;if(Iu)return{...Iu.specId?{agent_spec_id:Iu.specId}:null,...Iu.createPayload}}}),components:[{slot:LoopSlots.status,id:"sandbox-status",Component:SandboxStatusBridge},{slot:LoopSlots.status,id:"datalayer-agent",Component:DatalayerAgentMount},...Ru&&Au.showTeamPicker!==!1?[{slot:LoopSlots.header,id:"team-member-picker",Component:TeamMemberPicker}]:[],...$u?[{slot:LoopSlots.header,id:"sandbox-selector",Component:SandboxSelector}]:[],...Au.showAgentSummary===!1?[]:[{slot:LoopSlots.header,id:"agent-summary",Component:AgentSummaryPanel}],{slot:LoopSlots.chatHeader,id:"anonymous-key",Component:AnonymousKeyBadge},{slot:LoopSlots.header,id:"anonymous-key-header",Component:AnonymousKeyHeaderBadge}]}},register({contribute:Au,state:lo}){const $u=lo.getOutput()?.sandbox;if($u)return Au(LoopAgentGate,{check:Ru=>{const Iu=Ru.sandbox.target??$u.target.peek();return targetHasAgent(Iu)||TARGET_SPECS[Iu].noAgentReason}},{id:"sandbox-target"})},contributes:[contribution(LoopViewType,{viewType:"sandbox",title:"Sandbox",icon:ServerIcon,order:40,load:()=>__vitePreload(()=>import("./chunks/SandboxView-NqXA2LuS.js"),[],import.meta.url)},{id:"sandbox",order:40}),contribution(LoopCommand,{name:"sandbox",aliases:["code-sandbox"],description:"Show the code sandbox: variant, kernel, Jupyter server",group:"Capabilities",run:async({workspace:Au})=>{Au.setActiveViewType("sandbox")}},{id:"sandbox"})]},PULSE_ANIMATION="loop-subagent-pulse",KEYFRAMES=`@keyframes ${PULSE_ANIMATION} {
3839
3839
  0%, 100% { opacity: 0.25; }
3840
3840
  50% { opacity: 1; }
3841
- }`;function SubagentPulse(){const Au=useAgentRuntimeActiveSubagentToolCallId(),lo=useAgentRuntimeSubagentActivity(Au??void 0),$u=useOptionalReactorPlatform(),Ru=lo[0]?.subagentName??Au??"",Iu=$u?.getOutput(AGENTS_PLUGIN_NAME)?.team?.members.find(Du=>Du.name===Ru),Pu=agentIcon(Iu?.icon);if(!Au)return null;const Mu=lo.some(Du=>Du.transport==="a2a")?`${Ru} is working over A2A…`:`${Ru} is working…`;return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("style",{children:KEYFRAMES}),jsxRuntimeExports.jsx(Tooltip,{text:Mu,direction:"n",children:jsxRuntimeExports.jsx(Box,{as:"button",type:"button","aria-label":Mu,"data-subagent-pulse":Ru,display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,p:0,border:0,bg:"transparent",color:"accent.fg",cursor:"default",animation:`${PULSE_ANIMATION} 1.4s ease-in-out infinite`,children:jsxRuntimeExports.jsx(Pu,{size:16})})})]})}const SUBAGENT_ACTIVITY_PLUGIN_NAME="@datalayer/loop-plugin-subagent-activity",SubagentActivityPlugin={name:SUBAGENT_ACTIVITY_PLUGIN_NAME,displayName:"Subagent activity",description:"A delegated agent's icon, pulsing in the prompt's header while it works.",octicon:"people",emoji:"👥",dependencies:[InputPromptPlugin],build:()=>({components:[{id:"subagent-pulse",slot:LoopSlots.inpromptMenu,order:0,Component:SubagentPulse}]})},A2UI_PLUGIN_NAME="@datalayer/loop-plugin-a2ui",A2uiPlugin={name:A2UI_PLUGIN_NAME,displayName:"A2UI surfaces",description:"The last execution, rendered as a surface rather than dumped.",octicon:"browser",emoji:"🖼",dependencies:[AgentsPlugin],contributes:[contribution(LoopViewType,{viewType:"a2ui",title:"Surface",icon:BrowserIcon,order:30,canOpen:Au=>Au.sandbox.state==="running"&&Au.sandbox.variant!=="pyodide",unavailableReason:Au=>Au.sandbox.variant==="pyodide"?"Surfaces are rendered by the server; this sandbox runs in the browser":"Needs a running sandbox",load:()=>__vitePreload(()=>import("./chunks/A2uiView-EmeKVJZp.js"),[],import.meta.url)},{id:"a2ui",order:30}),contribution(LoopCommand,{name:"a2ui",aliases:["surface"],description:"Show the last execution as a rendered surface",group:"Open",keybinding:"Mod+Alt+U",run:async({workspace:Au})=>{Au.setActiveViewType("a2ui")}},{id:"a2ui"})]},NONE_VIEW="none";let state={viewId:NONE_VIEW,options:[],allowNone:!0},announcer=()=>!0;const listeners=new Set;function notify(){for(const Au of[...listeners])Au()}function getViewChoice(){return state}function subscribeViewChoice(Au){return listeners.add(Au),()=>{listeners.delete(Au)}}function setViewAnnouncer(Au){const lo=announcer;return announcer=Au,()=>{announcer=lo}}function setViewOptions(Au,lo=!0){if(lo===state.allowNone&&Au.length===state.options.length&&Au.every((Ru,Iu)=>Ru===state.options[Iu]))return;state={viewId:!lo&&!Au.includes(state.viewId)?Au[0]??NONE_VIEW:state.viewId,options:Au,allowNone:lo},notify()}function chooseView(Au){return state={...state,viewId:Au},notify(),announcer(Au)}function seedViewChoice(Au){state.viewId!==Au&&(state={...state,viewId:Au},notify())}function nextView(){const Au=state.allowNone?[NONE_VIEW,...state.options]:[...state.options];if(Au.length===0)return NONE_VIEW;const lo=Au.indexOf(state.viewId);return Au[(lo+1)%Au.length]}function ViewSelector({point:Au,describe:lo,context:$u,noneLabel:Ru,ariaLabel:Iu,allowNone:Pu=!0}){const Ou=useContributions(Au),Mu=reactExports.useSyncExternalStore(subscribeViewChoice,getViewChoice),[Du,Lu]=reactExports.useState(null),Bu=reactExports.useRef(null),ju=()=>{Bu.current!==null&&(window.clearTimeout(Bu.current),Bu.current=null)},Fu=Vu=>{ju(),Lu(Vu)},zu=()=>{ju(),Bu.current=window.setTimeout(()=>{Lu(null),Bu.current=null},250)};reactExports.useEffect(()=>ju,[]);const Uu=reactExports.useMemo(()=>Ou.map(Vu=>lo(Vu.value,$u)).sort((Vu,Gu)=>(Vu.order??100)-(Gu.order??100)),[Ou,lo,$u]);if(reactExports.useEffect(()=>{setViewOptions(Uu.map(Vu=>Vu.id),Pu)},[Uu,Pu]),Uu.length<(Pu?1:2))return null;const Hu=Uu.find(Vu=>Vu.id===Du&&Vu.details);return jsxRuntimeExports.jsxs(Box$1,{sx:{marginLeft:"auto",display:"flex",alignItems:"center",position:"relative"},children:[jsxRuntimeExports.jsxs(SegmentedControl,{"aria-label":Iu,size:"small",children:[Pu?jsxRuntimeExports.jsx(SegmentedControl.Button,{selected:Mu.viewId===NONE_VIEW,onClick:()=>chooseView(NONE_VIEW),children:Ru}):null,Uu.map(Vu=>jsxRuntimeExports.jsx(SegmentedControl.Button,{selected:Mu.viewId===Vu.id,"aria-disabled":Vu.disabled||void 0,title:Vu.disabled?Vu.disabledReason:Vu.title,leadingIcon:Vu.icon,onMouseEnter:Vu.details?()=>Fu(Vu.id):void 0,onMouseLeave:Vu.details?zu:void 0,onClick:()=>{Vu.disabled||chooseView(Vu.id)},children:Vu.badge?`${Vu.title} (${Vu.badge})`:Vu.title},Vu.id))]}),Hu?jsxRuntimeExports.jsx(Box$1,{onMouseEnter:ju,onMouseLeave:zu,sx:{position:"absolute",top:"calc(100% + 6px)",right:0,minWidth:260,maxWidth:380,maxHeight:320,overflowY:"auto",p:2,bg:"canvas.overlay",border:"1px solid",borderColor:"border.default",borderRadius:2,boxShadow:"shadow.large",zIndex:40,fontSize:0,color:"fg.default",textAlign:"left"},children:Hu.details}):null]})}const SHELL_PLUGIN_NAME$1="@datalayer/reactor-shell",ShellView=defineContributionPoint("reactor.shell.view"),describeAsIs=Au=>Au,ShellPlugin$1={name:SHELL_PLUGIN_NAME$1,displayName:"Shell",description:"A view point, its selector, and the choice as a command.",octicon:"columns",emoji:"📑",config:{point:ShellView,describe:describeAsIs,slot:"header",defaultView:NONE_VIEW,showSelector:!0,allowNone:!0,noneLabel:"None",ariaLabel:"View",announce:()=>!0,commandId:"shell.cycleView",commandName:"Switch the view",commandDescription:"Cycle through the contributed views, and none",keybinding:"Mod+Alt+E"},contributionPoints:[ShellView],register:({config:Au,registerCommand:lo})=>{const $u=setViewAnnouncer(Au.announce),Ru=lo({id:Au.commandId,name:Au.commandName,description:Au.commandDescription,emoji:"📑",category:"Workspace",keybinding:Au.keybinding||void 0,execute:()=>{chooseView(nextView())}});return()=>{$u(),Ru()}},build:({config:Au})=>(seedViewChoice(Au.defaultView||NONE_VIEW),{components:Au.showSelector?[{id:"view-selector",slot:Au.slot,Component:lo=>jsxRuntimeExports.jsx(ViewSelector,{point:Au.point,describe:Au.describe,context:lo,noneLabel:Au.noneLabel,allowNone:Au.allowNone,ariaLabel:Au.ariaLabel})}]:[]})};setViewAnnouncer(requestSurface);const NONE_EDITOR=NONE_VIEW;let mappedFor=null,mapped=null;function getEditorChoice(){const Au=getViewChoice();return(Au!==mappedFor||!mapped)&&(mappedFor=Au,mapped={editorId:Au.viewId,options:Au.options}),mapped}const subscribeEditorChoice=subscribeViewChoice,setEditorOptions=setViewOptions,chooseEditor=chooseView,seedEditorChoice=seedViewChoice,nextEditor=nextView;let jupyterReact=null;function loadJupyterReact(){return jupyterReact?Promise.resolve(jupyterReact):__vitePreload(()=>import("./chunks/index-CyQgE_Es.js").then(Au=>Au.r),[],import.meta.url).then(Au=>(jupyterReact=Au,Au))}const PREVIEW_LENGTH=56;function stripped(Au){const $u=(Au.split(`
3842
- `).find(Ru=>Ru.trim())??"").trim();return $u.length>PREVIEW_LENGTH?`${$u.slice(0,PREVIEW_LENGTH-1)}…`:$u||"(empty)"}function PreviewList({title:Au,rows:lo}){return jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold",display:"block",mb:1},children:Au}),lo.length===0?jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted"},children:"Empty so far."}):lo.map(($u,Ru)=>jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,py:"2px",alignItems:"baseline",children:[jsxRuntimeExports.jsxs(Text$3,{sx:{color:"fg.muted",flexShrink:0,fontFamily:"mono"},children:[Ru," · ",$u.kind]}),jsxRuntimeExports.jsx(Text$3,{sx:{fontFamily:"mono",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:$u.text})]},Ru))]})}function useOfferedEditors(){return reactExports.useSyncExternalStore(subscribeEditorChoice,()=>getEditorChoice().options)}function useNotebookRows(Au,lo){const[$u,Ru]=reactExports.useState(0);return reactExports.useEffect(()=>{if(!lo)return;let Iu=!1;const Pu=()=>Ru(Du=>Du+1),Ou=[],Mu=jupyterReact!==null;return loadJupyterReact().then(({notebookStore:Du})=>{if(!Iu)try{const Lu=Du.subscribe?.(Pu);Lu&&Ou.push(Lu);const Bu=Du.getState()?.notebooks?.get(Au)?.model;if(Bu){const ju=[Bu.contentChanged,Bu.cells?.changed];for(const Fu of ju)Fu?.connect&&(Fu.connect(Pu),Ou.push(()=>Fu.disconnect(Pu)))}Mu||Pu()}catch{}}),()=>{Iu=!0;for(const Du of Ou)try{Du()}catch{}}},[lo,Au,$u]),reactExports.useMemo(()=>{if(!lo)return null;const Iu=safeModel(Au);if(!Iu)return null;const Pu=[],Ou=Iu.cells;for(let Mu=0;Mu<Ou.length;Mu+=1){const Du=Ou.get(Mu);Pu.push({kind:Du.type,text:stripped(Du.sharedModel.getSource())})}return Pu},[lo,Au,$u])}function safeModel(Au){try{return jupyterReact?.notebookStore.getState()?.notebooks?.get(Au)?.model??null}catch{return null}}function useDocumentRows(Au,lo){const[$u,Ru]=reactExports.useState(null);return reactExports.useEffect(()=>{if(!lo){Ru(null);return}let Iu=!1,Pu,Ou=!1;return __vitePreload(()=>import("./chunks/PrismCss-CcU1ChRk.js").then(Mu=>Mu.a),[],import.meta.url).then(()=>__vitePreload(()=>import("./chunks/index-x45cMPwN.js"),[],import.meta.url)).then(({lexicalStore:Mu})=>{if(Iu)return;const Du=()=>{Ou||(Ou=!0,Mu.getState().readAllBlocks(Au,"brief").then(Lu=>{Ou=!1,!(Iu||!Array.isArray(Lu))&&Ru(Lu.map(Bu=>({kind:Bu.block_type??"block",text:stripped(Bu.preview??"")})))}).catch(()=>{Ou=!1,Iu||Ru(null)}))};Du(),Pu=Mu.subscribe(Du)}).catch(()=>{Iu||Ru(null)}),()=>{Iu=!0,Pu?.()}},[lo,Au]),$u}function useEditorPreviews(Au){const lo=useOfferedEditors(),$u=useNotebookRows(Au,lo.includes("notebook")),Ru=useDocumentRows(Au,lo.includes("document"));return reactExports.useMemo(()=>{const Iu={};return $u&&(Iu.notebook={badge:String($u.length),details:jsxRuntimeExports.jsx(PreviewList,{title:"Cells",rows:$u})}),Ru&&(Iu.document={badge:String(Ru.length),details:jsxRuntimeExports.jsx(PreviewList,{title:"Blocks",rows:Ru})}),Iu},[$u,Ru])}const SHELL_PLUGIN_NAME="@datalayer/loop-plugin-shell";function describeEditor(Au,lo){const $u=Au,Ru=lo?.workspace,Iu=Ru?canOpenView($u,Ru):!0;return{id:$u.surfaceId,title:$u.title,icon:$u.icon,order:$u.order,disabled:!Iu,disabledReason:Iu?void 0:Ru&&$u.unavailableReason?.(Ru)||"Not available right now"}}function EditorSelectorComponent(Au){const lo=Au.workspace,$u=useEditorPreviews(lo?.surfaceId??""),Ru=(Iu,Pu)=>{const Ou=describeEditor(Iu,Pu),Mu=$u[Ou.id];return Mu?{...Ou,badge:Mu.badge,details:Mu.details}:Ou};return jsxRuntimeExports.jsx(ViewSelector,{point:LoopEditorView,describe:Ru,context:Au,noneLabel:"Chat",ariaLabel:"Editor"})}const ShellPlugin={name:SHELL_PLUGIN_NAME,displayName:"Loop shell",description:"The Loop workspace’s extension points, and the editor choice.",octicon:"columns",emoji:"📑",config:{defaultEditor:NONE_EDITOR,showSelector:!0},dependencies:[configurePlugin(ShellPlugin$1,{point:LoopEditorView,describe:describeEditor,showSelector:!1,announce:Au=>requestSurface(Au),commandId:"loop.shell.cycleEditor",commandName:"Switch the editor",commandDescription:"Cycle through the editors beside the conversation, and none",keybinding:""})],contributionPoints:[LoopViewType,LoopEditorView],contributes:[contribution(LoopCommand,{name:"editor",aliases:["editors"],description:"Switch the editor beside the conversation",group:"Open",keybinding:"Mod+Alt+E",args:[{name:"editor",description:"Which editor: none, or a surface id. Omit to cycle.",required:!1,choices:()=>[NONE_EDITOR,...getEditorChoice().options]}],run:async({argv:Au})=>{const lo=Au.trim(),$u=lo===""?nextEditor():lo,Ru=[NONE_EDITOR,...getEditorChoice().options];if(!Ru.includes($u))throw new Error(`No editor called '${$u}'. There is: ${Ru.join(", ")}.`);if(!chooseEditor($u))throw new Error("No chat is on screen to host the editor.")}},{id:"editor"})],build:({config:Au})=>(seedEditorChoice(Au.defaultEditor||NONE_EDITOR),{components:Au.showSelector?[{id:"editor-selector",slot:LoopSlots.header,Component:EditorSelectorComponent}]:[]})};function NewChatAction({workspace:Au}){return Au?jsxRuntimeExports.jsx(IconButton,{icon:PlusIcon,"aria-label":"New conversation",title:"New conversation",variant:"invisible",size:"small",onClick:()=>{Au.submit("/new")}}):null}const PROMPT_PLUGIN_NAME="@datalayer/loop-plugin-prompt",PromptPlugin={name:PROMPT_PLUGIN_NAME,displayName:"Prompt",description:"Prompt commands: focus the composer, start over, and the +.",octicon:"paper-airplane",emoji:"🪶",contributes:[contribution(LoopCommand,{name:"prompt",description:"Focus the prompt",group:"Session",keybinding:"Mod+Alt+P",run:async()=>{if(!focusPrompt())throw new Error("No prompt is on screen to focus.")}},{id:"prompt"}),contribution(LoopCommand,{name:"new",aliases:["reset"],description:"Start the conversation over",group:"Session",keybinding:"Mod+Alt+R",run:async({workspace:Au})=>{const lo=Au.viewControls.newChat;if(!lo)throw new Error("No conversation is on screen to start over.");lo()}},{id:"new"})],build:()=>({components:[{id:"new-chat",slot:LoopSlots.promptAction,Component:NewChatAction}]})};function AgentspecPicker({workspace:Au}){const[lo,$u]=reactExports.useState([]),[Ru,Iu]=reactExports.useState(!1),[Pu,Ou]=reactExports.useState(Au.agentId),Mu=Au.sandbox.target,Du=Au.sandbox.state;reactExports.useEffect(()=>{let Fu=!1;return fetch(`${Au.serverUrl}/api/v1/agents`).then(zu=>zu.ok?zu.json():{agents:[]}).then(zu=>{Fu||$u(zu.agents??[])}).catch(()=>{}),()=>{Fu=!0}},[Au.serverUrl,Mu,Du]),reactExports.useEffect(()=>{Ou(Au.agentId)},[Au.agentId]);const Lu=reactExports.useCallback(async Fu=>{Iu(!0);try{(await fetch(`${Au.serverUrl}/api/v1/loop/sessions/${encodeURIComponent(Au.conversationId||Au.agentId||"session")}/agent`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({agent_id:Fu})})).ok&&(Ou(Fu),Au.setAgentId(Fu))}finally{Iu(!1)}},[Au.agentId,Au.conversationId,Au.serverUrl,Au.setAgentId]),Bu=lo.find(Fu=>Fu.id===Pu),ju=Bu?.name||getAgentspecs(Pu)?.name||Pu||"Agent";return lo.length===0?null:jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:1,children:[Ru?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):null,jsxRuntimeExports.jsxs(ActionMenu,{children:[jsxRuntimeExports.jsxs(ActionMenu.Button,{variant:"invisible",size:"small",children:[Bu?.emoji?`${Bu.emoji} `:"",ju]}),jsxRuntimeExports.jsx(ActionMenu.Overlay,{width:"medium",children:jsxRuntimeExports.jsx(ActionList,{selectionVariant:"single",children:lo.map(Fu=>jsxRuntimeExports.jsxs(ActionList.Item,{selected:Fu.id===Pu,onSelect:()=>{Lu(Fu.id)},children:[Fu.emoji?`${Fu.emoji} `:"",Fu.name||Fu.id,Fu.description?jsxRuntimeExports.jsx(ActionList.Description,{variant:"block",children:Fu.description}):null]},Fu.id))})})]})]})}const AGENTSPECS_PLUGIN_NAME="@datalayer/loop-plugin-agentspecs",AgentspecsPlugin={name:AGENTSPECS_PLUGIN_NAME,displayName:"Agentspecs",description:"Pick the agentspec this session runs.",octicon:"people",emoji:"🤖",build(){return{components:[{slot:LoopSlots.header,id:"agent-picker",Component:AgentspecPicker}]}},contributes:[contribution(LoopCommand,{name:"agents",aliases:["agent"],description:"Switch the agent this session is using",group:"Agents",keybinding:"Mod+Alt+A",args:[{name:"agent-id",description:"Agent to switch to"}],run:async({workspace:Au,argv:lo})=>{const $u=lo.trim();if(!$u)return{content:"Pick an agent from the header, or /agents <id>."};const Ru=await fetch(`${Au.serverUrl}/api/v1/loop/sessions/${encodeURIComponent(Au.conversationId||Au.agentId||"session")}/agent`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({agent_id:$u})});if(!Ru.ok)return{content:`Unknown agent: ${$u}`};const Iu=await Ru.json();return{content:`Now using ${Iu.name??Iu.agent_id}.`}}},{id:"agents"})]},CHAT_HEADER_PLUGIN_NAME="@datalayer/loop-plugin-chat-header",LazyHeaderView=reactExports.lazy(()=>__vitePreload(()=>import("./chunks/HeaderView-DVGhaRai.js"),[],import.meta.url));function HeaderView(Au){return jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(LazyHeaderView,{...Au})})}const ChatHeaderPlugin={name:CHAT_HEADER_PLUGIN_NAME,displayName:"Chat Header",description:"The conversation’s title bar: agent, kernel, actions.",octicon:"rows",emoji:"🏷️",contributes:[contribution(LoopChatHeader,{id:"chat-header",Component:HeaderView},{id:"chat-header"})]};function readA2uiToolResult(Au,lo){if(!Au)return null;let $u=Au;if(typeof Au=="string")try{$u=JSON.parse(Au)}catch{return null}if(typeof $u!="object"||$u===null||!Array.isArray($u.messages))return null;const Ru=$u,Iu=(Ru.messages??[]).map(Pu=>{const Ou=Pu;return Ou.createSurface&&Ou.createSurface.catalogId!==lo?{...Ou,createSurface:{...Ou.createSurface,catalogId:lo}}:Pu});return{...Ru,messages:Iu}}function isEmptyA2uiValue(Au){return Au==null?!0:typeof Au=="string"?Au.trim()==="":Array.isArray(Au)?Au.length===0:typeof Au=="boolean"?Au===!1:!1}const EMAIL_PATTERN=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function validateA2uiField(Au,lo){if(isEmptyA2uiValue(lo))return Au.required?`${Au.label} is required.`:null;if(Au.format==="email"&&typeof lo=="string"&&!EMAIL_PATTERN.test(lo.trim()))return`${Au.label} must be a valid email address.`;if(Au.pattern&&typeof lo=="string"){let $u;try{$u=new RegExp(Au.pattern).test(lo.trim())}catch{$u=!0}if(!$u)return`${Au.label} is not in the expected format.`}if(Au.minLength!==void 0&&typeof lo=="string"&&lo.trim().length<Au.minLength)return`${Au.label} must be at least ${Au.minLength} characters.`;if(Au.type==="slider"&&typeof lo=="number"){if(Au.min!==void 0&&lo<Au.min)return`${Au.label} must be at least ${Au.min}.`;if(Au.max!==void 0&&lo>Au.max)return`${Au.label} must be at most ${Au.max}.`}return null}function validateA2uiSubmission(Au,lo){return Au.map($u=>validateA2uiField($u,lo[$u.id])).filter($u=>$u!==null)}const ANSWER_DISPLAY_TYPE="application/vnd.datalayer.loop.answer+json";function answerSurface(Au,lo){return Au.type!==ANSWER_DISPLAY_TYPE?null:readA2uiToolResult(Au.data?.surface,lo)}function answerPress(Au,lo){const $u=lo.name.trim(),Ru=(Au.actions??[]).find(Iu=>Iu.name===$u);return Ru?{message:$u,forwardedProps:{loop:{action:{name:$u,display_id:Au.id,token:Ru.token,payload:{...lo.context}}}}}:{refused:`“${$u||"This button"}” was not offered here.`}}function AnswerShowsView({display:Au,send:lo}){const $u=reactExports.useMemo(()=>answerSurface(Au,SURFACE_CATALOG_ID),[Au]),Ru=useOwnCatalog(),[Iu,Pu]=reactExports.useState(null);if(!$u?.messages||$u.messages.length===0)return jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted"},children:Au.text});const Ou=Mu=>{const Du=answerPress(Au,Mu);if("refused"in Du){Pu(Du.refused);return}Pu(lo(Du.message,Du.forwardedProps)?null:"The chat is not ready to take it yet.")};return jsxRuntimeExports.jsx(InlineSurface,{messages:$u.messages,onAction:Ou,validationError:Iu,catalog:Ru},JSON.stringify(Au))}function SurfaceToolResult({context:Au,send:lo,onRendered:$u,onSubmitted:Ru}){const Iu=reactExports.useMemo(()=>Au.status==="complete"?readA2uiToolResult(Au.result,SURFACE_CATALOG_ID):null,[Au.status,Au.result]),Pu=Iu?.title??"the form",[Ou,Mu]=reactExports.useState(null),Du=useOwnCatalog();reactExports.useEffect(()=>{Iu?.messages&&Iu.messages.length>0&&$u?.({toolCallId:Au.toolCallId,surfaceId:Iu.surfaceId,title:Pu,messages:Iu.messages,result:Iu})},[Iu,Au.toolCallId]);const Lu=reactExports.useCallback(Bu=>{if(Bu.name!=="submit_a2ui_form")return;const ju=Bu.context??{},Fu=validateA2uiSubmission(Iu?.fieldRules??[],ju);if(Fu.length>0){Mu(Fu.join(" "));return}Mu(null),Ru?.({surfaceId:Bu.surfaceId,title:Pu,values:ju}),lo(encodeFormSubmission({title:Pu,surfaceId:Bu.surfaceId,values:ju}))||Mu("The chat is not ready to take the submission yet.")},[Iu,Pu,lo,Ru]);return!Iu?.messages||Iu.messages.length===0?jsxRuntimeExports.jsxs(Box,{border:"1px solid",borderColor:"border.default",borderRadius:2,px:3,py:2,bg:"canvas.default",display:"flex",alignItems:"center",gap:2,children:[jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,color:"fg.muted"},children:"Rendering A2UI surface..."})]}):jsxRuntimeExports.jsxs(Box,{display:"flex",flexDirection:"column",gap:2,children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"bold"},children:Pu}),jsxRuntimeExports.jsx(InlineSurface,{messages:Iu.messages,onAction:Lu,validationError:Ou,catalog:Du})]})}const A2UI_SURFACE_PLUGIN_NAME="@datalayer/loop-plugin-a2ui-surface",A2UI_SURFACE_RENDERER="a2ui-surface",A2UI_SURFACE_TYPE="application/vnd.datalayer.a2ui.surface+json";function surfaceToolNames(){const Au=new Set;for(const lo of Object.values(AGENTSPECS))for(const $u of lo.frontendRenderTools??[])$u.renderer===A2UI_SURFACE_RENDERER&&Au.add($u.tool);return Au}let counter=0;function createA2uiSurfacePlugin(Au={}){const lo=`a2ui-surface-${counter+=1}`;let $u;const Ru=(Du,Lu)=>$u?!$u(Du,Lu):!1;function Iu({workspace:Du}){const Lu=Du?.viewControls.send;return reactExports.useEffect(()=>($u=Lu,()=>{$u===Lu&&($u=void 0)}),[Lu]),null}function Pu({context:Du}){return Du?Du.status==="error"?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Du.defaultUI}):jsxRuntimeExports.jsx(SurfaceToolResult,{context:Du,send:Ru,onRendered:Au.onRendered,onSubmitted:Au.onSubmitted},Du.toolCallId):null}function Ou({display:Du}){return jsxRuntimeExports.jsx(AnswerShowsView,{display:Du,send:Ru})}return{name:counter===1?A2UI_SURFACE_PLUGIN_NAME:`${A2UI_SURFACE_PLUGIN_NAME}-${lo}`,displayName:"A2UI surfaces",description:"Generated surfaces drawn in the transcript, and submitted back to the agent.",octicon:"browser",emoji:"🪟",contributes:[contribution(Renderers,defineRenderer({type:A2UI_SURFACE_TYPE,component:Pu,rank:Au.onRendered||Au.onSubmitted?1:0}),{id:lo}),contribution(Renderers,defineRenderer({type:ANSWER_DISPLAY_TYPE,component:Ou}),{id:`${lo}:answer`}),...[...surfaceToolNames()].map(Du=>contribution(ToolBindings,{tool:Du,type:A2UI_SURFACE_TYPE},{id:`${lo}:${Du}`}))],build(){return{components:[{slot:LoopSlots.chatHeader,id:lo,Component:Iu}]}}}}const A2uiSurfacePlugin=createA2uiSurfacePlugin(),qrcode=function(Au,lo){let Iu=Au;const Pu=QRErrorCorrectionLevel[lo];let Ou=null,Mu=0,Du=null;const Lu=[],Bu={},ju=function(ed,td){Mu=Iu*4+17,Ou=(function(nd){const od=new Array(nd);for(let sd=0;sd<nd;sd+=1){od[sd]=new Array(nd);for(let ad=0;ad<nd;ad+=1)od[sd][ad]=null}return od})(Mu),Fu(0,0),Fu(Mu-7,0),Fu(0,Mu-7),Hu(),Uu(),Gu(ed,td),Iu>=7&&Vu(ed),Du==null&&(Du=Ju(Iu,Pu,Lu)),Wu(Du,td)},Fu=function(ed,td){for(let nd=-1;nd<=7;nd+=1)if(!(ed+nd<=-1||Mu<=ed+nd))for(let od=-1;od<=7;od+=1)td+od<=-1||Mu<=td+od||(0<=nd&&nd<=6&&(od==0||od==6)||0<=od&&od<=6&&(nd==0||nd==6)||2<=nd&&nd<=4&&2<=od&&od<=4?Ou[ed+nd][td+od]=!0:Ou[ed+nd][td+od]=!1)},zu=function(){let ed=0,td=0;for(let nd=0;nd<8;nd+=1){ju(!0,nd);const od=QRUtil.getLostPoint(Bu);(nd==0||ed>od)&&(ed=od,td=nd)}return td},Uu=function(){for(let ed=8;ed<Mu-8;ed+=1)Ou[ed][6]==null&&(Ou[ed][6]=ed%2==0);for(let ed=8;ed<Mu-8;ed+=1)Ou[6][ed]==null&&(Ou[6][ed]=ed%2==0)},Hu=function(){const ed=QRUtil.getPatternPosition(Iu);for(let td=0;td<ed.length;td+=1)for(let nd=0;nd<ed.length;nd+=1){const od=ed[td],sd=ed[nd];if(Ou[od][sd]==null)for(let ad=-2;ad<=2;ad+=1)for(let pd=-2;pd<=2;pd+=1)ad==-2||ad==2||pd==-2||pd==2||ad==0&&pd==0?Ou[od+ad][sd+pd]=!0:Ou[od+ad][sd+pd]=!1}},Vu=function(ed){const td=QRUtil.getBCHTypeNumber(Iu);for(let nd=0;nd<18;nd+=1){const od=!ed&&(td>>nd&1)==1;Ou[Math.floor(nd/3)][nd%3+Mu-8-3]=od}for(let nd=0;nd<18;nd+=1){const od=!ed&&(td>>nd&1)==1;Ou[nd%3+Mu-8-3][Math.floor(nd/3)]=od}},Gu=function(ed,td){const nd=Pu<<3|td,od=QRUtil.getBCHTypeInfo(nd);for(let sd=0;sd<15;sd+=1){const ad=!ed&&(od>>sd&1)==1;sd<6?Ou[sd][8]=ad:sd<8?Ou[sd+1][8]=ad:Ou[Mu-15+sd][8]=ad}for(let sd=0;sd<15;sd+=1){const ad=!ed&&(od>>sd&1)==1;sd<8?Ou[8][Mu-sd-1]=ad:sd<9?Ou[8][15-sd-1+1]=ad:Ou[8][15-sd-1]=ad}Ou[Mu-8][8]=!ed},Wu=function(ed,td){let nd=-1,od=Mu-1,sd=7,ad=0;const pd=QRUtil.getMaskFunction(td);for(let gd=Mu-1;gd>0;gd-=2)for(gd==6&&(gd-=1);;){for(let xd=0;xd<2;xd+=1)if(Ou[od][gd-xd]==null){let yd=!1;ad<ed.length&&(yd=(ed[ad]>>>sd&1)==1),pd(od,gd-xd)&&(yd=!yd),Ou[od][gd-xd]=yd,sd-=1,sd==-1&&(ad+=1,sd=7)}if(od+=nd,od<0||Mu<=od){od-=nd,nd=-nd;break}}},Ku=function(ed,td){let nd=0,od=0,sd=0;const ad=new Array(td.length),pd=new Array(td.length);for(let vd=0;vd<td.length;vd+=1){const wd=td[vd].dataCount,Td=td[vd].totalCount-wd;od=Math.max(od,wd),sd=Math.max(sd,Td),ad[vd]=new Array(wd);for(let ld=0;ld<ad[vd].length;ld+=1)ad[vd][ld]=255&ed.getBuffer()[ld+nd];nd+=wd;const cd=QRUtil.getErrorCorrectPolynomial(Td),md=qrPolynomial(ad[vd],cd.getLength()-1).mod(cd);pd[vd]=new Array(cd.getLength()-1);for(let ld=0;ld<pd[vd].length;ld+=1){const hd=ld+md.getLength()-pd[vd].length;pd[vd][ld]=hd>=0?md.getAt(hd):0}}let gd=0;for(let vd=0;vd<td.length;vd+=1)gd+=td[vd].totalCount;const xd=new Array(gd);let yd=0;for(let vd=0;vd<od;vd+=1)for(let wd=0;wd<td.length;wd+=1)vd<ad[wd].length&&(xd[yd]=ad[wd][vd],yd+=1);for(let vd=0;vd<sd;vd+=1)for(let wd=0;wd<td.length;wd+=1)vd<pd[wd].length&&(xd[yd]=pd[wd][vd],yd+=1);return xd},Ju=function(ed,td,nd){const od=QRRSBlock.getRSBlocks(ed,td),sd=qrBitBuffer();for(let pd=0;pd<nd.length;pd+=1){const gd=nd[pd];sd.put(gd.getMode(),4),sd.put(gd.getLength(),QRUtil.getLengthInBits(gd.getMode(),ed)),gd.write(sd)}let ad=0;for(let pd=0;pd<od.length;pd+=1)ad+=od[pd].dataCount;if(sd.getLengthInBits()>ad*8)throw"code length overflow. ("+sd.getLengthInBits()+">"+ad*8+")";for(sd.getLengthInBits()+4<=ad*8&&sd.put(0,4);sd.getLengthInBits()%8!=0;)sd.putBit(!1);for(;!(sd.getLengthInBits()>=ad*8||(sd.put(236,8),sd.getLengthInBits()>=ad*8));)sd.put(17,8);return Ku(sd,od)};Bu.addData=function(ed,td){td=td||"Byte";let nd=null;switch(td){case"Numeric":nd=qrNumber(ed);break;case"Alphanumeric":nd=qrAlphaNum(ed);break;case"Byte":nd=qr8BitByte(ed);break;case"Kanji":nd=qrKanji(ed);break;default:throw"mode:"+td}Lu.push(nd),Du=null},Bu.isDark=function(ed,td){if(ed<0||Mu<=ed||td<0||Mu<=td)throw ed+","+td;return Ou[ed][td]},Bu.getModuleCount=function(){return Mu},Bu.make=function(){if(Iu<1){let ed=1;for(;ed<40;ed++){const td=QRRSBlock.getRSBlocks(ed,Pu),nd=qrBitBuffer();for(let sd=0;sd<Lu.length;sd++){const ad=Lu[sd];nd.put(ad.getMode(),4),nd.put(ad.getLength(),QRUtil.getLengthInBits(ad.getMode(),ed)),ad.write(nd)}let od=0;for(let sd=0;sd<td.length;sd++)od+=td[sd].dataCount;if(nd.getLengthInBits()<=od*8)break}Iu=ed}ju(!1,zu())},Bu.createTableTag=function(ed,td){ed=ed||2,td=typeof td>"u"?ed*4:td;let nd="";nd+='<table style="',nd+=" border-width: 0px; border-style: none;",nd+=" border-collapse: collapse;",nd+=" padding: 0px; margin: "+td+"px;",nd+='">',nd+="<tbody>";for(let od=0;od<Bu.getModuleCount();od+=1){nd+="<tr>";for(let sd=0;sd<Bu.getModuleCount();sd+=1)nd+='<td style="',nd+=" border-width: 0px; border-style: none;",nd+=" border-collapse: collapse;",nd+=" padding: 0px; margin: 0px;",nd+=" width: "+ed+"px;",nd+=" height: "+ed+"px;",nd+=" background-color: ",nd+=Bu.isDark(od,sd)?"#000000":"#ffffff",nd+=";",nd+='"/>';nd+="</tr>"}return nd+="</tbody>",nd+="</table>",nd},Bu.createSvgTag=function(ed,td,nd,od){let sd={};typeof arguments[0]=="object"&&(sd=arguments[0],ed=sd.cellSize,td=sd.margin,nd=sd.alt,od=sd.title),ed=ed||2,td=typeof td>"u"?ed*4:td,nd=typeof nd=="string"?{text:nd}:nd||{},nd.text=nd.text||null,nd.id=nd.text?nd.id||"qrcode-description":null,od=typeof od=="string"?{text:od}:od||{},od.text=od.text||null,od.id=od.text?od.id||"qrcode-title":null;const ad=Bu.getModuleCount()*ed+td*2;let pd,gd,xd,yd,vd="",wd;for(wd="l"+ed+",0 0,"+ed+" -"+ed+",0 0,-"+ed+"z ",vd+='<svg version="1.1" xmlns="http://www.w3.org/2000/svg"',vd+=sd.scalable?"":' width="'+ad+'px" height="'+ad+'px"',vd+=' viewBox="0 0 '+ad+" "+ad+'" ',vd+=' preserveAspectRatio="xMinYMin meet"',vd+=od.text||nd.text?' role="img" aria-labelledby="'+Yu([od.id,nd.id].join(" ").trim())+'"':"",vd+=">",vd+=od.text?'<title id="'+Yu(od.id)+'">'+Yu(od.text)+"</title>":"",vd+=nd.text?'<description id="'+Yu(nd.id)+'">'+Yu(nd.text)+"</description>":"",vd+='<rect width="100%" height="100%" fill="white" cx="0" cy="0"/>',vd+='<path d="',xd=0;xd<Bu.getModuleCount();xd+=1)for(yd=xd*ed+td,pd=0;pd<Bu.getModuleCount();pd+=1)Bu.isDark(xd,pd)&&(gd=pd*ed+td,vd+="M"+gd+","+yd+wd);return vd+='" stroke="transparent" fill="black"/>',vd+="</svg>",vd},Bu.createDataURL=function(ed,td){ed=ed||2,td=typeof td>"u"?ed*4:td;const nd=Bu.getModuleCount()*ed+td*2,od=td,sd=nd-td;return createDataURL(nd,nd,function(ad,pd){if(od<=ad&&ad<sd&&od<=pd&&pd<sd){const gd=Math.floor((ad-od)/ed),xd=Math.floor((pd-od)/ed);return Bu.isDark(xd,gd)?0:1}else return 1})},Bu.createImgTag=function(ed,td,nd){ed=ed||2,td=typeof td>"u"?ed*4:td;const od=Bu.getModuleCount()*ed+td*2;let sd="";return sd+="<img",sd+=' src="',sd+=Bu.createDataURL(ed,td),sd+='"',sd+=' width="',sd+=od,sd+='"',sd+=' height="',sd+=od,sd+='"',nd&&(sd+=' alt="',sd+=Yu(nd),sd+='"'),sd+="/>",sd};const Yu=function(ed){let td="";for(let nd=0;nd<ed.length;nd+=1){const od=ed.charAt(nd);switch(od){case"<":td+="&lt;";break;case">":td+="&gt;";break;case"&":td+="&amp;";break;case'"':td+="&quot;";break;default:td+=od;break}}return td},Xu=function(ed){ed=typeof ed>"u"?2:ed;const nd=Bu.getModuleCount()*1+ed*2,od=ed,sd=nd-ed;let ad,pd,gd,xd,yd;const vd={"██":"█","█ ":"▀"," █":"▄"," ":" "},wd={"██":"▀","█ ":"▀"," █":" "," ":" "};let Td="";for(ad=0;ad<nd;ad+=2){for(gd=Math.floor((ad-od)/1),xd=Math.floor((ad+1-od)/1),pd=0;pd<nd;pd+=1)yd="█",od<=pd&&pd<sd&&od<=ad&&ad<sd&&Bu.isDark(gd,Math.floor((pd-od)/1))&&(yd=" "),od<=pd&&pd<sd&&od<=ad+1&&ad+1<sd&&Bu.isDark(xd,Math.floor((pd-od)/1))?yd+=" ":yd+="█",Td+=ed<1&&ad+1>=sd?wd[yd]:vd[yd];Td+=`
3841
+ }`;function SubagentPulse(){const Au=useAgentRuntimeActiveSubagentToolCallId(),lo=useAgentRuntimeSubagentActivity(Au??void 0),$u=useOptionalReactorPlatform(),Ru=lo[0]?.subagentName??Au??"",Iu=$u?.getOutput(AGENTS_PLUGIN_NAME)?.team?.members.find(Du=>Du.name===Ru),Pu=agentIcon(Iu?.icon);if(!Au)return null;const Mu=lo.some(Du=>Du.transport==="a2a")?`${Ru} is working over A2A…`:`${Ru} is working…`;return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("style",{children:KEYFRAMES}),jsxRuntimeExports.jsx(Tooltip,{text:Mu,direction:"n",children:jsxRuntimeExports.jsx(Box,{as:"button",type:"button","aria-label":Mu,"data-subagent-pulse":Ru,display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,p:0,border:0,bg:"transparent",color:"accent.fg",cursor:"default",animation:`${PULSE_ANIMATION} 1.4s ease-in-out infinite`,children:jsxRuntimeExports.jsx(Pu,{size:16})})})]})}const SUBAGENT_ACTIVITY_PLUGIN_NAME="@datalayer/loop-plugin-subagent-activity",SubagentActivityPlugin={name:SUBAGENT_ACTIVITY_PLUGIN_NAME,displayName:"Subagent activity",description:"A delegated agent's icon, pulsing in the prompt's header while it works.",octicon:"people",emoji:"👥",dependencies:[InputPromptPlugin],build:()=>({components:[{id:"subagent-pulse",slot:LoopSlots.inpromptMenu,order:0,Component:SubagentPulse}]})},A2UI_PLUGIN_NAME="@datalayer/loop-plugin-a2ui",A2uiPlugin={name:A2UI_PLUGIN_NAME,displayName:"A2UI surfaces",description:"The last execution, rendered as a surface rather than dumped.",octicon:"browser",emoji:"🖼",dependencies:[AgentsPlugin],contributes:[contribution(LoopViewType,{viewType:"a2ui",title:"Surface",icon:BrowserIcon,order:30,canOpen:Au=>Au.sandbox.state==="running"&&Au.sandbox.variant!=="pyodide",unavailableReason:Au=>Au.sandbox.variant==="pyodide"?"Surfaces are rendered by the server; this sandbox runs in the browser":"Needs a running sandbox",load:()=>__vitePreload(()=>import("./chunks/A2uiView-EmeKVJZp.js"),[],import.meta.url)},{id:"a2ui",order:30}),contribution(LoopCommand,{name:"a2ui",aliases:["surface"],description:"Show the last execution as a rendered surface",group:"Open",keybinding:"Mod+Alt+U",run:async({workspace:Au})=>{Au.setActiveViewType("a2ui")}},{id:"a2ui"})]},NONE_VIEW="none";let state={viewId:NONE_VIEW,options:[],allowNone:!0},announcer=()=>!0;const listeners=new Set;function notify(){for(const Au of[...listeners])Au()}function getViewChoice(){return state}function subscribeViewChoice(Au){return listeners.add(Au),()=>{listeners.delete(Au)}}function setViewAnnouncer(Au){const lo=announcer;return announcer=Au,()=>{announcer=lo}}function setViewOptions(Au,lo=!0){if(lo===state.allowNone&&Au.length===state.options.length&&Au.every((Ru,Iu)=>Ru===state.options[Iu]))return;state={viewId:!lo&&!Au.includes(state.viewId)?Au[0]??NONE_VIEW:state.viewId,options:Au,allowNone:lo},notify()}function chooseView(Au){return state={...state,viewId:Au},notify(),announcer(Au)}function seedViewChoice(Au){state.viewId!==Au&&(state={...state,viewId:Au},notify())}function nextView(){const Au=state.allowNone?[NONE_VIEW,...state.options]:[...state.options];if(Au.length===0)return NONE_VIEW;const lo=Au.indexOf(state.viewId);return Au[(lo+1)%Au.length]}function ViewSelector({point:Au,describe:lo,context:$u,noneLabel:Ru,ariaLabel:Iu,allowNone:Pu=!0}){const Ou=useContributions(Au),Mu=reactExports.useSyncExternalStore(subscribeViewChoice,getViewChoice),[Du,Lu]=reactExports.useState(null),Bu=reactExports.useRef(null),ju=()=>{Bu.current!==null&&(window.clearTimeout(Bu.current),Bu.current=null)},Fu=Vu=>{ju(),Lu(Vu)},zu=()=>{ju(),Bu.current=window.setTimeout(()=>{Lu(null),Bu.current=null},250)};reactExports.useEffect(()=>ju,[]);const Uu=reactExports.useMemo(()=>Ou.map(Vu=>lo(Vu.value,$u)).sort((Vu,Gu)=>(Vu.order??100)-(Gu.order??100)),[Ou,lo,$u]);if(reactExports.useEffect(()=>{setViewOptions(Uu.map(Vu=>Vu.id),Pu)},[Uu,Pu]),Uu.length<(Pu?1:2))return null;const Hu=Uu.find(Vu=>Vu.id===Du&&Vu.details);return jsxRuntimeExports.jsxs(Box$1,{sx:{marginLeft:"auto",display:"flex",alignItems:"center",position:"relative"},children:[jsxRuntimeExports.jsxs(SegmentedControl,{"aria-label":Iu,size:"small",children:[Pu?jsxRuntimeExports.jsx(SegmentedControl.Button,{selected:Mu.viewId===NONE_VIEW,onClick:()=>chooseView(NONE_VIEW),children:Ru}):null,Uu.map(Vu=>jsxRuntimeExports.jsx(SegmentedControl.Button,{selected:Mu.viewId===Vu.id,"aria-disabled":Vu.disabled||void 0,title:Vu.disabled?Vu.disabledReason:Vu.title,leadingIcon:Vu.icon,onMouseEnter:Vu.details?()=>Fu(Vu.id):void 0,onMouseLeave:Vu.details?zu:void 0,onClick:()=>{Vu.disabled||chooseView(Vu.id)},children:Vu.badge?`${Vu.title} (${Vu.badge})`:Vu.title},Vu.id))]}),Hu?jsxRuntimeExports.jsx(Box$1,{onMouseEnter:ju,onMouseLeave:zu,sx:{position:"absolute",top:"calc(100% + 6px)",right:0,minWidth:260,maxWidth:380,maxHeight:320,overflowY:"auto",p:2,bg:"canvas.overlay",border:"1px solid",borderColor:"border.default",borderRadius:2,boxShadow:"shadow.large",zIndex:40,fontSize:0,color:"fg.default",textAlign:"left"},children:Hu.details}):null]})}const SHELL_PLUGIN_NAME$1="@datalayer/reactor-shell",ShellView=defineContributionPoint("reactor.shell.view"),describeAsIs=Au=>Au,ShellPlugin$1={name:SHELL_PLUGIN_NAME$1,displayName:"Shell",description:"A view point, its selector, and the choice as a command.",octicon:"columns",emoji:"📑",config:{point:ShellView,describe:describeAsIs,slot:"header",defaultView:NONE_VIEW,showSelector:!0,allowNone:!0,noneLabel:"None",ariaLabel:"View",announce:()=>!0,commandId:"shell.cycleView",commandName:"Switch the view",commandDescription:"Cycle through the contributed views, and none",keybinding:"Mod+Alt+E"},contributionPoints:[ShellView],register:({config:Au,registerCommand:lo})=>{const $u=setViewAnnouncer(Au.announce),Ru=lo({id:Au.commandId,name:Au.commandName,description:Au.commandDescription,emoji:"📑",category:"Workspace",keybinding:Au.keybinding||void 0,execute:()=>{chooseView(nextView())}});return()=>{$u(),Ru()}},build:({config:Au})=>(seedViewChoice(Au.defaultView||NONE_VIEW),{components:Au.showSelector?[{id:"view-selector",slot:Au.slot,Component:lo=>jsxRuntimeExports.jsx(ViewSelector,{point:Au.point,describe:Au.describe,context:lo,noneLabel:Au.noneLabel,allowNone:Au.allowNone,ariaLabel:Au.ariaLabel})}]:[]})};setViewAnnouncer(requestSurface);const NONE_EDITOR=NONE_VIEW;let mappedFor=null,mapped=null;function getEditorChoice(){const Au=getViewChoice();return(Au!==mappedFor||!mapped)&&(mappedFor=Au,mapped={editorId:Au.viewId,options:Au.options}),mapped}const subscribeEditorChoice=subscribeViewChoice,setEditorOptions=setViewOptions,chooseEditor=chooseView,seedEditorChoice=seedViewChoice,nextEditor=nextView;let jupyterReact=null;function loadJupyterReact(){return jupyterReact?Promise.resolve(jupyterReact):__vitePreload(()=>import("./chunks/index-BN8Bbau-.js").then(Au=>Au.r),[],import.meta.url).then(Au=>(jupyterReact=Au,Au))}const PREVIEW_LENGTH=56;function stripped(Au){const $u=(Au.split(`
3842
+ `).find(Ru=>Ru.trim())??"").trim();return $u.length>PREVIEW_LENGTH?`${$u.slice(0,PREVIEW_LENGTH-1)}…`:$u||"(empty)"}function PreviewList({title:Au,rows:lo}){return jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold",display:"block",mb:1},children:Au}),lo.length===0?jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted"},children:"Empty so far."}):lo.map(($u,Ru)=>jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,py:"2px",alignItems:"baseline",children:[jsxRuntimeExports.jsxs(Text$3,{sx:{color:"fg.muted",flexShrink:0,fontFamily:"mono"},children:[Ru," · ",$u.kind]}),jsxRuntimeExports.jsx(Text$3,{sx:{fontFamily:"mono",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:$u.text})]},Ru))]})}function useOfferedEditors(){return reactExports.useSyncExternalStore(subscribeEditorChoice,()=>getEditorChoice().options)}function useNotebookRows(Au,lo){const[$u,Ru]=reactExports.useState(0);return reactExports.useEffect(()=>{if(!lo)return;let Iu=!1;const Pu=()=>Ru(Du=>Du+1),Ou=[],Mu=jupyterReact!==null;return loadJupyterReact().then(({notebookStore:Du})=>{if(!Iu)try{const Lu=Du.subscribe?.(Pu);Lu&&Ou.push(Lu);const Bu=Du.getState()?.notebooks?.get(Au)?.model;if(Bu){const ju=[Bu.contentChanged,Bu.cells?.changed];for(const Fu of ju)Fu?.connect&&(Fu.connect(Pu),Ou.push(()=>Fu.disconnect(Pu)))}Mu||Pu()}catch{}}),()=>{Iu=!0;for(const Du of Ou)try{Du()}catch{}}},[lo,Au,$u]),reactExports.useMemo(()=>{if(!lo)return null;const Iu=safeModel(Au);if(!Iu)return null;const Pu=[],Ou=Iu.cells;for(let Mu=0;Mu<Ou.length;Mu+=1){const Du=Ou.get(Mu);Pu.push({kind:Du.type,text:stripped(Du.sharedModel.getSource())})}return Pu},[lo,Au,$u])}function safeModel(Au){try{return jupyterReact?.notebookStore.getState()?.notebooks?.get(Au)?.model??null}catch{return null}}function useDocumentRows(Au,lo){const[$u,Ru]=reactExports.useState(null);return reactExports.useEffect(()=>{if(!lo){Ru(null);return}let Iu=!1,Pu,Ou=!1;return __vitePreload(()=>import("./chunks/PrismCss-CcU1ChRk.js").then(Mu=>Mu.a),[],import.meta.url).then(()=>__vitePreload(()=>import("./chunks/index-_nsBY26B.js"),[],import.meta.url)).then(({lexicalStore:Mu})=>{if(Iu)return;const Du=()=>{Ou||(Ou=!0,Mu.getState().readAllBlocks(Au,"brief").then(Lu=>{Ou=!1,!(Iu||!Array.isArray(Lu))&&Ru(Lu.map(Bu=>({kind:Bu.block_type??"block",text:stripped(Bu.preview??"")})))}).catch(()=>{Ou=!1,Iu||Ru(null)}))};Du(),Pu=Mu.subscribe(Du)}).catch(()=>{Iu||Ru(null)}),()=>{Iu=!0,Pu?.()}},[lo,Au]),$u}function useEditorPreviews(Au){const lo=useOfferedEditors(),$u=useNotebookRows(Au,lo.includes("notebook")),Ru=useDocumentRows(Au,lo.includes("document"));return reactExports.useMemo(()=>{const Iu={};return $u&&(Iu.notebook={badge:String($u.length),details:jsxRuntimeExports.jsx(PreviewList,{title:"Cells",rows:$u})}),Ru&&(Iu.document={badge:String(Ru.length),details:jsxRuntimeExports.jsx(PreviewList,{title:"Blocks",rows:Ru})}),Iu},[$u,Ru])}const SHELL_PLUGIN_NAME="@datalayer/loop-plugin-shell";function describeEditor(Au,lo){const $u=Au,Ru=lo?.workspace,Iu=Ru?canOpenView($u,Ru):!0;return{id:$u.surfaceId,title:$u.title,icon:$u.icon,order:$u.order,disabled:!Iu,disabledReason:Iu?void 0:Ru&&$u.unavailableReason?.(Ru)||"Not available right now"}}function EditorSelectorComponent(Au){const lo=Au.workspace,$u=useEditorPreviews(lo?.surfaceId??""),Ru=(Iu,Pu)=>{const Ou=describeEditor(Iu,Pu),Mu=$u[Ou.id];return Mu?{...Ou,badge:Mu.badge,details:Mu.details}:Ou};return jsxRuntimeExports.jsx(ViewSelector,{point:LoopEditorView,describe:Ru,context:Au,noneLabel:"Chat",ariaLabel:"Editor"})}const ShellPlugin={name:SHELL_PLUGIN_NAME,displayName:"Loop shell",description:"The Loop workspace’s extension points, and the editor choice.",octicon:"columns",emoji:"📑",config:{defaultEditor:NONE_EDITOR,showSelector:!0},dependencies:[configurePlugin(ShellPlugin$1,{point:LoopEditorView,describe:describeEditor,showSelector:!1,announce:Au=>requestSurface(Au),commandId:"loop.shell.cycleEditor",commandName:"Switch the editor",commandDescription:"Cycle through the editors beside the conversation, and none",keybinding:""})],contributionPoints:[LoopViewType,LoopEditorView],contributes:[contribution(LoopCommand,{name:"editor",aliases:["editors"],description:"Switch the editor beside the conversation",group:"Open",keybinding:"Mod+Alt+E",args:[{name:"editor",description:"Which editor: none, or a surface id. Omit to cycle.",required:!1,choices:()=>[NONE_EDITOR,...getEditorChoice().options]}],run:async({argv:Au})=>{const lo=Au.trim(),$u=lo===""?nextEditor():lo,Ru=[NONE_EDITOR,...getEditorChoice().options];if(!Ru.includes($u))throw new Error(`No editor called '${$u}'. There is: ${Ru.join(", ")}.`);if(!chooseEditor($u))throw new Error("No chat is on screen to host the editor.")}},{id:"editor"})],build:({config:Au})=>(seedEditorChoice(Au.defaultEditor||NONE_EDITOR),{components:Au.showSelector?[{id:"editor-selector",slot:LoopSlots.header,Component:EditorSelectorComponent}]:[]})};function NewChatAction({workspace:Au}){return Au?jsxRuntimeExports.jsx(IconButton,{icon:PlusIcon,"aria-label":"New conversation",title:"New conversation",variant:"invisible",size:"small",onClick:()=>{Au.submit("/new")}}):null}const PROMPT_PLUGIN_NAME="@datalayer/loop-plugin-prompt",PromptPlugin={name:PROMPT_PLUGIN_NAME,displayName:"Prompt",description:"Prompt commands: focus the composer, start over, and the +.",octicon:"paper-airplane",emoji:"🪶",contributes:[contribution(LoopCommand,{name:"prompt",description:"Focus the prompt",group:"Session",keybinding:"Mod+Alt+P",run:async()=>{if(!focusPrompt())throw new Error("No prompt is on screen to focus.")}},{id:"prompt"}),contribution(LoopCommand,{name:"new",aliases:["reset"],description:"Start the conversation over",group:"Session",keybinding:"Mod+Alt+R",run:async({workspace:Au})=>{const lo=Au.viewControls.newChat;if(!lo)throw new Error("No conversation is on screen to start over.");lo()}},{id:"new"})],build:()=>({components:[{id:"new-chat",slot:LoopSlots.promptAction,Component:NewChatAction}]})};function AgentspecPicker({workspace:Au}){const[lo,$u]=reactExports.useState([]),[Ru,Iu]=reactExports.useState(!1),[Pu,Ou]=reactExports.useState(Au.agentId),Mu=Au.sandbox.target,Du=Au.sandbox.state;reactExports.useEffect(()=>{let Fu=!1;return fetch(`${Au.serverUrl}/api/v1/agents`).then(zu=>zu.ok?zu.json():{agents:[]}).then(zu=>{Fu||$u(zu.agents??[])}).catch(()=>{}),()=>{Fu=!0}},[Au.serverUrl,Mu,Du]),reactExports.useEffect(()=>{Ou(Au.agentId)},[Au.agentId]);const Lu=reactExports.useCallback(async Fu=>{Iu(!0);try{(await fetch(`${Au.serverUrl}/api/v1/loop/sessions/${encodeURIComponent(Au.conversationId||Au.agentId||"session")}/agent`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({agent_id:Fu})})).ok&&(Ou(Fu),Au.setAgentId(Fu))}finally{Iu(!1)}},[Au.agentId,Au.conversationId,Au.serverUrl,Au.setAgentId]),Bu=lo.find(Fu=>Fu.id===Pu),ju=Bu?.name||getAgentspecs(Pu)?.name||Pu||"Agent";return lo.length===0?null:jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:1,children:[Ru?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):null,jsxRuntimeExports.jsxs(ActionMenu,{children:[jsxRuntimeExports.jsxs(ActionMenu.Button,{variant:"invisible",size:"small",children:[Bu?.emoji?`${Bu.emoji} `:"",ju]}),jsxRuntimeExports.jsx(ActionMenu.Overlay,{width:"medium",children:jsxRuntimeExports.jsx(ActionList,{selectionVariant:"single",children:lo.map(Fu=>jsxRuntimeExports.jsxs(ActionList.Item,{selected:Fu.id===Pu,onSelect:()=>{Lu(Fu.id)},children:[Fu.emoji?`${Fu.emoji} `:"",Fu.name||Fu.id,Fu.description?jsxRuntimeExports.jsx(ActionList.Description,{variant:"block",children:Fu.description}):null]},Fu.id))})})]})]})}const AGENTSPECS_PLUGIN_NAME="@datalayer/loop-plugin-agentspecs",AgentspecsPlugin={name:AGENTSPECS_PLUGIN_NAME,displayName:"Agentspecs",description:"Pick the agentspec this session runs.",octicon:"people",emoji:"🤖",build(){return{components:[{slot:LoopSlots.header,id:"agent-picker",Component:AgentspecPicker}]}},contributes:[contribution(LoopCommand,{name:"agents",aliases:["agent"],description:"Switch the agent this session is using",group:"Agents",keybinding:"Mod+Alt+A",args:[{name:"agent-id",description:"Agent to switch to"}],run:async({workspace:Au,argv:lo})=>{const $u=lo.trim();if(!$u)return{content:"Pick an agent from the header, or /agents <id>."};const Ru=await fetch(`${Au.serverUrl}/api/v1/loop/sessions/${encodeURIComponent(Au.conversationId||Au.agentId||"session")}/agent`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({agent_id:$u})});if(!Ru.ok)return{content:`Unknown agent: ${$u}`};const Iu=await Ru.json();return{content:`Now using ${Iu.name??Iu.agent_id}.`}}},{id:"agents"})]},CHAT_HEADER_PLUGIN_NAME="@datalayer/loop-plugin-chat-header",LazyHeaderView=reactExports.lazy(()=>__vitePreload(()=>import("./chunks/HeaderView-DVGhaRai.js"),[],import.meta.url));function HeaderView(Au){return jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(LazyHeaderView,{...Au})})}const ChatHeaderPlugin={name:CHAT_HEADER_PLUGIN_NAME,displayName:"Chat Header",description:"The conversation’s title bar: agent, kernel, actions.",octicon:"rows",emoji:"🏷️",contributes:[contribution(LoopChatHeader,{id:"chat-header",Component:HeaderView},{id:"chat-header"})]};function readA2uiToolResult(Au,lo){if(!Au)return null;let $u=Au;if(typeof Au=="string")try{$u=JSON.parse(Au)}catch{return null}if(typeof $u!="object"||$u===null||!Array.isArray($u.messages))return null;const Ru=$u,Iu=(Ru.messages??[]).map(Pu=>{const Ou=Pu;return Ou.createSurface&&Ou.createSurface.catalogId!==lo?{...Ou,createSurface:{...Ou.createSurface,catalogId:lo}}:Pu});return{...Ru,messages:Iu}}function isEmptyA2uiValue(Au){return Au==null?!0:typeof Au=="string"?Au.trim()==="":Array.isArray(Au)?Au.length===0:typeof Au=="boolean"?Au===!1:!1}const EMAIL_PATTERN=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function validateA2uiField(Au,lo){if(isEmptyA2uiValue(lo))return Au.required?`${Au.label} is required.`:null;if(Au.format==="email"&&typeof lo=="string"&&!EMAIL_PATTERN.test(lo.trim()))return`${Au.label} must be a valid email address.`;if(Au.pattern&&typeof lo=="string"){let $u;try{$u=new RegExp(Au.pattern).test(lo.trim())}catch{$u=!0}if(!$u)return`${Au.label} is not in the expected format.`}if(Au.minLength!==void 0&&typeof lo=="string"&&lo.trim().length<Au.minLength)return`${Au.label} must be at least ${Au.minLength} characters.`;if(Au.type==="slider"&&typeof lo=="number"){if(Au.min!==void 0&&lo<Au.min)return`${Au.label} must be at least ${Au.min}.`;if(Au.max!==void 0&&lo>Au.max)return`${Au.label} must be at most ${Au.max}.`}return null}function validateA2uiSubmission(Au,lo){return Au.map($u=>validateA2uiField($u,lo[$u.id])).filter($u=>$u!==null)}const ANSWER_DISPLAY_TYPE="application/vnd.datalayer.loop.answer+json";function answerSurface(Au,lo){return Au.type!==ANSWER_DISPLAY_TYPE?null:readA2uiToolResult(Au.data?.surface,lo)}function answerPress(Au,lo){const $u=lo.name.trim(),Ru=(Au.actions??[]).find(Iu=>Iu.name===$u);return Ru?{message:$u,forwardedProps:{loop:{action:{name:$u,display_id:Au.id,token:Ru.token,payload:{...lo.context}}}}}:{refused:`“${$u||"This button"}” was not offered here.`}}function AnswerShowsView({display:Au,send:lo}){const $u=reactExports.useMemo(()=>answerSurface(Au,SURFACE_CATALOG_ID),[Au]),Ru=useOwnCatalog(),[Iu,Pu]=reactExports.useState(null);if(!$u?.messages||$u.messages.length===0)return jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted"},children:Au.text});const Ou=Mu=>{const Du=answerPress(Au,Mu);if("refused"in Du){Pu(Du.refused);return}Pu(lo(Du.message,Du.forwardedProps)?null:"The chat is not ready to take it yet.")};return jsxRuntimeExports.jsx(InlineSurface,{messages:$u.messages,onAction:Ou,validationError:Iu,catalog:Ru},JSON.stringify(Au))}function SurfaceToolResult({context:Au,send:lo,onRendered:$u,onSubmitted:Ru}){const Iu=reactExports.useMemo(()=>Au.status==="complete"?readA2uiToolResult(Au.result,SURFACE_CATALOG_ID):null,[Au.status,Au.result]),Pu=Iu?.title??"the form",[Ou,Mu]=reactExports.useState(null),Du=useOwnCatalog();reactExports.useEffect(()=>{Iu?.messages&&Iu.messages.length>0&&$u?.({toolCallId:Au.toolCallId,surfaceId:Iu.surfaceId,title:Pu,messages:Iu.messages,result:Iu})},[Iu,Au.toolCallId]);const Lu=reactExports.useCallback(Bu=>{if(Bu.name!=="submit_a2ui_form")return;const ju=Bu.context??{},Fu=validateA2uiSubmission(Iu?.fieldRules??[],ju);if(Fu.length>0){Mu(Fu.join(" "));return}Mu(null),Ru?.({surfaceId:Bu.surfaceId,title:Pu,values:ju}),lo(encodeFormSubmission({title:Pu,surfaceId:Bu.surfaceId,values:ju}))||Mu("The chat is not ready to take the submission yet.")},[Iu,Pu,lo,Ru]);return!Iu?.messages||Iu.messages.length===0?jsxRuntimeExports.jsxs(Box,{border:"1px solid",borderColor:"border.default",borderRadius:2,px:3,py:2,bg:"canvas.default",display:"flex",alignItems:"center",gap:2,children:[jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,color:"fg.muted"},children:"Rendering A2UI surface..."})]}):jsxRuntimeExports.jsxs(Box,{display:"flex",flexDirection:"column",gap:2,children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"bold"},children:Pu}),jsxRuntimeExports.jsx(InlineSurface,{messages:Iu.messages,onAction:Lu,validationError:Ou,catalog:Du})]})}const A2UI_SURFACE_PLUGIN_NAME="@datalayer/loop-plugin-a2ui-surface",A2UI_SURFACE_RENDERER="a2ui-surface",A2UI_SURFACE_TYPE="application/vnd.datalayer.a2ui.surface+json";function surfaceToolNames(){const Au=new Set;for(const lo of Object.values(AGENTSPECS))for(const $u of lo.frontendRenderTools??[])$u.renderer===A2UI_SURFACE_RENDERER&&Au.add($u.tool);return Au}let counter=0;function createA2uiSurfacePlugin(Au={}){const lo=`a2ui-surface-${counter+=1}`;let $u;const Ru=(Du,Lu)=>$u?!$u(Du,Lu):!1;function Iu({workspace:Du}){const Lu=Du?.viewControls.send;return reactExports.useEffect(()=>($u=Lu,()=>{$u===Lu&&($u=void 0)}),[Lu]),null}function Pu({context:Du}){return Du?Du.status==="error"?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Du.defaultUI}):jsxRuntimeExports.jsx(SurfaceToolResult,{context:Du,send:Ru,onRendered:Au.onRendered,onSubmitted:Au.onSubmitted},Du.toolCallId):null}function Ou({display:Du}){return jsxRuntimeExports.jsx(AnswerShowsView,{display:Du,send:Ru})}return{name:counter===1?A2UI_SURFACE_PLUGIN_NAME:`${A2UI_SURFACE_PLUGIN_NAME}-${lo}`,displayName:"A2UI surfaces",description:"Generated surfaces drawn in the transcript, and submitted back to the agent.",octicon:"browser",emoji:"🪟",contributes:[contribution(Renderers,defineRenderer({type:A2UI_SURFACE_TYPE,component:Pu,rank:Au.onRendered||Au.onSubmitted?1:0}),{id:lo}),contribution(Renderers,defineRenderer({type:ANSWER_DISPLAY_TYPE,component:Ou}),{id:`${lo}:answer`}),...[...surfaceToolNames()].map(Du=>contribution(ToolBindings,{tool:Du,type:A2UI_SURFACE_TYPE},{id:`${lo}:${Du}`}))],build(){return{components:[{slot:LoopSlots.chatHeader,id:lo,Component:Iu}]}}}}const A2uiSurfacePlugin=createA2uiSurfacePlugin(),qrcode=function(Au,lo){let Iu=Au;const Pu=QRErrorCorrectionLevel[lo];let Ou=null,Mu=0,Du=null;const Lu=[],Bu={},ju=function(ed,td){Mu=Iu*4+17,Ou=(function(nd){const od=new Array(nd);for(let sd=0;sd<nd;sd+=1){od[sd]=new Array(nd);for(let ad=0;ad<nd;ad+=1)od[sd][ad]=null}return od})(Mu),Fu(0,0),Fu(Mu-7,0),Fu(0,Mu-7),Hu(),Uu(),Gu(ed,td),Iu>=7&&Vu(ed),Du==null&&(Du=Ju(Iu,Pu,Lu)),Wu(Du,td)},Fu=function(ed,td){for(let nd=-1;nd<=7;nd+=1)if(!(ed+nd<=-1||Mu<=ed+nd))for(let od=-1;od<=7;od+=1)td+od<=-1||Mu<=td+od||(0<=nd&&nd<=6&&(od==0||od==6)||0<=od&&od<=6&&(nd==0||nd==6)||2<=nd&&nd<=4&&2<=od&&od<=4?Ou[ed+nd][td+od]=!0:Ou[ed+nd][td+od]=!1)},zu=function(){let ed=0,td=0;for(let nd=0;nd<8;nd+=1){ju(!0,nd);const od=QRUtil.getLostPoint(Bu);(nd==0||ed>od)&&(ed=od,td=nd)}return td},Uu=function(){for(let ed=8;ed<Mu-8;ed+=1)Ou[ed][6]==null&&(Ou[ed][6]=ed%2==0);for(let ed=8;ed<Mu-8;ed+=1)Ou[6][ed]==null&&(Ou[6][ed]=ed%2==0)},Hu=function(){const ed=QRUtil.getPatternPosition(Iu);for(let td=0;td<ed.length;td+=1)for(let nd=0;nd<ed.length;nd+=1){const od=ed[td],sd=ed[nd];if(Ou[od][sd]==null)for(let ad=-2;ad<=2;ad+=1)for(let pd=-2;pd<=2;pd+=1)ad==-2||ad==2||pd==-2||pd==2||ad==0&&pd==0?Ou[od+ad][sd+pd]=!0:Ou[od+ad][sd+pd]=!1}},Vu=function(ed){const td=QRUtil.getBCHTypeNumber(Iu);for(let nd=0;nd<18;nd+=1){const od=!ed&&(td>>nd&1)==1;Ou[Math.floor(nd/3)][nd%3+Mu-8-3]=od}for(let nd=0;nd<18;nd+=1){const od=!ed&&(td>>nd&1)==1;Ou[nd%3+Mu-8-3][Math.floor(nd/3)]=od}},Gu=function(ed,td){const nd=Pu<<3|td,od=QRUtil.getBCHTypeInfo(nd);for(let sd=0;sd<15;sd+=1){const ad=!ed&&(od>>sd&1)==1;sd<6?Ou[sd][8]=ad:sd<8?Ou[sd+1][8]=ad:Ou[Mu-15+sd][8]=ad}for(let sd=0;sd<15;sd+=1){const ad=!ed&&(od>>sd&1)==1;sd<8?Ou[8][Mu-sd-1]=ad:sd<9?Ou[8][15-sd-1+1]=ad:Ou[8][15-sd-1]=ad}Ou[Mu-8][8]=!ed},Wu=function(ed,td){let nd=-1,od=Mu-1,sd=7,ad=0;const pd=QRUtil.getMaskFunction(td);for(let gd=Mu-1;gd>0;gd-=2)for(gd==6&&(gd-=1);;){for(let xd=0;xd<2;xd+=1)if(Ou[od][gd-xd]==null){let yd=!1;ad<ed.length&&(yd=(ed[ad]>>>sd&1)==1),pd(od,gd-xd)&&(yd=!yd),Ou[od][gd-xd]=yd,sd-=1,sd==-1&&(ad+=1,sd=7)}if(od+=nd,od<0||Mu<=od){od-=nd,nd=-nd;break}}},Ku=function(ed,td){let nd=0,od=0,sd=0;const ad=new Array(td.length),pd=new Array(td.length);for(let vd=0;vd<td.length;vd+=1){const wd=td[vd].dataCount,Td=td[vd].totalCount-wd;od=Math.max(od,wd),sd=Math.max(sd,Td),ad[vd]=new Array(wd);for(let ld=0;ld<ad[vd].length;ld+=1)ad[vd][ld]=255&ed.getBuffer()[ld+nd];nd+=wd;const cd=QRUtil.getErrorCorrectPolynomial(Td),md=qrPolynomial(ad[vd],cd.getLength()-1).mod(cd);pd[vd]=new Array(cd.getLength()-1);for(let ld=0;ld<pd[vd].length;ld+=1){const hd=ld+md.getLength()-pd[vd].length;pd[vd][ld]=hd>=0?md.getAt(hd):0}}let gd=0;for(let vd=0;vd<td.length;vd+=1)gd+=td[vd].totalCount;const xd=new Array(gd);let yd=0;for(let vd=0;vd<od;vd+=1)for(let wd=0;wd<td.length;wd+=1)vd<ad[wd].length&&(xd[yd]=ad[wd][vd],yd+=1);for(let vd=0;vd<sd;vd+=1)for(let wd=0;wd<td.length;wd+=1)vd<pd[wd].length&&(xd[yd]=pd[wd][vd],yd+=1);return xd},Ju=function(ed,td,nd){const od=QRRSBlock.getRSBlocks(ed,td),sd=qrBitBuffer();for(let pd=0;pd<nd.length;pd+=1){const gd=nd[pd];sd.put(gd.getMode(),4),sd.put(gd.getLength(),QRUtil.getLengthInBits(gd.getMode(),ed)),gd.write(sd)}let ad=0;for(let pd=0;pd<od.length;pd+=1)ad+=od[pd].dataCount;if(sd.getLengthInBits()>ad*8)throw"code length overflow. ("+sd.getLengthInBits()+">"+ad*8+")";for(sd.getLengthInBits()+4<=ad*8&&sd.put(0,4);sd.getLengthInBits()%8!=0;)sd.putBit(!1);for(;!(sd.getLengthInBits()>=ad*8||(sd.put(236,8),sd.getLengthInBits()>=ad*8));)sd.put(17,8);return Ku(sd,od)};Bu.addData=function(ed,td){td=td||"Byte";let nd=null;switch(td){case"Numeric":nd=qrNumber(ed);break;case"Alphanumeric":nd=qrAlphaNum(ed);break;case"Byte":nd=qr8BitByte(ed);break;case"Kanji":nd=qrKanji(ed);break;default:throw"mode:"+td}Lu.push(nd),Du=null},Bu.isDark=function(ed,td){if(ed<0||Mu<=ed||td<0||Mu<=td)throw ed+","+td;return Ou[ed][td]},Bu.getModuleCount=function(){return Mu},Bu.make=function(){if(Iu<1){let ed=1;for(;ed<40;ed++){const td=QRRSBlock.getRSBlocks(ed,Pu),nd=qrBitBuffer();for(let sd=0;sd<Lu.length;sd++){const ad=Lu[sd];nd.put(ad.getMode(),4),nd.put(ad.getLength(),QRUtil.getLengthInBits(ad.getMode(),ed)),ad.write(nd)}let od=0;for(let sd=0;sd<td.length;sd++)od+=td[sd].dataCount;if(nd.getLengthInBits()<=od*8)break}Iu=ed}ju(!1,zu())},Bu.createTableTag=function(ed,td){ed=ed||2,td=typeof td>"u"?ed*4:td;let nd="";nd+='<table style="',nd+=" border-width: 0px; border-style: none;",nd+=" border-collapse: collapse;",nd+=" padding: 0px; margin: "+td+"px;",nd+='">',nd+="<tbody>";for(let od=0;od<Bu.getModuleCount();od+=1){nd+="<tr>";for(let sd=0;sd<Bu.getModuleCount();sd+=1)nd+='<td style="',nd+=" border-width: 0px; border-style: none;",nd+=" border-collapse: collapse;",nd+=" padding: 0px; margin: 0px;",nd+=" width: "+ed+"px;",nd+=" height: "+ed+"px;",nd+=" background-color: ",nd+=Bu.isDark(od,sd)?"#000000":"#ffffff",nd+=";",nd+='"/>';nd+="</tr>"}return nd+="</tbody>",nd+="</table>",nd},Bu.createSvgTag=function(ed,td,nd,od){let sd={};typeof arguments[0]=="object"&&(sd=arguments[0],ed=sd.cellSize,td=sd.margin,nd=sd.alt,od=sd.title),ed=ed||2,td=typeof td>"u"?ed*4:td,nd=typeof nd=="string"?{text:nd}:nd||{},nd.text=nd.text||null,nd.id=nd.text?nd.id||"qrcode-description":null,od=typeof od=="string"?{text:od}:od||{},od.text=od.text||null,od.id=od.text?od.id||"qrcode-title":null;const ad=Bu.getModuleCount()*ed+td*2;let pd,gd,xd,yd,vd="",wd;for(wd="l"+ed+",0 0,"+ed+" -"+ed+",0 0,-"+ed+"z ",vd+='<svg version="1.1" xmlns="http://www.w3.org/2000/svg"',vd+=sd.scalable?"":' width="'+ad+'px" height="'+ad+'px"',vd+=' viewBox="0 0 '+ad+" "+ad+'" ',vd+=' preserveAspectRatio="xMinYMin meet"',vd+=od.text||nd.text?' role="img" aria-labelledby="'+Yu([od.id,nd.id].join(" ").trim())+'"':"",vd+=">",vd+=od.text?'<title id="'+Yu(od.id)+'">'+Yu(od.text)+"</title>":"",vd+=nd.text?'<description id="'+Yu(nd.id)+'">'+Yu(nd.text)+"</description>":"",vd+='<rect width="100%" height="100%" fill="white" cx="0" cy="0"/>',vd+='<path d="',xd=0;xd<Bu.getModuleCount();xd+=1)for(yd=xd*ed+td,pd=0;pd<Bu.getModuleCount();pd+=1)Bu.isDark(xd,pd)&&(gd=pd*ed+td,vd+="M"+gd+","+yd+wd);return vd+='" stroke="transparent" fill="black"/>',vd+="</svg>",vd},Bu.createDataURL=function(ed,td){ed=ed||2,td=typeof td>"u"?ed*4:td;const nd=Bu.getModuleCount()*ed+td*2,od=td,sd=nd-td;return createDataURL(nd,nd,function(ad,pd){if(od<=ad&&ad<sd&&od<=pd&&pd<sd){const gd=Math.floor((ad-od)/ed),xd=Math.floor((pd-od)/ed);return Bu.isDark(xd,gd)?0:1}else return 1})},Bu.createImgTag=function(ed,td,nd){ed=ed||2,td=typeof td>"u"?ed*4:td;const od=Bu.getModuleCount()*ed+td*2;let sd="";return sd+="<img",sd+=' src="',sd+=Bu.createDataURL(ed,td),sd+='"',sd+=' width="',sd+=od,sd+='"',sd+=' height="',sd+=od,sd+='"',nd&&(sd+=' alt="',sd+=Yu(nd),sd+='"'),sd+="/>",sd};const Yu=function(ed){let td="";for(let nd=0;nd<ed.length;nd+=1){const od=ed.charAt(nd);switch(od){case"<":td+="&lt;";break;case">":td+="&gt;";break;case"&":td+="&amp;";break;case'"':td+="&quot;";break;default:td+=od;break}}return td},Xu=function(ed){ed=typeof ed>"u"?2:ed;const nd=Bu.getModuleCount()*1+ed*2,od=ed,sd=nd-ed;let ad,pd,gd,xd,yd;const vd={"██":"█","█ ":"▀"," █":"▄"," ":" "},wd={"██":"▀","█ ":"▀"," █":" "," ":" "};let Td="";for(ad=0;ad<nd;ad+=2){for(gd=Math.floor((ad-od)/1),xd=Math.floor((ad+1-od)/1),pd=0;pd<nd;pd+=1)yd="█",od<=pd&&pd<sd&&od<=ad&&ad<sd&&Bu.isDark(gd,Math.floor((pd-od)/1))&&(yd=" "),od<=pd&&pd<sd&&od<=ad+1&&ad+1<sd&&Bu.isDark(xd,Math.floor((pd-od)/1))?yd+=" ":yd+="█",Td+=ed<1&&ad+1>=sd?wd[yd]:vd[yd];Td+=`
3843
3843
  `}return nd%2&&ed>0?Td.substring(0,Td.length-nd-1)+Array(nd+1).join("▀"):Td.substring(0,Td.length-1)};return Bu.createASCII=function(ed,td){if(ed=ed||1,ed<2)return Xu(td);ed-=1,td=typeof td>"u"?ed*2:td;const nd=Bu.getModuleCount()*ed+td*2,od=td,sd=nd-td;let ad,pd,gd,xd;const yd=Array(ed+1).join("██"),vd=Array(ed+1).join(" ");let wd="",Td="";for(ad=0;ad<nd;ad+=1){for(gd=Math.floor((ad-od)/ed),Td="",pd=0;pd<nd;pd+=1)xd=1,od<=pd&&pd<sd&&od<=ad&&ad<sd&&Bu.isDark(gd,Math.floor((pd-od)/ed))&&(xd=0),Td+=xd?yd:vd;for(gd=0;gd<ed;gd+=1)wd+=Td+`
3844
3844
  `}return wd.substring(0,wd.length-1)},Bu.renderTo2dContext=function(ed,td){td=td||2;const nd=Bu.getModuleCount();for(let od=0;od<nd;od++)for(let sd=0;sd<nd;sd++)ed.fillStyle=Bu.isDark(od,sd)?"black":"white",ed.fillRect(sd*td,od*td,td,td)},Bu};qrcode.stringToBytes=function(Au){const lo=[];for(let $u=0;$u<Au.length;$u+=1){const Ru=Au.charCodeAt($u);lo.push(Ru&255)}return lo};qrcode.createStringToBytes=function(Au,lo){const $u=(function(){const Iu=base64DecodeInputStream(Au),Pu=function(){const Du=Iu.read();if(Du==-1)throw"eof";return Du};let Ou=0;const Mu={};for(;;){const Du=Iu.read();if(Du==-1)break;const Lu=Pu(),Bu=Pu(),ju=Pu(),Fu=String.fromCharCode(Du<<8|Lu),zu=Bu<<8|ju;Mu[Fu]=zu,Ou+=1}if(Ou!=lo)throw Ou+" != "+lo;return Mu})(),Ru=63;return function(Iu){const Pu=[];for(let Ou=0;Ou<Iu.length;Ou+=1){const Mu=Iu.charCodeAt(Ou);if(Mu<128)Pu.push(Mu);else{const Du=$u[Iu.charAt(Ou)];typeof Du=="number"?(Du&255)==Du?Pu.push(Du):(Pu.push(Du>>>8),Pu.push(Du&255)):Pu.push(Ru)}}return Pu}};const QRMode={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},QRErrorCorrectionLevel={L:1,M:0,Q:3,H:2},QRMaskPattern={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},QRUtil=(function(){const Au=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],lo=1335,$u=7973,Ru=21522,Iu={},Pu=function(Ou){let Mu=0;for(;Ou!=0;)Mu+=1,Ou>>>=1;return Mu};return Iu.getBCHTypeInfo=function(Ou){let Mu=Ou<<10;for(;Pu(Mu)-Pu(lo)>=0;)Mu^=lo<<Pu(Mu)-Pu(lo);return(Ou<<10|Mu)^Ru},Iu.getBCHTypeNumber=function(Ou){let Mu=Ou<<12;for(;Pu(Mu)-Pu($u)>=0;)Mu^=$u<<Pu(Mu)-Pu($u);return Ou<<12|Mu},Iu.getPatternPosition=function(Ou){return Au[Ou-1]},Iu.getMaskFunction=function(Ou){switch(Ou){case QRMaskPattern.PATTERN000:return function(Mu,Du){return(Mu+Du)%2==0};case QRMaskPattern.PATTERN001:return function(Mu,Du){return Mu%2==0};case QRMaskPattern.PATTERN010:return function(Mu,Du){return Du%3==0};case QRMaskPattern.PATTERN011:return function(Mu,Du){return(Mu+Du)%3==0};case QRMaskPattern.PATTERN100:return function(Mu,Du){return(Math.floor(Mu/2)+Math.floor(Du/3))%2==0};case QRMaskPattern.PATTERN101:return function(Mu,Du){return Mu*Du%2+Mu*Du%3==0};case QRMaskPattern.PATTERN110:return function(Mu,Du){return(Mu*Du%2+Mu*Du%3)%2==0};case QRMaskPattern.PATTERN111:return function(Mu,Du){return(Mu*Du%3+(Mu+Du)%2)%2==0};default:throw"bad maskPattern:"+Ou}},Iu.getErrorCorrectPolynomial=function(Ou){let Mu=qrPolynomial([1],0);for(let Du=0;Du<Ou;Du+=1)Mu=Mu.multiply(qrPolynomial([1,QRMath.gexp(Du)],0));return Mu},Iu.getLengthInBits=function(Ou,Mu){if(1<=Mu&&Mu<10)switch(Ou){case QRMode.MODE_NUMBER:return 10;case QRMode.MODE_ALPHA_NUM:return 9;case QRMode.MODE_8BIT_BYTE:return 8;case QRMode.MODE_KANJI:return 8;default:throw"mode:"+Ou}else if(Mu<27)switch(Ou){case QRMode.MODE_NUMBER:return 12;case QRMode.MODE_ALPHA_NUM:return 11;case QRMode.MODE_8BIT_BYTE:return 16;case QRMode.MODE_KANJI:return 10;default:throw"mode:"+Ou}else if(Mu<41)switch(Ou){case QRMode.MODE_NUMBER:return 14;case QRMode.MODE_ALPHA_NUM:return 13;case QRMode.MODE_8BIT_BYTE:return 16;case QRMode.MODE_KANJI:return 12;default:throw"mode:"+Ou}else throw"type:"+Mu},Iu.getLostPoint=function(Ou){const Mu=Ou.getModuleCount();let Du=0;for(let ju=0;ju<Mu;ju+=1)for(let Fu=0;Fu<Mu;Fu+=1){let zu=0;const Uu=Ou.isDark(ju,Fu);for(let Hu=-1;Hu<=1;Hu+=1)if(!(ju+Hu<0||Mu<=ju+Hu))for(let Vu=-1;Vu<=1;Vu+=1)Fu+Vu<0||Mu<=Fu+Vu||Hu==0&&Vu==0||Uu==Ou.isDark(ju+Hu,Fu+Vu)&&(zu+=1);zu>5&&(Du+=3+zu-5)}for(let ju=0;ju<Mu-1;ju+=1)for(let Fu=0;Fu<Mu-1;Fu+=1){let zu=0;Ou.isDark(ju,Fu)&&(zu+=1),Ou.isDark(ju+1,Fu)&&(zu+=1),Ou.isDark(ju,Fu+1)&&(zu+=1),Ou.isDark(ju+1,Fu+1)&&(zu+=1),(zu==0||zu==4)&&(Du+=3)}for(let ju=0;ju<Mu;ju+=1)for(let Fu=0;Fu<Mu-6;Fu+=1)Ou.isDark(ju,Fu)&&!Ou.isDark(ju,Fu+1)&&Ou.isDark(ju,Fu+2)&&Ou.isDark(ju,Fu+3)&&Ou.isDark(ju,Fu+4)&&!Ou.isDark(ju,Fu+5)&&Ou.isDark(ju,Fu+6)&&(Du+=40);for(let ju=0;ju<Mu;ju+=1)for(let Fu=0;Fu<Mu-6;Fu+=1)Ou.isDark(Fu,ju)&&!Ou.isDark(Fu+1,ju)&&Ou.isDark(Fu+2,ju)&&Ou.isDark(Fu+3,ju)&&Ou.isDark(Fu+4,ju)&&!Ou.isDark(Fu+5,ju)&&Ou.isDark(Fu+6,ju)&&(Du+=40);let Lu=0;for(let ju=0;ju<Mu;ju+=1)for(let Fu=0;Fu<Mu;Fu+=1)Ou.isDark(Fu,ju)&&(Lu+=1);const Bu=Math.abs(100*Lu/Mu/Mu-50)/5;return Du+=Bu*10,Du},Iu})(),QRMath=(function(){const Au=new Array(256),lo=new Array(256);for(let Ru=0;Ru<8;Ru+=1)Au[Ru]=1<<Ru;for(let Ru=8;Ru<256;Ru+=1)Au[Ru]=Au[Ru-4]^Au[Ru-5]^Au[Ru-6]^Au[Ru-8];for(let Ru=0;Ru<255;Ru+=1)lo[Au[Ru]]=Ru;const $u={};return $u.glog=function(Ru){if(Ru<1)throw"glog("+Ru+")";return lo[Ru]},$u.gexp=function(Ru){for(;Ru<0;)Ru+=255;for(;Ru>=256;)Ru-=255;return Au[Ru]},$u})(),qrPolynomial=function(Au,lo){if(typeof Au.length>"u")throw Au.length+"/"+lo;const $u=(function(){let Iu=0;for(;Iu<Au.length&&Au[Iu]==0;)Iu+=1;const Pu=new Array(Au.length-Iu+lo);for(let Ou=0;Ou<Au.length-Iu;Ou+=1)Pu[Ou]=Au[Ou+Iu];return Pu})(),Ru={};return Ru.getAt=function(Iu){return $u[Iu]},Ru.getLength=function(){return $u.length},Ru.multiply=function(Iu){const Pu=new Array(Ru.getLength()+Iu.getLength()-1);for(let Ou=0;Ou<Ru.getLength();Ou+=1)for(let Mu=0;Mu<Iu.getLength();Mu+=1)Pu[Ou+Mu]^=QRMath.gexp(QRMath.glog(Ru.getAt(Ou))+QRMath.glog(Iu.getAt(Mu)));return qrPolynomial(Pu,0)},Ru.mod=function(Iu){if(Ru.getLength()-Iu.getLength()<0)return Ru;const Pu=QRMath.glog(Ru.getAt(0))-QRMath.glog(Iu.getAt(0)),Ou=new Array(Ru.getLength());for(let Mu=0;Mu<Ru.getLength();Mu+=1)Ou[Mu]=Ru.getAt(Mu);for(let Mu=0;Mu<Iu.getLength();Mu+=1)Ou[Mu]^=QRMath.gexp(QRMath.glog(Iu.getAt(Mu))+Pu);return qrPolynomial(Ou,0).mod(Iu)},Ru},QRRSBlock=(function(){const Au=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12,7,37,13],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]],lo=function(Iu,Pu){const Ou={};return Ou.totalCount=Iu,Ou.dataCount=Pu,Ou},$u={},Ru=function(Iu,Pu){switch(Pu){case QRErrorCorrectionLevel.L:return Au[(Iu-1)*4+0];case QRErrorCorrectionLevel.M:return Au[(Iu-1)*4+1];case QRErrorCorrectionLevel.Q:return Au[(Iu-1)*4+2];case QRErrorCorrectionLevel.H:return Au[(Iu-1)*4+3];default:return}};return $u.getRSBlocks=function(Iu,Pu){const Ou=Ru(Iu,Pu);if(typeof Ou>"u")throw"bad rs block @ typeNumber:"+Iu+"/errorCorrectionLevel:"+Pu;const Mu=Ou.length/3,Du=[];for(let Lu=0;Lu<Mu;Lu+=1){const Bu=Ou[Lu*3+0],ju=Ou[Lu*3+1],Fu=Ou[Lu*3+2];for(let zu=0;zu<Bu;zu+=1)Du.push(lo(ju,Fu))}return Du},$u})(),qrBitBuffer=function(){const Au=[];let lo=0;const $u={};return $u.getBuffer=function(){return Au},$u.getAt=function(Ru){const Iu=Math.floor(Ru/8);return(Au[Iu]>>>7-Ru%8&1)==1},$u.put=function(Ru,Iu){for(let Pu=0;Pu<Iu;Pu+=1)$u.putBit((Ru>>>Iu-Pu-1&1)==1)},$u.getLengthInBits=function(){return lo},$u.putBit=function(Ru){const Iu=Math.floor(lo/8);Au.length<=Iu&&Au.push(0),Ru&&(Au[Iu]|=128>>>lo%8),lo+=1},$u},qrNumber=function(Au){const lo=QRMode.MODE_NUMBER,$u=Au,Ru={};Ru.getMode=function(){return lo},Ru.getLength=function(Ou){return $u.length},Ru.write=function(Ou){const Mu=$u;let Du=0;for(;Du+2<Mu.length;)Ou.put(Iu(Mu.substring(Du,Du+3)),10),Du+=3;Du<Mu.length&&(Mu.length-Du==1?Ou.put(Iu(Mu.substring(Du,Du+1)),4):Mu.length-Du==2&&Ou.put(Iu(Mu.substring(Du,Du+2)),7))};const Iu=function(Ou){let Mu=0;for(let Du=0;Du<Ou.length;Du+=1)Mu=Mu*10+Pu(Ou.charAt(Du));return Mu},Pu=function(Ou){if("0"<=Ou&&Ou<="9")return Ou.charCodeAt(0)-48;throw"illegal char :"+Ou};return Ru},qrAlphaNum=function(Au){const lo=QRMode.MODE_ALPHA_NUM,$u=Au,Ru={};Ru.getMode=function(){return lo},Ru.getLength=function(Pu){return $u.length},Ru.write=function(Pu){const Ou=$u;let Mu=0;for(;Mu+1<Ou.length;)Pu.put(Iu(Ou.charAt(Mu))*45+Iu(Ou.charAt(Mu+1)),11),Mu+=2;Mu<Ou.length&&Pu.put(Iu(Ou.charAt(Mu)),6)};const Iu=function(Pu){if("0"<=Pu&&Pu<="9")return Pu.charCodeAt(0)-48;if("A"<=Pu&&Pu<="Z")return Pu.charCodeAt(0)-65+10;switch(Pu){case" ":return 36;case"$":return 37;case"%":return 38;case"*":return 39;case"+":return 40;case"-":return 41;case".":return 42;case"/":return 43;case":":return 44;default:throw"illegal char :"+Pu}};return Ru},qr8BitByte=function(Au){const lo=QRMode.MODE_8BIT_BYTE,$u=qrcode.stringToBytes(Au),Ru={};return Ru.getMode=function(){return lo},Ru.getLength=function(Iu){return $u.length},Ru.write=function(Iu){for(let Pu=0;Pu<$u.length;Pu+=1)Iu.put($u[Pu],8)},Ru},qrKanji=function(Au){const lo=QRMode.MODE_KANJI,$u=qrcode.stringToBytes;(function(Pu,Ou){const Mu=$u(Pu);if(Mu.length!=2||(Mu[0]<<8|Mu[1])!=Ou)throw"sjis not supported."})("友",38726);const Ru=$u(Au),Iu={};return Iu.getMode=function(){return lo},Iu.getLength=function(Pu){return~~(Ru.length/2)},Iu.write=function(Pu){const Ou=Ru;let Mu=0;for(;Mu+1<Ou.length;){let Du=(255&Ou[Mu])<<8|255&Ou[Mu+1];if(33088<=Du&&Du<=40956)Du-=33088;else if(57408<=Du&&Du<=60351)Du-=49472;else throw"illegal char at "+(Mu+1)+"/"+Du;Du=(Du>>>8&255)*192+(Du&255),Pu.put(Du,13),Mu+=2}if(Mu<Ou.length)throw"illegal char at "+(Mu+1)},Iu},byteArrayOutputStream=function(){const Au=[],lo={};return lo.writeByte=function($u){Au.push($u&255)},lo.writeShort=function($u){lo.writeByte($u),lo.writeByte($u>>>8)},lo.writeBytes=function($u,Ru,Iu){Ru=Ru||0,Iu=Iu||$u.length;for(let Pu=0;Pu<Iu;Pu+=1)lo.writeByte($u[Pu+Ru])},lo.writeString=function($u){for(let Ru=0;Ru<$u.length;Ru+=1)lo.writeByte($u.charCodeAt(Ru))},lo.toByteArray=function(){return Au},lo.toString=function(){let $u="";$u+="[";for(let Ru=0;Ru<Au.length;Ru+=1)Ru>0&&($u+=","),$u+=Au[Ru];return $u+="]",$u},lo},base64EncodeOutputStream=function(){let Au=0,lo=0,$u=0,Ru="";const Iu={},Pu=function(Mu){Ru+=String.fromCharCode(Ou(Mu&63))},Ou=function(Mu){if(Mu<0)throw"n:"+Mu;if(Mu<26)return 65+Mu;if(Mu<52)return 97+(Mu-26);if(Mu<62)return 48+(Mu-52);if(Mu==62)return 43;if(Mu==63)return 47;throw"n:"+Mu};return Iu.writeByte=function(Mu){for(Au=Au<<8|Mu&255,lo+=8,$u+=1;lo>=6;)Pu(Au>>>lo-6),lo-=6},Iu.flush=function(){if(lo>0&&(Pu(Au<<6-lo),Au=0,lo=0),$u%3!=0){const Mu=3-$u%3;for(let Du=0;Du<Mu;Du+=1)Ru+="="}},Iu.toString=function(){return Ru},Iu},base64DecodeInputStream=function(Au){const lo=Au;let $u=0,Ru=0,Iu=0;const Pu={};Pu.read=function(){for(;Iu<8;){if($u>=lo.length){if(Iu==0)return-1;throw"unexpected end of file./"+Iu}const Du=lo.charAt($u);if($u+=1,Du=="=")return Iu=0,-1;if(Du.match(/^\s$/))continue;Ru=Ru<<6|Ou(Du.charCodeAt(0)),Iu+=6}const Mu=Ru>>>Iu-8&255;return Iu-=8,Mu};const Ou=function(Mu){if(65<=Mu&&Mu<=90)return Mu-65;if(97<=Mu&&Mu<=122)return Mu-97+26;if(48<=Mu&&Mu<=57)return Mu-48+52;if(Mu==43)return 62;if(Mu==47)return 63;throw"c:"+Mu};return Pu},gifImage=function(Au,lo){const $u=Au,Ru=lo,Iu=new Array(Au*lo),Pu={};Pu.setPixel=function(Lu,Bu,ju){Iu[Bu*$u+Lu]=ju},Pu.write=function(Lu){Lu.writeString("GIF87a"),Lu.writeShort($u),Lu.writeShort(Ru),Lu.writeByte(128),Lu.writeByte(0),Lu.writeByte(0),Lu.writeByte(0),Lu.writeByte(0),Lu.writeByte(0),Lu.writeByte(255),Lu.writeByte(255),Lu.writeByte(255),Lu.writeString(","),Lu.writeShort(0),Lu.writeShort(0),Lu.writeShort($u),Lu.writeShort(Ru),Lu.writeByte(0);const Bu=2,ju=Mu(Bu);Lu.writeByte(Bu);let Fu=0;for(;ju.length-Fu>255;)Lu.writeByte(255),Lu.writeBytes(ju,Fu,255),Fu+=255;Lu.writeByte(ju.length-Fu),Lu.writeBytes(ju,Fu,ju.length-Fu),Lu.writeByte(0),Lu.writeString(";")};const Ou=function(Lu){const Bu=Lu;let ju=0,Fu=0;const zu={};return zu.write=function(Uu,Hu){if(Uu>>>Hu)throw"length over";for(;ju+Hu>=8;)Bu.writeByte(255&(Uu<<ju|Fu)),Hu-=8-ju,Uu>>>=8-ju,Fu=0,ju=0;Fu=Uu<<ju|Fu,ju=ju+Hu},zu.flush=function(){ju>0&&Bu.writeByte(Fu)},zu},Mu=function(Lu){const Bu=1<<Lu,ju=(1<<Lu)+1;let Fu=Lu+1;const zu=Du();for(let Wu=0;Wu<Bu;Wu+=1)zu.add(String.fromCharCode(Wu));zu.add(String.fromCharCode(Bu)),zu.add(String.fromCharCode(ju));const Uu=byteArrayOutputStream(),Hu=Ou(Uu);Hu.write(Bu,Fu);let Vu=0,Gu=String.fromCharCode(Iu[Vu]);for(Vu+=1;Vu<Iu.length;){const Wu=String.fromCharCode(Iu[Vu]);Vu+=1,zu.contains(Gu+Wu)?Gu=Gu+Wu:(Hu.write(zu.indexOf(Gu),Fu),zu.size()<4095&&(zu.size()==1<<Fu&&(Fu+=1),zu.add(Gu+Wu)),Gu=Wu)}return Hu.write(zu.indexOf(Gu),Fu),Hu.write(ju,Fu),Hu.flush(),Uu.toByteArray()},Du=function(){const Lu={};let Bu=0;const ju={};return ju.add=function(Fu){if(ju.contains(Fu))throw"dup key:"+Fu;Lu[Fu]=Bu,Bu+=1},ju.size=function(){return Bu},ju.indexOf=function(Fu){return Lu[Fu]},ju.contains=function(Fu){return typeof Lu[Fu]<"u"},ju};return Pu},createDataURL=function(Au,lo,$u){const Ru=gifImage(Au,lo);for(let Mu=0;Mu<lo;Mu+=1)for(let Du=0;Du<Au;Du+=1)Ru.setPixel(Du,Mu,$u(Du,Mu));const Iu=byteArrayOutputStream();Ru.write(Iu);const Pu=base64EncodeOutputStream(),Ou=Iu.toByteArray();for(let Mu=0;Mu<Ou.length;Mu+=1)Pu.writeByte(Ou[Mu]);return Pu.flush(),"data:image/gif;base64,"+Pu};qrcode.stringToBytes;function _extends(){return _extends=Object.assign?Object.assign.bind():function(Au){for(var lo=1;lo<arguments.length;lo++){var $u=arguments[lo];for(var Ru in $u)({}).hasOwnProperty.call($u,Ru)&&(Au[Ru]=$u[Ru])}return Au},_extends.apply(null,arguments)}function _objectWithoutProperties(Au,lo){if(Au==null)return{};var $u,Ru,Iu=_objectWithoutPropertiesLoose(Au,lo);if(Object.getOwnPropertySymbols){var Pu=Object.getOwnPropertySymbols(Au);for(Ru=0;Ru<Pu.length;Ru++)$u=Pu[Ru],lo.indexOf($u)===-1&&{}.propertyIsEnumerable.call(Au,$u)&&(Iu[$u]=Au[$u])}return Iu}function _objectWithoutPropertiesLoose(Au,lo){if(Au==null)return{};var $u={};for(var Ru in Au)if({}.hasOwnProperty.call(Au,Ru)){if(lo.indexOf(Ru)!==-1)continue;$u[Ru]=Au[Ru]}return $u}var _excluded$1=["bgColor","bgD","fgD","fgColor","size","title","viewBoxSize","xmlns"],propTypes$1={bgColor:s$5.oneOfType([s$5.object,s$5.string]).isRequired,bgD:s$5.string.isRequired,fgColor:s$5.oneOfType([s$5.object,s$5.string]).isRequired,fgD:s$5.string.isRequired,size:s$5.number.isRequired,title:s$5.string,viewBoxSize:s$5.number.isRequired,xmlns:s$5.string},QRCodeSvg=reactExports.forwardRef(function(Au,lo){var $u=Au.bgColor,Ru=Au.bgD,Iu=Au.fgD,Pu=Au.fgColor,Ou=Au.size,Mu=Au.title,Du=Au.viewBoxSize,Lu=Au.xmlns,Bu=Lu===void 0?"http://www.w3.org/2000/svg":Lu,ju=_objectWithoutProperties(Au,_excluded$1);return vM.createElement("svg",_extends({},ju,{height:Ou,ref:lo,viewBox:"0 0 ".concat(Du," ").concat(Du),width:Ou,xmlns:Bu}),Mu?vM.createElement("title",null,Mu):null,vM.createElement("path",{d:Ru,fill:$u}),vM.createElement("path",{d:Iu,fill:Pu}))});QRCodeSvg.displayName="QRCodeSvg";QRCodeSvg.propTypes=propTypes$1;var _excluded=["bgColor","fgColor","level","size","value"];qrcode.stringToBytes=function(Au){return Array.from(new TextEncoder().encode(Au))};var propTypes={bgColor:s$5.oneOfType([s$5.object,s$5.string]),fgColor:s$5.oneOfType([s$5.object,s$5.string]),level:s$5.string,size:s$5.number,value:s$5.string.isRequired},QRCode=reactExports.forwardRef(function(Au,lo){var $u=Au.bgColor,Ru=$u===void 0?"#FFFFFF":$u,Iu=Au.fgColor,Pu=Iu===void 0?"#000000":Iu,Ou=Au.level,Mu=Ou===void 0?"L":Ou,Du=Au.size,Lu=Du===void 0?256:Du,Bu=Au.value,ju=_objectWithoutProperties(Au,_excluded),Fu=qrcode(0,Mu);Fu.addData(Bu),Fu.make();var zu=Fu.getModuleCount(),Uu=Array.from({length:zu},function(Hu,Vu){return Array.from({length:zu},function(Gu,Wu){return Fu.isDark(Vu,Wu)})});return vM.createElement(QRCodeSvg,_extends({},ju,{bgColor:Ru,bgD:Uu.map(function(Hu,Vu){return Hu.map(function(Gu,Wu){return Gu?"":"M ".concat(Wu," ").concat(Vu," l 1 0 0 1 -1 0 Z")}).join(" ")}).join(" "),fgColor:Pu,fgD:Uu.map(function(Hu,Vu){return Hu.map(function(Gu,Wu){return Gu?"M ".concat(Wu," ").concat(Vu," l 1 0 0 1 -1 0 Z"):""}).join(" ")}).join(" "),ref:lo,size:Lu,viewBoxSize:zu}))});QRCode.displayName="QRCode";QRCode.propTypes=propTypes;const PAP_SIGN_IN_WORDS={title:Au=>`Sign in at ${Au}`,direct:"Open the company’s page through Datalayer, sign in there, and this conversation goes on once you are back.",device:"Open the company’s page and enter this code there.",mediatedTitle:Au=>`Sign in through ${Au}`,mediated:"Open this page: it names the company and asks what the company needs. Type it there, never in this conversation.",sentTo:Au=>`The company sent a code to ${Au}.`,needs:Au=>`It needs: ${Au.join(", ")}.`,open:Au=>`Open ${Au}`,code:"Your code",copy:"Copy the code",copied:"Copied",until:Au=>`Until ${new Date(Au).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}.`,checkAgain:"I have signed in: check again",tellMe:"Tell me when you are done.",checkMessage:Au=>`I have signed in at ${Au}. Please check again.`,refused:"This sign-in link cannot be opened safely, so it is not shown.",qr:Au=>`A code to scan to open ${Au} on your phone`,returned:{signed_in:Au=>`Signed in at ${Au}: checking again.`,denied:Au=>`You did not sign in at ${Au}: ask again when you want to.`,refused:Au=>`That sign-in at ${Au} was refused, and nothing was kept: start it again here.`}},PAP_SIGN_IN_CHANNEL="datalayer-pap-sign-in",SCOPE=/^[\x21\x23-\x5B\x5D-\x7E]{1,128}$/,DOMAIN=/^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;function signInReturnOf(Au,lo){if(!Au||typeof Au!="object"||Array.isArray(Au))return null;const $u=Au,Ru=$u.outcome;return $u.company===lo&&(Ru==="signed_in"||Ru==="denied"||Ru==="refused")?Ru:null}const PAP_SIGN_IN_TOOL=/(^|[_.:\-/])pa(?:p|ct)_sign_in$/;function unwrapped(Au){let lo=Au;if(typeof lo=="string")try{lo=JSON.parse(lo)}catch{return null}if(!lo||typeof lo!="object"||Array.isArray(lo))return null;const $u=lo;if($u.structuredContent&&typeof $u.structuredContent=="object")return unwrapped($u.structuredContent);if(Array.isArray($u.content)){const Ru=$u.content.find(Iu=>Iu?.type==="text"&&typeof Iu.text=="string");return Ru?unwrapped(Ru.text):null}return $u.result&&typeof $u.result=="object"&&!("status"in $u)?unwrapped($u.result):$u}function safeSignInUrl(Au){if(typeof Au!="string")return null;try{const lo=new URL(Au);return lo.protocol==="https:"&&lo.hostname?lo:null}catch{return null}}function readPapSignIn(Au){const lo=unwrapped(Au);if(!lo||lo.status!=="waiting_for_the_person"||lo.mode!=="direct"&&lo.mode!=="device"&&lo.mode!=="mediated")return null;const $u=safeSignInUrl(lo.open);if(!$u)return{refused:PAP_SIGN_IN_WORDS.refused};if(lo.mode==="device"&&(typeof lo.code!="string"||!lo.code))return null;const Ru=typeof lo.company=="string"&&DOMAIN.test(lo.company)?lo.company:"",Iu=Array.isArray(lo.needs)?lo.needs.filter(Pu=>typeof Pu=="string"&&SCOPE.test(Pu)):[];return{mode:lo.mode,open:$u.toString(),host:$u.hostname,...Ru?{company:Ru}:{},...typeof lo.code=="string"&&lo.code?{code:lo.code}:{},...lo.mode==="mediated"&&typeof lo.sent_to=="string"&&lo.sent_to?{sentTo:lo.sent_to}:{},...typeof lo.expires_at=="string"&&lo.expires_at?{expiresAt:lo.expires_at}:{},...Iu.length>0?{needs:Iu}:{}}}function PapSignInCard({context:Au,send:lo}){const[$u,Ru]=reactExports.useState(!1),[Iu,Pu]=reactExports.useState(!1),[Ou,Mu]=reactExports.useState(null),Du=Au.status==="complete"?readPapSignIn(Au.result):null,Lu=Du&&!("refused"in Du)&&Du.mode==="direct"?Du.company??"":"";if(reactExports.useEffect(()=>{if(!Lu||typeof BroadcastChannel>"u")return;const zu=new BroadcastChannel(PAP_SIGN_IN_CHANNEL);return zu.onmessage=Uu=>{const Hu=signInReturnOf(Uu.data,Lu);Hu&&(Mu(Hu),zu.close())},()=>zu.close()},[Lu]),reactExports.useEffect(()=>{Ou==="signed_in"&&lo&&!Iu&&Pu(lo(PAP_SIGN_IN_WORDS.checkMessage(Lu)))},[Ou,lo,Iu,Lu]),!Du)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Au.defaultUI});if("refused"in Du)return jsxRuntimeExports.jsx(Flash,{variant:"danger",role:"alert",sx:{my:2},children:Du.refused});const Bu=async()=>{try{await navigator.clipboard.writeText(Du.code??""),Ru(!0)}catch{Ru(!1)}},ju=Du.company??Du.host,Fu=Du.mode==="mediated"?PAP_SIGN_IN_WORDS.mediatedTitle(Du.host):PAP_SIGN_IN_WORDS.title(ju);return jsxRuntimeExports.jsxs(Box,{as:"section","aria-label":Fu,my:2,p:3,border:"1px solid",borderColor:"border.default",borderRadius:2,bg:"canvas.subtle",maxWidth:480,children:[jsxRuntimeExports.jsx(Heading$2,{as:"h4",sx:{fontSize:2,mb:1},children:Fu}),jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{mt:0,mb:2,color:"fg.muted",fontSize:1},children:Du.mode==="device"?PAP_SIGN_IN_WORDS.device:Du.mode==="mediated"?PAP_SIGN_IN_WORDS.mediated:PAP_SIGN_IN_WORDS.direct}),Du.needs?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{mt:0,mb:2,fontSize:1},children:PAP_SIGN_IN_WORDS.needs(Du.needs)}):null,Du.sentTo?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{mt:0,mb:2,fontSize:1},children:PAP_SIGN_IN_WORDS.sentTo(Du.sentTo)}):null,Du.code?jsxRuntimeExports.jsxs(Box,{display:"flex",gap:3,alignItems:"center",flexWrap:"wrap",mb:2,children:[jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{as:"div",sx:{fontSize:0,color:"fg.muted"},children:PAP_SIGN_IN_WORDS.code}),jsxRuntimeExports.jsx(Text$3,{as:"div","aria-live":"polite",sx:{fontFamily:"mono",fontSize:5,fontWeight:"bold",letterSpacing:"0.15em"},children:Du.code}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",leadingVisual:CopyIcon,onClick:()=>{Bu()},children:$u?PAP_SIGN_IN_WORDS.copied:PAP_SIGN_IN_WORDS.copy})]}),jsxRuntimeExports.jsx(Box,{bg:"#ffffff",p:2,borderRadius:2,lineHeight:0,children:jsxRuntimeExports.jsx(QRCode,{value:Du.open,size:112,title:PAP_SIGN_IN_WORDS.qr(Du.host)})})]}):null,jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,flexWrap:"wrap",alignItems:"center",children:[jsxRuntimeExports.jsx(ButtonComponent,{as:"a",href:Du.open,target:"_blank",rel:"noopener noreferrer",variant:"primary",trailingVisual:LinkExternalIcon,children:PAP_SIGN_IN_WORDS.open(ju)}),lo?jsxRuntimeExports.jsx(ButtonComponent,{disabled:Iu,onClick:()=>Pu(lo(PAP_SIGN_IN_WORDS.checkMessage(ju))),children:PAP_SIGN_IN_WORDS.checkAgain}):null]}),Ou?jsxRuntimeExports.jsx(Text$3,{as:"p",role:"status",sx:{mt:2,mb:0,fontSize:1},children:PAP_SIGN_IN_WORDS.returned[Ou](ju)}):null,Du.expiresAt?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{mt:2,mb:0,fontSize:0,color:"fg.muted"},children:PAP_SIGN_IN_WORDS.until(Du.expiresAt)}):null,lo?null:jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{mt:1,mb:0,fontSize:1},children:PAP_SIGN_IN_WORDS.tellMe})]})}const PAP_SIGN_IN_PLUGIN_NAME="@datalayer/loop-plugin-pap-sign-in",PAP_SIGN_IN_TYPE="application/vnd.datalayer.pap.sign-in+json";function resultOf(Au,lo){const $u=Au.data??{};return"toolName"in $u?lo?.result:{status:"waiting_for_the_person",...$u}}function createPapSignInPlugin(){let Au;const lo=Pu=>Au?!Au(Pu):!1;function $u({workspace:Pu}){const Ou=Pu?.viewControls.send;return reactExports.useEffect(()=>(Au=Ou,()=>{Au===Ou&&(Au=void 0)}),[Ou]),null}function Ru({display:Pu,context:Ou}){const Mu=resultOf(Pu,Ou);return reactExports.createElement(PapSignInCard,{key:Pu.id,context:Ou?{...Ou,result:Mu}:{toolCallId:Pu.id,toolName:"pap_sign_in",name:"pap_sign_in",args:{},status:"complete",result:Mu},send:Au?lo:void 0})}return{name:PAP_SIGN_IN_PLUGIN_NAME,displayName:"Sign in at a company",description:"The company’s page, the code and until when, where the agent asks the person to sign in.",octicon:"sign-in",emoji:"🔑",contributes:[contribution(Renderers,defineRenderer({type:PAP_SIGN_IN_TYPE,component:Ru}),{id:"pap-sign-in"}),contribution(ToolBindings,{tool:PAP_SIGN_IN_TOOL,type:PAP_SIGN_IN_TYPE},{id:"pap-sign-in"})],build(){return{components:[{slot:LoopSlots.chatHeader,id:"pap-sign-in",Component:$u}]}}}}const PapSignInPlugin=createPapSignInPlugin();function makeViewSwitchAction({viewId:Au,icon:lo,tooltip:$u}){return function(){const Iu=reactExports.useSyncExternalStore(subscribeEditorChoice,()=>getEditorChoice().editorId),Pu=useContributions(LoopEditorView);if(Au!==NONE_EDITOR&&!Pu.some(Mu=>Mu.value.surfaceId===Au))return null;const Ou=(Iu||NONE_EDITOR)===Au;return jsxRuntimeExports.jsx(IconButton,{icon:lo,"aria-label":$u,size:"small",variant:"invisible",onClick:()=>{chooseEditor(Au)||console.warn(`[loop] No chat is on screen to switch to '${Au}'.`)},sx:Ou?{color:"accent.fg"}:void 0})}}function defineViewPlugin(Au){const{key:lo,viewId:$u,displayName:Ru,description:Iu,icon:Pu,tooltip:Ou,order:Mu}=Au,Du=makeViewSwitchAction({viewId:$u,icon:Pu,tooltip:Ou});return{name:`@datalayer/loop-plugin-${lo}-view`,displayName:Ru,description:Iu,octicon:Au.octicon??"eye",emoji:Au.emoji,dependencies:[InputPromptPlugin],build:()=>({components:[{id:`${lo}-view-action`,slot:LoopSlots.promptAction,order:Mu,Component:Du}]})}}const ChatViewPlugin=defineViewPlugin({key:"chat",viewId:NONE_EDITOR,displayName:"Chat view",description:"The conversation on its own, from the composer footer.",icon:CommentDiscussionIcon,tooltip:"Show the chat",octicon:"comment-discussion",emoji:"💬",order:10}),DocumentViewPlugin=defineViewPlugin({key:"document",viewId:"document",displayName:"Document view",description:"The document beside the chat, from the composer footer.",icon:FileIcon,tooltip:"Show the document",octicon:"file",emoji:"📄",order:12}),NotebookViewPlugin=defineViewPlugin({key:"notebook",viewId:"notebook",displayName:"Notebook view",description:"The notebook beside the chat, from the composer footer.",icon:RowsIcon,tooltip:"Show the notebook",octicon:"rows",emoji:"📓",order:11}),STYLE_ELEMENT_ID="datalayer-reactor-commands-style",PALETTE_CSS=`
3845
3845
  /*
@@ -3998,9 +3998,9 @@ ${Mu}`:ju,inputs:Mu,clear:Ou?[]:[DRAFT.path],loop:Lu()}:{refused:"Nothing to sen
3998
3998
  opacity: 0.6;
3999
3999
  border-top: 1px solid var(--cmdk-border);
4000
4000
  }
4001
- `;function usePaletteStyles(){reactExports.useEffect(()=>{if(typeof document>"u"||document.getElementById(STYLE_ELEMENT_ID))return;const Au=document.createElement("style");Au.id=STYLE_ELEMENT_ID,Au.textContent=PALETTE_CSS,document.head.appendChild(Au)},[])}function rank(Au,lo){if(!lo)return{command:Au,score:0};const $u=lo.toLowerCase(),Ru=[[Au.name.toLowerCase(),0],[Au.id.toLowerCase(),100],[(Au.category??"").toLowerCase(),200],[(Au.description??"").toLowerCase(),300]];for(const[Iu,Pu]of Ru){const Ou=Iu.indexOf($u);if(Ou>=0)return{command:Au,score:Pu+Ou}}return null}const PRIMER_PORTAL_ROOT_ID="__primerPortalRoot__";function paletteRoot(){return document.getElementById(PRIMER_PORTAL_ROOT_ID)??document.body}const LIST_ID="dla-cmdk-list",optionId=Au=>`dla-cmdk-option-${Au}`,PALETTE_KEYBINDING="Mod+K",PALETTE_CHORD=parseKeybinding(PALETTE_KEYBINDING);function CommandPalette(){const Au=useReactorPlatform(),lo=useCommands();usePaletteStyles();const[$u,Ru]=reactExports.useState(!1),[Iu,Pu]=reactExports.useState(""),[Ou,Mu]=reactExports.useState(0),[Du,Lu]=reactExports.useState(null),[Bu,ju]=reactExports.useState(null),Fu=reactExports.useRef(null),zu=reactExports.useMemo(()=>lo.map(Wu=>rank(Wu,Iu)).filter(Wu=>Wu!==null).sort((Wu,Ku)=>Wu.score-Ku.score).map(Wu=>Wu.command),[lo,Iu]),Uu=reactExports.useCallback(()=>{Ru(!1),Pu(""),Mu(0),ju(null)},[]),Hu=reactExports.useCallback(async Wu=>{Lu(Wu.id),ju(null);try{await Au.executeCommand(Wu.id),Uu()}catch(Ku){ju(Ku instanceof Error?Ku.message:String(Ku))}finally{Lu(null)}},[Uu,Au]);if(reactExports.useEffect(()=>{const Wu=lo.map(Yu=>{const Xu=Yu.keybinding?parseKeybinding(Yu.keybinding):null;return Xu?{chord:Xu,id:Yu.id}:null}).filter(Yu=>Yu!==null),Ku=isApplePlatform();function Ju(Yu){if(PALETTE_CHORD&&matchesKeybinding(Yu,PALETTE_CHORD,Ku)){Yu.preventDefault(),Yu.stopPropagation(),Ru(Xu=>!Xu);return}if(Yu.key==="Escape"){Ru(Xu=>Xu&&!1);return}if(!$u){for(const Xu of Wu)if(matchesKeybinding(Yu,Xu.chord,Ku)){Yu.preventDefault(),Yu.stopPropagation();const ed=Au.getCommand(Xu.id);ed&&ed.isEnabled?.()!==!1&&Au.executeCommand(Xu.id).catch(td=>{console.error(`Command ${Xu.id} failed`,td)});return}}}return document.addEventListener("keydown",Ju,{capture:!0}),()=>document.removeEventListener("keydown",Ju,{capture:!0})},[lo,$u,Au]),reactExports.useEffect(()=>{if(!$u)return;Pu(""),Mu(0),ju(null);const Wu=window.requestAnimationFrame(()=>Fu.current?.focus());return()=>window.cancelAnimationFrame(Wu)},[$u]),reactExports.useEffect(()=>{Mu(Wu=>Wu>=zu.length?0:Wu)},[zu.length]),!$u||typeof document>"u")return null;const Vu=Wu=>{if(Wu.key==="ArrowDown")Wu.preventDefault(),Mu(Ku=>zu.length===0?0:(Ku+1)%zu.length);else if(Wu.key==="ArrowUp")Wu.preventDefault(),Mu(Ku=>zu.length===0?0:(Ku-1+zu.length)%zu.length);else if(Wu.key==="Enter"){Wu.preventDefault();const Ku=zu[Ou];Ku&&Ku.isEnabled?.()!==!1&&Hu(Ku)}},Gu=jsxRuntimeExports.jsx("div",{className:"dla-cmdk-backdrop",onClick:Uu,children:jsxRuntimeExports.jsxs("div",{className:"dla-cmdk-panel",role:"dialog","aria-modal":"true","aria-label":"Command palette",onClick:Wu=>Wu.stopPropagation(),children:[jsxRuntimeExports.jsx("div",{className:"dla-cmdk-search",children:jsxRuntimeExports.jsx("input",{ref:Fu,className:"dla-cmdk-input",type:"text",placeholder:"Run a command…","aria-label":"Search commands",autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:!1,role:"combobox","aria-expanded":!0,"aria-controls":LIST_ID,"aria-autocomplete":"list","aria-activedescendant":zu.length>0?optionId(Ou):void 0,value:Iu,onChange:Wu=>Pu(Wu.target.value),onKeyDown:Vu})}),Bu!==null&&jsxRuntimeExports.jsx("div",{className:"dla-cmdk-error",children:Bu}),jsxRuntimeExports.jsx("ul",{className:"dla-cmdk-list",id:LIST_ID,role:"listbox",children:zu.length===0?jsxRuntimeExports.jsx("li",{className:"dla-cmdk-empty",children:lo.length===0?"No plugin has registered a command yet.":`Nothing matches “${Iu}”.`}):zu.map((Wu,Ku)=>{const Ju=Wu.isEnabled?.()!==!1;return jsxRuntimeExports.jsx("li",{children:jsxRuntimeExports.jsxs("button",{type:"button",className:"dla-cmdk-item",id:optionId(Ku),role:"option","aria-selected":Ku===Ou,"aria-disabled":!Ju,disabled:!Ju,onMouseEnter:()=>Mu(Ku),onClick:()=>{Hu(Wu)},children:[jsxRuntimeExports.jsx("span",{className:"dla-cmdk-mark","aria-hidden":"true",children:Wu.emoji??"·"}),jsxRuntimeExports.jsxs("span",{className:"dla-cmdk-text",children:[jsxRuntimeExports.jsx("span",{className:"dla-cmdk-name",children:Wu.name}),Wu.description&&jsxRuntimeExports.jsx("p",{className:"dla-cmdk-description",children:Wu.description})]}),Du===Wu.id&&jsxRuntimeExports.jsx("span",{className:"dla-cmdk-meta",children:"running…"}),Wu.keybinding&&jsxRuntimeExports.jsx("kbd",{className:"dla-cmdk-key",children:formatKeybinding(Wu.keybinding)}),Wu.category&&jsxRuntimeExports.jsx("span",{className:"dla-cmdk-meta",children:Wu.category})]})},Wu.id)})}),jsxRuntimeExports.jsxs("div",{className:"dla-cmdk-footer",children:[jsxRuntimeExports.jsxs("span",{children:["↑↓ to move · ↵ to run · esc to close ·"," ",jsxRuntimeExports.jsx("kbd",{className:"dla-cmdk-key",children:formatKeybinding(PALETTE_KEYBINDING)})," ","to reopen"]}),jsxRuntimeExports.jsxs("span",{children:[zu.length," of ",lo.length]})]})]})});return reactDomExports.createPortal(Gu,paletteRoot())}const CommandsPlugin={name:"@datalayer/reactor-commands",version:"1.0.0",displayName:"Commands",description:"A command palette: Ctrl-K opens a floating search over every command plugins have registered.",octicon:"command-palette",emoji:"⌘",build(){return{components:[{slot:"root",id:"command-palette",Component:CommandPalette}]}},commands:[{id:"commands.showPalette",name:"Show the command palette",description:"The same thing Ctrl-K does — listed so it is discoverable",emoji:"⌘",category:"Commands",keybinding:PALETTE_KEYBINDING,execute:()=>{document.dispatchEvent(new KeyboardEvent("keydown",{key:"k",ctrlKey:!0,bubbles:!0}))}}]},COMMANDS_PLUGIN_NAME="@datalayer/loop-plugin-commands",DEFAULT_CATEGORY="Workspace",GROUP_EMOJI={Agents:"🤖",Open:"📂",Session:"🧭",Workspace:"🪟"};function LoopCommandBridge({workspace:Au,sync:lo}){const $u=useContributions(LoopCommand);return reactExports.useEffect(()=>{lo($u,Au)},[$u,Au,lo]),null}const LoopCommandsPlugin={name:COMMANDS_PLUGIN_NAME,displayName:"Command palette",description:"Puts the workspace commands in a Ctrl-K palette, beside every plugin that registers one.",octicon:"command-palette",emoji:"⌘",dependencies:[CommandsPlugin,ThemePlugin],build:Au=>{const lo=new Map;let $u="",Ru;const Iu=(Pu,Ou)=>{const Mu=Ou?Pu.map(Du=>`${Du.plugin}:${Du.value.name}`).join("|"):"";if(!(Mu===$u&&Ou===Ru)){$u=Mu,Ru=Ou;for(const Du of lo.values())Du();if(lo.clear(),!!Ou)for(const Du of Pu){const Lu=Du.value,Bu=Lu.group??DEFAULT_CATEGORY;lo.set(Lu.name,Au.registerCommand({id:`loop.${Lu.name}`,name:Lu.description,description:`/${Lu.name}`,emoji:GROUP_EMOJI[Bu]??"💠",category:Bu,keybinding:Lu.keybinding,execute:async()=>{await Lu.run({workspace:Ou,argv:""})}}))}}};return{components:[{id:"loop-command-bridge",slot:LoopSlots.status,Component:({workspace:Pu})=>jsxRuntimeExports.jsx(LoopCommandBridge,{workspace:Pu,sync:Iu})}]}}},MODELS_PLUGIN_NAME="@datalayer/loop-plugin-models",ModelsPlugin={name:MODELS_PLUGIN_NAME,displayName:"Models",description:"Which model answers, from the agentspecs catalog.",octicon:"cpu",emoji:"🧠",contributes:[contribution(LoopCommand,{name:"models",aliases:["model"],description:"Show the models available to this session",group:"Agents",keybinding:"Mod+Alt+M",run:async({workspace:Au})=>{const lo=await fetch(`${Au.serverUrl}/api/v1/configure/models`);if(!lo.ok)return{content:"The model catalogue is unavailable."};const $u=await lo.json();return{content:`${($u.models??[]).filter(Iu=>Iu.available!==!1).length} of ${($u.models??[]).length} models are ready. Pick one under the prompt.`}}},{id:"models"})]},WINDOW_CONTROLS_SLOT="loop.window.controls",WINDOW_ACTIONS_SLOT="loop.window.actions";function WindowFrame({children:Au,title:lo,height:$u,slotProps:Ru={}}){const Iu=useOptionalSlotComponents(WINDOW_ACTIONS_SLOT);return jsxRuntimeExports.jsxs(Box,{position:"relative",borderRadius:"14px",overflow:"hidden",border:"1px solid",borderColor:"border.default",bg:"canvas.default",boxShadow:"0 24px 60px -28px rgba(0, 0, 0, 0.55)",height:$u===void 0?"100%":void 0,display:$u===void 0?"flex":void 0,flexDirection:$u===void 0?"column":void 0,children:[jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,px:3,py:2,borderBottom:"1px solid",borderColor:"border.default",bg:"canvas.subtle",flexWrap:"wrap",rowGap:2,flex:"0 0 auto",children:[jsxRuntimeExports.jsx(Box,{display:"flex",alignItems:"center",gap:"6px",mr:1,flexShrink:0,children:jsxRuntimeExports.jsx(ReactorSlot,{slot:WINDOW_CONTROLS_SLOT,props:Ru})}),jsxRuntimeExports.jsx(Box,{minWidth:0,flex:"1 1 auto",children:lo}),Iu.length>0?jsxRuntimeExports.jsx(Box,{display:"flex",alignItems:"center",gap:2,flexShrink:0,ml:"auto",children:jsxRuntimeExports.jsx(ReactorSlot,{slot:WINDOW_ACTIONS_SLOT,props:Ru})}):null]}),jsxRuntimeExports.jsx(Box,{sx:$u===void 0?{flex:"1 1 auto",minHeight:0}:{height:$u,minHeight:0},children:Au})]})}const WINDOW_FRAME_PLUGIN_NAME="@datalayer/loop-plugin-window-frame";function WindowControls(){return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:["danger.emphasis","attention.emphasis","success.emphasis"].map(Au=>jsxRuntimeExports.jsx(Box,{width:10,height:10,borderRadius:"50%",bg:Au},Au))})}const WindowFramePlugin={name:WINDOW_FRAME_PLUGIN_NAME,displayName:"Window frame",description:"Draws Loop as a window, and opens its title bar to controls and actions.",octicon:"browser",emoji:"🪟",build:()=>({components:[{id:"window-controls",slot:WINDOW_CONTROLS_SLOT,Component:WindowControls},{id:"full-screen",slot:LoopSlots.header,Component:WorkspaceFullScreenAction}]})},DOCUMENT_PLUGIN_NAME="@datalayer/loop-plugin-document",DocumentPlugin={name:DOCUMENT_PLUGIN_NAME,displayName:"Document editor",description:"A rich-text document beside the chat, driven by the agent.",octicon:"file",emoji:"📄",dependencies:[AgentsPlugin],contributionPoints:[LoopDocumentToolbar,LoopOpeningDocument],contributes:[contribution(LoopEditorView,{surfaceId:"document",title:"Document",icon:FileIcon,order:20,canOpen:Au=>Au.sandbox.state==="running",unavailableReason:()=>"Needs a running sandbox",load:()=>__vitePreload(()=>import("./chunks/DocumentView-Caxb2xz-.js"),[],import.meta.url)},{id:"document",order:20}),contribution(LoopCommand,{name:"document",description:"Open the document beside the chat",group:"Open",keybinding:"Mod+Alt+O",run:async({workspace:Au})=>{if(Au.setActiveViewType("chat"),!requestSurface("document"))throw new Error("No chat is on screen to open the document beside.")}},{id:"document"})],build:Au=>(__vitePreload(async()=>{const{createLexicalTools:lo}=await import("./chunks/lexicalHooks-Pqoe8h_O.js");return{createLexicalTools:lo}},[],import.meta.url).then(({createLexicalTools:lo})=>{Au.contribute(LoopFrontendTool,{id:"document-tools",tools:$u=>lo($u.surfaceId)},{id:"document-tools"})},lo=>{console.warn("The document tools could not be loaded",lo)}),{})},DOCUMENT_TOOLBAR_PLUGIN_NAME="@datalayer/loop-plugin-document-toolbar",DocumentToolbarPlugin=defineLazyPlugin({name:DOCUMENT_TOOLBAR_PLUGIN_NAME,displayName:"Document toolbar",description:"Shows what the document’s code blocks run on.",octicon:"circle",emoji:"🔵",activationEvents:[onContributionPoint(LoopDocumentToolbar)],contributionPoints:[LoopDocumentToolbarItem],load:()=>__vitePreload(()=>import("./chunks/plugin-Cf3g-jak.js"),[],import.meta.url)}),NOTEBOOK_PLUGIN_NAME="@datalayer/loop-plugin-notebook",NotebookPlugin={name:NOTEBOOK_PLUGIN_NAME,displayName:"Notebook editor",description:"A notebook beside the chat, on the session’s kernel.",octicon:"rows",emoji:"📓",dependencies:[AgentsPlugin],contributionPoints:[LoopNotebookToolbar,LoopOpeningNotebook],contributes:[contribution(LoopEditorView,{surfaceId:"notebook",title:"Notebook",icon:RowsIcon,order:10,canOpen:Au=>Au.sandbox.state==="running",unavailableReason:()=>"Needs a running sandbox",load:()=>__vitePreload(()=>import("./chunks/NotebookView-C8RCvsR1.js"),[],import.meta.url)},{id:"notebook",order:10}),contribution(LoopCommand,{name:"notebook",description:"Open the notebook beside the chat",group:"Open",keybinding:"Mod+Alt+N",run:async({workspace:Au})=>{if(Au.setActiveViewType("chat"),!requestSurface("notebook"))throw new Error("No chat is on screen to open the notebook beside.")}},{id:"notebook"})],build:Au=>(__vitePreload(async()=>{const{createNotebookTools:lo}=await Promise.resolve().then(()=>notebookHooks);return{createNotebookTools:lo}},void 0,import.meta.url).then(({createNotebookTools:lo})=>{Au.contribute(LoopFrontendTool,{id:"notebook-tools",tools:$u=>lo($u.surfaceId)},{id:"notebook-tools"})},lo=>{console.warn("The notebook tools could not be loaded",lo)}),{})},NOTEBOOK_TOOLBAR_PLUGIN_NAME="@datalayer/loop-plugin-notebook-toolbar",NotebookToolbarPlugin=defineLazyPlugin({name:NOTEBOOK_TOOLBAR_PLUGIN_NAME,displayName:"Notebook toolbar",description:"Shows what the notebook is running on, on its toolbar.",octicon:"circle",emoji:"🟢",activationEvents:[onContributionPoint(LoopNotebookToolbar)],contributionPoints:[LoopNotebookToolbarItem],load:()=>__vitePreload(()=>import("./chunks/plugin-DA_NCYQX.js"),[],import.meta.url)}),NotebookExtension=defineExtension({name:"@datalayer/loop-extension-notebook",displayName:"Notebooks",description:"A notebook beside the chat, and the toolbar that reports on it.",octicon:"rows",emoji:"📓",plugins:[NotebookPlugin,NotebookToolbarPlugin]}),DocumentExtension=defineExtension({name:"@datalayer/loop-extension-document",displayName:"Documents",description:"A rich-text document beside the chat, and the toolbar that reports on it.",octicon:"file",emoji:"📄",plugins:[DocumentPlugin,DocumentToolbarPlugin]}),NO_TURN$5=signal$2({id:0,status:"idle"}),MAX_HEIGHT=168;function Thinking(){return jsxRuntimeExports.jsxs(Box,{as:"span","aria-label":"The agent is thinking",display:"inline-flex",gap:"4px",alignItems:"center",sx:{height:"1.5em","& > i":{width:5,height:5,borderRadius:"50%",bg:"fg.muted",animation:"loop-turn-dot 1.2s ease-in-out infinite"},"& > i:nth-of-type(2)":{animationDelay:"0.15s"},"& > i:nth-of-type(3)":{animationDelay:"0.3s"},"@keyframes loop-turn-dot":{"0%, 80%, 100%":{opacity:.25},"40%":{opacity:1}}},children:[jsxRuntimeExports.jsx("i",{}),jsxRuntimeExports.jsx("i",{}),jsxRuntimeExports.jsx("i",{})]})}function TurnPanel({footer:Au="full"}){const lo=useContributions(LoopChatTurn),$u=useSignalValue$1(lo[0]?.value.turn??NO_TURN$5),Ru=useSignalValue$1(pageLayoutSheet),Iu=reactExports.useRef(null),[Pu,Ou]=reactExports.useState(null),[Mu,Du]=reactExports.useState(!1);reactExports.useEffect(()=>{const ju=Iu.current;ju&&(ju.scrollTop=ju.scrollHeight)},[$u.assistant]),reactExports.useEffect(()=>{if(!Mu)return;const ju=window.setTimeout(()=>Du(!1),1400);return()=>window.clearTimeout(ju)},[Mu]);const Lu=reactExports.useCallback(async()=>{const ju=[$u.user,$u.assistant].filter(Boolean).join(`
4001
+ `;function usePaletteStyles(){reactExports.useEffect(()=>{if(typeof document>"u"||document.getElementById(STYLE_ELEMENT_ID))return;const Au=document.createElement("style");Au.id=STYLE_ELEMENT_ID,Au.textContent=PALETTE_CSS,document.head.appendChild(Au)},[])}function rank(Au,lo){if(!lo)return{command:Au,score:0};const $u=lo.toLowerCase(),Ru=[[Au.name.toLowerCase(),0],[Au.id.toLowerCase(),100],[(Au.category??"").toLowerCase(),200],[(Au.description??"").toLowerCase(),300]];for(const[Iu,Pu]of Ru){const Ou=Iu.indexOf($u);if(Ou>=0)return{command:Au,score:Pu+Ou}}return null}const PRIMER_PORTAL_ROOT_ID="__primerPortalRoot__";function paletteRoot(){return document.getElementById(PRIMER_PORTAL_ROOT_ID)??document.body}const LIST_ID="dla-cmdk-list",optionId=Au=>`dla-cmdk-option-${Au}`,PALETTE_KEYBINDING="Mod+K",PALETTE_CHORD=parseKeybinding(PALETTE_KEYBINDING);function CommandPalette(){const Au=useReactorPlatform(),lo=useCommands();usePaletteStyles();const[$u,Ru]=reactExports.useState(!1),[Iu,Pu]=reactExports.useState(""),[Ou,Mu]=reactExports.useState(0),[Du,Lu]=reactExports.useState(null),[Bu,ju]=reactExports.useState(null),Fu=reactExports.useRef(null),zu=reactExports.useMemo(()=>lo.map(Wu=>rank(Wu,Iu)).filter(Wu=>Wu!==null).sort((Wu,Ku)=>Wu.score-Ku.score).map(Wu=>Wu.command),[lo,Iu]),Uu=reactExports.useCallback(()=>{Ru(!1),Pu(""),Mu(0),ju(null)},[]),Hu=reactExports.useCallback(async Wu=>{Lu(Wu.id),ju(null);try{await Au.executeCommand(Wu.id),Uu()}catch(Ku){ju(Ku instanceof Error?Ku.message:String(Ku))}finally{Lu(null)}},[Uu,Au]);if(reactExports.useEffect(()=>{const Wu=lo.map(Yu=>{const Xu=Yu.keybinding?parseKeybinding(Yu.keybinding):null;return Xu?{chord:Xu,id:Yu.id}:null}).filter(Yu=>Yu!==null),Ku=isApplePlatform();function Ju(Yu){if(PALETTE_CHORD&&matchesKeybinding(Yu,PALETTE_CHORD,Ku)){Yu.preventDefault(),Yu.stopPropagation(),Ru(Xu=>!Xu);return}if(Yu.key==="Escape"){Ru(Xu=>Xu&&!1);return}if(!$u){for(const Xu of Wu)if(matchesKeybinding(Yu,Xu.chord,Ku)){Yu.preventDefault(),Yu.stopPropagation();const ed=Au.getCommand(Xu.id);ed&&ed.isEnabled?.()!==!1&&Au.executeCommand(Xu.id).catch(td=>{console.error(`Command ${Xu.id} failed`,td)});return}}}return document.addEventListener("keydown",Ju,{capture:!0}),()=>document.removeEventListener("keydown",Ju,{capture:!0})},[lo,$u,Au]),reactExports.useEffect(()=>{if(!$u)return;Pu(""),Mu(0),ju(null);const Wu=window.requestAnimationFrame(()=>Fu.current?.focus());return()=>window.cancelAnimationFrame(Wu)},[$u]),reactExports.useEffect(()=>{Mu(Wu=>Wu>=zu.length?0:Wu)},[zu.length]),!$u||typeof document>"u")return null;const Vu=Wu=>{if(Wu.key==="ArrowDown")Wu.preventDefault(),Mu(Ku=>zu.length===0?0:(Ku+1)%zu.length);else if(Wu.key==="ArrowUp")Wu.preventDefault(),Mu(Ku=>zu.length===0?0:(Ku-1+zu.length)%zu.length);else if(Wu.key==="Enter"){Wu.preventDefault();const Ku=zu[Ou];Ku&&Ku.isEnabled?.()!==!1&&Hu(Ku)}},Gu=jsxRuntimeExports.jsx("div",{className:"dla-cmdk-backdrop",onClick:Uu,children:jsxRuntimeExports.jsxs("div",{className:"dla-cmdk-panel",role:"dialog","aria-modal":"true","aria-label":"Command palette",onClick:Wu=>Wu.stopPropagation(),children:[jsxRuntimeExports.jsx("div",{className:"dla-cmdk-search",children:jsxRuntimeExports.jsx("input",{ref:Fu,className:"dla-cmdk-input",type:"text",placeholder:"Run a command…","aria-label":"Search commands",autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:!1,role:"combobox","aria-expanded":!0,"aria-controls":LIST_ID,"aria-autocomplete":"list","aria-activedescendant":zu.length>0?optionId(Ou):void 0,value:Iu,onChange:Wu=>Pu(Wu.target.value),onKeyDown:Vu})}),Bu!==null&&jsxRuntimeExports.jsx("div",{className:"dla-cmdk-error",children:Bu}),jsxRuntimeExports.jsx("ul",{className:"dla-cmdk-list",id:LIST_ID,role:"listbox",children:zu.length===0?jsxRuntimeExports.jsx("li",{className:"dla-cmdk-empty",children:lo.length===0?"No plugin has registered a command yet.":`Nothing matches “${Iu}”.`}):zu.map((Wu,Ku)=>{const Ju=Wu.isEnabled?.()!==!1;return jsxRuntimeExports.jsx("li",{children:jsxRuntimeExports.jsxs("button",{type:"button",className:"dla-cmdk-item",id:optionId(Ku),role:"option","aria-selected":Ku===Ou,"aria-disabled":!Ju,disabled:!Ju,onMouseEnter:()=>Mu(Ku),onClick:()=>{Hu(Wu)},children:[jsxRuntimeExports.jsx("span",{className:"dla-cmdk-mark","aria-hidden":"true",children:Wu.emoji??"·"}),jsxRuntimeExports.jsxs("span",{className:"dla-cmdk-text",children:[jsxRuntimeExports.jsx("span",{className:"dla-cmdk-name",children:Wu.name}),Wu.description&&jsxRuntimeExports.jsx("p",{className:"dla-cmdk-description",children:Wu.description})]}),Du===Wu.id&&jsxRuntimeExports.jsx("span",{className:"dla-cmdk-meta",children:"running…"}),Wu.keybinding&&jsxRuntimeExports.jsx("kbd",{className:"dla-cmdk-key",children:formatKeybinding(Wu.keybinding)}),Wu.category&&jsxRuntimeExports.jsx("span",{className:"dla-cmdk-meta",children:Wu.category})]})},Wu.id)})}),jsxRuntimeExports.jsxs("div",{className:"dla-cmdk-footer",children:[jsxRuntimeExports.jsxs("span",{children:["↑↓ to move · ↵ to run · esc to close ·"," ",jsxRuntimeExports.jsx("kbd",{className:"dla-cmdk-key",children:formatKeybinding(PALETTE_KEYBINDING)})," ","to reopen"]}),jsxRuntimeExports.jsxs("span",{children:[zu.length," of ",lo.length]})]})]})});return reactDomExports.createPortal(Gu,paletteRoot())}const CommandsPlugin={name:"@datalayer/reactor-commands",version:"1.0.0",displayName:"Commands",description:"A command palette: Ctrl-K opens a floating search over every command plugins have registered.",octicon:"command-palette",emoji:"⌘",build(){return{components:[{slot:"root",id:"command-palette",Component:CommandPalette}]}},commands:[{id:"commands.showPalette",name:"Show the command palette",description:"The same thing Ctrl-K does — listed so it is discoverable",emoji:"⌘",category:"Commands",keybinding:PALETTE_KEYBINDING,execute:()=>{document.dispatchEvent(new KeyboardEvent("keydown",{key:"k",ctrlKey:!0,bubbles:!0}))}}]},COMMANDS_PLUGIN_NAME="@datalayer/loop-plugin-commands",DEFAULT_CATEGORY="Workspace",GROUP_EMOJI={Agents:"🤖",Open:"📂",Session:"🧭",Workspace:"🪟"};function LoopCommandBridge({workspace:Au,sync:lo}){const $u=useContributions(LoopCommand);return reactExports.useEffect(()=>{lo($u,Au)},[$u,Au,lo]),null}const LoopCommandsPlugin={name:COMMANDS_PLUGIN_NAME,displayName:"Command palette",description:"Puts the workspace commands in a Ctrl-K palette, beside every plugin that registers one.",octicon:"command-palette",emoji:"⌘",dependencies:[CommandsPlugin,ThemePlugin],build:Au=>{const lo=new Map;let $u="",Ru;const Iu=(Pu,Ou)=>{const Mu=Ou?Pu.map(Du=>`${Du.plugin}:${Du.value.name}`).join("|"):"";if(!(Mu===$u&&Ou===Ru)){$u=Mu,Ru=Ou;for(const Du of lo.values())Du();if(lo.clear(),!!Ou)for(const Du of Pu){const Lu=Du.value,Bu=Lu.group??DEFAULT_CATEGORY;lo.set(Lu.name,Au.registerCommand({id:`loop.${Lu.name}`,name:Lu.description,description:`/${Lu.name}`,emoji:GROUP_EMOJI[Bu]??"💠",category:Bu,keybinding:Lu.keybinding,execute:async()=>{await Lu.run({workspace:Ou,argv:""})}}))}}};return{components:[{id:"loop-command-bridge",slot:LoopSlots.status,Component:({workspace:Pu})=>jsxRuntimeExports.jsx(LoopCommandBridge,{workspace:Pu,sync:Iu})}]}}},MODELS_PLUGIN_NAME="@datalayer/loop-plugin-models",ModelsPlugin={name:MODELS_PLUGIN_NAME,displayName:"Models",description:"Which model answers, from the agentspecs catalog.",octicon:"cpu",emoji:"🧠",contributes:[contribution(LoopCommand,{name:"models",aliases:["model"],description:"Show the models available to this session",group:"Agents",keybinding:"Mod+Alt+M",run:async({workspace:Au})=>{const lo=await fetch(`${Au.serverUrl}/api/v1/configure/models`);if(!lo.ok)return{content:"The model catalogue is unavailable."};const $u=await lo.json();return{content:`${($u.models??[]).filter(Iu=>Iu.available!==!1).length} of ${($u.models??[]).length} models are ready. Pick one under the prompt.`}}},{id:"models"})]},WINDOW_CONTROLS_SLOT="loop.window.controls",WINDOW_ACTIONS_SLOT="loop.window.actions";function WindowFrame({children:Au,title:lo,height:$u,slotProps:Ru={}}){const Iu=useOptionalSlotComponents(WINDOW_ACTIONS_SLOT);return jsxRuntimeExports.jsxs(Box,{position:"relative",borderRadius:"14px",overflow:"hidden",border:"1px solid",borderColor:"border.default",bg:"canvas.default",boxShadow:"0 24px 60px -28px rgba(0, 0, 0, 0.55)",height:$u===void 0?"100%":void 0,display:$u===void 0?"flex":void 0,flexDirection:$u===void 0?"column":void 0,children:[jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,px:3,py:2,borderBottom:"1px solid",borderColor:"border.default",bg:"canvas.subtle",flexWrap:"wrap",rowGap:2,flex:"0 0 auto",children:[jsxRuntimeExports.jsx(Box,{display:"flex",alignItems:"center",gap:"6px",mr:1,flexShrink:0,children:jsxRuntimeExports.jsx(ReactorSlot,{slot:WINDOW_CONTROLS_SLOT,props:Ru})}),jsxRuntimeExports.jsx(Box,{minWidth:0,flex:"1 1 auto",children:lo}),Iu.length>0?jsxRuntimeExports.jsx(Box,{display:"flex",alignItems:"center",gap:2,flexShrink:0,ml:"auto",children:jsxRuntimeExports.jsx(ReactorSlot,{slot:WINDOW_ACTIONS_SLOT,props:Ru})}):null]}),jsxRuntimeExports.jsx(Box,{sx:$u===void 0?{flex:"1 1 auto",minHeight:0}:{height:$u,minHeight:0},children:Au})]})}const WINDOW_FRAME_PLUGIN_NAME="@datalayer/loop-plugin-window-frame";function WindowControls(){return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:["danger.emphasis","attention.emphasis","success.emphasis"].map(Au=>jsxRuntimeExports.jsx(Box,{width:10,height:10,borderRadius:"50%",bg:Au},Au))})}const WindowFramePlugin={name:WINDOW_FRAME_PLUGIN_NAME,displayName:"Window frame",description:"Draws Loop as a window, and opens its title bar to controls and actions.",octicon:"browser",emoji:"🪟",build:()=>({components:[{id:"window-controls",slot:WINDOW_CONTROLS_SLOT,Component:WindowControls},{id:"full-screen",slot:LoopSlots.header,Component:WorkspaceFullScreenAction}]})},DOCUMENT_PLUGIN_NAME="@datalayer/loop-plugin-document",DocumentPlugin={name:DOCUMENT_PLUGIN_NAME,displayName:"Document editor",description:"A rich-text document beside the chat, driven by the agent.",octicon:"file",emoji:"📄",dependencies:[AgentsPlugin],contributionPoints:[LoopDocumentToolbar,LoopOpeningDocument],contributes:[contribution(LoopEditorView,{surfaceId:"document",title:"Document",icon:FileIcon,order:20,canOpen:Au=>Au.sandbox.state==="running",unavailableReason:()=>"Needs a running sandbox",load:()=>__vitePreload(()=>import("./chunks/DocumentView-i99p_Qzt.js"),[],import.meta.url)},{id:"document",order:20}),contribution(LoopCommand,{name:"document",description:"Open the document beside the chat",group:"Open",keybinding:"Mod+Alt+O",run:async({workspace:Au})=>{if(Au.setActiveViewType("chat"),!requestSurface("document"))throw new Error("No chat is on screen to open the document beside.")}},{id:"document"})],build:Au=>(__vitePreload(async()=>{const{createLexicalTools:lo}=await import("./chunks/lexicalHooks-Pqoe8h_O.js");return{createLexicalTools:lo}},[],import.meta.url).then(({createLexicalTools:lo})=>{Au.contribute(LoopFrontendTool,{id:"document-tools",tools:$u=>lo($u.surfaceId)},{id:"document-tools"})},lo=>{console.warn("The document tools could not be loaded",lo)}),{})},DOCUMENT_TOOLBAR_PLUGIN_NAME="@datalayer/loop-plugin-document-toolbar",DocumentToolbarPlugin=defineLazyPlugin({name:DOCUMENT_TOOLBAR_PLUGIN_NAME,displayName:"Document toolbar",description:"Shows what the document’s code blocks run on.",octicon:"circle",emoji:"🔵",activationEvents:[onContributionPoint(LoopDocumentToolbar)],contributionPoints:[LoopDocumentToolbarItem],load:()=>__vitePreload(()=>import("./chunks/plugin-Cf3g-jak.js"),[],import.meta.url)}),NOTEBOOK_PLUGIN_NAME="@datalayer/loop-plugin-notebook",NotebookPlugin={name:NOTEBOOK_PLUGIN_NAME,displayName:"Notebook editor",description:"A notebook beside the chat, on the session’s kernel.",octicon:"rows",emoji:"📓",dependencies:[AgentsPlugin],contributionPoints:[LoopNotebookToolbar,LoopOpeningNotebook],contributes:[contribution(LoopEditorView,{surfaceId:"notebook",title:"Notebook",icon:RowsIcon,order:10,canOpen:Au=>Au.sandbox.state==="running",unavailableReason:()=>"Needs a running sandbox",load:()=>__vitePreload(()=>import("./chunks/NotebookView-BJpTApeL.js"),[],import.meta.url)},{id:"notebook",order:10}),contribution(LoopCommand,{name:"notebook",description:"Open the notebook beside the chat",group:"Open",keybinding:"Mod+Alt+N",run:async({workspace:Au})=>{if(Au.setActiveViewType("chat"),!requestSurface("notebook"))throw new Error("No chat is on screen to open the notebook beside.")}},{id:"notebook"})],build:Au=>(__vitePreload(async()=>{const{createNotebookTools:lo}=await Promise.resolve().then(()=>notebookHooks);return{createNotebookTools:lo}},void 0,import.meta.url).then(({createNotebookTools:lo})=>{Au.contribute(LoopFrontendTool,{id:"notebook-tools",tools:$u=>lo($u.surfaceId)},{id:"notebook-tools"})},lo=>{console.warn("The notebook tools could not be loaded",lo)}),{})},NOTEBOOK_TOOLBAR_PLUGIN_NAME="@datalayer/loop-plugin-notebook-toolbar",NotebookToolbarPlugin=defineLazyPlugin({name:NOTEBOOK_TOOLBAR_PLUGIN_NAME,displayName:"Notebook toolbar",description:"Shows what the notebook is running on, on its toolbar.",octicon:"circle",emoji:"🟢",activationEvents:[onContributionPoint(LoopNotebookToolbar)],contributionPoints:[LoopNotebookToolbarItem],load:()=>__vitePreload(()=>import("./chunks/plugin-DA_NCYQX.js"),[],import.meta.url)}),NotebookExtension=defineExtension({name:"@datalayer/loop-extension-notebook",displayName:"Notebooks",description:"A notebook beside the chat, and the toolbar that reports on it.",octicon:"rows",emoji:"📓",plugins:[NotebookPlugin,NotebookToolbarPlugin]}),DocumentExtension=defineExtension({name:"@datalayer/loop-extension-document",displayName:"Documents",description:"A rich-text document beside the chat, and the toolbar that reports on it.",octicon:"file",emoji:"📄",plugins:[DocumentPlugin,DocumentToolbarPlugin]}),NO_TURN$5=signal$2({id:0,status:"idle"}),MAX_HEIGHT=168;function Thinking(){return jsxRuntimeExports.jsxs(Box,{as:"span","aria-label":"The agent is thinking",display:"inline-flex",gap:"4px",alignItems:"center",sx:{height:"1.5em","& > i":{width:5,height:5,borderRadius:"50%",bg:"fg.muted",animation:"loop-turn-dot 1.2s ease-in-out infinite"},"& > i:nth-of-type(2)":{animationDelay:"0.15s"},"& > i:nth-of-type(3)":{animationDelay:"0.3s"},"@keyframes loop-turn-dot":{"0%, 80%, 100%":{opacity:.25},"40%":{opacity:1}}},children:[jsxRuntimeExports.jsx("i",{}),jsxRuntimeExports.jsx("i",{}),jsxRuntimeExports.jsx("i",{})]})}function TurnPanel({footer:Au="full"}){const lo=useContributions(LoopChatTurn),$u=useSignalValue$1(lo[0]?.value.turn??NO_TURN$5),Ru=useSignalValue$1(pageLayoutSheet),Iu=reactExports.useRef(null),[Pu,Ou]=reactExports.useState(null),[Mu,Du]=reactExports.useState(!1);reactExports.useEffect(()=>{const ju=Iu.current;ju&&(ju.scrollTop=ju.scrollHeight)},[$u.assistant]),reactExports.useEffect(()=>{if(!Mu)return;const ju=window.setTimeout(()=>Du(!1),1400);return()=>window.clearTimeout(ju)},[Mu]);const Lu=reactExports.useCallback(async()=>{const ju=[$u.user,$u.assistant].filter(Boolean).join(`
4002
4002
 
4003
- `);await navigator.clipboard?.writeText(ju),Du(!0)},[$u.user,$u.assistant]);if(Ru==="panel"||$u.status==="idle"||!$u.user||Pu===$u.id)return null;const Bu=$u.status==="thinking"||$u.status==="streaming";return jsxRuntimeExports.jsxs(Box,{"data-turn-panel":"",borderTop:"1px solid",borderColor:"border.muted",px:3,pt:2,pb:Au==="none"?2:1,display:"flex",flexDirection:"column",gap:2,bg:"canvas.default",children:[jsxRuntimeExports.jsx(Box,{display:"flex",justifyContent:"flex-end",children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,lineHeight:1.45,px:2,py:1,borderRadius:"10px",bg:"accent.subtle",color:"fg.default",maxWidth:"85%",overflow:"hidden",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical"},children:$u.user})}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,alignItems:"flex-start",children:[jsxRuntimeExports.jsx(Box,{ref:Iu,flex:"1 1 auto",minWidth:0,maxHeight:MAX_HEIGHT,overflowY:"auto",fontSize:0,lineHeight:1.5,color:$u.assistant?"fg.default":"fg.muted",whiteSpace:$u.assistant?"normal":"pre-wrap",overflowWrap:"anywhere",children:$u.assistant?jsxRuntimeExports.jsx(Box,{sx:{...streamdownMarkdownStyles,fontSize:0},children:jsxRuntimeExports.jsx(_o$1,{rehypePlugins:REHYPE_PLUGINS_WITHOUT_HTML,children:normalizeAssistantMarkdown($u.assistant)})}):$u.activity?jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontStyle:"italic"},children:$u.activity}):Bu?jsxRuntimeExports.jsx(Thinking,{}):$u.status==="error"?"The agent could not answer.":"Done — the result is in the page."}),jsxRuntimeExports.jsx(IconButton,{icon:CommentDiscussionIcon,size:"small",variant:"invisible","aria-label":"Open the conversation",onClick:openPagePanel,sx:{color:"fg.muted",flexShrink:0}})]}),$u.assistant&&$u.activity?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted",fontStyle:"italic"},children:$u.activity}):null,Au==="full"?jsxRuntimeExports.jsx(TurnFooter,{usage:$u.usage,live:Bu,latest:!0,padding:0,onCopy:Lu,onRemove:()=>Ou($u.id)}):Au==="actions"?jsxRuntimeExports.jsxs(Box,{display:"flex",justifyContent:"flex-end",gap:1,mt:-1,children:[jsxRuntimeExports.jsx(IconButton,{icon:Mu?CheckIcon:CopyIcon,size:"small",variant:"invisible","aria-label":Mu?"Copied":"Copy this turn",onClick:()=>{Lu()},sx:{color:"fg.muted"}}),jsxRuntimeExports.jsx(IconButton,{icon:XIcon,size:"small",variant:"invisible","aria-label":"Dismiss until the next turn",onClick:()=>Ou($u.id),sx:{color:"fg.muted"}})]}):null]})}const SPLIT_DEFAULT_SHARE=.4,SPLIT_MIN_SHARE=.2,SPLIT_MAX_SHARE=.8,SPLIT_KEY_STEP=.05;function clampSplitShare(Au){return Number.isFinite(Au)?Math.min(SPLIT_MAX_SHARE,Math.max(SPLIT_MIN_SHARE,Au)):SPLIT_DEFAULT_SHARE}function splitShareForKey(Au,lo){switch(lo){case"ArrowLeft":return clampSplitShare(Au-SPLIT_KEY_STEP);case"ArrowRight":return clampSplitShare(Au+SPLIT_KEY_STEP);case"Home":return SPLIT_MIN_SHARE;case"End":return SPLIT_MAX_SHARE;default:return null}}function SplitLayout({editors:Au,hasEditor:lo,transcript:$u,prompt:Ru,chips:Iu,picker:Pu,transient:Ou}){const[Mu,Du]=reactExports.useState(SPLIT_DEFAULT_SHARE),Lu=reactExports.useRef(null),Bu=reactExports.useRef(!1),ju=reactExports.useCallback(Gu=>{const Wu=Lu.current?.getBoundingClientRect();return!Wu||Wu.width<=0?null:clampSplitShare((Gu-Wu.left)/Wu.width)},[]),Fu=Gu=>{Bu.current=!0,Gu.currentTarget.setPointerCapture?.(Gu.pointerId),Gu.preventDefault()},zu=Gu=>{if(!Bu.current)return;const Wu=ju(Gu.clientX);Wu!==null&&Du(Wu)},Uu=Gu=>{Bu.current=!1,Gu.currentTarget.releasePointerCapture?.(Gu.pointerId)},Hu=Gu=>{const Wu=splitShareForKey(Mu,Gu.key);Wu!==null&&(Gu.preventDefault(),Du(Wu))},Vu=Math.round(Mu*100);return jsxRuntimeExports.jsxs(Box,{"data-testid":"loop-split-layout",flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column",children:[Pu,jsxRuntimeExports.jsxs(Box,{ref:Lu,flex:"1 1 auto",minHeight:0,display:"flex",position:"relative",overflow:"hidden",children:[jsxRuntimeExports.jsxs(Box,{"data-testid":"loop-split-conversation",flex:lo?`0 0 ${Vu}%`:"1 1 auto",minWidth:0,minHeight:0,display:"flex",flexDirection:"column",ml:lo?"-1px":0,children:[$u,Iu,Ru]}),lo?jsxRuntimeExports.jsx(Box,{role:"separator","aria-orientation":"vertical","aria-label":"Resize the conversation and the page","aria-valuemin":Math.round(SPLIT_MIN_SHARE*100),"aria-valuemax":Math.round(SPLIT_MAX_SHARE*100),"aria-valuenow":Vu,tabIndex:0,onPointerDown:Fu,onPointerMove:zu,onPointerUp:Uu,onPointerCancel:Uu,onKeyDown:Hu,flex:"0 0 7px",mx:"-3px",zIndex:1,cursor:"col-resize",display:"flex",justifyContent:"center",outline:"none",touchAction:"none",sx:{"&::before":{content:'""',width:"1px",height:"100%",bg:"border.default"},"&:hover::before, &:focus-visible::before":{width:"3px",bg:"accent.emphasis"}}}):null,jsxRuntimeExports.jsx(Box,{"data-testid":"loop-split-page",sx:lo?{flex:"1 1 0",minWidth:0,minHeight:0,display:"flex",...paneOpening("right")}:{position:"absolute",inset:0,visibility:"hidden",pointerEvents:"none",zIndex:-1},children:Au})]}),Ou]})}const LOOP_PAGE_LAYOUT_PLUGIN_NAME="@datalayer/loop-plugin-page-layout",NO_TURN$4=signal$2({id:0,status:"idle"}),pageLayoutChatMode=signal$2("floating-draggable"),promptStance=signal$2("floating-top");let floatingStance="floating-top";const PAGE_LAYOUT_DISABLED_MODES=["assistant"];function pageLayoutForChatMode(Au){switch(Au){case"sidebar":return{bandMode:"panel",panelMode:"docked"};case"floating":return{bandMode:"panel",panelMode:"overlay"};case"floating-small":return{bandMode:"panel",panelMode:"popup"};default:return{bandMode:"floating",panelMode:"docked"}}}function setPageLayoutChatMode(Au){pageLayoutChatMode.value=Au;const{bandMode:lo}=pageLayoutForChatMode(Au);promptStance.value=lo==="floating"?floatingStance:"docked-top",lo==="panel"&&openPagePanel()}function ChatModeAction(){const Au=useSignalValue$1(pageLayoutChatMode);return jsxRuntimeExports.jsx(ChatViewModeToggle,{value:Au,onChange:setPageLayoutChatMode,disabledModes:PAGE_LAYOUT_DISABLED_MODES})}function LoopPageLayout({parts:Au,promptMode:lo,pageSize:$u}){const Ru=useContributions(LoopChatTurn),Iu=useSignalValue$1(Ru[0]?.value.turn??NO_TURN$4),Pu=useSignalValue$1(pageLayoutChatMode),Ou=lo==="floating"?pageLayoutForChatMode(Pu):{bandMode:"docked",panelMode:"docked"};return jsxRuntimeExports.jsx(PageLayout,{page:Au.editors,hasPage:Au.hasEditor,panel:Au.transcript,band:Au.prompt,chips:Au.chips,picker:Au.picker,transient:Au.transient,activity:Iu.activity,bandMode:Ou.bandMode,panelMode:Ou.panelMode,pageSize:$u})}function ConversationToggle(){return jsxRuntimeExports.jsx(PagePanelToggle,{panelName:"conversation",icon:CommentDiscussionIcon,sx:{order:2}})}const LoopPageLayoutPlugin={name:LOOP_PAGE_LAYOUT_PLUGIN_NAME,config:{arrangement:"page",turnPanel:"below",turnPanelFooter:"full",prompt:"docked",promptAnchor:"top",pageSize:void 0},displayName:"Page layout",description:"The editor — or, in the chat view, the conversation — on a centred sheet, the prompt docked above it at the same width or floating over it as a draggable card, the current turn under the prompt, the conversation in a side panel; or, split, the conversation and the work side by side with a hairline to drag.",octicon:"file",emoji:"📄",build:({config:Au,...lo})=>{if(Au.arrangement==="split")return lo.contribute(LoopChatLayout,{id:"split-layout",prompt:"docked",Component:SplitLayout},{id:"split-layout"}),{components:[]};const $u=Au.prompt,Ru=Au.pageSize;floatingStance=Au.promptAnchor==="bottom"?"floating-bottom":"floating-top",$u==="floating"&&(promptStance.value=floatingStance);const Iu=Pu=>jsxRuntimeExports.jsx(LoopPageLayout,{parts:Pu,promptMode:$u,pageSize:Ru});if(lo.contribute(LoopChatLayout,{id:"page-layout",prompt:$u==="floating"?floatingStance:"docked-top",promptStance:$u==="floating"?promptStance:void 0,Component:Iu},{id:"page-layout"}),Au.turnPanel!=="none"){const Pu=Au.turnPanelFooter,Ou=()=>jsxRuntimeExports.jsx(TurnPanel,{footer:Pu});lo.contribute(LoopPromptPanel,{id:"page-layout-turn",placement:Au.turnPanel,order:0,Component:Ou},{id:"page-layout-turn"})}return{components:[{id:"page-layout-conversation-toggle",slot:LoopSlots.header,Component:ConversationToggle},...$u==="floating"?[{id:"page-layout-chat-mode",slot:LoopSlots.promptAction,Component:ChatModeAction}]:[]]}}};function loopPlugins(Au={}){const{serverUrl:lo,target:$u="browser",defaultEditor:Ru,showViewSelector:Iu=!0,hideChatHeader:Pu=!1,chatHeaderButtons:Ou=!1,promptPlacement:Mu,autoFocusPrompt:Du=!0,suggestionLabels:Lu=!0,fullScreenTopOffset:Bu=0,showAgentVariants:ju=!1,agentSummary:Fu=!0,teamId:zu,teamPicker:Uu=!0,pageLayout:Hu=!1,pageLayoutArrangement:Vu="page",pageLayoutTurnPanel:Gu="below",pageLayoutPrompt:Wu="docked",pageLayoutPromptAnchor:Ku="top",pageLayoutSize:Ju,pageLayoutTurnPanelFooter:Yu="full",localAgent:Xu,localAgentSpec:ed,datalayerAgentSpecId:td,datalayerCreatePayload:nd,datalayerVisitors:od,datalayerKept:sd,embedToken:ad,targetFixed:pd,themeVariant:gd,themeOverrides:xd,colorMode:yd,presence:vd,showTokenUsage:wd,voice:Td,thread:cd,floatingPrompt:dd=!1,editorSelector:md=!1,editors:ld=!0,conversation:hd=!0,commandPalette:bd=!1,pluginsPanel:Sd=!1,windowFrame:kd=!1,firstPromptHook:Rd}=Au,Od=Ru??(ld?"notebook":"none");return hd?[configurePlugin(ChatPlugin,{defaultSurface:Od,showSurfaceSelector:ld&&Iu&&!md,hideHeader:Pu,headerButtons:{newChat:Ou,clear:Ou},promptPlacement:dd?"floating":Mu,autoFocusPrompt:Du,suggestionLabels:Lu,fullScreenTopOffset:Bu,themeVariant:gd,themeOverrides:xd,colorMode:yd,presence:vd,showTokenUsage:wd,...Td?{voice:Td}:{},...cd?{thread:cd}:{}}),configurePlugin(InputPromptPlugin,{firstPromptHook:Rd}),ChatHeaderPlugin,A2uiSurfacePlugin,PapSignInPlugin,ChatViewPlugin,...ld?[NotebookViewPlugin,DocumentViewPlugin]:[],configurePlugin(AgentsPlugin,{serverUrl:lo,target:$u,datalayerAgentSpecId:td,datalayerCreatePayload:nd,datalayerVisitors:od,datalayerKept:sd,embedToken:ad,targetFixed:pd,showAgentVariants:ju,showAgentSummary:Fu,teamId:zu,showTeamPicker:Uu,localAgent:Xu??(ed?{createPayload:{description:`Local agent from the ${ed} spec`,agent_library:"pydantic-ai",agent_spec_id:ed,enable_codemode:!1}}:void 0)}),...ld?[NotebookExtension,DocumentExtension]:[],A2uiPlugin,AgentspecsPlugin,ModelsPlugin,ThemePlugin,SubagentActivityPlugin,configurePlugin(ShellPlugin,{defaultEditor:Od,showSelector:ld&&md}),...dd?[PromptPlugin]:[],...Hu?[configurePlugin(LoopPageLayoutPlugin,{arrangement:Vu,turnPanel:Gu,turnPanelFooter:Yu,prompt:Wu,promptAnchor:Ku,pageSize:Ju})]:[],...bd?[LoopCommandsPlugin]:[],...Sd?[PluginsPanelPlugin]:[],...kd?[WindowFramePlugin]:[]]:[ThemePlugin,configurePlugin(ShellPlugin,{defaultEditor:"none",showSelector:!1}),...bd?[LoopCommandsPlugin]:[],...Sd?[PluginsPanelPlugin]:[],...kd?[WindowFramePlugin]:[]]}function LoopEmbed({agentId:Au="",showHeader:lo=!1,chatHeaderActions:$u,headerActions:Ru,headerContainer:Iu,frameTitle:Pu,frameHeight:Ou,sidebarRail:Mu=!1,plugins:Du=[],...Lu}){const Bu=reactExports.useRef(Lu.firstPromptHook);Bu.current=Lu.firstPromptHook;const ju=reactExports.useMemo(()=>buildLoopReactor([...loopPlugins({...Lu,windowFrame:Lu.windowFrame||Pu!==void 0,firstPromptHook:()=>Bu.current?.()}),...Du]),[Lu.serverUrl,Lu.target,Lu.datalayerAgentSpecId,Lu.targetFixed,Lu.themeVariant,JSON.stringify(Lu.themeOverrides??null),Lu.colorMode,Lu.presence?.name,Lu.presence?.face,Lu.presence?.welcome,Lu.presence?.paused,Lu.showTokenUsage,JSON.stringify({...Lu.voice??{},engines:void 0,token:void 0}),Lu.thread?.id,JSON.stringify(Lu.datalayerCreatePayload??null),JSON.stringify(Lu.datalayerVisitors??null),Lu.datalayerKept?.url,Lu.embedToken,Lu.defaultEditor,Lu.showViewSelector,Lu.hideChatHeader,Lu.chatHeaderButtons,Lu.promptPlacement,Lu.autoFocusPrompt,Lu.suggestionLabels,Lu.fullScreenTopOffset,Lu.showAgentVariants,Lu.agentSummary,Lu.teamId,Lu.teamPicker,Lu.pageLayout,Lu.pageLayoutTurnPanel,Lu.pageLayoutTurnPanelFooter,Lu.pageLayoutPrompt,Lu.pageLayoutPromptAnchor,Lu.pageLayoutSize?.format,Lu.pageLayoutSize?.width,Lu.pageLayoutSize?.height,Lu.localAgentSpec,Lu.floatingPrompt,Lu.editorSelector,Lu.editors,Lu.conversation,Lu.commandPalette,Lu.pluginsPanel,Lu.windowFrame,Pu!==void 0,Du]);useReactor(ju);const Fu=jsxRuntimeExports.jsx(LoopWorkspace,{serverUrl:Lu.serverUrl??"",agentId:Au,reactor:ju,manageReactor:!1,showViewSelector:Lu.showViewSelector,showHeader:lo,chatHeaderActions:$u,headerActions:Ru,headerContainer:Iu,sidebarRail:Mu});return jsxRuntimeExports.jsx(QueryClientProvider,{client:internalQueryClient,children:Pu!==void 0?jsxRuntimeExports.jsx(WindowFrame,{title:Pu,height:Ou,children:Fu}):jsxRuntimeExports.jsx(Box,{height:"100%",minHeight:0,width:"100%",flex:"1 1 auto",minWidth:0,children:Fu})})}const RECORD_KIND_WORDS={session:"Session",tool_call:"Tool call",decision:"Rule",check:"Check",approval:"Approval",output:"Answer",feedback:"Feedback",turn:"Turn",run:"Working",notification:"Notification"};function entryOf(Au){return{uid:String(Au.uid??""),sessionUid:String(Au.session_uid??""),deploymentUid:String(Au.deployment_uid??""),version:Number(Au.version)||0,kind:String(Au.kind??"output"),summary:String(Au.summary??""),payload:Au.payload&&typeof Au.payload=="object"?Au.payload:{},createdAt:String(Au.created_at??"")}}function runEndOf(Au){const lo=Au.kind==="output"?Au.payload.status:void 0;return typeof lo=="string"&&lo in RUN_END_WORDS?lo:""}function entrySaid(Au){return Au.summary||RUN_END_WORDS[runEndOf(Au)]||""}function sessionSentence(Au){const lo=Au.filter(Ou=>Ou.kind==="tool_call").length,$u=Au.filter(Ou=>Ou.kind==="check"),Ru=Au.map(runEndOf).filter(Boolean),Iu=Ru.filter(Ou=>Ou==="answered").length,Pu=[lo===0?"No tool called":`${lo} tool call${lo===1?"":"s"}`];return $u.length&&Pu.push(`${$u.length} step${$u.length===1?"":"s"} a check did not let pass`),Ru[Ru.length-1]==="stopped"?Pu.push("stopped"):Iu&&Pu.push(`${Iu} answer${Iu===1?"":"s"}`),`${Pu.join(", ")}.`}async function read(Au,lo,$u){if(!Au.aiAgentsUrl)throw new Error("The record service is not configured.");const Ru=await fetch(`${Au.aiAgentsUrl.replace(/\/+$/,"")}/api/ai-agents/v1/apps${lo}`,{headers:Au.token?{Authorization:`Bearer ${Au.token}`}:{}}),Iu=await Ru.json().catch(()=>({}));if(!Ru.ok||Iu.success===!1)throw new Error(`${$u}: ${String(Iu.detail??Ru.status)}`);return Iu}async function listSessions(Au,lo,$u=20,Ru=!1){const Iu=await read(Au,`/sessions?app_uid=${encodeURIComponent(lo)}&limit=${$u}${Ru===null?"":`&tests=${Ru}`}`,"The sessions could not be read");return Array.isArray(Iu.sessions)?Iu.sessions.map(entryOf):[]}async function readSession(Au,lo){const $u=await read(Au,`/records?session_uid=${encodeURIComponent(lo)}&limit=500`,"The session could not be read");return Array.isArray($u.entries)?$u.entries.map(entryOf).filter(Ru=>Ru.kind!=="run"):[]}const APP_ACTIVITY_WORDS={title:"Activity",unsaved:"Recorded once it is saved on Datalayer: each session there — its address, or its Preview on Datalayer — is listed here.",signedOut:"Its activity is its owner’s: sign in to Datalayer to read it.",none:"Nothing yet: a session on Datalayer — its address, or the Preview on Datalayer — is recorded here."},NO_TURN$3=signal$2({id:0,status:"idle"});function useRead(Au,lo,$u=!0){const[Ru,Iu]=reactExports.useState({loading:$u});return reactExports.useEffect(()=>{if(!$u)return;let Pu=!1;return Iu(Ou=>({...Ou,loading:!0})),Au().then(Ou=>!Pu&&Iu({value:Ou,loading:!1}),Ou=>!Pu&&Iu({error:Ou instanceof Error?Ou.message:String(Ou),loading:!1})),()=>{Pu=!0}},[lo,$u]),Ru}function Session({context:Au,session:lo}){const[$u,Ru]=reactExports.useState(!1),Iu=useRead(()=>readSession(Au,lo.sessionUid),`${lo.sessionUid}:${Au.token}`,$u);return jsxRuntimeExports.jsxs(Box,{as:"details",onToggle:Pu=>Ru(Pu.currentTarget.open),borderTop:"1px solid",borderColor:"border.muted",py:2,children:[jsxRuntimeExports.jsxs(Box,{as:"summary",cursor:"pointer",fontSize:1,children:[lo.createdAt?jsxRuntimeExports.jsx(RelativeTime,{datetime:lo.createdAt}):"A session",lo.version?` · version ${lo.version}`:"",Iu.value?` · ${sessionSentence(Iu.value)}`:""]}),$u?Iu.loading?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):Iu.error?jsxRuntimeExports.jsx(Text$3,{role:"alert",sx:{fontSize:1},children:Iu.error}):jsxRuntimeExports.jsx(Box,{as:"ol",pl:3,mt:2,mb:0,fontSize:1,children:(Iu.value??[]).map(Pu=>jsxRuntimeExports.jsxs(Box,{as:"li",mb:1,children:[jsxRuntimeExports.jsx(Label,{sx:{mr:2},children:RECORD_KIND_WORDS[Pu.kind]??Pu.kind}),entrySaid(Pu)]},Pu.uid))}):null]})}function AppActivity({appUid:Au}){const lo=useIAMStore(ju=>ju.token)??"",$u=useCoreStore(ju=>ju.configuration)?.aiAgentsUrl??"",Ru=useContributions(LoopChatTurn),Iu=useSignalValue$1(Ru[0]?.value.turn??NO_TURN$3),Pu=Iu.status!=="thinking"&&Iu.status!=="streaming",[Ou,Mu]=reactExports.useState(0);reactExports.useEffect(()=>{Pu&&Mu(Iu.id)},[Pu,Iu.id]);const Du={aiAgentsUrl:$u,token:lo},Lu=!!(Au&&lo),Bu=useRead(()=>listSessions(Du,Au??""),`${Au}:${lo}:${$u}:${Ou}`,Lu);return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-activity",children:[jsxRuntimeExports.jsx(Heading$2,{as:"h3",sx:{fontSize:2,mb:2},children:APP_ACTIVITY_WORDS.title}),Au?lo?Bu.loading&&!Bu.value?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):Bu.error?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:Bu.error}):(Bu.value??[]).length===0?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_ACTIVITY_WORDS.none}):(Bu.value??[]).map(ju=>jsxRuntimeExports.jsx(Session,{context:Du,session:ju},ju.uid)):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_ACTIVITY_WORDS.signedOut}):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_ACTIVITY_WORDS.unsaved})]})}const APP_ACTIVITY_PLUGIN_NAME="@datalayer/loop-plugin-app-activity";function defineAppActivityPlugin(Au,lo){function $u(){return jsxRuntimeExports.jsx(AppActivity,{appUid:lo})}return{name:`${APP_ACTIVITY_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: activity`,description:`What ${Au.name} did, session by session, from its record.`,octicon:"pulse",build:()=>({components:[{id:"app-activity",slot:LoopSlots.sidebar,order:20,Component:$u,rail:{label:"Activity",icon:PulseIcon}}]})}}const APP_PANEL_WIDTH=380;function elementsByPlace(Au){const lo=Au.filter($u=>$u.where==="page");return{panels:Au.filter($u=>$u.where==="panel"),page:lo.length>0?lo[lo.length-1]:null}}function ElementBody({element:Au,send:lo}){return jsxRuntimeExports.jsx(AnswerShowsView,{display:Au.shows,send:($u,Ru)=>lo!==void 0&&!lo($u,Ru)})}function ElementHeader({element:Au}){return jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",justifyContent:"space-between",gap:2,mb:2,children:[jsxRuntimeExports.jsx(Text$3,{as:"h2",sx:{fontSize:2,fontWeight:"bold",m:0},children:Au.title}),jsxRuntimeExports.jsx(IconButton,{icon:XIcon,variant:"invisible",size:"small","aria-label":`Close ${Au.title}`,onClick:()=>closeLoopElement(Au.id)})]})}function AppElements({workspace:Au}){const lo=reactExports.useSyncExternalStore(onLoopElements,openLoopElements,openLoopElements),{panels:$u,page:Ru}=elementsByPlace(lo),Iu=Au?.viewControls.send;return $u.length===0&&Ru===null?null:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[$u.length>0?jsxRuntimeExports.jsx(Box,{as:"aside","aria-label":"Side panel",position:"absolute",top:0,right:0,bottom:0,width:`min(${APP_PANEL_WIDTH}px, 100%)`,zIndex:1,overflowY:"auto",borderLeft:"1px solid",borderColor:"border.default",bg:"canvas.subtle",boxShadow:"shadow.medium",p:3,display:"flex",flexDirection:"column",gap:3,children:$u.map(Pu=>jsxRuntimeExports.jsxs(Box,{as:"section","aria-label":Pu.title,children:[jsxRuntimeExports.jsx(ElementHeader,{element:Pu}),jsxRuntimeExports.jsx(ElementBody,{element:Pu,send:Iu})]},Pu.id))}):null,Ru!==null?jsxRuntimeExports.jsxs(Box,{role:"dialog","aria-label":Ru.title,position:"absolute",inset:0,zIndex:2,overflowY:"auto",bg:"canvas.default",p:[3,4],children:[jsxRuntimeExports.jsx(ElementHeader,{element:Ru}),jsxRuntimeExports.jsx(ElementBody,{element:Ru,send:Iu})]}):null]})}const QUESTION_DISPLAY_TYPE="application/vnd.datalayer.loop.question+json",SchemaForm=reactExports.lazy(()=>__vitePreload(()=>import("./chunks/SchemaForm-CO_2yGg2.js"),[],import.meta.url));function questionOf(Au){const lo=Au.data??{},$u=lo.kind;if(Au.type!==QUESTION_DISPLAY_TYPE||$u!=="text"&&$u!=="choice"&&$u!=="file"&&$u!=="form"||typeof lo.prompt!="string")throw new Error(`Display ${Au.id} is not a question`);const Ru=Iu=>Array.isArray(Iu)?Iu.filter(Pu=>typeof Pu=="string"):[];return{kind:$u,prompt:lo.prompt,options:Ru(lo.options),accept:Ru(lo.accept),form:lo.form&&typeof lo.form=="object"?lo.form:{},answered:typeof lo.answered=="string"?lo.answered:null,answerable:(Au.actions??[]).some(Iu=>Iu.name===ANSWER_ACTION)}}function QuestionView({display:Au,act:lo,upload:$u}){const Ru=questionOf(Au),[Iu,Pu]=reactExports.useState(""),[Ou,Mu]=reactExports.useState(null),Du=Bu=>{if(!lo){Mu("The chat cannot take an answer here.");return}Mu(null),Promise.resolve(lo({action:ANSWER_ACTION,payload:{value:Bu}})).catch(ju=>Mu(ju instanceof Error?ju.message:String(ju)))};if(Ru.answered!==null)return jsxRuntimeExports.jsxs(Text$3,{as:"p",sx:{color:"fg.muted",fontSize:1,m:0},children:["Answered: ",Ru.answered]});const Lu=Ru.answerable&&!!lo;return jsxRuntimeExports.jsxs(Box$1,{display:"flex",flexDirection:"column",gap:2,"data-question-kind":Ru.kind,children:[Ru.kind==="choice"?jsxRuntimeExports.jsx(Box$1,{display:"flex",gap:2,flexWrap:"wrap",children:Ru.options.map(Bu=>jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:!Lu,onClick:()=>Du(Bu),children:Bu},Bu))}):null,Ru.kind==="text"?jsxRuntimeExports.jsxs(Box$1,{as:"form",display:"flex",gap:2,onSubmit:Bu=>{Bu.preventDefault(),Iu.trim()&&Du(Iu.trim())},children:[jsxRuntimeExports.jsx(TextInput$1,{"aria-label":Ru.prompt,value:Iu,disabled:!Lu,onChange:Bu=>Pu(Bu.target.value)}),jsxRuntimeExports.jsx(ButtonComponent,{type:"submit",size:"small",disabled:!Lu||!Iu.trim(),children:"Answer"})]}):null,Ru.kind==="form"?jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(SchemaForm,{schema:Ru.form,disabled:!Lu,onSubmit:({formData:Bu})=>Du(Bu??{})})}):null,Ru.kind==="file"?jsxRuntimeExports.jsx("input",{type:"file","aria-label":Ru.prompt,accept:Ru.accept.join(",")||void 0,disabled:!Lu||!$u,onChange:Bu=>{const ju=Bu.target.files?.[0];if(ju){if(!$u){Mu("The chat cannot take a file here.");return}Mu(null),$u(ju).then(Fu=>Du(Fu)).catch(Fu=>Mu(Fu instanceof Error?Fu.message:String(Fu)))}}}):null,Ou?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{color:"danger.fg",fontSize:1,m:0},children:Ou}):null]})}const APP_ELEMENTS_PLUGIN_NAME="@datalayer/loop-plugin-app-elements",AppElementsPlugin={name:APP_ELEMENTS_PLUGIN_NAME,displayName:"Side panel and pages",description:"What an application opens beside the conversation: a side panel, or a page of its own.",octicon:"sidebar-expand",contributes:[contribution(Renderers,defineRenderer({type:QUESTION_DISPLAY_TYPE,component:QuestionView}),{id:"app-elements:question"})],build:()=>({components:[{id:"app-elements",slot:LoopSlots.root,Component:AppElements}]}),register:()=>clearLoopElements},appComponentsPluginName=Au=>`@datalayer/loop-plugin-app-components-${Au}`,hasCustomComponents=Au=>(Au.interface.customComponents??[]).length>0;function defineAppComponentsPlugin(Au,lo){const $u=Au.interface.customComponents??[];if($u.length===0)throw new Error(`“${Au.name}” has no component of its own to contribute.`);return{name:appComponentsPluginName(Au.id),displayName:`${Au.name}'s components`,description:`The components ${Au.name}'s developer wrote: ${$u.map(Ru=>Ru.name).join(", ")}.`,octicon:"apps",contributes:$u.flatMap(Ru=>[contribution(LoopCanvasBlock,{id:Ru.name,ui:`app:${Au.id}`,component:customComponentEntry(Ru,Au.version)},{id:Ru.name}),contribution(LoopA2uiComponent,{id:Ru.name,app:Au.id,implementation:customImplementation(Ru,Au.version,lo,Au.id)},{id:Ru.name})])}}const COMPUTER_PARTS=["browse","files","shell"],COMPUTER_PART_TOOLS={browse:["open_page","read_page","page_screenshot","click_on_page","type_on_page"],files:["list_computer_files","read_computer_file","write_computer_file"],shell:["execute_code","run_skill_script"]},COMPUTER_WORDS={title:"Computer",part:{browse:"Browse",files:"Files",shell:"Shell"},on:"on",off:"off",none:"It has no computer: browse, files and shell are all off. Turn one on in its permissions to give it one.",offSaid:Au=>`Off, so its agent is given no tool for it: ${Au.join(", ")}.`,browser:"Browser",noBrowser:"No browser is installed on its computer.",noPage:"Its browser has opened no page yet.",pageAlt:Au=>`The page its browser shows: ${Au}`,clickToAct:"Click on the page to click there; with the page selected, what you type goes to it.",typeOnPage:"Text to type on the page",type:"Type",address:"An address to open",open:"Open",scrollUp:"Scroll up",scrollDown:"Scroll down",agentHas:"Its agent has the computer.",youHave:"You have the computer: its agent waits for it until you hand it back.",someoneHas:"Somebody else has taken this computer over.",takeOver:"Take over",handBack:"Hand back",run:"Run",yourCode:"Python to run on its computer",terminal:"What ran on it",nothingRan:"Nothing has run on it yet in this conversation.",files:"Files",notStarted:"Its computer starts when its agent first uses it: no file yet.",emptyDirectory:"Empty.",up:"Up",download:"Download",signedOut:"Its computer is shown once you are signed in to Datalayer."};function computerParts(Au){const lo=Au.permissions?.computer;return{browse:!!lo?.browse,files:!!lo?.files,shell:!!lo?.shell}}const hasComputer=Au=>COMPUTER_PARTS.some(lo=>Au[lo]),partsOff=Au=>COMPUTER_PARTS.filter(lo=>!Au[lo]).map(lo=>COMPUTER_WORDS.part[lo].toLowerCase());function partOf(Au){return COMPUTER_PARTS.find(lo=>COMPUTER_PART_TOOLS[lo].includes(Au))}const OUTPUT_LIMIT=4e3;function outputOf(Au){let lo=Au;if(typeof lo=="string")try{const Ru=JSON.parse(lo);Ru&&typeof Ru=="object"&&!Array.isArray(Ru)&&(lo=Ru)}catch{}let $u;if(lo&&typeof lo=="object"&&!Array.isArray(lo)){const Ru=lo,Iu=[typeof Ru.stdout=="string"?Ru.stdout:Ru.output,Ru.stderr,Ru.error??Ru.execution_error??Ru.code_error].filter(Pu=>typeof Pu=="string"&&Pu.trim()!=="");$u=Iu.length>0?Iu.join(`
4003
+ `);await navigator.clipboard?.writeText(ju),Du(!0)},[$u.user,$u.assistant]);if(Ru==="panel"||$u.status==="idle"||!$u.user||Pu===$u.id)return null;const Bu=$u.status==="thinking"||$u.status==="streaming";return jsxRuntimeExports.jsxs(Box,{"data-turn-panel":"",borderTop:"1px solid",borderColor:"border.muted",px:3,pt:2,pb:Au==="none"?2:1,display:"flex",flexDirection:"column",gap:2,bg:"canvas.default",children:[jsxRuntimeExports.jsx(Box,{display:"flex",justifyContent:"flex-end",children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,lineHeight:1.45,px:2,py:1,borderRadius:"10px",bg:"accent.subtle",color:"fg.default",maxWidth:"85%",overflow:"hidden",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical"},children:$u.user})}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,alignItems:"flex-start",children:[jsxRuntimeExports.jsx(Box,{ref:Iu,flex:"1 1 auto",minWidth:0,maxHeight:MAX_HEIGHT,overflowY:"auto",fontSize:0,lineHeight:1.5,color:$u.assistant?"fg.default":"fg.muted",whiteSpace:$u.assistant?"normal":"pre-wrap",overflowWrap:"anywhere",children:$u.assistant?jsxRuntimeExports.jsx(Box,{sx:{...streamdownMarkdownStyles,fontSize:0},children:jsxRuntimeExports.jsx(_o$1,{rehypePlugins:REHYPE_PLUGINS_WITHOUT_HTML,children:normalizeAssistantMarkdown($u.assistant)})}):$u.activity?jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontStyle:"italic"},children:$u.activity}):Bu?jsxRuntimeExports.jsx(Thinking,{}):$u.status==="error"?"The agent could not answer.":"Done — the result is in the page."}),jsxRuntimeExports.jsx(IconButton,{icon:CommentDiscussionIcon,size:"small",variant:"invisible","aria-label":"Open the conversation",onClick:openPagePanel,sx:{color:"fg.muted",flexShrink:0}})]}),$u.assistant&&$u.activity?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted",fontStyle:"italic"},children:$u.activity}):null,Au==="full"?jsxRuntimeExports.jsx(TurnFooter,{usage:$u.usage,live:Bu,latest:!0,padding:0,onCopy:Lu,onRemove:()=>Ou($u.id)}):Au==="actions"?jsxRuntimeExports.jsxs(Box,{display:"flex",justifyContent:"flex-end",gap:1,mt:-1,children:[jsxRuntimeExports.jsx(IconButton,{icon:Mu?CheckIcon:CopyIcon,size:"small",variant:"invisible","aria-label":Mu?"Copied":"Copy this turn",onClick:()=>{Lu()},sx:{color:"fg.muted"}}),jsxRuntimeExports.jsx(IconButton,{icon:XIcon,size:"small",variant:"invisible","aria-label":"Dismiss until the next turn",onClick:()=>Ou($u.id),sx:{color:"fg.muted"}})]}):null]})}const SPLIT_DEFAULT_SHARE=.4,SPLIT_MIN_SHARE=.2,SPLIT_MAX_SHARE=.8,SPLIT_KEY_STEP=.05;function clampSplitShare(Au){return Number.isFinite(Au)?Math.min(SPLIT_MAX_SHARE,Math.max(SPLIT_MIN_SHARE,Au)):SPLIT_DEFAULT_SHARE}function splitShareForKey(Au,lo){switch(lo){case"ArrowLeft":return clampSplitShare(Au-SPLIT_KEY_STEP);case"ArrowRight":return clampSplitShare(Au+SPLIT_KEY_STEP);case"Home":return SPLIT_MIN_SHARE;case"End":return SPLIT_MAX_SHARE;default:return null}}function SplitLayout({editors:Au,hasEditor:lo,transcript:$u,prompt:Ru,chips:Iu,picker:Pu,transient:Ou}){const[Mu,Du]=reactExports.useState(SPLIT_DEFAULT_SHARE),Lu=reactExports.useRef(null),Bu=reactExports.useRef(!1),ju=reactExports.useCallback(Gu=>{const Wu=Lu.current?.getBoundingClientRect();return!Wu||Wu.width<=0?null:clampSplitShare((Gu-Wu.left)/Wu.width)},[]),Fu=Gu=>{Bu.current=!0,Gu.currentTarget.setPointerCapture?.(Gu.pointerId),Gu.preventDefault()},zu=Gu=>{if(!Bu.current)return;const Wu=ju(Gu.clientX);Wu!==null&&Du(Wu)},Uu=Gu=>{Bu.current=!1,Gu.currentTarget.releasePointerCapture?.(Gu.pointerId)},Hu=Gu=>{const Wu=splitShareForKey(Mu,Gu.key);Wu!==null&&(Gu.preventDefault(),Du(Wu))},Vu=Math.round(Mu*100);return jsxRuntimeExports.jsxs(Box,{"data-testid":"loop-split-layout",flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column",children:[Pu,jsxRuntimeExports.jsxs(Box,{ref:Lu,flex:"1 1 auto",minHeight:0,display:"flex",position:"relative",overflow:"hidden",children:[jsxRuntimeExports.jsxs(Box,{"data-testid":"loop-split-conversation",flex:lo?`0 0 ${Vu}%`:"1 1 auto",minWidth:0,minHeight:0,display:"flex",flexDirection:"column",ml:lo?"-1px":0,children:[$u,Iu,Ru]}),lo?jsxRuntimeExports.jsx(Box,{role:"separator","aria-orientation":"vertical","aria-label":"Resize the conversation and the page","aria-valuemin":Math.round(SPLIT_MIN_SHARE*100),"aria-valuemax":Math.round(SPLIT_MAX_SHARE*100),"aria-valuenow":Vu,tabIndex:0,onPointerDown:Fu,onPointerMove:zu,onPointerUp:Uu,onPointerCancel:Uu,onKeyDown:Hu,flex:"0 0 7px",mx:"-3px",zIndex:1,cursor:"col-resize",display:"flex",justifyContent:"center",outline:"none",touchAction:"none",sx:{"&::before":{content:'""',width:"1px",height:"100%",bg:"border.default"},"&:hover::before, &:focus-visible::before":{width:"3px",bg:"accent.emphasis"}}}):null,jsxRuntimeExports.jsx(Box,{"data-testid":"loop-split-page",sx:lo?{flex:"1 1 0",minWidth:0,minHeight:0,display:"flex",...paneOpening("right")}:{position:"absolute",inset:0,visibility:"hidden",pointerEvents:"none",zIndex:-1},children:Au})]}),Ou]})}const LOOP_PAGE_LAYOUT_PLUGIN_NAME="@datalayer/loop-plugin-page-layout",NO_TURN$4=signal$2({id:0,status:"idle"}),pageLayoutChatMode=signal$2("floating-draggable"),promptStance=signal$2("floating-top");let floatingStance="floating-top";const PAGE_LAYOUT_DISABLED_MODES=["assistant"];function pageLayoutForChatMode(Au){switch(Au){case"sidebar":return{bandMode:"panel",panelMode:"docked"};case"floating":return{bandMode:"panel",panelMode:"overlay"};case"floating-small":return{bandMode:"panel",panelMode:"popup"};default:return{bandMode:"floating",panelMode:"docked"}}}function setPageLayoutChatMode(Au){pageLayoutChatMode.value=Au;const{bandMode:lo}=pageLayoutForChatMode(Au);promptStance.value=lo==="floating"?floatingStance:"docked-top",lo==="panel"&&openPagePanel()}function ChatModeAction(){const Au=useSignalValue$1(pageLayoutChatMode);return jsxRuntimeExports.jsx(ChatViewModeToggle,{value:Au,onChange:setPageLayoutChatMode,disabledModes:PAGE_LAYOUT_DISABLED_MODES})}function LoopPageLayout({parts:Au,promptMode:lo,pageSize:$u}){const Ru=useContributions(LoopChatTurn),Iu=useSignalValue$1(Ru[0]?.value.turn??NO_TURN$4),Pu=useSignalValue$1(pageLayoutChatMode),Ou=lo==="floating"?pageLayoutForChatMode(Pu):{bandMode:"docked",panelMode:"docked"};return jsxRuntimeExports.jsx(PageLayout,{page:Au.editors,hasPage:Au.hasEditor,panel:Au.transcript,band:Au.prompt,chips:Au.chips,picker:Au.picker,transient:Au.transient,activity:Iu.activity,bandMode:Ou.bandMode,panelMode:Ou.panelMode,pageSize:$u})}function ConversationToggle(){return jsxRuntimeExports.jsx(PagePanelToggle,{panelName:"conversation",icon:CommentDiscussionIcon,sx:{order:2}})}const LoopPageLayoutPlugin={name:LOOP_PAGE_LAYOUT_PLUGIN_NAME,config:{arrangement:"page",turnPanel:"below",turnPanelFooter:"full",prompt:"docked",promptAnchor:"top",pageSize:void 0},displayName:"Page layout",description:"The editor — or, in the chat view, the conversation — on a centred sheet, the prompt docked above it at the same width or floating over it as a draggable card, the current turn under the prompt, the conversation in a side panel; or, split, the conversation and the work side by side with a hairline to drag.",octicon:"file",emoji:"📄",build:({config:Au,...lo})=>{if(Au.arrangement==="split")return lo.contribute(LoopChatLayout,{id:"split-layout",prompt:"docked",Component:SplitLayout},{id:"split-layout"}),{components:[]};const $u=Au.prompt,Ru=Au.pageSize;floatingStance=Au.promptAnchor==="bottom"?"floating-bottom":"floating-top",$u==="floating"&&(promptStance.value=floatingStance);const Iu=Pu=>jsxRuntimeExports.jsx(LoopPageLayout,{parts:Pu,promptMode:$u,pageSize:Ru});if(lo.contribute(LoopChatLayout,{id:"page-layout",prompt:$u==="floating"?floatingStance:"docked-top",promptStance:$u==="floating"?promptStance:void 0,Component:Iu},{id:"page-layout"}),Au.turnPanel!=="none"){const Pu=Au.turnPanelFooter,Ou=()=>jsxRuntimeExports.jsx(TurnPanel,{footer:Pu});lo.contribute(LoopPromptPanel,{id:"page-layout-turn",placement:Au.turnPanel,order:0,Component:Ou},{id:"page-layout-turn"})}return{components:[{id:"page-layout-conversation-toggle",slot:LoopSlots.header,Component:ConversationToggle},...$u==="floating"?[{id:"page-layout-chat-mode",slot:LoopSlots.promptAction,Component:ChatModeAction}]:[]]}}};function loopPlugins(Au={}){const{serverUrl:lo,target:$u="browser",defaultEditor:Ru,showViewSelector:Iu=!0,hideChatHeader:Pu=!1,chatHeaderButtons:Ou=!1,promptPlacement:Mu,autoFocusPrompt:Du=!0,suggestionLabels:Lu=!0,fullScreenTopOffset:Bu=0,showAgentVariants:ju=!1,agentSummary:Fu=!0,teamId:zu,teamPicker:Uu=!0,pageLayout:Hu=!1,pageLayoutArrangement:Vu="page",pageLayoutTurnPanel:Gu="below",pageLayoutPrompt:Wu="docked",pageLayoutPromptAnchor:Ku="top",pageLayoutSize:Ju,pageLayoutTurnPanelFooter:Yu="full",localAgent:Xu,localAgentSpec:ed,datalayerAgentSpecId:td,datalayerCreatePayload:nd,datalayerVisitors:od,datalayerKept:sd,embedToken:ad,targetFixed:pd,themeVariant:gd,themeOverrides:xd,colorMode:yd,presence:vd,showTokenUsage:wd,voice:Td,thread:cd,floatingPrompt:dd=!1,editorSelector:md=!1,editors:ld=!0,conversation:hd=!0,commandPalette:bd=!1,pluginsPanel:Sd=!1,windowFrame:kd=!1,firstPromptHook:Rd}=Au,Od=Ru??(ld?"notebook":"none");return hd?[configurePlugin(ChatPlugin,{defaultSurface:Od,showSurfaceSelector:ld&&Iu&&!md,hideHeader:Pu,headerButtons:{newChat:Ou,clear:Ou},promptPlacement:dd?"floating":Mu,autoFocusPrompt:Du,suggestionLabels:Lu,fullScreenTopOffset:Bu,themeVariant:gd,themeOverrides:xd,colorMode:yd,presence:vd,showTokenUsage:wd,...Td?{voice:Td}:{},...cd?{thread:cd}:{}}),configurePlugin(InputPromptPlugin,{firstPromptHook:Rd}),ChatHeaderPlugin,A2uiSurfacePlugin,PapSignInPlugin,ChatViewPlugin,...ld?[NotebookViewPlugin,DocumentViewPlugin]:[],configurePlugin(AgentsPlugin,{serverUrl:lo,target:$u,datalayerAgentSpecId:td,datalayerCreatePayload:nd,datalayerVisitors:od,datalayerKept:sd,embedToken:ad,targetFixed:pd,showAgentVariants:ju,showAgentSummary:Fu,teamId:zu,showTeamPicker:Uu,localAgent:Xu??(ed?{createPayload:{description:`Local agent from the ${ed} spec`,agent_library:"pydantic-ai",agent_spec_id:ed,enable_codemode:!1}}:void 0)}),...ld?[NotebookExtension,DocumentExtension]:[],A2uiPlugin,AgentspecsPlugin,ModelsPlugin,ThemePlugin,SubagentActivityPlugin,configurePlugin(ShellPlugin,{defaultEditor:Od,showSelector:ld&&md}),...dd?[PromptPlugin]:[],...Hu?[configurePlugin(LoopPageLayoutPlugin,{arrangement:Vu,turnPanel:Gu,turnPanelFooter:Yu,prompt:Wu,promptAnchor:Ku,pageSize:Ju})]:[],...bd?[LoopCommandsPlugin]:[],...Sd?[PluginsPanelPlugin]:[],...kd?[WindowFramePlugin]:[]]:[ThemePlugin,configurePlugin(ShellPlugin,{defaultEditor:"none",showSelector:!1}),...bd?[LoopCommandsPlugin]:[],...Sd?[PluginsPanelPlugin]:[],...kd?[WindowFramePlugin]:[]]}function LoopEmbed({agentId:Au="",showHeader:lo=!1,chatHeaderActions:$u,headerActions:Ru,headerContainer:Iu,frameTitle:Pu,frameHeight:Ou,sidebarRail:Mu=!1,plugins:Du=[],...Lu}){const Bu=reactExports.useRef(Lu.firstPromptHook);Bu.current=Lu.firstPromptHook;const ju=reactExports.useMemo(()=>buildLoopReactor([...loopPlugins({...Lu,windowFrame:Lu.windowFrame||Pu!==void 0,firstPromptHook:()=>Bu.current?.()}),...Du]),[Lu.serverUrl,Lu.target,Lu.datalayerAgentSpecId,Lu.targetFixed,Lu.themeVariant,JSON.stringify(Lu.themeOverrides??null),Lu.colorMode,Lu.presence?.name,Lu.presence?.face,Lu.presence?.welcome,Lu.presence?.paused,Lu.showTokenUsage,JSON.stringify({...Lu.voice??{},engines:void 0,token:void 0}),Lu.thread?.id,JSON.stringify(Lu.datalayerCreatePayload??null),JSON.stringify(Lu.datalayerVisitors??null),Lu.datalayerKept?.url,Lu.embedToken,Lu.defaultEditor,Lu.showViewSelector,Lu.hideChatHeader,Lu.chatHeaderButtons,Lu.promptPlacement,Lu.autoFocusPrompt,Lu.suggestionLabels,Lu.fullScreenTopOffset,Lu.showAgentVariants,Lu.agentSummary,Lu.teamId,Lu.teamPicker,Lu.pageLayout,Lu.pageLayoutTurnPanel,Lu.pageLayoutTurnPanelFooter,Lu.pageLayoutPrompt,Lu.pageLayoutPromptAnchor,Lu.pageLayoutSize?.format,Lu.pageLayoutSize?.width,Lu.pageLayoutSize?.height,Lu.localAgentSpec,Lu.floatingPrompt,Lu.editorSelector,Lu.editors,Lu.conversation,Lu.commandPalette,Lu.pluginsPanel,Lu.windowFrame,Pu!==void 0,Du]);useReactor(ju);const Fu=jsxRuntimeExports.jsx(LoopWorkspace,{serverUrl:Lu.serverUrl??"",agentId:Au,reactor:ju,manageReactor:!1,showViewSelector:Lu.showViewSelector,showHeader:lo,chatHeaderActions:$u,headerActions:Ru,headerContainer:Iu,sidebarRail:Mu});return jsxRuntimeExports.jsx(QueryClientProvider,{client:internalQueryClient,children:Pu!==void 0?jsxRuntimeExports.jsx(WindowFrame,{title:Pu,height:Ou,children:Fu}):jsxRuntimeExports.jsx(Box,{height:"100%",minHeight:0,width:"100%",flex:"1 1 auto",minWidth:0,children:Fu})})}const RECORD_KIND_WORDS={session:"Session",tool_call:"Tool call",decision:"Rule",check:"Check",approval:"Approval",output:"Answer",feedback:"Feedback",turn:"Turn",run:"Working",notification:"Notification"};function entryOf(Au){return{uid:String(Au.uid??""),sessionUid:String(Au.session_uid??""),deploymentUid:String(Au.deployment_uid??""),version:Number(Au.version)||0,kind:String(Au.kind??"output"),summary:String(Au.summary??""),payload:Au.payload&&typeof Au.payload=="object"?Au.payload:{},createdAt:String(Au.created_at??"")}}function runEndOf(Au){const lo=Au.kind==="output"?Au.payload.status:void 0;return typeof lo=="string"&&lo in RUN_END_WORDS?lo:""}function entrySaid(Au){return Au.summary||RUN_END_WORDS[runEndOf(Au)]||""}function sessionSentence(Au){const lo=Au.filter(Ou=>Ou.kind==="tool_call").length,$u=Au.filter(Ou=>Ou.kind==="check"),Ru=Au.map(runEndOf).filter(Boolean),Iu=Ru.filter(Ou=>Ou==="answered").length,Pu=[lo===0?"No tool called":`${lo} tool call${lo===1?"":"s"}`];return $u.length&&Pu.push(`${$u.length} step${$u.length===1?"":"s"} a check did not let pass`),Ru[Ru.length-1]==="stopped"?Pu.push("stopped"):Iu&&Pu.push(`${Iu} answer${Iu===1?"":"s"}`),`${Pu.join(", ")}.`}async function read(Au,lo,$u){if(!Au.aiAgentsUrl)throw new Error("The record service is not configured.");const Ru=await fetch(`${Au.aiAgentsUrl.replace(/\/+$/,"")}/api/ai-agents/v1/apps${lo}`,{headers:Au.token?{Authorization:`Bearer ${Au.token}`}:{}}),Iu=await Ru.json().catch(()=>({}));if(!Ru.ok||Iu.success===!1)throw new Error(`${$u}: ${String(Iu.detail??Ru.status)}`);return Iu}async function listSessions(Au,lo,$u=20,Ru=!1){const Iu=await read(Au,`/sessions?app_uid=${encodeURIComponent(lo)}&limit=${$u}${Ru===null?"":`&tests=${Ru}`}`,"The sessions could not be read");return Array.isArray(Iu.sessions)?Iu.sessions.map(entryOf):[]}async function readSession(Au,lo){const $u=await read(Au,`/records?session_uid=${encodeURIComponent(lo)}&limit=500`,"The session could not be read");return Array.isArray($u.entries)?$u.entries.map(entryOf).filter(Ru=>Ru.kind!=="run"):[]}const APP_ACTIVITY_WORDS={title:"Activity",unsaved:"Recorded once it is saved on Datalayer: each session there — its address, or its Preview on Datalayer — is listed here.",signedOut:"Its activity is its owner’s: sign in to Datalayer to read it.",none:"Nothing yet: a session on Datalayer — its address, or the Preview on Datalayer — is recorded here."},NO_TURN$3=signal$2({id:0,status:"idle"});function useRead(Au,lo,$u=!0){const[Ru,Iu]=reactExports.useState({loading:$u});return reactExports.useEffect(()=>{if(!$u)return;let Pu=!1;return Iu(Ou=>({...Ou,loading:!0})),Au().then(Ou=>!Pu&&Iu({value:Ou,loading:!1}),Ou=>!Pu&&Iu({error:Ou instanceof Error?Ou.message:String(Ou),loading:!1})),()=>{Pu=!0}},[lo,$u]),Ru}function Session({context:Au,session:lo}){const[$u,Ru]=reactExports.useState(!1),Iu=useRead(()=>readSession(Au,lo.sessionUid),`${lo.sessionUid}:${Au.token}`,$u);return jsxRuntimeExports.jsxs(Box,{as:"details",onToggle:Pu=>Ru(Pu.currentTarget.open),borderTop:"1px solid",borderColor:"border.muted",py:2,children:[jsxRuntimeExports.jsxs(Box,{as:"summary",cursor:"pointer",fontSize:1,children:[lo.createdAt?jsxRuntimeExports.jsx(RelativeTime,{datetime:lo.createdAt}):"A session",lo.version?` · version ${lo.version}`:"",Iu.value?` · ${sessionSentence(Iu.value)}`:""]}),$u?Iu.loading?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):Iu.error?jsxRuntimeExports.jsx(Text$3,{role:"alert",sx:{fontSize:1},children:Iu.error}):jsxRuntimeExports.jsx(Box,{as:"ol",pl:3,mt:2,mb:0,fontSize:1,children:(Iu.value??[]).map(Pu=>jsxRuntimeExports.jsxs(Box,{as:"li",mb:1,children:[jsxRuntimeExports.jsx(Label,{sx:{mr:2},children:RECORD_KIND_WORDS[Pu.kind]??Pu.kind}),entrySaid(Pu)]},Pu.uid))}):null]})}function AppActivity({appUid:Au}){const lo=useIAMStore(ju=>ju.token)??"",$u=useCoreStore(ju=>ju.configuration)?.aiAgentsUrl??"",Ru=useContributions(LoopChatTurn),Iu=useSignalValue$1(Ru[0]?.value.turn??NO_TURN$3),Pu=Iu.status!=="thinking"&&Iu.status!=="streaming",[Ou,Mu]=reactExports.useState(0);reactExports.useEffect(()=>{Pu&&Mu(Iu.id)},[Pu,Iu.id]);const Du={aiAgentsUrl:$u,token:lo},Lu=!!(Au&&lo),Bu=useRead(()=>listSessions(Du,Au??""),`${Au}:${lo}:${$u}:${Ou}`,Lu);return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-activity",children:[jsxRuntimeExports.jsx(Heading$2,{as:"h3",sx:{fontSize:2,mb:2},children:APP_ACTIVITY_WORDS.title}),Au?lo?Bu.loading&&!Bu.value?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):Bu.error?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:Bu.error}):(Bu.value??[]).length===0?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_ACTIVITY_WORDS.none}):(Bu.value??[]).map(ju=>jsxRuntimeExports.jsx(Session,{context:Du,session:ju},ju.uid)):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_ACTIVITY_WORDS.signedOut}):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_ACTIVITY_WORDS.unsaved})]})}const APP_ACTIVITY_PLUGIN_NAME="@datalayer/loop-plugin-app-activity";function defineAppActivityPlugin(Au,lo){function $u(){return jsxRuntimeExports.jsx(AppActivity,{appUid:lo})}return{name:`${APP_ACTIVITY_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: activity`,description:`What ${Au.name} did, session by session, from its record.`,octicon:"pulse",build:()=>({components:[{id:"app-activity",slot:LoopSlots.sidebar,order:20,Component:$u,rail:{label:"Activity",icon:PulseIcon}}]})}}const APP_PANEL_WIDTH=380;function elementsByPlace(Au){const lo=Au.filter($u=>$u.where==="page");return{panels:Au.filter($u=>$u.where==="panel"),page:lo.length>0?lo[lo.length-1]:null}}function ElementBody({element:Au,send:lo}){return jsxRuntimeExports.jsx(AnswerShowsView,{display:Au.shows,send:($u,Ru)=>lo!==void 0&&!lo($u,Ru)})}function ElementHeader({element:Au}){return jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",justifyContent:"space-between",gap:2,mb:2,children:[jsxRuntimeExports.jsx(Text$3,{as:"h2",sx:{fontSize:2,fontWeight:"bold",m:0},children:Au.title}),jsxRuntimeExports.jsx(IconButton,{icon:XIcon,variant:"invisible",size:"small","aria-label":`Close ${Au.title}`,onClick:()=>closeLoopElement(Au.id)})]})}function AppElements({workspace:Au}){const lo=reactExports.useSyncExternalStore(onLoopElements,openLoopElements,openLoopElements),{panels:$u,page:Ru}=elementsByPlace(lo),Iu=Au?.viewControls.send;return $u.length===0&&Ru===null?null:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[$u.length>0?jsxRuntimeExports.jsx(Box,{as:"aside","aria-label":"Side panel",position:"absolute",top:0,right:0,bottom:0,width:`min(${APP_PANEL_WIDTH}px, 100%)`,zIndex:1,overflowY:"auto",borderLeft:"1px solid",borderColor:"border.default",bg:"canvas.subtle",boxShadow:"shadow.medium",p:3,display:"flex",flexDirection:"column",gap:3,children:$u.map(Pu=>jsxRuntimeExports.jsxs(Box,{as:"section","aria-label":Pu.title,children:[jsxRuntimeExports.jsx(ElementHeader,{element:Pu}),jsxRuntimeExports.jsx(ElementBody,{element:Pu,send:Iu})]},Pu.id))}):null,Ru!==null?jsxRuntimeExports.jsxs(Box,{role:"dialog","aria-label":Ru.title,position:"absolute",inset:0,zIndex:2,overflowY:"auto",bg:"canvas.default",p:[3,4],children:[jsxRuntimeExports.jsx(ElementHeader,{element:Ru}),jsxRuntimeExports.jsx(ElementBody,{element:Ru,send:Iu})]}):null]})}const QUESTION_DISPLAY_TYPE="application/vnd.datalayer.loop.question+json",SchemaForm=reactExports.lazy(()=>__vitePreload(()=>import("./chunks/SchemaForm-CE5NfpBU.js"),[],import.meta.url));function questionOf(Au){const lo=Au.data??{},$u=lo.kind;if(Au.type!==QUESTION_DISPLAY_TYPE||$u!=="text"&&$u!=="choice"&&$u!=="file"&&$u!=="form"||typeof lo.prompt!="string")throw new Error(`Display ${Au.id} is not a question`);const Ru=Iu=>Array.isArray(Iu)?Iu.filter(Pu=>typeof Pu=="string"):[];return{kind:$u,prompt:lo.prompt,options:Ru(lo.options),accept:Ru(lo.accept),form:lo.form&&typeof lo.form=="object"?lo.form:{},answered:typeof lo.answered=="string"?lo.answered:null,answerable:(Au.actions??[]).some(Iu=>Iu.name===ANSWER_ACTION)}}function QuestionView({display:Au,act:lo,upload:$u}){const Ru=questionOf(Au),[Iu,Pu]=reactExports.useState(""),[Ou,Mu]=reactExports.useState(null),Du=Bu=>{if(!lo){Mu("The chat cannot take an answer here.");return}Mu(null),Promise.resolve(lo({action:ANSWER_ACTION,payload:{value:Bu}})).catch(ju=>Mu(ju instanceof Error?ju.message:String(ju)))};if(Ru.answered!==null)return jsxRuntimeExports.jsxs(Text$3,{as:"p",sx:{color:"fg.muted",fontSize:1,m:0},children:["Answered: ",Ru.answered]});const Lu=Ru.answerable&&!!lo;return jsxRuntimeExports.jsxs(Box$1,{display:"flex",flexDirection:"column",gap:2,"data-question-kind":Ru.kind,children:[Ru.kind==="choice"?jsxRuntimeExports.jsx(Box$1,{display:"flex",gap:2,flexWrap:"wrap",children:Ru.options.map(Bu=>jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:!Lu,onClick:()=>Du(Bu),children:Bu},Bu))}):null,Ru.kind==="text"?jsxRuntimeExports.jsxs(Box$1,{as:"form",display:"flex",gap:2,onSubmit:Bu=>{Bu.preventDefault(),Iu.trim()&&Du(Iu.trim())},children:[jsxRuntimeExports.jsx(TextInput$1,{"aria-label":Ru.prompt,value:Iu,disabled:!Lu,onChange:Bu=>Pu(Bu.target.value)}),jsxRuntimeExports.jsx(ButtonComponent,{type:"submit",size:"small",disabled:!Lu||!Iu.trim(),children:"Answer"})]}):null,Ru.kind==="form"?jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(SchemaForm,{schema:Ru.form,disabled:!Lu,onSubmit:({formData:Bu})=>Du(Bu??{})})}):null,Ru.kind==="file"?jsxRuntimeExports.jsx("input",{type:"file","aria-label":Ru.prompt,accept:Ru.accept.join(",")||void 0,disabled:!Lu||!$u,onChange:Bu=>{const ju=Bu.target.files?.[0];if(ju){if(!$u){Mu("The chat cannot take a file here.");return}Mu(null),$u(ju).then(Fu=>Du(Fu)).catch(Fu=>Mu(Fu instanceof Error?Fu.message:String(Fu)))}}}):null,Ou?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{color:"danger.fg",fontSize:1,m:0},children:Ou}):null]})}const APP_ELEMENTS_PLUGIN_NAME="@datalayer/loop-plugin-app-elements",AppElementsPlugin={name:APP_ELEMENTS_PLUGIN_NAME,displayName:"Side panel and pages",description:"What an application opens beside the conversation: a side panel, or a page of its own.",octicon:"sidebar-expand",contributes:[contribution(Renderers,defineRenderer({type:QUESTION_DISPLAY_TYPE,component:QuestionView}),{id:"app-elements:question"})],build:()=>({components:[{id:"app-elements",slot:LoopSlots.root,Component:AppElements}]}),register:()=>clearLoopElements},appComponentsPluginName=Au=>`@datalayer/loop-plugin-app-components-${Au}`,hasCustomComponents=Au=>(Au.interface.customComponents??[]).length>0;function defineAppComponentsPlugin(Au,lo){const $u=Au.interface.customComponents??[];if($u.length===0)throw new Error(`“${Au.name}” has no component of its own to contribute.`);return{name:appComponentsPluginName(Au.id),displayName:`${Au.name}'s components`,description:`The components ${Au.name}'s developer wrote: ${$u.map(Ru=>Ru.name).join(", ")}.`,octicon:"apps",contributes:$u.flatMap(Ru=>[contribution(LoopCanvasBlock,{id:Ru.name,ui:`app:${Au.id}`,component:customComponentEntry(Ru,Au.version)},{id:Ru.name}),contribution(LoopA2uiComponent,{id:Ru.name,app:Au.id,implementation:customImplementation(Ru,Au.version,lo,Au.id)},{id:Ru.name})])}}const COMPUTER_PARTS=["browse","files","shell"],COMPUTER_PART_TOOLS={browse:["open_page","read_page","page_screenshot","click_on_page","type_on_page"],files:["list_computer_files","read_computer_file","write_computer_file"],shell:["execute_code","run_skill_script"]},COMPUTER_WORDS={title:"Computer",part:{browse:"Browse",files:"Files",shell:"Shell"},on:"on",off:"off",none:"It has no computer: browse, files and shell are all off. Turn one on in its permissions to give it one.",offSaid:Au=>`Off, so its agent is given no tool for it: ${Au.join(", ")}.`,browser:"Browser",noBrowser:"No browser is installed on its computer.",noPage:"Its browser has opened no page yet.",pageAlt:Au=>`The page its browser shows: ${Au}`,clickToAct:"Click on the page to click there; with the page selected, what you type goes to it.",typeOnPage:"Text to type on the page",type:"Type",address:"An address to open",open:"Open",scrollUp:"Scroll up",scrollDown:"Scroll down",agentHas:"Its agent has the computer.",youHave:"You have the computer: its agent waits for it until you hand it back.",someoneHas:"Somebody else has taken this computer over.",takeOver:"Take over",handBack:"Hand back",run:"Run",yourCode:"Python to run on its computer",terminal:"What ran on it",nothingRan:"Nothing has run on it yet in this conversation.",files:"Files",notStarted:"Its computer starts when its agent first uses it: no file yet.",emptyDirectory:"Empty.",up:"Up",download:"Download",signedOut:"Its computer is shown once you are signed in to Datalayer."};function computerParts(Au){const lo=Au.permissions?.computer;return{browse:!!lo?.browse,files:!!lo?.files,shell:!!lo?.shell}}const hasComputer=Au=>COMPUTER_PARTS.some(lo=>Au[lo]),partsOff=Au=>COMPUTER_PARTS.filter(lo=>!Au[lo]).map(lo=>COMPUTER_WORDS.part[lo].toLowerCase());function partOf(Au){return COMPUTER_PARTS.find(lo=>COMPUTER_PART_TOOLS[lo].includes(Au))}const OUTPUT_LIMIT=4e3;function outputOf(Au){let lo=Au;if(typeof lo=="string")try{const Ru=JSON.parse(lo);Ru&&typeof Ru=="object"&&!Array.isArray(Ru)&&(lo=Ru)}catch{}let $u;if(lo&&typeof lo=="object"&&!Array.isArray(lo)){const Ru=lo,Iu=[typeof Ru.stdout=="string"?Ru.stdout:Ru.output,Ru.stderr,Ru.error??Ru.execution_error??Ru.code_error].filter(Pu=>typeof Pu=="string"&&Pu.trim()!=="");$u=Iu.length>0?Iu.join(`
4004
4004
  `):"stdout"in Ru||"output"in Ru?"":JSON.stringify(lo,null,2)}else $u=typeof lo=="string"?lo:lo==null?"":JSON.stringify(lo,null,2);return $u.length>OUTPUT_LIMIT?`${$u.slice(0,OUTPUT_LIMIT)}
4005
4005
  … (${($u.length-OUTPUT_LIMIT).toLocaleString("en")} characters more)`:$u}function commandOf(Au){for(const lo of["code","path","script_name","url","selector"]){const $u=Au[lo];if(typeof $u=="string"&&$u.trim())return $u}return Object.keys(Au).length?JSON.stringify(Au):""}function terminalEntries(Au){const lo=[];for(const $u of Au){if($u.role!=="tool")continue;const Ru=partOf($u.name);Ru&&lo.push({tool:$u.name,part:Ru,command:commandOf($u.args??{}),output:$u.result===void 0?void 0:outputOf($u.result)})}return lo}const computerUrl=(Au,lo="")=>`${Au.serverUrl.replace(/\/+$/,"")}/api/v1/apps/agents/${encodeURIComponent(Au.agentId)}/computer${lo}`;function computerFileUrl(Au,lo){const $u=computerUrl(Au,`/file?path=${encodeURIComponent(lo)}`),Ru=(Au.userAppsUrl||"").trim();if(!Ru)return $u;try{const Iu=new URL($u),Pu=new URL(Ru);return Iu.protocol=Pu.protocol,Iu.host=Pu.host,Iu.toString()}catch{return $u}}async function asked(Au,lo,$u={}){const Ru=await fetch(computerUrl(Au,lo),{...$u,headers:{...$u.body?{"Content-Type":"application/json"}:{},...Au.token?{Authorization:`Bearer ${Au.token}`}:{}}});if(!Ru.ok){let Iu=`${Ru.status}`;try{const Pu=await Ru.json();Iu=typeof Pu.detail=="string"?Pu.detail:Iu}catch{}throw new Error(Iu)}return Ru}const readComputer=async Au=>(await asked(Au,"")).json(),listComputerFiles=async(Au,lo=".")=>(await(await asked(Au,`/files?path=${encodeURIComponent(lo)}`)).json()).entries,downloadComputerFile=async(Au,lo)=>{const $u=await fetch(computerFileUrl(Au,lo),{headers:Au.token?{Authorization:`Bearer ${Au.token}`}:{}});if(!$u.ok){let Ru=`${$u.status}`;try{const Iu=await $u.json();Ru=typeof Iu.detail=="string"?Iu.detail:Ru}catch{}throw new Error(Ru)}return $u.blob()},takeOverComputer=async Au=>(await asked(Au,"/take-over",{method:"POST"})).json(),handBackComputer=async Au=>{await asked(Au,"/hand-back",{method:"POST"})},runOnComputer=async(Au,lo)=>(await asked(Au,"/run",{method:"POST",body:JSON.stringify({code:lo})})).json(),BROWSER_KEYS=["Enter","Tab","Backspace","Escape","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","PageUp","PageDown"],readBrowserScreenshot=async Au=>{const lo=await fetch(computerUrl(Au,"/browser/screenshot"),{headers:Au.token?{Authorization:`Bearer ${Au.token}`}:{},cache:"no-store"});if(lo.status!==404){if(!lo.ok){let $u=`${lo.status}`;try{const Ru=await lo.json();$u=typeof Ru.detail=="string"?Ru.detail:$u}catch{}throw new Error($u)}return lo.blob()}},onBrowser=async(Au,lo,$u)=>(await(await asked(Au,`/browser/${lo}`,{method:"POST",body:JSON.stringify($u)})).json()).page,clickOnBrowser=(Au,lo,$u)=>onBrowser(Au,"click",{x:lo,y:$u}),typeOnBrowser=(Au,lo)=>onBrowser(Au,"type",{text:lo}),pressOnBrowser=(Au,lo)=>onBrowser(Au,"key",{key:lo}),scrollBrowser=(Au,lo)=>onBrowser(Au,"scroll",{dy:lo}),openOnBrowser=(Au,lo)=>onBrowser(Au,"open",{url:lo});function pointOnPage(Au,lo,$u){const Ru=(Iu,Pu,Ou)=>Pu>0?Math.round(Iu*Ou/Pu):Iu;return{x:Math.max(0,Math.min($u.width,Ru(Au.x,lo.width,$u.width))),y:Math.max(0,Math.min($u.height,Ru(Au.y,lo.height,$u.height)))}}function parentOf(Au){const lo=Au.split("/").filter($u=>$u&&$u!==".");return lo.pop(),lo.length?lo.join("/"):"."}const NO_TURN$2=signal$2({id:0,status:"idle"}),NO_CONVERSATION$1=signal$2([]),MONO_FACE='ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',MONO={fontFamily:MONO_FACE,fontSize:0,whiteSpace:"pre-wrap",wordBreak:"break-word",m:0};function Parts({app:Au}){const lo=computerParts(Au),$u=partsOff(lo);return jsxRuntimeExports.jsxs(Box,{"data-testid":"computer-parts",children:[jsxRuntimeExports.jsx(Box,{display:"flex",gap:1,flexWrap:"wrap",mb:1,children:COMPUTER_PARTS.map(Ru=>jsxRuntimeExports.jsxs(Label,{variant:lo[Ru]?"success":"secondary","data-part":Ru,"data-on":lo[Ru]?"true":"false",children:[COMPUTER_WORDS.part[Ru],":"," ",lo[Ru]?COMPUTER_WORDS.on:COMPUTER_WORDS.off]},Ru))}),$u.length>0&&$u.length<COMPUTER_PARTS.length?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",m:0},children:COMPUTER_WORDS.offSaid($u)}):null]})}function Terminal({conversation:Au}){const lo=terminalEntries(Au);return jsxRuntimeExports.jsxs(Box,{"data-testid":"computer-terminal",children:[jsxRuntimeExports.jsx(Heading$2,{as:"h4",sx:{fontSize:1,mt:3,mb:1},children:COMPUTER_WORDS.terminal}),lo.length===0?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:COMPUTER_WORDS.nothingRan}):jsxRuntimeExports.jsx(Box,{bg:"canvas.inset",border:"1px solid",borderColor:"border.muted",borderRadius:2,p:2,maxHeight:320,overflow:"auto",children:lo.map(($u,Ru)=>jsxRuntimeExports.jsxs(Box,{mb:2,children:[jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{...MONO,fontWeight:"semibold"},children:`$ ${$u.tool}${$u.command?`: ${$u.command}`:""}`}),$u.output===void 0?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):jsxRuntimeExports.jsx(Text$3,{as:"pre",sx:{...MONO,color:"fg.muted"},children:$u.output})]},Ru))})]})}function save(Au,lo){const $u=URL.createObjectURL(new Blob([Au],{type:"application/octet-stream"})),Ru=document.createElement("a");Ru.href=$u,Ru.download=lo,Ru.click(),URL.revokeObjectURL($u)}function Files({context:Au,state:lo,ended:$u}){const[Ru,Iu]=reactExports.useState("."),[Pu,Ou]=reactExports.useState(),[Mu,Du]=reactExports.useState("");return reactExports.useEffect(()=>{if(!lo.started)return;let Lu=!1;return listComputerFiles(Au,Ru).then(Bu=>{Lu||(Ou(Bu),Du(""))},Bu=>!Lu&&Du(Bu instanceof Error?Bu.message:String(Bu))),()=>{Lu=!0}},[Au.serverUrl,Au.agentId,Au.token,Ru,lo.started,$u]),jsxRuntimeExports.jsxs(Box,{"data-testid":"computer-files",children:[jsxRuntimeExports.jsxs(Heading$2,{as:"h4",sx:{fontSize:1,mt:3,mb:1},children:[COMPUTER_WORDS.files,Ru!=="."?jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"normal",color:"fg.muted"},children:` · ${Ru}`}):null]}),lo.started?Mu?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"danger.fg",m:0},children:Mu}):Pu?jsxRuntimeExports.jsxs(Box,{as:"ul",listStyle:"none",p:0,m:0,children:[Ru!=="."?jsxRuntimeExports.jsx(Box,{as:"li",children:jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"invisible",onClick:()=>Iu(parentOf(Ru)),children:COMPUTER_WORDS.up})}):null,Pu.length===0?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:COMPUTER_WORDS.emptyDirectory}):null,Pu.map(Lu=>jsxRuntimeExports.jsx(Box,{as:"li","data-path":Lu.path,display:"flex",alignItems:"center",gap:2,fontSize:1,py:1,borderTop:"1px solid",borderColor:"border.muted",children:Lu.type==="directory"?jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"invisible",onClick:()=>Iu(Lu.path),children:`${Lu.name}/`}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{flex:1,fontFamily:MONO_FACE,fontSize:0},children:Lu.name}),jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontSize:0},children:`${Lu.size.toLocaleString("en")} bytes`}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small","aria-label":`${COMPUTER_WORDS.download} ${Lu.name}`,onClick:()=>{downloadComputerFile(Au,Lu.path).then(Bu=>save(Bu,Lu.name),Bu=>Du(Bu instanceof Error?Bu.message:String(Bu)))},children:COMPUTER_WORDS.download})]})},Lu.path))]}):jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:COMPUTER_WORDS.notStarted})]})}const BROWSER_POLL_MS=1500;function BrowserView({context:Au,state:lo,mine:$u}){const[Ru,Iu]=reactExports.useState(),[Pu,Ou]=reactExports.useState(!1),[Mu,Du]=reactExports.useState(lo.page),[Lu,Bu]=reactExports.useState(""),[ju,Fu]=reactExports.useState(""),[zu,Uu]=reactExports.useState(""),[Hu,Vu]=reactExports.useState(0),Gu=reactExports.useRef(void 0);reactExports.useEffect(()=>Du(lo.page),[lo.page]),reactExports.useEffect(()=>{if(!lo.browser)return;let Yu=!1;const Xu=()=>readBrowserScreenshot(Au).then(td=>{Yu||(Bu(""),Ou(!td),Gu.current&&URL.revokeObjectURL(Gu.current),Gu.current=td?URL.createObjectURL(td):void 0,Iu(Gu.current))},td=>!Yu&&Bu(td instanceof Error?td.message:String(td)));Xu();const ed=setInterval(Xu,BROWSER_POLL_MS);return()=>{Yu=!0,clearInterval(ed)}},[Au.serverUrl,Au.agentId,Au.token,lo.browser,Hu]),reactExports.useEffect(()=>()=>{Gu.current&&URL.revokeObjectURL(Gu.current)},[]);const Wu=Yu=>Yu.then(Xu=>{Du(Xu),Bu(""),Vu(ed=>ed+1)},Xu=>Bu(Xu instanceof Error?Xu.message:String(Xu))),Ku=Yu=>{const Xu=Yu.currentTarget,ed=Xu.getBoundingClientRect(),td=pointOnPage({x:Yu.clientX-ed.left,y:Yu.clientY-ed.top},{width:ed.width,height:ed.height},{width:Xu.naturalWidth,height:Xu.naturalHeight});Xu.focus(),Wu(clickOnBrowser(Au,td.x,td.y))},Ju=Yu=>{Yu.metaKey||Yu.ctrlKey||Yu.altKey||(BROWSER_KEYS.includes(Yu.key)?(Yu.preventDefault(),Wu(pressOnBrowser(Au,Yu.key))):Yu.key.length===1&&(Yu.preventDefault(),Wu(typeOnBrowser(Au,Yu.key))))};return jsxRuntimeExports.jsxs(Box,{"data-testid":"computer-browser",children:[jsxRuntimeExports.jsxs(Heading$2,{as:"h4",sx:{fontSize:1,mt:3,mb:1},children:[COMPUTER_WORDS.browser,Mu?jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"normal",color:"fg.muted"},children:` · ${Mu.title||Mu.url}`}):null]}),lo.browser?Pu||!Ru?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:Pu?COMPUTER_WORDS.noPage:null}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Mu?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontFamily:MONO_FACE,fontSize:0,color:"fg.muted",m:0,mb:1,wordBreak:"break-all"},children:Mu.url}):null,jsxRuntimeExports.jsx("img",{src:Ru,alt:COMPUTER_WORDS.pageAlt(Mu?.title||Mu?.url||""),"data-testid":"computer-browser-page",tabIndex:$u?0:-1,onClick:$u?Ku:void 0,onKeyDown:$u?Ju:void 0,style:{width:"100%",height:"auto",display:"block",border:"1px solid var(--borderColor-muted, #d0d7de)",borderRadius:6,cursor:$u?"pointer":"default"}})]}):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:COMPUTER_WORDS.noBrowser}),Lu?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"danger.fg",m:0,mt:1},children:Lu}):null,$u&&lo.browser?jsxRuntimeExports.jsxs(Box,{mt:2,"data-testid":"computer-browser-controls",children:[jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",m:0,mb:1},children:COMPUTER_WORDS.clickToAct}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:1,mb:1,children:[jsxRuntimeExports.jsx(TextInput$1,{size:"small","aria-label":COMPUTER_WORDS.typeOnPage,placeholder:COMPUTER_WORDS.typeOnPage,value:ju,onChange:Yu=>Fu(Yu.target.value),sx:{flex:1}}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:!ju,onClick:()=>{Wu(typeOnBrowser(Au,ju)),Fu("")},children:COMPUTER_WORDS.type}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",onClick:()=>{Wu(pressOnBrowser(Au,"Enter"))},children:"Enter"})]}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:1,mb:1,children:[jsxRuntimeExports.jsx(TextInput$1,{size:"small","aria-label":COMPUTER_WORDS.address,placeholder:COMPUTER_WORDS.address,value:zu,onChange:Yu=>Uu(Yu.target.value),sx:{flex:1}}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:!zu.trim(),onClick:()=>{Wu(openOnBrowser(Au,zu.trim()))},children:COMPUTER_WORDS.open})]}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:1,children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",onClick:()=>{Wu(scrollBrowser(Au,-400))},children:COMPUTER_WORDS.scrollUp}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",onClick:()=>{Wu(scrollBrowser(Au,400))},children:COMPUTER_WORDS.scrollDown})]})]}):null]})}function YourTerminal({context:Au}){const[lo,$u]=reactExports.useState(""),[Ru,Iu]=reactExports.useState(!1),[Pu,Ou]=reactExports.useState([]),Mu=()=>{Iu(!0),runOnComputer(Au,lo).then(Du=>{Ou(Lu=>[...Lu,{code:lo,output:Du}]),$u(""),Iu(!1)},Du=>{Ou(Lu=>[...Lu,{code:lo,output:{stdout:"",stderr:"",error:Du instanceof Error?Du.message:String(Du)}}]),Iu(!1)})};return jsxRuntimeExports.jsxs(Box,{"data-testid":"computer-your-terminal",mt:2,children:[Pu.map((Du,Lu)=>jsxRuntimeExports.jsxs(Box,{mb:2,children:[jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{...MONO,fontWeight:"semibold"},children:`>>> ${Du.code}`}),jsxRuntimeExports.jsx(Text$3,{as:"pre",sx:{...MONO,color:"fg.muted"},children:[Du.output.stdout,Du.output.stderr,Du.output.error].filter(Boolean).join(`
4006
4006
  `)})]},Lu)),jsxRuntimeExports.jsx(Textarea,{"aria-label":COMPUTER_WORDS.yourCode,placeholder:COMPUTER_WORDS.yourCode,value:lo,onChange:Du=>$u(Du.target.value),sx:{width:"100%",fontFamily:MONO_FACE},rows:3}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",sx:{mt:1},disabled:Ru||!lo.trim(),onClick:Mu,children:COMPUTER_WORDS.run})]})}function AppComputer({app:Au,workspace:lo}){const $u=useIAMStore(sd=>sd.token)??"",Ru=useContributions(LoopChatTurn),Iu=useSignalValue$1(Ru[0]?.value.turn??NO_TURN$2),Pu=useSignalValue$1(Ru[0]?.value.conversation??NO_CONVERSATION$1),Ou=Iu.status!=="thinking"&&Iu.status!=="streaming",[Mu,Du]=reactExports.useState(0);reactExports.useEffect(()=>{Ou&&Du(Iu.id)},[Ou,Iu.id]);const Lu=useChatWords(),Bu=lo?agentServerOf(lo.sandbox,lo.serverUrl):void 0,ju=Bu===void 0?noRuntimeSaid(lo?.sandbox??IDLE_SANDBOX_SNAPSHOT,Lu):void 0,Fu=lo?.agentId||Au.id,[zu,Uu]=reactExports.useState(),Hu=zu?.servedFrom??"",Vu=reactExports.useMemo(()=>Bu===void 0?void 0:{serverUrl:Bu,agentId:Fu,token:$u||void 0,userAppsUrl:Hu||void 0},[Bu,Fu,$u,Hu]),Gu=computerParts(Au),[Wu,Ku]=reactExports.useState(""),[Ju,Yu]=reactExports.useState(!1),Xu=reactExports.useRef(!0);reactExports.useEffect(()=>(Xu.current=!0,()=>{Xu.current=!1}),[]);const ed=reactExports.useCallback(()=>{Vu&&readComputer(Vu).then(sd=>{Xu.current&&(Uu(sd),Ku(""))},sd=>Xu.current&&Ku(sd instanceof Error?sd.message:String(sd)))},[Vu]),td=hasComputer(Gu);reactExports.useEffect(()=>{td&&Vu&&ed()},[td,Vu,ed,Mu]);const nd=sd=>{Vu&&(Yu(!0),sd(Vu).then(()=>{Xu.current&&(Yu(!1),ed())},ad=>{Xu.current&&(Yu(!1),Ku(ad instanceof Error?ad.message:String(ad)))}))},od=!!zu?.yours;return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-computer",children:[jsxRuntimeExports.jsx(Heading$2,{as:"h3",sx:{fontSize:2,mb:2},children:COMPUTER_WORDS.title}),jsxRuntimeExports.jsx(Parts,{app:Au}),td?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[ju?jsxRuntimeExports.jsx(Text$3,{as:"p",role:"status",sx:{fontSize:1,color:"fg.default",m:0,mt:2},children:ju}):null,Wu?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"danger.fg",m:0,mt:2},children:Wu}):null,zu&&Vu?jsxRuntimeExports.jsxs(Box,{mt:2,"data-testid":"computer-holder",children:[jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,m:0,mb:1},children:zu.held?od?COMPUTER_WORDS.youHave:COMPUTER_WORDS.someoneHas:COMPUTER_WORDS.agentHas}),zu.held?od?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"primary",disabled:Ju,onClick:()=>nd(handBackComputer),children:COMPUTER_WORDS.handBack}),jsxRuntimeExports.jsx(YourTerminal,{context:Vu})]}):null:jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:Ju,onClick:()=>nd(takeOverComputer),children:COMPUTER_WORDS.takeOver})]}):null,Gu.browse&&zu&&Vu?jsxRuntimeExports.jsx(BrowserView,{context:Vu,state:zu,mine:od}):null,jsxRuntimeExports.jsx(Terminal,{conversation:Pu}),zu&&Vu?jsxRuntimeExports.jsx(Files,{context:Vu,state:zu,ended:Mu}):null]}):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0,mt:1},children:COMPUTER_WORDS.none})]})}const APP_COMPUTER_PLUGIN_NAME="@datalayer/loop-plugin-app-computer";function defineAppComputerPlugin(Au){function lo({workspace:Ru}){return jsxRuntimeExports.jsx(AppComputer,{app:Au,workspace:Ru})}return{name:`${APP_COMPUTER_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: computer`,description:`The computer ${Au.name} runs on: what ran on it, its files, and taking it over.`,octicon:"device-desktop",build:()=>({components:[{id:"app-computer",slot:LoopSlots.sidebar,order:30,Component:lo,rail:{label:"Computer",icon:DeviceDesktopIcon}}]})}}const SAVE_TOOL="save_to_space",SAVE_WORDS={approve:"Approve and save",decline:"Decline",where:Au=>Au?`To keep as a page of ${Au}:`:"To keep as a page of its Space:"};function draftOfApproval(Au){if(Au.tool_name!==SAVE_TOOL)return null;const lo=$u=>{const Ru=Au.tool_args?.[$u];return typeof Ru=="string"?Ru:""};return{title:lo("title"),content:lo("content"),space:lo("space")}}const APP_RULES_WORDS={title:"Rules and approvals",byDefault:"With no rule of its own: reading is done, anything else waits for you.",none:"It has no rule of its own.",waiting:"Waiting for you",nothingWaiting:"Nothing is waiting for your yes.",signedOut:"Its approvals reach you here once you are signed in to Datalayer.",offline:"Approvals are not connected yet: what you approve or reject is not sent until they are.",approve:"Approve",reject:"Reject"};function ruleInWords(Au){const lo=BEHAVIOUR_WORDS[Au.behaviour];return{action:Au.action,covers:Au.appliesTo.map(coverOf).join(", "),says:lo.says,means:lo.means}}const ruleOfApproval=Au=>{const lo=Au.tool_args?._rule??Au.tool_args?._check;return typeof lo=="string"?lo:""};function approvalsOfApp(Au,lo){return Au.filter($u=>$u.agent_id===lo||$u.tool_args?._app===lo)}const PENDING={status:"pending"};function DraftShown({draft:Au}){return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-draft",mt:1,children:[jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,fontSize:0,color:"fg.muted"},children:SAVE_WORDS.where(Au.space)}),jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,fontWeight:"semibold"},children:Au.title}),jsxRuntimeExports.jsx(Box,{as:"pre",m:0,mt:1,p:2,maxHeight:240,overflow:"auto",whiteSpace:"pre-wrap",fontFamily:"inherit",fontSize:0,bg:"canvas.subtle",borderRadius:2,children:Au.content})]})}function Approvals({app:Au}){const lo=useToolApprovalsQuery(PENDING),$u=useApproveToolRequest(),Ru=useRejectToolRequest(),Iu=reactExports.useMemo(()=>approvalsOfApp(lo.data?.approvals??[],Au.id),[lo.data,Au.id]);return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-approvals",children:[jsxRuntimeExports.jsx(Heading$2,{as:"h4",sx:{fontSize:1,mt:3,mb:1},children:APP_RULES_WORDS.waiting}),$u.connectionState!=="connected"?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",m:0,mb:1},children:APP_RULES_WORDS.offline}):null,Iu.length===0?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_RULES_WORDS.nothingWaiting}):jsxRuntimeExports.jsx(Box,{as:"ul",listStyle:"none",p:0,m:0,children:Iu.map(Pu=>{const Ou=draftOfApproval(Pu);return jsxRuntimeExports.jsxs(Box,{as:"li",py:2,borderTop:"1px solid",borderColor:"border.muted",fontSize:1,children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold"},children:Pu.tool_name}),ruleOfApproval(Pu)?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,color:"fg.muted",fontSize:0},children:ruleOfApproval(Pu)}):null,Ou?jsxRuntimeExports.jsx(DraftShown,{draft:Ou}):null,jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,mt:1,children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"primary",disabled:$u.isPending,onClick:()=>$u.mutate({id:Pu.id}),children:Ou?SAVE_WORDS.approve:APP_RULES_WORDS.approve}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:Ru.isPending,onClick:()=>Ru.mutate({id:Pu.id}),children:Ou?SAVE_WORDS.decline:APP_RULES_WORDS.reject})]})]},Pu.id)})})]})}function AppRulesCard({app:Au}){const lo=!!useIAMStore($u=>$u.token);return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-rules",mb:4,children:[jsxRuntimeExports.jsx(Heading$2,{as:"h3",sx:{fontSize:2,mb:2},children:APP_RULES_WORDS.title}),Au.rules.length===0?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_RULES_WORDS.none}):jsxRuntimeExports.jsx(Box,{as:"ul",listStyle:"none",p:0,m:0,children:Au.rules.map(ruleInWords).map(($u,Ru)=>jsxRuntimeExports.jsxs(Box,{as:"li",py:1,fontSize:1,children:[jsxRuntimeExports.jsx(Text$3,{children:$u.action})," ",jsxRuntimeExports.jsx(Label,{title:$u.means,children:$u.says}),jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,color:"fg.muted",fontSize:0},children:$u.covers})]},Ru))}),jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",mt:1,mb:0},children:APP_RULES_WORDS.byDefault}),lo?jsxRuntimeExports.jsx(Approvals,{app:Au}):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",mt:3,mb:0},children:APP_RULES_WORDS.signedOut})]})}const APP_RULES_PLUGIN_NAME="@datalayer/loop-plugin-app-rules";function defineAppRulesPlugin(Au){function lo(){return jsxRuntimeExports.jsx(AppRulesCard,{app:Au})}return{name:`${APP_RULES_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: rules and approvals`,description:`When ${Au.name} acts alone, when it asks, and what waits for your yes.`,octicon:"shield-check",build:()=>({components:[{id:"app-rules",slot:LoopSlots.sidebar,order:10,Component:lo,rail:{label:"Rules",icon:ShieldCheckIcon}}]})}}const COMMAND_INPUT="{input}";function commandPrompt(Au,lo=""){const $u=lo.trim();return Au.prompt.includes(COMMAND_INPUT)?Au.prompt.split(COMMAND_INPUT).join($u).trim():$u?`${Au.prompt}
@@ -4050,4 +4050,4 @@ iframe.datalayer-app-frame {
4050
4050
  `;return Au?`${lo}
4051
4051
  ${scopeThemeCss(Au,[`[${THEME_SCOPE_ATTRIBUTE}]`])}`:lo}const THREAD_WORDS={opening:"Opening your conversation…",notOpened:Au=>`Your conversation could not be opened, so this is a new one: ${Au}`};function messagesOfThread(Au){if(!Array.isArray(Au))return[];const lo=[];for(const $u of Au){if(!$u||typeof $u!="object")continue;const{id:Ru,role:Iu,content:Pu,activityType:Ou}=$u;if(Iu==="activity"&&Ou===REACTOR_UI_NAME)throw new Error(`Activity ${String(Ru)}: what a message showed comes on the ui socket (REACTOR_UI RU-W)`);(Iu==="user"||Iu==="assistant")&&typeof Ru=="string"&&typeof Pu=="string"&&Pu.trim()&&lo.push({id:Ru,role:Iu,content:Iu==="user"?askedOf(Pu):Pu,createdAt:new Date})}return lo}function snapshotOfStream(Au){let lo;for(const $u of eventsOfStream(Au))$u.type==="MESSAGES_SNAPSHOT"&&Array.isArray($u.messages)&&(lo=$u.messages);return lo}async function detailOf(Au){try{const lo=await Au.json();if(typeof lo.detail=="string"&&lo.detail)return lo.detail}catch{}return`${Au.status}`}async function openThread({agentBaseUrl:Au,agentId:lo,uid:$u,token:Ru,fetcher:Iu=fetch}){const Pu=`${Au.replace(/\/+$/,"")}/api/v1/apps/sessions/${encodeURIComponent($u)}`,Ou=Ru?{Authorization:`Bearer ${Ru}`}:{},Mu=await Iu(`${Pu}/messages`,{headers:Ou});if(Mu.ok){const Bu=await Mu.json();return messagesOfThread(Bu.messages)}if(Mu.status!==404)throw new Error(await detailOf(Mu));const Du=await Iu(`${Pu}/resume`,{method:"POST",headers:{"Content-Type":"application/json",...Ou},body:JSON.stringify({agent:lo})});if(!Du.ok)throw new Error(await detailOf(Du));const Lu=snapshotOfStream(await Du.text());if(!Lu)throw new Error(`The runtime said nothing of session ${$u}.`);return messagesOfThread(Lu)}const EMBED_SESSION_KEY_PREFIX="datalayer-app:session";function visitOfToken(Au){const lo=Au?.split(".")[1];if(lo)try{const $u=lo.replace(/-/g,"+").replace(/_/g,"/"),Ru=$u+"=".repeat((4-$u.length%4)%4),Iu=JSON.parse(atob(Ru));return typeof Iu.visit=="string"&&Iu.visit?Iu.visit:void 0}catch{return}}function embedSessionKey(Au,lo){return`${EMBED_SESSION_KEY_PREFIX}:${Au}:${lo}`}const IN_MEMORY=new Map;function hostStorage(){try{return typeof window<"u"?window.localStorage:void 0}catch{return}}function sessionKeeper({persist:Au,storage:lo=hostStorage}){return{read:$u=>{if(Au)try{const Ru=lo()?.getItem($u);if(Ru)return Ru}catch{}return IN_MEMORY.get($u)},keep:($u,Ru)=>{if(IN_MEMORY.set($u,Ru),Au)try{lo()?.setItem($u,Ru)}catch{}},forget:$u=>{IN_MEMORY.delete($u);try{lo()?.removeItem($u)}catch{}}}}async function reattachSession({serverUrl:Au,uid:lo,token:$u,fetcher:Ru=fetch}){try{const Iu=await Ru(`${Au.replace(/\/+$/,"")}/api/v1/apps/sessions/${encodeURIComponent(lo)}/messages`,{headers:{Authorization:`Bearer ${$u}`}});if(!Iu.ok)return{kind:"gone",uid:lo};const Pu=await Iu.json();return{kind:"resumed",uid:lo,messages:messagesOfThread(Pu.messages)}}catch{return{kind:"gone",uid:lo}}}const WINDOW_NOT_YET='The application takes a window message once its conversation has started, on its own server (the "server" attribute).';async function postWindowMessage({serverUrl:Au,uid:lo,token:$u,data:Ru,fetcher:Iu=fetch}){const Pu=await Iu(`${Au.replace(/\/+$/,"")}/api/v1/apps/sessions/${encodeURIComponent(lo)}/window`,{method:"POST",headers:{"content-type":"application/json",...$u?{Authorization:`Bearer ${$u}`}:{}},body:JSON.stringify({data:Ru})});if(!Pu.ok){let Mu="";try{const Du=await Pu.json();Mu=typeof Du.detail=="string"?Du.detail:""}catch{}throw new Error(Mu||`The window message was refused (${Pu.status}).`)}const Ou=windowTurnErrorOf(await Pu.text());if(Ou)throw new Error(Ou)}const sessionGoneSentence=Au=>`Your earlier conversation with ${Au} has ended, so this is a new one.`;function useEmbedSession({app:Au,serverUrl:lo,embedToken:$u,resume:Ru=!0}){const Iu=lo&&$u?visitOfToken($u):void 0,Pu=Iu?embedSessionKey(Au.id,Iu):void 0,Ou=reactExports.useMemo(()=>sessionKeeper({persist:Ru}),[Ru]),[Mu,Du]=reactExports.useState();return reactExports.useEffect(()=>{if(!Pu||!lo||!$u)return;let Lu=!1;const Bu=zu=>{Ou.keep(Pu,zu),Du(Uu=>Uu?.said?{...Uu,said:void 0}:Uu)},ju=zu=>Du({token:$u,thread:{id:generateMessageId(),messages:[],onStarted:Bu},...zu?{said:zu}:{}}),Fu=Ou.read(Pu);if(!Fu){ju();return}return reattachSession({serverUrl:lo,uid:Fu,token:$u}).then(zu=>{if(!Lu){if(zu.kind==="resumed"){Du({token:$u,thread:{id:Fu,messages:zu.messages,onStarted:Bu}});return}Ou.forget(Pu),ju(sessionGoneSentence(Au.name))}}),()=>{Lu=!0}},[Pu,lo,$u,Ou]),Pu?!Mu||Mu.token!==$u?{ready:!1}:{ready:!0,thread:Mu.thread,...Mu.said?{said:Mu.said}:{}}:{ready:!0}}function useWindowPort({serverUrl:Au,embedToken:lo,session:$u,host:Ru}){const Iu=reactExports.useRef(Ru);Iu.current=Ru;const Pu=$u.thread,Ou=reactExports.useRef(Pu?.messages.length?Pu.id:void 0),Mu=reactExports.useMemo(()=>({id:generateMessageId(),messages:[]}),[]),Du=Pu??(Au&&$u.ready?Mu:void 0),Lu=reactExports.useMemo(()=>Du&&{...Du,onStarted:Bu=>{Ou.current=Bu,Du.onStarted?.(Bu)}},[Du]);return reactExports.useEffect(()=>{const Bu=Ru?.onWindowPort;if(!(!Au||!Bu))return Bu(async ju=>{if(!Ou.current)throw new Error(WINDOW_NOT_YET);await postWindowMessage({serverUrl:Au,uid:Ou.current,...lo?{token:lo}:{},data:ju})}),()=>Bu(null)},[Au,lo,Ru]),Lu?{...$u,thread:Lu}:$u}function SessionSaid({said:Au}){return Au?jsxRuntimeExports.jsx(Text$3,{as:"p",role:"status",sx:{px:3,py:2,m:0,fontSize:1},children:Au}):null}const NO_HOST_PLUGINS=[];function useHostBridge(Au,lo){const $u=reactExports.useRef(lo);$u.current=lo;const Ru=Au.deployment.embedded?.host,Iu=JSON.stringify([Ru??null,Au.rules,Au.connections]),Pu=reactExports.useMemo(()=>hostPlugin(Au,()=>$u.current??{}),[Au.id,Iu]),Ou=Ru?.user==="signed",Mu=reactExports.useMemo(()=>{const Uu=hostUserRunProps(Au,()=>$u.current??{});return Uu?{name:`loop-host-user-${Au.id}`,displayName:`${Au.name}: who its user is`,description:`The token naming its user that the host's server signed, sent with every run of ${Au.name}.`,octicon:"person",emoji:"👤",contributes:[contribution(LoopRunProps,Uu,{id:"host-user"})]}:void 0},[Au.id,Ou]),Du=reactExports.useMemo(()=>Pu?[Pu,...Mu?[Mu]:[]]:NO_HOST_PLUGINS,[Pu,Mu]);reactExports.useEffect(()=>onLoopWindowMessage(Uu=>$u.current?.onEvent?.({type:"window-message",detail:{data:Uu}})),[]);const Lu=reactExports.useRef({answering:!1}),Bu=reactExports.useRef("idle"),ju=reactExports.useRef(""),Fu=reactExports.useCallback(Uu=>{Lu.current=Uu},[]),zu=reactExports.useCallback(Uu=>{const Hu=Bu.current;Bu.current=Uu;const Vu=Uu==="idle"||Uu==="waiting",Gu=Lu.current.saying;Vu&&Hu!=="idle"&&Hu!=="waiting"&&Lu.current.answering&&Gu&&Gu.id!==ju.current&&(ju.current=Gu.id,$u.current?.onEvent?.({type:"message",detail:{id:Gu.id,text:Gu.markdown||Gu.text}}))},[]);return{plugins:Du,onPresence:zu,onSaying:Fu}}const NO_PLUGINS=[];function embedAssistantCharacter(Au,lo=NO_PLUGINS){return assistantCharacterFor(assistantCharactersFrom([AssistantCharactersPlugin,...lo]),{app:Au.interface.assistant})}const signedOutSentence=Au=>`${Au.name} runs on Datalayer, which needs you signed in. An application embedded for visitors who are not needs its embed token (LOOP D-14), or an agent-runtimes server of the host's own (the "server" attribute).`;function Face({emoji:Au}){return jsxRuntimeExports.jsx(FluentEmoji,{emoji:Au,size:20,label:""})}function AppFloating({app:Au,view:lo,colorMode:$u,themeVariant:Ru,themeOverrides:Iu,character:Pu,serverUrl:Ou,instance:Mu,embedToken:Du,renderer:Lu,host:Bu,session:ju,language:Fu}){const zu=useChatWords(),[Uu,Hu]=reactExports.useState("idle"),[Vu,Gu]=reactExports.useState({answering:!1}),Wu=useHostBridge(Au,Bu),Ku=reactExports.useCallback(td=>{Hu(td),Wu.onPresence(td)},[Wu.onPresence]),Ju=reactExports.useCallback(td=>{Gu(td),Wu.onSaying(td)},[Wu.onSaying]),Yu=Au.interface.welcome||Au.description,Xu=useIAMStore(td=>td.token),ed=!Ou&&!Xu&&!Lu?.datalayerVisitors;return jsxRuntimeExports.jsx(ChatFloating,{defaultViewMode:lo,...Pu?{assistantCharacter:Pu}:{},...Au.interface.balloon?{balloonDisplay:Au.interface.balloon}:{},title:Au.name,description:Yu,brandIcon:jsxRuntimeExports.jsx(Face,{emoji:Au.emoji}),buttonIcon:jsxRuntimeExports.jsx(Face,{emoji:Au.emoji}),buttonTooltip:zu.talkTo(Au.name),colorMode:$u,useStore:!1,conversation:{body:ed?jsxRuntimeExports.jsx(Text$3,{as:"p",role:"status",sx:{p:3,m:0,fontSize:1},children:signedOutSentence(Au)}):ju&&!ju.ready?null:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(SessionSaid,{said:ju?.said}),jsxRuntimeExports.jsx(AppRenderer,{app:Au,target:Ou?"local":"datalayer",...Ou?{serverUrl:Ou}:{},...Ou&&Du?{embedToken:Du}:{},instance:Mu,themeOverrides:Iu,colorMode:$u,...Ru?{themeVariant:Ru}:{},hideChatHeader:!0,autoFocusPrompt:!1,onPresence:Ku,onSaying:Ju,plugins:Wu.plugins,...ju?.thread?{thread:ju.thread}:{},...Fu?{language:Fu}:{},...Lu})]}),presence:Uu,saying:Vu.saying,answering:Vu.answering}})}function OwnPortalRoot(){const Au=reactExports.useRef(null);return reactExports.useLayoutEffect(()=>{Au.current&&registerPortalRoot(Au.current)},[]),jsxRuntimeExports.jsx("div",{ref:Au,className:"datalayer-app-portal"})}function useSystemMode(){const Au=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(prefers-color-scheme: dark)"):null,[lo,$u]=reactExports.useState(!!Au?.matches);return reactExports.useEffect(()=>{if(!Au)return;const Ru=()=>$u(Au.matches);return Au.addEventListener?.("change",Ru),()=>Au.removeEventListener?.("change",Ru)},[Au]),lo?"dark":"light"}function EmbedThemed({accent:Au,colorMode:lo,font:$u,variant:Ru,children:Iu,style:Pu}){const Ou=reactExports.useMemo(()=>embedThemeStyles({accent:Au,font:$u,variant:Ru}),[Au,$u,Ru]);return jsxRuntimeExports.jsx("div",{"data-color-mode":lo,style:{display:"contents"},children:jsxRuntimeExports.jsx(DatalayerThemeProvider,{colorMode:lo,theme:getThemeConfig(Ru).primerTheme,themeStyles:Ou,baseStyles:Pu,children:Iu})})}function AppEmbed({app:Au,mode:lo,accent:$u,colorMode:Ru,font:Iu,language:Pu,serverUrl:Ou,instance:Mu,embedToken:Du,visitors:Lu,speech:Bu,height:ju=640,ownPortal:Fu=!1,plugins:zu=NO_PLUGINS,host:Uu,resume:Hu=!0}){const Vu=lo??Au.deployment.embedded?.mode??"inline",Gu=useHostBridge(Au,Vu==="inline"?Uu:void 0),Wu=reactExports.useMemo(()=>Lu||Bu?{...Lu?{datalayerVisitors:Lu}:{},...Bu?{speech:Bu}:{}}:void 0,[Lu,Bu]),Ku=useEmbedSession({app:Au,serverUrl:Ou,embedToken:Du,resume:Hu}),Ju=useWindowPort({serverUrl:Ou,embedToken:Du,session:Ku,host:Uu}),Yu=useSystemMode(),Xu=Au.interface.theme?.variant??"loop",ed=Ru??Au.interface.theme?.mode??"auto",td=ed==="auto"?Yu:ed,nd=floatingViewOf(Vu),od=$u??Au.interface.accent,sd=reactExports.useMemo(()=>embedThemeOverrides({accent:od,font:Iu,variant:Xu}),[od,Iu,Xu]),ad=Au.interface.assistant,pd=reactExports.useMemo(()=>nd==="assistant"?embedAssistantCharacter(Au,zu):void 0,[nd,ad,zu]);if(pd&&"problem"in pd)return jsxRuntimeExports.jsx("p",{role:"status",className:"datalayer-app-said",children:pd.problem});const gd=pd?.character;return jsxRuntimeExports.jsx(ChatLanguage,{language:Pu,children:jsxRuntimeExports.jsxs(EmbedThemed,{accent:od,colorMode:td,font:Iu,variant:Xu,style:nd?{backgroundColor:"transparent"}:{height:ju,display:"flex",flexDirection:"column"},children:[Fu?jsxRuntimeExports.jsx(OwnPortalRoot,{}):null,nd?jsxRuntimeExports.jsx(AppFloating,{app:Au,view:nd,serverUrl:Ou,instance:Mu,embedToken:Du,colorMode:td,themeVariant:Xu,themeOverrides:sd,character:gd,host:Uu,session:Ju,...Wu?{renderer:Wu}:{},...Pu?{language:Pu}:{}}):Ju.ready?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(SessionSaid,{said:Ju.said}),jsxRuntimeExports.jsx(AppRenderer,{app:Au,target:Ou?"local":"datalayer",...Ou?{serverUrl:Ou}:{},...Ou&&Du?{embedToken:Du}:{},...Wu??{},instance:Mu,themeOverrides:sd,colorMode:td,themeVariant:Xu,plugins:Gu.plugins,onPresence:Gu.onPresence,onSaying:Gu.onSaying,...Ju.thread?{thread:Ju.thread}:{},...Pu?{language:Pu}:{}})]}):null]})})}const VISITORS_PATH="/api/runtime-visitors",VISITOR_EXAMPLES=["web-research","customer-interview"],AT_PREFIX="at:",DEFAULT_API="https://prod1.datalayer.run",isAppUid=Au=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(Au),SLUG=/^[a-z0-9][a-z0-9-]{0,62}$/;function visitorsAt(Au,lo,$u){const Ru=Au.replace(/\/+$/,"");return{url:$u?$u.replace(/\/+$/,""):`${Ru}${VISITORS_PATH}`,app:lo,inferenceUrl:Ru}}const TOKEN_HINT='Embedded for a visitor it refuses, it takes its embed token (the "token" attribute).',notKeptSentence=Au=>`datalayer-app: "${Au}" is an example Datalayer does not keep ready for visitors (${VISITOR_EXAMPLES.join(", ")} are); embed it at its address once it is deployed. ${TOKEN_HINT}`,refusedSentence=Au=>`datalayer-app: ${Au.trim().replace(/\.?\s*Sign in to use it\.?$/,".")} ${TOKEN_HINT}`;async function readVisitorApp({api:Au=DEFAULT_API,app:lo,fetcher:$u=fetch,catalogue:Ru=getApp}){const Iu=lo.trim();if(isAppUid(Iu))return{kind:"decision",app:Iu};const Pu=Ru(Iu);if(Pu)return Pu.kind==="decision"?{kind:"decision",app:Iu}:VISITOR_EXAMPLES.includes(Pu.id)?{kind:"visitors",app:runnable({app:Pu,problems:[]}),visitors:visitorsAt(Au,Pu.id)}:{kind:"said",text:notKeptSentence(Iu)};if(!SLUG.test(Iu))return{kind:"said",text:`datalayer-app: "${Iu}" is neither an application's id, an example's, nor an address.`};let Ou;try{Ou=await $u(`${Au.replace(/\/+$/,"")}/api/ai-agents/v1/apps/deployments/at/${encodeURIComponent(Iu)}`)}catch(zu){return{kind:"said",text:`datalayer-app: Datalayer could not be reached to read "${Iu}" (${zu instanceof Error?zu.message:String(zu)}).`}}const Mu=await Ou.json().catch(()=>({}));if(!Ou.ok||Mu.success===!1){const zu=String(Mu.detail??Mu.message??`No application is at "${Iu}".`);return{kind:"said",text:refusedSentence(zu)}}const Du=Mu.session??{};if(!Du.opens)return{kind:"said",text:refusedSentence(String(Du.reason||`"${Iu}" is not run without an account.`))};const Lu=Mu.deployment??{},Bu=parseAppspec(Mu.spec);if(Bu.app.kind==="decision")return{kind:"decision",app:Iu};const ju=typeof Lu.app_name=="string"&&Lu.app_name?Lu.app_name:Bu.app.name,Fu=signedOutRuntime(Mu);return"said"in Fu?{kind:"said",text:refusedSentence(Fu.said)}:{kind:"visitors",app:runnable({app:{...Bu.app,name:ju},problems:Bu.problems}),visitors:visitorsAt(Au,`${AT_PREFIX}${Iu}`,Fu.url)}}function signedOutRuntime(Au){if(typeof Au.runs_code!="boolean")return{said:"Datalayer did not say whether it runs code of its own, so it is not run."};if(!Au.runs_code)return{};const lo=Au.kept??{},$u=typeof lo.url=="string"?lo.url.trim():"";return $u?{url:$u}:{said:"It runs its own code on a runtime kept for it, and none is running now."}}const EMBED_MESSAGES={size:"datalayer-app:size",decision:"datalayer-app:decision",token:"datalayer-app:token",tokenExpired:"datalayer-app:token-expired"};function appspecOfText(Au){const lo=Au.replace(/\t/g," ").split(`
4052
4052
  `),$u=Math.min(...lo.filter(Pu=>Pu.trim()).map(Pu=>Pu.length-Pu.trimStart().length)),Ru=lo.map(Pu=>Pu.slice(Number.isFinite($u)?$u:0)).join(`
4053
- `).trim();if(!Ru)throw new EmbedAttributeError("datalayer-app: the Appspec is empty.");let Iu;if(Ru.startsWith("{")){let Pu;try{Pu=JSON.parse(Ru)}catch(Ou){throw new EmbedAttributeError(`datalayer-app: the Appspec is not JSON (${Ou.message}).`)}Iu=parseAppspec(Pu)}else Iu=readAppspecYaml(Ru);return runnable(Iu)}function frameSrcOf(Au,lo,$u=""){return`${Au.replace(/\/+$/,"")}/public/apps/${encodeURIComponent(lo)}/run?embed=1${$u?`#token=${encodeURIComponent($u)}`:""}`}function frameInLanguage(Au,lo){if(!lo)return Au;const $u=Au.indexOf("#"),[Ru,Iu]=$u<0?[Au,""]:[Au.slice(0,$u),Au.slice($u)];return`${Ru}${Ru.includes("?")?"&":"?"}language=${encodeURIComponent(lo)}${Iu}`}async function readEmbeddedApp({api:Au,origin:lo,app:$u,token:Ru,fetcher:Iu=fetch}){const Pu=await Iu(`${Au.replace(/\/+$/,"")}/api/spacer/v1/apps/${encodeURIComponent($u)}/embedded`,{headers:{Authorization:`Bearer ${Ru}`}});if(Pu.status===401)return{kind:"said",text:"datalayer-app: the embed token expired or is not for this application.",expired:!0};if(!Pu.ok)return{kind:"said",text:`datalayer-app: the application could not be read (${Pu.status}).`};const Ou=await Pu.json();let Mu;try{Mu=JSON.parse(String(Ou.app?.model_s??"{}"))}catch{Mu={}}if(!Mu.spec)return{kind:"frame",src:frameSrcOf(lo,$u,Ru)};const Du=runnable(parseAppspec(Mu.spec));return Du.kind==="decision"?{kind:"frame",src:frameSrcOf(lo,$u,Ru)}:{kind:"spec",app:Du}}function currentScriptUrl(){try{const Au=document.currentScript;return Au?.src?new URL(Au.src,location.href).href:""}catch{return""}}function defineDatalayerAppElement(Au={}){if(typeof window>"u"||!("customElements"in window))return;const lo=Au.tag??EMBED_TAG,$u=customElements.get(lo);if($u)return $u;const Ru=Au.scriptUrl??currentScriptUrl(),Iu=Ru?new URL(Ru).origin:"",Pu=Ru?Ru.replace(/\.js(\?.*)?$/,".css"):"";class Ou extends HTMLElement{static get observedAttributes(){return EMBED_OBSERVED_ATTRIBUTES}root=null;frame=null;source=null;loading=0;passed={};offered={};windowPort=null;host={context:()=>this.passed,userToken:()=>this.getAttribute("user-token")||void 0,functions:this.offered,onWindowPort:Du=>{this.windowPort=Du},onEvent:Du=>this.dispatchEvent(new CustomEvent(Du.type,{detail:Du.detail,bubbles:!0,composed:!0}))};get context(){return this.passed}set context(Du){this.passed={...Du??{}}}postWindowMessage(Du){const Lu=this.windowPort;return Lu?Lu(Du):Promise.reject(new Error(`datalayer-app: ${WINDOW_NOT_YET}`))}get functions(){return this.offered}set functions(Du){for(const Lu of Object.keys(this.offered))delete this.offered[Lu];Object.assign(this.offered,Du??{})}constructor(){super(),this.attachShadow({mode:"open"}),this.onMessage=this.onMessage.bind(this),adoptPropertiesSetEarly(this)}get token(){return this.getAttribute("token")??""}set token(Du){Du?this.setAttribute("token",String(Du)):this.removeAttribute("token")}get userToken(){return this.getAttribute("user-token")??""}set userToken(Du){Du?this.setAttribute("user-token",String(Du)):this.removeAttribute("user-token")}connectedCallback(){window.addEventListener("message",this.onMessage),this.load()}disconnectedCallback(){window.removeEventListener("message",this.onMessage),this.unmount()}attributeChangedCallback(Du,Lu,Bu){if(!(!this.isConnected||Lu===Bu)&&Du!=="user-token"){if(Du==="token"&&this.frame?.contentWindow&&Bu){this.frame.contentWindow.postMessage({type:EMBED_MESSAGES.token,token:Bu},this.origin());return}if(["mode","accent","theme","font","height","resume","language"].includes(Du)){this.draw();return}this.load()}}origin(){return(this.getAttribute("origin")||Iu||location.origin).replace(/\/+$/,"")}inputs(){const Du={};for(const ju of EMBED_OBSERVED_ATTRIBUTES)Du[ju]=this.getAttribute(ju);const Lu=getComputedStyle(this),Bu={};for(const[ju,Fu]of Object.entries(EMBED_HOST_VARIABLES)){const zu=Lu.getPropertyValue(Fu).trim();zu&&(Bu[ju]=zu.replace(/^["']|["']$/g,""))}return{attributes:Du,variables:Bu}}async read(){const Du=this.querySelector('script[type="application/yaml"], script[type="application/json"], script[type="text/yaml"]');if(Du?.textContent?.trim())return{kind:"spec",app:appspecOfText(Du.textContent)};const Lu=this.getAttribute("spec");if(Lu){const Fu=await fetch(new URL(Lu,location.href).href);return Fu.ok?{kind:"spec",app:appspecOfText(await Fu.text())}:{kind:"said",text:`datalayer-app: the Appspec at ${Lu} could not be read (${Fu.status}).`}}const Bu=this.getAttribute("app");if(!Bu)return{kind:"said",text:'datalayer-app: the "app" attribute names the application to show, or "spec" the address of its Appspec.'};const ju=this.token;if(!ju){const Fu=await readVisitorApp({api:this.api(),app:Bu});return Fu.kind==="decision"?{kind:"frame",src:frameSrcOf(this.origin(),Fu.app)}:Fu.kind==="said"?{kind:"said",text:Fu.text}:{kind:"spec",app:Fu.app,visitors:Fu.visitors}}return readEmbeddedApp({api:this.api(),origin:this.origin(),app:Bu,token:ju})}spoken=null;get speech(){const Du=coreStore.getState().configuration?.aiAgentsUrl??"";return this.spoken?.speechUrl!==Du&&(this.spoken={speechUrl:Du}),this.spoken}api(){return(this.getAttribute("api")||coreStore.getState().configuration?.spacerUrl||DEFAULT_API).replace(/\/+$/,"")}async load(){const Du=++this.loading;let Lu;try{Lu=await this.read()}catch(Bu){Lu={kind:"said",text:Bu instanceof Error?Bu.message:`datalayer-app: ${String(Bu)}`}}Du!==this.loading||!this.isConnected||(this.source=Lu,this.draw(),Lu.kind==="said"&&Lu.expired&&this.dispatchEvent(new CustomEvent("token-expired",{detail:{app:this.getAttribute("app")??""},bubbles:!0,composed:!0})))}unmount(){this.root?.unmount(),this.root=null,this.frame=null}skeleton(Du){const Lu=this.shadowRoot;if(this.unmount(),Lu.replaceChildren(),Pu){const ju=document.createElement("link");ju.rel="stylesheet",ju.href=Pu,Lu.appendChild(ju)}const Bu=document.createElement("style");return Bu.textContent=embedShadowCss(Du),Lu.appendChild(Bu),Lu}say(Du){this.setAttribute("data-embed-mode","inline");const Lu=this.skeleton(),Bu=document.createElement("p");Bu.className="datalayer-app-said",Bu.setAttribute("role","status"),Bu.textContent=Du,Lu.appendChild(Bu)}draw(){const Du=this.source;if(!Du)return;if(Du.kind==="said"){this.say(Du.text);return}if(Du.kind==="frame"){let Hu;try{Hu=languageOf(this.getAttribute("language"))}catch(Wu){this.say(Wu.message);return}this.setAttribute("data-embed-mode","inline");const Vu=this.skeleton(),Gu=document.createElement("iframe");Gu.className="datalayer-app-frame",Gu.src=frameInLanguage(Du.src,Hu),Gu.title="Datalayer app",Gu.style.height=`${inlineHeightOf(this.getAttribute("height"))}px`,Gu.setAttribute("allow","clipboard-write"),Vu.appendChild(Gu),this.frame=Gu;return}let Lu,Bu,ju;try{Lu=embedLookOf(this.inputs(),Du.app),Bu=resumeOf(this.getAttribute("resume")),ju=languageOf(this.getAttribute("language"))}catch(Hu){this.say(Hu.message);return}if(Lu.mode==="assistant"){const Hu=embedAssistantCharacter(Du.app);if("problem"in Hu){this.say(Hu.problem);return}}this.setAttribute("data-embed-mode",Lu.mode);const Fu=this.skeleton(getThemeConfig(Lu.variant).themeStyles.css),zu=document.createElement("div");zu.className="datalayer-app-root",Fu.appendChild(zu),this.root=clientExports.createRoot(zu);const Uu=this.getAttribute("server")||void 0;this.root.render(jsxRuntimeExports.jsx(me$3,{target:Fu,children:jsxRuntimeExports.jsx(AppEmbed,{app:Du.app,mode:Lu.mode,accent:Lu.accent,colorMode:Lu.colorMode,font:Lu.font,serverUrl:Uu,...Uu&&this.token?{embedToken:this.token}:{},...Du.visitors?{visitors:Du.visitors}:{},speech:this.speech,height:inlineHeightOf(this.getAttribute("height")),ownPortal:!0,host:this.host,resume:Bu,...ju?{language:ju}:{}})}))}onMessage(Du){if(!this.frame||Du.source!==this.frame.contentWindow||Du.origin!==this.origin())return;const Lu=Du.data??{};Lu.type===EMBED_MESSAGES.size&&typeof Lu.height=="number"&&Lu.height>0?this.frame.style.height=`${Math.ceil(Lu.height)}px`:Lu.type===EMBED_MESSAGES.decision?this.dispatchEvent(new CustomEvent("decision",{detail:Lu.record,bubbles:!0,composed:!0})):Lu.type===EMBED_MESSAGES.tokenExpired&&this.dispatchEvent(new CustomEvent("token-expired",{detail:{app:this.getAttribute("app")??""},bubbles:!0,composed:!0}))}}return customElements.define(lo,Ou),Ou}const SCRIPT_FILE="datalayer-app.js";defineDatalayerAppElement({scriptUrl:new URL(SCRIPT_FILE,import.meta.url).href});const mermaidVLURNSYL=Object.freeze(Object.defineProperty({__proto__:null,Mermaid:Ee$2},Symbol.toStringTag,{value:"Module"}));export{styleTags as $,A2uiSurfaceComposed as A,Box as B,CheckIcon as C,Dialog$1 as D,useContributions as E,LoopPromptPanel as F,InputPrompt as G,Heading$2 as H,IconButton as I,Signal as J,o$1 as K,Label as L,MessageProcessor as M,NO_SANDBOX_YET as N,LoopOpeningNotebook as O,PlayIcon as P,QueryClient as Q,LoopNotebookToolbarItem as R,SANDBOX_KIND_LABELS as S,Text$3 as T,LoopNotebookToolbar as U,LRLanguage as V,LanguageSupport as W,indentNodeProp as X,continuedIndent as Y,foldNodeProp as Z,__vitePreload as _,QueryClientProvider as a,AGENTS_PLUGIN_NAME as a$,tags as a0,ExternalTokenizer as a1,ifNotIn as a2,completeFromList as a3,LRParser as a4,syntaxTree as a5,delimitedIndent as a6,foldInside as a7,getDefaultExportFromCjs as a8,MimeModel as a9,DatalayerThemeProvider as aA,de$1 as aB,on$1 as aC,nl as aD,es as aE,H as aF,disposeServiceManager as aG,create$g as aH,setIfUndefined as aI,create$6 as aJ,fromBase64 as aK,onChange as aL,varStorage as aM,toBase64 as aN,offChange as aO,createUint8ArrayFromArrayBuffer as aP,map$3 as aQ,ContextTracker as aR,NodeWeakMap as aS,IterMode as aT,snippetCompletion as aU,Panel as aV,PromiseDelegate as aW,DEFAULT_SERVICE_URLS as aX,requestDatalayerAPI as aY,API_BASE_PATHS as aZ,useReactorPlatform as a_,standardRendererFactories as aa,purify$1 as ab,Token$2 as ac,Menu as ad,DisposableDelegate as ae,ArrayExt as af,Widget as ag,PanelLayout as ah,ITranslator as ai,createToolbarFactory as aj,nullTranslator as ak,ObservableList as al,Toolbar$1 as am,ReactWidget as an,some$1 as ao,useAgentsRuntimes as ap,xu as aq,useThemeStore as ar,useSystemColorMode as as,getThemeConfig as at,JupyterReactTheme$1 as au,l$1 as av,v$1 as aw,a$1 as ax,Kernel as ay,registerSandboxServiceManager as az,sandboxExecuteOverHttp as b,VDomModel as b$,DEFAULT_DATALAYER_AGENTSPEC as b0,useOptionalSandboxService as b1,IDLE_SANDBOX_TARGET_SIGNAL as b2,ensureVisitorAgent as b3,AGENTSPECS$1 as b4,useAgentRuntimes as b5,ActionList as b6,distExports as b7,ActionListContainerContext as b8,BoxWithFallback as b9,defineLanguageFacet as bA,Parser$2 as bB,NodeType as bC,NodeProp as bD,Tag as bE,NodeSet as bF,Tree as bG,countColumn as bH,Prec as bI,keymap as bJ,Language as bK,indentUnit as bL,foldService as bM,CompletionContext as bN,EditorState as bO,languageDataProp as bP,LanguageDescription as bQ,ParseContext as bR,Eu as bS,Ke$2 as bT,_c as bU,is as bV,Ys as bW,PencilIcon as bX,SingletonLayout as bY,FocusTracker as bZ,libExports$5 as b_,merge$5 as ba,defaultSxProp as bb,useId as bc,reactDomExports as bd,useIsomorphicLayoutEffect$2 as be,ChevronDownIcon as bf,classes$t as bg,SubItem as bh,Box$1 as bi,themeConfigs as bj,LoopDocumentToolbarItem as bk,LoopDocumentToolbar as bl,LoopOpeningDocument as bm,IDLE_SANDBOX_SNAPSHOT_SIGNAL as bn,definePlugin as bo,DOCUMENT_TOOLBAR_PLUGIN_NAME as bp,contribution as bq,KernelIndicator as br,NOTEBOOK_TOOLBAR_PLUGIN_NAME as bs,LocalTokenGroup as bt,flatIndent as bu,parseMixed as bv,bracketMatchingHandle as bw,EditorView as bx,EditorSelection as by,sublanguageProp as bz,ButtonComponent as c,ITableOfContentsRegistry as c$,TableOfContents as c0,JSONExt as c1,VDomRenderer as c2,LabIcon as c3,classes as c4,map$5 as c5,showErrorMessage as c6,AttachedProperty as c7,addIcon as c8,launcherIcon as c9,linkIcon as cA,Clipboard as cB,downloadIcon as cC,copyIcon as cD,setToolbar as cE,Notification as cF,CommandRegistry as cG,closeIcon as cH,cutIcon as cI,pasteIcon as cJ,newFolderIcon as cK,textEditorIcon as cL,markdownIcon as cM,refreshIcon as cN,editIcon as cO,fileIcon as cP,stopIcon as cQ,filterIcon as cR,DisposableSet as cS,clearNumbering as cT,getHeadingId as cU,addPrefix as cV,parseHeadings as cW,filterHeadings as cX,StackedLayout as cY,ABCWidgetFactory as cZ,DocumentWidget as c_,MainAreaWidget as ca,find$3 as cb,TranslatorConnector as cc,Gettext as cd,DEFAULT_LANGUAGE_CODE as ce,normalizeDomain as cf,ITranslatorConnector as cg,Dialog as ch,showDialog$1 as ci,SearchDocumentModel as cj,SearchDocumentView as ck,isResponsiveValue as cl,clsx as cm,commonjsRequire as cn,TextInput$1 as co,SearchIcon as cp,SyncIcon as cq,ToggleSwitch as cr,Flash as cs,ChevronRightIcon as ct,StyledSpinner as cu,ToolbarButton as cv,fileUploadIcon as cw,libExports$2 as cx,WidgetTracker as cy,folderIcon as cz,displayUrl as d,OutputPrompt as d$,markdownRendererFactory as d0,SkeletonBox as d1,getBrightPalette as d2,useColorPalette as d3,SkeletonText as d4,Tooltip as d5,ActionMenu as d6,buildIcon as d7,jupyterIcon as d8,SettingRegistry as d9,EditorExtensionRegistry as dA,ybinding as dB,IPositionModel as dC,historyIcon as dD,CommandToolbarButton as dE,caretLeftIcon as dF,caretRightIcon as dG,checkIcon as dH,COMPLETER_ACTIVE_CLASS as dI,Debouncer as dJ,SessionContextDialogs as dK,saveIcon as dL,addCommandToolbarButtonClass as dM,UseSignal as dN,CommandToolbarButtonComponent as dO,createStore$1 as dP,useStore$1 as dQ,runtimesStore as dR,DATALAYER_IAM_TOKEN_KEY as dS,DATALAYER_IAM_USER_KEY as dT,coreStore as dU,iamStore as dV,layoutStore as dW,useCoreStore as dX,useIAMStore as dY,useLayoutStore as dZ,useRuntimesStore as d_,moveUpIcon as da,moveDownIcon as db,Button$1 as dc,deleteIcon as dd,DOMUtils as de,lineFormIcon as df,deleteLine as dg,toggleBlockComment as dh,toggleComment as di,toggleTabFocusMode as dj,selectNextOccurrence as dk,foldable as dl,foldCode as dm,unfoldCode as dn,foldState as dp,foldEffect as dq,unfoldEffect as dr,foldAll as ds,unfoldAll as dt,IEditorServices as du,EditorLanguageRegistry as dv,parseMathIPython as dw,StreamLanguage as dx,pythonBuiltin as dy,EditorThemeRegistry as dz,Link$1 as e,CHAT_PLUGIN_NAME as e$,Stdin as e0,CodeCell as e1,useJupyterLabCssLoaded as e2,TelescopeIcon as e3,XIcon as e4,CounterLabel as e5,PauseIcon as e6,DownloadIcon as e7,SPAN_SOURCE_LABELS as e8,sourceOfSpan as e9,useAgentRuntimeMcpStatus as eA,useAgentRuntimeCodemodeStatus as eB,useAgentRuntimeContextSnapshot as eC,useAgentRuntimeFullContext as eD,useAgentRuntimeWsState as eE,useMutation as eF,useQuery as eG,ForwardRef$2 as eH,NoteIcon as eI,ServerIcon as eJ,CheckCircleIcon as eK,XCircleIcon as eL,BriefcaseIcon as eM,AgentTools as eN,useToast as eO,isInsideJupyterLab as eP,FormControl$1 as eQ,MailIcon as eR,Textarea as eS,$e$5 as eT,useAnonymousInferenceSession as eU,browserModelRequiresSignIn as eV,getAgentspecs as eW,useOptionalReactorPlatform as eX,FluentEmoji as eY,PRESENCE_LINES as eZ,useChatWords as e_,AGENT_SPAN_ATTRIBUTES as ea,describeAgentSpan as eb,SpecMark as ec,parse$4 as ed,UUID as ee,EN_US as ef,errorIcon as eg,Platform as eh,caretDownEmptyThinIcon as ei,StringExt as ej,SegmentedControl as ek,ListUnorderedIcon as el,GraphIcon as em,ClockIcon as en,DatabaseIcon as eo,FileIcon as ep,ToolsIcon as eq,CommentDiscussionIcon as er,AiModelIcon as es,InfoIcon as et,KeyIcon as eu,devtools as ev,subscribeWithSelector as ew,persist as ex,CheckCircleFillIcon as ey,AlertIcon as ez,CopyIcon as f,ChatBase as f$,INPUT_PROMPT_PLUGIN_NAME as f0,LoopChatSurface as f1,LoopChatComposer as f2,LoopChatHeader as f3,LoopChatLayout as f4,LoopChatTurn as f5,turnWritersOf as f6,LoopChatExtras as f7,computed$1 as f8,useGate as f9,LoopCommand as fA,subagentsFor as fB,useChatAvailability as fC,noRuntimeSaid as fD,useVoiceSettings as fE,settledVoice as fF,useSlotComponents as fG,LoopSlots as fH,onPromptFocusRequest as fI,useVisitorToken as fJ,voiceAskedAs as fK,generateMessageId as fL,openThread as fM,THREAD_WORDS as fN,agentInstructions as fO,useConfig as fP,useSkills as fQ,useSkillActions as fR,runtimeModelsUrl as fS,readServerCatalogue as fT,readServerDecisions as fU,offeredModels as fV,AI_MODEL_CATALOGUE as fW,isChatModel as fX,ReactorSlot as fY,ComposerVoice as fZ,ReactorLazy as f_,presenceState as fa,presenceToolOf as fb,newestIsAnswer as fc,latestSaying as fd,messageText as fe,LoopRunProps as ff,runForwardedProps as fg,dataUrlBase64 as fh,sandboxFileName as fi,writeFilesCode as fj,givenFilesSentence as fk,sendInstead as fl,onSurfaceRequest as fm,setEditorOptions as fn,seedEditorChoice as fo,canOpenView as fp,useWorkspaceFullScreen as fq,targetRunsAgentInPage as fr,useOptionalTeamSelection as fs,LoopAgentBlueprint as ft,resolveAgentspec as fu,LoopChatSuggestion as fv,agentIcon as fw,LoopFrontendTool as fx,BROWSER_CODE_TOOL as fy,agentServerOf as fz,createAllAgentRuntimesTools as g,CommandPalette$1 as g$,ScreenNormalIcon as g0,ScreenFullIcon as g1,SUGGESTION_CHIP_WIDTH as g2,Truncate as g3,useAnonymousSessionStore as g4,inPageAgentRefusal as g5,signal$2 as g6,LoopAgentGate as g7,agentRuntimeStore as g8,loopShapeVars as g9,requireMessages as gA,mockSocketExports as gB,ObservableMap as gC,CodeEditorWrapper as gD,CodeEditor as gE,IEditorMimeTypeService as gF,EditorSearchProvider as gG,CodeMirrorEditor as gH,getPrefix as gI,isMarkdown as gJ,findNext as gK,gotoLine as gL,consoleIcon as gM,undoIcon as gN,redoIcon as gO,selectAll as gP,Sanitizer as gQ,COMPLETER_ENABLED_CLASS as gR,MessageLoop as gS,COMPLETER_LINE_BEGINNING_CLASS as gT,Message as gU,ElementExt as gV,renderText as gW,Printing as gX,clientExports as gY,RenderedJavaScript as gZ,filterListIcon as g_,NONE_EDITOR as ga,MenuBar as gb,runIcon as gc,fastForwardIcon as gd,require_MapCache as ge,require_Symbol as gf,require_Uint8Array as gg,requireEq as gh,require_getAllKeys as gi,require_Stack as gj,require_getTag as gk,requireIsArray as gl,requireIsBuffer as gm,requireIsTypedArray as gn,requireIsObjectLike as go,getAnchoredPosition as gp,reactIsExports as gq,useTheme as gr,useOnEscapePress as gs,useOnOutsideClick as gt,useResizeObserver as gu,VisuallyHidden as gv,TriangleDownIcon as gw,qe$4 as gx,sx as gy,requireSerialize as gz,renderOcticon as h,strokeWidth$1 as h$,h$7 as h0,LabIconStyle as h1,copyrightIcon as h2,ToolbarButtonComponent as h3,bellIcon as h4,Button$3 as h5,paletteIcon as h6,Throttler as h7,Selector$1 as h8,jupyterFaviconIcon as h9,startSlotTemplate as hA,endSlotTemplate as hB,slotted as hC,elements as hD,FoundationElement as hE,isHTMLElement as hF,__decorate$1 as hG,attr as hH,observable as hI,applyMixins as hJ,StartEnd as hK,keyEnter as hL,keyArrowUp as hM,keyArrowDown as hN,keyArrowRight as hO,keyArrowLeft as hP,keyEnd as hQ,keyHome as hR,DOM as hS,getDisplayedNodes as hT,direction$1 as hU,neutralForegroundRest$1 as hV,neutralFillStealthRest$1 as hW,bodyFont$1 as hX,focusVisible as hY,accentFillFocus$1 as hZ,focusStrokeWidth$1 as h_,caretDownEmptyIcon as ha,addToolbarButtonClass as hb,NotebookActions as hc,offlineBoltIcon as hd,circleIcon as he,ObservableJSON as hf,ConflatableMessage as hg,jumpBackIcon as hh,jumpForwardIcon as hi,MarkdownCell as hj,Cell as hk,trustedIcon as hl,notTrustedIcon as hm,runCell as hn,InputPrompt$1 as ho,NotebookPanel as hp,setCellExecutor as hq,StaticNotebook as hr,notebookIcon as hs,NotebookSearchProvider as ht,duplicateIcon as hu,addAboveIcon as hv,addBelowIcon as hw,children$1 as hx,ref$1 as hy,html$6 as hz,SquareFillIcon as i,createCellModelFromSharedType as i$,controlCornerRadius$1 as i0,heightNumber$1 as i1,neutralFillStealthHover$1 as i2,neutralFillStealthActive$1 as i3,designUnit$1 as i4,typeRampBaseFontSize$1 as i5,typeRampBaseLineHeight$1 as i6,density$1 as i7,typeRampPlus1FontSize$1 as i8,disabledOpacity$1 as i9,circleEmptyIcon as iA,searchIcon as iB,SplitPanel as iC,TabBar as iD,jsonIcon as iE,spreadsheetIcon as iF,terminalIcon as iG,kernelIcon as iH,NotificationManager as iI,SessionContext as iJ,Spinner as iK,Styling as iL,SystemClipboard as iM,VisuallyHidden$1 as iN,StopIcon as iO,ViewPlugin as iP,createRelativePositionFromTypeIndex as iQ,createRelativePositionFromJSON as iR,tooltips as iS,Facet as iT,Annotation as iU,layer as iV,StateField as iW,showTooltip as iX,createAbsolutePositionFromRelativePosition as iY,RectangleMarker as iZ,YDocument as i_,disabledCursor as ia,baseHeightMultiplier$1 as ib,neutralFillRest$1 as ic,neutralFillHover$1 as id,neutralFillActive$1 as ie,accentForegroundRest$1 as ig,display as ih,css as ii,forcedColorsStylesheetBehavior as ij,SystemColors as ik,cssPartial as il,DesignToken as im,neutralFillStealthRecipe$1 as io,neutralFillRecipe$1 as ip,useEventListener as iq,useProperties as ir,provideJupyterDesignSystem$1 as is,ITableOfContentsTracker as it,tocIcon as iu,numberingIcon as iv,expandAllIcon as iw,collapseAllIcon as ix,ellipsesIcon as iy,caretDownIcon as iz,jsxRuntimeExports as j,activateHover as j$,createCell as j0,YMap as j1,RawCellModel as j2,MarkdownCellModel as j3,CodeCellModel as j4,MINOR_VERSION as j5,MAJOR_VERSION as j6,StateEffect as j7,Decoration as j8,WidgetType as j9,CheckboxOrRadioGroup$1 as jA,CheckboxGroupContext as jB,Checkbox as jC,RadioGroup$1 as jD,Radio as jE,SelectPanel as jF,Select$1 as jG,TextInputWithTokens as jH,object as jI,preprocess$1 as jJ,record$1 as jK,string$2 as jL,unknown$1 as jM,zodToToolParameters as jN,array as jO,_enum as jP,number$2 as jQ,boolean$1 as jR,validateWithZod as jS,useJupyterReactStoreFromProps as jT,OutputArea as jU,createStandaloneCell as jV,BoxPanel as jW,cellsStore as jX,RawCell as jY,useCellsStore as jZ,getPanel as j_,DEFAULT_VARIANT as ja,MarimoReactive as jb,NotebookCommandIds as jc,OutputAreaModel as jd,useJupyterReactStore as je,newUuid as jf,NotebookPanelProvider as jg,addNotebookCommands as jh,YArray as ji,YText as jj,newUlid as jk,k$2 as jl,loopColors as jm,sunColors as jn,ivoryColors as jo,sandColors as jp,earthColors as jq,matrixColors as jr,lovelyColors as js,spatialColors as jt,datalayerColors as ju,getColorPalette as jv,CheckboxOrRadioGroupValidation as jw,CheckboxOrRadioGroupLabel as jx,CheckboxOrRadioGroupCaption as jy,useRenderForcingRef as jz,TrashIcon as k,y$3 as k$,showPanel as k0,combineConfig as k1,RangeSetBuilder as k2,crelt as k3,hoverTooltip as k4,lineNumbers as k5,highlightActiveLineGutter as k6,highlightSpecialChars as k7,history as k8,foldGutter as k9,ccount as kA,zwitch as kB,html$4 as kC,htmlVoidElements as kD,C$1 as kE,Dt$4 as kF,u$2 as kG,dt$2 as kH,Go as kI,ns as kJ,mn$1 as kK,qi as kL,Pi as kM,isStream as kN,isExecuteResult as kO,isDisplayData as kP,isError$1 as kQ,Xo as kR,Ki as kS,Yi as kT,er as kU,T as kV,v$2 as kW,S$1 as kX,C as kY,m$2 as kZ,x$5 as k_,drawSelection as ka,dropCursor as kb,indentOnInput as kc,syntaxHighlighting as kd,bracketMatching as ke,closeBrackets as kf,autocompletion as kg,rectangularSelection as kh,crosshairCursor as ki,highlightActiveLine as kj,highlightSelectionMatches as kk,closeBracketsKeymap as kl,defaultKeymap as km,searchKeymap as kn,historyKeymap as ko,foldKeymap as kp,completionKeymap as kq,defaultHighlightStyle as kr,ArrowRightIcon as ks,useOutputsStore as kt,Compartment as ku,whitespace as kv,svg$2 as kw,find as kx,stringify$1 as ky,stringify as kz,libExports$3 as l,TextModelFactory as l$,p$4 as l0,ol as l1,He$2 as l2,pn$2 as l3,Kr as l4,ur as l5,ls as l6,cn$1 as l7,_n as l8,hn$2 as l9,useResponsiveValue as lA,ScrollableRegion as lB,viewportRanges as lC,JupyterLiteServer as lD,Router as lE,ContextMenu as lF,TabPanel as lG,DockPanel as lH,hpass as lI,AccordionPanel as lJ,AccordionLayout as lK,FormAssociated as lL,nullableNumberConverter as lM,ARIAGlobalStatesAndProperties as lN,neutralFillInputRest$1 as lO,neutralFillStrongRest$1 as lP,errorFillRest$1 as lQ,neutralFillInputHover$1 as lR,neutralFillStrongHover$1 as lS,errorFillHover$1 as lT,neutralFillStrongActive$1 as lU,errorFillActive$1 as lV,errorFillFocus$1 as lW,neutralStrokeRest$1 as lX,__decorate as lY,BoxLayout as lZ,VirtualDOM as l_,qc as la,Ie$2 as lb,cs as lc,dr as ld,Jl as le,fn$2 as lf,hn$1 as lg,pn$1 as lh,Wo as li,xt$2 as lj,Zs as lk,gc as ll,On as lm,na as ln,ea as lo,ia as lp,sa as lq,decodeNamedCharacterReference as lr,requireReact as ls,StyleModule as lt,jupyterHighlightStyle as lu,useFocusZone as lv,FocusKeys as lw,useSafeTimeout as lx,useSlots as ly,useProvidedRefOrCreate as lz,PlusIcon as m,KERNEL_STATE_LABELS as m$,pdfIcon as m0,pythonIcon as m1,juliaIcon as m2,rKernelIcon as m3,yamlIcon as m4,imageIcon as m5,audioIcon as m6,videoIcon as m7,writeVarUint as m8,encodeStateVector as m9,filter$3 as mA,caretUpIcon as mB,Poll as mC,each as mD,Application as mE,StackedPanel as mF,tabIcon as mG,Base64ModelFactory as mH,useTerminalStore as mI,requestAPI$1 as mJ,loadJupyterConfig as mK,createLiteServiceManager as mL,jupyterReactStore as mM,ANSWER_MARKER as mN,BuilderManagerLess as mO,ContentsManagerLess as mP,DEFAULT_API_KERNEL_PREFIX_URL as mQ,DEFAULT_JUPYTER_SERVER_TOKEN as mR,DEFAULT_JUPYTER_SERVER_URL as mS,DEFAULT_KERNEL_NAME as mT,DefaultExecutor as mU,EventsManagerLess as mV,ExecutionPhase as mW,HELPER_NAME as mX,JupyterLabCss as mY,KERNEL_HELPER_SOURCE as mZ,KERNEL_STATES as m_,writeVarUint8Array as ma,encodeStateAsUpdate as mb,readVarUint as mc,applyUpdate as md,readVarUint8Array as me,readVarString as mf,ObservableV2 as mg,Awareness as mh,toUint8Array$1 as mi,length as mj,encodeAwarenessUpdate as mk,removeAwarenessStates as ml,isNode as mm,getUnixTime as mn,createEncoder as mo,min as mp,pow as mq,createDecoder as mr,applyAwarenessUpdate as ms,UndoManager as mt,Doc$1 as mu,isCodeCellModel as mv,Drag as mw,MimeData as mx,useConsoleStore as my,folderFavoriteIcon as mz,CodeIcon as n,Fi as n$,KERNEL_STATE_VISUALS as n0,KernelExecutor as n1,KernelManagerLess as n2,KernelspecManagerLess as n3,NbConvertManagerLess as n4,OperationRunner as n5,ServiceManagerLess as n6,SessionManagerLess as n7,SettingManagerLess as n8,TerminalManagerLess as n9,loadJupyterLabCss as nA,notebookToolDefinitions as nB,notebookToolOperations as nC,notebookTools as nD,outputsAsString as nE,outputsStore as nF,readAllCellsOperation as nG,readAllCellsTool as nH,readCellOperation as nI,readCellTool as nJ,refreshJupyterLabPortalTheme as nK,renderKernelStateGlyph as nL,resetJupyterConfig as nM,runCellOperation as nN,runCellTool as nO,setJupyterServerToken as nP,setJupyterServerUrl as nQ,sleep as nR,syncJupyterLabPortalTheme as nS,terminalStore as nT,toKernelState as nU,updateCellOperation as nV,updateCellTool as nW,useJupyterReactColormode as nX,useKernelsStore as nY,ThemeProvider as nZ,Overlay$1 as n_,UserManagerLess as na,WorkspaceManagerLess as nb,cellSourceAsString as nc,consoleStore as nd,createLiteServer as ne,createServerSettings as nf,deleteCellsOperation as ng,deleteCellsTool as nh,disableKernelReconnect as ni,disposeKernelConnections as nj,ensureJupyterAuth as nk,ensureJupyterConfig as nl,executeCodeOperation as nm,executeCodeTool as nn,formatResponse as no,getCookie as np,getJupyterServerToken as nq,getJupyterServerUrl as nr,getKernelIndicatorMeta as ns,insertCellOperation as nt,insertCellTool as nu,isAnyCellRunning as nv,isReactiveVariant as nw,isServedByJupyterLab as nx,jupyterLabTheme as ny,kernelsStore as nz,notebookStore as o,kn$1 as o$,Zl as o0,bu as o1,Nu as o2,Wl as o3,Fr as o4,Li as o5,Vc as o6,Fo as o7,sn$1 as o8,vc as o9,Is as oA,Dl as oB,h$1 as oC,Sn$1 as oD,Nn$1 as oE,ce$1 as oF,Tu as oG,vu as oH,ae$1 as oI,xt$3 as oJ,St$3 as oK,Pc as oL,Lc as oM,Ic as oN,mt$3 as oO,rs as oP,an$1 as oQ,Je$2 as oR,Ft$1 as oS,Os as oT,Mt$1 as oU,gt as oV,Co as oW,Tn as oX,Dt as oY,So as oZ,vn as o_,tr as oa,Sn as ob,Zo as oc,Cu as od,Bs as oe,Me as of,yn as og,Se as oh,Cn as oi,fn as oj,qr as ok,Ia as ol,zs as om,gn$2 as on,or as oo,Jr as op,sn$2 as oq,ln$1 as or,rn$1 as os,nn$2 as ot,Vr as ou,nu as ov,du as ow,Va as ox,au as oy,La as oz,decode$4 as p,We as p$,xl as p0,oa as p1,Cn$1 as p2,et as p3,xn as p4,St as p5,Rt as p6,xt as p7,yn$1 as p8,It$1 as p9,Yt as pA,Ya as pB,Pe$2 as pC,Ja as pD,tu as pE,zl as pF,Fl as pG,Ma as pH,ja as pI,Hl as pJ,Ba as pK,Bl as pL,Pr as pM,Pe as pN,uo as pO,mu as pP,iu as pQ,ku as pR,Mo as pS,Rl as pT,wu as pU,Fn as pV,lc as pW,$s as pX,he as pY,Fe as pZ,Ut$1 as p_,Tt as pa,l$2 as pb,a$2 as pc,d$2 as pd,s$2 as pe,Ue$2 as pf,dn$2 as pg,$e$2 as ph,un$1 as pi,Bi as pj,It as pk,en$2 as pl,_$1 as pm,te$2 as pn,le$2 as po,on$2 as pp,$t$3 as pq,mn$2 as pr,Xe$2 as ps,gr as pt,Ge$2 as pu,_r as pv,Ve$2 as pw,je$1 as px,Ye$1 as py,qe$2 as pz,formatTokenCount as q,En$1 as q$,Fs as q0,Al as q1,No as q2,bo as q3,as as q4,_t as q5,eu as q6,fc as q7,Re as q8,Kc as q9,z as qA,O$1 as qB,r$2 as qC,t$2 as qD,Es as qE,_s as qF,vt$2 as qG,n$2 as qH,b$1 as qI,nn$1 as qJ,r$1 as qK,g$1 as qL,Tt$2 as qM,ys as qN,e$1 as qO,vl as qP,u$1 as qQ,b$3 as qR,z$1 as qS,zi as qT,Ji as qU,ko as qV,To as qW,Ze$2 as qX,Qe$2 as qY,Mn$1 as qZ,wn$1 as q_,Wt$1 as qa,z$2 as qb,ac as qc,On$1 as qd,Ht$1 as qe,Le$2 as qf,zr as qg,Bt$1 as qh,Ll as qi,ui as qj,ec as qk,nc as ql,zt$1 as qm,Ir as qn,i$1 as qo,uu as qp,Aa as qq,Wa as qr,Ul as qs,ql as qt,dc as qu,be as qv,ke as qw,ft as qx,pi as qy,x$4 as qz,reactExports as r,RssIcon as r$,xo as r0,vi as r1,Ql as r2,ut$2 as r3,Gl as r4,ReactDOM as r5,M$2 as r6,PersonIcon as r7,Pt$1 as r8,s$1 as r9,BroadcastIcon as rA,BrowserIcon as rB,BugIcon as rC,CircleSlashIcon as rD,CodeReviewIcon as rE,CpuIcon as rF,CreditCardIcon as rG,DependabotIcon as rH,DeviceDesktopIcon as rI,DeviceMobileIcon as rJ,FoldIcon as rK,GearIcon as rL,GitBranchIcon as rM,GlobeIcon as rN,HeartIcon as rO,IssueOpenedIcon as rP,LightBulbIcon as rQ,LinkExternalIcon as rR,MegaphoneIcon as rS,MortarBoardIcon as rT,MuteIcon as rU,OrganizationIcon as rV,PackageIcon as rW,PaperclipIcon as rX,PeopleIcon as rY,PulseIcon as rZ,RocketIcon as r_,f$3 as ra,P$1 as rb,fe$1 as rc,PaperAirplaneIcon as rd,bn$2 as re,TableIcon as rf,q as rg,ChecklistIcon as rh,fn$1 as ri,GrabberIcon as rj,vo as rk,yo as rl,wo as rm,mo as rn,j$1 as ro,r$3 as rp,$2AODx$react as rq,jt$1 as rr,oe$1 as rs,ie$2 as rt,RowsIcon as ru,x$2 as rv,AlertFillIcon as rw,BeakerIcon as rx,BellIcon as ry,BookIcon as rz,sandboxIsLive as s,__rest as s$,ShareAndroidIcon as s0,ShieldCheckIcon as s1,ShieldIcon as s2,SidebarExpandIcon as s3,SkipIcon as s4,SlidersIcon as s5,SparkleFillIcon as s6,SquareCircleIcon as s7,SunIcon as s8,TagIcon as s9,require_Set as sA,requireKeysIn as sB,requireIsArrayLikeObject as sC,requireIsPlainObject$1 as sD,require_baseMerge as sE,require_createAssigner as sF,require_apply as sG,require_copyArray as sH,require_arrayEach as sI,requireCloneDeep as sJ,requireFastUri as sK,ForwardRef$1 as sL,ForwardRef as sM,memoize as sN,isPropValid as sO,tabbable as sP,focusable as sQ,isTabbable as sR,getTabIndex as sS,isFocusable as sT,index_esm as sU,requirePropTypes as sV,s$5 as sW,__assign as sX,requireReactDom as sY,__extends as sZ,__awaiter as s_,TasklistIcon as sa,ThumbsdownIcon as sb,ThumbsupIcon as sc,UnmuteIcon as sd,UploadIcon as se,XCircleFillIcon as sf,ZapIcon as sg,requireFastDeepEqual as sh,getAugmentedNamespace as si,requireParseSrcset as sj,requirePostcss as sk,requireIsPlainObject as sl,requireEscapeStringRegexp as sm,requireIsArguments as sn,require_arrayPush as so,require_baseGetTag as sp,requireIsObject as sq,requireKeys as sr,require_isIndex as ss,requireIsLength as st,requireIdentity as su,require_baseFor as sv,requireIsArrayLike as sw,require_baseUnary as sx,require_baseRest as sy,require_isIterateeCall as sz,timeLeft as t,__generator as t0,require$$0 as t1,requireObjectAssign as t2,ulid$1 as t3,AGENTS_VIEW as t4,CONTENTS_VIEW as t5,DATALAYER_VIEW as t6,JWT_DATALAYER_ISSUER as t7,JWT_REFRESH_TOKEN_COOKIE_NAME as t8,LIBRARY_VIEW as t9,katex$1 as tA,Lexical_prod as tB,LexicalUtils_prod as tC,NAVIGATION_VIEW_HOMES as ta,RESERVATION_WARNING_TIME_MS as tb,SESSION_COOKIES as tc,SESSION_LOCAL_STORAGE_KEYS as td,SESSION_OWNER_KEY as te,SETTINGS_VIEW as tf,TUTOR_VIEW as tg,claimSessionState as th,forgetSessionState as ti,getOtelConsumeUrl as tj,getStoredToken as tk,getStoredUser as tl,isRememberableRoute as tm,isShellNeutralRoute as tn,loadRefreshTokenFromCookie as to,navigationStore as tp,pageConfiguration as tq,profileStore as tr,registerSessionState as ts,storeToken as tt,storeUser as tu,useNavigationStore as tv,useProfile as tw,useProfileStore as tx,viewForRoute as ty,__spreadArray as tz,useNotebookStore$1 as u,vM as v,useSandboxService as w,useSignalValue$1 as x,datalayerCatalog as y,ChatBaseHeader as z};
4053
+ `).trim();if(!Ru)throw new EmbedAttributeError("datalayer-app: the Appspec is empty.");let Iu;if(Ru.startsWith("{")){let Pu;try{Pu=JSON.parse(Ru)}catch(Ou){throw new EmbedAttributeError(`datalayer-app: the Appspec is not JSON (${Ou.message}).`)}Iu=parseAppspec(Pu)}else Iu=readAppspecYaml(Ru);return runnable(Iu)}function frameSrcOf(Au,lo,$u=""){return`${Au.replace(/\/+$/,"")}/public/apps/${encodeURIComponent(lo)}/run?embed=1${$u?`#token=${encodeURIComponent($u)}`:""}`}function frameInLanguage(Au,lo){if(!lo)return Au;const $u=Au.indexOf("#"),[Ru,Iu]=$u<0?[Au,""]:[Au.slice(0,$u),Au.slice($u)];return`${Ru}${Ru.includes("?")?"&":"?"}language=${encodeURIComponent(lo)}${Iu}`}async function readEmbeddedApp({api:Au,origin:lo,app:$u,token:Ru,fetcher:Iu=fetch}){const Pu=await Iu(`${Au.replace(/\/+$/,"")}/api/spacer/v1/apps/${encodeURIComponent($u)}/embedded`,{headers:{Authorization:`Bearer ${Ru}`}});if(Pu.status===401)return{kind:"said",text:"datalayer-app: the embed token expired or is not for this application.",expired:!0};if(!Pu.ok)return{kind:"said",text:`datalayer-app: the application could not be read (${Pu.status}).`};const Ou=await Pu.json();let Mu;try{Mu=JSON.parse(String(Ou.app?.model_s??"{}"))}catch{Mu={}}if(!Mu.spec)return{kind:"frame",src:frameSrcOf(lo,$u,Ru)};const Du=runnable(parseAppspec(Mu.spec));return Du.kind==="decision"?{kind:"frame",src:frameSrcOf(lo,$u,Ru)}:{kind:"spec",app:Du}}function currentScriptUrl(){try{const Au=document.currentScript;return Au?.src?new URL(Au.src,location.href).href:""}catch{return""}}function defineDatalayerAppElement(Au={}){if(typeof window>"u"||!("customElements"in window))return;const lo=Au.tag??EMBED_TAG,$u=customElements.get(lo);if($u)return $u;const Ru=Au.scriptUrl??currentScriptUrl(),Iu=Ru?new URL(Ru).origin:"",Pu=Ru?Ru.replace(/\.js(\?.*)?$/,".css"):"";class Ou extends HTMLElement{static get observedAttributes(){return EMBED_OBSERVED_ATTRIBUTES}root=null;frame=null;source=null;loading=0;passed={};offered={};windowPort=null;host={context:()=>this.passed,userToken:()=>this.getAttribute("user-token")||void 0,functions:this.offered,onWindowPort:Du=>{this.windowPort=Du},onEvent:Du=>this.dispatchEvent(new CustomEvent(Du.type,{detail:Du.detail,bubbles:!0,composed:!0}))};get context(){return this.passed}set context(Du){this.passed={...Du??{}}}postWindowMessage(Du){const Lu=this.windowPort;return Lu?Lu(Du):Promise.reject(new Error(`datalayer-app: ${WINDOW_NOT_YET}`))}get functions(){return this.offered}set functions(Du){for(const Lu of Object.keys(this.offered))delete this.offered[Lu];Object.assign(this.offered,Du??{})}constructor(){super(),this.attachShadow({mode:"open"}),this.onMessage=this.onMessage.bind(this),adoptPropertiesSetEarly(this)}get token(){return this.getAttribute("token")??""}set token(Du){Du?this.setAttribute("token",String(Du)):this.removeAttribute("token")}get userToken(){return this.getAttribute("user-token")??""}set userToken(Du){Du?this.setAttribute("user-token",String(Du)):this.removeAttribute("user-token")}connectedCallback(){window.addEventListener("message",this.onMessage),this.load()}disconnectedCallback(){window.removeEventListener("message",this.onMessage),this.unmount()}attributeChangedCallback(Du,Lu,Bu){if(!(!this.isConnected||Lu===Bu)&&Du!=="user-token"){if(Du==="token"&&this.frame?.contentWindow&&Bu){this.frame.contentWindow.postMessage({type:EMBED_MESSAGES.token,token:Bu},this.origin());return}if(["mode","accent","theme","font","height","resume","language"].includes(Du)){this.draw();return}this.load()}}origin(){return(this.getAttribute("origin")||Iu||location.origin).replace(/\/+$/,"")}inputs(){const Du={};for(const ju of EMBED_OBSERVED_ATTRIBUTES)Du[ju]=this.getAttribute(ju);const Lu=getComputedStyle(this),Bu={};for(const[ju,Fu]of Object.entries(EMBED_HOST_VARIABLES)){const zu=Lu.getPropertyValue(Fu).trim();zu&&(Bu[ju]=zu.replace(/^["']|["']$/g,""))}return{attributes:Du,variables:Bu}}async read(){const Du=this.querySelector('script[type="application/yaml"], script[type="application/json"], script[type="text/yaml"]');if(Du?.textContent?.trim())return{kind:"spec",app:appspecOfText(Du.textContent)};const Lu=this.getAttribute("spec");if(Lu){const Fu=await fetch(new URL(Lu,location.href).href);return Fu.ok?{kind:"spec",app:appspecOfText(await Fu.text())}:{kind:"said",text:`datalayer-app: the Appspec at ${Lu} could not be read (${Fu.status}).`}}const Bu=this.getAttribute("app");if(!Bu)return{kind:"said",text:'datalayer-app: the "app" attribute names the application to show, or "spec" the address of its Appspec.'};const ju=this.token;if(!ju){const Fu=await readVisitorApp({api:this.api(),app:Bu});return Fu.kind==="decision"?{kind:"frame",src:frameSrcOf(this.origin(),Fu.app)}:Fu.kind==="said"?{kind:"said",text:Fu.text}:{kind:"spec",app:Fu.app,visitors:Fu.visitors}}return readEmbeddedApp({api:this.api(),origin:this.origin(),app:Bu,token:ju})}spoken=null;get speech(){const Du=coreStore.getState().configuration?.aiAgentsUrl??"";return this.spoken?.speechUrl!==Du&&(this.spoken={speechUrl:Du}),this.spoken}api(){return(this.getAttribute("api")||coreStore.getState().configuration?.spacerUrl||DEFAULT_API).replace(/\/+$/,"")}async load(){const Du=++this.loading;let Lu;try{Lu=await this.read()}catch(Bu){Lu={kind:"said",text:Bu instanceof Error?Bu.message:`datalayer-app: ${String(Bu)}`}}Du!==this.loading||!this.isConnected||(this.source=Lu,this.draw(),Lu.kind==="said"&&Lu.expired&&this.dispatchEvent(new CustomEvent("token-expired",{detail:{app:this.getAttribute("app")??""},bubbles:!0,composed:!0})))}unmount(){this.root?.unmount(),this.root=null,this.frame=null}skeleton(Du){const Lu=this.shadowRoot;if(this.unmount(),Lu.replaceChildren(),Pu){const ju=document.createElement("link");ju.rel="stylesheet",ju.href=Pu,Lu.appendChild(ju)}const Bu=document.createElement("style");return Bu.textContent=embedShadowCss(Du),Lu.appendChild(Bu),Lu}say(Du){this.setAttribute("data-embed-mode","inline");const Lu=this.skeleton(),Bu=document.createElement("p");Bu.className="datalayer-app-said",Bu.setAttribute("role","status"),Bu.textContent=Du,Lu.appendChild(Bu)}draw(){const Du=this.source;if(!Du)return;if(Du.kind==="said"){this.say(Du.text);return}if(Du.kind==="frame"){let Hu;try{Hu=languageOf(this.getAttribute("language"))}catch(Wu){this.say(Wu.message);return}this.setAttribute("data-embed-mode","inline");const Vu=this.skeleton(),Gu=document.createElement("iframe");Gu.className="datalayer-app-frame",Gu.src=frameInLanguage(Du.src,Hu),Gu.title="Datalayer app",Gu.style.height=`${inlineHeightOf(this.getAttribute("height"))}px`,Gu.setAttribute("allow","clipboard-write"),Vu.appendChild(Gu),this.frame=Gu;return}let Lu,Bu,ju;try{Lu=embedLookOf(this.inputs(),Du.app),Bu=resumeOf(this.getAttribute("resume")),ju=languageOf(this.getAttribute("language"))}catch(Hu){this.say(Hu.message);return}if(Lu.mode==="assistant"){const Hu=embedAssistantCharacter(Du.app);if("problem"in Hu){this.say(Hu.problem);return}}this.setAttribute("data-embed-mode",Lu.mode);const Fu=this.skeleton(getThemeConfig(Lu.variant).themeStyles.css),zu=document.createElement("div");zu.className="datalayer-app-root",Fu.appendChild(zu),this.root=clientExports.createRoot(zu);const Uu=this.getAttribute("server")||void 0;this.root.render(jsxRuntimeExports.jsx(me$3,{target:Fu,children:jsxRuntimeExports.jsx(AppEmbed,{app:Du.app,mode:Lu.mode,accent:Lu.accent,colorMode:Lu.colorMode,font:Lu.font,serverUrl:Uu,...Uu&&this.token?{embedToken:this.token}:{},...Du.visitors?{visitors:Du.visitors}:{},speech:this.speech,height:inlineHeightOf(this.getAttribute("height")),ownPortal:!0,host:this.host,resume:Bu,...ju?{language:ju}:{}})}))}onMessage(Du){if(!this.frame||Du.source!==this.frame.contentWindow||Du.origin!==this.origin())return;const Lu=Du.data??{};Lu.type===EMBED_MESSAGES.size&&typeof Lu.height=="number"&&Lu.height>0?this.frame.style.height=`${Math.ceil(Lu.height)}px`:Lu.type===EMBED_MESSAGES.decision?this.dispatchEvent(new CustomEvent("decision",{detail:Lu.record,bubbles:!0,composed:!0})):Lu.type===EMBED_MESSAGES.tokenExpired&&this.dispatchEvent(new CustomEvent("token-expired",{detail:{app:this.getAttribute("app")??""},bubbles:!0,composed:!0}))}}return customElements.define(lo,Ou),Ou}const SCRIPT_FILE="datalayer-app.js";defineDatalayerAppElement({scriptUrl:new URL(SCRIPT_FILE,import.meta.url).href});const mermaidVLURNSYL=Object.freeze(Object.defineProperty({__proto__:null,Mermaid:Ee$2},Symbol.toStringTag,{value:"Module"}));export{styleTags as $,A2uiSurfaceComposed as A,Box as B,CheckIcon as C,Dialog$1 as D,useContributions as E,LoopPromptPanel as F,InputPrompt as G,Heading$2 as H,IconButton as I,Signal as J,o$1 as K,Label as L,MessageProcessor as M,NO_SANDBOX_YET as N,LoopOpeningNotebook as O,PlayIcon as P,QueryClient as Q,LoopNotebookToolbarItem as R,SANDBOX_KIND_LABELS as S,Text$3 as T,LoopNotebookToolbar as U,LRLanguage as V,LanguageSupport as W,indentNodeProp as X,continuedIndent as Y,foldNodeProp as Z,__vitePreload as _,QueryClientProvider as a,AGENTS_PLUGIN_NAME as a$,tags as a0,ExternalTokenizer as a1,ifNotIn as a2,completeFromList as a3,LRParser as a4,syntaxTree as a5,delimitedIndent as a6,foldInside as a7,getDefaultExportFromCjs as a8,MimeModel as a9,DatalayerThemeProvider as aA,de$1 as aB,on$1 as aC,nl as aD,es as aE,H as aF,disposeServiceManager as aG,create$g as aH,setIfUndefined as aI,create$6 as aJ,fromBase64 as aK,onChange as aL,varStorage as aM,toBase64 as aN,offChange as aO,createUint8ArrayFromArrayBuffer as aP,map$3 as aQ,ContextTracker as aR,NodeWeakMap as aS,IterMode as aT,snippetCompletion as aU,Panel as aV,PromiseDelegate as aW,DEFAULT_SERVICE_URLS as aX,requestDatalayerAPI as aY,API_BASE_PATHS as aZ,useReactorPlatform as a_,standardRendererFactories as aa,purify$1 as ab,Token$2 as ac,Menu as ad,DisposableDelegate as ae,ArrayExt as af,Widget as ag,PanelLayout as ah,ITranslator as ai,createToolbarFactory as aj,nullTranslator as ak,ObservableList as al,Toolbar$1 as am,ReactWidget as an,some$1 as ao,useAgentsRuntimes as ap,xu as aq,useThemeStore as ar,useSystemColorMode as as,getThemeConfig as at,JupyterReactTheme$1 as au,l$1 as av,v$1 as aw,a$1 as ax,Kernel as ay,registerSandboxServiceManager as az,sandboxExecuteOverHttp as b,VDomModel as b$,DEFAULT_DATALAYER_AGENTSPEC as b0,useOptionalSandboxService as b1,IDLE_SANDBOX_TARGET_SIGNAL as b2,ensureVisitorAgent as b3,AGENTSPECS$1 as b4,useAgentRuntimes as b5,ActionList as b6,distExports as b7,ActionListContainerContext as b8,BoxWithFallback as b9,defineLanguageFacet as bA,Parser$2 as bB,NodeType as bC,NodeProp as bD,Tag as bE,NodeSet as bF,Tree as bG,countColumn as bH,Prec as bI,keymap as bJ,Language as bK,indentUnit as bL,foldService as bM,CompletionContext as bN,EditorState as bO,languageDataProp as bP,LanguageDescription as bQ,ParseContext as bR,Eu as bS,Ke$2 as bT,_c as bU,is as bV,Ys as bW,PencilIcon as bX,SingletonLayout as bY,FocusTracker as bZ,libExports$5 as b_,merge$5 as ba,defaultSxProp as bb,useId as bc,reactDomExports as bd,useIsomorphicLayoutEffect$2 as be,ChevronDownIcon as bf,classes$t as bg,SubItem as bh,Box$1 as bi,themeConfigs as bj,LoopDocumentToolbarItem as bk,LoopDocumentToolbar as bl,LoopOpeningDocument as bm,IDLE_SANDBOX_SNAPSHOT_SIGNAL as bn,definePlugin as bo,DOCUMENT_TOOLBAR_PLUGIN_NAME as bp,contribution as bq,KernelIndicator as br,NOTEBOOK_TOOLBAR_PLUGIN_NAME as bs,LocalTokenGroup as bt,flatIndent as bu,parseMixed as bv,bracketMatchingHandle as bw,EditorView as bx,EditorSelection as by,sublanguageProp as bz,ButtonComponent as c,ITableOfContentsRegistry as c$,TableOfContents as c0,JSONExt as c1,VDomRenderer as c2,LabIcon as c3,classes as c4,map$5 as c5,showErrorMessage as c6,AttachedProperty as c7,addIcon as c8,launcherIcon as c9,linkIcon as cA,Clipboard as cB,downloadIcon as cC,copyIcon as cD,setToolbar as cE,Notification as cF,CommandRegistry as cG,closeIcon as cH,cutIcon as cI,pasteIcon as cJ,newFolderIcon as cK,textEditorIcon as cL,markdownIcon as cM,refreshIcon as cN,editIcon as cO,fileIcon as cP,stopIcon as cQ,filterIcon as cR,DisposableSet as cS,clearNumbering as cT,getHeadingId as cU,addPrefix as cV,parseHeadings as cW,filterHeadings as cX,StackedLayout as cY,ABCWidgetFactory as cZ,DocumentWidget as c_,MainAreaWidget as ca,find$3 as cb,TranslatorConnector as cc,Gettext as cd,DEFAULT_LANGUAGE_CODE as ce,normalizeDomain as cf,ITranslatorConnector as cg,Dialog as ch,showDialog$1 as ci,SearchDocumentModel as cj,SearchDocumentView as ck,isResponsiveValue as cl,clsx as cm,commonjsRequire as cn,TextInput$1 as co,SearchIcon as cp,SyncIcon as cq,ToggleSwitch as cr,Flash as cs,ChevronRightIcon as ct,StyledSpinner as cu,ToolbarButton as cv,fileUploadIcon as cw,libExports$2 as cx,WidgetTracker as cy,folderIcon as cz,displayUrl as d,OutputPrompt as d$,markdownRendererFactory as d0,SkeletonBox as d1,getBrightPalette as d2,useColorPalette as d3,SkeletonText as d4,Tooltip as d5,ActionMenu as d6,buildIcon as d7,jupyterIcon as d8,SettingRegistry as d9,EditorExtensionRegistry as dA,ybinding as dB,IPositionModel as dC,historyIcon as dD,CommandToolbarButton as dE,caretLeftIcon as dF,caretRightIcon as dG,checkIcon as dH,COMPLETER_ACTIVE_CLASS as dI,Debouncer as dJ,SessionContextDialogs as dK,saveIcon as dL,addCommandToolbarButtonClass as dM,UseSignal as dN,CommandToolbarButtonComponent as dO,createStore$1 as dP,useStore$1 as dQ,runtimesStore as dR,DATALAYER_IAM_TOKEN_KEY as dS,DATALAYER_IAM_USER_KEY as dT,coreStore as dU,iamStore as dV,layoutStore as dW,useCoreStore as dX,useIAMStore as dY,useLayoutStore as dZ,useRuntimesStore as d_,moveUpIcon as da,moveDownIcon as db,Button$1 as dc,deleteIcon as dd,DOMUtils as de,lineFormIcon as df,deleteLine as dg,toggleBlockComment as dh,toggleComment as di,toggleTabFocusMode as dj,selectNextOccurrence as dk,foldable as dl,foldCode as dm,unfoldCode as dn,foldState as dp,foldEffect as dq,unfoldEffect as dr,foldAll as ds,unfoldAll as dt,IEditorServices as du,EditorLanguageRegistry as dv,parseMathIPython as dw,StreamLanguage as dx,pythonBuiltin as dy,EditorThemeRegistry as dz,Link$1 as e,AgentTools as e$,Stdin as e0,CodeCell as e1,useJupyterLabCssLoaded as e2,TelescopeIcon as e3,XIcon as e4,CounterLabel as e5,PauseIcon as e6,DownloadIcon as e7,SPAN_SOURCE_LABELS as e8,sourceOfSpan as e9,useAgentRuntimeMcpStatus as eA,useAgentRuntimeCodemodeStatus as eB,useAgentRuntimeContextSnapshot as eC,useAgentRuntimeFullContext as eD,useAgentRuntimeWsState as eE,useMutation as eF,useQuery as eG,ForwardRef$2 as eH,NoteIcon as eI,ServerIcon as eJ,CheckCircleIcon as eK,XCircleIcon as eL,BriefcaseIcon as eM,MenuBar as eN,runIcon as eO,fastForwardIcon as eP,require_MapCache as eQ,require_Symbol as eR,require_Uint8Array as eS,requireEq as eT,require_getAllKeys as eU,require_Stack as eV,require_getTag as eW,requireIsArray as eX,requireIsBuffer as eY,requireIsTypedArray as eZ,requireIsObjectLike as e_,AGENT_SPAN_ATTRIBUTES as ea,describeAgentSpan as eb,SpecMark as ec,parse$4 as ed,UUID as ee,EN_US as ef,errorIcon as eg,Platform as eh,caretDownEmptyThinIcon as ei,StringExt as ej,SegmentedControl as ek,ListUnorderedIcon as el,GraphIcon as em,ClockIcon as en,DatabaseIcon as eo,FileIcon as ep,ToolsIcon as eq,CommentDiscussionIcon as er,AiModelIcon as es,InfoIcon as et,KeyIcon as eu,devtools as ev,subscribeWithSelector as ew,persist as ex,CheckCircleFillIcon as ey,AlertIcon as ez,CopyIcon as f,THREAD_WORDS as f$,useToast as f0,isInsideJupyterLab as f1,FormControl$1 as f2,MailIcon as f3,Textarea as f4,$e$5 as f5,useAnonymousInferenceSession as f6,browserModelRequiresSignIn as f7,getAgentspecs as f8,useOptionalReactorPlatform as f9,onSurfaceRequest as fA,setEditorOptions as fB,seedEditorChoice as fC,canOpenView as fD,useWorkspaceFullScreen as fE,targetRunsAgentInPage as fF,useOptionalTeamSelection as fG,LoopAgentBlueprint as fH,resolveAgentspec as fI,LoopChatSuggestion as fJ,agentIcon as fK,LoopFrontendTool as fL,BROWSER_CODE_TOOL as fM,agentServerOf as fN,LoopCommand as fO,subagentsFor as fP,useChatAvailability as fQ,noRuntimeSaid as fR,useVoiceSettings as fS,settledVoice as fT,useSlotComponents as fU,LoopSlots as fV,onPromptFocusRequest as fW,useVisitorToken as fX,voiceAskedAs as fY,generateMessageId as fZ,openThread as f_,PRESENCE_LINES as fa,FluentEmoji as fb,useChatWords as fc,CHAT_PLUGIN_NAME as fd,INPUT_PROMPT_PLUGIN_NAME as fe,LoopChatSurface as ff,LoopChatComposer as fg,LoopChatHeader as fh,LoopChatLayout as fi,LoopChatTurn as fj,turnWritersOf as fk,LoopChatExtras as fl,computed$1 as fm,useGate as fn,presenceState as fo,presenceToolOf as fp,newestIsAnswer as fq,latestSaying as fr,messageText as fs,LoopRunProps as ft,runForwardedProps as fu,dataUrlBase64 as fv,sandboxFileName as fw,writeFilesCode as fx,givenFilesSentence as fy,sendInstead as fz,createAllAgentRuntimesTools as g,CommandPalette$1 as g$,agentInstructions as g0,useConfig as g1,useSkills as g2,useSkillActions as g3,runtimeModelsUrl as g4,readServerCatalogue as g5,readServerDecisions as g6,offeredModels as g7,AI_MODEL_CATALOGUE as g8,isChatModel as g9,requireMessages as gA,mockSocketExports as gB,ObservableMap as gC,CodeEditorWrapper as gD,CodeEditor as gE,IEditorMimeTypeService as gF,EditorSearchProvider as gG,CodeMirrorEditor as gH,getPrefix as gI,isMarkdown as gJ,findNext as gK,gotoLine as gL,consoleIcon as gM,undoIcon as gN,redoIcon as gO,selectAll as gP,Sanitizer as gQ,COMPLETER_ENABLED_CLASS as gR,MessageLoop as gS,COMPLETER_LINE_BEGINNING_CLASS as gT,Message as gU,ElementExt as gV,renderText as gW,Printing as gX,clientExports as gY,RenderedJavaScript as gZ,filterListIcon as g_,ReactorSlot as ga,ComposerVoice as gb,ReactorLazy as gc,ChatBase as gd,ScreenNormalIcon as ge,ScreenFullIcon as gf,SUGGESTION_CHIP_WIDTH as gg,Truncate as gh,useAnonymousSessionStore as gi,inPageAgentRefusal as gj,signal$2 as gk,LoopAgentGate as gl,agentRuntimeStore as gm,loopShapeVars as gn,NONE_EDITOR as go,getAnchoredPosition as gp,reactIsExports as gq,useTheme as gr,useOnEscapePress as gs,useOnOutsideClick as gt,useResizeObserver as gu,VisuallyHidden as gv,TriangleDownIcon as gw,qe$4 as gx,sx as gy,requireSerialize as gz,renderOcticon as h,strokeWidth$1 as h$,h$7 as h0,LabIconStyle as h1,copyrightIcon as h2,ToolbarButtonComponent as h3,bellIcon as h4,Button$3 as h5,paletteIcon as h6,Throttler as h7,Selector$1 as h8,jupyterFaviconIcon as h9,startSlotTemplate as hA,endSlotTemplate as hB,slotted as hC,elements as hD,FoundationElement as hE,isHTMLElement as hF,__decorate$1 as hG,attr as hH,observable as hI,applyMixins as hJ,StartEnd as hK,keyEnter as hL,keyArrowUp as hM,keyArrowDown as hN,keyArrowRight as hO,keyArrowLeft as hP,keyEnd as hQ,keyHome as hR,DOM as hS,getDisplayedNodes as hT,direction$1 as hU,neutralForegroundRest$1 as hV,neutralFillStealthRest$1 as hW,bodyFont$1 as hX,focusVisible as hY,accentFillFocus$1 as hZ,focusStrokeWidth$1 as h_,caretDownEmptyIcon as ha,addToolbarButtonClass as hb,NotebookActions as hc,offlineBoltIcon as hd,circleIcon as he,ObservableJSON as hf,ConflatableMessage as hg,jumpBackIcon as hh,jumpForwardIcon as hi,MarkdownCell as hj,Cell as hk,trustedIcon as hl,notTrustedIcon as hm,runCell as hn,InputPrompt$1 as ho,NotebookPanel as hp,setCellExecutor as hq,StaticNotebook as hr,notebookIcon as hs,NotebookSearchProvider as ht,duplicateIcon as hu,addAboveIcon as hv,addBelowIcon as hw,children$1 as hx,ref$1 as hy,html$6 as hz,SquareFillIcon as i,createCellModelFromSharedType as i$,controlCornerRadius$1 as i0,heightNumber$1 as i1,neutralFillStealthHover$1 as i2,neutralFillStealthActive$1 as i3,designUnit$1 as i4,typeRampBaseFontSize$1 as i5,typeRampBaseLineHeight$1 as i6,density$1 as i7,typeRampPlus1FontSize$1 as i8,disabledOpacity$1 as i9,circleEmptyIcon as iA,searchIcon as iB,SplitPanel as iC,TabBar as iD,jsonIcon as iE,spreadsheetIcon as iF,terminalIcon as iG,kernelIcon as iH,NotificationManager as iI,SessionContext as iJ,Spinner as iK,Styling as iL,SystemClipboard as iM,VisuallyHidden$1 as iN,StopIcon as iO,ViewPlugin as iP,createRelativePositionFromTypeIndex as iQ,createRelativePositionFromJSON as iR,tooltips as iS,Facet as iT,Annotation as iU,layer as iV,StateField as iW,showTooltip as iX,createAbsolutePositionFromRelativePosition as iY,RectangleMarker as iZ,YDocument as i_,disabledCursor as ia,baseHeightMultiplier$1 as ib,neutralFillRest$1 as ic,neutralFillHover$1 as id,neutralFillActive$1 as ie,accentForegroundRest$1 as ig,display as ih,css as ii,forcedColorsStylesheetBehavior as ij,SystemColors as ik,cssPartial as il,DesignToken as im,neutralFillStealthRecipe$1 as io,neutralFillRecipe$1 as ip,useEventListener as iq,useProperties as ir,provideJupyterDesignSystem$1 as is,ITableOfContentsTracker as it,tocIcon as iu,numberingIcon as iv,expandAllIcon as iw,collapseAllIcon as ix,ellipsesIcon as iy,caretDownIcon as iz,jsxRuntimeExports as j,activateHover as j$,createCell as j0,YMap as j1,RawCellModel as j2,MarkdownCellModel as j3,CodeCellModel as j4,MINOR_VERSION as j5,MAJOR_VERSION as j6,StateEffect as j7,Decoration as j8,WidgetType as j9,CheckboxOrRadioGroup$1 as jA,CheckboxGroupContext as jB,Checkbox as jC,RadioGroup$1 as jD,Radio as jE,SelectPanel as jF,Select$1 as jG,TextInputWithTokens as jH,object as jI,preprocess$1 as jJ,record$1 as jK,string$2 as jL,unknown$1 as jM,zodToToolParameters as jN,array as jO,_enum as jP,number$2 as jQ,boolean$1 as jR,validateWithZod as jS,useJupyterReactStoreFromProps as jT,OutputArea as jU,createStandaloneCell as jV,BoxPanel as jW,cellsStore as jX,RawCell as jY,useCellsStore as jZ,getPanel as j_,DEFAULT_VARIANT as ja,MarimoReactive as jb,NotebookCommandIds as jc,OutputAreaModel as jd,useJupyterReactStore as je,newUuid as jf,NotebookPanelProvider as jg,addNotebookCommands as jh,YArray as ji,YText as jj,newUlid as jk,k$2 as jl,loopColors as jm,sunColors as jn,ivoryColors as jo,sandColors as jp,earthColors as jq,matrixColors as jr,lovelyColors as js,spatialColors as jt,datalayerColors as ju,getColorPalette as jv,CheckboxOrRadioGroupValidation as jw,CheckboxOrRadioGroupLabel as jx,CheckboxOrRadioGroupCaption as jy,useRenderForcingRef as jz,TrashIcon as k,y$3 as k$,showPanel as k0,combineConfig as k1,RangeSetBuilder as k2,crelt as k3,hoverTooltip as k4,lineNumbers as k5,highlightActiveLineGutter as k6,highlightSpecialChars as k7,history as k8,foldGutter as k9,ccount as kA,zwitch as kB,html$4 as kC,htmlVoidElements as kD,C$1 as kE,Dt$4 as kF,u$2 as kG,dt$2 as kH,Go as kI,ns as kJ,mn$1 as kK,qi as kL,Pi as kM,isStream as kN,isExecuteResult as kO,isDisplayData as kP,isError$1 as kQ,Xo as kR,Ki as kS,Yi as kT,er as kU,T as kV,v$2 as kW,S$1 as kX,C as kY,m$2 as kZ,x$5 as k_,drawSelection as ka,dropCursor as kb,indentOnInput as kc,syntaxHighlighting as kd,bracketMatching as ke,closeBrackets as kf,autocompletion as kg,rectangularSelection as kh,crosshairCursor as ki,highlightActiveLine as kj,highlightSelectionMatches as kk,closeBracketsKeymap as kl,defaultKeymap as km,searchKeymap as kn,historyKeymap as ko,foldKeymap as kp,completionKeymap as kq,defaultHighlightStyle as kr,ArrowRightIcon as ks,useOutputsStore as kt,Compartment as ku,whitespace as kv,svg$2 as kw,find as kx,stringify$1 as ky,stringify as kz,libExports$3 as l,TextModelFactory as l$,p$4 as l0,ol as l1,He$2 as l2,pn$2 as l3,Kr as l4,ur as l5,ls as l6,cn$1 as l7,_n as l8,hn$2 as l9,useResponsiveValue as lA,ScrollableRegion as lB,viewportRanges as lC,JupyterLiteServer as lD,Router as lE,ContextMenu as lF,TabPanel as lG,DockPanel as lH,hpass as lI,AccordionPanel as lJ,AccordionLayout as lK,FormAssociated as lL,nullableNumberConverter as lM,ARIAGlobalStatesAndProperties as lN,neutralFillInputRest$1 as lO,neutralFillStrongRest$1 as lP,errorFillRest$1 as lQ,neutralFillInputHover$1 as lR,neutralFillStrongHover$1 as lS,errorFillHover$1 as lT,neutralFillStrongActive$1 as lU,errorFillActive$1 as lV,errorFillFocus$1 as lW,neutralStrokeRest$1 as lX,__decorate as lY,BoxLayout as lZ,VirtualDOM as l_,qc as la,Ie$2 as lb,cs as lc,dr as ld,Jl as le,fn$2 as lf,hn$1 as lg,pn$1 as lh,Wo as li,xt$2 as lj,Zs as lk,gc as ll,On as lm,na as ln,ea as lo,ia as lp,sa as lq,decodeNamedCharacterReference as lr,requireReact as ls,StyleModule as lt,jupyterHighlightStyle as lu,useFocusZone as lv,FocusKeys as lw,useSafeTimeout as lx,useSlots as ly,useProvidedRefOrCreate as lz,PlusIcon as m,KERNEL_STATE_LABELS as m$,pdfIcon as m0,pythonIcon as m1,juliaIcon as m2,rKernelIcon as m3,yamlIcon as m4,imageIcon as m5,audioIcon as m6,videoIcon as m7,writeVarUint as m8,encodeStateVector as m9,filter$3 as mA,caretUpIcon as mB,Poll as mC,each as mD,Application as mE,StackedPanel as mF,tabIcon as mG,Base64ModelFactory as mH,useTerminalStore as mI,requestAPI$1 as mJ,loadJupyterConfig as mK,createLiteServiceManager as mL,jupyterReactStore as mM,ANSWER_MARKER as mN,BuilderManagerLess as mO,ContentsManagerLess as mP,DEFAULT_API_KERNEL_PREFIX_URL as mQ,DEFAULT_JUPYTER_SERVER_TOKEN as mR,DEFAULT_JUPYTER_SERVER_URL as mS,DEFAULT_KERNEL_NAME as mT,DefaultExecutor as mU,EventsManagerLess as mV,ExecutionPhase as mW,HELPER_NAME as mX,JupyterLabCss as mY,KERNEL_HELPER_SOURCE as mZ,KERNEL_STATES as m_,writeVarUint8Array as ma,encodeStateAsUpdate as mb,readVarUint as mc,applyUpdate as md,readVarUint8Array as me,readVarString as mf,ObservableV2 as mg,Awareness as mh,toUint8Array$1 as mi,length as mj,encodeAwarenessUpdate as mk,removeAwarenessStates as ml,isNode as mm,getUnixTime as mn,createEncoder as mo,min as mp,pow as mq,createDecoder as mr,applyAwarenessUpdate as ms,UndoManager as mt,Doc$1 as mu,isCodeCellModel as mv,Drag as mw,MimeData as mx,useConsoleStore as my,folderFavoriteIcon as mz,CodeIcon as n,Fi as n$,KERNEL_STATE_VISUALS as n0,KernelExecutor as n1,KernelManagerLess as n2,KernelspecManagerLess as n3,NbConvertManagerLess as n4,OperationRunner as n5,ServiceManagerLess as n6,SessionManagerLess as n7,SettingManagerLess as n8,TerminalManagerLess as n9,loadJupyterLabCss as nA,notebookToolDefinitions as nB,notebookToolOperations as nC,notebookTools as nD,outputsAsString as nE,outputsStore as nF,readAllCellsOperation as nG,readAllCellsTool as nH,readCellOperation as nI,readCellTool as nJ,refreshJupyterLabPortalTheme as nK,renderKernelStateGlyph as nL,resetJupyterConfig as nM,runCellOperation as nN,runCellTool as nO,setJupyterServerToken as nP,setJupyterServerUrl as nQ,sleep as nR,syncJupyterLabPortalTheme as nS,terminalStore as nT,toKernelState as nU,updateCellOperation as nV,updateCellTool as nW,useJupyterReactColormode as nX,useKernelsStore as nY,ThemeProvider as nZ,Overlay$1 as n_,UserManagerLess as na,WorkspaceManagerLess as nb,cellSourceAsString as nc,consoleStore as nd,createLiteServer as ne,createServerSettings as nf,deleteCellsOperation as ng,deleteCellsTool as nh,disableKernelReconnect as ni,disposeKernelConnections as nj,ensureJupyterAuth as nk,ensureJupyterConfig as nl,executeCodeOperation as nm,executeCodeTool as nn,formatResponse as no,getCookie as np,getJupyterServerToken as nq,getJupyterServerUrl as nr,getKernelIndicatorMeta as ns,insertCellOperation as nt,insertCellTool as nu,isAnyCellRunning as nv,isReactiveVariant as nw,isServedByJupyterLab as nx,jupyterLabTheme as ny,kernelsStore as nz,notebookStore as o,kn$1 as o$,Zl as o0,bu as o1,Nu as o2,Wl as o3,Fr as o4,Li as o5,Vc as o6,Fo as o7,sn$1 as o8,vc as o9,Is as oA,Dl as oB,h$1 as oC,Sn$1 as oD,Nn$1 as oE,ce$1 as oF,Tu as oG,vu as oH,ae$1 as oI,xt$3 as oJ,St$3 as oK,Pc as oL,Lc as oM,Ic as oN,mt$3 as oO,rs as oP,an$1 as oQ,Je$2 as oR,Ft$1 as oS,Os as oT,Mt$1 as oU,gt as oV,Co as oW,Tn as oX,Dt as oY,So as oZ,vn as o_,tr as oa,Sn as ob,Zo as oc,Cu as od,Bs as oe,Me as of,yn as og,Se as oh,Cn as oi,fn as oj,qr as ok,Ia as ol,zs as om,gn$2 as on,or as oo,Jr as op,sn$2 as oq,ln$1 as or,rn$1 as os,nn$2 as ot,Vr as ou,nu as ov,du as ow,Va as ox,au as oy,La as oz,decode$4 as p,We as p$,xl as p0,oa as p1,Cn$1 as p2,et as p3,xn as p4,St as p5,Rt as p6,xt as p7,yn$1 as p8,It$1 as p9,Yt as pA,Ya as pB,Pe$2 as pC,Ja as pD,tu as pE,zl as pF,Fl as pG,Ma as pH,ja as pI,Hl as pJ,Ba as pK,Bl as pL,Pr as pM,Pe as pN,uo as pO,mu as pP,iu as pQ,ku as pR,Mo as pS,Rl as pT,wu as pU,Fn as pV,lc as pW,$s as pX,he as pY,Fe as pZ,Ut$1 as p_,Tt as pa,l$2 as pb,a$2 as pc,d$2 as pd,s$2 as pe,Ue$2 as pf,dn$2 as pg,$e$2 as ph,un$1 as pi,Bi as pj,It as pk,en$2 as pl,_$1 as pm,te$2 as pn,le$2 as po,on$2 as pp,$t$3 as pq,mn$2 as pr,Xe$2 as ps,gr as pt,Ge$2 as pu,_r as pv,Ve$2 as pw,je$1 as px,Ye$1 as py,qe$2 as pz,formatTokenCount as q,En$1 as q$,Fs as q0,Al as q1,No as q2,bo as q3,as as q4,_t as q5,eu as q6,fc as q7,Re as q8,Kc as q9,z as qA,O$1 as qB,r$2 as qC,t$2 as qD,Es as qE,_s as qF,vt$2 as qG,n$2 as qH,b$1 as qI,nn$1 as qJ,r$1 as qK,g$1 as qL,Tt$2 as qM,ys as qN,e$1 as qO,vl as qP,u$1 as qQ,b$3 as qR,z$1 as qS,zi as qT,Ji as qU,ko as qV,To as qW,Ze$2 as qX,Qe$2 as qY,Mn$1 as qZ,wn$1 as q_,Wt$1 as qa,z$2 as qb,ac as qc,On$1 as qd,Ht$1 as qe,Le$2 as qf,zr as qg,Bt$1 as qh,Ll as qi,ui as qj,ec as qk,nc as ql,zt$1 as qm,Ir as qn,i$1 as qo,uu as qp,Aa as qq,Wa as qr,Ul as qs,ql as qt,dc as qu,be as qv,ke as qw,ft as qx,pi as qy,x$4 as qz,reactExports as r,RssIcon as r$,xo as r0,vi as r1,Ql as r2,ut$2 as r3,Gl as r4,ReactDOM as r5,M$2 as r6,PersonIcon as r7,Pt$1 as r8,s$1 as r9,BroadcastIcon as rA,BrowserIcon as rB,BugIcon as rC,CircleSlashIcon as rD,CodeReviewIcon as rE,CpuIcon as rF,CreditCardIcon as rG,DependabotIcon as rH,DeviceDesktopIcon as rI,DeviceMobileIcon as rJ,FoldIcon as rK,GearIcon as rL,GitBranchIcon as rM,GlobeIcon as rN,HeartIcon as rO,IssueOpenedIcon as rP,LightBulbIcon as rQ,LinkExternalIcon as rR,MegaphoneIcon as rS,MortarBoardIcon as rT,MuteIcon as rU,OrganizationIcon as rV,PackageIcon as rW,PaperclipIcon as rX,PeopleIcon as rY,PulseIcon as rZ,RocketIcon as r_,f$3 as ra,P$1 as rb,fe$1 as rc,PaperAirplaneIcon as rd,bn$2 as re,TableIcon as rf,q as rg,ChecklistIcon as rh,fn$1 as ri,GrabberIcon as rj,vo as rk,yo as rl,wo as rm,mo as rn,j$1 as ro,r$3 as rp,$2AODx$react as rq,jt$1 as rr,oe$1 as rs,ie$2 as rt,RowsIcon as ru,x$2 as rv,AlertFillIcon as rw,BeakerIcon as rx,BellIcon as ry,BookIcon as rz,sandboxIsLive as s,__rest as s$,ShareAndroidIcon as s0,ShieldCheckIcon as s1,ShieldIcon as s2,SidebarExpandIcon as s3,SkipIcon as s4,SlidersIcon as s5,SparkleFillIcon as s6,SquareCircleIcon as s7,SunIcon as s8,TagIcon as s9,require_Set as sA,requireKeysIn as sB,requireIsArrayLikeObject as sC,requireIsPlainObject$1 as sD,require_baseMerge as sE,require_createAssigner as sF,require_apply as sG,require_copyArray as sH,require_arrayEach as sI,requireCloneDeep as sJ,requireFastUri as sK,ForwardRef$1 as sL,ForwardRef as sM,memoize as sN,isPropValid as sO,tabbable as sP,focusable as sQ,isTabbable as sR,getTabIndex as sS,isFocusable as sT,index_esm as sU,requirePropTypes as sV,s$5 as sW,__assign as sX,requireReactDom as sY,__extends as sZ,__awaiter as s_,TasklistIcon as sa,ThumbsdownIcon as sb,ThumbsupIcon as sc,UnmuteIcon as sd,UploadIcon as se,XCircleFillIcon as sf,ZapIcon as sg,requireFastDeepEqual as sh,getAugmentedNamespace as si,requireParseSrcset as sj,requirePostcss as sk,requireIsPlainObject as sl,requireEscapeStringRegexp as sm,requireIsArguments as sn,require_arrayPush as so,require_baseGetTag as sp,requireIsObject as sq,requireKeys as sr,require_isIndex as ss,requireIsLength as st,requireIdentity as su,require_baseFor as sv,requireIsArrayLike as sw,require_baseUnary as sx,require_baseRest as sy,require_isIterateeCall as sz,timeLeft as t,__generator as t0,require$$0 as t1,requireObjectAssign as t2,ulid$1 as t3,AGENTS_VIEW as t4,CONTENTS_VIEW as t5,DATALAYER_VIEW as t6,JWT_DATALAYER_ISSUER as t7,JWT_REFRESH_TOKEN_COOKIE_NAME as t8,LIBRARY_VIEW as t9,katex$1 as tA,Lexical_prod as tB,LexicalUtils_prod as tC,NAVIGATION_VIEW_HOMES as ta,RESERVATION_WARNING_TIME_MS as tb,SESSION_COOKIES as tc,SESSION_LOCAL_STORAGE_KEYS as td,SESSION_OWNER_KEY as te,SETTINGS_VIEW as tf,TUTOR_VIEW as tg,claimSessionState as th,forgetSessionState as ti,getOtelConsumeUrl as tj,getStoredToken as tk,getStoredUser as tl,isRememberableRoute as tm,isShellNeutralRoute as tn,loadRefreshTokenFromCookie as to,navigationStore as tp,pageConfiguration as tq,profileStore as tr,registerSessionState as ts,storeToken as tt,storeUser as tu,useNavigationStore as tv,useProfile as tw,useProfileStore as tx,viewForRoute as ty,__spreadArray as tz,useNotebookStore$1 as u,vM as v,useSandboxService as w,useSignalValue$1 as x,datalayerCatalog as y,ChatBaseHeader as z};